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 <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-09-25 22:09:28 +09:00
co-authored by Claude Opus 5.5
parent 926f448fce
commit dfb1b9e0ee
9 changed files with 386 additions and 97 deletions
@@ -219,9 +219,19 @@ type ApplicationMutationController<Input, Value> = Readonly<{
state: AsyncState;
submit(input: Input): Promise<ApplicationResult<Value>>;
resolveConflict(): Promise<void>;
/**
* 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<void>;
/**
* 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<ApplicationResult<Value> | null>;
}>;
type MutationExecution<Input> =
@@ -231,7 +241,10 @@ type MutationExecution<Input> =
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<Input, Value>(
),
});
}
// 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<Input, Value>(
};
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<Input, Value>(
const pending = (async (): Promise<ApplicationResult<Value>> => {
let execution: MutationExecution<Input>;
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<Input, Value>(
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<Input, Value>(
[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<Input, Value>(
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,
+14 -15
View File
@@ -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 ? (
<>
<Button
onClick={() => onReconcileUnknownEffect("APPLIED")}
>
{message("action.confirmMutationApplied")}
</Button>
<Button
onClick={() => onReconcileUnknownEffect("NOT_APPLIED")}
>
{message("action.confirmMutationNotApplied")}
</Button>
</>
<Button onClick={() => onReconcileUnknownEffect("APPLIED")}>
{message("action.confirmMutationApplied")}
</Button>
) : null}
{state.indicator === "mutation-effect-unknown" &&
onResendUnknownEffect ? (
<Button onClick={onResendUnknownEffect}>
{message("action.resendMutation")}
</Button>
) : null}
</div>
) : null}
+72 -33
View File
@@ -175,6 +175,44 @@ export function useAppForm<
setResult("idle");
}, []);
const applyOutcome = useCallback(
(outcome: FormResult<Output>, submittedValues: Values) => {
if (outcome.ok) {
settleSuccessfulValues(submittedValues);
return;
}
if (outcome.error.kind === "VALIDATION_REJECTED") {
unknownSubmissionRef.current = null;
const mapped = mapValidationFailureToFields<Values>(
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<FormResult<Output> | null> => {
setFieldErrors({} as FieldErrors<Values>);
@@ -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<Values>(
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<FormResult<Output> | null>,
): Promise<FormResult<Output> | 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,
+2 -2
View File
@@ -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",