lantern-harness 0.1.8 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +2 -2
  3. package/cli/server.mjs +2 -0
  4. package/config/app.defaults.json +1 -0
  5. package/dist/500.html +3 -3
  6. package/dist/_astro/Base.4X_wsSoR.css +1 -0
  7. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.Dy7fJoxu.js +1 -0
  8. package/dist/_astro/{CaseExecBoard.BAV4EE3o.js → CaseExecBoard.DKdfW5fM.js} +1 -1
  9. package/dist/_astro/{CaseGenerateApp.Bz4ryNJG.js → CaseGenerateApp.Bm8AyH9s.js} +1 -1
  10. package/dist/_astro/{CasesLibrary.BPifyHUA.js → CasesLibrary.CvVJZ74h.js} +1 -1
  11. package/dist/_astro/{ChatApp.DLo31SYZ.js → ChatApp.BS-wLBRa.js} +3 -3
  12. package/dist/_astro/{DashboardBoard.Bd3eUPwZ.js → DashboardBoard.DCtfrrJz.js} +1 -1
  13. package/dist/_astro/{DocsFileBrowser.D3cKurQE.js → DocsFileBrowser.BtRoZ787.js} +1 -1
  14. package/dist/_astro/{DocsPager.rzu4mnzw.js → DocsPager.C20ue_JZ.js} +1 -1
  15. package/dist/_astro/{KnowledgeLibrary.B0sO4QR1.js → KnowledgeLibrary.CV4DyStj.js} +1 -1
  16. package/dist/_astro/{NavLibraries.Cvg3wery.js → NavLibraries.DmD2lZBZ.js} +1 -1
  17. package/dist/_astro/PluginsPage.B59AMDrB.js +1 -0
  18. package/dist/_astro/{PluginsPage.DIltPILi.js → PluginsPage.BEAPymNL.js} +1 -1
  19. package/dist/_astro/PmBugsBoard.CPEyBp0l.js +1 -0
  20. package/dist/_astro/PmIterationsBoard.zCeLpcBo.js +1 -0
  21. package/dist/_astro/{PmProjectDetail.DqDoIg8a.js → PmProjectDetail.ejIam5sD.js} +1 -1
  22. package/dist/_astro/{PmProjectsBoard.nOC1Hugt.js → PmProjectsBoard.DbXzir8o.js} +1 -1
  23. package/dist/_astro/PmRequirementsBoard.CynewRfv.js +1 -0
  24. package/dist/_astro/PmRequirementsBoard.D9eUMJWI.js +1 -0
  25. package/dist/_astro/{PmShared.CZnXaUq-.js → PmShared.BxTHKdjY.js} +1 -1
  26. package/dist/_astro/{PromptsLibrary.DU9EuSim.js → PromptsLibrary.Bkruu80b.js} +1 -1
  27. package/dist/_astro/{ReportsPage.Cr88iz8c.js → ReportsPage.BoBQshMQ.js} +1 -1
  28. package/dist/_astro/{RequirementsLibrary.BwriF8F0.js → RequirementsLibrary.BC0A8qdk.js} +1 -1
  29. package/dist/_astro/{SearchableSelect.Ctg8V1Z1.js → SearchableSelect.CXa1hiDd.js} +1 -1
  30. package/dist/_astro/SettingsDialog.Dc-9QNJI.js +1 -0
  31. package/dist/_astro/{SpaceSwitcher.BEJo5KFi.js → SpaceSwitcher.CI3KDBOA.js} +1 -1
  32. package/dist/_astro/{TasksBoard.BZi_GBPG.js → TasksBoard.Bb--oVV8.js} +1 -1
  33. package/dist/_astro/{TemplatesLibrary.T4K9jUex.js → TemplatesLibrary.D1wZq94E.js} +1 -1
  34. package/dist/_astro/{TestStatsBoard.Dd1Kcmx6.js → TestStatsBoard.DlVezlXl.js} +1 -1
  35. package/dist/_astro/{TodosBoard.C4yd_JFb.js → TodosBoard.S84wqcWY.js} +1 -1
  36. package/dist/_astro/UiAutoBoard.BKp9ifxg.js +1 -0
  37. package/dist/_astro/app-config.DUyozIL9.js +1 -0
  38. package/dist/_astro/i18n.B52gLzii.js +7 -0
  39. package/dist/_astro/{open-docs-in-session.B0ZdZNj2.js → open-docs-in-session.Xg3OSOfc.js} +1 -1
  40. package/dist/_astro/{plugins.D5ypJIXn.js → plugins.BDZqJNOy.js} +1 -1
  41. package/dist/_astro/{pm.BsnTv63L.js → pm.Bl3hz9fF.js} +4 -4
  42. package/dist/_astro/{settings.CnDCvwnQ.js → settings.C6NWuiFO.js} +2 -2
  43. package/dist/_astro/{spaces-client.Cai2tHEI.js → spaces-client.k_ciWMai.js} +1 -1
  44. package/dist/_astro/update.Bl_HfSe6.js +1 -0
  45. package/dist/_astro/{view-prefs.HCowOWXL.js → view-prefs.Dyu_lmN2.js} +1 -1
  46. package/dist/case-exec/index.html +4 -4
  47. package/dist/cases/generate/index.html +4 -4
  48. package/dist/cases/library/index.html +4 -4
  49. package/dist/dashboard/index.html +4 -4
  50. package/dist/docs/changelog/index.html +26 -4
  51. package/dist/docs/install/index.html +3 -3
  52. package/dist/docs/manual/index.html +24 -6
  53. package/dist/index.html +4 -4
  54. package/dist/knowledge/index.html +4 -4
  55. package/dist/knowledge//345/212/237/350/203/275/346/265/213/350/257/225/347/224/250/344/276/213/347/274/226/345/206/231/350/247/204/350/214/203/index.html +3 -3
  56. package/dist/plugins/index.html +4 -4
  57. package/dist/pm/bugs/index.html +4 -4
  58. package/dist/pm/iterations/index.html +4 -4
  59. package/dist/pm/projects/detail/index.html +4 -4
  60. package/dist/pm/projects/index.html +4 -4
  61. package/dist/pm/requirements/index.html +4 -4
  62. package/dist/prompts/index.html +4 -4
  63. package/dist/reports/index.html +4 -4
  64. package/dist/requirements/index.html +4 -4
  65. package/dist/tasks/index.html +4 -4
  66. package/dist/templates/index.html +4 -4
  67. package/dist/templates//345/212/237/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212//345/212/237/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212/346/250/241/346/235/277/index.html +3 -3
  68. package/dist/templates//346/200/247/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212//346/200/247/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212/346/250/241/346/235/277/index.html +3 -3
  69. package/dist/templates//346/200/247/350/203/275/346/265/213/350/257/225/347/224/250/344/276/213//346/200/247/350/203/275/346/265/213/350/257/225/347/224/250/344/276/213/346/250/241/346/235/277/index.html +3 -3
  70. package/dist/templates//346/216/245/345/217/243/346/265/213/350/257/225/346/212/245/345/221/212//346/216/245/345/217/243/346/265/213/350/257/225/346/212/245/345/221/212/346/250/241/346/235/277/index.html +3 -3
  71. package/dist/templates//350/207/252/345/212/250/345/214/226/346/265/213/350/257/225/347/224/250/344/276/213//350/207/252/345/212/250/345/214/226/346/265/213/350/257/225/347/224/250/344/276/213/346/250/241/346/235/277/index.html +3 -3
  72. package/dist/test-stats/index.html +4 -4
  73. package/dist/todos/index.html +4 -4
  74. package/dist/ui-automation/index.html +281 -0
  75. package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +17 -3
  76. package/lh-plugins/lh-uiauto.mjs +1237 -0
  77. package/lh-plugins/storage-domain.mjs +7 -0
  78. package/lh-plugins/uiauto-argv-guard.cjs +41 -0
  79. package/package.json +1 -1
  80. package/dist/_astro/Base.DjIEQkT7.css +0 -1
  81. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.D0snmAJ_.js +0 -1
  82. package/dist/_astro/PluginsPage.uvmSuXzi.js +0 -1
  83. package/dist/_astro/PmBugsBoard.CiaIhCHv.js +0 -1
  84. package/dist/_astro/PmIterationsBoard.H67QwKFw.js +0 -1
  85. package/dist/_astro/PmRequirementsBoard.BPjZ7khP.js +0 -1
  86. package/dist/_astro/PmRequirementsBoard.CanxvcKg.js +0 -1
  87. package/dist/_astro/SettingsDialog.DEgsVfaL.js +0 -1
  88. package/dist/_astro/app-config.DKMxjv3g.js +0 -1
  89. package/dist/_astro/i18n.BXeGGutk.js +0 -7
  90. package/dist/_astro/update.DXCPfU4a.js +0 -1
