serve.ts 20.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
import { createServer, IncomingMessage, ServerResponse } from 'node:http';
import { readFileSync, existsSync, readdirSync, statSync } from 'node:fs';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import { spawn, execSync, type ChildProcess } from 'node:child_process';
import net from 'node:net';
import os from 'node:os';

import { Command } from 'commander';
import { ValidationMode } from '../types/graph-types';
import { loadConfig, saveConfig, configExists } from '../utils/config';
import { subscribeLogs, logger, type LogEntry } from '../utils/logger';
import { parseFigmaUrl } from '../utils/url-parser';

/**
 * Service mode: a tiny zero-dependency web server that exposes the
 * design-to-code pipeline through a browser UI.
 *
 * - Serves the static UI from `web/index.html`.
 * - `GET/POST /api/config`  - read & write ~/.coderio/config.yaml.
 * - `POST /api/generate`    - start a (single, serial) generation job.
 * - `GET /api/stream`       - Server-Sent Events stream of logs + job status + preview state.
 * - `GET /api/job`          - current job snapshot.
 * - `GET|POST /api/preview` - start/inspect a persistent dev server for the generated app.
 * - `POST /api/preview/stop`- stop the preview dev server.
 */

interface JobStatus {
    id: string;
    status: 'idle' | 'running' | 'done' | 'error';
    figmaUrl: string;
    outputDir: string | null;
    appName: string;
    startedAt: string;
    finishedAt?: string;
    error?: string | null;
    resultDir?: string | null;
    reportPath?: string | null;
}

const DEFAULT_CONFIG = {
    model: { provider: 'openai', model: 'qwen3.8-max', baseUrl: 'https://llm-29tadkloiraxs298.cn-beijing.maas.aliyuncs.com/compatible-mode/v1', apiKey: '' },
    figma: { token: '' },
};

let currentJob: JobStatus | null = null;
const sseClients = new Set<ServerResponse>();

function broadcast(event: string, data: unknown): void {
    const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
    for (const res of sseClients) {
        try {
            res.write(payload);
        } catch {
            sseClients.delete(res);
        }
    }
}

function setJob(patch: Partial<JobStatus>): void {
    currentJob = currentJob ? { ...currentJob, ...patch } : (patch as JobStatus);
    broadcast('job', currentJob);
}

// ---------------------------------------------------------------------------
// Preview: a persistent dev server for the generated app so the user can
// actually open and inspect the result. This is distinct from the transient
// dev server the VALIDATION node spins up internally for screenshot/pixel
// comparison (which gets torn down after each iteration).
// ---------------------------------------------------------------------------
interface PreviewState {
    running: boolean;
    appPath: string | null;
    url: string | null; // Network URL (reachable from other devices)
    localUrl: string | null;
    port: number | null;
    pid: number | null;
    error: string | null;
}

let previewProc: ChildProcess | null = null;
let previewState: PreviewState = {
    running: false,
    appPath: null,
    url: null,
    localUrl: null,
    port: null,
    pid: null,
    error: null,
};

function findLatestAppPath(): string | null {    if (currentJob?.resultDir) {
        const p = path.join(currentJob.resultDir, 'my-app');
        if (existsSync(p)) return p;
    }
    const root = process.env.CODERIO_CLI_USER_CWD ?? process.cwd();
    const base = path.join(root, 'coderio');
    if (!existsSync(base)) return null;
    const candidates = readdirSync(base)
        .map((d) => path.join(base, d, 'my-app'))
        .filter((p) => existsSync(p));
    if (candidates.length === 0) return null;
    candidates.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs);
    return candidates[0] ?? null;
}

function getLanIp(): string {
    const nets = os.networkInterfaces();
    for (const name of Object.keys(nets)) {
        for (const ni of nets[name] ?? []) {
            if (ni.family === 'IPv4' && !ni.internal) return ni.address;
        }
    }
    return 'localhost';
}

