project-runner.ts 11.7 KB
import { spawn, execSync, type ChildProcess } from 'node:child_process';
import net from 'node:net';
import os from 'node:os';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import type { ProjectManager, ProjectRunState } from './types';
import { getLanIp, killProcess, killProcessOnPort, listListeningPorts as listListeningPortsImpl } from './net';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
/**
 * Captures the spawned dev-server stdout+stderr so a silent failure (e.g. a
 * missing dependency or a port clash) is diagnosable from the panel.
 */
const RUN_LOG = path.resolve(__dirname, '..', '..', '..', '.workbuddy', 'project-run.log');

type Scripts = Record<string, string>;

/**
 * Launches the user's *own* target project as a dev server (npm/pnpm/yarn run
 * dev) so generated code that lands inside it can be previewed live — in
 * contrast to {@link PreviewManager}, which serves the isolated app coderio
 * scaffolds. Only one target project runs at a time.
 */
export class ProjectRunner {
    private proc: ChildProcess | null = null;
    private logStream: fs.WriteStream | null = null;
    /** Listening TCP ports that existed *before* this run started — used to
     *  ignore the orchestration server's own port (and any other pre-existing
     *  service) when detecting the dev server port. */
    private baselinePorts: Set<number> = new Set();
    state: ProjectRunState = {
        running: false,
        dir: null,
        script: null,
        manager: null,
        url: null,
        localUrl: null,
        port: null,
        pid: null,
        error: null,
    };

    constructor(private readonly onChange: (s: ProjectRunState) => void) {}

    static pickScript(scripts: Scripts | undefined): string | null {
        if (!scripts) return null;
        // Return the *script name* (e.g. "dev"), not its command value — the
        // launched command is `<manager> run <name>`, so passing the value
        // (e.g. "vite" / "node server.js") would make npm look for a script
        // literally named that and exit 1.
        for (const key of ['dev', 'start', 'serve', 'dev:server']) {
            if (scripts[key]) return key;
        }
        return null;
    }

    static pickManager(dir: string): ProjectManager {
        if (fs.existsSync(path.join(dir, 'pnpm-lock.yaml'))) return 'pnpm';
        if (fs.existsSync(path.join(dir, 'yarn.lock'))) return 'yarn';
        return 'npm';
    }

    start(dir: string): { ok: boolean; error?: string } {
        if (this.proc) return { ok: false, error: '已有目标项目在运行,请先停止' };
        if (!fs.existsSync(dir)) return { ok: false, error: `目录不存在:${dir}` };
        const pkgPath = path.join(dir, 'package.json');
        if (!fs.existsSync(pkgPath)) {
            return { ok: false, error: `该目录不是 npm 项目(缺少 package.json):${dir}` };
        }
        let pkg: { scripts?: Scripts };
        try {
            pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
        } catch (e) {
            return { ok: false, error: `package.json 解析失败:${e instanceof Error ? e.message : String(e)}` };
        }
        const script = ProjectRunner.pickScript(pkg.scripts);
        if (!script) {
            return { ok: false, error: '未找到 dev/start/serve 脚本,无法启动(可在 package.json scripts 中补充)' };
        }
        const manager = ProjectRunner.pickManager(dir);

        this.state = {
            running: true,
            dir,
            script,
            manager,
            url: null,
            localUrl: null,
            port: null,
            pid: null,
            error: null,
        };
        try {
            fs.mkdirSync(path.dirname(RUN_LOG), { recursive: true });
            fs.appendFileSync(
                RUN_LOG,
                `\n===== project run start ${new Date().toISOString()} | dir=${dir} | manager=${manager} | script=${script} =====\n`,
            );
            // Capture the dev-server's stdout/stderr directly via pipes. A shell
            // redirect (`>> log 2>&1`) proved unreliable on Windows — npm buffers
            // its output until the process exits, so a live server's "Local:"
            // line never reaches the redirected file. We still sink the pipe to
            // RUN_LOG for post-mortem diagnostics, but port detection below does
            // NOT depend on it (it uses netstat + the process tree instead).
            // Snapshot pre-existing listening ports so the orchestration
            // server's own port is never mistaken for the dev server.
            this.baselinePorts = new Set(listListeningPortsImpl().keys());
            const logStream = fs.createWriteStream(RUN_LOG, { flags: 'a' });
            this.logStream = logStream;
            const child = spawn(`${manager} run ${script}`, {
                cwd: dir,
                env: { ...process.env },
                windowsHide: true,
                detached: true,
                shell: true,
                stdio: ['ignore', 'pipe', 'pipe'],
            });
            child.unref();
            this.proc = child;
            this.state.pid = child.pid ?? null;
            child.stdout?.on('data', (d) => logStream.write(d));
            child.stderr?.on('data', (d) => logStream.write(d));

            child.on('error', (e) => {
                this.state = { ...this.state, running: false, error: e.message };
                this.proc = null;
                this.onChange(this.state);
            });
            child.on('exit', (code) => {
                if (this.proc === child) {
                    this.state = {
                        ...this.state,
                        running: false,
                        error: code ? `目标项目进程退出 (code ${code})` : null,
                    };
                    this.proc = null;
                    this.onChange(this.state);
                }
            });

            // Detect the dev-server port: tail the log file for a
            // "Local: http://localhost:<port>" line, then TCP-probe to confirm
            // the server is actually listening before reporting the URL.
            const deadline = Date.now() + 90_000;
            const timer = setInterval(() => {
                if (!this.proc || this.state.url) {
                    clearInterval(timer);
                    return;
                }
                if (Date.now() > deadline) {
                    clearInterval(timer);
                    if (!this.state.url) {
                        this.state = {
                            ...this.state,
                            error: '启动超时:未能自动识别 dev server 端口(netstat 未找到监听端口)',
                        };
                        this.onChange(this.state);
                    }
                    return;
                }
                // Walk the spawned process tree and ask netstat which LISTENING
                // port a descendant owns. This avoids parsing npm's (buffered)
                // stdout. A TCP probe then confirms the server actually answers.
                const port = this.proc.pid ? this.findDevServerPort(this.proc.pid) : null;
                if (port) {
                    const sock = net.createConnection({ port, host: '127.0.0.1' });
                    let settled = false;
                    sock.once('connect', () => {
                        settled = true;
                        sock.destroy();
                        clearInterval(timer);
                        const ip = getLanIp();
                        this.state = {
                            ...this.state,
                            port,
                            localUrl: `http://localhost:${port}/`,
                            url: `http://${ip}:${port}/`,
                        };
                        this.onChange(this.state);
                    });
                    sock.once('error', () => {
                        if (!settled) sock.destroy();
                    });
                }
            }, 800);

            this.onChange(this.state);
            return { ok: true };
        } catch (e) {
            const message = e instanceof Error ? e.message : String(e);
            this.state = {
                running: false,
                dir: null,
                script: null,
                manager: null,
                url: null,
                localUrl: null,
                port: null,
                pid: null,
                error: message,
            };
            this.proc = null;
            return { ok: false, error: message };
        }
    }

