Commit 68df4e3a by liimin

refactor: 拆分项目为 pnpm workspace 三模块并升级前端

- 拆分为 packages/coderio(底层引擎)、apps/server(编排服务)、apps/web(前端工程)
- 后端:REST+SSE、SQLite Job 持久化、并发队列、子进程隔离、密钥服务端化
- 前端:React+Vite+TS+shadcn 工程化,五大页面,企业级深色 UI(翡翠绿主色、立体分层)
- 清理拆分前根目录残留代码;忽略运行时 data/ 目录
1 parent fe950691
Showing 345 changed files with 3904 additions and 154 deletions
# Dependencies
node_modules/
# Build output
/dist/
@dist/
.pnpm/
dist/
.workbuddy/
.trash/
.trash-win/
*.tsbuildinfo
# But keep template dist
!src/tools/report-tool/template/dist/
# IDE
.vscode/launch.json
.idea/
*.swp
*.swo
*~
.claude/
.cursor/
# OS
.DS_Store
Thumbs.db
# Logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Environment
.env
.env.local
.env.*.local
# Temporary files
*.tmp
.cache/
# Test coverage
coverage/
.nyc_output/
# runtime data (sqlite job store + generated outputs)
data/
# Coderio
coderio/
# runtime data (sqlite job store + generated outputs)
data/
# ============================================================
# CodeRio 编排服务配置
# 重要:所有密钥/令牌都由【服务端】持有,前端只传 Figma 链接 + 模式 + 输出偏好,
# 前端代码中绝不出现任何 apiKey / token。
# ============================================================
# —— 模型(OpenAI 兼容接口,例如阿里云 MAAS Qwen)——
CODERIO_PROVIDER=openai
CODERIO_MODEL=qwen3.8-max
CODERIO_BASE_URL=https://llm-xxxxxxxx.cn-beijing.maas.aliyuncs.com/compatible-mode/v1
CODERIO_API_KEY=sk-xxxxxxxx
# —— Figma 访问令牌(用于拉取 Figma 文件/图片)——
CODERIO_FIGMA_TOKEN=figd_xxxxxxxx
# —— 服务本身 ——
CODERIO_SERVER_HOST=0.0.0.0
CODERIO_SERVER_PORT=4173
# 同时运行的生成任务上限(生成吃 LLM 配额,建议 1~2)
CODERIO_MAX_CONCURRENT=1
# 数据目录:Job 持久化 SQLite + 生成产物元数据
CODERIO_SERVER_DATA_DIR=./data
# 生成产物根目录(design2code 会在其下再建 coderio/<figmaName>/<appName>)
# 默认使用 <数据目录>/output
# CODERIO_OUTPUT_DIR=./data/output
# @coderio/server —— CodeRio 编排服务
三层架构中的 **中间层(模块 2)**。它接收前端指令、管理生成任务、持有全部密钥、
调用最底层的 `coderio` 引擎,并托管生成结果的预览。
```
前端工程 (apps/web, Phase 2) ──HTTP/SSE──▶ 本服务 (apps/server) ──▶ coderio 引擎 (packages/coderio)
```
## 职责
- **密钥服务端化**:apiKey / baseUrl / figmaToken 只读环境变量或 `~/.coderio/config.yaml`,
前端永远不接触任何密钥(前端只传 Figma 链接 + 模式 + 输出偏好)。
- **Job 持久化**:使用 Node 内置 `node:sqlite`(不可用时自动回退 JSON 文件),
任务状态(queued/running/done/error)跨重启不丢。
- **并发队列**:`CODERIO_MAX_CONCURRENT` 限制同时运行的生成任务(默认 1,建议 1~2,
因为生成很吃 LLM 配额)。
- **子进程隔离**:每个生成任务在独立 detached 子进程里跑 `design2code`,重任务/崩溃
不会拖垮服务;模型配置通过环境变量 `COD_RUNTIME_CONFIG` 注入子进程(不落 argv、不落文件)。
- **SSE 实时日志**:`/api/stream` 推送 log / jobs / preview 事件。
- **预览托管**:生成完成后可启动一个持久 dev server(`npm run dev`,端口探测)供前端 iframe 嵌入。
(Phase 3 将升级为 `vite build` 静态产物托管。)
## 启动
```bash
# 1) 配置密钥(二选一)
# a) 复制并填写 .env
cp .env.example .env
# b) 或直接写 ~/.coderio/config.yaml(coderio 引擎兼容格式)
# 2) 从仓库根目录启动(保证 coderio 包与产物路径解析正确)
npx tsx apps/server/src/index.ts
# 或
cd apps/server && npm run dev
```
默认监听 `http://localhost:4173`。
## 环境变量
| 变量 | 说明 | 默认 |
|---|---|---|
| `CODERIO_PROVIDER` | 模型 provider(OpenAI 兼容填 `openai`) | `openai` |
| `CODERIO_MODEL` | 模型名,如 `qwen3.8-max` | `qwen3.8-max` |
| `CODERIO_BASE_URL` | OpenAI 兼容端点 | 空 |
| `CODERIO_API_KEY` | 模型 API Key | 空 |
| `CODERIO_FIGMA_TOKEN` | Figma 访问令牌 | 空 |
| `CODERIO_SERVER_HOST` | 监听地址 | `0.0.0.0` |
| `CODERIO_SERVER_PORT` | 监听端口 | `4173` |
| `CODERIO_MAX_CONCURRENT` | 并发生成上限 | `1` |
| `CODERIO_SERVER_DATA_DIR` | Job 持久化目录 | `./data` |
| `CODERIO_OUTPUT_DIR` | 生成产物根目录 | `<data>/output` |
## API
- `GET /api/config` 返回脱敏配置(不含量钥明文)
- `POST /api/generate` 提交任务 `{figmaUrl, mode, outputDir?, appName?}`
- `GET /api/jobs` 任务列表(最新在前)
- `GET /api/job/:id` 单个任务
- `GET /api/stream` SSE 日志/状态流
- `GET /api/preview` 预览状态
- `POST /api/preview` 启动预览(可选 `{appPath}`)
- `POST /api/preview/stop` 停止预览
## 注意
- 本服务依赖 `packages/coderio` 经 workspace 软链解析(`import { design2code } from 'coderio'`)。
在 pnpm 正常的机器上 `pnpm install` 即可;当前受限环境已用 junction 临时解析。
- `coderio` 引擎的 `dist/` 需先构建(`cd packages/coderio && npx tsc`)。
{
"name": "@coderio/server",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "CodeRio 编排服务:接收前端指令、管理生成任务(Job)、持有密钥、调用 Coderio 引擎并托管预览",
"scripts": {
"dev": "tsx watch src/index.ts",
"start": "tsx src/index.ts"
},
"dependencies": {
"coderio": "workspace:*"
},
"devDependencies": {
"@types/node": "^22.0.0",
"tsx": "^4.21.0",
"typescript": "^5.6.0"
}
}
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>CodeRio 编排服务</title>
<style>
:root { --bg:#0f172a; --card:#1e293b; --fg:#e2e8f0; --muted:#94a3b8; --accent:#38bdf8; --ok:#22c55e; --err:#ef4444; }
* { box-sizing: border-box; }
body { margin:0; font-family: system-ui, -apple-system, "Segoe UI", Roboto, "PingFang SC", "Microsoft YaHei", sans-serif; background:var(--bg); color:var(--fg); }
header { padding:16px 24px; border-bottom:1px solid #334155; display:flex; align-items:center; gap:12px; }
header h1 { font-size:18px; margin:0; }
.badge { font-size:12px; padding:2px 8px; border-radius:999px; background:#334155; color:var(--muted); }
main { display:grid; grid-template-columns: 360px 1fr; gap:16px; padding:16px 24px; }
@media (max-width: 900px){ main{ grid-template-columns:1fr; } }
.card { background:var(--card); border:1px solid #334155; border-radius:12px; padding:16px; }
.card h2 { font-size:14px; margin:0 0 12px; color:var(--accent); }
label { display:block; font-size:12px; color:var(--muted); margin:10px 0 4px; }
input, select { width:100%; padding:8px 10px; border-radius:8px; border:1px solid #475569; background:#0f172a; color:var(--fg); font-size:13px; }
button { margin-top:12px; width:100%; padding:10px; border:0; border-radius:8px; background:var(--accent); color:#06283d; font-weight:600; cursor:pointer; }
button.ghost { background:#334155; color:var(--fg); }
button.danger { background:var(--err); color:#fff; }
.row { display:flex; gap:8px; }
.row > * { flex:1; }
#logs { background:#0b1120; border:1px solid #334155; border-radius:8px; height:360px; overflow:auto; padding:10px; font-family: ui-monospace, Menlo, Consolas, monospace; font-size:12px; white-space:pre-wrap; }
.log-line { padding:1px 0; border-bottom:1px solid #1e293b; }
.log-info { color:#7dd3fc; } .log-error { color:#fca5a5; } .log-success { color:#86efac; } .log-warn { color:#fcd34d; }
.jobs { margin-top:10px; }
.job { border:1px solid #334155; border-radius:8px; padding:8px 10px; margin-bottom:8px; font-size:12px; }
.job .id { color:var(--muted); font-size:11px; }
.status { display:inline-block; padding:1px 8px; border-radius:999px; font-size:11px; }
.status.queued { background:#475569; } .status.running { background:#0ea5e9; } .status.done { background:#16a34a; } .status.error { background:#dc2626; }
#previewFrame { width:100%; height:420px; border:1px solid #334155; border-radius:8px; background:#fff; margin-top:8px; }
.hint { font-size:11px; color:var(--muted); margin-top:6px; }
a { color:var(--accent); }
</style>
</head>
<body>
<header>
<h1>🎨 CodeRio 编排服务</h1>
<span class="badge" id="cfgBadge">loading…</span>
</header>
<main>
<div>
<div class="card">
<h2>新建生成任务</h2>
<label>Figma 链接(需含 ?node-id=)</label>
<input id="figmaUrl" placeholder="https://www.figma.com/design/xxx?node-id=1-2" />
<label>模式</label>
<select id="mode">
<option value="full">完整(生成 + 校验)</option>
<option value="code">仅代码</option>
<option value="with-report">仅报告</option>
</select>
<label>输出目录(可选,默认服务端 data/output)</label>
<input id="outputDir" placeholder="留空使用服务端默认" />
<label>应用名(可选,默认 my-app)</label>
<input id="appName" placeholder="my-app" />
<button id="generateBtn">开始生成</button>
<div class="hint">密钥由服务端统一持有,前端不接触任何 apiKey / token。</div>
</div>
<div class="card" style="margin-top:16px;">
<h2>任务历史</h2>
<div class="jobs" id="jobs"></div>
</div>
<div class="card" style="margin-top:16px;">
<h2>预览</h2>
<div class="row">
<button id="previewBtn">启动预览</button>
<button id="stopPreviewBtn" class="danger">停止预览</button>
</div>
<div class="hint" id="previewHint">生成完成后可启动预览(dev server)</div>
<iframe id="previewFrame" style="display:none;"></iframe>
</div>
</div>
<div class="card">
<h2>实时日志 (SSE)</h2>
<div id="logs"></div>
</div>
</main>
<script>
const $ = (id) => document.getElementById(id);
const logsEl = $('logs');
function addLog(level, msg) {
const line = document.createElement('div');
line.className = 'log-line log-' + (level || 'info');
const t = new Date().toLocaleTimeString();
line.textContent = `[${t}] ${msg}`;
logsEl.appendChild(line);
logsEl.scrollTop = logsEl.scrollHeight;
}
// ---- config ----
fetch('/api/config').then(r => r.json()).then(c => {
$('cfgBadge').textContent = `${c.provider} / ${c.model} · 并发${c.maxConcurrent}`;
$('cfgBadge').title = `baseUrl: ${c.baseUrl}\napiKey: ${c.apiKeySet ? '已配置' : '未配置'}\nfigmaToken: ${c.figmaTokenSet ? '已配置' : '未配置'}`;
}).catch(e => addLog('error', 'config 加载失败: ' + e));
// ---- SSE ----
const es = new EventSource('/api/stream');
es.addEventListener('log', (e) => { try { const d = JSON.parse(e.data); addLog(d.level, d.message); } catch {} });
es.addEventListener('jobs', (e) => { try { renderJobs(JSON.parse(e.data).jobs); } catch {} });
es.addEventListener('preview', (e) => { try { renderPreview(JSON.parse(e.data)); } catch {} });
es.onerror = () => addLog('warn', 'SSE 连接中断,重连中…');
function renderJobs(jobs) {
const el = $('jobs');
el.innerHTML = '';
if (!jobs.length) { el.innerHTML = '<div class="hint">暂无任务</div>'; return; }
for (const j of jobs) {
const d = document.createElement('div');
d.className = 'job';
d.innerHTML = `<div class="id">${j.id}</div>
<span class="status ${j.status}">${j.status}</span>
<span style="margin-left:6px;">${j.mode}</span>
${j.error ? `<div style="color:#fca5a5;margin-top:4px;">${j.error}</div>` : ''}`;
el.appendChild(d);
}
}
function renderPreview(state) {
const hint = $('previewHint');
const frame = $('previewFrame');
if (state.running && state.url) {
hint.textContent = `预览运行中: ${state.url}`;
frame.style.display = 'block';
if (frame.src !== state.url) frame.src = state.url;
} else if (state.error) {
hint.textContent = '预览错误: ' + state.error;
frame.style.display = 'none';
} else {
hint.textContent = '生成完成后可启动预览(dev server)';
frame.style.display = 'none';
}
}
// ---- generate ----
$('generateBtn').onclick = async () => {
const figmaUrl = $('figmaUrl').value.trim();
if (!figmaUrl) { alert('请填写 Figma 链接'); return; }
const body = {
figmaUrl,
mode: $('mode').value,
outputDir: $('outputDir').value.trim() || undefined,
appName: $('appName').value.trim() || undefined,
};
addLog('info', '提交生成任务…');
const r = await fetch('/api/generate', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body) });
const data = await r.json();
addLog(data.error ? 'error' : 'success', data.error || (data.message + ' (job ' + data.jobId + ')'));
};
// ---- preview ----
$('previewBtn').onclick = async () => {
const r = await fetch('/api/preview', { method:'POST', headers:{'Content-Type':'application/json'}, body: '{}' });
const d = await r.json();
if (!d.ok) addLog('error', '预览启动失败: ' + (d.error || ''));
else addLog('success', '预览启动中…');
};
$('stopPreviewBtn').onclick = async () => {
await fetch('/api/preview/stop', { method:'POST' });
addLog('info', '已请求停止预览');
};
</script>
</body>
</html>
import { readFileSync, existsSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { loadConfig, configExists, type ModelConfig, type FigmaConfig } from 'coderio';
import type { ServerConfigView } from './types';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
/**
* Minimal `.env` loader (no external dependency). Reads the first `.env` found
* in CWD or the server package dir, populating `process.env` for keys that are
* not already set. This keeps secrets server-side and out of the frontend.
*/
export function loadDotEnv(): void {
const candidates = [
path.resolve(process.cwd(), '.env'),
path.join(__dirname, '..', '.env'),
];
for (const file of candidates) {
if (existsSync(file)) {
try {
const raw = readFileSync(file, 'utf8');
for (const line of raw.split('\n')) {
const m = line.match(/^\s*([\w.-]+)\s*=\s*(.*)\s*$/);
if (!m) continue;
const key = m[1];
const val = m[2].replace(/^["']|["']$/g, '');
if (process.env[key] === undefined) process.env[key] = val;
}
} catch {
/* ignore malformed .env */
}
return;
}
}
}
/**
* The full credential bundle the server uses to drive the coderio engine.
* Resolution order: environment variables > ~/.coderio/config.yaml > defaults.
*/
export interface ServerModelConfig {
provider: string;
model: string;
baseUrl: string;
apiKey: string;
figmaToken: string;
}
export function loadServerModelConfig(): ServerModelConfig {
const env = process.env;
let fileModel: Partial<ModelConfig> = {};
let fileFigma: Partial<FigmaConfig> = {};
if (configExists()) {
try {
const c = loadConfig();
fileModel = c.model ?? {};
fileFigma = c.figma ?? {};
} catch {
/* ignore unreadable config */
}
}
return {
provider: env.CODERIO_PROVIDER ?? fileModel.provider ?? 'openai',
model: env.CODERIO_MODEL ?? fileModel.model ?? 'qwen3.8-max',
baseUrl: env.CODERIO_BASE_URL ?? fileModel.baseUrl ?? '',
apiKey: env.CODERIO_API_KEY ?? fileModel.apiKey ?? '',
figmaToken: env.CODERIO_FIGMA_TOKEN ?? fileFigma.token ?? '',
};
}
/** Frontend-safe view: never includes the actual secret values. */
export function configView(model: ServerModelConfig, maxConcurrent: number): ServerConfigView {
return {
provider: model.provider,
model: model.model,
baseUrl: model.baseUrl,
apiKeySet: Boolean(model.apiKey),
figmaTokenSet: Boolean(model.figmaToken),
maxConcurrent,
};
}
export function resolveServerOptions() {
const dataDir = path.resolve(process.env.CODERIO_SERVER_DATA_DIR ?? './data');
const outputDir = path.resolve(process.env.CODERIO_OUTPUT_DIR ?? path.join(dataDir, 'output'));
const port = Number(process.env.CODERIO_SERVER_PORT ?? 4173);
const host = process.env.CODERIO_SERVER_HOST ?? '0.0.0.0';
const maxConcurrent = Math.max(1, Number(process.env.CODERIO_MAX_CONCURRENT ?? 1) || 1);
return { dataDir, outputDir, port, host, maxConcurrent };
}
/**
* Child process entry for a single generation job. Runs in a detached process
* so a failing/hanging run cannot crash the server. It receives the server's
* model + figma credentials via `COD_RUNTIME_CONFIG` (never via argv, never
* via the frontend) and injects them into the coderio engine at runtime.
*/
import { design2code, setRuntimeConfig, patchEvoltagentStreamingForceOff, ValidationMode } from 'coderio';
function mapMode(mode: string): ValidationMode {
if (mode === 'code') return ValidationMode.CodeOnly;
if (mode === 'with-report') return ValidationMode.ReportOnly;
return ValidationMode.Full;
}
async function main(): Promise<void> {
const argv = process.argv.slice(2);
const get = (name: string): string | undefined => {
const i = argv.indexOf(`--${name}`);
return i >= 0 ? argv[i + 1] : undefined;
};
const figmaUrl = get('figmaUrl');
const mode = mapMode(get('mode') ?? 'full');
const outputDir = get('outputDir');
const appName = get('appName');
if (!figmaUrl) {
process.stdout.write('__D2C_ERROR__:missing figmaUrl\n');
process.exit(1);
}
const raw = process.env.COD_RUNTIME_CONFIG;
if (raw) {
try {
const cfg = JSON.parse(raw) as {
model?: Record<string, unknown>;
figma?: Record<string, unknown>;
};
setRuntimeConfig({ model: cfg.model, figma: cfg.figma });
} catch (e) {
process.stdout.write(`__D2C_ERROR__:invalid runtime config: ${e instanceof Error ? e.message : String(e)}\n`);
process.exit(1);
}
}
// Force non-streaming agent calls (see patch module) — avoids the hang
// against OpenAI-compatible endpoints that stream reasoning_content.
patchEvoltagentStreamingForceOff();
try {
await design2code(figmaUrl, mode, {
outputDir: outputDir || undefined,
appName: appName || undefined,
resume: false,
});
process.stdout.write('__D2C_DONE__\n');
process.exit(0);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
process.stdout.write(`__D2C_ERROR__:${message}\n`);
process.exit(1);
}
}
void main();
import { design2code } from 'coderio';
// Smoke test: proves the backend (apps/server) can consume the Coderio engine
// (packages/coderio) as a library via `import { design2code } from 'coderio'`.
console.log('[smoke] design2code is', typeof design2code);
if (typeof design2code !== 'function') {
console.error('[smoke] FAIL: design2code not imported');
process.exit(1);
}
console.log('[smoke] OK: backend -> engine wiring works');
import { JobStore } from './jobStore';
import { JobQueue } from './queue';
import { PreviewManager } from './preview';
import { createApp } from './server';
import { loadDotEnv, loadServerModelConfig, resolveServerOptions } from './config';
import { runJob } from './runner';
/**
* CodeRio 编排服务入口。
*
* 依赖方向:前端(Phase 2) → 本服务 → coderio 引擎。本服务持有全部密钥,
* 通过子进程隔离调用 coderio 的 `design2code`,并管理 Job 持久化、并发队列
* 与预览托管。
*/
function main(): void {
loadDotEnv();
const opts = resolveServerOptions();
const model = loadServerModelConfig();
const store = new JobStore(opts.dataDir);
// Shared broadcast bus. preview/queue callbacks push events through `hub`;
// once `createApp` returns its real SSE broadcaster we point `hub` at it.
const hub: { broadcast: (event: string, data: unknown) => void } = {
broadcast: () => {},
};
const preview = new PreviewManager((state) => hub.broadcast('preview', state));
const queue = new JobQueue(
store,
(job, onPid) => runJob(job, model, opts.outputDir, onPid),
opts.maxConcurrent,
(s) => hub.broadcast('jobs', s.list()),
);
const { server, broadcast: realBroadcast } = createApp({ store, queue, preview });
hub.broadcast = realBroadcast;
server.listen(opts.port, opts.host, () => {
const banner = [
'',
' 🎨 CodeRio 编排服务已启动',
` 本地访问: http://localhost:${opts.port}`,
` 数据目录: ${opts.dataDir}`,
` 产物目录: ${opts.outputDir}`,
` 并发上限: ${opts.maxConcurrent}`,
' 按 Ctrl+C 停止',
'',
].join('\n');
// eslint-disable-next-line no-console
console.log(banner);
});
}
main();
import { DatabaseSync } from 'node:sqlite';
import path from 'node:path';
import fs from 'node:fs';
import type { Job } from './types';
/**
* Job persistence. Primary backend is SQLite (Node's built-in `node:sqlite`,
* zero external dependencies). If SQLite is unavailable for any reason we fall
* back to a JSON file so the service still runs. Either way, jobs survive a
* server restart (unlike the old single in-memory `currentJob`).
*/
export class JobStore {
private db: DatabaseSync | null = null;
private jsonFallback: string | null = null;
private jobs = new Map<string, Job>();
constructor(dataDir: string) {
fs.mkdirSync(dataDir, { recursive: true });
const dbPath = path.join(dataDir, 'jobs.db');
try {
this.db = new DatabaseSync(dbPath);
this.db.exec(
'CREATE TABLE IF NOT EXISTS jobs (id TEXT PRIMARY KEY, payload TEXT NOT NULL, updated_at INTEGER NOT NULL)',
);
const rows = this.db.prepare('SELECT payload FROM jobs').all() as Array<{ payload: string }>;
for (const r of rows) {
try {
const j = JSON.parse(r.payload) as Job;
this.jobs.set(j.id, j);
} catch {
/* skip corrupt row */
}
}
} catch (e) {
console.warn(
'[jobStore] SQLite 不可用,回退到 JSON 文件存储:',
e instanceof Error ? e.message : String(e),
);
this.db = null;
this.jsonFallback = path.join(dataDir, 'jobs.json');
if (fs.existsSync(this.jsonFallback)) {
try {
const arr = JSON.parse(fs.readFileSync(this.jsonFallback, 'utf8')) as Job[];
for (const j of arr) this.jobs.set(j.id, j);
} catch {
/* ignore */
}
}
}
}
private persist(jobs: Job[]): void {
if (this.db) {
const stmt = this.db.prepare('INSERT OR REPLACE INTO jobs (id, payload, updated_at) VALUES (?, ?, ?)');
for (const j of jobs) stmt.run(j.id, JSON.stringify(j), Date.now());
} else if (this.jsonFallback) {
fs.writeFileSync(this.jsonFallback, JSON.stringify([...this.jobs.values()], null, 2));
}
}
create(job: Job): void {
this.jobs.set(job.id, job);
this.persist([job]);
}
update(id: string, patch: Partial<Job>): Job | null {
const cur = this.jobs.get(id);
if (!cur) return null;
const next = { ...cur, ...patch };
this.jobs.set(id, next);
this.persist([next]);
return next;
}
get(id: string): Job | undefined {
return this.jobs.get(id);
}
/** Most-recent-first list (for the history view). */
list(limit = 50): Job[] {
return [...this.jobs.values()]
.sort((a, b) => b.createdAt.localeCompare(a.createdAt))
.slice(0, limit);
}
}
// Minimal ambient declaration for Node's experimental built-in `node:sqlite`
// module. @types/node does not yet ship these types, but the module is present
// at runtime in Node 22.x. We only declare what this project uses.
declare module 'node:sqlite' {
export class DatabaseSync {
constructor(path?: string, options?: Record<string, unknown>);
exec(sql: string): void;
prepare(sql: string): {
run(...params: unknown[]): unknown;
all(...params: unknown[]): Array<Record<string, unknown>>;
get(...params: unknown[]): Record<string, unknown> | undefined;
};
}
}
import { spawn, execSync, type ChildProcess } from 'node:child_process';
import net from 'node:net';
import os from 'node:os';
import path from 'node:path';
import { existsSync } from 'node:fs';
import type { PreviewState } from './types';
/**
* Manages a persistent dev server for a generated `my-app` so the user can open
* and inspect the result in the browser. Distinct from the transient dev server
* the VALIDATION node spins up internally for screenshots (torn down after each
* iteration). This is a placeholder for the Phase 3 static-build hosting: for
* now we `npm run dev` the generated app and probe the port.
*/
export class PreviewManager {
private proc: ChildProcess | null = null;
state: PreviewState = {
running: false,
appPath: null,
url: null,
localUrl: null,
port: null,
pid: null,
error: null,
};
constructor(private readonly onChange: (s: PreviewState) => void) {}
private getLanIp(): string {
const nets = os.networkInterfaces();
for (const name of Object.keys(nets)) {
for (const ni of nets[name] ?? []) {
if (ni.family === 'IPv4' && !ni.internal) return ni.address;
}
}
return 'localhost';
}
start(explicitAppPath?: string | null): { ok: boolean; error?: string } {
if (this.proc) return { ok: false, error: '预览服务已在运行,请先停止' };
const appPath =
explicitAppPath && existsSync(explicitAppPath) ? explicitAppPath : null;
if (!appPath) return { ok: false, error: '未找到生成的 my-app,请先完成一次生成' };
this.state = {
running: true,
appPath,
url: null,
localUrl: null,
port: null,
pid: null,
error: null,
};
try {
const child = spawn('npm run dev -- --host --port 5180', {
cwd: appPath,
env: { ...process.env },
windowsHide: true,
detached: true,
shell: true,
});
child.unref();
this.proc = child;
this.state.pid = child.pid ?? null;
child.on('error', (e) => {
this.state = { ...this.state, running: false, error: e.message };
this.proc = null;
this.onChange(this.state);
});
child.on('exit', (code) => {
if (this.proc === child) {
this.state = {
...this.state,
running: false,
error: code ? `预览进程退出 (code ${code})` : null,
};
this.proc = null;
this.onChange(this.state);
}
});
// Reliable URL detection: probe the dev-server port(s) until reachable.
const startPort = 5180;
const endPort = 5195;
const deadline = Date.now() + 90_000;
const probe = setInterval(() => {
if (this.state.url || !this.proc) {
clearInterval(probe);
return;
}
if (Date.now() > deadline) {
clearInterval(probe);
return;
}
for (let p = startPort; p <= endPort; p++) {
const sock = net.createConnection({ port: p, host: '127.0.0.1' });
let connected = false;
sock.once('connect', () => {
connected = true;
sock.destroy();
clearInterval(probe);
const ip = this.getLanIp();
this.state.localUrl = `http://localhost:${p}/`;
this.state.url = `http://${ip}:${p}/`;
this.state.port = p;
this.onChange(this.state);
});
sock.once('error', () => {
if (!connected) sock.destroy();
});
}
}, 1000);
this.onChange(this.state);
return { ok: true };
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
this.state = {
running: false,
appPath: null,
url: null,
localUrl: null,
port: null,
pid: null,
error: message,
};
this.proc = null;
return { ok: false, error: message };
}
}
stop(): void {
if (this.proc?.pid) {
try {
if (os.platform() === 'win32') {
execSync(`taskkill /pid ${this.proc.pid} /f /t`, { stdio: 'ignore' });
} else {
process.kill(-this.proc.pid, 'SIGKILL');
}
} catch {
/* ignore */
}
}
this.proc = null;
this.state = {
running: false,
appPath: null,
url: null,
localUrl: null,
port: null,
pid: null,
error: null,
};
this.onChange(this.state);
}
/** Default app path = latest done job's resultDir/my-app. */
static defaultAppPath(resultDir: string | null): string | null {
if (!resultDir) return null;
const p = path.join(resultDir, 'my-app');
return existsSync(p) ? p : null;
}
}
import type { Job } from './types';
import type { JobStore } from './jobStore';
export interface RunResult {
resultDir: string;
reportPath: string | null;
}
/** A single run: drives the coderio engine for one job and resolves with paths. */
export type Runner = (
job: Job,
onPid: (pid: number) => void,
) => Promise<RunResult>;
/**
* Concurrency-limited job queue. Generation is heavy (LLM quota, Playwright),
* so we cap how many run at once. Jobs submitted beyond the limit are queued
* (FIFO) and picked up as slots free up. `onChange` is invoked after every
* state transition so the server can broadcast fresh state over SSE.
*/
export class JobQueue {
private queue: string[] = [];
private active = new Set<string>();
constructor(
private readonly store: JobStore,
private readonly runner: Runner,
private readonly maxConcurrent: number,
private readonly onChange: (store: JobStore) => void,
) {}
submit(job: Job): void {
this.store.create(job);
this.queue.push(job.id);
void this.pump();
this.onChange(this.store);
}
private async pump(): Promise<void> {
while (this.active.size < this.maxConcurrent && this.queue.length > 0) {
const id = this.queue.shift()!;
const job = this.store.get(id);
if (!job) continue;
this.active.add(id);
this.store.update(id, { status: 'running', startedAt: new Date().toISOString() });
this.onChange(this.store);
void this.runOne(job);
}
}
private async runOne(job: Job): Promise<void> {
try {
const result = await this.runner(job, (pid) => {
this.store.update(job.id, { pid });
this.onChange(this.store);
});
this.store.update(job.id, {
status: 'done',
finishedAt: new Date().toISOString(),
resultDir: result.resultDir,
reportPath: result.reportPath,
});
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
this.store.update(job.id, {
status: 'error',
finishedAt: new Date().toISOString(),
error: message,
});
} finally {
this.active.delete(job.id);
void this.pump();
this.onChange(this.store);
}
}
/** 1-based position in the wait queue, or 0 if not queued. */
position(id: string): number {
const i = this.queue.indexOf(id);
return i >= 0 ? i + 1 : 0;
}
pendingCount(): number {
return this.queue.length;
}
activeCount(): number {
return this.active.size;
}
}
import { spawn, type ChildProcess } from 'node:child_process';
import { createRequire } from 'node:module';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { existsSync } from 'node:fs';
import { logger, parseFigmaUrl } from 'coderio';
import type { Job } from './types';
import type { ServerModelConfig } from './config';
import type { RunResult } from './queue';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
/**
* Resolve the tsx CLI entry so we can run the TypeScript child script with the
* same runtime that serves this process (no separate build step needed).
*/
function resolveTsx(): string {
try {
const req = createRequire(import.meta.url);
const loader = req.resolve('tsx');
return path.join(path.dirname(loader), 'cli.mjs');
} catch {
return fileURLToPath(new URL('../../node_modules/tsx/dist/cli.mjs', import.meta.url));
}
}
/**
* Run one generation job in a detached child process so a heavy/failing run
* (Playwright, multi-agent work, OOM) can never take down the server. The
* child calls `design2code` with the server-injected `modelConfig`, so
* credentials never live in the frontend and never hit a global config file
* unless the server chooses to. Logs are streamed back and re-emitted through
* the coderio logger (which the server forwards to SSE clients).
*/
export async function runJob(
job: Job,
model: ServerModelConfig,
outputDir: string,
onPid: (pid: number) => void,
): Promise<RunResult> {
const childScript = fileURLToPath(new URL('./generate-child.ts', import.meta.url));
const tsx = resolveTsx();
const modeArg = job.mode === 'code' ? 'code' : job.mode === 'with-report' ? 'with-report' : 'full';
// Compute the eventual result dir (<outputDir>/coderio/<figmaName>).
let threadId = job.appName || 'my-app';
try {
threadId = parseFigmaUrl(job.figmaUrl).projectName ?? job.appName;
} catch {
/* leave default */
}
const resultDir = path.resolve(outputDir, 'coderio', threadId);
const runtimeConfig = JSON.stringify({
model: {
provider: model.provider,
model: model.model,
baseUrl: model.baseUrl,
apiKey: model.apiKey,
},
figma: { token: model.figmaToken },
});
const args = [
tsx,
childScript,
'--figmaUrl',
job.figmaUrl,
'--mode',
modeArg,
'--outputDir',
outputDir,
'--appName',
job.appName,
];
const child: ChildProcess = spawn(process.execPath, args, {
cwd: process.cwd(),
env: { ...process.env, COD_RUNTIME_CONFIG: runtimeConfig },
windowsHide: true,
detached: true,
});
if (child.pid) onPid(child.pid);
return new Promise<RunResult>((resolve, reject) => {
let settled = false;
let reportPath: string | null = null;
const inferReport = (): string | null => {
const validationReport = path.join(resultDir, 'process', 'validation', 'index.html');
const summaryReport = path.join(resultDir, 'reports.html');
if (existsSync(validationReport)) return validationReport;
if (existsSync(summaryReport)) return summaryReport;
return null;
};
const onData = (buf: Buffer): void => {
const text = buf.toString();
if (text.includes('__D2C_DONE__') && !settled) {
settled = true;
resolve({ resultDir, reportPath: inferReport() });
return;
}
const errMatch = text.match(/__D2C_ERROR__[:\s]*(.*)/);
if (errMatch && !settled) {
settled = true;
reject(new Error((errMatch[1] ?? '生成失败').trim()));
return;
}
for (const line of text.split('\n')) {
const t = line.trim();
if (t) logger.printInfoLog(t);
}
};
child.stdout?.on('data', onData);
child.stderr?.on('data', onData);
child.on('error', (e) => {
if (!settled) {
settled = true;
reject(e);
}
});
child.on('exit', (code) => {
if (settled) return;
settled = true;
if (code === 0) {
resolve({ resultDir, reportPath: inferReport() });
} else {
reject(new Error(`子进程退出码 ${code}`));
}
});
});
}
/**
* Shared types for the CodeRio orchestration backend (apps/server).
* These form the contract between the frontend, this server, and the
* underlying coderio engine — keep them in sync with `apps/web` (Phase 2).
*/
export type JobStatus = 'queued' | 'running' | 'done' | 'error';
export type GenerationMode = 'full' | 'code' | 'with-report';
export interface Job {
id: string;
status: JobStatus;
figmaUrl: string;
mode: GenerationMode;
outputDir: string | null;
appName: string;
/** Absolute path to the generated <outputDir>/coderio/<figmaName> workspace. */
resultDir: string | null;
reportPath: string | null;
error: string | null;
pid: number | null;
createdAt: string;
startedAt: string | null;
finishedAt: string | null;
}
/** Payload accepted by POST /api/generate (sent by the frontend). */
export interface GenerateRequest {
figmaUrl?: string;
mode?: GenerationMode;
/** Optional override; otherwise the server's default output root is used. */
outputDir?: string;
appName?: string;
}
export interface LogEntry {
level: string;
message: string;
timestamp: string;
}
export interface PreviewState {
running: boolean;
appPath: string | null;
url: string | null;
localUrl: string | null;
port: number | null;
pid: number | null;
error: string | null;
}
/** Sanitized configuration view sent to the frontend (no secrets). */
export interface ServerConfigView {
provider: string;
model: string;
baseUrl: string;
apiKeySet: boolean;
figmaTokenSet: boolean;
maxConcurrent: number;
}
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"lib": ["ES2022"],
"types": ["node"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"resolveJsonModule": true,
"noEmit": false,
"outDir": "dist",
"rootDir": "src"
},
"include": ["src"]
}
# CodeRio Web 控制台(前端工程)
Figma → React 生成系统的**前端工程**,对应架构分层中的「模块 1:生成系统前端工程」。
通过 HTTP / SSE 调用后端编排服务(`apps/server`),由后端再调用 `packages/coderio` 引擎。
## 技术栈
- React 18 + Vite 5 + TypeScript
- Tailwind CSS + shadcn 风格基础组件(基于 Radix UI)
- react-router-dom(多页路由)
- sonner(轻量提示)
- 实时日志 / 任务状态 / 预览状态通过 **SSE**(`/api/stream`)订阅
## 页面
| 路由 | 页面 | 说明 |
|---|---|---|
| `/` | 新建生成 | 填写 Figma 链接(需含 `?node-id=`)、选择模式、提交任务 |
| `/logs` | 实时日志 | SSE 实时引擎日志 + 任务队列状态 |
| `/preview` | 预览 | 启动/停止本地预览服务,iframe 嵌入产物 |
| `/history` | 历史 | 持久化任务列表(跨重启不丢) |
| `/settings` | 设置 | 只读展示服务端模型/密钥配置状态 |
## 安全边界
**前端绝不接触任何密钥**。API Key 与 Figma Token 由后端持有(`apps/server` 的环境变量或 `~/.coderio/config.yaml`),`/api/config` 只返回脱敏视图(`apiKeySet` / `figmaTokenSet` 布尔)。
## 开发
```bash
cd apps/web
npm install
npm run dev # http://localhost:5173,自动代理 /api 到后端 :4173
```
## 构建(生产)
```bash
npm run build # 产出 apps/web/dist
```
构建后由后端(`apps/server`)直接托管 `apps/web/dist`:
- 开发时:`apps/server` 托管自带的 `public/index.html` 极简页(兜底)。
- 生产时:优先托管 `apps/web/dist`,并支持 SPA 路由回退(刷新子路由不 404)。
## 与后端约定(类型契约)
见 `src/lib/types.ts`,与 `apps/server/src/types.ts` 保持一致:
- `GET /api/config` → `ServerConfigView`
- `POST /api/generate` → `GenerateResponse`
- `GET /api/jobs` → `{ jobs: Job[] }`
- `GET /api/job/:id` → `Job`
- `GET /api/preview` → `PreviewState`
- `POST /api/preview` / `/api/preview/stop`
- `GET /api/stream` → SSE:`log`(LogEntry) / `jobs`(Job[]) / `preview`(PreviewState)
<!doctype html>
<html lang="zh-CN" class="dark">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CodeRio Studio · 设计转代码指挥中心</title>
<script>
// 防止主题闪烁:在首屏绘制前根据本地存储设定主题
(function () {
try {
var t = localStorage.getItem('coderio-theme');
if (t !== 'light' && t !== 'dark') t = 'dark';
var r = document.documentElement;
r.classList.toggle('dark', t === 'dark');
r.style.colorScheme = t;
} catch (e) {}
})();
</script>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
This diff could not be displayed because it is too large.
{
"name": "@coderio/web",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"preview": "vite preview",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@radix-ui/react-label": "^2.1.1",
"@radix-ui/react-select": "^2.1.4",
"@radix-ui/react-slot": "^1.1.1",
"@radix-ui/react-tabs": "^1.1.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.460.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.28.0",
"sonner": "^1.7.0",
"tailwind-merge": "^2.5.5"
},
"devDependencies": {
"@types/node": "^22.10.0",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.4",
"autoprefixer": "^10.4.20",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.15",
"tailwindcss-animate": "^1.0.7",
"typescript": "^5.6.3",
"vite": "^5.4.11"
}
}
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
import { useState } from 'react';
import { Routes, Route } from 'react-router-dom';
import { Sidebar } from '@/components/layout/Sidebar';
import { Topbar } from '@/components/layout/Topbar';
import NewGeneration from '@/pages/NewGeneration';
import Logs from '@/pages/Logs';
import Preview from '@/pages/Preview';
import History from '@/pages/History';
import Settings from '@/pages/Settings';
export default function App() {
const [collapsed, setCollapsed] = useState(false);
return (
<div className="flex h-screen overflow-hidden">
<Sidebar collapsed={collapsed} onToggle={() => setCollapsed((c) => !c)} />
<div className="flex min-w-0 flex-1 flex-col">
<Topbar
collapsed={collapsed}
onExpand={() => setCollapsed(false)}
/>
<main className="scrollbar-thin flex-1 overflow-auto">
<Routes>
<Route path="/" element={<NewGeneration />} />
<Route path="/logs" element={<Logs />} />
<Route path="/preview" element={<Preview />} />
<Route path="/history" element={<History />} />
<Route path="/settings" element={<Settings />} />
</Routes>
</main>
</div>
</div>
);
}
import type { ReactNode } from 'react';
import type { LucideIcon } from 'lucide-react';
import { cn } from '@/lib/utils';
export function PageHeader({
title,
description,
icon: Icon,
actions,
className,
}: {
title: string;
description?: string;
icon?: LucideIcon;
actions?: ReactNode;
className?: string;
}) {
return (
<div
className={cn(
'flex flex-wrap items-end justify-between gap-4',
className,
)}
>
<div className="flex items-start gap-3">
{Icon && (
<div className="mt-0.5 flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-primary">
<Icon className="h-5 w-5" />
</div>
)}
<div>
<h2 className="text-xl font-semibold tracking-tight">{title}</h2>
{description && (
<p className="mt-1 max-w-2xl text-sm text-muted-foreground">
{description}
</p>
)}
</div>
</div>
{actions && <div className="flex items-center gap-2">{actions}</div>}
</div>
);
}
import { NavLink } from 'react-router-dom';
import {
PanelLeftClose,
PanelLeft,
Zap,
type LucideIcon,
} from 'lucide-react';
import { navItems, brandIcon } from './nav';
import { cn } from '@/lib/utils';
import { useConnection } from '@/lib/connection';
function ConnDot() {
const { connected } = useConnection();
return (
<span className="flex items-center gap-2 text-xs">
<span
className={cn(
'relative inline-flex h-2 w-2 rounded-full',
connected ? 'bg-emerald-500 text-emerald-500' : 'bg-rose-500 text-rose-500',
)}
>
{connected && (
<span className="pulse-ring absolute inset-0 rounded-full" />
)}
</span>
<span className="text-muted-foreground">
{connected ? '服务在线' : '连接断开'}
</span>
</span>
);
}
export function Sidebar({
collapsed,
onToggle,
}: {
collapsed: boolean;
onToggle: () => void;
}) {
return (
<aside
className={cn(
'relative z-20 flex shrink-0 flex-col border-r border-border/70 bg-card/60 glass transition-[width] duration-300 ease-in-out dark:shadow-[1px_0_0_0_rgba(255,255,255,0.05),16px_0_44px_-22px_rgba(0,0,0,0.7)]',
collapsed ? 'w-[76px]' : 'w-64',
)}
>
{/* Brand */}
<div
className={cn(
'flex h-16 items-center gap-3 border-b border-border/70 px-5',
collapsed && 'justify-center px-0',
)}
>
<div className="brand-gradient flex h-9 w-9 shrink-0 items-center justify-center rounded-xl shadow-lg shadow-primary/20">
{(() => {
const Icon: LucideIcon = brandIcon;
return <Icon className="h-5 w-5 text-white" />;
})()}
</div>
{!collapsed && (
<div className="min-w-0 animate-fade-in">
<div className="truncate text-[15px] font-semibold tracking-tight">
CodeRio <span className="text-primary">Studio</span>
</div>
<div className="truncate text-[11px] text-muted-foreground">
设计转代码指挥中心
</div>
</div>
)}
</div>
{/* Nav */}
<nav className="flex-1 space-y-1 p-3">
{navItems.map((item) => (
<NavLink
key={item.to}
to={item.to}
end={item.end}
title={collapsed ? item.label : undefined}
className={({ isActive }) =>
cn(
'group relative flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium transition-all',
collapsed && 'justify-center px-0',
isActive
? 'bg-primary/10 text-foreground'
: 'text-muted-foreground hover:bg-accent hover:text-foreground',
)
}
>
{({ isActive }) => (
<>
{isActive && (
<span className="absolute left-0 top-1/2 h-5 w-1 -translate-y-1/2 rounded-r-full bg-primary" />
)}
<item.icon
className={cn(
'h-[18px] w-[18px] shrink-0 transition-colors',
isActive && 'text-primary',
)}
/>
{!collapsed && <span className="truncate">{item.label}</span>}
</>
)}
</NavLink>
))}
</nav>
{/* Footer */}
<div className="space-y-3 border-t border-border/70 p-3">
{!collapsed && (
<div className="flex items-center justify-between px-2">
<ConnDot />
<span className="flex items-center gap-1 text-[10px] text-muted-foreground">
<Zap className="h-3 w-3 text-primary" /> v0.1
</span>
</div>
)}
{collapsed && (
<div className="flex justify-center">
<ConnDot />
</div>
)}
<button
onClick={onToggle}
className={cn(
'flex w-full items-center gap-2 rounded-lg px-3 py-2 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground',
collapsed && 'justify-center px-0',
)}
>
{collapsed ? (
<PanelLeft className="h-4 w-4" />
) : (
<>
<PanelLeftClose className="h-4 w-4" />
收起侧栏
</>
)}
</button>
</div>
</aside>
);
}
import { useLocation, useNavigate } from 'react-router-dom';
import { Moon, Sun, Plus, ChevronRight, PanelLeft } from 'lucide-react';
import { navItems } from './nav';
import { useTheme } from '@/lib/theme';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
export function Topbar({
onExpand,
collapsed,
}: {
onExpand: () => void;
collapsed: boolean;
}) {
const { pathname } = useLocation();
const navigate = useNavigate();
const { theme, toggle } = useTheme();
const current =
navItems.find((n) => (n.end ? pathname === n.to : pathname.startsWith(n.to))) ??
navItems[0];
return (
<header className="sticky top-0 z-10 flex h-16 items-center justify-between gap-4 border-b border-border/70 bg-background/70 px-6 glass dark:shadow-[0_1px_0_0_rgba(255,255,255,0.05),0_16px_44px_-22px_rgba(0,0,0,0.7)]">
<div className="flex min-w-0 items-center gap-3">
{collapsed && (
<button
onClick={onExpand}
className="flex h-9 w-9 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
title="展开侧栏"
>
<PanelLeft className="h-5 w-5" />
</button>
)}
<div className="min-w-0 animate-fade-in">
<div className="flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
<span>CodeRio Studio</span>
<ChevronRight className="h-3 w-3" />
<span className="text-foreground/70">{current.label}</span>
</div>
<h1 className="truncate text-lg font-semibold leading-tight tracking-tight">
{current.label}
</h1>
</div>
</div>
<div className="flex items-center gap-2">
<button
onClick={toggle}
className="flex h-9 w-9 items-center justify-center rounded-lg border border-border text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
title={theme === 'dark' ? '切换到浅色' : '切换到深色'}
>
{theme === 'dark' ? (
<Sun className="h-[18px] w-[18px]" />
) : (
<Moon className="h-[18px] w-[18px]" />
)}
</button>
<Button
className={cn(
'brand-gradient shadow-lg shadow-primary/25 transition-transform hover:scale-[1.02]',
)}
onClick={() => navigate('/')}
>
<Plus className="h-4 w-4" />
新建生成
</Button>
</div>
</header>
);
}
import {
PlusCircle,
ScrollText,
Eye,
History as HistoryIcon,
Settings as SettingsIcon,
LayoutTemplate,
type LucideIcon,
} from 'lucide-react';
export interface NavItem {
to: string;
label: string;
desc: string;
icon: LucideIcon;
end?: boolean;
}
export const navItems: NavItem[] = [
{
to: '/',
label: '新建生成',
desc: '提交设计稿转换任务',
icon: PlusCircle,
end: true,
},
{
to: '/logs',
label: '实时日志',
desc: '监控引擎输出与任务队列',
icon: ScrollText,
},
{
to: '/preview',
label: '预览',
desc: '在线预览生成产物',
icon: Eye,
},
{
to: '/history',
label: '历史任务',
desc: '全部生成记录与报告',
icon: HistoryIcon,
},
{
to: '/settings',
label: '设置',
desc: '凭据与模型配置',
icon: SettingsIcon,
},
];
export const brandIcon = LayoutTemplate;
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
const badgeVariants = cva(
'inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-xs font-medium transition-colors focus:outline-none whitespace-nowrap',
{
variants: {
variant: {
default: 'border-transparent bg-primary text-primary-foreground shadow-sm',
secondary:
'border-transparent bg-secondary text-secondary-foreground',
outline: 'border-border text-foreground',
brand:
'border-primary/25 bg-primary/12 text-primary',
neutral:
'border-border bg-muted text-muted-foreground',
success:
'border-emerald-500/20 bg-emerald-500/12 text-emerald-600 dark:text-emerald-400',
info: 'border-slate-500/20 bg-slate-500/12 text-slate-600 dark:text-slate-400',
warning:
'border-amber-500/20 bg-amber-500/12 text-amber-600 dark:text-amber-400',
danger:
'border-rose-500/20 bg-rose-500/12 text-rose-600 dark:text-rose-400',
},
},
defaultVariants: { variant: 'default' },
},
);
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
);
}
export { Badge, badgeVariants };
import * as React from 'react';
import { Slot } from '@radix-ui/react-slot';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
const buttonVariants = cva(
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50',
{
variants: {
variant: {
default: 'bg-primary text-primary-foreground hover:bg-primary/90',
destructive:
'bg-destructive text-destructive-foreground hover:bg-destructive/90',
outline:
'border border-input bg-background hover:bg-accent hover:text-accent-foreground',
secondary:
'bg-secondary text-secondary-foreground hover:bg-secondary/80',
ghost: 'hover:bg-accent hover:text-accent-foreground',
link: 'text-primary underline-offset-4 hover:underline',
},
size: {
default: 'h-10 px-4 py-2',
sm: 'h-9 rounded-md px-3',
lg: 'h-11 rounded-md px-8',
icon: 'h-10 w-10',
},
},
defaultVariants: { variant: 'default', size: 'default' },
},
);
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : 'button';
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
);
},
);
Button.displayName = 'Button';
export { Button, buttonVariants };
import * as React from 'react';
import { cn } from '@/lib/utils';
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
'rounded-lg border bg-card text-card-foreground shadow-sm dark:shadow-[0_1px_0_0_rgba(255,255,255,0.05),0_10px_30px_-12px_rgba(0,0,0,0.65)]',
className,
)}
{...props}
/>
));
Card.displayName = 'Card';
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn('flex flex-col space-y-1.5 p-6', className)}
{...props}
/>
));
CardHeader.displayName = 'CardHeader';
const CardTitle = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
'text-xl font-semibold leading-none tracking-tight',
className,
)}
{...props}
/>
));
CardTitle.displayName = 'CardTitle';
const CardDescription = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
));
CardDescription.displayName = 'CardDescription';
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn('p-6 pt-0', className)} {...props} />
));
CardContent.displayName = 'CardContent';
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn('flex items-center p-6 pt-0', className)}
{...props}
/>
));
CardFooter.displayName = 'CardFooter';
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardDescription,
CardContent,
};
import * as React from 'react';
import { cn } from '@/lib/utils';
const Input = React.forwardRef<
HTMLInputElement,
React.InputHTMLAttributes<HTMLInputElement>
>(({ className, type, ...props }, ref) => (
<input
type={type}
className={cn(
'flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
className,
)}
ref={ref}
{...props}
/>
));
Input.displayName = 'Input';
export { Input };
import * as React from 'react';
import * as LabelPrimitive from '@radix-ui/react-label';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
const labelVariants = cva(
'text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70',
);
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
));
Label.displayName = LabelPrimitive.Root.displayName;
export { Label };
import * as React from 'react';
import { cn } from '@/lib/utils';
interface ProgressProps extends React.HTMLAttributes<HTMLDivElement> {
value?: number; // 0-100
indeterminate?: boolean;
tone?: 'brand' | 'success' | 'info' | 'warning' | 'danger';
}
const toneClass: Record<NonNullable<ProgressProps['tone']>, string> = {
brand: 'bg-primary',
success: 'bg-emerald-500',
info: 'bg-slate-500',
warning: 'bg-amber-500',
danger: 'bg-rose-500',
};
function Progress({
value = 0,
indeterminate = false,
tone = 'brand',
className,
...props
}: ProgressProps) {
return (
<div
className={cn(
'h-1.5 w-full overflow-hidden rounded-full bg-muted',
className,
)}
{...props}
>
{indeterminate ? (
<div className={cn('h-full w-1/3 rounded-full', toneClass[tone], 'shimmer')} />
) : (
<div
className={cn(
'h-full rounded-full transition-[width] duration-500 ease-out',
toneClass[tone],
)}
style={{ width: `${Math.min(100, Math.max(0, value))}%` }}
/>
)}
</div>
);
}
export { Progress };
import * as React from 'react';
import * as SelectPrimitive from '@radix-ui/react-select';
import { Check, ChevronDown, ChevronUp } from 'lucide-react';
import { cn } from '@/lib/utils';
const Select = SelectPrimitive.Root;
const SelectGroup = SelectPrimitive.Group;
const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
'flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1',
className,
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
));
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
ref={ref}
className={cn('flex cursor-default items-center justify-center py-1', className)}
{...props}
>
<ChevronUp className="h-4 w-4" />
</SelectPrimitive.ScrollUpButton>
));
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
ref={ref}
className={cn('flex cursor-default items-center justify-center py-1', className)}
{...props}
>
<ChevronDown className="h-4 w-4" />
</SelectPrimitive.ScrollDownButton>
));
SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName;
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = 'popper', ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
'relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
position === 'popper' &&
'data-[side=bottom]:translate-y-1 data-[side=top]:-translate-y-1',
className,
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
'p-1',
position === 'popper' &&
'h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]',
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
));
SelectContent.displayName = SelectPrimitive.Content.displayName;
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
'relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className,
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
));
SelectItem.displayName = SelectPrimitive.Item.displayName;
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectItem,
};
import * as React from 'react';
import { cn } from '@/lib/utils';
function Separator({
className,
orientation = 'horizontal',
...props
}: React.HTMLAttributes<HTMLDivElement> & {
orientation?: 'horizontal' | 'vertical';
}) {
return (
<div
role="separator"
className={cn(
'shrink-0 bg-border',
orientation === 'horizontal' ? 'h-px w-full' : 'h-full w-px',
className,
)}
{...props}
/>
);
}
export { Separator };
import { Toaster as Sonner } from 'sonner';
import { cn } from '@/lib/utils';
type ToasterProps = React.ComponentProps<typeof Sonner>;
export function Toaster(props: ToasterProps) {
return (
<Sonner
className="toaster group"
position="top-center"
toastOptions={{
classNames: {
toast: cn(
'group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg',
),
description: 'group-[.toast]:text-muted-foreground',
actionButton:
'group-[.toast]:bg-primary group-[.toast]:text-primary-foreground',
cancelButton:
'group-[.toast]:bg-muted group-[.toast]:text-muted-foreground',
},
}}
{...props}
/>
);
}
import type { ComponentProps } from 'react';
import { statusMeta, type Tone } from '@/lib/status';
import { Badge } from './badge';
import type { JobStatus } from '@/lib/types';
import { cn } from '@/lib/utils';
const toneToVariant: Record<Tone, NonNullable<ComponentProps<typeof Badge>['variant']>> = {
brand: 'brand',
neutral: 'neutral',
success: 'success',
warning: 'warning',
danger: 'danger',
info: 'info',
};
export function StatusPill({
status,
className,
}: {
status: JobStatus;
className?: string;
}) {
const meta = statusMeta[status];
const Icon = meta.icon;
return (
<Badge variant={toneToVariant[meta.tone]} className={cn('px-2.5 py-1', className)}>
<Icon className={cn('h-3.5 w-3.5', meta.spin && 'animate-spin')} />
{meta.label}
</Badge>
);
}
import * as React from 'react';
import * as TabsPrimitive from '@radix-ui/react-tabs';
import { cn } from '@/lib/utils';
const Tabs = TabsPrimitive.Root;
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
'inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground',
className,
)}
{...props}
/>
));
TabsList.displayName = TabsPrimitive.List.displayName;
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
'inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm',
className,
)}
{...props}
/>
));
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn(
'mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
className,
)}
{...props}
/>
));
TabsContent.displayName = TabsPrimitive.Content.displayName;
export { Tabs, TabsList, TabsTrigger, TabsContent };
import * as React from 'react';
import { cn } from '@/lib/utils';
const Textarea = React.forwardRef<
HTMLTextAreaElement,
React.TextareaHTMLAttributes<HTMLTextAreaElement>
>(({ className, ...props }, ref) => (
<textarea
className={cn(
'flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
className,
)}
ref={ref}
{...props}
/>
));
Textarea.displayName = 'Textarea';
export { Textarea };
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
/* ===== Light theme (clean, enterprise) ===== */
:root {
--background: 215 18% 97%;
--foreground: 222 24% 13%;
--card: 0 0% 100%;
--card-foreground: 222 24% 13%;
--popover: 0 0% 100%;
--popover-foreground: 222 24% 13%;
--primary: 152 48% 38%;
--primary-foreground: 0 0% 100%;
--secondary: 215 16% 95%;
--secondary-foreground: 222 24% 20%;
--muted: 215 14% 94%;
--muted-foreground: 215 12% 44%;
--accent: 215 16% 92%;
--accent-foreground: 222 24% 20%;
--destructive: 0 72% 51%;
--destructive-foreground: 0 0% 100%;
--border: 215 16% 88%;
--input: 215 16% 86%;
--ring: 152 48% 38%;
--radius: 0.85rem;
}
/* ===== Dark theme (premium, neutral graphite) ===== */
.dark {
--background: 220 16% 5%;
--foreground: 215 18% 91%;
--card: 220 13% 12%;
--card-foreground: 215 18% 91%;
--popover: 220 14% 10%;
--popover-foreground: 215 18% 91%;
--primary: 152 45% 48%;
--primary-foreground: 220 24% 8%;
--secondary: 220 11% 17%;
--secondary-foreground: 215 18% 91%;
--muted: 220 9% 15%;
--muted-foreground: 215 12% 64%;
--accent: 220 12% 19%;
--accent-foreground: 215 18% 91%;
--destructive: 0 72% 58%;
--destructive-foreground: 0 0% 100%;
--border: 220 10% 20%;
--input: 220 10% 20%;
--ring: 152 45% 48%;
}
}
@layer base {
* {
@apply border-border;
}
html {
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
}
body {
@apply bg-background text-foreground;
margin: 0;
font-family: 'Inter', ui-sans-serif, system-ui, -apple-system, 'Segoe UI',
Roboto, 'Helvetica Neue', Arial, 'PingFang SC', 'Microsoft YaHei', sans-serif;
font-feature-settings: 'cv02', 'cv03', 'cv04', 'cv11';
}
/* Ambient background: extremely faint neutral haze (no colored glow) */
body::before {
content: '';
position: fixed;
inset: 0;
z-index: -1;
pointer-events: none;
background:
radial-gradient(
900px 500px at 12% -8%,
hsl(215 14% 55% / 0.05),
transparent 60%
),
radial-gradient(
800px 500px at 100% 0%,
hsl(205 12% 50% / 0.04),
transparent 55%
);
}
.dark body::before {
background:
radial-gradient(
900px 520px at 10% -10%,
hsl(215 12% 50% / 0.06),
transparent 60%
),
radial-gradient(
820px 520px at 100% -5%,
hsl(200 10% 45% / 0.05),
transparent 55%
);
}
}
@layer components {
/* Brand surface: single-hue emerald, weighted depth (no rainbow gradient) */
.brand-gradient {
background-image: linear-gradient(
135deg,
hsl(152 44% 34%) 0%,
hsl(152 50% 50%) 100%
);
}
.brand-text {
color: hsl(152 48% 32%);
}
.dark .brand-text {
color: hsl(152 46% 58%);
}
.glass {
@apply backdrop-blur-xl;
}
.glass-dark {
background: hsl(222 14% 9% / 0.7);
}
/* Shimmering skeleton / pulse */
.shimmer {
background: linear-gradient(
90deg,
transparent,
hsl(220 22% 92% / 0.4),
transparent
);
background-size: 200% 100%;
animation: shimmer 1.4s infinite;
}
@keyframes shimmer {
0% {
background-position: -200% 0;
}
100% {
background-position: 200% 0;
}
}
/* Connection pulse ring */
.pulse-ring {
position: relative;
}
.pulse-ring::after {
content: '';
position: absolute;
inset: -3px;
border-radius: 9999px;
border: 2px solid currentColor;
opacity: 0.6;
animation: pulse-ring 1.8s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}
@keyframes pulse-ring {
0% {
transform: scale(0.8);
opacity: 0.7;
}
80%,
100% {
transform: scale(2.1);
opacity: 0;
}
}
.animate-fade-in {
animation: fade-in 0.4s ease both;
}
@keyframes fade-in {
from {
opacity: 0;
transform: translateY(6px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.animate-slide-up {
animation: slide-up 0.45s cubic-bezier(0.22, 1, 0.36, 1) both;
}
@keyframes slide-up {
from {
opacity: 0;
transform: translateY(14px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
}
@layer utilities {
.scrollbar-thin {
scrollbar-width: thin;
scrollbar-color: hsl(var(--border)) transparent;
}
.scrollbar-thin::-webkit-scrollbar {
width: 8px;
height: 8px;
}
.scrollbar-thin::-webkit-scrollbar-thumb {
background: hsl(var(--border));
border-radius: 9999px;
}
.scrollbar-thin::-webkit-scrollbar-thumb:hover {
background: hsl(var(--muted-foreground) / 0.5);
}
.scrollbar-thin::-webkit-scrollbar-track {
background: transparent;
}
}
/* 日志终端 */
.log-terminal {
font-family: ui-monospace, SFMono-Regular, 'JetBrains Mono', Menlo, Consolas,
'Liberation Mono', monospace;
font-size: 12.5px;
line-height: 1.65;
}
import type {
Job,
ServerConfigView,
GenerateRequest,
GenerateResponse,
PreviewState,
LogEntry,
} from './types';
// 同源调用:开发时由 Vite 代理到后端 :4173;生产时后端直接托管本应用。
const BASE = '';
async function http<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(BASE + path, {
...init,
headers: { 'Content-Type': 'application/json', ...(init?.headers ?? {}) },
});
const text = await res.text();
const data = text ? JSON.parse(text) : null;
if (!res.ok) {
throw new Error(data?.error || `请求失败 (${res.status})`);
}
return data as T;
}
export const api = {
getConfig: () => http<ServerConfigView>('/api/config'),
generate: (req: GenerateRequest) =>
http<GenerateResponse>('/api/generate', {
method: 'POST',
body: JSON.stringify(req),
}),
listJobs: () => http<{ jobs: Job[] }>('/api/jobs'),
getJob: (id: string) => http<Job>(`/api/job/${id}`),
getPreview: () => http<PreviewState>('/api/preview'),
startPreview: (appPath?: string) =>
http<{ ok: boolean; error?: string }>('/api/preview', {
method: 'POST',
body: JSON.stringify({ appPath }),
}),
stopPreview: () =>
http<{ ok: boolean }>('/api/preview/stop', { method: 'POST' }),
};
export type SSEEventName = 'log' | 'jobs' | 'preview' | string;
export interface SSEPayload {
event: SSEEventName;
data: unknown;
}
/**
* 订阅后端 SSE 流(/api/stream)。后端会推送三种事件:
* - log: 实时引擎日志 (LogEntry)
* - jobs: 任务列表快照 (Job[]),每次状态变更都会重发
* - preview: 预览服务状态 (PreviewState)
* 返回取消订阅函数。
*/
export function subscribeSSE(
onMessage: (msg: SSEPayload) => void,
onError?: (e: Event) => void,
): () => void {
const es = new EventSource('/api/stream');
const handle = (name: SSEEventName) => (e: MessageEvent) => {
try {
onMessage({ event: name, data: JSON.parse(e.data) });
} catch {
/* ignore malformed */
}
};
es.addEventListener('log', handle('log') as EventListener);
es.addEventListener('jobs', handle('jobs') as EventListener);
es.addEventListener('preview', handle('preview') as EventListener);
es.onerror = (e) => {
onError?.(e);
};
return () => es.close();
}
export type { LogEntry, Job };
import {
createContext,
useContext,
useEffect,
useRef,
useState,
type ReactNode,
} from 'react';
import { subscribeSSE } from './api';
interface ConnectionContextValue {
connected: boolean;
lastEventAt: number | null;
}
const ConnectionContext = createContext<ConnectionContextValue>({
connected: false,
lastEventAt: null,
});
/**
* 全局 SSE 连接监控:订阅一次后端事件流,向整个应用提供「已连接」状态,
* 用于顶栏的实时连接脉冲指示。
*/
export function ConnectionProvider({ children }: { children: ReactNode }) {
const [connected, setConnected] = useState(false);
const [lastEventAt, setLastEventAt] = useState<number | null>(null);
const aliveRef = useRef(true);
useEffect(() => {
aliveRef.current = true;
const unsub = subscribeSSE(
() => {
if (!aliveRef.current) return;
setConnected(true);
setLastEventAt(Date.now());
},
() => {
if (!aliveRef.current) return;
setConnected(false);
},
);
// SSE 打开即视为已连接(即使尚未收到业务事件)
const t = window.setTimeout(() => {
if (aliveRef.current) setConnected(true);
}, 800);
return () => {
aliveRef.current = false;
window.clearTimeout(t);
unsub();
};
}, []);
return (
<ConnectionContext.Provider value={{ connected, lastEventAt }}>
{children}
</ConnectionContext.Provider>
);
}
export function useConnection() {
return useContext(ConnectionContext);
}
import {
CheckCircle2,
Clock,
Loader2,
XCircle,
Code2,
Layers,
FileBarChart2,
type LucideIcon,
} from 'lucide-react';
import type { JobStatus, ValidationMode } from './types';
export type Tone =
| 'brand'
| 'neutral'
| 'success'
| 'warning'
| 'danger'
| 'info';
export const statusMeta: Record<
JobStatus,
{ label: string; tone: Tone; icon: LucideIcon; spin?: boolean }
> = {
queued: { label: '排队中', tone: 'neutral', icon: Clock },
running: { label: '生成中', tone: 'info', icon: Loader2, spin: true },
done: { label: '已完成', tone: 'success', icon: CheckCircle2 },
error: { label: '失败', tone: 'danger', icon: XCircle },
};
export const modeMeta: Record<
ValidationMode,
{ label: string; short: string; desc: string; icon: LucideIcon; tone: Tone }
> = {
code: {
label: '仅代码',
short: 'Code',
desc: 'Figma → React 代码,最快交付',
icon: Code2,
tone: 'brand',
},
full: {
label: '完整流程',
short: 'Full',
desc: '代码 + 自动化校验与自修复',
icon: Layers,
tone: 'info',
},
'with-report': {
label: '带报告',
short: 'Report',
desc: '完整流程并产出可视化报告',
icon: FileBarChart2,
tone: 'warning',
},
};
export const modeLabel: Record<ValidationMode, string> = {
full: '完整流程',
code: '仅代码',
'with-report': '带报告',
};
import {
createContext,
useContext,
useEffect,
useState,
type ReactNode,
} from 'react';
type Theme = 'dark' | 'light';
interface ThemeContextValue {
theme: Theme;
toggle: () => void;
setTheme: (t: Theme) => void;
}
const ThemeContext = createContext<ThemeContextValue | null>(null);
const STORAGE_KEY = 'coderio-theme';
function applyTheme(theme: Theme) {
const root = document.documentElement;
root.classList.toggle('dark', theme === 'dark');
root.style.colorScheme = theme;
}
export function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setThemeState] = useState<Theme>(() => {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored === 'light' || stored === 'dark') return stored;
return 'dark';
});
useEffect(() => {
applyTheme(theme);
localStorage.setItem(STORAGE_KEY, theme);
}, [theme]);
const value: ThemeContextValue = {
theme,
setTheme: setThemeState,
toggle: () => setThemeState((t) => (t === 'dark' ? 'light' : 'dark')),
};
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}
export function useTheme() {
const ctx = useContext(ThemeContext);
if (!ctx) throw new Error('useTheme must be used within ThemeProvider');
return ctx;
}
// 与后端 apps/server/src/types.ts 保持一致的共享契约。
// 前端只依赖这些类型,不接触任何密钥。
export type ValidationMode = 'full' | 'code' | 'with-report';
export type JobStatus = 'queued' | 'running' | 'done' | 'error';
export interface Job {
id: string;
status: JobStatus;
figmaUrl: string;
mode: ValidationMode;
outputDir: string;
appName: string;
resultDir: string | null;
reportPath: string | null;
error: string | null;
pid: number | null;
createdAt: string;
startedAt: string | null;
finishedAt: string | null;
}
export interface ServerConfigView {
provider: string;
model: string;
baseUrl: string;
apiKeySet: boolean;
figmaTokenSet: boolean;
maxConcurrent: number;
}
export interface GenerateRequest {
figmaUrl: string;
mode?: ValidationMode;
outputDir?: string;
appName?: string;
}
export interface GenerateResponse {
jobId: string;
position: number;
message: string;
}
export interface PreviewState {
running: boolean;
appPath: string | null;
url: string | null;
localUrl: string | null;
port: number | null;
pid: number | null;
error: string | null;
}
export type LogLevel = 'log' | 'info' | 'warn' | 'error' | 'success' | 'test';
export interface LogEntry {
level: LogLevel;
message: string;
timestamp: string;
}
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]): string {
return twMerge(clsx(inputs));
}
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import { ThemeProvider } from './lib/theme';
import { ConnectionProvider } from './lib/connection';
import { Toaster } from '@/components/ui/sonner';
import './index.css';
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<ThemeProvider>
<ConnectionProvider>
<BrowserRouter>
<App />
</BrowserRouter>
<Toaster />
</ConnectionProvider>
</ThemeProvider>
</React.StrictMode>,
);
import { useEffect, useMemo, useState } from 'react';
import { toast } from 'sonner';
import {
RefreshCw,
FileText,
Eye,
History as HistoryIcon,
Clock,
CheckCircle2,
XCircle,
ListChecks,
} from 'lucide-react';
import { api, subscribeSSE } from '@/lib/api';
import type { Job } from '@/lib/types';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { StatusPill } from '@/components/ui/status-pill';
import { PageHeader } from '@/components/layout/PageHeader';
import { modeLabel } from '@/lib/status';
import { cn } from '@/lib/utils';
function fmt(ts: string | null) {
if (!ts) return '—';
const d = new Date(ts);
if (Number.isNaN(d.getTime())) return ts.slice(0, 19).replace('T', ' ');
const p = (n: number) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
}
function duration(j: Job) {
if (!j.startedAt || !j.finishedAt) return j.status === 'running' ? '进行中' : '—';
const ms = new Date(j.finishedAt).getTime() - new Date(j.startedAt).getTime();
if (ms < 0) return '—';
const s = Math.round(ms / 1000);
if (s < 60) return `${s}s`;
return `${Math.floor(s / 60)}m${s % 60}s`;
}
export default function History() {
const [jobs, setJobs] = useState<Job[]>([]);
const [loading, setLoading] = useState(true);
const refresh = async () => {
try {
const r = await api.listJobs();
setJobs(r.jobs);
} catch (e) {
toast.error('加载失败', {
description: e instanceof Error ? e.message : String(e),
});
} finally {
setLoading(false);
}
};
useEffect(() => {
refresh();
const unsub = subscribeSSE((msg) => {
if (msg.event === 'jobs') setJobs(msg.data as Job[]);
});
return unsub;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const stats = useMemo(() => {
const total = jobs.length;
const done = jobs.filter((j) => j.status === 'done').length;
const error = jobs.filter((j) => j.status === 'error').length;
const running = jobs.filter((j) => j.status === 'running').length;
const rate = total ? Math.round((done / total) * 100) : 0;
return { total, done, error, running, rate };
}, [jobs]);
return (
<div className="p-6">
<PageHeader
icon={HistoryIcon}
title="历史任务"
description="所有生成任务持久化记录,跨服务重启不丢失。"
actions={
<Button variant="outline" size="sm" onClick={refresh} disabled={loading}>
<RefreshCw className={cn('h-4 w-4', loading && 'animate-spin')} /> 刷新
</Button>
}
/>
{/* Stat cards */}
<div className="mt-5 grid grid-cols-2 gap-3 lg:grid-cols-4">
{[
{ icon: ListChecks, label: '任务总数', value: stats.total, tone: 'text-foreground' },
{ icon: CheckCircle2, label: '成功', value: stats.done, tone: 'text-emerald-500' },
{ icon: XCircle, label: '失败', value: stats.error, tone: 'text-rose-500' },
{ icon: Clock, label: '成功率', value: `${stats.rate}%`, tone: 'text-emerald-500' },
].map((s) => (
<div
key={s.label}
className="flex items-center gap-3 rounded-xl border border-border bg-card p-4"
>
<div className="flex h-10 w-10 items-center justify-center rounded-xl bg-muted">
<s.icon className={cn('h-5 w-5', s.tone)} />
</div>
<div>
<div className="text-xs text-muted-foreground">{s.label}</div>
<div className="text-xl font-semibold tabular-nums">{s.value}</div>
</div>
</div>
))}
</div>
{/* Table */}
<div className="mt-5 overflow-hidden rounded-2xl border border-border bg-card">
{loading ? (
<div className="p-10 text-center text-sm text-muted-foreground">
加载中…
</div>
) : jobs.length === 0 ? (
<div className="flex flex-col items-center gap-3 p-14 text-center">
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-muted text-muted-foreground">
<HistoryIcon className="h-7 w-7" />
</div>
<p className="text-sm text-muted-foreground">暂无任务记录</p>
</div>
) : (
<div className="scrollbar-thin overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border text-left text-xs uppercase tracking-wider text-muted-foreground">
<th className="px-4 py-3 font-medium">状态</th>
<th className="px-4 py-3 font-medium">模式</th>
<th className="px-4 py-3 font-medium">应用</th>
<th className="px-4 py-3 font-medium">Figma 来源</th>
<th className="px-4 py-3 font-medium">创建时间</th>
<th className="px-4 py-3 font-medium">耗时</th>
<th className="px-4 py-3 text-right font-medium">操作</th>
</tr>
</thead>
<tbody>
{jobs.map((j) => (
<tr
key={j.id}
className="group border-b border-border/60 transition-colors last:border-0 hover:bg-accent/40"
>
<td className="px-4 py-3">
<StatusPill status={j.status} />
</td>
<td className="px-4 py-3">
<Badge variant="neutral">{modeLabel[j.mode]}</Badge>
</td>
<td className="px-4 py-3 font-medium">{j.appName || '未命名'}</td>
<td
className="max-w-[240px] truncate px-4 py-3 font-mono text-xs text-muted-foreground"
title={j.figmaUrl}
>
{j.figmaUrl}
</td>
<td className="whitespace-nowrap px-4 py-3 text-muted-foreground">
{fmt(j.createdAt)}
</td>
<td className="whitespace-nowrap px-4 py-3 text-muted-foreground">
{duration(j)}
</td>
<td className="px-4 py-3">
<div className="flex justify-end gap-1.5 opacity-0 transition-opacity group-hover:opacity-100">
{j.reportPath ? (
<a
href={`/api/job/${j.id}`}
className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-background hover:text-foreground"
title="查看报告"
>
<FileText className="h-4 w-4" />
</a>
) : null}
<button
onClick={async () => {
const r = await api.startPreview();
if (r.ok) toast.success('已为该任务产物启动预览');
else toast.error('启动失败', { description: r.error });
}}
className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-background hover:text-foreground"
title="在预览中打开"
>
<Eye className="h-4 w-4" />
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
{/* Failures */}
{jobs.some((j) => j.status === 'error' && j.error) && (
<div className="mt-4 space-y-2">
{jobs
.filter((j) => j.status === 'error' && j.error)
.map((j) => (
<div
key={j.id}
className="flex items-start gap-2 rounded-lg border border-rose-500/25 bg-rose-500/10 p-3 text-xs text-rose-500"
>
<XCircle className="mt-0.5 h-4 w-4 shrink-0" />
<div>
<span className="font-medium">{j.appName}</span>:{j.error}
</div>
</div>
))}
</div>
)}
</div>
);
}
import { useEffect, useMemo, useRef, useState } from 'react';
import { subscribeSSE } from '@/lib/api';
import type { Job, LogEntry, LogLevel } from '@/lib/types';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { StatusPill } from '@/components/ui/status-pill';
import { PageHeader } from '@/components/layout/PageHeader';
import { ScrollText, Trash2, ArrowDownToLine } from 'lucide-react';
import { cn } from '@/lib/utils';
import { modeLabel } from '@/lib/status';
const levelStyle: Record<LogLevel, string> = {
info: 'text-slate-400',
success: 'text-emerald-400',
warn: 'text-amber-400',
error: 'text-rose-400',
test: 'text-zinc-500',
log: 'text-zinc-300',
};
const levelTag: Record<LogLevel, string> = {
info: 'INFO',
success: 'OK',
warn: 'WARN',
error: 'ERR',
test: 'TEST',
log: 'LOG',
};
const filterOptions: { key: LogLevel | 'all'; label: string }[] = [
{ key: 'all', label: '全部' },
{ key: 'info', label: '信息' },
{ key: 'success', label: '成功' },
{ key: 'warn', label: '警告' },
{ key: 'error', label: '错误' },
];
function jobProgress(j: Job): { value: number; indeterminate: boolean; tone: 'info' | 'success' | 'danger' | 'brand' } {
if (j.status === 'done') return { value: 100, indeterminate: false, tone: 'success' };
if (j.status === 'error') return { value: 100, indeterminate: false, tone: 'danger' };
if (j.status === 'running') return { value: 0, indeterminate: true, tone: 'info' };
return { value: 0, indeterminate: false, tone: 'brand' };
}
export default function Logs() {
const [logs, setLogs] = useState<LogEntry[]>([]);
const [jobs, setJobs] = useState<Job[]>([]);
const [filter, setFilter] = useState<LogLevel | 'all'>('all');
const [autoScroll, setAutoScroll] = useState(true);
const scrollRef = useRef<HTMLDivElement>(null);
const autoRef = useRef(autoScroll);
autoRef.current = autoScroll;
useEffect(() => {
const unsub = subscribeSSE((msg) => {
if (msg.event === 'log') {
setLogs((prev) => [...prev, msg.data as LogEntry].slice(-2000));
} else if (msg.event === 'jobs') {
setJobs(msg.data as Job[]);
}
});
return unsub;
}, []);
const visibleLogs = useMemo(
() => (filter === 'all' ? logs : logs.filter((l) => l.level === filter)),
[logs, filter],
);
useEffect(() => {
if (autoScroll && scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
}, [visibleLogs, autoScroll]);
const stats = useMemo(() => {
return {
total: jobs.length,
running: jobs.filter((j) => j.status === 'running').length,
done: jobs.filter((j) => j.status === 'done').length,
error: jobs.filter((j) => j.status === 'error').length,
};
}, [jobs]);
return (
<div className="flex h-full flex-col p-6">
<PageHeader
icon={ScrollText}
title="实时日志"
description="监控底层引擎输出与任务队列,所有事件通过 SSE 实时推送。"
actions={
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={() => setAutoScroll((v) => !v)}
className={cn(autoScroll && 'border-primary/40 text-primary')}
>
<ArrowDownToLine className="h-4 w-4" />
自动滚动{autoScroll ? '开' : '关'}
</Button>
<Button variant="outline" size="sm" onClick={() => setLogs([])}>
<Trash2 className="h-4 w-4" /> 清空
</Button>
</div>
}
/>
{/* Stats strip */}
<div className="mt-5 grid grid-cols-2 gap-3 sm:grid-cols-4">
{[
{ label: '任务总数', value: stats.total, tone: 'text-foreground' },
{ label: '进行中', value: stats.running, tone: 'text-amber-500' },
{ label: '已完成', value: stats.done, tone: 'text-emerald-500' },
{ label: '失败', value: stats.error, tone: 'text-rose-500' },
].map((s) => (
<div key={s.label} className="rounded-xl border border-border bg-card p-3.5">
<div className="text-xs text-muted-foreground">{s.label}</div>
<div className={cn('mt-1 text-2xl font-semibold tabular-nums', s.tone)}>
{s.value}
</div>
</div>
))}
</div>
<div className="mt-5 grid flex-1 grid-cols-1 gap-5 lg:grid-cols-3">
{/* Terminal */}
<div className="flex min-h-0 flex-col lg:col-span-2">
<div className="flex items-center justify-between rounded-t-xl border border-b-0 border-border bg-card px-4 py-2.5">
<div className="flex items-center gap-2">
<span className="flex gap-1.5">
<span className="h-3 w-3 rounded-full bg-rose-500/80" />
<span className="h-3 w-3 rounded-full bg-amber-500/80" />
<span className="h-3 w-3 rounded-full bg-emerald-500/80" />
</span>
<span className="ml-2 text-xs font-medium text-muted-foreground">
Engine Output
</span>
</div>
<div className="flex gap-1.5">
{filterOptions.map((o) => (
<button
key={o.key}
onClick={() => setFilter(o.key)}
className={cn(
'rounded-full px-2.5 py-1 text-xs font-medium transition-colors',
filter === o.key
? 'bg-primary/15 text-primary'
: 'text-muted-foreground hover:bg-accent',
)}
>
{o.label}
</button>
))}
</div>
</div>
<div
ref={scrollRef}
onScroll={(e) => {
const el = e.currentTarget;
autoRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 48;
}}
className="log-terminal scrollbar-thin flex-1 overflow-auto rounded-b-xl border border-border bg-[#0b0e14] p-4 text-zinc-100"
>
{visibleLogs.length === 0 ? (
<div className="text-zinc-500">
暂无日志。提交生成任务后将实时显示引擎输出…
</div>
) : (
visibleLogs.map((l, i) => (
<div key={i} className="flex gap-2 whitespace-pre-wrap break-words py-0.5">
<span className="shrink-0 select-none text-zinc-600">
[{l.timestamp}]
</span>
<span className={cn('shrink-0 font-semibold', levelStyle[l.level])}>
{levelTag[l.level]}
</span>
<span className={levelStyle[l.level]}>{l.message}</span>
</div>
))
)}
</div>
</div>
{/* Job queue */}
<div className="flex min-h-0 flex-col">
<div className="mb-2 flex items-center justify-between">
<h3 className="text-sm font-medium text-muted-foreground">
任务队列
</h3>
<Badge variant="neutral">{jobs.length}</Badge>
</div>
<div className="scrollbar-thin flex-1 space-y-3 overflow-auto pr-1">
{jobs.length === 0 ? (
<div className="rounded-xl border border-dashed border-border p-8 text-center text-sm text-muted-foreground">
暂无任务
</div>
) : (
jobs.map((j) => {
const p = jobProgress(j);
return (
<div
key={j.id}
className="animate-fade-in rounded-xl border border-border bg-card p-3.5"
>
<div className="mb-2 flex items-center justify-between gap-2">
<StatusPill status={j.status} />
<span className="text-xs text-muted-foreground">
{modeLabel[j.mode]}
</span>
</div>
<div className="truncate text-sm font-medium" title={j.appName}>
{j.appName || '未命名应用'}
</div>
<div
className="mt-0.5 truncate text-[11px] text-muted-foreground"
title={j.figmaUrl}
>
{j.figmaUrl}
</div>
<div className="mt-2.5">
<Progress
value={p.value}
indeterminate={p.indeterminate}
tone={p.tone}
/>
</div>
<div className="mt-2 flex items-center justify-between text-[11px] text-zinc-500">
<span>
{j.startedAt ? j.startedAt.slice(11, 19) : '—'}
{j.pid ? ` · pid ${j.pid}` : ''}
</span>
</div>
{j.error && (
<div className="mt-2 break-words rounded-md bg-rose-500/10 px-2 py-1.5 text-[11px] text-rose-400">
{j.error}
</div>
)}
</div>
);
})
)}
</div>
</div>
</div>
</div>
);
}
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import {
Loader2,
Rocket,
Figma,
Hammer,
BrainCircuit,
Code2,
ShieldCheck,
ArrowRight,
Sparkles,
Lock,
} from 'lucide-react';
import { api } from '@/lib/api';
import { modeMeta } from '@/lib/status';
import type { ValidationMode } from '@/lib/types';
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { cn } from '@/lib/utils';
const pipeline = [
{ icon: Hammer, name: 'INITIAL', desc: '脚手架初始化', tone: 'text-slate-400' },
{ icon: BrainCircuit, name: 'PROCESS', desc: '视觉理解设计稿', tone: 'text-slate-400' },
{ icon: Code2, name: 'CODE', desc: '生成 React 组件', tone: 'text-slate-400' },
{ icon: ShieldCheck, name: 'VALIDATION', desc: '自检与自修复', tone: 'text-emerald-400' },
];
export default function NewGeneration() {
const navigate = useNavigate();
const [figmaUrl, setFigmaUrl] = useState('');
const [mode, setMode] = useState<ValidationMode>('code');
const [outputDir, setOutputDir] = useState('');
const [appName, setAppName] = useState('');
const [submitting, setSubmitting] = useState(false);
const handleSubmit = async () => {
if (!figmaUrl.trim()) {
toast.error('请填写 Figma 链接');
return;
}
if (!figmaUrl.includes('node-id=')) {
toast.error('Figma 链接必须包含 ?node-id= 参数');
return;
}
setSubmitting(true);
try {
const res = await api.generate({
figmaUrl: figmaUrl.trim(),
mode,
outputDir: outputDir.trim() || undefined,
appName: appName.trim() || undefined,
});
toast.success('已提交生成任务', { description: res.message });
navigate('/logs');
} catch (e) {
toast.error('提交失败', {
description: e instanceof Error ? e.message : String(e),
});
} finally {
setSubmitting(false);
}
};
return (
<div className="animate-slide-up mx-auto max-w-6xl p-6 lg:p-8">
{/* Hero */}
<div className="mb-8">
<span className="inline-flex items-center gap-1.5 rounded-full border border-primary/25 bg-primary/10 px-3 py-1 text-xs font-medium text-primary">
<Sparkles className="h-3.5 w-3.5" />
Figma → React · 企业级生成流水线
</span>
<h1 className="mt-4 text-3xl font-semibold tracking-tight lg:text-4xl">
将设计稿转化为
<span className="brand-text"> 生产级代码</span>
</h1>
<p className="mt-2 max-w-2xl text-sm text-muted-foreground">
粘贴 Figma 设计稿链接,底层 CodeRio 引擎会经历脚手架、视觉理解、代码生成与自动校验四个阶段,
输出可直接运行的 React 应用。
</p>
</div>
<div className="grid gap-6 lg:grid-cols-5">
{/* Form */}
<Card className="lg:col-span-3">
<CardHeader>
<CardTitle className="text-lg">生成配置</CardTitle>
</CardHeader>
<CardContent className="space-y-6">
<div className="space-y-2">
<Label htmlFor="figmaUrl" className="flex items-center gap-1.5">
<Figma className="h-4 w-4 text-primary" /> Figma 链接
<span className="text-rose-400">*</span>
</Label>
<div className="relative">
<Input
id="figmaUrl"
className="pl-9 font-mono text-[13px]"
placeholder="https://www.figma.com/design/xxx/Name?node-id=1-2"
value={figmaUrl}
onChange={(e) => setFigmaUrl(e.target.value)}
/>
<Figma className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
</div>
<p className="text-xs text-muted-foreground">
链接需包含 <code className="rounded bg-muted px-1">?node-id=</code> 以定位具体画板。
</p>
</div>
<div className="space-y-2.5">
<Label>生成模式</Label>
<div className="grid gap-3 sm:grid-cols-3">
{(Object.keys(modeMeta) as ValidationMode[]).map((key) => {
const m = modeMeta[key];
const Icon = m.icon;
const active = mode === key;
return (
<button
key={key}
type="button"
onClick={() => setMode(key)}
className={cn(
'group relative flex flex-col gap-2 rounded-xl border p-3 text-left transition-all',
active
? 'border-primary bg-primary/5 ring-1 ring-primary/40'
: 'border-border bg-card hover:border-primary/40 hover:bg-accent/50',
)}
>
<div
className={cn(
'flex h-9 w-9 items-center justify-center rounded-lg transition-colors',
active ? 'bg-primary/15 text-primary' : 'bg-muted text-muted-foreground',
)}
>
<Icon className="h-[18px] w-[18px]" />
</div>
<div className="text-sm font-semibold">{m.label}</div>
<div className="text-[11px] leading-relaxed text-muted-foreground">
{m.desc}
</div>
{active && (
<span className="absolute right-3 top-3 h-2 w-2 rounded-full bg-primary shadow-[0_0_8px] shadow-primary" />
)}
</button>
);
})}
</div>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="appName">应用名称</Label>
<Input
id="appName"
placeholder="my-app"
value={appName}
onChange={(e) => setAppName(e.target.value)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="outputDir">输出目录(可选)</Label>
<Input
id="outputDir"
placeholder="默认服务端 data/output"
value={outputDir}
onChange={(e) => setOutputDir(e.target.value)}
/>
</div>
</div>
<Button
className="h-11 w-full brand-gradient shadow-lg shadow-primary/25 transition-transform hover:scale-[1.01]"
onClick={handleSubmit}
disabled={submitting}
>
{submitting ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Rocket className="h-4 w-4" />
)}
{submitting ? '正在提交…' : '开始生成'}
</Button>
<div className="flex items-center justify-center gap-1.5 text-xs text-muted-foreground">
<Lock className="h-3.5 w-3.5" />
密钥与令牌由服务端统一管理,前端不接触任何凭证
</div>
</CardContent>
</Card>
{/* Pipeline */}
<div className="space-y-4 lg:col-span-2">
<Card>
<CardHeader>
<CardTitle className="text-base">生成流水线</CardTitle>
</CardHeader>
<CardContent className="space-y-1">
{pipeline.map((step, i) => {
const Icon = step.icon;
const last = i === pipeline.length - 1;
return (
<div key={step.name} className="relative flex gap-3 pb-4 last:pb-0">
{!last && (
<span className="absolute left-[18px] top-9 h-[calc(100%-12px)] w-px bg-border" />
)}
<div
className={cn(
'relative z-10 flex h-9 w-9 shrink-0 items-center justify-center rounded-xl border border-border bg-card',
step.tone,
)}
>
<Icon className="h-[18px] w-[18px]" />
</div>
<div className="pt-1">
<div className="font-mono text-xs font-semibold tracking-wide">
{step.name}
</div>
<div className="text-xs text-muted-foreground">
{step.desc}
</div>
</div>
</div>
);
})}
<div className="mt-2 flex items-center gap-1.5 rounded-lg bg-muted/60 px-3 py-2 text-xs text-muted-foreground">
<ArrowRight className="h-3.5 w-3.5 text-primary" />
全流程自动化,无需人工介入
</div>
</CardContent>
</Card>
<Card className="overflow-hidden border-primary/15 bg-primary/[0.04]">
<CardContent className="p-5">
<div className="flex items-center gap-2 text-sm font-semibold">
<Sparkles className="h-4 w-4 text-primary" /> 提示
</div>
<p className="mt-2 text-xs leading-relaxed text-muted-foreground">
生成在独立子进程中执行,常驻服务不受影响。提交后可在「实时日志」中观察每个阶段的进度。
</p>
</CardContent>
</Card>
</div>
</div>
</div>
);
}
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import {
Loader2,
Play,
Square,
ExternalLink,
RotateCw,
MonitorSmartphone,
Globe,
} from 'lucide-react';
import { api, subscribeSSE } from '@/lib/api';
import type { PreviewState } from '@/lib/types';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { PageHeader } from '@/components/layout/PageHeader';
import { cn } from '@/lib/utils';
export default function Preview() {
const [state, setState] = useState<PreviewState | null>(null);
const [busy, setBusy] = useState(false);
const [reloadKey, setReloadKey] = useState(0);
useEffect(() => {
const unsub = subscribeSSE((msg) => {
if (msg.event === 'preview') setState(msg.data as PreviewState);
});
api.getPreview().then(setState).catch(() => {});
return unsub;
}, []);
const start = async () => {
setBusy(true);
try {
const r = await api.startPreview();
if (!r.ok) toast.error('启动预览失败', { description: r.error });
else toast.success('预览服务启动中…');
} catch (e) {
toast.error('启动预览失败', {
description: e instanceof Error ? e.message : String(e),
});
} finally {
setBusy(false);
}
};
const stop = async () => {
setBusy(true);
try {
await api.stopPreview();
toast.success('预览已停止');
} finally {
setBusy(false);
}
};
const running = !!state?.running;
const embedUrl = state?.localUrl ?? state?.url ?? null;
const displayUrl = embedUrl ?? '未启动预览服务';
return (
<div className="flex h-full flex-col p-6">
<PageHeader
icon={MonitorSmartphone}
title="预览"
description="为最近一次完成的生成产物托管本地预览服务,实时查看运行效果。"
actions={
<div className="flex items-center gap-2">
{running ? (
<Badge variant="success" className="px-2.5 py-1">
<span className="mr-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500" />
运行中
</Badge>
) : (
<Badge variant="neutral" className="px-2.5 py-1">
已停止
</Badge>
)}
{!running ? (
<Button onClick={start} disabled={busy}>
{busy ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Play className="h-4 w-4" />
)}
启动预览
</Button>
) : (
<Button variant="destructive" onClick={stop} disabled={busy}>
{busy ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Square className="h-4 w-4" />
)}
停止
</Button>
)}
</div>
}
/>
{state?.error && (
<div className="mt-4 rounded-lg border border-rose-500/30 bg-rose-500/10 p-3 text-sm text-rose-500">
{state.error}
</div>
)}
{/* Browser chrome */}
<div className="mt-5 flex min-h-0 flex-1 flex-col overflow-hidden rounded-2xl border border-border bg-card shadow-sm">
<div className="flex items-center gap-3 border-b border-border bg-muted/40 px-4 py-2.5">
<span className="flex gap-1.5">
<span className="h-3 w-3 rounded-full bg-rose-500/80" />
<span className="h-3 w-3 rounded-full bg-amber-500/80" />
<span className="h-3 w-3 rounded-full bg-emerald-500/80" />
</span>
<div className="flex flex-1 items-center gap-2 rounded-lg border border-border bg-background px-3 py-1.5">
<Globe className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<span className="truncate font-mono text-xs text-muted-foreground">
{displayUrl}
</span>
</div>
<button
disabled={!running}
onClick={() => setReloadKey((k) => k + 1)}
className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-40"
title="刷新"
>
<RotateCw className="h-4 w-4" />
</button>
<a
href={embedUrl ?? undefined}
target="_blank"
rel="noreferrer"
className={cn(
'flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-accent hover:text-foreground',
!embedUrl && 'pointer-events-none opacity-40',
)}
title="新窗口打开"
>
<ExternalLink className="h-4 w-4" />
</a>
</div>
<div className="relative min-h-0 flex-1 bg-white">
{embedUrl ? (
<iframe
key={reloadKey}
title="preview"
src={embedUrl}
className="h-full w-full border-0"
/>
) : (
<div className="flex h-full flex-col items-center justify-center gap-4 p-8 text-center">
<div className="brand-gradient flex h-16 w-16 items-center justify-center rounded-2xl shadow-lg shadow-primary/25">
<MonitorSmartphone className="h-8 w-8 text-white" />
</div>
<div>
<p className="text-base font-medium">尚未启动预览</p>
<p className="mt-1 max-w-sm text-sm text-muted-foreground">
请先完成一次生成任务,然后点击右上角「启动预览」,
系统会自动为最新产物托管一个本地服务。
</p>
</div>
{!running && (
<Button onClick={start} disabled={busy} className="brand-gradient">
{busy ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Play className="h-4 w-4" />
)}
启动预览
</Button>
)}
</div>
)}
</div>
</div>
</div>
);
}
import { useEffect, useState } from 'react';
import {
KeyRound,
ShieldCheck,
ShieldAlert,
Cpu,
Server,
Network,
Gauge,
CheckCircle2,
XCircle,
Settings as SettingsIcon,
} from 'lucide-react';
import { api } from '@/lib/api';
import type { ServerConfigView } from '@/lib/types';
import { Badge } from '@/components/ui/badge';
import { PageHeader } from '@/components/layout/PageHeader';
import { useConnection } from '@/lib/connection';
import { cn } from '@/lib/utils';
function SecretTile({
label,
set,
}: {
label: string;
set: boolean;
}) {
return (
<div
className={cn(
'flex items-center gap-3 rounded-xl border p-4 transition-colors',
set
? 'border-emerald-500/25 bg-emerald-500/5'
: 'border-amber-500/25 bg-amber-500/5',
)}
>
<div
className={cn(
'flex h-10 w-10 items-center justify-center rounded-xl',
set
? 'bg-emerald-500/15 text-emerald-500'
: 'bg-amber-500/15 text-amber-500',
)}
>
{set ? (
<ShieldCheck className="h-5 w-5" />
) : (
<ShieldAlert className="h-5 w-5" />
)}
</div>
<div className="min-w-0 flex-1">
<div className="text-sm font-medium">{label}</div>
<div
className={cn(
'text-xs',
set ? 'text-emerald-600 dark:text-emerald-400' : 'text-amber-600 dark:text-amber-400',
)}
>
{set ? '已配置并加密存储' : '尚未配置'}
</div>
</div>
{set ? (
<CheckCircle2 className="h-5 w-5 text-emerald-500" />
) : (
<XCircle className="h-5 w-5 text-amber-500" />
)}
</div>
);
}
export default function Settings() {
const [cfg, setCfg] = useState<ServerConfigView | null>(null);
const [loading, setLoading] = useState(true);
const { connected } = useConnection();
useEffect(() => {
api
.getConfig()
.then(setCfg)
.catch(() => {})
.finally(() => setLoading(false));
}, []);
const configRows = [
{ icon: Cpu, label: 'Provider', value: cfg?.provider ?? '-' },
{ icon: Cpu, label: 'Model', value: cfg?.model ?? '-' },
{ icon: Network, label: 'Base URL', value: cfg?.baseUrl || '(默认)' },
{ icon: Gauge, label: '并发上限', value: String(cfg?.maxConcurrent ?? '-') },
];
return (
<div className="mx-auto max-w-4xl p-6">
<PageHeader
icon={SettingsIcon}
title="设置"
description="密钥由服务端统一管理,前端不接触任何凭证。以下仅展示配置状态。"
/>
<div className="mt-5 space-y-5">
{/* Credentials */}
<section className="rounded-2xl border border-border bg-card p-5">
<div className="mb-4 flex items-center gap-2">
<KeyRound className="h-4 w-4 text-primary" />
<h3 className="text-sm font-semibold">凭据状态</h3>
</div>
{loading || !cfg ? (
<div className="grid gap-3 sm:grid-cols-2">
<div className="h-20 animate-pulse rounded-xl bg-muted/60" />
<div className="h-20 animate-pulse rounded-xl bg-muted/60" />
</div>
) : (
<div className="grid gap-3 sm:grid-cols-2">
<SecretTile label="模型 API Key" set={cfg.apiKeySet} />
<SecretTile label="Figma Token" set={cfg.figmaTokenSet} />
</div>
)}
<p className="mt-3 text-xs text-muted-foreground">
API Key 与 Figma Token 通过服务端环境变量或{' '}
<code className="rounded bg-muted px-1">~/.coderio/config.yaml</code>{' '}
注入,无需在此填写。
</p>
</section>
{/* Model config */}
<section className="rounded-2xl border border-border bg-card p-5">
<div className="mb-4 flex items-center gap-2">
<Cpu className="h-4 w-4 text-primary" />
<h3 className="text-sm font-semibold">模型配置(只读)</h3>
</div>
<div className="grid gap-px overflow-hidden rounded-xl border border-border bg-border sm:grid-cols-2">
{configRows.map((r) => {
const Icon = r.icon;
return (
<div key={r.label} className="flex items-center gap-3 bg-card p-4">
<Icon className="h-4 w-4 shrink-0 text-muted-foreground" />
<div className="min-w-0 flex-1">
<div className="text-xs text-muted-foreground">{r.label}</div>
<div className="truncate break-all text-sm font-medium">
{r.value}
</div>
</div>
</div>
);
})}
</div>
</section>
{/* System status */}
<section className="rounded-2xl border border-border bg-card p-5">
<div className="mb-4 flex items-center gap-2">
<Server className="h-4 w-4 text-primary" />
<h3 className="text-sm font-semibold">系统状态</h3>
</div>
<div className="flex items-center justify-between rounded-xl border border-border bg-muted/40 px-4 py-3">
<div className="flex items-center gap-2 text-sm">
<Network className="h-4 w-4 text-muted-foreground" />
后端连接
</div>
<Badge variant={connected ? 'success' : 'danger'} className="px-2.5 py-1">
{connected ? '已连接' : '断开'}
</Badge>
</div>
</section>
</div>
</div>
);
}
import tailwindcssAnimate from 'tailwindcss-animate';
/** @type {import('tailwindcss').Config} */
export default {
darkMode: ['class'],
content: ['./index.html', './src/**/*.{ts,tsx}'],
theme: {
extend: {
colors: {
border: 'hsl(var(--border))',
input: 'hsl(var(--input))',
ring: 'hsl(var(--ring))',
background: 'hsl(var(--background))',
foreground: 'hsl(var(--foreground))',
primary: {
DEFAULT: 'hsl(var(--primary))',
foreground: 'hsl(var(--primary-foreground))',
},
secondary: {
DEFAULT: 'hsl(var(--secondary))',
foreground: 'hsl(var(--secondary-foreground))',
},
destructive: {
DEFAULT: 'hsl(var(--destructive))',
foreground: 'hsl(var(--destructive-foreground))',
},
muted: {
DEFAULT: 'hsl(var(--muted))',
foreground: 'hsl(var(--muted-foreground))',
},
accent: {
DEFAULT: 'hsl(var(--accent))',
foreground: 'hsl(var(--accent-foreground))',
},
popover: {
DEFAULT: 'hsl(var(--popover))',
foreground: 'hsl(var(--popover-foreground))',
},
card: {
DEFAULT: 'hsl(var(--card))',
foreground: 'hsl(var(--card-foreground))',
},
},
borderRadius: {
lg: 'var(--radius)',
md: 'calc(var(--radius) - 2px)',
sm: 'calc(var(--radius) - 4px)',
},
},
},
plugins: [tailwindcssAnimate],
};
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["src", "vite.config.ts"]
}
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Dev: Vite serves the SPA on :5173 and proxies API/SSE to the CodeRio
// backend on :4173. Prod: the backend serves `dist/` directly (same origin),
// so no proxy is needed.
export default defineConfig({
plugins: [react()],
resolve: {
alias: { '@': path.resolve(__dirname, './src') },
},
server: {
port: 5173,
proxy: {
'/api': {
target: 'http://localhost:4173',
changeOrigin: true,
},
},
},
build: {
outDir: 'dist',
sourcemap: false,
},
});
{
"name": "coderio",
"version": "1.0.3",
"description": "A modern CLI development tool built with TypeScript",
"type": "module",
"bin": {
"coderio": "./dist/cli.js"
},
"main": "./dist/index.js",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"default": "./dist/index.js"
},
"./package.json": "./package.json"
},
"files": [
"dist",
"README.md",
"LICENSE"
],
"name": "coderio-monorepo",
"version": "0.0.0",
"private": true,
"description": "CodeRio monorepo: 前端工程(apps/web) + 后端编排服务(apps/server) + Coderio 生成引擎(packages/coderio)",
"scripts": {
"dev": "tsup --watch",
"build": "pnpm run check && tsup",
"build:report": "cd src/tools/report-tool/template && pnpm install && pnpm build",
"check": "pnpm run typecheck && pnpm run lint && pnpm run format:check",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"format": "prettier --write \"src/**/*.ts\"",
"format:check": "prettier --check \"src/**/*.ts\"",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
"test:coverage:ui": "vitest --ui --coverage",
"prepare": "husky"
},
"keywords": [
"figma",
"design-to-code",
"figma-to-react",
"ai-code-generation",
"visual-validation",
"react",
"typescript",
"tailwindcss",
"multi-agent",
"design-automation",
"frontend-tools",
"ui-restoration",
"design-ops",
"code-generation",
"ai-tool",
"vite",
"cli"
],
"author": "",
"license": "Apache-2.0",
"dependencies": {
"@langchain/core": "^1.1.17",
"@langchain/langgraph": "^1.1.2",
"@langchain/langgraph-checkpoint-sqlite": "^1.0.0",
"@langchain/openai": "^1.2.3",
"@types/pixelmatch": "^5.2.6",
"axios": "^1.13.2",
"better-sqlite3": "^11.10.0",
"chalk": "^5.4.1",
"commander": "^12.1.0",
"evoltagent": "1.1.5",
"js-yaml": "^4.1.1",
"pixelmatch": "^7.1.0",
"prompts": "^2.4.2"
},
"peerDependencies": {
"playwright": "^1.57.0",
"sharp": "^0.34.5"
},
"peerDependenciesMeta": {
"playwright": {
"optional": true
},
"sharp": {
"optional": true
}
},
"devDependencies": {
"@types/js-yaml": "^4.0.9",
"@types/node": "^22.10.2",
"@types/prompts": "^2.4.9",
"@vitest/coverage-v8": "^2.1.9",
"eslint": "^9.17.0",
"husky": "^9.1.7",
"lint-staged": "^16.2.7",
"prettier": "^3.4.2",
"tsup": "^8.3.5",
"tsx": "^4.21.0",
"typescript": "^5.7.2",
"typescript-eslint": "^8.18.1",
"vitest": "^2.1.9"
"coderio:build": "tsc -p packages/coderio/tsconfig.json",
"server": "tsx apps/server/src/index.ts",
"server:dev": "tsx watch apps/server/src/index.ts",
"web": "npm --prefix apps/web run dev",
"web:build": "npm --prefix apps/web run build",
"build:all": "npm run coderio:build && npm run web:build"
},
"engines": {
"node": ">=18.0.0 <25.0.0"
},
"pnpm": {
"onlyBuiltDependencies": [
"better-sqlite3",
"esbuild",
"protobufjs"
]
},
"lint-staged": {
"*.ts": [
"prettier --write",
"eslint --fix"
]
"node": ">=18"
}
}
# Dependencies
node_modules/
# Build output
/dist/
@dist/
*.tsbuildinfo
# But keep template dist
!src/tools/report-tool/template/dist/
# IDE
.vscode/launch.json
.idea/
*.swp
*.swo
*~
.claude/
.cursor/
# OS
.DS_Store
Thumbs.db
# Logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Environment
.env
.env.local
.env.*.local
# Temporary files
*.tmp
.cache/
# Test coverage
coverage/
.nyc_output/
# Coderio
coderio/
......@@ -146,6 +146,7 @@ report path: coderio/<design-name_node-id>/process/validation/index.html
| `protocol2code` | `p2c` | Generate code from existing protocol |
| `validate` | `val` | Run validation on generated code |
| `images` | - | Download and process Figma assets |
| `serve` | `s` | Start the web service UI (form-based workflow) |
### Option 2: Docker
......@@ -254,6 +255,29 @@ Copy `skills\design-to-code` folder to `~\.cursor\skills` (Windows: `%USERPROFIL
1. Start Claude Code.
2. Type: **"Read docs/skills/SKILL.md and perform design conversion: [Your Figma URL]"**
### Option 4: Service Mode (Web UI) 🆕
Best for non-CLI users who want a visual, form-based workflow: configure the AI key / model / Figma token in the browser, paste a Figma link, pick a mode and output directory, then click **生成** and watch progress live.
**Start the server**:
```bash
# From a cloned repo (dev)
pnpm serve:dev
# Or via the installed CLI
coderio serve # default port 4173
coderio serve -p 8080 # custom port
```
Open <http://localhost:4173> in your browser. The UI lets you:
- **Configure** model provider (OpenAI / Anthropic / Google), model name, base URL, API key, and Figma token — saved to `~/.coderio/config.yaml` (shared with the CLI).
- **Generate** by entering a Figma link, choosing a mode (`code` / `with-report` / `full`), and optionally a custom output directory and app name.
- **Watch** a live log stream and, on completion, copy the generated project path and validation report path.
> The web UI is a single self-contained `web/index.html` served by a zero-dependency Node HTTP server bundled into the CLI. No separate frontend build is required.
## 💎 Key Features
### 1. Intelligent Design Protocol Generation
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!