android-midscene-automation 0.1.0

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 (78) hide show
  1. package/README.md +160 -0
  2. package/bin/android-midscene-automation.js +27 -0
  3. package/index.html +12 -0
  4. package/package.json +49 -0
  5. package/remote-agent/index.ts +206 -0
  6. package/server/appium-recorder/appium-runner.ts +427 -0
  7. package/server/appium-recorder/repository.ts +228 -0
  8. package/server/appium-recorder/routes.ts +219 -0
  9. package/server/config-store.ts +167 -0
  10. package/server/config.ts +130 -0
  11. package/server/device-locks/repository.ts +147 -0
  12. package/server/device-locks/service.ts +72 -0
  13. package/server/device-locks/types.ts +22 -0
  14. package/server/device-sessions/repository.ts +169 -0
  15. package/server/device-sessions/service.ts +59 -0
  16. package/server/device-sessions/types.ts +24 -0
  17. package/server/http-api.ts +1389 -0
  18. package/server/model-call-usage-importer.ts +108 -0
  19. package/server/model-tester.ts +104 -0
  20. package/server/model-usage-repository.ts +131 -0
  21. package/server/operations/repository.ts +218 -0
  22. package/server/operations/service.ts +84 -0
  23. package/server/operations/types.ts +27 -0
  24. package/server/paths.ts +27 -0
  25. package/server/remote-agents/protocol.ts +38 -0
  26. package/server/remote-agents/registry.ts +136 -0
  27. package/server/remote-agents/routes.ts +89 -0
  28. package/server/script-agent.ts +284 -0
  29. package/server/script-db.ts +281 -0
  30. package/server/script-runner.ts +551 -0
  31. package/server/storage/sqlite.ts +49 -0
  32. package/server/test-case-import/formatter.ts +28 -0
  33. package/server/test-case-import/parsers/excel.ts +69 -0
  34. package/server/test-case-import/parsers/txt.ts +11 -0
  35. package/server/test-case-import/parsers/word.ts +9 -0
  36. package/server/test-case-import/service.ts +58 -0
  37. package/server/test-case-import/text-normalizer.ts +98 -0
  38. package/server/test-case-import/types.ts +24 -0
  39. package/server/test-case-import/validator.ts +34 -0
  40. package/src/App.vue +1450 -0
  41. package/src/api.ts +290 -0
  42. package/src/appium-recorder/AppiumPage.vue +894 -0
  43. package/src/appium-recorder/api.ts +64 -0
  44. package/src/appium-recorder/components/ComponentTree.vue +44 -0
  45. package/src/appium-recorder/components/NodeDetail.vue +152 -0
  46. package/src/appium-recorder/components/RecordedSteps.vue +79 -0
  47. package/src/appium-recorder/tree.ts +129 -0
  48. package/src/appium-recorder/types.ts +88 -0
  49. package/src/assets/device-actions/back.svg +5 -0
  50. package/src/assets/device-actions/home.svg +3 -0
  51. package/src/assets/device-actions/power.svg +5 -0
  52. package/src/assets/device-actions/tasks.svg +3 -0
  53. package/src/assets/device-actions/volume-down.svg +3 -0
  54. package/src/assets/device-actions/volume-up.svg +3 -0
  55. package/src/components/config/ModelUsageChart.vue +188 -0
  56. package/src/components/device/DevicePreviewPanel.vue +266 -0
  57. package/src/components/generator/GeneratedCodePanel.vue +70 -0
  58. package/src/components/generator/TestCaseFileUpload.vue +97 -0
  59. package/src/config/midscene-model-presets.ts +75 -0
  60. package/src/config/prompt-example.ts +6 -0
  61. package/src/main.ts +7 -0
  62. package/src/pages/AiGeneratorPage.vue +90 -0
  63. package/src/pages/AutomationPage.vue +161 -0
  64. package/src/pages/ConfigPage.vue +273 -0
  65. package/src/pages/GeneratorPage.vue +97 -0
  66. package/src/pages/ManualStepsPage.vue +179 -0
  67. package/src/script-generator/codegen.ts +126 -0
  68. package/src/script-generator/index.ts +4 -0
  69. package/src/script-generator/presets.ts +37 -0
  70. package/src/script-generator/step-options.ts +52 -0
  71. package/src/script-generator/types.ts +27 -0
  72. package/src/style.css +1983 -0
  73. package/src/types.ts +157 -0
  74. package/src/vite-env.d.ts +1 -0
  75. package/tsconfig.app.json +8 -0
  76. package/tsconfig.json +11 -0
  77. package/tsconfig.node.json +16 -0
  78. package/vite.config.ts +28 -0
