From 856830edf4ad87fc76256f063c5b9b9c8028b118 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 01:53:01 +0000 Subject: [PATCH 01/11] =?UTF-8?q?feat(spec,console):=20ask=5Fai=20action?= =?UTF-8?q?=20type=20=E2=80=94=20focus=20the=20in-app=20assistant=20on=20a?= =?UTF-8?q?=20record?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ADR-0160 D7. The spec member and the console executor in one change: ActionType gains ask_ai (no target, refused at parse beside a target or ai.exposed: true); the runtime keeps it out of every headless door; the console executor pins the record through setChatFocus and opens the drawer, and the action is absent where the console has no assistant that honours a focus. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbZNHwt6dj15KeoAPMP --- .../src/action-ask-ai-headless.test.ts | 52 ++++++ packages/runtime/src/action-execution.ts | 13 ++ packages/spec/src/ui/action-ask-ai.test.ts | 120 +++++++++++++ .../spec/src/ui/action-row-update.test.ts | 8 +- .../ui/action-undoable-fulfillment.test.ts | 1 + packages/spec/src/ui/action.zod.ts | 67 ++++++- packages/spec/src/ui/inline-action.test.ts | 4 +- .../app-shell/src/console/ConsoleShell.tsx | 1 + .../__tests__/useAskAiHandler-37142.test.tsx | 91 ++++++++++ .../app-shell/src/hooks/surfaceAgent.ts | 10 ++ .../app-shell/src/hooks/useAiSurface.ts | 11 +- .../app-shell/src/hooks/useAskAiHandler.ts | 50 ++++++ .../src/hooks/useConsoleActionRuntime.tsx | 13 +- .../src/views/DeclaredActionsBar.tsx | 8 +- .../DeclaredActionsBar.askAi-37142.test.tsx | 110 ++++++++++++ .../src/renderers/action/action-bar.tsx | 9 +- .../src/renderers/basic/elements.tsx | 6 + .../src/renderers/complex/data-table.tsx | 14 +- .../src/renderers/layout/containers.tsx | 6 +- ui/packages/core/src/actions/ActionEngine.ts | 5 +- ui/packages/core/src/actions/ActionRunner.ts | 131 ++++++++++++++ .../ActionRunner.askAi-37142.test.ts | 168 ++++++++++++++++++ ui/packages/plugin-detail/src/RelatedList.tsx | 9 +- ui/packages/plugin-grid/src/ObjectGrid.tsx | 6 +- .../src/components/BulkActionBar.tsx | 7 +- .../src/components/RowActionMenu.tsx | 9 +- .../src/objectGridActionsColumn.tsx | 8 +- .../react/src/context/ActionContext.tsx | 73 +++++++- .../ActionProvider.askAi-37142.test.tsx | 96 ++++++++++ 29 files changed, 1065 insertions(+), 41 deletions(-) create mode 100644 packages/runtime/src/action-ask-ai-headless.test.ts create mode 100644 packages/spec/src/ui/action-ask-ai.test.ts create mode 100644 ui/packages/app-shell/src/hooks/__tests__/useAskAiHandler-37142.test.tsx create mode 100644 ui/packages/app-shell/src/hooks/useAskAiHandler.ts create mode 100644 ui/packages/app-shell/src/views/__tests__/DeclaredActionsBar.askAi-37142.test.tsx create mode 100644 ui/packages/core/src/actions/__tests__/ActionRunner.askAi-37142.test.ts create mode 100644 ui/packages/react/src/context/__tests__/ActionProvider.askAi-37142.test.tsx 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..3f77c3501a5 --- /dev/null +++ b/packages/runtime/src/action-ask-ai-headless.test.ts @@ -0,0 +1,52 @@ +// 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'; + +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 626bc59a191..9dab1c019a3 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/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/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/hooks/__tests__/useAskAiHandler-37142.test.tsx b/ui/packages/app-shell/src/hooks/__tests__/useAskAiHandler-37142.test.tsx new file mode 100644 index 00000000000..ce4b0184f02 --- /dev/null +++ b/ui/packages/app-shell/src/hooks/__tests__/useAskAiHandler-37142.test.tsx @@ -0,0 +1,91 @@ +// 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 pins the record + * through `setChatFocus` and opens the drawer; it sends nothing. + */ + +import { describe, it, expect, vi, beforeEach } 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: ReturnType } { + 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' }); + expect(control.open).toHaveBeenCalledTimes(1); + // On whatever the drawer shows: no target, no hand-off message. + expect(control.open).toHaveBeenCalledWith(); + expect(control.toggle).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/app-shell/src/hooks/surfaceAgent.ts b/ui/packages/app-shell/src/hooks/surfaceAgent.ts index f786b80c041..35a9791ae06 100644 --- a/ui/packages/app-shell/src/hooks/surfaceAgent.ts +++ b/ui/packages/app-shell/src/hooks/surfaceAgent.ts @@ -91,6 +91,16 @@ 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 agents.some((agent) => agent.capabilities?.focus === true); +} + /** * 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..4d3170879aa 100644 --- a/ui/packages/app-shell/src/hooks/useAiSurface.ts +++ b/ui/packages/app-shell/src/hooks/useAiSurface.ts @@ -42,7 +42,7 @@ import { useRef } from 'react'; import { useAgents } from '@object-ui/plugin-chatbot/core'; -import { catalogServesBuild } from './surfaceAgent.js'; +import { catalogServesBuild, catalogServesFocus } from './surfaceAgent.js'; /** * Resolve the AI service base URL, mirroring AiChatPage / the Home CTAs: @@ -69,6 +69,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 +98,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..704eeff9961 --- /dev/null +++ b/ui/packages/app-shell/src/hooks/useAskAiHandler.ts @@ -0,0 +1,50 @@ +// 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: it pins the record through the + * one setter (`setChatFocus`), then opens the drawer on whatever it shows. It + * sends no message and makes no server call. A drawer that is closed has no + * chat host yet; the setter holds the focus for the host that opening it + * mounts. + */ + +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 './useAiSurface.js'; +import { catalogServesFocus } 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 focusServed = catalogServesFocus(agents); + const open = dock?.open; + return useMemo( + () => + open && focusServed + ? (focus) => { + setChatFocus({ object: focus.object, id: focus.id }); + open(); + } + : undefined, + [open, focusServed], + ); +} 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/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/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, mayInvoke: ReturnType, + drawsAction: ReturnType, ): RowActionDef[] { return Array.isArray(schema.rowActionDefs) && schema.onRowActionDef - ? schema.rowActionDefs.filter((d) => mayInvoke(d.requiredPermissions) && !isActionSwitchedOff(d)) + ? schema.rowActionDefs.filter((d) => mayInvoke(d.requiredPermissions) && !isActionSwitchedOff(d) && drawsAction(d)) : []; } @@ -849,9 +850,11 @@ function useDataTableRowMenuPlan(schema: DataTableSchema, row: any): DataTableRo * to, so an unhandled `rowActionDefs` contributes no items (unchanged). */ const mayInvoke = useCapabilityGate(); + // [ADR-0160 D7] An `ask_ai` row action is absent without an in-app assistant. + const drawsAction = useDrawsAction(); const customActions = useMemo( - () => gatedDataTableRowActions(schema, mayInvoke), - [schema.rowActionDefs, schema.onRowActionDef, mayInvoke], + () => gatedDataTableRowActions(schema, mayInvoke, drawsAction), + [schema.rowActionDefs, schema.onRowActionDef, mayInvoke, drawsAction], ); return useMemo( () => @@ -2262,6 +2265,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // decision and the items it opens read one answer (see `rowContextMenuItems`). const rowMenuScope = usePredicateScope(); const rowMenuMayInvoke = useCapabilityGate(); + const rowMenuDrawsAction = useDrawsAction(); // Refs for column resizing const resizingColumn = useRef(null); @@ -4539,7 +4543,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { onRowDelete: schema.onRowDelete, editPredicates: schema.rowEditPredicates, deletePredicates: schema.rowDeletePredicates, - customActions: gatedDataTableRowActions(schema, rowMenuMayInvoke), + customActions: gatedDataTableRowActions(schema, rowMenuMayInvoke, rowMenuDrawsAction), row, scope: rowMenuScope, }); diff --git a/ui/packages/components/src/renderers/layout/containers.tsx b/ui/packages/components/src/renderers/layout/containers.tsx index ae7ddbb7d93..aba2fc8d140 100644 --- a/ui/packages/components/src/renderers/layout/containers.tsx +++ b/ui/packages/components/src/renderers/layout/containers.tsx @@ -24,7 +24,7 @@ import { ComponentRegistry, ExpressionEvaluator, declaredNameField, isElementDat import type { ComponentInput } from '@object-ui/core'; import { actionRendersAt, detectStatusField, arrangedHeaderActions, placedHeaderActions, resolveDeclaredActionIds } from '@object-ui/types'; import type { DeclaredActionsRefusal } from '@object-ui/types'; -import { useRecordContext, useAction, useCapabilityGate, usePredicateScope, usePageVariables, useInlineEdit, useActionTextLocalizer, useMetadataItem, reportUnresolvableVisibilityPredicate, resolveInlineAriaProps, buildNodeEvaluationScope } from '@object-ui/react'; +import { useRecordContext, useAction, useCapabilityGate, useDrawsAction, usePredicateScope, usePageVariables, useInlineEdit, useActionTextLocalizer, useMetadataItem, reportUnresolvableVisibilityPredicate, resolveInlineAriaProps, buildNodeEvaluationScope } from '@object-ui/react'; import { renderChildren, renderNodeSlot, cn } from '../../lib/utils'; import { LazyIcon } from '../../lib/lazy-icon'; import { RelatedCountStore, useRelatedCountVersion } from '../../hooks/related-count-store'; @@ -2121,6 +2121,9 @@ export const PageHeaderActions: React.FC = ({ const { execute } = useAction(); // [ADR-0066 D4 / framework#3923] Shared capability gate — see filterAction. const mayInvoke = useCapabilityGate(); + // [ADR-0160 D7] An `ask_ai` action is absent where the provider has no + // in-app assistant — see filterAction. + const drawsAction = useDrawsAction(); const isMobile = useIsMobile(); // The ONE resolver for a declared action's authored strings (objectui#4265). // This header used to localize `label` only — via `useObjectLabel().actionLabel` @@ -2420,6 +2423,7 @@ export const PageHeaderActions: React.FC = ({ // [objectstack#27504] Switched off for this installation (served // activation state): not offered, as the door would refuse it. if (isActionSwitchedOff(a)) return false; + if (!drawsAction(a)) return false; // Boolean / expression visibility — supports both `visible: false`, // `visible: 'record.status == "open"'` and the structured shape // `visible: { dialect: 'cel', source: '…' }` used by spec authors. diff --git a/ui/packages/core/src/actions/ActionEngine.ts b/ui/packages/core/src/actions/ActionEngine.ts index 8cfe504a220..890116cdf51 100644 --- a/ui/packages/core/src/actions/ActionEngine.ts +++ b/ui/packages/core/src/actions/ActionEngine.ts @@ -232,6 +232,9 @@ export class ActionEngine { // [objectstack#27504] An action this installation switched off is not // offered (the served activation state — see `utils/action-activation`). .filter(ra => !isActionSwitchedOff(ra.action)) + // [ADR-0160 D7] An `ask_ai` action is absent where the runner has no + // in-app assistant to hand its record to. + .filter(ra => this.runner.drawsAction(ra.action)) .filter(ra => { // [ADR-0066 D4] Capability gate (UI half — the server enforces the // source of truth). Hide an action whose `requiredPermissions` are not @@ -308,7 +311,7 @@ export class ActionEngine { /** Get actions that support bulk operations */ getBulkActions(): ActionDef[] { return Array.from(this.actions.values()) - .filter(ra => ra.bulkEnabled && !isActionSwitchedOff(ra.action)) + .filter(ra => ra.bulkEnabled && !isActionSwitchedOff(ra.action) && this.runner.drawsAction(ra.action)) .sort((a, b) => (a.priority ?? 100) - (b.priority ?? 100)) .map(ra => ra.action); } diff --git a/ui/packages/core/src/actions/ActionRunner.ts b/ui/packages/core/src/actions/ActionRunner.ts index 4fc5fe72a22..00a9461f4b1 100644 --- a/ui/packages/core/src/actions/ActionRunner.ts +++ b/ui/packages/core/src/actions/ActionRunner.ts @@ -695,6 +695,17 @@ const RUNNER_TEXT = { key: 'actions.undo', defaultValue: 'Undo', }, + // `ask_ai`'s two refusals reuse the record-id dance's locale keys + // (`serverActionHandler.ts` `RECORD_SELECTION_REFUSAL`): the same sentence + // for the same situation, already in every pack. + askAiNoRecord: { + key: 'actions.selectRowFirst', + defaultValue: 'This action runs on a single record — select a row first.', + }, + askAiSeveralRecords: { + key: 'actions.selectExactlyOneRow', + defaultValue: 'This action runs on a single record — select exactly one row.', + }, } as const; type RunnerText = { readonly key: string; readonly defaultValue: string }; @@ -853,6 +864,23 @@ export type ResultDialogHandler = ( action?: ActionDef, ) => Promise; +/** The record an `ask_ai` action hands the assistant: the object's machine name and the record id. */ +export interface AssistantFocus { + object: string; + id: string; +} + +/** + * ADR-0160 D7 — the host's in-app assistant, as the `ask_ai` executor reaches + * it. Called with the record the action runs on, it pins that record as the + * conversation's focus and expands the assistant. It sends no message and + * makes no server call. A host sets one only where it draws the assistant's + * pin control (the assistant surface on, and the AI service advertising that + * it honours a focus); with none set, an `ask_ai` action is absent from every + * surface that asks {@link ActionRunner.drawsAction}. + */ +export type AssistantFocusHandler = (focus: AssistantFocus) => void; + /** * One entry of a param's option list, as the RESOLVED param carries it. * @@ -1258,6 +1286,26 @@ function isUpdateOperationAction(action: ActionDef): boolean { return action.operation === 'update'; } +/** + * What a launch of an `ask_ai` action on a runner with no in-app assistant is + * told. Not a locale-pack text: such an action is not drawn + * ({@link ActionRunner.drawsAction}), so only a surface that skipped that + * question reaches it, and the sentence is for its developer. + */ +const ASK_AI_UNAVAILABLE = 'The in-app assistant is not available here, so `ask_ai` has nothing to open.'; + +/** + * Whether `action` is an `ask_ai` action (ADR-0160 D7), read on the declared + * type the way {@link resolveDispatchType} reads it (`type`, then the legacy + * `actionType`). A typeless action is never one: the type has no default + * spelling and no handler-name dispatch. + */ +export function isAskAiAction(action: unknown): boolean { + if (!action || typeof action !== 'object') return false; + const { type, actionType } = action as { type?: unknown; actionType?: unknown }; + return (type || actionType) === 'ask_ai'; +} + /** * The row a dispatch carries — the clicked row a row surface stashes under * `params._rowRecord` — or `undefined` when it carries none. The record its @@ -1442,6 +1490,7 @@ export class ActionRunner { private navigationHandler: NavigationHandler | null; private paramCollectionHandler: ParamCollectionHandler | null; private resultDialogHandler: ResultDialogHandler | null; + private assistantFocusHandler: AssistantFocusHandler | null; private translate: RunnerTranslate | null; private displayLocale: (() => string | undefined) | null; private tenantCurrency: (() => string | undefined) | null; @@ -1472,6 +1521,7 @@ export class ActionRunner { flow: (action) => this.executeFlow(action), api: (action) => this.executeAPI(action), form: (action) => this.executeForm(action), + ask_ai: (action) => this.executeAskAi(action), navigation: (action) => this.executeNavigation(action), }; @@ -1485,6 +1535,7 @@ export class ActionRunner { this.navigationHandler = null; this.paramCollectionHandler = null; this.resultDialogHandler = null; + this.assistantFocusHandler = null; this.translate = null; this.displayLocale = null; this.tenantCurrency = null; @@ -1579,6 +1630,27 @@ export class ActionRunner { this.resultDialogHandler = handler; } + /** + * Set (or, with `null`, clear) the in-app assistant the `ask_ai` executor + * hands its record to — see {@link AssistantFocusHandler}. Whether one is + * set is also what {@link ActionRunner.drawsAction} answers for an `ask_ai` + * action, so the action is drawn exactly where a click can be served. + */ + setAssistantFocusHandler(handler: AssistantFocusHandler | null): void { + this.assistantFocusHandler = handler; + } + + /** + * Whether a surface draws `action` at all on this runner — `false` only for + * an `ask_ai` action on a runner with no in-app assistant (ADR-0160 D7: it + * is then absent, not disabled). Every other action is drawn or hidden by + * its own gates (`visible`, `requiredPermissions`, the served activation + * state), which this does not answer. + */ + drawsAction(action: unknown): boolean { + return !isAskAiAction(action) || this.assistantFocusHandler !== null; + } + registerHandler(actionName: string, handler: ActionRunnerHandler): void { this.handlers.set(actionName, handler); } @@ -1969,6 +2041,14 @@ export class ActionRunner { */ private refusalBeforeInput(action: ActionDef, actionType: string): string | undefined { if (isUpdateOperationAction(action)) return undefined; + // `ask_ai` runs on exactly one record: a launch that names none (a list + // header with no row selected) or several is refused before its + // `confirmText` asks anything, and a list header greys it out the same way. + if (actionType === 'ask_ai' && !this.handlers.has('ask_ai')) { + if (!this.assistantFocusHandler) return ASK_AI_UNAVAILABLE; + const focus = this.askAiFocus(action); + return 'refusal' in focus ? this.runnerText(focus.refusal) : undefined; + } const handler = actionType ? this.handlers.get(actionType) : undefined; const refusal = handler?.refuseBeforeInput?.(action, this.context); if (!refusal?.error) return undefined; @@ -2959,6 +3039,56 @@ export class ActionRunner { return this.announceNavigation(action, { success: true, redirect: to }); } + /** + * The record an `ask_ai` dispatch runs on, or the refusal naming why there + * is not exactly one. The object is the one the runner's context names (a + * related-list row's dispatch names the child object, objectui#13063); the + * record is, in order, the row a row surface stashed (`params._rowRecord`, + * read by `recordIdField` like the record-id dance), the record the context + * names (a record page, a related-list row), or the one row selected in a + * list header. Several selected rows are refused, not guessed between. + */ + private askAiFocus(action: ActionDef): AssistantFocus | { refusal: RunnerText } { + const object = readContextObjectName(this.context); + const idField = typeof action.recordIdField === 'string' && action.recordIdField ? action.recordIdField : 'id'; + const asId = (value: unknown): string | undefined => + (typeof value === 'string' && value !== '') || typeof value === 'number' ? String(value) : undefined; + const row = dispatchRow(action); + let id = asId(row?.[idField]); + if (id === undefined && !row) { + const record = this.context.record as Record | undefined; + id = asId(record?.id) ?? asId(this.context.recordId); + } + if (id === undefined && !row) { + const selected = Array.isArray(this.context.selectedRecords) ? this.context.selectedRecords : []; + if (selected.length > 1) return { refusal: RUNNER_TEXT.askAiSeveralRecords }; + if (selected.length === 1) id = asId((selected[0] as Record | undefined)?.[idField]); + } + if (!object || id === undefined) return { refusal: RUNNER_TEXT.askAiNoRecord }; + return { object, id }; + } + + /** + * `ask_ai` (ADR-0160 D7) — focus the in-app assistant on the record the + * action runs on and expand it, through the host's + * {@link AssistantFocusHandler}: the same setter the assistant's own pin + * control calls. It sends no message and makes no server call. A success is + * silent unless the action declares its own `successMessage` (the + * navigation rule, `announceNavigation`): opening a panel is not an outcome + * to announce. + * + * With no handler set the action is not drawn ({@link ActionRunner.drawsAction}); + * a launch that reaches here anyway — a stale surface, a host that never + * asked — is refused rather than reported done. + */ + private async executeAskAi(action: ActionDef): Promise { + if (!this.assistantFocusHandler) return { success: false, error: ASK_AI_UNAVAILABLE }; + const focus = this.askAiFocus(action); + if ('refusal' in focus) return { success: false, error: this.runnerText(focus.refusal) }; + this.assistantFocusHandler(focus); + return this.announceNavigation(action, { success: true }); + } + /** * `navigation` — objectui's alias of the spec's `url` (`ObjectUiLocalActionType`). * @@ -3356,6 +3486,7 @@ export class ActionRunner { scoped.navigationHandler = this.navigationHandler; scoped.paramCollectionHandler = this.paramCollectionHandler; scoped.resultDialogHandler = this.resultDialogHandler; + scoped.assistantFocusHandler = this.assistantFocusHandler; scoped.translate = this.translate; scoped.displayLocale = this.displayLocale; scoped.tenantCurrency = this.tenantCurrency; diff --git a/ui/packages/core/src/actions/__tests__/ActionRunner.askAi-37142.test.ts b/ui/packages/core/src/actions/__tests__/ActionRunner.askAi-37142.test.ts new file mode 100644 index 00000000000..0ff03025bf9 --- /dev/null +++ b/ui/packages/core/src/actions/__tests__/ActionRunner.askAi-37142.test.ts @@ -0,0 +1,168 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * `type: 'ask_ai'` — the console executor (objectstack#37142, ADR-0160 D7). + * + * The action focuses the host's in-app assistant on the record it runs on and + * expands it, through the handler the host installs + * (`setAssistantFocusHandler`). Pinned here: + * 1. A click hands the record — the page record, a row a row surface stashed, + * the one selected row — to the handler, once, and nothing else runs: no + * server dispatch, no registered handler, no fetch, no success toast. + * 2. With no record, or several selected, the launch is refused before the + * `confirmText` asks anything, and the handler is not called. + * 3. With no handler installed the action is not drawn (`drawsAction`, + * `ActionEngine.getActionsForLocation`) and a launch that reaches the + * runner anyway is refused, not reported done. + * 4. Other actions are drawn whatever the assistant answer is. + */ + +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { ActionSchema } from '@objectstack/spec/ui'; +import { ActionRunner, isAskAiAction, type ActionDef } from '../ActionRunner'; +import { ActionEngine } from '../ActionEngine'; + +const ASK: ActionDef = { name: 'ask_about_account', label: 'Ask AI', type: 'ask_ai', locations: ['record_header'] }; + +function hostRunner(context: Record = {}) { + const runner = new ActionRunner({ objectName: 'account', ...context }); + const focus = vi.fn(); + const toast = vi.fn(); + const confirm = vi.fn(async () => true); + const script = vi.fn(async () => ({ success: true })); + runner.setAssistantFocusHandler(focus); + runner.setToastHandler(toast); + runner.setConfirmHandler(confirm); + // A console host registers its server dispatch; `ask_ai` must never reach it. + runner.registerHandler('script', script); + return { runner, focus, toast, confirm, script }; +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('ask_ai — the executor (ADR-0160 D7)', () => { + it('is the type the spec parses, with no target', () => { + const parsed = ActionSchema.parse({ ...ASK }); + expect(parsed.type).toBe('ask_ai'); + expect(isAskAiAction(parsed)).toBe(true); + }); + + it('hands the page record to the assistant, once, and sends nothing', async () => { + const fetchSpy = vi.fn(); + vi.stubGlobal('fetch', fetchSpy); + const { runner, focus, toast, script } = hostRunner({ record: { id: 'acc_1', name: 'Acme' } }); + + const result = await runner.execute({ ...ASK }); + + expect(result.success).toBe(true); + expect(focus).toHaveBeenCalledTimes(1); + expect(focus).toHaveBeenCalledWith({ object: 'account', id: 'acc_1' }); + expect(script).not.toHaveBeenCalled(); + expect(fetchSpy).not.toHaveBeenCalled(); + // Opening the assistant is not an outcome to announce. + expect(toast).not.toHaveBeenCalled(); + }); + + it('reads the row a row surface stashed, by `recordIdField`', async () => { + const { runner, focus } = hostRunner({ record: { id: 'page_record' } }); + await runner.execute({ ...ASK, recordIdField: 'uid', params: { _rowRecord: { id: 'x', uid: 'row_7' } } }); + expect(focus).toHaveBeenCalledWith({ object: 'account', id: 'row_7' }); + }); + + it('reads the record of a dispatch scoped to another object (a related-list row)', async () => { + const { runner, focus } = hostRunner({ record: { id: 'acc_1' } }); + await runner.execute({ ...ASK }, { objectName: 'contact', record: { id: 'con_3' } }); + expect(focus).toHaveBeenCalledWith({ object: 'contact', id: 'con_3' }); + }); + + it('reads the one selected row in a list header', async () => { + const { runner, focus } = hostRunner({ selectedRecords: [{ id: 'acc_9' }] }); + await runner.execute({ ...ASK }); + expect(focus).toHaveBeenCalledWith({ object: 'account', id: 'acc_9' }); + }); + + it('shows a declared successMessage, as a navigation does', async () => { + const { runner, toast } = hostRunner({ record: { id: 'acc_1' } }); + await runner.execute({ ...ASK, successMessage: 'Assistant opened' }); + expect(toast).toHaveBeenCalledWith('Assistant opened', expect.objectContaining({ type: 'success' })); + }); +}); + +describe('ask_ai — refused before anything is asked', () => { + it('refuses with no record, before the confirmText', async () => { + const { runner, focus, confirm } = hostRunner(); + const result = await runner.execute({ ...ASK, confirmText: 'Open the assistant?' }); + expect(result.success).toBe(false); + expect(result.error).toBe('This action runs on a single record — select a row first.'); + expect(confirm).not.toHaveBeenCalled(); + expect(focus).not.toHaveBeenCalled(); + expect(runner.launchRefusal({ ...ASK })).toBe('This action runs on a single record — select a row first.'); + }); + + it('refuses several selected rows rather than guessing between them', async () => { + const { runner, focus } = hostRunner({ selectedRecords: [{ id: 'a' }, { id: 'b' }] }); + const result = await runner.execute({ ...ASK }); + expect(result.success).toBe(false); + expect(result.error).toBe('This action runs on a single record — select exactly one row.'); + expect(focus).not.toHaveBeenCalled(); + }); + + it('refuses with no object named', async () => { + const runner = new ActionRunner({ record: { id: 'acc_1' } }); + const focus = vi.fn(); + runner.setAssistantFocusHandler(focus); + const result = await runner.execute({ ...ASK }); + expect(result.success).toBe(false); + expect(focus).not.toHaveBeenCalled(); + }); +}); + +describe('ask_ai — absent without an in-app assistant', () => { + it('is not drawn on a runner with no handler, and drawn once one is set', () => { + const runner = new ActionRunner({ objectName: 'account' }); + expect(runner.drawsAction(ASK)).toBe(false); + runner.setAssistantFocusHandler(() => {}); + expect(runner.drawsAction(ASK)).toBe(true); + runner.setAssistantFocusHandler(null); + expect(runner.drawsAction(ASK)).toBe(false); + }); + + it('draws every other action whatever the assistant answer is', () => { + const runner = new ActionRunner(); + for (const action of [{ type: 'script', target: 'x' }, { type: 'url', target: '/x' }, { name: 'typeless' }, null]) { + expect(runner.drawsAction(action)).toBe(true); + } + }); + + it('reads the legacy `actionType` spelling as the resolver does', () => { + const runner = new ActionRunner(); + expect(runner.drawsAction({ actionType: 'ask_ai' })).toBe(false); + }); + + it('refuses a launch that reaches the runner anyway, before the confirmText', async () => { + const runner = new ActionRunner({ objectName: 'account', record: { id: 'acc_1' } }); + const confirm = vi.fn(async () => true); + runner.setConfirmHandler(confirm); + const result = await runner.execute({ ...ASK, confirmText: 'Open?' }); + expect(result.success).toBe(false); + expect(result.error).toContain('in-app assistant is not available'); + expect(confirm).not.toHaveBeenCalled(); + }); + + it('is left out of ActionEngine.getActionsForLocation until the runner has an assistant', () => { + const engine = new ActionEngine({ objectName: 'account' }); + engine.registerActions([{ ...ASK }, { name: 'edit', type: 'script', target: 'edit', locations: ['record_header'] }]); + expect(engine.getActionsForLocation('record_header').map((a) => a.name)).toEqual(['edit']); + engine.getRunner().setAssistantFocusHandler(() => {}); + expect(engine.getActionsForLocation('record_header').map((a) => a.name)).toEqual(['ask_about_account', 'edit']); + }); + + it('a scoped dispatch keeps the host assistant', async () => { + const { runner, focus } = hostRunner(); + await runner.execute({ ...ASK }, { record: { id: 'acc_2' } }); + expect(focus).toHaveBeenCalledWith({ object: 'account', id: 'acc_2' }); + }); +}); diff --git a/ui/packages/plugin-detail/src/RelatedList.tsx b/ui/packages/plugin-detail/src/RelatedList.tsx index b4c79e4a546..2ebef38750d 100644 --- a/ui/packages/plugin-detail/src/RelatedList.tsx +++ b/ui/packages/plugin-detail/src/RelatedList.tsx @@ -34,7 +34,7 @@ import { RecordHeaderBarContext, toast, } from '@object-ui/components'; -import { SchemaRenderer, ActionCtxReact, useCapabilityGate, useCondition, toPredicateInput, useSettledSchema, useFilterScope, useResolvedFilter, usePredicateScope, classifyLoadError, answeredLoadFailure, declaredUserMessage, extractWriteErrorMessage, isExternalWriteRefusal, type LoadErrorKind, type RelatedRowActionDef } from '@object-ui/react'; +import { SchemaRenderer, ActionCtxReact, useCapabilityGate, useDrawsAction, useCondition, toPredicateInput, useSettledSchema, useFilterScope, useResolvedFilter, usePredicateScope, classifyLoadError, answeredLoadFailure, declaredUserMessage, extractWriteErrorMessage, isExternalWriteRefusal, type LoadErrorKind, type RelatedRowActionDef } from '@object-ui/react'; import { Plus, ExternalLink, @@ -1577,9 +1577,12 @@ export const RelatedList: React.FC = ({ * and can only ever hide more than before. */ const mayInvoke = useCapabilityGate(); + // [ADR-0160 D7] An `ask_ai` action is absent where the provider has no + // in-app assistant. + const drawsAction = useDrawsAction(); const permittedToolbarActions = React.useMemo( - () => (toolbarActions ?? []).filter((a) => mayInvoke(a?.requiredPermissions) && !isActionSwitchedOff(a)), - [toolbarActions, mayInvoke], + () => (toolbarActions ?? []).filter((a) => mayInvoke(a?.requiredPermissions) && !isActionSwitchedOff(a) && drawsAction(a)), + [toolbarActions, mayInvoke, drawsAction], ); // In the record page's related column (objectstack#26678) the list is a diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 149687ef191..73bdd549d5b 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -24,7 +24,7 @@ import React, { useEffect, useState, useCallback, useMemo } from 'react'; import type { ObjectGridSchema, DataSource, ViewData, TableSortItem, DataTableSchema, ListViewExportFormat, RecordNavigateAction } from '@object-ui/types'; import { isSystemManagedField, detectStatusField } from '@object-ui/types'; -import { SchemaRenderer, isPermissionError, useDataScope, useNavigationOverlay, useAction, useSafeFieldLabel, usePredicateScope, useCapabilityGate, useRelatedRecordActions, notifyDataChanged, useMetadata, claimAnswerWarnings, toastRecordSave, useOwnWrites, createOwnWrites, type AnswerWarningClaim, type RecordSaveFeedback } from '@object-ui/react'; +import { SchemaRenderer, isPermissionError, useDataScope, useNavigationOverlay, useAction, useSafeFieldLabel, usePredicateScope, useCapabilityGate, useDrawsAction, useRelatedRecordActions, notifyDataChanged, useMetadata, claimAnswerWarnings, toastRecordSave, useOwnWrites, createOwnWrites, type AnswerWarningClaim, type RecordSaveFeedback } from '@object-ui/react'; // objectui#8920 — the grid reaches a cell renderer through THIS module and // nowhere else. `getCellRenderer` / `resolveCellRendererType` are deliberately // NOT imported here: six sites spelling the resolve three different ways is @@ -2007,6 +2007,8 @@ export const ObjectGrid: React.FC = ({ // applies per row, read here too so the Actions column's verdict (below the // early returns, where no hook may sit) sees the same declared set. const mayInvokeRowAction = useCapabilityGate(); + // [ADR-0160 D7] …and the provider's answer for an `ask_ai` row action. + const drawsRowAction = useDrawsAction(); const getRowStyle = useCallback((row: Record): React.CSSProperties | undefined => { const rules = schema.conditionalFormatting; if (!rules || rules.length === 0) return undefined; @@ -2439,7 +2441,7 @@ export const ObjectGrid: React.FC = ({ pinnedRightCols, unpinnedCols, rightPinnedClasses, rightPinnedCellClasses, userLeftPinnedCount, } = resolveObjectGridActionsColumn({ schema, data, objectSchema, persistedColumns, operations, resolvedRowActionDefs, - wantEditAction, wantDeleteAction, mayInvokeRowAction, rowOperations, canEdit, canDelete, + wantEditAction, wantDeleteAction, mayInvokeRowAction, drawsRowAction, rowOperations, canEdit, canDelete, recordVerdict, approvalLocks, demandRowActions, predicateScope, onEdit, onDelete, editPredicates, deletePredicates, executeAction, setRefreshKey, t, foldInlineRowActions: inlineActionFold.folded, drawRowControls: !listPageGrid, diff --git a/ui/packages/plugin-grid/src/components/BulkActionBar.tsx b/ui/packages/plugin-grid/src/components/BulkActionBar.tsx index 71fca331237..20e58901b35 100644 --- a/ui/packages/plugin-grid/src/components/BulkActionBar.tsx +++ b/ui/packages/plugin-grid/src/components/BulkActionBar.tsx @@ -10,7 +10,7 @@ import React from 'react'; import { Button } from '@object-ui/components'; import { Trash2 } from 'lucide-react'; import { LazyIcon, toKebabIconName } from '@object-ui/components'; -import { useObjectTranslation, usePredicateScope, useCapabilityGate } from '@object-ui/react'; +import { useObjectTranslation, usePredicateScope, useCapabilityGate, useDrawsAction } from '@object-ui/react'; import { isActionSwitchedOff } from '@object-ui/core'; import type { BulkActionDef } from '@object-ui/types'; import { partitionBulkRows, hasVisibilityGate } from '../bulkEligibility'; @@ -100,6 +100,8 @@ export function useBulkActionItems(input: { }): BulkActionItems { const { selectedRows, actions, actionDefs, objectFields } = input; const mayInvoke = useCapabilityGate(); + // [ADR-0160 D7] An `ask_ai` def is absent without an in-app assistant. + const drawsAction = useDrawsAction(); const scope = usePredicateScope(); // `language` keys the memo on the active language itself, so the label // follows a switch whatever identity `t` keeps across it. @@ -109,6 +111,7 @@ export function useBulkActionItems(input: { (d) => mayInvoke(d?.requiredPermissions) && !isActionSwitchedOff(d) + && drawsAction(d) && isBulkDefOffered(d, selectedRows, scope, objectFields), ); const legacy = (Array.isArray(actions) ? actions : []).map((action) => { @@ -124,7 +127,7 @@ export function useBulkActionItems(input: { }; }); return { defs, legacy }; - }, [actionDefs, actions, selectedRows, scope, objectFields, mayInvoke, t, language]); + }, [actionDefs, actions, selectedRows, scope, objectFields, mayInvoke, drawsAction, t, language]); } /** A rich def reads as destructive by its variant or by the delete operation it runs. */ diff --git a/ui/packages/plugin-grid/src/components/RowActionMenu.tsx b/ui/packages/plugin-grid/src/components/RowActionMenu.tsx index 8d67804e900..90666acf45f 100644 --- a/ui/packages/plugin-grid/src/components/RowActionMenu.tsx +++ b/ui/packages/plugin-grid/src/components/RowActionMenu.tsx @@ -37,7 +37,7 @@ import { } from '@object-ui/components'; import { Edit, Trash2, MoreVertical } from 'lucide-react'; import { evalRowPredicate, hasDeclaredPredicate, isActionSwitchedOff, type CrudAffordances } from '@object-ui/core'; -import { useObjectTranslation, useRowPredicate, useCapabilityGate, usePredicateScope } from '@object-ui/react'; +import { useObjectTranslation, useRowPredicate, useCapabilityGate, useDrawsAction, usePredicateScope } from '@object-ui/react'; import { orderRowMenuActions } from '../rowActionArrangement'; const ROW_ACTION_FALLBACKS: Record = { @@ -638,9 +638,12 @@ export function useRowActionPlan( // rendered. Unknown capabilities fail OPEN (see `useCapabilityGate`); the // server remains the authority. const mayInvoke = useCapabilityGate(); + // [ADR-0160 D7] …and an `ask_ai` row action is absent where the provider has + // no in-app assistant. + const drawsAction = useDrawsAction(); const gatedActionDefs = React.useMemo( - () => (rowActionDefs ?? []).filter(d => mayInvoke((d as any)?.requiredPermissions) && !isActionSwitchedOff(d)), - [rowActionDefs, mayInvoke], + () => (rowActionDefs ?? []).filter(d => mayInvoke((d as any)?.requiredPermissions) && !isActionSwitchedOff(d) && drawsAction(d)), + [rowActionDefs, mayInvoke, drawsAction], ); // What this row will ACTUALLY render, per-record predicates applied — the // guard and the items read one visibility source, so they cannot disagree. diff --git a/ui/packages/plugin-grid/src/objectGridActionsColumn.tsx b/ui/packages/plugin-grid/src/objectGridActionsColumn.tsx index c420482ddd3..383ae543746 100644 --- a/ui/packages/plugin-grid/src/objectGridActionsColumn.tsx +++ b/ui/packages/plugin-grid/src/objectGridActionsColumn.tsx @@ -6,7 +6,7 @@ import React from 'react'; import type { ObjectGridSchema } from '@object-ui/types'; -import { useAction, usePredicateScope, useCapabilityGate } from '@object-ui/react'; +import { useAction, usePredicateScope, useCapabilityGate, type useDrawsAction } from '@object-ui/react'; import { isActionSwitchedOff } from '@object-ui/core'; import { PINNED_RIGHT_SEAM_SHADOW_CLASSES } from '@object-ui/components'; import { resolveRowRecordCrudAffordance } from './rowCrudAffordances'; @@ -29,7 +29,7 @@ type RowCrudAffordances = ReturnType; */ export function resolveObjectGridActionsColumn({ schema, data, objectSchema, persistedColumns, operations, resolvedRowActionDefs, - wantEditAction, wantDeleteAction, mayInvokeRowAction, rowOperations, canEdit, canDelete, + wantEditAction, wantDeleteAction, mayInvokeRowAction, drawsRowAction, rowOperations, canEdit, canDelete, recordVerdict, approvalLocks, demandRowActions, predicateScope, onEdit, onDelete, editPredicates, deletePredicates, executeAction, setRefreshKey, t, foldInlineRowActions = false, drawRowControls = true, }: { @@ -42,6 +42,8 @@ export function resolveObjectGridActionsColumn({ wantEditAction: boolean; wantDeleteAction: boolean; mayInvokeRowAction: ReturnType; + /** [ADR-0160 D7] `useDrawsAction`'s answer: an `ask_ai` row action is absent without an in-app assistant. */ + drawsRowAction: ReturnType; rowOperations: ObjectGridComponentProps['rowOperations']; canEdit: RowCrudAffordances['canEdit']; canDelete: RowCrudAffordances['canDelete']; @@ -99,7 +101,7 @@ export function resolveObjectGridActionsColumn({ // per-record predicates and the record-level verdicts are applied. Wiring // alone (`operations`, a declared list) used to draw an empty column over // rows that offer nothing. One row is enough, so the read stops at the first. - const rowActionDefsGated = (resolvedRowActionDefs as any[]).filter((d) => mayInvokeRowAction(d?.requiredPermissions) && !isActionSwitchedOff(d)); + const rowActionDefsGated = (resolvedRowActionDefs as any[]).filter((d) => mayInvokeRowAction(d?.requiredPermissions) && !isActionSwitchedOff(d) && drawsRowAction(d)); // NON-AUTHOR SURFACE — see the `maxInlineActions` prop below. const maxInlineRowActions: number = foldInlineRowActions ? 0 : ((schema as any).maxInlineRowActions ?? 1); /** diff --git a/ui/packages/react/src/context/ActionContext.tsx b/ui/packages/react/src/context/ActionContext.tsx index dad41d73895..c1eab23619a 100644 --- a/ui/packages/react/src/context/ActionContext.tsx +++ b/ui/packages/react/src/context/ActionContext.tsx @@ -13,10 +13,13 @@ * Components can consume actions without creating their own runner instances. */ -import React, { createContext, useCallback, useContext, useMemo, useState } from 'react'; +import React, { createContext, useCallback, useContext, useMemo, useRef, useState } from 'react'; import { ActionRunner, + isAskAiAction, subjectPermissionsOf, + type AssistantFocus, + type AssistantFocusHandler, type ActionContext as ActionCtx, type ActionDef, type ActionResult, @@ -46,6 +49,16 @@ export interface ActionProviderProps { onParamCollection?: ParamCollectionHandler; /** Custom result-dialog handler — show one-shot reveal of API response after success */ onResultDialog?: ResultDialogHandler; + /** + * The host's in-app assistant, for `type: 'ask_ai'` actions (ADR-0160 D7): + * pin the record as the conversation's focus and expand the assistant. Pass + * it only where the assistant's pin control is drawn (the assistant surface + * on, and the AI service advertising that it honours a focus). Without it an + * `ask_ai` action is absent from every surface under this provider that + * asks {@link useDrawsAction}. It may come and go between renders: the + * catalog that decides it loads after the first one. + */ + onAskAi?: AssistantFocusHandler; /** Pre-registered custom action handlers */ handlers?: Record Promise>; } @@ -65,6 +78,15 @@ interface ActionContextValue { runner: ActionRunner; /** Update context data */ updateContext: (ctx: Partial) => void; + /** + * Whether a surface draws `action` at all under this provider — `false` only + * for an `ask_ai` action where the host gave no in-app assistant + * (ADR-0160 D7). Changes identity when that answer can change, so a surface + * that memoises its filtered list on it re-filters. Optional so a + * hand-built context value (a test, a routed wrapper) need not carry it: + * {@link useDrawsAction} falls back to the runner's own answer. + */ + drawsAction?: (action: unknown) => boolean; } export const ActionCtxReact = createContext(null); @@ -93,6 +115,7 @@ export const ActionProvider: React.FC = ({ onNavigate, onParamCollection, onResultDialog, + onAskAi, handlers, }) => { const [loading, setLoading] = useState(false); @@ -138,6 +161,28 @@ export const ActionProvider: React.FC = ({ // eslint-disable-next-line react-hooks/exhaustive-deps }, [JSON.stringify(context)]); + // ADR-0160 D7 — the in-app assistant `ask_ai` hands its record to. Unlike the + // handlers above it is (re)installed on every change, not only when the + // runner is built: whether the host has an assistant is decided by a catalog + // that resolves after the first render, and the answer is what draws or + // hides every `ask_ai` action under this provider. Bound during render, so + // no child renders against the previous answer; the runner calls the latest + // `onAskAi` through a ref, so a new function identity alone changes nothing. + const askAiRef = useRef(onAskAi); + askAiRef.current = onAskAi; + const hasAskAi = onAskAi !== undefined; + useMemo(() => { + runner.setAssistantFocusHandler( + hasAskAi ? (focus: AssistantFocus) => { askAiRef.current?.(focus); } : null, + ); + }, [runner, hasAskAi]); + const drawsAction = useCallback( + (action: unknown) => runner.drawsAction(action), + // `hasAskAi` is the answer's input the runner does not change identity on. + // eslint-disable-next-line react-hooks/exhaustive-deps + [runner, hasAskAi], + ); + // The acting subject the surrounding predicate scope binds as `current_user` // (objectui#11242): the ONE object `ExpressionProvider` publishes under // `current_user` / `user` / `ctx.user` / `os.user`, carrying the caller's @@ -232,8 +277,8 @@ export const ActionProvider: React.FC = ({ ); const value = useMemo( - () => ({ execute, executeChain, loading, error, result, runner, updateContext }), - [execute, executeChain, loading, error, result, runner, updateContext], + () => ({ execute, executeChain, loading, error, result, runner, updateContext, drawsAction }), + [execute, executeChain, loading, error, result, runner, updateContext, drawsAction], ); return ( @@ -269,6 +314,28 @@ export function useAction(): ActionContextValue { return ctx; } +/** No provider: no host assistant, so only `ask_ai` is not drawn. */ +const drawsWithoutProvider = (action: unknown): boolean => !isAskAiAction(action); + +/** + * `(action) => boolean`: whether a surface draws `action` at all under the + * nearest `ActionProvider` — `false` only for a `type: 'ask_ai'` action where + * that provider has no in-app assistant (ADR-0160 D7: absent, not disabled). + * A surface asks it beside `isActionSwitchedOff` and the capability gate, on + * the same list. The answer reads the provider whose runner would execute the + * action, so a drawn `ask_ai` button is one a click can serve. + */ +export function useDrawsAction(): (action: unknown) => boolean { + const ctx = useContext(ActionCtxReact); + const runner = ctx?.runner; + const own = ctx?.drawsAction; + const fromRunner = useCallback( + (action: unknown) => (runner ? runner.drawsAction(action) : drawsWithoutProvider(action)), + [runner], + ); + return own ?? fromRunner; +} + /** * Hook to check if an ActionProvider is available. */ diff --git a/ui/packages/react/src/context/__tests__/ActionProvider.askAi-37142.test.tsx b/ui/packages/react/src/context/__tests__/ActionProvider.askAi-37142.test.tsx new file mode 100644 index 00000000000..ad125ed48a7 --- /dev/null +++ b/ui/packages/react/src/context/__tests__/ActionProvider.askAi-37142.test.tsx @@ -0,0 +1,96 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#37142 (ADR-0160 D7) — `` and + * `useDrawsAction`. + * + * The provider installs the host's in-app assistant on its runner, and the + * hook answers, for every surface under it, whether an `ask_ai` action is + * drawn at all. Pinned: + * 1. No `onAskAi` → `ask_ai` is not drawn; every other action is. + * 2. `onAskAi` arriving on a LATER render (the agent catalog resolves after + * the first) draws it, and the hook's identity changes so a memoised + * filter re-runs; `onAskAi` leaving hides it again. + * 3. A click runs the LATEST `onAskAi` with the record, and nothing else. + * 4. No provider at all → `ask_ai` is not drawn. + */ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { act, cleanup, renderHook } from '@testing-library/react'; +import React from 'react'; +import type { AssistantFocusHandler } from '@object-ui/core'; +import { ActionProvider, useAction, useDrawsAction } from '../ActionContext'; + +afterEach(() => cleanup()); + +const ASK = { name: 'ask_about_account', type: 'ask_ai' }; +const SCRIPT = { name: 'close', type: 'script', target: 'close' }; + +function harness(initial: AssistantFocusHandler | undefined) { + let onAskAi = initial; + const wrapper = ({ children }: { children: React.ReactNode }) => ( + + {children} + + ); + const view = renderHook(() => ({ draws: useDrawsAction(), action: useAction() }), { wrapper }); + return { + ...view, + setOnAskAi(next: AssistantFocusHandler | undefined) { + onAskAi = next; + view.rerender(); + }, + }; +} + +describe(' — whether ask_ai is drawn', () => { + it('does not draw ask_ai without an assistant, and draws everything else', () => { + const { result } = harness(undefined); + expect(result.current.draws(ASK)).toBe(false); + expect(result.current.draws(SCRIPT)).toBe(true); + }); + + it('draws ask_ai once the assistant arrives on a later render, with a new gate identity', () => { + const view = harness(undefined); + const before = view.result.current.draws; + view.setOnAskAi(vi.fn()); + expect(view.result.current.draws(ASK)).toBe(true); + expect(view.result.current.draws).not.toBe(before); + view.setOnAskAi(undefined); + expect(view.result.current.draws(ASK)).toBe(false); + }); + + it('keeps the gate identity when only the handler function changes', () => { + const view = harness(vi.fn()); + const before = view.result.current.draws; + view.setOnAskAi(vi.fn()); + expect(view.result.current.draws).toBe(before); + }); + + it('runs the latest onAskAi with the record on a click', async () => { + const first = vi.fn(); + const latest = vi.fn(); + const view = harness(first); + view.setOnAskAi(latest); + let outcome: { success: boolean } | undefined; + await act(async () => { + outcome = await view.result.current.action.execute({ ...ASK }); + }); + expect(outcome?.success).toBe(true); + expect(first).not.toHaveBeenCalled(); + expect(latest).toHaveBeenCalledWith({ object: 'account', id: 'acc_1' }); + }); +}); + +describe('useDrawsAction — no provider', () => { + it('does not draw ask_ai, and draws everything else', () => { + const { result } = renderHook(() => useDrawsAction()); + expect(result.current(ASK)).toBe(false); + expect(result.current(SCRIPT)).toBe(true); + }); +}); From d1f71bdda53d7862bd858f198ee7dea394c943aa Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 03:18:24 +0000 Subject: [PATCH 02/11] feat(spec,console): ask_ai absent on page action renderers and dashboard headers Gate action:button, action:icon, action:group and action:menu members with useDrawsAction, refuse `actionType: 'ask_ai'` on a dashboard header (it runs on no record), carry `focusServed` in the AI surface fixtures, and teach the two Studio pin tests that `ask_ai` takes no target. Changeset for #37142. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbZNHwt6dj15KeoAPMP --- .changeset/37142-ask-ai-action-type.md | 27 +++++++++++++++++ content/docs/references/data/object.mdx | 2 +- .../references/kernel/metadata-plugin.mdx | 2 +- content/docs/references/ui/action.mdx | 5 ++-- content/docs/references/ui/component.mdx | 4 +-- content/docs/references/ui/dashboard.mdx | 9 +++--- packages/spec/src/ui/component.zod.ts | 2 +- .../ui/dashboard-header-ask-ai-37142.test.ts | 29 +++++++++++++++++++ packages/spec/src/ui/dashboard.zod.ts | 28 ++++++++++++++++-- .../__tests__/RequireAiSurface.test.tsx | 18 ++++++------ .../src/hooks/__tests__/useAiSurface.test.ts | 22 ++++++++++---- .../__tests__/useAskAiHandler-37142.test.tsx | 6 ++-- ...DefaultInspector.typeSwitch-26736.test.tsx | 3 ++ .../previews/ObjectFormCanvas.test.tsx | 6 ++-- .../ObjectActionsPanel.presets-11861.test.tsx | 7 +++++ .../src/renderers/action/action-button.tsx | 5 +++- .../src/renderers/action/action-group.tsx | 8 ++++- .../src/renderers/action/action-icon.tsx | 5 +++- .../src/renderers/action/action-menu.tsx | 5 +++- 19 files changed, 156 insertions(+), 37 deletions(-) create mode 100644 .changeset/37142-ask-ai-action-type.md create mode 100644 packages/spec/src/ui/dashboard-header-ask-ai-37142.test.ts diff --git a/.changeset/37142-ask-ai-action-type.md b/.changeset/37142-ask-ai-action-type.md new file mode 100644 index 00000000000..3a36caaf7da --- /dev/null +++ b/.changeset/37142-ask-ai-action-type.md @@ -0,0 +1,27 @@ +--- +'@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 owed — skills/objectstack-ui/SKILL.md, skills/objectstack-ai/SKILL.md + +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, bulk bar, page action renderers). A launch that reaches the runner anyway is refused, not reported done. 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 d7c5089aefd..57670f64b5c 100644 --- a/content/docs/references/kernel/metadata-plugin.mdx +++ b/content/docs/references/kernel/metadata-plugin.mdx @@ -327,7 +327,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/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/ui/packages/app-shell/src/console/__tests__/RequireAiSurface.test.tsx b/ui/packages/app-shell/src/console/__tests__/RequireAiSurface.test.tsx index b39c19024b8..d23588e0154 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(); @@ -117,7 +117,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»'); @@ -130,14 +130,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(); @@ -152,7 +152,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' }, @@ -168,7 +168,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' }, @@ -185,7 +185,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(); 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 index ce4b0184f02..eb0a079e40b 100644 --- a/ui/packages/app-shell/src/hooks/__tests__/useAskAiHandler-37142.test.tsx +++ b/ui/packages/app-shell/src/hooks/__tests__/useAskAiHandler-37142.test.tsx @@ -13,7 +13,7 @@ * through `setChatFocus` and opens the drawer; it sends nothing. */ -import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { describe, it, expect, vi, beforeEach, type Mock } from 'vitest'; import { renderHook } from '@testing-library/react'; import React from 'react'; @@ -39,8 +39,8 @@ vi.mock('../../layout/chatFocus.js', async (importOriginal) => ({ import { ChatDockControlProvider, type ChatDockControl } from '../../layout/chatDockControl.js'; import { useAskAiHandler } from '../useAskAiHandler.js'; -function dock(): ChatDockControl & { open: ReturnType } { - return { expanded: false, fullWindow: false, toggle: vi.fn(), open: vi.fn() }; +function dock(): ChatDockControl & { open: Mock } { + return { expanded: false, fullWindow: false, toggle: vi.fn(), open: vi.fn() }; } function renderWith(control: ChatDockControl | null) { 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..07c9c5bd2fc 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 @@ -180,6 +180,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/studio-design/ObjectActionsPanel.presets-11861.test.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectActionsPanel.presets-11861.test.tsx index 7dec755a5a4..e2f97ed4846 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 @@ -340,6 +340,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-button.tsx b/ui/packages/components/src/renderers/action/action-button.tsx index 0f8fe0064d2..45c99febf73 100644 --- a/ui/packages/components/src/renderers/action/action-button.tsx +++ b/ui/packages/components/src/renderers/action/action-button.tsx @@ -21,7 +21,7 @@ import React, { forwardRef, useCallback, useState } from 'react'; import { ComponentRegistry } from '@object-ui/core'; import type { ActionDef } from '@object-ui/core'; import type { UIActionSchema } from '@object-ui/types'; -import { useAction, useRecordContext } from '@object-ui/react'; +import { useAction, useDrawsAction, useRecordContext } from '@object-ui/react'; import { useCondition, toPredicateInput, usePredicateRecordContext } from '@object-ui/react'; import { Button } from '../../ui'; import { cn } from '../../lib/utils'; @@ -432,7 +432,10 @@ const ActionButtonRenderer = forwardRef< // everyone (objectui#3823). Reachable because `action:bar` bypasses // `SchemaRenderer` and spreads the whole member action onto this schema, so // this gate is the only one on that path. See `hasDeclaredVisibilityGate`. + // `ask_ai` is absent, not disabled, where no in-app assistant can take it (objectstack#37142). + const drawsAction = useDrawsAction(); if (hasDeclaredVisibilityGate(schema.visible) && !isVisible) return null; + if (!drawsAction(schema)) return null; const button = (