diff --git a/apps/stock/web-app/package.json b/apps/stock/web-app/package.json
index 5e7de329..6923ac23 100644
--- a/apps/stock/web-app/package.json
+++ b/apps/stock/web-app/package.json
@@ -40,6 +40,7 @@
"eslint-plugin-react": "^7.32.2",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.3",
+ "happy-dom": "21.0.4",
"postcss": "^8.4.27",
"tailwindcss": "^3.3.3",
"typescript": "^5.0.2",
diff --git a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx
index 7fb69c67..9dda14dc 100644
--- a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx
+++ b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx
@@ -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 (
+
+ 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.
+
void refreshRun()}>
+ Retry results
+
+
+ );
+ }
+ }
+ // A missing result is not a successful run with zero trades.
if (!currentRun && ['details', 'trades'].includes(activeTab)) {
return (
@@ -246,7 +224,7 @@ export function BacktestDetailPageV2() {
{
- 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 (
-
Backtest not found
+
{error || 'Backtest not found'}
+ {error && id && (
+
void loadBacktest(id)}>
+ Retry backtest
+
+ )}
navigate('/backtests')}
className="text-primary-500 hover:text-primary-600"
@@ -378,10 +361,9 @@ export function BacktestDetailPageV2() {
)}
@@ -392,7 +374,14 @@ export function BacktestDetailPageV2() {
{error && (
-
{error}
+
+ {error}
+
+ {runId && (
+
void refreshRun()}>
+ Retry run
+
+ )}
)}
{renderTabContent()}
diff --git a/apps/stock/web-app/src/features/backtest/components/RunControlsCompact.tsx b/apps/stock/web-app/src/features/backtest/components/RunControlsCompact.tsx
index cc86b289..89470f11 100644
--- a/apps/stock/web-app/src/features/backtest/components/RunControlsCompact.tsx
+++ b/apps/stock/web-app/src/features/backtest/components/RunControlsCompact.tsx
@@ -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 (
- {/* Progress */}
Progress:
-
+
{run.progress.toFixed(0)}%
-
- {/* Control Buttons */}
- {isRunning ? (
+ {active && (
-
-
- ) : isPaused ? (
-
-
-
- ) : null}
-
- {onNext && (
-
-
+
)}
-
onRerun(null)} // Always use max speed
+ onClick={() => onRerun(null)}
className="p-1 rounded hover:bg-surface-tertiary transition-colors"
title="Rerun"
+ aria-label="Rerun"
>
-
- {/* Status Indicator */}
- {run.status !== 'running' && run.status !== 'paused' && (
- <>
-
-
- {run.status.charAt(0).toUpperCase() + run.status.slice(1)}
-
- >
- )}
+
+ {requested
+ ? 'Cancellation requested'
+ : run.status.charAt(0).toUpperCase() + run.status.slice(1)}
+
);
}
diff --git a/apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts b/apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts
index 189903c0..7aed9320 100644
--- a/apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts
+++ b/apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts
@@ -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
;
- createBacktest: (request: CreateBacktestRequest) => Promise;
- updateBacktest: (id: string, updates: Partial) => Promise;
- deleteBacktest: (id: string) => Promise;
-
- createRun: (speedMultiplier?: number | null) => Promise;
- pauseRun: () => Promise;
- resumeRun: () => Promise;
- cancelRun: () => Promise;
- updateRunSpeed: (speedMultiplier: number | null) => Promise;
- selectRun: (runId: string | undefined) => Promise;
+interface RunSelection {
+ id: string;
+ controller: AbortController;
+ timer?: ReturnType;
+ request?: Promise;
+ 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(null);
const [runs, setRuns] = useState([]);
const [currentRun, setCurrentRun] = useState(null);
const [runResults, setRunResults] = useState(null);
- const [isLoading, setIsLoading] = useState(false);
+ const [isBacktestLoading, setIsBacktestLoading] = useState(false);
+ const [isRunLoading, setIsRunLoading] = useState(false);
const [error, setError] = useState(null);
+ const [runError, setRunError] = useState(null);
+ const [cancelRequested, setCancelRequested] = useState(false);
+ const mounted = useRef(true);
+ const backtestGeneration = useRef(0);
+ const selection = useRef(null);
+ const cancellation = useRef(null);
- const pollingIntervalRef = useRef(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 {
+ 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 => {
- 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) => {
- 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) => {
+ 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,
};
}
diff --git a/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts b/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts
index f82aa3b6..b2a28df3 100644
--- a/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts
+++ b/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts
@@ -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 {
@@ -144,8 +151,8 @@ export const backtestApiV2 = {
return response.json();
},
- async getRun(id: string): Promise {
- const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}`);
+ async getRun(id: string, signal?: AbortSignal): Promise {
+ 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 {
- const response = await fetch(`${API_BASE_URL}/api/v2/runs/${runId}/results`);
+ async getRunResults(runId: string, signal?: AbortSignal): Promise {
+ 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 {
+ async cancelRun(id: string, signal?: AbortSignal): Promise {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/cancel`, {
method: 'POST',
+ signal,
});
if (!response.ok) {
diff --git a/apps/stock/web-app/src/hooks/useWebSocket.ts b/apps/stock/web-app/src/hooks/useWebSocket.ts
index 67985416..56dc6084 100644
--- a/apps/stock/web-app/src/hooks/useWebSocket.ts
+++ b/apps/stock/web-app/src/hooks/useWebSocket.ts
@@ -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(null);
+ const callbacksRef = useRef(callbacks);
const wsRef = useRef(null);
- const reconnectTimeoutRef = useRef(null);
- const pingIntervalRef = useRef(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 | undefined;
+ let pingTimer: ReturnType | 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 };
}
diff --git a/bun.lock b/bun.lock
index 422c3793..a12d7667 100644
--- a/bun.lock
+++ b/bun.lock
@@ -218,6 +218,7 @@
"eslint-plugin-react": "^7.32.2",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.3",
+ "happy-dom": "21.0.4",
"postcss": "^8.4.27",
"tailwindcss": "^3.3.3",
"typescript": "^5.0.2",
@@ -1134,8 +1135,12 @@
"@types/webidl-conversions": ["@types/webidl-conversions@7.0.3", "", {}, "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA=="],
+ "@types/whatwg-mimetype": ["@types/whatwg-mimetype@3.0.2", "", {}, "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA=="],
+
"@types/whatwg-url": ["@types/whatwg-url@11.0.5", "", { "dependencies": { "@types/webidl-conversions": "*" } }, "sha512-coYR071JRaHa+xoEvvYqvnIHaVqaYrLPbsufM9BF63HkwI5Lgmy2QR8Q5K/lYDYo5AK82wOvSOS0UsLTpTG7uQ=="],
+ "@types/ws": ["@types/ws@8.18.2", "", { "dependencies": { "@types/node": "*" } }, "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w=="],
+
"@types/yup": ["@types/yup@0.32.0", "", { "dependencies": { "yup": "*" } }, "sha512-Gr2lllWTDxGVYHgWfL8szjdedERpNgm44L9BDL2cmcHG7Bfd6taEpiW3ayMFLaYvlJr/6bFXDJdh6L406AGlFg=="],
"@typescript-eslint/eslint-plugin": ["@typescript-eslint/eslint-plugin@8.35.1", "", { "dependencies": { "@eslint-community/regexpp": "^4.10.0", "@typescript-eslint/scope-manager": "8.35.1", "@typescript-eslint/type-utils": "8.35.1", "@typescript-eslint/utils": "8.35.1", "@typescript-eslint/visitor-keys": "8.35.1", "graphemer": "^1.4.0", "ignore": "^7.0.0", "natural-compare": "^1.4.0", "ts-api-utils": "^2.1.0" }, "peerDependencies": { "@typescript-eslint/parser": "^8.35.1", "eslint": "^8.57.0 || ^9.0.0", "typescript": ">=4.8.4 <5.9.0" } }, "sha512-9XNTlo7P7RJxbVeICaIIIEipqxLKguyh+3UbXuT2XQuFp6d8VOeDEGuz5IiX0dgZo8CiI6aOFLg4e8cF71SFVg=="],
@@ -1300,6 +1305,8 @@
"buffer-crc32": ["buffer-crc32@1.0.0", "", {}, "sha512-Db1SbgBS/fg/392AblrMJk97KggmvYhr4pB5ZIMTWtaivCPMWLkmb7m21cJvpvgK+J3nsU2CmmixNBZx4vFj/w=="],
+ "buffer-image-size": ["buffer-image-size@0.6.4", "", { "dependencies": { "@types/node": "*" } }, "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ=="],
+
"buildcheck": ["buildcheck@0.0.6", "", {}, "sha512-8f9ZJCUXyT1M35Jx7MkBgmBMo3oHTTBIPLiY9xyL0pl3T5RwcPEY8cUHr5LBNfu/fk6c2T4DJZuVM/8ZZT2D2A=="],
"bullmq": ["bullmq@5.56.1", "", { "dependencies": { "cron-parser": "^4.9.0", "ioredis": "^5.4.1", "msgpackr": "^1.11.2", "node-abort-controller": "^3.1.1", "semver": "^7.5.4", "tslib": "^2.0.0", "uuid": "^9.0.0" } }, "sha512-HmX53sf24bbDj5NVrDLDEjy8OSDmbGMESfvFhVK8NpHsA4WlAdKxPDf7c5b9RZf5wZGHyAd2XhWSkE9dmNPYww=="],
@@ -1534,7 +1541,7 @@
"engine.io-parser": ["engine.io-parser@5.2.3", "", {}, "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q=="],
- "entities": ["entities@4.5.0", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="],
+ "entities": ["entities@7.0.1", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="],
"es-abstract": ["es-abstract@1.24.0", "", { "dependencies": { "array-buffer-byte-length": "^1.0.2", "arraybuffer.prototype.slice": "^1.0.4", "available-typed-arrays": "^1.0.7", "call-bind": "^1.0.8", "call-bound": "^1.0.4", "data-view-buffer": "^1.0.2", "data-view-byte-length": "^1.0.2", "data-view-byte-offset": "^1.0.1", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "es-set-tostringtag": "^2.1.0", "es-to-primitive": "^1.3.0", "function.prototype.name": "^1.1.8", "get-intrinsic": "^1.3.0", "get-proto": "^1.0.1", "get-symbol-description": "^1.1.0", "globalthis": "^1.0.4", "gopd": "^1.2.0", "has-property-descriptors": "^1.0.2", "has-proto": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "internal-slot": "^1.1.0", "is-array-buffer": "^3.0.5", "is-callable": "^1.2.7", "is-data-view": "^1.0.2", "is-negative-zero": "^2.0.3", "is-regex": "^1.2.1", "is-set": "^2.0.3", "is-shared-array-buffer": "^1.0.4", "is-string": "^1.1.1", "is-typed-array": "^1.1.15", "is-weakref": "^1.1.1", "math-intrinsics": "^1.1.0", "object-inspect": "^1.13.4", "object-keys": "^1.1.1", "object.assign": "^4.1.7", "own-keys": "^1.0.1", "regexp.prototype.flags": "^1.5.4", "safe-array-concat": "^1.1.3", "safe-push-apply": "^1.0.0", "safe-regex-test": "^1.1.0", "set-proto": "^1.0.0", "stop-iteration-iterator": "^1.1.0", "string.prototype.trim": "^1.2.10", "string.prototype.trimend": "^1.0.9", "string.prototype.trimstart": "^1.0.8", "typed-array-buffer": "^1.0.3", "typed-array-byte-length": "^1.0.3", "typed-array-byte-offset": "^1.0.4", "typed-array-length": "^1.0.7", "unbox-primitive": "^1.1.0", "which-typed-array": "^1.1.19" } }, "sha512-WSzPgsdLtTcQwm4CROfS5ju2Wa1QQcVeT37jFjYzdFz1r9ahadC8B8/a4qxJxM+09F18iumCdRmlr96ZYkQvEg=="],
@@ -1752,6 +1759,8 @@
"handlebars": ["handlebars@4.7.8", "", { "dependencies": { "minimist": "^1.2.5", "neo-async": "^2.6.2", "source-map": "^0.6.1", "wordwrap": "^1.0.0" }, "optionalDependencies": { "uglify-js": "^3.1.4" }, "bin": { "handlebars": "bin/handlebars" } }, "sha512-vafaFqs8MZkRrSX7sFVUdo3ap/eNiLnb4IakshzvP56X5Nr1iGKAIqdX6tMlm6HcNRIkr6AxO5jFEoJzzpT8aQ=="],
+ "happy-dom": ["happy-dom@21.0.4", "", { "dependencies": { "@types/node": ">=20.0.0", "@types/whatwg-mimetype": "^3.0.2", "@types/ws": "^8.18.1", "buffer-image-size": "^0.6.4", "entities": "^7.0.1", "whatwg-mimetype": "^3.0.0", "ws": "^8.21.0" } }, "sha512-tFm+GaLBgo6o0awHnvHaNoraVo27qJ+2tZEtZ+cIa08hXbeitrxAJajLI05hsUy/2/YTKcUjQYzHe5mCcraLBw=="],
+
"has-bigints": ["has-bigints@1.1.0", "", {}, "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg=="],
"has-flag": ["has-flag@4.0.0", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],
@@ -2680,7 +2689,7 @@
"wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
- "ws": ["ws@8.17.1", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ=="],
+ "ws": ["ws@8.22.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg=="],
"xmlhttprequest-ssl": ["xmlhttprequest-ssl@2.1.2", "", {}, "sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ=="],
@@ -2820,10 +2829,16 @@
"dockerode/uuid": ["uuid@10.0.0", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ=="],
+ "dom-serializer/entities": ["entities@4.5.0", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="],
+
"engine.io/debug": ["debug@4.3.7", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ=="],
+ "engine.io/ws": ["ws@8.17.1", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ=="],
+
"engine.io-client/debug": ["debug@4.3.7", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ=="],
+ "engine.io-client/ws": ["ws@8.17.1", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ=="],
+
"eslint/chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="],
"eslint/ignore": ["ignore@5.3.2", "", {}, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="],
@@ -2872,6 +2887,8 @@
"got/type-fest": ["type-fest@4.41.0", "", {}, "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA=="],
+ "happy-dom/whatwg-mimetype": ["whatwg-mimetype@3.0.0", "", {}, "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q=="],
+
"htmlparser2/entities": ["entities@6.0.1", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="],
"http-proxy-agent/agent-base": ["agent-base@7.1.3", "", {}, "sha512-jRR5wdylq8CkOe6hei19GGZnxM6rBGwFl3Bg0YItGDimvjGtAvdZk4Pu6Cl4u4Igsws4a1fd1Vq3ezrhn4KmFw=="],
@@ -2956,6 +2973,8 @@
"socket.io-adapter/debug": ["debug@4.3.7", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ=="],
+ "socket.io-adapter/ws": ["ws@8.17.1", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ=="],
+
"socket.io-client/debug": ["debug@4.3.7", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ=="],
"socket.io-parser/debug": ["debug@4.3.7", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ=="],
diff --git a/test/integration/backtest-run-controls.test.tsx b/test/integration/backtest-run-controls.test.tsx
new file mode 100644
index 00000000..e6646029
--- /dev/null
+++ b/test/integration/backtest-run-controls.test.tsx
@@ -0,0 +1,556 @@
+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 {
+ Run,
+ RunResult,
+} from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2';
+
+// 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', '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 router: typeof import('react-router-dom');
+let root: Root | undefined;
+let host: HTMLDivElement;
+let latest: ReturnType;
+let renders = 0;
+let now = 0;
+let timerId = 0;
+const timers = new Map<
+ number,
+ { at: number; delay: number; callback: () => void; repeat: boolean }
+>();
+
+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;
+ method: string;
+ signal?: AbortSignal | null;
+ settled: boolean;
+};
+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,
+ },
+ equity: [],
+ ohlcData: {},
+ positions: [],
+ trades: [],
+ analytics: {},
+ executionTime: 0,
+});
+const definition = {
+ id: 'definition',
+ name: 'Fixture',
+ strategy: 'sma',
+ symbols: ['A.US'],
+ startDate: '2024-01-01',
+ endDate: '2024-02-01',
+ initialCapital: 1000,
+ config: {},
+ createdAt: '2024-01-01',
+ updatedAt: '2024-01-01',
+};
+
+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 button = [...host.querySelectorAll('button')].find(
+ item => item.getAttribute('aria-label') === label || item.textContent?.trim() === label
+ );
+ if (!button) throw new Error(`Missing button ${label}`);
+ button.click();
+}
+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));
+}
+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),
+ })
+ )
+ )
+ );
+ 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' } : {})
+ );
+ });
+}
+
+beforeAll(async () => {
+ for (const [key, value] of Object.entries({
+ window: browser,
+ document: browser.document,
+ WebSocket: TestSocket,
+ 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'
+ ));
+ router = await import('react-router-dom');
+});
+beforeEach(() => {
+ requests.length = 0;
+ TestSocket.instances.length = 0;
+ renders = 0;
+ 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) => {
+ const pending: Request = {
+ ...deferred(),
+ path: new URL(String(input)).pathname,
+ method: init?.method ?? 'GET',
+ signal: init?.signal,
+ settled: false,
+ };
+ requests.push(pending);
+ // Deliberately ignore abort: guards must also reject a late server continuation.
+ return pending.promise;
+ }) 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('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',
+ 'Rerun',
+ ]);
+ await selectRunning('B', 'paused');
+ expect([...host.querySelectorAll('button')].map(item => item.title)).toEqual([
+ 'Cancel run',
+ 'Rerun',
+ ]);
+ });
+
+ 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(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');
+ 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');
+ 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');
+ });
+});