Files
tech-log-frontend/tests/component/application-mutation-admission.test.tsx
DongHyeonka c80320dfc7 chore: sync the frontend template from ebea300 to af3d8e6
Carries 359 template commits, tag v0.2.0 plus one documentation commit: the
generator-built feature index with its app, bounded-context and feature
declarations, the src/platform kernel and scale tooling, the 2026-09-24 src
review fixes, and the 2026-09-25 maturity review round with its CHANGELOG
[보안]/[계약] rows. 691 of the 824 template paths are applied, 85 of them
merged with product changes; 127 are not carried.

Product identity is unchanged: name, version 0.1.0, routes, design and the
TechLog domain.

Three decisions worth naming. TechLog stays composed directly, as the last
two syncs recorded; its directory carries a NOT_INSTALLED marker that says so,
and every installed-* composer takes the template's projection with TechLog
added on top. The reference sample is no longer installed: the template now
installs a feature only through feature-module.ts and context-routes.ts,
which load the screens this product deleted, so its three operations, six
schemas and one topic leave the registries, recorded as registry change
evidence. And AppRouter mounts the platform and TechLog routes only; the
template's bounded-context route gateway waits for a generator-installed
feature.

Required fixes: readSubject on the BFF session owner (without it every HTTP
Studio session would close as integration-failed), zod through the facade in
nine TechLog files, noUnusedLocals, and public/config.json written out to
match the local profile. Derived baselines were recomputed after reproducing
both sides' values: CI contract 101 commands / 106 references / 141
artifacts, gate shape c9adcf85; registry approval 2dc6c3a3; the runtime
config schema baseline equals the schema at 8210d48.

Verified here: types, lint, architecture, adapter inventory, CI contract,
i18n, design system, diagnostics, browser security, dev release manifest,
TechLog contract and build pass; 220 component, 155 integration, 15
contract, 418 TechLog, 43 reference-feature, 18 recipe and 46
release-coherence tests pass, and 2381 of 2383 unit tests. Reproduced at
8210d48 first and unchanged: check:registries (byte-identical),
test:runtime-schema, verify:documentation. Brought by the template and
escalated rather than suppressed: check:request-fanout on TechLog's cursor
pagination, check:remediation-ledger (fails upstream too), the shared-chunk
hash test, and the registry-dependent sample removal and second-feature
tests. Playwright suites were not run.

Full record, the five open questions and the follow-ups in
docs/operations/template-sync-2026-09-29.md.

(cherry picked from commit b2170cf265dea45dc9cc05d3c61e627e97f31cdb)
2026-11-12 08:28:54 +09:00

498 lines
16 KiB
TypeScript

