Skip to content

Commit 31eb2ae

Browse files
fix(plugin-grid): report a rejected aggregate bulk action as one outcome and refresh the list (#34213)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9FjkKnUT9gkJCgXLZMd3GkS)_ Fixes #34173 Clause-②: yes (widening) — optional member userMessage on ActionResult (@object-ui/types) and ActionResponseOutcome (@object-ui/core); nothing removed or renamed Metadata-protocol: none ## 维护者速读 - **改了什么**:选择栏里「整体执行」(`execution: 'aggregate'`)的批量动作被拒时,结果框只说一次「操作未对所选记录全部完成」,并只显示一次处理器写给用户的提示(`userMessage`,没有就用 `message`);不再逐行重复同一句报错,也不再显示「成功 0 / N」。关掉结果框后列表会重新读取,被改过的记录显示新值。逐条执行的批量动作显示完全不变。 - **为什么改**:HotCRM 实测:选两个商机批量改阶段,一个已赢单被拒、另一个其实改了,结果框却说 0/2、每行都是平台报错,列表也不刷新,销售看不出哪条动了。 - **风险与回滚**:只影响 aggregate 批量动作的结果框和关闭后的刷新;`ActionResult`(`@object-ui/types`)和 `ActionResponseOutcome`(`@object-ui/core`)各多一个可选字段 `userMessage`。回滚即 revert 本 PR。 - **先看**:`ui/packages/plugin-grid/src/hooks/useBulkExecutor.ts`(aggregate 一次结算、一个结果);`ui/packages/plugin-grid/src/components/BulkActionDialog.tsx`(结果框的 aggregate 分支);`ui/packages/plugin-grid/src/ObjectGrid.tsx`(拒绝时带上 `userMessage`、关闭时刷新)。 - **两分钟验证**:`pnpm --dir ui exec vitest run packages/plugin-grid/src/__tests__/objectBulkActionDispatch.test.tsx`,预期全绿,其中 `an aggregate rejection is one outcome for the selection` 组 5 条。 - **需要你做的**:无,席位落地。 ## What changes A rejected aggregate bulk run is ONE outcome for the selection. The one call cannot say which rows it wrote before it stopped (a non-transactional body can move some rows and then reject once), so the result no longer pretends to a per-row count. - `useBulkExecutor`: an `execution: 'aggregate'` def no longer rides the bulk-first decision tree. It makes its one `runAggregate` call; resolved, every row counts as covered (unchanged); rejected, the result carries `aggregateRejection: { message }`, where `message` is `declaredUserMessage(error)` (the producer-marked `userMessage`) else the error's own message, and `errors` gets no per-row entry. A rejected run also invalidates the resource's cached related counts, as a successful one does. `BulkResult` is not exported from the package. - `BulkActionDialog`: for a result with `aggregateRejection`, the panel says the action did not complete for the selected records (new key `grid.bulk.aggregateNotCompleted`) and shows the message once. No "Succeeded x / N", no per-row list, no error CSV, no Retry. Every other result renders exactly as before. - `ObjectGrid`: the aggregate dispatcher rejects with an `Error` whose `message` is `ActionResult.error` and which carries `ActionResult.userMessage` when present. On dialog close, a result with `aggregateRejection` bumps `refreshKey`, the same refresh path the per-row run already takes when rows succeeded; the selection stays, ready for a re-run. A resolved aggregate run keeps its existing refresh, which happens once. - The carrier: `interpretActionResponse` reads the refusal's `error.userMessage` (ADR-0112 envelope; non-empty string only, verbatim) onto `ActionResponseOutcome.userMessage`, and `createServerActionHandler` relays it on the failed `ActionResult.userMessage`. `error` stays the whole text, so every existing reader of `error` (toasts, the per-row list) is unchanged. The reader `refusalUserMessage` stays off the package's public entry. - i18n: `grid.bulk.aggregateNotCompleted` in all eleven packs (`zh-Hant` regenerated with `gen-zh-hant.mjs`). The sentence has no `{{count}}`, so it is not a plural family. - Docs: `content/docs/ui/views.mdx` says what the dialog shows for a rejected aggregate run and when the list re-reads. ## Tests - `objectBulkActionDispatch.test.tsx`, new top-level describe `an aggregate rejection is one outcome for the selection (objectstack#34173)`, driven through the real `script` dispatch (`createServerActionHandler`) and the `/actions` door's refusal envelope: - the rejection's `userMessage` shows once; the platform `message` is absent; zero `bulk-error-row-*`; no "Succeeded" and no "0 / 2" text; - with no `userMessage`, the `message` shows once; - the grid's `find` runs exactly once after Done following a rejection, and exactly once following a resolve; - CONTROL: a per-record dispatch (`bulkActions: ['mass_update_stage']`) with one refused row still reads "Succeeded 1 / 2" and lists `bulk-error-row-r2` with the row's error text. - `useBulkExecutor.test.ts`: a rejection is one `aggregateRejection` with `errors: []`; it reports `userMessage` over `message`; a resolved call carries no rejection. - `serverActionHandler.test.ts`, new describe `userMessage relay`: relayed verbatim beside `error`; absent when unmarked; a blank, numeric or object value is no marking. - **Forced test edits** (each pinned the behaviour this card calls the defect): - `useBulkExecutor.test.ts` "attributes a failed aggregate call to every id with the real error — no per-record re-dispatch" is now "a failed aggregate call is one outcome for the selection — no per-id error, no per-record re-dispatch". - `useBulkExecutor.test.ts` "fails loudly when no runAggregate is wired…" now reads the message from `aggregateRejection` instead of `errors[0]`. - `objectBulkActionDispatch.test.tsx` "attributes a failed aggregate call to every record, with no per-row Retry" is now "reports a failed aggregate call once for the selection, with no per-row list and no Retry". ## Acceptance notes - **File surface beyond the claim, declared:** `ui/packages/plugin-grid/src/ObjectGrid.tsx` (the dialog's mount, and the per-row refresh path the order says to reuse lives there); `ui/packages/types/src/ui-action.ts` (`ActionResult.userMessage`, the carrier from the script dispatch to the grid); `content/docs/ui/views.mdx` (ui commandment 2, docs-driven); all eleven locale packs, because `all-locales-key-parity.test.ts` requires every pack to define every `en` key, so "let other locales fall back" is not available in this pack. - **Public face for the seat to judge:** two optional members on published types, `ActionResult.userMessage` (`@object-ui/types`) and `ActionResponseOutcome.userMessage` (`@object-ui/core`). No new exported name. Precedent: `ActionResult.fieldErrors`, the same relay of the same refusal envelope. The seat ruled the declaration `Clause-②: yes (widening)` (a non-protocol widening, so the changeset stays `patch`); the PR body and the changeset carry it since head 3f829b5. - **Card ask 3 (a per-row result shape for aggregate handlers) is still needed** for a truthful per-row count: with this PR the dialog no longer states a false count, but it still cannot say which rows moved. That is an action-contract change in `packages/spec`, out of scope here. - **Same class, left unchanged as ordered:** a per-record bulk row refused with a `userMessage` still lists the row's `error` (the platform message), and the single-record action toast reads `error` too. With `ActionResult.userMessage` now carried, preferring it there is a small follow-up. The CONTROL pin above shows the current per-row text. - The list re-reads when the dialog closes (the path the per-row run uses), not at the instant the call settles; the dialog is modal over the grid. - Out of scope, as the card says: a script action body gets no locale in `ctx.session` (the #34062 class). ## Verification <details><summary>Measured on main 75ab117 before the fix: all three symptoms, script dispatch</summary> A probe test drove the real `ObjectGrid` with `createServerActionHandler`; the `/actions` answer was `400 { success: false, error: { code: 'HOOK_ABORTED', message: 'mass_update_stage: Plan B is Closed Won', userMessage: 'Plan B is Closed Won and was not moved.' } }`: ```text PROBE[reject] dialog text: "Update StageSucceeded 0 / 2 · Failed 2 … Plan A: mass_update_stage: Plan B is Closed WonPlan B: mass_update_stage: Plan B is Closed Won Download error CSV Done" PROBE[reject] actions POSTs: 1 error rows: 2 PROBE[reject] find calls on Done: 0 PROBE[resolve] dialog text: "Update StageSucceeded 2 / 2 … • Plan A• Plan B Done" PROBE[resolve] find calls on Done: 1 ``` The wire for both handler shapes, read from `actionsDoorAnswerOf` (`@objectstack/types` dist on the same tree): a script body's sandboxed throw and a server action's plain throw both answer `userMessage` beside `message`: ```text script-body {"status":400,"code":"HOOK_ABORTED","message":"Plan B is Closed Won","userMessage":"Plan B is Closed Won and was not moved."} server-handler {"status":400,"code":"VALIDATION_ERROR","message":"Plan B is Closed Won","userMessage":"Plan B is Closed Won and was not moved."} ``` The client then dropped `userMessage` in `interpretActionResponse` / `actionErrorDetail`, which read `error.message` only. </details> <details><summary>Ablation: five legs, each red, restored clean (scripts/ablation-replace.mjs, anchors hit 1 → 0)</summary> Committed fix first (7cf6c65); each leg mutated one line and ran the three touched test files; the trap restored `git checkout HEAD -- ui/packages` and printed `RESTORED-CLEAN`. Tests resolve `@object-ui/*` from source, so no dist rebuild was involved. - `useBulkExecutor.ts` `declaredUserMessage(e)` → `null`: red "shows the rejection's userMessage once…" and "the rejection reports its producer-marked userMessage, not its message". - `ObjectGrid.tsx` the rejection refresh branch disabled: red "re-reads the grid once when the dialog closes after a rejection". - `BulkActionDialog.tsx` per-row branch guard removed (`!result.aggregateRejection`): red "shows the rejection's userMessage once, with no per-row list and no "0 / N" count". - `serverActionHandler.ts` `userMessage` relay removed: red "relays error.userMessage verbatim…" and the dialog userMessage pin. - `useBulkExecutor.ts` aggregate branch disabled: red across both aggregate describes (11 tests). </details> <details><summary>Local runs on head 2ee839f (main 571cf90 merged)</summary> Head 3f829b5 changes only the changeset's Clause-② line; on it `check-changeset-no-major`, `check-empty-changeset`, `check-adr-0087-registration` (each `--base origin/main`), `check:changeset-gate-self-tests` and `check:nul-bytes` re-ran, exit 0 each. - Type-check (`pnpm run type-check`, tsc echoed): `@object-ui/types`, `@object-ui/core`, `@object-ui/i18n`, `@object-ui/plugin-grid` — each exit 0. - Whole packages: `pnpm exec vitest run packages/plugin-grid/ packages/types/ packages/i18n/ packages/core/src/actions/` — Test Files 830 passed (830), Tests 15603 passed, 13 skipped. Lock VERDICT command-exit 0. - Wider readers, narrowed by grep for the changed symbols and testids under `ui/packages` and `ui/apps` (declared narrowing; CI's Test UI runs everything): 12 files in components, app-shell and console — Test Files 12 passed, Tests 466 passed. - `check:i18n-keys`, `check:i18n-drift`, `check:i18n-dead-keys` (ui): exit 0 each. - `node scripts/pm/dispatch-gates.mjs --commands`: 72 derived families, all exit 0; `--ran` reconciliation: 72 derived, 72 run, 0 NOT-MEASURED, 0 UNRUN. - Dogfood battery: not run — no `!` in the title and no `(narrowing)` arm. </details> <!-- signed: domain:ui#1 · os-steve · session_01ADHkmRD9ZdCE9G3z9FgtCj --> --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent adccc24 commit 31eb2ae

22 files changed

Lines changed: 367 additions & 71 deletions
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@object-ui/plugin-grid': patch
3+
'@object-ui/core': patch
4+
'@object-ui/types': patch
5+
'@object-ui/i18n': patch
6+
---
7+
8+
fix(plugin-grid): a rejected aggregate bulk action reports one outcome for the selection and refreshes the list
9+
10+
Clause-②: yes (widening) — optional member userMessage on ActionResult (@object-ui/types) and ActionResponseOutcome (@object-ui/core); nothing removed or renamed
11+
Metadata-protocol: none
12+
13+
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.
14+
15+
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.
16+
17+
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.

‎content/docs/ui/views.mdx‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,18 @@ and per-row retry is replaced by re-running the action. `batchSize` does not
259259
apply (the call is never chunked); set `maxRecords` when the server work is
260260
expensive.
261261

262+
A rejection is reported as **one outcome for the whole selection**: the result
263+
dialog says the action did not complete for the selected records and shows the
264+
rejection's message once — its `userMessage` when the handler threw one (the
265+
text the handler wrote for the user, in the request's locale), else its
266+
`message`. It shows no per-row count and no per-row failure list, because one
267+
call cannot say which records it had changed before it stopped, nor whether
268+
it kept any of those changes. So the dialog says only that some records may
269+
already have been changed. When you close the dialog at the result step, the
270+
list re-reads its rows, whether the action resolved or rejected, so a record
271+
the handler changed shows its current value; the selection stays after a
272+
rejection, ready for a re-run.
273+
262274
**Pick the right key for the dispatch you mean.** Per-record is
263275
`bulkActions: ['<name>']` — the bare-string form, which has nowhere to carry a
264276
flag and is promoted with the action's own label, params and `visible`.

‎ui/packages/core/src/actions/__tests__/serverActionHandler.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -423,3 +423,44 @@ describe('createServerActionHandler — transport failure', () => {
423423
expect(fetch).toHaveBeenCalledTimes(2);
424424
});
425425
});
426+
427+
/**
428+
* The refusal's producer-marked `userMessage` (objectstack#34173). The
429+
* `/actions` door answers a thrown `userMessage` beside `message` on the
430+
* ADR-0112 `error` object — from a script body and from a server action's
431+
* handler alike. The handler relays it on `ActionResult.userMessage`, so a
432+
* host that reports the failure to the end user (the grid's aggregate bulk
433+
* result) can show it; `error` stays the whole text.
434+
*/
435+
describe('createServerActionHandler — userMessage relay (objectstack#34173)', () => {
436+
const refusing = (error: Record<string, unknown>) => vi.fn(async () => ({
437+
ok: false,
438+
status: 400,
439+
json: async () => ({ success: false, error: { code: 'HOOK_ABORTED', httpStatus: 400, message: 'plan_b is closed_won', ...error } }),
440+
})) as unknown as ServerActionFetch;
441+
442+
it('relays error.userMessage verbatim beside error, which stays the message', async () => {
443+
const handler = createServerActionHandler({ fetch: refusing({ userMessage: ' Plan B is Closed Won.' }) });
444+
445+
const res = await handler({ type: 'script', name: 'mass_update_stage' } as ActionDef);
446+
447+
expect(res).toEqual({ success: false, error: 'plan_b is closed_won', userMessage: ' Plan B is Closed Won.' });
448+
});
449+
450+
it('an unmarked refusal carries no userMessage', async () => {
451+
const handler = createServerActionHandler({ fetch: refusing({}) });
452+
453+
const res = await handler({ type: 'script', name: 'mass_update_stage' } as ActionDef);
454+
455+
expect(res).toEqual({ success: false, error: 'plan_b is closed_won' });
456+
expect('userMessage' in res).toBe(false);
457+
});
458+
459+
it('a blank or non-string userMessage is no marking', async () => {
460+
for (const userMessage of [' ', 42, { text: 'x' }]) {
461+
const handler = createServerActionHandler({ fetch: refusing({ userMessage }) });
462+
const res = await handler({ type: 'script', name: 'mass_update_stage' } as ActionDef);
463+
expect('userMessage' in res).toBe(false);
464+
}
465+
});
466+
});

