lantern-harness 0.1.45 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (274) hide show
  1. package/CHANGELOG.md +242 -0
  2. package/README.md +25 -8
  3. package/builtin/case-backup-contract.mjs +27 -0
  4. package/builtin/case-workflow-contract.mjs +158 -0
  5. package/builtin/session/lh-fs.mjs +93 -4
  6. package/builtin/session/lh-nav-groups.mjs +36 -1
  7. package/builtin/session/mcp-client.mjs +7 -3
  8. package/builtin/session/session-runs.mjs +5 -1
  9. package/builtin/session/skill-validation.mjs +72 -0
  10. package/builtin/session/space-layout.mjs +8 -1
  11. package/builtin/session/space-skills.mjs +758 -0
  12. package/cli/data-root.mjs +21 -4
  13. package/cli/lantern.mjs +26 -1
  14. package/cli/mcp-server.mjs +3733 -0
  15. package/cli/server.mjs +10 -2
  16. package/config/app.defaults.json +4 -2
  17. package/dist/500.html +14 -6
  18. package/dist/_astro/Base.BQf1tZMl.css +1 -0
  19. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.Dm3O_y-S.js +2 -0
  20. package/dist/_astro/BusinessMapBoard.CYxHcku_.js +5 -0
  21. package/dist/_astro/CaseExecBoard.CK9aGPmH.js +1 -0
  22. package/dist/_astro/CaseExecutionBoard.C94pmIMQ.js +5 -0
  23. package/dist/_astro/CaseGenerateApp.D5xlk9At.js +10 -0
  24. package/dist/_astro/CasesLibrary.BHQC955x.js +21 -0
  25. package/dist/_astro/ChatApp.CIt15w_1.js +1 -0
  26. package/dist/_astro/ChatApp.d4a9R3YS.js +262 -0
  27. package/dist/_astro/{ConfirmDialog.DrrPf1MB.js → ConfirmDialog.DQFd6g2r.js} +1 -1
  28. package/dist/_astro/DashboardBoard.qgc1s7pG.js +5 -0
  29. package/dist/_astro/{DatePicker.Bkl71M49.js → DatePicker.BRO_CjVQ.js} +1 -1
  30. package/dist/_astro/DefectSubmitEntry.JI85N1-i.js +2 -0
  31. package/dist/_astro/DocsFileBrowser.z5JZ74cy.js +1 -0
  32. package/dist/_astro/{DocsPager.Duf4I68E.js → DocsPager.Dg765uHW.js} +1 -1
  33. package/dist/_astro/{DrawerField.BH3p4Q4D.js → DrawerField.CLdvmHc6.js} +1 -1
  34. package/dist/_astro/KnowledgeLibrary.mkShtVun.js +1 -0
  35. package/dist/_astro/LifeKrTasksBoard.DpAwQffE.js +1 -0
  36. package/dist/_astro/LifeKrTodosBoard.BIjPiZ8H.js +1 -0
  37. package/dist/_astro/LifeObjectivesBoard.DYwLHPEG.js +1 -0
  38. package/dist/_astro/LifePlanTypeSelect.CYaziESp.js +1 -0
  39. package/dist/_astro/{LifeReviewsBoard.BPXeVpg1.js → LifeReviewsBoard.DIxoWBDA.js} +3 -3
  40. package/dist/_astro/{LifeShared.tnT7aQON.js → LifeShared.DuFQsMEx.js} +2 -2
  41. package/dist/_astro/LifeStagesBoard.DtOri9EW.js +1 -0
  42. package/dist/_astro/LifeYearCycleSelect.ByJ9-PGg.js +1 -0
  43. package/dist/_astro/LifeYearPlansBoard.BQN07wcv.js +1 -0
  44. package/dist/_astro/MultiSelectDropdown.D-rbpivp.js +1 -0
  45. package/dist/_astro/{NamePromptDialog.Csfnh5eM.js → NamePromptDialog.KPCeXmri.js} +1 -1
  46. package/dist/_astro/NavLibraries.BO4ezcUc.js +1 -0
  47. package/dist/_astro/PluginsPage.B1VeDtLx.js +18 -0
  48. package/dist/_astro/PmBugsBoard.Ddl3kqqt.js +1 -0
  49. package/dist/_astro/PmIterationsBoard.BJN7disI.js +1 -0
  50. package/dist/_astro/{PmProjectDetail.DneFVBpy.js → PmProjectDetail.D78gWhqk.js} +1 -1
  51. package/dist/_astro/PmProjectsBoard.Bf8VB3t6.js +1 -0
  52. package/dist/_astro/PmRequirementsBoard.CDyNHN2a.js +1 -0
  53. package/dist/_astro/PmRequirementsBoard.DarfGIrL.js +1 -0
  54. package/dist/_astro/PmShared.TOjBbtV8.js +1 -0
  55. package/dist/_astro/ReportsPage.BXGduuY3.js +1 -0
  56. package/dist/_astro/ReqAnalysisBoard.WLtIfBg8.js +39 -0
  57. package/dist/_astro/RequirementBreakdownLibrary.DMoeTeqX.js +2 -0
  58. package/dist/_astro/RequirementsLibrary.Iv7zOqWe.js +1 -0
  59. package/dist/_astro/SearchableSelect.DXclLMJI.js +1 -0
  60. package/dist/_astro/SelectDropdown.D7IeyHDI.js +1 -0
  61. package/dist/_astro/SettingsDialog.BvDU9EU6.js +1 -0
  62. package/dist/_astro/SlideOverDrawer.CvyB-quk.js +1 -0
  63. package/dist/_astro/SpaceSwitcher.D9bBNQBZ.js +7 -0
  64. package/dist/_astro/{TableFieldConfig.C7O-mL-p.js → TableFieldConfig.DHj25OKN.js} +1 -1
  65. package/dist/_astro/{TagSelect.UUXgkMqJ.js → TagSelect.B_r2p0fp.js} +1 -1
  66. package/dist/_astro/TasksBoard.CXmGdylV.js +1 -0
  67. package/dist/_astro/TemplatesLibrary.DsL2q-wp.js +1 -0
  68. package/dist/_astro/TestReportsLibrary.BBC1TYgP.js +1 -0
  69. package/dist/_astro/TestStatsBoard.VXjP4hu6.js +1 -0
  70. package/dist/_astro/Toast.BydY-X7T.js +1 -0
  71. package/dist/_astro/TodosBoard.-yKgp06M.js +1 -0
  72. package/dist/_astro/UiAutoBoard.BD5ZyLHj.js +3 -0
  73. package/dist/_astro/UiAutoEnvPanel.DrHUOlmH.js +10 -0
  74. package/dist/_astro/UiAutoGenerationDialog.gypq1zP9.js +12 -0
  75. package/dist/_astro/UiAutoProjectsPage.Dhzr09E9.js +3 -0
  76. package/dist/_astro/app-config.BSO5r82v.js +1 -0
  77. package/dist/_astro/app-version.CkDFkv4s.js +1 -0
  78. package/dist/_astro/{bash-tools.D9HCzC_7.js → bash-tools.C4DJiRJs.js} +1 -1
  79. package/dist/_astro/business-map.BiJ85oxm.js +1 -0
  80. package/dist/_astro/business-map.DKwdW1VL.css +1 -0
  81. package/dist/_astro/case-fields.C03NY3zC.js +148 -0
  82. package/dist/_astro/case-gen-run.C4p8uyU3.js +26 -0
  83. package/dist/_astro/case-prompt.ByLTgz4r.js +2 -0
  84. package/dist/_astro/{case-review.TdDs1WFM.js → case-review.BodP2jKm.js} +2 -2
  85. package/dist/_astro/{case-template.Cd2xNbgy.js → case-template.CC2eXegU.js} +2 -2
  86. package/dist/_astro/case-types.BjF1BivA.js +1 -0
  87. package/dist/_astro/case-workflow-contract.BBQ9bbKL.js +1 -0
  88. package/dist/_astro/defect-submit.Dc49lFjm.css +1 -0
  89. package/dist/_astro/defect-workbench.DBmohR-y.js +6 -0
  90. package/dist/_astro/dialog.XgRGNF_Q.js +1 -0
  91. package/dist/_astro/doc-roots.C-20VD0x.js +1 -0
  92. package/dist/_astro/{hydrate-cache.B15Nrpq0.js → hydrate-cache.CMMErx63.js} +1 -1
  93. package/dist/_astro/i18n.CEWjL5GX.js +7 -0
  94. package/dist/_astro/{llm.DN5S1KBK.js → llm.BCYNgppW.js} +1 -1
  95. package/dist/_astro/mcp-tools.Kf-lupGn.js +7 -0
  96. package/dist/_astro/{open-docs-in-session.CRiZT022.js → open-docs-in-session.BoyV6R2A.js} +1 -1
  97. package/dist/_astro/plugins.ChGmBEkF.js +1 -0
  98. package/dist/_astro/project-docs.BRgNjXhG.js +1 -0
  99. package/dist/_astro/prompts-meta.VAjE4OET.js +2 -0
  100. package/dist/_astro/report-prompt.CwHuOcRN.js +1 -0
  101. package/dist/_astro/req-analysis.BLvcktvQ.js +31 -0
  102. package/dist/_astro/requirement-breakdown-library.l0rPd7b3.js +1 -0
  103. package/dist/_astro/{settings.38J2uD5M.js → settings.BojKNwUC.js} +2 -2
  104. package/dist/_astro/space-skills.CPucW8zt.js +1 -0
  105. package/dist/_astro/{spaces-client.DV04tRyD.js → spaces-client.B28rzu8J.js} +1 -1
  106. package/dist/_astro/story-review.dEBWTeOW.js +7 -0
  107. package/dist/_astro/test-points.BuNgdNcU.js +8 -0
  108. package/dist/_astro/test-reports.0gr6-c_0.js +19 -0
  109. package/dist/_astro/ui-auto-prompt.BmO3ja2m.js +8 -0
  110. package/dist/_astro/ui-auto.LUcREUMe.js +1 -0
  111. package/dist/_astro/{view-prefs.DhdLZjGh.js → view-prefs.CWc5cQ2q.js} +1 -1
  112. package/dist/business-map/index.html +988 -0
  113. package/dist/case-exec/index.html +15 -7
  114. package/dist/{prompts → case-execution}/index.html +17 -9
  115. package/dist/cases/api/index.html +988 -0
  116. package/dist/cases/automation/index.html +988 -0
  117. package/dist/cases/functional/index.html +988 -0
  118. package/dist/cases/generate/index.html +14 -6
  119. package/dist/cases/index.html +1 -1
  120. package/dist/cases/library/index.html +1 -980
  121. package/dist/cases/other/index.html +988 -0
  122. package/dist/cases/performance/index.html +988 -0
  123. package/dist/dashboard/index.html +15 -7
  124. package/dist/defect-rules/index.html +695 -0
  125. package/dist/defect-submit/index.html +695 -0
  126. package/dist/defect-submit/templates/index.html +695 -0
  127. package/dist/docs/changelog/index.html +289 -52
  128. package/dist/docs/install/index.html +50 -12
  129. package/dist/docs/manual/index.html +230 -82
  130. package/dist/knowledge/index.html +15 -7
  131. package/dist/life/kr-tasks/index.html +15 -7
  132. package/dist/life/kr-todos/index.html +15 -7
  133. package/dist/life/objectives/index.html +15 -7
  134. package/dist/life/reviews/index.html +15 -7
  135. package/dist/life/stages/index.html +15 -7
  136. package/dist/life/year-plans/index.html +15 -7
  137. package/dist/plugins/index.html +15 -7
  138. package/dist/pm/bugs/index.html +15 -7
  139. package/dist/pm/iterations/index.html +15 -7
  140. package/dist/pm/projects/detail/index.html +15 -7
  141. package/dist/pm/projects/index.html +15 -7
  142. package/dist/pm/requirements/index.html +15 -7
  143. package/dist/reports/index.html +15 -7
  144. package/dist/requirement-analysis/index.html +15 -7
  145. package/dist/requirement-breakdowns/index.html +988 -0
  146. package/dist/requirements/index.html +15 -7
  147. package/dist/tasks/index.html +15 -7
  148. package/dist/templates/index.html +15 -7
  149. package/dist/test-automation/index.html +15 -7
  150. package/dist/test-automation/projects/index.html +15 -7
  151. package/dist/test-reports/index.html +15 -7
  152. package/dist/test-stats/index.html +15 -7
  153. package/dist/todos/index.html +15 -7
  154. package/dist/workbench/index.html +14 -6
  155. package/docs/Codex-MCP/351/233/206/346/210/220.md +340 -0
  156. package/docs//344/270/232/345/212/241/345/234/260/345/233/276/350/257/204/344/274/260.md +39 -0
  157. package/docs//344/270/232/345/212/241/345/234/260/345/233/276/350/257/206/345/210/253/351/207/215/346/236/204/346/226/271/346/241/210.md +88 -0
  158. package/docs//344/274/232/350/257/235/346/217/222/344/273/266.md +28 -3
  159. package/docs//345/205/250/345/261/200/346/217/222/344/273/266.md +41 -1
  160. package/docs//345/256/211/350/243/205/346/211/213/345/206/214.md +65 -17
  161. package/docs//346/217/222/344/273/266/344/273/223/345/272/223/344/270/216/346/212/200/350/203/275/346/225/264/345/220/210/346/226/271/346/241/210.md +187 -0
  162. package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +219 -74
  163. package/lh-plugins/business-map/assistant.mjs +958 -0
  164. package/lh-plugins/business-map/auth-paths.mjs +61 -0
  165. package/lh-plugins/business-map/jobs.mjs +749 -0
  166. package/lh-plugins/business-map/login.mjs +295 -0
  167. package/lh-plugins/business-map/sources.mjs +1014 -0
  168. package/lh-plugins/case-automation/service.mjs +921 -0
  169. package/lh-plugins/case-automation/store.mjs +231 -0
  170. package/lh-plugins/case-automation/tables.mjs +115 -0
  171. package/lh-plugins/case-automation-prompt.mjs +57 -0
  172. package/lh-plugins/case-execution/assets.mjs +180 -0
  173. package/lh-plugins/case-execution/files.mjs +829 -0
  174. package/lh-plugins/case-execution/plans.mjs +318 -0
  175. package/lh-plugins/case-execution/service.mjs +1026 -0
  176. package/lh-plugins/case-execution-prompt.mjs +36 -0
  177. package/lh-plugins/lh-business-map.mjs +2431 -0
  178. package/lh-plugins/lh-case-automation.mjs +169 -0
  179. package/lh-plugins/lh-case-design.mjs +456 -0
  180. package/lh-plugins/lh-case-execution.mjs +356 -0
  181. package/lh-plugins/lh-case-review.mjs +29 -11
  182. package/lh-plugins/lh-config.mjs +13 -0
  183. package/lh-plugins/lh-defect-submit.mjs +989 -0
  184. package/lh-plugins/lh-project-docs.mjs +55 -140
  185. package/lh-plugins/lh-reports.mjs +29 -57
  186. package/lh-plugins/lh-req-analysis.mjs +32 -3
  187. package/lh-plugins/lh-req-breakdown-library.mjs +1084 -0
  188. package/lh-plugins/lh-uiauto.mjs +625 -24
  189. package/lh-plugins/plugin-prompts.mjs +20 -15
  190. package/lh-plugins/req-analysis-revision.mjs +24 -0
  191. package/lh-plugins/test-points-prompt.mjs +2 -3
  192. package/lh-plugins/uiauto-adapters/playwright.mjs +44 -4
  193. package/lh-plugins/uiauto-adapters/shared.mjs +4 -0
  194. package/lh-plugins/uiauto-auth-setup.mjs +218 -0
  195. package/lh-plugins/uiauto-explorer/apps.mjs +13 -2
  196. package/lh-plugins/uiauto-explorer/emit-files.mjs +16 -2
  197. package/lh-plugins/uiauto-explorer/ir.mjs +3 -0
  198. package/lh-plugins/uiauto-explorer/merge.mjs +37 -1
  199. package/lh-plugins/uiauto-explorer/navigation-guard.mjs +255 -0
  200. package/lh-plugins/uiauto-explorer/runner.mjs +80 -5
  201. package/lh-plugins/uiauto-explorer/sessions.mjs +334 -18
  202. package/lh-plugins/uiauto-node.mjs +102 -11
  203. package/lh-plugins/uiauto-prompt.mjs +20 -15
  204. package/lh-plugins/uiauto-sso.mjs +407 -0
  205. package/package.json +5 -2
  206. package/skills/case-automation-bridge/SKILL.md +27 -0
  207. package/skills/case-execution/SKILL.md +41 -0
  208. package/skills/lantern-defect-submit/SKILL.md +15 -0
  209. package/skills/lantern-workflow/SKILL.md +95 -0
  210. package/skills/office/SKILL.md +26 -0
  211. package/dist/_astro/Base.Bkt1lrgu.css +0 -1
  212. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.UKTVQqk7.js +0 -2
  213. package/dist/_astro/CaseExecBoard.DICluCbK.js +0 -1
  214. package/dist/_astro/CaseGenerateApp.Be3h5XPG.js +0 -10
  215. package/dist/_astro/CasesLibrary.Buys7Cy-.js +0 -21
  216. package/dist/_astro/ChatApp.D3BheKci.js +0 -227
  217. package/dist/_astro/DashboardBoard.Qvf8o4v1.js +0 -5
  218. package/dist/_astro/DocsFileBrowser.DwKBffbM.js +0 -1
  219. package/dist/_astro/KnowledgeLibrary.MDpMqeOd.js +0 -1
  220. package/dist/_astro/LifeKrTasksBoard.DsvW_S66.js +0 -1
  221. package/dist/_astro/LifeKrTodosBoard.D2KTqvg1.js +0 -1
  222. package/dist/_astro/LifeObjectivesBoard.B0cDK934.js +0 -1
  223. package/dist/_astro/LifePlanTypeSelect.BELDvMWU.js +0 -1
  224. package/dist/_astro/LifeStagesBoard.CZftLR9K.js +0 -1
  225. package/dist/_astro/LifeYearCycleSelect.Bw2eRbSm.js +0 -1
  226. package/dist/_astro/LifeYearPlansBoard.DB-RJFEl.js +0 -1
  227. package/dist/_astro/MultiSelectDropdown.CBC7aNOv.js +0 -1
  228. package/dist/_astro/NavLibraries.DdQYsZbe.js +0 -1
  229. package/dist/_astro/OverflowHint.CHZeFfUj.js +0 -1
  230. package/dist/_astro/PluginsPage.C1JnInH4.js +0 -17
  231. package/dist/_astro/PluginsPage.C3eEwy3K.js +0 -1
  232. package/dist/_astro/PmBugsBoard.CGpXUTPu.js +0 -1
  233. package/dist/_astro/PmIterationsBoard.BaKiFIam.js +0 -1
  234. package/dist/_astro/PmProjectsBoard.BxoMF9gK.js +0 -1
  235. package/dist/_astro/PmRequirementsBoard.-SI8VZXI.js +0 -1
  236. package/dist/_astro/PmRequirementsBoard.DsK6RF7Q.js +0 -1
  237. package/dist/_astro/PmShared.BK8kWRSV.js +0 -1
  238. package/dist/_astro/PromptMountDialog.mrTx3U5T.js +0 -1
  239. package/dist/_astro/PromptsLibrary.B_SUf47p.js +0 -1
  240. package/dist/_astro/ReportsPage.B9lGg1_s.js +0 -16
  241. package/dist/_astro/ReqAnalysisBoard.CIZKnCQH.js +0 -39
  242. package/dist/_astro/RequirementsLibrary.cJc-bnGQ.js +0 -1
  243. package/dist/_astro/SearchableSelect.SyLRS-Jj.js +0 -1
  244. package/dist/_astro/SelectDropdown.T3CKHaLt.js +0 -1
  245. package/dist/_astro/SettingsDialog.DYdtCvLc.js +0 -1
  246. package/dist/_astro/SpaceSwitcher.C47_S1g9.js +0 -7
  247. package/dist/_astro/TasksBoard.BUEg2BYk.js +0 -1
  248. package/dist/_astro/TemplatesLibrary.BLVIphXO.js +0 -1
  249. package/dist/_astro/TestReportsLibrary.DVq30Jae.js +0 -1
  250. package/dist/_astro/TestStatsBoard.-5BWQ6bI.js +0 -1
  251. package/dist/_astro/Toast.BO2NFckG.js +0 -1
  252. package/dist/_astro/TodosBoard.DI_lTp2e.js +0 -1
  253. package/dist/_astro/UiAutoBoard.ChFdgv7s.js +0 -2
  254. package/dist/_astro/UiAutoEnvPanel.B50q4kYb.js +0 -19
  255. package/dist/_astro/UiAutoGenerationDialog.CLkFAHrm.js +0 -1
  256. package/dist/_astro/UiAutoProjectsPage.DCsDeN5d.js +0 -3
  257. package/dist/_astro/app-config.DkyjuL-S.js +0 -1
  258. package/dist/_astro/app-version.Cy-5oZO2.js +0 -1
  259. package/dist/_astro/case-fields.CmePqYfh.js +0 -148
  260. package/dist/_astro/case-gen-run.BklG1H8k.js +0 -22
  261. package/dist/_astro/case-types.DlFkbZJN.js +0 -1
  262. package/dist/_astro/dialog.DZHZCe_T.js +0 -1
  263. package/dist/_astro/doc-roots.CO3IBiY6.js +0 -1
  264. package/dist/_astro/i18n.D_aOCHSN.js +0 -7
  265. package/dist/_astro/markdown-client.BS19nLL3.js +0 -62
  266. package/dist/_astro/plugins.BRvXWHLe.js +0 -1
  267. package/dist/_astro/project-docs.CCjtiFjB.js +0 -1
  268. package/dist/_astro/prompts-meta.BUGutlsk.js +0 -2
  269. package/dist/_astro/report-prompt.B9C4cv84.js +0 -1
  270. package/dist/_astro/req-analysis.B12_MGMQ.js +0 -31
  271. package/dist/_astro/story-review.D2W5tEOY.js +0 -14
  272. package/dist/_astro/test-reports.CuIjlEyK.js +0 -19
  273. package/dist/_astro/ui-auto-prompt.H9_yhau9.js +0 -9
  274. package/dist/_astro/ui-auto.DMv940x4.js +0 -1
