"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(reports): add interactive backtest research dashboard
AndyLongest50bc8fab6519
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.pyindex a450c2243..d2038e276 100644--- a/agent/cli/_legacy.py+++ b/agent/cli/_legacy.py@@ -1503,6 +1503,15 @@ def cmd_run(prompt: str, max_iter: int, *, json_mode: bool = False, no_rich: boo_print_json_result(result)return _result_exit_code(result)_print_result(result, time.perf_counter() - start, no_rich=no_rich)+ from cli.report_server import ensure_report_server, load_backtest_metrics++ if result.get("run_id") and load_backtest_metrics(result.get("run_dir")):+ report_url = ensure_report_server(str(result["run_id"]))+ if report_url:+ if no_rich:+ print(f"Dashboard: {report_url}")+ else:+ console.print(f"[bold]Dashboard:[/bold] [link={report_url}]{report_url}[/link]")if result.get("run_id"):tip = f"--show {result['run_id']} | --continue {result['run_id']} \"...\" | --code {result['run_id']} | --pine {result['run_id']}"if no_rich:diff --git a/agent/cli/main.py b/agent/cli/main.pyindex 8694b5e17..9ad6cf90c 100644--- a/agent/cli/main.py+++ b/agent/cli/main.py@@ -21,7 +21,6 @@ from __future__ import annotationsimport importlibimport logging-import osimport sysimport threadingimport time@@ -777,15 +776,42 @@ def _print_interactive_result(console: Any, result: Dict[str, Any], elapsed: flo"""Print the assistant answer after the rail without boxed run panels."""from cli.ui.transcript import render_answer, render_elapsed_status+ from cli.report_server import ensure_report_server, load_backtest_metricscontent = (result.get("content") or "").strip()if content:console.print(render_answer(content))console.print()- console.print(render_elapsed_status(elapsed))run_id = result.get("run_id")- if run_id:+ metrics = load_backtest_metrics(result.get("run_dir"))+ if run_id and metrics:+ console.print("[bold green]✓ 回测完成[/bold green]")+ metric_rows = (+ ("总收益率", "total_return", True),+ ("年化收益率", "annual_return", True),+ ("Sharpe", "sharpe", False),+ ("最大回撤", "max_drawdown", True),+ ("胜率", "win_rate", True),+ ("交易次数", "trade_count", False),+ )+ for label, key, as_percent in metric_rows:+ value = metrics.get(key)+ if value is None:+ continue+ rendered = f"{value * 100:.1f}%" if as_percent else (+ f"{int(value)}" if key == "trade_count" else f"{value:.2f}"+ )+ console.print(f" {label:<10} [bold]{rendered}[/bold]")+ console.print()+ console.print(f"[bold]Run ID:[/bold] [cyan]{run_id}[/cyan]")+ report_url = ensure_report_server(str(run_id))+ if report_url:+ console.print(f"[bold]报告:[/bold] [link={report_url}]{report_url}[/link]")+ else:+ console.print("[yellow]报告服务未能启动;回测产物已经安全保存。[/yellow]")+ elif run_id:console.print(f"[dim]/show {run_id} · {elapsed:.1f}s[/dim]")+ console.print(render_elapsed_status(elapsed))def _print_recap_if_needed(console: Any, ctx: InteractiveContext) -> None:diff --git a/agent/cli/report_server.py b/agent/cli/report_server.pynew file mode 100644index 000000000..514398852--- /dev/null+++ b/agent/cli/report_server.py@@ -0,0 +1,137 @@+"""Quiet local report-server bootstrap for interactive backtest runs."""++from __future__ import annotations++import csv+import os+import socket+import subprocess+import sys+import time+from pathlib import Path+from typing import Any+from urllib.error import HTTPError, URLError+from urllib.parse import quote+from urllib.request import Request, urlopen+++DEFAULT_REPORT_PORT = 8000+_SPAWNED_PROCESSES: list[subprocess.Popen[Any]] = []+++def load_backtest_metrics(run_dir: str | Path | None) -> dict[str, float]:+ """Read the scalar metrics row that proves a turn produced a backtest."""+ if not run_dir:+ return {}+ path = Path(run_dir) / "artifacts" / "metrics.csv"+ try:+ with path.open("r", encoding="utf-8", newline="") as handle:+ row = next(csv.DictReader(handle), None) or {}+ except (OSError, csv.Error):+ return {}++ metrics: dict[str, float] = {}+ for key, value in row.items():+ try:+ metrics[str(key)] = float(value)+ except (TypeError, ValueError):+ continue+ return metrics+++def _candidate_ports() -> list[int]:+ raw = os.environ.get("VIBE_TRADING_REPORT_PORT", "").strip()+ try:+ preferred = int(raw) if raw else DEFAULT_REPORT_PORT+ except ValueError:+ preferred = DEFAULT_REPORT_PORT+ preferred = preferred if 1 <= preferred <= 65535 else DEFAULT_REPORT_PORT++ candidates = [preferred, DEFAULT_REPORT_PORT, 8899]+ candidates.extend(port for port in range(preferred + 1, min(preferred + 7, 65536)))+ return list(dict.fromkeys(candidates))+++def _port_is_open(port: int) -> bool:+ try:+ with socket.create_connection(("127.0.0.1", port), timeout=0.2):+ return True+ except OSError:+ return False+++def _run_url(port: int, run_id: str) -> str:+ return f"http://127.0.0.1:{port}/runs/{quote(run_id, safe='')}?view=dashboard"+++def _vibe_report_ready(port: int, run_id: str) -> bool:+ headers: dict[str, str] = {"Accept": "application/json"}+ api_key = os.environ.get("API_AUTH_KEY", "").strip()+ if api_key:+ headers["Authorization"] = f"Bearer {api_key}"+ request = Request(_run_url(port, run_id), headers=headers)+ try:+ with urlopen(request, timeout=0.6) as response: # noqa: S310 - fixed loopback URL+ return response.status == 200+ except (HTTPError, URLError, OSError, TimeoutError):+ return False+++def _spawn_report_server(port: int) -> subprocess.Popen[Any] | None:+ agent_dir = Path(__file__).resolve().parents[1]+ command = [+ sys.executable,+ "-m",+ "cli._legacy",+ "serve",+ "--host",+ "127.0.0.1",+ "--port",+ str(port),+ ]+ kwargs: dict[str, Any] = {+ "cwd": str(agent_dir),+ "stdin": subprocess.DEVNULL,+ "stdout": subprocess.DEVNULL,+ "stderr": subprocess.DEVNULL,+ }+ if os.name == "nt":+ kwargs["creationflags"] = (+ getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000)+ | getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0x00000200)+ )+ else:+ kwargs["start_new_session"] = True+ try:+ process = subprocess.Popen(command, **kwargs)+ except OSError:+ return None+ _SPAWNED_PROCESSES.append(process)+ return process+++def ensure_report_server(run_id: str, *, timeout_seconds: float = 30.0) -> str | None:+ """Return a working report URL, quietly starting a loopback server if needed."""+ if not run_id:+ return None++ candidates = _candidate_ports()+ for port in candidates:+ if _vibe_report_ready(port, run_id):+ return _run_url(port, run_id)++ port = next((candidate for candidate in candidates if not _port_is_open(candidate)), None)+ if port is None:+ return None+ process = _spawn_report_server(port)+ if process is None:+ return None++ deadline = time.monotonic() + max(0.1, timeout_seconds)+ while time.monotonic() < deadline:+ if _vibe_report_ready(port, run_id):+ return _run_url(port, run_id)+ if process.poll() is not None:+ return None+ time.sleep(0.15)+ return Nonediff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex 15181811c..5ee4bb774 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -18,6 +18,7 @@ import copyimport jsonimport loggingimport queue+import shutilimport sysimport threadingimport time as _time@@ -47,7 +48,7 @@ from src.providers.content_filter import (from src.config.accessor import get_env_configfrom src.config.paths import get_runs_dir, get_sessions_dirfrom src.tools.background_tools import get_background_manager-from src.config.limits import TOOL_RESULT_LIMIT, truncate_tool_result+from src.config.limits import truncate_tool_resultfrom src.tools.redaction import redact_payload, redact_tool_resultRUNS_DIR = get_runs_dir()@@ -577,6 +578,52 @@ def _normalize_tool_run_dir(args: dict[str, Any], memory_run_dir: str | None) ->return normalized+def _archive_backtest_result(result: str, active_run_dir: str | None) -> bool:+ """Copy a successful detached backtest into the active, reportable run.++ The model may choose another allowed run directory while iterating. The+ CLI and web API, however, identify the turn by ``active_run_dir``. Keep+ that public identity stable by copying only deterministic backtest output+ into the active run as soon as the backtest tool succeeds.+ """+ if not active_run_dir:+ return False+ try:+ payload = json.loads(result)+ except (json.JSONDecodeError, TypeError):+ return False+ if not isinstance(payload, dict):+ return False++ source_value = payload.get("run_dir")+ if not source_value:+ return False+ source = Path(str(source_value)).resolve()+ target = Path(active_run_dir).resolve()+ if source == target or not (source / "artifacts" / "metrics.csv").is_file():+ return False++ target.mkdir(parents=True, exist_ok=True)+ for directory in ("artifacts", "code", "logs"):+ source_dir = source / directory+ if source_dir.is_dir():+ shutil.copytree(source_dir, target / directory, dirs_exist_ok=True)+ for filename in (+ "config.json",+ "design_spec.json",+ "planner_output.json",+ "rag_metadata.json",+ "review_report.json",+ "run_card.json",+ "run_card.md",+ "llm_usage.json",+ ):+ source_file = source / filename+ if source_file.is_file():+ shutil.copy2(source_file, target / filename)+ return (target / "artifacts" / "metrics.csv").is_file()++class AgentLoop:"""ReAct Agent core loop.@@ -1822,6 +1869,11 @@ class AgentLoop:success = _is_tool_success(result)if success:self._called_ok.add(tc.name)+ if tc.name == "backtest":+ try:+ _archive_backtest_result(result, self.memory.run_dir)+ except OSError as exc:+ logger.warning("Could not archive backtest output into active run: %s", exc)if self._grounding is not None:self._grounding.ingest_tool_result(diff --git a/agent/src/api/models.py b/agent/src/api/models.pyindex 18733a45e..7d05379eb 100644--- a/agent/src/api/models.py+++ b/agent/src/api/models.py@@ -60,6 +60,7 @@ class RunResponse(BaseModel):run_id: str = Field(..., description="Run identifier")elapsed_seconds: float = Field(..., description="Execution time in seconds")reason: Optional[str] = Field(None, description="Failure reason when available")+ prompt: Optional[str] = Field(None, description="Original natural-language request")planner_output: Optional[Dict[str, Any]] = Field(None, description="Planner output")strategy_spec: Optional[Dict[str, Any]] = Field(None, description="Strategy specification")diff --git a/agent/src/api/runs_routes.py b/agent/src/api/runs_routes.pyindex c3e064b73..7bb82ffca 100644--- a/agent/src/api/runs_routes.py+++ b/agent/src/api/runs_routes.py@@ -89,6 +89,9 @@ def _build_response_from_run_dir(else:response.status = "unknown"+ request_data = _load_json_file(run_dir / "req.json") or {}+ response.prompt = request_data.get("prompt") or request_data.get("request")+planner_path = run_dir / "planner_output.json"response.planner_output = _load_json_file(planner_path)diff --git a/agent/tests/test_cli_report_server.py b/agent/tests/test_cli_report_server.pynew file mode 100644index 000000000..0fdd8b774--- /dev/null+++ b/agent/tests/test_cli_report_server.py@@ -0,0 +1,93 @@+from __future__ import annotations++from pathlib import Path++from rich.console import Console+from unittest.mock import Mock++from cli import report_server+++def test_load_backtest_metrics_reads_scalar_row(tmp_path: Path) -> None:+ artifacts = tmp_path / "artifacts"+ artifacts.mkdir()+ (artifacts / "metrics.csv").write_text(+ "total_return,annual_return,sharpe,max_drawdown,win_rate,trade_count\n"+ "0.824,0.131,1.08,-0.187,0.564,42\n",+ encoding="utf-8",+ )++ metrics = report_server.load_backtest_metrics(tmp_path)++ assert metrics["total_return"] == 0.824+ assert metrics["trade_count"] == 42+++def test_ensure_report_server_reuses_running_local_server(monkeypatch) -> None:+ monkeypatch.setattr(report_server, "_candidate_ports", lambda: [8123])+ monkeypatch.setattr(report_server, "_vibe_report_ready", lambda port, run_id: True)++ url = report_server.ensure_report_server("run 1")++ assert url == "http://127.0.0.1:8123/runs/run%201?view=dashboard"+++def test_interactive_backtest_result_prints_metrics_and_dashboard_link(tmp_path: Path, monkeypatch) -> None:+ from cli.main import _print_interactive_result++ artifacts = tmp_path / "artifacts"+ artifacts.mkdir()+ (artifacts / "metrics.csv").write_text(+ "total_return,annual_return,sharpe,max_drawdown,win_rate,trade_count\n"+ "0.824,0.131,1.08,-0.187,0.564,42\n",+ encoding="utf-8",+ )+ monkeypatch.setattr(+ report_server,+ "ensure_report_server",+ lambda run_id: f"http://127.0.0.1:8000/runs/{run_id}?view=dashboard",+ )+ console = Console(record=True, force_terminal=False, color_system=None, width=100)++ _print_interactive_result(+ console,+ {"status": "success", "run_id": "run_123", "run_dir": str(tmp_path), "content": "Done."},+ 3.5,+ )+ output = console.export_text()++ assert "82.4%" in output+ assert "Sharpe" in output and "1.08" in output+ assert "run_123" in output+ assert "http://127.0.0.1:8000/runs/run_123?view=dashboard" in output+++def test_single_prompt_run_prints_dashboard_link(tmp_path: Path, monkeypatch) -> None:+ from cli import _legacy+ from src import preflight++ artifacts = tmp_path / "artifacts"+ artifacts.mkdir()+ (artifacts / "metrics.csv").write_text("total_return\n0.1\n", encoding="utf-8")+ result = {+ "status": "success",+ "run_id": "single-run",+ "run_dir": str(tmp_path),+ "content": "Done.",+ }+ monkeypatch.setattr(preflight, "run_preflight", lambda console: [])+ monkeypatch.setattr(_legacy, "_ensure_session_id", lambda prompt: "session")+ monkeypatch.setattr(_legacy, "_run_agent", lambda *args, **kwargs: result)+ monkeypatch.setattr(_legacy, "_print_result", Mock())+ monkeypatch.setattr(+ report_server,+ "ensure_report_server",+ lambda run_id: f"http://127.0.0.1:8000/runs/{run_id}?view=dashboard",+ )+ test_console = Console(record=True, force_terminal=False, color_system=None, width=100)+ monkeypatch.setattr(_legacy, "console", test_console)++ exit_code = _legacy.cmd_run("Backtest AAPL", 10)++ assert exit_code == 0+ assert "http://127.0.0.1:8000/runs/single-run?view=dashboard" in test_console.export_text()diff --git a/agent/tests/test_loop_helpers.py b/agent/tests/test_loop_helpers.pyindex 4a6c8c622..0f684e8d2 100644--- a/agent/tests/test_loop_helpers.py+++ b/agent/tests/test_loop_helpers.py@@ -6,8 +6,6 @@ import jsonimport osfrom pathlib import Path-import pytest-from src.agent.loop import (KEEP_RECENT,COLLAPSE_PRESERVE_RECENT,@@ -19,6 +17,7 @@ from src.agent.loop import (_fix_tool_pairs,_is_tool_success,_normalize_tool_run_dir,+ _archive_backtest_result,)@@ -327,3 +326,39 @@ class TestNormalizeToolRunDir:args = {"run_dir": absolute_run_dir}out = _normalize_tool_run_dir(args, "/tmp/run_123")assert out["run_dir"] == absolute_run_dir+++class TestArchiveBacktestResult:+ def test_copies_detached_backtest_into_active_run(self, tmp_path: Path) -> None:+ source = tmp_path / "detached"+ active = tmp_path / "active"+ (source / "artifacts").mkdir(parents=True)+ (source / "code").mkdir()+ (source / "artifacts" / "metrics.csv").write_text(+ "total_return,sharpe\n0.12,1.1\n", encoding="utf-8"+ )+ (source / "artifacts" / "equity.csv").write_text(+ "timestamp,equity\n2026-01-01,1\n", encoding="utf-8"+ )+ (source / "code" / "signal_engine.py").write_text("pass\n", encoding="utf-8")+ (source / "config.json").write_text("{}\n", encoding="utf-8")++ archived = _archive_backtest_result(+ json.dumps({"status": "ok", "run_dir": str(source)}), str(active)+ )++ assert archived is True+ assert (active / "artifacts" / "metrics.csv").is_file()+ assert (active / "artifacts" / "equity.csv").is_file()+ assert (active / "code" / "signal_engine.py").is_file()+ assert (active / "config.json").is_file()++ def test_ignores_result_without_metrics(self, tmp_path: Path) -> None:+ source = tmp_path / "not-a-backtest"+ source.mkdir()++ archived = _archive_backtest_result(+ json.dumps({"status": "ok", "run_dir": str(source)}), str(tmp_path / "active")+ )++ assert archived is Falsediff --git a/frontend/src/components/charts/StrategyResearchDashboard.tsx b/frontend/src/components/charts/StrategyResearchDashboard.tsxnew file mode 100644index 000000000..dd6051a45--- /dev/null+++ b/frontend/src/components/charts/StrategyResearchDashboard.tsx@@ -0,0 +1,268 @@+import { useEffect, useMemo, useRef } from "react";+import { CalendarRange, Database, FlaskConical } from "lucide-react";+import i18n from "@/i18n";+import { echarts } from "@/lib/echarts";+import { getChartTheme } from "@/lib/chart-theme";+import { useThemeDark } from "@/lib/theme-store";+import type { RunData } from "@/lib/api";++const BLUE = "#3676df";+const DEEP_BLUE = "#2156ae";+const ORANGE = "#ff8a3d";+const GREEN = "#3b9b8f";+const SLATE = "#8f98a6";++function tr(en: string, zh: string): string {+ return i18n.language.toLowerCase().startsWith("zh") ? zh : en;+}++function num(value: unknown): number | null {+ const parsed = Number(value);+ return Number.isFinite(parsed) ? parsed : null;+}++function fixed(value: unknown, digits = 2): string {+ const parsed = num(value);+ return parsed == null ? "—" : parsed.toFixed(digits);+}++function pct(value: unknown, digits = 1): string {+ const parsed = num(value);+ return parsed == null ? "—" : `${(parsed * 100).toFixed(digits)}%`;+}++function timestamp(row: Record<string, string>): string {+ return row.timestamp || row.time || row.date || "";+}++type ReportIdentity = {+ title: string;+ strategy: string;+ symbols: string[];+ startDate: string;+ endDate: string;+ source: string;+ engine: string;+};++function compactPrompt(prompt: string): string {+ const firstClause = prompt.trim().split(/[。.!!??;;\n]/, 1)[0] || "";+ return firstClause.length > 68 ? `${firstClause.slice(0, 65).trim()}…` : firstClause;+}++function inferStrategyName(prompt: string): string {+ const zhMa = prompt.match(/(\d+)\s*(?:日|天)?\s*[\//-]\s*(\d+)\s*(?:日|天)?[^。;,,]{0,18}均线/i)+ || prompt.match(/(\d+)\s*日均线[^。;,,]{0,18}(\d+)\s*日均线/i);+ if (zhMa) return `${zhMa[1]}/${zhMa[2]} 日均线交叉策略`;++ const enMa = prompt.match(/(\d+)\s*[\/\-]\s*(\d+)[^.!?]{0,28}(?:moving[ -]?average|\bma\b)/i)+ || prompt.match(/(?:moving[ -]?average|\bma\b)[^.!?]{0,28}(\d+)\s*[\/\-]\s*(\d+)/i);+ if (enMa) return `${enMa[1]}/${enMa[2]}-day moving-average crossover`;++ if (/macd/i.test(prompt)) return "MACD 趋势策略";+ if (/rsi/i.test(prompt)) return "RSI 择时策略";+ if (/动量|momentum/i.test(prompt)) return "动量策略";+ if (/均值回归|mean reversion/i.test(prompt)) return "均值回归策略";+ if (/突破|breakout/i.test(prompt)) return "突破策略";+ return compactPrompt(prompt) || tr("Systematic strategy", "系统化交易策略");+}++export function getStrategyReportIdentity(run: RunData): ReportIdentity {+ const backtest = (run.run_card?.backtest || {}) as Record<string, unknown>;+ const symbols = (Array.isArray(backtest.codes) ? backtest.codes : run.chart_symbols || [])+ .map(String)+ .filter(Boolean);+ const prompt = run.prompt || "";+ const strategy = inferStrategyName(prompt);+ const symbolLabel = symbols.length === 0+ ? tr("Portfolio", "投资组合")+ : symbols.length <= 2+ ? symbols.join(" + ")+ : `${symbols[0]} +${symbols.length - 1}`;+ const fallbackRows = run.artifacts_equity_csv || [];+ const startDate = String(backtest.start_date || (fallbackRows[0] ? timestamp(fallbackRows[0]) : ""));+ const endDate = String(backtest.end_date || (fallbackRows.length ? timestamp(fallbackRows[fallbackRows.length - 1]) : ""));+ return {+ title: `${symbolLabel} · ${strategy}`,+ strategy,+ symbols,+ startDate,+ endDate,+ source: String((run.run_card?.data_sources || [])[0] || backtest.source || ""),+ engine: String(backtest.engine || ""),+ };+}++function rollingSharpe(rows: Array<Record<string, string>>, window = 20): Array<number | null> {+ const returns = rows.map((row) => num(row.ret));+ return returns.map((_, index) => {+ if (index + 1 < window) return null;+ const sample = returns+ .slice(index + 1 - window, index + 1)+ .filter((value): value is number => value != null);+ if (sample.length < window) return null;+ const mean = sample.reduce((sum, value) => sum + value, 0) / sample.length;+ const variance = sample.reduce((sum, value) => sum + (value - mean) ** 2, 0)+ / Math.max(1, sample.length - 1);+ const std = Math.sqrt(variance);+ return std > 0 ? (mean / std) * Math.sqrt(252) : 0;+ });+}++function FigureTitle({ index, title, note }: { index: string; title: string; note: string }) {+ return (+ <div className="border-l-4 border-[#3676df] pl-3">+ <p className="font-mono text-[10px] uppercase tracking-[0.18em] text-[#3676df]">Figure {index}</p>+ <h3 className="mt-0.5 text-sm font-semibold text-foreground">{title}</h3>+ <p className="mt-1 text-xs text-muted-foreground">{note}</p>+ </div>+ );+}++export function StrategyResearchDashboard({ run }: { run: RunData }) {+ const navRef = useRef<HTMLDivElement>(null);+ const riskRef = useRef<HTMLDivElement>(null);+ const tradesRef = useRef<HTMLDivElement>(null);+ const dark = useThemeDark();++ const equityRows = useMemo<Array<Record<string, string>>>(() => {+ if (run.artifacts_equity_csv?.length) return run.artifacts_equity_csv;+ return (run.equity_curve || []).map((row) => ({+ timestamp: row.time,+ equity: String(row.equity),+ drawdown: String(row.drawdown ?? ""),+ }));+ }, [run.artifacts_equity_csv, run.equity_curve]);+ const trades = run.artifacts_trades_csv || run.trade_log || [];+ const identity = useMemo(() => getStrategyReportIdentity(run), [run]);++ useEffect(() => {+ const nodes = [navRef.current, riskRef.current, tradesRef.current];+ if (nodes.some((node) => !node)) return;+ const charts = nodes.map((node) => echarts.init(node!));+ const [navChart, riskChart, tradeChart] = charts;+ const theme = getChartTheme();+ const axis = {+ axisLine: { lineStyle: { color: theme.axisColor } },+ axisLabel: { color: theme.textColor, fontSize: 10 },+ splitLine: { lineStyle: { color: theme.gridColor } },+ };+ const dates = equityRows.map(timestamp);+ const equities = equityRows.map((row) => num(row.equity));+ const benchmarks = equityRows.map((row) => num(row.benchmark_equity));+ const firstEquity = equities.find((value): value is number => value != null && value !== 0) || 1;+ const firstBenchmark = benchmarks.find((value): value is number => value != null && value !== 0) || 1;++ navChart.setOption({+ backgroundColor: "transparent",+ tooltip: { trigger: "axis" },+ legend: { top: 0, right: 4, textStyle: { color: theme.textColor, fontSize: 10 } },+ grid: { left: 18, right: 22, top: 32, bottom: 18, containLabel: true },+ xAxis: { ...axis, type: "category", data: dates, boundaryGap: false },+ yAxis: { ...axis, type: "value", axisLabel: { color: theme.textColor, fontSize: 10, formatter: (v: number) => `${v.toFixed(2)}x` } },+ series: [+ { name: tr("Strategy", "策略"), type: "line", showSymbol: false, data: equities.map((v) => v == null ? null : v / firstEquity), lineStyle: { color: BLUE, width: 2.5 }, itemStyle: { color: BLUE } },+ ...(benchmarks.some((value) => value != null) ? [{ name: tr("Benchmark", "基准"), type: "line", showSymbol: false, data: benchmarks.map((v) => v == null ? null : v / firstBenchmark), lineStyle: { color: SLATE, width: 1.5, type: "dashed" }, itemStyle: { color: SLATE } }] : []),+ ],+ });++ const drawdown = equityRows.map((row) => num(row.drawdown));+ const sharpe = rollingSharpe(equityRows);+ riskChart.setOption({+ backgroundColor: "transparent",+ tooltip: { trigger: "axis" },+ legend: { top: 0, right: 4, textStyle: { color: theme.textColor, fontSize: 10 } },+ grid: { left: 18, right: 24, top: 32, bottom: 18, containLabel: true },+ xAxis: { ...axis, type: "category", data: dates, boundaryGap: false },+ yAxis: [+ { ...axis, type: "value", axisLabel: { color: theme.textColor, fontSize: 10, formatter: (v: number) => `${(v * 100).toFixed(0)}%` } },+ { ...axis, type: "value", splitLine: { show: false }, axisLabel: { color: theme.textColor, fontSize: 10 } },+ ],+ series: [+ { name: tr("Drawdown", "回撤"), type: "line", showSymbol: false, data: drawdown, lineStyle: { color: ORANGE, width: 2 }, areaStyle: { color: "rgba(255,138,61,.10)" }, itemStyle: { color: ORANGE } },+ { name: tr("Rolling Sharpe (20)", "滚动 Sharpe(20)"), type: "line", yAxisIndex: 1, showSymbol: false, connectNulls: false, data: sharpe, lineStyle: { color: GREEN, width: 1.5 }, itemStyle: { color: GREEN } },+ ],+ });++ const exits = trades.filter((trade) => (num(trade.pnl) || 0) !== 0).slice(-60);+ tradeChart.setOption({+ backgroundColor: "transparent",+ tooltip: { trigger: "axis", axisPointer: { type: "shadow" } },+ grid: { left: 18, right: 18, top: 14, bottom: 18, containLabel: true },+ xAxis: { ...axis, type: "category", data: exits.map((trade, index) => trade.timestamp || String(index + 1)), axisLabel: { color: theme.textColor, fontSize: 9, hideOverlap: true } },+ yAxis: { ...axis, type: "value" },+ series: [{ type: "bar", barMaxWidth: 12, data: exits.map((trade) => { const value = num(trade.pnl) || 0; return { value, itemStyle: { color: value >= 0 ? GREEN : ORANGE } }; }) }],+ });++ let frame: number | null = null;+ const observer = new ResizeObserver(() => {+ if (frame != null) cancelAnimationFrame(frame);+ frame = requestAnimationFrame(() => charts.forEach((chart) => chart.resize()));+ });+ nodes.forEach((node) => observer.observe(node!));+ return () => {+ observer.disconnect();+ if (frame != null) cancelAnimationFrame(frame);+ charts.forEach((chart) => chart.dispose());+ };+ }, [dark, equityRows, trades]);++ const metrics: Record<string, number> = run.metrics || {};+ const kpis = [+ [tr("Total return", "总收益率"), pct(metrics.total_return), BLUE],+ [tr("Annual return", "年化收益率"), pct(metrics.annual_return), DEEP_BLUE],+ ["Sharpe", fixed(metrics.sharpe), GREEN],+ [tr("Max drawdown", "最大回撤"), pct(metrics.max_drawdown), ORANGE],+ [tr("Win rate", "胜率"), pct(metrics.win_rate), GREEN],+ [tr("Trades", "交易次数"), fixed(metrics.trade_count, 0), SLATE],+ ] as const;++ return (+ <article className="mx-auto max-w-[1180px] overflow-hidden border border-[#dfe2e7] bg-card shadow-sm">+ <header className="relative overflow-hidden border-b border-[#dfe2e7] bg-gradient-to-br from-[#3676df]/[0.10] via-background to-[#3b9b8f]/[0.05] p-5 md:p-8">+ <div className="absolute -right-16 -top-20 h-52 w-52 rounded-full bg-[#3676df]/[0.08] blur-3xl" aria-hidden="true" />+ <div className="relative">+ <div className="flex flex-wrap items-center justify-between gap-3">+ <p className="font-mono text-[10px] uppercase tracking-[0.22em] text-[#3676df]">{tr("Quantitative research · Backtest", "量化研究 · 策略回测")}</p>+ <span className="rounded-full border border-[#3676df]/20 bg-background/70 px-2.5 py-1 font-mono text-[10px] text-muted-foreground">RUN {run.run_id.slice(-8).toUpperCase()}</span>+ </div>+ <h2 className="mt-4 max-w-4xl text-2xl font-semibold leading-tight tracking-[-0.025em] text-foreground md:text-[30px]">{identity.title}</h2>+ {run.prompt && run.prompt !== identity.strategy && (+ <p className="mt-2 max-w-4xl text-sm leading-6 text-muted-foreground">{compactPrompt(run.prompt)}</p>+ )}+ <div className="mt-5 flex flex-wrap gap-2 text-xs text-muted-foreground">+ {(identity.startDate || identity.endDate) && <span className="inline-flex items-center gap-1.5 rounded-md border border-border/70 bg-background/65 px-2.5 py-1.5"><CalendarRange className="h-3.5 w-3.5 text-[#3676df]" />{identity.startDate || "—"} — {identity.endDate || "—"}</span>}+ {identity.engine && <span className="inline-flex items-center gap-1.5 rounded-md border border-border/70 bg-background/65 px-2.5 py-1.5"><FlaskConical className="h-3.5 w-3.5 text-[#3676df]" />{identity.engine.toUpperCase()} {tr("engine", "回测引擎")}</span>}+ {identity.source && <span className="inline-flex items-center gap-1.5 rounded-md border border-border/70 bg-background/65 px-2.5 py-1.5"><Database className="h-3.5 w-3.5 text-[#3676df]" />{identity.source}</span>}+ </div>+ </div>+ </header>++ <div className="grid grid-cols-2 border-b border-[#dfe2e7] md:grid-cols-3 lg:grid-cols-6">+ {kpis.map(([label, value, color]) => <div key={label} className="border-b border-r border-[#dfe2e7] p-4 lg:border-b-0"><p className="text-[11px] text-muted-foreground">{label}</p><p className="mt-1 font-mono text-xl font-semibold tabular-nums" style={{ color }}>{value}</p></div>)}+ </div>++ <div className="space-y-8 p-5 md:p-7">+ <section className="space-y-3"><FigureTitle index="01" title={tr("Equity and benchmark", "净值与基准")} note={tr("Compare the strategy's growth path with its benchmark.", "比较策略与基准的累计收益路径。")} /><div ref={navRef} className="h-[320px] border border-[#dfe2e7] bg-background/40" /></section>+ <section className="space-y-3"><FigureTitle index="02" title={tr("Drawdown and rolling risk", "回撤与滚动风险")} note={tr("See when losses deepened and risk-adjusted performance changed.", "观察亏损加深和风险调整后表现发生变化的时点。")} /><div ref={riskRef} className="h-[300px] border border-[#dfe2e7] bg-background/40" /></section>+ <section className="space-y-3"><FigureTitle index="03" title={tr("Realized trade P&L", "已实现成交盈亏")} note={tr("Profit and loss from completed trades.", "展示已完成交易带来的实际盈亏。")} /><div ref={tradesRef} className="h-[260px] border border-[#dfe2e7] bg-background/40" /></section>+ <section className="space-y-3"><FigureTitle index="04" title={tr("Trade ledger", "成交明细")} note={tr("Review the latest 100 trades in chronological detail.", "按时间查看最近 100 笔交易明细。")} /><TradeTable rows={trades.slice(-100).reverse()} /></section>+ <section className="space-y-3"><FigureTitle index="05" title={tr("Performance metrics", "绩效指标")} note={tr("A complete summary of return, risk, and trading statistics.", "汇总策略的收益、风险与交易统计。")} /><MetricTable metrics={metrics} /></section>+ </div>+ </article>+ );+}++function TradeTable({ rows }: { rows: Array<Record<string, string>> }) {+ if (!rows.length) return <EmptyData text={tr("No trades were recorded.", "没有成交记录。")} />;+ return <div className="max-h-[440px] overflow-auto border border-[#dfe2e7]"><table className="w-full min-w-[760px] text-xs"><thead className="sticky top-0 bg-[#f5f7fa] text-muted-foreground dark:bg-slate-900"><tr><th className="px-3 py-2 text-left">Time</th><th className="px-3 py-2 text-left">Symbol</th><th className="px-3 py-2 text-left">Side</th><th className="px-3 py-2 text-right">Price</th><th className="px-3 py-2 text-right">Qty</th><th className="px-3 py-2 text-right">PnL</th><th className="px-3 py-2 text-left">Reason</th></tr></thead><tbody>{rows.map((row, index) => { const pnl = num(row.pnl) || 0; return <tr key={`${row.timestamp}-${row.code}-${index}`} className="border-t border-[#dfe2e7]"><td className="px-3 py-2 font-mono">{row.timestamp || "—"}</td><td className="px-3 py-2 font-mono">{row.code || "—"}</td><td className="px-3 py-2 uppercase">{row.side || "—"}</td><td className="px-3 py-2 text-right font-mono">{fixed(row.price, 4)}</td><td className="px-3 py-2 text-right font-mono">{fixed(row.qty, 4)}</td><td className="px-3 py-2 text-right font-mono font-semibold" style={{ color: pnl > 0 ? GREEN : pnl < 0 ? ORANGE : SLATE }}>{fixed(pnl)}</td><td className="px-3 py-2 text-muted-foreground">{row.reason || "—"}</td></tr>; })}</tbody></table></div>;+}++function MetricTable({ metrics }: { metrics: Record<string, number> }) {+ const entries = Object.entries(metrics);+ return <div className="overflow-x-auto border border-[#dfe2e7]"><table className="w-full text-xs"><tbody>{entries.map(([key, value]) => <tr key={key} className="border-b border-[#dfe2e7] last:border-0"><td className="w-1/2 bg-[#f5f7fa] px-3 py-2 font-mono text-muted-foreground dark:bg-slate-900">{key}</td><td className="px-3 py-2 text-right font-mono tabular-nums">{fixed(value, 4)}</td></tr>)}</tbody></table></div>;+}++function EmptyData({ text }: { text: string }) {+ return <div className="border border-dashed border-[#dfe2e7] p-6 text-center text-xs text-muted-foreground">{text}</div>;+}diff --git a/frontend/src/components/chat/RunCompleteCard.tsx b/frontend/src/components/chat/RunCompleteCard.tsxindex d1e2ea5b8..f876928f8 100644--- a/frontend/src/components/chat/RunCompleteCard.tsx+++ b/frontend/src/components/chat/RunCompleteCard.tsx@@ -1,7 +1,7 @@import { useTranslation } from 'react-i18next';import { lazy, memo, Suspense, useCallback, useEffect, useState } from "react";import { Link } from "react-router";-import { BarChart3, Code2, FileText, Loader2 } from "lucide-react";+import { LayoutDashboard, Code2, FileText, Loader2 } from "lucide-react";import { api } from "@/lib/api";import { AgentAvatar } from "./AgentAvatar";import { MetricsCard } from "./MetricsCard";@@ -102,10 +102,10 @@ export const RunCompleteCard = memo(function RunCompleteCard({ msg }: Props) {<div className="flex items-center gap-3 flex-wrap">{msg.runId && (<Link- to={`/runs/${msg.runId}`}+ to={`/runs/${encodeURIComponent(msg.runId)}?view=dashboard`}className="text-sm text-primary hover:underline inline-flex items-center gap-1.5 font-medium">- <BarChart3 className="h-3.5 w-3.5" />+ <LayoutDashboard className="h-3.5 w-3.5" />{t("runComplete.fullReport")}</Link>)}diff --git a/frontend/src/components/chat/__tests__/RunCompleteCard.test.tsx b/frontend/src/components/chat/__tests__/RunCompleteCard.test.tsxnew file mode 100644index 000000000..4a89b0c17--- /dev/null+++ b/frontend/src/components/chat/__tests__/RunCompleteCard.test.tsx@@ -0,0 +1,39 @@+import { render, screen } from "@testing-library/react";+import { MemoryRouter } from "react-router";+import { RunCompleteCard } from "../RunCompleteCard";+import { makeMessage } from "@/tests/helpers/factories";++const apiMock = vi.hoisted(() => ({+ getRun: vi.fn(),+ getRunPine: vi.fn(),+}));++vi.mock("@/lib/api", () => ({ api: apiMock }));++describe("RunCompleteCard", () => {+ beforeEach(() => {+ apiMock.getRun.mockResolvedValue({ status: "success", run_id: "strategy-run" });+ apiMock.getRunPine.mockResolvedValue({ exists: false, content: null });+ });++ it("opens every completed backtest in the research dashboard view", () => {+ render(+ <MemoryRouter>+ <RunCompleteCard msg={makeMessage({ type: "run_complete", runId: "strategy-run" })} />+ </MemoryRouter>,+ );++ expect(screen.getByRole("link", { name: /Full Report/i }))+ .toHaveAttribute("href", "/runs/strategy-run?view=dashboard");+ });++ it("does not render a dashboard link without a run id", () => {+ render(+ <MemoryRouter>+ <RunCompleteCard msg={makeMessage({ type: "run_complete" })} />+ </MemoryRouter>,+ );++ expect(screen.queryByRole("link", { name: /Full Report/i })).not.toBeInTheDocument();+ });+});diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 69c412695..a55da3219 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -613,6 +613,9 @@ export interface RunData {trade_markers?: TradeMarker[];equity_curve?: EquityPoint[];trade_log?: Array<Record<string, string>>;+ artifacts_equity_csv?: Array<Record<string, string>>;+ artifacts_metrics_csv?: Array<Record<string, string>>;+ artifacts_trades_csv?: Array<Record<string, string>>;run_logs?: Array<{ source?: string; line_number?: number; message?: string }>;}diff --git a/frontend/src/pages/RunDetail.tsx b/frontend/src/pages/RunDetail.tsxindex 050cf1010..185a4ce67 100644--- a/frontend/src/pages/RunDetail.tsx+++ b/frontend/src/pages/RunDetail.tsx@@ -2,7 +2,7 @@ import i18n from '@/i18n';import { useEffect, useRef, useState } from "react";import type { ReactNode } from "react";import { useTranslation } from "react-i18next";-import { useParams, useNavigate } from "react-router";+import { useParams, useNavigate, useSearchParams } from "react-router";import {AlertTriangle,ArrowLeft,@@ -16,6 +16,7 @@ import {Fingerprint,Gauge,List,+ LayoutDashboard,Loader2,ShieldCheck,XCircle,@@ -32,10 +33,11 @@ import { MetricsCard } from "@/components/chat/MetricsCard";import { ValidationPanel } from "@/components/charts/ValidationPanel";import { Skeleton, SkeletonMetrics, SkeletonChart } from "@/components/common/Skeleton";import { ErrorBoundary } from "@/components/common/ErrorBoundary";+import { getStrategyReportIdentity, StrategyResearchDashboard } from "@/components/charts/StrategyResearchDashboard";const rehypePlugins = [rehypeHighlight];-type Tab = "chart" | "trades" | "runCard" | "code" | "validation" | "studio";+type Tab = "dashboard" | "chart" | "trades" | "runCard" | "code" | "validation" | "studio";type ChartPayload = Pick<RunData, "price_series" | "indicator_series" | "trade_markers">;type ChartCache = Record<string, ChartPayload>;type ChartLoadProgress = { done: number; total: number };@@ -97,11 +99,13 @@ function yieldToBrowser(): Promise<void> {export function RunDetail() {const { runId } = useParams<{ runId: string }>();+ const [searchParams] = useSearchParams();+ const requestedInitialTab: Tab = searchParams.get("view") === "dashboard" ? "dashboard" : "chart";const navigate = useNavigate();const { t } = useTranslation();const [run, setRun] = useState<RunData | null>(null);const [code, setCode] = useState<Record<string, string>>({});- const [tab, setTab] = useState<Tab>("chart");+ const [tab, setTab] = useState<Tab>(requestedInitialTab);const [loading, setLoading] = useState(true);const [selectedSymbol, setSelectedSymbol] = useState("");const [chartPickerSymbol, setChartPickerSymbol] = useState("");@@ -118,6 +122,7 @@ export function RunDetail() {const hasRunCard = !!run?.run_card;const hasStudio = !!run?.risk_xray || !!run?.rebalance_notes;const TABS: { id: Tab; label: string; icon: typeof BarChart3; hidden?: boolean }[] = [+ { id: "dashboard", label: i18n.language.toLowerCase().startsWith("zh") ? "研究 Dashboard" : "Research dashboard", icon: LayoutDashboard },{ id: "chart", label: i18n.t("runDetail.chart"), icon: BarChart3 },{ id: "trades", label: i18n.t("runDetail.trades"), icon: List },{ id: "studio", label: i18n.t("runDetail.studio"), icon: Gauge, hidden: !hasStudio },@@ -131,7 +136,7 @@ export function RunDetail() {cancelBulkChartLoadRef.current = true;setRun(null);setCode({});- setTab("chart");+ setTab(requestedInitialTab);setLoading(true);setSelectedSymbol("");setChartPickerSymbol("");@@ -173,7 +178,7 @@ export function RunDetail() {cancelBulkChartLoadRef.current = true;if (runGenerationRef.current === generation) runGenerationRef.current += 1;};- }, [runId]);+ }, [runId, requestedInitialTab]);if (loading) {return (@@ -201,6 +206,7 @@ export function RunDetail() {const ok = run.status === "success";const cancelled = run.status === "cancelled";+ const reportIdentity = getStrategyReportIdentity(run);async function loadChartSymbol(symbol: string,@@ -317,7 +323,10 @@ export function RunDetail() {<span className="sr-only">{t("swarm.status.failed")}</span></>)}- <h1 className="font-mono text-2xl font-semibold">{runId}</h1>+ <div className="min-w-0">+ <h1 className="truncate text-xl font-semibold tracking-tight">{reportIdentity.title}</h1>+ <p className="mt-0.5 font-mono text-[10px] uppercase tracking-[0.12em] text-muted-foreground">RUN {runId}</p>+ </div>{run.elapsed_seconds && <span className="text-xs text-muted-foreground">{run.elapsed_seconds.toFixed(1)}s</span>}</div>{run.prompt && <p className="text-sm text-muted-foreground">{run.prompt}</p>}@@ -366,6 +375,7 @@ export function RunDetail() {<div className="flex-1 overflow-auto"><ErrorBoundary>+ {tab === "dashboard" && <div className="p-4"><StrategyResearchDashboard run={run} /></div>}{tab === "chart" && (<ChartTabrun={run}diff --git a/frontend/src/pages/__tests__/RunDetail.test.tsx b/frontend/src/pages/__tests__/RunDetail.test.tsxindex 090f6e8b7..68a883f1c 100644--- a/frontend/src/pages/__tests__/RunDetail.test.tsx+++ b/frontend/src/pages/__tests__/RunDetail.test.tsx@@ -15,6 +15,13 @@ vi.mock("@/components/charts/CandlestickChart", () => ({vi.mock("@/components/charts/EquityChart", () => ({EquityChart: () => <div data-testid="equity-chart" />,}));+vi.mock("@/components/charts/StrategyResearchDashboard", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@/components/charts/StrategyResearchDashboard")>();+ return {+ ...actual,+ StrategyResearchDashboard: ({ run }: { run: RunData }) => <div data-testid="strategy-dashboard">{run.run_id}</div>,+ };+});function deferred<T>() {let resolve!: (value: T) => void;@@ -39,6 +46,35 @@ describe("RunDetail page", () => {apiMock.getRunCode.mockReset();});+ it("presents a readable strategy title instead of promoting the run id", async () => {+ apiMock.getRun.mockResolvedValue({+ status: "success",+ run_id: "20260811_110751_32_d951c8",+ prompt: "回测 000001.SZ 在 2024 年的 20/50 日均线交叉策略。",+ chart_symbols: ["000001.SZ"],+ run_card: {+ backtest: { codes: ["000001.SZ"], start_date: "2024-01-01", end_date: "2024-12-31", engine: "daily" },+ data_sources: ["tencent"],+ },+ });+ apiMock.getRunCode.mockResolvedValueOnce({});++ renderRunDetail("/runs/20260811_110751_32_d951c8?view=dashboard");++ expect(await screen.findByRole("heading", { name: "000001.SZ · 20/50 日均线交叉策略" })).toBeInTheDocument();+ expect(screen.getByText("RUN 20260811_110751_32_d951c8")).toHaveClass("text-[10px]");+ });++ it("opens the research dashboard when requested by the terminal report URL", async () => {+ apiMock.getRun.mockResolvedValue({ status: "success", run_id: "terminal-run", prompt: "MA strategy" });+ apiMock.getRunCode.mockResolvedValue({});++ renderRunDetail("/runs/terminal-run?view=dashboard");++ expect(await screen.findByTestId("strategy-dashboard")).toHaveTextContent("terminal-run");+ expect(screen.getByRole("tab", { name: /dashboard/i })).toHaveAttribute("aria-selected", "true");+ });+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>>();@@ -127,7 +163,8 @@ describe("RunDetail page", () => {await screen.findByText("Accessible run");expect(screen.getByText("Completed")).toHaveClass("sr-only");- expect(screen.getByRole("heading", { level: 1, name: "accessible" })).toHaveClass("text-2xl", "font-semibold");+ expect(screen.getByRole("heading", { level: 1, name: "Portfolio · Accessible run" })).toHaveClass("text-xl", "font-semibold");+ expect(screen.getByText("RUN accessible")).toHaveClass("font-mono", "text-[10px]");expect(screen.getByRole("tablist")).toBeInTheDocument();const chartTab = screen.getByRole("tab", { name: "Chart" });