android-midscene-automation 1.1.5 → 1.1.7

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 (30) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +13 -0
  3. package/package.json +1 -1
  4. package/server/appium-config.test.ts +5 -1
  5. package/server/appium-recorder/ai-recognition.ts +9 -0
  6. package/server/appium-recorder/appium-runner.ts +13 -2
  7. package/server/appium-recorder/element-tap.test.ts +61 -0
  8. package/server/appium-recorder/request-timeout.test.ts +34 -0
  9. package/server/appium-recorder/request-timeout.ts +7 -3
  10. package/server/config.ts +7 -3
  11. package/src/App.vue +1 -0
  12. package/src/appium-recorder/AppiumPage.vue +9 -4
  13. package/src/appium-recorder/components/AiRecognitionSettings.vue +141 -84
  14. package/src/appium-recorder/components/FlowCanvas.vue +39 -1
  15. package/src/appium-recorder/components/FlowNodeCard.vue +11 -1
  16. package/src/appium-recorder/components/FlowRoundedEdge.vue +20 -2
  17. package/src/appium-recorder/components/FlowStepEditor.vue +114 -85
  18. package/src/appium-recorder/components/LoopSettings.vue +12 -10
  19. package/src/appium-recorder/components/NestedConditionBranches.vue +5 -1
  20. package/src/appium-recorder/components/RecordedSteps.vue +14 -0
  21. package/src/appium-recorder/components/TextClickSettings.vue +11 -11
  22. package/src/appium-recorder/components/VariableExtractionSettings.vue +6 -4
  23. package/src/appium-recorder/flow-appearance.ts +9 -2
  24. package/src/appium-recorder/flow-graph.ts +13 -7
  25. package/src/components/config/AppiumConfigPanel.vue +2 -2
  26. package/src/components/config/FlowAppearanceSettings.vue +12 -5
  27. package/src/config/use-model-config.ts +2 -1
  28. package/src/pages/ConfigPage.vue +6 -6
  29. package/src/style.css +28 -18
  30. package/src/types.ts +1 -1
package/CHANGELOG.md CHANGED
@@ -1,4 +1,17 @@
1
1
  # 更新记录
2
+ ## v1.1.7
3
+ - [Appium]修复元素判断临近超时时误报“设备自动化服务无响应”的问题。
4
+ - [Appium]流程编辑器新增直线与曲线切换,默认使用曲线,配置自动保存并同步至主画布和流程总览。
5
+ - [Appium]优化多分支汇合线:汇合点按左右汇入线居中,增大纵向间距,曲线在底部留白处平滑汇入,减少节点遮挡。
6
+
7
+ ## v1.1.6
8
+ - [Appium]优化流程画布交互:点击节点自动放大并居中,流程总览支持还原位置,AI 识别节点提示词最多展示三行。
9
+ - [Appium]统一节点编辑界面:AI 识别、组件定位、节点信息和超时设置使用紧凑分组,优化循环、滑动、缩放等参数布局。
10
+ - [Appium]组件树搜索支持上下切换匹配项,组件详情按优先级展示定位方式和组件属性。
11
+ - [AI识别]分支提示词校验增加开放式输出说明和具体修改建议。
12
+ - [配置/UI]修复 API Key 显示按钮,统一提示弹窗、选项控件及相关配置区域样式。
13
+ - [Artemis]停止输出成功的状态与就绪探测访问日志,保留服务运行和异常日志。
14
+
2
15
  ## v1.1.5
3
16
  - UI优化
4
17
 
package/README.md CHANGED
@@ -1502,6 +1502,19 @@ Linux: ~/.local/share/android-midscene-automation
1502
1502
 
1503
1503
  # 项目更新记录
1504
1504
 
1505
+ ## v1.1.7
1506
+ - [Appium]修复元素判断临近超时时误报“设备自动化服务无响应”的问题。
1507
+ - [Appium]流程编辑器新增直线与曲线切换,默认使用曲线,配置自动保存并同步至主画布和流程总览。
1508
+ - [Appium]优化多分支汇合线:汇合点按左右汇入线居中,增大纵向间距,曲线在底部留白处平滑汇入,减少节点遮挡。
1509
+
1510
+ ## v1.1.6
1511
+ - [Appium]优化流程画布交互:点击节点自动放大并居中,流程总览支持还原位置,AI 识别节点提示词最多展示三行。
1512
+ - [Appium]统一节点编辑界面:AI 识别、组件定位、节点信息和超时设置使用紧凑分组,优化循环、滑动、缩放等参数布局。
1513
+ - [Appium]组件树搜索支持上下切换匹配项,组件详情按优先级展示定位方式和组件属性。
1514
+ - [AI识别]分支提示词校验增加开放式输出说明和具体修改建议。
1515
+ - [配置/UI]修复 API Key 显示按钮,统一提示弹窗、选项控件及相关配置区域样式。
1516
+ - [Artemis]停止输出成功的状态与就绪探测访问日志,保留服务运行和异常日志。
1517
+
1505
1518
  ## v1.1.5
