fix(forms): give sign-in, forbidden and retry-later save failures their own state (08-01)

Every non-input save failure became "unavailable" under the "review the entered
information" summary, with no sign-in button. useAppForm now reports
reauth-required, forbidden and retry-later with the failure, and
FormFailureStatus shows each one's copy and action outside ErrorSummary.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-09-25 22:22:58 +09:00
co-authored by Claude Opus 5.5
parent 2afee67150
commit 9894a70f04
12 changed files with 217 additions and 4 deletions
@@ -18,7 +18,8 @@ field orchestration까지 플랫폼 기본값으로 고정하게 된다.
2. Zod presentation schema, application command mapper와 domain invariant는 서로
다른 소유물로 유지한다.
3. page와 feature는 `useAppForm`, `Form`, `FormField`, `ErrorSummary`,
`mapValidationFailureToFields`, `useDirtyNavigationGuard`만 사용한다.
`FormFailureStatus`, `mapValidationFailureToFields`, `useDirtyNavigationGuard`만
사용한다.
4. 422 details는 승인된 `path`와 `code`만 HTTP 경계에서 투영한다. backend
message와 알 수 없는 field는 field에 전달하지 않고 안전한 form-level
error로 이동한다.
@@ -27,6 +28,15 @@ field orchestration까지 플랫폼 기본값으로 고정하게 된다.
dirty 상태를 해제한다.
7. `StandardPage`, `CollectionPage`, `DetailPage`, `FormPage`, `StatusPage`는
layout과 state slot만 소유하며 application/query/HTTP를 import하지 않는다.
8. (2026-09-25, 08-01) 입력 오류가 아닌 저장 실패는 ErrorSummary에 넣지 않는다.
`useAppForm`은 `action: "reauth"`를 `reauth-required`, `FORBIDDEN`을 `forbidden`,
`action: "retry"`를 `retry-later`로 구분하고 그 실패를 `failure`로 낸다. 화면은
`FormFailureStatus`로 문구와 행동(로그인·이동·다시 시도)을 보여 준다. 재로그인은
입력을 지운다는 안내를 버튼 앞에 둔다(`src/presentation/forms/use-app-form.ts`,
`form-components.tsx`).
9. (2026-09-25, 03-01) 결과 불명 저장은 사용자가 "변경되지 않음"을 판정하지 않는다.
`resendUnknown(mutation.resendUnknownEffect)`로 같은 intent·같은
`Idempotency-Key`를 다시 보낸다(`src/presentation/adapters/query/application-query.ts`).
## React Hook Form 도입 조건
@@ -597,6 +597,7 @@ Form 또는 TanStack Form adapter를 평가한다.
- `Description`
- `FieldError`
- `ErrorSummary`
- `FormFailureStatus` (재로그인·권한 없음·잠시 후 재시도 저장 실패)
- `useAppForm`
- `mapValidationFailureToFields`
- `useDirtyNavigationGuard`
@@ -620,6 +621,7 @@ backend message와 알 수 없는 path는 field copy로 사용하지 않는다.
3. submitting 중 중복 제출 방지
4. 422 응답의 알려진 field만 표시하고 나머지는 form-level failure로 처리
5. 409 conflict는 validation error로 위장하지 않음
5a. 401·403·429 같은 입력 외 실패는 ErrorSummary가 아니라 `FormFailureStatus`로 표시
6. 취소와 route 이탈 시 dirty policy 적용
7. form value → application command mapper를 별도 함수로 둠
8. browser autofill, IME composition, paste, password manager를 방해하지 않음
@@ -8,6 +8,7 @@ import {
ErrorSummary,
Form,
FormActions,
FormFailureStatus,
FormPage,
FormField,
useAppForm,
@@ -21,6 +22,7 @@ import {
toCreateReferenceCommand,
type ReferenceResourceFormValues,
} from "./reference-resource-form.ts";
import { useReferenceFailureAction } from "./use-reference-failure-action.ts";
import { useReferenceCreate } from "./use-reference-feature.ts";
const FIELD_LABELS = Object.freeze({
@@ -44,6 +46,7 @@ export default function ReferenceResourceFormPage() {
mapToCommand: toCreateReferenceCommand,
submit,
});
const failureAction = useReferenceFailureAction(form.failure ?? undefined);
const mutationEffectUnknown =
mutation.state.indicator === "mutation-effect-unknown";
const mutationBlocked =
@@ -129,7 +132,16 @@ export default function ReferenceResourceFormPage() {
</FormActions>
}
feedback={
mutationEffectUnknown ? (
form.failure ? (
<FormFailureStatus
failure={form.failure}
onAction={
form.result === "retry-later"
? () => void form.submitForm()
: failureAction
}
/>
) : mutationEffectUnknown ? (
<>
<AsyncSurface
state={mutation.state}
@@ -55,12 +55,15 @@ export type TerminalErrorSurfaceProps = Readonly<{
userMessageKey: string;
action: AppFailure["action"];
onAction?: () => void;
/** Read before the action, inside the same alert. */
description?: string;
}>;
export function TerminalErrorSurface({
userMessageKey,
action,
onAction,
description,
}: TerminalErrorSurfaceProps) {
const { locale, message } = useLocale();
const messageId = useId();
@@ -81,6 +84,7 @@ export function TerminalErrorSurface({
data-message-key={userMessageKey}
>
<h2 id={messageId}>{errorMessage(userMessageKey, locale)}</h2>
{description ? <p>{description}</p> : null}
{action !== "none" && onAction && (
<Button onClick={onAction}>{actionLabels[action]}</Button>
)}
+1
View File
@@ -136,6 +136,7 @@ export {
ErrorSummary,
Form,
FormActions,
FormFailureStatus,
FormField,
useAppForm,
useDirtyNavigationGuard,
@@ -1,5 +1,7 @@
import { useId, type FormHTMLAttributes, type ReactNode } from "react";
import type { AppFailure } from "../../contracts/errors.ts";
import { TerminalErrorSurface } from "../components/async-surface.tsx";
import { TextField } from "../components/ui/text-field.ts";
import { useLocale } from "../i18n/index.ts";
import type {
@@ -78,6 +80,33 @@ export function ErrorSummary<Values extends FormValues>(props: Readonly<{
);
}
/**
* 08-01. A save that failed for a reason other than the input (sign-in,
* permission, retry later) is announced here with its own action, not in
* ErrorSummary. Pass `useAppForm().failure`.
*/
export function FormFailureStatus(props: Readonly<{
failure: AppFailure | null;
onAction?: () => void;
}>) {
const { message } = useLocale();
const { failure, onAction } = props;
if (!failure) return null;
return (
<TerminalErrorSurface
userMessageKey={failure.userMessageKey}
action={failure.action}
onAction={onAction}
// Signing in remounts the scope, so the entered values do not survive.
description={
failure.action === "reauth"
? message("form.reauthLosesInput")
: undefined
}
/>
);
}
export function FormActions(props: Readonly<{
children: ReactNode;
sticky?: boolean;
+4
View File
@@ -19,6 +19,10 @@ export type FormResultState =
| "validation-error"
| "conflict"
| "effect-unknown"
/** 08-01. Not input errors: shown by `FormFailureStatus`, never ErrorSummary. */
| "reauth-required"
| "forbidden"
| "retry-later"
| "unavailable";
export type MappedValidationFailure<Values extends FormValues> = Readonly<{
+26
View File
@@ -9,6 +9,7 @@ import {
} from "react";
import { flushSync } from "react-dom";
import type { ZodType, ZodIssue } from "zod";
import type { AppFailure } from "../../contracts/errors.ts";
import {
useLocale,
type ParameterlessMessageKey,
@@ -64,6 +65,7 @@ export function useAppForm<
const [formErrors, setFormErrors] = useState<readonly string[]>([]);
const [pending, setPending] = useState(false);
const [result, setResult] = useState<FormResultState>("idle");
const [statusFailure, setStatusFailure] = useState<AppFailure | null>(null);
const pendingRef = useRef<Promise<FormResult<Output> | null> | null>(null);
const unknownSubmissionRef = useRef<Values | null>(null);
@@ -192,6 +194,12 @@ export function useAppForm<
setFormErrors(mapped.formErrors);
setResult("validation-error");
focusFirstError(mapped.fieldErrors);
} else if (outcome.error.action === "reauth") {
// D-2. Signing in again comes first, whatever the effect.
unknownSubmissionRef.current = null;
setFormErrors([]);
setStatusFailure(outcome.error);
setResult("reauth-required");
} else if (outcome.error.effect === "MAYBE_APPLIED") {
unknownSubmissionRef.current = submittedValues;
setFormErrors([]);
@@ -204,6 +212,16 @@ export function useAppForm<
message("form.conflict"),
]);
setResult("conflict");
} else if (
outcome.error.kind === "FORBIDDEN" ||
outcome.error.action === "retry"
) {
unknownSubmissionRef.current = null;
setFormErrors([]);
setStatusFailure(outcome.error);
setResult(
outcome.error.kind === "FORBIDDEN" ? "forbidden" : "retry-later",
);
} else {
unknownSubmissionRef.current = null;
setFormErrors([message("form.unavailable")]);
@@ -317,6 +335,8 @@ export function useAppForm<
formErrors,
pending,
result,
/** The save failure behind `reauth-required`, `forbidden` or `retry-later`. */
failure: STATUS_RESULTS.has(result) ? statusFailure : null,
field,
fieldId,
focusField,
@@ -329,6 +349,12 @@ export function useAppForm<
});
}
const STATUS_RESULTS: ReadonlySet<FormResultState> = new Set([
"reauth-required",
"forbidden",
"retry-later",
]);
function issuesToFieldErrors<Values extends FormValues>(
issues: readonly ZodIssue[],
allowedFields: readonly FieldName<Values>[],
+4
View File
@@ -125,6 +125,8 @@ const PLATFORM_KO_MESSAGES = {
"form.conflict":
"다른 변경과 충돌했습니다. 입력은 유지되었으니 최신 상태를 확인해 주세요.",
"form.unavailable": "저장하지 못했습니다. 잠시 후 다시 시도해 주세요.",
"form.reauthLosesInput":
"다시 로그인하면 이 화면에 입력한 내용은 사라집니다. 필요하면 먼저 복사해 두세요.",
"form.remaining": "{count}자 남음",
"toast.region": "알림",
"error.network_unreachable": "네트워크에 연결할 수 없습니다.",
@@ -283,6 +285,8 @@ const PLATFORM_EN_MESSAGES = {
"form.conflict":
"Another update conflicts with this change. Your input has been preserved.",
"form.unavailable": "The change could not be saved. Try again shortly.",
"form.reauthLosesInput":
"Signing in again clears what you entered on this page. Copy it first if you need it.",
"form.remaining": "{count} characters remaining",
"toast.region": "Notifications",
"error.network_unreachable": "The network is unavailable.",
+65
View File
@@ -13,6 +13,7 @@ import {
DirtyNavigationDialog,
ErrorSummary,
Form,
FormFailureStatus,
FormField,
useAppForm,
useDirtyNavigationGuard,
@@ -34,6 +35,7 @@ function FormHarness(props: Readonly<{
| Readonly<{ ok: false; error: ReturnType<typeof createFailure> }>
>;
resetOnSuccess?: boolean;
onFailureAction?(): void;
}>) {
const form = useAppForm({
schema,
@@ -57,6 +59,14 @@ function FormHarness(props: Readonly<{
fieldId={form.fieldId}
onFocusField={form.focusField}
/>
<FormFailureStatus
failure={form.failure}
onAction={
form.result === "retry-later"
? () => void form.submitForm()
: props.onFailureAction
}
/>
<FormField {...form.field("name")} label="Name" required />
<FormField {...form.field("note")} label="Note" />
<Button type="submit" disabled={form.pending}>
@@ -137,6 +147,61 @@ describe("local form facade", () => {
expect(document.body).not.toHaveTextContent("raw-secret-message");
});
it.each([
[
"AUTH_REQUIRED",
"reauth-required",
"계속하려면 로그인이 필요합니다.",
"로그인",
],
[
"FORBIDDEN",
"forbidden",
"이 작업을 수행할 권한이 없습니다.",
"안전한 화면으로 이동",
],
[
"RATE_LIMITED",
"retry-later",
"요청이 많습니다. 잠시 후 다시 시도해 주세요.",
"다시 시도",
],
] as const)(
"shows %s as its own save state, not an input error",
async (kind, result, copy, action) => {
const user = userEvent.setup();
const onFailureAction = vi.fn();
const submit = vi.fn(async () => ({
ok: false as const,
error: createFailure(kind, "CREATE_ENTITY", 0, {
effect: "NOT_APPLIED",
}),
}));
render(
<FormHarness submit={submit} onFailureAction={onFailureAction} />,
);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Valid");
await user.click(screen.getByRole("button", { name: "Submit" }));
expect(await screen.findByTestId("result")).toHaveTextContent(result);
expect(screen.getByRole("alert")).toHaveTextContent(copy);
expect(document.body).not.toHaveTextContent("입력 내용을 확인해 주세요.");
expect(document.body).not.toHaveTextContent("저장하지 못했습니다.");
expect(
document.body.textContent?.includes("입력한 내용은 사라집니다"),
).toBe(kind === "AUTH_REQUIRED");
expect(screen.getByRole("textbox", { name: /Name/ })).toHaveValue("Valid");
await user.click(screen.getByRole("button", { name: action }));
if (kind === "RATE_LIMITED") {
expect(submit).toHaveBeenCalledTimes(2);
expect(onFailureAction).not.toHaveBeenCalled();
} else {
expect(onFailureAction).toHaveBeenCalledOnce();
}
},
);
it("keeps conflict input out of URL and storage", async () => {
const user = userEvent.setup();
localStorage.clear();
@@ -393,6 +393,61 @@ describe("reference feature page states", () => {
expect(name).toHaveValue("");
});
it.each([
["AUTH_REQUIRED", "계속하려면 로그인이 필요합니다.", "로그인"],
["FORBIDDEN", "이 작업을 수행할 권한이 없습니다.", "안전한 화면으로 이동"],
["RATE_LIMITED", "요청이 많습니다. 잠시 후 다시 시도해 주세요.", "다시 시도"],
] as const)(
"gives a %s create failure its own copy and action",
async (kind, copy, action) => {
const user = userEvent.setup();
const demoSession = createDemoSessionAdapter("authenticated");
const beginSignIn = vi.fn(async () => {});
const createResource = vi.fn(async () => ({
ok: false as const,
error: createFailure(kind, "CREATE_REFERENCE_RESOURCE", 0, {
effect: "NOT_APPLIED",
}),
}));
renderReference(
inputWith({ createResource }),
"/examples/reference-resources/new",
{ ...demoSession, beginSignIn },
);
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
"Rejected",
);
await user.click(screen.getByRole("button", { name: "저장" }));
expect(await screen.findByRole("alert")).toHaveTextContent(copy);
expect(document.body).not.toHaveTextContent("입력 내용을 확인해 주세요.");
expect(
screen.queryByText("변경 결과를 확인할 수 없습니다."),
).not.toBeInTheDocument();
await user.click(screen.getByRole("button", { name: action }));
if (kind === "AUTH_REQUIRED") {
expect(beginSignIn).toHaveBeenCalledWith(
"/examples/reference-resources/new",
);
} else if (kind === "FORBIDDEN") {
// Leaving still passes the dirty-input guard.
await user.click(
await screen.findByRole("button", { name: "변경 버리고 이동" }),
);
expect(
await screen.findByRole("heading", {
level: 1,
name: "Clean Architecture Frontend",
}),
).toBeVisible();
} else {
await waitFor(() => expect(createResource).toHaveBeenCalledTimes(2));
}
},
);
it("settles the form after confirming an unknown create was applied", async () => {
const user = userEvent.setup();
const createResource = vi.fn(async () => ({
@@ -170,8 +170,8 @@ describe("reference feature production vertical path", () => {
// The demo session treats a server 401 as signed out; the route guard
// then asks for sign-in and the form is gone.
[401, "세션이 필요합니다."],
[403, "저장하지 못했습니다. 잠시 후 다시 시도해 주세요."],
[429, "저장하지 못했습니다. 잠시 후 다시 시도해 주세요."],
[403, "이 작업을 수행할 권한이 없습니다."],
[429, "요청이 많습니다. 잠시 후 다시 시도해 주세요."],
])(
"treats a create rejected with %i as not applied, not unknown",
async (status, guidance) => {
@@ -205,6 +205,7 @@ describe("reference feature production vertical path", () => {
expect(
screen.queryByRole("button", { name: "같은 요청으로 다시 보내기" }),
).not.toBeInTheDocument();
expect(document.body).not.toHaveTextContent("입력 내용을 확인해 주세요.");
},
);
});