feat(research): add retained-input parameter sweep workbench

This commit is contained in:
Boki 2026-10-24 10:33:05 -04:00
parent 30accfcf43
commit 6f64ef62ba
41 changed files with 4469 additions and 34 deletions

View file

@ -0,0 +1,333 @@
import { useEffect, useRef, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { z } from 'zod';
import {
experimentInputSchema,
MAX_EXPERIMENT_TRIALS,
type ExperimentSubmission,
} from '@stock-bot/stock-config/experiments';
import { Button } from '@/components/ui/Button';
import { backtestApiV2, type Backtest } from '@/features/backtest/services/backtestApiV2';
import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning';
import {
experimentApi,
ExperimentApiError,
type ExperimentPreviewView,
} from '../services/experimentApi';
import { ExperimentInputs } from './ExperimentInputs';
const fieldClass =
'mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-text-primary disabled:opacity-60';
const message = (cause: unknown) =>
cause instanceof z.ZodError
? cause.issues.map(issue => `${issue.path.join('.') || 'Input'}: ${issue.message}`).join('; ')
: cause instanceof Error
? cause.message
: 'Could not prepare the experiment';
const canonical = (value: Backtest) =>
value &&
typeof value.id === 'string' &&
typeof value.name === 'string' &&
!value.archivedAt &&
value.strategyVersionId &&
value.config &&
typeof value.config.canonical === 'object' &&
value.config.canonical !== null &&
typeof value.config.datasetHash === 'string';
export function ExperimentEditor({
initialBacktestId,
onDirty,
}: {
initialBacktestId: string;
onDirty: (dirty: boolean) => void;
}) {
const navigate = useNavigate();
const alive = useRef(false);
const generation = useRef(0);
const previewRequest = useRef<AbortController | null>(null);
const pending = useRef(false);
const intent = useRef<{ body: ExperimentSubmission; key: string } | null>(null);
const [hasIntent, setHasIntent] = useState(false);
const [backtestId, setBacktestId] = useState(initialBacktestId);
const [name, setName] = useState('');
const [grid, setGrid] = useState('{}');
const [backtests, setBacktests] = useState<Backtest[]>([]);
const [templateLoading, setTemplateLoading] = useState(true);
const [templateError, setTemplateError] = useState('');
const [templateReload, setTemplateReload] = useState(0);
const [limit, setLimit] = useState(50);
const [moreTemplates, setMoreTemplates] = useState(false);
const [preview, setPreview] = useState<ExperimentPreviewView | null>(null);
const [previewLoading, setPreviewLoading] = useState(false);
const [error, setError] = useState('');
const [submitting, setSubmitting] = useState(false);
const [ambiguous, setAmbiguous] = useState(false);
const dirty = hasIntent || Boolean(name || grid !== '{}' || backtestId !== initialBacktestId);
useUnsavedWarning(dirty);
useEffect(() => {
onDirty(dirty);
}, [dirty, onDirty]);
useEffect(() => {
alive.current = true;
return () => {
alive.current = false;
generation.current++;
previewRequest.current?.abort();
};
}, []);
useEffect(() => {
let current = true;
const controller = new AbortController();
setTemplateLoading(true);
setTemplateError('');
void (async () => {
const rows = await backtestApiV2.listBacktests(limit, 0, false, controller.signal);
if (!Array.isArray(rows)) {
throw new Error('The saved backtest list could not be read');
}
const selected =
initialBacktestId && !rows.some(item => item?.id === initialBacktestId)
? await backtestApiV2.getBacktest(initialBacktestId)
: null;
if (current) {
setMoreTemplates(rows.length === limit);
setBacktests((selected ? [...rows, selected] : rows).filter(canonical));
}
})()
.catch(cause => {
if (current) {
setTemplateError(message(cause));
}
})
.finally(() => {
if (current) {
setTemplateLoading(false);
}
});
return () => {
current = false;
controller.abort();
};
}, [initialBacktestId, templateReload, limit]);
const invalidate = (change: () => void) => {
if (intent.current) {
return;
}
generation.current++;
previewRequest.current?.abort();
setPreview(null);
setPreviewLoading(false);
setError('');
change();
};
const prepare = async () => {
if (intent.current || previewLoading) {
return;
}
const current = ++generation.current;
previewRequest.current?.abort();
const controller = new AbortController();
previewRequest.current = controller;
setPreview(null);
setError('');
setPreviewLoading(true);
try {
const input = experimentInputSchema.parse({ backtestId, name, grid: JSON.parse(grid) });
const value = await experimentApi.preview(input, controller.signal);
if (alive.current && current === generation.current) {
setPreview(value);
}
} catch (cause) {
if (alive.current && current === generation.current) {
setError(message(cause));
}
} finally {
if (alive.current && current === generation.current) {
setPreviewLoading(false);
}
}
};
const submit = async () => {
if (pending.current || (!intent.current && !preview)) {
return;
}
if (!intent.current) {
if (!preview) {
return;
}
intent.current = {
key: crypto.randomUUID(),
body: { ...preview.input, previewHash: preview.previewHash },
};
}
const captured = intent.current;
pending.current = true;
setHasIntent(true);
setSubmitting(true);
setError('');
try {
const accepted = await experimentApi.create(captured.body, captured.key);
if (alive.current) {
intent.current = null;
setHasIntent(false);
navigate(`/experiments/${encodeURIComponent(accepted.id)}`);
}
} catch (cause) {
if (alive.current) {
setError(message(cause));
setAmbiguous(!(cause instanceof ExperimentApiError) || cause.ambiguous);
}
} finally {
pending.current = false;
if (alive.current) {
setSubmitting(false);
}
}
};
const newIntent = () => {
if (
pending.current ||
!window.confirm(
'Release this submission? If its response was lost, it may already exist. Check the experiment list before creating another.'
)
) {
return;
}
intent.current = null;
setHasIntent(false);
setAmbiguous(false);
setPreview(null);
setError('');
};
return (
<section
aria-label="Create experiment"
className="rounded-lg border border-border bg-surface p-4 space-y-4"
>
<h2 className="font-semibold text-text-primary">New parameter sweep</h2>
<p className="text-sm text-text-secondary">
Choose a saved canonical backtest and vary its strategy parameters. Preview validates every
combination before any trials are submitted.
</p>
{templateLoading && <p role="status">Loading saved backtests...</p>}
{templateError && (
<div role="alert">
{templateError}{' '}
<Button variant="outline" size="sm" onClick={() => setTemplateReload(value => value + 1)}>
Retry saved backtests
</Button>
</div>
)}
{!templateLoading && !templateError && backtests.length === 0 && (
<p>
No saved canonical backtests are available.{' '}
<Link className="text-primary-500" to="/backtests">
Configure a backtest
</Link>{' '}
with a retained dataset and strategy version.
</p>
)}
<div className="grid gap-4 sm:grid-cols-2 text-sm">
<label>
Saved backtest
<select
className={fieldClass}
value={backtestId}
disabled={hasIntent || templateLoading}
onChange={event => invalidate(() => setBacktestId(event.target.value))}
>
<option value="">Select a saved canonical backtest</option>
{initialBacktestId && !backtests.some(item => item.id === initialBacktestId) && (
<option value={initialBacktestId}>Selected backtest is unavailable</option>
)}
{backtests.map(item => (
<option key={item.id} value={item.id}>
{item.name}
</option>
))}
</select>
</label>
<label>
Experiment name
<input
className={fieldClass}
value={name}
disabled={hasIntent}
onChange={event => invalidate(() => setName(event.target.value))}
/>
</label>
</div>
{moreTemplates && (
<Button
variant="outline"
size="sm"
disabled={templateLoading || hasIntent}
onClick={() => setLimit(value => value + 50)}
>
Load more backtests
</Button>
)}
<label className="block text-sm">
Parameter grid (JSON)
<textarea
className={`${fieldClass} font-mono`}
rows={4}
value={grid}
disabled={hasIntent}
onChange={event => invalidate(() => setGrid(event.target.value))}
aria-describedby="experiment-grid-help"
/>
</label>
<p id="experiment-grid-help" className="text-xs text-text-secondary">
Use parameter names from the selected strategy with arrays of values, e.g.{' '}
{'{"fastPeriod":[5,10],"slowPeriod":[20,30]}'}. All combinations must be valid. {'{}'} runs
the unchanged parameters once. Maximum {MAX_EXPERIMENT_TRIALS} trials per experiment; this
does not promise concurrent execution.
</p>
<Button
variant="outline"
disabled={
hasIntent ||
previewLoading ||
!backtests.some(item => item.id === backtestId) ||
!name.trim()
}
onClick={() => void prepare()}
>
Preview experiment
</Button>
{previewLoading && <p role="status">Validating experiment inputs...</p>}
{preview && <ExperimentInputs preview={preview} />}
{error && (
<p role="alert" className="text-error">
{error}
</p>
)}
{hasIntent && (
<p role="status" className="text-sm text-text-secondary">
{ambiguous ? 'Acceptance is unconfirmed. ' : ''}This submission keeps its exact inputs and
key. Retry to recover the same experiment; check saved experiments before starting
another.
</p>
)}
{(preview || hasIntent) && (
<div className="flex flex-wrap gap-2">
<Button disabled={submitting} onClick={() => void submit()}>
{submitting
? 'Submitting experiment...'
: hasIntent
? 'Retry experiment submission'
: 'Confirm experiment'}
</Button>
{hasIntent && (
<Button variant="outline" disabled={submitting} onClick={newIntent}>
Start new experiment
</Button>
)}
</div>
)}
</section>
);
}