Skip to content
This repository was archived by the owner on Nov 4, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions .changeset/7252-form-outcome-toast-supersede.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
---
'@object-ui/components': patch
'@object-ui/console': patch
---

A form no longer ends on a screen asserting both a failure and a success (objectui#7252).

A refused submit raised an error toast that nothing ever retired, so when the user
fixed the input and submitted again the confirmation of that second attempt appeared
*beside* the refusal of the first — a wizard's last step showing "Invalid project
status transition." and "Your new project is ready…" at the same time.

Every outcome toast a form raises now travels under one stable per-form id, so the
later outcome supersedes the earlier one instead of stacking beside it:

- `@object-ui/components`' form renderer publishes its three outcome toasts (the
field-level rejection, an `onAction` error, and a rejected write) under that id, and
retires the previous attempt's toast in the same place it already cleared the
previous attempt's in-form banner. This is what fixes the reported wizard flow: the
refusal comes from this renderer while the success toast is raised by the host
(`WizardForm` / `ObjectForm`), so no single raiser could supersede the other before.
- the console's own `FormPage` publishes its confirmation and its submit failure under
one id, for the same reason.

Toast durations are unchanged — this is about supersession, not lifetime. The
objectui#4190 arm is deliberately excluded: a refused redirect *destination* still gets
its own toast, because the write succeeded and that refusal has to stay readable beside
the confirmation it qualifies.
180 changes: 180 additions & 0 deletions apps/console/src/components/FormPage.outcomeToast.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* objectui#7252 — a form never ends on a screen that asserts BOTH outcomes.
*
* The card was filed against the console's WIZARD path, where the refusal and
* the confirmation are raised by two different modules (`@object-ui/components`'
* form renderer and `@object-ui/plugin-form`'s `WizardForm`); that end-to-end
* flow is pinned in
* `packages/plugin-form/src/WizardForm.outcomeToastSupersede.test.tsx`.
*
* This page carried the SAME defect in a single function. `handleSubmit` clears
* the `error` banner at the top of every attempt but published its toast under
* sonner's auto-generated id, so nothing here could retire it: a refused submit
* left its toast up, and the confirmation of the retry landed beside it. Both
* outcomes now travel under one per-form id, so the later one supersedes the
* earlier in place.
*
* ## Why the assertion is a registry rather than a call count
*
* `toast.error` was called and `toast.success` was called is true both before
* and after the fix — it is exactly the reading under which the defect looks
* fine. What the card is about is what remains ON SCREEN, so `sonner` is
* replaced by a registry modelling the one behaviour the fix relies on: raising
* a toast under an id the registry already holds REPLACES that entry.
*
* ## Reverse verification — predicted, then measured
*
* Dropping `{ id: outcomeToastId }` from the two submit-outcome toasts turns
* the first test RED (two entries on screen: the refusal and the confirmation)
* and leaves the second one — which asserts that the redirect refusal is NOT
* folded into that id — green, since it never depended on the id at all.
*/

import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
import { FormPage } from './FormPage';

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 is sonner's auto-id — a NEW toast every time, which is precisely
// the pre-fix behaviour that let two outcomes share the screen.
const id = options?.id ?? `auto:${(auto += 1)}`;
toastRegistry.set(id, { type, message: String(message) });
return id;
};
const fakeToast = {
success: raise('success'),
error: raise('error'),
info: raise('info'),
warning: raise('warning'),
dismiss: (id?: string | number) => {
if (id === undefined) toastRegistry.clear();
else toastRegistry.delete(id);
return id;
},
};
return { toastRegistry, fakeToast };
});

vi.mock('sonner', () => ({ toast: fakeToast }));

/** What the submitter can actually see, in the order sonner holds it. */
const onScreen = (): ToastEntry[] => [...toastRegistry.values()];

const publicPayload = (submitBehavior?: unknown) => ({
slug: 'contact-us',
object: 'showcase_inquiry',
label: 'Contact us',
form: {
type: 'simple',
sections: [{ fields: ['title'] }],
...(submitBehavior ? { submitBehavior } : {}),
},
objectSchema: { name: 'showcase_inquiry', fields: { title: { type: 'text', label: 'Title' } } },
});

