lantern-harness 0.1.8 → 0.1.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +106 -0
- package/README.md +7 -7
- package/builtin/session/lh-fs.mjs +32 -14
- package/cli/server.mjs +2 -0
- package/config/app.defaults.json +1 -0
- package/dist/500.html +258 -22
- package/dist/_astro/Base.BOY6F0mi.css +1 -0
- package/dist/_astro/Base.astro_astro_type_script_index_0_lang.C30xtpc6.js +1 -0
- package/dist/_astro/CaseExecBoard.Dttqp0wg.js +1 -0
- package/dist/_astro/CaseGenerateApp.DqW_nWMc.js +9 -0
- package/dist/_astro/CasesLibrary.8aMUUGp_.js +1 -0
- package/dist/_astro/ChatApp.BLxf0h1d.js +219 -0
- package/dist/_astro/ColumnResize.BEkEW7qw.js +1 -0
- package/dist/_astro/{ConfirmDialog.CBVsDJ8f.js → ConfirmDialog.BZzZWDci.js} +1 -1
- package/dist/_astro/{DashboardBoard.Bd3eUPwZ.js → DashboardBoard.CkSbhEDI.js} +3 -3
- package/dist/_astro/DatePicker.Bkl71M49.js +1 -0
- package/dist/_astro/DocsFileBrowser.MKVCfZrE.js +1 -0
- package/dist/_astro/DocsPager.DJY4foYL.js +1 -0
- package/dist/_astro/{DrawerField.CWMLhcPX.js → DrawerField.CHRg77LG.js} +1 -1
- package/dist/_astro/{ExcelFieldTags.B_XMwNNx.js → ExcelFieldTags.DXMeaDa5.js} +4 -4
- package/dist/_astro/KnowledgeLibrary.B-p1aoQN.js +1 -0
- package/dist/_astro/NamePromptDialog.Wa9O530a.js +1 -0
- package/dist/_astro/NavLibraries.C6LImMO_.js +1 -0
- package/dist/_astro/OverflowHint.D6v4Uj2N.js +1 -0
- package/dist/_astro/PluginsPage.-97n3x2U.js +39 -0
- package/dist/_astro/PluginsPage.DkmRPfbU.js +1 -0
- package/dist/_astro/PmBugsBoard.CMT4-eoB.js +1 -0
- package/dist/_astro/PmIterationsBoard.BQM_dzdZ.js +1 -0
- package/dist/_astro/PmProjectDetail.CzU80pat.js +1 -0
- package/dist/_astro/PmProjectsBoard.Cxsa7SYQ.js +1 -0
- package/dist/_astro/PmRequirementsBoard.4_JMDDN0.js +1 -0
- package/dist/_astro/PmRequirementsBoard.B8HL07cw.js +1 -0
- package/dist/_astro/PmShared.Ca2Ao7v_.js +1 -0
- package/dist/_astro/PromptsLibrary.C9BcIxKK.js +1 -0
- package/dist/_astro/ReportsPage.Fh5DRKLT.js +1 -0
- package/dist/_astro/RequirementsLibrary.CBkuWE8X.js +1 -0
- package/dist/_astro/SearchableSelect.DnjoSslK.js +1 -0
- package/dist/_astro/SelectDropdown.CuuDHa8s.js +1 -0
- package/dist/_astro/SettingsDialog.CJvBRcs9.js +1 -0
- package/dist/_astro/SlideOverDrawer.B7B5Wu8I.js +1 -0
- package/dist/_astro/{SpaceSwitcher.BEJo5KFi.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.BGPnP1Bg.js +7 -0
- 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.B0ZdZNj2.js → open-docs-in-session.CyFNgh1I.js} +1 -1
- package/dist/_astro/{plugins.D5ypJIXn.js → plugins.C2BMfzv1.js} +1 -1
- package/dist/_astro/{pm.BsnTv63L.js → pm.CagBA-ht.js} +4 -4
- 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.CnDCvwnQ.js → settings.Ceefeil5.js} +2 -2
- package/dist/_astro/{spaces-client.Cai2tHEI.js → spaces-client.BocUabwy.js} +1 -1
- package/dist/_astro/ui-auto-prompt.CX8fju7r.js +3 -0
- package/dist/_astro/ui-auto.BmC9JJ_X.js +1 -0
- package/dist/_astro/update.CvfIVwnq.js +1 -0
- package/dist/_astro/use-text-value.DBQvHeNl.js +1 -0
- package/dist/_astro/use-tree-walker.DFU2AaAP.js +1 -0
- package/dist/_astro/useListAnim.BoerpmsB.js +1 -0
- package/dist/_astro/{view-prefs.HCowOWXL.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 +389 -23
- package/dist/docs/install/index.html +258 -22
- package/dist/docs/manual/index.html +324 -27
- 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 +85 -34
- package/lh-plugins/lh-project-docs.mjs +14 -0
- package/lh-plugins/lh-uiauto.mjs +2296 -0
- package/lh-plugins/plugin-prompts.mjs +200 -0
- package/lh-plugins/storage-domain.mjs +13 -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-argv-guard.cjs +41 -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.DjIEQkT7.css +0 -1
- package/dist/_astro/Base.astro_astro_type_script_index_0_lang.D0snmAJ_.js +0 -1
- package/dist/_astro/CaseExecBoard.BAV4EE3o.js +0 -1
- package/dist/_astro/CaseGenerateApp.Bz4ryNJG.js +0 -9
- package/dist/_astro/CasesLibrary.BPifyHUA.js +0 -1
- package/dist/_astro/ChatApp.DLo31SYZ.js +0 -276
- package/dist/_astro/ColumnResize.Bs6GL3DJ.js +0 -1
- package/dist/_astro/DatePicker.CMfX7F6z.js +0 -1
- package/dist/_astro/DocsFileBrowser.D3cKurQE.js +0 -1
- package/dist/_astro/DocsPager.rzu4mnzw.js +0 -1
- package/dist/_astro/KnowledgeLibrary.B0sO4QR1.js +0 -1
- package/dist/_astro/NamePromptDialog.Dl5kSnQI.js +0 -1
- package/dist/_astro/NavLibraries.Cvg3wery.js +0 -1
- package/dist/_astro/OverflowHint.lzmplP5j.js +0 -1
- package/dist/_astro/PluginsPage.DIltPILi.js +0 -39
- package/dist/_astro/PluginsPage.uvmSuXzi.js +0 -1
- package/dist/_astro/PmBugsBoard.CiaIhCHv.js +0 -1
- package/dist/_astro/PmIterationsBoard.H67QwKFw.js +0 -1
- package/dist/_astro/PmProjectDetail.DqDoIg8a.js +0 -1
- package/dist/_astro/PmProjectsBoard.nOC1Hugt.js +0 -1
- package/dist/_astro/PmRequirementsBoard.BPjZ7khP.js +0 -1
- package/dist/_astro/PmRequirementsBoard.CanxvcKg.js +0 -1
- package/dist/_astro/PmShared.CZnXaUq-.js +0 -1
- package/dist/_astro/PromptsLibrary.DU9EuSim.js +0 -1
- package/dist/_astro/ReportsPage.Cr88iz8c.js +0 -1
- package/dist/_astro/RequirementsLibrary.BwriF8F0.js +0 -1
- package/dist/_astro/SearchableSelect.Ctg8V1Z1.js +0 -1
- package/dist/_astro/SelectDropdown.Buv7rQJ_.js +0 -1
- package/dist/_astro/SettingsDialog.DEgsVfaL.js +0 -1
- package/dist/_astro/SlideOverDrawer.TPbGEoWn.js +0 -1
- package/dist/_astro/TagSelect.u8DTop7v.js +0 -1
- package/dist/_astro/TasksBoard.BZi_GBPG.js +0 -1
- package/dist/_astro/TemplatesLibrary.T4K9jUex.js +0 -1
- package/dist/_astro/TestStatsBoard.Dd1Kcmx6.js +0 -1
- package/dist/_astro/TodosBoard.C4yd_JFb.js +0 -1
- package/dist/_astro/active-element-history.CeefGkFQ.js +0 -1
- package/dist/_astro/app-config.DKMxjv3g.js +0 -1
- package/dist/_astro/dialog.DXHznyjD.js +0 -1
- package/dist/_astro/i18n.BXeGGutk.js +0 -7
- 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.DXCPfU4a.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
|
@@ -0,0 +1,2296 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 自动化测试(空间级):挂载目标项目里已有的 Playwright,跑用例、看日志、看报告。
|
|
3
|
+
*
|
|
4
|
+
* 数据落在:
|
|
5
|
+
* ```
|
|
6
|
+
* <当前数据空间>/自动化测试/
|
|
7
|
+
* 自动化测试.json # { version, projects, runs }
|
|
8
|
+
* <项目名>/
|
|
9
|
+
* 报告/<runId>/ # 运行结束后快照过来的 HTML 报告
|
|
10
|
+
* 结果/<runId>.json|xml # Playwright JSON / JUnit XML 原始结果
|
|
11
|
+
* 日志/<runId>.log # 原始 stdout / stderr
|
|
12
|
+
* ```
|
|
13
|
+
* 本机数据(应用图标缓存、生成会话与截图)不进内容目录,落在
|
|
14
|
+
* `<当前数据空间>/.lantern/local/uiauto/{app-icons,sessions}/`。
|
|
15
|
+
* 旧版本的 `UI自动化/` 目录在首次访问时自动改名迁移,不需要重开插件开关。
|
|
16
|
+
*
|
|
17
|
+
* 约束:
|
|
18
|
+
* - 不自动安装依赖、不联网:只用项目自己的 `node_modules/.bin/playwright`,
|
|
19
|
+
* 退而求其次 `npx --no-install playwright`;找不到就报「未安装」。
|
|
20
|
+
* - 常规运行 / 浏览是只读的;只有 AI 生成(`/agent/*`)会在用户确认后写文件:
|
|
21
|
+
* 试跑草稿写进测试目录并立刻删除,最终脚本由用户点「写入项目」才落盘。
|
|
22
|
+
* - 同一项目同时只允许一个 run,全局最多 2 个。
|
|
23
|
+
*/
|
|
24
|
+
import crypto from 'node:crypto';
|
|
25
|
+
import fs from 'node:fs';
|
|
26
|
+
import path from 'node:path';
|
|
27
|
+
import { spawn } from 'node:child_process';
|
|
28
|
+
import { fileURLToPath } from 'node:url';
|
|
29
|
+
|
|
30
|
+
import { pickDirectoryResult } from '../builtin/session/lh-fs.mjs';
|
|
31
|
+
import { getDataRoot } from '../builtin/session/space-context.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';
|
|
98
|
+
|
|
99
|
+
const PREFIX = '/__tb_uiauto';
|
|
100
|
+
const VERSION = 2;
|
|
101
|
+
|
|
102
|
+
/** 预加载守卫:给 Playwright 的 `--project` 参数让路(见文件内注释) */
|
|
103
|
+
const ARGV_GUARD_PATH = path.join(
|
|
104
|
+
path.dirname(fileURLToPath(import.meta.url)),
|
|
105
|
+
'uiauto-argv-guard.cjs',
|
|
106
|
+
);
|
|
107
|
+
|
|
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';
|
|
115
|
+
export const REPORT_DIR_NAME = '报告';
|
|
116
|
+
export const RESULT_DIR_NAME = '结果';
|
|
117
|
+
export const LOG_DIR_NAME = '日志';
|
|
118
|
+
|
|
119
|
+
export const MAX_CONCURRENT_RUNS = 2;
|
|
120
|
+
export const MAX_PREVIEW_BYTES = 256 * 1024;
|
|
121
|
+
const MAX_RAW_LOG_BYTES = 4 * 1024 * 1024;
|
|
122
|
+
const MAX_BODY_BYTES = 1024 * 1024;
|
|
123
|
+
const STOP_GRACE_MS = 5000;
|
|
124
|
+
|
|
125
|
+
/** 目录树里一律不展开的目录名(构建产物 / 依赖 / 测试输出) */
|
|
126
|
+
export const TREE_IGNORED_NAMES = new Set([
|
|
127
|
+
'node_modules',
|
|
128
|
+
'.git',
|
|
129
|
+
'.svn',
|
|
130
|
+
'.hg',
|
|
131
|
+
'.lantern-ai',
|
|
132
|
+
'test-results',
|
|
133
|
+
'playwright-report',
|
|
134
|
+
'blob-report',
|
|
135
|
+
'dist',
|
|
136
|
+
'coverage',
|
|
137
|
+
'.next',
|
|
138
|
+
'.nuxt',
|
|
139
|
+
'.cache',
|
|
140
|
+
'.turbo',
|
|
141
|
+
'.DS_Store',
|
|
142
|
+
]);
|
|
143
|
+
|
|
144
|
+
export const RUN_STATUSES = ['running', 'passed', 'failed', 'cancelled', 'error', 'interrupted'];
|
|
145
|
+
|
|
146
|
+
const MAX_ARG_TEXT = 500;
|
|
147
|
+
|
|
148
|
+
/** @type {Map<string, RunProcess>} */
|
|
149
|
+
const RUNNING = new Map();
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* @typedef {object} RunProcess
|
|
153
|
+
* @property {import('node:child_process').ChildProcess} child
|
|
154
|
+
* @property {string} projectId
|
|
155
|
+
* @property {string} runId
|
|
156
|
+
* @property {string} logAbs
|
|
157
|
+
* @property {fs.WriteStream | null} stream
|
|
158
|
+
* @property {string} log
|
|
159
|
+
* @property {number} logStart
|
|
160
|
+
* @property {boolean} stopping
|
|
161
|
+
* @property {NodeJS.Timeout | null} killTimer
|
|
162
|
+
* @property {boolean} settled
|
|
163
|
+
*/
|
|
164
|
+
|
|
165
|
+
function sendJson(res, status, body) {
|
|
166
|
+
res.statusCode = status;
|
|
167
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
168
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
169
|
+
res.end(JSON.stringify(body));
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function readBodyLimited(req) {
|
|
173
|
+
return new Promise((resolve, reject) => {
|
|
174
|
+
const chunks = [];
|
|
175
|
+
let size = 0;
|
|
176
|
+
req.on('data', (chunk) => {
|
|
177
|
+
size += chunk.length;
|
|
178
|
+
if (size > MAX_BODY_BYTES) {
|
|
179
|
+
reject(new Error('请求体过大'));
|
|
180
|
+
req.destroy();
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
chunks.push(chunk);
|
|
184
|
+
});
|
|
185
|
+
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
186
|
+
req.on('error', reject);
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** 绝对路径是否在 base 内(base 自身也算内) */
|
|
191
|
+
export function isPathInside(base, target) {
|
|
192
|
+
const root = path.resolve(base);
|
|
193
|
+
const abs = path.resolve(target);
|
|
194
|
+
return abs === root || abs.startsWith(`${root}${path.sep}`);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* 把相对路径解析到 base 内;`../`、绝对路径、盘符逃逸一律返回空串。
|
|
199
|
+
* @param {string} base
|
|
200
|
+
* @param {string} rel
|
|
201
|
+
* @returns {string}
|
|
202
|
+
*/
|
|
203
|
+
export function resolveInside(base, rel) {
|
|
204
|
+
const raw = String(rel ?? '').replace(/\\/g, '/');
|
|
205
|
+
if (raw.includes('\0')) return '';
|
|
206
|
+
if (path.isAbsolute(raw) || /^[a-zA-Z]:/.test(raw)) return '';
|
|
207
|
+
const abs = path.resolve(base, raw);
|
|
208
|
+
return isPathInside(base, abs) ? abs : '';
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export function shouldIgnoreTreeName(name) {
|
|
212
|
+
return TREE_IGNORED_NAMES.has(String(name));
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** 项目内相对路径(POSIX),用于前端展示 */
|
|
216
|
+
function toPosixRel(base, abs) {
|
|
217
|
+
return path.relative(base, abs).split(path.sep).join('/');
|
|
218
|
+
}
|
|
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
|
+
|
|
249
|
+
function storeDir(root) {
|
|
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;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export function uiautoStorePaths(root) {
|
|
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
|
+
}
|
|
299
|
+
return {
|
|
300
|
+
dir,
|
|
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,
|
|
359
|
+
reportDir: path.join(dir, REPORT_DIR_NAME),
|
|
360
|
+
resultDir: path.join(dir, RESULT_DIR_NAME),
|
|
361
|
+
logDir: path.join(dir, LOG_DIR_NAME),
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function emptyStore() {
|
|
366
|
+
return { version: VERSION, projects: [], runs: [] };
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function normalizeProject(raw) {
|
|
370
|
+
if (!raw || typeof raw !== 'object') return null;
|
|
371
|
+
const dir = text(raw.dir, 4096);
|
|
372
|
+
if (!dir) return null;
|
|
373
|
+
const name = text(raw.name, 200) || path.basename(dir);
|
|
374
|
+
return {
|
|
375
|
+
id: text(raw.id, 64) || `uia_${crypto.randomBytes(8).toString('hex')}`,
|
|
376
|
+
name,
|
|
377
|
+
// 存放目录在创建时定下,之后改项目名也不换目录(历史报告路径不失效)
|
|
378
|
+
folder: text(raw.folder, 100) || sanitizeFolderName(name),
|
|
379
|
+
dir,
|
|
380
|
+
// 老数据没有 framework:一律按 Playwright 处理,不做批量迁移
|
|
381
|
+
framework: ADAPTER_IDS.includes(raw.framework) ? raw.framework : 'playwright',
|
|
382
|
+
createdAt: text(raw.createdAt, 40) || new Date().toISOString(),
|
|
383
|
+
lastRunId: text(raw.lastRunId, 64),
|
|
384
|
+
lastRunAt: text(raw.lastRunAt, 40),
|
|
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),
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
function normalizeRun(raw) {
|
|
403
|
+
if (!raw || typeof raw !== 'object') return null;
|
|
404
|
+
const id = text(raw.id, 64);
|
|
405
|
+
const projectId = text(raw.projectId, 64);
|
|
406
|
+
if (!id || !projectId) return null;
|
|
407
|
+
const status = RUN_STATUSES.includes(raw.status) ? raw.status : 'error';
|
|
408
|
+
return {
|
|
409
|
+
id,
|
|
410
|
+
projectId,
|
|
411
|
+
framework: ADAPTER_IDS.includes(raw.framework) ? raw.framework : 'playwright',
|
|
412
|
+
startedAt: text(raw.startedAt, 40),
|
|
413
|
+
finishedAt: text(raw.finishedAt, 40),
|
|
414
|
+
status,
|
|
415
|
+
exitCode: Number.isFinite(raw.exitCode) ? raw.exitCode : null,
|
|
416
|
+
durationMs: intOr(raw.durationMs, 0, 0, Number.MAX_SAFE_INTEGER),
|
|
417
|
+
total: intOr(raw.total, 0, 0, 1_000_000),
|
|
418
|
+
passed: intOr(raw.passed, 0, 0, 1_000_000),
|
|
419
|
+
failed: intOr(raw.failed, 0, 0, 1_000_000),
|
|
420
|
+
skipped: intOr(raw.skipped, 0, 0, 1_000_000),
|
|
421
|
+
flaky: intOr(raw.flaky, 0, 0, 1_000_000),
|
|
422
|
+
args: normalizeRunArgs(raw.args),
|
|
423
|
+
// 这一次实际执行的命令行(任务运行才有),历史里直接显示
|
|
424
|
+
command: text(raw.command, 1000),
|
|
425
|
+
taskId: text(raw.taskId, 64),
|
|
426
|
+
taskLabel: text(raw.taskLabel, 200),
|
|
427
|
+
projectNames: Array.isArray(raw.projectNames)
|
|
428
|
+
? raw.projectNames
|
|
429
|
+
.map((name) => text(name, 100))
|
|
430
|
+
.filter(Boolean)
|
|
431
|
+
.slice(0, 50)
|
|
432
|
+
: [],
|
|
433
|
+
reportRel: text(raw.reportRel, 1024),
|
|
434
|
+
resultRel: text(raw.resultRel, 1024),
|
|
435
|
+
logRel: text(raw.logRel, 1024),
|
|
436
|
+
error: text(raw.error, 4000),
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
function normalizeRunArgs(raw) {
|
|
441
|
+
const source = raw && typeof raw === 'object' ? raw : {};
|
|
442
|
+
return {
|
|
443
|
+
file: text(source.file, 1024),
|
|
444
|
+
grep: text(source.grep, MAX_ARG_TEXT),
|
|
445
|
+
// 老数据里叫 browser,读取时兼容;新写入统一用 project(Playwright config 里的项目名)
|
|
446
|
+
project: text(source.project, 100) || text(source.browser, 100),
|
|
447
|
+
headed: source.headed === true,
|
|
448
|
+
workers: intOr(source.workers, 0, 0, 32),
|
|
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),
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function normalizeStore(raw) {
|
|
459
|
+
const base = emptyStore();
|
|
460
|
+
if (!raw || typeof raw !== 'object') return base;
|
|
461
|
+
base.projects = Array.isArray(raw.projects)
|
|
462
|
+
? raw.projects.map(normalizeProject).filter(Boolean)
|
|
463
|
+
: [];
|
|
464
|
+
base.runs = Array.isArray(raw.runs) ? raw.runs.map(normalizeRun).filter(Boolean) : [];
|
|
465
|
+
return base;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function readStore(root) {
|
|
469
|
+
const fp = uiautoStorePaths(root).store;
|
|
470
|
+
let store;
|
|
471
|
+
try {
|
|
472
|
+
store = normalizeStore(JSON.parse(fs.readFileSync(fp, 'utf8')));
|
|
473
|
+
} catch {
|
|
474
|
+
store = emptyStore();
|
|
475
|
+
}
|
|
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;
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/** 服务重启后内存里没有对应进程的 running,一定是上次异常退出留下的 */
|
|
553
|
+
function reconcileStore(store, root) {
|
|
554
|
+
let dirty = false;
|
|
555
|
+
if (root && migrateLegacyRunArtifacts(root, store)) dirty = true;
|
|
556
|
+
for (const run of store.runs) {
|
|
557
|
+
if (run.status !== 'running' || RUNNING.has(run.id)) continue;
|
|
558
|
+
run.status = 'interrupted';
|
|
559
|
+
run.finishedAt = run.finishedAt || new Date().toISOString();
|
|
560
|
+
run.error = run.error || '服务已重启,本次运行被中断';
|
|
561
|
+
dirty = true;
|
|
562
|
+
}
|
|
563
|
+
return { store, dirty };
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
function writeStore(root, store) {
|
|
567
|
+
const fp = uiautoStorePaths(root).store;
|
|
568
|
+
fs.mkdirSync(path.dirname(fp), { recursive: true });
|
|
569
|
+
const tmp = `${fp}.${process.pid}.tmp`;
|
|
570
|
+
fs.writeFileSync(tmp, `${JSON.stringify(store, null, 2)}\n`, 'utf8');
|
|
571
|
+
fs.renameSync(tmp, fp);
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
function readStoreForWrite(root) {
|
|
575
|
+
const { store } = readStore(root);
|
|
576
|
+
return store;
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
function findProject(store, projectId) {
|
|
580
|
+
return store.projects.find((p) => p.id === projectId) ?? null;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
function findRun(store, runId) {
|
|
584
|
+
return store.runs.find((r) => r.id === runId) ?? null;
|
|
585
|
+
}
|
|
586
|
+
|
|
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';
|
|
600
|
+
}
|
|
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
|
+
};
|
|
622
|
+
}
|
|
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;
|
|
639
|
+
return {
|
|
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),
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/** 框架下拉的可选项(Playwright / pytest / Selenium) */
|
|
658
|
+
export function frameworkOptions() {
|
|
659
|
+
return adapterOptions();
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
function decorateProject(project) {
|
|
663
|
+
const health = detectProject(project.dir, project.framework);
|
|
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
|
+
};
|
|
687
|
+
return {
|
|
688
|
+
...project,
|
|
689
|
+
customTasks,
|
|
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)],
|
|
698
|
+
runningRunId: running ? running.runId : '',
|
|
699
|
+
};
|
|
700
|
+
}
|
|
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
|
+
|
|
720
|
+
/** 该项目最近一次运行解析到的 Playwright 项目名(setup / chromium-login …) */
|
|
721
|
+
function latestProjectNames(store, projectId) {
|
|
722
|
+
const runs = store.runs
|
|
723
|
+
.filter((run) => run.projectId === projectId && run.projectNames.length)
|
|
724
|
+
.sort((a, b) => (a.startedAt < b.startedAt ? 1 : -1));
|
|
725
|
+
return runs[0]?.projectNames ?? [];
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
/** 把相对文件路径清成项目内的 POSIX 路径;越界返回空串 */
|
|
729
|
+
export function normalizeRunFile(base, file) {
|
|
730
|
+
const raw = text(file, 1024).replace(/\\/g, '/');
|
|
731
|
+
if (!raw) return '';
|
|
732
|
+
if (path.isAbsolute(raw) || /^[a-zA-Z]:/.test(raw) || raw.split('/').includes('..')) return '';
|
|
733
|
+
const abs = resolveInside(base, raw);
|
|
734
|
+
if (!abs) return '';
|
|
735
|
+
try {
|
|
736
|
+
if (!fs.statSync(abs).isFile()) return '';
|
|
737
|
+
} catch {
|
|
738
|
+
return '';
|
|
739
|
+
}
|
|
740
|
+
return raw.replace(/^\.\//, '');
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
function appendLog(entry, chunk) {
|
|
744
|
+
const value = String(chunk ?? '');
|
|
745
|
+
if (!value) return;
|
|
746
|
+
entry.log += value;
|
|
747
|
+
if (entry.log.length > MAX_RAW_LOG_BYTES) {
|
|
748
|
+
const drop = entry.log.length - MAX_RAW_LOG_BYTES;
|
|
749
|
+
entry.log = entry.log.slice(drop);
|
|
750
|
+
entry.logStart += drop;
|
|
751
|
+
}
|
|
752
|
+
if (entry.stream) {
|
|
753
|
+
try {
|
|
754
|
+
entry.stream.write(value);
|
|
755
|
+
} catch {
|
|
756
|
+
// 写盘失败不影响运行
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
function killRun(entry, signal) {
|
|
762
|
+
const pid = entry.child.pid;
|
|
763
|
+
if (!pid) return;
|
|
764
|
+
try {
|
|
765
|
+
if (process.platform === 'win32') {
|
|
766
|
+
if (signal === 'SIGKILL') {
|
|
767
|
+
spawn('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore' });
|
|
768
|
+
} else {
|
|
769
|
+
entry.child.kill();
|
|
770
|
+
}
|
|
771
|
+
} else {
|
|
772
|
+
process.kill(-pid, signal);
|
|
773
|
+
}
|
|
774
|
+
} catch {
|
|
775
|
+
try {
|
|
776
|
+
entry.child.kill(signal);
|
|
777
|
+
} catch {
|
|
778
|
+
// 已经退出
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
/** 结果文件的后缀:JSON 交给适配器自己解析,pytest / selenium 用 XML */
|
|
784
|
+
function resultFileName(runId, adapter) {
|
|
785
|
+
return `${runId}${adapter.id === 'playwright' ? '.json' : '.xml'}`;
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
function finishRun(root, entry, runId, exitCode, spawnError) {
|
|
789
|
+
if (entry.settled) return;
|
|
790
|
+
entry.settled = true;
|
|
791
|
+
if (entry.killTimer) clearTimeout(entry.killTimer);
|
|
792
|
+
RUNNING.delete(runId);
|
|
793
|
+
if (entry.stream) {
|
|
794
|
+
try {
|
|
795
|
+
entry.stream.end();
|
|
796
|
+
} catch {
|
|
797
|
+
// ignore
|
|
798
|
+
}
|
|
799
|
+
entry.stream = null;
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
const paths = uiautoStorePaths(root);
|
|
803
|
+
const store = readStoreForWrite(root);
|
|
804
|
+
const run = findRun(store, runId);
|
|
805
|
+
if (!run) return;
|
|
806
|
+
|
|
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
|
+
|
|
858
|
+
const finishedAt = new Date().toISOString();
|
|
859
|
+
const started = Date.parse(run.startedAt);
|
|
860
|
+
const durationMs = summary.durationMs || (Number.isFinite(started) ? Date.now() - started : 0);
|
|
861
|
+
|
|
862
|
+
let status;
|
|
863
|
+
if (entry.stopping) status = 'cancelled';
|
|
864
|
+
else if (spawnError) status = 'error';
|
|
865
|
+
else if (exitCode === 0) status = 'passed';
|
|
866
|
+
else status = 'failed';
|
|
867
|
+
|
|
868
|
+
let error = '';
|
|
869
|
+
if (spawnError) error = text(spawnError, 4000);
|
|
870
|
+
else if (summary.errors.length) error = summary.errors.join('\n').slice(0, 4000);
|
|
871
|
+
else if (status === 'failed' && summary.total === 0) {
|
|
872
|
+
const hint = text(adapter.hintFromLog?.(entry.log), 1000);
|
|
873
|
+
const tail = entry.log.slice(-1200).trim();
|
|
874
|
+
error = hint || tail;
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
run.status = status;
|
|
878
|
+
run.exitCode = exitCode;
|
|
879
|
+
run.finishedAt = finishedAt;
|
|
880
|
+
run.durationMs = durationMs;
|
|
881
|
+
run.total = summary.total;
|
|
882
|
+
run.passed = summary.passed;
|
|
883
|
+
run.failed = summary.failed;
|
|
884
|
+
run.skipped = summary.skipped;
|
|
885
|
+
run.flaky = summary.flaky;
|
|
886
|
+
if (summary.projectNames.length) run.projectNames = summary.projectNames;
|
|
887
|
+
run.reportRel = reportRel;
|
|
888
|
+
run.error = error;
|
|
889
|
+
|
|
890
|
+
if (project) {
|
|
891
|
+
project.lastRunId = run.id;
|
|
892
|
+
project.lastRunAt = run.startedAt;
|
|
893
|
+
project.lastStatus = run.status;
|
|
894
|
+
}
|
|
895
|
+
writeStore(root, store);
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
function runView(run) {
|
|
899
|
+
return {
|
|
900
|
+
...run,
|
|
901
|
+
reportUrl: run.reportRel ? `${PREFIX}/report/${encodeURIComponent(run.id)}/` : '',
|
|
902
|
+
logUrl: run.logRel ? `${PREFIX}/run?id=${encodeURIComponent(run.id)}` : '',
|
|
903
|
+
};
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
function startRun(root, body) {
|
|
907
|
+
const store = readStoreForWrite(root);
|
|
908
|
+
const projectId = text(body?.projectId, 64);
|
|
909
|
+
const project = findProject(store, projectId);
|
|
910
|
+
if (!project) return { error: '项目不存在', status: 404 };
|
|
911
|
+
|
|
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);
|
|
918
|
+
if (!health.mountable) {
|
|
919
|
+
return { error: '没有识别到该目录的测试框架,请重新识别或换个目录', status: 400 };
|
|
920
|
+
}
|
|
921
|
+
if (!health.frameworkReady) {
|
|
922
|
+
return { error: health.readyHint || '运行环境未就绪', status: 400 };
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
for (const entry of RUNNING.values()) {
|
|
926
|
+
if (entry.projectId === projectId) {
|
|
927
|
+
return { error: '该项目已有运行中的任务,请等待结束或先停止', status: 409 };
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
if (RUNNING.size >= MAX_CONCURRENT_RUNS) {
|
|
931
|
+
return { error: `全局最多同时运行 ${MAX_CONCURRENT_RUNS} 个项目,请稍后再试`, status: 409 };
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
const args = normalizeRunArgs({
|
|
935
|
+
...body,
|
|
936
|
+
project: project.framework === 'playwright' ? body?.project : '',
|
|
937
|
+
});
|
|
938
|
+
if (args.file) {
|
|
939
|
+
const file = normalizeRunFile(project.dir, args.file);
|
|
940
|
+
if (!file) return { error: '指定的测试文件不在项目目录内或不存在', status: 400 };
|
|
941
|
+
args.file = file;
|
|
942
|
+
}
|
|
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
|
+
|
|
962
|
+
const runId = `uar_${Date.now().toString(36)}_${crypto.randomBytes(3).toString('hex')}`;
|
|
963
|
+
const paths = uiautoStorePaths(root);
|
|
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 };
|
|
1007
|
+
|
|
1008
|
+
const startedAt = new Date().toISOString();
|
|
1009
|
+
const env = {
|
|
1010
|
+
...process.env,
|
|
1011
|
+
...(resolved.env ?? {}),
|
|
1012
|
+
FORCE_COLOR: '0',
|
|
1013
|
+
NO_COLOR: '1',
|
|
1014
|
+
};
|
|
1015
|
+
|
|
1016
|
+
// 记录真实执行的命令行:任务运行时是 shell 命令串,全量运行时是命令 + 参数
|
|
1017
|
+
const commandLine = resolved.shell
|
|
1018
|
+
? resolved.command
|
|
1019
|
+
: [resolved.command, ...(resolved.args ?? [])].join(' ');
|
|
1020
|
+
|
|
1021
|
+
const win = process.platform === 'win32';
|
|
1022
|
+
let child;
|
|
1023
|
+
try {
|
|
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
|
+
});
|
|
1043
|
+
} catch (err) {
|
|
1044
|
+
return { error: `启动失败:${err instanceof Error ? err.message : String(err)}`, status: 500 };
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
const run = {
|
|
1048
|
+
id: runId,
|
|
1049
|
+
projectId,
|
|
1050
|
+
framework: adapter.id,
|
|
1051
|
+
startedAt,
|
|
1052
|
+
finishedAt: '',
|
|
1053
|
+
status: 'running',
|
|
1054
|
+
exitCode: null,
|
|
1055
|
+
durationMs: 0,
|
|
1056
|
+
total: 0,
|
|
1057
|
+
passed: 0,
|
|
1058
|
+
failed: 0,
|
|
1059
|
+
skipped: 0,
|
|
1060
|
+
flaky: 0,
|
|
1061
|
+
args,
|
|
1062
|
+
command: commandLine,
|
|
1063
|
+
taskId,
|
|
1064
|
+
taskLabel: task ? taskCommandLine(task) : '',
|
|
1065
|
+
projectNames: [],
|
|
1066
|
+
reportRel: '',
|
|
1067
|
+
resultRel,
|
|
1068
|
+
logRel,
|
|
1069
|
+
error: '',
|
|
1070
|
+
};
|
|
1071
|
+
store.runs.push(run);
|
|
1072
|
+
project.lastRunId = runId;
|
|
1073
|
+
project.lastRunAt = startedAt;
|
|
1074
|
+
project.lastStatus = 'running';
|
|
1075
|
+
writeStore(root, store);
|
|
1076
|
+
|
|
1077
|
+
/** @type {RunProcess} */
|
|
1078
|
+
const entry = {
|
|
1079
|
+
child,
|
|
1080
|
+
projectId,
|
|
1081
|
+
runId,
|
|
1082
|
+
logAbs,
|
|
1083
|
+
stream: fs.createWriteStream(logAbs, { flags: 'a' }),
|
|
1084
|
+
log: '',
|
|
1085
|
+
logStart: 0,
|
|
1086
|
+
stopping: false,
|
|
1087
|
+
killTimer: null,
|
|
1088
|
+
settled: false,
|
|
1089
|
+
};
|
|
1090
|
+
RUNNING.set(runId, entry);
|
|
1091
|
+
appendLog(entry, `[lantern] $ ${commandLine}\n`);
|
|
1092
|
+
|
|
1093
|
+
child.stdout?.setEncoding('utf8');
|
|
1094
|
+
child.stderr?.setEncoding('utf8');
|
|
1095
|
+
child.stdout?.on('data', (chunk) => appendLog(entry, chunk));
|
|
1096
|
+
child.stderr?.on('data', (chunk) => appendLog(entry, chunk));
|
|
1097
|
+
child.on('error', (err) => {
|
|
1098
|
+
appendLog(entry, `\n[lantern] 启动失败:${err.message}\n`);
|
|
1099
|
+
finishRun(root, entry, runId, null, err.message);
|
|
1100
|
+
});
|
|
1101
|
+
child.on('close', (code) => {
|
|
1102
|
+
appendLog(entry, `\n[lantern] 进程退出,exitCode=${code ?? 'null'}\n`);
|
|
1103
|
+
finishRun(root, entry, runId, code, '');
|
|
1104
|
+
});
|
|
1105
|
+
|
|
1106
|
+
return { run: runView(run), command: commandLine, args: resolved.args };
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
function stopRun(runId) {
|
|
1110
|
+
const entry = RUNNING.get(runId);
|
|
1111
|
+
if (!entry) return false;
|
|
1112
|
+
if (entry.stopping) return true;
|
|
1113
|
+
entry.stopping = true;
|
|
1114
|
+
appendLog(entry, '\n[lantern] 收到停止请求,正在结束进程…\n');
|
|
1115
|
+
killRun(entry, 'SIGTERM');
|
|
1116
|
+
entry.killTimer = setTimeout(() => {
|
|
1117
|
+
if (!RUNNING.has(runId)) return;
|
|
1118
|
+
appendLog(entry, '\n[lantern] 5s 内未退出,强制结束。\n');
|
|
1119
|
+
killRun(entry, 'SIGKILL');
|
|
1120
|
+
}, STOP_GRACE_MS);
|
|
1121
|
+
entry.killTimer.unref?.();
|
|
1122
|
+
return true;
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
const MIME_BY_EXT = {
|
|
1126
|
+
'.html': 'text/html; charset=utf-8',
|
|
1127
|
+
'.htm': 'text/html; charset=utf-8',
|
|
1128
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
1129
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
1130
|
+
'.css': 'text/css; charset=utf-8',
|
|
1131
|
+
'.json': 'application/json; charset=utf-8',
|
|
1132
|
+
'.map': 'application/json; charset=utf-8',
|
|
1133
|
+
'.svg': 'image/svg+xml',
|
|
1134
|
+
'.png': 'image/png',
|
|
1135
|
+
'.jpg': 'image/jpeg',
|
|
1136
|
+
'.jpeg': 'image/jpeg',
|
|
1137
|
+
'.gif': 'image/gif',
|
|
1138
|
+
'.webp': 'image/webp',
|
|
1139
|
+
'.ico': 'image/x-icon',
|
|
1140
|
+
'.woff': 'font/woff',
|
|
1141
|
+
'.woff2': 'font/woff2',
|
|
1142
|
+
'.ttf': 'font/ttf',
|
|
1143
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
1144
|
+
'.zip': 'application/zip',
|
|
1145
|
+
'.webm': 'video/webm',
|
|
1146
|
+
'.mp4': 'video/mp4',
|
|
1147
|
+
};
|
|
1148
|
+
|
|
1149
|
+
function sendReportFile(root, res, runId, rawPath) {
|
|
1150
|
+
if (!/^[A-Za-z0-9_-]+$/.test(runId))
|
|
1151
|
+
return sendJson(res, 400, { ok: false, error: '运行 ID 不合法' });
|
|
1152
|
+
const paths = uiautoStorePaths(root);
|
|
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)) {
|
|
1157
|
+
return sendJson(res, 400, { ok: false, error: '报告路径不合法' });
|
|
1158
|
+
}
|
|
1159
|
+
let rel;
|
|
1160
|
+
try {
|
|
1161
|
+
rel = decodeURIComponent(rawPath || '');
|
|
1162
|
+
} catch {
|
|
1163
|
+
return sendJson(res, 400, { ok: false, error: '报告路径不合法' });
|
|
1164
|
+
}
|
|
1165
|
+
if (rel.includes('\0')) return sendJson(res, 400, { ok: false, error: '报告路径不合法' });
|
|
1166
|
+
const target = resolveInside(dir, rel || 'index.html');
|
|
1167
|
+
if (!target) return sendJson(res, 400, { ok: false, error: '报告路径不合法' });
|
|
1168
|
+
let file = target;
|
|
1169
|
+
try {
|
|
1170
|
+
if (fs.statSync(file).isDirectory()) file = path.join(file, 'index.html');
|
|
1171
|
+
} catch {
|
|
1172
|
+
return sendJson(res, 404, { ok: false, error: '报告文件不存在' });
|
|
1173
|
+
}
|
|
1174
|
+
let stat;
|
|
1175
|
+
try {
|
|
1176
|
+
stat = fs.statSync(file);
|
|
1177
|
+
} catch {
|
|
1178
|
+
return sendJson(res, 404, { ok: false, error: '报告文件不存在' });
|
|
1179
|
+
}
|
|
1180
|
+
if (!stat.isFile()) return sendJson(res, 404, { ok: false, error: '报告文件不存在' });
|
|
1181
|
+
|
|
1182
|
+
const ext = path.extname(file).toLowerCase();
|
|
1183
|
+
res.statusCode = 200;
|
|
1184
|
+
res.setHeader('Content-Type', MIME_BY_EXT[ext] ?? 'application/octet-stream');
|
|
1185
|
+
res.setHeader('Content-Length', String(stat.size));
|
|
1186
|
+
res.setHeader('Cache-Control', 'no-cache');
|
|
1187
|
+
// 报告里可能有 trace / 附件:未知类型按下载处理,避免浏览器误渲染
|
|
1188
|
+
if (!MIME_BY_EXT[ext]) {
|
|
1189
|
+
res.setHeader(
|
|
1190
|
+
'Content-Disposition',
|
|
1191
|
+
`attachment; filename*=UTF-8''${encodeURIComponent(path.basename(file))}`,
|
|
1192
|
+
);
|
|
1193
|
+
}
|
|
1194
|
+
fs.createReadStream(file).pipe(res);
|
|
1195
|
+
}
|
|
1196
|
+
|
|
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
|
+
};
|
|
1203
|
+
|
|
1204
|
+
/** 从目录树里筛出测试文件,供「指定文件」下拉使用 */
|
|
1205
|
+
function listSpecFiles(project, framework = project.framework) {
|
|
1206
|
+
const pattern = SPEC_PATTERNS[framework] ?? SPEC_PATTERNS.playwright;
|
|
1207
|
+
const result = [];
|
|
1208
|
+
const walk = (abs, level) => {
|
|
1209
|
+
if (level > 6 || result.length >= 500) return;
|
|
1210
|
+
let items;
|
|
1211
|
+
try {
|
|
1212
|
+
items = fs.readdirSync(abs, { withFileTypes: true });
|
|
1213
|
+
} catch {
|
|
1214
|
+
return;
|
|
1215
|
+
}
|
|
1216
|
+
for (const item of items) {
|
|
1217
|
+
if (result.length >= 500) return;
|
|
1218
|
+
if (shouldIgnoreTreeName(item.name)) continue;
|
|
1219
|
+
const child = path.join(abs, item.name);
|
|
1220
|
+
if (item.isDirectory()) walk(child, level + 1);
|
|
1221
|
+
else if (pattern.test(item.name)) {
|
|
1222
|
+
result.push(toPosixRel(project.dir, child));
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
};
|
|
1226
|
+
walk(project.dir, 0);
|
|
1227
|
+
return result.sort();
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
function removeRunArtifacts(root, run) {
|
|
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
|
+
}
|
|
1239
|
+
if (run.reportRel) {
|
|
1240
|
+
const abs = path.join(paths.dir, run.reportRel);
|
|
1241
|
+
if (inside(abs)) fs.rmSync(abs, { recursive: true, force: true });
|
|
1242
|
+
}
|
|
1243
|
+
if (run.resultRel) {
|
|
1244
|
+
const abs = path.join(paths.dir, run.resultRel);
|
|
1245
|
+
if (inside(abs)) fs.rmSync(abs, { force: true });
|
|
1246
|
+
}
|
|
1247
|
+
if (run.logRel) {
|
|
1248
|
+
const abs = path.join(paths.dir, run.logRel);
|
|
1249
|
+
if (inside(abs)) fs.rmSync(abs, { force: true });
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
/**
|
|
1254
|
+
* @returns {import('vite').Plugin}
|
|
1255
|
+
*/
|
|
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
|
+
|
|
1286
|
+
return {
|
|
1287
|
+
name: 'lh-uiauto',
|
|
1288
|
+
configureServer(server) {
|
|
1289
|
+
server.httpServer?.on('close', () => {
|
|
1290
|
+
stopAllExplorers();
|
|
1291
|
+
stopAllDebugSessions();
|
|
1292
|
+
});
|
|
1293
|
+
server.middlewares.use(async (req, res, next) => {
|
|
1294
|
+
const parsed = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
1295
|
+
if (!parsed.pathname.startsWith(PREFIX)) return next();
|
|
1296
|
+
// 数据根惰性读取:切换数据空间后无需重启
|
|
1297
|
+
const root = getDataRoot();
|
|
1298
|
+
const method = req.method || 'GET';
|
|
1299
|
+
const tail = parsed.pathname.slice(PREFIX.length) || '/';
|
|
1300
|
+
|
|
1301
|
+
try {
|
|
1302
|
+
// 任何一次插件请求都顺手把旧版放在内容目录里的本机数据搬到 .lantern/local/uiauto
|
|
1303
|
+
try {
|
|
1304
|
+
uiautoCachePaths(root);
|
|
1305
|
+
} catch {
|
|
1306
|
+
// 迁移失败不阻塞主流程
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
if (method === 'GET' && tail.startsWith('/report/')) {
|
|
1310
|
+
const rest = tail.slice('/report/'.length);
|
|
1311
|
+
const slash = rest.indexOf('/');
|
|
1312
|
+
const runId = slash === -1 ? rest : rest.slice(0, slash);
|
|
1313
|
+
const rel = slash === -1 ? '' : rest.slice(slash + 1);
|
|
1314
|
+
return sendReportFile(root, res, runId, rel);
|
|
1315
|
+
}
|
|
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
|
+
|
|
1361
|
+
if (method === 'GET' && parsed.searchParams.get('health') === '1') {
|
|
1362
|
+
const healthStore = readStore(root).store;
|
|
1363
|
+
return sendJson(res, 200, {
|
|
1364
|
+
ok: true,
|
|
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
|
+
},
|
|
1373
|
+
running: [...RUNNING.keys()],
|
|
1374
|
+
frameworks: frameworkOptions(),
|
|
1375
|
+
version: VERSION,
|
|
1376
|
+
});
|
|
1377
|
+
}
|
|
1378
|
+
|
|
1379
|
+
if (method === 'GET' && tail === '/projects') {
|
|
1380
|
+
const { store, dirty } = readStore(root);
|
|
1381
|
+
if (dirty) writeStore(root, store);
|
|
1382
|
+
const projects = store.projects.map((project) => ({
|
|
1383
|
+
...decorateProject(project),
|
|
1384
|
+
specFiles: buildProbe(project.dir).exists
|
|
1385
|
+
? listSpecFiles(project, project.framework)
|
|
1386
|
+
: [],
|
|
1387
|
+
// 上次运行拿到的 Playwright 项目名(setup / chromium-login 之类),给下拉做候选
|
|
1388
|
+
projectNames: latestProjectNames(store, project.id),
|
|
1389
|
+
}));
|
|
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
|
+
});
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
if (method === 'POST' && tail === '/pick-directory') {
|
|
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 ?? '' });
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
if (method === 'POST' && tail === '/projects') {
|
|
1429
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
1430
|
+
const rawDir = text(body.dir, 4096);
|
|
1431
|
+
if (!rawDir) return sendJson(res, 400, { ok: false, error: '缺少项目目录' });
|
|
1432
|
+
const dir = path.resolve(rawDir);
|
|
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);
|
|
1438
|
+
if (!health.exists) return sendJson(res, 400, { ok: false, error: '目录不存在' });
|
|
1439
|
+
if (!health.mountable) {
|
|
1440
|
+
return sendJson(res, 400, {
|
|
1441
|
+
ok: false,
|
|
1442
|
+
error:
|
|
1443
|
+
'没有识别到受支持的框架(Playwright / pytest / Selenium),请确认目录里是测试项目',
|
|
1444
|
+
});
|
|
1445
|
+
}
|
|
1446
|
+
const framework = requested || health.framework;
|
|
1447
|
+
if (!ADAPTER_IDS.includes(framework)) {
|
|
1448
|
+
return sendJson(res, 400, { ok: false, error: '请选择要使用的框架' });
|
|
1449
|
+
}
|
|
1450
|
+
const store = readStoreForWrite(root);
|
|
1451
|
+
if (store.projects.some((p) => path.resolve(p.dir) === dir)) {
|
|
1452
|
+
return sendJson(res, 409, { ok: false, error: '该目录已经添加过了' });
|
|
1453
|
+
}
|
|
1454
|
+
const id = `uia_${crypto.randomBytes(8).toString('hex')}`;
|
|
1455
|
+
const name = text(body.name, 200) || path.basename(dir);
|
|
1456
|
+
const project = {
|
|
1457
|
+
id,
|
|
1458
|
+
name,
|
|
1459
|
+
folder: uniqueFolder(store, name, id),
|
|
1460
|
+
dir,
|
|
1461
|
+
framework,
|
|
1462
|
+
createdAt: new Date().toISOString(),
|
|
1463
|
+
lastRunId: '',
|
|
1464
|
+
lastRunAt: '',
|
|
1465
|
+
lastStatus: '',
|
|
1466
|
+
};
|
|
1467
|
+
store.projects.push(project);
|
|
1468
|
+
writeStore(root, store);
|
|
1469
|
+
return sendJson(res, 200, {
|
|
1470
|
+
ok: true,
|
|
1471
|
+
project: {
|
|
1472
|
+
...decorateProject(project),
|
|
1473
|
+
specFiles: listSpecFiles(project, framework),
|
|
1474
|
+
projectNames: latestProjectNames(store, project.id),
|
|
1475
|
+
},
|
|
1476
|
+
});
|
|
1477
|
+
}
|
|
1478
|
+
|
|
1479
|
+
if (method === 'PATCH' && tail === '/projects') {
|
|
1480
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
1481
|
+
const store = readStoreForWrite(root);
|
|
1482
|
+
const project = findProject(store, text(body.id, 64));
|
|
1483
|
+
if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
|
|
1484
|
+
const name = text(body.name, 200);
|
|
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
|
+
}
|
|
1493
|
+
if (typeof body.dir === 'string' && body.dir.trim()) {
|
|
1494
|
+
const dir = path.resolve(text(body.dir, 4096));
|
|
1495
|
+
const health = detectProject(dir, project.framework);
|
|
1496
|
+
if (!health.exists) return sendJson(res, 400, { ok: false, error: '目录不存在' });
|
|
1497
|
+
if (!health.mountable) {
|
|
1498
|
+
return sendJson(res, 400, {
|
|
1499
|
+
ok: false,
|
|
1500
|
+
error:
|
|
1501
|
+
'没有识别到受支持的框架(Playwright / pytest / Selenium),请确认目录里是测试项目',
|
|
1502
|
+
});
|
|
1503
|
+
}
|
|
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);
|
|
1527
|
+
}
|
|
1528
|
+
writeStore(root, store);
|
|
1529
|
+
return sendJson(res, 200, {
|
|
1530
|
+
ok: true,
|
|
1531
|
+
project: {
|
|
1532
|
+
...decorateProject(project),
|
|
1533
|
+
specFiles: listSpecFiles(project, project.framework),
|
|
1534
|
+
projectNames: latestProjectNames(store, project.id),
|
|
1535
|
+
},
|
|
1536
|
+
});
|
|
1537
|
+
}
|
|
1538
|
+
|
|
1539
|
+
if (method === 'DELETE' && tail === '/projects') {
|
|
1540
|
+
const id = text(parsed.searchParams.get('id'), 64);
|
|
1541
|
+
const store = readStoreForWrite(root);
|
|
1542
|
+
const project = findProject(store, id);
|
|
1543
|
+
if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
|
|
1544
|
+
if ([...RUNNING.values()].some((entry) => entry.projectId === id)) {
|
|
1545
|
+
return sendJson(res, 409, { ok: false, error: '项目正在运行,请先停止再移出列表' });
|
|
1546
|
+
}
|
|
1547
|
+
store.projects = store.projects.filter((p) => p.id !== id);
|
|
1548
|
+
writeStore(root, store);
|
|
1549
|
+
return sendJson(res, 200, { ok: true });
|
|
1550
|
+
}
|
|
1551
|
+
|
|
1552
|
+
if (method === 'POST' && tail === '/run') {
|
|
1553
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
1554
|
+
const result = startRun(root, body);
|
|
1555
|
+
if (result.error)
|
|
1556
|
+
return sendJson(res, result.status, { ok: false, error: result.error });
|
|
1557
|
+
return sendJson(res, 200, { ok: true, ...result });
|
|
1558
|
+
}
|
|
1559
|
+
|
|
1560
|
+
if (method === 'POST' && tail === '/stop') {
|
|
1561
|
+
const body = JSON.parse((await readBodyLimited(req)) || '{}');
|
|
1562
|
+
const runId = text(body.runId, 64);
|
|
1563
|
+
if (!runId) return sendJson(res, 400, { ok: false, error: '缺少 runId' });
|
|
1564
|
+
if (!stopRun(runId)) {
|
|
1565
|
+
return sendJson(res, 409, { ok: false, error: '该运行已结束或不在本进程中' });
|
|
1566
|
+
}
|
|
1567
|
+
return sendJson(res, 200, { ok: true });
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
if (method === 'GET' && tail === '/run') {
|
|
1571
|
+
const id = text(parsed.searchParams.get('id'), 64);
|
|
1572
|
+
const offset = intOr(parsed.searchParams.get('offset'), 0, 0, Number.MAX_SAFE_INTEGER);
|
|
1573
|
+
const store = readStore(root).store;
|
|
1574
|
+
const run = findRun(store, id);
|
|
1575
|
+
if (!run) return sendJson(res, 404, { ok: false, error: '运行记录不存在' });
|
|
1576
|
+
const entry = RUNNING.get(id);
|
|
1577
|
+
if (!entry) {
|
|
1578
|
+
// 已结束:从日志文件尾部补一段,刷新页面后仍能看到上次输出
|
|
1579
|
+
let log = '';
|
|
1580
|
+
let reset = false;
|
|
1581
|
+
if (run.logRel) {
|
|
1582
|
+
const abs = path.join(uiautoStorePaths(root).dir, run.logRel);
|
|
1583
|
+
if (isPathInside(uiautoStorePaths(root).dir, abs)) {
|
|
1584
|
+
try {
|
|
1585
|
+
const stat = fs.statSync(abs);
|
|
1586
|
+
const start = Math.max(0, stat.size - MAX_PREVIEW_BYTES);
|
|
1587
|
+
const buffer = Buffer.alloc(stat.size - start);
|
|
1588
|
+
const fd = fs.openSync(abs, 'r');
|
|
1589
|
+
try {
|
|
1590
|
+
fs.readSync(fd, buffer, 0, buffer.length, start);
|
|
1591
|
+
} finally {
|
|
1592
|
+
fs.closeSync(fd);
|
|
1593
|
+
}
|
|
1594
|
+
log = buffer.toString('utf8');
|
|
1595
|
+
reset = true;
|
|
1596
|
+
} catch {
|
|
1597
|
+
log = '';
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
}
|
|
1601
|
+
return sendJson(res, 200, {
|
|
1602
|
+
ok: true,
|
|
1603
|
+
run: runView(run),
|
|
1604
|
+
stopping: false,
|
|
1605
|
+
log,
|
|
1606
|
+
nextOffset: 0,
|
|
1607
|
+
reset,
|
|
1608
|
+
});
|
|
1609
|
+
}
|
|
1610
|
+
const reset = offset < entry.logStart;
|
|
1611
|
+
const from = Math.max(offset, entry.logStart);
|
|
1612
|
+
return sendJson(res, 200, {
|
|
1613
|
+
ok: true,
|
|
1614
|
+
run: runView(run),
|
|
1615
|
+
stopping: entry.stopping,
|
|
1616
|
+
log: entry.log.slice(from - entry.logStart),
|
|
1617
|
+
nextOffset: entry.logStart + entry.log.length,
|
|
1618
|
+
reset,
|
|
1619
|
+
});
|
|
1620
|
+
}
|
|
1621
|
+
|
|
1622
|
+
if (method === 'GET' && tail === '/runs') {
|
|
1623
|
+
const projectId = text(parsed.searchParams.get('projectId'), 64);
|
|
1624
|
+
const store = readStore(root).store;
|
|
1625
|
+
const runs = store.runs
|
|
1626
|
+
.filter((run) => !projectId || run.projectId === projectId)
|
|
1627
|
+
.slice()
|
|
1628
|
+
.sort((a, b) => (a.startedAt < b.startedAt ? 1 : -1))
|
|
1629
|
+
.map(runView);
|
|
1630
|
+
return sendJson(res, 200, { ok: true, runs });
|
|
1631
|
+
}
|
|
1632
|
+
|
|
1633
|
+
if (method === 'DELETE' && tail === '/run') {
|
|
1634
|
+
const id = text(parsed.searchParams.get('id'), 64);
|
|
1635
|
+
if (RUNNING.has(id)) {
|
|
1636
|
+
return sendJson(res, 409, { ok: false, error: '运行中,不能删除' });
|
|
1637
|
+
}
|
|
1638
|
+
const store = readStoreForWrite(root);
|
|
1639
|
+
const run = findRun(store, id);
|
|
1640
|
+
if (!run) return sendJson(res, 404, { ok: false, error: '运行记录不存在' });
|
|
1641
|
+
removeRunArtifacts(root, run);
|
|
1642
|
+
store.runs = store.runs.filter((r) => r.id !== id);
|
|
1643
|
+
const project = findProject(store, run.projectId);
|
|
1644
|
+
if (project && project.lastRunId === id) {
|
|
1645
|
+
const latest = store.runs
|
|
1646
|
+
.filter((r) => r.projectId === project.id)
|
|
1647
|
+
.sort((a, b) => (a.startedAt < b.startedAt ? 1 : -1))[0];
|
|
1648
|
+
project.lastRunId = latest?.id ?? '';
|
|
1649
|
+
project.lastRunAt = latest?.startedAt ?? '';
|
|
1650
|
+
project.lastStatus = latest?.status ?? '';
|
|
1651
|
+
}
|
|
1652
|
+
writeStore(root, store);
|
|
1653
|
+
return sendJson(res, 200, { ok: true });
|
|
1654
|
+
}
|
|
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
|
+
|
|
2288
|
+
return next();
|
|
2289
|
+
} catch (err) {
|
|
2290
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2291
|
+
return sendJson(res, 500, { ok: false, error: message });
|
|
2292
|
+
}
|
|
2293
|
+
});
|
|
2294
|
+
},
|
|
2295
|
+
};
|
|
2296
|
+
}
|