gz-laya-pilot 0.1.0 → 0.1.1
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.
- package/NOTICE.md +6 -2
- package/README.md +32 -2
- package/dist/agent/bridge.d.ts +21 -0
- package/dist/agent/bridge.js +158 -0
- package/dist/agent/bridge.js.map +1 -0
- package/dist/agent/report.d.ts +51 -0
- package/dist/agent/report.js +91 -0
- package/dist/agent/report.js.map +1 -0
- package/dist/agent/run.d.ts +19 -0
- package/dist/agent/run.js +121 -0
- package/dist/agent/run.js.map +1 -0
- package/dist/agent/schema.d.ts +32 -0
- package/dist/agent/schema.js +9 -0
- package/dist/agent/schema.js.map +1 -0
- package/dist/agent/worker.d.ts +1 -0
- package/dist/agent/worker.js +102 -0
- package/dist/agent/worker.js.map +1 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +7 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/package.json +14 -6
- package/src/agent/bridge.ts +180 -0
- package/src/agent/report.ts +126 -0
- package/src/agent/run.ts +136 -0
- package/src/agent/schema.ts +33 -0
- package/src/agent/worker.ts +114 -0
- package/src/cli.ts +5 -0
- package/src/index.ts +3 -0
- package/vendor/.gitattributes +4 -0
- package/vendor/UPSTREAM.json +79 -0
- package/vendor/laya-pilot/LICENSE +21 -0
- package/vendor/laya-pilot/README.en.md +116 -0
- package/vendor/laya-pilot/README.md +116 -0
- package/vendor/laya-pilot/ROADMAP.md +21 -0
- package/vendor/laya-pilot/config.example.json +14 -0
- package/vendor/laya-pilot/docs/architecture.md +21 -0
- package/vendor/laya-pilot/docs/browser-use-evaluation.md +32 -0
- package/vendor/laya-pilot/docs/demo.png +0 -0
- package/vendor/laya-pilot/docs/local-runtime.md +88 -0
- package/vendor/laya-pilot/docs/pr1-selection.md +33 -0
- package/vendor/laya-pilot/docs/retry-policy.md +14 -0
- package/vendor/laya-pilot/examples/demo-cases.xlsx +0 -0
- package/vendor/laya-pilot/examples/demo-server.mjs +19 -0
- package/vendor/laya-pilot/examples/demo.html +733 -0
- package/vendor/laya-pilot/lib/auth-state.mjs +141 -0
- package/vendor/laya-pilot/lib/browser-provider.mjs +31 -0
- package/vendor/laya-pilot/lib/diagnostics.mjs +210 -0
- package/vendor/laya-pilot/lib/discovery.mjs +323 -0
- package/vendor/laya-pilot/lib/dom.mjs +476 -0
- package/vendor/laya-pilot/lib/engine.mjs +879 -0
- package/vendor/laya-pilot/lib/form.mjs +377 -0
- package/vendor/laya-pilot/lib/language.mjs +273 -0
- package/vendor/laya-pilot/lib/model.mjs +271 -0
- package/vendor/laya-pilot/lib/pending-writes.mjs +50 -0
- package/vendor/laya-pilot/lib/planner.mjs +127 -0
- package/vendor/laya-pilot/lib/project-config.mjs +95 -0
- package/vendor/laya-pilot/lib/readiness.mjs +179 -0
- package/vendor/laya-pilot/lib/replay-model.mjs +44 -0
- package/vendor/laya-pilot/lib/run-state.mjs +119 -0
- package/vendor/laya-pilot/lib/test-data.mjs +115 -0
- package/vendor/laya-pilot/lib/workflow-policy.mjs +61 -0
- package/vendor/laya-pilot/lib/workflow.mjs +1906 -0
- package/vendor/laya-pilot/lib/workflow_excel.py +431 -0
- package/vendor/laya-pilot/requirements-local.txt +2 -0
- package/vendor/laya-pilot/requirements.txt +1 -0
- package/vendor/laya-pilot/runner.mjs +452 -0
- package/vendor/laya-pilot/tests/api.test.mjs +98 -0
- package/vendor/laya-pilot/tests/browser/runtime.test.mjs +847 -0
- package/vendor/laya-pilot/tests/config.test.mjs +109 -0
- package/vendor/laya-pilot/tests/diagnostics.test.mjs +91 -0
- package/vendor/laya-pilot/tests/discovery.test.mjs +76 -0
- package/vendor/laya-pilot/tests/fixtures/local-model/laya.py +28 -0
- package/vendor/laya-pilot/tests/fixtures/local-model/torch.py +5 -0
- package/vendor/laya-pilot/tests/guards.test.mjs +43 -0
- package/vendor/laya-pilot/tests/language.test.mjs +39 -0
- package/vendor/laya-pilot/tests/planner.test.mjs +129 -0
- package/vendor/laya-pilot/tests/readiness.test.mjs +118 -0
- package/vendor/laya-pilot/tests/real-model.smoke.mjs +74 -0
- package/vendor/laya-pilot/tests/replay-model.test.mjs +90 -0
- package/vendor/laya-pilot/tests/retries.test.mjs +257 -0
- package/vendor/laya-pilot/tests/run-state.test.mjs +162 -0
- package/vendor/laya-pilot/tests/selected-pr1.test.mjs +291 -0
- package/vendor/laya-pilot/tests/test-data.test.mjs +83 -0
- package/vendor/laya-pilot/tests/test_workflow_excel.py +162 -0
- package/vendor/laya-pilot/tests/worker_test.py +33 -0
- package/vendor/laya-pilot/tests/workflow.test.mjs +98 -0
- package/vendor/laya-pilot/worker.py +135 -0
- package/vendor/patches/0001-native-field-recipes.patch +57 -0
|
@@ -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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,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,CAAC,CAAC;IAC3C,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,OAAO,CAAC,SAAS;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
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
|
package/dist/cli.js.map
ADDED
|
@@ -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.
|
|
3
|
+
"version": "0.1.1",
|
|
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
|
-
"
|
|
39
|
-
"
|
|
46
|
+
"dom-accessibility-api": "^0.7.1",
|
|
47
|
+
"playwright": "1.62.1"
|
|
40
48
|
},
|
|
41
49
|
"devDependencies": {
|
|
42
|
-
"
|
|
43
|
-
"
|
|
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|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,126 @@
|
|
|
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
|
+
status: string;
|
|
13
|
+
reason: string;
|
|
14
|
+
steps: UpstreamStep[];
|
|
15
|
+
evidence?: string;
|
|
16
|
+
failedStep?: { number: number; action: string; target?: string } | null;
|
|
17
|
+
browserEvents?: { type?: string; message?: string; url?: string }[];
|
|
18
|
+
}
|
|
19
|
+
export interface UpstreamReport {
|
|
20
|
+
runStatus?: string;
|
|
21
|
+
status?: string;
|
|
22
|
+
error?: string;
|
|
23
|
+
exitCode?: number;
|
|
24
|
+
results: UpstreamCase[];
|
|
25
|
+
activeCase?: { title?: string };
|
|
26
|
+
caseFile?: string;
|
|
27
|
+
retainedRecord?: string;
|
|
28
|
+
pendingWrite?: unknown;
|
|
29
|
+
metrics?: { modelCalls?: number };
|
|
30
|
+
runtime?: { currentName?: string };
|
|
31
|
+
}
|
|
32
|
+
function assertionTitle(step: UpstreamStep): string {
|
|
33
|
+
if (step.spec?.title) return step.spec.title;
|
|
34
|
+
const target = step.target?.label ?? step.target?.name ?? '';
|
|
35
|
+
const value = Array.isArray(step.value)
|
|
36
|
+
? step.value.join('、')
|
|
37
|
+
: typeof step.value === 'string'
|
|
38
|
+
? step.value
|
|
39
|
+
.replaceAll('${recordName}', '本轮测试记录')
|
|
40
|
+
.replaceAll('${updatedName}', '修改后的本轮记录')
|
|
41
|
+
: '';
|
|
42
|
+
const titles: Record<string, string> = {
|
|
43
|
+
'assert-control': `控件可见且唯一:${target}`,
|
|
44
|
+
'assert-selected': `页签已选中:${target}`,
|
|
45
|
+
'assert-disabled': `控件不可用:${target}`,
|
|
46
|
+
'assert-headers': `列表包含列头:${value}`,
|
|
47
|
+
'assert-form-errors': `表单提示必填错误:${value}`,
|
|
48
|
+
'assert-input-invalid': `输入校验阻止无效数据:${target}`,
|
|
49
|
+
'assert-row': `列表存在唯一记录:${value}`,
|
|
50
|
+
'assert-absent': `列表中记录已消失:${value}`,
|
|
51
|
+
'assert-text': `页面显示文本:${value}`,
|
|
52
|
+
};
|
|
53
|
+
return titles[step.kind] ?? `${step.kind} ${target}`;
|
|
54
|
+
}
|
|
55
|
+
/** Preserve upstream truth: recorded assertion steps are appended after successful execution. */
|
|
56
|
+
export function projectReport(
|
|
57
|
+
report: UpstreamReport,
|
|
58
|
+
mode: AgentStatus['mode'],
|
|
59
|
+
final: boolean,
|
|
60
|
+
): AgentStatus {
|
|
61
|
+
const cases: CaseEvidence[] = (report.results ?? []).map((c) => ({
|
|
62
|
+
id: c.id,
|
|
63
|
+
title: c.title,
|
|
64
|
+
state: ['通过', '已验证'].includes(c.status)
|
|
65
|
+
? 'passed'
|
|
66
|
+
: ['不适用', '未选择'].includes(c.status)
|
|
67
|
+
? 'skipped'
|
|
68
|
+
: 'failed',
|
|
69
|
+
reason: `${c.status}:${c.reason}`,
|
|
70
|
+
screenshot: c.evidence || undefined,
|
|
71
|
+
assertions: [
|
|
72
|
+
...c.steps.flatMap((step, i) =>
|
|
73
|
+
step.kind.startsWith('assert-')
|
|
74
|
+
? [
|
|
75
|
+
{
|
|
76
|
+
step: i + 1,
|
|
77
|
+
expected: assertionTitle(step),
|
|
78
|
+
actual: '页面断言已通过,原始执行记录和浏览器证据见报告。',
|
|
79
|
+
passed: true,
|
|
80
|
+
},
|
|
81
|
+
]
|
|
82
|
+
: [],
|
|
83
|
+
),
|
|
84
|
+
...(c.failedStep?.action.startsWith('assert-')
|
|
85
|
+
? [
|
|
86
|
+
{
|
|
87
|
+
step: c.failedStep.number,
|
|
88
|
+
expected: assertionTitle({
|
|
89
|
+
kind: c.failedStep.action,
|
|
90
|
+
target: { name: c.failedStep.target },
|
|
91
|
+
}),
|
|
92
|
+
actual: c.reason,
|
|
93
|
+
passed: false,
|
|
94
|
+
},
|
|
95
|
+
]
|
|
96
|
+
: []),
|
|
97
|
+
],
|
|
98
|
+
errors: (c.browserEvents ?? []).map((e) => e.message ?? e.type ?? '页面事件'),
|
|
99
|
+
...(report.retainedRecord
|
|
100
|
+
? { cleanup: `保留测试记录:${report.retainedRecord}` }
|
|
101
|
+
: report.pendingWrite
|
|
102
|
+
? { cleanup: '存在未确认写入,请核对 checkpoint.json 后清理。' }
|
|
103
|
+
: {}),
|
|
104
|
+
}));
|
|
105
|
+
const passed = cases.filter((c) => c.state === 'passed').length;
|
|
106
|
+
const state: AgentStatus['state'] = !final
|
|
107
|
+
? 'running'
|
|
108
|
+
: report.runStatus === 'interrupted'
|
|
109
|
+
? 'stopped'
|
|
110
|
+
: report.exitCode === 0
|
|
111
|
+
? 'passed'
|
|
112
|
+
: passed
|
|
113
|
+
? 'partial'
|
|
114
|
+
: 'failed';
|
|
115
|
+
return {
|
|
116
|
+
mode,
|
|
117
|
+
state,
|
|
118
|
+
cases,
|
|
119
|
+
decisions: report.metrics?.modelCalls ?? 0,
|
|
120
|
+
message: !final
|
|
121
|
+
? (report.activeCase?.title ?? '上游 LayaPilot 正在执行')
|
|
122
|
+
: (report.error ??
|
|
123
|
+
`${mode === 'explore' ? '探索' : '回放'}结束:${passed} 条通过,${cases.filter((c) => c.state === 'failed').length} 条失败,${cases.filter((c) => c.state === 'skipped').length} 条不适用/未选择`),
|
|
124
|
+
...(final && mode === 'explore' && report.caseFile ? { workbook: 'cases.xlsx' } : {}),
|
|
125
|
+
};
|
|
126
|
+
}
|
package/src/agent/run.ts
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { fork, execFile } from 'node:child_process';
|
|
2
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { existsSync } from 'node:fs';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { testUrl, type AgentStatus } from './schema.js';
|
|
7
|
+
import { projectReport, type UpstreamReport } from './report.js';
|
|
8
|
+
|
|
9
|
+
export interface AgentOptions {
|
|
10
|
+
url: string;
|
|
11
|
+
outputDir: string;
|
|
12
|
+
python: string;
|
|
13
|
+
model: string;
|
|
14
|
+
workbook?: string;
|
|
15
|
+
allowWrite?: boolean;
|
|
16
|
+
headed?: boolean;
|
|
17
|
+
channel?: string;
|
|
18
|
+
authState?: string;
|
|
19
|
+
authCheck?: string;
|
|
20
|
+
manualLogin?: boolean;
|
|
21
|
+
signal?: AbortSignal;
|
|
22
|
+
timeout?: number;
|
|
23
|
+
onProgress?: (status: AgentStatus) => void;
|
|
24
|
+
}
|
|
25
|
+
/** Functional npm facade over the pinned upstream generate/execute workflow. No second planner. */
|
|
26
|
+
export async function runAgent(options: AgentOptions): Promise<AgentStatus> {
|
|
27
|
+
options.signal?.throwIfAborted();
|
|
28
|
+
const url = testUrl(options.url),
|
|
29
|
+
outputDir = path.resolve(options.outputDir);
|
|
30
|
+
if (!existsSync(options.python) || !existsSync(options.model))
|
|
31
|
+
throw Error('请配置可用的本地 Laya Python 和模型路径');
|
|
32
|
+
if (options.authState && !options.authCheck)
|
|
33
|
+
throw Error('复用登录态需要 authCheck 校验登录成功页面');
|
|
34
|
+
await mkdir(outputDir, { recursive: true });
|
|
35
|
+
if (existsSync(path.join(outputDir, 'checkpoint.json')))
|
|
36
|
+
throw Error('输出目录已有运行记录,请使用新的目录');
|
|
37
|
+
const mode = options.workbook ? 'replay' : 'explore';
|
|
38
|
+
let last: AgentStatus = {
|
|
39
|
+
state: 'running',
|
|
40
|
+
mode,
|
|
41
|
+
message: '正在启动上游 LayaPilot',
|
|
42
|
+
cases: [],
|
|
43
|
+
decisions: 0,
|
|
44
|
+
};
|
|
45
|
+
options.onProgress?.(last);
|
|
46
|
+
const child = fork(fileURLToPath(new URL('./worker.js', import.meta.url)), [], {
|
|
47
|
+
execArgv: [],
|
|
48
|
+
stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
|
|
49
|
+
...{ windowsHide: true },
|
|
50
|
+
env: {
|
|
51
|
+
...process.env,
|
|
52
|
+
PYTHONIOENCODING: 'utf-8',
|
|
53
|
+
PYTHONUTF8: '1',
|
|
54
|
+
PYTHONDONTWRITEBYTECODE: '1',
|
|
55
|
+
HF_HUB_OFFLINE: '1',
|
|
56
|
+
},
|
|
57
|
+
});
|
|
58
|
+
let stopped = false,
|
|
59
|
+
finished = false,
|
|
60
|
+
diagnostic = '',
|
|
61
|
+
stopping: ReturnType<typeof setTimeout> | undefined;
|
|
62
|
+
const stop = () => {
|
|
63
|
+
if (stopped) return;
|
|
64
|
+
stopped = true;
|
|
65
|
+
if (child.connected) child.send({ type: 'stop' }, () => {});
|
|
66
|
+
stopping = setTimeout(() => {
|
|
67
|
+
if (child.exitCode !== null || !child.pid) return;
|
|
68
|
+
if (process.platform === 'win32')
|
|
69
|
+
execFile(
|
|
70
|
+
'taskkill',
|
|
71
|
+
['/PID', String(child.pid), '/T', '/F'],
|
|
72
|
+
{ windowsHide: true },
|
|
73
|
+
() => {},
|
|
74
|
+
);
|
|
75
|
+
else child.kill('SIGKILL');
|
|
76
|
+
}, 20000);
|
|
77
|
+
};
|
|
78
|
+
options.signal?.addEventListener('abort', stop, { once: true });
|
|
79
|
+
const timeout = setTimeout(stop, options.timeout ?? 12 * 60 * 1000);
|
|
80
|
+
const readProgress = async () => {
|
|
81
|
+
try {
|
|
82
|
+
const report = JSON.parse(
|
|
83
|
+
await readFile(path.join(outputDir, 'checkpoint.json'), 'utf8'),
|
|
84
|
+
) as UpstreamReport;
|
|
85
|
+
if (finished) return;
|
|
86
|
+
last = projectReport(report, mode, false);
|
|
87
|
+
options.onProgress?.(last);
|
|
88
|
+
} catch {
|
|
89
|
+
/* Atomic checkpoint may not exist until startup completes. */
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
const polling = setInterval(() => void readProgress(), 1000);
|
|
93
|
+
child.stdout?.on('data', (chunk) => {
|
|
94
|
+
const message = chunk.toString().trim();
|
|
95
|
+
if (message && !message.startsWith('RESULT '))
|
|
96
|
+
options.onProgress?.({ ...last, message: message.slice(-1000) });
|
|
97
|
+
});
|
|
98
|
+
child.stderr?.on('data', (chunk) => {
|
|
99
|
+
diagnostic = (diagnostic + chunk.toString()).slice(-1000);
|
|
100
|
+
});
|
|
101
|
+
child.on('message', (message: { error?: string }) => {
|
|
102
|
+
if (message.error) diagnostic = message.error;
|
|
103
|
+
});
|
|
104
|
+
try {
|
|
105
|
+
const exited = new Promise<number | null>((resolve, reject) => {
|
|
106
|
+
child.once('error', reject);
|
|
107
|
+
child.once('exit', resolve);
|
|
108
|
+
});
|
|
109
|
+
child.send({
|
|
110
|
+
type: 'run',
|
|
111
|
+
options: { ...options, url, outputDir, signal: undefined, onProgress: undefined },
|
|
112
|
+
});
|
|
113
|
+
if (options.signal?.aborted) stop();
|
|
114
|
+
const code = await exited;
|
|
115
|
+
finished = true;
|
|
116
|
+
clearInterval(polling);
|
|
117
|
+
let report: UpstreamReport;
|
|
118
|
+
try {
|
|
119
|
+
report = JSON.parse(await readFile(path.join(outputDir, 'results.json'), 'utf8'));
|
|
120
|
+
} catch {
|
|
121
|
+
report = { results: [], exitCode: code ?? 1, error: diagnostic || '上游执行未生成报告' };
|
|
122
|
+
}
|
|
123
|
+
last = projectReport(report, mode, true);
|
|
124
|
+
if (stopped) last.state = 'stopped';
|
|
125
|
+
if (existsSync(path.join(outputDir, 'trace.zip'))) last.trace = 'trace.zip';
|
|
126
|
+
await writeFile(path.join(outputDir, 'assistant-status.json'), JSON.stringify(last, null, 2));
|
|
127
|
+
options.onProgress?.(last);
|
|
128
|
+
return last;
|
|
129
|
+
} finally {
|
|
130
|
+
finished = true;
|
|
131
|
+
clearInterval(polling);
|
|
132
|
+
clearTimeout(timeout);
|
|
133
|
+
clearTimeout(stopping);
|
|
134
|
+
options.signal?.removeEventListener('abort', stop);
|
|
135
|
+
}
|
|
136
|
+
}
|