function startPreview(explicitAppPath?: string): { ok: boolean; error?: string } {
    if (previewProc) return { ok: false, error: '预览服务已在运行,请先停止' };
    const appPath = explicitAppPath && existsSync(explicitAppPath) ? explicitAppPath : findLatestAppPath();
    if (!appPath) return { ok: false, error: '未找到生成的 my-app,请先完成一次生成' };

    previewState = { running: true, appPath, url: null, localUrl: null, port: null, pid: null, error: null };
    try {
        const shellCmd = 'npm run dev -- --host --port 5180';
        const child = spawn(shellCmd, {
            cwd: appPath,
            env: { ...process.env },
            windowsHide: true,
            detached: true,
            shell: true,
        });
        child.unref();
        previewProc = child;
        previewState.pid = child.pid ?? null;

        child.on('error', (e) => {
            previewState = { ...previewState, running: false, error: e.message };
            previewProc = null;
            broadcast('preview', previewState);
        });
        child.on('exit', (code) => {
            if (previewProc === child) {
                previewState = { ...previewState, running: false, error: code ? `预览进程退出 (code ${code})` : null };
                previewProc = null;
                broadcast('preview', previewState);
            }
        });

        // Reliable URL detection: probe the dev-server port(s) until reachable.
        // (stdout parsing is unreliable under detached+shell spawn on Windows.)
        const startPort = 5180;
        const endPort = 5195;
        const deadline = Date.now() + 90_000;
        const probe = setInterval(() => {
            if (previewState.url || !previewProc) {
                clearInterval(probe);
                return;
            }
            if (Date.now() > deadline) {
                clearInterval(probe);
                return;
            }
            for (let p = startPort; p <= endPort; p++) {
                const sock = net.createConnection({ port: p, host: '127.0.0.1' });
                let settled = false;
                sock.once('connect', () => {
                    settled = true;
                    sock.destroy();
                    clearInterval(probe);
                    const ip = getLanIp();
                    previewState.localUrl = `http://localhost:${p}/`;
                    previewState.url = `http://${ip}:${p}/`;
                    previewState.port = p;
                    broadcast('preview', previewState);
                });
                sock.once('error', () => {
                    if (!settled) sock.destroy();
                });
            }
        }, 1000);

        broadcast('preview', previewState);
        return { ok: true };
    } catch (e) {
        const message = e instanceof Error ? e.message : String(e);
        previewState = { running: false, appPath: null, url: null, localUrl: null, port: null, pid: null, error: message };
        previewProc = null;
        return { ok: false, error: message };
    }
}

function stopPreview(): void {
    if (previewProc?.pid) {
        try {
            if (os.platform() === 'win32') {
                execSync(`taskkill /pid ${previewProc.pid} /f /t`, { stdio: 'ignore' });
            } else {
                process.kill(-previewProc.pid, 'SIGKILL');
            }
        } catch {
            /* ignore */
        }
    }
    previewProc = null;
    previewState = { running: false, appPath: null, url: null, localUrl: null, port: null, pid: null, error: null };
    broadcast('preview', previewState);
}

function resolveWebIndex(): string {
    const here = path.dirname(fileURLToPath(import.meta.url));
    const candidates = [
        path.join(here, '../../web/index.html'), // published layout (dist/cli -> package/web)
        path.join(here, '../web/index.html'), // copied into dist/web
        path.join(here, '../../../web/index.html'), // dev layout (src/cli -> project/web)
    ];
    for (const c of candidates) {
        if (existsSync(c)) return c;
    }
    return candidates[0] ?? path.join(here, '../../web/index.html');
}

function readBody(req: IncomingMessage): Promise<string> {
    return new Promise((resolve, reject) => {
        let data = '';
        req.on('data', (chunk) => {
            data += chunk;
            if (data.length > 5 * 1024 * 1024) req.destroy(); // 5MB guard
        });
        req.on('end', () => resolve(data));
        req.on('error', reject);
    });
}

function sendJson(res: ServerResponse, code: number, obj: unknown): void {
    const body = JSON.stringify(obj);
    res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8' });
    res.end(body);
}

function mapMode(mode?: string): ValidationMode {
    if (mode === 'code') return ValidationMode.CodeOnly;
    if (mode === 'with-report') return ValidationMode.ReportOnly;
    return ValidationMode.Full;
}

