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,42 @@
1
+ /** UI projection of upstream reports. Execution and workbook grammar remain upstream-owned. */
2
+ export interface CaseEvidence {
3
+ id: string;
4
+ title: string;
5
+ operation?: string;
6
+ state: 'passed' | 'failed' | 'skipped';
7
+ reason: string;
8
+ assertions: {
9
+ step: number;
10
+ expected: string;
11
+ actual: string;
12
+ passed: boolean;
13
+ }[];
14
+ screenshot?: string;
15
+ errors: string[];
16
+ cleanup?: string;
17
+ }
18
+ export interface AgentStatus {
19
+ id?: string;
20
+ state: 'idle' | 'running' | 'passed' | 'partial' | 'failed' | 'stopped';
21
+ mode: 'explore' | 'replay';
22
+ message: string;
23
+ cases: CaseEvidence[];
24
+ decisions: number;
25
+ workbook?: string;
26
+ trace?: string;
27
+ coverage?: {
28
+ states: string[];
29
+ gaps: {
30
+ state: string;
31
+ role: string;
32
+ name: string;
33
+ reason: string;
34
+ }[];
35
+ };
36
+ }
37
+ export interface AgentCapabilities {
38
+ configured: boolean;
39
+ message: string;
40
+ targets: string[];
41
+ }
42
+ export declare function testUrl(value: unknown): string;
@@ -0,0 +1,9 @@
1
+ export function testUrl(value) {
2
+ if (typeof value !== 'string' || value.length > 2000)
3
+ throw Error('测试地址格式错误');
4
+ const url = new URL(value);
5
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password)
6
+ throw Error('测试地址必须为不含凭据的 HTTP(S) 地址');
7
+ return url.href;
8
+ }
9
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.js","sourceRoot":"","sources":["../../src/agent/schema.ts"],"names":[],"mappings":"AA+BA,MAAM,UAAU,OAAO,CAAC,KAAc;IACpC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,GAAG,IAAI;QAAE,MAAM,KAAK,CAAC,UAAU,CAAC,CAAC;IAC9E,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC;IAC3B,IAAI,CAAC,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,GAAG,CAAC,QAAQ,IAAI,GAAG,CAAC,QAAQ;QAC7E,MAAM,KAAK,CAAC,yBAAyB,CAAC,CAAC;IACzC,OAAO,GAAG,CAAC,IAAI,CAAC;AAClB,CAAC"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,102 @@
1
+ import { fileURLToPath } from 'node:url';
2
+ import path from 'node:path';
3
+ import { spawn } from 'node:child_process';
4
+ const root = fileURLToPath(new URL('../../vendor/laya-pilot/', import.meta.url));
5
+ let started = false, cancelled = false;
6
+ process.on('disconnect', () => {
7
+ cancelled = true;
8
+ });
9
+ process.on('message', async (message) => {
10
+ if (message.type === 'stop') {
11
+ cancelled = true;
12
+ return;
13
+ }
14
+ if (started || !message.options)
15
+ return;
16
+ started = true;
17
+ const options = message.options;
18
+ const timer = setInterval(() => {
19
+ if (cancelled && process.listenerCount('SIGTERM'))
20
+ process.emit('SIGTERM');
21
+ }, 200);
22
+ try {
23
+ // Import exact vendored upstream source; the npm facade owns configuration, not workflow logic.
24
+ const upstream = (await import(new URL('../../vendor/laya-pilot/lib/workflow.mjs', import.meta.url).href));
25
+ if (cancelled)
26
+ throw Error('任务已取消');
27
+ if (options.workbook) {
28
+ const workbook = await new Promise((resolve, reject) => {
29
+ const child = spawn(options.python, [path.join(root, 'lib/workflow_excel.py'), 'read'], {
30
+ windowsHide: true,
31
+ stdio: ['pipe', 'pipe', 'pipe'],
32
+ timeout: 60000,
33
+ });
34
+ let output = '', error = '';
35
+ child.stdout.on('data', (chunk) => {
36
+ output += chunk;
37
+ });
38
+ child.stderr.on('data', (chunk) => {
39
+ error = (error + chunk).slice(-1000);
40
+ });
41
+ child.on('error', reject);
42
+ child.stdin.on('error', reject);
43
+ child.once('close', (code) => {
44
+ if (code)
45
+ reject(Error(error));
46
+ else {
47
+ try {
48
+ resolve(JSON.parse(output));
49
+ }
50
+ catch {
51
+ reject(Error('Excel 元数据无效'));
52
+ }
53
+ }
54
+ });
55
+ child.stdin.end(JSON.stringify({ path: options.workbook }));
56
+ });
57
+ const saved = upstream.validateWorkflow(workbook);
58
+ const target = new URL(options.url);
59
+ target.search = '';
60
+ target.hash = '';
61
+ if (new URL(saved.moduleUrl).href !== target.href)
62
+ throw Error('Excel 入口与宿主授权地址不一致');
63
+ }
64
+ const summary = await upstream.runWorkflow({
65
+ url: options.url,
66
+ out: options.outputDir,
67
+ caseFile: options.workbook ?? path.join(options.outputDir, 'cases.xlsx'),
68
+ python: options.python,
69
+ model: options.model,
70
+ provider: 'local',
71
+ browserProvider: 'playwright',
72
+ browserChannel: options.channel ?? 'chrome',
73
+ headless: !options.headed,
74
+ readOnly: !options.allowWrite,
75
+ allowWrite: options.allowWrite === true,
76
+ authState: options.authState ?? '',
77
+ authCheck: options.authCheck ?? '',
78
+ manualLogin: options.manualLogin ?? false,
79
+ pageTimeout: 18000,
80
+ assertTimeout: 4000,
81
+ delay: 180,
82
+ maxSteps: 100,
83
+ minProbability: 0.68,
84
+ minMargin: 0.18,
85
+ data: {},
86
+ cases: [],
87
+ }, options.workbook ? 'execute' : 'generate', async () => {
88
+ throw Error('请在宿主配置登录态或使用手动登录');
89
+ }, root);
90
+ process.exitCode = summary.exitCode ?? 1;
91
+ }
92
+ catch (error) {
93
+ if (process.connected)
94
+ process.send?.({ error: error instanceof Error ? error.message : String(error) });
95
+ process.exitCode = 1;
96
+ }
97
+ finally {
98
+ clearInterval(timer);
99
+ process.disconnect?.();
100
+ }
101
+ });
102
+ //# sourceMappingURL=worker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker.js","sourceRoot":"","sources":["../../src/agent/worker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAI3C,MAAM,IAAI,GAAG,aAAa,CAAC,IAAI,GAAG,CAAC,0BAA0B,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AACjF,IAAI,OAAO,GAAG,KAAK,EACjB,SAAS,GAAG,KAAK,CAAC;AACpB,OAAO,CAAC,EAAE,CAAC,YAAY,EAAE,GAAG,EAAE;IAC5B,SAAS,GAAG,IAAI,CAAC;AACnB,CAAC,CAAC,CAAC;AACH,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,KAAK,EAAE,OAAiD,EAAE,EAAE;IAChF,I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;YACnB,OAAO,CAAC,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACpF,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;IACvB,CAAC;YAAS,CAAC;QACT,aAAa,CAAC,KAAK,CAAC,CAAC;QACrB,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC;IACzB,CAAC;AACH,CAAC,CAAC,CAAC"}
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ // Preserve all upstream CLI modes and workbook behavior; use UTF-8 for Windows Python IPC.
3
+ process.env.PYTHONIOENCODING = 'utf-8';
4
+ process.env.PYTHONUTF8 = '1';
5
+ await import(new URL('../vendor/laya-pilot/runner.mjs', import.meta.url).href);
6
+ export {};
7
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA,2FAA2F;AAC3F,OAAO,CAAC,GAAG,CAAC,gBAAgB,GAAG,OAAO,CAAC;AACvC,OAAO,CAAC,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC;AAC7B,MAAM,MAAM,CAAC,IAAI,GAAG,CAAC,iCAAiC,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC"}
package/dist/index.d.ts CHANGED
@@ -5,3 +5,6 @@ export { openBrowser } from './browser.js';
5
5
  export { waitForReady } from './readiness.js';