@@ -0,0 +1,1237 @@
1
+ /**
2
+ * 自动化测试(空间级):挂载目标项目里已有的 Playwright,跑用例、看日志、看报告。
3
+ *
4
+ * 数据落在:
5
+ * ```
6
+ * <当前数据空间>/UI自动化/
7
+ * UI自动化.json # { version, projects, runs }
8
+ * 报告/<runId>/ # Playwright HTML report 直接写到这里
9
+ * 结果/<runId>.json # Playwright JSON reporter 原始结果
10
+ * 日志/<runId>.log # 原始 stdout / stderr
11
+ * ```
12
+ *
13
+ * 约束:
14
+ * - 不自动安装依赖、不联网:只用项目自己的 `node_modules/.bin/playwright`,
15
+ * 退而求其次 `npx --no-install playwright`;找不到就报「未安装」。
16
+ * - 项目目录只读:目录树 / 文件预览都限制在项目目录内,不做写操作。
17
+ * - 同一项目同时只允许一个 run,全局最多 2 个。
18
+ */
19
+ import crypto from 'node:crypto';
20
+ import fs from 'node:fs';
21
+ import path from 'node:path';
22
+ import { spawn } from 'node:child_process';
23
+ import { fileURLToPath } from 'node:url';
24
+
25
+ import { nativePickDirectory } from '../builtin/session/lh-fs.mjs';
26
+ import { getDataRoot } from '../builtin/session/space-context.mjs';
27
+ import { resolveContentRoot } from '../builtin/session/space-layout.mjs';
28
+
29
+ const PREFIX = '/__tb_uiauto';
30
+ const VERSION = 1;
31
+
32
+ /** 预加载守卫:给 Playwright 的 `--project` 参数让路(见文件内注释) */
33
+ const ARGV_GUARD_PATH = path.join(
34
+ path.dirname(fileURLToPath(import.meta.url)),
35
+ 'uiauto-argv-guard.cjs',
36
+ );
37
+
38
+ export const UIAUTO_DIR_NAME = 'UI自动化';
39
+ export const UIAUTO_STORE_FILE = 'UI自动化.json';
40
+ export const REPORT_DIR_NAME = '报告';
41
+ export const RESULT_DIR_NAME = '结果';
42
+ export const LOG_DIR_NAME = '日志';
43
+
44
+ export const MAX_CONCURRENT_RUNS = 2;
45
+ export const MAX_TREE_ITEMS = 2000;
46
+ export const MAX_PREVIEW_BYTES = 256 * 1024;
47
+ const MAX_JSON_BYTES = 32 * 1024 * 1024;
48
+ const MAX_RAW_LOG_BYTES = 4 * 1024 * 1024;
49
+ const MAX_BODY_BYTES = 1024 * 1024;
50
+ const STOP_GRACE_MS = 5000;
51
+
52
+ export const PLAYWRIGHT_CONFIG_FILES = [
53
+ 'playwright.config.ts',
54
+ 'playwright.config.js',
55
+ 'playwright.config.mjs',
56
+ 'playwright.config.cjs',
57
+ ];
58
+
59
+ /** 目录树里一律不展开的目录名(构建产物 / 依赖 / 测试输出) */
60
+ export const TREE_IGNORED_NAMES = new Set([
61
+ 'node_modules',
62
+ '.git',
63
+ '.svn',
64
+ '.hg',
65
+ 'test-results',
66
+ 'playwright-report',
67
+ 'blob-report',
68
+ 'dist',
69
+ 'coverage',
70
+ '.next',
71
+ '.nuxt',
72
+ '.cache',
73
+ '.turbo',
74
+ '.DS_Store',
75
+ ]);
76
+
77
+ export const RUN_STATUSES = ['running', 'passed', 'failed', 'cancelled', 'error', 'interrupted'];
78
+
79
+ const MAX_ARG_TEXT = 500;
80
+
81
+ /** @type {Map<string, RunProcess>} */
82
+ const RUNNING = new Map();
83
+
84
+ /**
85
+ * @typedef {object} RunProcess
86
+ * @property {import('node:child_process').ChildProcess} child
87
+ * @property {string} projectId
88
+ * @property {string} runId
89
+ * @property {string} logAbs
90
+ * @property {fs.WriteStream | null} stream
91
+ * @property {string} log
92
+ * @property {number} logStart
93
+ * @property {boolean} stopping
94
+ * @property {NodeJS.Timeout | null} killTimer
95
+ * @property {boolean} settled
96
+ */
97
+
98
+ function sendJson(res, status, body) {
99
+ res.statusCode = status;
100
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
101
+ res.setHeader('Cache-Control', 'no-store');
102
+ res.end(JSON.stringify(body));
103
+ }
104
+
105
+ function readBodyLimited(req) {
106
+ return new Promise((resolve, reject) => {
107
+ const chunks = [];
108
+ let size = 0;
109
+ req.on('data', (chunk) => {
110
+ size += chunk.length;
111
+ if (size > MAX_BODY_BYTES) {
112
+ reject(new Error('请求体过大'));
113
+ req.destroy();
114
+ return;
115
+ }
116
+ chunks.push(chunk);
117
+ });
118
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
119
+ req.on('error', reject);
120
+ });
121
+ }
122
+
123
+ function text(value, max = 200) {
124
+ return typeof value === 'string' ? value.trim().slice(0, max) : '';
125
+ }
126
+
127
+ function intOr(value, fallback, min, max) {
128
+ const n = typeof value === 'number' ? value : Number(String(value ?? '').trim());
129
+ if (!Number.isFinite(n)) return fallback;
130
+ return Math.min(max, Math.max(min, Math.round(n)));
131
+ }
132
+
133
+ /** 绝对路径是否在 base 内(base 自身也算内) */
134
+ export function isPathInside(base, target) {
135
+ const root = path.resolve(base);
136
+ const abs = path.resolve(target);
137
+ return abs === root || abs.startsWith(`${root}${path.sep}`);
138
+ }
139
+
140
+ /**
141
+ * 把相对路径解析到 base 内;`../`、绝对路径、盘符逃逸一律返回空串。
142
+ * @param {string} base
143
+ * @param {string} rel
144
+ * @returns {string}
145
+ */
146
+ export function resolveInside(base, rel) {
147
+ const raw = String(rel ?? '').replace(/\\/g, '/');
148
+ if (raw.includes('\0')) return '';
149
+ if (path.isAbsolute(raw) || /^[a-zA-Z]:/.test(raw)) return '';
150
+ const abs = path.resolve(base, raw);
151
+ return isPathInside(base, abs) ? abs : '';
152
+ }
153
+
154
+ export function shouldIgnoreTreeName(name) {
155
+ return TREE_IGNORED_NAMES.has(String(name));
156
+ }
157
+
158
+ /** 项目内相对路径(POSIX),用于前端展示 */
159
+ function toPosixRel(base, abs) {
160
+ return path.relative(base, abs).split(path.sep).join('/');
161
+ }
162
+
163
+ function storeDir(root) {
164
+ return resolveContentRoot(root, UIAUTO_DIR_NAME).abs;
165
+ }
166
+
167
+ export function uiautoStorePaths(root) {
168
+ const dir = storeDir(root);
169
+ return {
170
+ dir,
171
+ store: path.join(dir, UIAUTO_STORE_FILE),
172
+ reportDir: path.join(dir, REPORT_DIR_NAME),
173
+ resultDir: path.join(dir, RESULT_DIR_NAME),
174
+ logDir: path.join(dir, LOG_DIR_NAME),
175
+ };
176
+ }
177
+
178
+ function emptyStore() {
179
+ return { version: VERSION, projects: [], runs: [] };
180
+ }
181
+
182
+ function normalizeProject(raw) {
183
+ if (!raw || typeof raw !== 'object') return null;
184
+ const dir = text(raw.dir, 4096);
185
+ if (!dir) return null;
186
+ return {
187
+ id: text(raw.id, 64) || `uia_${crypto.randomBytes(8).toString('hex')}`,
188
+ name: text(raw.name, 200) || path.basename(dir),
189
+ dir,
190
+ createdAt: text(raw.createdAt, 40) || new Date().toISOString(),
191
+ lastRunId: text(raw.lastRunId, 64),
192
+ lastRunAt: text(raw.lastRunAt, 40),
193
+ lastStatus: RUN_STATUSES.includes(raw.lastStatus) ? raw.lastStatus : '',
194
+ };
195
+ }
196
+
197
+ function normalizeRun(raw) {
198
+ if (!raw || typeof raw !== 'object') return null;
199
+ const id = text(raw.id, 64);
200
+ const projectId = text(raw.projectId, 64);
201
+ if (!id || !projectId) return null;
202
+ const status = RUN_STATUSES.includes(raw.status) ? raw.status : 'error';
203
+ return {
204
+ id,
205
+ projectId,
206
+ startedAt: text(raw.startedAt, 40),
207
+ finishedAt: text(raw.finishedAt, 40),
208
+ status,
209
+ exitCode: Number.isFinite(raw.exitCode) ? raw.exitCode : null,
210
+ durationMs: intOr(raw.durationMs, 0, 0, Number.MAX_SAFE_INTEGER),
211
+ total: intOr(raw.total, 0, 0, 1_000_000),
212
+ passed: intOr(raw.passed, 0, 0, 1_000_000),
213
+ failed: intOr(raw.failed, 0, 0, 1_000_000),
214
+ skipped: intOr(raw.skipped, 0, 0, 1_000_000),
215
+ flaky: intOr(raw.flaky, 0, 0, 1_000_000),
216
+ args: normalizeRunArgs(raw.args),
217
+ projectNames: Array.isArray(raw.projectNames)
218
+ ? raw.projectNames
219
+ .map((name) => text(name, 100))
220
+ .filter(Boolean)
221
+ .slice(0, 50)
222
+ : [],
223
+ reportRel: text(raw.reportRel, 1024),
224
+ resultRel: text(raw.resultRel, 1024),
225
+ logRel: text(raw.logRel, 1024),
226
+ error: text(raw.error, 4000),
227
+ };
228
+ }
229
+
230
+ function normalizeRunArgs(raw) {
231
+ const source = raw && typeof raw === 'object' ? raw : {};
232
+ return {
233
+ file: text(source.file, 1024),
234
+ grep: text(source.grep, MAX_ARG_TEXT),
235
+ // 老数据里叫 browser,读取时兼容;新写入统一用 project(Playwright config 里的项目名)
236
+ project: text(source.project, 100) || text(source.browser, 100),
237
+ headed: source.headed === true,
238
+ workers: intOr(source.workers, 0, 0, 32),
239
+ lastFailed: source.lastFailed === true,
240
+ };
241
+ }
242
+
243
+ function normalizeStore(raw) {
244
+ const base = emptyStore();
245
+ if (!raw || typeof raw !== 'object') return base;
246
+ base.projects = Array.isArray(raw.projects)
247
+ ? raw.projects.map(normalizeProject).filter(Boolean)
248
+ : [];
249
+ base.runs = Array.isArray(raw.runs) ? raw.runs.map(normalizeRun).filter(Boolean) : [];
250
+ return base;
251
+ }
252
+
253
+ function readStore(root) {
254
+ const fp = uiautoStorePaths(root).store;
255
+ let store;
256
+ try {
257
+ store = normalizeStore(JSON.parse(fs.readFileSync(fp, 'utf8')));
258
+ } catch {
259
+ store = emptyStore();
260
+ }
261
+ return reconcileStore(store);
262
+ }
263
+
264
+ /** 服务重启后内存里没有对应进程的 running,一定是上次异常退出留下的 */
265
+ function reconcileStore(store) {
266
+ let dirty = false;
267
+ for (const run of store.runs) {
268
+ if (run.status !== 'running' || RUNNING.has(run.id)) continue;
269
+ run.status = 'interrupted';
270
+ run.finishedAt = run.finishedAt || new Date().toISOString();
271
+ run.error = run.error || '服务已重启,本次运行被中断';
272
+ dirty = true;
273
+ }
274
+ return { store, dirty };
275
+ }
276
+
277
+ function writeStore(root, store) {
278
+ const fp = uiautoStorePaths(root).store;
279
+ fs.mkdirSync(path.dirname(fp), { recursive: true });
280
+ const tmp = `${fp}.${process.pid}.tmp`;
281
+ fs.writeFileSync(tmp, `${JSON.stringify(store, null, 2)}\n`, 'utf8');
282
+ fs.renameSync(tmp, fp);
283
+ }
284
+
285
+ function readStoreForWrite(root) {
286
+ const { store } = readStore(root);
287
+ return store;
288
+ }
289
+
290
+ function findProject(store, projectId) {
291
+ return store.projects.find((p) => p.id === projectId) ?? null;
292
+ }
293
+
294
+ function findRun(store, runId) {
295
+ return store.runs.find((r) => r.id === runId) ?? null;
296
+ }
297
+
298
+ /** 目录状态:是否存在、有没有配置文件、依赖装没装 */
299
+ export function detectProject(dir) {
300
+ let exists = false;
301
+ try {
302
+ exists = fs.statSync(dir).isDirectory();
303
+ } catch {
304
+ exists = false;
305
+ }
306
+ const configFile = exists
307
+ ? (PLAYWRIGHT_CONFIG_FILES.find((name) => fs.existsSync(path.join(dir, name))) ?? '')
308
+ : '';
309
+ const binName = process.platform === 'win32' ? 'playwright.cmd' : 'playwright';
310
+ const localBin = exists ? path.join(dir, 'node_modules', '.bin', binName) : '';
311
+ const localPkg = exists ? path.join(dir, 'node_modules', '@playwright', 'test') : '';
312
+ let packageManager = '';
313
+ let hasDependency = false;
314
+ if (exists) {
315
+ try {
316
+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
317
+ const deps = {
318
+ ...(pkg?.dependencies ?? {}),
319
+ ...(pkg?.devDependencies ?? {}),
320
+ };
321
+ hasDependency = Object.keys(deps).includes('@playwright/test');
322
+ if (typeof pkg?.packageManager === 'string' && pkg.packageManager) {
323
+ packageManager = pkg.packageManager.split('@')[0] || '';
324
+ }
325
+ } catch {
326
+ // 没有 / 坏掉的 package.json:以配置文件为准
327
+ }
328
+ if (!packageManager && fs.existsSync(path.join(dir, 'pnpm-lock.yaml'))) packageManager = 'pnpm';
329
+ else if (!packageManager && fs.existsSync(path.join(dir, 'yarn.lock'))) packageManager = 'yarn';
330
+ else if (!packageManager && fs.existsSync(path.join(dir, 'package-lock.json'))) {
331
+ packageManager = 'npm';
332
+ }
333
+ }
334
+ const playwrightInstalled = Boolean(
335
+ exists && (fs.existsSync(localBin) || fs.existsSync(localPkg)),
336
+ );
337
+ return {
338
+ exists,
339
+ configFile,
340
+ playwrightInstalled,
341
+ hasDependency,
342
+ packageManager,
343
+ /** 添加项目时的最低要求:有配置文件,或 package.json 声明了 @playwright/test */
344
+ mountable: Boolean(exists && (configFile || hasDependency)),
345
+ };
346
+ }
347
+
348
+ function decorateProject(project) {
349
+ const health = detectProject(project.dir);
350
+ const running = [...RUNNING.values()].find((entry) => entry.projectId === project.id);
351
+ return {
352
+ ...project,
353
+ ...health,
354
+ runningRunId: running ? running.runId : '',
355
+ };
356
+ }
357
+
358
+ /** 该项目最近一次运行解析到的 Playwright 项目名(setup / chromium-login …) */
359
+ function latestProjectNames(store, projectId) {
360
+ const runs = store.runs
361
+ .filter((run) => run.projectId === projectId && run.projectNames.length)
362
+ .sort((a, b) => (a.startedAt < b.startedAt ? 1 : -1));
363
+ return runs[0]?.projectNames ?? [];
364
+ }
365
+
366
+ /**
367
+ * 拼 Playwright 运行参数(纯函数,便于单测)。
368
+ * @param {{ file?: string, grep?: string, project?: string, headed?: boolean, workers?: number, lastFailed?: boolean }} options
369
+ */
370
+ export function buildPlaywrightArgs(options = {}) {
371
+ const args = ['test', '--reporter=list,json,html'];
372
+ const file = text(options.file, 1024);
373
+ if (file) args.push(file.replace(/\\/g, '/'));
374
+ const grep = text(options.grep, MAX_ARG_TEXT);
375
+ if (grep) args.push('--grep', grep);
376
+ const project = text(options.project, 100);
377
+ if (project) args.push(`--project=${project}`);
378
+ if (options.headed === true) args.push('--headed');
379
+ const workers = intOr(options.workers, 0, 0, 32);
380
+ if (workers > 0) args.push(`--workers=${workers}`);
381
+ if (options.lastFailed === true) args.push('--last-failed');
382
+ return args;
383
+ }
384
+
385
+ /** 把相对文件路径清成项目内的 POSIX 路径;越界返回空串 */
386
+ export function normalizeRunFile(base, file) {
387
+ const raw = text(file, 1024).replace(/\\/g, '/');
388
+ if (!raw) return '';
389
+ if (path.isAbsolute(raw) || /^[a-zA-Z]:/.test(raw) || raw.split('/').includes('..')) return '';
390
+ const abs = resolveInside(base, raw);
391
+ if (!abs) return '';
392
+ try {
393
+ if (!fs.statSync(abs).isFile()) return '';
394
+ } catch {
395
+ return '';
396
+ }
397
+ return raw.replace(/^\.\//, '');
398
+ }
399
+
400
+ /**
401
+ * 解析 Playwright JSON reporter 的结果(纯函数)。
402
+ * @param {any} raw
403
+ */
404
+ export function parsePlaywrightReport(raw) {
405
+ const empty = {
406
+ total: 0,
407
+ passed: 0,
408
+ failed: 0,
409
+ skipped: 0,
410
+ flaky: 0,
411
+ durationMs: 0,
412
+ errors: [],
413
+ failedTests: [],
414
+ projectNames: [],
415
+ };
416
+ if (!raw || typeof raw !== 'object') return empty;
417
+ const stats = raw.stats && typeof raw.stats === 'object' ? raw.stats : {};
418
+ const projectNames = Array.isArray(raw.config?.projects)
419
+ ? raw.config.projects
420
+ .map((item) => text(item?.name, 100))
421
+ .filter(Boolean)
422
+ .slice(0, 50)
423
+ : [];
424
+ const expected = intOr(stats.expected, 0, 0, 1_000_000);
425
+ const unexpected = intOr(stats.unexpected, 0, 0, 1_000_000);
426
+ const skipped = intOr(stats.skipped, 0, 0, 1_000_000);
427
+ const flaky = intOr(stats.flaky, 0, 0, 1_000_000);
428
+ const errors = Array.isArray(raw.errors)
429
+ ? raw.errors
430
+ .map((item) => text(typeof item === 'string' ? item : item?.message, 2000))
431
+ .filter(Boolean)
432
+ .slice(0, 20)
433
+ : [];
434
+ const failedTests = [];
435
+ const walk = (suite, trail) => {
436
+ if (!suite || typeof suite !== 'object') return;
437
+ const file = text(suite.file, 1024);
438
+ const own = text(suite.title, 500);
439
+ const nextTrail = own ? [...trail, own] : trail;
440
+ for (const spec of Array.isArray(suite.specs) ? suite.specs : []) {
441
+ const tests = Array.isArray(spec?.tests) ? spec.tests : [];
442
+ const bad = tests.some(
443
+ (t) =>
444
+ t?.status === 'unexpected' ||
445
+ t?.status === 'timedOut' ||
446
+ (Array.isArray(t?.results) &&
447
+ t.results.some((r) => r?.status === 'unexpected' || r?.status === 'timedOut')),
448
+ );
449
+ if (!bad) continue;
450
+ failedTests.push({
451
+ title: [...nextTrail, text(spec?.title, 500)].filter(Boolean).join(' › '),
452
+ file,
453
+ });
454
+ if (failedTests.length >= 50) return;
455
+ }
456
+ for (const child of Array.isArray(suite.suites) ? suite.suites : []) walk(child, nextTrail);
457
+ };
458
+ for (const suite of Array.isArray(raw.suites) ? raw.suites : []) walk(suite, []);
459
+ return {
460
+ total: expected + unexpected + skipped + flaky,
461
+ passed: expected,
462
+ failed: unexpected,
463
+ skipped,
464
+ flaky,
465
+ durationMs: intOr(stats.duration, 0, 0, Number.MAX_SAFE_INTEGER),
466
+ errors,
467
+ failedTests,
468
+ projectNames,
469
+ };
470
+ }
471
+
472
+ /** 读取 JSON 结果文件(超过上限当没有,避免把进程内存打满) */
473
+ function readReportResult(abs) {
474
+ try {
475
+ const stat = fs.statSync(abs);
476
+ if (!stat.isFile() || stat.size > MAX_JSON_BYTES) return null;
477
+ return JSON.parse(fs.readFileSync(abs, 'utf8'));
478
+ } catch {
479
+ return null;
480
+ }
481
+ }
482
+
483
+ function resolvePlaywrightCommand(dir) {
484
+ const bin = process.platform === 'win32' ? 'playwright.cmd' : 'playwright';
485
+ const local = path.join(dir, 'node_modules', '.bin', bin);
486
+ if (fs.existsSync(local)) {
487
+ return { command: local, prefix: [], local: true };
488
+ }
489
+ const pkg = path.join(dir, 'node_modules', '@playwright', 'test');
490
+ if (fs.existsSync(pkg)) {
491
+ return {
492
+ command: process.platform === 'win32' ? 'npx.cmd' : 'npx',
493
+ prefix: ['--no-install', 'playwright'],
494
+ local: false,
495
+ };
496
+ }
497
+ return null;
498
+ }
499
+
500
+ function installHint(dir, packageManager) {
501
+ const runner =
502
+ packageManager === 'pnpm' ? 'pnpm install' : packageManager === 'yarn' ? 'yarn' : 'npm install';
503
+ return `未找到 Playwright:请先在 ${dir} 运行「${runner}」,如首次使用再运行「${runner === 'yarn' ? 'yarn playwright install' : runner === 'pnpm' ? 'pnpm exec playwright install' : 'npx playwright install'}」。`;
504
+ }
505
+
506
+ function appendLog(entry, chunk) {
507
+ const value = String(chunk ?? '');
508
+ if (!value) return;
509
+ entry.log += value;
510
+ if (entry.log.length > MAX_RAW_LOG_BYTES) {
511
+ const drop = entry.log.length - MAX_RAW_LOG_BYTES;
512
+ entry.log = entry.log.slice(drop);
513
+ entry.logStart += drop;
514
+ }
515
+ if (entry.stream) {
516
+ try {
517
+ entry.stream.write(value);
518
+ } catch {
519
+ // 写盘失败不影响运行
520
+ }
521
+ }
522
+ }
523
+
524
+ function killRun(entry, signal) {
525
+ const pid = entry.child.pid;
526
+ if (!pid) return;
527
+ try {
528
+ if (process.platform === 'win32') {
529
+ if (signal === 'SIGKILL') {
530
+ spawn('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore' });
531
+ } else {
532
+ entry.child.kill();
533
+ }
534
+ } else {
535
+ process.kill(-pid, signal);
536
+ }
537
+ } catch {
538
+ try {
539
+ entry.child.kill(signal);
540
+ } catch {
541
+ // 已经退出
542
+ }
543
+ }
544
+ }
545
+
546
+ function finishRun(root, entry, runId, exitCode, spawnError) {
547
+ if (entry.settled) return;
548
+ entry.settled = true;
549
+ if (entry.killTimer) clearTimeout(entry.killTimer);
550
+ RUNNING.delete(runId);
551
+ if (entry.stream) {
552
+ try {
553
+ entry.stream.end();
554
+ } catch {
555
+ // ignore
556
+ }
557
+ entry.stream = null;
558
+ }
559
+
560
+ const paths = uiautoStorePaths(root);
561
+ const store = readStoreForWrite(root);
562
+ const run = findRun(store, runId);
563
+ if (!run) return;
564
+
565
+ const summary = parsePlaywrightReport(
566
+ readReportResult(path.join(paths.resultDir, `${runId}.json`)),
567
+ );
568
+ const finishedAt = new Date().toISOString();
569
+ const started = Date.parse(run.startedAt);
570
+ const durationMs = summary.durationMs || (Number.isFinite(started) ? Date.now() - started : 0);
571
+
572
+ let status;
573
+ if (entry.stopping) status = 'cancelled';
574
+ else if (spawnError) status = 'error';
575
+ else if (exitCode === 0) status = 'passed';
576
+ else status = 'failed';
577
+
578
+ let error = '';
579
+ if (spawnError) error = text(spawnError, 4000);
580
+ else if (summary.errors.length) error = summary.errors.join('\n').slice(0, 4000);
581
+ else if (status === 'failed' && summary.total === 0) {
582
+ const tail = entry.log.slice(-1200).trim();
583
+ if (tail) error = tail;
584
+ }
585
+
586
+ run.status = status;
587
+ run.exitCode = exitCode;
588
+ run.finishedAt = finishedAt;
589
+ run.durationMs = durationMs;
590
+ run.total = summary.total;
591
+ run.passed = summary.passed;
592
+ run.failed = summary.failed;
593
+ run.skipped = summary.skipped;
594
+ run.flaky = summary.flaky;
595
+ if (summary.projectNames.length) run.projectNames = summary.projectNames;
596
+ run.error = error;
597
+
598
+ const project = findProject(store, run.projectId);
599
+ if (project) {
600
+ project.lastRunId = run.id;
601
+ project.lastRunAt = run.startedAt;
602
+ project.lastStatus = run.status;
603
+ }
604
+ writeStore(root, store);
605
+ }
606
+
607
+ function runView(run) {
608
+ return {
609
+ ...run,
610
+ reportUrl: run.reportRel ? `${PREFIX}/report/${encodeURIComponent(run.id)}/` : '',
611
+ logUrl: run.logRel ? `${PREFIX}/run?id=${encodeURIComponent(run.id)}` : '',
612
+ };
613
+ }
614
+
615
+ function startRun(root, body) {
616
+ const store = readStoreForWrite(root);
617
+ const projectId = text(body?.projectId, 64);
618
+ const project = findProject(store, projectId);
619
+ if (!project) return { error: '项目不存在', status: 404 };
620
+
621
+ const health = detectProject(project.dir);
622
+ if (!health.exists) return { error: '项目目录不存在,请重新选择目录', status: 400 };
623
+ if (!health.mountable) {
624
+ return {
625
+ error: '该目录下没有 playwright.config 或 @playwright/test 依赖,无法运行',
626
+ status: 400,
627
+ };
628
+ }
629
+ const command = resolvePlaywrightCommand(project.dir);
630
+ if (!command) {
631
+ return { error: installHint(project.dir, health.packageManager), status: 400 };
632
+ }
633
+
634
+ for (const entry of RUNNING.values()) {
635
+ if (entry.projectId === projectId) {
636
+ return { error: '该项目已有运行中的任务,请等待结束或先停止', status: 409 };
637
+ }
638
+ }
639
+ if (RUNNING.size >= MAX_CONCURRENT_RUNS) {
640
+ return { error: `全局最多同时运行 ${MAX_CONCURRENT_RUNS} 个项目,请稍后再试`, status: 409 };
641
+ }
642
+
643
+ const args = normalizeRunArgs(body);
644
+ if (args.file) {
645
+ const file = normalizeRunFile(project.dir, args.file);
646
+ if (!file) return { error: '指定的测试文件不在项目目录内或不存在', status: 400 };
647
+ args.file = file;
648
+ }
649
+
650
+ const runId = `uar_${Date.now().toString(36)}_${crypto.randomBytes(3).toString('hex')}`;
651
+ const paths = uiautoStorePaths(root);
652
+ const reportAbs = path.join(paths.reportDir, runId);
653
+ const resultAbs = path.join(paths.resultDir, `${runId}.json`);
654
+ const logAbs = path.join(paths.logDir, `${runId}.log`);
655
+ fs.mkdirSync(reportAbs, { recursive: true });
656
+ fs.mkdirSync(paths.resultDir, { recursive: true });
657
+ fs.mkdirSync(paths.logDir, { recursive: true });
658
+
659
+ const startedAt = new Date().toISOString();
660
+ const cliArgs = [...command.prefix, ...buildPlaywrightArgs(args)];
661
+ const env = {
662
+ ...process.env,
663
+ PLAYWRIGHT_HTML_REPORT: reportAbs,
664
+ PLAYWRIGHT_HTML_OPEN: 'never',
665
+ PLAYWRIGHT_JSON_OUTPUT_NAME: resultAbs,
666
+ FORCE_COLOR: '0',
667
+ NO_COLOR: '1',
668
+ };
669
+ // 有些项目的 config 会 import tsconfig-paths/register,它把 `--project` 当成 tsconfig 路径;
670
+ // 预加载守卫只在加载它的瞬间摘掉这两个参数,避免 ENOENT(详见 uiauto-argv-guard.cjs)
671
+ const guard = ARGV_GUARD_PATH;
672
+ if (args.project && fs.existsSync(guard)) {
673
+ const requireFlag = `--require ${JSON.stringify(guard)}`;
674
+ env.NODE_OPTIONS = env.NODE_OPTIONS ? `${env.NODE_OPTIONS} ${requireFlag}` : requireFlag;
675
+ }
676
+
677
+ let child;
678
+ try {
679
+ child = spawn(command.command, cliArgs, {
680
+ cwd: project.dir,
681
+ env,
682
+ stdio: ['ignore', 'pipe', 'pipe'],
683
+ detached: process.platform !== 'win32',
684
+ windowsHide: true,
685
+ });
686
+ } catch (err) {
687
+ return { error: `启动失败:${err instanceof Error ? err.message : String(err)}`, status: 500 };
688
+ }
689
+
690
+ const run = {
691
+ id: runId,
692
+ projectId,
693
+ startedAt,
694
+ finishedAt: '',
695
+ status: 'running',
696
+ exitCode: null,
697
+ durationMs: 0,
698
+ total: 0,
699
+ passed: 0,
700
+ failed: 0,
701
+ skipped: 0,
702
+ flaky: 0,
703
+ args,
704
+ projectNames: [],
705
+ reportRel: `${REPORT_DIR_NAME}/${runId}`,
706
+ resultRel: `${RESULT_DIR_NAME}/${runId}.json`,
707
+ logRel: `${LOG_DIR_NAME}/${runId}.log`,
708
+ error: '',
709
+ };
710
+ store.runs.push(run);
711
+ project.lastRunId = runId;
712
+ project.lastRunAt = startedAt;
713
+ project.lastStatus = 'running';
714
+ writeStore(root, store);
715
+
716
+ /** @type {RunProcess} */
717
+ const entry = {
718
+ child,
719
+ projectId,
720
+ runId,
721
+ logAbs,
722
+ stream: fs.createWriteStream(logAbs, { flags: 'a' }),
723
+ log: '',
724
+ logStart: 0,
725
+ stopping: false,
726
+ killTimer: null,
727
+ settled: false,
728
+ };
729
+ RUNNING.set(runId, entry);
730
+
731
+ child.stdout?.setEncoding('utf8');
732
+ child.stderr?.setEncoding('utf8');
733
+ child.stdout?.on('data', (chunk) => appendLog(entry, chunk));
734
+ child.stderr?.on('data', (chunk) => appendLog(entry, chunk));
735
+ child.on('error', (err) => {
736
+ appendLog(entry, `\n[lantern] 启动失败:${err.message}\n`);
737
+ finishRun(root, entry, runId, null, err.message);
738
+ });
739
+ child.on('close', (code) => {
740
+ appendLog(entry, `\n[lantern] 进程退出,exitCode=${code ?? 'null'}\n`);
741
+ finishRun(root, entry, runId, code, '');
742
+ });
743
+
744
+ return { run: runView(run), command: command.command, args: cliArgs };
745
+ }
746
+
747
+ function stopRun(runId) {
748
+ const entry = RUNNING.get(runId);
749
+ if (!entry) return false;
750
+ if (entry.stopping) return true;
751
+ entry.stopping = true;
752
+ appendLog(entry, '\n[lantern] 收到停止请求,正在结束进程…\n');
753
+ killRun(entry, 'SIGTERM');
754
+ entry.killTimer = setTimeout(() => {
755
+ if (!RUNNING.has(runId)) return;
756
+ appendLog(entry, '\n[lantern] 5s 内未退出,强制结束。\n');
757
+ killRun(entry, 'SIGKILL');
758
+ }, STOP_GRACE_MS);
759
+ entry.killTimer.unref?.();
760
+ return true;
761
+ }
762
+
763
+ const MIME_BY_EXT = {
764
+ '.html': 'text/html; charset=utf-8',
765
+ '.htm': 'text/html; charset=utf-8',
766
+ '.js': 'text/javascript; charset=utf-8',
767
+ '.mjs': 'text/javascript; charset=utf-8',
768
+ '.css': 'text/css; charset=utf-8',
769
+ '.json': 'application/json; charset=utf-8',
770
+ '.map': 'application/json; charset=utf-8',
771
+ '.svg': 'image/svg+xml',
772
+ '.png': 'image/png',
773
+ '.jpg': 'image/jpeg',
774
+ '.jpeg': 'image/jpeg',
775
+ '.gif': 'image/gif',
776
+ '.webp': 'image/webp',
777
+ '.ico': 'image/x-icon',
778
+ '.woff': 'font/woff',
779
+ '.woff2': 'font/woff2',
780
+ '.ttf': 'font/ttf',
781
+ '.txt': 'text/plain; charset=utf-8',
782
+ '.zip': 'application/zip',
783
+ '.webm': 'video/webm',
784
+ '.mp4': 'video/mp4',
785
+ };
786
+
787
+ function sendReportFile(root, res, runId, rawPath) {
788
+ if (!/^[A-Za-z0-9_-]+$/.test(runId))
789
+ return sendJson(res, 400, { ok: false, error: '运行 ID 不合法' });
790
+ const paths = uiautoStorePaths(root);
791
+ const dir = path.join(paths.reportDir, runId);
792
+ if (!isPathInside(paths.reportDir, dir)) {
793
+ return sendJson(res, 400, { ok: false, error: '报告路径不合法' });
794
+ }
795
+ let rel;
796
+ try {
797
+ rel = decodeURIComponent(rawPath || '');
798
+ } catch {
799
+ return sendJson(res, 400, { ok: false, error: '报告路径不合法' });
800
+ }
801
+ if (rel.includes('\0')) return sendJson(res, 400, { ok: false, error: '报告路径不合法' });
802
+ const target = resolveInside(dir, rel || 'index.html');
803
+ if (!target) return sendJson(res, 400, { ok: false, error: '报告路径不合法' });
804
+ let file = target;
805
+ try {
806
+ if (fs.statSync(file).isDirectory()) file = path.join(file, 'index.html');
807
+ } catch {
808
+ return sendJson(res, 404, { ok: false, error: '报告文件不存在' });
809
+ }
810
+ let stat;
811
+ try {
812
+ stat = fs.statSync(file);
813
+ } catch {
814
+ return sendJson(res, 404, { ok: false, error: '报告文件不存在' });
815
+ }
816
+ if (!stat.isFile()) return sendJson(res, 404, { ok: false, error: '报告文件不存在' });
817
+
818
+ const ext = path.extname(file).toLowerCase();
819
+ res.statusCode = 200;
820
+ res.setHeader('Content-Type', MIME_BY_EXT[ext] ?? 'application/octet-stream');
821
+ res.setHeader('Content-Length', String(stat.size));
822
+ res.setHeader('Cache-Control', 'no-cache');
823
+ // 报告里可能有 trace / 附件:未知类型按下载处理,避免浏览器误渲染
824
+ if (!MIME_BY_EXT[ext]) {
825
+ res.setHeader(
826
+ 'Content-Disposition',
827
+ `attachment; filename*=UTF-8''${encodeURIComponent(path.basename(file))}`,
828
+ );
829
+ }
830
+ fs.createReadStream(file).pipe(res);
831
+ }
832
+
833
+ function listTree(project, rel, depth) {
834
+ const base = project.dir;
835
+ const startAbs = resolveInside(base, rel);
836
+ if (!startAbs) return { error: '目录路径不合法', status: 400 };
837
+ let stat;
838
+ try {
839
+ stat = fs.statSync(startAbs);
840
+ } catch {
841
+ return { error: '目录不存在', status: 404 };
842
+ }
843
+ if (!stat.isDirectory()) return { error: '不是目录', status: 400 };
844
+
845
+ const entries = [];
846
+ let truncated = false;
847
+ const walk = (abs, level) => {
848
+ if (level > depth || truncated) return;
849
+ let names;
850
+ try {
851
+ names = fs.readdirSync(abs, { withFileTypes: true });
852
+ } catch {
853
+ return;
854
+ }
855
+ names.sort((a, b) => {
856
+ if (a.isDirectory() !== b.isDirectory()) return a.isDirectory() ? -1 : 1;
857
+ return a.name.localeCompare(b.name);
858
+ });
859
+ for (const item of names) {
860
+ if (entries.length >= MAX_TREE_ITEMS) {
861
+ truncated = true;
862
+ return;
863
+ }
864
+ if (shouldIgnoreTreeName(item.name)) continue;
865
+ const childAbs = path.join(abs, item.name);
866
+ const childRel = toPosixRel(base, childAbs);
867
+ if (item.isDirectory()) {
868
+ entries.push({ name: item.name, path: childRel, type: 'dir' });
869
+ walk(childAbs, level + 1);
870
+ } else if (item.isFile()) {
871
+ let size = 0;
872
+ try {
873
+ size = fs.statSync(childAbs).size;
874
+ } catch {
875
+ size = 0;
876
+ }
877
+ entries.push({ name: item.name, path: childRel, type: 'file', size });
878
+ }
879
+ }
880
+ };
881
+ walk(startAbs, 0);
882
+ return {
883
+ ok: true,
884
+ path: toPosixRel(base, startAbs),
885
+ entries,
886
+ truncated,
887
+ };
888
+ }
889
+
890
+ /** 从目录树里筛出测试文件,供「指定文件」下拉使用 */
891
+ function listSpecFiles(project) {
892
+ const result = [];
893
+ const walk = (abs, level) => {
894
+ if (level > 6 || result.length >= 500) return;
895
+ let items;
896
+ try {
897
+ items = fs.readdirSync(abs, { withFileTypes: true });
898
+ } catch {
899
+ return;
900
+ }
901
+ for (const item of items) {
902
+ if (result.length >= 500) return;
903
+ if (shouldIgnoreTreeName(item.name)) continue;
904
+ const child = path.join(abs, item.name);
905
+ if (item.isDirectory()) walk(child, level + 1);
906
+ else if (/\.(spec|test)\.(ts|js|mjs|cjs|tsx|jsx)$/.test(item.name)) {
907
+ result.push(toPosixRel(project.dir, child));
908
+ }
909
+ }
910
+ };
911
+ walk(project.dir, 0);
912
+ return result.sort();
913
+ }
914
+
915
+ function previewFile(project, rel) {
916
+ const abs = resolveInside(project.dir, rel);
917
+ if (!abs) return { error: '文件路径不合法', status: 400 };
918
+ let stat;
919
+ try {
920
+ stat = fs.statSync(abs);
921
+ } catch {
922
+ return { error: '文件不存在', status: 404 };
923
+ }
924
+ if (!stat.isFile()) return { error: '不是文件', status: 400 };
925
+ const size = stat.size;
926
+ const readSize = Math.min(size, MAX_PREVIEW_BYTES);
927
+ const buffer = Buffer.alloc(readSize);
928
+ let fd;
929
+ try {
930
+ fd = fs.openSync(abs, 'r');
931
+ fs.readSync(fd, buffer, 0, readSize, 0);
932
+ } catch {
933
+ return { error: '文件读取失败', status: 500 };
934
+ } finally {
935
+ if (fd !== undefined) {
936
+ try {
937
+ fs.closeSync(fd);
938
+ } catch {
939
+ // ignore
940
+ }
941
+ }
942
+ }
943
+ const binary = buffer.includes(0);
944
+ return {
945
+ ok: true,
946
+ path: toPosixRel(project.dir, abs),
947
+ size,
948
+ truncated: size > MAX_PREVIEW_BYTES,
949
+ binary,
950
+ content: binary ? '' : buffer.toString('utf8'),
951
+ };
952
+ }
953
+
954
+ function removeRunArtifacts(root, run) {
955
+ const paths = uiautoStorePaths(root);
956
+ if (run.reportRel) {
957
+ const abs = path.join(paths.dir, run.reportRel);
958
+ if (isPathInside(paths.reportDir, abs)) fs.rmSync(abs, { recursive: true, force: true });
959
+ }
960
+ if (run.resultRel) {
961
+ const abs = path.join(paths.dir, run.resultRel);
962
+ if (isPathInside(paths.resultDir, abs)) fs.rmSync(abs, { force: true });
963
+ }
964
+ if (run.logRel) {
965
+ const abs = path.join(paths.dir, run.logRel);
966
+ if (isPathInside(paths.logDir, abs)) fs.rmSync(abs, { force: true });
967
+ }
968
+ }
969
+
970
+ /**
971
+ * @returns {import('vite').Plugin}
972
+ */
973
+ export function lhUiautoPlugin() {
974
+ return {
975
+ name: 'lh-uiauto',
976
+ configureServer(server) {
977
+ server.middlewares.use(async (req, res, next) => {
978
+ const parsed = new URL(req.url ?? '/', 'http://127.0.0.1');
979
+ if (!parsed.pathname.startsWith(PREFIX)) return next();
980
+ // 数据根惰性读取:切换数据空间后无需重启
981
+ const root = getDataRoot();
982
+ const method = req.method || 'GET';
983
+ const tail = parsed.pathname.slice(PREFIX.length) || '/';
984
+
985
+ try {
986
+ if (method === 'GET' && tail.startsWith('/report/')) {
987
+ const rest = tail.slice('/report/'.length);
988
+ const slash = rest.indexOf('/');
989
+ const runId = slash === -1 ? rest : rest.slice(0, slash);
990
+ const rel = slash === -1 ? '' : rest.slice(slash + 1);
991
+ return sendReportFile(root, res, runId, rel);
992
+ }
993
+
994
+ if (method === 'GET' && parsed.searchParams.get('health') === '1') {
995
+ return sendJson(res, 200, {
996
+ ok: true,
997
+ files: uiautoStorePaths(root),
998
+ running: [...RUNNING.keys()],
999
+ version: VERSION,
1000
+ });
1001
+ }
1002
+
1003
+ if (method === 'GET' && tail === '/projects') {
1004
+ const { store, dirty } = readStore(root);
1005
+ if (dirty) writeStore(root, store);
1006
+ const projects = store.projects.map((project) => ({
1007
+ ...decorateProject(project),
1008
+ specFiles: detectProject(project.dir).exists ? listSpecFiles(project) : [],
1009
+ // 上次运行拿到的 Playwright 项目名(setup / chromium-login 之类),给下拉做候选
1010
+ projectNames: latestProjectNames(store, project.id),
1011
+ }));
1012
+ return sendJson(res, 200, { ok: true, projects });
1013
+ }
1014
+
1015
+ if (method === 'POST' && tail === '/pick-directory') {
1016
+ const picked = await nativePickDirectory();
1017
+ return sendJson(res, 200, { ok: true, dir: picked || '' });
1018
+ }
1019
+
1020
+ if (method === 'POST' && tail === '/projects') {
1021
+ const body = JSON.parse((await readBodyLimited(req)) || '{}');
1022
+ const rawDir = text(body.dir, 4096);
1023
+ if (!rawDir) return sendJson(res, 400, { ok: false, error: '缺少项目目录' });
1024
+ const dir = path.resolve(rawDir);
1025
+ const health = detectProject(dir);
1026
+ if (!health.exists) return sendJson(res, 400, { ok: false, error: '目录不存在' });
1027
+ if (!health.mountable) {
1028
+ return sendJson(res, 400, {
1029
+ ok: false,
1030
+ error:
1031
+ '目录下没有 playwright.config 或 @playwright/test 依赖,不像是 Playwright 项目',
1032
+ });
1033
+ }
1034
+ const store = readStoreForWrite(root);
1035
+ if (store.projects.some((p) => path.resolve(p.dir) === dir)) {
1036
+ return sendJson(res, 409, { ok: false, error: '该目录已经添加过了' });
1037
+ }
1038
+ const project = {
1039
+ id: `uia_${crypto.randomBytes(8).toString('hex')}`,
1040
+ name: text(body.name, 200) || path.basename(dir),
1041
+ dir,
1042
+ createdAt: new Date().toISOString(),
1043
+ lastRunId: '',
1044
+ lastRunAt: '',
1045
+ lastStatus: '',
1046
+ };
1047
+ store.projects.push(project);
1048
+ writeStore(root, store);
1049
+ return sendJson(res, 200, {
1050
+ ok: true,
1051
+ project: {
1052
+ ...decorateProject(project),
1053
+ specFiles: listSpecFiles(project),
1054
+ projectNames: latestProjectNames(store, project.id),
1055
+ },
1056
+ });
1057
+ }
1058
+
1059
+ if (method === 'PATCH' && tail === '/projects') {
1060
+ const body = JSON.parse((await readBodyLimited(req)) || '{}');
1061
+ const store = readStoreForWrite(root);
1062
+ const project = findProject(store, text(body.id, 64));
1063
+ if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
1064
+ const name = text(body.name, 200);
1065
+ if (name) project.name = name;
1066
+ if (typeof body.dir === 'string' && body.dir.trim()) {
1067
+ const dir = path.resolve(text(body.dir, 4096));
1068
+ const health = detectProject(dir);
1069
+ if (!health.exists) return sendJson(res, 400, { ok: false, error: '目录不存在' });
1070
+ if (!health.mountable) {
1071
+ return sendJson(res, 400, {
1072
+ ok: false,
1073
+ error:
1074
+ '目录下没有 playwright.config 或 @playwright/test 依赖,不像是 Playwright 项目',
1075
+ });
1076
+ }
1077
+ project.dir = dir;
1078
+ }
1079
+ writeStore(root, store);
1080
+ return sendJson(res, 200, {
1081
+ ok: true,
1082
+ project: {
1083
+ ...decorateProject(project),
1084
+ specFiles: listSpecFiles(project),
1085
+ projectNames: latestProjectNames(store, project.id),
1086
+ },
1087
+ });
1088
+ }
1089
+
1090
+ if (method === 'DELETE' && tail === '/projects') {
1091
+ const id = text(parsed.searchParams.get('id'), 64);
1092
+ const store = readStoreForWrite(root);
1093
+ const project = findProject(store, id);
1094
+ if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
1095
+ if ([...RUNNING.values()].some((entry) => entry.projectId === id)) {
1096
+ return sendJson(res, 409, { ok: false, error: '项目正在运行,请先停止再移出列表' });
1097
+ }
1098
+ store.projects = store.projects.filter((p) => p.id !== id);
1099
+ writeStore(root, store);
1100
+ return sendJson(res, 200, { ok: true });
1101
+ }
1102
+
1103
+ if (method === 'GET' && tail === '/tree') {
1104
+ const store = readStore(root).store;
1105
+ const project = findProject(store, text(parsed.searchParams.get('projectId'), 64));
1106
+ if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
1107
+ const depth = intOr(parsed.searchParams.get('depth'), 2, 0, 6);
1108
+ const rel = text(parsed.searchParams.get('path'), 2048);
1109
+ const result = listTree(project, rel, depth);
1110
+ if (result.error)
1111
+ return sendJson(res, result.status, { ok: false, error: result.error });
1112
+ return sendJson(res, 200, result);
1113
+ }
1114
+
1115
+ if (method === 'GET' && tail === '/file') {
1116
+ const store = readStore(root).store;
1117
+ const project = findProject(store, text(parsed.searchParams.get('projectId'), 64));
1118
+ if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
1119
+ const result = previewFile(project, text(parsed.searchParams.get('path'), 2048));
1120
+ if (result.error)
1121
+ return sendJson(res, result.status, { ok: false, error: result.error });
1122
+ return sendJson(res, 200, result);
1123
+ }
1124
+
1125
+ if (method === 'POST' && tail === '/run') {
1126
+ const body = JSON.parse((await readBodyLimited(req)) || '{}');
1127
+ const result = startRun(root, body);
1128
+ if (result.error)
1129
+ return sendJson(res, result.status, { ok: false, error: result.error });
1130
+ return sendJson(res, 200, { ok: true, ...result });
1131
+ }
1132
+
1133
+ if (method === 'POST' && tail === '/stop') {
1134
+ const body = JSON.parse((await readBodyLimited(req)) || '{}');
1135
+ const runId = text(body.runId, 64);
1136
+ if (!runId) return sendJson(res, 400, { ok: false, error: '缺少 runId' });
1137
+ if (!stopRun(runId)) {
1138
+ return sendJson(res, 409, { ok: false, error: '该运行已结束或不在本进程中' });
1139
+ }
1140
+ return sendJson(res, 200, { ok: true });
1141
+ }
1142
+
1143
+ if (method === 'GET' && tail === '/run') {
1144
+ const id = text(parsed.searchParams.get('id'), 64);
1145
+ const offset = intOr(parsed.searchParams.get('offset'), 0, 0, Number.MAX_SAFE_INTEGER);
1146
+ const store = readStore(root).store;
1147
+ const run = findRun(store, id);
1148
+ if (!run) return sendJson(res, 404, { ok: false, error: '运行记录不存在' });
1149
+ const entry = RUNNING.get(id);
1150
+ if (!entry) {
1151
+ // 已结束:从日志文件尾部补一段,刷新页面后仍能看到上次输出
1152
+ let log = '';
1153
+ let reset = false;
1154
+ if (run.logRel) {
1155
+ const abs = path.join(uiautoStorePaths(root).dir, run.logRel);
1156
+ if (isPathInside(uiautoStorePaths(root).logDir, abs)) {
1157
+ try {
1158
+ const stat = fs.statSync(abs);
1159
+ const start = Math.max(0, stat.size - MAX_PREVIEW_BYTES);
1160
+ const buffer = Buffer.alloc(stat.size - start);
1161
+ const fd = fs.openSync(abs, 'r');
1162
+ try {
1163
+ fs.readSync(fd, buffer, 0, buffer.length, start);
1164
+ } finally {
1165
+ fs.closeSync(fd);
1166
+ }
1167
+ log = buffer.toString('utf8');
1168
+ reset = true;
1169
+ } catch {
1170
+ log = '';
1171
+ }
1172
+ }
1173
+ }
1174
+ return sendJson(res, 200, {
1175
+ ok: true,
1176
+ run: runView(run),
1177
+ stopping: false,
1178
+ log,
1179
+ nextOffset: 0,
1180
+ reset,
1181
+ });
1182
+ }
1183
+ const reset = offset < entry.logStart;
1184
+ const from = Math.max(offset, entry.logStart);
1185
+ return sendJson(res, 200, {
1186
+ ok: true,
1187
+ run: runView(run),
1188
+ stopping: entry.stopping,
1189
+ log: entry.log.slice(from - entry.logStart),
1190
+ nextOffset: entry.logStart + entry.log.length,
1191
+ reset,
1192
+ });
1193
+ }
1194
+
1195
+ if (method === 'GET' && tail === '/runs') {
1196
+ const projectId = text(parsed.searchParams.get('projectId'), 64);
1197
+ const store = readStore(root).store;
1198
+ const runs = store.runs
1199
+ .filter((run) => !projectId || run.projectId === projectId)
1200
+ .slice()
1201
+ .sort((a, b) => (a.startedAt < b.startedAt ? 1 : -1))
1202
+ .map(runView);
1203
+ return sendJson(res, 200, { ok: true, runs });
1204
+ }
1205
+
1206
+ if (method === 'DELETE' && tail === '/run') {
1207
+ const id = text(parsed.searchParams.get('id'), 64);
1208
+ if (RUNNING.has(id)) {
1209
+ return sendJson(res, 409, { ok: false, error: '运行中,不能删除' });
1210
+ }
1211
+ const store = readStoreForWrite(root);
1212
+ const run = findRun(store, id);
1213
+ if (!run) return sendJson(res, 404, { ok: false, error: '运行记录不存在' });
1214
+ removeRunArtifacts(root, run);
1215
+ store.runs = store.runs.filter((r) => r.id !== id);
1216
+ const project = findProject(store, run.projectId);
1217
+ if (project && project.lastRunId === id) {
1218
+ const latest = store.runs
1219
+ .filter((r) => r.projectId === project.id)
1220
+ .sort((a, b) => (a.startedAt < b.startedAt ? 1 : -1))[0];
1221
+ project.lastRunId = latest?.id ?? '';
1222
+ project.lastRunAt = latest?.startedAt ?? '';
1223
+ project.lastStatus = latest?.status ?? '';
1224
+ }
1225
+ writeStore(root, store);
1226
+ return sendJson(res, 200, { ok: true });
1227
+ }
1228
+
1229
+ return next();
1230
+ } catch (err) {
1231
+ const message = err instanceof Error ? err.message : String(err);
1232
+ return sendJson(res, 500, { ok: false, error: message });
1233
+ }
1234
+ });
1235
+ },
1236
+ };
1237
+ }