From 1030bf5422ee34b13ee45b6e18c72f3fd8ce4842 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 09:19:35 +0000 Subject: [PATCH 1/8] wip: hook form offers refusal reasons and params Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oQHgtkqYPCqstiKir --- packages/spec/src/data/hook.form.ts | 17 +- .../metadata-form-zod-reconciliation.test.ts | 13 -- ...EditPage.hookRefusalReasons-33657.test.tsx | 162 ++++++++++++++++++ .../SchemaForm.keyOnlyRecord-26835.test.tsx | 113 +++++++++++- 4 files changed, 286 insertions(+), 19 deletions(-) create mode 100644 ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.hookRefusalReasons-33657.test.tsx diff --git a/packages/spec/src/data/hook.form.ts b/packages/spec/src/data/hook.form.ts index bed8c2aa62b..0028097ad58 100644 --- a/packages/spec/src/data/hook.form.ts +++ b/packages/spec/src/data/hook.form.ts @@ -48,15 +48,28 @@ export const hookForm = defineForm({ }, // The catalogue is a record keyed by the code, and an entry has no // member that echoes its key — so the row takes the key-only record - // control, which never writes the key into the entry (#26835). + // control, which never writes the key into the entry (#26835). An + // entry's `reasons` is the same shape one level down (keyed by the + // reason, each `{ message }`), so it takes the same control; the key + // rule each level checks is the one its served schema declares. { field: 'refusals', type: 'record', widget: 'key-only-record', helpText: 'Refusal catalogue, keyed by the SCREAMING_SNAKE code the body throws (e.g. CLEAN_VERSION_REQUIRED). The caller reads the declared message, translated into their language, with the declared status. JavaScript (L2) bodies only', fields: [ - { field: 'message', type: 'textarea', required: true, helpText: 'The sentence the user reads when the body throws this code — plain text, with no placeholders' }, + { field: 'message', type: 'textarea', required: true, helpText: 'The sentence the user reads when the body throws this code. Plain text, unless the entry declares params: then a {{ name }} hole fills a declared param' }, { field: 'status', type: 'number', helpText: 'HTTP status of the refusal (400–499). Absent: 400' }, + { + field: 'reasons', + type: 'record', + widget: 'key-only-record', + helpText: 'Further sentences under this same code, keyed by the snake_case reason the body throws beside the code ({ code, reason }). The wire code and status stay this entry\'s; a reason not declared here is refused. Absent: a thrown reason is not read', + fields: [ + { field: 'message', type: 'textarea', required: true, helpText: 'The sentence the user reads when the body throws this reason under the code. Its {{ }} holes follow the entry\'s params' }, + ], + }, + { field: 'params', type: 'tags', helpText: 'Names the sentences may fill (e.g. state): the body throws { code, params: { state } }, and a {{ state }} hole renders it. Absent: the sentences are plain text' }, ], }, ], diff --git a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts index 35f979507fa..5c1868dca5d 100644 --- a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts +++ b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts @@ -191,19 +191,6 @@ type OmitEntry = { kind: 'omit'; type: string; path: string; key: string; why: s type SubsetEntry = { kind: 'subset'; type: string; path: string; why: string }; const LEDGER: ReadonlyArray = [ - // #33214 (ruling 6879477573, S1 and params) — a hook refusal's further - // sentences under one code and the names its holes fill. The hook form lays - // out a refusal as message + status, which is all a Studio-authored hook - // needs to refuse by code; `reasons` and `params` are authored in code - // beside the throw that names them. Offering them in the form is a Studio - // change of its own (a record nested in a key-only record, and a name list). - ...(['reasons', 'params'] as const).map((key): OmitEntry => ({ - kind: 'omit', - type: 'hook', - path: 'refusals', - key, - why: "authored in code beside the throw that names it — a `reason` or a `params` value is spelled in the hook's throw, which a Studio-authored body writes in the same code; the form lays out a refusal as message + status, and offering a nested reasons record and a params list is a Studio change of its own", - })), { kind: 'omit', type: 'page', diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.hookRefusalReasons-33657.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.hookRefusalReasons-33657.test.tsx new file mode 100644 index 00000000000..43fd0e672e4 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.hookRefusalReasons-33657.test.tsx @@ -0,0 +1,162 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * MEASUREMENT (objectstack#33657) — the Studio hook form against a refusal + * catalogue that declares `reasons` and `params`, through the real edit page. + */ + +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 } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import { z } from 'zod'; +import { HookSchema, hookForm } from '@objectstack/spec/data'; + +import '@objectstack/formula'; +import '@objectstack/lint'; + +const HOOK_JSON_SCHEMA = z.toJSONSchema(HookSchema as unknown as z.ZodType, { + io: 'input', + unrepresentable: 'any', +}) as Record; + +const STORED_HOOK = { + name: 'sign_contract', + label: 'Sign contract', + object: 'contract', + events: ['beforeUpdate'], + body: { language: 'js', source: "throw { code: 'CONTRACT_LOCKED', reason: 'plan_locked', params: { state: 'x' } };" }, + refusals: { + CONTRACT_LOCKED: { + message: 'This contract is locked ({{ state }}).', + status: 409, + params: ['state'], + reasons: { plan_locked: { message: 'The plan is locked while {{ state }}.' } }, + }, + }, +}; + +let stored: Record = STORED_HOOK; +const FORM: { current: unknown } = { current: hookForm }; +function withReasons(): unknown { + const clone = JSON.parse(JSON.stringify(hookForm)); + for (const s of clone.sections) for (const f of s.fields) if (f.field === 'refusals') { + f.fields.push({ field: 'reasons', type: 'record', widget: 'key-only-record', fields: [{ field: 'message', type: 'textarea', required: true }] }); + f.fields.push({ field: 'params', type: 'tags' }); + } + return clone; +} + +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 (_t: string, _n: string, item: unknown) => { + stored = item as Record; + return {}; + }), + saveDraft: vi.fn(async () => ({})), + publish: vi.fn(async () => ({ success: true })), + references: vi.fn(async () => []), + history: vi.fn(async () => []), +}; + +vi.mock('./useMetadata', async (importOriginal) => ({ + ...(await importOriginal()), + useMetadataClient: () => mockClient, + useMetadataTypes: () => ({ + loading: false, + error: null, + entries: [ + { + type: 'hook', + name: 'hook', + label: 'Hook', + domain: 'data', + allowEnvironmentOverlay: true, + allowRuntimeCreate: true, + schema: HOOK_JSON_SCHEMA, + form: FORM.current, + }, + ], + }), +})); +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 './register-builtins'; +import { registerBuiltinDesigners } from './register-builtin-designers'; +registerBuiltinDesigners(); + +beforeEach(() => { + stored = STORED_HOOK; + FORM.current = hookForm; + for (const fn of Object.values(mockClient)) (fn as unknown as { mockClear: () => void }).mockClear(); + window.localStorage.setItem('metadata-admin:autosave', '0'); +}); +afterEach(() => { + cleanup(); + window.localStorage.removeItem('metadata-admin:autosave'); +}); + +describe('MEASURE', () => { + it('what the refusal entry offers, and what a label edit saves', async () => { + render( + + + , + ); + fireEvent.click((await screen.findAllByRole('button', { name: 'Edit' }, { timeout: 8000 }))[0]); + fireEvent.click(await screen.findByText('CONTRACT_LOCKED')); + const group = screen.getByText('CONTRACT_LOCKED').closest('.rounded-md') as HTMLElement; + const labels = Array.from(group.querySelectorAll('label')).map((l) => l.textContent); + console.log('MEASURE entry labels:', JSON.stringify(labels)); + const label = document.getElementById('mdf-label') as HTMLInputElement; + fireEvent.change(label, { target: { value: 'Sign the contract' } }); + fireEvent.click(screen.getByTestId('resource-save')); + await waitFor(() => expect(mockClient.save.mock.calls.length + mockClient.saveDraft.mock.calls.length).toBeGreaterThan(0)); + console.log('MEASURE save calls:', JSON.stringify(mockClient.save.mock.calls.map((c) => c[2]))); + console.log('MEASURE saveDraft calls:', JSON.stringify(mockClient.saveDraft.mock.calls)); + }); + + it('editing the entry message keeps reasons/params', async () => { + render( + + + , + ); + fireEvent.click((await screen.findAllByRole('button', { name: 'Edit' }, { timeout: 8000 }))[0]); + fireEvent.click(await screen.findByText('CONTRACT_LOCKED')); + fireEvent.change(screen.getByDisplayValue('This contract is locked ({{ state }}).'), { target: { value: 'Locked ({{ state }}).' } }); + fireEvent.click(screen.getByTestId('resource-save')); + await waitFor(() => expect(mockClient.save).toHaveBeenCalled()); + console.log('MEASURE2 refusals:', JSON.stringify((mockClient.save.mock.calls[0][2] as any).refusals)); + }); + it('renderer with a nested key-only record + tags row', async () => { + FORM.current = withReasons(); + render( + + + , + ); + fireEvent.click((await screen.findAllByRole('button', { name: 'Edit' }, { timeout: 8000 }))[0]); + fireEvent.click(await screen.findByText('CONTRACT_LOCKED')); + const group = screen.getByText('CONTRACT_LOCKED').closest('.rounded-md') as HTMLElement; + console.log('MEASURE3 labels:', JSON.stringify(Array.from(group.querySelectorAll('label')).map((l) => l.textContent))); + console.log('MEASURE3 has plan_locked:', !!screen.queryByText('plan_locked')); + console.log('MEASURE3 placeholders:', JSON.stringify(Array.from(group.querySelectorAll('input')).map((i) => [i.placeholder, i.value, i.id]))); + const ids = Array.from(document.querySelectorAll('[id]')).map((e) => e.id); + console.log('MEASURE3 dup ids:', JSON.stringify(ids.filter((x, i) => ids.indexOf(x) !== i))); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.keyOnlyRecord-26835.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.keyOnlyRecord-26835.test.tsx index bb44e1b7af9..6d5609e2a79 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.keyOnlyRecord-26835.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.keyOnlyRecord-26835.test.tsx @@ -20,9 +20,14 @@ import * as React from 'react'; import { describe, it, expect, afterEach } from 'vitest'; -import { render, screen, cleanup, fireEvent } from '@testing-library/react'; +import { render, screen, cleanup, fireEvent, within } from '@testing-library/react'; import { z } from 'zod'; -import { HookSchema, hookForm, HOOK_REFUSAL_CODE_PATTERN } from '@objectstack/spec/data'; +import { + HookSchema, + hookForm, + HOOK_REFUSAL_CODE_PATTERN, + HOOK_REFUSAL_REASON_PATTERN, +} from '@objectstack/spec/data'; import { SchemaForm, KEY_ONLY_RECORD_WIDGET } from './SchemaForm'; afterEach(cleanup); @@ -86,9 +91,14 @@ function renderHook(row: FormRow, initial: Record = HOOK_BASE) return sink; } +/** + * Add a code through the catalogue's own add box. An open entry draws a second + * one for its `reasons` (objectstack#33657), inside its card; the catalogue's + * box comes after every card, so it is the last of them. + */ function addKey(code: string) { - fireEvent.change(screen.getByPlaceholderText('Key'), { target: { value: code } }); - fireEvent.click(screen.getByRole('button', { name: 'Add' })); + fireEvent.change(screen.getAllByPlaceholderText('Key').at(-1)!, { target: { value: code } }); + fireEvent.click(screen.getAllByRole('button', { name: 'Add' }).at(-1)!); } function refusalsOf(sink: { value: Record }) { @@ -200,3 +210,98 @@ describe('the default record face is unchanged (objectstack#26835)', () => { ]); }); }); + +/** A sub-row of the hook form's `refusals` row, by field name — read from `hookForm`. */ +function refusalSubRow(field: string): FormRow { + const row = (refusalsRow().fields ?? []) as Array; + const found = row.find((f): f is FormRow => typeof f !== 'string' && f.field === field); + if (!found) throw new Error(`hookForm's refusals row offers no \`${field}\``); + return found; +} + +/** The entry card the key-only face draws for `key`, found from its header chip. */ +function entryCard(key: string): HTMLElement { + return screen.getByText(key, { selector: 'span' }).closest('.rounded-md') as HTMLElement; +} + +describe('a refusal entry offers `reasons` and `params` (objectstack#33657)', () => { + it('declares `reasons` as a key-only record of `{ message }` and `params` as a name list', () => { + const reasons = refusalSubRow('reasons'); + expect(reasons.type).toBe('record'); + expect(reasons.widget).toBe(KEY_ONLY_RECORD_WIDGET); + expect((reasons.fields as FormRow[]).map((f) => f.field)).toEqual(['message']); + expect(refusalSubRow('params').type).toBe('tags'); + }); + + it("serves the reason key rule the nested control reads, derived from the spec's reason spelling", () => { + const refusals = (HOOK_JSON_SCHEMA.properties as Record>).refusals; + const entry = refusals.additionalProperties as { properties: Record> }; + const reasons = entry.properties.reasons; + expect((reasons.propertyNames as { pattern?: string }).pattern).toBe(HOOK_REFUSAL_REASON_PATTERN.source); + }); + + it('authors a reason and a param under a code, and saves a body HookSchema accepts as written', () => { + const sink = renderHook(refusalsRow(), { + ...HOOK_BASE, + refusals: { CONTRACT_LOCKED: { message: 'This contract is locked.', status: 409 } }, + }); + fireEvent.click(screen.getByText('CONTRACT_LOCKED')); + const card = entryCard('CONTRACT_LOCKED'); + // The nested key-only control: its own add box, inside the entry's card. + const reasonKeyBox = within(card).getByPlaceholderText('Key'); + fireEvent.change(reasonKeyBox, { target: { value: 'plan_locked' } }); + fireEvent.click(within(card).getByRole('button', { name: 'Add' })); + // The new reason opens on its own message row, beside the entry's. + const messages = within(card).getAllByLabelText(/Message/); + expect(messages).toHaveLength(2); + fireEvent.change(messages[1]!, { target: { value: 'The plan is locked while {{ state }}.' } }); + const params = within(card).getByLabelText(/Params/); + fireEvent.change(params, { target: { value: 'state' } }); + fireEvent.keyDown(params, { key: 'Enter' }); + + const saved = JSON.parse(JSON.stringify(sink.value)) as Record; + expect(saved.refusals).toEqual({ + CONTRACT_LOCKED: { + message: 'This contract is locked.', + status: 409, + reasons: { plan_locked: { message: 'The plan is locked while {{ state }}.' } }, + params: ['state'], + }, + }); + const parsed = HookSchema.safeParse(saved); + expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); + expect(JSON.stringify(parsed.data!.refusals)).toBe(JSON.stringify(saved.refusals)); + }); + + it('refuses a reason key that breaks the served reason rule, and leaves the value as it was', () => { + const sink = renderHook(refusalsRow(), { + ...HOOK_BASE, + refusals: { CONTRACT_LOCKED: { message: 'This contract is locked.' } }, + }); + fireEvent.click(screen.getByText('CONTRACT_LOCKED')); + const card = entryCard('CONTRACT_LOCKED'); + fireEvent.change(within(card).getByPlaceholderText('Key'), { target: { value: 'PLAN_LOCKED' } }); + fireEvent.click(within(card).getByRole('button', { name: 'Add' })); + expect(refusalsOf(sink)).toEqual({ CONTRACT_LOCKED: { message: 'This contract is locked.' } }); + expect(within(card).getByText(`Key must match ${String(HOOK_REFUSAL_REASON_PATTERN)}`)).toBeInTheDocument(); + }); + + it('reloads a catalogue that declares reasons and params into the same rows', () => { + renderHook(refusalsRow(), { + ...HOOK_BASE, + refusals: { + CONTRACT_LOCKED: { + message: 'This contract is locked ({{ state }}).', + params: ['state'], + reasons: { plan_locked: { message: 'The plan is locked while {{ state }}.' } }, + }, + }, + }); + fireEvent.click(screen.getByText('CONTRACT_LOCKED')); + const card = entryCard('CONTRACT_LOCKED'); + fireEvent.click(within(card).getByText('plan_locked')); + expect(within(card).getByDisplayValue('plan_locked')).toBeInTheDocument(); + expect(within(card).getByDisplayValue('The plan is locked while {{ state }}.')).toBeInTheDocument(); + expect(within(card).getByText('state', { selector: 'span' })).toBeInTheDocument(); + }); +}); From 5123b38149a66025c3257d9f0fd96021aa4fd3fe Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 09:21:59 +0000 Subject: [PATCH 2/8] test: pin the Studio hook editor authoring refusal reasons and params Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oQHgtkqYPCqstiKir --- ...EditPage.hookRefusalReasons-33657.test.tsx | 178 +++++++++++------- 1 file changed, 114 insertions(+), 64 deletions(-) diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.hookRefusalReasons-33657.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.hookRefusalReasons-33657.test.tsx index 43fd0e672e4..d204ecd117b 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.hookRefusalReasons-33657.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.hookRefusalReasons-33657.test.tsx @@ -1,32 +1,55 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * MEASUREMENT (objectstack#33657) — the Studio hook form against a refusal - * catalogue that declares `reasons` and `params`, through the real edit page. + * The Studio hook editor authors a refusal's `reasons` and `params` + * (objectstack#33657), through the real edit page. + * + * A refusal entry is `{ message, status?, reasons?, params? }` + * (`HookRefusalSchema`): `reasons` is keyed by the snake_case reason the body + * throws beside the code, each `{ message }`, and `params` names the holes its + * sentences may fill. The hook form offers both on the entry: `reasons` takes + * the key-only record control one level down, `params` the name list. + * + * The REAL page with the production registrations: `hook` has no designer, so + * the page takes its generic-form branch and renders the form the server + * serves for the type. The type row here is that row built from the spec the + * way the server builds it: `hookForm` as the form, and `HookSchema` converted + * with `z.toJSONSchema(…, { io: 'input' })` as the schema. The only stand-ins + * are the metadata client (the "server" a save writes to and a reload reads + * back) and the code editor's loader. */ 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 } from '@testing-library/react'; +import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; import { z } from 'zod'; import { HookSchema, hookForm } from '@objectstack/spec/data'; +// Module-scope imports of the engines the page reaches through dynamic +// `import()` (the condition row's CEL authoring and the save-time lint), per +// AGENTS.md's flaky-test rule: a cold first load stays out of every `waitFor`. import '@objectstack/formula'; import '@objectstack/lint'; +/** The `hook` row's `schema`, converted from the spec the way the server does. */ const HOOK_JSON_SCHEMA = z.toJSONSchema(HookSchema as unknown as z.ZodType, { io: 'input', unrepresentable: 'any', }) as Record; -const STORED_HOOK = { +const BASE = { name: 'sign_contract', label: 'Sign contract', object: 'contract', events: ['beforeUpdate'], - body: { language: 'js', source: "throw { code: 'CONTRACT_LOCKED', reason: 'plan_locked', params: { state: 'x' } };" }, + body: { language: 'js', source: "throw { code: 'CONTRACT_LOCKED' };" }, +}; + +/** A catalogue that uses both parts, as code would declare it. */ +const WITH_REASONS = { + ...BASE, refusals: { CONTRACT_LOCKED: { message: 'This contract is locked ({{ state }}).', @@ -37,16 +60,14 @@ const STORED_HOOK = { }, }; -let stored: Record = STORED_HOOK; -const FORM: { current: unknown } = { current: hookForm }; -function withReasons(): unknown { - const clone = JSON.parse(JSON.stringify(hookForm)); - for (const s of clone.sections) for (const f of s.fields) if (f.field === 'refusals') { - f.fields.push({ field: 'reasons', type: 'record', widget: 'key-only-record', fields: [{ field: 'message', type: 'textarea', required: true }] }); - f.fields.push({ field: 'params', type: 'tags' }); - } - return clone; -} +/** The control: a refusal that declares only what the form offered before. */ +const PLAIN = { + ...BASE, + refusals: { CONTRACT_LOCKED: { message: 'This contract is locked.', status: 409 } }, +}; + +/** What the last accepted save stored — the "server" a reload reads back. */ +let stored: Record = PLAIN; const mockClient = { list: vi.fn(async () => []), @@ -54,7 +75,7 @@ const mockClient = { 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 (_t: string, _n: string, item: unknown) => { + save: vi.fn(async (_type: string, _name: string, item: unknown) => { stored = item as Record; return {}; }), @@ -79,29 +100,34 @@ vi.mock('./useMetadata', async (importOriginal) => ({ allowEnvironmentOverlay: true, allowRuntimeCreate: true, schema: HOOK_JSON_SCHEMA, - form: FORM.current, + form: hookForm, }, ], }), })); +// The body's code editor falls back to its plain textarea when Monaco's loader +// rejects — the shape an offline install gets. 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() })); +// The page's own side reads go through the global `fetch`; one double answers +// "absent" for the whole file, so no read reaches a socket. vi.stubGlobal( 'fetch', vi.fn(async () => new Response('null', { status: 404, headers: { 'content-type': 'application/json' } })), ); import { MetadataResourceEditPage } from './ResourceEditPage'; +// 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_HOOK; - FORM.current = hookForm; + stored = PLAIN; for (const fn of Object.values(mockClient)) (fn as unknown as { mockClear: () => void }).mockClear(); window.localStorage.setItem('metadata-admin:autosave', '0'); }); @@ -110,53 +136,77 @@ afterEach(() => { window.localStorage.removeItem('metadata-admin:autosave'); }); -describe('MEASURE', () => { - it('what the refusal entry offers, and what a label edit saves', async () => { - render( - - - , - ); - fireEvent.click((await screen.findAllByRole('button', { name: 'Edit' }, { timeout: 8000 }))[0]); - fireEvent.click(await screen.findByText('CONTRACT_LOCKED')); - const group = screen.getByText('CONTRACT_LOCKED').closest('.rounded-md') as HTMLElement; - const labels = Array.from(group.querySelectorAll('label')).map((l) => l.textContent); - console.log('MEASURE entry labels:', JSON.stringify(labels)); - const label = document.getElementById('mdf-label') as HTMLInputElement; - fireEvent.change(label, { target: { value: 'Sign the contract' } }); - fireEvent.click(screen.getByTestId('resource-save')); - await waitFor(() => expect(mockClient.save.mock.calls.length + mockClient.saveDraft.mock.calls.length).toBeGreaterThan(0)); - console.log('MEASURE save calls:', JSON.stringify(mockClient.save.mock.calls.map((c) => c[2]))); - console.log('MEASURE saveDraft calls:', JSON.stringify(mockClient.saveDraft.mock.calls)); +/** Open the stored hook, enter edit mode, and open its one refusal entry. */ +async function openRefusal(): Promise { + render( + + + , + ); + // The page renders Edit twice (header and toolbar); either enters edit mode. + fireEvent.click((await screen.findAllByRole('button', { name: 'Edit' }, { timeout: 8000 }))[0]!); + fireEvent.click(await screen.findByText('CONTRACT_LOCKED', { selector: 'span' })); + return screen.getByText('CONTRACT_LOCKED', { selector: 'span' }).closest('.rounded-md') as HTMLElement; +} + +/** Save, and hand back the body the page sent. */ +async function save(): Promise> { + fireEvent.click(screen.getByTestId('resource-save')); + await waitFor(() => expect(mockClient.save).toHaveBeenCalledTimes(1)); + return JSON.parse(JSON.stringify(mockClient.save.mock.calls[0]![2])) as Record; +} + +describe('the Studio hook editor authors a refusal\'s reasons and params (objectstack#33657)', () => { + it('offers Reasons and Params on a refusal entry, beside Message and Status', async () => { + const card = await openRefusal(); + const labels = Array.from(card.querySelectorAll('label')).map((l) => l.textContent?.replace(/\*$/, '')); + expect(labels).toEqual(['Key', 'Message', 'Status', 'Reasons', 'Params']); }); - it('editing the entry message keeps reasons/params', async () => { - render( - - - , - ); - fireEvent.click((await screen.findAllByRole('button', { name: 'Edit' }, { timeout: 8000 }))[0]); - fireEvent.click(await screen.findByText('CONTRACT_LOCKED')); - fireEvent.change(screen.getByDisplayValue('This contract is locked ({{ state }}).'), { target: { value: 'Locked ({{ state }}).' } }); - fireEvent.click(screen.getByTestId('resource-save')); - await waitFor(() => expect(mockClient.save).toHaveBeenCalled()); - console.log('MEASURE2 refusals:', JSON.stringify((mockClient.save.mock.calls[0][2] as any).refusals)); + it('authors a reason and a param, saves them, and the stored hook reads them back', async () => { + const card = await openRefusal(); + // The entry's own reasons control: its add box sits inside the entry's card. + fireEvent.change(within(card).getByPlaceholderText('Key'), { target: { value: 'plan_locked' } }); + fireEvent.click(within(card).getByRole('button', { name: 'Add' })); + const messages = within(card).getAllByLabelText(/Message/); + fireEvent.change(messages[1]!, { target: { value: 'The plan is locked while {{ state }}.' } }); + const params = within(card).getByLabelText(/Params/); + fireEvent.change(params, { target: { value: 'state' } }); + fireEvent.keyDown(params, { key: 'Enter' }); + + const body = await save(); + expect(body.refusals).toEqual({ + CONTRACT_LOCKED: { + message: 'This contract is locked.', + status: 409, + reasons: { plan_locked: { message: 'The plan is locked while {{ state }}.' } }, + params: ['state'], + }, + }); + const parsed = HookSchema.safeParse(body); + expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); + + // Read the stored hook back: a fresh page over what the save stored. + cleanup(); + const reloaded = await openRefusal(); + fireEvent.click(within(reloaded).getByText('plan_locked', { selector: 'span' })); + expect(within(reloaded).getByDisplayValue('The plan is locked while {{ state }}.')).toBeInTheDocument(); + expect(within(reloaded).getByText('state', { selector: 'span' })).toBeInTheDocument(); }); - it('renderer with a nested key-only record + tags row', async () => { - FORM.current = withReasons(); - render( - - - , - ); - fireEvent.click((await screen.findAllByRole('button', { name: 'Edit' }, { timeout: 8000 }))[0]); - fireEvent.click(await screen.findByText('CONTRACT_LOCKED')); - const group = screen.getByText('CONTRACT_LOCKED').closest('.rounded-md') as HTMLElement; - console.log('MEASURE3 labels:', JSON.stringify(Array.from(group.querySelectorAll('label')).map((l) => l.textContent))); - console.log('MEASURE3 has plan_locked:', !!screen.queryByText('plan_locked')); - console.log('MEASURE3 placeholders:', JSON.stringify(Array.from(group.querySelectorAll('input')).map((i) => [i.placeholder, i.value, i.id]))); - const ids = Array.from(document.querySelectorAll('[id]')).map((e) => e.id); - console.log('MEASURE3 dup ids:', JSON.stringify(ids.filter((x, i) => ids.indexOf(x) !== i))); + + it('a catalogue that uses reasons and params round-trips a Studio edit of another field unchanged', async () => { + stored = WITH_REASONS; + await openRefusal(); + fireEvent.change(document.getElementById('mdf-label') as HTMLInputElement, { target: { value: 'Sign the contract' } }); + const body = await save(); + expect(body).toEqual({ ...WITH_REASONS, label: 'Sign the contract' }); + }); + + it('CONTROL: a refusal with only message and status saves exactly as it was', async () => { + await openRefusal(); + fireEvent.change(document.getElementById('mdf-label') as HTMLInputElement, { target: { value: 'Sign the contract' } }); + const body = await save(); + expect(body).toEqual({ ...PLAIN, label: 'Sign the contract' }); + expect(Object.keys((body.refusals as Record).CONTRACT_LOCKED)).toEqual(['message', 'status']); }); }); From 8daba638621763cec93eb8121b6e71521b5eda3b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 09:29:22 +0000 Subject: [PATCH 3/8] chore: changeset for the hook form refusal reasons and params Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oQHgtkqYPCqstiKir --- .changeset/33657-hook-form-refusal-reasons-params.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 .changeset/33657-hook-form-refusal-reasons-params.md diff --git a/.changeset/33657-hook-form-refusal-reasons-params.md b/.changeset/33657-hook-form-refusal-reasons-params.md new file mode 100644 index 00000000000..3590141011e --- /dev/null +++ b/.changeset/33657-hook-form-refusal-reasons-params.md @@ -0,0 +1,12 @@ +--- +'@objectstack/spec': patch +--- + +feat(spec): the Studio hook form offers a refusal's `reasons` and `params` + +Clause-②: yes (widening) +Metadata-protocol: none + +The hook form (`hookForm`) lays out a refusal entry as `message`, `status`, `reasons` and `params`, so a Studio author can declare the several sentences under one code and the named params that a hook's refusal catalogue accepts. `reasons` is a record keyed by the snake_case reason the body throws beside the code, each `{ message }`; it takes the same key-only record control as the catalogue, and the reason key rule it checks is the one the served `HookSchema` declares. `params` is a name list. The entry's `message` help text now says a `{{ name }}` hole fills a declared param, where it said the sentence takes no placeholders. + +Nothing a metadata author can write changes: `reasons` and `params` were already accepted on a refusal entry; only the form now offers them. A catalogue that uses them already kept them through a Studio edit, and still does. A refusal with only `message` and `status` saves exactly as before. From 0b80932de395bf4b98ad034043a268e848ee3cb7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 09:44:51 +0000 Subject: [PATCH 4/8] i18n: translate the hook form's refusal reasons and params rows Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oQHgtkqYPCqstiKir --- .../translations/ar.metadata-forms.generated.ts | 14 +++++++++++++- .../translations/de.metadata-forms.generated.ts | 14 +++++++++++++- .../translations/en.metadata-forms.generated.ts | 14 +++++++++++++- .../translations/es-ES.metadata-forms.generated.ts | 14 +++++++++++++- .../translations/fr.metadata-forms.generated.ts | 14 +++++++++++++- .../translations/fr.source-hashes.generated.ts | 1 + .../translations/ja-JP.metadata-forms.generated.ts | 14 +++++++++++++- .../translations/ko.metadata-forms.generated.ts | 14 +++++++++++++- .../translations/pt-BR.metadata-forms.generated.ts | 14 +++++++++++++- .../translations/ru.metadata-forms.generated.ts | 14 +++++++++++++- .../translations/zh-CN.metadata-forms.generated.ts | 14 +++++++++++++- .../zh-Hant.metadata-forms.generated.ts | 14 +++++++++++++- .../views/metadata-admin/metadata-form-zh-cn.ts | 3 +++ 13 files changed, 147 insertions(+), 11 deletions(-) diff --git a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts index a7f1573b02c..7850a43b4ee 100644 --- a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts @@ -971,12 +971,24 @@ export const arMetadataForms: NonNullable = { }, "refusals.message": { label: "الرسالة", - helpText: "الجملة التي يقرؤها المستخدم عندما يرمي المتن هذا الرمز — نص عادي، بلا عناصر نائبة" + helpText: "الجملة التي يقرؤها المستخدم عندما يرمي المتن هذا الرمز. نص عادي، ما لم يُعلن الإدخال params: عندها يملأ العنصر النائب {{ name }} معاملًا مُعلنًا" }, "refusals.status": { label: "الحالة", helpText: "حالة HTTP للرفض (400–499). عند الغياب: 400" }, + "refusals.reasons": { + label: "الأسباب", + helpText: "جمل إضافية تحت الرمز نفسه، مفهرسة بالسبب بصيغة snake_case الذي يرميه المتن بجانب الرمز ({ code, reason }). يبقى الرمز والحالة المُرسَلان لهذا الإدخال؛ ويُرفض سبب غير مُعلن هنا. عند الغياب: لا يُقرأ السبب المرمي" + }, + "refusals.reasons.message": { + label: "الرسالة", + helpText: "الجملة التي يقرؤها المستخدم عندما يرمي المتن هذا السبب تحت الرمز. تتبع عناصرها النائبة {{ }} معاملات params للإدخال" + }, + "refusals.params": { + label: "المعاملات", + helpText: "الأسماء التي يمكن للجمل ملؤها (مثل state): يرمي المتن { code, params: { state } } ويعرض العنصر النائب {{ state }} قيمتها. عند الغياب: الجمل نص عادي" + }, handler: { label: "المعالج", helpText: "اسم دالة المعالج (مُهمَل — يُفضَّل `body`)" diff --git a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts index 3cb7566e621..aa73db0f1bc 100644 --- a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts @@ -971,12 +971,24 @@ export const deMetadataForms: NonNullable = { }, "refusals.message": { label: "Meldung", - helpText: "Der Satz, den der Benutzer liest, wenn der Rumpf diesen Code wirft – einfacher Text ohne Platzhalter" + helpText: "Der Satz, den der Benutzer liest, wenn der Rumpf diesen Code wirft. Einfacher Text, außer der Eintrag deklariert params: dann füllt ein Platzhalter {{ name }} einen deklarierten Parameter" }, "refusals.status": { label: "Status", helpText: "HTTP-Status der Ablehnung (400–499). Fehlt er: 400" }, + "refusals.reasons": { + label: "Gründe", + helpText: "Weitere Sätze unter demselben Code, nach dem snake_case-Grund, den der Rumpf neben dem Code wirft ({ code, reason }). Gesendeter Code und Status bleiben die dieses Eintrags; ein hier nicht deklarierter Grund wird abgelehnt. Fehlt er: Ein geworfener Grund wird nicht gelesen" + }, + "refusals.reasons.message": { + label: "Meldung", + helpText: "Der Satz, den der Benutzer liest, wenn der Rumpf diesen Grund unter dem Code wirft. Seine {{ }}-Platzhalter folgen den params des Eintrags" + }, + "refusals.params": { + label: "Parameter", + helpText: "Namen, die die Sätze füllen dürfen (z. B. state): Der Rumpf wirft { code, params: { state } }, und ein Platzhalter {{ state }} zeigt den Wert. Fehlt er: Die Sätze sind einfacher Text" + }, handler: { label: "Handler", helpText: "Name der Handler-Funktion (veraltet – besser `body`)" diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index 629f4f6c5c1..a3be994eb1f 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -971,12 +971,24 @@ export const enMetadataForms: NonNullable = { }, "refusals.message": { label: "Message", - helpText: "The sentence the user reads when the body throws this code — plain text, with no placeholders" + helpText: "The sentence the user reads when the body throws this code. Plain text, unless the entry declares params: then a {{ name }} hole fills a declared param" }, "refusals.status": { label: "Status", helpText: "HTTP status of the refusal (400–499). Absent: 400" }, + "refusals.reasons": { + label: "Reasons", + helpText: "Further sentences under this same code, keyed by the snake_case reason the body throws beside the code ({ code, reason }). The wire code and status stay this entry's; a reason not declared here is refused. Absent: a thrown reason is not read" + }, + "refusals.reasons.message": { + label: "Message", + helpText: "The sentence the user reads when the body throws this reason under the code. Its {{ }} holes follow the entry's params" + }, + "refusals.params": { + label: "Params", + helpText: "Names the sentences may fill (e.g. state): the body throws { code, params: { state } }, and a {{ state }} hole renders it. Absent: the sentences are plain text" + }, handler: { label: "Handler", helpText: "Handler function name (deprecated — prefer `body`)" diff --git a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts index 148bdc3ec4f..a8c4a72b543 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts @@ -971,12 +971,24 @@ export const esESMetadataForms: NonNullable = }, "refusals.message": { label: "Mensaje", - helpText: "La frase que lee el usuario cuando el cuerpo lanza este código — texto plano, sin marcadores" + helpText: "La frase que lee el usuario cuando el cuerpo lanza este código. Texto plano, salvo que la entrada declare params: entonces un marcador {{ name }} se rellena con un parámetro declarado" }, "refusals.status": { label: "Estado", helpText: "Estado HTTP del rechazo (400–499). Si se omite: 400" }, + "refusals.reasons": { + label: "Motivos", + helpText: "Más frases bajo este mismo código, indexadas por el motivo snake_case que el cuerpo lanza junto al código ({ code, reason }). El código y el estado que se envían siguen siendo los de esta entrada; se rechaza un motivo no declarado aquí. Si se omite: no se lee un motivo lanzado" + }, + "refusals.reasons.message": { + label: "Mensaje", + helpText: "La frase que lee el usuario cuando el cuerpo lanza este motivo bajo el código. Sus marcadores {{ }} siguen los params de la entrada" + }, + "refusals.params": { + label: "Parámetros", + helpText: "Nombres que las frases pueden rellenar (p. ej. state): el cuerpo lanza { code, params: { state } } y un marcador {{ state }} muestra su valor. Si se omite: las frases son texto plano" + }, handler: { label: "Manejador", helpText: "Nombre de función manejadora (obsoleto — preferir `body`)" diff --git a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts index d7f336f257e..64f5e67ce3b 100644 --- a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts @@ -971,12 +971,24 @@ export const frMetadataForms: NonNullable = { }, "refusals.message": { label: "Message", - helpText: "La phrase que lit l’utilisateur lorsque le corps lève ce code — texte brut, sans espaces réservés" + helpText: "La phrase que lit l’utilisateur lorsque le corps lève ce code. Texte brut, sauf si l’entrée déclare des params : un espace réservé {{ name }} reçoit alors un paramètre déclaré" }, "refusals.status": { label: "Statut", helpText: "Statut HTTP du refus (400–499). Absent : 400" }, + "refusals.reasons": { + label: "Motifs", + helpText: "D’autres phrases sous ce même code, indexées par le motif snake_case que le corps lève avec le code ({ code, reason }). Le code et le statut transmis restent ceux de cette entrée ; un motif non déclaré ici est refusé. Absent : un motif levé n’est pas lu" + }, + "refusals.reasons.message": { + label: "Message", + helpText: "La phrase que lit l’utilisateur lorsque le corps lève ce motif sous ce code. Ses espaces réservés {{ }} suivent les params de l’entrée" + }, + "refusals.params": { + label: "Paramètres", + helpText: "Les noms que les phrases peuvent remplir (par ex. state) : le corps lève { code, params: { state } }, et un espace réservé {{ state }} en affiche la valeur. Absent : les phrases sont du texte brut" + }, handler: { label: "Gestionnaire", helpText: "Nom de la fonction de gestion (obsolète — préférez `body`)" diff --git a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts index ad1a675472e..7806b6bde62 100644 --- a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts @@ -65,6 +65,7 @@ export const frGeneratedSourceHashes: Readonly> = { "metadataForms.hook.fields.condition.label": "bfcca3fe6f93b90c", "metadataForms.hook.fields.description.label": "779a4342c8eb6707", "metadataForms.hook.fields.refusals.message.label": "2af15199795c25b9", + "metadataForms.hook.fields.refusals.reasons.message.label": "2af15199795c25b9", "metadataForms.hook.label": "248bb1cdc692252d", "metadataForms.object.fields.description.label": "779a4342c8eb6707", "metadataForms.object.fields.fields.description.label": "779a4342c8eb6707", diff --git a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts index e1522536768..7eb6aed7a01 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts @@ -971,12 +971,24 @@ export const jaJPMetadataForms: NonNullable = }, "refusals.message": { label: "メッセージ", - helpText: "本体がこのコードをスローしたときにユーザーが読む文 — プレーンテキスト、プレースホルダーなし" + helpText: "本体がこのコードをスローしたときにユーザーが読む文。プレーンテキスト。ただしエントリが params を宣言している場合、{{ name }} プレースホルダーに宣言済みのパラメーターが入ります" }, "refusals.status": { label: "ステータス", helpText: "拒否の HTTP ステータス(400–499)。未指定: 400" }, + "refusals.reasons": { + label: "理由", + helpText: "同じコードの下に置く追加の文。本体がコードと一緒にスローする snake_case の理由({ code, reason })をキーとします。送信されるコードとステータスはこのエントリのものです。ここで宣言されていない理由は拒否されます。未指定: スローされた理由は読まれません" + }, + "refusals.reasons.message": { + label: "メッセージ", + helpText: "本体がこのコードの下でこの理由をスローしたときにユーザーが読む文。{{ }} プレースホルダーはエントリの params に従います" + }, + "refusals.params": { + label: "パラメーター", + helpText: "文に埋め込める名前(例: state)。本体が { code, params: { state } } をスローすると、{{ state }} プレースホルダーにその値が表示されます。未指定: 文はプレーンテキストです" + }, handler: { label: "ハンドラー", helpText: "ハンドラー関数名(非推奨 — `body` を推奨)" diff --git a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts index 10d20a4e798..ac0e05e3574 100644 --- a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts @@ -971,12 +971,24 @@ export const koMetadataForms: NonNullable = { }, "refusals.message": { label: "메시지", - helpText: "본문이 이 코드를 던질 때 사용자가 읽는 문장으로, 자리 표시자가 없는 일반 텍스트입니다" + helpText: "본문이 이 코드를 던질 때 사용자가 읽는 문장입니다. 일반 텍스트이며, 항목이 params를 선언하면 {{ name }} 자리 표시자에 선언된 매개변수가 채워집니다" }, "refusals.status": { label: "상태", helpText: "거부의 HTTP 상태(400–499)입니다. 없으면 400" }, + "refusals.reasons": { + label: "사유", + helpText: "같은 코드 아래의 추가 문장으로, 본문이 코드와 함께 던지는 snake_case 사유({ code, reason })를 키로 합니다. 전송되는 코드와 상태는 이 항목의 것을 따릅니다. 여기에 선언되지 않은 사유는 거부됩니다. 없으면 던진 사유를 읽지 않습니다" + }, + "refusals.reasons.message": { + label: "메시지", + helpText: "본문이 이 코드 아래에서 이 사유를 던질 때 사용자가 읽는 문장입니다. {{ }} 자리 표시자는 항목의 params를 따릅니다" + }, + "refusals.params": { + label: "매개변수", + helpText: "문장에 채울 수 있는 이름(예: state)입니다. 본문이 { code, params: { state } }를 던지면 {{ state }} 자리 표시자에 그 값이 표시됩니다. 없으면 문장은 일반 텍스트입니다" + }, handler: { label: "핸들러", helpText: "핸들러 함수 이름(사용 중단, `body` 권장)" diff --git a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts index 79c78e646f2..37d055c596b 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts @@ -971,12 +971,24 @@ export const ptBRMetadataForms: NonNullable = }, "refusals.message": { label: "Mensagem", - helpText: "A frase que o usuário lê quando o corpo lança este código — texto simples, sem marcadores" + helpText: "A frase que o usuário lê quando o corpo lança este código. Texto simples, a menos que a entrada declare params: então um marcador {{ name }} é preenchido com um parâmetro declarado" }, "refusals.status": { label: "Status", helpText: "Status HTTP da recusa (400–499). Ausente: 400" }, + "refusals.reasons": { + label: "Motivos", + helpText: "Outras frases sob este mesmo código, indexadas pelo motivo snake_case que o corpo lança junto com o código ({ code, reason }). O código e o status enviados continuam sendo os desta entrada; um motivo não declarado aqui é recusado. Ausente: um motivo lançado não é lido" + }, + "refusals.reasons.message": { + label: "Mensagem", + helpText: "A frase que o usuário lê quando o corpo lança este motivo sob o código. Seus marcadores {{ }} seguem os params da entrada" + }, + "refusals.params": { + label: "Parâmetros", + helpText: "Nomes que as frases podem preencher (por exemplo state): o corpo lança { code, params: { state } } e um marcador {{ state }} mostra o valor. Ausente: as frases são texto simples" + }, handler: { label: "Handler", helpText: "Nome da função handler (obsoleto — prefira `body`)" diff --git a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts index c86a9d28472..b504aecc186 100644 --- a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts @@ -971,12 +971,24 @@ export const ruMetadataForms: NonNullable = { }, "refusals.message": { label: "Сообщение", - helpText: "Фраза, которую видит пользователь, когда тело выбрасывает этот код, — простой текст без заполнителей" + helpText: "Фраза, которую видит пользователь, когда тело выбрасывает этот код. Простой текст, если запись не объявляет params: тогда заполнитель {{ name }} подставляет объявленный параметр" }, "refusals.status": { label: "Статус", helpText: "HTTP-статус отказа (400–499). Если отсутствует: 400" }, + "refusals.reasons": { + label: "Причины", + helpText: "Дополнительные фразы под тем же кодом с ключами — причинами в snake_case, которые тело выбрасывает вместе с кодом ({ code, reason }). Передаваемые код и статус остаются от этой записи; причина, не объявленная здесь, отклоняется. Если отсутствует: выброшенная причина не читается" + }, + "refusals.reasons.message": { + label: "Сообщение", + helpText: "Фраза, которую видит пользователь, когда тело выбрасывает эту причину под этим кодом. Её заполнители {{ }} следуют params записи" + }, + "refusals.params": { + label: "Параметры", + helpText: "Имена, которые могут заполнять фразы (например, state): тело выбрасывает { code, params: { state } }, и заполнитель {{ state }} показывает значение. Если отсутствует: фразы — простой текст" + }, handler: { label: "Обработчик", helpText: "Имя функции-обработчика (устарело — используйте `body`)" diff --git a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts index 6d38daaf247..38da08d7c02 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts @@ -971,12 +971,24 @@ export const zhCNMetadataForms: NonNullable = }, "refusals.message": { label: "提示语", - helpText: "正文抛出此错误码时用户读到的句子——纯文本,不含占位符" + helpText: "正文抛出此错误码时用户读到的句子。纯文本;若该条目声明了参数,则 {{ name }} 占位符填入一个已声明的参数" }, "refusals.status": { label: "状态码", helpText: "拒绝的 HTTP 状态码(400–499)。不填:400" }, + "refusals.reasons": { + label: "原因", + helpText: "同一错误码下的更多句子,以正文在错误码旁抛出的 snake_case 原因为键({ code, reason })。线上的错误码和状态码仍取本条目的;未在此声明的原因会被拒绝。不填:抛出的原因不被读取" + }, + "refusals.reasons.message": { + label: "提示语", + helpText: "正文在此错误码下抛出此原因时用户读到的句子。其中的 {{ }} 占位符遵循本条目的参数" + }, + "refusals.params": { + label: "参数", + helpText: "句子可填入的名称(例如 state):正文抛出 { code, params: { state } },{{ state }} 占位符即显示该值。不填:句子为纯文本" + }, handler: { label: "处理器", helpText: "处理器函数名(已废弃——建议使用 body)" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts index 44b79162193..d4fb5e947eb 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts @@ -971,12 +971,24 @@ export const zhHantMetadataForms: NonNullable }, "refusals.message": { label: "提示語", - helpText: "內文丟擲此錯誤碼時使用者讀到的句子——純文字,不含預留位置" + helpText: "內文丟擲此錯誤碼時使用者讀到的句子。純文字;若該條目宣告了參數,則 {{ name }} 預留位置填入一個已宣告的參數" }, "refusals.status": { label: "狀態碼", helpText: "拒絕的 HTTP 狀態碼(400–499)。不填:400" }, + "refusals.reasons": { + label: "原因", + helpText: "同一錯誤碼下的更多句子,以內文在錯誤碼旁丟擲的 snake_case 原因為鍵({ code, reason })。線上的錯誤碼和狀態碼仍取本條目的;未在此宣告的原因會被拒絕。不填:丟擲的原因不被讀取" + }, + "refusals.reasons.message": { + label: "提示語", + helpText: "內文在此錯誤碼下丟擲此原因時使用者讀到的句子。其中的 {{ }} 預留位置遵循本條目的參數" + }, + "refusals.params": { + label: "參數", + helpText: "句子可填入的名稱(例如 state):內文丟擲 { code, params: { state } },{{ state }} 預留位置即顯示該值。不填:句子為純文字" + }, handler: { label: "處理器", helpText: "處理器函式名(已廢棄——建議使用 body)" diff --git a/ui/packages/app-shell/src/views/metadata-admin/metadata-form-zh-cn.ts b/ui/packages/app-shell/src/views/metadata-admin/metadata-form-zh-cn.ts index 268b3a00d43..c6505a1e802 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/metadata-form-zh-cn.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/metadata-form-zh-cn.ts @@ -280,6 +280,9 @@ export const ZH_CN_SPEC_FORMS: NonNullable = { refusals: { label: '拒绝目录' }, 'refusals.message': { label: '提示语' }, 'refusals.status': { label: '状态码' }, + 'refusals.reasons': { label: '原因' }, + 'refusals.reasons.message': { label: '提示语' }, + 'refusals.params': { label: '参数' }, handler: { label: '处理器' }, async: { label: '异步' }, onError: { label: '错误处理' }, From 5bae050b8e6f11efa3a0fb2686cc028ad1589c14 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 09:45:47 +0000 Subject: [PATCH 5/8] chore: changeset names the translated bundles and the console labels Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oQHgtkqYPCqstiKir --- .changeset/33657-hook-form-refusal-reasons-params.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.changeset/33657-hook-form-refusal-reasons-params.md b/.changeset/33657-hook-form-refusal-reasons-params.md index 3590141011e..1bc31339194 100644 --- a/.changeset/33657-hook-form-refusal-reasons-params.md +++ b/.changeset/33657-hook-form-refusal-reasons-params.md @@ -1,5 +1,8 @@ --- '@objectstack/spec': patch +'@objectstack/platform-objects': patch +'@object-ui/app-shell': patch +'@object-ui/console': patch --- feat(spec): the Studio hook form offers a refusal's `reasons` and `params` @@ -7,6 +10,6 @@ feat(spec): the Studio hook form offers a refusal's `reasons` and `params` Clause-②: yes (widening) Metadata-protocol: none -The hook form (`hookForm`) lays out a refusal entry as `message`, `status`, `reasons` and `params`, so a Studio author can declare the several sentences under one code and the named params that a hook's refusal catalogue accepts. `reasons` is a record keyed by the snake_case reason the body throws beside the code, each `{ message }`; it takes the same key-only record control as the catalogue, and the reason key rule it checks is the one the served `HookSchema` declares. `params` is a name list. The entry's `message` help text now says a `{{ name }}` hole fills a declared param, where it said the sentence takes no placeholders. +The hook form (`hookForm`) lays out a refusal entry as `message`, `status`, `reasons` and `params`, so a Studio author can declare the several sentences under one code and the named params that a hook's refusal catalogue accepts. `reasons` is a record keyed by the snake_case reason the body throws beside the code, each `{ message }`; it takes the same key-only record control as the catalogue, and the reason key rule it checks is the one the served `HookSchema` declares. `params` is a name list. The entry's `message` help text now says a `{{ name }}` hole fills a declared param, where it said the sentence takes no placeholders. The three new rows and the changed help text are translated in the ten locales of the platform's metadata-form bundles (`@objectstack/platform-objects`), and the console's zh-CN form labels (`@object-ui/app-shell`, shipped in `@object-ui/console`) name the three rows for the Pending changes sheet. Nothing a metadata author can write changes: `reasons` and `params` were already accepted on a refusal entry; only the form now offers them. A catalogue that uses them already kept them through a Studio edit, and still does. A refusal with only `message` and `status` saves exactly as before. From e76449765bf49fab208251381f4e5804d7cd6d72 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 09:57:51 +0000 Subject: [PATCH 6/8] test: the hook form's three new refusal rows move the panel census counts Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oQHgtkqYPCqstiKir --- .../action-body-panel-echo-decisions.test.ts | 9 +++++++-- .../hook-execution-panel-echo-decisions.test.ts | 6 ++++-- .../object-lifecycle-panel-echo-decisions.test.ts | 5 ++++- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/packages/platform-objects/src/apps/translations/action-body-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/action-body-panel-echo-decisions.test.ts index c13467bb158..28836024b59 100644 --- a/packages/platform-objects/src/apps/translations/action-body-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/action-body-panel-echo-decisions.test.ts @@ -703,14 +703,19 @@ describe('#19403 round 5 — the blind spot, FIFTH shape: one schema, two forms, // and CORRECT — `hookForm` enumerates no repeater at all — while seven // children sit enumerated and outside it. // 9 since #26835: the hook form offers the `refusals` record, whose two - // entry fields (`message`, `status`) are enumerated the same way. + // entry fields (`message`, `status`) are enumerated the same way. 12 since + // #33657: the entry also offers `reasons` (a record of `{ message }`) and + // `params`, three more enumerated children. expect(HOOK_ENUMERATED.covered.length, 'hookForm enumerates no repeater row properties').toBe(0); - expect(HOOK_ENUMERATED.skipped.length).toBe(9); + expect(HOOK_ENUMERATED.skipped.length).toBe(12); for (const child of SHARED_BODY_CHILDREN) expect(HOOK_ENUMERATED.skipped).toContain(`body.${child}`); expect(HOOK_ENUMERATED.skipped).toContain('retryPolicy.maxRetries'); expect(HOOK_ENUMERATED.skipped).toContain('retryPolicy.backoffMs'); expect(HOOK_ENUMERATED.skipped).toContain('refusals.message'); expect(HOOK_ENUMERATED.skipped).toContain('refusals.status'); + expect(HOOK_ENUMERATED.skipped).toContain('refusals.reasons'); + expect(HOOK_ENUMERATED.skipped).toContain('refusals.reasons.message'); + expect(HOOK_ENUMERATED.skipped).toContain('refusals.params'); // // ⇒ one composite, two forms, two different greens: a lit control that // passes on a sibling repeater, and a dark control that is right about diff --git a/packages/platform-objects/src/apps/translations/hook-execution-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/hook-execution-panel-echo-decisions.test.ts index f5a07ca0b6b..a16a1620b59 100644 --- a/packages/platform-objects/src/apps/translations/hook-execution-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/hook-execution-panel-echo-decisions.test.ts @@ -783,9 +783,11 @@ describe('#19403 round 6 — the composite blind spot, hook side, CLOSED', () => // `hookForm` enumerates no repeater at all, so `repeater-row-properties.test.ts` // is blind here through a DARK control that is TRUE and CORRECT — the shape // round 5 wrote down. Seven children sit enumerated and outside it — 9 - // since #26835, when the `refusals` record's `message` / `status` joined. + // since #26835, when the `refusals` record's `message` / `status` joined, + // and 12 since #33657, when its `reasons` (with `reasons.message`) and + // `params` joined. expect(HOOK_ENUMERATED.covered.length, 'hookForm enumerates no repeater row properties').toBe(0); - expect(HOOK_ENUMERATED.skipped.length).toBe(9); + expect(HOOK_ENUMERATED.skipped.length).toBe(12); for (const child of SHARED_BODY_CHILDREN) expect(HOOK_ENUMERATED.skipped).toContain(`body.${child}`); expect(HOOK_ENUMERATED.skipped).toContain('retryPolicy.maxRetries'); expect(HOOK_ENUMERATED.skipped).toContain('retryPolicy.backoffMs'); diff --git a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts index 894b48a434c..b6691bf30e5 100644 --- a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts @@ -1283,7 +1283,10 @@ describe('#19403 round 10 — the verdicts, on the live bundles', () => { // offers `writeRequiresMasterRead` (ADR-0055 §3 as amended: read on the // master is enough to write) — one row label, authored in all three // locales. - expect(translated.length, `${locale} positive control`).toBe(738); + // 741 since #33657: the hook form's refusal entry offers `reasons` (with + // its `message`) and `params` — three row labels, authored in all three + // locales. + expect(translated.length, `${locale} positive control`).toBe(741); } // ⭐ DARK — the blindness, executable. On a synthetic two-locale catalog the // all-three predicate returns 0 while the per-locale one returns 1, so the From 2238c90f43bd2269dcd2b1dbabfda56d5d515af3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 10:20:33 +0000 Subject: [PATCH 7/8] test: load the CEL engines at module top in the key-only record test Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oQHgtkqYPCqstiKir --- .../metadata-admin/SchemaForm.keyOnlyRecord-26835.test.tsx | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.keyOnlyRecord-26835.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.keyOnlyRecord-26835.test.tsx index 6d5609e2a79..4590df26ee5 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.keyOnlyRecord-26835.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.keyOnlyRecord-26835.test.tsx @@ -29,6 +29,11 @@ import { HOOK_REFUSAL_REASON_PATTERN, } from '@objectstack/spec/data'; import { SchemaForm, KEY_ONLY_RECORD_WIDGET } from './SchemaForm'; +// Module-scope loads of the engines the form reaches through dynamic `import()` +// (the condition widget's CEL authoring), per AGENTS.md's flaky-test rule: the +// first load is paid during collection, never inside a clocked window. +import '@objectstack/formula'; +import '@objectstack/lint'; afterEach(cleanup); From d3ff3bdbe9d993dc085875193bacc72c9e187724 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 11:30:43 +0000 Subject: [PATCH 8/8] fix: an optional record row is written absent when its last entry is removed Removing the last entry of a record row emitted `{}`, which the form kept. An empty map and an absent key draw the same empty list but read apart: an entry's `reasons: {}` refuses every thrown reason, an absent one ignores it; a hook's `refusals: {}` refuses every thrown code, an absent one leaves the throws as they were. An optional row now writes the key absent through the form's clear convention; a required row keeps `{}`. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oQHgtkqYPCqstiKir --- .../33657-hook-form-refusal-reasons-params.md | 2 + ...EditPage.hookRefusalReasons-33657.test.tsx | 63 +++++++++++++++++++ .../SchemaForm.keyOnlyRecord-26835.test.tsx | 17 +++++ .../src/views/metadata-admin/SchemaForm.tsx | 16 ++++- 4 files changed, 97 insertions(+), 1 deletion(-) diff --git a/.changeset/33657-hook-form-refusal-reasons-params.md b/.changeset/33657-hook-form-refusal-reasons-params.md index 1bc31339194..feef4f0c9d3 100644 --- a/.changeset/33657-hook-form-refusal-reasons-params.md +++ b/.changeset/33657-hook-form-refusal-reasons-params.md @@ -13,3 +13,5 @@ Metadata-protocol: none The hook form (`hookForm`) lays out a refusal entry as `message`, `status`, `reasons` and `params`, so a Studio author can declare the several sentences under one code and the named params that a hook's refusal catalogue accepts. `reasons` is a record keyed by the snake_case reason the body throws beside the code, each `{ message }`; it takes the same key-only record control as the catalogue, and the reason key rule it checks is the one the served `HookSchema` declares. `params` is a name list. The entry's `message` help text now says a `{{ name }}` hole fills a declared param, where it said the sentence takes no placeholders. The three new rows and the changed help text are translated in the ten locales of the platform's metadata-form bundles (`@objectstack/platform-objects`), and the console's zh-CN form labels (`@object-ui/app-shell`, shipped in `@object-ui/console`) name the three rows for the Pending changes sheet. Nothing a metadata author can write changes: `reasons` and `params` were already accepted on a refusal entry; only the form now offers them. A catalogue that uses them already kept them through a Studio edit, and still does. A refusal with only `message` and `status` saves exactly as before. + +In the metadata form (`@object-ui/app-shell`), removing the last entry of an optional record row now leaves the key absent rather than writing `{}`. The two read differently, though both draw the same empty list: an entry's `reasons: {}` refuses every reason the body throws under that code, where an absent `reasons` does not read the thrown reason; and a hook's `refusals: {}` refuses every code its body throws, where an absent catalogue leaves its throws as they were. A required record row, such as an object's `fields`, keeps `{}` as before. diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.hookRefusalReasons-33657.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.hookRefusalReasons-33657.test.tsx index d204ecd117b..ef75c97eab1 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.hookRefusalReasons-33657.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.hookRefusalReasons-33657.test.tsx @@ -156,6 +156,11 @@ async function save(): Promise> { return JSON.parse(JSON.stringify(mockClient.save.mock.calls[0]![2])) as Record; } +/** The card of one reason inside a refusal entry's card. */ +function reasonCard(entry: HTMLElement, reason: string): HTMLElement { + return within(entry).getByText(reason, { selector: 'span' }).closest('.rounded-md') as HTMLElement; +} + describe('the Studio hook editor authors a refusal\'s reasons and params (objectstack#33657)', () => { it('offers Reasons and Params on a refusal entry, beside Message and Status', async () => { const card = await openRefusal(); @@ -202,6 +207,64 @@ describe('the Studio hook editor authors a refusal\'s reasons and params (object expect(body).toEqual({ ...WITH_REASONS, label: 'Sign the contract' }); }); + // An empty `reasons` is not an absent one: under `reasons: {}` every reason + // the body throws is refused (at save when literal, at run time otherwise), + // while an absent `reasons` does not read a thrown reason at all. Both draw + // the same empty list, so removing the last reason must leave it absent. + it('removing the only reason leaves the entry with no reasons, not an empty one', async () => { + const card = await openRefusal(); + fireEvent.change(within(card).getByPlaceholderText('Key'), { target: { value: 'plan_locked' } }); + fireEvent.click(within(card).getByRole('button', { name: 'Add' })); + fireEvent.click(within(reasonCard(card, 'plan_locked')).getByRole('button', { name: 'Remove' })); + // Add-then-remove alone returns the draft to what is stored, so the page + // has nothing to save; an edit elsewhere makes the save happen. + fireEvent.change(document.getElementById('mdf-label') as HTMLInputElement, { target: { value: 'Sign the contract' } }); + + const body = await save(); + expect(body.refusals).toEqual({ CONTRACT_LOCKED: { message: 'This contract is locked.', status: 409 } }); + expect(Object.keys((body.refusals as Record).CONTRACT_LOCKED)).toEqual(['message', 'status']); + }); + + it('removing the last stored reason leaves reasons absent too', async () => { + stored = WITH_REASONS; + const card = await openRefusal(); + fireEvent.click(within(reasonCard(card, 'plan_locked')).getByRole('button', { name: 'Remove' })); + + const body = await save(); + const { reasons: _dropped, ...rest } = WITH_REASONS.refusals.CONTRACT_LOCKED; + expect(body.refusals).toEqual({ CONTRACT_LOCKED: rest }); + }); + + it('CONTROL: removing one of two reasons stores the other, as before', async () => { + stored = WITH_REASONS; + const card = await openRefusal(); + fireEvent.change(within(card).getByPlaceholderText('Key'), { target: { value: 'plan_archived' } }); + fireEvent.click(within(card).getByRole('button', { name: 'Add' })); + fireEvent.change(within(reasonCard(card, 'plan_archived')).getByLabelText(/Message/), { + target: { value: 'The plan is archived.' }, + }); + fireEvent.click(within(reasonCard(card, 'plan_locked')).getByRole('button', { name: 'Remove' })); + + const body = await save(); + expect(body.refusals).toEqual({ + CONTRACT_LOCKED: { + ...WITH_REASONS.refusals.CONTRACT_LOCKED, + reasons: { plan_archived: { message: 'The plan is archived.' } }, + }, + }); + }); + + // The same rule one level up: `refusals: {}` declares a catalogue with no + // codes (every code the body throws is refused), an absent one leaves the + // hook's throws answered as they always were. + it('removing the only refusal code leaves the hook with no catalogue, not an empty one', async () => { + const card = await openRefusal(); + fireEvent.click(within(card).getAllByRole('button', { name: 'Remove' })[0]!); + + const body = await save(); + expect(body).not.toHaveProperty('refusals'); + }); + it('CONTROL: a refusal with only message and status saves exactly as it was', async () => { await openRefusal(); fireEvent.change(document.getElementById('mdf-label') as HTMLInputElement, { target: { value: 'Sign the contract' } }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.keyOnlyRecord-26835.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.keyOnlyRecord-26835.test.tsx index 4590df26ee5..0bf39bf5500 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.keyOnlyRecord-26835.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.keyOnlyRecord-26835.test.tsx @@ -310,3 +310,20 @@ describe('a refusal entry offers `reasons` and `params` (objectstack#33657)', () expect(within(card).getByText('state', { selector: 'span' })).toBeInTheDocument(); }); }); + +describe('removing the last entry of a record row (objectstack#33657)', () => { + const ONE_CODE = { ...HOOK_BASE, refusals: { CONTRACT_LOCKED: { message: 'This contract is locked.' } } }; + + it('an optional row is written absent, not as an empty map', () => { + const sink = renderHook(refusalsRow(), ONE_CODE); + fireEvent.click(within(entryCard('CONTRACT_LOCKED')).getByRole('button', { name: 'Remove' })); + expect(sink.value).not.toHaveProperty('refusals'); + expect(HookSchema.safeParse(sink.value).success).toBe(true); + }); + + it('CONTROL: a required row keeps the empty map, as before', () => { + const sink = renderHook({ ...refusalsRow(), required: true } as FormRow, ONE_CODE); + fireEvent.click(within(entryCard('CONTRACT_LOCKED')).getByRole('button', { name: 'Remove' })); + expect(sink.value.refusals).toEqual({}); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.tsx b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.tsx index 48ac94ede5d..edfccccb225 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.tsx @@ -2295,6 +2295,7 @@ function FieldControl({ value={value} fields={fields} schema={schema} + offerUnset={offerUnset} readOnly={readOnly} widgetContext={widgetContext} widget={fieldSpec?.widget} @@ -3120,6 +3121,7 @@ function RecordField({ value, fields, schema, + offerUnset, readOnly, widgetContext, widget, @@ -3132,6 +3134,17 @@ function RecordField({ value: unknown; fields: Array; schema: JsonSchema; + /** + * The key is OPTIONAL (`FieldControl`'s `offerUnset`): removing its last + * entry writes it ABSENT, through the form's clear convention + * (`onChange(undefined)`), not as `{}`. An empty map and an absent one draw + * the same empty list, yet a key may read them apart — a hook's + * `refusals: {}` refuses every code its body throws while an absent one + * leaves its throws as they were; an entry's `reasons: {}` refuses every + * thrown reason while an absent one does not read it (objectstack#33657). + * A required key keeps `{}`: it has no absent state. + */ + offerUnset?: boolean; readOnly?: boolean; widgetContext?: WidgetContext; widget?: string; @@ -3218,7 +3231,8 @@ function RecordField({ const entries = Object.entries(record); const specs = fields.map(normaliseField).filter((s) => s.field !== keyProp); - const emit = (next: Record>) => onChange(next); + const emit = (next: Record>) => + onChange(offerUnset && Object.keys(next).length === 0 ? undefined : next); const updateItem = (key: string, patch: Record) => { const next: Record> = {};