lantern-harness 0.1.45 → 0.2.2

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 (244) hide show
  1. package/CHANGELOG.md +215 -0
  2. package/README.md +25 -8
  3. package/builtin/session/lh-fs.mjs +93 -4
  4. package/builtin/session/lh-nav-groups.mjs +3 -0
  5. package/builtin/session/mcp-client.mjs +7 -3
  6. package/builtin/session/session-runs.mjs +5 -1
  7. package/builtin/session/skill-validation.mjs +72 -0
  8. package/builtin/session/space-skills.mjs +751 -0
  9. package/cli/data-root.mjs +21 -4
  10. package/cli/lantern.mjs +26 -1
  11. package/cli/mcp-server.mjs +2779 -0
  12. package/cli/server.mjs +8 -2
  13. package/config/app.defaults.json +4 -2
  14. package/dist/500.html +9 -6
  15. package/dist/_astro/Base.Du_-4L-4.css +1 -0
  16. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.XUV2H6ea.js +2 -0
  17. package/dist/_astro/BusinessMapBoard.mRxl2G3D.js +5 -0
  18. package/dist/_astro/CaseExecBoard.Cqkxuf5c.js +1 -0
  19. package/dist/_astro/CaseExecutionBoard.CjX4CoKd.js +5 -0
  20. package/dist/_astro/CaseGenerateApp.acgnxl79.js +10 -0
  21. package/dist/_astro/CasesLibrary.zmzOQwdn.js +21 -0
  22. package/dist/_astro/ChatApp.Ben9LFra.js +1 -0
  23. package/dist/_astro/ChatApp.DBi6q7Qv.js +262 -0
  24. package/dist/_astro/{ConfirmDialog.DrrPf1MB.js → ConfirmDialog.DQFd6g2r.js} +1 -1
  25. package/dist/_astro/DashboardBoard.CAJVE2G4.js +5 -0
  26. package/dist/_astro/{DatePicker.Bkl71M49.js → DatePicker.BRO_CjVQ.js} +1 -1
  27. package/dist/_astro/DefectSubmitEntry.BzKXJ-zq.js +2 -0
  28. package/dist/_astro/DocsFileBrowser.apKMbGVf.js +1 -0
  29. package/dist/_astro/{DocsPager.Duf4I68E.js → DocsPager.DMN9-Tjg.js} +1 -1
  30. package/dist/_astro/{DrawerField.BH3p4Q4D.js → DrawerField.CLdvmHc6.js} +1 -1
  31. package/dist/_astro/KnowledgeLibrary.BcoMQeUd.js +1 -0
  32. package/dist/_astro/LifeKrTasksBoard.DJU0-QI-.js +1 -0
  33. package/dist/_astro/LifeKrTodosBoard.GK7KRAO3.js +1 -0
  34. package/dist/_astro/LifeObjectivesBoard.DuKa6Q3k.js +1 -0
  35. package/dist/_astro/LifePlanTypeSelect.Cm2lUmnH.js +1 -0
  36. package/dist/_astro/{LifeReviewsBoard.BPXeVpg1.js → LifeReviewsBoard.BWOOVMtz.js} +3 -3
  37. package/dist/_astro/{LifeShared.tnT7aQON.js → LifeShared.bY2l01Ha.js} +2 -2
  38. package/dist/_astro/LifeStagesBoard.CIzxPOJB.js +1 -0
  39. package/dist/_astro/LifeYearCycleSelect.BlsyPmmI.js +1 -0
  40. package/dist/_astro/LifeYearPlansBoard.DaA9O08j.js +1 -0
  41. package/dist/_astro/MultiSelectDropdown.D-rbpivp.js +1 -0
  42. package/dist/_astro/{NamePromptDialog.Csfnh5eM.js → NamePromptDialog.KPCeXmri.js} +1 -1
  43. package/dist/_astro/NavLibraries.DVR5Ua-S.js +1 -0
  44. package/dist/_astro/PluginsPage.B063QIlQ.js +18 -0
  45. package/dist/_astro/PmBugsBoard.Cu-v0Gfd.js +1 -0
  46. package/dist/_astro/PmIterationsBoard.CgRzkP-j.js +1 -0
  47. package/dist/_astro/{PmProjectDetail.DneFVBpy.js → PmProjectDetail.DVCEh0Lm.js} +1 -1
  48. package/dist/_astro/PmProjectsBoard.z-bQa98r.js +1 -0
  49. package/dist/_astro/PmRequirementsBoard.B0W6bsW2.js +1 -0
  50. package/dist/_astro/PmRequirementsBoard.CyfBI0u_.js +1 -0
  51. package/dist/_astro/PmShared.BQVzwsiz.js +1 -0
  52. package/dist/_astro/ReportsPage.najSzJeT.js +1 -0
  53. package/dist/_astro/ReqAnalysisBoard.BQb8dHFD.js +39 -0
  54. package/dist/_astro/RequirementBreakdownLibrary.Cn6OV6xt.js +2 -0
  55. package/dist/_astro/RequirementsLibrary.CqKNFVsP.js +1 -0
  56. package/dist/_astro/SearchableSelect.DXclLMJI.js +1 -0
  57. package/dist/_astro/SelectDropdown.D7IeyHDI.js +1 -0
  58. package/dist/_astro/SettingsDialog.db3BpFw0.js +1 -0
  59. package/dist/_astro/SlideOverDrawer.BMg2tce6.js +1 -0
  60. package/dist/_astro/SpaceSwitcher.DSUVAPOi.js +7 -0
  61. package/dist/_astro/{TableFieldConfig.C7O-mL-p.js → TableFieldConfig.72AL-8p-.js} +1 -1
  62. package/dist/_astro/{TagSelect.UUXgkMqJ.js → TagSelect.B_r2p0fp.js} +1 -1
  63. package/dist/_astro/TasksBoard.CCDhCSR7.js +1 -0
  64. package/dist/_astro/TemplatesLibrary.peYzrHZ2.js +1 -0
  65. package/dist/_astro/TestReportsLibrary.fWiEyCRx.js +1 -0
  66. package/dist/_astro/TestStatsBoard.BSUBsWSu.js +1 -0
  67. package/dist/_astro/Toast.BydY-X7T.js +1 -0
  68. package/dist/_astro/TodosBoard.By5YdlUe.js +1 -0
  69. package/dist/_astro/UiAutoBoard.BGdlp5Sr.js +3 -0
  70. package/dist/_astro/UiAutoEnvPanel.BUASgPLB.js +10 -0
  71. package/dist/_astro/UiAutoGenerationDialog.D1PyCgrD.js +12 -0
  72. package/dist/_astro/UiAutoProjectsPage.B6A9NlVK.js +3 -0
  73. package/dist/_astro/app-config.Dvfzl5_N.js +1 -0
  74. package/dist/_astro/app-version.CNpnKIb9.js +1 -0
  75. package/dist/_astro/{bash-tools.D9HCzC_7.js → bash-tools.CS2w8LOb.js} +1 -1
  76. package/dist/_astro/business-map.BiJ85oxm.js +1 -0
  77. package/dist/_astro/business-map.DKwdW1VL.css +1 -0
  78. package/dist/_astro/case-gen-run.Cvvdv_kv.js +26 -0
  79. package/dist/_astro/case-prompt.CZ3vWUju.js +2 -0
  80. package/dist/_astro/{case-review.TdDs1WFM.js → case-review.DFWZkoR9.js} +1 -1
  81. package/dist/_astro/{case-template.Cd2xNbgy.js → case-template.Clb7HrDB.js} +1 -1
  82. package/dist/_astro/defect-submit.Dc49lFjm.css +1 -0
  83. package/dist/_astro/defect-workbench.CjTb4FDv.js +6 -0
  84. package/dist/_astro/dialog.XgRGNF_Q.js +1 -0
  85. package/dist/_astro/doc-roots.C-20VD0x.js +1 -0
  86. package/dist/_astro/{hydrate-cache.B15Nrpq0.js → hydrate-cache.O4CIma9y.js} +1 -1
  87. package/dist/_astro/i18n.Cp4so7KR.js +7 -0
  88. package/dist/_astro/{llm.DN5S1KBK.js → llm.BCYNgppW.js} +1 -1
  89. package/dist/_astro/mcp-tools.Kf-lupGn.js +7 -0
  90. package/dist/_astro/{open-docs-in-session.CRiZT022.js → open-docs-in-session.BpcAcBSI.js} +1 -1
  91. package/dist/_astro/plugins.Db9xoFZb.js +1 -0
  92. package/dist/_astro/project-docs.bB9lQ1Ki.js +1 -0
  93. package/dist/_astro/prompts-meta.VAjE4OET.js +2 -0
  94. package/dist/_astro/report-prompt.CwHuOcRN.js +1 -0
  95. package/dist/_astro/req-analysis.C_gARMrB.js +31 -0
  96. package/dist/_astro/requirement-breakdown-library.l0rPd7b3.js +1 -0
  97. package/dist/_astro/{settings.38J2uD5M.js → settings.D02wZj3w.js} +2 -2
  98. package/dist/_astro/space-skills.CPucW8zt.js +1 -0
  99. package/dist/_astro/{spaces-client.DV04tRyD.js → spaces-client.BAtG6PkW.js} +1 -1
  100. package/dist/_astro/story-review.DTN91Vl9.js +7 -0
  101. package/dist/_astro/test-points.C7ZgggQT.js +8 -0
  102. package/dist/_astro/test-reports.0gr6-c_0.js +19 -0
  103. package/dist/_astro/ui-auto-prompt.BmO3ja2m.js +8 -0
  104. package/dist/_astro/{view-prefs.DhdLZjGh.js → view-prefs.COAKEQtZ.js} +1 -1
  105. package/dist/business-map/index.html +983 -0
  106. package/dist/case-exec/index.html +10 -7
  107. package/dist/{prompts → case-execution}/index.html +12 -9
  108. package/dist/cases/generate/index.html +9 -6
  109. package/dist/cases/library/index.html +10 -7
  110. package/dist/dashboard/index.html +10 -7
  111. package/dist/defect-rules/index.html +690 -0
  112. package/dist/defect-submit/index.html +690 -0
  113. package/dist/defect-submit/templates/index.html +690 -0
  114. package/dist/docs/changelog/index.html +259 -52
  115. package/dist/docs/install/index.html +44 -12
  116. package/dist/docs/manual/index.html +212 -75
  117. package/dist/knowledge/index.html +10 -7
  118. package/dist/life/kr-tasks/index.html +10 -7
  119. package/dist/life/kr-todos/index.html +10 -7
  120. package/dist/life/objectives/index.html +10 -7
  121. package/dist/life/reviews/index.html +10 -7
  122. package/dist/life/stages/index.html +10 -7
  123. package/dist/life/year-plans/index.html +10 -7
  124. package/dist/plugins/index.html +10 -7
  125. package/dist/pm/bugs/index.html +10 -7
  126. package/dist/pm/iterations/index.html +10 -7
  127. package/dist/pm/projects/detail/index.html +10 -7
  128. package/dist/pm/projects/index.html +10 -7
  129. package/dist/pm/requirements/index.html +10 -7
  130. package/dist/reports/index.html +10 -7
  131. package/dist/requirement-analysis/index.html +10 -7
  132. package/dist/requirement-breakdowns/index.html +983 -0
  133. package/dist/requirements/index.html +10 -7
  134. package/dist/tasks/index.html +10 -7
  135. package/dist/templates/index.html +10 -7
  136. package/dist/test-automation/index.html +10 -7
  137. package/dist/test-automation/projects/index.html +10 -7
  138. package/dist/test-reports/index.html +10 -7
  139. package/dist/test-stats/index.html +10 -7
  140. package/dist/todos/index.html +10 -7
  141. package/dist/workbench/index.html +9 -6
  142. package/docs/Codex-MCP/351/233/206/346/210/220.md +296 -0
  143. package/docs//344/270/232/345/212/241/345/234/260/345/233/276/350/257/204/344/274/260.md +39 -0
  144. 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
  145. package/docs//344/274/232/350/257/235/346/217/222/344/273/266.md +22 -3
  146. package/docs//345/205/250/345/261/200/346/217/222/344/273/266.md +41 -1
  147. package/docs//345/256/211/350/243/205/346/211/213/345/206/214.md +63 -17
  148. 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
  149. package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +207 -69
  150. package/lh-plugins/business-map/assistant.mjs +958 -0
  151. package/lh-plugins/business-map/auth-paths.mjs +61 -0
  152. package/lh-plugins/business-map/jobs.mjs +749 -0
  153. package/lh-plugins/business-map/login.mjs +295 -0
  154. package/lh-plugins/business-map/sources.mjs +1014 -0
  155. package/lh-plugins/case-execution/files.mjs +777 -0
  156. package/lh-plugins/case-execution/service.mjs +959 -0
  157. package/lh-plugins/case-execution-prompt.mjs +33 -0
  158. package/lh-plugins/lh-business-map.mjs +2431 -0
  159. package/lh-plugins/lh-case-execution.mjs +304 -0
  160. package/lh-plugins/lh-config.mjs +13 -0
  161. package/lh-plugins/lh-defect-submit.mjs +989 -0
  162. package/lh-plugins/lh-project-docs.mjs +31 -140
  163. package/lh-plugins/lh-reports.mjs +29 -57
  164. package/lh-plugins/lh-req-analysis.mjs +32 -3
  165. package/lh-plugins/lh-req-breakdown-library.mjs +1084 -0
  166. package/lh-plugins/lh-uiauto.mjs +514 -22
  167. package/lh-plugins/plugin-prompts.mjs +19 -15
  168. package/lh-plugins/req-analysis-revision.mjs +24 -0
  169. package/lh-plugins/test-points-prompt.mjs +2 -3
  170. package/lh-plugins/uiauto-auth-setup.mjs +218 -0
  171. package/lh-plugins/uiauto-explorer/apps.mjs +13 -2
  172. package/lh-plugins/uiauto-explorer/runner.mjs +15 -2
  173. package/lh-plugins/uiauto-explorer/sessions.mjs +305 -17
  174. package/lh-plugins/uiauto-node.mjs +102 -11
  175. package/lh-plugins/uiauto-prompt.mjs +20 -15
  176. package/lh-plugins/uiauto-sso.mjs +407 -0
  177. package/package.json +5 -2
  178. package/skills/case-execution/SKILL.md +30 -0
  179. package/skills/lantern-defect-submit/SKILL.md +15 -0
  180. package/skills/lantern-workflow/SKILL.md +57 -0
  181. package/skills/office/SKILL.md +26 -0
  182. package/dist/_astro/Base.Bkt1lrgu.css +0 -1
  183. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.UKTVQqk7.js +0 -2
  184. package/dist/_astro/CaseExecBoard.DICluCbK.js +0 -1
  185. package/dist/_astro/CaseGenerateApp.Be3h5XPG.js +0 -10
  186. package/dist/_astro/CasesLibrary.Buys7Cy-.js +0 -21
  187. package/dist/_astro/ChatApp.D3BheKci.js +0 -227
  188. package/dist/_astro/DashboardBoard.Qvf8o4v1.js +0 -5
  189. package/dist/_astro/DocsFileBrowser.DwKBffbM.js +0 -1
  190. package/dist/_astro/KnowledgeLibrary.MDpMqeOd.js +0 -1
  191. package/dist/_astro/LifeKrTasksBoard.DsvW_S66.js +0 -1
  192. package/dist/_astro/LifeKrTodosBoard.D2KTqvg1.js +0 -1
  193. package/dist/_astro/LifeObjectivesBoard.B0cDK934.js +0 -1
  194. package/dist/_astro/LifePlanTypeSelect.BELDvMWU.js +0 -1
  195. package/dist/_astro/LifeStagesBoard.CZftLR9K.js +0 -1
  196. package/dist/_astro/LifeYearCycleSelect.Bw2eRbSm.js +0 -1
  197. package/dist/_astro/LifeYearPlansBoard.DB-RJFEl.js +0 -1
  198. package/dist/_astro/MultiSelectDropdown.CBC7aNOv.js +0 -1
  199. package/dist/_astro/NavLibraries.DdQYsZbe.js +0 -1
  200. package/dist/_astro/OverflowHint.CHZeFfUj.js +0 -1
  201. package/dist/_astro/PluginsPage.C1JnInH4.js +0 -17
  202. package/dist/_astro/PluginsPage.C3eEwy3K.js +0 -1
  203. package/dist/_astro/PmBugsBoard.CGpXUTPu.js +0 -1
  204. package/dist/_astro/PmIterationsBoard.BaKiFIam.js +0 -1
  205. package/dist/_astro/PmProjectsBoard.BxoMF9gK.js +0 -1
  206. package/dist/_astro/PmRequirementsBoard.-SI8VZXI.js +0 -1
  207. package/dist/_astro/PmRequirementsBoard.DsK6RF7Q.js +0 -1
  208. package/dist/_astro/PmShared.BK8kWRSV.js +0 -1
  209. package/dist/_astro/PromptMountDialog.mrTx3U5T.js +0 -1
  210. package/dist/_astro/PromptsLibrary.B_SUf47p.js +0 -1
  211. package/dist/_astro/ReportsPage.B9lGg1_s.js +0 -16
  212. package/dist/_astro/ReqAnalysisBoard.CIZKnCQH.js +0 -39
  213. package/dist/_astro/RequirementsLibrary.cJc-bnGQ.js +0 -1
  214. package/dist/_astro/SearchableSelect.SyLRS-Jj.js +0 -1
  215. package/dist/_astro/SelectDropdown.T3CKHaLt.js +0 -1
  216. package/dist/_astro/SettingsDialog.DYdtCvLc.js +0 -1
  217. package/dist/_astro/SpaceSwitcher.C47_S1g9.js +0 -7
  218. package/dist/_astro/TasksBoard.BUEg2BYk.js +0 -1
  219. package/dist/_astro/TemplatesLibrary.BLVIphXO.js +0 -1
  220. package/dist/_astro/TestReportsLibrary.DVq30Jae.js +0 -1
  221. package/dist/_astro/TestStatsBoard.-5BWQ6bI.js +0 -1
  222. package/dist/_astro/Toast.BO2NFckG.js +0 -1
  223. package/dist/_astro/TodosBoard.DI_lTp2e.js +0 -1
  224. package/dist/_astro/UiAutoBoard.ChFdgv7s.js +0 -2
  225. package/dist/_astro/UiAutoEnvPanel.B50q4kYb.js +0 -19
  226. package/dist/_astro/UiAutoGenerationDialog.CLkFAHrm.js +0 -1
  227. package/dist/_astro/UiAutoProjectsPage.DCsDeN5d.js +0 -3
  228. package/dist/_astro/app-config.DkyjuL-S.js +0 -1
  229. package/dist/_astro/app-version.Cy-5oZO2.js +0 -1
  230. package/dist/_astro/case-gen-run.BklG1H8k.js +0 -22
  231. package/dist/_astro/case-types.DlFkbZJN.js +0 -1
  232. package/dist/_astro/dialog.DZHZCe_T.js +0 -1
  233. package/dist/_astro/doc-roots.CO3IBiY6.js +0 -1
  234. package/dist/_astro/i18n.D_aOCHSN.js +0 -7
  235. package/dist/_astro/markdown-client.BS19nLL3.js +0 -62
  236. package/dist/_astro/plugins.BRvXWHLe.js +0 -1
  237. package/dist/_astro/project-docs.CCjtiFjB.js +0 -1
  238. package/dist/_astro/prompts-meta.BUGutlsk.js +0 -2
  239. package/dist/_astro/report-prompt.B9C4cv84.js +0 -1
  240. package/dist/_astro/req-analysis.B12_MGMQ.js +0 -31
  241. package/dist/_astro/story-review.D2W5tEOY.js +0 -14
  242. package/dist/_astro/test-reports.CuIjlEyK.js +0 -19
  243. package/dist/_astro/ui-auto-prompt.H9_yhau9.js +0 -9
  244. package/dist/_astro/ui-auto.DMv940x4.js +0 -1
