import { useEffect, useRef, useState } from 'react'; import { Link, useParams } from 'react-router-dom'; import type { WalkForwardReceipt } from '@stock-bot/stock-config/walk-forward'; import { Button } from '@/components/ui/Button'; import { walkForwardFindingSource } from '@/features/research/services/findingSources'; import { useUnsavedWarning } from '@/hooks/useUnsavedWarning'; import { RegimeEvidenceUnavailable } from './components/RegimeEvidenceUnavailable'; import { SourceFindingAction } from './components/SourceFindingAction'; import { ValidationEvidence } from './components/ValidationEvidence'; import { walkForwardApi, WalkForwardApiError, type WalkForwardDetailView, } from './services/walkForwardApi'; export function WalkForwardDetailPage() { const { walkForwardId = '' } = useParams<{ walkForwardId: string }>(); return ; } type Intent = { id: string; body: { previewHash: string }; key: string }; function WalkForwardDetail({ walkForwardId }: { walkForwardId: string }) { const [findingDirty, setFindingDirty] = useState(false); const alive = useRef(false), pending = useRef(false), reading = useRef(true), generation = useRef(0), read = useRef(null), captured = useRef(null); const [value, setValue] = useState(null), [intent, setIntent] = useState(null), [receipt, setReceipt] = useState(null); const [loading, setLoading] = useState(true), [busy, setBusy] = useState(false), [reload, setReload] = useState(0), [readError, setReadError] = useState(''), [actionError, setActionError] = useState(''), [ambiguous, setAmbiguous] = useState(false); useUnsavedWarning(Boolean(intent)); useEffect(() => { alive.current = true; return () => { alive.current = false; generation.current++; read.current?.abort(); }; }, []); useEffect(() => { if (pending.current) { return; } let current = true; const revision = ++generation.current, controller = new AbortController(); read.current = controller; reading.current = true; setLoading(true); setReadError(''); void walkForwardApi .get(walkForwardId, controller.signal) .then(result => { if (current && revision === generation.current) { setValue(result); } }) .catch(cause => { if (current && revision === generation.current) { setReadError( cause instanceof Error ? cause.message : 'Could not load walk-forward validation' ); } }) .finally(() => { if (current && revision === generation.current) { reading.current = false; setLoading(false); } }); return () => { current = false; controller.abort(); }; }, [walkForwardId, reload]); const begin = () => { if (pending.current || reading.current) { return false; } pending.current = true; generation.current++; read.current?.abort(); setBusy(true); setActionError(''); return true; }; const finish = () => { pending.current = false; if (alive.current) { setBusy(false); } }; const finalize = async () => { if (pending.current || reading.current || !value) { return; } if (!captured.current) { if (!value.actions.finalize.available) { return; } captured.current = { id: walkForwardId, body: { previewHash: value.previewHash }, key: crypto.randomUUID(), }; setIntent(captured.current); setReceipt(null); } const original = captured.current; if (!begin()) { return; } try { const result = await walkForwardApi.finalize(original.id, original.body, original.key); if (alive.current) { captured.current = null; setIntent(null); setReceipt(result.receipt); setValue(result.walkForward); setAmbiguous(false); } } catch (cause) { if (alive.current) { setActionError( cause instanceof Error ? cause.message : 'Could not save walk-forward report' ); setAmbiguous(!(cause instanceof WalkForwardApiError) || cause.ambiguous); } } finally { finish(); } }; const cancel = async () => { if (!value || !begin()) { return; } try { const result = await walkForwardApi.cancel(walkForwardId); if (alive.current) { setValue(result); } } catch (cause) { if (alive.current) { setActionError( `${cause instanceof Error ? cause.message : 'Cancellation failed'}. Refresh to verify cancellation or retry the request.` ); } } finally { finish(); } }; const discard = () => { if ( pending.current || !window.confirm( 'Discard this report request? It may already have succeeded. Refresh the saved walk-forward validation before preparing another action.' ) ) { return; } captured.current = null; setIntent(null); setActionError(''); setAmbiguous(false); }; 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') && captured.current && !event.ctrlKey && !event.metaKey && !event.shiftKey && !window.confirm( 'Leave this unconfirmed walk-forward report request? Its exact body and key will be discarded. You can inspect evidence in another tab.' ) ) { event.preventDefault(); event.stopPropagation(); } }} > All experiments

{value?.name ?? 'Walk-forward validation'}

{loading &&

Loading walk-forward validation...

} {readError && (

{readError} {value && ' Showing the last loaded state.'}

)} {actionError && (

{actionError}

)} {intent && (

{ambiguous ? 'Report acceptance is unconfirmed. ' : ''}This request retains its exact walk-forward identity, preview and key.

{' '}
)} {receipt && (

Walk-forward report accepted. Receipt {receipt.id} · {receipt.createdAt}

)} {value && ( <> {!value.report && ( )}

{value.report ? 'Execution complete · walk-forward report saved' : 'Window validations admitted · walk-forward report not yet saved'}

{value.reportedWindowCount}/{value.windowCount} window reports saved ·{' '} {value.trainingRunCount} training runs · {value.plannedRunCount} total planned runs, including future holdouts.

Each phase and window resets initial capital and positions. These are ordered independent reset segments, not a continuous portfolio equity curve. No returns are compounded and no window metrics are averaged.

{value.cancelRequested && (

Cancellation requested for all windows. Completed evidence remains retained; active work may still finish.

)}
{!intent && !value.report && ( )}
{!value.report && value.actions.finalize.reason &&

{value.actions.finalize.reason}

}

Window progress and evidence

{value.windows.map(member => (

Window {member.index + 1}

Open window {member.index + 1} validation {member.status === 'missing' ? (

Window {member.index + 1} validation is missing. Its outcome has not been omitted.

) : ( <>

{member.validation?.report ? 'Window report saved' : member.validation?.selection ? 'Fixed winner selected · validation and test admitted' : 'Training candidates admitted · selection not yet frozen'}

{member.validation?.cancelRequested && (

Cancellation requested for this window.

)} {member.validation?.phases.map(phase => (

{phase.phase}:{' '} {phase.status === 'not-admitted' ? 'Not admitted' : phase.status === 'missing' ? 'Experiment missing' : phase.experiment ? `${phase.experiment.counts.completed} completed, ${phase.experiment.counts.failed} failed, ${phase.experiment.counts.cancelled} cancelled, ${phase.experiment.counts.pending} pending, ${phase.experiment.counts.running} running, ${phase.experiment.counts.paused} paused` : 'Unavailable'}

{phase.experiment && phase.experiment.trials .filter( trial => trial.status === 'missing' || trial.error || (trial.status === 'completed' && !trial.comparable) ) .map(trial => (

Candidate {trial.index + 1}: {trial.status};{' '} {trial.error ?? trial.diagnostic ?? 'Evidence unavailable'}

))}
))} )}
))}
Frozen walk-forward inputs
              {JSON.stringify(value.preview, null, 2)}
            
{value.report && (

Saved walk-forward report

Report {value.report.id} · {value.report.createdAt} · Hash {value.report.reportHash}

{value.report.limitations.map((limitation, index) => (

{limitation}

))} {value.report.segments.map(segment => (

Window {segment.index + 1} reset segment

Window report {segment.reportId} · {segment.reportHash}

Selection {segment.selectionHash}

))}
Exact retained walk-forward report
                  {JSON.stringify(value.report, null, 2)}
                
)} )}
); }