runner.ts
4.51 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
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 { RunResult } from './queue';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
/**
* 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,
): 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 },
});
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);
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 onData = (buf: Buffer): void => {
const text = buf.toString();
if (text.includes('__D2C_DONE__') && !settled) {
settled = true;
resolve({ resultDir, reportPath: inferReport() });
return;
}
const errMatch = text.match(/__D2C_ERROR__[:\s]*(.*)/);
if (errMatch && !settled) {
settled = true;
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) {
settled = true;
reject(e);
}
});
child.on('exit', (code) => {
if (settled) return;
settled = true;
if (code === 0) {
resolve({ resultDir, reportPath: inferReport() });
} else {
reject(new Error(`子进程退出码 ${code}`));
}
});
});
}