@@ -89,6 +89,8 @@ import {
89
89
  scanEnvFiles,
90
90
  validateEnvEntries,
91
91
  } from './uiauto-env.mjs';
92
+ import { projectHasSsoConfig, runSsoLoginAndSave } from './uiauto-sso.mjs';
93
+ import { projectHasAuthSetup, runAuthSetupAndSave } from './uiauto-auth-setup.mjs';
92
94
  import {
93
95
  applySkeletonToStack,
94
96
  auditScaffold,
@@ -104,7 +106,9 @@ import {
104
106
  callExplorer,
105
107
  cleanupDraft,
106
108
  cleanupStaleDrafts,
109
+ cleanupStaleSessions,
107
110
  debugSession,
111
+ deleteGeneratedSession,
108
112
  detectBaseURL,
109
113
  detectEmitLayout,
110
114
  detectStorageState,
@@ -130,6 +134,8 @@ import {
130
134
  suggestedPath,
131
135
  verifySession,
132
136
  writeGeneratedFiles,
137
+ writeSessionDraftFiles,
138
+ revertGeneratedFiles,
133
139
  findPlaywrightConfig,
134
140
  mergeActivityLog,
135
141
  } from './uiauto-explorer/sessions.mjs';
@@ -288,6 +294,86 @@ export function shouldIgnoreTreeName(name) {
288
294
  return TREE_IGNORED_NAMES.has(String(name));
289
295
  }
290
296
 
297
+ /** 生成页文件树:允许看到 `.lantern-ai` 草稿,其余忽略集与骨架树相同 */
298
+ export function shouldIgnoreBrowseName(name) {
299
+ const n = String(name);
300
+ if (n === '.lantern-ai') return false;
301
+ return TREE_IGNORED_NAMES.has(n);
302
+ }
303
+
304
+ const MAX_BROWSE_FILES = 800;
305
+ const MAX_BROWSE_DEPTH = 8;
306
+ const MAX_FILE_READ_BYTES = 512 * 1024;
307
+
308
+ /**
309
+ * 项目目录浅树(生成 Tab 浏览用)。
310
+ * @returns {{ tree: Array<object>; truncated: boolean }}
311
+ */
312
+ export function browseProjectTree(rootDir) {
313
+ const root = path.resolve(rootDir);
314
+ let fileCount = 0;
315
+ let truncated = false;
316
+
317
+ function walk(abs, rel, depth) {
318
+ if (depth > MAX_BROWSE_DEPTH) {
319
+ truncated = true;
320
+ return [];
321
+ }
322
+ let names = [];
323
+ try {
324
+ names = fs.readdirSync(abs);
325
+ } catch {
326
+ return [];
327
+ }
328
+ names.sort((a, b) => a.localeCompare(b, 'en'));
329
+ const dirs = [];
330
+ const files = [];
331
+ for (const name of names) {
332
+ if (shouldIgnoreBrowseName(name)) continue;
333
+ if (
334
+ name.startsWith('.') &&
335
+ name !== '.lantern-ai' &&
336
+ name !== '.env' &&
337
+ !name.startsWith('.env.')
338
+ ) {
339
+ // 其它点文件(.gitignore 等)仍展示;点目录除 .lantern-ai 外跳过
340
+ try {
341
+ if (fs.statSync(path.join(abs, name)).isDirectory()) continue;
342
+ } catch {
343
+ continue;
344
+ }
345
+ }
346
+ const childAbs = path.join(abs, name);
347
+ const childRel = rel ? `${rel}/${name}` : name;
348
+ let st;
349
+ try {
350
+ st = fs.statSync(childAbs);
351
+ } catch {
352
+ continue;
353
+ }
354
+ if (st.isDirectory()) {
355
+ dirs.push({
356
+ path: childRel,
357
+ name,
358
+ dir: true,
359
+ children: walk(childAbs, childRel, depth + 1),
360
+ });
361
+ } else if (st.isFile()) {
362
+ fileCount += 1;
363
+ if (fileCount > MAX_BROWSE_FILES) {
364
+ truncated = true;
365
+ break;
366
+ }
367
+ files.push({ path: childRel, name, dir: false, bytes: st.size });
368
+ }
369
+ }
370
+ // 同级:文件夹在上、文件在下(各自保持名字序)
371
+ return [...dirs, ...files];
372
+ }
373
+
374
+ return { tree: walk(root, '', 0), truncated };
375
+ }
376
+
291
377
  /** 项目内相对路径(POSIX),用于前端展示 */
292
378
  function toPosixRel(base, abs) {
293
379
  return path.relative(base, abs).split(path.sep).join('/');
@@ -460,6 +546,21 @@ export function uiautoStorePaths(root) {
460
546
  /** 本机缓存目录(不进空间内容池):`<空间>/.lantern/local/uiauto` */
461
547
  export const UIAUTO_CACHE_DIR_NAME = 'uiauto';
462
548
 
549
+ /** 过期生成会话清扫限流:任意 agent 请求最多每小时扫一次磁盘 */
550
+ const SESSION_CLEANUP_INTERVAL_MS = 60 * 60 * 1000;
551
+ let lastSessionCleanupAt = 0;
552
+
553
+ function maybeCleanupStaleSessions(baseDir) {
554
+ const now = Date.now();
555
+ if (now - lastSessionCleanupAt < SESSION_CLEANUP_INTERVAL_MS) return;
556
+ lastSessionCleanupAt = now;
557
+ try {
558
+ cleanupStaleSessions(baseDir);
559
+ } catch {
560
+ // 清扫失败不挡主流程
561
+ }
562
+ }
563
+
463
564
  /**
464
565
  * 应用图标、生成会话这类只对本机有意义、体积还不小的数据放本机缓存目录,
465
566
  * 不混在 `自动化测试/` 的项目目录里。旧版本把这些放在内容目录,首次访问时搬过来。
@@ -758,6 +859,102 @@ export function setupPlanFor(input = {}, deps = {}) {
758
859
  };
759
860
  }
760
861
 
862
+ /**
863
+ * 挂载项目常已在终端装过依赖:平台 setup 记录仍是 idle,界面会一直显示「待安装」。
864
+ * 按磁盘探测:node_modules 里有 Playwright,以及本机 / 项目内 chromium 缓存。
865
+ */
866
+ export function detectPlaywrightInstall(dir) {
867
+ const root = String(dir || '');
868
+ const empty = { deps: false, browser: false };
869
+ if (!root || !fs.existsSync(root)) return empty;
870
+ const nm = path.join(root, 'node_modules');
871
+ if (!fs.existsSync(nm)) return empty;
872
+ const deps =
873
+ fs.existsSync(path.join(nm, '@playwright', 'test', 'package.json')) ||
874
+ fs.existsSync(path.join(nm, 'playwright', 'package.json')) ||
875
+ fs.existsSync(path.join(nm, 'playwright-core', 'package.json'));
876
+ if (!deps) return empty;
877
+
878
+ const hasChromiumDir = (folder) => {
879
+ try {
880
+ if (!folder || !fs.existsSync(folder)) return false;
881
+ return fs.readdirSync(folder).some((name) => /^chromium/i.test(String(name)));
882
+ } catch {
883
+ return false;
884
+ }
885
+ };
886
+
887
+ let browser = hasChromiumDir(path.join(nm, 'playwright-core', '.local-browsers'));
888
+ if (!browser) {
889
+ const home = process.env.HOME || process.env.USERPROFILE || '';
890
+ const caches = [
891
+ process.env.PLAYWRIGHT_BROWSERS_PATH,
892
+ home ? path.join(home, 'Library', 'Caches', 'ms-playwright') : '',
893
+ home ? path.join(home, '.cache', 'ms-playwright') : '',
894
+ ].filter(Boolean);
895
+ browser = caches.some((folder) => hasChromiumDir(folder));
896
+ }
897
+ // 依赖齐了、项目已能跑时,缓存路径偶发探测不到也不该卡在「待安装」
898
+ if (!browser && deps) browser = true;
899
+ return { deps, browser };
900
+ }
901
+
902
+ /**
903
+ * idle / 失败态下用磁盘探测回填步骤状态,只影响展示,不写回 store。
904
+ */
905
+ export function enrichSetupWithDisk(setup, project) {
906
+ const base = normalizeSetup(setup);
907
+ if (!project?.dir || project.framework !== 'playwright') return base;
908
+ if (base.status === 'running') return base;
909
+ // 平台装过且成功:以记录为准
910
+ if (base.status === 'done' && base.steps.some((step) => step.status === 'done')) return base;
911
+
912
+ const probe = detectPlaywrightInstall(project.dir);
913
+ if (!probe.deps) return base;
914
+
915
+ const plan = setupPlanFor({
916
+ framework: project.framework,
917
+ dir: project.dir,
918
+ packageManager: '',
919
+ });
920
+ const sourceSteps = base.steps.length
921
+ ? base.steps
922
+ : plan.steps.map((step) => ({
923
+ id: step.id,
924
+ label: step.label,
925
+ command: step.command,
926
+ status: 'pending',
927
+ startedAt: '',
928
+ finishedAt: '',
929
+ exitCode: null,
930
+ }));
931
+
932
+ const steps = sourceSteps.map((step) => {
933
+ const ready =
934
+ step.id === 'deps'
935
+ ? probe.deps
936
+ : step.id === 'browser'
937
+ ? probe.browser
938
+ : step.status === 'done';
939
+ if (!ready) return step;
940
+ return {
941
+ ...step,
942
+ status: 'done',
943
+ exitCode: 0,
944
+ finishedAt: step.finishedAt || new Date().toISOString(),
945
+ };
946
+ });
947
+ const allDone = steps.length > 0 && steps.every((step) => step.status === 'done');
948
+ return {
949
+ ...base,
950
+ status: allDone ? 'done' : base.status === 'idle' ? 'idle' : base.status,
951
+ steps,
952
+ error: allDone ? '' : base.error,
953
+ // 展示用:告诉前端这是目录探测,不是平台刚装完
954
+ detectedFromDisk: true,
955
+ };
956
+ }
957
+
761
958
  /**
762
959
  * 技术栈 → 空间里的骨架(缺文件时按内置版本补种子)。
763
960
  * 新建项目只看骨架文件,跟「提示词管理」里的提示词无关:
@@ -1090,6 +1287,10 @@ function normalizeProject(raw) {
1090
1287
  // 该项目的登录态文件(相对项目根):按项目记,换项目不会串味;
1091
1288
  // 留空时自动探测项目里的 auth*.json / .auth/ 等
1092
1289
  storageState: text(raw.storageState, 300),
1290
+ // 登录墙偏好:ask_each_time(默认)/ ui_orchestrate / sso
1291
+ loginStrategy: ['ask_each_time', 'ui_orchestrate', 'sso'].includes(raw.loginStrategy)
1292
+ ? raw.loginStrategy
1293
+ : 'ask_each_time',
1093
1294
  // 该项目用哪份提示词(提示词管理里的文件名):不同框架可以挂不同提示词
1094
1295
  promptFile: text(raw.promptFile, 200),
1095
1296
  // 默认环境名(.env.<ENV>):运行面板下拉的初始值,空串表示 `.env`(各环境共用)
@@ -1482,14 +1683,14 @@ function decorateProject(project, root) {
1482
1683
  const settingUp = SETUPS.get(project.id);
1483
1684
  const customTasks = normalizeCustomTasks(project.customTasks);
1484
1685
  const probe = health.exists ? buildProbe(project.dir) : null;
1485
- const setup = normalizeSetup(project.setup);
1686
+ let setup = enrichSetupWithDisk(project.setup, project);
1486
1687
  const plan = setupPlanFor({
1487
1688
  framework: project.framework,
1488
1689
  dir: project.dir,
1489
1690
  packageManager: probe?.packageManager ?? '',
1490
1691
  });
1491
1692
  // 装到一半进程还没起来 / 进程没了但记录还是 running:一律按「正在装」展示
1492
- if (settingUp) setup.status = 'running';
1693
+ if (settingUp) setup = { ...setup, status: 'running' };
1493
1694
  // 自动发现 → 套上用户在运行配置里改过的名称 / 命令。
1494
1695
  // 被忽略的命令只从「运行任务」下拉里消失,仍然随项目返回(`ignoredTasks`),
1495
1696
  // 运行配置里排在列表最后,点一下就能恢复。
@@ -1521,6 +1722,9 @@ function decorateProject(project, root) {
1521
1722
  // 登录态同理:项目上记的优先,其次读项目里的登录态文件(换项目要重新识别)
1522
1723
  storageState: project.storageState || '',
1523
1724
  detectedStorageState: health.exists ? safeDetectStorageState(project.dir) : '',
1725
+ loginStrategy: project.loginStrategy || 'ask_each_time',
1726
+ ssoConfigured: health.exists ? projectHasSsoConfig(project.dir, project.envName || '') : false,
1727
+ authSetupDetected: health.exists ? projectHasAuthSetup(project.dir) : false,
1524
1728
  // 环境面板的入口条件:Playwright 且项目按 .env.<ENV> 约定做的
1525
1729
  envName: project.envName || '',
1526
1730
  hasEnvConvention:
@@ -2469,7 +2673,7 @@ function stopProjectSetup(projectId) {
2469
2673
 
2470
2674
  /** 安装日志读法:跑着的用内存缓冲,结束的从日志文件尾部取(与 /run 一致) */
2471
2675
  function readSetupLog(root, project, offset) {
2472
- const setup = normalizeSetup(project.setup);
2676
+ const setup = enrichSetupWithDisk(project.setup, project);
2473
2677
  const entry = SETUPS.get(project.id);
2474
2678
  if (!entry) {
2475
2679
  let log = '';
@@ -2493,6 +2697,10 @@ function readSetupLog(root, project, offset) {
2493
2697
  }
2494
2698
  }
2495
2699
  }
2700
+ // 从未用平台装过、但目录里已有依赖:补一句说明,避免空白日志看着像「没装」
2701
+ if (!log && setup.detectedFromDisk && setup.status === 'done') {
2702
+ log = '已从项目目录检测到依赖与浏览器内核,无需再走「一键安装」。需要时可点「重新安装」。\n';
2703
+ }
2496
2704
  return {
2497
2705
  setup: { ...setup, status: setup.status },
2498
2706
  stopping: false,
@@ -3537,6 +3745,13 @@ export function lhUiautoPlugin() {
3537
3745
  if (typeof body.storageState === 'string') {
3538
3746
  project.storageState = text(body.storageState, 300);
3539
3747
  }
3748
+ if (typeof body.loginStrategy === 'string') {
3749
+ project.loginStrategy = ['ask_each_time', 'ui_orchestrate', 'sso'].includes(
3750
+ body.loginStrategy,
3751
+ )
3752
+ ? body.loginStrategy
3753
+ : 'ask_each_time';
3754
+ }
3540
3755
  // 记住这个项目默认用哪套环境(运行面板下拉的初始值)
3541
3756
  if (typeof body.envName === 'string') {
3542
3757
  project.envName = sanitizeEnvName(body.envName);
@@ -3571,6 +3786,72 @@ export function lhUiautoPlugin() {
3571
3786
  return sendJson(res, 200, { ok: true });
3572
3787
  }
3573
3788
 
3789
+ /* ── 项目文件树 / 读写(生成 Tab;写默认仅 .lantern-ai 草稿) ── */
3790
+
3791
+ if (method === 'GET' && tail === '/project/files') {
3792
+ const projectId = text(parsed.searchParams.get('projectId'), 64);
3793
+ const project = findProject(readStore(root).store, projectId);
3794
+ if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
3795
+ if (!fs.existsSync(project.dir) || !fs.statSync(project.dir).isDirectory()) {
3796
+ return sendJson(res, 400, { ok: false, error: '项目目录已不存在,先重新指定目录' });
3797
+ }
3798
+ const browsed = browseProjectTree(project.dir);
3799
+ return sendJson(res, 200, {
3800
+ ok: true,
3801
+ root: project.dir,
3802
+ tree: browsed.tree,
3803
+ truncated: browsed.truncated,
3804
+ });
3805
+ }
3806
+
3807
+ if (method === 'GET' && tail === '/project/file') {
3808
+ const projectId = text(parsed.searchParams.get('projectId'), 64);
3809
+ const rel = String(parsed.searchParams.get('path') || '').replace(/\\/g, '/');
3810
+ const project = findProject(readStore(root).store, projectId);
3811
+ if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
3812
+ const abs = resolveInside(project.dir, rel);
3813
+ if (!abs) return sendJson(res, 400, { ok: false, error: '路径非法' });
3814
+ if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
3815
+ return sendJson(res, 404, { ok: false, error: '文件不存在' });
3816
+ }
3817
+ const st = fs.statSync(abs);
3818
+ if (st.size > MAX_FILE_READ_BYTES) {
3819
+ return sendJson(res, 400, { ok: false, error: '文件过大,请用外部编辑器打开' });
3820
+ }
3821
+ const content = fs.readFileSync(abs, 'utf8');
3822
+ return sendJson(res, 200, {
3823
+ ok: true,
3824
+ path: toPosixRel(project.dir, abs),
3825
+ content,
3826
+ bytes: st.size,
3827
+ });
3828
+ }
3829
+
3830
+ if (method === 'PUT' && tail === '/project/file') {
3831
+ const body = JSON.parse((await readBodyLimited(req)) || '{}');
3832
+ const projectId = text(body.projectId, 64);
3833
+ const rel = String(body.path || '').replace(/\\/g, '/');
3834
+ const content = typeof body.content === 'string' ? body.content : '';
3835
+ const allow = body.allow === 'any' ? 'any' : 'draft';
3836
+ const project = findProject(readStore(root).store, projectId);
3837
+ if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
3838
+ const abs = resolveInside(project.dir, rel);
3839
+ if (!abs) return sendJson(res, 400, { ok: false, error: '路径非法' });
3840
+ const posix = toPosixRel(project.dir, abs);
3841
+ if (allow !== 'any' && posix.split('/')[0] !== '.lantern-ai') {
3842
+ return sendJson(res, 403, {
3843
+ ok: false,
3844
+ error: '正式源码请走「写入」确认;此处只能改 .lantern-ai 草稿',
3845
+ });
3846
+ }
3847
+ if (Buffer.byteLength(content, 'utf8') > MAX_FILE_READ_BYTES) {
3848
+ return sendJson(res, 400, { ok: false, error: '内容过大' });
3849
+ }
3850
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
3851
+ fs.writeFileSync(abs, content, 'utf8');
3852
+ return sendJson(res, 200, { ok: true, path: posix });
3853
+ }
3854
+
3574
3855
  /* ── 项目 Node 版本:读 .nvmrc / engines,列出本机已装版本 ── */
3575
3856
 
3576
3857
  if (method === 'GET' && tail === '/project/node') {
@@ -3952,6 +4233,66 @@ export function lhUiautoPlugin() {
3952
4233
  });
3953
4234
  }
3954
4235
 
4236
+ // 登录墙选 SSO:按 env 调接口登录,写入 .auth/admin.json
4237
+ if (method === 'POST' && tail === '/project/sso-login') {
4238
+ const body = JSON.parse((await readBodyLimited(req)) || '{}');
4239
+ const projectId = text(body.projectId, 64);
4240
+ const store = readStoreForWrite(root);
4241
+ const project = findProject(store, projectId);
4242
+ if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
4243
+ if (!fs.existsSync(project.dir)) {
4244
+ return sendJson(res, 400, { ok: false, error: '项目目录已不存在' });
4245
+ }
4246
+ const result = await runSsoLoginAndSave({
4247
+ dir: project.dir,
4248
+ envName: typeof body.envName === 'string' ? body.envName : project.envName || '',
4249
+ baseURL:
4250
+ text(body.baseURL, 500) || project.baseURL || safeDetectBaseURL(project.dir) || '',
4251
+ });
4252
+ if (!result.ok) {
4253
+ return sendJson(res, 400, { ok: false, error: result.error });
4254
+ }
4255
+ project.storageState = result.storageState;
4256
+ writeStore(root, store);
4257
+ return sendJson(res, 200, {
4258
+ ok: true,
4259
+ storageState: result.storageState,
4260
+ tokenSaved: result.tokenSaved,
4261
+ project: decorateProject(project, root),
4262
+ });
4263
+ }
4264
+
4265
+ // 登录墙自动链:跑项目 auth.setup / setup 工程,产出 storageState
4266
+ if (method === 'POST' && tail === '/project/auth-setup') {
4267
+ const body = JSON.parse((await readBodyLimited(req)) || '{}');
4268
+ const projectId = text(body.projectId, 64);
4269
+ const store = readStoreForWrite(root);
4270
+ const project = findProject(store, projectId);
4271
+ if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
4272
+ if (!fs.existsSync(project.dir)) {
4273
+ return sendJson(res, 400, { ok: false, error: '项目目录已不存在' });
4274
+ }
4275
+ const result = await runAuthSetupAndSave({
4276
+ dir: project.dir,
4277
+ envName: typeof body.envName === 'string' ? body.envName : project.envName || '',
4278
+ });
4279
+ if (!result.ok) {
4280
+ return sendJson(res, 400, {
4281
+ ok: false,
4282
+ error: result.error,
4283
+ output: result.output || '',
4284
+ });
4285
+ }
4286
+ project.storageState = result.storageState;
4287
+ writeStore(root, store);
4288
+ return sendJson(res, 200, {
4289
+ ok: true,
4290
+ storageState: result.storageState,
4291
+ command: result.command,
4292
+ project: decorateProject(project, root),
4293
+ });
4294
+ }
4295
+
3955
4296
  if (method === 'POST' && tail === '/project/env/clear-auth') {
3956
4297
  const body = JSON.parse((await readBodyLimited(req)) || '{}');
3957
4298
  const store = readStore(root).store;
@@ -4098,6 +4439,10 @@ export function lhUiautoPlugin() {
4098
4439
  /** 生成会话与应用图标属于本机数据,放 `.lantern/local/uiauto`,不落进项目目录 */
4099
4440
  const agentBaseDir = uiautoCachePaths(root).dir;
4100
4441
 
4442
+ // 过期生成会话(含截图)顺手清:不进工作台侧栏,留着只是盲盒缓存
4443
+ // 限流避免每个请求都扫磁盘;prepare / 列会话时仍会强制再跑一次
4444
+ maybeCleanupStaleSessions(agentBaseDir);
4445
+
4101
4446
  /** 应用图标缓存目录:抽一次存下来,下次直接读 */
4102
4447
  const appIconDir = path.join(agentBaseDir, 'app-icons');
4103
4448
 
@@ -4139,7 +4484,7 @@ export function lhUiautoPlugin() {
4139
4484
  return { record, project };
4140
4485
  };
4141
4486
 
4142
- if (method === 'GET' && tail.startsWith('/agent/shot/')) {
4487
+ if ((method === 'GET' || method === 'DELETE') && tail.startsWith('/agent/shot/')) {
4143
4488
  const rest = tail.slice('/agent/shot/'.length);
4144
4489
  const slash = rest.indexOf('/');
4145
4490
  const sessionId = slash === -1 ? '' : rest.slice(0, slash);
@@ -4152,6 +4497,10 @@ export function lhUiautoPlugin() {
4152
4497
  if (!isPathInside(dir, abs) || !fs.existsSync(abs)) {
4153
4498
  return sendJson(res, 404, { ok: false, error: '截图不存在' });
4154
4499
  }
4500
+ if (method === 'DELETE') {
4501
+ fs.unlinkSync(abs);
4502
+ return sendJson(res, 200, { ok: true });
4503
+ }
4155
4504
  res.statusCode = 200;
4156
4505
  res.setHeader('Content-Type', 'image/png');
4157
4506
  res.setHeader('Cache-Control', 'no-store');
@@ -4198,7 +4547,15 @@ export function lhUiautoPlugin() {
4198
4547
  headed: typeof body.headed === 'boolean' ? body.headed : existing.headed,
4199
4548
  plan: Array.isArray(body.plan) ? body.plan : undefined,
4200
4549
  ...(reset
4201
- ? { ir: null, lastVerify: null, savedPath: '', status: 'draft' }
4550
+ ? {
4551
+ ir: null,
4552
+ lastVerify: null,
4553
+ savedPath: '',
4554
+ status: 'draft',
4555
+ // 新一轮清空控制台 / 网络快照;试跑结果一并作废
4556
+ consoleLog: [],
4557
+ networkLog: [],
4558
+ }
4202
4559
  : {
4203
4560
  // 已写入 / 已试跑通过的会话不要被打回草稿
4204
4561
  status:
@@ -4231,6 +4588,7 @@ export function lhUiautoPlugin() {
4231
4588
  const created = createAgentSession(body);
4232
4589
  if (created.error) return sendJson(res, 404, { ok: false, error: created.error });
4233
4590
  cleanupStaleDrafts(created.project.dir);
4591
+ cleanupStaleSessions(agentBaseDir);
4234
4592
  return sendJson(res, 200, {
4235
4593
  ok: true,
4236
4594
  session: created.session,
@@ -4334,20 +4692,43 @@ export function lhUiautoPlugin() {
4334
4692
  if (method === 'POST' && (tail === '/agent/console' || tail === '/agent/network')) {
4335
4693
  const body = JSON.parse((await readBodyLimited(req)) || '{}');
4336
4694
  const sessionId = text(body.sessionId, 64);
4337
- // 控制台 / 网络是「读」操作:没有在跑的浏览器就直接回空表。
4338
- // 这里以前走 requireExplorer,导致前端一切到这个 Tab(含 HMR 重载后恢复)
4339
- // 就凭空拉起一个有头浏览器窗口(baseURL 不可达时停在 about:blank)。
4695
+ const record = readGeneratedSession(agentBaseDir, sessionId);
4696
+ // 控制台 / 网络是「读」:浏览器还在就取活数据并落盘;关掉后回本轮缓存。
4697
+ // 不走 requireExplorer,避免切 Tab / HMR 时凭空拉起浏览器。
4340
4698
  if (!hasExplorer(sessionId)) {
4341
4699
  return sendJson(res, 200, {
4342
4700
  ok: true,
4343
- messages: [],
4344
- requests: [],
4701
+ messages: Array.isArray(record?.consoleLog) ? record.consoleLog : [],
4702
+ requests: Array.isArray(record?.networkLog) ? record.networkLog : [],
4345
4703
  running: false,
4346
4704
  });
4347
4705
  }
4348
4706
  const cmd = tail === '/agent/console' ? 'console' : 'network';
4349
4707
  const result = await callExplorer(sessionId, cmd, {});
4350
- return sendJson(res, 200, { ok: true, ...result });
4708
+ const consoleLog = Array.isArray(result.messages)
4709
+ ? result.messages.slice(-80)
4710
+ : record?.consoleLog;
4711
+ const networkLog = Array.isArray(result.requests)
4712
+ ? result.requests.slice(-80)
4713
+ : record?.networkLog;
4714
+ // 活数据顺手写回会话:关浏览器后还能回看这一轮
4715
+ if (cmd === 'console' && Array.isArray(result.messages)) {
4716
+ saveGeneratedSession(agentBaseDir, {
4717
+ id: sessionId,
4718
+ consoleLog: result.messages.slice(-80),
4719
+ });
4720
+ } else if (cmd === 'network' && Array.isArray(result.requests)) {
4721
+ saveGeneratedSession(agentBaseDir, {
4722
+ id: sessionId,
4723
+ networkLog: result.requests.slice(-80),
4724
+ });
4725
+ }
4726
+ return sendJson(res, 200, {
4727
+ ok: true,
4728
+ ...result,
4729
+ messages: consoleLog ?? result.messages,
4730
+ requests: networkLog ?? result.requests,
4731
+ });
4351
4732
  }
4352
4733
 
4353
4734
  if (method === 'POST' && tail === '/agent/wait') {
@@ -4385,6 +4766,26 @@ export function lhUiautoPlugin() {
4385
4766
  if (method === 'POST' && tail === '/agent/close') {
4386
4767
  const body = JSON.parse((await readBodyLimited(req)) || '{}');
4387
4768
  const sessionId = text(body.sessionId, 64);
4769
+ // 关窗前尽量快照;超时要短,避免探索结束后浏览器还挂几十秒
4770
+ if (hasExplorer(sessionId)) {
4771
+ try {
4772
+ const [consoleResult, networkResult] = await Promise.all([
4773
+ callExplorer(sessionId, 'console', {}, 2500),
4774
+ callExplorer(sessionId, 'network', {}, 2500),
4775
+ ]);
4776
+ saveGeneratedSession(agentBaseDir, {
4777
+ id: sessionId,
4778
+ consoleLog: Array.isArray(consoleResult.messages)
4779
+ ? consoleResult.messages.slice(-80)
4780
+ : [],
4781
+ networkLog: Array.isArray(networkResult.requests)
4782
+ ? networkResult.requests.slice(-80)
4783
+ : [],
4784
+ });
4785
+ } catch {
4786
+ // 快照失败仍继续关浏览器
4787
+ }
4788
+ }
4388
4789
  const stopped = stopExplorer(sessionId);
4389
4790
  const record = readGeneratedSession(agentBaseDir, sessionId);
4390
4791
  if (record && record.status === 'exploring') {
@@ -4427,7 +4828,31 @@ export function lhUiautoPlugin() {
4427
4828
  ? body.activity
4428
4829
  : mergeActivityLog(existing.activity, body.activity)
4429
4830
  : undefined,
4831
+ // 规划说明(测试思路等)跟活动日志分开存:探索追加过程时不要冲掉
4832
+ narrative:
4833
+ typeof body.narrative === 'string'
4834
+ ? String(body.narrative).slice(0, 80000)
4835
+ : undefined,
4430
4836
  status: text(body.status, 40) || existing.status,
4837
+ chatSessionId:
4838
+ typeof body.chatSessionId === 'string'
4839
+ ? text(body.chatSessionId, 80) || existing.chatSessionId
4840
+ : undefined,
4841
+ // 代码页手改:null 清空;数组覆盖;不传保持原值
4842
+ editedFiles:
4843
+ body.editedFiles === null
4844
+ ? null
4845
+ : Array.isArray(body.editedFiles)
4846
+ ? body.editedFiles
4847
+ .slice(0, 40)
4848
+ .map((item) => ({
4849
+ path: text(item?.path, 400),
4850
+ content: typeof item?.content === 'string' ? item.content : '',
4851
+ role: text(item?.role, 32),
4852
+ language: text(item?.language, 32),
4853
+ }))
4854
+ .filter((item) => item.path)
4855
+ : undefined,
4431
4856
  });
4432
4857
  const emitted = emitCode(saved.ir || {}, saved.target);
4433
4858
  return sendJson(res, 200, {
@@ -4484,10 +4909,20 @@ export function lhUiautoPlugin() {
4484
4909
  }
4485
4910
  const project = agentProject(record.projectId);
4486
4911
  if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
4912
+ const draftFiles = Array.isArray(body.files)
4913
+ ? body.files
4914
+ .map((item) => ({
4915
+ path: text(item?.path, 400),
4916
+ content: typeof item?.content === 'string' ? item.content : '',
4917
+ role: text(item?.role, 32),
4918
+ }))
4919
+ .filter((item) => item.path)
4920
+ : undefined;
4487
4921
  const result = await verifySession({
4488
4922
  project,
4489
4923
  session: record,
4490
4924
  timeoutMs: intOr(body.timeoutMs, 180000, 10000, 600000),
4925
+ draftFiles,
4491
4926
  });
4492
4927
  saveGeneratedSession(agentBaseDir, {
4493
4928
  id: sessionId,
@@ -4498,7 +4933,8 @@ export function lhUiautoPlugin() {
4498
4933
  passed: Boolean(result.passed),
4499
4934
  exitCode: result.exitCode ?? null,
4500
4935
  durationMs: result.durationMs ?? 0,
4501
- log: String(result.log ?? '').slice(-4000),
4936
+ log: String(result.log ?? '').slice(-24000),
4937
+ logPath: result.logPath || '',
4502
4938
  },
4503
4939
  });
4504
4940
  return sendJson(res, 200, {
@@ -4543,17 +4979,47 @@ export function lhUiautoPlugin() {
4543
4979
  const savedPaths = result.paths.slice();
4544
4980
  // 主用例(spec)优先,试跑 / 验收 / 打开草稿都从它出发
4545
4981
  const spec = files.find((item) => item.role === 'spec')?.path || savedPaths[0] || '';
4982
+ // 与历史 savedPaths 合并,避免分批写入时丢掉上一批
4983
+ const prevSaved = Array.isArray(record.savedPaths) ? record.savedPaths : [];
4984
+ const mergedSaved = [...new Set([...prevSaved, ...savedPaths].filter(Boolean))];
4546
4985
  record = saveGeneratedSession(agentBaseDir, {
4547
4986
  id: sessionId,
4548
4987
  status: 'written',
4549
- savedPath: spec,
4550
- savedPaths,
4988
+ savedPath: spec || record.savedPath || mergedSaved[0] || '',
4989
+ savedPaths: mergedSaved,
4551
4990
  changes: result.changes,
4552
4991
  });
4553
4992
  }
4554
4993
  return sendJson(res, result.ok ? 200 : 409, {
4555
4994
  ...result,
4556
- savedPaths: result.ok ? result.paths : undefined,
4995
+ savedPaths: result.ok ? record.savedPaths : undefined,
4996
+ suggestedPath: suggestedPath({ project, session: record }),
4997
+ });
4998
+ }
4999
+
5000
+ if (method === 'POST' && tail === '/agent/write/revert') {
5001
+ const body = JSON.parse((await readBodyLimited(req)) || '{}');
5002
+ const sessionId = text(body.sessionId, 64);
5003
+ let record = readGeneratedSession(agentBaseDir, sessionId);
5004
+ if (!record) return sendJson(res, 404, { ok: false, error: '生成会话不存在' });
5005
+ const project = agentProject(record.projectId);
5006
+ if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
5007
+ const paths = Array.isArray(body.paths)
5008
+ ? body.paths.map((item) => text(item, 500)).filter(Boolean)
5009
+ : [];
5010
+ const result = revertGeneratedFiles({ project, session: record, paths });
5011
+ if (result.ok) {
5012
+ record = saveGeneratedSession(agentBaseDir, {
5013
+ id: sessionId,
5014
+ status: result.status,
5015
+ savedPath: result.savedPath || '',
5016
+ savedPaths: result.savedPaths,
5017
+ changes: result.changes,
5018
+ });
5019
+ }
5020
+ return sendJson(res, result.ok ? 200 : 409, {
5021
+ ...result,
5022
+ session: record,
4557
5023
  suggestedPath: suggestedPath({ project, session: record }),
4558
5024
  });
4559
5025
  }
@@ -4676,6 +5142,31 @@ export function lhUiautoPlugin() {
4676
5142
  return sendJson(res, 200, result);
4677
5143
  }
4678
5144
 
5145
+ if (method === 'POST' && tail === '/agent/draft/write') {
5146
+ const body = JSON.parse((await readBodyLimited(req)) || '{}');
5147
+ const sessionId = text(body.sessionId, 64);
5148
+ const record = readGeneratedSession(agentBaseDir, sessionId);
5149
+ if (!record) return sendJson(res, 404, { ok: false, error: '生成会话不存在' });
5150
+ const project = agentProject(record.projectId);
5151
+ if (!project) return sendJson(res, 404, { ok: false, error: '项目不存在' });
5152
+ const draftFiles = Array.isArray(body.files)
5153
+ ? body.files
5154
+ .map((item) => ({
5155
+ path: text(item?.path, 400),
5156
+ content: typeof item?.content === 'string' ? item.content : '',
5157
+ role: text(item?.role, 32),
5158
+ }))
5159
+ .filter((item) => item.path)
5160
+ : [];
5161
+ const result = writeSessionDraftFiles({
5162
+ project,
5163
+ session: record,
5164
+ draftFiles,
5165
+ });
5166
+ if (result.error) return sendJson(res, 400, { ok: false, error: result.error });
5167
+ return sendJson(res, 200, { ok: true, ...result });
5168
+ }
5169
+
4679
5170
  if (method === 'POST' && tail === '/agent/draft/clean') {
4680
5171
  const body = JSON.parse((await readBodyLimited(req)) || '{}');
4681
5172
  const sessionId = text(body.sessionId, 64);
@@ -4693,6 +5184,8 @@ export function lhUiautoPlugin() {
4693
5184
 
4694
5185
  if (method === 'GET' && tail === '/agent/sessions') {
4695
5186
  const projectId = text(parsed.searchParams.get('projectId'), 64);
5187
+ // 列出来之前先清过期的,避免前端捞到一周前的盲盒草稿
5188
+ cleanupStaleSessions(agentBaseDir);
4696
5189
  return sendJson(res, 200, {
4697
5190
  ok: true,
4698
5191
  sessions: listGeneratedSessions(agentBaseDir, projectId),
@@ -4721,18 +5214,17 @@ export function lhUiautoPlugin() {
4721
5214
  if (method === 'DELETE' && tail === '/agent/session') {
4722
5215
  const id = text(parsed.searchParams.get('id'), 64);
4723
5216
  if (!id) return sendJson(res, 400, { ok: false, error: '缺少 id' });
5217
+ const dir = sessionsDir(agentBaseDir);
5218
+ const file = path.join(dir, `${id}.json`);
5219
+ if (!isPathInside(dir, file) || !isPathInside(dir, path.join(dir, id))) {
5220
+ return sendJson(res, 400, { ok: false, error: '路径不合法' });
5221
+ }
4724
5222
  stopExplorer(id);
4725
5223
  stopDebugSession(id);
4726
5224
  const record = readGeneratedSession(agentBaseDir, id);
4727
5225
  const project = record ? agentProject(record.projectId) : null;
4728
5226
  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 });
5227
+ deleteGeneratedSession(agentBaseDir, id);
4736
5228
  return sendJson(res, 200, { ok: true });
4737
5229
  }
4738
5230