lantern-harness 0.2.2 → 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 (178) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +7 -7
  3. package/builtin/case-backup-contract.mjs +27 -0
  4. package/builtin/case-workflow-contract.mjs +158 -0
  5. package/builtin/session/lh-nav-groups.mjs +33 -1
  6. package/builtin/session/space-layout.mjs +8 -1
  7. package/builtin/session/space-skills.mjs +8 -1
  8. package/cli/mcp-server.mjs +986 -32
  9. package/cli/server.mjs +2 -0
  10. package/dist/500.html +9 -4
  11. package/dist/_astro/Base.BQf1tZMl.css +1 -0
  12. package/dist/_astro/{Base.astro_astro_type_script_index_0_lang.XUV2H6ea.js → Base.astro_astro_type_script_index_0_lang.Dm3O_y-S.js} +1 -1
  13. package/dist/_astro/{BusinessMapBoard.mRxl2G3D.js → BusinessMapBoard.CYxHcku_.js} +1 -1
  14. package/dist/_astro/{CaseExecBoard.Cqkxuf5c.js → CaseExecBoard.CK9aGPmH.js} +1 -1
  15. package/dist/_astro/CaseExecutionBoard.C94pmIMQ.js +5 -0
  16. package/dist/_astro/CaseGenerateApp.D5xlk9At.js +10 -0
  17. package/dist/_astro/CasesLibrary.BHQC955x.js +21 -0
  18. package/dist/_astro/ChatApp.CIt15w_1.js +1 -0
  19. package/dist/_astro/ChatApp.d4a9R3YS.js +262 -0
  20. package/dist/_astro/{DashboardBoard.CAJVE2G4.js → DashboardBoard.qgc1s7pG.js} +1 -1
  21. package/dist/_astro/{DefectSubmitEntry.BzKXJ-zq.js → DefectSubmitEntry.JI85N1-i.js} +1 -1
  22. package/dist/_astro/{DocsFileBrowser.apKMbGVf.js → DocsFileBrowser.z5JZ74cy.js} +1 -1
  23. package/dist/_astro/{DocsPager.DMN9-Tjg.js → DocsPager.Dg765uHW.js} +1 -1
  24. package/dist/_astro/{KnowledgeLibrary.BcoMQeUd.js → KnowledgeLibrary.mkShtVun.js} +1 -1
  25. package/dist/_astro/{LifeKrTasksBoard.DJU0-QI-.js → LifeKrTasksBoard.DpAwQffE.js} +1 -1
  26. package/dist/_astro/{LifeKrTodosBoard.GK7KRAO3.js → LifeKrTodosBoard.BIjPiZ8H.js} +1 -1
  27. package/dist/_astro/{LifeObjectivesBoard.DuKa6Q3k.js → LifeObjectivesBoard.DYwLHPEG.js} +1 -1
  28. package/dist/_astro/{LifePlanTypeSelect.Cm2lUmnH.js → LifePlanTypeSelect.CYaziESp.js} +1 -1
  29. package/dist/_astro/{LifeReviewsBoard.BWOOVMtz.js → LifeReviewsBoard.DIxoWBDA.js} +1 -1
  30. package/dist/_astro/{LifeShared.bY2l01Ha.js → LifeShared.DuFQsMEx.js} +1 -1
  31. package/dist/_astro/{LifeStagesBoard.CIzxPOJB.js → LifeStagesBoard.DtOri9EW.js} +1 -1
  32. package/dist/_astro/{LifeYearCycleSelect.BlsyPmmI.js → LifeYearCycleSelect.ByJ9-PGg.js} +1 -1
  33. package/dist/_astro/{LifeYearPlansBoard.DaA9O08j.js → LifeYearPlansBoard.BQN07wcv.js} +1 -1
  34. package/dist/_astro/NavLibraries.BO4ezcUc.js +1 -0
  35. package/dist/_astro/{PluginsPage.B063QIlQ.js → PluginsPage.B1VeDtLx.js} +2 -2
  36. package/dist/_astro/{PmBugsBoard.Cu-v0Gfd.js → PmBugsBoard.Ddl3kqqt.js} +1 -1
  37. package/dist/_astro/{PmIterationsBoard.CgRzkP-j.js → PmIterationsBoard.BJN7disI.js} +1 -1
  38. package/dist/_astro/{PmProjectDetail.DVCEh0Lm.js → PmProjectDetail.D78gWhqk.js} +1 -1
  39. package/dist/_astro/{PmProjectsBoard.z-bQa98r.js → PmProjectsBoard.Bf8VB3t6.js} +1 -1
  40. package/dist/_astro/PmRequirementsBoard.CDyNHN2a.js +1 -0
  41. package/dist/_astro/{PmRequirementsBoard.CyfBI0u_.js → PmRequirementsBoard.DarfGIrL.js} +1 -1
  42. package/dist/_astro/{PmShared.BQVzwsiz.js → PmShared.TOjBbtV8.js} +1 -1
  43. package/dist/_astro/{ReportsPage.najSzJeT.js → ReportsPage.BXGduuY3.js} +1 -1
  44. package/dist/_astro/{ReqAnalysisBoard.BQb8dHFD.js → ReqAnalysisBoard.WLtIfBg8.js} +1 -1
  45. package/dist/_astro/{RequirementBreakdownLibrary.Cn6OV6xt.js → RequirementBreakdownLibrary.DMoeTeqX.js} +1 -1
  46. package/dist/_astro/{RequirementsLibrary.CqKNFVsP.js → RequirementsLibrary.Iv7zOqWe.js} +1 -1
  47. package/dist/_astro/{SettingsDialog.db3BpFw0.js → SettingsDialog.BvDU9EU6.js} +1 -1
  48. package/dist/_astro/SlideOverDrawer.CvyB-quk.js +1 -0
  49. package/dist/_astro/{SpaceSwitcher.DSUVAPOi.js → SpaceSwitcher.D9bBNQBZ.js} +1 -1
  50. package/dist/_astro/{TableFieldConfig.72AL-8p-.js → TableFieldConfig.DHj25OKN.js} +1 -1
  51. package/dist/_astro/{TasksBoard.CCDhCSR7.js → TasksBoard.CXmGdylV.js} +1 -1
  52. package/dist/_astro/TemplatesLibrary.DsL2q-wp.js +1 -0
  53. package/dist/_astro/{TestReportsLibrary.fWiEyCRx.js → TestReportsLibrary.BBC1TYgP.js} +1 -1
  54. package/dist/_astro/{TestStatsBoard.BSUBsWSu.js → TestStatsBoard.VXjP4hu6.js} +1 -1
  55. package/dist/_astro/{TodosBoard.By5YdlUe.js → TodosBoard.-yKgp06M.js} +1 -1
  56. package/dist/_astro/UiAutoBoard.BD5ZyLHj.js +3 -0
  57. package/dist/_astro/UiAutoEnvPanel.DrHUOlmH.js +10 -0
  58. package/dist/_astro/UiAutoGenerationDialog.gypq1zP9.js +12 -0
  59. package/dist/_astro/UiAutoProjectsPage.Dhzr09E9.js +3 -0
  60. package/dist/_astro/app-config.BSO5r82v.js +1 -0
  61. package/dist/_astro/app-version.CkDFkv4s.js +1 -0
  62. package/dist/_astro/{bash-tools.CS2w8LOb.js → bash-tools.C4DJiRJs.js} +1 -1
  63. package/dist/_astro/case-fields.C03NY3zC.js +148 -0
  64. package/dist/_astro/case-gen-run.C4p8uyU3.js +26 -0
  65. package/dist/_astro/case-prompt.ByLTgz4r.js +2 -0
  66. package/dist/_astro/{case-review.DFWZkoR9.js → case-review.BodP2jKm.js} +1 -1
  67. package/dist/_astro/{case-template.Clb7HrDB.js → case-template.CC2eXegU.js} +2 -2
  68. package/dist/_astro/case-types.BjF1BivA.js +1 -0
  69. package/dist/_astro/case-workflow-contract.BBQ9bbKL.js +1 -0
  70. package/dist/_astro/{defect-workbench.CjTb4FDv.js → defect-workbench.DBmohR-y.js} +1 -1
  71. package/dist/_astro/{hydrate-cache.O4CIma9y.js → hydrate-cache.CMMErx63.js} +1 -1
  72. package/dist/_astro/{i18n.Cp4so7KR.js → i18n.CEWjL5GX.js} +2 -2
  73. package/dist/_astro/{open-docs-in-session.BpcAcBSI.js → open-docs-in-session.BoyV6R2A.js} +1 -1
  74. package/dist/_astro/plugins.ChGmBEkF.js +1 -0
  75. package/dist/_astro/{project-docs.bB9lQ1Ki.js → project-docs.BRgNjXhG.js} +1 -1
  76. package/dist/_astro/{req-analysis.C_gARMrB.js → req-analysis.BLvcktvQ.js} +1 -1
  77. package/dist/_astro/{settings.D02wZj3w.js → settings.BojKNwUC.js} +2 -2
  78. package/dist/_astro/{spaces-client.BAtG6PkW.js → spaces-client.B28rzu8J.js} +1 -1
  79. package/dist/_astro/{story-review.DTN91Vl9.js → story-review.dEBWTeOW.js} +1 -1
  80. package/dist/_astro/{test-points.C7ZgggQT.js → test-points.BuNgdNcU.js} +1 -1
  81. package/dist/_astro/ui-auto.LUcREUMe.js +1 -0
  82. package/dist/_astro/{view-prefs.COAKEQtZ.js → view-prefs.CWc5cQ2q.js} +1 -1
  83. package/dist/business-map/index.html +10 -5
  84. package/dist/case-exec/index.html +10 -5
  85. package/dist/case-execution/index.html +10 -5
  86. package/dist/cases/api/index.html +988 -0
  87. package/dist/cases/automation/index.html +988 -0
  88. package/dist/cases/functional/index.html +988 -0
  89. package/dist/cases/generate/index.html +10 -5
  90. package/dist/cases/index.html +1 -1
  91. package/dist/cases/library/index.html +1 -983
  92. package/dist/cases/other/index.html +988 -0
  93. package/dist/cases/performance/index.html +988 -0
  94. package/dist/dashboard/index.html +10 -5
  95. package/dist/defect-rules/index.html +10 -5
  96. package/dist/defect-submit/index.html +10 -5
  97. package/dist/defect-submit/templates/index.html +10 -5
  98. package/dist/docs/changelog/index.html +88 -58
  99. package/dist/docs/install/index.html +12 -6
  100. package/dist/docs/manual/index.html +42 -31
  101. package/dist/knowledge/index.html +10 -5
  102. package/dist/life/kr-tasks/index.html +10 -5
  103. package/dist/life/kr-todos/index.html +10 -5
  104. package/dist/life/objectives/index.html +10 -5
  105. package/dist/life/reviews/index.html +10 -5
  106. package/dist/life/stages/index.html +10 -5
  107. package/dist/life/year-plans/index.html +10 -5
  108. package/dist/plugins/index.html +10 -5
  109. package/dist/pm/bugs/index.html +10 -5
  110. package/dist/pm/iterations/index.html +10 -5
  111. package/dist/pm/projects/detail/index.html +10 -5
  112. package/dist/pm/projects/index.html +10 -5
  113. package/dist/pm/requirements/index.html +10 -5
  114. package/dist/reports/index.html +10 -5
  115. package/dist/requirement-analysis/index.html +10 -5
  116. package/dist/requirement-breakdowns/index.html +10 -5
  117. package/dist/requirements/index.html +10 -5
  118. package/dist/tasks/index.html +10 -5
  119. package/dist/templates/index.html +10 -5
  120. package/dist/test-automation/index.html +10 -5
  121. package/dist/test-automation/projects/index.html +10 -5
  122. package/dist/test-reports/index.html +10 -5
  123. package/dist/test-stats/index.html +10 -5
  124. package/dist/todos/index.html +10 -5
  125. package/dist/workbench/index.html +10 -5
  126. package/docs/Codex-MCP/351/233/206/346/210/220.md +97 -53
  127. package/docs//344/274/232/350/257/235/346/217/222/344/273/266.md +7 -1
  128. package/docs//345/205/250/345/261/200/346/217/222/344/273/266.md +1 -1
  129. package/docs//345/256/211/350/243/205/346/211/213/345/206/214.md +4 -2
  130. package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +43 -36
  131. package/lh-plugins/case-automation/service.mjs +921 -0
  132. package/lh-plugins/case-automation/store.mjs +231 -0
  133. package/lh-plugins/case-automation/tables.mjs +115 -0
  134. package/lh-plugins/case-automation-prompt.mjs +57 -0
  135. package/lh-plugins/case-execution/assets.mjs +180 -0
  136. package/lh-plugins/case-execution/files.mjs +67 -15
  137. package/lh-plugins/case-execution/plans.mjs +318 -0
  138. package/lh-plugins/case-execution/service.mjs +80 -13
  139. package/lh-plugins/case-execution-prompt.mjs +4 -1
  140. package/lh-plugins/lh-case-automation.mjs +169 -0
  141. package/lh-plugins/lh-case-design.mjs +456 -0
  142. package/lh-plugins/lh-case-execution.mjs +53 -1
  143. package/lh-plugins/lh-case-review.mjs +29 -11
  144. package/lh-plugins/lh-project-docs.mjs +24 -0
  145. package/lh-plugins/lh-uiauto.mjs +111 -2
  146. package/lh-plugins/plugin-prompts.mjs +1 -0
  147. package/lh-plugins/uiauto-adapters/playwright.mjs +44 -4
  148. package/lh-plugins/uiauto-adapters/shared.mjs +4 -0
  149. package/lh-plugins/uiauto-explorer/emit-files.mjs +16 -2
  150. package/lh-plugins/uiauto-explorer/ir.mjs +3 -0
  151. package/lh-plugins/uiauto-explorer/merge.mjs +37 -1
  152. package/lh-plugins/uiauto-explorer/navigation-guard.mjs +255 -0
  153. package/lh-plugins/uiauto-explorer/runner.mjs +65 -3
  154. package/lh-plugins/uiauto-explorer/sessions.mjs +29 -1
  155. package/package.json +1 -1
  156. package/skills/case-automation-bridge/SKILL.md +27 -0
  157. package/skills/case-execution/SKILL.md +11 -0
  158. package/skills/lantern-workflow/SKILL.md +39 -1
  159. package/dist/_astro/Base.Du_-4L-4.css +0 -1
  160. package/dist/_astro/CaseExecutionBoard.CjX4CoKd.js +0 -5
  161. package/dist/_astro/CaseGenerateApp.acgnxl79.js +0 -10
  162. package/dist/_astro/CasesLibrary.zmzOQwdn.js +0 -21
  163. package/dist/_astro/ChatApp.Ben9LFra.js +0 -1
  164. package/dist/_astro/ChatApp.DBi6q7Qv.js +0 -262
  165. package/dist/_astro/NavLibraries.DVR5Ua-S.js +0 -1
  166. package/dist/_astro/PmRequirementsBoard.B0W6bsW2.js +0 -1
  167. package/dist/_astro/SlideOverDrawer.BMg2tce6.js +0 -1
  168. package/dist/_astro/TemplatesLibrary.peYzrHZ2.js +0 -1
  169. package/dist/_astro/UiAutoBoard.BGdlp5Sr.js +0 -3
  170. package/dist/_astro/UiAutoEnvPanel.BUASgPLB.js +0 -10
  171. package/dist/_astro/UiAutoGenerationDialog.D1PyCgrD.js +0 -12
  172. package/dist/_astro/UiAutoProjectsPage.B6A9NlVK.js +0 -3
  173. package/dist/_astro/app-config.Dvfzl5_N.js +0 -1
  174. package/dist/_astro/app-version.CNpnKIb9.js +0 -1
  175. package/dist/_astro/case-fields.CmePqYfh.js +0 -148
  176. package/dist/_astro/case-gen-run.Cvvdv_kv.js +0 -26
  177. package/dist/_astro/case-prompt.CZ3vWUju.js +0 -2
  178. package/dist/_astro/plugins.Db9xoFZb.js +0 -1