@@ -0,0 +1,1026 @@
1
+ import { caseContentFingerprint, recordManualVerification } from './assets.mjs';
2
+ import { assertTargetUrl, assessExecutionEvidence } from '../../builtin/case-workflow-contract.mjs';
3
+ import crypto from 'node:crypto';
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ import { getUserConfigDir } from '../../cli/user-config.mjs';
9
+ import { resolveModelForSpace } from '../lh-config.mjs';
10
+ import { readPluginPrompt } from '../plugin-prompts.mjs';
11
+ import {
12
+ callExplorer,
13
+ hasExplorer,
14
+ startExplorer,
15
+ stopExplorer,
16
+ } from '../uiauto-explorer/sessions.mjs';
17
+ import { CASE_EXECUTION_PROMPT_FILE } from '../case-execution-prompt.mjs';
18
+ import { EXECUTION_STATUSES, applyCaseExecutionResult, loadCaseDocument } from './files.mjs';
19
+
20
+ const PACKAGE_ROOT = path.resolve(fileURLToPath(new URL('../..', import.meta.url)));
21
+ const MODEL_TIMEOUT_MS = 90_000;
22
+ const MODEL_HEARTBEAT_MS = 5_000;
23
+ const MAX_TOOL_ROUNDS = 60;
24
+ const AI_RESULT_STATUSES = ['通过', '不通过', '阻塞', '跳过'];
25
+ const ACTIVE = new Map();
26
+ const AUTH_ACTIVE = new Map();
27
+ const CLIENTS = new Map();
28
+
29
+ const str = (value, max = 4000) => (typeof value === 'string' ? value.trim().slice(0, max) : '');
30
+ const now = () => new Date().toISOString();
31
+
32
+ export const caseExecutionRoot = (root) => path.join(root, '.lantern', 'local', 'case-execution');
33
+
34
+ const runsDir = (root) => path.join(caseExecutionRoot(root), 'runs');
35
+ const runPath = (root, runId) => path.join(runsDir(root), `${runId}.json`);
36
+
37
+ function readJson(file, fallback) {
38
+ try {
39
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
40
+ } catch {
41
+ return fallback;
42
+ }
43
+ }
44
+
45
+ function writeJson(file, value) {
46
+ fs.mkdirSync(path.dirname(file), { recursive: true });
47
+ const temp = `${file}.${process.pid}.${Date.now()}.tmp`;
48
+ fs.writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
49
+ fs.renameSync(temp, file);
50
+ }
51
+
52
+ function safeId(value) {
53
+ const id = str(value, 80);
54
+ if (!/^[a-zA-Z0-9_-]+$/.test(id)) {
55
+ throw Object.assign(new Error('执行编号无效'), { statusCode: 400 });
56
+ }
57
+ return id;
58
+ }
59
+
60
+ function targetUrl(value) {
61
+ let url;
62
+ try {
63
+ url = new URL(str(value, 2000));
64
+ } catch {
65
+ throw Object.assign(new Error('请填写有效的 HTTP / HTTPS 测试地址'), { statusCode: 400 });
66
+ }
67
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) {
68
+ throw Object.assign(new Error('测试地址必须是有效的 HTTP / HTTPS 地址'), {
69
+ statusCode: 400,
70
+ });
71
+ }
72
+ return url.href;
73
+ }
74
+
75
+ function authRoot() {
76
+ return path.join(getUserConfigDir(), 'case-execution', 'auth');
77
+ }
78
+
79
+ function authKey(root, url) {
80
+ const space = crypto.createHash('sha256').update(path.resolve(root)).digest('hex');
81
+ const origin = crypto.createHash('sha256').update(new URL(url).origin).digest('hex');
82
+ return path.join(authRoot(), space, `${origin}.json`);
83
+ }
84
+
85
+ function savedAuthPath(root, url) {
86
+ const file = authKey(root, url);
87
+ return fs.existsSync(file) ? file : '';
88
+ }
89
+
90
+ function normalizeResult(raw) {
91
+ const status = AI_RESULT_STATUSES.includes(str(raw?.status, 20)) ? str(raw?.status, 20) : '阻塞';
92
+ return {
93
+ status,
94
+ actualResult: str(raw?.actualResult ?? raw?.actual_result, 30000),
95
+ rationale: str(raw?.rationale, 12000),
96
+ unverified: Array.isArray(raw?.unverified)
97
+ ? raw.unverified
98
+ .map((item) => str(item, 1000))
99
+ .filter(Boolean)
100
+ .slice(0, 100)
101
+ : [],
102
+ blocker: str(raw?.blocker, 4000),
103
+ stepResults: Array.isArray(raw?.stepResults)
104
+ ? raw.stepResults
105
+ .slice(0, 100)
106
+ .map((item) => ({
107
+ expected: str(item?.expected, 4000),
108
+ actual: str(item?.actual, 4000),
109
+ passed: item?.passed === true,
110
+ evidence: str(item?.evidence, 2000),
111
+ }))
112
+ .filter((item) => item.expected || item.actual || item.evidence)
113
+ : [],
114
+ };
115
+ }
116
+
117
+ function emptyRun({ casePath, rowIndex, caseData, fileHash, target, authPath }) {
118
+ const at = now();
119
+ return {
120
+ version: 1,
121
+ id: crypto.randomUUID(),
122
+ casePath,
123
+ rowIndex,
124
+ case: caseData,
125
+ fileHash,
126
+ target: {
127
+ url: target,
128
+ authPath: authPath || '',
129
+ },
130
+ status: 'idle',
131
+ runId: '',
132
+ seq: 0,
133
+ events: [],
134
+ progress: {
135
+ label: '等待执行',
136
+ elapsedSeconds: 0,
137
+ toolCount: 0,
138
+ },
139
+ result: null,
140
+ confirmed: null,
141
+ error: '',
142
+ createdAt: at,
143
+ updatedAt: at,
144
+ };
145
+ }
146
+
147
+ function publicRun(run) {
148
+ return {
149
+ ...run,
150
+ target: { ...run.target, authPath: run.target.authPath ? '[local]' : '' },
151
+ };
152
+ }
153
+
154
+ function appendEvent(run, event, root) {
155
+ run.seq += 1;
156
+ const item = {
157
+ id: crypto.randomUUID(),
158
+ seq: run.seq,
159
+ at: now(),
160
+ ...event,
161
+ };
162
+ run.events.push(item);
163
+ run.events = run.events.slice(-800);
164
+ run.updatedAt = now();
165
+ for (const res of CLIENTS.get(`${root}\0${run.id}`) || []) {
166
+ if (res.destroyed || res.writableEnded) continue;
167
+ res.write(`data: ${JSON.stringify(item)}\n\n`);
168
+ }
169
+ return item;
170
+ }
171
+
172
+ function saveRun(root, run) {
173
+ run.updatedAt = now();
174
+ writeJson(runPath(root, run.id), run);
175
+ }
176
+
177
+ function loadRun(root, runId) {
178
+ const run = readJson(runPath(root, safeId(runId)), null);
179
+ if (!run) throw Object.assign(new Error('执行记录不存在'), { statusCode: 404 });
180
+ if (run.status === 'running' && !ACTIVE.has(`${root}\0${run.id}`)) {
181
+ run.status = 'interrupted';
182
+ run.error = '服务重启导致执行中断,请重新执行或手动记录结果';
183
+ appendEvent(run, { type: 'error', title: '执行中断', detail: run.error }, root);
184
+ saveRun(root, run);
185
+ }
186
+ return run;
187
+ }
188
+
189
+ function listRuns(root, casePath = '') {
190
+ if (!fs.existsSync(runsDir(root))) return [];
191
+ return fs
192
+ .readdirSync(runsDir(root))
193
+ .filter((name) => name.endsWith('.json'))
194
+ .map((name) => readJson(path.join(runsDir(root), name), null))
195
+ .filter(Boolean)
196
+ .filter((run) => !casePath || run.casePath === casePath)
197
+ .sort((left, right) => String(right.createdAt).localeCompare(String(left.createdAt)))
198
+ .slice(0, 200)
199
+ .map((run) => publicRun(loadRun(root, run.id)));
200
+ }
201
+
202
+ function shotsDir(root, runId) {
203
+ return path.join(caseExecutionRoot(root), 'shots', runId);
204
+ }
205
+
206
+ function clip(value, max = 12000) {
207
+ const text = String(value ?? '');
208
+ return text.length > max ? `${text.slice(0, max)}\n...(已截断)` : text;
209
+ }
210
+
211
+ const TOOL_DEFS = [
212
+ {
213
+ type: 'function',
214
+ function: {
215
+ name: 'case_browser_open',
216
+ description: '打开当前测试目标地址。第一次执行必须先调用。',
217
+ parameters: {
218
+ type: 'object',
219
+ properties: {
220
+ url: { type: 'string', description: '默认使用任务目标;可传相对路径' },
221
+ },
222
+ },
223
+ },
224
+ },
225
+ {
226
+ type: 'function',
227
+ function: {
228
+ name: 'case_browser_snapshot',
229
+ description: '读取当前页面可交互元素快照,ref 只在本页有效。',
230
+ parameters: {
231
+ type: 'object',
232
+ properties: {
233
+ depth: { type: 'number' },
234
+ targetRef: { type: 'string' },
235
+ },
236
+ },
237
+ },
238
+ },
239
+ {
240
+ type: 'function',
241
+ function: {
242
+ name: 'case_browser_click',
243
+ description: '点击页面元素,成功后自动返回新快照。',
244
+ parameters: {
245
+ type: 'object',
246
+ properties: {
247
+ ref: { type: 'string' },
248
+ note: { type: 'string' },
249
+ },
250
+ required: ['ref'],
251
+ },
252
+ },
253
+ },
254
+ {
255
+ type: 'function',
256
+ function: {
257
+ name: 'case_browser_fill',
258
+ description: '清空并填写输入框。',
259
+ parameters: {
260
+ type: 'object',
261
+ properties: {
262
+ ref: { type: 'string' },
263
+ text: { type: 'string' },
264
+ note: { type: 'string' },
265
+ },
266
+ required: ['ref', 'text'],
267
+ },
268
+ },
269
+ },
270
+ {
271
+ type: 'function',
272
+ function: {
273
+ name: 'case_browser_select',
274
+ description: '选择下拉选项。',
275
+ parameters: {
276
+ type: 'object',
277
+ properties: {
278
+ ref: { type: 'string' },
279
+ value: { type: 'string' },
280
+ note: { type: 'string' },
281
+ },
282
+ required: ['ref', 'value'],
283
+ },
284
+ },
285
+ },
286
+ {
287
+ type: 'function',
288
+ function: {
289
+ name: 'case_browser_press',
290
+ description: '按键盘按键。',
291
+ parameters: {
292
+ type: 'object',
293
+ properties: {
294
+ key: { type: 'string' },
295
+ ref: { type: 'string' },
296
+ },
297
+ required: ['key'],
298
+ },
299
+ },
300
+ },
301
+ {
302
+ type: 'function',
303
+ function: {
304
+ name: 'case_browser_hover',
305
+ description: '悬停到页面元素。',
306
+ parameters: {
307
+ type: 'object',
308
+ properties: {
309
+ ref: { type: 'string' },
310
+ note: { type: 'string' },
311
+ },
312
+ required: ['ref'],
313
+ },
314
+ },
315
+ },
316
+ {
317
+ type: 'function',
318
+ function: {
319
+ name: 'case_browser_wait',
320
+ description: '等待页面出现指定文案或等待指定毫秒。',
321
+ parameters: {
322
+ type: 'object',
323
+ properties: {
324
+ text: { type: 'string' },
325
+ ms: { type: 'number' },
326
+ timeout: { type: 'number' },
327
+ },
328
+ },
329
+ },
330
+ },
331
+ {
332
+ type: 'function',
333
+ function: {
334
+ name: 'case_browser_screenshot',
335
+ description: '保存当前页面截图作为执行证据。',
336
+ parameters: {
337
+ type: 'object',
338
+ properties: { label: { type: 'string' } },
339
+ },
340
+ },
341
+ },
342
+ {
343
+ type: 'function',
344
+ function: {
345
+ name: 'case_browser_console',
346
+ description: '读取当前页面控制台错误、警告和 pageerror。',
347
+ parameters: { type: 'object', properties: {} },
348
+ },
349
+ },
350
+ {
351
+ type: 'function',
352
+ function: {
353
+ name: 'case_browser_network',
354
+ description: '读取最近失败的网络请求。',
355
+ parameters: { type: 'object', properties: {} },
356
+ },
357
+ },
358
+ {
359
+ type: 'function',
360
+ function: {
361
+ name: 'finish_case_execution',
362
+ description: '提交本条用例的最终执行结论。完成所有可执行步骤后必须调用。',
363
+ parameters: {
364
+ type: 'object',
365
+ properties: {
366
+ status: { type: 'string', enum: AI_RESULT_STATUSES },
367
+ actualResult: { type: 'string' },
368
+ rationale: { type: 'string' },
369
+ unverified: { type: 'array', items: { type: 'string' } },
370
+ blocker: { type: 'string' },
371
+ stepResults: {
372
+ type: 'array',
373
+ items: {
374
+ type: 'object',
375
+ properties: {
376
+ expected: { type: 'string' },
377
+ actual: { type: 'string' },
378
+ passed: { type: 'boolean' },
379
+ evidence: { type: 'string' },
380
+ },
381
+ },
382
+ },
383
+ },
384
+ required: ['status', 'actualResult', 'rationale'],
385
+ },
386
+ },
387
+ },
388
+ ];
389
+
390
+ function modelMessages(skill, run) {
391
+ return [
392
+ {
393
+ role: 'system',
394
+ content: `${skill}
395
+
396
+ 当前任务只执行一条测试用例。目标地址:${run.target.url}
397
+ 你可以使用提供的浏览器工具。每次操作前先读取快照,元素 ref 在页面变化后会失效。
398
+ 只有真正观察到预期结果才能判定通过。最终必须调用 finish_case_execution。
399
+ 安全边界:只操作当前目标站点;遇到验证码、登录墙、系统原生弹窗、文件选择器、支付、短信验证码或不可逆高风险动作时标记阻塞。`,
400
+ },
401
+ {
402
+ role: 'user',
403
+ content: JSON.stringify({
404
+ case: run.case,
405
+ targetUrl: run.target.url,
406
+ requiredExecutionColumns: {
407
+ status: true,
408
+ actualResult: true,
409
+ },
410
+ }),
411
+ },
412
+ ];
413
+ }
414
+
415
+ async function callModel(settings, messages, signal) {
416
+ const url = new URL(settings.baseURL.replace(/\/+$/, '') + '/chat/completions');
417
+ const response = await fetch(url, {
418
+ method: 'POST',
419
+ headers: {
420
+ 'Content-Type': 'application/json',
421
+ Authorization: `Bearer ${settings.apiKey}`,
422
+ },
423
+ body: JSON.stringify({
424
+ model: settings.model,
425
+ messages,
426
+ tools: TOOL_DEFS,
427
+ tool_choice: 'auto',
428
+ temperature: 0.1,
429
+ stream: false,
430
+ }),
431
+ signal,
432
+ });
433
+ if (!response.ok) {
434
+ const detail = (await response.text().catch(() => '')).slice(0, 400);
435
+ throw new Error(`模型请求失败(HTTP ${response.status})${detail ? `:${detail}` : ''}`);
436
+ }
437
+ const data = await response.json();
438
+ return {
439
+ usage: data.usage || {},
440
+ message: data.choices?.[0]?.message || {},
441
+ };
442
+ }
443
+
444
+ async function executeTool(root, run, name, args) {
445
+ if (name === 'case_browser_open') {
446
+ const result = await callExplorer(run.id, 'open', {
447
+ url: assertTargetUrl(
448
+ str(args.url, 2000) || run.target.url,
449
+ run.target.url,
450
+ run.target.allowedOrigins || [],
451
+ ),
452
+ settle: 450,
453
+ });
454
+ return {
455
+ url: result.url,
456
+ title: result.title,
457
+ count: result.count,
458
+ snapshot: clip(result.snapshot),
459
+ };
460
+ }
461
+ if (name === 'case_browser_snapshot') {
462
+ const result = await callExplorer(run.id, 'snapshot', {
463
+ depth: Number(args.depth) || 7,
464
+ targetRef: str(args.targetRef, 40),
465
+ });
466
+ return {
467
+ url: result.url,
468
+ title: result.title,
469
+ count: result.count,
470
+ snapshot: clip(result.snapshot),
471
+ };
472
+ }
473
+ if (
474
+ name === 'case_browser_click' ||
475
+ name === 'case_browser_fill' ||
476
+ name === 'case_browser_select' ||
477
+ name === 'case_browser_hover'
478
+ ) {
479
+ const action = name.replace('case_browser_', '');
480
+ const result = await callExplorer(
481
+ run.id,
482
+ 'action',
483
+ {
484
+ action,
485
+ ref: str(args.ref, 40),
486
+ text: str(args.text, 8000),
487
+ value: str(args.value, 8000),
488
+ note: str(args.note, 200),
489
+ },
490
+ 90_000,
491
+ );
492
+ return {
493
+ ok: true,
494
+ url: result.url,
495
+ snapshot: clip(result.snapshot, 9000),
496
+ };
497
+ }
498
+ if (name === 'case_browser_press') {
499
+ const result = await callExplorer(run.id, 'action', {
500
+ action: 'press',
501
+ ref: str(args.ref, 40),
502
+ key: str(args.key, 40),
503
+ });
504
+ return { ok: true, url: result.url, snapshot: clip(result.snapshot, 9000) };
505
+ }
506
+ if (name === 'case_browser_wait') {
507
+ const result = await callExplorer(
508
+ run.id,
509
+ 'waitFor',
510
+ {
511
+ text: str(args.text, 200),
512
+ ms: Number(args.ms) || 0,
513
+ timeout: Math.min(60_000, Math.max(1000, Number(args.timeout) || 15_000)),
514
+ },
515
+ 90_000,
516
+ );
517
+ return { ok: true, url: result.url, snapshot: clip(result.snapshot, 9000) };
518
+ }
519
+ if (name === 'case_browser_screenshot') {
520
+ const result = await callExplorer(run.id, 'screenshot', {
521
+ label: str(args.label, 80) || `step-${run.progress.toolCount}`,
522
+ });
523
+ const url = `/__tb_case_run/runs/${encodeURIComponent(run.id)}/shots/${encodeURIComponent(result.file)}`;
524
+ appendEvent(run, { type: 'screenshot', title: '执行截图', detail: result.file, url }, root);
525
+ return { ok: true, file: result.file, url };
526
+ }
527
+ if (name === 'case_browser_console') {
528
+ const result = await callExplorer(run.id, 'console', {});
529
+ return { count: result.messages?.length || 0, messages: (result.messages || []).slice(-40) };
530
+ }
531
+ if (name === 'case_browser_network') {
532
+ const result = await callExplorer(run.id, 'network', {});
533
+ return { count: result.requests?.length || 0, requests: (result.requests || []).slice(-40) };
534
+ }
535
+ throw new Error(`未知工具:${name}`);
536
+ }
537
+
538
+ async function executeRun(root, run, skill, settings, signal) {
539
+ const active = ACTIVE.get(`${root}\0${run.id}`);
540
+ try {
541
+ run.status = 'running';
542
+ saveRun(root, run);
543
+ appendEvent(run, { type: 'status', title: '开始执行', detail: run.case.title }, root);
544
+ fs.mkdirSync(caseExecutionRoot(root), { recursive: true });
545
+ if (run.target.authPath && !fs.existsSync(run.target.authPath)) {
546
+ throw new Error('目标登录态不存在,请先填写登录态文件或完成手动登录');
547
+ }
548
+ await startExplorer({
549
+ baseDir: caseExecutionRoot(root),
550
+ project: { dir: PACKAGE_ROOT },
551
+ sessionId: run.id,
552
+ baseURL: run.target.url,
553
+ headed: true,
554
+ storageState: run.target.authPath,
555
+ allowedOrigins: [new URL(run.target.url).origin, ...(run.target.allowedOrigins || [])],
556
+ });
557
+ fs.mkdirSync(shotsDir(root, run.id), { recursive: true });
558
+ const messages = modelMessages(skill, run);
559
+ const startedAt = Date.now();
560
+ let result = null;
561
+ for (let round = 0; round < MAX_TOOL_ROUNDS && !result; round += 1) {
562
+ if (signal.aborted) throw signal.reason || new Error('已停止');
563
+ run.progress.elapsedSeconds = Math.max(1, Math.round((Date.now() - startedAt) / 1000));
564
+ run.progress.label = `AI 正在执行(第 ${round + 1} 轮)`;
565
+ saveRun(root, run);
566
+ const heartbeat = setInterval(() => {
567
+ run.progress.elapsedSeconds = Math.max(1, Math.round((Date.now() - startedAt) / 1000));
568
+ run.progress.label = `AI 正在执行(已等待 ${run.progress.elapsedSeconds} 秒)`;
569
+ appendEvent(
570
+ run,
571
+ {
572
+ type: 'progress',
573
+ title: run.progress.label,
574
+ detail: `${run.progress.toolCount} 次工具调用`,
575
+ },
576
+ root,
577
+ );
578
+ saveRun(root, run);
579
+ }, MODEL_HEARTBEAT_MS);
580
+ let response;
581
+ try {
582
+ response = await callModel(settings, messages, signal);
583
+ } finally {
584
+ clearInterval(heartbeat);
585
+ }
586
+ const message = response.message || {};
587
+ messages.push(message);
588
+ const toolCalls = Array.isArray(message.tool_calls) ? message.tool_calls : [];
589
+ if (!toolCalls.length) {
590
+ const content = str(message.content, 30000);
591
+ if (content) {
592
+ try {
593
+ const parsed = JSON.parse(
594
+ content.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, ''),
595
+ );
596
+ result = normalizeResult(parsed);
597
+ break;
598
+ } catch {
599
+ messages.push({
600
+ role: 'user',
601
+ content: '请继续执行;完成后必须调用 finish_case_execution,不要只返回普通文本。',
602
+ });
603
+ continue;
604
+ }
605
+ }
606
+ messages.push({
607
+ role: 'user',
608
+ content: '请继续执行,并在完成时调用 finish_case_execution。',
609
+ });
610
+ continue;
611
+ }
612
+ for (const call of toolCalls) {
613
+ if (signal.aborted) throw signal.reason || new Error('已停止');
614
+ const name = str(call?.function?.name, 100);
615
+ let args = {};
616
+ try {
617
+ args = JSON.parse(str(call?.function?.arguments, 20000) || '{}');
618
+ } catch {
619
+ messages.push({
620
+ role: 'tool',
621
+ tool_call_id: str(call?.id, 200),
622
+ content: JSON.stringify({ error: '工具参数不是合法 JSON' }),
623
+ });
624
+ continue;
625
+ }
626
+ if (name === 'finish_case_execution') {
627
+ result = normalizeResult(args);
628
+ messages.push({
629
+ role: 'tool',
630
+ tool_call_id: str(call?.id, 200),
631
+ content: JSON.stringify({ ok: true, accepted: true }),
632
+ });
633
+ break;
634
+ }
635
+ run.progress.toolCount += 1;
636
+ appendEvent(
637
+ run,
638
+ {
639
+ type: 'tool',
640
+ title: name,
641
+ detail: str(args.note, 300) || '执行浏览器操作',
642
+ status: 'running',
643
+ },
644
+ root,
645
+ );
646
+ try {
647
+ const output = await executeTool(root, run, name, args);
648
+ if (output.snapshot) {
649
+ const snapshot = String(output.snapshot)
650
+ .replace(/(Bearer\s+)[A-Za-z0-9._~+\/=-]+/gi, '$1[已隐藏]')
651
+ .replace(
652
+ /((?:password|token|api[_-]?key|authorization)\s*[:=]\s*)[^\s,;]+/gi,
653
+ '$1[已隐藏]',
654
+ );
655
+ appendEvent(
656
+ run,
657
+ {
658
+ type: 'observation',
659
+ title: '页面观察证据',
660
+ url: output.url || '',
661
+ detail: clip(snapshot, 12000),
662
+ },
663
+ root,
664
+ );
665
+ }
666
+ messages.push({
667
+ role: 'tool',
668
+ tool_call_id: str(call?.id, 200),
669
+ content: JSON.stringify(output),
670
+ });
671
+ appendEvent(
672
+ run,
673
+ {
674
+ type: 'tool',
675
+ title: name,
676
+ detail: str(args.note, 300) || '已完成',
677
+ status: 'done',
678
+ },
679
+ root,
680
+ );
681
+ } catch (error) {
682
+ const messageText = error instanceof Error ? error.message : String(error);
683
+ messages.push({
684
+ role: 'tool',
685
+ tool_call_id: str(call?.id, 200),
686
+ content: JSON.stringify({ error: messageText }),
687
+ });
688
+ appendEvent(
689
+ run,
690
+ { type: 'tool', title: name, detail: messageText, status: 'error' },
691
+ root,
692
+ );
693
+ }
694
+ }
695
+ }
696
+ if (!result) {
697
+ result = normalizeResult({
698
+ status: '阻塞',
699
+ actualResult: 'AI 执行达到工具轮次上限,未形成最终结论。',
700
+ rationale: '执行过程未完成全部步骤或未观察到可判定结果。',
701
+ blocker: '达到工具轮次上限',
702
+ });
703
+ }
704
+ if (!run.result && !result.actualResult) {
705
+ result.actualResult = result.blocker || result.rationale || '未完成用例执行';
706
+ }
707
+ run.evidenceAssessment = assessExecutionEvidence(result, run.events);
708
+ if (result.status === '通过' && !run.evidenceAssessment.sufficient) {
709
+ result.status = '阻塞';
710
+ result.blocker = '证据不足:' + run.evidenceAssessment.issues.join(';');
711
+ result.unverified = [...new Set([...result.unverified, ...run.evidenceAssessment.issues])];
712
+ }
713
+ run.result = result;
714
+ run.status = 'awaiting_confirmation';
715
+ run.progress.label = '执行完成,等待确认';
716
+ appendEvent(
717
+ run,
718
+ {
719
+ type: 'result',
720
+ title: '执行完成',
721
+ detail: `${result.status} · ${result.actualResult.slice(0, 160)}`,
722
+ },
723
+ root,
724
+ );
725
+ saveRun(root, run);
726
+ } catch (error) {
727
+ const aborted = signal.aborted;
728
+ const message = aborted ? '执行已停止' : error instanceof Error ? error.message : String(error);
729
+ run.status = aborted ? 'stopped' : 'error';
730
+ run.error = message;
731
+ run.result = normalizeResult({
732
+ status: '阻塞',
733
+ actualResult: message,
734
+ rationale: '执行未能完成。',
735
+ blocker: message,
736
+ unverified: ['全部用例步骤'],
737
+ });
738
+ appendEvent(
739
+ run,
740
+ {
741
+ type: 'error',
742
+ title: run.status === 'stopped' ? '执行已停止' : '执行失败',
743
+ detail: message,
744
+ },
745
+ root,
746
+ );
747
+ saveRun(root, run);
748
+ } finally {
749
+ if (hasExplorer(run.id)) stopExplorer(run.id);
750
+ active?.controller?.abort();
751
+ const key = `${root}\0${run.id}`;
752
+ for (const client of CLIENTS.get(key) || []) {
753
+ if (!client.destroyed && !client.writableEnded) client.end();
754
+ }
755
+ CLIENTS.delete(key);
756
+ ACTIVE.delete(`${root}\0${run.id}`);
757
+ }
758
+ }
759
+
760
+ function skillText(root) {
761
+ return (
762
+ readPluginPrompt(CASE_EXECUTION_PROMPT_FILE, root).trim() ||
763
+ '执行当前单条测试用例,真实操作并给出通过、不通过、阻塞或跳过的可核验结论。'
764
+ );
765
+ }
766
+
767
+ export function startRun(root, raw) {
768
+ if (ACTIVE.size) {
769
+ throw Object.assign(new Error('当前空间已有用例正在执行'), { statusCode: 409 });
770
+ }
771
+ const casePath = str(raw.casePath, 1000);
772
+ const rowIndex = Number(raw.rowIndex);
773
+ const url = targetUrl(raw.url || raw.targetUrl);
774
+ const authPath = str(raw.storageStatePath, 2000) || savedAuthPath(root, url) || '';
775
+ const authAbs = authPath ? path.resolve(authPath) : '';
776
+ if (authAbs && (!fs.existsSync(authAbs) || !fs.statSync(authAbs).isFile()))
777
+ throw Object.assign(new Error('登录态文件不存在'), { statusCode: 400 });
778
+ return (async () => {
779
+ const document = await loadCaseDocument(root, casePath);
780
+ if (ACTIVE.size)
781
+ throw Object.assign(new Error('已有用例正在执行,请等待结束'), { statusCode: 409 });
782
+ if (!document.executable) {
783
+ throw Object.assign(new Error(document.executionIssue), {
784
+ statusCode: 422,
785
+ });
786
+ }
787
+ if (!Number.isInteger(rowIndex) || rowIndex < 0 || rowIndex >= document.cases.length) {
788
+ throw Object.assign(new Error('用例行不存在'), { statusCode: 404 });
789
+ }
790
+ const caseData = document.cases[rowIndex];
791
+ const run = emptyRun({
792
+ casePath,
793
+ rowIndex,
794
+ caseData,
795
+ fileHash: document.fileHash,
796
+ target: url,
797
+ authPath: authAbs,
798
+ });
799
+ run.target.allowedOrigins = (Array.isArray(raw.allowedOrigins) ? raw.allowedOrigins : [])
800
+ .slice(0, 20)
801
+ .map((value) => new URL(targetUrl(value)).origin);
802
+ run.environment = {
803
+ name: str(raw.environment?.name, 100),
804
+ role: str(raw.environment?.role, 100),
805
+ build: str(raw.environment?.build, 200),
806
+ dataNote: str(raw.environment?.dataNote, 2000),
807
+ };
808
+ run.caseId = caseData.id;
809
+ run.caseFingerprint = caseContentFingerprint(caseData);
810
+ run.provenance = document.provenance;
811
+ if (document.provenance?.stale)
812
+ throw Object.assign(new Error('需求基线已变化,请重新生成或重新关联用例后执行'), {
813
+ statusCode: 409,
814
+ });
815
+ const settings = resolveModelForSpace(root);
816
+ if (!settings.baseURL || !settings.apiKey || !settings.model) {
817
+ throw Object.assign(new Error('请先在模型设置中配置可用模型'), { statusCode: 400 });
818
+ }
819
+ const controller = new AbortController();
820
+ run.status = 'running';
821
+ run.runId = run.id;
822
+ saveRun(root, run);
823
+ ACTIVE.set(`${root}\0${run.id}`, { controller, run });
824
+ void executeRun(root, run, skillText(root), settings, controller.signal);
825
+ return publicRun(run);
826
+ })();
827
+ }
828
+
829
+ export function getRun(root, runId) {
830
+ return publicRun(loadRun(root, runId));
831
+ }
832
+
833
+ export function listExecutionRuns(root, casePath) {
834
+ return listRuns(root, str(casePath, 1000));
835
+ }
836
+
837
+ export function stopRun(root, runId) {
838
+ const run = loadRun(root, runId);
839
+ const active = ACTIVE.get(`${root}\0${run.id}`);
840
+ if (!active) return publicRun(run);
841
+ active.controller.abort(new Error('用户停止执行'));
842
+ if (hasExplorer(run.id)) stopExplorer(run.id);
843
+ run.status = 'stopped';
844
+ run.error = '用户停止执行';
845
+ appendEvent(run, { type: 'status', title: '执行已停止', status: 'stopped' }, root);
846
+ saveRun(root, run);
847
+ return publicRun(run);
848
+ }
849
+
850
+ export async function confirmRun(root, runId, raw) {
851
+ const run = loadRun(root, runId);
852
+ if (run.status === 'running') {
853
+ throw Object.assign(new Error('用例仍在执行,请等待结束或先停止'), { statusCode: 409 });
854
+ }
855
+ const status = str(raw.status, 20);
856
+ const actualResult = str(raw.actualResult, 30000);
857
+ if (!EXECUTION_STATUSES.includes(status)) {
858
+ throw Object.assign(new Error('用例状态无效'), { statusCode: 400 });
859
+ }
860
+ if (!actualResult) {
861
+ throw Object.assign(new Error('实际结果不能为空'), { statusCode: 400 });
862
+ }
863
+ const currentDocument = await loadCaseDocument(root, run.casePath);
864
+ const currentCase = run.caseId
865
+ ? currentDocument.cases.find((item) => item.id === run.caseId)
866
+ : currentDocument.cases[run.rowIndex];
867
+ if (
868
+ !currentCase ||
869
+ (run.caseFingerprint && caseContentFingerprint(currentCase) !== run.caseFingerprint) ||
870
+ currentDocument.provenance?.stale ||
871
+ (run.provenance?.baselineId &&
872
+ currentDocument.provenance?.baselineId !== run.provenance.baselineId)
873
+ ) {
874
+ throw Object.assign(new Error('用例内容或需求基线已变化,请重新执行;历史结果保留'), {
875
+ statusCode: 409,
876
+ });
877
+ }
878
+ const applied = await applyCaseExecutionResult(root, {
879
+ path: run.casePath,
880
+ expectedFileHash: raw.expectedFileHash || run.fileHash,
881
+ rowIndex: currentCase.rowIndex,
882
+ status,
883
+ actualResult,
884
+ executor: str(raw.executor, 200) || '人工验证',
885
+ executedAt: now().replace('T', ' ').slice(0, 19),
886
+ evidence: run.events
887
+ .filter((event) => event.type === 'screenshot')
888
+ .map((event) => event.url)
889
+ .slice(-8)
890
+ .join('\n'),
891
+ defectNo: raw.defectNo === undefined ? currentCase.defectNo : str(raw.defectNo, 200),
892
+ });
893
+ recordManualVerification(
894
+ root,
895
+ await loadCaseDocument(root, run.casePath),
896
+ currentCase.rowIndex,
897
+ run.environment,
898
+ );
899
+ run.fileHash = applied.fileHash;
900
+ run.status = 'confirmed';
901
+ run.confirmed = {
902
+ status,
903
+ actualResult,
904
+ at: now(),
905
+ backup: applied.backup,
906
+ fileHash: applied.fileHash,
907
+ };
908
+ appendEvent(
909
+ run,
910
+ {
911
+ type: 'applied',
912
+ title: '结果已写入用例文件',
913
+ detail: `${status} · ${actualResult.slice(0, 120)}`,
914
+ },
915
+ root,
916
+ );
917
+ saveRun(root, run);
918
+ return { run: publicRun(run), applied };
919
+ }
920
+
921
+ export async function applyManualResult(root, raw) {
922
+ const status = str(raw.status, 20);
923
+ const actualResult = str(raw.actualResult, 30000);
924
+ if (!EXECUTION_STATUSES.includes(status)) {
925
+ throw Object.assign(new Error('用例状态无效'), { statusCode: 400 });
926
+ }
927
+ if (!actualResult) {
928
+ throw Object.assign(new Error('实际结果不能为空'), { statusCode: 400 });
929
+ }
930
+ return applyCaseExecutionResult(root, {
931
+ path: str(raw.casePath, 1000),
932
+ expectedFileHash: str(raw.expectedFileHash, 80),
933
+ rowIndex: Number(raw.rowIndex),
934
+ status,
935
+ actualResult,
936
+ executor: str(raw.executor, 200) || '人工',
937
+ executedAt: now().replace('T', ' ').slice(0, 19),
938
+ evidence: str(raw.evidence, 4000),
939
+ defectNo: str(raw.defectNo, 200),
940
+ });
941
+ }
942
+
943
+ export function subscribeRun(root, runId, after, res) {
944
+ const run = loadRun(root, runId);
945
+ const key = `${root}\0${run.id}`;
946
+ res.statusCode = 200;
947
+ res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
948
+ res.setHeader('Cache-Control', 'no-cache, no-transform');
949
+ res.setHeader('Connection', 'keep-alive');
950
+ res.flushHeaders?.();
951
+ for (const event of run.events.filter((item) => Number(item.seq) > Number(after || 0))) {
952
+ res.write(`data: ${JSON.stringify(event)}\n\n`);
953
+ }
954
+ if (run.status !== 'running') {
955
+ res.end();
956
+ return;
957
+ }
958
+ const set = CLIENTS.get(key) || new Set();
959
+ set.add(res);
960
+ CLIENTS.set(key, set);
961
+ reqOnClose(res, () => {
962
+ set.delete(res);
963
+ if (!set.size) CLIENTS.delete(key);
964
+ });
965
+ }
966
+
967
+ function reqOnClose(res, fn) {
968
+ res.once('close', fn);
969
+ res.once('finish', fn);
970
+ }
971
+
972
+ export async function startManualLogin(root, raw) {
973
+ if (AUTH_ACTIVE.size) {
974
+ throw Object.assign(new Error('已有登录窗口正在等待完成'), { statusCode: 409 });
975
+ }
976
+ const url = targetUrl(raw.url);
977
+ const { chromium } = await import('playwright');
978
+ const browser = await chromium.launch({ headless: false });
979
+ const context = await browser.newContext();
980
+ const page = await context.newPage();
981
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30_000 });
982
+ const id = crypto.randomUUID();
983
+ const session = { id, root, url, browser, context, page, status: 'awaiting_login' };
984
+ AUTH_ACTIVE.set(root, session);
985
+ return { ok: true, authId: id, status: session.status, url: page.url() };
986
+ }
987
+
988
+ export async function completeManualLogin(root) {
989
+ const session = AUTH_ACTIVE.get(root);
990
+ if (!session) {
991
+ throw Object.assign(new Error('没有等待完成的登录窗口'), { statusCode: 404 });
992
+ }
993
+ const pageUrl = new URL(session.page.url());
994
+ if (pageUrl.origin !== new URL(session.url).origin) {
995
+ throw Object.assign(new Error('请先完成登录并进入目标业务系统'), { statusCode: 409 });
996
+ }
997
+ const state = await session.context.storageState();
998
+ const file = authKey(root, session.url);
999
+ writeJson(file, state);
1000
+ await session.browser.close().catch(() => undefined);
1001
+ AUTH_ACTIVE.delete(root);
1002
+ return { ok: true, status: 'ready', authPath: file };
1003
+ }
1004
+
1005
+ export async function cancelManualLogin(root) {
1006
+ const session = AUTH_ACTIVE.get(root);
1007
+ if (!session) return { ok: true, status: 'idle' };
1008
+ await session.browser.close().catch(() => undefined);
1009
+ AUTH_ACTIVE.delete(root);
1010
+ return { ok: true, status: 'cancelled' };
1011
+ }
1012
+
1013
+ export function savedAuthFor(root, raw) {
1014
+ const url = targetUrl(raw.url);
1015
+ const file = savedAuthPath(root, url);
1016
+ return { exists: Boolean(file) };
1017
+ }
1018
+
1019
+ export function shotPath(root, runId, file) {
1020
+ const base = path.resolve(shotsDir(root, safeId(runId)));
1021
+ const abs = path.resolve(base, path.basename(str(file, 200)));
1022
+ if (!abs.startsWith(base + path.sep)) {
1023
+ throw Object.assign(new Error('截图路径无效'), { statusCode: 400 });
1024
+ }
1025
+ return abs;
1026
+ }