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, type CanonicalReproductionComparison, type CanonicalReproductionPreview, } from '@stock-bot/stock-config/canonical-research'; import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy'; import type { Run } 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 RunReproduction: typeof import('../../apps/stock/web-app/src/features/backtest/components/RunReproduction').RunReproduction; let BacktestDetailPageV2: typeof import('../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2').BacktestDetailPageV2; let root: Root | undefined; let host: HTMLDivElement; let navigate: ReturnType; let location = ''; const sourceId = '11111111-1111-4111-8111-111111111111'; const otherId = '22222222-2222-4222-8222-222222222222'; const backtestId = '33333333-3333-4333-8333-333333333333'; const versionId = '44444444-4444-4444-8444-444444444444'; 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; headers: Headers; settled: boolean; signal?: AbortSignal | null; }; 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 item = [...host.querySelectorAll('button')].find( item => item.textContent?.trim() === label ); if (!item) { throw new Error(`Missing ${label}: ${host.textContent}`); } return item; } function Probe() { navigate = router.useNavigate(); location = router.useLocation().pathname; return null; } async function render(element: ReactElement, path = `/backtests/${backtestId}/run/${sourceId}`) { root ??= createRoot(host); await flush(() => root!.render( createElement(router.MemoryRouter, { initialEntries: [path] }, element, createElement(Probe)) ) ); } const run = (id = sourceId, extra: Partial = {}): Run => ({ id, backtestId, runNumber: 1, status: 'completed', speedMultiplier: null, progress: 100, createdAt: '2026-10-24', updatedAt: '2026-10-24', originalRunId: null, ...extra, }); function preview( id = sourceId, extra: Partial = {} ): CanonicalReproductionPreview { const owner = `strategy:${versionId}`; const { config, dataset } = nativeReplayFixture(3, 1, [owner]); config.matching.risk.ledger.sessionId = id; config.matching.risk.ledger.accountId = `research:${id}`; const builtin = builtinCatalogDescriptors[0]!; const request = canonicalRunRequestSchema.parse({ kind: 'canonical-research/v1', runId: id, backtestId, name: 'Frozen original inputs', strategy: { familyId: '55555555-5555-4555-8555-555555555555', versionId, origin: 'builtin', reviewId: '66666666-6666-4666-8666-666666666666', package: { version: 1, program: builtin.program, parameterSchema: builtin.parameterSchema, artifact: { format: 'esm-bundle/v1', entryExport: builtin.entryExport, content: 'Never execute this 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: 3 }, }, }, 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: [], }); return { originalRunId: id, backtestId, available: true, reason: null, currentReviewId: '77777777-7777-4777-8777-777777777777', request, ...extra, }; } const comparison = ( status: CanonicalReproductionComparison['status'] = 'match' ): CanonicalReproductionComparison => ({ version: 'canonical-reproduction/v1', runId: otherId, backtestId, originalRunId: sourceId, status, reason: null, originalHash: ['match', 'mismatch'].includes(status) ? 'a'.repeat(64) : null, reproducedHash: status === 'match' ? 'a'.repeat(64) : status === 'mismatch' ? 'b'.repeat(64) : null, }); async function open(source = run(), archived = false) { await render(createElement(RunReproduction, { run: source, archived })); await flush(() => button('Reproduce original').click()); } async function ready(source = run(), archived = false) { await open(source, archived); const value = preview(source.id); await flush(() => reply(request(`/api/v2/runs/${source.id}/reproduction`), value)); return value; } const post = () => request(`/api/v2/runs/${sourceId}/reproduce`, 'POST'); 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'); ({ RunReproduction } = await import( '../../apps/stock/web-app/src/features/backtest/components/RunReproduction' )); ({ BacktestDetailPageV2 } = await import( '../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2' )); }); 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', body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined, headers: new Headers(init?.headers), signal: init?.signal, settled: false, }; requests.push(item); return item.promise; // Ignore abort deliberately; component identity must fence late replies. }, }); }); 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('original-run reproduction UI', () => { test('preview is read-only, renders exact retained inputs, and double-click admission sends only source/key', async () => { const value = await ready(); expect(host.textContent).toContain('Frozen original inputs'); expect(host.textContent).toContain(value.request!.datasetHash); expect(host.textContent).toContain(versionId); expect(host.textContent).toContain('Random seed: 17'); expect(host.querySelector('pre')?.textContent).toContain('"fastPeriod": 2'); expect(host.querySelector('pre')?.textContent).toContain( value.request!.build.engineBinarySha256 ); expect(host.querySelector('pre')?.textContent).not.toContain('Never execute this code'); expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); const submit = button('Confirm reproduction'); await flush(() => { submit.click(); submit.click(); }); expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); expect(post().body).toEqual({}); expect(post().headers.get('Idempotency-Key')).toMatch(/^[a-f0-9-]{36}$/); await flush(() => reply(post(), run(otherId, { originalRunId: sourceId, status: 'pending' }), 202) ); expect(location).toBe(`/backtests/${backtestId}/run/${otherId}`); }); test('loading and failed preview do not become unavailable provenance and read retry does not submit', async () => { await open(); expect(host.textContent).toContain('Loading original inputs...'); expect(button('Confirm reproduction').disabled).toBe(true); await flush(() => reply(request(`/api/v2/runs/${sourceId}/reproduction`), { error: 'Store offline' }, 503) ); expect(host.textContent).toContain('Store offline'); expect(host.textContent).not.toContain('Original reproduction unavailable'); await flush(() => button('Refresh original inputs').click()); await flush(() => reply(request(`/api/v2/runs/${sourceId}/reproduction`), preview())); expect(button('Confirm reproduction').disabled).toBe(false); expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); }); test.each([ 'Legacy run lacks retained provenance', 'Original strategy approval was revoked', 'Installed build is unsupported', ])('%s displays an explicit unavailable reason with no fallback', async reason => { await open(); await flush(() => reply( request(`/api/v2/runs/${sourceId}/reproduction`), preview(sourceId, { available: false, reason, request: null, currentReviewId: null }) ) ); expect(host.textContent).toContain(reason); expect(button('Confirm reproduction').disabled).toBe(true); expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); }); test('an archived parent blocks fresh admission even if a stale preview says available', async () => { await ready(run(), true); expect(host.textContent).toContain('This backtest is archived'); expect(button('Confirm reproduction').disabled).toBe(true); }); test.each(['lost', 'malformed', 'wrong-parent', 'server-error'])( '%s response retains the key across close, refresh, archive and explicit retry', async failure => { await ready(); await flush(() => button('Confirm reproduction').click()); const first = post(); const key = first.headers.get('Idempotency-Key'); await flush(() => { if (failure === 'lost') { first.settled = true; first.reject(new Error('Lost')); } else if (failure === 'malformed') { reply(first, {}, 202); } else if (failure === 'wrong-parent') { reply(first, run(otherId, { originalRunId: sourceId, backtestId: 'wrong' }), 202); } else { reply(first, { error: 'Response unavailable' }, 500); } }); expect(host.textContent).toContain('previous request may already have been accepted'); await flush(() => button('Close').click()); await render(createElement(RunReproduction, { run: run(), archived: true })); await flush(() => button('Reproduce original').click()); await flush(() => reply( request(`/api/v2/runs/${sourceId}/reproduction`), preview(sourceId, { available: false, reason: 'Archived', currentReviewId: null }) ) ); expect(button('Retry reproduction').disabled).toBe(false); await flush(() => button('Retry reproduction').click()); expect(post().headers.get('Idempotency-Key')).toBe(key); expect(post().body).toEqual({}); await flush(() => reply(post(), run(otherId, { originalRunId: sourceId }), 202)); expect(location).toBe(`/backtests/${backtestId}/run/${otherId}`); } ); test.each([400, 401, 404, 409])( 'HTTP %s never automatically retries or changes the receipt', async status => { await ready(); await flush(() => button('Confirm reproduction').click()); const first = post(); const key = first.headers.get('Idempotency-Key'); await flush(() => reply(first, { error: `Definite rejection ${status}` }, status)); expect(host.textContent).toContain(`Definite rejection ${status}`); expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); await flush(() => button('Retry reproduction').click()); expect(post().headers.get('Idempotency-Key')).toBe(key); } ); test('a new receipt requires deliberate confirmation and fresh eligible preview', async () => { await ready(); await flush(() => button('Confirm reproduction').click()); const first = post(); await flush(() => reply(first, { error: 'Conflict' }, 409)); Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false }); await flush(() => button('Start new reproduction').click()); expect(button('Retry reproduction')).toBeTruthy(); Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true }); await flush(() => button('Start new reproduction').click()); expect(button('Confirm reproduction').disabled).toBe(true); await flush(() => reply(request(`/api/v2/runs/${sourceId}/reproduction`), preview())); await flush(() => button('Confirm reproduction').click()); expect(post().headers.get('Idempotency-Key')).not.toBe(first.headers.get('Idempotency-Key')); }); test('source and parent mismatched preview fails closed', async () => { await open(); await flush(() => reply(request(`/api/v2/runs/${sourceId}/reproduction`), preview(otherId))); expect(button('Confirm reproduction').disabled).toBe(true); expect(host.textContent).toContain('could not be verified'); await flush(() => button('Refresh original inputs').click()); const wrong = preview(); wrong.backtestId = otherId; wrong.request!.backtestId = otherId; await flush(() => reply(request(`/api/v2/runs/${sourceId}/reproduction`), wrong)); expect(host.textContent).toContain('different run or backtest'); expect(button('Confirm reproduction').disabled).toBe(true); }); test('late preview and late accepted mutation cannot navigate or overwrite a new selection', async () => { await open(); const oldPreview = request(`/api/v2/runs/${sourceId}/reproduction`); await render(createElement(RunReproduction, { run: run(otherId), archived: false })); await flush(() => reply(oldPreview, preview())); expect(host.querySelector('[role="dialog"]')).toBeNull(); await ready(); await flush(() => button('Confirm reproduction').click()); const oldPost = post(); await render(createElement(RunReproduction, { run: run(otherId), archived: false })); await flush(() => navigate(`/backtests/${backtestId}/run/${otherId}`)); await flush(() => reply(oldPost, run('accepted-late', { originalRunId: sourceId }), 202)); expect(location).toBe(`/backtests/${backtestId}/run/${otherId}`); expect(host.querySelector('[role="dialog"]')).toBeNull(); }); test.each(['match', 'mismatch', 'pending', 'unavailable'] as const)( 'saved reproduction displays server %s, exact source lineage and no invented result', async status => { await render( createElement(RunReproduction, { run: run(otherId, { originalRunId: sourceId }), archived: false, }) ); expect(host.textContent).toContain('Loading reproduction comparison'); const link = host.querySelector('a'); expect(link?.getAttribute('href')).toBe(`/backtests/${backtestId}/run/${sourceId}`); const value = comparison(status); if (status === 'unavailable') { value.reason = 'No completed saved result'; } await flush(() => reply(request(`/api/v2/runs/${otherId}/reproduction-comparison`), value)); expect(host.textContent).toContain( { match: 'Economic results match the original.', mismatch: 'Economic results differ from the original.', pending: 'Reproduction comparison pending completion.', unavailable: 'Reproduction comparison unavailable.', }[status] ); if (value.originalHash) { expect(host.textContent).toContain(value.originalHash); } if (status === 'unavailable') { expect(host.textContent).toContain(value.reason!); } expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); } ); test('comparison errors, malformed matches and foreign sources cannot display a successful match', async () => { await render( createElement(RunReproduction, { run: run(otherId, { originalRunId: sourceId }), archived: false, }) ); await flush(() => reply( request(`/api/v2/runs/${otherId}/reproduction-comparison`), { error: 'Unavailable store' }, 503 ) ); expect(host.textContent).toContain('Unavailable store'); expect(host.textContent).not.toContain('Economic results match'); await flush(() => button('Refresh comparison').click()); await flush(() => reply(request(`/api/v2/runs/${otherId}/reproduction-comparison`), { ...comparison(), originalHash: null, }) ); expect(host.textContent).toContain('could not be verified'); await flush(() => button('Refresh comparison').click()); await flush(() => reply(request(`/api/v2/runs/${otherId}/reproduction-comparison`), { ...comparison(), reproducedHash: 'b'.repeat(64), }) ); expect(host.textContent).toContain('could not be verified'); await flush(() => button('Refresh comparison').click()); await flush(() => reply(request(`/api/v2/runs/${otherId}/reproduction-comparison`), { ...comparison(), originalRunId: 'foreign', }) ); expect(host.textContent).toContain('does not match'); expect(host.textContent).not.toContain('Economic results match'); }); test('status changes invalidate late comparisons and request committed completion', async () => { await render( createElement(RunReproduction, { run: run(otherId, { originalRunId: sourceId, status: 'running' }), archived: false, }) ); const old = request(`/api/v2/runs/${otherId}/reproduction-comparison`); old.settled = true; await render( createElement(RunReproduction, { run: run(otherId, { originalRunId: sourceId }), archived: false, }) ); await flush(() => reply(request(`/api/v2/runs/${otherId}/reproduction-comparison`), comparison()) ); await flush(() => old.resolve(Response.json(comparison('pending')))); expect(host.textContent).toContain('Economic results match the original.'); expect(host.textContent).not.toContain('pending completion'); }); test('parent uses original preview even when current catalog configuration cannot execute', async () => { await render( createElement( router.Routes, null, createElement(router.Route, { path: '/backtests/:id/run/:runId', element: createElement(BacktestDetailPageV2), }) ) ); await flush(() => { reply(request(`/api/v2/backtests/${backtestId}`), { id: backtestId, name: 'Different current setup', strategy: 'catalog', strategyVersionId: 'different-version', strategyParameters: {}, symbols: ['OTHER'], startDate: '2024-01-01', endDate: '2024-01-02', initialCapital: 20000, config: {}, archivedAt: null, createdAt: '2024-01-01', updatedAt: '2024-01-01', }); reply(request(`/api/v2/backtests/${backtestId}/runs`), [run()]); }); await flush(() => { reply(request(`/api/v2/backtests/${backtestId}/canonical-capability`), { available: false, reason: 'Current version unavailable', }); reply(request(`/api/v2/runs/${sourceId}`), run()); }); await flush(() => reply(request(`/api/v2/runs/${sourceId}/results`), { error: 'Missing display result' }, 404) ); expect(host.textContent).toContain('Current version unavailable'); expect(host.textContent).toContain('Run current settings'); expect(button('Reproduce original').disabled).toBe(false); await flush(() => button('Reproduce original').click()); await flush(() => reply(request(`/api/v2/runs/${sourceId}/reproduction`), preview())); expect(button('Confirm reproduction').disabled).toBe(false); expect(host.textContent).toContain('Frozen original inputs'); }); });