/**
* Answers the form resolver, then refuses the first N submits with a 400 the
* way the reported flow was refused, and accepts every one after that.
*/
function stubFetchRefusingFirst(refusals: number, payload: Record<string, unknown>) {
let posts = 0;
return vi.fn(async (url: string, init?: RequestInit) => {
if (init?.method === 'POST') {
posts += 1;
if (posts <= refusals) {
return {
ok: false,
status: 400,
statusText: 'Bad Request',
text: async () => 'Invalid project status transition.',
json: async () => ({ error: 'Invalid project status transition.' }),
} as unknown as Response;
}
return {
ok: true,
status: 201,
statusText: 'Created',
json: async () => ({ object: 'showcase_inquiry', id: 'inq-1', record: { id: 'inq-1' } }),
text: async () => '{}',
} as unknown as Response;
}
if (!String(url).includes('/forms/')) throw new Error(`unstubbed fetch: ${url}`);
return {
ok: true,
status: 200,
statusText: 'OK',
json: async () => payload,
text: async () => JSON.stringify(payload),
} as unknown as Response;
});
}

const renderPublic = () =>
render(
<MemoryRouter initialEntries={['/f/contact-us']}>
<Routes>
<Route path="/f/:slug" element={<FormPage mode="public" />} />
</Routes>
</MemoryRouter>,
);

beforeEach(() => {
toastRegistry.clear();
});

afterEach(() => {
vi.unstubAllGlobals();
});

describe('FormPage — the later submit outcome supersedes the earlier one', () => {
it('leaves only the confirmation after a refused submit is retried and accepted', async () => {
vi.stubGlobal('fetch', stubFetchRefusingFirst(1, publicPayload()));
renderPublic();

await screen.findByLabelText(/Title/);
await userEvent.type(screen.getByLabelText(/Title/), 'Ship it');

await userEvent.click(screen.getByRole('button', { name: /Submit/ }));
await waitFor(() => expect(onScreen()).toHaveLength(1));
expect(onScreen()[0].type).toBe('error');
expect(onScreen()[0].message).toContain('Invalid project status transition.');

// The retry the card describes: same form, same page, and it is accepted.
await userEvent.click(screen.getByRole('button', { name: /Submit/ }));
expect(await screen.findByText('Your submission has been received.')).toBeInTheDocument();

await waitFor(() => expect(onScreen()).toEqual([{ type: 'success', message: 'Submitted' }]));
});

/**
* The objectui#4190 arm is NOT a submit outcome: the write succeeded and only
* the declared destination is out of contract, so its refusal has to stay
* readable BESIDE the confirmation. It therefore keeps its own toast — folding
* it into the shared id would silently delete the confirmation of a write that
* really happened.
*/
it('keeps a refused redirect destination beside the confirmation it qualifies', async () => {
vi.stubGlobal(
'fetch',
stubFetchRefusingFirst(0, publicPayload({ kind: 'redirect', url: 'https://evil.example/x' })),
);
renderPublic();

await screen.findByLabelText(/Title/);
await userEvent.click(screen.getByRole('button', { name: /Submit/ }));

await waitFor(() => expect(onScreen()).toHaveLength(2));
expect(onScreen().map((e) => e.type)).toEqual(['success', 'error']);
});
});
23 changes: 20 additions & 3 deletions apps/console/src/components/FormPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@
* sibling of `@object-ui/plugin-form`'s `omitServerResolvedDefaults`.
*/

