gz-laya-pilot 0.1.1 → 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.
@@ -0,0 +1,328 @@
1
+ // A bounded relation transaction: select an existing item for our own parent,
2
+ // verify it in a fresh session, remove the relation, and verify restoration.
3
+ // No business labels, URLs, API endpoints or DOM ids are supplied to the agent.
4
+ import { matchReplayTarget } from './replay-model.mjs';
5
+ import { selectDiscovery } from './discovery.mjs';
6
+ import { assertPageIdentity, waitForVisibleStep } from './page-session.mjs';
7
+ import { openOwnedRecord, assertRecordDetail } from './page-exploration.mjs';
8
+
9
+ const ADD = /新增|添加|关联|\badd\b|\battach\b|\blink\b/i;
10
+ const REMOVE = /^(移除|取消关联|remove(?:\s.+)?|unlink(?:\s.+)?)$/i;
11
+ const CONFIRM = /^(确定|确认|保存|confirm|ok|save|add selected)$/i;
12
+ const CANCEL = /^(取消|关闭|cancel|close)$/i;
13
+ const GRID = 'table,[role="grid"],[role="treegrid"]';
14
+ const tabName = (name) => name.replace(/\s*[((]\d+[))]\s*$/u, '').trim();
15
+ const unsupported = (reason) => Object.assign(Error(reason), { notApplicable: true });
16
+
17
+ export function validateRelatedStep(step) {
18
+ if (step.kind !== 'assert-related-records' || step.parent !== '${recordName}')
19
+ throw Error('关联测试必须属于本轮创建的父记录');
20
+ for (const field of ['tab', 'add', 'remove'])
21
+ if (
22
+ typeof step.target?.[field] !== 'string' ||
23
+ !step.target[field] ||
24
+ step.target[field].length > 150
25
+ )
26
+ throw Error('关联测试缺少明确的语义入口');
27
+ if (!ADD.test(step.target.add) || !REMOVE.test(step.target.remove))
28
+ throw Error('关联测试只支持添加和移除关联,不能删除全局对象');
29
+ if (typeof step.item !== 'string' || step.item.length < 3 || step.item.length > 150)
30
+ throw Error('关联用例缺少可回放的数据标识');
31
+ }
32
+
33
+ async function currentPanel(w, name, select = false) {
34
+ const tabs = await w.page.getByRole('tab').all();
35
+ const matches = [];
36
+ for (const tab of tabs) {
37
+ const label = (await tab.getAttribute('aria-label')) || (await tab.innerText());
38
+ if (tabName(label) === tabName(name) && (await tab.isVisible())) matches.push(tab);
39
+ }
40
+ if (matches.length !== 1) throw Error('关联列表所属页签不唯一');
41
+ const tab = matches[0];
42
+ if (select && (await tab.getAttribute('aria-selected')) !== 'true')
43
+ await w.clickTab((await tab.getAttribute('aria-label')) || (await tab.innerText()));
44
+ if ((await tab.getAttribute('aria-selected')) !== 'true') throw Error('关联列表页签未选中');
45
+ const id = await tab.getAttribute('aria-controls');
46
+ const panel = w.page.getByRole('tabpanel').filter({ visible: true });
47
+ if ((await panel.count()) !== 1 || (await panel.getAttribute('id')) !== id)
48
+ throw Error('关联列表需要唯一的可见 tabpanel');
49
+ return panel;
50
+ }
51
+
52
+ // Merge standard row fragments by aria-rowindex (AG Grid has pinned columns).
53
+ // Native tables need no row index. All selection refs come from the observer.
54
+ export async function relationRows(grid) {
55
+ return grid.evaluate((root) => {
56
+ const groups = new Map();
57
+ const visible = (e) => {
58
+ const r = e.getBoundingClientRect();
59
+ return r.width > 0 && r.height > 0 && !e.closest('[hidden],[aria-hidden="true"]');
60
+ };
61
+ for (const [i, row] of [...root.querySelectorAll('tr,[role="row"]')].entries()) {
62
+ if (!visible(row) || row.closest('table,[role="grid"],[role="treegrid"]') !== root)
63
+ continue;
64
+ const cells = [...row.querySelectorAll('td,[role="gridcell"],[role="cell"]')]
65
+ .filter(visible)
66
+ .map((e) => e.textContent.replace(/\s+/g, ' ').trim())
67
+ .filter(Boolean);
68
+ const checkbox = [
69
+ ...row.querySelectorAll('input[type="checkbox"],[role="checkbox"]'),
70
+ ].find((e) => visible(e) && !e.disabled && e.getAttribute('aria-disabled') !== 'true');
71
+ // Ignore header rows, placeholder rows and fixed-column duplicates.
72
+ if (row.querySelector('th,[role="columnheader"]') || (!cells.length && !checkbox))
73
+ continue;
74
+ const key =
75
+ row.getAttribute('aria-rowindex') || row.getAttribute('row-index') || `native-${i}`;
76
+ const item = groups.get(key) || { cells: [], ref: null, checked: false };
77
+ item.cells.push(...cells);
78
+ if (checkbox) {
79
+ item.ref = checkbox.getAttribute('data-laya-live-ref');
80
+ item.checked =
81
+ checkbox.checked === true || checkbox.getAttribute('aria-checked') === 'true';
82
+ }
83
+ groups.set(key, item);
84
+ }
85
+ return [...groups.values()]
86
+ .filter((r) => r.cells.length)
87
+ .map((r) => ({ ...r, cells: [...new Set(r.cells)] }));
88
+ });
89
+ }
90
+
91
+ async function relationGrid(root) {
92
+ const grids = root.locator(GRID).filter({ visible: true });
93
+ if ((await grids.count()) !== 1) throw unsupported('当前面板不是唯一的关联列表');
94
+ return grids;
95
+ }
96
+
97
+ async function clickControl(w, root, name, purpose) {
98
+ const snap = await w.snapshot();
99
+ const candidates = [];
100
+ for (const c of snap.controls.filter(
101
+ (c) => c.role === 'button' && c.name === name && !c.disabled,
102
+ ))
103
+ if (await root.locator(`[data-laya-live-ref="${c.ref}"]`).count()) candidates.push(c);
104
+ const c = await matchReplayTarget(w.laya, '点击', name, candidates, w.config);
105
+ const locator = snap.frames[c.frame].locator(`[data-laya-live-ref="${c.ref}"]`);
106
+ if (purpose)
107
+ await w.dispatchClick(locator, {
108
+ kind: 'click',
109
+ target: { role: 'button', name },
110
+ purpose,
111
+ });
112
+ else await locator.click();
113
+ await waitForVisibleStep(w);
114
+ }
115
+
116
+ async function buttonName(w, root, pattern, { disabled = false } = {}) {
117
+ const snap = await w.snapshot();
118
+ const matches = [];
119
+ for (const c of snap.controls.filter(
120
+ (c) => c.role === 'button' && pattern.test(c.name) && (disabled || !c.disabled),
121
+ ))
122
+ if (await root.locator(`[data-laya-live-ref="${c.ref}"]`).count()) matches.push(c);
123
+ if (pattern === CANCEL && matches.length > 1) {
124
+ const cancel = matches.filter((c) => /^(取消|cancel)$/i.test(c.name));
125
+ if (cancel.length === 1) return cancel[0];
126
+ }
127
+ if (matches.length !== 1) throw unsupported('关联对话框缺少唯一的确认/取消入口');
128
+ return matches[0];
129
+ }
130
+
131
+ async function selectItem(w, grid, identity) {
132
+ await w.snapshot();
133
+ const rows = await relationRows(grid);
134
+ const matches = rows.filter((r) => r.cells.includes(identity));
135
+ if (matches.length !== 1 || matches[0].checked) throw Error('关联目标不唯一或已经选中');
136
+ const row = matches[0];
137
+ const snap = await w.snapshot();
138
+ // Refresh refs after observation; use the logical row as the model label.
139
+ const fresh = (await relationRows(grid)).find((r) => r.cells.includes(identity));
140
+ const control = snap.controls.find((c) => c.ref === fresh?.ref);
141
+ if (!control) throw Error('关联记录缺少可操作的选择控件');
142
+ await matchReplayTarget(w.laya, '选择', identity, [{ ...control, name: identity }], w.config);
143
+ await snap.frames[control.frame].locator(`[data-laya-live-ref="${control.ref}"]`).check();
144
+ await waitForVisibleStep(w);
145
+ await w.snapshot();
146
+ const selected = (await relationRows(grid)).filter((r) => r.checked);
147
+ if (selected.length !== 1 || !selected[0].cells.includes(identity))
148
+ throw Error('选择结果与目标记录不符');
149
+ }
150
+
151
+ async function assertRelation(w, spec, present) {
152
+ const panel = await currentPanel(w, spec.target.tab, true);
153
+ const grid = await relationGrid(panel);
154
+ const deadline = Date.now() + (w.config.assertTimeout || 4000);
155
+ do {
156
+ w.checkInterrupted();
157
+ await w.snapshot();
158
+ const rows = await relationRows(grid);
159
+ if (present ? rows.length === 1 && rows[0].cells.includes(spec.item) : rows.length === 0)
160
+ return;
161
+ await w.page.waitForTimeout(100);
162
+ } while (Date.now() < deadline);
163
+ throw Error(present ? '添加后关联列表未显示唯一目标记录' : '移除后关联列表未恢复为空');
164
+ }
165
+
166
+ export async function executeRelatedRecords(w, step) {
167
+ if (
168
+ w.config.readOnly ||
169
+ !w.allowed.has('related-records') ||
170
+ !w.created ||
171
+ w.currentName !== w.variables.recordName
172
+ )
173
+ throw Error('关联写入仅允许在本轮新建父记录中执行');
174
+ await assertRecordDetail(
175
+ w,
176
+ { kind: 'assert-record-detail', value: '${recordName}' },
177
+ { record: false },
178
+ );
179
+ await assertPageIdentity(w.page, w.identity);
180
+ let panel = await currentPanel(w, step.target.tab);
181
+ await w.snapshot();
182
+ if ((await relationRows(await relationGrid(panel))).length)
183
+ throw unsupported('关联列表不为空,未改动已有关系');
184
+ const spec = structuredClone(step);
185
+ let submitted = false;
186
+ const dialogs = w.page.getByRole('dialog').filter({ visible: true });
187
+ try {
188
+ await clickControl(w, panel, spec.target.add);
189
+ await dialogs.waitFor({ state: 'visible', timeout: w.config.assertTimeout || 4000 });
190
+ const confirm = await buttonName(w, dialogs, CONFIRM, { disabled: true });
191
+ if (!confirm.disabled)
192
+ throw unsupported('未选择记录时确认按钮可用,不能证明这是关联选择器');
193
+ let selectable = [];
194
+ const deadline = Date.now() + (w.config.assertTimeout || 4000);
195
+ do {
196
+ w.checkInterrupted();
197
+ await w.snapshot();
198
+ selectable = [];
199
+ for (const grid of await dialogs.locator(GRID).filter({ visible: true }).all()) {
200
+ const rows = await relationRows(grid);
201
+ if (rows.length && rows.every((r) => r.ref && !r.checked))
202
+ selectable.push({ grid, rows });
203
+ }
204
+ if (selectable.length) break;
205
+ await w.page.waitForTimeout(100);
206
+ } while (Date.now() < deadline);
207
+ if (selectable.length !== 1) throw unsupported('未识别到唯一的待选关联列表');
208
+ const { grid, rows } = selectable[0];
209
+ if (!spec.item) {
210
+ const choices = rows
211
+ .flatMap((row) => {
212
+ const identity = row.cells.find(
213
+ (s) =>
214
+ s.length >= 3 &&
215
+ s.length <= 150 &&
216
+ !/^\d{1,2}$/.test(s) &&
217
+ rows.filter((r) => r.cells.includes(s)).length === 1,
218
+ );
219
+ return identity ? [{ ...row, name: identity }] : [];
220
+ })
221
+ .slice(0, 7);
222
+ if (!choices.length) throw unsupported('待选数据没有稳定且唯一的可见标识');
223
+ // Test data is reproducible; Laya grounds this chosen identity in
224
+ // the live picker below instead of guessing among equivalent rows.
225
+ spec.item = choices.toSorted((a, b) => a.name.localeCompare(b.name))[0].name;
226
+ }
227
+ await selectItem(w, grid, spec.item);
228
+ submitted = true;
229
+ await clickControl(w, dialogs, confirm.name, 'save');
230
+ await dialogs.waitFor({ state: 'hidden', timeout: w.config.pageTimeout || 8000 });
231
+ await w.pendingWrites.wait(w.config.pageTimeout || 8000);
232
+ await assertRelation(w, spec, true);
233
+ await w.page.screenshot({ path: `${w.config.out}/evidence/${w.case.id}-added.png` });
234
+ const verify = async (reader, present) => {
235
+ await openOwnedRecord(reader, { kind: 'open-owned-record', value: '${recordName}' });
236
+ await assertRecordDetail(reader, {
237
+ kind: 'assert-record-detail',
238
+ value: '${recordName}',
239
+ });
240
+ await assertRelation(reader, spec, present);
241
+ };
242
+ spec.query = await w.assertPersisted('${recordName}', true, {
243
+ record: false,
244
+ query: spec.query,
245
+ evidenceId: `${w.case.id}-added`,
246
+ inspect: (reader) => verify(reader, true),
247
+ });
248
+ panel = await currentPanel(w, spec.target.tab);
249
+ await selectItem(w, await relationGrid(panel), spec.item);
250
+ await clickControl(w, panel, spec.target.remove, 'delete');
251
+ if (await dialogs.count()) {
252
+ const confirm = await buttonName(w, dialogs, CONFIRM);
253
+ await clickControl(w, dialogs, confirm.name, 'confirm');
254
+ await dialogs.waitFor({ state: 'hidden' });
255
+ }
256
+ await w.pendingWrites.wait(w.config.pageTimeout || 8000);
257
+ await assertRelation(w, spec, false);
258
+ await w.assertPersisted('${recordName}', true, {
259
+ record: false,
260
+ query: spec.query,
261
+ evidenceId: `${w.case.id}-removed`,
262
+ inspect: (reader) => verify(reader, false),
263
+ });
264
+ await assertPageIdentity(w.page, w.identity);
265
+ w.record(spec);
266
+ w.coverage.gaps = w.coverage.gaps.filter(
267
+ (g) =>
268
+ !(
269
+ g.state === `详情 / ${step.target.tab}` &&
270
+ [step.target.add, step.target.remove].includes(g.name)
271
+ ),
272
+ );
273
+ } catch (error) {
274
+ if (submitted) {
275
+ w.restorationFailure =
276
+ '关联写入或独立校验未完成,保留本轮父记录及证据,停止后续写入:' + error.message;
277
+ throw Error(w.restorationFailure);
278
+ }
279
+ try {
280
+ if ((await dialogs.count()) === 1) {
281
+ const cancel = await buttonName(w, dialogs, CANCEL);
282
+ await clickControl(w, dialogs, cancel.name);
283
+ await dialogs.waitFor({ state: 'hidden' });
284
+ }
285
+ } catch (restoreError) {
286
+ w.restorationFailure =
287
+ error.message + ';关联选择器未恢复,停止后续探索:' + restoreError.message;
288
+ throw Error(w.restorationFailure);
289
+ }
290
+ throw error;
291
+ }
292
+ }
293
+
294
+ export async function exploreRelatedRecords(w, tab, index) {
295
+ if (!w.allowed.has('related-records')) return;
296
+ const controls = (await w.snapshot()).controls.filter((c) => c.inPanel && c.role === 'button');
297
+ const adds = controls.filter((c) => ADD.test(c.name) && !c.disabled);
298
+ const removes = controls.filter((c) => REMOVE.test(c.name));
299
+ if (adds.length !== 1 || removes.length !== 1) return;
300
+ const target = { tab: tab.name, add: adds[0].name, remove: removes[0].name };
301
+ const title = `${tabName(tab.name)}:添加关联记录、独立查询并移除`;
302
+ const decision = await selectDiscovery(w.laya, {
303
+ title,
304
+ evidence: `本轮新建父记录详情内有唯一「${target.add}」和「${target.remove}」入口;只支持空关联列表与禁用确认的选择器;验证新增可查询、独立会话持久化、移除后恢复空列表`,
305
+ });
306
+ if (!decision.selected) {
307
+ const gap = w.coverage.gaps.find(
308
+ (g) => g.state === `详情 / ${tab.name}` && g.name === target.add,
309
+ );
310
+ if (gap) gap.reason = '模型未选择关联测试,未提交写入;不能计为已验证';
311
+ return;
312
+ }
313
+ const result = await w.runCase(`related-${index + 1}`, title, 'related-records', () =>
314
+ executeRelatedRecords(w, {
315
+ kind: 'assert-related-records',
316
+ parent: '${recordName}',
317
+ target,
318
+ }),
319
+ );
320
+ w.completeCase(result);
321
+ if (result.status !== '已验证') {
322
+ const gap = w.coverage.gaps.find(
323
+ (g) => g.state === `详情 / ${tab.name}` && g.name === target.add,
324
+ );
325
+ if (gap) gap.reason = result.reason;
326
+ }
327
+ if (w.restorationFailure) throw Error(w.restorationFailure);
328
+ }
@@ -10,7 +10,21 @@ export function writePrivateJson(file, value) {
10
10
  mode: 0o600,
11
11
  flag: 'wx',
12
12
  });
