import { useEffect, useRef, useState } from 'react'; import type { ExperimentRetryInput, ExperimentTrial, ExperimentTrialRetry, } from '@stock-bot/stock-config/experiments'; import { Button } from '@/components/ui/Button'; import { experimentApi, ExperimentApiError, type ExperimentRetryTarget, type WorkbenchExperimentDetailView, } from '../services/experimentApi'; interface Props { experimentId: string; backtestId: string; previewHash: string; strategyOrigin?: 'builtin' | 'candidate'; experimentCancelled: boolean; trial: ExperimentTrial; disabled: boolean; beginMutation: () => boolean; acceptMutation: (experiment: WorkbenchExperimentDetailView) => void; endMutation: () => void; onIntentChange: (trialKey: string, active: boolean) => void; } interface RetryIntent { target: ExperimentRetryTarget; input: ExperimentRetryInput; key: string; error: string | null; progress: number; } const message = (cause: unknown) => cause instanceof Error ? cause.message : 'Could not complete the retry request'; /** The row stays mounted through detail refreshes so a receipt can be recovered after state changes. */ export function ExperimentTrialRecovery({ experimentId, backtestId, previewHash, strategyOrigin = 'builtin', experimentCancelled, trial, disabled, beginMutation, acceptMutation, endMutation, onIntentChange, }: Props) { const number = trial.index + 1; const alive = useRef(false); const pending = useRef(false); const intentRef = useRef(null); const [intent, setIntent] = useState(null); const [sent, setSent] = useState(false); const [submitting, setSubmitting] = useState(false); const [error, setError] = useState(''); const [ambiguous, setAmbiguous] = useState(false); const [accepted, setAccepted] = useState(null); const [historyOpen, setHistoryOpen] = useState(false); const [history, setHistory] = useState(null); const [historyLoading, setHistoryLoading] = useState(false); const [historyError, setHistoryError] = useState(''); const [historyReload, setHistoryReload] = useState(0); const freshAllowed = Boolean(trial.runId) && trial.status === 'failed' && !trial.cancelRequested && !experimentCancelled; const sameFailure = intent && intent.target.runId === trial.runId && intent.input.expectedAttemptNumber === trial.attemptNumber && intent.input.expectedRetryCount === trial.retryCount; useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []); useEffect(() => { onIntentChange(trial.trialKey, Boolean(intent)); return () => onIntentChange(trial.trialKey, false); }, [intent, onIntentChange, trial.trialKey]); useEffect(() => { if (!historyOpen || !trial.runId) { return; } let current = true; const controller = new AbortController(); setHistory(null); setHistoryLoading(true); setHistoryError(''); void experimentApi .retryHistory(experimentId, trial.runId, trial.trialKey, controller.signal, strategyOrigin) .then(value => { if (current) { setHistory(value); } }) .catch(cause => { if (current) { setHistoryError(message(cause)); } }) .finally(() => { if (current) { setHistoryLoading(false); } }); return () => { current = false; controller.abort(); }; }, [ experimentId, trial.runId, trial.trialKey, trial.retryCount, historyOpen, historyReload, strategyOrigin, ]); const review = () => { if (disabled || !freshAllowed || !trial.runId || intentRef.current) { return; } const captured: RetryIntent = { target: { experimentId, backtestId, previewHash, runId: trial.runId, trialKey: trial.trialKey, }, input: { expectedAttemptNumber: trial.attemptNumber, expectedRetryCount: trial.retryCount }, key: crypto.randomUUID(), error: trial.error, progress: trial.progress, }; intentRef.current = captured; setIntent(captured); setSent(false); setError(''); setAmbiguous(false); setAccepted(null); }; const submit = async () => { const captured = intentRef.current; if ( !captured || pending.current || disabled || (!sent && (!freshAllowed || !sameFailure)) || !beginMutation() ) { return; } pending.current = true; setSent(true); setSubmitting(true); setError(''); try { const result = await experimentApi.retryTrial(captured.target, captured.input, captured.key); if (alive.current) { intentRef.current = null; setIntent(null); setSent(false); setAmbiguous(false); setAccepted(result.retry.retryNumber); setHistoryReload(value => value + 1); acceptMutation(result.experiment); } } catch (cause) { if (alive.current) { setError(message(cause)); setAmbiguous(!(cause instanceof ExperimentApiError) || cause.ambiguous); } } finally { pending.current = false; if (alive.current) { setSubmitting(false); } endMutation(); } }; const discard = () => { if ( pending.current || (sent && !window.confirm( 'Discard this retry request? It may already have been accepted. Refresh the experiment and inspect retry history before preparing another retry.' )) ) { return; } intentRef.current = null; setIntent(null); setSent(false); setError(''); setAmbiguous(false); }; return (
{freshAllowed && !intent && ( )} {accepted !== null && (

Retry {accepted} accepted for trial {number}. The current outcome may have advanced since acceptance.

)} {intent && (

Reviewed failed attempt {intent.input.expectedAttemptNumber} · prior manual retries{' '} {intent.input.expectedRetryCount} · progress {intent.progress}%

{intent.error ?? 'No error was recorded for this failure.'}

Retry keeps the same run, frozen dataset, strategy parameters, seed, costs and risk policy. Current eligibility is verified by the server.

{(!sameFailure || !freshAllowed) && (

The current trial state has changed. This request still targets the reviewed failure; it never starts a retry for a newer failure.

)} {sent && (

{ambiguous ? 'Acceptance is unconfirmed. ' : ''}The exact failure counters and submission key are retained. Retry the same request to recover its receipt.

)} {error && (

{error}

)}
)} {trial.runId && ( )} {historyOpen && trial.runId && (

Prior failures captured when manual retries were accepted. This is not a complete history of automatic recovery attempts.

{historyLoading &&

Loading retry history for trial {number}...

} {historyError && (

{historyError}

)} {history && history.length === 0 &&

No accepted manual retries for this trial.

} {history?.map(item => (

Retry {item.retryNumber} · previous attempt {item.previousAttemptNumber}

{item.error ?? 'No error was recorded for this failure.'}

Prior attempt ID
{item.previousAttemptId ?? 'No attempt ID was recorded.'}
Progress at failure
{item.progress}%
Simulation date
{item.currentDate ?? 'Not recorded'}
Started / completed / paused
{item.startedAt ?? 'Not recorded'} / {item.completedAt ?? 'Not recorded'} /{' '} {item.pausedAt ?? 'Not recorded'}
Failure last updated
{item.failureUpdatedAt}
Retry accepted
{item.recordedAt} · {item.principal}
Approval at retry admission
{item.reviewId ?? 'Unreviewed isolated candidate'}
))}
)}
); }