runner.ts
6.5 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
import { spawn, type ChildProcess } from 'node:child_process';
import { createRequire } from 'node:module';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { existsSync } from 'node:fs';
import { logger, parseFigmaUrl } from 'coderio';
import type { Job } from './types';
import type { ServerModelConfig } from './config';
import type { ProjectProfile } from 'coderio';
import type { RunResult } from './queue';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
/**
* Track every live child process by job id so a run can be aborted on demand.
* Children are spawned `detached`, so killing the direct child is enough to
* stop the generation (tsx runs in the same process; Playwright spawns are
* grandchildren and may linger, which is acceptable for an abort).
*/
const activeChildren = new Map<string, ChildProcess>();
const cancelledIds = new Set<string>();
/**
* Request cancellation of a running job. Kills the child process (and, on
* POSIX, its whole process group). Returns false if there is no live child
* for that job (it may be queued, already finished, or unknown).
*/
export function cancelRun(id: string): boolean {
const child = activeChildren.get(id);
if (!child) return false;
cancelledIds.add(id);
try {
if (child.pid != null) {
try {
process.kill(-child.pid, 'SIGTERM'); // POSIX: whole group
} catch {
/* negative pid unsupported (Windows) — fall through */
}
}
child.kill('SIGTERM');
} catch {
/* ignore */
}
return true;
}
/**
* Resolve the tsx CLI entry so we can run the TypeScript child script with the
* same runtime that serves this process (no separate build step needed).
*/
function resolveTsx(): string {
try {
const req = createRequire(import.meta.url);
const loader = req.resolve('tsx');
return path.join(path.dirname(loader), 'cli.mjs');
} catch {
return fileURLToPath(new URL('../../node_modules/tsx/dist/cli.mjs', import.meta.url));
}
}
/**
* Run one generation job in a detached child process so a heavy/failing run
* (Playwright, multi-agent work, OOM) can never take down the server. The
* child calls `design2code` with the server-injected `modelConfig`, so
* credentials never live in the frontend and never hit a global config file
* unless the server chooses to. Logs are streamed back and re-emitted through
* the coderio logger (which the server forwards to SSE clients).
*/
export async function runJob(
job: Job,
model: ServerModelConfig,
outputDir: string,
onPid: (pid: number) => void,
projectProfile: ProjectProfile | null = null,
): Promise<RunResult> {
const childScript = fileURLToPath(new URL('./generate-child.ts', import.meta.url));
const tsx = resolveTsx();
const modeArg = job.mode === 'code' ? 'code' : job.mode === 'with-report' ? 'with-report' : 'full';
// Compute the eventual result dir (<outputDir>/coderio/<figmaName>).
let threadId = job.appName || 'my-app';
try {
threadId = parseFigmaUrl(job.figmaUrl).projectName ?? job.appName;
} catch {
/* leave default */
}
const resultDir = path.resolve(outputDir, 'coderio', threadId);
const runtimeConfig = JSON.stringify({
model: {
provider: model.provider,
model: model.model,
baseUrl: model.baseUrl,
apiKey: model.apiKey,
},
figma: { token: model.figmaToken },
// Target-project profile (画像): when present the engine constrains
// generation to the project's components / tokens / conventions.
projectProfile: projectProfile ?? null,
// Where the generated code should land (standalone / new-page /
// modify-slot). Recorded for the engine; slot rewriting is a later phase.
target: job.target ?? null,
// Whether the generated root should fill its host container (default true).
fillContainer: job.fillContainer ?? true,
});
const args = [
tsx,
childScript,
'--figmaUrl',
job.figmaUrl,
'--mode',
modeArg,
'--outputDir',
outputDir,
'--appName',
job.appName,
];
const child: ChildProcess = spawn(process.execPath, args, {
cwd: process.cwd(),
env: { ...process.env, COD_RUNTIME_CONFIG: runtimeConfig },
windowsHide: true,
detached: true,
});
if (child.pid) onPid(child.pid);
activeChildren.set(job.id, child);
return new Promise<RunResult>((resolve, reject) => {
let settled = false;
let reportPath: string | null = null;
const inferReport = (): string | null => {
const validationReport = path.join(resultDir, 'process', 'validation', 'index.html');
const summaryReport = path.join(resultDir, 'reports.html');
if (existsSync(validationReport)) return validationReport;
if (existsSync(summaryReport)) return summaryReport;
return null;
};
const finish = () => {
settled = true;
activeChildren.delete(job.id);
};
const onData = (buf: Buffer): void => {
const text = buf.toString();
if (text.includes('__D2C_DONE__') && !settled) {
finish();
resolve({ resultDir, reportPath: inferReport() });
return;
}
const errMatch = text.match(/__D2C_ERROR__[:\s]*(.*)/);
if (errMatch && !settled) {
finish();
reject(new Error((errMatch[1] ?? '生成失败').trim()));
return;
}
for (const line of text.split('\n')) {
const t = line.trim();
if (t) logger.printInfoLog(t);
}
};
child.stdout?.on('data', onData);
child.stderr?.on('data', onData);
child.on('error', (e) => {
if (!settled) {
finish();
reject(e);
}
});
child.on('exit', (code) => {
if (settled) return;
finish();
if (cancelledIds.has(job.id)) {
resolve({ resultDir: null, reportPath: null, cancelled: true });
return;
}
if (code === 0) {
resolve({ resultDir, reportPath: inferReport() });
} else {
reject(new Error(`子进程退出码 ${code}`));
}
});
});
}