From dfb1b9e0ee89a573016a9d4c14bc7206598af4cc Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 25 Sep 2026 22:09:28 +0900 Subject: [PATCH 01/14] fix(query): resend an unknown-effect write with its original idempotency key (03-01, 08-03) A save whose response was lost minted a new key on the next submit, and the screen let the user declare "not applied" without evidence. The same canonical input now reuses the unknown admission's intent; the screen offers "send the same request again" and a list refresh link instead. Co-Authored-By: Claude Opus 5.5 --- .../reference-resource-form-page.tsx | 42 ++++-- .../adapters/query/application-query.ts | 60 ++++++++- src/presentation/components/async-surface.tsx | 29 ++--- src/presentation/forms/use-app-form.ts | 105 ++++++++++----- src/presentation/i18n/catalog.ts | 4 +- .../application-mutation-admission.test.tsx | 123 ++++++++++++++++++ tests/component/async-surface.test.tsx | 13 +- .../reference-feature/reference-page.test.tsx | 60 +++++---- .../reference-production-vertical.test.tsx | 47 +++++++ 9 files changed, 386 insertions(+), 97 deletions(-) diff --git a/src/features/reference-feature/presentation/reference-resource-form-page.tsx b/src/features/reference-feature/presentation/reference-resource-form-page.tsx index 599bdd6e..d54e0eb1 100644 --- a/src/features/reference-feature/presentation/reference-resource-form-page.tsx +++ b/src/features/reference-feature/presentation/reference-resource-form-page.tsx @@ -1,5 +1,5 @@ import { useCallback } from "react"; -import { useNavigate } from "react-router-dom"; +import { Link, useNavigate } from "react-router-dom"; import { Button, @@ -13,6 +13,8 @@ import { useAppForm, useDirtyNavigationGuard, } from "../../../presentation/design-system/index.ts"; +import { useQueryInvalidationCoordinator } from "../../../presentation/adapters/query/query-invalidation-provider.tsx"; +import { REFERENCE_RESOURCE_INVALIDATION_TOPIC } from "../contracts/reference-feature-contract.ts"; import { REFERENCE_FORM_DEFAULTS, referenceResourceFormSchema, @@ -29,6 +31,7 @@ const FIELD_LABELS = Object.freeze({ export default function ReferenceResourceFormPage() { const navigate = useNavigate(); const mutation = useReferenceCreate(); + const invalidation = useQueryInvalidationCoordinator(); const submit = useCallback( (command: ReturnType) => mutation.submit(command), @@ -127,18 +130,31 @@ export default function ReferenceResourceFormPage() { } feedback={ mutationEffectUnknown ? ( - { - void mutation.reconcileUnknownEffect(resolution).then(() => { - if (resolution === "APPLIED") { - form.settleApplied(); - } else { - form.settleNotApplied(); - } - }); - }} - /> + <> + { + void mutation + .reconcileUnknownEffect(resolution) + .then(form.settleApplied); + }} + onResendUnknownEffect={() => { + void form.resendUnknown(mutation.resendUnknownEffect); + }} + /> +

+ { + void invalidation + ?.invalidate([REFERENCE_RESOURCE_INVALIDATION_TOPIC]) + .catch(() => {}); + }} + > + 목록을 새로 불러와 확인 + +

