Commit f67ea294 by liimin

refactor: 全仓库代码摸排与清理(死代码/服务端合并/前端合并/引擎模板裁剪)

P0 死代码与废弃状态:
- 删除未接线的服务端 health.ts、队列无调用方方法(pendingCount/activeCount)
- 删除前端未使用的 ui 组件(card/select/separator/tabs/textarea)
- 删除引擎未接线的 initial-agent 入口
- 移除 connection 中未使用的 lastEventAt 状态

P1 服务端公共逻辑合并:
- 新增 net.ts 统一 getLanIp/端口探测/进程清理,并修复 preview 端口清理正则 off-by-one(原 m[2] 取错导致从不杀进程)
- server.ts 抽出 readJsonBody,消除 5 处重复的 readBody+JSON.parse
- preview/project-runner 委托 net.ts,保留公开方法签名不变

P2 前端合并清理:
- 抽出 lib/jobActions.ts,合并 Workbench/History 重复的取消/删除/启动预览/清空交互
- SSE 统一到 onSSE,删除已废弃 subscribeSSE 与 SSEPayload
- PageHeader 不再重复渲染标题(由 Topbar 统一展示)
- Settings 合并两处重复的状态拉取 effect 为单一 effect
- 清理 Workbench 注释块(filterOptions/过滤 JSX/embedUrl span)与空 useMemo(visibleLogs)

P3 引擎 report-tool 模板裁剪:
- 删除 template 的 src/、构建配置、lockfile 等开发脚手架,运行时仅消费 template/dist/
- 经核查 template/src 未被引擎 TS 引用,零编译/运行影响;已重建引擎 dist 并重发 .d.ts

