lantern-harness 0.1.9 → 0.1.11
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 +90 -0
- package/README.md +6 -6
- package/builtin/session/lh-fs.mjs +32 -14
- package/dist/500.html +258 -22
- package/dist/_astro/Base.Bgxs1QQl.css +1 -0
- package/dist/_astro/Base.astro_astro_type_script_index_0_lang.CvbRi7Tl.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.CVB5Gtk4.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.CtF8vsag.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 +373 -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
package/lh-plugins/lh-uiauto.mjs
CHANGED
|
@@ -3,17 +3,22 @@
|
|
|
3
3
|
*
|
|
4
4
|
* 数据落在:
|
|
5
5
|
* ```
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
6
|
+
* <当前数据空间>/自动化测试/
|
|
7
|
+
* 自动化测试.json # { version, projects, runs }
|
|
8
|
+
* <项目名>/
|
|
9
|
+
* 报告/<runId>/ # 运行结束后快照过来的 HTML 报告
|
|
10
|
+
* 结果/<runId>.json|xml # Playwright JSON / JUnit XML 原始结果
|
|
11
|
+
* 日志/<runId>.log # 原始 stdout / stderr
|
|
11
12
|
* ```
|
|
13
|
+
* 本机数据(应用图标缓存、生成会话与截图)不进内容目录,落在
|
|
14
|
+
* `<当前数据空间>/.lantern/local/uiauto/{app-icons,sessions}/`。
|
|
15
|
+
* 旧版本的 `UI自动化/` 目录在首次访问时自动改名迁移,不需要重开插件开关。
|
|
12
16
|
*
|
|
13
17
|
* 约束:
|
|
14
18
|
* - 不自动安装依赖、不联网:只用项目自己的 `node_modules/.bin/playwright`,
|
|
15
19
|
* 退而求其次 `npx --no-install playwright`;找不到就报「未安装」。
|
|
16
|
-
* -
|
|
20
|
+
* - 常规运行 / 浏览是只读的;只有 AI 生成(`/agent/*`)会在用户确认后写文件:
|
|
21
|
+
* 试跑草稿写进测试目录并立刻删除,最终脚本由用户点「写入项目」才落盘。
|
|
17
22
|
* - 同一项目同时只允许一个 run,全局最多 2 个。
|
|
18
23
|
*/
|
|
19
24
|
import crypto from 'node:crypto';
|
|
@@ -22,12 +27,77 @@ import path from 'node:path';
|
|
|
22
27
|
import { spawn } from 'node:child_process';
|
|
23
28
|
import { fileURLToPath } from 'node:url';
|
|
24
29
|
|
|
25
|
-
import {
|
|
30
|
+
import { pickDirectoryResult } from '../builtin/session/lh-fs.mjs';
|
|
26
31
|
import { getDataRoot } from '../builtin/session/space-context.mjs';
|
|
27
|
-
import { resolveContentRoot } from '../builtin/session/space-layout.mjs';
|
|
32
|
+
import { resolveContentRoot, spaceLocalDir } from '../builtin/session/space-layout.mjs';
|
|
33
|
+
import { ensurePluginPrompt, pluginPromptPath, readPluginPrompt } from './plugin-prompts.mjs';
|
|
34
|
+
import {
|
|
35
|
+
parseUiAutoPrompt,
|
|
36
|
+
UI_AUTO_PROMPT_FILE,
|
|
37
|
+
UI_AUTO_PROMPT_TEMPLATE,
|
|
38
|
+
} from './uiauto-prompt.mjs';
|
|
39
|
+
import {
|
|
40
|
+
ADAPTER_IDS,
|
|
41
|
+
adapterOptions,
|
|
42
|
+
buildProbe,
|
|
43
|
+
detectCandidates,
|
|
44
|
+
getAdapter,
|
|
45
|
+
MIN_DETECT_SCORE,
|
|
46
|
+
} from './uiauto-adapters/index.mjs';
|
|
47
|
+
import { buildPlaywrightArgs, parsePlaywrightReport } from './uiauto-adapters/playwright.mjs';
|
|
48
|
+
import { emptySummary, intOr, text } from './uiauto-adapters/shared.mjs';
|
|
49
|
+
import {
|
|
50
|
+
customToTasks,
|
|
51
|
+
detectPythonCommand,
|
|
52
|
+
discoverRunTasks,
|
|
53
|
+
applyTaskOverrides,
|
|
54
|
+
normalizeCustomTasks,
|
|
55
|
+
normalizeHiddenTaskIds,
|
|
56
|
+
normalizeTaskOverrides,
|
|
57
|
+
taskCommandLine,
|
|
58
|
+
taskView,
|
|
59
|
+
} from './uiauto-adapters/tasks.mjs';
|
|
60
|
+
import { hasReportEntry, snapshotReport } from './uiauto-report.mjs';
|
|
61
|
+
import {
|
|
62
|
+
callExplorer,
|
|
63
|
+
cleanupDraft,
|
|
64
|
+
cleanupStaleDrafts,
|
|
65
|
+
debugSession,
|
|
66
|
+
detectBaseURL,
|
|
67
|
+
detectStorageState,
|
|
68
|
+
detectPlaywrightTestDir,
|
|
69
|
+
draftSummary,
|
|
70
|
+
gitStatusSummary,
|
|
71
|
+
hasDebugSession,
|
|
72
|
+
hasExplorer,
|
|
73
|
+
listGeneratedSessions,
|
|
74
|
+
onExplorerClosed,
|
|
75
|
+
readGeneratedSession,
|
|
76
|
+
runProjectFile,
|
|
77
|
+
saveGeneratedSession,
|
|
78
|
+
sessionChanges,
|
|
79
|
+
sessionShotsDir,
|
|
80
|
+
sessionsDir,
|
|
81
|
+
SESSIONS_DIR_NAME,
|
|
82
|
+
showTrace,
|
|
83
|
+
startExplorer,
|
|
84
|
+
stopAllDebugSessions,
|
|
85
|
+
stopAllExplorers,
|
|
86
|
+
stopDebugSession,
|
|
87
|
+
stopExplorer,
|
|
88
|
+
suggestedPath,
|
|
89
|
+
verifySession,
|
|
90
|
+
writeGeneratedFiles,
|
|
91
|
+
findPlaywrightConfig,
|
|
92
|
+
mergeActivityLog,
|
|
93
|
+
} from './uiauto-explorer/sessions.mjs';
|
|
94
|
+
import { emitCode } from './uiauto-explorer/emit.mjs';
|
|
95
|
+
import { emitFiles } from './uiauto-explorer/emit-files.mjs';
|
|
96
|
+
import { appIcon, defaultOpenApp, listOpenApps, openWith } from './uiauto-explorer/apps.mjs';
|
|
97
|
+
import { bindPlanStep, mergePlanWithModel } from './uiauto-explorer/plan.mjs';
|
|
28
98
|
|
|
29
99
|
const PREFIX = '/__tb_uiauto';
|
|
30
|
-
const VERSION =
|
|
100
|
+
const VERSION = 2;
|
|
31
101
|
|
|
32
102
|
/** 预加载守卫:给 Playwright 的 `--project` 参数让路(见文件内注释) */
|
|
33
103
|
const ARGV_GUARD_PATH = path.join(
|
|
@@ -35,33 +105,30 @@ const ARGV_GUARD_PATH = path.join(
|
|
|
35
105
|
'uiauto-argv-guard.cjs',
|
|
36
106
|
);
|
|
37
107
|
|
|
38
|
-
export
|
|
39
|
-
|
|
108
|
+
export { buildPlaywrightArgs, parsePlaywrightReport };
|
|
109
|
+
|
|
110
|
+
export const UIAUTO_DIR_NAME = '自动化测试';
|
|
111
|
+
export const UIAUTO_STORE_FILE = '自动化测试.json';
|
|
112
|
+
/** 0.1.9 及之前的目录 / 文件名,读取时自动迁移 */
|
|
113
|
+
export const LEGACY_DIR_NAME = 'UI自动化';
|
|
114
|
+
export const LEGACY_STORE_FILE = 'UI自动化.json';
|
|
40
115
|
export const REPORT_DIR_NAME = '报告';
|
|
41
116
|
export const RESULT_DIR_NAME = '结果';
|
|
42
117
|
export const LOG_DIR_NAME = '日志';
|
|
43
118
|
|
|
44
119
|
export const MAX_CONCURRENT_RUNS = 2;
|
|
45
|
-
export const MAX_TREE_ITEMS = 2000;
|
|
46
120
|
export const MAX_PREVIEW_BYTES = 256 * 1024;
|
|
47
|
-
const MAX_JSON_BYTES = 32 * 1024 * 1024;
|
|
48
121
|
const MAX_RAW_LOG_BYTES = 4 * 1024 * 1024;
|
|
49
122
|
const MAX_BODY_BYTES = 1024 * 1024;
|
|
50
123
|
const STOP_GRACE_MS = 5000;
|
|
51
124
|
|
|
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
125
|
/** 目录树里一律不展开的目录名(构建产物 / 依赖 / 测试输出) */
|
|
60
126
|
export const TREE_IGNORED_NAMES = new Set([
|
|
61
127
|
'node_modules',
|
|
62
128
|
'.git',
|
|
63
129
|
'.svn',
|
|
64
130
|
'.hg',
|
|
131
|
+
'.lantern-ai',
|
|
65
132
|
'test-results',
|
|
66
133
|
'playwright-report',
|
|
67
134
|
'blob-report',
|
|
@@ -120,16 +187,6 @@ function readBodyLimited(req) {
|
|
|
120
187
|
});
|
|
121
188
|
}
|
|
122
189
|
|
|
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
190
|
/** 绝对路径是否在 base 内(base 自身也算内) */
|
|
134
191
|
export function isPathInside(base, target) {
|
|
135
192
|
const root = path.resolve(base);
|
|
@@ -160,15 +217,145 @@ function toPosixRel(base, abs) {
|
|
|
160
217
|
return path.relative(base, abs).split(path.sep).join('/');
|
|
161
218
|
}
|
|
162
219
|
|
|
220
|
+
/** 把旧目录里的内容搬到新目录(跨卷 / 目标已存在时逐个搬,不覆盖) */
|
|
221
|
+
function migrateLegacyDir(legacy, target) {
|
|
222
|
+
if (!legacy || !target || legacy === target || !fs.existsSync(legacy)) return;
|
|
223
|
+
if (!fs.existsSync(target)) {
|
|
224
|
+
try {
|
|
225
|
+
fs.renameSync(legacy, target);
|
|
226
|
+
return;
|
|
227
|
+
} catch {
|
|
228
|
+
// 跨卷等情况:走逐个搬迁
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
try {
|
|
232
|
+
fs.mkdirSync(target, { recursive: true });
|
|
233
|
+
for (const name of fs.readdirSync(legacy)) {
|
|
234
|
+
const from = path.join(legacy, name);
|
|
235
|
+
const to = path.join(target, name);
|
|
236
|
+
if (fs.existsSync(to)) continue;
|
|
237
|
+
try {
|
|
238
|
+
fs.renameSync(from, to);
|
|
239
|
+
} catch {
|
|
240
|
+
// 单个条目失败不影响其它条目
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
if (fs.readdirSync(legacy).length === 0) fs.rmdirSync(legacy);
|
|
244
|
+
} catch {
|
|
245
|
+
// 迁移失败就继续用旧目录,不阻塞使用
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
163
249
|
function storeDir(root) {
|
|
164
|
-
|
|
250
|
+
const target = resolveContentRoot(root, UIAUTO_DIR_NAME).abs;
|
|
251
|
+
const legacy = resolveContentRoot(root, LEGACY_DIR_NAME).abs;
|
|
252
|
+
if (legacy === target) return target;
|
|
253
|
+
if (!fs.existsSync(legacy)) return target;
|
|
254
|
+
if (fs.existsSync(target)) {
|
|
255
|
+
migrateLegacyDir(legacy, target);
|
|
256
|
+
return target;
|
|
257
|
+
}
|
|
258
|
+
// 旧目录可能已经被分组(<组>/UI自动化):在原位改名,别把它搬出分组
|
|
259
|
+
const sibling = path.join(path.dirname(legacy), UIAUTO_DIR_NAME);
|
|
260
|
+
migrateLegacyDir(legacy, sibling);
|
|
261
|
+
if (fs.existsSync(sibling)) return sibling;
|
|
262
|
+
migrateLegacyDir(legacy, target);
|
|
263
|
+
return target;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** 数据文件:优先新名字,旧文件存在时顺手改名(改不动就继续读写旧的) */
|
|
267
|
+
function storeFilePath(dir) {
|
|
268
|
+
const next = path.join(dir, UIAUTO_STORE_FILE);
|
|
269
|
+
const legacy = path.join(dir, LEGACY_STORE_FILE);
|
|
270
|
+
if (!fs.existsSync(next) && fs.existsSync(legacy)) {
|
|
271
|
+
try {
|
|
272
|
+
fs.renameSync(legacy, next);
|
|
273
|
+
} catch {
|
|
274
|
+
return legacy;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
return next;
|
|
165
278
|
}
|
|
166
279
|
|
|
167
280
|
export function uiautoStorePaths(root) {
|
|
168
281
|
const dir = storeDir(root);
|
|
282
|
+
return { dir, store: storeFilePath(dir) };
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** 本机缓存目录(不进空间内容池):`<空间>/.lantern/local/uiauto` */
|
|
286
|
+
export const UIAUTO_CACHE_DIR_NAME = 'uiauto';
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* 应用图标、生成会话这类只对本机有意义、体积还不小的数据放本机缓存目录,
|
|
290
|
+
* 不混在 `自动化测试/` 的项目目录里。旧版本把这些放在内容目录,首次访问时搬过来。
|
|
291
|
+
*/
|
|
292
|
+
export function uiautoCachePaths(root) {
|
|
293
|
+
const dir = path.join(spaceLocalDir(path.resolve(root)), UIAUTO_CACHE_DIR_NAME);
|
|
294
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
295
|
+
const store = storeDir(root);
|
|
296
|
+
for (const name of ['app-icons', SESSIONS_DIR_NAME]) {
|
|
297
|
+
migrateLegacyDir(path.join(store, name), path.join(dir, name));
|
|
298
|
+
}
|
|
169
299
|
return {
|
|
170
300
|
dir,
|
|
171
|
-
|
|
301
|
+
appIcons: path.join(dir, 'app-icons'),
|
|
302
|
+
sessions: path.join(dir, SESSIONS_DIR_NAME),
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* 只接受「提示词管理」根目录下的 .md 文件名(可带一层分组目录)。
|
|
308
|
+
* 提示词下拉会把项目选中的文件名带回来,这里挡住 ../ 之类的越界读取。
|
|
309
|
+
*/
|
|
310
|
+
export function isPromptFileName(name) {
|
|
311
|
+
const value = String(name ?? '')
|
|
312
|
+
.trim()
|
|
313
|
+
.replace(/\\/g, '/');
|
|
314
|
+
if (!value || value.length > 200) return false;
|
|
315
|
+
if (value.startsWith('/') || value.includes('..')) return false;
|
|
316
|
+
if (!/\.md$/i.test(value)) return false;
|
|
317
|
+
return value.split('/').every((part) => part && part !== '.' && part !== '..');
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** 项目名 → 目录名(去掉路径分隔符等非法字符,保持可读) */ export function sanitizeFolderName(
|
|
321
|
+
name,
|
|
322
|
+
) {
|
|
323
|
+
const base = String(name ?? '')
|
|
324
|
+
.replace(/[\\/:*?"<>|\u0000-\u001f]/g, ' ')
|
|
325
|
+
.replace(/\s+/g, ' ')
|
|
326
|
+
.trim()
|
|
327
|
+
.replace(/^\.+/, '')
|
|
328
|
+
.slice(0, 60);
|
|
329
|
+
return base || '项目';
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** 同名项目自动加 id 后缀,避免两个项目写进同一个目录 */
|
|
333
|
+
export function uniqueFolder(store, name, id) {
|
|
334
|
+
const base = sanitizeFolderName(name);
|
|
335
|
+
const used = new Set((store?.projects ?? []).map((project) => project.folder).filter(Boolean));
|
|
336
|
+
if (!used.has(base)) return base;
|
|
337
|
+
const suffix = String(id ?? '').slice(-6) || crypto.randomBytes(3).toString('hex');
|
|
338
|
+
let candidate = `${base}-${suffix}`;
|
|
339
|
+
let index = 2;
|
|
340
|
+
while (used.has(candidate)) {
|
|
341
|
+
candidate = `${base}-${suffix}-${index}`;
|
|
342
|
+
index += 1;
|
|
343
|
+
}
|
|
344
|
+
return candidate;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** 项目在空间里的存放目录:自动化测试/<项目名>/{报告,结果,日志} */
|
|
348
|
+
export function projectPaths(root, project) {
|
|
349
|
+
const base = uiautoStorePaths(root);
|
|
350
|
+
const raw = project?.folder ? String(project.folder) : '';
|
|
351
|
+
const folder =
|
|
352
|
+
raw && !/[\\/]/.test(raw) && raw !== '.' && raw !== '..'
|
|
353
|
+
? raw
|
|
354
|
+
: sanitizeFolderName(project?.name || project?.id || '项目');
|
|
355
|
+
const dir = path.join(base.dir, folder);
|
|
356
|
+
return {
|
|
357
|
+
dir,
|
|
358
|
+
folder,
|
|
172
359
|
reportDir: path.join(dir, REPORT_DIR_NAME),
|
|
173
360
|
resultDir: path.join(dir, RESULT_DIR_NAME),
|
|
174
361
|
logDir: path.join(dir, LOG_DIR_NAME),
|
|
@@ -183,14 +370,32 @@ function normalizeProject(raw) {
|
|
|
183
370
|
if (!raw || typeof raw !== 'object') return null;
|
|
184
371
|
const dir = text(raw.dir, 4096);
|
|
185
372
|
if (!dir) return null;
|
|
373
|
+
const name = text(raw.name, 200) || path.basename(dir);
|
|
186
374
|
return {
|
|
187
375
|
id: text(raw.id, 64) || `uia_${crypto.randomBytes(8).toString('hex')}`,
|
|
188
|
-
name
|
|
376
|
+
name,
|
|
377
|
+
// 存放目录在创建时定下,之后改项目名也不换目录(历史报告路径不失效)
|
|
378
|
+
folder: text(raw.folder, 100) || sanitizeFolderName(name),
|
|
189
379
|
dir,
|
|
380
|
+
// 老数据没有 framework:一律按 Playwright 处理,不做批量迁移
|
|
381
|
+
framework: ADAPTER_IDS.includes(raw.framework) ? raw.framework : 'playwright',
|
|
190
382
|
createdAt: text(raw.createdAt, 40) || new Date().toISOString(),
|
|
191
383
|
lastRunId: text(raw.lastRunId, 64),
|
|
192
384
|
lastRunAt: text(raw.lastRunAt, 40),
|
|
193
385
|
lastStatus: RUN_STATUSES.includes(raw.lastStatus) ? raw.lastStatus : '',
|
|
386
|
+
// 用户自己添加的运行命令(存在项目记录里,跟着空间走)
|
|
387
|
+
customTasks: normalizeCustomTasks(raw.customTasks),
|
|
388
|
+
// 对自动发现任务的改动 / 删除:只存差异,扫描结果变了也不影响
|
|
389
|
+
taskOverrides: normalizeTaskOverrides(raw.taskOverrides),
|
|
390
|
+
hiddenTasks: normalizeHiddenTaskIds(raw.hiddenTasks),
|
|
391
|
+
// 被测应用起始地址(含 /admin 这类路由后缀):用户改过一次就按项目记住,
|
|
392
|
+
// 下次进生成页自动带出来;留空时读项目自己的 playwright 配置 / .env
|
|
393
|
+
baseURL: text(raw.baseURL, 500),
|
|
394
|
+
// 该项目的登录态文件(相对项目根):按项目记,换项目不会串味;
|
|
395
|
+
// 留空时自动探测项目里的 auth*.json / .auth/ 等
|
|
396
|
+
storageState: text(raw.storageState, 300),
|
|
397
|
+
// 该项目用哪份提示词(提示词管理里的文件名):不同框架可以挂不同提示词
|
|
398
|
+
promptFile: text(raw.promptFile, 200),
|
|
194
399
|
};
|
|
195
400
|
}
|
|
196
401
|
|
|
@@ -203,6 +408,7 @@ function normalizeRun(raw) {
|
|
|
203
408
|
return {
|
|
204
409
|
id,
|
|
205
410
|
projectId,
|
|
411
|
+
framework: ADAPTER_IDS.includes(raw.framework) ? raw.framework : 'playwright',
|
|
206
412
|
startedAt: text(raw.startedAt, 40),
|
|
207
413
|
finishedAt: text(raw.finishedAt, 40),
|
|
208
414
|
status,
|
|
@@ -214,6 +420,10 @@ function normalizeRun(raw) {
|
|
|
214
420
|
skipped: intOr(raw.skipped, 0, 0, 1_000_000),
|
|
215
421
|
flaky: intOr(raw.flaky, 0, 0, 1_000_000),
|
|
216
422
|
args: normalizeRunArgs(raw.args),
|
|
423
|
+
// 这一次实际执行的命令行(任务运行才有),历史里直接显示
|
|
424
|
+
command: text(raw.command, 1000),
|
|
425
|
+
taskId: text(raw.taskId, 64),
|
|
426
|
+
taskLabel: text(raw.taskLabel, 200),
|
|
217
427
|
projectNames: Array.isArray(raw.projectNames)
|
|
218
428
|
? raw.projectNames
|
|
219
429
|
.map((name) => text(name, 100))
|
|
@@ -237,6 +447,11 @@ function normalizeRunArgs(raw) {
|
|
|
237
447
|
headed: source.headed === true,
|
|
238
448
|
workers: intOr(source.workers, 0, 0, 32),
|
|
239
449
|
lastFailed: source.lastFailed === true,
|
|
450
|
+
// 遇到第一个失败就停(Playwright --max-failures=1 / pytest -x)
|
|
451
|
+
bail: source.bail === true,
|
|
452
|
+
// pytest 专属:-m 标记表达式与 --maxfail
|
|
453
|
+
marker: text(source.marker, 200),
|
|
454
|
+
maxFail: intOr(source.maxFail, 0, 0, 10_000),
|
|
240
455
|
};
|
|
241
456
|
}
|
|
242
457
|
|
|
@@ -258,12 +473,86 @@ function readStore(root) {
|
|
|
258
473
|
} catch {
|
|
259
474
|
store = emptyStore();
|
|
260
475
|
}
|
|
261
|
-
|
|
476
|
+
const result = reconcileStore(store, root);
|
|
477
|
+
// 迁移 / 收敛会改记录:立刻写回,避免文件已搬走而记录还指向旧路径
|
|
478
|
+
if (result.dirty) {
|
|
479
|
+
try {
|
|
480
|
+
writeStore(root, store);
|
|
481
|
+
} catch {
|
|
482
|
+
// 写失败不影响本次读取
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
return result;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/**
|
|
489
|
+
* 0.1.9 的运行产物平铺在 `报告/<runId>`、`结果/…`、`日志/…`;
|
|
490
|
+
* 新版改成按项目分目录。读取时顺手搬过去,老记录的报告链接不会失效。
|
|
491
|
+
*/
|
|
492
|
+
function migrateLegacyRunArtifacts(root, store) {
|
|
493
|
+
const paths = uiautoStorePaths(root);
|
|
494
|
+
const dirs = new Set([REPORT_DIR_NAME, RESULT_DIR_NAME, LOG_DIR_NAME]);
|
|
495
|
+
let changed = false;
|
|
496
|
+
const move = (fromAbs, toAbs) => {
|
|
497
|
+
if (fs.existsSync(toAbs)) return true;
|
|
498
|
+
try {
|
|
499
|
+
fs.mkdirSync(path.dirname(toAbs), { recursive: true });
|
|
500
|
+
fs.renameSync(fromAbs, toAbs);
|
|
501
|
+
return true;
|
|
502
|
+
} catch {
|
|
503
|
+
return false;
|
|
504
|
+
}
|
|
505
|
+
};
|
|
506
|
+
|
|
507
|
+
for (const run of store.runs) {
|
|
508
|
+
const project = findProject(store, run.projectId);
|
|
509
|
+
if (!project) continue;
|
|
510
|
+
const pp = projectPaths(root, project);
|
|
511
|
+
for (const key of ['reportRel', 'resultRel', 'logRel']) {
|
|
512
|
+
const rel = run[key];
|
|
513
|
+
if (!rel) continue;
|
|
514
|
+
const abs = path.join(paths.dir, rel);
|
|
515
|
+
if (!isPathInside(paths.dir, abs)) continue;
|
|
516
|
+
const parts = path.relative(paths.dir, abs).split(path.sep);
|
|
517
|
+
if (parts[0] === pp.folder) continue; // 已经在项目目录里
|
|
518
|
+
const nextAbs = path.join(pp.dir, ...parts);
|
|
519
|
+
if (!fs.existsSync(abs)) {
|
|
520
|
+
// 文件可能已经搬走但记录没来得及写回:按新位置修正记录
|
|
521
|
+
if (fs.existsSync(nextAbs)) {
|
|
522
|
+
run[key] = toPosixRel(paths.dir, nextAbs);
|
|
523
|
+
changed = true;
|
|
524
|
+
}
|
|
525
|
+
continue;
|
|
526
|
+
}
|
|
527
|
+
if (!dirs.has(parts[0])) continue;
|
|
528
|
+
if (!move(abs, nextAbs)) continue;
|
|
529
|
+
run[key] = toPosixRel(paths.dir, nextAbs);
|
|
530
|
+
changed = true;
|
|
531
|
+
// surefire 结果目录跟着走,避免留下孤儿目录
|
|
532
|
+
if (key === 'resultRel') {
|
|
533
|
+
const oldSf = path.join(path.dirname(abs), `${run.id}-surefire`);
|
|
534
|
+
if (fs.existsSync(oldSf)) {
|
|
535
|
+
move(oldSf, path.join(path.dirname(nextAbs), `${run.id}-surefire`));
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
// 平铺的旧目录不管有没有搬东西,空了就删掉(0.1.9 每次运行都会预建这三个目录)
|
|
541
|
+
for (const name of dirs) {
|
|
542
|
+
const abs = path.join(paths.dir, name);
|
|
543
|
+
try {
|
|
544
|
+
if (fs.statSync(abs).isDirectory() && fs.readdirSync(abs).length === 0) fs.rmdirSync(abs);
|
|
545
|
+
} catch {
|
|
546
|
+
// ignore
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
return changed;
|
|
262
550
|
}
|
|
263
551
|
|
|
264
552
|
/** 服务重启后内存里没有对应进程的 running,一定是上次异常退出留下的 */
|
|
265
|
-
function reconcileStore(store) {
|
|
553
|
+
function reconcileStore(store, root) {
|
|
266
554
|
let dirty = false;
|
|
555
|
+
if (root && migrateLegacyRunArtifacts(root, store)) dirty = true;
|
|
267
556
|
for (const run of store.runs) {
|
|
268
557
|
if (run.status !== 'running' || RUNNING.has(run.id)) continue;
|
|
269
558
|
run.status = 'interrupted';
|
|
@@ -295,66 +584,139 @@ function findRun(store, runId) {
|
|
|
295
584
|
return store.runs.find((r) => r.id === runId) ?? null;
|
|
296
585
|
}
|
|
297
586
|
|
|
298
|
-
/**
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
587
|
+
/**
|
|
588
|
+
* 运行方式:同一批测试项目跑法不一样(Playwright CLI / pytest / Maven / Gradle / npm test),
|
|
589
|
+
* 页面上直接展示这条,不用让人猜「运行」会执行什么。
|
|
590
|
+
*/
|
|
591
|
+
function runnerLabel(probe, picked) {
|
|
592
|
+
if (!picked) return '';
|
|
593
|
+
if (picked.id === 'playwright') return 'Playwright Test';
|
|
594
|
+
// 用真实的解释器路径,和「运行任务」下拉里的命令保持一致
|
|
595
|
+
if (picked.id === 'pytest') return detectPythonCommand(probe.dir);
|
|
596
|
+
if (picked.id === 'selenium') {
|
|
597
|
+
if (probe.hasPom) return 'Maven · mvn test';
|
|
598
|
+
if (probe.hasGradle) return 'Gradle · gradle test';
|
|
599
|
+
if (probe.pkg) return 'npm test';
|
|
305
600
|
}
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
const
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
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
|
-
}
|
|
601
|
+
return picked.label;
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/** 目录状态:是否存在、识别成哪个框架、能不能跑 */
|
|
605
|
+
export function detectProject(dir, frameworkId = '') {
|
|
606
|
+
const probe = buildProbe(dir);
|
|
607
|
+
if (!probe.exists) {
|
|
608
|
+
return {
|
|
609
|
+
exists: false,
|
|
610
|
+
framework: frameworkId,
|
|
611
|
+
frameworkLabel: '',
|
|
612
|
+
kind: '',
|
|
613
|
+
runner: '',
|
|
614
|
+
candidates: [],
|
|
615
|
+
controls: [],
|
|
616
|
+
specFiles: [],
|
|
617
|
+
frameworkReady: false,
|
|
618
|
+
readyHint: '',
|
|
619
|
+
mountable: false,
|
|
620
|
+
packageManager: '',
|
|
621
|
+
};
|
|
333
622
|
}
|
|
334
|
-
const
|
|
335
|
-
|
|
336
|
-
);
|
|
623
|
+
const candidates = detectCandidates(probe);
|
|
624
|
+
const forced = frameworkId && ADAPTER_IDS.includes(frameworkId) ? frameworkId : '';
|
|
625
|
+
const forcedAdapter = forced ? getAdapter(forced) : null;
|
|
626
|
+
const matched = forced ? candidates.find((item) => item.id === forced) : null;
|
|
627
|
+
const picked = forced
|
|
628
|
+
? (matched ?? {
|
|
629
|
+
id: forced,
|
|
630
|
+
label: forcedAdapter?.label ?? forced,
|
|
631
|
+
kind: forcedAdapter?.kind ?? '',
|
|
632
|
+
score: 0,
|
|
633
|
+
evidence: [],
|
|
634
|
+
controls: forcedAdapter?.controls ?? [],
|
|
635
|
+
ready: Boolean(forcedAdapter?.ready?.(probe)),
|
|
636
|
+
})
|
|
637
|
+
: candidates[0];
|
|
638
|
+
const adapter = picked ? getAdapter(picked.id) : null;
|
|
337
639
|
return {
|
|
338
|
-
exists,
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
640
|
+
exists: true,
|
|
641
|
+
framework: picked?.id ?? '',
|
|
642
|
+
frameworkLabel: picked?.label ?? '',
|
|
643
|
+
kind: picked?.kind ?? '',
|
|
644
|
+
runner: runnerLabel(probe, picked),
|
|
645
|
+
controls: picked?.controls ?? [],
|
|
646
|
+
frameworkReady: picked ? picked.ready : false,
|
|
647
|
+
readyHint: adapter ? text(adapter.readyHint?.(probe), 500) : '',
|
|
648
|
+
candidates,
|
|
649
|
+
packageManager: probe.packageManager,
|
|
650
|
+
// 手动指定框架时以「能不能跑」为准,避免用户改选后立刻被识别结果顶回去
|
|
651
|
+
mountable: forced
|
|
652
|
+
? Boolean(picked && (picked.score >= MIN_DETECT_SCORE || picked.ready))
|
|
653
|
+
: Boolean(picked && picked.score >= MIN_DETECT_SCORE),
|
|
345
654
|
};
|
|
346
655
|
}
|
|
347
656
|
|
|
657
|
+
/** 框架下拉的可选项(Playwright / pytest / Selenium) */
|
|
658
|
+
export function frameworkOptions() {
|
|
659
|
+
return adapterOptions();
|
|
660
|
+
}
|
|
661
|
+
|
|
348
662
|
function decorateProject(project) {
|
|
349
|
-
const health = detectProject(project.dir);
|
|
663
|
+
const health = detectProject(project.dir, project.framework);
|
|
350
664
|
const running = [...RUNNING.values()].find((entry) => entry.projectId === project.id);
|
|
665
|
+
const customTasks = normalizeCustomTasks(project.customTasks);
|
|
666
|
+
const probe = health.exists ? buildProbe(project.dir) : null;
|
|
667
|
+
// 自动发现 → 套上用户在运行配置里改过的名称 / 命令,删掉的不再出现
|
|
668
|
+
const detected = probe
|
|
669
|
+
? applyTaskOverrides(
|
|
670
|
+
discoverRunTasks(probe, project.framework),
|
|
671
|
+
project.taskOverrides,
|
|
672
|
+
project.hiddenTasks,
|
|
673
|
+
)
|
|
674
|
+
: [];
|
|
675
|
+
// 「全量运行」固定排第一,后面是项目自带任务与用户自己加的命令
|
|
676
|
+
const fullTask = {
|
|
677
|
+
id: 'full',
|
|
678
|
+
label: '全量运行',
|
|
679
|
+
display: '全量运行',
|
|
680
|
+
hint: health.runner || '',
|
|
681
|
+
kind: 'full',
|
|
682
|
+
// Selenium 的 mvn / gradle 没有稳定的「只跑失败」开关,只给全量
|
|
683
|
+
failureFlags: project.framework !== 'selenium',
|
|
684
|
+
custom: false,
|
|
685
|
+
command: health.runner || '',
|
|
686
|
+
};
|
|
351
687
|
return {
|
|
352
688
|
...project,
|
|
689
|
+
customTasks,
|
|
353
690
|
...health,
|
|
691
|
+
// 生成页起始地址:项目上记的优先,其次读项目配置(playwright use.baseURL / .env)
|
|
692
|
+
baseURL: project.baseURL || '',
|
|
693
|
+
detectedBaseURL: health.exists ? safeDetectBaseURL(project.dir) : '',
|
|
694
|
+
// 登录态同理:项目上记的优先,其次读项目里的登录态文件(换项目要重新识别)
|
|
695
|
+
storageState: project.storageState || '',
|
|
696
|
+
detectedStorageState: health.exists ? safeDetectStorageState(project.dir) : '',
|
|
697
|
+
runTasks: [fullTask, ...detected.map(taskView), ...customToTasks(customTasks).map(taskView)],
|
|
354
698
|
runningRunId: running ? running.runId : '',
|
|
355
699
|
};
|
|
356
700
|
}
|
|
357
701
|
|
|
702
|
+
/** 探测地址失败不能把「项目列表」一起拖垮:读不到就返回空串 */
|
|
703
|
+
function safeDetectBaseURL(dir) {
|
|
704
|
+
try {
|
|
705
|
+
return detectBaseURL(dir);
|
|
706
|
+
} catch {
|
|
707
|
+
return '';
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
/** 登录态探测同理:目录读不了就当没有 */
|
|
712
|
+
function safeDetectStorageState(dir) {
|
|
713
|
+
try {
|
|
714
|
+
return detectStorageState(dir);
|
|
715
|
+
} catch {
|
|
716
|
+
return '';
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
|
|
358
720
|
/** 该项目最近一次运行解析到的 Playwright 项目名(setup / chromium-login …) */
|
|
359
721
|
function latestProjectNames(store, projectId) {
|
|
360
722
|
const runs = store.runs
|
|
@@ -363,25 +725,6 @@ function latestProjectNames(store, projectId) {
|
|
|
363
725
|
return runs[0]?.projectNames ?? [];
|
|
364
726
|
}
|
|
365
727
|
|
|
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
728
|
/** 把相对文件路径清成项目内的 POSIX 路径;越界返回空串 */
|
|
386
729
|
export function normalizeRunFile(base, file) {
|
|
387
730
|
const raw = text(file, 1024).replace(/\\/g, '/');
|
|
@@ -397,112 +740,6 @@ export function normalizeRunFile(base, file) {
|
|
|
397
740
|
return raw.replace(/^\.\//, '');
|
|
398
741
|
}
|
|
399
742
|
|
|
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
743
|
function appendLog(entry, chunk) {
|
|
507
744
|
const value = String(chunk ?? '');
|
|
508
745
|
if (!value) return;
|
|
@@ -543,6 +780,11 @@ function killRun(entry, signal) {
|
|
|
543
780
|
}
|
|
544
781
|
}
|
|
545
782
|
|
|
783
|
+
/** 结果文件的后缀:JSON 交给适配器自己解析,pytest / selenium 用 XML */
|
|
784
|
+
function resultFileName(runId, adapter) {
|
|
785
|
+
return `${runId}${adapter.id === 'playwright' ? '.json' : '.xml'}`;
|
|
786
|
+
}
|
|
787
|
+
|
|
546
788
|
function finishRun(root, entry, runId, exitCode, spawnError) {
|
|
547
789
|
if (entry.settled) return;
|
|
548
790
|
entry.settled = true;
|
|
@@ -562,9 +804,57 @@ function finishRun(root, entry, runId, exitCode, spawnError) {
|
|
|
562
804
|
const run = findRun(store, runId);
|
|
563
805
|
if (!run) return;
|
|
564
806
|
|
|
565
|
-
const
|
|
566
|
-
|
|
567
|
-
);
|
|
807
|
+
const project = findProject(store, run.projectId);
|
|
808
|
+
const adapter = getAdapter(run.framework) ?? getAdapter('playwright');
|
|
809
|
+
const probe = project ? buildProbe(project.dir) : null;
|
|
810
|
+
const pp = project ? projectPaths(root, project) : null;
|
|
811
|
+
const resultAbs = run.resultRel ? path.join(paths.dir, run.resultRel) : '';
|
|
812
|
+
const reportAbs = pp
|
|
813
|
+
? path.join(pp.reportDir, runId)
|
|
814
|
+
: run.reportRel
|
|
815
|
+
? path.join(paths.dir, run.reportRel)
|
|
816
|
+
: '';
|
|
817
|
+
const ctx = {
|
|
818
|
+
dir: project?.dir ?? '',
|
|
819
|
+
probe,
|
|
820
|
+
runId,
|
|
821
|
+
startedAt: run.startedAt,
|
|
822
|
+
exitCode,
|
|
823
|
+
log: entry.log,
|
|
824
|
+
resultAbs,
|
|
825
|
+
resultDirAbs: pp ? pp.resultDir : path.dirname(resultAbs),
|
|
826
|
+
reportAbs,
|
|
827
|
+
};
|
|
828
|
+
|
|
829
|
+
let summary = emptySummary();
|
|
830
|
+
try {
|
|
831
|
+
summary = adapter.parse?.(ctx) ?? summary;
|
|
832
|
+
} catch {
|
|
833
|
+
summary = emptySummary();
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
// 报告快照:项目里的 HTML 报告复制一份到空间(按项目分目录),历史记录不会被下次运行覆盖
|
|
837
|
+
let reportRel = '';
|
|
838
|
+
if (ctx.reportAbs && !entry.stopping && project && probe) {
|
|
839
|
+
try {
|
|
840
|
+
const dirs = adapter.reportDirs?.(probe) ?? [];
|
|
841
|
+
if (dirs.length) {
|
|
842
|
+
snapshotReport({
|
|
843
|
+
projectDir: project.dir,
|
|
844
|
+
candidates: dirs,
|
|
845
|
+
destAbs: ctx.reportAbs,
|
|
846
|
+
// 本次运行开始前的旧报告不复制,避免「这次没生成报告却显示上次的」
|
|
847
|
+
minMtime: (Date.parse(run.startedAt) || 0) - 1000,
|
|
848
|
+
});
|
|
849
|
+
}
|
|
850
|
+
} catch {
|
|
851
|
+
// 快照失败不影响结果
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
if (ctx.reportAbs && hasReportEntry(ctx.reportAbs)) {
|
|
855
|
+
reportRel = toPosixRel(paths.dir, ctx.reportAbs);
|
|
856
|
+
}
|
|
857
|
+
|
|
568
858
|
const finishedAt = new Date().toISOString();
|
|
569
859
|
const started = Date.parse(run.startedAt);
|
|
570
860
|
const durationMs = summary.durationMs || (Number.isFinite(started) ? Date.now() - started : 0);
|
|
@@ -579,8 +869,9 @@ function finishRun(root, entry, runId, exitCode, spawnError) {
|
|
|
579
869
|
if (spawnError) error = text(spawnError, 4000);
|
|
580
870
|
else if (summary.errors.length) error = summary.errors.join('\n').slice(0, 4000);
|
|
581
871
|
else if (status === 'failed' && summary.total === 0) {
|
|
872
|
+
const hint = text(adapter.hintFromLog?.(entry.log), 1000);
|
|
582
873
|
const tail = entry.log.slice(-1200).trim();
|
|
583
|
-
|
|
874
|
+
error = hint || tail;
|
|
584
875
|
}
|
|
585
876
|
|
|
586
877
|
run.status = status;
|
|
@@ -593,9 +884,9 @@ function finishRun(root, entry, runId, exitCode, spawnError) {
|
|
|
593
884
|
run.skipped = summary.skipped;
|
|
594
885
|
run.flaky = summary.flaky;
|
|
595
886
|
if (summary.projectNames.length) run.projectNames = summary.projectNames;
|
|
887
|
+
run.reportRel = reportRel;
|
|
596
888
|
run.error = error;
|
|
597
889
|
|
|
598
|
-
const project = findProject(store, run.projectId);
|
|
599
890
|
if (project) {
|
|
600
891
|
project.lastRunId = run.id;
|
|
601
892
|
project.lastRunAt = run.startedAt;
|
|
@@ -618,17 +909,17 @@ function startRun(root, body) {
|
|
|
618
909
|
const project = findProject(store, projectId);
|
|
619
910
|
if (!project) return { error: '项目不存在', status: 404 };
|
|
620
911
|
|
|
621
|
-
const
|
|
622
|
-
if (!
|
|
912
|
+
const adapter = getAdapter(project.framework);
|
|
913
|
+
if (!adapter) return { error: `不支持的框架:${project.framework}`, status: 400 };
|
|
914
|
+
|
|
915
|
+
const probe = buildProbe(project.dir);
|
|
916
|
+
if (!probe.exists) return { error: '项目目录不存在,请重新选择目录', status: 400 };
|
|
917
|
+
const health = detectProject(project.dir, project.framework);
|
|
623
918
|
if (!health.mountable) {
|
|
624
|
-
return {
|
|
625
|
-
error: '该目录下没有 playwright.config 或 @playwright/test 依赖,无法运行',
|
|
626
|
-
status: 400,
|
|
627
|
-
};
|
|
919
|
+
return { error: '没有识别到该目录的测试框架,请重新识别或换个目录', status: 400 };
|
|
628
920
|
}
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
return { error: installHint(project.dir, health.packageManager), status: 400 };
|
|
921
|
+
if (!health.frameworkReady) {
|
|
922
|
+
return { error: health.readyHint || '运行环境未就绪', status: 400 };
|
|
632
923
|
}
|
|
633
924
|
|
|
634
925
|
for (const entry of RUNNING.values()) {
|
|
@@ -640,49 +931,115 @@ function startRun(root, body) {
|
|
|
640
931
|
return { error: `全局最多同时运行 ${MAX_CONCURRENT_RUNS} 个项目,请稍后再试`, status: 409 };
|
|
641
932
|
}
|
|
642
933
|
|
|
643
|
-
const args = normalizeRunArgs(
|
|
934
|
+
const args = normalizeRunArgs({
|
|
935
|
+
...body,
|
|
936
|
+
project: project.framework === 'playwright' ? body?.project : '',
|
|
937
|
+
});
|
|
644
938
|
if (args.file) {
|
|
645
939
|
const file = normalizeRunFile(project.dir, args.file);
|
|
646
940
|
if (!file) return { error: '指定的测试文件不在项目目录内或不存在', status: 400 };
|
|
647
941
|
args.file = file;
|
|
648
942
|
}
|
|
649
943
|
|
|
944
|
+
// 运行任务:`full` 走框架默认命令(沿用适配器),其余从项目任务 + 自定义命令里找
|
|
945
|
+
const taskId = text(body?.taskId, 64) || 'full';
|
|
946
|
+
const customTasks = normalizeCustomTasks(project.customTasks);
|
|
947
|
+
const task =
|
|
948
|
+
taskId === 'full'
|
|
949
|
+
? null
|
|
950
|
+
: [
|
|
951
|
+
...applyTaskOverrides(
|
|
952
|
+
discoverRunTasks(probe, project.framework),
|
|
953
|
+
project.taskOverrides,
|
|
954
|
+
project.hiddenTasks,
|
|
955
|
+
),
|
|
956
|
+
...customToTasks(customTasks),
|
|
957
|
+
].find((item) => item.id === taskId);
|
|
958
|
+
if (taskId !== 'full' && !task) {
|
|
959
|
+
return { error: '这条运行任务已不存在,请刷新后重新选择', status: 404 };
|
|
960
|
+
}
|
|
961
|
+
|
|
650
962
|
const runId = `uar_${Date.now().toString(36)}_${crypto.randomBytes(3).toString('hex')}`;
|
|
651
963
|
const paths = uiautoStorePaths(root);
|
|
652
|
-
|
|
653
|
-
const
|
|
654
|
-
const
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
964
|
+
// 按项目分目录:自动化测试/<项目名>/{报告,结果,日志}
|
|
965
|
+
const pp = projectPaths(root, project);
|
|
966
|
+
const reportAbs = path.join(pp.reportDir, runId);
|
|
967
|
+
const resultAbs = path.join(pp.resultDir, resultFileName(runId, adapter));
|
|
968
|
+
const resultRel = toPosixRel(paths.dir, resultAbs);
|
|
969
|
+
const logAbs = path.join(pp.logDir, `${runId}.log`);
|
|
970
|
+
const logRel = toPosixRel(paths.dir, logAbs);
|
|
971
|
+
fs.mkdirSync(pp.reportDir, { recursive: true });
|
|
972
|
+
fs.mkdirSync(pp.resultDir, { recursive: true });
|
|
973
|
+
fs.mkdirSync(pp.logDir, { recursive: true });
|
|
974
|
+
|
|
975
|
+
/**
|
|
976
|
+
* 任务运行走 shell:项目自带脚本 / Makefile 目标 / 用户手写的命令都按原样执行,
|
|
977
|
+
* 支持引号与 `&&`。报告路径靠环境变量注入,不改用户命令本身:
|
|
978
|
+
* - pytest:`PYTEST_ADDOPTS` 追加 `--junitxml`(在配置的 addopts 之后生效)
|
|
979
|
+
* - Playwright:`PLAYWRIGHT_JSON_OUTPUT_NAME` 指定 JSON 结果落点
|
|
980
|
+
*/
|
|
981
|
+
let resolved;
|
|
982
|
+
if (task) {
|
|
983
|
+
const env = {};
|
|
984
|
+
if (project.framework === 'pytest') {
|
|
985
|
+
env.PYTEST_ADDOPTS = [process.env.PYTEST_ADDOPTS ?? '', `--junitxml=${resultAbs}`]
|
|
986
|
+
.filter(Boolean)
|
|
987
|
+
.join(' ');
|
|
988
|
+
} else {
|
|
989
|
+
env.PLAYWRIGHT_JSON_OUTPUT_NAME = resultAbs;
|
|
990
|
+
env.PLAYWRIGHT_JSON_OUTPUT_DIR = path.dirname(resultAbs);
|
|
991
|
+
}
|
|
992
|
+
resolved = { shell: true, command: taskCommandLine(task, args), args: [], env };
|
|
993
|
+
} else {
|
|
994
|
+
resolved = adapter.resolve({
|
|
995
|
+
dir: project.dir,
|
|
996
|
+
probe,
|
|
997
|
+
args,
|
|
998
|
+
runId,
|
|
999
|
+
resultAbs,
|
|
1000
|
+
resultDirAbs: pp.resultDir,
|
|
1001
|
+
reportAbs,
|
|
1002
|
+
guardPath: ARGV_GUARD_PATH,
|
|
1003
|
+
});
|
|
1004
|
+
}
|
|
1005
|
+
if (resolved?.error) return { error: resolved.error, status: 400 };
|
|
1006
|
+
if (!resolved?.command) return { error: '运行命令解析失败', status: 500 };
|
|
658
1007
|
|
|
659
1008
|
const startedAt = new Date().toISOString();
|
|
660
|
-
const cliArgs = [...command.prefix, ...buildPlaywrightArgs(args)];
|
|
661
1009
|
const env = {
|
|
662
1010
|
...process.env,
|
|
663
|
-
|
|
664
|
-
PLAYWRIGHT_HTML_OPEN: 'never',
|
|
665
|
-
PLAYWRIGHT_JSON_OUTPUT_NAME: resultAbs,
|
|
1011
|
+
...(resolved.env ?? {}),
|
|
666
1012
|
FORCE_COLOR: '0',
|
|
667
1013
|
NO_COLOR: '1',
|
|
668
1014
|
};
|
|
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
1015
|
|
|
1016
|
+
// 记录真实执行的命令行:任务运行时是 shell 命令串,全量运行时是命令 + 参数
|
|
1017
|
+
const commandLine = resolved.shell
|
|
1018
|
+
? resolved.command
|
|
1019
|
+
: [resolved.command, ...(resolved.args ?? [])].join(' ');
|
|
1020
|
+
|
|
1021
|
+
const win = process.platform === 'win32';
|
|
677
1022
|
let child;
|
|
678
1023
|
try {
|
|
679
|
-
child =
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
1024
|
+
child = resolved.shell
|
|
1025
|
+
? spawn(
|
|
1026
|
+
win ? 'cmd.exe' : '/bin/sh',
|
|
1027
|
+
win ? ['/d', '/s', '/c', resolved.command] : ['-c', resolved.command],
|
|
1028
|
+
{
|
|
1029
|
+
cwd: project.dir,
|
|
1030
|
+
env,
|
|
1031
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
1032
|
+
detached: !win,
|
|
1033
|
+
windowsHide: true,
|
|
1034
|
+
},
|
|
1035
|
+
)
|
|
1036
|
+
: spawn(resolved.command, resolved.args, {
|
|
1037
|
+
cwd: project.dir,
|
|
1038
|
+
env,
|
|
1039
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
1040
|
+
detached: !win,
|
|
1041
|
+
windowsHide: true,
|
|
1042
|
+
});
|
|
686
1043
|
} catch (err) {
|
|
687
1044
|
return { error: `启动失败:${err instanceof Error ? err.message : String(err)}`, status: 500 };
|
|
688
1045
|
}
|
|
@@ -690,6 +1047,7 @@ function startRun(root, body) {
|
|
|
690
1047
|
const run = {
|
|
691
1048
|
id: runId,
|
|
692
1049
|
projectId,
|
|
1050
|
+
framework: adapter.id,
|
|
693
1051
|
startedAt,
|
|
694
1052
|
finishedAt: '',
|
|
695
1053
|
status: 'running',
|
|
@@ -701,10 +1059,13 @@ function startRun(root, body) {
|
|
|
701
1059
|
skipped: 0,
|
|
702
1060
|
flaky: 0,
|
|
703
1061
|
args,
|
|
1062
|
+
command: commandLine,
|
|
1063
|
+
taskId,
|
|
1064
|
+
taskLabel: task ? taskCommandLine(task) : '',
|
|
704
1065
|
projectNames: [],
|
|
705
|
-
reportRel:
|
|
706
|
-
resultRel
|
|
707
|
-
logRel
|
|
1066
|
+
reportRel: '',
|
|
1067
|
+
resultRel,
|
|
1068
|
+
logRel,
|
|
708
1069
|
error: '',
|
|
709
1070
|
};
|
|
710
1071
|
store.runs.push(run);
|
|
@@ -727,6 +1088,7 @@ function startRun(root, body) {
|
|
|
727
1088
|
settled: false,
|
|
728
1089
|
};
|
|
729
1090
|
RUNNING.set(runId, entry);
|
|
1091
|
+
appendLog(entry, `[lantern] $ ${commandLine}\n`);
|
|
730
1092
|
|
|
731
1093
|
child.stdout?.setEncoding('utf8');
|
|
732
1094
|
child.stderr?.setEncoding('utf8');
|
|
@@ -741,7 +1103,7 @@ function startRun(root, body) {
|
|
|
741
1103
|
finishRun(root, entry, runId, code, '');
|
|
742
1104
|
});
|
|
743
1105
|
|
|
744
|
-
return { run: runView(run), command:
|
|
1106
|
+
return { run: runView(run), command: commandLine, args: resolved.args };
|
|
745
1107
|
}
|
|
746
1108
|
|
|
747
1109
|
function stopRun(runId) {
|
|
@@ -788,8 +1150,10 @@ function sendReportFile(root, res, runId, rawPath) {
|
|
|
788
1150
|
if (!/^[A-Za-z0-9_-]+$/.test(runId))
|
|
789
1151
|
return sendJson(res, 400, { ok: false, error: '运行 ID 不合法' });
|
|
790
1152
|
const paths = uiautoStorePaths(root);
|
|
791
|
-
const
|
|
792
|
-
if (!
|
|
1153
|
+
const run = findRun(readStore(root).store, runId);
|
|
1154
|
+
if (!run || !run.reportRel) return sendJson(res, 404, { ok: false, error: '报告不存在' });
|
|
1155
|
+
const dir = path.join(paths.dir, run.reportRel);
|
|
1156
|
+
if (!isPathInside(paths.dir, dir)) {
|
|
793
1157
|
return sendJson(res, 400, { ok: false, error: '报告路径不合法' });
|
|
794
1158
|
}
|
|
795
1159
|
let rel;
|
|
@@ -830,65 +1194,16 @@ function sendReportFile(root, res, runId, rawPath) {
|
|
|
830
1194
|
fs.createReadStream(file).pipe(res);
|
|
831
1195
|
}
|
|
832
1196
|
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
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
|
-
}
|
|
1197
|
+
/** 各框架的测试文件命名规则:只用于「指定文件」下拉,识别不依赖它 */
|
|
1198
|
+
const SPEC_PATTERNS = {
|
|
1199
|
+
playwright: /\.(spec|test)\.(ts|js|mjs|cjs|tsx|jsx)$/,
|
|
1200
|
+
pytest: /^(test_.*|.*_test)\.py$/,
|
|
1201
|
+
selenium: /\.(java|kt|scala)$/,
|
|
1202
|
+
};
|
|
889
1203
|
|
|
890
1204
|
/** 从目录树里筛出测试文件,供「指定文件」下拉使用 */
|
|
891
|
-
function listSpecFiles(project) {
|
|
1205
|
+
function listSpecFiles(project, framework = project.framework) {
|
|
1206
|
+
const pattern = SPEC_PATTERNS[framework] ?? SPEC_PATTERNS.playwright;
|
|
892
1207
|
const result = [];
|
|
893
1208
|
const walk = (abs, level) => {
|
|
894
1209
|
if (level > 6 || result.length >= 500) return;
|
|
@@ -903,7 +1218,7 @@ function listSpecFiles(project) {
|
|
|
903
1218
|
if (shouldIgnoreTreeName(item.name)) continue;
|
|
904
1219
|
const child = path.join(abs, item.name);
|
|
905
1220
|
if (item.isDirectory()) walk(child, level + 1);
|
|
906
|
-
else if (
|
|
1221
|
+
else if (pattern.test(item.name)) {
|
|
907
1222
|
result.push(toPosixRel(project.dir, child));
|
|
908
1223
|
}
|
|
909
1224
|
}
|
|
@@ -912,58 +1227,26 @@ function listSpecFiles(project) {
|
|
|
912
1227
|
return result.sort();
|
|
913
1228
|
}
|
|
914
1229
|
|
|
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
1230
|
function removeRunArtifacts(root, run) {
|
|
955
1231
|
const paths = uiautoStorePaths(root);
|
|
1232
|
+
const inside = (abs) => abs && isPathInside(paths.dir, abs);
|
|
1233
|
+
// Selenium/Maven 的 surefire XML 落在该项目 结果/<runId>-surefire/
|
|
1234
|
+
if (run.resultRel) {
|
|
1235
|
+
const resultAbs = path.join(paths.dir, run.resultRel);
|
|
1236
|
+
const surefireDir = path.join(path.dirname(resultAbs), `${run.id}-surefire`);
|
|
1237
|
+
if (inside(surefireDir)) fs.rmSync(surefireDir, { recursive: true, force: true });
|
|
1238
|
+
}
|
|
956
1239
|
if (run.reportRel) {
|
|
957
1240
|
const abs = path.join(paths.dir, run.reportRel);
|
|
958
|
-
if (
|
|
1241
|
+
if (inside(abs)) fs.rmSync(abs, { recursive: true, force: true });
|
|
959
1242
|
}
|
|
960
1243
|
if (run.resultRel) {
|
|
961
1244
|
const abs = path.join(paths.dir, run.resultRel);
|
|
962
|
-
if (
|
|
1245
|
+
if (inside(abs)) fs.rmSync(abs, { force: true });
|
|
963
1246
|
}
|
|
964
1247
|
if (run.logRel) {
|
|
965
1248
|
const abs = path.join(paths.dir, run.logRel);
|
|
966
|
-
if (
|
|
1249
|
+
if (inside(abs)) fs.rmSync(abs, { force: true });
|
|
967
1250
|
}
|
|
968
1251
|
}
|
|
969
1252
|
|
|
@@ -971,9 +1254,42 @@ function removeRunArtifacts(root, run) {
|
|
|
971
1254
|
* @returns {import('vite').Plugin}
|
|
972
1255
|
*/
|
|
973
1256
|
export function lhUiautoPlugin() {
|
|
1257
|
+
// 浏览器被用户手动关掉:把会话从「探索中」收回草稿,并在活动日志里留一条,
|
|
1258
|
+
// 前端再打开还能看出这一轮是被关窗结束的(模型那边也会收到 CLOSED_MESSAGE 而停手)。
|
|
1259
|
+
onExplorerClosed(({ sessionId }) => {
|
|
1260
|
+
try {
|
|
1261
|
+
const baseDir = uiautoCachePaths(getDataRoot()).dir;
|
|
1262
|
+
const record = readGeneratedSession(baseDir, sessionId);
|
|
1263
|
+
if (!record) return;
|
|
1264
|
+
const activity = Array.isArray(record.activity) ? record.activity.slice() : [];
|
|
1265
|
+
const last = activity[activity.length - 1];
|
|
1266
|
+
if (!(last && last.name === '浏览器已关闭')) {
|
|
1267
|
+
activity.push({
|
|
1268
|
+
kind: 'error',
|
|
1269
|
+
name: '浏览器已关闭',
|
|
1270
|
+
detail: '你关闭了浏览器窗口,这一轮探索已结束;重新点「开始探索」会新开一个浏览器',
|
|
1271
|
+
status: 'failed',
|
|
1272
|
+
at: new Date().toISOString(),
|
|
1273
|
+
});
|
|
1274
|
+
}
|
|
1275
|
+
saveGeneratedSession(baseDir, {
|
|
1276
|
+
id: sessionId,
|
|
1277
|
+
// 只有还在探索中的会话需要收回草稿;已写入 / 已试跑的别降级
|
|
1278
|
+
status: record.status === 'exploring' ? 'draft' : record.status,
|
|
1279
|
+
activity,
|
|
1280
|
+
});
|
|
1281
|
+
} catch {
|
|
1282
|
+
// 收尾失败不影响其它流程
|
|
1283
|
+
}
|
|
1284
|
+
});
|
|
1285
|
+
|
|
974
1286
|
return {
|
|
975
1287
|
name: 'lh-uiauto',
|
|
976
1288
|
configureServer(server) {
|
|
1289
|
+
server.httpServer?.on('close', () => {
|
|
1290
|
+
stopAllExplorers();
|
|
1291
|
+
stopAllDebugSessions();
|
|
1292
|
+
});
|
|
977
1293
|
server.middlewares.use(async (req, res, next) => {
|
|
978
1294
|
const parsed = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
979
1295
|
if (!parsed.pathname.startsWith(PREFIX)) return next();
|
|
@@ -983,6 +1299,13 @@ export function lhUiautoPlugin() {
|
|
|
983
1299
|
const tail = parsed.pathname.slice(PREFIX.length) || '/';
|
|
984
1300
|
|
|
985
1301
|
try {
|
|
1302
|
+
// 任何一次插件请求都顺手把旧版放在内容目录里的本机数据搬到 .lantern/local/uiauto
|
|
1303
|
+
try {
|
|
1304
|
+
uiautoCachePaths(root);
|
|
1305
|
+
} catch {
|
|
1306
|
+
// 迁移失败不阻塞主流程
|
|
1307
|
+
}
|
|
1308
|
+
|
|
986
1309
|
if (method === 'GET' && tail.startsWith('/report/')) {
|
|
987
1310
|
const rest = tail.slice('/report/'.length);
|
|
988
1311
|
const slash = rest.indexOf('/');
|
|
@@ -991,11 +1314,64 @@ export function lhUiautoPlugin() {
|
|
|
991
1314
|
return sendReportFile(root, res, runId, rel);
|
|
992
1315
|
}
|
|
993
1316
|
|
|
1317
|
+
/* ── 提示词:与「提示词管理/Playwright提示词.md」联动 ── */
|
|
1318
|
+
|
|
1319
|
+
if (method === 'GET' && tail === '/prompt') {
|
|
1320
|
+
// 允许按项目指定提示词文件(不同框架挂不同提示词);只接受提示词目录里的文件名,
|
|
1321
|
+
// 传空 / 不存在时退回插件默认那份,避免把接口当任意文件读取
|
|
1322
|
+
const wanted = text(parsed.searchParams.get('file'), 200);
|
|
1323
|
+
const file = wanted && isPromptFileName(wanted) ? wanted : UI_AUTO_PROMPT_FILE;
|
|
1324
|
+
const content = readPluginPrompt(file, root);
|
|
1325
|
+
const sections = parseUiAutoPrompt(content);
|
|
1326
|
+
return sendJson(res, 200, {
|
|
1327
|
+
ok: true,
|
|
1328
|
+
file,
|
|
1329
|
+
exists: Boolean(content.trim()),
|
|
1330
|
+
plan: sections.plan,
|
|
1331
|
+
agent: sections.agent,
|
|
1332
|
+
code: sections.code,
|
|
1333
|
+
});
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
if (method === 'POST' && tail === '/prompt/sync') {
|
|
1337
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
1338
|
+
const wanted = body.enabled === true;
|
|
1339
|
+
if (!wanted) {
|
|
1340
|
+
// 关闭只停用:文件保留,再打开仍引用同一份
|
|
1341
|
+
const exists = fs.existsSync(pluginPromptPath(UI_AUTO_PROMPT_FILE, root));
|
|
1342
|
+
return sendJson(res, 200, {
|
|
1343
|
+
ok: true,
|
|
1344
|
+
enabled: false,
|
|
1345
|
+
removed: false,
|
|
1346
|
+
exists,
|
|
1347
|
+
file: UI_AUTO_PROMPT_FILE,
|
|
1348
|
+
});
|
|
1349
|
+
}
|
|
1350
|
+
const out = ensurePluginPrompt(UI_AUTO_PROMPT_FILE, UI_AUTO_PROMPT_TEMPLATE, root);
|
|
1351
|
+
return sendJson(res, 200, {
|
|
1352
|
+
ok: true,
|
|
1353
|
+
enabled: true,
|
|
1354
|
+
created: out.created,
|
|
1355
|
+
updated: out.updated,
|
|
1356
|
+
exists: out.exists,
|
|
1357
|
+
file: out.file,
|
|
1358
|
+
});
|
|
1359
|
+
}
|
|
1360
|
+
|
|
994
1361
|
if (method === 'GET' && parsed.searchParams.get('health') === '1') {
|
|
1362
|
+
const healthStore = readStore(root).store;
|
|
995
1363
|
return sendJson(res, 200, {
|
|
996
1364
|
ok: true,
|
|
997
|
-
files:
|
|
1365
|
+
files: {
|
|
1366
|
+
...uiautoStorePaths(root),
|
|
1367
|
+
projects: healthStore.projects.map((project) => ({
|
|
1368
|
+
id: project.id,
|
|
1369
|
+
name: project.name,
|
|
1370
|
+
dir: projectPaths(root, project).dir,
|
|
1371
|
+
})),
|
|
1372
|
+
},
|
|
998
1373
|
running: [...RUNNING.keys()],
|
|
1374
|
+
frameworks: frameworkOptions(),
|
|
999
1375
|
version: VERSION,
|
|
1000
1376
|
});
|
|
1001
1377
|
}
|
|
@@ -1005,16 +1381,48 @@ export function lhUiautoPlugin() {
|
|
|
1005
1381
|
if (dirty) writeStore(root, store);
|
|
1006
1382
|
const projects = store.projects.map((project) => ({
|
|
1007
1383
|
...decorateProject(project),
|
|
1008
|
-
specFiles:
|
|
1384
|
+
specFiles: buildProbe(project.dir).exists
|
|
1385
|
+
? listSpecFiles(project, project.framework)
|
|
1386
|
+
: [],
|
|
1009
1387
|
// 上次运行拿到的 Playwright 项目名(setup / chromium-login 之类),给下拉做候选
|
|
1010
1388
|
projectNames: latestProjectNames(store, project.id),
|
|
1011
1389
|
}));
|
|
1012
|
-
return sendJson(res, 200, {
|
|
1390
|
+
return sendJson(res, 200, {
|
|
1391
|
+
ok: true,
|
|
1392
|
+
projects,
|
|
1393
|
+
frameworks: frameworkOptions(),
|
|
1394
|
+
});
|
|
1395
|
+
}
|
|
1396
|
+
|
|
1397
|
+
if (method === 'POST' && tail === '/detect') {
|
|
1398
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
1399
|
+
const rawDir = text(body.dir, 4096);
|
|
1400
|
+
if (!rawDir) return sendJson(res, 400, { ok: false, error: '缺少项目目录' });
|
|
1401
|
+
const dir = path.resolve(rawDir);
|
|
1402
|
+
const probe = buildProbe(dir);
|
|
1403
|
+
if (!probe.exists) return sendJson(res, 400, { ok: false, error: '目录不存在' });
|
|
1404
|
+
const candidates = detectCandidates(probe);
|
|
1405
|
+
const hints = {};
|
|
1406
|
+
for (const candidate of candidates) {
|
|
1407
|
+
const adapter = getAdapter(candidate.id);
|
|
1408
|
+
hints[candidate.id] = adapter?.readyHint?.(probe) ?? '';
|
|
1409
|
+
}
|
|
1410
|
+
return sendJson(res, 200, {
|
|
1411
|
+
ok: true,
|
|
1412
|
+
dir,
|
|
1413
|
+
candidates,
|
|
1414
|
+
hints,
|
|
1415
|
+
frameworks: frameworkOptions(),
|
|
1416
|
+
});
|
|
1013
1417
|
}
|
|
1014
1418
|
|
|
1015
1419
|
if (method === 'POST' && tail === '/pick-directory') {
|
|
1016
|
-
const picked = await
|
|
1017
|
-
|
|
1420
|
+
const picked = await pickDirectoryResult('选择测试项目目录');
|
|
1421
|
+
if (picked.error) {
|
|
1422
|
+
return sendJson(res, 200, { ok: false, error: picked.error, dir: '' });
|
|
1423
|
+
}
|
|
1424
|
+
if (picked.canceled) return sendJson(res, 200, { ok: true, canceled: true, dir: '' });
|
|
1425
|
+
return sendJson(res, 200, { ok: true, dir: picked.path ?? '' });
|
|
1018
1426
|
}
|
|
1019
1427
|
|
|
1020
1428
|
if (method === 'POST' && tail === '/projects') {
|
|
@@ -1022,23 +1430,35 @@ export function lhUiautoPlugin() {
|
|
|
1022
1430
|
const rawDir = text(body.dir, 4096);
|
|
1023
1431
|
if (!rawDir) return sendJson(res, 400, { ok: false, error: '缺少项目目录' });
|
|
1024
1432
|
const dir = path.resolve(rawDir);
|
|
1025
|
-
const
|
|
1433
|
+
const requested = text(body.framework, 40);
|
|
1434
|
+
if (requested && !ADAPTER_IDS.includes(requested)) {
|
|
1435
|
+
return sendJson(res, 400, { ok: false, error: `不支持的框架:${requested}` });
|
|
1436
|
+
}
|
|
1437
|
+
const health = detectProject(dir, requested);
|
|
1026
1438
|
if (!health.exists) return sendJson(res, 400, { ok: false, error: '目录不存在' });
|
|
1027
1439
|
if (!health.mountable) {
|
|
1028
1440
|
return sendJson(res, 400, {
|
|
1029
1441
|
ok: false,
|
|
1030
1442
|
error:
|
|
1031
|
-
'
|
|
1443
|
+
'没有识别到受支持的框架(Playwright / pytest / Selenium),请确认目录里是测试项目',
|
|
1032
1444
|
});
|
|
1033
1445
|
}
|
|
1446
|
+
const framework = requested || health.framework;
|
|
1447
|
+
if (!ADAPTER_IDS.includes(framework)) {
|
|
1448
|
+
return sendJson(res, 400, { ok: false, error: '请选择要使用的框架' });
|
|
1449
|
+
}
|
|
1034
1450
|
const store = readStoreForWrite(root);
|
|
1035
1451
|
if (store.projects.some((p) => path.resolve(p.dir) === dir)) {
|
|
1036
1452
|
return sendJson(res, 409, { ok: false, error: '该目录已经添加过了' });
|
|
1037
1453
|
}
|
|
1454
|
+
const id = `uia_${crypto.randomBytes(8).toString('hex')}`;
|
|
1455
|
+
const name = text(body.name, 200) || path.basename(dir);
|
|
1038
1456
|
const project = {
|
|
1039
|
-
id
|
|
1040
|
-
name
|
|
1457
|
+
id,
|
|
1458
|
+
name,
|
|
1459
|
+
folder: uniqueFolder(store, name, id),
|
|
1041
1460
|
dir,
|
|
1461
|
+
framework,
|
|
1042
1462
|
createdAt: new Date().toISOString(),
|
|
1043
1463
|
lastRunId: '',
|
|
1044
1464
|
lastRunAt: '',
|
|
@@ -1050,7 +1470,7 @@ export function lhUiautoPlugin() {
|
|
|
1050
1470
|
ok: true,
|
|
1051
1471
|
project: {
|
|
1052
1472
|
...decorateProject(project),
|
|
1053
|
-
specFiles: listSpecFiles(project),
|
|
1473
|
+
specFiles: listSpecFiles(project, framework),
|
|
1054
1474
|
projectNames: latestProjectNames(store, project.id),
|
|
1055
1475
|
},
|
|
1056
1476
|
});
|
|
@@ -1063,25 +1483,54 @@ export function lhUiautoPlugin() {
|
|
|
1063
1483
|
if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
|
|
1064
1484
|
const name = text(body.name, 200);
|
|
1065
1485
|
if (name) project.name = name;
|
|
1486
|
+
if (typeof body.framework === 'string' && body.framework.trim()) {
|
|
1487
|
+
const next = text(body.framework, 40);
|
|
1488
|
+
if (!ADAPTER_IDS.includes(next)) {
|
|
1489
|
+
return sendJson(res, 400, { ok: false, error: `不支持的框架:${next}` });
|
|
1490
|
+
}
|
|
1491
|
+
project.framework = next;
|
|
1492
|
+
}
|
|
1066
1493
|
if (typeof body.dir === 'string' && body.dir.trim()) {
|
|
1067
1494
|
const dir = path.resolve(text(body.dir, 4096));
|
|
1068
|
-
const health = detectProject(dir);
|
|
1495
|
+
const health = detectProject(dir, project.framework);
|
|
1069
1496
|
if (!health.exists) return sendJson(res, 400, { ok: false, error: '目录不存在' });
|
|
1070
1497
|
if (!health.mountable) {
|
|
1071
1498
|
return sendJson(res, 400, {
|
|
1072
1499
|
ok: false,
|
|
1073
1500
|
error:
|
|
1074
|
-
'
|
|
1501
|
+
'没有识别到受支持的框架(Playwright / pytest / Selenium),请确认目录里是测试项目',
|
|
1075
1502
|
});
|
|
1076
1503
|
}
|
|
1077
1504
|
project.dir = dir;
|
|
1505
|
+
if (!body.framework) project.framework = health.framework || project.framework;
|
|
1506
|
+
}
|
|
1507
|
+
// 运行配置面板整组提交:名称 + 命令,空数组等于清空自定义任务
|
|
1508
|
+
if (Array.isArray(body.customTasks)) {
|
|
1509
|
+
project.customTasks = normalizeCustomTasks(body.customTasks);
|
|
1510
|
+
}
|
|
1511
|
+
if (Array.isArray(body.taskOverrides)) {
|
|
1512
|
+
project.taskOverrides = normalizeTaskOverrides(body.taskOverrides);
|
|
1513
|
+
}
|
|
1514
|
+
if (Array.isArray(body.hiddenTasks)) {
|
|
1515
|
+
project.hiddenTasks = normalizeHiddenTaskIds(body.hiddenTasks);
|
|
1516
|
+
}
|
|
1517
|
+
// 生成页的起始地址 / 提示词:按项目保存,下次自动带出来
|
|
1518
|
+
if (typeof body.baseURL === 'string') {
|
|
1519
|
+
project.baseURL = text(body.baseURL, 500);
|
|
1520
|
+
}
|
|
1521
|
+
if (typeof body.promptFile === 'string') {
|
|
1522
|
+
project.promptFile = text(body.promptFile, 200);
|
|
1523
|
+
}
|
|
1524
|
+
// 登录态文件也按项目存:换项目重新识别,不会沿用上一个项目的 cookie 文件
|
|
1525
|
+
if (typeof body.storageState === 'string') {
|
|
1526
|
+
project.storageState = text(body.storageState, 300);
|
|
1078
1527
|
}
|
|
1079
1528
|
writeStore(root, store);
|
|
1080
1529
|
return sendJson(res, 200, {
|
|
1081
1530
|
ok: true,
|
|
1082
1531
|
project: {
|
|
1083
1532
|
...decorateProject(project),
|
|
1084
|
-
specFiles: listSpecFiles(project),
|
|
1533
|
+
specFiles: listSpecFiles(project, project.framework),
|
|
1085
1534
|
projectNames: latestProjectNames(store, project.id),
|
|
1086
1535
|
},
|
|
1087
1536
|
});
|
|
@@ -1100,28 +1549,6 @@ export function lhUiautoPlugin() {
|
|
|
1100
1549
|
return sendJson(res, 200, { ok: true });
|
|
1101
1550
|
}
|
|
1102
1551
|
|
|
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
1552
|
if (method === 'POST' && tail === '/run') {
|
|
1126
1553
|
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
1127
1554
|
const result = startRun(root, body);
|
|
@@ -1153,7 +1580,7 @@ export function lhUiautoPlugin() {
|
|
|
1153
1580
|
let reset = false;
|
|
1154
1581
|
if (run.logRel) {
|
|
1155
1582
|
const abs = path.join(uiautoStorePaths(root).dir, run.logRel);
|
|
1156
|
-
if (isPathInside(uiautoStorePaths(root).
|
|
1583
|
+
if (isPathInside(uiautoStorePaths(root).dir, abs)) {
|
|
1157
1584
|
try {
|
|
1158
1585
|
const stat = fs.statSync(abs);
|
|
1159
1586
|
const start = Math.max(0, stat.size - MAX_PREVIEW_BYTES);
|
|
@@ -1226,6 +1653,638 @@ export function lhUiautoPlugin() {
|
|
|
1226
1653
|
return sendJson(res, 200, { ok: true });
|
|
1227
1654
|
}
|
|
1228
1655
|
|
|
1656
|
+
/* ==================== AI 生成:浏览器探索 ==================== */
|
|
1657
|
+
|
|
1658
|
+
/** 生成会话与应用图标属于本机数据,放 `.lantern/local/uiauto`,不落进项目目录 */
|
|
1659
|
+
const agentBaseDir = uiautoCachePaths(root).dir;
|
|
1660
|
+
|
|
1661
|
+
/** 应用图标缓存目录:抽一次存下来,下次直接读 */
|
|
1662
|
+
const appIconDir = path.join(agentBaseDir, 'app-icons');
|
|
1663
|
+
|
|
1664
|
+
/** 项目的 playwright 配置里有没有 baseURL(没有时只给 config 补丁建议) */
|
|
1665
|
+
const projectHasBaseURL = (dir) => {
|
|
1666
|
+
const name = findPlaywrightConfig(dir);
|
|
1667
|
+
if (!name) return false;
|
|
1668
|
+
try {
|
|
1669
|
+
return /baseURL\s*:/.test(fs.readFileSync(path.join(dir, name), 'utf8'));
|
|
1670
|
+
} catch {
|
|
1671
|
+
return false;
|
|
1672
|
+
}
|
|
1673
|
+
};
|
|
1674
|
+
|
|
1675
|
+
const agentProject = (projectId) => {
|
|
1676
|
+
const store = readStore(root).store;
|
|
1677
|
+
return findProject(store, projectId);
|
|
1678
|
+
};
|
|
1679
|
+
|
|
1680
|
+
const requireExplorer = async (sessionId) => {
|
|
1681
|
+
const record = readGeneratedSession(agentBaseDir, sessionId);
|
|
1682
|
+
if (!record) throw new Error('生成会话不存在');
|
|
1683
|
+
const project = agentProject(record.projectId);
|
|
1684
|
+
if (!project) throw new Error('项目不存在或已移出挂载列表');
|
|
1685
|
+
if (!hasExplorer(sessionId)) {
|
|
1686
|
+
await startExplorer({
|
|
1687
|
+
baseDir: agentBaseDir,
|
|
1688
|
+
project,
|
|
1689
|
+
sessionId,
|
|
1690
|
+
baseURL: record.baseURL || '',
|
|
1691
|
+
headed: record.headed !== false,
|
|
1692
|
+
storageState: record.storageState || '',
|
|
1693
|
+
});
|
|
1694
|
+
// 浏览器起得来才算真的在探索;失败时不改状态,前端能看出会话还停在草稿
|
|
1695
|
+
if (record.status !== 'exploring') {
|
|
1696
|
+
saveGeneratedSession(agentBaseDir, { id: sessionId, status: 'exploring' });
|
|
1697
|
+
}
|
|
1698
|
+
}
|
|
1699
|
+
return { record, project };
|
|
1700
|
+
};
|
|
1701
|
+
|
|
1702
|
+
if (method === 'GET' && tail.startsWith('/agent/shot/')) {
|
|
1703
|
+
const rest = tail.slice('/agent/shot/'.length);
|
|
1704
|
+
const slash = rest.indexOf('/');
|
|
1705
|
+
const sessionId = slash === -1 ? '' : rest.slice(0, slash);
|
|
1706
|
+
const file = slash === -1 ? '' : decodeURIComponent(rest.slice(slash + 1));
|
|
1707
|
+
if (!/^[A-Za-z0-9_-]+$/.test(sessionId) || !/^[\w.-]+\.png$/.test(file)) {
|
|
1708
|
+
return sendJson(res, 400, { ok: false, error: '截图路径不合法' });
|
|
1709
|
+
}
|
|
1710
|
+
const dir = sessionShotsDir(agentBaseDir, sessionId);
|
|
1711
|
+
const abs = path.join(dir, file);
|
|
1712
|
+
if (!isPathInside(dir, abs) || !fs.existsSync(abs)) {
|
|
1713
|
+
return sendJson(res, 404, { ok: false, error: '截图不存在' });
|
|
1714
|
+
}
|
|
1715
|
+
res.statusCode = 200;
|
|
1716
|
+
res.setHeader('Content-Type', 'image/png');
|
|
1717
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
1718
|
+
fs.createReadStream(abs).pipe(res);
|
|
1719
|
+
return;
|
|
1720
|
+
}
|
|
1721
|
+
|
|
1722
|
+
/** 建 / 复用生成会话(不启动浏览器):规划步骤、改计划都先落在会话上 */
|
|
1723
|
+
const createAgentSession = (body) => {
|
|
1724
|
+
const existingId = text(body.sessionId, 64);
|
|
1725
|
+
const existing = existingId ? readGeneratedSession(agentBaseDir, existingId) : null;
|
|
1726
|
+
const project = agentProject(text(body.projectId, 64) || existing?.projectId || '');
|
|
1727
|
+
if (!project) return { error: '项目不存在' };
|
|
1728
|
+
const requestedStorage = text(body.storageState, 300);
|
|
1729
|
+
// 项目上记的登录态可能是 `-`(用户明确不要登录态),别把它当路径传下去
|
|
1730
|
+
const projectStorage = text(project.storageState, 300);
|
|
1731
|
+
const rememberStorage = projectStorage === '-' ? '' : projectStorage;
|
|
1732
|
+
// 优先级:面板这次提交的值 → 项目上记的 → 上次会话用的 → 自动探测
|
|
1733
|
+
// (项目配置优先,避免刚在面板改完又被旧会话里的文件顶回去)
|
|
1734
|
+
const storageState =
|
|
1735
|
+
requestedStorage === '-'
|
|
1736
|
+
? ''
|
|
1737
|
+
: requestedStorage ||
|
|
1738
|
+
rememberStorage ||
|
|
1739
|
+
(existing?.projectId === project.id ? existing.storageState : '') ||
|
|
1740
|
+
safeDetectStorageState(project.dir);
|
|
1741
|
+
const target = text(body.target, 16);
|
|
1742
|
+
// 起始地址:请求里带了就以请求为准(用户可能刚改),否则用项目记的 / 项目配置里探测到的
|
|
1743
|
+
const baseURL =
|
|
1744
|
+
text(body.baseURL, 500) || project.baseURL || safeDetectBaseURL(project.dir) || '';
|
|
1745
|
+
// 重新规划 / 重新探索:上一轮的步骤与试跑结果作废,否则旧 IR 会被当成这次的产出
|
|
1746
|
+
// (代码页与试跑都显示上一轮内容)。活动日志不跟着清:它按时间累积,
|
|
1747
|
+
// 用户想看上一轮跑到哪一步;要清由「清除活动日志」显式传 clearActivity。
|
|
1748
|
+
const reset = body.reset === true;
|
|
1749
|
+
const clearActivity = body.clearActivity === true;
|
|
1750
|
+
if (existing && existing.projectId === project.id) {
|
|
1751
|
+
const session = saveGeneratedSession(agentBaseDir, {
|
|
1752
|
+
id: existing.id,
|
|
1753
|
+
title: text(body.title, 200) || existing.title,
|
|
1754
|
+
target: target === 'python' ? 'python' : target === 'ts' ? 'ts' : undefined,
|
|
1755
|
+
baseURL: baseURL || existing.baseURL,
|
|
1756
|
+
storageState,
|
|
1757
|
+
source: text(body.source, 4000) || existing.source,
|
|
1758
|
+
headed: typeof body.headed === 'boolean' ? body.headed : existing.headed,
|
|
1759
|
+
plan: Array.isArray(body.plan) ? body.plan : undefined,
|
|
1760
|
+
...(reset
|
|
1761
|
+
? { ir: null, lastVerify: null, savedPath: '', status: 'draft' }
|
|
1762
|
+
: {
|
|
1763
|
+
// 已写入 / 已试跑通过的会话不要被打回草稿
|
|
1764
|
+
status:
|
|
1765
|
+
existing.status === 'written' || existing.status === 'verified'
|
|
1766
|
+
? existing.status
|
|
1767
|
+
: existing.status === 'exploring'
|
|
1768
|
+
? 'exploring'
|
|
1769
|
+
: 'draft',
|
|
1770
|
+
}),
|
|
1771
|
+
...(clearActivity ? { activity: [] } : {}),
|
|
1772
|
+
});
|
|
1773
|
+
return { project, session };
|
|
1774
|
+
}
|
|
1775
|
+
const session = saveGeneratedSession(agentBaseDir, {
|
|
1776
|
+
projectId: project.id,
|
|
1777
|
+
title: text(body.title, 200) || '未命名流程',
|
|
1778
|
+
target: target === 'python' ? 'python' : 'ts',
|
|
1779
|
+
baseURL,
|
|
1780
|
+
storageState,
|
|
1781
|
+
source: text(body.source, 4000),
|
|
1782
|
+
headed: body.headed !== false,
|
|
1783
|
+
plan: Array.isArray(body.plan) ? body.plan : undefined,
|
|
1784
|
+
status: 'draft',
|
|
1785
|
+
});
|
|
1786
|
+
return { project, session };
|
|
1787
|
+
};
|
|
1788
|
+
|
|
1789
|
+
if (method === 'POST' && tail === '/agent/prepare') {
|
|
1790
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
1791
|
+
const created = createAgentSession(body);
|
|
1792
|
+
if (created.error) return sendJson(res, 404, { ok: false, error: created.error });
|
|
1793
|
+
cleanupStaleDrafts(created.project.dir);
|
|
1794
|
+
return sendJson(res, 200, {
|
|
1795
|
+
ok: true,
|
|
1796
|
+
session: created.session,
|
|
1797
|
+
suggestedPath: suggestedPath({ project: created.project, session: created.session }),
|
|
1798
|
+
draft: draftSummary({ project: created.project, session: created.session }),
|
|
1799
|
+
});
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1802
|
+
if (method === 'POST' && tail === '/agent/start') {
|
|
1803
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
1804
|
+
const created = createAgentSession(body);
|
|
1805
|
+
if (created.error) return sendJson(res, 404, { ok: false, error: created.error });
|
|
1806
|
+
const { project, session } = created;
|
|
1807
|
+
const started = saveGeneratedSession(agentBaseDir, {
|
|
1808
|
+
id: session.id,
|
|
1809
|
+
status: 'exploring',
|
|
1810
|
+
});
|
|
1811
|
+
await startExplorer({
|
|
1812
|
+
baseDir: agentBaseDir,
|
|
1813
|
+
project,
|
|
1814
|
+
sessionId: started.id,
|
|
1815
|
+
baseURL: started.baseURL,
|
|
1816
|
+
headed: started.headed,
|
|
1817
|
+
storageState: started.storageState,
|
|
1818
|
+
});
|
|
1819
|
+
return sendJson(res, 200, {
|
|
1820
|
+
ok: true,
|
|
1821
|
+
session: started,
|
|
1822
|
+
suggestedPath: suggestedPath({ project, session: started }),
|
|
1823
|
+
});
|
|
1824
|
+
}
|
|
1825
|
+
|
|
1826
|
+
if (method === 'POST' && tail === '/agent/open') {
|
|
1827
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
1828
|
+
const sessionId = text(body.sessionId, 64);
|
|
1829
|
+
await requireExplorer(sessionId);
|
|
1830
|
+
const result = await callExplorer(sessionId, 'open', { url: text(body.url, 2000) });
|
|
1831
|
+
return sendJson(res, 200, { ok: true, ...result });
|
|
1832
|
+
}
|
|
1833
|
+
|
|
1834
|
+
if (method === 'POST' && tail === '/agent/snapshot') {
|
|
1835
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
1836
|
+
const sessionId = text(body.sessionId, 64);
|
|
1837
|
+
await requireExplorer(sessionId);
|
|
1838
|
+
const result = await callExplorer(sessionId, 'snapshot', {
|
|
1839
|
+
depth: intOr(body.depth, 6, 1, 20),
|
|
1840
|
+
targetRef: text(body.targetRef, 32),
|
|
1841
|
+
});
|
|
1842
|
+
return sendJson(res, 200, { ok: true, ...result });
|
|
1843
|
+
}
|
|
1844
|
+
|
|
1845
|
+
if (method === 'POST' && tail === '/agent/action') {
|
|
1846
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
1847
|
+
const sessionId = text(body.sessionId, 64);
|
|
1848
|
+
await requireExplorer(sessionId);
|
|
1849
|
+
const result = await callExplorer(
|
|
1850
|
+
sessionId,
|
|
1851
|
+
'action',
|
|
1852
|
+
{
|
|
1853
|
+
action: text(body.action, 32),
|
|
1854
|
+
ref: text(body.ref, 32),
|
|
1855
|
+
text: typeof body.text === 'string' ? body.text.slice(0, 4000) : '',
|
|
1856
|
+
value: typeof body.value === 'string' ? body.value.slice(0, 4000) : '',
|
|
1857
|
+
key: text(body.key, 40),
|
|
1858
|
+
note: text(body.note, 200),
|
|
1859
|
+
snapshot: body.snapshot !== false,
|
|
1860
|
+
settle: intOr(body.settle, 300, 0, 10000),
|
|
1861
|
+
},
|
|
1862
|
+
90000,
|
|
1863
|
+
);
|
|
1864
|
+
return sendJson(res, 200, { ok: true, ...result });
|
|
1865
|
+
}
|
|
1866
|
+
|
|
1867
|
+
if (method === 'POST' && tail === '/agent/probe') {
|
|
1868
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
1869
|
+
const sessionId = text(body.sessionId, 64);
|
|
1870
|
+
await requireExplorer(sessionId);
|
|
1871
|
+
const result = await callExplorer(sessionId, 'probe', { ref: text(body.ref, 32) });
|
|
1872
|
+
// 带 stepId 时顺手把定位器回填到左侧计划,省得模型再写一遍
|
|
1873
|
+
const stepId = text(body.stepId, 40);
|
|
1874
|
+
let plan = null;
|
|
1875
|
+
let planStep = null;
|
|
1876
|
+
if (stepId) {
|
|
1877
|
+
const record = readGeneratedSession(agentBaseDir, sessionId);
|
|
1878
|
+
if (record) {
|
|
1879
|
+
plan = bindPlanStep(record.plan || [], stepId, result);
|
|
1880
|
+
const saved = saveGeneratedSession(agentBaseDir, { id: sessionId, plan });
|
|
1881
|
+
plan = saved.plan;
|
|
1882
|
+
planStep = plan.find((step) => step.id === stepId) ?? null;
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1885
|
+
return sendJson(res, 200, {
|
|
1886
|
+
ok: true,
|
|
1887
|
+
...result,
|
|
1888
|
+
warning: result.warning ?? '',
|
|
1889
|
+
plan,
|
|
1890
|
+
planStep,
|
|
1891
|
+
});
|
|
1892
|
+
}
|
|
1893
|
+
|
|
1894
|
+
if (method === 'POST' && (tail === '/agent/console' || tail === '/agent/network')) {
|
|
1895
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
1896
|
+
const sessionId = text(body.sessionId, 64);
|
|
1897
|
+
// 控制台 / 网络是「读」操作:没有在跑的浏览器就直接回空表。
|
|
1898
|
+
// 这里以前走 requireExplorer,导致前端一切到这个 Tab(含 HMR 重载后恢复)
|
|
1899
|
+
// 就凭空拉起一个有头浏览器窗口(baseURL 不可达时停在 about:blank)。
|
|
1900
|
+
if (!hasExplorer(sessionId)) {
|
|
1901
|
+
return sendJson(res, 200, {
|
|
1902
|
+
ok: true,
|
|
1903
|
+
messages: [],
|
|
1904
|
+
requests: [],
|
|
1905
|
+
running: false,
|
|
1906
|
+
});
|
|
1907
|
+
}
|
|
1908
|
+
const cmd = tail === '/agent/console' ? 'console' : 'network';
|
|
1909
|
+
const result = await callExplorer(sessionId, cmd, {});
|
|
1910
|
+
return sendJson(res, 200, { ok: true, ...result });
|
|
1911
|
+
}
|
|
1912
|
+
|
|
1913
|
+
if (method === 'POST' && tail === '/agent/wait') {
|
|
1914
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
1915
|
+
const sessionId = text(body.sessionId, 64);
|
|
1916
|
+
await requireExplorer(sessionId);
|
|
1917
|
+
const result = await callExplorer(
|
|
1918
|
+
sessionId,
|
|
1919
|
+
'waitFor',
|
|
1920
|
+
{
|
|
1921
|
+
text: text(body.text, 200),
|
|
1922
|
+
ms: intOr(body.ms, 500, 0, 15000),
|
|
1923
|
+
timeout: intOr(body.timeout, 15000, 1000, 60000),
|
|
1924
|
+
},
|
|
1925
|
+
90000,
|
|
1926
|
+
);
|
|
1927
|
+
return sendJson(res, 200, { ok: true, ...result });
|
|
1928
|
+
}
|
|
1929
|
+
|
|
1930
|
+
if (method === 'POST' && tail === '/agent/screenshot') {
|
|
1931
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
1932
|
+
const sessionId = text(body.sessionId, 64);
|
|
1933
|
+
await requireExplorer(sessionId);
|
|
1934
|
+
const result = await callExplorer(sessionId, 'screenshot', {
|
|
1935
|
+
label: text(body.label, 60),
|
|
1936
|
+
fullPage: Boolean(body.fullPage),
|
|
1937
|
+
});
|
|
1938
|
+
return sendJson(res, 200, {
|
|
1939
|
+
ok: true,
|
|
1940
|
+
...result,
|
|
1941
|
+
url: `${PREFIX}/agent/shot/${sessionId}/${encodeURIComponent(result.file)}`,
|
|
1942
|
+
});
|
|
1943
|
+
}
|
|
1944
|
+
|
|
1945
|
+
if (method === 'POST' && tail === '/agent/close') {
|
|
1946
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
1947
|
+
const sessionId = text(body.sessionId, 64);
|
|
1948
|
+
const stopped = stopExplorer(sessionId);
|
|
1949
|
+
const record = readGeneratedSession(agentBaseDir, sessionId);
|
|
1950
|
+
if (record && record.status === 'exploring') {
|
|
1951
|
+
saveGeneratedSession(agentBaseDir, { id: sessionId, status: 'draft' });
|
|
1952
|
+
}
|
|
1953
|
+
return sendJson(res, 200, { ok: true, stopped });
|
|
1954
|
+
}
|
|
1955
|
+
|
|
1956
|
+
if (method === 'POST' && tail === '/agent/save') {
|
|
1957
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
1958
|
+
const sessionId = text(body.sessionId, 64);
|
|
1959
|
+
if (!sessionId) return sendJson(res, 400, { ok: false, error: '缺少 sessionId' });
|
|
1960
|
+
const existing = readGeneratedSession(agentBaseDir, sessionId);
|
|
1961
|
+
if (!existing) return sendJson(res, 404, { ok: false, error: '生成会话不存在' });
|
|
1962
|
+
const project = agentProject(existing.projectId);
|
|
1963
|
+
if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
|
|
1964
|
+
// 模型提交的计划只合并、不覆盖:用户手改的步骤不能被模型重写掉。
|
|
1965
|
+
// 空计划默认不落盘(前端丢状态时最怕把整份计划冲掉),
|
|
1966
|
+
// 用户在计划里删到空要显式带 allowEmptyPlan。
|
|
1967
|
+
const planPatch = Array.isArray(body.plan) ? body.plan : undefined;
|
|
1968
|
+
const nextPlan =
|
|
1969
|
+
planPatch === undefined
|
|
1970
|
+
? undefined
|
|
1971
|
+
: body.mergePlan === true
|
|
1972
|
+
? mergePlanWithModel(existing.plan, planPatch)
|
|
1973
|
+
: planPatch.length || body.allowEmptyPlan === true
|
|
1974
|
+
? planPatch
|
|
1975
|
+
: existing.plan || [];
|
|
1976
|
+
const saved = saveGeneratedSession(agentBaseDir, {
|
|
1977
|
+
id: sessionId,
|
|
1978
|
+
title: text(body.title, 200) || existing.title,
|
|
1979
|
+
target: body.target === 'python' ? 'python' : body.target === 'ts' ? 'ts' : undefined,
|
|
1980
|
+
baseURL:
|
|
1981
|
+
typeof body.baseURL === 'string' ? text(body.baseURL, 500) : existing.baseURL,
|
|
1982
|
+
source: typeof body.source === 'string' ? text(body.source, 4000) : existing.source,
|
|
1983
|
+
ir: body.ir ? body.ir : existing.ir,
|
|
1984
|
+
plan: nextPlan,
|
|
1985
|
+
activity: Array.isArray(body.activity)
|
|
1986
|
+
? body.replaceActivity === true
|
|
1987
|
+
? body.activity
|
|
1988
|
+
: mergeActivityLog(existing.activity, body.activity)
|
|
1989
|
+
: undefined,
|
|
1990
|
+
status: text(body.status, 40) || existing.status,
|
|
1991
|
+
});
|
|
1992
|
+
const emitted = emitCode(saved.ir || {}, saved.target);
|
|
1993
|
+
return sendJson(res, 200, {
|
|
1994
|
+
ok: true,
|
|
1995
|
+
session: saved,
|
|
1996
|
+
code: emitted.code,
|
|
1997
|
+
filename: emitted.filename,
|
|
1998
|
+
suggestedPath: suggestedPath({ project, session: saved }),
|
|
1999
|
+
});
|
|
2000
|
+
}
|
|
2001
|
+
|
|
2002
|
+
if (method === 'POST' && tail === '/agent/emit') {
|
|
2003
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
2004
|
+
const emitted = emitCode(body.ir || {}, body.target);
|
|
2005
|
+
// 多文件:同一份 IR 拆成 spec + page object(+ fixture),旧字段保留给单文件调用点
|
|
2006
|
+
const testDir = text(body.testDir, 200) || 'tests';
|
|
2007
|
+
const multi = emitFiles(body.ir || {}, body.target, {
|
|
2008
|
+
testDir,
|
|
2009
|
+
hasBaseURL: Boolean(body.hasBaseURL),
|
|
2010
|
+
});
|
|
2011
|
+
return sendJson(res, 200, {
|
|
2012
|
+
ok: true,
|
|
2013
|
+
code: emitted.code,
|
|
2014
|
+
filename: emitted.filename,
|
|
2015
|
+
language: emitted.language,
|
|
2016
|
+
files: multi.files,
|
|
2017
|
+
configPatch: multi.configPatch,
|
|
2018
|
+
});
|
|
2019
|
+
}
|
|
2020
|
+
|
|
2021
|
+
if (method === 'POST' && tail === '/agent/verify') {
|
|
2022
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
2023
|
+
const sessionId = text(body.sessionId, 64);
|
|
2024
|
+
let record = readGeneratedSession(agentBaseDir, sessionId);
|
|
2025
|
+
if (!record) return sendJson(res, 404, { ok: false, error: '生成会话不存在' });
|
|
2026
|
+
if (body.ir) {
|
|
2027
|
+
record = saveGeneratedSession(agentBaseDir, {
|
|
2028
|
+
id: sessionId,
|
|
2029
|
+
ir: body.ir,
|
|
2030
|
+
target:
|
|
2031
|
+
body.target === 'python' ? 'python' : body.target === 'ts' ? 'ts' : undefined,
|
|
2032
|
+
});
|
|
2033
|
+
}
|
|
2034
|
+
const project = agentProject(record.projectId);
|
|
2035
|
+
if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
|
|
2036
|
+
const result = await verifySession({
|
|
2037
|
+
project,
|
|
2038
|
+
session: record,
|
|
2039
|
+
timeoutMs: intOr(body.timeoutMs, 180000, 10000, 600000),
|
|
2040
|
+
});
|
|
2041
|
+
saveGeneratedSession(agentBaseDir, {
|
|
2042
|
+
id: sessionId,
|
|
2043
|
+
status: result.passed ? 'verified' : 'failed',
|
|
2044
|
+
ir: record.ir,
|
|
2045
|
+
lastVerify: {
|
|
2046
|
+
at: new Date().toISOString(),
|
|
2047
|
+
passed: Boolean(result.passed),
|
|
2048
|
+
exitCode: result.exitCode ?? null,
|
|
2049
|
+
durationMs: result.durationMs ?? 0,
|
|
2050
|
+
log: String(result.log ?? '').slice(-4000),
|
|
2051
|
+
},
|
|
2052
|
+
});
|
|
2053
|
+
return sendJson(res, 200, {
|
|
2054
|
+
...result,
|
|
2055
|
+
suggestedPath: suggestedPath({ project, session: record }),
|
|
2056
|
+
});
|
|
2057
|
+
}
|
|
2058
|
+
|
|
2059
|
+
if (method === 'POST' && tail === '/agent/write') {
|
|
2060
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
2061
|
+
const sessionId = text(body.sessionId, 64);
|
|
2062
|
+
let record = readGeneratedSession(agentBaseDir, sessionId);
|
|
2063
|
+
if (!record) return sendJson(res, 404, { ok: false, error: '生成会话不存在' });
|
|
2064
|
+
const project = agentProject(record.projectId);
|
|
2065
|
+
if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
|
|
2066
|
+
|
|
2067
|
+
// 前端没给文件时按会话实时出码(含 page object),保证写的就是当前步骤
|
|
2068
|
+
let files = Array.isArray(body.files) ? body.files : [];
|
|
2069
|
+
if (!files.length) {
|
|
2070
|
+
if (!record.ir?.steps?.length) {
|
|
2071
|
+
return sendJson(res, 409, { ok: false, error: '还没有生成步骤,先探索或试跑一次' });
|
|
2072
|
+
}
|
|
2073
|
+
const emitted = emitFiles(record.ir || {}, record.target, {
|
|
2074
|
+
testDir: detectPlaywrightTestDir(project.dir),
|
|
2075
|
+
hasBaseURL: projectHasBaseURL(project.dir),
|
|
2076
|
+
});
|
|
2077
|
+
files = emitted.files;
|
|
2078
|
+
}
|
|
2079
|
+
|
|
2080
|
+
const result = writeGeneratedFiles({
|
|
2081
|
+
project,
|
|
2082
|
+
session: record,
|
|
2083
|
+
files: files.map((item) => ({
|
|
2084
|
+
path: text(item.path, 500),
|
|
2085
|
+
content: String(item.content ?? ''),
|
|
2086
|
+
force: Boolean(item.force),
|
|
2087
|
+
role: text(item.role, 20),
|
|
2088
|
+
})),
|
|
2089
|
+
force: Boolean(body.force),
|
|
2090
|
+
});
|
|
2091
|
+
if (result.ok) {
|
|
2092
|
+
const savedPaths = result.paths.slice();
|
|
2093
|
+
// 主用例(spec)优先,试跑 / 验收 / 打开草稿都从它出发
|
|
2094
|
+
const spec = files.find((item) => item.role === 'spec')?.path || savedPaths[0] || '';
|
|
2095
|
+
record = saveGeneratedSession(agentBaseDir, {
|
|
2096
|
+
id: sessionId,
|
|
2097
|
+
status: 'written',
|
|
2098
|
+
savedPath: spec,
|
|
2099
|
+
savedPaths,
|
|
2100
|
+
changes: result.changes,
|
|
2101
|
+
});
|
|
2102
|
+
}
|
|
2103
|
+
return sendJson(res, result.ok ? 200 : 409, {
|
|
2104
|
+
...result,
|
|
2105
|
+
savedPaths: result.ok ? result.paths : undefined,
|
|
2106
|
+
suggestedPath: suggestedPath({ project, session: record }),
|
|
2107
|
+
});
|
|
2108
|
+
}
|
|
2109
|
+
|
|
2110
|
+
if (method === 'POST' && tail === '/agent/debug') {
|
|
2111
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
2112
|
+
const sessionId = text(body.sessionId, 64);
|
|
2113
|
+
const record = readGeneratedSession(agentBaseDir, sessionId);
|
|
2114
|
+
if (!record) return sendJson(res, 404, { ok: false, error: '生成会话不存在' });
|
|
2115
|
+
const project = agentProject(record.projectId);
|
|
2116
|
+
if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
|
|
2117
|
+
const result = await debugSession({
|
|
2118
|
+
project,
|
|
2119
|
+
session: record,
|
|
2120
|
+
mode: body.mode === 'ui' ? 'ui' : 'headed',
|
|
2121
|
+
});
|
|
2122
|
+
return sendJson(res, 200, result);
|
|
2123
|
+
}
|
|
2124
|
+
|
|
2125
|
+
if (method === 'POST' && tail === '/agent/debug/stop') {
|
|
2126
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
2127
|
+
const sessionId = text(body.sessionId, 64);
|
|
2128
|
+
return sendJson(res, 200, { ok: true, stopped: stopDebugSession(sessionId) });
|
|
2129
|
+
}
|
|
2130
|
+
|
|
2131
|
+
if (method === 'GET' && tail === '/agent/changes') {
|
|
2132
|
+
const sessionId = text(parsed.searchParams.get('sessionId'), 64);
|
|
2133
|
+
const record = readGeneratedSession(agentBaseDir, sessionId);
|
|
2134
|
+
if (!record) return sendJson(res, 404, { ok: false, error: '生成会话不存在' });
|
|
2135
|
+
const project = agentProject(record.projectId);
|
|
2136
|
+
if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
|
|
2137
|
+
const git = await gitStatusSummary(project.dir);
|
|
2138
|
+
return sendJson(res, 200, {
|
|
2139
|
+
ok: true,
|
|
2140
|
+
changes: sessionChanges(record),
|
|
2141
|
+
git,
|
|
2142
|
+
draft: draftSummary({ project, session: record }),
|
|
2143
|
+
});
|
|
2144
|
+
}
|
|
2145
|
+
|
|
2146
|
+
if (method === 'GET' && tail === '/agent/apps') {
|
|
2147
|
+
const apps = await listOpenApps();
|
|
2148
|
+
return sendJson(res, 200, {
|
|
2149
|
+
ok: true,
|
|
2150
|
+
apps: apps.map((app) => ({
|
|
2151
|
+
...app,
|
|
2152
|
+
iconUrl: app.appPath
|
|
2153
|
+
? `${PREFIX}/agent/app-icon?id=${encodeURIComponent(app.id)}`
|
|
2154
|
+
: '',
|
|
2155
|
+
})),
|
|
2156
|
+
defaultId: defaultOpenApp(apps),
|
|
2157
|
+
});
|
|
2158
|
+
}
|
|
2159
|
+
|
|
2160
|
+
if (method === 'GET' && tail === '/agent/app-icon') {
|
|
2161
|
+
const id = text(parsed.searchParams.get('id'), 40);
|
|
2162
|
+
const apps = await listOpenApps();
|
|
2163
|
+
const app = apps.find((item) => item.id === id);
|
|
2164
|
+
if (!app) return sendJson(res, 404, { ok: false, error: '应用不存在' });
|
|
2165
|
+
const file = await appIcon(app, appIconDir);
|
|
2166
|
+
if (!file) return sendJson(res, 404, { ok: false, error: '没有可用图标' });
|
|
2167
|
+
res.statusCode = 200;
|
|
2168
|
+
res.setHeader('Content-Type', 'image/png');
|
|
2169
|
+
res.setHeader('Cache-Control', 'public, max-age=604800');
|
|
2170
|
+
fs.createReadStream(file).pipe(res);
|
|
2171
|
+
return;
|
|
2172
|
+
}
|
|
2173
|
+
|
|
2174
|
+
if (method === 'POST' && tail === '/agent/reveal') {
|
|
2175
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
2176
|
+
const sessionId = text(body.sessionId, 64);
|
|
2177
|
+
const record = sessionId ? readGeneratedSession(agentBaseDir, sessionId) : null;
|
|
2178
|
+
const project = agentProject(text(body.projectId, 64) || record?.projectId || '');
|
|
2179
|
+
if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
|
|
2180
|
+
const rel = text(body.path, 500);
|
|
2181
|
+
const abs = rel ? resolveInside(project.dir, rel) : project.dir;
|
|
2182
|
+
if (!abs) return sendJson(res, 400, { ok: false, error: '路径不合法' });
|
|
2183
|
+
if (!fs.existsSync(abs)) {
|
|
2184
|
+
return sendJson(res, 404, { ok: false, error: '文件还不存在,先试跑或写入项目' });
|
|
2185
|
+
}
|
|
2186
|
+
// trace 要用项目自带的 show-trace 打开,不能丢给解压软件
|
|
2187
|
+
if (/trace\.zip$/i.test(rel)) {
|
|
2188
|
+
const shown = showTrace({ project, relPath: rel });
|
|
2189
|
+
return sendJson(res, shown.ok ? 200 : 500, shown);
|
|
2190
|
+
}
|
|
2191
|
+
const apps = await listOpenApps();
|
|
2192
|
+
const wanted = text(body.app, 40);
|
|
2193
|
+
const app =
|
|
2194
|
+
apps.find((item) => item.id === wanted) ??
|
|
2195
|
+
apps.find((item) => item.id === defaultOpenApp(apps));
|
|
2196
|
+
try {
|
|
2197
|
+
await openWith({
|
|
2198
|
+
abs,
|
|
2199
|
+
dir: project.dir,
|
|
2200
|
+
app,
|
|
2201
|
+
line: Number(body.line) > 0 ? Number(body.line) : 0,
|
|
2202
|
+
});
|
|
2203
|
+
return sendJson(res, 200, { ok: true, path: rel || '.', app: app?.id ?? '' });
|
|
2204
|
+
} catch (e) {
|
|
2205
|
+
return sendJson(res, 500, {
|
|
2206
|
+
ok: false,
|
|
2207
|
+
error: e instanceof Error ? e.message : String(e),
|
|
2208
|
+
});
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
|
|
2212
|
+
if (method === 'POST' && tail === '/agent/run-file') {
|
|
2213
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
2214
|
+
const sessionId = text(body.sessionId, 64);
|
|
2215
|
+
const record = readGeneratedSession(agentBaseDir, sessionId);
|
|
2216
|
+
if (!record) return sendJson(res, 404, { ok: false, error: '生成会话不存在' });
|
|
2217
|
+
const project = agentProject(record.projectId);
|
|
2218
|
+
if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
|
|
2219
|
+
const result = await runProjectFile({
|
|
2220
|
+
project,
|
|
2221
|
+
session: record,
|
|
2222
|
+
relPath: text(body.path, 500) || record.savedPath || '',
|
|
2223
|
+
timeoutMs: intOr(body.timeoutMs, 180000, 10000, 600000),
|
|
2224
|
+
});
|
|
2225
|
+
return sendJson(res, 200, result);
|
|
2226
|
+
}
|
|
2227
|
+
|
|
2228
|
+
if (method === 'POST' && tail === '/agent/draft/clean') {
|
|
2229
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
2230
|
+
const sessionId = text(body.sessionId, 64);
|
|
2231
|
+
const record = readGeneratedSession(agentBaseDir, sessionId);
|
|
2232
|
+
if (!record) return sendJson(res, 404, { ok: false, error: '生成会话不存在' });
|
|
2233
|
+
const project = agentProject(record.projectId);
|
|
2234
|
+
if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
|
|
2235
|
+
stopDebugSession(sessionId);
|
|
2236
|
+
cleanupDraft(project.dir, sessionId);
|
|
2237
|
+
return sendJson(res, 200, {
|
|
2238
|
+
ok: true,
|
|
2239
|
+
draft: draftSummary({ project, session: record }),
|
|
2240
|
+
});
|
|
2241
|
+
}
|
|
2242
|
+
|
|
2243
|
+
if (method === 'GET' && tail === '/agent/sessions') {
|
|
2244
|
+
const projectId = text(parsed.searchParams.get('projectId'), 64);
|
|
2245
|
+
return sendJson(res, 200, {
|
|
2246
|
+
ok: true,
|
|
2247
|
+
sessions: listGeneratedSessions(agentBaseDir, projectId),
|
|
2248
|
+
});
|
|
2249
|
+
}
|
|
2250
|
+
|
|
2251
|
+
if (method === 'GET' && tail === '/agent/session') {
|
|
2252
|
+
const id = text(parsed.searchParams.get('id'), 64);
|
|
2253
|
+
const record = readGeneratedSession(agentBaseDir, id);
|
|
2254
|
+
if (!record) return sendJson(res, 404, { ok: false, error: '生成会话不存在' });
|
|
2255
|
+
const project = agentProject(record.projectId);
|
|
2256
|
+
const emitted = emitCode(record.ir || {}, record.target);
|
|
2257
|
+
return sendJson(res, 200, {
|
|
2258
|
+
ok: true,
|
|
2259
|
+
session: record,
|
|
2260
|
+
code: emitted.code,
|
|
2261
|
+
filename: emitted.filename,
|
|
2262
|
+
suggestedPath: project ? suggestedPath({ project, session: record }) : '',
|
|
2263
|
+
exploring: hasExplorer(id),
|
|
2264
|
+
debugging: hasDebugSession(id),
|
|
2265
|
+
changes: sessionChanges(record),
|
|
2266
|
+
draft: project ? draftSummary({ project, session: record }) : null,
|
|
2267
|
+
});
|
|
2268
|
+
}
|
|
2269
|
+
|
|
2270
|
+
if (method === 'DELETE' && tail === '/agent/session') {
|
|
2271
|
+
const id = text(parsed.searchParams.get('id'), 64);
|
|
2272
|
+
if (!id) return sendJson(res, 400, { ok: false, error: '缺少 id' });
|
|
2273
|
+
stopExplorer(id);
|
|
2274
|
+
stopDebugSession(id);
|
|
2275
|
+
const record = readGeneratedSession(agentBaseDir, id);
|
|
2276
|
+
const project = record ? agentProject(record.projectId) : null;
|
|
2277
|
+
if (project) cleanupDraft(project.dir, id);
|
|
2278
|
+
const dir = sessionsDir(agentBaseDir);
|
|
2279
|
+
const file = path.join(dir, `${id}.json`);
|
|
2280
|
+
if (!isPathInside(dir, file)) {
|
|
2281
|
+
return sendJson(res, 400, { ok: false, error: '路径不合法' });
|
|
2282
|
+
}
|
|
2283
|
+
fs.rmSync(file, { force: true });
|
|
2284
|
+
fs.rmSync(path.join(dir, id), { recursive: true, force: true });
|
|
2285
|
+
return sendJson(res, 200, { ok: true });
|
|
2286
|
+
}
|
|
2287
|
+
|
|
1229
2288
|
return next();
|
|
1230
2289
|
} catch (err) {
|
|
1231
2290
|
const message = err instanceof Error ? err.message : String(err);
|