    /**
     * Returns every PID in the process tree rooted at `rootPid` (inclusive),
     * using `wmic` to map parent→child relationships.
     */
    private getDescendantPids(rootPid: number): number[] {
        let out = '';
        try {
            out = execSync('wmic process get processid,parentprocessid', {
                stdio: ['ignore', 'pipe', 'ignore'],
            }).toString();
        } catch {
            return [rootPid];
        }
        const childToParent = new Map<number, number>();
        for (const line of out.split('\n')) {
            const nums = line
                .trim()
                .split(/\s+/)
                .map(Number)
                .filter((n) => !Number.isNaN(n));
            if (nums.length >= 2) childToParent.set(nums[1], nums[0]);
        }
        const result = new Set<number>([rootPid]);
        const stack = [rootPid];
        while (stack.length) {
            const p = stack.pop() as number;
            for (const [pid, parent] of childToParent) {
                if (parent === p && !result.has(pid)) {
                    result.add(pid);
                    stack.push(pid);
                }
            }
        }
        return [...result];
    }

    /**
     * Finds the dev server's listening port by scanning the OS socket table for
     * a LISTENING socket owned by any process in the spawned tree. npm buffers
     * its stdout (so the "Local:" line is unavailable while the server runs),
     * hence we look at `netstat` instead. Ports that were already listening
     * before this run started (`baselinePorts`) are ignored, so the
     * orchestration server's own port (and any other pre-existing service) can
     * never be mistaken for the dev server.
     */
    private findDevServerPort(rootPid: number): number | null {
        const pids = new Set(this.getDescendantPids(rootPid));
        for (const [port, owners] of listListeningPortsImpl()) {
            if (this.baselinePorts.has(port)) continue;
            if (owners.some((pid) => pids.has(pid))) return port;
        }
        return null;
    }

    stop(): void {
        if (this.proc?.pid) {
            try {
                if (os.platform() === 'win32') {
                    killProcess(this.proc.pid);
                } else {
                    process.kill(-this.proc.pid, 'SIGKILL');
                }
            } catch {
                /* ignore */
            }
        }
        // Also kill the grandchild dev server by port (the shell kill above may
        // not reach it), reliably freeing the port.
        killProcessOnPort(this.state.port ?? 0);
        this.proc = null;
        try {
            this.logStream?.end();
        } catch {
            /* ignore */
        }
        this.logStream = null;
        this.state = {
            running: false,
            dir: null,
            script: null,
            manager: null,
            url: null,
            localUrl: null,
            port: null,
            pid: null,
            error: null,
        };
        this.onChange(this.state);
    }

    getStatus(): ProjectRunState {
        return this.state;
    }
}