gz-laya-pilot 0.1.0 → 0.1.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 (95) hide show
  1. package/NOTICE.md +20 -2
  2. package/README.md +54 -2
  3. package/dist/agent/bridge.d.ts +21 -0
  4. package/dist/agent/bridge.js +158 -0
  5. package/dist/agent/bridge.js.map +1 -0
  6. package/dist/agent/report.d.ts +54 -0
  7. package/dist/agent/report.js +100 -0
  8. package/dist/agent/report.js.map +1 -0
  9. package/dist/agent/run.d.ts +19 -0
  10. package/dist/agent/run.js +121 -0
  11. package/dist/agent/run.js.map +1 -0
  12. package/dist/agent/schema.d.ts +42 -0
  13. package/dist/agent/schema.js +9 -0
  14. package/dist/agent/schema.js.map +1 -0
  15. package/dist/agent/worker.d.ts +1 -0
  16. package/dist/agent/worker.js +102 -0
  17. package/dist/agent/worker.js.map +1 -0
  18. package/dist/cli.d.ts +2 -0
  19. package/dist/cli.js +7 -0
  20. package/dist/cli.js.map +1 -0
  21. package/dist/index.d.ts +3 -0
  22. package/dist/index.js +2 -0
  23. package/dist/index.js.map +1 -1
  24. package/package.json +14 -6
  25. package/src/agent/bridge.ts +180 -0
  26. package/src/agent/report.ts +139 -0
  27. package/src/agent/run.ts +136 -0
  28. package/src/agent/schema.ts +38 -0
  29. package/src/agent/worker.ts +114 -0
  30. package/src/cli.ts +5 -0
  31. package/src/index.ts +3 -0
  32. package/vendor/.gitattributes +5 -0
  33. package/vendor/UPSTREAM.json +168 -0
  34. package/vendor/laya-pilot/LICENSE +21 -0
  35. package/vendor/laya-pilot/README.en.md +116 -0
  36. package/vendor/laya-pilot/README.md +116 -0
  37. package/vendor/laya-pilot/ROADMAP.md +21 -0
  38. package/vendor/laya-pilot/config.example.json +14 -0
  39. package/vendor/laya-pilot/docs/architecture.md +21 -0
  40. package/vendor/laya-pilot/docs/browser-use-evaluation.md +32 -0
  41. package/vendor/laya-pilot/docs/demo.png +0 -0
  42. package/vendor/laya-pilot/docs/local-runtime.md +88 -0
  43. package/vendor/laya-pilot/docs/pr1-selection.md +33 -0
  44. package/vendor/laya-pilot/docs/retry-policy.md +14 -0
  45. package/vendor/laya-pilot/examples/demo-cases.xlsx +0 -0
  46. package/vendor/laya-pilot/examples/demo-server.mjs +19 -0
  47. package/vendor/laya-pilot/examples/demo.html +733 -0
  48. package/vendor/laya-pilot/lib/auth-state.mjs +141 -0
  49. package/vendor/laya-pilot/lib/browser-provider.mjs +43 -0
  50. package/vendor/laya-pilot/lib/diagnostics.mjs +210 -0
  51. package/vendor/laya-pilot/lib/discovery.mjs +474 -0
  52. package/vendor/laya-pilot/lib/dom.mjs +539 -0
  53. package/vendor/laya-pilot/lib/engine.mjs +879 -0
  54. package/vendor/laya-pilot/lib/form.mjs +377 -0
  55. package/vendor/laya-pilot/lib/language.mjs +273 -0
  56. package/vendor/laya-pilot/lib/model.mjs +271 -0
  57. package/vendor/laya-pilot/lib/page-capabilities.mjs +356 -0
  58. package/vendor/laya-pilot/lib/page-exploration.mjs +372 -0
  59. package/vendor/laya-pilot/lib/page-session.mjs +69 -0
  60. package/vendor/laya-pilot/lib/pending-writes.mjs +50 -0
  61. package/vendor/laya-pilot/lib/planner.mjs +127 -0
  62. package/vendor/laya-pilot/lib/project-config.mjs +95 -0
  63. package/vendor/laya-pilot/lib/readiness.mjs +179 -0
  64. package/vendor/laya-pilot/lib/related-records.mjs +328 -0
  65. package/vendor/laya-pilot/lib/replay-model.mjs +44 -0
  66. package/vendor/laya-pilot/lib/run-state.mjs +133 -0
  67. package/vendor/laya-pilot/lib/test-data.mjs +128 -0
  68. package/vendor/laya-pilot/lib/workflow-policy.mjs +68 -0
  69. package/vendor/laya-pilot/lib/workflow.mjs +2321 -0
  70. package/vendor/laya-pilot/lib/workflow_excel.py +462 -0
  71. package/vendor/laya-pilot/requirements-local.txt +2 -0
  72. package/vendor/laya-pilot/requirements.txt +1 -0
  73. package/vendor/laya-pilot/runner.mjs +452 -0
  74. package/vendor/laya-pilot/tests/api.test.mjs +98 -0
  75. package/vendor/laya-pilot/tests/browser/runtime.test.mjs +847 -0
  76. package/vendor/laya-pilot/tests/config.test.mjs +109 -0
  77. package/vendor/laya-pilot/tests/diagnostics.test.mjs +91 -0
  78. package/vendor/laya-pilot/tests/discovery.test.mjs +76 -0
  79. package/vendor/laya-pilot/tests/fixtures/local-model/laya.py +28 -0
  80. package/vendor/laya-pilot/tests/fixtures/local-model/torch.py +5 -0
  81. package/vendor/laya-pilot/tests/guards.test.mjs +43 -0
  82. package/vendor/laya-pilot/tests/language.test.mjs +39 -0
  83. package/vendor/laya-pilot/tests/planner.test.mjs +129 -0
  84. package/vendor/laya-pilot/tests/readiness.test.mjs +118 -0
  85. package/vendor/laya-pilot/tests/real-model.smoke.mjs +74 -0
  86. package/vendor/laya-pilot/tests/replay-model.test.mjs +90 -0
  87. package/vendor/laya-pilot/tests/retries.test.mjs +270 -0
  88. package/vendor/laya-pilot/tests/run-state.test.mjs +162 -0
  89. package/vendor/laya-pilot/tests/selected-pr1.test.mjs +309 -0
  90. package/vendor/laya-pilot/tests/test-data.test.mjs +83 -0
  91. package/vendor/laya-pilot/tests/test_workflow_excel.py +162 -0
  92. package/vendor/laya-pilot/tests/worker_test.py +33 -0
  93. package/vendor/laya-pilot/tests/workflow.test.mjs +98 -0
  94. package/vendor/laya-pilot/worker.py +135 -0
  95. package/vendor/patches/0001-native-field-recipes.patch +3009 -0