function runGeneration(figmaUrl: string, mode: ValidationMode, outputDir?: string, appName?: string): void {
    // Run generation in a detached child process so a heavy/failing run
    // (Playwright, multi-agent INITIAL, OOM) cannot take down the serve UI.
    const root = outputDir || (process.env.CODERIO_CLI_USER_CWD ?? process.cwd());
    // Best-effort: derive the result dir from the URL. If the URL can't be
    // parsed here (e.g. missing node-id) we fall back and let the child report
    // the real directory via its own workspace resolution.
    let threadId = 'my-app';
    try {
        threadId = parseFigmaUrl(figmaUrl).projectName ?? 'my-app';
    } catch {
        /* leave default */
    }
    const resultDir = path.resolve(root, 'coderio', threadId);
    const scriptPath = fileURLToPath(new URL('./generate-child.ts', import.meta.url));
    // The child script is TypeScript; run it through the same tsx runtime that
    // serves this process so we don't depend on a separate build step. Resolve
    // tsx's cli.mjs at runtime (it lives under .pnpm in a pnpm layout).
    let tsxPath: string;
    try {
        const req = createRequire(import.meta.url);
        const loader = req.resolve('tsx');
        tsxPath = path.join(path.dirname(loader), 'cli.mjs');
    } catch {
        tsxPath = fileURLToPath(new URL('../../node_modules/tsx/dist/cli.mjs', import.meta.url));
    }
    const args = [
        scriptPath,
        '--figmaUrl', figmaUrl,
        '--mode', mode === ValidationMode.CodeOnly ? 'code' : mode === ValidationMode.ReportOnly ? 'with-report' : 'full',
    ];
    if (outputDir) args.push('--outputDir', outputDir);
    if (appName) args.push('--appName', appName);

    let child: ChildProcess;
    try {
        child = spawn(process.execPath, [tsxPath, ...args], {
            cwd: process.cwd(),
            env: { ...process.env },
            windowsHide: true,
            detached: true,
        });
    } catch (err) {
        const message = err instanceof Error ? err.message : String(err);
        setJob({ status: 'error', finishedAt: new Date().toISOString(), error: message });
        return;
    }

    const onData = (buf: Buffer) => {
        const text = buf.toString();
        // Detect sentinel lines, but still let normal logs pass through.
        if (text.includes('__D2C_DONE__')) {
            let reportPath: string | null = null;
            const validationReport = path.join(resultDir, 'process', 'validation', 'index.html');
            const summaryReport = path.join(resultDir, 'reports.html');
            if (existsSync(validationReport)) reportPath = validationReport;
            else if (existsSync(summaryReport)) reportPath = summaryReport;
            setJob({ status: 'done', finishedAt: new Date().toISOString(), resultDir, reportPath });
            return;
        }
        const errMatch = text.match(/__D2C_ERROR__[:\s]*(.*)/);
        if (errMatch) {
            const msg = errMatch[1] ?? '生成失败';
            setJob({ status: 'error', finishedAt: new Date().toISOString(), error: msg.trim() });
            return;
        }
        // Forward the child's stdout/stderr to our logger (which broadcasts via SSE).
        for (const line of text.split('\n')) {
            const t = line.trim();
            if (t) logger.printInfoLog(t);
        }
    };
    child.stdout?.on('data', onData);
    child.stderr?.on('data', onData);
    child.on('error', (e) => {
        setJob({ status: 'error', finishedAt: new Date().toISOString(), error: e.message });
    });
    child.on('exit', (code) => {
        // If we never received a sentinel, infer status from exit code.
        if (currentJob?.status === 'running') {
            if (code === 0) {
                setJob({ status: 'done', finishedAt: new Date().toISOString(), resultDir });
            } else {
                setJob({ status: 'error', finishedAt: new Date().toISOString(), error: `子进程退出码 ${code}` });
            }
        }
    });
}