三端 tsc 均通过(engine/server/web),引擎 dist 已重建。
1 parent c8d03b08
Showing 32 changed files with 220 additions and 1424 deletions
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 { readFileSync } from 'node:fs'; import { readFileSync } from 'node:fs';
import { spawn, execSync } from 'node:child_process'; import { spawn } from 'node:child_process';
import path from 'node:path'; import path from 'node:path';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import type { Server } from 'node:http'; import type { Server } from 'node:http';
...@@ -8,6 +8,7 @@ import { JobQueue } from './queue'; ...@@ -8,6 +8,7 @@ import { JobQueue } from './queue';
import { PreviewManager } from './preview'; import { PreviewManager } from './preview';
import { ProjectRunner } from './project-runner'; import { ProjectRunner } from './project-runner';
import { createApp } from './server'; import { createApp } from './server';
import { killOtherListenersOnPort } from './net';
import { loadDotEnv, loadServerModelConfig, resolveServerOptions, loadProjectProfile } from './config'; import { loadDotEnv, loadServerModelConfig, resolveServerOptions, loadProjectProfile } from './config';
import { runJob } from './runner'; import { runJob } from './runner';
import { parseFigmaUrl, emptyProfile } from 'coderio'; import { parseFigmaUrl, emptyProfile } from 'coderio';
...@@ -29,35 +30,6 @@ function buildSyntheticProfile(stack: TechStack): ProjectProfile { ...@@ -29,35 +30,6 @@ function buildSyntheticProfile(stack: TechStack): ProjectProfile {
return base; return base;
} }
/**
* 杀掉占用指定端口、且不是自身 pid 的监听进程。
* 用于重启前清理陈旧/孤儿 server,避免新进程与它们抢同一端口
* (双绑 → 请求被随机转发到半死进程 → 前端报 500)。
*/
function killOtherListenersOnPort(port: number, selfPid: number): void {
let out = '';
try {
out = execSync('netstat -ano', { stdio: ['ignore', 'pipe', 'ignore'] }).toString();
} catch {
return;
}
const re = new RegExp(`:${port}\\s+\\S+\\s+LISTENING\\s+(\\d+)`, 'g');
let m: RegExpExecArray | null;
while ((m = re.exec(out)) !== null) {
const pid = parseInt(m[1], 10);
if (pid && pid !== selfPid) {
try {
execSync(`taskkill /pid ${pid} /f /t`);
// eslint-disable-next-line no-console
console.warn(` ⚠ 已清理端口 ${port} 上的陈旧监听进程 (pid ${pid})`);
} catch {
/* ignore */
}
}
}
}
function readPkgVersion(p: string): string { function readPkgVersion(p: string): string {
try { try {
return JSON.parse(readFileSync(p, 'utf8')).version ?? '0.0.0'; return JSON.parse(readFileSync(p, 'utf8')).version ?? '0.0.0';
......
import { execSync } from 'node:child_process';
import os from 'node:os';
/** LAN IPv4 address, or 'localhost' if none found. Shared by the preview / project runners. */
export 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';
}
/** Parse `netstat -ano` into a map of listening TCP ports -> owning PIDs. */
export function listListeningPorts(): Map<number, number[]> {
const map = new Map<number, number[]>();
try {
const out = execSync('netstat -ano', { stdio: ['ignore', 'pipe', 'ignore'] }).toString();
const re = /^\s*TCP\s+\S+:(\d+)\s+\S+\s+LISTENING\s+(\d+)/i;
for (const line of out.split('\n')) {
const m = line.match(re);
if (m) {
const port = parseInt(m[1], 10);
const pid = parseInt(m[2], 10);
const arr = map.get(port) ?? [];
arr.push(pid);
map.set(port, arr);
}
}
} catch {
/* ignore */
}
return map;
}
/** Kill the process tree (if any) listening on `port`. */
export function killProcessOnPort(port: number): void {
if (!port) return;
for (const pid of listListeningPorts().get(port) ?? []) {
try {
execSync(`taskkill /pid ${pid} /f /t`, { stdio: 'ignore' });
} catch {
/* ignore */
}
}
}
/** Kill a spawned process tree by PID (used to terminate the package-manager shell). */
export function killProcess(pid: number): void {
if (!pid) return;
try {
execSync(`taskkill /pid ${pid} /f /t`, { stdio: 'ignore' });
} catch {
/* ignore */
}
}
/** Kill every listener on `port` except `excludePid` (free a port before re-binding). */
export function killOtherListenersOnPort(port: number, excludePid: number): void {
for (const pid of listListeningPorts().get(port) ?? []) {
if (pid && pid !== excludePid) {
try {
execSync(`taskkill /pid ${pid} /f /t`, { stdio: 'ignore' });
// eslint-disable-next-line no-console
console.warn(` ⚠ 已清理端口 ${port} 上的陈旧监听进程 (pid ${pid})`);
} catch {
/* ignore */
}
}
}
}
/**
* Kill leaked dev servers on the Coderio-managed ranges:
* - 5180–5195 : preview service (`npm run dev -- --port 5180`)
* - 5200–6199 : validation internal dev server (`calculateHashPort`, base 5200)
* The front-end's 5173 is deliberately NOT covered (would kill the UI).
*/
export function killStalePreviewPorts(): void {
const re = /:5(?:18[0-9]|19[0-5]|[2-9]\d\d|6[01]\d\d)\s+\S+\s+LISTENING\s+(\d+)/g;
try {
const out = execSync('netstat -ano', { stdio: ['ignore', 'pipe', 'ignore'] }).toString();
const pids = new Set<string>();
let m: RegExpExecArray | null;
while ((m = re.exec(out))) pids.add(m[1]);
for (const pid of pids) {
try {
execSync(`taskkill /pid ${pid} /f /t`, { stdio: 'ignore' });
} catch {
/* ignore */
}
}
} catch {
/* ignore */
}
}
import { spawn, execSync, type ChildProcess } from 'node:child_process'; import { spawn, type ChildProcess } from 'node:child_process';
import net from 'node:net'; import net from 'node:net';
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { existsSync, appendFileSync, mkdirSync } from 'node:fs'; import { existsSync, appendFileSync, mkdirSync } from 'node:fs';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import type { PreviewState } from './types'; import type { PreviewState } from './types';
import {
getLanIp,
killProcess,
killProcessOnPort,
killStalePreviewPorts as killStalePreviewPortsImpl,
} from './net';
const __dirname = path.dirname(fileURLToPath(import.meta.url)); const __dirname = path.dirname(fileURLToPath(import.meta.url));
/** Captures the spawned npm/vite stdout+stderr so a silent failure is diagnosable. */ /** Captures the spawned npm/vite stdout+stderr so a silent failure is diagnosable. */
...@@ -31,58 +37,14 @@ export class PreviewManager { ...@@ -31,58 +37,14 @@ export class PreviewManager {
constructor(private readonly onChange: (s: PreviewState) => void) {} 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';
}
/** /**
* Kill whatever process is listening on a given TCP port. Needed because the * Kill any lingering dev servers on the Coderio-managed ranges
* dev server is launched via `npm install && npm run dev` inside a shell, so * (5180–5195 preview, 5200–6199 validation). 5173 (front-end) excluded.
* `this.proc` is the npm shell — killing it does NOT reliably terminate the * Delegates to the shared implementation in ./net (which also fixes the
* grandchild `vite` process, which would otherwise leak and occupy the port. * original off-by-one capture-group bug).
*/
private killPort(port: number): void {
if (!port) return;
try {
const out = execSync('netstat -ano', { stdio: ['ignore', 'pipe', 'ignore'] }).toString();
const m = out.match(new RegExp(`:${port}\\s+\\S+\\s+LISTENING\\s+(\\d+)`));
if (m?.[1]) execSync(`taskkill /pid ${m[1]} /f /t`, { stdio: 'ignore' });
} catch {
/* ignore */
}
}
/**
* Kill any lingering dev servers on the Coderio-managed ranges:
* - 5180–5195 : preview service (`npm run dev -- --port 5180`)
* - 5200–6199 : validation internal dev server (`calculateHashPort`, base 5200)
* The front-end's 5173 is deliberately NOT covered (would kill the UI).
* Public so the server can call it at boot and before each generation to
* reclaim dev servers detached from a previous backend/generation process.
*/ */
killStalePreviewPorts(): void { killStalePreviewPorts(): void {
try { killStalePreviewPortsImpl();
const out = execSync('netstat -ano', { stdio: ['ignore', 'pipe', 'ignore'] }).toString();
const re = /:5(?:18[0-9]|19[0-5]|[2-9]\d\d|6[01]\d\d)\s+\S+\s+LISTENING\s+(\d+)/g;
const pids = new Set<string>();
let m: RegExpExecArray | null;
while ((m = re.exec(out))) pids.add(m[2]);
for (const pid of pids) {
try {
execSync(`taskkill /pid ${pid} /f /t`, { stdio: 'ignore' });
} catch {
/* ignore */
}
}
} catch {
/* ignore */
}
} }
start(explicitAppPath?: string | null): { ok: boolean; error?: string } { start(explicitAppPath?: string | null): { ok: boolean; error?: string } {
...@@ -173,7 +135,7 @@ export class PreviewManager { ...@@ -173,7 +135,7 @@ export class PreviewManager {
connected = true; connected = true;
sock.destroy(); sock.destroy();
clearInterval(probe); clearInterval(probe);
const ip = this.getLanIp(); const ip = getLanIp();
this.state.localUrl = `http://localhost:${p}/`; this.state.localUrl = `http://localhost:${p}/`;
this.state.url = `http://${ip}:${p}/`; this.state.url = `http://${ip}:${p}/`;
this.state.port = p; this.state.port = p;
...@@ -207,7 +169,7 @@ export class PreviewManager { ...@@ -207,7 +169,7 @@ export class PreviewManager {
if (this.proc?.pid) { if (this.proc?.pid) {
try { try {
if (os.platform() === 'win32') { if (os.platform() === 'win32') {
execSync(`taskkill /pid ${this.proc.pid} /f /t`, { stdio: 'ignore' }); killProcess(this.proc.pid);
} else { } else {
process.kill(-this.proc.pid, 'SIGKILL'); process.kill(-this.proc.pid, 'SIGKILL');
} }
...@@ -217,7 +179,7 @@ export class PreviewManager { ...@@ -217,7 +179,7 @@ export class PreviewManager {
} }
// Also kill the grandchild vite by port (the npm-shell kill above may not // Also kill the grandchild vite by port (the npm-shell kill above may not
// reach it), so the port is reliably freed. // reach it), so the port is reliably freed.
this.killPort(this.state.port ?? 0); killProcessOnPort(this.state.port ?? 0);
this.proc = null; this.proc = null;
this.state = { this.state = {
running: false, running: false,
......
...@@ -5,6 +5,7 @@ import fs from 'node:fs'; ...@@ -5,6 +5,7 @@ import fs from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import type { ProjectManager, ProjectRunState } from './types'; import type { ProjectManager, ProjectRunState } from './types';
import { getLanIp, killProcess, killProcessOnPort, listListeningPorts as listListeningPortsImpl } from './net';
const __dirname = path.dirname(fileURLToPath(import.meta.url)); const __dirname = path.dirname(fileURLToPath(import.meta.url));
/** /**
...@@ -42,34 +43,6 @@ export class ProjectRunner { ...@@ -42,34 +43,6 @@ export class ProjectRunner {
constructor(private readonly onChange: (s: ProjectRunState) => void) {} constructor(private readonly onChange: (s: ProjectRunState) => 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';
}
/**
* Kill whatever process is listening on a TCP port. The dev server is
* launched via a shell (`<mgr> run <script>`), so `this.proc` is the
* package-manager shell — killing it does NOT reliably terminate the
* grandchild vite/next process, which would otherwise keep occupying the
* port.
*/
private killPort(port: number): void {
if (!port) return;
try {
const out = execSync('netstat -ano', { stdio: ['ignore', 'pipe', 'ignore'] }).toString();
const m = out.match(new RegExp(`:${port}\\s+\\S+\\s+LISTENING\\s+(\\d+)`));
if (m?.[1]) execSync(`taskkill /pid ${m[1]} /f /t`, { stdio: 'ignore' });
} catch {
/* ignore */
}
}
static pickScript(scripts: Scripts | undefined): string | null { static pickScript(scripts: Scripts | undefined): string | null {
if (!scripts) return null; if (!scripts) return null;
// Return the *script name* (e.g. "dev"), not its command value — the // Return the *script name* (e.g. "dev"), not its command value — the
...@@ -132,7 +105,7 @@ export class ProjectRunner { ...@@ -132,7 +105,7 @@ export class ProjectRunner {
// NOT depend on it (it uses netstat + the process tree instead). // NOT depend on it (it uses netstat + the process tree instead).
// Snapshot pre-existing listening ports so the orchestration // Snapshot pre-existing listening ports so the orchestration
// server's own port is never mistaken for the dev server. // server's own port is never mistaken for the dev server.
this.baselinePorts = this.listListeningPorts(); this.baselinePorts = new Set(listListeningPortsImpl().keys());
const logStream = fs.createWriteStream(RUN_LOG, { flags: 'a' }); const logStream = fs.createWriteStream(RUN_LOG, { flags: 'a' });
this.logStream = logStream; this.logStream = logStream;
const child = spawn(`${manager} run ${script}`, { const child = spawn(`${manager} run ${script}`, {
...@@ -197,7 +170,7 @@ export class ProjectRunner { ...@@ -197,7 +170,7 @@ export class ProjectRunner {
settled = true; settled = true;
sock.destroy(); sock.destroy();
clearInterval(timer); clearInterval(timer);
const ip = this.getLanIp(); const ip = getLanIp();
this.state = { this.state = {
...this.state, ...this.state,
port, port,
...@@ -268,48 +241,20 @@ export class ProjectRunner { ...@@ -268,48 +241,20 @@ export class ProjectRunner {
return [...result]; return [...result];
} }
/** All currently LISTENING TCP ports (regardless of owner). */
private listListeningPorts(): Set<number> {
const ports = new Set<number>();
let net = '';
try {
net = execSync('netstat -ano', { stdio: ['ignore', 'pipe', 'ignore'] }).toString();
} catch {
return ports;
}
for (const line of net.split('\n')) {
const m = line.match(/^\s*TCP\s+\S+:(\d+)\s+\S+\s+LISTENING\s+(\d+)/i);
if (m) ports.add(parseInt(m[1], 10));
}
return ports;
}
/** /**
* Finds the dev server's listening port by scanning `netstat` for a * Finds the dev server's listening port by scanning the OS socket table for
* LISTENING socket owned by any process in the spawned tree. npm buffers * a LISTENING socket owned by any process in the spawned tree. npm buffers
* its stdout (so the "Local:" line is unavailable while the server runs), * its stdout (so the "Local:" line is unavailable while the server runs),
* hence we look at the OS socket table instead. Ports that were already * hence we look at `netstat` instead. Ports that were already listening
* listening before this run started (`baselinePorts`) are ignored, so the * before this run started (`baselinePorts`) are ignored, so the
* orchestration server's own port (and any other pre-existing service) can * orchestration server's own port (and any other pre-existing service) can
* never be mistaken for the dev server. * never be mistaken for the dev server.
*/ */
private findDevServerPort(rootPid: number): number | null { private findDevServerPort(rootPid: number): number | null {
const pids = new Set(this.getDescendantPids(rootPid)); const pids = new Set(this.getDescendantPids(rootPid));
let net = ''; for (const [port, owners] of listListeningPortsImpl()) {
try {
net = execSync('netstat -ano', { stdio: ['ignore', 'pipe', 'ignore'] }).toString();
} catch {
return null;
}
for (const line of net.split('\n')) {
const m = line.match(
/^\s*(TCP|UDP)\s+\S+:(\d+)\s+\S+\s+(LISTENING|CLOSE_WAIT|ESTABLISHED)\s+(\d+)/i,
);
if (!m) continue;
const pid = parseInt(m[4], 10);
const port = parseInt(m[2], 10);
if (this.baselinePorts.has(port)) continue; if (this.baselinePorts.has(port)) continue;
if (pids.has(pid) && m[3].toUpperCase() === 'LISTENING') return port; if (owners.some((pid) => pids.has(pid))) return port;
} }
return null; return null;
} }
...@@ -318,7 +263,7 @@ export class ProjectRunner { ...@@ -318,7 +263,7 @@ export class ProjectRunner {
if (this.proc?.pid) { if (this.proc?.pid) {
try { try {
if (os.platform() === 'win32') { if (os.platform() === 'win32') {
execSync(`taskkill /pid ${this.proc.pid} /f /t`, { stdio: 'ignore' }); killProcess(this.proc.pid);
} else { } else {
process.kill(-this.proc.pid, 'SIGKILL'); process.kill(-this.proc.pid, 'SIGKILL');
} }
...@@ -328,7 +273,7 @@ export class ProjectRunner { ...@@ -328,7 +273,7 @@ export class ProjectRunner {
} }
// Also kill the grandchild dev server by port (the shell kill above may // Also kill the grandchild dev server by port (the shell kill above may
// not reach it), reliably freeing the port. // not reach it), reliably freeing the port.
this.killPort(this.state.port ?? 0); killProcessOnPort(this.state.port ?? 0);
this.proc = null; this.proc = null;
try { try {
this.logStream?.end(); this.logStream?.end();
......
...@@ -114,12 +114,4 @@ export class JobQueue { ...@@ -114,12 +114,4 @@ export class JobQueue {
const i = this.queue.indexOf(id); const i = this.queue.indexOf(id);
return i >= 0 ? i + 1 : 0; return i >= 0 ? i + 1 : 0;
} }
pendingCount(): number {
return this.queue.length;
}
activeCount(): number {
return this.active.size;
}
} }
...@@ -201,6 +201,10 @@ export function createApp(deps: ServerDeps): AppHandle { ...@@ -201,6 +201,10 @@ export function createApp(deps: ServerDeps): AppHandle {
req.on('error', reject); req.on('error', reject);
}); });
/** Read the request body and parse it as JSON (returns `{}` for empty bodies). */
const readJsonBody = async <T = Record<string, unknown>>(req: IncomingMessage): Promise<T> =>
JSON.parse((await readBody(req)) || '{}') as T;
const server = createServer(async (req, res) => { const server = createServer(async (req, res) => {
try { try {
const url = new URL(req.url ?? '/', `http://localhost:${opts.port}`); const url = new URL(req.url ?? '/', `http://localhost:${opts.port}`);
...@@ -311,10 +315,9 @@ export function createApp(deps: ServerDeps): AppHandle { ...@@ -311,10 +315,9 @@ export function createApp(deps: ServerDeps): AppHandle {
// whole profile; the engine picks it up on the next job (it reads // whole profile; the engine picks it up on the next job (it reads
// the file per run, so no restart is required). // the file per run, so no restart is required).
if (req.method === 'PUT' && url.pathname === '/api/project-profile') { if (req.method === 'PUT' && url.pathname === '/api/project-profile') {
const raw = await readBody(req);
let incoming: unknown; let incoming: unknown;
try { try {
incoming = JSON.parse(raw || '{}'); incoming = await readJsonBody(req);
} catch { } catch {
sendJson(res, 400, { error: 'Invalid JSON body' }); sendJson(res, 400, { error: 'Invalid JSON body' });
return; return;
...@@ -339,10 +342,9 @@ export function createApp(deps: ServerDeps): AppHandle { ...@@ -339,10 +342,9 @@ export function createApp(deps: ServerDeps): AppHandle {
// the canonical profile file — it just returns a draft for the UI // the canonical profile file — it just returns a draft for the UI
// to review and (optionally) persist via PUT. // to review and (optionally) persist via PUT.
if (req.method === 'POST' && url.pathname === '/api/project-profile/scan') { if (req.method === 'POST' && url.pathname === '/api/project-profile/scan') {
const raw = await readBody(req);
let body: { rootDir?: string } = {}; let body: { rootDir?: string } = {};
try { try {
body = JSON.parse(raw || '{}'); body = await readJsonBody<{ rootDir?: string }>(req);
} catch { } catch {
sendJson(res, 400, { error: 'Invalid JSON body' }); sendJson(res, 400, { error: 'Invalid JSON body' });
return; return;
...@@ -405,10 +407,9 @@ export function createApp(deps: ServerDeps): AppHandle { ...@@ -405,10 +407,9 @@ export function createApp(deps: ServerDeps): AppHandle {
// ---- POST /api/generate ---- // ---- POST /api/generate ----
if (req.method === 'POST' && url.pathname === '/api/generate') { if (req.method === 'POST' && url.pathname === '/api/generate') {
const raw = await readBody(req);
let body: GenerateRequest; let body: GenerateRequest;
try { try {
body = JSON.parse(raw || '{}'); body = await readJsonBody<GenerateRequest>(req);
} catch { } catch {
sendJson(res, 400, { error: 'Invalid JSON body' }); sendJson(res, 400, { error: 'Invalid JSON body' });
return; return;
...@@ -541,10 +542,9 @@ export function createApp(deps: ServerDeps): AppHandle { ...@@ -541,10 +542,9 @@ export function createApp(deps: ServerDeps): AppHandle {
// ---- POST /api/preview (start) ---- // ---- POST /api/preview (start) ----
if (req.method === 'POST' && url.pathname === '/api/preview') { if (req.method === 'POST' && url.pathname === '/api/preview') {
const raw = await readBody(req);
let body: { appPath?: string } = {}; let body: { appPath?: string } = {};
try { try {
body = JSON.parse(raw || '{}'); body = await readJsonBody<{ appPath?: string }>(req);
} catch { } catch {
/* ignore */ /* ignore */
} }
...@@ -600,10 +600,9 @@ export function createApp(deps: ServerDeps): AppHandle { ...@@ -600,10 +600,9 @@ export function createApp(deps: ServerDeps): AppHandle {
// ---- POST /api/project/run (launch target project dev server) ---- // ---- POST /api/project/run (launch target project dev server) ----
if (req.method === 'POST' && url.pathname === '/api/project/run') { if (req.method === 'POST' && url.pathname === '/api/project/run') {
const raw = await readBody(req);
let body: { dir?: string } = {}; let body: { dir?: string } = {};
try { try {
body = JSON.parse(raw || '{}'); body = await readJsonBody<{ dir?: string }>(req);
} catch { } catch {
/* ignore */ /* ignore */
} }
......
...@@ -3,13 +3,11 @@ import type { LucideIcon } from 'lucide-react'; ...@@ -3,13 +3,11 @@ import type { LucideIcon } from 'lucide-react';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
export function PageHeader({ export function PageHeader({
title,
description, description,
icon: Icon, icon: Icon,
actions, actions,
className, className,
}: { }: {
title: string;
description?: string; description?: string;
icon?: LucideIcon; icon?: LucideIcon;
actions?: ReactNode; actions?: ReactNode;
...@@ -28,15 +26,12 @@ export function PageHeader({ ...@@ -28,15 +26,12 @@ export function PageHeader({
<Icon className="h-5 w-5" /> <Icon className="h-5 w-5" />
</div> </div>
)} )}
<div>
<h2 className="text-xl font-semibold tracking-tight">{title}</h2>
{description && ( {description && (
<p className="mt-1 max-w-2xl text-sm text-muted-foreground"> <p className="max-w-2xl text-sm text-muted-foreground">
{description} {description}
</p> </p>
)} )}
</div> </div>
</div>
{actions && <div className="flex items-center gap-2">{actions}</div>} {actions && <div className="flex items-center gap-2">{actions}</div>}
</div> </div>
); );
......
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 * 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 * 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 };
...@@ -173,11 +173,6 @@ export async function checkBackendHealth(): Promise<boolean> { ...@@ -173,11 +173,6 @@ export async function checkBackendHealth(): Promise<boolean> {
export type SSEEventName = 'log' | 'jobs' | 'preview' | 'projectRun' | 'system' | string; export type SSEEventName = 'log' | 'jobs' | 'preview' | 'projectRun' | 'system' | string;
export interface SSEPayload {
event: SSEEventName;
data: unknown;
}
// 全局单例 SSE 连接:整个应用只建立一条 /api/stream,所有组件通过 onSSE 订阅 // 全局单例 SSE 连接:整个应用只建立一条 /api/stream,所有组件通过 onSSE 订阅
// 特定事件。避免每个组件各开一条连接、也彻底消除「前端用 setInterval 轮询后端状态」的刷屏。 // 特定事件。避免每个组件各开一条连接、也彻底消除「前端用 setInterval 轮询后端状态」的刷屏。
// 后端在状态变化时通过 hub.broadcast 推送(jobs / preview / projectRun 等),SSE 连接建立时 // 后端在状态变化时通过 hub.broadcast 推送(jobs / preview / projectRun 等),SSE 连接建立时
...@@ -235,16 +230,3 @@ export function onSSEStatus( ...@@ -235,16 +230,3 @@ export function onSSEStatus(
} }
export type { LogEntry, Job }; export type { LogEntry, Job };
/**
* @deprecated 兼容旧用法:把全部事件汇聚到一个回调。内部复用全局单例 SSE 连接,
* 不另开连接。新代码请直接用 `onSSE(event, handler)` 按事件订阅。
*/
export function subscribeSSE(
onMessage: (msg: SSEPayload) => void,
_onError?: (e: Event) => void,
): () => void {
ensureSSE();
const unsubs = SSE_EVENTS.map((ev) => onSSE(ev, (data) => onMessage({ event: ev, data })));
return () => unsubs.forEach((u) => u());
}
...@@ -10,12 +10,10 @@ import { onSSEStatus } from './api'; ...@@ -10,12 +10,10 @@ import { onSSEStatus } from './api';
interface ConnectionContextValue { interface ConnectionContextValue {
connected: boolean; connected: boolean;
lastEventAt: number | null;
} }
const ConnectionContext = createContext<ConnectionContextValue>({ const ConnectionContext = createContext<ConnectionContextValue>({
connected: false, connected: false,
lastEventAt: null,
}); });
/** /**
...@@ -24,7 +22,6 @@ const ConnectionContext = createContext<ConnectionContextValue>({ ...@@ -24,7 +22,6 @@ const ConnectionContext = createContext<ConnectionContextValue>({
*/ */
export function ConnectionProvider({ children }: { children: ReactNode }) { export function ConnectionProvider({ children }: { children: ReactNode }) {
const [connected, setConnected] = useState(false); const [connected, setConnected] = useState(false);
const [lastEventAt, setLastEventAt] = useState<number | null>(null);
const aliveRef = useRef(true); const aliveRef = useRef(true);
useEffect(() => { useEffect(() => {
...@@ -33,7 +30,6 @@ export function ConnectionProvider({ children }: { children: ReactNode }) { ...@@ -33,7 +30,6 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
() => { () => {
if (!aliveRef.current) return; if (!aliveRef.current) return;
setConnected(true); setConnected(true);
setLastEventAt(Date.now());
}, },
() => { () => {
if (!aliveRef.current) return; if (!aliveRef.current) return;
...@@ -47,7 +43,7 @@ export function ConnectionProvider({ children }: { children: ReactNode }) { ...@@ -47,7 +43,7 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
}, []); }, []);
return ( return (
<ConnectionContext.Provider value={{ connected, lastEventAt }}> <ConnectionContext.Provider value={{ connected }}>
{children} {children}
</ConnectionContext.Provider> </ConnectionContext.Provider>
); );
......
import { toast } from 'sonner';
import { api } from '@/lib/api';
// 任务相关交互(结束 / 删除 / 启动预览 / 清空)在 Workbench 与 History 间完全重复,
// 抽到此处统一维护,避免两处文案 / 行为漂移。
export async function cancelJob(id: string): Promise<void> {
if (!confirm('确定要结束该生成任务吗?子进程将被终止。')) return;
try {
const r = await api.cancelJob(id);
if (r.ok) toast.success('已发送结束指令,任务即将中止');
else toast.error('结束失败', { description: '任务不存在或已结束' });
} catch (e) {
toast.error('结束失败', { description: e instanceof Error ? e.message : String(e) });
}
}
export async function deleteJob(id: string): Promise<void> {
if (!confirm('确定删除该任务记录吗?此操作不可撤销。')) return;
try {
const r = await api.deleteJob(id);
if (r.ok) toast.success('已删除任务记录');
else toast.error('删除失败', { description: '任务不存在' });
} catch (e) {
toast.error('删除失败', { description: e instanceof Error ? e.message : String(e) });
}
}
/**
* 启动预览(针对当前全局预览产物)。successMsg 允许调用方定制成功提示,
* Workbench 需要连带管理 busy 态,故返回结果由调用方决定;History 直接传入文案即可。
*/
export async function startPreview(
successMsg = '已启动预览',
): Promise<{ ok: boolean; error?: string } | null> {
try {
const r = await api.startPreview();
if (r.ok) toast.success(successMsg);
else toast.error('启动预览失败', { description: r.error });
return r;
} catch (e) {
toast.error('启动预览失败', { description: e instanceof Error ? e.message : String(e) });
return null;
}
}
export async function clearAllJobs(): Promise<void> {
if (!confirm('确定清空全部任务记录吗?进行中的任务会被中止,此操作不可撤销。')) return;
try {
const r = await api.clearJobs();
if (r.ok) toast.success(`已清空 ${r.count} 条记录`);
else toast.error('清空失败');
} catch (e) {
toast.error('清空失败', { description: e instanceof Error ? e.message : String(e) });
}
}
...@@ -12,7 +12,8 @@ import { ...@@ -12,7 +12,8 @@ import {
StopCircle, StopCircle,
Trash2, Trash2,
} from 'lucide-react'; } from 'lucide-react';
import { api, subscribeSSE } from '@/lib/api'; import { api, onSSE } from '@/lib/api';
import { cancelJob, deleteJob, startPreview as startPreviewAction, clearAllJobs } from '@/lib/jobActions';
import type { Job } from '@/lib/types'; import type { Job } from '@/lib/types';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
...@@ -38,28 +39,6 @@ function duration(j: Job) { ...@@ -38,28 +39,6 @@ function duration(j: Job) {
return `${Math.floor(s / 60)}m${s % 60}s`; return `${Math.floor(s / 60)}m${s % 60}s`;
} }
async function handleDelete(id: string) {
if (!confirm('确定删除该任务记录吗?此操作不可撤销。')) return;
try {
const r = await api.deleteJob(id);
if (r.ok) toast.success('已删除任务记录');
else toast.error('删除失败', { description: '任务不存在' });
} catch (e) {
toast.error('删除失败', { description: e instanceof Error ? e.message : String(e) });
}
}
async function clearAll() {
if (!confirm('确定清空全部历史记录吗?此操作不可撤销。')) return;
try {
const r = await api.clearJobs();
if (r.ok) toast.success(`已清空 ${r.count} 条记录`);
else toast.error('清空失败');
} catch (e) {
toast.error('清空失败', { description: e instanceof Error ? e.message : String(e) });
}
}
export default function History() { export default function History() {
const [jobs, setJobs] = useState<Job[]>([]); const [jobs, setJobs] = useState<Job[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
...@@ -79,10 +58,7 @@ export default function History() { ...@@ -79,10 +58,7 @@ export default function History() {
useEffect(() => { useEffect(() => {
refresh(); refresh();
const unsub = subscribeSSE((msg) => { return onSSE('jobs', (d) => setJobs(d as Job[]));
if (msg.event === 'jobs') setJobs(msg.data as Job[]);
});
return unsub;
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, []); }, []);
...@@ -99,14 +75,13 @@ export default function History() { ...@@ -99,14 +75,13 @@ export default function History() {
<div className="p-6"> <div className="p-6">
<PageHeader <PageHeader
icon={HistoryIcon} icon={HistoryIcon}
title="历史任务"
description="所有生成任务持久化记录,跨服务重启不丢失。" description="所有生成任务持久化记录,跨服务重启不丢失。"
actions={ actions={
<> <>
<Button <Button
variant="outline" variant="outline"
size="sm" size="sm"
onClick={clearAll} onClick={() => { void clearAllJobs(); }}
disabled={loading || jobs.length === 0} disabled={loading || jobs.length === 0}
className="text-muted-foreground hover:text-rose-400" className="text-muted-foreground hover:text-rose-400"
> >
...@@ -198,18 +173,7 @@ export default function History() { ...@@ -198,18 +173,7 @@ export default function History() {
<div className="flex justify-end gap-1.5 opacity-0 transition-opacity group-hover:opacity-100"> <div className="flex justify-end gap-1.5 opacity-0 transition-opacity group-hover:opacity-100">
{j.status === 'running' || j.status === 'queued' ? ( {j.status === 'running' || j.status === 'queued' ? (
<button <button
onClick={async () => { onClick={() => { void cancelJob(j.id); }}
if (!confirm('确定要结束该生成任务吗?')) return;
try {
const r = await api.cancelJob(j.id);
if (r.ok) toast.success('已发送结束指令,任务即将中止');
else toast.error('结束失败', { description: '任务不存在或已结束' });
} catch (e) {
toast.error('结束失败', {
description: e instanceof Error ? e.message : String(e),
});
}
}}
className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-background hover:text-rose-400" className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-background hover:text-rose-400"
title="结束任务" title="结束任务"
> >
...@@ -226,18 +190,14 @@ export default function History() { ...@@ -226,18 +190,14 @@ export default function History() {
</a> </a>
) : null} ) : null}
<button <button
onClick={async () => { onClick={() => { void startPreviewAction('已为该任务产物启动预览'); }}
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" className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-background hover:text-foreground"
title="在预览中打开" title="在预览中打开"
> >
<Eye className="h-4 w-4" /> <Eye className="h-4 w-4" />
</button> </button>
<button <button
onClick={() => handleDelete(j.id)} onClick={() => { void deleteJob(j.id); }}
className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-background hover:text-rose-400" className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-background hover:text-rose-400"
title="删除记录" title="删除记录"
> >
......
...@@ -200,7 +200,7 @@ export default function Settings() { ...@@ -200,7 +200,7 @@ export default function Settings() {
}, []); }, []);
// 拉取系统状态快照:初次进入拉一次,后端(重)连接后(connected false→true)再拉一次。 // 拉取系统状态快照:初次进入拉一次,后端(重)连接后(connected false→true)再拉一次。
// 完全事件驱动,不再 setInterval 轮询。 // 完全事件驱动,不再 setInterval 轮询;单一 effect 同时覆盖「挂载」与「(重)连接」两种时机。
const refresh = useCallback(async () => { const refresh = useCallback(async () => {
try { try {
const s = await api.getStatus(); const s = await api.getStatus();
...@@ -212,17 +212,8 @@ export default function Settings() { ...@@ -212,17 +212,8 @@ export default function Settings() {
}, []); }, []);
useEffect(() => { useEffect(() => {
if (!connected) return;
let alive = true;
api.getStatus().then((s) => { if (alive) setStatus(s); }).catch(() => {});
return () => {
alive = false;
};
}, [connected]);
useEffect(() => {
void refresh(); void refresh();
}, [refresh]); }, [refresh, connected]);
const runAction = useCallback( const runAction = useCallback(
async (key: string, fn: () => Promise<unknown>, okMsg: string) => { async (key: string, fn: () => Promise<unknown>, okMsg: string) => {
...@@ -286,7 +277,6 @@ export default function Settings() { ...@@ -286,7 +277,6 @@ export default function Settings() {
<div className="mx-auto max-w-5xl p-6"> <div className="mx-auto max-w-5xl p-6">
<PageHeader <PageHeader
icon={SettingsIcon} icon={SettingsIcon}
title="设置"
description="凭据、模型与服务信息统一管理:以下仅展示配置状态,密钥由服务端保管,前端不接触任何凭证。" description="凭据、模型与服务信息统一管理:以下仅展示配置状态,密钥由服务端保管,前端不接触任何凭证。"
/> />
......
...@@ -19,7 +19,8 @@ import { ...@@ -19,7 +19,8 @@ import {
Layers, Layers,
Boxes, Boxes,
} from 'lucide-react'; } from 'lucide-react';
import { api, subscribeSSE, checkBackendHealth } from '@/lib/api'; import { api, onSSE, checkBackendHealth } from '@/lib/api';
import { cancelJob, deleteJob, startPreview as startPreviewAction, clearAllJobs } from '@/lib/jobActions';
import type { Job, LogEntry, LogLevel, PreviewState, ProjectRunState, ValidationMode, GenerationTarget, GenerationTargetMode, ProjectProfile, TechStack } from '@/lib/types'; import type { Job, LogEntry, LogLevel, PreviewState, ProjectRunState, ValidationMode, GenerationTarget, GenerationTargetMode, ProjectProfile, TechStack } from '@/lib/types';
import { STACK_PRESETS } from '@/components/project/profile-presets'; import { STACK_PRESETS } from '@/components/project/profile-presets';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
...@@ -48,13 +49,6 @@ const levelTag: Record<LogLevel, string> = { ...@@ -48,13 +49,6 @@ const levelTag: Record<LogLevel, string> = {
test: 'TEST', test: 'TEST',
log: 'LOG', log: 'LOG',
}; };
// const filterOptions: { key: LogLevel | 'all'; label: string }[] = [
// { key: 'all', label: '全部' },
// { key: 'info', label: '信息' },
// { key: 'success', label: '成功' },
// { key: 'warn', label: '警告' },
// { key: 'error', label: '错误' },
// ];
/* ---------------- embed url helpers ---------------- */ /* ---------------- embed url helpers ---------------- */
const SCHEME_RE = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//; const SCHEME_RE = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//;
...@@ -84,27 +78,6 @@ const targetModes: { key: GenerationTargetMode; label: string; hint: string }[] ...@@ -84,27 +78,6 @@ const targetModes: { key: GenerationTargetMode; label: string; hint: string }[]
{ key: 'modify-slot', label: '修改区域', hint: '修改已有页面的指定区域 / 插槽' }, { key: 'modify-slot', label: '修改区域', hint: '修改已有页面的指定区域 / 插槽' },
]; ];
async function handleCancel(id: string) {
if (!confirm('确定要结束该生成任务吗?子进程将被终止。')) return;
try {
const r = await api.cancelJob(id);
if (r.ok) toast.success('已发送结束指令,任务即将中止');
else toast.error('结束失败', { description: '任务不存在或已结束' });
} catch (e) {
toast.error('结束失败', { description: e instanceof Error ? e.message : String(e) });
}
}
async function handleDelete(id: string) {
if (!confirm('确定删除该任务记录吗?此操作不可撤销。')) return;
try {
const r = await api.deleteJob(id);
if (r.ok) toast.success('已删除任务记录');
else toast.error('删除失败', { description: '任务不存在' });
} catch (e) {
toast.error('删除失败', { description: e instanceof Error ? e.message : String(e) });
}
}
export default function Workbench() { export default function Workbench() {
/* ----- generate form ----- */ /* ----- generate form ----- */
const [figmaUrl, setFigmaUrl] = useState(''); const [figmaUrl, setFigmaUrl] = useState('');
...@@ -185,7 +158,6 @@ export default function Workbench() { ...@@ -185,7 +158,6 @@ export default function Workbench() {
/* ----- logs ----- */ /* ----- logs ----- */
const [logs, setLogs] = useState<LogEntry[]>([]); const [logs, setLogs] = useState<LogEntry[]>([]);
// const [filter, setFilter] = useState<LogLevel | 'all'>('all');
const [autoScroll, setAutoScroll] = useState(true); const [autoScroll, setAutoScroll] = useState(true);
const logRef = useRef<HTMLDivElement>(null); const logRef = useRef<HTMLDivElement>(null);
const autoRef = useRef(autoScroll); const autoRef = useRef(autoScroll);
...@@ -208,29 +180,23 @@ export default function Workbench() { ...@@ -208,29 +180,23 @@ export default function Workbench() {
api.getProjectRun().then(setProjectRun).catch(() => {}); api.getProjectRun().then(setProjectRun).catch(() => {});
api.getProjectProfile().then((r) => setProjectProfile(r.profile ?? null)).catch(() => {}); api.getProjectProfile().then((r) => setProjectProfile(r.profile ?? null)).catch(() => {});
const unsub = subscribeSSE((msg) => { const unsubLog = onSSE('log', (d) => setLogs((prev) => [...prev, d as LogEntry].slice(-2000)));
if (msg.event === 'log') { const unsubJobs = onSSE('jobs', (d) => setJobs(d as Job[]));
setLogs((prev) => [...prev, msg.data as LogEntry].slice(-2000)); const unsubPreview = onSSE('preview', (d) => setState(d as PreviewState));
} else if (msg.event === 'jobs') { const unsubProjRun = onSSE('projectRun', (d) => setProjectRun(d as ProjectRunState));
setJobs(msg.data as Job[]); return () => {
} else if (msg.event === 'preview') { unsubLog();
setState(msg.data as PreviewState); unsubJobs();
} else if (msg.event === 'projectRun') { unsubPreview();
setProjectRun(msg.data as ProjectRunState); unsubProjRun();
} };
});
return unsub;
}, []); }, []);
const visibleLogs = useMemo(
() => logs,
[logs],
);
useEffect(() => { useEffect(() => {
if (autoScroll && logRef.current) { if (autoScroll && logRef.current) {
logRef.current.scrollTop = logRef.current.scrollHeight; logRef.current.scrollTop = logRef.current.scrollHeight;
} }
}, [visibleLogs, autoScroll]); }, [logs, autoScroll]);
const activeCount = useMemo( const activeCount = useMemo(
() => jobs.filter((j) => j.status === 'running' || j.status === 'queued').length, () => jobs.filter((j) => j.status === 'running' || j.status === 'queued').length,
...@@ -240,11 +206,7 @@ export default function Workbench() { ...@@ -240,11 +206,7 @@ export default function Workbench() {
const startPreview = async () => { const startPreview = async () => {
setBusy(true); setBusy(true);
try { try {
const r = await api.startPreview(); await startPreviewAction('预览服务启动中…');
if (!r.ok) toast.error('启动预览失败', { description: r.error });
else toast.success('预览服务启动中…');
} catch (e) {
toast.error('启动预览失败', { description: e instanceof Error ? e.message : String(e) });
} finally { } finally {
setBusy(false); setBusy(false);
} }
...@@ -302,17 +264,6 @@ export default function Workbench() { ...@@ -302,17 +264,6 @@ export default function Workbench() {
}, [previewSource, targetUrl, coderioUrl, overrideUrl]); }, [previewSource, targetUrl, coderioUrl, overrideUrl]);
const running = previewSource === 'target' ? !!projectRun?.running : !!state?.running; const running = previewSource === 'target' ? !!projectRun?.running : !!state?.running;
const clearAll = async () => {
if (!confirm('确定清空全部任务记录吗?进行中的任务会被中止,此操作不可撤销。')) return;
try {
const r = await api.clearJobs();
if (r.ok) toast.success(`已清空 ${r.count} 条记录`);
else toast.error('清空失败');
} catch (e) {
toast.error('清空失败', { description: e instanceof Error ? e.message : String(e) });
}
};
return ( return (
<div className="flex h-full flex-col"> <div className="flex h-full flex-col">
{/* ===== Generate bar ===== */} {/* ===== Generate bar ===== */}
...@@ -596,22 +547,6 @@ export default function Workbench() { ...@@ -596,22 +547,6 @@ export default function Workbench() {
</span> </span>
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
{/* <div className="hidden gap-1.5 sm:flex">
{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>*/}
<button <button
onClick={() => setAutoScroll((v) => !v)} onClick={() => setAutoScroll((v) => !v)}
className={cn( className={cn(
...@@ -634,12 +569,12 @@ export default function Workbench() { ...@@ -634,12 +569,12 @@ export default function Workbench() {
}} }}
className="log-terminal scrollbar-thin flex-1 overflow-auto rounded-b-xl border border-border bg-[#0b0e14] p-3 text-zinc-100" className="log-terminal scrollbar-thin flex-1 overflow-auto rounded-b-xl border border-border bg-[#0b0e14] p-3 text-zinc-100"
> >
{visibleLogs.length === 0 ? ( {logs.length === 0 ? (
<div className="text-zinc-500"> <div className="text-zinc-500">
暂无日志。提交生成任务后将实时显示引擎输出… 暂无日志。提交生成任务后将实时显示引擎输出…
</div> </div>
) : ( ) : (
visibleLogs.map((l, i) => ( logs.map((l, i) => (
<div key={i} className="border-b border-white/5 py-1 last:border-0"> <div key={i} className="border-b border-white/5 py-1 last:border-0">
<div className="flex items-center gap-2 text-[10px] leading-none text-zinc-600"> <div className="flex items-center gap-2 text-[10px] leading-none text-zinc-600">
<span className={cn('font-semibold', levelStyle[l.level])}> <span className={cn('font-semibold', levelStyle[l.level])}>
...@@ -675,7 +610,7 @@ export default function Workbench() { ...@@ -675,7 +610,7 @@ export default function Workbench() {
variant="ghost" variant="ghost"
size="sm" size="sm"
className="h-7 px-2 text-xs text-muted-foreground hover:text-rose-400" className="h-7 px-2 text-xs text-muted-foreground hover:text-rose-400"
onClick={clearAll} onClick={() => { void clearAllJobs(); }}
disabled={jobs.length === 0} disabled={jobs.length === 0}
title="清空全部" title="清空全部"
> >
...@@ -728,14 +663,14 @@ export default function Workbench() { ...@@ -728,14 +663,14 @@ export default function Workbench() {
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
{isActive(j) && ( {isActive(j) && (
<button <button
onClick={() => handleCancel(j.id)} onClick={() => { void cancelJob(j.id); }}
className="flex items-center gap-1 rounded-md border border-border px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:border-rose-500/40 hover:bg-rose-500/10 hover:text-rose-400" className="flex items-center gap-1 rounded-md border border-border px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:border-rose-500/40 hover:bg-rose-500/10 hover:text-rose-400"
> >
<StopCircle className="h-3.5 w-3.5" /> 结束 <StopCircle className="h-3.5 w-3.5" /> 结束
</button> </button>
)} )}
<button <button
onClick={() => handleDelete(j.id)} onClick={() => { void deleteJob(j.id); }}
className="flex items-center gap-1 rounded-md border border-border px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:border-rose-500/40 hover:bg-rose-500/10 hover:text-rose-400" className="flex items-center gap-1 rounded-md border border-border px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:border-rose-500/40 hover:bg-rose-500/10 hover:text-rose-400"
title="删除记录" title="删除记录"
> >
...@@ -792,9 +727,6 @@ export default function Workbench() { ...@@ -792,9 +727,6 @@ export default function Workbench() {
<div className="flex-1 flex"> <div className="flex-1 flex">
<div className="flex min-w-0 flex-1 items-center gap-3 border-r border-border bg-muted/30 px-4"> <div className="flex min-w-0 flex-1 items-center gap-3 border-r border-border bg-muted/30 px-4">
<Globe className="h-4 w-4 shrink-0 text-muted-foreground" /> <Globe className="h-4 w-4 shrink-0 text-muted-foreground" />
{/* <span className="truncate font-mono text-xs text-muted-foreground">
{embedUrl ?? (previewSource === 'target' ? '目标项目未启动' : '未启动预览服务')}
</span> */}
<button <button
onClick={() => setScheme((s) => (s === 'http' ? 'https' : 'http'))} onClick={() => setScheme((s) => (s === 'http' ? 'https' : 'http'))}
className="flex h-8 shrink-0 items-center rounded-md border border-border bg-card px-2 font-mono text-[11px] font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground" className="flex h-8 shrink-0 items-center rounded-md border border-border bg-card px-2 font-mono text-[11px] font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
......
import { Agent, type ModelConfig } from 'evoltagent';
import { INITIAL_AGENT_SYSTEM_PROMPT } from './prompt';
/**
* Creates an initial agent for scaffolding a project.
* @param options - The options for creating the agent.
* @param options.modelConfig - The model configuration.
* @param options.appPath - The path to the app.
* @returns The initial agent.
*/
export function createInitialAgent(modelConfig: ModelConfig): Agent {
const systemTools = ['ThinkTool.execute', 'FileEditor.read', 'FileEditor.write'];
return new Agent({
name: 'InitialAgent',
profile: 'Expert Frontend Engineer specialized in project scaffolding with React, TypeScript, and Tailwind CSS V4.',
system: INITIAL_AGENT_SYSTEM_PROMPT,
tools: systemTools,
modelConfig,
verbose: true,
});
}
# Validation Report Template
This directory contains the interactive React-based validation report viewer used by CodeRio to visualize design-to-code validation results.
## What It Is
The validation report template is a standalone web application that provides an interactive UI for comparing Figma designs with generated code implementations. It displays position validation metrics, annotated screenshots, and detailed component-level feedback.
## Why It's Here
During the validation workflow, CodeRio generates a comprehensive validation report that includes:
- Position validation metrics (MAE, SAE, misaligned element count)
- Side-by-side comparison of design vs. implementation
- Annotated screenshots highlighting misaligned elements
- Component-level deviation details
This template provides the UI layer for visualizing that data. The built template is inlined into a single HTML file with embedded data, allowing users to view validation results without any server or dependencies.
## What It Looks Like
The report viewer features two main visualization modes:
### 1. Annotation Mode (Default)
- Split-screen comparison of annotated design and implementation
- Color-coded bounding boxes around misaligned elements
- Element indices for cross-referencing with the feedback panel
### 2. Rubbing Mode (Experimental)
- Interactive slider to compare design and implementation
- Drag the slider to overlay and compare alignment
- Optional pixel-difference heatmap visualization
### Feedback Panel
- Overall validation metrics (MAE, SAE, misaligned count)
- Expandable component list showing:
- Component ID and file path
- Per-element position deviations (x/y in pixels)
- Element indices matching the annotations
## How to Use
### For End Users
When CodeRio completes validation, it generates an `index.html` report file in your workspace:
```
coderio/<projectname>/validation/index.html
```
Open this file in any web browser to view the interactive report. No server or dependencies required.
### For Developers
#### Building the Template
The template is built during the main CodeRio build process:
```bash
pnpm build # Builds both main coderio and report template
```
Or build the template independently:
```bash
cd src/tools/report-tool/template
pnpm install
pnpm build # Outputs to dist/
```
#### Development Mode
To work on the template UI:
```bash
cd src/tools/report-tool/template
pnpm dev # Starts Vite dev server
```
Note: In dev mode, you'll need to manually inject sample data into `window.__REPORT_DATA__` for testing.
#### How It's Integrated
The `ReportTool.generateHtml()` method (in `src/tools/report-tool/index.ts`) performs the following:
1. Reads the built template from `template/dist/index.html`
2. Injects validation data into `window.__REPORT_DATA__`
3. Inlines all JavaScript and CSS assets into the HTML
4. Escapes special characters to prevent script injection
5. Writes a standalone single-file HTML report
This ensures the report is fully self-contained and portable.
## Technical Details
### Stack
- **React 19** with TypeScript
- **Vite** for building and bundling
- **TailwindCSS** for styling (via CDN in production build)
- **lucide-react** for icons
### Key Components
- `App.tsx`: Main application shell with mode switching
- `ComparisonSlider.tsx`: Interactive slider for rubbing mode
- `AnnotationView.tsx`: Split-screen annotated comparison
- `FeedbackPanel.tsx`: Component-level validation details
### Data Contract
The template expects `window.__REPORT_DATA__` to be a `UserReport` object:
```typescript
interface UserReport {
design: {
snap: string; // Figma thumbnail URL
markedSnap: string; // Annotated design (base64 data URI)
};
page: {
url: string; // Local dev server URL
snap: string; // Page screenshot (base64 data URI)
markedSnap: string; // Annotated page (base64 data URI)
};
report: {
heatmap: string; // Pixel-diff heatmap (base64 data URI)
detail: {
metrics: {
mae: number; // Mean Absolute Error
sae: number; // Sum of Absolute Errors
misalignedCount: number; // Total misaligned components
};
components: Array<{
componentId: string;
componentPath: string;
elements: Array<{
elementId: string;
elementIndex: number;
validationInfo: {
x: number; // Horizontal deviation (px)
y: number; // Vertical deviation (px)
};
}>;
}>;
};
};
}
```
### File Structure
```
template/
├── src/
│ ├── components/
│ │ ├── AnnotationView.tsx # Split-screen annotated view
│ │ ├── ComparisonSlider.tsx # Interactive rubbing slider
│ │ └── FeedbackPanel.tsx # Validation details panel
│ ├── App.tsx # Main application component
│ ├── index.tsx # React entry point
│ └── types.ts # TypeScript interfaces
├── dist/ # Built output (generated)
│ ├── index.html
│ └── assets/
├── package.json
├── tsconfig.json
└── README.md # This file
```
## Notes
- The template is version-controlled in source form only (`dist/` is gitignored)
- The build output is embedded directly into the main CodeRio bundle
- Base64-encoded images are used to ensure the report is fully self-contained
- The template supports responsive design but is optimized for desktop viewing
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CodeRio Design2Code</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Inter', sans-serif;
}
/* Custom scrollbar for a cleaner look */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: #cbd5e1;
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: #94a3b8;
}
</style>
<script type="importmap">
{
"imports": {
"lucide-react": "https://esm.sh/lucide-react@^0.561.0",
"react-dom/": "https://esm.sh/react-dom@^19.2.3/",
"react/": "https://esm.sh/react@^19.2.3/",
"react": "https://esm.sh/react@^19.2.3"
}
}
</script>
<script>
window.__REPORT_DATA__ = null;
</script>
<link rel="stylesheet" href="/index.css">
</head>
<body class="bg-slate-50 text-slate-900 antialiased overflow-hidden h-screen w-screen">
<div id="root"></div>
<script type="module" src="/src/index.tsx"></script>
</body>
</html>
\ No newline at end of file \ No newline at end of file
{
"name": "CodeRio Design2Code",
"description": "A professional frontend engineering tool to compare design mockups with implemented code, featuring pixel-perfect overlay comparison and detailed component feedback.",
"requestFramePermissions": []
}
\ No newline at end of file \ No newline at end of file
import React, { useState } from 'react';
import { Layers, ScanEye, Code2, ChevronRight, FlaskConical } from 'lucide-react';
import ComparisonSlider from './components/ComparisonSlider';
import AnnotationView from './components/AnnotationView';
import FeedbackPanel from './components/FeedbackPanel';
import { ViewMode, UserReport } from './types';
// ... imports ...
// Define global interface for injected data
declare global {
interface Window {
__REPORT_DATA__?: UserReport;
}
}
const App: React.FC = () => {
const [viewMode, setViewMode] = useState<ViewMode>('annotation');
const { design, page, report } = window.__REPORT_DATA__;
return (
<div className="h-screen flex flex-col bg-slate-50 text-slate-900 font-sans">
{/* --- Top Navigation Bar --- */}
<header className="h-16 flex-none bg-white border-b border-slate-200 px-6 flex items-center justify-between shadow-sm z-30">
<div className="flex items-center gap-3">
<div className="bg-indigo-600 p-2 rounded-lg text-white">
<Code2 size={20} strokeWidth={2.5} />
</div>
<div>
<h1 className="font-bold text-lg tracking-tight text-slate-900 leading-none">CodeRio</h1>
<span className="text-[10px] font-semibold tracking-widest text-indigo-500 uppercase">Design2Code</span>
</div>
</div>
{/* Mode Switcher */}
<div className="flex bg-slate-100 p-1 rounded-lg border border-slate-200">
<button
onClick={() => setViewMode('annotation')}
className={`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all duration-200 ${
viewMode === 'annotation' ? 'bg-white text-indigo-600 shadow-sm' : 'text-slate-500 hover:text-slate-700'
}`}
>
<ScanEye size={16} />
<span>Annotation Mode</span>
</button>
<button
onClick={() => setViewMode('rubbing')}
className={`relative flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all duration-200 ${
viewMode === 'rubbing' ? 'bg-white text-indigo-600 shadow-sm' : 'text-slate-500 hover:text-slate-700'
}`}
>
<Layers size={16} />
<span>Rubbing Mode</span>
{/* Fun Badge */}
<span className="flex h-2 w-2 absolute top-1 right-1">
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-pink-400 opacity-75"></span>
<span className="relative inline-flex rounded-full h-2 w-2 bg-pink-500"></span>
</span>
<div className="ml-1 text-[10px] bg-pink-100 text-pink-600 px-1.5 py-0.5 rounded-full flex items-center gap-0.5 font-bold tracking-wide uppercase">
<FlaskConical size={10} /> Lab
</div>
</button>
</div>
{/* Actions */}
<div className="flex items-center gap-3">
{/* <button className="p-2 text-slate-400 hover:text-slate-600 transition-colors">
<Settings size={20} />
</button>
<button className="flex items-center gap-2 bg-slate-900 hover:bg-slate-800 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors shadow-sm">
<Download size={16} />
Export Report
</button> */}
</div>
</header>
{/* --- Main Workspace --- */}
<main className="flex-1 flex overflow-hidden">
{/* Left/Center: Visualization Area */}
<section className="flex-1 flex flex-col min-w-0 bg-slate-50/50 relative">
{/* Breadcrumb / Context Bar */}
<div className="h-12 border-b border-slate-200 flex items-center px-6 text-sm text-slate-500 gap-2 bg-white/50 backdrop-blur-sm">
<span className="font-medium text-slate-800">Home Page</span>
<ChevronRight size={14} />
<span className={viewMode === 'rubbing' ? 'text-indigo-600 font-medium' : ''}>
{viewMode === 'rubbing' ? 'Rubbing Mode' : 'Annotation Mode'}
</span>
</div>
{/* Canvas */}
<div className="flex-1 p-6 overflow-hidden">
<div className="w-full h-full shadow-lg rounded-2xl overflow-hidden ring-1 ring-black/5 bg-white">
{viewMode === 'rubbing' ? (
<ComparisonSlider beforeImage={page.snap} afterImage={design.snap} heatmapImage={report.heatmap} />
) : (
<AnnotationView designUrl={design.markedSnap} pageUrl={page.markedSnap} />
)}
</div>
</div>
</section>
{/* Right: Feedback Panel */}
<aside className="w-[340px] flex-none z-20 shadow-xl shadow-slate-200/50">
<FeedbackPanel detail={report.detail} />
</aside>
</main>
</div>
);
};
export default App;
import React, { useRef } from 'react';
// import { AlertCircle } from 'lucide-react';
interface AnnotationViewProps {
designUrl: string;
pageUrl: string;
}
const AnnotationView: React.FC<AnnotationViewProps> = ({ designUrl, pageUrl }) => {
const designRef = useRef<HTMLDivElement>(null);
const pageRef = useRef<HTMLDivElement>(null);
const isSyncingDesign = useRef(false);
const isSyncingPage = useRef(false);
const handleDesignScroll = () => {
if (!designRef.current || !pageRef.current) return;
if (isSyncingDesign.current) {
isSyncingDesign.current = false;
return;
}
isSyncingPage.current = true;
pageRef.current.scrollTop = designRef.current.scrollTop;
pageRef.current.scrollLeft = designRef.current.scrollLeft;
};
const handlePageScroll = () => {
if (!designRef.current || !pageRef.current) return;
if (isSyncingPage.current) {
isSyncingPage.current = false;
return;
}
isSyncingDesign.current = true;
designRef.current.scrollTop = pageRef.current.scrollTop;
designRef.current.scrollLeft = pageRef.current.scrollLeft;
};
return (
<div className="flex h-full w-full gap-4">
{/* Left: Design Mockup */}
<div className="flex-1 flex flex-col min-w-0 rounded-xl border border-slate-200 bg-white overflow-hidden shadow-sm">
<div className="h-10 border-b border-slate-100 bg-slate-50 flex items-center px-4 justify-between">
<span className="text-xs font-semibold text-slate-500 uppercase tracking-wider">Design</span>
<div className="w-2 h-2 rounded-full bg-slate-300"></div>
</div>
<div
ref={designRef}
onScroll={handleDesignScroll}
className="flex-1 relative overflow-auto bg-slate-100/50"
>
<img src={designUrl} alt="Design" className="w-full h-auto object-contain object-top" />
</div>
</div>
{/* Right: Live Iframe */}
<div className="flex-1 flex flex-col min-w-0 rounded-xl border border-slate-200 bg-white overflow-hidden shadow-sm">
<div className="h-10 border-b border-slate-100 bg-slate-50 flex items-center px-4 justify-between">
<div className="flex items-center gap-2">
<span className="text-xs font-semibold text-indigo-600 uppercase tracking-wider">Page</span>
<span className="text-[10px] text-slate-400 font-mono px-1.5 py-0.5 bg-slate-200 rounded">
Rectangle indicates positional mismatch
</span>
</div>
{/* <a href={liveUrl} target="_blank" rel="noreferrer" className="text-slate-400 hover:text-indigo-600 transition-colors">
<ExternalLink size={14} />
</a> */}
</div>
<div
ref={pageRef}
onScroll={handlePageScroll}
className="flex-1 relative overflow-auto bg-white"
>
<img src={pageUrl} alt="Design" className="w-full h-auto object-contain object-top" />
{/* Fallback overlay for demo purposes since localhost might not be running for the user */}
{/* <div className="absolute inset-0 pointer-events-none flex items-center justify-center opacity-0 hover:opacity-100 transition-opacity bg-slate-900/5">
<div className="bg-white/90 backdrop-blur px-4 py-2 rounded-lg shadow-sm border border-slate-200 flex items-center gap-2 text-xs text-slate-500">
<AlertCircle size={14} />
Ensure {liveUrl} is running
</div>
</div> */}
</div>
</div>
</div>
);
};
export default AnnotationView;
import React, { useState, useRef, useEffect, useCallback } from 'react';
import { GripVertical, Flame } from 'lucide-react';
interface ComparisonSliderProps {
beforeImage: string; // Design
afterImage: string; // Implementation (Page Screenshot)
heatmapImage?: string;
}
const ComparisonSlider: React.FC<ComparisonSliderProps> = ({ beforeImage, afterImage, heatmapImage }) => {
const [sliderPosition, setSliderPosition] = useState(50);
const [isDragging, setIsDragging] = useState(false);
const [showHeatmap, setShowHeatmap] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
const handleMove = useCallback((clientX: number) => {
if (containerRef.current) {
const rect = containerRef.current.getBoundingClientRect();
const x = Math.max(0, Math.min(clientX - rect.left, rect.width));
const percentage = (x / rect.width) * 100;
setSliderPosition(percentage);
}
}, []);
const handleMouseDown = () => setIsDragging(true);
const handleTouchStart = () => setIsDragging(true);
const handleMouseUp = useCallback(() => setIsDragging(false), []);
const handleTouchEnd = useCallback(() => setIsDragging(false), []);
const handleMouseMove = useCallback(
(e: MouseEvent) => {
if (isDragging) handleMove(e.clientX);
},
[isDragging, handleMove]
);
const handleTouchMove = useCallback(
(e: TouchEvent) => {
if (isDragging) handleMove(e.touches[0].clientX);
},
[isDragging, handleMove]
);
useEffect(() => {
if (isDragging) {
window.addEventListener('mousemove', handleMouseMove);
window.addEventListener('mouseup', handleMouseUp);
window.addEventListener('touchmove', handleTouchMove);
window.addEventListener('touchend', handleTouchEnd);
} else {
window.removeEventListener('mousemove', handleMouseMove);
window.removeEventListener('mouseup', handleMouseUp);
window.removeEventListener('touchmove', handleTouchMove);
window.removeEventListener('touchend', handleTouchEnd);
}
return () => {
window.removeEventListener('mousemove', handleMouseMove);
window.removeEventListener('mouseup', handleMouseUp);
window.removeEventListener('touchmove', handleTouchMove);
window.removeEventListener('touchend', handleTouchEnd);
};
}, [isDragging, handleMouseMove, handleMouseUp, handleTouchMove, handleTouchEnd]);
return (
<div className="relative flex flex-col gap w-full h-full">
<div className="flex justify-between items-center w-full px-4 py-3">
<div className="bg-black/50 backdrop-blur-md text-white px-3 py-1 rounded-full text-xs font-medium">Design</div>
{/* Controls: Heatmap Toggle */}
<label className="flex items-center gap-2 bg-white/80 backdrop-blur border border-slate-200 px-3 py-1.5 rounded-full cursor-pointer hover:bg-white transition-colors shadow-sm group">
<input type="checkbox" className="sr-only" checked={showHeatmap} onChange={e => setShowHeatmap(e.target.checked)} />
<div
className={`w-4 h-4 rounded flex items-center justify-center border transition-colors ${showHeatmap ? 'bg-orange-500 border-orange-500 text-white' : 'bg-slate-100 border-slate-300'}`}
>
{showHeatmap && <Flame size={10} fill="currentColor" />}
</div>
<span className={`text-xs font-medium ${showHeatmap ? 'text-orange-600' : 'text-slate-600'}`}>Heatmap</span>
</label>
<div className="bg-indigo-600/80 backdrop-blur-md text-white px-3 py-1 rounded-full text-xs font-medium">Page</div>
</div>
<div
ref={containerRef}
className="relative w-full h-full select-none overflow-hidden rounded-xl border border-slate-200 shadow-sm bg-white"
>
{/*
LOGIC EXPLANATION:
- Layer 1 (Bottom): Design Mockup (Visible on the RIGHT side when clipped)
- Layer 2 (Top): Code Implementation (Visible on the LEFT side, clipped from the right)
*/}
{/* 1. Design Mockup (Full Width Background) */}
{!showHeatmap && (
<img
src={beforeImage}
alt="Design Mockup"
className="absolute inset-0 h-full w-full object-contain object-top pointer-events-none"
/>
)}
{/* 2. Implementation (Clipped to show only the left part based on slider position) */}
{!showHeatmap && (
<img
src={afterImage}
alt="Implementation"
className="absolute inset-0 h-full w-full object-contain object-top pointer-events-none z-10"
style={{
clipPath: `inset(0 ${100 - sliderPosition}% 0 0)`,
}}
/>
)}
{/* 3. Heatmap Overlay */}
{showHeatmap && heatmapImage && (
<img
src={heatmapImage}
alt="heatmap"
className="absolute inset-0 h-full w-full object-contain object-top pointer-events-none z-15"
/>
)}
{/* Slider Handle */}
{!showHeatmap && (
<div
className="absolute inset-y-0 cursor-ew-resize z-40 group"
style={{ left: `${sliderPosition}%` }}
onMouseDown={handleMouseDown}
onTouchStart={handleTouchStart}
>
<div className="h-full w-0.5 bg-white shadow-[0_0_10px_rgba(0,0,0,0.3)] group-hover:bg-indigo-400 transition-colors"></div>
<div className="absolute top-1/2 -translate-y-1/2 -translate-x-1/2 w-8 h-8 bg-white rounded-full shadow-lg flex items-center justify-center border border-slate-100 group-hover:scale-110 transition-transform">
<GripVertical size={16} className="text-slate-400" />
</div>
</div>
)}
</div>
</div>
);
};
export default ComparisonSlider;
import React, { useState } from 'react';
import { ChevronDown, ChevronRight, AlertTriangle, Ruler, Info } from 'lucide-react';
import type { UserReport } from '../types';
interface FeedbackPanelProps {
detail: UserReport['report']['detail'];
}
const FeedbackPanel: React.FC<FeedbackPanelProps> = ({ detail }) => {
// Group by status for a quick summary
const { metrics, components } = detail;
return (
<div className="flex flex-col h-full bg-white border-l border-slate-200 w-full">
{/* Header */}
<div className="p-5 border-b border-slate-100">
<h2 className="text-lg font-bold text-slate-900 tracking-tight">Analysis Report</h2>
<div className="flex flex-col gap-3 mt-4">
<div className="flex items-center gap-1.5 px-3 py-1.5 bg-amber-50 text-amber-700 rounded-md text-xs font-medium border border-amber-100">
<Info size={14} />
MAE: {metrics.mae.toFixed(2)}, SAE: {metrics.sae.toFixed(2)}
</div>
<div className="flex items-center gap-1.5 px-3 py-1.5 bg-red-50 text-red-700 rounded-md text-xs font-medium border border-red-100">
<AlertTriangle size={14} />
{components?.length || 0} instances mismatched
</div>
</div>
<span className="text-xs text-slate-500 mt-1 italic">Only positional detection supported currently</span>
</div>
{/* List */}
<div className="flex-1 overflow-y-auto p-4 space-y-3">
{components.map(item => (
<FeedbackCard key={item.componentId} item={item} />
))}
</div>
</div>
);
};
const FeedbackCard: React.FC<{ item: UserReport['report']['detail']['components'][number] }> = ({ item }) => {
const [isExpanded, setIsExpanded] = useState(false);
return (
<div
className={`border rounded-lg transition-all duration-200 ${isExpanded ? 'border-indigo-100 shadow-md bg-white' : 'border-slate-100 hover:border-slate-200 bg-slate-50/50'}`}
>
<button
onClick={() => setIsExpanded(!isExpanded)}
className="w-full flex items-center justify-between p-3 text-left focus:outline-none"
>
<div className="flex items-center gap-3">
<h3 className="text-sm font-semibold text-slate-800">{item.componentId}</h3>
{item.elements && item.elements?.length > 0 && (
<span className="text-[10px] bg-red-50 text-red-600 px-1.5 py-0.5 rounded-full font-bold ml-1">
{item.elements?.length} elements
</span>
)}
</div>
{isExpanded ? <ChevronDown size={16} className="text-slate-400" /> : <ChevronRight size={16} className="text-slate-400" />}
</button>
{isExpanded && (
<div className="px-3 pb-4 pt-0 border-t border-slate-50">
<p className="text-[10px] text-slate-400 mt-2">Path: {item.componentPath}</p>
{/* Metrics */}
<div className="space-y-2 mt-3 mb-2">
{item.elements?.map(el => (
<div key={el.elementId} className="bg-slate-50 p-2 rounded border border-slate-100">
<div className="flex items-center justify-between mb-1">
<div className="flex items-center gap-1 text-[10px] text-slate-500">
<Ruler size={10} />{' '}
<span className="text-[9px] text-slate-800 font-mono truncate max-w-[100px]" title={el.elementId}>
ID: <strong>{el.elementId}</strong>
</span>
</div>
<span className="text-[10px] text-slate-500">Index: {el.elementIndex}</span>
</div>
<div className="font-mono text-[10px] text-slate-800 font-medium">
x: <span className={el.validationInfo.x !== 0 ? 'text-red-500' : ''}>{el.validationInfo.x}px</span>, y:{' '}
<span className={el.validationInfo.y !== 0 ? 'text-red-500' : ''}>{el.validationInfo.y}px</span>
</div>
</div>
))}
</div>
</div>
)}
</div>
);
};
export default FeedbackPanel;
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
const rootElement = document.getElementById('root');
if (!rootElement) {
throw new Error("Could not find root element to mount to");
}
const root = ReactDOM.createRoot(rootElement);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
\ No newline at end of file \ No newline at end of file
export type ViewMode = 'rubbing' | 'annotation';
export interface UserReport {
design: {
snap: string; // Figma thumbnail URL
markedSnap: string; // Annotated design image (base64 data URI)
};
page: {
url: string; // Local server URL
snap: string; // Page screenshot (base64 data URI)
markedSnap: string; // Annotated page screenshot (base64 data URI)
};
report: {
heatmap: string; // Reserved for future heatmap implementation (empty for now)
detail: {
metrics: {
mae: number;
sae: number;
misalignedCount: number;
};
// Grouped component type for report visualization
components: {
componentId: string;
componentPath: string;
elements: {
elementId: string;
elementIndex: number;
validationInfo: {
x: number; // Horizontal deviation in px
y: number; // Vertical deviation in px
};
}[];
}[];
};
};
}
{
"compilerOptions": {
"target": "ES2022",
"experimentalDecorators": true,
"useDefineForClassFields": false,
"module": "ESNext",
"lib": [
"ES2022",
"DOM",
"DOM.Iterable"
],
"skipLibCheck": true,
"types": [
"node"
],
"moduleResolution": "bundler",
"isolatedModules": true,
"moduleDetection": "force",
"allowJs": true,
"jsx": "react-jsx",
"paths": {
"@/*": [
"./*"
]
},
"allowImportingTsExtensions": true,
"noEmit": true
}
}
\ No newline at end of file \ No newline at end of file
import path from 'path';
import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, '.', '');
return {
server: {
port: 3000,
host: '0.0.0.0',
},
plugins: [react()],
define: {
'process.env.API_KEY': JSON.stringify(env.GEMINI_API_KEY),
'process.env.GEMINI_API_KEY': JSON.stringify(env.GEMINI_API_KEY),
},
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
};
});
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!