android-midscene-automation 1.1.11 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -1775
- package/bin/android-midscene-automation.js +14 -97
- package/package.json +6 -79
- package/AI/350/257/206/345/210/253/346/223/215/344/275/234/350/257/264/346/230/216.md +0 -442
- package/CHANGELOG.md +0 -286
- package/FAQ.md +0 -105
- package/USAGE.md +0 -1085
- package/artemis-main/.dockerignore +0 -15
- package/artemis-main/.env.example +0 -34
- package/artemis-main/CONTRIBUTING.md +0 -35
- package/artemis-main/Dockerfile +0 -68
- package/artemis-main/LICENSE +0 -202
- package/artemis-main/Makefile +0 -115
- package/artemis-main/README.md +0 -322
- package/artemis-main/README_CN.md +0 -320
- package/artemis-main/apps/__init__.py +0 -15
- package/artemis-main/apps/admin_console/__init__.py +0 -19
- package/artemis-main/apps/admin_console/core/__init__.py +0 -13
- package/artemis-main/apps/admin_console/core/config.py +0 -43
- package/artemis-main/apps/admin_console/core/security.py +0 -178
- package/artemis-main/apps/admin_console/core/state.py +0 -243
- package/artemis-main/apps/admin_console/database/__init__.py +0 -13
- package/artemis-main/apps/admin_console/database/connection.py +0 -60
- package/artemis-main/apps/admin_console/database/repositories/__init__.py +0 -13
- package/artemis-main/apps/admin_console/database/repositories/session_repository.py +0 -564
- package/artemis-main/apps/admin_console/database/repositories/step_repository.py +0 -512
- package/artemis-main/apps/admin_console/database/repositories/trace_repository.py +0 -133
- package/artemis-main/apps/admin_console/index.html +0 -3787
- package/artemis-main/apps/admin_console/replay_manager.py +0 -2585
- package/artemis-main/apps/admin_console/routers/__init__.py +0 -13
- package/artemis-main/apps/admin_console/routers/media.py +0 -198
- package/artemis-main/apps/admin_console/routers/replay.py +0 -91
- package/artemis-main/apps/admin_console/routers/sessions.py +0 -239
- package/artemis-main/apps/admin_console/routers/steps.py +0 -109
- package/artemis-main/apps/admin_console/routers/stream.py +0 -56
- package/artemis-main/apps/admin_console/routers/system.py +0 -761
- package/artemis-main/apps/admin_console/routers/tasks.py +0 -517
- package/artemis-main/apps/admin_console/schemas/__init__.py +0 -13
- package/artemis-main/apps/admin_console/schemas/task_schema.py +0 -47
- package/artemis-main/apps/admin_console/server.py +0 -541
- package/artemis-main/apps/admin_console/services/__init__.py +0 -13
- package/artemis-main/apps/admin_console/services/device_stream_service.py +0 -137
- package/artemis-main/apps/admin_console/services/ipc_service.py +0 -262
- package/artemis-main/apps/admin_console/services/media_service.py +0 -623
- package/artemis-main/apps/admin_console/services/model_service.py +0 -148
- package/artemis-main/apps/admin_console/services/task_preset_catalog.py +0 -514
- package/artemis-main/apps/admin_console/services/task_queue_service.py +0 -1719
- package/artemis-main/apps/admin_console/services/worker_process_io.py +0 -144
- package/artemis-main/apps/showcase_ui/README.md +0 -31
- package/artemis-main/apps/showcase_ui/angular.json +0 -132
- package/artemis-main/apps/showcase_ui/package-lock.json +0 -9472
- package/artemis-main/apps/showcase_ui/package.json +0 -39
- package/artemis-main/apps/showcase_ui/proxy.conf.json +0 -23
- package/artemis-main/apps/showcase_ui/public/favicon.ico +0 -0
- package/artemis-main/apps/showcase_ui/public/logo.png +0 -0
- package/artemis-main/apps/showcase_ui/public/logo.svg +0 -56
- package/artemis-main/apps/showcase_ui/src/app/app.component.html +0 -24
- package/artemis-main/apps/showcase_ui/src/app/app.component.scss +0 -49
- package/artemis-main/apps/showcase_ui/src/app/app.component.spec.ts +0 -42
- package/artemis-main/apps/showcase_ui/src/app/app.component.ts +0 -32
- package/artemis-main/apps/showcase_ui/src/app/app.config.ts +0 -29
- package/artemis-main/apps/showcase_ui/src/app/app.routes.ts +0 -27
- package/artemis-main/apps/showcase_ui/src/app/components/agent-stream/agent-stream-startup.spec.ts +0 -108
- package/artemis-main/apps/showcase_ui/src/app/components/agent-stream/agent-stream.component.html +0 -1436
- package/artemis-main/apps/showcase_ui/src/app/components/agent-stream/agent-stream.component.scss +0 -3973
- package/artemis-main/apps/showcase_ui/src/app/components/agent-stream/agent-stream.component.ts +0 -2235
- package/artemis-main/apps/showcase_ui/src/app/components/chat-interface/chat-interface.component.html +0 -380
- package/artemis-main/apps/showcase_ui/src/app/components/chat-interface/chat-interface.component.scss +0 -1171
- package/artemis-main/apps/showcase_ui/src/app/components/chat-interface/chat-interface.component.ts +0 -270
- package/artemis-main/apps/showcase_ui/src/app/components/floating-video-player/floating-video-player.component.html +0 -433
- package/artemis-main/apps/showcase_ui/src/app/components/floating-video-player/floating-video-player.component.scss +0 -987
- package/artemis-main/apps/showcase_ui/src/app/components/floating-video-player/floating-video-player.component.ts +0 -632
- package/artemis-main/apps/showcase_ui/src/app/components/legacy-agent-stream/legacy-agent-stream.component.html +0 -130
- package/artemis-main/apps/showcase_ui/src/app/components/legacy-agent-stream/legacy-agent-stream.component.scss +0 -406
- package/artemis-main/apps/showcase_ui/src/app/components/legacy-agent-stream/legacy-agent-stream.component.ts +0 -74
- package/artemis-main/apps/showcase_ui/src/app/components/nav-switcher/nav-switcher.component.scss +0 -115
- package/artemis-main/apps/showcase_ui/src/app/components/nav-switcher/nav-switcher.component.ts +0 -52
- package/artemis-main/apps/showcase_ui/src/app/core/data/smart-tasks.data.ts +0 -334
- package/artemis-main/apps/showcase_ui/src/app/core/i18n/language.service.spec.ts +0 -55
- package/artemis-main/apps/showcase_ui/src/app/core/i18n/language.service.ts +0 -61
- package/artemis-main/apps/showcase_ui/src/app/core/i18n/translate.pipe.ts +0 -11
- package/artemis-main/apps/showcase_ui/src/app/core/i18n/zh-cn.ts +0 -651
- package/artemis-main/apps/showcase_ui/src/app/core/models/markdown.model.ts +0 -43
- package/artemis-main/apps/showcase_ui/src/app/core/models/pro-tuning.model.spec.ts +0 -47
- package/artemis-main/apps/showcase_ui/src/app/core/models/pro-tuning.model.ts +0 -165
- package/artemis-main/apps/showcase_ui/src/app/core/models/session.model.ts +0 -85
- package/artemis-main/apps/showcase_ui/src/app/core/models/stream.model.ts +0 -246
- package/artemis-main/apps/showcase_ui/src/app/core/models/system.model.ts +0 -118
- package/artemis-main/apps/showcase_ui/src/app/core/services/task-recommendation.service.ts +0 -111
- package/artemis-main/apps/showcase_ui/src/app/pages/home/home.component.html +0 -2130
- package/artemis-main/apps/showcase_ui/src/app/pages/home/home.component.scss +0 -5204
- package/artemis-main/apps/showcase_ui/src/app/pages/home/home.component.ts +0 -1189
- package/artemis-main/apps/showcase_ui/src/app/pages/legacy-workspace/legacy-workspace.component.html +0 -39
- package/artemis-main/apps/showcase_ui/src/app/pages/legacy-workspace/legacy-workspace.component.scss +0 -151
- package/artemis-main/apps/showcase_ui/src/app/pages/legacy-workspace/legacy-workspace.component.ts +0 -58
- package/artemis-main/apps/showcase_ui/src/app/pages/workspace/workspace.component.html +0 -201
- package/artemis-main/apps/showcase_ui/src/app/pages/workspace/workspace.component.scss +0 -886
- package/artemis-main/apps/showcase_ui/src/app/pages/workspace/workspace.component.ts +0 -324
- package/artemis-main/apps/showcase_ui/src/app/services/agent.service.spec.ts +0 -418
- package/artemis-main/apps/showcase_ui/src/app/services/agent.service.ts +0 -2012
- package/artemis-main/apps/showcase_ui/src/app/services/system.service.spec.ts +0 -173
- package/artemis-main/apps/showcase_ui/src/app/services/system.service.ts +0 -620
- package/artemis-main/apps/showcase_ui/src/app/utils/action-formatter.util.spec.ts +0 -513
- package/artemis-main/apps/showcase_ui/src/app/utils/action-formatter.util.ts +0 -1015
- package/artemis-main/apps/showcase_ui/src/app/utils/image-overlay.util.spec.ts +0 -85
- package/artemis-main/apps/showcase_ui/src/app/utils/image-overlay.util.ts +0 -662
- package/artemis-main/apps/showcase_ui/src/app/utils/markdown-parser.util.spec.ts +0 -70
- package/artemis-main/apps/showcase_ui/src/app/utils/markdown-parser.util.ts +0 -383
- package/artemis-main/apps/showcase_ui/src/app/utils/recording-timeline.util.spec.ts +0 -107
- package/artemis-main/apps/showcase_ui/src/app/utils/recording-timeline.util.ts +0 -123
- package/artemis-main/apps/showcase_ui/src/app/utils/run-info.util.spec.ts +0 -92
- package/artemis-main/apps/showcase_ui/src/app/utils/run-info.util.ts +0 -116
- package/artemis-main/apps/showcase_ui/src/app/utils/stream-aggregator.util.spec.ts +0 -640
- package/artemis-main/apps/showcase_ui/src/app/utils/stream-aggregator.util.ts +0 -1021
- package/artemis-main/apps/showcase_ui/src/app/utils/tool-formatter.util.spec.ts +0 -375
- package/artemis-main/apps/showcase_ui/src/app/utils/tool-formatter.util.ts +0 -1419
- package/artemis-main/apps/showcase_ui/src/index.html +0 -37
- package/artemis-main/apps/showcase_ui/src/main.ts +0 -22
- package/artemis-main/apps/showcase_ui/src/styles.scss +0 -60
- package/artemis-main/apps/showcase_ui/tsconfig.app.json +0 -23
- package/artemis-main/apps/showcase_ui/tsconfig.json +0 -27
- package/artemis-main/apps/showcase_ui/tsconfig.spec.json +0 -23
- package/artemis-main/artemis/__init__.py +0 -44
- package/artemis-main/artemis/__main__.py +0 -18
- package/artemis-main/artemis/_legacy_imports.py +0 -94
- package/artemis-main/artemis/_version.py +0 -30
- package/artemis-main/artemis/agents/__init__.py +0 -17
- package/artemis-main/artemis/agents/checker/checker.json +0 -9
- package/artemis-main/artemis/agents/checker/checker.py +0 -859
- package/artemis-main/artemis/agents/diagnoser/diagnoser.json +0 -23
- package/artemis-main/artemis/agents/diagnoser/diagnoser.py +0 -608
- package/artemis-main/artemis/agents/explorer/constants.py +0 -52
- package/artemis-main/artemis/agents/explorer/explorer.json +0 -57
- package/artemis-main/artemis/agents/explorer/explorer.py +0 -473
- package/artemis-main/artemis/agents/explorer/geometry.py +0 -73
- package/artemis-main/artemis/agents/explorer/native_runner.py +0 -878
- package/artemis-main/artemis/agents/explorer/perception_tools.py +0 -632
- package/artemis-main/artemis/agents/explorer/run_setup.py +0 -403
- package/artemis-main/artemis/agents/explorer/screen_index.py +0 -266
- package/artemis-main/artemis/agents/explorer/tiers.py +0 -110
- package/artemis-main/artemis/agents/explorer/tool_declarations.py +0 -394
- package/artemis-main/artemis/agents/explorer/universal_runner.py +0 -317
- package/artemis-main/artemis/agents/flash/context_compressor.py +0 -452
- package/artemis-main/artemis/agents/flash/flash_runner.md +0 -51
- package/artemis-main/artemis/agents/flash/flash_summarizer.md +0 -53
- package/artemis-main/artemis/agents/flash/flash_summarizer_single.md +0 -54
- package/artemis-main/artemis/agents/flash/runner.py +0 -1167
- package/artemis-main/artemis/agents/flash/summarizer.py +0 -511
- package/artemis-main/artemis/agents/history_analyzer/history_analyzer.md +0 -8
- package/artemis-main/artemis/agents/history_analyzer/history_analyzer.py +0 -182
- package/artemis-main/artemis/agents/image_processor/image_processor.md +0 -74
- package/artemis-main/artemis/agents/image_processor/image_processor.py +0 -322
- package/artemis-main/artemis/agents/log_analyzer/log_analyzer.md +0 -15
- package/artemis-main/artemis/agents/log_analyzer/log_analyzer.py +0 -403
- package/artemis-main/artemis/agents/log_analyzer/log_reader_sub_agent.md +0 -8
- package/artemis-main/artemis/agents/log_analyzer/output_analyzer.md +0 -11
- package/artemis-main/artemis/agents/log_analyzer/output_analyzer.py +0 -163
- package/artemis-main/artemis/agents/object_detector/object_detector.json +0 -9
- package/artemis-main/artemis/agents/object_detector/object_detector.py +0 -211
- package/artemis-main/artemis/agents/operator/operator.json +0 -3
- package/artemis-main/artemis/agents/operator/operator.py +0 -1394
- package/artemis-main/artemis/agents/operator/prompts.py +0 -1064
- package/artemis-main/artemis/agents/outputter/outputter.md +0 -36
- package/artemis-main/artemis/agents/outputter/outputter.py +0 -552
- package/artemis-main/artemis/agents/planner/planner.json +0 -32
- package/artemis-main/artemis/agents/planner/planner.py +0 -436
- package/artemis-main/artemis/agents/prompt_assembly.py +0 -79
- package/artemis-main/artemis/agents/summarizer/summarizer.py +0 -190
- package/artemis-main/artemis/agents/validator/action_execution.py +0 -98
- package/artemis-main/artemis/agents/validator/categories.py +0 -33
- package/artemis-main/artemis/agents/validator/execution_loop.py +0 -488
- package/artemis-main/artemis/agents/validator/incidents.py +0 -120
- package/artemis-main/artemis/agents/validator/pixel_safety_net.md +0 -15
- package/artemis-main/artemis/agents/validator/precondition_pixel.py +0 -320
- package/artemis-main/artemis/agents/validator/precondition_xml.py +0 -672
- package/artemis-main/artemis/agents/validator/tool_declarations.py +0 -332
- package/artemis-main/artemis/agents/validator/validator.py +0 -188
- package/artemis-main/artemis/agents/video_analyzer/__init__.py +0 -15
- package/artemis-main/artemis/agents/video_analyzer/audio_native.py +0 -543
- package/artemis-main/artemis/agents/video_analyzer/blackboard.py +0 -821
- package/artemis-main/artemis/agents/video_analyzer/chunk_agentic.py +0 -455
- package/artemis-main/artemis/agents/video_analyzer/chunk_conversation.py +0 -491
- package/artemis-main/artemis/agents/video_analyzer/chunk_native.py +0 -437
- package/artemis-main/artemis/agents/video_analyzer/conflict_resolution.py +0 -137
- package/artemis-main/artemis/agents/video_analyzer/gemini_files.py +0 -162
- package/artemis-main/artemis/agents/video_analyzer/native_coordinator.py +0 -541
- package/artemis-main/artemis/agents/video_analyzer/reliability.py +0 -128
- package/artemis-main/artemis/agents/video_analyzer/universal_engine.py +0 -487
- package/artemis-main/artemis/agents/video_analyzer/universal_tools.py +0 -323
- package/artemis-main/artemis/agents/video_analyzer/video_analyzer.md +0 -51
- package/artemis-main/artemis/agents/video_analyzer/video_analyzer.py +0 -875
- package/artemis-main/artemis/agents/video_analyzer/video_sub_agent.md +0 -15
- package/artemis-main/artemis/agents/video_analyzer/video_sub_agent_audio.md +0 -12
- package/artemis-main/artemis/clients/accessibility_client.py +0 -438
- package/artemis-main/artemis/clients/screen_client_factory.py +0 -403
- package/artemis-main/artemis/config/__init__.py +0 -309
- package/artemis-main/artemis/config/agent.py +0 -1098
- package/artemis-main/artemis/config/constants.py +0 -151
- package/artemis-main/artemis/config/core/__init__.py +0 -24
- package/artemis-main/artemis/config/core/engine.py +0 -118
- package/artemis-main/artemis/config/core/interpolator.py +0 -78
- package/artemis-main/artemis/config/llm.py +0 -267
- package/artemis-main/artemis/config/paths.py +0 -244
- package/artemis-main/artemis/config/runtime.py +0 -197
- package/artemis-main/artemis/config/settings.py +0 -315
- package/artemis-main/artemis/constants.py +0 -47
- package/artemis-main/artemis/context.py +0 -289
- package/artemis-main/artemis/controllers/__init__.py +0 -41
- package/artemis-main/artemis/controllers/controller_factory.py +0 -41
- package/artemis-main/artemis/controllers/device_controller.py +0 -29
- package/artemis-main/artemis/controllers/types.py +0 -37
- package/artemis-main/artemis/controllers/unified_controller.py +0 -649
- package/artemis-main/artemis/core/__init__.py +0 -21
- package/artemis-main/artemis/core/diagnostics/__init__.py +0 -90
- package/artemis-main/artemis/core/diagnostics/adb_keys.py +0 -270
- package/artemis-main/artemis/core/diagnostics/adb_server_connection.py +0 -330
- package/artemis-main/artemis/core/diagnostics/device_smoke.py +0 -364
- package/artemis-main/artemis/core/diagnostics/emulator_manager.py +0 -501
- package/artemis-main/artemis/core/diagnostics/engine.py +0 -438
- package/artemis-main/artemis/core/diagnostics/hierarchy_parity.py +0 -216
- package/artemis-main/artemis/core/diagnostics/probes/adb_probe.py +0 -887
- package/artemis-main/artemis/core/diagnostics/probes/base.py +0 -45
- package/artemis-main/artemis/core/diagnostics/probes/credentials_probe.py +0 -296
- package/artemis-main/artemis/core/diagnostics/probes/host_probe.py +0 -427
- package/artemis-main/artemis/core/diagnostics/probes/runtime_probe.py +0 -169
- package/artemis-main/artemis/core/diagnostics/probes/toolchain_probe.py +0 -139
- package/artemis-main/artemis/core/diagnostics/readiness.py +0 -83
- package/artemis-main/artemis/core/diagnostics/schema.py +0 -118
- package/artemis-main/artemis/core/tool_declaration.py +0 -43
- package/artemis-main/artemis/core/tool_failure.py +0 -56
- package/artemis-main/artemis/data_engine/context_vars.py +0 -24
- package/artemis-main/artemis/data_engine/engine.py +0 -1615
- package/artemis-main/artemis/data_engine/history_reader.py +0 -142
- package/artemis-main/artemis/data_engine/models.py +0 -131
- package/artemis-main/artemis/data_engine/storage.py +0 -1245
- package/artemis-main/artemis/data_engine/trace.py +0 -727
- package/artemis-main/artemis/drivers/__init__.py +0 -48
- package/artemis-main/artemis/drivers/android/adb_driver.py +0 -507
- package/artemis-main/artemis/drivers/android/hierarchy.py +0 -64
- package/artemis-main/artemis/drivers/android/input_ime.py +0 -120
- package/artemis-main/artemis/drivers/android/recorder.py +0 -57
- package/artemis-main/artemis/drivers/base.py +0 -290
- package/artemis-main/artemis/drivers/cloud/cloud_driver.py +0 -117
- package/artemis-main/artemis/drivers/factory.py +0 -80
- package/artemis-main/artemis/drivers/mock/mock_driver.py +0 -198
- package/artemis-main/artemis/drivers/types.py +0 -67
- package/artemis-main/artemis/graph/checkpoints.py +0 -1243
- package/artemis-main/artemis/graph/graph.py +0 -1055
- package/artemis-main/artemis/graph/perception.py +0 -234
- package/artemis-main/artemis/graph/state.py +0 -151
- package/artemis-main/artemis/graph/visibility.py +0 -238
- package/artemis-main/artemis/interfaces/cli/__init__.py +0 -19
- package/artemis-main/artemis/interfaces/cli/commands/__init__.py +0 -15
- package/artemis-main/artemis/interfaces/cli/commands/batch.py +0 -278
- package/artemis-main/artemis/interfaces/cli/commands/doctor.py +0 -468
- package/artemis-main/artemis/interfaces/cli/commands/helper.py +0 -226
- package/artemis-main/artemis/interfaces/cli/commands/init.py +0 -193
- package/artemis-main/artemis/interfaces/cli/commands/mcp.py +0 -862
- package/artemis-main/artemis/interfaces/cli/commands/run.py +0 -463
- package/artemis-main/artemis/interfaces/cli/commands/server.py +0 -151
- package/artemis-main/artemis/interfaces/cli/commands/server_lifecycle.py +0 -328
- package/artemis-main/artemis/interfaces/cli/commands/trace.py +0 -111
- package/artemis-main/artemis/interfaces/cli/commands/ui.py +0 -404
- package/artemis-main/artemis/interfaces/cli/main.py +0 -109
- package/artemis-main/artemis/interfaces/sdk/__init__.py +0 -31
- package/artemis-main/artemis/interfaces/sdk/client.py +0 -19
- package/artemis-main/artemis/interfaces/sdk/task.py +0 -72
- package/artemis-main/artemis/llm/__init__.py +0 -25
- package/artemis-main/artemis/llm/fake_model.py +0 -179
- package/artemis-main/artemis/llm/google/__init__.py +0 -57
- package/artemis-main/artemis/llm/google/provider.py +0 -185
- package/artemis-main/artemis/llm/google/usage.py +0 -148
- package/artemis-main/artemis/llm/parser.py +0 -32
- package/artemis-main/artemis/llm/reliability.py +0 -267
- package/artemis-main/artemis/llm/router.py +0 -389
- package/artemis-main/artemis/llm/schemas.py +0 -36
- package/artemis-main/artemis/llm/structured.py +0 -196
- package/artemis-main/artemis/main.py +0 -58
- package/artemis-main/artemis/mcp/__init__.py +0 -20
- package/artemis-main/artemis/mcp/action_executor.py +0 -760
- package/artemis-main/artemis/mcp/action_manifest.py +0 -320
- package/artemis-main/artemis/mcp/action_names.py +0 -172
- package/artemis-main/artemis/mcp/action_server.py +0 -202
- package/artemis-main/artemis/mcp/action_session.py +0 -245
- package/artemis-main/artemis/mcp/action_specs.py +0 -868
- package/artemis-main/artemis/mcp/action_types.py +0 -86
- package/artemis-main/artemis/mcp/actuators/__init__.py +0 -21
- package/artemis-main/artemis/mcp/actuators/adb.py +0 -414
- package/artemis-main/artemis/mcp/actuators/base.py +0 -113
- package/artemis-main/artemis/mcp/actuators/mock.py +0 -70
- package/artemis-main/artemis/mcp/adb_server.py +0 -490
- package/artemis-main/artemis/mcp/observation.py +0 -133
- package/artemis-main/artemis/mcp/xml_search_server.py +0 -297
- package/artemis-main/artemis/memory/__init__.py +0 -90
- package/artemis-main/artemis/memory/chunking.py +0 -1843
- package/artemis-main/artemis/memory/context_policy.py +0 -226
- package/artemis-main/artemis/memory/step_capsule.md +0 -73
- package/artemis-main/artemis/memory/step_memory.py +0 -281
- package/artemis-main/artemis/memory/transcript.py +0 -798
- package/artemis-main/artemis/platform/__init__.py +0 -61
- package/artemis-main/artemis/platform/base.py +0 -104
- package/artemis-main/artemis/platform/darwin.py +0 -184
- package/artemis-main/artemis/platform/linux.py +0 -207
- package/artemis-main/artemis/platform/windows.py +0 -193
- package/artemis-main/artemis/resources/__init__.py +0 -46
- package/artemis-main/artemis/runtime/__init__.py +0 -108
- package/artemis-main/artemis/runtime/adb_endpoint.py +0 -173
- package/artemis-main/artemis/runtime/awake_lease.py +0 -283
- package/artemis-main/artemis/runtime/awake_service.py +0 -343
- package/artemis-main/artemis/runtime/cancel_requests.py +0 -254
- package/artemis-main/artemis/runtime/daemon_client.py +0 -422
- package/artemis-main/artemis/runtime/device_lock.py +0 -1013
- package/artemis-main/artemis/runtime/device_pool.py +0 -478
- package/artemis-main/artemis/runtime/helper_manager.py +0 -1030
- package/artemis-main/artemis/runtime/process_probe.py +0 -98
- package/artemis-main/artemis/runtime/server_lifecycle.py +0 -435
- package/artemis-main/artemis/runtime/supervisor.py +0 -121
- package/artemis-main/artemis/runtime/trace_store.py +0 -375
- package/artemis-main/artemis/sdk/__init__.py +0 -26
- package/artemis-main/artemis/sdk/agent.py +0 -485
- package/artemis-main/artemis/sdk/builders/__init__.py +0 -29
- package/artemis-main/artemis/sdk/builders/agent_config_builder.py +0 -474
- package/artemis-main/artemis/sdk/constants.py +0 -15
- package/artemis-main/artemis/sdk/run_outcome.py +0 -58
- package/artemis-main/artemis/sdk/types/__init__.py +0 -61
- package/artemis-main/artemis/sdk/types/agent.py +0 -89
- package/artemis-main/artemis/sdk/utils.py +0 -28
- package/artemis-main/artemis/services/llm.py +0 -1040
- package/artemis-main/artemis/services/token_meter.py +0 -267
- package/artemis-main/artemis/telemetry/__init__.py +0 -35
- package/artemis-main/artemis/telemetry/models.py +0 -64
- package/artemis-main/artemis/telemetry/replay.py +0 -34
- package/artemis-main/artemis/telemetry/storage/json_storage.py +0 -47
- package/artemis-main/artemis/telemetry/tracer.py +0 -85
- package/artemis-main/artemis/toolchain/__init__.py +0 -52
- package/artemis-main/artemis/toolchain/descriptors.py +0 -92
- package/artemis-main/artemis/toolchain/resolver.py +0 -185
- package/artemis-main/artemis/tools/base.py +0 -232
- package/artemis-main/artemis/tools/command_tool.py +0 -1240
- package/artemis-main/artemis/tools/committee_prompts.json +0 -5
- package/artemis-main/artemis/tools/committee_tool.py +0 -422
- package/artemis-main/artemis/tools/diagnoser_submit_answer_tool.py +0 -87
- package/artemis-main/artemis/tools/diagnostic_tool.py +0 -120
- package/artemis-main/artemis/tools/explorer_tool.py +0 -581
- package/artemis-main/artemis/tools/history/__init__.py +0 -398
- package/artemis-main/artemis/tools/history/replay.py +0 -120
- package/artemis-main/artemis/tools/history/screenshot.py +0 -139
- package/artemis-main/artemis/tools/history/search.py +0 -563
- package/artemis-main/artemis/tools/image_processor_tool.py +0 -124
- package/artemis-main/artemis/tools/index.py +0 -47
- package/artemis-main/artemis/tools/log_tool.py +0 -108
- package/artemis-main/artemis/tools/mobile/launch_app.py +0 -132
- package/artemis-main/artemis/tools/mobile/log_utils.py +0 -138
- package/artemis-main/artemis/tools/mobile/ocr.py +0 -202
- package/artemis-main/artemis/tools/mobile/read_hierarchy.py +0 -108
- package/artemis-main/artemis/tools/mobile/read_logs.py +0 -116
- package/artemis-main/artemis/tools/mobile/search_logs.py +0 -260
- package/artemis-main/artemis/tools/object_detection_tool.py +0 -244
- package/artemis-main/artemis/tools/scratchpad.py +0 -819
- package/artemis-main/artemis/tools/system/adb_shell.py +0 -31
- package/artemis-main/artemis/tools/tool_wrapper.py +0 -270
- package/artemis-main/artemis/tools/video_tool.py +0 -261
- package/artemis-main/artemis/tools/wait_tool.py +0 -97
- package/artemis-main/artemis/utils/app_launch_utils.py +0 -207
- package/artemis-main/artemis/utils/coordinates.py +0 -606
- package/artemis-main/artemis/utils/credentials_validator.py +0 -201
- package/artemis-main/artemis/utils/cv_canvas.py +0 -189
- package/artemis-main/artemis/utils/cython_compat.py +0 -45
- package/artemis-main/artemis/utils/element_hit_test.py +0 -80
- package/artemis-main/artemis/utils/image_diff.py +0 -335
- package/artemis-main/artemis/utils/image_hash.py +0 -80
- package/artemis-main/artemis/utils/notes.py +0 -470
- package/artemis-main/artemis/utils/ocr_api.py +0 -105
- package/artemis-main/artemis/utils/ocr_xml_fusion.py +0 -318
- package/artemis-main/artemis/utils/plan_grammar.py +0 -513
- package/artemis-main/artemis/utils/python_executor.py +0 -213
- package/artemis-main/artemis/utils/startup_progress.py +0 -60
- package/artemis-main/artemis/utils/task_tree.py +0 -1174
- package/artemis-main/artemis/utils/text.py +0 -37
- package/artemis-main/artemis/utils/ui_filter.py +0 -651
- package/artemis-main/artemis/utils/video.py +0 -685
- package/artemis-main/artemis/utils/visualization.py +0 -802
- package/artemis-main/config/artemis.example.jsonc +0 -12
- package/artemis-main/mcp_server/README.md +0 -111
- package/artemis-main/mcp_server/__init__.py +0 -21
- package/artemis-main/mcp_server/__main__.py +0 -20
- package/artemis-main/mcp_server/background/__init__.py +0 -15
- package/artemis-main/mcp_server/background/task_runner.py +0 -453
- package/artemis-main/mcp_server/base.py +0 -49
- package/artemis-main/mcp_server/notifiers/__init__.py +0 -74
- package/artemis-main/mcp_server/notifiers/agentapi.py +0 -289
- package/artemis-main/mcp_server/notifiers/base.py +0 -45
- package/artemis-main/mcp_server/notifiers/composite.py +0 -87
- package/artemis-main/mcp_server/notifiers/desktop.py +0 -108
- package/artemis-main/mcp_server/notifiers/file.py +0 -69
- package/artemis-main/mcp_server/notifiers/script.py +0 -90
- package/artemis-main/mcp_server/notifiers/webhook.py +0 -87
- package/artemis-main/mcp_server/rules.md +0 -68
- package/artemis-main/mcp_server/server.py +0 -106
- package/artemis-main/mcp_server/tools/__init__.py +0 -29
- package/artemis-main/mcp_server/tools/device_state.py +0 -107
- package/artemis-main/mcp_server/tools/diagnose.py +0 -1249
- package/artemis-main/mcp_server/tools/inspect_trace.py +0 -394
- package/artemis-main/mcp_server/tools/task_manager.py +0 -627
- package/artemis-main/mcp_server/tools/task_runner.py +0 -548
- package/artemis-main/mcp_server/utils/__init__.py +0 -15
- package/artemis-main/mcp_server/utils/device_utils.py +0 -180
- package/artemis-main/mcp_server/utils/env_utils.py +0 -65
- package/artemis-main/packages/artemis-accessibility-helper/ArtemisAccessibilityHelper.apk +0 -0
- package/artemis-main/packages/artemis-accessibility-helper/app/build.gradle.kts +0 -35
- package/artemis-main/packages/artemis-accessibility-helper/app/src/main/AndroidManifest.xml +0 -49
- package/artemis-main/packages/artemis-accessibility-helper/app/src/main/java/com/artemis/helper/A11yNode.java +0 -274
- package/artemis-main/packages/artemis-accessibility-helper/app/src/main/java/com/artemis/helper/ArtemisAccessibilityService.java +0 -227
- package/artemis-main/packages/artemis-accessibility-helper/app/src/main/java/com/artemis/helper/CommandServer.java +0 -463
- package/artemis-main/packages/artemis-accessibility-helper/app/src/main/java/com/artemis/helper/DisplayUtils.java +0 -111
- package/artemis-main/packages/artemis-accessibility-helper/app/src/main/java/com/artemis/helper/GestureController.java +0 -232
- package/artemis-main/packages/artemis-accessibility-helper/app/src/main/java/com/artemis/helper/HierarchyDumper.java +0 -832
- package/artemis-main/packages/artemis-accessibility-helper/app/src/main/java/com/artemis/helper/TokenReceiver.java +0 -36
- package/artemis-main/packages/artemis-accessibility-helper/app/src/main/java/com/artemis/helper/TokenStore.java +0 -38
- package/artemis-main/packages/artemis-accessibility-helper/app/src/main/java/com/artemis/helper/XmlUtils.java +0 -102
- package/artemis-main/packages/artemis-accessibility-helper/app/src/main/res/values/strings.xml +0 -4
- package/artemis-main/packages/artemis-accessibility-helper/app/src/main/res/xml/accessibility_service_config.xml +0 -10
- package/artemis-main/packages/artemis-accessibility-helper/build.gradle.kts +0 -3
- package/artemis-main/packages/artemis-accessibility-helper/build_apk.sh +0 -215
- package/artemis-main/packages/artemis-accessibility-helper/debug.keystore +0 -0
- package/artemis-main/packages/artemis-accessibility-helper/gradle.properties +0 -2
- package/artemis-main/packages/artemis-accessibility-helper/helper_manifest.json +0 -7
- package/artemis-main/packages/artemis-accessibility-helper/settings.gradle.kts +0 -17
- package/artemis-main/packages/artemis-client/DESIGN.md +0 -89
- package/artemis-main/packages/artemis-client/README.md +0 -112
- package/artemis-main/packages/artemis-client/examples/basic.py +0 -30
- package/artemis-main/packages/artemis-client/pyproject.toml +0 -36
- package/artemis-main/packages/artemis-client/src/artemis_client/__init__.py +0 -45
- package/artemis-main/packages/artemis-client/src/artemis_client/client.py +0 -401
- package/artemis-main/packages/artemis-client/src/artemis_client/errors.py +0 -66
- package/artemis-main/packages/artemis-client/src/artemis_client/models.py +0 -212
- package/artemis-main/packages/artemis-client/src/artemis_client/py.typed +0 -1
- package/artemis-main/packages/artemis-client/src/artemis_client/transport.py +0 -134
- package/artemis-main/packages/artemis-client/tests/test_client.py +0 -289
- package/artemis-main/packages/artemis-client/tests/test_transport.py +0 -85
- package/artemis-main/pyproject.toml +0 -259
- package/artemis-main/pyright-core.json +0 -17
- package/artemis-main/scripts/check_dependency_sources.py +0 -68
- package/artemis-main/scripts/install_deps.ps1 +0 -520
- package/artemis-main/scripts/install_deps.sh +0 -533
- package/artemis-main/scripts/quality_ratchet.py +0 -97
- package/artemis-main/scripts/real_device_video_acceptance.py +0 -483
- package/artemis-main/scripts/run_edge_case_part.py +0 -327
- package/artemis-main/scripts/run_ui.py +0 -242
- package/artemis-main/scripts/start.ps1 +0 -500
- package/artemis-main/scripts/test_all_edge_cases.py +0 -269
- package/artemis-main/scripts/verify_concurrency_and_devices.py +0 -385
- package/artemis-main/setup.py +0 -164
- package/artemis-main/start.bat +0 -35
- package/artemis-main/start.sh +0 -423
- package/artemis-main/third_party/mobile_use/LICENSE +0 -190
- package/artemis-main/third_party/mobile_use/METADATA +0 -27
- package/artemis-main/third_party/mobile_use/NOTICE +0 -12
- package/artemis-main/third_party/mobile_use/__init__.py +0 -19
- package/artemis-main/third_party/mobile_use/agents/__init__.py +0 -13
- package/artemis-main/third_party/mobile_use/agents/hopper/__init__.py +0 -13
- package/artemis-main/third_party/mobile_use/agents/hopper/hopper.md +0 -22
- package/artemis-main/third_party/mobile_use/agents/hopper/hopper.py +0 -80
- package/artemis-main/third_party/mobile_use/clients/__init__.py +0 -13
- package/artemis-main/third_party/mobile_use/clients/ui_automator_client.py +0 -482
- package/artemis-main/third_party/mobile_use/config/__init__.py +0 -13
- package/artemis-main/third_party/mobile_use/config/llm.py +0 -183
- package/artemis-main/third_party/mobile_use/config/output.py +0 -184
- package/artemis-main/third_party/mobile_use/context.py +0 -119
- package/artemis-main/third_party/mobile_use/controllers/__init__.py +0 -13
- package/artemis-main/third_party/mobile_use/controllers/platform_specific_commands_controller.py +0 -151
- package/artemis-main/third_party/mobile_use/controllers/types.py +0 -92
- package/artemis-main/third_party/mobile_use/controllers/unified_controller.py +0 -183
- package/artemis-main/third_party/mobile_use/graph.py +0 -54
- package/artemis-main/third_party/mobile_use/llm_service.py +0 -193
- package/artemis-main/third_party/mobile_use/main.py +0 -130
- package/artemis-main/third_party/mobile_use/sdk/__init__.py +0 -13
- package/artemis-main/third_party/mobile_use/sdk/agent.py +0 -1060
- package/artemis-main/third_party/mobile_use/sdk/builders/__init__.py +0 -13
- package/artemis-main/third_party/mobile_use/sdk/builders/agent_config_builder.py +0 -225
- package/artemis-main/third_party/mobile_use/sdk/builders/index.py +0 -33
- package/artemis-main/third_party/mobile_use/sdk/builders/task_request_builder.py +0 -243
- package/artemis-main/third_party/mobile_use/sdk/types/__init__.py +0 -13
- package/artemis-main/third_party/mobile_use/sdk/types/agent.py +0 -98
- package/artemis-main/third_party/mobile_use/sdk/types/exceptions.py +0 -109
- package/artemis-main/third_party/mobile_use/sdk/types/task.py +0 -234
- package/artemis-main/third_party/mobile_use/testing.py +0 -59
- package/artemis-main/third_party/mobile_use/tools/__init__.py +0 -13
- package/artemis-main/third_party/mobile_use/tools/index.py +0 -44
- package/artemis-main/third_party/mobile_use/tools/mobile/__init__.py +0 -13
- package/artemis-main/third_party/mobile_use/tools/mobile/launch_app.py +0 -89
- package/artemis-main/third_party/mobile_use/tools/tool_wrapper.py +0 -52
- package/artemis-main/third_party/mobile_use/utils/__init__.py +0 -13
- package/artemis-main/third_party/mobile_use/utils/app_launch_utils.py +0 -217
- package/artemis-main/third_party/mobile_use/utils/cli_helpers.py +0 -60
- package/artemis-main/third_party/mobile_use/utils/decorators.py +0 -158
- package/artemis-main/third_party/mobile_use/utils/file.py +0 -31
- package/artemis-main/third_party/mobile_use/utils/logger.py +0 -216
- package/artemis-main/third_party/mobile_use/utils/media.py +0 -213
- package/artemis-main/third_party/mobile_use/utils/shell_utils.py +0 -39
- package/artemis-main/third_party/mobile_use/utils/video.py +0 -398
- package/artemis-main/uv.lock +0 -4908
- package/bin/artemis-config.mjs +0 -15
- package/bin/artemis-embedded.py +0 -56
- package/bin/start-artemis.mjs +0 -30
- package/bin/start-dev.mjs +0 -112
- package/bin/sync-readme-docs.mjs +0 -49
- package/bin/test_artemis_embedded.py +0 -44
- package/index.html +0 -12
- package/remote-agent/index.ts +0 -232
- package/server/analytics.test.ts +0 -46
- package/server/analytics.ts +0 -24
- package/server/android-device-info.ts +0 -28
- package/server/android-sdk.ts +0 -104
- package/server/api-safety-analytics.test.ts +0 -57
- package/server/appium-auto-save.test.ts +0 -79
- package/server/appium-config.test.ts +0 -182
- package/server/appium-recorder/ai-deduplication.test.ts +0 -80
- package/server/appium-recorder/ai-deduplication.ts +0 -74
- package/server/appium-recorder/ai-observation.test.ts +0 -125
- package/server/appium-recorder/ai-observation.ts +0 -125
- package/server/appium-recorder/ai-recognition.test.ts +0 -27
- package/server/appium-recorder/ai-recognition.ts +0 -186
- package/server/appium-recorder/appium-runner.ts +0 -1993
- package/server/appium-recorder/appium-version.test.ts +0 -55
- package/server/appium-recorder/bounded-loop.test.ts +0 -55
- package/server/appium-recorder/bounded-loop.ts +0 -129
- package/server/appium-recorder/condition-timeout.ts +0 -4
- package/server/appium-recorder/element-tap.test.ts +0 -312
- package/server/appium-recorder/flow-layout.test.ts +0 -52
- package/server/appium-recorder/history-capture.ts +0 -35
- package/server/appium-recorder/image-check.ts +0 -174
- package/server/appium-recorder/managed-appium.ts +0 -198
- package/server/appium-recorder/managed-cleanup.test.ts +0 -113
- package/server/appium-recorder/open-gallery.ts +0 -61
- package/server/appium-recorder/prompt-optimizer.ts +0 -57
- package/server/appium-recorder/random-value-replay.test.ts +0 -101
- package/server/appium-recorder/random-value.test.ts +0 -114
- package/server/appium-recorder/random-value.ts +0 -34
- package/server/appium-recorder/replay-lifecycle.test.ts +0 -123
- package/server/appium-recorder/replay-log.ts +0 -13
- package/server/appium-recorder/replay-mp4.ts +0 -72
- package/server/appium-recorder/replay-video-segments.ts +0 -77
- package/server/appium-recorder/replay-video.ts +0 -125
- package/server/appium-recorder/report-summary.test.ts +0 -78
- package/server/appium-recorder/report-summary.ts +0 -60
- package/server/appium-recorder/report.ts +0 -935
- package/server/appium-recorder/repository.ts +0 -567
- package/server/appium-recorder/request-timeout.test.ts +0 -34
- package/server/appium-recorder/request-timeout.ts +0 -34
- package/server/appium-recorder/routes.ts +0 -524
- package/server/appium-recorder/run-history.ts +0 -53
- package/server/appium-recorder/scrcpy-recording-source.ts +0 -85
- package/server/appium-recorder/screenshot.ts +0 -22
- package/server/appium-recorder/script-export.ts +0 -80
- package/server/appium-recorder/script-import.test.ts +0 -45
- package/server/appium-recorder/stop-app.ts +0 -18
- package/server/appium-recorder/stopwatch.test.ts +0 -74
- package/server/appium-recorder/stopwatch.ts +0 -24
- package/server/appium-recorder/tree-dump.ts +0 -66
- package/server/appium-recorder/variable-store.ts +0 -22
- package/server/appium-recorder/variables.ts +0 -89
- package/server/appium-recorder/video-response.ts +0 -36
- package/server/appium-recorder/visual-change.ts +0 -184
- package/server/artemis.ts +0 -34
- package/server/config-access.test.ts +0 -27
- package/server/config-access.ts +0 -27
- package/server/config-store.ts +0 -137
- package/server/config.ts +0 -272
- package/server/device-locks/repository.ts +0 -147
- package/server/device-locks/service.ts +0 -72
- package/server/device-locks/types.ts +0 -22
- package/server/device-sessions/repository.ts +0 -169
- package/server/device-sessions/service.ts +0 -59
- package/server/device-sessions/types.ts +0 -24
- package/server/http-api.ts +0 -1505
- package/server/model-tester.ts +0 -121
- package/server/operations/repository.ts +0 -226
- package/server/operations/service.ts +0 -84
- package/server/operations/types.ts +0 -27
- package/server/paths.ts +0 -36
- package/server/remote-agents/protocol.ts +0 -40
- package/server/remote-agents/registry.test.ts +0 -65
- package/server/remote-agents/registry.ts +0 -191
- package/server/remote-agents/replay-integration.test.ts +0 -79
- package/server/remote-agents/routes.ts +0 -86
- package/server/request-body.test.ts +0 -40
- package/server/request-body.ts +0 -48
- package/server/script-agent.ts +0 -289
- package/server/script-db.ts +0 -255
- package/server/script-runner.ts +0 -554
- package/server/storage/sqlite.ts +0 -112
- package/server/test-case-import/formatter.ts +0 -28
- package/server/test-case-import/parsers/excel.ts +0 -69
- package/server/test-case-import/parsers/txt.ts +0 -11
- package/server/test-case-import/parsers/word.ts +0 -9
- package/server/test-case-import/service.ts +0 -58
- package/server/test-case-import/text-normalizer.ts +0 -98
- package/server/test-case-import/types.ts +0 -24
- package/server/test-case-import/validator.ts +0 -34
- package/src/App.vue +0 -1035
- package/src/analytics/summary.ts +0 -75
- package/src/api.ts +0 -320
- package/src/appium-recorder/AppiumPage.vue +0 -2861
- package/src/appium-recorder/RunHistoryDialog.vue +0 -203
- package/src/appium-recorder/action-descriptions.ts +0 -50
- package/src/appium-recorder/ai-deduplication.ts +0 -34
- package/src/appium-recorder/ai-prompt-presets.ts +0 -34
- package/src/appium-recorder/ai-recognition.ts +0 -48
- package/src/appium-recorder/api.ts +0 -209
- package/src/appium-recorder/bounded-loop.ts +0 -74
- package/src/appium-recorder/components/AiRecognitionPromptInput.vue +0 -41
- package/src/appium-recorder/components/AiRecognitionSettings.vue +0 -251
- package/src/appium-recorder/components/AiRecognitionTestDialog.vue +0 -86
- package/src/appium-recorder/components/BranchTimeoutSettings.vue +0 -23
- package/src/appium-recorder/components/BreakLoopSettings.vue +0 -45
- package/src/appium-recorder/components/ComponentInspector.vue +0 -33
- package/src/appium-recorder/components/ComponentTree.vue +0 -139
- package/src/appium-recorder/components/CoordinatePointPicker.vue +0 -23
- package/src/appium-recorder/components/FlowActionMenu.vue +0 -257
- package/src/appium-recorder/components/FlowCanvas.vue +0 -391
- package/src/appium-recorder/components/FlowNodeCard.vue +0 -318
- package/src/appium-recorder/components/FlowNodeSearch.vue +0 -62
- package/src/appium-recorder/components/FlowRoundedEdge.vue +0 -58
- package/src/appium-recorder/components/FlowStepEditor.vue +0 -543
- package/src/appium-recorder/components/ImageCheckDialog.vue +0 -172
- package/src/appium-recorder/components/LongPressSettings.vue +0 -58
- package/src/appium-recorder/components/LoopSettings.vue +0 -39
- package/src/appium-recorder/components/MergeBranchesDialog.vue +0 -102
- package/src/appium-recorder/components/NestedConditionBranches.vue +0 -403
- package/src/appium-recorder/components/NewScriptDialog.vue +0 -27
- package/src/appium-recorder/components/NodeDetail.vue +0 -179
- package/src/appium-recorder/components/PresetVariables.vue +0 -110
- package/src/appium-recorder/components/RandomValueSettings.vue +0 -139
- package/src/appium-recorder/components/RecordedSteps.vue +0 -469
- package/src/appium-recorder/components/RecorderWorkspace.vue +0 -132
- package/src/appium-recorder/components/ScriptParameterSettings.vue +0 -65
- package/src/appium-recorder/components/StageLogSettings.vue +0 -17
- package/src/appium-recorder/components/StopwatchSettings.vue +0 -40
- package/src/appium-recorder/components/TextClickSettings.vue +0 -19
- package/src/appium-recorder/components/VariableExtractionSettings.vue +0 -19
- package/src/appium-recorder/components/VariableTable.vue +0 -82
- package/src/appium-recorder/components/VisualChangeDialog.vue +0 -151
- package/src/appium-recorder/components/VisualChangeEndPicker.vue +0 -21
- package/src/appium-recorder/coordinate-preview.ts +0 -37
- package/src/appium-recorder/flow-appearance.ts +0 -70
- package/src/appium-recorder/flow-copy.ts +0 -279
- package/src/appium-recorder/flow-graph.ts +0 -869
- package/src/appium-recorder/flow-insert.ts +0 -27
- package/src/appium-recorder/flow-labels.ts +0 -141
- package/src/appium-recorder/flow-layout.ts +0 -88
- package/src/appium-recorder/flow-merge.ts +0 -123
- package/src/appium-recorder/flow-normalize.ts +0 -77
- package/src/appium-recorder/flow-remove.ts +0 -75
- package/src/appium-recorder/flow-search.ts +0 -29
- package/src/appium-recorder/flow-unmerge.ts +0 -145
- package/src/appium-recorder/image-check.ts +0 -121
- package/src/appium-recorder/long-press.ts +0 -27
- package/src/appium-recorder/native-control-state.ts +0 -33
- package/src/appium-recorder/node-locators.ts +0 -25
- package/src/appium-recorder/node-timeout.ts +0 -1
- package/src/appium-recorder/random-value.ts +0 -60
- package/src/appium-recorder/report-summary.ts +0 -60
- package/src/appium-recorder/run-history.ts +0 -53
- package/src/appium-recorder/stage-log.ts +0 -21
- package/src/appium-recorder/stopwatch.ts +0 -27
- package/src/appium-recorder/text-click.ts +0 -9
- package/src/appium-recorder/tree.ts +0 -176
- package/src/appium-recorder/types.ts +0 -201
- package/src/appium-recorder/variable-presets.ts +0 -24
- package/src/appium-recorder/variables.ts +0 -34
- package/src/appium-recorder/visual-change-pairs.ts +0 -155
- package/src/appium-recorder/visual-change.ts +0 -87
- package/src/assets/appium-actions/add.svg +0 -7
- package/src/assets/appium-actions/android.svg +0 -6
- package/src/assets/appium-actions/back.svg +0 -6
- package/src/assets/appium-actions/bidirection.svg +0 -6
- package/src/assets/appium-actions/browser.svg +0 -6
- package/src/assets/appium-actions/clear.svg +0 -3
- package/src/assets/appium-actions/crosshair.svg +0 -6
- package/src/assets/appium-actions/eye.svg +0 -3
- package/src/assets/appium-actions/pause.svg +0 -7
- package/src/assets/appium-actions/phone.svg +0 -9
- package/src/assets/appium-actions/pin.svg +0 -6
- package/src/assets/appium-actions/power.svg +0 -6
- package/src/assets/appium-actions/select.svg +0 -3
- package/src/assets/appium-actions/sidebar.svg +0 -6
- package/src/assets/appium-actions/text.svg +0 -6
- package/src/assets/appium-actions/zoom.svg +0 -6
- package/src/assets/device-actions/back.svg +0 -5
- package/src/assets/device-actions/home.svg +0 -3
- package/src/assets/device-actions/power.svg +0 -5
- package/src/assets/device-actions/tasks.svg +0 -3
- package/src/assets/device-actions/volume-down.svg +0 -3
- package/src/assets/device-actions/volume-up.svg +0 -3
- package/src/components/AppSidebar.vue +0 -62
- package/src/components/MidsceneMaintenanceNotice.vue +0 -17
- package/src/components/analytics/AnalysisCharts.vue +0 -189
- package/src/components/analytics/ReportAnalysis.vue +0 -78
- package/src/components/config/AiDeduplicationSettings.vue +0 -70
- package/src/components/config/AiPromptPresetsSettings.vue +0 -113
- package/src/components/config/AppiumConfigPanel.vue +0 -118
- package/src/components/config/AppiumModelSettings.vue +0 -45
- package/src/components/config/BaseConfigPanel.vue +0 -127
- package/src/components/config/FlowAppearanceSettings.vue +0 -150
- package/src/components/config/MidsceneConfigPanel.vue +0 -220
- package/src/components/config/ReplayReportSummarySettings.vue +0 -118
- package/src/components/device/DeviceInfoTooltip.vue +0 -55
- package/src/components/device/DevicePreviewPanel.vue +0 -482
- package/src/components/generator/GeneratedCodePanel.vue +0 -70
- package/src/components/generator/TestCaseFileUpload.vue +0 -97
- package/src/components/help/HelpCenter.vue +0 -204
- package/src/components/help/MarkdownDocument.vue +0 -139
- package/src/composables/use-device-preview.ts +0 -279
- package/src/composables/use-initial-resource.ts +0 -17
- package/src/composables/use-script-execution.ts +0 -277
- package/src/config/credentials.ts +0 -2
- package/src/config/midscene-model-presets.ts +0 -103
- package/src/config/prompt-example.ts +0 -10
- package/src/config/prompt-presets.ts +0 -172
- package/src/config/use-appium-auto-save.ts +0 -75
- package/src/config/use-model-config.ts +0 -161
- package/src/main.ts +0 -10
- package/src/pages/AiGeneratorPage.vue +0 -273
- package/src/pages/AnalysisPage.vue +0 -60
- package/src/pages/ArtemisPage.vue +0 -72
- package/src/pages/AutomationPage.vue +0 -161
- package/src/pages/ConfigPage.vue +0 -146
- package/src/pages/GeneratorPage.vue +0 -104
- package/src/pages/ManualStepsPage.vue +0 -179
- package/src/script-generator/codegen.ts +0 -126
- package/src/script-generator/index.ts +0 -4
- package/src/script-generator/presets.ts +0 -37
- package/src/script-generator/step-options.ts +0 -52
- package/src/script-generator/types.ts +0 -27
- package/src/style.css +0 -4188
- package/src/types.ts +0 -167
- package/src/vite-env.d.ts +0 -1
- package/tsconfig.app.json +0 -8
- package/tsconfig.json +0 -11
- package/tsconfig.node.json +0 -16
- package/vite.config.ts +0 -28
- 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 +0 -418
|
@@ -1,1993 +0,0 @@
|
|
|
1
|
-
import { resolveReportSummary } from '../../src/appium-recorder/report-summary';
|
|
2
|
-
import { execFile } from 'node:child_process';
|
|
3
|
-
import { VariableScope, variableContext, resolveVariableStep } from './variables';
|
|
4
|
-
import { RandomValueGenerator } from './random-value';
|
|
5
|
-
import { ReplayStopwatches } from './stopwatch';
|
|
6
|
-
import { getPresetVariables } from './variable-store';
|
|
7
|
-
import { validateExtraction, validateVariables, type TestVariable } from '../../src/appium-recorder/variables';
|
|
8
|
-
import { captureHistoryFrames, readAppVersion } from './history-capture';
|
|
9
|
-
import { BoundedLoopTraversal } from './bounded-loop';
|
|
10
|
-
import { validateLoopSteps } from '../../src/appium-recorder/bounded-loop';
|
|
11
|
-
import { adbScreenshotBase64 } from './screenshot';
|
|
12
|
-
import { loadConfig } from '../config';
|
|
13
|
-
import { timestampReplayLog } from './replay-log';
|
|
14
|
-
import { checkImage } from './image-check';
|
|
15
|
-
import { recognizeDeviceScreen, resolveAiInvalidResultFallback } from './ai-recognition';
|
|
16
|
-
import { IMAGE_CHECK_MODES, type ImageCheckResult } from '../../src/appium-recorder/image-check';
|
|
17
|
-
import { formatStageLog } from '../../src/appium-recorder/stage-log';
|
|
18
|
-
import { openGalleryOnDevice } from './open-gallery';
|
|
19
|
-
import { stopAppOnDevice } from './stop-app';
|
|
20
|
-
import { DEFAULT_NODE_TIMEOUT_MS } from '../../src/appium-recorder/node-timeout';
|
|
21
|
-
import { startReplayVideo, type ReplayVideo } from './replay-video';
|
|
22
|
-
import { ConditionTimeoutError, AppiumServiceError } from './condition-timeout';
|
|
23
|
-
import { AppiumRequestTimeoutError, remainingElementDeadlineMs, timedAppiumFetch, withElementDeadline } from './request-timeout';
|
|
24
|
-
import { textClickSelector } from '../../src/appium-recorder/text-click';
|
|
25
|
-
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
26
|
-
import { mkdir, writeFile } from 'node:fs/promises';
|
|
27
|
-
import { join } from 'node:path';
|
|
28
|
-
import { linkedScriptSnapshot, type AppiumRecordedScriptRecord, type AppiumRecordedStepRecord } from './repository';
|
|
29
|
-
import { appDataPath } from '../paths';
|
|
30
|
-
import { ensureAndroidSdkAvailable, getAdbCommand } from '../android-sdk';
|
|
31
|
-
import { createAppiumReplayReport, type AppiumReplayFrame, type AppiumReplayVisualCheck } from './report';
|
|
32
|
-
import { startManagedAppiumServer, stopManagedUiAutomator, usesManagedAppiumServer } from './managed-appium';
|
|
33
|
-
import { compareVisualChangeFrames, type VisualChangeRegion } from './visual-change';
|
|
34
|
-
import { longPressMode, validateLongPress } from '../../src/appium-recorder/long-press';
|
|
35
|
-
import { defaultFlowKind, flowBranchLabel } from '../../src/appium-recorder/flow-labels';
|
|
36
|
-
import { isNativeStateCondition, nativeControlName, matchesNativeControl, parseNativeBoolean } from '../../src/appium-recorder/native-control-state';
|
|
37
|
-
import { findHierarchyBounds, readFreshWindowHierarchy } from './tree-dump';
|
|
38
|
-
|
|
39
|
-
type AppiumSessionResponse = {
|
|
40
|
-
value?: {
|
|
41
|
-
sessionId?: string;
|
|
42
|
-
capabilities?: unknown;
|
|
43
|
-
};
|
|
44
|
-
sessionId?: string;
|
|
45
|
-
};
|
|
46
|
-
|
|
47
|
-
type AppiumElementResponse = {
|
|
48
|
-
value?: Record<string, string>;
|
|
49
|
-
};
|
|
50
|
-
|
|
51
|
-
type AppiumValueResponse<T> = {
|
|
52
|
-
value?: T;
|
|
53
|
-
};
|
|
54
|
-
|
|
55
|
-
const ELEMENT_KEY = 'element-6066-11e4-a52e-4f735466cecf';
|
|
56
|
-
const UIAUTOMATOR_IDLE_TIMEOUT_MS = 0;
|
|
57
|
-
const MIN_ELEMENT_ATTEMPT_BUDGET_MS = 100;
|
|
58
|
-
const configuredAppiumServerUrl = () => (process.env.APPIUM_SERVER_URL || 'http://127.0.0.1:4723').replace(/\/+$/, '');
|
|
59
|
-
|
|
60
|
-
class ReplayStoppedError extends Error {
|
|
61
|
-
constructor() {
|
|
62
|
-
super('用户手动终止');
|
|
63
|
-
this.name = 'ReplayStoppedError';
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
type PendingVisualChangeCheck = {
|
|
68
|
-
step: AppiumRecordedStepRecord;
|
|
69
|
-
nodeNumber: number;
|
|
70
|
-
scriptName: string;
|
|
71
|
-
frameStart: number;
|
|
72
|
-
endFrameStart: number;
|
|
73
|
-
};
|
|
74
|
-
|
|
75
|
-
const replayContext = new AsyncLocalStorage<{
|
|
76
|
-
randomValues: RandomValueGenerator;
|
|
77
|
-
stopwatches: ReplayStopwatches;
|
|
78
|
-
signal?: AbortSignal;
|
|
79
|
-
appiumLog: (line: string) => void;
|
|
80
|
-
serverUrl: string;
|
|
81
|
-
deviceId: string;
|
|
82
|
-
scripts: Map<string, AppiumRecordedScriptRecord>;
|
|
83
|
-
frames: AppiumReplayFrame[];
|
|
84
|
-
screenshotReport: boolean;
|
|
85
|
-
visualCaptureNodes: Set<string>;
|
|
86
|
-
historyEvents: AppiumReplayFrame[];
|
|
87
|
-
visualChecks: AppiumReplayVisualCheck[];
|
|
88
|
-
imageChecks: Array<ImageCheckResult & { nodeId: string; nodeNumber: number; nodeLabel: string; scriptName: string; settings: string }>;
|
|
89
|
-
pendingVisualChecks: PendingVisualChangeCheck[];
|
|
90
|
-
visualStartOffsets: Map<string, number>;
|
|
91
|
-
softFailureCount: number;
|
|
92
|
-
flowEnded?: boolean;
|
|
93
|
-
selectVideoScript?: (id: string, name: string, force?: boolean) => Promise<void>;
|
|
94
|
-
sessionId?: string;
|
|
95
|
-
}>();
|
|
96
|
-
|
|
97
|
-
const appiumServerUrl = () => replayContext.getStore()?.serverUrl || configuredAppiumServerUrl();
|
|
98
|
-
|
|
99
|
-
function isReplayStopped(error?: unknown) {
|
|
100
|
-
return error instanceof ReplayStoppedError || replayContext.getStore()?.signal?.aborted === true;
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
function throwIfReplayStopped(error?: unknown) {
|
|
104
|
-
if (isReplayStopped(error)) throw new ReplayStoppedError();
|
|
105
|
-
// 驱动失去响应不是“元素不存在”,不能被备用定位或可选步骤吞掉。
|
|
106
|
-
if (error instanceof AppiumRequestTimeoutError || error instanceof AppiumServiceError) throw error;
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
function errorDetail(error: unknown) {
|
|
110
|
-
if (!(error instanceof Error)) return String(error || '未知错误');
|
|
111
|
-
const cause = error.cause;
|
|
112
|
-
if (cause instanceof Error && cause.message && cause.message !== error.message) {
|
|
113
|
-
return `${error.message}:${cause.message}`;
|
|
114
|
-
}
|
|
115
|
-
return error.message;
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
function isTimeoutError(error: unknown) {
|
|
119
|
-
const detail = errorDetail(error).toLowerCase();
|
|
120
|
-
return detail.includes('timeout') || detail.includes('timed out');
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
function isStaleElementError(error: unknown) {
|
|
124
|
-
const detail = errorDetail(error);
|
|
125
|
-
return detail.includes('stale element reference') || detail.includes('does not exist in DOM anymore');
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
function wait(ms: number) {
|
|
129
|
-
const signal = replayContext.getStore()?.signal;
|
|
130
|
-
if (!signal) return new Promise<void>((resolve) => setTimeout(resolve, ms));
|
|
131
|
-
throwIfReplayStopped();
|
|
132
|
-
return new Promise<void>((resolve, reject) => {
|
|
133
|
-
const onAbort = () => {
|
|
134
|
-
clearTimeout(timer);
|
|
135
|
-
reject(new ReplayStoppedError());
|
|
136
|
-
};
|
|
137
|
-
const timer = setTimeout(() => {
|
|
138
|
-
signal.removeEventListener('abort', onAbort);
|
|
139
|
-
resolve();
|
|
140
|
-
}, ms);
|
|
141
|
-
signal.addEventListener('abort', onAbort, { once: true });
|
|
142
|
-
});
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
function normalizeTextForContains(value: string) {
|
|
146
|
-
return value.replace(/\s+/g, ' ').trim();
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
function adbTap(deviceId: string, x: number, y: number) {
|
|
150
|
-
throwIfReplayStopped();
|
|
151
|
-
return new Promise<void>((resolve, reject) => {
|
|
152
|
-
execFile(getAdbCommand(), ['-s', deviceId, 'shell', 'input', 'tap', String(Math.round(x)), String(Math.round(y))], { timeout: 10000, signal: replayContext.getStore()?.signal }, (error, _stdout, stderr) => {
|
|
153
|
-
if (error) {
|
|
154
|
-
reject(new Error(stderr || error.message));
|
|
155
|
-
return;
|
|
156
|
-
}
|
|
157
|
-
resolve();
|
|
158
|
-
});
|
|
159
|
-
});
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
function adbKey(deviceId: string, keyCode: number) {
|
|
163
|
-
throwIfReplayStopped();
|
|
164
|
-
return new Promise<void>((resolve, reject) => {
|
|
165
|
-
execFile(getAdbCommand(), ['-s', deviceId, 'shell', 'input', 'keyevent', String(Math.round(keyCode))], { timeout: 10000, signal: replayContext.getStore()?.signal }, (error, _stdout, stderr) => {
|
|
166
|
-
if (error) {
|
|
167
|
-
reject(new Error(stderr || error.message));
|
|
168
|
-
return;
|
|
169
|
-
}
|
|
170
|
-
resolve();
|
|
171
|
-
});
|
|
172
|
-
});
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
export function launchAppOnDevice(deviceId: string, packageName: string, signal = replayContext.getStore()?.signal) {
|
|
176
|
-
signal?.throwIfAborted();
|
|
177
|
-
if (!packageName) return Promise.reject(new Error('启动 APP 缺少包名'));
|
|
178
|
-
return new Promise<void>((resolve, reject) => {
|
|
179
|
-
execFile(getAdbCommand(), [
|
|
180
|
-
'-s',
|
|
181
|
-
deviceId,
|
|
182
|
-
'shell',
|
|
183
|
-
'monkey',
|
|
184
|
-
'-p',
|
|
185
|
-
packageName,
|
|
186
|
-
'-c',
|
|
187
|
-
'android.intent.category.LAUNCHER',
|
|
188
|
-
'1',
|
|
189
|
-
], { maxBuffer: 4 * 1024 * 1024, timeout: 30000, signal }, (error, stdout, stderr) => {
|
|
190
|
-
const output = `${stdout || ''}\n${stderr || ''}`.trim();
|
|
191
|
-
if (error || /no activities found|monkey aborted/i.test(output)) {
|
|
192
|
-
reject(new Error(output || error?.message || `ADB 启动 ${packageName} 失败`));
|
|
193
|
-
return;
|
|
194
|
-
}
|
|
195
|
-
resolve();
|
|
196
|
-
});
|
|
197
|
-
});
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
export function clearAppDataOnDevice(deviceId: string, packageName: string, signal = replayContext.getStore()?.signal) {
|
|
201
|
-
signal?.throwIfAborted();
|
|
202
|
-
if (!packageName) return Promise.reject(new Error('清理 App 缓存缺少包名'));
|
|
203
|
-
return new Promise<void>((resolve, reject) => {
|
|
204
|
-
execFile(getAdbCommand(), [
|
|
205
|
-
'-s',
|
|
206
|
-
deviceId,
|
|
207
|
-
'shell',
|
|
208
|
-
'pm',
|
|
209
|
-
'clear',
|
|
210
|
-
packageName,
|
|
211
|
-
], { maxBuffer: 4 * 1024 * 1024, timeout: 30000, signal }, (error, stdout, stderr) => {
|
|
212
|
-
const output = `${stdout || ''}\n${stderr || ''}`.trim();
|
|
213
|
-
if (error || !/^success$/im.test(output)) {
|
|
214
|
-
reject(new Error(output || error?.message || `ADB 清理 ${packageName} 失败`));
|
|
215
|
-
return;
|
|
216
|
-
}
|
|
217
|
-
resolve();
|
|
218
|
-
});
|
|
219
|
-
});
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
function adbSwipe(deviceId: string, step: Required<AppiumRecordedStepRecord>['swipe']) {
|
|
223
|
-
throwIfReplayStopped();
|
|
224
|
-
return new Promise<void>((resolve, reject) => {
|
|
225
|
-
execFile(getAdbCommand(), [
|
|
226
|
-
'-s',
|
|
227
|
-
deviceId,
|
|
228
|
-
'shell',
|
|
229
|
-
'input',
|
|
230
|
-
'swipe',
|
|
231
|
-
String(Math.round(step.startX)),
|
|
232
|
-
String(Math.round(step.startY)),
|
|
233
|
-
String(Math.round(step.endX)),
|
|
234
|
-
String(Math.round(step.endY)),
|
|
235
|
-
String(Math.round(step.duration)),
|
|
236
|
-
], { timeout: Math.max(10000, step.duration + 5000), signal: replayContext.getStore()?.signal }, (error, _stdout, stderr) => {
|
|
237
|
-
if (error) {
|
|
238
|
-
reject(new Error(stderr || error.message));
|
|
239
|
-
return;
|
|
240
|
-
}
|
|
241
|
-
resolve();
|
|
242
|
-
});
|
|
243
|
-
});
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
function adbText(deviceId: string, args: string[], strict = false) {
|
|
247
|
-
return new Promise<string>((resolve, reject) => {
|
|
248
|
-
execFile(getAdbCommand(), ['-s', deviceId, ...args], { maxBuffer: 4 * 1024 * 1024, timeout: 10000, signal: replayContext.getStore()?.signal }, (error, stdout, stderr) => {
|
|
249
|
-
if (strict && error) { reject(new AppiumServiceError(`读取设备状态失败:${stderr || error.message}`)); return; }
|
|
250
|
-
resolve((stdout || stderr || '').trim());
|
|
251
|
-
});
|
|
252
|
-
});
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
async function getCurrentActivity(deviceId: string) {
|
|
256
|
-
const output = await adbText(deviceId, ['shell', 'dumpsys', 'activity', 'activities'], true);
|
|
257
|
-
const resumedLine = output
|
|
258
|
-
.split(/\r?\n/)
|
|
259
|
-
.find((line) => /(?:topResumedActivity|ResumedActivity|mResumedActivity)/.test(line));
|
|
260
|
-
return resumedLine?.match(/\s([\w.$]+\/[\w.$]+)\s/)?.[1] || '';
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
async function isAppInForeground(deviceId: string, packageName: string) {
|
|
264
|
-
if (!packageName) return false;
|
|
265
|
-
const currentActivity = await getCurrentActivity(deviceId);
|
|
266
|
-
return currentActivity.split('/')[0] === packageName;
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
async function waitForActivity(deviceId: string, step: AppiumRecordedStepRecord) {
|
|
270
|
-
const expectedActivity = step.value || '';
|
|
271
|
-
if (!expectedActivity) throw new Error(`${step.label} 缺少目标 Activity`);
|
|
272
|
-
const startedAt = Date.now();
|
|
273
|
-
const timeoutMs = step.timeoutMs ?? DEFAULT_NODE_TIMEOUT_MS;
|
|
274
|
-
let currentActivity = '';
|
|
275
|
-
while (Date.now() - startedAt <= timeoutMs) {
|
|
276
|
-
throwIfReplayStopped();
|
|
277
|
-
currentActivity = await getCurrentActivity(deviceId);
|
|
278
|
-
if (currentActivity === expectedActivity) return;
|
|
279
|
-
await wait(500);
|
|
280
|
-
}
|
|
281
|
-
throw new ConditionTimeoutError(`${step.label} 等待超时,当前 Activity:${currentActivity || '-'}`);
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
async function appendSettingsDiagnostics(lines: string[], deviceId: string) {
|
|
285
|
-
const packageInfo = await adbText(deviceId, ['shell', 'dumpsys', 'package', 'io.appium.settings']);
|
|
286
|
-
const launchInfo = await adbText(deviceId, ['shell', 'am', 'start-activity', '-n', 'io.appium.settings/.Settings', '-a', 'android.intent.action.MAIN', '-c', 'android.intent.category.LAUNCHER']);
|
|
287
|
-
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
288
|
-
const serviceInfo = await adbText(deviceId, ['shell', 'dumpsys', 'activity', 'services', 'io.appium.settings']);
|
|
289
|
-
lines.push('Appium Settings 诊断:');
|
|
290
|
-
lines.push(`- 安装状态:${packageInfo.includes('Package [io.appium.settings]') ? '已安装' : '未检测到 io.appium.settings'}`);
|
|
291
|
-
lines.push(`- 手动启动:${launchInfo || '-'}`);
|
|
292
|
-
lines.push(`- 服务状态:${serviceInfo || '-'}`);
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
function appendAndroidSdkDiagnostics(lines: string[]) {
|
|
296
|
-
lines.push('Android SDK 环境变量未配置:');
|
|
297
|
-
lines.push('- 可在本项目“参数配置 > 运行配置”中指定 Android SDK 路径。');
|
|
298
|
-
lines.push('- Windows 常见 SDK 路径:%LOCALAPPDATA%\\Android\\Sdk');
|
|
299
|
-
lines.push('- PowerShell 设置示例:');
|
|
300
|
-
lines.push(' [Environment]::SetEnvironmentVariable("ANDROID_HOME", "$env:LOCALAPPDATA\\Android\\Sdk", "User")');
|
|
301
|
-
lines.push(' [Environment]::SetEnvironmentVariable("ANDROID_SDK_ROOT", "$env:LOCALAPPDATA\\Android\\Sdk", "User")');
|
|
302
|
-
lines.push(' [Environment]::SetEnvironmentVariable("Path", $env:Path + ";$env:LOCALAPPDATA\\Android\\Sdk\\platform-tools", "User")');
|
|
303
|
-
lines.push('- Appium 是独立进程时不会继承网页中后设置的环境变量;设置后请重新打开终端,并重启 appium 服务。');
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
async function appiumRequest<T>(
|
|
307
|
-
path: string,
|
|
308
|
-
init?: RequestInit,
|
|
309
|
-
options?: { ignoreAbort?: boolean; timeoutMs?: number },
|
|
310
|
-
) {
|
|
311
|
-
const context = replayContext.getStore();
|
|
312
|
-
const effectivePath = context?.sessionId
|
|
313
|
-
? path.replace(/^\/session\/[^/]+/, `/session/${context.sessionId}`)
|
|
314
|
-
: path;
|
|
315
|
-
const requestUrl = `${appiumServerUrl()}${effectivePath}`;
|
|
316
|
-
const method = init?.method || 'GET';
|
|
317
|
-
const startedAt = Date.now();
|
|
318
|
-
if (!options?.ignoreAbort) throwIfReplayStopped();
|
|
319
|
-
context?.appiumLog(`[Appium] 请求:${method} ${effectivePath}`);
|
|
320
|
-
let response: Response;
|
|
321
|
-
let responseText: string;
|
|
322
|
-
try {
|
|
323
|
-
const result = await timedAppiumFetch(requestUrl, {
|
|
324
|
-
...init,
|
|
325
|
-
signal: options?.ignoreAbort ? undefined : (context?.signal && init?.signal
|
|
326
|
-
? AbortSignal.any([context.signal, init.signal]) : context?.signal || init?.signal),
|
|
327
|
-
headers: {
|
|
328
|
-
'Content-Type': 'application/json',
|
|
329
|
-
...(init?.headers || {}),
|
|
330
|
-
},
|
|
331
|
-
}, options?.timeoutMs ?? (effectivePath === '/session' && method === 'POST' ? 120000 : 30000));
|
|
332
|
-
response = result.response;
|
|
333
|
-
responseText = result.text;
|
|
334
|
-
} catch (error) {
|
|
335
|
-
if (isReplayStopped(error) && !options?.ignoreAbort) {
|
|
336
|
-
context?.appiumLog(`[Appium] 取消:${method} ${effectivePath}`);
|
|
337
|
-
throw new ReplayStoppedError();
|
|
338
|
-
}
|
|
339
|
-
context?.appiumLog(`[Appium] 异常:${method} ${effectivePath}(${errorDetail(error)})`);
|
|
340
|
-
if (error instanceof AppiumRequestTimeoutError || error instanceof ConditionTimeoutError) throw error;
|
|
341
|
-
if (isTimeoutError(error)) {
|
|
342
|
-
throw new AppiumServiceError(`Appium 请求超时 ${requestUrl},${errorDetail(error)}`);
|
|
343
|
-
}
|
|
344
|
-
throw new AppiumServiceError(`无法连接 Appium 服务 ${requestUrl},${errorDetail(error)}`);
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
context?.appiumLog(`[Appium] 响应:HTTP ${response.status} ${method} ${effectivePath}(${Date.now() - startedAt}ms)`);
|
|
348
|
-
const payload = (() => {
|
|
349
|
-
try {
|
|
350
|
-
return responseText ? JSON.parse(responseText) : {};
|
|
351
|
-
} catch {
|
|
352
|
-
return {};
|
|
353
|
-
}
|
|
354
|
-
})() as T & {
|
|
355
|
-
value?: { error?: string; message?: string; stacktrace?: string };
|
|
356
|
-
error?: string;
|
|
357
|
-
message?: string;
|
|
358
|
-
stacktrace?: string;
|
|
359
|
-
};
|
|
360
|
-
if (!response.ok) {
|
|
361
|
-
const detail = [
|
|
362
|
-
payload.value?.error || payload.error ? `错误类型:${payload.value?.error || payload.error}` : '',
|
|
363
|
-
payload.value?.message || payload.message ? `错误信息:${payload.value?.message || payload.message}` : '',
|
|
364
|
-
payload.value?.stacktrace || payload.stacktrace ? `堆栈信息:\n${payload.value?.stacktrace || payload.stacktrace}` : '',
|
|
365
|
-
responseText ? `原始响应:\n${responseText}` : '',
|
|
366
|
-
].filter(Boolean).join('\n');
|
|
367
|
-
const ErrorType = ['no such element', 'stale element reference'].includes(payload.value?.error || payload.error || '') ? Error : AppiumServiceError;
|
|
368
|
-
throw new ErrorType(`Appium ${method} ${effectivePath} 失败(HTTP ${response.status}):\n${detail || '未返回错误详情'}`);
|
|
369
|
-
}
|
|
370
|
-
return payload;
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
function appiumNodeRequest<T>(path: string, init?: RequestInit) {
|
|
374
|
-
return appiumRequest<T>(path, init, { timeoutMs: DEFAULT_NODE_TIMEOUT_MS });
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
function replayFrameSelector(step: AppiumRecordedStepRecord) {
|
|
378
|
-
if (step.type === 'textClick') return `${step.flow?.textMatch === 'exact' ? '精准匹配' : '模糊匹配'}:${step.value || ''}`;
|
|
379
|
-
const selector = step.selector;
|
|
380
|
-
if (!selector) return '-';
|
|
381
|
-
if (selector.strategy === 'bounds') return `bounds (${selector.centerX ?? '-'}, ${selector.centerY ?? '-'})`;
|
|
382
|
-
return `${selector.strategy} ${selector.value || ''}`.trim();
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
async function captureReplayFrame(
|
|
386
|
-
_sessionId: string,
|
|
387
|
-
step: AppiumRecordedStepRecord,
|
|
388
|
-
nodeNumber: number,
|
|
389
|
-
scriptName: string,
|
|
390
|
-
phase: AppiumReplayFrame['phase'],
|
|
391
|
-
status: string,
|
|
392
|
-
imageBase64?: string,
|
|
393
|
-
) {
|
|
394
|
-
const context = replayContext.getStore();
|
|
395
|
-
if (!context || !context.deviceId) return;
|
|
396
|
-
const capturedAt = new Date().toISOString();
|
|
397
|
-
// 执行记录独立于截图,设备截图失败不能让失败节点从统计中消失。
|
|
398
|
-
context.historyEvents.push({ sequence: context.historyEvents.length + 1, scriptName, nodeId: step.id,
|
|
399
|
-
nodeNumber, nodeLabel: step.label, nodeType: step.type, note: step.note || '',
|
|
400
|
-
selector: replayFrameSelector(step), phase, status, capturedAt, imageBase64: '' });
|
|
401
|
-
const appendFrame = (imageBase64: string) => {
|
|
402
|
-
context.frames.push({
|
|
403
|
-
sequence: context.frames.length + 1,
|
|
404
|
-
scriptName,
|
|
405
|
-
nodeId: step.id,
|
|
406
|
-
nodeNumber,
|
|
407
|
-
nodeLabel: step.label,
|
|
408
|
-
nodeType: step.type,
|
|
409
|
-
logContent: step.type === 'log' && phase === 'after' ? formatStageLog(resolveVariableStep(step)) : undefined,
|
|
410
|
-
note: step.note || '',
|
|
411
|
-
selector: replayFrameSelector(step),
|
|
412
|
-
phase,
|
|
413
|
-
status,
|
|
414
|
-
capturedAt,
|
|
415
|
-
imageBase64,
|
|
416
|
-
});
|
|
417
|
-
};
|
|
418
|
-
|
|
419
|
-
// 关闭报告截图时仍保留时间锚点;视觉比较所需的结束帧不能省略。
|
|
420
|
-
if (!context.screenshotReport && !(phase === 'after' && context.visualCaptureNodes.has(step.id))) {
|
|
421
|
-
appendFrame('');
|
|
422
|
-
return;
|
|
423
|
-
}
|
|
424
|
-
if (phase === 'stopped' && context.signal?.aborted) {
|
|
425
|
-
const previousFrame = context.frames.at(-1);
|
|
426
|
-
if (previousFrame) appendFrame(previousFrame.imageBase64);
|
|
427
|
-
return;
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
try {
|
|
431
|
-
// Report screenshots use ADB so a slow capture cannot block Appium's command queue.
|
|
432
|
-
appendFrame(imageBase64 || await adbScreenshotBase64(context.deviceId));
|
|
433
|
-
} catch (error) {
|
|
434
|
-
context.appiumLog(`[节点 ${nodeNumber}] 截图失败:${errorDetail(error)}`);
|
|
435
|
-
// 截图失败仍保留时间锚点,报告可定位到该节点的录像。
|
|
436
|
-
appendFrame('');
|
|
437
|
-
}
|
|
438
|
-
}
|
|
439
|
-
|
|
440
|
-
async function createSession(deviceId: string) {
|
|
441
|
-
const payload = await appiumRequest<AppiumSessionResponse>('/session', {
|
|
442
|
-
method: 'POST',
|
|
443
|
-
body: JSON.stringify({
|
|
444
|
-
capabilities: {
|
|
445
|
-
alwaysMatch: {
|
|
446
|
-
platformName: 'Android',
|
|
447
|
-
'appium:automationName': 'UiAutomator2',
|
|
448
|
-
'appium:udid': deviceId,
|
|
449
|
-
'appium:autoLaunch': false,
|
|
450
|
-
'appium:noReset': true,
|
|
451
|
-
// 实时画面、动画和频繁无障碍事件可能让 UiAutomator2 始终等不到界面空闲。
|
|
452
|
-
// 节点已有显式等待,因此关闭驱动内部空闲等待,避免元素查询和点击确认占住命令队列。
|
|
453
|
-
'appium:settings': { waitForIdleTimeout: UIAUTOMATOR_IDLE_TIMEOUT_MS },
|
|
454
|
-
// 托管进程由 finally 释放;外部服务保留回收期限,避免创建请求取消后遗留永久会话。
|
|
455
|
-
'appium:newCommandTimeout': usesManagedAppiumServer() ? 0 : 60,
|
|
456
|
-
'appium:skipDeviceInitialization': true,
|
|
457
|
-
'appium:ignoreHiddenApiPolicyError': true,
|
|
458
|
-
},
|
|
459
|
-
},
|
|
460
|
-
}),
|
|
461
|
-
});
|
|
462
|
-
const sessionId = payload.value?.sessionId || payload.sessionId || '';
|
|
463
|
-
if (!sessionId) throw new Error('Appium 未返回 sessionId');
|
|
464
|
-
return sessionId;
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
function isUiAutomationDisconnected(error: unknown) {
|
|
468
|
-
return errorDetail(error).includes('UiAutomation not connected');
|
|
469
|
-
}
|
|
470
|
-
|
|
471
|
-
async function resetUiAutomator2(deviceId: string) {
|
|
472
|
-
await adbText(deviceId, ['shell', 'pkill', '-f', 'com.android.commands.uiautomator.Launcher']);
|
|
473
|
-
await adbText(deviceId, ['shell', 'am', 'force-stop', 'io.appium.uiautomator2.server']);
|
|
474
|
-
await adbText(deviceId, ['shell', 'am', 'force-stop', 'io.appium.uiautomator2.server.test']);
|
|
475
|
-
await wait(800);
|
|
476
|
-
}
|
|
477
|
-
|
|
478
|
-
function adbHierarchyText(command: string, args: string[]) {
|
|
479
|
-
return new Promise<string>((resolve, reject) => {
|
|
480
|
-
execFile(command, args, {
|
|
481
|
-
maxBuffer: 20 * 1024 * 1024,
|
|
482
|
-
timeout: DEFAULT_NODE_TIMEOUT_MS,
|
|
483
|
-
signal: replayContext.getStore()?.signal,
|
|
484
|
-
}, (error, stdout, stderr) => {
|
|
485
|
-
if (error) reject(new Error(stderr || error.message));
|
|
486
|
-
else resolve(stdout);
|
|
487
|
-
});
|
|
488
|
-
});
|
|
489
|
-
}
|
|
490
|
-
|
|
491
|
-
async function recoverOptionalLookup(deviceId: string, sessionId: string, step: AppiumRecordedStepRecord) {
|
|
492
|
-
const context = replayContext.getStore();
|
|
493
|
-
context?.appiumLog(`[Appium] ${step.label} 查询超时,正在重建 UiAutomator2 会话并通过 ADB 组件树判断`);
|
|
494
|
-
await resetUiAutomator2(deviceId);
|
|
495
|
-
await appiumRequest(`/session/${sessionId}`, { method: 'DELETE' }, { ignoreAbort: true, timeoutMs: 1000 })
|
|
496
|
-
.catch(error => context?.appiumLog(`[Appium] 旧会话释放未及时返回:${errorDetail(error)}`));
|
|
497
|
-
|
|
498
|
-
let bounds: ReturnType<typeof findHierarchyBounds>;
|
|
499
|
-
try {
|
|
500
|
-
const xml = await readFreshWindowHierarchy(deviceId, getAdbCommand(), adbHierarchyText);
|
|
501
|
-
bounds = findHierarchyBounds(xml, [step.selector, ...(step.selectorChain || [])].filter(Boolean) as NonNullable<AppiumRecordedStepRecord['selector']>[]);
|
|
502
|
-
} catch (error) {
|
|
503
|
-
context?.appiumLog(`[ADB] 可选元素组件树检查失败,按未出现处理:${errorDetail(error)}`);
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
const replacementSessionId = await createSession(deviceId);
|
|
507
|
-
if (context) context.sessionId = replacementSessionId;
|
|
508
|
-
context?.appiumLog(`[Appium] UiAutomator2 会话已恢复:${replacementSessionId}`);
|
|
509
|
-
return bounds;
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
function toAppiumUsing(selector: NonNullable<AppiumRecordedStepRecord['selector']>) {
|
|
513
|
-
if (selector.strategy === 'accessibilityId') return { using: 'accessibility id', value: selector.value || '' };
|
|
514
|
-
if (selector.strategy === 'id') return { using: 'id', value: selector.value || '' };
|
|
515
|
-
if (selector.strategy === 'androidUiAutomator') return { using: '-android uiautomator', value: selector.value || '' };
|
|
516
|
-
if (selector.strategy === 'xpath') return { using: 'xpath', value: selector.value || '' };
|
|
517
|
-
throw new Error('需要使用 bounds 坐标执行');
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
async function findElementBySelector(
|
|
521
|
-
sessionId: string,
|
|
522
|
-
selector: NonNullable<AppiumRecordedStepRecord['selector']>,
|
|
523
|
-
parentElementId?: string,
|
|
524
|
-
) {
|
|
525
|
-
const using = toAppiumUsing(selector);
|
|
526
|
-
const path = parentElementId
|
|
527
|
-
? `/session/${sessionId}/element/${parentElementId}/element`
|
|
528
|
-
: `/session/${sessionId}/element`;
|
|
529
|
-
const payload = await appiumRequest<AppiumElementResponse>(path, {
|
|
530
|
-
method: 'POST',
|
|
531
|
-
body: JSON.stringify(using),
|
|
532
|
-
});
|
|
533
|
-
const elementId = payload.value?.[ELEMENT_KEY] || payload.value?.ELEMENT || '';
|
|
534
|
-
if (!elementId) throw new Error('未找到元素');
|
|
535
|
-
return elementId;
|
|
536
|
-
}
|
|
537
|
-
|
|
538
|
-
async function findElement(sessionId: string, step: AppiumRecordedStepRecord, timeoutMs = step.timeoutMs ?? DEFAULT_NODE_TIMEOUT_MS) {
|
|
539
|
-
return withElementDeadline(timeoutMs, () => findElementWithinDeadline(sessionId, step));
|
|
540
|
-
}
|
|
541
|
-
|
|
542
|
-
async function findElementWithinDeadline(sessionId: string, step: AppiumRecordedStepRecord) {
|
|
543
|
-
if (!step.selector) throw new Error(`${step.label} 缺少 selector`);
|
|
544
|
-
const attempts: string[] = [];
|
|
545
|
-
let requestAttempted = false;
|
|
546
|
-
let lastError: unknown;
|
|
547
|
-
|
|
548
|
-
if (step.contextSelector) {
|
|
549
|
-
try {
|
|
550
|
-
attempts.push(`context ${step.contextSelector.strategy} ${step.contextSelector.value || ''} -> ${step.selector.strategy} ${step.selector.value || ''}`);
|
|
551
|
-
requestAttempted = true;
|
|
552
|
-
const parentId = await findElementBySelector(sessionId, step.contextSelector);
|
|
553
|
-
if (remainingElementDeadlineMs() < MIN_ELEMENT_ATTEMPT_BUDGET_MS) throw new Error('元素定位时间已用完');
|
|
554
|
-
return await findElementBySelector(sessionId, step.selector, parentId);
|
|
555
|
-
} catch (error) {
|
|
556
|
-
throwIfReplayStopped(error);
|
|
557
|
-
if (error instanceof ConditionTimeoutError) throw error;
|
|
558
|
-
lastError = error;
|
|
559
|
-
// Continue with the fallback chain below.
|
|
560
|
-
}
|
|
561
|
-
}
|
|
562
|
-
|
|
563
|
-
// 唯一原生定位优先;非唯一元素仍保留父级与备用 XPath 的精确匹配。
|
|
564
|
-
const preferPrimary = step.selector.unique === true && ['id', 'accessibilityId'].includes(step.selector.strategy);
|
|
565
|
-
const selectors = [...(preferPrimary ? [step.selector] : []), ...(step.selectorChain || []), ...(!preferPrimary ? [step.selector] : [])]
|
|
566
|
-
.filter((selector, index, list) => list.findIndex(item => item.strategy === selector.strategy && item.value === selector.value) === index);
|
|
567
|
-
for (const selector of selectors) {
|
|
568
|
-
if (requestAttempted && remainingElementDeadlineMs() < MIN_ELEMENT_ATTEMPT_BUDGET_MS) break;
|
|
569
|
-
try {
|
|
570
|
-
attempts.push(`${selector.strategy} ${selector.value || ''}`);
|
|
571
|
-
requestAttempted = true;
|
|
572
|
-
return await findElementBySelector(sessionId, selector);
|
|
573
|
-
} catch (error) {
|
|
574
|
-
throwIfReplayStopped(error);
|
|
575
|
-
if (error instanceof ConditionTimeoutError) throw error;
|
|
576
|
-
lastError = error;
|
|
577
|
-
}
|
|
578
|
-
}
|
|
579
|
-
throw new Error(`${step.label} 未找到元素;尝试过:${attempts.filter(Boolean).join(';') || '-'};${errorDetail(lastError)}`);
|
|
580
|
-
}
|
|
581
|
-
|
|
582
|
-
// 图像判断不能使用通用定位的“第一个匹配”及坐标回退,父级和子级均须唯一。
|
|
583
|
-
async function imageCheckRegion(sessionId: string, step: AppiumRecordedStepRecord) {
|
|
584
|
-
async function unique(selector: AppiumRecordedStepRecord['selector'], parent?: string) {
|
|
585
|
-
if (!selector || selector.strategy === 'bounds') throw new Error('缺少可唯一定位的组件信息');
|
|
586
|
-
const path = parent ? `/session/${sessionId}/element/${parent}/elements` : `/session/${sessionId}/elements`;
|
|
587
|
-
const payload = await appiumNodeRequest<AppiumValueResponse<Array<Record<string, string>>>>(path, {
|
|
588
|
-
method: 'POST', body: JSON.stringify(toAppiumUsing(selector)),
|
|
589
|
-
});
|
|
590
|
-
if (payload.value?.length !== 1) throw new Error(`目标组件匹配 ${payload.value?.length || 0} 个,请限定父级或条目文字`);
|
|
591
|
-
const id = payload.value[0]?.[ELEMENT_KEY] || payload.value[0]?.ELEMENT;
|
|
592
|
-
if (!id) throw new Error('目标组件缺少元素标识');
|
|
593
|
-
return id;
|
|
594
|
-
}
|
|
595
|
-
const parent = step.contextSelector ? await unique(step.contextSelector) : undefined;
|
|
596
|
-
const id = await unique(step.selector, parent);
|
|
597
|
-
const rect = await appiumNodeRequest<AppiumValueResponse<VisualChangeRegion>>(`/session/${sessionId}/element/${id}/rect`);
|
|
598
|
-
if (!rect.value) throw new Error('无法读取组件实时区域');
|
|
599
|
-
return rect.value;
|
|
600
|
-
}
|
|
601
|
-
|
|
602
|
-
function hasUsableFallbackCoordinates(step: AppiumRecordedStepRecord): step is AppiumRecordedStepRecord & {
|
|
603
|
-
fallback: { strategy: 'bounds'; centerX: number; centerY: number };
|
|
604
|
-
} {
|
|
605
|
-
return step.fallback?.strategy === 'bounds'
|
|
606
|
-
&& Number.isFinite(step.fallback.centerX)
|
|
607
|
-
&& Number.isFinite(step.fallback.centerY)
|
|
608
|
-
&& (Number(step.fallback.centerX) !== 0 || Number(step.fallback.centerY) !== 0);
|
|
609
|
-
}
|
|
610
|
-
|
|
611
|
-
async function tapFallback(deviceId: string, step: AppiumRecordedStepRecord) {
|
|
612
|
-
if (!hasUsableFallbackCoordinates(step)) {
|
|
613
|
-
throw new Error(`${step.label} 没有可用点击坐标`);
|
|
614
|
-
}
|
|
615
|
-
await adbTap(deviceId, Number(step.fallback.centerX), Number(step.fallback.centerY));
|
|
616
|
-
}
|
|
617
|
-
|
|
618
|
-
async function tapLocatedElement(
|
|
619
|
-
sessionId: string,
|
|
620
|
-
deviceId: string,
|
|
621
|
-
elementId: string,
|
|
622
|
-
step?: AppiumRecordedStepRecord,
|
|
623
|
-
) {
|
|
624
|
-
try {
|
|
625
|
-
const payload = await appiumNodeRequest<AppiumValueResponse<VisualChangeRegion>>(`/session/${sessionId}/element/${elementId}/rect`);
|
|
626
|
-
const rect = payload.value;
|
|
627
|
-
if (rect && [rect.x, rect.y, rect.width, rect.height].every(Number.isFinite) && rect.width > 0 && rect.height > 0) {
|
|
628
|
-
await adbTap(deviceId, rect.x + rect.width / 2, rect.y + rect.height / 2);
|
|
629
|
-
return;
|
|
630
|
-
}
|
|
631
|
-
} catch (error) {
|
|
632
|
-
throwIfReplayStopped(error);
|
|
633
|
-
// 普通点击的外层会重新定位一次,避免列表刷新后使用已失效元素的旧位置。
|
|
634
|
-
if (isStaleElementError(error)) throw error;
|
|
635
|
-
}
|
|
636
|
-
if (step) {
|
|
637
|
-
await tapFallback(deviceId, step);
|
|
638
|
-
return;
|
|
639
|
-
}
|
|
640
|
-
throw new Error('无法读取目标元素的实时点击区域');
|
|
641
|
-
}
|
|
642
|
-
|
|
643
|
-
async function longPressLocatedElement(
|
|
644
|
-
sessionId: string,
|
|
645
|
-
deviceId: string,
|
|
646
|
-
elementId: string,
|
|
647
|
-
step: AppiumRecordedStepRecord,
|
|
648
|
-
duration: number,
|
|
649
|
-
) {
|
|
650
|
-
try {
|
|
651
|
-
const payload = await appiumNodeRequest<AppiumValueResponse<VisualChangeRegion>>(`/session/${sessionId}/element/${elementId}/rect`);
|
|
652
|
-
const rect = payload.value;
|
|
653
|
-
if (rect && [rect.x, rect.y, rect.width, rect.height].every(Number.isFinite) && rect.width > 0 && rect.height > 0) {
|
|
654
|
-
const x = rect.x + rect.width / 2;
|
|
655
|
-
const y = rect.y + rect.height / 2;
|
|
656
|
-
await adbSwipe(deviceId, { startX: x, startY: y, endX: x, endY: y, duration });
|
|
657
|
-
return;
|
|
658
|
-
}
|
|
659
|
-
} catch (error) {
|
|
660
|
-
throwIfReplayStopped(error);
|
|
661
|
-
if (isStaleElementError(error)) throw error;
|
|
662
|
-
}
|
|
663
|
-
if (!hasUsableFallbackCoordinates(step)) {
|
|
664
|
-
throw new Error('无法读取目标元素的实时长按区域');
|
|
665
|
-
}
|
|
666
|
-
const x = Number(step.fallback.centerX);
|
|
667
|
-
const y = Number(step.fallback.centerY);
|
|
668
|
-
await adbSwipe(deviceId, { startX: x, startY: y, endX: x, endY: y, duration });
|
|
669
|
-
}
|
|
670
|
-
|
|
671
|
-
async function waitForElement(sessionId: string, step: AppiumRecordedStepRecord) {
|
|
672
|
-
const startedAt = Date.now();
|
|
673
|
-
const timeoutMs = step.timeoutMs ?? DEFAULT_NODE_TIMEOUT_MS;
|
|
674
|
-
let lastError: unknown;
|
|
675
|
-
let attempted = false;
|
|
676
|
-
while (true) {
|
|
677
|
-
const remaining = timeoutMs - (Date.now() - startedAt);
|
|
678
|
-
if (remaining <= 0 || (attempted && remaining < MIN_ELEMENT_ATTEMPT_BUDGET_MS)) break;
|
|
679
|
-
attempted = true;
|
|
680
|
-
try {
|
|
681
|
-
return await findElement(sessionId, step, remaining);
|
|
682
|
-
} catch (error) {
|
|
683
|
-
throwIfReplayStopped(error);
|
|
684
|
-
lastError = error;
|
|
685
|
-
const pauseMs = Math.min(500, timeoutMs - (Date.now() - startedAt));
|
|
686
|
-
if (pauseMs > 0) await wait(pauseMs);
|
|
687
|
-
}
|
|
688
|
-
}
|
|
689
|
-
throw new ConditionTimeoutError(`${step.label} 等待元素超时(${timeoutMs}ms):${errorDetail(lastError)}`);
|
|
690
|
-
}
|
|
691
|
-
|
|
692
|
-
async function findOptionalElement(sessionId: string, step: AppiumRecordedStepRecord) {
|
|
693
|
-
const startedAt = Date.now();
|
|
694
|
-
const timeoutMs = step.timeoutMs ?? DEFAULT_NODE_TIMEOUT_MS;
|
|
695
|
-
let attempted = false;
|
|
696
|
-
while (true) {
|
|
697
|
-
const remaining = timeoutMs - (Date.now() - startedAt);
|
|
698
|
-
if (remaining <= 0 || (attempted && remaining < MIN_ELEMENT_ATTEMPT_BUDGET_MS)) return '';
|
|
699
|
-
attempted = true;
|
|
700
|
-
try {
|
|
701
|
-
return await findElement(sessionId, step, remaining);
|
|
702
|
-
} catch (error) {
|
|
703
|
-
throwIfReplayStopped(error);
|
|
704
|
-
const pauseMs = Math.min(250, timeoutMs - (Date.now() - startedAt));
|
|
705
|
-
if (pauseMs > 0) await wait(pauseMs);
|
|
706
|
-
}
|
|
707
|
-
}
|
|
708
|
-
}
|
|
709
|
-
|
|
710
|
-
async function findOptionalElementWithRecovery(
|
|
711
|
-
sessionId: string,
|
|
712
|
-
deviceId: string,
|
|
713
|
-
step: AppiumRecordedStepRecord,
|
|
714
|
-
) {
|
|
715
|
-
try {
|
|
716
|
-
return { elementId: await findOptionalElement(sessionId, step), recovered: false as const };
|
|
717
|
-
} catch (error) {
|
|
718
|
-
if (!(error instanceof AppiumRequestTimeoutError)) throw error;
|
|
719
|
-
return { bounds: await recoverOptionalLookup(deviceId, sessionId, step), recovered: true as const };
|
|
720
|
-
}
|
|
721
|
-
}
|
|
722
|
-
|
|
723
|
-
async function waitForElementGone(sessionId: string, step: AppiumRecordedStepRecord) {
|
|
724
|
-
const startedAt = Date.now();
|
|
725
|
-
const timeoutMs = step.timeoutMs ?? DEFAULT_NODE_TIMEOUT_MS;
|
|
726
|
-
let attempted = false;
|
|
727
|
-
while (true) {
|
|
728
|
-
const remaining = timeoutMs - (Date.now() - startedAt);
|
|
729
|
-
if (remaining <= 0 || (attempted && remaining < MIN_ELEMENT_ATTEMPT_BUDGET_MS)) break;
|
|
730
|
-
attempted = true;
|
|
731
|
-
try {
|
|
732
|
-
await findElement(sessionId, step, remaining);
|
|
733
|
-
} catch (error) {
|
|
734
|
-
throwIfReplayStopped(error);
|
|
735
|
-
if (error instanceof ConditionTimeoutError) throw error;
|
|
736
|
-
return;
|
|
737
|
-
}
|
|
738
|
-
const pauseMs = Math.min(500, timeoutMs - (Date.now() - startedAt));
|
|
739
|
-
if (pauseMs > 0) await wait(pauseMs);
|
|
740
|
-
}
|
|
741
|
-
throw new ConditionTimeoutError(`${step.label} 等待消失超时`);
|
|
742
|
-
}
|
|
743
|
-
|
|
744
|
-
async function saveScreenshot(deviceId: string) {
|
|
745
|
-
if (variableContext.getStore()?.privacy.enabled) return;
|
|
746
|
-
const dir = appDataPath('.midscene-app', 'screenshots');
|
|
747
|
-
await mkdir(dir, { recursive: true });
|
|
748
|
-
const file = join(dir, `appium-${Date.now()}.png`);
|
|
749
|
-
await writeFile(file, Buffer.from(await adbScreenshotBase64(deviceId), 'base64'));
|
|
750
|
-
}
|
|
751
|
-
|
|
752
|
-
type RunStepMeta = {
|
|
753
|
-
onModelOutput?: (content: string) => void;
|
|
754
|
-
onAiAnalysisStart?: () => void;
|
|
755
|
-
onAiProgress?: (message: string) => void;
|
|
756
|
-
nodeNumber: number;
|
|
757
|
-
scriptName: string;
|
|
758
|
-
frameStart?: number;
|
|
759
|
-
};
|
|
760
|
-
|
|
761
|
-
type RunStepResult = string | {
|
|
762
|
-
message?: string;
|
|
763
|
-
softFailed?: boolean;
|
|
764
|
-
};
|
|
765
|
-
|
|
766
|
-
function completedStepStatus(step: AppiumRecordedStepRecord, softFailed: boolean) {
|
|
767
|
-
if (step.type === 'endFlow') return '流程已结束';
|
|
768
|
-
if (step.type === 'visualChange') {
|
|
769
|
-
if (step.visualChange?.role === 'start') return '已记录基准帧';
|
|
770
|
-
if (step.visualChange?.role === 'end') return '已记录对比帧';
|
|
771
|
-
}
|
|
772
|
-
return softFailed ? '视觉变化未达预期' : '成功';
|
|
773
|
-
}
|
|
774
|
-
|
|
775
|
-
function visualChangeNumber(value: unknown, fallback: number, min: number, max = Number.POSITIVE_INFINITY) {
|
|
776
|
-
const number = Number(value);
|
|
777
|
-
if (!Number.isFinite(number)) return fallback;
|
|
778
|
-
return Math.min(max, Math.max(min, number));
|
|
779
|
-
}
|
|
780
|
-
|
|
781
|
-
function visualChangeRegion(step: AppiumRecordedStepRecord): VisualChangeRegion {
|
|
782
|
-
const config = step.visualChange;
|
|
783
|
-
if (!config?.region) throw new Error(`${step.label} 缺少检测区域`);
|
|
784
|
-
return {
|
|
785
|
-
x: Math.max(0, Math.round(Number(config.region.x) || 0)),
|
|
786
|
-
y: Math.max(0, Math.round(Number(config.region.y) || 0)),
|
|
787
|
-
width: Math.max(1, Math.round(Number(config.region.width) || 1)),
|
|
788
|
-
height: Math.max(1, Math.round(Number(config.region.height) || 1)),
|
|
789
|
-
};
|
|
790
|
-
}
|
|
791
|
-
|
|
792
|
-
function findVisualFrame(
|
|
793
|
-
frames: AppiumReplayFrame[],
|
|
794
|
-
nodeId: string,
|
|
795
|
-
scriptName: string,
|
|
796
|
-
preferredPhase: AppiumReplayFrame['phase'],
|
|
797
|
-
) {
|
|
798
|
-
const matches = frames.filter((frame) => frame.nodeId === nodeId && frame.scriptName === scriptName);
|
|
799
|
-
if (!matches.length) return undefined;
|
|
800
|
-
const frame = preferredPhase === 'before' ? matches[0] : matches[matches.length - 1];
|
|
801
|
-
// A failed capture must not fall back to an older round or a before/error image.
|
|
802
|
-
return frame?.phase === preferredPhase ? frame : undefined;
|
|
803
|
-
}
|
|
804
|
-
|
|
805
|
-
const EMPTY_PNG_BASE64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=';
|
|
806
|
-
|
|
807
|
-
function registerVisualChangeStep(
|
|
808
|
-
step: AppiumRecordedStepRecord,
|
|
809
|
-
meta: RunStepMeta,
|
|
810
|
-
): RunStepResult {
|
|
811
|
-
const config = step.visualChange;
|
|
812
|
-
if (!config) throw new Error(`${step.label} 缺少画面变化检测配置`);
|
|
813
|
-
const context = replayContext.getStore();
|
|
814
|
-
if (config.role === 'start') {
|
|
815
|
-
// Invalidate the previous capture even when this start's after screenshot fails.
|
|
816
|
-
context?.visualStartOffsets.set(JSON.stringify([meta.frameStart || 0, step.id]), context.frames.length);
|
|
817
|
-
return {
|
|
818
|
-
message: `已记录画面变化基准点:${config.pairLabel || step.label}`,
|
|
819
|
-
};
|
|
820
|
-
}
|
|
821
|
-
const endStep = {
|
|
822
|
-
...step,
|
|
823
|
-
visualChange: {
|
|
824
|
-
...config,
|
|
825
|
-
endStepId: config.endStepId || step.id,
|
|
826
|
-
},
|
|
827
|
-
};
|
|
828
|
-
context?.pendingVisualChecks.push({ step: endStep, nodeNumber: meta.nodeNumber, scriptName: meta.scriptName,
|
|
829
|
-
frameStart: context.visualStartOffsets.get(JSON.stringify([meta.frameStart || 0, config.startStepId])) ?? meta.frameStart ?? 0,
|
|
830
|
-
endFrameStart: context.frames.length });
|
|
831
|
-
return {
|
|
832
|
-
message: `已记录画面变化对比点:${config.pairLabel || step.label}`,
|
|
833
|
-
};
|
|
834
|
-
}
|
|
835
|
-
|
|
836
|
-
function appendVisualCheckFailure(lines: string[], check: PendingVisualChangeCheck, message: string) {
|
|
837
|
-
const context = replayContext.getStore();
|
|
838
|
-
if (context) {
|
|
839
|
-
const config = check.step.visualChange;
|
|
840
|
-
context.softFailureCount += 1;
|
|
841
|
-
context.visualChecks.push({
|
|
842
|
-
nodeId: check.step.id,
|
|
843
|
-
nodeNumber: check.nodeNumber,
|
|
844
|
-
nodeLabel: check.step.label,
|
|
845
|
-
status: 'failed',
|
|
846
|
-
message,
|
|
847
|
-
region: config?.region ? visualChangeRegion(check.step) : { x: 0, y: 0, width: 1, height: 1 },
|
|
848
|
-
durationMs: 0,
|
|
849
|
-
intervalMs: 0,
|
|
850
|
-
sampleCount: 0,
|
|
851
|
-
changeRatioThreshold: visualChangeNumber(config?.changeRatioThreshold, 2, 0.01),
|
|
852
|
-
maxChangeRatio: 0,
|
|
853
|
-
baselineBase64: EMPTY_PNG_BASE64,
|
|
854
|
-
comparisonBase64: EMPTY_PNG_BASE64,
|
|
855
|
-
diffBase64: EMPTY_PNG_BASE64,
|
|
856
|
-
startNodeId: config?.startStepId,
|
|
857
|
-
endNodeId: config?.endStepId,
|
|
858
|
-
});
|
|
859
|
-
}
|
|
860
|
-
lines.push(`[节点 ${check.nodeNumber}] 视觉变化检测异常:${message}(继续执行)`);
|
|
861
|
-
}
|
|
862
|
-
|
|
863
|
-
function processPendingVisualChecks(lines: string[]) {
|
|
864
|
-
const context = replayContext.getStore();
|
|
865
|
-
if (!context || !context.pendingVisualChecks.length) return;
|
|
866
|
-
|
|
867
|
-
// Resolve each pair immediately after its end capture, before later rounds
|
|
868
|
-
// or linked-script calls can replace the images associated with these IDs.
|
|
869
|
-
context.pendingVisualChecks.forEach((check) => {
|
|
870
|
-
const config = check.step.visualChange;
|
|
871
|
-
if (!config?.startStepId || !config.endStepId) {
|
|
872
|
-
appendVisualCheckFailure(lines, check, `${check.step.label} 缺少开始节点或结束节点`);
|
|
873
|
-
return;
|
|
874
|
-
}
|
|
875
|
-
const baselineFrame = findVisualFrame(context.frames.slice(check.frameStart, check.endFrameStart), config.startStepId, check.scriptName, 'after');
|
|
876
|
-
const comparisonFrame = findVisualFrame(context.frames.slice(check.endFrameStart), config.endStepId, check.scriptName, 'after');
|
|
877
|
-
if (!baselineFrame || !comparisonFrame) {
|
|
878
|
-
const missing = [
|
|
879
|
-
baselineFrame ? '' : '开始节点截图',
|
|
880
|
-
comparisonFrame ? '' : '结束节点截图',
|
|
881
|
-
].filter(Boolean).join('、');
|
|
882
|
-
appendVisualCheckFailure(lines, check, `${check.step.label} 未捕获到${missing}`);
|
|
883
|
-
return;
|
|
884
|
-
}
|
|
885
|
-
let result: ReturnType<typeof compareVisualChangeFrames>;
|
|
886
|
-
try {
|
|
887
|
-
result = compareVisualChangeFrames({
|
|
888
|
-
baselineScreenshot: Buffer.from(baselineFrame.imageBase64, 'base64'),
|
|
889
|
-
comparisonScreenshot: Buffer.from(comparisonFrame.imageBase64, 'base64'),
|
|
890
|
-
region: visualChangeRegion(check.step),
|
|
891
|
-
changeRatioThreshold: visualChangeNumber(config.changeRatioThreshold, 2, 0.01),
|
|
892
|
-
pixelmatchThreshold: visualChangeNumber(config.pixelmatchThreshold, 0.1, 0, 1),
|
|
893
|
-
});
|
|
894
|
-
} catch (error) {
|
|
895
|
-
appendVisualCheckFailure(lines, check, `${check.step.label} 对比失败:${errorDetail(error)}`);
|
|
896
|
-
return;
|
|
897
|
-
}
|
|
898
|
-
context.visualChecks.push({
|
|
899
|
-
nodeId: check.step.id,
|
|
900
|
-
nodeNumber: check.nodeNumber,
|
|
901
|
-
nodeLabel: check.step.label,
|
|
902
|
-
status: result.passed ? 'passed' : 'failed',
|
|
903
|
-
message: result.message,
|
|
904
|
-
region: result.region,
|
|
905
|
-
durationMs: result.durationMs,
|
|
906
|
-
intervalMs: result.intervalMs,
|
|
907
|
-
sampleCount: result.sampleCount,
|
|
908
|
-
changeRatioThreshold: result.changeRatioThreshold,
|
|
909
|
-
maxChangeRatio: result.maxChangeRatio,
|
|
910
|
-
baselineBase64: result.baselineBase64,
|
|
911
|
-
comparisonBase64: result.comparisonBase64,
|
|
912
|
-
diffBase64: result.diffBase64,
|
|
913
|
-
startNodeId: config.startStepId,
|
|
914
|
-
startNodeLabel: `${baselineFrame.nodeNumber}. ${baselineFrame.nodeLabel}`,
|
|
915
|
-
endNodeId: config.endStepId,
|
|
916
|
-
endNodeLabel: `${comparisonFrame.nodeNumber}. ${comparisonFrame.nodeLabel}`,
|
|
917
|
-
});
|
|
918
|
-
if (!result.passed) context.softFailureCount += 1;
|
|
919
|
-
lines.push(`[节点 ${check.nodeNumber}] 视觉变化检测${result.passed ? '有变化' : '无明显变化'}:${result.message}${result.passed ? '' : '(继续执行)'}`);
|
|
920
|
-
});
|
|
921
|
-
context.pendingVisualChecks = [];
|
|
922
|
-
}
|
|
923
|
-
|
|
924
|
-
async function runStep(
|
|
925
|
-
sessionId: string,
|
|
926
|
-
deviceId: string,
|
|
927
|
-
step: AppiumRecordedStepRecord,
|
|
928
|
-
meta: RunStepMeta,
|
|
929
|
-
): Promise<RunStepResult | void> {
|
|
930
|
-
throwIfReplayStopped();
|
|
931
|
-
step = resolveVariableStep(step);
|
|
932
|
-
if (step.type === 'stopwatch') {
|
|
933
|
-
const context = replayContext.getStore();
|
|
934
|
-
if (!context || !step.stopwatch) throw new Error('计时打点配置未初始化');
|
|
935
|
-
return `TIMER:${JSON.stringify(context.stopwatches.record(step.stopwatch, step.label))}`;
|
|
936
|
-
}
|
|
937
|
-
if (step.type === 'randomValue') {
|
|
938
|
-
const scope = variableContext.getStore();
|
|
939
|
-
const context = replayContext.getStore();
|
|
940
|
-
if (!scope || !context) throw new Error('随机值变量作用域未初始化');
|
|
941
|
-
return context.randomValues.write(scope, JSON.stringify([meta.scriptName, step.id]), step.randomValue);
|
|
942
|
-
}
|
|
943
|
-
if (step.type === 'aiRecognition') {
|
|
944
|
-
const recognition = await recognizeDeviceScreen({
|
|
945
|
-
deviceId, prompt: step.value, aiBranchEnabled: step.aiBranchEnabled, aiObservation: step.aiObservation,
|
|
946
|
-
onProgress: meta.onAiProgress,
|
|
947
|
-
onObservationFrame: frame => captureReplayFrame(sessionId, step, meta.nodeNumber, meta.scriptName || '', 'observation', `观察第 ${frame.index} 帧 · ${frame.elapsedMs}ms`, frame.imageBase64),
|
|
948
|
-
timeoutMs: step.timeoutMs, aiTimeoutEnabled: step.aiTimeoutEnabled === true,
|
|
949
|
-
signal: replayContext.getStore()?.signal,
|
|
950
|
-
onAnalysisStart: meta.onAiAnalysisStart,
|
|
951
|
-
onModelOutput: meta.onModelOutput,
|
|
952
|
-
});
|
|
953
|
-
return `AI 识别回答:${recognition.reason}`;
|
|
954
|
-
}
|
|
955
|
-
if (step.type === 'extractVariable') {
|
|
956
|
-
const config = validateExtraction(step.extractVariable);
|
|
957
|
-
const scope = variableContext.getStore();
|
|
958
|
-
if (!scope) throw new Error('变量作用域未初始化');
|
|
959
|
-
const elementId = await findElement(sessionId, step);
|
|
960
|
-
const endpoint = config.attribute === 'text' ? 'text' : `attribute/${encodeURIComponent(config.attribute)}`;
|
|
961
|
-
const payload = await appiumNodeRequest<AppiumValueResponse<unknown>>(`/session/${sessionId}/element/${elementId}/${endpoint}`);
|
|
962
|
-
if (payload.value === null || payload.value === undefined) throw new Error(`组件不存在属性:${config.attribute}`);
|
|
963
|
-
scope.set({ name: config.name, value: String(payload.value), sensitive: config.sensitive }, true);
|
|
964
|
-
return `已提取变量:${config.name}`;
|
|
965
|
-
}
|
|
966
|
-
if (step.type === 'delay') {
|
|
967
|
-
await wait(Math.max(0, step.timeoutMs || 1000));
|
|
968
|
-
return;
|
|
969
|
-
}
|
|
970
|
-
|
|
971
|
-
if (step.type === 'waitActivity') {
|
|
972
|
-
await waitForActivity(deviceId, step);
|
|
973
|
-
return;
|
|
974
|
-
}
|
|
975
|
-
|
|
976
|
-
if (step.type === 'key') {
|
|
977
|
-
await adbKey(deviceId, step.keyCode || 4);
|
|
978
|
-
return;
|
|
979
|
-
}
|
|
980
|
-
|
|
981
|
-
if (step.type === 'launchApp') {
|
|
982
|
-
const packageName = step.value || '';
|
|
983
|
-
if (await isAppInForeground(deviceId, packageName).catch(error => { throwIfReplayStopped(error); return false; })) {
|
|
984
|
-
return `APP 已在前台,跳过启动 ${packageName}`;
|
|
985
|
-
}
|
|
986
|
-
await launchAppOnDevice(deviceId, packageName);
|
|
987
|
-
return `ADB 已启动 ${packageName}`;
|
|
988
|
-
}
|
|
989
|
-
|
|
990
|
-
if (step.type === 'stopApp') {
|
|
991
|
-
return stopAppOnDevice(deviceId, step.value || '', replayContext.getStore()?.signal);
|
|
992
|
-
}
|
|
993
|
-
|
|
994
|
-
if (step.type === 'clearAppData') {
|
|
995
|
-
const packageName = step.value || '';
|
|
996
|
-
await clearAppDataOnDevice(deviceId, packageName);
|
|
997
|
-
return `ADB 已清除 ${packageName} 的应用数据与缓存`;
|
|
998
|
-
}
|
|
999
|
-
|
|
1000
|
-
if (step.type === 'screenshot') {
|
|
1001
|
-
await saveScreenshot(deviceId);
|
|
1002
|
-
return;
|
|
1003
|
-
}
|
|
1004
|
-
|
|
1005
|
-
if (step.type === 'visualChange') {
|
|
1006
|
-
return registerVisualChangeStep(step, meta);
|
|
1007
|
-
}
|
|
1008
|
-
|
|
1009
|
-
if (step.type === 'noop') {
|
|
1010
|
-
return;
|
|
1011
|
-
}
|
|
1012
|
-
if (step.type === 'log') return formatStageLog(step);
|
|
1013
|
-
if (step.type === 'openGallery') return openGalleryOnDevice(deviceId, replayContext.getStore()?.signal);
|
|
1014
|
-
if (step.type === 'endFlow') {
|
|
1015
|
-
// 同一次回放的主脚本和连接脚本共享结束状态,不影响下一次回放。
|
|
1016
|
-
const context = replayContext.getStore();
|
|
1017
|
-
if (context) context.flowEnded = true;
|
|
1018
|
-
return '流程已主动结束,后续节点不再执行';
|
|
1019
|
-
}
|
|
1020
|
-
|
|
1021
|
-
if (step.type === 'coordinateTap') {
|
|
1022
|
-
await tapFallback(deviceId, step);
|
|
1023
|
-
return;
|
|
1024
|
-
}
|
|
1025
|
-
|
|
1026
|
-
if (step.type === 'swipe') {
|
|
1027
|
-
if (!step.swipe) throw new Error(`${step.label} 缺少滑动坐标`);
|
|
1028
|
-
await adbSwipe(deviceId, step.swipe);
|
|
1029
|
-
return;
|
|
1030
|
-
}
|
|
1031
|
-
|
|
1032
|
-
if (step.type === 'longPress') {
|
|
1033
|
-
const error = validateLongPress(step);
|
|
1034
|
-
if (error) throw new Error(`${step.label}:${error}`);
|
|
1035
|
-
const duration = step.timeoutMs ?? 800;
|
|
1036
|
-
if (longPressMode(step) === 'element') {
|
|
1037
|
-
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
1038
|
-
try {
|
|
1039
|
-
const elementId = await findElement(sessionId, step);
|
|
1040
|
-
await longPressLocatedElement(sessionId, deviceId, elementId, step, duration);
|
|
1041
|
-
return `已长按元素 ${duration}ms`;
|
|
1042
|
-
} catch (error) {
|
|
1043
|
-
throwIfReplayStopped(error);
|
|
1044
|
-
if (attempt === 0 && isStaleElementError(error)) {
|
|
1045
|
-
await wait(300);
|
|
1046
|
-
continue;
|
|
1047
|
-
}
|
|
1048
|
-
if (isStaleElementError(error) && hasUsableFallbackCoordinates(step)) {
|
|
1049
|
-
const x = Number(step.fallback.centerX);
|
|
1050
|
-
const y = Number(step.fallback.centerY);
|
|
1051
|
-
await adbSwipe(deviceId, { startX: x, startY: y, endX: x, endY: y, duration });
|
|
1052
|
-
return `实时元素已失效,已按录制坐标长按 ${duration}ms`;
|
|
1053
|
-
}
|
|
1054
|
-
throw error;
|
|
1055
|
-
}
|
|
1056
|
-
}
|
|
1057
|
-
return `已长按元素 ${duration}ms`;
|
|
1058
|
-
}
|
|
1059
|
-
const x = Number(step.fallback!.centerX);
|
|
1060
|
-
const y = Number(step.fallback!.centerY);
|
|
1061
|
-
await adbSwipe(deviceId, { startX: x, startY: y, endX: x, endY: y, duration });
|
|
1062
|
-
return `已长按坐标 ${x},${y} ${duration}ms`;
|
|
1063
|
-
}
|
|
1064
|
-
|
|
1065
|
-
if (step.type === 'pinch') {
|
|
1066
|
-
if (!step.pinch) throw new Error(`${step.label} 缺少缩放参数`);
|
|
1067
|
-
const size = Math.round(Math.min(500, Math.max(120, step.pinch.centerX, step.pinch.centerY)));
|
|
1068
|
-
await appiumNodeRequest(`/session/${sessionId}/execute/sync`, {
|
|
1069
|
-
method: 'POST',
|
|
1070
|
-
body: JSON.stringify({
|
|
1071
|
-
script: step.pinch.direction === 'out' ? 'mobile: pinchOpenGesture' : 'mobile: pinchCloseGesture',
|
|
1072
|
-
args: [{
|
|
1073
|
-
left: Math.max(0, Math.round(step.pinch.centerX - size / 2)),
|
|
1074
|
-
top: Math.max(0, Math.round(step.pinch.centerY - size / 2)),
|
|
1075
|
-
width: size,
|
|
1076
|
-
height: size,
|
|
1077
|
-
percent: step.pinch.percent,
|
|
1078
|
-
}],
|
|
1079
|
-
}),
|
|
1080
|
-
});
|
|
1081
|
-
return;
|
|
1082
|
-
}
|
|
1083
|
-
|
|
1084
|
-
if (step.type === 'waitDisappear') {
|
|
1085
|
-
await waitForElementGone(sessionId, step);
|
|
1086
|
-
return;
|
|
1087
|
-
}
|
|
1088
|
-
|
|
1089
|
-
if (step.type === 'tapIfExists') {
|
|
1090
|
-
const lookup = await findOptionalElementWithRecovery(sessionId, deviceId, step);
|
|
1091
|
-
if (lookup.recovered) {
|
|
1092
|
-
if (!lookup.bounds) return '自动化会话已恢复,ADB 组件树未发现目标,已跳过';
|
|
1093
|
-
await adbTap(deviceId, lookup.bounds.centerX, lookup.bounds.centerY);
|
|
1094
|
-
return '自动化会话已恢复,ADB 组件树发现目标并已点击';
|
|
1095
|
-
}
|
|
1096
|
-
if (!lookup.elementId) return '未出现,已跳过';
|
|
1097
|
-
await tapLocatedElement(sessionId, deviceId, lookup.elementId, step);
|
|
1098
|
-
return '已出现,已点击';
|
|
1099
|
-
}
|
|
1100
|
-
|
|
1101
|
-
if (step.type === 'inputIfExists') {
|
|
1102
|
-
const lookup = await findOptionalElementWithRecovery(sessionId, deviceId, step);
|
|
1103
|
-
if (lookup.recovered) return lookup.bounds ? '自动化会话已恢复,目标存在但无法安全输入,已跳过' : '自动化会话已恢复,目标未出现,已跳过';
|
|
1104
|
-
if (!lookup.elementId) return '未出现,已跳过';
|
|
1105
|
-
await appiumNodeRequest(`/session/${sessionId}/element/${lookup.elementId}/value`, {
|
|
1106
|
-
method: 'POST',
|
|
1107
|
-
body: JSON.stringify({ text: step.value || '', value: [...(step.value || '')] }),
|
|
1108
|
-
});
|
|
1109
|
-
return '已出现,已输入';
|
|
1110
|
-
}
|
|
1111
|
-
|
|
1112
|
-
if (step.type === 'clearIfExists') {
|
|
1113
|
-
const lookup = await findOptionalElementWithRecovery(sessionId, deviceId, step);
|
|
1114
|
-
if (lookup.recovered) return lookup.bounds ? '自动化会话已恢复,目标存在但无法安全清空,已跳过' : '自动化会话已恢复,目标未出现,已跳过';
|
|
1115
|
-
if (!lookup.elementId) return '未出现,已跳过';
|
|
1116
|
-
await appiumNodeRequest(`/session/${sessionId}/element/${lookup.elementId}/clear`, {
|
|
1117
|
-
method: 'POST',
|
|
1118
|
-
body: JSON.stringify({}),
|
|
1119
|
-
});
|
|
1120
|
-
return '已出现,已清空';
|
|
1121
|
-
}
|
|
1122
|
-
|
|
1123
|
-
if (step.type === 'backIfExists') {
|
|
1124
|
-
const lookup = await findOptionalElementWithRecovery(sessionId, deviceId, step);
|
|
1125
|
-
if (lookup.recovered && !lookup.bounds) return '自动化会话已恢复,目标未出现,已跳过';
|
|
1126
|
-
if (!lookup.recovered && !lookup.elementId) return '未出现,已跳过';
|
|
1127
|
-
await adbKey(deviceId, 4);
|
|
1128
|
-
return lookup.recovered ? '自动化会话已恢复,ADB 组件树发现目标并已返回' : '已出现,已返回';
|
|
1129
|
-
}
|
|
1130
|
-
|
|
1131
|
-
if (step.type === 'waitFor' || step.type === 'assertExists') {
|
|
1132
|
-
await waitForElement(sessionId, step);
|
|
1133
|
-
return;
|
|
1134
|
-
}
|
|
1135
|
-
|
|
1136
|
-
if (step.type === 'assertText') {
|
|
1137
|
-
const elementId = await findElement(sessionId, step);
|
|
1138
|
-
const payload = await appiumNodeRequest<AppiumValueResponse<string>>(`/session/${sessionId}/element/${elementId}/text`);
|
|
1139
|
-
const actual = payload.value || '';
|
|
1140
|
-
if (!actual.includes(step.value || '')) throw new Error(`${step.label} 不匹配,实际文本:${actual || '-'}`);
|
|
1141
|
-
return;
|
|
1142
|
-
}
|
|
1143
|
-
|
|
1144
|
-
if (step.type === 'tap') {
|
|
1145
|
-
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
1146
|
-
try {
|
|
1147
|
-
const elementId = await findElement(sessionId, step);
|
|
1148
|
-
await tapLocatedElement(sessionId, deviceId, elementId, step);
|
|
1149
|
-
return;
|
|
1150
|
-
} catch (error) {
|
|
1151
|
-
throwIfReplayStopped(error);
|
|
1152
|
-
if (attempt === 0 && isStaleElementError(error)) {
|
|
1153
|
-
await wait(300);
|
|
1154
|
-
continue;
|
|
1155
|
-
}
|
|
1156
|
-
await tapFallback(deviceId, step);
|
|
1157
|
-
return;
|
|
1158
|
-
}
|
|
1159
|
-
}
|
|
1160
|
-
return;
|
|
1161
|
-
}
|
|
1162
|
-
|
|
1163
|
-
if (step.type === 'input') {
|
|
1164
|
-
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
1165
|
-
try {
|
|
1166
|
-
const elementId = await findElement(sessionId, step);
|
|
1167
|
-
await appiumNodeRequest(`/session/${sessionId}/element/${elementId}/value`, {
|
|
1168
|
-
method: 'POST',
|
|
1169
|
-
body: JSON.stringify({ text: step.value || '', value: [...(step.value || '')] }),
|
|
1170
|
-
});
|
|
1171
|
-
return;
|
|
1172
|
-
} catch (error) {
|
|
1173
|
-
throwIfReplayStopped(error);
|
|
1174
|
-
if (attempt === 0 && isStaleElementError(error)) {
|
|
1175
|
-
await wait(300);
|
|
1176
|
-
continue;
|
|
1177
|
-
}
|
|
1178
|
-
throw error;
|
|
1179
|
-
}
|
|
1180
|
-
}
|
|
1181
|
-
}
|
|
1182
|
-
|
|
1183
|
-
if (step.type === 'clearInput') {
|
|
1184
|
-
const elementId = await findElement(sessionId, step);
|
|
1185
|
-
await appiumNodeRequest(`/session/${sessionId}/element/${elementId}/clear`, {
|
|
1186
|
-
method: 'POST',
|
|
1187
|
-
body: JSON.stringify({}),
|
|
1188
|
-
});
|
|
1189
|
-
}
|
|
1190
|
-
}
|
|
1191
|
-
|
|
1192
|
-
async function readNativeControlState(sessionId: string, step: AppiumRecordedStepRecord) {
|
|
1193
|
-
if (!isNativeStateCondition(step)) throw new Error('不是原生控件状态判断节点');
|
|
1194
|
-
const elementId = await waitForElement(sessionId, step);
|
|
1195
|
-
const attribute = async (name: string) => (
|
|
1196
|
-
await appiumNodeRequest<AppiumValueResponse<unknown>>(`/session/${sessionId}/element/${elementId}/attribute/${name}`)
|
|
1197
|
-
).value;
|
|
1198
|
-
const className = await attribute('className');
|
|
1199
|
-
if (!matchesNativeControl(step.type, className)) {
|
|
1200
|
-
throw new Error(`${step.label} 目标不是原生 ${nativeControlName(step.type)},实际类型:${String(className ?? '未知')}`);
|
|
1201
|
-
}
|
|
1202
|
-
if (parseNativeBoolean(await attribute('checkable')) !== true) {
|
|
1203
|
-
throw new Error(`${step.label} 目标不支持原生勾选状态(checkable 不为 true)`);
|
|
1204
|
-
}
|
|
1205
|
-
const checked = parseNativeBoolean(await attribute('checked'));
|
|
1206
|
-
if (checked === undefined) throw new Error(`${step.label} 无法读取有效的 checked 属性`);
|
|
1207
|
-
return checked;
|
|
1208
|
-
}
|
|
1209
|
-
|
|
1210
|
-
async function evaluateCondition(sessionId: string, deviceId: string, step: AppiumRecordedStepRecord) {
|
|
1211
|
-
step = resolveVariableStep(step);
|
|
1212
|
-
if (step.type === 'loop') {
|
|
1213
|
-
if (step.loop?.exitWhen === 'never') return false;
|
|
1214
|
-
const selector = toAppiumUsing(step.selector!);
|
|
1215
|
-
const payload = await withElementDeadline(step.timeoutMs ?? DEFAULT_NODE_TIMEOUT_MS, () => (
|
|
1216
|
-
appiumNodeRequest<AppiumValueResponse<Record<string, string>[]>>(`/session/${sessionId}/elements`, {
|
|
1217
|
-
method: 'POST', body: JSON.stringify(selector),
|
|
1218
|
-
})
|
|
1219
|
-
));
|
|
1220
|
-
if (!Array.isArray(payload.value)) throw new Error('循环退出条件查询返回了无效结果');
|
|
1221
|
-
return step.loop?.exitWhen === 'exists' ? payload.value.length > 0 : payload.value.length === 0;
|
|
1222
|
-
}
|
|
1223
|
-
if (step.type === 'textClick') {
|
|
1224
|
-
const selector = textClickSelector(step);
|
|
1225
|
-
const timeoutMs = Math.max(0, step.timeoutMs ?? DEFAULT_NODE_TIMEOUT_MS);
|
|
1226
|
-
const deadline = Date.now() + timeoutMs;
|
|
1227
|
-
let attempted = false;
|
|
1228
|
-
const timeoutResult = () => {
|
|
1229
|
-
if (step.timeoutMs === 0) return false;
|
|
1230
|
-
throw new ConditionTimeoutError(`文字点击等待匹配超时(${timeoutMs}ms)`);
|
|
1231
|
-
};
|
|
1232
|
-
// 查询空结果才是未匹配;通信错误、重复匹配和点击失败走现有异常处理。
|
|
1233
|
-
do {
|
|
1234
|
-
const remaining = deadline - Date.now();
|
|
1235
|
-
if (attempted && (remaining <= 0 || remaining < MIN_ELEMENT_ATTEMPT_BUDGET_MS)) return timeoutResult();
|
|
1236
|
-
attempted = true;
|
|
1237
|
-
const requestBudget = timeoutMs === 0 ? DEFAULT_NODE_TIMEOUT_MS : remaining;
|
|
1238
|
-
const payload = await withElementDeadline(requestBudget, () => (
|
|
1239
|
-
appiumNodeRequest<AppiumValueResponse<Record<string, string>[]>>(`/session/${sessionId}/elements`, {
|
|
1240
|
-
method: 'POST', body: JSON.stringify(selector),
|
|
1241
|
-
})
|
|
1242
|
-
));
|
|
1243
|
-
if (!Array.isArray(payload.value)) throw new Error('文字点击查询返回了无效结果');
|
|
1244
|
-
if (payload.value.length > 1) throw new Error(`匹配到 ${payload.value.length} 个文字元素,请使用更精确的文字`);
|
|
1245
|
-
if (payload.value.length === 1) {
|
|
1246
|
-
const element = payload.value[0]!;
|
|
1247
|
-
const id = element[ELEMENT_KEY] || element.ELEMENT;
|
|
1248
|
-
if (!id) throw new Error('文字点击查询缺少元素 ID');
|
|
1249
|
-
await tapLocatedElement(sessionId, deviceId, id);
|
|
1250
|
-
return true;
|
|
1251
|
-
}
|
|
1252
|
-
if (timeoutMs === 0 || Date.now() >= deadline) return timeoutResult();
|
|
1253
|
-
await wait(Math.max(0, Math.min(500, deadline - Date.now())));
|
|
1254
|
-
} while (true);
|
|
1255
|
-
}
|
|
1256
|
-
// 未找到控件、类型错误和属性读取异常不等于未勾选,必须交给回放错误处理。
|
|
1257
|
-
if (isNativeStateCondition(step)) return readNativeControlState(sessionId, step);
|
|
1258
|
-
try {
|
|
1259
|
-
if (step.type === 'waitActivity') {
|
|
1260
|
-
await waitForActivity(deviceId, step);
|
|
1261
|
-
return true;
|
|
1262
|
-
}
|
|
1263
|
-
if (step.type === 'waitDisappear') {
|
|
1264
|
-
await waitForElementGone(sessionId, step);
|
|
1265
|
-
return true;
|
|
1266
|
-
}
|
|
1267
|
-
if (step.type === 'assertText' || (step.type === 'assertExists' && step.value)) {
|
|
1268
|
-
const elementId = await waitForElement(sessionId, step);
|
|
1269
|
-
const payload = await appiumNodeRequest<AppiumValueResponse<string>>(`/session/${sessionId}/element/${elementId}/text`);
|
|
1270
|
-
const actualText = payload.value || '';
|
|
1271
|
-
const expectedText = step.value || '';
|
|
1272
|
-
return step.flow?.textMatch === 'exact'
|
|
1273
|
-
? actualText === expectedText
|
|
1274
|
-
: normalizeTextForContains(actualText).includes(normalizeTextForContains(expectedText));
|
|
1275
|
-
}
|
|
1276
|
-
await waitForElement(sessionId, step);
|
|
1277
|
-
return true;
|
|
1278
|
-
} catch (error) {
|
|
1279
|
-
throwIfReplayStopped(error);
|
|
1280
|
-
throw error;
|
|
1281
|
-
}
|
|
1282
|
-
}
|
|
1283
|
-
|
|
1284
|
-
function hasFlowSteps(steps: AppiumRecordedStepRecord[]) {
|
|
1285
|
-
return steps.some((step) => (
|
|
1286
|
-
defaultFlowKind(step) === 'condition'
|
|
1287
|
-
|| Boolean(step.flow?.yesTargetId)
|
|
1288
|
-
|| Boolean(step.flow?.noTargetId)
|
|
1289
|
-
|| Boolean(step.flow?.successTargetId)
|
|
1290
|
-
|| Boolean(step.flow?.failureTargetId)
|
|
1291
|
-
));
|
|
1292
|
-
}
|
|
1293
|
-
|
|
1294
|
-
async function appendStepDiagnostics(lines: string[], deviceId: string, step: AppiumRecordedStepRecord) {
|
|
1295
|
-
const currentActivity = await getCurrentActivity(deviceId).catch(() => '');
|
|
1296
|
-
lines.push(`诊断 Activity:${currentActivity || '-'}`);
|
|
1297
|
-
lines.push(`诊断 selector:${step.selector ? `${step.selector.strategy} ${step.selector.value || ''}` : '-'}`);
|
|
1298
|
-
if (step.contextSelector) {
|
|
1299
|
-
lines.push(`诊断上下文:${step.contextSelector.strategy} ${step.contextSelector.value || ''}`);
|
|
1300
|
-
}
|
|
1301
|
-
if (step.selectorChain?.length) {
|
|
1302
|
-
lines.push(`诊断备用 selector:${step.selectorChain.map((selector) => `${selector.strategy} ${selector.value || ''}`).join(';')}`);
|
|
1303
|
-
}
|
|
1304
|
-
if (step.pageBefore) {
|
|
1305
|
-
lines.push(`录制前 Activity:${step.pageBefore.activity || '-'}`);
|
|
1306
|
-
}
|
|
1307
|
-
if (step.pageAfter) {
|
|
1308
|
-
lines.push(`录制后 Activity:${step.pageAfter.activity || '-'}`);
|
|
1309
|
-
}
|
|
1310
|
-
}
|
|
1311
|
-
|
|
1312
|
-
type ReplayStepOptions = {
|
|
1313
|
-
frameStart?: number;
|
|
1314
|
-
skipAppInitialization?: boolean;
|
|
1315
|
-
scriptName?: string;
|
|
1316
|
-
};
|
|
1317
|
-
|
|
1318
|
-
function shouldSkipLinkedScriptInitStep(options: ReplayStepOptions, step: AppiumRecordedStepRecord, steps: AppiumRecordedStepRecord[]) {
|
|
1319
|
-
if (!options.skipAppInitialization) return false;
|
|
1320
|
-
// Only the leading initialization sequence is redundant in a linked script.
|
|
1321
|
-
// Launches inside branches or after other operations are intentional actions.
|
|
1322
|
-
return steps.slice(0, steps.indexOf(step) + 1).every(item =>
|
|
1323
|
-
!item.flow?.parentConditionId && (item.type === 'launchApp' || item.type === 'clearAppData'));
|
|
1324
|
-
}
|
|
1325
|
-
|
|
1326
|
-
function linkedScriptInitSkipReason(step: AppiumRecordedStepRecord) {
|
|
1327
|
-
return step.type === 'clearAppData'
|
|
1328
|
-
? '连接脚本不重复清理 App'
|
|
1329
|
-
: '连接脚本不重复启动 App';
|
|
1330
|
-
}
|
|
1331
|
-
|
|
1332
|
-
async function replayLinkedScript(
|
|
1333
|
-
sessionId: string,
|
|
1334
|
-
deviceId: string,
|
|
1335
|
-
step: AppiumRecordedStepRecord,
|
|
1336
|
-
lines: string[],
|
|
1337
|
-
stack: string[],
|
|
1338
|
-
) {
|
|
1339
|
-
throwIfReplayStopped();
|
|
1340
|
-
const scriptId = step.value || '';
|
|
1341
|
-
if (!scriptId) throw new Error(`${step.label} 缺少连接脚本 ID`);
|
|
1342
|
-
if (stack.includes(scriptId)) throw new Error(`${step.label} 检测到循环连接脚本`);
|
|
1343
|
-
const linkedScript = replayContext.getStore()?.scripts.get(scriptId);
|
|
1344
|
-
if (!linkedScript) throw new Error(`${step.label} 指向的脚本不存在`);
|
|
1345
|
-
|
|
1346
|
-
if (linkedScript.appActivity) {
|
|
1347
|
-
const currentActivity = await getCurrentActivity(deviceId).catch(() => '');
|
|
1348
|
-
if (currentActivity !== linkedScript.appActivity) {
|
|
1349
|
-
lines.push(`等待连接脚本入口 Activity:${linkedScript.appActivity}`);
|
|
1350
|
-
try {
|
|
1351
|
-
await waitForActivity(deviceId, {
|
|
1352
|
-
id: `${step.id}_wait_activity`,
|
|
1353
|
-
type: 'waitActivity',
|
|
1354
|
-
label: step.label,
|
|
1355
|
-
value: linkedScript.appActivity,
|
|
1356
|
-
timeoutMs: DEFAULT_NODE_TIMEOUT_MS,
|
|
1357
|
-
});
|
|
1358
|
-
} catch (error) {
|
|
1359
|
-
throwIfReplayStopped(error);
|
|
1360
|
-
const latestActivity = await getCurrentActivity(deviceId).catch(() => currentActivity);
|
|
1361
|
-
throw new Error(
|
|
1362
|
-
`${step.label} 无法执行:当前 Activity 为 ${latestActivity || '-'},`
|
|
1363
|
-
+ `目标脚本入口 Activity 为 ${linkedScript.appActivity}`,
|
|
1364
|
-
);
|
|
1365
|
-
}
|
|
1366
|
-
}
|
|
1367
|
-
}
|
|
1368
|
-
|
|
1369
|
-
// 每次调用独立分段,即使连续两次连接的是同一个脚本。
|
|
1370
|
-
await replayContext.getStore()?.selectVideoScript?.(linkedScript.id, linkedScript.name, true);
|
|
1371
|
-
lines.push(`连接脚本开始:${linkedScript.name}`);
|
|
1372
|
-
const nextStack = [...stack, linkedScript.id];
|
|
1373
|
-
const parent = variableContext.getStore()!;
|
|
1374
|
-
const child = parent.child(linkedScript.variables || [], step.parameters);
|
|
1375
|
-
await variableContext.run(child, () => replayScriptSteps(sessionId, deviceId, linkedScript.steps, lines, nextStack, {
|
|
1376
|
-
skipAppInitialization: true, scriptName: linkedScript.name,
|
|
1377
|
-
}));
|
|
1378
|
-
if (!replayContext.getStore()?.flowEnded) parent.acceptReturns(child, step.returns);
|
|
1379
|
-
lines.push(`连接脚本完成:${linkedScript.name}`);
|
|
1380
|
-
}
|
|
1381
|
-
|
|
1382
|
-
function appendRunStepResult(lines: string[], nodeNumber: number, result: RunStepResult | void) {
|
|
1383
|
-
if (!result) return false;
|
|
1384
|
-
if (typeof result === 'string') {
|
|
1385
|
-
if (result) lines.push(`[节点 ${nodeNumber}] 结果:${result}`);
|
|
1386
|
-
return false;
|
|
1387
|
-
}
|
|
1388
|
-
if (result.softFailed) {
|
|
1389
|
-
lines.push(`[节点 ${nodeNumber}] 视觉变化未达预期:${result.message || '未检测到明显变化'}(继续执行)`);
|
|
1390
|
-
return true;
|
|
1391
|
-
}
|
|
1392
|
-
if (result.message) lines.push(`[节点 ${nodeNumber}] 结果:${result.message}`);
|
|
1393
|
-
return false;
|
|
1394
|
-
}
|
|
1395
|
-
|
|
1396
|
-
async function replayLinearSteps(
|
|
1397
|
-
sessionId: string,
|
|
1398
|
-
deviceId: string,
|
|
1399
|
-
steps: AppiumRecordedStepRecord[],
|
|
1400
|
-
lines: string[],
|
|
1401
|
-
stack: string[] = [],
|
|
1402
|
-
options: ReplayStepOptions = {},
|
|
1403
|
-
) {
|
|
1404
|
-
for (const [index, step] of steps.entries()) {
|
|
1405
|
-
if (replayContext.getStore()?.flowEnded) return;
|
|
1406
|
-
throwIfReplayStopped();
|
|
1407
|
-
if (shouldSkipLinkedScriptInitStep(options, step, steps)) {
|
|
1408
|
-
lines.push(`[节点 ${index + 1}] 跳过:${step.label}(${linkedScriptInitSkipReason(step)})`);
|
|
1409
|
-
continue;
|
|
1410
|
-
}
|
|
1411
|
-
await replayContext.getStore()?.selectVideoScript?.(stack.at(-1) || '', options.scriptName || '');
|
|
1412
|
-
const nodeStartedAt = Date.now();
|
|
1413
|
-
lines.push(`[节点 ${index + 1}] 开始:${step.label}`);
|
|
1414
|
-
await captureReplayFrame(sessionId, step, index + 1, options.scriptName || '', 'before', '执行前');
|
|
1415
|
-
try {
|
|
1416
|
-
let softFailed = false;
|
|
1417
|
-
if (step.type === 'runScript') {
|
|
1418
|
-
await replayLinkedScript(sessionId, deviceId, step, lines, stack);
|
|
1419
|
-
} else {
|
|
1420
|
-
const result = await runStep(sessionId, deviceId, step, {
|
|
1421
|
-
onAiProgress: message => lines.push(`[节点 ${index + 1}] AI 持续观察:${message}`),
|
|
1422
|
-
onAiAnalysisStart: () => lines.push(`[节点 ${index + 1}] AI 识别内容开始:距进入当前节点 ${Date.now() - nodeStartedAt}ms`),
|
|
1423
|
-
onModelOutput: content => lines.push(`[节点 ${index + 1}] AI 识别模型输出:${content}`),
|
|
1424
|
-
nodeNumber: index + 1,
|
|
1425
|
-
scriptName: options.scriptName || '',
|
|
1426
|
-
frameStart: options.frameStart,
|
|
1427
|
-
});
|
|
1428
|
-
softFailed = appendRunStepResult(lines, index + 1, result);
|
|
1429
|
-
}
|
|
1430
|
-
lines.push(`[节点 ${index + 1}] 完成:${step.label}${softFailed ? '(存在软失败,已继续)' : ''}`);
|
|
1431
|
-
await captureReplayFrame(sessionId, step, index + 1, options.scriptName || '', 'after', completedStepStatus(step, softFailed));
|
|
1432
|
-
processPendingVisualChecks(lines);
|
|
1433
|
-
} catch (error) {
|
|
1434
|
-
if (isReplayStopped(error)) {
|
|
1435
|
-
lines.push(`[节点 ${index + 1}] 已终止:${step.label}`);
|
|
1436
|
-
await captureReplayFrame(sessionId, step, index + 1, options.scriptName || '', 'stopped', '已终止');
|
|
1437
|
-
throw new ReplayStoppedError();
|
|
1438
|
-
}
|
|
1439
|
-
lines.push(`[节点 ${index + 1}] 失败:${errorDetail(error)}`);
|
|
1440
|
-
await captureReplayFrame(sessionId, step, index + 1, options.scriptName || '', 'error', '失败');
|
|
1441
|
-
await appendStepDiagnostics(lines, deviceId, step);
|
|
1442
|
-
throw error;
|
|
1443
|
-
}
|
|
1444
|
-
}
|
|
1445
|
-
}
|
|
1446
|
-
|
|
1447
|
-
async function replayFlowSteps(
|
|
1448
|
-
sessionId: string,
|
|
1449
|
-
deviceId: string,
|
|
1450
|
-
steps: AppiumRecordedStepRecord[],
|
|
1451
|
-
lines: string[],
|
|
1452
|
-
stack: string[] = [],
|
|
1453
|
-
options: ReplayStepOptions = {},
|
|
1454
|
-
) {
|
|
1455
|
-
const idToIndex = new Map(steps.map((step, index) => [step.id, index]));
|
|
1456
|
-
const traversal = new BoundedLoopTraversal(steps);
|
|
1457
|
-
const nextIndexAfterStep = (index: number, step: AppiumRecordedStepRecord) => traversal.next(step, index);
|
|
1458
|
-
const visitedPath: string[] = [];
|
|
1459
|
-
let index: number | undefined = 0;
|
|
1460
|
-
|
|
1461
|
-
while (typeof index === 'number' && index >= 0 && index < steps.length) {
|
|
1462
|
-
if (replayContext.getStore()?.flowEnded) return;
|
|
1463
|
-
throwIfReplayStopped();
|
|
1464
|
-
const step = steps[index];
|
|
1465
|
-
traversal.visit(step);
|
|
1466
|
-
const loopContext = traversal.context(step);
|
|
1467
|
-
const frameStep = loopContext ? { ...step, label: `${step.label}(${loopContext})` } : step;
|
|
1468
|
-
if (shouldSkipLinkedScriptInitStep(options, step, steps)) {
|
|
1469
|
-
lines.push(`[节点 ${index + 1}] 跳过:${step.label}(${linkedScriptInitSkipReason(step)})`);
|
|
1470
|
-
index = nextIndexAfterStep(index, step);
|
|
1471
|
-
continue;
|
|
1472
|
-
}
|
|
1473
|
-
await replayContext.getStore()?.selectVideoScript?.(stack.at(-1) || '', options.scriptName || '');
|
|
1474
|
-
visitedPath.push(step.label);
|
|
1475
|
-
const nodeKind = defaultFlowKind(step);
|
|
1476
|
-
const nodeStartedAt = Date.now();
|
|
1477
|
-
lines.push(`[节点 ${index + 1}] 开始:${frameStep.label}`);
|
|
1478
|
-
await captureReplayFrame(sessionId, frameStep, index + 1, options.scriptName || '', 'before', '执行前');
|
|
1479
|
-
|
|
1480
|
-
if (nodeKind === 'condition') {
|
|
1481
|
-
try {
|
|
1482
|
-
if (step.type === 'loop') {
|
|
1483
|
-
const iterations = traversal.iteration(step);
|
|
1484
|
-
const atLimit = iterations >= step.loop!.maxIterations;
|
|
1485
|
-
const exitMatched = !atLimit && await evaluateCondition(sessionId, deviceId, step);
|
|
1486
|
-
if (atLimit || exitMatched) {
|
|
1487
|
-
const reason = atLimit ? '达到最大次数' : '满足退出条件';
|
|
1488
|
-
lines.push(`[循环 ${step.label}] 结束:${reason},已执行 ${iterations} 轮`);
|
|
1489
|
-
await captureReplayFrame(sessionId, frameStep, index + 1, options.scriptName || '', 'after', `${reason},已执行 ${iterations} 轮`);
|
|
1490
|
-
index = traversal.exit(step);
|
|
1491
|
-
} else {
|
|
1492
|
-
const entered = traversal.enter(step);
|
|
1493
|
-
lines.push(`[循环 ${step.label}] 第 ${entered.iteration}/${step.loop!.maxIterations} 轮开始`);
|
|
1494
|
-
await captureReplayFrame(sessionId, frameStep, index + 1, options.scriptName || '', 'after', `第 ${entered.iteration}/${step.loop!.maxIterations} 轮`);
|
|
1495
|
-
index = entered.next;
|
|
1496
|
-
}
|
|
1497
|
-
continue;
|
|
1498
|
-
}
|
|
1499
|
-
const beforeFrame = replayContext.getStore()?.frames.at(-1);
|
|
1500
|
-
const recognition = step.type === 'aiRecognition' ? await recognizeDeviceScreen({
|
|
1501
|
-
deviceId, prompt: resolveVariableStep(step).value, timeoutMs: step.timeoutMs,
|
|
1502
|
-
aiTimeoutEnabled: step.aiTimeoutEnabled === true, aiObservation: step.aiObservation,
|
|
1503
|
-
onProgress: message => lines.push(`[节点 ${index + 1}] AI 持续观察:${message}`),
|
|
1504
|
-
onObservationFrame: frame => captureReplayFrame(sessionId, frameStep, index + 1, options.scriptName || '', 'observation', `观察第 ${frame.index} 帧 · ${frame.elapsedMs}ms`, frame.imageBase64),
|
|
1505
|
-
onAnalysisStart: () => lines.push(`[节点 ${index + 1}] AI 识别内容开始:距进入当前节点 ${Date.now() - nodeStartedAt}ms`),
|
|
1506
|
-
onModelOutput: (content) => lines.push(`[节点 ${index + 1}] AI 识别模型输出:${content}`),
|
|
1507
|
-
signal: replayContext.getStore()?.signal,
|
|
1508
|
-
imageBase64: beforeFrame?.nodeId === step.id && beforeFrame.phase === 'before' ? beforeFrame.imageBase64 : undefined,
|
|
1509
|
-
}) : undefined;
|
|
1510
|
-
let imageResult: ImageCheckResult | undefined;
|
|
1511
|
-
if (step.type === 'imageCheck') {
|
|
1512
|
-
const resolved = resolveVariableStep(step);
|
|
1513
|
-
imageResult = await checkImage({ config: resolved.imageCheck!,
|
|
1514
|
-
capture: async () => Buffer.from(await adbScreenshotBase64(deviceId, replayContext.getStore()?.signal), 'base64'),
|
|
1515
|
-
resolveRegion: () => imageCheckRegion(sessionId, resolved), wait,
|
|
1516
|
-
signal: replayContext.getStore()?.signal, saveImages: !variableContext.getStore()?.privacy.enabled });
|
|
1517
|
-
const config = resolved.imageCheck;
|
|
1518
|
-
const settings = config ? [
|
|
1519
|
-
IMAGE_CHECK_MODES[config.mode],
|
|
1520
|
-
config.mode === 'template' ? `预期匹配结果:${config.expectation === 'present' ? '匹配到模板' : '未匹配到模板'}` : '',
|
|
1521
|
-
['template', 'state'].includes(config.mode) ? `匹配严格度 ${config.threshold * 100}%` : '',
|
|
1522
|
-
config.mode === 'state' ? `最小得分差 ${config.minScoreGap}` : '',
|
|
1523
|
-
['black', 'color', 'change'].includes(config.mode) ? `RGB/亮度容差 ${config.tolerance};像素占比 ${config.ratio}%` : '',
|
|
1524
|
-
config.mode === 'color' ? `目标色 ${config.color}` : '',
|
|
1525
|
-
config.mode === 'change' ? `预期:${config.expectation === 'present' ? '画面有变化' : '持续无明显变化'}` : '',
|
|
1526
|
-
config.mode !== 'state' ? `观察 ${config.durationMs}ms;间隔 ${config.intervalMs}ms;连续 ${config.consecutive} 帧` : '',
|
|
1527
|
-
].filter(Boolean).join(';') : '缺少配置';
|
|
1528
|
-
replayContext.getStore()?.imageChecks.push({ ...imageResult, nodeId: step.id, nodeNumber: index + 1, nodeLabel: frameStep.label, scriptName: options.scriptName || '', settings });
|
|
1529
|
-
lines.push(`[节点 ${index + 1}] 图像判断:${imageResult.result === null ? '无法判定' : imageResult.result},${imageResult.message};${settings};采样 ${imageResult.sampleCount} 帧,耗时 ${imageResult.durationMs}ms;指标 ${JSON.stringify(imageResult.metrics)}`);
|
|
1530
|
-
if (imageResult.result === null) throw new Error(imageResult.message);
|
|
1531
|
-
if (imageResult.timedOut) throw new ConditionTimeoutError(imageResult.message);
|
|
1532
|
-
}
|
|
1533
|
-
const matched = imageResult ? imageResult.result! : recognition ? recognition.result : await evaluateCondition(sessionId, deviceId, step);
|
|
1534
|
-
if (recognition) lines.push(`[节点 ${index + 1}] AI 识别:${recognition.result},耗时 ${recognition.durationMs}ms,依据:${recognition.reason}`);
|
|
1535
|
-
const branchTargetId = matched ? step.flow?.yesTargetId : step.flow?.noTargetId;
|
|
1536
|
-
const next = traversal.branch(step, matched);
|
|
1537
|
-
const targetId = branchTargetId || (next === undefined ? '' : steps[next]?.id) || '';
|
|
1538
|
-
const branchLabel = flowBranchLabel(step, matched ? 'yes' : 'no');
|
|
1539
|
-
lines.push(`[节点 ${index + 1}] 判断:${branchLabel}${isNativeStateCondition(step) ? `(checked=${matched})` : ''}${targetId ? `,进入 ${targetId}` : ',流程结束'}`);
|
|
1540
|
-
await captureReplayFrame(
|
|
1541
|
-
sessionId,
|
|
1542
|
-
frameStep,
|
|
1543
|
-
index + 1,
|
|
1544
|
-
options.scriptName || '',
|
|
1545
|
-
'after',
|
|
1546
|
-
`判断:${branchLabel}${recognition?.reason ? `;${recognition.reason}` : ''}`,
|
|
1547
|
-
recognition?.imageBase64,
|
|
1548
|
-
);
|
|
1549
|
-
index = next;
|
|
1550
|
-
} catch (error) {
|
|
1551
|
-
if (isReplayStopped(error)) {
|
|
1552
|
-
lines.push(`[节点 ${index + 1}] 已终止:${step.label}`);
|
|
1553
|
-
await captureReplayFrame(sessionId, step, index + 1, options.scriptName || '', 'stopped', '已终止');
|
|
1554
|
-
throw new ReplayStoppedError();
|
|
1555
|
-
}
|
|
1556
|
-
const invalidResultFallback = step.type === 'aiRecognition'
|
|
1557
|
-
? resolveAiInvalidResultFallback(error, step.aiInvalidResultBranch)
|
|
1558
|
-
: null;
|
|
1559
|
-
if (invalidResultFallback !== null) {
|
|
1560
|
-
const status = `AI 未返回有效 true/false,按兜底配置进入 ${invalidResultFallback ? 'true' : 'false'} 分支`;
|
|
1561
|
-
lines.push(`[节点 ${index + 1}] ${status};${errorDetail(error)}`);
|
|
1562
|
-
await captureReplayFrame(sessionId, frameStep, index + 1, options.scriptName || '', 'after', status);
|
|
1563
|
-
index = traversal.branch(step, invalidResultFallback);
|
|
1564
|
-
continue;
|
|
1565
|
-
}
|
|
1566
|
-
if (error instanceof ConditionTimeoutError && (step.timeoutBranch === 'yes' || step.timeoutBranch === 'no')) {
|
|
1567
|
-
const branch = step.timeoutBranch;
|
|
1568
|
-
const status = `判断超时,按配置进入${branch === 'yes' ? '左' : '右'}侧分支(${flowBranchLabel(step, branch)})`;
|
|
1569
|
-
lines.push(`[节点 ${index + 1}] ${status};${error.message}`);
|
|
1570
|
-
await captureReplayFrame(sessionId, frameStep, index + 1, options.scriptName || '', 'after', status);
|
|
1571
|
-
// 循环体必须经过 enter,才能正确记轮次及受最大次数保护。
|
|
1572
|
-
index = step.type === 'loop'
|
|
1573
|
-
? branch === 'yes' ? traversal.enter(step).next : traversal.exit(step)
|
|
1574
|
-
: traversal.branch(step, branch === 'yes');
|
|
1575
|
-
continue;
|
|
1576
|
-
}
|
|
1577
|
-
lines.push(`[节点 ${index + 1}] 失败:${errorDetail(error)}`);
|
|
1578
|
-
await captureReplayFrame(sessionId, step, index + 1, options.scriptName || '', 'error', '失败');
|
|
1579
|
-
await appendStepDiagnostics(lines, deviceId, step);
|
|
1580
|
-
throw error;
|
|
1581
|
-
}
|
|
1582
|
-
continue;
|
|
1583
|
-
}
|
|
1584
|
-
|
|
1585
|
-
try {
|
|
1586
|
-
let softFailed = false;
|
|
1587
|
-
if (step.type === 'breakLoop') {
|
|
1588
|
-
const exited = traversal.break(step);
|
|
1589
|
-
lines.push(`[循环 ${exited.loop.label}] 第 ${exited.iteration} 轮主动退出`);
|
|
1590
|
-
await captureReplayFrame(sessionId, frameStep, index + 1, options.scriptName || '', 'after', `已退出循环:${exited.loop.label}`);
|
|
1591
|
-
index = exited.next;
|
|
1592
|
-
continue;
|
|
1593
|
-
} else if (step.type === 'continueLoop') {
|
|
1594
|
-
const continued = traversal.continue(step);
|
|
1595
|
-
lines.push(`[循环 ${continued.loop.label}] 第 ${continued.iteration} 轮提前结束,进入下一轮判断`);
|
|
1596
|
-
await captureReplayFrame(sessionId, frameStep, index + 1, options.scriptName || '', 'after', `继续下一轮:${continued.loop.label}`);
|
|
1597
|
-
index = continued.next;
|
|
1598
|
-
continue;
|
|
1599
|
-
} else if (step.type === 'runScript') {
|
|
1600
|
-
await replayLinkedScript(sessionId, deviceId, step, lines, stack);
|
|
1601
|
-
} else {
|
|
1602
|
-
const result = await runStep(sessionId, deviceId, step, {
|
|
1603
|
-
onAiProgress: message => lines.push(`[节点 ${index + 1}] AI 持续观察:${message}`),
|
|
1604
|
-
onAiAnalysisStart: () => lines.push(`[节点 ${index + 1}] AI 识别内容开始:距进入当前节点 ${Date.now() - nodeStartedAt}ms`),
|
|
1605
|
-
onModelOutput: content => lines.push(`[节点 ${index + 1}] AI 识别模型输出:${content}`),
|
|
1606
|
-
nodeNumber: index + 1,
|
|
1607
|
-
scriptName: options.scriptName || '',
|
|
1608
|
-
frameStart: options.frameStart,
|
|
1609
|
-
});
|
|
1610
|
-
softFailed = appendRunStepResult(lines, index + 1, result);
|
|
1611
|
-
}
|
|
1612
|
-
lines.push(`[节点 ${index + 1}] 完成:${step.label}${softFailed ? '(存在软失败,已继续)' : ''}`);
|
|
1613
|
-
await captureReplayFrame(sessionId, frameStep, index + 1, options.scriptName || '', 'after', completedStepStatus(step, softFailed));
|
|
1614
|
-
processPendingVisualChecks(lines);
|
|
1615
|
-
index = nextIndexAfterStep(index, step);
|
|
1616
|
-
} catch (error) {
|
|
1617
|
-
if (isReplayStopped(error)) {
|
|
1618
|
-
lines.push(`[节点 ${index + 1}] 已终止:${step.label}`);
|
|
1619
|
-
await captureReplayFrame(sessionId, step, index + 1, options.scriptName || '', 'stopped', '已终止');
|
|
1620
|
-
throw new ReplayStoppedError();
|
|
1621
|
-
}
|
|
1622
|
-
const failureTarget = step.flow?.failureTargetId;
|
|
1623
|
-
if (failureTarget && idToIndex.has(failureTarget)) {
|
|
1624
|
-
lines.push(`[节点 ${index + 1}] 失败分支:${errorDetail(error)}`);
|
|
1625
|
-
await captureReplayFrame(sessionId, step, index + 1, options.scriptName || '', 'error', '进入失败分支');
|
|
1626
|
-
index = idToIndex.get(failureTarget);
|
|
1627
|
-
continue;
|
|
1628
|
-
}
|
|
1629
|
-
lines.push(`[节点 ${index + 1}] 失败:${errorDetail(error)}`);
|
|
1630
|
-
await captureReplayFrame(sessionId, step, index + 1, options.scriptName || '', 'error', '失败');
|
|
1631
|
-
lines.push(`执行路径:${visitedPath.join(' -> ')}`);
|
|
1632
|
-
await appendStepDiagnostics(lines, deviceId, step);
|
|
1633
|
-
throw error;
|
|
1634
|
-
}
|
|
1635
|
-
}
|
|
1636
|
-
}
|
|
1637
|
-
|
|
1638
|
-
async function replayStepGroup(
|
|
1639
|
-
sessionId: string,
|
|
1640
|
-
deviceId: string,
|
|
1641
|
-
steps: AppiumRecordedStepRecord[],
|
|
1642
|
-
lines: string[],
|
|
1643
|
-
stack: string[],
|
|
1644
|
-
options: ReplayStepOptions = {},
|
|
1645
|
-
) {
|
|
1646
|
-
if (!steps.length) return;
|
|
1647
|
-
if (hasFlowSteps(steps)) {
|
|
1648
|
-
await replayFlowSteps(sessionId, deviceId, steps, lines, stack, options);
|
|
1649
|
-
} else {
|
|
1650
|
-
await replayLinearSteps(sessionId, deviceId, steps, lines, stack, options);
|
|
1651
|
-
}
|
|
1652
|
-
}
|
|
1653
|
-
|
|
1654
|
-
async function replayScriptSteps(
|
|
1655
|
-
sessionId: string,
|
|
1656
|
-
deviceId: string,
|
|
1657
|
-
steps: AppiumRecordedStepRecord[],
|
|
1658
|
-
lines: string[],
|
|
1659
|
-
stack: string[],
|
|
1660
|
-
options: ReplayStepOptions = {},
|
|
1661
|
-
) {
|
|
1662
|
-
validateLoopSteps(steps);
|
|
1663
|
-
options = { ...options, frameStart: replayContext.getStore()?.frames.length || 0 };
|
|
1664
|
-
let trailingLinkIndex = steps.length;
|
|
1665
|
-
while (
|
|
1666
|
-
trailingLinkIndex > 0
|
|
1667
|
-
&& steps[trailingLinkIndex - 1]?.type === 'runScript'
|
|
1668
|
-
&& !steps[trailingLinkIndex - 1]?.flow?.parentConditionId
|
|
1669
|
-
) {
|
|
1670
|
-
trailingLinkIndex -= 1;
|
|
1671
|
-
}
|
|
1672
|
-
|
|
1673
|
-
const mainSteps = steps.slice(0, trailingLinkIndex);
|
|
1674
|
-
const trailingLinkedSteps = steps.slice(trailingLinkIndex);
|
|
1675
|
-
await replayStepGroup(sessionId, deviceId, mainSteps, lines, stack, options);
|
|
1676
|
-
|
|
1677
|
-
for (const [offset, step] of trailingLinkedSteps.entries()) {
|
|
1678
|
-
if (replayContext.getStore()?.flowEnded) return;
|
|
1679
|
-
const nodeNumber = trailingLinkIndex + offset + 1;
|
|
1680
|
-
lines.push(`当前脚本步骤完成,开始执行:${step.label}`);
|
|
1681
|
-
lines.push(`[节点 ${nodeNumber}] 开始:${step.label}`);
|
|
1682
|
-
await captureReplayFrame(sessionId, step, nodeNumber, options.scriptName || '', 'before', '执行前');
|
|
1683
|
-
try {
|
|
1684
|
-
await replayLinkedScript(sessionId, deviceId, step, lines, stack);
|
|
1685
|
-
lines.push(`[节点 ${nodeNumber}] 完成:${step.label}`);
|
|
1686
|
-
await captureReplayFrame(sessionId, step, nodeNumber, options.scriptName || '', 'after', completedStepStatus(step, false));
|
|
1687
|
-
} catch (error) {
|
|
1688
|
-
if (isReplayStopped(error)) {
|
|
1689
|
-
lines.push(`[节点 ${nodeNumber}] 已终止:${step.label}`);
|
|
1690
|
-
await captureReplayFrame(sessionId, step, nodeNumber, options.scriptName || '', 'stopped', '已终止');
|
|
1691
|
-
throw new ReplayStoppedError();
|
|
1692
|
-
}
|
|
1693
|
-
lines.push(`[节点 ${nodeNumber}] 失败:${errorDetail(error)}`);
|
|
1694
|
-
await captureReplayFrame(sessionId, step, nodeNumber, options.scriptName || '', 'error', '失败');
|
|
1695
|
-
throw error;
|
|
1696
|
-
}
|
|
1697
|
-
}
|
|
1698
|
-
}
|
|
1699
|
-
|
|
1700
|
-
export async function replayAppiumScript(
|
|
1701
|
-
script: AppiumRecordedScriptRecord,
|
|
1702
|
-
deviceId: string,
|
|
1703
|
-
onOutput?: (line: string) => void,
|
|
1704
|
-
signal?: AbortSignal,
|
|
1705
|
-
runOptions: { screenshotReport?: boolean; recordVideo?: boolean; reportSummaryEnabled?: boolean; reportSummaryPrompt?: string; parameters?: TestVariable[]; globalVariables?: TestVariable[]; linkedScripts?: AppiumRecordedScriptRecord[] } = {},
|
|
1706
|
-
) {
|
|
1707
|
-
const targetDeviceId = deviceId || script.deviceId;
|
|
1708
|
-
if (!targetDeviceId) throw new Error('未检测到可用设备');
|
|
1709
|
-
if (!script.steps.length) throw new Error('脚本没有可回放步骤');
|
|
1710
|
-
|
|
1711
|
-
const scope = new VariableScope(runOptions.globalVariables ?? getPresetVariables(), script.variables || []);
|
|
1712
|
-
const scripts = new Map((runOptions.linkedScripts ?? linkedScriptSnapshot(script)).map(item => [item.id, item]));
|
|
1713
|
-
for (const item of validateVariables(runOptions.parameters)) scope.set(item);
|
|
1714
|
-
// 提前登记子脚本敏感预设,避免进入子脚本前的原始日志或截图泄露。
|
|
1715
|
-
const visited = new Set<string>();
|
|
1716
|
-
const registerSecrets = (current: AppiumRecordedScriptRecord) => {
|
|
1717
|
-
if (visited.has(current.id)) return;
|
|
1718
|
-
visited.add(current.id);
|
|
1719
|
-
(current.variables || []).forEach(item => scope.track(item));
|
|
1720
|
-
for (const step of current.steps) {
|
|
1721
|
-
(step.parameters || []).forEach(item => scope.track(item));
|
|
1722
|
-
if (step.extractVariable) scope.track({ ...step.extractVariable, value: '' });
|
|
1723
|
-
if (step.randomValue) {
|
|
1724
|
-
const name = step.randomValue.name;
|
|
1725
|
-
scope.track({ name, value: step.randomValue.text || '', sensitive: step.randomValue.sensitive
|
|
1726
|
-
|| current.variables?.find(item => item.name === name)?.sensitive || scope.locals.get(name)?.sensitive || scope.globals.get(name)?.sensitive });
|
|
1727
|
-
}
|
|
1728
|
-
if (step.type === 'runScript' && step.value) {
|
|
1729
|
-
const child = scripts.get(step.value);
|
|
1730
|
-
if (child) registerSecrets(child);
|
|
1731
|
-
}
|
|
1732
|
-
}
|
|
1733
|
-
};
|
|
1734
|
-
registerSecrets(script);
|
|
1735
|
-
|
|
1736
|
-
const appiumConfig = loadConfig().appium;
|
|
1737
|
-
const configuredReportSummary = resolveReportSummary(appiumConfig.reportSummary);
|
|
1738
|
-
const reportSummary = resolveReportSummary({
|
|
1739
|
-
...configuredReportSummary,
|
|
1740
|
-
enabled: runOptions.reportSummaryEnabled ?? configuredReportSummary.enabled,
|
|
1741
|
-
prompt: runOptions.reportSummaryPrompt?.trim() || configuredReportSummary.prompt,
|
|
1742
|
-
});
|
|
1743
|
-
const reportSummaryModel = appiumConfig.promptOptimizer?.model;
|
|
1744
|
-
const startedAt = new Date();
|
|
1745
|
-
const appVersion = await readAppVersion(targetDeviceId, script.appPackage).catch(() => '');
|
|
1746
|
-
const lines: string[] = [];
|
|
1747
|
-
const pushLine = lines.push.bind(lines);
|
|
1748
|
-
lines.push = (...items: string[]) => {
|
|
1749
|
-
items = items.map(item => timestampReplayLog(scope.redact(item)));
|
|
1750
|
-
const length = pushLine(...items);
|
|
1751
|
-
items.forEach((line) => onOutput?.(line));
|
|
1752
|
-
return length;
|
|
1753
|
-
};
|
|
1754
|
-
const context = {
|
|
1755
|
-
randomValues: new RandomValueGenerator(),
|
|
1756
|
-
stopwatches: new ReplayStopwatches(),
|
|
1757
|
-
screenshotReport: (runOptions.screenshotReport ?? loadConfig().appium.screenshotReport) === true,
|
|
1758
|
-
visualCaptureNodes: new Set([script, ...scripts.values()].flatMap(item => item.steps.flatMap(step =>
|
|
1759
|
-
step.visualChange ? [step.id, step.visualChange.startStepId || '', step.visualChange.endStepId || ''] : []))),
|
|
1760
|
-
signal,
|
|
1761
|
-
sessionId: '',
|
|
1762
|
-
appiumLog: (line) => { if (!scope.privacy.enabled) lines.push(line); },
|
|
1763
|
-
serverUrl: configuredAppiumServerUrl(),
|
|
1764
|
-
deviceId: targetDeviceId,
|
|
1765
|
-
scripts,
|
|
1766
|
-
frames: [] as AppiumReplayFrame[],
|
|
1767
|
-
historyEvents: [] as AppiumReplayFrame[],
|
|
1768
|
-
visualChecks: [] as AppiumReplayVisualCheck[],
|
|
1769
|
-
imageChecks: [] as Array<ImageCheckResult & { nodeId: string; nodeNumber: number; nodeLabel: string; scriptName: string; settings: string }>,
|
|
1770
|
-
visualStartOffsets: new Map<string, number>(),
|
|
1771
|
-
pendingVisualChecks: [] as PendingVisualChangeCheck[],
|
|
1772
|
-
softFailureCount: 0,
|
|
1773
|
-
};
|
|
1774
|
-
return variableContext.run(scope, () => replayContext.run(context, async () => {
|
|
1775
|
-
lines.push(context.screenshotReport ? '截图与 HTML 报告已开启:节点截图会增加回放耗时' : '截图与 HTML 报告已关闭:仅保留日志和运行历史,检测及手动截图节点仍按需截图');
|
|
1776
|
-
if (scope.privacy.enabled) lines.push('敏感变量保护已启用:不保存报告截图、截图节点文件或 Appium 原始日志');
|
|
1777
|
-
lines.push(
|
|
1778
|
-
`目标设备:${targetDeviceId}`,
|
|
1779
|
-
`App 包名:${script.appPackage}`,
|
|
1780
|
-
`录制步骤:${script.steps.length}`,
|
|
1781
|
-
);
|
|
1782
|
-
let sessionId = '';
|
|
1783
|
-
let sessionCreationStarted = false;
|
|
1784
|
-
let stopHeartbeat: (() => Promise<void>) | undefined;
|
|
1785
|
-
let success = false;
|
|
1786
|
-
let stopped = false;
|
|
1787
|
-
let recording: Awaited<ReturnType<typeof startReplayVideo>> | undefined;
|
|
1788
|
-
let video: ReplayVideo | undefined;
|
|
1789
|
-
let managedAppium: Awaited<ReturnType<typeof startManagedAppiumServer>> | null = null;
|
|
1790
|
-
try {
|
|
1791
|
-
validateLoopSteps(script.steps);
|
|
1792
|
-
lines.push('正在检测 Android SDK...');
|
|
1793
|
-
const androidSdk = ensureAndroidSdkAvailable();
|
|
1794
|
-
lines.push(`Android SDK 已就绪:${androidSdk.root}`);
|
|
1795
|
-
if (usesManagedAppiumServer()) {
|
|
1796
|
-
lines.push('正在启动本次回放的 Appium 服务...');
|
|
1797
|
-
lines.push('----- Appium 服务端原始日志开始 -----');
|
|
1798
|
-
managedAppium = await startManagedAppiumServer((line) => { if (!scope.privacy.enabled) lines.push(line); }, signal);
|
|
1799
|
-
context.serverUrl = managedAppium.serverUrl;
|
|
1800
|
-
}
|
|
1801
|
-
lines.push(`Appium 服务:${appiumServerUrl()}`);
|
|
1802
|
-
lines.push('正在创建 Appium session...');
|
|
1803
|
-
sessionCreationStarted = true;
|
|
1804
|
-
try {
|
|
1805
|
-
sessionId = await createSession(targetDeviceId);
|
|
1806
|
-
} catch (error) {
|
|
1807
|
-
throwIfReplayStopped(error);
|
|
1808
|
-
if (!isUiAutomationDisconnected(error)) throw error;
|
|
1809
|
-
lines.push('检测到 UiAutomation 连接冲突,正在清理残留进程并重试...');
|
|
1810
|
-
await resetUiAutomator2(targetDeviceId);
|
|
1811
|
-
sessionId = await createSession(targetDeviceId);
|
|
1812
|
-
}
|
|
1813
|
-
context.sessionId = sessionId;
|
|
1814
|
-
if (!managedAppium) {
|
|
1815
|
-
const heartbeatAbort = new AbortController();
|
|
1816
|
-
let heartbeatTask: Promise<unknown> | undefined;
|
|
1817
|
-
const timer = setInterval(() => {
|
|
1818
|
-
if (heartbeatTask || signal?.aborted) return;
|
|
1819
|
-
heartbeatTask = appiumRequest(`/session/${sessionId}/timeouts`, { signal: heartbeatAbort.signal }, { timeoutMs: 5000 })
|
|
1820
|
-
.catch(error => { if (!heartbeatAbort.signal.aborted && !signal?.aborted) lines.push(`Appium 保活失败:${errorDetail(error)}`); })
|
|
1821
|
-
.finally(() => { heartbeatTask = undefined; });
|
|
1822
|
-
}, 15000);
|
|
1823
|
-
timer.unref();
|
|
1824
|
-
stopHeartbeat = async () => { clearInterval(timer); heartbeatAbort.abort(); await heartbeatTask; };
|
|
1825
|
-
}
|
|
1826
|
-
lines.push(`Appium session 已创建:${sessionId}`);
|
|
1827
|
-
if (runOptions.recordVideo) {
|
|
1828
|
-
if (scope.privacy.enabled) throw new Error('本次运行包含敏感变量,为避免泄露已禁止录屏,请关闭录制回放视频');
|
|
1829
|
-
lines.push('正在启动后台录屏...');
|
|
1830
|
-
try {
|
|
1831
|
-
recording = await startReplayVideo(targetDeviceId, signal, message => lines.push(message));
|
|
1832
|
-
replayContext.getStore()!.selectVideoScript = recording.selectScript;
|
|
1833
|
-
await recording.selectScript(script.id, script.name);
|
|
1834
|
-
} catch (error) {
|
|
1835
|
-
if (!isReplayStopped(error)) {
|
|
1836
|
-
lines.push('[录屏提示] 录屏启动失败,尚未执行任何流程节点。请检查设备连接、其他录屏或投屏占用,以及报告目录的写入权限和磁盘空间;也可关闭“录制回放视频”后重新回放。详细原因见下方错误日志。');
|
|
1837
|
-
}
|
|
1838
|
-
throw error;
|
|
1839
|
-
}
|
|
1840
|
-
lines.push('后台录屏已启动(MP4 / H.264 / 最高15fps,无音频)');
|
|
1841
|
-
}
|
|
1842
|
-
if (hasFlowSteps(script.steps)) lines.push('按流程图路径回放...');
|
|
1843
|
-
await replayScriptSteps(sessionId, targetDeviceId, script.steps, lines, [script.id], {
|
|
1844
|
-
scriptName: script.name,
|
|
1845
|
-
});
|
|
1846
|
-
processPendingVisualChecks(lines);
|
|
1847
|
-
if (context.softFailureCount > 0) {
|
|
1848
|
-
lines.push(`回放完成,但存在 ${context.softFailureCount} 个视觉变化未达预期节点`);
|
|
1849
|
-
success = false;
|
|
1850
|
-
} else {
|
|
1851
|
-
lines.push('回放完成');
|
|
1852
|
-
success = true;
|
|
1853
|
-
}
|
|
1854
|
-
} catch (error) {
|
|
1855
|
-
stopped = isReplayStopped(error);
|
|
1856
|
-
const detail = errorDetail(error);
|
|
1857
|
-
if (stopped) {
|
|
1858
|
-
lines.push('回放已终止:用户手动终止');
|
|
1859
|
-
} else {
|
|
1860
|
-
if (detail.includes('Appium Settings app is not running')) {
|
|
1861
|
-
await appendSettingsDiagnostics(lines, targetDeviceId);
|
|
1862
|
-
}
|
|
1863
|
-
if (detail.includes('Neither ANDROID_HOME nor ANDROID_SDK_ROOT')) {
|
|
1864
|
-
appendAndroidSdkDiagnostics(lines);
|
|
1865
|
-
}
|
|
1866
|
-
lines.push(`回放终止:${detail}`);
|
|
1867
|
-
}
|
|
1868
|
-
} finally {
|
|
1869
|
-
if (recording) {
|
|
1870
|
-
try {
|
|
1871
|
-
video = await recording.stop();
|
|
1872
|
-
if (scope.privacy.enabled) {
|
|
1873
|
-
for (const segment of video.segments || [video]) {
|
|
1874
|
-
await import('node:fs/promises').then(fs => fs.rm(segment.filePath, { force: true }));
|
|
1875
|
-
}
|
|
1876
|
-
video = undefined;
|
|
1877
|
-
lines.push('敏感变量保护:已删除回放视频');
|
|
1878
|
-
} else {
|
|
1879
|
-
for (const [index, segment] of (video.segments || [video]).entries()) {
|
|
1880
|
-
lines.push(`回放视频 ${index + 1}(${segment.scriptName || script.name})已保存:${segment.filePath}`);
|
|
1881
|
-
}
|
|
1882
|
-
if (video.warning) {
|
|
1883
|
-
lines.push(`录屏警告:${video.warning}`);
|
|
1884
|
-
lines.push('[录屏提示] 本次录像可能不完整,请结合节点日志和截图确认执行结果;需要完整录像时,请检查设备连接和录屏占用后重新回放。');
|
|
1885
|
-
}
|
|
1886
|
-
}
|
|
1887
|
-
} catch (error) {
|
|
1888
|
-
lines.push(`回放视频保存失败:${errorDetail(error)}`);
|
|
1889
|
-
lines.push('[录屏提示] 本次录像未能完整保存。请检查报告目录的写入权限、磁盘空间及设备连接;录像保存失败不等同于流程节点失败,请以节点执行日志为准。');
|
|
1890
|
-
}
|
|
1891
|
-
}
|
|
1892
|
-
await stopHeartbeat?.();
|
|
1893
|
-
let managedAppiumStopped = false;
|
|
1894
|
-
if (signal?.aborted && managedAppium) {
|
|
1895
|
-
await managedAppium.stop();
|
|
1896
|
-
managedAppiumStopped = true;
|
|
1897
|
-
} else if (sessionId) {
|
|
1898
|
-
await appiumRequest(
|
|
1899
|
-
`/session/${sessionId}`,
|
|
1900
|
-
{ method: 'DELETE' },
|
|
1901
|
-
{ ignoreAbort: true, timeoutMs: 2000 },
|
|
1902
|
-
).catch(error => { lines.push(`Appium 会话清理失败:${errorDetail(error)}${managedAppium ? '' : ';外部服务将在命令空闲 60 秒后回收会话'}`); });
|
|
1903
|
-
}
|
|
1904
|
-
if (managedAppium) {
|
|
1905
|
-
if (!managedAppiumStopped) await managedAppium.stop();
|
|
1906
|
-
if (sessionCreationStarted) {
|
|
1907
|
-
try {
|
|
1908
|
-
await stopManagedUiAutomator(targetDeviceId, getAdbCommand());
|
|
1909
|
-
} catch (error) {
|
|
1910
|
-
lines.push(`设备端 UiAutomator2 清理失败,可能影响组件树刷新:${errorDetail(error)}`);
|
|
1911
|
-
}
|
|
1912
|
-
}
|
|
1913
|
-
lines.push('----- Appium 服务端原始日志结束 -----');
|
|
1914
|
-
}
|
|
1915
|
-
if (runOptions.recordVideo) {
|
|
1916
|
-
if (video) {
|
|
1917
|
-
for (const [index, segment] of (video.segments || [video]).entries()) {
|
|
1918
|
-
lines.push(`录屏位置 ${index + 1}(${segment.scriptName || script.name}):${segment.filePath}`);
|
|
1919
|
-
}
|
|
1920
|
-
} else {
|
|
1921
|
-
lines.push(scope.privacy.enabled
|
|
1922
|
-
? '录屏位置:无(敏感变量保护,本次不保留录像)'
|
|
1923
|
-
: '录屏位置:无(未生成可用视频,请查看上方录屏提示)');
|
|
1924
|
-
}
|
|
1925
|
-
}
|
|
1926
|
-
}
|
|
1927
|
-
|
|
1928
|
-
if (signal?.aborted && !stopped) {
|
|
1929
|
-
stopped = true;
|
|
1930
|
-
success = false;
|
|
1931
|
-
lines.push('回放已终止:用户手动终止');
|
|
1932
|
-
}
|
|
1933
|
-
|
|
1934
|
-
const completedAt = new Date();
|
|
1935
|
-
const safeFrames = scope.privacy.enabled || !context.screenshotReport ? [] : scope.scrub(context.frames);
|
|
1936
|
-
const safeChecks = scope.scrub(context.visualChecks.map(check => scope.privacy.enabled
|
|
1937
|
-
? { ...check, baselineBase64: '', comparisonBase64: '', diffBase64: '' } : check));
|
|
1938
|
-
let reportPath = '';
|
|
1939
|
-
let reportId = '';
|
|
1940
|
-
let logPath = '';
|
|
1941
|
-
let htmlReportPath = '';
|
|
1942
|
-
try {
|
|
1943
|
-
const report = await createAppiumReplayReport({
|
|
1944
|
-
reportSummary,
|
|
1945
|
-
reportSummaryModel,
|
|
1946
|
-
linkedScripts: scope.scrub([...scripts.values()].filter(item => item.id !== script.id)),
|
|
1947
|
-
redact: text => scope.redact(text),
|
|
1948
|
-
onSummaryStatus: status => { lines.push(status); },
|
|
1949
|
-
screenshotReport: context.screenshotReport,
|
|
1950
|
-
script: scope.scrub(script),
|
|
1951
|
-
deviceId: targetDeviceId,
|
|
1952
|
-
success,
|
|
1953
|
-
stopped,
|
|
1954
|
-
output: scope.redact(lines.join('\n')),
|
|
1955
|
-
video,
|
|
1956
|
-
startedAt,
|
|
1957
|
-
completedAt,
|
|
1958
|
-
frames: safeFrames,
|
|
1959
|
-
visualChecks: safeChecks,
|
|
1960
|
-
imageChecks: scope.scrub(context.imageChecks.map(check => scope.privacy.enabled ? { ...check, images: [] } : check)),
|
|
1961
|
-
});
|
|
1962
|
-
reportPath = report.filePath;
|
|
1963
|
-
reportId = report.id;
|
|
1964
|
-
logPath = report.logPath;
|
|
1965
|
-
htmlReportPath = report.htmlReportPath;
|
|
1966
|
-
lines.push(`回放报告已生成:${reportPath}`);
|
|
1967
|
-
if (report.htmlReportPath) lines.push(`截图回放已生成:${report.htmlReportPath}`);
|
|
1968
|
-
lines.push(`回放日志已生成:${logPath}`);
|
|
1969
|
-
} catch (error) {
|
|
1970
|
-
lines.push(`回放报告和日志生成失败:${errorDetail(error)}`);
|
|
1971
|
-
}
|
|
1972
|
-
return {
|
|
1973
|
-
success,
|
|
1974
|
-
stopped,
|
|
1975
|
-
output: scope.redact(lines.join('\n')),
|
|
1976
|
-
reportPath,
|
|
1977
|
-
reportId,
|
|
1978
|
-
logPath,
|
|
1979
|
-
htmlReportPath,
|
|
1980
|
-
videoPath: video?.filePath,
|
|
1981
|
-
softFailureCount: context.softFailureCount,
|
|
1982
|
-
history: {
|
|
1983
|
-
scriptId: script.id, scriptName: script.name, appPackage: script.appPackage,
|
|
1984
|
-
video,
|
|
1985
|
-
appVersion, deviceId: targetDeviceId, startedAt: startedAt.toISOString(),
|
|
1986
|
-
durationMs: completedAt.getTime() - startedAt.getTime(),
|
|
1987
|
-
status: stopped ? 'stopped' as const : success ? 'passed' as const : 'failed' as const,
|
|
1988
|
-
output: scope.redact(lines.join('\n')),
|
|
1989
|
-
...scope.scrub(captureHistoryFrames(safeFrames, safeChecks, context.historyEvents)),
|
|
1990
|
-
},
|
|
1991
|
-
};
|
|
1992
|
-
}));
|
|
1993
|
-
}
|