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> { ...@@ -32,6 +32,7 @@ async function main(): Promise<void> {
const raw = process.env.COD_RUNTIME_CONFIG; const raw = process.env.COD_RUNTIME_CONFIG;
let targetArg: unknown = undefined; let targetArg: unknown = undefined;
let fillContainerArg: boolean | undefined = undefined;
if (raw) { if (raw) {
try { try {
const cfg = JSON.parse(raw) as { const cfg = JSON.parse(raw) as {
...@@ -39,6 +40,7 @@ async function main(): Promise<void> { ...@@ -39,6 +40,7 @@ async function main(): Promise<void> {
figma?: Record<string, unknown>; figma?: Record<string, unknown>;
projectProfile?: unknown; projectProfile?: unknown;
target?: unknown; target?: unknown;
fillContainer?: unknown;
}; };
setRuntimeConfig({ model: cfg.model, figma: cfg.figma }); setRuntimeConfig({ model: cfg.model, figma: cfg.figma });
// projectProfile is passed to design2code below (typed via the // projectProfile is passed to design2code below (typed via the
...@@ -50,6 +52,9 @@ async function main(): Promise<void> { ...@@ -50,6 +52,9 @@ async function main(): Promise<void> {
if (cfg.target && typeof cfg.target === 'object') { if (cfg.target && typeof cfg.target === 'object') {
targetArg = cfg.target; targetArg = cfg.target;
} }
if (typeof cfg.fillContainer === 'boolean') {
fillContainerArg = cfg.fillContainer;
}
} catch (e) { } catch (e) {
process.stdout.write(`__D2C_ERROR__:invalid runtime config: ${e instanceof Error ? e.message : String(e)}\n`); process.stdout.write(`__D2C_ERROR__:invalid runtime config: ${e instanceof Error ? e.message : String(e)}\n`);
process.exit(1); process.exit(1);
...@@ -67,6 +72,7 @@ async function main(): Promise<void> { ...@@ -67,6 +72,7 @@ async function main(): Promise<void> {
resume: false, resume: false,
projectProfile: projectProfileArg, projectProfile: projectProfileArg,
target: targetArg as never, target: targetArg as never,
fillContainer: fillContainerArg,
}); });
process.stdout.write('__D2C_DONE__\n'); process.stdout.write('__D2C_DONE__\n');
process.exit(0); process.exit(0);
......
import { readFileSync } from 'node:fs'; import { readFileSync } from 'node:fs';
import { spawn } from 'node:child_process'; import { spawn, execSync } from 'node:child_process';
import path from 'node:path'; import path from 'node:path';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import type { Server } from 'node:http';
import { JobStore } from './jobStore'; import { JobStore } from './jobStore';
import { JobQueue } from './queue'; import { JobQueue } from './queue';
import { PreviewManager } from './preview'; import { PreviewManager } from './preview';
import { ProjectRunner } from './project-runner';
import { createApp } from './server'; import { createApp } from './server';
import { loadDotEnv, loadServerModelConfig, resolveServerOptions, loadProjectProfile } from './config'; import { loadDotEnv, loadServerModelConfig, resolveServerOptions, loadProjectProfile } from './config';
import { runJob } from './runner'; import { runJob } from './runner';
import { parseFigmaUrl, emptyProfile } from 'coderio';
import type { ProjectProfile } from 'coderio';
import type { TechStack } from './types';
const __dirname = path.dirname(fileURLToPath(import.meta.url)); 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 { function readPkgVersion(p: string): string {
try { try {
return JSON.parse(readFileSync(p, 'utf8')).version ?? '0.0.0'; return JSON.parse(readFileSync(p, 'utf8')).version ?? '0.0.0';
...@@ -46,22 +93,35 @@ function main(): void { ...@@ -46,22 +93,35 @@ function main(): void {
path.join(__dirname, '..', '..', '..', 'packages', 'coderio', 'package.json'), path.join(__dirname, '..', '..', '..', 'packages', 'coderio', 'package.json'),
); );
// 由 createApp 返回后在下方赋值;restartServer 闭包里需要引用它来主动释放端口。
let server: Server;
const restartServer = (): void => { const restartServer = (): void => {
// 重启前先清掉端口上任何「非自身」的陈旧监听者(孤儿/上次没退干净的进程),
// 确保新进程能独占端口,避免双绑导致部分请求打到半死进程而报 500。
killOtherListenersOnPort(opts.port, process.pid);
try { try {
const child = spawn('npm', ['run', 'server'], { const child = spawn('npm', ['run', 'server'], {
cwd: REPO_ROOT, cwd: REPO_ROOT,
detached: true, detached: true,
stdio: 'ignore', stdio: 'ignore',
shell: true, shell: true,
env: process.env, env: { ...process.env },
}); });
child.unref(); child.unref();
} catch (e) { } catch (e) {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
console.error('重启失败:', e); 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. // 留出足够时间让端口被 OS 回收后再退出。
setTimeout(() => process.exit(0), 400); setTimeout(() => process.exit(0), 600);
}; };
const shutdownServer = (): void => { const shutdownServer = (): void => {
...@@ -75,39 +135,101 @@ function main(): void { ...@@ -75,39 +135,101 @@ function main(): void {
}; };
const preview = new PreviewManager((state) => hub.broadcast('preview', state)); 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( const queue = new JobQueue(
store, 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, opts.maxConcurrent,
(s) => hub.broadcast('jobs', s.list()), (s) => hub.broadcast('jobs', s.list()),
); );
const { server, broadcast: realBroadcast } = createApp({ const { server: srv, broadcast: realBroadcast } = createApp({
store, store,
queue, queue,
preview, preview,
projectRunner,
opts, opts,
startTime: START_TIME, startTime: START_TIME,
serverVersion: SERVER_VERSION, serverVersion: SERVER_VERSION,
coderioVersion: CODERIO_VERSION, coderioVersion: CODERIO_VERSION,
admin: { restart: restartServer, shutdown: shutdownServer }, admin: { restart: restartServer, shutdown: shutdownServer },
}); });
server = srv;
hub.broadcast = realBroadcast; hub.broadcast = realBroadcast;
server.listen(opts.port, opts.host, () => { // 启动并带 EADDRINUSE 重试:重启场景下旧进程可能尚未释放端口,
const banner = [ // 新进程应轮询等待而非直接崩溃,保证重启在任何时序下都成功。
'', const listenWithRetry = (attempt = 0): void => {
' 🎨 CodeRio 编排服务已启动', const onError = (err: NodeJS.ErrnoException): void => {
` 本地访问: http://localhost:${opts.port}`, if (err.code === 'EADDRINUSE') {
` 数据目录: ${opts.dataDir}`, if (attempt < 25) {
` 产物目录: ${opts.outputDir}`, // eslint-disable-next-line no-console
` 并发上限: ${opts.maxConcurrent}`, console.warn(
' 按 Ctrl+C 停止', ` ⚠ 端口 ${opts.port} 仍被占用,0.3s 后重试 (${attempt + 1}/25)`,
'', );
].join('\n'); setTimeout(() => listenWithRetry(attempt + 1), 300);
// eslint-disable-next-line no-console return;
console.log(banner); }
}); // 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(); main();
...@@ -58,11 +58,18 @@ export class PreviewManager { ...@@ -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 { try {
const out = execSync('netstat -ano', { stdio: ['ignore', 'pipe', 'ignore'] }).toString(); 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>(); const pids = new Set<string>();
let m: RegExpExecArray | null; let m: RegExpExecArray | null;
while ((m = re.exec(out))) pids.add(m[2]); while ((m = re.exec(out))) pids.add(m[2]);
......
...@@ -100,6 +100,8 @@ export async function runJob( ...@@ -100,6 +100,8 @@ export async function runJob(
// Where the generated code should land (standalone / new-page / // Where the generated code should land (standalone / new-page /
// modify-slot). Recorded for the engine; slot rewriting is a later phase. // modify-slot). Recorded for the engine; slot rewriting is a later phase.
target: job.target ?? null, target: job.target ?? null,
// Whether the generated root should fill its host container (default true).
fillContainer: job.fillContainer ?? true,
}); });
const args = [ const args = [
......
...@@ -7,6 +7,7 @@ import { subscribeLogs, parseFigmaUrl, type LogEntry } from 'coderio'; ...@@ -7,6 +7,7 @@ import { subscribeLogs, parseFigmaUrl, type LogEntry } from 'coderio';
import type { JobStore } from './jobStore'; import type { JobStore } from './jobStore';
import type { JobQueue } from './queue'; import type { JobQueue } from './queue';
import { PreviewManager } from './preview'; import { PreviewManager } from './preview';
import { ProjectRunner } from './project-runner';
import { configView, loadServerModelConfig, resolveServerOptions, loadProjectProfile, saveProjectProfile, projectProfileTemplate } from './config'; import { configView, loadServerModelConfig, resolveServerOptions, loadProjectProfile, saveProjectProfile, projectProfileTemplate } from './config';
import { scanProject } from './project-scanner'; import { scanProject } from './project-scanner';
import type { import type {
...@@ -104,6 +105,7 @@ export interface ServerDeps { ...@@ -104,6 +105,7 @@ export interface ServerDeps {
store: JobStore; store: JobStore;
queue: JobQueue; queue: JobQueue;
preview: PreviewManager; preview: PreviewManager;
projectRunner: ProjectRunner;
opts: ReturnType<typeof resolveServerOptions>; opts: ReturnType<typeof resolveServerOptions>;
startTime: number; startTime: number;
serverVersion: string; serverVersion: string;
...@@ -118,7 +120,7 @@ export interface AppHandle { ...@@ -118,7 +120,7 @@ export interface AppHandle {
} }
export function createApp(deps: ServerDeps): 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 sseClients = new Set<ServerResponse>();
const model = loadServerModelConfig(); const model = loadServerModelConfig();
...@@ -203,8 +205,27 @@ export function createApp(deps: ServerDeps): AppHandle { ...@@ -203,8 +205,27 @@ export function createApp(deps: ServerDeps): AppHandle {
try { try {
const url = new URL(req.url ?? '/', `http://localhost:${opts.port}`); 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) ---- // ---- 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)); const fp = path.join(WEB_DIST, decodeURIComponent(url.pathname));
if (existsSync(fp) && statSync(fp).isFile()) { if (existsSync(fp) && statSync(fp).isFile()) {
serveStaticFile(res, fp); serveStaticFile(res, fp);
...@@ -213,7 +234,7 @@ export function createApp(deps: ServerDeps): AppHandle { ...@@ -213,7 +234,7 @@ export function createApp(deps: ServerDeps): AppHandle {
} }
// ---- SPA root / index ---- // ---- 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(); const idx = resolveIndexHtml();
if (existsSync(idx)) { if (existsSync(idx)) {
serveStaticFile(res, idx); serveStaticFile(res, idx);
...@@ -226,6 +247,7 @@ export function createApp(deps: ServerDeps): AppHandle { ...@@ -226,6 +247,7 @@ export function createApp(deps: ServerDeps): AppHandle {
// ---- SPA fallback (client-side routing, non-asset GET) ---- // ---- SPA fallback (client-side routing, non-asset GET) ----
if ( if (
SERVE_WEB &&
req.method === 'GET' && req.method === 'GET' &&
!url.pathname.startsWith('/api') && !url.pathname.startsWith('/api') &&
!path.extname(url.pathname) !path.extname(url.pathname)
...@@ -252,6 +274,7 @@ export function createApp(deps: ServerDeps): AppHandle { ...@@ -252,6 +274,7 @@ export function createApp(deps: ServerDeps): AppHandle {
} }
broadcast('jobs', store.list()); // replay current jobs snapshot broadcast('jobs', store.list()); // replay current jobs snapshot
res.write(`event: preview\ndata: ${JSON.stringify(preview.state)}\n\n`); 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(() => { const ping = setInterval(() => {
try { try {
res.write(': ping\n\n'); res.write(': ping\n\n');
...@@ -418,6 +441,8 @@ export function createApp(deps: ServerDeps): AppHandle { ...@@ -418,6 +441,8 @@ export function createApp(deps: ServerDeps): AppHandle {
: opts.outputDir, : opts.outputDir,
appName: body.appName || 'my-app', appName: body.appName || 'my-app',
target: body.target ?? null, target: body.target ?? null,
stack: body.stack ?? null,
fillContainer: body.fillContainer ?? true,
resultDir: null, resultDir: null,
reportPath: null, reportPath: null,
error: null, error: null,
...@@ -567,10 +592,44 @@ export function createApp(deps: ServerDeps): AppHandle { ...@@ -567,10 +592,44 @@ export function createApp(deps: ServerDeps): AppHandle {
return; 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) ---- // ---- POST /api/admin/restart (self-restart) ----
if (req.method === 'POST' && url.pathname === '/api/admin/restart') { if (req.method === 'POST' && url.pathname === '/api/admin/restart') {
sendJson(res, 200, { ok: true, message: '服务正在重启…' }); sendJson(res, 200, { ok: true, message: '服务正在重启…' });
res.on('finish', () => admin.restart()); // 直接触发重启,不依赖 res.on('finish'):否则连接被提前关闭时
// 回调可能不触发,导致「点了重启却没反应」。
admin.restart();
return; return;
} }
......
...@@ -24,6 +24,13 @@ export interface GenerationTarget { ...@@ -24,6 +24,13 @@ export interface GenerationTarget {
slot?: string; slot?: string;
} }
/** Tech stack chosen for a standalone generation. */
export interface TechStack {
framework: string;
styling?: string;
componentLibrary?: string;
}
export interface Job { export interface Job {
id: string; id: string;
status: JobStatus; status: JobStatus;
...@@ -33,6 +40,10 @@ export interface Job { ...@@ -33,6 +40,10 @@ export interface Job {
appName: string; appName: string;
/** Where the generated code targets (standalone / new-page / modify-slot). */ /** Where the generated code targets (standalone / new-page / modify-slot). */
target: GenerationTarget | null; 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. */ /** Absolute path to the generated <outputDir>/coderio/<figmaName> workspace. */
resultDir: string | null; resultDir: string | null;
reportPath: string | null; reportPath: string | null;
...@@ -52,6 +63,10 @@ export interface GenerateRequest { ...@@ -52,6 +63,10 @@ export interface GenerateRequest {
appName?: string; appName?: string;
/** Where the generated code should target. */ /** Where the generated code should target. */
target?: GenerationTarget | null; 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 { export interface LogEntry {
...@@ -129,3 +144,28 @@ export interface SystemStatus { ...@@ -129,3 +144,28 @@ export interface SystemStatus {
env: EnvInfo; env: EnvInfo;
jobs: JobStats; 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 { ...@@ -14,10 +14,15 @@ import {
AlertTriangle, AlertTriangle,
CheckCircle2, CheckCircle2,
Layers, Layers,
Play,
Square,
ExternalLink,
Loader2,
} from 'lucide-react'; } from 'lucide-react';
import { api } from '@/lib/api'; import { api, onSSE } from '@/lib/api';
import type { import type {
ProjectProfile, ProjectProfile,
ProjectRunState,
TokenCategory, TokenCategory,
TokenMapping, TokenMapping,
ComponentMapping, ComponentMapping,
...@@ -88,6 +93,8 @@ export function ProjectAccessPanel() { ...@@ -88,6 +93,8 @@ export function ProjectAccessPanel() {
const [tab, setTab] = useState<TabKey>('meta'); const [tab, setTab] = useState<TabKey>('meta');
const [dirty, setDirty] = useState(false); const [dirty, setDirty] = useState(false);
const [rootDirDraft, setRootDirDraft] = useState(''); const [rootDirDraft, setRootDirDraft] = useState('');
const [run, setRun] = useState<ProjectRunState | null>(null);
const [runBusy, setRunBusy] = useState(false);
const load = useCallback(async () => { const load = useCallback(async () => {
setLoading(true); setLoading(true);
...@@ -107,6 +114,49 @@ export function ProjectAccessPanel() { ...@@ -107,6 +114,49 @@ export function ProjectAccessPanel() {
void load(); void load();
}, [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>) => { const update = useCallback((patch: Partial<ProjectProfile>) => {
setProfile((p) => (p ? { ...p, ...patch } : p)); setProfile((p) => (p ? { ...p, ...patch } : p));
setDirty(true); setDirty(true);
...@@ -280,6 +330,56 @@ export function ProjectAccessPanel() { ...@@ -280,6 +330,56 @@ export function ProjectAccessPanel() {
</Button> </Button>
</div> </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) ? ( {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"> <div className="mt-3 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
<span>已识别</span> <span>已识别</span>
......
...@@ -98,6 +98,30 @@ export const ROUTING_PRESETS = [ ...@@ -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 { function norm(p: string): string {
......
...@@ -8,24 +8,78 @@ import type { ...@@ -8,24 +8,78 @@ import type {
SystemStatus, SystemStatus,
ProjectProfile, ProjectProfile,
FsListResult, FsListResult,
ProjectRunState,
} from './types'; } from './types';
// 同源调用:开发时由 Vite 代理到后端 :4173;生产时后端直接托管本应用。 // 同源调用:开发时由 Vite 代理到后端 :4173;生产时后端直接托管本应用。
const BASE = ''; const BASE = '';
async function http<T>(path: string, init?: RequestInit): Promise<T> { // 后端重启宽限期:重启后短时间内,网络错误/5xx 属「后端短暂不可用」,
const res = await fetch(BASE + path, { // http() 会静默重试,避免重启窗口期弹出一堆「请求失败」。宽限期外仍照常报错。
...init, let backendRestartingUntil = 0;
headers: { 'Content-Type': 'application/json', ...(init?.headers ?? {}) }, 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 text = await res.text();
const data = text ? JSON.parse(text) : null; const data = text ? JSON.parse(text) : null;
if (!res.ok) { 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; 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 = { export const api = {
getConfig: () => http<ServerConfigView>('/api/config'), getConfig: () => http<ServerConfigView>('/api/config'),
generate: (req: GenerateRequest) => generate: (req: GenerateRequest) =>
...@@ -73,41 +127,124 @@ export const api = { ...@@ -73,41 +127,124 @@ export const api = {
http<FsListResult>( http<FsListResult>(
'/api/fs/list' + (dir ? `?dir=${encodeURIComponent(dir)}` : ''), '/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 { export interface SSEPayload {
event: SSEEventName; event: SSEEventName;
data: unknown; data: unknown;
} }
/** // 全局单例 SSE 连接:整个应用只建立一条 /api/stream,所有组件通过 onSSE 订阅
* 订阅后端 SSE 流(/api/stream)。后端会推送三种事件: // 特定事件。避免每个组件各开一条连接、也彻底消除「前端用 setInterval 轮询后端状态」的刷屏。
* - log: 实时引擎日志 (LogEntry) // 后端在状态变化时通过 hub.broadcast 推送(jobs / preview / projectRun 等),SSE 连接建立时
* - jobs: 任务列表快照 (Job[]),每次状态变更都会重发 // 还会 replay 一次当前快照(见 server.ts 的 /api/stream 处理)。
* - preview: 预览服务状态 (PreviewState) let sseInstance: EventSource | null = null;
* 返回取消订阅函数。 const sseEventSubs = new Map<SSEEventName, Set<(data: unknown) => void>>();
*/ const sseOpenSubs = new Set<() => void>();
export function subscribeSSE( const sseCloseSubs = new Set<() => void>();
onMessage: (msg: SSEPayload) => void, const SSE_EVENTS: SSEEventName[] = ['log', 'jobs', 'preview', 'projectRun', 'system'];
onError?: (e: Event) => void,
): () => void { function ensureSSE(): EventSource {
if (sseInstance) return sseInstance;
const es = new EventSource('/api/stream'); const es = new EventSource('/api/stream');
const handle = (name: SSEEventName) => (e: MessageEvent) => { for (const name of SSE_EVENTS) {
try { es.addEventListener(name, (e: MessageEvent) => {
onMessage({ event: name, data: JSON.parse(e.data) }); try {
} catch { const data = JSON.parse(e.data);
/* ignore malformed */ 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); /** 订阅 SSE 连接状态变化(打开 / 关闭),返回取消订阅函数。 */
es.onerror = (e) => { export function onSSEStatus(
onError?.(e); 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 }; 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 { ...@@ -6,7 +6,7 @@ import {
useState, useState,
type ReactNode, type ReactNode,
} from 'react'; } from 'react';
import { subscribeSSE } from './api'; import { onSSEStatus } from './api';
interface ConnectionContextValue { interface ConnectionContextValue {
connected: boolean; connected: boolean;
...@@ -29,7 +29,7 @@ export function ConnectionProvider({ children }: { children: ReactNode }) { ...@@ -29,7 +29,7 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
useEffect(() => { useEffect(() => {
aliveRef.current = true; aliveRef.current = true;
const unsub = subscribeSSE( const unsub = onSSEStatus(
() => { () => {
if (!aliveRef.current) return; if (!aliveRef.current) return;
setConnected(true); setConnected(true);
...@@ -40,13 +40,8 @@ export function ConnectionProvider({ children }: { children: ReactNode }) { ...@@ -40,13 +40,8 @@ export function ConnectionProvider({ children }: { children: ReactNode }) {
setConnected(false); setConnected(false);
}, },
); );
// SSE 打开即视为已连接(即使尚未收到业务事件)
const t = window.setTimeout(() => {
if (aliveRef.current) setConnected(true);
}, 800);
return () => { return () => {
aliveRef.current = false; aliveRef.current = false;
window.clearTimeout(t);
unsub(); unsub();
}; };
}, []); }, []);
......
...@@ -13,6 +13,10 @@ export interface Job { ...@@ -13,6 +13,10 @@ export interface Job {
outputDir: string; outputDir: string;
appName: string; appName: string;
target: GenerationTarget | null; target: GenerationTarget | null;
/** 生成时选定的技术栈(独立预览时);项目模式为 null。 */
stack?: TechStack | null;
/** 生成的页面是否撑满容器(默认 true)。 */
fillContainer?: boolean;
resultDir: string | null; resultDir: string | null;
reportPath: string | null; reportPath: string | null;
error: string | null; error: string | null;
...@@ -37,6 +41,17 @@ export interface GenerateRequest { ...@@ -37,6 +41,17 @@ export interface GenerateRequest {
outputDir?: string; outputDir?: string;
appName?: string; appName?: string;
target?: GenerationTarget | null; target?: GenerationTarget | null;
/** 生成前选定的技术栈(独立预览时生效;项目模式由「项目接入」画像决定,此处为 null)。 */
stack?: TechStack | null;
/** 生成的页面是否撑满容器(默认 true;固定宽度设计稿可选 false 居中)。 */
fillContainer?: boolean;
}
/** 一次生成所选的技术栈组合。 */
export interface TechStack {
framework: string;
styling?: string;
componentLibrary?: string;
} }
export interface GenerateResponse { export interface GenerateResponse {
...@@ -55,6 +70,21 @@ export interface PreviewState { ...@@ -55,6 +70,21 @@ export interface PreviewState {
error: string | null; 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 { export interface JobStats {
total: number; total: number;
queued: number; queued: number;
......
...@@ -15,11 +15,23 @@ export default defineConfig({ ...@@ -15,11 +15,23 @@ export default defineConfig({
}, },
server: { server: {
port: 5173, port: 5173,
// 绑定 IPv4,确保 127.0.0.1 与 localhost 均可访问(Windows 上 localhost
// 默认优先 ::1,会导致 127.0.0.1 直连代理/SSE 时失败)。
host: '127.0.0.1',
proxy: { proxy: {
'/api': { '/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, changeOrigin: true,
}, },
// supervisor 控制端口(scripts/dev.mjs):后端启动/停止/重启。
// 它独立于后端常驻,因此「停止后端」后前端仍能向其发启动指令。
'/devctl': {
target: 'http://127.0.0.1:4174',
changeOrigin: true,
rewrite: (p) => p.replace(/^\/devctl/, ''),
},
}, },
}, },
build: { build: {
......
...@@ -9,6 +9,7 @@ ...@@ -9,6 +9,7 @@
"server:dev": "tsx watch apps/server/src/index.ts", "server:dev": "tsx watch apps/server/src/index.ts",
"web": "npm --prefix apps/web run dev", "web": "npm --prefix apps/web run dev",
"web:build": "npm --prefix apps/web run build", "web:build": "npm --prefix apps/web run build",
"dev": "node scripts/dev.mjs",
"build:all": "npm run coderio:build && npm run web:build" "build:all": "npm run coderio:build && npm run web:build"
}, },
"engines": { "engines": {
......
...@@ -24,6 +24,7 @@ export const registerD2PCommand = (program: Command) => { ...@@ -24,6 +24,7 @@ export const registerD2PCommand = (program: Command) => {
protocol: undefined, protocol: undefined,
messages: [], messages: [],
config: {}, config: {},
fillContainer: true,
}); });
logger.printSuccessLog('Successfully completed Design to Protocol conversion!'); logger.printSuccessLog('Successfully completed Design to Protocol conversion!');
......
...@@ -31,6 +31,7 @@ export const registerP2CCommand = (program: Command) => { ...@@ -31,6 +31,7 @@ export const registerP2CCommand = (program: Command) => {
}, },
messages: [], messages: [],
config: {}, config: {},
fillContainer: true,
}; };
await initialProject(state); await initialProject(state);
await generateCode(state); await generateCode(state);
......
...@@ -80,6 +80,7 @@ export function registerValidateCommand(program: Command): void { ...@@ -80,6 +80,7 @@ export function registerValidateCommand(program: Command): void {
protocol, protocol,
messages: [], messages: [],
config, config,
fillContainer: true,
}); });
// If we reach here, validation passed // If we reach here, validation passed
......
...@@ -65,6 +65,13 @@ export interface Design2CodeOptions { ...@@ -65,6 +65,13 @@ export interface Design2CodeOptions {
page?: string; page?: string;
slot?: string; slot?: string;
} | null; } | 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> { 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?: ...@@ -169,6 +176,7 @@ export async function design2code(url: string, mode?: ValidationMode, options?:
config: { config: {
validationMode, validationMode,
}, },
fillContainer: opts.fillContainer ?? true,
}; };
await graph.invoke(state, config); await graph.invoke(state, config);
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
// ============================================ // ============================================
import { getProjectProfile, renderProfileConstraint } from '../../utils/project-profile'; import { getProjectProfile, renderProfileConstraint } from '../../utils/project-profile';
import { buildComponentUsageGuidance, buildStretchGuidance } from './strategies/component-usage';
/** /**
* Renders the target-project profile (components / tokens / utils / conventions) * Renders the target-project profile (components / tokens / utils / conventions)
...@@ -46,9 +47,36 @@ const ASSETS_HANDLING = ` ...@@ -46,9 +47,36 @@ const ASSETS_HANDLING = `
- **Usage**: \`<img src={ArXivIcon} />\`, do not use backgroundImage property. - **Usage**: \`<img src={ArXivIcon} />\`, do not use backgroundImage property.
- **NEVER** use the string path directly in JSX or styles.`; - **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 = ` const DOM_IDS_REQUIREMENT = `
- Assign \`id\` attributes to the main container and any internal elements, matching \`frame_details\`.`; - 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 = ` const REACT_IMPORT_RULE = `
- Do **NOT** include \`import React from 'react';\` at the top of the file.`; - Do **NOT** include \`import React from 'react';\` at the top of the file.`;
...@@ -148,6 +176,7 @@ export const generateFramePrompt = ({ ...@@ -148,6 +176,7 @@ export const generateFramePrompt = ({
assetFiles, assetFiles,
styling, styling,
renderingModes, renderingModes,
fillContainer,
}: { }: {
childrenImports: string; childrenImports: string;
frameDetails: string; frameDetails: string;
...@@ -157,6 +186,7 @@ export const generateFramePrompt = ({ ...@@ -157,6 +186,7 @@ export const generateFramePrompt = ({
hasStates: boolean; hasStates: boolean;
hasIndependentChildren: boolean; hasIndependentChildren: boolean;
}; };
fillContainer?: boolean;
}) => { }) => {
return ` return `
<system_instructions> <system_instructions>
...@@ -206,12 +236,22 @@ ${STYLING_GUIDELINES} ...@@ -206,12 +236,22 @@ ${STYLING_GUIDELINES}
- Use \`relative\` positioning for the container. - Use \`relative\` positioning for the container.
- Use \`spacing\` field in <frame_details> to set the spacing between elements - Use \`spacing\` field in <frame_details> to set the spacing between elements
</req_2> </req_2>
<req_7>
**App Layout & Shell**:
${LAYOUT_GUIDANCE}
</req_7>
<req_3> <req_3>
**Images & Assets**: **Images & Assets**:
${ASSETS_HANDLING} ${ASSETS_HANDLING}
</req_3> </req_3>
<req_13>
**Icon Props ≠ Image URLs**:
${ICON_PROP_GUIDANCE}
</req_13>
<req_4> <req_4>
**DOM IDs**: **DOM IDs**:
${DOM_IDS_REQUIREMENT} ${DOM_IDS_REQUIREMENT}
...@@ -226,6 +266,21 @@ ${REACT_IMPORT_RULE} ...@@ -226,6 +266,21 @@ ${REACT_IMPORT_RULE}
**File Naming**: **File Naming**:
${FILE_NAMING_CONVENTION} ${FILE_NAMING_CONVENTION}
</req_6> </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> </requirements>
${OUTPUT_FORMAT} ${OUTPUT_FORMAT}
...@@ -239,11 +294,13 @@ export const generateComponentPrompt = ({ ...@@ -239,11 +294,13 @@ export const generateComponentPrompt = ({
componentDetails, componentDetails,
styling, styling,
assetFiles, assetFiles,
fillContainer,
}: { }: {
componentName: string; componentName: string;
componentDetails: string; componentDetails: string;
styling: string; styling: string;
assetFiles?: string; assetFiles?: string;
fillContainer?: boolean;
}) => { }) => {
return ` return `
<system_instructions> <system_instructions>
...@@ -311,6 +368,11 @@ ${STYLING_GUIDELINES} ...@@ -311,6 +368,11 @@ ${STYLING_GUIDELINES}
${ASSETS_HANDLING} ${ASSETS_HANDLING}
</req_3> </req_3>
<req_13>
**Icon Props ≠ Image URLs**:
${ICON_PROP_GUIDANCE}
</req_13>
<req_4> <req_4>
**Semantic HTML**: **Semantic HTML**:
- Use semantic tags: \`<header>\`, \`<footer>\`, \`<nav>\`, \`<article>\`, \`<section>\`, \`<button>\`. - Use semantic tags: \`<header>\`, \`<footer>\`, \`<nav>\`, \`<article>\`, \`<section>\`, \`<button>\`.
...@@ -344,6 +406,21 @@ ${ASSETS_HANDLING} ...@@ -344,6 +406,21 @@ ${ASSETS_HANDLING}
**Both types**: Do NOT repeat JSX to simulate grids; parent components handle iteration. **Both types**: Do NOT repeat JSX to simulate grids; parent components handle iteration.
</req_7> </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> <req_9>
**React Import**: **React Import**:
${REACT_IMPORT_RULE} ${REACT_IMPORT_RULE}
......
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;
}
...@@ -3,16 +3,55 @@ import { GraphState } from '../../state'; ...@@ -3,16 +3,55 @@ import { GraphState } from '../../state';
import { logger } from '../../utils/logger'; import { logger } from '../../utils/logger';
import { callModel } from '../../utils/call-model'; import { callModel } from '../../utils/call-model';
import { promisePool } from '../../utils/promise-pool'; import { promisePool } from '../../utils/promise-pool';
import { generateFramePrompt, generateComponentPrompt, injectRootComponentPrompt } from './prompt'; import { getActiveStrategy } from './strategies';
import { Protocol } from '../../types'; import { Protocol } from '../../types';
import { createFiles, writeFile } from '../../utils/file'; import { createFiles, writeFile } from '../../utils/file';
import { DEFAULT_APP_CONTENT, DEFAULT_STYLING } from './constants'; import { DEFAULT_STYLING } from './constants';
import path from 'path'; import path from 'path';
import { extractCode, extractFiles } from '../../utils/parser'; import { extractCode, extractFiles } from '../../utils/parser';
import { workspaceManager } from '../../utils/workspace'; import { workspaceManager } from '../../utils/workspace';
import { CodeCache, isComponentGenerated, saveComponentGenerated, isAppInjected, saveAppInjected } from '../../utils/code-cache'; 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 * Process a node tree and generate code for all nodes
* Uses post-order traversal (children first, then parent) * Uses post-order traversal (children first, then parent)
*/ */
...@@ -120,13 +159,14 @@ export async function generateFrame(node: Protocol, state: GraphState, assetFile ...@@ -120,13 +159,14 @@ export async function generateFrame(node: Protocol, state: GraphState, assetFile
// Detect rendering modes // Detect rendering modes
const renderingModes = detectRenderingModes(node); const renderingModes = detectRenderingModes(node);
// Generate prompt // Generate prompt (framework dispatched via the active strategy)
const prompt = generateFramePrompt({ const prompt = getActiveStrategy().buildFramePrompt({
frameDetails: JSON.stringify(node.data), frameDetails: JSON.stringify(node.data),
childrenImports: JSON.stringify(childrenImports), childrenImports: JSON.stringify(childrenImports),
styling: JSON.stringify(DEFAULT_STYLING), styling: JSON.stringify(DEFAULT_STYLING),
assetFiles: assetFilesList, assetFiles: assetFilesList,
renderingModes, renderingModes,
fillContainer: state.fillContainer ?? true,
}); });
// Call AI model // Call AI model
...@@ -152,12 +192,13 @@ export async function generateComponent(node: Protocol, state: GraphState, asset ...@@ -152,12 +192,13 @@ export async function generateComponent(node: Protocol, state: GraphState, asset
logger.printInfoLog(`${progressInfo} 📦 Generating Component: ${componentName}`); logger.printInfoLog(`${progressInfo} 📦 Generating Component: ${componentName}`);
// Generate prompt // Generate prompt (framework dispatched via the active strategy)
const prompt = generateComponentPrompt({ const prompt = getActiveStrategy().buildComponentPrompt({
componentName, componentName,
componentDetails: JSON.stringify(node.data), componentDetails: JSON.stringify(node.data),
styling: JSON.stringify(DEFAULT_STYLING), styling: JSON.stringify(DEFAULT_STYLING),
assetFiles: assetFilesList, assetFiles: assetFilesList,
fillContainer: state.fillContainer ?? true,
}); });
// Call AI model // Call AI model
...@@ -219,19 +260,20 @@ export async function injectRootComponentToApp(state: GraphState, cache: CodeCac ...@@ -219,19 +260,20 @@ export async function injectRootComponentToApp(state: GraphState, cache: CodeCac
return; return;
} }
logger.printInfoLog('💉 Injecting root component into App.tsx...'); logger.printInfoLog(`💉 Injecting root component into ${getActiveStrategy().rootFileName}...`);
// Construct App.tsx path // Construct the framework-specific app entry path (App.tsx for React, App.vue for Vue, …)
const appTsxPath = workspaceManager.resolveAppSrc(state.workspace, 'App.tsx'); 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; let appContent: string;
try { try {
appContent = fs.readFileSync(appTsxPath, 'utf8'); appContent = fs.readFileSync(appEntryPath, 'utf8');
} catch { } catch {
// Use default template if App.tsx doesn't exist // Use default template if the app entry doesn't exist yet
logger.printWarnLog('App.tsx not found, using default template'); logger.printWarnLog(`${strategy.rootFileName} not found, using default template`);
appContent = DEFAULT_APP_CONTENT; appContent = strategy.defaultAppContent;
} }
// Get root component information // Get root component information
...@@ -239,8 +281,8 @@ export async function injectRootComponentToApp(state: GraphState, cache: CodeCac ...@@ -239,8 +281,8 @@ export async function injectRootComponentToApp(state: GraphState, cache: CodeCac
const componentName = rootNode.data.name || 'RootComponent'; const componentName = rootNode.data.name || 'RootComponent';
const componentPath = rootNode.data.path || ''; const componentPath = rootNode.data.path || '';
// Generate prompt // Generate prompt (framework dispatched via the active strategy)
const prompt = injectRootComponentPrompt({ const prompt = strategy.buildRootInjectionPrompt({
appContent, appContent,
componentName, componentName,
componentPath, componentPath,
...@@ -254,13 +296,20 @@ export async function injectRootComponentToApp(state: GraphState, cache: CodeCac ...@@ -254,13 +296,20 @@ export async function injectRootComponentToApp(state: GraphState, cache: CodeCac
// Extract code (no markdown blocks expected based on prompt requirements) // Extract code (no markdown blocks expected based on prompt requirements)
const finalCode = updatedCode.includes('```') ? extractCode(updatedCode) : updatedCode.trim(); const finalCode = updatedCode.includes('```') ? extractCode(updatedCode) : updatedCode.trim();
// Write updated App.tsx // Write updated app entry
const appFolderPath = path.dirname(appTsxPath); const appFolderPath = path.dirname(appEntryPath);
writeFile(appFolderPath, 'App.tsx', finalCode); writeFile(appFolderPath, strategy.rootFileName, finalCode);
// Mark as injected and save immediately // Mark as injected and save immediately
saveAppInjected(cache, state.workspace); 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`); logger.printSuccessLog(`Successfully injected ${componentName} into App.tsx`);
} catch (error) { } catch (error) {
logger.printErrorLog(`Failed to inject root component: ${(error as Error).message}`); logger.printErrorLog(`Failed to inject root component: ${(error as Error).message}`);
......
...@@ -2,7 +2,8 @@ import fs from 'node:fs'; ...@@ -2,7 +2,8 @@ import fs from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import { logger } from '../../utils/logger'; import { logger } from '../../utils/logger';
import { GraphState } from '../../state'; 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. * 'initial' node: initialize the empty project scaffold.
...@@ -23,10 +24,11 @@ export const initialProject = async (state: GraphState) => { ...@@ -23,10 +24,11 @@ export const initialProject = async (state: GraphState) => {
} }
fs.mkdirSync(appPath, { recursive: true }); fs.mkdirSync(appPath, { recursive: true });
writeScaffold(appPath, appName); const profile = getProjectProfile();
writeScaffold(appPath, appName, profile);
// Validate that essential files/directories were created. // Validate that essential files/directories were created (framework-specific).
const essentialFiles = ['package.json', 'src', 'vite.config.ts', 'tsconfig.json', 'index.html', 'src/main.tsx', 'src/App.tsx']; const essentialFiles = getScaffoldEssentialFiles(profile);
for (const file of essentialFiles) { for (const file of essentialFiles) {
const fullPath = path.join(appPath, file); const fullPath = path.join(appPath, file);
if (!fs.existsSync(fullPath)) { if (!fs.existsSync(fullPath)) {
......
...@@ -10,6 +10,8 @@ export const GraphStateAnnotation = Annotation.Root({ ...@@ -10,6 +10,8 @@ export const GraphStateAnnotation = Annotation.Root({
figmaInfo: Annotation<GlobalFigmaInfo>(), figmaInfo: Annotation<GlobalFigmaInfo>(),
protocol: Annotation<Protocol | undefined>(), protocol: Annotation<Protocol | undefined>(),
config: Annotation<ValidationConfig>(), config: Annotation<ValidationConfig>(),
/** Whether the generated root should fill its host container (default true). */
fillContainer: Annotation<boolean>(),
}); });
export type GraphState = typeof GraphStateAnnotation.State; export type GraphState = typeof GraphStateAnnotation.State;
...@@ -84,7 +84,20 @@ export const fetchFigmaNode = async (fileId: string, nodeId: string, token: stri ...@@ -84,7 +84,20 @@ export const fetchFigmaNode = async (fileId: string, nodeId: string, token: stri
const resData = data.nodes?.[nodeId]; const resData = data.nodes?.[nodeId];
return resData?.document; return resData?.document;
} catch (error) { } 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; return undefined;
} }
}; };
......
import * as http from 'http'; import * as http from 'http';
import * as net from 'net'; 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 { buildDevServerUrl, DEFAULT_PORT } from '../../../nodes/validation/constants';
import { logger } from '../../../utils/logger'; import { logger } from '../../../utils/logger';
...@@ -16,13 +16,24 @@ export interface DevServerHandle { ...@@ -16,13 +16,24 @@ export interface DevServerHandle {
} }
function terminateChildProcess(child: ChildProcess): void { function terminateChildProcess(child: ChildProcess): void {
// Windows does not support POSIX signals like SIGTERM reliably. // Windows 上 dev server 以 `npm → vite` 的孙进程方式运行,child.kill() 只杀到
// Calling kill() without a signal uses the platform default behavior. // npm 外壳,杀不到 vite 本体,导致 dev server 泄漏、持续锁住项目目录(典型表现:
// 下一次生成在 initial 阶段写 package.json 时抛 EPERM)。因此统一用 taskkill /f /t
// 杀掉整个进程树(含孙进程)。POSIX 下按进程组 SIGKILL。
try { try {
if (process.platform === 'win32') { const pid = child.pid;
if (!pid) {
child.kill(); child.kill();
return;
}
if (process.platform === 'win32') {
execSync(`taskkill /pid ${pid} /f /t`, { stdio: 'ignore' });
} else { } else {
child.kill('SIGTERM'); try {
process.kill(-pid, 'SIGKILL');
} catch {
child.kill('SIGKILL');
}
} }
} catch { } catch {
// ignore // ignore
......
...@@ -62,6 +62,16 @@ export async function callModel(options: CallModelOptions): Promise<string> { ...@@ -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. // (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; 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 // Get and validate config separately
let config: ModelConfig; let config: ModelConfig;
try { try {
...@@ -92,7 +102,16 @@ export async function callModel(options: CallModelOptions): Promise<string> { ...@@ -92,7 +102,16 @@ export async function callModel(options: CallModelOptions): Promise<string> {
}, },
}), }),
...(!streaming && { streamUsage: true }), ...(!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); const agentModel = new ChatOpenAI(requestConfig);
......
...@@ -8,6 +8,35 @@ import { FileInfo } from '../types/file-types'; ...@@ -8,6 +8,35 @@ import { FileInfo } from '../types/file-types';
* @param filePath - The path to the file * @param filePath - The path to the file
* @param content - The content to write 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) => { export const writeFile = (folderPath: string, filePath: string, content: string) => {
if (!folderPath || !filePath || !content) { if (!folderPath || !filePath || !content) {
return; return;
...@@ -15,9 +44,20 @@ export const writeFile = (folderPath: string, filePath: string, content: string) ...@@ -15,9 +44,20 @@ export const writeFile = (folderPath: string, filePath: string, content: string)
if (!fs.existsSync(folderPath)) { if (!fs.existsSync(folderPath)) {
fs.mkdirSync(folderPath, { recursive: true }); 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 * 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!