export async function startServer(port: number): Promise<void> {
    const indexPath = resolveWebIndex();

    // Forward console logs to all connected SSE clients.
    subscribeLogs((entry: LogEntry) => broadcast('log', entry));

    const server = createServer(async (req, res) => {
        try {
            const url = new URL(req.url ?? '/', `http://localhost:${port}`);

            // ---- Static UI ----
            if (req.method === 'GET' && (url.pathname === '/' || url.pathname === '/index.html')) {
                if (existsSync(indexPath)) {
                    res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
                    res.end(readFileSync(indexPath));
                } else {
                    res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
                    res.end('UI not found. Run `pnpm build` to bundle web assets.');
                }
                return;
            }

            // ---- SSE stream ----
            if (req.method === 'GET' && url.pathname === '/api/stream') {
                res.writeHead(200, {
                    'Content-Type': 'text/event-stream; charset=utf-8',
                    'Cache-Control': 'no-cache',
                    Connection: 'keep-alive',
                });
                res.write('retry: 3000\n\n');
                sseClients.add(res);
                if (currentJob) broadcast('job', currentJob); // replay current snapshot
                res.write(`event: preview\ndata: ${JSON.stringify(previewState)}\n\n`); // replay preview snapshot
                const ping = setInterval(() => {
                    try {
                        res.write(': ping\n\n');
                    } catch {
                        /* ignore */
                    }
                }, 15000);
                req.on('close', () => {
                    clearInterval(ping);
                    sseClients.delete(res);
                });
                return;
            }

            // ---- GET /api/config ----
            if (req.method === 'GET' && url.pathname === '/api/config') {
                if (!configExists()) {
                    sendJson(res, 200, DEFAULT_CONFIG);
                    return;
                }
                try {
                    sendJson(res, 200, loadConfig());
                } catch (err) {
                    sendJson(res, 200, DEFAULT_CONFIG);
                }
                return;
            }

            // ---- POST /api/config ----
            if (req.method === 'POST' && url.pathname === '/api/config') {
                const raw = await readBody(req);
                let body: Record<string, unknown>;
                try {
                    body = JSON.parse(raw || '{}');
                } catch {
                    sendJson(res, 400, { ok: false, error: 'Invalid JSON body' });
                    return;
                }
                try {
                    saveConfig(body);
                    sendJson(res, 200, { ok: true });
                } catch (err) {
                    sendJson(res, 500, { ok: false, error: err instanceof Error ? err.message : String(err) });
                }
                return;
            }

            // ---- POST /api/generate ----
            if (req.method === 'POST' && url.pathname === '/api/generate') {
                if (currentJob && currentJob.status === 'running') {
                    sendJson(res, 409, { error: '已有任务在运行,请等待其完成后再试' });
                    return;
                }
                const raw = await readBody(req);
                let body: { figmaUrl?: string; mode?: string; outputDir?: string; appName?: string };
                try {
                    body = JSON.parse(raw || '{}');
                } catch {
                    sendJson(res, 400, { error: 'Invalid JSON body' });
                    return;
                }
                const figmaUrl = (body.figmaUrl || '').trim();
                if (!figmaUrl) {
                    sendJson(res, 400, { error: 'figmaUrl 为必填项' });
                    return;
                }
                // Validate the URL format up front so we don't spawn a doomed run.
                try {
                    parseFigmaUrl(figmaUrl);
                } catch {
                    sendJson(res, 400, { error: 'Invalid Figma URL(需包含 design/file 链接与 ?node-id=)' });
                    return;
                }

                const jobId = `job-${Date.now()}`;
                const mode = mapMode(body.mode);
                currentJob = {
                    id: jobId,
                    status: 'running',
                    figmaUrl,
                    outputDir: body.outputDir || null,
                    appName: body.appName || 'my-app',
                    startedAt: new Date().toISOString(),
                    error: null,
                    resultDir: null,
                    reportPath: null,
                };
                broadcast('job', currentJob);

                runGeneration(figmaUrl, mode, body.outputDir, body.appName);
                sendJson(res, 200, { jobId });
                return;
            }

            // ---- GET /api/job ----
            if (req.method === 'GET' && url.pathname === '/api/job') {
                sendJson(res, 200, currentJob || { status: 'idle' });
                return;
            }

            // ---- GET /api/preview ----
            if (req.method === 'GET' && url.pathname === '/api/preview') {
                sendJson(res, 200, previewState);
                return;
            }

            // ---- POST /api/preview (start a persistent dev server) ----
            if (req.method === 'POST' && url.pathname === '/api/preview') {
                const raw = await readBody(req);
                let body: { appPath?: string } = {};
                try {
                    body = JSON.parse(raw || '{}');
                } catch {
                    /* ignore malformed body */
                }
                const r = startPreview(body.appPath);
                sendJson(res, r.ok ? 200 : 409, { ok: r.ok, error: r.error });
                return;
            }

            // ---- POST /api/preview/stop ----
            if (req.method === 'POST' && url.pathname === '/api/preview/stop') {
                stopPreview();
                sendJson(res, 200, { ok: true });
                return;
            }

            res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
            res.end('Not Found');
        } catch (err) {
            sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) });
        }
    });

    server.listen(port, () => {
        const banner = [
            '',
            '  🎨 CodeRio 服务模式已启动',
            `     本地访问: http://localhost:${port}`,
            '     按 Ctrl+C 停止',
            '',
        ].join('\n');
        // eslint-disable-next-line no-console
        console.log(banner);
    });
}

export const registerServeCommand = (program: Command) => {
    program
        .command('serve')
        .alias('s')
        .description('Start the CodeRio web service (UI mode)')
        .option('-p, --port <number>', 'Port to listen on', '4173')
        .action(async (opts: { port?: string }) => {
            const port = Number(opts.port) || 4173;
            await startServer(port);
        });
};