@@ -0,0 +1,3009 @@
1
+ --- a/lib/workflow-policy.mjs
2
+ +++ b/lib/workflow-policy.mjs
3
+ @@ -1,3 +1,5 @@
4
+ +import { validateDiscovery } from './discovery.mjs';
5
+ +
6
+ export const OPERATIONS = [
7
+ 'tabs',
8
+ 'tab-switch',
9
+ @@ -8,6 +10,7 @@
10
+ 'create',
11
+ 'search',
12
+ 'view',
13
+ + 'related-records',
14
+ 'edit',
15
+ 'delete',
16
+ 'discover',
17
+ @@ -30,7 +33,7 @@
18
+ if (config.readOnly && operations.some((op) => !READ_OPERATIONS.includes(op)))
19
+ throw Error('--read-only 只允许 tabs,tab-switch,table,filters');
20
+ const allowed = new Set(operations);
21
+ - for (const op of ['search', 'view', 'edit', 'delete']) {
22
+ + for (const op of ['search', 'view', 'related-records', 'edit', 'delete']) {
23
+ if (allowed.has(op) && !allowed.has('create'))
24
+ throw Error(`${op} 依赖本轮 create,请同时选择 create;只读检查使用 table,filters`);
25
+ }
26
+ @@ -43,6 +46,10 @@
27
+ if (!allowed.has(c.operation)) throw Error(`回放用例 ${c.id} 超出 --operations 范围`);
28
+ if (config.readOnly) {
29
+ for (const step of c.steps) {
30
+ + if (c.operation === 'filters' && step.kind === 'assert-discovery') {
31
+ + validateDiscovery(step, { readOnly: true });
32
+ + continue;
33
+ + }
34
+ const assertion = [
35
+ 'assert-control',
36
+ 'assert-selected',
37
+ --- a/lib/browser-provider.mjs
38
+ +++ b/lib/browser-provider.mjs
39
+ @@ -1,19 +1,24 @@
40
+ import { loadAuthState, restoreSessionStorage } from './auth-state.mjs';
41
+ // Keep the browser boundary in one place. A future driver must provide the
42
+ // page/context methods used by the engines before it can be selected here.
43
+ -export async function openBrowser(config) {
44
+ +export async function launchBrowser(config) {
45
+ if (config.browserProvider !== 'playwright') {
46
+ throw new Error(
47
+ `Unsupported browser provider: ${config.browserProvider}. Currently supported: playwright`,
48
+ );
49
+ }
50
+ - const auth = await loadAuthState(config);
51
+ const { chromium } = await import('playwright');
52
+ const options = { headless: config.headless };
53
+ if (config.browserChannel) options.channel = config.browserChannel;
54
+ - const browser = await chromium.launch(options);
55
+ + return chromium.launch(options);
56
+ +}
57
+ +
58
+ +export async function openBrowser(config, { authState, browser: sharedBrowser } = {}) {
59
+ + const auth = authState ?? (await loadAuthState(config));
60
+ + const browser = sharedBrowser ?? (await launchBrowser(config));
61
+ + let context;
62
+ try {
63
+ - const context = await browser.newContext({
64
+ + context = await browser.newContext({
65
+ ...(auth ? { storageState: auth.storageState } : {}),
66
+ viewport: { width: 1500, height: 980 },
67
+ locale: 'zh-CN',
68
+ @@ -23,9 +28,16 @@
69
+ const page = await context.newPage();
70
+ page.setDefaultTimeout(9000);
71
+ page.setDefaultNavigationTimeout(config.pageTimeout || 18000);
72
+ - return { browser, context, page, authRestored: !!auth };
73
+ + return {
74
+ + browser,
75
+ + context,
76
+ + page,
77
+ + authRestored: !!auth,
78
+ + close: () => (sharedBrowser ? context.close() : browser.close()),
79
+ + };
80
+ } catch (error) {
81
+ - await browser.close();
82
+ + if (sharedBrowser) await context?.close();
83
+ + else await browser.close();
84
+ throw error;
85
+ }
86
+ }
87
+ --- a/lib/test-data.mjs
88
+ +++ b/lib/test-data.mjs
89
+ @@ -58,8 +58,12 @@
90
+
91
+ // Laya selects a data recipe from observed field semantics. The executor creates
92
+ // the value, so record identifiers remain unique and replay can bind fresh data.
93
+ -export async function chooseFieldValue(laya, field, { name = '${recordName}', index = 0 } = {}) {
94
+ - const criteria = {
95
+ +export async function chooseFieldValue(
96
+ + laya,
97
+ + field,
98
+ + { name = '${recordName}', index = 0, identity = false } = {},
99
+ +) {
100
+ + const recipes = {
101
+ 账号: '填写登录账号、登录账户或 account 标识',
102
+ 名称: '填写名称、姓名、用户名或标题',
103
+ 邮箱: '填写电子邮箱 email 地址',
104
+ @@ -69,8 +73,23 @@
105
+ 文本: '填写普通文本、描述或备注',
106
+ 停止: '字段用途不明确,无法生成测试值',
107
+ };
108
+ + // Native input types are observed constraints, not business-name heuristics.
109
+ + // Keep a real model decision (including refusal), but exclude incompatible recipes.
110
+ + const typedRecipe = { number: '数值', email: '邮箱' }[field.type];
111
+ + const criteria = typedRecipe
112
+ + ? { [typedRecipe]: recipes[typedRecipe], 停止: recipes.停止 }
113
+ + : recipes;
114
+ + if (field.type === 'number') {
115
+ + // Classify the observed input contract instead of inferring a business
116
+ + // meaning from its label. This also applies to unfamiliar/localized labels.
117
+ + criteria.数值 = '此字段是数字输入框,需要填写满足页面最小值和最大值约束的数字';
118
+ + criteria.停止 = '页面证据不足,不能判断字段需要填写哪类数据';
119
+ + }
120
+ const decision = await laya.choose(
121
+ - `填写「${field.label || field.placeholder}」${field.placeholder ? ',提示:' + field.placeholder : ''}${field.type && !['input', 'text', 'textarea'].includes(field.type) ? ',输入类型:' + field.type : ''}`,
122
+ + // The caller has already located the name/title field. Length hints are
123
+ + // validation constraints, not a competing field purpose. Retain them in
124
+ + // evidence and browser validation, with all semantic recipes/refusal intact.
125
+ + `填写「${field.label || field.placeholder}」${field.placeholder && !identity ? ',提示:' + field.placeholder : ''}${field.type && !['input', 'text', 'textarea'].includes(field.type) ? ',输入类型:' + field.type : ''}`,
126
+ criteria,
127
+ { phase: 'form-field', field: field.label, input: { ...field, value: undefined } },
128
+ );
129
+ --- a/lib/workflow.mjs
130
+ +++ b/lib/workflow.mjs
131
+ @@ -5,12 +5,22 @@
132
+ import { randomBytes } from 'node:crypto';
133
+ import { spawn } from 'node:child_process';
134
+ import { Laya, beginModelWarmup, waitModelWarmup } from './model.mjs';
135
+ -import { openBrowser } from './browser-provider.mjs';
136
+ +import { openBrowser, launchBrowser } from './browser-provider.mjs';
137
+ import { matchReplayTarget } from './replay-model.mjs';
138
+ +import { executeRelatedRecords, validateRelatedStep } from './related-records.mjs';
139
+ import { observe, discoverRowLabels, settle } from './dom.mjs';
140
+ import { ensureAuthentication, saveAuthState } from './auth-state.mjs';
141
+ import { RunJournal, watchInterruption, resultExitCode, writePrivateJson } from './run-state.mjs';
142
+ import { workflowPolicy, enforceReplayPolicy } from './workflow-policy.mjs';
143
+ +import {
144
+ + openOwnedRecord,
145
+ + assertRecordDetail,
146
+ + assertSearchResult,
147
+ + assertTabPanel,
148
+ + inspectDisclosure,
149
+ + observeCoverage,
150
+ + exploreDetailTabs,
151
+ +} from './page-exploration.mjs';
152
+ import {
153
+ accountField,
154
+ expiryField,
155
+ @@ -25,6 +35,26 @@
156
+ observeFormEvidence,
157
+ } from './discovery.mjs';
158
+ import { waitForReady } from './readiness.mjs';
159
+ +import {
160
+ + pageIdentity,
161
+ + assertPageIdentity,
162
+ + captureVerificationAuth,
163
+ + activity,
164
+ + waitForVisibleStep,
165
+ +} from './page-session.mjs';
166
+ +import {
167
+ + activateEditor,
168
+ + formRoot,
169
+ + COLLECTION,
170
+ + recordRows,
171
+ + sameRegion,
172
+ + expandCollection,
173
+ + expandTree,
174
+ + validateTreeTarget,
175
+ + revealTreeActions,
176
+ + captureTreePath,
177
+ + verifyInput,
178
+ +} from './page-capabilities.mjs';
179
+ import {
180
+ BrowserDiagnostics,
181
+ diagnoseFailure,
182
+ @@ -70,8 +100,40 @@
183
+ .replace(/-+/g, '-')
184
+ .slice(0, 85);
185
+ const ownName = () => `LayaAuto_${Date.now().toString(36)}_${randomBytes(3).toString('hex')}`;
186
+ -const controlInfo = (c) => ({ name: c.name, role: c.role, scope: c.scope || 'page' });
187
+ +const controlInfo = (c) => ({
188
+ + name: c.name,
189
+ + role: c.role,
190
+ + scope: c.scope || 'page',
191
+ + ...(c.region ? { region: c.region } : {}),
192
+ + ...(c.treePath ? { treePath: c.treePath } : {}),
193
+ +});
194
+ const message = (e) => safeText(e?.message || String(e), 1200);
195
+ +
196
+ +function validatePersistenceQuery(query) {
197
+ + const [fill, search] = Array.isArray(query) ? query : [];
198
+ + if (
199
+ + !Array.isArray(query) ||
200
+ + query.length < 1 ||
201
+ + query.length > 2 ||
202
+ + fill?.kind !== 'fill' ||
203
+ + !['textbox', 'spinbutton'].includes(fill.target?.role) ||
204
+ + typeof fill.target.name !== 'string' ||
205
+ + !fill.target.name ||
206
+ + fill.target.name.length > 150 ||
207
+ + fill.target.scope !== 'page' ||
208
+ + typeof fill.value !== 'string' ||
209
+ + fill.value.length > 200 ||
210
+ + (search &&
211
+ + (search.kind !== 'click' ||
212
+ + search.purpose !== 'search' ||
213
+ + !['button', 'link'].includes(search.target?.role) ||
214
+ + search.target.scope !== 'page' ||
215
+ + typeof search.target.name !== 'string' ||
216
+ + search.target.name.length > 150 ||
217
+ + !actions.search.test(search.target.name)))
218
+ + )
219
+ + throw Error('持久化断言缺少受限的语义查询步骤,请重新生成 Excel');
220
+ +}
221
+
222
+ export function validateWorkflow(file) {
223
+ if (file?.schemaVersion !== 1 || !Array.isArray(file.cases) || !file.cases.length)
224
+ @@ -89,6 +151,8 @@
225
+ 'assert-input-invalid',
226
+ 'assert-row',
227
+ 'assert-absent',
228
+ + 'assert-persisted-row',
229
+ + 'assert-persisted-absent',
230
+ 'assert-text',
231
+ 'assert-control',
232
+ 'assert-selected',
233
+ @@ -96,6 +160,13 @@
234
+ 'assert-disabled',
235
+ 'reload',
236
+ 'assert-discovery',
237
+ + 'expand-tree',
238
+ + 'open-owned-record',
239
+ + 'assert-record-detail',
240
+ + 'assert-tab-panel',
241
+ + 'assert-query-result',
242
+ + 'assert-disclosure',
243
+ + 'assert-related-records',
244
+ ]);
245
+ for (const c of file.cases) {
246
+ if (
247
+ @@ -109,6 +180,7 @@
248
+ 'create',
249
+ 'search',
250
+ 'view',
251
+ + 'related-records',
252
+ 'edit',
253
+ 'delete',
254
+ 'discover',
255
+ @@ -118,13 +190,63 @@
256
+ )
257
+ throw Error('用例包含不支持的操作:' + c.id);
258
+ for (const step of c.steps) {
259
+ - if (c.operation === 'discover') {
260
+ + if (
261
+ + c.operation === 'discover' ||
262
+ + (c.operation === 'filters' && step.kind === 'assert-discovery')
263
+ + ) {
264
+ if (step.kind !== 'assert-discovery') throw Error('补充测试只允许受限的验证步骤');
265
+ - validateDiscovery(step);
266
+ + validateDiscovery(step, { readOnly: c.operation === 'filters' });
267
+ continue;
268
+ }
269
+ if (step.kind === 'assert-discovery') throw Error('补充测试步骤必须属于 discover');
270
+ if (!allowed.has(step.kind)) throw Error('用例包含不支持的步骤:' + step.kind);
271
+ + if (step.kind === 'assert-related-records') {
272
+ + if (c.operation !== 'related-records')
273
+ + throw Error('关联步骤必须属于 related-records 写操作');
274
+ + validateRelatedStep(step);
275
+ + validatePersistenceQuery(step.query);
276
+ + continue;
277
+ + }
278
+ + if (c.operation === 'related-records') throw Error('关联用例仅允许受限的关联事务');
279
+ + if (
280
+ + ['open-owned-record', 'assert-record-detail'].includes(step.kind) &&
281
+ + (c.operation !== 'view' ||
282
+ + !['${recordName}', '${updatedName}'].includes(step.value))
283
+ + )
284
+ + throw Error('详情步骤必须引用本轮创建的记录');
285
+ + if (
286
+ + step.kind === 'assert-query-result' &&
287
+ + (c.operation !== 'search' || step.value !== '${recordName}')
288
+ + )
289
+ + throw Error('查询断言必须引用本轮记录');
290
+ + if (
291
+ + step.kind === 'assert-disclosure' &&
292
+ + (c.operation !== 'view' ||
293
+ + step.target?.role !== 'button' ||
294
+ + [step.target?.name, step.target?.tab].some(
295
+ + (value) => typeof value !== 'string' || !value || value.length > 150,
296
+ + ))
297
+ + )
298
+ + throw Error('展开检查必须指定详情页签内的唯一语义按钮');
299
+ + if (
300
+ + step.kind === 'assert-tab-panel' &&
301
+ + (c.operation !== 'view' ||
302
+ + step.target?.role !== 'tab' ||
303
+ + typeof step.target.name !== 'string' ||
304
+ + !step.target.name ||
305
+ + step.target.name.length > 150)
306
+ + )
307
+ + throw Error('详情页签断言缺少明确入口');
308
+ + if (
309
+ + ['assert-persisted-row', 'assert-persisted-absent'].includes(step.kind) &&
310
+ + (typeof step.value !== 'string' || !step.value || step.value.length > 200)
311
+ + )
312
+ + throw Error('持久化断言缺少明确的记录值');
313
+ + if (['assert-persisted-row', 'assert-persisted-absent'].includes(step.kind))
314
+ + validatePersistenceQuery(step.query);
315
+ + if (step.kind === 'expand-tree') validateTreeTarget(step.target);
316
+ + if (step.target?.treePath)
317
+ + validateTreeTarget(step.target.treePath, { allowRoot: true });
318
+ if (step.kind === 'assert-disabled' && (!step.target?.name || !step.target?.role))
319
+ throw Error('禁用态断言缺少控件名称和角色');
320
+ if (['click', 'fill'].includes(step.kind) && (!step.target?.name || !step.target?.role))
321
+ @@ -260,7 +382,24 @@
322
+ 'replayStep',
323
+ ]) {
324
+ const operation = this[name].bind(this);
325
+ - this[name] = (...args) => this.withAttempts(name, () => operation(...args));
326
+ + this[name] = (...args) =>
327
+ + this.withAttempts(name, async () => {
328
+ + const result = await operation(...args);
329
+ + if (
330
+ + [
331
+ + 'click',
332
+ + 'clickCreate',
333
+ + 'fill',
334
+ + 'formFill',
335
+ + 'formFillRequired',
336
+ + 'formSelect',
337
+ + 'formDate',
338
+ + 'clickTab',
339
+ + ].includes(name)
340
+ + )
341
+ + await waitForVisibleStep(this);
342
+ + return result;
343
+ + });
344
+ }
345
+ }
346
+ checkInterrupted() {
347
+ @@ -283,9 +422,7 @@
348
+ this.journal?.completeCase(c, this.runtime());
349
+ }
350
+ ownedRows(name) {
351
+ - return this.page
352
+ - .locator('table tbody tr:visible,[role="rowgroup"] [role="row"]:visible')
353
+ - .filter({ has: this.page.getByText(name, { exact: true }) });
354
+ + return recordRows(this.page, name);
355
+ }
356
+ async ownedActionRows(name) {
357
+ const row = this.ownedRows(name);
358
+ @@ -330,8 +467,14 @@
359
+ .waitFor({ state: 'visible', timeout })
360
+ .catch(() => {});
361
+ }
362
+ + async editorPresent() {
363
+ + return (await formRoot(this.page).count()) > 0;
364
+ + }
365
+ + async waitForEditor() {
366
+ + await activateEditor(this.page, this.config.assertTimeout || 4000);
367
+ + }
368
+ async waitModalClosed(timeout = 8000) {
369
+ - await this.page.locator(MODAL_SEL).last().waitFor({ state: 'hidden', timeout });
370
+ + await formRoot(this.page).waitFor({ state: 'hidden', timeout });
371
+ }
372
+ async safeClick(locator) {
373
+ await locator.click({ timeout: 4000 });
374
+ @@ -341,7 +484,7 @@
375
+ if (
376
+ step.purpose === 'save' &&
377
+ /^(确定|确认|confirm|ok)$/i.test(step.target.name) &&
378
+ - !(await this.modalPresent())
379
+ + !(await this.editorPresent())
380
+ )
381
+ throw Error('表单确认提交前必须有当前可见表单');
382
+ // Trial checks actionability without dispatching a click. Once dispatched,
383
+ @@ -368,7 +511,7 @@
384
+ const errors = await formErrors(this.page);
385
+ return errors.open && errors.labels.length > 0;
386
+ }
387
+ - if (await this.modalPresent()) return false;
388
+ + if (await this.editorPresent()) return false;
389
+ const deleting = ['delete', 'confirm'].includes(step.purpose) && op === 'delete';
390
+ const name =
391
+ op === 'create'
392
+ @@ -432,6 +575,10 @@
393
+ this.case.attempts ??= [];
394
+ this.case.attempts.push(entry);
395
+ }
396
+ + // A failed restoration/compound transaction has already
397
+ + // established an unsafe next state. Do not replace its
398
+ + // business failure with generic click retry verification.
399
+ + if (this.restorationFailure) throw error;
400
+ if (attempt === 3)
401
+ throw Error(`${label} 尝试3次未成功:${entry.reason}`, { cause: error });
402
+ await settle(this.page, 250).catch(() => {});
403
+ @@ -442,26 +589,36 @@
404
+ }
405
+ }
406
+ async clickCreate() {
407
+ - // withAttempts owns the three-attempt budget; retain tried names between observations.
408
+ + // withAttempts owns the three-attempt budget; retain semantic targets, not live refs.
409
+ const tried = this.attemptState ? (this.attemptState.createTried ??= new Set()) : new Set();
410
+ - if (await this.modalPresent()) {
411
+ + if (await this.editorPresent()) {
412
+ if (this.attemptState?.createClicked) return;
413
+ if (!(await this.dismissModal())) throw Error('旧弹窗未关闭,不能选择新的创建入口');
414
+ }
415
+ let snap = await this.snapshot();
416
+ let candidates = snap.controls.filter((c) => isAction(c) && actions.create.test(c.name));
417
+ + if (!candidates.length) {
418
+ + await expandCollection(this);
419
+ + await revealTreeActions(this.page);
420
+ + snap = await this.snapshot();
421
+ + candidates = snap.controls.filter((c) => isAction(c) && actions.create.test(c.name));
422
+ + }
423
+ if (!candidates.length) {
424
+ await this.click('area');
425
+ snap = await this.snapshot();
426
+ candidates = snap.controls.filter((c) => isAction(c) && actions.create.test(c.name));
427
+ }
428
+ - const c = candidates.find((c) => !tried.has(c.name)) || candidates[0];
429
+ - if (!c) throw Error('页面上没有创建类控件');
430
+ - const locator = snap.frames[c.frame].locator(`[${LIVE_REF}="${c.ref}"]`);
431
+ - if ((await locator.count()) !== 1 || !(await locator.isVisible()))
432
+ - throw Error('创建入口已变化');
433
+ - tried.add(c.name);
434
+ - await this.safeClick(locator, c.name);
435
+ + const entryKey = (c) => JSON.stringify([c.role, c.name, c.region, c.context]);
436
+ + const untried = candidates.filter((c) => !tried.has(entryKey(c)));
437
+ + const { control: c, locator } = await this.chooseFromSnapshot(
438
+ + snap,
439
+ + untried.length ? untried : candidates,
440
+ + '创建独立记录',
441
+ + );
442
+ + tried.add(entryKey(c));
443
+ + c.treePath = await captureTreePath(this.page, locator);
444
+ + const bound = c.treePath ? await revealTreeActions(this.page, c) : locator;
445
+ + await this.safeClick(bound, c.name);
446
+ if (this.attemptState) this.attemptState.createClicked = true;
447
+ this.record({
448
+ kind: 'click',
449
+ @@ -469,20 +626,17 @@
450
+ purpose: 'create',
451
+ });
452
+ await settle(this.page, 150);
453
+ - await this.waitForModal(1800);
454
+ - if (!(await this.modalPresent())) throw Error('创建入口「' + c.name + '」未打开表单弹窗');
455
+ + await this.waitForEditor();
456
+ await observeFormEvidence(this, c);
457
+ }
458
+ async dismissModal() {
459
+ await this.page.keyboard.press('Escape').catch(() => {});
460
+ - if (!(await this.modalPresent())) return true;
461
+ - const close = this.page
462
+ - .locator(MODAL_SEL)
463
+ - .last()
464
+ + if (!(await this.editorPresent())) return true;
465
+ + const close = formRoot(this.page)
466
+ .locator('button:visible')
467
+ .filter({ hasText: /^(取消|关闭|close|cancel)$/i });
468
+ if ((await close.count()) === 1) await close.click({ timeout: 1500 });
469
+ - return !(await this.modalPresent());
470
+ + return !(await this.editorPresent());
471
+ }
472
+ async chooseFromSnapshot(snap, candidates, purpose) {
473
+ if (!candidates.length) throw Error('页面上没有可操作的' + purpose + '控件');
474
+ @@ -536,13 +690,17 @@
475
+ throw Error('决策后页面控件已变化:' + purpose);
476
+ return { control, locator };
477
+ }
478
+ - async action(op, { rowName, optional = false } = {}) {
479
+ - if (op === 'save' && !(await this.modalPresent()))
480
+ + async action(op, { rowName, optional = false, region, frame } = {}) {
481
+ + if (op === 'save' && !(await this.editorPresent()))
482
+ throw Error('保存表单前必须有当前可见表单');
483
+ let snap = await this.snapshot();
484
+ let owned;
485
+ if (rowName) {
486
+ owned = await this.ownedActionRows(rowName);
487
+ + if ((await this.ownedRows(rowName).getAttribute('role')) === 'treeitem') {
488
+ + await owned.locator('button,[role="button"]').first().hover();
489
+ + snap = await this.snapshot();
490
+ + }
491
+ const key = await this.ownedRows(rowName).getAttribute('data-row-key');
492
+ if (key) snap = await discoverRowLabels(this.page, key);
493
+ }
494
+ @@ -552,13 +710,20 @@
495
+ (op === 'area' ? c.role === 'tab' && !c.disabled : isAction(c)) &&
496
+ actions[op].test(c.name) &&
497
+ (op !== 'confirm' || c.role === 'button') &&
498
+ + (region === undefined || sameRegion(c, { region, frame })) &&
499
+ (!rowName || c.context.includes(rowName)),
500
+ );
501
+ const inOwnedRow = async (items) => {
502
+ if (!owned) return items;
503
+ const scoped = [];
504
+ - for (const c of items)
505
+ - if (await owned.locator(`[${LIVE_REF}="${c.ref}"]`).count()) scoped.push(c);
506
+ + for (const c of items) {
507
+ + // A delayed list render can replace nodes after observation. An
508
+ + // expired live ref is not proof that an optional action is absent.
509
+ + const selector = `[${LIVE_REF}="${c.ref}"]`;
510
+ + if (!(await snap.frames[c.frame].locator(selector).count()))
511
+ + throw Error('页面观察后控件已更新,需要重新定位:' + c.name);
512
+ + if (await owned.locator(selector).count()) scoped.push(c);
513
+ + }
514
+ return scoped;
515
+ };
516
+ let candidates = await inOwnedRow(matching());
517
+ @@ -652,14 +817,27 @@
518
+ await this.dispatchClick(found.locator, found.step);
519
+ this.record(found.step);
520
+ await settle(this.page, 120);
521
+ + if (op === 'edit' || op === 'create') await this.waitForEditor();
522
+ return found.step;
523
+ }
524
+ - async field(purpose, { name } = {}) {
525
+ + async field(purpose, { name, search = false } = {}) {
526
+ const snap = await this.snapshot();
527
+ const fields = snap.controls.filter(
528
+ - (c) => ['textbox', 'spinbutton'].includes(c.role) && !c.disabled && !c.readonly,
529
+ + (c) =>
530
+ + ['textbox', 'spinbutton'].includes(c.role) &&
531
+ + !c.disabled &&
532
+ + !c.readonly &&
533
+ + (!search ||
534
+ + (!c.regionAmbiguous && !['banner', 'navigation'].includes(c.region?.role))),
535
+ );
536
+ - const matches = fields.filter((c) => (name ? c.name === name : nameField.test(c.name)));
537
+ + const matches = fields.filter((c) =>
538
+ + name
539
+ + ? c.name === name
540
+ + : (search
541
+ + ? /名称|姓名|用户名|登录账号|标题|name|title|搜索|查询|关键字|search|query|filter/i
542
+ + : nameField
543
+ + ).test(c.name),
544
+ + );
545
+ return this.chooseFromSnapshot(snap, matches, purpose);
546
+ }
547
+ record(step) {
548
+ @@ -685,8 +863,7 @@
549
+ }
550
+ const actual = this.resolve(value);
551
+ await field.locator.fill(actual);
552
+ - if ((await field.locator.inputValue()) !== actual)
553
+ - throw Error('输入值没有进入' + field.control.name);
554
+ + await verifyInput(this, field.control, actual);
555
+ this.record({ kind: 'fill', target: { ...controlInfo(field.control), scope }, value });
556
+ await settle(this.page, 80);
557
+ }
558
+ @@ -922,9 +1099,10 @@
559
+ const plan = await chooseFieldValue(
560
+ this.laya,
561
+ { ...fields[0].inputs[0], label: fields[0].label },
562
+ - { name: value },
563
+ + { name: value, identity: true },
564
+ );
565
+ - if (plan.strategy !== '名称') throw Error('模型未将记录名称字段识别为名称');
566
+ + if (plan.kind !== 'fill' || plan.value !== value)
567
+ + throw Error('模型未生成可追踪的唯一记录名称');
568
+ await this.formFill(fields[0].label, 0, value);
569
+ return fields[0].label;
570
+ }
571
+ @@ -932,9 +1110,10 @@
572
+ const plan = await chooseFieldValue(
573
+ this.laya,
574
+ { label: field.control.name },
575
+ - { name: value },
576
+ + { name: value, identity: true },
577
+ );
578
+ - if (plan.strategy !== '名称') throw Error('模型未将记录名称字段识别为名称');
579
+ + if (plan.kind !== 'fill' || plan.value !== value)
580
+ + throw Error('模型未生成可追踪的唯一记录名称');
581
+ await this.fill(field, value);
582
+ return null;
583
+ }
584
+ @@ -1007,13 +1186,18 @@
585
+ return actual;
586
+ }
587
+ async row(value, present = true) {
588
+ + const lastClick = this.case?.steps.findLast((step) => step.kind === 'click');
589
+ + if (['save', 'delete', 'confirm'].includes(lastClick?.purpose))
590
+ + await this.waitModalClosed();
591
+ + await this.pendingWrites.wait(this.config.pageTimeout || 8000);
592
+ + await expandCollection(this);
593
+ const name = this.resolve(value),
594
+ rows = this.ownedRows(name);
595
+ if (present) await rows.first().waitFor({ timeout: this.config.assertTimeout });
596
+ else {
597
+ // A missing list or a loading page is not proof of deletion.
598
+ await this.page
599
+ - .locator('table:visible,[role="grid"]:visible')
600
+ + .locator(COLLECTION)
601
+ .first()
602
+ .waitFor({ state: 'visible', timeout: this.config.assertTimeout });
603
+ await rows.first().waitFor({ state: 'hidden', timeout: this.config.assertTimeout });
604
+ @@ -1024,18 +1208,27 @@
605
+ this.record({ kind: present ? 'assert-row' : 'assert-absent', value });
606
+ }
607
+ async query(value, { assert = true } = {}) {
608
+ - const search = await this.field('按名称查询独立记录');
609
+ + const search = await this.field('按名称查询独立记录', { search: true });
610
+ const byAccount = /登录账号|登录账户|account|login/i.test(search.control.name);
611
+ - await this.fill(search, byAccount ? '${recordAccount}' : value, 'page');
612
+ - const button = await this.action('search', { optional: true });
613
+ + const requested = byAccount && value ? '${recordAccount}' : value;
614
+ + if ((await search.locator.inputValue()) !== this.resolve(requested))
615
+ + await this.fill(search, requested, 'page');
616
+ + const button = await this.action('search', {
617
+ + optional: true,
618
+ + region: search.control.region || null,
619
+ + frame: search.control.frame,
620
+ + });
621
+ if (button) {
622
+ await button.locator.click();
623
+ this.record(button.step);
624
+ await settle(this.page, 180);
625
+ + await waitForVisibleStep(this);
626
+ }
627
+ if (assert) await this.row(value, true);
628
+ }
629
+ async reload() {
630
+ + if (this.identity?.host)
631
+ + throw Error('旧用例要求刷新主应用,请重新探索生成采用独立持久化校验的新用例');
632
+ const lastClick = this.case?.steps.findLast((step) => step.kind === 'click');
633
+ if (['save', 'delete', 'confirm'].includes(lastClick?.purpose))
634
+ await this.waitModalClosed();
635
+ @@ -1043,6 +1236,105 @@
636
+ await this.page.reload({ waitUntil: 'domcontentloaded' });
637
+ await waitForReady(this.page, { timeout: this.config.pageTimeout });
638
+ this.record({ kind: 'reload' });
639
+ + }
640
+ + async assertPersisted(
641
+ + value,
642
+ + present = true,
643
+ + { record = true, query, inspect, evidenceId } = {},
644
+ + ) {
645
+ + this.checkInterrupted();
646
+ + await assertPageIdentity(this.page, this.identity);
647
+ + await this.pendingWrites.wait(this.config.pageTimeout || 8000);
648
+ + activity(this, '正在独立后台会话校验数据持久化,当前主子应用保持不变');
649
+ + const config = {
650
+ + ...this.config,
651
+ + url: this.startUrl,
652
+ + headless: true,
653
+ + manualLogin: false,
654
+ + user: '',
655
+ + journal: undefined,
656
+ + };
657
+ + let session, diagnostics;
658
+ + const evidence = `evidence/${safeKey(evidenceId || this.case.id)}-persistence.png`;
659
+ + const trace = `persistence-${safeKey(evidenceId || this.case.id)}.zip`;
660
+ + const stop = () => {
661
+ + void session?.close().catch(() => {});
662
+ + };
663
+ + try {
664
+ + if (!this.verificationAuth) throw Error('缺少探索开始前的登录态快照,不能校验持久化');
665
+ + session = await openBrowser(config, {
666
+ + authState: this.verificationAuth,
667
+ + browser: this.verificationBrowser,
668
+ + });
669
+ + config.signal?.addEventListener('abort', stop, { once: true });
670
+ + this.checkInterrupted();
671
+ + diagnostics = new BrowserDiagnostics(session.context);
672
+ + diagnostics.begin(this.case.id);
673
+ + await session.context.tracing.start({ screenshots: true, snapshots: true });
674
+ + await session.page.goto(this.startUrl, { waitUntil: 'domcontentloaded' });
675
+ + await waitForReady(session.page, { timeout: config.pageTimeout });
676
+ + await ensureAuthentication(
677
+ + session.page,
678
+ + config,
679
+ + async () => {
680
+ + throw Error('独立校验会话登录态已失效');
681
+ + },
682
+ + undefined,
683
+ + true,
684
+ + );
685
+ + await assertPageIdentity(session.page, this.identity, { fresh: true });
686
+ + const reader = new Workflow(session.page, this.laya, config, this.mode, diagnostics);
687
+ + reader.identity = await pageIdentity(session.page);
688
+ + reader.variables = { ...this.variables };
689
+ + await reader.assertModuleAccess();
690
+ + if (query) {
691
+ + validatePersistenceQuery(query);
692
+ + for (const step of query) await reader.replayStep(step);
693
+ + } else {
694
+ + if (this.mode === 'execute')
695
+ + throw Error('持久化断言缺少原始查询步骤,请重新生成 Excel');
696
+ + await reader.query(value, { assert: false });
697
+ + query = reader.log.map(({ step }) => step);
698
+ + validatePersistenceQuery(query);
699
+ + }
700
+ + await reader.row(value, present);
701
+ + if (inspect) {
702
+ + reader.created = this.created;
703
+ + reader.currentName = this.currentName;
704
+ + await inspect(reader);
705
+ + }
706
+ + const events = await diagnostics.end();
707
+ + const severe = severeEvent(events);
708
+ + if (severe) throw Error('独立持久化校验发现 ' + eventLabel(severe));
709
+ + await assertPageIdentity(this.page, this.identity);
710
+ + this.journal?.event('persistence-verified', {
711
+ + caseId: this.case.id,
712
+ + present,
713
+ + evidence,
714
+ + trace,
715
+ + });
716
+ + if (record)
717
+ + this.record({
718
+ + kind: present ? 'assert-persisted-row' : 'assert-persisted-absent',
719
+ + value,
720
+ + query,
721
+ + evidence,
722
+ + trace,
723
+ + });
724
+ + return query;
725
+ + } finally {
726
+ + config.signal?.removeEventListener('abort', stop);
727
+ + if (session) {
728
+ + await session.page
729
+ + .screenshot({ path: path.join(this.config.out, evidence), timeout: 5000 })
730
+ + .catch(() => {});
731
+ + await session.context.tracing
732
+ + .stop({ path: path.join(this.config.out, trace) })
733
+ + .catch(() => {});
734
+ + await session.close();
735
+ + }
736
+ + activity(this, '');
737
+ + }
738
+ }
739
+ async assertControl(role, name, selected = false) {
740
+ const snap = await this.snapshot(),
741
+ @@ -1076,9 +1368,13 @@
742
+ );
743
+ const found = await this.chooseFromSnapshot(snap, matches, '切换到「' + name + '」Tab');
744
+ await found.locator.click();
745
+ + const target = { ...controlInfo(found.control), scope: 'page' };
746
+ + // Exact role/name is already required to be unique above. An unnamed
747
+ + // nested main is not a usable region constraint for the saved target.
748
+ + if (found.control.regionAmbiguous) delete target.region;
749
+ this.record({
750
+ kind: 'click',
751
+ - target: { ...controlInfo(found.control), scope: 'page' },
752
+ + target,
753
+ purpose: 'tab',
754
+ });
755
+ await settle(this.page, 180);
756
+ @@ -1098,7 +1394,7 @@
757
+ };
758
+ this.case = c;
759
+ this.diagnostics.begin(id);
760
+ - this.journal?.checkpoint({ activeCase: c, runtime: this.runtime() });
761
+ + this.journal?.checkpoint({ activeCase: c, runtime: this.runtime(), activity: '' });
762
+ try {
763
+ await fn();
764
+ c.status = '已验证';
765
+ @@ -1123,7 +1419,7 @@
766
+ c.reason = '页面断言通过,但本用例期间发现 ' + eventLabel(severe);
767
+ }
768
+ c.diagnosis = c.status === '未生成' ? diagnoseFailure(c.reason, c.browserEvents) : null;
769
+ - if (await this.modalPresent().catch(() => false)) {
770
+ + if (await this.editorPresent().catch(() => false)) {
771
+ try {
772
+ await this.pendingWrites.wait(this.config.pageTimeout || 8000);
773
+ await this.dismissModal();
774
+ @@ -1187,77 +1483,116 @@
775
+ if (search) await this.assertControl(search.role, search.name);
776
+ if (reset) await this.assertControl(reset.role, reset.name);
777
+ });
778
+ - await add(
779
+ - 'form-validation',
780
+ - '新增表单必填项为空时阻止保存',
781
+ - 'form-validation',
782
+ + const validateEmptyForm = async () => {
783
+ + const saveControls = (await this.snapshot()).controls.filter(
784
+ + (c) => actions.save.test(c.name) && c.role === 'button',
785
+ + );
786
+ + if (saveControls.length === 1 && saveControls[0].disabled)
787
+ + await this.replayStep({
788
+ + kind: 'assert-disabled',
789
+ + target: controlInfo(saveControls[0]),
790
+ + });
791
+ + else {
792
+ + await this.click('save');
793
+ + await this.assertFormErrors();
794
+ + }
795
+ + };
796
+ + let formValidated = false;
797
+ + if (!this.allowed.has('create'))
798
+ + formValidated = await add(
799
+ + 'form-validation',
800
+ + '新增表单必填项为空时阻止保存',
801
+ + 'form-validation',
802
+ + async () => {
803
+ + await this.clickCreate();
804
+ + await validateEmptyForm();
805
+ + await this.click('close');
806
+ + },
807
+ + );
808
+ + const validateFormat = async () =>
809
+ + add('form-invalid', '数值区间示例的非法括号触发校验', 'form-invalid', async () => {
810
+ + // Reuse only evidence from this run's successfully validated initial
811
+ + // form. Missing/failed observation still follows the normal live check.
812
+ + if (formValidated && this.formEvidence?.hasRangeFormatInput === false)
813
+ + throw Object.assign(Error('已观察的新增表单没有区间格式输入框,本项不适用'), {
814
+ + notApplicable: true,
815
+ + });
816
+ + await this.clickCreate();
817
+ + try {
818
+ + const formatTarget = (await inspectLooseRequired(this.page)).find((x) =>
819
+ + invalidExampleValue(x.placeholder),
820
+ + );
821
+ + if (!formatTarget) {
822
+ + const error = Error('页面没有区间格式输入框,本项不适用');
823
+ + error.notApplicable = true;
824
+ + throw error;
825
+ + }
826
+ + const name = await this.field('填写校验记录名称');
827
+ + await this.fill(name, '${recordName}_invalid');
828
+ + await this.populateForm('名称');
829
+ + const target = (await inspectLooseRequired(this.page)).find((x) =>
830
+ + invalidExampleValue(x.placeholder),
831
+ + );
832
+ + if (!target) throw Error('格式校验输入框在填写后发生变化');
833
+ + await this.formFillRequired(target, invalidExampleValue(target.placeholder));
834
+ + await this.click('save');
835
+ + await this.assertInputInvalid(target);
836
+ + } finally {
837
+ + if ((await formErrors(this.page)).open)
838
+ + await this.click('close').catch(() => {});
839
+ + }
840
+ + });
841
+ + if (!this.allowed.has('create')) await validateFormat();
842
+ + const created = await add(
843
+ + 'create',
844
+ + '新增独立测试记录并验证必填约束',
845
+ + 'create',
846
+ async () => {
847
+ - const snap = await this.snapshot();
848
+ - if (!snap.controls.some((c) => isAction(c) && actions.create.test(c.name)))
849
+ - await this.click('area');
850
+ await this.clickCreate();
851
+ - const saveControls = (await this.snapshot()).controls.filter(
852
+ - (c) => actions.save.test(c.name) && c.role === 'button',
853
+ - );
854
+ - if (saveControls.length === 1 && saveControls[0].disabled) {
855
+ - await this.replayStep({
856
+ - kind: 'assert-disabled',
857
+ - target: controlInfo(saveControls[0]),
858
+ + if (this.allowed.has('form-validation')) {
859
+ + await validateEmptyForm();
860
+ + formValidated = true;
861
+ + }
862
+ + const nameLabel = await this.fillRecordName('${recordName}');
863
+ + await this.populateForm(nameLabel);
864
+ + await this.click('save');
865
+ + await this.waitModalClosed();
866
+ + await this.pendingWrites.wait(this.config.pageTimeout || 8000);
867
+ + await this.row('${recordName}');
868
+ + await this.assertPersisted('${recordName}');
869
+ + this.created = true;
870
+ + },
871
+ + );
872
+ + if (created) {
873
+ + await add('search', '查询:按唯一名称检索并核对本轮记录', 'search', async () => {
874
+ + await this.query('${recordName}');
875
+ + await assertSearchResult(this, {
876
+ + kind: 'assert-query-result',
877
+ + value: '${recordName}',
878
+ + });
879
+ + await this.query('', { assert: false });
880
+ + await this.row('${recordName}');
881
+ + });
882
+ + let inlineDetail = false;
883
+ + const viewed = await add('view', '查询:打开本轮记录并核对详情', 'view', async () => {
884
+ + if (!(await this.click('view', { rowName: this.currentName, optional: true }))) {
885
+ + const row = this.ownedRows(this.currentName);
886
+ + if ((await row.getAttribute('aria-selected')) === null)
887
+ + throw Object.assign(Error('列表没有查看入口或可选中记录的语义'), {
888
+ + notApplicable: !this.config.operations,
889
+ + });
890
+ + await openOwnedRecord(this, {
891
+ + kind: 'open-owned-record',
892
+ + value: '${recordName}',
893
+ });
894
+ - await this.click('close');
895
+ + await assertRecordDetail(this, {
896
+ + kind: 'assert-record-detail',
897
+ + value: '${recordName}',
898
+ + });
899
+ + await observeCoverage(this, '详情');
900
+ + inlineDetail = true;
901
+ return;
902
+ }
903
+ - await this.click('save');
904
+ - await this.assertFormErrors();
905
+ - await this.click('close');
906
+ - },
907
+ - );
908
+ - await add('form-invalid', '数值区间示例的非法括号触发校验', 'form-invalid', async () => {
909
+ - await this.clickCreate();
910
+ - try {
911
+ - const formatTarget = (await inspectLooseRequired(this.page)).find((x) =>
912
+ - invalidExampleValue(x.placeholder),
913
+ - );
914
+ - if (!formatTarget) {
915
+ - const error = Error('页面没有区间格式输入框,本项不适用');
916
+ - error.notApplicable = true;
917
+ - throw error;
918
+ - }
919
+ - const name = await this.field('填写校验记录名称');
920
+ - await this.fill(name, '${recordName}_invalid');
921
+ - await this.populateForm('名称');
922
+ - const target = (await inspectLooseRequired(this.page)).find((x) =>
923
+ - invalidExampleValue(x.placeholder),
924
+ - );
925
+ - if (!target) throw Error('格式校验输入框在填写后发生变化');
926
+ - await this.formFillRequired(target, invalidExampleValue(target.placeholder));
927
+ - await this.click('save');
928
+ - await this.assertInputInvalid(target);
929
+ - } finally {
930
+ - if ((await formErrors(this.page)).open) await this.click('close').catch(() => {});
931
+ - }
932
+ - });
933
+ - const created = await add('create', '新增独立测试记录', 'create', async () => {
934
+ - let snap = await this.snapshot();
935
+ - if (!snap.controls.some((c) => isAction(c) && actions.create.test(c.name))) {
936
+ - await this.click('area');
937
+ - snap = await this.snapshot();
938
+ - }
939
+ - await this.clickCreate();
940
+ - const nameLabel = await this.fillRecordName('${recordName}');
941
+ - await this.populateForm(nameLabel);
942
+ - await this.click('save');
943
+ - await this.reload();
944
+ - await this.query('${recordName}');
945
+ - this.created = true;
946
+ - });
947
+ - if (created) {
948
+ - await add('search', '按名称查询刚创建的记录', 'search', async () => {
949
+ - await this.query('${recordName}');
950
+ - });
951
+ - await add('view', '查看独立测试记录', 'view', async () => {
952
+ - if (!(await this.click('view', { rowName: this.currentName, optional: true })))
953
+ - throw Error('列表没有可识别的查看详情入口');
954
+ await this.page
955
+ .locator(MODAL_SEL)
956
+ .last()
957
+ @@ -1267,25 +1602,32 @@
958
+ this.record({ kind: 'assert-text', value: '${recordName}', scope: 'form' });
959
+ await this.click('close');
960
+ });
961
+ + if (viewed && inlineDetail) await exploreDetailTabs(this);
962
+ const edited = await add('edit', '修改独立测试记录名称', 'edit', async () => {
963
+ - await this.query('${recordName}');
964
+ + // Remove our own filter before editing, so the renamed record can
965
+ + // appear without a query that would conceal a stale UI update.
966
+ + await this.query('', { assert: false });
967
+ await this.click('edit', { rowName: this.currentName });
968
+ await this.fillRecordName('${updatedName}');
969
+ await this.click('save');
970
+ - await this.reload();
971
+ - await this.query('${updatedName}');
972
+ + await this.waitModalClosed();
973
+ + await this.pendingWrites.wait(this.config.pageTimeout || 8000);
974
+ + await this.row('${updatedName}');
975
+ + await this.row('${recordName}', false);
976
+ + await this.assertPersisted('${updatedName}');
977
+ this.currentName = this.variables.updatedName;
978
+ });
979
+ if (edited || !this.allowed.has('edit'))
980
+ await add('delete', '删除独立测试记录', 'delete', async () => {
981
+ const value = edited ? '${updatedName}' : '${recordName}';
982
+ - await this.query(value);
983
+ + await this.row(value);
984
+ await this.click('delete', { rowName: this.currentName });
985
+ const dialog = this.page.locator(MODAL_SEL + ',.ant-popover:visible');
986
+ if (await dialog.count()) await this.click('confirm');
987
+ - await this.reload();
988
+ - await this.query(value, { assert: false });
989
+ + await this.waitModalClosed();
990
+ + await this.pendingWrites.wait(this.config.pageTimeout || 8000);
991
+ await this.row(value, false);
992
+ + await this.assertPersisted(value, false);
993
+ this.created = false;
994
+ });
995
+ else if (this.allowed.has('delete'))
996
+ @@ -1314,14 +1656,37 @@
997
+ attempts: [],
998
+ evidence: '',
999
+ });
1000
+ + if (this.allowed.has('create') && this.formEvidence?.hasRangeFormatInput)
1001
+ + await validateFormat();
1002
+ if (this.allowed.has('discover')) await discoverTests(this);
1003
+ + else if (this.allowed.has('filters')) {
1004
+ + activity(this, '正在只读探索:展开记录树、验证筛选并恢复查询条件');
1005
+ + try {
1006
+ + await discoverTests(this, { readOnly: true });
1007
+ + } finally {
1008
+ + activity(this, '');
1009
+ + }
1010
+ + }
1011
+ if (!results.length)
1012
+ throw Error(
1013
+ - '当前页面未发现所选范围的可验证用例;请检查页面是否为目标模块及 --operations 配置',
1014
+ + this.config.readOnly
1015
+ + ? '只读探索未找到可验证的页签、列表或筛选用例。请确认当前业务页面已加载且控件具有可访问名称;如需探索新增、修改、删除,请勾选“允许创建、修改和删除本轮测试数据”。'
1016
+ + : '当前页面未发现所选范围的可验证用例;请检查页面是否为目标模块及 --operations 配置',
1017
+ );
1018
+ return results;
1019
+ }
1020
+ async replayStep(step) {
1021
+ + if (step.kind === 'assert-related-records') return executeRelatedRecords(this, step);
1022
+ + if (step.kind === 'open-owned-record') return openOwnedRecord(this, step);
1023
+ + if (step.kind === 'assert-record-detail') return assertRecordDetail(this, step);
1024
+ + if (step.kind === 'assert-tab-panel') return assertTabPanel(this, step);
1025
+ + if (step.kind === 'assert-query-result') return assertSearchResult(this, step);
1026
+ + if (step.kind === 'assert-disclosure') return inspectDisclosure(this, step);
1027
+ + if (step.kind === 'assert-persisted-row' || step.kind === 'assert-persisted-absent')
1028
+ + return this.assertPersisted(step.value, step.kind === 'assert-persisted-row', {
1029
+ + query: step.query,
1030
+ + });
1031
+ + if (step.kind === 'expand-tree') return expandTree(this, step.target);
1032
+ if (step.kind === 'assert-discovery') return executeDiscovery(this, step);
1033
+ if (step.kind === 'assert-control' || step.kind === 'assert-selected')
1034
+ return this.assertControl(
1035
+ @@ -1368,6 +1733,10 @@
1036
+ return;
1037
+ }
1038
+ const target = step.target;
1039
+ + const treeCreate =
1040
+ + step.kind === 'click' && step.purpose === 'create'
1041
+ + ? await revealTreeActions(this.page, target)
1042
+ + : null;
1043
+ const rowMenu =
1044
+ target.scope === 'owned-row' &&
1045
+ target.role === 'menuitem' &&
1046
+ @@ -1380,6 +1749,15 @@
1047
+ }
1048
+ let snap = await this.snapshot();
1049
+ if (target.scope === 'owned-row' && !rowMenu) {
1050
+ + if ((await this.ownedRows(this.currentName).getAttribute('role')) === 'treeitem') {
1051
+ + await (
1052
+ + await this.ownedActionRows(this.currentName)
1053
+ + )
1054
+ + .locator('button,[role="button"]')
1055
+ + .first()
1056
+ + .hover();
1057
+ + snap = await this.snapshot();
1058
+ + }
1059
+ const key = await this.ownedRows(this.currentName).getAttribute('data-row-key');
1060
+ if (key) snap = await discoverRowLabels(this.page, key);
1061
+ }
1062
+ @@ -1389,10 +1767,13 @@
1063
+ c.role === target.role &&
1064
+ !c.disabled &&
1065
+ !c.readonly &&
1066
+ + (!target.region || sameRegion(c, target)) &&
1067
+ (target.scope !== 'owned-row' || rowMenu || c.context.includes(this.currentName)),
1068
+ );
1069
+ const scoped = [];
1070
+ + const treeCreateRef = treeCreate ? await treeCreate.getAttribute(LIVE_REF) : null;
1071
+ for (const c of matches) {
1072
+ + if (treeCreate && c.ref !== treeCreateRef) continue;
1073
+ if (
1074
+ target.scope !== 'owned-row' ||
1075
+ rowMenu ||
1076
+ @@ -1419,17 +1800,25 @@
1077
+ if (step.kind === 'fill') {
1078
+ const value = this.resolve(step.value);
1079
+ await found.locator.fill(value);
1080
+ - if ((await found.locator.inputValue()) !== value) throw Error('回放输入值未生效');
1081
+ + await verifyInput(this, found.control, value);
1082
+ } else await this.dispatchClick(found.locator, step);
1083
+ this.record(step);
1084
+ await settle(this.page, 120);
1085
+ + if (step.kind === 'click' && ['create', 'edit'].includes(step.purpose))
1086
+ + await this.waitForEditor();
1087
+ + await waitForVisibleStep(this);
1088
+ }
1089
+ async replay(file) {
1090
+ await this.assertModuleAccess();
1091
+ + this.coverage = file.exploration || null;
1092
+ + if (this.identity?.host && file.cases.some((c) => c.steps.some((s) => s.kind === 'reload')))
1093
+ + throw Error('旧 Excel 含整页刷新步骤;主子应用请重新探索生成新用例,未执行任何用例');
1094
+ const results = this.results;
1095
+ let editFailed = false;
1096
+ + let viewFailed = false;
1097
+ for (const saved of file.cases) {
1098
+ this.checkInterrupted();
1099
+ + if (this.restorationFailure) throw Error(this.restorationFailure);
1100
+ const started = performance.now();
1101
+ const c = {
1102
+ id: saved.id,
1103
+ @@ -1446,12 +1835,15 @@
1104
+ this.diagnostics.begin(c.id);
1105
+ this.journal?.checkpoint({ activeCase: c, runtime: this.runtime() });
1106
+ if (
1107
+ - ['search', 'view', 'edit', 'delete'].includes(saved.operation) &&
1108
+ + ['search', 'view', 'related-records', 'edit', 'delete'].includes(saved.operation) &&
1109
+ (!this.created ||
1110
+ + (viewFailed &&
1111
+ + ['view', 'related-records'].includes(saved.operation) &&
1112
+ + saved.id !== 'view') ||
1113
+ (editFailed && JSON.stringify(saved.steps).includes('${updatedName}')))
1114
+ ) {
1115
+ c.status = '未执行(依赖阻断)';
1116
+ - c.reason = '前置新增或修改未通过,本条所需的记录状态未确认';
1117
+ + c.reason = '前置新增、详情打开或修改未通过,本条所需的页面状态未确认';
1118
+ } else
1119
+ try {
1120
+ for (const [index, step] of saved.steps.entries()) {
1121
+ @@ -1499,9 +1891,10 @@
1122
+ : null;
1123
+ if (c.status === '通过' && saved.operation === 'create') this.created = true;
1124
+ if (saved.operation === 'edit') editFailed = c.status !== '通过';
1125
+ + if (saved.id === 'view') viewFailed = c.status !== '通过';
1126
+ if (c.status === '通过' && saved.operation === 'edit')
1127
+ this.currentName = this.variables.updatedName;
1128
+ - if (await this.modalPresent().catch(() => false)) {
1129
+ + if (await this.editorPresent().catch(() => false)) {
1130
+ try {
1131
+ await this.pendingWrites.wait(this.config.pageTimeout || 8000);
1132
+ await this.dismissModal();
1133
+ @@ -1555,6 +1948,7 @@
1134
+ const journal = new RunJournal(config.out, { mode, moduleUrl, provider: config.provider });
1135
+ try {
1136
+ let browser,
1137
+ + verificationBrowser,
1138
+ context,
1139
+ page,
1140
+ diagnostics,
1141
+ @@ -1570,7 +1964,7 @@
1142
+ await Promise.race([
1143
+ context.tracing.stop({ path: path.join(config.out, 'trace.zip') }),
1144
+ new Promise((_, reject) => {
1145
+ - timer = setTimeout(() => reject(Error('保存 trace 超时')), 5000);
1146
+ + timer = setTimeout(() => reject(Error('保存 trace 超时')), 30000);
1147
+ }),
1148
+ ]);
1149
+ } catch (error) {
1150
+ @@ -1598,6 +1992,7 @@
1151
+ clearTimeout(timer);
1152
+ }
1153
+ await browser?.close().catch(() => {});
1154
+ + await verificationBrowser?.close().catch(() => {});
1155
+ });
1156
+ config = { ...config, url: url.href, journal, signal: interruption.signal };
1157
+ let savedCaseFile = null,
1158
+ @@ -1627,8 +2022,18 @@
1159
+ `模式:${mode};模型:${config.provider};浏览器:${config.headless ? '无头' : '可见'}`,
1160
+ );
1161
+ const modelWarmup = beginModelWarmup(laya, config);
1162
+ + journal.checkpoint({ activity: '正在打开测试页面并校验登录状态' });
1163
+ config.signal.throwIfAborted();
1164
+ let authRestored;
1165
+ + // Start the headless verifier BEFORE showing the test window. Creating
1166
+ + // Chrome processes during a visible run can steal focus on Windows.
1167
+ + // Each verification still gets a fresh context with pre-write auth.
1168
+ + if (!config.readOnly)
1169
+ + verificationBrowser = await launchBrowser({ ...config, headless: true });
1170
+ + if (verificationBrowser)
1171
+ + journal.event('verification-browser-ready', {
1172
+ + lifecycle: 'one-per-run-before-visible-browser',
1173
+ + });
1174
+ ({ browser, context, page, authRestored } = await openBrowser(config));
1175
+ config.signal.throwIfAborted();
1176
+ diagnostics = new BrowserDiagnostics(context);
1177
+ @@ -1649,11 +2054,22 @@
1178
+ authRestored,
1179
+ );
1180
+ await saveAuthState(context, page, config);
1181
+ + journal.checkpoint({
1182
+ + activity: '页面已就绪,正在等待本地 Laya 模型加载;首次加载可能需要约一分钟',
1183
+ + });
1184
+ await waitModelWarmup(modelWarmup);
1185
+ writePrivateJson(path.join(config.out, '启动浏览器事件.json'), await diagnostics.end());
1186
+ config.signal.throwIfAborted();
1187
+ workflow = new Workflow(page, laya, config, mode, diagnostics);
1188
+ - journal.checkpoint({ runtime: workflow.runtime(), authStatus });
1189
+ + workflow.verificationBrowser = verificationBrowser;
1190
+ + workflow.identity = await pageIdentity(page);
1191
+ + workflow.verificationAuth = await captureVerificationAuth(page, config);
1192
+ + journal.checkpoint({
1193
+ + runtime: workflow.runtime(),
1194
+ + authStatus,
1195
+ + activity: '',
1196
+ + explorationMode: config.readOnly ? 'read-only' : 'read-write',
1197
+ + });
1198
+ // Authentication is complete before screenshots/traces/progress are recorded.
1199
+ await context.tracing.start({ screenshots: true, snapshots: true, sources: false });
1200
+ traceStarted = true;
1201
+ @@ -1666,6 +2082,7 @@
1202
+ schemaVersion: 1,
1203
+ generatedAt: new Date().toISOString(),
1204
+ moduleUrl,
1205
+ + exploration: workflow.coverage || null,
1206
+ cases: results
1207
+ .filter((r) => r.status === '已验证')
1208
+ .map(({ status, reason, evidence, attempts, ...c }) => c),
1209
+ @@ -1724,6 +2141,7 @@
1210
+ await stopTrace();
1211
+ await interruption.dispose();
1212
+ laya?.close();
1213
+ + await verificationBrowser?.close().catch(() => {});
1214
+ if (!(config.keepOpen && !config.headless && !failure))
1215
+ await browser?.close().catch(() => {});
1216
+ }
1217
+ @@ -1775,6 +2193,7 @@
1218
+ retainedRecord: workflow?.created ? workflow.currentName : null,
1219
+ modelStartup: laya?.startup || null,
1220
+ discovery: workflow?.discovery || null,
1221
+ + coverage: workflow?.coverage || null,
1222
+ metrics: {
1223
+ modelCalls: actualCalls.length + (laya?.errors?.length || 0),
1224
+ modelErrors: laya?.errors?.length || 0,
1225
+ --- a/lib/run-state.mjs
1226
+ +++ b/lib/run-state.mjs
1227
+ @@ -10,7 +10,21 @@
1228
+ mode: 0o600,
1229
+ flag: 'wx',
1230
+ });
1231
+ - fs.renameSync(temporary, file);
1232
+ + // On Windows, a concurrent status reader or virus scanner can briefly
1233
+ + // deny replacement. Retry the atomic rename; never delete the last checkpoint.
1234
+ + for (let attempt = 0; ; attempt++) {
1235
+ + try {
1236
+ + fs.renameSync(temporary, file);
1237
+ + break;
1238
+ + } catch (error) {
1239
+ + if (
1240
+ + process.platform !== 'win32' ||
1241
+ + !['EPERM', 'EACCES', 'EBUSY'].includes(error.code) ||
1242
+ + attempt >= 5
1243
+ + ) throw error;
1244
+ + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10 * 2 ** attempt);
1245
+ + }
1246
+ + }
1247
+ } finally {
1248
+ if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
1249
+ }
1250
+ --- a/lib/dom.mjs
1251
+ +++ b/lib/dom.mjs
1252
+ @@ -12,20 +12,72 @@
1253
+ const visible = (e) => {
1254
+ const s = getComputedStyle(e),
1255
+ r = e.getBoundingClientRect();
1256
+ + let left = r.left,
1257
+ + right = r.right,
1258
+ + top = r.top,
1259
+ + bottom = r.bottom;
1260
+ + // Collapsed disclosure content may retain nonzero boxes.
1261
+ + // Do not offer controls clipped by overflow:hidden/clip;
1262
+ + // scrollable containers remain usable by Playwright.
1263
+ + for (let p = e.parentElement; p; p = p.parentElement) {
1264
+ + const style = getComputedStyle(p),
1265
+ + box = p.getBoundingClientRect();
1266
+ + if (['hidden', 'clip'].includes(style.overflowX)) {
1267
+ + left = Math.max(left, box.left);
1268
+ + right = Math.min(right, box.right);
1269
+ + }
1270
+ + if (['hidden', 'clip'].includes(style.overflowY)) {
1271
+ + top = Math.max(top, box.top);
1272
+ + bottom = Math.min(bottom, box.bottom);
1273
+ + }
1274
+ + }
1275
+ return (
1276
+ s.display !== 'none' &&
1277
+ s.visibility !== 'hidden' &&
1278
+ r.width > 0 &&
1279
+ r.height > 0 &&
1280
+ + right > left &&
1281
+ + bottom > top &&
1282
+ !e.closest('[inert],[aria-hidden="true"]')
1283
+ );
1284
+ };
1285
+ const text = (e) =>
1286
+ (e?.innerText || e?.textContent || '').replace(/\s+/g, ' ').trim();
1287
+ + const regionSelector =
1288
+ + 'aside,[role="complementary"],section[aria-label],section[aria-labelledby],[role="region"],main,[role="main"],header,[role="banner"],nav,[role="navigation"]';
1289
+ + const describeRegion = (e) =>
1290
+ + e
1291
+ + ? {
1292
+ + role:
1293
+ + e.getAttribute('role') ||
1294
+ + {
1295
+ + aside: 'complementary',
1296
+ + main: 'main',
1297
+ + header: 'banner',
1298
+ + nav: 'navigation',
1299
+ + section: 'region',
1300
+ + }[e.tagName.toLowerCase()],
1301
+ + name: (
1302
+ + (e.getAttribute('aria-labelledby') || '')
1303
+ + .split(/\s+/)
1304
+ + .map((id) => text(e.getRootNode().getElementById(id)))
1305
+ + .join(' ')
1306
+ + .trim() ||
1307
+ + e.getAttribute('aria-label') ||
1308
+ + ''
1309
+ + )
1310
+ + .replace(/\s+/g, ' ')
1311
+ + .trim(),
1312
+ + }
1313
+ + : null;
1314
+ const roots = [document];
1315
+ for (let i = 0; i < roots.length; i++)
1316
+ for (const e of roots[i].querySelectorAll('*'))
1317
+ if (e.shadowRoot) roots.push(e.shadowRoot);
1318
+ + const regions = roots
1319
+ + .flatMap((root) => [...root.querySelectorAll(regionSelector)])
1320
+ + .filter(visible)
1321
+ + .map(describeRegion);
1322
+ const selector =
1323
+ 'button,a[href],input:not([type="hidden"]),textarea,select,[role="button"],[role="link"],[role="tab"],[role="menuitem"],[role="option"],[role="combobox"],[role="checkbox"],[role="radio"],[role="switch"],[tabindex],[contenteditable="true"],summary';
1324
+ let elements = roots
1325
+ @@ -72,7 +124,7 @@
1326
+ const modals = roots
1327
+ .flatMap((root) => [
1328
+ ...root.querySelectorAll(
1329
+ - 'dialog[open],[role="dialog"],[role="alertdialog"],[data-slot="dialog-content"],[data-slot="alert-dialog-content"],.ant-drawer-open .ant-drawer-content,.el-dialog',
1330
+ + 'dialog[open],[role="dialog"],[role="alertdialog"],[data-slot="dialog-content"],[data-slot="alert-dialog-content"],.ant-drawer-open .ant-drawer-content,.el-dialog,[data-laya-editor-root]',
1331
+ ),
1332
+ ])
1333
+ .filter(visible);
1334
+ @@ -175,8 +227,14 @@
1335
+ )
1336
+ .replace(/^\*\s*/, '')
1337
+ .slice(0, 130);
1338
+ - const row = e.closest('tr,[role="row"]'),
1339
+ + const row = e.closest('tr,[role="row"],[role="treeitem"]'),
1340
+ group = e.closest('fieldset,[role="group"],form');
1341
+ + const region = describeRegion(e.closest(regionSelector));
1342
+ + const regionAmbiguous =
1343
+ + !!region &&
1344
+ + regions.filter(
1345
+ + (r) => r.role === region.role && r.name === region.name,
1346
+ + ).length !== 1;
1347
+ const rowKey = row?.getAttribute('data-row-key') || '';
1348
+ // Fixed operation columns have rows containing only icons. Join their live
1349
+ // data-row-key to the main table, rather than mistaking all icons for one row.
1350
+ @@ -205,6 +263,11 @@
1351
+ rowKey,
1352
+ placeholder: e.getAttribute('placeholder') || '',
1353
+ context,
1354
+ + region,
1355
+ + regionAmbiguous,
1356
+ + expanded: e.hasAttribute('aria-expanded')
1357
+ + ? e.getAttribute('aria-expanded') === 'true'
1358
+ + : null,
1359
+ inPanel: !!e.closest('[role="tabpanel"]'),
1360
+ disabled:
1361
+ e.matches(':disabled') ||
1362
+ --- a/lib/form.mjs
1363
+ +++ b/lib/form.mjs
1364
+ @@ -1,9 +1,9 @@
1365
+ import { randomBytes } from 'node:crypto';
1366
+ +import { FORM_ROOT } from './page-capabilities.mjs';
1367
+
1368
+ const REF = 'data-laya-form-ref';
1369
+ // 弹窗根选择器:与 dom.mjs / workflow.mjs 的模态判定同族,使用标准语义与已支持的组件容器
1370
+ -const ROOT_SEL =
1371
+ - 'dialog[open],[role="dialog"],[role="alertdialog"],[data-slot="dialog-content"],[data-slot="alert-dialog-content"],.ant-drawer-open .ant-drawer-content,.el-dialog';
1372
+ +const ROOT_SEL = FORM_ROOT;
1373
+ const visible = (e) => {
1374
+ const r = e.getBoundingClientRect(),
1375
+ s = getComputedStyle(e);
1376
+ @@ -52,7 +52,7 @@
1377
+ ? text(nativeSelect.selectedOptions[0])
1378
+ : text(
1379
+ item.querySelector(
1380
+ - '.ant-select-selection-selected-value,.ant-select-selection-item,.ant-select-selection__choice__content,.tntd-rc-select-selection-item,.tntd-select-selection-item',
1381
+ + '.ant-select-content-has-value:not(.ant-select-content-has-search-value),.ant-select-selection-selected-value,.ant-select-selection-item,.ant-select-selection__choice__content,.tntd-rc-select-selection-item,.tntd-select-selection-item',
1382
+ ),
1383
+ );
1384
+ return {
1385
+ --- a/lib/discovery.mjs
1386
+ +++ b/lib/discovery.mjs
1387
+ @@ -1,12 +1,25 @@
1388
+ -import { inspectForm, findFormItem } from './form.mjs';
1389
+ -import { waitForReady } from './readiness.mjs';
1390
+ +import { inspectForm, findFormItem, inspectLooseRequired, invalidExampleValue } from './form.mjs';
1391
+ +import { assertPageIdentity, activity, waitForVisibleStep } from './page-session.mjs';
1392
+ +import { settle } from './dom.mjs';
1393
+ +import {
1394
+ + sameRegion,
1395
+ + expandCollection,
1396
+ + revealTreeActions,
1397
+ + recordTrees,
1398
+ + validateTreeTarget,
1399
+ +} from './page-capabilities.mjs';
1400
+
1401
+ const SEARCH = /搜索|查询|search|query/i;
1402
+ const RESET = /^(重置|清空|reset|clear)$/i;
1403
+ const CREATE = /新增|新建|创建|添加|\badd\b|\bnew\b|\bcreate\b/i;
1404
+ const CANCEL = /^(取消|关闭|cancel|close)$/i;
1405
+ const searchField = /名称|姓名|用户名|账号|账户|name|account|搜索|查询|search/i;
1406
+ -const target = ({ name, role }) => ({ name, role });
1407
+ +const target = ({ name, role, region, treePath }) => ({
1408
+ + name,
1409
+ + role,
1410
+ + ...(region ? { region } : {}),
1411
+ + ...(treePath ? { treePath } : {}),
1412
+ +});
1413
+ const keyOf = (c) => `${c.role}:${c.name}`;
1414
+
1415
+ export function discoveryCandidates(snapshot, form) {
1416
+ @@ -14,12 +27,27 @@
1417
+ const unique = (items) =>
1418
+ items.filter((c) => items.filter((x) => keyOf(x) === keyOf(c)).length === 1);
1419
+ const fields = unique(
1420
+ - controls.filter((c) => c.role === 'textbox' && !c.readonly && searchField.test(c.name)),
1421
+ + controls.filter(
1422
+ + (c) =>
1423
+ + c.role === 'textbox' &&
1424
+ + !c.readonly &&
1425
+ + searchField.test(c.name) &&
1426
+ + !c.regionAmbiguous &&
1427
+ + !['banner', 'navigation'].includes(c.region?.role),
1428
+ + ),
1429
+ );
1430
+ let searches = unique(controls.filter((c) => c.role === 'button' && SEARCH.test(c.name)));
1431
+ + if (fields.length === 1) searches = searches.filter((c) => sameRegion(c, fields[0]));
1432
+ const explicitSearch = searches.filter((c) => /^(搜索|查询|search|query)$/i.test(c.name));
1433
+ if (explicitSearch.length === 1) searches = explicitSearch;
1434
+ - const resets = unique(controls.filter((c) => c.role === 'button' && RESET.test(c.name)));
1435
+ + const resets = unique(
1436
+ + controls.filter(
1437
+ + (c) =>
1438
+ + c.role === 'button' &&
1439
+ + RESET.test(c.name) &&
1440
+ + (fields.length !== 1 || sameRegion(c, fields[0])),
1441
+ + ),
1442
+ + );
1443
+ const candidates = [];
1444
+ const query =
1445
+ fields.length === 1 && searches.length <= 1
1446
+ @@ -89,14 +117,17 @@
1447
+ return candidates;
1448
+ }
1449
+
1450
+ -export function validateDiscovery(step) {
1451
+ +export function validateDiscovery(step, { readOnly = false } = {}) {
1452
+ const c = step.spec;
1453
+ + if (c?.create?.treePath) validateTreeTarget(c.create.treePath, { allowRoot: true });
1454
+ if (
1455
+ step.kind !== 'assert-discovery' ||
1456
+ !c ||
1457
+ !['filter-empty', 'filter-reset', 'cancel-create', 'field-invalid'].includes(c.check)
1458
+ )
1459
+ throw Error('不支持的补充测试步骤');
1460
+ + if (readOnly && !['filter-empty', 'filter-reset'].includes(c.check))
1461
+ + throw Error('只读探索只允许筛选及恢复验证,不能打开新增表单');
1462
+ const named = (t, role, pattern) =>
1463
+ t?.role === role &&
1464
+ typeof t.name === 'string' &&
1465
+ @@ -151,20 +182,76 @@
1466
+ }
1467
+
1468
+ async function control(w, t) {
1469
+ - const snap = await w.snapshot();
1470
+ - return (
1471
+ - await w.chooseFromSnapshot(
1472
+ - snap,
1473
+ - snap.controls.filter((c) => c.name === t.name && c.role === t.role && !c.disabled),
1474
+ - `${['textbox', 'spinbutton'].includes(t.role) ? '填写' : '点击'}「${t.name}」`,
1475
+ - )
1476
+ - ).locator;
1477
+ -}
1478
+ -async function reload(w) {
1479
+ - await w.page.reload({ waitUntil: 'domcontentloaded' });
1480
+ - await waitForReady(w.page, { timeout: w.config.pageTimeout });
1481
+ + return w.withAttempts('定位恢复控件', async () => {
1482
+ + const treeAction = t.treePath ? await revealTreeActions(w.page, t) : null;
1483
+ + const snap = await w.snapshot();
1484
+ + const treeRef = treeAction ? await treeAction.getAttribute('data-laya-live-ref') : null;
1485
+ + return (
1486
+ + await w.chooseFromSnapshot(
1487
+ + snap,
1488
+ + snap.controls.filter(
1489
+ + (c) =>
1490
+ + c.name === t.name &&
1491
+ + c.role === t.role &&
1492
+ + !c.disabled &&
1493
+ + (!treeAction || c.ref === treeRef) &&
1494
+ + (!t.region || sameRegion(c, t)),
1495
+ + ),
1496
+ + `${['textbox', 'spinbutton'].includes(t.role) ? '填写' : '点击'}「${t.name}」`,
1497
+ + )
1498
+ + ).locator;
1499
+ + });
1500
+ +}
1501
+ +async function setFilter(w, c, value) {
1502
+ + await assertPageIdentity(w.page, w.identity);
1503
+ + const input = await control(w, c.field);
1504
+ + if ((await input.inputValue()) !== value) {
1505
+ + await input.fill(value);
1506
+ + await settle(w.page, 180);
1507
+ + }
1508
+ + if ((await (await control(w, c.field)).inputValue()) !== value)
1509
+ + throw Error('筛选条件没有恢复到预期值');
1510
+ + if (c.search) await (await control(w, c.search)).click();
1511
+ + await w.pendingWrites.wait(w.config.pageTimeout || 8000);
1512
+ + await expandCollection(w, { record: false });
1513
+ +}
1514
+ +
1515
+ +const sameRows = (a, b) => JSON.stringify([...a].sort()) === JSON.stringify([...b].sort());
1516
+ +
1517
+ +async function restoreDiscovery(w, c, original, baseline) {
1518
+ + activity(w, '正在恢复当前子应用的表单和筛选条件,不刷新主应用');
1519
+ + try {
1520
+ + await assertPageIdentity(w.page, w.identity);
1521
+ + if (await w.editorPresent()) {
1522
+ + if (!c.cancel) throw Error('没有已确认的取消入口,无法恢复编辑区');
1523
+ + await (await control(w, c.cancel)).click();
1524
+ + await w.waitModalClosed();
1525
+ + }
1526
+ + if (c.field) await setFilter(w, c, original);
1527
+ + await waitTable(w, (rows) => sameRows(rows, baseline));
1528
+ + await waitForVisibleStep(w);
1529
+ + } catch (error) {
1530
+ + // Do not turn an assertion failure into success by refreshing. The next
1531
+ + // case must not run against an unknown child-app state either.
1532
+ + w.restorationFailure = `当前子应用状态恢复失败,已停止后续探索:${error.message}`;
1533
+ + throw Error(w.restorationFailure, { cause: error });
1534
+ + } finally {
1535
+ + activity(w, '');
1536
+ + }
1537
+ }
1538
+ async function tableState(w) {
1539
+ + const trees = recordTrees(w.page);
1540
+ + if (await trees.count()) {
1541
+ + if ((await trees.count()) !== 1) throw Error('补充测试无法确定唯一记录树');
1542
+ + return trees
1543
+ + .getByRole('treeitem')
1544
+ + .filter({ visible: true })
1545
+ + .evaluateAll((items) =>
1546
+ + items
1547
+ + .filter((item) => !item.hasAttribute('aria-expanded'))
1548
+ + .map((item) => item.getAttribute('aria-label') || item.innerText),
1549
+ + );
1550
+ + }
1551
+ const table = w.page.locator('table:visible,[role="grid"]:visible');
1552
+ // Fixed-column copies are not independent tables. Require a single main table.
1553
+ const main = table
1554
+ @@ -201,15 +288,24 @@
1555
+ // This bounded grammar never submits a form. Replay uses the recorded recipe;
1556
+ // the model cannot introduce selectors, scripts, URLs or write operations.
1557
+ export async function executeDiscovery(w, step) {
1558
+ - const c = validateDiscovery(step);
1559
+ - await reload(w);
1560
+ + if (w.restorationFailure) throw Error(w.restorationFailure);
1561
+ + const c = validateDiscovery(step, { readOnly: w.config.readOnly });
1562
+ + await assertPageIdentity(w.page, w.identity);
1563
+ + // The recipe's precondition is an unfiltered list in both generation and
1564
+ + // replay. A preceding delete may leave its run-owned keyword in the field.
1565
+ + if (c.field && (await (await control(w, c.field)).inputValue()) !== '')
1566
+ + await setFilter(w, c, '');
1567
+ + await expandCollection(w, { record: false });
1568
+ + const baseline = await tableState(w);
1569
+ + const original = c.field ? await (await control(w, c.field)).inputValue() : null;
1570
+ + let failure;
1571
+ try {
1572
+ if (c.check.startsWith('filter-')) {
1573
+ - const baseline = await tableState(w);
1574
+ if (!baseline.length) throw Error('列表原本为空,无法验证筛选及恢复');
1575
+ await (await control(w, c.field)).fill(`no_match_${w.variables.recordAccount}`);
1576
+ if (c.search) await (await control(w, c.search)).click();
1577
+ await waitTable(w, (rows) => rows.length === 0);
1578
+ + await waitForVisibleStep(w);
1579
+ if (c.check === 'filter-reset') {
1580
+ await (await control(w, c.reset)).click();
1581
+ if ((await (await control(w, c.field)).inputValue()) !== '')
1582
+ @@ -220,8 +316,10 @@
1583
+ );
1584
+ }
1585
+ } else {
1586
+ + if (!c.create.treePath) await revealTreeActions(w.page, c.create);
1587
+ await (await control(w, c.create)).click();
1588
+ - await w.waitForModal();
1589
+ + await w.waitForEditor();
1590
+ + await waitForVisibleStep(w);
1591
+ if (w.mode === 'execute') await w.matchFormTarget(c.label);
1592
+ const { info, item } = await findFormItem(w.page, c.label);
1593
+ const input = item.locator('input:visible,textarea:visible');
1594
+ @@ -229,12 +327,32 @@
1595
+ throw Error('补充测试字段已变化');
1596
+ if (c.check === 'cancel-create') {
1597
+ await input.fill(w.variables.recordAccount);
1598
+ + await waitForVisibleStep(w);
1599
+ await (await control(w, c.cancel)).click();
1600
+ await w.waitModalClosed();
1601
+ - await reload(w);
1602
+ + await waitForVisibleStep(w);
1603
+ await (await control(w, c.field)).fill(w.variables.recordAccount);
1604
+ if (c.search) await (await control(w, c.search)).click();
1605
+ await waitTable(w, (rows) => rows.length === 0);
1606
+ + await w.assertPersisted('${recordAccount}', false, {
1607
+ + record: false,
1608
+ + query: [
1609
+ + {
1610
+ + kind: 'fill',
1611
+ + target: { ...c.field, scope: 'page' },
1612
+ + value: '${recordAccount}',
1613
+ + },
1614
+ + ...(c.search
1615
+ + ? [
1616
+ + {
1617
+ + kind: 'click',
1618
+ + purpose: 'search',
1619
+ + target: { ...c.search, scope: 'page' },
1620
+ + },
1621
+ + ]
1622
+ + : []),
1623
+ + ],
1624
+ + });
1625
+ } else {
1626
+ const observed = info.inputs[0];
1627
+ if (
1628
+ @@ -261,17 +379,25 @@
1629
+ c.constraint,
1630
+ );
1631
+ if (!invalid) throw Error('字段未按声明的约束拒绝非法值');
1632
+ + await waitForVisibleStep(w);
1633
+ await (await control(w, c.cancel)).click();
1634
+ await w.waitModalClosed();
1635
+ }
1636
+ }
1637
+ - } finally {
1638
+ - await reload(w);
1639
+ - }
1640
+ + } catch (error) {
1641
+ + failure = error;
1642
+ + }
1643
+ + try {
1644
+ + await restoreDiscovery(w, c, original, baseline);
1645
+ + } catch (error) {
1646
+ + if (!failure) throw error;
1647
+ + throw Error(`${failure.message};${error.message}`, { cause: failure });
1648
+ + }
1649
+ + if (failure) throw failure;
1650
+ w.record(step);
1651
+ }
1652
+
1653
+ -export async function discoverTests(w) {
1654
+ +export async function discoverTests(w, { readOnly = w.config.readOnly } = {}) {
1655
+ if (w.pendingWrite || w.created) {
1656
+ w.discovery = {
1657
+ status: 'blocked',
1658
+ @@ -280,9 +406,21 @@
1659
+ };
1660
+ return;
1661
+ }
1662
+ - await reload(w);
1663
+ - const snapshot = await w.snapshot();
1664
+ - const candidates = discoveryCandidates(snapshot, w.formEvidence);
1665
+ + await assertPageIdentity(w.page, w.identity);
1666
+ + if (await w.editorPresent()) throw Error('编辑区未关闭,停止补充探索');
1667
+ + let snapshot = await w.snapshot();
1668
+ + const query = discoveryCandidates(snapshot, null).find((c) => c.check === 'filter-empty');
1669
+ + if (query && (await (await control(w, query.field)).inputValue()) !== '') {
1670
+ + activity(w, '正在清除本轮查询条件,保留主应用及其他子应用状态');
1671
+ + try {
1672
+ + await setFilter(w, query, '');
1673
+ + } finally {
1674
+ + activity(w, '');
1675
+ + }
1676
+ + }
1677
+ + await expandCollection(w, { record: false });
1678
+ + snapshot = await w.snapshot();
1679
+ + const candidates = discoveryCandidates(snapshot, readOnly ? null : w.formEvidence);
1680
+ w.discovery = {
1681
+ status: 'completed',
1682
+ candidates: [],
1683
+ @@ -297,13 +435,23 @@
1684
+ const entry = { ...c, ...decision };
1685
+ w.discovery.candidates.push(entry);
1686
+ if (!decision.selected) continue;
1687
+ - const result = await w.runCase(`discover-${i + 1}`, c.title, 'discover', async () => {
1688
+ - await executeDiscovery(w, { kind: 'assert-discovery', spec: c });
1689
+ - });
1690
+ + const result = await w.runCase(
1691
+ + `discover-${i + 1}`,
1692
+ + c.title,
1693
+ + readOnly ? 'filters' : 'discover',
1694
+ + async () => {
1695
+ + await executeDiscovery(w, { kind: 'assert-discovery', spec: c });
1696
+ + },
1697
+ + );
1698
+ entry.status = result.status;
1699
+ entry.reason = result.reason;
1700
+ w.completeCase(result);
1701
+ console.log(`${result.status} ${result.id}: ${result.reason}`);
1702
+ + if (w.restorationFailure) {
1703
+ + w.discovery.status = 'blocked';
1704
+ + w.discovery.reason = w.restorationFailure;
1705
+ + break;
1706
+ + }
1707
+ }
1708
+ w.discovery.truncated = Math.max(0, candidates.length - 12);
1709
+ }
1710
+ @@ -319,5 +467,8 @@
1711
+ create: target(create),
1712
+ cancel: cancel.length === 1 ? target(cancel[0]) : null,
1713
+ fields: await inspectForm(w.page),
1714
+ + hasRangeFormatInput: (await inspectLooseRequired(w.page)).some((input) =>
1715
+ + invalidExampleValue(input.placeholder),
1716
+ + ),
1717
+ };
1718
+ }
1719
+ --- a/lib/workflow_excel.py
1720
+ +++ b/lib/workflow_excel.py
1721
+ @@ -68,6 +68,26 @@
1722
+ kind = step['kind']
1723
+ target = step.get('target', {}).get('name', '')
1724
+ value = step.get('value', '')
1725
+ + if kind in ('assert-persisted-row', 'assert-persisted-absent'):
1726
+ + state = '存在唯一记录' if kind == 'assert-persisted-row' else '记录不存在'
1727
+ + return f'在独立后台浏览器会话重新打开相同模块,查询并核对{state}:{value}(不刷新当前主子应用)'
1728
+ + if kind == 'expand-tree':
1729
+ + node = step['target']
1730
+ + return f'在「{node["tree"]}」树中展开「{" → ".join(node["path"])}」,核对节点已展开'
1731
+ + if kind == 'open-owned-record':
1732
+ + return f'点击本轮独立记录「{value}」的名称入口,原地打开详情'
1733
+ + if kind == 'assert-record-detail':
1734
+ + return f'核对列表之外的详情标题或定义内容包含本轮记录「{value}」,不能用列表同名文本代替'
1735
+ + if kind == 'assert-query-result':
1736
+ + return f'核对唯一关键词查询只返回本轮记录「{value}」,不能只检查输入框文字'
1737
+ + if kind == 'assert-tab-panel':
1738
+ + return f'核对「{target}」页签选中且 aria-controls 关联的内容面板已显示'
1739
+ + if kind == 'assert-disclosure':
1740
+ + return f'在「{step["target"]["tab"]}」面板内展开「{target}」,核对新控件出现,再收起并核对状态恢复'
1741
+ + if kind == 'assert-related-records':
1742
+ + return (f'在本轮父记录的「{step["target"]["tab"]}」面板点击「{step["target"]["add"]}」;'
1743
+ + f'选择唯一数据「{step["item"]}」并确认;断言关联列表显示该记录,在独立会话重新打开并核对;'
1744
+ + f'选中该关联记录,点击「{step["target"]["remove"]}」;断言列表恢复为空,并再次独立校验。')
1745
+ if kind == 'assert-discovery':
1746
+ spec = step['spec']
1747
+ check = spec['check']
1748
+ @@ -81,7 +101,7 @@
1749
+ if check == 'filter-reset':
1750
+ return f'先查询不存在的关键词并核对列表为空,再点击「{spec["reset"]["name"]}」,核对条件清空且原列表记录恢复'
1751
+ if check == 'cancel-create':
1752
+ - return f'点击「{spec["create"]["name"]}」,填写「{spec["label"]}」,点击「{spec["cancel"]["name"]}」,核对弹窗关闭且刷新后没有新增记录'
1753
+ + return f'展开当前列表中的分类,点击「{spec["create"]["name"]}」,填写「{spec["label"]}」,点击「{spec["cancel"]["name"]}」,核对编辑区关闭且当前页面、独立会话均无新增记录,最后原地恢复筛选条件'
1754
+ if check == 'field-invalid':
1755
+ return f'打开新增表单,向「{spec["label"]}」输入违反 {spec["constraint"]}={spec.get("bound", "邮箱格式")} 的值,核对浏览器约束校验失败,再取消(不提交)'
1756
+ raise ValueError('不支持的补充测试:' + check)
1757
+ @@ -184,13 +204,23 @@
1758
+ 'generatedAt': file['generatedAt'],
1759
+ 'moduleUrl': file['moduleUrl'],
1760
+ 'coverage': file['coverage'],
1761
+ + 'exploration': file.get('exploration'),
1762
+ },
1763
+ ensure_ascii=False,
1764
+ )
1765
+ meta.append(['id', 'visible_sha256', 'case_json'])
1766
+ module = Path(file['moduleUrl'].split('?')[0].rstrip('/')).name or '目标页面'
1767
+ + if file.get('exploration'):
1768
+ + scope = book.create_sheet('探索范围')
1769
+ + scope.append(['已观察状态', '入口', '未验证原因'])
1770
+ + scope.append(['说明', '用例通过不代表页面功能全覆盖', '以下入口未计入通过用例'])
1771
+ + for gap in file['exploration'].get('gaps', []):
1772
+ + scope.append([clean(gap.get('state')), clean(gap.get('name')), clean(gap.get('reason'))])
1773
+ + scope.freeze_panes = 'A2'
1774
+ + for letter, width in [('A', 32), ('B', 35), ('C', 65)]:
1775
+ + scope.column_dimensions[letter].width = width
1776
+ for index, case in enumerate(file['cases'], 2):
1777
+ - uses_owned_record = case['operation'] in ('create', 'search', 'view', 'edit', 'delete')
1778
+ + uses_owned_record = case['operation'] in ('create', 'search', 'view', 'related-records', 'edit', 'delete')
1779
+ precondition = (
1780
+ '已登录并进入目标模块;使用本轮唯一命名的独立测试记录'
1781
+ if uses_owned_record
1782
+ @@ -277,6 +307,7 @@
1783
+ 'moduleUrl': header['moduleUrl'],
1784
+ 'cases': cases,
1785
+ 'coverage': header.get('coverage', []),
1786
+ + 'exploration': header.get('exploration'),
1787
+ }
1788
+
1789
+
1790
+ --- a/tests/retries.test.mjs
1791
+ +++ b/tests/retries.test.mjs
1792
+ @@ -152,6 +152,8 @@
1793
+ const { workflow, page } = setup();
1794
+ workflow.attemptState = { writeSequence: 0 };
1795
+ workflow.snapshot = async () => ({ controls: [{ name: '新增' }] });
1796
+ + workflow.editorPresent = async () => false;
1797
+ + workflow.ownedRows = () => ({ count: async () => 1 });
1798
+ page.getByText = () => ({});
1799
+ page.locator = () => ({ filter: () => ({ count: async () => 1 }) });
1800
+ const step = { purpose: 'save' };
1801
+ @@ -212,12 +214,23 @@
1802
+ count: async () => 1,
1803
+ isVisible: async () => true,
1804
+ click: async () => clicked.push(ref),
1805
+ + evaluate: async () => false, // These toolbar entries do not belong to a tree.
1806
+ }),
1807
+ },
1808
+ ],
1809
+ };
1810
+ };
1811
+ - workflow.waitForModal = async () => {};
1812
+ + workflow.editorPresent = async () => false;
1813
+ + workflow.waitForEditor = async () => {
1814
+ + throw Error('No editor opened');
1815
+ + };
1816
+ + workflow.chooseFromSnapshot = async (snap, candidates) => {
1817
+ + const control = candidates[0];
1818
+ + return {
1819
+ + control,
1820
+ + locator: snap.frames[control.frame].locator(`[data-laya-live-ref="${control.ref}"]`),
1821
+ + };
1822
+ + };
1823
+ await assert.rejects(workflow.clickCreate(), /尝试3次/);
1824
+ assert.equal(observed, 3);
1825
+ assert.equal(clicked.length, 3);
1826
+ --- a/tests/selected-pr1.test.mjs
1827
+ +++ b/tests/selected-pr1.test.mjs
1828
+ @@ -24,7 +24,14 @@
1829
+ closest: () => null,
1830
+ querySelector: () => null,
1831
+ matches: () => false,
1832
+ - getBoundingClientRect: () => ({ width: 100, height: 30 }),
1833
+ + getBoundingClientRect: () => ({
1834
+ + width: 100,
1835
+ + height: 30,
1836
+ + left: 0,
1837
+ + right: 100,
1838
+ + top: 0,
1839
+ + bottom: 30,
1840
+ + }),
1841
+ classList: { contains: () => false },
1842
+ });
1843
+ const label = node('LABEL', '名称'),
1844
+ @@ -75,6 +82,7 @@
1845
+ locator: (selector) => ({
1846
+ count: async () => (selector.includes('"' + generation + '-') ? 1 : 0),
1847
+ isVisible: async () => true,
1848
+ + evaluate: async () => false, // Entries in this fixture are outside a tree.
1849
+ }),
1850
+ },
1851
+ ],
1852
+ @@ -82,8 +90,18 @@
1853
+ },
1854
+ safeClick: async (_, name) => clicked.push(name),
1855
+ record: () => {},
1856
+ - waitForModal: async () => {},
1857
+ - modalPresent: async () => clicked.includes('新增乙'),
1858
+ + waitForEditor: async () => {
1859
+ + if (!clicked.includes('新增乙')) throw Error('No editor opened');
1860
+ + },
1861
+ + editorPresent: async () => clicked.includes('新增乙'),
1862
+ + chooseFromSnapshot: async (snap, candidates) => {
1863
+ + const control = candidates[0];
1864
+ + const locator = snap.frames[control.frame].locator(
1865
+ + `[data-laya-live-ref="${control.ref}"]`,
1866
+ + );
1867
+ + assert.equal(await locator.count(), 1, 'must select the current observed reference');
1868
+ + return { control, locator };
1869
+ + },
1870
+ dismissModal: async () => {},
1871
+ };
1872
+ await Workflow.prototype.withAttempts.call(fake, 'clickCreate', () =>
1873
+ --- /dev/null
1874
+ +++ b/lib/page-capabilities.mjs
1875
+ @@ -0,0 +1,356 @@
1876
+ +// Bounded extensions to the upstream workflow. Standard page semantics plus
1877
+ +// upstream component compatibility; no business routes, labels or second planner.
1878
+ +import { randomBytes } from 'node:crypto';
1879
+ +import { waitForVisibleStep } from './page-session.mjs';
1880
+ +
1881
+ +export const MODAL =
1882
+ + 'dialog[open],[role="dialog"],[role="alertdialog"],[data-slot="dialog-content"],[data-slot="alert-dialog-content"],.ant-drawer-open .ant-drawer-content,.el-dialog';
1883
+ +export const EDITOR = '[data-laya-editor-root]';
1884
+ +export const FORM_ROOT = `${EDITOR},${MODAL}`;
1885
+ +const TREE_REF = 'data-laya-tree-ref';
1886
+ +const SAVE = /保存|提交|\bsave\b|\bsubmit\b/i;
1887
+ +const CREATE = /新增|新建|创建|添加|\badd\b|\bnew\b|\bcreate\b/i;
1888
+ +const RECORD_TREE = '[role="tree"]:not(nav *,[role="navigation"] *,header *,[role="banner"] *)';
1889
+ +export const COLLECTION = `table:visible,[role="grid"]:visible,${RECORD_TREE}:visible`;
1890
+ +
1891
+ +export const recordTrees = (page) => page.locator(RECORD_TREE).filter({ visible: true });
1892
+ +
1893
+ +export function formRoot(page) {
1894
+ + const modal = page.locator(MODAL).filter({ visible: true });
1895
+ + return page
1896
+ + .locator(EDITOR)
1897
+ + .filter({ visible: true })
1898
+ + .filter({ hasNot: modal })
1899
+ + .or(modal)
1900
+ + .last();
1901
+ +}
1902
+ +
1903
+ +// Called only after a create/edit action. A filter form alone never activates an editor.
1904
+ +export async function activateEditor(page, timeout = 4000) {
1905
+ + const deadline = Date.now() + timeout;
1906
+ + do {
1907
+ + if (await formRoot(page).count()) return;
1908
+ + const roots = await page.evaluate(
1909
+ + ({ attr, source }) => {
1910
+ + const visible = (e) =>
1911
+ + !!(e.getBoundingClientRect().width && e.getBoundingClientRect().height) &&
1912
+ + getComputedStyle(e).visibility !== 'hidden' &&
1913
+ + !e.closest('[hidden],[inert]');
1914
+ + const save = new RegExp(source, 'i');
1915
+ + const forms = [...document.querySelectorAll('form,[role="form"]')].filter(
1916
+ + (e) =>
1917
+ + visible(e) &&
1918
+ + e.querySelector(
1919
+ + 'input[required],input[aria-required="true"],textarea[required],textarea[aria-required="true"]',
1920
+ + ),
1921
+ + );
1922
+ + const roots = new Set();
1923
+ + for (const form of forms) {
1924
+ + const region = form.closest(
1925
+ + '[role="region"][aria-label],section[aria-label],main,[role="main"]',
1926
+ + );
1927
+ + const root = region || form;
1928
+ + const saves = [
1929
+ + ...root.querySelectorAll('button,[role="button"],input[type="submit"]'),
1930
+ + ].filter(
1931
+ + (e) =>
1932
+ + visible(e) &&
1933
+ + save.test(e.getAttribute('aria-label') || e.innerText || e.value || ''),
1934
+ + );
1935
+ + if (saves.length === 1 && forms.filter((f) => root.contains(f)).length === 1)
1936
+ + roots.add(root);
1937
+ + }
1938
+ + if (roots.size === 1) [...roots][0].setAttribute(attr, '');
1939
+ + return roots.size;
1940
+ + },
1941
+ + { attr: 'data-laya-editor-root', source: SAVE.source },
1942
+ + );
1943
+ + if (roots > 1) throw Error('存在多个独立编辑表单,无法确定当前编辑区');
1944
+ + if (roots === 1) return;
1945
+ + await page.waitForTimeout(100);
1946
+ + } while (Date.now() < deadline);
1947
+ + throw Error('创建或修改入口未打开唯一可识别的表单(弹窗或独立编辑区)');
1948
+ +}
1949
+ +
1950
+ +export function sameRegion(a, b) {
1951
+ + if (a?.regionAmbiguous || b?.regionAmbiguous) return false;
1952
+ + if (a?.frame != null && b?.frame != null && a.frame !== b.frame) return false;
1953
+ + return (
1954
+ + (a?.region?.role || '') === (b?.region?.role || '') &&
1955
+ + (a?.region?.name || '') === (b?.region?.name || '')
1956
+ + );
1957
+ +}
1958
+ +
1959
+ +export async function verifyInput(w, control, value) {
1960
+ + // Input/change handlers may replace a DOM node. Re-observe the same semantic
1961
+ + // field for the postcondition; never re-submit a write or accept a stale ref.
1962
+ + const snap = await w.snapshot();
1963
+ + const matches = snap.controls.filter(
1964
+ + (c) =>
1965
+ + c.name === control.name &&
1966
+ + c.role === control.role &&
1967
+ + c.frame === control.frame &&
1968
+ + sameRegion(c, control) &&
1969
+ + !c.disabled &&
1970
+ + !c.readonly,
1971
+ + );
1972
+ + if (matches.length !== 1) throw Error('输入后无法唯一确认字段:' + control.name);
1973
+ + const current = matches[0];
1974
+ + const input = snap.frames[current.frame].locator(`[data-laya-live-ref="${current.ref}"]`);
1975
+ + if ((await input.inputValue()) !== value) throw Error('输入值没有进入' + control.name);
1976
+ +}
1977
+ +
1978
+ +export function recordRows(page, name) {
1979
+ + const table = page
1980
+ + .locator('table tbody tr:visible,[role="rowgroup"] [role="row"]:visible')
1981
+ + .filter({ has: page.getByText(name, { exact: true }) });
1982
+ + // Exact accessible record name prevents prefix collisions and parent-node matches.
1983
+ + return table.or(
1984
+ + recordTrees(page).getByRole('treeitem', { name, exact: true }).filter({ visible: true }),
1985
+ + );
1986
+ +}
1987
+ +
1988
+ +export async function observeTree(page) {
1989
+ + return page.evaluate(
1990
+ + ({ attr, nonce, selector }) => {
1991
+ + const visible = (e) =>
1992
+ + !!(e.getBoundingClientRect().width && e.getBoundingClientRect().height) &&
1993
+ + getComputedStyle(e).visibility !== 'hidden' &&
1994
+ + !e.closest('[hidden],[inert]');
1995
+ + const name = (e) =>
1996
+ + (
1997
+ + (e.getAttribute('aria-labelledby') || '')
1998
+ + .split(/\s+/)
1999
+ + .map((id) => e.getRootNode().getElementById(id)?.textContent || '')
2000
+ + .join(' ')
2001
+ + .trim() ||
2002
+ + e.getAttribute('aria-label') ||
2003
+ + ''
2004
+ + )
2005
+ + .replace(/\s+/g, ' ')
2006
+ + .trim();
2007
+ + const trees = [...document.querySelectorAll(selector)].filter(visible);
2008
+ + if (trees.length > 1) throw Error('存在多个记录树,无法确定唯一探索范围');
2009
+ + if (trees.some((tree) => !name(tree) || name(tree).length > 150))
2010
+ + throw Error('记录树缺少明确的可访问名称或名称超过 150 字符');
2011
+ + return [...document.querySelectorAll('[role="treeitem"]')]
2012
+ + .filter((item) => visible(item) && trees.includes(item.closest('[role="tree"]')))
2013
+ + .map((item, i) => {
2014
+ + const tree = item.closest('[role="tree"]');
2015
+ + const path = [];
2016
+ + for (
2017
+ + let current = item;
2018
+ + current && current !== tree;
2019
+ + current = current.parentElement
2020
+ + )
2021
+ + if (current.getAttribute('role') === 'treeitem')
2022
+ + path.unshift(name(current));
2023
+ + if (path.some((n) => !n || n.length > 150) || path.length > 8)
2024
+ + throw Error(
2025
+ + '树节点路径缺少名称、名称超过 150 字符或超过 8 层,无法稳定回放',
2026
+ + );
2027
+ + const ref = nonce + '-' + i;
2028
+ + item.setAttribute(attr, ref);
2029
+ + return {
2030
+ + tree: name(tree),
2031
+ + path,
2032
+ + ref,
2033
+ + expanded: item.getAttribute('aria-expanded'),
2034
+ + };
2035
+ + });
2036
+ + },
2037
+ + { attr: TREE_REF, nonce: randomBytes(4).toString('hex'), selector: RECORD_TREE },
2038
+ + );
2039
+ +}
2040
+ +
2041
+ +export function validateTreeTarget(target, { allowRoot = false } = {}) {
2042
+ + if (
2043
+ + !target ||
2044
+ + typeof target.tree !== 'string' ||
2045
+ + !target.tree ||
2046
+ + target.tree.length > 150 ||
2047
+ + !Array.isArray(target.path) ||
2048
+ + (!allowRoot && !target.path.length) ||
2049
+ + target.path.length > 8 ||
2050
+ + target.path.some((n) => typeof n !== 'string' || !n || n.length > 150)
2051
+ + )
2052
+ + throw Error('树展开步骤缺少明确的树名称和节点路径');
2053
+ +}
2054
+ +
2055
+ +export const sameTreePath = (a, b) =>
2056
+ + a?.tree === b?.tree &&
2057
+ + Array.isArray(a?.path) &&
2058
+ + Array.isArray(b?.path) &&
2059
+ + a.path.length === b.path.length &&
2060
+ + a.path.every((name, i) => name === b.path[i]);
2061
+ +
2062
+ +// Store semantic ownership before navigation replaces the source DOM. Never
2063
+ +// persist child indexes, transient refs, CSS classes or the first matching name.
2064
+ +export async function captureTreePath(page, locator) {
2065
+ + if (!(await locator.evaluate((e) => !!e.closest('[role="tree"]')))) return undefined;
2066
+ + if (
2067
+ + !(await locator.evaluate(
2068
+ + (e, selector) => e.closest('[role="tree"]').matches(selector),
2069
+ + RECORD_TREE,
2070
+ + ))
2071
+ + )
2072
+ + throw Error('全局导航树不能作为记录创建入口');
2073
+ + const nodes = await observeTree(page);
2074
+ + const owner = await locator.evaluate((e) => {
2075
+ + const item = e.closest('[role="treeitem"]');
2076
+ + return item ? { ref: item.getAttribute('data-laya-tree-ref') } : null;
2077
+ + });
2078
+ + if (owner) {
2079
+ + const node = nodes.find((n) => n.ref === owner.ref);
2080
+ + if (!node || nodes.filter((n) => sameTreePath(n, node)).length !== 1)
2081
+ + throw Error('创建入口所属树路径不唯一');
2082
+ + return { tree: node.tree, path: node.path };
2083
+ + }
2084
+ + const name = await recordTrees(page).evaluate(
2085
+ + (e) =>
2086
+ + (e.getAttribute('aria-labelledby') || '')
2087
+ + .split(/\s+/)
2088
+ + .map((id) => e.getRootNode().getElementById(id)?.textContent || '')
2089
+ + .join(' ')
2090
+ + .trim() ||
2091
+ + e.getAttribute('aria-label') ||
2092
+ + '',
2093
+ + );
2094
+ + return { tree: name.replace(/\s+/g, ' ').trim(), path: [] };
2095
+ +}
2096
+ +
2097
+ +export async function expandTree(w, target, { record = true } = {}) {
2098
+ + validateTreeTarget(target);
2099
+ + const nodes = (await observeTree(w.page)).filter((n) => sameTreePath(n, target));
2100
+ + if (nodes.length !== 1) throw Error('树节点路径不唯一或已变化:' + target.path.join(' / '));
2101
+ + const node = nodes[0];
2102
+ + if (!['true', 'false'].includes(node.expanded)) throw Error('目标节点没有可展开状态');
2103
+ + const item = w.page.locator(`[${TREE_REF}="${node.ref}"]`);
2104
+ + if (node.expanded === 'false') {
2105
+ + // Only an expander owned by this node may be clicked, never an arbitrary child action.
2106
+ + const expanders = item.locator(
2107
+ + 'button[aria-expanded="false"],[role="button"][aria-expanded="false"]',
2108
+ + );
2109
+ + const ownedCount = await expanders.evaluateAll(
2110
+ + (elements, ref) =>
2111
+ + elements.filter(
2112
+ + (e) =>
2113
+ + e.closest('[role="treeitem"]')?.getAttribute('data-laya-tree-ref') === ref,
2114
+ + ).length,
2115
+ + node.ref,
2116
+ + );
2117
+ + if (ownedCount === 1) {
2118
+ + // Observe first so the existing model/locator binding can be reused.
2119
+ + const snap = await w.snapshot();
2120
+ + const candidates = [];
2121
+ + for (const c of snap.controls) {
2122
+ + const live = snap.frames[c.frame].locator(`[data-laya-live-ref="${c.ref}"]`);
2123
+ + if (
2124
+ + c.expanded === false &&
2125
+ + (await item.locator(`[data-laya-live-ref="${c.ref}"]`).count()) &&
2126
+ + (await live.evaluate((e) =>
2127
+ + e.closest('[role="treeitem"]')?.getAttribute('data-laya-tree-ref'),
2128
+ + )) === node.ref
2129
+ + )
2130
+ + candidates.push(c);
2131
+ + }
2132
+ + const found = await w.chooseFromSnapshot(
2133
+ + snap,
2134
+ + candidates,
2135
+ + '展开「' + target.path.at(-1) + '」',
2136
+ + );
2137
+ + await found.locator.click({ timeout: 4000 });
2138
+ + } else if (!ownedCount && (await item.getAttribute('tabindex')) !== null) {
2139
+ + await item.focus();
2140
+ + await item.press('ArrowRight');
2141
+ + } else throw Error('树节点没有唯一的语义展开控件');
2142
+ + const deadline = Date.now() + 3000;
2143
+ + let expanded = false;
2144
+ + do {
2145
+ + const live = (await observeTree(w.page)).filter((n) => sameTreePath(n, target));
2146
+ + expanded = live.length === 1 && live[0].expanded === 'true';
2147
+ + if (expanded) break;
2148
+ + await w.page.waitForTimeout(80);
2149
+ + } while (Date.now() < deadline);
2150
+ + if (!expanded) throw Error('点击后未证实树节点已展开:' + target.path.join(' / '));
2151
+ + await waitForVisibleStep(w);
2152
+ + }
2153
+ + if (record) w.record({ kind: 'expand-tree', target });
2154
+ +}
2155
+ +
2156
+ +export async function expandCollection(w, options) {
2157
+ + // Bounded structural navigation within the supplied module, not whole-site crawling.
2158
+ + for (let count = 0; count < 24; count++) {
2159
+ + w.checkInterrupted();
2160
+ + const node = (await observeTree(w.page)).find((n) => n.expanded === 'false');
2161
+ + if (!node) return;
2162
+ + await expandTree(w, { tree: node.tree, path: node.path }, options);
2163
+ + }
2164
+ + if ((await observeTree(w.page)).some((n) => n.expanded === 'false'))
2165
+ + throw Error('树探索达到 24 个展开节点上限,未将不完整列表视为成功');
2166
+ +}
2167
+ +
2168
+ +export async function revealTreeActions(page, target) {
2169
+ + if (
2170
+ + target &&
2171
+ + !target.treePath &&
2172
+ + (await page
2173
+ + .getByRole(target.role, {
2174
+ + name: target.name,
2175
+ + exact: true,
2176
+ + })
2177
+ + .filter({ visible: true })
2178
+ + .count())
2179
+ + )
2180
+ + return;
2181
+ + const trees = recordTrees(page);
2182
+ + if (!(await trees.count())) {
2183
+ + if (target?.treePath) throw Error('记录的创建入口所属树已不存在');
2184
+ + return;
2185
+ + }
2186
+ + // Validate the whole scope before hovering or clicking. Multiple independent
2187
+ + // collections and duplicate paths must not silently turn into "pick first".
2188
+ + await observeTree(page);
2189
+ + if (target?.treePath) validateTreeTarget(target.treePath, { allowRoot: true });
2190
+ + const roles = target ? [target.role] : ['button', 'link', 'menuitem'];
2191
+ + const create = roles
2192
+ + .map((role) =>
2193
+ + trees.getByRole(role, {
2194
+ + name: target?.name || CREATE,
2195
+ + exact: !!target?.name,
2196
+ + includeHidden: true,
2197
+ + }),
2198
+ + )
2199
+ + .reduce((all, locator) => all.or(locator));
2200
+ + const count = await create.count();
2201
+ + if (count > 24) throw Error('树创建入口超过 24 个观察上限');
2202
+ + const candidates = [];
2203
+ + for (let i = 0; i < count; i++) {
2204
+ + const button = create.nth(i);
2205
+ + if (await button.isDisabled()) continue;
2206
+ + const path = await captureTreePath(page, button);
2207
+ + if (!target?.treePath || sameTreePath(path, target.treePath)) candidates.push(button);
2208
+ + }
2209
+ + if (!candidates.length && !target?.treePath) return;
2210
+ + if (candidates.length !== 1) throw Error('树创建入口不唯一或所属路径已变化');
2211
+ + const button = candidates[0];
2212
+ + if (await button.isVisible()) return button;
2213
+ + // The trigger may sit above an invisible wrapper. Walk only within its
2214
+ + // owning tree node; never hover a sibling branch or assume one DOM level.
2215
+ + const ancestors = await button.evaluate((e) => {
2216
+ + const owner = e.closest('[role="treeitem"]') || e.closest('[role="tree"]');
2217
+ + let depth = 0;
2218
+ + for (let p = e.parentElement; p && depth < 12; p = p.parentElement) {
2219
+ + depth++;
2220
+ + if (p === owner) return depth;
2221
+ + }
2222
+ + throw Error('树操作入口嵌套超过 12 层,无法确定悬浮触发区');
2223
+ + });
2224
+ + let parent = button;
2225
+ + for (let i = 0; i < ancestors; i++) {
2226
+ + parent = parent.locator('..');
2227
+ + if (await parent.isVisible()) await parent.hover({ timeout: 1500 });
2228
+ + if (await button.isVisible()) return button;
2229
+ + }
2230
+ + throw Error('无法在所属树节点内显示创建入口');
2231
+ +}
2232
+ --- /dev/null
2233
+ +++ b/lib/page-session.mjs
2234
+ @@ -0,0 +1,69 @@
2235
+ +import { waitForReady } from './readiness.mjs';
2236
+ +
2237
+ +// Page continuity is separate from persistence. Never reload the host merely to
2238
+ +// clear a child application's form/filter, or mistake a remount for a fresh read.
2239
+ +export async function pageIdentity(page) {
2240
+ + const apps = await page.locator('[data-laya-app]').evaluateAll((roots) =>
2241
+ + roots
2242
+ + .filter((root) => root.getAttribute('data-laya-active') === 'true')
2243
+ + .map((root) => ({
2244
+ + app: root.getAttribute('data-laya-app'),
2245
+ + instance: root.getAttribute('data-laya-instance'),
2246
+ + })),
2247
+ + );
2248
+ + if (apps.length > 1 || (apps.length === 1 && (!apps[0].app || !apps[0].instance)))
2249
+ + throw Error('无法确定唯一的当前子应用实例');
2250
+ + return {
2251
+ + url: page.url(),
2252
+ + host: (await page.locator('[data-laya-host],[data-laya-app]').count()) > 0,
2253
+ + app: apps[0]?.app ?? null,
2254
+ + instance: apps[0]?.instance ?? null,
2255
+ + };
2256
+ +}
2257
+ +
2258
+ +export async function assertPageIdentity(page, expected, { fresh = false } = {}) {
2259
+ + const current = await pageIdentity(page);
2260
+ + if (
2261
+ + current.url !== expected.url ||
2262
+ + current.host !== expected.host ||
2263
+ + current.app !== expected.app ||
2264
+ + (!fresh && current.instance !== expected.instance)
2265
+ + )
2266
+ + throw Error('页面路由或子应用实例已变化;停止操作,不刷新主应用或切换其他标签');
2267
+ +}
2268
+ +
2269
+ +export async function captureVerificationAuth(page, config) {
2270
+ + // Capture BEFORE any test mutation. Copying storage after a write could copy
2271
+ + // optimistic business caches and falsely make an unpersisted record pass.
2272
+ + return {
2273
+ + origin: new URL(config.url).origin,
2274
+ + storageState: await page.context().storageState({ indexedDB: true }),
2275
+ + ...(config.authSessionStorage
2276
+ + ? {
2277
+ + sessionStorage: await page.evaluate(() =>
2278
+ + Object.fromEntries(
2279
+ + Object.entries(sessionStorage).filter(
2280
+ + ([key]) => key !== '__laya_auth_restored__',
2281
+ + ),
2282
+ + ),
2283
+ + ),
2284
+ + }
2285
+ + : {}),
2286
+ + };
2287
+ +}
2288
+ +
2289
+ +export function activity(w, message) {
2290
+ + w.journal?.checkpoint({ activity: message });
2291
+ + if (message) console.log(message);
2292
+ +}
2293
+ +
2294
+ +// Visible runs need time to observe a completed interaction before the next
2295
+ +// action replaces it. DOM reads and headless persistence checks never wait here.
2296
+ +export async function waitForVisibleStep(w) {
2297
+ + if (w.config?.headless !== false) return;
2298
+ + w.checkInterrupted?.();
2299
+ + // Observe a stable, non-loading UI before advancing. A fixed sleep alone
2300
+ + // can expire halfway through an asynchronous panel replacement.
2301
+ + await waitForReady(w.page, { minimum: 650, timeout: w.config.pageTimeout || 8000 });
2302
+ + w.checkInterrupted?.();
2303
+ +}
2304
+ --- /dev/null
2305
+ +++ b/lib/page-exploration.mjs
2306
+ @@ -0,0 +1,372 @@
2307
+ +// Semantic master/detail navigation extends the upstream executor. The model
2308
+ +// chooses from observed controls; it never supplies selectors or scripts.
2309
+ +import { selectDiscovery } from './discovery.mjs';
2310
+ +import { assertPageIdentity, activity, waitForVisibleStep } from './page-session.mjs';
2311
+ +import { recordTrees } from './page-capabilities.mjs';
2312
+ +import { matchReplayTarget } from './replay-model.mjs';
2313
+ +import { exploreRelatedRecords } from './related-records.mjs';
2314
+ +
2315
+ +export async function assertSearchResult(w, step) {
2316
+ + await w.row(step.value);
2317
+ + const trees = recordTrees(w.page);
2318
+ + let total;
2319
+ + if ((await trees.count()) === 1)
2320
+ + total = await trees
2321
+ + .getByRole('treeitem')
2322
+ + .filter({ visible: true })
2323
+ + .evaluateAll((items) => items.filter((e) => !e.hasAttribute('aria-expanded')).length);
2324
+ + else {
2325
+ + const collection = w
2326
+ + .ownedRows(w.resolve(step.value))
2327
+ + .locator('xpath=ancestor::*[self::table or @role="grid"][1]');
2328
+ + if ((await collection.count()) !== 1) throw Error('无法确定查询结果所属的唯一列表');
2329
+ + total = await collection
2330
+ + .locator('tbody tr,[role="row"]')
2331
+ + .filter({ visible: true })
2332
+ + .evaluateAll(
2333
+ + (rows) =>
2334
+ + rows.filter(
2335
+ + (e) =>
2336
+ + e.querySelector('td,[role="gridcell"],[role="cell"]') &&
2337
+ + !e.matches('.ant-table-placeholder') &&
2338
+ + !e.querySelector('.ant-empty,.el-table__empty-block'),
2339
+ + ).length,
2340
+ + );
2341
+ + }
2342
+ + if (total !== 1) throw Error('唯一关键词查询未收敛到本轮记录,不能只凭输入框变化认为查询通过');
2343
+ + w.record(step);
2344
+ +}
2345
+ +
2346
+ +export async function openOwnedRecord(w, step) {
2347
+ + if (!w.created) throw Error('查看详情需要本轮已创建的独立记录');
2348
+ + const name = w.resolve(step.value);
2349
+ + if (name !== w.currentName) throw Error('详情目标不是本轮当前记录');
2350
+ + const row = w.ownedRows(name);
2351
+ + if ((await row.count()) !== 1) throw Error('详情记录不唯一');
2352
+ + const snap = await w.snapshot();
2353
+ + const candidates = [];
2354
+ + for (const c of snap.controls) {
2355
+ + if (!['button', 'link'].includes(c.role) || c.disabled || !c.name.includes(name)) continue;
2356
+ + if (await row.locator(`[data-laya-live-ref="${c.ref}"]`).count()) candidates.push(c);
2357
+ + }
2358
+ + let found;
2359
+ + if (w.mode === 'execute' && candidates.length === 1) {
2360
+ + // Upstream replay uses stable option keys (目标1, 目标2). A random record
2361
+ + // identifier is test data, not a useful classifier label for Laya.
2362
+ + const c = await matchReplayTarget(w.laya, '点击', candidates[0].name, candidates, w.config);
2363
+ + found = { locator: snap.frames[c.frame].locator(`[data-laya-live-ref="${c.ref}"]`) };
2364
+ + } else
2365
+ + found = await w.chooseFromSnapshot(snap, candidates, '打开本轮记录「' + name + '」的详情');
2366
+ + await found.locator.click();
2367
+ + await assertPageIdentity(w.page, w.identity);
2368
+ + await waitForVisibleStep(w);
2369
+ + w.record(step);
2370
+ +}
2371
+ +
2372
+ +export async function assertRecordDetail(w, step, { record = true } = {}) {
2373
+ + const name = w.resolve(step.value);
2374
+ + // A matching list label is not evidence that detail opened. Require an
2375
+ + // independently rendered heading/definition outside every collection.
2376
+ + await w.page.waitForFunction(
2377
+ + (name) =>
2378
+ + [...document.querySelectorAll('h1,h2,h3,h4,h5,h6,[role="heading"],dd')].some((e) => {
2379
+ + const rect = e.getBoundingClientRect();
2380
+ + return (
2381
+ + rect.width > 0 &&
2382
+ + rect.height > 0 &&
2383
+ + !e.closest(
2384
+ + '[role="tree"],table,[role="grid"],nav,header,[aria-hidden="true"]',
2385
+ + ) &&
2386
+ + e.textContent.includes(name)
2387
+ + );
2388
+ + }),
2389
+ + name,
2390
+ + { timeout: w.config.assertTimeout || 4000 },
2391
+ + );
2392
+ + if (record) w.record(step);
2393
+ +}
2394
+ +
2395
+ +export async function assertTabPanel(w, step) {
2396
+ + const tab = w.page.getByRole('tab', { name: step.target.name, exact: true });
2397
+ + if ((await tab.count()) !== 1) throw Error('页签入口不唯一:' + step.target.name);
2398
+ + await w.page.waitForFunction(
2399
+ + (name) => {
2400
+ + const visible = (e) =>
2401
+ + !!e &&
2402
+ + e.getBoundingClientRect().width > 0 &&
2403
+ + e.getBoundingClientRect().height > 0 &&
2404
+ + !e.closest('[hidden],[aria-hidden="true"]');
2405
+ + const tabs = [...document.querySelectorAll('[role="tab"]')].filter(
2406
+ + (e) =>
2407
+ + visible(e) && (e.getAttribute('aria-label') || e.textContent).trim() === name,
2408
+ + );
2409
+ + if (tabs.length !== 1 || tabs[0].getAttribute('aria-selected') !== 'true') return false;
2410
+ + const panel = document.getElementById(tabs[0].getAttribute('aria-controls'));
2411
+ + return (
2412
+ + visible(panel) &&
2413
+ + panel.getAttribute('role') === 'tabpanel' &&
2414
+ + panel.getAttribute('aria-busy') !== 'true'
2415
+ + );
2416
+ + },
2417
+ + step.target.name,
2418
+ + { timeout: w.config.assertTimeout || 4000 },
2419
+ + );
2420
+ + w.record(step);
2421
+ +}
2422
+ +
2423
+ +export async function inspectDisclosure(w, step) {
2424
+ + if (w.restorationFailure) throw Error(w.restorationFailure);
2425
+ + const tab = w.page.getByRole('tab', { name: step.target.tab, exact: true });
2426
+ + const panel = w.page.getByRole('tabpanel').filter({ visible: true });
2427
+ + if ((await tab.getAttribute('aria-selected')) !== 'true' || (await panel.count()) !== 1)
2428
+ + throw Error('展开检查需要唯一的当前详情面板');
2429
+ + const initial = await w.snapshot();
2430
+ + const candidates = initial.controls.filter(
2431
+ + (c) =>
2432
+ + c.role === 'button' &&
2433
+ + c.name === step.target.name &&
2434
+ + c.inPanel &&
2435
+ + !c.disabled &&
2436
+ + c.expanded === false,
2437
+ + );
2438
+ + if (candidates.length !== 1) throw Error('展开入口不唯一或不是收起状态');
2439
+ + if ((await panel.locator(`[data-laya-live-ref="${candidates[0].ref}"]`).count()) !== 1)
2440
+ + throw Error('展开按钮不属于当前详情面板');
2441
+ + const before = initial.controls.filter((c) => c.inPanel).map((c) => c.role + ':' + c.name);
2442
+ + let failure;
2443
+ + try {
2444
+ + const found = await w.chooseFromSnapshot(
2445
+ + initial,
2446
+ + candidates,
2447
+ + '点击「' + step.target.name + '」',
2448
+ + );
2449
+ + await found.locator.click();
2450
+ + await waitForVisibleStep(w);
2451
+ + const opened = panel.locator(
2452
+ + 'button[aria-expanded="true"],[role="button"][aria-expanded="true"]',
2453
+ + );
2454
+ + await opened.waitFor({ state: 'visible', timeout: w.config.assertTimeout || 4000 });
2455
+ + if ((await opened.count()) !== 1) throw Error('展开后无法确定唯一恢复入口');
2456
+ + let after = [];
2457
+ + const deadline = Date.now() + (w.config.assertTimeout || 4000);
2458
+ + do {
2459
+ + w.checkInterrupted();
2460
+ + after = (await w.snapshot()).controls.filter(
2461
+ + (c) => c.inPanel && !before.includes(c.role + ':' + c.name) && c.expanded !== true,
2462
+ + );
2463
+ + if (after.length) break;
2464
+ + await w.page.waitForTimeout(80);
2465
+ + } while (Date.now() < deadline);
2466
+ + if (!after.length) throw Error('展开后没有出现新的可操作控件');
2467
+ + await observeCoverage(w, `详情 / ${step.target.tab} / ${step.target.name}`, {
2468
+ + panel: step.target.tab,
2469
+ + });
2470
+ + } catch (e) {
2471
+ + failure = e;
2472
+ + }
2473
+ + try {
2474
+ + const opened = panel.locator(
2475
+ + 'button[aria-expanded="true"],[role="button"][aria-expanded="true"]',
2476
+ + );
2477
+ + if ((await opened.count()) === 1) {
2478
+ + const snap = await w.snapshot();
2479
+ + const ref = await opened.getAttribute('data-laya-live-ref');
2480
+ + const candidate = snap.controls.find((c) => c.ref === ref);
2481
+ + const found = await w.chooseFromSnapshot(
2482
+ + snap,
2483
+ + [candidate].filter(Boolean),
2484
+ + '点击「' + candidate?.name + '」',
2485
+ + );
2486
+ + await found.locator.click();
2487
+ + await waitForVisibleStep(w);
2488
+ + }
2489
+ + const restored = (await w.snapshot()).controls.filter(
2490
+ + (c) =>
2491
+ + c.role === 'button' &&
2492
+ + c.name === step.target.name &&
2493
+ + c.inPanel &&
2494
+ + c.expanded === false,
2495
+ + );
2496
+ + if (restored.length !== 1) throw Error('展开区未恢复');
2497
+ + await assertPageIdentity(w.page, w.identity);
2498
+ + } catch (e) {
2499
+ + w.restorationFailure = '详情展开区恢复失败,停止后续探索:' + e.message;
2500
+ + throw Error(w.restorationFailure);
2501
+ + }
2502
+ + if (failure) throw failure;
2503
+ + w.coverage.gaps = w.coverage.gaps.filter(
2504
+ + (g) =>
2505
+ + !(
2506
+ + g.name === step.target.name &&
2507
+ + ['详情', `详情 / ${step.target.tab}`].includes(g.state)
2508
+ + ),
2509
+ + );
2510
+ + w.record(step);
2511
+ +}
2512
+ +
2513
+ +export async function observeCoverage(w, state, { panel } = {}) {
2514
+ + const snap = await w.snapshot();
2515
+ + w.coverage ??= { states: [], gaps: [] };
2516
+ + if (!w.coverage.states.includes(state)) w.coverage.states.push(state);
2517
+ + for (const c of snap.controls) {
2518
+ + if (!['button', 'link', 'checkbox', 'switch', 'combobox'].includes(c.role) || !c.name)
2519
+ + continue;
2520
+ + // Bind inventory to its owning panel. Re-observing an expanded state
2521
+ + // must not count the same button again, or include sibling-panel tools.
2522
+ + if (panel ? !c.inPanel : c.inPanel) continue;
2523
+ + if (c.expanded === true) continue;
2524
+ + const locator = snap.frames[c.frame].locator(`[data-laya-live-ref="${c.ref}"]`);
2525
+ + const inside = await locator.evaluate(
2526
+ + (e) =>
2527
+ + !!e.closest('main,[role="main"],[role="tabpanel"],dialog,[role="dialog"]') &&
2528
+ + !e.closest(
2529
+ + '[role="tree"],nav,header,[data-research-assistant],gz-research-assistant',
2530
+ + ),
2531
+ + );
2532
+ + if (!inside || c.name.includes(w.variables.recordName)) continue;
2533
+ + const reason = c.disabled
2534
+ + ? '当前数据条件下入口不可用,未执行'
2535
+ + : '已发现入口,尚无可验证并可恢复的测试步骤';
2536
+ + const owner = panel ? `详情 / ${panel}` : state;
2537
+ + const item = { state: owner, role: c.role, name: c.name, reason };
2538
+ + if (
2539
+ + !w.coverage.gaps.some(
2540
+ + (g) => g.state === owner && g.role === c.role && g.name === c.name,
2541
+ + )
2542
+ + )
2543
+ + w.coverage.gaps.push(item);
2544
+ + }
2545
+ + w.journal?.checkpoint({ coverage: w.coverage });
2546
+ +}
2547
+ +
2548
+ +export async function exploreDetailTabs(w) {
2549
+ + const snap = await w.snapshot();
2550
+ + const tabs = snap.controls.filter(
2551
+ + (c) =>
2552
+ + c.role === 'tab' &&
2553
+ + c.name &&
2554
+ + !c.disabled &&
2555
+ + !['navigation', 'banner'].includes(c.region?.role),
2556
+ + );
2557
+ + const selected = tabs.filter((c) => c.selected);
2558
+ + if (
2559
+ + selected.length !== 1 ||
2560
+ + tabs.some((c) => tabs.filter((t) => t.name === c.name).length !== 1)
2561
+ + ) {
2562
+ + if (tabs.length) {
2563
+ + w.coverage.gaps.push({
2564
+ + state: '详情',
2565
+ + role: 'tablist',
2566
+ + name: '详情页签',
2567
+ + reason: '无法确定唯一页签组及恢复入口',
2568
+ + });
2569
+ + }
2570
+ + return;
2571
+ + }
2572
+ + const original = selected[0];
2573
+ + const group = w.page
2574
+ + .getByRole('tab', { name: original.name, exact: true })
2575
+ + .locator('xpath=ancestor::*[@role="tablist"][1]');
2576
+ + if ((await group.count()) !== 1) throw Error('详情页签缺少唯一的 tablist 容器');
2577
+ + let changed = false;
2578
+ + const queue = [...tabs];
2579
+ + const seen = new Set();
2580
+ + for (let index = 0; index < queue.length && index < 12; index++) {
2581
+ + const tab = queue[index];
2582
+ + seen.add(tab.name);
2583
+ + w.checkInterrupted();
2584
+ + if ((await group.getByRole('tab', { name: tab.name, exact: true }).count()) !== 1) continue;
2585
+ + const title = `查询详情:${tab.name}页签及关联内容`;
2586
+ + const decision = await selectDiscovery(w.laya, {
2587
+ + title,
2588
+ + evidence: `role=tab;${tab.name};有明确的初始选中页签 ${original.name}`,
2589
+ + });
2590
+ + if (!decision.selected) {
2591
+ + w.coverage.gaps.push({
2592
+ + state: '详情',
2593
+ + role: 'tab',
2594
+ + name: tab.name,
2595
+ + reason: '模型判断证据不足,未执行',
2596
+ + });
2597
+ + continue;
2598
+ + }
2599
+ + activity(w, '正在探索' + title);
2600
+ + const result = await w.runCase(`view-tab-${index + 1}`, title, 'view', async () => {
2601
+ + if (tab.name !== original.name || changed) await w.clickTab(tab.name);
2602
+ + changed = tab.name !== original.name;
2603
+ + await assertRecordDetail(w, { kind: 'assert-record-detail', value: '${recordName}' });
2604
+ + await assertTabPanel(w, {
2605
+ + kind: 'assert-tab-panel',
2606
+ + target: { role: 'tab', name: tab.name },
2607
+ + });
2608
+ + await observeCoverage(w, `详情 / ${tab.name}`, { panel: tab.name });
2609
+ + const controls = (await w.snapshot()).controls;
2610
+ + for (const c of controls
2611
+ + .filter(
2612
+ + (c) => c.role === 'button' && c.inPanel && c.expanded === false && !c.disabled,
2613
+ + )
2614
+ + .slice(0, 4)) {
2615
+ + if (
2616
+ + controls.filter((t) => t.inPanel && t.role === 'button' && t.name === c.name)
2617
+ + .length !== 1
2618
+ + )
2619
+ + continue;
2620
+ + const decision = await selectDiscovery(w.laya, {
2621
+ + title: `展开「${c.name}」查看隐藏控件,再收起恢复`,
2622
+ + evidence: `${tab.name}面板内唯一可见可用的 button「${c.name}」,aria-expanded=false;验证目标为展开状态变为 true 并出现新控件,再恢复为 false;不提交表单或修改记录`,
2623
+ + });
2624
+ + if (decision.selected)
2625
+ + await inspectDisclosure(w, {
2626
+ + kind: 'assert-disclosure',
2627
+ + target: { role: 'button', name: c.name, tab: tab.name },
2628
+ + });
2629
+ + else {
2630
+ + const gap = w.coverage.gaps.find(
2631
+ + (g) => g.state === `详情 / ${tab.name}` && g.name === c.name,
2632
+ + );
2633
+ + if (gap) gap.reason = '模型未选择展开检查;保留为未验证,不强行点击或计入通过';
2634
+ + }
2635
+ + }
2636
+ + });
2637
+ + w.completeCase(result);
2638
+ + if (w.restorationFailure) throw Error(w.restorationFailure);
2639
+ + if (result.status !== '已验证') break;
2640
+ + await exploreRelatedRecords(w, tab, index);
2641
+ + // New page states may reveal more tabs. Re-observe after every verified
2642
+ + // transition instead of declaring coverage from the entry snapshot.
2643
+ + const next = await w.snapshot();
2644
+ + for (const c of next.controls.filter((c) => c.role === 'tab' && c.name && !c.disabled)) {
2645
+ + if (
2646
+ + !seen.has(c.name) &&
2647
+ + !queue.some((t) => t.name === c.name) &&
2648
+ + next.controls.filter((t) => t.role === 'tab' && t.name === c.name).length === 1 &&
2649
+ + (await group.getByRole('tab', { name: c.name, exact: true }).count()) === 1
2650
+ + )
2651
+ + queue.push(c);
2652
+ + }
2653
+ + }
2654
+ + if (queue.length > 12)
2655
+ + w.coverage.gaps.push({
2656
+ + state: '详情',
2657
+ + role: 'tablist',
2658
+ + name: '其余页签',
2659
+ + reason: `达到 12 个页签预算,剩余 ${queue.length - 12} 个未探索`,
2660
+ + });
2661
+ + if (changed) {
2662
+ + const result = await w.runCase(
2663
+ + 'view-return',
2664
+ + '查询详情:恢复初始页签',
2665
+ + 'view',
2666
+ + async () => {
2667
+ + await w.clickTab(original.name);
2668
+ + await assertTabPanel(w, {
2669
+ + kind: 'assert-tab-panel',
2670
+ + target: { role: 'tab', name: original.name },
2671
+ + });
2672
+ + },
2673
+ + );
2674
+ + w.completeCase(result);
2675
+ + if (result.status !== '已验证') throw Error('详情页签恢复失败,停止后续写操作');
2676
+ + }
2677
+ + activity(w, '');
2678
+ +}
2679
+ --- /dev/null
2680
+ +++ b/lib/related-records.mjs
2681
+ @@ -0,0 +1,328 @@
2682
+ +// A bounded relation transaction: select an existing item for our own parent,
2683
+ +// verify it in a fresh session, remove the relation, and verify restoration.
2684
+ +// No business labels, URLs, API endpoints or DOM ids are supplied to the agent.
2685
+ +import { matchReplayTarget } from './replay-model.mjs';
2686
+ +import { selectDiscovery } from './discovery.mjs';
2687
+ +import { assertPageIdentity, waitForVisibleStep } from './page-session.mjs';
2688
+ +import { openOwnedRecord, assertRecordDetail } from './page-exploration.mjs';
2689
+ +
2690
+ +const ADD = /新增|添加|关联|\badd\b|\battach\b|\blink\b/i;
2691
+ +const REMOVE = /^(移除|取消关联|remove(?:\s.+)?|unlink(?:\s.+)?)$/i;
2692
+ +const CONFIRM = /^(确定|确认|保存|confirm|ok|save|add selected)$/i;
2693
+ +const CANCEL = /^(取消|关闭|cancel|close)$/i;
2694
+ +const GRID = 'table,[role="grid"],[role="treegrid"]';
2695
+ +const tabName = (name) => name.replace(/\s*[((]\d+[))]\s*$/u, '').trim();
2696
+ +const unsupported = (reason) => Object.assign(Error(reason), { notApplicable: true });
2697
+ +
2698
+ +export function validateRelatedStep(step) {
2699
+ + if (step.kind !== 'assert-related-records' || step.parent !== '${recordName}')
2700
+ + throw Error('关联测试必须属于本轮创建的父记录');
2701
+ + for (const field of ['tab', 'add', 'remove'])
2702
+ + if (
2703
+ + typeof step.target?.[field] !== 'string' ||
2704
+ + !step.target[field] ||
2705
+ + step.target[field].length > 150
2706
+ + )
2707
+ + throw Error('关联测试缺少明确的语义入口');
2708
+ + if (!ADD.test(step.target.add) || !REMOVE.test(step.target.remove))
2709
+ + throw Error('关联测试只支持添加和移除关联,不能删除全局对象');
2710
+ + if (typeof step.item !== 'string' || step.item.length < 3 || step.item.length > 150)
2711
+ + throw Error('关联用例缺少可回放的数据标识');
2712
+ +}
2713
+ +
2714
+ +async function currentPanel(w, name, select = false) {
2715
+ + const tabs = await w.page.getByRole('tab').all();
2716
+ + const matches = [];
2717
+ + for (const tab of tabs) {
2718
+ + const label = (await tab.getAttribute('aria-label')) || (await tab.innerText());
2719
+ + if (tabName(label) === tabName(name) && (await tab.isVisible())) matches.push(tab);
2720
+ + }
2721
+ + if (matches.length !== 1) throw Error('关联列表所属页签不唯一');
2722
+ + const tab = matches[0];
2723
+ + if (select && (await tab.getAttribute('aria-selected')) !== 'true')
2724
+ + await w.clickTab((await tab.getAttribute('aria-label')) || (await tab.innerText()));
2725
+ + if ((await tab.getAttribute('aria-selected')) !== 'true') throw Error('关联列表页签未选中');
2726
+ + const id = await tab.getAttribute('aria-controls');
2727
+ + const panel = w.page.getByRole('tabpanel').filter({ visible: true });
2728
+ + if ((await panel.count()) !== 1 || (await panel.getAttribute('id')) !== id)
2729
+ + throw Error('关联列表需要唯一的可见 tabpanel');
2730
+ + return panel;
2731
+ +}
2732
+ +
2733
+ +// Merge standard row fragments by aria-rowindex (AG Grid has pinned columns).
2734
+ +// Native tables need no row index. All selection refs come from the observer.
2735
+ +export async function relationRows(grid) {
2736
+ + return grid.evaluate((root) => {
2737
+ + const groups = new Map();
2738
+ + const visible = (e) => {
2739
+ + const r = e.getBoundingClientRect();
2740
+ + return r.width > 0 && r.height > 0 && !e.closest('[hidden],[aria-hidden="true"]');
2741
+ + };
2742
+ + for (const [i, row] of [...root.querySelectorAll('tr,[role="row"]')].entries()) {
2743
+ + if (!visible(row) || row.closest('table,[role="grid"],[role="treegrid"]') !== root)
2744
+ + continue;
2745
+ + const cells = [...row.querySelectorAll('td,[role="gridcell"],[role="cell"]')]
2746
+ + .filter(visible)
2747
+ + .map((e) => e.textContent.replace(/\s+/g, ' ').trim())
2748
+ + .filter(Boolean);
2749
+ + const checkbox = [
2750
+ + ...row.querySelectorAll('input[type="checkbox"],[role="checkbox"]'),
2751
+ + ].find((e) => visible(e) && !e.disabled && e.getAttribute('aria-disabled') !== 'true');
2752
+ + // Ignore header rows, placeholder rows and fixed-column duplicates.
2753
+ + if (row.querySelector('th,[role="columnheader"]') || (!cells.length && !checkbox))
2754
+ + continue;
2755
+ + const key =
2756
+ + row.getAttribute('aria-rowindex') || row.getAttribute('row-index') || `native-${i}`;
2757
+ + const item = groups.get(key) || { cells: [], ref: null, checked: false };
2758
+ + item.cells.push(...cells);
2759
+ + if (checkbox) {
2760
+ + item.ref = checkbox.getAttribute('data-laya-live-ref');
2761
+ + item.checked =
2762
+ + checkbox.checked === true || checkbox.getAttribute('aria-checked') === 'true';
2763
+ + }
2764
+ + groups.set(key, item);
2765
+ + }
2766
+ + return [...groups.values()]
2767
+ + .filter((r) => r.cells.length)
2768
+ + .map((r) => ({ ...r, cells: [...new Set(r.cells)] }));
2769
+ + });
2770
+ +}
2771
+ +
2772
+ +async function relationGrid(root) {
2773
+ + const grids = root.locator(GRID).filter({ visible: true });
2774
+ + if ((await grids.count()) !== 1) throw unsupported('当前面板不是唯一的关联列表');
2775
+ + return grids;
2776
+ +}
2777
+ +
2778
+ +async function clickControl(w, root, name, purpose) {
2779
+ + const snap = await w.snapshot();
2780
+ + const candidates = [];
2781
+ + for (const c of snap.controls.filter(
2782
+ + (c) => c.role === 'button' && c.name === name && !c.disabled,
2783
+ + ))
2784
+ + if (await root.locator(`[data-laya-live-ref="${c.ref}"]`).count()) candidates.push(c);
2785
+ + const c = await matchReplayTarget(w.laya, '点击', name, candidates, w.config);
2786
+ + const locator = snap.frames[c.frame].locator(`[data-laya-live-ref="${c.ref}"]`);
2787
+ + if (purpose)
2788
+ + await w.dispatchClick(locator, {
2789
+ + kind: 'click',
2790
+ + target: { role: 'button', name },
2791
+ + purpose,
2792
+ + });
2793
+ + else await locator.click();
2794
+ + await waitForVisibleStep(w);
2795
+ +}
2796
+ +
2797
+ +async function buttonName(w, root, pattern, { disabled = false } = {}) {
2798
+ + const snap = await w.snapshot();
2799
+ + const matches = [];
2800
+ + for (const c of snap.controls.filter(
2801
+ + (c) => c.role === 'button' && pattern.test(c.name) && (disabled || !c.disabled),
2802
+ + ))
2803
+ + if (await root.locator(`[data-laya-live-ref="${c.ref}"]`).count()) matches.push(c);
2804
+ + if (pattern === CANCEL && matches.length > 1) {
2805
+ + const cancel = matches.filter((c) => /^(取消|cancel)$/i.test(c.name));
2806
+ + if (cancel.length === 1) return cancel[0];
2807
+ + }
2808
+ + if (matches.length !== 1) throw unsupported('关联对话框缺少唯一的确认/取消入口');
2809
+ + return matches[0];
2810
+ +}
2811
+ +
2812
+ +async function selectItem(w, grid, identity) {
2813
+ + await w.snapshot();
2814
+ + const rows = await relationRows(grid);
2815
+ + const matches = rows.filter((r) => r.cells.includes(identity));
2816
+ + if (matches.length !== 1 || matches[0].checked) throw Error('关联目标不唯一或已经选中');
2817
+ + const row = matches[0];
2818
+ + const snap = await w.snapshot();
2819
+ + // Refresh refs after observation; use the logical row as the model label.
2820
+ + const fresh = (await relationRows(grid)).find((r) => r.cells.includes(identity));
2821
+ + const control = snap.controls.find((c) => c.ref === fresh?.ref);
2822
+ + if (!control) throw Error('关联记录缺少可操作的选择控件');
2823
+ + await matchReplayTarget(w.laya, '选择', identity, [{ ...control, name: identity }], w.config);
2824
+ + await snap.frames[control.frame].locator(`[data-laya-live-ref="${control.ref}"]`).check();
2825
+ + await waitForVisibleStep(w);
2826
+ + await w.snapshot();
2827
+ + const selected = (await relationRows(grid)).filter((r) => r.checked);
2828
+ + if (selected.length !== 1 || !selected[0].cells.includes(identity))
2829
+ + throw Error('选择结果与目标记录不符');
2830
+ +}
2831
+ +
2832
+ +async function assertRelation(w, spec, present) {
2833
+ + const panel = await currentPanel(w, spec.target.tab, true);
2834
+ + const grid = await relationGrid(panel);
2835
+ + const deadline = Date.now() + (w.config.assertTimeout || 4000);
2836
+ + do {
2837
+ + w.checkInterrupted();
2838
+ + await w.snapshot();
2839
+ + const rows = await relationRows(grid);
2840
+ + if (present ? rows.length === 1 && rows[0].cells.includes(spec.item) : rows.length === 0)
2841
+ + return;
2842
+ + await w.page.waitForTimeout(100);
2843
+ + } while (Date.now() < deadline);
2844
+ + throw Error(present ? '添加后关联列表未显示唯一目标记录' : '移除后关联列表未恢复为空');
2845
+ +}
2846
+ +
2847
+ +export async function executeRelatedRecords(w, step) {
2848
+ + if (
2849
+ + w.config.readOnly ||
2850
+ + !w.allowed.has('related-records') ||
2851
+ + !w.created ||
2852
+ + w.currentName !== w.variables.recordName
2853
+ + )
2854
+ + throw Error('关联写入仅允许在本轮新建父记录中执行');
2855
+ + await assertRecordDetail(
2856
+ + w,
2857
+ + { kind: 'assert-record-detail', value: '${recordName}' },
2858
+ + { record: false },
2859
+ + );
2860
+ + await assertPageIdentity(w.page, w.identity);
2861
+ + let panel = await currentPanel(w, step.target.tab);
2862
+ + await w.snapshot();
2863
+ + if ((await relationRows(await relationGrid(panel))).length)
2864
+ + throw unsupported('关联列表不为空,未改动已有关系');
2865
+ + const spec = structuredClone(step);
2866
+ + let submitted = false;
2867
+ + const dialogs = w.page.getByRole('dialog').filter({ visible: true });
2868
+ + try {
2869
+ + await clickControl(w, panel, spec.target.add);
2870
+ + await dialogs.waitFor({ state: 'visible', timeout: w.config.assertTimeout || 4000 });
2871
+ + const confirm = await buttonName(w, dialogs, CONFIRM, { disabled: true });
2872
+ + if (!confirm.disabled)
2873
+ + throw unsupported('未选择记录时确认按钮可用,不能证明这是关联选择器');
2874
+ + let selectable = [];
2875
+ + const deadline = Date.now() + (w.config.assertTimeout || 4000);
2876
+ + do {
2877
+ + w.checkInterrupted();
2878
+ + await w.snapshot();
2879
+ + selectable = [];
2880
+ + for (const grid of await dialogs.locator(GRID).filter({ visible: true }).all()) {
2881
+ + const rows = await relationRows(grid);
2882
+ + if (rows.length && rows.every((r) => r.ref && !r.checked))
2883
+ + selectable.push({ grid, rows });
2884
+ + }
2885
+ + if (selectable.length) break;
2886
+ + await w.page.waitForTimeout(100);
2887
+ + } while (Date.now() < deadline);
2888
+ + if (selectable.length !== 1) throw unsupported('未识别到唯一的待选关联列表');
2889
+ + const { grid, rows } = selectable[0];
2890
+ + if (!spec.item) {
2891
+ + const choices = rows
2892
+ + .flatMap((row) => {
2893
+ + const identity = row.cells.find(
2894
+ + (s) =>
2895
+ + s.length >= 3 &&
2896
+ + s.length <= 150 &&
2897
+ + !/^\d{1,2}$/.test(s) &&
2898
+ + rows.filter((r) => r.cells.includes(s)).length === 1,
2899
+ + );
2900
+ + return identity ? [{ ...row, name: identity }] : [];
2901
+ + })
2902
+ + .slice(0, 7);
2903
+ + if (!choices.length) throw unsupported('待选数据没有稳定且唯一的可见标识');
2904
+ + // Test data is reproducible; Laya grounds this chosen identity in
2905
+ + // the live picker below instead of guessing among equivalent rows.
2906
+ + spec.item = choices.toSorted((a, b) => a.name.localeCompare(b.name))[0].name;
2907
+ + }
2908
+ + await selectItem(w, grid, spec.item);
2909
+ + submitted = true;
2910
+ + await clickControl(w, dialogs, confirm.name, 'save');
2911
+ + await dialogs.waitFor({ state: 'hidden', timeout: w.config.pageTimeout || 8000 });
2912
+ + await w.pendingWrites.wait(w.config.pageTimeout || 8000);
2913
+ + await assertRelation(w, spec, true);
2914
+ + await w.page.screenshot({ path: `${w.config.out}/evidence/${w.case.id}-added.png` });
2915
+ + const verify = async (reader, present) => {
2916
+ + await openOwnedRecord(reader, { kind: 'open-owned-record', value: '${recordName}' });
2917
+ + await assertRecordDetail(reader, {
2918
+ + kind: 'assert-record-detail',
2919
+ + value: '${recordName}',
2920
+ + });
2921
+ + await assertRelation(reader, spec, present);
2922
+ + };
2923
+ + spec.query = await w.assertPersisted('${recordName}', true, {
2924
+ + record: false,
2925
+ + query: spec.query,
2926
+ + evidenceId: `${w.case.id}-added`,
2927
+ + inspect: (reader) => verify(reader, true),
2928
+ + });
2929
+ + panel = await currentPanel(w, spec.target.tab);
2930
+ + await selectItem(w, await relationGrid(panel), spec.item);
2931
+ + await clickControl(w, panel, spec.target.remove, 'delete');
2932
+ + if (await dialogs.count()) {
2933
+ + const confirm = await buttonName(w, dialogs, CONFIRM);
2934
+ + await clickControl(w, dialogs, confirm.name, 'confirm');
2935
+ + await dialogs.waitFor({ state: 'hidden' });
2936
+ + }
2937
+ + await w.pendingWrites.wait(w.config.pageTimeout || 8000);
2938
+ + await assertRelation(w, spec, false);
2939
+ + await w.assertPersisted('${recordName}', true, {
2940
+ + record: false,
2941
+ + query: spec.query,
2942
+ + evidenceId: `${w.case.id}-removed`,
2943
+ + inspect: (reader) => verify(reader, false),
2944
+ + });
2945
+ + await assertPageIdentity(w.page, w.identity);
2946
+ + w.record(spec);
2947
+ + w.coverage.gaps = w.coverage.gaps.filter(
2948
+ + (g) =>
2949
+ + !(
2950
+ + g.state === `详情 / ${step.target.tab}` &&
2951
+ + [step.target.add, step.target.remove].includes(g.name)
2952
+ + ),
2953
+ + );
2954
+ + } catch (error) {
2955
+ + if (submitted) {
2956
+ + w.restorationFailure =
2957
+ + '关联写入或独立校验未完成,保留本轮父记录及证据,停止后续写入:' + error.message;
2958
+ + throw Error(w.restorationFailure);
2959
+ + }
2960
+ + try {
2961
+ + if ((await dialogs.count()) === 1) {
2962
+ + const cancel = await buttonName(w, dialogs, CANCEL);
2963
+ + await clickControl(w, dialogs, cancel.name);
2964
+ + await dialogs.waitFor({ state: 'hidden' });
2965
+ + }
2966
+ + } catch (restoreError) {
2967
+ + w.restorationFailure =
2968
+ + error.message + ';关联选择器未恢复,停止后续探索:' + restoreError.message;
2969
+ + throw Error(w.restorationFailure);
2970
+ + }
2971
+ + throw error;
2972
+ + }
2973
+ +}
2974
+ +
2975
+ +export async function exploreRelatedRecords(w, tab, index) {
2976
+ + if (!w.allowed.has('related-records')) return;
2977
+ + const controls = (await w.snapshot()).controls.filter((c) => c.inPanel && c.role === 'button');
2978
+ + const adds = controls.filter((c) => ADD.test(c.name) && !c.disabled);
2979
+ + const removes = controls.filter((c) => REMOVE.test(c.name));
2980
+ + if (adds.length !== 1 || removes.length !== 1) return;
2981
+ + const target = { tab: tab.name, add: adds[0].name, remove: removes[0].name };
2982
+ + const title = `${tabName(tab.name)}:添加关联记录、独立查询并移除`;
2983
+ + const decision = await selectDiscovery(w.laya, {
2984
+ + title,
2985
+ + evidence: `本轮新建父记录详情内有唯一「${target.add}」和「${target.remove}」入口;只支持空关联列表与禁用确认的选择器;验证新增可查询、独立会话持久化、移除后恢复空列表`,
2986
+ + });
2987
+ + if (!decision.selected) {
2988
+ + const gap = w.coverage.gaps.find(
2989
+ + (g) => g.state === `详情 / ${tab.name}` && g.name === target.add,
2990
+ + );
2991
+ + if (gap) gap.reason = '模型未选择关联测试,未提交写入;不能计为已验证';
2992
+ + return;
2993
+ + }
2994
+ + const result = await w.runCase(`related-${index + 1}`, title, 'related-records', () =>
2995
+ + executeRelatedRecords(w, {
2996
+ + kind: 'assert-related-records',
2997
+ + parent: '${recordName}',
2998
+ + target,
2999
+ + }),
3000
+ + );
3001
+ + w.completeCase(result);
3002
+ + if (result.status !== '已验证') {
3003
+ + const gap = w.coverage.gaps.find(
3004
+ + (g) => g.state === `详情 / ${tab.name}` && g.name === target.add,
3005
+ + );
3006
+ + if (gap) gap.reason = result.reason;
3007
+ + }
3008
+ + if (w.restorationFailure) throw Error(w.restorationFailure);
3009
+ +}