import { useEffect, useMemo, useState, type FormEvent } from 'react';
import { useEffect, useId, useMemo, useState, type FormEvent } from 'react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { toast } from 'sonner';
import {
Expand Down Expand Up @@ -1578,6 +1578,23 @@ export function FormPage({ mode, recordPath }: FormPageProps) {
const [loaded, setLoaded] = useState<LoadedForm | null>(null);
const [values, setValues] = useState<Record<string, unknown>>({});
const [submitting, setSubmitting] = useState(false);
/**
* The sonner id this form's submit OUTCOME is published under — one id for
* the confirmation and for the refusal, so the later of the two SUPERSEDES
* the earlier instead of stacking beside it (objectui#7252).
*
* The `error` banner above is already cleared at the top of every attempt;
* its toast was not, because it went out under sonner's auto-generated id and
* nothing here held a handle on it. A refused submit therefore left its toast
* on screen, and the success toast of the retry landed next to it — the form
* ending on a screen that asserted both outcomes at once.
*
* ⚠️ The redirect REFUSAL below deliberately does NOT share this id. That one
* is not a submit outcome: the write succeeded and only the declared
* destination is out of contract, so it has to be readable BESIDE the
* confirmation this id carries, exactly as objectui#4190 ruled.
*/
const outcomeToastId = `form-outcome:${useId()}`;
const [submitted, setSubmitted] = useState(false);
/**
* The outcome of a `redirect` submit behaviour: the in-app route to go to
Expand Down Expand Up @@ -1681,7 +1698,7 @@ export function FormPage({ mode, recordPath }: FormPageProps) {
mode === 'public'
? await submitPublic(identifier, payload)
: await submitInternal(loaded.object, payload, editingId);
toast.success('Submitted');
toast.success('Submitted', { id: outcomeToastId });
// Behaviour after submit
switch (behavior.kind) {
case 'created-record': {
Expand Down Expand Up @@ -1766,7 +1783,7 @@ export function FormPage({ mode, recordPath }: FormPageProps) {
} catch (err: any) {
const msg = err?.message ?? String(err);
setError(msg);
toast.error(msg);
toast.error(msg, { id: outcomeToastId });
} finally {
setSubmitting(false);
}
Expand Down
33 changes: 30 additions & 3 deletions packages/components/src/renderers/form/form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1130,6 +1130,29 @@ ComponentRegistry.register('form',

const [isSubmitting, setIsSubmitting] = React.useState(false);
const [submitError, setSubmitError] = React.useState<string | null>(null);
/**
* The sonner id every OUTCOME toast of THIS form is published under.
*
* The in-form banner (`submitError`) and its toast are raised together at
* each of the three points below, but only the banner was ever retired
* together: the toast went out under sonner's auto-generated id, so nothing
* here held a handle on it and a refused submit's toast outlived the
* attempt that raised it. A later SUCCESSFUL submit — whose success toast a
* host raises (`WizardForm`, `ObjectForm`), not this renderer — then landed
* BESIDE that stale refusal, and the form ended on a screen asserting both
* outcomes at once (objectui#7252).
*
* One stable id closes both halves. Reusing an id sonner already holds
* UPDATES that toast rather than stacking a second one, so every outcome
* this form reports supersedes the one before it; and the dismissal beside
* `setSubmitError(null)` retires it the moment a new attempt starts, so by
* the time any host can confirm a success this form's last refusal is gone.
*
* Scoped to this form instance (`React.useId()`) on purpose: a blanket
* `toast.dismiss()` would take unrelated toasts down with it.
*/
const formInstanceId = React.useId();
const outcomeToastId = `form-outcome:${formInstanceId}`;
// Active `fieldTabs` panel. Undefined until something picks one — the
// effective tab falls back to `defaultFieldTab`, then to the first tab.
// Which tab of an in-progress form is showing is presentational and dies
Expand Down Expand Up @@ -1912,7 +1935,7 @@ ComponentRegistry.register('form',
const fieldsText =
labels.slice(0, MAX).join(t('validation.formInvalidJoiner')) +
(labels.length > MAX ? '…' : '');
toast.error(t('validation.formInvalid', { fields: fieldsText }));
toast.error(t('validation.formInvalid', { fields: fieldsText }), { id: outcomeToastId });

const errored = new Set(names);
const firstName =
Expand Down Expand Up @@ -1948,6 +1971,10 @@ ComponentRegistry.register('form',
const handleSubmit = form.handleSubmit(async (data) => {
setIsSubmitting(true);
setSubmitError(null);
// …and the toast twin of that banner (objectui#7252). Both belong to the
// previous attempt and both are stale now; the toast outliving it is what
// let an earlier refusal share the screen with the success that followed.
toast.dismiss(outcomeToastId);
// This attempt cleared client validation — drop the previous attempt's
// tab markers (the server may re-add its own below).
setRejectedFieldNames([]);
Expand Down Expand Up @@ -1999,7 +2026,7 @@ ComponentRegistry.register('form',
setSubmitError(result.error);
// Also surface as a toast so the message is visible even when the
// in-form banner has scrolled out of view (long forms in modals/drawers).
toast.error(result.error);
toast.error(result.error, { id: outcomeToastId });
return;
}
}
Expand Down Expand Up @@ -2069,7 +2096,7 @@ ComponentRegistry.register('form',
setSubmitError(errorMessage);
// Also surface as a toast so the message is visible even when the
// in-form banner has scrolled out of view (long forms in modals/drawers).
toast.error(errorMessage);
toast.error(errorMessage, { id: outcomeToastId });

// Log errors for debugging (dev environment only)
// process may not be defined in all environments
Expand Down
Loading
Loading