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 6607 additions and 816 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}`));
}
});
});
}
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { readFileSync, existsSync, statSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { subscribeLogs, parseFigmaUrl, type LogEntry } from 'coderio';
import type { JobStore } from './jobStore';
import type { JobQueue } from './queue';
import { PreviewManager } from './preview';
import { configView, loadServerModelConfig, resolveServerOptions } from './config';
import type { GenerateRequest, Job, ServerConfigView } from './types';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PUBLIC_INDEX = path.join(__dirname, '..', 'public', 'index.html');
// Phase 2 前端工程构建产物:apps/web/dist。存在时优先托管它(支持 SPA 路由)。
const WEB_DIST = path.join(__dirname, '..', '..', 'web', 'dist');
const MIME: Record<string, string> = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.ico': 'image/x-icon',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.ttf': 'font/ttf',
'.map': 'application/json',
};
function serveStaticFile(res: ServerResponse, filePath: string): void {
try {
const data = readFileSync(filePath);
const ext = path.extname(filePath).toLowerCase();
res.writeHead(200, {
'Content-Type': MIME[ext] ?? 'application/octet-stream',
'Cache-Control': 'no-cache',
});
res.end(data);
} catch {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Not Found');
}
}
function resolveIndexHtml(): string {
if (WEB_DIST && existsSync(path.join(WEB_DIST, 'index.html'))) {
return path.join(WEB_DIST, 'index.html');
}
return PUBLIC_INDEX;
}
export interface ServerDeps {
store: JobStore;
queue: JobQueue;
preview: PreviewManager;
}
export interface AppHandle {
server: ReturnType<typeof createServer>;
/** Broadcast an SSE event to all connected clients. */
broadcast: (event: string, data: unknown) => void;
}
export function createApp(deps: ServerDeps): AppHandle {
const { store, queue, preview } = deps;
const sseClients = new Set<ServerResponse>();
const opts = resolveServerOptions();
const model = loadServerModelConfig();
const broadcast = (event: string, data: unknown): void => {
const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
for (const res of sseClients) {
try {
res.write(payload);
} catch {
sseClients.delete(res);
}
}
};
// Forward engine logs to every connected SSE client.
subscribeLogs((entry: LogEntry) => broadcast('log', entry));
const sendJson = (res: ServerResponse, code: number, obj: unknown): void => {
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify(obj));
};
const readBody = (req: IncomingMessage): Promise<string> =>
new Promise((resolve, reject) => {
let data = '';
req.on('data', (chunk) => {
data += chunk;
if (data.length > 5 * 1024 * 1024) req.destroy();
});
req.on('end', () => resolve(data));
req.on('error', reject);
});
const server = createServer(async (req, res) => {
try {
const url = new URL(req.url ?? '/', `http://localhost:${opts.port}`);
// ---- Built web static assets (apps/web/dist) ----
if (req.method === 'GET' && WEB_DIST && url.pathname.startsWith('/assets/')) {
const fp = path.join(WEB_DIST, decodeURIComponent(url.pathname));
if (existsSync(fp) && statSync(fp).isFile()) {
serveStaticFile(res, fp);
return;
}
}
// ---- SPA root / index ----
if (req.method === 'GET' && (url.pathname === '/' || url.pathname === '/index.html')) {
const idx = resolveIndexHtml();
if (existsSync(idx)) {
serveStaticFile(res, idx);
} else {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('UI not found.');
}
return;
}
// ---- SPA fallback (client-side routing, non-asset GET) ----
if (
req.method === 'GET' &&
!url.pathname.startsWith('/api') &&
!path.extname(url.pathname)
) {
const idx = resolveIndexHtml();
if (existsSync(idx)) {
serveStaticFile(res, idx);
return;
}
}
// ---- SSE stream ----
if (req.method === 'GET' && url.pathname === '/api/stream') {
res.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
});
res.write('retry: 3000\n\n');
sseClients.add(res);
broadcast('jobs', store.list()); // replay current jobs snapshot
res.write(`event: preview\ndata: ${JSON.stringify(preview.state)}\n\n`);
const ping = setInterval(() => {
try {
res.write(': ping\n\n');
} catch {
/* ignore */
}
}, 15000);
req.on('close', () => {
clearInterval(ping);
sseClients.delete(res);
});
return;
}
// ---- GET /api/config ----
if (req.method === 'GET' && url.pathname === '/api/config') {
const view: ServerConfigView = configView(model, opts.maxConcurrent);
sendJson(res, 200, view);
return;
}
// ---- POST /api/generate ----
if (req.method === 'POST' && url.pathname === '/api/generate') {
const raw = await readBody(req);
let body: GenerateRequest;
try {
body = JSON.parse(raw || '{}');
} catch {
sendJson(res, 400, { error: 'Invalid JSON body' });
return;
}
const figmaUrl = (body.figmaUrl || '').trim();
if (!figmaUrl) {
sendJson(res, 400, { error: 'figmaUrl 为必填项' });
return;
}
try {
parseFigmaUrl(figmaUrl);
} catch {
sendJson(res, 400, {
error: 'Invalid Figma URL(需包含 design/file 链接与 ?node-id=)',
});
return;
}
const mode =
body.mode && ['full', 'code', 'with-report'].includes(body.mode)
? body.mode
: 'full';
const job: Job = {
id: `job-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
status: 'queued',
figmaUrl,
mode,
outputDir: body.outputDir
? path.resolve(body.outputDir)
: opts.outputDir,
appName: body.appName || 'my-app',
resultDir: null,
reportPath: null,
error: null,
pid: null,
createdAt: new Date().toISOString(),
startedAt: null,
finishedAt: null,
};
queue.submit(job);
const position = queue.position(job.id);
sendJson(res, 200, {
jobId: job.id,
position,
message:
position > 0
? `已加入队列,前方还有 ${position} 个任务`
: '开始生成',
});
return;
}
// ---- GET /api/jobs ----
if (req.method === 'GET' && url.pathname === '/api/jobs') {
sendJson(res, 200, { jobs: store.list() });
return;
}
// ---- GET /api/job/:id ----
if (req.method === 'GET' && url.pathname.startsWith('/api/job/')) {
const id = url.pathname.slice('/api/job/'.length);
const job = store.get(id);
sendJson(res, job ? 200 : 404, job ?? { error: 'not found' });
return;
}
// ---- GET /api/preview ----
if (req.method === 'GET' && url.pathname === '/api/preview') {
sendJson(res, 200, preview.state);
return;
}
// ---- POST /api/preview (start) ----
if (req.method === 'POST' && url.pathname === '/api/preview') {
const raw = await readBody(req);
let body: { appPath?: string } = {};
try {
body = JSON.parse(raw || '{}');
} catch {
/* ignore */
}
const latestDone = store
.list()
.find((j) => j.status === 'done' && j.resultDir);
const appPath =
body.appPath ||
PreviewManager.defaultAppPath(latestDone?.resultDir ?? null);
const r = preview.start(appPath);
sendJson(res, r.ok ? 200 : 409, { ok: r.ok, error: r.error });
return;
}
// ---- POST /api/preview/stop ----
if (req.method === 'POST' && url.pathname === '/api/preview/stop') {
preview.stop();
sendJson(res, 200, { ok: true });
return;
}
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Not Found');
} catch (err) {
sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) });
}
});
return { server, broadcast };
}
/**
* 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
......
{
"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"
],
"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"
},
"engines": {
"node": ">=18.0.0 <25.0.0"
},
"pnpm": {
"onlyBuiltDependencies": [
"better-sqlite3",
"esbuild",
"protobufjs"
]
},
"lint-staged": {
"*.ts": [
"prettier --write",
"eslint --fix"
]
}
}
......@@ -2,6 +2,7 @@ import { Command } from 'commander';
import { logger } from '../utils/logger';
import { design2code } from '../graph';
import { ValidationMode } from '../types/graph-types';
import { patchEvoltagentStreamingForceOff } from '../utils/patch-evoltagent';
/**
* Validate and map CLI mode parameter to internal validationMode.
......@@ -43,6 +44,8 @@ export const registerD2CCommand = (program: Command) => {
)
.action(async (opts: { source: string; mode?: string }) => {
try {
// Force evoltagent agents to use non-streaming calls (see patch module).
patchEvoltagentStreamingForceOff();
const { source, mode = 'code' } = opts;
const validationMode = getValidationMode(mode);
......
/**
* Child process entry point for service-mode generation.
*
* Why a separate process: generation (especially VALIDATION's Playwright work
* and the multi-agent INITIAL node) is heavy and can crash the whole event
* loop. By running it in a detached child, the `serve` UI process stays alive
* no matter what happens during a run. Logs are forwarded to the parent by
* simply printing to stdout (the parent captures and re-broadcasts them via
* SSE), and a sentinel line marks completion so the parent can flip job state.
*/
import { design2code } from '../graph';
import { ValidationMode } from '../types/graph-types';
import { patchEvoltagentStreamingForceOff } from '../utils/patch-evoltagent';
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);
}
// Force non-streaming agent calls (see patch module).
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);
}
}
main();
......@@ -16,6 +16,7 @@ import { registerD2CCommand } from './d2c';
import { registerImagesCommand } from './images';
import { registerP2CCommand } from './p2c';
import { registerValidateCommand } from './val';
import { registerServeCommand } from './serve';
async function main(argv: string[]): Promise<void> {
const program = new Command();
......@@ -27,6 +28,7 @@ async function main(argv: string[]): Promise<void> {
registerP2CCommand(program);
registerImagesCommand(program);
registerValidateCommand(program);
registerServeCommand(program);
if (argv.length <= 2) {
program.help({ error: false });
......
import { createServer, IncomingMessage, ServerResponse } from 'node:http';
import { readFileSync, existsSync, readdirSync, statSync } from 'node:fs';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import { spawn, execSync, type ChildProcess } from 'node:child_process';
import net from 'node:net';
import os from 'node:os';
import { Command } from 'commander';
import { ValidationMode } from '../types/graph-types';
import { loadConfig, saveConfig, configExists } from '../utils/config';
import { subscribeLogs, logger, type LogEntry } from '../utils/logger';
import { parseFigmaUrl } from '../utils/url-parser';
/**
* Service mode: a tiny zero-dependency web server that exposes the
* design-to-code pipeline through a browser UI.
*
* - Serves the static UI from `web/index.html`.
* - `GET/POST /api/config` - read & write ~/.coderio/config.yaml.
* - `POST /api/generate` - start a (single, serial) generation job.
* - `GET /api/stream` - Server-Sent Events stream of logs + job status + preview state.
* - `GET /api/job` - current job snapshot.
* - `GET|POST /api/preview` - start/inspect a persistent dev server for the generated app.
* - `POST /api/preview/stop`- stop the preview dev server.
*/
interface JobStatus {
id: string;
status: 'idle' | 'running' | 'done' | 'error';
figmaUrl: string;
outputDir: string | null;
appName: string;
startedAt: string;
finishedAt?: string;
error?: string | null;
resultDir?: string | null;
reportPath?: string | null;
}
const DEFAULT_CONFIG = {
model: { provider: 'openai', model: 'qwen3.8-max', baseUrl: 'https://llm-29tadkloiraxs298.cn-beijing.maas.aliyuncs.com/compatible-mode/v1', apiKey: '' },
figma: { token: '' },
};
let currentJob: JobStatus | null = null;
const sseClients = new Set<ServerResponse>();
function broadcast(event: string, data: unknown): void {
const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
for (const res of sseClients) {
try {
res.write(payload);
} catch {
sseClients.delete(res);
}
}
}
function setJob(patch: Partial<JobStatus>): void {
currentJob = currentJob ? { ...currentJob, ...patch } : (patch as JobStatus);
broadcast('job', currentJob);
}
// ---------------------------------------------------------------------------
// Preview: a persistent dev server for the generated app so the user can
// actually open and inspect the result. This is distinct from the transient
// dev server the VALIDATION node spins up internally for screenshot/pixel
// comparison (which gets torn down after each iteration).
// ---------------------------------------------------------------------------
interface PreviewState {
running: boolean;
appPath: string | null;
url: string | null; // Network URL (reachable from other devices)
localUrl: string | null;
port: number | null;
pid: number | null;
error: string | null;
}
let previewProc: ChildProcess | null = null;
let previewState: PreviewState = {
running: false,
appPath: null,
url: null,
localUrl: null,
port: null,
pid: null,
error: null,
};
function findLatestAppPath(): string | null { if (currentJob?.resultDir) {
const p = path.join(currentJob.resultDir, 'my-app');
if (existsSync(p)) return p;
}
const root = process.env.CODERIO_CLI_USER_CWD ?? process.cwd();
const base = path.join(root, 'coderio');
if (!existsSync(base)) return null;
const candidates = readdirSync(base)
.map((d) => path.join(base, d, 'my-app'))
.filter((p) => existsSync(p));
if (candidates.length === 0) return null;
candidates.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs);
return candidates[0] ?? null;
}
function 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';
}
function startPreview(explicitAppPath?: string): { ok: boolean; error?: string } {
if (previewProc) return { ok: false, error: '预览服务已在运行,请先停止' };
const appPath = explicitAppPath && existsSync(explicitAppPath) ? explicitAppPath : findLatestAppPath();
if (!appPath) return { ok: false, error: '未找到生成的 my-app,请先完成一次生成' };
previewState = { running: true, appPath, url: null, localUrl: null, port: null, pid: null, error: null };
try {
const shellCmd = 'npm run dev -- --host --port 5180';
const child = spawn(shellCmd, {
cwd: appPath,
env: { ...process.env },
windowsHide: true,
detached: true,
shell: true,
});
child.unref();
previewProc = child;
previewState.pid = child.pid ?? null;
child.on('error', (e) => {
previewState = { ...previewState, running: false, error: e.message };
previewProc = null;
broadcast('preview', previewState);
});
child.on('exit', (code) => {
if (previewProc === child) {
previewState = { ...previewState, running: false, error: code ? `预览进程退出 (code ${code})` : null };
previewProc = null;
broadcast('preview', previewState);
}
});
// Reliable URL detection: probe the dev-server port(s) until reachable.
// (stdout parsing is unreliable under detached+shell spawn on Windows.)
const startPort = 5180;
const endPort = 5195;
const deadline = Date.now() + 90_000;
const probe = setInterval(() => {
if (previewState.url || !previewProc) {
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 settled = false;
sock.once('connect', () => {
settled = true;
sock.destroy();
clearInterval(probe);
const ip = getLanIp();
previewState.localUrl = `http://localhost:${p}/`;
previewState.url = `http://${ip}:${p}/`;
previewState.port = p;
broadcast('preview', previewState);
});
sock.once('error', () => {
if (!settled) sock.destroy();
});
}
}, 1000);
broadcast('preview', previewState);
return { ok: true };
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
previewState = { running: false, appPath: null, url: null, localUrl: null, port: null, pid: null, error: message };
previewProc = null;
return { ok: false, error: message };
}
}
function stopPreview(): void {
if (previewProc?.pid) {
try {
if (os.platform() === 'win32') {
execSync(`taskkill /pid ${previewProc.pid} /f /t`, { stdio: 'ignore' });
} else {
process.kill(-previewProc.pid, 'SIGKILL');
}
} catch {
/* ignore */
}
}
previewProc = null;
previewState = { running: false, appPath: null, url: null, localUrl: null, port: null, pid: null, error: null };
broadcast('preview', previewState);
}
function resolveWebIndex(): string {
const here = path.dirname(fileURLToPath(import.meta.url));
const candidates = [
path.join(here, '../../web/index.html'), // published layout (dist/cli -> package/web)
path.join(here, '../web/index.html'), // copied into dist/web
path.join(here, '../../../web/index.html'), // dev layout (src/cli -> project/web)
];
for (const c of candidates) {
if (existsSync(c)) return c;
}
return candidates[0] ?? path.join(here, '../../web/index.html');
}
function readBody(req: IncomingMessage): Promise<string> {
return new Promise((resolve, reject) => {
let data = '';
req.on('data', (chunk) => {
data += chunk;
if (data.length > 5 * 1024 * 1024) req.destroy(); // 5MB guard
});
req.on('end', () => resolve(data));
req.on('error', reject);
});
}
function sendJson(res: ServerResponse, code: number, obj: unknown): void {
const body = JSON.stringify(obj);
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(body);
}
function mapMode(mode?: string): ValidationMode {
if (mode === 'code') return ValidationMode.CodeOnly;
if (mode === 'with-report') return ValidationMode.ReportOnly;
return ValidationMode.Full;
}
function runGeneration(figmaUrl: string, mode: ValidationMode, outputDir?: string, appName?: string): void {
// Run generation in a detached child process so a heavy/failing run
// (Playwright, multi-agent INITIAL, OOM) cannot take down the serve UI.
const root = outputDir || (process.env.CODERIO_CLI_USER_CWD ?? process.cwd());
// Best-effort: derive the result dir from the URL. If the URL can't be
// parsed here (e.g. missing node-id) we fall back and let the child report
// the real directory via its own workspace resolution.
let threadId = 'my-app';
try {
threadId = parseFigmaUrl(figmaUrl).projectName ?? 'my-app';
} catch {
/* leave default */
}
const resultDir = path.resolve(root, 'coderio', threadId);
const scriptPath = fileURLToPath(new URL('./generate-child.ts', import.meta.url));
// The child script is TypeScript; run it through the same tsx runtime that
// serves this process so we don't depend on a separate build step. Resolve
// tsx's cli.mjs at runtime (it lives under .pnpm in a pnpm layout).
let tsxPath: string;
try {
const req = createRequire(import.meta.url);
const loader = req.resolve('tsx');
tsxPath = path.join(path.dirname(loader), 'cli.mjs');
} catch {
tsxPath = fileURLToPath(new URL('../../node_modules/tsx/dist/cli.mjs', import.meta.url));
}
const args = [
scriptPath,
'--figmaUrl', figmaUrl,
'--mode', mode === ValidationMode.CodeOnly ? 'code' : mode === ValidationMode.ReportOnly ? 'with-report' : 'full',
];
if (outputDir) args.push('--outputDir', outputDir);
if (appName) args.push('--appName', appName);
let child: ChildProcess;
try {
child = spawn(process.execPath, [tsxPath, ...args], {
cwd: process.cwd(),
env: { ...process.env },
windowsHide: true,
detached: true,
});
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
setJob({ status: 'error', finishedAt: new Date().toISOString(), error: message });
return;
}
const onData = (buf: Buffer) => {
const text = buf.toString();
// Detect sentinel lines, but still let normal logs pass through.
if (text.includes('__D2C_DONE__')) {
let reportPath: string | null = null;
const validationReport = path.join(resultDir, 'process', 'validation', 'index.html');
const summaryReport = path.join(resultDir, 'reports.html');
if (existsSync(validationReport)) reportPath = validationReport;
else if (existsSync(summaryReport)) reportPath = summaryReport;
setJob({ status: 'done', finishedAt: new Date().toISOString(), resultDir, reportPath });
return;
}
const errMatch = text.match(/__D2C_ERROR__[:\s]*(.*)/);
if (errMatch) {
const msg = errMatch[1] ?? '生成失败';
setJob({ status: 'error', finishedAt: new Date().toISOString(), error: msg.trim() });
return;
}
// Forward the child's stdout/stderr to our logger (which broadcasts via SSE).
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) => {
setJob({ status: 'error', finishedAt: new Date().toISOString(), error: e.message });
});
child.on('exit', (code) => {
// If we never received a sentinel, infer status from exit code.
if (currentJob?.status === 'running') {
if (code === 0) {
setJob({ status: 'done', finishedAt: new Date().toISOString(), resultDir });
} else {
setJob({ status: 'error', finishedAt: new Date().toISOString(), error: `子进程退出码 ${code}` });
}
}
});
}
export async function startServer(port: number): Promise<void> {
const indexPath = resolveWebIndex();
// Forward console logs to all connected SSE clients.
subscribeLogs((entry: LogEntry) => broadcast('log', entry));
const server = createServer(async (req, res) => {
try {
const url = new URL(req.url ?? '/', `http://localhost:${port}`);
// ---- Static UI ----
if (req.method === 'GET' && (url.pathname === '/' || url.pathname === '/index.html')) {
if (existsSync(indexPath)) {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(readFileSync(indexPath));
} else {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('UI not found. Run `pnpm build` to bundle web assets.');
}
return;
}
// ---- SSE stream ----
if (req.method === 'GET' && url.pathname === '/api/stream') {
res.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
});
res.write('retry: 3000\n\n');
sseClients.add(res);
if (currentJob) broadcast('job', currentJob); // replay current snapshot
res.write(`event: preview\ndata: ${JSON.stringify(previewState)}\n\n`); // replay preview snapshot
const ping = setInterval(() => {
try {
res.write(': ping\n\n');
} catch {
/* ignore */
}
}, 15000);
req.on('close', () => {
clearInterval(ping);
sseClients.delete(res);
});
return;
}
// ---- GET /api/config ----
if (req.method === 'GET' && url.pathname === '/api/config') {
if (!configExists()) {
sendJson(res, 200, DEFAULT_CONFIG);
return;
}
try {
sendJson(res, 200, loadConfig());
} catch (err) {
sendJson(res, 200, DEFAULT_CONFIG);
}
return;
}
// ---- POST /api/config ----
if (req.method === 'POST' && url.pathname === '/api/config') {
const raw = await readBody(req);
let body: Record<string, unknown>;
try {
body = JSON.parse(raw || '{}');
} catch {
sendJson(res, 400, { ok: false, error: 'Invalid JSON body' });
return;
}
try {
saveConfig(body);
sendJson(res, 200, { ok: true });
} catch (err) {
sendJson(res, 500, { ok: false, error: err instanceof Error ? err.message : String(err) });
}
return;
}
// ---- POST /api/generate ----
if (req.method === 'POST' && url.pathname === '/api/generate') {
if (currentJob && currentJob.status === 'running') {
sendJson(res, 409, { error: '已有任务在运行,请等待其完成后再试' });
return;
}
const raw = await readBody(req);
let body: { figmaUrl?: string; mode?: string; outputDir?: string; appName?: string };
try {
body = JSON.parse(raw || '{}');
} catch {
sendJson(res, 400, { error: 'Invalid JSON body' });
return;
}
const figmaUrl = (body.figmaUrl || '').trim();
if (!figmaUrl) {
sendJson(res, 400, { error: 'figmaUrl 为必填项' });
return;
}
// Validate the URL format up front so we don't spawn a doomed run.
try {
parseFigmaUrl(figmaUrl);
} catch {
sendJson(res, 400, { error: 'Invalid Figma URL(需包含 design/file 链接与 ?node-id=)' });
return;
}
const jobId = `job-${Date.now()}`;
const mode = mapMode(body.mode);
currentJob = {
id: jobId,
status: 'running',
figmaUrl,
outputDir: body.outputDir || null,
appName: body.appName || 'my-app',
startedAt: new Date().toISOString(),
error: null,
resultDir: null,
reportPath: null,
};
broadcast('job', currentJob);
runGeneration(figmaUrl, mode, body.outputDir, body.appName);
sendJson(res, 200, { jobId });
return;
}
// ---- GET /api/job ----
if (req.method === 'GET' && url.pathname === '/api/job') {
sendJson(res, 200, currentJob || { status: 'idle' });
return;
}
// ---- GET /api/preview ----
if (req.method === 'GET' && url.pathname === '/api/preview') {
sendJson(res, 200, previewState);
return;
}
// ---- POST /api/preview (start a persistent dev server) ----
if (req.method === 'POST' && url.pathname === '/api/preview') {
const raw = await readBody(req);
let body: { appPath?: string } = {};
try {
body = JSON.parse(raw || '{}');
} catch {
/* ignore malformed body */
}
const r = startPreview(body.appPath);
sendJson(res, r.ok ? 200 : 409, { ok: r.ok, error: r.error });
return;
}
// ---- POST /api/preview/stop ----
if (req.method === 'POST' && url.pathname === '/api/preview/stop') {
stopPreview();
sendJson(res, 200, { ok: true });
return;
}
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Not Found');
} catch (err) {
sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) });
}
});
server.listen(port, () => {
const banner = [
'',
' 🎨 CodeRio 服务模式已启动',
` 本地访问: http://localhost:${port}`,
' 按 Ctrl+C 停止',
'',
].join('\n');
// eslint-disable-next-line no-console
console.log(banner);
});
}
export const registerServeCommand = (program: Command) => {
program
.command('serve')
.alias('s')
.description('Start the CodeRio web service (UI mode)')
.option('-p, --port <number>', 'Port to listen on', '4173')
.action(async (opts: { port?: string }) => {
const port = Number(opts.port) || 4173;
await startServer(port);
});
};
......@@ -9,15 +9,75 @@ import { workspaceManager } from './utils/workspace';
import { generateCode } from './nodes/code';
import { initializeSqliteSaver, promptCheckpointChoice, clearThreadCheckpoint } from './utils/checkpoint';
import { logger } from './utils/logger';
import { setRuntimeConfig } from './utils/config';
/**
* Optional parameters for the design-to-code run, used by the service mode
* (`coderio serve`) to drive generation non-interactively.
*/
export interface Design2CodeOptions {
/**
* Custom root directory for the generated project. Maps to the `rootPath`
* argument of `workspaceManager.initWorkspace`. Defaults to the current
* working directory when omitted (CLI behavior).
*/
outputDir?: string;
/**
* Custom generated app folder name (defaults to `my-app`).
*/
appName?: string;
/**
* Explicit resume decision. When provided (true/false) the interactive
* checkpoint prompt is skipped — required for non-interactive service mode.
* When omitted, the CLI falls back to `promptCheckpointChoice`.
*/
resume?: boolean;
/**
* Runtime model + Figma configuration injected by the orchestration backend
* (apps/server). When provided, it overrides `~/.coderio/config.yaml` for
* this run, so the backend owns credentials instead of a global file.
* `figmaToken` maps to the Figma personal access token.
*/
modelConfig?: {
provider?: string;
model?: string;
baseUrl?: string;
apiKey?: string;
figmaToken?: string;
};
}
export async function design2code(url: string, mode?: ValidationMode, options?: Design2CodeOptions): Promise<void> {
const opts = options ?? {};
// Apply backend-injected runtime config (overrides ~/.coderio/config.yaml).
if (opts.modelConfig) {
const mc = opts.modelConfig;
const modelOverride: Record<string, string> = {};
if (mc.provider !== undefined) modelOverride.provider = mc.provider;
if (mc.model !== undefined) modelOverride.model = mc.model;
if (mc.baseUrl !== undefined) modelOverride.baseUrl = mc.baseUrl;
if (mc.apiKey !== undefined) modelOverride.apiKey = mc.apiKey;
setRuntimeConfig({
model: modelOverride,
figma: mc.figmaToken !== undefined ? { token: mc.figmaToken } : undefined,
});
}
// Reset cached workspace so a fresh run (especially in service mode, where
// multiple jobs may run in the same process) does not reuse a stale path.
workspaceManager.reset();
export async function design2code(url: string, mode?: ValidationMode): Promise<void> {
const urlInfo = parseFigmaUrl(url);
const threadId = urlInfo.projectName!;
const workspace = workspaceManager.initWorkspace(threadId);
const workspace = workspaceManager.initWorkspace(threadId, opts.outputDir, opts.appName);
// Initialize SqliteSaver with the database path
const checkpointer = initializeSqliteSaver(workspace.db);
const resume = await promptCheckpointChoice(checkpointer, threadId);
// Resolve resume decision: explicit override (service mode) or interactive prompt (CLI).
const resume: boolean | undefined =
typeof opts.resume === 'boolean' ? opts.resume : await promptCheckpointChoice(checkpointer, threadId);
logger.printInfoLog(`Starting design-to-code process for: ${urlInfo.projectName}`);
......
......@@ -14,3 +14,27 @@ export * from './types/index';
// - JSON parser: extractJSON
// - Naming utilities: toKebabCase
export * from './skill-api';
// ============= Engine API Exports =============
// The primary entry point used by the orchestration backend (apps/server) to
// generate a React project from a Figma URL. `Design2CodeOptions` accepts an
// optional `modelConfig` so the backend can inject credentials at runtime.
export { design2code } from './graph';
export type { Design2CodeOptions } from './graph';
// ============= Orchestration Backend Support =============
// Helpers the apps/server backend needs so it can own credentials, stream logs,
// and drive generation without reaching into internal modules.
export { subscribeLogs, logger } from './utils/logger';
export type { LogEntry, LogLevel } from './utils/logger';
export {
loadConfig,
configExists,
getConfigPath,
saveConfig,
setRuntimeConfig,
clearRuntimeConfig,
} from './utils/config';
export type { ModelConfig, FigmaConfig } from './utils/config';
export { patchEvoltagentStreamingForceOff } from './utils/patch-evoltagent';
export { parseFigmaUrl } from './utils/url-parser';
import { createInitialAgent } from '../../agents/initial-agent';
import fs from 'node:fs';
import path from 'node:path';
import { logger } from '../../utils/logger';
import { getModelConfig } from '../../utils/config';
import { GraphState } from '../../state';
import { MAX_OUTPUT_TOKENS, AGENT_CONTEXT_WINDOW_TOKENS } from '../../constants';
import { initialAgentInstruction } from '../../agents/initial-agent/instruction';
import { writeScaffold } from './scaffold';
/**
* 'initial' node, responsible for initializing the empty project scaffold.
* It uses an LLM-based agent to create the basic project structure and files.
* 'initial' node: initialize the empty project scaffold.
*
* The scaffold is deterministic (React V18 + TS + Vite + TailwindCSS V4 + Less),
* so we generate it directly instead of driving an LLM agent. This is instant,
* reproducible, and keeps the model out of the critical path — the previous
* agent-based approach could hang indefinitely against some OpenAI-compatible
* endpoints (e.g. Aliyun MAAS Qwen) due to an unbounded agent loop.
*/
export const initialProject = async (state: GraphState) => {
logger.printInfoLog('Initializing project...');
const envConfig = getModelConfig();
const modelConfig = {
...envConfig,
contextWindowTokens: AGENT_CONTEXT_WINDOW_TOKENS,
maxOutputTokens: MAX_OUTPUT_TOKENS,
};
const appPath = state.workspace.app;
const appName = state.urlInfo.name || '';
const appName = state.urlInfo.name || 'my-app';
if (!appPath) {
throw new Error('Workspace application path is not defined.');
}
const initialAgent = createInitialAgent(modelConfig);
const result: unknown = await initialAgent.run(initialAgentInstruction({ appPath, appName }));
fs.mkdirSync(appPath, { recursive: true });
writeScaffold(appPath, appName);
// Validate if essential files were created
// Validate that essential files/directories were created.
const essentialFiles = ['package.json', 'src', 'vite.config.ts', 'tsconfig.json', 'index.html', 'src/main.tsx', 'src/App.tsx'];
for (const file of essentialFiles) {
const fullPath = path.join(appPath, file);
......@@ -39,7 +34,7 @@ export const initialProject = async (state: GraphState) => {
}
}
logger.printSuccessLog(result as string);
logger.printSuccessLog(`Scaffold created at ${appPath}`);
return {};
};
import fs from 'node:fs';
import path from 'node:path';
/**
* Deterministic React + Vite + TS + TailwindCSS V4 + Less scaffold.
*
* Why this exists: the original INITIAL node drove an LLM agent (evoltagent) to
* generate these files. That agent has an unbounded `while(true)` loop and is
* fragile against some OpenAI-compatible endpoints (e.g. Aliyun MAAS Qwen),
* which caused runs to hang indefinitely at "Initializing project...".
*
* The scaffold is identical on every run (the only variable is the app name /
* page title), so generating it directly is faster, deterministic, and removes
* the model from the critical path. The generated structure matches exactly
* what the downstream CODE node expects (src/components, src/App.tsx, etc.).
*/
function renderPackageJson(appName: string): string {
return JSON.stringify(
{
name: appName || 'my-app',
private: true,
version: '0.0.0',
type: 'module',
scripts: {
dev: 'pnpm exec vite',
build: 'pnpm exec tsc && pnpm exec vite build',
preview: 'pnpm exec vite preview',
},
dependencies: {
react: '^18.3.1',
'react-dom': '^18.3.1',
},
devDependencies: {
'@tailwindcss/vite': '^4.1.4',
'@types/node': '^20.17.30',
'@types/react': '^18.3.20',
'@types/react-dom': '^18.3.6',
'@vitejs/plugin-react': '^4.4.1',
less: '^4.3.0',
tailwindcss: '^4.1.4',
typescript: '~5.8.3',
vite: '^6.3.5',
},
},
null,
2
);
}
function renderViteConfig(): string {
return `import path from "node:path";
import { fileURLToPath } from "node:url";
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export default defineConfig({
plugins: [react(), tailwindcss()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
});
`;
}
function renderTsConfig(): string {
return `{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"skipLibCheck": true,
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src"]
}
`;
}
function renderIndexHtml(title: string): string {
return `<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>${title}</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
`;
}
function renderMainTsx(): string {
return `import React from "react";
import ReactDOM from "react-dom/client";
import App from "@/App";
import "@/globals.css";
import "@/App.less";
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
`;
}
function renderAppTsx(): string {
return `import ReviewDetailPage from '@/components';
export default function App() {
return <div><ReviewDetailPage /></div>;
}
`;
}
function renderGlobalsCss(): string {
return `@import "tailwindcss";
`;
}
function renderAppLess(): string {
return ``;
}
function renderViteEnvDts(): string {
return `/// <reference types="vite/client" />
`;
}
function renderGitignore(): string {
return `# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
# Dependencies
node_modules/
# Build output
dist/
build/
dist-ssr/
*.local
# Environment files
.env
.env.*
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea/
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# Cache
.cache/
.eslintcache
.stylelintcache
*.tsbuildinfo
# Lock files
package-lock.json
yarn.lock
pnpm-lock.yaml
`;
}
/**
* Write the full scaffold into `appPath`.
* @param appPath absolute path to the generated app folder
* @param appName project name (used in package.json and page title)
*/
export function writeScaffold(appPath: string, appName: string): void {
const files: Record<string, string> = {
'package.json': renderPackageJson(appName),
'vite.config.ts': renderViteConfig(),
'tsconfig.json': renderTsConfig(),
'index.html': renderIndexHtml(appName || 'my-app'),
'src/main.tsx': renderMainTsx(),
'src/App.tsx': renderAppTsx(),
'src/globals.css': renderGlobalsCss(),
'src/App.less': renderAppLess(),
'src/vite-env.d.ts': renderViteEnvDts(),
'.gitignore': renderGitignore(),
};
for (const [rel, content] of Object.entries(files)) {
const full = path.join(appPath, rel);
fs.mkdirSync(path.dirname(full), { recursive: true });
fs.writeFileSync(full, content, 'utf8');
}
// Ensure the components directory exists (App.tsx imports from '@/components').
fs.mkdirSync(path.join(appPath, 'src', 'components'), { recursive: true });
}
/**
* File information for batch creation
*/
export interface FileInfo {
filename: string;
content: string;
}
import { readFileSync, existsSync } from 'fs';
import { readFileSync, existsSync, writeFileSync, mkdirSync } from 'fs';
import { resolve } from 'path';
import { homedir } from 'os';
import yaml from 'js-yaml';
......@@ -15,6 +15,10 @@ export interface ModelConfig {
model: string;
baseUrl: string;
apiKey: string;
/** Force non-streaming mode. evoltagent's default streaming hangs against
* some OpenAI-compatible endpoints (e.g. Aliyun MAAS Qwen) that stream
* `reasoning_content`, so we disable it globally here. */
stream?: boolean;
}
/**
......@@ -82,11 +86,17 @@ export function loadConfig(): Config {
* @throws Error if configuration is invalid
*/
export function getModelConfig(): ModelConfig {
if (runtimeModel) {
return { ...runtimeModel, stream: false };
}
const config = loadConfig();
if (!config.model) {
throw new Error('Model configuration not found in config.yaml');
}
return config.model;
// Disable streaming globally: evoltagent defaults to streaming, which hangs
// against OpenAI-compatible endpoints that emit `reasoning_content` chunks
// (e.g. Aliyun MAAS Qwen). Non-streaming is verified working for those.
return { ...config.model, stream: false };
}
/**
......@@ -95,6 +105,9 @@ export function getModelConfig(): ModelConfig {
* @throws Error if configuration is invalid
*/
export function getFigmaConfig(): FigmaConfig {
if (runtimeFigma) {
return runtimeFigma;
}
const config = loadConfig();
if (!config.figma) {
throw new Error('Figma configuration not found in config.yaml');
......@@ -131,3 +144,73 @@ export function configExists(): boolean {
export function clearConfigCache(): void {
cachedConfig = null;
}
/**
* Runtime configuration override injected by the orchestration backend
* (apps/server). When set, `getModelConfig()` / `getFigmaConfig()` return it
* instead of the file-based config, so the backend can own credentials per
* request without relying on a global `~/.coderio/config.yaml`.
*/
let runtimeModel: ModelConfig | null = null;
let runtimeFigma: FigmaConfig | null = null;
export function setRuntimeConfig(override: {
model?: Partial<ModelConfig>;
figma?: Partial<FigmaConfig>;
}): void {
if (override.model) {
runtimeModel = {
...(runtimeModel ?? { provider: '', model: '', baseUrl: '', apiKey: '' }),
...override.model,
} as ModelConfig;
}
if (override.figma) {
runtimeFigma = { ...(runtimeFigma ?? { token: '' }), ...override.figma } as FigmaConfig;
}
}
export function clearRuntimeConfig(): void {
runtimeModel = null;
runtimeFigma = null;
}
/**
* Merge a partial configuration into the existing config.yaml and persist it.
*
* Only the provided top-level keys are merged (shallow per section), so callers
* can update `model` without touching `figma`. The in-memory cache is cleared
* afterwards so subsequent `loadConfig()` reads the new values.
*
* @param partial - Sections to merge (e.g. `{ model: {...}, figma: {...} }`)
*/
export function saveConfig(partial: Partial<Config>): void {
let existing: Partial<Config> = {};
if (configExists()) {
try {
const raw = yaml.load(readFileSync(CONFIG_FILE, 'utf8')) as Partial<Config> | null;
if (raw && typeof raw === 'object') {
existing = raw;
}
} catch {
existing = {};
}
}
const merged: Config = {
model: { ...(existing.model as ModelConfig), ...(partial.model as Partial<ModelConfig>) } as ModelConfig,
figma: { ...(existing.figma as FigmaConfig), ...(partial.figma as Partial<FigmaConfig>) } as FigmaConfig,
};
if (partial.debug !== undefined) {
merged.debug = { ...(existing.debug as DebugConfig), ...partial.debug } as DebugConfig;
} else if (existing.debug) {
merged.debug = existing.debug;
}
if (!existsSync(CONFIG_DIR)) {
mkdirSync(CONFIG_DIR, { recursive: true });
}
writeFileSync(CONFIG_FILE, yaml.dump(merged), 'utf8');
clearConfigCache();
}
import chalk from 'chalk';
/**
* Log levels emitted by the logger.
*/
export type LogLevel = 'log' | 'info' | 'warn' | 'error' | 'success' | 'test';
/**
* A single log entry forwarded to subscribers (used by the service mode SSE stream).
*/
export interface LogEntry {
level: LogLevel;
message: string;
timestamp: string;
}
type LogListener = (entry: LogEntry) => void;
// Subscribers (e.g. the web service) receive every log entry in real time.
const listeners = new Set<LogListener>();
/**
* Subscribe to all log output. Returns an unsubscribe function.
* Used by the service mode to stream console logs to the web UI via SSE.
*/
export function subscribeLogs(listener: LogListener): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
/**
* Get current timestamp in YYYY-MM-DD HH:mm:ss format
*/
function getTimestamp(): string {
......@@ -15,6 +45,21 @@ function getTimestamp(): string {
}
/**
* Forward an entry to all subscribers (best-effort, never throws).
*/
function emit(level: LogLevel, message: string): void {
if (listeners.size === 0) return;
const entry: LogEntry = { level, message, timestamp: getTimestamp() };
for (const listener of listeners) {
try {
listener(entry);
} catch {
// Ignore subscriber errors to avoid breaking the main flow
}
}
}
/**
* Logger utility for consistent console output with colors
*/
export const logger = {
......@@ -25,6 +70,7 @@ export const logger = {
*/
printLog(message: string): void {
console.log(message);
emit('log', message);
},
/**
......@@ -32,6 +78,7 @@ export const logger = {
*/
printInfoLog(message: string): void {
console.log(chalk.blue(`[${getTimestamp()}] [INFO] ${message}`));
emit('info', message);
},
/**
......@@ -39,6 +86,7 @@ export const logger = {
*/
printWarnLog(message: string): void {
console.warn(chalk.yellow(`[${getTimestamp()}] [WARNING] ${message}`));
emit('warn', message);
},
/**
......@@ -46,6 +94,7 @@ export const logger = {
*/
printErrorLog(message: string): void {
console.error(chalk.red(`[${getTimestamp()}] [ERROR] ✖ ${message}`));
emit('error', message);
},
/**
......@@ -55,6 +104,7 @@ export const logger = {
printTestLog(message: string): void {
if (process.env.NODE_ENV === 'development') {
console.log(chalk.gray(`[${getTimestamp()}] [DEBUG] ${message}`));
emit('test', message);
}
},
......@@ -63,5 +113,6 @@ export const logger = {
*/
printSuccessLog(message: string): void {
console.log(chalk.green(`[${getTimestamp()}] [SUCCESS] ✔ ${message}`));
emit('success', message);
},
};
import { Agent } from 'evoltagent';
/**
* Force evoltagent's model calls to be non-streaming.
*
* Root cause: `Model.achat(messages, tools2, stream = true)` defaults to
* streaming, and `_agentLoop` calls it as `achat(messages, tools2)` — never
* passing the third argument. Inside `achat`, `useStream = stream !== void 0
* ? stream : !!this.config.stream`, so the `stream = true` default *shadows*
* `config.stream`, making a non-streaming config ineffective for agents.
*
* Against some OpenAI-compatible endpoints (e.g. Aliyun MAAS Qwen) the streamed
* response carries `reasoning_content` chunks that evoltagent fails to parse,
* causing the request to hang forever (e.g. stuck at "Initializing project...").
*
* This monkey-patch overrides `achat` on the Model prototype so the third
* argument is always forced to `false`, regardless of what the caller passes.
* Applied once, class-level, so every agent (initial/refiner/judger/launch/
* commit) benefits.
*/
let patched = false;
export function patchEvoltagentStreamingForceOff(): void {
if (patched) return;
try {
const probe = new (Agent as any)({
provider: 'openai',
model: 'probe',
apiKey: 'probe',
baseUrl: 'http://localhost',
});
const modelProto = probe?.model?.constructor?.prototype;
if (modelProto && typeof modelProto.achat === 'function') {
const original = modelProto.achat;
modelProto.achat = function (messages: any, tools?: any, _stream?: boolean) {
// Force non-streaming for every agent call.
return original.call(this, messages, tools, false);
};
}
patched = true;
} catch {
// Best-effort: if probing fails (e.g. missing config), agents still
// run — they may just fall back to streaming. Not fatal.
}
}
......@@ -48,6 +48,17 @@ class Workspace {
}
/**
* Reset the cached workspace so the next `initWorkspace` call rebuilds it.
*
* The CLI runs once per process, but the service mode may run multiple
* jobs (potentially with different root paths / app names) within the same
* process, so it must clear the cached path between jobs.
*/
reset(): void {
this.path = null;
}
/**
* Delete all files and directories inside the workspace
* @param workspace - The workspace structure
* @param preserve - Optional list of relative paths (from workspace root) to preserve from deletion
......
import { describe, it, expect, vi, beforeEach, afterEach, type Mock } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';
import { initializeSqliteSaver } from '../../src/utils/checkpoint';
import { SqliteSaver } from '@langchain/langgraph-checkpoint-sqlite';
// Mock fs
vi.mock('node:fs', () => ({
default: {
existsSync: vi.fn(),
mkdirSync: vi.fn(),
},
}));
// Mock SqliteSaver
vi.mock('@langchain/langgraph-checkpoint-sqlite', () => ({
SqliteSaver: {
fromConnString: vi.fn(),
},
}));
describe('initializeSqliteSaver', () => {
beforeEach(() => {
vi.resetAllMocks();
});
afterEach(() => {
vi.restoreAllMocks();
});
it('should use path.dirname and create directory if it does not exist', () => {
const dbPath = '/path/to/db/file.db';
const dbDir = '/path/to/db'; // Expected dirname on POSIX
// Spy on path.dirname to ensure it is called
// Note: path module is frozen in some environments, so spyOn might fail.
// If so, we rely on the behavior correctness.
const dirnameSpy = vi.spyOn(path, 'dirname');
(fs.existsSync as Mock).mockReturnValue(false);
initializeSqliteSaver(dbPath);
expect(dirnameSpy).toHaveBeenCalledWith(dbPath);
expect(fs.existsSync).toHaveBeenCalledWith(dbDir);
expect(fs.mkdirSync).toHaveBeenCalledWith(dbDir, { recursive: true });
expect(SqliteSaver.fromConnString).toHaveBeenCalledWith(dbPath);
});
});
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { writeFile, createFiles } from '../../src/utils/file';
describe('file utilities', () => {
let tempDir: string;
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'coderio-file-'));
});
afterEach(() => {
fs.rmSync(tempDir, { recursive: true, force: true });
});
it('should create folder and write file content', () => {
const folderPath = path.join(tempDir, 'nested', 'dir');
writeFile(folderPath, 'hello.txt', 'hello');
const fullPath = path.join(folderPath, 'hello.txt');
expect(fs.existsSync(fullPath)).toBe(true);
expect(fs.readFileSync(fullPath, 'utf-8')).toBe('hello');
});
it('should no-op when missing required arguments', () => {
writeFile('', 'a.txt', 'content');
writeFile(tempDir, '', 'content');
writeFile(tempDir, 'a.txt', '');
expect(fs.readdirSync(tempDir)).toHaveLength(0);
});
it('createFiles should write multiple files to directory derived from filePath', () => {
const outputFilePath = path.join(tempDir, 'App.tsx');
createFiles({
filePath: outputFilePath,
files: [
{ filename: 'A.ts', content: 'export const A = 1;' },
{ filename: 'B.ts', content: 'export const B = 2;' },
],
});
expect(fs.readFileSync(path.join(tempDir, 'A.ts'), 'utf-8')).toBe('export const A = 1;');
expect(fs.readFileSync(path.join(tempDir, 'B.ts'), 'utf-8')).toBe('export const B = 2;');
});
});
import { describe, it, expect, vi } from 'vitest';
import { promisePool } from '../../src/utils/promise-pool';
describe('promisePool', () => {
it('should process all items successfully', async () => {
const items = [1, 2, 3, 4, 5];
const taskGenerator = async (item: number) => item * 2;
const results = await promisePool(items, taskGenerator, 2);
expect(results).toEqual([2, 4, 6, 8, 10]);
});
it('should respect concurrency limit', async () => {
const items = [1, 2, 3, 4, 5];
let currentConcurrency = 0;
let maxConcurrency = 0;
const taskGenerator = async (item: number) => {
currentConcurrency++;
maxConcurrency = Math.max(maxConcurrency, currentConcurrency);
await new Promise(resolve => setTimeout(resolve, 10));
currentConcurrency--;
return item * 2;
};
await promisePool(items, taskGenerator, 2);
expect(maxConcurrency).toBe(2);
});
it('should handle empty array', async () => {
const items: number[] = [];
const taskGenerator = async (item: number) => item * 2;
const results = await promisePool(items, taskGenerator, 2);
expect(results).toEqual([]);
});
it('should handle null or undefined items array', async () => {
const taskGenerator = async (item: number) => item * 2;
const results1 = await promisePool(null as any, taskGenerator, 2);
const results2 = await promisePool(undefined as any, taskGenerator, 2);
expect(results1).toEqual([]);
expect(results2).toEqual([]);
});
it('should maintain order of results', async () => {
const items = [1, 2, 3, 4, 5];
const taskGenerator = async (item: number) => {
// Simulate different processing times
await new Promise(resolve => setTimeout(resolve, (5 - item) * 10));
return item * 2;
};
const results = await promisePool(items, taskGenerator, 3);
expect(results).toEqual([2, 4, 6, 8, 10]);
});
it('should handle errors in task execution', async () => {
const items = [1, 2, 3, 4, 5];
const taskGenerator = async (item: number) => {
if (item === 3) {
throw new Error('Task failed');
}
return item * 2;
};
await expect(promisePool(items, taskGenerator, 2)).rejects.toThrow('Task failed');
});
it('should work with default concurrency', async () => {
const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const taskGenerator = async (item: number) => item * 2;
const results = await promisePool(items, taskGenerator);
expect(results).toEqual([2, 4, 6, 8, 10, 12, 14, 16, 18, 20]);
});
it('should handle concurrency of 1', async () => {
const items = [1, 2, 3];
const executionOrder: number[] = [];
const taskGenerator = async (item: number) => {
executionOrder.push(item);
await new Promise(resolve => setTimeout(resolve, 5));
return item * 2;
};
const results = await promisePool(items, taskGenerator, 1);
expect(results).toEqual([2, 4, 6]);
expect(executionOrder).toEqual([1, 2, 3]);
});
it('should handle concurrency greater than items length', async () => {
const items = [1, 2, 3];
const taskGenerator = async (item: number) => item * 2;
const results = await promisePool(items, taskGenerator, 10);
expect(results).toEqual([2, 4, 6]);
});
it('should handle async tasks that return different types', async () => {
const items = ['a', 'b', 'c'];
const taskGenerator = async (item: string) => ({ value: item, length: item.length });
const results = await promisePool(items, taskGenerator, 2);
expect(results).toEqual([
{ value: 'a', length: 1 },
{ value: 'b', length: 1 },
{ value: 'c', length: 1 },
]);
});
it('should handle tasks with varying completion times', async () => {
const items = [100, 50, 25, 10, 5];
const taskGenerator = async (item: number) => {
await new Promise(resolve => setTimeout(resolve, item));
return item;
};
const results = await promisePool(items, taskGenerator, 3);
expect(results).toEqual([100, 50, 25, 10, 5]);
});
it('should handle promises that resolve immediately', async () => {
const items = [1, 2, 3, 4, 5];
const taskGenerator = async (item: number) => item * 2;
const results = await promisePool(items, taskGenerator, 2);
expect(results).toEqual([2, 4, 6, 8, 10]);
});
it('should call task generator for each item', async () => {
const items = [1, 2, 3];
const taskGenerator = vi.fn(async (item: number) => item * 2);
await promisePool(items, taskGenerator, 2);
expect(taskGenerator).toHaveBeenCalledTimes(3);
expect(taskGenerator).toHaveBeenCalledWith(1);
expect(taskGenerator).toHaveBeenCalledWith(2);
expect(taskGenerator).toHaveBeenCalledWith(3);
});
it('should handle large arrays efficiently', async () => {
const items = Array.from({ length: 100 }, (_, i) => i + 1); // Start from 1 to avoid 0 edge case
const taskGenerator = async (item: number) => item * 2;
const results = await promisePool(items, taskGenerator, 10);
expect(results.length).toBe(100);
expect(results[0]).toBe(2); // First item is 1 * 2
expect(results[99]).toBe(200); // Last item is 100 * 2
});
});
import { describe, it, expect } from 'vitest';
import { parseFigmaUrl } from '../../src/utils/url-parser';
describe('parseFigmaUrl', () => {
it('should parse valid Figma URL with node-id', () => {
const url = 'https://www.figma.com/design/aONcu8L82l1PdcT304Q8Za/Intern?node-id=0-495';
const result = parseFigmaUrl(url);
expect(result).toEqual({
fileId: 'aONcu8L82l1PdcT304Q8Za',
name: 'intern',
nodeId: '0:495',
projectName: 'intern_0_495',
});
});
it('should convert node-id hyphens to colons', () => {
const url = 'https://www.figma.com/design/abc123/MyProject?node-id=123-456';
const result = parseFigmaUrl(url);
expect(result.nodeId).toBe('123:456');
});
it('should handle URL-encoded characters in project name', () => {
const url = 'https://www.figma.com/design/abc123/My%20Project?node-id=0-1';
const result = parseFigmaUrl(url);
// encodeURI on already encoded string results in double encoding
expect(result.name).toBe('my%2520project');
});
it('should convert project name to lowercase', () => {
const url = 'https://www.figma.com/design/abc123/MyProject?node-id=0-1';
const result = parseFigmaUrl(url);
expect(result.name).toBe('myproject');
});
it('should truncate long project names to 20 characters', () => {
const longName = 'a'.repeat(30);
const url = `https://www.figma.com/design/abc123/${longName}?node-id=0-1`;
const result = parseFigmaUrl(url);
expect(result.name).toHaveLength(20);
expect(result.name).toBe('a'.repeat(20));
});
it('should handle empty project name slot', () => {
// When the project name slot is empty but pathParts length is still >= 3
const url = 'https://www.figma.com/design/abc123?node-id=0-1';
// This will throw because fileId extraction expects at least 3 path parts
expect(() => parseFigmaUrl(url)).toThrow('Invalid Figma URL');
});
it('should throw error for URL without fileId', () => {
const url = 'https://www.figma.com/design/?node-id=0-1';
expect(() => parseFigmaUrl(url)).toThrow('Invalid Figma URL');
});
it('should throw error for URL without node-id', () => {
const url = 'https://www.figma.com/design/abc123/MyProject';
expect(() => parseFigmaUrl(url)).toThrow('Invalid Figma URL');
});
it('should throw error for invalid URL format', () => {
const url = 'not-a-valid-url';
expect(() => parseFigmaUrl(url)).toThrow('Invalid Figma URL');
});
it('should handle file URLs', () => {
const url = 'https://www.figma.com/file/abc123/MyProject?node-id=0-1';
const result = parseFigmaUrl(url);
expect(result.fileId).toBe('abc123');
expect(result.nodeId).toBe('0:1');
});
it('should handle complex node-id with multiple hyphens', () => {
const url = 'https://www.figma.com/design/abc123/MyProject?node-id=123-456-789';
const result = parseFigmaUrl(url);
expect(result.nodeId).toBe('123:456:789');
});
it('should generate correct projectName', () => {
const url = 'https://www.figma.com/design/abc123/TestProject?node-id=1-2';
const result = parseFigmaUrl(url);
expect(result.projectName).toBe('testproject_1_2');
});
it('should handle URLs with additional query parameters', () => {
const url = 'https://www.figma.com/design/abc123/MyProject?node-id=0-1&mode=design&t=xyz123';
const result = parseFigmaUrl(url);
expect(result.fileId).toBe('abc123');
expect(result.nodeId).toBe('0:1');
expect(result.name).toBe('myproject');
});
it('should handle URLs with hash fragments', () => {
const url = 'https://www.figma.com/design/abc123/MyProject?node-id=0-1#section';
const result = parseFigmaUrl(url);
expect(result.fileId).toBe('abc123');
expect(result.nodeId).toBe('0:1');
});
it('should handle proto URLs', () => {
const url = 'https://www.figma.com/proto/abc123/MyProject?node-id=0-1';
const result = parseFigmaUrl(url);
expect(result.fileId).toBe('abc123');
expect(result.name).toBe('myproject');
});
});
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { workspaceManager } from '../../src/utils/workspace';
import { WorkspaceStructure } from '../../src/types/workspace-types';
describe('workspaceManager', () => {
let tempRoot: string;
beforeEach(() => {
// Reset singleton internal state between tests
(workspaceManager as any).path = null;
tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'coderio-ws-'));
});
afterEach(() => {
fs.rmSync(tempRoot, { recursive: true, force: true });
(workspaceManager as any).path = null;
});
it('initWorkspace should compute workspace structure and cache it', () => {
const ws1 = workspaceManager.initWorkspace('proj', tempRoot, 'my-app');
const ws2 = workspaceManager.initWorkspace('other', '/should-not-apply', 'other-app');
expect(ws2).toBe(ws1);
expect(ws1.root).toBe(path.resolve(tempRoot, 'coderio', 'proj'));
expect(ws1.app).toBe(path.join(ws1.root, 'my-app'));
expect(ws1.process).toBe(path.join(ws1.root, 'process'));
expect(ws1.debug).toBe(path.join(ws1.root, 'debug'));
expect(ws1.reports).toBe(path.join(ws1.root, 'reports.html'));
expect(ws1.db).toBe(path.join(ws1.root, 'checkpoint', 'coderio-cli.db'));
expect(ws1.checkpoint).toBe(path.join(ws1.root, 'checkpoint', 'checkpoint.json'));
});
it('resolveAppSrc should join app/src with subpath', () => {
const paths: WorkspaceStructure = {
root: '/r',
app: '/r/my-app',
process: '/r/process',
debug: '/r/debug',
reports: '/r/reports.html',
db: '/r/checkpoint/db.sqlite',
checkpoint: '/r/checkpoint/checkpoint.json',
};
expect(workspaceManager.resolveAppSrc(paths, 'components/Button')).toBe(path.join(paths.app, 'src', 'components/Button'));
});
it('resolveComponentPath should normalize common alias variants', () => {
expect(workspaceManager.resolveComponentPath('@/components/Button')).toBe('components/Button/index.tsx');
expect(workspaceManager.resolveComponentPath('@/src/components/Button')).toBe('components/Button/index.tsx');
expect(workspaceManager.resolveComponentPath('components/Button')).toBe('components/Button/index.tsx');
expect(workspaceManager.resolveComponentPath('components/Button.tsx')).toBe('components/Button.tsx');
expect(workspaceManager.resolveComponentPath('components/Button/index.tsx')).toBe('components/Button/index.tsx');
});
it('deleteWorkspace should delete all entries inside workspace root', () => {
const root = path.join(tempRoot, 'workspace');
fs.mkdirSync(root, { recursive: true });
fs.writeFileSync(path.join(root, 'a.txt'), 'a');
fs.mkdirSync(path.join(root, 'dir'));
fs.writeFileSync(path.join(root, 'dir', 'b.txt'), 'b');
const ws: WorkspaceStructure = {
root,
app: '',
process: '',
debug: '',
reports: '',
db: '',
checkpoint: '',
};
workspaceManager.deleteWorkspace(ws);
expect(fs.existsSync(root)).toBe(true);
expect(fs.readdirSync(root)).toHaveLength(0);
});
it('deleteWorkspace should preserve specified files while deleting others', () => {
const root = path.join(tempRoot, 'workspace-preserve');
fs.mkdirSync(root, { recursive: true });
fs.writeFileSync(path.join(root, 'a.txt'), 'a');
fs.writeFileSync(path.join(root, 'delete-me.txt'), 'delete');
fs.mkdirSync(path.join(root, 'checkpoint'), { recursive: true });
fs.writeFileSync(path.join(root, 'checkpoint', 'coderio-cli.db'), 'db');
fs.writeFileSync(path.join(root, 'checkpoint', 'checkpoint.json'), 'json');
fs.mkdirSync(path.join(root, 'process'), { recursive: true });
fs.writeFileSync(path.join(root, 'process', 'data.txt'), 'data');
const ws: WorkspaceStructure = {
root,
app: '',
process: '',
debug: '',
reports: '',
db: '',
checkpoint: '',
};
// Preserve only the database file
workspaceManager.deleteWorkspace(ws, ['checkpoint/coderio-cli.db']);
// Root should still exist
expect(fs.existsSync(root)).toBe(true);
// checkpoint directory should still exist (contains preserved file)
expect(fs.existsSync(path.join(root, 'checkpoint'))).toBe(true);
// Database file should be preserved
expect(fs.existsSync(path.join(root, 'checkpoint', 'coderio-cli.db'))).toBe(true);
expect(fs.readFileSync(path.join(root, 'checkpoint', 'coderio-cli.db'), 'utf8')).toBe('db');
// checkpoint.json should be deleted
expect(fs.existsSync(path.join(root, 'checkpoint', 'checkpoint.json'))).toBe(false);
// Other files and directories should be deleted
expect(fs.existsSync(path.join(root, 'a.txt'))).toBe(false);
expect(fs.existsSync(path.join(root, 'delete-me.txt'))).toBe(false);
expect(fs.existsSync(path.join(root, 'process'))).toBe(false);
});
});
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"lib": ["ES2022"],
"moduleResolution": "bundler",
"resolveJsonModule": true,
"allowJs": false,
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"strictPropertyInitialization": true,
"noImplicitThis": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"types": ["node"]
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "scripts", "src/tools/report-tool/template/**"]
}
import { defineConfig } from 'tsup';
import { readFileSync, cpSync, existsSync } from 'fs';
// Read version from package.json at build time
const pkg = JSON.parse(readFileSync('./package.json', 'utf8')) as { version: string };
export default defineConfig({
entry: {
index: 'src/index.ts',
cli: 'src/cli/index.ts',
},
// Use ESM format with proper CJS interop
format: ['esm'],
dts: true,
splitting: false,
sourcemap: true,
clean: true,
minify: false,
target: 'node18',
outDir: 'dist',
platform: 'node',
// All dependencies are external by default (automatic)
// Explicitly list only special cases for documentation purposes
external: [
/^@langchain\//, // Scoped package with many submodules
],
// Inject version at build time
define: {
__VERSION__: JSON.stringify(pkg.version),
},
// Copy report template to dist after build
onSuccess: async () => {
const templateSrc = 'src/tools/report-tool/template/dist';
const templateDest = 'dist/tools/report-tool/template';
if (existsSync(templateSrc)) {
console.log(`\nCopying report template from ${templateSrc} to ${templateDest}...`);
cpSync(templateSrc, templateDest, { recursive: true });
console.log('✓ Report template copied successfully');
} else {
console.warn(`⚠ Warning: Report template source not found at ${templateSrc}`);
console.warn(' Run "pnpm run build:report" first to build the template');
}
},
});
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true,
environment: 'node',
include: ['tests/**/*.test.ts'],
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html'],
include: [
// Only include files that have tests
'src/utils/naming.ts',
'src/utils/parser.ts',
'src/utils/url-parser.ts',
'src/utils/promise-pool.ts',
'src/utils/config.ts',
'src/utils/file.ts',
'src/utils/workspace.ts',
'src/utils/checkpoint.ts',
'src/utils/code-cache.ts',
'src/tools/style-tool/color.ts',
'src/tools/position-tool/utils/position-metrics.ts',
'src/nodes/validation/utils/tree/tree-traversal.ts',
],
exclude: [
'node_modules/',
'dist/',
'tests/',
'coderio/',
'src/tools/report-tool/template/',
'**/*.d.ts',
'**/*.config.ts',
'**/*.config.js',
'src/cli/',
'src/env.d.ts',
],
},
},
});
<!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: #f7f8fa;
--panel: #ffffff;
--border: #e6e8eb;
--text: #1f2329;
--muted: #8a9099;
--primary: #534ab7;
--primary-soft: #eeeefe;
--green: #1d9e75;
--red: #e24b4a;
--amber: #ba7517;
--radius: 12px;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: -apple-system, blinkmacsystemfont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
background: var(--bg);
color: var(--text);
font-size: 14px;
line-height: 1.6;
}
header {
padding: 20px 28px;
background: var(--panel);
border-bottom: 1px solid var(--border);
display: flex;
align-items: center;
justify-content: space-between;
}
header h1 {
font-size: 18px;
margin: 0;
font-weight: 600;
}
header .sub {
color: var(--muted);
font-size: 12px;
margin-top: 2px;
}
.badge {
font-size: 12px;
padding: 4px 10px;
border-radius: 999px;
background: var(--primary-soft);
color: var(--primary);
font-weight: 500;
}
.wrap {
max-width: 980px;
margin: 24px auto;
padding: 0 20px;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
}
@media (max-width: 760px) {
.wrap {
grid-template-columns: 1fr;
}
}
.card {
background: var(--panel);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 20px;
}
.card h2 {
font-size: 15px;
margin: 0 0 14px;
font-weight: 600;
}
label {
display: block;
font-size: 12px;
color: var(--muted);
margin: 12px 0 6px;
}
input,
select {
width: 100%;
padding: 9px 11px;
border: 1px solid var(--border);
border-radius: 8px;
font-size: 13px;
background: #fff;
color: var(--text);
}
input:focus,
select:focus {
outline: none;
border-color: var(--primary);
}
.hint {
font-size: 11px;
color: var(--muted);
margin-top: 4px;
}
button {
margin-top: 16px;
width: 100%;
padding: 10px 14px;
border: none;
border-radius: 8px;
background: var(--primary);
color: #fff;
font-size: 14px;
font-weight: 500;
cursor: pointer;
}
button.secondary {
background: var(--primary-soft);
color: var(--primary);
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.row {
display: flex;
gap: 10px;
}
.row > * {
flex: 1;
}
.logwrap {
margin: 0 20px 28px;
max-width: 980px;
margin-left: auto;
margin-right: auto;
}
.loghead {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
}
.status {
font-size: 12px;
padding: 4px 10px;
border-radius: 999px;
background: #f1efea;
color: var(--muted);
}
.status.idle {
background: #f1efea;
}
.status.running {
background: #e6f1fb;
color: #185fa5;
}
.status.done {
background: #eaf3de;
color: var(--green);
}
.status.error {
background: #fcebeb;
color: var(--red);
}
#log {
background: #0f1115;
color: #d7dbe0;
border-radius: var(--radius);
padding: 14px 16px;
height: 320px;
overflow-y: auto;
font-family: 'SFMono-Regular', consolas, 'Liberation Mono', monospace;
font-size: 12px;
line-height: 1.55;
white-space: pre-wrap;
word-break: break-word;
}
#log .info {
color: #8ab4f8;
}
#log .warn {
color: #f5c777;
}
#log .error {
color: #ff8a8a;
}
#log .success {
color: #7fdca0;
}
.result {
margin-top: 14px;
padding: 12px 14px;
border: 1px dashed var(--border);
border-radius: 8px;
font-size: 13px;
display: none;
}
.result.show {
display: block;
}
.result code {
background: var(--primary-soft);
padding: 2px 6px;
border-radius: 5px;
color: var(--primary);
}
.copy {
margin-left: 8px;
font-size: 11px;
color: var(--primary);
cursor: pointer;
border: 1px solid var(--border);
border-radius: 5px;
padding: 1px 6px;
}
.msg {
font-size: 12px;
margin-top: 10px;
min-height: 16px;
}
.msg.ok {
color: var(--green);
}
.msg.err {
color: var(--red);
}
</style>
</head>
<body>
<header>
<div>
<h1>🎨 CodeRio 服务模式</h1>
<div class="sub">配置 AI / Figma 参数,一键将设计稿转换为生产级前端代码</div>
</div>
<span class="badge" id="conn">连接中…</span>
</header>
<div class="wrap">
<div class="card">
<h2>① 模型与密钥配置</h2>
<label>模型服务商</label>
<select id="provider">
<option value="openai" selected>OpenAI 兼容 (Qwen / DeepSeek / 自建)</option>
<option value="anthropic">Anthropic</option>
<option value="google">Google</option>
</select>
<label>模型名称</label>
<input id="model" placeholder="如 qwen3.8-max(需多模态视觉能力)" />
<label>API Base URL</label>
<input id="baseUrl" placeholder="https://...maas.aliyuncs.com/compatible-mode/v1" />
<label>API Key</label>
<input id="apiKey" type="password" placeholder="sk-..." />
<label>Figma Token</label>
<input id="figmaToken" type="password" placeholder="Figma Personal Access Token" />
<div class="hint">配置保存在 ~/.coderio/config.yaml,与 CLI 共用。</div>
<button class="secondary" id="saveConfig">保存配置</button>
<div class="msg" id="configMsg"></div>
</div>
<div class="card">
<h2>② 生成页面</h2>
<label>Figma 链接 <span style="color: var(--red)">*</span></label>
<input id="figmaUrl" placeholder="https://www.figma.com/design/..." />
<label>执行模式</label>
<select id="mode">
<option value="code">仅生成代码(code)</option>
<option value="with-report">生成 + 单次校验报告(with-report)</option>
<option value="full" selected>生成 + 迭代校验修复(full)</option>
</select>
<div class="row">
<div>
<label>输出目录</label>
<input id="outputDir" placeholder="留空=当前目录/coderio" />
</div>
<div>
<label>应用名</label>
<input id="appName" placeholder="my-app" />
</div>
</div>
<div class="hint">技术栈:React + Vite + TypeScript + Tailwind(当前版本)。</div>
<button id="generate">🚀 生成页面</button>
<div class="msg" id="genMsg"></div>
</div>
</div>
<div class="logwrap">
<div class="card">
<h2>③ 预览生成结果</h2>
<div class="hint">
启动一个持久化的本地开发服务器(Vite),用于实时查看生成的页面。验证阶段内部临时起的 5837
服务会自动关闭,此处的预览服务会一直运行,直到你点「停止预览」。
</div>
<div class="row">
<button id="previewStart">▶ 启动预览</button>
<button class="secondary" id="previewStop" disabled>■ 停止预览</button>
</div>
<div class="msg" id="previewMsg"></div>
<div class="result" id="previewResult"></div>
</div>
</div>
<div class="logwrap">
<div class="loghead">
<h2 style="margin: 0; font-size: 15px">实时进度</h2>
<span class="status idle" id="status">空闲</span>
</div>
<div id="log"></div>
<div class="result" id="result"></div>
</div>
<script>
const $ = (id) => document.getElementById(id);
const logEl = $('log');
const statusEl = $('status');
function setStatus(state, text) {
statusEl.className = 'status ' + state;
statusEl.textContent = text;
}
function appendLog(entry) {
const line = document.createElement('div');
const cls = entry.level === 'log' ? '' : entry.level;
if (cls) line.className = cls;
line.textContent = '[' + entry.timestamp.split(' ')[1] + '] ' + entry.message;
logEl.appendChild(line);
logEl.scrollTop = logEl.scrollHeight;
}
// Load existing config
async function loadConfig() {
try {
const r = await fetch('/api/config');
const c = await r.json();
if (c.model) {
$('provider').value = c.model.provider || 'qwen';
$('model').value = c.model.model || '';
$('baseUrl').value = c.model.baseUrl || '';
$('apiKey').value = c.model.apiKey || '';
}
if (c.figma) $('figmaToken').value = c.figma.token || '';
$('conn').textContent = '已连接';
$('conn').style.color = 'var(--green)';
} catch (e) {
$('conn').textContent = '连接失败';
$('conn').style.color = 'var(--red)';
}
}
// Save config
$('saveConfig').addEventListener('click', async () => {
const body = {
model: {
provider: $('provider').value,
model: $('model').value.trim(),
baseUrl: $('baseUrl').value.trim(),
apiKey: $('apiKey').value.trim(),
},
figma: { token: $('figmaToken').value.trim() },
};
const msg = $('configMsg');
msg.className = 'msg';
msg.textContent = '保存中…';
try {
const r = await fetch('/api/config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const j = await r.json();
if (j.ok) {
msg.className = 'msg ok';
msg.textContent = '✓ 配置已保存';
} else {
msg.className = 'msg err';
msg.textContent = '✖ ' + (j.error || '保存失败');
}
} catch (e) {
msg.className = 'msg err';
msg.textContent = '✖ 请求失败';
}
});
// Generate
$('generate').addEventListener('click', async () => {
const figmaUrl = $('figmaUrl').value.trim();
if (!figmaUrl) {
$('genMsg').className = 'msg err';
$('genMsg').textContent = '✖ 请填写 Figma 链接';
return;
}
const genMsg = $('genMsg');
genMsg.className = 'msg';
genMsg.textContent = '提交任务中…';
$('result').className = 'result';
try {
const r = await fetch('/api/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
figmaUrl,
mode: $('mode').value,
outputDir: $('outputDir').value.trim() || undefined,
appName: $('appName').value.trim() || undefined,
}),
});
const j = await r.json();
if (!r.ok) {
genMsg.className = 'msg err';
genMsg.textContent = '✖ ' + (j.error || '提交失败');
return;
}
genMsg.className = 'msg ok';
genMsg.textContent = '✓ 已启动,任务 ID: ' + j.jobId;
$('generate').disabled = true;
} catch (e) {
genMsg.className = 'msg err';
genMsg.textContent = '✖ 请求失败';
}
});
function showResult(job) {
const box = $('result');
box.className = 'result show';
if (job.status === 'done') {
let html = '✓ 生成完成!<br/>产物目录:<code>' + (job.outputDir || '-') + '</code>';
if (job.reportPath) {
html += '<br/>校验报告:<code>' + job.reportPath + '</code>';
}
box.innerHTML = html;
} else if (job.status === 'error') {
box.className = 'result show';
box.innerHTML = '✖ 生成失败:' + (job.error || '未知错误');
}
}
// Preview
function updatePreviewUI(st) {
const msg = $('previewMsg');
const box = $('previewResult');
if (st.running && !st.url && !st.error) {
msg.className = 'msg';
msg.textContent = '预览服务启动中,等待地址…';
$('previewStart').disabled = true;
$('previewStop').disabled = false;
}
if (st.url) {
box.className = 'result show';
const local = st.localUrl ? `<code>${st.localUrl}</code>` : '-';
const net = st.url
? `<a href="${st.url}" target="_blank" style="color:var(--primary)">${st.url}</a>`
: '-';
box.innerHTML =
'✓ 预览已启动<br/>本地地址:' + local + '<br/>网络地址:' + net;
$('previewStop').disabled = false;
$('previewStart').disabled = true;
msg.className = 'msg ok';
msg.textContent = '预览运行中';
}
if (st.error) {
msg.className = 'msg err';
msg.textContent = '✖ ' + st.error;
$('previewStart').disabled = false;
$('previewStop').disabled = true;
}
if (!st.running && !st.url && !st.error) {
$('previewStart').disabled = false;
$('previewStop').disabled = true;
box.className = 'result';
}
}
$('previewStart').addEventListener('click', async () => {
const msg = $('previewMsg');
msg.className = 'msg';
msg.textContent = '正在启动预览服务…';
$('previewStart').disabled = true;
try {
const r = await fetch('/api/preview', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
});
const j = await r.json();
if (!j.ok) {
msg.className = 'msg err';
msg.textContent = '✖ ' + (j.error || '启动失败');
$('previewStart').disabled = false;
return;
}
msg.textContent = '预览服务启动中,等待地址…';
} catch (e) {
msg.className = 'msg err';
msg.textContent = '✖ 请求失败';
$('previewStart').disabled = false;
}
});
$('previewStop').addEventListener('click', async () => {
try {
await fetch('/api/preview/stop', { method: 'POST' });
} catch {
/* ignore */
}
$('previewStart').disabled = false;
$('previewStop').disabled = true;
$('previewResult').className = 'result';
$('previewMsg').textContent = '已停止预览';
});
// SSE stream
function connectStream() {
const es = new EventSource('/api/stream');
es.addEventListener('log', (e) => appendLog(JSON.parse(e.data)));
es.addEventListener('job', (e) => {
const job = JSON.parse(e.data);
if (job.status === 'running') {
setStatus('running', '生成中');
$('generate').disabled = true;
} else if (job.status === 'done') {
setStatus('done', '完成');
$('generate').disabled = false;
showResult(job);
} else if (job.status === 'error') {
setStatus('error', '失败');
$('generate').disabled = false;
showResult(job);
}
});
es.addEventListener('preview', (e) => {
try {
updatePreviewUI(JSON.parse(e.data));
} catch {
/* ignore */
}
});
es.onerror = () => {
$('conn').textContent = '流断开,重连中…';
$('conn').style.color = 'var(--amber)';
};
}
loadConfig();
connectStream();
</script>
</body>
</html>
packages:
- 'packages/*'
- 'apps/*'
/**
* File information for batch creation
*/
export interface FileInfo {
filename: string;
content: string;
}
import { describe, it, expect, vi, beforeEach, afterEach, type Mock } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';
import { initializeSqliteSaver } from '../../src/utils/checkpoint';
import { SqliteSaver } from '@langchain/langgraph-checkpoint-sqlite';
// Mock fs
vi.mock('node:fs', () => ({
default: {
existsSync: vi.fn(),
mkdirSync: vi.fn(),
},
}));
// Mock SqliteSaver
vi.mock('@langchain/langgraph-checkpoint-sqlite', () => ({
SqliteSaver: {
fromConnString: vi.fn(),
},
}));
describe('initializeSqliteSaver', () => {
beforeEach(() => {
vi.resetAllMocks();
});
afterEach(() => {
vi.restoreAllMocks();
});
it('should use path.dirname and create directory if it does not exist', () => {
const dbPath = '/path/to/db/file.db';
const dbDir = '/path/to/db'; // Expected dirname on POSIX
// Spy on path.dirname to ensure it is called
// Note: path module is frozen in some environments, so spyOn might fail.
// If so, we rely on the behavior correctness.
const dirnameSpy = vi.spyOn(path, 'dirname');
(fs.existsSync as Mock).mockReturnValue(false);
initializeSqliteSaver(dbPath);
expect(dirnameSpy).toHaveBeenCalledWith(dbPath);
expect(fs.existsSync).toHaveBeenCalledWith(dbDir);
expect(fs.mkdirSync).toHaveBeenCalledWith(dbDir, { recursive: true });
expect(SqliteSaver.fromConnString).toHaveBeenCalledWith(dbPath);
});
});
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { writeFile, createFiles } from '../../src/utils/file';
describe('file utilities', () => {
let tempDir: string;
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'coderio-file-'));
});
afterEach(() => {
fs.rmSync(tempDir, { recursive: true, force: true });
});
it('should create folder and write file content', () => {
const folderPath = path.join(tempDir, 'nested', 'dir');
writeFile(folderPath, 'hello.txt', 'hello');
const fullPath = path.join(folderPath, 'hello.txt');
expect(fs.existsSync(fullPath)).toBe(true);
expect(fs.readFileSync(fullPath, 'utf-8')).toBe('hello');
});
it('should no-op when missing required arguments', () => {
writeFile('', 'a.txt', 'content');
writeFile(tempDir, '', 'content');
writeFile(tempDir, 'a.txt', '');
expect(fs.readdirSync(tempDir)).toHaveLength(0);
});
it('createFiles should write multiple files to directory derived from filePath', () => {
const outputFilePath = path.join(tempDir, 'App.tsx');
createFiles({
filePath: outputFilePath,
files: [
{ filename: 'A.ts', content: 'export const A = 1;' },
{ filename: 'B.ts', content: 'export const B = 2;' },
],
});
expect(fs.readFileSync(path.join(tempDir, 'A.ts'), 'utf-8')).toBe('export const A = 1;');
expect(fs.readFileSync(path.join(tempDir, 'B.ts'), 'utf-8')).toBe('export const B = 2;');
});
});
import { describe, it, expect, vi } from 'vitest';
import { promisePool } from '../../src/utils/promise-pool';
describe('promisePool', () => {
it('should process all items successfully', async () => {
const items = [1, 2, 3, 4, 5];
const taskGenerator = async (item: number) => item * 2;
const results = await promisePool(items, taskGenerator, 2);
expect(results).toEqual([2, 4, 6, 8, 10]);
});
it('should respect concurrency limit', async () => {
const items = [1, 2, 3, 4, 5];
let currentConcurrency = 0;
let maxConcurrency = 0;
const taskGenerator = async (item: number) => {
currentConcurrency++;
maxConcurrency = Math.max(maxConcurrency, currentConcurrency);
await new Promise(resolve => setTimeout(resolve, 10));
currentConcurrency--;
return item * 2;
};
await promisePool(items, taskGenerator, 2);
expect(maxConcurrency).toBe(2);
});
it('should handle empty array', async () => {
const items: number[] = [];
const taskGenerator = async (item: number) => item * 2;
const results = await promisePool(items, taskGenerator, 2);
expect(results).toEqual([]);
});
it('should handle null or undefined items array', async () => {
const taskGenerator = async (item: number) => item * 2;
const results1 = await promisePool(null as any, taskGenerator, 2);
const results2 = await promisePool(undefined as any, taskGenerator, 2);
expect(results1).toEqual([]);
expect(results2).toEqual([]);
});
it('should maintain order of results', async () => {
const items = [1, 2, 3, 4, 5];
const taskGenerator = async (item: number) => {
// Simulate different processing times
await new Promise(resolve => setTimeout(resolve, (5 - item) * 10));
return item * 2;
};
const results = await promisePool(items, taskGenerator, 3);
expect(results).toEqual([2, 4, 6, 8, 10]);
});
it('should handle errors in task execution', async () => {
const items = [1, 2, 3, 4, 5];
const taskGenerator = async (item: number) => {
if (item === 3) {
throw new Error('Task failed');
}
return item * 2;
};
await expect(promisePool(items, taskGenerator, 2)).rejects.toThrow('Task failed');
});
it('should work with default concurrency', async () => {
const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const taskGenerator = async (item: number) => item * 2;
const results = await promisePool(items, taskGenerator);
expect(results).toEqual([2, 4, 6, 8, 10, 12, 14, 16, 18, 20]);
});
it('should handle concurrency of 1', async () => {
const items = [1, 2, 3];
const executionOrder: number[] = [];
const taskGenerator = async (item: number) => {
executionOrder.push(item);
await new Promise(resolve => setTimeout(resolve, 5));
return item * 2;
};
const results = await promisePool(items, taskGenerator, 1);
expect(results).toEqual([2, 4, 6]);
expect(executionOrder).toEqual([1, 2, 3]);
});
it('should handle concurrency greater than items length', async () => {
const items = [1, 2, 3];
const taskGenerator = async (item: number) => item * 2;
const results = await promisePool(items, taskGenerator, 10);
expect(results).toEqual([2, 4, 6]);
});
it('should handle async tasks that return different types', async () => {
const items = ['a', 'b', 'c'];
const taskGenerator = async (item: string) => ({ value: item, length: item.length });
const results = await promisePool(items, taskGenerator, 2);
expect(results).toEqual([
{ value: 'a', length: 1 },
{ value: 'b', length: 1 },
{ value: 'c', length: 1 },
]);
});
it('should handle tasks with varying completion times', async () => {
const items = [100, 50, 25, 10, 5];
const taskGenerator = async (item: number) => {
await new Promise(resolve => setTimeout(resolve, item));
return item;
};
const results = await promisePool(items, taskGenerator, 3);
expect(results).toEqual([100, 50, 25, 10, 5]);
});
it('should handle promises that resolve immediately', async () => {
const items = [1, 2, 3, 4, 5];
const taskGenerator = async (item: number) => item * 2;
const results = await promisePool(items, taskGenerator, 2);
expect(results).toEqual([2, 4, 6, 8, 10]);
});
it('should call task generator for each item', async () => {
const items = [1, 2, 3];
const taskGenerator = vi.fn(async (item: number) => item * 2);
await promisePool(items, taskGenerator, 2);
expect(taskGenerator).toHaveBeenCalledTimes(3);
expect(taskGenerator).toHaveBeenCalledWith(1);
expect(taskGenerator).toHaveBeenCalledWith(2);
expect(taskGenerator).toHaveBeenCalledWith(3);
});
it('should handle large arrays efficiently', async () => {
const items = Array.from({ length: 100 }, (_, i) => i + 1); // Start from 1 to avoid 0 edge case
const taskGenerator = async (item: number) => item * 2;
const results = await promisePool(items, taskGenerator, 10);
expect(results.length).toBe(100);
expect(results[0]).toBe(2); // First item is 1 * 2
expect(results[99]).toBe(200); // Last item is 100 * 2
});
});
import { describe, it, expect } from 'vitest';
import { parseFigmaUrl } from '../../src/utils/url-parser';
describe('parseFigmaUrl', () => {
it('should parse valid Figma URL with node-id', () => {
const url = 'https://www.figma.com/design/aONcu8L82l1PdcT304Q8Za/Intern?node-id=0-495';
const result = parseFigmaUrl(url);
expect(result).toEqual({
fileId: 'aONcu8L82l1PdcT304Q8Za',
name: 'intern',
nodeId: '0:495',
projectName: 'intern_0_495',
});
});
it('should convert node-id hyphens to colons', () => {
const url = 'https://www.figma.com/design/abc123/MyProject?node-id=123-456';
const result = parseFigmaUrl(url);
expect(result.nodeId).toBe('123:456');
});
it('should handle URL-encoded characters in project name', () => {
const url = 'https://www.figma.com/design/abc123/My%20Project?node-id=0-1';
const result = parseFigmaUrl(url);
// encodeURI on already encoded string results in double encoding
expect(result.name).toBe('my%2520project');
});
it('should convert project name to lowercase', () => {
const url = 'https://www.figma.com/design/abc123/MyProject?node-id=0-1';
const result = parseFigmaUrl(url);
expect(result.name).toBe('myproject');
});
it('should truncate long project names to 20 characters', () => {
const longName = 'a'.repeat(30);
const url = `https://www.figma.com/design/abc123/${longName}?node-id=0-1`;
const result = parseFigmaUrl(url);
expect(result.name).toHaveLength(20);
expect(result.name).toBe('a'.repeat(20));
});
it('should handle empty project name slot', () => {
// When the project name slot is empty but pathParts length is still >= 3
const url = 'https://www.figma.com/design/abc123?node-id=0-1';
// This will throw because fileId extraction expects at least 3 path parts
expect(() => parseFigmaUrl(url)).toThrow('Invalid Figma URL');
});
it('should throw error for URL without fileId', () => {
const url = 'https://www.figma.com/design/?node-id=0-1';
expect(() => parseFigmaUrl(url)).toThrow('Invalid Figma URL');
});
it('should throw error for URL without node-id', () => {
const url = 'https://www.figma.com/design/abc123/MyProject';
expect(() => parseFigmaUrl(url)).toThrow('Invalid Figma URL');
});
it('should throw error for invalid URL format', () => {
const url = 'not-a-valid-url';
expect(() => parseFigmaUrl(url)).toThrow('Invalid Figma URL');
});
it('should handle file URLs', () => {
const url = 'https://www.figma.com/file/abc123/MyProject?node-id=0-1';
const result = parseFigmaUrl(url);
expect(result.fileId).toBe('abc123');
expect(result.nodeId).toBe('0:1');
});
it('should handle complex node-id with multiple hyphens', () => {
const url = 'https://www.figma.com/design/abc123/MyProject?node-id=123-456-789';
const result = parseFigmaUrl(url);
expect(result.nodeId).toBe('123:456:789');
});
it('should generate correct projectName', () => {
const url = 'https://www.figma.com/design/abc123/TestProject?node-id=1-2';
const result = parseFigmaUrl(url);
expect(result.projectName).toBe('testproject_1_2');
});
it('should handle URLs with additional query parameters', () => {
const url = 'https://www.figma.com/design/abc123/MyProject?node-id=0-1&mode=design&t=xyz123';
const result = parseFigmaUrl(url);
expect(result.fileId).toBe('abc123');
expect(result.nodeId).toBe('0:1');
expect(result.name).toBe('myproject');
});
it('should handle URLs with hash fragments', () => {
const url = 'https://www.figma.com/design/abc123/MyProject?node-id=0-1#section';
const result = parseFigmaUrl(url);
expect(result.fileId).toBe('abc123');
expect(result.nodeId).toBe('0:1');
});
it('should handle proto URLs', () => {
const url = 'https://www.figma.com/proto/abc123/MyProject?node-id=0-1';
const result = parseFigmaUrl(url);
expect(result.fileId).toBe('abc123');
expect(result.name).toBe('myproject');
});
});
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { workspaceManager } from '../../src/utils/workspace';
import { WorkspaceStructure } from '../../src/types/workspace-types';
describe('workspaceManager', () => {
let tempRoot: string;
beforeEach(() => {
// Reset singleton internal state between tests
(workspaceManager as any).path = null;
tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'coderio-ws-'));
});
afterEach(() => {
fs.rmSync(tempRoot, { recursive: true, force: true });
(workspaceManager as any).path = null;
});
it('initWorkspace should compute workspace structure and cache it', () => {
const ws1 = workspaceManager.initWorkspace('proj', tempRoot, 'my-app');
const ws2 = workspaceManager.initWorkspace('other', '/should-not-apply', 'other-app');
expect(ws2).toBe(ws1);
expect(ws1.root).toBe(path.resolve(tempRoot, 'coderio', 'proj'));
expect(ws1.app).toBe(path.join(ws1.root, 'my-app'));
expect(ws1.process).toBe(path.join(ws1.root, 'process'));
expect(ws1.debug).toBe(path.join(ws1.root, 'debug'));
expect(ws1.reports).toBe(path.join(ws1.root, 'reports.html'));
expect(ws1.db).toBe(path.join(ws1.root, 'checkpoint', 'coderio-cli.db'));
expect(ws1.checkpoint).toBe(path.join(ws1.root, 'checkpoint', 'checkpoint.json'));
});
it('resolveAppSrc should join app/src with subpath', () => {
const paths: WorkspaceStructure = {
root: '/r',
app: '/r/my-app',
process: '/r/process',
debug: '/r/debug',
reports: '/r/reports.html',
db: '/r/checkpoint/db.sqlite',
checkpoint: '/r/checkpoint/checkpoint.json',
};
expect(workspaceManager.resolveAppSrc(paths, 'components/Button')).toBe(path.join(paths.app, 'src', 'components/Button'));
});
it('resolveComponentPath should normalize common alias variants', () => {
expect(workspaceManager.resolveComponentPath('@/components/Button')).toBe('components/Button/index.tsx');
expect(workspaceManager.resolveComponentPath('@/src/components/Button')).toBe('components/Button/index.tsx');
expect(workspaceManager.resolveComponentPath('components/Button')).toBe('components/Button/index.tsx');
expect(workspaceManager.resolveComponentPath('components/Button.tsx')).toBe('components/Button.tsx');
expect(workspaceManager.resolveComponentPath('components/Button/index.tsx')).toBe('components/Button/index.tsx');
});
it('deleteWorkspace should delete all entries inside workspace root', () => {
const root = path.join(tempRoot, 'workspace');
fs.mkdirSync(root, { recursive: true });
fs.writeFileSync(path.join(root, 'a.txt'), 'a');
fs.mkdirSync(path.join(root, 'dir'));
fs.writeFileSync(path.join(root, 'dir', 'b.txt'), 'b');
const ws: WorkspaceStructure = {
root,
app: '',
process: '',
debug: '',
reports: '',
db: '',
checkpoint: '',
};
workspaceManager.deleteWorkspace(ws);
expect(fs.existsSync(root)).toBe(true);
expect(fs.readdirSync(root)).toHaveLength(0);
});
it('deleteWorkspace should preserve specified files while deleting others', () => {
const root = path.join(tempRoot, 'workspace-preserve');
fs.mkdirSync(root, { recursive: true });
fs.writeFileSync(path.join(root, 'a.txt'), 'a');
fs.writeFileSync(path.join(root, 'delete-me.txt'), 'delete');
fs.mkdirSync(path.join(root, 'checkpoint'), { recursive: true });
fs.writeFileSync(path.join(root, 'checkpoint', 'coderio-cli.db'), 'db');
fs.writeFileSync(path.join(root, 'checkpoint', 'checkpoint.json'), 'json');
fs.mkdirSync(path.join(root, 'process'), { recursive: true });
fs.writeFileSync(path.join(root, 'process', 'data.txt'), 'data');
const ws: WorkspaceStructure = {
root,
app: '',
process: '',
debug: '',
reports: '',
db: '',
checkpoint: '',
};
// Preserve only the database file
workspaceManager.deleteWorkspace(ws, ['checkpoint/coderio-cli.db']);
// Root should still exist
expect(fs.existsSync(root)).toBe(true);
// checkpoint directory should still exist (contains preserved file)
expect(fs.existsSync(path.join(root, 'checkpoint'))).toBe(true);
// Database file should be preserved
expect(fs.existsSync(path.join(root, 'checkpoint', 'coderio-cli.db'))).toBe(true);
expect(fs.readFileSync(path.join(root, 'checkpoint', 'coderio-cli.db'), 'utf8')).toBe('db');
// checkpoint.json should be deleted
expect(fs.existsSync(path.join(root, 'checkpoint', 'checkpoint.json'))).toBe(false);
// Other files and directories should be deleted
expect(fs.existsSync(path.join(root, 'a.txt'))).toBe(false);
expect(fs.existsSync(path.join(root, 'delete-me.txt'))).toBe(false);
expect(fs.existsSync(path.join(root, 'process'))).toBe(false);
});
});
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"lib": ["ES2022"],
"moduleResolution": "bundler",
"resolveJsonModule": true,
"allowJs": false,
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"strictPropertyInitialization": true,
"noImplicitThis": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"types": ["node"]
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "scripts", "src/tools/report-tool/template/**"]
}
import { defineConfig } from 'tsup';
import { readFileSync, cpSync, existsSync } from 'fs';
// Read version from package.json at build time
const pkg = JSON.parse(readFileSync('./package.json', 'utf8')) as { version: string };
export default defineConfig({
entry: {
index: 'src/index.ts',
cli: 'src/cli/index.ts',
},
// Use ESM format with proper CJS interop
format: ['esm'],
dts: true,
splitting: false,
sourcemap: true,
clean: true,
minify: false,
target: 'node18',
outDir: 'dist',
platform: 'node',
// All dependencies are external by default (automatic)
// Explicitly list only special cases for documentation purposes
external: [
/^@langchain\//, // Scoped package with many submodules
],
// Inject version at build time
define: {
__VERSION__: JSON.stringify(pkg.version),
},
// Copy report template to dist after build
onSuccess: async () => {
const templateSrc = 'src/tools/report-tool/template/dist';
const templateDest = 'dist/tools/report-tool/template';
if (existsSync(templateSrc)) {
console.log(`\nCopying report template from ${templateSrc} to ${templateDest}...`);
cpSync(templateSrc, templateDest, { recursive: true });
console.log('✓ Report template copied successfully');
} else {
console.warn(`⚠ Warning: Report template source not found at ${templateSrc}`);
console.warn(' Run "pnpm run build:report" first to build the template');
}
},
});
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true,
environment: 'node',
include: ['tests/**/*.test.ts'],
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html'],
include: [
// Only include files that have tests
'src/utils/naming.ts',
'src/utils/parser.ts',
'src/utils/url-parser.ts',
'src/utils/promise-pool.ts',
'src/utils/config.ts',
'src/utils/file.ts',
'src/utils/workspace.ts',
'src/utils/checkpoint.ts',
'src/utils/code-cache.ts',
'src/tools/style-tool/color.ts',
'src/tools/position-tool/utils/position-metrics.ts',
'src/nodes/validation/utils/tree/tree-traversal.ts',
],
exclude: [
'node_modules/',
'dist/',
'tests/',
'coderio/',
'src/tools/report-tool/template/',
'**/*.d.ts',
'**/*.config.ts',
'**/*.config.js',
'src/cli/',
'src/env.d.ts',
],
},
},
});
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!