@@ -0,0 +1,38 @@
1
+ export type RemoteAgentDevice = {
2
+ id: string;
3
+ status: string;
4
+ model?: string;
5
+ description?: string;
6
+ };
7
+
8
+ export type RemoteCommandType =
9
+ | 'screenshot'
10
+ | 'displayInfo'
11
+ | 'tree'
12
+ | 'tap'
13
+ | 'swipe'
14
+ | 'key'
15
+ | 'replay';
16
+
17
+ export type RemoteCommand = {
18
+ id: string;
19
+ type: RemoteCommandType;
20
+ deviceId: string;
21
+ payload?: Record<string, unknown>;
22
+ };
23
+
24
+ export type RemoteCommandResult = {
25
+ commandId: string;
26
+ ok: boolean;
27
+ data?: unknown;
28
+ error?: string;
29
+ };
30
+
31
+ export type RemoteAndroidDevice = {
32
+ id: string;
33
+ status: string;
34
+ description: string;
35
+ source: 'remote';
36
+ agentId: string;
37
+ deviceSerial: string;
38
+ };
@@ -0,0 +1,136 @@
1
+ import type { RemoteAgentDevice, RemoteAndroidDevice, RemoteCommand, RemoteCommandResult, RemoteCommandType } from './protocol';
2
+
3
+ const REMOTE_DEVICE_PREFIX = 'remote:';
4
+ const AGENT_TTL_MS = 15_000;
5
+ const COMMAND_TIMEOUT_MS = 15_000;
6
+ const REPLAY_COMMAND_TIMEOUT_MS = 10 * 60_000;
7
+
8
+ type RegisteredAgent = {
9
+ id: string;
10
+ name: string;
11
+ version: string;
12
+ devices: RemoteAgentDevice[];
13
+ lastSeenAt: number;
14
+ };
15
+
16
+ type PendingCommand = RemoteCommand & {
17
+ resolve: (result: unknown) => void;
18
+ reject: (error: Error) => void;
19
+ timer: ReturnType<typeof setTimeout>;
20
+ };
21
+
22
+ const agents = new Map<string, RegisteredAgent>();
23
+ const queues = new Map<string, RemoteCommand[]>();
24
+ const pending = new Map<string, PendingCommand>();
25
+
26
+ function validateToken(token?: string) {
27
+ const expected = process.env.REMOTE_AGENT_TOKEN || '';
28
+ if (expected && token !== expected) {
29
+ throw new Error('Remote Agent token 无效');
30
+ }
31
+ }
32
+
33
+ export function isRemoteDeviceId(deviceId: string) {
34
+ return deviceId.startsWith(REMOTE_DEVICE_PREFIX);
35
+ }
36
+
37
+ export function makeRemoteDeviceId(agentId: string, deviceSerial: string) {
38
+ return `${REMOTE_DEVICE_PREFIX}${encodeURIComponent(agentId)}:${encodeURIComponent(deviceSerial)}`;
39
+ }
40
+
41
+ export function parseRemoteDeviceId(deviceId: string) {
42
+ if (!isRemoteDeviceId(deviceId)) return null;
43
+ const raw = deviceId.slice(REMOTE_DEVICE_PREFIX.length);
44
+ const splitAt = raw.indexOf(':');
45
+ if (splitAt <= 0) return null;
46
+ return {
47
+ agentId: decodeURIComponent(raw.slice(0, splitAt)),
48
+ deviceSerial: decodeURIComponent(raw.slice(splitAt + 1)),
49
+ };
50
+ }
51
+
52
+ function isOnline(agent: RegisteredAgent) {
53
+ return Date.now() - agent.lastSeenAt <= AGENT_TTL_MS;
54
+ }
55
+
56
+ export function registerRemoteAgent(input: {
57
+ agentId: string;
58
+ agentName?: string;
59
+ version?: string;
60
+ token?: string;
61
+ devices?: RemoteAgentDevice[];
62
+ }) {
63
+ validateToken(input.token);
64
+ const agentId = input.agentId.trim();
65
+ if (!agentId) throw new Error('agentId 不能为空');
66
+ agents.set(agentId, {
67
+ id: agentId,
68
+ name: input.agentName?.trim() || agentId,
69
+ version: input.version || '',
70
+ devices: input.devices || [],
71
+ lastSeenAt: Date.now(),
72
+ });
73
+ }
74
+
75
+ export function listRemoteAndroidDevices(): RemoteAndroidDevice[] {
76
+ return [...agents.values()]
77
+ .filter(isOnline)
78
+ .flatMap((agent) => agent.devices.map((device) => ({
79
+ id: makeRemoteDeviceId(agent.id, device.id),
80
+ status: device.status,
81
+ description: [agent.name, device.model, device.description || device.status].filter(Boolean).join(' · '),
82
+ source: 'remote' as const,
83
+ agentId: agent.id,
84
+ deviceSerial: device.id,
85
+ })));
86
+ }
87
+
88
+ export function pollRemoteCommand(input: { agentId: string; token?: string }) {
89
+ validateToken(input.token);
90
+ const queue = queues.get(input.agentId) || [];
91
+ return queue.shift() || null;
92
+ }
93
+
94
+ export function completeRemoteCommand(input: {
95
+ agentId: string;
96
+ token?: string;
97
+ } & RemoteCommandResult) {
98
+ validateToken(input.token);
99
+ const command = pending.get(input.commandId);
100
+ if (!command) return;
101
+ pending.delete(input.commandId);
102
+ clearTimeout(command.timer);
103
+ if (input.ok) {
104
+ command.resolve(input.data);
105
+ } else {
106
+ command.reject(new Error(input.error || '远程设备命令失败'));
107
+ }
108
+ }
109
+
110
+ export function sendRemoteCommand(deviceId: string, type: RemoteCommandType, payload?: Record<string, unknown>) {
111
+ const parsed = parseRemoteDeviceId(deviceId);
112
+ if (!parsed) throw new Error('远程设备 ID 无效');
113
+ const agent = agents.get(parsed.agentId);
114
+ if (!agent || !isOnline(agent)) throw new Error('远程设备代理已离线');
115
+ const commandId = `remote_cmd_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
116
+ const command: RemoteCommand = {
117
+ id: commandId,
118
+ type,
119
+ deviceId: parsed.deviceSerial,
120
+ payload,
121
+ };
122
+
123
+ return new Promise<unknown>((resolve, reject) => {
124
+ const timeoutMs = type === 'replay' ? REPLAY_COMMAND_TIMEOUT_MS : COMMAND_TIMEOUT_MS;
125
+ const timer = setTimeout(() => {
126
+ pending.delete(commandId);
127
+ const queue = queues.get(parsed.agentId) || [];
128
+ queues.set(parsed.agentId, queue.filter((item) => item.id !== commandId));
129
+ reject(new Error('远程设备命令超时'));
130
+ }, timeoutMs);
131
+ pending.set(commandId, { ...command, resolve, reject, timer });
132
+ const queue = queues.get(parsed.agentId) || [];
133
+ queue.push(command);
134
+ queues.set(parsed.agentId, queue);
135
+ });
136
+ }
@@ -0,0 +1,89 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { completeRemoteCommand, listRemoteAndroidDevices, pollRemoteCommand, registerRemoteAgent } from './registry';
3
+ import type { RemoteAgentDevice } from './protocol';
4
+
5
+ function sendJson(res: ServerResponse, payload: unknown, statusCode = 200) {
6
+ res.statusCode = statusCode;
7
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
8
+ res.end(JSON.stringify(payload));
9
+ }
10
+
11
+ async function readBody<T>(req: IncomingMessage) {
12
+ let body = '';
13
+ req.on('data', (chunk) => {
14
+ body += chunk;
15
+ });
16
+ return await new Promise<T>((resolve) => {
17
+ req.on('end', () => {
18
+ resolve(JSON.parse(body || '{}') as T);
19
+ });
20
+ });
21
+ }
22
+
23
+ export async function handleRemoteAgentRequest(req: IncomingMessage, res: ServerResponse) {
24
+ const requestUrl = new URL(req.url || '/', 'http://localhost');
25
+ const pathname = requestUrl.pathname;
26
+ if (!pathname.startsWith('/api/remote-agents')) return false;
27
+
28
+ try {
29
+ if (pathname === '/api/remote-agents' && req.method === 'GET') {
30
+ sendJson(res, { devices: listRemoteAndroidDevices() });
31
+ return true;
32
+ }
33
+
34
+ if (pathname === '/api/remote-agents/heartbeat' && req.method === 'POST') {
35
+ const parsed = await readBody<{
36
+ agentId?: string;
37
+ agentName?: string;
38
+ version?: string;
39
+ token?: string;
40
+ devices?: RemoteAgentDevice[];
41
+ }>(req);
42
+ registerRemoteAgent({
43
+ agentId: parsed.agentId || '',
44
+ agentName: parsed.agentName,
45
+ version: parsed.version,
46
+ token: parsed.token,
47
+ devices: parsed.devices || [],
48
+ });
49
+ sendJson(res, { success: true });
50
+ return true;
51
+ }
52
+
53
+ if (pathname === '/api/remote-agents/poll' && req.method === 'GET') {
54
+ const command = pollRemoteCommand({
55
+ agentId: requestUrl.searchParams.get('agentId') || '',
56
+ token: requestUrl.searchParams.get('token') || '',
57
+ });
58
+ sendJson(res, { command });
59
+ return true;
60
+ }
61
+
62
+ if (pathname === '/api/remote-agents/result' && req.method === 'POST') {
63
+ const parsed = await readBody<{
64
+ agentId?: string;
65
+ token?: string;
66
+ commandId?: string;
67
+ ok?: boolean;
68
+ data?: unknown;
69
+ error?: string;
70
+ }>(req);
71
+ completeRemoteCommand({
72
+ agentId: parsed.agentId || '',
73
+ token: parsed.token,
74
+ commandId: parsed.commandId || '',
75
+ ok: parsed.ok === true,
76
+ data: parsed.data,
77
+ error: parsed.error,
78
+ });
79
+ sendJson(res, { success: true });
80
+ return true;
81
+ }
82
+
83
+ sendJson(res, { message: 'Remote Agent 接口不存在' }, 404);
84
+ return true;
85
+ } catch (error) {
86
+ sendJson(res, { message: error instanceof Error ? error.message : 'Remote Agent 请求失败' }, 500);
87
+ return true;
88
+ }
89
+ }
@@ -0,0 +1,284 @@
1
+ import OpenAI from 'openai';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { loadConfig } from './config';
6
+
7
+ const allowedTypes = new Set([
8
+ 'comment',
9
+ 'waitFor',
10
+ 'act',
11
+ 'tap',
12
+ 'input',
13
+ 'query',
14
+ 'boolean',
15
+ 'string',
16
+ 'number',
17
+ ]);
18
+
19
+ const systemPrompt = `你是一个 Midscene 自动化脚本规划器。
20
+
21
+ 目标:把中文自动化需求拆成适合 Midscene Android 自动化的结构化步骤。
22
+
23
+ 规则:
24
+ 1. 参考 Midscene 示例项目的写法:输出稳定的结构化脚本步骤,每一步可以是短自然语言指令;不要输出“整段自然语言一次性跑完整用例”的巨型 aiAct。
25
+ 2. 默认生成低模型调用脚本,避免为了稳妥堆叠重复判断。每个 aiAct、aiTap、aiInput、aiWaitFor、aiBoolean、aiQuery 都可能触发模型调用,能少一步就少一步。
26
+ 3. 合理混用 aiAct、aiWaitFor、aiTap、aiInput、aiQuery、aiBoolean、aiString、aiNumber。
27
+ 4. 只有在确实适合注释时才使用 comment。
28
+ 5. 输出必须是 JSON 对象,不要输出 markdown。
29
+ 6. JSON 结构如下:
30
+ {
31
+ "promptTitle": "场景标题",
32
+ "steps": [
33
+ {
34
+ "type": "act | waitFor | tap | input | query | boolean | string | number | comment",
35
+ "label": "步骤标题",
36
+ "prompt": "描述",
37
+ "outputVar": "可选,仅 query/boolean/string/number 时使用",
38
+ "value": "可选,仅 input 时使用",
39
+ "observePrompt": "可选,仅 act/tap/input 时使用;描述执行该动作期间需要捕获的瞬时界面现象",
40
+ "repeat": "可选数字,仅 act/tap 可使用,表示重复执行次数",
41
+ "enabled": true
42
+ }
43
+ ]
44
+ }
45
+ 7. 通用测试场景默认按“进入/确认目标 App -> 处理启动阶段遮挡 -> 等待起始页面稳定 -> 执行核心业务动作 -> 等待结果页面或读取结果”的结构拆分。不要只生成一条巨型 act,也不要为同一状态生成重复验证。
46
+ 8. 如果需求涉及某个 App,第一条可执行步骤只做轻量进入/确认目标 App:若当前已在目标 App 内则保持当前状态;若不在目标 App 内,使用包名打开目标 App 并等待首屏,不要描述“查找桌面图标/从最近任务选择”等视觉搜索过程。启动后不要再生成额外 boolean 确认。
47
+ 9. 如果原始需求里有“遇到弹窗则关闭/允许/跳过”这类策略,生成 1 条启动阶段总括 act 步骤即可,默认 repeat: 1;只有用户明确要求“反复处理/直到没有/所有弹窗”时才设置 repeat: 2。prompt 要写清楚只检查权限、启动协议、广告、更新、活动、通知引导等启动阶段弹窗;如果没有弹窗,不要点击业务内容、表单字段、复选框或提交按钮。
48
+ 10. 所有场景都要把输入、点击、等待结果拆成独立步骤。输入使用 input,明确点击使用 tap,条件式处理使用 act,页面稳定使用 waitFor,读取数据使用 query/string/number,真假判断使用 boolean。
49
+ 11. 所有定位 prompt 都要具体到页面、区域、附近文本或业务含义,例如“搜索页顶部搜索框”“设备列表中的第一个在线设备”“详情页右上角设置按钮”。不要写“输入框”“按钮”“列表项”等泛化描述。
50
+ 12. 所有 input 的 value 必须完全来自原始需求;不得改写、脱敏、复用历史值或编造示例值。aiInput 步骤中 prompt 只表示输入框定位描述,value 表示要输入的内容。
51
+ 13. 结果验证默认用 1 条 waitFor 写正向、可观察的成功信号,例如目标页面标题、列表项、详情页核心元素、提交成功页、设备状态变化。不要默认追加长串失败排除条件;只有用户明确要求校验失败原因时,才额外生成错误提示读取或失败断言。
52
+ 14. 每个 boolean 步骤只能问一个真假问题;默认不要为了确认当前页面状态而生成 boolean,优先使用 waitFor 作为稳定状态验证。不要生成“waitFor + boolean”重复判断同一结果。
53
+ 15. 条件式 no-op 动作会增加模型调用,只有确实存在分支时才生成。如果一个动作步骤的 prompt 包含“如果存在/若出现/如果当前不是/如果未勾选/如果已经/否则跳过/保持当前状态”,不能使用 tap;应使用单次 act,或者先用 boolean 判断后再生成确定目标的 tap,但不要两者都生成。
54
+ 16. “处理弹窗/关闭弹窗/允许权限/同意协议”必须使用 act 或 tap,因为 boolean/query 只会判断或读取,不会点击按钮。
55
+ 17. 生成步骤时必须参考后续提供的 Midscene 文档内容,尤其是 JavaScript 优化建议、aiAct/aiTap/aiInput/aiWaitFor/aiQuery/aiBoolean/aiString/aiNumber 的职责边界和用法。
56
+ 18. 不要生成 Midscene 文档中不存在的 API 名称。当前只输出结构化 JSON steps,由代码生成器映射为对应的 Midscene API。
57
+ 19. 优先套用后续 Midscene 脚本生成参考中的拆分策略、步骤标题规范、通用场景模板、登录场景模板、弹窗处理模板和失败验证规则。
58
+ 20. Midscene 1.10.4 支持 startObserving/UIObserver。只有原始需求明确需要验证动作过程中一闪而过的 Toast、短暂错误提示、Banner、加载状态或自动消失控件时,才给触发该现象的 act/tap/input 步骤填写 observePrompt;如果不需要验证瞬时现象,必须省略该字段。
59
+ 21. observePrompt 必须描述一个肯定、可观察的历史事件,例如“点击保存后,执行过程中出现过保存成功提示”。不要用它判断最终页面是否稳定、当前是否仍有弹窗、是否进入结果页等持续状态,这些情况默认只用 aiWaitFor。
60
+ 22. observePrompt 应挂在直接触发现象的动作步骤上,不要挂在启动 App、循环处理弹窗或等待步骤上。即使观察到了成功 Toast,只要用户把“进入结果页/列表更新/状态变化”作为成功标准,仍必须生成最终页面的 waitFor;不要再默认补结果 boolean。
61
+ 23. 登录场景默认控制在 7 到 9 个可执行步骤:进入/确认 App、处理启动弹窗、等待登录页、必要时进入账号密码登录、输入账号、输入密码、必要时勾选协议、提交登录、等待首页。最终默认用 waitFor 作为成功判定;只有用户明确要求读取布尔结果、错误原因或断言日志时,才额外生成 boolean/string/query。
62
+ 24. 登录场景必须先从原始需求中抽取账号、密码、验证码等输入值;所有后续步骤必须复用完全相同的字面量,禁止把邮箱改成手机号、把手机号改成邮箱、使用历史账号、示例账号或自行编造账号。
63
+ 25. 登录表单必须拆分:账号输入是独立 input,密码输入是独立 input,登录按钮是独立 tap。登录协议勾选框只有在页面/需求明确需要时才生成独立处理步骤。不要用一条 act 同时输入账号、输入密码、勾选协议和点击登录。
64
+ 26. 登录按钮步骤必须使用 tap,prompt 只描述点击当前页面的登录按钮,例如“点击登录页中的登录按钮,提交当前已填写的表单;不要修改账号、密码或其他输入框”。不要在登录按钮 prompt 中重新写账号或密码,也不要追加“如果软键盘遮挡”等条件式子句。
65
+ 27. 简单且目标确定可见的点击优先使用 tap。登录按钮适合 tap;只有明确当前不在账号密码登录页时,账号密码登录入口才适合 tap;只有明确协议未勾选时,登录协议勾选框才适合 tap。
66
+ 28. 如果步骤语义是“如果当前不是账号密码登录页则点击入口,否则保持当前状态”,必须使用单次 act,不要用 tap。
67
+ 29. 如果步骤语义是“如果协议未勾选则勾选,已勾选或没有复选框则保持当前状态”,必须使用单次 act,避免 tap 反选已勾选的协议。
68
+ 30. 登录协议勾选框、登录按钮和登录后协议确认弹窗不能设置 repeat;每个步骤最多点击一次,后续用 waitFor 判断是否成功,避免再补重复 boolean。
69
+ 31. 如果等待登录页后还可能停留在欢迎页、手机号登录页、微信登录页或其他非账号密码登录页,必须在输入账号前生成单次 act:如果当前不是账号密码登录页,点击账号密码登录入口或切换到账号密码登录方式;如果当前已经显示账号和密码输入框,则保持当前状态。
70
+ 32. 登录账号输入框 prompt 必须根据已选择的登录方式精确定位:账号密码登录页中写“账号密码登录页中的账号或邮箱输入框”;手机号登录页中写“手机号登录页中的手机号输入框”。不要写“手机号、账号或邮箱输入框”这种会匹配多个字段的泛化描述。
71
+ 33. 登录协议勾选 prompt 必须说明只点击复选框本身,不点击用户协议、隐私政策等文本链接。
72
+ 34. 登录成功后的 waitFor 默认只写正向成功信号:等待首页或主界面稳定显示,出现设备列表、添加设备入口、底部导航、用户头像或我的页面入口等首页核心元素之一。不要默认追加长串失败排除条件;只有用户明确要求校验失败原因时,才额外生成错误提示读取或失败断言。
73
+ 35. 协议确认弹窗和“再次提交登录”不是登录脚本的默认步骤。只有原始需求明确提到点击登录后会出现服务协议/隐私政策/声明与条款确认弹窗,或上下文明确该 App 存在这个二次确认,才生成这两个条件式 act 步骤。`;
74
+
75
+ const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
76
+ const midsceneDocsDir = path.join(projectRoot, 'docs', 'midscene');
77
+ const midsceneDocPaths = {
78
+ scriptGenerationReference: path.join(midsceneDocsDir, 'script-generation-reference.md'),
79
+ optimize: path.join(midsceneDocsDir, 'use-javascript-to-optimize-ai-automation-code.md'),
80
+ api: path.join(midsceneDocsDir, 'api.md'),
81
+ };
82
+
83
+ function readMidsceneDoc(filePath: string) {
84
+ if (!existsSync(filePath)) return '';
85
+ return readFileSync(filePath, 'utf8');
86
+ }
87
+
88
+ function excerptAround(content: string, pattern: RegExp, radius = 1800) {
89
+ const match = pattern.exec(content);
90
+ if (!match || match.index === undefined) return '';
91
+
92
+ const start = Math.max(0, match.index - radius);
93
+ const end = Math.min(content.length, match.index + match[0].length + radius);
94
+ return content.slice(start, end).trim();
95
+ }
96
+
97
+ function buildMidsceneDocsContext() {
98
+ const mergedReference = readMidsceneDoc(midsceneDocPaths.scriptGenerationReference);
99
+ if (mergedReference) {
100
+ return [
101
+ '下面是本项目整理后的 Midscene 脚本生成参考。你必须参考这些内容规划脚本步骤,但最终仍只能输出前面约定的 JSON 对象。',
102
+ `文档路径:${midsceneDocPaths.scriptGenerationReference}`,
103
+ mergedReference,
104
+ ].join('\n\n');
105
+ }
106
+
107
+ const optimizeDoc = readMidsceneDoc(midsceneDocPaths.optimize);
108
+ const apiDoc = readMidsceneDoc(midsceneDocPaths.api);
109
+
110
+ // 兜底逻辑:合并参考文件不存在时,从原始文档抽取当前脚本生成会用到的 API 片段。
111
+ const apiSnippets = [
112
+ excerptAround(apiDoc, /agent\.aiAct\(\)/i),
113
+ excerptAround(apiDoc, /agent\.aiTap\(\)/i),
114
+ excerptAround(apiDoc, /agent\.aiInput\(\)/i),
115
+ excerptAround(apiDoc, /agent\.aiQuery\(\)/i),
116
+ excerptAround(apiDoc, /agent\.aiBoolean\(\)/i),
117
+ excerptAround(apiDoc, /agent\.aiNumber\(\)/i),
118
+ excerptAround(apiDoc, /agent\.aiString\(\)/i),
119
+ excerptAround(apiDoc, /agent\.aiWaitFor\(\)/i),
120
+ excerptAround(apiDoc, /startObserving/i),
121
+ excerptAround(apiDoc, /deepLocate/i),
122
+ ].filter(Boolean);
123
+
124
+ return [
125
+ '下面是本项目保存的 Midscene 官方文档参考。你必须参考这些内容规划脚本步骤,但最终仍只能输出前面约定的 JSON 对象。',
126
+ `文档路径:${midsceneDocPaths.optimize}`,
127
+ `文档路径:${midsceneDocPaths.api}`,
128
+ '## use-javascript-to-optimize-ai-automation-code.md',
129
+ optimizeDoc || '未读取到该文档。',
130
+ '## api.md 相关片段',
131
+ Array.from(new Set(apiSnippets)).join('\n\n---\n\n') || '未读取到相关 API 文档片段。',
132
+ ].join('\n\n');
133
+ }
134
+
135
+ function stripThinking(content: string) {
136
+ return content.replace(/<think>[\s\S]*?<\/think>/g, '').trim();
137
+ }
138
+
139
+ function extractJson(content: string) {
140
+ const clean = stripThinking(content);
141
+ const fenceMatch = clean.match(/```json\s*([\s\S]*?)```/i) || clean.match(/```\s*([\s\S]*?)```/i);
142
+ if (fenceMatch) {
143
+ return fenceMatch[1].trim();
144
+ }
145
+
146
+ const start = clean.indexOf('{');
147
+ const end = clean.lastIndexOf('}');
148
+ if (start >= 0 && end > start) {
149
+ return clean.slice(start, end + 1);
150
+ }
151
+
152
+ return clean;
153
+ }
154
+
155
+ function normalizeStep(step: Record<string, unknown>) {
156
+ const rawType = typeof step.type === 'string' && allowedTypes.has(step.type) ? step.type : 'act';
157
+ const hasRepeat = step.repeat !== undefined && step.repeat !== null && step.repeat !== '';
158
+ const rawRepeat = Number(step.repeat);
159
+ const labelText = typeof step.label === 'string' ? step.label : '';
160
+ const promptText = typeof step.prompt === 'string' ? step.prompt : '';
161
+ const isStartupPopupHandling = /(处理|关闭|循环处理).*(启动)?弹窗|启动阶段.*弹窗/.test(labelText);
162
+ const isSoftKeyboardLoginHint = /(软键盘|键盘遮挡)/.test(promptText) && /(登录按钮|提交登录|提交当前已填写)/.test(promptText);
163
+ const isConditionalNoopAction =
164
+ !isSoftKeyboardLoginHint &&
165
+ /(如果|若|如有|如果当前|如果.*未勾选|已勾选|不存在.*跳过|则跳过|保持当前|否则)/.test(promptText);
166
+ const isConditionalNoopTap =
167
+ rawType === 'tap' &&
168
+ isConditionalNoopAction;
169
+ const isLoginOneShotAction =
170
+ (rawType === 'act' || rawType === 'tap') &&
171
+ !isStartupPopupHandling &&
172
+ !isConditionalNoopAction &&
173
+ (
174
+ /(登录按钮|提交登录|登录提交|账号密码登录入口|登录协议|协议勾选|勾选.*协议|复选框|同意协议弹窗|协议确认弹窗)/.test(labelText) ||
175
+ /^(点击登录页中的登录按钮|登录页中的登录按钮|登录页底部.*勾选框|.*协议.*确认.*按钮|.*同意.*按钮)/.test(promptText)
176
+ );
177
+ const type = rawType === 'act' && isLoginOneShotAction ? 'tap' : isConditionalNoopTap ? 'act' : rawType;
178
+ const supportsObservation = type === 'act' || type === 'tap' || type === 'input';
179
+ const fallbackRepeat = 1;
180
+ const repeat = Math.max(1, Math.min(10, Math.floor(hasRepeat && Number.isFinite(rawRepeat) ? rawRepeat : fallbackRepeat)));
181
+ return {
182
+ type,
183
+ label: typeof step.label === 'string' ? step.label : '未命名步骤',
184
+ prompt: typeof step.prompt === 'string' ? step.prompt : '',
185
+ outputVar: typeof step.outputVar === 'string' ? step.outputVar : '',
186
+ value: typeof step.value === 'string' ? step.value : '',
187
+ observePrompt: supportsObservation && typeof step.observePrompt === 'string' ? step.observePrompt.trim() : '',
188
+ repeat: isLoginOneShotAction ? 1 : repeat,
189
+ enabled: step.enabled !== false,
190
+ };
191
+ }
192
+
193
+ function isMixedLoginBlockingBoolean(step: ReturnType<typeof normalizeStep>) {
194
+ if (step.type !== 'boolean') return false;
195
+ const text = `${step.label} ${step.prompt}`;
196
+ return (
197
+ text.includes('是否还存在') &&
198
+ /(登录页|登录相关|登录流程|就绪|稳定|入口)/.test(text) &&
199
+ /(遮挡|弹窗|权限|协议|广告|更新|活动)/.test(text)
200
+ );
201
+ }
202
+
203
+ function normalizeSteps(steps: Array<Record<string, unknown>>) {
204
+ return steps.flatMap((step) => {
205
+ const normalized = normalizeStep(step);
206
+ if (!isMixedLoginBlockingBoolean(normalized)) {
207
+ return [normalized];
208
+ }
209
+
210
+ return [
211
+ {
212
+ type: 'boolean',
213
+ label: '确认无干扰弹窗',
214
+ prompt: '当前页面是否还存在会遮挡登录操作的弹窗,例如权限、协议、广告、更新或活动弹窗?',
215
+ outputVar: 'hasBlockingModal',
216
+ value: '',
217
+ enabled: normalized.enabled,
218
+ },
219
+ {
220
+ type: 'boolean',
221
+ label: '验证登录页就绪',
222
+ prompt: '当前页面是否已稳定停留在目标 App 的登录页、手机号登录页、账号密码登录页,或显示可进入登录流程的入口?',
223
+ outputVar: 'isLoginReady',
224
+ value: '',
225
+ enabled: normalized.enabled,
226
+ },
227
+ ];
228
+ });
229
+ }
230
+
231
+ export async function generatePlan(input: { prompt: string }) {
232
+ const startedAt = Date.now();
233
+ const config = loadConfig();
234
+
235
+ if (!config.scriptOptimizer.model.apiKey) {
236
+ throw new Error('Missing scriptOptimizer.model.apiKey in config.json');
237
+ }
238
+
239
+ const client = new OpenAI({
240
+ apiKey: config.scriptOptimizer.model.apiKey,
241
+ baseURL: config.scriptOptimizer.model.baseUrl,
242
+ });
243
+
244
+ const completion = await client.chat.completions.create({
245
+ model: config.scriptOptimizer.model.name,
246
+ temperature: 0.2,
247
+ messages: [
248
+ { role: 'system', content: systemPrompt },
249
+ { role: 'system', content: buildMidsceneDocsContext() },
250
+ {
251
+ role: 'user',
252
+ content: JSON.stringify(
253
+ {
254
+ prompt: input.prompt,
255
+ },
256
+ null,
257
+ 2,
258
+ ),
259
+ },
260
+ ],
261
+ });
262
+
263
+ const content = completion.choices[0]?.message?.content;
264
+ if (!content) {
265
+ throw new Error('Model returned empty content');
266
+ }
267
+
268
+ const parsed = JSON.parse(extractJson(content)) as {
269
+ promptTitle?: string;
270
+ steps?: Array<Record<string, unknown>>;
271
+ };
272
+
273
+ return {
274
+ promptTitle: parsed.promptTitle || 'AI 生成脚本',
275
+ steps: Array.isArray(parsed.steps) ? normalizeSteps(parsed.steps) : [],
276
+ raw: content,
277
+ durationMs: Date.now() - startedAt,
278
+ usage: {
279
+ promptTokens: completion.usage?.prompt_tokens,
280
+ completionTokens: completion.usage?.completion_tokens,
281
+ totalTokens: completion.usage?.total_tokens,
282
+ },
283
+ };
284
+ }