lantern-harness 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/README.md +7 -7
  3. package/builtin/session/lh-fs.mjs +32 -14
  4. package/cli/server.mjs +2 -0
  5. package/config/app.defaults.json +1 -0
  6. package/dist/500.html +258 -22
  7. package/dist/_astro/Base.BOY6F0mi.css +1 -0
  8. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.C30xtpc6.js +1 -0
  9. package/dist/_astro/CaseExecBoard.Dttqp0wg.js +1 -0
  10. package/dist/_astro/CaseGenerateApp.DqW_nWMc.js +9 -0
  11. package/dist/_astro/CasesLibrary.8aMUUGp_.js +1 -0
  12. package/dist/_astro/ChatApp.BLxf0h1d.js +219 -0
  13. package/dist/_astro/ColumnResize.BEkEW7qw.js +1 -0
  14. package/dist/_astro/{ConfirmDialog.CBVsDJ8f.js → ConfirmDialog.BZzZWDci.js} +1 -1
  15. package/dist/_astro/{DashboardBoard.Bd3eUPwZ.js → DashboardBoard.CkSbhEDI.js} +3 -3
  16. package/dist/_astro/DatePicker.Bkl71M49.js +1 -0
  17. package/dist/_astro/DocsFileBrowser.MKVCfZrE.js +1 -0
  18. package/dist/_astro/DocsPager.DJY4foYL.js +1 -0
  19. package/dist/_astro/{DrawerField.CWMLhcPX.js → DrawerField.CHRg77LG.js} +1 -1
  20. package/dist/_astro/{ExcelFieldTags.B_XMwNNx.js → ExcelFieldTags.DXMeaDa5.js} +4 -4
  21. package/dist/_astro/KnowledgeLibrary.B-p1aoQN.js +1 -0
  22. package/dist/_astro/NamePromptDialog.Wa9O530a.js +1 -0
  23. package/dist/_astro/NavLibraries.C6LImMO_.js +1 -0
  24. package/dist/_astro/OverflowHint.D6v4Uj2N.js +1 -0
  25. package/dist/_astro/PluginsPage.-97n3x2U.js +39 -0
  26. package/dist/_astro/PluginsPage.DkmRPfbU.js +1 -0
  27. package/dist/_astro/PmBugsBoard.CMT4-eoB.js +1 -0
  28. package/dist/_astro/PmIterationsBoard.BQM_dzdZ.js +1 -0
  29. package/dist/_astro/PmProjectDetail.CzU80pat.js +1 -0
  30. package/dist/_astro/PmProjectsBoard.Cxsa7SYQ.js +1 -0
  31. package/dist/_astro/PmRequirementsBoard.4_JMDDN0.js +1 -0
  32. package/dist/_astro/PmRequirementsBoard.B8HL07cw.js +1 -0
  33. package/dist/_astro/PmShared.Ca2Ao7v_.js +1 -0
  34. package/dist/_astro/PromptsLibrary.C9BcIxKK.js +1 -0
  35. package/dist/_astro/ReportsPage.Fh5DRKLT.js +1 -0
  36. package/dist/_astro/RequirementsLibrary.CBkuWE8X.js +1 -0
  37. package/dist/_astro/SearchableSelect.DnjoSslK.js +1 -0
  38. package/dist/_astro/SelectDropdown.CuuDHa8s.js +1 -0
  39. package/dist/_astro/SettingsDialog.CJvBRcs9.js +1 -0
  40. package/dist/_astro/SlideOverDrawer.B7B5Wu8I.js +1 -0
  41. package/dist/_astro/{SpaceSwitcher.BEJo5KFi.js → SpaceSwitcher.BVQLt_tL.js} +2 -2
  42. package/dist/_astro/TagSelect.CuN5RdF4.js +1 -0
  43. package/dist/_astro/TasksBoard.Bu-fpIZ7.js +1 -0
  44. package/dist/_astro/TemplatesLibrary.DSylQGlN.js +1 -0
  45. package/dist/_astro/TestStatsBoard.CPyKW4wc.js +1 -0
  46. package/dist/_astro/Toast.R8_2OWRX.js +1 -0
  47. package/dist/_astro/TodosBoard.8kvRTEW-.js +1 -0
  48. package/dist/_astro/UiAutoBoard.DFTiDqCp.js +9 -0
  49. package/dist/_astro/active-element-history.CED-m1Zp.js +1 -0
  50. package/dist/_astro/app-config.BUPzGl9f.js +1 -0
  51. package/dist/_astro/{client.Be_SakrB.js → client.BHNTqLjv.js} +3 -3
  52. package/dist/_astro/dialog.BAPTk9a_.js +1 -0
  53. package/dist/_astro/hydrate-cache.BXX604Bw.js +1 -0
  54. package/dist/_astro/i18n.BGPnP1Bg.js +7 -0
  55. package/dist/_astro/index.astro_astro_type_script_index_0_lang.LPL9mPQY.js +1 -0
  56. package/dist/_astro/jsx-runtime.DUg_B_vD.js +1 -0
  57. package/dist/_astro/{lib.DJNDi_Ht.js → lib.CgXLzMMd.js} +15 -15
  58. package/dist/_astro/listbox.C96OCanh.js +1 -0
  59. package/dist/_astro/markdown-client.DRva7DS9.js +58 -0
  60. package/dist/_astro/menu.IPWdRoNM.js +1 -0
  61. package/dist/_astro/{open-docs-in-session.B0ZdZNj2.js → open-docs-in-session.CyFNgh1I.js} +1 -1
  62. package/dist/_astro/{plugins.D5ypJIXn.js → plugins.C2BMfzv1.js} +1 -1
  63. package/dist/_astro/{pm.BsnTv63L.js → pm.CagBA-ht.js} +4 -4
  64. package/dist/_astro/{portal.Cm9XlIPf.js → portal.C0hAhXDF.js} +2 -2
  65. package/dist/_astro/prompts-meta.Bua-j14I.js +2 -0
  66. package/dist/_astro/react-dom.DLW9pGCF.js +1 -0
  67. package/dist/_astro/{react-dom.CqAxpHMt.js → react.Blvh0GOs.js} +1 -1
  68. package/dist/_astro/report-prompt.CAfZ6RIo.js +1 -0
  69. package/dist/_astro/{settings.CnDCvwnQ.js → settings.Ceefeil5.js} +2 -2
  70. package/dist/_astro/{spaces-client.Cai2tHEI.js → spaces-client.BocUabwy.js} +1 -1
  71. package/dist/_astro/ui-auto-prompt.CX8fju7r.js +3 -0
  72. package/dist/_astro/ui-auto.BmC9JJ_X.js +1 -0
  73. package/dist/_astro/update.CvfIVwnq.js +1 -0
  74. package/dist/_astro/use-text-value.DBQvHeNl.js +1 -0
  75. package/dist/_astro/use-tree-walker.DFU2AaAP.js +1 -0
  76. package/dist/_astro/useListAnim.BoerpmsB.js +1 -0
  77. package/dist/_astro/{view-prefs.HCowOWXL.js → view-prefs.BEAZRcxF.js} +1 -1
  78. package/dist/case-exec/index.html +458 -22
  79. package/dist/cases/generate/index.html +258 -22
  80. package/dist/cases/library/index.html +458 -22
  81. package/dist/dashboard/index.html +458 -22
  82. package/dist/docs/changelog/index.html +389 -23
  83. package/dist/docs/install/index.html +258 -22
  84. package/dist/docs/manual/index.html +324 -27
  85. package/dist/index.html +2 -281
  86. package/dist/knowledge/index.html +458 -22
  87. package/dist/knowledge//345/212/237/350/203/275/346/265/213/350/257/225/347/224/250/344/276/213/347/274/226/345/206/231/350/247/204/350/214/203/index.html +258 -22
  88. package/dist/plugins/index.html +258 -22
  89. package/dist/pm/bugs/index.html +458 -22
  90. package/dist/pm/iterations/index.html +458 -22
  91. package/dist/pm/projects/detail/index.html +458 -22
  92. package/dist/pm/projects/index.html +458 -22
  93. package/dist/pm/requirements/index.html +458 -22
  94. package/dist/prompts/index.html +458 -22
  95. package/dist/reports/index.html +458 -22
  96. package/dist/requirements/index.html +458 -22
  97. package/dist/tasks/index.html +458 -22
  98. package/dist/templates/index.html +458 -22
  99. package/dist/templates//345/212/237/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212//345/212/237/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212/346/250/241/346/235/277/index.html +258 -22
  100. package/dist/templates//346/200/247/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212//346/200/247/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212/346/250/241/346/235/277/index.html +258 -22
  101. package/dist/templates//346/200/247/350/203/275/346/265/213/350/257/225/347/224/250/344/276/213//346/200/247/350/203/275/346/265/213/350/257/225/347/224/250/344/276/213/346/250/241/346/235/277/index.html +258 -22
  102. package/dist/templates//346/216/245/345/217/243/346/265/213/350/257/225/346/212/245/345/221/212//346/216/245/345/217/243/346/265/213/350/257/225/346/212/245/345/221/212/346/250/241/346/235/277/index.html +258 -22
  103. package/dist/templates//350/207/252/345/212/250/345/214/226/346/265/213/350/257/225/347/224/250/344/276/213//350/207/252/345/212/250/345/214/226/346/265/213/350/257/225/347/224/250/344/276/213/346/250/241/346/235/277/index.html +258 -22
  104. package/dist/test-automation/index.html +717 -0
  105. package/dist/test-stats/index.html +458 -22
  106. package/dist/todos/index.html +458 -22
  107. package/dist/workbench/index.html +517 -0
  108. package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +85 -34
  109. package/lh-plugins/lh-project-docs.mjs +14 -0
  110. package/lh-plugins/lh-uiauto.mjs +2296 -0
  111. package/lh-plugins/plugin-prompts.mjs +200 -0
  112. package/lh-plugins/storage-domain.mjs +13 -0
  113. package/lh-plugins/uiauto-adapters/index.mjs +57 -0
  114. package/lh-plugins/uiauto-adapters/playwright.mjs +215 -0
  115. package/lh-plugins/uiauto-adapters/pytest.mjs +151 -0
  116. package/lh-plugins/uiauto-adapters/selenium.mjs +163 -0
  117. package/lh-plugins/uiauto-adapters/shared.mjs +371 -0
  118. package/lh-plugins/uiauto-adapters/tasks.mjs +369 -0
  119. package/lh-plugins/uiauto-argv-guard.cjs +41 -0
  120. package/lh-plugins/uiauto-explorer/apps.mjs +332 -0
  121. package/lh-plugins/uiauto-explorer/diff.mjs +159 -0
  122. package/lh-plugins/uiauto-explorer/emit-files.mjs +506 -0
  123. package/lh-plugins/uiauto-explorer/emit-python.mjs +160 -0
  124. package/lh-plugins/uiauto-explorer/emit-ts.mjs +118 -0
  125. package/lh-plugins/uiauto-explorer/emit.mjs +15 -0
  126. package/lh-plugins/uiauto-explorer/ir.mjs +114 -0
  127. package/lh-plugins/uiauto-explorer/locators.mjs +267 -0
  128. package/lh-plugins/uiauto-explorer/merge.mjs +235 -0
  129. package/lh-plugins/uiauto-explorer/plan.mjs +165 -0
  130. package/lh-plugins/uiauto-explorer/runner.mjs +370 -0
  131. package/lh-plugins/uiauto-explorer/sessions.mjs +1373 -0
  132. package/lh-plugins/uiauto-explorer/snapshot.mjs +492 -0
  133. package/lh-plugins/uiauto-prompt.mjs +122 -0
  134. package/lh-plugins/uiauto-report.mjs +111 -0
  135. package/package.json +1 -1
  136. package/dist/_astro/Base.DjIEQkT7.css +0 -1
  137. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.D0snmAJ_.js +0 -1
  138. package/dist/_astro/CaseExecBoard.BAV4EE3o.js +0 -1
  139. package/dist/_astro/CaseGenerateApp.Bz4ryNJG.js +0 -9
  140. package/dist/_astro/CasesLibrary.BPifyHUA.js +0 -1
  141. package/dist/_astro/ChatApp.DLo31SYZ.js +0 -276
  142. package/dist/_astro/ColumnResize.Bs6GL3DJ.js +0 -1
  143. package/dist/_astro/DatePicker.CMfX7F6z.js +0 -1
  144. package/dist/_astro/DocsFileBrowser.D3cKurQE.js +0 -1
  145. package/dist/_astro/DocsPager.rzu4mnzw.js +0 -1
  146. package/dist/_astro/KnowledgeLibrary.B0sO4QR1.js +0 -1
  147. package/dist/_astro/NamePromptDialog.Dl5kSnQI.js +0 -1
  148. package/dist/_astro/NavLibraries.Cvg3wery.js +0 -1
  149. package/dist/_astro/OverflowHint.lzmplP5j.js +0 -1
  150. package/dist/_astro/PluginsPage.DIltPILi.js +0 -39
  151. package/dist/_astro/PluginsPage.uvmSuXzi.js +0 -1
  152. package/dist/_astro/PmBugsBoard.CiaIhCHv.js +0 -1
  153. package/dist/_astro/PmIterationsBoard.H67QwKFw.js +0 -1
  154. package/dist/_astro/PmProjectDetail.DqDoIg8a.js +0 -1
  155. package/dist/_astro/PmProjectsBoard.nOC1Hugt.js +0 -1
  156. package/dist/_astro/PmRequirementsBoard.BPjZ7khP.js +0 -1
  157. package/dist/_astro/PmRequirementsBoard.CanxvcKg.js +0 -1
  158. package/dist/_astro/PmShared.CZnXaUq-.js +0 -1
  159. package/dist/_astro/PromptsLibrary.DU9EuSim.js +0 -1
  160. package/dist/_astro/ReportsPage.Cr88iz8c.js +0 -1
  161. package/dist/_astro/RequirementsLibrary.BwriF8F0.js +0 -1
  162. package/dist/_astro/SearchableSelect.Ctg8V1Z1.js +0 -1
  163. package/dist/_astro/SelectDropdown.Buv7rQJ_.js +0 -1
  164. package/dist/_astro/SettingsDialog.DEgsVfaL.js +0 -1
  165. package/dist/_astro/SlideOverDrawer.TPbGEoWn.js +0 -1
  166. package/dist/_astro/TagSelect.u8DTop7v.js +0 -1
  167. package/dist/_astro/TasksBoard.BZi_GBPG.js +0 -1
  168. package/dist/_astro/TemplatesLibrary.T4K9jUex.js +0 -1
  169. package/dist/_astro/TestStatsBoard.Dd1Kcmx6.js +0 -1
  170. package/dist/_astro/TodosBoard.C4yd_JFb.js +0 -1
  171. package/dist/_astro/active-element-history.CeefGkFQ.js +0 -1
  172. package/dist/_astro/app-config.DKMxjv3g.js +0 -1
  173. package/dist/_astro/dialog.DXHznyjD.js +0 -1
  174. package/dist/_astro/i18n.BXeGGutk.js +0 -7
  175. package/dist/_astro/jsx-runtime.BUXbF_vF.js +0 -1
  176. package/dist/_astro/listbox.Di-t5U37.js +0 -1
  177. package/dist/_astro/menu.Bkluqxic.js +0 -1
  178. package/dist/_astro/prompts-meta.F4wwkjUA.js +0 -2
  179. package/dist/_astro/report-prompt.Cmw4XzfY.js +0 -1
  180. package/dist/_astro/update.DXCPfU4a.js +0 -1
  181. package/dist/_astro/use-text-value.BuY0Cm1z.js +0 -1
  182. package/dist/_astro/use-tree-walker.CfTHFX43.js +0 -1
  183. package/dist/_astro/useListAnim.CpGB1cft.js +0 -1
