Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/35650-action-designer-served-rows.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@object-ui/app-shell': patch
---

fix(studio): the action designer draws a script action's refusal catalogue and declared texts with their served rows

Clause-②: no
Metadata-protocol: none

The served `action` form gives `refusals` and `texts` the key-only record control (an entry is drawn under its code or key, with its message, status, reasons and params rows) and help text, but only the Related drawer editor read that form. The action's full-page editor and the Studio object's Actions view mount the action designer, whose "More fields" section was handed the bare schema, so both keys read as the raw JSON editor.

The designer now takes the served form from its host (`serverForm` on the default-inspector props) and draws the two rows from it in its Behavior section, beside the script body; the row's own visibility rule shows them on a script action only. A host with no served form keeps both keys in "More fields", as before. Nothing about what an action stores or what the server accepts changes.

The console's zh-CN overlay gains the labels for the action's `refusals` and `texts` rows and the hook's `texts` rows.
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* objectstack#35650 — the action's full-page editor draws a script action's
* refusal catalogue (`refusals`) and declared texts (`texts`) with their
* served rows: the key-only record control and the row's help text, not the
* raw JSON editor the bare schema gives a record.
*
* The REAL page with the production registrations: `action` registers a
* preview and a default inspector, so the page takes its designer branch and
* the no-selection panel is `ActionDefaultInspector`. The type row is built
* from the spec the way the server builds it: `actionForm` as the form, and
* `ActionSchema` converted with `z.toJSONSchema(…, { io: 'input' })` as the
* schema. The only stand-ins are the metadata client and the network.
*/

import '@testing-library/jest-dom/vitest';
import * as React from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { z } from 'zod';
import { ActionSchema, actionForm } from '@objectstack/spec/ui';

// Module-scope imports of the engines the page reaches through dynamic
// `import()` (the CEL authoring and the save-time lint): a cold first load
// stays out of every `waitFor` (`check:test-source-alias`).
import '@objectstack/formula';
import '@objectstack/lint';

/** The `action` row's `schema`, converted from the spec the way the server does. */
const ACTION_JSON_SCHEMA = z.toJSONSchema(ActionSchema as unknown as z.ZodType, {
io: 'input',
unrepresentable: 'any',
}) as Record<string, unknown>;

/** The served row of `key`, read off the form the server serves. */
function servedHelpText(key: string): string {
for (const section of actionForm.sections ?? []) {
for (const row of section.fields ?? []) {
if (typeof row !== 'string' && row.field === key) return String(row.helpText);
}
}
throw new Error(`actionForm declares no ${key} row`);
}

const STORED = {
name: 'sign_contract',
label: 'Sign contract',
objectName: 'contract',
type: 'script',
locations: ['record_header'],
body: { language: 'js', source: "throw { code: 'SIGN_IN_REQUIRED' };" },
refusals: { SIGN_IN_REQUIRED: { message: 'Sign in first.', status: 401 } },
texts: { email_subject: { message: 'Contract signed' } },
};

let stored: Record<string, unknown> = STORED;

const mockClient = {
list: vi.fn(async () => []),
listDrafts: vi.fn(async () => []),
layered: vi.fn(async () => ({ effective: stored, code: null, editable: true, deletable: true })),
getDraft: vi.fn(async () => null),
get: vi.fn(async () => stored),
save: vi.fn(async (_type: string, _name: string, item: unknown) => {
stored = item as Record<string, unknown>;
return {};
}),
saveDraft: vi.fn(async () => ({})),
publish: vi.fn(async () => ({ success: true })),
references: vi.fn(async () => []),
history: vi.fn(async () => []),
// The object-scoped field pickers read the bound object through the draft-preview client.
withPreviewDrafts: vi.fn(),
};
mockClient.withPreviewDrafts.mockImplementation(() => mockClient);

vi.mock('./useMetadata', async (importOriginal) => ({
...(await importOriginal<typeof import('./useMetadata')>()),
useMetadataClient: () => mockClient,
useMetadataTypes: () => ({
loading: false,
error: null,
entries: [
{
type: 'action',
name: 'action',
label: 'Action',
domain: 'ui',
allowEnvironmentOverlay: true,
allowRuntimeCreate: true,
schema: ACTION_JSON_SCHEMA,
form: actionForm,
},
],
}),
}));
vi.mock('@monaco-editor/react', () => {
const Editor = () => null;
return { Editor, default: Editor, loader: { init: () => Promise.reject(new Error('offline')) } };
});
vi.mock('@object-ui/plugin-editor', () => ({ configureBundledMonaco: () => Promise.resolve() }));
vi.stubGlobal(
'fetch',
vi.fn(async () => new Response('null', { status: 404, headers: { 'content-type': 'application/json' } })),
);

