Commit c8d03b08 by liimin

feat: 技术栈选择 + 严格技术栈降级链 + 撑满开关 + 图标铁律 + 启动竞态修复

- 前端 Workbench 技术栈 localStorage 持久化、默认 Vue3+Element Plus、生成前提示
- 引擎 CODE 节点策略化(react/vue3/component-usage),严格技术栈降级链 Tier1 自定义>库>原生
- 内容区生成指引(req_8)、撑满容器开关(req_12)、图标属性铁律(req_13)
- 服务端 /api/health 探针 + 前端就绪门控,根治重启启动竞态 ECONNREFUSED
- vite 代理 target localhost->127.0.0.1
- 新增 scripts/dev.mjs supervisor(4174) 编排后端(4173)+Vite(5173)
- 修复产物白屏 InvalidCharacterError(svg 当组件传给 icon prop)
1 parent 8def5834
......@@ -32,6 +32,7 @@ async function main(): Promise<void> {
const raw = process.env.COD_RUNTIME_CONFIG;
let targetArg: unknown = undefined;
let fillContainerArg: boolean | undefined = undefined;
if (raw) {
try {
const cfg = JSON.parse(raw) as {
......@@ -39,6 +40,7 @@ async function main(): Promise<void> {
figma?: Record<string, unknown>;
projectProfile?: unknown;
target?: unknown;
fillContainer?: unknown;
};
setRuntimeConfig({ model: cfg.model, figma: cfg.figma });
// projectProfile is passed to design2code below (typed via the
......@@ -50,6 +52,9 @@ async function main(): Promise<void> {
if (cfg.target && typeof cfg.target === 'object') {
targetArg = cfg.target;
}
if (typeof cfg.fillContainer === 'boolean') {
fillContainerArg = cfg.fillContainer;
}
} catch (e) {
process.stdout.write(`__D2C_ERROR__:invalid runtime config: ${e instanceof Error ? e.message : String(e)}\n`);
process.exit(1);
......@@ -67,6 +72,7 @@ async function main(): Promise<void> {
resume: false,
projectProfile: projectProfileArg,
target: targetArg as never,
fillContainer: fillContainerArg,
});
process.stdout.write('__D2C_DONE__\n');
process.exit(0);
......
import { readFileSync } from 'node:fs';
import { spawn } from 'node:child_process';
import { spawn, execSync } from 'node:child_process';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import type { Server } from 'node:http';
import { JobStore } from './jobStore';
import { JobQueue } from './queue';
import { PreviewManager } from './preview';
import { ProjectRunner } from './project-runner';
import { createApp } from './server';
import { loadDotEnv, loadServerModelConfig, resolveServerOptions, loadProjectProfile } from './config';
import { runJob } from './runner';
import { parseFigmaUrl, emptyProfile } from 'coderio';
import type { ProjectProfile } from 'coderio';
import type { TechStack } from './types';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
/**
* Build a minimal synthetic ProjectProfile from a standalone tech-stack choice.
* The engine's strategy layer reads `framework` to decide React vs Vue, etc.,
* and `styling` / `componentLibrary` flow into the generated constraints.
*/
function buildSyntheticProfile(stack: TechStack): ProjectProfile {
const base = emptyProfile();
base.framework = stack.framework || 'React 18';
base.styling = stack.styling || '';
base.componentLibrary = stack.componentLibrary || '';
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 {
try {
return JSON.parse(readFileSync(p, 'utf8')).version ?? '0.0.0';
......@@ -46,22 +93,35 @@ function main(): void {
path.join(__dirname, '..', '..', '..', 'packages', 'coderio', 'package.json'),
);
// 由 createApp 返回后在下方赋值;restartServer 闭包里需要引用它来主动释放端口。
let server: Server;
const restartServer = (): void => {
// 重启前先清掉端口上任何「非自身」的陈旧监听者(孤儿/上次没退干净的进程),
// 确保新进程能独占端口,避免双绑导致部分请求打到半死进程而报 500。
killOtherListenersOnPort(opts.port, process.pid);
try {
const child = spawn('npm', ['run', 'server'], {
cwd: REPO_ROOT,
detached: true,
stdio: 'ignore',
shell: true,
env: process.env,
env: { ...process.env },
});
child.unref();
} catch (e) {
// eslint-disable-next-line no-console
console.error('重启失败:', e);
return;
}
// 断开所有长连接(SSE 等)并尽快让出端口,避免新进程 bind 时发生 EADDRINUSE。
try {
(server as unknown as { closeAllConnections?: () => void }).closeAllConnections?.();
} catch {
/* ignore */
}
// Exit after a short grace period so the port is released for the new process.
setTimeout(() => process.exit(0), 400);
// 留出足够时间让端口被 OS 回收后再退出。
setTimeout(() => process.exit(0), 600);
};
const shutdownServer = (): void => {
......@@ -75,39 +135,101 @@ function main(): void {
};
const preview = new PreviewManager((state) => hub.broadcast('preview', state));
// 启动时清掉从旧后端进程 detached 残留的预览 vite,避免它们占用端口 / 锁住目录。
preview.killStalePreviewPorts();
const projectRunner = new ProjectRunner((state) => hub.broadcast('projectRun', state));
const queue = new JobQueue(
store,
(job, onPid) => runJob(job, model, opts.outputDir, onPid, loadProjectProfile()),
(job, onPid) => {
// 生成会重写 <outputDir>/coderio/<project>/my-app 下的产物(含
// package.json)。若该预览服务正对此产物目录运行 vite,Windows 上
// vite 持有的文件句柄会阻塞引擎的写操作并抛 EPERM。因此在生成开始
// 前,停掉服务于同一产物目录的预览;其它项目的预览不受影响。
const threadId = (() => {
try {
return parseFigmaUrl(job.figmaUrl).projectName ?? job.appName;
} catch {
return job.appName;
}
})();
const resultDir = path.resolve(job.outputDir ?? opts.outputDir, 'coderio', threadId);
const appPath = preview.state.appPath;
if (appPath && (appPath === resultDir || appPath.startsWith(resultDir + path.sep))) {
preview.stop();
}
// 兜底:清掉可能从旧后端 detached 残留、且不在 preview.state 掌控内的预览
// vite(监听 5180–5195 端口)。否则它会持续锁住 my-app 目录,导致 scaffold
// 写 package.json 抛 EPERM。
preview.killStalePreviewPorts();
// 独立预览 + 用户自选技术栈:用 stack 合成最小 profile,驱动引擎走对应
// 生成策略(含 Vue 等);项目模式忽略 stack,改用「项目接入」画像。
const profile: ProjectProfile | null =
job.stack && job.target?.mode === 'standalone'
? buildSyntheticProfile(job.stack)
: loadProjectProfile();
return runJob(job, model, opts.outputDir, onPid, profile);
},
opts.maxConcurrent,
(s) => hub.broadcast('jobs', s.list()),
);
const { server, broadcast: realBroadcast } = createApp({
const { server: srv, broadcast: realBroadcast } = createApp({
store,
queue,
preview,
projectRunner,
opts,
startTime: START_TIME,
serverVersion: SERVER_VERSION,
coderioVersion: CODERIO_VERSION,
admin: { restart: restartServer, shutdown: shutdownServer },
});
server = srv;
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);
});
// 启动并带 EADDRINUSE 重试:重启场景下旧进程可能尚未释放端口,
// 新进程应轮询等待而非直接崩溃,保证重启在任何时序下都成功。
const listenWithRetry = (attempt = 0): void => {
const onError = (err: NodeJS.ErrnoException): void => {
if (err.code === 'EADDRINUSE') {
if (attempt < 25) {
// eslint-disable-next-line no-console
console.warn(
` ⚠ 端口 ${opts.port} 仍被占用,0.3s 后重试 (${attempt + 1}/25)`,
);
setTimeout(() => listenWithRetry(attempt + 1), 300);
return;
}
// eslint-disable-next-line no-console
console.error(` ✗ 端口 ${opts.port} 持续被占用,启动失败`);
process.exit(1);
return;
}
// eslint-disable-next-line no-console
console.error(' ✗ 服务启动失败:', err);
process.exit(1);
};
server.once('error', onError);
server.listen({ port: opts.port, host: opts.host }, () => {
server.removeListener('error', onError);
// 自身已成功绑定,清掉端口上任何残留的陈旧监听者(上次没退干净的孤儿/
// 重复启动的实例),保证起来就是独占端口,避免请求被甩到半死进程。
killOtherListenersOnPort(opts.port, process.pid);
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);
});
};
listenWithRetry();
}
main();
......@@ -58,11 +58,18 @@ export class PreviewManager {
}
}
/** Kill any lingering preview dev servers on the 5180–5195 range. */
private killStalePreviewPorts(): void {
/**
* 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 {
try {
const out = execSync('netstat -ano', { stdio: ['ignore', 'pipe', 'ignore'] }).toString();
const re = /:51(8[0-9]|9[0-5])\s+\S+\s+LISTENING\s+(\d+)/g;
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]);
......
import { spawn, execSync, type ChildProcess } from 'node:child_process';
import net from 'node:net';
import os from 'node:os';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import type { ProjectManager, ProjectRunState } from './types';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
/**
* Captures the spawned dev-server stdout+stderr so a silent failure (e.g. a
* missing dependency or a port clash) is diagnosable from the panel.
*/
const RUN_LOG = path.resolve(__dirname, '..', '..', '..', '.workbuddy', 'project-run.log');
type Scripts = Record<string, string>;
/**
* Launches the user's *own* target project as a dev server (npm/pnpm/yarn run
* dev) so generated code that lands inside it can be previewed live — in
* contrast to {@link PreviewManager}, which serves the isolated app coderio
* scaffolds. Only one target project runs at a time.
*/
export class ProjectRunner {
private proc: ChildProcess | null = null;
private logStream: fs.WriteStream | null = null;
/** Listening TCP ports that existed *before* this run started — used to
* ignore the orchestration server's own port (and any other pre-existing
* service) when detecting the dev server port. */
private baselinePorts: Set<number> = new Set();
state: ProjectRunState = {
running: false,
dir: null,
script: null,
manager: null,
url: null,
localUrl: null,
port: null,
pid: null,
error: null,
};
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 {
if (!scripts) return null;
// Return the *script name* (e.g. "dev"), not its command value — the
// launched command is `<manager> run <name>`, so passing the value
// (e.g. "vite" / "node server.js") would make npm look for a script
// literally named that and exit 1.
for (const key of ['dev', 'start', 'serve', 'dev:server']) {
if (scripts[key]) return key;
}
return null;
}
static pickManager(dir: string): ProjectManager {
if (fs.existsSync(path.join(dir, 'pnpm-lock.yaml'))) return 'pnpm';
if (fs.existsSync(path.join(dir, 'yarn.lock'))) return 'yarn';
return 'npm';
}
start(dir: string): { ok: boolean; error?: string } {
if (this.proc) return { ok: false, error: '已有目标项目在运行,请先停止' };
if (!fs.existsSync(dir)) return { ok: false, error: `目录不存在:${dir}` };
const pkgPath = path.join(dir, 'package.json');
if (!fs.existsSync(pkgPath)) {
return { ok: false, error: `该目录不是 npm 项目(缺少 package.json):${dir}` };
}
let pkg: { scripts?: Scripts };
try {
pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
} catch (e) {
return { ok: false, error: `package.json 解析失败:${e instanceof Error ? e.message : String(e)}` };
}
const script = ProjectRunner.pickScript(pkg.scripts);
if (!script) {
return { ok: false, error: '未找到 dev/start/serve 脚本,无法启动(可在 package.json scripts 中补充)' };
}
const manager = ProjectRunner.pickManager(dir);
this.state = {
running: true,
dir,
script,
manager,
url: null,
localUrl: null,
port: null,
pid: null,
error: null,
};
try {
fs.mkdirSync(path.dirname(RUN_LOG), { recursive: true });
fs.appendFileSync(
RUN_LOG,
`\n===== project run start ${new Date().toISOString()} | dir=${dir} | manager=${manager} | script=${script} =====\n`,
);
// Capture the dev-server's stdout/stderr directly via pipes. A shell
// redirect (`>> log 2>&1`) proved unreliable on Windows — npm buffers
// its output until the process exits, so a live server's "Local:"
// line never reaches the redirected file. We still sink the pipe to
// RUN_LOG for post-mortem diagnostics, but port detection below does
// NOT depend on it (it uses netstat + the process tree instead).
// Snapshot pre-existing listening ports so the orchestration
// server's own port is never mistaken for the dev server.
this.baselinePorts = this.listListeningPorts();
const logStream = fs.createWriteStream(RUN_LOG, { flags: 'a' });
this.logStream = logStream;
const child = spawn(`${manager} run ${script}`, {
cwd: dir,
env: { ...process.env },
windowsHide: true,
detached: true,
shell: true,
stdio: ['ignore', 'pipe', 'pipe'],
});
child.unref();
this.proc = child;
this.state.pid = child.pid ?? null;
child.stdout?.on('data', (d) => logStream.write(d));
child.stderr?.on('data', (d) => logStream.write(d));
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);
}
});
// Detect the dev-server port: tail the log file for a
// "Local: http://localhost:<port>" line, then TCP-probe to confirm
// the server is actually listening before reporting the URL.
const deadline = Date.now() + 90_000;
const timer = setInterval(() => {
if (!this.proc || this.state.url) {
clearInterval(timer);
return;
}
if (Date.now() > deadline) {
clearInterval(timer);
if (!this.state.url) {
this.state = {
...this.state,
error: '启动超时:未能自动识别 dev server 端口(netstat 未找到监听端口)',
};
this.onChange(this.state);
}
return;
}
// Walk the spawned process tree and ask netstat which LISTENING
// port a descendant owns. This avoids parsing npm's (buffered)
// stdout. A TCP probe then confirms the server actually answers.
const port = this.proc.pid ? this.findDevServerPort(this.proc.pid) : null;
if (port) {
const sock = net.createConnection({ port, host: '127.0.0.1' });
let settled = false;
sock.once('connect', () => {
settled = true;
sock.destroy();
clearInterval(timer);
const ip = this.getLanIp();
this.state = {
...this.state,
port,
localUrl: `http://localhost:${port}/`,
url: `http://${ip}:${port}/`,
};
this.onChange(this.state);
});
sock.once('error', () => {
if (!settled) sock.destroy();
});
}
}, 800);
this.onChange(this.state);
return { ok: true };
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
this.state = {
running: false,
dir: null,
script: null,
manager: null,
url: null,
localUrl: null,
port: null,
pid: null,
error: message,
};
this.proc = null;
return { ok: false, error: message };
}
}
/**
* Returns every PID in the process tree rooted at `rootPid` (inclusive),
* using `wmic` to map parent→child relationships.
*/
private getDescendantPids(rootPid: number): number[] {
let out = '';
try {
out = execSync('wmic process get processid,parentprocessid', {
stdio: ['ignore', 'pipe', 'ignore'],
}).toString();
} catch {
return [rootPid];
}
const childToParent = new Map<number, number>();
for (const line of out.split('\n')) {
const nums = line
.trim()
.split(/\s+/)
.map(Number)
.filter((n) => !Number.isNaN(n));
if (nums.length >= 2) childToParent.set(nums[1], nums[0]);
}
const result = new Set<number>([rootPid]);
const stack = [rootPid];
while (stack.length) {
const p = stack.pop() as number;
for (const [pid, parent] of childToParent) {
if (parent === p && !result.has(pid)) {
result.add(pid);
stack.push(pid);
}
}
}
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
* LISTENING socket owned by any process in the spawned tree. npm buffers
* 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
* listening before this run started (`baselinePorts`) are ignored, so the
* orchestration server's own port (and any other pre-existing service) can
* never be mistaken for the dev server.
*/
private findDevServerPort(rootPid: number): number | null {
const pids = new Set(this.getDescendantPids(rootPid));
let net = '';
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 (pids.has(pid) && m[3].toUpperCase() === 'LISTENING') return port;
}
return null;
}
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 */
}
}
// Also kill the grandchild dev server by port (the shell kill above may
// not reach it), reliably freeing the port.
this.killPort(this.state.port ?? 0);
this.proc = null;
try {
this.logStream?.end();
} catch {
/* ignore */
}
this.logStream = null;
this.state = {
running: false,
dir: null,
script: null,
manager: null,
url: null,
localUrl: null,
port: null,
pid: null,
error: null,
};
this.onChange(this.state);
}
getStatus(): ProjectRunState {
return this.state;
}
}
......@@ -100,6 +100,8 @@ export async function runJob(
// Where the generated code should land (standalone / new-page /
// modify-slot). Recorded for the engine; slot rewriting is a later phase.
target: job.target ?? null,
// Whether the generated root should fill its host container (default true).
fillContainer: job.fillContainer ?? true,
});
const args = [
......
......@@ -7,6 +7,7 @@ import { subscribeLogs, parseFigmaUrl, type LogEntry } from 'coderio';
import type { JobStore } from './jobStore';
import type { JobQueue } from './queue';
import { PreviewManager } from './preview';
import { ProjectRunner } from './project-runner';
import { configView, loadServerModelConfig, resolveServerOptions, loadProjectProfile, saveProjectProfile, projectProfileTemplate } from './config';
import { scanProject } from './project-scanner';
import type {
......@@ -104,6 +105,7 @@ export interface ServerDeps {
store: JobStore;
queue: JobQueue;
preview: PreviewManager;
projectRunner: ProjectRunner;
opts: ReturnType<typeof resolveServerOptions>;
startTime: number;
serverVersion: string;
......@@ -118,7 +120,7 @@ export interface AppHandle {
}
export function createApp(deps: ServerDeps): AppHandle {
const { store, queue, preview, opts, startTime, serverVersion, coderioVersion, admin } = deps;
const { store, queue, preview, projectRunner, opts, startTime, serverVersion, coderioVersion, admin } = deps;
const sseClients = new Set<ServerResponse>();
const model = loadServerModelConfig();
......@@ -203,8 +205,27 @@ export function createApp(deps: ServerDeps): AppHandle {
try {
const url = new URL(req.url ?? '/', `http://localhost:${opts.port}`);
// 开发模式(COD_SERVE_WEB=0)下后端不托管 UI,根路径跳转前端 dev server。
const SERVE_WEB = process.env.COD_SERVE_WEB !== '0';
if (!SERVE_WEB && req.method === 'GET' && url.pathname === '/') {
const webPort = process.env.COD_WEB_PORT || '5173';
res.writeHead(302, { Location: `http://localhost:${webPort}/` });
res.end();
return;
}
// ---- 就绪探针(轻量、首屏即开)----
// 端口仅在引擎加载 + sqlite 初始化全部完成后才 listen(),因此本端点
// 一旦返回 200,即可认定后端已完全就绪、可接收 /api/generate。前端用它
// 在「重启后端」的 boot 窗口期内门控「开始生成」按钮,避免点进未就绪的端口。
if (req.method === 'GET' && url.pathname === '/api/health') {
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ ok: true, uptime: Math.round(process.uptime()) }));
return;
}
// ---- Built web static assets (apps/web/dist) ----
if (req.method === 'GET' && WEB_DIST && url.pathname.startsWith('/assets/')) {
if (SERVE_WEB && 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);
......@@ -213,7 +234,7 @@ export function createApp(deps: ServerDeps): AppHandle {
}
// ---- SPA root / index ----
if (req.method === 'GET' && (url.pathname === '/' || url.pathname === '/index.html')) {
if (SERVE_WEB && req.method === 'GET' && (url.pathname === '/' || url.pathname === '/index.html')) {
const idx = resolveIndexHtml();
if (existsSync(idx)) {
serveStaticFile(res, idx);
......@@ -226,6 +247,7 @@ export function createApp(deps: ServerDeps): AppHandle {
// ---- SPA fallback (client-side routing, non-asset GET) ----
if (
SERVE_WEB &&
req.method === 'GET' &&
!url.pathname.startsWith('/api') &&
!path.extname(url.pathname)
......@@ -252,6 +274,7 @@ export function createApp(deps: ServerDeps): AppHandle {
}
broadcast('jobs', store.list()); // replay current jobs snapshot
res.write(`event: preview\ndata: ${JSON.stringify(preview.state)}\n\n`);
res.write(`event: projectRun\ndata: ${JSON.stringify(projectRunner.getStatus())}\n\n`);
const ping = setInterval(() => {
try {
res.write(': ping\n\n');
......@@ -418,6 +441,8 @@ export function createApp(deps: ServerDeps): AppHandle {
: opts.outputDir,
appName: body.appName || 'my-app',
target: body.target ?? null,
stack: body.stack ?? null,
fillContainer: body.fillContainer ?? true,
resultDir: null,
reportPath: null,
error: null,
......@@ -567,10 +592,44 @@ export function createApp(deps: ServerDeps): AppHandle {
return;
}
// ---- GET /api/project/run (target-project dev-server status) ----
if (req.method === 'GET' && url.pathname === '/api/project/run') {
sendJson(res, 200, projectRunner.getStatus());
return;
}
// ---- POST /api/project/run (launch target project dev server) ----
if (req.method === 'POST' && url.pathname === '/api/project/run') {
const raw = await readBody(req);
let body: { dir?: string } = {};
try {
body = JSON.parse(raw || '{}');
} catch {
/* ignore */
}
const dir = (body.dir || loadProjectProfile()?.rootDir || '').trim();
if (!dir) {
sendJson(res, 400, { ok: false, error: '未配置工作目录(请先在「项目接入」中选择目标项目根)' });
return;
}
const r = projectRunner.start(dir);
sendJson(res, r.ok ? 200 : 409, { ok: r.ok, error: r.error });
return;
}
// ---- POST /api/project/run/stop ----
if (req.method === 'POST' && url.pathname === '/api/project/run/stop') {
projectRunner.stop();
sendJson(res, 200, { ok: true });
return;
}
// ---- POST /api/admin/restart (self-restart) ----
if (req.method === 'POST' && url.pathname === '/api/admin/restart') {
sendJson(res, 200, { ok: true, message: '服务正在重启…' });
res.on('finish', () => admin.restart());
// 直接触发重启,不依赖 res.on('finish'):否则连接被提前关闭时
// 回调可能不触发,导致「点了重启却没反应」。
admin.restart();
return;
}
......
......@@ -24,6 +24,13 @@ export interface GenerationTarget {
slot?: string;
}
/** Tech stack chosen for a standalone generation. */
export interface TechStack {
framework: string;
styling?: string;
componentLibrary?: string;
}
export interface Job {
id: string;
status: JobStatus;
......@@ -33,6 +40,10 @@ export interface Job {
appName: string;
/** Where the generated code targets (standalone / new-page / modify-slot). */
target: GenerationTarget | null;
/** Tech stack chosen for standalone generation (null for project modes). */
stack?: TechStack | null;
/** Whether the generated root should fill its host container (default true). */
fillContainer?: boolean;
/** Absolute path to the generated <outputDir>/coderio/<figmaName> workspace. */
resultDir: string | null;
reportPath: string | null;
......@@ -52,6 +63,10 @@ export interface GenerateRequest {
appName?: string;
/** Where the generated code should target. */
target?: GenerationTarget | null;
/** Tech stack for standalone generation (ignored for project modes). */
stack?: TechStack | null;
/** Whether the generated root should fill its host container (default true). */
fillContainer?: boolean;
}
export interface LogEntry {
......@@ -129,3 +144,28 @@ export interface SystemStatus {
env: EnvInfo;
jobs: JobStats;
}
export type ProjectManager = 'npm' | 'pnpm' | 'yarn';
/**
* Runtime state of the target-project dev server launched by the user from the
* "项目接入" panel. Distinct from {@link PreviewState} (which serves the code
* coderio generates into an isolated dir); this launches the *user's own*
* project so freshly generated code dropped inside it can be inspected live.
*/
export interface ProjectRunState {
running: boolean;
/** Absolute path of the launched project root. */
dir: string | null;
/** The npm script used to start it (dev/start/serve…). */
script: string | null;
/** Package manager resolved from the project's lockfile. */
manager: ProjectManager | null;
/** LAN-reachable URL (for opening from another device). */
url: string | null;
/** http://localhost:<port>/ for the same-machine browser/iframe. */
localUrl: string | null;
port: number | null;
pid: number | null;
error: string | null;
}
......@@ -14,10 +14,15 @@ import {
AlertTriangle,
CheckCircle2,
Layers,
Play,
Square,
ExternalLink,
Loader2,
} from 'lucide-react';
import { api } from '@/lib/api';
import { api, onSSE } from '@/lib/api';
import type {
ProjectProfile,
ProjectRunState,
TokenCategory,
TokenMapping,
ComponentMapping,
......@@ -88,6 +93,8 @@ export function ProjectAccessPanel() {
const [tab, setTab] = useState<TabKey>('meta');
const [dirty, setDirty] = useState(false);
const [rootDirDraft, setRootDirDraft] = useState('');
const [run, setRun] = useState<ProjectRunState | null>(null);
const [runBusy, setRunBusy] = useState(false);
const load = useCallback(async () => {
setLoading(true);
......@@ -107,6 +114,49 @@ export function ProjectAccessPanel() {
void load();
}, [load]);
// 初始拉一次目标项目运行态作为快照;随后完全由 SSE 的 'projectRun' 事件推送更新,
// 不再使用任何 setInterval 轮询(ProjectRunner 在启动 / 停止 / 端口识别时都会 broadcast 该事件)。
useEffect(() => {
let alive = true;
api.getProjectRun().then((s) => { if (alive) setRun(s); }).catch(() => {});
return () => { alive = false; };
}, []);
useEffect(() => {
return onSSE('projectRun', (data) => setRun(data as ProjectRunState));
}, []);
const runDir = (rootDirDraft || profile?.rootDir || '').trim();
const handleRun = useCallback(async () => {
if (!runDir) {
toast.error('请先选择工作目录');
return;
}
setRunBusy(true);
try {
const r = await api.startProject(runDir);
if (r.ok) toast.success('正在启动目标项目…(识别到端口后会自动显示)');
else toast.error('启动失败', { description: r.error });
} catch (e) {
toast.error('启动失败', { description: e instanceof Error ? e.message : String(e) });
} finally {
setRunBusy(false);
}
}, [runDir]);
const handleStop = useCallback(async () => {
setRunBusy(true);
try {
await api.stopProject();
toast.success('已停止目标项目');
} catch (e) {
toast.error('停止失败', { description: e instanceof Error ? e.message : String(e) });
} finally {
setRunBusy(false);
}
}, []);
const update = useCallback((patch: Partial<ProjectProfile>) => {
setProfile((p) => (p ? { ...p, ...patch } : p));
setDirty(true);
......@@ -280,6 +330,56 @@ export function ProjectAccessPanel() {
</Button>
</div>
{/* 启动目标项目 */}
<div className="mt-3 flex flex-col gap-2 rounded-xl border border-border bg-muted/30 p-3 sm:flex-row sm:items-center sm:justify-between">
<div className="flex min-w-0 items-center gap-2 text-xs">
<Play className="h-3.5 w-3.5 text-primary" />
<span className="font-medium">目标项目</span>
{run?.running ? (
<Badge variant="success" className="px-2 py-0.5">运行中</Badge>
) : (
<Badge variant="neutral" className="px-2 py-0.5">已停止</Badge>
)}
{run?.script && (
<span className="truncate font-mono text-muted-foreground">
{run.manager} run {run.script}
</span>
)}
{run?.localUrl && (
<a href={run.localUrl} target="_blank" rel="noreferrer" className="truncate font-mono text-primary hover:underline">
{run.localUrl}
</a>
)}
{run?.error && !run.running && (
<span className="truncate text-rose-500">{run.error}</span>
)}
</div>
<div className="flex shrink-0 items-center gap-2">
{!run?.running ? (
<Button size="sm" onClick={handleRun} disabled={runBusy || !runDir}>
{runBusy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
启动项目
</Button>
) : (
<Button size="sm" variant="destructive" onClick={handleStop} disabled={runBusy}>
{runBusy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Square className="h-4 w-4" />}
停止
</Button>
)}
{run?.localUrl && (
<a
href={run.localUrl}
target="_blank"
rel="noreferrer"
className="flex h-8 w-8 items-center justify-center rounded-lg border border-border text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
title="新窗口打开"
>
<ExternalLink className="h-4 w-4" />
</a>
)}
</div>
</div>
{summary && (profile.components.length || profile.utils.length || profile.tokens.length) ? (
<div className="mt-3 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
<span>已识别</span>
......
......@@ -98,6 +98,30 @@ export const ROUTING_PRESETS = [
'其他',
];
/* ----------------------- 技术栈预设(生成目标用) ----------------------- */
/** 一个可点选的技术栈组合(框架 + 样式 + 组件库)。 */
export interface StackPreset {
id: string;
label: string;
framework: string;
styling?: string;
componentLibrary?: string;
}
/**
* 工作台「生成目标 → 技术栈」的预设卡片。新增组合只需在此追加一项;
* 引擎侧通过 framework 字段(含 "vue" 走 Vue 策略,否则 React)决定生成策略。
*/
export const STACK_PRESETS: StackPreset[] = [
{ id: 'react-antd', label: 'React + Ant Design', framework: 'React 18', styling: 'CSS Modules', componentLibrary: 'Ant Design' },
{ id: 'react-tailwind', label: 'React + Tailwind', framework: 'React 18', styling: 'Tailwind CSS', componentLibrary: '无(原生元素)' },
{ id: 'react-shadcn', label: 'React + shadcn/ui', framework: 'React 18', styling: 'Tailwind CSS', componentLibrary: 'shadcn/ui' },
{ id: 'react-mui', label: 'React + MUI', framework: 'React 18', styling: 'Emotion', componentLibrary: 'Material UI (MUI)' },
{ id: 'vue-elementplus', label: 'Vue 3 + Element Plus', framework: 'Vue 3', styling: 'CSS', componentLibrary: 'Element Plus' },
{ id: 'vue-antdv', label: 'Vue 3 + Ant Design Vue', framework: 'Vue 3', styling: 'Less', componentLibrary: 'Ant Design Vue' },
];
/* ----------------------- 浏览器安全路径工具 ----------------------- */
function norm(p: string): string {
......
......@@ -8,24 +8,78 @@ import type {
SystemStatus,
ProjectProfile,
FsListResult,
ProjectRunState,
} 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 ?? {}) },
});
// 后端重启宽限期:重启后短时间内,网络错误/5xx 属「后端短暂不可用」,
// http() 会静默重试,避免重启窗口期弹出一堆「请求失败」。宽限期外仍照常报错。
let backendRestartingUntil = 0;
export function markBackendRestarting(cooldownMs = 9000): void {
backendRestartingUntil = Date.now() + cooldownMs;
}
// 后端被「有意停止」标记:此时常规 /api 请求经 Vite 代理会得到 5xx/连接错误,
// 我们把它标记为非意外错误,避免刷「请求失败」;同时 UI 据此显示「已停止」状态。
let backendKnownDown = false;
export function setBackendKnownDown(v: boolean): void {
backendKnownDown = v;
}
export function isBackendDownError(e: unknown): boolean {
return (e as { expectedDown?: boolean })?.expectedDown === true;
}
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
async function httpOnce<T>(path: string, init?: RequestInit): Promise<T> {
let res: Response;
try {
res = await fetch(BASE + path, {
...init,
headers: { 'Content-Type': 'application/json', ...(init?.headers ?? {}) },
});
} catch (e) {
// 网络层错误(后端已停止,代理连不上)。已知后端被有意停止时标记为非意外错误。
if (backendKnownDown && path.startsWith('/api')) {
throw Object.assign(new Error('后端未运行'), { status: 0, expectedDown: true });
}
throw e;
}
const text = await res.text();
const data = text ? JSON.parse(text) : null;
if (!res.ok) {
throw new Error(data?.error || `请求失败 (${res.status})`);
const err = Object.assign(new Error(data?.error || `请求失败 (${res.status})`), {
status: res.status,
});
// 后端被有意停止时,常规 /api 请求会经 Vite 代理得到 5xx,标记为非意外错误。
if (backendKnownDown && path.startsWith('/api') && res.status >= 500) {
(err as { expectedDown?: boolean }).expectedDown = true;
}
throw err;
}
return data as T;
}
async function http<T>(path: string, init?: RequestInit): Promise<T> {
if (Date.now() < backendRestartingUntil) {
let lastErr: unknown;
for (let i = 0; i < 12; i++) {
try {
return await httpOnce<T>(path, init);
} catch (e) {
const status = (e as { status?: number })?.status;
// 仅对「网络错误(status 缺失) / 5xx」重试;业务 4xx 立即抛出。
lastErr = e;
if (status != null && status < 500) throw e;
await sleep(400);
}
}
throw lastErr;
}
return httpOnce<T>(path, init);
}
export const api = {
getConfig: () => http<ServerConfigView>('/api/config'),
generate: (req: GenerateRequest) =>
......@@ -73,41 +127,124 @@ export const api = {
http<FsListResult>(
'/api/fs/list' + (dir ? `?dir=${encodeURIComponent(dir)}` : ''),
),
getProjectRun: () => http<ProjectRunState>('/api/project/run'),
startProject: (dir: string) =>
http<{ ok: boolean; error?: string }>('/api/project/run', {
method: 'POST',
body: JSON.stringify({ dir }),
}),
stopProject: () =>
http<{ ok: boolean }>('/api/project/run/stop', { method: 'POST' }),
// ---- 后端生命周期(由开发模式 supervisor 管理,见 scripts/dev.mjs)----
// 这些请求走 /devctl 代理到 supervisor(4174),supervisor 常驻,即使后端已停止
// 也能接收启动指令。生产单进程模式无 supervisor,这些调用会失败。
backendStatus: () => http<{ running: boolean }>('/devctl/backend/status'),
startBackend: () =>
http<{ ok: boolean }>('/devctl/backend/start', { method: 'POST' }),
stopBackend: () =>
http<{ ok: boolean }>('/devctl/backend/stop', { method: 'POST' }),
restartBackend: () =>
http<{ ok: boolean }>('/devctl/backend/restart', { method: 'POST' }),
// 停止全部:请求 supervisor 自杀式退出(连同前端 Vite 与后端一起回收)。
// 仅开发模式(supervisor 常驻)可用;之后需重新运行 npm run dev 启动。
shutdownDev: () =>
http<{ ok: boolean }>('/devctl/shutdown', { method: 'POST' }),
};
export type SSEEventName = 'log' | 'jobs' | 'preview' | string;
/**
* 直接探测后端就绪状态(不走 http() 的重试/冷却机制,静默吞掉网络错误)。
* 后端端口仅在引擎加载 + sqlite 初始化完成后才 listen(),故本调用返回 true
* 即代表后端已完全就绪、可安全发起 /api/generate。用于「重启后端」boot 窗口期
* 门控「开始生成」按钮,避免点进尚未就绪的端口报 ECONNREFUSED。
*/
export async function checkBackendHealth(): Promise<boolean> {
try {
const res = await fetch(BASE + '/api/health', {
headers: { 'Content-Type': 'application/json' },
});
// 只要后端回了任何 HTTP 响应(含 404,来自尚未升级的旧后端)即说明端口已开、
// 后端已就绪,可安全发起 /api/generate;仅网络层错误(端口未开 / ECONNREFUSED)
// 代表后端仍在 boot 中。这样对「旧后端(无 /api/health)」也向后兼容。
return res.status < 500;
} catch {
return false;
}
}
export type SSEEventName = 'log' | 'jobs' | 'preview' | 'projectRun' | 'system' | 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 {
// 全局单例 SSE 连接:整个应用只建立一条 /api/stream,所有组件通过 onSSE 订阅
// 特定事件。避免每个组件各开一条连接、也彻底消除「前端用 setInterval 轮询后端状态」的刷屏。
// 后端在状态变化时通过 hub.broadcast 推送(jobs / preview / projectRun 等),SSE 连接建立时
// 还会 replay 一次当前快照(见 server.ts 的 /api/stream 处理)。
let sseInstance: EventSource | null = null;
const sseEventSubs = new Map<SSEEventName, Set<(data: unknown) => void>>();
const sseOpenSubs = new Set<() => void>();
const sseCloseSubs = new Set<() => void>();
const SSE_EVENTS: SSEEventName[] = ['log', 'jobs', 'preview', 'projectRun', 'system'];
function ensureSSE(): EventSource {
if (sseInstance) return sseInstance;
const es = new EventSource('/api/stream');
const handle = (name: SSEEventName) => (e: MessageEvent) => {
try {
onMessage({ event: name, data: JSON.parse(e.data) });
} catch {
/* ignore malformed */
}
for (const name of SSE_EVENTS) {
es.addEventListener(name, (e: MessageEvent) => {
try {
const data = JSON.parse(e.data);
sseEventSubs.get(name)?.forEach((h) => h(data));
} catch {
/* ignore malformed */
}
});
}
es.onopen = () => sseOpenSubs.forEach((f) => f());
es.onerror = () => sseCloseSubs.forEach((f) => f());
sseInstance = es;
return es;
}
/** 订阅某个 SSE 事件,返回取消订阅函数。 */
export function onSSE(
event: SSEEventName,
handler: (data: unknown) => void,
): () => void {
ensureSSE();
if (!sseEventSubs.has(event)) sseEventSubs.set(event, new Set());
sseEventSubs.get(event)!.add(handler);
return () => {
sseEventSubs.get(event)?.delete(handler);
};
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);
}
/** 订阅 SSE 连接状态变化(打开 / 关闭),返回取消订阅函数。 */
export function onSSEStatus(
onOpen: () => void,
onClose: () => void,
): () => void {
ensureSSE();
sseOpenSubs.add(onOpen);
sseCloseSubs.add(onClose);
return () => {
sseOpenSubs.delete(onOpen);
sseCloseSubs.delete(onClose);
};
return () => es.close();
}
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());
}
......@@ -6,7 +6,7 @@ import {
useState,
type ReactNode,
} from 'react';
import { subscribeSSE } from './api';
import { onSSEStatus } from './api';
interface ConnectionContextValue {
connected: boolean;
......@@ -29,7 +29,7 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
useEffect(() => {
aliveRef.current = true;
const unsub = subscribeSSE(
const unsub = onSSEStatus(
() => {
if (!aliveRef.current) return;
setConnected(true);
......@@ -40,13 +40,8 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
setConnected(false);
},
);
// SSE 打开即视为已连接(即使尚未收到业务事件)
const t = window.setTimeout(() => {
if (aliveRef.current) setConnected(true);
}, 800);
return () => {
aliveRef.current = false;
window.clearTimeout(t);
unsub();
};
}, []);
......
......@@ -13,6 +13,10 @@ export interface Job {
outputDir: string;
appName: string;
target: GenerationTarget | null;
/** 生成时选定的技术栈(独立预览时);项目模式为 null。 */
stack?: TechStack | null;
/** 生成的页面是否撑满容器(默认 true)。 */
fillContainer?: boolean;
resultDir: string | null;
reportPath: string | null;
error: string | null;
......@@ -37,6 +41,17 @@ export interface GenerateRequest {
outputDir?: string;
appName?: string;
target?: GenerationTarget | null;
/** 生成前选定的技术栈(独立预览时生效;项目模式由「项目接入」画像决定,此处为 null)。 */
stack?: TechStack | null;
/** 生成的页面是否撑满容器(默认 true;固定宽度设计稿可选 false 居中)。 */
fillContainer?: boolean;
}
/** 一次生成所选的技术栈组合。 */
export interface TechStack {
framework: string;
styling?: string;
componentLibrary?: string;
}
export interface GenerateResponse {
......@@ -55,6 +70,21 @@ export interface PreviewState {
error: string | null;
}
export type ProjectManager = 'npm' | 'pnpm' | 'yarn';
/** Runtime state of the user's own target-project dev server (启动目标项目). */
export interface ProjectRunState {
running: boolean;
dir: string | null;
script: string | null;
manager: ProjectManager | null;
url: string | null;
localUrl: string | null;
port: number | null;
pid: number | null;
error: string | null;
}
export interface JobStats {
total: number;
queued: number;
......
......@@ -12,6 +12,8 @@ import {
XCircle,
Settings as SettingsIcon,
ServerCog,
Globe,
Rocket,
Boxes,
RotateCw,
Power,
......@@ -25,8 +27,8 @@ import {
ExternalLink,
type LucideIcon,
} from 'lucide-react';
import { api } from '@/lib/api';
import type { ServerConfigView, SystemStatus, PreviewState } from '@/lib/types';
import { api, markBackendRestarting, setBackendKnownDown, isBackendDownError } from '@/lib/api';
import type { ServerConfigView, SystemStatus, OrchestratorStatus, PreviewState } from '@/lib/types';
import { Badge } from '@/components/ui/badge';
import { PageHeader } from '@/components/layout/PageHeader';
import { ProjectAccessPanel } from '@/components/project/ProjectAccessPanel';
......@@ -165,12 +167,40 @@ export default function Settings() {
const [status, setStatus] = useState<SystemStatus | null>(null);
const [pending, setPending] = useState<string | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [sup, setSup] = useState<{ available: boolean; running: boolean }>({ available: true, running: true });
const { connected } = useConnection();
// supervisor / 后端在线状态:由 SSE 连接(connected)实时反映,不再轮询。
// 仅在「后端离线」时按需探测一次 supervisor 是否可达,决定显示「启动后端」还是「单进程模式」。
useEffect(() => {
if (connected) {
setSup({ available: true, running: true });
setBackendKnownDown(false);
return;
}
let alive = true;
api
.backendStatus()
.then((r) => {
if (!alive) return;
setSup({ available: true, running: r.running });
setBackendKnownDown(!r.running);
})
.catch(() => {
if (!alive) return;
setSup({ available: false, running: false });
});
return () => {
alive = false;
};
}, [connected]);
useEffect(() => {
api.getConfig().then(setCfg).catch(() => {}).finally(() => setLoading(false));
}, []);
// 拉取系统状态快照:初次进入拉一次,后端(重)连接后(connected false→true)再拉一次。
// 完全事件驱动,不再 setInterval 轮询。
const refresh = useCallback(async () => {
try {
const s = await api.getStatus();
......@@ -182,9 +212,16 @@ export default function Settings() {
}, []);
useEffect(() => {
refresh();
const t = window.setInterval(refresh, 3000);
return () => window.clearInterval(t);
if (!connected) return;
let alive = true;
api.getStatus().then((s) => { if (alive) setStatus(s); }).catch(() => {});
return () => {
alive = false;
};
}, [connected]);
useEffect(() => {
void refresh();
}, [refresh]);
const runAction = useCallback(
......@@ -194,7 +231,11 @@ export default function Settings() {
await fn();
toast.success(okMsg);
} catch (e) {
toast.error(e instanceof Error ? e.message : '操作失败');
if (isBackendDownError(e)) {
toast.error('后端未运行,请先在「设置」中启动后端');
} else {
toast.error(e instanceof Error ? e.message : '操作失败');
}
return;
} finally {
setPending(null);
......@@ -309,6 +350,8 @@ export default function Settings() {
{loadError ? <span className="ml-1 text-xs text-amber-500">{loadError}</span> : null}
</div>
<LaunchOverview orchestrator={o} preview={pv} sup={sup} connected={connected} />
<div className="grid gap-4 lg:grid-cols-3">
<ServiceCard
icon={ServerCog}
......@@ -323,7 +366,7 @@ export default function Settings() {
<InfoRow icon={Gauge} label="并发上限" value={o?.maxConcurrent ?? '—'} mono />
<InfoRow icon={HardDrive} label="数据目录" value={o?.dataDir ?? '—'} mono />
<InfoRow icon={HardDrive} label="产物目录" value={o?.outputDir ?? '—'} mono />
<OrchestratorActions pending={pending} setPending={setPending} />
<OrchestratorActions pending={pending} setPending={setPending} sup={sup} />
</ServiceCard>
<ServiceCard
......@@ -417,49 +460,248 @@ export default function Settings() {
);
}
function LaunchOverview({
orchestrator,
preview,
sup,
connected,
}: {
orchestrator: OrchestratorStatus | undefined;
preview: PreviewState | undefined;
sup: { available: boolean; running: boolean };
connected: boolean;
}) {
const webAddr = 'http://localhost:5173';
const backendPort = orchestrator?.port ?? 4173;
const backendAddr = `http://localhost:${backendPort}`;
const supPort = 4174;
const items = [
{
icon: Globe,
label: '前端界面',
addr: webAddr,
running: true,
hint: '当前页面(你正在看)',
},
{
icon: ServerCog,
label: '后端 API',
addr: backendAddr,
running: connected,
hint: `端口 ${backendPort}`,
},
{
icon: Rocket,
label: 'supervisor',
addr: `http://localhost:${supPort}`,
running: sup.available,
hint: sup.available ? `控制端口 ${supPort}` : '单进程模式(无 supervisor)',
},
{
icon: Eye,
label: '预览服务',
addr: preview?.url ?? null,
running: preview?.running ?? false,
hint: preview?.running ? `端口 ${preview.port}` : '未启动',
},
];
return (
<div className="rounded-xl border border-border bg-muted/40 p-4">
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
<div className="flex items-center gap-2">
<Rocket className="h-4 w-4 text-primary" />
<h4 className="text-sm font-semibold">启动与访问入口</h4>
</div>
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span>启动命令</span>
<code className="rounded bg-emerald-500/10 px-2 py-0.5 font-mono text-[12px] text-emerald-500">
npm run dev
</code>
<span>(仓库根目录执行)</span>
</div>
</div>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
{items.map((it) => {
const Icon = it.icon;
return (
<div key={it.label} className="rounded-xl border border-border bg-card p-3">
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-1.5">
<Icon className="h-4 w-4 text-muted-foreground" />
<span className="text-sm font-medium">{it.label}</span>
</div>
<Badge variant={it.running ? 'success' : 'neutral'}>
{it.running ? '运行中' : '已停止'}
</Badge>
</div>
<div className="mt-2">
{it.addr ? (
<a
href={it.addr}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 truncate font-mono text-[12px] text-primary hover:underline"
>
{it.addr}
<ExternalLink className="h-3 w-3 shrink-0" />
</a>
) : (
<span className="font-mono text-[12px] text-muted-foreground">—</span>
)}
</div>
<div className="mt-1 text-xs text-muted-foreground">{it.hint}</div>
</div>
);
})}
</div>
<p className="mt-3 text-xs text-muted-foreground">
开发模式只需一次 <code className="rounded bg-muted px-1">npm run dev</code>
;其后端启停、重启、停止全部均在本页「编排服务」卡片操作。改后端或引擎代码后请点「重启」或重跑该命令。
</p>
</div>
);
}
function OrchestratorActions({
pending,
setPending,
sup,
}: {
pending: string | null;
setPending: (v: string | null) => void;
sup: { available: boolean; running: boolean };
}) {
// 生产单进程模式:没有 supervisor,停止即需手动重启。
if (!sup.available) {
return (
<div className="mt-4 flex flex-wrap items-center gap-2">
<button
type="button"
disabled={pending !== null}
onClick={() => {
if (!window.confirm('确定停止服务吗?停止后需手动重新启动后端进程。')) return;
setPending('shutdown');
api
.shutdownServer()
.then(() => toast.message('服务已停止,请手动重新启动'))
.catch((e: unknown) => toast.error(e instanceof Error ? e.message : '停止失败'))
.finally(() => setPending(null));
}}
className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-border px-3 text-xs font-medium text-muted-foreground transition-colors hover:border-rose-500/40 hover:bg-rose-500/10 hover:text-rose-400 disabled:opacity-50"
>
<Power className="h-3.5 w-3.5" />
停止服务
</button>
<span className="text-xs text-muted-foreground">
当前为单进程模式(无 supervisor),停止后需手动重启后端进程。
</span>
</div>
);
}
const doStart = () => {
setPending('start');
api
.startBackend()
.then(() => {
setBackendKnownDown(false);
markBackendRestarting();
toast.success('后端正在启动,请稍候…');
})
.catch((e: unknown) => toast.error(e instanceof Error ? e.message : '启动失败'))
.finally(() => setPending(null));
};
const doRestart = () => {
if (!window.confirm('确定重启编排服务吗?进行中的任务会中断,页面会短暂重连。')) return;
setPending('restart');
api
.restartBackend()
.then(() => {
setBackendKnownDown(false);
markBackendRestarting();
toast.success('服务正在重启,请稍候…');
})
.catch((e: unknown) => toast.error(e instanceof Error ? e.message : '重启失败'))
.finally(() => setPending(null));
};
const doStop = () => {
if (!window.confirm('确定停止后端吗?停止后可通过「启动后端」恢复,预览/生成将不可用。')) return;
setPending('stop');
api
.stopBackend()
.then(() => {
setBackendKnownDown(true);
toast.message('后端已停止,可随时点「启动后端」恢复');
})
.catch((e: unknown) => toast.error(e instanceof Error ? e.message : '停止失败'))
.finally(() => setPending(null));
};
const doShutdown = () => {
if (
!window.confirm(
'确定停止全部吗?将关闭前端、后端与开发服务(supervisor)。之后需重新运行 npm run dev 启动。',
)
)
return;
setPending('shutdown-dev');
api
.shutdownDev()
.then(() => toast.message('正在停止全部服务…'))
.catch((e: unknown) => toast.error(e instanceof Error ? e.message : '操作失败'))
.finally(() => setPending(null));
};
return (
<div className="mt-4 flex flex-wrap gap-2">
<button
type="button"
disabled={pending !== null}
onClick={() => {
if (!window.confirm('确定重启编排服务吗?进行中的任务会中断,页面会短暂重连。')) return;
setPending('restart');
api
.restartServer()
.then(() => toast.success('服务正在重启,请稍候…'))
.catch((e: unknown) => toast.error(e instanceof Error ? e.message : '重启失败'))
.finally(() => setPending(null));
}}
className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-border px-3 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50"
>
<RotateCw className={cn('h-3.5 w-3.5', pending === 'restart' && 'animate-spin')} />
重启
</button>
<div className="mt-4 flex flex-wrap items-center gap-2">
{!sup.running ? (
<button
type="button"
disabled={pending !== null}
onClick={doStart}
className="inline-flex h-8 items-center gap-1.5 rounded-lg bg-emerald-500 px-3 text-xs font-medium text-white transition-colors hover:bg-emerald-600 disabled:opacity-50"
>
<Play className={cn('h-3.5 w-3.5', pending === 'start' && 'animate-pulse')} />
启动后端
</button>
) : (
<>
<button
type="button"
disabled={pending !== null}
onClick={doRestart}
className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-border px-3 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50"
>
<RotateCw className={cn('h-3.5 w-3.5', pending === 'restart' && 'animate-spin')} />
重启
</button>
<button
type="button"
disabled={pending !== null}
onClick={doStop}
className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-border px-3 text-xs font-medium text-muted-foreground transition-colors hover:border-rose-500/40 hover:bg-rose-500/10 hover:text-rose-400 disabled:opacity-50"
>
<Power className="h-3.5 w-3.5" />
停止后端
</button>
</>
)}
<button
type="button"
disabled={pending !== null}
onClick={() => {
if (!window.confirm('确定停止服务吗?停止后需手动重新启动,页面将断开连接。')) return;
setPending('shutdown');
api
.shutdownServer()
.then(() => toast.message('服务已停止,请手动重新启动'))
.catch((e: unknown) => toast.error(e instanceof Error ? e.message : '停止失败'))
.finally(() => setPending(null));
}}
onClick={doShutdown}
className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-border px-3 text-xs font-medium text-muted-foreground transition-colors hover:border-rose-500/40 hover:bg-rose-500/10 hover:text-rose-400 disabled:opacity-50"
>
<Power className="h-3.5 w-3.5" />
停止服务
<Power className={cn('h-3.5 w-3.5', pending === 'shutdown-dev' && 'animate-pulse')} />
停止全部
</button>
{!sup.running && (
<span className="inline-flex items-center gap-1.5 rounded-full bg-amber-500/10 px-2.5 py-1 text-xs font-medium text-amber-500">
<AlertTriangle className="h-3.5 w-3.5" />
后端已停止
</span>
)}
</div>
);
}
......
......@@ -17,9 +17,11 @@ import {
Lock,
LayoutDashboard,
Layers,
Boxes,
} from 'lucide-react';
import { api, subscribeSSE } from '@/lib/api';
import type { Job, LogEntry, LogLevel, PreviewState, ValidationMode, GenerationTarget, GenerationTargetMode } from '@/lib/types';
import { api, subscribeSSE, checkBackendHealth } from '@/lib/api';
import type { Job, LogEntry, LogLevel, PreviewState, ProjectRunState, ValidationMode, GenerationTarget, GenerationTargetMode, ProjectProfile, TechStack } from '@/lib/types';
import { STACK_PRESETS } from '@/components/project/profile-presets';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
......@@ -46,13 +48,22 @@ const levelTag: Record<LogLevel, string> = {
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: '错误' },
];
// 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 ---------------- */
const SCHEME_RE = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//;
function parseScheme(url: string | null): 'http' | 'https' | null {
if (!url) return null;
const m = /^(https?):\/\//i.exec(url);
return m ? (m[1].toLowerCase() as 'http' | 'https') : null;
}
const stripScheme = (url: string) => url.replace(SCHEME_RE, '');
function jobProgress(j: Job): {
value: number;
......@@ -99,14 +110,71 @@ export default function Workbench() {
const [figmaUrl, setFigmaUrl] = useState('');
const [mode, setMode] = useState<ValidationMode>('code');
const [target, setTarget] = useState<GenerationTarget>({ mode: 'standalone' });
const [stack, setStack] = useState<TechStack | null>(() => {
try {
const saved = localStorage.getItem('coderio.workbench.stack');
if (saved) return JSON.parse(saved) as TechStack;
} catch {
/* ignore */
}
// 首次进入默认采用用户常用的 Vue 3 + Element Plus,避免「独立预览忘选技术栈
// → 静默回退成 React」的踩坑;随后每次选择都会持久化到 localStorage。
return STACK_PRESETS.find((s) => s.id === 'vue-elementplus') ?? null;
});
const [fillContainer, setFillContainer] = useState(true);
const [projectProfile, setProjectProfile] = useState<ProjectProfile | null>(null);
const [submitting, setSubmitting] = useState(false);
// 后端就绪门控:重启后端后引擎加载 + sqlite 初始化完成前端口未开,
// 此时点「开始生成」会 ECONNREFUSED。boot 期间轮询 /api/health,就绪前禁用按钮。
const [backendReady, setBackendReady] = useState(true);
// 持久化技术栈选择,避免刷新 / HMR 后丢失导致「独立预览意外生成 React」。
useEffect(() => {
try {
if (stack) localStorage.setItem('coderio.workbench.stack', JSON.stringify(stack));
else localStorage.removeItem('coderio.workbench.stack');
} catch {
/* ignore */
}
}, [stack]);
// 后端就绪探测:挂载后若后端尚未就绪(刚重启),持续轮询 /api/health,
// 就绪后放开「开始生成」。后端已在线时首轮即 true,不阻塞正常操作。
useEffect(() => {
let alive = true;
let timer: ReturnType<typeof setTimeout> | undefined;
const tick = async () => {
const ok = await checkBackendHealth();
if (!alive) return;
if (ok) {
setBackendReady(true);
return;
}
setBackendReady(false);
timer = setTimeout(tick, 1500);
};
void tick();
return () => {
alive = false;
if (timer) clearTimeout(timer);
};
}, []);
const handleSubmit = async () => {
if (!figmaUrl.trim()) return toast.error('请填写 Figma 链接');
if (!figmaUrl.includes('node-id=')) return toast.error('Figma 链接必须包含 ?node-id= 参数');
if (!backendReady) return toast.error('后端启动中,请稍候…', { description: '引擎与数据库初始化完成后即可生成' });
setSubmitting(true);
try {
const res = await api.generate({ figmaUrl: figmaUrl.trim(), mode, target });
const res = await api.generate({
figmaUrl: figmaUrl.trim(),
mode,
target,
// 仅独立预览时附带自选技术栈;项目模式由「项目接入」画像决定
stack: target.mode === 'standalone' ? stack : null,
// 默认撑满容器;固定宽度设计稿可取消
fillContainer,
});
toast.success('已提交生成任务', { description: res.message });
} catch (e) {
toast.error('提交失败', { description: e instanceof Error ? e.message : String(e) });
......@@ -117,7 +185,7 @@ export default function Workbench() {
/* ----- logs ----- */
const [logs, setLogs] = useState<LogEntry[]>([]);
const [filter, setFilter] = useState<LogLevel | 'all'>('all');
// const [filter, setFilter] = useState<LogLevel | 'all'>('all');
const [autoScroll, setAutoScroll] = useState(true);
const logRef = useRef<HTMLDivElement>(null);
const autoRef = useRef(autoScroll);
......@@ -128,6 +196,8 @@ export default function Workbench() {
/* ----- preview ----- */
const [state, setState] = useState<PreviewState | null>(null);
const [projectRun, setProjectRun] = useState<ProjectRunState | null>(null);
const [previewSource, setPreviewSource] = useState<'coderio' | 'target'>('coderio');
const [busy, setBusy] = useState(false);
const [reloadKey, setReloadKey] = useState(0);
......@@ -135,6 +205,8 @@ export default function Workbench() {
api.listJobs().then((r) => setJobs(r.jobs)).catch(() => {});
api.getLogs().then((r) => setLogs(r.logs.slice(-2000))).catch(() => {});
api.getPreview().then(setState).catch(() => {});
api.getProjectRun().then(setProjectRun).catch(() => {});
api.getProjectProfile().then((r) => setProjectProfile(r.profile ?? null)).catch(() => {});
const unsub = subscribeSSE((msg) => {
if (msg.event === 'log') {
......@@ -143,14 +215,16 @@ export default function Workbench() {
setJobs(msg.data as Job[]);
} else if (msg.event === 'preview') {
setState(msg.data as PreviewState);
} else if (msg.event === 'projectRun') {
setProjectRun(msg.data as ProjectRunState);
}
});
return unsub;
}, []);
const visibleLogs = useMemo(
() => (filter === 'all' ? logs : logs.filter((l) => l.level === filter)),
[logs, filter],
() => logs,
[logs],
);
useEffect(() => {
if (autoScroll && logRef.current) {
......@@ -184,9 +258,50 @@ export default function Workbench() {
setBusy(false);
}
};
const embedUrl = state?.localUrl ?? state?.url ?? null;
const running = !!state?.running;
const startTarget = async () => {
setBusy(true);
try {
// dir 留空:后端回退到已配置画像根目录
const r = await api.startProject('');
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 stopTarget = async () => {
setBusy(true);
try {
await api.stopProject();
toast.success('目标项目已停止');
} catch (e) {
toast.error('停止目标项目失败', { description: e instanceof Error ? e.message : String(e) });
} finally {
setBusy(false);
}
};
const coderioUrl = state?.localUrl ?? state?.url ?? null;
const targetUrl = projectRun?.localUrl ?? projectRun?.url ?? null;
const [overrideUrl, setOverrideUrl] = useState<string | null>(null);
const [scheme, setScheme] = useState<'http' | 'https'>('http');
const embedUrl = overrideUrl ?? (previewSource === 'target' ? targetUrl : coderioUrl);
const [embedUrlValue, setEmbedUrlValue] = useState(embedUrl ? stripScheme(embedUrl) : '');
// 切换预览源时清除自定义地址
useEffect(() => {
setOverrideUrl(null);
}, [previewSource]);
// 未使用自定义地址时,跟随自动检测地址更新输入框
useEffect(() => {
if (overrideUrl) return;
const u = previewSource === 'target' ? targetUrl : coderioUrl;
setEmbedUrlValue(u ? stripScheme(u) : '');
const s = parseScheme(u);
if (s) setScheme(s);
}, [previewSource, targetUrl, coderioUrl, overrideUrl]);
const running = previewSource === 'target' ? !!projectRun?.running : !!state?.running;
const clearAll = async () => {
if (!confirm('确定清空全部任务记录吗?进行中的任务会被中止,此操作不可撤销。')) return;
try {
......@@ -247,18 +362,39 @@ export default function Workbench() {
<Button
className="h-10 brand-gradient shadow-lg shadow-primary/25 transition-transform hover:scale-[1.01]"
onClick={handleSubmit}
disabled={submitting}
disabled={submitting || !backendReady}
>
{submitting ? (
{!backendReady ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : submitting ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Rocket className="h-4 w-4" />
)}
{submitting ? '提交中…' : '开始生成'}
{!backendReady ? '后端启动中…' : submitting ? '提交中…' : '开始生成'}
</Button>
<p className="mt-1.5 text-[11px] text-muted-foreground">
{!backendReady ? (
<span className="text-amber-500">后端正在初始化(引擎加载 + 数据库准备),就绪后按钮自动亮起</span>
) : target.mode === 'standalone' ? (
stack && stack.framework ? (
<>
将使用技术栈:
<span className="font-medium text-foreground">
{stack.framework}
{stack.componentLibrary ? ` + ${stack.componentLibrary}` : ''}
</span>
</>
) : (
<span className="text-amber-500">未选择技术栈,将默认生成 React</span>
)
) : (
<>独立预览技术栈取自「设置 → 项目接入」</>
)}
</p>
</div>
{/* ----- 生成目标 (target) ----- */}
<div className="flex flex-col gap-2 border-t border-border/60 pt-3 lg:flex-row lg:items-center">
<div className="flex flex-col gap-2 pt-3 lg:flex-row lg:items-center">
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
<Layers className="h-3.5 w-3.5 text-primary" /> 生成目标
</span>
......@@ -314,6 +450,125 @@ export default function Workbench() {
</>
)}
</div>
{/* ----- 技术栈 (tech stack) ----- */}
<div className="flex flex-col gap-2 pt-3 lg:flex-row lg:items-center">
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
<Boxes className="h-3.5 w-3.5 text-primary" /> 技术栈
</span>
{target.mode === 'standalone' ? (
<div className="flex flex-wrap items-center gap-1.5">
{STACK_PRESETS.map((s) => {
const active =
stack != null &&
stack.framework === s.framework &&
(stack.componentLibrary ?? '') === (s.componentLibrary ?? '');
return (
<button
key={s.id}
type="button"
onClick={() =>
setStack({
framework: s.framework,
styling: s.styling,
componentLibrary: s.componentLibrary,
})
}
className={cn(
'rounded-lg border px-2.5 py-1.5 text-xs font-medium transition-colors',
active
? 'border-primary/40 bg-primary/15 text-primary'
: 'border-border bg-card text-muted-foreground hover:bg-accent hover:text-foreground',
)}
>
{s.label}
</button>
);
})}
<button
type="button"
onClick={() =>
setStack((prev) =>
prev && prev.framework === '' ? null : { framework: '', styling: '', componentLibrary: '' },
)
}
className={cn(
'rounded-lg border px-2.5 py-1.5 text-xs font-medium transition-colors',
stack && stack.framework === ''
? 'border-primary/40 bg-primary/15 text-primary'
: 'border-dashed border-border text-muted-foreground hover:bg-accent hover:text-foreground',
)}
>
➕ 自定义
</button>
{stack && stack.framework === '' && (
<div className="flex flex-wrap items-center gap-1.5">
<select
className="h-8 rounded-md border border-border bg-card px-2 text-xs text-foreground"
value={stack.framework}
onChange={(e) => setStack((p) => ({ ...(p as TechStack), framework: e.target.value }))}
>
<option value="">框架…</option>
<option value="React 18">React 18</option>
<option value="React 19">React 19</option>
<option value="Vue 3">Vue 3</option>
</select>
<select
className="h-8 rounded-md border border-border bg-card px-2 text-xs text-foreground"
value={stack.styling ?? ''}
onChange={(e) => setStack((p) => ({ ...(p as TechStack), styling: e.target.value }))}
>
<option value="">样式…</option>
<option value="Tailwind CSS">Tailwind CSS</option>
<option value="CSS Modules">CSS Modules</option>
<option value="Less">Less</option>
<option value="原生 CSS">原生 CSS</option>
</select>
<select
className="h-8 rounded-md border border-border bg-card px-2 text-xs text-foreground"
value={stack.componentLibrary ?? ''}
onChange={(e) => setStack((p) => ({ ...(p as TechStack), componentLibrary: e.target.value }))}
>
<option value="">组件库…</option>
<option value="Ant Design">Ant Design</option>
<option value="Element Plus">Element Plus</option>
<option value="Ant Design Vue">Ant Design Vue</option>
<option value="无(原生元素)">无(原生元素)</option>
</select>
</div>
)}
</div>
) : (
<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
<span className="rounded-lg border border-border bg-card px-2.5 py-1.5">
{projectProfile?.framework || '未配置'} + {projectProfile?.componentLibrary || '未配置'}
</span>
<span>取自「设置 → 项目接入」</span>
</div>
)}
</div>
{/* ----- 撑满容器 (fill container) ----- */}
<div className="flex flex-col gap-2 pt-3 lg:flex-row lg:items-center">
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
<MonitorSmartphone className="h-3.5 w-3.5 text-primary" /> 撑满容器
</span>
<button
type="button"
onClick={() => setFillContainer((v) => !v)}
className={cn(
'rounded-lg px-3 py-1.5 text-xs font-medium transition-colors',
fillContainer
? 'bg-primary/15 text-primary'
: 'border border-border bg-card text-muted-foreground hover:bg-accent hover:text-foreground',
)}
title="关闭后按 Figma 帧原始宽度居中渲染,适合固定宽度的设计稿"
>
{fillContainer ? '撑满(默认)' : '按设计稿宽度'}
</button>
<span className="text-[11px] text-muted-foreground">
关闭后按 Figma 帧原始宽度居中,适合固定宽度设计稿
</span>
</div>
<p className="mt-2 flex items-center gap-3 text-[11px] text-muted-foreground">
<span>链接需包含 <code className="rounded bg-muted px-1">?node-id=</code> 以定位画板</span>
......@@ -341,7 +596,7 @@ export default function Workbench() {
</span>
</div>
<div className="flex items-center gap-2">
<div className="hidden gap-1.5 sm:flex">
{/* <div className="hidden gap-1.5 sm:flex">
{filterOptions.map((o) => (
<button
key={o.key}
......@@ -356,7 +611,7 @@ export default function Workbench() {
{o.label}
</button>
))}
</div>
</div>*/}
<button
onClick={() => setAutoScroll((v) => !v)}
className={cn(
......@@ -445,6 +700,11 @@ export default function Workbench() {
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
{j.target?.mode === 'new-page' && <span className="rounded bg-primary/10 px-1.5 py-0.5 text-primary">新页</span>}
{j.target?.mode === 'modify-slot' && <span className="rounded bg-primary/10 px-1.5 py-0.5 text-primary">改区</span>}
{j.target?.mode === 'standalone' && j.stack && (
<span className="rounded bg-emerald-500/10 px-1.5 py-0.5 text-emerald-400">
{j.stack.framework}{j.stack.componentLibrary ? ` + ${j.stack.componentLibrary}` : ''}
</span>
)}
{modeLabel[j.mode]}
</span>
</div>
......@@ -499,45 +759,71 @@ export default function Workbench() {
{/* Preview */}
<section className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-2xl border border-border bg-card shadow-sm min-h-[60vh] lg:min-h-0">
<div className="flex items-center justify-between gap-3 border-b border-border bg-muted/40 px-4 py-2.5">
<div className="flex items-center gap-2 text-sm font-medium">
<MonitorSmartphone className="h-4 w-4 text-primary" /> 预览
{running ? (
<Badge variant="success" className="px-2 py-0.5">运行中</Badge>
) : (
<Badge variant="neutral" className="px-2 py-0.5">已停止</Badge>
)}
</div>
<div className="flex items-center gap-2">
{!running ? (
<Button size="sm" onClick={startPreview} disabled={busy}>
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
启动预览
</Button>
) : (
<Button size="sm" variant="destructive" onClick={stopPreview} disabled={busy}>
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Square className="h-4 w-4" />}
停止
</Button>
)}
</div>
</div>
{state?.error && (
<div className="px-4 pt-2">
<div className="rounded-lg border border-rose-500/30 bg-rose-500/10 p-2 text-xs text-rose-500">
{state.error}
<div className="flex items-center gap-3">
<div className="flex items-center gap-2 text-sm font-medium">
<MonitorSmartphone className="h-4 w-4 text-primary" /> 预览
{running ? (
<Badge variant="success" className="px-2 py-0.5">运行中</Badge>
) : (
<Badge variant="neutral" className="px-2 py-0.5">已停止</Badge>
)}
</div>
<div className="flex items-center gap-1 rounded-lg border border-border bg-card p-0.5">
<button
onClick={() => setPreviewSource('coderio')}
className={cn(
'rounded-md px-2.5 py-1 text-xs font-medium transition-colors',
previewSource === 'coderio' ? 'bg-primary/15 text-primary' : 'text-muted-foreground hover:bg-accent',
)}
>
Coderio 预览
</button>
<button
onClick={() => setPreviewSource('target')}
className={cn(
'rounded-md px-2.5 py-1 text-xs font-medium transition-colors',
previewSource === 'target' ? 'bg-primary/15 text-primary' : 'text-muted-foreground hover:bg-accent',
)}
>
目标项目
</button>
</div>
</div>
)}
<div className="flex min-h-0 shrink-0 h-11">
<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">
<Globe className="h-4 w-4 shrink-0 text-muted-foreground" />
<span className="truncate font-mono text-xs text-muted-foreground">
{embedUrl ?? '未启动预览服务'}
</span>
{/* <span className="truncate font-mono text-xs text-muted-foreground">
{embedUrl ?? (previewSource === 'target' ? '目标项目未启动' : '未启动预览服务')}
</span> */}
<button
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"
title={`切换协议,当前 ${scheme}://`}
>
{scheme}://
</button>
<Input
value={embedUrlValue}
onChange={(e) => setEmbedUrlValue(e.target.value)}
placeholder="输入地址,无需填写协议头"
className="w-full h-8 px-2.5 py-1 text-xs font-medium text-muted-foreground"
/>
</div>
<div className="flex items-center gap-1 px-2">
<div className="flex items-center gap-1 px-2">
<button
title="确定"
onClick={() => {
const raw = embedUrlValue?.trim();
if (!raw) return;
const v = SCHEME_RE.test(raw) ? raw : `${scheme}://${raw}`;
setOverrideUrl(v);
setReloadKey((k) => k + 1);
}}
disabled={!embedUrlValue?.trim()}
className="flex h-8 items-center justify-center rounded-lg border border-border px-2.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-40"
>
确定
</button>
<button
disabled={!running}
onClick={() => setReloadKey((k) => k + 1)}
......@@ -559,8 +845,39 @@ export default function Workbench() {
<ExternalLink className="h-4 w-4" />
</a>
</div>
</div>
<div className="flex items-center gap-2">
{!running ? (
<Button
size="sm"
onClick={previewSource === 'target' ? startTarget : startPreview}
disabled={busy}
>
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
{previewSource === 'target' ? '启动项目' : '启动预览'}
</Button>
) : (
<Button
size="sm"
variant="destructive"
onClick={previewSource === 'target' ? stopTarget : stopPreview}
disabled={busy}
>
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Square className="h-4 w-4" />}
停止
</Button>
)}
</div>
</div>
{state?.error && (
<div className="px-4 pt-2">
<div className="rounded-lg border border-rose-500/30 bg-rose-500/10 p-2 text-xs text-rose-500">
{state.error}
</div>
</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" />
......@@ -569,9 +886,11 @@ export default function Workbench() {
<div className="brand-gradient flex h-12 w-12 items-center justify-center rounded-2xl shadow-lg shadow-primary/25">
<LayoutDashboard className="h-6 w-6 text-white" />
</div>
<p className="text-sm font-medium">尚未启动预览</p>
<p className="text-sm font-medium">{previewSource === 'target' ? '目标项目未启动' : '尚未启动预览'}</p>
<p className="max-w-sm text-xs text-muted-foreground">
完成一次生成后点击「启动预览」,即可在此实时查看运行效果。
{previewSource === 'target'
? '在「设置 → 项目接入」选择工作目录后,点「启动项目」即可在此实时预览目标项目运行效果。'
: '完成一次生成后点击「启动预览」,即可在此实时查看运行效果。'}
</p>
</div>
)}
......
......@@ -15,11 +15,23 @@ export default defineConfig({
},
server: {
port: 5173,
// 绑定 IPv4,确保 127.0.0.1 与 localhost 均可访问(Windows 上 localhost
// 默认优先 ::1,会导致 127.0.0.1 直连代理/SSE 时失败)。
host: '127.0.0.1',
proxy: {
'/api': {
target: 'http://localhost:4173',
// 用 127.0.0.1 而非 localhost:Windows 上 localhost 默认优先解析 IPv6(::1),
// 而后端仅监听 IPv4,会导致间歇 ECONNREFUSED(Vite 自身也绑 127.0.0.1)。
target: 'http://127.0.0.1:4173',
changeOrigin: true,
},
// supervisor 控制端口(scripts/dev.mjs):后端启动/停止/重启。
// 它独立于后端常驻,因此「停止后端」后前端仍能向其发启动指令。
'/devctl': {
target: 'http://127.0.0.1:4174',
changeOrigin: true,
rewrite: (p) => p.replace(/^\/devctl/, ''),
},
},
},
build: {
......
......@@ -9,6 +9,7 @@
"server:dev": "tsx watch apps/server/src/index.ts",
"web": "npm --prefix apps/web run dev",
"web:build": "npm --prefix apps/web run build",
"dev": "node scripts/dev.mjs",
"build:all": "npm run coderio:build && npm run web:build"
},
"engines": {
......
......@@ -24,6 +24,7 @@ export const registerD2PCommand = (program: Command) => {
protocol: undefined,
messages: [],
config: {},
fillContainer: true,
});
logger.printSuccessLog('Successfully completed Design to Protocol conversion!');
......
......@@ -31,6 +31,7 @@ export const registerP2CCommand = (program: Command) => {
},
messages: [],
config: {},
fillContainer: true,
};
await initialProject(state);
await generateCode(state);
......
......@@ -80,6 +80,7 @@ export function registerValidateCommand(program: Command): void {
protocol,
messages: [],
config,
fillContainer: true,
});
// If we reach here, validation passed
......
......@@ -65,6 +65,13 @@ export interface Design2CodeOptions {
page?: string;
slot?: string;
} | null;
/**
* Whether the generated root component should fill its host container.
* Defaults to `true` (embed-into-app-shell scenario). When `false`, the
* root renders at the Figma frame's intrinsic width, centered, without
* stretching to a wide viewport (useful for fixed-width standalone previews).
*/
fillContainer?: boolean;
}
export async function design2code(url: string, mode?: ValidationMode, options?: Design2CodeOptions): Promise<void> {
......@@ -169,6 +176,7 @@ export async function design2code(url: string, mode?: ValidationMode, options?:
config: {
validationMode,
},
fillContainer: opts.fillContainer ?? true,
};
await graph.invoke(state, config);
......
......@@ -3,6 +3,7 @@
// ============================================
import { getProjectProfile, renderProfileConstraint } from '../../utils/project-profile';
import { buildComponentUsageGuidance, buildStretchGuidance } from './strategies/component-usage';
/**
* Renders the target-project profile (components / tokens / utils / conventions)
......@@ -46,9 +47,36 @@ const ASSETS_HANDLING = `
- **Usage**: \`<img src={ArXivIcon} />\`, do not use backgroundImage property.
- **NEVER** use the string path directly in JSX or styles.`;
const ICON_PROP_GUIDANCE = `
- **CRITICAL — Icon props are React nodes/components, NOT image URLs (a wrong usage crashes the render)**:
- An imported asset file (\`import X from '@/assets/foo.svg'\`) is a **string URL** at runtime (in dev it may be a \`data:image/svg+xml,...\` data URI). It is NEVER a React component.
- A URL string may ONLY be used as: (1) \`<img src={X} />\`, or (2) a CSS \`backgroundImage: url(...)\` value (use a relative/absolute path there, NOT the \`@\` alias).
- NEVER pass it to a prop that expects a **React node/component**, such as Ant Design \`Input\`/\`Select\` \`suffix\`/\`prefix\`, \`Button\`'s \`icon\`, or MUI \`startIcon\`/\`endIcon\`. Passing a URL there makes React call \`createElement('data:image/svg+xml,...')\` → \`InvalidCharacterError\`.
- ✅ To show a custom arrow/icon: import an ICON COMPONENT from the kit's icon package (e.g. Ant Design: \`import { ArrowDownOutlined } from '@ant-design/icons';\` then \`<Select suffixIcon={<ArrowDownOutlined />}>\`) or use a plain \`<img>\`/CSS background for decorative icons.
- ❌ NEVER do \`<Select suffixIcon={importedSvgUrl}>\` where \`importedSvgUrl\` is an imported \`.svg\`.`;
const DOM_IDS_REQUIREMENT = `
- Assign \`id\` attributes to the main container and any internal elements, matching \`frame_details\`.`;
const LAYOUT_GUIDANCE = `
- **Layout & Shell (CRITICAL — no overlapping regions)**:
- When a frame contains a navigation/menu/sidebar region AND a content region meant to sit side-by-side, render them as flex children of a row container:
\`display: flex; min-height: 100vh;\`
- Give the menu/sidebar a FIXED width and \`flex-shrink: 0\` (e.g. \`width: 240px;\`), and the content area \`flex: 1; min-width: 0;\`.
- Add spacing between them (e.g. \`gap: 16px;\` or padding) — the menu and content must NEVER touch or overlap.
- NEVER use \`position: absolute\` to overlay the menu on top of the content. They must be separate flex children laid out left-to-right.
- If the design is a top bar + content (vertical), use \`flex-direction: column\` with the header \`flex-shrink: 0\` and content \`flex: 1; overflow: auto;\`.
- The content area must be allowed to scroll independently; never squeeze the menu width to 0.
- Honor the explicit \`layout\` from \`frame_details\` (flex/grid/absolute); only apply the rules above when the design actually places regions side-by-side.`;
const CONTENT_REGION_GUIDANCE = `
- **Content Region — NOT the whole app shell**:
- If the design shows a persistent application chrome — a LEFT sidebar/menu, a TOP navigation bar, and/or a BREADCRUMB — treat those three areas as the host application's fixed shell, which is ALREADY provided by the parent app.
- Generate ONLY the **main content region**: the area to the RIGHT of the left menu and BELOW the top nav and breadcrumb. Do NOT re-implement the left menu, top navigation, or breadcrumb.
- The component you emit MUST BE the content area itself: a self-contained panel that fills the available space. When it sits beside a sidebar, give the content root \`flex: 1; min-width: 0; overflow: auto;\` and do NOT wrap it inside another app shell (no second sidebar, no second top bar).
- If you must render the full frame (e.g. for a standalone preview), keep the menu / top nav / breadcrumb as minimal STATIC, NON-interactive placeholders (plain labeled containers) and spend all visual fidelity on the content region. NEVER build a real working menu / router / breadcrumb for them.
- Rule of thumb: your output = "what lives inside the content area", not "the entire application chrome".`;
const REACT_IMPORT_RULE = `
- Do **NOT** include \`import React from 'react';\` at the top of the file.`;
......@@ -148,6 +176,7 @@ export const generateFramePrompt = ({
assetFiles,
styling,
renderingModes,
fillContainer,
}: {
childrenImports: string;
frameDetails: string;
......@@ -157,6 +186,7 @@ export const generateFramePrompt = ({
hasStates: boolean;
hasIndependentChildren: boolean;
};
fillContainer?: boolean;
}) => {
return `
<system_instructions>
......@@ -206,12 +236,22 @@ ${STYLING_GUIDELINES}
- Use \`relative\` positioning for the container.
- Use \`spacing\` field in <frame_details> to set the spacing between elements
</req_2>
<req_7>
**App Layout & Shell**:
${LAYOUT_GUIDANCE}
</req_7>
<req_3>
**Images & Assets**:
${ASSETS_HANDLING}
</req_3>
<req_13>
**Icon Props ≠ Image URLs**:
${ICON_PROP_GUIDANCE}
</req_13>
<req_4>
**DOM IDs**:
${DOM_IDS_REQUIREMENT}
......@@ -226,6 +266,21 @@ ${REACT_IMPORT_RULE}
**File Naming**:
${FILE_NAMING_CONVENTION}
</req_6>
<req_8>
**Content Region (dashboard / app pages)**:
${CONTENT_REGION_GUIDANCE}
</req_8>
<req_11>
**Strict Tech-Stack Compliance (UI components)**:
${buildComponentUsageGuidance()}
</req_11>
<req_12>
**Fill Container**:
${buildStretchGuidance(fillContainer !== false)}
</req_12>
</requirements>
${OUTPUT_FORMAT}
......@@ -239,11 +294,13 @@ export const generateComponentPrompt = ({
componentDetails,
styling,
assetFiles,
fillContainer,
}: {
componentName: string;
componentDetails: string;
styling: string;
assetFiles?: string;
fillContainer?: boolean;
}) => {
return `
<system_instructions>
......@@ -311,6 +368,11 @@ ${STYLING_GUIDELINES}
${ASSETS_HANDLING}
</req_3>
<req_13>
**Icon Props ≠ Image URLs**:
${ICON_PROP_GUIDANCE}
</req_13>
<req_4>
**Semantic HTML**:
- Use semantic tags: \`<header>\`, \`<footer>\`, \`<nav>\`, \`<article>\`, \`<section>\`, \`<button>\`.
......@@ -344,6 +406,21 @@ ${ASSETS_HANDLING}
**Both types**: Do NOT repeat JSX to simulate grids; parent components handle iteration.
</req_7>
<req_8>
**Content Region (dashboard / app pages)**:
${CONTENT_REGION_GUIDANCE}
</req_8>
<req_11>
**Strict Tech-Stack Compliance (UI components)**:
${buildComponentUsageGuidance()}
</req_11>
<req_12>
**Fill Container**:
${buildStretchGuidance(fillContainer !== false)}
</req_12>
<req_9>
**React Import**:
${REACT_IMPORT_RULE}
......
import { getProjectProfile } from '../../../utils/project-profile';
/**
* Shared, framework-agnostic generation guidance for two concerns:
*
* 1. STRICT tech-stack compliance — the model MUST build UI from the selected
* stack's components and NEVER fall back to raw HTML primitives when an
* equivalent component exists. A degradation chain governs which component
* wins: custom/project component > library component > native HTML.
*
* 2. Fill-container behaviour — whether the generated root fills its host
* container (default, for embedding into an app shell) or renders at the
* design's intrinsic width (for fixed-width standalone previews).
*
* This module is the single extension point for "which component to use".
* Adding a new UI kit = one entry in LIBRARY_COMPONENT_CATALOG (Open-Closed
* Principle); no edit to React/Vue prompt code is required.
*/
/** A single library component mapped from a generic UI widget. */
export interface LibComponent {
/** Tag / JSX element name to use in markup. */
tag: string;
/** Named or default import name ('' for auto-import / global registration). */
importName: string;
/** Module to import from ('' when globally registered by the kit). */
importFrom: string;
/** Optional composition note (for composite components like MUI/shadcn tables). */
note?: string;
}
/**
* Per-library UI widget → component catalog.
*
* Keys are matched by longest case-insensitive substring against
* ProjectProfile.componentLibrary, so "Ant Design Vue" wins over "Ant Design",
* "Material UI (MUI)" resolves, etc. Adding a new kit is a single map entry.
*/
const LIBRARY_COMPONENT_CATALOG: Record<string, Record<string, LibComponent>> = {
'Element Plus': {
table: { tag: 'el-table', importName: 'ElTable', importFrom: 'element-plus' },
button: { tag: 'el-button', importName: 'ElButton', importFrom: 'element-plus' },
input: { tag: 'el-input', importName: 'ElInput', importFrom: 'element-plus' },
select: { tag: 'el-select', importName: 'ElSelect', importFrom: 'element-plus' },
option: { tag: 'el-option', importName: 'ElOption', importFrom: 'element-plus' },
form: { tag: 'el-form', importName: 'ElForm', importFrom: 'element-plus' },
formItem: { tag: 'el-form-item', importName: 'ElFormItem', importFrom: 'element-plus' },
dialog: { tag: 'el-dialog', importName: 'ElDialog', importFrom: 'element-plus' },
drawer: { tag: 'el-drawer', importName: 'ElDrawer', importFrom: 'element-plus' },
tabs: { tag: 'el-tabs', importName: 'ElTabs', importFrom: 'element-plus' },
tabPane: { tag: 'el-tab-pane', importName: 'ElTabPane', importFrom: 'element-plus' },
card: { tag: 'el-card', importName: 'ElCard', importFrom: 'element-plus' },
tag: { tag: 'el-tag', importName: 'ElTag', importFrom: 'element-plus' },
tooltip: { tag: 'el-tooltip', importName: 'ElTooltip', importFrom: 'element-plus' },
dropdown: { tag: 'el-dropdown', importName: 'ElDropdown', importFrom: 'element-plus' },
menu: { tag: 'el-menu', importName: 'ElMenu', importFrom: 'element-plus' },
breadcrumb: { tag: 'el-breadcrumb', importName: 'ElBreadcrumb', importFrom: 'element-plus' },
pagination: { tag: 'el-pagination', importName: 'ElPagination', importFrom: 'element-plus' },
checkbox: { tag: 'el-checkbox', importName: 'ElCheckbox', importFrom: 'element-plus' },
radio: { tag: 'el-radio', importName: 'ElRadio', importFrom: 'element-plus' },
switch: { tag: 'el-switch', importName: 'ElSwitch', importFrom: 'element-plus' },
datePicker: { tag: 'el-date-picker', importName: 'ElDatePicker', importFrom: 'element-plus' },
upload: { tag: 'el-upload', importName: 'ElUpload', importFrom: 'element-plus' },
progress: { tag: 'el-progress', importName: 'ElProgress', importFrom: 'element-plus' },
avatar: { tag: 'el-avatar', importName: 'ElAvatar', importFrom: 'element-plus' },
alert: { tag: 'el-alert', importName: 'ElAlert', importFrom: 'element-plus' },
steps: { tag: 'el-steps', importName: 'ElSteps', importFrom: 'element-plus' },
collapse: { tag: 'el-collapse', importName: 'ElCollapse', importFrom: 'element-plus' },
tree: { tag: 'el-tree', importName: 'ElTree', importFrom: 'element-plus' },
popover: { tag: 'el-popover', importName: 'ElPopover', importFrom: 'element-plus' },
slider: { tag: 'el-slider', importName: 'ElSlider', importFrom: 'element-plus' },
rate: { tag: 'el-rate', importName: 'ElRate', importFrom: 'element-plus' },
image: { tag: 'el-image', importName: 'ElImage', importFrom: 'element-plus' },
link: { tag: 'el-link', importName: 'ElLink', importFrom: 'element-plus' },
},
'Ant Design Vue': {
table: { tag: 'a-table', importName: 'Table', importFrom: 'ant-design-vue' },
button: { tag: 'a-button', importName: 'Button', importFrom: 'ant-design-vue' },
input: { tag: 'a-input', importName: 'Input', importFrom: 'ant-design-vue' },
select: { tag: 'a-select', importName: 'Select', importFrom: 'ant-design-vue' },
option: { tag: 'a-select-option', importName: 'Select', importFrom: 'ant-design-vue', note: 'use <a-select-option> as child of <a-select>' },
form: { tag: 'a-form', importName: 'Form', importFrom: 'ant-design-vue' },
formItem: { tag: 'a-form-item', importName: 'Form', importFrom: 'ant-design-vue', note: 'use <a-form-item> as child of <a-form>' },
modal: { tag: 'a-modal', importName: 'Modal', importFrom: 'ant-design-vue' },
drawer: { tag: 'a-drawer', importName: 'Drawer', importFrom: 'ant-design-vue' },
tabs: { tag: 'a-tabs', importName: 'Tabs', importFrom: 'ant-design-vue' },
tabPane: { tag: 'a-tab-pane', importName: 'Tabs', importFrom: 'ant-design-vue', note: 'use <a-tab-pane> as child of <a-tabs>' },
card: { tag: 'a-card', importName: 'Card', importFrom: 'ant-design-vue' },
tag: { tag: 'a-tag', importName: 'Tag', importFrom: 'ant-design-vue' },
tooltip: { tag: 'a-tooltip', importName: 'Tooltip', importFrom: 'ant-design-vue' },
dropdown: { tag: 'a-dropdown', importName: 'Dropdown', importFrom: 'ant-design-vue' },
menu: { tag: 'a-menu', importName: 'Menu', importFrom: 'ant-design-vue' },
breadcrumb: { tag: 'a-breadcrumb', importName: 'Breadcrumb', importFrom: 'ant-design-vue' },
pagination: { tag: 'a-pagination', importName: 'Pagination', importFrom: 'ant-design-vue' },
checkbox: { tag: 'a-checkbox', importName: 'Checkbox', importFrom: 'ant-design-vue' },
radio: { tag: 'a-radio', importName: 'Radio', importFrom: 'ant-design-vue' },
switch: { tag: 'a-switch', importName: 'Switch', importFrom: 'ant-design-vue' },
datePicker: { tag: 'a-date-picker', importName: 'DatePicker', importFrom: 'ant-design-vue' },
upload: { tag: 'a-upload', importName: 'Upload', importFrom: 'ant-design-vue' },
progress: { tag: 'a-progress', importName: 'Progress', importFrom: 'ant-design-vue' },
avatar: { tag: 'a-avatar', importName: 'Avatar', importFrom: 'ant-design-vue' },
alert: { tag: 'a-alert', importName: 'Alert', importFrom: 'ant-design-vue' },
steps: { tag: 'a-steps', importName: 'Steps', importFrom: 'ant-design-vue' },
collapse: { tag: 'a-collapse', importName: 'Collapse', importFrom: 'ant-design-vue' },
tree: { tag: 'a-tree', importName: 'Tree', importFrom: 'ant-design-vue' },
popover: { tag: 'a-popover', importName: 'Popover', importFrom: 'ant-design-vue' },
slider: { tag: 'a-slider', importName: 'Slider', importFrom: 'ant-design-vue' },
rate: { tag: 'a-rate', importName: 'Rate', importFrom: 'ant-design-vue' },
image: { tag: 'a-image', importName: 'Image', importFrom: 'ant-design-vue' },
},
'Ant Design': {
table: { tag: 'Table', importName: 'Table', importFrom: 'antd' },
button: { tag: 'Button', importName: 'Button', importFrom: 'antd' },
input: { tag: 'Input', importName: 'Input', importFrom: 'antd' },
select: { tag: 'Select', importName: 'Select', importFrom: 'antd' },
option: { tag: 'Select.Option', importName: 'Select', importFrom: 'antd', note: 'use <Select.Option> as child of <Select>' },
form: { tag: 'Form', importName: 'Form', importFrom: 'antd' },
formItem: { tag: 'Form.Item', importName: 'Form', importFrom: 'antd', note: 'use <Form.Item> as child of <Form>' },
modal: { tag: 'Modal', importName: 'Modal', importFrom: 'antd' },
drawer: { tag: 'Drawer', importName: 'Drawer', importFrom: 'antd' },
tabs: { tag: 'Tabs', importName: 'Tabs', importFrom: 'antd' },
tabPane: { tag: 'Tabs.TabPane', importName: 'Tabs', importFrom: 'antd', note: 'use <Tabs.TabPane> as child of <Tabs>' },
card: { tag: 'Card', importName: 'Card', importFrom: 'antd' },
tag: { tag: 'Tag', importName: 'Tag', importFrom: 'antd' },
tooltip: { tag: 'Tooltip', importName: 'Tooltip', importFrom: 'antd' },
dropdown: { tag: 'Dropdown', importName: 'Dropdown', importFrom: 'antd' },
menu: { tag: 'Menu', importName: 'Menu', importFrom: 'antd' },
breadcrumb: { tag: 'Breadcrumb', importName: 'Breadcrumb', importFrom: 'antd' },
pagination: { tag: 'Pagination', importName: 'Pagination', importFrom: 'antd' },
checkbox: { tag: 'Checkbox', importName: 'Checkbox', importFrom: 'antd' },
radio: { tag: 'Radio', importName: 'Radio', importFrom: 'antd' },
switch: { tag: 'Switch', importName: 'Switch', importFrom: 'antd' },
datePicker: { tag: 'DatePicker', importName: 'DatePicker', importFrom: 'antd' },
upload: { tag: 'Upload', importName: 'Upload', importFrom: 'antd' },
progress: { tag: 'Progress', importName: 'Progress', importFrom: 'antd' },
avatar: { tag: 'Avatar', importName: 'Avatar', importFrom: 'antd' },
alert: { tag: 'Alert', importName: 'Alert', importFrom: 'antd' },
steps: { tag: 'Steps', importName: 'Steps', importFrom: 'antd' },
collapse: { tag: 'Collapse', importName: 'Collapse', importFrom: 'antd' },
tree: { tag: 'Tree', importName: 'Tree', importFrom: 'antd' },
popover: { tag: 'Popover', importName: 'Popover', importFrom: 'antd' },
slider: { tag: 'Slider', importName: 'Slider', importFrom: 'antd' },
rate: { tag: 'Rate', importName: 'Rate', importFrom: 'antd' },
image: { tag: 'Image', importName: 'Image', importFrom: 'antd' },
},
'Material UI (MUI)': {
table: { tag: 'Table', importName: 'Table', importFrom: '@mui/material', note: 'compose TableContainer > Table > TableHead > TableRow > TableCell' },
button: { tag: 'Button', importName: 'Button', importFrom: '@mui/material' },
input: { tag: 'TextField', importName: 'TextField', importFrom: '@mui/material' },
select: { tag: 'Select', importName: 'Select', importFrom: '@mui/material' },
form: { tag: 'FormControl', importName: 'FormControl', importFrom: '@mui/material' },
dialog: { tag: 'Dialog', importName: 'Dialog', importFrom: '@mui/material' },
drawer: { tag: 'Drawer', importName: 'Drawer', importFrom: '@mui/material' },
tabs: { tag: 'Tabs', importName: 'Tabs', importFrom: '@mui/material' },
card: { tag: 'Card', importName: 'Card', importFrom: '@mui/material' },
chip: { tag: 'Chip', importName: 'Chip', importFrom: '@mui/material' },
tooltip: { tag: 'Tooltip', importName: 'Tooltip', importFrom: '@mui/material' },
menu: { tag: 'Menu', importName: 'Menu', importFrom: '@mui/material' },
breadcrumb: { tag: 'Breadcrumbs', importName: 'Breadcrumbs', importFrom: '@mui/material' },
pagination: { tag: 'Pagination', importName: 'Pagination', importFrom: '@mui/material' },
checkbox: { tag: 'Checkbox', importName: 'Checkbox', importFrom: '@mui/material' },
radio: { tag: 'Radio', importName: 'Radio', importFrom: '@mui/material' },
switch: { tag: 'Switch', importName: 'Switch', importFrom: '@mui/material' },
datePicker: { tag: 'DatePicker', importName: 'DatePicker', importFrom: '@mui/x-date-pickers' },
progress: { tag: 'LinearProgress', importName: 'LinearProgress', importFrom: '@mui/material' },
avatar: { tag: 'Avatar', importName: 'Avatar', importFrom: '@mui/material' },
alert: { tag: 'Alert', importName: 'Alert', importFrom: '@mui/material' },
slider: { tag: 'Slider', importName: 'Slider', importFrom: '@mui/material' },
},
'shadcn/ui': {
table: { tag: 'Table', importName: 'Table', importFrom: '@/components/ui/table', note: 'compose Table > TableHeader > TableBody > TableRow > TableCell' },
button: { tag: 'Button', importName: 'Button', importFrom: '@/components/ui/button' },
input: { tag: 'Input', importName: 'Input', importFrom: '@/components/ui/input' },
select: { tag: 'Select', importName: 'Select', importFrom: '@/components/ui/select' },
form: { tag: 'Form', importName: 'Form', importFrom: '@/components/ui/form', note: 'react-hook-form + @/components/ui/form' },
dialog: { tag: 'Dialog', importName: 'Dialog', importFrom: '@/components/ui/dialog' },
drawer: { tag: 'Sheet', importName: 'Sheet', importFrom: '@/components/ui/sheet' },
tabs: { tag: 'Tabs', importName: 'Tabs', importFrom: '@/components/ui/tabs' },
card: { tag: 'Card', importName: 'Card', importFrom: '@/components/ui/card' },
badge: { tag: 'Badge', importName: 'Badge', importFrom: '@/components/ui/badge' },
tooltip: { tag: 'Tooltip', importName: 'Tooltip', importFrom: '@/components/ui/tooltip' },
dropdown: { tag: 'DropdownMenu', importName: 'DropdownMenu', importFrom: '@/components/ui/dropdown-menu' },
avatar: { tag: 'Avatar', importName: 'Avatar', importFrom: '@/components/ui/avatar' },
alert: { tag: 'Alert', importName: 'Alert', importFrom: '@/components/ui/alert' },
checkbox: { tag: 'Checkbox', importName: 'Checkbox', importFrom: '@/components/ui/checkbox' },
radio: { tag: 'RadioGroup', importName: 'RadioGroup', importFrom: '@/components/ui/radio-group' },
switch: { tag: 'Switch', importName: 'Switch', importFrom: '@/components/ui/switch' },
progress: { tag: 'Progress', importName: 'Progress', importFrom: '@/components/ui/progress' },
slider: { tag: 'Slider', importName: 'Slider', importFrom: '@/components/ui/slider' },
},
'Naive UI': {
table: { tag: 'n-data-table', importName: 'NDataTable', importFrom: 'naive-ui' },
button: { tag: 'n-button', importName: 'NButton', importFrom: 'naive-ui' },
input: { tag: 'n-input', importName: 'NInput', importFrom: 'naive-ui' },
select: { tag: 'n-select', importName: 'NSelect', importFrom: 'naive-ui' },
form: { tag: 'n-form', importName: 'NForm', importFrom: 'naive-ui' },
formItem: { tag: 'n-form-item', importName: 'NFormItem', importFrom: 'naive-ui' },
dialog: { tag: 'n-modal', importName: 'NModal', importFrom: 'naive-ui' },
drawer: { tag: 'n-drawer', importName: 'NDrawer', importFrom: 'naive-ui' },
tabs: { tag: 'n-tabs', importName: 'NTabs', importFrom: 'naive-ui' },
tabPane: { tag: 'n-tab-pane', importName: 'NTabPane', importFrom: 'naive-ui' },
card: { tag: 'n-card', importName: 'NCard', importFrom: 'naive-ui' },
tag: { tag: 'n-tag', importName: 'NTag', importFrom: 'naive-ui' },
tooltip: { tag: 'n-tooltip', importName: 'NTooltip', importFrom: 'naive-ui' },
dropdown: { tag: 'n-dropdown', importName: 'NDropdown', importFrom: 'naive-ui' },
menu: { tag: 'n-menu', importName: 'NMenu', importFrom: 'naive-ui' },
breadcrumb: { tag: 'n-breadcrumb', importName: 'NBreadcrumb', importFrom: 'naive-ui' },
pagination: { tag: 'n-pagination', importName: 'NPagination', importFrom: 'naive-ui' },
checkbox: { tag: 'n-checkbox', importName: 'NCheckbox', importFrom: 'naive-ui' },
radio: { tag: 'n-radio', importName: 'NRadio', importFrom: 'naive-ui' },
switch: { tag: 'n-switch', importName: 'NSwitch', importFrom: 'naive-ui' },
datePicker: { tag: 'n-date-picker', importName: 'NDatePicker', importFrom: 'naive-ui' },
upload: { tag: 'n-upload', importName: 'NUpload', importFrom: 'naive-ui' },
progress: { tag: 'n-progress', importName: 'NProgress', importFrom: 'naive-ui' },
avatar: { tag: 'n-avatar', importName: 'NAvatar', importFrom: 'naive-ui' },
alert: { tag: 'n-alert', importName: 'NAlert', importFrom: 'naive-ui' },
steps: { tag: 'n-steps', importName: 'NSteps', importFrom: 'naive-ui' },
collapse: { tag: 'n-collapse', importName: 'NCollapse', importFrom: 'naive-ui' },
tree: { tag: 'n-tree', importName: 'NTree', importFrom: 'naive-ui' },
popover: { tag: 'n-popover', importName: 'NPopover', importFrom: 'naive-ui' },
slider: { tag: 'n-slider', importName: 'NSlider', importFrom: 'naive-ui' },
rate: { tag: 'n-rate', importName: 'NRate', importFrom: 'naive-ui' },
},
};
/** Resolve the catalog for a component-library string (longest-substring match). */
function resolveCatalog(library?: string): Record<string, LibComponent> | null {
if (!library) return null;
const lower = library.toLowerCase();
const keys = Object.keys(LIBRARY_COMPONENT_CATALOG).sort((a, b) => b.length - a.length);
const hit = keys.find((k) => lower.includes(k.toLowerCase()));
return hit ? (LIBRARY_COMPONENT_CATALOG[hit] ?? null) : null;
}
/**
* Build the "STRICT tech-stack compliance" guidance block. Reads the runtime
* project profile so custom (Tier-1) components are honoured. Returns a
* non-empty string always (even with no library selected, it still enforces
* custom-first + semantic-HTML fallback).
*/
export function buildComponentUsageGuidance(): string {
const profile = getProjectProfile();
const library = profile?.componentLibrary;
const catalog = resolveCatalog(library);
const lines: string[] = [];
lines.push(
' - **STRICT tech-stack compliance (CRITICAL)**: You MUST build every UI widget using the selected stack’s components. NEVER replace a stack/library component with a raw HTML primitive when an equivalent exists in the stack.',
);
lines.push(
' - **Component priority (degradation chain)** — for any UI widget, pick the FIRST available in this order:',
);
lines.push(
' 1. **Custom / project component** — any component listed in <project_profile><components> is a bespoke component of the target project. ALWAYS prefer it over the library equivalent. Example: if a custom `XTable` is listed and the design needs a data grid, use `XTable`, NOT el-table / Table.',
);
lines.push(
' 2. **Library component** — the component from the selected UI kit (see the catalog below). The active kit is decided by the generation’s componentLibrary setting, so choosing Element Plus vs Ant Design Vue vs Ant Design vs MUI determines which table/button you get.',
);
lines.push(
' 3. **Native HTML** — ONLY when neither a custom nor a library component covers that widget. Even then prefer semantic elements (table, button, form, nav, …).',
);
if (catalog) {
lines.push(` - **Selected UI kit**: "${library}". Use these components (import the named export, then use the tag in markup):`);
lines.push(' <component_catalog>');
for (const [widget, c] of Object.entries(catalog)) {
const importHint = c.importFrom
? `import { ${c.importName} } from '${c.importFrom}'`
: `${c.importName} (globally registered)`;
const note = c.note ? ` — ${c.note}` : '';
lines.push(` - ${widget}: <${c.tag}> (${importHint})${note}`);
}
lines.push(' </component_catalog>');
} else {
lines.push(
' - **No UI component library selected** for this generation. Use semantic HTML primitives (table, button, form, nav, …) together with the selected styling strategy. Still prefer any custom component from <project_profile><components> when one matches the widget.',
);
}
lines.push(
' - **Concrete example — data table**: if the design contains a data grid / table, do NOT write a native <table><tr><td>. Use, in priority order: (1) a custom table component from <project_profile>, else (2) the kit component — <el-table> (Element Plus), <a-table> (Ant Design Vue), <Table> (Ant Design / MUI), <Table> from @/components/ui/table (shadcn) — driven by its data/columns API. The SAME rule applies to buttons (el-button / <Button>), inputs, forms, selects, dialogs, tabs, cards, tags, pagination, menus, breadcrumbs, etc.',
);
lines.push(
' - **Hard rule**: generating a native <table> (or a plain <button> / <input>) for a widget that has a stack or library component is a FAILURE. Always map the widget to its stack component.',
);
return lines.join('\n');
}
/**
* Build the "fill container" guidance based on the user's choice.
* - fill = true (default): root must fill the host container (embed scenario).
* - fill = false: render at the design's intrinsic width, centered, no stretch.
*/
export function buildStretchGuidance(fill: boolean): string {
if (fill) {
return [
' - **Fill the container (CRITICAL)**: The generated root component MUST fill its host container. Use `width: 100%; height: 100%` (or, when nested in a flex column, `flex: 1; min-height: 0`). Do NOT hardcode a max-width, a fixed page width, or `min-height: 100vh` that assumes a standalone viewport. The parent app shell owns the outer layout.',
].join('\n');
}
return [
' - **Render at the design’s intrinsic width (do NOT stretch)**: Do NOT expand to 100% of a wide viewport. Render the root at the Figma frame’s original width (e.g. width: 1440px) inside a centered container with `margin: 0 auto`, and let the inner content scroll. This keeps fixed-width designs from breaking on ultra-wide screens.',
].join('\n');
}
import type { ProjectProfile } from '../../../types/project-profile';
import { getProjectProfile } from '../../../utils/project-profile';
import type { FrameworkStrategy } from './types';
import { reactStrategy } from './react';
import { vue3Strategy } from './vue3';
/**
* Registered framework strategies. To support a new framework, add a strategy
* module under this folder and append it here — the CODE node dispatch and all
* existing strategies stay untouched (Open-Closed Principle).
*/
const STRATEGIES: FrameworkStrategy[] = [reactStrategy, vue3Strategy];
/**
* Resolve a strategy from an explicit profile. Falls back to React when no
* framework matches (React is the legacy default and must remain unchanged).
*/
export function getStrategyForProfile(profile?: ProjectProfile | null): FrameworkStrategy {
const fw = (profile?.framework || '').toLowerCase();
const matched = STRATEGIES.find((s) => fw.includes(s.id));
return matched ?? reactStrategy;
}
/**
* Resolve the active strategy from the runtime project profile (set per run by
* the orchestration backend via `setProjectProfile`).
*/
export function getActiveStrategy(): FrameworkStrategy {
return getStrategyForProfile(getProjectProfile());
}
export type { FrameworkStrategy, FramePromptInput, ComponentPromptInput, RootInjectionInput } from './types';
import { generateFramePrompt, generateComponentPrompt, injectRootComponentPrompt } from '../prompt';
import { DEFAULT_APP_CONTENT } from '../constants';
import type { FrameworkStrategy } from './types';
/**
* React strategy — a thin wrapper that delegates to the existing, battle-tested
* React prompts **unchanged**. The original `prompt.ts` is never modified, so
* established React behaviour is preserved byte-for-byte. This wrapper exists
* purely so the CODE node can treat every framework uniformly via the
* `FrameworkStrategy` interface.
*/
export const reactStrategy: FrameworkStrategy = {
id: 'react',
label: 'React',
isVue: false,
entryFileName: 'index.tsx',
rootFileName: 'App.tsx',
defaultAppContent: DEFAULT_APP_CONTENT,
buildFramePrompt: (i) => generateFramePrompt(i),
buildComponentPrompt: (i) => generateComponentPrompt(i),
buildRootInjectionPrompt: (i) => injectRootComponentPrompt(i),
// React prompts already honour the project profile's component library
// through the injected `<profile_rules>` constraint block, so no extra
// guidance is needed here.
libraryGuidance: () => '',
};
/** Inputs for building a "Frame" (container) component prompt. */
export interface FramePromptInput {
frameDetails: string;
childrenImports: string;
styling: string;
assetFiles?: string;
renderingModes: { hasStates: boolean; hasIndependentChildren: boolean };
/** Whether the root should fill its host container (default true). */
fillContainer?: boolean;
}
/** Inputs for building a leaf / reusable component prompt. */
export interface ComponentPromptInput {
componentName: string;
componentDetails: string;
styling: string;
assetFiles?: string;
/** Whether the root should fill its host container (default true). */
fillContainer?: boolean;
}
/** Inputs for injecting the root component into the app entry file. */
export interface RootInjectionInput {
appContent: string;
componentName: string;
componentPath: string;
}
/**
* A framework-specific code-generation strategy (Strategy pattern).
*
* Each supported framework (React, Vue 3, …) implements this interface so the
* CODE node can stay framework-agnostic. Adding a brand-new framework only
* requires a new strategy module + one registry entry in `./index.ts` — no
* edits to existing strategies or to the CODE node dispatch. This is the
* Open-Closed Principle: open for extension, closed for modification.
*/
export interface FrameworkStrategy {
/** Stable id; also used as a case-insensitive substring to detect the framework from `ProjectProfile.framework`. */
readonly id: string;
/** Human label for logs / diagnostics. */
readonly label: string;
/** True for Vue-style SFC output (affects entry file name, templates, etc.). */
readonly isVue: boolean;
/** Entry component file name, e.g. "index.tsx" or "index.vue". */
readonly entryFileName: string;
/** Root application file name, e.g. "App.tsx" or "App.vue". */
readonly rootFileName: string;
/** Default root application template used when no App file exists yet. */
readonly defaultAppContent: string;
buildFramePrompt(input: FramePromptInput): string;
buildComponentPrompt(input: ComponentPromptInput): string;
buildRootInjectionPrompt(input: RootInjectionInput): string;
/**
* Component-library-specific guidance snippet (e.g. Element Plus usage).
* Implementations should resolve the library from a lookup map so adding a
* new UI kit is just one map entry (OCP).
*/
libraryGuidance(componentLibrary?: string): string;
}
import { getProjectProfile, renderProfileConstraint } from '../../../utils/project-profile';
import type { FrameworkStrategy, FramePromptInput, ComponentPromptInput, RootInjectionInput } from './types';
import { buildComponentUsageGuidance, buildStretchGuidance } from './component-usage';
/**
* Vue 3 strategy — a NEW, self-contained generation strategy that emits Vue 3
* Single-File Components (SFC). It is intentionally separate from `prompt.ts`
* (React) so the two never interfere. Adding support for another Vue UI kit is
* a single entry in `VUE_LIBRARY_GUIDANCE` below (Open-Closed Principle).
*/
/** Renders the target-project profile constraint block (mirrors prompt.ts `profileConstraintSection`). */
function profileConstraintSection(): string {
const p = getProjectProfile();
return p ? renderProfileConstraint(p) : '';
}
const VUE_OUTPUT_FORMAT = `
<output_format>
**CRITICAL - Output Format Requirements (Vue 3 SFC):**
- Return Vue 3 Single-File Components. Each file is a \`## <filename>\` section followed by a fenced code block.
- Main component file MUST be named \`index.vue\`.
- Style file (if separate) named \`index.module.less\` or \`index.module.scss\` (scoped CSS modules); otherwise inline \`<style scoped>\`.
- Each file section MUST start with EXACTLY \`## \` (two hashes + one space) followed by the filename with extension.
- Example:
## index.vue
\`\`\`vue
<template>
<div class="container">...</div>
</template>
<script setup lang="ts">
// component logic
</script>
<style scoped>
.container { /* styles */ }
</style>
\`\`\`
</output_format>`;
const ASSETS_HANDLING = `
- **CRITICAL**: For any image URL starting with \`@/assets\`, import it at the top of \`<script setup>\`:
\`import ArXivIcon from '@/assets/arxiv-1-2956.svg';\` and use \`<img :src="ArXivIcon" />\`.
- NEVER use the raw string path directly in the template or styles.`;
const ICON_PROP_GUIDANCE = `
- **CRITICAL — Icon props are COMPONENTS, not image URLs (a wrong usage causes a white-screen crash)**:
- An imported asset file (\`import X from '@/assets/foo.svg'\`) is a **string URL** at runtime (in dev it may be a \`data:image/svg+xml,...\` data URI). It is NEVER a Vue component.
- A URL string may ONLY be used as: (1) \`<img :src="X" />\`, or (2) a CSS \`background-image: url(...)\` value (use a relative/absolute path there, NOT the \`@\` alias).
- NEVER pass it to a prop that expects a **component**, such as Element Plus \`el-select\` / \`el-input\` \`suffix-icon\`, \`prefix-icon\`, or \`el-button\`'s \`icon\`. Passing a URL there makes the library call \`createElement('data:image/svg+xml,...')\` → \`InvalidCharacterError\` → the WHOLE page renders blank.
- ✅ To show a custom arrow/icon on a library control: import an ICON COMPONENT from the kit's icon package (e.g. \`import { ArrowDown } from '@element-plus/icons-vue'\`) and pass \`<el-select :suffix-icon="ArrowDown">\`; OR hide the default icon via CSS (\`.el-select__suffix { display: none }\`) and draw your own with \`.wrapper::after { background-image: url(...) }\`.
- ❌ NEVER do \`<el-select :suffix-icon="importedSvgUrl">\` where \`importedSvgUrl\` is an imported \`.svg\`.`;
const LAYOUT_GUIDANCE = `
- **Layout & Shell (CRITICAL — no overlapping regions)**:
- When a frame contains a navigation/menu/sidebar region AND a content region meant to sit side-by-side, render them as flex children of a row container:
\`display: flex; min-height: 100vh;\`
- Give the menu/sidebar a FIXED width and \`flex-shrink: 0\` (e.g. \`width: 240px;\`), and the content area \`flex: 1; min-width: 0;\`.
- Add spacing between them (e.g. \`gap: 16px;\` or padding) — the menu and content must NEVER touch or overlap.
- NEVER use \`position: absolute\` to overlay the menu on top of the content. They must be separate flex children laid out left-to-right.
- If the design is a top bar + content (vertical), use \`flex-direction: column\` with the header \`flex-shrink: 0\` and content \`flex: 1; overflow: auto;\`.
- The content area must be allowed to scroll independently; never squeeze the menu width to 0.
- Honor the explicit \`layout\` from \`frame_details\` (flex/grid/absolute); only apply the rules above when the design actually places regions side-by-side.`;
const CONTENT_REGION_GUIDANCE = `
- **Content Region — NOT the whole app shell**:
- If the design shows a persistent application chrome — a LEFT sidebar/menu, a TOP navigation bar, and/or a BREADCRUMB — treat those three areas as the host application's fixed shell, which is ALREADY provided by the parent app.
- Generate ONLY the **main content region**: the area to the RIGHT of the left menu and BELOW the top nav and breadcrumb. Do NOT re-implement the left menu, top navigation, or breadcrumb.
- The component you emit MUST BE the content area itself: a self-contained panel that fills the available space. When it sits beside a sidebar, give the content root \`flex: 1; min-width: 0; overflow: auto;\` and do NOT wrap it inside another app shell (no second sidebar, no second top bar).
- If you must render the full frame (e.g. for a standalone preview), keep the menu / top nav / breadcrumb as minimal STATIC, NON-interactive placeholders (plain labeled containers) and spend all visual fidelity on the content region. NEVER build a real working menu / router / breadcrumb for them.
- Rule of thumb: your output = "what lives inside the content area", not "the entire application chrome".`;
const DOM_IDS_REQUIREMENT = `
- Assign an \`id\` attribute to the root container and any internal elements, matching \`frame_details\` (required for automated validation).`;
/**
* Component-library guidance for the Vue ecosystem. Extend by adding a key;
* matching is a case-insensitive substring so "Ant Design Vue",
* "ant-design-vue", "Element Plus" all resolve. Unknown libraries fall back to
* a generic instruction. This is the single extension point for new Vue kits.
*/
const VUE_LIBRARY_GUIDANCE: Record<string, string> = {
'Element Plus': `
- **UI Library: Element Plus**. Import the components you use, e.g. \`import { ElButton, ElCard, ElInput } from 'element-plus';\` (on-demand named imports).
- Use Element Plus components in \`<template>\` (e.g. \`<el-button type="primary">…</el-button>\`, \`<el-card>…</el-card>\`).
- Element Plus theming uses CSS variables; import \`element-plus/dist/index.css\` once at the app entry.`,
'Ant Design Vue': `
- **UI Library: Ant Design Vue**. Import the components you use, e.g. \`import { Button, Card, Input } from 'ant-design-vue';\`.
- Use Ant Design Vue components in \`<template>\` (e.g. \`<a-button type="primary">…</a-button>\`, \`<a-card>…</a-card>\`).
- Import \`ant-design-vue/dist/reset.css\` once at the app entry for base styles.`,
};
function libraryGuidance(componentLibrary?: string): string {
if (!componentLibrary) return '';
const key = Object.keys(VUE_LIBRARY_GUIDANCE).find((k) => componentLibrary.toLowerCase().includes(k.toLowerCase()));
const guidance = key ? VUE_LIBRARY_GUIDANCE[key] : undefined;
if (guidance) return guidance;
return `
- **UI Library**: The project uses "${componentLibrary}". Use its standard Vue 3 components in \`<template>\` and import them accordingly.`;
}
const DEFAULT_VUE_APP = `<template>
<RootComponent />
</template>
<script setup lang="ts">
import RootComponent from '@/components';
</script>`;
function buildFramePrompt({
frameDetails,
childrenImports,
styling,
assetFiles,
renderingModes,
fillContainer,
}: FramePromptInput): string {
const lib = libraryGuidance(getProjectProfile()?.componentLibrary);
return `
<system_instructions>
<role>
You are a Vue 3 Architect.
Your task is to assemble a "Frame" component (a Vue 3 SFC) that composes multiple child components based on Figma layout data, using \`<script setup lang="ts">\`.
</role>
<input_context>
<frame_details>${frameDetails}</frame_details>
<children>${childrenImports}</children>
<styling>${styling}</styling>
${assetFiles ? `<available_assets>Available asset files: ${assetFiles}</available_assets>` : ''}
<frame_structure>
The \`frame_details\` contains:
- \`layout\`: Layout info (flex/grid/absolute)
- \`elements\`: CSS styles and asset URLs for all elements
- \`states\` (optional): reusable components; each entry has \`state\` (data array), \`componentName\`, \`componentPath\`
</frame_structure>
</input_context>
<requirements>
<req_1>
**Children Components & Props (CRITICAL)**:
- Import child components at the top of \`<script setup>\` using the EXACT path from \`<children>\`.
- Example: \`import TaskGrid from "@/components/tasks-section/task-grid";\`
- Use them in \`<template>\` as \`<TaskGrid />\`.
- When \`states\` exists, render via \`v-for\`:
\`\`\`vue
<TaskGrid v-for="(item, i) in states[0].state" :key="i" v-bind="item" />
\`\`\`
- ONLY pass props present in the state data.
</req_1>
<req_2>
**Layout & Styling**:
- Use \`layout\` for dimensions/spacing/flow (flex/grid).
- Prefer \`<style scoped>\` or CSS Modules; if the stack uses Less/SCSS, emit \`index.module.less\`.
- Use \`relative\` positioning for the container.
</req_2>
<req_8>
**App Layout & Shell**:
${LAYOUT_GUIDANCE}
</req_8>
<req_9>
**Content Region (dashboard / app pages)**:
${CONTENT_REGION_GUIDANCE}
</req_9>
<req_11>
**Strict Tech-Stack Compliance (UI components)**:
${buildComponentUsageGuidance()}
</req_11>
<req_12>
**Fill Container**:
${buildStretchGuidance(fillContainer !== false)}
</req_12>
<req_3>
**Images & Assets**:
${ASSETS_HANDLING}
</req_3>
<req_13>
**Icon Props ≠ Image URLs**:
${ICON_PROP_GUIDANCE}
</req_13>
<req_4>
**DOM IDs**:
${DOM_IDS_REQUIREMENT}
</req_4>
<req_5>
**File Naming**:
- ALWAYS name the main component file \`index.vue\`.
- NEVER use PascalCase file names like \`MainFrame.vue\`.
</req_5>
${lib ? ` <req_6>\n **Component Library**:\n${lib}\n </req_6>` : ''}
${renderingModes.hasStates ? ` <req_7>
**List Rendering (States-based)**:
- When \`frame_details\` contains a \`states\` array, render each entry with \`v-for\`:
\`\`\`vue
<ChildComp v-for="(item, i) in states[0].state" :key="i" v-bind="item" />
\`\`\`
- ONLY pass props that exist in the state data objects.
</req_7>` : ''}
</requirements>
${VUE_OUTPUT_FORMAT}
${profileConstraintSection()}
</system_instructions>
`.trim();
}
function buildComponentPrompt({
componentName,
componentDetails,
styling,
assetFiles,
fillContainer,
}: ComponentPromptInput): string {
const lib = libraryGuidance(getProjectProfile()?.componentLibrary);
return `
<system_instructions>
<role>
You are a Pixel-Perfect Vue 3 Frontend Engineer.
Your goal is to implement a specific UI component from Figma design data with 100% visual fidelity, as a Vue 3 SFC with \`<script setup lang="ts">\`.
</role>
<input_context>
<component_details>${componentDetails}</component_details>
${assetFiles ? `<available_assets>Available asset files: ${assetFiles}</available_assets>` : ''}
<styling>${styling}</styling>
</input_context>
<requirements>
<req_1>
**High Fidelity & Responsive**:
- Use exact design values from \`component_details.elements\` (colors, spacing, font sizes, gradients, shadows).
- Prefer \`<style scoped>\` or CSS Modules; if the stack uses Less/SCSS emit \`index.module.less\`.
</req_1>
<req_2>
**DOM Identification**:
- EVERY DOM element corresponding to a Figma node MUST have an \`id\` attribute matching the Figma node id.
</req_2>
<req_3>
**Images & Assets**:
${ASSETS_HANDLING}
</req_3>
<req_13>
**Icon Props ≠ Image URLs**:
${ICON_PROP_GUIDANCE}
</req_13>
<req_4>
**Semantic HTML & Vue idioms**:
- Use semantic tags: \`<header>\`, \`<footer>\`, \`<nav>\`, \`<section>\`, \`<button>\`.
- Use \`v-for\` for lists, \`:prop\` for binding, \`@click\` for events.
</req_4>
<req_5>
**Component Type & Props (CRITICAL)**:
- IF \`component_details.componentName\` exists: generate \`const props = defineProps<${componentName}Props>()\` from \`component_details.props\`; reference props in template as \`{{ title }}\`, \`<img :src="iconSrc" />\`.
- IF it does NOT exist: hardcode content from \`component_details.elements\` directly.
</req_5>
<req_6>
**Naming & Structure**:
- Component Name: **${componentName}** (PascalCase).
- Export via \`<script setup lang="ts">\` (auto-exposed).
- File name: \`index.vue\`.
</req_6>
${lib ? ` <req_7>\n **Component Library**:\n${lib}\n </req_7>` : ''}
<req_9>
**App Layout & Shell**:
${LAYOUT_GUIDANCE}
</req_9>
<req_10>
**Content Region (dashboard / app pages)**:
${CONTENT_REGION_GUIDANCE}
</req_10>
<req_11>
**Strict Tech-Stack Compliance (UI components)**:
${buildComponentUsageGuidance()}
</req_11>
<req_12>
**Fill Container**:
${buildStretchGuidance(fillContainer !== false)}
</req_12>
</requirements>
${VUE_OUTPUT_FORMAT}
${profileConstraintSection()}
</system_instructions>
`.trim();
}
function buildRootInjectionPrompt({ appContent, componentName }: RootInjectionInput): string {
const lib = libraryGuidance(getProjectProfile()?.componentLibrary);
return `
<system_instructions>
<role>
You are a Vue 3 code refactoring expert.
Your task is to inject a root component into an existing App.vue file with minimal changes.
</role>
<input_context>
<current_app_content>
${appContent}
</current_app_content>
<component_to_inject>
- Component Name: ${componentName}
- The root page component is published through the barrel at \`@/components\` (src/components/index.vue).
</component_to_inject>
</input_context>
<requirements>
<req_1>
**Import Statement**:
- The App entry MUST import the root component from the barrel \`@/components\`.
- Keep EXACTLY ONE import line for the root component. If the current file already has
\`import RootComponent from '@/components';\`, simply rename its local binding to \`${componentName}\`
(do NOT add a second import line). Final result:
\`import ${componentName} from '@/components';\`
</req_1>
<req_2>
**Component Rendering**:
- Inside the App component's \`<template>\`, replace the existing content with \`<${componentName} />\`.
- Keep any wrapper element and its classes.
</req_2>
<req_3>
**Preserve Existing Code**:
- Keep all existing styles and logic.
- Maintain the SFC structure (\`<template>\` / \`<script setup>\` / \`<style>\`).
</req_3>
<req_4>
**Minimal Changes**:
- Only rename the import binding and render the component.
- Do NOT add comments or explanatory text, and do NOT duplicate the import.
</req_4>
${lib ? ` <req_5>\n **Component Library**:\n${lib}\n </req_5>` : ''}
</requirements>
<output_format>
Return ONLY the complete updated App.vue code (full SFC) without markdown code blocks or explanation.
It must be valid Vue 3 that can be written directly to App.vue.
</output_format>
</system_instructions>
`.trim();
}
export const vue3Strategy: FrameworkStrategy = {
id: 'vue',
label: 'Vue 3',
isVue: true,
entryFileName: 'index.vue',
rootFileName: 'App.vue',
defaultAppContent: DEFAULT_VUE_APP,
buildFramePrompt,
buildComponentPrompt,
buildRootInjectionPrompt,
libraryGuidance,
};
......@@ -3,16 +3,55 @@ import { GraphState } from '../../state';
import { logger } from '../../utils/logger';
import { callModel } from '../../utils/call-model';
import { promisePool } from '../../utils/promise-pool';
import { generateFramePrompt, generateComponentPrompt, injectRootComponentPrompt } from './prompt';
import { getActiveStrategy } from './strategies';
import { Protocol } from '../../types';
import { createFiles, writeFile } from '../../utils/file';
import { DEFAULT_APP_CONTENT, DEFAULT_STYLING } from './constants';
import { DEFAULT_STYLING } from './constants';
import path from 'path';
import { extractCode, extractFiles } from '../../utils/parser';
import { workspaceManager } from '../../utils/workspace';
import { CodeCache, isComponentGenerated, saveComponentGenerated, isAppInjected, saveAppInjected } from '../../utils/code-cache';
/**
* Ensure src/components/index.ts re-exports the root component actually present
* on disk. This makes `import X from '@/components'` resolve reliably for Vue,
* regardless of whether the CODE node wrote src/components/index.vue or a named
* file (e.g. src/components/DashboardLayout.vue).
*
* `.ts` is in Vite's default resolve.extensions, so the directory index resolves
* to this barrel file (more robust than relying on `.vue` directory-index).
*/
function ensureVueComponentsBarrel(state: GraphState, rootName: string): void {
const componentsDir = workspaceManager.resolveAppSrc(state.workspace, 'components');
try {
if (!fs.existsSync(componentsDir)) return;
const entries = fs.readdirSync(componentsDir);
// Preferred: src/components/index.vue (the convention we instruct the LLM to use)
const pick = (ext: string) =>
entries.find((e) => e.toLowerCase() === `index.${ext}`) ||
entries.find((e) => e.toLowerCase() === `${rootName.toLowerCase()}.${ext}`) ||
entries.find((e) => e.toLowerCase().endsWith(`.${ext}`) && fs.statSync(path.join(componentsDir, e)).isFile());
const file =
pick('vue') ||
pick('tsx') ||
pick('ts') ||
pick('jsx') ||
pick('js');
if (!file) return;
const rel = `./${file}`;
const barrel = `export { default } from '${rel}';\n`;
writeFile(componentsDir, 'index.ts', barrel);
logger.printInfoLog(`🔗 components barrel -> ${rel}`);
} catch (err) {
logger.printWarnLog(`Failed to ensure components barrel: ${(err as Error).message}`);
}
}
/**
* Process a node tree and generate code for all nodes
* Uses post-order traversal (children first, then parent)
*/
......@@ -120,13 +159,14 @@ export async function generateFrame(node: Protocol, state: GraphState, assetFile
// Detect rendering modes
const renderingModes = detectRenderingModes(node);
// Generate prompt
const prompt = generateFramePrompt({
// Generate prompt (framework dispatched via the active strategy)
const prompt = getActiveStrategy().buildFramePrompt({
frameDetails: JSON.stringify(node.data),
childrenImports: JSON.stringify(childrenImports),
styling: JSON.stringify(DEFAULT_STYLING),
assetFiles: assetFilesList,
renderingModes,
fillContainer: state.fillContainer ?? true,
});
// Call AI model
......@@ -152,12 +192,13 @@ export async function generateComponent(node: Protocol, state: GraphState, asset
logger.printInfoLog(`${progressInfo} 📦 Generating Component: ${componentName}`);
// Generate prompt
const prompt = generateComponentPrompt({
// Generate prompt (framework dispatched via the active strategy)
const prompt = getActiveStrategy().buildComponentPrompt({
componentName,
componentDetails: JSON.stringify(node.data),
styling: JSON.stringify(DEFAULT_STYLING),
assetFiles: assetFilesList,
fillContainer: state.fillContainer ?? true,
});
// Call AI model
......@@ -219,19 +260,20 @@ export async function injectRootComponentToApp(state: GraphState, cache: CodeCac
return;
}
logger.printInfoLog('💉 Injecting root component into App.tsx...');
logger.printInfoLog(`💉 Injecting root component into ${getActiveStrategy().rootFileName}...`);
// Construct App.tsx path
const appTsxPath = workspaceManager.resolveAppSrc(state.workspace, 'App.tsx');
// Construct the framework-specific app entry path (App.tsx for React, App.vue for Vue, …)
const strategy = getActiveStrategy();
const appEntryPath = workspaceManager.resolveAppSrc(state.workspace, strategy.rootFileName);
// Read existing App.tsx or use default template
// Read existing app entry or use the strategy's default template
let appContent: string;
try {
appContent = fs.readFileSync(appTsxPath, 'utf8');
appContent = fs.readFileSync(appEntryPath, 'utf8');
} catch {
// Use default template if App.tsx doesn't exist
logger.printWarnLog('App.tsx not found, using default template');
appContent = DEFAULT_APP_CONTENT;
// Use default template if the app entry doesn't exist yet
logger.printWarnLog(`${strategy.rootFileName} not found, using default template`);
appContent = strategy.defaultAppContent;
}
// Get root component information
......@@ -239,8 +281,8 @@ export async function injectRootComponentToApp(state: GraphState, cache: CodeCac
const componentName = rootNode.data.name || 'RootComponent';
const componentPath = rootNode.data.path || '';
// Generate prompt
const prompt = injectRootComponentPrompt({
// Generate prompt (framework dispatched via the active strategy)
const prompt = strategy.buildRootInjectionPrompt({
appContent,
componentName,
componentPath,
......@@ -254,13 +296,20 @@ export async function injectRootComponentToApp(state: GraphState, cache: CodeCac
// Extract code (no markdown blocks expected based on prompt requirements)
const finalCode = updatedCode.includes('```') ? extractCode(updatedCode) : updatedCode.trim();
// Write updated App.tsx
const appFolderPath = path.dirname(appTsxPath);
writeFile(appFolderPath, 'App.tsx', finalCode);
// Write updated app entry
const appFolderPath = path.dirname(appEntryPath);
writeFile(appFolderPath, strategy.rootFileName, finalCode);
// Mark as injected and save immediately
saveAppInjected(cache, state.workspace);
// For Vue, ensure the "@/components" barrel re-exports whatever file the
// CODE node actually generated for the root component (LLMs sometimes
// write src/components/<Name>.vue instead of src/components/index.vue).
if (strategy.rootFileName === 'App.vue') {
ensureVueComponentsBarrel(state, componentName);
}
logger.printSuccessLog(`Successfully injected ${componentName} into App.tsx`);
} catch (error) {
logger.printErrorLog(`Failed to inject root component: ${(error as Error).message}`);
......
......@@ -2,7 +2,8 @@ import fs from 'node:fs';
import path from 'node:path';
import { logger } from '../../utils/logger';
import { GraphState } from '../../state';
import { writeScaffold } from './scaffold';
import { writeScaffold, getScaffoldEssentialFiles } from './scaffold';
import { getProjectProfile } from '../../utils/project-profile';
/**
* 'initial' node: initialize the empty project scaffold.
......@@ -23,10 +24,11 @@ export const initialProject = async (state: GraphState) => {
}
fs.mkdirSync(appPath, { recursive: true });
writeScaffold(appPath, appName);
const profile = getProjectProfile();
writeScaffold(appPath, appName, profile);
// 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'];
// Validate that essential files/directories were created (framework-specific).
const essentialFiles = getScaffoldEssentialFiles(profile);
for (const file of essentialFiles) {
const fullPath = path.join(appPath, file);
if (!fs.existsSync(fullPath)) {
......
import fs from 'node:fs';
import path from 'node:path';
import { writeFileSyncSafe } from '../../utils/file';
import type { ProjectProfile } from '../../types/project-profile';
/**
* Deterministic React + Vite + TS + TailwindCSS V4 + Less scaffold.
* Framework-aware 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.).
* The original INITIAL node hard-coded a React + Vite + TS + Tailwind scaffold.
* To support other frameworks (Vue 3, …) without touching the React template,
* scaffolding is now a small strategy layer: each framework supplies its own
* file map. Adding a new framework = append one `ScaffoldStrategy` here
* (Open-Closed Principle) — the INITIAL node and everything else stay untouched.
*/
export interface ScaffoldStrategy {
/** Lowercase framework id used for matching (mirrors the CODE strategy ids). */
id: string;
/** Files that MUST exist after scaffolding (validated by the INITIAL node). */
essentialFiles: string[];
/** Render the full file map for this framework. */
build(appName: string, profile: ProjectProfile | null): Record<string, string>;
}
// ============================================================
// React scaffold (default — behavior unchanged)
// ============================================================
function renderPackageJson(appName: string): string {
return JSON.stringify(
{
......@@ -194,31 +205,281 @@ pnpm-lock.yaml
`;
}
const reactScaffold: ScaffoldStrategy = {
id: 'react',
essentialFiles: [
'package.json',
'src',
'vite.config.ts',
'tsconfig.json',
'index.html',
'src/main.tsx',
'src/App.tsx',
],
build(appName) {
return {
'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(),
};
},
};
// ============================================================
// Vue 3 scaffold (new)
// ============================================================
type VueLibrary = 'element-plus' | 'ant-design-vue' | null;
function detectVueLibrary(profile: ProjectProfile | null): VueLibrary {
const lib = (profile?.componentLibrary || '').toLowerCase();
if (lib.includes('ant-design-vue') || lib.includes('ant design vue')) return 'ant-design-vue';
if (lib.includes('element-plus') || lib.includes('element plus')) return 'element-plus';
return null;
}
function renderVuePackageJson(appName: string, lib: VueLibrary): string {
const dependencies: Record<string, string> = {
vue: '^3.5.13',
};
if (lib === 'element-plus') {
dependencies['element-plus'] = '^2.9.1';
dependencies['@element-plus/icons-vue'] = '^2.3.1';
} else if (lib === 'ant-design-vue') {
dependencies['ant-design-vue'] = '^4.2.6';
}
return JSON.stringify(
{
name: appName || 'my-app',
private: true,
version: '0.0.0',
type: 'module',
scripts: {
dev: 'vite',
build: 'vue-tsc -b && vite build',
preview: 'vite preview',
},
dependencies,
devDependencies: {
'@vitejs/plugin-vue': '^5.2.1',
'@tailwindcss/vite': '^4.1.4',
'@types/node': '^20.17.30',
typescript: '~5.8.3',
'vue-tsc': '^2.2.0',
vite: '^6.3.5',
less: '^4.3.0',
tailwindcss: '^4.1.4',
},
},
null,
2
);
}
function renderVueViteConfig(): string {
return `import path from "node:path";
import { fileURLToPath } from "node:url";
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import tailwindcss from "@tailwindcss/vite";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export default defineConfig({
plugins: [vue(), tailwindcss()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
// Include ".vue" so bare directory imports like "@/components" resolve to
// src/components/index.vue. Vite's defaults do NOT contain ".vue" for
// directory-index resolution, which is why "@/components" failed to resolve.
extensions: ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.vue', '.json'],
},
});
`;
}
/**
* Write the full scaffold into `appPath`.
* Barrel file so that `import X from '@/components'` always resolves.
* `.ts` is in Vite's default extensions, so the directory index resolves to
* this file (not relying on `.vue` directory-index resolution). It re-exports
* the root page component written by the CODE node at src/components/index.vue.
*/
function renderVueComponentsIndex(): string {
return `export { default } from './index.vue';\n`;
}
function renderVueTsConfig(): string {
return `{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"strict": true,
"skipLibCheck": true,
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
},
"types": ["vite/client"]
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.vue"]
}
`;
}
function renderVueIndexHtml(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="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
`;
}
function renderVueMainTs(lib: VueLibrary): string {
const libImport: string =
lib === 'element-plus'
? `import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';`
: lib === 'ant-design-vue'
? `import Antd from 'ant-design-vue';
import 'ant-design-vue/dist/reset.css';`
: '';
const libUse: string =
lib === 'element-plus'
? `app.use(ElementPlus);
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component as any);
}`
: lib === 'ant-design-vue'
? `app.use(Antd);`
: '';
return `import { createApp } from 'vue';
${libImport}
import App from '@/App.vue';
import '@/globals.css';
const app = createApp(App);
${libUse}
app.mount('#app');
`;
}
function renderVueAppVue(): string {
return `<template>
<RootComponent />
</template>
<script setup lang="ts">
import RootComponent from '@/components';
</script>
`;
}
function renderVueShims(): string {
return `declare module '*.vue' {
import type { DefineComponent } from 'vue';
const component: DefineComponent<Record<string, unknown>, Record<string, unknown>, unknown>;
export default component;
}
`;
}
function renderVueGlobalsCss(): string {
return `/* global styles */
@import "tailwindcss";
@source "./src/**/*.{vue,js,ts,jsx,tsx}";
`;
}
const vue3Scaffold: ScaffoldStrategy = {
id: 'vue',
essentialFiles: [
'package.json',
'src',
'vite.config.ts',
'tsconfig.json',
'index.html',
'src/main.ts',
'src/App.vue',
],
build(appName, profile) {
const lib = detectVueLibrary(profile);
return {
'package.json': renderVuePackageJson(appName, lib),
'vite.config.ts': renderVueViteConfig(),
'tsconfig.json': renderVueTsConfig(),
'index.html': renderVueIndexHtml(appName || 'my-app'),
'src/main.ts': renderVueMainTs(lib),
'src/App.vue': renderVueAppVue(),
'src/components/index.ts': renderVueComponentsIndex(),
'src/shims-vue.d.ts': renderVueShims(),
'src/globals.css': renderVueGlobalsCss(),
'src/vite-env.d.ts': renderViteEnvDts(),
'.gitignore': renderGitignore(),
};
},
};
// ============================================================
// Registry
// ============================================================
const SCAFFOLDS: ScaffoldStrategy[] = [reactScaffold, vue3Scaffold];
/**
* Resolve a scaffold strategy from a framework string. Falls back to React
* (the legacy default) when nothing matches.
*/
export function getScaffoldForFramework(framework?: string): ScaffoldStrategy {
const fw = (framework || '').toLowerCase();
return SCAFFOLDS.find((s) => fw.includes(s.id)) ?? reactScaffold;
}
/**
* Write the framework-appropriate scaffold into `appPath`.
* @param appPath absolute path to the generated app folder
* @param appName project name (used in package.json and page title)
* @param profile the active project profile (drives framework + UI library)
*/
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(),
};
export function writeScaffold(appPath: string, appName: string, profile: ProjectProfile | null = null): void {
const strategy = getScaffoldForFramework(profile?.framework);
const files: Record<string, string> = strategy.build(appName, profile);
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');
// 用安全写入:vite 监视器 / IDE / 杀软可能短暂停有该文件句柄,重试可吸收。
writeFileSyncSafe(full, content, 'utf8');
}
// Ensure the components directory exists (App.tsx imports from '@/components').
// Ensure the components directory exists (App imports from '@/components').
fs.mkdirSync(path.join(appPath, 'src', 'components'), { recursive: true });
}
/** Essential files the INITIAL node must validate for the active framework. */
export function getScaffoldEssentialFiles(profile: ProjectProfile | null): string[] {
return getScaffoldForFramework(profile?.framework).essentialFiles;
}
......@@ -10,6 +10,8 @@ export const GraphStateAnnotation = Annotation.Root({
figmaInfo: Annotation<GlobalFigmaInfo>(),
protocol: Annotation<Protocol | undefined>(),
config: Annotation<ValidationConfig>(),
/** Whether the generated root should fill its host container (default true). */
fillContainer: Annotation<boolean>(),
});
export type GraphState = typeof GraphStateAnnotation.State;
......@@ -84,7 +84,20 @@ export const fetchFigmaNode = async (fileId: string, nodeId: string, token: stri
const resData = data.nodes?.[nodeId];
return resData?.document;
} catch (error) {
logger.printErrorLog(`Failed to fetch Figma node: ${error instanceof Error ? error.message : 'Unknown error'}`);
const resp = (error as { response?: { status?: number; data?: unknown } })?.response;
const status = resp?.status;
let msg = error instanceof Error ? error.message : 'Unknown error';
// Figma returns a clear reason in the response body for auth failures
// (e.g. {"status":403,"err":"Token expired"}). Surface it so the user
// isn't left guessing why a 403 happened.
if (status === 403) {
const body = resp?.data as { err?: string; message?: string } | undefined;
const figmaErr = body?.err || body?.message;
msg =
`Figma 返回 403${figmaErr ? `(${figmaErr})` : ''}:通常是 Figma 个人访问令牌已过期或无效。` +
` 请在 Figma 账号设置重新生成 token,更新 ~/.coderio/config.yaml 的 figma.token,并重启后端后再试`;
}
logger.printErrorLog(`Failed to fetch Figma node: ${msg}`);
return undefined;
}
};
......
import * as http from 'http';
import * as net from 'net';
import { spawn, type ChildProcess } from 'child_process';
import { spawn, execSync, type ChildProcess } from 'child_process';
import { buildDevServerUrl, DEFAULT_PORT } from '../../../nodes/validation/constants';
import { logger } from '../../../utils/logger';
......@@ -16,13 +16,24 @@ export interface DevServerHandle {
}
function terminateChildProcess(child: ChildProcess): void {
// Windows does not support POSIX signals like SIGTERM reliably.
// Calling kill() without a signal uses the platform default behavior.
// Windows 上 dev server 以 `npm → vite` 的孙进程方式运行,child.kill() 只杀到
// npm 外壳,杀不到 vite 本体,导致 dev server 泄漏、持续锁住项目目录(典型表现:
// 下一次生成在 initial 阶段写 package.json 时抛 EPERM)。因此统一用 taskkill /f /t
// 杀掉整个进程树(含孙进程)。POSIX 下按进程组 SIGKILL。
try {
if (process.platform === 'win32') {
const pid = child.pid;
if (!pid) {
child.kill();
return;
}
if (process.platform === 'win32') {
execSync(`taskkill /pid ${pid} /f /t`, { stdio: 'ignore' });
} else {
child.kill('SIGTERM');
try {
process.kill(-pid, 'SIGKILL');
} catch {
child.kill('SIGKILL');
}
}
} catch {
// ignore
......
......@@ -62,6 +62,16 @@ export async function callModel(options: CallModelOptions): Promise<string> {
// (2 x timeout), so we skip it and give the single call the full budget.
const maxRetries = Number.isFinite(requestTimeoutMs) && requestTimeoutMs > 0 && requestTimeoutMs <= 60000 ? 1 : 0;
// Qwen3 / qwen3.8-max are *reasoning* models: they emit `reasoning_content`
// and "think" before answering. On a complex Figma design the thinking phase
// alone can exceed the upstream gateway's ~300s server-side timeout (the
// endpoint then returns "Request timed out"), which is exactly the failure
// we saw. Disabling thinking (`enable_thinking: false`) keeps the same model
// but cuts latency from several minutes to tens of seconds — plenty for the
// structured extraction tasks here. Re-enable reasoning with
// COD_R_ENABLE_THINKING=1 if a future task genuinely needs it.
const enableThinking = process.env.COD_R_ENABLE_THINKING === '1';
// Get and validate config separately
let config: ModelConfig;
try {
......@@ -92,7 +102,16 @@ export async function callModel(options: CallModelOptions): Promise<string> {
},
}),
...(!streaming && { streamUsage: true }),
...(responseFormat && { modelKwargs: { response_format: responseFormat } }),
// Qwen3 reasoning toggle. We always forward response_format (needed
// for json_object mode) and additionally disable thinking
// (enable_thinking: false) unless COD_R_ENABLE_THINKING=1. See the
// enableThinking note above.
...((responseFormat || !enableThinking) && {
modelKwargs: {
...(responseFormat ? { response_format: responseFormat } : {}),
...(enableThinking ? {} : { enable_thinking: false }),
},
}),
};
const agentModel = new ChatOpenAI(requestConfig);
......
......@@ -8,6 +8,35 @@ import { FileInfo } from '../types/file-types';
* @param filePath - The path to the file
* @param content - The content to write to the file
*/
/**
* 底层安全写入:对 Windows 上常见的文件锁(EPERM / EBUSY)做有限次指数退避重试。
* 锁可能来自:预览用的 vite、IDE/编辑器文件监视器、杀软实时扫描等。
* 非锁类错误(如路径非法、磁盘满)仍立即抛出。
* @param options 透传给 fs.writeFileSync 的编码/选项(如 'utf8')
*/
export function writeFileSyncSafe(
full: string,
content: string,
options?: BufferEncoding,
): void {
let lastErr: unknown;
for (let attempt = 0; attempt < 8; attempt++) {
try {
fs.writeFileSync(full, content, options);
return;
} catch (e) {
const code = (e as NodeJS.ErrnoException)?.code;
if (code === 'EPERM' || code === 'EBUSY') {
lastErr = e;
syncSleep(50 * Math.pow(2, attempt));
continue;
}
throw e;
}
}
throw lastErr;
}
export const writeFile = (folderPath: string, filePath: string, content: string) => {
if (!folderPath || !filePath || !content) {
return;
......@@ -15,9 +44,20 @@ export const writeFile = (folderPath: string, filePath: string, content: string)
if (!fs.existsSync(folderPath)) {
fs.mkdirSync(folderPath, { recursive: true });
}
fs.writeFileSync(path.join(folderPath, filePath), content);
const full = path.join(folderPath, filePath);
writeFileSyncSafe(full, content);
};
/** 主线程同步休眠(Node 下 Atomics.wait 可用),用于写重试的退避。 */
function syncSleep(ms: number): void {
try {
const sab = new SharedArrayBuffer(4);
Atomics.wait(new Int32Array(sab), 0, 0, ms);
} catch {
/* 极端环境退化:忽略 */
}
}
/**
* Create multiple files from parsed data
*/
......
// scripts/dev.mjs
// CodeRio 开发模式启动器 / 后端生命周期 supervisor。
//
// 设计要点:
// - 本进程(supervisor)常驻,独立控制端口 4174,永远活着;
// 它只负责 spawn / kill 后端(4173) 子进程,不随后端一起退出。
// - 前端(Vite 5173)也由本进程拉起,因此「停止/重启后端」只会影响 API 与 SSE,
// 前端 UI 始终保持在线,且能随时通过 supervisor 把后端重新拉起。
// 这正是修复「关闭服务后前端再也起不来」的关键:关闭后端不再杀死能接收
// 启动指令的进程。
// - 后端以 COD_SERVE_WEB=0 启动,不托管 apps/web/dist;UI 唯一入口是 Vite 的
// 5173,代理把 /api 与 /api/stream(SSE) 转发到 4173,/devctl 转发到 4174(supervisor)。
// - 统一捕获 SIGINT/SIGTERM,按进程树回收后端与 web 及其子进程(esbuild/vite 等)。
import { spawn, spawnSync, execSync } from 'node:child_process';
import http from 'node:http';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, '..');
const WEB_PORT = process.env.COD_WEB_PORT || '5173';
const CTL_PORT = Number(process.env.COD_CTL_PORT || '4174');
const BACKEND_PORT = Number(process.env.COD_PORT || '4173');
const out_write = (s) => process.stdout.write(s);
const tag = (label) => `\u001b[36m[${label}]\u001b[0m `;
// ---- 启动前端口清理 ----
// 回收上一次未彻底退出的 supervisor 树占用本项目的端口,避免新进程被迫换端口
// (前端 Vite) 或反复 EADDRINUSE 重试 (后端)。排除自身,避免自杀。
// 用 taskkill /f /t 杀整棵进程树(含 vite / esbuild 等孙进程),确保端口真正释放。
function killStalePort(port) {
try {
const out = execSync('netstat -ano', { stdio: ['ignore', 'pipe', 'ignore'] }).toString();
const re = new RegExp(`:${port}\\s+\\S+\\s+LISTENING\\s+(\\d+)`, 'g');
const pids = new Set();
let m;
while ((m = re.exec(out))) {
const pid = Number(m[1]);
if (pid !== process.pid) pids.add(pid);
}
for (const pid of pids) {
try {
spawnSync('taskkill', ['/pid', String(pid), '/f', '/t'], { stdio: 'ignore', windowsHide: true });
} catch {
/* ignore */
}
}
if (pids.size) {
out_write(tag('dev') + `已清理端口 ${port} 上的陈旧进程: ${[...pids].join(', ')}\n`);
}
} catch {
/* ignore */
}
}
// 启动前先回收三处端口,再拉起任何子进程(统一等 OS 释放端口)。
killStalePort(WEB_PORT);
killStalePort(BACKEND_PORT);
killStalePort(CTL_PORT);
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 300);
// ---- 前端 Vite(常驻,UI 入口)----
// detached: 让子进程脱离控制台前台进程组,Ctrl+C 不会直接发给被 cmd 包裹的
// npm/vite,从而避免 Windows 弹出 "Terminate batch job (Y/N)?" 卡住。回收由
// supervisor 的 SIGINT/SIGTERM handler 统一 taskkill 完成。
const web = spawn('npm', ['--prefix', 'apps/web', 'run', 'dev'], {
cwd: ROOT,
env: { ...process.env },
shell: true,
windowsHide: true,
detached: true,
});
const pipe = (stream, label) => {
let buf = '';
stream.on('data', (d) => {
buf += d.toString();
const lines = buf.split('\n');
buf = lines.pop() ?? '';
for (const line of lines) out_write(tag(label) + line + '\n');
});
};
pipe(web.stdout, 'web');
pipe(web.stderr, 'web');
web.on('exit', (code, signal) =>
out_write(tag('web') + `exited (code=${code ?? 'null'}, signal=${signal ?? 'null'})\n`),
);
// ---- 后端(受 supervisor 管理的子进程)----
let backend = null;
function startBackend() {
if (backend && !backend.killed) return backend;
// 重启场景下旧后端可能尚未释放端口,启动前先回收,避免 EADDRINUSE。
killStalePort(BACKEND_PORT);
const p = spawn('npx', ['tsx', 'apps/server/src/index.ts'], {
cwd: ROOT,
env: { ...process.env, COD_SERVE_WEB: '0', COD_WEB_PORT: WEB_PORT, COD_PORT: String(BACKEND_PORT) },
shell: true,
windowsHide: true,
detached: true,
});
pipe(p.stdout, 'server');
pipe(p.stderr, 'server');
p.on('exit', (code, signal) => {
out_write(tag('server') + `exited (code=${code ?? 'null'}, signal=${signal ?? 'null'})\n`);
if (backend === p) backend = null;
});
backend = p;
return p;
}
function stopBackend() {
if (!backend) return;
const p = backend;
backend = null;
try {
p.kill('SIGTERM');
} catch {
/* ignore */
}
// 兜底:Windows 上 SIGTERM 可能被忽略,树杀确保回收
try {
spawn('taskkill', ['/pid', String(p.pid), '/f', '/t'], { stdio: 'ignore', windowsHide: true });
} catch {
/* ignore */
}
}
function restartBackend() {
stopBackend();
setTimeout(startBackend, 600);
}
startBackend();
out_write(`\n\u001b[32mCodeRio 开发模式已启动(supervisor 常驻):\u001b[0m\n`);
out_write(` 前端 UI : http://localhost:${WEB_PORT}/\n`);
out_write(` 后端 API : http://localhost:${BACKEND_PORT}/ (受 supervisor 管理,可在「设置」中启动/停止/重启)\n`);
out_write(` supervisor: http://localhost:${CTL_PORT}/ (控制端口,常驻)\n`);
out_write(` 按 Ctrl+C 停止全部。\n\n`);
// ---- supervisor 控制 HTTP 服务(常驻,独立于后端)----
// 控制端口(4174)已在启动时由 killStalePort() 统一清理(见文件顶部),
// 上一次未彻底退出的 supervisor 进程在启动前已被回收,避免新进程 EADDRINUSE
// 以及前端代理打到没有 /shutdown 路由的旧代码。
const ctl = http.createServer((req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Content-Type', 'application/json; charset=utf-8');
const send = (code, obj) => {
res.writeHead(code);
res.end(JSON.stringify(obj));
};
const url = (req.url || '').split('?')[0];
if (req.method === 'GET' && url === '/backend/status') {
send(200, { running: !!(backend && !backend.killed) });
return;
}
if (req.method === 'POST' && url === '/backend/stop') {
stopBackend();
send(200, { ok: true });
return;
}
if (req.method === 'POST' && url === '/backend/start') {
startBackend();
send(200, { ok: true });
return;
}
if (req.method === 'POST' && url === '/backend/restart') {
restartBackend();
send(200, { ok: true });
return;
}
// 停止全部:supervisor 自杀式退出,按进程树回收前端(Vite)与后端。
// 经 /devctl 调用,用于前端「停止全部」按钮;仅在开发模式(supervisor 常驻)可用。
if (req.method === 'POST' && url === '/shutdown') {
send(200, { ok: true });
setTimeout(shutdown, 120);
return;
}
send(404, { error: 'not found' });
});
function listenCtl(attempt = 0) {
ctl.listen(CTL_PORT, '127.0.0.1');
ctl.once('error', (err) => {
if (err.code === 'EADDRINUSE' && attempt < 15) {
setTimeout(() => listenCtl(attempt + 1), 300);
} else {
out_write(tag('supervisor') + `无法绑定 ${CTL_PORT}: ${err.message}\n`);
process.exit(1);
}
});
}
ctl.once('listening', () => {
out_write(tag('supervisor') + `control server on http://localhost:${CTL_PORT}/\n`);
});
listenCtl();
// ---- 退出时回收所有子进程 ----
let shutting = false;
function shutdown() {
if (shutting) return;
shutting = true;
out_write(`\n\u001b[33m[dev] 收到退出信号,正在按进程树回收子进程...\u001b[0m\n`);
stopBackend();
try {
spawn('taskkill', ['/pid', String(web.pid), '/f', '/t'], { stdio: 'ignore', windowsHide: true });
} catch {
try {
web.kill('SIGTERM');
} catch {
/* ignore */
}
}
setTimeout(() => process.exit(0), 600);
}
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!