13
- fs.renameSync(temporary, file);
13
+ // On Windows, a concurrent status reader or virus scanner can briefly
14
+ // deny replacement. Retry the atomic rename; never delete the last checkpoint.
15
+ for (let attempt = 0; ; attempt++) {
16
+ try {
17
+ fs.renameSync(temporary, file);
18
+ break;
19
+ } catch (error) {
20
+ if (
21
+ process.platform !== 'win32' ||
22
+ !['EPERM', 'EACCES', 'EBUSY'].includes(error.code) ||
23
+ attempt >= 5
24
+ ) throw error;
25
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10 * 2 ** attempt);
26
+ }
27
+ }
14
28
  } finally {
15
29
  if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
16
30
  }
@@ -58,7 +58,11 @@ export async function chooseTestOption(laya, label, options) {
58
58
 
59
59
  // Laya selects a data recipe from observed field semantics. The executor creates
60
60
  // the value, so record identifiers remain unique and replay can bind fresh data.
61
- export async function chooseFieldValue(laya, field, { name = '${recordName}', index = 0 } = {}) {
61
+ export async function chooseFieldValue(
62
+ laya,
63
+ field,
64
+ { name = '${recordName}', index = 0, identity = false } = {},
65
+ ) {
62
66
  const recipes = {
63
67
  账号: '填写登录账号、登录账户或 account 标识',
64
68
  名称: '填写名称、姓名、用户名或标题',
@@ -75,8 +79,17 @@ export async function chooseFieldValue(laya, field, { name = '${recordName}', in
75
79
  const criteria = typedRecipe
76
80
  ? { [typedRecipe]: recipes[typedRecipe], 停止: recipes.停止 }
77
81
  : recipes;
82
+ if (field.type === 'number') {
83
+ // Classify the observed input contract instead of inferring a business
84
+ // meaning from its label. This also applies to unfamiliar/localized labels.
85
+ criteria.数值 = '此字段是数字输入框,需要填写满足页面最小值和最大值约束的数字';
86
+ criteria.停止 = '页面证据不足,不能判断字段需要填写哪类数据';
87
+ }
78
88
  const decision = await laya.choose(
79
- `填写「${field.label || field.placeholder}」${field.placeholder ? ',提示:' + field.placeholder : ''}${field.type && !['input', 'text', 'textarea'].includes(field.type) ? ',输入类型:' + field.type : ''}`,
89
+ // The caller has already located the name/title field. Length hints are
90
+ // validation constraints, not a competing field purpose. Retain them in
91
+ // evidence and browser validation, with all semantic recipes/refusal intact.
92
+ `填写「${field.label || field.placeholder}」${field.placeholder && !identity ? ',提示:' + field.placeholder : ''}${field.type && !['input', 'text', 'textarea'].includes(field.type) ? ',输入类型:' + field.type : ''}`,
80
93
  criteria,
81
94
  { phase: 'form-field', field: field.label, input: { ...field, value: undefined } },
82
95
  );
@@ -1,3 +1,5 @@
1
+ import { validateDiscovery } from './discovery.mjs';
2
+
1
3
  export const OPERATIONS = [
2
4
  'tabs',
3
5
  'tab-switch',
@@ -8,6 +10,7 @@ export const OPERATIONS = [
8
10
  'create',
9
11
  'search',
10
12
  'view',
13
+ 'related-records',
11
14
  'edit',
12
15
  'delete',
13
16
  'discover',
@@ -30,7 +33,7 @@ export function workflowPolicy(config) {
30
33
  if (config.readOnly && operations.some((op) => !READ_OPERATIONS.includes(op)))
31
34
  throw Error('--read-only 只允许 tabs,tab-switch,table,filters');
32
35
  const allowed = new Set(operations);
33
- for (const op of ['search', 'view', 'edit', 'delete']) {
36
+ for (const op of ['search', 'view', 'related-records', 'edit', 'delete']) {
34
37
  if (allowed.has(op) && !allowed.has('create'))
35
38
  throw Error(`${op} 依赖本轮 create,请同时选择 create;只读检查使用 table,filters`);
36
39
  }
@@ -43,6 +46,10 @@ export function enforceReplayPolicy(file, config) {
43
46
  if (!allowed.has(c.operation)) throw Error(`回放用例 ${c.id} 超出 --operations 范围`);
44
47
  if (config.readOnly) {
45
48
  for (const step of c.steps) {
49
+ if (c.operation === 'filters' && step.kind === 'assert-discovery') {
50
+ validateDiscovery(step, { readOnly: true });
51
+ continue;
52
+ }
46
53
  const assertion = [
47
54
  'assert-control',
48
55
  'assert-selected',