# Console UI Refactor (console10) Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Rebuild `apps/web` as a Preact + Vite SPA with 5-page IA, design tokens, modular API client, and responsive shell — zero backend contract changes.
**Architecture:** Scaffold Vite under `apps/web`, port each page into Preact components driven by `@preact/signals`, keep cookie/Bearer auth and all `/api/*` paths identical. Build outputs to `apps/web/dist`; FastAPI mounts `dist` (legacy console9 stays until parity). Deploy builds locally then scp `dist` to pxed (model B).
**Tech Stack:** Preact 10 + `@preact/signals`, Vite 6, CSS custom properties (no Tailwind), FastAPI StaticFiles, Python backend untouched.
## Global Constraints
- **Backend zero-change:** no edits to `/api/*` contracts, auth, runs, nodes, accounts, import, ops.
- **Product contract:** disk-first; supervisor hard-forces `CPA_PROBE_CHAT=false` / mid-bulk inject off; UI must still send those knobs as today.
- **Auth:** cookie session + optional Bearer in `sessionStorage` (`controlToken`); login gate; 401 → show gate.
- **GitHub banner:** keep `https://github.com/dengyie/ai-register-machine`.
- **Deploy model B:** in-repo; build locally; scp `dist`; do not disrupt live batch on pxed.
- **Poll interval:** keep ~4s for run status; `regFormDirty` equivalent must not wipe form edits on poll.
- **Ops feedback:** never silent top-bar actions — toast + sticky banner + ops log.
- **Stop UX:** confirm before stop (kills lock-held external supervisors); no chromium pkill UI.
- **Copy language:** Chinese UI labels as today.
- **Repo path:** `/Users/mango/project/claude-project/grok-register`
- **Spec:** `docs/superpowers/specs/2026-07-22-console-ui-refactor-design.md`
- **Baseline:** console9 `apps/web/index.html` + `assets/app.js` + `assets/app.css`; FastAPI mount `apps/control_api/app.py:98-100`
## File map
| Path | Role |
|------|------|
| `apps/web/package.json` | preact, @preact/signals, vite, @preact/preset-vite |
| `apps/web/vite.config.js` | base `/`, outDir `dist`, emptyOutDir true, dev proxy `/api` → `http://127.0.0.1:8787` |
| `apps/web/index.html` | Vite entry (replaces legacy root after cutover) |
| `apps/web/src/main.jsx` | render `` into `#root` |
| `apps/web/src/App.jsx` | auth gate + shell + hash router |
| `apps/web/src/api/client.js` | `api()`, `headers()`, multipart, all endpoint helpers |
| `apps/web/src/store/*.js` | signals: session, run, feedback, config, accounts, nodes |
| `apps/web/src/lib/format.js` | `pct`, `fmtNum`, `dash`, `escapeHtml`, `healthBadge`, `formatApiError` |
| `apps/web/src/ui/*` | Button, Card, Field, Select, Table, ToastHost, StatusDot, Chip, Kpi, Bar, Tabs, Drawer |
| `apps/web/src/styles/tokens.css` | design tokens |
| `apps/web/src/styles/base.css` | reset + shell layout + responsive |
| `apps/web/src/styles/components.css` | primitive component styles |
| `apps/web/src/pages/Register/*` | form + RunProgress pipeline |
| `apps/web/src/pages/Logs/*` | tail + history |
| `apps/web/src/pages/Accounts/*` | table + filters |
| `apps/web/src/pages/Resources/*` | tabs: Nodes, Mail, Import |
| `apps/web/src/pages/Settings/*` | secrets + bearer + selfcheck/cleanup only |
| `apps/control_api/app.py` | mount prefers `web/dist` then falls back to `web` |
| `scripts/build_web_console.sh` | `npm ci && npm run build` in `apps/web` |
| `scripts/deploy_web_console10.sh` | build + scp `dist` to pxed (manual) |
| `apps/web/legacy/` | move console9 files here during cutover so rollback is one path flip |
| `.gitignore` | ensure `apps/web/node_modules/` ignored (root already has `dist/`) |
**Does not touch:** progress.py, runs semantics, coinbot, clash import backend, auth backend.
---
### Task 1: Scaffold Vite + Preact under `apps/web`
**Files:**
- Create: `apps/web/package.json`
- Create: `apps/web/vite.config.js`
- Create: `apps/web/src/main.jsx`
- Create: `apps/web/src/App.jsx` (hello shell)
- Create: `apps/web/src/styles/tokens.css`, `base.css`
- Modify: `.gitignore` — add `apps/web/node_modules/` if missing
- Keep: existing `apps/web/index.html` + `assets/*` until Task 9 cutover (scaffold uses a temporary entry or coexists carefully — see steps)
**Interfaces:**
- Consumes: none
- Produces: `npm run dev` / `npm run build` work; `dist/index.html` + assets
- [ ] **Step 1: Create package.json**
```json
{
"name": "ai-register-console",
"private": true,
"version": "10.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"preact": "^10.26.4",
"@preact/signals": "^2.0.4"
},
"devDependencies": {
"@preact/preset-vite": "^2.10.1",
"vite": "^6.2.0"
}
}
```
- [ ] **Step 2: Create vite.config.js**
```js
import { defineConfig } from "vite";
import preact from "@preact/preset-vite";
import { resolve } from "node:path";
export default defineConfig({
plugins: [preact()],
base: "/",
root: resolve(__dirname),
publicDir: false,
build: {
outDir: "dist",
emptyOutDir: true,
sourcemap: true,
},
server: {
port: 5173,
proxy: {
"/api": {
target: "http://127.0.0.1:8787",
changeOrigin: true,
},
},
},
});
```
- [ ] **Step 3: Move legacy console9 aside and add Vite entry**
```bash
mkdir -p apps/web/legacy
mv apps/web/index.html apps/web/legacy/index.html
mv apps/web/assets apps/web/legacy/assets
```
Create new `apps/web/index.html`:
```html
AI 注册机 · Control Plane
```
> Rollback path: restore `legacy/` to root and revert FastAPI mount.
- [ ] **Step 4: Hello App**
`src/main.jsx`:
```jsx
import { render } from "preact";
import { App } from "./App.jsx";
import "./styles/tokens.css";
import "./styles/base.css";
render(, document.getElementById("root"));
```
`src/App.jsx`:
```jsx
export function App() {
return (
AI 注册机 · console10 scaffold
Vite + Preact OK
);
}
```
`src/styles/tokens.css` — port color roles from legacy `app.css:1-17`:
```css
:root {
--bg: #0b0f14;
--panel: #121a24;
--panel-2: #182231;
--text: #e8eef7;
--muted: #8b9bb4;
--accent: #5b9fd4;
--accent-2: #3d7eb0;
--danger: #d45b5b;
--ok: #5bd49a;
--warn: #d4b15b;
--border: #243044;
--sidebar: #0a1018;
--sidebar-w: 220px;
--radius-sm: 6px;
--radius-md: 10px;
--radius-lg: 14px;
--space-1: 4px;
--space-2: 8px;
--space-3: 12px;
--space-4: 16px;
--space-5: 24px;
--space-6: 32px;
--font: ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
--shadow-card: 0 18px 50px rgba(0, 0, 0, 0.35);
}
```
`src/styles/base.css` minimal:
```css
* { box-sizing: border-box; }
html, body { margin: 0; min-height: 100%; background: var(--bg); color: var(--text); font-family: var(--font); }
.hidden { display: none !important; }
.hint { color: var(--muted); font-size: 0.9rem; }
```
- [ ] **Step 5: Install + verify**
```bash
cd apps/web && npm install
npm run build
ls dist/index.html dist/assets/
```
Expected: build succeeds; `dist/` contains hashed JS/CSS.
```bash
npm run dev
# open http://127.0.0.1:5173 — stub page renders
```
- [ ] **Step 6: Commit**
```bash
git add apps/web/package.json apps/web/package-lock.json apps/web/vite.config.js \
apps/web/index.html apps/web/src apps/web/legacy .gitignore
git commit -m "feat(web): scaffold console10 Vite+Preact (legacy → apps/web/legacy)"
```
---
### Task 2: API client + format helpers
**Files:**
- Create: `apps/web/src/api/client.js`
- Create: `apps/web/src/lib/format.js`
- Create: `apps/web/src/store/session.js`
- Test manually against running control_api (or unit-test helpers with node)
**Interfaces:**
- Consumes: `/api/*` as listed in spec §5
- Produces:
- `api(path, opts)` → body or throws `Error` with `.status`
- `headers(json?: boolean)`
- `getToken()` / `setToken(t)` / `clearToken()`
- named helpers: `login`, `logout`, `me`, `overview`, `getConfig`, `putConfig`, `startRun`, `stopRun`, `currentRun`, `listRuns`, `runLogs`, `listAccounts`, `listClashNodes`, `importClashUrl`, `testClash`, `listCatalogNodes`, `testCatalog`, `importNodes`, `importMail`, `importAuths`, `importPack`, `selfcheck`, `cleanupOrphans`
- format: `pct(a,b)`, `fmtNum(v)`, `dash(v)`, `escapeHtml(s)`, `formatApiError(e)`, `healthBadge(h)`
- [ ] **Step 1: Write format helpers** (`src/lib/format.js`)
```js
export function escapeHtml(s) {
return String(s ?? "")
.replace(/&/g, "&")
.replace(//g, ">")
.replace(/"/g, """);
}
export function dash(v) {
return v == null || v === "" ? "—" : String(v);
}
export function fmtNum(v) {
return v == null || v === "" ? "—" : String(v);
}
export function pct(a, b) {
if (b == null || a == null || Number(b) <= 0) return null;
return Math.max(0, Math.min(100, (Number(a) / Number(b)) * 100));
}
export function formatApiError(e) {
if (!e) return "unknown error";
if (typeof e === "string") return e;
if (e.message) return e.status ? `${e.status}: ${e.message}` : e.message;
return String(e);
}
export function healthBadge(h) {
if (h === "ok" || h === true) return { label: "ok", cls: "ok" };
if (h === "fail" || h === false) return { label: "fail", cls: "danger" };
return { label: "?", cls: "muted" };
}
```
- [ ] **Step 2: Write API client** (`src/api/client.js`)
Port logic from legacy `app.js` `token`/`headers`/`api`/`postMultipart` exactly:
```js
const TOKEN_KEY = "controlToken";
export function getToken() {
return sessionStorage.getItem(TOKEN_KEY) || "";
}
export function setToken(t) {
if (t) sessionStorage.setItem(TOKEN_KEY, t);
else sessionStorage.removeItem(TOKEN_KEY);
}
export function clearToken() {
sessionStorage.removeItem(TOKEN_KEY);
}
export function headers(json = false) {
const h = {};
if (json) h["Content-Type"] = "application/json";
const t = getToken();
if (t) h["Authorization"] = `Bearer ${t}`;
return h;
}
export async function api(path, opts = {}) {
const res = await fetch(path, { credentials: "same-origin", ...opts });
const text = await res.text();
let body;
try {
body = text ? JSON.parse(text) : {};
} catch {
body = { detail: text };
}
if (!res.ok) {
const detail = body.detail || res.statusText;
const err = new Error(typeof detail === "string" ? detail : JSON.stringify(detail));
err.status = res.status;
throw err;
}
return body;
}
export async function postMultipart(url, formData) {
const res = await fetch(url, {
method: "POST",
headers: headers(),
body: formData,
credentials: "same-origin",
});
const body = await res.json().catch(() => ({}));
if (!res.ok) {
const err = new Error(body.detail || res.statusText);
err.status = res.status;
throw err;
}
return body;
}
// Auth
export const login = (username, password) =>
api("/api/auth/login", {
method: "POST",
headers: headers(true),
body: JSON.stringify({ username, password }),
});
export const logout = () => api("/api/auth/logout", { method: "POST", headers: headers(true) });
export const me = () => api("/api/auth/me");
// Core
export const overview = () => api("/api/overview");
export const getConfig = () => api("/api/config");
export const putConfig = (partial) =>
api("/api/config", {
method: "PUT",
headers: headers(true),
body: JSON.stringify(partial),
});
// Runs
export const listRuns = () => api("/api/runs");
export const currentRun = () => api("/api/runs/current");
export const startRun = (body) =>
api("/api/runs/start", {
method: "POST",
headers: headers(true),
body: JSON.stringify(body),
});
export const stopRun = () =>
api("/api/runs/stop", { method: "POST", headers: headers(true) });
export const runLogs = (tail = 200, which = "auto") =>
api(`/api/runs/current/logs?tail=${tail}&which=${which}`);
// Accounts
export const listAccounts = (qs) => api(`/api/accounts?${qs}`);
export const accountAction = (id, action) =>
api(`/api/accounts/${encodeURIComponent(id)}`, {
method: "POST",
headers: headers(true),
body: JSON.stringify({ action }),
});
// Nodes
export const listClash = () => api("/api/nodes/clash");
export const testClash = (body) =>
api("/api/nodes/clash/test", {
method: "POST",
headers: headers(true),
body: JSON.stringify(body || {}),
});
export const importClashUrl = (body) =>
api("/api/nodes/clash/import-url", {
method: "POST",
headers: headers(true),
body: JSON.stringify(body),
});
export const listCatalog = (qs) => api(`/api/nodes?${qs}`);
export const addCatalogNode = (body) =>
api("/api/nodes", {
method: "POST",
headers: headers(true),
body: JSON.stringify(body),
});
export const testCatalog = (body) =>
api("/api/nodes/test", {
method: "POST",
headers: headers(true),
body: JSON.stringify(body || {}),
});
// Import multipart
export const importNodesFile = (fd) => postMultipart("/api/import/nodes", fd);
export const importMailText = (fd) => postMultipart("/api/import/mail", fd);
export const importAuthsFile = (fd) => postMultipart("/api/import/auths", fd);
export const importPackFile = (fd) => postMultipart("/api/import/pack", fd);
// Ops
export const selfcheck = () =>
api("/api/ops/selfcheck", { method: "POST", headers: headers(true) });
export const cleanupOrphans = () =>
api("/api/ops/cleanup-orphans?dry_run=false", {
method: "POST",
headers: headers(true),
});
```
> If any account/node action signature differs when porting a page, adjust the helper to match the **live** call site in `legacy/assets/app.js` — do not invent new request shapes.
- [ ] **Step 3: Session signal store**
```js
// src/store/session.js
import { signal } from "@preact/signals";
export const session = signal({
authenticated: false,
username: null,
auth_required: true,
password_login_enabled: true,
users_configured: false,
checked: false,
});
```
- [ ] **Step 4: Smoke test client against control_api**
```bash
# terminal A
./scripts/run_control_api.sh
# terminal B
cd apps/web && npm run dev
# browser console or temporary button:
# await fetch('/api/auth/me', {credentials:'same-origin'}).then(r=>r.json())
```
Expected: proxy returns 200 JSON from control_api.
- [ ] **Step 5: Commit**
```bash
git add apps/web/src/api apps/web/src/lib apps/web/src/store
git commit -m "feat(web): api client + format helpers + session signal"
```
---
### Task 3: UI primitives + feedback system + shell layout
**Files:**
- Create: `apps/web/src/ui/Button.jsx`, `Card.jsx`, `Field.jsx`, `Select.jsx`, `Tabs.jsx`, `StatusDot.jsx`, `Chip.jsx`, `Kpi.jsx`, `Bar.jsx`, `ToastHost.jsx`, `Drawer.jsx`, `index.js`
- Create: `apps/web/src/styles/components.css`
- Create: `apps/web/src/store/feedback.js`
- Modify: `App.jsx` — login gate + sidebar shell + hash router stubs
- Modify: `base.css` — shell grid + responsive sidebar
**Interfaces:**
- Produces:
- `