1506
1519
  - UI优化
1507
1520
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "android-midscene-automation",
3
- "version": "1.1.5",
3
+ "version": "1.1.7",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/oooooooko/android-midscene-automation.git"
@@ -42,10 +42,12 @@ test('Appium autosave is isolated from manual config, persists and rejects inval
42
42
  const base = `http://127.0.0.1:${address.port}`;
43
43
  const post = (path: string, body: unknown) => fetch(base + path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
44
44
  const initial = await (await fetch(base + '/api/config')).json() as AppConfig;
45
- const appium = { ...initial.appium, flowLineColor: '#AbC', model: { baseUrl: 'https://example.invalid', apiKey: 'test', name: 'new-model' } };
45
+ assert.equal(initial.appium.flowLineStyle, 'curved');
46
+ const appium = { ...initial.appium, flowLineStyle: 'curved', flowLineColor: '#AbC', model: { baseUrl: 'https://example.invalid', apiKey: 'test', name: 'new-model' } };
46
47
  assert.equal((await post('/api/config/appium', { appium, runtime: { androidSdkPath: 'invalid-draft' }, midscene: { model: { name: 'unsaved' } } })).status, 200);
47
48
  let stored = await (await fetch(base + '/api/config')).json() as AppConfig;
48
49
  assert.equal(stored.appium.flowLineColor, '#aabbcc');
50
+ assert.equal(stored.appium.flowLineStyle, 'curved');
49
51
  assert.deepEqual(stored.runtime, initial.runtime);
50
52
  assert.deepEqual(stored.midscene, initial.midscene);
51
53
  const { appium: _appium, ...manual } = structuredClone(initial);
@@ -55,9 +57,11 @@ test('Appium autosave is isolated from manual config, persists and rejects inval
55
57
  assert.deepEqual(stored.appium.model, initial.appium.model, 'automatic saves must not persist untested model drafts');
56
58
  assert.equal(stored.midscene.model.name, initial.midscene.model.name, 'runtime save must not persist an untested model');
57
59
  assert.equal((await post('/api/config/appium', { appium: { ...appium, flowLineColor: 'invalid' } })).status, 400);
60
+ assert.equal((await post('/api/config/appium', { appium: { ...appium, flowLineStyle: 'invalid' } })).status, 400);
58
61
  assert.equal((await post('/api/config/appium', { appium: null })).status, 400);
59
62
  const { loadModelConfigFromDb } = await import('./config-store');
60
63
  assert.equal(loadModelConfigFromDb()?.appium?.flowLineColor, '#aabbcc');
64
+ assert.equal(loadModelConfigFromDb()?.appium?.flowLineStyle, 'curved');
61
65
 
62
66
  for (const key of ['midscene', 'scriptOptimizer', 'appium'] as const) {
63
67
  const before = await (await fetch(base + '/api/config')).json() as AppConfig;
@@ -55,6 +55,7 @@ export async function recognizeDeviceScreen(input: {
55
55
  onObservationFrame?: (frame: ObservationCapture) => Promise<void> | void;
56
56
  signal?: AbortSignal;
57
57
  imageBase64?: string;
58
+ onAnalysisStart?: () => void;
58
59
  onModelOutput?: (content: string) => void;
59
60
  }): Promise<AiRecognitionResult & { imageBase64: string }> {
60
61
  const prompt = validateAiRecognitionPrompt(input.prompt);
@@ -68,6 +69,7 @@ export async function recognizeDeviceScreen(input: {
68
69
  const timeoutMs = Number.isFinite(input.timeoutMs) && input.timeoutMs! > 0
69
70
  ? Math.min(300000, Math.max(1000, input.timeoutMs!)) : DEFAULT_NODE_TIMEOUT_MS;
70
71
  const captureSignal = input.signal || new AbortController().signal;
72
+ let analysisStartNotified = false;
71
73
  captureSignal.throwIfAborted();
72
74
  async function analyze(observation?: AiRecognitionResult['observation'], imageBase64 = '', requestSignal = captureSignal) {
73
75
  // 持续观察的采集窗口与模型请求分别计时,避免 3 秒请求超时截断 15 秒观察。
@@ -90,6 +92,10 @@ export async function recognizeDeviceScreen(input: {
90
92
  { type: 'image_url' as const, image_url: { url: frame.imageDataUrl, detail: 'high' as const } },
91
93
  ])
92
94
  : [{ type: 'image_url', image_url: { url: `data:image/png;base64,${imageBase64}`, detail: 'high' } }];
95
+ if (!analysisStartNotified) {
96
+ analysisStartNotified = true;
97
+ input.onAnalysisStart?.();
98
+ }
93
99
  const response = await client.chat.completions.create({
94
100
  model: model.name,
95
101
  max_completion_tokens: 2048,
@@ -163,6 +169,9 @@ export async function validateAiBranchQuestion(value: unknown, signal?: AbortSig
163
169
  询问指定对象是否存在或指定状态是否成立,包括“有没有”“是否”“是不是”“了吗”“吗”等问法,都可以作为分支条件。广告弹窗、黑屏、按钮可用等视觉概念不要求用户额外定义像素或坐标。
164
170
  必须区分封闭判断与开放问题:“当前画面有没有广告弹窗”是指定对象的存在性判断,应返回 true;“当前画面是否有广告弹窗”“页面是不是黑屏”“登录按钮可用吗”也应返回 true。
165
171
  “当前画面有什么”“描述当前画面”“提取画面中的所有文字”需要列举、描述或提取内容,应返回 false。“有没有广告弹窗,如果有请列出全部广告内容”包含开放任务,也应返回 false。
172
+ 要求输出时长、时间点、数量、名称、文字内容、画面描述、失败原因、判断依据、列表、总结,或指定“XX秒”“HH:MM:SS”“播放失败”等自定义输出格式,也属于开放式输出;即使文本前半部分可以回答是/否,只要同时要求这些额外输出,仍返回 false。
173
+ 返回 false 时,reason 必须包含“开放式内容”和“修改建议”两部分:先逐项短引用用户文本中导致失败的具体要求,再说明应删除或如何改写,并给出一个保留原判断目标、可直接回答是/否的简短问题。不得只写“包含开放式任务”等笼统原因。
174
+ 示例 reason:“开放式内容:‘输出首次变化时长’、‘失败时简要说明依据’;修改建议:删除自定义输出要求,改为‘本次观察期间录像回放是否播放成功?’。”
166
175
  只返回 JSON:{"result":true或false,"reason":"简短中文原因"}。不要输出思考过程。` },
167
176
  { role: 'user', content: prompt },
168
177
  ],
@@ -333,7 +333,7 @@ async function appiumRequest<T>(
333
333
  throw new ReplayStoppedError();
334
334
  }
335
335
  context?.appiumLog(`[Appium] 异常:${method} ${effectivePath}(${errorDetail(error)})`);
336
- if (error instanceof AppiumRequestTimeoutError) throw error;
336
+ if (error instanceof AppiumRequestTimeoutError || error instanceof ConditionTimeoutError) throw error;
337
337
  if (isTimeoutError(error)) {
338
338
  throw new AppiumServiceError(`Appium 请求超时 ${requestUrl},${errorDetail(error)}`);
339
339
  }
@@ -550,6 +550,7 @@ async function findElementWithinDeadline(sessionId: string, step: AppiumRecorded
550
550
  return await findElementBySelector(sessionId, step.selector, parentId);
551
551
  } catch (error) {
552
552
  throwIfReplayStopped(error);
553
+ if (error instanceof ConditionTimeoutError) throw error;
553
554
  lastError = error;
554
555
  // Continue with the fallback chain below.
555
556
  }
@@ -567,6 +568,7 @@ async function findElementWithinDeadline(sessionId: string, step: AppiumRecorded
567
568
  return await findElementBySelector(sessionId, selector);
568
569
  } catch (error) {
569
570
  throwIfReplayStopped(error);
571
+ if (error instanceof ConditionTimeoutError) throw error;
570
572
  lastError = error;
571
573
  }
572
574
  }
@@ -726,6 +728,7 @@ async function waitForElementGone(sessionId: string, step: AppiumRecordedStepRec
726
728
  await findElement(sessionId, step, remaining);
727
729
  } catch (error) {
728
730
  throwIfReplayStopped(error);
731
+ if (error instanceof ConditionTimeoutError) throw error;
729
732
  return;
730
733
  }
731
734
  const pauseMs = Math.min(500, timeoutMs - (Date.now() - startedAt));
@@ -744,6 +747,7 @@ async function saveScreenshot(deviceId: string) {
744
747
 
745
748
  type RunStepMeta = {
746
749
  onModelOutput?: (content: string) => void;
750
+ onAiAnalysisStart?: () => void;
747
751
  onAiProgress?: (message: string) => void;
748
752
  nodeNumber: number;
749
753
  scriptName: string;
@@ -927,7 +931,9 @@ async function runStep(
927
931
  onProgress: meta.onAiProgress,
928
932
  onObservationFrame: frame => captureReplayFrame(sessionId, step, meta.nodeNumber, meta.scriptName || '', 'observation', `观察第 ${frame.index} 帧 · ${frame.elapsedMs}ms`, frame.imageBase64),
929
933
  timeoutMs: step.timeoutMs, aiTimeoutEnabled: step.aiTimeoutEnabled === true,
930
- signal: replayContext.getStore()?.signal, onModelOutput: meta.onModelOutput,
934
+ signal: replayContext.getStore()?.signal,
935
+ onAnalysisStart: meta.onAiAnalysisStart,
936
+ onModelOutput: meta.onModelOutput,
931
937
  });
932
938
  return `AI 识别回答:${recognition.reason}`;
933
939
  }
@@ -1388,6 +1394,7 @@ async function replayLinearSteps(
1388
1394
  continue;
1389
1395
  }
1390
1396
  await replayContext.getStore()?.selectVideoScript?.(stack.at(-1) || '', options.scriptName || '');
1397
+ const nodeStartedAt = Date.now();
1391
1398
  lines.push(`[节点 ${index + 1}] 开始:${step.label}`);
1392
1399
  await captureReplayFrame(sessionId, step, index + 1, options.scriptName || '', 'before', '执行前');
1393
1400
  try {
@@ -1397,6 +1404,7 @@ async function replayLinearSteps(
1397
1404
  } else {
1398
1405
  const result = await runStep(sessionId, deviceId, step, {
1399
1406
  onAiProgress: message => lines.push(`[节点 ${index + 1}] AI 持续观察:${message}`),
1407
+ onAiAnalysisStart: () => lines.push(`[节点 ${index + 1}] AI 识别内容开始:距进入当前节点 ${Date.now() - nodeStartedAt}ms`),
1400
1408
  onModelOutput: content => lines.push(`[节点 ${index + 1}] AI 识别模型输出:${content}`),
1401
1409
  nodeNumber: index + 1,
1402
1410
  scriptName: options.scriptName || '',
@@ -1450,6 +1458,7 @@ async function replayFlowSteps(
1450
1458
  await replayContext.getStore()?.selectVideoScript?.(stack.at(-1) || '', options.scriptName || '');
1451
1459
  visitedPath.push(step.label);
1452
1460
  const nodeKind = defaultFlowKind(step);
1461
+ const nodeStartedAt = Date.now();
1453
1462
  lines.push(`[节点 ${index + 1}] 开始:${frameStep.label}`);
1454
1463
  await captureReplayFrame(sessionId, frameStep, index + 1, options.scriptName || '', 'before', '执行前');
1455
1464
 
@@ -1478,6 +1487,7 @@ async function replayFlowSteps(
1478
1487
  aiTimeoutEnabled: step.aiTimeoutEnabled === true, aiObservation: step.aiObservation,
1479
1488
  onProgress: message => lines.push(`[节点 ${index + 1}] AI 持续观察:${message}`),
1480
1489
  onObservationFrame: frame => captureReplayFrame(sessionId, frameStep, index + 1, options.scriptName || '', 'observation', `观察第 ${frame.index} 帧 · ${frame.elapsedMs}ms`, frame.imageBase64),
1490
+ onAnalysisStart: () => lines.push(`[节点 ${index + 1}] AI 识别内容开始:距进入当前节点 ${Date.now() - nodeStartedAt}ms`),
1481
1491
  onModelOutput: (content) => lines.push(`[节点 ${index + 1}] AI 识别模型输出:${content}`),
1482
1492
  signal: replayContext.getStore()?.signal,
1483
1493
  imageBase64: beforeFrame?.nodeId === step.id && beforeFrame.phase === 'before' ? beforeFrame.imageBase64 : undefined,
@@ -1576,6 +1586,7 @@ async function replayFlowSteps(
1576
1586
  } else {
1577
1587
  const result = await runStep(sessionId, deviceId, step, {
1578
1588
  onAiProgress: message => lines.push(`[节点 ${index + 1}] AI 持续观察:${message}`),
1589
+ onAiAnalysisStart: () => lines.push(`[节点 ${index + 1}] AI 识别内容开始:距进入当前节点 ${Date.now() - nodeStartedAt}ms`),
1579
1590
  onModelOutput: content => lines.push(`[节点 ${index + 1}] AI 识别模型输出:${content}`),
1580
1591
  nodeNumber: index + 1,
1581
1592
  scriptName: options.scriptName || '',
@@ -1,5 +1,6 @@
1
1
  import assert from 'node:assert/strict';
2
2
  import { test } from 'node:test';
3
+ import { setTimeout as delay } from 'node:timers/promises';
3
4
  import childProcess from 'node:child_process';
4
5
  import { syncBuiltinESMExports } from 'node:module';
5
6
  import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
@@ -186,6 +187,66 @@ test('text matching does not start another Appium query at the node deadline', a
186
187
  }
187
188
  });
188
189
 
190
+ test('missing element completes its last query and follows the timeout branch without reporting a service failure', async () => {
191
+ const root = await mkdtemp(join(tmpdir(), 'text-deadline-'));
192
+ const env = { ...process.env };
193
+ const original = { execFile: childProcess.execFile, fetch: globalThis.fetch };
194
+ let elementQueries = 0;
195
+ try {
196
+ const sdk = join(root, 'sdk');
197
+ await mkdir(join(sdk, 'platform-tools'), { recursive: true });
198
+ await writeFile(join(sdk, 'platform-tools', 'adb'), '');
199
+ Object.assign(process.env, {
200
+ ANDROID_MIDSCENE_DATA_ROOT: root,
201
+ ANDROID_HOME: sdk,
202
+ ANDROID_SDK_ROOT: sdk,
203
+ APPIUM_SERVER_URL: 'http://external.invalid',
204
+ });
205
+ childProcess.execFile = ((_command, _args: string[], _options, callback) => {
206
+ queueMicrotask(() => callback(null, '', ''));
207
+ return {};
208
+ }) as typeof childProcess.execFile;
209
+ syncBuiltinESMExports();
210
+ globalThis.fetch = async (input, init) => {
211
+ const path = new URL(String(input)).pathname;
212
+ if (path === '/session' && init?.method === 'POST') {
213
+ return Response.json({ value: { sessionId: 'deadline-session' } });
214
+ }
215
+ if (path === '/session/deadline-session/element') {
216
+ elementQueries += 1;
217
+ await delay(150, undefined, { signal: init?.signal ?? undefined });
218
+ return Response.json({ value: { error: 'no such element', message: 'not found' } }, { status: 404 });
219
+ }
220
+ return Response.json({ value: null });
221
+ };
222
+ const { replayAppiumScript } = await import('./appium-runner');
223
+ const script: AppiumRecordedScriptRecord = {
224
+ id: 'deadline', name: 'deadline', deviceId: 'fake-device', appPackage: '', appActivity: '', createdAt: '', updatedAt: '',
225
+ steps: [{
226
+ id: 'text', type: 'assertExists', label: '判断低功耗主页', timeoutMs: 100,
227
+ selector: { strategy: 'id', value: 'example:id/batterItem', unique: true },
228
+ timeoutBranch: 'no', flow: { nodeKind: 'condition', noTargetId: 'done' },
229
+ }, { id: 'done', type: 'noop', label: '继续执行' }],
230
+ };
231
+ const result = await replayAppiumScript(script, 'fake-device', undefined, undefined, {
232
+ screenshotReport: false,
233
+ reportSummaryEnabled: false,
234
+ });
235
+ assert.equal(result.success, true, result.output);
236
+ assert.doesNotMatch(result.output, /服务无响应/);
237
+ assert.equal(elementQueries, 1, 'no retry after the node deadline');
238
+ assert.match(result.output, /判断超时,按配置进入右侧分支/);
239
+ } finally {
240
+ childProcess.execFile = original.execFile;
241
+ globalThis.fetch = original.fetch;
242
+ syncBuiltinESMExports();
243
+ for (const key of ['ANDROID_MIDSCENE_DATA_ROOT', 'ANDROID_HOME', 'ANDROID_SDK_ROOT', 'APPIUM_SERVER_URL']) {
244
+ if (env[key] === undefined) delete process.env[key]; else process.env[key] = env[key];
245
+ }
246
+ await rm(root, { recursive: true, force: true });
247
+ }
248
+ });
249
+
189
250
  test('optional tap recovers a blocked UiAutomator2 session and uses the ADB hierarchy', async () => {
190
251
  const root = await mkdtemp(join(tmpdir(), 'optional-recovery-'));
191
252
  const env = { ...process.env };
@@ -0,0 +1,34 @@
1
+ import assert from 'node:assert/strict';
2
+ import { test } from 'node:test';
3
+ import { createServer } from 'node:http';
4
+ import { setTimeout as delay } from 'node:timers/promises';
5
+ import { ConditionTimeoutError } from './condition-timeout';
6
+ import { AppiumRequestTimeoutError, timedAppiumFetch, withElementDeadline } from './request-timeout';
7
+
8
+ test('element deadline does not shorten an in-flight request or its response body', async () => {
9
+ const server = createServer(async (_req, res) => {
10
+ res.writeHead(404, { 'Content-Type': 'application/json' });
11
+ res.flushHeaders();
12
+ await delay(150);
13
+ res.end('{"value":{"error":"no such element"}}');
14
+ });
15
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
16
+ const url = `http://127.0.0.1:${(server.address() as { port: number }).port}/element`;
17
+ try {
18
+ const result = await withElementDeadline(50, () => timedAppiumFetch(url, {}, 2000));
19
+ assert.equal(result.response.status, 404);
20
+ assert.equal(JSON.parse(result.text).value.error, 'no such element');
21
+ await assert.rejects(withElementDeadline(1, async () => {
22
+ await delay(10);
23
+ return timedAppiumFetch(url, {}, 2000);
24
+ }), ConditionTimeoutError);
25
+ await assert.rejects(withElementDeadline(10, () => timedAppiumFetch(url, {}, 50)), AppiumRequestTimeoutError);
26
+ const controller = new AbortController();
27
+ const request = timedAppiumFetch(url, { signal: controller.signal }, 2000);
28
+ controller.abort(new Error('user stopped'));
29
+ await assert.rejects(request, /user stopped/);
30
+ } finally {
31
+ server.closeAllConnections();
32
+ await new Promise<void>(resolve => server.close(() => resolve()));
33
+ }
34
+ });
@@ -1,4 +1,5 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { ConditionTimeoutError } from './condition-timeout';
2
3
 
3
4
  const deadline = new AsyncLocalStorage<number>();
4
5
  export class AppiumRequestTimeoutError extends Error {}
@@ -14,8 +15,11 @@ export function remainingElementDeadlineMs() {
14
15
 
15
16
  // 响应体也受同一个期限约束,避免收到 HTTP 头后继续无限等待。
16
17
  export async function timedAppiumFetch(url: string, init: RequestInit, timeoutMs: number) {
17
- const remaining = Math.max(1, Math.min(timeoutMs, (deadline.getStore() ?? Infinity) - Date.now()));
18
- const timeout = AbortSignal.timeout(Math.ceil(remaining));
18
+ const elementRemaining = remainingElementDeadlineMs();
19
+ if (elementRemaining <= 0) throw new ConditionTimeoutError('元素定位等待期限已到');
20
+ // 节点期限限制是否继续查找;已发出的请求使用独立通信超时,
21
+ // 避免把最后一次正常查询因剩余预算过短误报为服务无响应。
22
+ const timeout = AbortSignal.timeout(Math.ceil(timeoutMs));
19
23
  const signal = init.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
20
24
  try {
21
25
  const response = await fetch(url, { ...init, signal });
@@ -23,7 +27,7 @@ export async function timedAppiumFetch(url: string, init: RequestInit, timeoutMs
23
27
  return { response, text };
24
28
  } catch (error) {
25
29
  if (timeout.aborted && !init.signal?.aborted) {
26
- throw new AppiumRequestTimeoutError(`设备自动化服务无响应:Appium 请求超过 ${Math.ceil(remaining)}ms,已停止等待(${url})`);
30
+ throw new AppiumRequestTimeoutError(`设备自动化服务无响应:Appium 请求超过 ${Math.ceil(timeoutMs)}ms,已停止等待(${url})`);
27
31
  }
28
32
  throw error;
29
33
  }
package/server/config.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { resolveReportSummary, type ReportSummaryConfig } from '../src/appium-recorder/report-summary';
2
2
  import type { AiPromptPreset } from '../src/appium-recorder/ai-prompt-presets';
3
3
  import fs from 'node:fs';
4
- import { isHexColor, normalizeFlowBackground, normalizeFlowLineColor } from '../src/appium-recorder/flow-appearance';
4
+ import { isHexColor, normalizeFlowBackground, normalizeFlowLineColor, normalizeFlowLineStyle } from '../src/appium-recorder/flow-appearance';
5
5
  import os from 'node:os';
6
6
  import path from 'node:path';
7
7
  import YAML from 'yaml';
@@ -13,7 +13,7 @@ import { resolveAiDeduplication, type AiDeduplicationConfig } from '../src/appiu
13
13
  import type { MidsceneModelProvider } from '../src/config/midscene-model-presets';
14
14
 
15
15
  export type AppConfig = {
16
- appium: { reportSummary?: ReportSummaryConfig; model: AiRecognitionModel; promptOptimizer?: { model: AiRecognitionModel }; aiPromptPresets?: AiPromptPreset[]; aiDeduplication?: AiDeduplicationConfig; flowBackgroundColor?: string; flowLineColor?: string; screenshotReport?: boolean };
16
+ appium: { reportSummary?: ReportSummaryConfig; model: AiRecognitionModel; promptOptimizer?: { model: AiRecognitionModel }; aiPromptPresets?: AiPromptPreset[]; aiDeduplication?: AiDeduplicationConfig; flowBackgroundColor?: string; flowLineColor?: string; flowLineStyle?: 'straight' | 'curved'; screenshotReport?: boolean };
17
17
  runtime: {
18
18
  androidSdkPath: string;
19
19
  reportOutputPath: string;
@@ -100,6 +100,7 @@ function normalizeConfig(config: Partial<AppConfig> | null | undefined): AppConf
100
100
  screenshotReport: config?.appium?.screenshotReport === true,
101
101
  flowBackgroundColor: normalizeFlowBackground(config?.appium?.flowBackgroundColor),
102
102
  flowLineColor: normalizeFlowLineColor(config?.appium?.flowLineColor),
103
+ flowLineStyle: normalizeFlowLineStyle(config?.appium?.flowLineStyle),
103
104
  model: Object.fromEntries(['baseUrl', 'apiKey', 'name'].map((key) => {
104
105
  const value = config?.appium?.model?.[key as keyof AiRecognitionModel];
105
106
  return [key, typeof value === 'string' ? value.trim() : ''];
@@ -234,11 +235,14 @@ export function saveConfig(config: AppConfig) {
234
235
  try { resolveAiDeduplication(config.appium?.aiDeduplication); }
235
236
  catch (error) { throw new ConfigValidationError(error instanceof Error ? error.message : '截图去重配置无效'); }
236
237
  if (config.appium?.flowBackgroundColor !== undefined && !isHexColor(config.appium.flowBackgroundColor)) {
237
- throw new ConfigValidationError('流程背景色必须是有效的十六进制颜色(#RGB 或 #RRGGBB)');
238
+ throw new ConfigValidationError('画布背景色必须是有效的十六进制颜色(#RGB 或 #RRGGBB)');
238
239
  }
239
240
  if (config.appium?.flowLineColor !== undefined && !isHexColor(config.appium.flowLineColor)) {
240
241
  throw new ConfigValidationError('连接线条颜色必须是有效的十六进制颜色(#RGB 或 #RRGGBB)');
241
242
  }
243
+ if (config.appium?.flowLineStyle !== undefined && !['straight', 'curved'].includes(config.appium.flowLineStyle)) {
244
+ throw new ConfigValidationError('连接线条样式必须是直线或曲线');
245
+ }
242
246
  const normalized = normalizeConfig(config);
243
247
  validateRuntimeConfig(normalized);
244
248
  cachedConfig = normalized;
package/src/App.vue CHANGED
@@ -994,6 +994,7 @@ onUnmounted(() => {
994
994
  :report-summary="configForm.appium.reportSummary"
995
995
  :flow-background-color="configForm.appium.flowBackgroundColor"
996
996
  :flow-line-color="configForm.appium.flowLineColor"
997
+ :flow-line-style="configForm.appium.flowLineStyle"
997
998
  :device-actions="deviceActions"
998
999
  :playground-available="playgroundAvailable"
999
1000
  :playground-device-id="playgroundDeviceId"
@@ -1,12 +1,12 @@
1
1
  <script setup lang="ts">
2
- import { computed, h, onMounted, onUnmounted, provide, reactive, shallowRef, watch } from 'vue';
3
- import { flowBackgroundKey, normalizeFlowBackground, flowLineColorKey, normalizeFlowLineColor } from './flow-appearance';
2
+ import { computed, h, nextTick, onMounted, onUnmounted, provide, reactive, shallowRef, useTemplateRef, watch } from 'vue';
3
+ import { flowBackgroundKey, normalizeFlowBackground, flowLineColorKey, normalizeFlowLineColor, flowLineStyleKey, normalizeFlowLineStyle, type FlowLineStyle } from './flow-appearance';
4
4
  import { useCoordinatePicker } from './coordinate-preview';
5
5
  import { DEFAULT_NODE_TIMEOUT_MS } from './node-timeout';
6
6
  import { aiPromptPresetsKey, DEFAULT_AI_PROMPT_PRESETS, type AiPromptPreset } from './ai-prompt-presets';
7
7
  import AiRecognitionPromptInput from './components/AiRecognitionPromptInput.vue';
8
8
  import { ElForm, ElFormItem, ElInputNumber, ElMessage, ElMessageBox, ElOption, ElSelect } from 'element-plus';
9
- import { ArrowDown, Check, CircleClose, CopyDocument, Delete, Document, Download, Edit, Plus, Refresh, Upload, VideoPlay, View, Clock } from '@element-plus/icons-vue';
9
+ import { ArrowDown, Check, CircleClose, CopyDocument, Delete, Document, Download, Edit, FolderOpened, Plus, Refresh, Upload, VideoPlay, View, Clock } from '@element-plus/icons-vue';
10
10
  import RunHistoryDialog from './RunHistoryDialog.vue';
11
11
  import type { AndroidDevice, AppPreset, DeviceAction } from '../types';
12
12
  import DevicePreviewPanel from '../components/device/DevicePreviewPanel.vue';
@@ -112,6 +112,7 @@ const props = defineProps<{
112
112
  reportSummary?: ReportSummaryConfig;
113
113
  flowBackgroundColor?: string;
114
114
  flowLineColor?: string;
115
+ flowLineStyle?: FlowLineStyle;
115
116
  active: boolean;
116
117
  appPresets: AppPreset[];
117
118
  deviceActions: readonly DeviceAction[];
@@ -138,6 +139,7 @@ const props = defineProps<{
138
139
  // provide/inject 随组件关系传递,放大弹窗 teleport 后也能使用同一颜色。
139
140
  provide(flowBackgroundKey, computed(() => normalizeFlowBackground(props.flowBackgroundColor)));
140
141
  provide(flowLineColorKey, computed(() => normalizeFlowLineColor(props.flowLineColor)));
142
+ provide(flowLineStyleKey, computed(() => normalizeFlowLineStyle(props.flowLineStyle)));
141
143
  const availableAiPromptPresets = computed(() => props.aiPromptPresets ?? DEFAULT_AI_PROMPT_PRESETS);
142
144
  const availableReportTemplates = computed(() => [
143
145
  ...REPORT_SUMMARY_PROMPT_PRESETS,
@@ -150,6 +152,7 @@ const tree = shallowRef<AppiumNode | null>(null);
150
152
  const selectedNode = shallowRef<AppiumNode | null>(null);
151
153
  const scripts = shallowRef<AppiumRecordedScript[]>([]);
152
154
  const selectedScriptId = shallowRef('');
155
+ const recordedStepsRef = useTemplateRef('recordedStepsRef');
153
156
  const newScriptDialogVisible = shallowRef(false);
154
157
  const newScriptRevision = shallowRef(0);
155
158
  const storedWorkbenchTab = window.localStorage.getItem(WORKBENCH_TAB_STORAGE_KEY);
@@ -1866,6 +1869,7 @@ function loadScript(script: AppiumRecordedScript) {
1866
1869
  }
1867
1870
  steps.value = normalizeLegacyNestedConditionBranches((script.steps || []).map(normalizeLegacyFlowScope));
1868
1871
  markDraftSaved();
1872
+ void nextTick(() => recordedStepsRef.value?.resetMainFlowPosition());
1869
1873
  }
1870
1874
 
1871
1875
  function loadSelectedScript() {
@@ -2390,6 +2394,7 @@ watch(
2390
2394
 
2391
2395
  <section class="appium-workbench__section appium-workbench__flow">
2392
2396
  <RecordedSteps
2397
+ ref="recordedStepsRef"
2393
2398
  :key="newScriptRevision"
2394
2399
  :ai-recognition-model-configured="aiRecognitionModelConfigured"
2395
2400
  :steps="steps"
@@ -2448,7 +2453,7 @@ watch(
2448
2453
  <el-button size="small" :icon="Clock" aria-label="历史结果对比" @click.stop="historyScript = { id: script.id, name: script.name }" />
2449
2454
  </span></el-tooltip>
2450
2455
  <el-tooltip content="加载" placement="top" :show-after="200"><span class="appium-script-icon">
2451
- <el-button size="small" :icon="Document" aria-label="加载" @click.stop="loadScript(script)" />
2456
+ <el-button size="small" :icon="FolderOpened" aria-label="加载" @click.stop="loadScript(script)" />
2452
2457
  </span></el-tooltip>
2453
2458
  <el-tooltip content="修改脚本名称" placement="top" :show-after="200"><span class="appium-script-icon">
2454
2459
  <el-button