6
6
  export { createApiDecision, decodeDecision, type Decision, type Decide } from './decision.js';
7
7
  export { chooseStep } from './planner.js';
8
+ export { runAgent, type AgentOptions } from './agent/run.js';
9
+ export { createAgentBridge, type AgentBridgeOptions, type AgentBridgeTarget } from './agent/bridge.js';
10
+ export type { AgentStatus, AgentCapabilities } from './agent/schema.js';
package/dist/index.js CHANGED
@@ -5,4 +5,6 @@ export { openBrowser } from './browser.js';
5
5
  export { waitForReady } from './readiness.js';
6
6
  export { createApiDecision, decodeDecision } from './decision.js';
7
7
  export { chooseStep } from './planner.js';
8
+ export { runAgent } from './agent/run.js';
9
+ export { createAgentBridge } from './agent/bridge.js';
8
10
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,OAAO,EAAE,OAAO,EAAsB,MAAM,aAAa,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAA8B,MAAM,eAAe,CAAC;AAC9F,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,OAAO,EAAE,OAAO,EAAsB,MAAM,aAAa,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAA8B,MAAM,eAAe,CAAC;AAC9F,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAqB,MAAM,gBAAgB,CAAC;AAC7D,OAAO,EAAE,iBAAiB,EAAmD,MAAM,mBAAmB,CAAC"}
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "gz-laya-pilot",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Functional TypeScript browser testing runtime adapted from LayaPilot",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "files": [
8
8
  "dist",
