"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(reports): add backtest report library page (#224)
LemonCANDY428f7dc0aa3d25
diff --git a/frontend/src/components/layout/Layout.tsx b/frontend/src/components/layout/Layout.tsxindex 8ab8c46ce..ef16d7232 100644--- a/frontend/src/components/layout/Layout.tsx+++ b/frontend/src/components/layout/Layout.tsx@@ -1,7 +1,7 @@import { useTranslation } from "react-i18next";import { useEffect, useState } from "react";import { Link, Outlet, useLocation, useSearchParams } from "react-router-dom";-import { Activity, BarChart3, Bot, Languages, Moon, Sun, Plus, Trash2, Pencil, MessageSquare, ChevronsLeft, ChevronsRight, Settings, Layers, Loader2 } from "lucide-react";+import { Activity, BarChart3, Bot, FileText, Languages, Moon, Sun, Plus, Trash2, Pencil, MessageSquare, ChevronsLeft, ChevronsRight, Settings, Layers, Loader2 } from "lucide-react";import { cn } from "@/lib/utils";import { useDarkMode } from "@/hooks/useDarkMode";import { api, type SessionItem } from "@/lib/api";@@ -18,6 +18,7 @@ export function Layout() {{ to: "/", icon: BarChart3, label: t('layout.home') },{ to: "/agent", icon: Bot, label: t('layout.agent') },{ to: "/runtime", icon: Activity, label: t('layout.runtime') },+ { to: "/reports", icon: FileText, label: t('layout.reports') },{ to: "/alpha-zoo", icon: Layers, label: t('layout.alphaZoo') },{ to: "/settings", icon: Settings, label: t('layout.settings') },{ to: "/correlation", icon: BarChart3, label: t('layout.correlation') },diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex eb05358cc..7ba7de11e 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -6,6 +6,7 @@"home": "Home","agent": "Agent","runtime": "Runtime",+ "reports": "Reports","alphaZoo": "Alpha Zoo","settings": "Settings","correlation": "Correlation Matrix",@@ -78,6 +79,34 @@"never": "never","ago": "ago"},+ "reports": {+ "badge": "Reports",+ "title": "Backtest Report Library",+ "subtitle": "Browse historical backtest reports, metrics, and run details from one place.",+ "refresh": "Refresh",+ "searchPlaceholder": "Search run id, prompt, symbol, status...",+ "allStatuses": "All statuses",+ "startDate": "Start date",+ "endDate": "End date",+ "sort": "Sort",+ "sortNewest": "Newest first",+ "sortOldest": "Oldest first",+ "sortReturn": "Return high to low",+ "sortSharpe": "Sharpe high to low",+ "count": "{{shown}} of {{total}} reports",+ "unavailable": "Report library unavailable",+ "loadError": "Unable to load reports.",+ "emptyTitle": "No reports yet",+ "emptyBody": "Create a backtest from Agent, then return here to review it.",+ "noMatchesTitle": "No matching reports",+ "noMatchesBody": "Adjust your search query, status filter, or date range.",+ "noPrompt": "No prompt recorded.",+ "to": "to",+ "return": "Return",+ "sharpe": "Sharpe",+ "fullReport": "Full Report",+ "compare": "Compare"+ },"connection": {"reconnecting": "Connection lost, reconnecting (attempt {{attempt}})…","disconnected": "Connection lost"diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex 9d2a58479..932aa5875 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -6,6 +6,7 @@"home": "首页","agent": "智能体","runtime": "运行时",+ "reports": "报告","alphaZoo": "Alpha 动物园","settings": "设置","correlation": "相关性矩阵",@@ -78,6 +79,34 @@"never": "从未","ago": "前"},+ "reports": {+ "badge": "报告",+ "title": "回测报告库",+ "subtitle": "集中浏览历史回测报告、指标和运行详情。",+ "refresh": "刷新",+ "searchPlaceholder": "搜索运行 ID、提示词、标的、状态...",+ "allStatuses": "全部状态",+ "startDate": "开始日期",+ "endDate": "结束日期",+ "sort": "排序",+ "sortNewest": "最新优先",+ "sortOldest": "最早优先",+ "sortReturn": "收益率从高到低",+ "sortSharpe": "夏普从高到低",+ "count": "{{shown}} / {{total}} 份报告",+ "unavailable": "报告库不可用",+ "loadError": "无法加载报告。",+ "emptyTitle": "暂无报告",+ "emptyBody": "先在智能体中创建一次回测,然后回到这里查看。",+ "noMatchesTitle": "没有匹配的报告",+ "noMatchesBody": "请调整搜索词、状态筛选或日期范围。",+ "noPrompt": "未记录提示词。",+ "to": "至",+ "return": "收益率",+ "sharpe": "夏普",+ "fullReport": "完整报告",+ "compare": "对比"+ },"connection": {"reconnecting": "连接已断开,正在重连(第 {{attempt}} 次)…","disconnected": "连接已断开"diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 7635bf9e1..13e50389d 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -73,7 +73,7 @@ function appendQueryParam(url: string, key: string, value: string): string {export const api = {uploadFile,- listRuns: () => request<RunListItem[]>("/runs"),+ listRuns: (limit?: number) => request<RunListItem[]>(`/runs${limit ? `?limit=${encodeURIComponent(String(limit))}` : ""}`),getRun: (id: string, params: RunDetailParams = {}) => {const q = new URLSearchParams();if (params.chart_payload) q.set("chart_payload", params.chart_payload);diff --git a/frontend/src/pages/Reports.tsx b/frontend/src/pages/Reports.tsxnew file mode 100644index 000000000..91d6a6e41--- /dev/null+++ b/frontend/src/pages/Reports.tsx@@ -0,0 +1,313 @@+import { useEffect, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { Link } from "react-router-dom";+import {+ AlertTriangle,+ ArrowRight,+ CheckCircle2,+ FileText,+ GitCompare,+ Loader2,+ RefreshCw,+ Search,+ XCircle,+} from "lucide-react";+import { api, type RunListItem } from "@/lib/api";+import { formatMetricVal } from "@/lib/formatters";+import { cn } from "@/lib/utils";++const REPORT_SCAN_LIMIT = 100;++type SortMode = "created_desc" | "created_asc" | "return_desc" | "sharpe_desc";++export function Reports() {+ const { t } = useTranslation();+ const [runs, setRuns] = useState<RunListItem[]>([]);+ const [loading, setLoading] = useState(true);+ const [refreshing, setRefreshing] = useState(false);+ const [query, setQuery] = useState("");+ const [statusFilter, setStatusFilter] = useState("all");+ const [startDate, setStartDate] = useState("");+ const [endDate, setEndDate] = useState("");+ const [sortMode, setSortMode] = useState<SortMode>("created_desc");+ const [error, setError] = useState<string | null>(null);++ async function loadReports(mode: "initial" | "refresh" = "refresh") {+ if (mode === "initial") setLoading(true);+ else setRefreshing(true);+ setError(null);+ try {+ const list = await api.listRuns(REPORT_SCAN_LIMIT);+ setRuns(Array.isArray(list) ? list.filter(isBacktestReportRun) : []);+ } catch (err) {+ setRuns([]);+ setError(err instanceof Error ? err.message : t("reports.loadError"));+ } finally {+ setLoading(false);+ setRefreshing(false);+ }+ }++ useEffect(() => {+ void loadReports("initial");+ }, []);++ const statusOptions = useMemo(() => {+ const values = Array.from(new Set(runs.map((run) => run.status || "unknown"))).sort();+ return ["all", ...values];+ }, [runs]);++ const filtered = useMemo(() => {+ const needle = query.trim().toLowerCase();+ const startMs = startDate ? Date.parse(startDate) : Number.NEGATIVE_INFINITY;+ const endMs = endDate ? Date.parse(`${endDate}T23:59:59`) : Number.POSITIVE_INFINITY;++ return [...runs]+ .filter((run) => {+ if (statusFilter !== "all" && (run.status || "unknown") !== statusFilter) return false;+ const created = Date.parse(run.created_at);+ if (Number.isFinite(created) && (created < startMs || created > endMs)) return false;+ if (!needle) return true;+ const haystack = [+ run.run_id,+ run.status,+ run.prompt,+ ...(run.codes || []),+ run.start_date,+ run.end_date,+ ].filter(Boolean).join(" ").toLowerCase();+ return haystack.includes(needle);+ })+ .sort((left, right) => compareRuns(left, right, sortMode));+ }, [runs, query, statusFilter, startDate, endDate, sortMode]);++ return (+ <div className="min-h-screen p-6 lg:p-8">+ <div className="mx-auto flex w-full max-w-6xl flex-col gap-6">+ <section className="flex flex-col gap-4 border-b pb-6 lg:flex-row lg:items-end lg:justify-between">+ <div className="space-y-3">+ <div className="inline-flex items-center gap-2 rounded-md border px-2.5 py-1 text-xs font-medium text-muted-foreground">+ <FileText className="h-3.5 w-3.5" />+ {t("reports.badge")}+ </div>+ <div>+ <h1 className="text-3xl font-bold tracking-tight">{t("reports.title")}</h1>+ <p className="mt-2 max-w-2xl text-sm text-muted-foreground">{t("reports.subtitle")}</p>+ </div>+ </div>+ <button+ type="button"+ onClick={() => void loadReports("refresh")}+ disabled={refreshing}+ className="inline-flex items-center gap-2 rounded-md border px-4 py-2 text-sm font-medium transition hover:bg-muted disabled:opacity-50"+ >+ {refreshing ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}+ {t("reports.refresh")}+ </button>+ </section>++ <section className="grid gap-3 lg:grid-cols-[minmax(220px,1fr)_160px_150px_150px_170px]">+ <label className="relative block">+ <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />+ <input+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ placeholder={t("reports.searchPlaceholder")}+ className="w-full rounded-md border bg-background py-2 pl-9 pr-3 text-sm outline-none transition focus:border-primary"+ />+ </label>+ <select+ value={statusFilter}+ onChange={(event) => setStatusFilter(event.target.value)}+ className="rounded-md border bg-background px-3 py-2 text-sm"+ >+ {statusOptions.map((status) => (+ <option key={status} value={status}>+ {status === "all" ? t("reports.allStatuses") : status}+ </option>+ ))}+ </select>+ <input+ type="date"+ value={startDate}+ onChange={(event) => setStartDate(event.target.value)}+ className="rounded-md border bg-background px-3 py-2 text-sm"+ aria-label={t("reports.startDate")}+ />+ <input+ type="date"+ value={endDate}+ onChange={(event) => setEndDate(event.target.value)}+ className="rounded-md border bg-background px-3 py-2 text-sm"+ aria-label={t("reports.endDate")}+ />+ <select+ value={sortMode}+ onChange={(event) => setSortMode(event.target.value as SortMode)}+ className="rounded-md border bg-background px-3 py-2 text-sm"+ aria-label={t("reports.sort")}+ >+ <option value="created_desc">{t("reports.sortNewest")}</option>+ <option value="created_asc">{t("reports.sortOldest")}</option>+ <option value="return_desc">{t("reports.sortReturn")}</option>+ <option value="sharpe_desc">{t("reports.sortSharpe")}</option>+ </select>+ </section>++ <div className="text-sm text-muted-foreground">+ {t("reports.count", { shown: filtered.length, total: runs.length })}+ </div>++ {loading ? (+ <div className="grid gap-3">+ {[1, 2, 3, 4].map((item) => (+ <div key={item} className="h-28 animate-pulse rounded-md border bg-muted/40" />+ ))}+ </div>+ ) : null}++ {!loading && error ? (+ <section className="rounded-md border border-amber-500/30 bg-amber-500/5 p-5">+ <div className="flex items-center gap-2 font-medium text-amber-700 dark:text-amber-300">+ <AlertTriangle className="h-5 w-5" />+ {t("reports.unavailable")}+ </div>+ <p className="mt-2 text-sm text-muted-foreground">{error}</p>+ </section>+ ) : null}++ {!loading && !error && filtered.length === 0 ? (+ <section className="rounded-md border border-dashed p-8 text-center">+ <FileText className="mx-auto h-8 w-8 text-muted-foreground" />+ <h2 className="mt-3 font-medium">{runs.length === 0 ? t("reports.emptyTitle") : t("reports.noMatchesTitle")}</h2>+ <p className="mt-1 text-sm text-muted-foreground">+ {runs.length === 0 ? t("reports.emptyBody") : t("reports.noMatchesBody")}+ </p>+ </section>+ ) : null}++ {!loading && !error && filtered.length > 0 ? (+ <section className="grid gap-3">+ {filtered.map((run) => (+ <ReportRow key={run.run_id} run={run} />+ ))}+ </section>+ ) : null}+ </div>+ </div>+ );+}++function ReportRow({ run }: { run: RunListItem }) {+ const { t } = useTranslation();+ return (+ <article className="rounded-md border p-4 transition hover:border-primary/40 hover:bg-muted/30">+ <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">+ <div className="min-w-0 space-y-2">+ <div className="flex flex-wrap items-center gap-2">+ <StatusBadge status={run.status} />+ <Link to={`/runs/${run.run_id}`} className="truncate font-mono text-sm font-medium hover:text-primary">+ {run.run_id}+ </Link>+ <span className="text-xs text-muted-foreground">{formatRunDate(run.created_at)}</span>+ </div>+ <p className="line-clamp-2 text-sm text-muted-foreground">{run.prompt || t("reports.noPrompt")}</p>+ <div className="flex flex-wrap gap-1.5">+ {(run.codes || []).slice(0, 6).map((code) => (+ <span key={code} className="rounded border px-2 py-0.5 font-mono text-xs text-muted-foreground">+ {code}+ </span>+ ))}+ {run.start_date || run.end_date ? (+ <span className="rounded border px-2 py-0.5 text-xs text-muted-foreground">+ {run.start_date || "?"} {t("reports.to")} {run.end_date || "?"}+ </span>+ ) : null}+ </div>+ </div>++ <div className="flex flex-col gap-3 lg:items-end">+ <div className="grid grid-cols-2 gap-2 text-right sm:flex sm:flex-wrap sm:justify-end">+ <MetricPill label={t("reports.return")} value={formatOptionalMetric("total_return", run.total_return)} />+ <MetricPill label={t("reports.sharpe")} value={formatOptionalMetric("sharpe", run.sharpe)} />+ </div>+ <div className="flex flex-wrap gap-2 lg:justify-end">+ <Link+ to={`/runs/${run.run_id}`}+ className="inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground transition hover:opacity-90"+ >+ {t("reports.fullReport")} <ArrowRight className="h-3.5 w-3.5" />+ </Link>+ <Link+ to="/compare"+ className="inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs font-medium transition hover:bg-muted"+ >+ <GitCompare className="h-3.5 w-3.5" />+ {t("reports.compare")}+ </Link>+ </div>+ </div>+ </div>+ </article>+ );+}++function StatusBadge({ status }: { status: string }) {+ const normalized = status.toLowerCase();+ const ok = ["success", "done", "completed", "complete"].includes(normalized);+ return (+ <span+ className={cn(+ "inline-flex items-center gap-1 rounded px-2 py-0.5 text-xs font-medium",+ ok ? "bg-success/10 text-success" : "bg-muted text-muted-foreground",+ )}+ >+ {ok ? <CheckCircle2 className="h-3 w-3" /> : <XCircle className="h-3 w-3" />}+ {status || "unknown"}+ </span>+ );+}++function MetricPill({ label, value }: { label: string; value: string }) {+ return (+ <div className="rounded-md border px-3 py-1.5">+ <div className="text-[11px] uppercase text-muted-foreground">{label}</div>+ <div className="font-mono text-sm font-medium">{value}</div>+ </div>+ );+}++function isBacktestReportRun(run: RunListItem): boolean {+ return Number.isFinite(run.total_return) || Number.isFinite(run.sharpe);+}++function compareRuns(left: RunListItem, right: RunListItem, mode: SortMode): number {+ if (mode === "created_asc") return dateMs(left.created_at) - dateMs(right.created_at);+ if (mode === "return_desc") return metric(right.total_return) - metric(left.total_return);+ if (mode === "sharpe_desc") return metric(right.sharpe) - metric(left.sharpe);+ return dateMs(right.created_at) - dateMs(left.created_at);+}++function metric(value: number | undefined): number {+ return Number.isFinite(value) ? Number(value) : Number.NEGATIVE_INFINITY;+}++function formatOptionalMetric(key: string, value: number | undefined): string {+ return Number.isFinite(value) ? formatMetricVal(key, value as number) : "-";+}++function dateMs(value: string): number {+ const parsed = Date.parse(value);+ return Number.isFinite(parsed) ? parsed : 0;+}++function formatRunDate(value: string): string {+ const parsed = new Date(value);+ if (!Number.isFinite(parsed.getTime())) return value || "unknown";+ return new Intl.DateTimeFormat(undefined, {+ month: "short",+ day: "numeric",+ hour: "2-digit",+ minute: "2-digit",+ }).format(parsed);+}diff --git a/frontend/src/pages/__tests__/Reports.test.tsx b/frontend/src/pages/__tests__/Reports.test.tsxnew file mode 100644index 000000000..c15da5048--- /dev/null+++ b/frontend/src/pages/__tests__/Reports.test.tsx@@ -0,0 +1,90 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { MemoryRouter } from "react-router-dom";+import { Reports } from "../Reports";++const apiMock = vi.hoisted(() => ({+ listRuns: vi.fn(),+}));++vi.mock("@/lib/api", () => ({+ api: apiMock,+}));++describe("Reports page", () => {+ beforeEach(() => {+ apiMock.listRuns.mockReset();+ });++ it("lists backtest reports newest first with Full Report links and skips non-report runs", async () => {+ apiMock.listRuns.mockResolvedValue([+ {+ run_id: "old-report",+ status: "success",+ created_at: "2026-06-01T00:00:00Z",+ prompt: "Old report",+ codes: ["MSFT"],+ total_return: 0.05,+ sharpe: 1.1,+ },+ {+ run_id: "chat-only",+ status: "success",+ created_at: "2026-06-03T00:00:00Z",+ prompt: "No metrics",+ codes: [],+ },+ {+ run_id: "new-report",+ status: "success",+ created_at: "2026-06-04T00:00:00Z",+ prompt: "New report",+ codes: ["AAPL"],+ total_return: 0.12,+ sharpe: 1.8,+ },+ ]);++ render(<Reports />, { wrapper: MemoryRouter });++ expect(await screen.findByText("Backtest Report Library")).toBeInTheDocument();+ expect(apiMock.listRuns).toHaveBeenCalledWith(100);+ expect(screen.queryByText("chat-only")).not.toBeInTheDocument();+ const reportRunLinks = screen.getAllByRole("link", { name: /-report$/ });+ expect(reportRunLinks[0]).toHaveAttribute("href", "/runs/new-report");+ expect(reportRunLinks[1]).toHaveAttribute("href", "/runs/old-report");+ const fullReportLinks = screen.getAllByRole("link", { name: "Full Report" });+ expect(fullReportLinks[0]).toHaveAttribute("href", "/runs/new-report");+ expect(fullReportLinks[1]).toHaveAttribute("href", "/runs/old-report");+ });++ it("filters reports by search text", async () => {+ apiMock.listRuns.mockResolvedValue([+ {+ run_id: "aapl-report",+ status: "success",+ created_at: "2026-06-04T00:00:00Z",+ prompt: "Apple strategy",+ codes: ["AAPL"],+ total_return: 0.12,+ },+ {+ run_id: "msft-report",+ status: "success",+ created_at: "2026-06-03T00:00:00Z",+ prompt: "Microsoft strategy",+ codes: ["MSFT"],+ total_return: 0.08,+ },+ ]);++ render(<Reports />, { wrapper: MemoryRouter });+ await screen.findByText("aapl-report");++ fireEvent.change(screen.getByPlaceholderText("Search run id, prompt, symbol, status..."), {+ target: { value: "MSFT" },+ });++ expect(screen.queryByText("aapl-report")).not.toBeInTheDocument();+ expect(screen.getByText("msft-report")).toBeInTheDocument();+ });+});diff --git a/frontend/src/router.tsx b/frontend/src/router.tsxindex 84f273dd3..a57fc735a 100644--- a/frontend/src/router.tsx+++ b/frontend/src/router.tsx@@ -16,6 +16,9 @@ const Settings = lazy(() =>const Runtime = lazy(() =>import("@/pages/Runtime").then((m) => ({ default: m.Runtime })),);+const Reports = lazy(() =>+ import("@/pages/Reports").then((m) => ({ default: m.Reports })),+);const Correlation = lazy(() =>import("@/pages/Correlation").then((m) => ({ default: m.Correlation })),);@@ -46,6 +49,7 @@ export const router = createBrowserRouter([{ path: "/", element: wrap(Home) },{ path: "/agent", element: wrap(Agent) },{ path: "/runtime", element: wrap(Runtime) },+ { path: "/reports", element: wrap(Reports) },{ path: "/settings", element: wrap(Settings) },{ path: "/runs/:runId", element: wrap(RunDetail) },{ path: "/compare", element: wrap(Compare) },