android-midscene-automation 1.1.4 → 1.1.6

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/CHANGELOG.md CHANGED
@@ -1,4 +1,15 @@
1
1
  # 更新记录
2
+ ## v1.1.6
3
+ - [Appium]优化流程画布交互:点击节点自动放大并居中,流程总览支持还原位置,AI 识别节点提示词最多展示三行。
4
+ - [Appium]统一节点编辑界面:AI 识别、组件定位、节点信息和超时设置使用紧凑分组,优化循环、滑动、缩放等参数布局。
5
+ - [Appium]组件树搜索支持上下切换匹配项,组件详情按优先级展示定位方式和组件属性。
6
+ - [AI识别]分支提示词校验增加开放式输出说明和具体修改建议。
7
+ - [配置/UI]修复 API Key 显示按钮,统一提示弹窗、选项控件及相关配置区域样式。
8
+ - [Artemis]停止输出成功的状态与就绪探测访问日志,保留服务运行和异常日志。
9
+
10
+ ## v1.1.5
11
+ - UI优化
12
+
2
13
  ## v1.1.4
3
14
  - [Appium]修复持续刷新页面中的操作超时,以及可选元素未出现时误报失败的问题。
4
15
  - [Appium]脚本列表支持批量导入并自动重建连接脚本关系;导入后保留列表页,不自动加载脚本。
package/README.md CHANGED
@@ -1502,6 +1502,17 @@ Linux: ~/.local/share/android-midscene-automation
1502
1502
 
1503
1503
  # 项目更新记录
1504
1504
 
1505
+ ## v1.1.6
1506
+ - [Appium]优化流程画布交互:点击节点自动放大并居中,流程总览支持还原位置,AI 识别节点提示词最多展示三行。
1507
+ - [Appium]统一节点编辑界面:AI 识别、组件定位、节点信息和超时设置使用紧凑分组,优化循环、滑动、缩放等参数布局。
1508
+ - [Appium]组件树搜索支持上下切换匹配项,组件详情按优先级展示定位方式和组件属性。
1509
+ - [AI识别]分支提示词校验增加开放式输出说明和具体修改建议。
1510
+ - [配置/UI]修复 API Key 显示按钮,统一提示弹窗、选项控件及相关配置区域样式。
1511
+ - [Artemis]停止输出成功的状态与就绪探测访问日志,保留服务运行和异常日志。
1512
+
1513
+ ## v1.1.5
1514
+ - UI优化
1515
+
1505
1516
  ## v1.1.4
1506
1517
  - [Appium]修复持续刷新页面中的操作超时,以及可选元素未出现时误报失败的问题。
1507
1518
  - [Appium]脚本列表支持批量导入并自动重建连接脚本关系;导入后保留列表页,不自动加载脚本。
@@ -19,7 +19,9 @@ Modular entrypoint for full trace inspection, step replay, and task execution ma
19
19
 
20
20
  import argparse
21
21
  import asyncio
22
+ import copy
22
23
  from contextlib import asynccontextmanager
24
+ import logging
23
25
  import os
24
26
  from pathlib import Path
25
27
  import secrets
@@ -452,6 +454,35 @@ class ArtemisUvicornServer(uvicorn.Server):
452
454
  super().handle_exit(sig, frame)
453
455
 
454
456
 
457
+ class QuietProbeAccessFilter(logging.Filter):
458
+ """Hide successful high-frequency probe requests from Uvicorn access logs."""
459
+
460
+ _quiet_paths = frozenset({"/api/status", "/api/system/readiness"})
461
+
462
+ def filter(self, record: logging.LogRecord) -> bool:
463
+ args = record.args
464
+ if not isinstance(args, tuple) or len(args) < 5:
465
+ return True
466
+ method = str(args[1]).upper()
467
+ path = str(args[2]).partition("?")[0]
468
+ try:
469
+ status_code = int(args[4])
470
+ except (TypeError, ValueError):
471
+ return True
472
+ return not (method == "GET" and path in self._quiet_paths and status_code == 200)
473
+
474
+
475
+ def _uvicorn_log_config() -> dict:
476
+ """Keep normal access logs while silencing successful background probes."""
477
+ config = copy.deepcopy(uvicorn.config.LOGGING_CONFIG)
478
+ filter_name = "quiet_artemis_probes"
479
+ config.setdefault("filters", {})[filter_name] = {"()": QuietProbeAccessFilter}
480
+ access_handler = config.get("handlers", {}).get("access")
481
+ if access_handler is not None:
482
+ access_handler["filters"] = [*access_handler.get("filters", []), filter_name]
483
+ return config
484
+
485
+
455
486
  def run_ui_server(host: str, port: int, reload: bool = False) -> None:
456
487
  """Run the UI server with bounded, signal-aware graceful shutdown."""
