diff --git a/.changeset/34215-failure-toast-row-user-message.md b/.changeset/34215-failure-toast-row-user-message.md new file mode 100644 index 00000000000..f0458df1498 --- /dev/null +++ b/.changeset/34215-failure-toast-row-user-message.md @@ -0,0 +1,13 @@ +--- +'@object-ui/core': patch +'@object-ui/plugin-grid': patch +--- + +fix(core, plugin-grid): an action's failure toast and a per-record bulk run's failed row show the handler's userMessage + +Clause-②: no +Metadata-protocol: none + +A handler that refuses with a `userMessage` (the text it wrote for the user, already in the request's locale) now has those words shown where a single action reports its failure. The failure toast of `ActionRunner` (`@object-ui/core`) shows the action's authored `errorMessage` when it declares one, else the refusal's `userMessage`, else the error's own message; before, it went straight from `errorMessage` to the platform's error text. An action that sets `errorMessage` keeps its text. + +The per-record bulk run (`bulkActions: ['NAME']`, `@object-ui/plugin-grid`) lists each failed record with its refusal's `userMessage` when the handler threw one, else the error's message, as the aggregate run already does for its one outcome. The error CSV keeps each failure's whole message. A blank `userMessage` is no marking and changes nothing. diff --git a/content/docs/ui/actions.mdx b/content/docs/ui/actions.mdx index 0c049dcabc8..00461226ab1 100644 --- a/content/docs/ui/actions.mdx +++ b/content/docs/ui/actions.mdx @@ -391,7 +391,10 @@ strict params gate admits either bag without a word. answer names, else `successMessage`, else a generic "Action completed successfully". A `message` in the server's answer is shown only when the copy asks for it (`{{ result.message }}`). Post-success navigation is - `onSuccess: { navigate, openIn }`. + `onSuccess: { navigate, openIn }`. A failure toast shows `errorMessage` when + the action declares one, else the refusal's `userMessage` when the handler + threw one (the text it wrote for the user, in the request's locale), else + the error's own message. - **`undoable`** — on a single-record update, the success toast offers an **Undo** that restores the record's prior field values (`Ctrl+Z` works too). The runtime only captures the prior values when this flag is set, so an diff --git a/content/docs/ui/views.mdx b/content/docs/ui/views.mdx index 1f8781869e1..a7146ad0c4f 100644 --- a/content/docs/ui/views.mdx +++ b/content/docs/ui/views.mdx @@ -271,6 +271,10 @@ list re-reads its rows, whether the action resolved or rejected, so a record the handler changed shows its current value; the selection stays after a rejection, ready for a re-run. +A per-record run reports each record on its own: the result dialog lists every +failed record with its refusal's `userMessage` when the handler threw one, else +the error's message, and the error CSV keeps each failure's whole message. + **Pick the right key for the dispatch you mean.** Per-record is `bulkActions: ['']` — the bare-string form, which has nowhere to carry a flag and is promoted with the action's own label, params and `visible`. diff --git a/ui/packages/core/src/actions/ActionRunner.ts b/ui/packages/core/src/actions/ActionRunner.ts index 65fd8f07a55..a1964f8ff73 100644 --- a/ui/packages/core/src/actions/ActionRunner.ts +++ b/ui/packages/core/src/actions/ActionRunner.ts @@ -2241,8 +2241,18 @@ export class ActionRunner { // An authored `errorMessage` is shown as written — a string, or the // `template` envelope's `source` (objectui#13367); no scope is declared // for its holes yet. An envelope with no text falls to the error. + // Between the two sits the refusal's producer-marked `userMessage` + // (objectstack#34215): the handler's words for the user, shown in + // place of the platform's `error` text. An authored `errorMessage` + // still wins — the spec declares it the override of the raw error, + // and an action that sets it keeps the text its author wrote. + // Presence is the marking: a blank value is no marking (the predicate + // `declaredUserMessage` and `@objectstack/client` apply). const authored = actionCopySource(action.errorMessage); - const raw: unknown = authored || result.error; + const declared = typeof result.userMessage === 'string' && result.userMessage.trim() + ? result.userMessage + : undefined; + const raw: unknown = authored || declared || result.error; const message = typeof raw === 'string' ? raw : (raw && typeof (raw as { message?: unknown }).message === 'string') diff --git a/ui/packages/core/src/actions/__tests__/ActionRunner.test.ts b/ui/packages/core/src/actions/__tests__/ActionRunner.test.ts index a6fac418d1d..a72dafa5280 100644 --- a/ui/packages/core/src/actions/__tests__/ActionRunner.test.ts +++ b/ui/packages/core/src/actions/__tests__/ActionRunner.test.ts @@ -13,6 +13,7 @@ import { type ActionDef, type ActionContext, } from '../ActionRunner'; +import { createServerActionHandler } from '../serverActionHandler'; describe('ActionRunner', () => { let runner: ActionRunner; @@ -1135,3 +1136,70 @@ describe('ActionRunner', () => { }); }); }); + +/** + * The failure toast speaks the handler's words (objectstack#34215): a refusal's + * producer-marked `userMessage` (`ActionResult.userMessage`) is shown in place + * of the platform's `error` text. An authored `errorMessage` stays first — the + * spec declares it the override of the raw error. + */ +describe('the failure toast shows the refusal\'s userMessage (objectstack#34215)', () => { + const USER_TEXT = 'Plan B is Closed Won and was not moved.'; + const PLATFORM_TEXT = 'mass_update_stage: plan_b stage is closed_won'; + let runner: ActionRunner; + let toast: Mock; + + beforeEach(() => { + runner = new ActionRunner(); + toast = vi.fn(); + runner.setToastHandler(toast); + }); + + const refuseWith = (extra: Record) => + runner.registerHandler('script', async () => ({ success: false, error: PLATFORM_TEXT, ...extra })); + + const errorToast = () => { + expect(toast).toHaveBeenCalledTimes(1); + expect(toast.mock.calls[0][1]).toMatchObject({ type: 'error' }); + return toast.mock.calls[0][0]; + }; + + it('shows the userMessage of a refusal that carries one', async () => { + refuseWith({ userMessage: USER_TEXT }); + await runner.execute({ type: 'script', name: 'mass_update_stage' }); + expect(errorToast()).toBe(USER_TEXT); + }); + + it('carries it from the /actions door: the server action handler\'s refusal reaches the toast', async () => { + const fetchRefusal = vi.fn(async () => ({ + ok: false, + status: 400, + json: async () => ({ + success: false, + error: { code: 'HOOK_ABORTED', httpStatus: 400, message: PLATFORM_TEXT, userMessage: USER_TEXT }, + }), + })); + runner.registerHandler('script', createServerActionHandler({ fetch: fetchRefusal as any, baseUrl: '' })); + await runner.execute({ type: 'script', name: 'mass_update_stage', objectName: 'opportunity' } as ActionDef); + expect(fetchRefusal).toHaveBeenCalledTimes(1); + expect(errorToast()).toBe(USER_TEXT); + }); + + it('CONTROL: a refusal without a userMessage keeps the error', async () => { + refuseWith({}); + await runner.execute({ type: 'script', name: 'mass_update_stage' }); + expect(errorToast()).toBe(PLATFORM_TEXT); + }); + + it('a blank userMessage is no marking: the error is shown', async () => { + refuseWith({ userMessage: ' ' }); + await runner.execute({ type: 'script', name: 'mass_update_stage' }); + expect(errorToast()).toBe(PLATFORM_TEXT); + }); + + it('an authored errorMessage keeps its text even when the refusal carries a userMessage', async () => { + refuseWith({ userMessage: USER_TEXT }); + await runner.execute({ type: 'script', name: 'mass_update_stage', errorMessage: 'Stage update failed' }); + expect(errorToast()).toBe('Stage update failed'); + }); +}); diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index a4af40e0efd..9b41859a0b4 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -2183,8 +2183,12 @@ export const ObjectGrid: React.FC = ({ } as any); // Reject so the executor records this row under its own id in the result // (and the error CSV) instead of counting a failed action as succeeded. + // The refusal's producer-marked `userMessage` rides on the rejection, as + // on the aggregate path below: the row shows it, and `message` stays the + // whole text the error CSV keeps (objectstack#34215). if (!res?.success) { - throw new Error(res?.error || `Action ${def.name} failed`); + const error = new Error(res?.error || `Action ${def.name} failed`); + throw res?.userMessage ? Object.assign(error, { userMessage: res.userMessage }) : error; } }; diff --git a/ui/packages/plugin-grid/src/__tests__/objectBulkActionDispatch.test.tsx b/ui/packages/plugin-grid/src/__tests__/objectBulkActionDispatch.test.tsx index fe72f47a125..e8afc398fc8 100644 --- a/ui/packages/plugin-grid/src/__tests__/objectBulkActionDispatch.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/objectBulkActionDispatch.test.tsx @@ -585,8 +585,9 @@ describe('an aggregate rejection is one outcome for the selection (objectstack#3 expect(await refreshesOnClose(ds)).toBe(1); }); - // CONTROL: the per-record dispatch keeps its per-row display exactly as it - // was — a failing row is listed under its record, with the run's count. + // CONTROL: the per-record dispatch keeps its per-row display — a failing + // row is listed under its record, with the run's count. The row reads the + // refusal's userMessage (objectstack#34215, pinned in its own block below). it('CONTROL: a per-record dispatch with one failing row still lists that row', async () => { const actionsFetch = vi.fn(async (_url: string, init: { body: string }) => JSON.parse(init.body).recordId === 'r2' ? refusal({ userMessage: USER_TEXT }) : accepted()); @@ -595,7 +596,81 @@ describe('an aggregate rejection is one outcome for the selection (objectstack#3 expect(actionsFetch).toHaveBeenCalledTimes(2); expect(screen.queryByTestId('bulk-aggregate-rejection')).not.toBeInTheDocument(); expect(screen.getByText(/Succeeded 1 \/ 2/)).toBeInTheDocument(); - expect(screen.getByTestId('bulk-error-row-r2')).toHaveTextContent(PLATFORM_TEXT); + expect(screen.getByTestId('bulk-error-row-r2')).toHaveTextContent(USER_TEXT); + expect(screen.queryByTestId('bulk-error-row-r1')).not.toBeInTheDocument(); + }); +}); + +/** + * A per-record dispatch's failed row speaks the handler's words + * (objectstack#34215): the row lists the refusal's producer-marked + * `userMessage`, while the error CSV keeps the failure's whole text — the + * record of what the platform answered. A refusal with no `userMessage` + * keeps the platform text on the row. + */ +describe('a per-record failed row shows the refusal\'s userMessage (objectstack#34215)', () => { + const MOVE = { name: 'mass_update_stage', label: 'Update Stage', type: 'script' }; + const USER_TEXT = 'Plan B is Closed Won and was not moved.'; + const PLATFORM_TEXT = 'mass_update_stage: plan_b stage is closed_won'; + const refusal = (error: Record) => ({ + ok: false, + status: 400, + json: async () => ({ success: false, error: { code: 'HOOK_ABORTED', httpStatus: 400, message: PLATFORM_TEXT, ...error } }), + }); + const accepted = () => ({ ok: true, status: 200, json: async () => ({ success: true, data: { moved: 1 } }) }); + + /** Run the per-record action over both rows; only r2 is refused, with `error`. */ + async function runWithRefusedR2(error: Record) { + const actionsFetch = vi.fn(async (_url: string, init: { body: string }) => + JSON.parse(init.body).recordId === 'r2' ? refusal(error) : accepted()); + const script = createServerActionHandler({ fetch: actionsFetch as any, baseUrl: '' }); + await renderAndSelectAll({ objectActions: [MOVE], schema: { bulkActions: ['mass_update_stage'] }, handlers: { script } }); + fireEvent.click(await screen.findByTestId('bulk-action-mass_update_stage')); + fireEvent.click(await screen.findByRole('button', { name: 'Run' })); + await screen.findByRole('button', { name: 'Done' }); + expect(actionsFetch).toHaveBeenCalledTimes(2); + expect(screen.getByText(/Succeeded 1 \/ 2/)).toBeInTheDocument(); + } + + /** Click "Download error CSV" and read the text of the file it builds. */ + async function downloadedCsv(): Promise { + let blob: Blob | undefined; + vi.spyOn(URL, 'createObjectURL').mockImplementation((b: Blob | MediaSource) => { blob = b as Blob; return 'blob:errors'; }); + vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {}); + vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}); + fireEvent.click(screen.getByRole('button', { name: 'Download error CSV' })); + expect(blob).toBeDefined(); + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(String(reader.result)); + reader.onerror = () => reject(reader.error); + reader.readAsText(blob!); + }); + } + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('lists the userMessage on the row, and the error CSV keeps the whole text', async () => { + await runWithRefusedR2({ userMessage: USER_TEXT }); + + const row = screen.getByTestId('bulk-error-row-r2'); + expect(row).toHaveTextContent(USER_TEXT); + expect(row).not.toHaveTextContent(PLATFORM_TEXT); expect(screen.queryByTestId('bulk-error-row-r1')).not.toBeInTheDocument(); + + const lines = (await downloadedCsv()).split('\n'); + expect(lines).toHaveLength(2); + expect(lines[1].startsWith('r2,"')).toBe(true); + expect(lines[1]).toContain(PLATFORM_TEXT); + expect(lines[1]).not.toContain(USER_TEXT); + }); + + it('CONTROL: a refusal without a userMessage keeps the platform text on the row', async () => { + await runWithRefusedR2({}); + + expect(screen.getByTestId('bulk-error-row-r2')).toHaveTextContent(PLATFORM_TEXT); + expect(screen.queryByText(USER_TEXT, { exact: false })).not.toBeInTheDocument(); }); }); diff --git a/ui/packages/plugin-grid/src/components/BulkActionDialog.tsx b/ui/packages/plugin-grid/src/components/BulkActionDialog.tsx index 640188e1ab2..86c49174c89 100644 --- a/ui/packages/plugin-grid/src/components/BulkActionDialog.tsx +++ b/ui/packages/plugin-grid/src/components/BulkActionDialog.tsx @@ -638,7 +638,7 @@ export const BulkActionDialog: React.FC = ({
- {refusedRecordName(e.id)}: {e.error} + {refusedRecordName(e.id)}: {e.userMessage ?? e.error}
{/* A plain `custom` callout has nothing to re-run, but diff --git a/ui/packages/plugin-grid/src/hooks/useBulkExecutor.ts b/ui/packages/plugin-grid/src/hooks/useBulkExecutor.ts index 601bd9dc243..40bdd59b895 100644 --- a/ui/packages/plugin-grid/src/hooks/useBulkExecutor.ts +++ b/ui/packages/plugin-grid/src/hooks/useBulkExecutor.ts @@ -15,7 +15,15 @@ import { normalizeMultiValuePatch, type MultiValueFieldDef } from './multiValueF export interface BulkRowError { id: string; + /** The failure's whole text — what the error CSV records for the row. */ error: string; + /** + * The rejection's producer-marked `userMessage` (`declaredUserMessage`), + * set only when a promoted per-record action's refusal carried one: the + * words the handler wrote for the user. The result lists it for the row in + * place of `error`, which stays the whole text (objectstack#34215). + */ + userMessage?: string; } export interface BulkProgress { @@ -129,6 +137,8 @@ export interface BulkExecutorOptions { * MUST reject on failure: the executor attributes per-row errors from the * rejection reason, so resolving on a failed action would report it as a * success (the exact #2960 failure mode this whole path exists to kill). + * Reject with an error that carries the producer's `userMessage` when the + * failure has one — the row shows it, the error CSV keeps the message. * * When absent, `operation: 'custom'` keeps its historical meaning: no * mutation, the consumer wires `onComplete`. @@ -261,6 +271,8 @@ export function useBulkExecutor({ resource, dataSource, objectFields, runAction, ? Math.max(1, rows.length) : Math.max(1, def.batchSize ?? 200); const errors: BulkRowError[] = []; + // Record id → its per-record rejection's `userMessage` (custom runner only). + const userMessages = new Map(); let succeeded = 0; let failed = 0; let aggregateRejection: BulkResult['aggregateRejection']; @@ -368,8 +380,15 @@ export function useBulkExecutor({ resource, dataSource, objectFields, runAction, // per record through the injected runner. Without one, this is // the historical callout shape — no mutation, caller wires // onComplete. + // A rejection's producer-marked `userMessage` is kept per row + // and attached to the row's error below; the rejection itself + // still settles the row as failed with its whole message. return def.actionDef && runAction - ? runAction(def, rowById.get(id) ?? { id }, { ...params }) + ? runAction(def, rowById.get(id) ?? { id }, { ...params }).catch((e: unknown) => { + const userMessage = declaredUserMessage(e); + if (userMessage !== null) userMessages.set(id, userMessage); + throw e; + }) : Promise.resolve(); default: return Promise.reject(new Error(`Unknown operation: ${def.operation}`)); @@ -382,7 +401,10 @@ export function useBulkExecutor({ resource, dataSource, objectFields, runAction, ); succeeded += outcome.succeeded; failed += outcome.failed; - errors.push(...outcome.errors); + errors.push(...outcome.errors.map((rowError) => { + const userMessage = userMessages.get(rowError.id); + return userMessage === undefined ? rowError : { ...rowError, userMessage }; + })); setProgress({ total, done: succeeded, failed, inFlight: true }); } });