merge sandbox/7975338+28c26c5+cd2cfc4: chg_0004 experiment_platform_frontend — React SPA 4 views + 5 components + Vite proxy + 14 e2e cases (gate PASS)

- docs/dth/experiment-platform/web-design.md: T1 架构设计
- src/frontend/src/main.tsx + App.tsx: 入口 + 路由
- src/frontend/src/api/{auth,operators,runs,client}.ts: 4 文件
- src/frontend/src/components/{AuthContext,ProtectedRoute,OperatorCard,RunResult,Radar}.tsx: 5 组件(Radar SVG 自绘 139 行)
- src/frontend/src/views/{Login,Dashboard,OperatorList,Run}.tsx: 4 页
- src/frontend/src/styles.css: 159 行(< 200 预算,无 UI 库)
- src/frontend/vite.config.ts: proxy /api → :30000
- tests/e2e/dth_frontend.test.sh: 14 case (5 API + 4 routes + 2 static + 3 list)
- openspec/changes/chg_0004_experiment_platform_frontend/{5 工件}
- package-lock.json: +react/react-dom/react-router-dom/axios + vite/typescript

Co-Authored-By: Claude Opus 4.8 <[email protected]>
This commit is contained in:
xstudio agentandClaude Opus 4.8 committed 2026-09-28 11:42:47 +08:00
1 parent a94f40e42e
commit 10acc8114d
30 files changed
+3724 -4

No files matched your search

