fix(web): make backtest run controls and selection reliable

This commit is contained in:
Boki 2026-10-22 14:17:25 -04:00
parent 3d26da07f5
commit 67f12b49a0
8 changed files with 1109 additions and 675 deletions

View file

@ -2,7 +2,6 @@ import { ArrowLeftIcon, PlusIcon } from '@heroicons/react/24/outline';
import { useCallback, useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useWebSocket } from '@/hooks/useWebSocket';
import { browserLog } from '@/utils/browserLog';
import { BacktestConfiguration } from './components/BacktestConfiguration';
import { BacktestPlayback } from './components/BacktestPlayback';
import { BacktestTrades } from './components/BacktestTrades';
@ -37,91 +36,36 @@ export function BacktestDetailPageV2() {
loadBacktest,
updateBacktest,
createRun,
pauseRun,
resumeRun,
updateRunSpeed,
cancelRun,
cancelRequested,
selectRun,
refreshRun,
} = useBacktestV2();
// WebSocket connection for real-time updates
// Notifications invalidate the same persisted-state reader used by polling.
useWebSocket({
runId: currentRun?.id || null,
onProgress: (progress, currentDate) => {
// Update the run progress in the UI
if (currentRun) {
// This will trigger a re-render with updated progress
browserLog.log('Progress update:', progress, currentDate);
}
},
onError: error => {
browserLog.error('Run error:', error);
// Reload runs to get updated status
if (id) {
loadBacktest(id);
}
},
onCompleted: async () => {
// When run completes, reload to get the final results
if (currentRun?.id) {
try {
// Small delay to ensure the results are persisted
await new Promise(resolve => setTimeout(resolve, 500));
// Force re-select the run to load its results
await selectRun(currentRun.id);
} catch (err) {
browserLog.error('Failed to load completed run results:', err);
}
runId:
currentRun && ['pending', 'running', 'paused'].includes(currentRun.status)
? currentRun.id
: null,
onMessage: message => {
if (message.type !== 'pong') {
void refreshRun(message.runId);
}
},
});
// Load backtest on mount
useEffect(() => {
if (id) {
loadBacktest(id);
void loadBacktest(id);
}
}, [id, loadBacktest]);
// Clear mismatched results immediately
// URL selection is immediate; a new selection invalidates every old continuation.
useEffect(() => {
if (runResults && currentRun && runResults.runId !== currentRun.id) {
browserLog.warn('Run results mismatch:', {
runResultsId: runResults.runId,
currentRunId: currentRun.id,
});
// Clear the mismatched results immediately to prevent rendering wrong data
// The selectRun effect will load the correct results
}
}, [runResults?.runId, currentRun?.id]);
// We don't need this effect anymore - it's causing unnecessary re-renders
// The selectRun function already handles clearing mismatched results
// Select run based on URL parameter with debounce
useEffect(() => {
const timeoutId = setTimeout(() => {
if (runId) {
// If the current run already matches, don't re-select
if (currentRun?.id === runId) {
return;
}
// Always try to select the run - selectRun will fetch it if not found
selectRun(runId);
// Show details tab by default when a run is selected
if (activeTab === 'runs') {
setActiveTab('details');
}
} else if (!runId && currentRun) {
// Clear run selection when navigating away from run URL
selectRun(undefined);
setActiveTab('runs');
}
}, 50); // Small debounce to prevent rapid switching
return () => clearTimeout(timeoutId);
}, [runId, currentRun?.id, selectRun, activeTab]);
void selectRun(runId);
setActiveTab(previous => (runId ? (previous === 'runs' ? 'details' : previous) : 'runs'));
}, [runId, selectRun]);
// Handle configuration save
const handleConfigSubmit = useCallback(
@ -156,23 +100,20 @@ export function BacktestDetailPageV2() {
);
// Handle new run creation
const handleCreateRun = useCallback(
async (speedMultiplier: number) => {
const newRun = await createRun(speedMultiplier);
setShowNewRun(false);
// Navigate to the new run
if (newRun && id) {
navigate(`/backtests/${id}/run/${newRun.id}`);
}
},
[createRun, navigate, id]
);
const handleCreateRun = useCallback(async () => {
const newRun = await createRun(null);
setShowNewRun(false);
// Navigate to the new run
if (newRun && id) {
navigate(`/backtests/${id}/run/${newRun.id}`);
}
}, [createRun, navigate, id]);
// Handle rerun
const handleRerun = useCallback(
async (speedMultiplier: number | null) => {
// Pass null for max speed (no limit)
const newRun = await createRun(speedMultiplier ?? undefined);
const newRun = await createRun(speedMultiplier);
// Navigate to the new run's URL
if (newRun && id) {
@ -205,7 +146,44 @@ export function BacktestDetailPageV2() {
: undefined;
const renderTabContent = () => {
// Show message if trying to view run-specific tabs without a run selected
if (['details', 'trades'].includes(activeTab)) {
if (isLoading) {
return (
<div role="status" className="p-8 text-text-secondary">
Loading run data...
</div>
);
}
if (currentRun?.status === 'failed' || currentRun?.status === 'cancelled') {
return (
<div role="status" className="p-8 text-text-secondary">
{currentRun.status === 'failed'
? `Run failed: ${currentRun.error || 'No error details were saved.'}`
: 'Run cancelled. No completed results are available.'}
</div>
);
}
if (currentRun && currentRun.status !== 'completed') {
return (
<div role="status" className="p-8 text-text-secondary">
{cancelRequested || currentRun.cancelRequested
? 'Cancellation requested. Waiting for the worker to stop.'
: 'Run is not complete. Results will appear when saved.'}
</div>
);
}
if (currentRun && !runResults) {
return (
<div className="p-8 text-text-secondary">
<p>Run completed, but saved results are unavailable.</p>
<button className="mt-2 text-primary-500" onClick={() => void refreshRun()}>
Retry results
</button>
</div>
);
}
}
// A missing result is not a successful run with zero trades.
if (!currentRun && ['details', 'trades'].includes(activeTab)) {
return (
<div className="flex items-center justify-center h-full">
@ -246,7 +224,7 @@ export function BacktestDetailPageV2() {
<div className="flex space-x-2">
<button
onClick={() => {
handleCreateRun(1000); // Always use max speed
void handleCreateRun();
}}
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
>
@ -313,7 +291,12 @@ export function BacktestDetailPageV2() {
return (
<div className="h-full flex items-center justify-center">
<div className="text-center">
<p className="text-text-secondary mb-4">Backtest not found</p>
<p className="text-text-secondary mb-4">{error || 'Backtest not found'}</p>
{error && id && (
<button className="mr-4 text-primary-500" onClick={() => void loadBacktest(id)}>
Retry backtest
</button>
)}
<button
onClick={() => navigate('/backtests')}
className="text-primary-500 hover:text-primary-600"
@ -378,10 +361,9 @@ export function BacktestDetailPageV2() {
<div className="px-4">
<RunControlsCompact
run={currentRun}
onPause={pauseRun}
onResume={resumeRun}
onCancel={cancelRun}
cancelRequested={cancelRequested}
onRerun={handleRerun}
onSpeedChange={updateRunSpeed}
/>
</div>
)}
@ -392,7 +374,14 @@ export function BacktestDetailPageV2() {
<div className="flex-1 overflow-hidden py-4">
{error && (
<div className="mb-4 p-4 bg-error/10 border border-error/20 rounded-lg">
<p className="text-sm text-error">{error}</p>
<p role="alert" className="text-sm text-error">
{error}
</p>
{runId && (
<button className="mt-2 text-primary-500" onClick={() => void refreshRun()}>
Retry run
</button>
)}
</div>
)}
{renderTabContent()}

View file

@ -1,102 +1,55 @@
import { ArrowPathIcon, ForwardIcon, PauseIcon, PlayIcon } from '@heroicons/react/24/solid';
import { ArrowPathIcon, StopIcon } from '@heroicons/react/24/solid';
import type { Run } from '../services/backtestApiV2';
interface RunControlsCompactProps {
run: Run;
onPause: () => void;
onResume: () => void;
cancelRequested: boolean;
onCancel: () => void;
onRerun: (speed: number | null) => void;
onNext?: () => void;
onSpeedChange: (speed: number | null) => void;
}
export function RunControlsCompact({
run,
onPause,
onResume,
cancelRequested,
onCancel,
onRerun,
onNext,
}: RunControlsCompactProps) {
const isRunning = run.status === 'running';
const isPaused = run.status === 'paused';
const _isCompleted =
run.status === 'completed' || run.status === 'failed' || run.status === 'cancelled';
const active = ['pending', 'running', 'paused'].includes(run.status);
const requested = active && (cancelRequested || run.cancelRequested);
return (
<div className="flex items-center space-x-3">
{/* Progress */}
<div className="flex items-center space-x-2">
<span className="text-xs text-text-secondary">Progress:</span>
<div className="w-24 bg-background rounded-full h-2 overflow-hidden">
<div
className="bg-primary-500 h-2 transition-all duration-300 relative"
style={{ width: `${run.progress}%` }}
>
<div className="absolute inset-0 bg-gradient-to-r from-primary-500 to-primary-400 opacity-50"></div>
</div>
</div>
<progress className="w-24 h-2" max={100} value={run.progress} aria-label="Run progress" />
<span className="text-xs text-text-primary font-medium">{run.progress.toFixed(0)}%</span>
</div>
{/* Control Buttons */}
<div className="flex items-center space-x-1">
{isRunning ? (
{active && (
<button
onClick={onPause}
className="p-1 rounded hover:bg-surface-tertiary transition-colors"
title="Pause"
>
<PauseIcon className="w-4 h-4 text-text-primary" />
</button>
) : isPaused ? (
<button
onClick={onResume}
className="p-1 rounded hover:bg-surface-tertiary transition-colors"
title="Resume"
>
<PlayIcon className="w-4 h-4 text-text-primary" />
</button>
) : null}
{onNext && (
<button
onClick={onNext}
onClick={onCancel}
disabled={Boolean(requested)}
className="p-1 rounded hover:bg-surface-tertiary transition-colors disabled:opacity-50"
disabled={!isRunning && !isPaused}
title="Next"
title={requested ? 'Cancellation requested' : 'Cancel run'}
aria-label={requested ? 'Cancellation requested' : 'Cancel run'}
>
<ForwardIcon className="w-4 h-4 text-text-primary" />
<StopIcon className="w-4 h-4 text-text-primary" />
</button>
)}
<button
onClick={() => onRerun(null)} // Always use max speed
onClick={() => onRerun(null)}
className="p-1 rounded hover:bg-surface-tertiary transition-colors"
title="Rerun"
aria-label="Rerun"
>
<ArrowPathIcon className="w-4 h-4 text-text-primary" />
</button>
</div>
{/* Status Indicator */}
{run.status !== 'running' && run.status !== 'paused' && (
<>
<div className="h-6 w-px bg-border"></div>
<span
className={`text-xs font-medium ${
run.status === 'completed'
? 'text-success'
: run.status === 'failed'
? 'text-error'
: run.status === 'cancelled'
? 'text-text-secondary'
: 'text-text-primary'
}`}
>
{run.status.charAt(0).toUpperCase() + run.status.slice(1)}
</span>
</>
)}
<span role="status" className="text-xs font-medium text-text-primary">
{requested
? 'Cancellation requested'
: run.status.charAt(0).toUpperCase() + run.status.slice(1)}
</span>
</div>
);
}

View file

@ -1,413 +1,362 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { defined } from '@stock-bot/invariants';
import { browserLog } from '@/utils/browserLog';
import { backtestApiV2 } from '../services/backtestApiV2';
import { backtestApiV2, RunResultsUnavailableError } from '../services/backtestApiV2';
import type { Backtest, CreateBacktestRequest, Run, RunResult } from '../services/backtestApiV2';
interface UseBacktestV2Return {
// State
backtest: Backtest | null;
runs: Run[];
currentRun: Run | null;
runResults: RunResult | null;
isLoading: boolean;
error: string | null;
// Actions
loadBacktest: (id: string) => Promise<void>;
createBacktest: (request: CreateBacktestRequest) => Promise<Backtest>;
updateBacktest: (id: string, updates: Partial<CreateBacktestRequest>) => Promise<void>;
deleteBacktest: (id: string) => Promise<void>;
createRun: (speedMultiplier?: number | null) => Promise<Run | undefined>;
pauseRun: () => Promise<void>;
resumeRun: () => Promise<void>;
cancelRun: () => Promise<void>;
updateRunSpeed: (speedMultiplier: number | null) => Promise<void>;
selectRun: (runId: string | undefined) => Promise<void>;
interface RunSelection {
id: string;
controller: AbortController;
timer?: ReturnType<typeof setTimeout>;
request?: Promise<void>;
refreshRequested: boolean;
results: RunResult | null;
}
export function useBacktestV2(): UseBacktestV2Return {
const isActive = (run: Run) => ['pending', 'running', 'paused'].includes(run.status);
const messageOf = (error: unknown, fallback: string) =>
error instanceof Error ? error.message : fallback;
export function useBacktestV2() {
const [backtest, setBacktest] = useState<Backtest | null>(null);
const [runs, setRuns] = useState<Run[]>([]);
const [currentRun, setCurrentRun] = useState<Run | null>(null);
const [runResults, setRunResults] = useState<RunResult | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [isBacktestLoading, setIsBacktestLoading] = useState(false);
const [isRunLoading, setIsRunLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [runError, setRunError] = useState<string | null>(null);
const [cancelRequested, setCancelRequested] = useState(false);
const mounted = useRef(true);
const backtestGeneration = useRef(0);
const selection = useRef<RunSelection | null>(null);
const cancellation = useRef<RunSelection | null>(null);
const pollingIntervalRef = useRef<NodeJS.Timeout | null>(null);
const isSelected = useCallback(
(selected: RunSelection) => mounted.current && selection.current === selected,
[]
);
const stopMonitoring = useCallback(() => {
const selected = selection.current;
selection.current = null;
cancellation.current = null;
if (selected) {
clearTimeout(selected.timer);
selected.controller.abort();
}
}, []);
// A selection owns one request chain (status, then results) and one timer.
// Polls, websocket invalidations and cancel acknowledgements all use this path.
const refreshSelection = useCallback(
function refresh(selected: RunSelection): Promise<void> {
if (!isSelected(selected)) {
return Promise.resolve();
}
if (selected.request) {
selected.refreshRequested = true;
return selected.request;
}
clearTimeout(selected.timer);
let monitorAgain = true;
selected.request = (async () => {
try {
const run = await backtestApiV2.getRun(selected.id, selected.controller.signal);
if (!isSelected(selected)) {
return;
}
setCurrentRun(run);
setRuns(previous =>
previous.some(item => item.id === run.id)
? previous.map(item => (item.id === run.id ? run : item))
: [run, ...previous]
);
setRunError(null);
monitorAgain = isActive(run);
if (!monitorAgain) {
cancellation.current = null;
setCancelRequested(false);
} else if (run.cancelRequested) {
setCancelRequested(true);
}
if (run.status === 'completed') {
if (!selected.results) {
const results = await backtestApiV2.getRunResults(
selected.id,
selected.controller.signal
);
if (!isSelected(selected)) {
return;
}
if (results && results.runId !== selected.id) {
throw new Error('Received results for a different run');
}
selected.results = results;
setRunResults(results);
}
} else {
selected.results = null;
setRunResults(null);
}
} catch (err) {
if (!isSelected(selected)) {
return;
}
setRunError(
err instanceof RunResultsUnavailableError
? null
: messageOf(err, 'Failed to refresh run')
);
} finally {
if (isSelected(selected)) {
selected.request = undefined;
setIsRunLoading(false);
if (selected.refreshRequested) {
selected.refreshRequested = false;
void refresh(selected);
} else if (monitorAgain) {
selected.timer = setTimeout(() => void refresh(selected), 1000);
}
}
}
})();
return selected.request;
},
[isSelected]
);
const refreshRun = useCallback(
(runId?: string) => {
const selected = selection.current;
return selected && (!runId || selected.id === runId)
? refreshSelection(selected)
: Promise.resolve();
},
[refreshSelection]
);
const selectRun = useCallback(
(runId: string | undefined) => {
if (runId && selection.current?.id === runId) {
return refreshSelection(selection.current);
}
stopMonitoring();
setCurrentRun(null);
setRunResults(null);
setRunError(null);
setCancelRequested(false);
setIsRunLoading(Boolean(runId));
if (!runId) {
return Promise.resolve();
}
const selected: RunSelection = {
id: runId,
controller: new AbortController(),
refreshRequested: false,
results: null,
};
selection.current = selected;
return refreshSelection(selected);
},
[refreshSelection, stopMonitoring]
);
// Load a specific backtest and its runs
const loadBacktest = useCallback(async (id: string) => {
setIsLoading(true);
const generation = ++backtestGeneration.current;
setIsBacktestLoading(true);
setError(null);
setBacktest(null);
setRuns([]);
try {
const [loadedBacktest, loadedRuns] = await Promise.all([
backtestApiV2.getBacktest(id),
backtestApiV2.listRuns(id),
]);
if (!mounted.current || generation !== backtestGeneration.current) {
return;
}
setBacktest(loadedBacktest);
setRuns(loadedRuns);
// Don't auto-select runs here - let the URL parameter drive the selection
// Run polling may already have a newer version of the selected row.
setRuns(previous =>
loadedRuns.map(run =>
run.id === selection.current?.id
? (previous.find(item => item.id === run.id) ?? run)
: run
)
);
} catch (err) {
browserLog.error('Failed to load backtest:', err);
setError(err instanceof Error ? err.message : 'Failed to load backtest');
if (mounted.current && generation === backtestGeneration.current) {
setError(messageOf(err, 'Failed to load backtest'));
}
} finally {
setIsLoading(false);
if (mounted.current && generation === backtestGeneration.current) {
setIsBacktestLoading(false);
}
}
}, []);
// Create a new backtest
const createBacktest = useCallback(async (request: CreateBacktestRequest): Promise<Backtest> => {
setIsLoading(true);
setError(null);
try {
const newBacktest = await backtestApiV2.createBacktest(request);
setBacktest(newBacktest);
setRuns([]);
setCurrentRun(null);
setRunResults(null);
return newBacktest;
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to create backtest');
throw err;
} finally {
setIsLoading(false);
}
}, []);
// Update backtest configuration
const updateBacktest = useCallback(
async (id: string, updates: Partial<CreateBacktestRequest>) => {
setIsLoading(true);
const createBacktest = useCallback(
async (request: CreateBacktestRequest) => {
const generation = ++backtestGeneration.current;
setIsBacktestLoading(true);
setError(null);
try {
const updatedBacktest = await backtestApiV2.updateBacktest(id, updates);
setBacktest(updatedBacktest);
const created = await backtestApiV2.createBacktest(request);
if (mounted.current && generation === backtestGeneration.current) {
setBacktest(created);
setRuns([]);
await selectRun(undefined);
}
return created;
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to update backtest');
if (mounted.current && generation === backtestGeneration.current) {
setError(messageOf(err, 'Failed to create backtest'));
}
throw err;
} finally {
setIsLoading(false);
if (mounted.current && generation === backtestGeneration.current) {
setIsBacktestLoading(false);
}
}
},
[selectRun]
);
const updateBacktest = useCallback(
async (id: string, updates: Partial<CreateBacktestRequest>) => {
const generation = ++backtestGeneration.current;
setIsBacktestLoading(true);
setError(null);
try {
const updated = await backtestApiV2.updateBacktest(id, updates);
if (mounted.current && generation === backtestGeneration.current) {
setBacktest(updated);
}
} catch (err) {
if (mounted.current && generation === backtestGeneration.current) {
setError(messageOf(err, 'Failed to update backtest'));
}
throw err;
} finally {
if (mounted.current && generation === backtestGeneration.current) {
setIsBacktestLoading(false);
}
}
},
[]
);
// Delete backtest
const deleteBacktest = useCallback(async (id: string) => {
setIsLoading(true);
setError(null);
try {
await backtestApiV2.deleteBacktest(id);
setBacktest(null);
setRuns([]);
setCurrentRun(null);
setRunResults(null);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to delete backtest');
throw err;
} finally {
setIsLoading(false);
}
}, []);
// Create a new run
const createRun = useCallback(
async (speedMultiplier?: number | null) => {
if (!backtest) {
return;
}
setIsLoading(true);
const deleteBacktest = useCallback(
async (id: string) => {
const generation = ++backtestGeneration.current;
setIsBacktestLoading(true);
setError(null);
setRunResults(null);
try {
// Pass speedMultiplier as-is, null means max speed
const newRun = await backtestApiV2.createRun(backtest.id, {
speedMultiplier: speedMultiplier === undefined ? null : speedMultiplier,
});
// Add to runs array first
setRuns(prevRuns => [newRun, ...prevRuns]);
// Clear previous results immediately
setRunResults(null);
// Set as current run
setCurrentRun(newRun);
// Small delay to ensure the run is properly created in the database
await new Promise(resolve => setTimeout(resolve, 100));
// Check if the run is completed (it might complete instantly)
let finalRun = newRun;
// If status is pending, check again after a short delay
if (newRun.status === 'pending') {
await new Promise(resolve => setTimeout(resolve, 500));
try {
finalRun = await backtestApiV2.getRun(newRun.id);
// Update the current run with the latest status
setCurrentRun(finalRun);
setRuns(prevRuns => prevRuns.map(r => (r.id === finalRun.id ? finalRun : r)));
} catch (err) {
browserLog.error('Failed to re-check run status:', err);
}
await backtestApiV2.deleteBacktest(id);
if (mounted.current && generation === backtestGeneration.current) {
setBacktest(null);
setRuns([]);
await selectRun(undefined);
}
// If the run is completed, load results
if (finalRun.status === 'completed') {
try {
const results = await backtestApiV2.getRunResults(finalRun.id);
setRunResults(results);
} catch (err) {
browserLog.error('Failed to load new run results:', err);
}
} else {
// Start monitoring the run
startMonitoringRun(finalRun.id);
}
return newRun; // Return the created run
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to create run');
throw err; // Re-throw so caller knows it failed
if (mounted.current && generation === backtestGeneration.current) {
setError(messageOf(err, 'Failed to delete backtest'));
}
throw err;
} finally {
setIsLoading(false);
if (mounted.current && generation === backtestGeneration.current) {
setIsBacktestLoading(false);
}
}
},
[selectRun]
);
const createRun = useCallback(
async (speedMultiplier: number | null = null) => {
if (!backtest) {
return undefined;
}
const generation = backtestGeneration.current;
const selected = selection.current;
setIsBacktestLoading(true);
setError(null);
try {
const created = await backtestApiV2.createRun(backtest.id, { speedMultiplier });
if (!mounted.current || generation !== backtestGeneration.current) {
return undefined;
}
setRuns(previous => [created, ...previous]);
// The route owns selection. Never navigate away from a newer user selection.
return selection.current === selected ? created : undefined;
} catch (err) {
if (mounted.current && generation === backtestGeneration.current) {
setError(messageOf(err, 'Failed to create run'));
}
return undefined;
} finally {
if (mounted.current && generation === backtestGeneration.current) {
setIsBacktestLoading(false);
}
}
},
[backtest]
);
// Run control actions
const pauseRun = useCallback(async () => {
if (!currentRun || currentRun.status !== 'running') {
return;
}
try {
await backtestApiV2.pauseRun(currentRun.id);
setCurrentRun(prev => (prev ? { ...prev, status: 'paused' } : null));
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to pause run');
}
}, [currentRun]);
const resumeRun = useCallback(async () => {
if (!currentRun || currentRun.status !== 'paused') {
return;
}
try {
await backtestApiV2.resumeRun(currentRun.id);
setCurrentRun(prev => (prev ? { ...prev, status: 'running' } : null));
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to resume run');
}
}, [currentRun]);
const cancelRun = useCallback(async () => {
if (!currentRun || !['pending', 'running', 'paused'].includes(currentRun.status)) {
const selected = selection.current;
if (
!selected ||
!currentRun ||
currentRun.id !== selected.id ||
!isActive(currentRun) ||
cancellation.current === selected
) {
return;
}
cancellation.current = selected;
setCancelRequested(true);
setRunError(null);
try {
await backtestApiV2.cancelRun(currentRun.id);
// Acceptance is not completion: keep monitoring the owner's persisted acknowledgement.
const updated = await backtestApiV2.getRun(currentRun.id);
setCurrentRun(updated);
setRuns(prev => prev.map(run => (run.id === updated.id ? updated : run)));
await backtestApiV2.cancelRun(selected.id, selected.controller.signal);
if (isSelected(selected)) {
await refreshSelection(selected);
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to cancel run');
if (isSelected(selected)) {
cancellation.current = null;
setCancelRequested(Boolean(currentRun.cancelRequested));
setRunError(messageOf(err, 'Failed to request cancellation'));
}
}
}, [currentRun]);
}, [currentRun, isSelected, refreshSelection]);
const updateRunSpeed = useCallback(
async (speedMultiplier: number | null) => {
if (!currentRun) {
return;
}
try {
// Keep null as null for max speed (no limit)
const apiSpeed = speedMultiplier;
// Only call API if run is active
if (currentRun.status === 'running' || currentRun.status === 'paused') {
await backtestApiV2.updateRunSpeed(currentRun.id, apiSpeed);
}
// Always update local state so UI reflects the selection
setCurrentRun(prev => (prev ? { ...prev, speedMultiplier: apiSpeed } : null));
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to update run speed');
}
},
[currentRun]
);
// Select a specific run
const selectRun = useCallback(
async (runId: string | undefined) => {
if (!runId) {
setCurrentRun(null);
setRunResults(null);
stopMonitoringRun();
return;
}
let run = runs.find(r => r.id === runId);
// If run not found in list, try to fetch it directly
if (!run) {
let attempts = 0;
const maxAttempts = 3;
while (attempts < maxAttempts) {
try {
run = await backtestApiV2.getRun(runId);
// Add to runs list if not present
setRuns(prevRuns => {
const exists = prevRuns.some(r => r.id === defined(run).id);
if (!exists) {
return [defined(run), ...prevRuns];
}
return prevRuns;
});
break; // Success, exit loop
} catch (err) {
attempts++;
if (attempts >= maxAttempts) {
browserLog.error('Failed to fetch run after all attempts:', runId, err);
setError(`Failed to load run ${runId}`);
return;
}
// Wait before retrying
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
}
if (!run) {
setError(`Run ${runId} not found`);
return;
}
setCurrentRun(run);
setRunResults(null);
if (run.status === 'completed') {
try {
const results = await backtestApiV2.getRunResults(run.id);
setRunResults(results);
} catch (err) {
browserLog.error('Failed to load run results:', err);
setError(err instanceof Error ? err.message : 'Failed to load run results');
}
} else if (run.status === 'running' || run.status === 'paused' || run.status === 'pending') {
startMonitoringRun(run.id);
} else {
browserLog.warn('Run has unexpected status:', run.status);
}
},
[runs]
);
// Monitor run progress
const startMonitoringRun = useCallback((runId: string) => {
// Stop any existing monitoring
stopMonitoringRun();
// For pending runs, we need to poll until they start or complete
// We'll check the run status by fetching it
pollingIntervalRef.current = setInterval(async () => {
try {
const updatedRun = await backtestApiV2.getRun(runId);
// Update the run in state
setCurrentRun(updatedRun);
setRuns(prevRuns => prevRuns.map(r => (r.id === updatedRun.id ? updatedRun : r)));
// If run is no longer pending, handle the new status
if (updatedRun.status === 'completed') {
stopMonitoringRun();
try {
const results = await backtestApiV2.getRunResults(runId);
setRunResults(results);
} catch (err) {
browserLog.error('Failed to load completed run results:', err);
}
} else if (updatedRun.status === 'failed' || updatedRun.status === 'cancelled') {
stopMonitoringRun();
}
} catch (err) {
browserLog.error('Failed to poll run status:', err);
}
}, 1000); // Poll every second
}, []);
const _startPollingRun = (runId: string) => {
pollingIntervalRef.current = setInterval(async () => {
try {
const updatedRun = await backtestApiV2.getRun(runId);
handleRunUpdate(updatedRun);
if (updatedRun.status === 'completed') {
const results = await backtestApiV2.getRunResults(runId);
setRunResults(results);
stopMonitoringRun();
} else if (updatedRun.status === 'failed' || updatedRun.status === 'cancelled') {
stopMonitoringRun();
}
} catch (err) {
browserLog.error('Failed to poll run status:', err);
}
}, 1000); // Poll every second
};
const stopMonitoringRun = () => {
if (pollingIntervalRef.current) {
clearInterval(pollingIntervalRef.current);
pollingIntervalRef.current = null;
}
};
const handleRunUpdate = (update: Run) => {
setCurrentRun(update);
setRuns(prevRuns => prevRuns.map(run => (run.id === update.id ? update : run)));
};
// Cleanup on unmount
useEffect(() => {
mounted.current = true;
return () => {
stopMonitoringRun();
mounted.current = false;
backtestGeneration.current++;
stopMonitoring();
};
}, []);
}, [stopMonitoring]);
return {
backtest,
runs,
currentRun,
runResults,
isLoading,
error,
isLoading: isBacktestLoading || isRunLoading,
error: runError ?? error,
cancelRequested,
loadBacktest,
createBacktest,
updateBacktest,
deleteBacktest,
createRun,
pauseRun,
resumeRun,
cancelRun,
updateRunSpeed,
selectRun,
refreshRun,
};
}

View file

@ -49,6 +49,13 @@ export interface CreateRunRequest {
export type RunResult = BacktestRunResult;
export class RunResultsUnavailableError extends Error {
constructor() {
super('Completed run results are not available');
this.name = 'RunResultsUnavailableError';
}
}
export const backtestApiV2 = {
// Backtest operations
async createBacktest(request: CreateBacktestRequest): Promise<Backtest> {
@ -144,8 +151,8 @@ export const backtestApiV2 = {
return response.json();
},
async getRun(id: string): Promise<Run> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}`);
async getRun(id: string, signal?: AbortSignal): Promise<Run> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}`, { signal });
if (!response.ok) {
throw new Error(`Failed to get run: ${response.statusText}`);
@ -154,8 +161,12 @@ export const backtestApiV2 = {
return response.json();
},
async getRunResults(runId: string): Promise<RunResult> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${runId}/results`);
async getRunResults(runId: string, signal?: AbortSignal): Promise<RunResult> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${runId}/results`, { signal });
if (response.status === 404) {
throw new RunResultsUnavailableError();
}
if (!response.ok) {
throw new Error(`Failed to get run results: ${response.status} ${response.statusText}`);
@ -184,9 +195,10 @@ export const backtestApiV2 = {
}
},
async cancelRun(id: string): Promise<void> {
async cancelRun(id: string, signal?: AbortSignal): Promise<void> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/cancel`, {
method: 'POST',
signal,
});
if (!response.ok) {

View file

@ -17,188 +17,143 @@ interface UseWebSocketOptions {
onCompleted?: (results?: unknown) => void;
}
export function useWebSocket({
runId,
onMessage,
onProgress,
onError,
onCompleted,
}: UseWebSocketOptions) {
export function useWebSocket({ runId, ...callbacks }: UseWebSocketOptions) {
const [isConnected, setIsConnected] = useState(false);
const [lastMessage, setLastMessage] = useState<WebSocketMessage | null>(null);
const callbacksRef = useRef(callbacks);
const wsRef = useRef<WebSocket | null>(null);
const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const pingIntervalRef = useRef<NodeJS.Timeout | null>(null);
const isIntentionalDisconnect = useRef(false);
const connectRef = useRef<() => void>(() => {});
const disconnectRef = useRef<() => void>(() => {});
callbacksRef.current = callbacks;
const connect = useCallback(() => {
if (!runId) {
browserLog.log('useWebSocket: No runId provided, skipping connection');
return;
}
useEffect(() => {
let disposed = false;
let reconnectTimer: ReturnType<typeof setTimeout> | undefined;
let pingTimer: ReturnType<typeof setInterval> | undefined;
setIsConnected(false);
setLastMessage(null);
// Check if already connected or connecting
if (
wsRef.current &&
(wsRef.current.readyState === WebSocket.OPEN ||
wsRef.current.readyState === WebSocket.CONNECTING)
) {
browserLog.log('useWebSocket: Already connected or connecting to runId:', runId);
return;
}
const connect = () => {
if (disposed || !runId || wsRef.current) {
return;
}
clearTimeout(reconnectTimer);
const url = new URL('/ws', API_BASE_URL);
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
url.searchParams.set('runId', runId);
// Reset intentional disconnect flag
isIntentionalDisconnect.current = false;
// Clear any pending reconnect timeout
if (reconnectTimeoutRef.current) {
clearTimeout(reconnectTimeoutRef.current);
reconnectTimeoutRef.current = null;
}
const url = new URL('/ws', API_BASE_URL);
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
url.searchParams.set('runId', runId);
const wsUrl = url.toString();
browserLog.log('Connecting to WebSocket:', wsUrl);
try {
const ws = new WebSocket(wsUrl);
wsRef.current = ws;
ws.onopen = () => {
browserLog.log('WebSocket connected');
setIsConnected(true);
// Start ping interval
pingIntervalRef.current = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'ping' }));
}
}, 30000); // Ping every 30 seconds
};
ws.onmessage = event => {
try {
const message: WebSocketMessage = JSON.parse(event.data);
browserLog.log('WebSocket message:', message);
setLastMessage(message);
// Call appropriate callbacks
if (onMessage) {
onMessage(message);
}
switch (message.type) {
case 'progress':
if (onProgress && message.data) {
onProgress(message.data.progress ?? 0, message.data.currentDate);
}
break;
case 'error':
if (onError && message.data?.error) {
onError(message.data.error);
browserLog.error('Run Error:', message.data.error);
}
break;
case 'completed':
if (onCompleted) {
onCompleted(message.data?.results);
}
browserLog.log('Run Completed: The backtest run has completed successfully.');
break;
}
} catch (error) {
browserLog.error('Error parsing WebSocket message:', error);
const retry = () => {
if (!disposed) {
reconnectTimer = setTimeout(connect, 3000);
}
};
ws.onerror = error => {
browserLog.error('WebSocket error:', error);
try {
const ws = new WebSocket(url.toString());
wsRef.current = ws;
const isCurrent = () => !disposed && wsRef.current === ws;
ws.onopen = () => {
if (!isCurrent()) {
return;
}
setIsConnected(true);
pingTimer = setInterval(() => {
if (isCurrent() && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'ping' }));
}
}, 30000);
};
ws.onmessage = event => {
if (!isCurrent()) {
return;
}
try {
const message: WebSocketMessage = JSON.parse(event.data);
if (message.runId && message.runId !== runId) {
return;
}
setLastMessage(message);
callbacksRef.current.onMessage?.(message);
switch (message.type) {
case 'progress':
if (message.data) {
callbacksRef.current.onProgress?.(
message.data.progress ?? 0,
message.data.currentDate
);
}
break;
case 'error':
if (message.data?.error) {
callbacksRef.current.onError?.(message.data.error);
}
break;
case 'completed':
callbacksRef.current.onCompleted?.(message.data?.results);
break;
}
} catch (error) {
browserLog.error('Error parsing WebSocket message:', error);
}
};
ws.onerror = () => {
if (isCurrent()) {
setIsConnected(false);
}
};
ws.onclose = () => {
if (!isCurrent()) {
return;
}
wsRef.current = null;
setIsConnected(false);
clearInterval(pingTimer);
// Check ownership before clearing the reference, not after.
retry();
};
} catch (error) {
browserLog.error('Error creating WebSocket:', error);
setIsConnected(false);
};
retry();
}
};
ws.onclose = () => {
browserLog.log('WebSocket disconnected');
setIsConnected(false);
wsRef.current = null;
// Clear ping interval
if (pingIntervalRef.current) {
clearInterval(pingIntervalRef.current);
pingIntervalRef.current = null;
}
// Attempt to reconnect after 3 seconds
// Only reconnect if not intentionally disconnected and still the same WebSocket
if (runId && wsRef.current === ws && !isIntentionalDisconnect.current) {
reconnectTimeoutRef.current = setTimeout(() => {
browserLog.log('Attempting to reconnect...');
connect();
}, 3000);
}
};
} catch (error) {
browserLog.error('Error creating WebSocket:', error);
setIsConnected(false);
}
}, [runId, onMessage, onProgress, onError, onCompleted]);
const disconnect = useCallback(() => {
browserLog.log('Disconnecting WebSocket...');
// Set flag to prevent automatic reconnection
isIntentionalDisconnect.current = true;
if (reconnectTimeoutRef.current) {
clearTimeout(reconnectTimeoutRef.current);
reconnectTimeoutRef.current = null;
}
if (pingIntervalRef.current) {
clearInterval(pingIntervalRef.current);
pingIntervalRef.current = null;
}
if (wsRef.current) {
// Set a flag to prevent reconnection
const close = () => {
clearTimeout(reconnectTimer);
clearInterval(pingTimer);
const ws = wsRef.current;
wsRef.current = null;
ws.close();
}
setIsConnected(false);
}, []);
if (ws) {
ws.onopen = null;
ws.onmessage = null;
ws.onerror = null;
ws.onclose = null;
ws.close();
}
};
connectRef.current = () => {
disposed = false;
connect();
};
disconnectRef.current = () => {
disposed = true;
close();
setIsConnected(false);
};
connect();
return () => {
disposed = true;
close();
connectRef.current = () => {};
disconnectRef.current = () => {};
};
}, [runId]);
const connect = useCallback(() => connectRef.current(), []);
const disconnect = useCallback(() => disconnectRef.current(), []);
const sendMessage = useCallback((message: unknown) => {
if (wsRef.current?.readyState === WebSocket.OPEN) {
wsRef.current.send(JSON.stringify(message));
} else {
browserLog.warn('WebSocket is not connected');
}
}, []);
useEffect(() => {
// Small delay to prevent rapid reconnections during React's render cycles
const timeoutId = setTimeout(() => {
if (runId) {
connect();
} else {
disconnect();
}
}, 100);
return () => {
clearTimeout(timeoutId);
disconnect();
};
}, [runId]); // Only depend on runId, not the functions
return {
isConnected,
lastMessage,
sendMessage,
disconnect,
connect,
};
return { isConnected, lastMessage, sendMessage, disconnect, connect };
}