import { useCallback, useRef, useState, type Dispatch, type MutableRefObject, type SetStateAction, } from 'react'; import type { CanonicalRunCapability } from '@stock-bot/stock-config/canonical-research'; import { catalogExecutionReason } from '@/features/strategies/components/StrategySelection'; import { backtestApiV2, type Backtest, type Run } from '../services/backtestApiV2'; import { messageOf } from './useRunMonitoring'; export function useRunSubmission({ backtest, loadedBacktestId, mounted, selectionGeneration, catalog, canonicalCapability, capabilityError, setRuns, }: { backtest: Backtest | null; loadedBacktestId: MutableRefObject; mounted: MutableRefObject; selectionGeneration: MutableRefObject; catalog: boolean; canonicalCapability: CanonicalRunCapability | null; capabilityError: string | null; setRuns: Dispatch>; }) { const [submissionError, setSubmissionError] = useState(null); const [isSubmitting, setIsSubmitting] = useState(false); // 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); /** * Retain the same key/body after an ambiguous response so Retry can recover * the accepted run. This receipt is in memory for this mounted hook; it is not * a persistent browser recovery journal. New admissions recheck eligibility; * receipt retries recover the original run before current eligibility checks. */ 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 resetSubmission = useCallback(() => { submission.current = null; setSubmissionError(null); setIsSubmitting(false); }, []); return { createRun, submissionError, isSubmitting, hasPendingSubmission: submission.current !== null, resetSubmission, }; }