import { useCallback, useEffect, useRef, useState } from 'react'; import { Link, useParams } from 'react-router-dom'; import type { ExperimentTrial } from '@stock-bot/stock-config/experiments'; import { Button } from '@/components/ui/Button'; import { experimentFindingSource } from '@/features/research/services/findingSources'; import { useUnsavedWarning } from '@/hooks/useUnsavedWarning'; import { ExperimentCounts } from './components/ExperimentCounts'; import { ExperimentInputs } from './components/ExperimentInputs'; import { ExperimentTrialRecovery } from './components/ExperimentTrialRecovery'; import { RegimeEvidenceUnavailable } from './components/RegimeEvidenceUnavailable'; import { SourceFindingAction } from './components/SourceFindingAction'; import { metricText } from './components/trialMetricText'; import { experimentApi, type WorkbenchExperimentDetailView as Detail, } from './services/experimentApi'; export function ExperimentDetailPage() { const { experimentId = '' } = useParams<{ experimentId: string }>(); return ; } function ExperimentDetailView({ experimentId }: { experimentId: string }) { const [findingDirty, setFindingDirty] = useState(false); const alive = useRef(false); const pending = useRef(false); const reading = useRef(true); const generation = useRef(0); const readRequest = useRef(null); const [experiment, setExperiment] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(''); const [reload, setReload] = useState(0); const [cancelling, setCancelling] = useState(false); const [mutating, setMutating] = useState(false); const [retryIntents, setRetryIntents] = useState([]); useUnsavedWarning(retryIntents.length > 0); const onIntentChange = useCallback((trialKey: string, active: boolean) => { setRetryIntents(previous => active ? previous.includes(trialKey) ? previous : [...previous, trialKey] : previous.includes(trialKey) ? previous.filter(key => key !== trialKey) : previous ); }, []); useEffect(() => { alive.current = true; return () => { alive.current = false; generation.current++; readRequest.current?.abort(); }; }, []); useEffect(() => { if (pending.current) { return; } let current = true; const revision = ++generation.current; const controller = new AbortController(); readRequest.current = controller; reading.current = true; setLoading(true); setError(''); void experimentApi .get(experimentId, controller.signal) .then(value => { if (current && revision === generation.current) { setExperiment(value); } }) .catch(cause => { if (current && revision === generation.current) { setError(cause instanceof Error ? cause.message : 'Could not load experiment'); } }) .finally(() => { if (current && revision === generation.current) { reading.current = false; setLoading(false); } }); return () => { current = false; controller.abort(); }; }, [experimentId, reload]); const beginMutation = () => { if (pending.current || reading.current) { return false; } pending.current = true; generation.current++; readRequest.current?.abort(); setLoading(false); setMutating(true); setError(''); return true; }; const acceptMutation = (value: Detail) => { if (alive.current && value.id === experimentId) { setExperiment(value); } }; const endMutation = () => { pending.current = false; if (alive.current) { setMutating(false); } }; const cancel = async () => { if (!experiment || loading || !beginMutation()) { return; } setCancelling(true); setError(''); try { const value = await experimentApi.cancel(experimentId); acceptMutation(value); } catch (cause) { if (alive.current) { setError( `${cause instanceof Error ? cause.message : 'Could not request cancellation'}. Refresh to verify the saved state, or retry cancellation.` ); } } finally { endMutation(); if (alive.current) { setCancelling(false); } } }; const active = experiment && experiment.counts.pending + experiment.counts.running + experiment.counts.paused > 0; return (
{ const findingLink = (event.target as HTMLElement).closest('a'); if ( findingLink && (!findingLink.target || findingLink.target === '_self') && findingDirty && !event.ctrlKey && !event.metaKey && !event.shiftKey && !window.confirm( 'Leave this finding draft? The previous request may already have saved if its response was lost. Inspect saved records before submitting again.' ) ) { event.preventDefault(); event.stopPropagation(); return; } if ( (event.target as HTMLElement).closest('a') && retryIntents.length > 0 && !event.ctrlKey && !event.metaKey && !event.shiftKey && !window.confirm( 'Leave this retry review or unconfirmed retry? Its exact inputs and key will be discarded. You can inspect runs in another tab.' ) ) { event.preventDefault(); event.stopPropagation(); } }} > All experiments

{experiment?.name ?? 'Experiment'}

{loading &&

Loading experiment...

} {error && (

{error} {experiment && ' Showing the last loaded state; refresh to verify current status.'}

)} {experiment && ( <> 0} onDirtyChange={setFindingDirty} unavailable="Only explicitly standalone experiments can be cited here. Use the saved chronological or walk-forward report for validation evidence." />
Open saved backtest {active && !experiment.cancelRequested && ( )}

Every trial outcome

Rows retain{' '} {experiment.preview.version === 'cost-sensitivity-preview/v1' ? 'baseline/scenario' : 'grid'}{' '} order. Metrics come from saved results; unavailable, failed and incomparable outcomes remain visible. Returns and drawdowns are fractions. No cross-experiment ranking is applied.

{[ experiment.preview.version === 'cost-sensitivity-preview/v1' ? 'Scenario / costs / fixed parameters' : 'Trial / parameters', 'Status', 'Comparability', 'Total return', 'Max drawdown', 'Sharpe ratio', 'Diagnostics / run', ].map(label => ( ))} {experiment.trials.map(trial => ( ))}
{label}
{'costs' in trial ? trial.index === 0 ? 'Baseline' : `Scenario ${trial.index}` : `Trial ${trial.index + 1}`} {'costs' in trial && (

Fee rate: {trial.costs.feeRate} · Slippage rate:{' '} {trial.costs.slippageRate} (fractions)

)}
                          {JSON.stringify(trial.parameters, null, 2)}
                        
{trial.status}

{trial.status === 'missing' ? 'Child run missing' : `${trial.progress}% complete`}

{trial.cancelRequested &&

Cancellation requested

} {trial.runId && (

Attempt {trial.attemptNumber} · Manual retries {trial.retryCount}

)}
{trial.comparable ? 'Comparable' : trial.status === 'completed' ? 'Incomparable' : 'Not evaluated'} {metricText(trial, 'totalReturn')} {metricText(trial, 'maxDrawdown')} {metricText(trial, 'sharpeRatio')} {trial.error &&

{trial.error}

} {trial.diagnostic &&

{trial.diagnostic}

} {trial.limitations.map((limitation, index) => (

{limitation}

))} {!trial.metrics &&

Metrics unavailable

} {trial.metrics && (
All reported metrics
{Object.keys(trial.metrics).map(key => (
{key}
{metricText( trial, key as keyof NonNullable )}
))}
)} {trial.runId && ( Open trial {trial.index + 1} run )}
)}
); }