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
@@ -67,6 +67,7 @@ import {
67
67
  taskView,
68
68
  } from './uiauto-adapters/tasks.mjs';
69
69
  import { hasFilesInside, hasReportEntry, snapshotReport } from './uiauto-report.mjs';
70
+ import { readAutomationLinks, upsertAutomationLinks } from './case-automation/store.mjs';
70
71
  import { nodeInstallPlan, nodeStatus, withProjectNode, writeNvmrc } from './uiauto-node.mjs';
71
72
  import { resolvePackageManager } from './uiauto-pm.mjs';
72
73
  import {
@@ -89,6 +90,8 @@ import {
89
90
  scanEnvFiles,
90
91
  validateEnvEntries,
91
92
  } from './uiauto-env.mjs';
93
+ import { projectHasSsoConfig, runSsoLoginAndSave } from './uiauto-sso.mjs';
94
+ import { projectHasAuthSetup, runAuthSetupAndSave } from './uiauto-auth-setup.mjs';
92
95
  import {
93
96
  applySkeletonToStack,
94
97
  auditScaffold,
@@ -104,7 +107,9 @@ import {
104
107
  callExplorer,
105
108
  cleanupDraft,
106
109
  cleanupStaleDrafts,
110
+ cleanupStaleSessions,
107
111
  debugSession,
112
+ deleteGeneratedSession,
108
113
  detectBaseURL,
109
114
  detectEmitLayout,
110
115
  detectStorageState,
@@ -130,6 +135,8 @@ import {
130
135
  suggestedPath,
131
136
  verifySession,
132
137
  writeGeneratedFiles,
138
+ writeSessionDraftFiles,
139
+ revertGeneratedFiles,
133
140
  findPlaywrightConfig,
134
141
  mergeActivityLog,
135
142
  } from './uiauto-explorer/sessions.mjs';
@@ -288,6 +295,86 @@ export function shouldIgnoreTreeName(name) {
288
295
  return TREE_IGNORED_NAMES.has(String(name));
289
296
  }
290
297
 
298
+ /** 生成页文件树:允许看到 `.lantern-ai` 草稿,其余忽略集与骨架树相同 */
299
+ export function shouldIgnoreBrowseName(name) {
300
+ const n = String(name);
301
+ if (n === '.lantern-ai') return false;
302
+ return TREE_IGNORED_NAMES.has(n);
303
+ }
304
+
305
+ const MAX_BROWSE_FILES = 800;
306
+ const MAX_BROWSE_DEPTH = 8;
307
+ const MAX_FILE_READ_BYTES = 512 * 1024;
308
+
309
+ /**
310
+ * 项目目录浅树(生成 Tab 浏览用)。
311
+ * @returns {{ tree: Array<object>; truncated: boolean }}
312
+ */
313
+ export function browseProjectTree(rootDir) {
314
+ const root = path.resolve(rootDir);
315
+ let fileCount = 0;
316
+ let truncated = false;
317
+
318
+ function walk(abs, rel, depth) {
319
+ if (depth > MAX_BROWSE_DEPTH) {
320
+ truncated = true;
321
+ return [];
322
+ }
323
+ let names = [];
324
+ try {
325
+ names = fs.readdirSync(abs);
326
+ } catch {
327
+ return [];
328
+ }
329
+ names.sort((a, b) => a.localeCompare(b, 'en'));
330
+ const dirs = [];
331
+ const files = [];
332
+ for (const name of names) {
333
+ if (shouldIgnoreBrowseName(name)) continue;
334
+ if (
335
+ name.startsWith('.') &&
336
+ name !== '.lantern-ai' &&
337
+ name !== '.env' &&
338
+ !name.startsWith('.env.')
339
+ ) {
340
+ // 其它点文件(.gitignore 等)仍展示;点目录除 .lantern-ai 外跳过
341
+ try {
342
+ if (fs.statSync(path.join(abs, name)).isDirectory()) continue;
343
+ } catch {
344
+ continue;
345
+ }
346
+ }
347
+ const childAbs = path.join(abs, name);
348
+ const childRel = rel ? `${rel}/${name}` : name;
349
+ let st;
350
+ try {
351
+ st = fs.statSync(childAbs);
352
+ } catch {
353
+ continue;
354
+ }
355
+ if (st.isDirectory()) {
356
+ dirs.push({
357
+ path: childRel,
358
+ name,
359
+ dir: true,
360
+ children: walk(childAbs, childRel, depth + 1),
361
+ });
362
+ } else if (st.isFile()) {
363
+ fileCount += 1;
364
+ if (fileCount > MAX_BROWSE_FILES) {
365
+ truncated = true;
366
+ break;
367
+ }
368
+ files.push({ path: childRel, name, dir: false, bytes: st.size });
369
+ }
370
+ }
371
+ // 同级:文件夹在上、文件在下(各自保持名字序)
372
+ return [...dirs, ...files];
373
+ }
374
+
375
+ return { tree: walk(root, '', 0), truncated };
376
+ }
377
+
291
378
  /** 项目内相对路径(POSIX),用于前端展示 */
292
379
  function toPosixRel(base, abs) {
293
380
  return path.relative(base, abs).split(path.sep).join('/');
@@ -460,6 +547,21 @@ export function uiautoStorePaths(root) {
460
547
  /** 本机缓存目录(不进空间内容池):`<空间>/.lantern/local/uiauto` */
461
548
  export const UIAUTO_CACHE_DIR_NAME = 'uiauto';
462
549
 
550
+ /** 过期生成会话清扫限流:任意 agent 请求最多每小时扫一次磁盘 */
551
+ const SESSION_CLEANUP_INTERVAL_MS = 60 * 60 * 1000;
552
+ let lastSessionCleanupAt = 0;
553
+
554
+ function maybeCleanupStaleSessions(baseDir) {
555
+ const now = Date.now();
556
+ if (now - lastSessionCleanupAt < SESSION_CLEANUP_INTERVAL_MS) return;
557
+ lastSessionCleanupAt = now;
558
+ try {
559
+ cleanupStaleSessions(baseDir);
560
+ } catch {
561
+ // 清扫失败不挡主流程
562
+ }
563
+ }
564
+
463
565
  /**
464
566
  * 应用图标、生成会话这类只对本机有意义、体积还不小的数据放本机缓存目录,
465
567
  * 不混在 `自动化测试/` 的项目目录里。旧版本把这些放在内容目录,首次访问时搬过来。
@@ -758,6 +860,102 @@ export function setupPlanFor(input = {}, deps = {}) {
758
860
  };
759
861
  }
760
862
 
863
+ /**
864
+ * 挂载项目常已在终端装过依赖:平台 setup 记录仍是 idle,界面会一直显示「待安装」。
865
+ * 按磁盘探测:node_modules 里有 Playwright,以及本机 / 项目内 chromium 缓存。
866
+ */
867
+ export function detectPlaywrightInstall(dir) {
868
+ const root = String(dir || '');
869
+ const empty = { deps: false, browser: false };
870
+ if (!root || !fs.existsSync(root)) return empty;
871
+ const nm = path.join(root, 'node_modules');
872
+ if (!fs.existsSync(nm)) return empty;
873
+ const deps =
874
+ fs.existsSync(path.join(nm, '@playwright', 'test', 'package.json')) ||
875
+ fs.existsSync(path.join(nm, 'playwright', 'package.json')) ||
876
+ fs.existsSync(path.join(nm, 'playwright-core', 'package.json'));
877
+ if (!deps) return empty;
878
+
879
+ const hasChromiumDir = (folder) => {
880
+ try {
881
+ if (!folder || !fs.existsSync(folder)) return false;
882
+ return fs.readdirSync(folder).some((name) => /^chromium/i.test(String(name)));
883
+ } catch {
884
+ return false;
885
+ }
886
+ };
887
+
888
+ let browser = hasChromiumDir(path.join(nm, 'playwright-core', '.local-browsers'));
889
+ if (!browser) {
890
+ const home = process.env.HOME || process.env.USERPROFILE || '';
891
+ const caches = [
892
+ process.env.PLAYWRIGHT_BROWSERS_PATH,
893
+ home ? path.join(home, 'Library', 'Caches', 'ms-playwright') : '',
894
+ home ? path.join(home, '.cache', 'ms-playwright') : '',
895
+ ].filter(Boolean);
896
+ browser = caches.some((folder) => hasChromiumDir(folder));
897
+ }
898
+ // 依赖齐了、项目已能跑时,缓存路径偶发探测不到也不该卡在「待安装」
899
+ if (!browser && deps) browser = true;
900
+ return { deps, browser };
901
+ }
902
+
903
+ /**
904
+ * idle / 失败态下用磁盘探测回填步骤状态,只影响展示,不写回 store。
905
+ */
906
+ export function enrichSetupWithDisk(setup, project) {
907
+ const base = normalizeSetup(setup);
908
+ if (!project?.dir || project.framework !== 'playwright') return base;
909
+ if (base.status === 'running') return base;
910
+ // 平台装过且成功:以记录为准
911
+ if (base.status === 'done' && base.steps.some((step) => step.status === 'done')) return base;
912
+
913
+ const probe = detectPlaywrightInstall(project.dir);
914
+ if (!probe.deps) return base;
915
+
916
+ const plan = setupPlanFor({
917
+ framework: project.framework,
918
+ dir: project.dir,
919
+ packageManager: '',
920
+ });
921
+ const sourceSteps = base.steps.length
922
+ ? base.steps
923
+ : plan.steps.map((step) => ({
924
+ id: step.id,
925
+ label: step.label,
926
+ command: step.command,
927
+ status: 'pending',
928
+ startedAt: '',
929
+ finishedAt: '',
930
+ exitCode: null,
931
+ }));
932
+
933
+ const steps = sourceSteps.map((step) => {
934
+ const ready =
935
+ step.id === 'deps'
936
+ ? probe.deps
937
+ : step.id === 'browser'
938
+ ? probe.browser
939
+ : step.status === 'done';
940
+ if (!ready) return step;
941
+ return {
942
+ ...step,
943
+ status: 'done',
944
+ exitCode: 0,
945
+ finishedAt: step.finishedAt || new Date().toISOString(),
946
+ };
947
+ });
948
+ const allDone = steps.length > 0 && steps.every((step) => step.status === 'done');
949
+ return {
950
+ ...base,
951
+ status: allDone ? 'done' : base.status === 'idle' ? 'idle' : base.status,
952
+ steps,
953
+ error: allDone ? '' : base.error,
954
+ // 展示用:告诉前端这是目录探测,不是平台刚装完
955
+ detectedFromDisk: true,
956
+ };
957
+ }
958
+
761
959
  /**
762
960
  * 技术栈 → 空间里的骨架(缺文件时按内置版本补种子)。
763
961
  * 新建项目只看骨架文件,跟「提示词管理」里的提示词无关:
@@ -1090,6 +1288,10 @@ function normalizeProject(raw) {
1090
1288
  // 该项目的登录态文件(相对项目根):按项目记,换项目不会串味;
1091
1289
  // 留空时自动探测项目里的 auth*.json / .auth/ 等
1092
1290
  storageState: text(raw.storageState, 300),
1291
+ // 登录墙偏好:ask_each_time(默认)/ ui_orchestrate / sso
1292
+ loginStrategy: ['ask_each_time', 'ui_orchestrate', 'sso'].includes(raw.loginStrategy)
1293
+ ? raw.loginStrategy
1294
+ : 'ask_each_time',
1093
1295
  // 该项目用哪份提示词(提示词管理里的文件名):不同框架可以挂不同提示词
1094
1296
  promptFile: text(raw.promptFile, 200),
1095
1297
  // 默认环境名(.env.<ENV>):运行面板下拉的初始值,空串表示 `.env`(各环境共用)
@@ -1194,6 +1396,40 @@ function normalizeRun(raw) {
1194
1396
  .filter(Boolean)
1195
1397
  .slice(0, 50)
1196
1398
  : [],
1399
+ tests: Array.isArray(raw.tests)
1400
+ ? raw.tests
1401
+ .filter((item) => item && typeof item === 'object')
1402
+ .slice(0, 5000)
1403
+ .map((item) => ({
1404
+ title: text(item.title, 1000),
1405
+ file: text(item.file, 1024),
1406
+ line: intOr(item.line, 0, 0, Number.MAX_SAFE_INTEGER),
1407
+ tags: Array.isArray(item.tags)
1408
+ ? item.tags
1409
+ .map((tag) => text(tag, 100))
1410
+ .filter(Boolean)
1411
+ .slice(0, 20)
1412
+ : [],
1413
+ annotations: Array.isArray(item.annotations)
1414
+ ? item.annotations
1415
+ .map((annotation) => ({
1416
+ type: text(annotation?.type, 200),
1417
+ description: text(annotation?.description, 2000),
1418
+ }))
1419
+ .filter((annotation) => annotation.type)
1420
+ .slice(0, 20)
1421
+ : [],
1422
+ automationCaseId: text(item.automationCaseId, 200),
1423
+ status: text(item.status, 40),
1424
+ durationMs: intOr(item.durationMs, 0, 0, Number.MAX_SAFE_INTEGER),
1425
+ errors: Array.isArray(item.errors)
1426
+ ? item.errors
1427
+ .map((error) => text(error, 2000))
1428
+ .filter(Boolean)
1429
+ .slice(0, 20)
1430
+ : [],
1431
+ }))
1432
+ : [],
1197
1433
  reportRel: text(raw.reportRel, 1024),
1198
1434
  // Allure 静态报告快照目录 + 「有原始结果、可以 generate」标记
1199
1435
  allureRel: text(raw.allureRel, 1024),
@@ -1482,14 +1718,14 @@ function decorateProject(project, root) {
1482
1718
  const settingUp = SETUPS.get(project.id);
1483
1719
  const customTasks = normalizeCustomTasks(project.customTasks);
1484
1720
  const probe = health.exists ? buildProbe(project.dir) : null;
1485
- const setup = normalizeSetup(project.setup);
1721
+ let setup = enrichSetupWithDisk(project.setup, project);
1486
1722
  const plan = setupPlanFor({
1487
1723
  framework: project.framework,
1488
1724
  dir: project.dir,
1489
1725
  packageManager: probe?.packageManager ?? '',
1490
1726
  });
1491
1727
  // 装到一半进程还没起来 / 进程没了但记录还是 running:一律按「正在装」展示
1492
- if (settingUp) setup.status = 'running';
1728
+ if (settingUp) setup = { ...setup, status: 'running' };
1493
1729
  // 自动发现 → 套上用户在运行配置里改过的名称 / 命令。
1494
1730
  // 被忽略的命令只从「运行任务」下拉里消失,仍然随项目返回(`ignoredTasks`),
1495
1731
  // 运行配置里排在列表最后,点一下就能恢复。
@@ -1521,6 +1757,9 @@ function decorateProject(project, root) {
1521
1757
  // 登录态同理:项目上记的优先,其次读项目里的登录态文件(换项目要重新识别)
1522
1758
  storageState: project.storageState || '',
1523
1759
  detectedStorageState: health.exists ? safeDetectStorageState(project.dir) : '',
1760
+ loginStrategy: project.loginStrategy || 'ask_each_time',
1761
+ ssoConfigured: health.exists ? projectHasSsoConfig(project.dir, project.envName || '') : false,
1762
+ authSetupDetected: health.exists ? projectHasAuthSetup(project.dir) : false,
1524
1763
  // 环境面板的入口条件:Playwright 且项目按 .env.<ENV> 约定做的
1525
1764
  envName: project.envName || '',
1526
1765
  hasEnvConvention:
@@ -1789,6 +2028,7 @@ function finishRun(root, entry, runId, exitCode, spawnError) {
1789
2028
  run.failed = summary.failed;
1790
2029
  run.skipped = summary.skipped;
1791
2030
  run.flaky = summary.flaky;
2031
+ run.tests = summary.tests;
1792
2032
  if (summary.projectNames.length) run.projectNames = summary.projectNames;
1793
2033
  run.reportRel = reportRel;
1794
2034
  run.allureRel = allureRel;
@@ -1985,6 +2225,7 @@ function startRun(root, body) {
1985
2225
  taskId,
1986
2226
  taskLabel: task ? taskCommandLine(task) : '',
1987
2227
  projectNames: [],
2228
+ tests: [],
1988
2229
  reportRel: '',
1989
2230
  resultRel,
1990
2231
  logRel,
@@ -2469,7 +2710,7 @@ function stopProjectSetup(projectId) {
2469
2710
 
2470
2711
  /** 安装日志读法:跑着的用内存缓冲,结束的从日志文件尾部取(与 /run 一致) */
2471
2712
  function readSetupLog(root, project, offset) {
2472
- const setup = normalizeSetup(project.setup);
2713
+ const setup = enrichSetupWithDisk(project.setup, project);
2473
2714
  const entry = SETUPS.get(project.id);
2474
2715
  if (!entry) {
2475
2716
  let log = '';
@@ -2493,6 +2734,10 @@ function readSetupLog(root, project, offset) {
2493
2734
  }
2494
2735
  }
2495
2736
  }
2737
+ // 从未用平台装过、但目录里已有依赖:补一句说明,避免空白日志看着像「没装」
2738
+ if (!log && setup.detectedFromDisk && setup.status === 'done') {
2739
+ log = '已从项目目录检测到依赖与浏览器内核,无需再走「一键安装」。需要时可点「重新安装」。\n';
2740
+ }
2496
2741
  return {
2497
2742
  setup: { ...setup, status: setup.status },
2498
2743
  stopping: false,
@@ -3537,6 +3782,13 @@ export function lhUiautoPlugin() {
3537
3782
  if (typeof body.storageState === 'string') {
3538
3783
  project.storageState = text(body.storageState, 300);
3539
3784
  }
3785
+ if (typeof body.loginStrategy === 'string') {
3786
+ project.loginStrategy = ['ask_each_time', 'ui_orchestrate', 'sso'].includes(
3787
+ body.loginStrategy,
3788
+ )
3789
+ ? body.loginStrategy
3790
+ : 'ask_each_time';
3791
+ }
3540
3792
  // 记住这个项目默认用哪套环境(运行面板下拉的初始值)
3541
3793
  if (typeof body.envName === 'string') {
3542
3794
  project.envName = sanitizeEnvName(body.envName);
@@ -3571,6 +3823,72 @@ export function lhUiautoPlugin() {
3571
3823
  return sendJson(res, 200, { ok: true });
3572
3824
  }
3573
3825
 
3826
+ /* ── 项目文件树 / 读写(生成 Tab;写默认仅 .lantern-ai 草稿) ── */
3827
+
3828
+ if (method === 'GET' && tail === '/project/files') {
3829
+ const projectId = text(parsed.searchParams.get('projectId'), 64);
3830
+ const project = findProject(readStore(root).store, projectId);
3831
+ if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
3832
+ if (!fs.existsSync(project.dir) || !fs.statSync(project.dir).isDirectory()) {
3833
+ return sendJson(res, 400, { ok: false, error: '项目目录已不存在,先重新指定目录' });
3834
+ }
3835
+ const browsed = browseProjectTree(project.dir);
3836
+ return sendJson(res, 200, {
3837
+ ok: true,
3838
+ root: project.dir,
3839
+ tree: browsed.tree,
3840
+ truncated: browsed.truncated,
3841
+ });
3842
+ }
3843
+
3844
+ if (method === 'GET' && tail === '/project/file') {
3845
+ const projectId = text(parsed.searchParams.get('projectId'), 64);
3846
+ const rel = String(parsed.searchParams.get('path') || '').replace(/\\/g, '/');
3847
+ const project = findProject(readStore(root).store, projectId);
3848
+ if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
3849
+ const abs = resolveInside(project.dir, rel);
3850
+ if (!abs) return sendJson(res, 400, { ok: false, error: '路径非法' });
3851
+ if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
3852
+ return sendJson(res, 404, { ok: false, error: '文件不存在' });
3853
+ }
3854
+ const st = fs.statSync(abs);
3855
+ if (st.size > MAX_FILE_READ_BYTES) {
3856
+ return sendJson(res, 400, { ok: false, error: '文件过大,请用外部编辑器打开' });
3857
+ }
3858
+ const content = fs.readFileSync(abs, 'utf8');
3859
+ return sendJson(res, 200, {
3860
+ ok: true,
3861
+ path: toPosixRel(project.dir, abs),
3862
+ content,
3863
+ bytes: st.size,
3864
+ });
3865
+ }
3866
+
3867
+ if (method === 'PUT' && tail === '/project/file') {
3868
+ const body = JSON.parse((await readBodyLimited(req)) || '{}');
3869
+ const projectId = text(body.projectId, 64);
3870
+ const rel = String(body.path || '').replace(/\\/g, '/');
3871
+ const content = typeof body.content === 'string' ? body.content : '';
3872
+ const allow = body.allow === 'any' ? 'any' : 'draft';
3873
+ const project = findProject(readStore(root).store, projectId);
3874
+ if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
3875
+ const abs = resolveInside(project.dir, rel);
3876
+ if (!abs) return sendJson(res, 400, { ok: false, error: '路径非法' });
3877
+ const posix = toPosixRel(project.dir, abs);
3878
+ if (allow !== 'any' && posix.split('/')[0] !== '.lantern-ai') {
3879
+ return sendJson(res, 403, {
3880
+ ok: false,
3881
+ error: '正式源码请走「写入」确认;此处只能改 .lantern-ai 草稿',
3882
+ });
3883
+ }
3884
+ if (Buffer.byteLength(content, 'utf8') > MAX_FILE_READ_BYTES) {
3885
+ return sendJson(res, 400, { ok: false, error: '内容过大' });
3886
+ }
3887
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
3888
+ fs.writeFileSync(abs, content, 'utf8');
3889
+ return sendJson(res, 200, { ok: true, path: posix });
3890
+ }
3891
+
3574
3892
  /* ── 项目 Node 版本:读 .nvmrc / engines,列出本机已装版本 ── */
3575
3893
 
3576
3894
  if (method === 'GET' && tail === '/project/node') {
@@ -3952,6 +4270,66 @@ export function lhUiautoPlugin() {
3952
4270
  });
3953
4271
  }
3954
4272
 
4273
+ // 登录墙选 SSO:按 env 调接口登录,写入 .auth/admin.json
4274
+ if (method === 'POST' && tail === '/project/sso-login') {
4275
+ const body = JSON.parse((await readBodyLimited(req)) || '{}');
4276
+ const projectId = text(body.projectId, 64);
4277
+ const store = readStoreForWrite(root);
4278
+ const project = findProject(store, projectId);
4279
+ if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
4280
+ if (!fs.existsSync(project.dir)) {
4281
+ return sendJson(res, 400, { ok: false, error: '项目目录已不存在' });
4282
+ }
4283
+ const result = await runSsoLoginAndSave({
4284
+ dir: project.dir,
4285
+ envName: typeof body.envName === 'string' ? body.envName : project.envName || '',
4286
+ baseURL:
4287
+ text(body.baseURL, 500) || project.baseURL || safeDetectBaseURL(project.dir) || '',
4288
+ });
4289
+ if (!result.ok) {
4290
+ return sendJson(res, 400, { ok: false, error: result.error });
4291
+ }
4292
+ project.storageState = result.storageState;
4293
+ writeStore(root, store);
4294
+ return sendJson(res, 200, {
4295
+ ok: true,
4296
+ storageState: result.storageState,
4297
+ tokenSaved: result.tokenSaved,
4298
+ project: decorateProject(project, root),
4299
+ });
4300
+ }
4301
+
4302
+ // 登录墙自动链:跑项目 auth.setup / setup 工程,产出 storageState
4303
+ if (method === 'POST' && tail === '/project/auth-setup') {
4304
+ const body = JSON.parse((await readBodyLimited(req)) || '{}');
4305
+ const projectId = text(body.projectId, 64);
4306
+ const store = readStoreForWrite(root);
4307
+ const project = findProject(store, projectId);
4308
+ if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
4309
+ if (!fs.existsSync(project.dir)) {
4310
+ return sendJson(res, 400, { ok: false, error: '项目目录已不存在' });
4311
+ }
4312
+ const result = await runAuthSetupAndSave({
4313
+ dir: project.dir,
4314
+ envName: typeof body.envName === 'string' ? body.envName : project.envName || '',
4315
+ });
4316
+ if (!result.ok) {
4317
+ return sendJson(res, 400, {
4318
+ ok: false,
4319
+ error: result.error,
4320
+ output: result.output || '',
4321
+ });
4322
+ }
4323
+ project.storageState = result.storageState;
4324
+ writeStore(root, store);
4325
+ return sendJson(res, 200, {
4326
+ ok: true,
4327
+ storageState: result.storageState,
4328
+ command: result.command,
4329
+ project: decorateProject(project, root),
4330
+ });
4331
+ }
4332
+
3955
4333
  if (method === 'POST' && tail === '/project/env/clear-auth') {
3956
4334
  const body = JSON.parse((await readBodyLimited(req)) || '{}');
3957
4335
  const store = readStore(root).store;
@@ -4098,6 +4476,10 @@ export function lhUiautoPlugin() {
4098
4476
  /** 生成会话与应用图标属于本机数据,放 `.lantern/local/uiauto`,不落进项目目录 */
4099
4477
  const agentBaseDir = uiautoCachePaths(root).dir;
4100
4478
 
4479
+ // 过期生成会话(含截图)顺手清:不进工作台侧栏,留着只是盲盒缓存
4480
+ // 限流避免每个请求都扫磁盘;prepare / 列会话时仍会强制再跑一次
4481
+ maybeCleanupStaleSessions(agentBaseDir);
4482
+
4101
4483
  /** 应用图标缓存目录:抽一次存下来,下次直接读 */
4102
4484
  const appIconDir = path.join(agentBaseDir, 'app-icons');
4103
4485
 
@@ -4117,6 +4499,35 @@ export function lhUiautoPlugin() {
4117
4499
  return findProject(store, projectId);
4118
4500
  };
4119
4501
 
4502
+ const applyPinnedIterationTarget = (project, record, files) => {
4503
+ const iterationFile = text(record?.iterationFile, 500).replace(/\\/g, '/');
4504
+ if (!iterationFile) return files;
4505
+ const layout = detectEmitLayout(project.dir);
4506
+ const fixture = `${layout.fixturesDir}/test.ts`.replace(/\\/g, '/');
4507
+ const fixtureAbs = path.join(project.dir, fixture);
4508
+ const testImport = fs.existsSync(fixtureAbs)
4509
+ ? path.posix
4510
+ .relative(path.posix.dirname(iterationFile), fixture.replace(/\.ts$/, ''))
4511
+ .replace(/^([^.])/, './$1')
4512
+ : '@playwright/test';
4513
+ return files.map((file) =>
4514
+ file.role === 'spec'
4515
+ ? {
4516
+ ...file,
4517
+ path: iterationFile,
4518
+ testImport,
4519
+ content:
4520
+ testImport === '@playwright/test'
4521
+ ? file.content
4522
+ : file.content.replace(
4523
+ "import { test, expect } from '@playwright/test';",
4524
+ `import { test, expect } from '${testImport}';`,
4525
+ ),
4526
+ }
4527
+ : file,
4528
+ );
4529
+ };
4530
+
4120
4531
  const requireExplorer = async (sessionId) => {
4121
4532
  const record = readGeneratedSession(agentBaseDir, sessionId);
4122
4533
  if (!record) throw new Error('生成会话不存在');
@@ -4139,7 +4550,7 @@ export function lhUiautoPlugin() {
4139
4550
  return { record, project };
4140
4551
  };
4141
4552
 
4142
- if (method === 'GET' && tail.startsWith('/agent/shot/')) {
4553
+ if ((method === 'GET' || method === 'DELETE') && tail.startsWith('/agent/shot/')) {
4143
4554
  const rest = tail.slice('/agent/shot/'.length);
4144
4555
  const slash = rest.indexOf('/');
4145
4556
  const sessionId = slash === -1 ? '' : rest.slice(0, slash);
@@ -4152,6 +4563,10 @@ export function lhUiautoPlugin() {
4152
4563
  if (!isPathInside(dir, abs) || !fs.existsSync(abs)) {
4153
4564
  return sendJson(res, 404, { ok: false, error: '截图不存在' });
4154
4565
  }
4566
+ if (method === 'DELETE') {
4567
+ fs.unlinkSync(abs);
4568
+ return sendJson(res, 200, { ok: true });
4569
+ }
4155
4570
  res.statusCode = 200;
4156
4571
  res.setHeader('Content-Type', 'image/png');
4157
4572
  res.setHeader('Cache-Control', 'no-store');
@@ -4198,7 +4613,15 @@ export function lhUiautoPlugin() {
4198
4613
  headed: typeof body.headed === 'boolean' ? body.headed : existing.headed,
4199
4614
  plan: Array.isArray(body.plan) ? body.plan : undefined,
4200
4615
  ...(reset
4201
- ? { ir: null, lastVerify: null, savedPath: '', status: 'draft' }
4616
+ ? {
4617
+ ir: null,
4618
+ lastVerify: null,
4619
+ savedPath: '',
4620
+ status: 'draft',
4621
+ // 新一轮清空控制台 / 网络快照;试跑结果一并作废
4622
+ consoleLog: [],
4623
+ networkLog: [],
4624
+ }
4202
4625
  : {
4203
4626
  // 已写入 / 已试跑通过的会话不要被打回草稿
4204
4627
  status:
@@ -4231,6 +4654,7 @@ export function lhUiautoPlugin() {
4231
4654
  const created = createAgentSession(body);
4232
4655
  if (created.error) return sendJson(res, 404, { ok: false, error: created.error });
4233
4656
  cleanupStaleDrafts(created.project.dir);
4657
+ cleanupStaleSessions(agentBaseDir);
4234
4658
  return sendJson(res, 200, {
4235
4659
  ok: true,
4236
4660
  session: created.session,
@@ -4334,20 +4758,43 @@ export function lhUiautoPlugin() {
4334
4758
  if (method === 'POST' && (tail === '/agent/console' || tail === '/agent/network')) {
4335
4759
  const body = JSON.parse((await readBodyLimited(req)) || '{}');
4336
4760
  const sessionId = text(body.sessionId, 64);
4337
- // 控制台 / 网络是「读」操作:没有在跑的浏览器就直接回空表。
4338
- // 这里以前走 requireExplorer,导致前端一切到这个 Tab(含 HMR 重载后恢复)
4339
- // 就凭空拉起一个有头浏览器窗口(baseURL 不可达时停在 about:blank)。
4761
+ const record = readGeneratedSession(agentBaseDir, sessionId);
4762
+ // 控制台 / 网络是「读」:浏览器还在就取活数据并落盘;关掉后回本轮缓存。
4763
+ // 不走 requireExplorer,避免切 Tab / HMR 时凭空拉起浏览器。
4340
4764
  if (!hasExplorer(sessionId)) {
4341
4765
  return sendJson(res, 200, {
4342
4766
  ok: true,
4343
- messages: [],
4344
- requests: [],
4767
+ messages: Array.isArray(record?.consoleLog) ? record.consoleLog : [],
4768
+ requests: Array.isArray(record?.networkLog) ? record.networkLog : [],
4345
4769
  running: false,
4346
4770
  });
4347
4771
  }
4348
4772
  const cmd = tail === '/agent/console' ? 'console' : 'network';
4349
4773
  const result = await callExplorer(sessionId, cmd, {});
4350
- return sendJson(res, 200, { ok: true, ...result });
4774
+ const consoleLog = Array.isArray(result.messages)
4775
+ ? result.messages.slice(-80)
4776
+ : record?.consoleLog;
4777
+ const networkLog = Array.isArray(result.requests)
4778
+ ? result.requests.slice(-80)
4779
+ : record?.networkLog;
4780
+ // 活数据顺手写回会话:关浏览器后还能回看这一轮
4781
+ if (cmd === 'console' && Array.isArray(result.messages)) {
4782
+ saveGeneratedSession(agentBaseDir, {
4783
+ id: sessionId,
4784
+ consoleLog: result.messages.slice(-80),
4785
+ });
4786
+ } else if (cmd === 'network' && Array.isArray(result.requests)) {
4787
+ saveGeneratedSession(agentBaseDir, {
4788
+ id: sessionId,
4789
+ networkLog: result.requests.slice(-80),
4790
+ });
4791
+ }
4792
+ return sendJson(res, 200, {
4793
+ ok: true,
4794
+ ...result,
4795
+ messages: consoleLog ?? result.messages,
4796
+ requests: networkLog ?? result.requests,
4797
+ });
4351
4798
  }
4352
4799
 
4353
4800
  if (method === 'POST' && tail === '/agent/wait') {
@@ -4385,6 +4832,26 @@ export function lhUiautoPlugin() {
4385
4832
  if (method === 'POST' && tail === '/agent/close') {
4386
4833
  const body = JSON.parse((await readBodyLimited(req)) || '{}');
4387
4834
  const sessionId = text(body.sessionId, 64);
4835
+ // 关窗前尽量快照;超时要短,避免探索结束后浏览器还挂几十秒
4836
+ if (hasExplorer(sessionId)) {
4837
+ try {
4838
+ const [consoleResult, networkResult] = await Promise.all([
4839
+ callExplorer(sessionId, 'console', {}, 2500),
4840
+ callExplorer(sessionId, 'network', {}, 2500),
4841
+ ]);
4842
+ saveGeneratedSession(agentBaseDir, {
4843
+ id: sessionId,
4844
+ consoleLog: Array.isArray(consoleResult.messages)
4845
+ ? consoleResult.messages.slice(-80)
4846
+ : [],
4847
+ networkLog: Array.isArray(networkResult.requests)
4848
+ ? networkResult.requests.slice(-80)
4849
+ : [],
4850
+ });
4851
+ } catch {
4852
+ // 快照失败仍继续关浏览器
4853
+ }
4854
+ }
4388
4855
  const stopped = stopExplorer(sessionId);
4389
4856
  const record = readGeneratedSession(agentBaseDir, sessionId);
4390
4857
  if (record && record.status === 'exploring') {
@@ -4427,7 +4894,31 @@ export function lhUiautoPlugin() {
4427
4894
  ? body.activity
4428
4895
  : mergeActivityLog(existing.activity, body.activity)
4429
4896
  : undefined,
4897
+ // 规划说明(测试思路等)跟活动日志分开存:探索追加过程时不要冲掉
4898
+ narrative:
4899
+ typeof body.narrative === 'string'
4900
+ ? String(body.narrative).slice(0, 80000)
4901
+ : undefined,
4430
4902
  status: text(body.status, 40) || existing.status,
4903
+ chatSessionId:
4904
+ typeof body.chatSessionId === 'string'
4905
+ ? text(body.chatSessionId, 80) || existing.chatSessionId
4906
+ : undefined,
4907
+ // 代码页手改:null 清空;数组覆盖;不传保持原值
4908
+ editedFiles:
4909
+ body.editedFiles === null
4910
+ ? null
4911
+ : Array.isArray(body.editedFiles)
4912
+ ? body.editedFiles
4913
+ .slice(0, 40)
4914
+ .map((item) => ({
4915
+ path: text(item?.path, 400),
4916
+ content: typeof item?.content === 'string' ? item.content : '',
4917
+ role: text(item?.role, 32),
4918
+ language: text(item?.language, 32),
4919
+ }))
4920
+ .filter((item) => item.path)
4921
+ : undefined,
4431
4922
  });
4432
4923
  const emitted = emitCode(saved.ir || {}, saved.target);
4433
4924
  return sendJson(res, 200, {
@@ -4452,13 +4943,22 @@ export function lhUiautoPlugin() {
4452
4943
  pagesDir: '',
4453
4944
  fixturesDir: '',
4454
4945
  };
4455
- const multi = emitFiles(body.ir || {}, body.target, {
4946
+ const record = text(body.sessionId, 64)
4947
+ ? readGeneratedSession(agentBaseDir, text(body.sessionId, 64))
4948
+ : null;
4949
+ let multi = emitFiles(body.ir || {}, body.target, {
4456
4950
  testDir: layout.testDir,
4457
4951
  pagesDir: layout.pagesDir || undefined,
4458
4952
  fixturesDir: layout.fixturesDir || undefined,
4459
4953
  tag: text(body.tag, 40),
4460
4954
  hasBaseURL: Boolean(body.hasBaseURL),
4461
4955
  });
4956
+ if (project && record) {
4957
+ multi = {
4958
+ ...multi,
4959
+ files: applyPinnedIterationTarget(project, record, multi.files),
4960
+ };
4961
+ }
4462
4962
  return sendJson(res, 200, {
4463
4963
  ok: true,
4464
4964
  code: emitted.code,
@@ -4466,6 +4966,16 @@ export function lhUiautoPlugin() {
4466
4966
  language: emitted.language,
4467
4967
  files: multi.files,
4468
4968
  configPatch: multi.configPatch,
4969
+ suggestedPath: project
4970
+ ? suggestedPath({
4971
+ project,
4972
+ session: record || {
4973
+ target: body.target,
4974
+ title: body.title,
4975
+ ir: body.ir || {},
4976
+ },
4977
+ })
4978
+ : '',
4469
4979
  });
4470
4980
  }
4471
4981
 
@@ -4484,10 +4994,20 @@ export function lhUiautoPlugin() {
4484
4994
  }
4485
4995
  const project = agentProject(record.projectId);
4486
4996
  if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
4997
+ const draftFiles = Array.isArray(body.files)
4998
+ ? body.files
4999
+ .map((item) => ({
5000
+ path: text(item?.path, 400),
5001
+ content: typeof item?.content === 'string' ? item.content : '',
5002
+ role: text(item?.role, 32),
5003
+ }))
5004
+ .filter((item) => item.path)
5005
+ : undefined;
4487
5006
  const result = await verifySession({
4488
5007
  project,
4489
5008
  session: record,
4490
5009
  timeoutMs: intOr(body.timeoutMs, 180000, 10000, 600000),
5010
+ draftFiles,
4491
5011
  });
4492
5012
  saveGeneratedSession(agentBaseDir, {
4493
5013
  id: sessionId,
@@ -4498,7 +5018,8 @@ export function lhUiautoPlugin() {
4498
5018
  passed: Boolean(result.passed),
4499
5019
  exitCode: result.exitCode ?? null,
4500
5020
  durationMs: result.durationMs ?? 0,
4501
- log: String(result.log ?? '').slice(-4000),
5021
+ log: String(result.log ?? '').slice(-24000),
5022
+ logPath: result.logPath || '',
4502
5023
  },
4503
5024
  });
4504
5025
  return sendJson(res, 200, {
@@ -4525,7 +5046,9 @@ export function lhUiautoPlugin() {
4525
5046
  ...detectEmitLayout(project.dir),
4526
5047
  hasBaseURL: projectHasBaseURL(project.dir),
4527
5048
  });
4528
- files = emitted.files;
5049
+ files = applyPinnedIterationTarget(project, record, emitted.files);
5050
+ } else if (record.iterationFile) {
5051
+ files = applyPinnedIterationTarget(project, record, files);
4529
5052
  }
4530
5053
 
4531
5054
  const result = writeGeneratedFiles({
@@ -4543,17 +5066,61 @@ export function lhUiautoPlugin() {
4543
5066
  const savedPaths = result.paths.slice();
4544
5067
  // 主用例(spec)优先,试跑 / 验收 / 打开草稿都从它出发
4545
5068
  const spec = files.find((item) => item.role === 'spec')?.path || savedPaths[0] || '';
5069
+ // 与历史 savedPaths 合并,避免分批写入时丢掉上一批
5070
+ const prevSaved = Array.isArray(record.savedPaths) ? record.savedPaths : [];
5071
+ const mergedSaved = [...new Set([...prevSaved, ...savedPaths].filter(Boolean))];
4546
5072
  record = saveGeneratedSession(agentBaseDir, {
4547
5073
  id: sessionId,
4548
5074
  status: 'written',
4549
- savedPath: spec,
4550
- savedPaths,
5075
+ savedPath: spec || record.savedPath || mergedSaved[0] || '',
5076
+ savedPaths: mergedSaved,
4551
5077
  changes: result.changes,
4552
5078
  });
5079
+ if (record.automationCaseId) {
5080
+ const link = readAutomationLinks(root).items.find(
5081
+ (item) => item.automationCaseId === record.automationCaseId,
5082
+ );
5083
+ if (link) {
5084
+ upsertAutomationLinks(root, [
5085
+ {
5086
+ ...link,
5087
+ scriptPath: spec || link.iterationFile || '',
5088
+ status: link.status === 'stale' ? 'stale' : 'connected',
5089
+ },
5090
+ ]);
5091
+ }
5092
+ }
4553
5093
  }
4554
5094
  return sendJson(res, result.ok ? 200 : 409, {
4555
5095
  ...result,
4556
- savedPaths: result.ok ? result.paths : undefined,
5096
+ savedPaths: result.ok ? record.savedPaths : undefined,
5097
+ suggestedPath: suggestedPath({ project, session: record }),
5098
+ });
5099
+ }
5100
+
5101
+ if (method === 'POST' && tail === '/agent/write/revert') {
5102
+ const body = JSON.parse((await readBodyLimited(req)) || '{}');
5103
+ const sessionId = text(body.sessionId, 64);
5104
+ let record = readGeneratedSession(agentBaseDir, sessionId);
5105
+ if (!record) return sendJson(res, 404, { ok: false, error: '生成会话不存在' });
5106
+ const project = agentProject(record.projectId);
5107
+ if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
5108
+ const paths = Array.isArray(body.paths)
5109
+ ? body.paths.map((item) => text(item, 500)).filter(Boolean)
5110
+ : [];
5111
+ const result = revertGeneratedFiles({ project, session: record, paths });
5112
+ if (result.ok) {
5113
+ record = saveGeneratedSession(agentBaseDir, {
5114
+ id: sessionId,
5115
+ status: result.status,
5116
+ savedPath: result.savedPath || '',
5117
+ savedPaths: result.savedPaths,
5118
+ changes: result.changes,
5119
+ });
5120
+ }
5121
+ return sendJson(res, result.ok ? 200 : 409, {
5122
+ ...result,
5123
+ session: record,
4557
5124
  suggestedPath: suggestedPath({ project, session: record }),
4558
5125
  });
4559
5126
  }
@@ -4676,6 +5243,31 @@ export function lhUiautoPlugin() {
4676
5243
  return sendJson(res, 200, result);
4677
5244
  }
4678
5245
 
5246
+ if (method === 'POST' && tail === '/agent/draft/write') {
5247
+ const body = JSON.parse((await readBodyLimited(req)) || '{}');
5248
+ const sessionId = text(body.sessionId, 64);
5249
+ const record = readGeneratedSession(agentBaseDir, sessionId);
5250
+ if (!record) return sendJson(res, 404, { ok: false, error: '生成会话不存在' });
5251
+ const project = agentProject(record.projectId);
5252
+ if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
5253
+ const draftFiles = Array.isArray(body.files)
5254
+ ? body.files
5255
+ .map((item) => ({
5256
+ path: text(item?.path, 400),
5257
+ content: typeof item?.content === 'string' ? item.content : '',
5258
+ role: text(item?.role, 32),
5259
+ }))
5260
+ .filter((item) => item.path)
5261
+ : [];
5262
+ const result = writeSessionDraftFiles({
5263
+ project,
5264
+ session: record,
5265
+ draftFiles,
5266
+ });
5267
+ if (result.error) return sendJson(res, 400, { ok: false, error: result.error });
5268
+ return sendJson(res, 200, { ok: true, ...result });
5269
+ }
5270
+
4679
5271
  if (method === 'POST' && tail === '/agent/draft/clean') {
4680
5272
  const body = JSON.parse((await readBodyLimited(req)) || '{}');
4681
5273
  const sessionId = text(body.sessionId, 64);
@@ -4693,6 +5285,8 @@ export function lhUiautoPlugin() {
4693
5285
 
4694
5286
  if (method === 'GET' && tail === '/agent/sessions') {
4695
5287
  const projectId = text(parsed.searchParams.get('projectId'), 64);
5288
+ // 列出来之前先清过期的,避免前端捞到一周前的盲盒草稿
5289
+ cleanupStaleSessions(agentBaseDir);
4696
5290
  return sendJson(res, 200, {
4697
5291
  ok: true,
4698
5292
  sessions: listGeneratedSessions(agentBaseDir, projectId),
@@ -4721,18 +5315,17 @@ export function lhUiautoPlugin() {
4721
5315
  if (method === 'DELETE' && tail === '/agent/session') {
4722
5316
  const id = text(parsed.searchParams.get('id'), 64);
4723
5317
  if (!id) return sendJson(res, 400, { ok: false, error: '缺少 id' });
5318
+ const dir = sessionsDir(agentBaseDir);
5319
+ const file = path.join(dir, `${id}.json`);
5320
+ if (!isPathInside(dir, file) || !isPathInside(dir, path.join(dir, id))) {
5321
+ return sendJson(res, 400, { ok: false, error: '路径不合法' });
5322
+ }
4724
5323
  stopExplorer(id);
4725
5324
  stopDebugSession(id);
4726
5325
  const record = readGeneratedSession(agentBaseDir, id);
4727
5326
  const project = record ? agentProject(record.projectId) : null;
4728
5327
  if (project) cleanupDraft(project.dir, id);
4729
- const dir = sessionsDir(agentBaseDir);
4730
- const file = path.join(dir, `${id}.json`);
4731
- if (!isPathInside(dir, file)) {
4732
- return sendJson(res, 400, { ok: false, error: '路径不合法' });
4733
- }
4734
- fs.rmSync(file, { force: true });
4735
- fs.rmSync(path.join(dir, id), { recursive: true, force: true });
5328
+ deleteGeneratedSession(agentBaseDir, id);
4736
5329
  return sendJson(res, 200, { ok: true });
4737
5330
  }
4738
5331
 
@@ -4745,3 +5338,11 @@ export function lhUiautoPlugin() {
4745
5338
  },
4746
5339
  };
4747
5340
  }
5341
+
5342
+ // In-process bridge: preserve the originating space while an execution plan runs.
5343
+ export { startRun as startAutomationProjectRun, stopRun as stopAutomationProjectRun };
5344
+ export function readAutomationProjectRun(root, id) {
5345
+ const run = findRun(readStore(root).store, id);
5346
+ if (!run) throw new Error('自动化执行记录不存在');
5347
+ return runView(run);
5348
+ }