+ ) : form.result === "success" ? (

저장했습니다.

) : form.result === "conflict" ? ( diff --git a/src/presentation/adapters/query/application-query.ts b/src/presentation/adapters/query/application-query.ts index 696869f0..c747c916 100644 --- a/src/presentation/adapters/query/application-query.ts +++ b/src/presentation/adapters/query/application-query.ts @@ -219,9 +219,19 @@ type ApplicationMutationController = Readonly<{ state: AsyncState; submit(input: Input): Promise>; resolveConflict(): Promise; + /** + * Settles the oldest unknown effect. `NOT_APPLIED` needs evidence (an + * inspect operation or a server read); without it, resend instead. + */ reconcileUnknownEffect( resolution: "APPLIED" | "NOT_APPLIED", ): Promise; + /** + * D-1. Sends the oldest unknown-effect request again with its original + * intent, so a keyed command carries the same `Idempotency-Key`. Resolves + * to `null` when nothing is waiting to be resent. + */ + resendUnknownEffect(): Promise | null>; }>; type MutationExecution = @@ -231,7 +241,10 @@ type MutationExecution = type MutationAdmission = { sequence: number; state: "ACTIVE" | "UNKNOWN" | "RECONCILING" | "SETTLED"; + readonly input: unknown; intent: MutationIntent | null; + /** Held while UNKNOWN so the same input keeps the same identity token. */ + identityLease: Readonly<{ release(): void }> | null; scope: CacheScopeSnapshot | null; optimisticLayer: OptimisticLayerLease | null; optimisticQueryKey: readonly unknown[] | null; @@ -486,10 +499,19 @@ export function useApplicationMutation( ), }); } + // D-1. Saving the same canonical input again is the same logical + // request: it reuses the unknown admission's intent (and key). + const replayed = unknownEffectChannel.admissions.find( + (candidate) => + candidate.state === "UNKNOWN" && + candidate.intent?.canonicalInputIdentity === identity, + ); const admission: MutationAdmission = { sequence: unknownEffectChannel.nextSequence++, state: "ACTIVE", + input, intent: null, + identityLease: null, scope: scope ?? null, optimisticLayer: null, optimisticQueryKey: optimistic?.queryKey ?? null, @@ -498,6 +520,12 @@ export function useApplicationMutation( }; unknownEffectChannel.admissions.push(admission); unknownEffectChannel.registry.activeAdmissions += 1; + if (replayed) { + // The new attempt re-applies its own optimistic layer and owns the + // outcome from here. + replayed.optimisticLayer?.reconcile("NOT_APPLIED"); + settleMutationAdmission(unknownEffectChannel, replayed); + } notifyUnknownEffectChannel(unknownEffectChannel); setConflict(null); mutation.reset(); @@ -506,11 +534,13 @@ export function useApplicationMutation( const pending = (async (): Promise> => { let execution: MutationExecution; if (scope) { - const intent = mutationIntentFactory.create({ - operationId: mutationOperationId, - canonicalInputIdentity: identity, - requiresIdempotencyKey, - }); + const intent = + replayed?.intent ?? + mutationIntentFactory.create({ + operationId: mutationOperationId, + canonicalInputIdentity: identity, + requiresIdempotencyKey, + }); admission.intent = intent; execution = Object.freeze({ kind: "BOUND", input, intent }); } else { @@ -572,6 +602,10 @@ export function useApplicationMutation( optimisticLayer?.markUncertain(); if (!scope || scope.isCurrent()) { admission.state = "UNKNOWN"; + if (identityLease) { + identityLease.acquire(); + admission.identityLease = identityLease; + } notifyUnknownEffectChannel(unknownEffectChannel); } else { settleMutationAdmission(unknownEffectChannel, admission); @@ -699,6 +733,19 @@ export function useApplicationMutation( [mutation, queryClient, unknownEffectChannel], ); + const resendUnknownEffect = useCallback(async () => { + const head = unknownEffectChannel?.admissions[0]; + if ( + !head || + head.state !== "UNKNOWN" || + !head.intent || + unknownEffectChannel?.reconciliationInFlight + ) { + return null; + } + return submit(head.input as Input); + }, [submit, unknownEffectChannel]); + const unknownEffectHead = unknownEffectChannel?.admissions[0]; return Object.freeze({ @@ -714,6 +761,7 @@ export function useApplicationMutation( submit, resolveConflict, reconcileUnknownEffect, + resendUnknownEffect, }); } @@ -822,6 +870,8 @@ function markMutationAdmissionSettled( ): void { if (admission.state === "SETTLED") return; admission.state = "SETTLED"; + admission.identityLease?.release(); + admission.identityLease = null; channel.registry.activeAdmissions = Math.max( 0, channel.registry.activeAdmissions - 1, diff --git a/src/presentation/components/async-surface.tsx b/src/presentation/components/async-surface.tsx index 08bde41e..836c39db 100644 --- a/src/presentation/components/async-surface.tsx +++ b/src/presentation/components/async-surface.tsx @@ -96,9 +96,10 @@ export type AsyncSurfaceProps = Readonly<{ onAction?: () => void; onRetry?: () => void; onResolveConflict?: () => void; - onReconcileUnknownEffect?: ( - resolution: "APPLIED" | "NOT_APPLIED", - ) => void; + /** Only `APPLIED` is offered: "not applied" needs evidence the UI lacks. */ + onReconcileUnknownEffect?: (resolution: "APPLIED") => void; + /** D-1. Resends the unknown request with its original intent and key. */ + onResendUnknownEffect?: () => void; }>; export function AsyncSurface({ @@ -109,6 +110,7 @@ export function AsyncSurface({ onRetry, onResolveConflict, onReconcileUnknownEffect, + onResendUnknownEffect, }: AsyncSurfaceProps) { const { message } = useLocale(); if (state.base === "idle") return idle ?? null; @@ -155,18 +157,15 @@ export function AsyncSurface({ ) : null} {state.indicator === "mutation-effect-unknown" && onReconcileUnknownEffect ? ( - <> - - - + + ) : null} + {state.indicator === "mutation-effect-unknown" && + onResendUnknownEffect ? ( + ) : null} ) : null} diff --git a/src/presentation/forms/use-app-form.ts b/src/presentation/forms/use-app-form.ts index bf389ab3..a6b26482 100644 --- a/src/presentation/forms/use-app-form.ts +++ b/src/presentation/forms/use-app-form.ts @@ -175,6 +175,44 @@ export function useAppForm< setResult("idle"); }, []); + const applyOutcome = useCallback( + (outcome: FormResult, submittedValues: Values) => { + if (outcome.ok) { + settleSuccessfulValues(submittedValues); + return; + } + if (outcome.error.kind === "VALIDATION_REJECTED") { + unknownSubmissionRef.current = null; + const mapped = mapValidationFailureToFields( + outcome.error, + allowedServerFields, + message, + ); + setFieldErrors(mapped.fieldErrors); + setFormErrors(mapped.formErrors); + setResult("validation-error"); + focusFirstError(mapped.fieldErrors); + } else if (outcome.error.effect === "MAYBE_APPLIED") { + unknownSubmissionRef.current = submittedValues; + setFormErrors([]); + setResult("effect-unknown"); + } else if (outcome.error.effect === "APPLIED_CONFIRMED") { + settleSuccessfulValues(submittedValues); + } else if (outcome.error.kind === "CONFLICT") { + unknownSubmissionRef.current = null; + setFormErrors([ + message("form.conflict"), + ]); + setResult("conflict"); + } else { + unknownSubmissionRef.current = null; + setFormErrors([message("form.unavailable")]); + setResult("unavailable"); + } + }, + [allowedServerFields, focusFirstError, message, settleSuccessfulValues], + ); + const validateAndSubmit = useCallback( async (): Promise | null> => { setFieldErrors({} as FieldErrors); @@ -205,38 +243,7 @@ export function useAppForm< setPending(true); try { const outcome = await submit(command); - if (outcome.ok) { - settleSuccessfulValues(parsed.data); - return outcome; - } - if (outcome.error.kind === "VALIDATION_REJECTED") { - unknownSubmissionRef.current = null; - const mapped = mapValidationFailureToFields( - outcome.error, - allowedServerFields, - message, - ); - setFieldErrors(mapped.fieldErrors); - setFormErrors(mapped.formErrors); - setResult("validation-error"); - focusFirstError(mapped.fieldErrors); - } else if (outcome.error.effect === "MAYBE_APPLIED") { - unknownSubmissionRef.current = parsed.data; - setFormErrors([]); - setResult("effect-unknown"); - } else if (outcome.error.effect === "APPLIED_CONFIRMED") { - settleSuccessfulValues(parsed.data); - } else if (outcome.error.kind === "CONFLICT") { - unknownSubmissionRef.current = null; - setFormErrors([ - message("form.conflict"), - ]); - setResult("conflict"); - } else { - unknownSubmissionRef.current = null; - setFormErrors([message("form.unavailable")]); - setResult("unavailable"); - } + applyOutcome(outcome, parsed.data); return outcome; } finally { setPending(false); @@ -244,11 +251,11 @@ export function useAppForm< }, [ allowedServerFields, + applyOutcome, focusFirstError, mapToCommand, message, schema, - settleSuccessfulValues, submit, values, ], @@ -270,6 +277,37 @@ export function useAppForm< [validateAndSubmit], ); + /** + * D-1. Runs a resend of the unknown submission (for example + * `mutation.resendUnknownEffect`) through the same outcome handling as a + * submit. The form never builds a new command here: the caller resends the + * original request with its original key. + */ + const resendUnknown = useCallback( + ( + send: () => Promise | null>, + ): Promise | null> => { + if (pendingRef.current) return pendingRef.current; + // After a remount the form no longer holds the submitted values. + const submittedValues = unknownSubmissionRef.current ?? values; + const resend = (async () => { + setPending(true); + try { + const outcome = await send(); + if (outcome) applyOutcome(outcome, submittedValues); + return outcome; + } finally { + setPending(false); + } + })().finally(() => { + pendingRef.current = null; + }); + pendingRef.current = resend; + return resend; + }, + [applyOutcome, values], + ); + return Object.freeze({ formId, values, @@ -284,6 +322,7 @@ export function useAppForm< focusField, setValue, submitForm, + resendUnknown, reset, settleApplied, settleNotApplied, diff --git a/src/presentation/i18n/catalog.ts b/src/presentation/i18n/catalog.ts index 9bf90c7c..5fed1810 100644 --- a/src/presentation/i18n/catalog.ts +++ b/src/presentation/i18n/catalog.ts @@ -12,7 +12,7 @@ const PLATFORM_KO_MESSAGES = { "action.contactSupport": "지원 정보 확인", "action.resolveConflict": "충돌 해결", "action.confirmMutationApplied": "변경됨으로 확인", - "action.confirmMutationNotApplied": "변경되지 않음으로 확인", + "action.resendMutation": "같은 요청으로 다시 보내기", "action.continueEditing": "계속 작성", "action.discardAndLeave": "변경 버리고 이동", "action.signIn": "로그인 시작", @@ -171,7 +171,7 @@ const PLATFORM_EN_MESSAGES = { "action.contactSupport": "View support information", "action.resolveConflict": "Resolve conflict", "action.confirmMutationApplied": "Confirm the change was applied", - "action.confirmMutationNotApplied": "Confirm the change was not applied", + "action.resendMutation": "Send the same request again", "action.continueEditing": "Continue editing", "action.discardAndLeave": "Discard and leave", "action.signIn": "Start sign-in", diff --git a/tests/component/application-mutation-admission.test.tsx b/tests/component/application-mutation-admission.test.tsx index 64d7c43e..d569e635 100644 --- a/tests/component/application-mutation-admission.test.tsx +++ b/tests/component/application-mutation-admission.test.tsx @@ -8,6 +8,9 @@ import { useApplicationMutation, } from "../../src/presentation/adapters/query/application-query.ts"; import type { MutationIntentFactory } from "../../src/application/ports/mutation-intent-factory.ts"; +import { createFailure } from "../../src/contracts/errors.ts"; +import type { MutationIntent } from "../../src/contracts/mutation-intent.ts"; +import { createRuntimeIdentityRegistry } from "../../src/contracts/query-keys.ts"; import { MUTATION_COORDINATOR_BOUNDS } from "../../src/contracts/server-state.ts"; import { RESOURCE_INVALIDATION_TOPIC, @@ -371,4 +374,124 @@ describe("application mutation intent admission", () => { }); }); + describe("unknown-effect replay (D-1)", () => { + function replayScope() { + let token = 0; + return { + ...scopeSnapshot(), + identities: createRuntimeIdentityRegistry({ + tokenFactory: () => `replay-identity-token-${String(++token).padStart(4, "0")}`, + }), + }; + } + + function renderKeyedCreate( + outcomes: ApplicationResult[], + ) { + const client = queryClient(); + const intents: MutationIntent[] = []; + const execute = vi.fn( + async ( + input: string, + context: Readonly<{ signal: AbortSignal; intent: MutationIntent }>, + ): Promise> => { + intents.push(context.intent); + return outcomes.shift() ?? { ok: true, value: input }; + }, + ); + const scope = replayScope(); + const hook = renderHook( + () => + useApplicationMutation({ + definitionId: "replay-intent-v1", + definitionVersion: 1, + operationId: "CREATE_REPLAYED", + requiresIdempotencyKey: true, + owner: "platform-test", + duplicatePolicy: "REJECT_WHILE_ACTIVE", + scope, + execute, + invalidate: [], + }), + { wrapper: wrapper(client) }, + ); + return { hook, intents, execute }; + } + + const unknown: ApplicationResult = { + ok: false, + error: createFailure("SERVER_FAILURE", "CREATE_REPLAYED", 0, { + effect: "MAYBE_APPLIED", + }), + }; + + it("sends the same intent when the same input is saved again after an unknown effect", async () => { + const { hook, intents } = renderKeyedCreate([unknown]); + await act(() => hook.result.current.submit("same-input")); + expect(hook.result.current.state.indicator).toBe( + "mutation-effect-unknown", + ); + + await act(() => hook.result.current.submit("same-input")); + + expect(intents).toHaveLength(2); + expect(intents[1]).toBe(intents[0]); + expect(intents[1]?.idempotencyKey).toBe("key-1"); + await waitFor(() => + expect(hook.result.current.state.indicator).toBeNull(), + ); + }); + + it("mints a new key when the input changes after an unknown effect", async () => { + const { hook, intents } = renderKeyedCreate([unknown]); + await act(() => hook.result.current.submit("first-input")); + await act(() => hook.result.current.submit("changed-input")); + + expect(intents.map((intent) => intent.idempotencyKey)).toEqual([ + "key-1", + "key-2", + ]); + // The first request is still unresolved; a different request cannot + // settle it. + expect(hook.result.current.state.indicator).toBe( + "mutation-effect-unknown", + ); + }); + + it("resends the unknown head request with its original key", async () => { + const { hook, intents, execute } = renderKeyedCreate([unknown, unknown]); + await act(() => hook.result.current.submit("resent-input")); + + let resent: ApplicationResult | null | undefined; + await act(async () => { + resent = await hook.result.current.resendUnknownEffect(); + }); + expect(resent).toMatchObject({ + ok: false, + error: { effect: "MAYBE_APPLIED" }, + }); + await act(async () => { + resent = await hook.result.current.resendUnknownEffect(); + }); + + expect(resent).toEqual({ ok: true, value: "resent-input" }); + expect(execute.mock.calls.map(([input]) => input)).toEqual([ + "resent-input", + "resent-input", + "resent-input", + ]); + expect(new Set(intents.map((intent) => intent.idempotencyKey))).toEqual( + new Set(["key-1"]), + ); + await waitFor(() => + expect(hook.result.current.state.indicator).toBeNull(), + ); + // Nothing is left to resend once the effect is settled. + await act(async () => { + resent = await hook.result.current.resendUnknownEffect(); + }); + expect(resent).toBeNull(); + expect(execute).toHaveBeenCalledTimes(3); + }); + }); }); diff --git a/tests/component/async-surface.test.tsx b/tests/component/async-surface.test.tsx index 24d1ddd0..7cb44269 100644 --- a/tests/component/async-surface.test.tsx +++ b/tests/component/async-surface.test.tsx @@ -53,10 +53,11 @@ describe("async UI state matrix", () => { }); }); - it("renders unknown mutation effects with reconciliation-only actions", async () => { + it("renders unknown mutation effects with confirm-applied and resend only", async () => { const user = userEvent.setup(); const retry = vi.fn(); const reconcile = vi.fn(); + const resend = vi.fn(); const state = deriveAsyncState({ data: ["value"], hasMutationEffectUnknown: true, @@ -67,6 +68,7 @@ describe("async UI state matrix", () => { state={state} onRetry={retry} onReconcileUnknownEffect={reconcile} + onResendUnknownEffect={resend} > existing content
, @@ -81,12 +83,15 @@ describe("async UI state matrix", () => { expect( screen.queryByRole("button", { name: "다시 시도" }), ).not.toBeInTheDocument(); + expect( + screen.queryByRole("button", { name: "변경되지 않음으로 확인" }), + ).not.toBeInTheDocument(); await user.click(screen.getByRole("button", { name: "변경됨으로 확인" })); await user.click( - screen.getByRole("button", { name: "변경되지 않음으로 확인" }), + screen.getByRole("button", { name: "같은 요청으로 다시 보내기" }), ); - expect(reconcile).toHaveBeenNthCalledWith(1, "APPLIED"); - expect(reconcile).toHaveBeenNthCalledWith(2, "NOT_APPLIED"); + expect(reconcile).toHaveBeenCalledExactlyOnceWith("APPLIED"); + expect(resend).toHaveBeenCalledOnce(); expect(retry).not.toHaveBeenCalled(); }); diff --git a/tests/features/reference-feature/reference-page.test.tsx b/tests/features/reference-feature/reference-page.test.tsx index e65aae92..a09ad43a 100644 --- a/tests/features/reference-feature/reference-page.test.tsx +++ b/tests/features/reference-feature/reference-page.test.tsx @@ -337,25 +337,29 @@ describe("reference feature page states", () => { expect(screen.getByLabelText("설명")).toHaveValue("Keep this input"); }); - it("blocks resubmit and exposes only reconciliation for an unknown create effect", async () => { + it("blocks a new save and resends an unknown create with the same key", async () => { const user = userEvent.setup(); - const createResource = vi.fn(async () => ({ - ok: false as const, - error: createFailure( - "SERVER_FAILURE", - "CREATE_REFERENCE_RESOURCE", - 0, - { effect: "MAYBE_APPLIED" }, - ), - })); + const createResource = vi + .fn() + .mockResolvedValueOnce({ + ok: false, + error: createFailure( + "SERVER_FAILURE", + "CREATE_REFERENCE_RESOURCE", + 0, + { effect: "MAYBE_APPLIED" }, + ), + }) + .mockResolvedValue({ + ok: true, + value: { resourceId: "created", title: "Unknown result", createdAt: null }, + }); renderReference( inputWith({ createResource }), "/examples/reference-resources/new", ); - await user.type( - await screen.findByRole("textbox", { name: /새 항목 이름/ }), - "Unknown result", - ); + const name = await screen.findByRole("textbox", { name: /새 항목 이름/ }); + await user.type(name, "Unknown result"); await user.click(screen.getByRole("button", { name: "저장" })); expect( @@ -365,22 +369,28 @@ describe("reference feature page states", () => { expect( screen.queryByText("저장하지 못했습니다. 잠시 후 다시 시도해 주세요."), ).not.toBeInTheDocument(); + // No path lets the user declare "not applied" without evidence. + expect( + screen.queryByRole("button", { name: "변경되지 않음으로 확인" }), + ).not.toBeInTheDocument(); + expect( + screen.getByRole("link", { name: "목록을 새로 불러와 확인" }), + ).toHaveAttribute("href", "/examples/reference-resources"); await user.click(screen.getByRole("button", { name: "저장" })); expect(createResource).toHaveBeenCalledOnce(); - expect( - screen.getByRole("textbox", { name: /새 항목 이름/ }), - ).toHaveValue("Unknown result"); + expect(name).toHaveValue("Unknown result"); await user.click( - screen.getByRole("button", { name: "변경되지 않음으로 확인" }), + screen.getByRole("button", { name: "같은 요청으로 다시 보내기" }), ); - await waitFor(() => - expect(screen.getByRole("button", { name: "저장" })).toBeEnabled(), - ); - expect(createResource).toHaveBeenCalledOnce(); - expect( - screen.getByRole("textbox", { name: /새 항목 이름/ }), - ).toHaveValue("Unknown result"); + + expect(await screen.findByRole("status")).toHaveTextContent("저장했습니다."); + expect(createResource).toHaveBeenCalledTimes(2); + const [first, second] = createResource.mock.calls; + expect(second?.[0]).toEqual(first?.[0]); + expect(first?.[1]?.intent?.idempotencyKey).toBe("reference-page-key-1"); + expect(second?.[1]?.intent?.idempotencyKey).toBe("reference-page-key-1"); + expect(name).toHaveValue(""); }); it("settles the form after confirming an unknown create was applied", async () => { diff --git a/tests/features/reference-feature/reference-production-vertical.test.tsx b/tests/features/reference-feature/reference-production-vertical.test.tsx index 18575f31..47a35f7b 100644 --- a/tests/features/reference-feature/reference-production-vertical.test.tsx +++ b/tests/features/reference-feature/reference-production-vertical.test.tsx @@ -2,6 +2,7 @@ import { render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; +import { http, HttpResponse } from "msw"; import { afterAll, afterEach, @@ -118,4 +119,50 @@ describe("reference feature production vertical path", () => { expect(createRequests).toHaveBeenCalledWith({ name: "Created" }); expect(listRequests.mock.calls.length).toBeGreaterThanOrEqual(2); }); + + it("resends a create whose 504 lost the response with the same Idempotency-Key", async () => { + const user = userEvent.setup(); + const idempotencyKeys: (string | null)[] = []; + mockApi.server.use( + http.post("https://api.test/api/reference-resources", async ({ request }) => { + idempotencyKeys.push(request.headers.get("idempotency-key")); + // The first request reaches the server; only its response is lost. + if (idempotencyKeys.length === 1) { + return new HttpResponse(null, { status: 504 }); + } + const body = (await request.json()) as { name: string }; + return HttpResponse.json( + { + id: "reference-created", + name: body.name, + createdAt: "2026-07-26T00:00:00.000Z", + }, + { status: 201 }, + ); + }), + ); + const composition = await createRuntimeComposition({ + fetcher: absoluteFetch, + host: {}, + }); + window.history.pushState({}, "", "/examples/reference-resources/new"); + render(); + + await user.click( + await screen.findByRole("button", { name: "로그인 시작" }), + ); + await user.type( + await screen.findByRole("textbox", { name: /새 항목 이름/ }), + "Lost response", + ); + await user.click(screen.getByRole("button", { name: "저장" })); + await user.click( + await screen.findByRole("button", { name: "같은 요청으로 다시 보내기" }), + ); + + expect(await screen.findByText("저장했습니다.")).toBeVisible(); + expect(idempotencyKeys).toHaveLength(2); + expect(idempotencyKeys[0]).toMatch(/^[\x21-\x7e]+$/u); + expect(idempotencyKeys[1]).toBe(idempotencyKeys[0]); + }); }); From 2afee67150c068aeadcc2a14d767fe2f2893020e Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 25 Sep 2026 22:16:25 +0900 Subject: [PATCH 02/14] fix(http): let the package classify command 401/403/429 and keep re-login first (03-02) These statuses skipped the package classifier and always became MAYBE_APPLIED, so an expired session ended in "contact support" or the unknown-result screen. The descriptor gains optional classifyStatus, the reference create declares NOT_APPLIED, and AUTH_REQUIRED keeps reauth. Co-Authored-By: Claude Opus 5.5 --- ...igned-implementation-closed-deep-design.md | 3 + src/adapters/http/http-effect-certainty.ts | 22 ++++++ src/adapters/http/http-execution-v3.ts | 23 +++---- src/contracts/errors.ts | 12 +++- src/contracts/external-contract-runtime.ts | 12 ++++ ...reference-feature-contract-contribution.ts | 5 ++ .../reference-production-vertical.test.tsx | 42 +++++++++++ tests/mocks/scenarios/catalog.ts | 6 +- tests/unit/error-classification.test.ts | 14 ++++ tests/unit/http-execution-v3.test.ts | 69 +++++++++++++++++++ 10 files changed, 190 insertions(+), 18 deletions(-) diff --git a/docs/architecture/2026-07-30-frontend-runtime-capability-repository-aligned-implementation-closed-deep-design.md b/docs/architecture/2026-07-30-frontend-runtime-capability-repository-aligned-implementation-closed-deep-design.md index a7bec984..2112ff41 100644 --- a/docs/architecture/2026-07-30-frontend-runtime-capability-repository-aligned-implementation-closed-deep-design.md +++ b/docs/architecture/2026-07-30-frontend-runtime-capability-repository-aligned-implementation-closed-deep-design.md @@ -635,6 +635,7 @@ export interface CommandEffectDescriptor { status: number; problem: Problem; }>): "NOT_APPLIED" | "APPLIED_CONFIRMED" | "MAYBE_APPLIED"; + classifyStatus?(status: 401 | 403 | 429): "NOT_APPLIED" | "MAYBE_APPLIED"; } ``` @@ -647,6 +648,8 @@ export interface CommandEffectDescriptor { - frontend는 inspect request/response wire shape나 problem effect meaning을 작성하지 않는다; - `classifyProblem`은 package가 제공한 pure bounded classifier다; - classifier가 throw/unknown을 반환하면 effect는 fail-safe `MAYBE_APPLIED`이고 contract runtime failure를 기록한다; +- 401·403·429는 본문을 읽기 전에 판정하므로 `classifyProblem`을 거치지 않는다. package가 `classifyStatus`를 주면 그 판정을 쓰고, 없거나 `NOT_APPLIED` 외 값·throw면 전송 뒤 `MAYBE_APPLIED`다(`src/adapters/http/http-effect-certainty.ts` `classifyStatusEffect`); +- `AUTH_REQUIRED`는 effect가 `MAYBE_APPLIED`여도 action이 `reauth`다(`src/contracts/errors.ts` `unknownEffectAction`); - feature gateway가 package의 inspect operation을 application-safe outcome으로 mapping한다. ### 4.5 event contribution diff --git a/src/adapters/http/http-effect-certainty.ts b/src/adapters/http/http-effect-certainty.ts index d008b707..0ad44c28 100644 --- a/src/adapters/http/http-effect-certainty.ts +++ b/src/adapters/http/http-effect-certainty.ts @@ -128,6 +128,28 @@ export function classifyProblemEffect( }); } +/** + * D-2. A dispatched command answered 401, 403 or 429 is `MAYBE_APPLIED` unless + * the package classifies that status as `NOT_APPLIED`. Any other answer, or a + * throw, fails safe to `MAYBE_APPLIED`. + */ +export function classifyStatusEffect( + descriptor: CommandEffectDescriptor | null, + status: 401 | 403 | 429, + abandoned: MutationEffectCertainty, +): MutationEffectCertainty { + if (abandoned !== "MAYBE_APPLIED" || !descriptor?.classifyStatus) { + return abandoned; + } + try { + return descriptor.classifyStatus(status) === "NOT_APPLIED" + ? "NOT_APPLIED" + : "MAYBE_APPLIED"; + } catch { + return "MAYBE_APPLIED"; + } +} + /** §8.10. Certainty to UI intent. The copy itself is owned by the i18n catalog. */ export function projectCertaintyToUi( certainty: MutationEffectCertainty, diff --git a/src/adapters/http/http-execution-v3.ts b/src/adapters/http/http-execution-v3.ts index 47138898..42d8b5ae 100644 --- a/src/adapters/http/http-execution-v3.ts +++ b/src/adapters/http/http-execution-v3.ts @@ -36,6 +36,7 @@ import { import { certaintyForAbandonedAttempt, classifyProblemEffect, + classifyStatusEffect, joinMutationEffectCertainty, type MutationEffectCertainty, type PhysicalAttemptState, @@ -1142,25 +1143,24 @@ async function admitResponse( } const metadata = safeMetadata(response, retryAfterMs); + const statusEffect = (classified: 401 | 403 | 429) => + classifyStatusEffect( + contract.commandEffect, + classified, + certaintyForAbandonedAttempt(attemptState, isCommand), + ); if (!contract.acceptedStatuses.includes(status)) { if (status === 401) { await response.body?.cancel().catch(() => {}); return settled( - unauthenticated( - certaintyForAbandonedAttempt(attemptState, isCommand), - isCommand, - metadata, - ), + unauthenticated(statusEffect(401), isCommand, metadata), "UNAUTHENTICATED", ); } if (status === 403) { await response.body?.cancel().catch(() => {}); - return settled( - forbidden(certaintyForAbandonedAttempt(attemptState, isCommand), isCommand), - "FORBIDDEN", - ); + return settled(forbidden(statusEffect(403), isCommand), "FORBIDDEN"); } if (status === 429) { await response.body?.cancel().catch(() => {}); @@ -1168,10 +1168,7 @@ async function admitResponse( result: Object.freeze({ kind: "RATE_LIMITED" as const, ...(retryAfterMs === null ? {} : { retryAfterMs }), - effect: normalizeOptionalEffect( - certaintyForAbandonedAttempt(attemptState, isCommand), - isCommand, - ), + effect: normalizeOptionalEffect(statusEffect(429), isCommand), }), certainty: "RATE_LIMITED", retryHint: true, diff --git a/src/contracts/errors.ts b/src/contracts/errors.ts index 3fc3e571..86873b98 100644 --- a/src/contracts/errors.ts +++ b/src/contracts/errors.ts @@ -314,13 +314,21 @@ export function createFailure( userMessageKey: definition.userMessageKey, action: details.effect === "MAYBE_APPLIED" - ? "contact-support" + ? unknownEffectAction(definition.action) : details.effect === "APPLIED_CONFIRMED" ? "none" : definition.action, }); } +/** + * D-2. An unknown effect sends the user to support, except when the session + * itself is the problem: signing in again comes first either way. + */ +function unknownEffectAction(action: ErrorAction): ErrorAction { + return action === "reauth" ? "reauth" : "contact-support"; +} + /** * Adds controller-owned mutation effect knowledge without weakening the * fail-safe handling required for an unknown server-side outcome. @@ -333,7 +341,7 @@ export function withFailureEffect( ...failure, effect, ...(effect === "MAYBE_APPLIED" - ? { retryable: false as const, action: "contact-support" as const } + ? { retryable: false as const, action: unknownEffectAction(failure.action) } : effect === "APPLIED_CONFIRMED" ? { retryable: false as const, action: "none" as const } : {}), diff --git a/src/contracts/external-contract-runtime.ts b/src/contracts/external-contract-runtime.ts index 671eaa7b..ca930d11 100644 --- a/src/contracts/external-contract-runtime.ts +++ b/src/contracts/external-contract-runtime.ts @@ -123,6 +123,12 @@ export interface CommandEffectDescriptor { classifyProblem( input: Readonly<{ status: number; problem: Problem }>, ): CommandEffectClassification; + /** + * D-2. 401, 403 and 429 are admitted by status before any problem body is + * read. Declare `NOT_APPLIED` only when the server contract guarantees the + * command was rejected untouched. Without this, they stay `MAYBE_APPLIED`. + */ + classifyStatus?(status: 401 | 403 | 429): "NOT_APPLIED" | "MAYBE_APPLIED"; } export type HttpMethod = @@ -470,6 +476,12 @@ function assertHttpContract( if (typeof contract.commandEffect.classifyProblem !== "function") { fail(`${label}: command effect classifier is required`); } + if ( + contract.commandEffect.classifyStatus !== undefined && + typeof contract.commandEffect.classifyStatus !== "function" + ) { + fail(`${label}: command status classifier must be a function`); + } if (contract.retrySemantics === "KEYED" && !contract.commandRecovery) { fail(`${label}: KEYED commands require a recovery descriptor`); } diff --git a/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts b/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts index 48985218..0f38d803 100644 --- a/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts +++ b/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts @@ -44,6 +44,11 @@ const CREATE_EFFECT: CommandEffectDescriptor = Object.freeze({ } return "MAYBE_APPLIED"; }, + /** + * D-2. The reference backend rejects an unauthenticated, forbidden or + * rate-limited create before touching state. + */ + classifyStatus: () => "NOT_APPLIED" as const, }); export const LIST_REFERENCE_RESOURCES_CONTRACT = Object.freeze({ diff --git a/tests/features/reference-feature/reference-production-vertical.test.tsx b/tests/features/reference-feature/reference-production-vertical.test.tsx index 47a35f7b..e1a14a16 100644 --- a/tests/features/reference-feature/reference-production-vertical.test.tsx +++ b/tests/features/reference-feature/reference-production-vertical.test.tsx @@ -165,4 +165,46 @@ describe("reference feature production vertical path", () => { expect(idempotencyKeys[0]).toMatch(/^[\x21-\x7e]+$/u); expect(idempotencyKeys[1]).toBe(idempotencyKeys[0]); }); + + it.each([ + // 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, "저장하지 못했습니다. 잠시 후 다시 시도해 주세요."], + ])( + "treats a create rejected with %i as not applied, not unknown", + async (status, guidance) => { + const user = userEvent.setup(); + mockApi.server.use( + http.post( + "https://api.test/api/reference-resources", + () => new HttpResponse(null, { status }), + ), + ); + const composition = await createRuntimeComposition({ + fetcher: absoluteFetch, + host: {}, + }); + window.history.pushState({}, "", "/examples/reference-resources/new"); + render(); + + await user.click( + await screen.findByRole("button", { name: "로그인 시작" }), + ); + await user.type( + await screen.findByRole("textbox", { name: /새 항목 이름/ }), + "Rejected", + ); + await user.click(screen.getByRole("button", { name: "저장" })); + + expect(await screen.findByText(guidance)).toBeVisible(); + expect( + screen.queryByText("변경 결과를 확인할 수 없습니다."), + ).not.toBeInTheDocument(); + expect( + screen.queryByRole("button", { name: "같은 요청으로 다시 보내기" }), + ).not.toBeInTheDocument(); + }, + ); }); diff --git a/tests/mocks/scenarios/catalog.ts b/tests/mocks/scenarios/catalog.ts index 3e8abaad..8ab7ba87 100644 --- a/tests/mocks/scenarios/catalog.ts +++ b/tests/mocks/scenarios/catalog.ts @@ -232,14 +232,14 @@ function expectationFor( case "unauthenticated-401": statuses = [401]; kind = "UNAUTHENTICATED"; - outcomeEffect = command ? "MAYBE_APPLIED" : "NOT_APPLICABLE"; + outcomeEffect = command ? "NOT_APPLIED" : "NOT_APPLICABLE"; observer = "UNAUTHENTICATED"; bodies = [attemptBody("CANCELLED_WITHOUT_READ", 0, 0)]; break; case "forbidden-403": statuses = [403]; kind = "FORBIDDEN"; - outcomeEffect = command ? "MAYBE_APPLIED" : "NOT_APPLICABLE"; + outcomeEffect = command ? "NOT_APPLIED" : "NOT_APPLICABLE"; observer = "FORBIDDEN"; bodies = [attemptBody("CANCELLED_WITHOUT_READ", 0, 0)]; break; @@ -289,7 +289,7 @@ function expectationFor( const attemptCount = command ? 1 : 3; statuses = Array.from({ length: attemptCount }, () => 429); kind = "RATE_LIMITED"; - outcomeEffect = command ? "MAYBE_APPLIED" : "NOT_APPLICABLE"; + outcomeEffect = command ? "NOT_APPLIED" : "NOT_APPLICABLE"; observer = "RATE_LIMITED"; retryReasons = command ? [] : ["HTTP_429", "HTTP_429"]; media = Array.from({ length: attemptCount }, () => "application/json"); diff --git a/tests/unit/error-classification.test.ts b/tests/unit/error-classification.test.ts index e13c2661..90ad93f0 100644 --- a/tests/unit/error-classification.test.ts +++ b/tests/unit/error-classification.test.ts @@ -5,6 +5,7 @@ import { createFailure, kindForStatus, normalizeUnknownFailure, + withFailureEffect, } from "../../src/contracts/errors.ts"; import { DIAGNOSTIC_EVENT_REGISTRY } from "../../src/contracts/diagnostics.ts"; import { TELEMETRY_REGISTRY } from "../../src/contracts/telemetry.ts"; @@ -51,6 +52,19 @@ describe("frontend failure classification", () => { expect(kindForStatus(status)).toBe(kind); }); + it("keeps re-login first for an auth failure whose effect is unknown (D-2)", () => { + expect( + createFailure("AUTH_REQUIRED", "CREATE", 0, { effect: "MAYBE_APPLIED" }), + ).toMatchObject({ action: "reauth", retryable: false }); + expect( + withFailureEffect(createFailure("AUTH_REQUIRED", "CREATE", 0), "MAYBE_APPLIED"), + ).toMatchObject({ action: "reauth", retryable: false }); + // Every other kind still sends an unknown effect to support. + expect( + createFailure("FORBIDDEN", "CREATE", 0, { effect: "MAYBE_APPLIED" }), + ).toMatchObject({ action: "contact-support" }); + }); + it("projects only allowlisted safe fields", () => { const untrustedDetails = { code: "TEMPORARY", diff --git a/tests/unit/http-execution-v3.test.ts b/tests/unit/http-execution-v3.test.ts index 660e68c0..44ba0012 100644 --- a/tests/unit/http-execution-v3.test.ts +++ b/tests/unit/http-execution-v3.test.ts @@ -992,6 +992,75 @@ describe("terminal owner classification at every wait", () => { ); }); +/** + * D-2 (03-02). 401, 403 and 429 are admitted before any problem body is read. + * The package may classify them by status; without a classifier, or when it + * misbehaves, a dispatched command stays MAYBE_APPLIED. + */ +describe("command status classification", () => { + function withStatusClassifier( + classifyStatus: ((status: 401 | 403 | 429) => unknown) | undefined, + ): InstalledHttpContract { + return { + ...createInstalled, + contract: { + ...createInstalled.contract, + commandEffect: { + ...createInstalled.contract.commandEffect!, + ...(classifyStatus === undefined ? {} : { classifyStatus }), + } as NonNullable, + }, + }; + } + + async function effectFor( + status: number, + contract: InstalledHttpContract, + ) { + const executor = createContractHttpExecutor({ + baseUrl: "https://api.example/", + maxRetryAttempts: 0, + attachCredentials: () => ({ kind: "READY", headers: {} }), + fetcher: vi.fn(async () => new Response(null, { status })), + }); + const outcome = await executor.execute( + contract, + { name: "created" }, + { routeId: ROUTE_ID, scope, intent: mutationIntent() }, + ); + return { kind: outcome.kind, effect: outcome.effect }; + } + + it.each([ + [401, "UNAUTHENTICATED"], + [403, "FORBIDDEN"], + [429, "RATE_LIMITED"], + ] as const)("uses the package classifier for %i", async (status, kind) => { + const classifyStatus = vi.fn(() => "NOT_APPLIED"); + await expect( + effectFor(status, withStatusClassifier(classifyStatus)), + ).resolves.toEqual({ kind, effect: "NOT_APPLIED" }); + expect(classifyStatus).toHaveBeenCalledWith(status); + }); + + const throwingClassifier = (): unknown => { + throw new Error("package defect"); + }; + const unknownAnswer = (): unknown => "APPLIED_CONFIRMED"; + + it.each([ + ["no classifier", undefined], + ["a throwing classifier", throwingClassifier], + ["an unknown answer", unknownAnswer], + ] as const)("keeps MAYBE_APPLIED for %s", async (_label, classifyStatus) => { + for (const status of [401, 403, 429]) { + await expect( + effectFor(status, withStatusClassifier(classifyStatus)), + ).resolves.toMatchObject({ effect: "MAYBE_APPLIED" }); + } + }); +}); + /** * Q-6.3-7. A retried command's final effect joins what earlier attempts already * established, and an answer that says the command may already be applied is From 9894a70f04807b3ed0038f3e2ca916b69afbc4da Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 25 Sep 2026 22:22:58 +0900 Subject: [PATCH 03/14] 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 --- .../decisions/VD-04-native-form-facade.md | 12 +++- .../typescript-state-and-data-flow.md | 2 + .../reference-resource-form-page.tsx | 14 +++- src/presentation/components/async-surface.tsx | 4 ++ src/presentation/design-system/index.ts | 1 + src/presentation/forms/form-components.tsx | 29 +++++++++ src/presentation/forms/form-contracts.ts | 4 ++ src/presentation/forms/use-app-form.ts | 26 ++++++++ src/presentation/i18n/catalog.ts | 4 ++ tests/component/form-foundation.test.tsx | 65 +++++++++++++++++++ .../reference-feature/reference-page.test.tsx | 55 ++++++++++++++++ .../reference-production-vertical.test.tsx | 5 +- 12 files changed, 217 insertions(+), 4 deletions(-) diff --git a/docs/architecture/decisions/VD-04-native-form-facade.md b/docs/architecture/decisions/VD-04-native-form-facade.md index 374fd20b..958581c6 100644 --- a/docs/architecture/decisions/VD-04-native-form-facade.md +++ b/docs/architecture/decisions/VD-04-native-form-facade.md @@ -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 도입 조건 diff --git a/docs/architecture/typescript-state-and-data-flow.md b/docs/architecture/typescript-state-and-data-flow.md index 32fa998f..e0bb045a 100644 --- a/docs/architecture/typescript-state-and-data-flow.md +++ b/docs/architecture/typescript-state-and-data-flow.md @@ -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를 방해하지 않음 diff --git a/src/features/reference-feature/presentation/reference-resource-form-page.tsx b/src/features/reference-feature/presentation/reference-resource-form-page.tsx index d54e0eb1..80bec0f4 100644 --- a/src/features/reference-feature/presentation/reference-resource-form-page.tsx +++ b/src/features/reference-feature/presentation/reference-resource-form-page.tsx @@ -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() { } feedback={ - mutationEffectUnknown ? ( + form.failure ? ( + void form.submitForm() + : failureAction + } + /> + ) : mutationEffectUnknown ? ( <> 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} >

{errorMessage(userMessageKey, locale)}

+ {description ?

{description}

: null} {action !== "none" && onAction && ( )} diff --git a/src/presentation/design-system/index.ts b/src/presentation/design-system/index.ts index 3467658e..5a519cf4 100644 --- a/src/presentation/design-system/index.ts +++ b/src/presentation/design-system/index.ts @@ -136,6 +136,7 @@ export { ErrorSummary, Form, FormActions, + FormFailureStatus, FormField, useAppForm, useDirtyNavigationGuard, diff --git a/src/presentation/forms/form-components.tsx b/src/presentation/forms/form-components.tsx index 16bc9b8e..f87d771f 100644 --- a/src/presentation/forms/form-components.tsx +++ b/src/presentation/forms/form-components.tsx @@ -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(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 ( + + ); +} + export function FormActions(props: Readonly<{ children: ReactNode; sticky?: boolean; diff --git a/src/presentation/forms/form-contracts.ts b/src/presentation/forms/form-contracts.ts index cdc1581d..c432ef1b 100644 --- a/src/presentation/forms/form-contracts.ts +++ b/src/presentation/forms/form-contracts.ts @@ -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 = Readonly<{ diff --git a/src/presentation/forms/use-app-form.ts b/src/presentation/forms/use-app-form.ts index a6b26482..5a4e00a8 100644 --- a/src/presentation/forms/use-app-form.ts +++ b/src/presentation/forms/use-app-form.ts @@ -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([]); const [pending, setPending] = useState(false); const [result, setResult] = useState("idle"); + const [statusFailure, setStatusFailure] = useState(null); const pendingRef = useRef | null> | null>(null); const unknownSubmissionRef = useRef(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 = new Set([ + "reauth-required", + "forbidden", + "retry-later", +]); + function issuesToFieldErrors( issues: readonly ZodIssue[], allowedFields: readonly FieldName[], diff --git a/src/presentation/i18n/catalog.ts b/src/presentation/i18n/catalog.ts index 5fed1810..6ec1a18c 100644 --- a/src/presentation/i18n/catalog.ts +++ b/src/presentation/i18n/catalog.ts @@ -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.", diff --git a/tests/component/form-foundation.test.tsx b/tests/component/form-foundation.test.tsx index 1711148d..a91113f8 100644 --- a/tests/component/form-foundation.test.tsx +++ b/tests/component/form-foundation.test.tsx @@ -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 }> >; resetOnSuccess?: boolean; + onFailureAction?(): void; }>) { const form = useAppForm({ schema, @@ -57,6 +59,14 @@ function FormHarness(props: Readonly<{ fieldId={form.fieldId} onFocusField={form.focusField} /> + void form.submitForm() + : props.onFailureAction + } + />