457
488
  state.host = host
@@ -466,6 +497,7 @@ def run_ui_server(host: str, port: int, reload: bool = False) -> None:
466
497
  port=port,
467
498
  reload=True,
468
499
  timeout_graceful_shutdown=5,
500
+ log_config=_uvicorn_log_config(),
469
501
  )
470
502
  return
471
503
 
@@ -474,6 +506,7 @@ def run_ui_server(host: str, port: int, reload: bool = False) -> None:
474
506
  host=host,
475
507
  port=port,
476
508
  timeout_graceful_shutdown=5,
509
+ log_config=_uvicorn_log_config(),
477
510
  )
478
511
  server = ArtemisUvicornServer(config)
479
512
  app.state.uvicorn_server = server
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "android-midscene-automation",
3
- "version": "1.1.4",
3
+ "version": "1.1.6",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/oooooooko/android-midscene-automation.git"
@@ -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
  ],
@@ -744,6 +744,7 @@ async function saveScreenshot(deviceId: string) {
744
744
 
745
745
  type RunStepMeta = {
746
746
  onModelOutput?: (content: string) => void;
747
+ onAiAnalysisStart?: () => void;
747
748
  onAiProgress?: (message: string) => void;
748
749
  nodeNumber: number;
749
750
  scriptName: string;
@@ -927,7 +928,9 @@ async function runStep(
927
928
  onProgress: meta.onAiProgress,
928
929
  onObservationFrame: frame => captureReplayFrame(sessionId, step, meta.nodeNumber, meta.scriptName || '', 'observation', `观察第 ${frame.index} 帧 · ${frame.elapsedMs}ms`, frame.imageBase64),
929
930
  timeoutMs: step.timeoutMs, aiTimeoutEnabled: step.aiTimeoutEnabled === true,
930
- signal: replayContext.getStore()?.signal, onModelOutput: meta.onModelOutput,
931
+ signal: replayContext.getStore()?.signal,
932
+ onAnalysisStart: meta.onAiAnalysisStart,
933
+ onModelOutput: meta.onModelOutput,
931
934
  });
932
935
  return `AI 识别回答:${recognition.reason}`;
933
936
  }
@@ -1388,6 +1391,7 @@ async function replayLinearSteps(
1388
1391
  continue;
1389
1392
  }
1390
1393
  await replayContext.getStore()?.selectVideoScript?.(stack.at(-1) || '', options.scriptName || '');
1394
+ const nodeStartedAt = Date.now();
1391
1395
  lines.push(`[节点 ${index + 1}] 开始:${step.label}`);
1392
1396
  await captureReplayFrame(sessionId, step, index + 1, options.scriptName || '', 'before', '执行前');
