project-runner.ts
11.7 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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
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;
}
}