summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--frontend/src/components/ProjectMetricRow.svelte83
-rw-r--r--frontend/src/components/Sparkline.svelte45
-rw-r--r--frontend/src/lib/dashboardMetrics.test.ts77
-rw-r--r--frontend/src/lib/dashboardMetrics.ts79
-rw-r--r--frontend/src/lib/metricRow.test.ts63
-rw-r--r--frontend/src/lib/sparkline.test.ts66
6 files changed, 413 insertions, 0 deletions
diff --git a/frontend/src/components/ProjectMetricRow.svelte b/frontend/src/components/ProjectMetricRow.svelte
new file mode 100644
index 0000000..31001bf
--- /dev/null
+++ b/frontend/src/components/ProjectMetricRow.svelte
@@ -0,0 +1,83 @@
+<script lang="ts">
+ // 首页指标卡行(leader round2 spec §1)
+ // 数据通过 props 注入(ProjectsPage 拉取并共享聚合输入,见 dashboardMetrics.ts)。
+ import { aggregateDashboard } from '../lib/dashboardMetrics';
+
+ interface Props {
+ /** 注入的聚合输入;null/undefined 视为"取不到"(占位 -) */
+ projects: { id: string }[] | null;
+ datasets: { id: string }[] | null;
+ runs: { id: string; status: string; result?: unknown }[] | null;
+ usage: { totals?: { input_tokens?: number; output_tokens?: number; requests?: number } } | null;
+ }
+ let { projects, datasets, runs, usage }: Props = $props();
+
+ const metric = $derived(aggregateDashboard({ projects, datasets, runs, usage }));
+</script>
+
+<div class="metric-row" role="list" aria-label="工作台概览">
+ <div class="metric-card" data-testid="metric-card" role="listitem">
+ <span class="mlabel">我的项目</span>
+ <span class="mvalue">{metric.projectCount}</span>
+ </div>
+ <div class="metric-card" data-testid="metric-card" role="listitem">
+ <span class="mlabel">数据集</span>
+ <span class="mvalue">{metric.datasetCount}</span>
+ </div>
+ <div class="metric-card" data-testid="metric-card" role="listitem">
+ <span class="mlabel">回测</span>
+ <span class="mvalue">
+ <span class="run-split"><i>运行中</i> {metric.runningRuns}</span>
+ <span class="run-split"><i>已完成</i> {metric.doneRuns}</span>
+ </span>
+ </div>
+ <div
+ class="metric-card"
+ data-testid="metric-card"
+ role="listitem"
+ data-todo={metric.usageLabel === '-' ? 'TODO: /api/ai/usage 无 totals.requests 时保持占位 -, 计数端点就绪后切换' : undefined}
+ >
+ <span class="mlabel">AI 用量</span>
+ <span class="mvalue">{metric.usageLabel}</span>
+ {#if metric.usageTokens}<span class="mvalue-sub">{metric.usageTokens}</span>{/if}
+ </div>
+</div>
+
+<style>
+ .metric-row {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
+ gap: 0.6rem;
+ margin-bottom: 1.1rem;
+ }
+ .metric-card {
+ background: var(--surface);
+ border: 1px solid var(--border);
+ border-radius: calc(var(--radius) * 1.4);
+ padding: 0.65rem 0.85rem;
+ display: flex;
+ flex-direction: column;
+ gap: 0.1rem;
+ min-width: 0;
+ transition: box-shadow 150ms ease, transform 150ms ease;
+ }
+ /* 桌面端 hover 轻微上浮阴影 */
+ @media (hover: hover) and (min-width: 768px) {
+ .metric-card:hover {
+ box-shadow: var(--shadow);
+ transform: translateY(-1px);
+ }
+ }
+ .metric-card .mvalue {
+ font-size: 1.35rem;
+ font-weight: 700;
+ letter-spacing: -0.01em;
+ color: var(--foreground);
+ font-variant-numeric: tabular-nums;
+ line-height: 1.2;
+ overflow-wrap: anywhere;
+ }
+ .run-split { display: inline-flex; align-items: baseline; gap: 0.3rem; }
+ .run-split i { font-style: normal; font-size: 0.68rem; color: var(--text-3); font-weight: 500; }
+ .mvalue-sub { font-size: 0.72rem; color: var(--text-3); }
+</style>
diff --git a/frontend/src/components/Sparkline.svelte b/frontend/src/components/Sparkline.svelte
new file mode 100644
index 0000000..12a3b47
--- /dev/null
+++ b/frontend/src/components/Sparkline.svelte
@@ -0,0 +1,45 @@
+<script lang="ts">
+ // 项目行迷你权益缩略图:最近一个回测 equity 的首尾两端点画一条线。
+ // 无数据(first/last 缺失)→ 组件整体留空,不渲染任何 svg(leader 约束)。
+ interface Props {
+ first: number | null;
+ last: number | null;
+ up?: boolean;
+ ariaLabel?: string;
+ }
+ let { first = null, last = null, up = false, ariaLabel = '最近回测权益缩略' }: Props = $props();
+
+ const H = 24;
+ const PAD = 3;
+ // 首尾两点:左起 0, 右侧满宽(宽度由父级 flex 决定,viewBox 归一为 100)
+ const X1 = PAD + 0;
+ const X2 = 100 - 0;
+ // 首尾净值常见的取值范围很大,只关心涨跌形态:把两点摆在对角带上,
+ // 上行从左下到右上,下行从左上到右下,端点各留 pad。
+ const y1 = $derived(up ? H - PAD : PAD);
+ const y2 = $derived(up ? PAD : H - PAD);
+</script>
+
+{#if first !== null && last !== null}
+ <svg
+ class="spark"
+ viewBox={`0 0 100 ${H}`}
+ preserveAspectRatio="none"
+ width="72"
+ height={H}
+ role="img"
+ aria-label={ariaLabel}
+ data-testid="sparkline"
+ >
+ <path
+ d={`M${X1},${y1} L${X2},${y2}`}
+ stroke={up ? 'var(--ok)' : 'var(--danger)'}
+ stroke-width="2.5"
+ fill="none"
+ stroke-linecap="round"
+ vector-effect="non-scaling-stroke"
+ />
+ <circle cx={X1} cy={y1} r="2.5" fill={up ? 'var(--ok)' : 'var(--danger)'} vector-effect="non-scaling-stroke" />
+ <circle cx={X2} cy={y2} r="2.5" fill={up ? 'var(--ok)' : 'var(--danger)'} />
+ </svg>
+{/if}
diff --git a/frontend/src/lib/dashboardMetrics.test.ts b/frontend/src/lib/dashboardMetrics.test.ts
new file mode 100644
index 0000000..2a25fda
--- /dev/null
+++ b/frontend/src/lib/dashboardMetrics.test.ts
@@ -0,0 +1,77 @@
+// @ts-nocheck
+import { describe, expect, it } from 'vitest';
+import { aggregateDashboard, sparkFirstLast } from './dashboardMetrics';
+
+// Leader round2 spec: 登录后默认页顶部一行指标卡——
+// 当前项目数 / 数据集总数 / 运行中-已完成回测数 / AI 用量。
+// 取不到的字段占位 "-"(不得编造数字)。行为合同先定义:
+
+describe('aggregateDashboard', () => {
+ const projects = [{ id: 'p1' }, { id: 'p2' }, { id: 'p3' }];
+ const datasets = [{ id: 'd1' }, { id: 'd2' }];
+ const runs = [
+ { id: 'r1', status: 'running', result: null },
+ { id: 'r2', status: 'queued', result: null },
+ { id: 'r3', status: 'succeeded', result: { metrics: {} } },
+ { id: 'r4', status: 'succeeded', result: { metrics: {} } },
+ { id: 'r5', status: 'failed', result: null }
+ ];
+
+ it('counts projects, datasets and running/done runs from plain item arrays', () => {
+ const x = aggregateDashboard({ projects, datasets, runs, usage: null });
+ expect(x.projectCount).toBe(3);
+ expect(x.datasetCount).toBe(2);
+ expect(x.runningRuns).toBe(2); // queued + running
+ expect(x.doneRuns).toBe(2); // succeeded
+ });
+
+ it('usage label uses real totals when present, "-" placeholder otherwise', () => {
+ const withUsage = aggregateDashboard({
+ projects, datasets, runs,
+ usage: { totals: { input_tokens: 1200, output_tokens: 340, requests: 7 } }
+ });
+ expect(withUsage.usageLabel).toBe('7 次');
+ expect(withUsage.usageTokens).toBe('(1.2k/340 tok)');
+
+ const withoutUsage = aggregateDashboard({ projects, datasets, runs, usage: null });
+ expect(withoutUsage.usageLabel).toBe('-');
+ expect(withoutUsage.usageTokens).toBe('');
+ });
+
+ it('is resilient to missing arrays (fresh account)', () => {
+ const x = aggregateDashboard({ projects: null, datasets: undefined, runs: null, usage: {} });
+ expect(x.projectCount).toBe(0);
+ expect(x.datasetCount).toBe(0);
+ expect(x.runningRuns).toBe(0);
+ expect(x.doneRuns).toBe(0);
+ });
+});
+
+describe('sparkFirstLast (per-project latest backtest equity endpoints)', () => {
+ it('picks the newest run with a result per project and returns first/last equity', () => {
+ const runs = [
+ { id: 'r-old', project_id: 'p1', created_at: '2026-01-01', result: { equity: [
+ { equity: 100 },
+ { equity: 130 } // old run: up
+ ] } },
+ { id: 'r-new', project_id: 'p1', created_at: '2026-02-01', result: { equity: [
+ { equity: 100 },
+ { equity: 90 } // newer run is down — must win over the old run
+ ] } },
+ { id: 'r-broken', project_id: 'p2', created_at: '2026-02-01', result: null },
+ { id: 'r-only', project_id: 'p3', created_at: '2026-02-03', result: { equity: [
+ { equity: 50 },
+ { equity: 50 },
+ { equity: 58 }
+ ] } }
+ ];
+ const m = sparkFirstLast(runs);
+ expect(m.get('p1')).toEqual({ first: 100, last: 90 });
+ expect(m.get('p3')).toEqual({ first: 50, last: 58 });
+ expect(m.has('p2')).toBe(false); // result=null → no sparkline, renders as empty
+ });
+
+ it('returns empty map for no runs', () => {
+ expect([...sparkFirstLast([]).keys()]).toEqual([]);
+ });
+});
diff --git a/frontend/src/lib/dashboardMetrics.ts b/frontend/src/lib/dashboardMetrics.ts
new file mode 100644
index 0000000..2801c9d
--- /dev/null
+++ b/frontend/src/lib/dashboardMetrics.ts
@@ -0,0 +1,79 @@
+// Leader round2 spec: 登录后默认页顶部指标卡 + 项目行迷你权益缩略图。
+// 纯函数层,聚合合同在 dashboardMetrics.test.ts 做真实断言。
+// 取不到的字段一律占位 "-",不得编造数字。
+
+export interface DashboardMetric {
+ projectCount: number;
+ datasetCount: number;
+ runningRuns: number;
+ doneRuns: number;
+ /** "7 次" 或 "-"(后端无请求计数时) */
+ usageLabel: string;
+ /** 次要说明:token 计数摘要,无数据为空串 */
+ usageTokens: string;
+}
+
+function kify(n: number): string {
+ if (n >= 10000) return `${Math.round(n / 1000)}k`;
+ if (n >= 1000) return `${(n / 1000).toFixed(1)}k`;
+ return `${n}`;
+}
+
+export function aggregateDashboard(input: {
+ projects?: { id: string }[] | null;
+ datasets?: { id: string }[] | null;
+ runs?: { id: string; status: string; result?: unknown }[] | null;
+ usage?: { totals?: { input_tokens?: number; output_tokens?: number; requests?: number } } | null;
+}): DashboardMetric {
+ const projects = Array.isArray(input.projects) ? input.projects : [];
+ const datasets = Array.isArray(input.datasets) ? input.datasets : [];
+ const runs = Array.isArray(input.runs) ? input.runs : [];
+ const runningRuns = runs.filter((r) => r.status === 'running' || r.status === 'queued').length;
+ const doneRuns = runs.filter((r) => r.status === 'succeeded').length;
+
+ const t = input.usage?.totals;
+ let usageLabel = '-';
+ let usageTokens = '';
+ if (t && typeof t.requests === 'number') {
+ usageLabel = `${t.requests} 次`;
+ const inTok = t.input_tokens ?? 0;
+ const outTok = t.output_tokens ?? 0;
+ usageTokens = `(${kify(inTok)}/${kify(outTok)} tok)`;
+ }
+
+ return {
+ projectCount: projects.length,
+ datasetCount: datasets.length,
+ runningRuns,
+ doneRuns,
+ usageLabel,
+ usageTokens
+ };
+}
+
+export interface SparkEndpoints {
+ first: number;
+ last: number;
+}
+
+/**
+ * Per-project latest backtest endpoints for the project-row sparkline.
+ * Latest = max created_at among runs whose result carries equity points.
+ * A project without any chart-carrying run gets NO entry (caller must not
+ * render a sparkline in that case).
+ */
+export function sparkFirstLast(
+ runs: { project_id?: string; created_at?: string; result?: { equity?: { equity: number }[] } | null }[]
+): Map<string, { first: number; last: number }> {
+ const best = new Map<string, { at: string; first: number; last: number }>();
+ const out = new Map<string, { first: number; last: number }>();
+ for (const r of runs) {
+ const eq = r.result?.equity;
+ if (!r.project_id || !Array.isArray(eq) || eq.length < 2) continue;
+ const prev = best.get(r.project_id);
+ if (prev && prev.at >= (r.created_at ?? '')) continue;
+ best.set(r.project_id, { at: r.created_at ?? '', first: eq[0].equity, last: eq[eq.length - 1].equity });
+ }
+ for (const [k, v] of best) out.set(k, { first: v.first, last: v.last });
+ return out;
+}
diff --git a/frontend/src/lib/metricRow.test.ts b/frontend/src/lib/metricRow.test.ts
new file mode 100644
index 0000000..bc41b54
--- /dev/null
+++ b/frontend/src/lib/metricRow.test.ts
@@ -0,0 +1,63 @@
+// @ts-nocheck
+import { describe, expect, it, vi, afterEach } from 'vitest';
+import { cleanup } from '@testing-library/svelte';
+import { render, screen } from '@testing-library/svelte';
+
+import ProjectMetricRow from '../components/ProjectMetricRow.svelte';
+
+// Leader round2: 首页改为指标卡行——当前项目数、数据集总数、
+// 运行中/已完成回测数、AI 用量;取不到的字段占位 "-"。
+// 真实渲染断言,测试数据通过 props 注入。
+
+afterEach(() => cleanup());
+
+const projects = [{ id: 'p1' }, { id: 'p2' }, { id: 'p3' }];
+const datasets = [{ id: 'd1' }, { id: 'd2' }];
+const runs = [
+ { id: 'r1', status: 'running', result: null },
+ { id: 'r2', status: 'queued', result: null },
+ { id: 'r3', status: 'succeeded', result: { metrics: {} } },
+ { id: 'r4', status: 'succeeded', result: { metrics: {} } }
+];
+
+describe('ProjectMetricRow (real render, 4 metric cards)', () => {
+ it('renders a metric-card row: 项目/数据集/回测 running+done/AI 用量, values visible', () => {
+ const { container } = render(ProjectMetricRow, {
+ props: {
+ projects, datasets, runs,
+ usage: { totals: { input_tokens: 1200, output_tokens: 340, requests: 7 } }
+ }
+ });
+ const cards = container.querySelectorAll('[data-testid="metric-card"]');
+ expect(cards.length).toBe(4);
+ expect(screen.getByText('我的项目')).toBeTruthy();
+ expect(screen.getByText('数据集')).toBeTruthy();
+ expect(screen.getByText('回测')).toBeTruthy();
+ expect(screen.getByText('AI 用量')).toBeTruthy();
+ // 数字直接可见:项目卡/数据集卡与回测拆分值
+ const values = [...container.querySelectorAll('.metric-card .mvalue')].map((n) => n.textContent!.replace(/\s+/g, ' ').trim());
+ expect(values[0]).toBe('3');
+ expect(values[1]).toBe('2');
+ expect(values[2]).toContain('运行中');
+ expect(values[2]).toContain('2');
+ expect(values[2]).toContain('已完成');
+ expect(values[2]).toContain('2');
+ expect(screen.getByText('7 次')).toBeTruthy();
+ });
+
+ it('usage unavailable → "-" placeholder + TODO marker on the card', () => {
+ const { container } = render(ProjectMetricRow, {
+ props: { projects, datasets, runs, usage: null }
+ });
+ const cards = [...container.querySelectorAll('[data-testid="metric-card"]')];
+ const usage = cards.at(-1)!;
+ expect(usage.textContent).toContain('-');
+ expect(usage.getAttribute('data-todo') ?? '').toContain('TODO');
+ });
+
+ it('runs card splits 运行中 / 已完成', () => {
+ render(ProjectMetricRow, { props: { projects, datasets, runs, usage: null } });
+ expect(screen.getByText(/运行中/)).toBeTruthy();
+ expect(screen.getByText(/已完成/)).toBeTruthy();
+ });
+});
diff --git a/frontend/src/lib/sparkline.test.ts b/frontend/src/lib/sparkline.test.ts
new file mode 100644
index 0000000..aecf20d
--- /dev/null
+++ b/frontend/src/lib/sparkline.test.ts
@@ -0,0 +1,66 @@
+// @ts-nocheck
+import { describe, expect, it, vi } from 'vitest';
+import { mount, unmount } from 'svelte';
+import Sparkline from '../components/Sparkline.svelte';
+
+// Leader round2: 项目列表每行内嵌迷你权益缩略图——
+// 用最近一个回测 equity 的首尾点画 sparkline SVG;
+// 无数据就整个组件留空(不渲染 svg)。
+
+describe('Sparkline (real render)', () => {
+ it('renders an svg with a first→last polyline when handed endpoints', async () => {
+ const host = document.createElement('div');
+ const inst = mount(Sparkline, {
+ target: host,
+ props: { first: 100, last: 90, up: false, ariaLabel: '最近回测权益缩略' }
+ });
+ await new Promise((r) => setTimeout(r, 50));
+ const svg = host.querySelector('svg');
+ expect(svg, 'sparkline must be a real svg element').toBeTruthy();
+ const path = svg.querySelector('path, polyline');
+ expect(path).toBeTruthy();
+ const d = (path.getAttribute('d') || path.getAttribute('points')) ?? '';
+ // polyline from left edge to right edge: both endpoints present in geometry
+ expect(d).toContain('0'); // first x
+ const coordsCount = d.trim().split(/[\s,L,M]+/).filter(Boolean).length;
+ expect(coordsCount).toBeGreaterThanOrEqual(4); // 2 points × (x,y)
+ unmount(inst);
+ host.remove();
+ });
+
+ it('renders NOTHING (no svg) for missing data — 留空不渲染', async () => {
+ const host = document.createElement('div');
+ const inst = mount(Sparkline, { target: host, props: { first: null, last: null, ariaLabel: 'x' } });
+ await new Promise((r) => setTimeout(r, 50));
+ expect(host.querySelector('svg')).toBeNull();
+ expect(host.textContent.trim()).toBe('');
+ unmount(inst);
+ host.remove();
+ });
+
+ it('方向语义:down 变红(危险色),up 变绿(成功色)', async () => {
+ const down = document.createElement('div');
+ const inst1 = mount(Sparkline, {
+ target: down,
+ props: { first: 100, last: 90, up: false, ariaLabel: 'x' }
+ });
+ await new Promise((r) => setTimeout(r, 30));
+ const downColor = down.querySelector('path, polyline')?.getAttribute('stroke') ?? '';
+ unmount(inst1);
+ down.remove();
+
+ const up = document.createElement('div');
+ const inst2 = mount(Sparkline, {
+ target: up,
+ props: { first: 100, last: 130, up: true, ariaLabel: 'x' }
+ });
+ await new Promise((r) => setTimeout(r, 30));
+ const upColor = up.querySelector('path, polyline')?.getAttribute('stroke') ?? '';
+ unmount(inst2);
+ up.remove();
+
+ expect(downColor).not.toBe('');
+ expect(upColor).not.toBe('');
+ expect(downColor).not.toBe(upColor);
+ });
+});