// @vitest-environment jsdom
import { act, renderHook, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import {
type ApplicationResult,
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,
deterministicMutationIntentFactory,
queryClient,
scopeSnapshot,
wrapper,
} from "./application-query-fixture.tsx";
describe("application mutation intent admission", () => {
it("retains optimistic data when execute throws after dispatch begins", async () => {
const client = queryClient();
const key = ["resource", "thrown-unknown-effect"];
client.setQueryData(key, ["base"]);
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
execute: async () => {
throw new Error("private transport defect");
},
currentData: client.getQueryData(key),
optimistic: {
queryKey: key,
update: (previous, input) => [
...(previous as string[]),
input,
],
},
}),
{ wrapper: wrapper(client) },
);
let outcome: ApplicationResult<string> | undefined;
await act(async () => {
outcome = await hook.result.current.submit("created");
});
expect(outcome).toMatchObject({
ok: false,
error: {
effect: "MAYBE_APPLIED",
retryable: false,
action: "contact-support",
},
});
expect(JSON.stringify(outcome)).not.toContain("private transport defect");
expect(client.getQueryData(key)).toEqual(["base", "created"]);
expect(hook.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
});
it("creates a distinct logical intent for each independently admitted submit", async () => {
const client = queryClient();
const scope = scopeSnapshot();
const observedIntents: unknown[] = [];
const execute = vi.fn(
async (
input: string,
context: Readonly<{ signal: AbortSignal; intent?: unknown }>,
) => {
observedIntents.push(context.intent);
return { ok: true as const, value: input };
},
);
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
definitionId: "independent-intent-v1",
definitionVersion: 1,
operationId: "CREATE_WITH_INTENT",
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "ALLOW_PARALLEL",
scope,
execute,
invalidate: [],
}),
{ wrapper: wrapper(client) },
);
await act(async () => {
await hook.result.current.submit("same-input");
await hook.result.current.submit("same-input");
});
expect(observedIntents).toHaveLength(2);
expect(observedIntents[0]).toMatchObject({
intentId: "intent-1",
operationId: "CREATE_WITH_INTENT",
idempotencyKey: "key-1",
});
expect(observedIntents[1]).toMatchObject({
intentId: "intent-2",
operationId: "CREATE_WITH_INTENT",
idempotencyKey: "key-2",
});
expect(observedIntents[0]).not.toEqual(observedIntents[1]);
});
it("creates no second intent when JOIN_IDENTICAL shares an admitted submit", async () => {
const client = queryClient();
const scope = scopeSnapshot();
const deterministicFactory = deterministicMutationIntentFactory();
const createIntent = vi.fn(deterministicFactory.create);
const factory: MutationIntentFactory = Object.freeze({
create: createIntent,
});
let complete: (value: ApplicationResult<string>) => void = () => {};
const execute = vi.fn(
() =>
new Promise<ApplicationResult<string>>((resolve) => {
complete = resolve;
}),
);
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
definitionId: "joined-intent-v1",
definitionVersion: 1,
operationId: "CREATE_JOINED",
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "JOIN_IDENTICAL",
scope,
execute,
invalidate: [],
}),
{ wrapper: wrapper(client, factory) },
);
let first: Promise<ApplicationResult<string>> | null = null;
let joined: Promise<ApplicationResult<string>> | null = null;
act(() => {
first = hook.result.current.submit("same-input");
joined = hook.result.current.submit("same-input");
});
expect(first).toBe(joined);
await waitFor(() => expect(execute).toHaveBeenCalledOnce());
expect(createIntent).toHaveBeenCalledOnce();
expect(createIntent).toHaveBeenCalledWith({
operationId: "CREATE_JOINED",
canonicalInputIdentity:
"scope-fingerprint-0001:joined-intent-v1:scope-identity-token-0001",
requiresIdempotencyKey: true,
});
complete({ ok: true, value: "same-input" });
if (!first) throw new Error("expected admitted mutation");
await act(() => first);
});
it("bounds JOIN_IDENTICAL waiters without starting another mutation", async () => {
const client = queryClient();
const scope = scopeSnapshot();
let complete: (value: ApplicationResult<string>) => void = () => {};
const execute = vi.fn(
() =>
new Promise<ApplicationResult<string>>((resolve) => {
complete = resolve;
}),
);
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
definitionId: "joined-waiter-budget-v1",
definitionVersion: 1,
operationId: "CREATE_JOINED_BOUNDED",
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "JOIN_IDENTICAL",
scope,
execute,
invalidate: [],
}),
{ wrapper: wrapper(client) },
);
let admitted: Promise<ApplicationResult<string>> | null = null;
let joined: readonly Promise<ApplicationResult<string>>[] = [];
let overflow: Promise<ApplicationResult<string>> | null = null;
act(() => {
admitted = hook.result.current.submit("same-input");
joined = Array.from(
{ length: MUTATION_COORDINATOR_BOUNDS.waitersPerJoinedIntent },
() => hook.result.current.submit("same-input"),
);
overflow = hook.result.current.submit("same-input");
});
expect(joined.every((waiter) => waiter === admitted)).toBe(true);
expect(overflow).not.toBe(admitted);
if (!overflow) throw new Error("expected overflow result");
await expect(overflow).resolves.toMatchObject({
ok: false,
error: {
kind: "DUPLICATE_IN_FLIGHT",
code: "JOIN_WAITER_LIMIT_EXCEEDED",
effect: "NOT_STARTED",
},
});
await waitFor(() => expect(execute).toHaveBeenCalledOnce());
complete({ ok: true, value: "same-input" });
if (!admitted) throw new Error("expected admitted mutation");
await act(() => admitted);
});
it("keeps the legacy raw mutation path outside the intent factory", async () => {
const client = queryClient();
const createIntent = vi.fn<MutationIntentFactory["create"]>();
const factory: MutationIntentFactory = Object.freeze({
create: createIntent,
});
const execute = vi.fn(async (input: string) => ({
ok: true as const,
value: input,
}));
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
definitionId: "legacy-raw-path-v1",
execute,
}),
{ wrapper: wrapper(client, factory) },
);
await act(() => hook.result.current.submit("legacy-input"));
expect(execute).toHaveBeenCalledOnce();
expect(createIntent).not.toHaveBeenCalled();
});
it("rejects a duplicate submit by default while one is active", async () => {
const client = queryClient();
let complete: (value: ApplicationResult<string>) => void = () => {};
const execute = vi.fn(
() =>
new Promise<ApplicationResult<string>>((resolve) => {
complete = resolve;
}),
);
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
definitionId: "legacy-duplicate-rejection-v1",
execute,
}),
{ wrapper: wrapper(client) },
);
let first: Promise<ApplicationResult<string>> | null = null;
let duplicate: Promise<ApplicationResult<string>> | null = null;
act(() => {
first = hook.result.current.submit("created");
duplicate = hook.result.current.submit("created");
});
if (!first || !duplicate) throw new Error("expected two submissions");
await expect(duplicate).resolves.toMatchObject({
ok: false,
error: { kind: "DUPLICATE_IN_FLIGHT" },
});
expect(execute).toHaveBeenCalledOnce();
complete({ ok: true, value: "created" });
await act(() => first as Promise<ApplicationResult<string>>);
});
it("deduplicates submit and commits one optimistic mutation", async () => {
const client = queryClient();
const key = ["resource", "list"];
client.setQueryData(key, ["existing"]);
let complete: (value: ApplicationResult<string>) => void = () => {};
const execute = vi.fn(
() =>
new Promise<ApplicationResult<string>>((resolve) => {
complete = resolve;
}),
);
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
// §11.2: joining is opt-in. The default is REJECT_WHILE_ACTIVE.
duplicatePolicy: "JOIN_IDENTICAL",
execute,
invalidate: [RESOURCE_INVALIDATION_TOPIC],
currentData: client.getQueryData(key),
optimistic: {
queryKey: key,
update: (previous, input) => [
...(previous as string[]),
input,
],
},
}),
{ wrapper: wrapper(client) },
);
let first: Promise<ApplicationResult<string>> | null = null;
let duplicate: Promise<ApplicationResult<string>> | null = null;
act(() => {
first = hook.result.current.submit("created");
duplicate = hook.result.current.submit("created");
});
expect(first).toBe(duplicate);
await waitFor(() =>
expect(client.getQueryData(key)).toEqual(["existing", "created"]),
);
await waitFor(() => expect(execute).toHaveBeenCalledOnce());
await waitFor(() =>
expect(hook.result.current.state.indicator).toBe("mutation-pending"),
);
complete({ ok: true, value: "created" });
if (!first) throw new Error("expected pending mutation");
await act(() => first);
expect(client.getQueryState(key)?.isInvalidated).toBe(true);
await waitFor(() =>
expect(hook.result.current.state.indicator).toBeNull(),
);
});
it("never joins distinct mutation inputs to the same runtime promise", async () => {
const client = queryClient();
const resolvers = new Map<
string,
(value: ApplicationResult<string>) => void
>();
const execute = vi.fn(
(input: string) =>
new Promise<ApplicationResult<string>>((resolve) => {
resolvers.set(input, resolve);
}),
);
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
definitionId: "legacy-parallel-distinct-inputs-v1",
execute,
currentData: true,
}),
{ wrapper: wrapper(client) },
);
let first: Promise<ApplicationResult<string>> | undefined;
let second: Promise<ApplicationResult<string>> | undefined;
act(() => {
first = hook.result.current.submit("first");
second = hook.result.current.submit("second");
});
expect(first).not.toBe(second);
await waitFor(() => expect(execute).toHaveBeenCalledTimes(2));
resolvers.get("first")?.({ ok: true, value: "first" });
resolvers.get("second")?.({ ok: true, value: "second" });
if (!first || !second) throw new Error("expected pending mutations");
await act(async () => {
await Promise.all([first, second]);
});
});
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<string>[],
) {
const client = queryClient();
const intents: MutationIntent[] = [];
const execute = vi.fn(
async (
input: string,
context: Readonly<{ signal: AbortSignal; intent: MutationIntent }>,
): Promise<ApplicationResult<string>> => {
intents.push(context.intent);
return outcomes.shift() ?? { ok: true, value: input };
},
);
const scope = replayScope();
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
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<string> = {
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<string> | 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);
});
});
});