/** * Browser state for an editable backtest template and one selected durable run. * The API owns execution status/results; this hook owns request lifetimes and * ignores responses belonging to a previous page or run selection. */ import { useCallback, useEffect, useRef, useState } from 'react'; import type { CanonicalRunCapability } from '@stock-bot/stock-config/canonical-research'; import { backtestApiV2 } from '../services/backtestApiV2'; import type { Backtest, CreateBacktestRequest, Run } from '../services/backtestApiV2'; import { messageOf, useRunMonitoring } from './useRunMonitoring'; import { useRunSubmission } from './useRunSubmission'; /** * Connects BacktestDetailPageV2 to backtestApiV2. Template loading, run monitoring * and submission have separate state because each can fail independently. * WebSocket notifications call refreshRun; they never replace the saved result. */ export function useBacktestV2() { const [backtest, setBacktest] = useState(null); const [runs, setRuns] = useState([]); const [isBacktestLoading, setIsBacktestLoading] = useState(false); const [error, setError] = useState(null); // Generations reject late responses even when an earlier request cannot be // aborted. The selection generation also prevents submission from taking the // user away from a different run they selected while admission was pending. const mounted = useRef(true); const backtestGeneration = useRef(0); const loadedBacktestId = 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]); // Eligibility belongs to this exact loaded definition, not just its ID: an // edit must invalidate an earlier successful capability check. 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 { currentRun, runResults, isRunLoading, runError, cancelRequested, selection, selectionGeneration, stopMonitoring, refreshRun, selectRun, cancelRun, } = useRunMonitoring({ mounted, loadedBacktestId, setRuns }); const { createRun, submissionError, isSubmitting, hasPendingSubmission, resetSubmission } = useRunSubmission({ backtest, loadedBacktestId, mounted, selectionGeneration, catalog, canonicalCapability, capabilityError, setRuns, }); const loadBacktest = useCallback( async (id: string) => { const generation = ++backtestGeneration.current; if (loadedBacktestId.current !== id) { resetSubmission(); // 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, resetSubmission] ); 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; resetSubmission(); 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, resetSubmission] ); 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; resetSubmission(); 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, resetSubmission] ); 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); } } }, []); 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, cancelRequested, loadBacktest, createBacktest, updateBacktest, deleteBacktest, setBacktestArchived, createRun, cancelRun, selectRun, refreshRun, }; }