import { ArrowLeftIcon, PlusIcon } from '@heroicons/react/24/outline'; import { useCallback, useEffect, useRef, useState } from 'react'; import { useNavigate, useParams } from 'react-router-dom'; import { useWebSocket } from '@/hooks/useWebSocket'; import { BacktestConfiguration } from './components/BacktestConfiguration'; import { BacktestPlayback } from './components/BacktestPlayback'; import { BacktestTrades } from './components/BacktestTrades'; import { RunControlsCompact } from './components/RunControlsCompact'; import { RunsListWithMetrics } from './components/RunsListWithMetrics'; import { useBacktestV2 } from './hooks/useBacktestV2'; import type { BacktestConfig } from './types/backtest.types'; const baseTabs = [ { id: 'runs', name: 'Runs' }, { id: 'settings', name: 'Settings' }, ]; const runTabs = [ { id: 'details', name: 'Details' }, { id: 'trades', name: 'Trades' }, ]; export function BacktestDetailPageV2() { const { id, runId } = useParams<{ id: string; runId?: string }>(); const navigate = useNavigate(); const [activeTab, setActiveTab] = useState('details'); const [showNewRun, setShowNewRun] = useState(false); const navigationGeneration = useRef(0); const { backtest, runs, currentRun, runResults, isLoading, error, submissionError, isSubmitting, hasPendingSubmission, loadBacktest, updateBacktest, createRun, cancelRun, cancelRequested, selectRun, refreshRun, } = useBacktestV2(); // Notifications invalidate the same persisted-state reader used by polling. useWebSocket({ runId: currentRun && ['pending', 'running', 'paused'].includes(currentRun.status) ? currentRun.id : null, onMessage: message => { if (message.type !== 'pong') { void refreshRun(message.runId); } }, }); useEffect(() => { navigationGeneration.current++; setShowNewRun(false); return () => { navigationGeneration.current++; }; }, [id, runId]); useEffect(() => { if (id) { void loadBacktest(id); } }, [id, loadBacktest]); // URL selection is immediate; a new selection invalidates every old continuation. useEffect(() => { void selectRun(runId); setActiveTab(previous => (runId ? (previous === 'runs' ? 'details' : previous) : 'runs')); }, [runId, selectRun]); // Handle configuration save const handleConfigSubmit = useCallback( async (config: BacktestConfig) => { if (!id) { return; } await updateBacktest(id, { name: config.name, strategy: config.strategy, symbols: config.symbols, startDate: config.startDate.toISOString().split('T')[0], endDate: config.endDate.toISOString().split('T')[0], initialCapital: config.initialCapital, config: { ...backtest?.config, commission: config.commission, slippage: config.slippage, speedMultiplier: config.speedMultiplier, dataPolicy: { adjustment: config.priceAdjustment ?? 'raw', timestamp: !backtest?.config?.dataFrequency || backtest.config.dataFrequency === '1d' ? 'utc-session-date' : 'utc-instant', }, }, }); }, [id, updateBacktest, backtest] ); // Handle new run creation const handleCreateRun = useCallback(async () => { const generation = navigationGeneration.current; const newRun = await createRun(null); if (newRun && id && generation === navigationGeneration.current) { setShowNewRun(false); navigate(`/backtests/${id}/run/${newRun.id}`); } }, [createRun, navigate, id]); // Handle rerun const handleRerun = useCallback( async (speedMultiplier: number | null) => { const generation = navigationGeneration.current; const newRun = await createRun(speedMultiplier); if (newRun && id && generation === navigationGeneration.current) { navigate(`/backtests/${id}/run/${newRun.id}`); } }, [createRun, navigate, id] ); // Convert backtest to config format for the form const backtestConfig: BacktestConfig | undefined = backtest ? { name: backtest.name, startDate: new Date(backtest.startDate), endDate: new Date(backtest.endDate), initialCapital: backtest.initialCapital, symbols: backtest.symbols, strategy: backtest.strategy, speedMultiplier: 1, commission: Number(backtest.config?.commission ?? 0.001), slippage: Number(backtest.config?.slippage ?? 0.0001), priceAdjustment: backtest.config?.dataPolicy && typeof backtest.config.dataPolicy === 'object' && 'adjustment' in backtest.config.dataPolicy && backtest.config.dataPolicy.adjustment === 'provider-adjusted' ? 'provider-adjusted' : 'raw', } : undefined; const renderTabContent = () => { if (['details', 'trades'].includes(activeTab)) { if (isLoading) { return (
Loading run data...
); } if (currentRun?.status === 'failed' || currentRun?.status === 'cancelled') { return (
{currentRun.status === 'failed' ? `Run failed: ${currentRun.error || 'No error details were saved.'}` : 'Run cancelled. No completed results are available.'}
); } if (currentRun && currentRun.status !== 'completed') { return (
{cancelRequested || currentRun.cancelRequested ? 'Cancellation requested. Waiting for the worker to stop.' : 'Run is not complete. Results will appear when saved.'}
); } if (currentRun && !runResults) { return (

Run completed, but saved results are unavailable.

); } } // A missing result is not a successful run with zero trades. if (!currentRun && ['details', 'trades'].includes(activeTab)) { return (

Please select a run to view {activeTab}

); } switch (activeTab) { case 'runs': return (

Run History

{showNewRun && (

Run current settings

Submit the current configuration, not a reproduction of a previous run. A retry recovers the original submission if it was already accepted.

)}
); case 'settings': return (
); case 'details': // Only render if we have matching results or no results yet if (runResults && currentRun && runResults.runId !== currentRun.id) { return (
Loading run data...
); } return (
); case 'trades': return (
); default: return null; } }; if (!backtest && !isLoading) { return (

{error || 'Backtest not found'}

{error && id && ( )}
); } return (
{/* Header with Tabs */}

{backtest?.name || 'Loading...'} {currentRun && ( - Run #{currentRun.runNumber} )}

Current definition: {backtest?.strategy || ''} •{' '} {backtest?.symbols.join(', ') || ''}

{/* Tabs */}
{/* Run Controls */} {currentRun && (
)}
{/* Tab Content */}
{submissionError && (

Run submission failed: {submissionError}. Retry to recover the same submission.

{!showNewRun && ( )}
)} {error && (

{error}

{runId && ( )}
)} {renderTabContent()}
); }