import { MetadataResourceEditPage } from './ResourceEditPage';
import { t } from './i18n';
// The load-time registrations, exactly as the package entry runs them, so the
// branch this file takes is the branch production takes.
import './register-builtins';
import { registerBuiltinDesigners } from './register-builtin-designers';
registerBuiltinDesigners();

beforeEach(() => {
stored = STORED;
for (const fn of Object.values(mockClient)) (fn as unknown as { mockClear: () => void }).mockClear();
mockClient.withPreviewDrafts.mockImplementation(() => mockClient);
window.localStorage.setItem('metadata-admin:autosave', '0');
});
afterEach(() => {
cleanup();
window.localStorage.removeItem('metadata-admin:autosave');
});

async function openAction(): Promise<void> {
render(
<MemoryRouter initialEntries={['/metadata/action/sign_contract']}>
<MetadataResourceEditPage type="action" name="sign_contract" />
</MemoryRouter>,
);
// The designer branch opens editable: its panel is the inspector itself.
await screen.findByText(t('engine.inspector.moreFields', 'en'), {}, { timeout: 8000 });

}

describe('the action full-page editor draws refusals and texts from their served rows (objectstack#35650)', () => {
it('draws each as the key-only record control with the served help text, and no raw JSON', async () => {
await openAction();
// No editor on the panel holds either record as JSON text (the raw JSON face).
const jsonHolders = Array.from(document.querySelectorAll('textarea')).filter(
(el) => el.value.includes('"SIGN_IN_REQUIRED"') || el.value.includes('"email_subject"'),
);
expect(jsonHolders).toEqual([]);
// The served rows' help text, and the key-only control drawing each entry under its key.
expect(screen.getByText(servedHelpText('refusals'))).toBeInTheDocument();
expect(screen.getByText(servedHelpText('texts'))).toBeInTheDocument();
const rows = screen.getByTestId('action-served-rows');
expect(within(rows).getByText('SIGN_IN_REQUIRED', { selector: 'span' })).toBeInTheDocument();
expect(within(rows).getByText('email_subject', { selector: 'span' })).toBeInTheDocument();
});

it('an entry edited through the served row saves as a spec-valid action', async () => {
await openAction();
const rows = screen.getByTestId('action-served-rows');
fireEvent.click(within(rows).getByText('email_subject', { selector: 'span' }));
const entry = within(rows).getByText('email_subject', { selector: 'span' }).closest('.rounded-md') as HTMLElement;
fireEvent.change(within(entry).getByDisplayValue('Contract signed'), { target: { value: 'Your contract is signed' } });
await waitFor(() => expect(screen.getByTestId('resource-save')).toBeEnabled(), { timeout: 4000 });
fireEvent.click(screen.getByTestId('resource-save'));
await waitFor(() => expect(mockClient.save).toHaveBeenCalledTimes(1), { timeout: 6000 });
const body = JSON.parse(JSON.stringify(mockClient.save.mock.calls[0]![2])) as Record<string, unknown>;
expect(body.texts).toEqual({ email_subject: { message: 'Your contract is signed' } });
expect(body.refusals).toEqual(STORED.refusals);
const parsed = ActionSchema.safeParse(body);
expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -3812,6 +3812,7 @@ function MetadataResourceEditPageImpl({
readOnly={formReadOnly}
locale={locale}
serverSchema={entry?.schema as Record<string, unknown> | undefined}
serverForm={entry?.form}
issues={displayIssues}
revealIssues={revealIssues}
onInlineIssueFieldsChange={setInlineIssueFields}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import type { ComponentType, ReactNode } from 'react';
import type { SupportedLocale } from './i18n.js';
import { createObservableTypeRegistry, type MetadataSelection } from './preview-registry.js';
import type { SchemaFormIssue } from './SchemaForm.js';
import type { FormViewSpec } from './form-spec.js';

export interface MetadataDefaultInspectorProps {
/** Metadata type, e.g. 'view'. */
Expand Down Expand Up @@ -73,6 +74,16 @@ export interface MetadataDefaultInspectorProps {
* server schema is available (offline / older server).
*/
serverSchema?: Record<string, unknown>;
/**
* The served FormView layout for this type (`RichMetadataTypeEntry.form`,
* from `/meta/types`), the form a generic host hands `SchemaForm` beside
* {@link serverSchema}. A curated inspector reads the rows it names from it,
* so a row the server declares a face for (a widget, help text, a
* visibility predicate) is drawn with that face rather than the one the
* bare schema implies (objectstack#35650). Undefined when the host has no
* served form: such an inspector draws those keys as it did without one.
*/
serverForm?: FormViewSpec;
/**
* The host's issues on the draft (a refused save, the live pass), paths
* relative to the draft — what the host's fallback form is handed. An
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@
* control, shared (`ScriptCapabilitiesField`), because both bodies are the
* spec's one `HookBodySchema`. An expression body shows none, and a switch to
* it drops the grant with the other L2-only keys ({@link writeScriptBody}).
*
* A script action's refusal catalogue (`refusals`) and declared texts (`texts`)
* are drawn from their SERVED form rows (objectstack#35650), handed in as
* `serverForm`: the key-only record control, the entry rows and the help text
* the server declares. Fed the bare schema in "More fields" they read as the
* raw JSON editor. A host with no served form keeps them in "More fields".
*/

import * as React from 'react';
Expand All @@ -59,6 +65,9 @@ import { usePermissions } from '@object-ui/permissions';
import type { MetadataDefaultInspectorProps } from '../default-inspector-registry.js';
import { SchemaForm } from '../SchemaForm.js';
import { fallbackFormPatch } from './fallbackFormPatch.js';
import { servedFormRows } from './servedFormRows.js';
import { useIssuePrefixRegister } from '../issuePath.js';
import type { FormViewSpec } from '../form-spec.js';
import { t, tFormat, type SupportedLocale } from '../i18n.js';
import {
InspectorShell,
Expand Down Expand Up @@ -479,6 +488,19 @@ const CURATED_FIELDS = [
*/
const RETIRED_FIELDS = ['bulkEnabled', 'shortcut'];

/**
* Keys this inspector draws from their SERVED form row (objectstack#35650),
* beside the script body in the Behavior section: the action's refusal
* catalogue and its declared texts. Each is a record keyed by the code or key
* the body uses, and its served row declares the key-only record control, the
* entry's own rows and the help text; the bare schema the fallback form reads
* says only "a record", which is the raw JSON editor. The row's own
* `visibleWhen` (a `script` action) decides when it shows.
*
* A key the served form has no row for stays in the fallback form, as before.
*/
const SERVED_ROW_FIELDS = ['refusals', 'texts'] as const;

/* ─────────────── small helpers ─────────────── */

function SectionHeader({ title, hint }: { title: string; hint?: string }) {
Expand Down Expand Up @@ -639,6 +661,23 @@ function ParamOptionsEditor({ options, onCommit, disabled, locale }: {

/* ─────────────── inspector ─────────────── */

/**
* The setter a whole-draft `SchemaForm` reports its inline rows through
* (`onInlineIssueFieldsChange`): each row key is registered, unprefixed, for as
* long as the form reports it, so two such forms on one draft are heard as one
* union rather than the later report replacing the earlier one.
*/
function useWholeDraftFormIssueRows(
register: (prefix: string) => () => void,
): (rows: ReadonlySet<string>) => void {
const [rows, setRows] = React.useState<ReadonlySet<string>>(() => new Set());
React.useEffect(() => {
const offs = [...rows].map((row) => register(row));
return () => offs.forEach((off) => off());
}, [rows, register]);
return setRows;
}

/**
* The CEL editors this inspector mounts, as aggregation keys. Errors are
* counted PER SITE rather than into one running total: the two predicate
Expand All @@ -659,8 +698,15 @@ export function ActionDefaultInspector({
issues,
revealIssues,
onInlineIssueFieldsChange,
serverForm,
}: MetadataDefaultInspectorProps) {
const tr = React.useCallback((key: string) => t(key, locale), [locale]);
// Two forms draw rows of this draft (the served rows below and the "More
// fields" fallback), so each registers the rows it draws and the host hears
// the union (objectstack#35628's inline register).
const registerIssuePrefix = useIssuePrefixRegister(onInlineIssueFieldsChange);
const setServedIssueRows = useWholeDraftFormIssueRows(registerIssuePrefix);
const setFallbackIssueRows = useWholeDraftFormIssueRows(registerIssuePrefix);
// objectui#12510 — the Icon label names the icon picker (the shape objectui#12531
// gave the object and app-nav icon fields): the picker is a combobox, which
// takes no name from its content.
Expand Down Expand Up @@ -899,6 +945,14 @@ export function ActionDefaultInspector({
};

const fallbackSchema = serverSchema as Record<string, unknown> | undefined;
// objectstack#35650 — the served rows of SERVED_ROW_FIELDS, for the keys the
// served schema declares, as a one-section form over the same schema.
const servedProps = (fallbackSchema?.properties ?? {}) as Record<string, unknown>;
const servedRows = servedFormRows(serverForm, SERVED_ROW_FIELDS).filter((row) => row.field in servedProps);
const servedRowsForm: FormViewSpec | undefined =
serverForm && servedRows.length > 0
? { ...serverForm, type: 'simple', sections: [{ fields: servedRows }], groups: undefined }
: undefined;

return (
<InspectorShell
Expand Down Expand Up @@ -1084,6 +1138,20 @@ export function ActionDefaultInspector({
<div className="text-[11px] text-muted-foreground/70">{tr('engine.inspector.action.bodyShapeHint')}</div>
</div>
)}
{fallbackSchema && servedRowsForm && (
<div data-testid="action-served-rows">
<SchemaForm
schema={fallbackSchema}
form={servedRowsForm}
value={draft}
readOnly={readOnly}
issues={issues}
revealIssues={revealIssues}
onInlineIssueFieldsChange={setServedIssueRows}
onChange={(next) => onPatch(fallbackFormPatch(draft, next))}
/>
</div>
)}
</div>

{/* 3 ─ Inputs (params) */}
Expand Down Expand Up @@ -1272,11 +1340,11 @@ export function ActionDefaultInspector({
<SchemaForm
schema={fallbackSchema}
value={draft}
hiddenFields={[...CURATED_FIELDS, ...RETIRED_FIELDS]}
hiddenFields={[...CURATED_FIELDS, ...RETIRED_FIELDS, ...(servedRowsForm ? servedRows.map((row) => row.field) : [])]}
readOnly={readOnly}
issues={issues}
revealIssues={revealIssues}
onInlineIssueFieldsChange={onInlineIssueFieldsChange}
onInlineIssueFieldsChange={setFallbackIssueRows}
onChange={(next) => onPatch(fallbackFormPatch(draft, next))}
/>
</div>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

import type { FormFieldSpec, FormViewSpec } from '../form-spec.js';

/**
* The rows the served form declares for `keys`, in the form's own order
* (objectstack#35650).
*
* A curated inspector edits most keys with its own controls and hands the rest
* to a "More fields" `SchemaForm` fed the bare served schema. A key whose
* served row declares its face — a `widget`, help text, nested row
* descriptors, a visibility predicate — loses all of it there: the schema
* alone says only "a record", and a record with no row reads as the raw JSON
* editor. Drawing such a key from its served row is how the inspector reads
* the contract the server already serves, instead of hand-building a second
* face for it.
*
* A key the form declares no row for is not returned, so the caller keeps
* drawing it in its fallback form, as before: nothing is lost when the host
* has no served form, or the server's form predates the row. A `{ group }`
* section names no row by key, so it contributes none here (`SchemaForm`
* resolves such a section when it renders a whole form; this is a lookup).
*/
export function servedFormRows(
form: FormViewSpec | undefined,
keys: readonly string[],
): FormFieldSpec[] {
const rows: FormFieldSpec[] = [];
for (const section of form?.sections ?? form?.groups ?? []) {
if (!Array.isArray(section.fields)) continue;
for (const row of section.fields) {
const spec: FormFieldSpec = typeof row === 'string' ? { field: row } : row;
if (keys.includes(spec.field) && !rows.some((r) => r.field === spec.field)) rows.push(spec);
}
}
return rows;
}
Loading
Loading