‎ui/packages/core/src/actions/actionResponse.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,11 @@ export interface ActionResponseOutcome {
6161
* any with a usable `field`. Only on a failure.
6262
*/
6363
fieldErrors?: ActionFieldError[];
64+
/**
65+
* The refusal's producer-marked user-facing text (`error.userMessage`),
66+
* when it carried one. Only on a failure; `error` stays the whole text.
67+
*/
68+
userMessage?: string;
6469
/**
6570
* The ACTION ENVELOPE (`body.data`) — `{ success, data }`. Kept as-is
6671
* because `ActionResult.data` has always carried this level and
@@ -126,18 +131,36 @@ export function interpretActionResponse(
126131
// string — handing that object to `toast.error()` as a React child
127132
// crashes the page, React #31).
128133
const fieldErrors = refusalFieldErrors(innerFailed ? envelope : json);
134+
const userMessage = refusalUserMessage(innerFailed ? envelope : json);
129135
return {
130136
ok: false,
131137
error: innerFailed
132138
? actionErrorDetail(envelope, `${label} failed`)
133139
: actionErrorDetail(json, `${label} failed (HTTP ${res.status})`),
134140
...(fieldErrors ? { fieldErrors } : {}),
141+
...(userMessage !== undefined ? { userMessage } : {}),
135142
};
136143
}
137144

138145
return { ok: true, envelope, payload: readActionPayload(envelope) };
139146
}
140147

148+
/**
149+
* The producer-marked user-facing text of a refusal body
150+
* (`ApiErrorSchema.userMessage`), as `ActionResult.userMessage` carries it.
151+
* The ADR-0112 envelope carries it beside `message` on the `error` object —
152+
* the `/actions` door answers a thrown `userMessage`, from a script body or a
153+
* server action's handler alike, there. Presence is the marking: a blank or
154+
* non-string value is no marking, and nothing else is promoted into it (the
155+
* same predicate `@objectstack/client` applies when it lifts the field).
156+
* Returned verbatim, untrimmed.
157+
*/
158+
export function refusalUserMessage(body: unknown): string | undefined {
159+
const b = body as { error?: { userMessage?: unknown } } | null | undefined;
160+
const raw = b?.error && typeof b.error === 'object' ? b.error.userMessage : undefined;
161+
return typeof raw === 'string' && raw.trim() ? raw : undefined;
162+
}
163+
141164
/**
142165
* The `fields` list of a refusal body, as `ActionResult.fieldErrors` carries
143166
* it. The ADR-0112 envelope carries the list in one of two members, both on

‎ui/packages/core/src/actions/serverActionHandler.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,7 @@ export function createServerActionHandler(config: ServerActionHandlerConfig): Se
305305
success: false,
306306
error: outcome.error,
307307
...(outcome.fieldErrors ? { fieldErrors: outcome.fieldErrors } : {}),
308+
...(outcome.userMessage !== undefined ? { userMessage: outcome.userMessage } : {}),
308309
};
309310
}
310311
// A declared `operation: 'update'` wrote the record it addresses — that

‎ui/packages/i18n/src/locales/ar.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -589,6 +589,7 @@ const ar = {
589589
succeeded: "نجح {{count}} / {{total}}",
590590
resultFailed: " · فشل {{count}}",
591591
succeededRecords: "السجلات الناجحة",
592+
aggregateNotCompleted: "لم يكتمل الإجراء للسجلات المحددة. ربما تم تغيير بعض السجلات بالفعل. عند الإغلاق تعرض القائمة قيمها الحالية.",
592593
retry: "إعادة المحاولة",
593594
downloadErrorCsv: "تنزيل ملف CSV للأخطاء",
594595
cancel: "إلغاء",

‎ui/packages/i18n/src/locales/de.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -543,6 +543,7 @@ const de = {
543543
succeeded: "Erfolgreich {{count}} / {{total}}",
544544
resultFailed: " · Fehlgeschlagen {{count}}",
545545
succeededRecords: "Erfolgreiche Datensätze",
546+
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.",
546547
retry: "Erneut versuchen",
547548
downloadErrorCsv: "Fehler-CSV herunterladen",
548549
cancel: "Abbrechen",

‎ui/packages/i18n/src/locales/en.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1039,6 +1039,7 @@ const en = {
10391039
succeeded: 'Succeeded {{count}} / {{total}}',
10401040
resultFailed: ' \u00b7 Failed {{count}}',
10411041
succeededRecords: 'Records that succeeded',
1042+
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.',
10421043
retry: 'Retry',
10431044
downloadErrorCsv: 'Download error CSV',
10441045
cancel: 'Cancel',

‎ui/packages/i18n/src/locales/es.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -558,6 +558,7 @@ const es = {
558558
succeeded: "Correctos {{count}} / {{total}}",
559559
resultFailed: " · Fallidos {{count}}",
560560
succeededRecords: "Registros correctos",
561+
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.",
561562
retry: "Reintentar",
562563
downloadErrorCsv: "Descargar CSV de errores",
563564
cancel: "Cancelar",

‎ui/packages/i18n/src/locales/fr.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -553,6 +553,7 @@ const fr = {
553553
succeeded: "Réussis {{count}} / {{total}}",
554554
resultFailed: " · Échecs {{count}}",
555555
succeededRecords: "Enregistrements réussis",
556+
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.",
556557
retry: "Réessayer",
557558
downloadErrorCsv: "Télécharger le CSV d'erreurs",
558559
cancel: "Annuler",

0 commit comments

Comments
 (0)