@@ -0,0 +1,255 @@
1
+ const HTTP_PROTOCOLS = new Set(['http:', 'https:']);
2
+ const DOCUMENT_TYPES = new Set(['Document']);
3
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
4
+ const MAX_BLOCKED_LOG = 80;
5
+ const MAX_REDIRECTS = 10;
6
+
7
+ function normalizeOrigin(value) {
8
+ try {
9
+ const url = new URL(String(value || ''));
10
+ if (!HTTP_PROTOCOLS.has(url.protocol) || url.username || url.password) return '';
11
+ return url.origin;
12
+ } catch {
13
+ return '';
14
+ }
15
+ }
16
+
17
+ export function normalizeAllowedOrigins(values) {
18
+ if (!Array.isArray(values)) return [];
19
+ return [...new Set(values.map(normalizeOrigin).filter(Boolean))];
20
+ }
21
+
22
+ export function isAllowedNavigationUrl(value, allowedOrigins) {
23
+ let url;
24
+ try {
25
+ url = new URL(String(value || ''));
26
+ } catch {
27
+ return false;
28
+ }
29
+ if (url.href === 'about:blank') return true;
30
+ if (!HTTP_PROTOCOLS.has(url.protocol) || url.username || url.password) return false;
31
+ return allowedOrigins.includes(url.origin);
32
+ }
33
+
34
+ /**
35
+ * Keep every browser page, popup and redirect inside the explicitly allowed origins.
36
+ *
37
+ * Playwright's context route does not see the destination of a server-side redirect:
38
+ * Chromium follows the new Location internally. The CDP Fetch domain pauses every
39
+ * document request, including each redirect hop, before it is sent. The context route
40
+ * remains as the first-navigation guard for newly created popup pages, which can begin
41
+ * navigating before a page-specific CDP session is attached.
42
+ */
43
+ export async function installNavigationGuard(context, rawOrigins, options = {}) {
44
+ const allowedOrigins = normalizeAllowedOrigins(rawOrigins);
45
+ if (!allowedOrigins.length) {
46
+ return {
47
+ allowedOrigins,
48
+ blocked: () => [],
49
+ guardPage: async () => undefined,
50
+ dispose: async () => undefined,
51
+ };
52
+ }
53
+
54
+ const onBlocked = typeof options.onBlocked === 'function' ? options.onBlocked : () => undefined;
55
+ const onError = typeof options.onError === 'function' ? options.onError : () => undefined;
56
+ const blocked = [];
57
+ const pageGuards = new WeakMap();
58
+ const sessions = new Set();
59
+ let disposed = false;
60
+
61
+ const recordBlocked = (value, source, pageUrl = '') => {
62
+ const entry = {
63
+ url: String(value || '').slice(0, 2000),
64
+ source,
65
+ pageUrl: String(pageUrl || '').slice(0, 2000),
66
+ allowedOrigins: [...allowedOrigins],
67
+ at: new Date().toISOString(),
68
+ };
69
+ blocked.push(entry);
70
+ if (blocked.length > MAX_BLOCKED_LOG) blocked.shift();
71
+ try {
72
+ onBlocked(entry);
73
+ } catch {
74
+ // A log sink must not weaken the navigation boundary.
75
+ }
76
+ };
77
+
78
+ const safeRedirectHeaders = (headers, from, to) => {
79
+ if (from.origin === to.origin) return headers;
80
+ const next = { ...headers };
81
+ for (const name of [
82
+ 'authorization',
83
+ 'cookie',
84
+ 'proxy-authorization',
85
+ 'host',
86
+ 'content-length',
87
+ ]) {
88
+ delete next[name];
89
+ }
90
+ return next;
91
+ };
92
+
93
+ /**
94
+ * New popup pages are not exposed to Playwright until their navigation finishes.
95
+ * For their first request, preflight every redirect with manual follow and stop on
96
+ * the first unauthorized Location. A successful first response is then fulfilled;
97
+ * for an allowed redirect chain Chromium can continue normally with the final URL.
98
+ */
99
+ const inspectPopupNavigation = async (route, request) => {
100
+ let current = request.url();
101
+ let method = request.method();
102
+ let postData = request.postDataBuffer() || undefined;
103
+ let headers = await request.allHeaders().catch(() => request.headers());
104
+ let firstResponse = null;
105
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
106
+ let response;
107
+ try {
108
+ response = await route.fetch({
109
+ url: current,
110
+ method,
111
+ headers,
112
+ postData,
113
+ maxRedirects: 0,
114
+ });
115
+ } catch (error) {
116
+ onError(error instanceof Error ? error : new Error(String(error)));
117
+ await route.abort('failed');
118
+ return false;
119
+ }
120
+ firstResponse ||= response;
121
+ if (!REDIRECT_STATUSES.has(response.status())) {
122
+ await route.fulfill({ response: firstResponse });
123
+ return true;
124
+ }
125
+ const location = response.headers().location;
126
+ if (!location) {
127
+ await route.fulfill({ response: firstResponse });
128
+ return true;
129
+ }
130
+ let next;
131
+ try {
132
+ next = new URL(location, current);
133
+ } catch {
134
+ recordBlocked(location, 'popup-redirect', current);
135
+ await route.abort('blockedbyclient');
136
+ return false;
137
+ }
138
+ if (!isAllowedNavigationUrl(next.href, allowedOrigins)) {
139
+ recordBlocked(next.href, 'popup-redirect', current);
140
+ await route.abort('blockedbyclient');
141
+ return false;
142
+ }
143
+ headers = safeRedirectHeaders(headers, new URL(current), next);
144
+ if (
145
+ response.status() === 303 ||
146
+ ([301, 302].includes(response.status()) && method.toUpperCase() === 'POST')
147
+ ) {
148
+ method = 'GET';
149
+ postData = undefined;
150
+ delete headers['content-type'];
151
+ delete headers['content-length'];
152
+ delete headers['transfer-encoding'];
153
+ }
154
+ current = next.href;
155
+ }
156
+ await route.abort('failed');
157
+ onError(new Error(`弹窗重定向超过 ${MAX_REDIRECTS} 次`));
158
+ return false;
159
+ };
160
+
161
+ await context.route('**/*', async (route) => {
162
+ const request = route.request();
163
+ if (!request.isNavigationRequest()) return route.continue();
164
+ const allowed = isAllowedNavigationUrl(request.url(), allowedOrigins);
165
+ let pageUrl = '';
166
+ let requestPage = null;
167
+ let frameUnavailable = false;
168
+ try {
169
+ const frame = request.frame();
170
+ pageUrl = frame?.url() || '';
171
+ requestPage = frame?.page?.() || null;
172
+ } catch {
173
+ // Popup documents can be intercepted before Playwright has attached a frame.
174
+ frameUnavailable = true;
175
+ }
176
+ if (frameUnavailable) {
177
+ if (!allowed) {
178
+ recordBlocked(request.url(), 'route', pageUrl);
179
+ return route.abort('blockedbyclient');
180
+ }
181
+ await inspectPopupNavigation(route, request);
182
+ return undefined;
183
+ }
184
+ // A popup can begin navigating before context.on('page') finishes attaching CDP.
185
+ // Wait for the request page guard before releasing this first request, otherwise
186
+ // a same-origin popup that immediately 302s cross-origin could race the guard.
187
+ if (requestPage) await guardPage(requestPage);
188
+ else await Promise.all(context.pages().map((page) => guardPage(page)));
189
+ if (allowed) return route.continue();
190
+ recordBlocked(request.url(), 'route', pageUrl);
191
+ return route.abort('blockedbyclient');
192
+ });
193
+
194
+ const guardPage = (page) => {
195
+ if (disposed) return Promise.resolve();
196
+ const existing = pageGuards.get(page);
197
+ if (existing) return existing;
198
+ const task = (async () => {
199
+ try {
200
+ const session = await context.newCDPSession(page);
201
+ if (disposed) {
202
+ await session.detach().catch(() => undefined);
203
+ return;
204
+ }
205
+ sessions.add(session);
206
+ session.on('Fetch.requestPaused', async (event) => {
207
+ if (disposed) return;
208
+ const isDocument = DOCUMENT_TYPES.has(event.resourceType);
209
+ const allowed = !isDocument || isAllowedNavigationUrl(event.request.url, allowedOrigins);
210
+ try {
211
+ if (allowed) {
212
+ await session.send('Fetch.continueRequest', { requestId: event.requestId });
213
+ } else {
214
+ recordBlocked(event.request.url, 'cdp', page.url());
215
+ await session.send('Fetch.failRequest', {
216
+ requestId: event.requestId,
217
+ errorReason: 'BlockedByClient',
218
+ });
219
+ }
220
+ } catch (error) {
221
+ if (!disposed) onError(error instanceof Error ? error : new Error(String(error)));
222
+ }
223
+ });
224
+ session.on('Inspector.detached', () => sessions.delete(session));
225
+ await session.send('Fetch.enable', {
226
+ patterns: [{ urlPattern: '*', requestStage: 'Request' }],
227
+ });
228
+ } catch (error) {
229
+ if (!disposed) onError(error instanceof Error ? error : new Error(String(error)));
230
+ }
231
+ })();
232
+ pageGuards.set(page, task);
233
+ return task;
234
+ };
235
+
236
+ context.on('page', (page) => void guardPage(page));
237
+ await Promise.all(context.pages().map((page) => guardPage(page)));
238
+
239
+ return {
240
+ allowedOrigins,
241
+ blocked: () => blocked.map((entry) => ({ ...entry })),
242
+ guardPage,
243
+ dispose: async () => {
244
+ disposed = true;
245
+ await Promise.all(
246
+ [...sessions].map(async (session) => {
247
+ await session.send('Fetch.disable').catch(() => undefined);
248
+ await session.detach().catch(() => undefined);
249
+ }),
250
+ );
251
+ sessions.clear();
252
+ await context.unroute('**/*').catch(() => undefined);
253
+ },
254
+ };
255
+ }
@@ -17,6 +17,7 @@ import { createRequire } from 'node:module';
17
17
 
