Merge branch 'main' into feature/tournament-lifecycle-e2e

This commit is contained in:
2026-07-26 05:10:19 +00:00
12 changed files with 1400 additions and 503 deletions
@@ -0,0 +1,238 @@
import { expect, test, type Page, type Route } from '@playwright/test';
import { readFile } from 'node:fs/promises';
import { dirname, extname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
const imageRoot = resolve(repositoryRoot, '../../image');
const artifactRoot = process.env.FRONTEND_PARITY_ARTIFACT_DIR;
const gameUrl = `http://127.0.0.1:${process.env.FRONTEND_PARITY_GAME_PORT ?? '15102'}/che/inherit`;
const response = (data: unknown) => ({ result: { data } });
const operations = (route: Route): string[] => {
const pathname = new URL(route.request().url()).pathname;
return decodeURIComponent(pathname.slice(pathname.lastIndexOf('/trpc/') + 6)).split(',');
};
const installImages = async (page: Page): Promise<void> => {
await page.route('**/image/**', async (route) => {
const relative = decodeURIComponent(new URL(route.request().url()).pathname).replace(/^\/image\//, '');
for (const candidate of [
resolve(imageRoot, relative),
resolve(imageRoot, 'game', relative),
resolve(imageRoot, 'icons', '22.jpg'),
]) {
try {
const body = await readFile(candidate);
await route.fulfill({
status: 200,
contentType: extname(candidate).toLowerCase() === '.png' ? 'image/png' : 'image/jpeg',
body,
});
return;
} catch {
// 다음 공개 image root 후보를 확인한다.
}
}
await route.abort('failed');
});
};
const statusFixture = {
items: {
previous: 12_000,
lived_month: 240,
max_domestic_critical: 80,
active_action: 35,
combat: 150,
sabotage: 60,
dex: 42,
unifier: 0,
tournament: 30,
betting: 20,
max_belong: 8,
},
totalPoint: 12_665,
inheritConst: {
minMonthToAllowInheritItem: 4,
inheritBornSpecialPoint: 6000,
inheritBornTurntimePoint: 2500,
inheritBornCityPoint: 1000,
inheritBornStatPoint: 1000,
inheritItemUniqueMinPoint: 5000,
inheritItemRandomPoint: 3000,
inheritBuffPoints: [0, 200, 600, 1200, 2000, 3000],
inheritSpecificSpecialPoint: 4000,
inheritResetAttrPointBase: [1000, 1000, 2000, 3000],
inheritCheckOwnerPoint: 1000,
},
buffLevels: {
warAvoidRatio: 0,
warCriticalRatio: 1,
warMagicTrialProb: 0,
domesticSuccessProb: 0,
domesticFailProb: 0,
warAvoidRatioOppose: 0,
warCriticalRatioOppose: 0,
warMagicTrialProbOppose: 0,
},
resetCosts: { resetSpecialWar: 1000, resetTurnTime: 1000 },
resetLevels: { resetSpecialWar: 0, resetTurnTime: 0 },
availableSpecialWar: [{ key: 'che_선봉', name: '선봉', info: '공격에 유리합니다.' }],
availableUnique: [
{
key: 'che_무기_12_칠성검',
name: '칠성검(+12)',
rawName: '칠성검',
info: '무력을 올려주는 유니크 무기입니다.',
},
],
availableTargetGenerals: [{ id: 8, name: '조조' }],
turnTimeZones: ['00:00'],
isUnited: false,
currentSpecialWar: 'che_선봉',
currentStat: { leadership: 70, strength: 45, intel: 85 },
};
const installFixture = async (page: Page, options: { failBuff?: boolean } = {}) => {
let buffMutationCount = 0;
await installImages(page);
await page.addInitScript(() => {
window.localStorage.setItem('sammo-game-token', 'ga_inherit-visual-token');
window.localStorage.setItem('sammo-game-profile', 'che');
});
await page.route('**/che/api/trpc/**', async (route) => {
const names = operations(route);
if (options.failBuff && names.includes('inherit.buyHiddenBuff')) {
await route.fulfill({
status: 500,
contentType: 'application/json',
body: JSON.stringify({ error: { message: '의도한 유산 구입 오류' } }),
});
return;
}
const result = names.map((name) => {
if (name === 'inherit.getStatus') return response(statusFixture);
if (name === 'lobby.info') {
return response({
profile: { id: 'che', scenario: 'default', name: '체섭' },
world: { year: 200, month: 4 },
myGeneral: { id: 7, name: '유비', nationId: 1 },
});
}
if (name === 'inherit.getLogs') {
return response([
{
id: 2,
year: 200,
month: 4,
text: '1000 포인트로 장수 소유자 확인',
createdAt: '2026-07-26T00:00:00.000Z',
},
]);
}
if (name === 'join.getConfig') {
return response({ rules: { stat: { total: 200, min: 10, max: 100 } } });
}
if (name === 'inherit.buyHiddenBuff') {
buffMutationCount += 1;
return response({ ok: true, remainPoint: 11_800 });
}
throw new Error(`Unhandled inheritance fixture operation: ${name}`);
});
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(result),
});
});
return { buffMutationCount: () => buffMutationCount };
};
test.describe('inheritance management legacy parity', () => {
test('matches the ref 1000px grid and computed styles on desktop and mobile', async ({ page }) => {
await installFixture(page);
await page.setViewportSize({ width: 1280, height: 900 });
await page.goto(gameUrl);
await expect(page.locator('#container')).toBeVisible();
await expect(page.locator('#specific-unique')).toHaveValue('che_무기_12_칠성검');
const desktop = await page.evaluate(() => {
const rect = (selector: string) => {
const box = document.querySelector<HTMLElement>(selector)!.getBoundingClientRect();
return { x: box.x, width: box.width };
};
const container = getComputedStyle(document.querySelector<HTMLElement>('#container')!);
const title = getComputedStyle(document.querySelector<HTMLElement>('.section-title')!);
const button = getComputedStyle(document.querySelector<HTMLElement>('.buy-button')!);
return {
container: rect('#container'),
firstPoint: rect('#inherit_sum'),
fontFamily: container.fontFamily,
fontSize: container.fontSize,
backgroundImage: container.backgroundImage,
titleBackgroundImage: title.backgroundImage,
buttonBackground: button.backgroundColor,
};
});
expect(desktop.container.width).toBe(1000);
expect(desktop.container.x).toBe(140);
expect(desktop.firstPoint.width).toBeCloseTo(327.3, 0);
expect(desktop.fontFamily).toContain('Pretendard');
expect(desktop.fontSize).toBe('14px');
expect(desktop.backgroundImage).toContain('back_walnut.jpg');
expect(desktop.titleBackgroundImage).toContain('back_green.jpg');
const buyButton = page.locator('.buy-button').first();
const beforeHover = await buyButton.evaluate((element) => getComputedStyle(element).backgroundColor);
await buyButton.hover();
const afterHover = await buyButton.evaluate((element) => getComputedStyle(element).backgroundColor);
expect(afterHover).not.toBe(beforeHover);
await buyButton.focus();
await expect(buyButton).toBeFocused();
if (artifactRoot) {
await page.screenshot({ path: resolve(artifactRoot, 'inherit-core-desktop.png'), fullPage: true });
}
await page.setViewportSize({ width: 500, height: 900 });
await page.reload();
await expect(page.locator('#container')).toBeVisible();
const mobile = await page.evaluate(() => {
const container = document.querySelector<HTMLElement>('#container')!.getBoundingClientRect();
const first = document.querySelector<HTMLElement>('#inherit_sum')!.getBoundingClientRect();
const second = document.querySelector<HTMLElement>('#inherit_previous')!.getBoundingClientRect();
return {
containerWidth: container.width,
firstWidth: first.width,
stacked: second.y > first.y,
};
});
expect(mobile.containerWidth).toBe(500);
expect(mobile.firstWidth).toBeCloseTo(482, 0);
expect(mobile.stacked).toBe(true);
});
test('submits a legacy buff purchase and refreshes status and logs', async ({ page }) => {
const fixture = await installFixture(page);
page.on('dialog', (dialog) => dialog.accept());
await page.goto(gameUrl);
await page.locator('#buff-warAvoidRatio').fill('1');
await page.locator('#buff-warAvoidRatio').locator('xpath=../..').getByRole('button', { name: '구입' }).click();
await expect.poll(fixture.buffMutationCount).toBe(1);
await expect(page.locator('#inherit_previous_value')).toHaveValue('12,000');
});
test('keeps controls usable and renders an API mutation error', async ({ page }) => {
await installFixture(page, { failBuff: true });
page.on('dialog', (dialog) => dialog.accept());
await page.goto(gameUrl);
await page.locator('#buff-warAvoidRatio').fill('1');
await page.locator('#buff-warAvoidRatio').locator('xpath=../..').getByRole('button', { name: '구입' }).click();
await expect(page.locator('[role="alert"]')).toBeVisible();
await expect(page.locator('#buff-warAvoidRatio')).toHaveValue('1');
await expect(page.locator('#buff-warAvoidRatio')).toBeEnabled();
});
});
@@ -13,6 +13,7 @@ export default defineConfig({
'public-gaps.spec.ts',
'instant-diplomacy-message.spec.ts',
'tournament-betting.spec.ts',
'inheritance-management.spec.ts',
],
fullyParallel: false,
workers: 1,
@@ -25,6 +25,11 @@ import {
type CanonicalTurnSnapshot,
} from './canonical.js';
interface GeneralCooldownSelector {
generalId: number;
actionName: string;
}
export interface TurnCommandFixtureRequest {
kind: 'general' | 'nation';
actorGeneralId: number;
@@ -47,6 +52,7 @@ export interface TurnCommandFixtureRequest {
troops?: Array<Record<string, unknown>>;
diplomacy?: Array<Record<string, unknown>>;
randomFoundingCandidateCityIds?: number[];
generalCooldowns?: Array<GeneralCooldownSelector & { nextAvailableTurn: number }>;
};
observe?: {
generalIds?: number[];
@@ -54,6 +60,7 @@ export interface TurnCommandFixtureRequest {
nationIds?: number[];
logAfterId?: number;
messageAfterId?: number;
generalCooldowns?: GeneralCooldownSelector[];
};
}
@@ -288,6 +295,19 @@ const buildWorldInput = (
const month = readNumber(referenceBefore.world, 'month', request.setup?.world?.month ?? 1);
const turnTime = new Date(`${String(year).padStart(4, '0')}-${String(month).padStart(2, '0')}-01T00:00:00.000Z`);
const generals = referenceBefore.generals.map((row) => buildGeneral(row, turnTime));
const referenceGeneralCooldowns = Array.isArray(referenceBefore.world.generalCooldowns)
? referenceBefore.world.generalCooldowns
: [];
for (const rawCooldown of referenceGeneralCooldowns) {
const cooldown = asRecord(rawCooldown);
const generalId = readNumber(cooldown, 'generalId');
const actionName = readString(cooldown, 'actionName', '');
const nextAvailableTurn = cooldown.nextAvailableTurn;
const general = generals.find((entry) => entry.id === generalId);
if (general && actionName && typeof nextAvailableTurn === 'number' && Number.isFinite(nextAvailableTurn)) {
general.meta[`next_execute_${actionName}`] = nextAvailableTurn;
}
}
const fixtureNations = new Map((request.setup?.nations ?? []).map((row) => [readNumber(row, 'id'), row] as const));
const nations = referenceBefore.nations.map((row) =>
buildNation(
@@ -429,6 +449,7 @@ const projectWorld = (
generalIds: Set<number>;
cityIds: Set<number>;
nationIds: Set<number>;
generalCooldowns: GeneralCooldownSelector[];
}
): CanonicalTurnSnapshot => {
const state = world.getState();
@@ -489,6 +510,15 @@ const projectWorld = (
tickMinutes: Math.max(1, Math.round(state.tickSeconds / 60)),
turnTime: state.lastTurnTime.toISOString(),
isUnited: readNumber(state.meta, 'isUnited'),
generalCooldowns: selector.generalCooldowns.map(({ generalId, actionName }) => {
const general = world.getGeneralById(generalId);
const raw = general?.meta[`next_execute_${actionName}`];
return {
generalId,
actionName,
nextAvailableTurn: typeof raw === 'number' && Number.isFinite(raw) ? raw : null,
};
}),
},
generals,
cities: world
@@ -595,6 +625,7 @@ export const runCoreTurnCommandTrace = async (
]),
cityIds: new Set(referenceBefore.cities.map((row) => readNumber(row, 'id'))),
nationIds: new Set(referenceBefore.nations.map((row) => readNumber(row, 'id'))),
generalCooldowns: request.observe?.generalCooldowns ?? [],
};
const reservedTurns = new InMemoryReservedTurnStore(emptyDatabaseClient as never, {
maxGeneralTurns: 10,
@@ -931,6 +931,133 @@ integration('general command pre-required turn boundary matrix', () => {
);
});
const readGeneralCooldown = (
snapshot: { world: Record<string, unknown> },
generalId: number,
actionName: string
): number | null => {
const cooldowns = Array.isArray(snapshot.world.generalCooldowns) ? snapshot.world.generalCooldowns : [];
const matched = cooldowns.find(
(entry) =>
typeof entry === 'object' &&
entry !== null &&
(entry as Record<string, unknown>).generalId === generalId &&
(entry as Record<string, unknown>).actionName === actionName
);
const value =
typeof matched === 'object' && matched !== null ? (matched as Record<string, unknown>).nextAvailableTurn : null;
return typeof value === 'number' ? value : null;
};
integration('general command post-required cooldown boundary matrix', () => {
it('stores the same 60-turn cooldown after domestic trait reset completion', async () => {
const request = buildRequest('che_내정특기초기화', undefined, {
specialDomestic: 'che_인덕',
lastTurn: { command: '내정 특기 초기화', term: 1 },
});
request.observe!.generalCooldowns = [{ generalId: 1, actionName: '내정 특기 초기화' }];
const reference = runReferenceTurnCommandTraceRequest(
workspaceRoot!,
request as unknown as Record<string, unknown>
);
const core = await runCoreTurnCommandTrace(request, reference.before);
const expectedNextAvailableTurn = 190 * 12 + 1 - 1 + 60 - 1;
expect(reference.execution.outcome).toMatchObject({ completed: true });
expect(core.execution.outcome).toMatchObject({
requestedAction: 'che_내정특기초기화',
actionKey: 'che_내정특기초기화',
usedFallback: false,
});
expect(readGeneralCooldown(reference.after, 1, '내정 특기 초기화')).toBe(expectedNextAvailableTurn);
expect(readGeneralCooldown(core.after, 1, '내정 특기 초기화')).toBe(expectedNextAvailableTurn);
expect(core.rng).toEqual(reference.rng);
expect(
compareTurnSnapshotDeltas(reference.before, reference.after, core.before, core.after, {
ignoredPathPatterns: ignoredLifecyclePaths,
})
).toEqual([]);
}, 120_000);
it('blocks domestic trait reset one turn before the cooldown boundary', async () => {
const currentYearMonth = 190 * 12 + 1 - 1;
const request = buildRequest('che_내정특기초기화', undefined, {
specialDomestic: 'che_인덕',
lastTurn: { command: '내정 특기 초기화', term: 1 },
});
request.setup!.generalCooldowns = [
{
generalId: 1,
actionName: '내정 특기 초기화',
nextAvailableTurn: currentYearMonth + 1,
},
];
request.observe!.generalCooldowns = [{ generalId: 1, actionName: '내정 특기 초기화' }];
const reference = runReferenceTurnCommandTraceRequest(
workspaceRoot!,
request as unknown as Record<string, unknown>
);
const core = await runCoreTurnCommandTrace(request, reference.before);
expect(readGeneralCooldown(reference.before, 1, '내정 특기 초기화')).toBe(currentYearMonth + 1);
expect(readGeneralCooldown(core.before, 1, '내정 특기 초기화')).toBe(currentYearMonth + 1);
expect(reference.execution.outcome).toMatchObject({ completed: false });
expect(core.execution.outcome).toMatchObject({
requestedAction: 'che_내정특기초기화',
actionKey: '휴식',
usedFallback: true,
blockedReason: '1턴 더 기다려야 합니다',
});
expect(reference.after.logs.some((entry) => String(entry.text).includes('1턴 더 기다려야 합니다'))).toBe(true);
expect(core.after.logs.some((entry) => String(entry.text).includes('1턴 더 기다려야 합니다'))).toBe(true);
expect(readGeneralCooldown(reference.after, 1, '내정 특기 초기화')).toBe(currentYearMonth + 1);
expect(readGeneralCooldown(core.after, 1, '내정 특기 초기화')).toBe(currentYearMonth + 1);
expect(core.rng).toEqual(reference.rng);
expect(
compareTurnSnapshotDeltas(reference.before, reference.after, core.before, core.after, {
ignoredPathPatterns: ignoredLifecyclePaths,
})
).toEqual([]);
}, 120_000);
it('allows war trait reset exactly at the cooldown boundary', async () => {
const currentYearMonth = 190 * 12 + 1 - 1;
const request = buildRequest('che_전투특기초기화', undefined, {
specialWar: 'che_귀병',
lastTurn: { command: '전투 특기 초기화', term: 1 },
});
request.setup!.generalCooldowns = [
{
generalId: 1,
actionName: '전투 특기 초기화',
nextAvailableTurn: currentYearMonth,
},
];
request.observe!.generalCooldowns = [{ generalId: 1, actionName: '전투 특기 초기화' }];
const reference = runReferenceTurnCommandTraceRequest(
workspaceRoot!,
request as unknown as Record<string, unknown>
);
const core = await runCoreTurnCommandTrace(request, reference.before);
const expectedNextAvailableTurn = currentYearMonth + 60 - 1;
expect(reference.execution.outcome).toMatchObject({ completed: true });
expect(core.execution.outcome).toMatchObject({
requestedAction: 'che_전투특기초기화',
actionKey: 'che_전투특기초기화',
usedFallback: false,
});
expect(readGeneralCooldown(reference.after, 1, '전투 특기 초기화')).toBe(expectedNextAvailableTurn);
expect(readGeneralCooldown(core.after, 1, '전투 특기 초기화')).toBe(expectedNextAvailableTurn);
expect(core.rng).toEqual(reference.rng);
expect(
compareTurnSnapshotDeltas(reference.before, reference.after, core.before, core.after, {
ignoredPathPatterns: ignoredLifecyclePaths,
})
).toEqual([]);
}, 120_000);
});
type GeneralConstraintCase = {
name: string;
action: string;