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 type { CanonicalStoredSourcePreparation } from '@stock-bot/stock-config/canonical-research'; import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2'; import type { Backtest, Run, RunResult, } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2'; import { nativeReplayFixture } from '../fixtures/native-replay'; // Local to this file: no global preload, browser server or second test runner. const browser = new GlobalWindow({ url: 'http://localhost:5173' }); const globals = [ 'window', 'document', 'WebSocket', 'ResizeObserver', 'IS_REACT_ACT_ENVIRONMENT', ] as const; const savedGlobals = new Map( globals.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]) ); const realTimeout = globalThis.setTimeout; const realClearTimeout = globalThis.clearTimeout; const realInterval = globalThis.setInterval; const realClearInterval = globalThis.clearInterval; let createRoot: typeof import('react-dom/client').createRoot; let useBacktestV2: typeof import('../../apps/stock/web-app/src/features/backtest/hooks/useBacktestV2').useBacktestV2; let useWebSocket: typeof import('../../apps/stock/web-app/src/hooks/useWebSocket').useWebSocket; let RunControlsCompact: typeof import('../../apps/stock/web-app/src/features/backtest/components/RunControlsCompact').RunControlsCompact; let BacktestDetailPageV2: typeof import('../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2').BacktestDetailPageV2; let CreateBacktestDialog: typeof import('../../apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog').CreateBacktestDialog; let BacktestListPageV2: typeof import('../../apps/stock/web-app/src/features/backtest/BacktestListPageV2').BacktestListPageV2; let router: typeof import('react-router-dom'); let root: Root | undefined; let host: HTMLDivElement; let latest: ReturnType; let renders = 0; let pageLocation = ''; let navigatePage: ReturnType; let now = 0; let timerId = 0; const timers = new Map< number, { at: number; delay: number; callback: () => void; repeat: boolean } >(); function submittedBody(request: { body?: string }): string { if (typeof request.body !== 'string') { throw new Error('Submission body is missing'); } return request.body; } function deferred() { let resolve!: (value: T) => void; let reject!: (reason: Error) => void; const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); return { promise, resolve, reject }; } type Request = ReturnType> & { path: string; query: string; method: string; signal?: AbortSignal | null; settled: boolean; body?: string; headers: Headers; }; const requests: Request[] = []; function request(path: string, method = 'GET') { const found = requests.find( item => item.path === path && item.method === method && !item.settled ); if (!found) { throw new Error(`No pending ${method} ${path}`); } return found; } function reply(pending: Request, body: unknown, status = 200) { pending.settled = true; pending.resolve(Response.json(body, { status })); } function fail(pending: Request) { pending.settled = true; pending.reject(new Error('Network unavailable')); } const run = (id: string, status: Run['status'] = 'running', extra: Partial = {}): Run => ({ id, backtestId: 'definition', runNumber: 1, status, speedMultiplier: null, progress: 0, createdAt: '2024-01-01', updatedAt: '2024-01-01', ...extra, }); const results = (id: string): RunResult => ({ runId: id, backtestId: 'definition', engine: 'typescript', status: 'completed', completedAt: '2024-02-01', config: { name: 'Fixture', strategy: 'sma', symbols: ['A.US'], startDate: '2024-01-01', endDate: '2024-02-01', initialCapital: 1000, commission: 0, slippage: 0, dataFrequency: '1d', parameters: {}, }, metrics: { totalReturn: 0, sharpeRatio: null, maxDrawdown: 0, winRate: 0, totalTrades: 0, profitFactor: null, avgWin: 0, avgLoss: 0, }, equity: [], ohlcData: {}, positions: [], trades: [], analytics: { exposureTime: null }, executionTime: 0, }); const definition = { id: 'definition', name: 'Fixture', strategy: 'catalog', strategyVersionId: 'version-one', symbols: ['A.US'], startDate: '2024-01-01', endDate: '2024-02-01', initialCapital: 1000, config: {}, createdAt: '2024-01-01', updatedAt: '2024-01-01', archivedAt: null, }; class TestSocket { static OPEN = 1; static CONNECTING = 0; static instances: TestSocket[] = []; readyState = 0; onopen: (() => void) | null = null; onmessage: ((event: { data: string }) => void) | null = null; onclose: (() => void) | null = null; onerror: (() => void) | null = null; constructor(readonly url: string) { TestSocket.instances.push(this); } send() {} open() { this.readyState = 1; this.onopen?.(); } close() { this.readyState = 3; this.onclose?.(); } message(value: unknown) { this.onmessage?.({ data: JSON.stringify(value) }); } } async function flush(action: () => void = () => {}) { await act(async () => { action(); await Promise.resolve(); }); } async function advance(ms: number) { now += ms; const due = [...timers].filter(([, timer]) => timer.at <= now); await flush(() => { for (const [id, timer] of due) { if (!timers.has(id)) { continue; } timers.delete(id); if (timer.repeat) { timers.set(id, { ...timer, at: now + timer.delay }); } timer.callback(); } }); } const polls = () => [...timers.values()].filter(timer => timer.delay === 1000).length; function click(label: string) { const buttons = [...host.querySelectorAll('button')]; const button = buttons.find(item => item.textContent?.trim() === label) ?? buttons.find(item => item.getAttribute('aria-label') === label); if (!button) { throw new Error(`Missing button ${label}`); } button.click(); } function settingsField(label: string) { const field = host.querySelector(`[aria-label="${label}"]`) as | HTMLInputElement | HTMLSelectElement | null; if (!field) { throw new Error(`Missing settings field ${label}`); } return field; } function editSettings(label: string, value: string) { const field = settingsField(label); const prototype = field.tagName === 'SELECT' ? browser.HTMLSelectElement.prototype : browser.HTMLInputElement.prototype; Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(field, value); field.dispatchEvent( new browser.Event(field.tagName === 'SELECT' ? 'change' : 'input', { bubbles: true, }) as unknown as Event ); } function HookHost({ socket = false }: { socket?: boolean }) { latest = useBacktestV2(); renders++; useWebSocket({ runId: socket ? (latest.currentRun?.id ?? null) : null, onMessage: message => { if (message.type !== 'pong') { void latest.refreshRun(message.runId); } }, }); return latest.currentRun ? createElement(RunControlsCompact, { run: latest.currentRun, cancelRequested: latest.cancelRequested, onCancel: latest.cancelRun, onRerun: () => {}, }) : null; } async function mount(element: ReactElement = createElement(HookHost)) { root = createRoot(host); await flush(() => root!.render( element.type === CreateBacktestDialog ? createElement(router.MemoryRouter, null, element) : element ) ); } async function select(id: string) { await flush(() => { void latest.selectRun(id); }); } async function selectRunning(id = 'A', status: Run['status'] = 'running') { await select(id); await flush(() => reply(request(`/api/v2/runs/${id}`), run(id, status))); } async function mountPage(status: Run['status']) { await mount( createElement( router.MemoryRouter, { initialEntries: ['/backtests/definition/run/A'] }, createElement( router.Routes, null, createElement(router.Route, { path: '/backtests/:id/run/:runId', element: createElement(BacktestDetailPageV2), }) ), createElement(LocationProbe) ) ); await flush(() => { reply(request('/api/v2/backtests/definition'), definition); reply(request('/api/v2/backtests/definition/runs'), []); reply( request('/api/v2/runs/A'), run('A', status, status === 'failed' ? { error: 'Fixture failure' } : {}) ); }); } async function mountSettingsPage() { // Match App's sibling index/run routes: both URLs must retain the same page owner. await mount( createElement( router.MemoryRouter, { initialEntries: ['/backtests/definition'] }, createElement( router.Routes, null, createElement( router.Route, { path: '/backtests/:id' }, createElement(router.Route, { index: true, element: createElement(BacktestDetailPageV2), }), createElement(router.Route, { path: 'run/:runId', element: createElement(BacktestDetailPageV2), }) ) ), createElement(LocationProbe) ) ); await flush(() => { reply(request('/api/v2/backtests/definition'), definition); reply(request('/api/v2/backtests/definition/runs'), []); }); } const storedPreparationPath = '/api/v2/datasets/canonical/stored-source'; const retentionPath = '/api/v2/datasets/canonical/retain'; function sessionPreparation(): CanonicalStoredSourcePreparation { const { dataset } = nativeReplayFixture(3); const { calendars, series, executionSeries, bounds, universe, corporateActions } = dataset.manifest; const day = 86400000; const metadata = { calendars: calendars.map(calendar => ({ ...calendar, endDate: '2024-01-03', sessions: [ ...calendar.sessions, ...calendar.sessions.map(session => ({ date: '2024-01-02', open: session.open + day, close: session.close + day, })), ], })), series: series.map(item => ({ ...item, source: { provider: 'eod', revision: 'custody-fixture' }, availability: 'interval-end-assumption' as const, })), executionSeries, bounds: { ...bounds, tradeEnd: bounds.tradeEnd + day }, universe, corporateActions: corporateActions.map(item => ({ ...item, end: item.end + day })), }; const input = { metadata, bars: [0, day] .flatMap(offset => dataset.bars.map(bar => ({ seriesId: bar.seriesId, timestamp: bar.intervalStart + offset, open: bar.open, high: bar.high, low: bar.low, close: bar.close, volume: bar.volume, })) ) .map((bar, sourceSequence) => ({ ...bar, sourceSequence })), }; const normalized = createDatasetV2(input); return { selection: 'declared-sessions', input, preparation: { version: 'canonical-dataset-preparation/v1', hash: normalized.manifest.hash, manifest: normalized.manifest, available: true, reason: null, }, }; } async function beginStoredPreparation() { await flush(() => click('Settings')); await flush(() => click('Configure canonical research')); await flush(() => editSettings('Dataset input', 'stored-eod-sessions')); const stored = sessionPreparation(); await flush(() => { const input = settingsField('Source metadata JSON'); Object.defineProperty(input, 'files', { configurable: true, value: [ new browser.File([JSON.stringify(stored.input.metadata)], 'sessions.json', { type: 'application/json', }), ], }); input.dispatchEvent(new browser.Event('change', { bubbles: true }) as unknown as Event); }); await flush(() => click('Preview dataset')); return { stored, pending: request(storedPreparationPath, 'POST') }; } function LocationProbe() { pageLocation = router.useLocation().pathname; navigatePage = router.useNavigate(); return null; } beforeAll(async () => { for (const [key, value] of Object.entries({ window: browser, document: browser.document, WebSocket: TestSocket, ResizeObserver: browser.ResizeObserver, IS_REACT_ACT_ENVIRONMENT: true, })) { Object.defineProperty(globalThis, key, { configurable: true, writable: true, value }); } ({ createRoot } = await import('react-dom/client')); ({ useBacktestV2 } = await import( '../../apps/stock/web-app/src/features/backtest/hooks/useBacktestV2' )); ({ useWebSocket } = await import('../../apps/stock/web-app/src/hooks/useWebSocket')); ({ RunControlsCompact } = await import( '../../apps/stock/web-app/src/features/backtest/components/RunControlsCompact' )); ({ BacktestDetailPageV2 } = await import( '../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2' )); ({ CreateBacktestDialog } = await import( '../../apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog' )); ({ BacktestListPageV2 } = await import( '../../apps/stock/web-app/src/features/backtest/BacktestListPageV2' )); router = await import('react-router-dom'); }); beforeEach(() => { requests.length = 0; TestSocket.instances.length = 0; renders = 0; pageLocation = ''; now = 0; timers.clear(); host = browser.document.createElement('div') as unknown as HTMLDivElement; browser.document.body.append(host as never); browser.fetch = ((input: RequestInfo | URL, init?: RequestInit) => { if (new URL(String(input)).pathname.endsWith('/canonical-capability')) { return Promise.resolve(Response.json({ available: true, reason: null })); } const pending: Request = { ...deferred(), path: new URL(String(input)).pathname, query: new URL(String(input)).search, method: init?.method ?? 'GET', signal: init?.signal, body: typeof init?.body === 'string' ? init.body : undefined, headers: new Headers(init?.headers), settled: false, }; requests.push(pending); // Deliberately ignore abort: guards must also reject a late server continuation. return pending.promise; }) as unknown as typeof browser.fetch; const schedule = (repeat: boolean, original: typeof setTimeout) => ((callback: () => void, delay?: number, ...args: unknown[]) => { if (![1000, 3000, 30000].includes(delay ?? 0)) { return original(callback, delay, ...args); } const id = ++timerId; timers.set(id, { at: now + delay!, delay: delay!, callback, repeat }); return id; }) as typeof setTimeout; globalThis.setTimeout = schedule(false, realTimeout); globalThis.setInterval = schedule(true, realInterval as typeof setTimeout) as typeof setInterval; globalThis.clearTimeout = ((id: number) => { if (!timers.delete(id)) { realClearTimeout(id); } }) as typeof clearTimeout; globalThis.clearInterval = ((id: number) => { if (!timers.delete(id)) { realClearInterval(id); } }) as typeof clearInterval; }); afterEach(async () => { let leakedTimers = 0; try { if (root) { await flush(() => root!.unmount()); } leakedTimers = timers.size; } finally { root = undefined; globalThis.setTimeout = realTimeout; globalThis.clearTimeout = realClearTimeout; globalThis.setInterval = realInterval; globalThis.clearInterval = realClearInterval; timers.clear(); host?.remove(); } expect(leakedTimers).toBe(0); }); afterAll(async () => { try { await browser.happyDOM.close(); } finally { for (const key of globals) { const descriptor = savedGlobals.get(key); if (descriptor) { Object.defineProperty(globalThis, key, descriptor); } else { Reflect.deleteProperty(globalThis, key); } } } }); describe('settings custody within one backtest', () => { test('canonical settings draft survives tab switches without remounting', async () => { await mountSettingsPage(); expect(requests.some(item => item.path === '/api/v2/datasets/canonical')).toBe(false); expect(requests.some(item => item.path === '/api/v2/strategies')).toBe(false); await flush(() => click('Settings')); await flush(() => click('Configure canonical research')); await flush(() => { editSettings('Backtest name', 'Research draft'); editSettings('Owner budget', '250'); }); const input = settingsField('Backtest name'); const catalogRequests = requests.filter(item => item.path === '/api/v2/datasets/canonical'); expect(catalogRequests).toHaveLength(1); await flush(() => click('Runs')); const panel = host.querySelector('[aria-label="Backtest settings panel"]'); expect(panel?.hasAttribute('hidden')).toBe(true); expect(input.isConnected).toBe(true); for (const id of ['A', 'B']) { await flush(() => { void navigatePage(`/backtests/definition/run/${id}`); }); await flush(() => reply(request(`/api/v2/runs/${id}`), run(id, 'failed'))); expect(settingsField('Backtest name')).toBe(input); expect(panel?.hasAttribute('hidden')).toBe(true); } await flush(() => { void navigatePage('/backtests/definition'); }); await flush(() => click('Settings')); expect(panel?.hasAttribute('hidden')).toBe(false); expect(settingsField('Backtest name').value).toBe('Research draft'); expect(settingsField('Owner budget').value).toBe('250'); expect(settingsField('Backtest name')).toBe(input); expect(requests.filter(item => item.path === '/api/v2/datasets/canonical')).toEqual( catalogRequests ); expect(requests.filter(item => item.method !== 'GET')).toHaveLength(0); }); test('hidden previews and ambiguous retention preserve the captured input without rereading source', async () => { await mountSettingsPage(); const { stored, pending } = await beginStoredPreparation(); await flush(() => click('Runs')); expect(pending.signal?.aborted).toBe(false); await flush(() => reply(pending, stored)); await flush(() => click('Settings')); expect(host.textContent).toContain(stored.preparation.hash); await flush(() => click('Retain dataset')); const original = request(retentionPath, 'POST'); expect(JSON.parse(submittedBody(original))).toEqual({ input: stored.input, expectedHash: stored.preparation.hash, }); await flush(() => fail(original)); await flush(() => click('Runs')); await flush(() => { void navigatePage('/backtests/definition/run/A'); }); await flush(() => reply(request('/api/v2/runs/A'), run('A', 'failed'))); await flush(() => click('Settings')); expect(settingsField('Dataset input').disabled).toBe(true); expect(settingsField('Source metadata JSON').disabled).toBe(true); await flush(() => click('Retry retaining same dataset')); const retry = request(retentionPath, 'POST'); expect(submittedBody(retry)).toBe(submittedBody(original)); expect(requests.filter(item => item.path === storedPreparationPath)).toHaveLength(1); await flush(() => click('Runs')); expect(retry.signal?.aborted).toBe(false); await flush(() => reply(retry, { preparation: stored.preparation })); await flush(() => click('Settings')); expect(settingsField('Canonical dataset').value).toBe(stored.preparation.hash); expect(host.textContent).toContain('Dataset retained.'); expect(requests.filter(item => item.method !== 'GET').map(item => item.path)).toEqual([ storedPreparationPath, retentionPath, retentionPath, ]); }); for (const phase of ['preview', 'retention'] as const) { test(`changing the backtest disposes the editor and fences late ${phase}`, async () => { await mountSettingsPage(); const { stored, pending: preview } = await beginStoredPreparation(); let pending = preview; if (phase === 'retention') { await flush(() => reply(preview, stored)); await flush(() => click('Retain dataset')); pending = request(retentionPath, 'POST'); } const original = settingsField('Source metadata JSON'); const catalogRequests = requests.filter( item => item.path === '/api/v2/datasets/canonical' ).length; await flush(() => { void navigatePage('/backtests/other'); }); expect(original.isConnected).toBe(false); expect(pending.signal?.aborted).toBe(true); await flush(() => reply(pending, phase === 'preview' ? stored : { preparation: stored.preparation }) ); await flush(() => { reply(request('/api/v2/backtests/other'), { ...definition, id: 'other', name: 'Other backtest', }); reply(request('/api/v2/backtests/other/runs'), []); }); expect(host.querySelector('[aria-label="Backtest settings panel"]')).toBeNull(); expect(requests.filter(item => item.path === '/api/v2/datasets/canonical')).toHaveLength( catalogRequests ); await flush(() => click('Settings')); await flush(() => click('Configure canonical research')); expect(settingsField('Backtest name').value).toBe('Other backtest'); expect(settingsField('Dataset input').value).toBe('export'); expect(settingsField('Canonical dataset').value).toBe(''); expect(host.textContent).not.toContain('sessions.json'); expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull(); expect( requests.filter( item => item.method === 'PUT' || (item.path.endsWith('/runs') && item.method === 'POST') ) ).toHaveLength(0); }); } test('explicitly discarding canonical setup still removes the draft', async () => { await mountSettingsPage(); await flush(() => click('Settings')); await flush(() => click('Configure canonical research')); await flush(() => editSettings('Backtest name', 'Discard this draft')); const oldConfirm = Object.getOwnPropertyDescriptor(browser, 'confirm'); try { Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false }); await flush(() => click('Back to draft settings')); expect(settingsField('Backtest name').value).toBe('Discard this draft'); Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true }); await flush(() => click('Back to draft settings')); expect(host.querySelector('[aria-label="Canonical dataset"]')).toBeNull(); await flush(() => click('Configure canonical research')); expect(settingsField('Backtest name').value).toBe(definition.name); } finally { if (oldConfirm) { Object.defineProperty(browser, 'confirm', oldConfirm); } else { Reflect.deleteProperty(browser, 'confirm'); } } }); }); describe('run selection and persisted status authority', () => { for (const lateFailure of [false, true]) { test(`stale_status_response: A ${lateFailure ? 'error' : 'success'}/finally cannot replace B loading`, async () => { await mount(); await select('A'); const previous = request('/api/v2/runs/A'); await select('B'); expect(previous.signal?.aborted).toBe(true); await flush(() => (lateFailure ? fail(previous) : reply(previous, run('A')))); expect(latest.currentRun).toBeNull(); expect(latest.isLoading).toBe(true); expect(latest.error).toBeNull(); await flush(() => reply(request('/api/v2/runs/B'), run('B'))); expect(latest.currentRun?.id).toBe('B'); expect(latest.isLoading).toBe(false); expect(polls()).toBe(1); }); test(`stale_results_response: A ${lateFailure ? 'error' : 'success'} cannot replace B results`, async () => { await mount(); await select('A'); await flush(() => reply(request('/api/v2/runs/A'), run('A', 'completed'))); const previous = request('/api/v2/runs/A/results'); await select('B'); await flush(() => reply(request('/api/v2/runs/B'), run('B', 'completed'))); await flush(() => reply(request('/api/v2/runs/B/results'), results('B'))); await flush(() => (lateFailure ? fail(previous) : reply(previous, results('A')))); expect(previous.signal?.aborted).toBe(true); expect(latest.currentRun?.id).toBe('B'); expect(latest.runResults?.runId).toBe('B'); expect(latest.error).toBeNull(); expect(polls()).toBe(0); }); } test('one_poll_in_flight: invalidations coalesce, slow requests do not overlap, polling recovers', async () => { await mount(); await selectRunning(); await advance(1000); const first = request('/api/v2/runs/A'); await advance(10000); await flush(() => { void latest.refreshRun('A'); void latest.refreshRun('A'); }); expect(requests.filter(item => item.path === '/api/v2/runs/A')).toHaveLength(2); await flush(() => reply(first, run('A', 'running', { progress: 20 }))); expect(requests.filter(item => item.path === '/api/v2/runs/A')).toHaveLength(3); await flush(() => fail(request('/api/v2/runs/A'))); expect(latest.error).toContain('Network unavailable'); expect(latest.currentRun?.progress).toBe(20); expect(polls()).toBe(1); await advance(1000); await flush(() => reply(request('/api/v2/runs/A'), run('A', 'completed'))); await flush(() => reply(request('/api/v2/runs/A/results'), results('A'))); expect(latest.error).toBeNull(); expect(latest.runResults?.runId).toBe('A'); expect(polls()).toBe(0); }); test('stale results error/finally does not clear the newer selection loading state', async () => { await mount(); await select('A'); await flush(() => reply(request('/api/v2/runs/A'), run('A', 'completed'))); const previous = request('/api/v2/runs/A/results'); await select('B'); await flush(() => fail(previous)); expect(latest.isLoading).toBe(true); expect(latest.error).toBeNull(); expect(latest.currentRun).toBeNull(); await flush(() => reply(request('/api/v2/runs/B'), run('B', 'failed'))); expect(latest.currentRun?.id).toBe('B'); expect(latest.isLoading).toBe(false); }); test('no_publish_after_unmount also ignores a late initial status failure', async () => { await mount(); await select('A'); const pending = request('/api/v2/runs/A'); await flush(() => root!.unmount()); root = undefined; const before = renders; await flush(() => fail(pending)); expect(pending.signal?.aborted).toBe(true); expect(renders).toBe(before); expect(timers.size).toBe(0); }); test('no_publish_after_unmount: abort results and remove pending poll/subscription work', async () => { await mount(createElement(HookHost, { socket: true })); await selectRunning(); const socket = TestSocket.instances[0]!; await flush(() => socket.open()); await advance(1000); await flush(() => reply(request('/api/v2/runs/A'), run('A', 'completed'))); const pending = request('/api/v2/runs/A/results'); await flush(() => root!.unmount()); root = undefined; const before = renders; await flush(() => reply(pending, results('A'))); await advance(30000); expect(pending.signal?.aborted).toBe(true); expect(socket.readyState).toBe(3); expect(renders).toBe(before); expect(timers.size).toBe(0); }); for (const initial of ['pending', 'running'] as const) { test(`pending_vs_active_cancel: ${initial} acknowledgement is not invented completion`, async () => { await mount(); await selectRunning('A', initial); await flush(() => click('Cancel run')); expect(host.textContent).toContain('Cancellation requested'); await flush(() => reply(request('/api/v2/runs/A/cancel', 'POST'), { accepted: true }, 202)); expect(latest.currentRun?.status).toBe(initial); const acknowledged = initial === 'pending' ? 'cancelled' : 'running'; await flush(() => reply(request('/api/v2/runs/A'), run('A', acknowledged, { cancelRequested: true })) ); expect(latest.currentRun?.status).toBe(acknowledged); if (initial === 'running') { expect(latest.cancelRequested).toBe(true); expect(host.textContent).toContain('Cancellation requested'); await advance(1000); await flush(() => reply(request('/api/v2/runs/A'), run('A', 'cancelled'))); } expect(host.textContent).toContain('Cancelled'); expect(latest.cancelRequested).toBe(false); expect(latest.runResults).toBeNull(); expect(polls()).toBe(0); }); } test('late cancel failure cannot change a newer selection', async () => { await mount(); await selectRunning(); await flush(() => click('Cancel run')); const pending = request('/api/v2/runs/A/cancel', 'POST'); await selectRunning('B'); await flush(() => fail(pending)); expect(latest.currentRun?.id).toBe('B'); expect(latest.cancelRequested).toBe(false); expect(latest.error).toBeNull(); }); test('failed cancellation is retriable and a racing persisted completion wins', async () => { await mount(); await selectRunning(); await flush(() => click('Cancel run')); await flush(() => fail(request('/api/v2/runs/A/cancel', 'POST'))); expect(latest.cancelRequested).toBe(false); expect(latest.error).toContain('Network unavailable'); await flush(() => click('Cancel run')); await flush(() => reply(request('/api/v2/runs/A/cancel', 'POST'), { accepted: true }, 202)); await flush(() => reply(request('/api/v2/runs/A'), run('A', 'completed'))); await flush(() => reply(request('/api/v2/runs/A/results'), results('A'))); expect(latest.currentRun?.status).toBe('completed'); expect(latest.cancelRequested).toBe(false); expect(latest.error).toBeNull(); expect(latest.runResults?.runId).toBe('A'); expect(polls()).toBe(0); }); test('unsupported_controls: server pause/resume/speed are absent for running and paused runs', async () => { await mount(); await selectRunning(); expect([...host.querySelectorAll('button')].map(item => item.title)).toEqual([ 'Cancel run', 'Run current settings', ]); await selectRunning('B', 'paused'); expect([...host.querySelectorAll('button')].map(item => item.title)).toEqual([ 'Cancel run', 'Run current settings', ]); }); test('reconnect_or_poll_recovery: reconnect refetches persisted state and old sockets cannot publish', async () => { await mount(createElement(HookHost, { socket: true })); await selectRunning(); const first = TestSocket.instances[0]!; await flush(() => first.open()); const lateMessage = first.onmessage!; await flush(() => first.close()); await advance(3000); expect(TestSocket.instances).toHaveLength(2); const second = TestSocket.instances[1]!; await flush(() => { second.open(); second.message({ type: 'connected', runId: 'A' }); }); // The websocket invalidation coalesces with the already due fallback poll. expect(requests.filter(item => !item.settled && item.path === '/api/v2/runs/A')).toHaveLength( 1 ); await selectRunning('B'); const count = requests.length; await flush(() => lateMessage({ data: JSON.stringify({ type: 'completed', runId: 'A' }) })); expect(requests).toHaveLength(count); expect(latest.currentRun?.id).toBe('B'); expect(second.readyState).toBe(3); }); }); describe('actual detail page result states', () => { test('detail cancel control is wired to durable cancellation, not chart playback', async () => { await mountPage('running'); await flush(() => click('Cancel run')); expect(host.textContent).toContain('Cancellation requested'); await flush(() => reply(request('/api/v2/runs/A/cancel', 'POST'), {}, 202)); expect(host.textContent).not.toContain('Run cancelled'); await flush(() => reply(request('/api/v2/runs/A'), run('A', 'cancelled'))); expect(host.textContent).toContain('Run cancelled'); expect(host.textContent).not.toContain('No trades executed'); }); for (const status of ['failed', 'cancelled'] as const) { test(`${status} is not successful zero-trade data`, async () => { await mountPage(status); await flush(() => click('Trades')); expect(host.textContent).toContain( status === 'failed' ? 'Run failed: Fixture failure' : 'Run cancelled' ); expect(host.textContent).not.toContain('No trades executed'); expect(host.querySelector('[aria-label="Result provenance and limitations"]')).toBeNull(); expect(requests.some(item => item.path.endsWith('/results'))).toBe(false); }); } test('completed missing results differ from successful zero trades and retry uses saved results', async () => { await mountPage('completed'); expect(host.textContent).toContain('Loading run data'); expect(host.querySelector('[aria-label="Result provenance and limitations"]')).toBeNull(); await flush(() => click('Trades')); await flush(() => reply(request('/api/v2/runs/A/results'), { error: 'Not found' }, 404)); expect(host.textContent).toContain('saved results are unavailable'); expect(host.textContent).not.toContain('No trades executed'); expect(host.querySelector('[aria-label="Result provenance and limitations"]')).toBeNull(); await flush(() => click('Retry results')); await flush(() => reply(request('/api/v2/runs/A'), run('A', 'completed'))); await flush(() => reply(request('/api/v2/runs/A/results'), results('A'))); expect(host.textContent).toContain('No trades executed in this backtest.'); expect(host.textContent).not.toContain('saved results are unavailable'); }); test('limitation_badge: completed detail shows unknown legacy provenance beside performance', async () => { await mountPage('completed'); await flush(() => reply(request('/api/v2/runs/A/results'), results('A'))); const evidence = host.querySelector('[aria-label="Result provenance and limitations"]'); expect(evidence).not.toBeNull(); expect(evidence!.textContent).toContain('Research only ยท Unverified economics'); const details = evidence!.querySelector('details')!; await flush(() => details.querySelector('summary')!.click()); expect(details.open).toBe(true); expect(evidence!.textContent).toContain('Stored run configuration: Unknown'); expect(evidence!.textContent).toContain('Provenance metadata is unavailable from this API'); expect(host.textContent).toContain('Performance'); }); }); async function nameBacktest() { const family = { id: 'family', name: 'Test strategy', archived: false }; const version = { id: 'version-one', strategyId: 'family', ordinal: 1, origin: 'builtin', package: { parameterSchema: { type: 'object', properties: {}, required: [], additionalProperties: false, }, }, }; await flush(() => reply(request('/api/v2/strategies'), { strategies: [family] })); const choose = (label: string, value: string) => { const select = host.querySelector(`select[aria-label="${label}"]`)!; Object.getOwnPropertyDescriptor(browser.HTMLSelectElement.prototype, 'value')!.set!.call( select, value ); select.dispatchEvent(new browser.Event('change', { bubbles: true }) as unknown as Event); }; await flush(() => choose('Strategy family', 'family')); await flush(() => reply(request('/api/v2/strategies/family/versions'), { versions: [version] })); await flush(() => choose('Immutable strategy version', 'version-one')); await flush(() => reply(request('/api/v2/strategy-versions/version-one'), { version, reviews: [] }) ); await flush(() => reply(request('/api/v2/strategies/family'), { strategy: family })); await flush(() => click('Validate parameters')); await flush(() => reply(request('/api/v2/strategy-versions/version-one/validate', 'POST'), { parameters: {}, runnable: false, reason: 'Configure canonical settings', }) ); await flush(() => { const input = host.querySelector('input[placeholder="My Strategy Backtest"]')!; Object.getOwnPropertyDescriptor(browser.HTMLInputElement.prototype, 'value')!.set!.call( input, 'Fixture' ); input.dispatchEvent(new browser.Event('input', { bubbles: true }) as unknown as Event); }); } async function loadDefinition(id = 'definition') { await flush(() => { void latest.loadBacktest(id); }); await flush(() => { reply(request(`/api/v2/backtests/${id}`), { ...definition, id }); reply(request(`/api/v2/backtests/${id}/runs`), []); }); } describe('explicit save and repeat-safe run submission', () => { test('save_only: definition save explicitly disables auto-start and makes no run request', async () => { const created: Backtest[] = []; await mount( createElement(CreateBacktestDialog, { onClose: () => {}, onCreated: value => created.push(value), }) ); await nameBacktest(); await flush(() => { click('Save'); click('Save'); }); const saving = request('/api/v2/backtests', 'POST'); expect(JSON.parse(saving.body!).autoStart).toBe(false); expect( requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'POST') ).toHaveLength(1); await flush(() => reply(saving, definition)); expect(created).toEqual([definition]); expect( requests.filter(item => item.path.endsWith('/runs') && item.method === 'POST') ).toHaveLength(0); }); test('new dialog cannot submit legacy or unconfigured execution', async () => { await mount(createElement(CreateBacktestDialog, { onClose: () => {}, onCreated: () => {} })); expect(host.querySelector('[aria-label="Strategy mode"]')).toBeNull(); await nameBacktest(); await flush(() => click('Save and run')); expect(requests.some(item => item.path === '/api/v2/backtests' && item.method === 'POST')).toBe( false ); expect(host.textContent).toContain('financial policies before running'); }); test('dialog unmount during save ignores late completion and navigation', async () => { let navigated = false; await mount( createElement(CreateBacktestDialog, { onClose: () => {}, onCreated: () => { navigated = true; }, }) ); await nameBacktest(); await flush(() => click('Save')); await flush(() => root!.unmount()); root = undefined; await flush(() => reply(request('/api/v2/backtests', 'POST'), definition)); expect(navigated).toBe(false); expect(requests.some(item => item.path.endsWith('/runs') && item.method === 'POST')).toBe( false ); }); test('save rejects double clicks and close while pending, then navigates to configure', async () => { await mount( createElement( router.MemoryRouter, { initialEntries: ['/backtests'] }, createElement( router.Routes, null, createElement(router.Route, { path: '/backtests', element: createElement(BacktestListPageV2), }), createElement(router.Route, { path: '/backtests/:id', element: createElement('p', null, 'Saved definition'), }) ), createElement(LocationProbe) ) ); await flush(() => reply(request('/api/v2/backtests'), [])); await flush(() => click('New Backtest')); await nameBacktest(); await flush(() => { click('Save'); click('Save'); click('Close backtest dialog'); click('Close'); }); expect(host.querySelector('[aria-label="Close backtest dialog"]')).not.toBeNull(); expect( requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'POST') ).toHaveLength(1); expect(pageLocation).toBe('/backtests'); await flush(() => reply(request('/api/v2/backtests', 'POST'), definition)); expect(pageLocation).toBe('/backtests/definition'); expect(requests.some(item => item.path.endsWith('/runs') && item.method === 'POST')).toBe( false ); }); test('legacy template stays readable but never creates a new run', async () => { await mount(); await flush(() => { void latest.loadBacktest('definition'); }); await flush(() => { reply(request('/api/v2/backtests/definition'), { ...definition, strategy: 'sma', strategyVersionId: null, }); reply(request('/api/v2/backtests/definition/runs'), []); }); await flush(() => { void latest.createRun(); }); expect(latest.submissionError).toContain('Legacy execution is retired'); expect(requests.some(item => item.method === 'POST')).toBe(false); expect(latest.backtest?.name).toBe('Fixture'); }); test('closing new-run confirmation prevents late successful submission from navigating', async () => { await mountPage('failed'); await flush(() => click('Runs')); await flush(() => click('New Run')); await flush(() => click('Run current settings')); const submitting = request('/api/v2/backtests/definition/runs', 'POST'); await flush(() => click('Cancel')); await flush(() => reply(submitting, run('B', 'pending'), 202)); expect(pageLocation).toBe('/backtests/definition/run/A'); expect(host.textContent).not.toContain('Submit the current configuration'); }); test('changing the actual run route prevents late submission navigation', async () => { await mountPage('failed'); await flush(() => click('Run current settings')); const submitting = request('/api/v2/backtests/definition/runs', 'POST'); await flush(() => { void navigatePage('/backtests/definition/run/B'); }); await flush(() => reply(request('/api/v2/runs/B'), run('B', 'failed'))); await flush(() => reply(submitting, run('C', 'pending'), 202)); expect(pageLocation).toBe('/backtests/definition/run/B'); expect(requests.some(item => item.path === '/api/v2/runs/C')).toBe(false); }); test('submission errors remain visible after selecting another run and retry the same intent', async () => { await mountPage('failed'); await flush(() => click('Run current settings')); const submitting = request('/api/v2/backtests/definition/runs', 'POST'); await flush(() => { void navigatePage('/backtests/definition/run/B'); }); await flush(() => reply(request('/api/v2/runs/B'), run('B', 'failed', { error: 'B failure' }))); await flush(() => fail(submitting)); expect(pageLocation).toBe('/backtests/definition/run/B'); expect(host.textContent).toContain('Run submission failed: Network unavailable'); expect(host.textContent).toContain('Run failed: B failure'); await flush(() => click('Retry submission')); const retry = request('/api/v2/backtests/definition/runs', 'POST'); expect(submittedBody(retry)).toBe(submittedBody(submitting)); expect(retry.headers.get('Idempotency-Key')).toBe(submitting.headers.get('Idempotency-Key')); }); test('detail retries freeze payload/key across settings edits; acknowledged next intent has a fresh key', async () => { await mount(); await loadDefinition(); await flush(() => { void latest.createRun(2); void latest.createRun(9); }); const first = request('/api/v2/backtests/definition/runs', 'POST'); expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); expect(latest.isSubmitting).toBe(true); await flush(() => fail(first)); expect(latest.submissionError).toContain('Network unavailable'); await flush(() => { void latest.updateBacktest('definition', { initialCapital: 2000 }); }); await flush(() => reply(request('/api/v2/backtests/definition', 'PUT'), { ...definition, initialCapital: 2000 }) ); // A status reader may already have learned the run accepted before the lost response. await selectRunning('A'); await flush(() => { void latest.createRun(9); }); const retry = request('/api/v2/backtests/definition/runs', 'POST'); expect(submittedBody(retry)).toBe(submittedBody(first)); expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key')); await flush(() => reply(retry, run('A', 'pending'), 202)); expect(latest.runs.filter(item => item.id === 'A')).toHaveLength(1); await flush(() => { void latest.createRun(9); }); const next = request('/api/v2/backtests/definition/runs', 'POST'); expect(next.headers.get('Idempotency-Key')).not.toBe(first.headers.get('Idempotency-Key')); expect(JSON.parse(next.body!)).toEqual({ speedMultiplier: null }); await flush(() => reply(next, run('B', 'pending'), 202)); expect(latest.runs.map(item => item.id)).toEqual(['B', 'A']); }); test('new-run form remains open and submission failure is visible alongside a polling failure', async () => { await mountPage('running'); await advance(1000); await flush(() => fail(request('/api/v2/runs/A'))); await flush(() => click('Runs')); await flush(() => click('New Run')); await flush(() => { click('Run current settings'); click('Run current settings'); }); const first = request('/api/v2/backtests/definition/runs', 'POST'); expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); await flush(() => reply(first, { error: 'Submission unavailable' }, 503)); expect(host.textContent).toContain('Run submission failed'); expect(host.textContent).toContain('Network unavailable'); expect(host.textContent).toContain('Submit the current configuration'); await flush(() => click('Retry submission')); const retry = request('/api/v2/backtests/definition/runs', 'POST'); expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key')); expect(submittedBody(retry)).toBe(submittedBody(first)); }); for (const change of ['selection', 'backtest', 'unmount'] as const) { test(`late submission completion cannot navigate or replace newer ${change}`, async () => { await mount(); await loadDefinition(); let completed: Run | undefined; await flush(() => { void latest.createRun().then(value => { completed = value; }); }); const first = request('/api/v2/backtests/definition/runs', 'POST'); if (change === 'selection') { await selectRunning('B'); } else if (change === 'backtest') { await loadDefinition('other'); } else { await flush(() => root!.unmount()); root = undefined; } const rendered = renders; await flush(() => reply(first, run('A', 'pending'), 202)); expect(completed).toBeUndefined(); expect(latest.runs.some(item => item.id === 'A')).toBe(false); if (change === 'selection') { expect(latest.currentRun?.id).toBe('B'); } else if (change === 'backtest') { expect(latest.backtest?.id).toBe('other'); } else { expect(renders).toBe(rendered); } }); } }); describe('template archive and restore', () => { const archived = { ...definition, archivedAt: '2024-03-01T00:00:00.000Z' }; function button(label: string) { const found = [...host.querySelectorAll('button')].find( item => item.textContent?.trim() === label || item.getAttribute('aria-label') === label ); if (!found) { throw new Error(`Missing button ${label}`); } return found; } test('confirmation archives only the template while active cancellation, history and restore remain available', async () => { await mountPage('running'); await flush(() => click('Archive backtest')); expect(host.querySelector('[role="dialog"]')?.getAttribute('aria-label')).toBe( 'Archive backtest' ); expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); await flush(() => { click('Confirm archive'); click('Confirm archive'); }); const archive = request('/api/v2/backtests/definition/archive', 'POST'); expect(JSON.parse(archive.body!)).toEqual({ archived: true }); expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); expect(button('Confirm archive').disabled).toBe(true); expect(host.textContent).not.toContain('This backtest is archived.'); await flush(() => reply(archive, archived)); expect(host.querySelector('[role="dialog"]')).toBeNull(); expect(host.textContent).toContain('This backtest is archived.'); expect(button('Run current settings').disabled).toBe(true); expect(button('Cancel run').disabled).toBe(false); expect(pageLocation).toBe('/backtests/definition/run/A'); expect(polls()).toBe(1); await flush(() => click('Settings')); expect(button('Save').disabled).toBe(true); expect((host.querySelector('input[name="name"]') as HTMLInputElement).disabled).toBe(true); await flush(() => click('Runs')); expect(button('New Run').disabled).toBe(true); await flush(() => click('Restore backtest')); expect(host.querySelector('[role="dialog"]')?.getAttribute('aria-label')).toBe( 'Restore backtest' ); await flush(() => click('Confirm restore')); const restore = request('/api/v2/backtests/definition/archive', 'POST'); expect(JSON.parse(restore.body!)).toEqual({ archived: false }); await flush(() => reply(restore, definition)); expect(button('New Run').disabled).toBe(false); expect(button('Run current settings').disabled).toBe(false); expect(host.textContent).not.toContain('This backtest is archived.'); expect(pageLocation).toBe('/backtests/definition/run/A'); }); test('archive cancellation writes nothing; failed archive stays open with actionable error and retries', async () => { await mountPage('running'); await flush(() => click('Archive backtest')); await flush(() => click('Cancel')); expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); await flush(() => click('Archive backtest')); await flush(() => click('Confirm archive')); await flush(() => reply( request('/api/v2/backtests/definition/archive', 'POST'), { error: 'Archive storage is unavailable' }, 503 ) ); expect(host.querySelector('[role="dialog"]')).not.toBeNull(); expect(host.textContent).toContain('Archive storage is unavailable'); expect(host.textContent).not.toContain('This backtest is archived.'); expect(button('Confirm archive').disabled).toBe(false); await flush(() => click('Confirm archive')); await flush(() => reply(request('/api/v2/backtests/definition/archive', 'POST'), archived)); expect(host.textContent).toContain('This backtest is archived.'); }); test('archival preserves a lost submission response key/body and completed evidence; only restore permits new intent', async () => { await mount(); await loadDefinition(); await flush(() => { void latest.createRun(2); }); const first = request('/api/v2/backtests/definition/runs', 'POST'); await flush(() => fail(first)); await selectRunning('A', 'completed'); await flush(() => reply(request('/api/v2/runs/A/results'), results('A'))); const savedResults = latest.runResults; await flush(() => { void latest.setBacktestArchived('definition', true); }); await flush(() => reply(request('/api/v2/backtests/definition/archive', 'POST'), archived)); expect(latest.backtest?.archivedAt).toBe(archived.archivedAt); expect(latest.runResults).toBe(savedResults); expect(latest.currentRun?.id).toBe('A'); expect(latest.runs.map(run => run.id)).toEqual(['A']); expect(latest.hasPendingSubmission).toBe(true); await flush(() => { void latest.createRun(9); }); const retry = request('/api/v2/backtests/definition/runs', 'POST'); expect(submittedBody(retry)).toBe(submittedBody(first)); expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key')); await flush(() => reply(retry, run('A', 'completed'), 202)); expect(latest.hasPendingSubmission).toBe(false); const count = requests.length; await flush(() => { void latest.createRun(9); }); expect(requests).toHaveLength(count); expect(latest.submissionError).toContain('Restore this archived backtest'); await expect(latest.updateBacktest('definition', { name: 'Disallowed edit' })).rejects.toThrow( 'Restore' ); expect(requests).toHaveLength(count); await flush(() => { void latest.setBacktestArchived('definition', false); }); await flush(() => reply(request('/api/v2/backtests/definition/archive', 'POST'), definition)); await flush(() => { void latest.createRun(9); }); const fresh = request('/api/v2/backtests/definition/runs', 'POST'); expect(fresh.headers.get('Idempotency-Key')).not.toBe(first.headers.get('Idempotency-Key')); expect(JSON.parse(fresh.body!)).toEqual({ speedMultiplier: null }); await flush(() => reply(fresh, run('B', 'pending'), 202)); expect(latest.runResults).toBe(savedResults); }); test('archived page still exposes recovery of the frozen submission key', async () => { await mountPage('running'); await flush(() => click('Run current settings')); const first = request('/api/v2/backtests/definition/runs', 'POST'); await flush(() => fail(first)); await flush(() => click('Archive backtest')); await flush(() => click('Confirm archive')); await flush(() => reply(request('/api/v2/backtests/definition/archive', 'POST'), archived)); expect(button('Retry submission').disabled).toBe(false); await flush(() => click('Retry submission')); const retry = request('/api/v2/backtests/definition/runs', 'POST'); expect(submittedBody(retry)).toBe(submittedBody(first)); expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key')); await flush(() => reply(retry, run('A', 'running'), 202)); expect(button('Run current settings').disabled).toBe(true); }); test('late archive completion cannot overwrite a different template after navigation', async () => { await mount(); await loadDefinition(); await flush(() => { void latest.setBacktestArchived('definition', true); }); const previous = request('/api/v2/backtests/definition/archive', 'POST'); await loadDefinition('other'); await flush(() => reply(previous, archived)); expect(latest.backtest?.id).toBe('other'); expect(latest.backtest?.archivedAt).toBeNull(); expect(latest.isLoading).toBe(false); }); test('retained-delete conflict surfaces archive guidance without clearing selected evidence', async () => { await mount(); await loadDefinition(); await selectRunning('A', 'completed'); await flush(() => reply(request('/api/v2/runs/A/results'), results('A'))); let failure: string | undefined; await flush(() => { void latest.deleteBacktest('definition').catch(error => { failure = error.message; }); }); await flush(() => reply( request('/api/v2/backtests/definition', 'DELETE'), { error: 'This backtest retains 1 run. Archive it to preserve its research history.', code: 'retained_runs', runCount: 1, }, 409 ) ); if (typeof failure !== 'string') { throw new Error('Expected a retained-history refusal'); } expect(failure).toContain('Archive it'); expect(latest.error).toBe(failure); expect(latest.backtest?.id).toBe('definition'); expect(latest.currentRun?.id).toBe('A'); expect(latest.runResults?.runId).toBe('A'); }); for (const lateFailure of [false, true]) { test(`archive list filter ignores stale ${lateFailure ? 'failure' : 'success'} and keeps truthful loading/empty states`, async () => { await mount(createElement(router.MemoryRouter, null, createElement(BacktestListPageV2))); const original = request('/api/v2/backtests'); expect(original.query).not.toContain('includeArchived'); expect(host.textContent).toContain('Loading backtests...'); await flush(() => (host.querySelector('input[type="checkbox"]') as HTMLInputElement).click()); const current = requests.find( item => item.path === '/api/v2/backtests' && item !== original && !item.settled )!; expect(current.query).toContain('includeArchived=true'); expect(original.signal?.aborted).toBe(true); await flush(() => (lateFailure ? fail(original) : reply(original, [definition]))); expect(host.textContent).toContain('Loading backtests...'); expect(host.textContent).not.toContain('Network unavailable'); await flush(() => reply(current, [])); expect(host.textContent).toContain('No backtests yet.'); expect(host.textContent).not.toContain('Loading backtests...'); await flush(() => (host.querySelector('input[type="checkbox"]') as HTMLInputElement).click()); const failed = request('/api/v2/backtests'); expect(failed.query).not.toContain('includeArchived'); await flush(() => reply(failed, { error: 'Retained history storage is unavailable' }, 503)); expect(host.textContent).toContain('Retained history storage is unavailable'); await flush(() => click('Retry backtests')); await flush(() => reply(request('/api/v2/backtests'), [])); expect(host.textContent).toContain('No active backtests.'); expect(host.textContent).not.toContain('Retained history storage is unavailable'); }); } });