preview.ts 7.84 KB
import { spawn, type ChildProcess } from 'node:child_process';
import net from 'node:net';
import os from 'node:os';
import path from 'node:path';
import { existsSync, appendFileSync, mkdirSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import type { PreviewState } from './types';
import {
    getLanIp,
    killProcess,
    killProcessOnPort,
    killStalePreviewPorts as killStalePreviewPortsImpl,
} from './net';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
/** Captures the spawned npm/vite stdout+stderr so a silent failure is diagnosable. */
const PREVIEW_LOG = path.resolve(__dirname, '..', '..', '..', '.workbuddy', 'preview-runtime.log');

/**
 * Manages a persistent dev server for a generated `my-app` so the user can open
 * and inspect the result in the browser. Distinct from the transient dev server
 * the VALIDATION node spins up internally for screenshots (torn down after each
 * iteration). This is a placeholder for the Phase 3 static-build hosting: for
 * now we `npm run dev` the generated app and probe the port.
 */
export class PreviewManager {
    private proc: ChildProcess | null = null;
    state: PreviewState = {
        running: false,
        appPath: null,
        url: null,
        localUrl: null,
        port: null,
        pid: null,
        error: null,
    };

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

    /**
     * Kill any lingering dev servers on the Coderio-managed ranges
     * (5180–5195 preview, 5200–6199 validation). 5173 (front-end) excluded.
     * Delegates to the shared implementation in ./net (which also fixes the
     * original off-by-one capture-group bug).
     */
    killStalePreviewPorts(): void {
        killStalePreviewPortsImpl();
    }

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

        this.state = {
            running: true,
            appPath,
            url: null,
            localUrl: null,
            port: null,
            pid: null,
            error: null,
        };
        try {
            // Clear any leaked dev server from a previous (improperly stopped)
            // preview run so we always bind a clean port.
            this.killStalePreviewPorts();

            // A freshly scaffolded app ships no node_modules, so we must install
            // once. But when deps are already present (the common case) we skip
            // `npm install` entirely to avoid any registry/network flakiness that
            // could hang the spawn before vite ever starts. `npm` is used (not
            // `pnpm`) because pnpm is unavailable in some environments, and the
            // generated `dev` script is plain `vite`.
            const viteBin = path.join(appPath, 'node_modules', '.bin', 'vite');
            const needsInstall = !existsSync(viteBin);
            // Shell-level redirect (more reliable than piping a detached child's
            // stdout on Windows) so npm/vite output lands in the log file.
            const cmd =
                (needsInstall ? 'npm install && ' : '') +
                `npm run dev -- --host --port 5180 >> "${PREVIEW_LOG}" 2>&1`;

            mkdirSync(path.dirname(PREVIEW_LOG), { recursive: true });
            appendFileSync(
                PREVIEW_LOG,
                `\n===== preview start ${new Date().toISOString()} | appPath=${appPath} | needsInstall=${needsInstall} =====\n`,
            );

            const child = spawn(cmd, {
                cwd: appPath,
                env: { ...process.env },
                windowsHide: true,
                detached: true,
                shell: true,
            });
            child.unref();
            this.proc = child;
            this.state.pid = child.pid ?? null;

            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);
                }
            });

            // Reliable URL detection: probe the dev-server port(s) until reachable.
            const startPort = 5180;
            const endPort = 5195;
            const deadline = Date.now() + 90_000;
            const probe = setInterval(() => {
                if (this.state.url || !this.proc) {
                    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 connected = false;
                    sock.once('connect', () => {
                        connected = true;
                        sock.destroy();
                        clearInterval(probe);
                        const ip = getLanIp();
                        this.state.localUrl = `http://localhost:${p}/`;
                        this.state.url = `http://${ip}:${p}/`;
                        this.state.port = p;
                        this.onChange(this.state);
                    });
                    sock.once('error', () => {
                        if (!connected) sock.destroy();
                    });
                }
            }, 1000);

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

    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 vite by port (the npm-shell kill above may not
        // reach it), so the port is reliably freed.
        killProcessOnPort(this.state.port ?? 0);
        this.proc = null;
        this.state = {
            running: false,
            appPath: null,
            url: null,
            localUrl: null,
            port: null,
            pid: null,
            error: null,
        };
        this.onChange(this.state);
    }

    /** Stop then start again on the same app path (no-op if nothing was running). */
    restart(): { ok: boolean; error?: string } {
        const appPath = this.state.appPath;
        this.stop();
        if (!appPath) return { ok: false, error: '当前没有运行中的预览,无法重启' };
        return this.start(appPath);
    }

    /** Default app path = latest done job's resultDir/my-app. */
    static defaultAppPath(resultDir: string | null): string | null {
        if (!resultDir) return null;
        const p = path.join(resultDir, 'my-app');
        return existsSync(p) ? p : null;
    }
}