diff --git a/.changeset/34173-aggregate-bulk-rejection-one-outcome.md b/.changeset/34173-aggregate-bulk-rejection-one-outcome.md new file mode 100644 index 00000000000..bde1ad1bc51 --- /dev/null +++ b/.changeset/34173-aggregate-bulk-rejection-one-outcome.md @@ -0,0 +1,17 @@ +--- +'@object-ui/plugin-grid': patch +'@object-ui/core': patch +'@object-ui/types': patch +'@object-ui/i18n': patch +--- + +fix(plugin-grid): a rejected aggregate bulk action reports one outcome for the selection and refreshes the list + +Clause-②: yes (widening) — optional member userMessage on ActionResult (@object-ui/types) and ActionResponseOutcome (@object-ui/core); nothing removed or renamed +Metadata-protocol: none + +An aggregate bulk action (`bulkActionDefs` entry with `execution: 'aggregate'`) is one call for the whole selection. When that call rejected, the result dialog printed the rejection's platform `message` against every selected record, read "Succeeded 0 / N" even when the handler had already changed some of them, and the list kept showing the old values until a manual reload. + +A rejected aggregate run is now one outcome for the selection. The dialog says the action did not complete for the selected records and shows the rejection's message once: its `userMessage` when the handler threw one (the text it wrote for the user, already in the request's locale), else its `message`. It shows no per-record count and no per-record failure list, because one call cannot say which records it changed before it stopped, nor whether it kept those changes; it says only that some records may already have been changed. When the dialog is closed at the result step, the list re-reads its rows, whether the action resolved or rejected, and the selection stays after a rejection for a re-run. The per-record dispatch (`bulkActions: ['NAME']`) reports exactly as before. + +To carry the text, a failed script/server action dispatch now relays the refusal's `error.userMessage` on `ActionResult.userMessage` (`@object-ui/types`), read by `createServerActionHandler` (`@object-ui/core`); `error` stays the whole text. The new dialog sentence is translated in every locale pack. diff --git a/content/docs/ui/views.mdx b/content/docs/ui/views.mdx index 684171dea35..1f8781869e1 100644 --- a/content/docs/ui/views.mdx +++ b/content/docs/ui/views.mdx @@ -259,6 +259,18 @@ and per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` when the server work is expensive. +A rejection is reported as **one outcome for the whole selection**: the result +dialog says the action did not complete for the selected records and shows the +rejection's message once — its `userMessage` when the handler threw one (the +text the handler wrote for the user, in the request's locale), else its +`message`. It shows no per-row count and no per-row failure list, because one +call cannot say which records it had changed before it stopped, nor whether +it kept any of those changes. So the dialog says only that some records may +already have been changed. When you close the dialog at the result step, the +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. + **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/__tests__/serverActionHandler.test.ts b/ui/packages/core/src/actions/__tests__/serverActionHandler.test.ts index 70f40fb3545..16d4e96e7e9 100644 --- a/ui/packages/core/src/actions/__tests__/serverActionHandler.test.ts +++ b/ui/packages/core/src/actions/__tests__/serverActionHandler.test.ts @@ -423,3 +423,44 @@ describe('createServerActionHandler — transport failure', () => { expect(fetch).toHaveBeenCalledTimes(2); }); }); + +/** + * The refusal's producer-marked `userMessage` (objectstack#34173). The + * `/actions` door answers a thrown `userMessage` beside `message` on the + * ADR-0112 `error` object — from a script body and from a server action's + * handler alike. The handler relays it on `ActionResult.userMessage`, so a + * host that reports the failure to the end user (the grid's aggregate bulk + * result) can show it; `error` stays the whole text. + */ +describe('createServerActionHandler — userMessage relay (objectstack#34173)', () => { + const refusing = (error: Record) => vi.fn(async () => ({ + ok: false, + status: 400, + json: async () => ({ success: false, error: { code: 'HOOK_ABORTED', httpStatus: 400, message: 'plan_b is closed_won', ...error } }), + })) as unknown as ServerActionFetch; + + it('relays error.userMessage verbatim beside error, which stays the message', async () => { + const handler = createServerActionHandler({ fetch: refusing({ userMessage: ' Plan B is Closed Won.' }) }); + + const res = await handler({ type: 'script', name: 'mass_update_stage' } as ActionDef); + + expect(res).toEqual({ success: false, error: 'plan_b is closed_won', userMessage: ' Plan B is Closed Won.' }); + }); + + it('an unmarked refusal carries no userMessage', async () => { + const handler = createServerActionHandler({ fetch: refusing({}) }); + + const res = await handler({ type: 'script', name: 'mass_update_stage' } as ActionDef); + + expect(res).toEqual({ success: false, error: 'plan_b is closed_won' }); + expect('userMessage' in res).toBe(false); + }); + + it('a blank or non-string userMessage is no marking', async () => { + for (const userMessage of [' ', 42, { text: 'x' }]) { + const handler = createServerActionHandler({ fetch: refusing({ userMessage }) }); + const res = await handler({ type: 'script', name: 'mass_update_stage' } as ActionDef); + expect('userMessage' in res).toBe(false); + } + }); +}); diff --git a/ui/packages/core/src/actions/actionResponse.ts b/ui/packages/core/src/actions/actionResponse.ts index 00c84412e26..6dbb8748f70 100644 --- a/ui/packages/core/src/actions/actionResponse.ts +++ b/ui/packages/core/src/actions/actionResponse.ts @@ -61,6 +61,11 @@ export interface ActionResponseOutcome { * any with a usable `field`. Only on a failure. */ fieldErrors?: ActionFieldError[]; + /** + * The refusal's producer-marked user-facing text (`error.userMessage`), + * when it carried one. Only on a failure; `error` stays the whole text. + */ + userMessage?: string; /** * The ACTION ENVELOPE (`body.data`) — `{ success, data }`. Kept as-is * because `ActionResult.data` has always carried this level and @@ -126,18 +131,36 @@ export function interpretActionResponse( // string — handing that object to `toast.error()` as a React child // crashes the page, React #31). const fieldErrors = refusalFieldErrors(innerFailed ? envelope : json); + const userMessage = refusalUserMessage(innerFailed ? envelope : json); return { ok: false, error: innerFailed ? actionErrorDetail(envelope, `${label} failed`) : actionErrorDetail(json, `${label} failed (HTTP ${res.status})`), ...(fieldErrors ? { fieldErrors } : {}), + ...(userMessage !== undefined ? { userMessage } : {}), }; } return { ok: true, envelope, payload: readActionPayload(envelope) }; } +/** + * The producer-marked user-facing text of a refusal body + * (`ApiErrorSchema.userMessage`), as `ActionResult.userMessage` carries it. + * The ADR-0112 envelope carries it beside `message` on the `error` object — + * the `/actions` door answers a thrown `userMessage`, from a script body or a + * server action's handler alike, there. Presence is the marking: a blank or + * non-string value is no marking, and nothing else is promoted into it (the + * same predicate `@objectstack/client` applies when it lifts the field). + * Returned verbatim, untrimmed. + */ +export function refusalUserMessage(body: unknown): string | undefined { + const b = body as { error?: { userMessage?: unknown } } | null | undefined; + const raw = b?.error && typeof b.error === 'object' ? b.error.userMessage : undefined; + return typeof raw === 'string' && raw.trim() ? raw : undefined; +} + /** * The `fields` list of a refusal body, as `ActionResult.fieldErrors` carries * it. The ADR-0112 envelope carries the list in one of two members, both on diff --git a/ui/packages/core/src/actions/serverActionHandler.ts b/ui/packages/core/src/actions/serverActionHandler.ts index dc0a20f3347..7c9a6bb41b5 100644 --- a/ui/packages/core/src/actions/serverActionHandler.ts +++ b/ui/packages/core/src/actions/serverActionHandler.ts @@ -305,6 +305,7 @@ export function createServerActionHandler(config: ServerActionHandlerConfig): Se success: false, error: outcome.error, ...(outcome.fieldErrors ? { fieldErrors: outcome.fieldErrors } : {}), + ...(outcome.userMessage !== undefined ? { userMessage: outcome.userMessage } : {}), }; } // A declared `operation: 'update'` wrote the record it addresses — that diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index f8a4d3cea7c..003c495c884 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -589,6 +589,7 @@ const ar = { succeeded: "نجح {{count}} / {{total}}", resultFailed: " · فشل {{count}}", succeededRecords: "السجلات الناجحة", + aggregateNotCompleted: "لم يكتمل الإجراء للسجلات المحددة. ربما تم تغيير بعض السجلات بالفعل. عند الإغلاق تعرض القائمة قيمها الحالية.", retry: "إعادة المحاولة", downloadErrorCsv: "تنزيل ملف CSV للأخطاء", cancel: "إلغاء", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 5f2a3369d71..09f9f6885b4 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -543,6 +543,7 @@ const de = { succeeded: "Erfolgreich {{count}} / {{total}}", resultFailed: " · Fehlgeschlagen {{count}}", succeededRecords: "Erfolgreiche Datensätze", + aggregateNotCompleted: "Die Aktion wurde für die ausgewählten Datensätze nicht abgeschlossen. Einige Datensätze wurden möglicherweise bereits geändert; nach dem Schließen zeigt die Liste ihre aktuellen Werte.", retry: "Erneut versuchen", downloadErrorCsv: "Fehler-CSV herunterladen", cancel: "Abbrechen", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 38d44ccad62..f0d586d03f8 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1039,6 +1039,7 @@ const en = { succeeded: 'Succeeded {{count}} / {{total}}', resultFailed: ' \u00b7 Failed {{count}}', succeededRecords: 'Records that succeeded', + aggregateNotCompleted: 'The action did not complete for the selected records. Some records may already have been changed; the list shows their current values when you close this.', retry: 'Retry', downloadErrorCsv: 'Download error CSV', cancel: 'Cancel', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index e7f43fda5f5..e929ae567ab 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -558,6 +558,7 @@ const es = { succeeded: "Correctos {{count}} / {{total}}", resultFailed: " · Fallidos {{count}}", succeededRecords: "Registros correctos", + aggregateNotCompleted: "La acción no se completó para los registros seleccionados. Es posible que algunos registros ya se hayan modificado; al cerrar, la lista muestra sus valores actuales.", retry: "Reintentar", downloadErrorCsv: "Descargar CSV de errores", cancel: "Cancelar", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 78783ed4870..86d795b5388 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -553,6 +553,7 @@ const fr = { succeeded: "Réussis {{count}} / {{total}}", resultFailed: " · Échecs {{count}}", succeededRecords: "Enregistrements réussis", + aggregateNotCompleted: "L’action ne s’est pas terminée pour les enregistrements sélectionnés. Certains enregistrements ont peut-être déjà été modifiés. À la fermeture, la liste affiche leurs valeurs actuelles.", retry: "Réessayer", downloadErrorCsv: "Télécharger le CSV d'erreurs", cancel: "Annuler", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 2bbdcf1d902..89f2dc89b01 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -543,6 +543,7 @@ const ja = { succeeded: "成功 {{count}} / {{total}}", resultFailed: " · 失敗 {{count}}", succeededRecords: "成功したレコード", + aggregateNotCompleted: "選択したレコードに対する操作は完了しませんでした。一部のレコードはすでに変更されている可能性があります。閉じると、一覧に現在の値が表示されます。", retry: "再試行", downloadErrorCsv: "エラー CSV をダウンロード", cancel: "キャンセル", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 85e340a1cee..1297d0a3293 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -543,6 +543,7 @@ const ko = { succeeded: "성공 {{count}} / {{total}}", resultFailed: " · 실패 {{count}}", succeededRecords: "성공한 레코드", + aggregateNotCompleted: "선택한 레코드에 대한 작업이 완료되지 않았습니다. 일부 레코드는 이미 변경되었을 수 있습니다. 닫으면 목록에 현재 값이 표시됩니다.", retry: "다시 시도", downloadErrorCsv: "오류 CSV 다운로드", cancel: "취소", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index fb06f2e6b8b..f383e059c69 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -553,6 +553,7 @@ const pt = { succeeded: "Concluídos {{count}} / {{total}}", resultFailed: " · Falhas {{count}}", succeededRecords: "Registros concluídos", + aggregateNotCompleted: "A ação não foi concluída para os registros selecionados. Alguns registros podem já ter sido alterados; ao fechar, a lista mostra os valores atuais.", retry: "Tentar novamente", downloadErrorCsv: "Baixar CSV de erros", cancel: "Cancelar", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 709edafa4a5..dd99af42b5c 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -566,6 +566,7 @@ const ru = { succeeded: "Успешно {{count}} / {{total}}", resultFailed: " · Ошибок {{count}}", succeededRecords: "Успешные записи", + aggregateNotCompleted: "Действие не было выполнено для выбранных записей. Некоторые записи могли уже измениться; после закрытия список покажет их текущие значения.", retry: "Повторить", downloadErrorCsv: "Скачать CSV с ошибками", cancel: "Отмена", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index dfa8db59aa2..aa6bf06dd7e 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -785,6 +785,7 @@ const zh = { succeeded: '成功 {{count}} / {{total}}', resultFailed: ' · 失败 {{count}}', succeededRecords: '成功的记录', + aggregateNotCompleted: '操作未对所选记录全部完成。部分记录可能已被修改;关闭后列表会显示它们的当前值。', retry: '重试', downloadErrorCsv: '下载错误 CSV', cancel: '取消', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index f6245ff3d7e..a74170aa283 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -785,6 +785,7 @@ const zhHant = { succeeded: '成功 {{count}} / {{total}}', resultFailed: ' · 失敗 {{count}}', succeededRecords: '成功的記錄', + aggregateNotCompleted: '操作未對所選記錄全部完成。部分記錄可能已被修改;關閉後列表會顯示它們的當前值。', retry: '重試', downloadErrorCsv: '下載錯誤 CSV', cancel: '取消', diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 7c4d76f5dbd..a4af40e0efd 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -2217,7 +2217,12 @@ export const ObjectGrid: React.FC = ({ toast: { showOnSuccess: false, showOnError: false }, } as any); if (!res?.success) { - throw new Error(res?.error || `Action ${def.name} failed`); + // The refusal's producer-marked `userMessage` rides on the rejection, + // so the result reports the ONE outcome for the selection in the words + // the handler wrote for the user (objectstack#34173). `message` stays + // the whole text. + const error = new Error(res?.error || `Action ${def.name} failed`); + throw res?.userMessage ? Object.assign(error, { userMessage: res.userMessage }) : error; } }; const handleBulkDialogClose = (result?: BulkResult | null) => { @@ -2232,6 +2237,12 @@ export const ObjectGrid: React.FC = ({ resetSelection(); // Trigger refresh via the same path used by single-record mutations. setRefreshKey(k => k + 1); + } else if (result?.aggregateRejection) { + // A rejected aggregate run (objectstack#34173) is ONE call that may have + // written some rows before it stopped, so the grid re-reads them by the + // same path. The selection stays: re-running the whole action is the + // retry, as for a total failure. + setRefreshKey(k => k + 1); } }; diff --git a/ui/packages/plugin-grid/src/__tests__/objectBulkActionDispatch.test.tsx b/ui/packages/plugin-grid/src/__tests__/objectBulkActionDispatch.test.tsx index cad94a83eba..fe72f47a125 100644 --- a/ui/packages/plugin-grid/src/__tests__/objectBulkActionDispatch.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/objectBulkActionDispatch.test.tsx @@ -44,6 +44,7 @@ import { ObjectGrid } from '../ObjectGrid'; import { resetUndeclaredActionNamesWarnings } from '../undeclaredActionNames'; import { registerAllFields } from '@object-ui/fields'; import { ActionProvider } from '@object-ui/react'; +import { createServerActionHandler } from '@object-ui/core'; registerAllFields(); @@ -392,7 +393,7 @@ describe('aggregate bulk actions (objectui#3139)', () => { await waitFor(() => expect(screen.getByText(/Succeeded 2 \/ 2/)).toBeInTheDocument()); }); - it('attributes a failed aggregate call to every record, with no per-row Retry', async () => { + it('reports a failed aggregate call once for the selection, with no per-row list and no Retry', async () => { fetchMock.mockResolvedValue({ ok: false, status: 500, @@ -410,15 +411,16 @@ describe('aggregate bulk actions (objectui#3139)', () => { // ONE call — a failed aggregate run must not fan out per-record dispatches // against an endpoint written for a single `_selectedIds` call. - await waitFor(() => expect(screen.getByText(/Succeeded 0 \/ 2/)).toBeInTheDocument()); + await waitFor(() => expect(screen.getByTestId('bulk-aggregate-rejection')).toBeInTheDocument()); expect(fetchMock).toHaveBeenCalledTimes(1); - // Each record shows the one real error (the builtin api executor - // formats a non-2xx response as `HTTP `, same as the - // per-record pin above)… - expect(screen.getByTestId('bulk-error-row-r1')).toHaveTextContent('HTTP 500'); - expect(screen.getByTestId('bulk-error-row-r2')).toHaveTextContent('HTTP 500'); - // …but there is no per-row slice to re-attempt: the whole-run re-run is - // the retry (a total failure keeps the selection for exactly that). + // The one real error (the builtin api executor formats a non-2xx response + // as `HTTP `), once — not attributed to each record + // (objectstack#34173): the one call cannot say which records it wrote. + expect(screen.getByTestId('bulk-aggregate-rejection-message')).toHaveTextContent('HTTP 500'); + expect(screen.queryByTestId('bulk-error-row-r1')).not.toBeInTheDocument(); + expect(screen.queryByTestId('bulk-error-row-r2')).not.toBeInTheDocument(); + // There is no per-row slice to re-attempt: the whole-run re-run is the + // retry (a failed run keeps the selection for exactly that). expect(screen.queryByTestId('bulk-error-retry-r1')).not.toBeInTheDocument(); }); @@ -500,3 +502,100 @@ describe('per-record `visible` on a bulk action (objectui#3067)', () => { await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2)); }); }); + +/** + * An aggregate action that REJECTS (objectstack#34173). The handler is one + * call for the whole selection; a non-transactional body can move some rows + * and then reject once, and nothing in the rejection says which rows moved. + * So the result is ONE outcome for the selection — the rejection's + * producer-marked `userMessage`, once, with no per-row count and no per-row + * list — and the grid re-reads its rows when the dialog closes, whether the + * call resolved or rejected. Driven through the console's real `script` + * dispatch (`createServerActionHandler`) and the `/actions` door's refusal + * envelope, which carries `userMessage` beside `message` on `error` for a + * script body and a server action's handler alike. + */ +describe('an aggregate rejection is one outcome for the selection (objectstack#34173)', () => { + const MOVE = { name: 'mass_update_stage', label: 'Update Stage', type: 'script' }; + const AGGREGATE = { bulkActionDefs: [{ name: 'mass_update_stage', operation: 'custom', execution: 'aggregate' }] }; + 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: 2 } }) }); + + async function runAndClose(actionsFetch: ReturnType, schema: Record = AGGREGATE) { + const script = createServerActionHandler({ fetch: actionsFetch as any, baseUrl: '' }); + const ds = await renderAndSelectAll({ objectActions: [MOVE], schema, 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' }); + return ds; + } + + /** Close the result and count the grid's re-reads: the refresh is exactly one. */ + async function refreshesOnClose(ds: any): Promise { + const before = ds.find.mock.calls.length; + fireEvent.click(screen.getByRole('button', { name: 'Done' })); + await waitFor(() => expect(ds.find.mock.calls.length).toBeGreaterThan(before)); + await new Promise(r => setTimeout(r, 50)); + return ds.find.mock.calls.length - before; + } + + it('shows the rejection’s userMessage once, with no per-row list and no "0 / N" count', async () => { + const actionsFetch = vi.fn(async () => refusal({ userMessage: USER_TEXT })); + await runAndClose(actionsFetch); + + expect(actionsFetch).toHaveBeenCalledTimes(1); + expect(screen.getByTestId('bulk-aggregate-rejection')).toHaveTextContent( + 'The action did not complete for the selected records.', + ); + // The client cannot know whether the handler kept any write (a + // transactional body keeps none), so the sentence is modal — it never + // asserts that changed records keep their changes. + expect(screen.getByTestId('bulk-aggregate-rejection')).toHaveTextContent( + 'Some records may already have been changed; the list shows their current values when you close this.', + ); + expect(screen.queryByText(/keep their changes/)).not.toBeInTheDocument(); + expect(screen.getAllByText(USER_TEXT)).toHaveLength(1); + expect(screen.queryByText(PLATFORM_TEXT, { exact: false })).not.toBeInTheDocument(); + expect(document.querySelectorAll('[data-testid^="bulk-error-row-"]')).toHaveLength(0); + expect(screen.queryByText(/Succeeded/)).not.toBeInTheDocument(); + expect(screen.queryByText(/0 \/ 2/)).not.toBeInTheDocument(); + }); + + it('falls back to the rejection’s message when it carries no userMessage', async () => { + await runAndClose(vi.fn(async () => refusal({}))); + + expect(screen.getByTestId('bulk-aggregate-rejection-message')).toHaveTextContent(PLATFORM_TEXT); + expect(screen.getAllByText(PLATFORM_TEXT)).toHaveLength(1); + }); + + it('re-reads the grid once when the dialog closes after a rejection', async () => { + const ds = await runAndClose(vi.fn(async () => refusal({ userMessage: USER_TEXT }))); + expect(await refreshesOnClose(ds)).toBe(1); + }); + + it('re-reads the grid once when the dialog closes after the call resolved', async () => { + const ds = await runAndClose(vi.fn(async () => accepted())); + expect(screen.getByText(/Succeeded 2 \/ 2/)).toBeInTheDocument(); + 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. + 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()); + await runAndClose(actionsFetch, { bulkActions: ['mass_update_stage'] }); + + 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.queryByTestId('bulk-error-row-r1')).not.toBeInTheDocument(); + }); +}); diff --git a/ui/packages/plugin-grid/src/__tests__/useBulkExecutor.test.ts b/ui/packages/plugin-grid/src/__tests__/useBulkExecutor.test.ts index 7c5f8599afb..3603c941f40 100644 --- a/ui/packages/plugin-grid/src/__tests__/useBulkExecutor.test.ts +++ b/ui/packages/plugin-grid/src/__tests__/useBulkExecutor.test.ts @@ -554,7 +554,10 @@ describe('useBulkExecutor', () => { expect(result.current.result?.succeeded).toBe(5); }); - it('attributes a failed aggregate call to every id with the real error — no per-record re-dispatch', async () => { + // [objectstack#34173] A rejection is ONE outcome for the selection, not + // the same error attributed to every id: the one call cannot say which + // rows it wrote before it stopped. + it('a failed aggregate call is one outcome for the selection — no per-id error, no per-record re-dispatch', async () => { const runAggregate = vi.fn(async () => { throw new Error('zip generation failed'); }); @@ -568,12 +571,41 @@ describe('useBulkExecutor', () => { expect(runAggregate).toHaveBeenCalledTimes(1); expect(runAction).not.toHaveBeenCalled(); + expect(result.current.result?.aggregateRejection).toEqual({ message: 'zip generation failed' }); + expect(result.current.result?.errors).toEqual([]); expect(result.current.result?.succeeded).toBe(0); - expect(result.current.result?.failed).toBe(2); - expect(result.current.result?.errors).toEqual([ - { id: 'a', error: 'zip generation failed' }, - { id: 'b', error: 'zip generation failed' }, - ]); + }); + + it('the rejection reports its producer-marked userMessage, not its message', async () => { + const runAggregate = vi.fn(async () => { + throw Object.assign(new Error('HOOK_ABORTED: deal_b is closed_won'), { + userMessage: 'Deal B is Closed Won and was not moved.', + }); + }); + const { result } = renderHook(() => + useBulkExecutor({ resource: 'opportunity', dataSource: ds(), runAggregate })); + + await act(async () => { + await result.current.run(agg(), [{ id: 'a' }, { id: 'b' }], {}); + }); + + expect(result.current.result?.aggregateRejection).toEqual({ + message: 'Deal B is Closed Won and was not moved.', + }); + expect(result.current.result?.errors).toEqual([]); + }); + + it('a resolved aggregate call carries no rejection', async () => { + const runAggregate = aggregateStub(); + const { result } = renderHook(() => + useBulkExecutor({ resource: 'device', dataSource: ds(), runAggregate })); + + await act(async () => { + await result.current.run(agg(), [{ id: 'a' }, { id: 'b' }], {}); + }); + + expect(result.current.result?.aggregateRejection).toBeUndefined(); + expect(result.current.result).toMatchObject({ total: 2, succeeded: 2, failed: 0, errors: [] }); }); it('fails loudly when no runAggregate is wired instead of degrading to per-record fan-out', async () => { @@ -586,8 +618,8 @@ describe('useBulkExecutor', () => { }); expect(runAction).not.toHaveBeenCalled(); - expect(result.current.result?.failed).toBe(2); - expect(result.current.result?.errors[0].error).toContain('no dispatcher wired'); + expect(result.current.result?.aggregateRejection?.message).toContain('no dispatcher wired'); + expect(result.current.result?.errors).toEqual([]); }); it('retry() refuses aggregate rows — the whole-run re-run is the retry', async () => { diff --git a/ui/packages/plugin-grid/src/components/BulkActionDialog.tsx b/ui/packages/plugin-grid/src/components/BulkActionDialog.tsx index d5b4cf32da7..640188e1ab2 100644 --- a/ui/packages/plugin-grid/src/components/BulkActionDialog.tsx +++ b/ui/packages/plugin-grid/src/components/BulkActionDialog.tsx @@ -562,7 +562,32 @@ export const BulkActionDialog: React.FC = ({ )} - {step === 'result' && result && ( + {step === 'result' && result?.aggregateRejection && ( + /* A rejected aggregate run (objectui#3139) is ONE outcome for the + whole selection (objectstack#34173): the one call cannot say which + rows it wrote before it stopped, so the panel reports no per-row + count ("Succeeded 0 / N" would be false after a partial move) and + no per-row list — it says the action did not complete, and shows + the rejection's message once. */ +
+
+ + + {t('grid.bulk.aggregateNotCompleted', { + defaultValue: 'The action did not complete for the selected records. Some records may already have been changed; the list shows their current values when you close this.', + })} + +
+

+ {result.aggregateRejection.message} +

+
+ )} + + {step === 'result' && result && !result.aggregateRejection && (
{result.failed === 0 ? ( diff --git a/ui/packages/plugin-grid/src/hooks/useBulkExecutor.ts b/ui/packages/plugin-grid/src/hooks/useBulkExecutor.ts index d3894cd9932..601bd9dc243 100644 --- a/ui/packages/plugin-grid/src/hooks/useBulkExecutor.ts +++ b/ui/packages/plugin-grid/src/hooks/useBulkExecutor.ts @@ -10,6 +10,7 @@ import { useCallback, useRef, useState } from 'react'; import type { BulkActionDef, BulkWriteResult, DataSource } from '@object-ui/types'; import { RelatedCountStore } from '@object-ui/components'; import { executeBulkBatch } from '@object-ui/core'; +import { declaredUserMessage } from '@object-ui/react'; import { normalizeMultiValuePatch, type MultiValueFieldDef } from './multiValueFields'; export interface BulkRowError { @@ -29,6 +30,19 @@ export interface BulkResult { succeeded: number; failed: number; errors: BulkRowError[]; + /** + * Set only when an `execution: 'aggregate'` run (objectui#3139) REJECTED. + * + * An aggregate dispatch is one call for the whole selection, and its + * rejection says nothing about which rows the handler had already written + * before it stopped: a non-transactional loop over the selection can move + * some rows and then reject once. So the run has ONE outcome, not N row + * outcomes. `message` is the rejection's producer-marked `userMessage` + * (`declaredUserMessage`), falling back to the error's own message; it is + * shown once, for the selection. `errors` carries no per-row entry for it, + * and `succeeded` / `failed` are not a per-row count the dialog may print. + */ + aggregateRejection?: { message: string }; } /** @@ -133,10 +147,12 @@ export interface BulkExecutorOptions { * server can produce one aggregate artifact (zip, merged PDF…) for the * whole selection. * - * MUST reject on failure, like `runAction`: the executor treats the one - * call as all-or-nothing and attributes the rejection reason to every - * selected id in the result, so resolving on a failed action would report - * the entire selection as succeeded. + * MUST reject on failure, like `runAction`: resolving on a failed action + * would report the entire selection as succeeded. A rejection is ONE + * outcome for the whole selection (`BulkResult.aggregateRejection`), never + * N row failures: the call cannot say which rows it wrote before it + * stopped (objectstack#34173). Reject with an error that carries the + * producer's `userMessage` when the failure has one — the result shows it. * * When absent, an `execution: 'aggregate'` def FAILS LOUDLY rather than * quietly degrading to per-record fan-out — N dispatches against an @@ -180,11 +196,13 @@ export interface BulkExecutorOptions { * whole list after every row, and the gaps that left between requests were * most of the wall time. * - * A `custom` def with `execution: 'aggregate'` (objectui#3139) rides the same - * bulk-first decision tree, but its "bulk call" is ONE `runAggregate` dispatch - * for the entire selection (never chunked, all-or-nothing) and its per-row - * "fallback" only re-throws the captured error for per-id attribution — it - * never fans out per-record dispatches against a single-call endpoint. + * A `custom` def with `execution: 'aggregate'` (objectui#3139) does not ride + * the bulk-first decision tree: it is ONE `runAggregate` dispatch for the + * entire selection (never chunked, never fanned out per record against a + * single-call endpoint). It settles as a whole — resolved, every row counts as + * covered; rejected, the result carries one `aggregateRejection` for the + * selection instead of the same error attributed to every row, because the + * call cannot say which rows it had already written (objectstack#34173). */ export function useBulkExecutor({ resource, dataSource, objectFields, runAction, runAggregate }: BulkExecutorOptions) { const [progress, setProgress] = useState({ @@ -245,6 +263,7 @@ export function useBulkExecutor({ resource, dataSource, objectFields, runAction, const errors: BulkRowError[] = []; let succeeded = 0; let failed = 0; + let aggregateRejection: BulkResult['aggregateRejection']; setResult(null); setProgress({ total, done: 0, failed: 0, inFlight: true }); @@ -299,33 +318,37 @@ export function useBulkExecutor({ resource, dataSource, objectFields, runAction, if (id) rowById.set(id, row); } + // Aggregate mode: the ONE call for the whole selection — even a + // single selected row goes through it, because the target endpoint + // reads `_selectedIds`, which the per-record dispatch shape never + // carries. It settles as a whole (objectstack#34173): resolved, it + // covered every id; rejected, the run has one outcome for the + // selection, not the same error attributed to each row — the call + // cannot say which rows it had written before it stopped. + if (isAggregate) { + try { + if (!runAggregate) { + throw new Error(`Aggregate action ${def.name} has no dispatcher wired`); + } + await runAggregate(def, validIds.map((id) => rowById.get(id) ?? { id }), { ...params }); + succeeded += validIds.length; + } catch (e) { + failed += validIds.length; + aggregateRejection = { + message: declaredUserMessage(e) + ?? (e instanceof Error ? e.message : String(e)), + }; + } + setProgress({ total, done: succeeded, failed, inFlight: true }); + continue; + } + // Decide whether the adapter can collapse this whole batch into 1 - // call. Single-row batches skip bulk (no win, just overhead) — EXCEPT - // in aggregate mode, where even one selected row must go through the - // single aggregate call: the target endpoint reads `_selectedIds`, - // which the per-record dispatch shape never carries. - const allowBulk = validIds.length >= 2 || isAggregate; + // call. Single-row batches skip bulk (no win, just overhead). + const allowBulk = validIds.length >= 2; let bulkCall: ((ids: string[]) => Promise) | undefined; let label = 'bulk'; - // The one real error from a failed aggregate call. The perRow - // "fallback" below re-throws it per id for attribution — it must - // never re-dispatch (see the `custom` case). - let aggregateError: unknown; - if (isAggregate && runAggregate) { - bulkCall = async (ids) => { - try { - await runAggregate(def, ids.map((id) => rowById.get(id) ?? { id }), { ...params }); - // All-or-nothing: the single call resolving means it covered - // every id. Partial success has no envelope on this path — a - // server that cannot cover the whole selection must reject. - return ids.length; - } catch (e) { - aggregateError = e; - throw e; - } - }; - label = 'aggregate action'; - } else if (def.operation === 'update' && typeof dataSource.bulkUpdate === 'function') { + if (def.operation === 'update' && typeof dataSource.bulkUpdate === 'function') { bulkCall = (ids) => dataSource.bulkUpdate!(resource, ids, buildPatch()); label = 'bulk update'; } else if (def.operation === 'delete' && typeof dataSource.bulkDelete === 'function') { @@ -340,22 +363,7 @@ export function useBulkExecutor({ resource, dataSource, objectFields, runAction, case 'update': return dataSource.update(resource, id, buildPatch()); case 'custom': - // Aggregate mode never fans out: the ONE bulkCall above either - // covered every id or failed as a whole. Reaching here means it - // threw (or `runAggregate` was never wired) — attribute the real - // error to each id rather than re-dispatching N per-record calls - // against an endpoint written for one `_selectedIds` call. - if (isAggregate) { - return Promise.reject( - aggregateError instanceof Error - ? aggregateError - : new Error( - aggregateError !== undefined - ? String(aggregateError) - : `Aggregate action ${def.name} has no dispatcher wired`, - ), - ); - } + // (Aggregate mode never reaches here: it settled above.) // A PROMOTED def (`actionDef` present) runs its object action once // per record through the injected runner. Without one, this is // the historical callout shape — no mutation, caller wires @@ -379,7 +387,13 @@ export function useBulkExecutor({ resource, dataSource, objectFields, runAction, } }); - const finalResult: BulkResult = { total, succeeded, failed, errors }; + const finalResult: BulkResult = { + total, + succeeded, + failed, + errors, + ...(aggregateRejection ? { aggregateRejection } : {}), + }; // Only retain the snapshot for rows that actually succeeded — there's // no point trying to "undo" a row whose mutation never landed. const failedIds = new Set(errors.map(e => e.id)); @@ -390,8 +404,9 @@ export function useBulkExecutor({ resource, dataSource, objectFields, runAction, // Mutating any row in `resource` may have changed how many records // belong to a parent (e.g. deleting Contacts under an Account). Drop // every cached count for this resource so the next page render - // re-probes. Cheap — counts are 1-int values. - if (succeeded > 0) { + // re-probes. Cheap — counts are 1-int values. A rejected aggregate run + // may have written rows before it stopped, so it invalidates too. + if (succeeded > 0 || aggregateRejection) { RelatedCountStore.invalidate(resource); } return finalResult; diff --git a/ui/packages/types/src/ui-action.ts b/ui/packages/types/src/ui-action.ts index 6b2a13c4b61..d778d59f78d 100644 --- a/ui/packages/types/src/ui-action.ts +++ b/ui/packages/types/src/ui-action.ts @@ -1203,6 +1203,15 @@ export interface ActionResult { */ fieldErrors?: ActionFieldError[]; + /** + * The refusal's producer-marked user-facing text, as the server answered it + * (`error.userMessage`, `ApiErrorSchema.userMessage`): verbatim, already in + * the request's locale. Set only on a failed result whose refusal carried + * it, beside `error`, which stays the whole text. A host that reports the + * failure to the end user shows this when present (objectstack#34173). + */ + userMessage?: string; + /** Whether the caller should reload its data after the action */ reload?: boolean;