import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test'; import { GlobalWindow } from 'happy-dom'; import { act, createElement, type ReactElement } from 'react'; import type { Root } from 'react-dom/client'; import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research'; import { costSensitivityInputSchema, type CostSensitivityDetail, type CostSensitivityPreview, } from '@stock-bot/stock-config/cost-sensitivity'; import type { ExperimentDetail, ExperimentPreview, ExperimentTrial, ExperimentTrialRetry, } from '@stock-bot/stock-config/experiments'; import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy'; import type { Backtest } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2'; import { nativeReplayFixture } from '../fixtures/native-replay'; const browser = new GlobalWindow({ url: 'http://localhost:5173' }); const keys = ['window', 'document', 'Event', 'ResizeObserver', 'IS_REACT_ACT_ENVIRONMENT'] as const; const originals = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])); let createRoot: typeof import('react-dom/client').createRoot; let router: typeof import('react-router-dom'); let ExperimentListPage: typeof import('../../apps/stock/web-app/src/features/experiments').ExperimentListPage; let ExperimentDetailPage: typeof import('../../apps/stock/web-app/src/features/experiments').ExperimentDetailPage; let root: Root | undefined; let host: HTMLDivElement; let navigate: ReturnType; let location = ''; const backtestId = '11111111-1111-4111-8111-111111111111'; const otherBacktestId = '22222222-2222-4222-8222-222222222222'; const experimentId = '33333333-3333-4333-8333-333333333333'; const otherExperimentId = '44444444-4444-4444-8444-444444444444'; const versionId = '55555555-5555-4555-8555-555555555555'; const runId = (index: number) => `77777777-7777-4777-8777-${String(index + 1).padStart(12, '0')}`; function deferred() { let resolve!: (value: T) => void; let reject!: (cause: Error) => void; const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); return { promise, resolve, reject }; } type Pending = ReturnType> & { path: string; method: string; body: unknown; rawBody: unknown; headers: Headers; settled: boolean; signal?: AbortSignal | null; credentials?: RequestCredentials; }; const requests: Pending[] = []; function request(path: string, method = 'GET') { const found = requests.find( item => item.path === path && item.method === method && !item.settled ); if (!found) { throw new Error( `Missing ${method} ${path}: ${requests.map(item => `${item.method} ${item.path} ${item.settled}`).join(', ')}` ); } return found; } function reply(item: Pending, value: unknown, status = 200) { item.settled = true; item.resolve(Response.json(value, { status })); } async function flush(action: () => void = () => {}) { await act(async () => { action(); await Promise.resolve(); }); } function button(label: string) { const found = [...host.querySelectorAll('button')].find( item => item.textContent?.trim() === label ); if (!found) { throw new Error(`Missing button ${label}: ${host.textContent}`); } return found; } function field(label: string) { const found = [...host.querySelectorAll('label')] .find( item => item.firstChild?.textContent?.trim() === label || item.textContent?.trim() === label ) ?.querySelector('input,select,textarea'); if (!found) { throw new Error(`Missing field ${label}`); } return found as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement; } function change(label: string, value: string) { const input = field(label); const prototype = input.tagName === 'SELECT' ? browser.HTMLSelectElement.prototype : input.tagName === 'TEXTAREA' ? browser.HTMLTextAreaElement.prototype : browser.HTMLInputElement.prototype; Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(input, value); input.dispatchEvent( new browser.Event(input.tagName === 'SELECT' ? 'change' : 'input', { bubbles: true, }) as unknown as Event ); } function Probe() { navigate = router.useNavigate(); location = router.useLocation().pathname + router.useLocation().search; return null; } async function render(element: ReactElement, path: string) { root ??= createRoot(host); await flush(() => root!.render( createElement(router.MemoryRouter, { initialEntries: [path] }, element, createElement(Probe)) ) ); } const template = (id = backtestId): Backtest => ({ id, name: 'Saved canonical template', strategy: 'sma', strategyVersionId: versionId, symbols: ['X0.US'], startDate: '2024-01-01', endDate: '2024-01-02', initialCapital: 100, config: { canonical: {}, datasetHash: 'a'.repeat(64) }, archivedAt: null, createdAt: '2026-10-24', updatedAt: '2026-10-24', }); function preview(count = 2, parent = backtestId): ExperimentPreview { const owner = `strategy:${versionId}`; const { config, dataset } = nativeReplayFixture(3, 1, [owner]); const previewId = '00000000-0000-4000-8000-000000000001'; config.matching.risk.ledger.sessionId = previewId; config.matching.risk.ledger.accountId = `research:${previewId}`; const builtin = builtinCatalogDescriptors[0]!; const candidates = Array.from({ length: count }, (_, index) => ({ index, trialKey: String(index + 1).padStart(64, '0'), parameters: { fastPeriod: index + 2, slowPeriod: 20 }, })); return { version: 'research-experiment-preview/v1', previewHash: 'e'.repeat(64), input: { backtestId: parent, name: 'Trend study', grid: { fastPeriod: candidates.map(item => item.parameters.fastPeriod) }, }, dataset: dataset.manifest, candidates, request: canonicalRunRequestSchema.parse({ kind: 'canonical-research/v1', runId: previewId, backtestId: parent, name: 'Frozen template name', strategy: { familyId: '66666666-6666-4666-8666-666666666666', versionId, origin: 'builtin', reviewId: '88888888-8888-4888-8888-888888888888', package: { version: 1, program: builtin.program, parameterSchema: builtin.parameterSchema, artifact: { format: 'esm-bundle/v1', entryExport: builtin.entryExport, content: 'Never execute fixture code', sha256: 'a'.repeat(64), }, dependencyLock: { format: 'bun-lock/v1', content: 'Retained lock', sha256: 'b'.repeat(64), }, source: { revision: 'c'.repeat(40), dirty: false }, build: { tool: 'bun', version: '1.2.17', target: 'browser' }, }, selection: { strategyId: builtin.program.strategyId, strategyVersion: builtin.program.strategyVersion, ownerId: owner, seed: 17, instrumentId: 'X0.US', seriesId: 'X0.US:1m', ownerBudget: '100', parameters: { fastPeriod: 2, slowPeriod: 20 }, }, }, datasetHash: dataset.manifest.hash, policy: config, analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null }, build: { version: 1, workerSha256: 'a'.repeat(64), engineWrapperSha256: 'b'.repeat(64), engineBinarySha256: 'c'.repeat(64), dependencyLockSha256: 'd'.repeat(64), runtime: 'bun', runtimeVersion: '1.2.17', platform: 'linux', arch: 'x64', }, modelArtifacts: [], }), }; } function metrics(): NonNullable { return { totalReturn: 0, cagr: null, maxDrawdown: 0, exposureTime: 0, volatility: null, downsideDeviation: null, sharpeRatio: null, sortinoRatio: null, var95: null, cvar95: null, var99: null, alpha: null, beta: null, informationRatio: null, roundTripCount: null, winRate: null, profitFactor: null, avgWin: null, avgLoss: null, }; } function detail( source: ExperimentPreview | CostSensitivityPreview = preview(), statuses: ExperimentTrial['status'][] = source.candidates.map(() => 'pending') ): ExperimentDetail | CostSensitivityDetail { const trials: ExperimentTrial[] = source.candidates.map((item, index) => ({ ...item, runId: statuses[index] === 'missing' ? null : runId(index), attemptNumber: 0, retryCount: 0, status: statuses[index]!, progress: statuses[index] === 'completed' ? 100 : 0, cancelRequested: false, error: statuses[index] === 'failed' ? 'Strategy callback failed' : null, comparable: statuses[index] === 'completed', diagnostic: statuses[index] === 'missing' ? 'Expected child run is missing' : null, metrics: statuses[index] === 'completed' ? metrics() : null, unavailable: statuses[index] === 'completed' ? { sharpeRatio: 'insufficient-periods' } : null, limitations: [], })); return { kind: source.version === 'cost-sensitivity-preview/v1' ? 'cost-sensitivity' : 'parameters', id: experimentId, name: source.input.name, backtestId: source.input.backtestId, createdAt: '2026-10-24T14:00:00Z', cancelRequested: false, trialCount: trials.length, counts: { pending: 0, running: 0, paused: 0, completed: 0, failed: 0, cancelled: 0, ...Object.fromEntries( ['pending', 'running', 'paused', 'completed', 'failed', 'cancelled'].map(status => [ status, trials.filter(item => item.status === status).length, ]) ), }, datasetHash: source.request.datasetHash, strategyVersionId: versionId, previewHash: source.previewHash, preview: source, trials, } as ExperimentDetail | CostSensitivityDetail; } async function list(parent = backtestId) { await render(createElement(ExperimentListPage), `/experiments?backtestId=${parent}`); await flush(() => { reply(request('/api/v2/backtests?limit=50&offset=0'), [template(parent)]); reply(request(`/api/v2/experiments?backtestId=${parent}`), { experiments: [] }); }); } const costPath = '/api/v2/experiments/cost-sensitivity'; const detailPath = `/api/v2/experiments/${experimentId}`; function costs( scenarios = [{ feeRate: '0.00100000', slippageRate: '0.00200000' }] ): CostSensitivityPreview { const source = preview(1); source.input.grid = {}; const input = costSensitivityInputSchema.parse({ backtestId: source.input.backtestId, name: source.input.name, scenarios, }); const pairs = [ { feeRate: source.request.policy.matching.risk.feeRate, slippageRate: source.request.policy.matching.slippageRate, }, ...input.scenarios, ]; return { version: 'cost-sensitivity-preview/v1', previewHash: 'f'.repeat(64), input, source, request: structuredClone(source.request), dataset: structuredClone(source.dataset), candidates: pairs.map((costs, index) => ({ index, trialKey: String(index + 3).padStart(64, '0'), parameters: { ...source.request.strategy.selection.parameters }, costs, })), }; } async function ready(value = costs()) { await list(); await flush(() => { change('Experiment name', value.input.name); change('Experiment type', 'cost-sensitivity'); }); for (let i = 1; i < value.input.scenarios.length; i++) { await flush(() => button('Add cost scenario').click()); } await flush(() => value.input.scenarios.forEach((scenario, index) => { change(`Scenario ${index + 1} fee rate`, scenario.feeRate); change(`Scenario ${index + 1} slippage rate`, scenario.slippageRate); }) ); await flush(() => button('Preview experiment').click()); await flush(() => reply(request(`${costPath}/preview`, 'POST'), { preview: value })); return value; } async function lose(item: Pending) { await flush(() => { item.settled = true; item.reject(new Error('Response lost')); }); } async function showDetail(value?: ExperimentDetail | CostSensitivityDetail) { const routes = createElement( router.Routes, null, createElement(router.Route, { path: '/experiments/:experimentId', element: createElement(ExperimentDetailPage), }) ); await render(routes, `/experiments/${value?.id ?? experimentId}`); if (value) { await flush(() => reply(request(`/api/v2/experiments/${value.id}`), { experiment: value })); } } beforeAll(async () => { for (const [key, value] of Object.entries({ window: browser, document: browser.document, Event: browser.Event, ResizeObserver: browser.ResizeObserver, IS_REACT_ACT_ENVIRONMENT: true, })) { Object.defineProperty(globalThis, key, { configurable: true, writable: true, value }); } ({ createRoot } = await import('react-dom/client')); router = await import('react-router-dom'); ({ ExperimentListPage, ExperimentDetailPage } = await import( '../../apps/stock/web-app/src/features/experiments' )); }); beforeEach(() => { requests.length = 0; location = ''; host = browser.document.createElement('div') as unknown as HTMLDivElement; browser.document.body.append(host as never); Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true }); Object.defineProperty(browser, 'fetch', { configurable: true, value: (input: unknown, init?: RequestInit) => { const url = new URL(String(input)); const item: Pending = { ...deferred(), path: url.pathname + url.search, method: init?.method ?? 'GET', rawBody: init?.body, body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined, headers: new Headers(init?.headers), signal: init?.signal, credentials: init?.credentials, settled: false, }; requests.push(item); return item.promise; // Deliberately ignore abort: identity fences must still reject stale responses. }, }); }); afterEach(async () => { if (root) { await flush(() => root!.unmount()); } root = undefined; host.remove(); }); afterAll(async () => { await browser.happyDOM.close(); for (const key of keys) { const old = originals.get(key); if (old) { Object.defineProperty(globalThis, key, old); } else { Reflect.deleteProperty(globalThis, key); } } }); describe('cost sensitivity in the existing experiment editor', () => { test('normalizes fraction spellings, previews baseline without writes, and submits the same frozen cost body', async () => { await list(); await flush(() => { change('Experiment name', 'Trend study'); change('Experiment type', 'cost-sensitivity'); }); expect(field('Scenario 1 fee rate').value).toBe(''); expect(host.querySelector('textarea')).toBeNull(); await flush(() => { change('Scenario 1 fee rate', '0.001'); change('Scenario 1 slippage rate', '0.0020'); }); await flush(() => button('Preview experiment').click()); const preparing = request(`${costPath}/preview`, 'POST'); expect(preparing.body).toEqual(costs().input); expect(requests.filter(item => item.path === costPath && item.method === 'POST')).toHaveLength( 0 ); await flush(() => reply(preparing, { preview: costs() })); expect(host.textContent).toContain('Baseline'); expect(host.textContent).toContain('0.00100000'); expect(host.textContent).toContain('2 trials'); expect(host.textContent).toContain('Fixed half-spread rate:'); const confirm = button('Confirm experiment'); await flush(() => { confirm.click(); confirm.click(); }); const post = request(costPath, 'POST'); expect(post.body).toEqual({ ...costs().input, previewHash: costs().previewHash }); expect(post.credentials).toBe('include'); expect(requests.filter(item => item.path === costPath && item.method === 'POST')).toHaveLength( 1 ); await flush(() => reply(post, { experiment: detail(costs()) }, 202)); expect(location).toBe(`/experiments/${experimentId}`); }); test('normalized duplicate pairs receive explicit preview failure and preserve editable inputs', async () => { await list(); await flush(() => { change('Experiment name', 'Trend study'); change('Experiment type', 'cost-sensitivity'); }); await flush(() => button('Add cost scenario').click()); await flush(() => { change('Scenario 1 fee rate', '0.001'); change('Scenario 1 slippage rate', '0.002'); change('Scenario 2 fee rate', '0.00100000'); change('Scenario 2 slippage rate', '0.00200000'); }); await flush(() => button('Preview experiment').click()); const previewRequest = request(`${costPath}/preview`, 'POST'); const input = previewRequest.body as { scenarios: unknown[] }; expect(input.scenarios[0]).toEqual(input.scenarios[1]); await flush(() => reply(previewRequest, { error: 'Duplicate normalized cost pair' }, 400)); expect(host.textContent).toContain('Duplicate normalized cost pair'); expect(field('Scenario 1 fee rate').value).toBe('0.001'); expect(field('Experiment type').disabled).toBe(false); }); test.each(['-0.01', '1.00000001', 'not-a-number'])( 'invalid fee %s never sends preview', async value => { await ready(); await flush(() => change('Scenario 1 fee rate', value)); const before = requests.length; await flush(() => button('Preview experiment').click()); expect(requests).toHaveLength(before); expect(host.querySelector('[role="alert"]')).not.toBeNull(); } ); test('slippage one is rejected while fee one is accepted as a fraction', async () => { await ready(); await flush(() => { change('Scenario 1 fee rate', '1'); change('Scenario 1 slippage rate', '1'); }); const before = requests.length; await flush(() => button('Preview experiment').click()); expect(requests).toHaveLength(before); await flush(() => change('Scenario 1 slippage rate', '0.99999999')); await flush(() => button('Preview experiment').click()); expect( (request(`${costPath}/preview`, 'POST').body as { scenarios: unknown[] }).scenarios ).toEqual([{ feeRate: '1.00000000', slippageRate: '0.99999999' }]); }); test.each(['network', 'malformed', 'wrong-kind', 'foreign'] as const)( '%s submission retains mode, body and key for exact retry', async kind => { await ready(); await flush(() => button('Confirm experiment').click()); const original = request(costPath, 'POST'); if (kind === 'network') { await lose(original); } else { const value = detail(costs()); if (kind === 'foreign') { value.backtestId = otherBacktestId; } await flush(() => reply( original, kind === 'malformed' ? { experiment: {} } : { experiment: kind === 'wrong-kind' ? detail() : value }, 202 ) ); } expect(host.textContent).toContain('Acceptance is unconfirmed.'); expect(field('Experiment type').disabled).toBe(true); expect( field('Scenario 1 fee rate').disabled || field('Scenario 1 fee rate').closest('fieldset')!.disabled ).toBe(true); await flush(() => change('Experiment type', 'parameters')); expect(field('Experiment type').value).toBe('cost-sensitivity'); await flush(() => button('Retry experiment submission').click()); const retry = request(costPath, 'POST'); expect(retry.rawBody).toBe(original.rawBody); expect(retry.headers.get('Idempotency-Key')).toBe(original.headers.get('Idempotency-Key')); expect( requests.some(item => item.path === '/api/v2/experiments' && item.method === 'POST') ).toBe(false); await flush(() => reply(retry, { experiment: detail(costs(), ['completed', 'completed']) }, 202) ); expect(location).toBe(`/experiments/${experimentId}`); } ); test('releasing uncertain intent is explicit and requires a fresh preview', async () => { await ready(); await flush(() => button('Confirm experiment').click()); await lose(request(costPath, 'POST')); Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false }); await flush(() => button('Start new experiment').click()); expect(field('Experiment type').disabled).toBe(true); Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true }); await flush(() => button('Start new experiment').click()); expect(field('Experiment type').disabled).toBe(false); expect(host.querySelector('[aria-label="Prepared cost scenarios"]')).toBeNull(); }); test('same-event mode change cannot submit the previously prepared ordinary experiment', async () => { await list(); await flush(() => { change('Experiment name', 'Trend study'); change('Parameter grid (JSON)', JSON.stringify(preview().input.grid)); }); await flush(() => button('Preview experiment').click()); await flush(() => reply(request('/api/v2/experiments/preview', 'POST'), { preview: preview() }) ); const submit = button('Confirm experiment'); await flush(() => { change('Experiment type', 'cost-sensitivity'); submit.click(); }); expect( requests.filter(item => item.method === 'POST' && !item.path.endsWith('/preview')) ).toHaveLength(0); expect(field('Experiment type').value).toBe('cost-sensitivity'); }); test('mode changes fence pending reads, retain drafts and disable parameter-only panels', async () => { await ready(); await flush(() => button('Preview experiment').click()); const stale = request(`${costPath}/preview`, 'POST'); await flush(() => change('Experiment type', 'parameters')); expect(stale.signal?.aborted).toBe(true); await flush(() => reply(stale, { preview: costs() })); expect(host.querySelector('[aria-label="Prepared cost scenarios"]')).toBeNull(); await flush(() => change('Parameter grid (JSON)', '{"fastPeriod":[3]}')); await flush(() => change('Experiment type', 'cost-sensitivity')); expect(field('Scenario 1 fee rate').value).toBe('0.00100000'); expect(button('Preview chronological validation').disabled).toBe(true); expect(button('Preview walk-forward').disabled).toBe(true); await flush(() => change('Experiment type', 'parameters')); expect(field('Parameter grid (JSON)').value).toBe('{"fastPeriod":[3]}'); }); test('adding/removing scenarios invalidates preview and preserves order', async () => { await ready(); expect(button('Remove scenario 1').disabled).toBe(true); await flush(() => button('Add cost scenario').click()); expect(host.querySelector('[aria-label="Prepared cost scenarios"]')).toBeNull(); await flush(() => { change('Scenario 2 fee rate', '0.02'); change('Scenario 2 slippage rate', '0.03'); }); await flush(() => button('Remove scenario 1').click()); expect(field('Scenario 1 fee rate').value).toBe('0.02'); expect(button('Remove scenario 1').disabled).toBe(true); }); test('unconfirmed cost submission guards owned links and ignores late completion after source navigation', async () => { await ready(); await flush(() => button('Confirm experiment').click()); const original = request(costPath, 'POST'); await lose(original); Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false }); await flush(() => [...host.querySelectorAll('a')] .find(item => item.textContent === 'Show all experiments')! .click() ); expect(location).toContain(backtestId); await flush(() => button('Retry experiment submission').click()); const retry = request(costPath, 'POST'); await flush(() => navigate(`/experiments?backtestId=${otherBacktestId}`)); await flush(() => reply(retry, { experiment: detail(costs()) }, 202)); expect(location).toContain(otherBacktestId); }); test.each([ 'baseline', 'parameters', 'source-grid', 'source-request', 'source-dataset', 'order', 'missing-costs', 'duplicates', 'extra-grid', ] as const)('malformed %s preview fails closed', async kind => { await ready(); await flush(() => button('Preview experiment').click()); const value = costs(); if (kind === 'baseline') { value.candidates[0]!.costs.feeRate = '0.05000000'; } if (kind === 'parameters') { value.candidates[1]!.parameters.fastPeriod = 3; } if (kind === 'source-grid') { value.source.input.grid = { fastPeriod: [2] }; } if (kind === 'source-request') { value.request.policy.matching.halfSpreadRate = '0.50000000' as never; } if (kind === 'source-dataset') { value.dataset = { ...value.dataset, hash: '1'.repeat(64) }; } if (kind === 'order') { value.candidates.reverse(); } if (kind === 'missing-costs') { delete (value.candidates[1] as Partial<(typeof value.candidates)[number]>).costs; } if (kind === 'duplicates') { value.input.scenarios[0] = { ...value.candidates[0]!.costs }; value.candidates[1]!.costs = { ...value.candidates[0]!.costs }; } if (kind === 'extra-grid') { Object.assign(value.input, { grid: {} }); } await flush(() => reply(request(`${costPath}/preview`, 'POST'), { preview: value })); expect(host.textContent).toContain('could not be verified'); expect(host.querySelector('[aria-label="Prepared cost scenarios"]')).toBeNull(); }); }); describe('cost outcomes on the ordinary detail and retry routes', () => { test('all outcomes keep exact costs, null reasons and zero without ranking', async () => { const value = detail( costs([ { feeRate: '0.001', slippageRate: '0.002' }, { feeRate: '0.002', slippageRate: '0.003' }, { feeRate: '0.003', slippageRate: '0.004' }, { feeRate: '0.004', slippageRate: '0.005' }, ]), ['completed', 'failed', 'missing', 'cancelled', 'completed'] ); value.trials[4]!.comparable = false; value.trials[4]!.diagnostic = 'Policy mismatch'; await showDetail(value); expect(host.textContent).toContain('Scenario / costs / fixed parameters'); expect(host.textContent).toContain('Baseline'); expect(host.textContent).toContain('Scenario 4'); expect(host.textContent).toContain('Fee rate: 0.00100000'); expect(host.textContent).toContain('Unavailable: insufficient-periods'); expect(host.textContent).toContain('Strategy callback failed'); expect(host.textContent).toContain('Expected child run is missing'); expect(host.textContent).toContain('Incomparable'); expect(host.textContent).toContain('Policy mismatch'); expect([...host.querySelectorAll('td')].some(item => item.textContent === '0')).toBe(true); expect(requests.every(item => item.method === 'GET')).toBe(true); }); test.each([ 'wrong-kind', 'missing-kind', 'unknown-kind', 'trial-costs', 'fixed-parameters', 'trial-order', 'missing-row', 'ordinary-cost-injection', ] as const)('malformed %s detail cannot display results', async kind => { await showDetail(); const value = detail(costs(), ['completed', 'completed']); if (kind === 'wrong-kind') { value.kind = 'parameters'; } if (kind === 'missing-kind') { delete value.kind; } if (kind === 'unknown-kind') { Object.assign(value, { kind: 'unknown' }); } if (kind === 'trial-costs') { Object.assign(value.trials[1]!, { costs: { feeRate: '0.9', slippageRate: '0.9' } }); } if (kind === 'fixed-parameters') { value.trials[1]!.parameters.fastPeriod = 7; } if (kind === 'trial-order') { value.trials.reverse(); } if (kind === 'missing-row') { value.trials.pop(); } let raw: unknown = value; if (kind === 'ordinary-cost-injection') { const ordinary = detail(); Object.assign(ordinary.trials[0]!, { costs: { feeRate: '0', slippageRate: '0' } }); raw = ordinary; } await flush(() => reply(request(detailPath), { experiment: raw })); expect(host.textContent).toContain('could not be verified'); expect(host.textContent).not.toContain('Every trial outcome'); }); test('same-event refresh blocks cancellation until the readonly response resolves', async () => { await showDetail(detail(costs())); const cancel = button('Cancel remaining trials'); await flush(() => { button('Refresh experiment').click(); cancel.click(); }); expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); await flush(() => reply(request(detailPath), { experiment: detail(costs()) })); await flush(() => button('Cancel remaining trials').click()); const value = detail(costs()); value.cancelRequested = true; await flush(() => reply(request(`${detailPath}/cancel`, 'POST'), { experiment: value })); expect(host.textContent).toContain('Cancellation requested'); }); test('failed cost trial reuses existing retry and lazy failure history with exact captured receipt', async () => { const value = detail(costs(), ['completed', 'failed']) as CostSensitivityDetail; await showDetail(value); await flush(() => button('Retry trial 2').click()); await flush(() => button('Confirm retry trial 2').click()); const path = `${detailPath}/trials/${runId(1)}/retry`, original = request(path, 'POST'); expect(original.body).toEqual({ expectedAttemptNumber: 0, expectedRetryCount: 0 }); await lose(original); await flush(() => button('Refresh experiment').click()); const newer = detail(costs(), ['completed', 'completed']) as CostSensitivityDetail; newer.trials[1]!.attemptNumber = 1; newer.trials[1]!.retryCount = 1; await flush(() => reply(request(detailPath), { experiment: newer })); const saved: ExperimentTrialRetry = { id: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', experimentId, runId: runId(1), trialKey: value.trials[1]!.trialKey, retryNumber: 1, previousAttemptNumber: 0, previousAttemptId: null, error: 'Strategy callback failed', progress: 0, currentDate: null, startedAt: null, completedAt: null, pausedAt: null, failureUpdatedAt: '2026-10-24T10:00:00Z', recordedAt: '2026-10-24T11:00:00Z', principal: 'operator', reviewId: '88888888-8888-4888-8888-888888888888', }; await flush(() => button('Retry same request for trial 2').click()); const retry = request(path, 'POST'); expect(retry.rawBody).toBe(original.rawBody); expect(retry.headers.get('Idempotency-Key')).toBe(original.headers.get('Idempotency-Key')); await flush(() => reply(retry, { retry: saved, experiment: newer }, 202)); expect(host.textContent).toContain('Retry 1 accepted'); expect(host.textContent).toContain('Fee rate: 0.00100000'); await flush(() => button('Show retry history for trial 2').click()); await flush(() => reply(request(`${detailPath}/trials/${runId(1)}/retries`), { retries: [saved] }) ); expect(host.textContent).toContain('Strategy callback failed'); expect(host.textContent).toContain('previous attempt 0'); }); test('late detail cannot replace a different saved experiment', async () => { await showDetail(); const stale = request(detailPath); await flush(() => navigate(`/experiments/${otherExperimentId}`)); const other = detail(costs()); other.id = otherExperimentId; await flush(() => reply(request(`/api/v2/experiments/${otherExperimentId}`), { experiment: other }) ); await flush(() => reply(stale, { experiment: detail(costs(), ['completed', 'completed']) })); expect(location).toBe(`/experiments/${otherExperimentId}`); expect(host.textContent).toContain('pending'); }); test('saved list identifies cost diagnostics and opens the existing detail route', async () => { await render(createElement(ExperimentListPage), `/experiments?backtestId=${backtestId}`); await flush(() => reply(request(`/api/v2/experiments?backtestId=${backtestId}`), { experiments: [detail(costs())], }) ); expect(host.textContent).toContain('Cost sensitivity ยท template diagnostics'); const link = [...host.querySelectorAll('a')].find(item => item.textContent === 'Trend study')!; expect(link.getAttribute('href')).toBe(`/experiments/${experimentId}`); await flush(() => link.click()); expect(location).toBe(`/experiments/${experimentId}`); }); });