9
9
  "src",
10
+ "vendor",
10
11
  "NOTICE.md",
11
12
  "README.md",
12
13
  "LICENSE"
@@ -15,11 +16,18 @@
15
16
  "node": ">=22"
16
17
  },
17
18
  "sideEffects": false,
19
+ "bin": {
20
+ "gz-laya-pilot": "./dist/cli.js"
21
+ },
18
22
  "exports": {
19
23
  ".": {
20
24
  "types": "./dist/index.d.ts",
21
25
  "import": "./dist/index.js"
22
26
  },
27
+ "./agent-schema": {
28
+ "types": "./dist/agent/schema.d.ts",
29
+ "import": "./dist/agent/schema.js"
30
+ },
23
31
  "./schema": {
24
32
  "types": "./dist/schema.d.ts",
25
33
  "import": "./dist/schema.js"
@@ -32,15 +40,15 @@
32
40
  "scripts": {
33
41
  "build": "tsc -p tsconfig.json",
34
42
  "prepack": "npm run build",
35
- "test": "node --test tests/*.test.mjs"
43
+ "test": "node --test tests/*.test.mjs && node --test --test-concurrency=1 vendor/laya-pilot/tests/*.test.mjs"
36
44
  },
37
45
  "dependencies": {
38
- "playwright": "1.62.1",
39
- "dom-accessibility-api": "^0.7.1"
46
+ "dom-accessibility-api": "^0.7.1",
47
+ "playwright": "1.62.1"
40
48
  },
41
49
  "devDependencies": {
42
- "typescript": "~5.9.3",
43
- "@types/node": "^24.12.0"
50
+ "@types/node": "^24.12.0",
51
+ "typescript": "~5.9.3"
44
52
  },
45
53
  "publishConfig": {
46
54
  "access": "public",
@@ -0,0 +1,180 @@
1
+ import { existsSync, createReadStream } from 'node:fs';
2
+ import { mkdir, writeFile } from 'node:fs/promises';
3
+ import { randomUUID } from 'node:crypto';
4
+ import path from 'node:path';
5
+ import type { IncomingMessage, ServerResponse } from 'node:http';
6
+ import { testUrl, type AgentStatus } from './schema.js';
7
+ import { runAgent } from './run.js';
8
+
9
+ export interface AgentBridgeTarget {
10
+ url: string;
11
+ authState?: string;
12
+ authCheck?: string;
13
+ }
14
+ export interface AgentBridgeOptions {
15
+ targets: AgentBridgeTarget[];
16
+ outputDir: string;
17
+ python: string;
18
+ model: string;
19
+ channel?: string;
20
+ headed?: boolean;
21
+ isBusy?: () => boolean;
22
+ }
23
+ /** Local HTTP adapter shared by React and SDK. All test decisions/execution remain upstream. */
24
+ export function createAgentBridge(options: AgentBridgeOptions) {
25
+ const targets = options.targets.map((t) => ({ ...t, url: testUrl(t.url) }));
26
+ const root = path.resolve(options.outputDir);
27
+ let active: Promise<void> | undefined, controller: AbortController | undefined;
28
+ let status: AgentStatus = {
29
+ state: 'idle',
30
+ mode: 'explore',
31
+ message: '尚未探索',
32
+ cases: [],
33
+ decisions: 0,
34
+ };
35
+ const stop = () => controller?.abort();
36
+ const middleware = async (req: IncomingMessage, res: ServerResponse, next: () => void) => {
37
+ const url = new URL(req.url ?? '/', 'http://localhost');
38
+ if (!['/status', '/explore', '/replay', '/stop', '/artifact'].includes(url.pathname))
39
+ return next();
40
+ const send = (code: number, body: unknown) => {
41
+ res.statusCode = code;
42
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
43
+ res.setHeader('Cache-Control', 'no-store');
44
+ res.end(JSON.stringify(body));
45
+ };
46
+ const host = req.headers.host ?? '';
47
+ if (
48
+ !['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(req.socket.remoteAddress ?? '') ||
49
+ !/^(localhost|127\.0\.0\.1|\[::1\]):\d+$/.test(host)
50
+ )
51
+ return send(403, { message: '执行服务仅允许本机访问' });
52
+ if (req.headers.origin && req.headers.origin !== `http://${host}`)
53
+ return send(403, { message: '仅接受同源访问' });
54
+ if (req.method === 'GET' && url.pathname === '/status') {
55
+ const configured =
56
+ existsSync(options.python) && existsSync(options.model) && targets.length > 0;
57
+ return send(200, {
58
+ ...status,
59
+ capabilities: {
60
+ configured,
61
+ targets: targets.map((t) => t.url),
62
+ message: configured
63
+ ? '本地 Laya 已配置 · 上游 LayaPilot 引擎'
64
+ : '请在宿主配置 LAYA_PYTHON、LAYA_MODEL 和 LAYA_TEST_URLS',
65
+ },
66
+ });
67
+ }
68
+ if (req.method === 'GET' && url.pathname === '/artifact') {
69
+ const id = url.searchParams.get('id') ?? '',
70
+ file = url.searchParams.get('file') ?? '';
71
+ if (
72
+ !/^[\da-f-]{36}$/.test(id) ||
73
+ !/^(cases\.xlsx|results\.xlsx|results\.json|decisions\.ndjson|checkpoint\.json|trace\.zip|persistence-[a-zA-Z0-9_-]{1,85}\.zip|evidence\/[a-zA-Z0-9_-]{1,150}\.png)$/.test(
74
+ file,
75
+ )
76
+ )
77
+ return send(400, { message: '无效的报告文件' });
78
+ const filename = path.join(root, id, file === 'results.xlsx' ? '执行结果.xlsx' : file);
79
+ if (!existsSync(filename)) return send(404, { message: '报告尚未生成' });
80
+ res.setHeader(
81
+ 'Content-Type',
82
+ file.endsWith('.png') ? 'image/png' : 'application/octet-stream',
83
+ );
84
+ res.setHeader('Content-Disposition', `attachment; filename="${path.basename(file)}"`);
85
+ res.setHeader('Cache-Control', 'no-store');
86
+ res.setHeader('X-Content-Type-Options', 'nosniff');
87
+ const stream = createReadStream(filename);
88
+ stream.on('error', () => res.destroy());
89
+ stream.pipe(res);
90
+ return;
91
+ }
92
+ if (req.method !== 'POST' || !['/explore', '/replay', '/stop'].includes(url.pathname))
93
+ return send(405, { message: '请求方法不支持' });
94
+ if (
95
+ req.headers.origin !== `http://${host}` ||
96
+ req.headers['x-laya-pilot'] !== 'agent-v1' ||
97
+ !req.headers['content-type']?.startsWith('application/json')
98
+ )
99
+ return send(403, { message: '仅接受页面内同源请求' });
100
+ if (url.pathname === '/stop') {
101
+ stop();
102
+ return send(200, status);
103
+ }
104
+ if (active || options.isBusy?.()) return send(409, { message: '已有测试正在运行' });
105
+ try {
106
+ let body = '';
107
+ for await (const chunk of req) {
108
+ body += chunk;
109
+ if (Buffer.byteLength(body) > 3 * 1024 * 1024) throw Error('请求超过 3 MB');
110
+ }
111
+ const input = JSON.parse(body),
112
+ target = targets.find((t) => t.url === testUrl(input.url));
113
+ if (!target) throw Error('入口不在宿主配置的测试地址列表中');
114
+ if (typeof input.allowWrite !== 'boolean') throw Error('需要明确选择是否允许创建测试数据');
115
+ if (!existsSync(options.python) || !existsSync(options.model))
116
+ throw Error('生成和回放均需配置本地 Laya');
117
+ if (active || options.isBusy?.()) return send(409, { message: '已有测试正在运行' });
118
+ const replay = url.pathname === '/replay';
119
+ let content: Buffer | undefined;
120
+ if (replay) {
121
+ if (typeof input.workbook !== 'string' || !/^[a-z\d+/]+={0,2}$/i.test(input.workbook))
122
+ throw Error('请上传有效的 Excel 用例');
123
+ content = Buffer.from(input.workbook, 'base64');
124
+ if (
125
+ content.length > 2 * 1024 * 1024 ||
126
+ content.length < 4 ||
127
+ content.readUInt32LE(0) !== 0x04034b50
128
+ )
129
+ throw Error('仅支持 2 MB 内的 xlsx 用例');
130
+ }
131
+ const id = randomUUID(),
132
+ outputDir = path.join(root, id);
133
+ controller = new AbortController();
134
+ const signal = controller.signal;
135
+ status = {
136
+ id,
137
+ state: 'running',
138
+ mode: replay ? 'replay' : 'explore',
139
+ message: '正在启动上游 LayaPilot',
140
+ cases: [],
141
+ decisions: 0,
142
+ };
143
+ active = (async () => {
144
+ try {
145
+ await mkdir(outputDir, { recursive: true });
146
+ const workbook = content ? path.join(outputDir, 'uploaded.xlsx') : undefined;
147
+ if (workbook && content) await writeFile(workbook, content);
148
+ const result = await runAgent({
149
+ ...target,
150
+ outputDir,
151
+ python: options.python,
152
+ model: options.model,
153
+ channel: options.channel,
154
+ workbook,
155
+ allowWrite: input.allowWrite,
156
+ headed: options.headed ?? false,
157
+ signal,
158
+ onProgress: (value) => {
159
+ status = { ...value, id };
160
+ },
161
+ });
162
+ status = { ...result, id };
163
+ } catch (error) {
164
+ status = {
165
+ ...status,
166
+ state: signal.aborted ? 'stopped' : 'failed',
167
+ message: error instanceof Error ? error.message : String(error),
168
+ };
169
+ } finally {
170
+ active = undefined;
171
+ controller = undefined;
172
+ }
173
+ })();
174
+ send(202, status);
175
+ } catch (error) {
176
+ send(400, { message: error instanceof Error ? error.message : '无法启动测试' });
177
+ }
178
+ };
179
+ return { middleware, stop, isRunning: () => Boolean(active) };
180
+ }
@@ -0,0 +1,139 @@
1
+ import type { AgentStatus, CaseEvidence } from './schema.js';
2
+
3
+ export interface UpstreamStep {
4
+ kind: string;
5
+ value?: unknown;
6
+ target?: { name?: string; label?: string };
7
+ spec?: { title?: string };
8
+ }
9
+ export interface UpstreamCase {
10
+ id: string;
11
+ title: string;
12
+ operation?: string;
13
+ status: string;
14
+ reason: string;
15
+ steps: UpstreamStep[];
16
+ evidence?: string;
17
+ failedStep?: { number: number; action: string; target?: string } | null;
18
+ browserEvents?: { type?: string; message?: string; url?: string }[];
19
+ }
20
+ export interface UpstreamReport {
21
+ runStatus?: string;
22
+ status?: string;
23
+ error?: string;
24
+ exitCode?: number;
25
+ results: UpstreamCase[];
26
+ activeCase?: { title?: string };
27
+ activity?: string;
28
+ caseFile?: string;
29
+ retainedRecord?: string;
30
+ pendingWrite?: unknown;
31
+ metrics?: { modelCalls?: number };
32
+ runtime?: { currentName?: string };
33
+ coverage?: AgentStatus['coverage'];
34
+ }
35
+ function assertionTitle(step: UpstreamStep): string {
36
+ if (step.spec?.title) return step.spec.title;
37
+ const target = step.target?.label ?? step.target?.name ?? '';
38
+ const value = Array.isArray(step.value)
39
+ ? step.value.join('、')
40
+ : typeof step.value === 'string'
41
+ ? step.value
42
+ .replaceAll('${recordName}', '本轮测试记录')
43
+ .replaceAll('${updatedName}', '修改后的本轮记录')
44
+ : '';
45
+ const titles: Record<string, string> = {
46
+ 'assert-control': `控件可见且唯一:${target}`,
47
+ 'assert-selected': `页签已选中:${target}`,
48
+ 'assert-disabled': `控件不可用:${target}`,
49
+ 'assert-headers': `列表包含列头:${value}`,
50
+ 'assert-form-errors': `表单提示必填错误:${value}`,
51
+ 'assert-input-invalid': `输入校验阻止无效数据:${target}`,
52
+ 'assert-row': `列表存在唯一记录:${value}`,
53
+ 'assert-absent': `列表中记录已消失:${value}`,
54
+ 'assert-persisted-row': `独立会话重新打开后存在唯一记录:${value}`,
55
+ 'assert-persisted-absent': `独立会话重新打开后记录不存在:${value}`,
56
+ 'assert-text': `页面显示文本:${value}`,
57
+ 'assert-record-detail': `列表之外的详情显示本轮记录:${value}`,
58
+ 'assert-tab-panel': `页签已选中且关联内容面板可见:${target}`,
59
+ 'assert-query-result': `唯一关键词查询仅返回本轮记录:${value}`,
60
+ 'assert-disclosure': `展开 ${target} 后出现新控件,并已恢复原状态`,
61
+ 'assert-related-records':
62
+ '关联添加后显示唯一记录,独立会话确认持久化;移除后列表恢复为空,并再次独立核对',
63
+ };
64
+ return titles[step.kind] ?? `${step.kind} ${target}`;
65
+ }
66
+ /** Preserve upstream truth: recorded assertion steps are appended after successful execution. */
67
+ export function projectReport(
68
+ report: UpstreamReport,
69
+ mode: AgentStatus['mode'],
70
+ final: boolean,
71
+ ): AgentStatus {
72
+ const cases: CaseEvidence[] = (report.results ?? []).map((c) => ({
73
+ id: c.id,
74
+ title: c.title,
75
+ ...(c.operation ? { operation: c.operation } : {}),
76
+ state: ['通过', '已验证'].includes(c.status)
77
+ ? 'passed'
78
+ : ['不适用', '未选择'].includes(c.status)
79
+ ? 'skipped'
80
+ : 'failed',
81
+ reason: `${c.status}:${c.reason}`,
82
+ screenshot: c.evidence || undefined,
83
+ assertions: [
84
+ ...c.steps.flatMap((step, i) =>
85
+ step.kind.startsWith('assert-')
86
+ ? [
87
+ {
88
+ step: i + 1,
89
+ expected: assertionTitle(step),
90
+ actual: '页面断言已通过,原始执行记录和浏览器证据见报告。',
91
+ passed: true,
92
+ },
93
+ ]
94
+ : [],
95
+ ),
96
+ ...(c.failedStep?.action.startsWith('assert-')
97
+ ? [
98
+ {
99
+ step: c.failedStep.number,
100
+ expected: assertionTitle({
101
+ kind: c.failedStep.action,
102
+ target: { name: c.failedStep.target },
103
+ }),
104
+ actual: c.reason,
105
+ passed: false,
106
+ },
107
+ ]
108
+ : []),
109
+ ],
110
+ errors: (c.browserEvents ?? []).map((e) => e.message ?? e.type ?? '页面事件'),
111
+ ...(report.retainedRecord
112
+ ? { cleanup: `保留测试记录:${report.retainedRecord}` }
113
+ : report.pendingWrite
114
+ ? { cleanup: '存在未确认写入,请核对 checkpoint.json 后清理。' }
115
+ : {}),
116
+ }));
117
+ const passed = cases.filter((c) => c.state === 'passed').length;
118
+ const state: AgentStatus['state'] = !final
119
+ ? 'running'
120
+ : report.runStatus === 'interrupted'
121
+ ? 'stopped'
122
+ : report.exitCode === 0
123
+ ? 'passed'
124
+ : passed
125
+ ? 'partial'
126
+ : 'failed';
127
+ return {
128
+ mode,
129
+ state,
130
+ cases,
131
+ decisions: report.metrics?.modelCalls ?? 0,
132
+ ...(report.coverage ? { coverage: report.coverage } : {}),
133
+ message: !final
134
+ ? report.activity || report.activeCase?.title || '正在识别页面控件并生成可验证用例'
135
+ : (report.error ??
136
+ `${mode === 'explore' ? '探索' : '回放'}结束:${passed} 条通过,${cases.filter((c) => c.state === 'failed').length} 条失败,${cases.filter((c) => c.state === 'skipped').length} 条不适用/未选择${report.coverage?.gaps.length ? `;另有 ${report.coverage.gaps.length} 项入口尚未验证` : ''}`),
137
+ ...(final && mode === 'explore' && report.caseFile ? { workbook: 'cases.xlsx' } : {}),
138
+ };
139
+ }