From 1c0b4d5be17737f6475c5b53ba12267342263fbb Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Sep 2026 12:33:05 +0000 Subject: [PATCH 1/2] fix(plugin-form): a later master-detail save outcome supersedes the earlier one (#7345) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MasterDetailForm raised its two save outcomes as two unrelated toasts: handleSaved's confirmation and handleError's refusal, each under sonner's auto-generated id. Nothing held a handle on the previous attempt's toast, so a save the server refused left its error on screen and the confirmation of the corrected retry landed beside it — the form ending on a screen that asserted both outcomes at once. This is the objectui#7252 defect class on a renderer PR #7342 did not touch: its surface was the SDUI form renderer and the console's FormPage, and both outcomes here are raised by this file, one line apart. Both now travel under one stable per-form id (React.useId()-scoped, "form-outcome:" + the id — the spelling #7342 landed), and each save attempt dismisses that id before it starts. The two halves close two different paths: - no host onSuccess (SDUI / embedded): the built-in confirmation is the fallback, and the shared id makes it supersede the refusal rather than stack beside it; - host onSuccess (the console): the built-in confirmation is deliberately skipped, so a shared id alone would retire nothing — the dismissal is what stops a stale refusal from standing over a save that succeeded. Measured, not assumed: the pin fails on that path with the id alone. Durations are untouched — the defect is supersession, and it reproduces inside any lifetime. Measured while pinning this and deliberately NOT changed here: a refused master-detail save currently puts the same refusal on screen twice, because the parent ObjectForm's renderer also toasts the write it re-threw. That is a distinct defect from supersession and is filed separately; the pin is written so its assertions do not depend on how many raisers report an outcome. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01NRRumy89BYdW9ogbcdHTho --- .../7345-master-detail-outcome-toast.md | 25 ++ ...rDetailForm.outcomeToastSupersede.test.tsx | 258 ++++++++++++++++++ packages/plugin-form/src/MasterDetailForm.tsx | 41 ++- 3 files changed, 319 insertions(+), 5 deletions(-) create mode 100644 .changeset/7345-master-detail-outcome-toast.md create mode 100644 packages/plugin-form/src/MasterDetailForm.outcomeToastSupersede.test.tsx diff --git a/.changeset/7345-master-detail-outcome-toast.md b/.changeset/7345-master-detail-outcome-toast.md new file mode 100644 index 0000000000..692b9175e3 --- /dev/null +++ b/.changeset/7345-master-detail-outcome-toast.md @@ -0,0 +1,25 @@ +--- +'@object-ui/plugin-form': patch +--- + +A master-detail form no longer ends on a screen asserting both a failure and a success +(objectui#7345). + +`MasterDetailForm` raised its two save outcomes — `handleSaved`'s confirmation and +`handleError`'s refusal — under sonner's auto-generated ids, so nothing held a handle on +the previous attempt's toast. A save the server refused left its error toast on screen, +and when the user corrected the input and saved again inside that toast's lifetime the +confirmation landed *beside* the refusal, exactly the objectui#7252 defect on a renderer +that fix did not touch. + +Both outcomes now travel under one stable per-form id (`React.useId()`-scoped, the same +spelling the form renderer and the console's `FormPage` publish under), and each save +attempt retires the previous attempt's toast before it starts: + +- with no host `onSuccess` (SDUI / embedded hosts), the confirmation supersedes the + refusal instead of stacking beside it; +- with a host `onSuccess` (the console), where the built-in confirmation is deliberately + skipped, the dismissal is what retires the refusal — otherwise it stood over a save + that had succeeded. + +Toast durations are unchanged: this is about supersession, not lifetime. diff --git a/packages/plugin-form/src/MasterDetailForm.outcomeToastSupersede.test.tsx b/packages/plugin-form/src/MasterDetailForm.outcomeToastSupersede.test.tsx new file mode 100644 index 0000000000..4d0a4afd04 --- /dev/null +++ b/packages/plugin-form/src/MasterDetailForm.outcomeToastSupersede.test.tsx @@ -0,0 +1,258 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * A master-detail form never ends on a screen that asserts BOTH outcomes + * (objectui#7345 — the objectui#7252 defect class, on a renderer PR #7342 did + * not touch). + * + * ## Where the two toasts come from here + * + * Unlike the wizard (whose refusal came from the step renderer and whose + * success came from `WizardForm`), BOTH outcomes of a master-detail save are + * raised by `MasterDetailForm` itself, one line apart: + * + * - `handleSaved` -> `toast.success('Created' | ' saved')`; + * - `handleError` -> `toast.error(err.message || 'Save failed')`. + * + * Neither carried a sonner id, so each went out under sonner's auto-generated + * one and nothing here held a handle on the previous attempt's toast. A save + * the server refused left its error toast on screen, and the confirmation of + * the corrected retry landed BESIDE it. + * + * ## The two paths, and why both are pinned + * + * 1. **No host `onSuccess`** (SDUI / embedded): the built-in success toast is + * the fallback, so the shared id is what makes the confirmation SUPERSEDE + * the refusal instead of stacking beside it. + * 2. **Host supplies `onSuccess`** (the console): the built-in success toast is + * deliberately skipped, so a shared id alone would retire nothing — the + * refusal would outlive a save that SUCCEEDED. The `toast.dismiss` at the + * start of each attempt is what closes that half, which is why it is part of + * the shape and not decoration. + * + * The parent `<ObjectForm>`'s own renderer also toasts a rejected write, under + * its OWN `form-outcome:` id, and retires it at the top of the next submit + * (objectui#7252). That toast is therefore already superseded and is not what + * this file pins; it is visible in the pre-fix registry below as the second + * error entry. + * + * ## Why the pin models sonner rather than counting calls + * + * Asserting `toast.error` was called and `toast.success` was called says + * nothing about what is on SCREEN — that is exactly the reading under which the + * defect looks fine. So the module is replaced by a registry modelling the one + * sonner behaviour the fix relies on: a toast raised under an id the registry + * already holds REPLACES that entry, and `dismiss(id)` removes exactly that + * one. The assertion is then the card's own sentence — what remains on screen. + * + * ⚠️ The mock target is `@object-ui/components/ui/sonner`, NOT bare `'sonner'`. + * That wrapper is the single module every raiser here reaches — the `toast` + * `MasterDetailForm` pulls from `@object-ui/components` is this module's + * re-export (`src/index.ts` -> `export * from './ui'` -> `./ui/sonner`) — and + * it is the only one of the two spellings that resolves from here: + * `plugin-form` does not depend on `sonner`, so `vi.mock('sonner')` in this + * package registers against an id nothing resolves to and intercepts NOTHING. + * A green run here is therefore also the proof that the mock is in the graph. + */ + +import React from 'react'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react'; + +type ToastEntry = { type: string; message: string }; + +const { toastRegistry, fakeToast } = vi.hoisted(() => { + const toastRegistry = new Map<string | number, { type: string; message: string }>(); + let auto = 0; + const raise = + (type: string) => + (message: unknown, options?: { id?: string | number }) => { + // No id supplied is sonner's auto-id: a NEW toast every time, which is + // precisely the pre-fix behaviour that let two outcomes coexist. + const id = options?.id ?? `auto:${(auto += 1)}`; + toastRegistry.set(id, { type, message: String(message) }); + return id; + }; + const fakeToast: any = Object.assign(raise('message'), { + success: raise('success'), + error: raise('error'), + info: raise('info'), + warning: raise('warning'), + loading: raise('loading'), + custom: raise('custom'), + promise: (p: unknown) => p, + dismiss: (id?: string | number) => { + if (id === undefined) toastRegistry.clear(); + else toastRegistry.delete(id); + return id; + }, + }); + return { toastRegistry, fakeToast }; +}); + +vi.mock('@object-ui/components/ui/sonner', async (importOriginal) => { + const actual = await importOriginal<any>(); + return { ...actual, toast: fakeToast }; +}); + +import { registerAllFields } from '@object-ui/fields'; +import { MasterDetailForm } from './MasterDetailForm'; + +registerAllFields(); + +const REFUSAL = 'Line 2 quantity exceeds the remaining allocation.'; + +const parentObjectSchema = { name: 'po', fields: { ref: { type: 'text', label: 'Ref' } } }; + +/** Refuses the first save the way the server did, accepts the second. */ +const makeDataSource = (overrides: Record<string, unknown> = {}) => { + let saves = 0; + return { + getObjectSchema: vi.fn().mockResolvedValue(parentObjectSchema), + find: vi.fn().mockResolvedValue({ data: [] }), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + bulk: vi.fn(), + batchTransaction: vi.fn(async () => { + saves += 1; + if (saves === 1) { + throw Object.assign(new Error(REFUSAL), { status: 400, code: 'VALIDATION_FAILED' }); + } + return { results: [{ id: 'po1' }] }; + }), + ...overrides, + } as any; +}; + +const masterDetail = (dataSource: any, extraSchema: Record<string, unknown> = {}) => + render( + <MasterDetailForm + schema={ + { + type: 'object-master-detail-form', + objectName: 'po', + mode: 'create', + fields: ['ref'], + details: [ + { + childObject: 'po_line', + relationshipField: 'po', + columns: [{ key: 'qty', label: 'Qty', type: 'number' } as any], + }, + ], + ...extraSchema, + } as any + } + dataSource={dataSource as any} + />, + ); + +const headerInput = (container: HTMLElement) => + waitFor(() => { + const el = container.querySelector('input[name="ref"]') as HTMLInputElement | null; + if (!el) throw new Error('parent form not ready'); + return el; + }); + +/** Drive the bottom action bar's single Save/Create button. */ +const save = () => fireEvent.click(screen.getByRole('button', { name: /create/i })); + +/** What the user can actually see, in the order sonner holds it. */ +const onScreen = (): ToastEntry[] => [...toastRegistry.values()]; + +/** + * What the screen SAYS, with each distinct statement counted once. + * + * Measured, not assumed: a refused master-detail save currently puts the SAME + * refusal on screen twice — `handleError` here raises one, and the parent + * `<ObjectForm>`'s renderer raises its own for the write it re-threw. That + * duplication is a separate defect from the one this file pins (it is filed + * out of scope), so the assertions below deliberately do not depend on HOW MANY + * raisers reported an outcome — only on WHICH outcomes remain readable. + */ +const distinctOnScreen = (): ToastEntry[] => { + const seen = new Map<string, ToastEntry>(); + for (const t of onScreen()) seen.set(`${t.type}:${t.message}`, t); + return [...seen.values()]; +}; + +beforeEach(() => { + toastRegistry.clear(); +}); + +afterEach(() => { + cleanup(); +}); + +describe('MasterDetailForm — a later save outcome supersedes this form’s earlier one', () => { + it('leaves only the success toast after a refused save is retried and accepted', async () => { + const ds = makeDataSource(); + const { container } = masterDetail(ds); + + fireEvent.change(await headerInput(container), { target: { value: 'PO-1' } }); + save(); + await waitFor(() => expect(ds.batchTransaction).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(distinctOnScreen()).toEqual([{ type: 'error', message: REFUSAL }])); + + // The user corrects the input and saves again inside the refusal's lifetime. + fireEvent.change(await headerInput(container), { target: { value: 'PO-1b' } }); + save(); + await waitFor(() => expect(ds.batchTransaction).toHaveBeenCalledTimes(2)); + + // The card's own sentence: one form, one outcome on screen. + await waitFor(() => expect(onScreen()).toEqual([{ type: 'success', message: 'Created' }])); + }); + + it('retires the refusal even when the host owns confirmation (no built-in success toast)', async () => { + // The console path: `onSuccess` is supplied, so the built-in success toast + // is deliberately skipped. A shared id alone would retire NOTHING here — + // the refusal of the first attempt would outlive a save that succeeded. + // The dismissal at the start of each attempt is what closes this half. + const onSuccess = vi.fn(); + const ds = makeDataSource(); + const { container } = masterDetail(ds, { onSuccess }); + + fireEvent.change(await headerInput(container), { target: { value: 'PO-2' } }); + save(); + await waitFor(() => expect(ds.batchTransaction).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(distinctOnScreen()).toEqual([{ type: 'error', message: REFUSAL }])); + + fireEvent.change(await headerInput(container), { target: { value: 'PO-2b' } }); + save(); + await waitFor(() => expect(ds.batchTransaction).toHaveBeenCalledTimes(2)); + await waitFor(() => expect(onSuccess).toHaveBeenCalled()); + + // Nothing left asserting the save was refused. + await waitFor(() => expect(onScreen()).toEqual([])); + }); + + it('does not stack a second refusal when the retry is refused too', async () => { + const ds = makeDataSource({ + batchTransaction: vi.fn(async () => { + throw Object.assign(new Error(REFUSAL), { status: 400, code: 'VALIDATION_FAILED' }); + }), + }); + const { container } = masterDetail(ds); + + fireEvent.change(await headerInput(container), { target: { value: 'PO-3' } }); + save(); + await waitFor(() => expect(ds.batchTransaction).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(distinctOnScreen()).toEqual([{ type: 'error', message: REFUSAL }])); + // How many raisers reported this refusal is not this file's subject; that + // the SECOND attempt adds none of its own is. + const afterFirstAttempt = onScreen().length; + + fireEvent.change(await headerInput(container), { target: { value: 'PO-3b' } }); + save(); + await waitFor(() => expect(ds.batchTransaction).toHaveBeenCalledTimes(2)); + await waitFor(() => expect(distinctOnScreen()).toEqual([{ type: 'error', message: REFUSAL }])); + expect(onScreen()).toHaveLength(afterFirstAttempt); + }); +}); diff --git a/packages/plugin-form/src/MasterDetailForm.tsx b/packages/plugin-form/src/MasterDetailForm.tsx index a9c54d1a83..299df451c5 100644 --- a/packages/plugin-form/src/MasterDetailForm.tsx +++ b/packages/plugin-form/src/MasterDetailForm.tsx @@ -714,6 +714,31 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({ const [saving, setSaving] = useState(false); const savingRef = useRef(false); const saveGuardTimer = useRef<ReturnType<typeof setTimeout> | null>(null); + /** + * The sonner id BOTH save outcomes of THIS form are published under. + * + * `handleSaved` and `handleError` below each raised their toast under + * sonner's auto-generated id, so nothing here held a handle on the previous + * attempt's. A save the server refused left its error toast on screen, and + * when the user corrected the input and saved again inside that toast's + * lifetime the confirmation landed BESIDE the refusal — the form ending on a + * screen that asserted both outcomes at once (objectui#7345, the + * objectui#7252 defect class). + * + * One stable id closes both halves. Reusing an id sonner already holds + * UPDATES that toast rather than stacking a second one, so the later outcome + * supersedes the earlier; and the dismissal at the top of `handleSave` + * retires it the moment a new attempt starts — which is the half that matters + * when a host supplies `onSuccess`, because the built-in confirmation is then + * skipped and a shared id alone would leave the stale refusal standing over a + * save that succeeded. + * + * Scoped to this form instance (`React.useId()`) on purpose: a blanket + * `toast.dismiss()` would take unrelated toasts down with it. Same spelling + * the form renderer and the console's `FormPage` publish under (#7342). + */ + const formInstanceId = React.useId(); + const outcomeToastId = `form-outcome:${formInstanceId}`; const releaseSave = useCallback(() => { savingRef.current = false; setSaving(false); @@ -828,7 +853,9 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({ async (parent: any) => { releaseSave(); if (!schema.onSuccess) { - toast.success(isEdit ? (schema.title ? `${schema.title} saved` : 'Saved') : 'Created'); + toast.success(isEdit ? (schema.title ? `${schema.title} saved` : 'Saved') : 'Created', { + id: outcomeToastId, + }); } if (!isEdit) { // Every collection back to empty for the next entry. Dropping the whole @@ -840,17 +867,17 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({ await schema.onSuccess?.(parent); }, // eslint-disable-next-line react-hooks/exhaustive-deps - [isEdit, schema.onSuccess, schema.title, entries.length, releaseSave], + [isEdit, schema.onSuccess, schema.title, entries.length, releaseSave, outcomeToastId], ); /** Surface failures (validation / network / atomic rollback) to the user. */ const handleError = useCallback( (err: Error) => { releaseSave(); - toast.error(err?.message || 'Save failed'); + toast.error(err?.message || 'Save failed', { id: outcomeToastId }); schema.onError?.(err); }, - [schema, releaseSave], + [schema, releaseSave, outcomeToastId], ); // Persistence ALWAYS goes through dataSource.batchTransaction: the parent and @@ -950,6 +977,10 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({ if (!form) return; savingRef.current = true; setSaving(true); + // The previous attempt's outcome belongs to the previous attempt: retire it + // the moment a new one starts, so no host can confirm a success while this + // form's last refusal is still on screen (objectui#7345). + toast.dismiss(outcomeToastId); // IMPORTANT: defer the submit out of this click's React dispatch AND // re-query the <form> inside the timer. Calling requestSubmit() // synchronously inside the onClick (or on a form reference captured before @@ -965,7 +996,7 @@ export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({ // onSuccess/onError, which would otherwise leave the button stuck. Release // the guard after a beat so the user can correct fields and retry. saveGuardTimer.current = setTimeout(() => releaseSave(), 1500); - }, [releaseSave]); + }, [releaseSave, outcomeToastId]); useEffect(() => () => { if (saveGuardTimer.current) clearTimeout(saveGuardTimer.current); }, []); From 2cb1f6ac1ca28005a9d32d5c15198da603dad406 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Wed, 2 Sep 2026 13:04:18 +0000 Subject: [PATCH 2/2] test(plugin-form): let the toast doubles inherit sonner's surface MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four fixtures replaced the whole `toast` export with a hand-listed object carrying only `success` and `error`. The moment MasterDetailForm called one more sonner method, every test that mounts it died with "toast.dismiss is not a function" — 16 failures across 4 files, none of them about what those files assert. This is the check:vi-mock-inherit defect one level down: those factories already spread the real module (`...actual`), but froze the export surface again inside `toast`. Spreading `actual.toast` and overriding only the two methods each file spies on closes the class rather than this one method — the next sonner call the form makes cannot break them either. No assertion changes. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NRRumy89BYdW9ogbcdHTho --- packages/plugin-form/src/MasterDetailForm.test.tsx | 6 +++++- .../plugin-form/src/masterDetailFormTypeVocabulary.test.tsx | 4 +++- packages/plugin-form/src/submitHandlerSeam.test.tsx | 3 +++ packages/plugin-form/src/submitTargetRefusal.test.tsx | 3 +++ 4 files changed, 14 insertions(+), 2 deletions(-) diff --git a/packages/plugin-form/src/MasterDetailForm.test.tsx b/packages/plugin-form/src/MasterDetailForm.test.tsx index 7f9ac8afde..7a5e8433b4 100644 --- a/packages/plugin-form/src/MasterDetailForm.test.tsx +++ b/packages/plugin-form/src/MasterDetailForm.test.tsx @@ -8,7 +8,11 @@ import { MasterDetailForm } from './MasterDetailForm'; const { toastSuccess, toastError } = vi.hoisted(() => ({ toastSuccess: vi.fn(), toastError: vi.fn() })); vi.mock('@object-ui/components', async (orig) => { const actual = await (orig as any)(); - return { ...actual, toast: { success: toastSuccess, error: toastError } }; + // Inherit the real toast surface and override only what this file asserts: + // a hand-listed double freezes sonner's methods at whatever was typed that + // day, and the next one the form calls (`dismiss`, objectui#7345) resolves + // to undefined — the `check:vi-mock-inherit` defect, one level down. + return { ...actual, toast: { ...actual.toast, success: toastSuccess, error: toastError } }; }); registerAllFields(); diff --git a/packages/plugin-form/src/masterDetailFormTypeVocabulary.test.tsx b/packages/plugin-form/src/masterDetailFormTypeVocabulary.test.tsx index 8f0fa0683b..83eafcdc34 100644 --- a/packages/plugin-form/src/masterDetailFormTypeVocabulary.test.tsx +++ b/packages/plugin-form/src/masterDetailFormTypeVocabulary.test.tsx @@ -70,7 +70,9 @@ import './index'; vi.mock('@object-ui/components', async (orig) => { const actual = await (orig as any)(); - return { ...actual, toast: { success: vi.fn(), error: vi.fn() } }; + // Inherit the real toast surface (see MasterDetailForm.test.tsx): a + // hand-listed double leaves every other sonner method undefined. + return { ...actual, toast: { ...actual.toast, success: vi.fn(), error: vi.fn() } }; }); registerAllFields(); diff --git a/packages/plugin-form/src/submitHandlerSeam.test.tsx b/packages/plugin-form/src/submitHandlerSeam.test.tsx index d6aa40b738..4ca631ee2b 100644 --- a/packages/plugin-form/src/submitHandlerSeam.test.tsx +++ b/packages/plugin-form/src/submitHandlerSeam.test.tsx @@ -61,7 +61,10 @@ vi.mock('@object-ui/components', async (orig) => { const actual = await (orig as any)(); return { ...actual, + // Inherit the real toast surface and override only what this file spies + // on — a hand-listed double leaves every other sonner method undefined. toast: { + ...actual.toast, success: (...a: any[]) => toastSuccess(...a), error: (...a: any[]) => toastError(...a), }, diff --git a/packages/plugin-form/src/submitTargetRefusal.test.tsx b/packages/plugin-form/src/submitTargetRefusal.test.tsx index 166453315e..64986a26f2 100644 --- a/packages/plugin-form/src/submitTargetRefusal.test.tsx +++ b/packages/plugin-form/src/submitTargetRefusal.test.tsx @@ -87,7 +87,10 @@ vi.mock('@object-ui/components', async (orig) => { const actual = await (orig as any)(); return { ...actual, + // Inherit the real toast surface and override only what this file spies + // on — a hand-listed double leaves every other sonner method undefined. toast: { + ...actual.toast, success: (...a: any[]) => toastSuccess(...a), error: (...a: any[]) => toastError(...a), },