import { useCallback, useEffect, useRef, useState } from 'react'; import type { CanonicalRunCapability } from '@stock-bot/stock-config/canonical-research'; import { catalogExecutionReason } from '@/features/strategies/components/StrategySelection'; import { backtestApiV2, RunResultsUnavailableError } from '../services/backtestApiV2'; import type { Backtest, CreateBacktestRequest, ResearchRunResult, Run, } from '../services/backtestApiV2'; interface RunSelection { id: string; backtestId: string | null; controller: AbortController; timer?: ReturnType; request?: Promise; refreshRequested: boolean; results: ResearchRunResult | null; } 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 [isBacktestLoading, setIsBacktestLoading] = useState(false); const [isRunLoading, setIsRunLoading] = useState(false); const [error, setError] = useState(null); const [runError, setRunError] = useState(null); const [submissionError, setSubmissionError] = useState(null); const [isSubmitting, setIsSubmitting] = useState(false); const [cancelRequested, setCancelRequested] = useState(false); const mounted = useRef(true); const backtestGeneration = useRef(0); const loadedBacktestId = useRef(null); const selectionGeneration = useRef(0); // The intent survives an ambiguous response and configuration edits. Only an // acknowledged submission (or leaving this definition) releases its key. const submission = useRef<{ backtestId: string; key: string; body: { speedMultiplier: number | null }; pending: boolean; } | null>(null); const selection = useRef(null); const cancellation = useRef(null); const [capabilityRetry, setCapabilityRetry] = useState(0); const [capabilityState, setCapabilityState] = useState<{ definition: Backtest; retry: number; capability: CanonicalRunCapability | null; error: string | null; } | null>(null); const catalog = Boolean(backtest?.strategyVersionId) || backtest?.strategy === 'catalog'; useEffect(() => { if (!backtest || !catalog || backtest.archivedAt) { return; } const controller = new AbortController(); setCapabilityState({ definition: backtest, retry: capabilityRetry, capability: null, error: null, }); void backtestApiV2 .canonicalCapability(backtest.id, controller.signal) .then(capability => { if (!controller.signal.aborted && mounted.current) { setCapabilityState({ definition: backtest, retry: capabilityRetry, capability, error: null, }); } }) .catch(error => { if (!controller.signal.aborted && mounted.current) { setCapabilityState({ definition: backtest, retry: capabilityRetry, capability: null, error: messageOf(error, 'Could not check execution eligibility'), }); } }); return () => controller.abort(); }, [backtest, catalog, capabilityRetry]); const currentCapability = capabilityState?.definition === backtest && capabilityState?.retry === capabilityRetry ? capabilityState : null; const canonicalCapability = !backtest?.archivedAt && !isBacktestLoading ? (currentCapability?.capability ?? null) : null; const capabilityError = currentCapability?.error ?? null; const isCapabilityLoading = catalog && !backtest?.archivedAt && !capabilityError && canonicalCapability === null; const refreshCanonicalCapability = useCallback(() => setCapabilityRetry(value => value + 1), []); const isSelected = useCallback( (selected: RunSelection) => mounted.current && selection.current === selected && selected.backtestId === loadedBacktestId.current, [] ); const stopMonitoring = useCallback(() => { selectionGeneration.current++; 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; } if ( run.id !== selected.id || (selected.backtestId !== null && run.backtestId !== selected.backtestId) ) { monitorAgain = false; selected.refreshRequested = false; selected.results = null; setCurrentRun(null); setRunResults(null); throw new Error('Received a run for a different backtest or run selection'); } 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 || results.backtestId !== run.backtestId) ) { selected.refreshRequested = false; throw new Error('Received results for a different backtest or 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 && selection.current.backtestId === loadedBacktestId.current ) { 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, backtestId: loadedBacktestId.current, controller: new AbortController(), refreshRequested: false, results: null, }; selection.current = selected; return refreshSelection(selected); }, [refreshSelection, stopMonitoring] ); const loadBacktest = useCallback( async (id: string) => { const generation = ++backtestGeneration.current; if (loadedBacktestId.current !== id) { submission.current = null; setSubmissionError(null); setIsSubmitting(false); // Parent-only route changes do not rerun the page's runId effect. Fence // the old request chain and validate the same selection against its new parent. loadedBacktestId.current = id; void selectRun(selection.current?.id); } loadedBacktestId.current = id; 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; } if (loadedBacktest.id !== id || loadedRuns.some(run => run.backtestId !== id)) { throw new Error('Received a definition or run history for a different backtest'); } setBacktest(loadedBacktest); // 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) { if (mounted.current && generation === backtestGeneration.current) { setError(messageOf(err, 'Failed to load backtest')); } } finally { if (mounted.current && generation === backtestGeneration.current) { setIsBacktestLoading(false); } } }, [selectRun] ); const createBacktest = useCallback( async (request: CreateBacktestRequest) => { const generation = ++backtestGeneration.current; setIsBacktestLoading(true); setError(null); try { const created = await backtestApiV2.createBacktest(request); if (mounted.current && generation === backtestGeneration.current) { loadedBacktestId.current = created.id; submission.current = null; setSubmissionError(null); setIsSubmitting(false); setBacktest(created); setRuns([]); await selectRun(undefined); } return created; } catch (err) { if (mounted.current && generation === backtestGeneration.current) { setError(messageOf(err, 'Failed to create backtest')); } throw err; } finally { if (mounted.current && generation === backtestGeneration.current) { setIsBacktestLoading(false); } } }, [selectRun] ); const updateBacktest = useCallback( async (id: string, updates: Partial) => { if (backtest?.id === id && backtest.archivedAt) { throw new Error('Restore this archived backtest before editing its settings.'); } 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); } } }, [backtest] ); const deleteBacktest = useCallback( async (id: string) => { const generation = ++backtestGeneration.current; setIsBacktestLoading(true); setError(null); try { await backtestApiV2.deleteBacktest(id); if (mounted.current && generation === backtestGeneration.current) { loadedBacktestId.current = null; submission.current = null; setSubmissionError(null); setIsSubmitting(false); setBacktest(null); setRuns([]); await selectRun(undefined); } } catch (err) { if (mounted.current && generation === backtestGeneration.current) { setError(messageOf(err, 'Failed to delete backtest')); } throw err; } finally { if (mounted.current && generation === backtestGeneration.current) { setIsBacktestLoading(false); } } }, [selectRun] ); const setBacktestArchived = useCallback(async (id: string, archived: boolean) => { const generation = ++backtestGeneration.current; setIsBacktestLoading(true); try { const updated = await backtestApiV2.setBacktestArchived(id, archived); if ( mounted.current && generation === backtestGeneration.current && loadedBacktestId.current === id ) { // Archival changes only the template. Keep selected results, active run // monitoring and custody of any ambiguous submission key/body intact. setBacktest(updated); } } finally { if (mounted.current && generation === backtestGeneration.current) { setIsBacktestLoading(false); } } }, []); const createRun = useCallback( async (_speedMultiplier: number | null = null) => { if (!backtest || backtest.id !== loadedBacktestId.current || submission.current?.pending) { return undefined; } if (backtest.archivedAt && !submission.current) { setSubmissionError('Restore this archived backtest before starting a new run.'); return undefined; } if (catalog && !canonicalCapability?.available && !submission.current) { setSubmissionError( capabilityError ?? canonicalCapability?.reason ?? catalogExecutionReason ); return undefined; } if (!catalog && !submission.current) { setSubmissionError( 'Legacy execution is retired. Create a catalog backtest to run with retained canonical inputs.' ); return undefined; } const intent = (submission.current ??= { backtestId: backtest.id, key: crypto.randomUUID(), body: { speedMultiplier: null }, pending: false, }); intent.pending = true; const selectedGeneration = selectionGeneration.current; const ownsSubmission = () => mounted.current && submission.current === intent; const ownsSelection = () => ownsSubmission() && selectionGeneration.current === selectedGeneration; setIsSubmitting(true); setSubmissionError(null); try { const created = await backtestApiV2.createRun(intent.backtestId, intent.body, intent.key); if (!ownsSubmission()) { return undefined; } const selected = ownsSelection(); submission.current = null; setIsSubmitting(false); if (!selected) { return undefined; } setRuns(previous => [created, ...previous.filter(run => run.id !== created.id)]); return created; } catch (err) { if (ownsSubmission()) { setSubmissionError(messageOf(err, 'Failed to submit run')); } return undefined; } finally { intent.pending = false; if (ownsSubmission()) { setIsSubmitting(false); } } }, [backtest, catalog, canonicalCapability, capabilityError] ); const cancelRun = useCallback(async () => { 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(selected.id, selected.controller.signal); if (isSelected(selected)) { await refreshSelection(selected); } } catch (err) { if (isSelected(selected)) { cancellation.current = null; setCancelRequested(Boolean(currentRun.cancelRequested)); setRunError(messageOf(err, 'Failed to request cancellation')); } } }, [currentRun, isSelected, refreshSelection]); useEffect(() => { mounted.current = true; return () => { mounted.current = false; backtestGeneration.current++; stopMonitoring(); }; }, [stopMonitoring]); return { backtest, runs, currentRun, runResults, canonicalCapability, capabilityError, isCapabilityLoading, refreshCanonicalCapability, isLoading: isBacktestLoading || isRunLoading, error: runError ?? error, submissionError, isSubmitting, hasPendingSubmission: submission.current !== null, cancelRequested, loadBacktest, createBacktest, updateBacktest, deleteBacktest, setBacktestArchived, createRun, cancelRun, selectRun, refreshRun, }; }