18
18
  import { takeSnapshot, describeElement } from './snapshot.mjs';
19
19
  import { probeLocators } from './locators.mjs';
20
+ import { installNavigationGuard, normalizeAllowedOrigins } from './navigation-guard.mjs';
20
21
 
21
22
  const config = (() => {
22
23
  try {
@@ -54,8 +55,11 @@ let page = null;
54
55
  let closing = false;
55
56
  let shotSeq = 0;
56
57
  let lastAction = '';
58
+ let blockedSeq = 0;
59
+ let navigationGuard = null;
57
60
  const consoleLog = [];
58
61
  const networkLog = [];
62
+ const navigationBlockedLog = [];
59
63
 
60
64
  function remember(list, entry, max = 120) {
61
65
  list.push(entry);
@@ -72,6 +76,32 @@ function describeError(err) {
72
76
  return message.split('\n').slice(0, 6).join('\n');
73
77
  }
74
78
 
79
+ function rememberBlockedNavigation(entry) {
80
+ blockedSeq += 1;
81
+ const logged = { ...entry, seq: blockedSeq };
82
+ remember(navigationBlockedLog, logged);
83
+ remember(networkLog, {
84
+ status: 0,
85
+ url: logged.url,
86
+ method: 'GET',
87
+ failure: '跨域导航已拦截',
88
+ blocked: true,
89
+ source: logged.source,
90
+ });
91
+ return logged;
92
+ }
93
+
94
+ function blockedSince(seq) {
95
+ return navigationBlockedLog.filter((entry) => entry.seq > seq);
96
+ }
97
+
98
+ function navigationFailure(error, seq) {
99
+ const blocked = blockedSince(seq);
100
+ if (!blocked.length) return error;
101
+ const targets = [...new Set(blocked.map((entry) => entry.url))].slice(0, 3).join('、');
102
+ return new Error(`跨域导航已拦截:${targets}`);
103
+ }
104
+
75
105
  async function resolveRef(ref) {
76
106
  const handle = await page.evaluateHandle((key) => {
77
107
  const store = window.__lanternRefs;
@@ -110,9 +140,16 @@ async function ensurePage() {
110
140
  const handlers = {
111
141
  async open(args) {
112
142
  const url = String(args.url || '/').trim() || '/';
113
- await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });
143
+ const beforeBlocked = blockedSeq;
144
+ try {
145
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });
146
+ } catch (error) {
147
+ throw navigationFailure(error, beforeBlocked);
148
+ }
114
149
  await page.waitForLoadState('networkidle', { timeout: 4000 }).catch(() => undefined);
115
150
  await settle(args.settle ?? 400);
151
+ const blocked = blockedSince(beforeBlocked);
152
+ if (blocked.length) throw navigationFailure(new Error('页面访问被拦截'), beforeBlocked);
116
153
  lastAction = `打开 ${url}`;
117
154
  return snapshotResult(args);
118
155
  },
@@ -127,6 +164,7 @@ const handlers = {
127
164
  const action = String(args.action || '');
128
165
  const ref = String(args.ref || '');
129
166
  const note = String(args.note || '');
167
+ const beforeBlocked = blockedSeq;
130
168
  let label = '';
131
169
  const element = ref ? await resolveRef(ref) : null;
132
170
  try {
@@ -165,12 +203,16 @@ const handlers = {
165
203
  } else {
166
204
  throw new Error(`不支持的动作:${action}`);
167
205
  }
206
+ } catch (error) {
207
+ throw navigationFailure(error, beforeBlocked);
168
208
  } finally {
169
209
  if (element) await element.dispose().catch(() => undefined);
170
210
  }
171
211
 
172
212
  await page.waitForLoadState('networkidle', { timeout: 3000 }).catch(() => undefined);
173
213
  await settle(args.settle ?? 300);
214
+ const blocked = blockedSince(beforeBlocked);
215
+ if (blocked.length) throw navigationFailure(new Error('页面操作触发了跨域导航'), beforeBlocked);
174
216
  lastAction = note ? `${label}(${note})` : label;
175
217
  if (args.snapshot === false) {
176
218
  return { action: lastAction, url: page.url(), title: await page.title(), snapshot: '' };
@@ -233,7 +275,10 @@ const handlers = {
233
275
  },
234
276
 
235
277
  async network() {
236
- return { requests: networkLog.slice(-40) };
278
+ return {
279
+ requests: networkLog.slice(-40),
280
+ blockedNavigations: navigationBlockedLog.slice(-40),
281
+ };
237
282
  },
238
283
 
239
284
  async state() {
@@ -271,11 +316,27 @@ async function start() {
271
316
  // 给主进程一点时间读到最后一行,然后退出;不留在后台当僵尸
272
317
  setTimeout(() => process.exit(0), 50);
273
318
  });
274
- const contextOptions = { viewport: { width: 1440, height: 900 } };
319
+ const allowedOrigins = normalizeAllowedOrigins(config.allowedOrigins);
320
+ const contextOptions = {
321
+ viewport: { width: 1440, height: 900 },
322
+ ...(allowedOrigins.length ? { serviceWorkers: 'block' } : {}),
323
+ };
275
324
  if (config.baseURL) contextOptions.baseURL = String(config.baseURL);
276
325
  if (storageState && fs.existsSync(storageState)) contextOptions.storageState = storageState;
277
326
  context = await browser.newContext(contextOptions);
327
+ if (allowedOrigins.length) {
328
+ navigationGuard = await installNavigationGuard(context, allowedOrigins, {
329
+ onBlocked: rememberBlockedNavigation,
330
+ onError: (error) => {
331
+ remember(consoleLog, {
332
+ type: 'navigation-guard',
333
+ text: describeError(error).slice(0, 500),
334
+ });
335
+ },
336
+ });
337
+ }
278
338
  page = await context.newPage();
339
+ await navigationGuard?.guardPage(page);
279
340
  page.setDefaultTimeout(15000);
280
341
  // 文档编号随导航递增:旧 ref 在刷新后一定失效,而不是误指到别的元素
281
342
  await page.addInitScript(() => {
@@ -319,6 +380,7 @@ async function start() {
319
380
 
320
381
  async function shutdown() {
321
382
  closing = true;
383
+ await navigationGuard?.dispose().catch(() => undefined);
322
384
  try {
323
385
  await context?.close();
324
386
  } catch {
@@ -150,6 +150,7 @@ export function saveGeneratedSession(baseDir, rawPatch = {}) {
150
150
  storageState: existing.storageState,
151
151
  source: existing.source,
152
152
  target: existing.target,
153
+ automationCaseId: existing.automationCaseId,
153
154
  })
154
155
  : null;
155
156
  const record = {
@@ -210,6 +211,20 @@ export function listGeneratedSessions(baseDir, projectId = '') {
210
211
  return items.sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : -1)).slice(0, 50);
211
212
  }
212
213
 
214
+ /** 按自动化用例 ID 查找已绑定会话,重复评估时继续更新同一份 Plan。 */
215
+ export function findGeneratedSessionByAutomationCaseId(baseDir, automationCaseId) {
216
+ const id = String(automationCaseId || '').trim();
217
+ if (!id) return null;
218
+ const dir = sessionsDir(baseDir);
219
+ if (!fs.existsSync(dir)) return null;
220
+ for (const name of fs.readdirSync(dir)) {
221
+ if (!name.endsWith('.json')) continue;
222
+ const record = readJson(path.join(dir, name));
223
+ if (record?.automationCaseId === id) return record;
224
+ }
225
+ return null;
226
+ }
227
+
213
228
  /** 删掉生成会话 JSON 与旁边的 shots 目录;不负责停浏览器(调用方先停) */
214
229
  export function deleteGeneratedSession(baseDir, id) {
215
230
  if (!id) return false;
@@ -282,6 +297,8 @@ export function cleanupStaleSessions(baseDir, opts = {}) {
282
297
  if (RUNNING.has(record.id) || hasDebugSession(record.id)) continue;
283
298
  // 已关联工作台编排会话:跳过 TTL,避免侧栏点开域状态已空
284
299
  if (String(record.chatSessionId || '').trim()) continue;
300
+ // 功能用例自动化关联必须长期可恢复,直到用户显式删除关联或会话。
301
+ if (record.keepAlive === true || String(record.automationCaseId || '').trim()) continue;
285
302
  if (sessionAgeMs(record, file, now) <= ttl) continue;
286
303
 
287
304
  stopExplorer(record.id);
@@ -321,7 +338,15 @@ function respondError(entry, id, message) {
321
338
  }
322
339
 
323
340
  /** 拉起浏览器子进程,等到 ready 再返回 */
324
- export function startExplorer({ baseDir, project, sessionId, baseURL, headed, storageState }) {
341
+ export function startExplorer({
342
+ baseDir,
343
+ project,
344
+ sessionId,
345
+ baseURL,
346
+ headed,
347
+ storageState,
348
+ allowedOrigins,
349
+ }) {
325
350
  const existing = RUNNING.get(sessionId);
326
351
  if (existing) return Promise.resolve(existing);
327
352
 
@@ -334,6 +359,7 @@ export function startExplorer({ baseDir, project, sessionId, baseURL, headed, st
334
359
  baseURL: baseURL || '',
335
360
  headed: Boolean(headed),
336
361
  storageState: storageState || '',
362
+ ...(allowedOrigins ? { allowedOrigins } : {}),
337
363
  };
338
364
 
339
365
  const child = spawn(process.execPath, [RUNNER_PATH, JSON.stringify(payload)], {
@@ -1689,6 +1715,8 @@ export async function gitStatusSummary(projectDir) {
1689
1715
  }
1690
1716
 
1691
1717
  export function suggestedPath({ project, session }) {
1718
+ const pinned = normalizeRelPath(session?.iterationFile || '');
1719
+ if (pinned) return pinned;
1692
1720
  const ir = normalizeIr(session.ir || {}, { target: session.target, title: session.title });
1693
1721
  const emitted = emitCode(ir, session.target);
1694
1722
  return `${detectPlaywrightTestDir(project.dir)}/${emitted.filename}`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lantern-harness",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "AI 工作台:对话与插件工具、内容库、模板库、会话记忆,数据留在本机。",
@@ -0,0 +1,27 @@
1
+ ---
2
+ name: case-automation-bridge
3
+ description: 将功能测试用例评估、拆解为可执行的 UI 自动化用例与 UI Plan,并绑定现有 UI 自动化项目和 iteration 文件。
4
+ ---
5
+
6
+ # 功能用例转 UI 自动化
7
+
8
+ ## 适用范围
9
+
10
+ 用于从功能测试用例中提取 UI 自动化范围。功能用例仍是业务事实来源;本技能只做可自动化评估、用例拆分和 UI Plan 设计。
11
+
12
+ ## 流程
13
+
14
+ 1. 读取用户明确选择的功能用例行,以及所选 UI 自动化项目的框架、地址和迭代文件。
15
+ 2. 逐条判断 `automatable`、`needs_manual` 或 `not_automatable`,说明依据和风险。
16
+ 3. 只对可自动化条目生成自动化用例:前置条件、可执行步骤、可观察预期和最小 UI Plan。
17
+ 4. 校验 Plan 动作、断言、环境变量占位和敏感信息。
18
+ 5. 用户确认后,由平台写入自动化用例文件、创建待探索 UI 自动化会话并绑定项目与 iteration 文件。
19
+
20
+ ## 约束
21
+
22
+ - 不生成 CSS、XPath、坐标、定位器或脚本代码。
23
+ - 不把接口、性能、数据库、App 原生操作误判为 UI 自动化。
24
+ - 不修改原功能用例,不覆盖人工执行结果。
25
+ - 不自动开始浏览器探索、写项目或运行脚本。
26
+ - 一个功能用例可拆成多个自动化用例;每条自动化用例必须有唯一稳定 ID。
27
+ - 目标脚本最终合并到项目现有 `tests/iteration/<迭代>.spec.ts`,而不是独立 spec。
@@ -21,6 +21,7 @@ Lantern 是执行记录、用例文件和确认结果的唯一持久化入口。
21
21
  3. 只有页面、截图、控制台或网络证据真正支持预期结果时才能建议「通过」。明确与预期不一致为「不通过」;登录失效、验证码、权限、测试数据或系统弹窗导致无法完成时为「阻塞」;用例不适用且理由充分时为「跳过」。
22
22
  4. 不要替用户确认。向用户展示建议状态、实际结果、判定依据、未验证项和证据;用户可把状态改为「待验证 / 通过 / 不通过 / 阻塞 / 跳过」。
23
23
  5. 需要停止时调用 `lantern_case_execution_stop`,保留已产生的日志和截图。
24
+ 6. 目标地址只能访问本次授权的目标 origin 和明确允许的登录 origin。脚本跳转、弹窗和每次服务端重定向都受同一限制;出现「跨域导航已拦截」时把目标地址写进阻塞原因,不继续尝试绕过。
24
25
 
25
26
  ## 确认与后续
26
27
 
@@ -28,3 +29,13 @@ Lantern 是执行记录、用例文件和确认结果的唯一持久化入口。
28
29
  2. 结果为「不通过」或「阻塞」时,主动提供创建缺陷入口,但不要在用户未要求时自动提交。用户要求提缺陷时,转入 `lantern-defect-submit`,把用例、目标地址、实际结果和证据作为待核验上下文。
29
30
  3. 用户要求同步统计时,先调用 `lantern_case_execution_sync_stats` 的 `preview`。已有同日手工统计时不自动覆盖;只有用户明确选择后才使用 `skip` 或 `overwrite`。
30
31
  4. 执行记录、日志和截图保存在当前空间的 `.lantern/local/case-execution/`。不要把这些内部文件加入 `用例管理/`,也不要把浏览器 Cookie、Token 或 API Key 写入结果。
32
+
33
+ ## 基线、生成与计划
34
+
35
+ - Codex 生成用例使用 `lantern_case_generation_context` 读取当前空间技能和需求基线,生成 rows 后用 `validate` 确定性校验引用与覆盖,再用 `save` 携带原 revision 和 sourceFileHash 入库;源文件变更后必须重新读取。新文件自动具备执行列。
36
+ - 已有文件缺执行列时用 `lantern_case_execution_prepare_columns` 先 preview,用户确认后 apply;XLS 仍需另存为 XLSX。
37
+ - 用户明确要求批量执行并指定范围时,可创建执行计划;保存 caseIds、环境、角色、构建和数据说明后,显式启动。浏览器串行执行;API / App 使用已有自动化项目与指定测试文件,环境缺失应报告阻塞。准备和清理任务只能使用用户选定的项目任务。性能测试不在本轮能力中。
38
+ - 计划停止后不启动新项;重启后显式继续未完成项。计划和单条执行都不会自动选择最终结果。
39
+ - 使用稳定 caseId 对应原用例;需求基线或用例步骤变化后不能把旧通过计入新版本验收。基线重新关联须先 preview 并由用户确认,历史运行保留但结果要求人工复核。
40
+ - 一条用例允许多个 HTTP(S) 缺陷地址;用例文件的缺陷地址字段以换行保存。仅维护链接,不自动提交、关闭或复测缺陷。
41
+ - `lantern_case_acceptance` 返回确定性的设计、执行与通过覆盖及未覆盖项;环境不同的结果要分开核验,报告不能当作缺陷关闭或性能验证证明。
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: lantern-workflow
3
- description: Use Lantern Harness MCP tools for requirement import, requirement breakdown, story review, test points and Lantern-backed test assets. Use when the user provides a requirement document or says to analyze, break down, review or generate tests with Lantern.
3
+ description: Use Lantern Harness MCP tools for requirement import, requirement breakdown, story review, test points, functional cases, UI automation projects and scripts, automation runs, defects and business-map updates. Use when the user provides a requirement document or asks Codex to analyze, generate, automate, execute or update Lantern test assets.
4
4
  ---
5
5
 
6
6
  # Lantern Workflow
@@ -13,6 +13,10 @@ Lantern is the source of truth for requirement documents and test assets. Codex
13
13
  - “完整需求分析” means: breakdown, save stories, review stories, generate test points, then return the combined summary.
14
14
  - “生成测试点” means: use existing saved stories and a Lantern test-point skill. Do not silently replace stories.
15
15
  - “继续生成用例” or “完整测试设计” continues from the saved requirement analysis.
16
+ - “生成功能测试用例” means: generate a functional case file in the `功能测试` folder, validate references and save it.
17
+ - “补自动化 / 转 UI 自动化 / 生成自动化脚本” means: inspect or prepare the UI project, assess selected functional cases, bind an iteration, explore pages, emit and verify the script, then write it into the project.
18
+ - “自动执行 / 运行自动化” means: run only explicit automationCaseIds or an explicit execution scope, then return the batch/report status.
19
+ - “更新业务地图” means: read the latest map first, then create or update only the systems, directories, functions and flows required by the request.
16
20
  - If multiple documents could be “这个需求”, ask which source before writing.
17
21
 
18
22
  ## Requirement breakdown
@@ -39,6 +43,38 @@ Lantern is the source of truth for requirement documents and test assets. Codex
39
43
  3. Use only `functional`, `boundary`, `exception`, `business`, `nonfunctional`, and P0–P3 priorities.
40
44
  4. Call `lantern_testpoints_save` with the complete report and the current `revision`.
41
45
 
46
+ ## Functional case generation
47
+
48
+ 1. Prefer the saved `analysisId`. Otherwise call `lantern_case_generation_context` with the known `sourcePath`.
49
+ 2. Follow the returned skill and output contract. Generate rows that use only real RO / US / TP references.
50
+ 3. Call `lantern_case_generation_validate`. Fix and revalidate until there are no deterministic issues.
51
+ 4. Call `lantern_case_generation_save` with the context revision, source hash, rows, title and format.
52
+ 5. Set `folder` to the matching case type folder, normally `功能测试`. Do not leave a functional case at the case-library root unless the user explicitly asks for root storage.
53
+ 6. Report the actual saved path, case count, executable status and coverage. Do not claim coverage from the model response.
54
+
55
+ ## UI automation closure
56
+
57
+ 1. Call `lantern_uiauto_projects` and select a UI project by the user's project name. A UI case conversion requires a project whose detected kind is UI and, for generated scripts, Playwright.
58
+ 2. If a suitable project directory already exists, call `lantern_uiauto_project_mount`. Configure the tested base URL, storageState path and environment with `lantern_uiauto_project_update` when needed.
59
+ 3. If it does not exist and the user asked to create it, call `lantern_uiauto_project_scaffold_preview` first. If the preview is valid, call `lantern_uiauto_project_scaffold_create` with the explicit parent directory, then `lantern_uiauto_project_setup_start`.
60
+ 4. Poll `lantern_uiauto_project_setup_get` until installation finishes. Do not invent a different environment check when setup is blocked.
61
+ 5. Call `lantern_case_automation_cases` to get stable source case IDs and `lantern_case_automation_iterations` to select or create the iteration name.
62
+ 6. Call `lantern_case_automation_assess` with only the user-requested caseIds, the project and iteration. Review decisions, risks and UI Plans with the user.
63
+ 7. When the user asked for the complete conversion, call `lantern_case_automation_apply`. Keep returned automationCaseIds and uiSessionIds.
64
+ 8. For each returned session, use `lantern_uiauto_agent_session_get`. Open the target page, inspect snapshots, wait for asynchronous conditions, perform authorized actions and bind locators with probe.
65
+ 9. Save the Plan/IR with `lantern_uiauto_agent_save`, preview files with `lantern_uiauto_agent_emit`, run the isolated draft with `lantern_uiauto_agent_verify`, then merge with `lantern_uiauto_agent_write` only after the preview and verification are understood.
66
+ 10. Close exploration with `lantern_uiauto_agent_close`.
67
+ 11. Start formal runs with `lantern_case_automation_run`, then use `run_wait` / `run_get`. Use `run_stop` only when requested or when the run is no longer useful.
68
+ 12. Report per-automationCaseId status and report paths. A formal pass may update the source case only when all linked automation cases pass and no manual result takes precedence.
69
+
70
+ ## Business-map updates
71
+
72
+ 1. Call `lantern_business_map_list` for the latest revision and `lantern_business_map_get` for the target system.
73
+ 2. If the target system does not exist and the user authorized creation, call `lantern_business_system_save` without a systemId.
74
+ 3. Create missing directories, functions and flows with the corresponding save tools and the current `expectedRevision`.
75
+ 4. Base functions and flows on the requirement, attached documents, page evidence or user statements. Use draft or lower-confidence content when evidence is incomplete; never present inferred behavior as verified without evidence.
76
+ 5. Re-read the map after a revision conflict and reapply only the intended change.
77
+
42
78
  ## Editing existing results
43
79
 
44
80
  - To change one story, read the analysis, then call `lantern_requirement_story_patch` with its `storyId`, `revision` and only the changed fields.
@@ -50,8 +86,10 @@ Lantern is the source of truth for requirement documents and test assets. Codex
50
86
 
51
87
  - Never edit Lantern JSON files directly.
52
88
  - Never use browser automation to click Lantern UI for ordinary operations.
89
+ - Browser automation through `lantern_uiauto_agent_*` is for the target system under test, not for clicking Lantern itself.
53
90
  - Use `analysisId`, `revision` and the latest saved content before modifying.
54
91
  - Disabled Lantern skills are not valid workflow rules. Use `lantern_skill_list` to check status; include disabled skills only when the user asks to inspect the store.
55
92
  - Previewing means not calling the save tool. Saving is a separate explicit action.
56
93
  - Bulk deletion and replacing stories require an explicit user request. Delete whole analyses only with `lantern_requirement_analysis_delete`.
57
94
  - Return Lantern artifact URLs and summaries to the user.
95
+ - Report only actual tool outputs. Do not say a project, script, test, regression or business flow was created unless the corresponding write/run tool returned success.