preview.ts
9.58 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
import { spawn, execSync, 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';
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) {}
private 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';
}
/**
* Kill whatever process is listening on a given TCP port. Needed because the
* dev server is launched via `npm install && npm run dev` inside a shell, so
* `this.proc` is the npm shell — killing it does NOT reliably terminate the
* grandchild `vite` process, which would otherwise leak and occupy the port.
*/
private killPort(port: number): void {
if (!port) return;
try {
const out = execSync('netstat -ano', { stdio: ['ignore', 'pipe', 'ignore'] }).toString();
const m = out.match(new RegExp(`:${port}\\s+\\S+\\s+LISTENING\\s+(\\d+)`));
if (m?.[1]) execSync(`taskkill /pid ${m[1]} /f /t`, { stdio: 'ignore' });
} catch {
/* ignore */
}
}
/**
* Kill any lingering dev servers on the Coderio-managed ranges:
* - 5180–5195 : preview service (`npm run dev -- --port 5180`)
* - 5200–6199 : validation internal dev server (`calculateHashPort`, base 5200)
* The front-end's 5173 is deliberately NOT covered (would kill the UI).
* Public so the server can call it at boot and before each generation to
* reclaim dev servers detached from a previous backend/generation process.
*/
killStalePreviewPorts(): void {
try {
const out = execSync('netstat -ano', { stdio: ['ignore', 'pipe', 'ignore'] }).toString();
const re = /:5(?:18[0-9]|19[0-5]|[2-9]\d\d|6[01]\d\d)\s+\S+\s+LISTENING\s+(\d+)/g;
const pids = new Set<string>();
let m: RegExpExecArray | null;
while ((m = re.exec(out))) pids.add(m[2]);
for (const pid of pids) {
try {
execSync(`taskkill /pid ${pid} /f /t`, { stdio: 'ignore' });
} catch {
/* ignore */
}
}
} catch {
/* ignore */
}
}
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 = this.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') {
execSync(`taskkill /pid ${this.proc.pid} /f /t`, { stdio: 'ignore' });
} 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.
this.killPort(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;
}
}