runner.ts 6.5 KB
import { spawn, type ChildProcess } from 'node:child_process';
import { createRequire } from 'node:module';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { existsSync } from 'node:fs';
import { logger, parseFigmaUrl } from 'coderio';
import type { Job } from './types';
import type { ServerModelConfig } from './config';
import type { ProjectProfile } from 'coderio';
import type { RunResult } from './queue';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

/**
 * Track every live child process by job id so a run can be aborted on demand.
 * Children are spawned `detached`, so killing the direct child is enough to
 * stop the generation (tsx runs in the same process; Playwright spawns are
 * grandchildren and may linger, which is acceptable for an abort).
 */
const activeChildren = new Map<string, ChildProcess>();
const cancelledIds = new Set<string>();

/**
 * Request cancellation of a running job. Kills the child process (and, on
 * POSIX, its whole process group). Returns false if there is no live child
 * for that job (it may be queued, already finished, or unknown).
 */
export function cancelRun(id: string): boolean {
    const child = activeChildren.get(id);
    if (!child) return false;
    cancelledIds.add(id);
    try {
        if (child.pid != null) {
            try {
                process.kill(-child.pid, 'SIGTERM'); // POSIX: whole group
            } catch {
                /* negative pid unsupported (Windows) — fall through */
            }
        }
        child.kill('SIGTERM');
    } catch {
        /* ignore */
    }
    return true;
}

/**
 * Resolve the tsx CLI entry so we can run the TypeScript child script with the
 * same runtime that serves this process (no separate build step needed).
 */
function resolveTsx(): string {
    try {
        const req = createRequire(import.meta.url);
        const loader = req.resolve('tsx');
        return path.join(path.dirname(loader), 'cli.mjs');
    } catch {
        return fileURLToPath(new URL('../../node_modules/tsx/dist/cli.mjs', import.meta.url));
    }
}

/**
 * Run one generation job in a detached child process so a heavy/failing run
 * (Playwright, multi-agent work, OOM) can never take down the server. The
 * child calls `design2code` with the server-injected `modelConfig`, so
 * credentials never live in the frontend and never hit a global config file
 * unless the server chooses to. Logs are streamed back and re-emitted through
 * the coderio logger (which the server forwards to SSE clients).
 */
export async function runJob(
    job: Job,
    model: ServerModelConfig,
    outputDir: string,
    onPid: (pid: number) => void,
    projectProfile: ProjectProfile | null = null,
): Promise<RunResult> {
    const childScript = fileURLToPath(new URL('./generate-child.ts', import.meta.url));
    const tsx = resolveTsx();
    const modeArg = job.mode === 'code' ? 'code' : job.mode === 'with-report' ? 'with-report' : 'full';

    // Compute the eventual result dir (<outputDir>/coderio/<figmaName>).
    let threadId = job.appName || 'my-app';
    try {
        threadId = parseFigmaUrl(job.figmaUrl).projectName ?? job.appName;
    } catch {
        /* leave default */
    }
    const resultDir = path.resolve(outputDir, 'coderio', threadId);

    const runtimeConfig = JSON.stringify({
        model: {
            provider: model.provider,
            model: model.model,
            baseUrl: model.baseUrl,
            apiKey: model.apiKey,
        },
        figma: { token: model.figmaToken },
        // Target-project profile (画像): when present the engine constrains
        // generation to the project's components / tokens / conventions.
        projectProfile: projectProfile ?? null,
        // Where the generated code should land (standalone / new-page /
        // modify-slot). Recorded for the engine; slot rewriting is a later phase.
        target: job.target ?? null,
        // Whether the generated root should fill its host container (default true).
        fillContainer: job.fillContainer ?? true,
    });

    const args = [
        tsx,
        childScript,
        '--figmaUrl',
        job.figmaUrl,
        '--mode',
        modeArg,
        '--outputDir',
        outputDir,
        '--appName',
        job.appName,
    ];

    const child: ChildProcess = spawn(process.execPath, args, {
        cwd: process.cwd(),
        env: { ...process.env, COD_RUNTIME_CONFIG: runtimeConfig },
        windowsHide: true,
        detached: true,
    });
    if (child.pid) onPid(child.pid);
    activeChildren.set(job.id, child);

    return new Promise<RunResult>((resolve, reject) => {
        let settled = false;
        let reportPath: string | null = null;

        const inferReport = (): string | null => {
            const validationReport = path.join(resultDir, 'process', 'validation', 'index.html');
            const summaryReport = path.join(resultDir, 'reports.html');
            if (existsSync(validationReport)) return validationReport;
            if (existsSync(summaryReport)) return summaryReport;
            return null;
        };

        const finish = () => {
            settled = true;
            activeChildren.delete(job.id);
        };

        const onData = (buf: Buffer): void => {
            const text = buf.toString();
            if (text.includes('__D2C_DONE__') && !settled) {
                finish();
                resolve({ resultDir, reportPath: inferReport() });
                return;
            }
            const errMatch = text.match(/__D2C_ERROR__[:\s]*(.*)/);
            if (errMatch && !settled) {
                finish();
                reject(new Error((errMatch[1] ?? '生成失败').trim()));
                return;
            }
            for (const line of text.split('\n')) {
                const t = line.trim();
                if (t) logger.printInfoLog(t);
            }
        };

        child.stdout?.on('data', onData);
        child.stderr?.on('data', onData);
        child.on('error', (e) => {
            if (!settled) {
                finish();
                reject(e);
            }
        });
        child.on('exit', (code) => {
            if (settled) return;
            finish();
            if (cancelledIds.has(job.id)) {
                resolve({ resultDir: null, reportPath: null, cancelled: true });
                return;
            }
            if (code === 0) {
                resolve({ resultDir, reportPath: inferReport() });
            } else {
                reject(new Error(`子进程退出码 ${code}`));
            }
        });
    });
}