lantern-harness 0.1.9 → 0.1.10
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.
- package/CHANGELOG.md +82 -0
- package/README.md +6 -6
- package/builtin/session/lh-fs.mjs +32 -14
- package/dist/500.html +258 -22
- package/dist/_astro/Base.BOY6F0mi.css +1 -0
- package/dist/_astro/Base.astro_astro_type_script_index_0_lang.C30xtpc6.js +1 -0
- package/dist/_astro/CaseExecBoard.Dttqp0wg.js +1 -0
- package/dist/_astro/CaseGenerateApp.DqW_nWMc.js +9 -0
- package/dist/_astro/CasesLibrary.8aMUUGp_.js +1 -0
- package/dist/_astro/ChatApp.BLxf0h1d.js +219 -0
- package/dist/_astro/ColumnResize.BEkEW7qw.js +1 -0
- package/dist/_astro/{ConfirmDialog.CBVsDJ8f.js → ConfirmDialog.BZzZWDci.js} +1 -1
- package/dist/_astro/{DashboardBoard.DCtfrrJz.js → DashboardBoard.CkSbhEDI.js} +3 -3
- package/dist/_astro/DatePicker.Bkl71M49.js +1 -0
- package/dist/_astro/DocsFileBrowser.MKVCfZrE.js +1 -0
- package/dist/_astro/DocsPager.DJY4foYL.js +1 -0
- package/dist/_astro/{DrawerField.CWMLhcPX.js → DrawerField.CHRg77LG.js} +1 -1
- package/dist/_astro/{ExcelFieldTags.B_XMwNNx.js → ExcelFieldTags.DXMeaDa5.js} +4 -4
- package/dist/_astro/KnowledgeLibrary.B-p1aoQN.js +1 -0
- package/dist/_astro/NamePromptDialog.Wa9O530a.js +1 -0
- package/dist/_astro/NavLibraries.C6LImMO_.js +1 -0
- package/dist/_astro/OverflowHint.D6v4Uj2N.js +1 -0
- package/dist/_astro/PluginsPage.-97n3x2U.js +39 -0
- package/dist/_astro/PluginsPage.DkmRPfbU.js +1 -0
- package/dist/_astro/PmBugsBoard.CMT4-eoB.js +1 -0
- package/dist/_astro/PmIterationsBoard.BQM_dzdZ.js +1 -0
- package/dist/_astro/PmProjectDetail.CzU80pat.js +1 -0
- package/dist/_astro/PmProjectsBoard.Cxsa7SYQ.js +1 -0
- package/dist/_astro/PmRequirementsBoard.4_JMDDN0.js +1 -0
- package/dist/_astro/PmRequirementsBoard.B8HL07cw.js +1 -0
- package/dist/_astro/PmShared.Ca2Ao7v_.js +1 -0
- package/dist/_astro/PromptsLibrary.C9BcIxKK.js +1 -0
- package/dist/_astro/ReportsPage.Fh5DRKLT.js +1 -0
- package/dist/_astro/RequirementsLibrary.CBkuWE8X.js +1 -0
- package/dist/_astro/SearchableSelect.DnjoSslK.js +1 -0
- package/dist/_astro/SelectDropdown.CuuDHa8s.js +1 -0
- package/dist/_astro/SettingsDialog.CJvBRcs9.js +1 -0
- package/dist/_astro/SlideOverDrawer.B7B5Wu8I.js +1 -0
- package/dist/_astro/{SpaceSwitcher.CI3KDBOA.js → SpaceSwitcher.BVQLt_tL.js} +2 -2
- package/dist/_astro/TagSelect.CuN5RdF4.js +1 -0
- package/dist/_astro/TasksBoard.Bu-fpIZ7.js +1 -0
- package/dist/_astro/TemplatesLibrary.DSylQGlN.js +1 -0
- package/dist/_astro/TestStatsBoard.CPyKW4wc.js +1 -0
- package/dist/_astro/Toast.R8_2OWRX.js +1 -0
- package/dist/_astro/TodosBoard.8kvRTEW-.js +1 -0
- package/dist/_astro/UiAutoBoard.DFTiDqCp.js +9 -0
- package/dist/_astro/active-element-history.CED-m1Zp.js +1 -0
- package/dist/_astro/app-config.BUPzGl9f.js +1 -0
- package/dist/_astro/{client.Be_SakrB.js → client.BHNTqLjv.js} +3 -3
- package/dist/_astro/dialog.BAPTk9a_.js +1 -0
- package/dist/_astro/hydrate-cache.BXX604Bw.js +1 -0
- package/dist/_astro/{i18n.B52gLzii.js → i18n.BGPnP1Bg.js} +1 -1
- package/dist/_astro/index.astro_astro_type_script_index_0_lang.LPL9mPQY.js +1 -0
- package/dist/_astro/jsx-runtime.DUg_B_vD.js +1 -0
- package/dist/_astro/{lib.DJNDi_Ht.js → lib.CgXLzMMd.js} +15 -15
- package/dist/_astro/listbox.C96OCanh.js +1 -0
- package/dist/_astro/markdown-client.DRva7DS9.js +58 -0
- package/dist/_astro/menu.IPWdRoNM.js +1 -0
- package/dist/_astro/{open-docs-in-session.Xg3OSOfc.js → open-docs-in-session.CyFNgh1I.js} +1 -1
- package/dist/_astro/{plugins.BDZqJNOy.js → plugins.C2BMfzv1.js} +1 -1
- package/dist/_astro/{pm.Bl3hz9fF.js → pm.CagBA-ht.js} +2 -2
- package/dist/_astro/{portal.Cm9XlIPf.js → portal.C0hAhXDF.js} +2 -2
- package/dist/_astro/prompts-meta.Bua-j14I.js +2 -0
- package/dist/_astro/react-dom.DLW9pGCF.js +1 -0
- package/dist/_astro/{react-dom.CqAxpHMt.js → react.Blvh0GOs.js} +1 -1
- package/dist/_astro/report-prompt.CAfZ6RIo.js +1 -0
- package/dist/_astro/{settings.C6NWuiFO.js → settings.Ceefeil5.js} +2 -2
- package/dist/_astro/{spaces-client.k_ciWMai.js → spaces-client.BocUabwy.js} +1 -1
- package/dist/_astro/ui-auto-prompt.CX8fju7r.js +3 -0
- package/dist/_astro/ui-auto.BmC9JJ_X.js +1 -0
- package/dist/_astro/update.CvfIVwnq.js +1 -0
- package/dist/_astro/use-text-value.DBQvHeNl.js +1 -0
- package/dist/_astro/use-tree-walker.DFU2AaAP.js +1 -0
- package/dist/_astro/useListAnim.BoerpmsB.js +1 -0
- package/dist/_astro/{view-prefs.Dyu_lmN2.js → view-prefs.BEAZRcxF.js} +1 -1
- package/dist/case-exec/index.html +458 -22
- package/dist/cases/generate/index.html +258 -22
- package/dist/cases/library/index.html +458 -22
- package/dist/dashboard/index.html +458 -22
- package/dist/docs/changelog/index.html +367 -23
- package/dist/docs/install/index.html +258 -22
- package/dist/docs/manual/index.html +314 -35
- package/dist/index.html +2 -281
- package/dist/knowledge/index.html +458 -22
- 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 +258 -22
- package/dist/plugins/index.html +258 -22
- package/dist/pm/bugs/index.html +458 -22
- package/dist/pm/iterations/index.html +458 -22
- package/dist/pm/projects/detail/index.html +458 -22
- package/dist/pm/projects/index.html +458 -22
- package/dist/pm/requirements/index.html +458 -22
- package/dist/prompts/index.html +458 -22
- package/dist/reports/index.html +458 -22
- package/dist/requirements/index.html +458 -22
- package/dist/tasks/index.html +458 -22
- package/dist/templates/index.html +458 -22
- 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 +258 -22
- 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 +258 -22
- 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 +258 -22
- 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 +258 -22
- 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 +258 -22
- package/dist/test-automation/index.html +717 -0
- package/dist/test-stats/index.html +458 -22
- package/dist/todos/index.html +458 -22
- package/dist/workbench/index.html +517 -0
- package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +80 -43
- package/lh-plugins/lh-project-docs.mjs +14 -0
- package/lh-plugins/lh-uiauto.mjs +1445 -386
- package/lh-plugins/plugin-prompts.mjs +200 -0
- package/lh-plugins/storage-domain.mjs +6 -0
- package/lh-plugins/uiauto-adapters/index.mjs +57 -0
- package/lh-plugins/uiauto-adapters/playwright.mjs +215 -0
- package/lh-plugins/uiauto-adapters/pytest.mjs +151 -0
- package/lh-plugins/uiauto-adapters/selenium.mjs +163 -0
- package/lh-plugins/uiauto-adapters/shared.mjs +371 -0
- package/lh-plugins/uiauto-adapters/tasks.mjs +369 -0
- package/lh-plugins/uiauto-explorer/apps.mjs +332 -0
- package/lh-plugins/uiauto-explorer/diff.mjs +159 -0
- package/lh-plugins/uiauto-explorer/emit-files.mjs +506 -0
- package/lh-plugins/uiauto-explorer/emit-python.mjs +160 -0
- package/lh-plugins/uiauto-explorer/emit-ts.mjs +118 -0
- package/lh-plugins/uiauto-explorer/emit.mjs +15 -0
- package/lh-plugins/uiauto-explorer/ir.mjs +114 -0
- package/lh-plugins/uiauto-explorer/locators.mjs +267 -0
- package/lh-plugins/uiauto-explorer/merge.mjs +235 -0
- package/lh-plugins/uiauto-explorer/plan.mjs +165 -0
- package/lh-plugins/uiauto-explorer/runner.mjs +370 -0
- package/lh-plugins/uiauto-explorer/sessions.mjs +1373 -0
- package/lh-plugins/uiauto-explorer/snapshot.mjs +492 -0
- package/lh-plugins/uiauto-prompt.mjs +122 -0
- package/lh-plugins/uiauto-report.mjs +111 -0
- package/package.json +1 -1
- package/dist/_astro/Base.4X_wsSoR.css +0 -1
- package/dist/_astro/Base.astro_astro_type_script_index_0_lang.Dy7fJoxu.js +0 -1
- package/dist/_astro/CaseExecBoard.DKdfW5fM.js +0 -1
- package/dist/_astro/CaseGenerateApp.Bm8AyH9s.js +0 -9
- package/dist/_astro/CasesLibrary.CvVJZ74h.js +0 -1
- package/dist/_astro/ChatApp.BS-wLBRa.js +0 -276
- package/dist/_astro/ColumnResize.Bs6GL3DJ.js +0 -1
- package/dist/_astro/DatePicker.CMfX7F6z.js +0 -1
- package/dist/_astro/DocsFileBrowser.BtRoZ787.js +0 -1
- package/dist/_astro/DocsPager.C20ue_JZ.js +0 -1
- package/dist/_astro/KnowledgeLibrary.CV4DyStj.js +0 -1
- package/dist/_astro/NamePromptDialog.Dl5kSnQI.js +0 -1
- package/dist/_astro/NavLibraries.DmD2lZBZ.js +0 -1
- package/dist/_astro/OverflowHint.lzmplP5j.js +0 -1
- package/dist/_astro/PluginsPage.B59AMDrB.js +0 -1
- package/dist/_astro/PluginsPage.BEAPymNL.js +0 -39
- package/dist/_astro/PmBugsBoard.CPEyBp0l.js +0 -1
- package/dist/_astro/PmIterationsBoard.zCeLpcBo.js +0 -1
- package/dist/_astro/PmProjectDetail.ejIam5sD.js +0 -1
- package/dist/_astro/PmProjectsBoard.DbXzir8o.js +0 -1
- package/dist/_astro/PmRequirementsBoard.CynewRfv.js +0 -1
- package/dist/_astro/PmRequirementsBoard.D9eUMJWI.js +0 -1
- package/dist/_astro/PmShared.BxTHKdjY.js +0 -1
- package/dist/_astro/PromptsLibrary.Bkruu80b.js +0 -1
- package/dist/_astro/ReportsPage.BoBQshMQ.js +0 -1
- package/dist/_astro/RequirementsLibrary.BC0A8qdk.js +0 -1
- package/dist/_astro/SearchableSelect.CXa1hiDd.js +0 -1
- package/dist/_astro/SelectDropdown.Buv7rQJ_.js +0 -1
- package/dist/_astro/SettingsDialog.Dc-9QNJI.js +0 -1
- package/dist/_astro/SlideOverDrawer.TPbGEoWn.js +0 -1
- package/dist/_astro/TagSelect.u8DTop7v.js +0 -1
- package/dist/_astro/TasksBoard.Bb--oVV8.js +0 -1
- package/dist/_astro/TemplatesLibrary.D1wZq94E.js +0 -1
- package/dist/_astro/TestStatsBoard.DlVezlXl.js +0 -1
- package/dist/_astro/TodosBoard.S84wqcWY.js +0 -1
- package/dist/_astro/UiAutoBoard.BKp9ifxg.js +0 -1
- package/dist/_astro/active-element-history.CeefGkFQ.js +0 -1
- package/dist/_astro/app-config.DUyozIL9.js +0 -1
- package/dist/_astro/dialog.DXHznyjD.js +0 -1
- package/dist/_astro/jsx-runtime.BUXbF_vF.js +0 -1
- package/dist/_astro/listbox.Di-t5U37.js +0 -1
- package/dist/_astro/menu.Bkluqxic.js +0 -1
- package/dist/_astro/prompts-meta.F4wwkjUA.js +0 -2
- package/dist/_astro/report-prompt.Cmw4XzfY.js +0 -1
- package/dist/_astro/update.Bl_HfSe6.js +0 -1
- package/dist/_astro/use-text-value.BuY0Cm1z.js +0 -1
- package/dist/_astro/use-tree-walker.CfTHFX43.js +0 -1
- package/dist/_astro/useListAnim.CpGB1cft.js +0 -1
- package/dist/ui-automation/index.html +0 -281
|
@@ -0,0 +1,1373 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 生成会话:浏览器子进程管理 + 会话落盘 + 试跑 / 写盘。
|
|
3
|
+
*
|
|
4
|
+
* 会话数据放在本机缓存目录 `<空间>/.lantern/local/uiauto/sessions/<id>.json`,
|
|
5
|
+
* 截图在旁边 `<id>/shots/`。
|
|
6
|
+
* 试跑草稿写进项目的 `.lantern-ai/<会话>/`(目录自带 .gitignore),失败保留现场,
|
|
7
|
+
* 可打开 / 重跑 / 看 trace;最终落盘由用户点击确认,写入后还能按项目配置验收。
|
|
8
|
+
*/
|
|
9
|
+
import crypto from 'node:crypto';
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import net from 'node:net';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import readline from 'node:readline';
|
|
14
|
+
import { execFile, spawn } from 'node:child_process';
|
|
15
|
+
import { fileURLToPath } from 'node:url';
|
|
16
|
+
|
|
17
|
+
import { diffText, summarizeDiff } from './diff.mjs';
|
|
18
|
+
import { emitCode } from './emit.mjs';
|
|
19
|
+
import { normalizeIr, slugify } from './ir.mjs';
|
|
20
|
+
import { mergeGeneratedFile } from './merge.mjs';
|
|
21
|
+
import { normalizePlan } from './plan.mjs';
|
|
22
|
+
|
|
23
|
+
const RUNNER_PATH = path.join(path.dirname(fileURLToPath(import.meta.url)), 'runner.mjs');
|
|
24
|
+
const MAX_VERIFY_LOG = 64 * 1024;
|
|
25
|
+
const DEFAULT_VERIFY_TIMEOUT = 180000;
|
|
26
|
+
/** 草稿保留天数:超过就没人再看了,留着只是占目录 */
|
|
27
|
+
const DRAFT_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
28
|
+
const MAX_LEDGER_FILE_BYTES = 400 * 1024;
|
|
29
|
+
|
|
30
|
+
/** Playwright 的 line reporter 会写光标控制符,日志里留着很难看 */
|
|
31
|
+
function stripAnsi(text) {
|
|
32
|
+
return String(text ?? '').replace(/\u001b\[[0-9;?]*[A-Za-z]/g, '');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** sessionId → { child, pending, shotsDir, sessionId } */
|
|
36
|
+
const RUNNING = new Map();
|
|
37
|
+
|
|
38
|
+
/** 浏览器被用户关掉时对外统一用这句,前端据此判断「这轮结束了,别重试」 */
|
|
39
|
+
export const CLOSED_MESSAGE = '浏览器已被关闭,探索已结束';
|
|
40
|
+
|
|
41
|
+
/** 订阅「浏览器被用户关掉」:lh-uiauto 用它把会话状态收回草稿 */
|
|
42
|
+
const closedHandlers = new Set();
|
|
43
|
+
|
|
44
|
+
export function onExplorerClosed(handler) {
|
|
45
|
+
closedHandlers.add(handler);
|
|
46
|
+
return () => closedHandlers.delete(handler);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export const SESSIONS_DIR_NAME = 'sessions';
|
|
50
|
+
|
|
51
|
+
export function sessionsDir(baseDir) {
|
|
52
|
+
return path.join(baseDir, SESSIONS_DIR_NAME);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function sessionFilePath(baseDir, id) {
|
|
56
|
+
return path.join(sessionsDir(baseDir), `${id}.json`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function sessionShotsDir(baseDir, id) {
|
|
60
|
+
return path.join(sessionsDir(baseDir), id, 'shots');
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function readJson(file) {
|
|
64
|
+
try {
|
|
65
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
66
|
+
} catch {
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function writeJsonAtomic(file, data) {
|
|
72
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
73
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
74
|
+
fs.writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`);
|
|
75
|
+
fs.renameSync(tmp, file);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** 探索活动最多留这么多条:只是给人回看的日志,别把会话文件撑大 */
|
|
79
|
+
const MAX_ACTIVITY = 200;
|
|
80
|
+
|
|
81
|
+
const ACTIVITY_KINDS = new Set(['info', 'tool', 'error', 'shot']);
|
|
82
|
+
const ACTIVITY_STATUSES = new Set(['running', 'done', 'failed']);
|
|
83
|
+
|
|
84
|
+
/** 活动日志归一化:只留展示需要的字段,超长截断 */
|
|
85
|
+
export function normalizeActivity(raw) {
|
|
86
|
+
const list = Array.isArray(raw) ? raw.slice(-MAX_ACTIVITY) : [];
|
|
87
|
+
const items = [];
|
|
88
|
+
for (const item of list) {
|
|
89
|
+
if (!item || typeof item !== 'object') continue;
|
|
90
|
+
const name = String(item.name ?? '').slice(0, 120);
|
|
91
|
+
if (!name) continue;
|
|
92
|
+
items.push({
|
|
93
|
+
kind: ACTIVITY_KINDS.has(item.kind) ? item.kind : 'info',
|
|
94
|
+
name,
|
|
95
|
+
detail: String(item.detail ?? '').slice(0, 2000),
|
|
96
|
+
status: ACTIVITY_STATUSES.has(item.status) ? item.status : 'done',
|
|
97
|
+
at: String(item.at ?? '').slice(0, 40) || undefined,
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
return items;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* 活动日志按「只增不删」合并。
|
|
105
|
+
*
|
|
106
|
+
* 前端每次存的是整份列表,页面重载 / 状态没捞回来时可能只带着最后两三条,
|
|
107
|
+
* 直接覆盖会把上一轮的记录抹掉(用户要的就是能回看)。这里按
|
|
108
|
+
* at + name 去重,老记录顺序不动,新记录追加在后面;真要清空走 replaceActivity。
|
|
109
|
+
*/
|
|
110
|
+
export function mergeActivityLog(existing, incoming) {
|
|
111
|
+
const old = normalizeActivity(existing);
|
|
112
|
+
const next = normalizeActivity(incoming);
|
|
113
|
+
if (!old.length) return next;
|
|
114
|
+
if (!next.length) return old;
|
|
115
|
+
const seen = new Set(old.map((item) => `${item.at ?? ''}|${item.name}`));
|
|
116
|
+
const appended = next.filter((item) => {
|
|
117
|
+
const key = `${item.at ?? ''}|${item.name}`;
|
|
118
|
+
if (seen.has(key)) return false;
|
|
119
|
+
seen.add(key);
|
|
120
|
+
return true;
|
|
121
|
+
});
|
|
122
|
+
return normalizeActivity([...old, ...appended]);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** 新建 / 更新会话;不带 id 时新建 */
|
|
126
|
+
export function saveGeneratedSession(baseDir, rawPatch = {}) {
|
|
127
|
+
// 前端没传的字段不能把已有值覆盖成 undefined(JSON 里会直接消失)
|
|
128
|
+
const patch = {};
|
|
129
|
+
for (const [key, value] of Object.entries(rawPatch)) {
|
|
130
|
+
if (value !== undefined) patch[key] = value;
|
|
131
|
+
}
|
|
132
|
+
const id = String(patch.id || '').trim() || `gen_${crypto.randomBytes(8).toString('hex')}`;
|
|
133
|
+
const file = sessionFilePath(baseDir, id);
|
|
134
|
+
const existing = readJson(file) || {};
|
|
135
|
+
const now = new Date().toISOString();
|
|
136
|
+
// 显式传 ir: null 表示「清掉上一轮的步骤」,不能当成没传而把旧脚本留下来
|
|
137
|
+
const hasIr = Object.prototype.hasOwnProperty.call(patch, 'ir');
|
|
138
|
+
const ir = !hasIr
|
|
139
|
+
? existing.ir || null
|
|
140
|
+
: patch.ir
|
|
141
|
+
? normalizeIr(patch.ir, {
|
|
142
|
+
title: existing.title,
|
|
143
|
+
baseURL: existing.baseURL,
|
|
144
|
+
storageState: existing.storageState,
|
|
145
|
+
source: existing.source,
|
|
146
|
+
target: existing.target,
|
|
147
|
+
})
|
|
148
|
+
: null;
|
|
149
|
+
const record = {
|
|
150
|
+
...existing,
|
|
151
|
+
...patch,
|
|
152
|
+
id,
|
|
153
|
+
ir,
|
|
154
|
+
plan: patch.plan !== undefined ? normalizePlan(patch.plan) : existing.plan || [],
|
|
155
|
+
activity:
|
|
156
|
+
patch.activity !== undefined ? normalizeActivity(patch.activity) : existing.activity || [],
|
|
157
|
+
createdAt: existing.createdAt || now,
|
|
158
|
+
updatedAt: now,
|
|
159
|
+
};
|
|
160
|
+
delete record.shots;
|
|
161
|
+
writeJsonAtomic(file, record);
|
|
162
|
+
return record;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export function readGeneratedSession(baseDir, id) {
|
|
166
|
+
if (!id) return null;
|
|
167
|
+
const record = readJson(sessionFilePath(baseDir, id));
|
|
168
|
+
if (!record) return null;
|
|
169
|
+
// 同 listGeneratedSessions:进程已经没了,「探索中」按未完成的草稿展示
|
|
170
|
+
if (record.status === 'exploring' && !RUNNING.has(record.id)) record.status = 'draft';
|
|
171
|
+
return record;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function listGeneratedSessions(baseDir, projectId = '') {
|
|
175
|
+
const dir = sessionsDir(baseDir);
|
|
176
|
+
if (!fs.existsSync(dir)) return [];
|
|
177
|
+
const items = [];
|
|
178
|
+
for (const name of fs.readdirSync(dir)) {
|
|
179
|
+
if (!name.endsWith('.json')) continue;
|
|
180
|
+
const record = readJson(path.join(dir, name));
|
|
181
|
+
if (!record || !record.id) continue;
|
|
182
|
+
if (projectId && record.projectId !== projectId) continue;
|
|
183
|
+
// 服务重启后浏览器进程一定没了:还在「探索中」的会话其实是上次没收尾的,
|
|
184
|
+
// 不收敛的话页面会一直显示探索中、按钮也点不动。
|
|
185
|
+
// 只在内存里改状态,不回写文件也不动 updatedAt —— 否则这条「空会话」会
|
|
186
|
+
// 因为时间戳变新被当成最近一次会话恢复出来,把用户真正的计划顶掉
|
|
187
|
+
if (record.status === 'exploring' && !RUNNING.has(record.id)) {
|
|
188
|
+
record.status = 'draft';
|
|
189
|
+
}
|
|
190
|
+
items.push({
|
|
191
|
+
id: record.id,
|
|
192
|
+
projectId: record.projectId || '',
|
|
193
|
+
title: record.title || '未命名流程',
|
|
194
|
+
target: record.target === 'python' ? 'python' : 'ts',
|
|
195
|
+
status: record.status || 'draft',
|
|
196
|
+
stepCount: Array.isArray(record.ir?.steps) ? record.ir.steps.length : 0,
|
|
197
|
+
createdAt: record.createdAt || '',
|
|
198
|
+
updatedAt: record.updatedAt || '',
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
return items.sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : -1)).slice(0, 50);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export function deleteGeneratedSession(baseDir, id) {
|
|
205
|
+
if (!id) return false;
|
|
206
|
+
const file = sessionFilePath(baseDir, id);
|
|
207
|
+
if (!fs.existsSync(file)) return false;
|
|
208
|
+
fs.rmSync(file, { force: true });
|
|
209
|
+
fs.rmSync(path.join(sessionsDir(baseDir), id), { recursive: true, force: true });
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function respondError(entry, id, message) {
|
|
214
|
+
const pending = entry.pending.get(id);
|
|
215
|
+
if (!pending) return;
|
|
216
|
+
entry.pending.delete(id);
|
|
217
|
+
clearTimeout(pending.timer);
|
|
218
|
+
pending.reject(new Error(message));
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** 拉起浏览器子进程,等到 ready 再返回 */
|
|
222
|
+
export function startExplorer({ baseDir, project, sessionId, baseURL, headed, storageState }) {
|
|
223
|
+
const existing = RUNNING.get(sessionId);
|
|
224
|
+
if (existing) return Promise.resolve(existing);
|
|
225
|
+
|
|
226
|
+
const shots = sessionShotsDir(baseDir, sessionId);
|
|
227
|
+
fs.mkdirSync(shots, { recursive: true });
|
|
228
|
+
|
|
229
|
+
const payload = {
|
|
230
|
+
projectDir: project.dir,
|
|
231
|
+
shotDir: shots,
|
|
232
|
+
baseURL: baseURL || '',
|
|
233
|
+
headed: Boolean(headed),
|
|
234
|
+
storageState: storageState || '',
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
const child = spawn(process.execPath, [RUNNER_PATH, JSON.stringify(payload)], {
|
|
238
|
+
cwd: project.dir,
|
|
239
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
240
|
+
env: { ...process.env, FORCE_COLOR: '0', NO_COLOR: '1' },
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
const entry = {
|
|
244
|
+
id: sessionId,
|
|
245
|
+
child,
|
|
246
|
+
pending: new Map(),
|
|
247
|
+
seq: 0,
|
|
248
|
+
stderr: '',
|
|
249
|
+
shotsDir: shots,
|
|
250
|
+
};
|
|
251
|
+
RUNNING.set(sessionId, entry);
|
|
252
|
+
|
|
253
|
+
child.stderr?.setEncoding('utf8');
|
|
254
|
+
child.stderr?.on('data', (chunk) => {
|
|
255
|
+
entry.stderr = `${entry.stderr}${chunk}`.slice(-8000);
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
const ready = new Promise((resolve, reject) => {
|
|
259
|
+
const timer = setTimeout(() => {
|
|
260
|
+
reject(new Error('浏览器启动超时(45s)'));
|
|
261
|
+
}, 45000);
|
|
262
|
+
entry.readyTimer = timer;
|
|
263
|
+
entry.resolveReady = resolve;
|
|
264
|
+
entry.rejectReady = reject;
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
child.on('error', (err) => {
|
|
268
|
+
entry.rejectReady?.(err);
|
|
269
|
+
for (const [id] of entry.pending) respondError(entry, id, String(err));
|
|
270
|
+
RUNNING.delete(sessionId);
|
|
271
|
+
});
|
|
272
|
+
child.on('exit', (code) => {
|
|
273
|
+
clearTimeout(entry.readyTimer);
|
|
274
|
+
// 浏览器被用户关掉时子进程会紧跟着退出:这时已经按「用户关闭」处理过,
|
|
275
|
+
// 别再拿进程退出码覆盖掉更准确的原因
|
|
276
|
+
if (entry.closedByUser) {
|
|
277
|
+
RUNNING.delete(sessionId);
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
entry.rejectReady?.(new Error(`浏览器进程退出(code=${code ?? 'null'})`));
|
|
281
|
+
for (const [id] of entry.pending) {
|
|
282
|
+
respondError(entry, id, `浏览器进程已退出(code=${code ?? 'null'})`);
|
|
283
|
+
}
|
|
284
|
+
RUNNING.delete(sessionId);
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
readline.createInterface({ input: child.stdout }).on('line', (line) => {
|
|
288
|
+
const text = line.trim();
|
|
289
|
+
if (!text) return;
|
|
290
|
+
let message;
|
|
291
|
+
try {
|
|
292
|
+
message = JSON.parse(text);
|
|
293
|
+
} catch {
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
if (message.type === 'ready') {
|
|
297
|
+
clearTimeout(entry.readyTimer);
|
|
298
|
+
entry.resolveReady?.({ playwright: message.playwright });
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
if (message.type === 'fatal') {
|
|
302
|
+
clearTimeout(entry.readyTimer);
|
|
303
|
+
entry.rejectReady?.(new Error(message.error || '浏览器启动失败'));
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
if (message.type === 'closed') {
|
|
307
|
+
// 用户手动关掉了浏览器窗口:把这一轮的待办全部失败掉,
|
|
308
|
+
// 并通知上层(lh-uiauto)结束探索状态,别让会话一直挂着「探索中」。
|
|
309
|
+
entry.closedByUser = true;
|
|
310
|
+
clearTimeout(entry.readyTimer);
|
|
311
|
+
for (const [id] of entry.pending) {
|
|
312
|
+
respondError(entry, id, CLOSED_MESSAGE);
|
|
313
|
+
}
|
|
314
|
+
RUNNING.delete(sessionId);
|
|
315
|
+
for (const handler of closedHandlers) {
|
|
316
|
+
try {
|
|
317
|
+
handler({ sessionId, reason: message.reason || 'browser-closed' });
|
|
318
|
+
} catch {
|
|
319
|
+
// 通知失败不影响清理
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
const pending = entry.pending.get(message.id);
|
|
325
|
+
if (!pending) return;
|
|
326
|
+
entry.pending.delete(message.id);
|
|
327
|
+
clearTimeout(pending.timer);
|
|
328
|
+
if (message.ok) pending.resolve(message.result);
|
|
329
|
+
else pending.reject(new Error(message.error || '浏览器操作失败'));
|
|
330
|
+
});
|
|
331
|
+
|
|
332
|
+
return ready.then(() => entry);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
export function hasExplorer(sessionId) {
|
|
336
|
+
return RUNNING.has(sessionId);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
export function explorerStderr(sessionId) {
|
|
340
|
+
return RUNNING.get(sessionId)?.stderr ?? '';
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** 调一条浏览器命令 */
|
|
344
|
+
export function callExplorer(sessionId, cmd, args = {}, timeoutMs = 60000) {
|
|
345
|
+
const entry = RUNNING.get(sessionId);
|
|
346
|
+
// 浏览器已经被关掉(或这轮本来就没起):用统一文案让上层直接结束,而不是让模型重试
|
|
347
|
+
if (!entry) return Promise.reject(new Error(CLOSED_MESSAGE));
|
|
348
|
+
entry.seq += 1;
|
|
349
|
+
const id = entry.seq;
|
|
350
|
+
return new Promise((resolve, reject) => {
|
|
351
|
+
const timer = setTimeout(() => {
|
|
352
|
+
entry.pending.delete(id);
|
|
353
|
+
reject(new Error(`浏览器操作超时:${cmd}`));
|
|
354
|
+
}, timeoutMs);
|
|
355
|
+
entry.pending.set(id, { resolve, reject, timer });
|
|
356
|
+
entry.child.stdin.write(`${JSON.stringify({ id, cmd, args })}\n`);
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
export function stopExplorer(sessionId) {
|
|
361
|
+
const entry = RUNNING.get(sessionId);
|
|
362
|
+
if (!entry) return false;
|
|
363
|
+
RUNNING.delete(sessionId);
|
|
364
|
+
try {
|
|
365
|
+
entry.child.stdin.write(`${JSON.stringify({ id: -1, cmd: 'close', args: {} })}\n`);
|
|
366
|
+
} catch {
|
|
367
|
+
// ignore
|
|
368
|
+
}
|
|
369
|
+
setTimeout(() => {
|
|
370
|
+
try {
|
|
371
|
+
entry.child.kill('SIGTERM');
|
|
372
|
+
} catch {
|
|
373
|
+
// ignore
|
|
374
|
+
}
|
|
375
|
+
}, 1200).unref?.();
|
|
376
|
+
for (const [id] of entry.pending) respondError(entry, id, '会话已关闭');
|
|
377
|
+
return true;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
export function stopAllExplorers() {
|
|
381
|
+
for (const id of [...RUNNING.keys()]) stopExplorer(id);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/* ------------------------- 草稿工作区 ------------------------- */
|
|
385
|
+
|
|
386
|
+
const toPosix = (value) => String(value).split(path.sep).join('/');
|
|
387
|
+
|
|
388
|
+
export function aiRootDir(projectDir) {
|
|
389
|
+
return path.join(projectDir, '.lantern-ai');
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** 一个生成会话的草稿目录:配置 / 草稿 / 失败产物都在一起 */
|
|
393
|
+
export function draftPaths(projectDir, sessionId) {
|
|
394
|
+
const root = path.join(aiRootDir(projectDir), sessionId);
|
|
395
|
+
const draftDir = path.join(root, 'draft');
|
|
396
|
+
const resultsDir = path.join(root, 'results');
|
|
397
|
+
return {
|
|
398
|
+
root,
|
|
399
|
+
draftDir,
|
|
400
|
+
resultsDir,
|
|
401
|
+
configFile: path.join(root, 'playwright.config.ts'),
|
|
402
|
+
relRoot: toPosix(path.relative(projectDir, root)),
|
|
403
|
+
relDraftDir: toPosix(path.relative(projectDir, draftDir)),
|
|
404
|
+
relResultsDir: toPosix(path.relative(projectDir, resultsDir)),
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* 草稿目录自带 `.gitignore`,不污染项目仓库。
|
|
410
|
+
* 只写一次:用户如果自己改过就不要覆盖。
|
|
411
|
+
*/
|
|
412
|
+
function ensureAiRoot(projectDir) {
|
|
413
|
+
const root = aiRootDir(projectDir);
|
|
414
|
+
fs.mkdirSync(root, { recursive: true });
|
|
415
|
+
const ignore = path.join(root, '.gitignore');
|
|
416
|
+
if (!fs.existsSync(ignore)) {
|
|
417
|
+
fs.writeFileSync(ignore, '# Lantern AI 生成的草稿与试跑产物,整个目录忽略\n*\n');
|
|
418
|
+
}
|
|
419
|
+
return root;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** 删掉某个会话的草稿;清空后把 `.lantern-ai` 一起收掉 */
|
|
423
|
+
export function cleanupDraft(projectDir, sessionId) {
|
|
424
|
+
const paths = draftPaths(projectDir, sessionId);
|
|
425
|
+
fs.rmSync(paths.root, { recursive: true, force: true });
|
|
426
|
+
const root = aiRootDir(projectDir);
|
|
427
|
+
try {
|
|
428
|
+
const rest = fs.readdirSync(root).filter((name) => name !== '.gitignore');
|
|
429
|
+
if (!rest.length) fs.rmSync(root, { recursive: true, force: true });
|
|
430
|
+
} catch {
|
|
431
|
+
// 目录不在就算了
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/** 启动时顺手清理过期草稿:AI 中间产物留一周足够 */
|
|
436
|
+
export function cleanupStaleDrafts(projectDir) {
|
|
437
|
+
const root = aiRootDir(projectDir);
|
|
438
|
+
let names = [];
|
|
439
|
+
try {
|
|
440
|
+
names = fs.readdirSync(root, { withFileTypes: true });
|
|
441
|
+
} catch {
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
const now = Date.now();
|
|
445
|
+
for (const item of names) {
|
|
446
|
+
if (!item.isDirectory()) continue;
|
|
447
|
+
const abs = path.join(root, item.name);
|
|
448
|
+
try {
|
|
449
|
+
if (now - fs.statSync(abs).mtimeMs > DRAFT_TTL_MS) {
|
|
450
|
+
fs.rmSync(abs, { recursive: true, force: true });
|
|
451
|
+
}
|
|
452
|
+
} catch {
|
|
453
|
+
// 并发删除 / 权限问题直接跳过
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function readTextFile(file) {
|
|
459
|
+
try {
|
|
460
|
+
return fs.readFileSync(file, 'utf8');
|
|
461
|
+
} catch {
|
|
462
|
+
return '';
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* 从项目里推断被测应用的起始地址。
|
|
468
|
+
*
|
|
469
|
+
* 之前只用一个写死的 `http://localhost:5173`,项目 `.env` / playwright 配置里
|
|
470
|
+
* 明明写着 `BASE_URL=http://localhost:5173/admin` 也读不到,探索一开始就撞 404。
|
|
471
|
+
* 这里按优先级读:
|
|
472
|
+
* 1. playwright 配置里 `use.baseURL`(`process.env.X || '字面量'` 取字面量兜底值)
|
|
473
|
+
* 2. 项目根 `.env` / `.env.local` 的 `BASE_URL=`(被注释掉的行不算)
|
|
474
|
+
* 3. 项目内 `utils/config.ts` 之类文件里的同名兜底(只在没有 playwright 配置时兜一下)
|
|
475
|
+
* 路径后缀(如 /admin)属于项目自己的路由,能读到就是读到的那个;读不到由用户
|
|
476
|
+
* 在生成页改一次,之后按项目记住(见项目记录的 baseURL 字段)。
|
|
477
|
+
*/
|
|
478
|
+
export function detectBaseURL(projectDir) {
|
|
479
|
+
const read = (name) => readTextFile(path.join(projectDir, name));
|
|
480
|
+
|
|
481
|
+
// 1) playwright 配置:use.baseURL
|
|
482
|
+
const configName = findPlaywrightConfig(projectDir);
|
|
483
|
+
if (configName) {
|
|
484
|
+
const content = read(configName);
|
|
485
|
+
const fromConfig = pickBaseURLLiteral(content);
|
|
486
|
+
if (fromConfig) return fromConfig;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
// 2) 项目根的环境变量文件(只认 BASE_URL,忽略注释行)
|
|
490
|
+
for (const name of ['.env', '.env.local', '.env.development']) {
|
|
491
|
+
const content = read(name);
|
|
492
|
+
if (!content) continue;
|
|
493
|
+
for (const line of content.split(/\r?\n/)) {
|
|
494
|
+
const trimmed = line.trim();
|
|
495
|
+
if (!trimmed || trimmed.startsWith('#')) continue;
|
|
496
|
+
const match = /^BASE_URL\s*=\s*(.+)$/.exec(trimmed);
|
|
497
|
+
if (!match) continue;
|
|
498
|
+
const value = match[1].trim().replace(/^['"]|['"]$/g, '');
|
|
499
|
+
if (/^https?:\/\//i.test(value)) return value;
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
// 3) 最后兜一下 utils/config.* 之类的常量
|
|
504
|
+
for (const name of ['utils/config.ts', 'src/utils/config.ts', 'config/base.ts']) {
|
|
505
|
+
const content = read(name);
|
|
506
|
+
if (!content) continue;
|
|
507
|
+
const fromConfig = pickBaseURLLiteral(content);
|
|
508
|
+
if (fromConfig) return fromConfig;
|
|
509
|
+
}
|
|
510
|
+
return '';
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/** `baseURL: process.env.BASE_URL || 'http://x'` → `http://x`;直接写字面量也认 */
|
|
514
|
+
function pickBaseURLLiteral(content) {
|
|
515
|
+
const key = /baseURL\s*:/i.exec(content);
|
|
516
|
+
if (!key) return '';
|
|
517
|
+
const tail = content.slice(key.index, key.index + 400);
|
|
518
|
+
const urls = tail.match(/https?:\/\/[^\s'"`,)]+/g);
|
|
519
|
+
if (!urls || !urls.length) return '';
|
|
520
|
+
// `process.env.BASE_URL || 'http://localhost:5173'`:取第一个真实地址
|
|
521
|
+
return urls[0].replace(/\/+$/, '') || '';
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/** 登录态文件的常见命名,按目录顺序找第一个存在的 */
|
|
525
|
+
const STORAGE_STATE_NAMES = [
|
|
526
|
+
'auth-admin.json',
|
|
527
|
+
'auth-user.json',
|
|
528
|
+
'auth.json',
|
|
529
|
+
'storage-state.json',
|
|
530
|
+
'state.json',
|
|
531
|
+
];
|
|
532
|
+
|
|
533
|
+
const STORAGE_STATE_DIRS = [
|
|
534
|
+
'',
|
|
535
|
+
'.auth',
|
|
536
|
+
'auth',
|
|
537
|
+
'tests',
|
|
538
|
+
'tests/.auth',
|
|
539
|
+
'tests/fixtures',
|
|
540
|
+
'fixtures',
|
|
541
|
+
'e2e',
|
|
542
|
+
'e2e/.auth',
|
|
543
|
+
];
|
|
544
|
+
|
|
545
|
+
const toPosixRel = (value) => value.split(path.sep).join('/');
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* 项目里已有的登录态(相对项目根的 POSIX 路径,找不到返回空串)。
|
|
549
|
+
*
|
|
550
|
+
* 只做「看一眼」,不代表一定能用:cookie 可能已过期,真正加载前 runner 还会再校验文件存在。
|
|
551
|
+
* 探测顺序:playwright 配置里写死的 storageState → 常见命名 → `.auth/` 下的任意 json。
|
|
552
|
+
*/
|
|
553
|
+
export function detectStorageState(projectDir) {
|
|
554
|
+
const abs = (rel) => path.join(projectDir, rel);
|
|
555
|
+
const existsFile = (rel) => {
|
|
556
|
+
try {
|
|
557
|
+
return fs.statSync(abs(rel)).isFile();
|
|
558
|
+
} catch {
|
|
559
|
+
return false;
|
|
560
|
+
}
|
|
561
|
+
};
|
|
562
|
+
|
|
563
|
+
// 1) playwright 配置:use.storageState / 项目级 storageState
|
|
564
|
+
const configName = findPlaywrightConfig(projectDir);
|
|
565
|
+
if (configName) {
|
|
566
|
+
const fromConfig = pickStorageStateLiteral(readTextFile(path.join(projectDir, configName)));
|
|
567
|
+
// 配置里常写成相对配置文件 / 项目根的路径,两种都试一下;
|
|
568
|
+
// 越界(../)或绝对路径只做存在性判断没意义,直接忽略
|
|
569
|
+
for (const candidate of [fromConfig, fromConfig.replace(/^\.\//, '')]) {
|
|
570
|
+
if (!candidate || path.isAbsolute(candidate) || candidate.includes('..')) continue;
|
|
571
|
+
if (existsFile(candidate)) return toPosixRel(candidate);
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
// 2) 约定命名:项目根 / .auth / tests / fixtures
|
|
576
|
+
for (const dir of STORAGE_STATE_DIRS) {
|
|
577
|
+
for (const name of STORAGE_STATE_NAMES) {
|
|
578
|
+
const rel = dir ? path.join(dir, name) : name;
|
|
579
|
+
if (existsFile(rel)) return toPosixRel(rel);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
// 3) `.auth/` 里项目自己命名的 json(`auth.setup.ts` 存出来的那种)
|
|
584
|
+
for (const dir of ['.auth', 'auth']) {
|
|
585
|
+
try {
|
|
586
|
+
const files = fs
|
|
587
|
+
.readdirSync(abs(dir))
|
|
588
|
+
.filter((name) => /\.json$/i.test(name))
|
|
589
|
+
.sort();
|
|
590
|
+
if (files.length) return toPosixRel(path.join(dir, files[0]));
|
|
591
|
+
} catch {
|
|
592
|
+
// 没有这个目录就算了
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
return '';
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/** `storageState: './auth.json'` → `./auth.json`;模板字符串 / 变量一律不认 */
|
|
599
|
+
function pickStorageStateLiteral(content) {
|
|
600
|
+
const match = /storageState\s*:\s*(['"])([^'"]+)\1/.exec(String(content || ''));
|
|
601
|
+
return match ? match[2].trim() : '';
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/** 从 playwright 配置里读 testDir,读不到就用默认值 */
|
|
605
|
+
export function detectPlaywrightTestDir(projectDir) {
|
|
606
|
+
for (const name of [
|
|
607
|
+
'playwright.config.ts',
|
|
608
|
+
'playwright.config.js',
|
|
609
|
+
'playwright.config.mjs',
|
|
610
|
+
'playwright.config.mts',
|
|
611
|
+
'playwright.config.cts',
|
|
612
|
+
]) {
|
|
613
|
+
const file = path.join(projectDir, name);
|
|
614
|
+
if (!fs.existsSync(file)) continue;
|
|
615
|
+
const content = readTextFile(file);
|
|
616
|
+
const match = /testDir\s*:\s*['"`]([^'"`]+)['"`]/.exec(content);
|
|
617
|
+
if (match) return match[1].replace(/^\.\//, '');
|
|
618
|
+
return 'tests';
|
|
619
|
+
}
|
|
620
|
+
return 'tests';
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
export function findPlaywrightConfig(projectDir) {
|
|
624
|
+
for (const name of [
|
|
625
|
+
'playwright.config.ts',
|
|
626
|
+
'playwright.config.js',
|
|
627
|
+
'playwright.config.mjs',
|
|
628
|
+
'playwright.config.mts',
|
|
629
|
+
'playwright.config.cts',
|
|
630
|
+
]) {
|
|
631
|
+
if (fs.existsSync(path.join(projectDir, name))) return name;
|
|
632
|
+
}
|
|
633
|
+
return '';
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/**
|
|
637
|
+
* 草稿放在项目的 `projects[].testMatch` 之外时,Playwright 会直接「No tests found」。
|
|
638
|
+
* 所以试跑 / 调试用一份独立配置:继承用户配置(webServer / expect / retries 等),
|
|
639
|
+
* 只把 testDir 指向草稿目录、reporter 收成 line、projects 换成一个不设 testMatch 的项目。
|
|
640
|
+
*/
|
|
641
|
+
function writeDraftConfig({ projectDir, sessionId, baseConfig, storageState, baseURL }) {
|
|
642
|
+
const paths = draftPaths(projectDir, sessionId);
|
|
643
|
+
ensureAiRoot(projectDir);
|
|
644
|
+
fs.mkdirSync(paths.draftDir, { recursive: true });
|
|
645
|
+
fs.mkdirSync(paths.resultsDir, { recursive: true });
|
|
646
|
+
const rootRel = toPosix(path.relative(path.dirname(paths.configFile), projectDir));
|
|
647
|
+
const importer = baseConfig
|
|
648
|
+
? `import base from '${rootRel}/${baseConfig.replace(/\.(ts|js|mjs|mts|cts)$/, '')}';\n\n`
|
|
649
|
+
: '';
|
|
650
|
+
const useLines = [' ...(config.use ?? {}),'];
|
|
651
|
+
if (baseURL) useLines.push(` baseURL: ${JSON.stringify(baseURL)},`);
|
|
652
|
+
if (storageState) useLines.push(` storageState: ${JSON.stringify(storageState)},`);
|
|
653
|
+
// 失败时留下 trace:用户可以在面板里直接打开回放
|
|
654
|
+
useLines.push(" trace: 'retain-on-failure',");
|
|
655
|
+
const source =
|
|
656
|
+
`${importer}` +
|
|
657
|
+
'// 自动生成:AI 草稿的试跑 / 调试配置,不属于用户用例\n' +
|
|
658
|
+
`${baseConfig ? 'const config = base as any;\n' : 'const config = {} as any;\n'}\n` +
|
|
659
|
+
'export default {\n' +
|
|
660
|
+
' ...config,\n' +
|
|
661
|
+
" testDir: './draft',\n" +
|
|
662
|
+
" outputDir: './results',\n" +
|
|
663
|
+
" reporter: [['line']],\n" +
|
|
664
|
+
' use: {\n' +
|
|
665
|
+
`${useLines.join('\n')}\n` +
|
|
666
|
+
' },\n' +
|
|
667
|
+
" projects: [{ name: 'lantern-ai' }],\n" +
|
|
668
|
+
'};\n';
|
|
669
|
+
fs.writeFileSync(paths.configFile, source);
|
|
670
|
+
return paths;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
function findPlaywrightBin(projectDir) {
|
|
674
|
+
const names =
|
|
675
|
+
process.platform === 'win32'
|
|
676
|
+
? ['playwright.cmd', 'playwright']
|
|
677
|
+
: ['playwright', 'playwright.sh'];
|
|
678
|
+
for (const name of names) {
|
|
679
|
+
const bin = path.join(projectDir, 'node_modules', '.bin', name);
|
|
680
|
+
if (fs.existsSync(bin)) return bin;
|
|
681
|
+
}
|
|
682
|
+
return '';
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/** 项目自己的 playwright 可执行文件;没有就退回 `npx --no-install` */
|
|
686
|
+
function playwrightRunner(projectDir) {
|
|
687
|
+
const bin = findPlaywrightBin(projectDir);
|
|
688
|
+
if (bin) return { command: bin, prefix: [] };
|
|
689
|
+
return {
|
|
690
|
+
command: process.platform === 'win32' ? 'npx.cmd' : 'npx',
|
|
691
|
+
prefix: ['--no-install', 'playwright'],
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
function detectPython(projectDir) {
|
|
696
|
+
const candidates =
|
|
697
|
+
process.platform === 'win32'
|
|
698
|
+
? [path.join(projectDir, '.venv', 'Scripts', 'python.exe'), 'python', 'py']
|
|
699
|
+
: [path.join(projectDir, '.venv', 'bin', 'python'), 'python3', 'python'];
|
|
700
|
+
for (const candidate of candidates) {
|
|
701
|
+
if (candidate.includes(path.sep)) {
|
|
702
|
+
if (fs.existsSync(candidate)) return candidate;
|
|
703
|
+
continue;
|
|
704
|
+
}
|
|
705
|
+
return candidate;
|
|
706
|
+
}
|
|
707
|
+
return 'python3';
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
function runProcess({ command, args, cwd, env, timeoutMs }) {
|
|
711
|
+
return new Promise((resolve) => {
|
|
712
|
+
const startedAt = Date.now();
|
|
713
|
+
let output = '';
|
|
714
|
+
let timedOut = false;
|
|
715
|
+
let child;
|
|
716
|
+
try {
|
|
717
|
+
child = spawn(command, args, {
|
|
718
|
+
cwd,
|
|
719
|
+
env: { ...process.env, ...(env || {}), FORCE_COLOR: '0' },
|
|
720
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
721
|
+
});
|
|
722
|
+
} catch (err) {
|
|
723
|
+
resolve({
|
|
724
|
+
exitCode: -1,
|
|
725
|
+
output: `启动失败:${err instanceof Error ? err.message : String(err)}`,
|
|
726
|
+
durationMs: 0,
|
|
727
|
+
timedOut: false,
|
|
728
|
+
});
|
|
729
|
+
return;
|
|
730
|
+
}
|
|
731
|
+
const append = (chunk) => {
|
|
732
|
+
output += chunk;
|
|
733
|
+
if (output.length > MAX_VERIFY_LOG) output = output.slice(-MAX_VERIFY_LOG);
|
|
734
|
+
};
|
|
735
|
+
child.stdout?.setEncoding('utf8');
|
|
736
|
+
child.stderr?.setEncoding('utf8');
|
|
737
|
+
child.stdout?.on('data', append);
|
|
738
|
+
child.stderr?.on('data', append);
|
|
739
|
+
child.on('error', (err) => append(`\n[lantern] ${err.message}`));
|
|
740
|
+
const timer = setTimeout(() => {
|
|
741
|
+
timedOut = true;
|
|
742
|
+
try {
|
|
743
|
+
child.kill('SIGKILL');
|
|
744
|
+
} catch {
|
|
745
|
+
// ignore
|
|
746
|
+
}
|
|
747
|
+
}, timeoutMs);
|
|
748
|
+
child.on('close', (code) => {
|
|
749
|
+
clearTimeout(timer);
|
|
750
|
+
resolve({
|
|
751
|
+
exitCode: code ?? -1,
|
|
752
|
+
output,
|
|
753
|
+
durationMs: Date.now() - startedAt,
|
|
754
|
+
timedOut,
|
|
755
|
+
});
|
|
756
|
+
});
|
|
757
|
+
});
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/** 递归找最新一个 trace.zip,失败现场就在里面 */
|
|
761
|
+
function findTrace(resultsDir) {
|
|
762
|
+
let newest = null;
|
|
763
|
+
const walk = (dir, level) => {
|
|
764
|
+
if (level > 4) return;
|
|
765
|
+
let items = [];
|
|
766
|
+
try {
|
|
767
|
+
items = fs.readdirSync(dir, { withFileTypes: true });
|
|
768
|
+
} catch {
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
for (const item of items) {
|
|
772
|
+
const abs = path.join(dir, item.name);
|
|
773
|
+
if (item.isDirectory()) walk(abs, level + 1);
|
|
774
|
+
else if (item.name === 'trace.zip') {
|
|
775
|
+
try {
|
|
776
|
+
const mtime = fs.statSync(abs).mtimeMs;
|
|
777
|
+
if (!newest || mtime > newest.mtime) newest = { abs, mtime };
|
|
778
|
+
} catch {
|
|
779
|
+
// ignore
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
};
|
|
784
|
+
walk(resultsDir, 0);
|
|
785
|
+
return newest ? newest.abs : '';
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
/** 把 IR 渲染成草稿文件(不执行),试跑 / 调试 / 打开草稿都走这里 */
|
|
789
|
+
function prepareDraft({ project, session }) {
|
|
790
|
+
const ir = normalizeIr(session.ir || {}, {
|
|
791
|
+
target: session.target,
|
|
792
|
+
title: session.title,
|
|
793
|
+
baseURL: session.baseURL,
|
|
794
|
+
storageState: session.storageState,
|
|
795
|
+
source: session.source,
|
|
796
|
+
});
|
|
797
|
+
if (!ir.steps.length) return { error: '还没有生成步骤,无法试跑' };
|
|
798
|
+
const emitted = emitCode(ir, session.target);
|
|
799
|
+
const isPython = emitted.language === 'python';
|
|
800
|
+
const paths = draftPaths(project.dir, session.id);
|
|
801
|
+
ensureAiRoot(project.dir);
|
|
802
|
+
fs.mkdirSync(paths.draftDir, { recursive: true });
|
|
803
|
+
const draftFile = path.join(paths.draftDir, emitted.filename);
|
|
804
|
+
fs.writeFileSync(draftFile, emitted.code);
|
|
805
|
+
const relDraft = toPosix(path.relative(project.dir, draftFile));
|
|
806
|
+
|
|
807
|
+
let configRel = '';
|
|
808
|
+
if (!isPython) {
|
|
809
|
+
const storageStateAbs = session.storageState
|
|
810
|
+
? path.resolve(project.dir, session.storageState)
|
|
811
|
+
: '';
|
|
812
|
+
writeDraftConfig({
|
|
813
|
+
projectDir: project.dir,
|
|
814
|
+
sessionId: session.id,
|
|
815
|
+
baseConfig: findPlaywrightConfig(project.dir),
|
|
816
|
+
storageState: storageStateAbs && fs.existsSync(storageStateAbs) ? storageStateAbs : '',
|
|
817
|
+
baseURL: ir.baseURL,
|
|
818
|
+
});
|
|
819
|
+
configRel = toPosix(path.relative(project.dir, paths.configFile));
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
return {
|
|
823
|
+
ir,
|
|
824
|
+
emitted,
|
|
825
|
+
isPython,
|
|
826
|
+
paths,
|
|
827
|
+
draftFile,
|
|
828
|
+
relDraft,
|
|
829
|
+
configRel,
|
|
830
|
+
draftInfo: {
|
|
831
|
+
draftPath: relDraft,
|
|
832
|
+
configPath: configRel,
|
|
833
|
+
artifactDir: paths.relResultsDir,
|
|
834
|
+
draftRoot: paths.relRoot,
|
|
835
|
+
},
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
/** 面板需要的「草稿现状」:没跑过也要能显示路径与按钮可用性 */
|
|
840
|
+
export function draftSummary({ project, session }) {
|
|
841
|
+
const paths = draftPaths(project.dir, session.id);
|
|
842
|
+
const hasSteps = Array.isArray(session.ir?.steps) && session.ir.steps.length > 0;
|
|
843
|
+
const traceAbs = fs.existsSync(paths.resultsDir) ? findTrace(paths.resultsDir) : '';
|
|
844
|
+
return {
|
|
845
|
+
draftRoot: paths.relRoot,
|
|
846
|
+
draftDir: paths.relDraftDir,
|
|
847
|
+
artifactDir: paths.relResultsDir,
|
|
848
|
+
configPath: toPosix(path.relative(project.dir, paths.configFile)),
|
|
849
|
+
exists: fs.existsSync(paths.root),
|
|
850
|
+
hasSteps,
|
|
851
|
+
tracePath: traceAbs ? toPosix(path.relative(project.dir, traceAbs)) : '',
|
|
852
|
+
};
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
function tailLog(output, lines = 120) {
|
|
856
|
+
const clean = stripAnsi(output);
|
|
857
|
+
return clean
|
|
858
|
+
.split(/\r?\n/)
|
|
859
|
+
.filter((line) => line.trim())
|
|
860
|
+
.slice(-lines)
|
|
861
|
+
.join('\n')
|
|
862
|
+
.slice(-12000);
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
/**
|
|
866
|
+
* 试跑:草稿写到 `.lantern-ai/<会话>/draft/`,**跑完不删**。
|
|
867
|
+
* 失败现场要能打开看、能重跑、能回放 trace;正式文件只在用户确认后写。
|
|
868
|
+
*/
|
|
869
|
+
export async function verifySession({ project, session, timeoutMs = DEFAULT_VERIFY_TIMEOUT }) {
|
|
870
|
+
const prepared = prepareDraft({ project, session });
|
|
871
|
+
if (prepared.error) return { ok: false, passed: false, error: prepared.error };
|
|
872
|
+
const { isPython, paths, relDraft, configRel, draftInfo, emitted } = prepared;
|
|
873
|
+
|
|
874
|
+
let command;
|
|
875
|
+
let args;
|
|
876
|
+
if (isPython) {
|
|
877
|
+
command = detectPython(project.dir);
|
|
878
|
+
args = ['-m', 'pytest', relDraft, '-q'];
|
|
879
|
+
} else {
|
|
880
|
+
const runner = playwrightRunner(project.dir);
|
|
881
|
+
command = runner.command;
|
|
882
|
+
args = [
|
|
883
|
+
...runner.prefix,
|
|
884
|
+
'test',
|
|
885
|
+
'--config',
|
|
886
|
+
configRel,
|
|
887
|
+
'--reporter=line',
|
|
888
|
+
'--workers=1',
|
|
889
|
+
'--timeout=30000',
|
|
890
|
+
];
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
const result = await runProcess({
|
|
894
|
+
command,
|
|
895
|
+
args,
|
|
896
|
+
cwd: project.dir,
|
|
897
|
+
timeoutMs,
|
|
898
|
+
env: { PLAYWRIGHT_HTML_OPEN: 'never', LANTERN_AI_DRAFT: '1' },
|
|
899
|
+
});
|
|
900
|
+
|
|
901
|
+
const traceAbs = isPython ? '' : findTrace(paths.resultsDir);
|
|
902
|
+
return {
|
|
903
|
+
ok: true,
|
|
904
|
+
passed: result.exitCode === 0,
|
|
905
|
+
exitCode: result.exitCode,
|
|
906
|
+
timedOut: result.timedOut,
|
|
907
|
+
durationMs: result.durationMs,
|
|
908
|
+
command: [command, ...args].join(' '),
|
|
909
|
+
code: emitted.code,
|
|
910
|
+
log: tailLog(result.output),
|
|
911
|
+
...draftInfo,
|
|
912
|
+
tracePath: traceAbs ? toPosix(path.relative(project.dir, traceAbs)) : '',
|
|
913
|
+
};
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
/* ---------------------------- 调试 ---------------------------- */
|
|
917
|
+
|
|
918
|
+
/** sessionId → { child, port };Playwright UI 是长驻进程,必须能停 */
|
|
919
|
+
const DEBUG_RUNNING = new Map();
|
|
920
|
+
|
|
921
|
+
function findFreePort() {
|
|
922
|
+
return new Promise((resolve) => {
|
|
923
|
+
const server = net.createServer();
|
|
924
|
+
server.once('error', () => resolve(0));
|
|
925
|
+
server.listen(0, '127.0.0.1', () => {
|
|
926
|
+
const address = server.address();
|
|
927
|
+
const port = address && typeof address === 'object' ? address.port : 0;
|
|
928
|
+
server.close(() => resolve(port));
|
|
929
|
+
});
|
|
930
|
+
});
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
function waitForPort(port, timeoutMs = 20000) {
|
|
934
|
+
const startedAt = Date.now();
|
|
935
|
+
return new Promise((resolve) => {
|
|
936
|
+
const tryOnce = () => {
|
|
937
|
+
const socket = net.connect({ port, host: '127.0.0.1' });
|
|
938
|
+
socket.setTimeout(800);
|
|
939
|
+
socket.once('connect', () => {
|
|
940
|
+
socket.destroy();
|
|
941
|
+
resolve(true);
|
|
942
|
+
});
|
|
943
|
+
const retry = () => {
|
|
944
|
+
socket.destroy();
|
|
945
|
+
if (Date.now() - startedAt > timeoutMs) resolve(false);
|
|
946
|
+
else setTimeout(tryOnce, 300).unref?.();
|
|
947
|
+
};
|
|
948
|
+
socket.once('error', retry);
|
|
949
|
+
socket.once('timeout', retry);
|
|
950
|
+
};
|
|
951
|
+
tryOnce();
|
|
952
|
+
});
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
/**
|
|
956
|
+
* 调试:`headed` 跑一遍并保留 trace;`ui` 拉起 Playwright UI(长驻,可停止)。
|
|
957
|
+
*/
|
|
958
|
+
export async function debugSession({ project, session, mode = 'headed' }) {
|
|
959
|
+
if (session.target === 'python') {
|
|
960
|
+
return {
|
|
961
|
+
ok: false,
|
|
962
|
+
error: 'Python 草稿没有 Playwright UI,可用「调试运行」在终端看输出,或直接打开草稿文件',
|
|
963
|
+
};
|
|
964
|
+
}
|
|
965
|
+
const prepared = prepareDraft({ project, session });
|
|
966
|
+
if (prepared.error) return { ok: false, error: prepared.error };
|
|
967
|
+
stopDebugSession(session.id);
|
|
968
|
+
const runner = playwrightRunner(project.dir);
|
|
969
|
+
const baseArgs = [
|
|
970
|
+
...runner.prefix,
|
|
971
|
+
'test',
|
|
972
|
+
'--config',
|
|
973
|
+
prepared.configRel,
|
|
974
|
+
'--workers=1',
|
|
975
|
+
'--timeout=30000',
|
|
976
|
+
];
|
|
977
|
+
|
|
978
|
+
if (mode === 'ui') {
|
|
979
|
+
const port = (await findFreePort()) || 0;
|
|
980
|
+
let child;
|
|
981
|
+
try {
|
|
982
|
+
child = spawn(runner.command, [...baseArgs, '--ui', `--ui-port=${port}`], {
|
|
983
|
+
cwd: project.dir,
|
|
984
|
+
env: { ...process.env, FORCE_COLOR: '0', PLAYWRIGHT_HTML_OPEN: 'never' },
|
|
985
|
+
stdio: 'ignore',
|
|
986
|
+
detached: false,
|
|
987
|
+
});
|
|
988
|
+
} catch (err) {
|
|
989
|
+
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
|
990
|
+
}
|
|
991
|
+
child.on('exit', () => DEBUG_RUNNING.delete(session.id));
|
|
992
|
+
DEBUG_RUNNING.set(session.id, { child, port });
|
|
993
|
+
const ready = port ? await waitForPort(port) : false;
|
|
994
|
+
return {
|
|
995
|
+
ok: true,
|
|
996
|
+
mode: 'ui',
|
|
997
|
+
url: `http://127.0.0.1:${port}`,
|
|
998
|
+
ready,
|
|
999
|
+
...prepared.draftInfo,
|
|
1000
|
+
note: ready ? 'Playwright UI 已启动' : 'UI 启动较慢,稍后再点一次「打开 Playwright UI」',
|
|
1001
|
+
};
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
const result = await runProcess({
|
|
1005
|
+
command: runner.command,
|
|
1006
|
+
args: [...baseArgs, '--headed', '--trace=on', '--reporter=line'],
|
|
1007
|
+
cwd: project.dir,
|
|
1008
|
+
timeoutMs: DEFAULT_VERIFY_TIMEOUT,
|
|
1009
|
+
env: { PLAYWRIGHT_HTML_OPEN: 'never', LANTERN_AI_DRAFT: '1' },
|
|
1010
|
+
});
|
|
1011
|
+
const traceAbs = findTrace(prepared.paths.resultsDir);
|
|
1012
|
+
return {
|
|
1013
|
+
ok: true,
|
|
1014
|
+
mode: 'headed',
|
|
1015
|
+
passed: result.exitCode === 0,
|
|
1016
|
+
exitCode: result.exitCode,
|
|
1017
|
+
timedOut: result.timedOut,
|
|
1018
|
+
durationMs: result.durationMs,
|
|
1019
|
+
command: [runner.command, ...baseArgs, '--headed', '--trace=on'].join(' '),
|
|
1020
|
+
log: tailLog(result.output),
|
|
1021
|
+
...prepared.draftInfo,
|
|
1022
|
+
tracePath: traceAbs ? toPosix(path.relative(project.dir, traceAbs)) : '',
|
|
1023
|
+
};
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
export function stopDebugSession(sessionId) {
|
|
1027
|
+
const entry = DEBUG_RUNNING.get(sessionId);
|
|
1028
|
+
if (!entry) return false;
|
|
1029
|
+
DEBUG_RUNNING.delete(sessionId);
|
|
1030
|
+
try {
|
|
1031
|
+
entry.child.kill('SIGTERM');
|
|
1032
|
+
} catch {
|
|
1033
|
+
// ignore
|
|
1034
|
+
}
|
|
1035
|
+
return true;
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
export function hasDebugSession(sessionId) {
|
|
1039
|
+
return DEBUG_RUNNING.has(sessionId);
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
export function stopAllDebugSessions() {
|
|
1043
|
+
for (const id of [...DEBUG_RUNNING.keys()]) stopDebugSession(id);
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
/**
|
|
1047
|
+
* 用项目自带的 `playwright show-trace` 打开 trace。
|
|
1048
|
+
* 直接 open 一个 zip 只会进解压软件,看不到回放。
|
|
1049
|
+
*/
|
|
1050
|
+
export function showTrace({ project, relPath }) {
|
|
1051
|
+
const target = String(relPath || '')
|
|
1052
|
+
.replace(/\\/g, '/')
|
|
1053
|
+
.replace(/^\.?\//, '')
|
|
1054
|
+
.trim();
|
|
1055
|
+
if (!target || target.includes('..') || path.isAbsolute(target)) {
|
|
1056
|
+
return { ok: false, error: 'trace 路径不合法' };
|
|
1057
|
+
}
|
|
1058
|
+
const abs = path.join(project.dir, target);
|
|
1059
|
+
const root = project.dir.endsWith(path.sep) ? project.dir : `${project.dir}${path.sep}`;
|
|
1060
|
+
if (!abs.startsWith(root) || !fs.existsSync(abs)) {
|
|
1061
|
+
return { ok: false, error: 'trace 还不存在,先试跑或调试运行一次' };
|
|
1062
|
+
}
|
|
1063
|
+
const runner = playwrightRunner(project.dir);
|
|
1064
|
+
try {
|
|
1065
|
+
const child = spawn(runner.command, [...runner.prefix, 'show-trace', abs], {
|
|
1066
|
+
cwd: project.dir,
|
|
1067
|
+
detached: true,
|
|
1068
|
+
stdio: 'ignore',
|
|
1069
|
+
env: { ...process.env, FORCE_COLOR: '0' },
|
|
1070
|
+
});
|
|
1071
|
+
child.unref();
|
|
1072
|
+
return { ok: true, path: target, kind: 'trace' };
|
|
1073
|
+
} catch (err) {
|
|
1074
|
+
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
/* ------------------------- 写入与验收 ------------------------- */
|
|
1079
|
+
|
|
1080
|
+
/** 归一化写入路径:去掉前导 ./ 与多余斜杠,拒绝跳出项目目录 */
|
|
1081
|
+
function normalizeRelPath(raw) {
|
|
1082
|
+
return String(raw ?? '')
|
|
1083
|
+
.replace(/\\/g, '/')
|
|
1084
|
+
.replace(/^\.?\//, '')
|
|
1085
|
+
.replace(/\/+/g, '/')
|
|
1086
|
+
.trim();
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
/** 单个路径的安全校验:非法时返回错误文案 */
|
|
1090
|
+
function checkRelPath(project, target) {
|
|
1091
|
+
if (!target || target.includes('..') || path.isAbsolute(target)) return '文件路径不合法';
|
|
1092
|
+
const abs = path.join(project.dir, target);
|
|
1093
|
+
const root = project.dir.endsWith(path.sep) ? project.dir : `${project.dir}${path.sep}`;
|
|
1094
|
+
if (!abs.startsWith(root)) return '只能写到项目目录内';
|
|
1095
|
+
return '';
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
/**
|
|
1099
|
+
* 一次写多个文件(一条用例可能同时动 spec / page object / fixture)。
|
|
1100
|
+
*
|
|
1101
|
+
* 先全量预检再写盘:只要有一个冲突就整批不写,避免「写了一半」的半成品。
|
|
1102
|
+
* 写盘中途异常时用账本里的 before 回滚已经写过的文件。
|
|
1103
|
+
*/
|
|
1104
|
+
export function writeGeneratedFiles(params) {
|
|
1105
|
+
const { project, files, session = null, force = false } = params;
|
|
1106
|
+
const list = Array.isArray(files) ? files.filter(Boolean) : [];
|
|
1107
|
+
if (!list.length) return { ok: false, error: '没有要写入的文件' };
|
|
1108
|
+
|
|
1109
|
+
const prepared = [];
|
|
1110
|
+
const conflicts = [];
|
|
1111
|
+
const seen = new Set();
|
|
1112
|
+
for (const item of list) {
|
|
1113
|
+
const target = normalizeRelPath(item.path);
|
|
1114
|
+
const bad = checkRelPath(project, target);
|
|
1115
|
+
if (bad) return { ok: false, error: `${bad}:${item.path ?? ''}` };
|
|
1116
|
+
if (seen.has(target)) continue;
|
|
1117
|
+
seen.add(target);
|
|
1118
|
+
const abs = path.join(project.dir, target);
|
|
1119
|
+
const existed = fs.existsSync(abs);
|
|
1120
|
+
const role = item.role ? String(item.role) : '';
|
|
1121
|
+
let content = String(item.content ?? '');
|
|
1122
|
+
let mergeMode = '';
|
|
1123
|
+
if (existed && !force && !item.force) {
|
|
1124
|
+
// 默认合并:已有文件保留,只把这次生成的用例 / 方法补进去。
|
|
1125
|
+
// 合并不了(类名对不上等)才退回冲突,让用户显式勾选覆盖。
|
|
1126
|
+
const merged = mergeGeneratedFile(fs.readFileSync(abs, 'utf8'), content, {
|
|
1127
|
+
role,
|
|
1128
|
+
path: target,
|
|
1129
|
+
});
|
|
1130
|
+
if (!merged) {
|
|
1131
|
+
conflicts.push({ path: target, exists: true });
|
|
1132
|
+
continue;
|
|
1133
|
+
}
|
|
1134
|
+
content = merged.content;
|
|
1135
|
+
mergeMode = merged.unchanged ? 'unchanged' : 'merge';
|
|
1136
|
+
}
|
|
1137
|
+
prepared.push({
|
|
1138
|
+
path: target,
|
|
1139
|
+
content,
|
|
1140
|
+
existed,
|
|
1141
|
+
role,
|
|
1142
|
+
mergeMode,
|
|
1143
|
+
});
|
|
1144
|
+
}
|
|
1145
|
+
if (conflicts.length) {
|
|
1146
|
+
return {
|
|
1147
|
+
ok: false,
|
|
1148
|
+
error: '目标文件已存在且无法合并,勾选覆盖后再写入',
|
|
1149
|
+
conflicts,
|
|
1150
|
+
files: [],
|
|
1151
|
+
changes: Array.isArray(session?.changes) ? session.changes : [],
|
|
1152
|
+
};
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
const written = [];
|
|
1156
|
+
const changes = Array.isArray(session?.changes) ? session.changes.slice() : [];
|
|
1157
|
+
try {
|
|
1158
|
+
for (const item of prepared) {
|
|
1159
|
+
const abs = path.join(project.dir, item.path);
|
|
1160
|
+
const before = item.existed ? readTextFile(abs) : '';
|
|
1161
|
+
// 内容和原文件一样(用例已经写过了)就别碰文件,也不进账本
|
|
1162
|
+
if (item.mergeMode === 'unchanged' || (item.existed && before === item.content)) {
|
|
1163
|
+
written.push({ path: item.path, kind: 'unchanged', role: item.role || '' });
|
|
1164
|
+
continue;
|
|
1165
|
+
}
|
|
1166
|
+
fs.mkdirSync(path.dirname(abs), { recursive: true });
|
|
1167
|
+
fs.writeFileSync(abs, item.content);
|
|
1168
|
+
const change = {
|
|
1169
|
+
path: item.path,
|
|
1170
|
+
kind: item.existed ? (item.mergeMode === 'merge' ? 'merge' : 'update') : 'create',
|
|
1171
|
+
role: item.role || undefined,
|
|
1172
|
+
at: new Date().toISOString(),
|
|
1173
|
+
before: before.slice(0, MAX_LEDGER_FILE_BYTES),
|
|
1174
|
+
after: item.content.slice(0, MAX_LEDGER_FILE_BYTES),
|
|
1175
|
+
...summarizeDiff(before, item.content),
|
|
1176
|
+
};
|
|
1177
|
+
const index = changes.findIndex((entry) => entry.path === item.path);
|
|
1178
|
+
if (index >= 0) changes[index] = change;
|
|
1179
|
+
else changes.push(change);
|
|
1180
|
+
written.push({ path: item.path, kind: change.kind, role: item.role || '' });
|
|
1181
|
+
}
|
|
1182
|
+
} catch (err) {
|
|
1183
|
+
// 回滚:只回滚已经写过的,新建的删掉、改过的写回原内容
|
|
1184
|
+
for (const item of written) {
|
|
1185
|
+
const abs = path.join(project.dir, item.path);
|
|
1186
|
+
try {
|
|
1187
|
+
if (item.kind === 'create') fs.rmSync(abs, { force: true });
|
|
1188
|
+
else {
|
|
1189
|
+
const ledger = changes.find((entry) => entry.path === item.path);
|
|
1190
|
+
fs.writeFileSync(abs, String(ledger?.before ?? ''));
|
|
1191
|
+
}
|
|
1192
|
+
} catch {
|
|
1193
|
+
/* 回滚失败也继续,最后把原始错误抛给用户 */
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
const summary = written.reduce(
|
|
1200
|
+
(acc, item) => {
|
|
1201
|
+
if (item.kind === 'create') acc.created += 1;
|
|
1202
|
+
else if (item.kind === 'merge') acc.merged += 1;
|
|
1203
|
+
else if (item.kind === 'unchanged') acc.unchanged += 1;
|
|
1204
|
+
else acc.updated += 1;
|
|
1205
|
+
return acc;
|
|
1206
|
+
},
|
|
1207
|
+
{ created: 0, merged: 0, updated: 0, unchanged: 0 },
|
|
1208
|
+
);
|
|
1209
|
+
|
|
1210
|
+
return {
|
|
1211
|
+
ok: true,
|
|
1212
|
+
files: written,
|
|
1213
|
+
paths: written.map((item) => item.path),
|
|
1214
|
+
summary,
|
|
1215
|
+
changes,
|
|
1216
|
+
};
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
/** 写进项目(用户确认后才调用);返回 before/after 供「变更」面板出 diff */
|
|
1220
|
+
export function writeGeneratedFile({ project, session, relPath, force = false }) {
|
|
1221
|
+
const ir = normalizeIr(session.ir || {}, { target: session.target, title: session.title });
|
|
1222
|
+
if (!ir.steps.length) return { ok: false, error: '还没有生成步骤' };
|
|
1223
|
+
const emitted = emitCode(ir, session.target);
|
|
1224
|
+
const testDir = detectPlaywrightTestDir(project.dir);
|
|
1225
|
+
const fallback = `${testDir}/${emitted.filename}`;
|
|
1226
|
+
const result = writeGeneratedFiles({
|
|
1227
|
+
project,
|
|
1228
|
+
session,
|
|
1229
|
+
force,
|
|
1230
|
+
files: [{ path: relPath || fallback, content: emitted.code, role: 'spec' }],
|
|
1231
|
+
});
|
|
1232
|
+
if (!result.ok) return result;
|
|
1233
|
+
const change = result.changes.find((item) => item.path === result.paths[0]);
|
|
1234
|
+
return {
|
|
1235
|
+
ok: true,
|
|
1236
|
+
path: result.paths[0],
|
|
1237
|
+
code: emitted.code,
|
|
1238
|
+
filename: emitted.filename,
|
|
1239
|
+
change,
|
|
1240
|
+
changes: result.changes,
|
|
1241
|
+
};
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
/** 会话里的变更账本 → 带 hunk 的 diff,前端直接渲染 */
|
|
1245
|
+
export function sessionChanges(session) {
|
|
1246
|
+
const ledger = Array.isArray(session.changes) ? session.changes : [];
|
|
1247
|
+
return ledger.map((item) => {
|
|
1248
|
+
const before = String(item.before ?? '');
|
|
1249
|
+
const after = String(item.after ?? '');
|
|
1250
|
+
// 只回传 diff,不回传整份文件内容(账本里的 before/after 只用于重算)
|
|
1251
|
+
const { before: _before, after: _after, ...rest } = item;
|
|
1252
|
+
return { ...rest, ...diffText(before, after) };
|
|
1253
|
+
});
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
/**
|
|
1257
|
+
* 写入后用项目真实配置再跑一遍:这才是「这条用例在项目里真的能跑」。
|
|
1258
|
+
* 若文件被项目 testMatch 排除,Playwright 会报 No tests found,这里单独标出来。
|
|
1259
|
+
*/
|
|
1260
|
+
export async function runProjectFile({
|
|
1261
|
+
project,
|
|
1262
|
+
session,
|
|
1263
|
+
relPath,
|
|
1264
|
+
timeoutMs = DEFAULT_VERIFY_TIMEOUT,
|
|
1265
|
+
}) {
|
|
1266
|
+
const target = String(relPath || session.savedPath || '')
|
|
1267
|
+
.replace(/\\/g, '/')
|
|
1268
|
+
.replace(/^\.?\//, '')
|
|
1269
|
+
.trim();
|
|
1270
|
+
if (!target || target.includes('..') || path.isAbsolute(target)) {
|
|
1271
|
+
return { ok: false, error: '文件路径不合法' };
|
|
1272
|
+
}
|
|
1273
|
+
const abs = path.join(project.dir, target);
|
|
1274
|
+
const root = project.dir.endsWith(path.sep) ? project.dir : `${project.dir}${path.sep}`;
|
|
1275
|
+
if (!abs.startsWith(root) || !fs.existsSync(abs)) {
|
|
1276
|
+
return { ok: false, error: '文件还没写入项目,先点「写入项目」' };
|
|
1277
|
+
}
|
|
1278
|
+
const isPython = /\.py$/i.test(target);
|
|
1279
|
+
let command;
|
|
1280
|
+
let args;
|
|
1281
|
+
if (isPython) {
|
|
1282
|
+
command = detectPython(project.dir);
|
|
1283
|
+
args = ['-m', 'pytest', target, '-q'];
|
|
1284
|
+
} else {
|
|
1285
|
+
const runner = playwrightRunner(project.dir);
|
|
1286
|
+
command = runner.command;
|
|
1287
|
+
args = [...runner.prefix, 'test', target, '--reporter=line', '--workers=1'];
|
|
1288
|
+
}
|
|
1289
|
+
const result = await runProcess({
|
|
1290
|
+
command,
|
|
1291
|
+
args,
|
|
1292
|
+
cwd: project.dir,
|
|
1293
|
+
timeoutMs,
|
|
1294
|
+
env: { PLAYWRIGHT_HTML_OPEN: 'never' },
|
|
1295
|
+
});
|
|
1296
|
+
const log = tailLog(result.output);
|
|
1297
|
+
const excluded = /No tests found/i.test(log);
|
|
1298
|
+
return {
|
|
1299
|
+
ok: true,
|
|
1300
|
+
checked: true,
|
|
1301
|
+
passed: result.exitCode === 0 && !excluded,
|
|
1302
|
+
excluded,
|
|
1303
|
+
exitCode: result.exitCode,
|
|
1304
|
+
timedOut: result.timedOut,
|
|
1305
|
+
durationMs: result.durationMs,
|
|
1306
|
+
command: [command, ...args].join(' '),
|
|
1307
|
+
path: target,
|
|
1308
|
+
log,
|
|
1309
|
+
note: excluded
|
|
1310
|
+
? '项目配置的 testMatch 不包含这个文件,Playwright 没把它当成用例;换个路径或者在项目配置里放开'
|
|
1311
|
+
: '',
|
|
1312
|
+
};
|
|
1313
|
+
}
|
|
1314
|
+
|
|
1315
|
+
/* --------------------------- git 摘要 --------------------------- */
|
|
1316
|
+
|
|
1317
|
+
const GIT_IGNORE_HINTS = [
|
|
1318
|
+
'.lantern-ai/',
|
|
1319
|
+
'node_modules/',
|
|
1320
|
+
'test-results/',
|
|
1321
|
+
'playwright-report/',
|
|
1322
|
+
'reports/',
|
|
1323
|
+
'dist/',
|
|
1324
|
+
'.next/',
|
|
1325
|
+
'__pycache__/',
|
|
1326
|
+
'.venv/',
|
|
1327
|
+
];
|
|
1328
|
+
|
|
1329
|
+
function git(args, cwd, timeout = 2000) {
|
|
1330
|
+
return new Promise((resolve) => {
|
|
1331
|
+
execFile('git', args, { cwd, timeout, maxBuffer: 512 * 1024 }, (err, stdout) => {
|
|
1332
|
+
if (err) resolve('');
|
|
1333
|
+
else resolve(String(stdout ?? ''));
|
|
1334
|
+
});
|
|
1335
|
+
});
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
/**
|
|
1339
|
+
* 只读的 git 工作区摘要:展示「除了本次 AI 写入,项目里还有哪些改动」。
|
|
1340
|
+
* 拿不到 git 就返回空,不让它影响主流程。
|
|
1341
|
+
*/
|
|
1342
|
+
export async function gitStatusSummary(projectDir) {
|
|
1343
|
+
const inside = (await git(['rev-parse', '--is-inside-work-tree'], projectDir)).trim();
|
|
1344
|
+
if (inside !== 'true') return { ok: false, entries: [], truncated: false };
|
|
1345
|
+
const raw = await git(['status', '--porcelain=v1', '--untracked-files=normal'], projectDir);
|
|
1346
|
+
const lines = raw.split(/\r?\n/).filter((line) => line.trim());
|
|
1347
|
+
const entries = [];
|
|
1348
|
+
let filtered = 0;
|
|
1349
|
+
for (const line of lines) {
|
|
1350
|
+
const code = line.slice(0, 2).trim() || '??';
|
|
1351
|
+
const file = line.slice(3).replace(/^"|"$/g, '');
|
|
1352
|
+
if (GIT_IGNORE_HINTS.some((hint) => file.includes(hint))) {
|
|
1353
|
+
filtered += 1;
|
|
1354
|
+
continue;
|
|
1355
|
+
}
|
|
1356
|
+
entries.push({ code, path: file });
|
|
1357
|
+
if (entries.length >= 40) break;
|
|
1358
|
+
}
|
|
1359
|
+
return {
|
|
1360
|
+
ok: true,
|
|
1361
|
+
entries,
|
|
1362
|
+
truncated: lines.length > entries.length + filtered,
|
|
1363
|
+
filtered,
|
|
1364
|
+
};
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1367
|
+
export function suggestedPath({ project, session }) {
|
|
1368
|
+
const ir = normalizeIr(session.ir || {}, { target: session.target, title: session.title });
|
|
1369
|
+
const emitted = emitCode(ir, session.target);
|
|
1370
|
+
return `${detectPlaywrightTestDir(project.dir)}/${emitted.filename}`;
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
export { slugify };
|