1393
1397
  try {
@@ -1397,6 +1401,7 @@ async function replayLinearSteps(
1397
1401
  } else {
1398
1402
  const result = await runStep(sessionId, deviceId, step, {
1399
1403
  onAiProgress: message => lines.push(`[节点 ${index + 1}] AI 持续观察:${message}`),
1404
+ onAiAnalysisStart: () => lines.push(`[节点 ${index + 1}] AI 识别内容开始:距进入当前节点 ${Date.now() - nodeStartedAt}ms`),
1400
1405
  onModelOutput: content => lines.push(`[节点 ${index + 1}] AI 识别模型输出:${content}`),
1401
1406
  nodeNumber: index + 1,
1402
1407
  scriptName: options.scriptName || '',
@@ -1450,6 +1455,7 @@ async function replayFlowSteps(
1450
1455
  await replayContext.getStore()?.selectVideoScript?.(stack.at(-1) || '', options.scriptName || '');
1451
1456
  visitedPath.push(step.label);
1452
1457
  const nodeKind = defaultFlowKind(step);
1458
+ const nodeStartedAt = Date.now();
1453
1459
  lines.push(`[节点 ${index + 1}] 开始:${frameStep.label}`);
1454
1460
  await captureReplayFrame(sessionId, frameStep, index + 1, options.scriptName || '', 'before', '执行前');
1455
1461
 
@@ -1478,6 +1484,7 @@ async function replayFlowSteps(
1478
1484
  aiTimeoutEnabled: step.aiTimeoutEnabled === true, aiObservation: step.aiObservation,
1479
1485
  onProgress: message => lines.push(`[节点 ${index + 1}] AI 持续观察:${message}`),
1480
1486
  onObservationFrame: frame => captureReplayFrame(sessionId, frameStep, index + 1, options.scriptName || '', 'observation', `观察第 ${frame.index} 帧 · ${frame.elapsedMs}ms`, frame.imageBase64),
1487
+ onAnalysisStart: () => lines.push(`[节点 ${index + 1}] AI 识别内容开始:距进入当前节点 ${Date.now() - nodeStartedAt}ms`),
1481
1488
  onModelOutput: (content) => lines.push(`[节点 ${index + 1}] AI 识别模型输出:${content}`),
1482
1489
  signal: replayContext.getStore()?.signal,
1483
1490
  imageBase64: beforeFrame?.nodeId === step.id && beforeFrame.phase === 'before' ? beforeFrame.imageBase64 : undefined,
@@ -1576,6 +1583,7 @@ async function replayFlowSteps(
1576
1583
  } else {
1577
1584
  const result = await runStep(sessionId, deviceId, step, {
1578
1585
  onAiProgress: message => lines.push(`[节点 ${index + 1}] AI 持续观察:${message}`),
1586
+ onAiAnalysisStart: () => lines.push(`[节点 ${index + 1}] AI 识别内容开始:距进入当前节点 ${Date.now() - nodeStartedAt}ms`),
1579
1587
  onModelOutput: content => lines.push(`[节点 ${index + 1}] AI 识别模型输出:${content}`),
1580
1588
  nodeNumber: index + 1,
1581
1589
  scriptName: options.scriptName || '',
@@ -19,6 +19,17 @@ const branch = computed(() => isAiBranchEnabled(props.step));
19
19
  const untilMatch = computed(() => props.step.aiObservation?.mode === 'untilMatch');
20
20
  const branchChoice = ref(branch.value);
21
21
  const fallbackEnabled = shallowRef(Boolean(props.step.aiInvalidResultBranch));
22
+ const activeSections = ref<string[]>(['prompt']);
23
+ const observationSummary = computed(() => {
24
+ if (!props.step.aiObservation) return '单帧识别';
25
+ const mode = props.step.aiObservation.mode === 'untilMatch' ? '命中即结束' : '统一分析';
26
+ return `${mode} · ${props.step.aiObservation.durationMs / 1000} 秒`;
27
+ });
28
+ const branchSummary = computed(() => {
29
+ if (!branch.value) return '未启用';
30
+ if (!props.step.aiInvalidResultBranch) return '已启用';
31
+ return `已启用 · 无效结果进入${props.step.aiInvalidResultBranch === 'yes' ? '左侧' : '右侧'}`;
32
+ });
22
33
  watch(branch, value => { branchChoice.value = value; });
23
34
  watch(() => props.step.aiInvalidResultBranch, value => { fallbackEnabled.value = Boolean(value); });
24
35
  let controller: AbortController | undefined;
@@ -82,7 +93,10 @@ async function save(enabled: boolean, observation?: AiObservationConfig) {
82
93
  const value = validateAiRecognitionPrompt(prompt.value);
83
94
  if (enabled || (observation ?? props.step.aiObservation)?.mode === 'untilMatch') {
84
95
  const validation = await validateAiBranchQuestion(value, signal);
85
- if (!validation.result) throw new Error(`${enabled ? '无法进入分支' : '命中条件无效'}:${validation.reason || '请填写可用 true/false 判断的问题'}`);
96
+ if (!validation.result) {
97
+ const reason = validation.reason || '提示词不是可直接判断 true/false 的封闭条件';
98
+ throw new Error(`${enabled ? '无法进入分支' : '命中条件无效'}:${reason}\n开放式输出包括:输出时长或时间点、列举或提取内容、描述画面、说明失败原因或判断依据,以及指定“XX秒”“HH:MM:SS”“播放失败”等格式。\n修改建议:删除额外输出要求,只保留一个可回答“是/否”的判断问题及其成立、不成立条件;需要详细内容时请关闭分支并使用普通识别。`);
99
+ }
86
100
  }
87
101
  if (signal.aborted) return;
88
102
  emit('update', { value, aiBranchEnabled: enabled, ...(observation ? { aiObservation: observation } : {}), flow: { ...props.step.flow, nodeKind: enabled ? 'condition' : 'action' } });
@@ -93,89 +107,113 @@ async function save(enabled: boolean, observation?: AiObservationConfig) {
93
107
  </script>
94
108
 
95
109
  <template>
96
- <el-form-item label="识别方式">
97
- <template #label>
98
- <span class="recognition-label">识别方式
99
- <el-tooltip placement="top" :show-after="200">
100
- <template #content><div class="recognition-help-content">单帧识别:截取当前画面并分析。持续观察:按采样间隔连续截图,判断目标是否在观察期间出现过。建议紧接启动 App 或触发广告的操作放置本节点。</div></template>
101
- <el-button class="recognition-help" text :icon="QuestionFilled" aria-label="识别方式说明" @click.prevent />
102
- </el-tooltip>
103
- </span>
104
- </template>
105
- <el-radio-group :model-value="Boolean(step.aiObservation)" :disabled="disabled || busy" @update:model-value="emit('update', { aiObservation: $event ? { ...DEFAULT_AI_OBSERVATION } : undefined }); error = ''">
106
- <el-radio-button :value="false">单帧识别</el-radio-button>
107
- <el-radio-button :value="true">持续观察</el-radio-button>
108
- </el-radio-group>
109
- </el-form-item>
110
- <template v-if="step.aiObservation">
111
- <el-form-item label="观察模式">
112
- <template #label>
113
- <span class="recognition-label">观察模式
114
- <el-tooltip placement="top" :show-after="200">
115
- <template #content>
116
- <div class="recognition-help-content">
117
- <p>观察结束后统一分析:完成采样后,将保留的截图一次提交给模型。</p>
118
- <p>检测命中后提前结束:采样期间逐次识别,确认命中后停止观察并执行下一节点;启用分支时走“是”分支。达到最长观察时间后停止采样,等待剩余关键帧判断,未命中则继续下一节点或走“否”分支。</p>
119
- <p>最多采样 30 帧,实际速度取决于设备,截图按去重配置保留。观察时长与模型请求超时分别计时;提前结束模式可能多次调用模型,实际结束时间包含模型等待,识别错误不会视为未命中。</p>
120
- </div>
110
+ <div class="ai-recognition-settings">
111
+ <el-collapse v-model="activeSections" class="ai-recognition-settings__groups">
112
+ <el-collapse-item name="prompt">
113
+ <template #title>
114
+ <span class="ai-recognition-settings__group-title"><strong>识别内容</strong><small>{{ prompt.trim() ? '已填写' : '未填写' }}</small></span>
115
+ </template>
116
+ <el-form-item :label="untilMatch ? '命中条件' : '识别内容'">
117
+ <template #label>
118
+ <span class="recognition-label">{{ untilMatch ? '命中条件' : '识别内容' }}
119
+ <el-tooltip v-if="untilMatch" placement="top" :show-after="200">
120
+ <template #content><div class="recognition-help-content">填写能用“是 / 否”判断的具体条件,例如“当前画面是否出现广告弹窗?”。模型判断为“是”即命中并提前结束观察;修改条件后需验证并保存。“广告内容是什么”等开放式问题请使用统一分析模式。</div></template>
121
+ <el-button class="recognition-help" text :icon="QuestionFilled" aria-label="命中条件说明" @click.prevent />
122
+ </el-tooltip>
123
+ </span>
124
+ </template>
125
+ <AiRecognitionPromptInput v-model="prompt" :presets="promptPresets" :placeholder="untilMatch ? '例如:当前画面是否出现广告弹窗?' : ''" :disabled="disabled || busy || optimizingPrompt" @change="error = ''; !branch && !untilMatch && save(false)" />
126
+ <div class="recognition-prompt-actions">
127
+ <el-button :loading="optimizingPrompt" :disabled="disabled || busy || !prompt.trim()" @click="optimizePrompt">优化提示词</el-button>
128
+ <el-button v-if="(branch || untilMatch) && prompt !== step.value" :disabled="disabled || busy || optimizingPrompt" @click="save(branch)">验证并保存问题</el-button>
129
+ </div>
130
+ </el-form-item>
131
+ </el-collapse-item>
132
+
133
+ <el-collapse-item name="observation">
134
+ <template #title>
135
+ <span class="ai-recognition-settings__group-title"><strong>观察设置</strong><small>{{ observationSummary }}</small></span>
136
+ </template>
137
+ <el-form-item label="识别方式">
138
+ <template #label>
139
+ <span class="recognition-label">识别方式
140
+ <el-tooltip placement="top" :show-after="200">
141
+ <template #content><div class="recognition-help-content">单帧识别:截取当前画面并分析。持续观察:按采样间隔连续截图,判断目标是否在观察期间出现过。建议紧接启动 App 或触发广告的操作放置本节点。</div></template>
142
+ <el-button class="recognition-help" text :icon="QuestionFilled" aria-label="识别方式说明" @click.prevent />
143
+ </el-tooltip>
144
+ </span>
145
+ </template>
146
+ <el-radio-group :model-value="Boolean(step.aiObservation)" :disabled="disabled || busy" @update:model-value="emit('update', { aiObservation: $event ? { ...DEFAULT_AI_OBSERVATION } : undefined }); error = ''">
147
+ <el-radio-button :value="false">单帧识别</el-radio-button>
148
+ <el-radio-button :value="true">持续观察</el-radio-button>
149
+ </el-radio-group>
150
+ </el-form-item>
151
+ <template v-if="step.aiObservation">
152
+ <el-form-item label="观察模式">
153
+ <template #label>
154
+ <span class="recognition-label">观察模式
155
+ <el-tooltip placement="top" :show-after="200">
156
+ <template #content>
157
+ <div class="recognition-help-content">
158
+ <p>观察结束后统一分析:完成采样后,将保留的截图一次提交给模型。</p>
159
+ <p>检测命中后提前结束:采样期间逐次识别,确认命中后停止观察并执行下一节点;启用分支时走“是”分支。达到最长观察时间后停止采样,等待剩余关键帧判断,未命中则继续下一节点或走“否”分支。</p>
160
+ <p>最多采样 30 帧,实际速度取决于设备,截图按去重配置保留。观察时长与模型请求超时分别计时;提前结束模式可能多次调用模型,实际结束时间包含模型等待,识别错误不会视为未命中。</p>
161
+ </div>
162
+ </template>
163
+ <el-button class="recognition-help" text :icon="QuestionFilled" aria-label="观察模式说明" @click.prevent />
164
+ </el-tooltip>
165
+ </span>
166
+ </template>
167
+ <el-radio-group :model-value="step.aiObservation.mode ?? 'batch'" :disabled="disabled || busy" @update:model-value="$event === 'untilMatch' ? save(branch, { ...step.aiObservation!, mode: 'untilMatch' }) : updateObservation({ mode: 'batch' })">
168
+ <el-radio-button value="batch">观察结束后统一分析</el-radio-button>
169
+ <el-radio-button value="untilMatch">检测命中后提前结束</el-radio-button>
170
+ </el-radio-group>
171
+ </el-form-item>
172
+ <div class="ai-recognition-settings__grid">
173
+ <el-form-item :label="untilMatch ? '最长观察时间 ms' : '观察时长 ms'">
174
+ <el-input-number :model-value="step.aiObservation.durationMs" :min="1000" :max="60000" :step="1000" :disabled="disabled || busy" controls-position="right" @change="updateObservation({ durationMs: $event })" />
175
+ </el-form-item>
176
+ <el-form-item label="采样间隔 ms">
177
+ <el-input-number :model-value="step.aiObservation.intervalMs" :min="500" :max="10000" :step="500" :disabled="disabled || busy" controls-position="right" @change="updateObservation({ intervalMs: $event })" />
178
+ </el-form-item>
179
+ </div>
180
+ </template>
181
+ </el-collapse-item>
182
+
183
+ <el-collapse-item name="branch">
184
+ <template #title>
185
+ <span class="ai-recognition-settings__group-title"><strong>分支设置</strong><small>{{ branchSummary }}</small></span>
186
+ </template>
187
+ <el-form-item class="ai-recognition-settings__toggles">
188
+ <div class="ai-recognition-settings__toggle-row">
189
+ <el-checkbox :model-value="branchChoice" :disabled="disabled || busy" @update:model-value="toggleBranch($event === true)">启用分支</el-checkbox>
190
+ <template v-if="branch">
191
+ <el-checkbox :model-value="fallbackEnabled" :disabled="disabled || busy" @update:model-value="toggleFallback($event === true)">启用兜底</el-checkbox>
192
+ <el-tooltip placement="top" :show-after="200">
193
+ <template #content><div class="recognition-help-content">仅在模型返回空内容、无效格式、无法判断或没有返回 true/false 时生效。正常返回布尔结果时仍按识别结果进入分支;请求失败和超时不使用此兜底。</div></template>
194
+ <el-button class="recognition-help" text :icon="QuestionFilled" aria-label="AI 识别兜底说明" @click.prevent />
195
+ </el-tooltip>
121
196
  </template>
122
- <el-button class="recognition-help" text :icon="QuestionFilled" aria-label="观察模式说明" @click.prevent />
123
- </el-tooltip>
124
- </span>
125
- </template>
126
- <el-radio-group :model-value="step.aiObservation.mode ?? 'batch'" :disabled="disabled || busy" @update:model-value="$event === 'untilMatch' ? save(branch, { ...step.aiObservation!, mode: 'untilMatch' }) : updateObservation({ mode: 'batch' })">
127
- <el-radio-button value="batch">观察结束后统一分析</el-radio-button>
128
- <el-radio-button value="untilMatch">检测命中后提前结束</el-radio-button>
129
- </el-radio-group>
130
- </el-form-item>
131
- <el-form-item :label="untilMatch ? '最长观察时间 ms' : '观察时长 ms'">
132
- <el-input-number :model-value="step.aiObservation.durationMs" :min="1000" :max="60000" :step="1000" :disabled="disabled || busy" controls-position="right" @change="updateObservation({ durationMs: $event })" />
133
- </el-form-item>
134
- <el-form-item label="采样间隔 ms">
135
- <el-input-number :model-value="step.aiObservation.intervalMs" :min="500" :max="10000" :step="500" :disabled="disabled || busy" controls-position="right" @change="updateObservation({ intervalMs: $event })" />
136
- </el-form-item>
137
- </template>
138
- <el-form-item :label="untilMatch ? '命中条件' : '识别内容'">
139
- <template #label>
140
- <span class="recognition-label">{{ untilMatch ? '命中条件' : '识别内容' }}
141
- <el-tooltip v-if="untilMatch" placement="top" :show-after="200">
142
- <template #content><div class="recognition-help-content">填写能用“是 / 否”判断的具体条件,例如“当前画面是否出现广告弹窗?”。模型判断为“是”即命中并提前结束观察;修改条件后需验证并保存。“广告内容是什么”等开放式问题请使用统一分析模式。</div></template>
143
- <el-button class="recognition-help" text :icon="QuestionFilled" aria-label="命中条件说明" @click.prevent />
144
- </el-tooltip>
145
- </span>
146
- </template>
147
- <AiRecognitionPromptInput v-model="prompt" :presets="promptPresets" :placeholder="untilMatch ? '例如:当前画面是否出现广告弹窗?' : ''" :disabled="disabled || busy || optimizingPrompt" @change="error = ''; !branch && !untilMatch && save(false)" />
148
- <div class="recognition-prompt-actions">
149
- <el-button :loading="optimizingPrompt" :disabled="disabled || busy || !prompt.trim()" @click="optimizePrompt">优化提示词</el-button>
150
- <el-button v-if="(branch || untilMatch) && prompt !== step.value" :disabled="disabled || busy || optimizingPrompt" @click="save(branch)">验证并保存问题</el-button>
151
- </div>
152
- </el-form-item>
153
- <el-form-item>
154
- <el-checkbox :model-value="branchChoice" :disabled="disabled || busy" @update:model-value="toggleBranch($event === true)">启用分支</el-checkbox>
155
- <span v-if="busy" class="validation-status" role="status">
156
- <el-icon class="is-loading" aria-hidden="true"><Loading /></el-icon>
157
- 正在验证…
158
- </span>
159
- </el-form-item>
160
- <el-form-item v-if="branch">
161
- <el-checkbox :model-value="fallbackEnabled" :disabled="disabled || busy" @update:model-value="toggleFallback($event === true)">启用兜底</el-checkbox>
162
- <el-tooltip placement="top" :show-after="200">
163
- <template #content><div class="recognition-help-content">仅在模型返回空内容、无效格式、无法判断或没有返回 true/false 时生效。正常返回布尔结果时仍按识别结果进入分支;请求失败和超时不使用此兜底。</div></template>
164
- <el-button class="recognition-help" text :icon="QuestionFilled" aria-label="AI 识别兜底说明" @click.prevent />
165
- </el-tooltip>
166
- </el-form-item>
167
- <el-form-item v-if="branch && fallbackEnabled" label="兜底分支">
168
- <el-select
169
- :model-value="step.aiInvalidResultBranch || ''"
170
- :disabled="disabled || busy"
171
- placeholder="请选择左右分支"
172
- @update:model-value="emit('update', { aiInvalidResultBranch: $event })"
173
- >
174
- <el-option :label="`进入左侧分支(${flowBranchLabel(step, 'yes')})`" value="yes" />
175
- <el-option :label="`进入右侧分支(${flowBranchLabel(step, 'no')})`" value="no" />
176
- </el-select>
177
- </el-form-item>
178
- <el-alert v-if="error" :title="error" type="warning" :closable="false" show-icon />
197
+ </div>
198
+ <span v-if="busy" class="validation-status" role="status">
199
+ <el-icon class="is-loading" aria-hidden="true"><Loading /></el-icon>
200
+ 正在验证…
201
+ </span>
202
+ </el-form-item>
203
+ <el-form-item v-if="branch && fallbackEnabled" label="兜底分支">
204
+ <el-select :model-value="step.aiInvalidResultBranch || ''" :disabled="disabled || busy" placeholder="请选择左右分支" @update:model-value="emit('update', { aiInvalidResultBranch: $event })">
205
+ <el-option :label="`进入左侧分支(${flowBranchLabel(step, 'yes')})`" value="yes" />
206
+ <el-option :label="`进入右侧分支(${flowBranchLabel(step, 'no')})`" value="no" />
207
+ </el-select>
208
+ </el-form-item>
209
+ </el-collapse-item>
210
+
211
+ <el-collapse-item title="节点信息与超时设置" name="other">
212
+ <slot name="other" />
213
+ </el-collapse-item>
214
+ </el-collapse>
215
+ <el-alert v-if="error" :title="error" type="warning" :closable="false" show-icon />
216
+ </div>
179
217
  </template>
180
218
 
181
219
  <style scoped>
@@ -184,7 +222,26 @@ async function save(enabled: boolean, observation?: AiObservationConfig) {
184
222
  .recognition-help-content { max-width: min(360px, calc(100vw - 40px)); line-height: 1.6; overflow-wrap: anywhere; }
185
223
  .recognition-help-content p { margin: 0 0 8px; }
186
224
  .recognition-help-content p:last-child { margin-bottom: 0; }
187
- .recognition-prompt-actions { display: flex; justify-content: flex-end; width: 100%; margin-top: 10px; }
225
+ .recognition-prompt-actions { display: flex; justify-content: flex-end; gap: 6px; width: 100%; margin-top: 6px; }
226
+ .recognition-prompt-actions .el-button + .el-button { margin-left: 0; }
227
+ .ai-recognition-settings { min-width: 0; }
228
+ .ai-recognition-settings :deep(.el-form-item) { margin-bottom: 10px; }
229
+ .ai-recognition-settings__grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }
230
+ .ai-recognition-settings__grid :deep(.el-form-item) { min-width: 0; }
231
+ .ai-recognition-settings__grid :deep(.el-input-number) { width: 100%; }
232
+ .ai-recognition-settings__toggle-row { display: flex; align-items: center; flex-wrap: wrap; gap: 0 12px; }
233
+ .ai-recognition-settings__toggle-row :deep(.el-checkbox) { margin-right: 0; }
234
+ .ai-recognition-settings__toggles :deep(.el-form-item__content) { align-items: center; }
235
+ .ai-recognition-settings__groups { overflow: hidden; border: 1px solid var(--el-border-color-lighter); border-radius: 10px; background: #fff; }
236
+ .ai-recognition-settings__groups :deep(.el-collapse-item__header) { height: 42px; padding: 0 10px; border-bottom-color: var(--el-border-color-lighter); font-size: 12px; }
237
+ .ai-recognition-settings__groups :deep(.el-collapse-item__wrap) { border-bottom-color: var(--el-border-color-lighter); }
238
+ .ai-recognition-settings__groups :deep(.el-collapse-item:last-child .el-collapse-item__header),
239
+ .ai-recognition-settings__groups :deep(.el-collapse-item:last-child .el-collapse-item__wrap) { border-bottom: 0; }
240
+ .ai-recognition-settings__groups :deep(.el-collapse-item__content) { padding: 8px 10px 2px; }
241
+ .ai-recognition-settings__group-title { display: flex; align-items: center; justify-content: space-between; min-width: 0; width: 100%; padding-right: 8px; gap: 8px; }
242
+ .ai-recognition-settings__group-title strong { color: var(--ui-text); font-size: 12px; }
243
+ .ai-recognition-settings__group-title small { min-width: 0; overflow: hidden; color: var(--ui-text-muted); font-size: 11px; font-weight: 400; text-overflow: ellipsis; white-space: nowrap; }
244
+ .el-alert :deep(.el-alert__title) { white-space: pre-line; line-height: 1.6; }
188
245
  .validation-status {
189
246
  display: inline-flex;
190
247
  align-items: center;
@@ -1,42 +1,99 @@
1
1
  <script setup lang="ts">
2
2
  import { computed, nextTick, ref, watch } from 'vue';
3
3
  import type { AppiumNode } from '../types';
4
- import { Search } from '@element-plus/icons-vue';
4
+ import { ArrowDown, ArrowUp, Search } from '@element-plus/icons-vue';
5
+ import { flattenNodes } from '../tree';
5
6
 
6
7
  const props = defineProps<{
7
8
  tree: AppiumNode | null;
8
9
  selectedId: string;
9
10
  }>();
10
11
 
11
- defineEmits<{
12
+ const emit = defineEmits<{
12
13
  select: [node: AppiumNode];
13
14
  }>();
14
15
 
15
16
  const containerRef = ref<HTMLElement | null>(null);
16
17
  const query = ref('');
18
+ const currentMatchIndex = ref(-1);
17
19
  // Keep the tree data identity stable while typing so filtering is not reset.
18
20
  const treeData = computed(() => props.tree ? [props.tree] : []);
19
21
  const treeRef = ref<{ setCurrentKey: (key: string) => void; filter: (value: string) => void } | null>(null);
20
22
  const filterNode = (value: string, node: AppiumNode) => !value || [node.label, node.resourceId, node.text, node.contentDesc, node.className].some((text) => text?.toLowerCase().includes(value.toLowerCase()));
21
- watch(query, (value) => treeRef.value?.filter(value));
22
- watch(() => props.tree, async () => { await nextTick(); treeRef.value?.filter(query.value); });
23
+ const matches = computed(() => {
24
+ const value = query.value.trim();
25
+ return value ? flattenNodes(props.tree).filter(node => filterNode(value, node)) : [];
26
+ });
27
+ const matchPosition = computed(() => matches.value.length && currentMatchIndex.value >= 0
28
+ ? `${currentMatchIndex.value + 1}/${matches.value.length}`
29
+ : `0/${matches.value.length}`);
30
+
31
+ const scrollToCurrentNode = async () => {
32
+ await nextTick();
33
+ containerRef.value
34
+ ?.querySelector('.el-tree-node.is-current')
35
+ ?.scrollIntoView({ block: 'center', inline: 'nearest' });
36
+ };
37
+
38
+ const focusMatch = (index: number) => {
39
+ if (!matches.value.length) return;
40
+ currentMatchIndex.value = (index + matches.value.length) % matches.value.length;
41
+ const node = matches.value[currentMatchIndex.value];
42
+ treeRef.value?.setCurrentKey(node.id);
43
+ emit('select', node);
44
+ void scrollToCurrentNode();
45
+ };
46
+
47
+ const refreshSearch = async () => {
48
+ treeRef.value?.filter(query.value);
49
+ await nextTick();
50
+ if (!query.value.trim() || !matches.value.length) {
51
+ currentMatchIndex.value = -1;
52
+ return;
53
+ }
54
+ const selectedMatchIndex = matches.value.findIndex(node => node.id === props.selectedId);
55
+ focusMatch(selectedMatchIndex >= 0 ? selectedMatchIndex : 0);
56
+ };
57
+
58
+ watch(query, refreshSearch);
59
+ watch(() => props.tree, refreshSearch);
23
60
 
24
61
  watch(
25
62
  () => props.selectedId,
26
63
  async () => {
27
- query.value = '';
64
+ if (query.value.trim()) {
65
+ const selectedMatchIndex = matches.value.findIndex(node => node.id === props.selectedId);
66
+ if (selectedMatchIndex >= 0) currentMatchIndex.value = selectedMatchIndex;
67
+ else query.value = '';
68
+ }
28
69
  treeRef.value?.setCurrentKey(props.selectedId);
29
- await nextTick();
30
- containerRef.value
31
- ?.querySelector('.el-tree-node.is-current')
32
- ?.scrollIntoView({ block: 'center', inline: 'nearest' });
70
+ await scrollToCurrentNode();
33
71
  },
34
72
  );
35
73
  </script>
36
74
 
37
75
  <template>
38
76
  <div class="appium-tree-container">
39
- <el-input v-model="query" size="small" :prefix-icon="Search" clearable placeholder="搜索文字、ID、组件类型" aria-label="搜索组件" />
77
+ <div class="appium-tree-search">
78
+ <el-input
79
+ v-model="query"
80
+ size="small"
81
+ :prefix-icon="Search"
82
+ clearable
83
+ placeholder="搜索文字、ID、组件类型"
84
+ aria-label="搜索组件"
85
+ @keydown.enter.prevent="focusMatch(currentMatchIndex + ($event.shiftKey ? -1 : 1))"
86
+ @keydown.up.prevent="focusMatch(currentMatchIndex - 1)"
87
+ @keydown.down.prevent="focusMatch(currentMatchIndex + 1)"
88
+ />
89
+ <span class="appium-tree-search__count" aria-live="polite">{{ matchPosition }}</span>
90
+ <el-tooltip content="上一个匹配项(Shift + Enter)" placement="top" :show-after="200">
91
+ <el-button :icon="ArrowUp" size="small" aria-label="上一个匹配项" :disabled="!matches.length" @click="focusMatch(currentMatchIndex - 1)" />
92
+ </el-tooltip>
93
+ <el-tooltip content="下一个匹配项(Enter)" placement="top" :show-after="200">
94
+ <el-button :icon="ArrowDown" size="small" aria-label="下一个匹配项" :disabled="!matches.length" @click="focusMatch(currentMatchIndex + 1)" />
95
+ </el-tooltip>
96
+ </div>
40
97
  <div ref="containerRef" class="appium-tree">
41
98
  <el-empty v-if="!tree" description="暂无组件树" />
42
99
  <el-tree
@@ -70,6 +127,11 @@ watch(
70
127
 
71
128
  <style scoped>
72
129
  .appium-tree-container { display: flex; flex-direction: column; gap: 8px; min-width: 0; min-height: 0; }
130
+ .appium-tree-search { display: flex; align-items: center; gap: 2px; }
131
+ .appium-tree-search .el-input { flex: 1; min-width: 0; }
132
+ .appium-tree-search__count { min-width: 28px; padding: 0 2px; text-align: center; font-size: 11px; color: var(--ui-text-secondary); font-variant-numeric: tabular-nums; }
133
+ .appium-tree-search .el-button { flex: none; width: 24px; height: 24px; min-height: 24px; padding: 0; border-radius: 5px; }
134
+ .appium-tree-search .el-button + .el-button { margin-left: 0; }
73
135
  .appium-tree { flex: 1; height: auto; overflow: auto; }
74
136
  .appium-tree :deep(.el-tree) { width: max-content; min-width: 100%; }
75
137
  .appium-tree-node { flex: 1 0 auto; }