371 lines
14 KiB
TypeScript
371 lines
14 KiB
TypeScript
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 <ExperimentDetailView key={experimentId} experimentId={experimentId} />;
|
|
}
|
|
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<AbortController | null>(null);
|
|
const [experiment, setExperiment] = useState<Detail | null>(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<string[]>([]);
|
|
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 (
|
|
<div
|
|
className="h-full overflow-auto space-y-5 p-1"
|
|
onClickCapture={event => {
|
|
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();
|
|
}
|
|
}}
|
|
>
|
|
<Link className="text-primary-500 text-sm" to="/experiments">
|
|
All experiments
|
|
</Link>
|
|
<div className="flex flex-wrap items-center justify-between gap-3">
|
|
<h1 className="text-lg font-bold">{experiment?.name ?? 'Experiment'}</h1>
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
disabled={loading || mutating}
|
|
onClick={() => {
|
|
if (!pending.current && !reading.current) {
|
|
reading.current = true;
|
|
generation.current++;
|
|
readRequest.current?.abort();
|
|
setReload(value => value + 1);
|
|
}
|
|
}}
|
|
>
|
|
Refresh experiment
|
|
</Button>
|
|
</div>
|
|
{loading && <p role="status">Loading experiment...</p>}
|
|
{error && (
|
|
<p role="alert" className="text-error">
|
|
{error}
|
|
{experiment && ' Showing the last loaded state; refresh to verify current status.'}
|
|
</p>
|
|
)}
|
|
{experiment && (
|
|
<>
|
|
<ExperimentCounts experiment={experiment} />
|
|
<RegimeEvidenceUnavailable />
|
|
<SourceFindingAction
|
|
key={`experiment:${experiment.id}:${experiment.previewHash}`}
|
|
source={experimentFindingSource(experiment)}
|
|
disabled={loading || mutating || retryIntents.length > 0}
|
|
onDirtyChange={setFindingDirty}
|
|
unavailable="Only explicitly standalone experiments can be cited here. Use the saved chronological or walk-forward report for validation evidence."
|
|
/>
|
|
<div className="flex flex-wrap items-center gap-4">
|
|
<Link
|
|
className="text-primary-500 text-sm"
|
|
to={`/backtests/${encodeURIComponent(experiment.backtestId)}`}
|
|
>
|
|
Open saved backtest
|
|
</Link>
|
|
{active && !experiment.cancelRequested && (
|
|
<Button
|
|
variant="danger"
|
|
size="sm"
|
|
disabled={mutating || loading}
|
|
onClick={() => void cancel()}
|
|
>
|
|
{cancelling ? 'Requesting cancellation...' : 'Cancel remaining trials'}
|
|
</Button>
|
|
)}
|
|
</div>
|
|
<ExperimentInputs preview={experiment.preview} />
|
|
<section aria-label="Experiment trial outcomes" className="space-y-2">
|
|
<h2 className="font-semibold">Every trial outcome</h2>
|
|
<p className="text-sm text-text-secondary">
|
|
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.
|
|
</p>
|
|
<div className="overflow-x-auto">
|
|
<table className="w-full text-sm text-left">
|
|
<thead>
|
|
<tr>
|
|
{[
|
|
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 => (
|
|
<th key={label} className="p-2 border-b border-border whitespace-nowrap">
|
|
{label}
|
|
</th>
|
|
))}
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{experiment.trials.map(trial => (
|
|
<tr key={trial.trialKey} className="align-top">
|
|
<td className="p-2 border-b border-border">
|
|
<span>
|
|
{'costs' in trial
|
|
? trial.index === 0
|
|
? 'Baseline'
|
|
: `Scenario ${trial.index}`
|
|
: `Trial ${trial.index + 1}`}
|
|
</span>
|
|
{'costs' in trial && (
|
|
<p className="text-xs">
|
|
Fee rate: {trial.costs.feeRate} · Slippage rate:{' '}
|
|
{trial.costs.slippageRate} (fractions)
|
|
</p>
|
|
)}
|
|
<pre className="whitespace-pre-wrap text-xs">
|
|
{JSON.stringify(trial.parameters, null, 2)}
|
|
</pre>
|
|
</td>
|
|
<td className="p-2 border-b border-border">
|
|
{trial.status}
|
|
<p className="text-xs">
|
|
{trial.status === 'missing'
|
|
? 'Child run missing'
|
|
: `${trial.progress}% complete`}
|
|
</p>
|
|
{trial.cancelRequested && <p className="text-xs">Cancellation requested</p>}
|
|
{trial.runId && (
|
|
<p className="text-xs">
|
|
Attempt {trial.attemptNumber} · Manual retries {trial.retryCount}
|
|
</p>
|
|
)}
|
|
</td>
|
|
<td className="p-2 border-b border-border">
|
|
{trial.comparable
|
|
? 'Comparable'
|
|
: trial.status === 'completed'
|
|
? 'Incomparable'
|
|
: 'Not evaluated'}
|
|
</td>
|
|
<td className="p-2 border-b border-border">
|
|
{metricText(trial, 'totalReturn')}
|
|
</td>
|
|
<td className="p-2 border-b border-border">
|
|
{metricText(trial, 'maxDrawdown')}
|
|
</td>
|
|
<td className="p-2 border-b border-border">
|
|
{metricText(trial, 'sharpeRatio')}
|
|
</td>
|
|
<td className="p-2 border-b border-border min-w-56 space-y-2">
|
|
{trial.error && <p className="text-error">{trial.error}</p>}
|
|
{trial.diagnostic && <p>{trial.diagnostic}</p>}
|
|
{trial.limitations.map((limitation, index) => (
|
|
<p key={index}>{limitation}</p>
|
|
))}
|
|
{!trial.metrics && <p>Metrics unavailable</p>}
|
|
{trial.metrics && (
|
|
<details>
|
|
<summary className="cursor-pointer">All reported metrics</summary>
|
|
<dl>
|
|
{Object.keys(trial.metrics).map(key => (
|
|
<div key={key}>
|
|
<dt>{key}</dt>
|
|
<dd>
|
|
{metricText(
|
|
trial,
|
|
key as keyof NonNullable<ExperimentTrial['metrics']>
|
|
)}
|
|
</dd>
|
|
</div>
|
|
))}
|
|
</dl>
|
|
</details>
|
|
)}
|
|
{trial.runId && (
|
|
<Link
|
|
className="text-primary-500"
|
|
to={`/backtests/${encodeURIComponent(experiment.backtestId)}/run/${encodeURIComponent(trial.runId)}`}
|
|
>
|
|
Open trial {trial.index + 1} run
|
|
</Link>
|
|
)}
|
|
<ExperimentTrialRecovery
|
|
experimentId={experiment.id}
|
|
backtestId={experiment.backtestId}
|
|
previewHash={experiment.previewHash}
|
|
strategyOrigin={experiment.preview.request.strategy.origin}
|
|
experimentCancelled={experiment.cancelRequested}
|
|
trial={trial}
|
|
disabled={mutating || loading}
|
|
beginMutation={beginMutation}
|
|
acceptMutation={acceptMutation}
|
|
endMutation={endMutation}
|
|
onIntentChange={onIntentChange}
|
|
/>
|
|
</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</section>
|
|
</>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|