preview.ts
7.84 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
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;
}
}