@@ -0,0 +1,370 @@
1
+ /**
2
+ * 浏览器探索子进程(由 lh-uiauto.mjs 拉起,一行一个 JSON 命令)。
3
+ *
4
+ * 为什么单开进程:
5
+ * - 浏览器和 Playwright 都从「被挂载的项目」里解析,不污染 harness 自身依赖
6
+ * - 崩溃 / 卡住只影响当前会话,SIGTERM 就能清干净
7
+ *
8
+ * 协议:
9
+ * 启动参数 argv[2] = { projectDir, shotDir, baseURL, headed, storageState, slowMo }
10
+ * 父 → 子:{ id, cmd, args }
11
+ * 子 → 父:{ type: 'ready' } / { type: 'closed' } / { id, ok, result } / { id, ok: false, error }
12
+ */
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import readline from 'node:readline';
16
+ import { createRequire } from 'node:module';
17
+
18
+ import { takeSnapshot, describeElement } from './snapshot.mjs';
19
+ import { probeLocators } from './locators.mjs';
20
+
21
+ const config = (() => {
22
+ try {
23
+ return JSON.parse(process.argv[2] || '{}');
24
+ } catch {
25
+ return {};
26
+ }
27
+ })();
28
+
29
+ const projectDir = path.resolve(config.projectDir || '.');
30
+ const shotDir = path.resolve(config.shotDir || path.join(projectDir, '.lantern-shots'));
31
+ const storageState = config.storageState ? path.resolve(projectDir, config.storageState) : '';
32
+ const slowMo = Number.isFinite(Number(config.slowMo)) ? Number(config.slowMo) : 120;
33
+
34
+ fs.mkdirSync(shotDir, { recursive: true });
35
+
36
+ /** 被挂载项目里的 Playwright(优先 playwright,其次 @playwright/test) */
37
+ function loadPlaywright() {
38
+ const requireFromProject = createRequire(path.join(projectDir, 'package.json'));
39
+ for (const name of ['playwright', '@playwright/test']) {
40
+ try {
41
+ const mod = requireFromProject(name);
42
+ if (mod && mod.chromium) return { mod, name };
43
+ } catch {
44
+ // 继续试下一个
45
+ }
46
+ }
47
+ return null;
48
+ }
49
+
50
+ let browser = null;
51
+ let context = null;
52
+ let page = null;
53
+ /** 主动关闭(收到 close 命令 / SIGTERM)时不要上报「浏览器被用户关了」 */
54
+ let closing = false;
55
+ let shotSeq = 0;
56
+ let lastAction = '';
57
+ const consoleLog = [];
58
+ const networkLog = [];
59
+
60
+ function remember(list, entry, max = 120) {
61
+ list.push(entry);
62
+ if (list.length > max) list.shift();
63
+ }
64
+
65
+ async function settle(ms) {
66
+ const wait = Number.isFinite(Number(ms)) ? Number(ms) : 260;
67
+ if (wait > 0) await page.waitForTimeout(wait);
68
+ }
69
+
70
+ function describeError(err) {
71
+ const message = err instanceof Error ? err.message : String(err);
72
+ return message.split('\n').slice(0, 6).join('\n');
73
+ }
74
+
75
+ async function resolveRef(ref) {
76
+ const handle = await page.evaluateHandle((key) => {
77
+ const store = window.__lanternRefs;
78
+ return store ? (store.get(key) ?? null) : null;
79
+ }, ref);
80
+ const element = handle.asElement();
81
+ if (!element) {
82
+ await handle.dispose().catch(() => undefined);
83
+ throw new Error(`ref ${ref} 已失效(元素不在页面上),请先重新获取快照`);
84
+ }
85
+ return element;
86
+ }
87
+
88
+ async function snapshotResult(options = {}) {
89
+ const snapshot = await takeSnapshot(page, {
90
+ maxNodes: options.maxNodes ?? 400,
91
+ maxText: options.maxText ?? 80,
92
+ maxDepth: options.depth ?? 6,
93
+ targetRef: options.targetRef ?? '',
94
+ includeBoxes: Boolean(options.boxes),
95
+ });
96
+ return {
97
+ url: snapshot.url,
98
+ title: snapshot.title,
99
+ count: snapshot.count,
100
+ truncated: snapshot.truncated,
101
+ snapshot: snapshot.text || '(页面上没有可交互元素)',
102
+ };
103
+ }
104
+
105
+ async function ensurePage() {
106
+ if (!page) throw new Error('浏览器还没打开页面,请先调用 ui_browser_open');
107
+ return page;
108
+ }
109
+
110
+ const handlers = {
111
+ async open(args) {
112
+ const url = String(args.url || '/').trim() || '/';
113
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });
114
+ await page.waitForLoadState('networkidle', { timeout: 4000 }).catch(() => undefined);
115
+ await settle(args.settle ?? 400);
116
+ lastAction = `打开 ${url}`;
117
+ return snapshotResult(args);
118
+ },
119
+
120
+ async snapshot(args) {
121
+ await ensurePage();
122
+ return snapshotResult(args);
123
+ },
124
+
125
+ async action(args) {
126
+ await ensurePage();
127
+ const action = String(args.action || '');
128
+ const ref = String(args.ref || '');
129
+ const note = String(args.note || '');
130
+ let label = '';
131
+ const element = ref ? await resolveRef(ref) : null;
132
+ try {
133
+ if (action === 'click') {
134
+ await element.click({ timeout: 15000 });
135
+ label = '点击';
136
+ } else if (action === 'fill') {
137
+ await element.fill(String(args.text ?? ''), { timeout: 15000 });
138
+ label = `填写「${String(args.text ?? '').slice(0, 40)}」`;
139
+ } else if (action === 'select') {
140
+ await element.selectOption(String(args.value ?? ''));
141
+ label = `选择「${String(args.value ?? '')}」`;
142
+ } else if (action === 'hover') {
143
+ await element.hover({ timeout: 15000 });
144
+ label = '悬停';
145
+ } else if (action === 'press') {
146
+ const key = String(args.key || 'Enter');
147
+ if (element) await element.press(key, { timeout: 15000 });
148
+ else await page.keyboard.press(key);
149
+ label = `按键 ${key}`;
150
+ } else if (action === 'check') {
151
+ await element.check({ timeout: 15000 });
152
+ label = '勾选';
153
+ } else if (action === 'uncheck') {
154
+ await element.uncheck({ timeout: 15000 });
155
+ label = '取消勾选';
156
+ } else if (action === 'scroll') {
157
+ await page.mouse.wheel(0, Number(args.value) || 600);
158
+ label = '滚动页面';
159
+ } else if (action === 'back') {
160
+ await page.goBack({ waitUntil: 'domcontentloaded', timeout: 15000 });
161
+ label = '后退';
162
+ } else if (action === 'reload') {
163
+ await page.reload({ waitUntil: 'domcontentloaded', timeout: 20000 });
164
+ label = '刷新页面';
165
+ } else {
166
+ throw new Error(`不支持的动作:${action}`);
167
+ }
168
+ } finally {
169
+ if (element) await element.dispose().catch(() => undefined);
170
+ }
171
+
172
+ await page.waitForLoadState('networkidle', { timeout: 3000 }).catch(() => undefined);
173
+ await settle(args.settle ?? 300);
174
+ lastAction = note ? `${label}(${note})` : label;
175
+ if (args.snapshot === false) {
176
+ return { action: lastAction, url: page.url(), title: await page.title(), snapshot: '' };
177
+ }
178
+ return { action: lastAction, ...(await snapshotResult(args)) };
179
+ },
180
+
181
+ async probe(args) {
182
+ await ensurePage();
183
+ const ref = String(args.ref || '');
184
+ if (!ref) throw new Error('缺少 ref');
185
+ const result = await probeLocators(page, { describeElement }, ref);
186
+ return {
187
+ ref,
188
+ element: result.element,
189
+ recommended: result.recommended,
190
+ confidence: result.confidence,
191
+ fragile: Boolean(result.fragile),
192
+ warning: result.warning || '',
193
+ candidates: result.candidates.slice(0, 6).map((item) => ({
194
+ locator: item.locator,
195
+ source: item.source,
196
+ count: item.count,
197
+ unique: item.unique,
198
+ same: item.same,
199
+ })),
200
+ };
201
+ },
202
+
203
+ async waitFor(args) {
204
+ await ensurePage();
205
+ const text = String(args.text || '').trim();
206
+ const timeout = Math.max(1000, Math.min(60000, Number(args.timeout) || 15000));
207
+ if (text) {
208
+ await page.getByText(text, { exact: false }).first().waitFor({ state: 'visible', timeout });
209
+ lastAction = `等待出现「${text.slice(0, 40)}」`;
210
+ } else {
211
+ const ms = Math.max(0, Math.min(15000, Number(args.ms) || 500));
212
+ await settle(ms);
213
+ lastAction = `等待 ${ms}ms`;
214
+ }
215
+ return { action: lastAction, ...(await snapshotResult(args)) };
216
+ },
217
+
218
+ async screenshot(args) {
219
+ await ensurePage();
220
+ shotSeq += 1;
221
+ const raw = String(args.label || `step-${shotSeq}`);
222
+ const name = `${String(shotSeq).padStart(2, '0')}-${raw
223
+ .replace(/[^\w.-]+/g, '-')
224
+ .replace(/^-+|-+$/g, '')
225
+ .slice(0, 40)}.png`;
226
+ const abs = path.join(shotDir, name);
227
+ await page.screenshot({ path: abs, fullPage: Boolean(args.fullPage) });
228
+ return { file: name, bytes: fs.statSync(abs).size };
229
+ },
230
+
231
+ async console() {
232
+ return { messages: consoleLog.slice(-40) };
233
+ },
234
+
235
+ async network() {
236
+ return { requests: networkLog.slice(-40) };
237
+ },
238
+
239
+ async state() {
240
+ await ensurePage();
241
+ return { url: page.url(), title: await page.title(), lastAction };
242
+ },
243
+
244
+ async close() {
245
+ return { closed: true };
246
+ },
247
+ };
248
+
249
+ async function start() {
250
+ const loaded = loadPlaywright();
251
+ if (!loaded) {
252
+ throw new Error(
253
+ '没有在被挂载项目里找到 playwright / @playwright/test,请先在该项目安装依赖(npm i -D @playwright/test)',
254
+ );
255
+ }
256
+ const { chromium } = loaded.mod;
257
+ browser = await chromium.launch({ headless: !config.headed, slowMo });
258
+ // 用户手动关掉浏览器窗口(或进程崩了)时,主进程必须知道:
259
+ // 否则这边继续等命令、模型那边一路重试,最后只能看到一串
260
+ // 「Target page, context or browser has been closed」。
261
+ browser.on('disconnected', () => {
262
+ if (closing) return;
263
+ closing = true;
264
+ try {
265
+ process.stdout.write(`${JSON.stringify({ type: 'closed', reason: 'browser-closed' })}\n`);
266
+ } catch {
267
+ // 管道已断就算了
268
+ }
269
+ // 给主进程一点时间读到最后一行,然后退出;不留在后台当僵尸
270
+ setTimeout(() => process.exit(0), 50);
271
+ });
272
+ const contextOptions = { viewport: { width: 1440, height: 900 } };
273
+ if (config.baseURL) contextOptions.baseURL = String(config.baseURL);
274
+ if (storageState && fs.existsSync(storageState)) contextOptions.storageState = storageState;
275
+ context = await browser.newContext(contextOptions);
276
+ page = await context.newPage();
277
+ page.setDefaultTimeout(15000);
278
+ // 文档编号随导航递增:旧 ref 在刷新后一定失效,而不是误指到别的元素
279
+ await page.addInitScript(() => {
280
+ try {
281
+ const next = Number(window.sessionStorage.getItem('__lantern_doc') || '0') + 1;
282
+ window.sessionStorage.setItem('__lantern_doc', String(next));
283
+ window.__lanternRefPrefix = `d${next}-`;
284
+ } catch {
285
+ window.__lanternRefPrefix = `d${Date.now().toString(36)}-`;
286
+ }
287
+ });
288
+
289
+ page.on('console', (message) => {
290
+ if (message.type() === 'error' || message.type() === 'warning') {
291
+ remember(consoleLog, { type: message.type(), text: message.text().slice(0, 500) });
292
+ }
293
+ });
294
+ page.on('pageerror', (error) => {
295
+ remember(consoleLog, { type: 'pageerror', text: String(error).slice(0, 500) });
296
+ });
297
+ page.on('response', (response) => {
298
+ if (response.status() >= 400) {
299
+ remember(networkLog, {
300
+ status: response.status(),
301
+ url: response.url().slice(0, 300),
302
+ method: response.request().method(),
303
+ });
304
+ }
305
+ });
306
+ page.on('requestfailed', (request) => {
307
+ remember(networkLog, {
308
+ status: 0,
309
+ url: request.url().slice(0, 300),
310
+ method: request.method(),
311
+ failure: request.failure()?.errorText ?? 'failed',
312
+ });
313
+ });
314
+
315
+ process.stdout.write(`${JSON.stringify({ type: 'ready', playwright: loaded.name })}\n`);
316
+ }
317
+
318
+ async function shutdown() {
319
+ closing = true;
320
+ try {
321
+ await context?.close();
322
+ } catch {
323
+ // ignore
324
+ }
325
+ try {
326
+ await browser?.close();
327
+ } catch {
328
+ // ignore
329
+ }
330
+ process.exit(0);
331
+ }
332
+
333
+ process.on('SIGTERM', () => void shutdown());
334
+ process.on('SIGINT', () => void shutdown());
335
+ process.stdin.on('close', () => void shutdown());
336
+
337
+ const rl = readline.createInterface({ input: process.stdin });
338
+ rl.on('line', (line) => {
339
+ const text = line.trim();
340
+ if (!text) return;
341
+ let message;
342
+ try {
343
+ message = JSON.parse(text);
344
+ } catch {
345
+ return;
346
+ }
347
+ const { id, cmd, args } = message || {};
348
+ if (!id) return;
349
+ const handler = handlers[cmd];
350
+ if (!handler) {
351
+ process.stdout.write(
352
+ `${JSON.stringify({ id, ok: false, error: `未知命令:${String(cmd)}` })}\n`,
353
+ );
354
+ return;
355
+ }
356
+ Promise.resolve()
357
+ .then(() => handler(args || {}))
358
+ .then((result) => {
359
+ process.stdout.write(`${JSON.stringify({ id, ok: true, result })}\n`);
360
+ if (cmd === 'close') void shutdown();
361
+ })
362
+ .catch((err) => {
363
+ process.stdout.write(`${JSON.stringify({ id, ok: false, error: describeError(err) })}\n`);
364
+ });
365
+ });
366
+
367
+ start().catch((err) => {
368
+ process.stdout.write(`${JSON.stringify({ type: 'fatal', error: describeError(err) })}\n`);
369
+ setTimeout(() => process.exit(1), 50);
370
+ });