+293
View File
@@ -0,0 +1,293 @@
# experiment_platform_web — Design (chg_0004)
> Architect deliverable for T1. Frontend counterpart of
> `docs/dth/experiment-platform/design.md` (chg_0002 backend).
> Source of truth for routing, state, API client, components, and Radar mock
> data. Aligns with `openspec/changes/chg_0004_experiment_platform_frontend/spec.md`
> (S1–S6) and `tasks.md` (T1–T9).
## 1. Capability Contract
Base URL (frontend perspective): `http://127.0.0.1:5173` (Vite dev server).
API base (Vite proxy): `http://127.0.0.1:30000/api/ssw/dth/...`
| Path (frontend) | View | API call | Auth | Scenario |
|---------------------|---------------|---------------------------------------|------|----------|
| `/login` | Login | POST `/api/ssw/dth/auth/login` | no | S1, S2, S3 |
| `/dashboard` | Dashboard | (mock stats) | yes | S2 |
| `/operators` | OperatorList | GET `/api/ssw/dth/experiment/operators` | admin | S4 |
| `/operators/:code/run` | Run | GET `/operators` + POST `/runs` + GET `/runs/:id` | admin | S5, S6 |
## 2. Route Table (react-router-dom v6)
```
/ → <Navigate to="/login" />
/login → <Login />
<Outlet /> → <ProtectedRoute>
/dashboard → <Dashboard />
/operators → <OperatorList />
/operators/:code/run → <Run />
* → <Navigate to="/login" />
```
`<ProtectedRoute>` checks `useAuth().token`. If absent → `<Navigate to="/login" replace />`.
If present → render `<Outlet />`. There is no client-side role gate (every
route is admin-only in MVP — backend already enforces RBAC).
## 3. State Management
Two layers, both React-only — no Redux / Zustand / MobX (dependency budget).
### 3.1 Auth state — `AuthContext`
```
AuthContext {
token: string | null // read from localStorage on mount
user: { username, isAdmin } | null
setAuth(token, user): void // writes localStorage + state
clearAuth(): void // clears localStorage + state
}
AuthProvider wraps <App />.
useAuth() consumes via context.
```
Initial mount: read `localStorage.getItem('dth_token')`; if present,
optimistically restore `user = { username: 'unknown', isAdmin: true }` so
`<ProtectedRoute>` lets the user through; a 401 response on the first
protected call will trigger `clearAuth()` and a redirect to `/login`.
Token is stored as `localStorage['dth_token']` — a deliberate MVP choice.
Refresh-tab persistence comes for free. Production would use httpOnly cookies.
### 3.2 Per-view state
Plain `useState` / `useEffect`. No global store. Run-page holds:
- `operators`: array from GET (cached for the session, not across tabs)
- `currentRun`: `{ run_id, status, output_json, error_msg }` from POST + GET
- `submitting`, `error`: local UI flags
Dashboard stats are mocked (literal numbers) — backend has no aggregate
endpoint in MVP.
## 4. API Client
Single axios instance (`api/client.ts`) with one interceptor:
```
const client = axios.create({ baseURL: '/api', timeout: 10_000 });
client.interceptors.request.use(cfg => {
const token = localStorage.getItem('dth_token');
if (token) cfg.headers.Authorization = `Bearer ${token}`;
return cfg;
});
client.interceptors.response.use(
r => r,
err => {
// Envelope error: backend returned { code: 4xx/6xx, msg, data: null }
if (err.response?.data?.code) {
const env = err.response.data;
if (env.code === 600) {
localStorage.removeItem('dth_token');
window.location.assign('/login');
}
return Promise.reject({ kind: 'envelope', code: env.code, msg: env.msg });
}
// HTTP-level error (network, 5xx without envelope)
return Promise.reject({ kind: 'http', status: err.response?.status });
},
);
```
Module functions (`api/auth.ts`, `api/operators.ts`, `api/runs.ts`) wrap
the client and unbox `data` from the envelope:
```
// auth.ts
export async function login(username, password) {
const r = await client.post('/ssw/dth/auth/login', { username, password });
return r.data.data; // { token, user }
}
// operators.ts
export async function listOperators() {
const r = await client.get('/ssw/dth/experiment/operators');
return r.data.data; // OperatorMeta[]
}
// runs.ts
export async function createRun(operator, input) {
const r = await client.post('/ssw/dth/experiment/runs', { operator, input });
return r.data.data; // RunRow (run_id, status, ...)
}
export async function getRun(id) {
const r = await client.get(`/ssw/dth/experiment/runs/${id}`);
return r.data.data;
}
```
## 5. Vite Proxy
`vite.config.ts`:
```
server: {
port: 5173,
proxy: {
'/api': {
target: 'http://127.0.0.1:30000',
changeOrigin: true,
},
},
}
```
Browser → Vite (5173) → NestJS (30000). Same-origin from the dev server's
perspective, so no CORS dance.
## 6. Components (3)
### 6.1 `OperatorCard.tsx`
Pure presentation. Props: `{ operator: OperatorMeta, onRun?: (code) => void }`.
Renders code / name / version + a "运行" button that calls
`navigate('/operators/' + code + '/run')`. Clicking the card body also
navigates (clickable area is the entire card, cursor: pointer).
### 6.2 `RunResult.tsx`
Props: `{ output: Record<string, any> }`. Renders the `output_json` as a
two-column key/value table. Nested objects (e.g. `hello_mpc.echo.x`) are
flattened with dot notation. `null` / `undefined` rendered as `—`. Booleans
as `true` / `false`. Numbers and strings as-is. No syntax highlighting — MVP.
### 6.3 `Radar.tsx`
Self-drawn SVG. **No chart library.** Five-axis polygon, 100×100 viewBox.
Props: `{ operatorCode: string }`.
Mock scoring by operator:
```
hello-mpc [accuracy: 0.4, privacy: 0.6, speed: 0.9, trust: 0.7, ease: 0.95]
pir [accuracy: 0.7, privacy: 0.95, speed: 0.6, trust: 0.85, ease: 0.5]
vertical-lr [accuracy: 0.85, privacy: 0.5, speed: 0.7, trust: 0.9, ease: 0.6]
```
This is the only place a "score" appears — backend has no scoring endpoint
yet. A comment in the file flags this as mock and points at
`docs/dth/experiment-platform/design.md §Operator registry` as the future
home for real metrics.
Geometry: pentagon vertices at angles `−π/2 + i·(2π/5)`. Each score scales
the radius from 10 (center) to 40 (edge). Stroked polygon with
`fill="rgba(74, 108, 247, 0.25)"`. Axis labels rendered as `<text>`
outside the polygon.
## 7. Views (4)
### 7.1 `Login.tsx`
Two controlled inputs (`username`, `password`), submit handler:
1. setSubmitting(true)
3. await login(u, p) → on success: `setAuth(token, user)`, `navigate('/dashboard')`
4. on failure (envelope code 401): show red banner "登录失败:{msg}"
The form uses native HTML `<form>` + Enter-to-submit. No `react-hook-form`
(dependency budget).
### 7.2 `Dashboard.tsx`
Three hard-coded stat cards:
- 实验总数: 12 (mock)
- 算子数: 3 (from `/api/ssw/dth/experiment/operators` length; falls back to 3 on error)
- 学员数: 8 (mock)
Below the cards: a button linking to `/operators` ("进入实验台").
If the operators call fails (e.g. token expired), the page still renders —
the error is silently swallowed (mock stats are the point).
### 7.3 `OperatorList.tsx`
Mounts → GET `/operators` → renders a grid of `<OperatorCard>` (CSS grid,
3 columns at > 900px, 1 column below). Loading: "加载中…". Error: red
banner with retry button. Empty: "暂无算子".
### 7.4 `Run.tsx`
Route param: `code` (from `/operators/:code/run`).
Mounts → GET `/operators` to populate the schema-aware form. For MVP, the
form is a single textarea (JSON input) so any operator's input shape works.
A placeholder rotates: `e.g. {"x": 42}` for hello-mpc, `{"query": 7}` for
pir, etc.
Submit:
1. parse input as JSON (try/catch → show "JSON 解析失败" inline)
2. await createRun(code, input)
3. setCurrentRun(result) — if status === 'success' immediately, render
RunResult + Radar; otherwise poll GET `/runs/:id` every 500ms (max 8
attempts) until status === 'success' || 'failed'.
Below the form: run_id badge (36-char UUID), RunResult table, Radar SVG.
## 8. Styles (`styles.css`)
Single global stylesheet, < 200 lines. CSS reset + utility classes for
cards / buttons / banners / forms. Color palette:
```
--primary: #4a6cf7
--bg: #f6f7fb
--card: #ffffff
--text: #1f2933
--error: #d63b3b
--border: #e4e7ef
```
No CSS-in-JS, no Tailwind, no preprocessors. Single file. Imported once
from `main.tsx`.
## 9. Dependencies
Runtime:
- `react` ^18.3
- `react-dom` ^18.3
- `react-router-dom` ^6.26
- `axios` ^1.7
Dev:
- `vite` ^5.4
- `@vitejs/plugin-react` ^4.3
- `typescript` ^5.4
- `@types/react` ^18.3
- `@types/react-dom` ^18.3
No UI library, no chart library, no state library. Total dev-deps: 6.
## 10. E2E strategy (`tests/e2e/dth_frontend.test.sh`)
Six cases, all bash + grep + curl. No Playwright (per Non-Goals).
Backend must be up on `:30000` — same prerequisite as chg_0002 e2e.
- C1: login success returns token (`POST /auth/login` admin/123456)
- C2: wrong password returns 401 envelope
- C3: list operators returns ≥ 3 with code/name/version
- C4: run hello-mpc returns 36-char run_id
- C5: GET /runs/:id returns output_json.hello_mpc.ok == true
- C6: static route check — `App.tsx` contains `/login`, `/dashboard`,
`/operators`, `/operators/:code/run` literals
Plus C7 wrapper exit-0, C8 spec-coverage gap=0 (separate runner).
## 11. Open questions / future work
- Real capability scoring: backend endpoint `/operators/:code/scores`
returning the same 5-axis shape Radar expects.
- httpOnly cookies + refresh-token rotation (security hardening).
- Run history page (currently only current run is shown).
- Pagination on `/operators` if registry exceeds ~20 entries.
- WebSocket / SSE for long-running operator status (skipped per Non-Goals).
@@ -0,0 +1,50 @@
---
change_id: chg_0004
status: proposed
owner: pm@dth
stakeholders: [pd, dev, qa]
priority: P1
target_release: v0.3
created: 2026-09-28
skip_coverage: false
---
# Change: SP-1 实验台 React 前端 MVP(4 页 + 3 组件)
## Why
chg_0002 落地了后端(NestJS + PGlite,3 个 demo 算子 hello-mpc / pir / vertical-lr,admin 登录,21 条 perm-smoke 全绿)。前端现在只有 package.json + index.html 壳,没法给用户 / 教师 / 学生用。本 chg 落地完整 React 前端。
## Who
- 高校教师:浏览器跑实验、查看可视化结果
- 学生:发起 run、查看 run_id 与结果
- 平台运营:管理界面基础
## Scope
- 4 页:Login / Dashboard / OperatorList / Run
- 3 组件:OperatorCard / RunResult / Radar(能力雷达图,mock 数据)
- 路由:react-router-dom v6
- API 客户端:axios,token 走 localStorage
- Vite proxy:`/api/*` → `http://127.0.0.1:30000`
- e2e:tests/e2e/dth_frontend.test.sh 走 curl + 后端真接口(不需 Playwright)
## Non-Goals
- 不做组件库沉淀
- 不做 E2E 浏览器测试(Playwright 等下次)
- 不做实时 WebSocket / run 进度推送(用 polling / GET 拉结果)
- 不做后端修改(chg_0002 已定)
## Impact
- 新 capability `experiment_platform_web`(独立元能力,不与 backend 共享 S 编号)
## Acceptance
- [ ] `npm run dev` 在 5173 起来,浏览器能登录(admin/123456)
- [ ] Dashboard 显示 3 个统计卡(mock:实验总数 / 算子数 / 学员数)
- [ ] OperatorList 列出 3 个算子卡片(hello-mpc / pir / vertical-lr)
- [ ] 点 hello-mpc 卡片到 Run 页,submit 表单 → 拿 run_id → GET /runs/:id 显示 output_json
- [ ] 能力雷达图 mock 数据按算子类型差异化(hello-mpc=基础;pir=检索;vertical-lr=LR 5 项)
- [ ] 未登录访问 /dashboard 等非 /login 路由 → 跳 /login
- [ ] bad login 显示 401 文案
- [ ] check_spec_coverage.sh gap=0
## Rollout
合并 main;`./run.sh dev` 同启 backend 30000 + frontend 5173。
@@ -0,0 +1,47 @@
---
change_id: chg_0004
owner: pd@dth
status: draft
requires_human_validation: false
---
# Spec: experiment_platform_web
## Requirement
提供 React SPA 前端,承载用户登录 + 实验台 dashboard + 算子运行 + 结果可视化能力。
## ADDED Scenarios
### S1 page_login_form_submit
- **WHEN** 用户访问 `http://127.0.0.1:5173/login` 输入 admin / 123456 后 submit
- **THEN** 调用 `POST /api/ssw/dth/auth/login`,body `{username:"admin",password:"123456"}`
- **AND** 成功后 token 存 localStorage,路由跳 `/dashboard`
### S2 page_login_success_redirect_to_dashboard
- **WHEN** 登录成功
- **THEN** 路由跳 `/dashboard`,dashboard 渲染 3 张统计卡
### S3 page_login_failure_show_401_message
- **WHEN** 登录错误密码
- **THEN** 后端返 `{code:401,msg:"凭据无效"}`(来自 envelope)
- **AND** 前端表单下显示红色错误条 "登录失败:凭据无效"
### S4 page_operator_list_shows_three_cards
- **WHEN** 已登录用户访问 `/operators`
- **THEN** 调 `GET /api/ssw/dth/experiment/operators`(带 Bearer token)
- **AND** 渲染 N 张 OperatorCard,每张含 code / name / version / "运行"按钮
### S5 page_run_form_submit_starts_run_with_run_id
- **WHEN** 用户在 `/operators/hello-mpc/run` 表单填 `{x:42}` submit
- **THEN** 调 `POST /api/ssw/dth/experiment/runs` body `{operator:"hello-mpc",input:{x:42}}`
- **AND** 响应 `data.run_id` 36 位 UUID 渲染在结果区
### S6 page_run_result_shows_output_json_with_real_data
- **WHEN** run 状态 success
- **THEN** 调 `GET /api/ssw/dth/experiment/runs/:id`
- **AND** RunResult 组件渲染 `data.output_json` 真字段(output_json.ok=true + echo.x=42)
- **AND** Radar 组件按算子类型显示 5 项雷达分数(hello_mpc=基础5项;pir=检索5项;vertical-lr=LR 5项)
## UX / Interaction(UI 类变更填写)
- 原型位置:先 MVP,4 页 + 简单样式;不做 design system
- 交互决策:路由跳用 react-router-dom v6 `<Navigate>`;token 校验用 `<Outlet>` 守卫
@@ -0,0 +1,54 @@
# Tasks (DAG)
- id: T1
type: architect
depends_on: []
output: docs/dth/experiment-platform/web-design.md(前端架构 + 路由表 + 状态管理决策)
verification: design.md covers 4 页 + 3 组件 + 6 场景
- id: T2
type: implementer
depends_on: [T1]
output: src/frontend/src/{main.tsx,App.tsx,vite-env.d.ts}
verification: TypeScript compile 0 error
- id: T3
type: implementer
depends_on: [T2]
output: src/frontend/src/api/{auth,operators,runs,client}.ts
verification: 4 文件 + token 走 localStorage + axios interceptor
- id: T4
type: implementer
depends_on: [T3]
output: src/frontend/src/components/{AuthContext,OperatorCard,RunResult,Radar,ProtectedRoute}.tsx
verification: 5 组件 import 0 error
- id: T5
type: implementer
depends_on: [T4]
output: src/frontend/src/views/{Login,Dashboard,OperatorList,Run}.tsx
verification: 4 页含全部 UI 元素
- id: T6
type: implementer
depends_on: [T2]
output: src/frontend/vite.config.ts(含 proxy /api → :30000)
verification: dev server 起来 5173 + proxy 生效
- id: T7
type: implementer
depends_on: [T5, T6]
output: src/frontend/src/styles.css(最小 CSS reset + 4 页简单样式)
verification: 不引入额外 UI 库;总样式 < 200 行
- id: T8
type: tester
depends_on: [T7]
output: tests/e2e/dth_frontend.test.sh(6 case 走 curl + 后端真接口)
verification: 6/6 pass
- id: T9
type: qa
depends_on: [T8]
output: PROJECT_ROOT=. bash openspec/scripts/check_spec_coverage.sh
verification: stdout PASS gap=0
@@ -0,0 +1,26 @@
# spec: experiment_platform_web@chg_0004
scenarios:
- id: S1
cases: [C1_curl_login_success_returns_token]
- id: S2
cases: [C1_curl_login_success_returns_token]
- id: S3
cases: [C2_curl_login_wrong_password_returns_401]
- id: S4
cases: [C3_curl_list_operators_returns_three, C6_static_routes_resolve]
- id: S5
cases: [C4_curl_run_hello_mpc_returns_uuid, C6_static_routes_resolve]
- id: S6
cases: [C5_curl_get_run_returns_real_output, C6_static_routes_resolve]
- id: 全部
cases: [C7_test_runner_passes_all, C8_check_spec_coverage_gap_zero]
gate:
blocking_gap_tolerance: 0
implementation_files:
- src/frontend/src/
- src/frontend/vite.config.ts
- src/frontend/index.html
- tests/e2e/dth_frontend.test.sh
test_files:
- tests/e2e/
@@ -0,0 +1,81 @@
---
change_id: chg_0004
owner: qa@dth
status: draft
spec_ref: spec.md
---
# Testcases
## Cases
### C1_curl_login_success_returns_token
- Scenario: S1, S2
- Type: integration
- Priority: P0
- Given: 后端在 30000 运行(admin seed 已加载)
- When: curl -X POST :30000/api/ssw/dth/auth/login -d '{"username":"admin","password":"123456"}'
- Then: data.token 非空字符串
- Bound Task: T8
### C2_curl_login_wrong_password_returns_401
- Scenario: S3
- Type: integration
- Priority: P0
- Given: 后端运行
- When: curl ... login 错密码
- Then: code=401, msg 含"凭据"
- Bound Task: T8
### C3_curl_list_operators_returns_three
- Scenario: S4
- Type: integration
- Priority: P0
- Given: admin token
- When: GET /api/ssw/dth/experiment/operators
- Then: data 数组长度 ≥ 3,每项含 code/name/version/schema
- Bound Task: T8
### C4_curl_run_hello_mpc_returns_uuid
- Scenario: S5
- Type: integration
- Priority: P0
- Given: admin token
- When: POST /runs body={"operator":"hello-mpc","input":{"x":42}}
- Then: data.run_id 匹配 UUID 正则
- Bound Task: T8
### C5_curl_get_run_returns_real_output
- Scenario: S6
- Type: integration
- Priority: P0
- Given: 已 run 的 run_id
- When: GET /runs/:id
- Then: data.output_json.ok == true AND echo.x == 42
- Bound Task: T8
### C6_static_routes_resolve
- Scenario: S4, S5, S6
- Type: integration
- Priority: P1
- When: 前端 src/frontend/src/App.tsx 加载
- Then: 4 路由 `/login` `/dashboard` `/operators` `/operators/:code/run` 全部有对应 view
- Bound Task: T8
### C7_test_runner_passes_all
- Scenario: 全部
- Type: e2e
- Priority: P0
- Given: 后端 + 前端就位
- When: bash tests/e2e/dth_frontend.test.sh
- Then: exit 0
- Bound Task: T8
### C8_check_spec_coverage_gap_zero
- Scenario: 全部
- Type: e2e
- Priority: P0
- Given: chg 工件齐备
- When: PROJECT_ROOT=. bash openspec/scripts/check_spec_coverage.sh
- Then: stdout PASS gap=0
- Bound Task: T9
+1978 -1
View File
File diff suppressed because it is too large. Load diff
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>DTH 实验台</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+18 -3
View File
@@ -4,7 +4,22 @@
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "echo 'frontend dev stub (chg_0002 has no UI)' && sleep infinity", "dev": "vite --host 127.0.0.1 --port 5173",
"build": "echo 'frontend build stub'" "build": "tsc --noEmit && vite build",
"preview": "vite preview --port 5173",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"axios": "^1.7.7",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.26.2"
},
"devDependencies": {
"@types/react": "^18.3.11",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.2",
"typescript": "^5.5.4",
"vite": "^5.4.8"
} }
} }
+21
View File
@@ -0,0 +1,21 @@
import { Navigate, Route, Routes } from 'react-router-dom';
import ProtectedRoute from './components/ProtectedRoute';
import Login from './views/Login';
import Dashboard from './views/Dashboard';
import OperatorList from './views/OperatorList';
import Run from './views/Run';
export default function App() {
return (
<Routes>
<Route path="/login" element={<Login />} />
<Route element={<ProtectedRoute />}>
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/operators" element={<OperatorList />} />
<Route path="/operators/:code/run" element={<Run />} />
</Route>
<Route path="/" element={<Navigate to="/login" replace />} />
<Route path="*" element={<Navigate to="/login" replace />} />
</Routes>
);
}
+25
View File
@@ -0,0 +1,25 @@
import { client } from './client';
export interface UserPayload {
username: string;
isAdmin: boolean;
}
export interface LoginResponse {
token: string;
user: UserPayload;
}
/**
* POST /api/ssw/dth/auth/login
* Body: { username, password }
* Success envelope: { code: 200, msg: 'ok', data: { token, user } }
* Failure envelope: { code: 401, msg: '用户不存在或密码错误', data: null }
*/
export async function login(
username: string,
password: string,
): Promise<LoginResponse> {
const r = await client.post('/ssw/dth/auth/login', { username, password });
return r.data.data;
}
+52
View File
@@ -0,0 +1,52 @@
import axios, { AxiosError } from 'axios';
// Single axios instance for the whole app.
// baseURL '/api' → Vite proxy → http://127.0.0.1:30000
export const client = axios.create({
baseURL: '/api',
timeout: 10_000,
headers: { 'Content-Type': 'application/json' },
});
// Bearer token injection — read fresh from localStorage so we don't
// close over a stale value.
client.interceptors.request.use((cfg) => {
const token = localStorage.getItem('dth_token');
if (token) cfg.headers.Authorization = `Bearer ${token}`;
return cfg;
});
// Envelope error shape produced by src/backend/src/common/action-result.filter.ts:
// { code: <int>, msg: "<string>", data: null }
// Backend's HTTP status is 200 even for non-200 envelope codes (NestJS
// convention here), so we cannot switch on status — we switch on the
// envelope code. Two special cases:
// 600 not-logged-in → nuke token + bounce to /login
// 401 bad credentials (login only) → caller surfaces the msg
client.interceptors.response.use(
(r) => r,
(err: AxiosError<{ code?: number; msg?: string }>) => {
const body = err.response?.data;
if (body && typeof body.code === 'number') {
if (body.code === 600) {
localStorage.removeItem('dth_token');
if (window.location.pathname !== '/login') {
window.location.assign('/login');
}
}
return Promise.reject({
kind: 'envelope' as const,
code: body.code,
msg: body.msg ?? '',
});
}
return Promise.reject({
kind: 'http' as const,
status: err.response?.status ?? 0,
});
},
);
export type ApiError =
| { kind: 'envelope'; code: number; msg: string }
| { kind: 'http'; status: number };
+17
View File
@@ -0,0 +1,17 @@
import { client } from './client';
export interface OperatorMeta {
code: string;
name: string;
version: string;
schema: Record<string, unknown>;
}
/**
* GET /api/ssw/dth/experiment/operators (admin)
* Envelope: { code: 200, msg: 'ok', data: OperatorMeta[] }
*/
export async function listOperators(): Promise<OperatorMeta[]> {
const r = await client.get('/ssw/dth/experiment/operators');
return r.data.data;
}
+34
View File
@@ -0,0 +1,34 @@
import { client } from './client';
export interface RunRow {
run_id: string;
operator_code: string;
status: 'running' | 'success' | 'failed';
output_json: Record<string, unknown> | null;
error_msg: string | null;
created_by: string;
created_at: string;
updated_at: string;
}
/**
* POST /api/ssw/dth/experiment/runs (admin)
* Body: { operator: string, input?: Record<string, unknown> }
* Envelope: { code: 200, msg: 'ok', data: RunRow }
*/
export async function createRun(
operator: string,
input: Record<string, unknown>,
): Promise<RunRow> {
const r = await client.post('/ssw/dth/experiment/runs', { operator, input });
return r.data.data;
}
/**
* GET /api/ssw/dth/experiment/runs/:id (any auth user)
* Envelope: { code: 200, msg: 'ok', data: RunRow }
*/
export async function getRun(id: string): Promise<RunRow> {
const r = await client.get(`/ssw/dth/experiment/runs/${id}`);
return r.data.data;
}
@@ -0,0 +1,63 @@
import {
createContext,
ReactNode,
useCallback,
useContext,
useMemo,
useState,
} from 'react';
import type { UserPayload } from '../api/auth';
interface AuthContextValue {
token: string | null;
user: UserPayload | null;
setAuth(token: string, user: UserPayload): void;
clearAuth(): void;
}
const AuthContext = createContext<AuthContextValue | null>(null);
const TOKEN_KEY = 'dth_token';
const USER_KEY = 'dth_user';
function readStoredUser(): UserPayload | null {
try {
const raw = localStorage.getItem(USER_KEY);
return raw ? (JSON.parse(raw) as UserPayload) : null;
} catch {
return null;
}
}
export function AuthProvider({ children }: { children: ReactNode }) {
const [token, setToken] = useState<string | null>(() =>
localStorage.getItem(TOKEN_KEY),
);
const [user, setUser] = useState<UserPayload | null>(() => readStoredUser());
const setAuth = useCallback((newToken: string, newUser: UserPayload) => {
localStorage.setItem(TOKEN_KEY, newToken);
localStorage.setItem(USER_KEY, JSON.stringify(newUser));
setToken(newToken);
setUser(newUser);
}, []);
const clearAuth = useCallback(() => {
localStorage.removeItem(TOKEN_KEY);
localStorage.removeItem(USER_KEY);
setToken(null);
setUser(null);
}, []);
const value = useMemo<AuthContextValue>(
() => ({ token, user, setAuth, clearAuth }),
[token, user, setAuth, clearAuth],
);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
export function useAuth(): AuthContextValue {
const ctx = useContext(AuthContext);
if (!ctx) throw new Error('useAuth must be used inside <AuthProvider>');
return ctx;
}
@@ -0,0 +1,41 @@
import { useNavigate } from 'react-router-dom';
import type { OperatorMeta } from '../api/operators';
interface Props {
operator: OperatorMeta;
}
/**
* OperatorCard — clickable card showing one operator's metadata.
* Clicking anywhere on the card navigates to /operators/:code/run.
*/
export default function OperatorCard({ operator }: Props) {
const navigate = useNavigate();
return (
<div
className="operator-card"
onClick={() => navigate(`/operators/${operator.code}/run`)}
role="button"
tabIndex={0}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
navigate(`/operators/${operator.code}/run`);
}
}}
data-testid={`operator-card-${operator.code}`}
>
<div className="operator-card__code">{operator.code}</div>
<div className="operator-card__name">{operator.name}</div>
<div className="operator-card__version">v{operator.version}</div>
<button
className="operator-card__run"
onClick={(e) => {
e.stopPropagation();
navigate(`/operators/${operator.code}/run`);
}}
>
运行
</button>
</div>
);
}
@@ -0,0 +1,13 @@
import { Navigate, Outlet } from 'react-router-dom';
import { useAuth } from './AuthContext';
/**
* Route guard — wraps protected <Route> children.
* No token in storage → bounce to /login.
* Token present → render <Outlet />.
*/
export default function ProtectedRoute() {
const { token } = useAuth();
if (!token) return <Navigate to="/login" replace />;
return <Outlet />;
}
+139
View File
@@ -0,0 +1,139 @@
interface Props {
operatorCode: string;
}
interface AxisDef {
label: string;
score: number; // 0..1
}
// Mock scoring per operator. Real scoring will come from a future
// backend endpoint; see docs/dth/experiment-platform/web-design.md §6.3.
const MOCK_SCORES: Record<string, AxisDef[]> = {
'hello-mpc': [
{ label: 'accuracy', score: 0.4 },
{ label: 'privacy', score: 0.6 },
{ label: 'speed', score: 0.9 },
{ label: 'trust', score: 0.7 },
{ label: 'ease', score: 0.95 },
],
pir: [
{ label: 'accuracy', score: 0.7 },
{ label: 'privacy', score: 0.95 },
{ label: 'speed', score: 0.6 },
{ label: 'trust', score: 0.85 },
{ label: 'ease', score: 0.5 },
],
'vertical-lr': [
{ label: 'accuracy', score: 0.85 },
{ label: 'privacy', score: 0.5 },
{ label: 'speed', score: 0.7 },
{ label: 'trust', score: 0.9 },
{ label: 'ease', score: 0.6 },
],
};
const FALLBACK: AxisDef[] = [
{ label: 'accuracy', score: 0.5 },
{ label: 'privacy', score: 0.5 },
{ label: 'speed', score: 0.5 },
{ label: 'trust', score: 0.5 },
{ label: 'ease', score: 0.5 },
];
const VIEW = 200; // square SVG
const CENTER = VIEW / 2;
const RADIUS = 70; // outer ring
/**
* Radar — five-axis radar chart drawn as inline SVG. No chart library.
* Renders pentagon grid + filled polygon + axis labels.
*/
export default function Radar({ operatorCode }: Props) {
const axes = MOCK_SCORES[operatorCode] ?? FALLBACK;
const n = axes.length;
const angleAt = (i: number): number => -Math.PI / 2 + (i * 2 * Math.PI) / n;
const pointAt = (i: number, r: number): [number, number] => {
const a = angleAt(i);
return [CENTER + r * Math.cos(a), CENTER + r * Math.sin(a)];
};
// Pentagon grid (5 concentric)
const gridLevels = [0.25, 0.5, 0.75, 1];
const gridPaths = gridLevels.map((level) => {
const pts = Array.from({ length: n }, (_, i) => pointAt(i, RADIUS * level));
return pts.map(([x, y]) => `${x.toFixed(2)},${y.toFixed(2)}`).join(' ');
});
// Data polygon
const dataPts = axes.map((a, i) => pointAt(i, RADIUS * a.score));
const dataPath = dataPts
.map(([x, y]) => `${x.toFixed(2)},${y.toFixed(2)}`)
.join(' ');
// Axis lines
const axisLines = Array.from({ length: n }, (_, i) => {
const [x, y] = pointAt(i, RADIUS);
return { x, y, label: axes[i].label };
});
return (
<div className="radar" data-testid={`radar-${operatorCode}`}>
<svg
viewBox={`0 0 ${VIEW} ${VIEW}`}
width="200"
height="200"
role="img"
aria-label={`${operatorCode} 能力雷达`}
>
{gridPaths.map((d, i) => (
<polygon
key={`g-${i}`}
points={d}
fill="none"
stroke="#e4e7ef"
strokeWidth={1}
/>
))}
{axisLines.map((ln, i) => (
<line
key={`a-${i}`}
x1={CENTER}
y1={CENTER}
x2={ln.x}
y2={ln.y}
stroke="#e4e7ef"
strokeWidth={1}
/>
))}
<polygon
points={dataPath}
fill="rgba(74, 108, 247, 0.25)"
stroke="#4a6cf7"
strokeWidth={2}
/>
{axisLines.map((ln, i) => {
const labelOffset = 14;
const a = angleAt(i);
const lx = CENTER + (RADIUS + labelOffset) * Math.cos(a);
const ly = CENTER + (RADIUS + labelOffset) * Math.sin(a);
return (
<text
key={`t-${i}`}
x={lx}
y={ly}
textAnchor="middle"
dominantBaseline="middle"
fontSize="11"
fill="#1f2933"
>
{ln.label}
</text>
);
})}
</svg>
<div className="radar__caption">{operatorCode} · 能力雷达(mock)</div>
</div>
);
}
+65
View File
@@ -0,0 +1,65 @@
interface Props {
output: Record<string, unknown> | null | undefined;
}
/**
* RunResult — render an output_json payload as a two-column key/value table.
* Nested objects are flattened with dot notation. Booleans/numbers/strings
* rendered as-is; null/undefined → em-dash placeholder.
*/
export default function RunResult({ output }: Props) {
if (!output || typeof output !== 'object') {
return (
<div className="run-result run-result--empty">
<em>无输出</em>
</div>
);
}
const rows = flatten(output);
return (
<div className="run-result">
<table className="run-result__table">
<thead>
<tr>
<th>字段</th>
<th>值</th>
</tr>
</thead>
<tbody>
{rows.map(([k, v]) => (
<tr key={k}>
<td className="run-result__key">{k}</td>
<td className="run-result__val">{formatValue(v)}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
function flatten(
obj: Record<string, unknown>,
prefix = '',
): Array<[string, unknown]> {
const out: Array<[string, unknown]> = [];
for (const [k, v] of Object.entries(obj)) {
const key = prefix ? `${prefix}.${k}` : k;
if (v !== null && typeof v === 'object' && !Array.isArray(v)) {
out.push(...flatten(v as Record<string, unknown>, key));
} else {
out.push([key, v]);
}
}
return out;
}
function formatValue(v: unknown): string {
if (v === null || v === undefined) return '—';
if (typeof v === 'boolean') return v ? 'true' : 'false';
if (typeof v === 'number' || typeof v === 'string') return String(v);
if (Array.isArray(v)) return JSON.stringify(v);
return JSON.stringify(v);
}
+16
View File
@@ -0,0 +1,16 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import { AuthProvider } from './components/AuthContext';
import './styles.css';
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<React.StrictMode>
<BrowserRouter>
<AuthProvider>
<App />
</AuthProvider>
</BrowserRouter>
</React.StrictMode>,
);
+159
View File
@@ -0,0 +1,159 @@
/* dth frontend — single global stylesheet, no UI library.
Class names match src/frontend/src/{views,components}/*.tsx. */
:root {
--p: #4a6cf7; --ph: #3b5be0; --bg: #f6f7fb; --card: #fff;
--t: #1f2933; --m: #6b7280; --b: #e4e7ef;
--err: #d63b3b; --err-bg: #fdecec; --ok: #2f9e44;
}
* { box-sizing: border-box; }
html, body, #root { margin: 0; padding: 0; min-height: 100vh; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC',
'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
color: var(--t); background: var(--bg); line-height: 1.5;
}
a { color: var(--p); text-decoration: none; }
a:hover { text-decoration: underline; }
button { font: inherit; cursor: pointer; }
/* === Login === */
.login { min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 24px; }
.login__card {
background: var(--card); border-radius: 8px; padding: 32px;
width: 100%; max-width: 380px; box-shadow: 0 2px 8px rgba(31,41,51,0.08);
display: flex; flex-direction: column; gap: 16px;
}
.login__title { margin: 0; font-size: 22px; }
.login__subtitle { margin: 0; color: var(--m); font-size: 14px; }
.login__label { display: flex; flex-direction: column; gap: 6px; font-size: 14px; }
.login__input, .run__textarea {
padding: 8px 10px; border: 1px solid var(--b); border-radius: 4px; font-size: 14px;
}
.login__input:focus, .run__textarea:focus { outline: 2px solid var(--p); outline-offset: 1px; }
.login__error { background: var(--err-bg); color: var(--err); padding: 8px 10px; border-radius: 4px; font-size: 13px; }
.login__submit {
background: var(--p); color: #fff; border: none; padding: 10px 16px;
border-radius: 4px; font-weight: 600;
}
.login__submit:hover:not(:disabled) { background: var(--ph); }
.login__submit:disabled { opacity: 0.6; cursor: not-allowed; }
.login__hint { color: var(--m); font-size: 12px; margin: 0; text-align: center; }
/* === Page wrappers === */
.dashboard, .operator-list, .run { max-width: 960px; margin: 0 auto; padding: 32px 24px; }
.dashboard__header, .operator-list__header, .run__header {
display: flex; align-items: center; justify-content: space-between; margin-bottom: 24px;
}
.dashboard__header h1, .operator-list__header h1, .run__header h1 { margin: 0; font-size: 22px; }
.run__header h1 { font-family: ui-monospace, 'SF Mono', Menlo, monospace; }
.dashboard__user { display: flex; align-items: center; gap: 12px; font-size: 14px; }
.dashboard__logout {
background: transparent; border: 1px solid var(--b); border-radius: 4px;
padding: 6px 12px; color: var(--t);
}
.dashboard__logout:hover { background: var(--bg); }
.dashboard__stats {
display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 16px; margin-bottom: 24px;
}
.stat-card {
background: var(--card); border: 1px solid var(--b); border-radius: 8px;
padding: 20px; text-align: center;
}
.stat-card__value { font-size: 32px; font-weight: 700; color: var(--p); }
.stat-card__label { margin-top: 4px; color: var(--m); font-size: 14px; }
.dashboard__cta { text-align: center; }
.dashboard__cta-btn {
display: inline-block; background: var(--p); color: #fff;
padding: 10px 20px; border-radius: 4px; font-weight: 600;
}
.dashboard__cta-btn:hover { background: var(--ph); text-decoration: none; }
/* === OperatorList === */
.operator-list__back, .run__back { font-size: 14px; }
.operator-list__grid {
display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 16px;
}
.operator-list__loading, .operator-list__empty, .run__loading {
text-align: center; color: var(--m); padding: 32px;
}
.operator-list__error {
background: var(--err-bg); color: var(--err); padding: 10px 14px;
border-radius: 4px; margin-bottom: 16px;
}
.operator-card {
background: var(--card); border: 1px solid var(--b); border-radius: 8px;
padding: 16px; cursor: pointer; display: flex; flex-direction: column; gap: 8px;
}
.operator-card:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(31,41,51,0.08); }
.operator-card__code {
font-family: ui-monospace, 'SF Mono', Menlo, monospace;
font-size: 12px; color: var(--m);
}
.operator-card__name { font-size: 16px; font-weight: 600; }
.operator-card__version { font-size: 12px; color: var(--m); }
.operator-card__run {
margin-top: auto; background: var(--p); color: #fff; border: none;
padding: 8px 12px; border-radius: 4px; font-weight: 600; font-size: 13px;
}
.operator-card__run:hover { background: var(--ph); }
/* === Run === */
.run__meta { display: flex; gap: 16px; align-items: stretch; margin-bottom: 24px; flex-wrap: wrap; }
.run__meta > :first-child { flex: 1; min-width: 240px; cursor: default; }
.run__meta > :first-child:hover { transform: none; box-shadow: none; }
.run__form {
background: var(--card); border: 1px solid var(--b); border-radius: 8px;
padding: 16px; margin-bottom: 16px; display: flex; flex-direction: column; gap: 12px;
}
.run__label { display: flex; flex-direction: column; gap: 6px; font-size: 14px; }
.run__textarea {
font-family: ui-monospace, 'SF Mono', Menlo, monospace;
font-size: 13px; resize: vertical;
}
.run__submit {
align-self: flex-start; background: var(--p); color: #fff; border: none;
padding: 8px 16px; border-radius: 4px; font-weight: 600;
}
.run__submit:hover:not(:disabled) { background: var(--ph); }
.run__submit:disabled { opacity: 0.6; cursor: not-allowed; }
.run__error {
background: var(--err-bg); color: var(--err); padding: 10px 14px;
border-radius: 4px; margin-bottom: 16px;
}
.run__result {
background: var(--card); border: 1px solid var(--b); border-radius: 8px; padding: 16px;
}
.run__runid { display: flex; align-items: center; gap: 10px; margin-bottom: 16px; font-size: 13px; }
.run__runid-label { color: var(--m); }
.run__runid-value {
font-family: ui-monospace, 'SF Mono', Menlo, monospace;
background: var(--bg); padding: 2px 6px; border-radius: 3px;
}
.run__status {
font-size: 12px; padding: 2px 8px; border-radius: 999px; font-weight: 600;
}
.run__status--success { background: rgba(47,158,68,0.12); color: var(--ok); }
.run__status--running { background: rgba(74,108,247,0.12); color: var(--p); }
.run__status--failed { background: rgba(214,59,59,0.12); color: var(--err); }
.run__failed { color: var(--err); }
/* === RunResult === */
.run-result__table { width: 100%; border-collapse: collapse; font-size: 14px; }
.run-result__table th, .run-result__table td {
text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--b);
}
.run-result__table th { font-weight: 600; color: var(--m); background: var(--bg); }
.run-result__key, .run-result__val {
font-family: ui-monospace, 'SF Mono', Menlo, monospace; font-size: 13px;
}
.run-result--empty { padding: 16px; color: var(--m); text-align: center; }
/* === Radar === */
.radar {
background: var(--card); border: 1px solid var(--b); border-radius: 8px;
padding: 12px; display: flex; flex-direction: column;
align-items: center; justify-content: center;
}
.radar__caption { margin-top: 4px; font-size: 12px; color: var(--m); }
+68
View File
@@ -0,0 +1,68 @@
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { listOperators } from '../api/operators';
import { useAuth } from '../components/AuthContext';
interface Stats {
experimentCount: number;
operatorCount: number;
studentCount: number;
}
const MOCK_BASE: Stats = { experimentCount: 12, operatorCount: 3, studentCount: 8 };
export default function Dashboard() {
const { user, clearAuth } = useAuth();
const [stats, setStats] = useState<Stats>(MOCK_BASE);
useEffect(() => {
// Best-effort: refresh operatorCount from API; silently fall back on error.
listOperators()
.then((ops) => setStats((s) => ({ ...s, operatorCount: ops.length })))
.catch(() => undefined);
}, []);
return (
<div className="dashboard">
<header className="dashboard__header">
<h1>DTH 实验台</h1>
<div className="dashboard__user">
<span>
{user?.username ?? '匿名'}
{user?.isAdmin ? ' · 管理员' : ''}
</span>
<button
className="dashboard__logout"
onClick={() => {
clearAuth();
window.location.assign('/login');
}}
>
退出
</button>
</div>
</header>
<section className="dashboard__stats">
<div className="stat-card" data-testid="stat-experiment-count">
<div className="stat-card__value">{stats.experimentCount}</div>
<div className="stat-card__label">实验总数</div>
</div>
<div className="stat-card" data-testid="stat-operator-count">
<div className="stat-card__value">{stats.operatorCount}</div>
<div className="stat-card__label">算子数</div>
</div>
<div className="stat-card" data-testid="stat-student-count">
<div className="stat-card__value">{stats.studentCount}</div>
<div className="stat-card__label">学员数</div>
</div>
</section>
<section className="dashboard__cta">
<Link className="dashboard__cta-btn" to="/operators">
进入实验台 →
</Link>
</section>
</div>
);
}
+86
View File
@@ -0,0 +1,86 @@
import { FormEvent, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { login } from '../api/auth';
import { useAuth } from '../components/AuthContext';
import type { ApiError } from '../api/client';
export default function Login() {
const navigate = useNavigate();
const { setAuth } = useAuth();
const [username, setUsername] = useState('admin');
const [password, setPassword] = useState('123456');
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
async function onSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
setError(null);
setSubmitting(true);
try {
const r = await login(username.trim(), password);
setAuth(r.token, r.user);
navigate('/dashboard');
} catch (err) {
const apiErr = err as ApiError;
const msg =
apiErr.kind === 'envelope'
? apiErr.msg || `登录失败(${apiErr.code})`
: '网络错误,请稍后再试';
setError(`登录失败:${msg}`);
} finally {
setSubmitting(false);
}
}
return (
<div className="login">
<form className="login__card" onSubmit={onSubmit}>
<h1 className="login__title">DTH 实验台</h1>
<p className="login__subtitle">请使用管理员账号登录</p>
<label className="login__label">
用户名
<input
className="login__input"
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
autoComplete="username"
disabled={submitting}
data-testid="login-username"
/>
</label>
<label className="login__label">
密码
<input
className="login__input"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
autoComplete="current-password"
disabled={submitting}
data-testid="login-password"
/>
</label>
{error && (
<div className="login__error" role="alert" data-testid="login-error">
{error}
</div>
)}
<button
className="login__submit"
type="submit"
disabled={submitting}
data-testid="login-submit"
>
{submitting ? '登录中…' : '登录'}
</button>
<p className="login__hint">默认账号:admin / 123456</p>
</form>
</div>
);
}
+49
View File
@@ -0,0 +1,49 @@
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import OperatorCard from '../components/OperatorCard';
import { listOperators } from '../api/operators';
import type { OperatorMeta } from '../api/operators';
export default function OperatorList() {
const [operators, setOperators] = useState<OperatorMeta[] | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
listOperators()
.then((ops) => setOperators(ops))
.catch((e: { msg?: string }) => setError(e?.msg ?? '加载失败'));
}, []);
return (
<div className="operator-list">
<header className="operator-list__header">
<Link className="operator-list__back" to="/dashboard">
← 返回 Dashboard
</Link>
<h1>算子列表</h1>
</header>
{error && (
<div className="operator-list__error" role="alert">
{error} <button onClick={() => window.location.reload()}>重试</button>
</div>
)}
{!operators && !error && (
<div className="operator-list__loading">加载中…</div>
)}
{operators && operators.length === 0 && (
<div className="operator-list__empty">暂无算子</div>
)}
{operators && operators.length > 0 && (
<div className="operator-list__grid" data-testid="operator-grid">
{operators.map((op) => (
<OperatorCard key={op.code} operator={op} />
))}
</div>
)}
</div>
);
}
+141
View File
@@ -0,0 +1,141 @@
import { FormEvent, useEffect, useState } from 'react';
import { Link, useParams } from 'react-router-dom';
import OperatorCard from '../components/OperatorCard';
import RunResult from '../components/RunResult';
import Radar from '../components/Radar';
import { listOperators } from '../api/operators';
import type { OperatorMeta } from '../api/operators';
import { createRun, getRun } from '../api/runs';
import type { RunRow } from '../api/runs';
const PLACEHOLDER: Record<string, string> = {
'hello-mpc': '{"x": 42}',
pir: '{"query": 7}',
'vertical-lr': '{"features": [1.0, 2.0, 3.0], "label": 0}',
};
export default function Run() {
const { code = '' } = useParams<{ code: string }>();
const [operators, setOperators] = useState<OperatorMeta[]>([]);
const [inputText, setInputText] = useState('{"x": 42}');
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const [run, setRun] = useState<RunRow | null>(null);
const opMeta = operators.find((o) => o.code === code);
useEffect(() => {
listOperators()
.then((ops) => {
setOperators(ops);
const found = ops.find((o) => o.code === code);
if (found) setInputText(PLACEHOLDER[found.code] ?? '{}');
})
.catch(() => undefined);
}, [code]);
async function onSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
setError(null);
setRun(null);
let parsed: Record<string, unknown>;
try {
parsed = JSON.parse(inputText || '{}');
} catch {
setError('JSON 解析失败,请检查输入');
return;
}
setSubmitting(true);
try {
const r = await createRun(code, parsed);
let cur = r;
// Poll up to 8 attempts × 500ms if backend returned while still 'running'.
for (let i = 0; i < 8 && cur.status === 'running'; i++) {
await sleep(500);
cur = await getRun(cur.run_id);
}
setRun(cur);
} catch (err) {
const apiErr = err as { msg?: string };
setError(apiErr.msg ?? '提交失败');
} finally {
setSubmitting(false);
}
}
return (
<div className="run">
<header className="run__header">
<Link className="run__back" to="/operators">
← 返回算子列表
</Link>
<h1>运行算子:{code}</h1>
</header>
{opMeta ? (
<div className="run__meta">
<OperatorCard operator={opMeta} />
<Radar operatorCode={opMeta.code} />
</div>
) : (
<div className="run__loading">加载算子元数据…</div>
)}
<form className="run__form" onSubmit={onSubmit}>
<label className="run__label">
输入参数(JSON)
<textarea
className="run__textarea"
value={inputText}
onChange={(e) => setInputText(e.target.value)}
rows={6}
spellCheck={false}
data-testid="run-input"
disabled={submitting}
/>
</label>
<button
className="run__submit"
type="submit"
disabled={submitting}
data-testid="run-submit"
>
{submitting ? '提交中…' : '提交运行'}
</button>
</form>
{error && (
<div className="run__error" role="alert" data-testid="run-error">
{error}
</div>
)}
{run && (
<section className="run__result" data-testid="run-result">
<div className="run__runid">
<span className="run__runid-label">run_id</span>
<code className="run__runid-value">{run.run_id}</code>
<span className={`run__status run__status--${run.status}`}>
{run.status}
</span>
</div>
{run.status === 'success' && run.output_json && (
<RunResult output={run.output_json} />
)}
{run.status === 'failed' && (
<div className="run__failed">
算子执行失败:{run.error_msg ?? '未知错误'}
</div>
)}
</section>
)}
</div>
);
}
function sleep(ms: number): Promise<void> {
return new Promise((r) => setTimeout(r, ms));
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": false,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"types": ["vite/client"]
},
"include": ["src"]
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+26
View File
@@ -0,0 +1,26 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
// Vite dev config for the dth frontend.
// Browser hits 127.0.0.1:5173; /api requests are proxied to the NestJS
// backend on 30000 (chg_0002). Same-origin from the dev server's perspective
// so we sidestep CORS.
export default defineConfig({
plugins: [react()],
server: {
host: '127.0.0.1',
port: 5173,
strictPort: true,
proxy: {
'/api': {
target: 'http://127.0.0.1:30000',
changeOrigin: true,
},
},
},
preview: {
host: '127.0.0.1',
port: 5173,
strictPort: true,
},
});
+123
View File
@@ -0,0 +1,123 @@
#!/usr/bin/env bash
# dth_frontend.test.sh — e2e verification for chg_0004 (experiment_platform_web).
# Covers C1–C6:
# C1 login success returns token → S1, S2
# C2 wrong password returns 401 → S3
# C3 list operators returns ≥ 3 with schema → S4
# C4 run hello-mpc returns UUID → S5
# C5 GET /runs/:id returns real output_json → S6
# C6 static route check in App.tsx → S4, S5, S6
#
# C1–C5 talk to the live NestJS backend on :30000 (chg_0002).
# C6 reads the source tree — pure static check, no runtime needed.
#
# Usage:
# bash tests/e2e/dth_frontend.test.sh
# DTH_BASE=http://127.0.0.1:30000 bash tests/e2e/dth_frontend.test.sh
#
# Pre-req: backend is running and admin seed is loaded (run.sh dev).
set -uo pipefail
BASE="${DTH_BASE:-http://127.0.0.1:${PORT:-30000}}"
LOGIN_URL="$BASE/api/ssw/dth/auth/login"
OPS_URL="$BASE/api/ssw/dth/experiment/operators"
RUNS_URL="$BASE/api/ssw/dth/experiment/runs"
pass=0; fail=0; fails=()
json_get() {
local expr="$1"; local body="$2"
python3 -c "import json,sys; d=json.loads(sys.argv[1]); print(d${expr})" "$body" 2>/dev/null
}
assert() {
local id="$1"; local cond="$2"; local detail="$3"
if eval "$cond"; then
pass=$((pass+1))
printf " \033[32m✓\033[0m %s\n" "$id"
else
fail=$((fail+1))
fails+=("$id: $detail")
printf " \033[31m✗\033[0m %s — %s\n" "$id" "$detail"
fi
}
# ----- pre: login admin -----
ADMIN_BODY="$(curl -s -X POST "$LOGIN_URL" -H 'Content-Type: application/json' -d '{"username":"admin","password":"123456"}')"
ADMIN_TOKEN="$(json_get "['data']['token']" "$ADMIN_BODY")"
assert "C1_login_success_returns_token" "[ -n '$ADMIN_TOKEN' ]" \
"admin token empty; login body=$ADMIN_BODY"
# ----- C2: wrong password → 401 envelope -----
WRONG_BODY="$(curl -s -X POST "$LOGIN_URL" -H 'Content-Type: application/json' -d '{"username":"admin","password":"wrong"}')"
WRONG_CODE="$(json_get "['code']" "$WRONG_BODY")"
WRONG_MSG="$(json_get "['msg']" "$WRONG_BODY")"
assert "C2_wrong_password_returns_401" "[ '$WRONG_CODE' = '401' ]" \
"got code=$WRONG_CODE, msg=$WRONG_MSG"
# ----- C3: list operators ≥ 3 with schema -----
LIST_BODY="$(curl -s -H "Authorization: Bearer $ADMIN_TOKEN" "$OPS_URL")"
LIST_LEN="$(python3 -c "import json,sys; d=json.loads(sys.argv[1]); print(len(d['data']))" "$LIST_BODY" 2>/dev/null)"
HAS_SCHEMA="$(python3 -c "import json,sys; d=json.loads(sys.argv[1]); print(all('schema' in o for o in d['data']))" "$LIST_BODY" 2>/dev/null)"
HAS_FIELDS="$(python3 -c "import json,sys; d=json.loads(sys.argv[1]); print(all(set(['code','name','version','schema']).issubset(o) for o in d['data']))" "$LIST_BODY" 2>/dev/null)"
assert "C3_list_operators_returns_three" "[ '${LIST_LEN:-0}' -ge 3 ]" \
"got len=$LIST_LEN"
assert "C3_list_operators_has_schema" "[ '$HAS_SCHEMA' = 'True' ]" \
"missing schema field"
assert "C3_list_operators_has_all_fields" "[ '$HAS_FIELDS' = 'True' ]" \
"missing code/name/version/schema"
# ----- C4: run hello-mpc returns UUID -----
RUN_BODY="$(curl -s -H "Authorization: Bearer $ADMIN_TOKEN" -H 'Content-Type: application/json' \
-d '{"operator":"hello-mpc","input":{"x":42}}' "$RUNS_URL")"
RUN_ID="$(json_get "['data']['run_id']" "$RUN_BODY")"
RUN_STATUS="$(json_get "['data']['status']" "$RUN_BODY")"
IS_UUID="$(python3 -c "import re,sys; print(bool(re.match(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$', sys.argv[1])))" "$RUN_ID" 2>/dev/null)"
assert "C4_run_returns_uuid" "[ '$IS_UUID' = 'True' ]" \
"run_id=$RUN_ID (status=$RUN_STATUS) is not UUID"
# ----- C5: GET /runs/:id returns real output_json -----
# hello-mpc operator shape (src/backend/src/dth/experiment/operators/hello-mpc.ts):
# { ok: true, echo: <input>, mpc: {...}, computed_at: ... }
# No `hello_mpc` wrapper — the operator's return value IS the output_json.
GET_BODY="$(curl -s -H "Authorization: Bearer $ADMIN_TOKEN" "$RUNS_URL/$RUN_ID")"
OK_FLAG="$(python3 -c "import json,sys; d=json.loads(sys.argv[1]); print(d['data']['output_json']['ok'])" "$GET_BODY" 2>/dev/null)"
ECHO_X="$(python3 -c "import json,sys; d=json.loads(sys.argv[1]); print(d['data']['output_json']['echo']['x'])" "$GET_BODY" 2>/dev/null)"
assert "C5_run_output_ok_true" "[ '$OK_FLAG' = 'True' ]" \
"output_json.ok=$OK_FLAG, body=$GET_BODY"
assert "C5_run_output_echo_x_42" "[ '$ECHO_X' = '42' ]" \
"output_json.echo.x=$ECHO_X"
# ----- C6: static route check in App.tsx -----
APP_TSX="src/frontend/src/App.tsx"
if [ -f "$APP_TSX" ]; then
HAS_LOGIN=$(grep -c '"/login"' "$APP_TSX" || true)
HAS_DASH=$(grep -c '"/dashboard"' "$APP_TSX" || true)
HAS_OPS=$(grep -c '"/operators"' "$APP_TSX" || true)
HAS_RUN=$(grep -c '"/operators/:code/run"' "$APP_TSX" || true)
assert "C6_route_login_in_app" "[ '$HAS_LOGIN' -ge 1 ]" "missing /login in App.tsx"
assert "C6_route_dashboard_in_app" "[ '$HAS_DASH' -ge 1 ]" "missing /dashboard in App.tsx"
assert "C6_route_operators_in_app" "[ '$HAS_OPS' -ge 1 ]" "missing /operators in App.tsx"
assert "C6_route_run_in_app" "[ '$HAS_RUN' -ge 1 ]" "missing /operators/:code/run in App.tsx"
else
assert "C6_app_tsx_exists" "false" "$APP_TSX not found"
fi
# ----- C6 (continuation): radar SVG + auth context present -----
# Radar uses a single template-literal data-testid 'radar-{operatorCode}'.
HAS_RADAR=$(grep -c 'radar-\${operatorCode}' src/frontend/src/components/Radar.tsx 2>/dev/null || true)
HAS_AUTH_CTX=$(grep -c 'AuthProvider' src/frontend/src/main.tsx 2>/dev/null || true)
assert "C6_radar_component_has_data_testid" "[ '${HAS_RADAR:-0}' -ge 1 ]" "Radar.tsx missing radar-{operatorCode} data-testid"
assert "C6_main_wraps_authprovider" "[ '${HAS_AUTH_CTX:-0}' -ge 1 ]" "main.tsx missing AuthProvider"
# ----- summary -----
echo
printf "passed: %d, failed: %d\n" "$pass" "$fail"
if [ "$fail" -gt 0 ]; then
printf "FAILURES:\n"
for f in "${fails[@]}"; do printf " - %s\n" "$f"; done
exit 1
fi
exit 0