Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(web): isolate run detail state by route

xkam7ar691a9bcc852d
diff --git a/frontend/src/pages/RunDetail.tsx b/frontend/src/pages/RunDetail.tsx
index 81b14cbc6..235028650 100644
--- a/frontend/src/pages/RunDetail.tsx
+++ b/frontend/src/pages/RunDetail.tsx
@@ -106,6 +106,7 @@ export function RunDetail() {
const [bulkChartProgress, setBulkChartProgress] = useState<ChartLoadProgress>({ done: 0, total: 0 });
const chartCacheRef = useRef<ChartCache>({});
const cancelBulkChartLoadRef = useRef(false);
+ const runGenerationRef = useRef(0);
const hasValidation = !!run?.validation;
const hasRunCard = !!run?.run_card;
@@ -118,11 +119,32 @@ export function RunDetail() {
];
useEffect(() => {
- if (!runId) return;
+ const generation = ++runGenerationRef.current;
+ cancelBulkChartLoadRef.current = true;
+ setRun(null);
+ setCode({});
+ setTab("chart");
+ setLoading(true);
+ setSelectedSymbol("");
+ setChartPickerSymbol("");
+ setSelectedSymbols([]);
+ chartCacheRef.current = {};
+ setChartCache({});
+ setChartLoadingSymbols({});
+ setBulkChartLoading(false);
+ setBulkChartProgress({ done: 0, total: 0 });
+
+ if (!runId) {
+ setLoading(false);
+ return;
+ }
+
+ const requestedRunId = runId;
Promise.all([
- api.getRun(runId, { chart_payload: "summary" }).catch(() => null),
- api.getRunCode(runId).catch(() => ({})),
+ api.getRun(requestedRunId, { chart_payload: "summary" }).catch(() => null),
+ api.getRunCode(requestedRunId).catch(() => ({})),
]).then(([r, c]) => {
+ if (runGenerationRef.current !== generation) return;
setRun(r);
setCode(c || {});
const firstSymbol = r?.chart_symbols?.[0] || Object.keys(r?.price_series || {})[0] || "";
@@ -133,9 +155,16 @@ export function RunDetail() {
chartCacheRef.current = initialCache;
setChartCache(initialCache);
if (firstSymbol && !initialCache[firstSymbol]?.price_series?.[firstSymbol]?.length) {
- void loadChartSymbol(firstSymbol);
+ void loadChartSymbol(firstSymbol, requestedRunId, generation);
}
- }).finally(() => setLoading(false));
+ }).finally(() => {
+ if (runGenerationRef.current === generation) setLoading(false);
+ });
+
+ return () => {
+ cancelBulkChartLoadRef.current = true;
+ if (runGenerationRef.current === generation) runGenerationRef.current += 1;
+ };
}, [runId]);
if (loading) {
@@ -165,12 +194,17 @@ export function RunDetail() {
const ok = run.status === "success";
- async function loadChartSymbol(symbol: string) {
- if (!runId || !symbol) return;
+ async function loadChartSymbol(
+ symbol: string,
+ requestedRunId = runId,
+ generation = runGenerationRef.current,
+ ) {
+ if (!requestedRunId || !symbol || runGenerationRef.current !== generation) return;
if (chartCacheRef.current[symbol]?.price_series?.[symbol]?.length) return;
setChartLoadingSymbols((prev) => ({ ...prev, [symbol]: true }));
try {
- const nextRun = await api.getRun(runId, { chart_symbol: symbol });
+ const nextRun = await api.getRun(requestedRunId, { chart_symbol: symbol });
+ if (runGenerationRef.current !== generation) return;
const nextCache = cacheFromRun(nextRun, symbol);
const mergedCache = { ...chartCacheRef.current, ...nextCache };
chartCacheRef.current = mergedCache;
@@ -182,11 +216,13 @@ export function RunDetail() {
trade_log: nextRun.trade_log?.length ? nextRun.trade_log : prev.trade_log,
} : nextRun);
} finally {
- setChartLoadingSymbols((prev) => {
- const next = { ...prev };
- delete next[symbol];
- return next;
- });
+ if (runGenerationRef.current === generation) {
+ setChartLoadingSymbols((prev) => {
+ const next = { ...prev };
+ delete next[symbol];
+ return next;
+ });
+ }
}
}
@@ -219,22 +255,25 @@ export function RunDetail() {
async function handleLoadAllChartSymbols() {
const symbols = run?.chart_symbols || [];
if (symbols.length === 0 || bulkChartLoading) return;
+ const generation = runGenerationRef.current;
+ const requestedRunId = runId;
cancelBulkChartLoadRef.current = false;
setBulkChartLoading(true);
setBulkChartProgress({ done: 0, total: symbols.length });
try {
for (let index = 0; index < symbols.length; index += 1) {
- if (cancelBulkChartLoadRef.current) break;
+ if (cancelBulkChartLoadRef.current || runGenerationRef.current !== generation) break;
const symbol = symbols[index];
setSelectedSymbol(symbol);
setChartPickerSymbol(symbol);
setSelectedSymbols((prev) => prev.includes(symbol) ? prev : [...prev, symbol]);
- await loadChartSymbol(symbol);
+ await loadChartSymbol(symbol, requestedRunId, generation);
+ if (runGenerationRef.current !== generation) break;
setBulkChartProgress({ done: index + 1, total: symbols.length });
await yieldToBrowser();
}
} finally {
- setBulkChartLoading(false);
+ if (runGenerationRef.current === generation) setBulkChartLoading(false);
}
}
diff --git a/frontend/src/pages/__tests__/RunDetail.test.tsx b/frontend/src/pages/__tests__/RunDetail.test.tsx
new file mode 100644
index 000000000..9d223c567
--- /dev/null
+++ b/frontend/src/pages/__tests__/RunDetail.test.tsx
@@ -0,0 +1,109 @@
+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { createMemoryRouter, RouterProvider } from "react-router-dom";
+import { RunDetail } from "../RunDetail";
+import type { RunData } from "@/lib/api";
+
+const apiMock = vi.hoisted(() => ({
+ getRun: vi.fn(),
+ getRunCode: vi.fn(),
+}));
+
+vi.mock("@/lib/api", () => ({ api: apiMock }));
+vi.mock("@/components/charts/CandlestickChart", () => ({
+ CandlestickChart: () => <div data-testid="candlestick-chart" />,
+}));
+vi.mock("@/components/charts/EquityChart", () => ({
+ EquityChart: () => <div data-testid="equity-chart" />,
+}));
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((res) => {
+ resolve = res;
+ });
+ return { promise, resolve };
+}
+
+function renderRunDetail(path = "/runs/old") {
+ const router = createMemoryRouter(
+ [{ path: "/runs/:runId", element: <RunDetail /> }],
+ { initialEntries: [path] },
+ );
+ render(<RouterProvider router={router} />);
+ return router;
+}
+
+describe("RunDetail page", () => {
+ beforeEach(() => {
+ apiMock.getRun.mockReset();
+ apiMock.getRunCode.mockReset();
+ });
+
+ it("does not let an older route load replace the current run or code", async () => {
+ const oldRun = deferred<RunData>();
+ const oldCode = deferred<Record<string, string>>();
+ const newRun = deferred<RunData>();
+ const newCode = deferred<Record<string, string>>();
+
+ apiMock.getRun.mockImplementation((runId: string) => runId === "old" ? oldRun.promise : newRun.promise);
+ apiMock.getRunCode.mockImplementation((runId: string) => runId === "old" ? oldCode.promise : newCode.promise);
+
+ const router = renderRunDetail();
+ await act(async () => { await router.navigate("/runs/new"); });
+
+ await act(async () => {
+ newRun.resolve({ status: "success", run_id: "new", prompt: "New run" });
+ newCode.resolve({ "new.py": "NEW_CODE" });
+ await Promise.all([newRun.promise, newCode.promise]);
+ });
+ expect(await screen.findByText("New run")).toBeInTheDocument();
+
+ await act(async () => {
+ oldRun.resolve({ status: "success", run_id: "old", prompt: "Old run" });
+ oldCode.resolve({ "old.py": "OLD_CODE" });
+ await Promise.all([oldRun.promise, oldCode.promise]);
+ });
+
+ expect(screen.getByText("New run")).toBeInTheDocument();
+ expect(screen.queryByText("Old run")).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Code" }));
+ expect(await screen.findByText("NEW_CODE")).toBeInTheDocument();
+ expect(screen.queryByText("OLD_CODE")).not.toBeInTheDocument();
+ });
+
+ it("ignores a chart response that finishes after the route changes", async () => {
+ const oldChart = deferred<RunData>();
+ apiMock.getRun.mockImplementation((runId: string, params: Record<string, string>) => {
+ if (runId === "old" && params.chart_payload === "summary") {
+ return Promise.resolve({ status: "success", run_id: "old", prompt: "Old run", chart_symbols: ["OLD"] });
+ }
+ if (runId === "old" && params.chart_symbol === "OLD") return oldChart.promise;
+ return Promise.resolve({ status: "success", run_id: "new", prompt: "New run" });
+ });
+ apiMock.getRunCode.mockResolvedValue({});
+
+ const router = renderRunDetail();
+ expect(await screen.findByText("Old run")).toBeInTheDocument();
+ await waitFor(() => {
+ expect(apiMock.getRun).toHaveBeenCalledWith("old", { chart_symbol: "OLD" });
+ });
+
+ await act(async () => { await router.navigate("/runs/new"); });
+ expect(await screen.findByText("New run")).toBeInTheDocument();
+
+ await act(async () => {
+ oldChart.resolve({
+ status: "success",
+ run_id: "old",
+ chart_symbols: ["OLD"],
+ trade_log: [{ note: "OLD TRADE" }],
+ });
+ await oldChart.promise;
+ });
+
+ expect(screen.getByText("New run")).toBeInTheDocument();
+ expect(screen.queryByRole("option", { name: "OLD" })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Trades" }));
+ expect(screen.queryByText("OLD TRADE")).not.toBeInTheDocument();
+ });
+});