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,
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue