refactor: share research domain and simplify application workflows
This commit is contained in:
parent
805a9f8fd4
commit
8c39ccf7ea
58 changed files with 3805 additions and 3081 deletions
|
|
@ -5,29 +5,10 @@
|
|||
*/
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { CanonicalRunCapability } from '@stock-bot/stock-config/canonical-research';
|
||||
import { catalogExecutionReason } from '@/features/strategies/components/StrategySelection';
|
||||
import { backtestApiV2, RunResultsUnavailableError } from '../services/backtestApiV2';
|
||||
import type {
|
||||
Backtest,
|
||||
CreateBacktestRequest,
|
||||
ResearchRunResult,
|
||||
Run,
|
||||
} from '../services/backtestApiV2';
|
||||
|
||||
/** Object identity is the ownership token for one status/result request chain. */
|
||||
interface RunSelection {
|
||||
id: string;
|
||||
backtestId: string | null;
|
||||
controller: AbortController;
|
||||
timer?: ReturnType<typeof setTimeout>;
|
||||
request?: Promise<void>;
|
||||
refreshRequested: boolean;
|
||||
results: ResearchRunResult | null;
|
||||
}
|
||||
|
||||
const isActive = (run: Run) => ['pending', 'running', 'paused'].includes(run.status);
|
||||
const messageOf = (error: unknown, fallback: string) =>
|
||||
error instanceof Error ? error.message : fallback;
|
||||
import { backtestApiV2 } from '../services/backtestApiV2';
|
||||
import type { Backtest, CreateBacktestRequest, Run } from '../services/backtestApiV2';
|
||||
import { messageOf, useRunMonitoring } from './useRunMonitoring';
|
||||
import { useRunSubmission } from './useRunSubmission';
|
||||
|
||||
/**
|
||||
* Connects BacktestDetailPageV2 to backtestApiV2. Template loading, run monitoring
|
||||
|
|
@ -37,32 +18,14 @@ const messageOf = (error: unknown, fallback: string) =>
|
|||
export function useBacktestV2() {
|
||||
const [backtest, setBacktest] = useState<Backtest | null>(null);
|
||||
const [runs, setRuns] = useState<Run[]>([]);
|
||||
const [currentRun, setCurrentRun] = useState<Run | null>(null);
|
||||
const [runResults, setRunResults] = useState<ResearchRunResult | null>(null);
|
||||
const [isBacktestLoading, setIsBacktestLoading] = useState(false);
|
||||
const [isRunLoading, setIsRunLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [runError, setRunError] = useState<string | null>(null);
|
||||
const [submissionError, setSubmissionError] = useState<string | null>(null);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [cancelRequested, setCancelRequested] = useState(false);
|
||||
// Generations reject late responses even when an earlier request cannot be
|
||||
// aborted. The selection generation also prevents submission from taking the
|
||||
// user away from a different run they selected while admission was pending.
|
||||
const mounted = useRef(true);
|
||||
const backtestGeneration = useRef(0);
|
||||
const loadedBacktestId = useRef<string | null>(null);
|
||||
const selectionGeneration = useRef(0);
|
||||
// The intent survives an ambiguous response and configuration edits. Only an
|
||||
// acknowledged submission (or leaving this definition) releases its key.
|
||||
const submission = useRef<{
|
||||
backtestId: string;
|
||||
key: string;
|
||||
body: { speedMultiplier: number | null };
|
||||
pending: boolean;
|
||||
} | null>(null);
|
||||
const selection = useRef<RunSelection | null>(null);
|
||||
const cancellation = useRef<RunSelection | null>(null);
|
||||
const [capabilityRetry, setCapabilityRetry] = useState(0);
|
||||
const [capabilityState, setCapabilityState] = useState<{
|
||||
definition: Backtest;
|
||||
|
|
@ -119,172 +82,36 @@ export function useBacktestV2() {
|
|||
catalog && !backtest?.archivedAt && !capabilityError && canonicalCapability === null;
|
||||
const refreshCanonicalCapability = useCallback(() => setCapabilityRetry(value => value + 1), []);
|
||||
|
||||
const isSelected = useCallback(
|
||||
(selected: RunSelection) =>
|
||||
mounted.current &&
|
||||
selection.current === selected &&
|
||||
selected.backtestId === loadedBacktestId.current,
|
||||
[]
|
||||
);
|
||||
|
||||
/** Stop browser observation only; cancelling server execution is cancelRun's job. */
|
||||
const stopMonitoring = useCallback(() => {
|
||||
selectionGeneration.current++;
|
||||
const selected = selection.current;
|
||||
selection.current = null;
|
||||
cancellation.current = null;
|
||||
if (selected) {
|
||||
clearTimeout(selected.timer);
|
||||
selected.controller.abort();
|
||||
}
|
||||
}, []);
|
||||
|
||||
// A selection owns one request chain (status, then results) and one timer.
|
||||
// Polls, websocket invalidations and cancel acknowledgements all use this path.
|
||||
const refreshSelection = useCallback(
|
||||
function refresh(selected: RunSelection): Promise<void> {
|
||||
if (!isSelected(selected)) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
if (selected.request) {
|
||||
selected.refreshRequested = true;
|
||||
return selected.request;
|
||||
}
|
||||
clearTimeout(selected.timer);
|
||||
let monitorAgain = true;
|
||||
selected.request = (async () => {
|
||||
try {
|
||||
const run = await backtestApiV2.getRun(selected.id, selected.controller.signal);
|
||||
if (!isSelected(selected)) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
run.id !== selected.id ||
|
||||
(selected.backtestId !== null && run.backtestId !== selected.backtestId)
|
||||
) {
|
||||
monitorAgain = false;
|
||||
selected.refreshRequested = false;
|
||||
selected.results = null;
|
||||
setCurrentRun(null);
|
||||
setRunResults(null);
|
||||
throw new Error('Received a run for a different backtest or run selection');
|
||||
}
|
||||
|
||||
setCurrentRun(run);
|
||||
setRuns(previous =>
|
||||
previous.some(item => item.id === run.id)
|
||||
? previous.map(item => (item.id === run.id ? run : item))
|
||||
: [run, ...previous]
|
||||
);
|
||||
setRunError(null);
|
||||
monitorAgain = isActive(run);
|
||||
if (!monitorAgain) {
|
||||
cancellation.current = null;
|
||||
setCancelRequested(false);
|
||||
} else if (run.cancelRequested) {
|
||||
setCancelRequested(true);
|
||||
}
|
||||
|
||||
if (run.status === 'completed') {
|
||||
if (!selected.results) {
|
||||
const results = await backtestApiV2.getRunResults(
|
||||
selected.id,
|
||||
selected.controller.signal
|
||||
);
|
||||
if (!isSelected(selected)) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
results &&
|
||||
(results.runId !== selected.id || results.backtestId !== run.backtestId)
|
||||
) {
|
||||
selected.refreshRequested = false;
|
||||
throw new Error('Received results for a different backtest or run');
|
||||
}
|
||||
selected.results = results;
|
||||
setRunResults(results);
|
||||
}
|
||||
} else {
|
||||
selected.results = null;
|
||||
setRunResults(null);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!isSelected(selected)) {
|
||||
return;
|
||||
}
|
||||
setRunError(
|
||||
err instanceof RunResultsUnavailableError
|
||||
? null
|
||||
: messageOf(err, 'Failed to refresh run')
|
||||
);
|
||||
} finally {
|
||||
if (isSelected(selected)) {
|
||||
selected.request = undefined;
|
||||
setIsRunLoading(false);
|
||||
if (selected.refreshRequested) {
|
||||
selected.refreshRequested = false;
|
||||
void refresh(selected);
|
||||
} else if (monitorAgain) {
|
||||
selected.timer = setTimeout(() => void refresh(selected), 1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
})();
|
||||
return selected.request;
|
||||
},
|
||||
[isSelected]
|
||||
);
|
||||
|
||||
const refreshRun = useCallback(
|
||||
(runId?: string) => {
|
||||
const selected = selection.current;
|
||||
return selected && (!runId || selected.id === runId)
|
||||
? refreshSelection(selected)
|
||||
: Promise.resolve();
|
||||
},
|
||||
[refreshSelection]
|
||||
);
|
||||
|
||||
/** Reopening a run reads its recorded state; it never submits another backtest. */
|
||||
const selectRun = useCallback(
|
||||
(runId: string | undefined) => {
|
||||
if (
|
||||
runId &&
|
||||
selection.current?.id === runId &&
|
||||
selection.current.backtestId === loadedBacktestId.current
|
||||
) {
|
||||
return refreshSelection(selection.current);
|
||||
}
|
||||
stopMonitoring();
|
||||
setCurrentRun(null);
|
||||
setRunResults(null);
|
||||
setRunError(null);
|
||||
setCancelRequested(false);
|
||||
setIsRunLoading(Boolean(runId));
|
||||
if (!runId) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
const selected: RunSelection = {
|
||||
id: runId,
|
||||
backtestId: loadedBacktestId.current,
|
||||
controller: new AbortController(),
|
||||
refreshRequested: false,
|
||||
results: null,
|
||||
};
|
||||
selection.current = selected;
|
||||
return refreshSelection(selected);
|
||||
},
|
||||
[refreshSelection, stopMonitoring]
|
||||
);
|
||||
const {
|
||||
currentRun,
|
||||
runResults,
|
||||
isRunLoading,
|
||||
runError,
|
||||
cancelRequested,
|
||||
selection,
|
||||
selectionGeneration,
|
||||
stopMonitoring,
|
||||
refreshRun,
|
||||
selectRun,
|
||||
cancelRun,
|
||||
} = useRunMonitoring({ mounted, loadedBacktestId, setRuns });
|
||||
const { createRun, submissionError, isSubmitting, hasPendingSubmission, resetSubmission } =
|
||||
useRunSubmission({
|
||||
backtest,
|
||||
loadedBacktestId,
|
||||
mounted,
|
||||
selectionGeneration,
|
||||
catalog,
|
||||
canonicalCapability,
|
||||
capabilityError,
|
||||
setRuns,
|
||||
});
|
||||
|
||||
const loadBacktest = useCallback(
|
||||
async (id: string) => {
|
||||
const generation = ++backtestGeneration.current;
|
||||
if (loadedBacktestId.current !== id) {
|
||||
submission.current = null;
|
||||
setSubmissionError(null);
|
||||
setIsSubmitting(false);
|
||||
resetSubmission();
|
||||
// Parent-only route changes do not rerun the page's runId effect. Fence
|
||||
// the old request chain and validate the same selection against its new parent.
|
||||
loadedBacktestId.current = id;
|
||||
|
|
@ -325,7 +152,7 @@ export function useBacktestV2() {
|
|||
}
|
||||
}
|
||||
},
|
||||
[selectRun]
|
||||
[selectRun, resetSubmission]
|
||||
);
|
||||
|
||||
const createBacktest = useCallback(
|
||||
|
|
@ -337,9 +164,7 @@ export function useBacktestV2() {
|
|||
const created = await backtestApiV2.createBacktest(request);
|
||||
if (mounted.current && generation === backtestGeneration.current) {
|
||||
loadedBacktestId.current = created.id;
|
||||
submission.current = null;
|
||||
setSubmissionError(null);
|
||||
setIsSubmitting(false);
|
||||
resetSubmission();
|
||||
setBacktest(created);
|
||||
setRuns([]);
|
||||
await selectRun(undefined);
|
||||
|
|
@ -356,7 +181,7 @@ export function useBacktestV2() {
|
|||
}
|
||||
}
|
||||
},
|
||||
[selectRun]
|
||||
[selectRun, resetSubmission]
|
||||
);
|
||||
|
||||
const updateBacktest = useCallback(
|
||||
|
|
@ -395,9 +220,7 @@ export function useBacktestV2() {
|
|||
await backtestApiV2.deleteBacktest(id);
|
||||
if (mounted.current && generation === backtestGeneration.current) {
|
||||
loadedBacktestId.current = null;
|
||||
submission.current = null;
|
||||
setSubmissionError(null);
|
||||
setIsSubmitting(false);
|
||||
resetSubmission();
|
||||
setBacktest(null);
|
||||
setRuns([]);
|
||||
await selectRun(undefined);
|
||||
|
|
@ -413,7 +236,7 @@ export function useBacktestV2() {
|
|||
}
|
||||
}
|
||||
},
|
||||
[selectRun]
|
||||
[selectRun, resetSubmission]
|
||||
);
|
||||
|
||||
const setBacktestArchived = useCallback(async (id: string, archived: boolean) => {
|
||||
|
|
@ -437,103 +260,6 @@ export function useBacktestV2() {
|
|||
}
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Retain the same key/body after an ambiguous response so Retry can recover
|
||||
* the accepted run. This receipt is in memory for this mounted hook; it is not
|
||||
* a persistent browser recovery journal. New admissions recheck eligibility;
|
||||
* receipt retries recover the original run before current eligibility checks.
|
||||
*/
|
||||
const createRun = useCallback(
|
||||
async (_speedMultiplier: number | null = null) => {
|
||||
if (!backtest || backtest.id !== loadedBacktestId.current || submission.current?.pending) {
|
||||
return undefined;
|
||||
}
|
||||
if (backtest.archivedAt && !submission.current) {
|
||||
setSubmissionError('Restore this archived backtest before starting a new run.');
|
||||
return undefined;
|
||||
}
|
||||
if (catalog && !canonicalCapability?.available && !submission.current) {
|
||||
setSubmissionError(
|
||||
capabilityError ?? canonicalCapability?.reason ?? catalogExecutionReason
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
if (!catalog && !submission.current) {
|
||||
setSubmissionError(
|
||||
'Legacy execution is retired. Create a catalog backtest to run with retained canonical inputs.'
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
const intent = (submission.current ??= {
|
||||
backtestId: backtest.id,
|
||||
key: crypto.randomUUID(),
|
||||
body: { speedMultiplier: null },
|
||||
pending: false,
|
||||
});
|
||||
intent.pending = true;
|
||||
const selectedGeneration = selectionGeneration.current;
|
||||
const ownsSubmission = () => mounted.current && submission.current === intent;
|
||||
const ownsSelection = () =>
|
||||
ownsSubmission() && selectionGeneration.current === selectedGeneration;
|
||||
setIsSubmitting(true);
|
||||
setSubmissionError(null);
|
||||
try {
|
||||
const created = await backtestApiV2.createRun(intent.backtestId, intent.body, intent.key);
|
||||
if (!ownsSubmission()) {
|
||||
return undefined;
|
||||
}
|
||||
const selected = ownsSelection();
|
||||
submission.current = null;
|
||||
setIsSubmitting(false);
|
||||
if (!selected) {
|
||||
return undefined;
|
||||
}
|
||||
setRuns(previous => [created, ...previous.filter(run => run.id !== created.id)]);
|
||||
return created;
|
||||
} catch (err) {
|
||||
if (ownsSubmission()) {
|
||||
setSubmissionError(messageOf(err, 'Failed to submit run'));
|
||||
}
|
||||
return undefined;
|
||||
} finally {
|
||||
intent.pending = false;
|
||||
if (ownsSubmission()) {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[backtest, catalog, canonicalCapability, capabilityError]
|
||||
);
|
||||
|
||||
/** Record a cancellation request, then monitor until the server reports a terminal state. */
|
||||
const cancelRun = useCallback(async () => {
|
||||
const selected = selection.current;
|
||||
if (
|
||||
!selected ||
|
||||
!currentRun ||
|
||||
currentRun.id !== selected.id ||
|
||||
!isActive(currentRun) ||
|
||||
cancellation.current === selected
|
||||
) {
|
||||
return;
|
||||
}
|
||||
cancellation.current = selected;
|
||||
setCancelRequested(true);
|
||||
setRunError(null);
|
||||
try {
|
||||
await backtestApiV2.cancelRun(selected.id, selected.controller.signal);
|
||||
if (isSelected(selected)) {
|
||||
await refreshSelection(selected);
|
||||
}
|
||||
} catch (err) {
|
||||
if (isSelected(selected)) {
|
||||
cancellation.current = null;
|
||||
setCancelRequested(Boolean(currentRun.cancelRequested));
|
||||
setRunError(messageOf(err, 'Failed to request cancellation'));
|
||||
}
|
||||
}
|
||||
}, [currentRun, isSelected, refreshSelection]);
|
||||
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
return () => {
|
||||
|
|
@ -556,7 +282,7 @@ export function useBacktestV2() {
|
|||
error: runError ?? error,
|
||||
submissionError,
|
||||
isSubmitting,
|
||||
hasPendingSubmission: submission.current !== null,
|
||||
hasPendingSubmission,
|
||||
cancelRequested,
|
||||
loadBacktest,
|
||||
createBacktest,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,250 @@
|
|||
import {
|
||||
useCallback,
|
||||
useRef,
|
||||
useState,
|
||||
type Dispatch,
|
||||
type MutableRefObject,
|
||||
type SetStateAction,
|
||||
} from 'react';
|
||||
import {
|
||||
backtestApiV2,
|
||||
RunResultsUnavailableError,
|
||||
type ResearchRunResult,
|
||||
type Run,
|
||||
} from '../services/backtestApiV2';
|
||||
|
||||
/** Object identity is the ownership token for one status/result request chain. */
|
||||
export interface RunSelection {
|
||||
id: string;
|
||||
backtestId: string | null;
|
||||
controller: AbortController;
|
||||
timer?: ReturnType<typeof setTimeout>;
|
||||
request?: Promise<void>;
|
||||
refreshRequested: boolean;
|
||||
results: ResearchRunResult | null;
|
||||
}
|
||||
|
||||
const isActive = (run: Run) => ['pending', 'running', 'paused'].includes(run.status);
|
||||
export const messageOf = (error: unknown, fallback: string) =>
|
||||
error instanceof Error ? error.message : fallback;
|
||||
|
||||
/** One selection owns status, results, polling, refresh and cancellation. */
|
||||
export function useRunMonitoring({
|
||||
mounted,
|
||||
loadedBacktestId,
|
||||
setRuns,
|
||||
}: {
|
||||
mounted: MutableRefObject<boolean>;
|
||||
loadedBacktestId: MutableRefObject<string | null>;
|
||||
setRuns: Dispatch<SetStateAction<Run[]>>;
|
||||
}) {
|
||||
const [currentRun, setCurrentRun] = useState<Run | null>(null);
|
||||
const [runResults, setRunResults] = useState<ResearchRunResult | null>(null);
|
||||
const [isRunLoading, setIsRunLoading] = useState(false);
|
||||
const [runError, setRunError] = useState<string | null>(null);
|
||||
const [cancelRequested, setCancelRequested] = useState(false);
|
||||
const selectionGeneration = useRef(0);
|
||||
const selection = useRef<RunSelection | null>(null);
|
||||
const cancellation = useRef<RunSelection | null>(null);
|
||||
const isSelected = useCallback(
|
||||
(selected: RunSelection) =>
|
||||
mounted.current &&
|
||||
selection.current === selected &&
|
||||
selected.backtestId === loadedBacktestId.current,
|
||||
[]
|
||||
);
|
||||
|
||||
/** Stop browser observation only; cancelling server execution is cancelRun's job. */
|
||||
const stopMonitoring = useCallback(() => {
|
||||
selectionGeneration.current++;
|
||||
const selected = selection.current;
|
||||
selection.current = null;
|
||||
cancellation.current = null;
|
||||
if (selected) {
|
||||
clearTimeout(selected.timer);
|
||||
selected.controller.abort();
|
||||
}
|
||||
}, []);
|
||||
|
||||
// A selection owns one request chain (status, then results) and one timer.
|
||||
// Polls, websocket invalidations and cancel acknowledgements all use this path.
|
||||
const refreshSelection = useCallback(
|
||||
function refresh(selected: RunSelection): Promise<void> {
|
||||
if (!isSelected(selected)) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
if (selected.request) {
|
||||
selected.refreshRequested = true;
|
||||
return selected.request;
|
||||
}
|
||||
clearTimeout(selected.timer);
|
||||
let monitorAgain = true;
|
||||
selected.request = (async () => {
|
||||
try {
|
||||
const run = await backtestApiV2.getRun(selected.id, selected.controller.signal);
|
||||
if (!isSelected(selected)) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
run.id !== selected.id ||
|
||||
(selected.backtestId !== null && run.backtestId !== selected.backtestId)
|
||||
) {
|
||||
monitorAgain = false;
|
||||
selected.refreshRequested = false;
|
||||
selected.results = null;
|
||||
setCurrentRun(null);
|
||||
setRunResults(null);
|
||||
throw new Error('Received a run for a different backtest or run selection');
|
||||
}
|
||||
|
||||
setCurrentRun(run);
|
||||
setRuns(previous =>
|
||||
previous.some(item => item.id === run.id)
|
||||
? previous.map(item => (item.id === run.id ? run : item))
|
||||
: [run, ...previous]
|
||||
);
|
||||
setRunError(null);
|
||||
monitorAgain = isActive(run);
|
||||
if (!monitorAgain) {
|
||||
cancellation.current = null;
|
||||
setCancelRequested(false);
|
||||
} else if (run.cancelRequested) {
|
||||
setCancelRequested(true);
|
||||
}
|
||||
|
||||
if (run.status === 'completed') {
|
||||
if (!selected.results) {
|
||||
const results = await backtestApiV2.getRunResults(
|
||||
selected.id,
|
||||
selected.controller.signal
|
||||
);
|
||||
if (!isSelected(selected)) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
results &&
|
||||
(results.runId !== selected.id || results.backtestId !== run.backtestId)
|
||||
) {
|
||||
selected.refreshRequested = false;
|
||||
throw new Error('Received results for a different backtest or run');
|
||||
}
|
||||
selected.results = results;
|
||||
setRunResults(results);
|
||||
}
|
||||
} else {
|
||||
selected.results = null;
|
||||
setRunResults(null);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!isSelected(selected)) {
|
||||
return;
|
||||
}
|
||||
setRunError(
|
||||
err instanceof RunResultsUnavailableError
|
||||
? null
|
||||
: messageOf(err, 'Failed to refresh run')
|
||||
);
|
||||
} finally {
|
||||
if (isSelected(selected)) {
|
||||
selected.request = undefined;
|
||||
setIsRunLoading(false);
|
||||
if (selected.refreshRequested) {
|
||||
selected.refreshRequested = false;
|
||||
void refresh(selected);
|
||||
} else if (monitorAgain) {
|
||||
selected.timer = setTimeout(() => void refresh(selected), 1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
})();
|
||||
return selected.request;
|
||||
},
|
||||
[isSelected]
|
||||
);
|
||||
|
||||
const refreshRun = useCallback(
|
||||
(runId?: string) => {
|
||||
const selected = selection.current;
|
||||
return selected && (!runId || selected.id === runId)
|
||||
? refreshSelection(selected)
|
||||
: Promise.resolve();
|
||||
},
|
||||
[refreshSelection]
|
||||
);
|
||||
|
||||
/** Reopening a run reads its recorded state; it never submits another backtest. */
|
||||
const selectRun = useCallback(
|
||||
(runId: string | undefined) => {
|
||||
if (
|
||||
runId &&
|
||||
selection.current?.id === runId &&
|
||||
selection.current.backtestId === loadedBacktestId.current
|
||||
) {
|
||||
return refreshSelection(selection.current);
|
||||
}
|
||||
stopMonitoring();
|
||||
setCurrentRun(null);
|
||||
setRunResults(null);
|
||||
setRunError(null);
|
||||
setCancelRequested(false);
|
||||
setIsRunLoading(Boolean(runId));
|
||||
if (!runId) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
const selected: RunSelection = {
|
||||
id: runId,
|
||||
backtestId: loadedBacktestId.current,
|
||||
controller: new AbortController(),
|
||||
refreshRequested: false,
|
||||
results: null,
|
||||
};
|
||||
selection.current = selected;
|
||||
return refreshSelection(selected);
|
||||
},
|
||||
[refreshSelection, stopMonitoring]
|
||||
);
|
||||
|
||||
/** Record a cancellation request, then monitor until the server reports a terminal state. */
|
||||
const cancelRun = useCallback(async () => {
|
||||
const selected = selection.current;
|
||||
if (
|
||||
!selected ||
|
||||
!currentRun ||
|
||||
currentRun.id !== selected.id ||
|
||||
!isActive(currentRun) ||
|
||||
cancellation.current === selected
|
||||
) {
|
||||
return;
|
||||
}
|
||||
cancellation.current = selected;
|
||||
setCancelRequested(true);
|
||||
setRunError(null);
|
||||
try {
|
||||
await backtestApiV2.cancelRun(selected.id, selected.controller.signal);
|
||||
if (isSelected(selected)) {
|
||||
await refreshSelection(selected);
|
||||
}
|
||||
} catch (err) {
|
||||
if (isSelected(selected)) {
|
||||
cancellation.current = null;
|
||||
setCancelRequested(Boolean(currentRun.cancelRequested));
|
||||
setRunError(messageOf(err, 'Failed to request cancellation'));
|
||||
}
|
||||
}
|
||||
}, [currentRun, isSelected, refreshSelection]);
|
||||
|
||||
return {
|
||||
currentRun,
|
||||
runResults,
|
||||
isRunLoading,
|
||||
runError,
|
||||
cancelRequested,
|
||||
selection,
|
||||
selectionGeneration,
|
||||
stopMonitoring,
|
||||
refreshRun,
|
||||
selectRun,
|
||||
cancelRun,
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,123 @@
|
|||
import {
|
||||
useCallback,
|
||||
useRef,
|
||||
useState,
|
||||
type Dispatch,
|
||||
type MutableRefObject,
|
||||
type SetStateAction,
|
||||
} from 'react';
|
||||
import type { CanonicalRunCapability } from '@stock-bot/stock-config/canonical-research';
|
||||
import { catalogExecutionReason } from '@/features/strategies/components/StrategySelection';
|
||||
import { backtestApiV2, type Backtest, type Run } from '../services/backtestApiV2';
|
||||
import { messageOf } from './useRunMonitoring';
|
||||
|
||||
export function useRunSubmission({
|
||||
backtest,
|
||||
loadedBacktestId,
|
||||
mounted,
|
||||
selectionGeneration,
|
||||
catalog,
|
||||
canonicalCapability,
|
||||
capabilityError,
|
||||
setRuns,
|
||||
}: {
|
||||
backtest: Backtest | null;
|
||||
loadedBacktestId: MutableRefObject<string | null>;
|
||||
mounted: MutableRefObject<boolean>;
|
||||
selectionGeneration: MutableRefObject<number>;
|
||||
catalog: boolean;
|
||||
canonicalCapability: CanonicalRunCapability | null;
|
||||
capabilityError: string | null;
|
||||
setRuns: Dispatch<SetStateAction<Run[]>>;
|
||||
}) {
|
||||
const [submissionError, setSubmissionError] = useState<string | null>(null);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
// The intent survives an ambiguous response and configuration edits. Only an
|
||||
// acknowledged submission (or leaving this definition) releases its key.
|
||||
const submission = useRef<{
|
||||
backtestId: string;
|
||||
key: string;
|
||||
body: { speedMultiplier: number | null };
|
||||
pending: boolean;
|
||||
} | null>(null);
|
||||
/**
|
||||
* Retain the same key/body after an ambiguous response so Retry can recover
|
||||
* the accepted run. This receipt is in memory for this mounted hook; it is not
|
||||
* a persistent browser recovery journal. New admissions recheck eligibility;
|
||||
* receipt retries recover the original run before current eligibility checks.
|
||||
*/
|
||||
const createRun = useCallback(
|
||||
async (_speedMultiplier: number | null = null) => {
|
||||
if (!backtest || backtest.id !== loadedBacktestId.current || submission.current?.pending) {
|
||||
return undefined;
|
||||
}
|
||||
if (backtest.archivedAt && !submission.current) {
|
||||
setSubmissionError('Restore this archived backtest before starting a new run.');
|
||||
return undefined;
|
||||
}
|
||||
if (catalog && !canonicalCapability?.available && !submission.current) {
|
||||
setSubmissionError(
|
||||
capabilityError ?? canonicalCapability?.reason ?? catalogExecutionReason
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
if (!catalog && !submission.current) {
|
||||
setSubmissionError(
|
||||
'Legacy execution is retired. Create a catalog backtest to run with retained canonical inputs.'
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
const intent = (submission.current ??= {
|
||||
backtestId: backtest.id,
|
||||
key: crypto.randomUUID(),
|
||||
body: { speedMultiplier: null },
|
||||
pending: false,
|
||||
});
|
||||
intent.pending = true;
|
||||
const selectedGeneration = selectionGeneration.current;
|
||||
const ownsSubmission = () => mounted.current && submission.current === intent;
|
||||
const ownsSelection = () =>
|
||||
ownsSubmission() && selectionGeneration.current === selectedGeneration;
|
||||
setIsSubmitting(true);
|
||||
setSubmissionError(null);
|
||||
try {
|
||||
const created = await backtestApiV2.createRun(intent.backtestId, intent.body, intent.key);
|
||||
if (!ownsSubmission()) {
|
||||
return undefined;
|
||||
}
|
||||
const selected = ownsSelection();
|
||||
submission.current = null;
|
||||
setIsSubmitting(false);
|
||||
if (!selected) {
|
||||
return undefined;
|
||||
}
|
||||
setRuns(previous => [created, ...previous.filter(run => run.id !== created.id)]);
|
||||
return created;
|
||||
} catch (err) {
|
||||
if (ownsSubmission()) {
|
||||
setSubmissionError(messageOf(err, 'Failed to submit run'));
|
||||
}
|
||||
return undefined;
|
||||
} finally {
|
||||
intent.pending = false;
|
||||
if (ownsSubmission()) {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[backtest, catalog, canonicalCapability, capabilityError]
|
||||
);
|
||||
|
||||
const resetSubmission = useCallback(() => {
|
||||
submission.current = null;
|
||||
setSubmissionError(null);
|
||||
setIsSubmitting(false);
|
||||
}, []);
|
||||
return {
|
||||
createRun,
|
||||
submissionError,
|
||||
isSubmitting,
|
||||
hasPendingSubmission: submission.current !== null,
|
||||
resetSubmission,
|
||||
};
|
||||
}
|
||||
|
|
@ -1,4 +1,8 @@
|
|||
import { z } from 'zod';
|
||||
import {
|
||||
datasetUnavailableReason,
|
||||
preparationManifestSchema,
|
||||
} from '@stock-bot/research/dataset-contracts';
|
||||
import { candidateExecutionSchema } from '@stock-bot/stock-config/candidate-execution';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import type {
|
||||
|
|
@ -113,112 +117,7 @@ const hashOrNull = (value: unknown) =>
|
|||
const preparationText = z.string().min(1);
|
||||
const preparationHash = z.string().regex(/^[a-f0-9]{64}$/);
|
||||
const preparationInstant = z.number().int().nonnegative().max(8_640_000_000_000_000);
|
||||
const preparationDay = z
|
||||
.string()
|
||||
.regex(/^\d{4}-\d{2}-\d{2}$/)
|
||||
.refine(
|
||||
value =>
|
||||
Number.isFinite(Date.parse(value)) && new Date(value).toISOString().slice(0, 10) === value
|
||||
);
|
||||
const preparationManifest = z
|
||||
.object({
|
||||
version: z.literal(2),
|
||||
hash: preparationHash,
|
||||
normalizationRevision: z.literal('historical-normalization-v2'),
|
||||
parentDatasetHash: z.null(),
|
||||
volumePolicy: z.literal('reported'),
|
||||
qualityPolicy: z.literal('reject-invalid-no-interpolation'),
|
||||
intradayPolicy: z.literal('full-duration-session-contained'),
|
||||
eligibility: z.enum(['eligible', 'exploratory', 'ineligible']),
|
||||
limitations: z.array(preparationText),
|
||||
barCount: z.number().int().positive().safe(),
|
||||
calendars: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
id: preparationText,
|
||||
venue: preparationText,
|
||||
timeZone: preparationText,
|
||||
source: preparationText,
|
||||
revision: preparationText,
|
||||
startDate: preparationDay,
|
||||
endDate: preparationDay,
|
||||
sessions: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
date: preparationDay,
|
||||
open: preparationInstant,
|
||||
close: preparationInstant,
|
||||
})
|
||||
.strict()
|
||||
.refine(value => value.open < value.close)
|
||||
)
|
||||
.min(1),
|
||||
})
|
||||
.strict()
|
||||
)
|
||||
.min(1),
|
||||
series: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
id: preparationText,
|
||||
instrumentId: preparationText,
|
||||
interval: z.enum(['1m', '5m', '15m', '1h', '1d']),
|
||||
calendarId: preparationText,
|
||||
venue: preparationText,
|
||||
source: z.object({ provider: preparationText, revision: preparationText }).strict(),
|
||||
timestamp: z.enum(['session-date', 'interval-start', 'interval-end']),
|
||||
availability: z.enum(['explicit', 'interval-end-assumption']),
|
||||
adjustment: z.enum(['raw', 'provider-adjusted']),
|
||||
})
|
||||
.strict()
|
||||
)
|
||||
.min(1),
|
||||
executionSeries: z
|
||||
.array(z.object({ instrumentId: preparationText, seriesId: preparationText }).strict())
|
||||
.min(1),
|
||||
bounds: z
|
||||
.object({
|
||||
warmupStart: preparationInstant,
|
||||
tradeStart: preparationInstant,
|
||||
tradeEnd: preparationInstant,
|
||||
})
|
||||
.strict()
|
||||
.refine(value => value.warmupStart <= value.tradeStart && value.tradeStart < value.tradeEnd),
|
||||
universe: z
|
||||
.object({
|
||||
selection: z.enum(['point-in-time', 'current-constituents', 'unknown']),
|
||||
asOf: preparationInstant.nullable(),
|
||||
revision: preparationText,
|
||||
instrumentIds: z.array(preparationText).min(1),
|
||||
})
|
||||
.strict(),
|
||||
corporateActions: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
instrumentId: preparationText,
|
||||
status: z.enum(['unknown', 'action-free', 'known-actions']),
|
||||
start: preparationInstant,
|
||||
end: preparationInstant,
|
||||
revision: preparationText,
|
||||
actions: z.array(
|
||||
z
|
||||
.object({
|
||||
effectiveAt: preparationInstant,
|
||||
kind: z.enum(['split', 'dividend', 'other']),
|
||||
reference: preparationText,
|
||||
})
|
||||
.strict()
|
||||
),
|
||||
})
|
||||
.strict()
|
||||
)
|
||||
.min(1),
|
||||
})
|
||||
.strict();
|
||||
const preparationManifest = preparationManifestSchema;
|
||||
const datasetPreparationSchema = z
|
||||
.object({
|
||||
version: z.literal('canonical-dataset-preparation/v1'),
|
||||
|
|
@ -234,11 +133,7 @@ export function parseDatasetPreparation(
|
|||
): CanonicalDatasetPreparation {
|
||||
const value = datasetPreparationSchema.parse(raw),
|
||||
manifest = value.manifest;
|
||||
const available =
|
||||
manifest.eligibility === 'eligible' &&
|
||||
manifest.executionSeries.length === 1 &&
|
||||
manifest.series.length === 1 &&
|
||||
manifest.universe.instrumentIds.length === 1;
|
||||
const available = datasetUnavailableReason(manifest) === null;
|
||||
if (
|
||||
value.hash !== manifest.hash ||
|
||||
(expectedHash !== undefined && value.hash !== expectedHash) ||
|
||||
|
|
|
|||
|
|
@ -1,51 +1,21 @@
|
|||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
costSensitivityInputSchema,
|
||||
type CostScenario,
|
||||
type CostSensitivitySubmission,
|
||||
} from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import {
|
||||
experimentInputSchema,
|
||||
MAX_EXPERIMENT_TRIALS,
|
||||
type ExperimentSubmission,
|
||||
} from '@stock-bot/stock-config/experiments';
|
||||
import { type CostScenario } from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import { MAX_EXPERIMENT_TRIALS } from '@stock-bot/stock-config/experiments';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { backtestApiV2, type Backtest } from '@/features/backtest/services/backtestApiV2';
|
||||
import {
|
||||
StrategySelection,
|
||||
type CatalogSelection,
|
||||
} from '@/features/strategies/components/StrategySelection';
|
||||
import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning';
|
||||
import {
|
||||
experimentApi,
|
||||
ExperimentApiError,
|
||||
type WorkbenchExperimentPreviewView,
|
||||
} from '../services/experimentApi';
|
||||
import { useExperimentSubmission } from '../hooks/useExperimentSubmission';
|
||||
import { useExperimentTemplates } from '../hooks/useExperimentTemplates';
|
||||
import { ChronologicalValidationPreflight } from './ChronologicalValidationPreflight';
|
||||
import { ExperimentInputs } from './ExperimentInputs';
|
||||
import { WalkForwardPreflight } from './WalkForwardPreflight';
|
||||
|
||||
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,
|
||||
|
|
@ -54,47 +24,9 @@ export function ExperimentEditor({
|
|||
onDirty: (dirty: boolean) => void;
|
||||
}) {
|
||||
const navigate = useNavigate();
|
||||
const alive = useRef(false);
|
||||
const generation = useRef(0);
|
||||
const previewRevision = useRef<number | null>(null);
|
||||
const previewRequest = useRef<AbortController | null>(null);
|
||||
const pending = useRef(false);
|
||||
type Intent =
|
||||
| { kind: 'parameters'; body: ExperimentSubmission; key: string }
|
||||
| { kind: 'cost-sensitivity'; body: CostSensitivitySubmission; key: string };
|
||||
const intent = useRef<Intent | null>(null);
|
||||
const [mode, setMode] = useState<'parameters' | 'cost-sensitivity'>('parameters');
|
||||
const modeRef = useRef(mode);
|
||||
const [scenarios, setScenarios] = useState<CostScenario[]>([{ feeRate: '', slippageRate: '' }]);
|
||||
const submissionOwner = useRef<'ordinary' | 'chronological' | 'walk-forward' | null>(null);
|
||||
const [lockedBy, setLockedBy] = useState<'ordinary' | 'chronological' | 'walk-forward' | null>(
|
||||
null
|
||||
);
|
||||
const claimSubmission = useCallback((owner: 'ordinary' | 'chronological' | 'walk-forward') => {
|
||||
if (
|
||||
(owner !== 'ordinary' && modeRef.current === 'cost-sensitivity') ||
|
||||
(submissionOwner.current && submissionOwner.current !== owner)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
submissionOwner.current = owner;
|
||||
setLockedBy(owner);
|
||||
if (owner !== 'ordinary') {
|
||||
generation.current++;
|
||||
previewRequest.current?.abort();
|
||||
previewRevision.current = null;
|
||||
setPreview(null);
|
||||
setPreviewLoading(false);
|
||||
}
|
||||
return true;
|
||||
}, []);
|
||||
const releaseSubmission = useCallback((owner: 'ordinary' | 'chronological' | 'walk-forward') => {
|
||||
if (submissionOwner.current === owner) {
|
||||
submissionOwner.current = null;
|
||||
setLockedBy(null);
|
||||
}
|
||||
}, []);
|
||||
const [hasIntent, setHasIntent] = useState(false);
|
||||
const [backtestId, setBacktestId] = useState(initialBacktestId);
|
||||
const [name, setName] = useState('');
|
||||
const [grid, setGrid] = useState('{}');
|
||||
|
|
@ -111,19 +43,38 @@ export function ExperimentEditor({
|
|||
parameters: candidateSelection.strategyParameters ?? {},
|
||||
}
|
||||
: undefined;
|
||||
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<WorkbenchExperimentPreviewView | null>(null);
|
||||
const [previewLoading, setPreviewLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [ambiguous, setAmbiguous] = useState(false);
|
||||
const [validationDirty, setValidationDirty] = useState(false);
|
||||
const [walkForwardDirty, setWalkForwardDirty] = useState(false);
|
||||
const { backtests, templateLoading, templateError, setTemplateReload, moreTemplates, setLimit } =
|
||||
useExperimentTemplates(initialBacktestId);
|
||||
const {
|
||||
submissionOwner,
|
||||
lockedBy,
|
||||
claimSubmission,
|
||||
releaseSubmission,
|
||||
preview,
|
||||
previewLoading,
|
||||
error,
|
||||
hasIntent,
|
||||
submitting,
|
||||
ambiguous,
|
||||
invalidate,
|
||||
prepare,
|
||||
submit,
|
||||
newIntent,
|
||||
} = useExperimentSubmission({
|
||||
backtestId,
|
||||
name,
|
||||
grid,
|
||||
modeRef,
|
||||
scenarios,
|
||||
candidate,
|
||||
candidateRevision,
|
||||
renderedCandidateRevision,
|
||||
useCandidate,
|
||||
candidateValid,
|
||||
onAccepted: id => navigate(`/experiments/${encodeURIComponent(id)}`),
|
||||
});
|
||||
const dirty =
|
||||
hasIntent ||
|
||||
validationDirty ||
|
||||
|
|
@ -141,183 +92,7 @@ export function ExperimentEditor({
|
|||
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 (submissionOwner.current) {
|
||||
return;
|
||||
}
|
||||
generation.current++;
|
||||
previewRequest.current?.abort();
|
||||
previewRevision.current = null;
|
||||
setPreview(null);
|
||||
setPreviewLoading(false);
|
||||
setError('');
|
||||
change();
|
||||
};
|
||||
const prepare = async () => {
|
||||
if (
|
||||
submissionOwner.current ||
|
||||
previewLoading ||
|
||||
candidateRevision.current !== renderedCandidateRevision ||
|
||||
(useCandidate && !candidateValid)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const current = ++generation.current;
|
||||
previewRequest.current?.abort();
|
||||
const controller = new AbortController();
|
||||
previewRequest.current = controller;
|
||||
previewRevision.current = null;
|
||||
setPreview(null);
|
||||
setError('');
|
||||
setPreviewLoading(true);
|
||||
try {
|
||||
const value =
|
||||
modeRef.current === 'cost-sensitivity'
|
||||
? await experimentApi.costPreview(
|
||||
costSensitivityInputSchema.parse({
|
||||
backtestId,
|
||||
name,
|
||||
scenarios,
|
||||
...(candidate ? { candidate } : {}),
|
||||
}),
|
||||
controller.signal
|
||||
)
|
||||
: await experimentApi.preview(
|
||||
experimentInputSchema.parse({
|
||||
backtestId,
|
||||
name,
|
||||
grid: JSON.parse(grid),
|
||||
...(candidate ? { candidate } : {}),
|
||||
}),
|
||||
controller.signal
|
||||
);
|
||||
if (alive.current && current === generation.current) {
|
||||
previewRevision.current = 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 || previewRevision.current !== generation.current)) ||
|
||||
!claimSubmission('ordinary')
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (!intent.current) {
|
||||
if (!preview) {
|
||||
return;
|
||||
}
|
||||
intent.current =
|
||||
preview.version === 'cost-sensitivity-preview/v1'
|
||||
? {
|
||||
kind: 'cost-sensitivity',
|
||||
key: crypto.randomUUID(),
|
||||
body: { ...preview.input, previewHash: preview.previewHash },
|
||||
}
|
||||
: {
|
||||
kind: 'parameters',
|
||||
key: crypto.randomUUID(),
|
||||
body: { ...preview.input, previewHash: preview.previewHash },
|
||||
};
|
||||
}
|
||||
const captured = intent.current;
|
||||
pending.current = true;
|
||||
setHasIntent(true);
|
||||
setSubmitting(true);
|
||||
setError('');
|
||||
try {
|
||||
const accepted =
|
||||
captured.kind === 'cost-sensitivity'
|
||||
? await experimentApi.costSubmit(captured.body, captured.key)
|
||||
: await experimentApi.create(captured.body, captured.key);
|
||||
if (alive.current) {
|
||||
intent.current = null;
|
||||
setHasIntent(false);
|
||||
releaseSubmission('ordinary');
|
||||
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);
|
||||
releaseSubmission('ordinary');
|
||||
setAmbiguous(false);
|
||||
previewRevision.current = null;
|
||||
setPreview(null);
|
||||
setError('');
|
||||
};
|
||||
return (
|
||||
<section
|
||||
aria-label="Create experiment"
|
||||
|
|
|
|||
|
|
@ -0,0 +1,252 @@
|
|||
import { useCallback, useEffect, useRef, useState, type MutableRefObject } from 'react';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
costSensitivityInputSchema,
|
||||
type CostScenario,
|
||||
type CostSensitivitySubmission,
|
||||
} from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import {
|
||||
experimentInputSchema,
|
||||
type ExperimentSubmission,
|
||||
} from '@stock-bot/stock-config/experiments';
|
||||
import type { StrategyParameterValue } from '@stock-bot/types';
|
||||
import {
|
||||
experimentApi,
|
||||
ExperimentApiError,
|
||||
type WorkbenchExperimentPreviewView,
|
||||
} from '../services/experimentApi';
|
||||
|
||||
interface Inputs {
|
||||
backtestId: string;
|
||||
name: string;
|
||||
grid: string;
|
||||
modeRef: MutableRefObject<'parameters' | 'cost-sensitivity'>;
|
||||
scenarios: CostScenario[];
|
||||
candidate: { versionId: string; parameters: Record<string, StrategyParameterValue> } | undefined;
|
||||
candidateRevision: MutableRefObject<number>;
|
||||
renderedCandidateRevision: number;
|
||||
useCandidate: boolean;
|
||||
candidateValid: boolean;
|
||||
onAccepted: (id: string) => void;
|
||||
}
|
||||
export 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';
|
||||
|
||||
/** One coordinator owns all submission modes and ordinary receipt recovery. */
|
||||
export function useExperimentSubmission({
|
||||
backtestId,
|
||||
name,
|
||||
grid,
|
||||
modeRef,
|
||||
scenarios,
|
||||
candidate,
|
||||
candidateRevision,
|
||||
renderedCandidateRevision,
|
||||
useCandidate,
|
||||
candidateValid,
|
||||
onAccepted,
|
||||
}: Inputs) {
|
||||
const alive = useRef(false);
|
||||
const generation = useRef(0);
|
||||
const previewRevision = useRef<number | null>(null);
|
||||
const previewRequest = useRef<AbortController | null>(null);
|
||||
const pending = useRef(false);
|
||||
type Intent =
|
||||
| { kind: 'parameters'; body: ExperimentSubmission; key: string }
|
||||
| { kind: 'cost-sensitivity'; body: CostSensitivitySubmission; key: string };
|
||||
const intent = useRef<Intent | null>(null);
|
||||
const [preview, setPreview] = useState<WorkbenchExperimentPreviewView | null>(null);
|
||||
const [previewLoading, setPreviewLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [phase, setPhase] = useState<'idle' | 'submitting' | 'uncertain' | 'rejected'>('idle');
|
||||
const hasIntent = phase !== 'idle';
|
||||
const submitting = phase === 'submitting';
|
||||
const ambiguous = phase === 'uncertain';
|
||||
const submissionOwner = useRef<'ordinary' | 'chronological' | 'walk-forward' | null>(null);
|
||||
const [lockedBy, setLockedBy] = useState<'ordinary' | 'chronological' | 'walk-forward' | null>(
|
||||
null
|
||||
);
|
||||
const claimSubmission = useCallback((owner: 'ordinary' | 'chronological' | 'walk-forward') => {
|
||||
if (
|
||||
(owner !== 'ordinary' && modeRef.current === 'cost-sensitivity') ||
|
||||
(submissionOwner.current && submissionOwner.current !== owner)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
submissionOwner.current = owner;
|
||||
setLockedBy(owner);
|
||||
if (owner !== 'ordinary') {
|
||||
generation.current++;
|
||||
previewRequest.current?.abort();
|
||||
previewRevision.current = null;
|
||||
setPreview(null);
|
||||
setPreviewLoading(false);
|
||||
}
|
||||
return true;
|
||||
}, []);
|
||||
const releaseSubmission = useCallback((owner: 'ordinary' | 'chronological' | 'walk-forward') => {
|
||||
if (submissionOwner.current === owner) {
|
||||
submissionOwner.current = null;
|
||||
setLockedBy(null);
|
||||
}
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
generation.current++;
|
||||
previewRequest.current?.abort();
|
||||
};
|
||||
}, []);
|
||||
const invalidate = (change: () => void) => {
|
||||
if (submissionOwner.current) {
|
||||
return;
|
||||
}
|
||||
generation.current++;
|
||||
previewRequest.current?.abort();
|
||||
previewRevision.current = null;
|
||||
setPreview(null);
|
||||
setPreviewLoading(false);
|
||||
setError('');
|
||||
change();
|
||||
};
|
||||
const prepare = async () => {
|
||||
if (
|
||||
submissionOwner.current ||
|
||||
previewLoading ||
|
||||
candidateRevision.current !== renderedCandidateRevision ||
|
||||
(useCandidate && !candidateValid)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const current = ++generation.current;
|
||||
previewRequest.current?.abort();
|
||||
const controller = new AbortController();
|
||||
previewRequest.current = controller;
|
||||
previewRevision.current = null;
|
||||
setPreview(null);
|
||||
setError('');
|
||||
setPreviewLoading(true);
|
||||
try {
|
||||
const value =
|
||||
modeRef.current === 'cost-sensitivity'
|
||||
? await experimentApi.costPreview(
|
||||
costSensitivityInputSchema.parse({
|
||||
backtestId,
|
||||
name,
|
||||
scenarios,
|
||||
...(candidate ? { candidate } : {}),
|
||||
}),
|
||||
controller.signal
|
||||
)
|
||||
: await experimentApi.preview(
|
||||
experimentInputSchema.parse({
|
||||
backtestId,
|
||||
name,
|
||||
grid: JSON.parse(grid),
|
||||
...(candidate ? { candidate } : {}),
|
||||
}),
|
||||
controller.signal
|
||||
);
|
||||
if (alive.current && current === generation.current) {
|
||||
previewRevision.current = 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 || previewRevision.current !== generation.current)) ||
|
||||
!claimSubmission('ordinary')
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (!intent.current) {
|
||||
if (!preview) {
|
||||
return;
|
||||
}
|
||||
intent.current =
|
||||
preview.version === 'cost-sensitivity-preview/v1'
|
||||
? {
|
||||
kind: 'cost-sensitivity',
|
||||
key: crypto.randomUUID(),
|
||||
body: { ...preview.input, previewHash: preview.previewHash },
|
||||
}
|
||||
: {
|
||||
kind: 'parameters',
|
||||
key: crypto.randomUUID(),
|
||||
body: { ...preview.input, previewHash: preview.previewHash },
|
||||
};
|
||||
}
|
||||
const captured = intent.current;
|
||||
pending.current = true;
|
||||
setPhase('submitting');
|
||||
setError('');
|
||||
try {
|
||||
const accepted =
|
||||
captured.kind === 'cost-sensitivity'
|
||||
? await experimentApi.costSubmit(captured.body, captured.key)
|
||||
: await experimentApi.create(captured.body, captured.key);
|
||||
if (alive.current) {
|
||||
intent.current = null;
|
||||
setPhase('idle');
|
||||
releaseSubmission('ordinary');
|
||||
onAccepted(accepted.id);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
setError(message(cause));
|
||||
setPhase(
|
||||
!(cause instanceof ExperimentApiError) || cause.ambiguous ? 'uncertain' : 'rejected'
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
pending.current = 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;
|
||||
setPhase('idle');
|
||||
releaseSubmission('ordinary');
|
||||
previewRevision.current = null;
|
||||
setPreview(null);
|
||||
setError('');
|
||||
};
|
||||
return {
|
||||
submissionOwner,
|
||||
lockedBy,
|
||||
claimSubmission,
|
||||
releaseSubmission,
|
||||
preview,
|
||||
previewLoading,
|
||||
error,
|
||||
hasIntent,
|
||||
submitting,
|
||||
ambiguous,
|
||||
invalidate,
|
||||
prepare,
|
||||
submit,
|
||||
newIntent,
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,59 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { backtestApiV2, type Backtest } from '@/features/backtest/services/backtestApiV2';
|
||||
import { message } from './useExperimentSubmission';
|
||||
|
||||
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 useExperimentTemplates(initialBacktestId: string) {
|
||||
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);
|
||||
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]);
|
||||
|
||||
return { backtests, templateLoading, templateError, setTemplateReload, moreTemplates, setLimit };
|
||||
}
|
||||
|
|
@ -15,7 +15,8 @@ import {
|
|||
validationSummarySchema as summary,
|
||||
ValidationApiError,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
import { API_BASE_URL } from '@/lib/api';
|
||||
import { requestJson } from '@/lib/requestJson';
|
||||
|
||||
export {
|
||||
parseValidationDetail,
|
||||
|
|
@ -26,41 +27,20 @@ export {
|
|||
export type { ValidationResultEvidence };
|
||||
|
||||
const envelope = (body: unknown, key: string) => z.record(z.unknown()).parse(body)[key];
|
||||
async function request<T>(
|
||||
function request<T>(
|
||||
path: string,
|
||||
init: RequestInit,
|
||||
status: number,
|
||||
parse: (body: unknown) => T
|
||||
): Promise<T> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await apiFetch(`${API_BASE_URL}/api/v2/experiments/validation${path}`, init);
|
||||
} catch (cause) {
|
||||
if (init.signal?.aborted) {
|
||||
throw cause;
|
||||
}
|
||||
throw new ValidationApiError(
|
||||
'The validation response was lost. Retry the same request to recover its receipt.',
|
||||
null
|
||||
);
|
||||
}
|
||||
const body: unknown = await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
const error = z.object({ error: z.string() }).safeParse(body);
|
||||
throw new ValidationApiError(
|
||||
error.success ? error.data.error : `Validation request failed (${response.status})`,
|
||||
response.status
|
||||
);
|
||||
}
|
||||
try {
|
||||
if (response.status !== status) {
|
||||
throw invalid();
|
||||
}
|
||||
return parse(body);
|
||||
} catch {
|
||||
throw invalid();
|
||||
}
|
||||
return requestJson(`${API_BASE_URL}/api/v2/experiments/validation${path}`, init, status, parse, {
|
||||
create: (message, code) => new ValidationApiError(message, code),
|
||||
invalid,
|
||||
lostMessage: 'The validation response was lost. Retry the same request to recover its receipt.',
|
||||
failureLabel: 'Validation request failed',
|
||||
});
|
||||
}
|
||||
|
||||
const post = (body: unknown, key?: string): RequestInit => ({
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
|
|
|
|||
|
|
@ -23,7 +23,8 @@ import {
|
|||
sameExperimentInput as same,
|
||||
type ExperimentRetryTarget,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
import { API_BASE_URL } from '@/lib/api';
|
||||
import { requestJson } from '@/lib/requestJson';
|
||||
|
||||
export {
|
||||
ExperimentApiError,
|
||||
|
|
@ -41,41 +42,21 @@ export {
|
|||
type WorkbenchExperimentPreviewView,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
|
||||
async function request<T>(
|
||||
function request<T>(
|
||||
path: string,
|
||||
init: RequestInit,
|
||||
expectedStatus: number,
|
||||
status: number,
|
||||
parse: (body: unknown) => T
|
||||
): Promise<T> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await apiFetch(`${API_BASE_URL}/api/v2/experiments${path}`, init);
|
||||
} catch (cause) {
|
||||
if (init.signal?.aborted) {
|
||||
throw cause;
|
||||
}
|
||||
throw new ExperimentApiError(
|
||||
return requestJson(`${API_BASE_URL}/api/v2/experiments${path}`, init, status, parse, {
|
||||
create: (message, code) => new ExperimentApiError(message, code),
|
||||
invalid,
|
||||
lostMessage:
|
||||
'The experiment response was lost. Retry the same submission to check whether it was accepted.',
|
||||
null
|
||||
);
|
||||
}
|
||||
const body: unknown = await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
const parsed = z.object({ error: z.string() }).safeParse(body);
|
||||
throw new ExperimentApiError(
|
||||
parsed.success ? parsed.data.error : `Experiment request failed (${response.status})`,
|
||||
response.status
|
||||
);
|
||||
}
|
||||
try {
|
||||
if (response.status !== expectedStatus) {
|
||||
throw invalid();
|
||||
}
|
||||
return parse(body);
|
||||
} catch {
|
||||
throw invalid();
|
||||
}
|
||||
failureLabel: 'Experiment request failed',
|
||||
});
|
||||
}
|
||||
|
||||
const envelope = (body: unknown, field: string): unknown =>
|
||||
z.record(z.unknown()).parse(body)[field];
|
||||
const json = (body: unknown): RequestInit => ({
|
||||
|
|
|
|||
|
|
@ -16,7 +16,8 @@ import {
|
|||
type WalkForwardSubmission,
|
||||
type WalkForwardSummary,
|
||||
} from '@stock-bot/stock-config/walk-forward';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
import { API_BASE_URL } from '@/lib/api';
|
||||
import { requestJson } from '@/lib/requestJson';
|
||||
|
||||
export {
|
||||
WalkForwardApiError,
|
||||
|
|
@ -27,41 +28,27 @@ export {
|
|||
} from '@stock-bot/stock-config/research-responses';
|
||||
|
||||
const envelope = (body: unknown, key: string) => z.record(z.unknown()).parse(body)[key];
|
||||
async function request<T>(
|
||||
function request<T>(
|
||||
path: string,
|
||||
init: RequestInit,
|
||||
status: number,
|
||||
parse: (body: unknown) => T
|
||||
): Promise<T> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await apiFetch(`${API_BASE_URL}/api/v2/experiments/walk-forward${path}`, init);
|
||||
} catch (cause) {
|
||||
if (init.signal?.aborted) {
|
||||
throw cause;
|
||||
return requestJson(
|
||||
`${API_BASE_URL}/api/v2/experiments/walk-forward${path}`,
|
||||
init,
|
||||
status,
|
||||
parse,
|
||||
{
|
||||
create: (message, code) => new WalkForwardApiError(message, code),
|
||||
invalid,
|
||||
lostMessage:
|
||||
'The walk-forward response was lost. Retry the same request to recover its receipt.',
|
||||
failureLabel: 'Walk-forward request failed',
|
||||
}
|
||||
throw new WalkForwardApiError(
|
||||
'The walk-forward response was lost. Retry the same request to recover its receipt.',
|
||||
null
|
||||
);
|
||||
}
|
||||
const body: unknown = await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
const error = z.object({ error: z.string() }).safeParse(body);
|
||||
throw new WalkForwardApiError(
|
||||
error.success ? error.data.error : `Walk-forward request failed (${response.status})`,
|
||||
response.status
|
||||
);
|
||||
}
|
||||
try {
|
||||
if (response.status !== status) {
|
||||
throw invalid();
|
||||
}
|
||||
return parse(body);
|
||||
} catch {
|
||||
throw invalid();
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const post = (body: unknown, key?: string): RequestInit => ({
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
|
|
|
|||
|
|
@ -1,15 +1,14 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, Navigate, useNavigate, useParams } from 'react-router-dom';
|
||||
import type {
|
||||
StrategyRecord,
|
||||
StrategyVersionPackage,
|
||||
StrategyVersionSummary,
|
||||
} from '@stock-bot/types';
|
||||
import type { StrategyRecord, StrategyVersionSummary } from '@stock-bot/types';
|
||||
import { BuiltinReview } from './components/BuiltinReview';
|
||||
import { CandidatePublication } from './components/CandidatePublication';
|
||||
import { StrategyMetadataForm } from './components/StrategyMetadataForm';
|
||||
import { actionClass, fieldClass, StrategyParameterForm } from './components/StrategyParameterForm';
|
||||
import { versionPath } from './components/StrategySelection';
|
||||
import { VersionComparison, VersionIdentity } from './components/StrategyVersionPanel';
|
||||
import { confirmDiscard, useUnsavedWarning } from './components/useUnsavedWarning';
|
||||
import { useStrategyClone } from './hooks/useStrategyClone';
|
||||
import { strategyApi, type Parameters } from './services/strategyApi';
|
||||
|
||||
export function StrategyDetailPage() {
|
||||
|
|
@ -35,21 +34,24 @@ function StrategyDetail({ strategyId, versionId }: { strategyId: string; version
|
|||
const [validParameters, setValidParameters] = useState(false);
|
||||
const [parameterEdits, setParameterEdits] = useState(false);
|
||||
const [publicationDirty, setPublicationDirty] = useState(false);
|
||||
const [cloneOpen, setCloneOpen] = useState(false);
|
||||
const [cloneName, setCloneName] = useState('');
|
||||
const [cloneDescription, setCloneDescription] = useState('');
|
||||
const [cloning, setCloning] = useState(false);
|
||||
const [cloneError, setCloneError] = useState<string | null>(null);
|
||||
const cloneIntent = useRef<{
|
||||
versionId: string;
|
||||
versionOrdinal: number;
|
||||
body: { name: string; description: string };
|
||||
key: string;
|
||||
} | null>(null);
|
||||
const [cloneFrozen, setCloneFrozen] = useState(false);
|
||||
const mounted = useRef(true);
|
||||
const selectedVersionId = useRef(versionId);
|
||||
selectedVersionId.current = versionId;
|
||||
const {
|
||||
cloneOpen,
|
||||
setCloneOpen,
|
||||
cloneName,
|
||||
setCloneName,
|
||||
cloneDescription,
|
||||
setCloneDescription,
|
||||
cloning,
|
||||
cloneError,
|
||||
setCloneError,
|
||||
cloneIntent,
|
||||
cloneFrozen,
|
||||
setCloneFrozen,
|
||||
clone,
|
||||
} = useStrategyClone(version, versionId, navigate);
|
||||
const metadataDirty = Boolean(
|
||||
strategy && (name !== strategy.name || description !== strategy.description)
|
||||
);
|
||||
|
|
@ -150,37 +152,7 @@ function StrategyDetail({ strategyId, versionId }: { strategyId: string; version
|
|||
}
|
||||
}
|
||||
};
|
||||
const clone = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (!version || cloning || !cloneName.trim()) {
|
||||
return;
|
||||
}
|
||||
const intent = (cloneIntent.current ??= {
|
||||
versionId: version.id,
|
||||
versionOrdinal: version.ordinal,
|
||||
body: { name: cloneName, description: cloneDescription },
|
||||
key: crypto.randomUUID(),
|
||||
});
|
||||
setCloneFrozen(true);
|
||||
setCloning(true);
|
||||
setCloneError(null);
|
||||
try {
|
||||
const result = await strategyApi.clone(intent.versionId, intent.body, intent.key);
|
||||
if (mounted.current && selectedVersionId.current === intent.versionId) {
|
||||
navigate(versionPath(result.version));
|
||||
}
|
||||
} catch (cause) {
|
||||
if (mounted.current && selectedVersionId.current === intent.versionId) {
|
||||
setCloneError(
|
||||
`${cause instanceof Error ? cause.message : 'Clone failed'}. Retry clone to recover the same immutable version.`
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (mounted.current) {
|
||||
setCloning(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-5 text-text-primary">
|
||||
<Link
|
||||
|
|
@ -218,84 +190,17 @@ function StrategyDetail({ strategyId, versionId }: { strategyId: string; version
|
|||
{strategy.name}
|
||||
{strategy.archived ? ' — Archived' : ''}
|
||||
</h1>
|
||||
<form
|
||||
className="space-y-3 border border-border rounded-md p-4"
|
||||
onSubmit={event => {
|
||||
event.preventDefault();
|
||||
void update({ name, description });
|
||||
}}
|
||||
>
|
||||
<label className="block text-sm">
|
||||
Strategy name
|
||||
<input
|
||||
aria-label="Strategy name"
|
||||
className={fieldClass}
|
||||
required
|
||||
disabled={saving}
|
||||
value={name}
|
||||
onChange={event => setName(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-sm">
|
||||
Strategy description
|
||||
<textarea
|
||||
aria-label="Strategy description"
|
||||
className={fieldClass}
|
||||
disabled={saving}
|
||||
value={description}
|
||||
onChange={event => setDescription(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
{metadataDirty && (
|
||||
<p role="status" className="text-sm text-text-secondary">
|
||||
Unsaved strategy metadata. Save or discard before leaving.
|
||||
</p>
|
||||
)}
|
||||
{saveError && (
|
||||
<p role="alert" className="text-error text-sm">
|
||||
{saveError}
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
className={actionClass}
|
||||
disabled={saving || !metadataDirty || !name.trim()}
|
||||
>
|
||||
Save metadata
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={saving || !metadataDirty}
|
||||
onClick={() => {
|
||||
if (confirmDiscard(metadataDirty)) {
|
||||
setName(strategy.name);
|
||||
setDescription(strategy.description);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Discard metadata changes
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={saving}
|
||||
onClick={() => {
|
||||
if (
|
||||
confirmDiscard(metadataDirty) &&
|
||||
window.confirm(
|
||||
strategy.archived
|
||||
? 'Restore this strategy family?'
|
||||
: 'Archive this strategy family? Saved versions and history remain available.'
|
||||
)
|
||||
) {
|
||||
void update({ archived: !strategy.archived });
|
||||
}
|
||||
}}
|
||||
>
|
||||
{strategy.archived ? 'Restore strategy' : 'Archive strategy'}
|
||||
</button>
|
||||
</form>
|
||||
<StrategyMetadataForm
|
||||
strategy={strategy}
|
||||
name={name}
|
||||
description={description}
|
||||
saving={saving}
|
||||
metadataDirty={metadataDirty}
|
||||
saveError={saveError}
|
||||
update={update}
|
||||
setName={setName}
|
||||
setDescription={setDescription}
|
||||
/>
|
||||
<CandidatePublication
|
||||
key={`publication:${strategyId}:${versionId ?? ''}`}
|
||||
strategyId={strategyId}
|
||||
|
|
@ -524,234 +429,6 @@ function StrategyDetail({ strategyId, versionId }: { strategyId: string; version
|
|||
</div>
|
||||
);
|
||||
}
|
||||
function VersionIdentity({ version }: { version: StrategyVersionSummary }) {
|
||||
const pkg = version.package;
|
||||
return (
|
||||
<div className="space-y-2 text-sm border border-border rounded-md p-4">
|
||||
<h3 className="font-medium">Version {version.ordinal}</h3>
|
||||
<p>
|
||||
Immutable version ID: <code>{version.id}</code>
|
||||
</p>
|
||||
<p>
|
||||
Origin: {version.origin} · Review: {version.reviewStatus}
|
||||
</p>
|
||||
<p role="status">
|
||||
{version.origin === 'candidate'
|
||||
? 'Candidate research uses the isolated runtime. Eligibility is checked against the retained package, dataset and financial policy.'
|
||||
: 'Canonical execution requires approval, a matching executable build, a supported dataset and an explicit simulation policy.'}
|
||||
</p>
|
||||
<p>
|
||||
Program: {pkg.program.strategyId} / {pkg.program.strategyVersion}
|
||||
</p>
|
||||
<p>
|
||||
API: {pkg.program.apiVersion} · Checkpoint: {pkg.program.checkpointVersion}
|
||||
</p>
|
||||
<p className="break-all">Artifact SHA256: {pkg.artifact.sha256}</p>
|
||||
<p className="break-all">Dependency lock SHA256: {pkg.dependencyLock.sha256}</p>
|
||||
<p className="break-all">
|
||||
Source revision: {pkg.source.revision} (
|
||||
{pkg.source.dirty ? 'dirty working tree' : 'clean working tree'})
|
||||
</p>
|
||||
<p>
|
||||
Build: {pkg.build.tool} {pkg.build.version} / {pkg.build.target}
|
||||
</p>
|
||||
{version.parentVersionId && <p>Parent version: {version.parentVersionId}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function VersionComparison({
|
||||
version,
|
||||
versions,
|
||||
}: {
|
||||
version: StrategyVersionSummary;
|
||||
versions: StrategyVersionSummary[];
|
||||
}) {
|
||||
const [showArtifact, setShowArtifact] = useState(false);
|
||||
const [compareId, setCompareId] = useState('');
|
||||
const [artifact, setArtifact] = useState<StrategyVersionPackage | null>(null);
|
||||
const [comparison, setComparison] = useState<StrategyVersionPackage | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [retry, setRetry] = useState(0);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setComparison(null);
|
||||
setError(null);
|
||||
if (!showArtifact && !compareId) {
|
||||
setLoading(false);
|
||||
return () => controller.abort();
|
||||
}
|
||||
setLoading(true);
|
||||
void Promise.all([
|
||||
strategyApi.artifact(version.id, controller.signal),
|
||||
compareId ? strategyApi.artifact(compareId, controller.signal) : Promise.resolve(null),
|
||||
])
|
||||
.then(([current, other]) => {
|
||||
if (!controller.signal.aborted) {
|
||||
setArtifact(current.package);
|
||||
setComparison(other?.package ?? null);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(cause.message);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [version.id, showArtifact, compareId, retry]);
|
||||
const options = versions.filter(item => item.id !== version.id);
|
||||
return (
|
||||
<section className="space-y-3">
|
||||
<button className={actionClass} onClick={() => setShowArtifact(value => !value)}>
|
||||
{showArtifact ? 'Hide bundled JavaScript' : 'View bundled JavaScript'}
|
||||
</button>
|
||||
<label className="block text-sm">
|
||||
Compare with version
|
||||
<select
|
||||
aria-label="Compare with version"
|
||||
className={fieldClass}
|
||||
value={compareId}
|
||||
onChange={event => setCompareId(event.target.value)}
|
||||
>
|
||||
<option value="">No comparison</option>
|
||||
{options.map(item => (
|
||||
<option key={item.id} value={item.id}>
|
||||
Version {item.ordinal} — {item.id}
|
||||
</option>
|
||||
))}
|
||||
{version.parentVersionId &&
|
||||
!options.some(item => item.id === version.parentVersionId) && (
|
||||
<option value={version.parentVersionId}>
|
||||
Parent version — {version.parentVersionId}
|
||||
</option>
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
{(showArtifact || compareId) && (
|
||||
<p className="text-sm text-text-secondary">
|
||||
Retained bundled JavaScript, not original TypeScript. Displayed as text; never executed in
|
||||
the browser.
|
||||
</p>
|
||||
)}
|
||||
{loading && <p role="status">Loading retained artifacts...</p>}
|
||||
{error && (
|
||||
<div>
|
||||
<p role="alert" className="text-error">
|
||||
{error}
|
||||
</p>
|
||||
<button className={actionClass} onClick={() => setRetry(value => value + 1)}>
|
||||
Retry artifacts
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{!loading && !error && artifact && (showArtifact || compareId) && (
|
||||
<>
|
||||
{comparison && (
|
||||
<>
|
||||
<h3 className="font-medium">Version comparison</h3>
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="text-left">Retained field</th>
|
||||
<th className="text-left">Comparison</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{(['program', 'parameterSchema', 'source', 'build'] as const).map(key => (
|
||||
<tr key={key}>
|
||||
<td>{key}</td>
|
||||
<td>
|
||||
{JSON.stringify(artifact[key]) === JSON.stringify(comparison[key])
|
||||
? 'Unchanged'
|
||||
: 'Changed'}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
<tr>
|
||||
<td>Artifact SHA256</td>
|
||||
<td>
|
||||
{artifact.artifact.sha256 === comparison.artifact.sha256
|
||||
? 'Identical artifact bytes'
|
||||
: 'Different artifact bytes'}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Dependency lock SHA256</td>
|
||||
<td>
|
||||
{artifact.dependencyLock.sha256 === comparison.dependencyLock.sha256
|
||||
? 'Unchanged'
|
||||
: 'Changed'}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div>
|
||||
<h4>Selected version metadata</h4>
|
||||
<pre className="overflow-auto text-xs max-h-64">
|
||||
{JSON.stringify(
|
||||
{
|
||||
program: artifact.program,
|
||||
parameterSchema: artifact.parameterSchema,
|
||||
source: artifact.source,
|
||||
build: artifact.build,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)}
|
||||
</pre>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Compared version metadata</h4>
|
||||
<pre className="overflow-auto text-xs max-h-64">
|
||||
{JSON.stringify(
|
||||
{
|
||||
program: comparison.program,
|
||||
parameterSchema: comparison.parameterSchema,
|
||||
source: comparison.source,
|
||||
build: comparison.build,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<div className={comparison ? 'grid gap-4 md:grid-cols-2' : ''}>
|
||||
<div>
|
||||
<h4>Selected bundled JavaScript</h4>
|
||||
<pre
|
||||
aria-label="Selected bundled JavaScript"
|
||||
className="overflow-auto max-h-96 text-xs p-3 border border-border rounded-md"
|
||||
>
|
||||
{artifact.artifact.content}
|
||||
</pre>
|
||||
</div>
|
||||
{comparison && (
|
||||
<div>
|
||||
<h4>Compared bundled JavaScript</h4>
|
||||
<pre
|
||||
aria-label="Compared bundled JavaScript"
|
||||
className="overflow-auto max-h-96 text-xs p-3 border border-border rounded-md"
|
||||
>
|
||||
{comparison.artifact.content}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** Saved backtests retain version identity without duplicating the mutable family metadata. */
|
||||
export function StrategyVersionPage() {
|
||||
const { versionId = '' } = useParams<{ versionId: string }>();
|
||||
|
|
|
|||
|
|
@ -0,0 +1,107 @@
|
|||
import type { StrategyRecord } from '@stock-bot/types';
|
||||
import { actionClass, fieldClass } from './StrategyParameterForm';
|
||||
import { confirmDiscard } from './useUnsavedWarning';
|
||||
|
||||
interface Props {
|
||||
strategy: StrategyRecord;
|
||||
name: string;
|
||||
description: string;
|
||||
saving: boolean;
|
||||
metadataDirty: boolean;
|
||||
saveError: string | null;
|
||||
update: (body: { name?: string; description?: string; archived?: boolean }) => Promise<void>;
|
||||
setName: (value: string) => void;
|
||||
setDescription: (value: string) => void;
|
||||
}
|
||||
export function StrategyMetadataForm({
|
||||
strategy,
|
||||
name,
|
||||
description,
|
||||
saving,
|
||||
metadataDirty,
|
||||
saveError,
|
||||
update,
|
||||
setName,
|
||||
setDescription,
|
||||
}: Props) {
|
||||
return (
|
||||
<form
|
||||
className="space-y-3 border border-border rounded-md p-4"
|
||||
onSubmit={event => {
|
||||
event.preventDefault();
|
||||
void update({ name, description });
|
||||
}}
|
||||
>
|
||||
<label className="block text-sm">
|
||||
Strategy name
|
||||
<input
|
||||
aria-label="Strategy name"
|
||||
className={fieldClass}
|
||||
required
|
||||
disabled={saving}
|
||||
value={name}
|
||||
onChange={event => setName(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-sm">
|
||||
Strategy description
|
||||
<textarea
|
||||
aria-label="Strategy description"
|
||||
className={fieldClass}
|
||||
disabled={saving}
|
||||
value={description}
|
||||
onChange={event => setDescription(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
{metadataDirty && (
|
||||
<p role="status" className="text-sm text-text-secondary">
|
||||
Unsaved strategy metadata. Save or discard before leaving.
|
||||
</p>
|
||||
)}
|
||||
{saveError && (
|
||||
<p role="alert" className="text-error text-sm">
|
||||
{saveError}
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
className={actionClass}
|
||||
disabled={saving || !metadataDirty || !name.trim()}
|
||||
>
|
||||
Save metadata
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={saving || !metadataDirty}
|
||||
onClick={() => {
|
||||
if (confirmDiscard(metadataDirty)) {
|
||||
setName(strategy.name);
|
||||
setDescription(strategy.description);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Discard metadata changes
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={saving}
|
||||
onClick={() => {
|
||||
if (
|
||||
confirmDiscard(metadataDirty) &&
|
||||
window.confirm(
|
||||
strategy.archived
|
||||
? 'Restore this strategy family?'
|
||||
: 'Archive this strategy family? Saved versions and history remain available.'
|
||||
)
|
||||
) {
|
||||
void update({ archived: !strategy.archived });
|
||||
}
|
||||
}}
|
||||
>
|
||||
{strategy.archived ? 'Restore strategy' : 'Archive strategy'}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,232 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import type { StrategyVersionPackage, StrategyVersionSummary } from '@stock-bot/types';
|
||||
import { strategyApi } from '../services/strategyApi';
|
||||
import { actionClass, fieldClass } from './StrategyParameterForm';
|
||||
|
||||
export function VersionIdentity({ version }: { version: StrategyVersionSummary }) {
|
||||
const pkg = version.package;
|
||||
return (
|
||||
<div className="space-y-2 text-sm border border-border rounded-md p-4">
|
||||
<h3 className="font-medium">Version {version.ordinal}</h3>
|
||||
<p>
|
||||
Immutable version ID: <code>{version.id}</code>
|
||||
</p>
|
||||
<p>
|
||||
Origin: {version.origin} · Review: {version.reviewStatus}
|
||||
</p>
|
||||
<p role="status">
|
||||
{version.origin === 'candidate'
|
||||
? 'Candidate research uses the isolated runtime. Eligibility is checked against the retained package, dataset and financial policy.'
|
||||
: 'Canonical execution requires approval, a matching executable build, a supported dataset and an explicit simulation policy.'}
|
||||
</p>
|
||||
<p>
|
||||
Program: {pkg.program.strategyId} / {pkg.program.strategyVersion}
|
||||
</p>
|
||||
<p>
|
||||
API: {pkg.program.apiVersion} · Checkpoint: {pkg.program.checkpointVersion}
|
||||
</p>
|
||||
<p className="break-all">Artifact SHA256: {pkg.artifact.sha256}</p>
|
||||
<p className="break-all">Dependency lock SHA256: {pkg.dependencyLock.sha256}</p>
|
||||
<p className="break-all">
|
||||
Source revision: {pkg.source.revision} (
|
||||
{pkg.source.dirty ? 'dirty working tree' : 'clean working tree'})
|
||||
</p>
|
||||
<p>
|
||||
Build: {pkg.build.tool} {pkg.build.version} / {pkg.build.target}
|
||||
</p>
|
||||
{version.parentVersionId && <p>Parent version: {version.parentVersionId}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export function VersionComparison({
|
||||
version,
|
||||
versions,
|
||||
}: {
|
||||
version: StrategyVersionSummary;
|
||||
versions: StrategyVersionSummary[];
|
||||
}) {
|
||||
const [showArtifact, setShowArtifact] = useState(false);
|
||||
const [compareId, setCompareId] = useState('');
|
||||
const [artifact, setArtifact] = useState<StrategyVersionPackage | null>(null);
|
||||
const [comparison, setComparison] = useState<StrategyVersionPackage | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [retry, setRetry] = useState(0);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setComparison(null);
|
||||
setError(null);
|
||||
if (!showArtifact && !compareId) {
|
||||
setLoading(false);
|
||||
return () => controller.abort();
|
||||
}
|
||||
setLoading(true);
|
||||
void Promise.all([
|
||||
strategyApi.artifact(version.id, controller.signal),
|
||||
compareId ? strategyApi.artifact(compareId, controller.signal) : Promise.resolve(null),
|
||||
])
|
||||
.then(([current, other]) => {
|
||||
if (!controller.signal.aborted) {
|
||||
setArtifact(current.package);
|
||||
setComparison(other?.package ?? null);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(cause.message);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [version.id, showArtifact, compareId, retry]);
|
||||
const options = versions.filter(item => item.id !== version.id);
|
||||
return (
|
||||
<section className="space-y-3">
|
||||
<button className={actionClass} onClick={() => setShowArtifact(value => !value)}>
|
||||
{showArtifact ? 'Hide bundled JavaScript' : 'View bundled JavaScript'}
|
||||
</button>
|
||||
<label className="block text-sm">
|
||||
Compare with version
|
||||
<select
|
||||
aria-label="Compare with version"
|
||||
className={fieldClass}
|
||||
value={compareId}
|
||||
onChange={event => setCompareId(event.target.value)}
|
||||
>
|
||||
<option value="">No comparison</option>
|
||||
{options.map(item => (
|
||||
<option key={item.id} value={item.id}>
|
||||
Version {item.ordinal} — {item.id}
|
||||
</option>
|
||||
))}
|
||||
{version.parentVersionId &&
|
||||
!options.some(item => item.id === version.parentVersionId) && (
|
||||
<option value={version.parentVersionId}>
|
||||
Parent version — {version.parentVersionId}
|
||||
</option>
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
{(showArtifact || compareId) && (
|
||||
<p className="text-sm text-text-secondary">
|
||||
Retained bundled JavaScript, not original TypeScript. Displayed as text; never executed in
|
||||
the browser.
|
||||
</p>
|
||||
)}
|
||||
{loading && <p role="status">Loading retained artifacts...</p>}
|
||||
{error && (
|
||||
<div>
|
||||
<p role="alert" className="text-error">
|
||||
{error}
|
||||
</p>
|
||||
<button className={actionClass} onClick={() => setRetry(value => value + 1)}>
|
||||
Retry artifacts
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{!loading && !error && artifact && (showArtifact || compareId) && (
|
||||
<>
|
||||
{comparison && (
|
||||
<>
|
||||
<h3 className="font-medium">Version comparison</h3>
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="text-left">Retained field</th>
|
||||
<th className="text-left">Comparison</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{(['program', 'parameterSchema', 'source', 'build'] as const).map(key => (
|
||||
<tr key={key}>
|
||||
<td>{key}</td>
|
||||
<td>
|
||||
{JSON.stringify(artifact[key]) === JSON.stringify(comparison[key])
|
||||
? 'Unchanged'
|
||||
: 'Changed'}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
<tr>
|
||||
<td>Artifact SHA256</td>
|
||||
<td>
|
||||
{artifact.artifact.sha256 === comparison.artifact.sha256
|
||||
? 'Identical artifact bytes'
|
||||
: 'Different artifact bytes'}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Dependency lock SHA256</td>
|
||||
<td>
|
||||
{artifact.dependencyLock.sha256 === comparison.dependencyLock.sha256
|
||||
? 'Unchanged'
|
||||
: 'Changed'}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div>
|
||||
<h4>Selected version metadata</h4>
|
||||
<pre className="overflow-auto text-xs max-h-64">
|
||||
{JSON.stringify(
|
||||
{
|
||||
program: artifact.program,
|
||||
parameterSchema: artifact.parameterSchema,
|
||||
source: artifact.source,
|
||||
build: artifact.build,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)}
|
||||
</pre>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Compared version metadata</h4>
|
||||
<pre className="overflow-auto text-xs max-h-64">
|
||||
{JSON.stringify(
|
||||
{
|
||||
program: comparison.program,
|
||||
parameterSchema: comparison.parameterSchema,
|
||||
source: comparison.source,
|
||||
build: comparison.build,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<div className={comparison ? 'grid gap-4 md:grid-cols-2' : ''}>
|
||||
<div>
|
||||
<h4>Selected bundled JavaScript</h4>
|
||||
<pre
|
||||
aria-label="Selected bundled JavaScript"
|
||||
className="overflow-auto max-h-96 text-xs p-3 border border-border rounded-md"
|
||||
>
|
||||
{artifact.artifact.content}
|
||||
</pre>
|
||||
</div>
|
||||
{comparison && (
|
||||
<div>
|
||||
<h4>Compared bundled JavaScript</h4>
|
||||
<pre
|
||||
aria-label="Compared bundled JavaScript"
|
||||
className="overflow-auto max-h-96 text-xs p-3 border border-border rounded-md"
|
||||
>
|
||||
{comparison.artifact.content}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,80 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { NavigateFunction } from 'react-router-dom';
|
||||
import type { StrategyVersionSummary } from '@stock-bot/types';
|
||||
import { versionPath } from '../components/StrategySelection';
|
||||
import { strategyApi } from '../services/strategyApi';
|
||||
|
||||
/** Own the immutable clone receipt for the lifetime of the strategy route. */
|
||||
export function useStrategyClone(
|
||||
version: StrategyVersionSummary | null,
|
||||
versionId: string | undefined,
|
||||
navigate: NavigateFunction
|
||||
) {
|
||||
const [cloneOpen, setCloneOpen] = useState(false);
|
||||
const [cloneName, setCloneName] = useState('');
|
||||
const [cloneDescription, setCloneDescription] = useState('');
|
||||
const [cloning, setCloning] = useState(false);
|
||||
const [cloneError, setCloneError] = useState<string | null>(null);
|
||||
const cloneIntent = useRef<{
|
||||
versionId: string;
|
||||
versionOrdinal: number;
|
||||
body: { name: string; description: string };
|
||||
key: string;
|
||||
} | null>(null);
|
||||
const [cloneFrozen, setCloneFrozen] = useState(false);
|
||||
const mounted = useRef(true);
|
||||
const selectedVersionId = useRef(versionId);
|
||||
selectedVersionId.current = versionId;
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
return () => {
|
||||
mounted.current = false;
|
||||
};
|
||||
}, []);
|
||||
const clone = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (!version || cloning || !cloneName.trim()) {
|
||||
return;
|
||||
}
|
||||
const intent = (cloneIntent.current ??= {
|
||||
versionId: version.id,
|
||||
versionOrdinal: version.ordinal,
|
||||
body: { name: cloneName, description: cloneDescription },
|
||||
key: crypto.randomUUID(),
|
||||
});
|
||||
setCloneFrozen(true);
|
||||
setCloning(true);
|
||||
setCloneError(null);
|
||||
try {
|
||||
const result = await strategyApi.clone(intent.versionId, intent.body, intent.key);
|
||||
if (mounted.current && selectedVersionId.current === intent.versionId) {
|
||||
navigate(versionPath(result.version));
|
||||
}
|
||||
} catch (cause) {
|
||||
if (mounted.current && selectedVersionId.current === intent.versionId) {
|
||||
setCloneError(
|
||||
`${cause instanceof Error ? cause.message : 'Clone failed'}. Retry clone to recover the same immutable version.`
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (mounted.current) {
|
||||
setCloning(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
return {
|
||||
cloneOpen,
|
||||
setCloneOpen,
|
||||
cloneName,
|
||||
setCloneName,
|
||||
cloneDescription,
|
||||
setCloneDescription,
|
||||
cloning,
|
||||
cloneError,
|
||||
setCloneError,
|
||||
cloneIntent,
|
||||
cloneFrozen,
|
||||
setCloneFrozen,
|
||||
clone,
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue