android-midscene-automation 1.1.9 → 1.1.11

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 (37) hide show
  1. package/CHANGELOG.md +60 -53
  2. package/README.md +60 -53
  3. package/package.json +1 -1
  4. package/server/appium-recorder/appium-runner.ts +22 -0
  5. package/server/appium-recorder/random-value-replay.test.ts +101 -0
  6. package/server/appium-recorder/random-value.test.ts +114 -0
  7. package/server/appium-recorder/random-value.ts +34 -0
  8. package/server/appium-recorder/repository.ts +11 -1
  9. package/server/appium-recorder/script-export.ts +6 -1
  10. package/server/appium-recorder/stopwatch.test.ts +74 -0
  11. package/server/appium-recorder/stopwatch.ts +24 -0
  12. package/src/App.vue +18 -5
  13. package/src/appium-recorder/AppiumPage.vue +137 -6
  14. package/src/appium-recorder/action-descriptions.ts +2 -0
  15. package/src/appium-recorder/components/FlowStepEditor.vue +5 -1
  16. package/src/appium-recorder/components/NestedConditionBranches.vue +3 -0
  17. package/src/appium-recorder/components/PresetVariables.vue +6 -5
  18. package/src/appium-recorder/components/RandomValueSettings.vue +139 -0
  19. package/src/appium-recorder/components/RecordedSteps.vue +2 -0
  20. package/src/appium-recorder/components/StopwatchSettings.vue +40 -0
  21. package/src/appium-recorder/flow-copy.ts +3 -2
  22. package/src/appium-recorder/flow-graph.ts +2 -0
  23. package/src/appium-recorder/flow-labels.ts +7 -1
  24. package/src/appium-recorder/random-value.ts +60 -0
  25. package/src/appium-recorder/stopwatch.ts +27 -0
  26. package/src/appium-recorder/types.ts +6 -0
  27. package/src/appium-recorder/variable-presets.ts +24 -0
  28. package/src/components/AppSidebar.vue +37 -7
  29. package/src/components/config/AiDeduplicationSettings.vue +21 -10
  30. package/src/components/config/AppiumConfigPanel.vue +10 -5
  31. package/src/components/config/BaseConfigPanel.vue +54 -33
  32. package/src/components/config/MidsceneConfigPanel.vue +9 -0
  33. package/src/config/use-model-config.ts +1 -1
  34. package/src/pages/ConfigPage.vue +0 -19
  35. package/src/style.css +6 -1
  36. package/src/types.ts +1 -1
  37. package//346/265/201/347/250/213/350/212/202/347/202/271/346/223/215/344/275/234/350/257/264/346/230/216.md +10 -0
@@ -0,0 +1,34 @@
1
+ import { randomInt, randomUUID } from 'node:crypto';
2
+ import { randomTextCandidates, validateRandomValue, type RandomValueConfig } from '../../src/appium-recorder/random-value';
3
+ import type { VariableScope } from './variables';
4
+
5
+ /** 每次回放独立创建;同一脚本节点被循环或连接脚本多次调用时共用抽取记录。 */
6
+ export class RandomValueGenerator {
7
+ private readonly pools = new Map<string, { text: string; remaining: string[] }>();
8
+
9
+ next(key: string, input: RandomValueConfig | undefined): string {
10
+ const config = validateRandomValue(input);
11
+ if (config.mode === 'uuid') return randomUUID();
12
+ if (config.mode === 'integer') return String(config.min! + randomInt(0, config.max! - config.min! + 1));
13
+ const candidates = randomTextCandidates(config.text);
14
+ if (!config.withoutReplacement) return candidates[randomInt(candidates.length)]!;
15
+ let pool = this.pools.get(key);
16
+ if (!pool || pool.text !== config.text) {
17
+ pool = { text: config.text!, remaining: [...new Set(candidates)] };
18
+ this.pools.set(key, pool);
19
+ }
20
+ if (!pool.remaining.length) throw new Error(`随机值节点 ${config.name} 的候选已耗尽;请增加候选或允许重复抽取`);
21
+ const index = randomInt(pool.remaining.length);
22
+ const value = pool.remaining[index]!;
23
+ pool.remaining[index] = pool.remaining[pool.remaining.length - 1]!;
24
+ pool.remaining.pop();
25
+ return value;
26
+ }
27
+
28
+ write(scope: VariableScope, key: string, config: RandomValueConfig | undefined) {
29
+ const value = this.next(key, config);
30
+ // 候选中出现 {{…}} 时按普通文字保存,后续多次引用也不会重新抽取或递归插值。
31
+ scope.set({ name: config!.name, value, sensitive: config!.sensitive }, true);
32
+ return `已获取随机值并写入脚本变量:${config!.name} = ${scope.redact(value)}`;
33
+ }
34
+ }
@@ -12,6 +12,8 @@ import { validateLoopSteps } from '../../src/appium-recorder/bounded-loop';
12
12
  import { validateVariables, validateExtraction, validateReturns, type TestVariable, type VariableExtraction, type ScriptReturn } from '../../src/appium-recorder/variables';
13
13
  import { getPresetVariables, savePresetVariables, deleteScriptVariables } from './variable-store';
14
14
  import { validateImageCheck, type ImageCheckConfig } from '../../src/appium-recorder/image-check';
15
+ import { validateRandomValue, type RandomValueConfig } from '../../src/appium-recorder/random-value';
16
+ import { validateStopwatch, remapStopwatchIds, type StopwatchConfig } from '../../src/appium-recorder/stopwatch';
15
17
 
16
18
  export type AppiumRecordedStepRecord = {
17
19
  mergeUndo?: import('../../src/appium-recorder/types').BranchMergeUndo;
@@ -53,6 +55,8 @@ export type AppiumRecordedStepRecord = {
53
55
  | 'runScript'
54
56
  | 'noop'
55
57
  | 'extractVariable'
58
+ | 'randomValue'
59
+ | 'stopwatch'
56
60
  | 'log'
57
61
  | 'visualChange';
58
62
  label: string;
@@ -97,6 +101,8 @@ export type AppiumRecordedStepRecord = {
97
101
  logPrefix?: string;
98
102
  imageCheck?: ImageCheckConfig;
99
103
  extractVariable?: VariableExtraction;
104
+ randomValue?: RandomValueConfig;
105
+ stopwatch?: StopwatchConfig;
100
106
  parameters?: TestVariable[];
101
107
  returns?: ScriptReturn[];
102
108
  keyCode?: number;
@@ -389,6 +395,8 @@ export function saveAppiumRecordedScript(input: {
389
395
  }
390
396
  if (step.type === 'imageCheck') validateImageCheck(step.imageCheck);
391
397
  if (step.type === 'extractVariable') validateExtraction(step.extractVariable);
398
+ if (step.type === 'randomValue') validateRandomValue(step.randomValue, { allowEmptySensitiveText: true });
399
+ if (step.type === 'stopwatch') validateStopwatch(step.stopwatch);
392
400
  if (step.type === 'runScript') { validateVariables(step.parameters); validateReturns(step.returns); }
393
401
  }
394
402
  validateLoopSteps(steps);
@@ -512,8 +520,10 @@ export function importAppiumRecordedScripts(inputs: Array<{
512
520
  });
513
521
  const importedIds = new Map(planned.filter(item => item.sourceId).map(item => [item.sourceId, item.id]));
514
522
 
523
+ const timerIds = new Map(planned.flatMap(input => input.steps.filter(step => step.stopwatch?.action === 'start' && step.stopwatch.timerId)
524
+ .map(step => [step.stopwatch!.timerId, crypto.randomUUID()])));
515
525
  return planned.map((input) => {
516
- const steps = input.steps.map(step => (
526
+ const steps = remapStopwatchIds(input.steps, timerIds).map(step => (
517
527
  step.type === 'runScript' && step.value && importedIds.has(step.value)
518
528
  ? { ...step, value: importedIds.get(step.value) }
519
529
  : step
@@ -45,7 +45,12 @@ export async function createAppiumScriptExport(
45
45
  appActivity: script.appActivity,
46
46
  deviceId: script.deviceId,
47
47
  variables: clearSecrets(script.variables),
48
- steps: script.steps.map(step => ({ ...step, mergeUndo: undefined, ...(step.parameters ? { parameters: clearSecrets(step.parameters) } : {}) })),
48
+ steps: script.steps.map(step => ({ ...step, mergeUndo: undefined,
49
+ ...(step.parameters ? { parameters: clearSecrets(step.parameters) } : {}),
50
+ ...(step.randomValue && (step.randomValue.sensitive || sensitiveVariableName(step.randomValue.name)
51
+ || script.variables?.find(item => item.name === step.randomValue?.name)?.sensitive)
52
+ ? { randomValue: { ...step.randomValue, text: '', sourceName: undefined, sensitive: true } } : {}),
53
+ })),
49
54
  },
50
55
  }), null, 2);
51
56
  };
@@ -0,0 +1,74 @@
1
+ import assert from 'node:assert/strict';
2
+ import { test } from 'node:test';
3
+ import { ReplayStopwatches } from './stopwatch';
4
+ import { defaultStopwatch, remapStopwatchIds, validateStopwatch, type StopwatchConfig } from '../../src/appium-recorder/stopwatch';
5
+ import { createFlowClipboard, pasteFlowClipboard } from '../../src/appium-recorder/flow-copy';
6
+ import type { AppiumRecordedStep } from '../../src/appium-recorder/types';
7
+ import { mkdtemp, rm } from 'node:fs/promises';
8
+ import { tmpdir } from 'node:os';
9
+ import { join } from 'node:path';
10
+
11
+ test('IDs isolate same-name timers; renaming never changes an association or loop count', () => {
12
+ const timers = new ReplayStopwatches();
13
+ const record = (action: StopwatchConfig['action'], now: number, timerId = 'id-a', name = '同名') => timers.record({ timerId, name, action }, action, now);
14
+ assert.deepEqual(record('start', 1000), { timerId: 'id-a', name: '同名', action: 'start', point: 'start', run: 1,
15
+ at: '1970-01-01T00:00:01.000Z', elapsedMs: 0, intervalMs: 0 });
16
+ record('start', 1200, 'id-b');
17
+ assert.deepEqual(record('mark', 1400, 'id-a', '改名'), { timerId: 'id-a', name: '同名', action: 'mark', point: 'mark', run: 1,
18
+ at: '1970-01-01T00:00:01.400Z', elapsedMs: 400, intervalMs: 400 });
19
+ assert.equal(record('end', 2000).intervalMs, 600);
20
+ assert.equal(record('end', 2200, 'id-b').elapsedMs, 1000);
21
+ assert.throws(() => record('mark', 2300), /尚未开始/);
22
+ assert.throws(() => record('mark', 2300, 'wrong-id', '同名'), /尚未开始/);
23
+ assert.equal(record('start', 2400, 'id-a', '重命名').run, 2);
24
+ assert.equal(record('start', 2500).restarted, true);
25
+ assert.equal(record('end', 2600).elapsedMs, 100);
26
+ assert.throws(() => new ReplayStopwatches().record({ timerId: 'id-a', name: '同名', action: 'end' }, 'end'), /尚未开始/);
27
+ const defaults = defaultStopwatch();
28
+ assert.notEqual(defaults.timerId, defaultStopwatch().timerId);
29
+ for (const config of [undefined, { ...defaults, name: '' }, { ...defaults, action: 'toString' },
30
+ { ...defaults, timerId: '' }, { name: 'old', action: 'start', point: 'old' }]) {
31
+ assert.throws(() => validateStopwatch(config as StopwatchConfig));
32
+ }
33
+ });
34
+
35
+ const steps: AppiumRecordedStep[] = [
36
+ { id: 'start', type: 'stopwatch', label: '开始', stopwatch: { timerId: 'original', name: '同名', action: 'start' } },
37
+ { id: 'mark', type: 'stopwatch', label: '打点', stopwatch: { timerId: 'original', name: '同名', action: 'mark' } },
38
+ { id: 'end', type: 'stopwatch', label: '结束', stopwatch: { timerId: 'original', name: '同名', action: 'end' } },
39
+ ];
40
+
41
+ test('copy/paste creates a new ID and remaps copied references; single marks retain explicit association', () => {
42
+ const pasted = pasteFlowClipboard(steps, createFlowClipboard(steps, [0, 1, 2]), { afterIndex: 2 });
43
+ assert.equal(pasted[0]!.stopwatch!.timerId, 'original');
44
+ const id = pasted[3]!.stopwatch!.timerId;
45
+ assert.notEqual(id, 'original');
46
+ assert.ok(pasted.slice(3).every(step => step.stopwatch!.timerId === id));
47
+ assert.equal(remapStopwatchIds([steps[1]!])[0]!.stopwatch!.timerId, 'original');
48
+ const duplicate = remapStopwatchIds(steps);
49
+ assert.notEqual(duplicate[0]!.stopwatch!.timerId, id);
50
+ assert.ok(duplicate.every(step => step.stopwatch!.timerId === duplicate[0]!.stopwatch!.timerId));
51
+ assert.equal(steps[0]!.stopwatch!.timerId, 'original');
52
+ });
53
+
54
+ test('batch import remaps timer IDs across scripts and keeps imported copies independent', async () => {
55
+ const root = await mkdtemp(join(tmpdir(), 'stopwatch-import-'));
56
+ const previous = process.env.ANDROID_MIDSCENE_DATA_ROOT;
57
+ process.env.ANDROID_MIDSCENE_DATA_ROOT = root;
58
+ try {
59
+ const { importAppiumRecordedScripts } = await import('./repository');
60
+ const inputs = [
61
+ { sourceId: 'parent', name: '父脚本', appPackage: 'example.app', steps: [steps[0]!, { id: 'call', type: 'runScript' as const, label: '子脚本', value: 'child' }] },
62
+ { sourceId: 'child', name: '子脚本', appPackage: 'example.app', steps: steps.slice(1) },
63
+ ];
64
+ const [parent, child] = importAppiumRecordedScripts(inputs);
65
+ const id = parent!.steps[0]!.stopwatch!.timerId;
66
+ assert.notEqual(id, 'original');
67
+ assert.ok(child!.steps.every(step => step.stopwatch!.timerId === id));
68
+ assert.equal(parent!.steps[1]!.value, child!.id);
69
+ assert.notEqual(importAppiumRecordedScripts(inputs)[0]!.steps[0]!.stopwatch!.timerId, id);
70
+ } finally {
71
+ if (previous === undefined) delete process.env.ANDROID_MIDSCENE_DATA_ROOT; else process.env.ANDROID_MIDSCENE_DATA_ROOT = previous;
72
+ await rm(root, { recursive: true, force: true });
73
+ }
74
+ });
@@ -0,0 +1,24 @@
1
+ import { STOPWATCH_ACTIONS, validateStopwatch, type StopwatchConfig } from '../../src/appium-recorder/stopwatch';
2
+
3
+ // System-generated IDs link timers within one replay, including linked scripts.
4
+ export class ReplayStopwatches {
5
+ private readonly active = new Map<string, { name: string; started: number; last: number; run: number }>();
6
+ private readonly counts = new Map<string, number>();
7
+ record(input: StopwatchConfig, point = STOPWATCH_ACTIONS[input.action], now = Date.now()) {
8
+ const config = validateStopwatch(input);
9
+ const timerId = config.timerId.trim();
10
+ const previous = this.active.get(timerId);
11
+ if (config.action === 'start') {
12
+ const run = (this.counts.get(timerId) || 0) + 1;
13
+ this.counts.set(timerId, run);
14
+ this.active.set(timerId, { name: config.name.trim(), started: now, last: now, run });
15
+ } else if (!previous) throw new Error(`计时器「${timerId}」尚未开始或已经结束`);
16
+ const timer = this.active.get(timerId)!;
17
+ const result = { timerId, name: timer.name, run: timer.run, action: config.action, point: point.trim() || STOPWATCH_ACTIONS[config.action], at: new Date(now).toISOString(),
18
+ elapsedMs: Math.max(0, now - timer.started), intervalMs: Math.max(0, now - timer.last),
19
+ ...(config.action === 'start' && previous ? { restarted: true } : {}),
20
+ };
21
+ if (config.action === 'end') this.active.delete(timerId); else timer.last = now;
22
+ return result;
23
+ }
24
+ }
package/src/App.vue CHANGED
@@ -42,6 +42,7 @@ const AutomationPage = defineAsyncComponent(() => import('./pages/AutomationPage
42
42
  const AppiumPage = defineAsyncComponent(() => import('./appium-recorder/AppiumPage.vue'));
43
43
  const ArtemisPage = defineAsyncComponent(() => import('./pages/ArtemisPage.vue'));
44
44
  const ConfigPage = defineAsyncComponent(() => import('./pages/ConfigPage.vue'));
45
+ const MidsceneConfigPanel = defineAsyncComponent(() => import('./components/config/MidsceneConfigPanel.vue'));
45
46
  const GeneratorPage = defineAsyncComponent(() => import('./pages/GeneratorPage.vue'));
46
47
  const HelpCenter = defineAsyncComponent(() => import('./components/help/HelpCenter.vue'));
47
48
  import type {
@@ -52,7 +53,7 @@ import type {
52
53
  } from './types';
53
54
 
54
55
  const ACTIVE_MENU_STORAGE_KEY = 'android-midscene-automation:active-menu';
55
- const menuKeys: MenuKey[] = ['appium', 'artemis', 'generator', 'automation', 'analysis', 'config', 'about'];
56
+ const menuKeys: MenuKey[] = ['appium', 'artemis', 'generator', 'automation', 'midscene-config', 'analysis', 'config', 'about'];
56
57
  const storedMenu = window.localStorage.getItem(ACTIVE_MENU_STORAGE_KEY) as MenuKey | null;
57
58
  const activeMenu = ref<MenuKey>(storedMenu && menuKeys.includes(storedMenu) ? storedMenu : 'generator');
58
59
  const activeGeneratorMode = ref<GeneratorMode>('ai');
@@ -125,7 +126,8 @@ const menuItems = [
125
126
  { key: 'appium', label: 'Appium', icon: Monitor },
126
127
  { key: 'artemis', label: 'Artemis', icon: Monitor },
127
128
  { key: 'generator', label: '测试脚本生成', icon: Operation },
128
- { key: 'automation', label: '自动化测试', icon: Monitor },
129
+ { key: 'automation', label: '自动化测试', icon: VideoPlay },
130
+ { key: 'midscene-config', label: 'Midscene参数配置', icon: Setting },
129
131
  { key: 'analysis', label: '分析页', icon: DataAnalysis },
130
132
  { key: 'config', label: '参数配置', icon: Setting },
131
133
  { key: 'about', label: '关于', icon: InfoFilled },
@@ -894,7 +896,7 @@ onUnmounted(() => {
894
896
  'page-body--artemis': activeMenu === 'artemis',
895
897
  }"
896
898
  >
897
- <el-alert v-if="activeMenu !== 'appium' && activeMenu !== 'artemis' && activeMenu !== 'config' && activeMenu !== 'about' && errorMessage" type="error" :closable="false" show-icon class="page-alert">
899
+ <el-alert v-if="activeMenu !== 'appium' && activeMenu !== 'artemis' && activeMenu !== 'config' && activeMenu !== 'midscene-config' && activeMenu !== 'about' && errorMessage" type="error" :closable="false" show-icon class="page-alert">
898
900
  <template #title>{{ errorMessage }}</template>
899
901
  </el-alert>
900
902
 
@@ -929,7 +931,19 @@ onUnmounted(() => {
929
931
  @clear-all="clearGeneratorPage"
930
932
  />
931
933
 
932
- <div v-if="activeMenu === 'config' && !configReady && !configResource.error.value" class="page-loading" role="status">正在加载参数配置…</div>
934
+ <div v-if="(activeMenu === 'config' || activeMenu === 'midscene-config') && !configReady && !configResource.error.value" class="page-loading" role="status">正在加载参数配置…</div>
935
+
936
+ <MidsceneConfigPanel
937
+ v-if="visitedMenus.has('midscene-config') && configReady"
938
+ v-show="activeMenu === 'midscene-config'"
939
+ role="region"
940
+ aria-label="Midscene参数配置"
941
+ :config-form="configForm"
942
+ :testing-model-key="testingModelKey"
943
+ :model-test-status="modelTestStatus"
944
+ @test-model="testModel"
945
+ @update-midscene-model-provider="updateMidsceneModelProvider"
946
+ />
933
947
 
934
948
  <ConfigPage
935
949
  v-if="visitedMenus.has('config') && configReady"
@@ -950,7 +964,6 @@ onUnmounted(() => {
950
964
  @edit-app-preset="editAppPreset"
951
965
  @delete-app-preset="removeAppPreset"
952
966
  @cancel-app-preset-edit="resetAppPresetForm"
953
- @update-midscene-model-provider="updateMidsceneModelProvider"
954
967
  />
955
968
 
956
969
  <AutomationPage
@@ -6,7 +6,7 @@ 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, FolderOpened, Plus, Refresh, Upload, VideoPlay, View, Clock } from '@element-plus/icons-vue';
9
+ import { ArrowDown, Check, CircleClose, CopyDocument, Delete, Document, Download, Edit, FolderOpened, Loading, 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';
@@ -28,6 +28,7 @@ import {
28
28
  getAppiumTree,
29
29
  importAppiumScripts,
30
30
  launchAppiumDeviceApp,
31
+ loadVariables,
31
32
  replayAppiumScript,
32
33
  saveAppiumScript,
33
34
  saveVariables,
@@ -39,9 +40,14 @@ import RecorderWorkspace from './components/RecorderWorkspace.vue';
39
40
  import FlowCanvas from './components/FlowCanvas.vue';
40
41
  import LongPressSettings from './components/LongPressSettings.vue';
41
42
  import StageLogSettings from './components/StageLogSettings.vue';
43
+ import StopwatchSettings from './components/StopwatchSettings.vue';
44
+ import { defaultStopwatch, validateStopwatch, stopwatchTargetsKey, remapStopwatchIds } from './stopwatch';
42
45
  import TextClickSettings from './components/TextClickSettings.vue';
43
46
  import { textClickSelector } from './text-click';
44
47
  import { DEFAULT_LOG_PREFIX, validateStageLog } from './stage-log';
48
+ import RandomValueSettings from './components/RandomValueSettings.vue';
49
+ import { defaultRandomValue, validateRandomValue } from './random-value';
50
+ import { variablePresetKey, variablePresetOptions, type VariablePresetContext } from './variable-presets';
45
51
  import RecordedSteps from './components/RecordedSteps.vue';
46
52
  import NewScriptDialog from './components/NewScriptDialog.vue';
47
53
  import VisualChangeDialog from './components/VisualChangeDialog.vue';
@@ -220,7 +226,63 @@ const form = reactive({
220
226
  appPackage: '',
221
227
  appActivity: '',
222
228
  });
229
+ const stopwatchTargets = computed(() => [
230
+ ...scripts.value.filter(script => script.id !== selectedScriptId.value),
231
+ { name: form.name || '当前脚本', steps: steps.value },
232
+ ].flatMap(script => script.steps.flatMap((step, index) => step.type === 'stopwatch' && step.stopwatch?.action === 'start' && step.stopwatch.timerId
233
+ ? [{ timerId: step.stopwatch.timerId, name: step.stopwatch.name,
234
+ label: `${step.stopwatch.name} · ${script.name} · 节点 ${index + 1} · ${step.stopwatch.timerId}` }] : [])));
235
+ provide(stopwatchTargetsKey, stopwatchTargets);
223
236
  const scriptVariables = shallowRef<TestVariable[]>([]);
237
+ const globalVariables = shallowRef<TestVariable[]>([]);
238
+ const variablePresetsLoading = shallowRef(false);
239
+ const variablePresetsError = shallowRef('');
240
+ const availableVariablePresets = computed(() => variablePresetOptions(globalVariables.value, scriptVariables.value));
241
+ const pendingRandomValue = shallowRef<{ step: AppiumRecordedStep; index?: number; branchTarget?: BranchTarget } | null>(null);
242
+ let variablePresetsRequest: Promise<void> | undefined;
243
+
244
+ function refreshVariablePresets(): Promise<void> {
245
+ if (variablePresetsRequest) return variablePresetsRequest;
246
+ variablePresetsLoading.value = true;
247
+ variablePresetsError.value = '';
248
+ variablePresetsRequest = loadVariables('/api/appium-recorder/variables').then(result => {
249
+ globalVariables.value = result.variables;
250
+ }).catch(error => {
251
+ variablePresetsError.value = error instanceof Error ? error.message : '预设变量加载失败';
252
+ }).finally(() => {
253
+ variablePresetsLoading.value = false;
254
+ variablePresetsRequest = undefined;
255
+ });
256
+ return variablePresetsRequest;
257
+ }
258
+
259
+ const variablePresets: VariablePresetContext = {
260
+ options: availableVariablePresets, loading: variablePresetsLoading, error: variablePresetsError,
261
+ refresh: refreshVariablePresets, open: () => setActiveWorkbenchTab('variables'),
262
+ };
263
+ provide(variablePresetKey, variablePresets);
264
+
265
+ function validateRandomValueTarget(step: AppiumRecordedStep) {
266
+ if (!availableVariablePresets.value.some(variable => variable.name === step.randomValue?.name)) {
267
+ throw new Error(`节点「${step.label}」请选择已有预设变量;没有对应 key 时请先到“预设变量”添加`);
268
+ }
269
+ }
270
+
271
+ async function validateRandomValueTargets() {
272
+ const randomSteps = steps.value.filter(step => step.type === 'randomValue');
273
+ if (!randomSteps.length) return;
274
+ await refreshVariablePresets();
275
+ randomSteps.forEach(validateRandomValueTarget);
276
+ steps.value = steps.value.map(step => step.randomValue && availableVariablePresets.value.some(variable => variable.name === step.randomValue!.name && variable.sensitive)
277
+ ? { ...step, randomValue: { ...step.randomValue, sensitive: true } } : step);
278
+ }
279
+
280
+ function resumeRandomValue() {
281
+ const pending = pendingRandomValue.value;
282
+ if (!pending) return;
283
+ setActiveWorkbenchTab('recording');
284
+ void addAction('randomValue', pending.index, pending.branchTarget);
285
+ }
224
286
 
225
287
  const savedDraftSnapshot = shallowRef('');
226
288
  const currentDraftSnapshot = computed(() => JSON.stringify({
@@ -1578,6 +1640,52 @@ async function addAction(
1578
1640
  if (result) return insertStep({ ...step }, index, branchTarget);
1579
1641
  return;
1580
1642
  }
1643
+ if (action === 'stopwatch') {
1644
+ const step = reactive<AppiumRecordedStep>({ id: createStepId(), type: 'stopwatch', label: '计时打点', stopwatch: defaultStopwatch(), flow: { nodeKind: 'action' } });
1645
+ const result = await ElMessageBox({
1646
+ title: '添加计时打点',
1647
+ message: h(ElForm, { labelPosition: 'top', style: { width: 'min(380px, calc(100vw - 64px))' } }, () => h(StopwatchSettings, { step, targets: stopwatchTargets.value, onUpdate: patch => Object.assign(step, patch) })),
1648
+ showCancelButton: true, confirmButtonText: '添加', cancelButtonText: '取消',
1649
+ beforeClose: (action, _instance, done) => {
1650
+ if (action === 'confirm') {
1651
+ try { validateStopwatch(step.stopwatch); } catch (error) { ElMessage.warning((error as Error).message); return; }
1652
+ }
1653
+ done();
1654
+ },
1655
+ }).catch(() => null);
1656
+ if (result) return insertStep({ ...step, stopwatch: { ...step.stopwatch! } }, index, branchTarget);
1657
+ return;
1658
+ }
1659
+ if (action === 'randomValue') {
1660
+ const step = reactive<AppiumRecordedStep>(pendingRandomValue.value?.step || {
1661
+ id: createStepId(), type: 'randomValue', label: '获取随机值', randomValue: { ...defaultRandomValue(), name: '' }, flow: { nodeKind: 'action' },
1662
+ });
1663
+ pendingRandomValue.value = null;
1664
+ const dialogPresets: VariablePresetContext = { ...variablePresets, open: () => {
1665
+ pendingRandomValue.value = { step: JSON.parse(JSON.stringify(step)), index, branchTarget };
1666
+ ElMessageBox.close();
1667
+ variablePresets.open();
1668
+ } };
1669
+ const result = await ElMessageBox({
1670
+ title: '添加获取随机值',
1671
+ message: h(ElForm, { labelPosition: 'top', style: { width: 'min(380px, calc(100vw - 64px))', maxHeight: '65vh', overflowY: 'auto', paddingRight: '4px' } }, () => h(RandomValueSettings, {
1672
+ step, presets: dialogPresets, onUpdate: patch => Object.assign(step, patch),
1673
+ })),
1674
+ showCancelButton: true, confirmButtonText: '添加', cancelButtonText: '取消',
1675
+ beforeClose: (action, _instance, done) => {
1676
+ if (action === 'confirm') {
1677
+ try {
1678
+ validateRandomValueTarget(step);
1679
+ validateRandomValue(step.randomValue);
1680
+ if (availableVariablePresets.value.some(variable => variable.name === step.randomValue!.name && variable.sensitive)) step.randomValue!.sensitive = true;
1681
+ } catch (error) { ElMessage.warning(error instanceof Error ? error.message : '随机值配置无效'); return; }
1682
+ }
1683
+ done();
1684
+ },
1685
+ }).catch(() => null);
1686
+ if (result) return insertStep(JSON.parse(JSON.stringify(step)), index, branchTarget);
1687
+ return;
1688
+ }
1581
1689
  if (action === 'launchApp') {
1582
1690
  return insertStep({
1583
1691
  id: `step_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`,
@@ -1863,6 +1971,7 @@ function setActiveWorkbenchTab(tab: string | number) {
1863
1971
  }
1864
1972
 
1865
1973
  function loadScript(script: AppiumRecordedScript) {
1974
+ pendingRandomValue.value = null;
1866
1975
  setActiveWorkbenchTab('recording');
1867
1976
  flowClipboard.value = null;
1868
1977
  selectedScriptId.value = script.id;
@@ -1887,6 +1996,7 @@ function loadSelectedScript() {
1887
1996
  }
1888
1997
 
1889
1998
  function resetCurrentScript() {
1999
+ pendingRandomValue.value = null;
1890
2000
  void saveVariables('/api/appium-recorder/variables?draft=1', []).catch(() => ElMessage.error('变量草稿清理失败'));
1891
2001
  scriptVariables.value = [];
1892
2002
  flowClipboard.value = null;
@@ -1959,7 +2069,7 @@ async function duplicateScript(script: AppiumRecordedScript) {
1959
2069
  appPackage: script.appPackage,
1960
2070
  appActivity: script.appActivity,
1961
2071
  deviceId: script.deviceId,
1962
- steps: cloneScriptSteps(script.steps),
2072
+ steps: remapStopwatchIds(cloneScriptSteps(script.steps)),
1963
2073
  });
1964
2074
  await loadScripts();
1965
2075
  ElMessage.success(`已复制为「${payload.script.name}」`);
@@ -2135,6 +2245,7 @@ async function saveScript() {
2135
2245
  saving.value = true;
2136
2246
  try {
2137
2247
  validateVariables(scriptVariables.value);
2248
+ await validateRandomValueTargets();
2138
2249
  const payload = await saveAppiumScript({
2139
2250
  id: selectedScriptId.value || undefined,
2140
2251
  name: form.name,
@@ -2239,9 +2350,7 @@ async function stopReplay() {
2239
2350
  stoppingReplay.value = true;
2240
2351
  try {
2241
2352
  const result = await stopAppiumReplay(activeReplayDeviceId.value);
2242
- if (result.stopped) {
2243
- ElMessage.info('正在终止回放并生成报告、日志和截图回放');
2244
- } else {
2353
+ if (!result.stopped) {
2245
2354
  stoppingReplay.value = false;
2246
2355
  ElMessage.warning('当前没有可终止的回放任务');
2247
2356
  }
@@ -2505,7 +2614,11 @@ watch(
2505
2614
  </div>
2506
2615
  </el-tab-pane>
2507
2616
  <el-tab-pane label="预设变量" name="variables" lazy>
2508
- <PresetVariables :key="`${selectedScriptId}:${newScriptRevision}`" v-model:variables="scriptVariables" :script-id="selectedScriptId" :script-name="form.name" :disabled="recordingBusy || saving" @saved="onVariablesSaved" />
2617
+ <div v-if="pendingRandomValue" class="random-value-return">
2618
+ <span>随机值节点配置已保留</span>
2619
+ <el-button type="primary" plain :disabled="recordingLocked" @click="resumeRandomValue">返回节点配置</el-button>
2620
+ </div>
2621
+ <PresetVariables :key="`${selectedScriptId}:${newScriptRevision}`" v-model:variables="scriptVariables" v-model:globals="globalVariables" :script-id="selectedScriptId" :script-name="form.name" :disabled="recordingBusy || saving" @saved="onVariablesSaved" />
2509
2622
  </el-tab-pane>
2510
2623
  </el-tabs>
2511
2624
  </el-card>
@@ -2674,6 +2787,22 @@ watch(
2674
2787
  </template>
2675
2788
  </el-dialog>
2676
2789
 
2790
+ <el-dialog
2791
+ :model-value="stoppingReplay"
2792
+ title="报告正在生成中"
2793
+ width="420px"
2794
+ align-center
2795
+ append-to-body
2796
+ :show-close="false"
2797
+ :close-on-click-modal="false"
2798
+ :close-on-press-escape="false"
2799
+ >
2800
+ <div class="appium-report-progress" role="status" aria-live="polite">
2801
+ <el-icon class="is-loading" aria-hidden="true"><Loading /></el-icon>
2802
+ <span>正在终止回放并生成报告、日志和截图回放,请稍候。</span>
2803
+ </div>
2804
+ </el-dialog>
2805
+
2677
2806
  <el-dialog
2678
2807
  v-model="replayOutputDialogVisible"
2679
2808
  title="回放输出"
@@ -2710,6 +2839,8 @@ watch(
2710
2839
  </template>
2711
2840
 
2712
2841
  <style scoped>
2842
+ .appium-report-progress { display: flex; align-items: center; gap: 12px; line-height: 1.6; }
2843
+ .random-value-return { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 12px 16px; color: var(--el-text-color-secondary); font-size: 13px; }
2713
2844
  .appium-script-icon { display: inline-flex; }
2714
2845
  .appium-script-icon .el-button { width: 30px; height: 30px; min-height: 30px; padding: 0; margin: 0; }
2715
2846
  :deep(.appium-recorder-card--workbench > .el-card__body) { overflow: hidden; }
@@ -6,6 +6,8 @@ export const actionDescriptions: Record<InsertAction, string> = {
6
6
  tap: '记录点击当前选中的组件,回放时重新定位后点击。',
7
7
  input: '向当前选中的输入组件写入指定文字,支持 {{变量名}} 引用。',
8
8
  extractVariable: '读取组件文字或属性,保存到当前脚本变量供后续节点引用。',
9
+ randomValue: '从预设文本或导入的 TXT 中抽取一条,或生成随机整数、UUID,写入脚本变量。每次执行抽取一次,放在循环体内可每轮重新取值。',
10
+ stopwatch: '通用计时:通过系统生成的计时器 ID 关联开始、打点和结束节点,名称仅用于显示;日志输出绝对时间、距开始和距上次打点的毫秒数。与等待节点配合,可测量页面加载、接口返回或聊天响应等流程。',
9
11
  clearInput: '清空当前选中输入组件的内容。',
10
12
  coordinateTap: '点击设备屏幕上的指定 X、Y 坐标。节点中可修改坐标,页面位置变化后需重新确认。',
11
13
  longPress: '长按指定元素或屏幕坐标,可设置按住时长,默认按元素定位。',
@@ -10,9 +10,11 @@ import BranchTimeoutSettings from './BranchTimeoutSettings.vue';
10
10
  import { DEFAULT_NODE_TIMEOUT_MS } from '../node-timeout';
11
11
  import LongPressSettings from './LongPressSettings.vue';
12
12
  import StageLogSettings from './StageLogSettings.vue';
13
+ import StopwatchSettings from './StopwatchSettings.vue';
13
14
  import LoopSettings from './LoopSettings.vue';
14
15
  import BreakLoopSettings from './BreakLoopSettings.vue';
15
16
  import VariableExtractionSettings from './VariableExtractionSettings.vue';
17
+ import RandomValueSettings from './RandomValueSettings.vue';
16
18
  import ScriptParameterSettings from './ScriptParameterSettings.vue';
17
19
  import AiRecognitionSettings from './AiRecognitionSettings.vue';
18
20
 
@@ -59,7 +61,7 @@ const selectorSummary = computed(() => {
59
61
  return `${selector.strategy} · ${value}${props.step.contextSelector ? ' · 含父级' : ''}`;
60
62
  });
61
63
  const supportsTimeout = computed(() => ![
62
- 'delay', 'longPress', 'stopApp', 'log', 'openGallery', 'endFlow', 'loop', 'breakLoop', 'continueLoop', 'aiRecognition',
64
+ 'delay', 'longPress', 'stopApp', 'log', 'stopwatch', 'openGallery', 'endFlow', 'loop', 'breakLoop', 'continueLoop', 'aiRecognition', 'randomValue',
63
65
  ].includes(props.step.type));
64
66
 
65
67
  function defaultKind(): FlowKind {
@@ -187,7 +189,9 @@ function patchSelector(patch: Partial<AppiumSelector>) {
187
189
  </div>
188
190
  </template>
189
191
  <StageLogSettings v-if="step.type === 'log'" :step="step" :disabled="disabled" @update="patchStep" />
192
+ <StopwatchSettings v-if="step.type === 'stopwatch'" :step="step" :disabled="disabled" @update="patchStep" />
190
193
  <VariableExtractionSettings v-if="step.type === 'extractVariable'" :step="step" :disabled="disabled" @update="patchStep" />
194
+ <RandomValueSettings v-if="step.type === 'randomValue'" :step="step" :disabled="disabled" @update="patchStep" />
191
195
  <ScriptParameterSettings v-if="step.type === 'runScript'" :step="step" :disabled="disabled" @update="patchStep" />
192
196
  <LoopSettings v-if="step.type === 'loop'" :step="step" :disabled="disabled" @update="patchStep" />
193
197
  <BreakLoopSettings v-if="step.type === 'breakLoop' || step.type === 'continueLoop'" :step="step" :steps="steps" :disabled="disabled" :mode="step.type === 'continueLoop' ? 'continue' : 'break'" @update="patchStep" />
@@ -102,6 +102,7 @@ const actionGroups: FlowActionGroup[] = [
102
102
  {
103
103
  title: '流程控制',
104
104
  actions: [
105
+ { type: 'randomValue', label: '获取随机值' },
105
106
  { type: 'noop', label: '空节点' },
106
107
  { type: 'endFlow', label: '终止流程' },
107
108
  {
@@ -131,6 +132,7 @@ function typeLabel(step: AppiumRecordedStep) {
131
132
  coordinateTap: '坐标点击', swipe: '滑动', launchApp: '启动 APP', stopApp: '杀死 APP', clearAppData: '清理 APP 缓存', longPress: '长按',
132
133
  pinch: '双指缩放', runScript: '连接脚本', screenshot: '截图', visualChange: '检测画面变化',
133
134
  noop: '空节点',
135
+ randomValue: '获取随机值',
134
136
  endFlow: '终止流程',
135
137
  loop: '有界循环',
136
138
  breakLoop: '退出循环',
@@ -148,6 +150,7 @@ function typeLabel(step: AppiumRecordedStep) {
148
150
  }
149
151
 
150
152
  function stepMeta(step: AppiumRecordedStep) {
153
+ if (step.type === 'randomValue') return flowStepMeta(step);
151
154
  if (step.type === 'imageCheck') return flowStepMeta(step);
152
155
  if (step.type === 'delay') return `${step.timeoutMs || 1000}ms`;
153
156
  if (step.type === 'input' || step.type === 'inputIfExists') return `输入内容:${step.value || '空'}`;
@@ -4,9 +4,8 @@ import { QuestionFilled } from '@element-plus/icons-vue';
4
4
  import { loadVariables, saveVariables } from '../api';
5
5
  import VariableTable from './VariableTable.vue';
6
6
  import { validateVariables, type TestVariable } from '../variables';
7
- const props = defineProps<{ variables: TestVariable[]; disabled?: boolean; scriptName: string; scriptId: string }>();
8
- const emit = defineEmits<{ 'update:variables': [TestVariable[]]; saved: [string, TestVariable[]] }>();
9
- const globals = ref<TestVariable[]>([]);
7
+ const props = defineProps<{ variables: TestVariable[]; globals: TestVariable[]; disabled?: boolean; scriptName: string; scriptId: string }>();
8
+ const emit = defineEmits<{ 'update:variables': [TestVariable[]]; 'update:globals': [TestVariable[]]; saved: [string, TestVariable[]] }>();
10
9
  const busy = ref(false);
11
10
  const loaded = ref(false);
12
11
  const error = ref('');
@@ -19,7 +18,9 @@ const privateUrl = props.scriptId ? `/api/appium-recorder/variables?scriptId=${e
19
18
  async function load() {
20
19
  busy.value = true; error.value = '';
21
20
  try {
22
- globals.value = (await loadVariables('/api/appium-recorder/variables')).variables; loaded.value = true;
21
+ const globals = (await loadVariables('/api/appium-recorder/variables')).variables;
22
+ if (mounted) emit('update:globals', globals);
23
+ loaded.value = true;
23
24
  if (props.scriptId || !props.variables.length) {
24
25
  const variables = (await loadVariables(privateUrl)).variables;
25
26
  if (mounted) emit('update:variables', variables);
@@ -28,7 +29,7 @@ async function load() {
28
29
  finally { busy.value = false; }
29
30
  }
30
31
  function update(scope: 'global' | 'private', values: TestVariable[]) {
31
- if (scope === 'global') globals.value = values;
32
+ if (scope === 'global') emit('update:globals', values);
32
33
  else emit('update:variables', values);
33
34
  const revision = ++revisions[scope];
34
35
  let variables: TestVariable[];