Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4d6560dbd4 | ||
|
|
df66897ff4 | ||
|
|
a6a3ee2eb0 | ||
|
|
49873e7f05 | ||
|
|
f826bdf3b0 | ||
|
|
c96935b47b | ||
|
|
18d17da966 | ||
|
|
0355af7833 | ||
|
|
079d7b1e28 | ||
|
|
1fdf7c0d1d |
No files matched your search
+17
-1
@@ -30,6 +30,16 @@ ARTEMIS_SCREENSHOT_LIMIT_ENABLED=true
|
||||
ARTEMIS_OPERATOR_MAX_NO_PROGRESS_ATTEMPTS=3
|
||||
# Flash 连续无工具调用的最大次数;无效回复不会重复送回模型。
|
||||
ARTEMIS_FLASH_MAX_NO_PROGRESS_ATTEMPTS=3
|
||||
# 所有网页/MCP 任务的总执行时限;排队、用户暂停不计入。任务 JSON 的 timeout_seconds 可覆盖。
|
||||
ARTEMIS_TASK_TIMEOUT_SECONDS=1800
|
||||
# 单次屏幕观测预算、最多恢复次数和备用 ADB 命令时限。
|
||||
ARTEMIS_OBSERVATION_TIMEOUT_SECONDS=60
|
||||
ARTEMIS_OBSERVATION_MAX_ATTEMPTS=3
|
||||
ARTEMIS_DEVICE_COMMAND_TIMEOUT_SECONDS=10
|
||||
# Flash 连续设备动作失败后,重新观察并切换兜底模型;兜底仍失败时结束。
|
||||
ARTEMIS_ACTION_FAILURE_ATTEMPTS=3
|
||||
# 已写出任务结果后,后台线程/录屏清理最多等待多久;超时回收进程释放队列。
|
||||
ARTEMIS_WORKER_CLEANUP_TIMEOUT_SECONDS=30
|
||||
|
||||
# 视频分段、重试与单次分析超时(秒)
|
||||
ARTEMIS_VIDEO_CHUNK_SECONDS=60
|
||||
@@ -40,6 +50,8 @@ ARTEMIS_CHECKPOINT_TIMEOUT_SECONDS=180
|
||||
ARTEMIS_SETTLEMENT_TIMEOUT_SECONDS=120
|
||||
ARTEMIS_CREDENTIAL_TIMEOUT_SECONDS=12
|
||||
ARTEMIS_MODEL_CACHE_TTL_SECONDS=10
|
||||
# 守护服务轻量探测超时;探测超时且端口仍占用时,不重复启动服务。
|
||||
ARTEMIS_DAEMON_PROBE_TIMEOUT_SECONDS=2
|
||||
# 模型重试耗尽后的暂停等待上限(秒);0 表示无限等待
|
||||
LLM_PAUSE_TIMEOUT_SECONDS=900
|
||||
|
||||
@@ -50,12 +62,16 @@ OCR_API_KEY=
|
||||
ADB_HOST=127.0.0.1
|
||||
ADB_PORT=5037
|
||||
# ADB_DEVICE_SERIAL=
|
||||
# 自动发现本机模拟器,并重连通过网页连接过的 TCP 设备;不扫描局域网。
|
||||
ARTEMIS_ADB_AUTO_CONNECT=true
|
||||
ARTEMIS_ADB_DISCOVERY_INTERVAL_SECONDS=10
|
||||
ARTEMIS_ADB_DISCOVERY_TIMEOUT_SECONDS=5
|
||||
ARTEMIS_KEEP_DEVICE_AWAKE=true
|
||||
ARTEMIS_HIERARCHY_BACKEND=auto
|
||||
ARTEMIS_HELPER_AUTO_INSTALL=true
|
||||
ARTEMIS_DEFAULT_PROFILE=flash
|
||||
|
||||
# 批量任务与 Excel 导入限制
|
||||
ARTEMIS_BATCH_TASK_TIMEOUT=1800
|
||||
ARTEMIS_IMPORT_MAX_ROWS=1000
|
||||
ARTEMIS_BATCH_MAX_EXECUTIONS=10000
|
||||
ARTEMIS_IMPORT_MAX_BYTES=10485760
|
||||
@@ -0,0 +1,2 @@
|
||||
# cmd.exe requires CRLF for batch scripts, especially UTF-8 Chinese text.
|
||||
*.bat text eol=crlf
|
||||
@@ -27,7 +27,7 @@
|
||||
| 核心类型检查 | `uv run pyright --project pyright-core.json` |
|
||||
| 源码打包 | `uv run --no-sync python scripts/package_source.py` |
|
||||
|
||||
Windows 首次安装使用 `start.bat`,国内镜像使用 `start-cn.bat`。开发中需要保留当前源码时传入 `-SkipUpdate`,避免启动脚本拉取远端更新。
|
||||
Windows 首次安装使用 `start.bat`,国内镜像使用 `start-cn.bat`。启动只提示源码更新;升级使用 `update.bat` / `update-cn.bat`,会终止本项目运行进程。开发中可传入 `-SkipUpdate` 跳过更新提示。
|
||||
|
||||
## Key Paths
|
||||
|
||||
@@ -58,6 +58,7 @@ Windows 首次安装使用 `start.bat`,国内镜像使用 `start-cn.bat`。开
|
||||
- 新增可调参数集中进入配置层,并更新环境示例、网页/MCP 入口和必要文档,避免散落硬编码。
|
||||
- MCP 工具增删时同步工具注册、CLI 安装白名单、测试、Skill 和能力文档。
|
||||
- Windows PowerShell 启动脚本保持兼容 Windows PowerShell 5.1,避免编码导致解析失败。升级只做 Git 快进,保护已有配置和本地修改。
|
||||
- `update*.bat` 保持精简的 ASCII 入口;升级程序及其辅助脚本先复制到项目外执行。更新后通过新版 `start.ps1 -PrepareOnly -SkipUpdate` 同步环境,保留此内部调用约定,避免继续运行旧版安装函数。
|
||||
- 前端遵循现有简体中文文案与视觉样式;不直接编辑构建产物。
|
||||
|
||||
## Definition of Done
|
||||
|
||||
@@ -29,9 +29,9 @@ cd Artemis-Eapil
|
||||
常用选项:
|
||||
|
||||
```powershell
|
||||
.\start-cn.bat -SetupOnly # 准备环境并安装/更新已检测客户端的 MCP
|
||||
.\start-cn.bat -SetupOnly # 准备环境并安装/更新 Codex MCP
|
||||
.\start.bat -Port 8001 # 指定端口
|
||||
.\start.bat -SkipUpdate # 跳过 Git 源码更新检查
|
||||
.\start.bat -SkipUpdate # 跳过源码更新提示
|
||||
.\start.bat -SkipMcpSync # MCP 配置异常时,仅启动网页
|
||||
```
|
||||
|
||||
@@ -39,7 +39,7 @@ cd Artemis-Eapil
|
||||
|
||||
### macOS / Linux
|
||||
|
||||
克隆仓库后在项目目录执行 `./start.sh`。国内镜像入口和启动时自动更新目前由 Windows 脚本提供。
|
||||
克隆仓库后在项目目录执行 `./start.sh`。国内镜像入口和独立升级脚本目前由 Windows 提供。
|
||||
|
||||
## 配置与使用
|
||||
|
||||
@@ -58,13 +58,13 @@ cd Artemis-Eapil
|
||||
|
||||
## 让 AI 使用
|
||||
|
||||
Windows 启动脚本会为已检测到的 AI 客户端安装或更新 MCP。未被检测到的客户端,可手动安装,例如 Codex:
|
||||
目前仅支持为 Codex 配置 MCP。Windows 启动脚本检测 Codex 配置目录并安装或更新 ARTEMIS;也可手动安装:
|
||||
|
||||
```sh
|
||||
uv run artemis mcp --install codex
|
||||
```
|
||||
|
||||
安装或更新后,在客户端重新加载 MCP 或重启客户端,并按 [AI 接入指南](docs/ai-automation.md) 安装仓库中的 [artemis-automation Skill](skills/artemis-automation/SKILL.md)。Skill 不会随启动脚本自动安装到用户全局目录。其他客户端可通过 `uv run artemis mcp --help` 查看接入方式。
|
||||
安装或更新后,在 Codex 中重新加载 MCP 或重启 Codex,并按 [AI 接入指南](docs/ai-automation.md) 安装仓库中的 [artemis-automation Skill](skills/artemis-automation/SKILL.md)。Skill 不会随启动脚本自动安装到用户全局目录。可用 `uv run artemis mcp --generate-config codex` 查看配置模板。
|
||||
|
||||
示例指令:
|
||||
|
||||
@@ -72,9 +72,11 @@ uv run artemis mcp --install codex
|
||||
|
||||
## 更新与排错
|
||||
|
||||
Windows 用户再次运行一键脚本时,会先检查 Git 上游;即使 `start.bat` 或 `start-cn.bat` 本身被更新,也会重新启动新版脚本,再检查项目依赖、前端构建并同步已检测客户端的 MCP。源码只做快进更新。本地修改、分支分叉或网络认证失败时保留本地版本;有任务执行或排队时停止更新启动。MCP 配置同步失败会明确停止启动,可使用 `-SkipMcpSync` 仅启动网页。更新后需在 AI 客户端重新加载 MCP。
|
||||
启动脚本只检查并提示源码更新,不自动拉取。升级运行 **`.\update.bat`**,国内网络运行 **`.\update-cn.bat`**;支持 `-Help`。升级会终止当前项目的 ARTEMIS 服务、MCP 和任务进程,然后快进更新源码,同步依赖、网页构建及 Codex MCP。升级程序先复制到项目外运行,避免更新正在执行的脚本;其他项目、Codex 本身、模拟器和共享 ADB 服务不会被终止。完成后重新启动 ARTEMIS,并在 Codex 中重载 MCP。
|
||||
|
||||
1.1.1 及更新版本的发布 ZIP 含浅层 Git 工作树,解压后再次运行一键脚本即可检查更新。1.1.0 及更早 ZIP 不含 Git 信息,无法自行拉取;需要下载新版源码包重新解压一次,之后即可自动更新。遇到启动或设备问题,在项目目录运行 `uv run artemis doctor`。
|
||||
本地修改、分支分叉或网络认证失败会停止升级,保留现有文件;`.env`、密钥和历史资料不会清空。启动/升级中的依赖或 MCP 同步失败会明确报错,修复后可重新执行;仅启动网页时可用 `-SkipMcpSync`。
|
||||
|
||||
1.1.1 及更新版本的发布 ZIP 含浅层 Git 工作树;包含独立升级入口的新版源码包可直接用上述脚本升级。1.1.0 及更早 ZIP 不含 Git 信息,需改用 Git 克隆或新版源码包。遇到启动或设备问题,在项目目录运行 `uv run artemis doctor`。
|
||||
|
||||
更多说明:[批量任务与报告](docs/automation-workspace.md) · [AI 接入](docs/ai-automation.md) · [开发协作指南](AGENTS.md)
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ from apps.admin_console.services.automation_store import identifier, store
|
||||
from apps.admin_console.services import automation_service as service
|
||||
from apps.admin_console.services import batch_archive as archive_service
|
||||
from apps.admin_console.services import report_export, task_import
|
||||
from artemis.config.settings import settings
|
||||
|
||||
router = APIRouter(prefix="/api/automation", tags=["automation"])
|
||||
|
||||
@@ -29,8 +30,9 @@ class BatchRequest(ReportPreferences):
|
||||
device_serial: str = Field(min_length=1, max_length=200)
|
||||
profile: Literal["flash", "pro"] = "flash"
|
||||
stop_on_failure: bool = False
|
||||
repeat_count: int = Field(default=1, ge=1, strict=True)
|
||||
timeout_seconds: int = Field(
|
||||
default_factory=lambda: int(os.getenv("ARTEMIS_BATCH_TASK_TIMEOUT", "1800")),
|
||||
default_factory=lambda: settings.ARTEMIS_TASK_TIMEOUT_SECONDS,
|
||||
ge=30,
|
||||
le=86400,
|
||||
)
|
||||
@@ -50,7 +52,8 @@ def require(kind, key):
|
||||
def preferences():
|
||||
return {
|
||||
**store.preferences(),
|
||||
"batch_timeout_seconds": int(os.getenv("ARTEMIS_BATCH_TASK_TIMEOUT", "1800")),
|
||||
"batch_timeout_seconds": settings.ARTEMIS_TASK_TIMEOUT_SECONDS,
|
||||
"batch_max_executions": settings.ARTEMIS_BATCH_MAX_EXECUTIONS,
|
||||
}
|
||||
|
||||
|
||||
@@ -255,7 +258,12 @@ def history(
|
||||
[*args, size, (page - 1) * size],
|
||||
).fetchall()
|
||||
items = [dict(row) for row in rows]
|
||||
jobs = store.jobs_for_sessions([item["session_id"] for item in items])
|
||||
for item in items:
|
||||
if item["case_id"]:
|
||||
if job := jobs.get(item["session_id"]):
|
||||
item["name"] = task_import.execution_title(job)
|
||||
item["iteration"] = job.get("iteration", 1)
|
||||
item["repeat_count"] = job.get("repeat_count", 1)
|
||||
elif item["case_id"]:
|
||||
item["name"] = task_import.case_title(item)
|
||||
return {"items": items, "total": total, "page": page, "size": size}
|
||||
@@ -28,7 +28,7 @@ try:
|
||||
from admin_console.services.media_service import media_service
|
||||
from admin_console.services.model_service import model_service
|
||||
from admin_console.services.automation_store import store
|
||||
from admin_console.services.task_import import case_title
|
||||
from admin_console.services.task_import import execution_title
|
||||
except ImportError:
|
||||
from apps.admin_console.core.state import state
|
||||
from apps.admin_console.database.repositories.session_repository import session_repo
|
||||
@@ -36,7 +36,7 @@ except ImportError:
|
||||
from apps.admin_console.services.media_service import media_service
|
||||
from apps.admin_console.services.model_service import model_service
|
||||
from apps.admin_console.services.automation_store import store
|
||||
from apps.admin_console.services.task_import import case_title
|
||||
from apps.admin_console.services.task_import import execution_title
|
||||
|
||||
|
||||
router = APIRouter(tags=["sessions"])
|
||||
@@ -83,7 +83,9 @@ def _list_sessions_sync():
|
||||
if job:
|
||||
case = job.get("case") or {}
|
||||
row_dict["case_id"] = case.get("case_id") or ""
|
||||
row_dict["display_name"] = case_title(case) or row_dict.get("initial_goal")
|
||||
row_dict["display_name"] = execution_title(job) or row_dict.get("initial_goal")
|
||||
row_dict["iteration"] = job.get("iteration", 1)
|
||||
row_dict["repeat_count"] = job.get("repeat_count", 1)
|
||||
row_dict["error"] = job.get("error") or ""
|
||||
if job.get("status") in {"completed", "failed", "cancelled", "interrupted", "skipped"}:
|
||||
row_dict["status"] = job["status"]
|
||||
|
||||
@@ -202,7 +202,9 @@ async def run_task(request: RunRequest):
|
||||
# With no explicit serial the probe itself resolves a live target (it
|
||||
# prefers the diagnostics target preference, then any unlocked ready
|
||||
# device); the verified serial is bound below.
|
||||
target_serial = request.device_serial
|
||||
target_serial = (
|
||||
request.runtime_overrides.device_serial if request.runtime_overrides else None
|
||||
) or request.device_serial
|
||||
device_probe = await readiness_engine.run_device_submission_probe(target_serial=target_serial)
|
||||
if device_probe and device_probe.summary in {"Device Locked", "Lock State Unknown"}:
|
||||
locked_serial = (
|
||||
@@ -224,7 +226,7 @@ async def run_task(request: RunRequest):
|
||||
# Only auto-selected targets may be re-bound to the probed device. An
|
||||
# explicitly requested serial is never silently replaced -- if it is
|
||||
# invalid, enqueue_tasks rejects the submission with a clear error.
|
||||
if verified_serial and not request.device_serial:
|
||||
if verified_serial and not target_serial:
|
||||
target_serial = verified_serial
|
||||
|
||||
response = await task_queue_service.enqueue_tasks(
|
||||
@@ -240,6 +242,9 @@ async def run_task(request: RunRequest):
|
||||
ingress=request.ingress or "frontend",
|
||||
session_id=request.session_id,
|
||||
conversation_id=request.conversation_id,
|
||||
runtime_overrides=request.runtime_overrides.model_dump(exclude_none=True)
|
||||
if request.runtime_overrides
|
||||
else None,
|
||||
)
|
||||
|
||||
from apps.admin_console.services.automation_service import register_submission
|
||||
@@ -269,7 +274,12 @@ async def get_run_defaults():
|
||||
async def list_devices():
|
||||
"""List all connected Android devices with their busy / idle status."""
|
||||
devices = await device_pool.list_devices_async()
|
||||
return {"devices": [d.to_dict() for d in devices]}
|
||||
from artemis.runtime.adb_discovery import adb_device_discovery
|
||||
|
||||
return {
|
||||
"devices": [d.to_dict() for d in devices],
|
||||
"automatic_connections": adb_device_discovery.results.copy(),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/stop")
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
# limitations under the License.
|
||||
|
||||
from pydantic import BaseModel
|
||||
from apps.admin_console.services.task_import import TaskOptions
|
||||
|
||||
|
||||
class RunRequest(BaseModel):
|
||||
@@ -32,6 +33,7 @@ class RunRequest(BaseModel):
|
||||
ingress: str | None = "frontend"
|
||||
session_id: str | None = None
|
||||
conversation_id: str | None = None
|
||||
runtime_overrides: TaskOptions | None = None
|
||||
|
||||
|
||||
class ReplayRequest(BaseModel):
|
||||
|
||||
@@ -24,6 +24,7 @@ import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import signal
|
||||
import socket
|
||||
import sys
|
||||
from types import FrameType
|
||||
|
||||
@@ -421,6 +422,14 @@ queue_goals = state.queue_goals
|
||||
class ArtemisUvicornServer(uvicorn.Server):
|
||||
"""Notify application streams before Uvicorn waits for them to close."""
|
||||
|
||||
async def startup(self, sockets: list[socket.socket] | None = None) -> None:
|
||||
# Reload workers start in a fresh interpreter; restore the actual bind
|
||||
# address there before lifespan publishes runtime metadata.
|
||||
state.host = self.config.host
|
||||
state.port = self.config.port
|
||||
app.state.uvicorn_server = self
|
||||
await super().startup(sockets=sockets)
|
||||
|
||||
@staticmethod
|
||||
def _task_is_active() -> bool:
|
||||
"""Check task state without doing process I/O from a signal handler."""
|
||||
@@ -470,31 +479,40 @@ class ArtemisUvicornServer(uvicorn.Server):
|
||||
|
||||
def run_ui_server(host: str, port: int, reload: bool = False) -> None:
|
||||
"""Run the UI server with bounded, signal-aware graceful shutdown."""
|
||||
# Reserve a listening socket before publishing metadata or running lifespan.
|
||||
# Uvicorn normally runs application startup *before* binding its port; a
|
||||
# duplicate daemon would otherwise recover jobs owned by the real server.
|
||||
family = socket.AF_INET6 if ":" in host else socket.AF_INET
|
||||
try:
|
||||
listener = socket.create_server((host, port), family=family)
|
||||
except OSError as exc:
|
||||
print(f"无法启动服务:{host}:{port} 端口不可用({exc})。现有服务和任务保持不变。")
|
||||
raise SystemExit(1) from exc
|
||||
listener.set_inheritable(True)
|
||||
port = listener.getsockname()[1]
|
||||
state.host = host
|
||||
state.port = port
|
||||
write_server_info(port=port, host=host, lifecycle_token=LIFECYCLE_TOKEN)
|
||||
|
||||
try:
|
||||
if reload:
|
||||
uvicorn.run(
|
||||
"apps.admin_console.server:app",
|
||||
host=host,
|
||||
port=port,
|
||||
reload=True,
|
||||
timeout_graceful_shutdown=5,
|
||||
)
|
||||
return
|
||||
|
||||
config = uvicorn.Config(
|
||||
app,
|
||||
"apps.admin_console.server:app" if reload else app,
|
||||
host=host,
|
||||
port=port,
|
||||
reload=reload,
|
||||
timeout_graceful_shutdown=5,
|
||||
)
|
||||
if reload:
|
||||
from uvicorn.supervisors import ChangeReload
|
||||
|
||||
server = ArtemisUvicornServer(config)
|
||||
ChangeReload(config, target=server.run, sockets=[listener]).run()
|
||||
return
|
||||
|
||||
server = ArtemisUvicornServer(config)
|
||||
app.state.uvicorn_server = server
|
||||
server.run()
|
||||
server.run(sockets=[listener])
|
||||
finally:
|
||||
listener.close()
|
||||
app.state.uvicorn_server = None
|
||||
clear_server_info(port=port, lifecycle_token=LIFECYCLE_TOKEN)
|
||||
|
||||
|
||||
@@ -8,8 +8,10 @@ import time
|
||||
from uuid import UUID
|
||||
|
||||
from apps.admin_console.core.state import state
|
||||
from apps.admin_console.services.automation_store import store, new_id
|
||||
from apps.admin_console.services.task_import import case_goal, case_title
|
||||
from apps.admin_console.services.automation_store import RECOVERY_ERRORS, store, new_id
|
||||
from apps.admin_console.services.task_import import case_goal, execution_title
|
||||
from artemis.config.settings import settings
|
||||
from artemis.runtime.task_limits import task_timeout
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
TERMINAL = {"completed", "failed", "cancelled", "skipped", "interrupted"}
|
||||
@@ -40,9 +42,46 @@ def register_submission(item: dict, case: dict | None = None, formats=None, **ex
|
||||
)
|
||||
|
||||
|
||||
def resolve_recovery_error(job: dict) -> bool:
|
||||
"""Archive a superseded recovery warning without erasing execution failures."""
|
||||
if job.get("error") not in RECOVERY_ERRORS:
|
||||
return False
|
||||
job.setdefault("recovery_events", []).append(
|
||||
{"message": job.pop("error"), "resolved_at": time.time()}
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
def recover_batches():
|
||||
"""Recovery never silently repeats a potentially side-effecting interrupted task."""
|
||||
from apps.admin_console.database.repositories.session_repository import SessionRepository
|
||||
from artemis.runtime import DeviceExecutionLock
|
||||
|
||||
repository = SessionRepository(store.path)
|
||||
live_sessions = {
|
||||
str(owner.session_id)
|
||||
for owner in DeviceExecutionLock.get_active_owners().values()
|
||||
if owner.session_id
|
||||
}
|
||||
live_sessions.update(
|
||||
str(row["session_id"])
|
||||
for row in repository.get_all_sessions()
|
||||
if row.get("status") not in TERMINAL and repository.process_is_alive(row.get("pid"))
|
||||
)
|
||||
live_sessions.update(
|
||||
str(item["session_id"])
|
||||
for item in state.queue_items
|
||||
if isinstance(item, dict) and item.get("session_id") and item.get("status") not in TERMINAL
|
||||
)
|
||||
for job in store.jobs():
|
||||
if job["status"] == "completed" and resolve_recovery_error(job):
|
||||
store.save_job(job)
|
||||
if str(job["session_id"]) in live_sessions:
|
||||
if job["status"] not in TERMINAL and str(job["session_id"]) not in state.active_runs:
|
||||
job["recovery_waiting"] = True
|
||||
store.save_job(job)
|
||||
logger.info("Recovery preserved live session %s", job["session_id"])
|
||||
continue
|
||||
if job["status"] in {"running", "queued", "finalizing", "task_paused", "resuming"}:
|
||||
job.update(
|
||||
status=job.get("terminal_status", "interrupted"),
|
||||
@@ -50,6 +89,9 @@ def recover_batches():
|
||||
or ("" if job.get("terminal_status") else "服务中断;未完成任务需手动重跑"),
|
||||
ended_at=job.get("ended_at") or time.time(),
|
||||
)
|
||||
if job["status"] == "completed":
|
||||
resolve_recovery_error(job)
|
||||
logger.info("Recovery resolved session %s to %s", job["session_id"], job["status"])
|
||||
store.save_job(job)
|
||||
for batch in store.records("batch"):
|
||||
if has_legacy_replay(batch["id"]):
|
||||
@@ -62,6 +104,8 @@ def recover_batches():
|
||||
store.put("batch", batch["id"], batch)
|
||||
continue
|
||||
if batch["status"] in {"running", "pausing", "paused"}:
|
||||
if any(str(job["session_id"]) in live_sessions for job in store.jobs(batch["id"])):
|
||||
continue
|
||||
batch.update(
|
||||
status="paused", reason="服务已重启;请检查中断任务,点击继续执行未开始任务"
|
||||
)
|
||||
@@ -86,6 +130,9 @@ async def on_terminal(item: dict, status: str):
|
||||
raise RuntimeError("任务元数据写入失败")
|
||||
if job.get("timed_out"):
|
||||
status = "failed"
|
||||
job.pop("recovery_waiting", None)
|
||||
if status == "completed":
|
||||
resolve_recovery_error(job)
|
||||
job.update(status="finalizing", terminal_status=status, ended_at=time.time())
|
||||
store.save_job(job)
|
||||
try:
|
||||
@@ -115,11 +162,37 @@ async def on_terminal(item: dict, status: str):
|
||||
store.save_job(job)
|
||||
|
||||
|
||||
async def reconcile_recovered_jobs():
|
||||
"""Finalize surviving workers once they exit; never resubmit their goals."""
|
||||
from apps.admin_console.database.repositories.session_repository import SessionRepository
|
||||
from artemis.runtime import DeviceExecutionLock
|
||||
from artemis.runtime.task_result import read_worker_outcome
|
||||
|
||||
waiting = [job for job in store.jobs() if job.get("recovery_waiting")]
|
||||
if not waiting:
|
||||
return
|
||||
repository = SessionRepository(store.path)
|
||||
owners = {str(owner.session_id) for owner in DeviceExecutionLock.get_active_owners().values()}
|
||||
for job in waiting:
|
||||
sid = str(job["session_id"])
|
||||
row = repository.get_session_by_id(sid) or {}
|
||||
if sid in owners or repository.process_is_alive(row.get("pid")):
|
||||
continue
|
||||
outcome = read_worker_outcome(sid)
|
||||
status = job.get("terminal_status") or outcome.get("task_status") or row.get("status")
|
||||
if status not in TERMINAL:
|
||||
status = "interrupted"
|
||||
job["error"] = job.get("error") or "服务中断;未完成任务需手动重跑"
|
||||
store.save_job(job)
|
||||
await on_terminal({"session_id": sid}, status)
|
||||
|
||||
|
||||
async def tick_batches():
|
||||
from apps.admin_console.server import task_queue_service
|
||||
from artemis.runtime import device_pool
|
||||
from apps.admin_console.services.report_export import export_batch
|
||||
|
||||
await reconcile_recovered_jobs()
|
||||
for batch in store.records("batch"):
|
||||
if batch["status"] not in {"running", "paused"}:
|
||||
continue
|
||||
@@ -135,10 +208,11 @@ async def tick_batches():
|
||||
# not consume this case's execution budget.
|
||||
if job["status"] != "running":
|
||||
continue
|
||||
limit = int(
|
||||
(job.get("case", {}).get("task_config") or {}).get("timeout_seconds")
|
||||
or batch.get("timeout_seconds", 1800)
|
||||
)
|
||||
from artemis.runtime.task_result import read_worker_outcome
|
||||
|
||||
if read_worker_outcome(str(job["session_id"])):
|
||||
continue # Execution has ended; the worker supervisor bounds cleanup.
|
||||
limit = task_timeout({}, job, batch)
|
||||
task_state = getattr(state, "active_runs", {}).get(str(job["session_id"])) or {}
|
||||
excluded = float(task_state.get("non_execution_seconds") or 0)
|
||||
if task_state.get("non_execution_started_at"):
|
||||
@@ -151,7 +225,17 @@ async def tick_batches():
|
||||
error=f"任务执行超时({limit} 秒,不含暂停/排队时间)", timed_out=True
|
||||
)
|
||||
store.save_job(job)
|
||||
task_queue_service.stop_tasks(session_id=job["session_id"])
|
||||
from artemis.runtime.task_result import save_failure_result
|
||||
|
||||
try:
|
||||
await asyncio.to_thread(
|
||||
save_failure_result,
|
||||
str(job["session_id"]),
|
||||
job["error"],
|
||||
code="task_timeout",
|
||||
)
|
||||
finally:
|
||||
task_queue_service.stop_tasks(session_id=job["session_id"])
|
||||
# on_terminal records the failed case. The next pending
|
||||
# case then runs normally unless stop_on_failure is set.
|
||||
continue
|
||||
@@ -213,7 +297,7 @@ async def tick_batches():
|
||||
runtime_overrides=options,
|
||||
session_id=job["session_id"],
|
||||
ingress="batch",
|
||||
display_name=case_title(job["case"]),
|
||||
display_name=execution_title(job),
|
||||
)
|
||||
if response.get("status") == "rejected" or not response.get("tasks"):
|
||||
raise ValueError(response.get("error") or "队列拒绝接收任务")
|
||||
@@ -246,6 +330,15 @@ def has_legacy_replay(batch_id: str) -> bool:
|
||||
|
||||
|
||||
def create_batch(payload: dict) -> dict:
|
||||
repeat_count = payload.get("repeat_count", 1)
|
||||
if type(repeat_count) is not int or repeat_count < 1:
|
||||
raise ValueError("循环次数必须为正整数")
|
||||
cases = payload["cases"]
|
||||
total = len(cases) * repeat_count
|
||||
if not cases or total > settings.ARTEMIS_BATCH_MAX_EXECUTIONS:
|
||||
raise ValueError(
|
||||
f"请选择用例;用例数 × 循环次数不能超过 {settings.ARTEMIS_BATCH_MAX_EXECUTIONS} 次执行"
|
||||
)
|
||||
bid = new_id()
|
||||
batch = {
|
||||
"id": bid,
|
||||
@@ -255,25 +348,31 @@ def create_batch(payload: dict) -> dict:
|
||||
"formats": payload.get("formats") or store.preferences()["formats"],
|
||||
"profile": payload.get("profile", "flash"),
|
||||
"device_serial": payload.get("device_serial"),
|
||||
"timeout_seconds": payload.get("timeout_seconds")
|
||||
or int(os.getenv("ARTEMIS_BATCH_TASK_TIMEOUT", "1800")),
|
||||
"timeout_seconds": payload.get("timeout_seconds") or settings.ARTEMIS_TASK_TIMEOUT_SECONDS,
|
||||
"stop_on_failure": payload.get("stop_on_failure", False),
|
||||
"request_id": payload.get("request_id"),
|
||||
"repeat_count": repeat_count,
|
||||
"case_count": len(cases),
|
||||
"total_executions": total,
|
||||
}
|
||||
jobs = []
|
||||
for number, case in enumerate(payload["cases"], 1):
|
||||
jobs.append(
|
||||
{
|
||||
"session_id": new_id(),
|
||||
"batch_id": bid,
|
||||
"position": number,
|
||||
"case": case,
|
||||
"status": "pending",
|
||||
"formats": batch["formats"],
|
||||
"created_at": time.time(),
|
||||
"device_serial": batch["device_serial"],
|
||||
}
|
||||
)
|
||||
for iteration in range(1, repeat_count + 1):
|
||||
for number, case in enumerate(cases, 1):
|
||||
jobs.append(
|
||||
{
|
||||
"session_id": new_id(),
|
||||
"batch_id": bid,
|
||||
"position": len(jobs) + 1,
|
||||
"iteration": iteration,
|
||||
"repeat_count": repeat_count,
|
||||
"case_position": number,
|
||||
"case": case,
|
||||
"status": "pending",
|
||||
"formats": batch["formats"],
|
||||
"created_at": batch["created_at"],
|
||||
"device_serial": batch["device_serial"],
|
||||
}
|
||||
)
|
||||
return store.create_batch(batch, jobs, payload)
|
||||
|
||||
|
||||
@@ -329,7 +428,13 @@ def batch_action(batch_id: str, action: str) -> dict:
|
||||
if not failed:
|
||||
raise ValueError("没有可重跑的失败或中断任务")
|
||||
revised = create_batch(
|
||||
{**batch, "name": batch["name"] + " · 失败项重跑", "cases": [j["case"] for j in failed]}
|
||||
{
|
||||
**batch,
|
||||
"name": batch["name"] + " · 失败项重跑",
|
||||
"cases": [j["case"] for j in failed],
|
||||
"repeat_count": 1,
|
||||
"request_id": None,
|
||||
}
|
||||
)
|
||||
return revised
|
||||
else:
|
||||
|
||||
@@ -12,6 +12,12 @@ import uuid
|
||||
from artemis.config import DB_PATH
|
||||
|
||||
|
||||
RECOVERY_ERRORS = {
|
||||
"服务中断;未完成任务需手动重跑",
|
||||
"服务中断,需手动重跑",
|
||||
}
|
||||
|
||||
|
||||
def identifier(value: str) -> str:
|
||||
if not re.fullmatch(r"[A-Za-z0-9_-]{1,100}", value):
|
||||
raise ValueError("无效的记录编号")
|
||||
|
||||
@@ -166,12 +166,37 @@ def persist_environment(values: dict[str, str]) -> None:
|
||||
|
||||
|
||||
class CapabilitySettings(BaseModel):
|
||||
adb_auto_connect: bool = Field(default_factory=lambda: settings.ARTEMIS_ADB_AUTO_CONNECT)
|
||||
adb_discovery_interval_seconds: float = Field(
|
||||
default_factory=lambda: settings.ARTEMIS_ADB_DISCOVERY_INTERVAL_SECONDS, ge=1, le=300
|
||||
)
|
||||
adb_discovery_timeout_seconds: float = Field(
|
||||
default_factory=lambda: settings.ARTEMIS_ADB_DISCOVERY_TIMEOUT_SECONDS, gt=0, le=30
|
||||
)
|
||||
video_enabled: bool = False
|
||||
recording_enabled: bool = False
|
||||
outputter_enabled: bool = True
|
||||
step_summarizer_enabled: bool = True
|
||||
screenshot_limit_enabled: bool = True
|
||||
screenshot_max_long_edge: int = 2048
|
||||
task_timeout_seconds: int = Field(
|
||||
default_factory=lambda: settings.ARTEMIS_TASK_TIMEOUT_SECONDS, ge=30, le=86400
|
||||
)
|
||||
observation_timeout_seconds: float = Field(
|
||||
default_factory=lambda: settings.ARTEMIS_OBSERVATION_TIMEOUT_SECONDS, gt=0, le=300
|
||||
)
|
||||
observation_max_attempts: int = Field(
|
||||
default_factory=lambda: settings.ARTEMIS_OBSERVATION_MAX_ATTEMPTS, ge=1, le=5
|
||||
)
|
||||
device_command_timeout_seconds: float = Field(
|
||||
default_factory=lambda: settings.ARTEMIS_DEVICE_COMMAND_TIMEOUT_SECONDS, gt=0, le=60
|
||||
)
|
||||
action_failure_attempts: int = Field(
|
||||
default_factory=lambda: settings.ARTEMIS_ACTION_FAILURE_ATTEMPTS, ge=1, le=10
|
||||
)
|
||||
worker_cleanup_timeout_seconds: float = Field(
|
||||
default_factory=lambda: settings.ARTEMIS_WORKER_CLEANUP_TIMEOUT_SECONDS, gt=0, le=300
|
||||
)
|
||||
|
||||
|
||||
def get_capability_settings() -> CapabilitySettings:
|
||||
@@ -188,11 +213,20 @@ def get_capability_settings() -> CapabilitySettings:
|
||||
|
||||
def save_capability_settings(update: CapabilitySettings) -> CapabilitySettings:
|
||||
values = {
|
||||
"ARTEMIS_ADB_AUTO_CONNECT": update.adb_auto_connect,
|
||||
"ARTEMIS_ADB_DISCOVERY_INTERVAL_SECONDS": update.adb_discovery_interval_seconds,
|
||||
"ARTEMIS_ADB_DISCOVERY_TIMEOUT_SECONDS": update.adb_discovery_timeout_seconds,
|
||||
"ARTEMIS_VIDEO_ENABLED": update.video_enabled,
|
||||
"ARTEMIS_RECORDING_ENABLED": update.recording_enabled,
|
||||
"ARTEMIS_OUTPUTTER_ENABLED": update.outputter_enabled,
|
||||
"ARTEMIS_STEP_SUMMARIZER_ENABLED": update.step_summarizer_enabled,
|
||||
"ARTEMIS_SCREENSHOT_LIMIT_ENABLED": update.screenshot_limit_enabled,
|
||||
"ARTEMIS_TASK_TIMEOUT_SECONDS": update.task_timeout_seconds,
|
||||
"ARTEMIS_OBSERVATION_TIMEOUT_SECONDS": update.observation_timeout_seconds,
|
||||
"ARTEMIS_OBSERVATION_MAX_ATTEMPTS": update.observation_max_attempts,
|
||||
"ARTEMIS_DEVICE_COMMAND_TIMEOUT_SECONDS": update.device_command_timeout_seconds,
|
||||
"ARTEMIS_ACTION_FAILURE_ATTEMPTS": update.action_failure_attempts,
|
||||
"ARTEMIS_WORKER_CLEANUP_TIMEOUT_SECONDS": update.worker_cleanup_timeout_seconds,
|
||||
}
|
||||
persist_environment({key: str(value).lower() for key, value in values.items()})
|
||||
for key, value in values.items():
|
||||
|
||||
@@ -22,7 +22,7 @@ from artemis.config import IMAGES_DIR, TRACES_PATH, WORKSPACE_ROOT
|
||||
from apps.admin_console.database.repositories.session_repository import SessionRepository
|
||||
from apps.admin_console.database.repositories.step_repository import StepRepository
|
||||
from apps.admin_console.services.automation_store import store, identifier
|
||||
from apps.admin_console.services.task_import import case_title
|
||||
from apps.admin_console.services.task_import import execution_title
|
||||
|
||||
EXPORT_ROOT = WORKSPACE_ROOT / "artifacts" / "reports"
|
||||
EXPORT_LOCK = threading.RLock()
|
||||
@@ -88,6 +88,10 @@ def failure_reason(directory: Path, status: str, recorded: str | None) -> str:
|
||||
)
|
||||
return safe[:500]
|
||||
|
||||
from apps.admin_console.services.automation_store import RECOVERY_ERRORS
|
||||
|
||||
if status == "completed" and recorded in RECOVERY_ERRORS:
|
||||
return ""
|
||||
if recorded:
|
||||
return redact(recorded)
|
||||
if status not in {"failed", "interrupted"}:
|
||||
@@ -95,6 +99,11 @@ def failure_reason(directory: Path, status: str, recorded: str | None) -> str:
|
||||
state = read_json(directory / "status.json", {})
|
||||
if isinstance(state, dict) and state.get("error"):
|
||||
return redact(state["error"])
|
||||
result = read_json(directory / "result.json", {})
|
||||
if isinstance(result, dict) and result.get("status") == "failed":
|
||||
reason = result.get("error") or result.get("explanation")
|
||||
if reason:
|
||||
return redact(reason)
|
||||
log_lines: list[str] = []
|
||||
for name in ("stdout.log", "stderr.log"):
|
||||
path = directory / name
|
||||
@@ -181,7 +190,9 @@ def session_report(session_id: str, db_path=None) -> dict:
|
||||
)
|
||||
return {
|
||||
"id": session_id,
|
||||
"name": case_title(case) or session.get("initial_goal", session_id)[:120],
|
||||
"name": execution_title(meta) or session.get("initial_goal", session_id)[:120],
|
||||
"iteration": meta.get("iteration", 1),
|
||||
"repeat_count": meta.get("repeat_count", 1),
|
||||
"goal": case.get("goal") or session.get("initial_goal", ""),
|
||||
"expected": case.get("expected", ""),
|
||||
"status": status,
|
||||
|
||||
@@ -42,6 +42,11 @@ class TaskOptions(BaseModel):
|
||||
max_retries: int | None = Field(default=None, ge=0, le=10)
|
||||
retry_interval_seconds: float | None = Field(default=None, ge=0, le=300)
|
||||
timeout_seconds: int | None = Field(default=None, ge=30, le=86400)
|
||||
observation_timeout_seconds: float | None = Field(default=None, gt=0, le=300)
|
||||
observation_max_attempts: int | None = Field(default=None, ge=1, le=5)
|
||||
device_command_timeout_seconds: float | None = Field(default=None, gt=0, le=60)
|
||||
action_failure_attempts: int | None = Field(default=None, ge=1, le=10)
|
||||
worker_cleanup_timeout_seconds: float | None = Field(default=None, gt=0, le=300)
|
||||
|
||||
|
||||
class TaskCase(BaseModel):
|
||||
@@ -184,3 +189,11 @@ def case_title(case: dict) -> str:
|
||||
case_id = str(case.get("case_id") or "").strip()
|
||||
name = str(case.get("name") or "").strip()
|
||||
return " ".join(part for part in (case_id, name) if part)
|
||||
|
||||
|
||||
def execution_title(job: dict) -> str:
|
||||
"""Distinguish repeated executions without altering the original case or prompt."""
|
||||
title = case_title(job.get("case") or {})
|
||||
if job.get("repeat_count", 1) > 1:
|
||||
title += f" · 第 {job['iteration']} / {job['repeat_count']} 轮"
|
||||
return title
|
||||
@@ -581,6 +581,10 @@ class TaskQueueService:
|
||||
"retry_interval_seconds": "OPENAI_RETRY_INTERVAL_SECONDS",
|
||||
"record_video": "ARTEMIS_RECORDING_ENABLED",
|
||||
"analyze_video": "ARTEMIS_VIDEO_ENABLED",
|
||||
"observation_timeout_seconds": "ARTEMIS_OBSERVATION_TIMEOUT_SECONDS",
|
||||
"observation_max_attempts": "ARTEMIS_OBSERVATION_MAX_ATTEMPTS",
|
||||
"device_command_timeout_seconds": "ARTEMIS_DEVICE_COMMAND_TIMEOUT_SECONDS",
|
||||
"action_failure_attempts": "ARTEMIS_ACTION_FAILURE_ATTEMPTS",
|
||||
}.items():
|
||||
if overrides.get(option) is not None:
|
||||
env[variable] = (
|
||||
@@ -630,6 +634,72 @@ class TaskQueueService:
|
||||
env["RESULTS_OUTPUT_PATH"] = str(TRACES_PATH / str(sess_id) / "result.json")
|
||||
return cmd, env
|
||||
|
||||
@classmethod
|
||||
async def _await_worker_with_budget(cls, proc, task_item: dict, run_key: str) -> int:
|
||||
from artemis.runtime.task_limits import ExecutionBudget, task_timeout
|
||||
from artemis.config.settings import settings
|
||||
from artemis.runtime.task_result import save_failure_result, read_worker_outcome
|
||||
from artemis.runtime.task_control import read_state
|
||||
from apps.admin_console.services.automation_store import store
|
||||
|
||||
sid = str(task_item.get("session_id") or run_key)
|
||||
job = store.job(sid)
|
||||
batch = store.get("batch", job["batch_id"]) if job and job.get("batch_id") else None
|
||||
limit = task_timeout(task_item, job, batch)
|
||||
budget = ExecutionBudget(limit)
|
||||
cleanup_limit = (task_item.get("runtime_overrides") or {}).get(
|
||||
"worker_cleanup_timeout_seconds"
|
||||
) or settings.ARTEMIS_WORKER_CLEANUP_TIMEOUT_SECONDS
|
||||
finalized_at = None
|
||||
waiter = asyncio.create_task(cls._wait_for_worker_process(proc))
|
||||
try:
|
||||
while True:
|
||||
done, _ = await asyncio.wait({waiter}, timeout=0.25)
|
||||
if waiter in done:
|
||||
return waiter.result()
|
||||
outcome = read_worker_outcome(sid)
|
||||
if outcome:
|
||||
finalized_at = finalized_at if finalized_at is not None else time.monotonic()
|
||||
if time.monotonic() - finalized_at >= cleanup_limit:
|
||||
logger.warning(
|
||||
"%s: task finalized but worker cleanup exceeded %s seconds; reclaiming process",
|
||||
sid,
|
||||
cleanup_limit,
|
||||
)
|
||||
await cls._terminate_worker_process(proc)
|
||||
return await waiter
|
||||
continue # Final result is authoritative; only bound resource cleanup now.
|
||||
cls._sync_control_states()
|
||||
run = state.active_runs.get(run_key, {})
|
||||
remaining = budget.update(
|
||||
excluded=bool(run.get("parked")) or read_state(sid).get("status") == "queued"
|
||||
)
|
||||
if remaining > 0:
|
||||
continue
|
||||
error = f"任务执行超时({limit} 秒,不含暂停/排队时间)"
|
||||
task_item.update(timed_out=True, error=error)
|
||||
logger.error("%s: %s", sid, error)
|
||||
try:
|
||||
latest = store.job(sid)
|
||||
if latest:
|
||||
latest.update(timed_out=True, error=error)
|
||||
store.save_job(latest)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Cannot persist timeout for %s; terminating worker anyway", sid
|
||||
)
|
||||
await cls._terminate_worker_process(proc)
|
||||
returncode = await waiter
|
||||
try:
|
||||
await asyncio.to_thread(save_failure_result, sid, error, code="task_timeout")
|
||||
except OSError:
|
||||
logger.exception("Cannot save timeout report for %s", sid)
|
||||
return returncode
|
||||
finally:
|
||||
if not waiter.done():
|
||||
waiter.cancel()
|
||||
await asyncio.gather(waiter, return_exceptions=True)
|
||||
|
||||
@classmethod
|
||||
def _register_worker_run(
|
||||
cls,
|
||||
@@ -721,6 +791,10 @@ class TaskQueueService:
|
||||
returncode,
|
||||
manual_stop,
|
||||
)
|
||||
from apps.admin_console.services.automation_store import store
|
||||
|
||||
if (store.job(str(sess_id)) or {}).get("timed_out"):
|
||||
new_status, should_persist = "failed", True
|
||||
if (
|
||||
state.is_shutting_down
|
||||
and not manual_stop
|
||||
@@ -943,7 +1017,7 @@ class TaskQueueService:
|
||||
await cls._terminate_if_cancelled_during_launch(run_key, sess_id, proc)
|
||||
|
||||
# 3. Await subprocess completion
|
||||
returncode = await cls._wait_for_worker_process(proc)
|
||||
returncode = await cls._await_worker_with_budget(proc, task_item, run_key)
|
||||
print(f"[QueueWorker] Task [{sess_id}] exited with returncode {returncode}")
|
||||
|
||||
manual_stop = run_key in state.manually_stopped_run_ids or bool(
|
||||
@@ -1141,6 +1215,12 @@ class TaskQueueService:
|
||||
forwarded to the worker as ``--verification-level`` / ``--explorer-pro-mode``;
|
||||
they are normalised here so the queue item and the CLI see one spelling.
|
||||
"""
|
||||
if runtime_overrides:
|
||||
profile = runtime_overrides.get("profile") or profile
|
||||
device_serial = runtime_overrides.get("device_serial") or device_serial
|
||||
locked_app_package = runtime_overrides.get("locked_app_package") or locked_app_package
|
||||
verification_level = runtime_overrides.get("verification_level") or verification_level
|
||||
explorer_mode = runtime_overrides.get("explorer_mode") or explorer_mode
|
||||
verification_level = (
|
||||
str(verification_level).strip().lower() or None if verification_level else None
|
||||
)
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "artemis-showcase-ui",
|
||||
"version": "1.3.0",
|
||||
"version": "1.4.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "artemis-showcase-ui",
|
||||
"version": "1.3.0",
|
||||
"version": "1.4.0",
|
||||
"dependencies": {
|
||||
"@angular/cdk": "^22.1.5",
|
||||
"@angular/common": "^22.1.4",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "artemis-showcase-ui",
|
||||
"version": "1.3.0",
|
||||
"version": "1.4.0",
|
||||
"scripts": {
|
||||
"ng": "ng",
|
||||
"start": "ng serve --proxy-config proxy.conf.json",
|
||||
|
||||
+20
-5
@@ -47,26 +47,41 @@
|
||||
<section><h3>导入任务</h3><p>每行一个用例,仅「Artemis提示词」作为任务正文;「任务配置(JSON)」可设置每项模型、模式、超时和录屏。「前置约束提取」仅供查看与搜索。示例在模板的「填写说明」页。</p>
|
||||
<div class="actions"><a href="/api/automation/template">下载 Excel 模板</a><label class="upload">导入 Excel<input type="file" accept=".xlsx" [disabled]="busy()" (change)="upload($event)"></label></div>
|
||||
@if(preview(); as p) {
|
||||
<p>有效任务 {{p.tasks.length}} 条 · 错误 {{p.errors.length}} 条</p>
|
||||
<div class="selection-toolbar"><span>已选 <strong>{{selectedCount()}}</strong> / {{p.tasks.length}} 个用例 · 错误 {{p.errors.length}} 条</span><button type="button" [disabled]="busy() || !p.tasks.length" (click)="toggleAllRows()">{{selectedCount() === p.tasks.length ? '全不选' : '全选'}}</button></div>
|
||||
@for(e of p.errors; track e.row){<p class="error">第 {{e.row}} 行:{{e.message}}</p>}
|
||||
<div class="table-wrap"><table><thead><tr><th>行</th><th>用例</th><th>提示词</th><th>任务配置</th></tr></thead><tbody>@for(t of p.tasks; track t.row){<tr><td>{{t.row}}</td><td>{{t.name}}</td><td>{{t.goal}}</td><td>{{t.task_config | json}}</td></tr>}</tbody></table></div>
|
||||
<div class="case-preview-list" aria-label="选择导入用例">
|
||||
@for(t of p.tasks; track t.row){
|
||||
<div class="case-preview" [class.unselected]="!selectedRows().has(t.row)">
|
||||
<span class="selection-column"><input type="checkbox" [checked]="selectedRows().has(t.row)" [disabled]="busy()" (change)="toggleRow(t.row)" [attr.aria-label]="'导入用例:' + (t.case_id ? t.case_id + ' ' : '') + t.name"></span>
|
||||
<div class="case-preview-content"><strong>{{t.case_id ? t.case_id + ' ' : ''}}{{t.name}}</strong><small>第 {{t.row}} 行</small>
|
||||
<p class="case-goal" [title]="t.goal">{{t.goal}}</p>
|
||||
@if(caseConfig(t.task_config); as config){<details><summary>自定义参数</summary><pre>{{config}}</pre></details>}@else{<small>使用批次 / 全局参数</small>}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
<label>批次名称<input [(ngModel)]="name" maxlength="200"></label>
|
||||
<div class="fields"><label>执行模式<select [(ngModel)]="profile"><option value="flash">Flash</option><option value="pro">Pro</option></select></label><label>单任务时限(秒)<input type="number" min="30" max="86400" [(ngModel)]="timeout"></label></div>
|
||||
<label for="batch-repeat-count">整批循环次数<input id="batch-repeat-count" type="number" min="1" [max]="maxExecutions" step="1" [(ngModel)]="repeatCount"></label>
|
||||
<p class="execution-summary">{{selectedCount()}} 个用例 × {{repeatCount || 0}} 轮,共 {{selectedCount() * (repeatCount || 0)}} 次执行</p>
|
||||
<p class="muted">每轮按表格顺序执行所选用例,分别保存结果。未勾选用例不会导入。</p>
|
||||
@if(!validRepetitions()){<p class="error">循环次数须为正整数,执行总数不超过 {{maxExecutions}}。</p>}
|
||||
<label><input type="checkbox" [(ngModel)]="stopOnFailure"> 失败即停止后续任务(默认继续)</label>
|
||||
<label><input type="checkbox" [(ngModel)]="word"> Word</label><label><input type="checkbox" [(ngModel)]="excel"> Excel</label>
|
||||
<button class="primary" [disabled]="busy() || !p.valid || !device || !name.trim() || !formats().length" (click)="startBatch()">确认导入并开始执行</button>
|
||||
<button class="primary" [disabled]="busy() || !p.valid || !selectedCount() || !validRepetitions() || !device || !name.trim() || !formats().length" (click)="startBatch()">确认导入并开始执行</button>
|
||||
}
|
||||
</section>
|
||||
<section><h3>批次记录</h3>
|
||||
@for(b of batches(); track b.id){
|
||||
<div class="batch-record">
|
||||
<button class="record" [class.selected]="batch()?.id === b.id" (click)="selectBatch(b.id)"><strong>{{b.name}}</strong><span>{{label(b.status)}} · {{b.created_at*1000 | date:'MM-dd HH:mm'}}</span></button>
|
||||
<button class="record" [class.selected]="batch()?.id === b.id" (click)="selectBatch(b.id)"><strong>{{b.name}}</strong><span>{{label(b.status)}} · {{b.created_at*1000 | date:'MM-dd HH:mm'}} · {{b.repeat_count || 1}} 轮@if(b.total_executions){ · {{b.total_executions}} 次执行}</span></button>
|
||||
<button class="delete-batch" type="button" [disabled]="busy() || b.status === 'running'" (click)="deleteBatch(b)" [attr.aria-label]="'删除批次:' + b.name" [title]="b.status === 'running' ? '执行中的批次不能删除' : '删除批次及其任务、报告和文件'"><span class="material-symbols-outlined">delete_outline</span></button>
|
||||
</div>
|
||||
}
|
||||
@if(!batches().length){<p>暂无批次。</p>}
|
||||
</section>
|
||||
@if(batch(); as b){<section><h3>{{b.name}}</h3><p>{{label(b.status)}} · {{b.reason}}</p>
|
||||
<p class="execution-summary">{{b.case_count || b.jobs?.length || 0}} 个用例 · {{b.repeat_count || 1}} 轮 · 共 {{b.total_executions || b.jobs?.length || 0}} 次执行</p>
|
||||
<div class="actions">
|
||||
@if(b.status === 'running'){<button [disabled]="busy()" (click)="batchAction('pause')">暂停后续任务</button>}
|
||||
@if(b.status === 'draft' || b.status === 'paused'){<button [disabled]="busy()" (click)="batchAction('resume')">{{b.status === 'draft' ? '开始执行' : '继续未开始任务'}}</button>}
|
||||
@@ -87,6 +102,6 @@
|
||||
</div>
|
||||
}
|
||||
@if(b.report_error){<p class="error">报告生成失败:{{b.report_error}}</p>}
|
||||
@for(j of b.jobs; track j.session_id){<div class="job"><button (click)="agent.selectSession(j.session_id,true); tab.set('reports')" [title]="j.case.goal">{{j.case.case_id ? j.case.case_id + ' ' : ''}}{{j.case.name}}</button><span>{{label(j.status)}}</span>@if(j.error){<small>{{j.error}}</small>}</div>}
|
||||
@for(j of b.jobs; track j.session_id){<div class="job"><button (click)="agent.selectSession(j.session_id,true); tab.set('reports')" [title]="j.case.goal">{{j.case.case_id ? j.case.case_id + ' ' : ''}}{{j.case.name}}@if(j.repeat_count > 1){ · 第 {{j.iteration}} / {{j.repeat_count}} 轮}</button><span>{{label(j.status)}}</span>@if(j.error){<small>{{j.error}}</small>}</div>}
|
||||
</section>}
|
||||
}
|
||||
@@ -16,6 +16,13 @@ input:not([type=checkbox]):not([type=file]),select,textarea{box-sizing:border-bo
|
||||
input[type=checkbox]{width:15px;height:15px;accent-color:#2563eb;vertical-align:-3px;margin-right:6px;}
|
||||
.upload{position:relative;margin:0;color:#fff;background:#2563eb;border-color:#2563eb;}.upload:hover{background:#1d4ed8;border-color:#1d4ed8;}.upload input{position:absolute;inset:0;width:100%;height:100%;opacity:0;cursor:pointer;}
|
||||
.device{background:#f8fafc;padding:12px 16px;}.device label{margin:0;}
|
||||
.selection-toolbar{display:flex;align-items:center;justify-content:space-between;gap:8px;margin:12px 0;color:#475569;}
|
||||
.selection-column{flex:0 0 18px;text-align:center;}.selection-column input{margin:0;}
|
||||
.case-preview-list{max-height:320px;overflow:auto;border:1px solid #e2e8f0;border-radius:8px;margin-bottom:14px;}
|
||||
.case-preview{display:flex;align-items:flex-start;gap:10px;padding:12px;border-bottom:1px solid #e2e8f0;&:last-child{border-bottom:0;}&.unselected{background:#f8fafc;color:#64748b;}}
|
||||
.case-preview-content{min-width:0;flex:1;strong{display:block;overflow-wrap:anywhere;}small{display:block;}details{margin:5px 0 0;}summary{padding:0;font-size:12px;color:#2563eb;}pre{max-height:160px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere;background:#f8fafc;border-radius:6px;padding:8px;font-size:11px;}}
|
||||
.case-goal{display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2;overflow:hidden;white-space:pre-wrap;margin:5px 0;font-size:12px;}
|
||||
.execution-summary{padding:9px 12px;border-radius:8px;background:#eff6ff;color:#1d4ed8;font-weight:500;}
|
||||
.record{display:flex;width:100%;text-align:left;align-items:flex-start;flex-direction:column;gap:4px;margin:8px 0 0;padding:12px;overflow-wrap:anywhere;}.record span{color:#64748b;font-size:12px;font-weight:400;}.record.selected{border-color:#93c5fd;background:#eff6ff;}.record.selected strong{color:#1d4ed8;}
|
||||
.batch-record{display:flex;gap:8px;align-items:stretch;margin-top:8px;}.batch-record .record{flex:1;min-width:0;width:auto;margin:0;}.batch-record .delete-batch{flex:0 0 40px;min-width:40px;padding:0;color:#b91c1c;}.batch-record .delete-batch:hover:not(:disabled){background:#fff1f2;border-color:#fda4af;}.batch-record .delete-batch .material-symbols-outlined{font-size:19px;}
|
||||
.archive-progress{margin:12px 0;padding:11px 13px;border:1px solid #bfdbfe;border-radius:10px;background:#f8fbff;color:#1e40af;}
|
||||
|
||||
+55
@@ -22,6 +22,7 @@ describe('AutomationPanelComponent batch deletion', () => {
|
||||
http.delete.and.returnValue(of({ status: 'deleted' }));
|
||||
http.post.and.returnValue(of({ status: 'ready', stage: '报告包已就绪', completed: 0, total: 0, elapsed_seconds: 0, eta_seconds: null, error: null }));
|
||||
http.delete.calls.reset();
|
||||
http.post.calls.reset();
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [AutomationPanelComponent],
|
||||
providers: [
|
||||
@@ -32,6 +33,60 @@ describe('AutomationPanelComponent batch deletion', () => {
|
||||
}).compileComponents();
|
||||
});
|
||||
|
||||
it('selects all imported cases by default, toggles all and submits only checked cases with rounds', async () => {
|
||||
const tasks = [
|
||||
{ row: 2, case_id: '1.1', name: '打开设置', goal: '观察设置', task_config: { model: 'mimo-v2.6-pro' } },
|
||||
{ row: 3, case_id: '1.2', name: '观察首页', goal: '观察首页', task_config: {} }
|
||||
];
|
||||
(http.post.and as any).callFake((url: string) => of(url.endsWith('/preview')
|
||||
? { valid: true, tasks, errors: [] } : url.endsWith('/batches')
|
||||
? { id: 'selected-batch', status: 'draft' } : { id: 'selected-batch', status: 'running' }));
|
||||
const fixture = TestBed.createComponent(AutomationPanelComponent);
|
||||
const component = fixture.componentInstance;
|
||||
component.tab.set('batches');
|
||||
component.upload({ target: { files: [new File(['test'], '用例.xlsx')] } } as unknown as Event);
|
||||
await new Promise<void>(resolve => setTimeout(resolve, 0));
|
||||
fixture.detectChanges();
|
||||
const checkboxes = () => [...fixture.nativeElement.querySelectorAll('.selection-column input')] as HTMLInputElement[];
|
||||
expect(checkboxes().every(c => c.checked)).toBeTrue();
|
||||
const toggle = fixture.nativeElement.querySelector('.selection-toolbar button') as HTMLButtonElement;
|
||||
expect(toggle.textContent).toContain('全不选');
|
||||
toggle.click(); fixture.detectChanges();
|
||||
expect(component.selectedCount()).toBe(0);
|
||||
expect((fixture.nativeElement.querySelector('.primary') as HTMLButtonElement).disabled).toBeTrue();
|
||||
expect(toggle.textContent).toContain('全选');
|
||||
toggle.click(); fixture.detectChanges();
|
||||
expect(component.selectedCount()).toBe(2);
|
||||
checkboxes()[1].click();
|
||||
component.repeatCount = 3; component.device = 'test-device';
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('.execution-summary').textContent).toContain('共 3 次执行');
|
||||
component.startBatch();
|
||||
await new Promise<void>(resolve => setTimeout(resolve, 0));
|
||||
const request = http.post.calls.allArgs().find(args => args[0] === '/api/automation/batches');
|
||||
expect(request?.[1]).toEqual(jasmine.objectContaining({
|
||||
cases: [{ case_id: '1.1', name: '打开设置', goal: '观察设置', task_config: { model: 'mimo-v2.6-pro' } }],
|
||||
repeat_count: 3, device_serial: 'test-device'
|
||||
}));
|
||||
});
|
||||
|
||||
it('rejects empty selections and invalid or excessive loop counts without creating a batch', async () => {
|
||||
const fixture = TestBed.createComponent(AutomationPanelComponent);
|
||||
const component = fixture.componentInstance;
|
||||
component.preview.set({ valid: true, tasks: [{ row: 2, name: '检查', goal: '观察' }], errors: [] });
|
||||
component.device = 'test-device';
|
||||
component.startBatch();
|
||||
await new Promise<void>(resolve => setTimeout(resolve, 0));
|
||||
expect(component.error()).toContain('至少勾选');
|
||||
component.selectedRows.set(new Set([2]));
|
||||
for (const count of [0, 1.5, 10001]) {
|
||||
component.repeatCount = count; component.startBatch();
|
||||
await new Promise<void>(resolve => setTimeout(resolve, 0));
|
||||
expect(component.error()).toContain('循环次数');
|
||||
}
|
||||
expect(http.post).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('confirms deletion and removes the batch from the visible list', async () => {
|
||||
const fixture = TestBed.createComponent(AutomationPanelComponent);
|
||||
fixture.componentInstance.tab.set('batches');
|
||||
|
||||
@@ -25,6 +25,8 @@ export class AutomationPanelComponent {
|
||||
agent = inject(AgentService); system = inject(SystemService); http = inject(HttpClient);
|
||||
tab = signal('reports'); error = signal(''); notice = signal(''); busy = signal(false);
|
||||
batches = signal<any[]>([]); preview = signal<any>(null);
|
||||
selectedRows = signal<Set<number>>(new Set());
|
||||
selectedCount = computed(() => this.selectedRows().size);
|
||||
batch = signal<any>(null); report = signal<any>(null);
|
||||
archiveProgress = signal<ArchiveProgress | null>(null);
|
||||
archiveBatchId = signal(''); archiveBusy = signal(false);
|
||||
@@ -37,10 +39,11 @@ export class AutomationPanelComponent {
|
||||
});
|
||||
liveTask = computed(() => ['running', 'paused', 'task_paused', 'resuming'].includes(this.taskStatus()));
|
||||
word = true; excel = true; name = ''; device = ''; profile = 'flash'; stopOnFailure = false; timeout = 1800;
|
||||
repeatCount = 1; maxExecutions = 10000;
|
||||
private destroyed = false;
|
||||
constructor() {
|
||||
const destroy = inject(DestroyRef);
|
||||
this.http.get<any>('/api/automation/preferences').subscribe(p => { this.word = p.formats.includes('docx'); this.excel = p.formats.includes('xlsx'); this.timeout = p.batch_timeout_seconds || 1800; });
|
||||
this.http.get<any>('/api/automation/preferences').subscribe(p => { this.word = p.formats.includes('docx'); this.excel = p.formats.includes('xlsx'); this.timeout = p.batch_timeout_seconds || 1800; this.maxExecutions = p.batch_max_executions || 10000; });
|
||||
void this.refresh();
|
||||
const timer = setInterval(() => void this.refresh(), 5000);
|
||||
destroy.onDestroy(() => { this.destroyed = true; clearInterval(timer); });
|
||||
@@ -104,13 +107,32 @@ export class AutomationPanelComponent {
|
||||
savePreferences() { void this.action(async () => { if (!this.formats().length) throw Error('请至少选择一种报告格式'); await firstValueFrom(this.http.put('/api/automation/preferences',{formats:this.formats()})); this.notice.set('已保存,后续任务和批次使用此默认格式'); }); }
|
||||
upload(event: Event) {
|
||||
const file = (event.target as HTMLInputElement).files?.[0]; if (!file) return;
|
||||
void this.action(async () => { this.preview.set(null); const data = new FormData(); data.append('file',file); this.preview.set(await firstValueFrom(this.http.post('/api/automation/import/preview',data))); this.name = file.name.replace(/\.xlsx$/i,''); });
|
||||
void this.action(async () => { this.preview.set(null); this.selectedRows.set(new Set()); const data = new FormData(); data.append('file',file); const preview: any = await firstValueFrom(this.http.post('/api/automation/import/preview',data)); this.preview.set(preview); this.selectedRows.set(new Set<number>(preview.tasks.map((t: any) => t.row))); this.repeatCount = 1; this.name = file.name.replace(/\.xlsx$/i,''); });
|
||||
}
|
||||
toggleRow(row: number) {
|
||||
const selected = new Set(this.selectedRows());
|
||||
if (selected.has(row)) selected.delete(row); else selected.add(row);
|
||||
this.selectedRows.set(selected);
|
||||
}
|
||||
toggleAllRows() {
|
||||
const rows: number[] = (this.preview()?.tasks || []).map((t: any) => t.row);
|
||||
this.selectedRows.set(this.selectedCount() === rows.length ? new Set() : new Set(rows));
|
||||
}
|
||||
validRepetitions() {
|
||||
return Number.isInteger(this.repeatCount) && this.repeatCount >= 1
|
||||
&& this.selectedCount() * this.repeatCount <= this.maxExecutions;
|
||||
}
|
||||
caseConfig(config: Record<string, unknown> | undefined) {
|
||||
const overrides = Object.fromEntries(Object.entries(config || {}).filter(([, value]) => value !== null && value !== undefined));
|
||||
return Object.keys(overrides).length ? JSON.stringify(overrides, null, 2) : '';
|
||||
}
|
||||
startBatch() { void this.action(async () => {
|
||||
if (!this.preview()?.valid) throw Error('请先导入并修正所有错误');
|
||||
if (!this.selectedCount()) throw Error('请至少勾选一个用例');
|
||||
if (!this.validRepetitions()) throw Error(`循环次数必须为正整数,执行总数不能超过 ${this.maxExecutions}`);
|
||||
if (!this.device) throw Error('请选择执行设备');
|
||||
const cases = this.preview().tasks.map(({row, ...c}: any) => c);
|
||||
const created: any = await firstValueFrom(this.http.post('/api/automation/batches',{name:this.name.trim(),cases,device_serial:this.device,profile:this.profile,stop_on_failure:this.stopOnFailure,timeout_seconds:this.timeout,formats:this.formats()}));
|
||||
const cases = this.preview().tasks.filter((t: any) => this.selectedRows().has(t.row)).map(({row, ...c}: any) => c);
|
||||
const created: any = await firstValueFrom(this.http.post('/api/automation/batches',{name:this.name.trim(),cases,repeat_count:this.repeatCount,device_serial:this.device,profile:this.profile,stop_on_failure:this.stopOnFailure,timeout_seconds:this.timeout,formats:this.formats()}));
|
||||
this.batch.set(created);
|
||||
await firstValueFrom(this.http.post(`/api/automation/batches/${created.id}/resume`,{}));
|
||||
this.preview.set(null); this.notice.set('批次已开始,可暂停或查看每项结果'); await this.refresh();
|
||||
|
||||
+2
@@ -338,6 +338,8 @@ limitations under the License.
|
||||
playsinline
|
||||
(loadedmetadata)="onLoadedMetadata()"
|
||||
(timeupdate)="onTimeUpdate()"
|
||||
(seeked)="onSeeked()"
|
||||
(emptied)="onPause()"
|
||||
(play)="onPlay()"
|
||||
(pause)="onPause()"
|
||||
(ended)="onEnded()"
|
||||
|
||||
+202
-5
@@ -1,17 +1,26 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
import { signal } from '@angular/core';
|
||||
import { AgentService } from '../../services/agent.service';
|
||||
import { StepReplayFrame } from '../../core/models/stream.model';
|
||||
import { FloatingVideoPlayerComponent } from './floating-video-player.component';
|
||||
|
||||
describe('FloatingVideoPlayerComponent video markers', () => {
|
||||
it('shows a recorded step on the video timeline and seeks when clicked', () => {
|
||||
let fixture: ComponentFixture<FloatingVideoPlayerComponent>;
|
||||
let component: FloatingVideoPlayerComponent;
|
||||
let video: HTMLVideoElement;
|
||||
let paused: boolean;
|
||||
let seeking: boolean;
|
||||
let time: number;
|
||||
let play: jasmine.Spy;
|
||||
let agentService: ReturnType<typeof createAgentService>;
|
||||
|
||||
function createAgentService() {
|
||||
const start = 1_800_000_000;
|
||||
const frame: StepReplayFrame = {
|
||||
index: 0, stepNumber: 1, title: '步骤 1: 点击设置', imageUrl: 'step.png',
|
||||
actionText: '点击设置', timestamp: start + 5
|
||||
};
|
||||
const agentService = {
|
||||
return {
|
||||
isVideoWindowOpen: signal(true),
|
||||
isVideoMinimized: signal(false),
|
||||
recordingPlaybackStatus: signal('ready'),
|
||||
@@ -25,15 +34,57 @@ describe('FloatingVideoPlayerComponent video markers', () => {
|
||||
currentSession: signal({ session_id: 'test', start_time: start }),
|
||||
currentSessionId: signal('test'),
|
||||
videoSeekRequest: signal(null),
|
||||
stepSeekRequest: signal(null)
|
||||
stepSeekRequest: signal(null),
|
||||
consumeVideoAutoplay: jasmine.createSpy('consumeVideoAutoplay').and.returnValue(false)
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
agentService = createAgentService();
|
||||
TestBed.configureTestingModule({
|
||||
imports: [FloatingVideoPlayerComponent],
|
||||
providers: [{ provide: AgentService, useValue: agentService }]
|
||||
});
|
||||
|
||||
const fixture = TestBed.createComponent(FloatingVideoPlayerComponent);
|
||||
fixture = TestBed.createComponent(FloatingVideoPlayerComponent);
|
||||
fixture.detectChanges();
|
||||
component = fixture.componentInstance;
|
||||
video = component.videoRef!.nativeElement;
|
||||
paused = true;
|
||||
seeking = false;
|
||||
time = 0;
|
||||
Object.defineProperties(video, {
|
||||
paused: { configurable: true, get: () => paused },
|
||||
seeking: { configurable: true, get: () => seeking },
|
||||
ended: { configurable: true, get: () => false },
|
||||
duration: { configurable: true, get: () => 20 },
|
||||
currentTime: {
|
||||
configurable: true, get: () => time,
|
||||
set: (value: number) => { time = value; seeking = true; }
|
||||
}
|
||||
});
|
||||
spyOn(video, 'pause').and.callFake(() => {
|
||||
paused = true;
|
||||
video.dispatchEvent(new Event('pause'));
|
||||
});
|
||||
play = spyOn(video, 'play').and.callFake(() => {
|
||||
paused = false;
|
||||
video.dispatchEvent(new Event('play'));
|
||||
return Promise.resolve();
|
||||
});
|
||||
});
|
||||
|
||||
function finishSeek(): void {
|
||||
seeking = false;
|
||||
video.dispatchEvent(new Event('seeked'));
|
||||
fixture.detectChanges();
|
||||
}
|
||||
|
||||
function playButton(): HTMLButtonElement {
|
||||
return fixture.nativeElement.querySelector('.play-btn');
|
||||
}
|
||||
|
||||
it('shows a recorded step on the video timeline and seeks when clicked', () => {
|
||||
const marker = fixture.nativeElement.querySelector('.video-marker') as HTMLButtonElement;
|
||||
expect(marker).not.toBeNull();
|
||||
expect(marker.getAttribute('aria-label')).toContain('步骤 1');
|
||||
@@ -43,4 +94,150 @@ describe('FloatingVideoPlayerComponent video markers', () => {
|
||||
marker.click();
|
||||
expect(seek).toHaveBeenCalledOnceWith(5);
|
||||
});
|
||||
|
||||
it('resumes a playing video after a marker seek finishes and synchronizes the button', async () => {
|
||||
component.togglePlay();
|
||||
await Promise.resolve();
|
||||
play.calls.reset();
|
||||
fixture.nativeElement.querySelector('.video-marker').click();
|
||||
expect(time).toBe(5);
|
||||
expect(play).not.toHaveBeenCalled();
|
||||
finishSeek();
|
||||
await Promise.resolve();
|
||||
fixture.detectChanges();
|
||||
expect(paused).toBeFalse();
|
||||
expect(play).toHaveBeenCalledTimes(1);
|
||||
expect(playButton().title).toBe('暂停');
|
||||
});
|
||||
|
||||
it('keeps a paused video paused after a marker seek and resumes with one click', async () => {
|
||||
fixture.nativeElement.querySelector('.video-marker').click();
|
||||
finishSeek();
|
||||
expect(paused).toBeTrue();
|
||||
expect(play).not.toHaveBeenCalled();
|
||||
expect(playButton().title).toBe('播放');
|
||||
playButton().click();
|
||||
await Promise.resolve();
|
||||
fixture.detectChanges();
|
||||
expect(paused).toBeFalse();
|
||||
expect(playButton().title).toBe('暂停');
|
||||
});
|
||||
|
||||
it('preserves playing intent across rapid consecutive marker seeks', () => {
|
||||
component.togglePlay();
|
||||
component.seek(5);
|
||||
component.seek(8);
|
||||
play.calls.reset();
|
||||
finishSeek();
|
||||
expect(time).toBe(8);
|
||||
expect(play).toHaveBeenCalledTimes(1);
|
||||
expect(paused).toBeFalse();
|
||||
});
|
||||
|
||||
it('honors play and pause clicks while the destination is still seeking', () => {
|
||||
component.togglePlay();
|
||||
component.seek(5);
|
||||
play.calls.reset();
|
||||
fixture.detectChanges();
|
||||
expect(playButton().title).toBe('播放');
|
||||
playButton().click();
|
||||
fixture.detectChanges();
|
||||
expect(playButton().title).toBe('暂停');
|
||||
expect(play).not.toHaveBeenCalled();
|
||||
playButton().click();
|
||||
finishSeek();
|
||||
expect(paused).toBeTrue();
|
||||
expect(play).not.toHaveBeenCalled();
|
||||
expect(playButton().title).toBe('播放');
|
||||
});
|
||||
|
||||
it('waits for the destination segment to seek before resuming playback', () => {
|
||||
agentService.activeVideoSegments.set([
|
||||
{ url: '/test.mp4', start: 0, duration: 20, width: 400, height: 800 },
|
||||
{ url: '/second.mp4', start: 20, duration: 20, width: 400, height: 800 }
|
||||
]);
|
||||
fixture.detectChanges();
|
||||
component.togglePlay();
|
||||
component.seek(25);
|
||||
play.calls.reset();
|
||||
fixture.detectChanges();
|
||||
video.dispatchEvent(new Event('loadedmetadata'));
|
||||
expect(component.activeSegmentIndex()).toBe(1);
|
||||
expect(time).toBe(5);
|
||||
expect(play).not.toHaveBeenCalled();
|
||||
finishSeek();
|
||||
expect(play).toHaveBeenCalledTimes(1);
|
||||
expect(paused).toBeFalse();
|
||||
expect(component.currentTime()).toBe(25);
|
||||
});
|
||||
|
||||
it('keeps a paused video paused when jumping to another segment', () => {
|
||||
agentService.activeVideoSegments.set([
|
||||
{ url: '/test.mp4', start: 0, duration: 20, width: 400, height: 800 },
|
||||
{ url: '/second.mp4', start: 20, duration: 20, width: 400, height: 800 }
|
||||
]);
|
||||
fixture.detectChanges();
|
||||
component.seek(25);
|
||||
fixture.detectChanges();
|
||||
video.dispatchEvent(new Event('loadedmetadata'));
|
||||
finishSeek();
|
||||
expect(time).toBe(5);
|
||||
expect(paused).toBeTrue();
|
||||
expect(play).not.toHaveBeenCalled();
|
||||
expect(playButton().title).toBe('播放');
|
||||
});
|
||||
|
||||
it('resumes after seeking a recording without a segment manifest', () => {
|
||||
agentService.activeVideoSegments.set([]);
|
||||
fixture.detectChanges();
|
||||
video.dispatchEvent(new Event('loadedmetadata'));
|
||||
component.togglePlay();
|
||||
component.seek(5);
|
||||
play.calls.reset();
|
||||
finishSeek();
|
||||
expect(time).toBe(5);
|
||||
expect(component.currentTime()).toBe(5);
|
||||
expect(paused).toBeFalse();
|
||||
expect(play).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('resets a rejected play request so a single subsequent click can resume', async () => {
|
||||
play.and.callFake(() => {
|
||||
paused = false;
|
||||
video.dispatchEvent(new Event('play'));
|
||||
return Promise.reject(new DOMException('Interrupted', 'AbortError'));
|
||||
});
|
||||
component.seek(5, true);
|
||||
finishSeek();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
fixture.detectChanges();
|
||||
expect(paused).toBeTrue();
|
||||
expect(playButton().title).toBe('播放');
|
||||
play.and.callFake(() => {
|
||||
paused = false;
|
||||
video.dispatchEvent(new Event('play'));
|
||||
return Promise.resolve();
|
||||
});
|
||||
playButton().click();
|
||||
await Promise.resolve();
|
||||
fixture.detectChanges();
|
||||
expect(paused).toBeFalse();
|
||||
expect(playButton().title).toBe('暂停');
|
||||
});
|
||||
|
||||
it('ignores an older aborted play request after a newer seek resumes', async () => {
|
||||
let rejectOldPlay!: (reason: unknown) => void;
|
||||
play.and.returnValue(new Promise<void>((_, reject) => { rejectOldPlay = reject; }));
|
||||
component.togglePlay();
|
||||
paused = false;
|
||||
component.seek(5);
|
||||
play.and.callFake(() => { paused = false; return Promise.resolve(); });
|
||||
finishSeek();
|
||||
rejectOldPlay(new DOMException('Interrupted', 'AbortError'));
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
expect(paused).toBeFalse();
|
||||
expect(component.isPlaying()).toBeTrue();
|
||||
});
|
||||
});
|
||||
+93
-28
@@ -71,6 +71,8 @@ export class FloatingVideoPlayerComponent implements OnDestroy {
|
||||
private pendingLocalTime: number | null = null;
|
||||
private pendingAutoplay = false;
|
||||
private pendingAbsoluteSeek: number | null = null;
|
||||
private seekPlaybackIntent: boolean | null = null;
|
||||
private playRequestId = 0;
|
||||
|
||||
// Step Replay state signals
|
||||
public activeStepIndex = signal<number>(0);
|
||||
@@ -138,6 +140,10 @@ export class FloatingVideoPlayerComponent implements OnDestroy {
|
||||
this.currentTime.set(0);
|
||||
this.duration.set(segments.reduce((sum, segment) => sum + segment.duration, 0));
|
||||
this.isPlaying.set(false);
|
||||
this.pendingLocalTime = null;
|
||||
this.pendingAutoplay = false;
|
||||
this.seekPlaybackIntent = null;
|
||||
this.playRequestId++;
|
||||
},
|
||||
{ allowSignalWrites: true }
|
||||
);
|
||||
@@ -315,20 +321,19 @@ export class FloatingVideoPlayerComponent implements OnDestroy {
|
||||
// that segment's metadata event apply pendingLocalTime.
|
||||
if (this.pendingLocalTime !== null) return;
|
||||
}
|
||||
if (this.pendingLocalTime !== null) {
|
||||
v.currentTime = Math.max(0, Math.min(v.duration || this.pendingLocalTime, this.pendingLocalTime));
|
||||
this.pendingLocalTime = null;
|
||||
}
|
||||
if (this.pendingAutoplay) {
|
||||
this.pendingAutoplay = false;
|
||||
v.play().catch(() => {});
|
||||
}
|
||||
if (this.agentService.consumeVideoAutoplay()) {
|
||||
const autoplay = this.agentService.consumeVideoAutoplay();
|
||||
if (autoplay) {
|
||||
this.isMuted.set(true);
|
||||
v.muted = true;
|
||||
v.play().catch(() => {
|
||||
this.isPlaying.set(false);
|
||||
});
|
||||
}
|
||||
const shouldPlay = this.pendingAutoplay || autoplay;
|
||||
this.pendingAutoplay = false;
|
||||
if (this.pendingLocalTime !== null) {
|
||||
const localTime = Math.max(0, Math.min(v.duration || this.pendingLocalTime, this.pendingLocalTime));
|
||||
this.pendingLocalTime = null;
|
||||
this.seekWithinVideo(localTime, shouldPlay);
|
||||
} else if (shouldPlay) {
|
||||
this.playVideo();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -346,14 +351,28 @@ export class FloatingVideoPlayerComponent implements OnDestroy {
|
||||
}
|
||||
|
||||
public onPlay(): void {
|
||||
this.isPlaying.set(true);
|
||||
this.isPlaying.set(!this.videoRef?.nativeElement.paused);
|
||||
}
|
||||
|
||||
public onPause(): void {
|
||||
this.isPlaying.set(false);
|
||||
}
|
||||
|
||||
public onSeeked(): void {
|
||||
const v = this.videoRef?.nativeElement;
|
||||
if (!v || v.seeking || this.pendingLocalTime !== null) return;
|
||||
const shouldPlay = this.seekPlaybackIntent;
|
||||
this.seekPlaybackIntent = null;
|
||||
this.onTimeUpdate();
|
||||
if (shouldPlay) {
|
||||
this.playVideo();
|
||||
} else {
|
||||
this.isPlaying.set(!v.paused && !v.ended);
|
||||
}
|
||||
}
|
||||
|
||||
public onEnded(): void {
|
||||
this.isPlaying.set(false);
|
||||
const segments = this.agentService.activeVideoSegments();
|
||||
if (segments.length && this.activeSegmentIndex() < segments.length - 1) {
|
||||
this.pendingLocalTime = 0;
|
||||
@@ -369,6 +388,10 @@ export class FloatingVideoPlayerComponent implements OnDestroy {
|
||||
}
|
||||
|
||||
public onError(): void {
|
||||
this.playRequestId++;
|
||||
this.pendingLocalTime = null;
|
||||
this.pendingAutoplay = false;
|
||||
this.seekPlaybackIntent = null;
|
||||
this.videoLoadError.set(true);
|
||||
this.isPlaying.set(false);
|
||||
}
|
||||
@@ -379,11 +402,52 @@ export class FloatingVideoPlayerComponent implements OnDestroy {
|
||||
public togglePlay(): void {
|
||||
const v = this.videoRef?.nativeElement;
|
||||
if (!v) return;
|
||||
if (v.paused) {
|
||||
v.play().catch(() => {});
|
||||
} else {
|
||||
v.pause();
|
||||
if (this.pendingLocalTime !== null) {
|
||||
this.pendingAutoplay = !this.isPlaying();
|
||||
this.isPlaying.set(this.pendingAutoplay);
|
||||
return;
|
||||
}
|
||||
if (this.seekPlaybackIntent !== null) {
|
||||
this.seekPlaybackIntent = !this.isPlaying();
|
||||
this.isPlaying.set(this.seekPlaybackIntent);
|
||||
return;
|
||||
}
|
||||
if (v.paused) {
|
||||
this.playVideo();
|
||||
} else {
|
||||
this.playRequestId++;
|
||||
v.pause();
|
||||
this.isPlaying.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
private playVideo(): void {
|
||||
const v = this.videoRef?.nativeElement;
|
||||
if (!v) return;
|
||||
const requestId = ++this.playRequestId;
|
||||
v.play().then(() => {
|
||||
if (requestId === this.playRequestId) this.isPlaying.set(!v.paused && !v.ended);
|
||||
}).catch(() => {
|
||||
// A rejected play request can leave paused=false without advancing frames.
|
||||
// Reset the native state too, so the next click really starts playback.
|
||||
if (requestId === this.playRequestId) {
|
||||
v.pause();
|
||||
this.isPlaying.set(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private seekWithinVideo(seconds: number, shouldPlay: boolean): void {
|
||||
const v = this.videoRef?.nativeElement;
|
||||
if (!v) return;
|
||||
this.playRequestId++;
|
||||
this.seekPlaybackIntent = shouldPlay;
|
||||
// Cancel any unfinished play request before seeking; resume only once the
|
||||
// browser has decoded the destination, including after a source switch.
|
||||
v.pause();
|
||||
this.isPlaying.set(false);
|
||||
v.currentTime = seconds;
|
||||
if (!v.seeking) this.onSeeked();
|
||||
}
|
||||
|
||||
public restart(): void {
|
||||
@@ -421,19 +485,19 @@ export class FloatingVideoPlayerComponent implements OnDestroy {
|
||||
const target = Math.max(0, Math.min(this.duration(), seconds));
|
||||
const segments = this.agentService.activeVideoSegments();
|
||||
const location = locateTimelineTime(segments, target);
|
||||
const shouldPlay = autoplay || this.pendingAutoplay || (this.seekPlaybackIntent ?? !v.paused);
|
||||
if (!location) {
|
||||
v.currentTime = target;
|
||||
if (autoplay) v.play().catch(() => {});
|
||||
return;
|
||||
}
|
||||
const { index, localTime } = location;
|
||||
if (index === this.activeSegmentIndex()) {
|
||||
v.currentTime = localTime;
|
||||
if (autoplay) v.play().catch(() => {});
|
||||
this.seekWithinVideo(target, shouldPlay);
|
||||
} else if (location.index === this.activeSegmentIndex() && this.pendingLocalTime === null) {
|
||||
this.seekWithinVideo(location.localTime, shouldPlay);
|
||||
} else {
|
||||
this.pendingLocalTime = localTime;
|
||||
this.pendingAutoplay = autoplay || !v.paused;
|
||||
this.activeSegmentIndex.set(index);
|
||||
this.playRequestId++;
|
||||
this.seekPlaybackIntent = null;
|
||||
v.pause();
|
||||
this.isPlaying.set(false);
|
||||
this.pendingLocalTime = location.localTime;
|
||||
this.pendingAutoplay = shouldPlay;
|
||||
this.activeSegmentIndex.set(location.index);
|
||||
}
|
||||
this.currentTime.set(target);
|
||||
}
|
||||
@@ -641,6 +705,7 @@ export class FloatingVideoPlayerComponent implements OnDestroy {
|
||||
}
|
||||
|
||||
public ngOnDestroy(): void {
|
||||
this.playRequestId++;
|
||||
if (this.stepTimer) {
|
||||
clearTimeout(this.stepTimer);
|
||||
this.stepTimer = null;
|
||||
|
||||
+46
-4
@@ -4,12 +4,21 @@ import { HttpClient } from '@angular/common/http';
|
||||
import { finalize } from 'rxjs';
|
||||
|
||||
interface Capabilities {
|
||||
adb_auto_connect: boolean;
|
||||
adb_discovery_interval_seconds: number;
|
||||
adb_discovery_timeout_seconds: number;
|
||||
video_enabled: boolean;
|
||||
recording_enabled: boolean;
|
||||
outputter_enabled: boolean;
|
||||
step_summarizer_enabled: boolean;
|
||||
screenshot_limit_enabled: boolean;
|
||||
screenshot_max_long_edge: number;
|
||||
task_timeout_seconds: number;
|
||||
observation_timeout_seconds: number;
|
||||
observation_max_attempts: number;
|
||||
device_command_timeout_seconds: number;
|
||||
action_failure_attempts: number;
|
||||
worker_cleanup_timeout_seconds: number;
|
||||
}
|
||||
|
||||
@Component({
|
||||
@@ -18,6 +27,8 @@ interface Capabilities {
|
||||
<section aria-label="功能开关">
|
||||
<h3>功能开关</h3>
|
||||
<p>按需启用,保存后对新任务生效。</p>
|
||||
<label><input type="checkbox" role="switch" [(ngModel)]="config.adb_auto_connect" [disabled]="busy() || loading() || !loaded()" />
|
||||
<span>自动连接设备<small>刷新设备时发现本机常见模拟器,并重连手动连接过的 TCP 设备;重启 ADB 后也会重连。不扫描局域网,不自动选择任务设备。保存后立即生效。</small></span></label>
|
||||
<label><input type="checkbox" role="switch" [(ngModel)]="config.video_enabled" [disabled]="busy() || loading() || !loaded()" />
|
||||
<span>视频分析<small>允许智能体分析任务画面。运行期间会临时录制,完成后不保留录像(除非开启录屏)。</small></span></label>
|
||||
<label><input type="checkbox" role="switch" [(ngModel)]="config.recording_enabled" [disabled]="busy() || loading() || !loaded()" />
|
||||
@@ -28,7 +39,21 @@ interface Capabilities {
|
||||
<span>步骤摘要压缩<small>Flash 模式下在后台生成摘要,减少长任务的上下文占用。</small></span></label>
|
||||
<label><input type="checkbox" role="switch" [(ngModel)]="config.screenshot_limit_enabled" [disabled]="busy() || loading() || !loaded()" />
|
||||
<span>限制截图分辨率<small>开启时长边最多 {{ config.screenshot_max_long_edge }} 像素;关闭后使用设备原始分辨率。JSON 配置可覆盖开关和上限。</small></span></label>
|
||||
<button type="button" (click)="save()" [disabled]="busy() || loading() || !loaded()">{{ busy() ? '正在保存…' : '保存功能设置' }}</button>
|
||||
<details class="execution-settings">
|
||||
<summary>执行保护</summary>
|
||||
<p>限制故障等待与反复失败;保存后对新任务生效,任务 JSON 可单独覆盖。</p>
|
||||
<div class="number-fields">
|
||||
<label>任务总超时(秒)<input type="number" min="30" max="86400" step="1" [(ngModel)]="config.task_timeout_seconds" [disabled]="busy() || !loaded()" /><small>不包含排队和用户暂停时间。</small></label>
|
||||
<label>屏幕观测超时(秒)<input type="number" min="1" max="300" [(ngModel)]="config.observation_timeout_seconds" [disabled]="busy() || !loaded()" /></label>
|
||||
<label>观测恢复最多尝试次数<input type="number" min="1" max="5" step="1" [(ngModel)]="config.observation_max_attempts" [disabled]="busy() || !loaded()" /></label>
|
||||
<label>ADB 命令超时(秒)<input type="number" min="1" max="60" [(ngModel)]="config.device_command_timeout_seconds" [disabled]="busy() || !loaded()" /></label>
|
||||
<label>连续动作失败次数<input type="number" min="1" max="10" step="1" [(ngModel)]="config.action_failure_attempts" [disabled]="busy() || !loaded()" /><small>先重新观察,再让兜底模型处理当前步骤。</small></label>
|
||||
<label>任务收尾超时(秒)<input type="number" min="1" max="300" [(ngModel)]="config.worker_cleanup_timeout_seconds" [disabled]="busy() || !loaded()" /><small>已有最终结果但进程未退出时,回收进程以释放队列。</small></label>
|
||||
<label>设备自动发现间隔(秒)<input type="number" min="1" max="300" [(ngModel)]="config.adb_discovery_interval_seconds" [disabled]="busy() || !loaded()" /></label>
|
||||
<label>每轮自动连接预算(秒)<input type="number" min="1" max="30" [(ngModel)]="config.adb_discovery_timeout_seconds" [disabled]="busy() || !loaded()" /></label>
|
||||
</div>
|
||||
</details>
|
||||
<button type="button" (click)="save()" [disabled]="busy() || loading() || !loaded() || !valid()">{{ busy() ? '正在保存…' : '保存功能设置' }}</button>
|
||||
@if (message()) { <p role="status">{{ message() }}</p> }
|
||||
@if (error()) { <p role="alert" class="error">{{ error() }}</p> }
|
||||
</section>
|
||||
@@ -38,12 +63,18 @@ interface Capabilities {
|
||||
label { display: flex; gap: 12px; align-items: flex-start; padding: 14px 0; cursor: pointer; }
|
||||
input { width: 20px; height: 20px; accent-color: #0284c7; flex-shrink: 0; }
|
||||
small { display: block; margin-top: 4px; } button { padding: 10px 18px; border-radius: 10px; border: 1px solid #38bdf877; background: #0284c7; color: white; font: inherit; cursor: pointer; }
|
||||
button:disabled { opacity: .5; cursor: default; } .error { color: #be123c; }`]
|
||||
button:disabled { opacity: .5; cursor: default; } .error { color: #be123c; }
|
||||
.execution-settings { margin: 12px 0 20px; padding: 12px 14px; border: 1px solid #cbd5e1; border-radius: 10px; background: #f8fafc; }
|
||||
summary { cursor: pointer; font-weight: 600; color: #334155; }
|
||||
.number-fields { display: grid; grid-template-columns: 1fr 1fr; gap: 12px 16px; }
|
||||
.number-fields label { display: block; padding: 0; color: #334155; }
|
||||
.number-fields input { box-sizing: border-box; display: block; width: 100%; height: auto; margin-top: 8px; padding: 9px; border: 1px solid #cbd5e1; border-radius: 8px; font: inherit; }
|
||||
@media(max-width: 480px) { .number-fields { grid-template-columns: 1fr; } }`]
|
||||
})
|
||||
export class CapabilitySettingsComponent implements OnInit {
|
||||
changed = output<Capabilities>();
|
||||
private http = inject(HttpClient);
|
||||
config: Capabilities = { video_enabled: false, recording_enabled: false, outputter_enabled: true, step_summarizer_enabled: true, screenshot_limit_enabled: true, screenshot_max_long_edge: 2048 };
|
||||
config: Capabilities = { adb_auto_connect: true, adb_discovery_interval_seconds: 10, adb_discovery_timeout_seconds: 5, video_enabled: false, recording_enabled: false, outputter_enabled: true, step_summarizer_enabled: true, screenshot_limit_enabled: true, screenshot_max_long_edge: 2048, task_timeout_seconds: 1800, observation_timeout_seconds: 60, observation_max_attempts: 3, device_command_timeout_seconds: 10, action_failure_attempts: 3, worker_cleanup_timeout_seconds: 30 };
|
||||
busy = signal(false); loading = signal(true); loaded = signal(false); message = signal(''); error = signal('');
|
||||
ngOnInit(): void {
|
||||
this.http.get<Capabilities>('/api/system/capability-settings').pipe(finalize(() => this.loading.set(false))).subscribe({
|
||||
@@ -51,11 +82,22 @@ export class CapabilitySettingsComponent implements OnInit {
|
||||
});
|
||||
}
|
||||
save(): void {
|
||||
if (this.busy() || this.loading() || !this.loaded()) return;
|
||||
if (this.busy() || this.loading() || !this.loaded() || !this.valid()) return;
|
||||
this.busy.set(true); this.message.set(''); this.error.set('');
|
||||
this.http.post<Capabilities>('/api/system/capability-settings', this.config).pipe(finalize(() => this.busy.set(false))).subscribe({
|
||||
next: config => { this.config = config; this.changed.emit(config); this.message.set('功能设置已保存,新任务将使用此配置。'); },
|
||||
error: () => this.error.set('保存失败,请检查服务器连接和 .env 文件权限。')
|
||||
});
|
||||
}
|
||||
valid(): boolean {
|
||||
const c = this.config;
|
||||
return Number.isInteger(c.task_timeout_seconds) && c.task_timeout_seconds >= 30 && c.task_timeout_seconds <= 86400
|
||||
&& c.observation_timeout_seconds > 0 && c.observation_timeout_seconds <= 300
|
||||
&& Number.isInteger(c.observation_max_attempts) && c.observation_max_attempts >= 1 && c.observation_max_attempts <= 5
|
||||
&& c.device_command_timeout_seconds > 0 && c.device_command_timeout_seconds <= 60
|
||||
&& Number.isInteger(c.action_failure_attempts) && c.action_failure_attempts >= 1 && c.action_failure_attempts <= 10
|
||||
&& c.worker_cleanup_timeout_seconds > 0 && c.worker_cleanup_timeout_seconds <= 300
|
||||
&& c.adb_discovery_interval_seconds >= 1 && c.adb_discovery_interval_seconds <= 300
|
||||
&& c.adb_discovery_timeout_seconds > 0 && c.adb_discovery_timeout_seconds <= 30;
|
||||
}
|
||||
}
|
||||
+53
-1
@@ -138,7 +138,7 @@ describe('持久化模型与功能设置', () => {
|
||||
});
|
||||
|
||||
it('录屏与视频分析独立保存,重新打开后保留各自状态', () => {
|
||||
const capabilities = { video_enabled: true, recording_enabled: false, outputter_enabled: true, step_summarizer_enabled: false, screenshot_limit_enabled: true, screenshot_max_long_edge: 2048 };
|
||||
const capabilities = { adb_auto_connect: true, adb_discovery_interval_seconds: 10, adb_discovery_timeout_seconds: 5, video_enabled: true, recording_enabled: false, outputter_enabled: true, step_summarizer_enabled: false, screenshot_limit_enabled: true, screenshot_max_long_edge: 2048, task_timeout_seconds: 1800, observation_timeout_seconds: 60, observation_max_attempts: 3, device_command_timeout_seconds: 10, action_failure_attempts: 3, worker_cleanup_timeout_seconds: 30 };
|
||||
const fixture = TestBed.createComponent(CapabilitySettingsComponent);
|
||||
fixture.detectChanges();
|
||||
http.expectOne('/api/system/capability-settings').flush(capabilities);
|
||||
@@ -160,4 +160,56 @@ describe('持久化模型与功能设置', () => {
|
||||
expect(reopened.componentInstance.config.recording_enabled).toBeTrue();
|
||||
expect(reopened.componentInstance.config.screenshot_limit_enabled).toBeFalse();
|
||||
});
|
||||
|
||||
it('执行保护默认折叠,修改时限可保存且拒绝无效数值', async () => {
|
||||
const capabilities = { adb_auto_connect: true, adb_discovery_interval_seconds: 10, adb_discovery_timeout_seconds: 5, video_enabled: false, recording_enabled: false, outputter_enabled: true, step_summarizer_enabled: true, screenshot_limit_enabled: true, screenshot_max_long_edge: 2048, task_timeout_seconds: 1800, observation_timeout_seconds: 60, observation_max_attempts: 3, device_command_timeout_seconds: 10, action_failure_attempts: 3, worker_cleanup_timeout_seconds: 30 };
|
||||
const fixture = TestBed.createComponent(CapabilitySettingsComponent);
|
||||
fixture.detectChanges();
|
||||
http.expectOne('/api/system/capability-settings').flush(capabilities);
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
expect(root.querySelector<HTMLDetailsElement>('.execution-settings')!.open).toBeFalse();
|
||||
root.querySelector<HTMLElement>('summary')!.click();
|
||||
const timeout = root.querySelector<HTMLInputElement>('input[type="number"]')!;
|
||||
timeout.value = '3600';
|
||||
timeout.dispatchEvent(new Event('input'));
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
root.querySelector<HTMLButtonElement>('button')!.click();
|
||||
const request = http.expectOne('/api/system/capability-settings');
|
||||
expect(request.request.body.task_timeout_seconds).toBe(3600);
|
||||
expect(request.request.body.observation_timeout_seconds).toBe(60);
|
||||
request.flush({ ...capabilities, task_timeout_seconds: 3600 });
|
||||
expect(fixture.componentInstance.message()).toContain('已保存');
|
||||
timeout.value = '0';
|
||||
timeout.dispatchEvent(new Event('input'));
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
expect(root.querySelector<HTMLButtonElement>('button')!.disabled).toBeTrue();
|
||||
fixture.componentInstance.save();
|
||||
http.expectNone('/api/system/capability-settings');
|
||||
});
|
||||
|
||||
it('自动连接默认开启,可独立关闭并保存发现预算', () => {
|
||||
const fixture = TestBed.createComponent(CapabilitySettingsComponent);
|
||||
const capabilities = { ...fixture.componentInstance.config };
|
||||
fixture.detectChanges();
|
||||
http.expectOne('/api/system/capability-settings').flush(capabilities);
|
||||
fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
expect(root.textContent).toContain('自动连接设备');
|
||||
expect(fixture.componentInstance.config.adb_auto_connect).toBeTrue();
|
||||
fixture.componentInstance.config.adb_auto_connect = false;
|
||||
fixture.componentInstance.config.adb_discovery_timeout_seconds = 8;
|
||||
fixture.componentInstance.save();
|
||||
const request = http.expectOne('/api/system/capability-settings');
|
||||
expect(request.request.body.adb_auto_connect).toBeFalse();
|
||||
expect(request.request.body.adb_discovery_timeout_seconds).toBe(8);
|
||||
expect(request.request.body.recording_enabled).toBeFalse();
|
||||
request.flush(request.request.body);
|
||||
fixture.componentInstance.config.adb_discovery_timeout_seconds = 0;
|
||||
fixture.componentInstance.save();
|
||||
http.expectNone('/api/system/capability-settings');
|
||||
});
|
||||
});
|
||||
@@ -20,7 +20,7 @@ import { Component, signal, computed, inject, OnInit, OnDestroy, ChangeDetection
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { Router } from '@angular/router';
|
||||
import { AgentService } from '../../services/agent.service';
|
||||
import { SystemService } from '../../services/system.service';
|
||||
import { SystemService, formatAdbRestartFeedback } from '../../services/system.service';
|
||||
import {
|
||||
AdbServerConnectionResult,
|
||||
AdbServerDevice,
|
||||
@@ -548,10 +548,8 @@ export class HomeComponent implements OnInit, OnDestroy {
|
||||
this.adbRestartFeedback.set(null);
|
||||
this.systemService.restartAdb().subscribe({
|
||||
next: (res) => {
|
||||
this.adbRestartFeedback.set(
|
||||
res?.restart_result?.skipped ? "设备已刷新 ✓" : "ADB 已刷新 ✓"
|
||||
);
|
||||
setTimeout(() => this.adbRestartFeedback.set(null), 2500);
|
||||
this.adbRestartFeedback.set(formatAdbRestartFeedback(res?.restart_result));
|
||||
setTimeout(() => this.adbRestartFeedback.set(null), 6000);
|
||||
},
|
||||
error: () => {
|
||||
this.adbRestartFeedback.set("重启失败");
|
||||
|
||||
@@ -3,7 +3,23 @@ import { HttpTestingController, provideHttpClientTesting } from '@angular/common
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
|
||||
import { SystemReadinessReport } from '../core/models/system.model';
|
||||
import { SystemService } from './system.service';
|
||||
import { SystemService, formatAdbRestartFeedback } from './system.service';
|
||||
|
||||
describe('ADB restart feedback', () => {
|
||||
it('区分已连接与正在连接,不把等待就绪显示为失败', () => {
|
||||
const message = formatAdbRestartFeedback({ success: true, automatic_connections: [{ success: true }, { success: false, pending: true }] });
|
||||
expect(message).toContain('已连接 1 台设备');
|
||||
expect(message).toContain('1 台设备连接中');
|
||||
expect(message).not.toContain('失败');
|
||||
});
|
||||
it('显示连接失败数量,提示查看诊断', () => {
|
||||
expect(formatAdbRestartFeedback({ success: true, automatic_connections: [{ success: false }] })).toContain('1 项连接失败,请查看诊断');
|
||||
});
|
||||
it('服务器重启失败不会显示成功,远程端点明确显示仅刷新', () => {
|
||||
expect(formatAdbRestartFeedback({ success: false, message: '端口被占用' })).toBe('端口被占用');
|
||||
expect(formatAdbRestartFeedback({ success: true, skipped: true })).toBe('设备已刷新 ✓');
|
||||
});
|
||||
});
|
||||
|
||||
describe('SystemService readiness polling', () => {
|
||||
let service: SystemService;
|
||||
|
||||
@@ -27,6 +27,19 @@ import {
|
||||
EmulatorLaunchStage
|
||||
} from '../core/models/system.model';
|
||||
|
||||
export function formatAdbRestartFeedback(result?: {
|
||||
success?: boolean; skipped?: boolean; message?: string;
|
||||
automatic_connections?: { success?: boolean; pending?: boolean }[];
|
||||
}): string {
|
||||
if (!result?.success) return result?.message || '重启失败';
|
||||
if (result.skipped) return '设备已刷新 ✓';
|
||||
const connections = result.automatic_connections ?? [];
|
||||
const connected = connections.filter(item => item.success).length;
|
||||
const pending = connections.filter(item => item.pending).length;
|
||||
const failed = connections.filter(item => !item.success && !item.pending).length;
|
||||
return `ADB 已重启${connected ? `,已连接 ${connected} 台设备` : ''}${pending ? `,${pending} 台设备连接中,将自动重试` : ''}${failed ? `,${failed} 项连接失败,请查看诊断` : ' ✓'}`;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
|
||||
@@ -81,7 +81,7 @@ from artemis.graph.state import State
|
||||
from artemis.llm.router import ModelEndpoint
|
||||
from artemis.llm.structured import ParseFailure, parse_structured
|
||||
from artemis.mcp.action_executor import McpActionExecutor
|
||||
from artemis.mcp.observation import observe
|
||||
from artemis.mcp.observation import DeviceObservationError, require_observation
|
||||
from artemis.memory.transcript import PRO_UI_LIST_MARKER, TranscriptLedger, mark_ephemeral
|
||||
from artemis.services.llm import (
|
||||
RobustChatModelWrapper,
|
||||
@@ -380,8 +380,16 @@ class FlashRunner:
|
||||
blocks.append(
|
||||
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{img_b64}"}}
|
||||
)
|
||||
if xml_list:
|
||||
blocks.append({"type": "text", "text": f"{PRO_UI_LIST_MARKER}\n{xml_list}"})
|
||||
blocks.append(
|
||||
{
|
||||
"type": "text",
|
||||
"text": f"{PRO_UI_LIST_MARKER}\n"
|
||||
+ (
|
||||
xml_list
|
||||
or "当前没有可用的元素索引。仅根据当前截图定位坐标,禁止使用历史画面的元素编号。"
|
||||
),
|
||||
}
|
||||
)
|
||||
ephemeral: list[int] = []
|
||||
# (text, ephemeral) in tail order.
|
||||
per_turn: list[tuple[str, bool]] = [(text, True) for text in (notices or [])]
|
||||
@@ -604,19 +612,14 @@ class FlashRunner:
|
||||
post_img_bytes = exec_result.screenshot_bytes
|
||||
if post_img_bytes or name not in action_names:
|
||||
return post_img_bytes
|
||||
try:
|
||||
obs, screenshot_bytes = await observe(self.ctx, self.controller, settle_ms=0)
|
||||
except Exception as shot_err:
|
||||
logger.warning(f"Failed to capture fallback screenshot in FlashRunner: {shot_err}")
|
||||
return post_img_bytes
|
||||
if not obs.ok:
|
||||
logger.warning(f"Failed to capture fallback screenshot in FlashRunner: {obs.message}")
|
||||
return post_img_bytes
|
||||
if state is not None:
|
||||
state.indexed_points = []
|
||||
state.indexed_elements = []
|
||||
state.latest_screenshot = None
|
||||
obs, screenshot_bytes = await require_observation(self.ctx, self.controller, settle_ms=0)
|
||||
post_img_bytes = screenshot_bytes
|
||||
if not exec_result.ui_elements_text:
|
||||
exec_result.ui_elements_text = obs.elements_text
|
||||
if not exec_result.screenshot_path and obs.screenshot_path:
|
||||
exec_result.screenshot_path = obs.screenshot_path
|
||||
exec_result.ui_elements_text = obs.elements_text
|
||||
exec_result.screenshot_path = obs.screenshot_path
|
||||
if state is not None:
|
||||
if obs.hierarchy_ok:
|
||||
state.indexed_points = [el["center"] for el in obs.elements]
|
||||
@@ -831,7 +834,7 @@ class FlashRunner:
|
||||
turn.actions.append((name, exec_result.status, exec_result.text_summary))
|
||||
|
||||
# ⚡ Non-blocking dispatch of objective visual transition summarizer
|
||||
if self.summarizer and name in action_names:
|
||||
if self.summarizer and name in action_names and post_img_bytes:
|
||||
action_sequence += 1
|
||||
self.summarizer.dispatch(
|
||||
step_number=action_sequence,
|
||||
@@ -857,7 +860,7 @@ class FlashRunner:
|
||||
|
||||
if post_img_bytes:
|
||||
pre_screenshot_bytes = post_img_bytes
|
||||
if exec_result.ui_elements_text:
|
||||
if exec_result.ui_elements_text is not None:
|
||||
xml_list = exec_result.ui_elements_text
|
||||
|
||||
# Helper tools may return multimodal blocks (a step screenshot);
|
||||
@@ -876,6 +879,8 @@ class FlashRunner:
|
||||
)
|
||||
)
|
||||
|
||||
except DeviceObservationError:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error executing tool {name}: {e}")
|
||||
if name in action_names:
|
||||
@@ -1047,6 +1052,21 @@ class FlashRunner:
|
||||
|
||||
@trace(type="agent", name="FlashRunner")
|
||||
async def run(self, state: State) -> dict:
|
||||
try:
|
||||
return await self._run(state)
|
||||
except DeviceObservationError as exc:
|
||||
state.indexed_points = []
|
||||
state.indexed_elements = []
|
||||
state.latest_screenshot = None
|
||||
logger.error(f"Flash 因设备观测失败停止:{exc}")
|
||||
return {
|
||||
"status": "failed",
|
||||
"explanation": str(exc),
|
||||
"error": str(exc),
|
||||
"code": "device_observation_failed",
|
||||
}
|
||||
|
||||
async def _run(self, state: State) -> dict:
|
||||
limit = self.turn_limit
|
||||
logger.info(
|
||||
f"Starting Artemis Flash reactive loop for goal: {self.goal}"
|
||||
@@ -1073,6 +1093,7 @@ class FlashRunner:
|
||||
no_tool_limit = settings.ARTEMIS_FLASH_MAX_NO_PROGRESS_ATTEMPTS
|
||||
fallback_llm = None
|
||||
using_tool_fallback = False
|
||||
action_failure_attempts = 0
|
||||
|
||||
while limit is None or turns < limit:
|
||||
control = getattr(self.ctx, "task_control", None)
|
||||
@@ -1084,6 +1105,7 @@ class FlashRunner:
|
||||
if resumed:
|
||||
using_tool_fallback = False
|
||||
no_tool_attempts = 0
|
||||
action_failure_attempts = 0
|
||||
self._llm = llm
|
||||
(
|
||||
shot_path,
|
||||
@@ -1157,6 +1179,7 @@ class FlashRunner:
|
||||
# assembled before the instruction arrived.
|
||||
using_tool_fallback = False
|
||||
no_tool_attempts = 0
|
||||
action_failure_attempts = 0
|
||||
self._llm = llm
|
||||
(
|
||||
shot_path,
|
||||
@@ -1241,6 +1264,7 @@ class FlashRunner:
|
||||
fallback_llm = get_llm(self.ctx, name="operator", use_fallback=True)
|
||||
using_tool_fallback = True
|
||||
no_tool_attempts = 0
|
||||
action_failure_attempts = 0
|
||||
logger.warning("Flash 首选模型未调用工具,当前步骤切换到兜底模型")
|
||||
pending_notices.append("首选模型连续未调用工具;本步骤改用兜底模型。")
|
||||
pending_notices.append(_NO_TOOL_CALL_NOTICE)
|
||||
@@ -1279,6 +1303,37 @@ class FlashRunner:
|
||||
using_tool_fallback = False
|
||||
self._llm = llm
|
||||
pending_notices.append("兜底模型已完成本步骤;后续步骤恢复首选模型。")
|
||||
for _, status, _ in turn.actions:
|
||||
action_failure_attempts = 0 if status == "success" else action_failure_attempts + 1
|
||||
failure_limit = (
|
||||
settings.ARTEMIS_TOOL_FALLBACK_MAX_NO_PROGRESS_ATTEMPTS
|
||||
if using_tool_fallback
|
||||
else settings.ARTEMIS_ACTION_FAILURE_ATTEMPTS
|
||||
)
|
||||
if action_failure_attempts >= failure_limit:
|
||||
if using_tool_fallback:
|
||||
final_report = {
|
||||
"status": "failed",
|
||||
"explanation": f"兜底模型连续 {action_failure_attempts} 次设备动作失败,已停止任务。最后原因:{turn.result()}",
|
||||
}
|
||||
break
|
||||
# A fresh, valid observation is required before spending any
|
||||
# fallback model calls. Hardware recovery is not model retry.
|
||||
(
|
||||
shot_path,
|
||||
current_pre_screenshot_bytes,
|
||||
current_xml_list,
|
||||
) = await capture_screenshot_and_parse_ui(self.ctx, state, self.controller)
|
||||
state.latest_screenshot = shot_path
|
||||
fallback_llm = get_llm(self.ctx, name="operator", use_fallback=True)
|
||||
using_tool_fallback = True
|
||||
self._llm = fallback_llm
|
||||
action_failure_attempts = 0
|
||||
no_tool_attempts = 0
|
||||
pending_notices.append(
|
||||
f"首选模型连续 {settings.ARTEMIS_ACTION_FAILURE_ATTEMPTS} 次设备动作失败。"
|
||||
f"最后原因:{turn.result()}。已重新观察;本步骤由兜底模型重新定位,勿重复旧动作。"
|
||||
)
|
||||
ledger.stage_turn(messages[turn_base:])
|
||||
previous_turn = turn
|
||||
if final_report_from_calls is not None:
|
||||
|
||||
@@ -136,9 +136,14 @@ async def capture_screenshot_and_parse_ui(
|
||||
Thin adapter over :func:`artemis.mcp.observation.observe` that adds the LangGraph
|
||||
``State`` write-back (indexed points/elements) the agents rely on.
|
||||
"""
|
||||
obs, screenshot_bytes = await observe(ctx, controller, settle_ms=0 if skip_settling else 400)
|
||||
if not obs.ok:
|
||||
return None, None, None
|
||||
from artemis.mcp.observation import require_observation
|
||||
|
||||
state.indexed_points = []
|
||||
state.indexed_elements = []
|
||||
state.latest_screenshot = None
|
||||
obs, screenshot_bytes = await require_observation(
|
||||
ctx, controller, settle_ms=0 if skip_settling else 400
|
||||
)
|
||||
|
||||
if obs.hierarchy_ok:
|
||||
state.indexed_points = [el["center"] for el in obs.elements]
|
||||
|
||||
@@ -108,6 +108,7 @@ class Settings(BaseSettings):
|
||||
OPENAI_REASONING_EFFORT: str = "high"
|
||||
ARTEMIS_CREDENTIAL_TIMEOUT_SECONDS: float = Field(default=12.0, gt=0)
|
||||
ARTEMIS_MODEL_CACHE_TTL_SECONDS: float = Field(default=10.0, ge=0)
|
||||
ARTEMIS_DAEMON_PROBE_TIMEOUT_SECONDS: float = Field(default=2.0, gt=0)
|
||||
ARTEMIS_VIDEO_TIMEOUT_SECONDS: float = Field(default=120.0, gt=0)
|
||||
ARTEMIS_VIDEO_MAX_RETRIES: int = Field(default=1, ge=0)
|
||||
ARTEMIS_VIDEO_CHUNK_SECONDS: float = Field(default=60.0, gt=0)
|
||||
@@ -122,11 +123,21 @@ class Settings(BaseSettings):
|
||||
ARTEMIS_OPERATOR_MAX_NO_PROGRESS_ATTEMPTS: int = Field(default=3, ge=1, le=20)
|
||||
# Consecutive Flash responses without any tool call before failing the task.
|
||||
ARTEMIS_FLASH_MAX_NO_PROGRESS_ATTEMPTS: int = Field(default=3, ge=1, le=20)
|
||||
ARTEMIS_TASK_TIMEOUT_SECONDS: int = Field(default=1800, ge=30, le=86400)
|
||||
ARTEMIS_BATCH_MAX_EXECUTIONS: int = Field(default=10000, ge=1)
|
||||
ARTEMIS_OBSERVATION_TIMEOUT_SECONDS: float = Field(default=60, gt=0, le=300)
|
||||
ARTEMIS_OBSERVATION_MAX_ATTEMPTS: int = Field(default=3, ge=1, le=5)
|
||||
ARTEMIS_DEVICE_COMMAND_TIMEOUT_SECONDS: float = Field(default=10, gt=0, le=60)
|
||||
ARTEMIS_ACTION_FAILURE_ATTEMPTS: int = Field(default=3, ge=1, le=10)
|
||||
ARTEMIS_WORKER_CLEANUP_TIMEOUT_SECONDS: float = Field(default=30, gt=0, le=300)
|
||||
|
||||
# Android ADB Connectivity
|
||||
ADB_HOST: str | None = Field(default=DEFAULT_ADB_HOST)
|
||||
ADB_PORT: int | None = Field(default=DEFAULT_ADB_PORT)
|
||||
ADB_DEVICE_SERIAL: str | None = None
|
||||
ARTEMIS_ADB_AUTO_CONNECT: bool = True
|
||||
ARTEMIS_ADB_DISCOVERY_INTERVAL_SECONDS: float = Field(default=10, ge=1, le=300)
|
||||
ARTEMIS_ADB_DISCOVERY_TIMEOUT_SECONDS: float = Field(default=5, gt=0, le=30)
|
||||
# UI hierarchy backend: "auto" = Accessibility Helper with UIAutomator2
|
||||
# fallback, "helper" = helper only, "uiautomator" = UIAutomator2 only.
|
||||
ARTEMIS_HIERARCHY_BACKEND: str = Field(default="auto")
|
||||
|
||||
@@ -21,6 +21,7 @@ import time
|
||||
from typing import Any
|
||||
|
||||
from artemis.core.diagnostics.adb_server_connection import adb_server_connection
|
||||
from artemis.runtime.adb_discovery import adb_device_discovery
|
||||
from artemis.core.diagnostics.probes.adb_probe import AdbDeviceProbe
|
||||
from artemis.core.diagnostics.probes.base import BaseProbe
|
||||
from artemis.core.diagnostics.probes.credentials_probe import (
|
||||
@@ -353,7 +354,12 @@ class ReadinessEngine:
|
||||
}
|
||||
|
||||
logger.info("[ReadinessEngine] Restarting ADB server...")
|
||||
return await asyncio.to_thread(_restart_sync)
|
||||
result = await asyncio.to_thread(_restart_sync)
|
||||
if result.get("success"):
|
||||
result["automatic_connections"] = await asyncio.to_thread(
|
||||
adb_device_discovery.refresh, adb_path, force=True
|
||||
)
|
||||
return result
|
||||
|
||||
async def launch_emulator(self, avd_name: str) -> dict[str, Any]:
|
||||
"""Launch an Android emulator by AVD name in the background and track its lifecycle."""
|
||||
@@ -417,8 +423,10 @@ class ReadinessEngine:
|
||||
)
|
||||
output = (res.stdout + "\n" + res.stderr).strip()
|
||||
success = "connected to" in output.lower() and "failed" not in output.lower()
|
||||
remembered = adb_device_discovery.remember(target) if success else False
|
||||
return {
|
||||
"success": success,
|
||||
"remembered": remembered,
|
||||
"target": target,
|
||||
"output": output,
|
||||
"message": f"Connected to {target}" if success else output,
|
||||
|
||||
@@ -33,6 +33,7 @@ from artemis.core.diagnostics.schema import (
|
||||
)
|
||||
from artemis.platform import OSType, platform
|
||||
from artemis.toolchain import toolchain
|
||||
from artemis.runtime.adb_discovery import adb_device_discovery
|
||||
from artemis.utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
@@ -477,6 +478,7 @@ class AdbDeviceProbe(BaseProbe):
|
||||
async def _parse_adb_devices(self, adb_path: str) -> list[DeviceInfo]:
|
||||
"""Execute `adb devices -l` and extract structured device metadata."""
|
||||
devices: list[DeviceInfo] = []
|
||||
await asyncio.to_thread(adb_device_discovery.refresh, adb_path)
|
||||
try:
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
adb_path,
|
||||
@@ -668,6 +670,7 @@ class AdbDeviceProbe(BaseProbe):
|
||||
"installed": True,
|
||||
"adb_path": adb_path,
|
||||
"adb_version": adb_ver,
|
||||
"automatic_connections": adb_device_discovery.results.copy(),
|
||||
"adb_keys": key_status.to_dict(),
|
||||
"emulator_path": emulator_path,
|
||||
"is_emulator_in_path": is_emu_in_path,
|
||||
|
||||
@@ -19,6 +19,7 @@ import base64
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal
|
||||
from PIL import Image
|
||||
|
||||
from adbutils import AdbClient, AdbDevice
|
||||
from artemis.clients.ui_automator_client import (
|
||||
@@ -26,6 +27,7 @@ from artemis.clients.ui_automator_client import (
|
||||
_parse_hierarchy_xml_to_elements,
|
||||
)
|
||||
from artemis.config.agent import load_agent_config
|
||||
from artemis.config.settings import settings
|
||||
from artemis.config.paths import get_temp_dir
|
||||
from artemis.drivers.base import BaseDeviceDriver, KeyCode, ScreenData, SwipeDirection
|
||||
from artemis.toolchain import find_ffmpeg, find_scrcpy
|
||||
@@ -91,6 +93,7 @@ class AndroidAdbDriver(BaseDeviceDriver):
|
||||
self._recording_process: asyncio.subprocess.Process | None = None
|
||||
self._recording_output_path: Path | None = None
|
||||
self._screenshot_config = load_agent_config().screenshot
|
||||
self._screen_capture_task: asyncio.Task[ScreenData] | None = None
|
||||
|
||||
@property
|
||||
def device_id(self) -> str:
|
||||
@@ -122,6 +125,24 @@ class AndroidAdbDriver(BaseDeviceDriver):
|
||||
await asyncio.to_thread(self._ui_adb_client.disconnect)
|
||||
|
||||
async def get_screen_data(self, skip_settling: bool = False) -> ScreenData:
|
||||
"""Bound observation latency and share unfinished capture work across retries."""
|
||||
task = self._screen_capture_task
|
||||
if task is None or task.done():
|
||||
task = asyncio.create_task(self._get_screen_data(skip_settling))
|
||||
# A timed-out caller does not cancel a blocking SDK thread or start
|
||||
# another concurrent read on the same device. Retrieve late errors.
|
||||
task.add_done_callback(lambda done: None if done.cancelled() else done.exception())
|
||||
self._screen_capture_task = task
|
||||
try:
|
||||
return await asyncio.wait_for(
|
||||
asyncio.shield(task), timeout=settings.ARTEMIS_OBSERVATION_TIMEOUT_SECONDS
|
||||
)
|
||||
except TimeoutError as exc:
|
||||
raise TimeoutError(
|
||||
f"设备屏幕观测超时({settings.ARTEMIS_OBSERVATION_TIMEOUT_SECONDS:g} 秒)"
|
||||
) from exc
|
||||
|
||||
async def _get_screen_data(self, skip_settling: bool = False) -> ScreenData:
|
||||
"""Captures screenshot and XML hierarchy concurrently."""
|
||||
if not skip_settling:
|
||||
await asyncio.sleep(0.3)
|
||||
@@ -131,11 +152,14 @@ class AndroidAdbDriver(BaseDeviceDriver):
|
||||
screenshot_base64: str = ""
|
||||
ui_hierarchy_xml: str | None = None
|
||||
ui_elements: list[dict[str, Any]] = []
|
||||
capture_errors: list[str] = []
|
||||
|
||||
# Check if ui_adb_client has direct screen data support
|
||||
if self._ui_adb_client and hasattr(self._ui_adb_client, "get_screen_data"):
|
||||
try:
|
||||
raw_ui_data = self._ui_adb_client.get_screen_data()
|
||||
raw_ui_data = await asyncio.to_thread(self._ui_adb_client.get_screen_data)
|
||||
if asyncio.iscoroutine(raw_ui_data):
|
||||
raw_ui_data = await raw_ui_data
|
||||
if (
|
||||
hasattr(raw_ui_data, "base64")
|
||||
and isinstance(raw_ui_data.base64, str)
|
||||
@@ -158,11 +182,18 @@ class AndroidAdbDriver(BaseDeviceDriver):
|
||||
elif isinstance(raw_elements, list):
|
||||
ui_elements = raw_elements
|
||||
except Exception as e:
|
||||
capture_errors.append(str(e))
|
||||
logger.debug(f"Direct ui_adb_client.get_screen_data error: {e}")
|
||||
|
||||
if not screenshot_base64 or not isinstance(screenshot_base64, str):
|
||||
try:
|
||||
pil_img = await asyncio.to_thread(self.device.screenshot)
|
||||
raw_image = await asyncio.to_thread(
|
||||
self.device.shell,
|
||||
["screencap", "-p"],
|
||||
encoding=None,
|
||||
timeout=settings.ARTEMIS_DEVICE_COMMAND_TIMEOUT_SECONDS,
|
||||
)
|
||||
pil_img = Image.open(BytesIO(raw_image))
|
||||
if hasattr(pil_img, "save"):
|
||||
buf = BytesIO()
|
||||
pil_img.save(buf, format="PNG")
|
||||
@@ -170,18 +201,24 @@ class AndroidAdbDriver(BaseDeviceDriver):
|
||||
self._width, self._height = pil_img.size
|
||||
screenshot_base64 = base64.b64encode(screenshot_bytes).decode("utf-8")
|
||||
except Exception as e:
|
||||
capture_errors.append(str(e))
|
||||
logger.warning(f"Device screenshot capture failed on {self._device_id}: {e}")
|
||||
|
||||
if not screenshot_base64 or not isinstance(screenshot_base64, str):
|
||||
# Fallback for headless testing environments
|
||||
screenshot_base64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="
|
||||
screenshot_bytes = base64.b64decode(screenshot_base64)
|
||||
raise RuntimeError(
|
||||
"设备截图失败:ADB 与屏幕辅助服务均未返回有效截图;" + "; ".join(capture_errors)
|
||||
)
|
||||
|
||||
with Image.open(BytesIO(screenshot_bytes)) as image:
|
||||
if min(image.size) <= 1:
|
||||
raise RuntimeError("设备截图无效:收到占位图,禁止基于旧画面继续操作")
|
||||
image.verify()
|
||||
|
||||
# 2. Capture UI Hierarchy via UIAutomator
|
||||
if self._ui_adb_client and not ui_elements:
|
||||
try:
|
||||
if hasattr(self._ui_adb_client, "get_hierarchy"):
|
||||
res = self._ui_adb_client.get_hierarchy()
|
||||
res = await asyncio.to_thread(self._ui_adb_client.get_hierarchy)
|
||||
hierarchy = await res if asyncio.iscoroutine(res) else res
|
||||
if isinstance(hierarchy, str):
|
||||
ui_hierarchy_xml = hierarchy
|
||||
@@ -189,7 +226,7 @@ class AndroidAdbDriver(BaseDeviceDriver):
|
||||
else:
|
||||
ui_elements = hierarchy
|
||||
elif hasattr(self._ui_adb_client, "get_ui_elements"):
|
||||
res = self._ui_adb_client.get_ui_elements()
|
||||
res = await asyncio.to_thread(self._ui_adb_client.get_ui_elements)
|
||||
ui_elements = await res if asyncio.iscoroutine(res) else res
|
||||
except Exception as e:
|
||||
logger.debug(f"UI hierarchy extraction failed: {e}")
|
||||
@@ -208,16 +245,8 @@ class AndroidAdbDriver(BaseDeviceDriver):
|
||||
screen_width=w,
|
||||
screen_height=h,
|
||||
)
|
||||
clean_b64 = (
|
||||
screenshot_base64
|
||||
if isinstance(screenshot_base64, str) and screenshot_base64
|
||||
else "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="
|
||||
)
|
||||
clean_bytes = (
|
||||
screenshot_bytes
|
||||
if isinstance(screenshot_bytes, bytes) and screenshot_bytes
|
||||
else base64.b64decode(clean_b64)
|
||||
)
|
||||
clean_b64 = screenshot_base64
|
||||
clean_bytes = screenshot_bytes
|
||||
if self._screenshot_config.enabled:
|
||||
limited_bytes = limit_screenshot_long_edge(
|
||||
clean_bytes, self._screenshot_config.max_long_edge
|
||||
@@ -255,7 +284,9 @@ class AndroidAdbDriver(BaseDeviceDriver):
|
||||
cmd = f" && sleep {delay_ms / 1000.0:.3f} && ".join(taps)
|
||||
|
||||
logger.info(f"[ADB] {cmd}")
|
||||
await asyncio.to_thread(self.device.shell, cmd)
|
||||
await asyncio.to_thread(
|
||||
self.device.shell, cmd, timeout=settings.ARTEMIS_DEVICE_COMMAND_TIMEOUT_SECONDS
|
||||
)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Tap failed at ({x}, {y}): {e}")
|
||||
@@ -275,7 +306,9 @@ class AndroidAdbDriver(BaseDeviceDriver):
|
||||
try:
|
||||
cmd = f"input swipe {start_x} {start_y} {end_x} {end_y} {duration_ms}"
|
||||
logger.info(f"[ADB] {cmd}")
|
||||
await asyncio.to_thread(self.device.shell, cmd)
|
||||
await asyncio.to_thread(
|
||||
self.device.shell, cmd, timeout=settings.ARTEMIS_DEVICE_COMMAND_TIMEOUT_SECONDS
|
||||
)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Swipe failed from ({start_x},{start_y}) to ({end_x},{end_y}): {e}")
|
||||
@@ -324,7 +357,11 @@ class AndroidAdbDriver(BaseDeviceDriver):
|
||||
"input keyevent 67 && "
|
||||
"input keyevent 67 67 67 67 67 67 67 67 67 67 67 67 67 67 67 67 67 67 67 67"
|
||||
)
|
||||
await asyncio.to_thread(self.device.shell, clear_cmd)
|
||||
await asyncio.to_thread(
|
||||
self.device.shell,
|
||||
clear_cmd,
|
||||
timeout=settings.ARTEMIS_DEVICE_COMMAND_TIMEOUT_SECONDS,
|
||||
)
|
||||
else:
|
||||
# Append mode: move cursor to the very end of existing text
|
||||
await asyncio.to_thread(
|
||||
@@ -346,7 +383,11 @@ class AndroidAdbDriver(BaseDeviceDriver):
|
||||
set_clip_ok = True
|
||||
|
||||
if set_clip_ok:
|
||||
await asyncio.to_thread(self.device.shell, "input keyevent 279")
|
||||
await asyncio.to_thread(
|
||||
self.device.shell,
|
||||
"input keyevent 279",
|
||||
timeout=settings.ARTEMIS_DEVICE_COMMAND_TIMEOUT_SECONDS,
|
||||
)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.debug(f"Clipboard paste fallback to ADB input: {e}")
|
||||
@@ -359,7 +400,11 @@ class AndroidAdbDriver(BaseDeviceDriver):
|
||||
if "adbkeyboard" in str(default_ime).lower():
|
||||
b64_text = base64.b64encode(norm_text.encode("utf-8")).decode("utf-8")
|
||||
broadcast_cmd = f"am broadcast -a ADB_INPUT_B64 --es msg '{b64_text}'"
|
||||
await asyncio.to_thread(self.device.shell, broadcast_cmd)
|
||||
await asyncio.to_thread(
|
||||
self.device.shell,
|
||||
broadcast_cmd,
|
||||
timeout=settings.ARTEMIS_DEVICE_COMMAND_TIMEOUT_SECONDS,
|
||||
)
|
||||
return True
|
||||
except Exception as e:
|
||||
# ADBKeyboard probe/broadcast failed; fall through to native input.
|
||||
@@ -370,10 +415,18 @@ class AndroidAdbDriver(BaseDeviceDriver):
|
||||
for i, line in enumerate(lines):
|
||||
if i > 0:
|
||||
# Send Enter key between lines
|
||||
await asyncio.to_thread(self.device.shell, "input keyevent 66")
|
||||
await asyncio.to_thread(
|
||||
self.device.shell,
|
||||
"input keyevent 66",
|
||||
timeout=settings.ARTEMIS_DEVICE_COMMAND_TIMEOUT_SECONDS,
|
||||
)
|
||||
if line:
|
||||
escaped = _escape_for_adb_text(line)
|
||||
await asyncio.to_thread(self.device.shell, f"input text {escaped}")
|
||||
await asyncio.to_thread(
|
||||
self.device.shell,
|
||||
f"input text {escaped}",
|
||||
timeout=settings.ARTEMIS_DEVICE_COMMAND_TIMEOUT_SECONDS,
|
||||
)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Input text failed for '{text}': {e}")
|
||||
@@ -386,7 +439,11 @@ class AndroidAdbDriver(BaseDeviceDriver):
|
||||
key_name = str(key).lower().replace("keycode.", "")
|
||||
keycode_val = ANDROID_KEYCODE_MAP.get(key_name, key)
|
||||
|
||||
await asyncio.to_thread(self.device.shell, f"input keyevent {keycode_val}")
|
||||
await asyncio.to_thread(
|
||||
self.device.shell,
|
||||
f"input keyevent {keycode_val}",
|
||||
timeout=settings.ARTEMIS_DEVICE_COMMAND_TIMEOUT_SECONDS,
|
||||
)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Press key failed for '{key}': {e}")
|
||||
@@ -395,7 +452,9 @@ class AndroidAdbDriver(BaseDeviceDriver):
|
||||
async def launch_app(self, package_name: str) -> bool:
|
||||
try:
|
||||
cmd = f"monkey -p {package_name} -c android.intent.category.LAUNCHER 1"
|
||||
await asyncio.to_thread(self.device.shell, cmd)
|
||||
await asyncio.to_thread(
|
||||
self.device.shell, cmd, timeout=settings.ARTEMIS_DEVICE_COMMAND_TIMEOUT_SECONDS
|
||||
)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Launch app failed for '{package_name}': {e}")
|
||||
@@ -403,7 +462,11 @@ class AndroidAdbDriver(BaseDeviceDriver):
|
||||
|
||||
async def stop_app(self, package_name: str) -> bool:
|
||||
try:
|
||||
await asyncio.to_thread(self.device.shell, f"am force-stop {package_name}")
|
||||
await asyncio.to_thread(
|
||||
self.device.shell,
|
||||
f"am force-stop {package_name}",
|
||||
timeout=settings.ARTEMIS_DEVICE_COMMAND_TIMEOUT_SECONDS,
|
||||
)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Stop app failed for '{package_name}': {e}")
|
||||
@@ -439,7 +502,11 @@ class AndroidAdbDriver(BaseDeviceDriver):
|
||||
async def execute_shell(self, command: str, timeout_seconds: float = 15.0) -> str:
|
||||
try:
|
||||
return await asyncio.wait_for(
|
||||
asyncio.to_thread(self.device.shell, command),
|
||||
asyncio.to_thread(
|
||||
self.device.shell,
|
||||
command,
|
||||
timeout=settings.ARTEMIS_DEVICE_COMMAND_TIMEOUT_SECONDS,
|
||||
),
|
||||
timeout=timeout_seconds,
|
||||
)
|
||||
except Exception as e:
|
||||
|
||||
@@ -51,212 +51,28 @@ ARTEMIS_MCP_TOOLS = (
|
||||
)
|
||||
|
||||
|
||||
def _eager_tools_config() -> dict[str, dict[str, bool]]:
|
||||
"""Return the eager-loading extension used by clients that support it."""
|
||||
return {tool_name: {"eager": True} for tool_name in ARTEMIS_MCP_TOOLS}
|
||||
|
||||
|
||||
def _get_vscode_user_dir() -> Path:
|
||||
"""Returns the platform-specific VS Code user configuration directory."""
|
||||
if sys.platform == "darwin":
|
||||
return Path.home() / "Library" / "Application Support" / "Code" / "User"
|
||||
elif sys.platform == "win32":
|
||||
appdata = os.environ.get("APPDATA") or str(Path.home() / "AppData" / "Roaming")
|
||||
return Path(appdata) / "Code" / "User"
|
||||
else:
|
||||
return Path.home() / ".config" / "Code" / "User"
|
||||
|
||||
|
||||
def _get_config_snippet(client: str, python_exe: str, project_root: str) -> dict:
|
||||
"""Generates MCP configuration dictionary for the specified client."""
|
||||
config_body = {
|
||||
"command": python_exe,
|
||||
"args": ["-m", "mcp_server"],
|
||||
"env": {
|
||||
"PYTHONUNBUFFERED": "1",
|
||||
"PYTHONPATH": project_root,
|
||||
"ARTEMIS_DESKTOP_NOTIFY": "true",
|
||||
},
|
||||
"""Generate the supported Codex MCP configuration."""
|
||||
if client != "codex":
|
||||
raise ValueError("Only Codex MCP configuration is supported")
|
||||
return {
|
||||
"mcp_servers": {
|
||||
"artemis": {
|
||||
"command": python_exe,
|
||||
"args": ["-m", "mcp_server"],
|
||||
"cwd": project_root,
|
||||
"env": {
|
||||
"PYTHONUNBUFFERED": "1",
|
||||
"PYTHONPATH": project_root,
|
||||
"ARTEMIS_DESKTOP_NOTIFY": "true",
|
||||
},
|
||||
"enabled": True,
|
||||
"required": True,
|
||||
"startup_timeout_sec": 120,
|
||||
"enabled_tools": list(ARTEMIS_MCP_TOOLS),
|
||||
}
|
||||
}
|
||||
}
|
||||
config_with_cwd = {**config_body, "cwd": project_root}
|
||||
|
||||
if client == "antigravity":
|
||||
return {
|
||||
"mcpServers": {
|
||||
"artemis": {
|
||||
**config_with_cwd,
|
||||
# This is the documented way to expose every tool. Avoid
|
||||
# proprietary eager fields in the current config so a
|
||||
# strict parser can always load the server.
|
||||
"disabledTools": [],
|
||||
}
|
||||
}
|
||||
}
|
||||
elif client == "jetski":
|
||||
return {
|
||||
"mcpServers": {
|
||||
"artemis": {
|
||||
**config_with_cwd,
|
||||
"disabledTools": [],
|
||||
# Retain the legacy Jetski eager extension only in its
|
||||
# legacy config file. Current Antigravity gets the strict,
|
||||
# documented configuration above as a safe fallback.
|
||||
"tools": _eager_tools_config(),
|
||||
}
|
||||
}
|
||||
}
|
||||
elif client == "openclaw":
|
||||
return {
|
||||
"mcp": {
|
||||
"servers": {
|
||||
"artemis": {
|
||||
**config_with_cwd,
|
||||
"enabled": True,
|
||||
"connectionTimeoutMs": 120000,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
elif client == "codex":
|
||||
return {
|
||||
"mcp_servers": {
|
||||
"artemis": {
|
||||
**config_with_cwd,
|
||||
# Codex has no eager/deferred MCP setting. Requiring the
|
||||
# server makes it initialize during host startup, while an
|
||||
# explicit allow-list guarantees all Artemis tools are
|
||||
# registered. The host may still present schemas through
|
||||
# tool search to control context size.
|
||||
"enabled": True,
|
||||
"required": True,
|
||||
"startup_timeout_sec": 120,
|
||||
"enabled_tools": list(ARTEMIS_MCP_TOOLS),
|
||||
}
|
||||
}
|
||||
}
|
||||
elif client == "vscode":
|
||||
return {"servers": {"artemis": {**config_with_cwd, "type": "stdio"}}}
|
||||
elif client in ("claude", "claude_code", "claude_desktop"):
|
||||
return {"mcpServers": {"artemis": {**config_body, "type": "stdio"}}}
|
||||
elif client == "cline":
|
||||
return {
|
||||
"mcpServers": {
|
||||
"artemis": {
|
||||
**config_body,
|
||||
"disabled": False,
|
||||
"autoApprove": [],
|
||||
"timeout": 120,
|
||||
}
|
||||
}
|
||||
}
|
||||
elif client in ("roo", "roo_code"):
|
||||
return {
|
||||
"mcpServers": {
|
||||
"artemis": {
|
||||
**config_body,
|
||||
"disabled": False,
|
||||
"alwaysAllow": [],
|
||||
"timeout": 120,
|
||||
}
|
||||
}
|
||||
}
|
||||
else: # cursor, windsurf, generic
|
||||
return {"mcpServers": {"artemis": config_body}}
|
||||
|
||||
|
||||
def _parse_json_lenient(text: str) -> dict | None:
|
||||
"""Parses JSON or JSONC (JSON with comments / trailing commas) safely.
|
||||
|
||||
Returns ``None`` when the text cannot be parsed as a JSON object, so callers
|
||||
can tell a genuinely empty ``{}`` file apart from a corrupt one.
|
||||
"""
|
||||
try:
|
||||
data = json.loads(text)
|
||||
return data if isinstance(data, dict) else None
|
||||
except ValueError:
|
||||
# Not strict JSON; fall through to the lenient JSONC cleanup below.
|
||||
pass
|
||||
# Remove // single-line comments
|
||||
cleaned = re.sub(r"//.*", "", text)
|
||||
# Remove /* ... */ multi-line comments
|
||||
cleaned = re.sub(r"/\*.*?\*/", "", cleaned, flags=re.DOTALL)
|
||||
# Remove trailing commas before } or ]
|
||||
cleaned = re.sub(r",\s*([}\]])", r"\1", cleaned)
|
||||
try:
|
||||
data = json.loads(cleaned)
|
||||
return data if isinstance(data, dict) else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _merge_json_file(
|
||||
file_path: Path,
|
||||
server_name: str,
|
||||
server_config: dict,
|
||||
key_name: str | tuple[str, ...] = "mcpServers",
|
||||
remove_paths: tuple[tuple[str, ...], ...] = (),
|
||||
strict_parse: bool = False,
|
||||
) -> bool:
|
||||
"""Merges server configuration into a target JSON file without overwriting existing servers.
|
||||
|
||||
With ``strict_parse=True``, an existing non-empty file that cannot be parsed
|
||||
aborts the merge instead of being replaced. Use this for files that hold
|
||||
state beyond MCP config (e.g. ~/.claude.json), where a degraded rewrite
|
||||
would destroy unrelated data.
|
||||
"""
|
||||
try:
|
||||
file_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
data: dict = {}
|
||||
if file_path.exists() and file_path.stat().st_size > 0:
|
||||
raw_text = file_path.read_text(encoding="utf-8")
|
||||
parsed = _parse_json_lenient(raw_text)
|
||||
data = parsed or {}
|
||||
if parsed is None and raw_text.strip():
|
||||
if strict_parse:
|
||||
logger.warning(
|
||||
f"Existing JSON in {file_path} could not be parsed; refusing to rewrite it. "
|
||||
"Fix or remove the file, then re-run the install."
|
||||
)
|
||||
return False
|
||||
# Backup unparseable existing file to prevent accidental loss
|
||||
backup_path = file_path.with_suffix(file_path.suffix + ".bak")
|
||||
try:
|
||||
backup_path.write_text(raw_text, encoding="utf-8")
|
||||
logger.warning(
|
||||
f"Existing JSON in {file_path} could not be parsed; backup created at {backup_path}"
|
||||
)
|
||||
except OSError as exc:
|
||||
logger.warning(
|
||||
f"Existing JSON in {file_path} could not be parsed AND the backup to"
|
||||
f" {backup_path} failed ({exc}); refusing to rewrite it."
|
||||
" Fix or remove the file, then re-run the install."
|
||||
)
|
||||
return False
|
||||
|
||||
for remove_path in remove_paths:
|
||||
parent = data
|
||||
for part in remove_path[:-1]:
|
||||
child = parent.get(part)
|
||||
if not isinstance(child, dict):
|
||||
parent = {}
|
||||
break
|
||||
parent = child
|
||||
if parent:
|
||||
parent.pop(remove_path[-1], None)
|
||||
|
||||
key_path = (key_name,) if isinstance(key_name, str) else key_name
|
||||
target = data
|
||||
for part in key_path:
|
||||
if not isinstance(target.get(part), dict):
|
||||
target[part] = {}
|
||||
target = target[part]
|
||||
|
||||
target[server_name] = server_config
|
||||
file_path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning(f"Could not update MCP config file {file_path}: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def _codex_toml_block(server_config: dict) -> str:
|
||||
@@ -302,7 +118,9 @@ def _merge_codex_toml(file_path: Path, server_config: dict) -> bool:
|
||||
managed_pattern = re.compile(
|
||||
rf"(?ms)^{re.escape(begin_marker)}\n.*?^{re.escape(end_marker)}\n?"
|
||||
)
|
||||
updated = managed_pattern.sub(managed_block, existing, count=1)
|
||||
# Windows paths contain backslashes; a replacement string would
|
||||
# interpret them as regex escapes on a second installation.
|
||||
updated = managed_pattern.sub(lambda _: managed_block, existing, count=1)
|
||||
else:
|
||||
# Remove an older, unmanaged Artemis table before adding the managed block.
|
||||
kept_lines: list[str] = []
|
||||
@@ -342,36 +160,6 @@ def _merge_codex_toml(file_path: Path, server_config: dict) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _remove_rules_block(file_path: Path) -> bool:
|
||||
"""Removes a previously injected managed ARTEMIS block from a rules file.
|
||||
|
||||
Used to migrate clients that load both their main rules file and a
|
||||
standalone rule file (e.g. Claude Code loads ~/.claude/CLAUDE.md AND
|
||||
~/.claude/rules/*.md), where keeping the injected block would duplicate
|
||||
the rules in the model's context. If the file contains nothing but the
|
||||
managed block, the file is deleted entirely.
|
||||
"""
|
||||
try:
|
||||
if not file_path.exists():
|
||||
return True
|
||||
begin_marker = "<!-- BEGIN ARTEMIS MOBILE TESTING RULES -->"
|
||||
end_marker = "<!-- END ARTEMIS MOBILE TESTING RULES -->"
|
||||
existing = file_path.read_text(encoding="utf-8")
|
||||
if begin_marker not in existing or end_marker not in existing:
|
||||
return True
|
||||
prefix = existing.split(begin_marker)[0]
|
||||
suffix = existing.split(end_marker)[1]
|
||||
remainder = f"{prefix.rstrip()}\n\n{suffix.lstrip()}".strip()
|
||||
if remainder:
|
||||
file_path.write_text(remainder + "\n", encoding="utf-8")
|
||||
else:
|
||||
file_path.unlink()
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning(f"Could not remove rules block from {file_path}: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def _inject_rules_block(file_path: Path, content: str) -> bool:
|
||||
"""Injects or updates a managed ARTEMIS block in a global rules file without overwriting user content."""
|
||||
try:
|
||||
@@ -404,297 +192,36 @@ def _inject_rules_block(file_path: Path, content: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _write_rule_file(file_path: Path, content: str) -> bool:
|
||||
"""Writes or overwrites a standalone rule file."""
|
||||
try:
|
||||
file_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
new_text = content.strip() + "\n"
|
||||
if file_path.exists():
|
||||
try:
|
||||
if file_path.read_text(encoding="utf-8") == new_text:
|
||||
return True
|
||||
except (OSError, UnicodeDecodeError):
|
||||
# Unreadable existing file: skip the no-op check and rewrite it.
|
||||
pass
|
||||
file_path.write_text(new_text, encoding="utf-8")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning(f"Could not write rule file {file_path}: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def _write_cursor_mdc(file_path: Path, content: str) -> bool:
|
||||
"""Writes a Cursor .mdc rule file with required YAML frontmatter."""
|
||||
try:
|
||||
file_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
mdc_header = (
|
||||
"---\n"
|
||||
"description: Artemis Mobile Testing Mindset & Rules\n"
|
||||
"globs: **/*\n"
|
||||
"alwaysApply: true\n"
|
||||
"---\n\n"
|
||||
)
|
||||
new_text = mdc_header + content.strip() + "\n"
|
||||
if file_path.exists():
|
||||
try:
|
||||
if file_path.read_text(encoding="utf-8") == new_text:
|
||||
return True
|
||||
except (OSError, UnicodeDecodeError):
|
||||
# Unreadable existing file: skip the no-op check and rewrite it.
|
||||
pass
|
||||
file_path.write_text(new_text, encoding="utf-8")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning(f"Could not write Cursor rule file {file_path}: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def install_rules(client: str, project_root: str) -> list[str]:
|
||||
"""Auto-installs ARTEMIS testing rules globally into user IDE rule directories across any OS."""
|
||||
installed_paths: list[str] = []
|
||||
"""Install testing rules only into the Codex instructions file."""
|
||||
if client != "codex":
|
||||
raise ValueError("Only Codex MCP configuration is supported")
|
||||
rules_src = Path(project_root) / "mcp_server" / "rules.md"
|
||||
if not rules_src.exists():
|
||||
alt_src = Path(__file__).resolve().parents[4] / "mcp_server" / "rules.md"
|
||||
if alt_src.exists():
|
||||
rules_src = alt_src
|
||||
else:
|
||||
logger.warning(f"Could not locate rules.md at {rules_src}")
|
||||
return []
|
||||
|
||||
rules_src = Path(__file__).resolve().parents[4] / "mcp_server" / "rules.md"
|
||||
try:
|
||||
raw_rules = rules_src.read_text(encoding="utf-8").strip()
|
||||
except Exception as e:
|
||||
logger.warning(f"Could not read rules file {rules_src}: {e}")
|
||||
except OSError:
|
||||
logger.warning(f"Could not read rules file {rules_src}")
|
||||
return []
|
||||
|
||||
targets = (
|
||||
[
|
||||
"antigravity",
|
||||
"cursor",
|
||||
"claude",
|
||||
"windsurf",
|
||||
"vscode",
|
||||
"cline",
|
||||
"roo",
|
||||
"openclaw",
|
||||
"codex",
|
||||
]
|
||||
if client == "all"
|
||||
else [client]
|
||||
codex_home = Path(os.environ.get("CODEX_HOME") or (Path.home() / ".codex"))
|
||||
override_file = codex_home / "AGENTS.override.md"
|
||||
agents_file = (
|
||||
override_file
|
||||
if override_file.exists() and override_file.read_text(encoding="utf-8").strip()
|
||||
else codex_home / "AGENTS.md"
|
||||
)
|
||||
|
||||
for target in targets:
|
||||
if target in ("antigravity", "jetski"):
|
||||
gemini_md = Path.home() / ".gemini" / "GEMINI.md"
|
||||
global_rule = Path.home() / ".gemini" / "rules" / "artemis.md"
|
||||
if _inject_rules_block(gemini_md, raw_rules):
|
||||
installed_paths.append(str(gemini_md))
|
||||
if _write_rule_file(global_rule, raw_rules):
|
||||
installed_paths.append(str(global_rule))
|
||||
elif target == "cursor":
|
||||
cursor_rules_file = Path.home() / ".cursorrules"
|
||||
global_mdc = Path.home() / ".cursor" / "rules" / "artemis.mdc"
|
||||
if _inject_rules_block(cursor_rules_file, raw_rules):
|
||||
installed_paths.append(str(cursor_rules_file))
|
||||
if _write_cursor_mdc(global_mdc, raw_rules):
|
||||
installed_paths.append(str(global_mdc))
|
||||
elif target in ("claude", "claude_code"):
|
||||
# Claude Code loads BOTH ~/.claude/CLAUDE.md and ~/.claude/rules/*.md
|
||||
# into context every session, so install the rules in exactly one
|
||||
# place (the standalone rule file) and migrate away any block a
|
||||
# previous version injected into CLAUDE.md.
|
||||
claude_md = Path.home() / ".claude" / "CLAUDE.md"
|
||||
global_rule = Path.home() / ".claude" / "rules" / "artemis.md"
|
||||
_remove_rules_block(claude_md)
|
||||
if _write_rule_file(global_rule, raw_rules):
|
||||
installed_paths.append(str(global_rule))
|
||||
elif target == "claude_desktop":
|
||||
# Claude Desktop only reads ~/.claude/CLAUDE.md (not rules/*.md), so
|
||||
# the rules block stays injected there for this target.
|
||||
claude_md = Path.home() / ".claude" / "CLAUDE.md"
|
||||
if _inject_rules_block(claude_md, raw_rules):
|
||||
installed_paths.append(str(claude_md))
|
||||
elif target == "windsurf":
|
||||
global_rule = Path.home() / ".codeium" / "windsurf" / "rules" / "artemis.md"
|
||||
global_mem = Path.home() / ".codeium" / "windsurf" / "memories" / "global_rules.md"
|
||||
if _inject_rules_block(global_mem, raw_rules):
|
||||
installed_paths.append(str(global_mem))
|
||||
if _write_rule_file(global_rule, raw_rules):
|
||||
installed_paths.append(str(global_rule))
|
||||
elif target == "vscode":
|
||||
global_rule = Path.home() / ".vscode" / "rules" / "artemis.md"
|
||||
user_rule = _get_vscode_user_dir() / "rules" / "artemis.md"
|
||||
if _write_rule_file(global_rule, raw_rules):
|
||||
installed_paths.append(str(global_rule))
|
||||
if _write_rule_file(user_rule, raw_rules):
|
||||
installed_paths.append(str(user_rule))
|
||||
elif target == "cline":
|
||||
clinerules = Path.home() / ".clinerules"
|
||||
global_rule = Path.home() / ".cline" / "rules" / "artemis.md"
|
||||
if _inject_rules_block(clinerules, raw_rules):
|
||||
installed_paths.append(str(clinerules))
|
||||
if _write_rule_file(global_rule, raw_rules):
|
||||
installed_paths.append(str(global_rule))
|
||||
elif target in ("roo", "roo_code"):
|
||||
roorules = Path.home() / ".roorules"
|
||||
global_rule = Path.home() / ".roo" / "rules" / "artemis.md"
|
||||
if _inject_rules_block(roorules, raw_rules):
|
||||
installed_paths.append(str(roorules))
|
||||
if _write_rule_file(global_rule, raw_rules):
|
||||
installed_paths.append(str(global_rule))
|
||||
elif target == "openclaw":
|
||||
openclaw_md = Path.home() / ".openclaw" / "OPENCLAW.md"
|
||||
global_rule = Path.home() / ".openclaw" / "rules" / "artemis.md"
|
||||
if _inject_rules_block(openclaw_md, raw_rules):
|
||||
installed_paths.append(str(openclaw_md))
|
||||
if _write_rule_file(global_rule, raw_rules):
|
||||
installed_paths.append(str(global_rule))
|
||||
elif target == "codex":
|
||||
codex_home = Path(os.environ.get("CODEX_HOME") or (Path.home() / ".codex"))
|
||||
override_file = codex_home / "AGENTS.override.md"
|
||||
agents_file = (
|
||||
override_file
|
||||
if override_file.exists() and override_file.read_text(encoding="utf-8").strip()
|
||||
else codex_home / "AGENTS.md"
|
||||
)
|
||||
if _inject_rules_block(agents_file, raw_rules):
|
||||
installed_paths.append(str(agents_file))
|
||||
|
||||
return installed_paths
|
||||
return [str(agents_file)] if _inject_rules_block(agents_file, raw_rules) else []
|
||||
|
||||
|
||||
def install_mcp_config(client: str, python_exe: str, project_root: str) -> list[str]:
|
||||
"""Auto-installs/merges ARTEMIS MCP configuration and testing rules into IDE config files across any OS."""
|
||||
installed_paths: list[str] = []
|
||||
targets = (
|
||||
[
|
||||
"antigravity",
|
||||
"cursor",
|
||||
"claude",
|
||||
"windsurf",
|
||||
"vscode",
|
||||
"cline",
|
||||
"roo",
|
||||
"openclaw",
|
||||
"codex",
|
||||
]
|
||||
if client == "all"
|
||||
else [client]
|
||||
)
|
||||
|
||||
for target in targets:
|
||||
snippet = _get_config_snippet(target, python_exe, project_root)
|
||||
if target in ("antigravity", "jetski"):
|
||||
current_server_cfg = _get_config_snippet("antigravity", python_exe, project_root)[
|
||||
"mcpServers"
|
||||
]["artemis"]
|
||||
legacy_server_cfg = _get_config_snippet("jetski", python_exe, project_root)[
|
||||
"mcpServers"
|
||||
]["artemis"]
|
||||
jetski_path = Path.home() / ".gemini" / "jetski" / "mcp_config.json"
|
||||
antigravity_legacy_path = Path.home() / ".gemini" / "antigravity" / "mcp_config.json"
|
||||
config_path = Path.home() / ".gemini" / "config" / "mcp_config.json"
|
||||
if _merge_json_file(jetski_path, "artemis", legacy_server_cfg):
|
||||
installed_paths.append(str(jetski_path))
|
||||
if _merge_json_file(antigravity_legacy_path, "artemis", current_server_cfg):
|
||||
installed_paths.append(str(antigravity_legacy_path))
|
||||
if _merge_json_file(config_path, "artemis", current_server_cfg):
|
||||
installed_paths.append(str(config_path))
|
||||
elif target in ("claude", "claude_code", "claude_desktop"):
|
||||
server_cfg = snippet["mcpServers"]["artemis"]
|
||||
if sys.platform == "darwin":
|
||||
claude_path = (
|
||||
Path.home()
|
||||
/ "Library"
|
||||
/ "Application Support"
|
||||
/ "Claude"
|
||||
/ "claude_desktop_config.json"
|
||||
)
|
||||
elif sys.platform == "win32":
|
||||
appdata = os.environ.get("APPDATA") or str(Path.home() / "AppData" / "Roaming")
|
||||
claude_path = Path(appdata) / "Claude" / "claude_desktop_config.json"
|
||||
else:
|
||||
claude_path = Path.home() / ".config" / "Claude" / "claude_desktop_config.json"
|
||||
if _merge_json_file(claude_path, "artemis", server_cfg):
|
||||
installed_paths.append(str(claude_path))
|
||||
|
||||
# Also install to Claude Code CLI global config (~/.claude.json).
|
||||
# This file holds Claude Code state well beyond MCP config, so a
|
||||
# parse failure must abort the merge rather than rewrite the file.
|
||||
claude_code_path = Path.home() / ".claude.json"
|
||||
if _merge_json_file(claude_code_path, "artemis", server_cfg, strict_parse=True):
|
||||
installed_paths.append(str(claude_code_path))
|
||||
elif target == "cursor":
|
||||
server_cfg = snippet["mcpServers"]["artemis"]
|
||||
cursor_path = Path.home() / ".cursor" / "mcp.json"
|
||||
if _merge_json_file(cursor_path, "artemis", server_cfg):
|
||||
installed_paths.append(str(cursor_path))
|
||||
elif target == "windsurf":
|
||||
server_cfg = snippet["mcpServers"]["artemis"]
|
||||
windsurf_path = Path.home() / ".codeium" / "windsurf" / "mcp_config.json"
|
||||
if _merge_json_file(windsurf_path, "artemis", server_cfg):
|
||||
installed_paths.append(str(windsurf_path))
|
||||
elif target == "vscode":
|
||||
server_cfg = snippet["servers"]["artemis"]
|
||||
vscode_path = _get_vscode_user_dir() / "mcp.json"
|
||||
copilot_path = Path.home() / ".copilot" / "mcp-config.json"
|
||||
if _merge_json_file(vscode_path, "artemis", server_cfg, key_name="servers"):
|
||||
installed_paths.append(str(vscode_path))
|
||||
if _merge_json_file(copilot_path, "artemis", server_cfg, key_name="servers"):
|
||||
installed_paths.append(str(copilot_path))
|
||||
elif target == "cline":
|
||||
server_cfg = snippet["mcpServers"]["artemis"]
|
||||
cline_paths = (
|
||||
Path.home() / ".cline" / "data" / "settings" / "cline_mcp_settings.json",
|
||||
Path.home() / ".cline" / "mcp.json",
|
||||
_get_vscode_user_dir()
|
||||
/ "globalStorage"
|
||||
/ "saoudrizwan.claude-dev"
|
||||
/ "settings"
|
||||
/ "cline_mcp_settings.json",
|
||||
)
|
||||
for cline_path in cline_paths:
|
||||
if _merge_json_file(cline_path, "artemis", server_cfg):
|
||||
installed_paths.append(str(cline_path))
|
||||
elif target in ("roo", "roo_code"):
|
||||
server_cfg = snippet["mcpServers"]["artemis"]
|
||||
roo_settings_dir = (
|
||||
_get_vscode_user_dir() / "globalStorage" / "rooveterinaryinc.roo-cline" / "settings"
|
||||
)
|
||||
roo_paths = (
|
||||
roo_settings_dir / "mcp_settings.json",
|
||||
roo_settings_dir / "cline_mcp_settings.json",
|
||||
Path(project_root) / ".roo" / "mcp.json",
|
||||
)
|
||||
for roo_path in roo_paths:
|
||||
if _merge_json_file(roo_path, "artemis", server_cfg):
|
||||
installed_paths.append(str(roo_path))
|
||||
elif target == "openclaw":
|
||||
server_cfg = snippet["mcp"]["servers"]["artemis"]
|
||||
openclaw_path = Path.home() / ".openclaw" / "openclaw.json"
|
||||
if _merge_json_file(
|
||||
openclaw_path,
|
||||
"artemis",
|
||||
server_cfg,
|
||||
key_name=("mcp", "servers"),
|
||||
remove_paths=(("plugins", "artemis_mcp"),),
|
||||
):
|
||||
installed_paths.append(str(openclaw_path))
|
||||
elif target == "codex":
|
||||
server_cfg = snippet["mcp_servers"]["artemis"]
|
||||
codex_home = Path(os.environ.get("CODEX_HOME") or (Path.home() / ".codex"))
|
||||
codex_path = codex_home / "config.toml"
|
||||
if _merge_codex_toml(codex_path, server_cfg):
|
||||
installed_paths.append(str(codex_path))
|
||||
|
||||
rules_paths = install_rules(client, project_root)
|
||||
installed_paths.extend(rules_paths)
|
||||
|
||||
unique_paths: list[str] = []
|
||||
for p in installed_paths:
|
||||
if p not in unique_paths:
|
||||
unique_paths.append(p)
|
||||
return unique_paths
|
||||
"""Install ARTEMIS configuration and rules only for Codex."""
|
||||
server_cfg = _get_config_snippet(client, python_exe, project_root)["mcp_servers"]["artemis"]
|
||||
codex_home = Path(os.environ.get("CODEX_HOME") or (Path.home() / ".codex"))
|
||||
codex_path = codex_home / "config.toml"
|
||||
if not _merge_codex_toml(codex_path, server_cfg):
|
||||
raise typer.Exit(1)
|
||||
return [str(codex_path), *install_rules(client, project_root)]
|
||||
|
||||
|
||||
def mcp_command(
|
||||
@@ -733,7 +260,7 @@ def mcp_command(
|
||||
typer.Option(
|
||||
"--install",
|
||||
"-i",
|
||||
help="Auto-install and merge ARTEMIS MCP configuration and testing rules into 'antigravity', 'claude', 'cursor', 'windsurf', 'vscode', 'cline', 'roo', 'openclaw', 'codex', or 'all'.",
|
||||
help="Install ARTEMIS MCP configuration and testing rules for Codex: --install codex.",
|
||||
),
|
||||
] = None,
|
||||
generate_config: Annotated[
|
||||
@@ -741,7 +268,7 @@ def mcp_command(
|
||||
typer.Option(
|
||||
"--generate-config",
|
||||
"-g",
|
||||
help="Output ready-to-use MCP configuration for 'antigravity', 'cursor', 'claude', 'windsurf', 'vscode', 'cline', 'roo', 'openclaw', 'codex', or 'all'.",
|
||||
help="Output ready-to-use Codex TOML configuration: --generate-config codex.",
|
||||
),
|
||||
] = None,
|
||||
) -> None:
|
||||
@@ -751,24 +278,9 @@ def mcp_command(
|
||||
|
||||
if install_config:
|
||||
client = install_config.lower()
|
||||
if client not in (
|
||||
"antigravity",
|
||||
"jetski",
|
||||
"claude",
|
||||
"claude_code",
|
||||
"claude_desktop",
|
||||
"cursor",
|
||||
"windsurf",
|
||||
"vscode",
|
||||
"cline",
|
||||
"roo",
|
||||
"roo_code",
|
||||
"openclaw",
|
||||
"codex",
|
||||
"all",
|
||||
):
|
||||
if client != "codex":
|
||||
console.print(
|
||||
f"[bold red]Unsupported install target: '{install_config}'. Use 'antigravity', 'claude', 'cursor', 'windsurf', 'vscode', 'cline', 'roo', 'openclaw', 'codex', or 'all'.[/bold red]"
|
||||
"[bold red]目前仅支持 Codex MCP 配置,请使用 --install codex。[/bold red]"
|
||||
)
|
||||
raise typer.Exit(1)
|
||||
installed_paths = install_mcp_config(client, python_exe, project_root)
|
||||
@@ -784,46 +296,14 @@ def mcp_command(
|
||||
|
||||
if generate_config:
|
||||
client = generate_config.lower()
|
||||
if client == "all":
|
||||
all_configs = {
|
||||
"antigravity (~/.gemini/jetski/mcp_config.json)": _get_config_snippet(
|
||||
"antigravity", python_exe, project_root
|
||||
),
|
||||
"cursor (.cursor/mcp.json)": _get_config_snippet(
|
||||
"cursor", python_exe, project_root
|
||||
),
|
||||
"claude (claude_desktop_config.json & ~/.claude.json)": _get_config_snippet(
|
||||
"claude", python_exe, project_root
|
||||
),
|
||||
"windsurf (~/.codeium/windsurf/mcp_config.json)": _get_config_snippet(
|
||||
"windsurf", python_exe, project_root
|
||||
),
|
||||
"vscode (mcp.json)": _get_config_snippet("vscode", python_exe, project_root),
|
||||
"cline (cline_mcp_settings.json)": _get_config_snippet(
|
||||
"cline", python_exe, project_root
|
||||
),
|
||||
"roo (cline_mcp_settings.json)": _get_config_snippet(
|
||||
"roo", python_exe, project_root
|
||||
),
|
||||
"openclaw (openclaw.json)": _get_config_snippet(
|
||||
"openclaw", python_exe, project_root
|
||||
),
|
||||
"codex (~/.codex/config.toml)": _get_config_snippet(
|
||||
"codex", python_exe, project_root
|
||||
),
|
||||
}
|
||||
json_str = json.dumps(all_configs, indent=2)
|
||||
syntax_language = "json"
|
||||
elif client == "codex":
|
||||
server_cfg = _get_config_snippet("codex", python_exe, project_root)["mcp_servers"][
|
||||
"artemis"
|
||||
]
|
||||
json_str = _codex_toml_block(server_cfg)
|
||||
syntax_language = "toml"
|
||||
else:
|
||||
snippet = _get_config_snippet(client, python_exe, project_root)
|
||||
json_str = json.dumps(snippet, indent=2)
|
||||
syntax_language = "json"
|
||||
if client != "codex":
|
||||
console.print(
|
||||
"[bold red]目前仅支持 Codex MCP 配置,请使用 --generate-config codex。[/bold red]"
|
||||
)
|
||||
raise typer.Exit(1)
|
||||
server_cfg = _get_config_snippet(client, python_exe, project_root)["mcp_servers"]["artemis"]
|
||||
json_str = _codex_toml_block(server_cfg)
|
||||
syntax_language = "toml"
|
||||
|
||||
syntax = Syntax(json_str, syntax_language, theme="monokai", line_numbers=False)
|
||||
console.print(f"[bold cyan]MCP Configuration for {client.upper()}:[/bold cyan]")
|
||||
|
||||
@@ -43,6 +43,7 @@ from artemis.clients.screen_client_factory import create_screen_client
|
||||
from artemis.context import ArtemisContext, DeviceContext, DevicePlatform
|
||||
from artemis.controllers.unified_controller import UnifiedMobileController
|
||||
from artemis.platform import platform
|
||||
from artemis.runtime.adb_endpoint import AdbEndpoint
|
||||
from artemis.utils.app_launch_utils import launch_app_with_retries
|
||||
|
||||
|
||||
@@ -127,7 +128,7 @@ def _get_controller(device_serial: str | None = None):
|
||||
port_str = os.environ.get("ADB_PORT", "5037")
|
||||
port = int(port_str) if port_str.isdigit() else 5037
|
||||
if "ADB_SERVER_SOCKET" not in os.environ and (host != "localhost" or port != 5037):
|
||||
os.environ["ADB_SERVER_SOCKET"] = f"tcp:{host}:{port}"
|
||||
os.environ["ADB_SERVER_SOCKET"] = AdbEndpoint.create(host, port).client_socket
|
||||
adb = AdbClient(host=host, port=port)
|
||||
|
||||
devices = adb.device_list()
|
||||
|
||||
@@ -22,9 +22,12 @@ Validator -- which runs its own UI-change polling -- simply never calls it.
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
from io import BytesIO
|
||||
import time
|
||||
from PIL import Image
|
||||
|
||||
from artemis.config import get_temp_dir
|
||||
from artemis.config.settings import settings
|
||||
from artemis.context import ArtemisContext
|
||||
from artemis.controllers.unified_controller import UnifiedMobileController
|
||||
from artemis.mcp.action_types import ActionCode, ObserveResult
|
||||
@@ -34,7 +37,29 @@ from artemis.utils.visualization import format_minimal_list_with_elements
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
__all__ = ["observe"]
|
||||
__all__ = ["observe", "require_observation", "DeviceObservationError"]
|
||||
|
||||
|
||||
class DeviceObservationError(RuntimeError):
|
||||
"""A live device could not be observed after bounded recovery."""
|
||||
|
||||
|
||||
async def require_observation(
|
||||
ctx: ArtemisContext, controller: UnifiedMobileController, settle_ms: int = 400
|
||||
) -> tuple[ObserveResult, bytes | None]:
|
||||
"""Recover observation without spending model calls on unavailable screens."""
|
||||
last = "设备未返回有效画面"
|
||||
for attempt in range(settings.ARTEMIS_OBSERVATION_MAX_ATTEMPTS):
|
||||
observation, image = await observe(ctx, controller, settle_ms=settle_ms)
|
||||
if observation.ok:
|
||||
return observation, image
|
||||
last = observation.message
|
||||
logger.warning(
|
||||
f"设备观测恢复 {attempt + 1}/{settings.ARTEMIS_OBSERVATION_MAX_ATTEMPTS}:{last}"
|
||||
)
|
||||
raise DeviceObservationError(
|
||||
f"设备观测失败(已尝试 {settings.ARTEMIS_OBSERVATION_MAX_ATTEMPTS} 次):{last}"
|
||||
)
|
||||
|
||||
|
||||
async def observe(
|
||||
@@ -60,9 +85,19 @@ async def observe(
|
||||
await asyncio.sleep(settle_ms / 1000.0)
|
||||
else:
|
||||
logger.info("Retrieving screen data directly (skip settling)...")
|
||||
device_data = await controller.get_screen_data()
|
||||
device_data = await asyncio.wait_for(
|
||||
controller.get_screen_data(), timeout=settings.ARTEMIS_OBSERVATION_TIMEOUT_SECONDS
|
||||
)
|
||||
screenshot_bytes = base64.b64decode(device_data.base64)
|
||||
with Image.open(BytesIO(screenshot_bytes)) as image:
|
||||
if min(image.size) <= 1:
|
||||
raise ValueError("设备截图为占位图,当前画面不可用")
|
||||
image.verify()
|
||||
except Exception as e:
|
||||
if isinstance(e, TimeoutError):
|
||||
e = TimeoutError(
|
||||
f"设备屏幕观测超时({settings.ARTEMIS_OBSERVATION_TIMEOUT_SECONDS:g} 秒)"
|
||||
)
|
||||
logger.error(f"Failed to capture screen state: {e}")
|
||||
return (
|
||||
ObserveResult(
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
"""Bounded TCP device discovery shared by the console, CLI and MCP.
|
||||
|
||||
USB and Android SDK emulators are discovered by ADB itself. Third-party
|
||||
emulators expose TCP adbd listeners; only listeners owned by known emulator
|
||||
processes are probed. Explicitly connected TCP devices are remembered separately.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
|
||||
import psutil
|
||||
|
||||
from artemis.config import settings
|
||||
from artemis.config.paths import get_app_dir
|
||||
from artemis.runtime.adb_endpoint import AdbSession, current_adb_endpoint
|
||||
from artemis.utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def _canonical_target(target: str) -> str:
|
||||
host, separator, port = target.rpartition(":")
|
||||
if separator and host.lower() in {"localhost", "127.0.0.1"}:
|
||||
return f"127.0.0.1:{port}"
|
||||
return target
|
||||
|
||||
|
||||
def emulator_listeners() -> list[list[str]]:
|
||||
"""Return listener groups, one per running emulator (never scan a network)."""
|
||||
owners = set()
|
||||
for process in psutil.process_iter(["pid", "name", "exe"]):
|
||||
info = process.info
|
||||
name = str(info.get("name") or "").lower().removesuffix(".exe")
|
||||
path = str(info.get("exe") or "").lower()
|
||||
known = name in {
|
||||
"mumunxdevice",
|
||||
"nemuheadless",
|
||||
"mumuheadless",
|
||||
"ldvboxheadless",
|
||||
"noxvmhandle",
|
||||
"memuheadless",
|
||||
"hd-player",
|
||||
}
|
||||
vendor_vm = name == "vboxheadless" and any(
|
||||
vendor in path for vendor in ("mumu", "nemu", "ldplayer", "leidian", "nox", "memu")
|
||||
)
|
||||
if known or vendor_vm:
|
||||
owners.add(info["pid"])
|
||||
if not owners:
|
||||
return []
|
||||
groups: dict[int, set[int]] = {}
|
||||
for connection in psutil.net_connections(kind="tcp"):
|
||||
address = connection.laddr
|
||||
pid = connection.pid
|
||||
if (
|
||||
pid is not None
|
||||
and pid in owners
|
||||
and address
|
||||
and connection.status == psutil.CONN_LISTEN
|
||||
and address.ip in {"127.0.0.1", "0.0.0.0"}
|
||||
):
|
||||
groups.setdefault(pid, set()).add(address.port)
|
||||
# Prefer current MuMu ports over its compatibility aliases (same adbd).
|
||||
return [
|
||||
[f"127.0.0.1:{port}" for port in sorted(ports, key=lambda p: (p in {5555, 7555}, p))]
|
||||
for ports in groups.values()
|
||||
]
|
||||
|
||||
|
||||
def is_adbd(target: str, timeout: float) -> bool:
|
||||
"""Confirm an ADB CNXN/AUTH header before giving a local port to adb connect."""
|
||||
host, port = target.rsplit(":", 1)
|
||||
payload = b"host::\x00"
|
||||
command = int.from_bytes(b"CNXN", "little")
|
||||
packet = struct.pack(
|
||||
"<6I", command, 0x01000000, 4096, len(payload), sum(payload), command ^ 0xFFFFFFFF
|
||||
)
|
||||
try:
|
||||
with socket.create_connection((host, int(port)), timeout=timeout) as stream:
|
||||
stream.sendall(packet + payload)
|
||||
header = b""
|
||||
deadline = time.monotonic() + timeout
|
||||
while len(header) < 24:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
return False
|
||||
stream.settimeout(remaining)
|
||||
chunk = stream.recv(24 - len(header))
|
||||
if not chunk:
|
||||
return False
|
||||
header += chunk
|
||||
kind, _, _, length, _, magic = struct.unpack("<6I", header)
|
||||
return (
|
||||
kind.to_bytes(4, "little") in {b"CNXN", b"AUTH"}
|
||||
and magic == kind ^ 0xFFFFFFFF
|
||||
and length <= 1048576
|
||||
)
|
||||
except (OSError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
class AdbDeviceDiscovery:
|
||||
"""Coalesce discovery and reconnect only missing transports, with a total budget."""
|
||||
|
||||
def __init__(self):
|
||||
self._gate = threading.Lock()
|
||||
self._last_scan = float("-inf")
|
||||
self.results: list[dict[str, object]] = []
|
||||
self._cursor = 0
|
||||
|
||||
@staticmethod
|
||||
def _directory() -> Path:
|
||||
return get_app_dir() / "adb-devices"
|
||||
|
||||
def remember(self, target: str) -> bool:
|
||||
"""Save an explicitly connected device, without credentials or shared-list races."""
|
||||
directory = self._directory()
|
||||
temporary = None
|
||||
try:
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
destination = directory / (hashlib.sha256(target.encode()).hexdigest() + ".json")
|
||||
fd, temporary = tempfile.mkstemp(dir=directory, prefix=".device-")
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as stream:
|
||||
json.dump({"target": target}, stream)
|
||||
os.replace(temporary, destination)
|
||||
return True
|
||||
except OSError as exc:
|
||||
logger.warning(f"Cannot remember ADB device {target}: {exc}")
|
||||
return False
|
||||
finally:
|
||||
if temporary:
|
||||
Path(temporary).unlink(missing_ok=True)
|
||||
|
||||
def _remembered(self) -> list[str]:
|
||||
targets = []
|
||||
for path in self._directory().glob("*.json"):
|
||||
try:
|
||||
target = json.loads(path.read_text(encoding="utf-8"))["target"]
|
||||
host, port = target.rsplit(":", 1)
|
||||
if host and 0 < int(port) < 65536:
|
||||
targets.append(target)
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError) as exc:
|
||||
logger.warning(f"Invalid remembered ADB device {path.name}: {exc}")
|
||||
return targets
|
||||
|
||||
def refresh(self, adb_path: str, *, force: bool = False) -> list[dict[str, object]]:
|
||||
if not settings.ARTEMIS_ADB_AUTO_CONNECT or not current_adb_endpoint().is_local_default:
|
||||
self.results = []
|
||||
return []
|
||||
if not self._gate.acquire(blocking=False):
|
||||
return self.results.copy()
|
||||
try:
|
||||
if (
|
||||
not force
|
||||
and time.monotonic() - self._last_scan
|
||||
< settings.ARTEMIS_ADB_DISCOVERY_INTERVAL_SECONDS
|
||||
):
|
||||
return self.results.copy()
|
||||
self._last_scan = time.monotonic()
|
||||
self.results = []
|
||||
self._refresh(adb_path)
|
||||
except (OSError, psutil.Error, ValueError, subprocess.SubprocessError) as exc:
|
||||
logger.warning(f"ADB automatic discovery unavailable: {exc}")
|
||||
self.results.append({"success": False, "message": str(exc)})
|
||||
finally:
|
||||
self._gate.release()
|
||||
return self.results.copy()
|
||||
|
||||
def _refresh(self, adb_path: str) -> None:
|
||||
session = AdbSession(current_adb_endpoint(), adb_path=adb_path)
|
||||
deadline = time.monotonic() + settings.ARTEMIS_ADB_DISCOVERY_TIMEOUT_SECONDS
|
||||
devices = session.run(
|
||||
["devices"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=max(deadline - time.monotonic(), 0.01),
|
||||
)
|
||||
if devices.returncode:
|
||||
return
|
||||
ready = {
|
||||
_canonical_target(parts[0])
|
||||
for line in devices.stdout.splitlines()
|
||||
if len(parts := line.split()) >= 2 and parts[1] in {"device", "unauthorized"}
|
||||
}
|
||||
try:
|
||||
groups = emulator_listeners()
|
||||
except (OSError, psutil.Error) as exc:
|
||||
# Missing process-inspection permissions must not stop reconnection
|
||||
# of explicitly configured phones or make device enumeration fail.
|
||||
groups = []
|
||||
logger.warning(f"Cannot inspect local emulator listeners: {exc}")
|
||||
self.results.append({"success": False, "message": str(exc)})
|
||||
remembered = self._remembered()
|
||||
targets = [(group, True) for group in groups] + [([target], False) for target in remembered]
|
||||
# Resume at a different group if a slow/offline peer exhausts the budget.
|
||||
# Large multi-instance installations must not starve later devices.
|
||||
count = len(targets)
|
||||
start = self._cursor % count if count else 0
|
||||
for offset in range(count):
|
||||
index = (start + offset) % count
|
||||
candidates, probe = targets[index]
|
||||
self._cursor = (index + 1) % count
|
||||
if any(_canonical_target(target) in ready for target in candidates):
|
||||
continue
|
||||
for target in candidates:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
return
|
||||
if probe and not is_adbd(target, min(remaining, 0.3)):
|
||||
continue
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
return
|
||||
try:
|
||||
result = session.run(
|
||||
["connect", target],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=min(remaining, 2),
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.results.append(
|
||||
{"target": target, "success": False, "message": "ADB 连接超时"}
|
||||
)
|
||||
continue
|
||||
output = (result.stdout + result.stderr).strip()
|
||||
success = (
|
||||
result.returncode == 0
|
||||
and "connected to" in output.lower()
|
||||
and "failed" not in output.lower()
|
||||
)
|
||||
state = self._wait_for_transport(session, target, deadline) if success else None
|
||||
pending = success and state is None
|
||||
if success and state is None:
|
||||
success = False
|
||||
output = f"{output};已发起连接,等待设备就绪,下次刷新会重试"
|
||||
self.results.append(
|
||||
{
|
||||
"target": target,
|
||||
"success": success,
|
||||
"state": state,
|
||||
"pending": pending,
|
||||
"message": output,
|
||||
}
|
||||
)
|
||||
if success:
|
||||
logger.info(f"ADB 自动连接:{target} — {output}")
|
||||
ready.add(_canonical_target(target))
|
||||
break
|
||||
if pending:
|
||||
logger.info(f"ADB 设备连接中:{target} — {output}")
|
||||
break # Do not create a second alias while the first transport is settling.
|
||||
logger.warning(f"ADB 自动连接失败:{target} — {output}")
|
||||
|
||||
@staticmethod
|
||||
def _wait_for_transport(session: AdbSession, target: str, deadline: float) -> str | None:
|
||||
"""adb connect can return before its transport appears in adb devices."""
|
||||
while (remaining := deadline - time.monotonic()) > 0:
|
||||
try:
|
||||
result = session.run(["devices"], capture_output=True, text=True, timeout=remaining)
|
||||
except subprocess.TimeoutExpired:
|
||||
return None
|
||||
for line in result.stdout.splitlines():
|
||||
parts = line.split()
|
||||
if (
|
||||
len(parts) >= 2
|
||||
and _canonical_target(parts[0]) == _canonical_target(target)
|
||||
and parts[1] in {"device", "unauthorized"}
|
||||
):
|
||||
return parts[1]
|
||||
time.sleep(min(0.1, max(deadline - time.monotonic(), 0)))
|
||||
return None
|
||||
|
||||
|
||||
adb_device_discovery = AdbDeviceDiscovery()
|
||||
@@ -92,6 +92,19 @@ class AdbEndpoint:
|
||||
def mode(self) -> str:
|
||||
return "local" if self.is_local_default else "remote"
|
||||
|
||||
@property
|
||||
def client_host(self) -> str:
|
||||
"""ADB only permits daemon auto-start for the literal host 'localhost'.
|
||||
|
||||
Keep forwarded/custom-port endpoints explicit, even on loopback, so a
|
||||
missing tunnel never starts a different local daemon at that address.
|
||||
"""
|
||||
return "localhost" if self.is_local_default else self.host
|
||||
|
||||
@property
|
||||
def client_socket(self) -> str:
|
||||
return f"tcp:localhost:{self.port}" if self.is_local_default else self.socket
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
**asdict(self),
|
||||
@@ -108,7 +121,7 @@ class AdbEndpoint:
|
||||
target = environment if environment is not None else os.environ
|
||||
target["ADB_HOST"] = self.host
|
||||
target["ADB_PORT"] = str(self.port)
|
||||
target["ADB_SERVER_SOCKET"] = self.socket
|
||||
target["ADB_SERVER_SOCKET"] = self.client_socket
|
||||
target[ADB_ENDPOINT_ID_ENV] = self.identity
|
||||
return target
|
||||
|
||||
@@ -145,7 +158,7 @@ class AdbSession:
|
||||
return [
|
||||
self.adb_path,
|
||||
"-H",
|
||||
self.endpoint.host,
|
||||
self.endpoint.client_host,
|
||||
"-P",
|
||||
str(self.endpoint.port),
|
||||
*arguments,
|
||||
|
||||
@@ -28,6 +28,9 @@ import urllib.error
|
||||
import urllib.request
|
||||
|
||||
from artemis.config.paths import ROOT_DIR
|
||||
from artemis.config.settings import settings
|
||||
from artemis.runtime.process_probe import pid_is_alive
|
||||
from artemis.runtime.server_lifecycle import is_port_in_use, read_server_info
|
||||
from artemis.utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
@@ -44,10 +47,11 @@ def is_standalone_forced() -> bool:
|
||||
def is_daemon_running(
|
||||
host: str = DEFAULT_DAEMON_HOST,
|
||||
port: int = DEFAULT_DAEMON_PORT,
|
||||
timeout: float = 0.3,
|
||||
timeout: float | None = None,
|
||||
) -> bool:
|
||||
"""Fast probe to check if the Artemis Daemon HTTP server is responding."""
|
||||
url = f"http://{host}:{port}/api/system/readiness"
|
||||
timeout = timeout if timeout is not None else settings.ARTEMIS_DAEMON_PROBE_TIMEOUT_SECONDS
|
||||
url = f"http://{host}:{port}/api/system/server-status"
|
||||
try:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "Artemis-Daemon-Probe"})
|
||||
with urllib.request.urlopen(req, timeout=timeout) as response:
|
||||
@@ -190,6 +194,15 @@ def ensure_daemon_running(
|
||||
if is_daemon_running(host, port):
|
||||
return True, f"http://{host}:{port}"
|
||||
|
||||
if is_port_in_use(port, host):
|
||||
# A slow/busy HTTP loop is not a stopped daemon. Only trust persisted
|
||||
# metadata belonging to a live process on the requested endpoint.
|
||||
info = read_server_info() or {}
|
||||
if info.get("port") == port and info.get("host") == host and pid_is_alive(info.get("pid")):
|
||||
return True, f"http://{host}:{port}"
|
||||
logger.warning(f"Port {host}:{port} is occupied; refusing to spawn another daemon")
|
||||
return False, None
|
||||
|
||||
# Auto-spawn Daemon in background
|
||||
spawn_daemon(host, port)
|
||||
|
||||
@@ -221,6 +234,7 @@ def submit_task_to_daemon(
|
||||
conversation_id: str | None = None,
|
||||
verification_level: str | None = None,
|
||||
explorer_mode: str | None = None,
|
||||
runtime_overrides: dict[str, Any] | None = None,
|
||||
base_url: str | None = None,
|
||||
timeout: float = 15.0,
|
||||
) -> dict[str, Any] | None:
|
||||
@@ -246,6 +260,7 @@ def submit_task_to_daemon(
|
||||
"session_id": session_id,
|
||||
"ingress": ingress,
|
||||
"conversation_id": conversation_id,
|
||||
"runtime_overrides": runtime_overrides,
|
||||
}
|
||||
|
||||
try:
|
||||
|
||||
@@ -25,6 +25,8 @@ import threading
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from artemis.runtime.adb_endpoint import AdbSession, current_adb_endpoint
|
||||
from artemis.runtime.adb_discovery import adb_device_discovery
|
||||
from artemis.runtime.device_lock import DeviceExecutionLock
|
||||
from artemis.toolchain import toolchain
|
||||
from artemis.utils.logger import get_logger
|
||||
@@ -107,6 +109,7 @@ class DevicePool:
|
||||
adb = self._resolve_adb()
|
||||
if not adb:
|
||||
return None
|
||||
adb_device_discovery.refresh(adb)
|
||||
try:
|
||||
res = subprocess.run(
|
||||
[adb, "devices", "-l"],
|
||||
@@ -131,6 +134,7 @@ class DevicePool:
|
||||
adb = self._resolve_adb()
|
||||
if not adb:
|
||||
return None
|
||||
await asyncio.to_thread(adb_device_discovery.refresh, adb)
|
||||
proc = None
|
||||
try:
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
@@ -242,23 +246,29 @@ class DevicePool:
|
||||
|
||||
async def _start_adb_server(self, timeout: float) -> None:
|
||||
"""Best-effort bounded `adb start-server` so later queries hit a warm daemon."""
|
||||
endpoint = current_adb_endpoint()
|
||||
if not endpoint.is_local_default:
|
||||
return
|
||||
adb = self._resolve_adb()
|
||||
if not adb:
|
||||
return
|
||||
proc = None
|
||||
try:
|
||||
clean_env = os.environ.copy()
|
||||
clean_env.pop("ADB_SERVER_SOCKET", None)
|
||||
session = AdbSession(endpoint, adb_path=adb)
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
adb,
|
||||
"start-server",
|
||||
*session.command(["start-server"]),
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
env=clean_env,
|
||||
env=session.environment(),
|
||||
)
|
||||
await asyncio.wait_for(proc.communicate(), timeout=timeout)
|
||||
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)
|
||||
if proc.returncode != 0:
|
||||
output = (stderr or stdout).decode(errors="replace").strip()
|
||||
logger.warning(
|
||||
f"Local ADB server startup failed (exit {proc.returncode}): {output}"
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.debug(f"adb start-server warm-up did not complete: {exc}")
|
||||
logger.warning(f"Local ADB server startup did not complete: {exc}")
|
||||
if proc is not None:
|
||||
try:
|
||||
proc.kill()
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Execution budgets shared by supervised web and MCP tasks."""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
import time
|
||||
|
||||
from artemis.config.settings import settings
|
||||
|
||||
|
||||
def task_timeout(item: dict, job: dict | None = None, batch: dict | None = None) -> int:
|
||||
options = item.get("runtime_overrides") or (job or {}).get("case", {}).get("task_config") or {}
|
||||
return int(
|
||||
options.get("timeout_seconds")
|
||||
or (batch or {}).get("timeout_seconds")
|
||||
or settings.ARTEMIS_TASK_TIMEOUT_SECONDS
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExecutionBudget:
|
||||
limit: float
|
||||
elapsed: float = 0
|
||||
_last: float = field(default_factory=time.monotonic)
|
||||
_excluded: bool = False
|
||||
|
||||
def update(self, *, excluded: bool = False) -> float:
|
||||
now = time.monotonic()
|
||||
if not self._excluded:
|
||||
self.elapsed += max(0, now - self._last)
|
||||
self._last, self._excluded = now, excluded
|
||||
return max(0, self.limit - self.elapsed)
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Persist useful failure evidence even when a worker must be terminated."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import uuid
|
||||
|
||||
from artemis.config import TRACES_PATH
|
||||
|
||||
|
||||
def read_worker_outcome(session_id: str) -> dict:
|
||||
"""Read a worker's terminal signal without waiting for hung SDK threads."""
|
||||
try:
|
||||
data = json.loads(
|
||||
(TRACES_PATH / session_id / "run_outcome.json").read_text(encoding="utf-8")
|
||||
)
|
||||
if (
|
||||
isinstance(data, dict)
|
||||
and data.get("worker_finalized") is True
|
||||
and data.get("task_status")
|
||||
in {
|
||||
"failed",
|
||||
"completed",
|
||||
"cancelled",
|
||||
"interrupted",
|
||||
}
|
||||
):
|
||||
return data
|
||||
except (OSError, ValueError):
|
||||
pass # Atomic outcome is absent until the task finalizes.
|
||||
return {}
|
||||
|
||||
|
||||
def save_failure_result(session_id: str, error: str, *, code: str = "execution_failed") -> None:
|
||||
if not session_id or not all(c.isalnum() or c in "-_" for c in session_id):
|
||||
raise ValueError("无效的任务编号")
|
||||
directory = TRACES_PATH / session_id
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
payload: dict = {}
|
||||
try:
|
||||
previous = json.loads((directory / "result.json").read_text(encoding="utf-8"))
|
||||
if isinstance(previous, dict):
|
||||
payload.update(previous)
|
||||
except (OSError, ValueError):
|
||||
pass # Missing/truncated results are expected after a killed worker.
|
||||
payload.update(
|
||||
{
|
||||
"status": "failed",
|
||||
"task_status": "failed",
|
||||
"explanation": error,
|
||||
"error": error,
|
||||
"code": code,
|
||||
"worker_finalized": True,
|
||||
"tests": payload.get("tests") or {},
|
||||
}
|
||||
)
|
||||
for name in ("result.json", "run_outcome.json"):
|
||||
target = directory / name
|
||||
temporary = target.with_name(f".{name}.{uuid.uuid4().hex}.tmp")
|
||||
try:
|
||||
temporary.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
|
||||
os.replace(temporary, target)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
@@ -32,6 +32,7 @@ import shutil
|
||||
from shutil import which
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from types import NoneType
|
||||
from typing import Any, TypeVar, overload
|
||||
import uuid
|
||||
@@ -573,6 +574,13 @@ class Agent:
|
||||
)
|
||||
try:
|
||||
if device_lock is not None and os.environ.get("ARTEMIS_CLOUD_MODE") != "1":
|
||||
from artemis.runtime.task_control import control_dir, _write_atomic
|
||||
|
||||
if sess_id and os.environ.get("ARTEMIS_TASK_WORKER") == "1":
|
||||
_write_atomic(
|
||||
control_dir(str(sess_id)) / "task_control_state.json",
|
||||
{"status": "queued", "updated_at": time.time(), "pid": os.getpid()},
|
||||
)
|
||||
queue_cancel_event = threading.Event()
|
||||
acquire_task = asyncio.create_task(
|
||||
asyncio.to_thread(
|
||||
@@ -605,6 +613,7 @@ class Agent:
|
||||
|
||||
task_control = TaskControl(str(sess_id), device_lock)
|
||||
context.task_control = task_control
|
||||
task_control._state("running")
|
||||
self._prepare_output_files(task=task)
|
||||
if os.environ.get("ARTEMIS_CLOUD_MODE") != "1":
|
||||
if self._ui_adb_client is not None:
|
||||
@@ -712,6 +721,14 @@ class Agent:
|
||||
state=last_state_snapshot,
|
||||
error=err,
|
||||
)
|
||||
from artemis.runtime.task_result import save_failure_result
|
||||
|
||||
if sess_id:
|
||||
save_failure_result(
|
||||
str(sess_id),
|
||||
err,
|
||||
code=flash_result.get("code", "execution_failed"),
|
||||
)
|
||||
if context.data_engine:
|
||||
context.data_engine.end_session("failed")
|
||||
return output
|
||||
@@ -862,6 +879,10 @@ class Agent:
|
||||
state=last_state_snapshot,
|
||||
error=err,
|
||||
)
|
||||
from artemis.runtime.task_result import save_failure_result
|
||||
|
||||
if sess_id:
|
||||
save_failure_result(str(sess_id), err)
|
||||
if context.data_engine:
|
||||
context.data_engine.end_session("failed")
|
||||
|
||||
|
||||
+10
-4
@@ -2,7 +2,7 @@
|
||||
|
||||
源码内的 `skills/artemis-automation/` 是可分发 Skill,不依赖本机 Codex 的私有能力。将整个目录复制到宿主支持的 Skill 目录即可;Codex 为 `$CODEX_HOME/skills/`(未配置时 `~/.codex/skills/`)。仓库包含 Skill,启动程序不会修改用户的全局 Skill 目录。
|
||||
|
||||
Windows 一键脚本会为检测到的客户端自动安装或更新 MCP 配置。未检测到客户端时,在项目目录执行 `uv run artemis mcp --install codex`;其他客户端将 `codex` 换成对应名称,`uv run artemis mcp --help` 可查看支持列表。更新后重新加载宿主 MCP;复制 Skill 后按宿主方式重新加载技能。
|
||||
目前仅支持 Codex MCP 配置。Windows 一键脚本检测并同步 Codex;未检测到配置目录时,在项目目录执行 `uv run artemis mcp --install codex`。配置模板使用 `uv run artemis mcp --generate-config codex` 查看;其他名称和 `all` 不再支持。更新后重新加载 Codex MCP;复制 Skill 后重新加载技能。
|
||||
|
||||
可以向 AI 这样下达任务:
|
||||
|
||||
@@ -32,11 +32,11 @@ Windows 一键脚本会为检测到的客户端自动安装或更新 MCP 配置
|
||||
|
||||
新增工具通过统一后台服务运行,与网页共享配置、队列、历史和报告;不另外启动独立调度器。`ARTEMIS_STANDALONE` 模式不支持这些工作区工具。
|
||||
|
||||
Windows 已安装用户再次运行 `start.bat` / `start-cn.bat` 时会检查当前分支的 Git 上游,仅做快进更新;拉取后重新加载新版启动脚本。1.1.1 及更新版本的发布 ZIP 是精简的 Git 工作树,解压后也能在后续运行时检查更新。1.1.0 及更早 ZIP 缺少 `.git`,需手动下载新版源码包一次。没有 Git、网络/认证失败、有本地修改或分支分叉时保留现有源码并给出提示,不重置或覆盖。`-SkipUpdate` 可跳过源码更新检查。
|
||||
Windows 启动入口 `start.bat` / `start-cn.bat` 只检查并提示源码更新,`-SkipUpdate` 跳过提示。独立升级入口为 `update.bat` / `update-cn.bat`:先把升级程序复制到项目外的临时目录,检查本地修改,再终止本项目的 ARTEMIS 服务、MCP 和任务进程;之后仅做 Git 快进更新,并用新版启动程序准备环境,完成后由用户重新启动。其他项目、Codex、模拟器和共享 ADB 不受影响;运行中的任务会被中断,不会作为成功任务处理。1.1.1 及更新版本的发布 ZIP 含 Git 工作树,旧版无 `.git` 的 ZIP 需改用新版包或 Git 克隆。没有 Git、网络/认证失败、有本地修改或分支分叉时升级失败并保留现有源码,不重置或覆盖。
|
||||
|
||||
Python 每次按 `uv.lock` 检查并同步缺失/变化的依赖;前端依据源码、资源及包锁文件指纹决定是否重新执行 `npm ci` 和构建,成功后才记录指纹。国内镜像选项继续生效。检测到正在执行/排队的任务时,自动更新启动会停止,让原任务继续。
|
||||
Python 按 `uv.lock` 同步缺失/变化的依赖;前端依据源码、资源及包锁指纹决定是否执行 `npm ci` 和构建,成功后才记录指纹。国内升级入口继续使用镜像配置。升级与启动的环境准备互斥;升级失败不会自动启动服务或回滚用户配置,处理错误后可重试。
|
||||
|
||||
MCP 同步会识别已安装客户端的配置目录,为缺少 ARTEMIS 条目的客户端安装当前源码的标准配置;已有标准配置即使指向旧解压目录,也会更新解释器、项目目录、环境路径和工具清单。保留用户额外环境变量、禁用状态及其他服务;自定义启动包装器保持原样并提示。无法安全解析配置时停止启动,原文件不被覆盖;可使用 `-SkipMcpSync` 仅启动网页。首次修改保留备份。源码和配置同步后需在 AI 客户端重新加载 MCP 连接或重启客户端,脚本无法替宿主重启已加载的 MCP 进程。
|
||||
MCP 同步仅检查 `$CODEX_HOME/config.toml`;未设置或为空时使用当前用户的 `~/.codex/config.toml`。日志会显示实际路径,以及新装、更新、已是最新、未检测到或自定义跳过的结果。检测到目录但缺少 ARTEMIS 条目时安装当前源码的标准配置;已有标准配置即使指向旧解压目录,也会更新解释器、项目目录、环境路径和工具清单。保留用户额外环境变量、禁用状态及其他服务;自定义启动包装器保持原样并提示。其他客户端的配置和规则文件不读取、不修改,其格式错误不会阻止启动。Codex 配置无法安全解析时停止启动,原文件不被覆盖;可使用 `-SkipMcpSync` 仅启动网页。首次修改保留备份。同步后需在 Codex 中重新加载 MCP 或重启 Codex,脚本无法替宿主重启已加载的 MCP 进程。
|
||||
|
||||
创建批次时必须提供唯一 `request_id`;请求超时后可以按编号查询或用相同内容重发,避免重复用例。创建只保存草稿,`start` 才执行。AI 无需先制造 Excel,也可直接提交 JSON;字段与示例见 [Skill 批量任务参考](../skills/artemis-automation/references/batches.md)。
|
||||
|
||||
@@ -49,3 +49,9 @@ MCP 同步会识别已安装客户端的配置目录,为缺少 ARTEMIS 条目
|
||||
批次任务在队列中使用“用例编号 + 用例名称”显示,提示词仍是模型实际收到的内容。任务历史展示失败原因、完成时间和总耗时;导出全部资料时以用例编号命名目录。删除非活跃批次会同步清理其任务记录、步骤、截图、录屏及生成的报告,删除后不能通过旧 `request_id` 重复执行。
|
||||
|
||||
保存全局配置要求用户明确指令;只读配置不包含密钥,MCP 不接收密钥。密钥仍在网页或 `.env` 中填写。设置对新任务生效,模型请求重试不会触发测试用例自动重跑。历史步骤证据保留,设备动作回放已移除。
|
||||
|
||||
执行保护默认总时限 1800 秒,单任务、批次和 MCP 都适用,排队及用户暂停不计时。设备观测默认 60 秒、最多 3 次,ADB 命令默认 10 秒;观测失败不会继续向模型发送占位图或旧元素索引。Flash 连续 3 次动作失败先重新观察再切换兜底,兜底仍失败则结束任务并保存原因。不能以提高步数或反复重提任务代替设备诊断。
|
||||
|
||||
`mobile_run_task(runtime_overrides={"timeout_seconds":1800,"observation_timeout_seconds":60,"observation_max_attempts":3,"device_command_timeout_seconds":10,"action_failure_attempts":3})` 可为单任务覆盖执行保护;其中 `model` 是 API 模型名,外层 `model` 仍是 Flash/Pro 模式。相同字段也支持批次的 `task_config`。全局默认通过网页功能配置或明确授权的 `mobile_config(section="capabilities", changes={"task_timeout_seconds":1800}, persist_defaults=true)` 保存,对后续任务生效,不接受密钥。
|
||||
|
||||
任务已经产生最终结果,但 SDK 线程或资源清理仍卡住时,默认最多再等待 30 秒后回收工作进程,避免继续占用队列。全局可用 `ARTEMIS_WORKER_CLEANUP_TIMEOUT_SECONDS` 或功能配置的 `worker_cleanup_timeout_seconds` 调整,任务 JSON 同名字段可覆盖。原有结果与截图保留,未完成保存的录屏尽力恢复。
|
||||
@@ -17,12 +17,14 @@
|
||||
1. 点击“下载 Excel 模板”,保留“任务”工作表及表头顺序。
|
||||
2. 标准列按顺序为“用例编号”“检测项目”“测试子项”“测试用例”“前置约束提取”“Artemis提示词”“任务配置(JSON)”。任务表留空,示例行在“填写说明”页。
|
||||
3. 每行的“Artemis提示词”必填,且是唯一提交给 AI 的任务正文;其他文本列用于显示、搜索和报告,不自动拼入提示词。任务配置可留空,或填写 JSON 对象,如 `{"profile":"pro","model":"mimo-v2.6-flash","reasoning_effort":"high","record_video":true,"analyze_video":false,"request_timeout_seconds":300}`。支持单项覆盖设备、验证级别、观察模式、目标应用包名、重试及单任务时限;未设置字段继承批次或全局设置。不接受密钥和未知字段。不要填写公式、宏或外部链接。
|
||||
4. 上传文件,查看逐行校验结果。所有错误修正后才能提交。
|
||||
5. 明确选择设备、执行模式和超时时间,然后点击“确认导入并开始执行”。
|
||||
4. 上传文件,查看逐行校验结果。默认勾选全部有效用例,可逐项取消,或用“全选 / 全不选”切换;未勾选用例不会导入。所有错误修正后才能提交。
|
||||
5. 明确选择设备、执行模式、超时时间和整批循环次数(默认 1),查看“已选用例数 × 轮数”的执行总数,然后点击“确认导入并开始执行”。
|
||||
|
||||
同一批次按顺序派发。默认失败后继续且不自动重试,也可以选择失败即停止。设备不可用、模型暂停或任务超时会暂停后续派发。暂停批次只停止后续派发。单个任务可在安全边界暂停并释放设备;批次下一项可继续,暂停的任务待提交指导或点击继续后在设备队列末尾恢复。运行中提交指导会中断当前模型思考或只读诊断,重新观察画面;已经开始的设备动作会安全结束。网页流程会显示指导的提交与领取状态,仍应检查后续动作是否符合指导。暂停等待和重新排队时间不计入该任务执行时限。
|
||||
循环次数独立保存在每个批次中。每轮按表格顺序执行整批所选用例,然后进入下一轮;各次执行有独立任务编号、状态和报告,队列及报告标题标注轮次。暂停、重启恢复只继续未开始项;“失败即停止”跳过全部后续轮次,“复制失败项为新批次”只复制失败记录各执行一次,不沿用原循环次数。单批默认最多 10000 次执行,可用 `.env` 中 `ARTEMIS_BATCH_MAX_EXECUTIONS` 调整;网页和 MCP 使用同一限制。
|
||||
|
||||
服务重启后保留批次,等待用户继续未开始的用例。正在执行或暂停的任务标记中断,不自动重做;“复制失败项为新批次”保留原记录并产生新任务编号。
|
||||
同一批次按顺序派发。默认失败后继续且不自动重试,也可以选择失败即停止。当前任务因设备异常或超时失败后,默认继续后续用例;设置失败即停止时才停止后续派发。暂停批次只停止后续派发。单个任务可在安全边界暂停并释放设备;批次下一项可继续,暂停的任务待提交指导或点击继续后在设备队列末尾恢复。运行中提交指导会中断当前模型思考或只读诊断,重新观察画面;已经开始的设备动作会安全结束。网页流程会显示指导的提交与领取状态,仍应检查后续动作是否符合指导。暂停等待和重新排队时间不计入该任务执行时限。
|
||||
|
||||
服务启动前先取得监听端口,重复启动不会修改现有任务或服务信息。恢复时核对原任务进程和设备锁:仍存活的任务继续等待其真实结果,退出后补齐报告;已经退出且没有终态的任务标记中断,不自动重做,批次等待用户继续未开始的用例。“复制失败项为新批次”保留原记录并产生新任务编号。任务正常完成后,已失效的“服务中断”提示归档为恢复事件,不再显示为当前失败原因;启动时也会纠正已有完成记录中的此类旧提示。
|
||||
|
||||
每个任务结束后生成所选格式报告。批次 ZIP 包含汇总、每项任务的报告和已保存的有序步骤截图;已开启录屏且文件存在时,还会按任务收录录屏片段。失败、跳过和中断任务也会列入。暂停时下载的是当前快照。录屏与 AI 视频分析分别配置,录屏默认关闭;仅开启分析时,录制内容用于本次分析,结束后不保留下载文件。暂停期间不录制其他任务的设备画面。
|
||||
|
||||
@@ -34,6 +36,16 @@
|
||||
|
||||
## 环境配置
|
||||
|
||||
`.env` 可配置 `ARTEMIS_BATCH_TASK_TIMEOUT`(默认 1800 秒)、`ARTEMIS_IMPORT_MAX_ROWS`(默认 1000 行)和 `ARTEMIS_IMPORT_MAX_BYTES`(默认 10 MiB)。修改后重启服务。网页的单批次超时设置优先于环境默认值。
|
||||
设备刷新、启动和重启 ADB 后会自动连接本机运行中的 MuMu、雷电、夜神、逍遥及蓝叠等常见模拟器:读取进程拥有的监听端口,验证 ADB 协议后连接,不扫描局域网。同一模拟器的兼容端口不重复连接,已有在线或等待授权的连接保持不动。USB 手机和 Android SDK 模拟器由 ADB 原生发现。其他模拟器或无线手机可在首页“无线 ADB”中填写实际地址和端口;成功后地址保存在本机应用数据目录的 `adb-devices` 中,后续自动重连。Android 无线调试须先完成配对和授权,端口变化后需要重新连接;自动连接不会绕过授权。
|
||||
|
||||
“功能配置”提供“自动连接设备”开关,默认开启;每轮连接预算默认 5 秒,发现间隔默认 10 秒,避免离线设备拖住刷新。对应环境变量为 `ARTEMIS_ADB_AUTO_CONNECT`、`ARTEMIS_ADB_DISCOVERY_TIMEOUT_SECONDS`、`ARTEMIS_ADB_DISCOVERY_INTERVAL_SECONDS`。MCP `mobile_config(section="capabilities")` 可配置 `adb_auto_connect`、`adb_discovery_timeout_seconds`、`adb_discovery_interval_seconds`;`mobile_workspace` 的设备列表和 `mobile_diagnose` 返回自动连接结果。使用远程或转发 ADB 服务时不发现本机端口。连接设备不等于选择任务设备,多个设备时仍需明确选择。
|
||||
|
||||
`.env` 可配置 `ARTEMIS_TASK_TIMEOUT_SECONDS`(单任务总执行时限,默认 1800 秒)、`ARTEMIS_IMPORT_MAX_ROWS`(默认 1000 行)和 `ARTEMIS_IMPORT_MAX_BYTES`(默认 10 MiB)。修改后重启服务。网页的单批次超时设置优先于环境默认值,每行 JSON 的 `timeout_seconds` 优先于批次。单任务、批次和 MCP 均受总执行时限保护,不计排队和用户暂停时间;即使执行进程卡住,也由父进程终止并保存失败原因。
|
||||
|
||||
守护服务通过轻量状态接口探测,`ARTEMIS_DAEMON_PROBE_TIMEOUT_SECONDS` 默认 2 秒。短暂超时且端口仍被存活的原服务占用时复用原服务,不重复启动;未知进程占用端口时明确拒绝覆盖。
|
||||
|
||||
网页“功能配置 → 执行保护”及 MCP `mobile_config(section="capabilities")` 可配置总时限、设备观测时限(默认 60 秒)、设备观测次数(默认 3 次)、ADB 命令超时(默认 10 秒)、连续动作失败次数(默认 3 次)。任务 JSON 可用 `observation_timeout_seconds`、`observation_max_attempts`、`device_command_timeout_seconds`、`action_failure_attempts` 覆盖。截图失效或收到占位图时先有限重取,耗尽后结束任务,不把旧画面发给模型;有效截图即使没有 XML 也可按坐标定位。连续动作失败时先刷新画面再尝试兜底,兜底耗尽后结束,不循环重提用例。
|
||||
|
||||
批次、任务元数据和报告偏好保存在现有 SQLite 数据库的 `automation_records`、`automation_jobs` 表。全局“清空任务历史”会清除批次与执行元数据;它与上文的单批次删除不同,已导出的文件会保留。
|
||||
|
||||
任务已经产生最终结果,但 SDK 线程或资源清理仍卡住时,默认最多再等待 30 秒后回收工作进程,避免继续占用队列。全局可用 `ARTEMIS_WORKER_CLEANUP_TIMEOUT_SECONDS` 或功能配置的 `worker_cleanup_timeout_seconds` 调整,任务 JSON 同名字段可覆盖。原有结果与截图保留,未完成保存的录屏尽力恢复。
|
||||
@@ -0,0 +1,21 @@
|
||||
# ARTEMIS-Eapil 1.3.1
|
||||
|
||||
## 修复
|
||||
|
||||
- 限制任务执行、设备观察、连续动作失败和资源清理的等待与重试。超时或失败后释放执行资源,让队列继续处理后续任务,避免单个任务长时间反复重试。
|
||||
- 修复点击录像时间轴关键步骤后,视频暂停但播放按钮状态未同步的问题。播放中跳转后继续播放,暂停时跳转保持暂停,恢复播放只需点击一次。
|
||||
- 修复服务探测超时后重复启动后台服务,导致仍在执行的任务被误标为“服务中断”的问题。启动时先占用监听端口,再初始化服务和恢复任务;已有服务占用端口时安全退出。
|
||||
- 恢复任务时保留仍存活的执行进程,并跟踪其最终结果。完成任务会清除已失效的“服务中断”提示并保留恢复记录,真实执行失败和超时原因继续显示。
|
||||
|
||||
## 安装与升级
|
||||
|
||||
下载附件 `artemis-eapil-1.3.1-source.zip`,解压后运行 `start.bat`;国内网络使用 `start-cn.bat`。源码包包含可继续更新的 Git 仓库,不包含虚拟环境、构建产物、密钥和执行记录。
|
||||
|
||||
已有安装可通过启动脚本更新。升级后重启服务、刷新网页,并重新加载 MCP,让各入口使用新版实现。
|
||||
|
||||
## 验证
|
||||
|
||||
- Python 默认测试:2246 项通过,6 项跳过,8 项未选中;最终恢复逻辑回归测试:65 项通过。
|
||||
- 前端测试:169 项通过;前端构建、Ruff、质量基线、核心类型检查及 Git 差异检查通过。
|
||||
- 使用独立进程验证重复启动不会修改现有任务或服务元数据;在浏览器验证录像关键步骤跳转及播放状态。
|
||||
- 本次验证未运行真实 Android 任务;跨录像片段跳转通过单元测试验证。
|
||||
@@ -0,0 +1,19 @@
|
||||
# ARTEMIS-Eapil 1.3.2
|
||||
|
||||
## 更新与修复
|
||||
|
||||
- MCP 配置安装与更新仅支持 Codex。一键启动不再检查或修改 VS Code、Cursor 等其他客户端的配置,其配置错误不会阻止网页启动。手动 CLI 仅接受 `--install codex` 和 `--generate-config codex`,不再支持其他客户端或 `all`。
|
||||
- 启动日志明确显示实际检查的 Codex 配置路径,以及安装、更新、已是最新、未检测到或自定义跳过的结果。未设置或空值的 `CODEX_HOME` 使用当前用户的 `.codex` 目录;保留已有自定义路径设置。
|
||||
- 修复 Windows 手动重复安装 Codex MCP 时,路径反斜杠被误当成正则替换符的问题。配置写入失败会返回失败状态。
|
||||
- 固定批处理脚本为 CRLF 换行,修复中文启动脚本在部分源码包中将中文截断并当成命令执行的问题。
|
||||
- 同步 README、AI 接入说明及随源码分发的 Skill。
|
||||
|
||||
## 安装与升级
|
||||
|
||||
下载附件 `artemis-eapil-1.3.2-source.zip`,解压后运行 `start.bat`;国内网络使用 `start-cn.bat`。附件包含可继续更新的 Git 仓库,不包含虚拟环境、构建产物、密钥和任务记录。请使用发布附件,Gitea 自动生成的“源代码”压缩包不含 Git 元数据。
|
||||
|
||||
已有安装可通过启动脚本更新。更新后重启服务、刷新网页,并重新加载 Codex MCP。未检测到 Codex 配置目录时,可运行 `uv run artemis mcp --install codex` 手动安装。仅需网页时使用 `-SkipMcpSync`。
|
||||
|
||||
## 验证
|
||||
|
||||
默认 Python 测试范围分批验证共 2267 项通过,6 项跳过,8 项按标记排除;Ruff、质量基线、核心类型检查和 Git 差异检查通过。已验证 Windows 中文启动与帮助输出、Codex 默认及自定义目录识别、重复安装、其他客户端配置保留,以及源码包 CRLF 和干净 Git 状态。本次没有修改前端交互,也未运行真实 Android 任务。
|
||||
@@ -26,7 +26,22 @@ MODEL_FIELDS = {
|
||||
"tool_fallback_no_progress_attempts",
|
||||
"reasoning_effort",
|
||||
}
|
||||
CAPABILITY_FIELDS = {"video_enabled", "outputter_enabled", "step_summarizer_enabled"}
|
||||
CAPABILITY_FIELDS = {
|
||||
"adb_auto_connect",
|
||||
"adb_discovery_interval_seconds",
|
||||
"adb_discovery_timeout_seconds",
|
||||
"video_enabled",
|
||||
"recording_enabled",
|
||||
"outputter_enabled",
|
||||
"step_summarizer_enabled",
|
||||
"screenshot_limit_enabled",
|
||||
"task_timeout_seconds",
|
||||
"observation_timeout_seconds",
|
||||
"observation_max_attempts",
|
||||
"device_command_timeout_seconds",
|
||||
"action_failure_attempts",
|
||||
"worker_cleanup_timeout_seconds",
|
||||
}
|
||||
|
||||
|
||||
def _id(value: str | None) -> str:
|
||||
@@ -131,8 +146,13 @@ async def mobile_config(
|
||||
tool_fallback_reasoning_effort, tool_fallback_max_retries,
|
||||
tool_fallback_no_progress_attempts. 'default' omits reasoning;
|
||||
unsupported values fail visibly.
|
||||
capabilities: video_enabled (recording + analysis), outputter_enabled,
|
||||
step_summarizer_enabled. reports: formats=['docx','xlsx'] (at least one).
|
||||
capabilities: video_enabled and recording_enabled are independent; outputter_enabled,
|
||||
step_summarizer_enabled, screenshot_limit_enabled, task_timeout_seconds (default 1800),
|
||||
observation_timeout_seconds (60), observation_max_attempts (3),
|
||||
device_command_timeout_seconds (10), action_failure_attempts (3),
|
||||
worker_cleanup_timeout_seconds (30), adb_auto_connect (true),
|
||||
adb_discovery_interval_seconds (10), adb_discovery_timeout_seconds (5).
|
||||
reports: formats=['docx','xlsx'] (at least one).
|
||||
API keys are never accepted or returned: use the Web UI or .env for credentials.
|
||||
Saving settings does not change an already running task. Flash/Pro are execution
|
||||
profiles, not model names. Model retries do not repeat device test cases.
|
||||
@@ -205,13 +225,19 @@ async def mobile_batch(
|
||||
reasoning_effort?,device_serial?,verification_level?,explorer_mode?,
|
||||
locked_app_package?,record_video?,analyze_video?,request_timeout_seconds?,
|
||||
max_retries?,retry_interval_seconds?,timeout_seconds?}}],profile?:flash|pro,
|
||||
formats?:[docx,xlsx],stop_on_failure?:false,timeout_seconds?:1800}. Required device
|
||||
formats?:[docx,xlsx],stop_on_failure?:false,timeout_seconds?:1800,repeat_count?:1}.
|
||||
repeat_count is a positive integer: execute all selected cases in order for each
|
||||
round, with independent session IDs, statuses and reports. The default total limit
|
||||
(cases * repeat_count) is 10000, configurable via ARTEMIS_BATCH_MAX_EXECUTIONS.
|
||||
Only include user-selected cases; get returns iteration/repeat_count per job.
|
||||
Required device
|
||||
must be user-selected. Creation validates and saves a DRAFT; start executes it.
|
||||
Reuse the same request_id and exact payload after a connection failure; never invent
|
||||
a new ID for the same submission. lookup(request_id) resolves an uncertain outcome.
|
||||
get returns per-case status. pause stops future dispatch, not the active task;
|
||||
use mobile_manage_task(stop) to stop that task. resume never repeats finished cases.
|
||||
retry_failed creates a new draft only after an explicit rerun request; it is not
|
||||
retry_failed copies each failed execution once into a new draft (repeat_count=1)
|
||||
only after an explicit rerun request; it is not
|
||||
transport-idempotent, so after an uncertain response use list instead of retrying.
|
||||
delete removes a non-active batch and its task sessions, reports and files after
|
||||
an explicit user request. Confirm the batch ID with get first; deletion is irreversible.
|
||||
|
||||
@@ -115,6 +115,8 @@ def _render_check(result: ProbeResult) -> dict[str, Any]:
|
||||
"summary": result.summary,
|
||||
}
|
||||
if result.status is ProbeStatus.PASS:
|
||||
if result.id == "android_adb" and result.metadata.get("automatic_connections"):
|
||||
check["automatic_connections"] = _scrub(result.metadata["automatic_connections"])
|
||||
return check
|
||||
check["category"] = result.category.value
|
||||
check["detail"] = result.description
|
||||
|
||||
@@ -35,6 +35,10 @@ from artemis.runtime import (
|
||||
submit_task_to_daemon,
|
||||
trace_store,
|
||||
)
|
||||
from artemis.runtime.task_limits import ExecutionBudget, task_timeout
|
||||
from artemis.runtime.task_control import read_state
|
||||
from artemis.runtime.task_result import save_failure_result, read_worker_outcome
|
||||
from artemis.config.settings import settings
|
||||
|
||||
# Seconds the spawned runner gets to finish its imports and open its log files
|
||||
# before the spawn is declared dead. Normal startup creates stdout.log within a
|
||||
@@ -44,6 +48,54 @@ from artemis.runtime import (
|
||||
SPAWN_WATCHDOG_SECONDS = 60
|
||||
|
||||
|
||||
def _watch_execution(proc, trace_id: str, limit: int, cleanup_limit: float | None = None) -> None:
|
||||
"""Supervise standalone MCP workers without charging device queue or pause time."""
|
||||
budget = ExecutionBudget(limit)
|
||||
finalized_at = None
|
||||
cleanup_limit = cleanup_limit or settings.ARTEMIS_WORKER_CLEANUP_TIMEOUT_SECONDS
|
||||
while proc.poll() is None:
|
||||
status = trace_store.read_status(trace_id) or {}
|
||||
outcome = read_worker_outcome(trace_id)
|
||||
if outcome and status.get("status") not in {
|
||||
"completed",
|
||||
"success",
|
||||
"failed",
|
||||
"cancelled",
|
||||
"interrupted",
|
||||
}:
|
||||
try:
|
||||
trace_store.update_trace_status(
|
||||
trace_id, outcome["task_status"], error=outcome.get("error")
|
||||
)
|
||||
except OSError:
|
||||
logging.exception("Cannot persist terminal status for %s", trace_id)
|
||||
if outcome or status.get("status") in {
|
||||
"completed",
|
||||
"success",
|
||||
"failed",
|
||||
"cancelled",
|
||||
"interrupted",
|
||||
}:
|
||||
finalized_at = finalized_at if finalized_at is not None else time.monotonic()
|
||||
if time.monotonic() - finalized_at >= cleanup_limit:
|
||||
_kill_process_tree(proc.pid)
|
||||
return
|
||||
time.sleep(0.5)
|
||||
continue
|
||||
control_status = read_state(trace_id).get("status")
|
||||
remaining = budget.update(excluded=control_status in {"queued", "task_paused", "resuming"})
|
||||
if remaining <= 0:
|
||||
error = f"任务执行超时({limit} 秒,不含暂停/排队时间)"
|
||||
_kill_process_tree(proc.pid)
|
||||
try:
|
||||
save_failure_result(trace_id, error, code="task_timeout")
|
||||
trace_store.update_trace_status(trace_id, "failed", error=error)
|
||||
except OSError:
|
||||
logging.exception("Cannot persist timeout report for %s", trace_id)
|
||||
return
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def _kill_process_tree(pid: int) -> None:
|
||||
"""Terminate a spawned runner and its children (the venv shim re-execs python)."""
|
||||
if sys.platform == "win32":
|
||||
@@ -212,6 +264,7 @@ def mobile_run_task(
|
||||
device_serial: str | None = None,
|
||||
verification_level: str | None = None,
|
||||
explorer_mode: str | None = None,
|
||||
runtime_overrides: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Starts an autonomous mobile UI automation subagent on a connected Android device.
|
||||
|
||||
@@ -277,7 +330,25 @@ def mobile_run_task(
|
||||
by the Operator: `"flash"` (1-shot detection, the default),
|
||||
`"pro"` (3-turn ReAct), `"ultra"` (deep pixel reasoning; slowest).
|
||||
Ignored for Flash.
|
||||
runtime_overrides: Optional TaskOptions JSON for this task only. Supports
|
||||
timeout_seconds (total execution, default 1800; excludes queue/pause),
|
||||
observation_timeout_seconds (60), observation_max_attempts (3),
|
||||
device_command_timeout_seconds (10), action_failure_attempts (3),
|
||||
worker_cleanup_timeout_seconds (30),
|
||||
model (API model name), reasoning_effort, request timeout/retries,
|
||||
recording and video analysis. Unknown fields and credentials are rejected.
|
||||
"""
|
||||
if runtime_overrides:
|
||||
from apps.admin_console.services.task_import import TaskOptions
|
||||
|
||||
runtime_overrides = TaskOptions.model_validate(runtime_overrides).model_dump(
|
||||
exclude_none=True
|
||||
)
|
||||
model = runtime_overrides.get("profile") or model
|
||||
device_serial = runtime_overrides.get("device_serial") or device_serial
|
||||
locked_app_package = runtime_overrides.get("locked_app_package") or locked_app_package
|
||||
verification_level = runtime_overrides.get("verification_level") or verification_level
|
||||
explorer_mode = runtime_overrides.get("explorer_mode") or explorer_mode
|
||||
# 0. Validate and normalize model
|
||||
if model.lower() not in ("flash", "pro"):
|
||||
raise ValueError(f"Invalid model '{model}'. Must be either 'Flash' or 'Pro'.")
|
||||
@@ -325,6 +396,7 @@ def mobile_run_task(
|
||||
conversation_id=conversation_id,
|
||||
verification_level=verification_level,
|
||||
explorer_mode=explorer_mode,
|
||||
runtime_overrides=runtime_overrides,
|
||||
base_url=base_url,
|
||||
)
|
||||
if resp and resp.get("status") == "rejected":
|
||||
@@ -475,6 +547,26 @@ def mobile_run_task(
|
||||
env = os.environ.copy()
|
||||
env["ARTEMIS_SESSION_ID"] = trace_id
|
||||
env["ARTEMIS_TASK_INGRESS"] = "mcp"
|
||||
env["ARTEMIS_TASK_WORKER"] = "1"
|
||||
for option, variable in {
|
||||
"model": "OPENAI_MODEL",
|
||||
"reasoning_effort": "OPENAI_REASONING_EFFORT",
|
||||
"request_timeout_seconds": "OPENAI_TIMEOUT_SECONDS",
|
||||
"max_retries": "OPENAI_MAX_RETRIES",
|
||||
"retry_interval_seconds": "OPENAI_RETRY_INTERVAL_SECONDS",
|
||||
"record_video": "ARTEMIS_RECORDING_ENABLED",
|
||||
"analyze_video": "ARTEMIS_VIDEO_ENABLED",
|
||||
"observation_timeout_seconds": "ARTEMIS_OBSERVATION_TIMEOUT_SECONDS",
|
||||
"observation_max_attempts": "ARTEMIS_OBSERVATION_MAX_ATTEMPTS",
|
||||
"device_command_timeout_seconds": "ARTEMIS_DEVICE_COMMAND_TIMEOUT_SECONDS",
|
||||
"action_failure_attempts": "ARTEMIS_ACTION_FAILURE_ATTEMPTS",
|
||||
}.items():
|
||||
if (runtime_overrides or {}).get(option) is not None:
|
||||
env[variable] = (
|
||||
str(runtime_overrides[option]).lower()
|
||||
if isinstance(runtime_overrides[option], bool)
|
||||
else str(runtime_overrides[option])
|
||||
)
|
||||
if device_serial:
|
||||
env["ADB_DEVICE_SERIAL"] = device_serial
|
||||
env["ARTEMIS_DEVICE_ID"] = device_serial
|
||||
@@ -519,6 +611,17 @@ def mobile_run_task(
|
||||
# interpreter startup and must be killed instead of squatting on the
|
||||
# queue as 'running' forever.
|
||||
_start_spawn_watchdog(trace_id, proc.pid, queue_ticket, conversation_id)
|
||||
threading.Thread(
|
||||
target=_watch_execution,
|
||||
args=(
|
||||
proc,
|
||||
trace_id,
|
||||
task_timeout({"runtime_overrides": runtime_overrides}),
|
||||
(runtime_overrides or {}).get("worker_cleanup_timeout_seconds"),
|
||||
),
|
||||
daemon=True,
|
||||
name=f"artemis-task-budget-{trace_id[:8]}",
|
||||
).start()
|
||||
|
||||
trace_dir = trace_store.get_trace_dir(trace_id)
|
||||
stdout_log_path = os.path.join(trace_dir, "stdout.log")
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
|
||||
[project]
|
||||
name = "artemis"
|
||||
version = "1.3.0"
|
||||
version = "1.4.0"
|
||||
description = "Autonomous AI Assistant for Mobile Automation"
|
||||
|
||||
authors = [
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Copyright 2026 Google LLC
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
@@ -91,12 +91,23 @@ function Update-EnvironmentPath {
|
||||
|
||||
function Start-LocalAdbServer {
|
||||
if (Test-CommandExists "adb") {
|
||||
$adbErrorPreference = $ErrorActionPreference
|
||||
try {
|
||||
$origSocket = $env:ADB_SERVER_SOCKET
|
||||
Remove-Item Env:\ADB_SERVER_SOCKET -ErrorAction SilentlyContinue
|
||||
& adb start-server 2>$null | Out-Null
|
||||
if ($origSocket) { $env:ADB_SERVER_SOCKET = $origSocket }
|
||||
} catch {}
|
||||
# Windows PowerShell 5.1 wraps native stderr in ErrorRecord objects.
|
||||
# ADB prints normal daemon-start messages there, so inspect its exit code.
|
||||
$ErrorActionPreference = "Continue"
|
||||
# Explicit options ignore inherited remote-server environment settings.
|
||||
$adbOutput = & adb -H localhost -P 5037 start-server 2>&1
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Host " [警告] 本机 ADB 服务启动失败(退出码 $LASTEXITCODE)。" -ForegroundColor Yellow
|
||||
Write-Host ($adbOutput | Out-String).Trim() -ForegroundColor Yellow
|
||||
Write-Host " [操作] 请检查 ADB 安装、端口占用或安全软件拦截;本机设备暂不可用。" -ForegroundColor Yellow
|
||||
}
|
||||
} catch {
|
||||
Write-Host " [警告] 本机 ADB 服务启动异常:$_" -ForegroundColor Yellow
|
||||
} finally {
|
||||
$ErrorActionPreference = $adbErrorPreference
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# Shared preparation/upgrade mutex. ASCII for Windows PowerShell 5.1.
|
||||
function Enter-ArtemisInstallationLock {
|
||||
param([string]$ProjectRoot)
|
||||
$normalized = [IO.Path]::GetFullPath($ProjectRoot).TrimEnd('\').ToLowerInvariant()
|
||||
$hash = [Security.Cryptography.SHA256]::Create()
|
||||
try { $digest = [BitConverter]::ToString($hash.ComputeHash([Text.Encoding]::UTF8.GetBytes($normalized))).Replace('-', '') }
|
||||
finally { $hash.Dispose() }
|
||||
$mutex = New-Object Threading.Mutex($false, "Local\ArtemisInstallation-$digest")
|
||||
try {
|
||||
try { $entered = $mutex.WaitOne(0) }
|
||||
catch [Threading.AbandonedMutexException] { $entered = $true }
|
||||
if (-not $entered) { throw 'Another startup preparation or upgrade is running. Please wait and retry.' }
|
||||
return $mutex
|
||||
} catch { $mutex.Dispose(); throw }
|
||||
}
|
||||
|
||||
function Exit-ArtemisInstallationLock {
|
||||
param($Mutex)
|
||||
if ($null -ne $Mutex) { $Mutex.ReleaseMutex(); $Mutex.Dispose() }
|
||||
}
|
||||
+67
-29
@@ -17,8 +17,10 @@ param(
|
||||
[int]$Port = 8000,
|
||||
[switch]$NoOpen = $false,
|
||||
[switch]$SetupOnly = $false,
|
||||
[switch]$PrepareOnly = $false,
|
||||
[switch]$SkipUpdate = $false,
|
||||
[switch]$SkipMcpSync = $false,
|
||||
[switch]$Help = $false,
|
||||
[ValidateSet('Official', 'China')][string]$Mirror
|
||||
)
|
||||
|
||||
@@ -31,6 +33,35 @@ function Get-LaunchText {
|
||||
return $English
|
||||
}
|
||||
|
||||
# Keep UTF-8 Chinese text in this BOM-encoded script, never in CMD batch files.
|
||||
# CMD can misparse multibyte batch lines when an archive/editor converts CRLF to LF.
|
||||
if ($Help) {
|
||||
Write-Host (Get-LaunchText 'Usage: start.bat [options]' '用法:start-cn.bat [选项]')
|
||||
Write-Host ''
|
||||
Write-Host (Get-LaunchText ' -SetupOnly Prepare the environment without launching the UI' ' -SetupOnly 安装或检查环境,不启动网页')
|
||||
Write-Host (Get-LaunchText ' -Port 8001 Use the specified port (default: 8000)' ' -Port 8001 使用指定端口,默认 8000')
|
||||
Write-Host (Get-LaunchText ' -NoOpen Do not open the browser automatically' ' -NoOpen 启动服务后不自动打开浏览器')
|
||||
Write-Host (Get-LaunchText ' -SkipUpdate Skip the source update notification' ' -SkipUpdate 跳过源码更新提示(启动不会拉取源码)')
|
||||
Write-Host (Get-LaunchText ' -SkipMcpSync Skip Codex MCP installation and updates' ' -SkipMcpSync 仅启动网页,跳过 Codex MCP 安装和更新')
|
||||
Write-Host (Get-LaunchText ' -Mirror China Use China download mirrors' ' -Mirror China 使用国内下载镜像')
|
||||
Write-Host (Get-LaunchText ' -Help Show this help' ' -Help 显示本说明')
|
||||
Write-Host ''
|
||||
Write-Host (Get-LaunchText 'Download sources: config\downloads.json' '国内镜像设置:config\downloads.json')
|
||||
Write-Host (Get-LaunchText 'First launch requires Internet access. Upgrade with update.bat; startup only checks for updates.' '首次运行需联网;启动仅提示源码更新,升级请运行 update-cn.bat。')
|
||||
exit 0
|
||||
}
|
||||
Write-Host '======================================================'
|
||||
if ($env:ARTEMIS_LAUNCH_LANG -eq 'zh-CN' -and $Mirror -eq 'China') {
|
||||
Write-Host ' ARTEMIS 中文启动 - 使用国内镜像'
|
||||
Write-Host '======================================================'
|
||||
Write-Host '正在检查已有环境、更新提示及依赖;首次启动可能需要下载组件。'
|
||||
Write-Host '镜像地址和下载超时可在 config\downloads.json 中调整。'
|
||||
} else {
|
||||
Write-Host (Get-LaunchText ' Artemis Autonomous Mobile Agent UI' ' ARTEMIS 手机自动化测试')
|
||||
Write-Host '======================================================'
|
||||
}
|
||||
Write-Host ''
|
||||
|
||||
# Ensure modern TLS protocols are enabled for downloads (GitHub releases, nodejs.org, Google repositories)
|
||||
try {
|
||||
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12
|
||||
@@ -40,28 +71,18 @@ $ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
|
||||
$RootDir = Split-Path -Parent $ScriptDir
|
||||
Set-Location $RootDir
|
||||
|
||||
# Existing installations check source BEFORE importing bootstrap helpers.
|
||||
# Startup never mutates source; upgrades run from a staged, independent process.
|
||||
. (Join-Path $ScriptDir 'installation_lock.ps1')
|
||||
$installationLock = $null
|
||||
if ($env:ARTEMIS_UPGRADE_CHILD -ne '1') {
|
||||
try { $installationLock = Enter-ArtemisInstallationLock -ProjectRoot $RootDir }
|
||||
catch { Write-Host (Get-LaunchText "[ERROR] $_" '[错误] 另一个环境准备或升级正在运行,请稍后重试。') -ForegroundColor Red; exit 1 }
|
||||
}
|
||||
$existingPython = Join-Path $RootDir '.venv\Scripts\python.exe'
|
||||
if ((-not $SkipUpdate) -and (Test-Path -LiteralPath $existingPython)) {
|
||||
& $existingPython (Join-Path $ScriptDir 'update_installation.py') source --port $Port
|
||||
$updateExit = $LASTEXITCODE
|
||||
if ($updateExit -eq 20) { exit 1 }
|
||||
if ($updateExit -eq 10) {
|
||||
# Reparse the freshly updated launcher; do not continue running stale functions.
|
||||
$reloadArgs = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', (Join-Path $ScriptDir 'start.ps1'), '-Port', $Port, '-SkipUpdate')
|
||||
if ($NoOpen) { $reloadArgs += '-NoOpen' }
|
||||
if ($SetupOnly) { $reloadArgs += '-SetupOnly' }
|
||||
if ($SkipMcpSync) { $reloadArgs += '-SkipMcpSync' }
|
||||
if ($Mirror) { $reloadArgs += @('-Mirror', $Mirror) }
|
||||
& powershell.exe @reloadArgs
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
if ($updateExit -ne 0) {
|
||||
Write-Host (Get-LaunchText ' [ERROR] Source update check failed. Resolve the error above, or use -SkipUpdate for local startup.' ' [错误] 源码更新检查失败。请处理上方错误;要运行当前源码可传入 -SkipUpdate。') -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
& $existingPython (Join-Path $ScriptDir 'update_installation.py') source-check
|
||||
# Network/authentication failures are warnings, never a reason to prevent startup.
|
||||
}
|
||||
|
||||
. (Join-Path $ScriptDir 'download_config.ps1')
|
||||
try {
|
||||
Initialize-ArtemisDownloads -ProjectRoot $RootDir -Mode $Mirror
|
||||
@@ -126,12 +147,23 @@ function Update-EnvironmentPath {
|
||||
|
||||
function Start-LocalAdbServer {
|
||||
if (Test-CommandExists "adb") {
|
||||
$adbErrorPreference = $ErrorActionPreference
|
||||
try {
|
||||
$origSocket = $env:ADB_SERVER_SOCKET
|
||||
Remove-Item Env:\ADB_SERVER_SOCKET -ErrorAction SilentlyContinue
|
||||
& adb start-server 2>$null | Out-Null
|
||||
if ($origSocket) { $env:ADB_SERVER_SOCKET = $origSocket }
|
||||
} catch {}
|
||||
# Windows PowerShell 5.1 wraps native stderr in ErrorRecord objects.
|
||||
# ADB prints normal daemon-start messages there, so inspect its exit code.
|
||||
$ErrorActionPreference = "Continue"
|
||||
# Explicit options ignore inherited remote-server environment settings.
|
||||
$adbOutput = & adb -H localhost -P 5037 start-server 2>&1
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Host " [警告] 本机 ADB 服务启动失败(退出码 $LASTEXITCODE)。" -ForegroundColor Yellow
|
||||
Write-Host ($adbOutput | Out-String).Trim() -ForegroundColor Yellow
|
||||
Write-Host " [操作] 请检查 ADB 安装、端口占用或安全软件拦截;本机设备暂不可用。" -ForegroundColor Yellow
|
||||
}
|
||||
} catch {
|
||||
Write-Host " [警告] 本机 ADB 服务启动异常:$_" -ForegroundColor Yellow
|
||||
} finally {
|
||||
$ErrorActionPreference = $adbErrorPreference
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -356,16 +388,16 @@ if (-not (Test-Path -LiteralPath (Join-Path $RootDir '.env'))) {
|
||||
}
|
||||
}
|
||||
if (-not $SkipMcpSync) {
|
||||
Write-Host (Get-LaunchText ' [CHECK] Installing/updating MCP for detected AI clients...' ' [检查] 正在为检测到的 AI 客户端安装或更新 MCP...') -ForegroundColor Cyan
|
||||
Write-Host (Get-LaunchText ' [CHECK] Installing/updating Codex MCP...' ' [检查] 正在安装或更新 Codex MCP...') -ForegroundColor Cyan
|
||||
& $ArtemisPython (Join-Path $ScriptDir 'update_installation.py') mcp
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Host (Get-LaunchText ' [ERROR] MCP synchronization failed. Fix the configuration above, or use -SkipMcpSync to run the web UI without MCP.' ' [错误] MCP 同步失败。请修复上方配置;仅需启动网页时可使用 -SkipMcpSync。') -ForegroundColor Red
|
||||
Write-Host (Get-LaunchText ' [ERROR] Codex MCP synchronization failed. Fix the configuration above, or use -SkipMcpSync to run the web UI without MCP.' ' [错误] Codex MCP 同步失败。请修复上方配置;仅需启动网页时可使用 -SkipMcpSync。') -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
} else {
|
||||
Write-Host (Get-LaunchText ' [SKIP] MCP synchronization was skipped.' ' [跳过] 已跳过 MCP 同步。') -ForegroundColor Yellow
|
||||
}
|
||||
if ($SetupOnly) {
|
||||
if ($SetupOnly -and -not $PrepareOnly) {
|
||||
Write-Host (Get-LaunchText ' [OK] Setup complete. Run start.bat to launch Artemis.' ' [完成] 环境已准备好。运行 start-cn.bat 启动 ARTEMIS。') -ForegroundColor Green
|
||||
exit 0
|
||||
}
|
||||
@@ -420,7 +452,7 @@ if ($missingCore.Count -gt 0) {
|
||||
}
|
||||
|
||||
# Ensure local ADB daemon is warm & listening so probes do not hit 'Connection refused'
|
||||
Start-LocalAdbServer
|
||||
if (-not $PrepareOnly) { Start-LocalAdbServer }
|
||||
|
||||
# 6. Check and build Showcase UI if not already compiled
|
||||
$ShowcaseIndex = "$RootDir\apps\showcase_ui\dist\frontend\browser\index.html"
|
||||
@@ -512,9 +544,15 @@ if ($frontendChanged -or ((-not (Test-Path $ShowcaseIndex)) -and (-not (Test-Pat
|
||||
|
||||
# MCP clients were refreshed after Python dependency sync above.
|
||||
|
||||
Exit-ArtemisInstallationLock -Mutex $installationLock
|
||||
$installationLock = $null
|
||||
if ($PrepareOnly) {
|
||||
Write-Host (Get-LaunchText '[OK] Python, frontend and Codex MCP preparation complete.' '[完成] Python、网页构建和 Codex MCP 已准备好。') -ForegroundColor Green
|
||||
exit 0
|
||||
}
|
||||
# 8. Launch unified Showcase UI & open browser
|
||||
# Ensure local ADB daemon is warm & listening
|
||||
Start-LocalAdbServer
|
||||
if (-not $PrepareOnly) { Start-LocalAdbServer }
|
||||
|
||||
# Launch via `python -m artemis` (not the `artemis.exe` console-script shim) so the
|
||||
# long-running server never locks .venv\Scripts\artemis.exe against `uv sync` reinstalls.
|
||||
|
||||
+102
-231
@@ -1,4 +1,4 @@
|
||||
"""Check an existing checkout and synchronize installed local MCP clients."""
|
||||
"""Check an existing checkout and synchronize the local Codex MCP configuration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -13,7 +13,6 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import tomllib
|
||||
import urllib.request
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
@@ -42,34 +41,16 @@ def git(root: Path, *args: str, timeout: int = 15) -> str:
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def update_source(root: Path, port: int = 8000) -> int:
|
||||
"""Return 10 after a fast-forward (caller reloads launcher); never overwrite local work."""
|
||||
try:
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
with opener.open(f"http://127.0.0.1:{port}/api/status", timeout=2) as response:
|
||||
status = json.load(response)
|
||||
if (
|
||||
status.get("active_tasks")
|
||||
or status.get("queue")
|
||||
or (status.get("status") == "running" and status.get("pid"))
|
||||
):
|
||||
print(
|
||||
launch_text(
|
||||
"[WAIT] Tasks are active. Finish/stop them before updating dependencies or restarting.",
|
||||
"[等待] 有任务正在执行或排队。请先处理任务,再更新依赖或重启。",
|
||||
)
|
||||
)
|
||||
return 20
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
def update_source(root: Path, *, check_only: bool = False) -> int:
|
||||
"""Return 10 for an available/applied fast-forward, 1 on failure; preserve local work."""
|
||||
if not shutil.which("git"):
|
||||
print(
|
||||
launch_text(
|
||||
"[SKIP] Git is not installed. Continuing with local source; install Git for automatic source updates.",
|
||||
"[跳过] 未安装 Git,继续使用当前源码;安装 Git 后可自动检查更新。",
|
||||
"[ERROR] Install Git before upgrading; local source is preserved.",
|
||||
"[提示] 未安装 Git,无法升级;当前源码保持不变。",
|
||||
)
|
||||
)
|
||||
return 0
|
||||
return 1
|
||||
if not (root / ".git").exists():
|
||||
print(
|
||||
launch_text(
|
||||
@@ -77,8 +58,16 @@ def update_source(root: Path, port: int = 8000) -> int:
|
||||
"[跳过] 旧版源码包不含 Git 信息。请使用新版源码包或 Git 克隆;当前文件保持不变。",
|
||||
)
|
||||
)
|
||||
return 0
|
||||
return 1
|
||||
try:
|
||||
if not check_only and git(root, "status", "--porcelain"):
|
||||
print(
|
||||
launch_text(
|
||||
"[ERROR] Local changes exist; commit or back up first.",
|
||||
"[错误] 发现本地修改;请先提交或备份后再升级。",
|
||||
)
|
||||
)
|
||||
return 1
|
||||
branch = git(root, "symbolic-ref", "--quiet", "--short", "HEAD")
|
||||
remote = git(root, "config", "--get", f"branch.{branch}.remote")
|
||||
merge_ref = git(root, "config", "--get", f"branch.{branch}.merge")
|
||||
@@ -98,45 +87,53 @@ def update_source(root: Path, port: int = 8000) -> int:
|
||||
"[检查] 正在检查当前分支的远程更新...",
|
||||
)
|
||||
)
|
||||
git(root, "fetch", "--no-tags", remote, merge_ref, timeout=45)
|
||||
git(root, "fetch", "--no-tags", remote, merge_ref, timeout=5 if check_only else 45)
|
||||
target = git(root, "rev-parse", "FETCH_HEAD")
|
||||
current = git(root, "rev-parse", "HEAD")
|
||||
if current == target:
|
||||
print(launch_text("[OK] Source is up to date.", "[完成] 源码已是最新版。"))
|
||||
return 0
|
||||
if check_only:
|
||||
print(
|
||||
launch_text(
|
||||
"[UPDATE] A different upstream revision is available. Run update.bat (update-cn.bat for China mirrors).",
|
||||
"[更新] 远程版本有变化;请运行 update-cn.bat 或 update.bat 升级。",
|
||||
)
|
||||
)
|
||||
return 10
|
||||
if git(root, "status", "--porcelain"):
|
||||
print(
|
||||
launch_text(
|
||||
"[SKIP] Upstream differs, but local changes exist. Commit/back up your work before updating; continuing locally.",
|
||||
"[跳过] 发现本地修改;请先提交或备份。此次继续使用本地源码。",
|
||||
"[ERROR] Local changes appeared during the check. Upgrade stopped; files preserved.",
|
||||
"[错误] 检查期间出现本地修改;已停止升级,保留现有文件。",
|
||||
)
|
||||
)
|
||||
return 0
|
||||
return 1
|
||||
ancestor = git(root, "merge-base", "HEAD", target)
|
||||
if ancestor != current:
|
||||
print(
|
||||
launch_text(
|
||||
"[SKIP] Local branch is ahead or diverged. No automatic merge/rebase; continuing locally.",
|
||||
"[跳过] 本地分支领先或分叉,不自动合并;继续使用本地源码。",
|
||||
"[ERROR] Local branch is ahead or diverged. Upgrade stopped; no merge/rebase performed.",
|
||||
"[错误] 本地分支领先或分叉;已停止升级,不自动合并。",
|
||||
)
|
||||
)
|
||||
return 0
|
||||
return 1
|
||||
git(root, "merge", "--ff-only", target, timeout=30)
|
||||
print(
|
||||
launch_text(
|
||||
f"[UPDATED] Source {current[:12]} -> {target[:12]}. Reloading launcher and checking dependencies.",
|
||||
f"[已更新] 源码 {current[:12]} -> {target[:12]},重新载入启动脚本并检查依赖。",
|
||||
f"[UPDATED] Source {current[:12]} -> {target[:12]}. Preparing the updated installation.",
|
||||
f"[已更新] 源码 {current[:12]} -> {target[:12]},准备同步新版环境。",
|
||||
)
|
||||
)
|
||||
return 10
|
||||
except (RuntimeError, subprocess.TimeoutExpired) as exc:
|
||||
except (OSError, RuntimeError, subprocess.TimeoutExpired) as exc:
|
||||
print(
|
||||
launch_text(
|
||||
f"[WARN] {exc if isinstance(exc, RuntimeError) else 'Git update timed out.'} Continuing with local source.",
|
||||
"[提示] Git 更新失败或超时;请检查网络、凭据和仓库状态。继续使用当前源码。",
|
||||
f"[WARN] {exc if isinstance(exc, RuntimeError) else 'Git check failed or timed out.'} Local source is preserved.",
|
||||
"[提示] Git 检查/更新失败或超时;请检查网络、凭据和仓库状态。当前源码保持不变。",
|
||||
)
|
||||
)
|
||||
return 0
|
||||
return 1
|
||||
|
||||
|
||||
def _atomic_write(path: Path, text: str) -> None:
|
||||
@@ -184,54 +181,6 @@ def _updated_entry(config: dict, template: dict, root: Path, names: tuple[str, .
|
||||
return updated
|
||||
|
||||
|
||||
def refresh_json(
|
||||
path: Path,
|
||||
keys: tuple[str, ...],
|
||||
root: Path,
|
||||
python: str,
|
||||
names: tuple[str, ...],
|
||||
template: dict | None = None,
|
||||
install_missing: bool = False,
|
||||
) -> bool | None:
|
||||
if not path.is_file() and not install_missing:
|
||||
return False
|
||||
raw = path.read_text(encoding="utf-8") if path.is_file() else "{}"
|
||||
data = json.loads(raw)
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("MCP configuration must be a JSON object")
|
||||
parent = data
|
||||
for key in keys:
|
||||
child = parent.get(key)
|
||||
if child is None and install_missing:
|
||||
child = parent[key] = {}
|
||||
if not isinstance(child, dict):
|
||||
raise ValueError(f"Invalid MCP configuration section: {key}")
|
||||
parent = child
|
||||
config = parent.get("artemis")
|
||||
if config is None and install_missing:
|
||||
if template is None:
|
||||
raise ValueError("A standard MCP template is required for installation")
|
||||
updated = template
|
||||
elif isinstance(config, dict) and _is_standard_local_artemis(config):
|
||||
if template is None:
|
||||
template = {
|
||||
"command": python,
|
||||
"args": ["-m", "mcp_server"],
|
||||
"env": {"PYTHONPATH": str(root)},
|
||||
}
|
||||
updated = _updated_entry(config, template, root, names)
|
||||
elif config is not None and not isinstance(config, dict):
|
||||
raise ValueError("The Artemis MCP configuration is not an object")
|
||||
else:
|
||||
return None
|
||||
if updated == config:
|
||||
return False
|
||||
parent["artemis"] = updated
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
_atomic_write(path, json.dumps(data, ensure_ascii=False, indent=2) + "\n")
|
||||
return True
|
||||
|
||||
|
||||
def _toml_value(value: object) -> str:
|
||||
if isinstance(value, bool):
|
||||
return "true" if value else "false"
|
||||
@@ -363,152 +312,73 @@ def refresh_codex(
|
||||
|
||||
|
||||
def refresh_mcp(root: Path) -> int:
|
||||
"""Synchronize only Codex; never inspect or modify other clients."""
|
||||
sys.path.insert(0, str(root))
|
||||
from artemis.interfaces.cli.commands.mcp import (
|
||||
ARTEMIS_MCP_TOOLS,
|
||||
_get_config_snippet,
|
||||
_get_vscode_user_dir,
|
||||
)
|
||||
from artemis.interfaces.cli.commands.mcp import ARTEMIS_MCP_TOOLS, _get_config_snippet
|
||||
|
||||
home = Path.home()
|
||||
vscode = _get_vscode_user_dir()
|
||||
appdata = Path(os.environ.get("APPDATA", home / "AppData/Roaming"))
|
||||
cline_store = vscode / "globalStorage/saoudrizwan.claude-dev"
|
||||
roo_store = vscode / "globalStorage/rooveterinaryinc.roo-cline"
|
||||
paths = [
|
||||
(home / ".gemini/config/mcp_config.json", ("mcpServers",), "antigravity", home / ".gemini"),
|
||||
(home / ".gemini/jetski/mcp_config.json", ("mcpServers",), "jetski", home / ".gemini"),
|
||||
(
|
||||
home / ".gemini/antigravity/mcp_config.json",
|
||||
("mcpServers",),
|
||||
"antigravity",
|
||||
home / ".gemini",
|
||||
),
|
||||
(home / ".cursor/mcp.json", ("mcpServers",), "cursor", home / ".cursor"),
|
||||
(
|
||||
home / ".codeium/windsurf/mcp_config.json",
|
||||
("mcpServers",),
|
||||
"windsurf",
|
||||
home / ".codeium/windsurf",
|
||||
),
|
||||
(home / ".claude.json", ("mcpServers",), "claude", home / ".claude"),
|
||||
(
|
||||
appdata / "Claude/claude_desktop_config.json",
|
||||
("mcpServers",),
|
||||
"claude",
|
||||
appdata / "Claude",
|
||||
),
|
||||
(vscode / "mcp.json", ("servers",), "vscode", vscode),
|
||||
(home / ".copilot/mcp-config.json", ("servers",), "vscode", home / ".copilot"),
|
||||
(
|
||||
home / ".cline/data/settings/cline_mcp_settings.json",
|
||||
("mcpServers",),
|
||||
"cline",
|
||||
home / ".cline",
|
||||
),
|
||||
(home / ".cline/mcp.json", ("mcpServers",), "cline", home / ".cline"),
|
||||
(
|
||||
cline_store / "settings/cline_mcp_settings.json",
|
||||
("mcpServers",),
|
||||
"cline",
|
||||
cline_store,
|
||||
),
|
||||
(
|
||||
roo_store / "settings/mcp_settings.json",
|
||||
("mcpServers",),
|
||||
"roo",
|
||||
roo_store,
|
||||
),
|
||||
(
|
||||
roo_store / "settings/cline_mcp_settings.json",
|
||||
("mcpServers",),
|
||||
"roo",
|
||||
roo_store,
|
||||
),
|
||||
(root / ".roo/mcp.json", ("mcpServers",), "roo", root / ".roo"),
|
||||
(home / ".openclaw/openclaw.json", ("mcp", "servers"), "openclaw", home / ".openclaw"),
|
||||
]
|
||||
codex_home = Path(os.environ.get("CODEX_HOME", home / ".codex"))
|
||||
paths.append((codex_home / "config.toml", (), "codex", codex_home))
|
||||
installed = updated_count = ready = skipped = errors = 0
|
||||
for path, keys, client, marker in paths:
|
||||
if not path.is_file() and not marker.is_dir():
|
||||
continue
|
||||
existed = path.is_file()
|
||||
template = _get_config_snippet(client, sys.executable, str(root))
|
||||
for key in keys:
|
||||
template = template[key]
|
||||
template = template["artemis"] if keys else template["mcp_servers"]["artemis"]
|
||||
try:
|
||||
changed = (
|
||||
refresh_json(
|
||||
path,
|
||||
keys,
|
||||
root,
|
||||
sys.executable,
|
||||
ARTEMIS_MCP_TOOLS,
|
||||
template=template,
|
||||
install_missing=True,
|
||||
)
|
||||
if keys
|
||||
else refresh_codex(
|
||||
path,
|
||||
root,
|
||||
sys.executable,
|
||||
ARTEMIS_MCP_TOOLS,
|
||||
template=template,
|
||||
install_missing=True,
|
||||
)
|
||||
)
|
||||
if changed:
|
||||
print(
|
||||
launch_text(
|
||||
f"[{'UPDATED' if existed else 'INSTALLED'}] MCP configuration: {path}",
|
||||
f"[{'已更新' if existed else '已安装'}] MCP 配置:{path}",
|
||||
)
|
||||
)
|
||||
if existed:
|
||||
updated_count += 1
|
||||
else:
|
||||
installed += 1
|
||||
elif changed is None:
|
||||
print(
|
||||
launch_text(
|
||||
f"[SKIP] Custom Artemis MCP entry in {path}; use the manual installer for this client.",
|
||||
f"[跳过] {path} 使用自定义 ARTEMIS MCP 启动方式;请手动检查此客户端。",
|
||||
)
|
||||
)
|
||||
skipped += 1
|
||||
else:
|
||||
ready += 1
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
print(
|
||||
launch_text(
|
||||
f"[ERROR] Could not safely synchronize {path}; original configuration preserved.",
|
||||
f"[错误] 无法安全同步 {path};原配置已保留。",
|
||||
)
|
||||
)
|
||||
errors += 1
|
||||
print(
|
||||
launch_text(
|
||||
f"[CHECK] MCP clients: installed {installed}, updated {updated_count}, already current {ready}, custom skipped {skipped}, errors {errors}.",
|
||||
f"[检查] MCP 客户端:新装 {installed} 个、更新 {updated_count} 个、已是最新 {ready} 个、自定义跳过 {skipped} 个、失败 {errors} 个。",
|
||||
)
|
||||
)
|
||||
print(
|
||||
launch_text(
|
||||
"[ACTION] Reload or restart your AI client to load the current MCP process and tool schemas.",
|
||||
"[操作] 请在 AI 客户端重新加载 MCP 或重启客户端,使新版进程和工具签名生效。",
|
||||
)
|
||||
)
|
||||
if not (installed or updated_count or ready or skipped or errors):
|
||||
codex_home = Path(os.environ.get("CODEX_HOME") or (Path.home() / ".codex"))
|
||||
path = codex_home / "config.toml"
|
||||
print(launch_text(f"[CHECK] Codex MCP configuration: {path}", f"[检查] Codex MCP 配置:{path}"))
|
||||
if not path.is_file() and not codex_home.is_dir():
|
||||
print(
|
||||
launch_text(
|
||||
"[TIP] No supported client detected; install one with: uv run artemis mcp --install <client>",
|
||||
"[提示] 未检测到受支持的客户端;可执行 uv run artemis mcp --install <client>。",
|
||||
"[SKIP] Codex configuration directory not found. Install with: uv run artemis mcp --install codex",
|
||||
"[跳过] 未发现 Codex 配置目录。可执行 uv run artemis mcp --install codex 安装。",
|
||||
)
|
||||
)
|
||||
return 1 if errors else 0
|
||||
return 0
|
||||
existed = path.is_file()
|
||||
template = _get_config_snippet("codex", sys.executable, str(root))["mcp_servers"]["artemis"]
|
||||
try:
|
||||
changed = refresh_codex(
|
||||
path, root, sys.executable, ARTEMIS_MCP_TOOLS, template=template, install_missing=True
|
||||
)
|
||||
except (OSError, ValueError, TypeError, AttributeError) as exc:
|
||||
if isinstance(exc, OSError):
|
||||
reason = launch_text(
|
||||
"Cannot read/write the configuration; check file permissions.",
|
||||
"无法读写配置,请检查文件权限。",
|
||||
)
|
||||
else:
|
||||
reason = launch_text(
|
||||
"Invalid TOML or Artemis configuration structure; check the file in Codex.",
|
||||
"TOML 格式或 ARTEMIS 配置结构无效,请在 Codex 中检查配置文件。",
|
||||
)
|
||||
print(
|
||||
launch_text(
|
||||
f"[ERROR] Cannot safely synchronize {path}; original preserved. {reason}",
|
||||
f"[错误] 无法安全同步 {path};原配置已保留。{reason}",
|
||||
)
|
||||
)
|
||||
return 1
|
||||
if changed:
|
||||
print(
|
||||
launch_text(
|
||||
f"[{'UPDATED' if existed else 'INSTALLED'}] Codex MCP: {path}",
|
||||
f"[{'已更新' if existed else '已安装'}] Codex MCP:{path}",
|
||||
)
|
||||
)
|
||||
elif changed is None:
|
||||
print(
|
||||
launch_text(
|
||||
"[SKIP] Custom Codex Artemis MCP command preserved; check it manually.",
|
||||
"[跳过] Codex 使用自定义 ARTEMIS MCP 启动方式,已保留,请手动检查。",
|
||||
)
|
||||
)
|
||||
return 0
|
||||
else:
|
||||
print(
|
||||
launch_text(
|
||||
"[OK] Codex Artemis MCP is already current.", "[完成] Codex ARTEMIS MCP 已是最新。"
|
||||
)
|
||||
)
|
||||
print(
|
||||
launch_text(
|
||||
"[ACTION] Reload MCP or restart Codex to activate the updated tools.",
|
||||
"[操作] 请在 Codex 中重新加载 MCP 或重启 Codex,使新版进程和工具签名生效。",
|
||||
)
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
def frontend_fingerprint(root: Path) -> str:
|
||||
@@ -533,12 +403,13 @@ def frontend_fingerprint(root: Path) -> str:
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("action", choices=["source", "mcp", "frontend-check", "frontend-mark"])
|
||||
parser.add_argument(
|
||||
"action", choices=["source", "source-check", "mcp", "frontend-check", "frontend-mark"]
|
||||
)
|
||||
parser.add_argument("--root", type=Path, default=ROOT)
|
||||
parser.add_argument("--port", type=int, default=8000)
|
||||
args = parser.parse_args()
|
||||
if args.action == "source":
|
||||
sys.exit(update_source(args.root, args.port))
|
||||
if args.action in {"source", "source-check"}:
|
||||
sys.exit(update_source(args.root, check_only=args.action == "source-check"))
|
||||
elif args.action == "mcp":
|
||||
sys.exit(refresh_mcp(args.root))
|
||||
else:
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$ProjectRoot,
|
||||
[ValidateSet('Official', 'China')][string]$Mirror,
|
||||
[switch]$Help,
|
||||
[switch]$Staged
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
[Console]::OutputEncoding = New-Object Text.UTF8Encoding($false)
|
||||
$env:PYTHONUTF8 = '1'
|
||||
$env:PYTHONIOENCODING = 'utf-8'
|
||||
if ($Help) {
|
||||
Write-Host '用法:update.bat 或 update-cn.bat [-Help]'
|
||||
Write-Host '升级会终止本项目的 ARTEMIS 服务、MCP 和任务进程;保留配置、密钥与历史资料。'
|
||||
Write-Host '随后快进更新源码,同步依赖、网页构建和 Codex MCP;完成后请重新启动并重载 MCP。'
|
||||
exit 0
|
||||
}
|
||||
if (-not $ProjectRoot) { $ProjectRoot = Split-Path $PSScriptRoot -Parent }
|
||||
$ProjectRoot = (Resolve-Path -LiteralPath $ProjectRoot).Path
|
||||
. (Join-Path $PSScriptRoot 'installation_lock.ps1')
|
||||
|
||||
if (-not $Staged) {
|
||||
$lock = $null
|
||||
$stage = $null
|
||||
$stageCreated = $false
|
||||
$code = 1
|
||||
try {
|
||||
$lock = Enter-ArtemisInstallationLock -ProjectRoot $ProjectRoot
|
||||
# Every program used before the merge is frozen outside the checkout.
|
||||
$stage = Join-Path ([IO.Path]::GetTempPath()) ('artemis-upgrade-' + [Guid]::NewGuid().ToString('N'))
|
||||
$fullStage = [IO.Path]::GetFullPath($stage)
|
||||
$rootPrefix = [IO.Path]::GetFullPath($ProjectRoot).TrimEnd('\') + '\'
|
||||
if ($fullStage.StartsWith($rootPrefix, [StringComparison]::OrdinalIgnoreCase)) { throw 'TEMP must be outside the project directory.' }
|
||||
New-Item -ItemType Directory -Path $stage | Out-Null
|
||||
$stageCreated = $true
|
||||
foreach ($name in @('upgrade.ps1', 'installation_lock.ps1', 'upgrade_processes.ps1', 'update_installation.py')) {
|
||||
Copy-Item -LiteralPath (Join-Path $PSScriptRoot $name) -Destination (Join-Path $stage $name)
|
||||
}
|
||||
$forward = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', (Join-Path $stage 'upgrade.ps1'), '-Staged', '-ProjectRoot', $ProjectRoot)
|
||||
if ($Mirror) { $forward += @('-Mirror', $Mirror) }
|
||||
& powershell.exe @forward
|
||||
$code = $LASTEXITCODE
|
||||
} catch {
|
||||
Write-Host "[升级失败] $_" -ForegroundColor Red
|
||||
} finally {
|
||||
# Only remove the unique, validated staging directory created above.
|
||||
if ($stageCreated -and (Test-Path -LiteralPath $stage)) { Remove-Item -LiteralPath $stage -Recurse -Force }
|
||||
Exit-ArtemisInstallationLock -Mutex $lock
|
||||
}
|
||||
exit $code
|
||||
}
|
||||
|
||||
try {
|
||||
Set-Location -LiteralPath $PSScriptRoot
|
||||
$python = Join-Path $ProjectRoot '.venv\Scripts\python.exe'
|
||||
if (-not (Test-Path -LiteralPath $python)) { throw '尚未安装项目 Python 环境;请先运行 start.bat 或 start-cn.bat。' }
|
||||
if (-not (Get-Command git -ErrorAction SilentlyContinue)) { throw '未安装 Git,无法升级。' }
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $ProjectRoot '.git'))) { throw '此目录不含 Git 信息;请改用 Git 克隆或新版发布源码包。' }
|
||||
# Refuse dirty checkouts before terminating the user's running processes.
|
||||
$localChanges = & git -C $ProjectRoot status --porcelain 2>$null
|
||||
if ($LASTEXITCODE -ne 0) { throw '无法检查 Git 工作区。' }
|
||||
if ($localChanges) { throw '发现本地修改;请先提交或备份,未终止任何任务。' }
|
||||
Write-Host '======================================================'
|
||||
Write-Host 'ARTEMIS 独立升级:将终止当前项目的服务、MCP 及任务。' -ForegroundColor Yellow
|
||||
. (Join-Path $PSScriptRoot 'upgrade_processes.ps1')
|
||||
Stop-ArtemisUpgradeProcesses -ProjectRoot $ProjectRoot
|
||||
& $python (Join-Path $PSScriptRoot 'update_installation.py') source --root $ProjectRoot
|
||||
if ($LASTEXITCODE -notin @(0, 10)) { throw '源码升级未完成;配置和历史资料已保留。' }
|
||||
Stop-ArtemisUpgradeProcesses -ProjectRoot $ProjectRoot
|
||||
# Load the new launcher only AFTER the frozen Git updater has exited.
|
||||
$prepare = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', (Join-Path $ProjectRoot 'scripts\start.ps1'), '-PrepareOnly', '-SkipUpdate', '-NoOpen')
|
||||
if ($Mirror) { $prepare += @('-Mirror', $Mirror) }
|
||||
$previousChild = $env:ARTEMIS_UPGRADE_CHILD
|
||||
$env:ARTEMIS_UPGRADE_CHILD = '1'
|
||||
try { & powershell.exe @prepare; $prepareCode = $LASTEXITCODE }
|
||||
finally { $env:ARTEMIS_UPGRADE_CHILD = $previousChild }
|
||||
if ($prepareCode -ne 0) { throw '新版源码已保留,但环境同步失败;请处理上方错误后重新运行升级脚本。' }
|
||||
Write-Host '[升级完成] 源码、依赖、网页及 Codex MCP 已检查并同步。' -ForegroundColor Green
|
||||
Write-Host '[下一步] 运行启动脚本,并在 Codex 中重载 MCP 或重启 Codex。'
|
||||
exit 0
|
||||
} catch {
|
||||
Write-Host "[升级失败] $_" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
# Process ownership is determined by checkout paths, never by a port or name alone.
|
||||
function Get-ArtemisUpgradeProcesses {
|
||||
param([string]$ProjectRoot, [object[]]$Processes, [int[]]$ProtectedIds = @())
|
||||
$root = [IO.Path]::GetFullPath($ProjectRoot).TrimEnd('\') + '\'
|
||||
$venv = $root + '.venv\'
|
||||
$selected = @{}
|
||||
foreach ($process in $Processes) {
|
||||
if ($ProtectedIds -contains [int]$process.ProcessId) { continue }
|
||||
$executable = [string]$process.ExecutablePath
|
||||
$command = [string]$process.CommandLine
|
||||
$python = $process.Name -match '^(python(w)?|artemis(-admin)?)\.exe$'
|
||||
$inVenv = $executable.StartsWith($venv, [StringComparison]::OrdinalIgnoreCase)
|
||||
$explicitRoot = $command.Replace('/', '\').IndexOf($root, [StringComparison]::OrdinalIgnoreCase) -ge 0
|
||||
$entrypoint = $command -match '(?i)(?:-m\s+(?:artemis(?:\s|\.|$)|apps\.admin_console(?:\.|\s)|mcp_server(?:\.|\s|$))|[\\/]artemis(?:\.exe|[\\/]__main__\.py)|[\\/]mcp_server[\\/])'
|
||||
if (($python -and $inVenv) -or ($explicitRoot -and $entrypoint -and ($python -or $process.Name -eq 'uv.exe'))) {
|
||||
$selected[[int]$process.ProcessId] = $process
|
||||
}
|
||||
}
|
||||
do {
|
||||
$added = $false
|
||||
foreach ($process in $Processes) {
|
||||
$id = [int]$process.ProcessId
|
||||
if ($selected.ContainsKey($id) -or $ProtectedIds -contains $id) { continue }
|
||||
# Shared device services and desktop applications can outlive a task.
|
||||
if ($process.Name -match '^(adb|codex|chrome|msedge|firefox|emulator|MuMu.*|Nemu.*|Nox.*|MEmu.*|LdVBox.*|HD-Player)\.exe$') { continue }
|
||||
if ($selected.ContainsKey([int]$process.ParentProcessId)) {
|
||||
$selected[$id] = $process
|
||||
$added = $true
|
||||
}
|
||||
}
|
||||
} while ($added)
|
||||
return @($selected.Values)
|
||||
}
|
||||
|
||||
function Stop-ArtemisUpgradeProcesses {
|
||||
param([string]$ProjectRoot)
|
||||
$snapshot = @(Get-CimInstance Win32_Process -ErrorAction Stop)
|
||||
$protected = @($PID)
|
||||
$parentId = $PID
|
||||
do {
|
||||
$parent = $snapshot | Where-Object { [int]$_.ProcessId -eq $parentId } | Select-Object -First 1
|
||||
$parentId = if ($parent) { [int]$parent.ParentProcessId } else { 0 }
|
||||
if ($parentId -and $protected -notcontains $parentId) { $protected += $parentId } else { break }
|
||||
} while ($true)
|
||||
$deadline = [DateTime]::UtcNow.AddSeconds(10)
|
||||
do {
|
||||
$targets = @(Get-ArtemisUpgradeProcesses -ProjectRoot $ProjectRoot -Processes $snapshot -ProtectedIds $protected)
|
||||
if (-not $targets.Count) { return }
|
||||
foreach ($target in $targets) {
|
||||
$id = [int]$target.ProcessId
|
||||
$current = Get-CimInstance Win32_Process -Filter "ProcessId = $id" -ErrorAction Stop
|
||||
if (-not $current -or $current.CreationDate -ne $target.CreationDate) { continue }
|
||||
Write-Host "[STOP] ARTEMIS PID $id ($($target.Name))"
|
||||
try { Stop-Process -Id $id -Force -ErrorAction Stop }
|
||||
catch {
|
||||
if (Get-CimInstance Win32_Process -Filter "ProcessId = $id" -ErrorAction Stop) { throw }
|
||||
}
|
||||
}
|
||||
Start-Sleep -Milliseconds 200
|
||||
$snapshot = @(Get-CimInstance Win32_Process -ErrorAction Stop)
|
||||
} while ([DateTime]::UtcNow -lt $deadline)
|
||||
if (@(Get-ArtemisUpgradeProcesses -ProjectRoot $ProjectRoot -Processes $snapshot -ProtectedIds $protected).Count) {
|
||||
throw 'ARTEMIS processes are still running. Source/dependency updates were not started.'
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,10 @@ description: 使用 ARTEMIS MCP 在 Android 真机或模拟器上完成自然语
|
||||
|
||||
# ARTEMIS 自动化
|
||||
|
||||
当前仅提供 Codex MCP 配置安装与更新:`uv run artemis mcp --install codex`;模板使用 `uv run artemis mcp --generate-config codex` 查看。启动日志会打印实际 Codex 配置路径,更新后重载 MCP。
|
||||
|
||||
Windows 启动脚本只提示源码更新。升级使用 `update.bat`(国内镜像 `update-cn.bat`),会终止该项目的 ARTEMIS 服务、MCP 和运行任务;仅在用户授权升级或终止任务后执行,先告知任务将中断。升级会同步依赖、网页及 Codex MCP,保留配置和历史;完成后启动 ARTEMIS 并重载 Codex MCP。不要通过启动脚本拉取源码或强行覆盖本地修改。
|
||||
|
||||
使用项目提供的 MCP 工具操作 Android。报告由 ARTEMIS 自己生成,不要求宿主 AI 具备 Codex 私有工具、Word 或 Excel 插件。该 Skill 不提供桌面/浏览器自动化,也不提供历史动作脚本回放。
|
||||
|
||||
## 从需求到执行
|
||||
@@ -26,6 +30,8 @@ description: 使用 ARTEMIS MCP 在 Android 真机或模拟器上完成自然语
|
||||
|
||||
## 配置和恢复边界
|
||||
|
||||
- 本机常见模拟器在设备刷新、启动及重启 ADB 后自动发现并连接,不必猜固定端口。USB 与 Android SDK 模拟器由 ADB 原生发现。首次连接其他 TCP 设备/无线手机时,在网页“无线 ADB”填写实际地址和端口,成功后程序保存地址并自动重连;无线调试的配对和授权仍由用户完成,端口变化后需重新连接。远程/转发 ADB 不执行本机发现。用 `mobile_workspace` 或 `mobile_diagnose` 检查自动连接结果;多设备时仍先确认用户要测试哪台。默认开关及扫描预算可由 `mobile_config(section="capabilities")` 的 `adb_auto_connect`、`adb_discovery_interval_seconds`(10)、`adb_discovery_timeout_seconds`(5)配置,修改全局默认需要用户授权。
|
||||
|
||||
- `mobile_config` 读取非敏感设置。只有用户明确要求保存或修改默认配置时,才传 `changes` 与 `persist_defaults=true`;这些设置影响后续任务,不能为一次临时需求擅自改变以后所有任务。
|
||||
- 模型名称支持预设 `gpt-5.6-luna`、`gpt-6-luna`、`mimo-v2.6-flash`、`mimo-v2.6-pro` 和自定义名称,取决于用户配置的 Responses 网关。思考强度最高支持 `max`,默认 `high`、单次请求 300 秒、失败后最多重试 5 次;普通错误每次等待 10 秒,429 每次等待 60 秒。首选模型连续 3 次未形成有效工具调用时,当前步骤改用 `gpt-6-luna`(high),兜底最多再尝试 3 次;下一步恢复首选模型。默认关闭视频分析与录屏。不根据模型名称猜测网关能力。
|
||||
- 强度选 `default` 表示不发送该参数,和 `none`(显式要求关闭)不同。接口拒绝强度参数时明确呈现失败,先询问用户是否改用 `default`,不能静默降级或换模型。
|
||||
@@ -35,3 +41,9 @@ description: 使用 ARTEMIS MCP 在 Android 真机或模拟器上完成自然语
|
||||
- 批次暂停只停止后续派发;当前任务等待指导时用 `mobile_manage_task(action="pause", trace_id=...)`,真正取消用 `stop`。用户明确要求删除批次记录时先 `mobile_batch(action="get")` 核对编号,再用 `delete`;执行中/排队中的批次不能删,删除会清除该批次的任务历史、报告和文件。服务重启后运行/暂停的任务标记中断,不自动重跑。停止可能保留已经产生的业务效果,不声称自动回滚。
|
||||
|
||||
需要编写外部可执行测试代码时,先通过 ARTEMIS 实际探索目标应用,确认页面、定位器和转换。优先动态定位,框架支持时才以已验证坐标兜底;在最终脚本中明确等待条件,不将 AI 思考耗时当作确定性等待。
|
||||
|
||||
执行保护默认总时限 1800 秒,单任务、批次和 MCP 都适用,排队及用户暂停不计时。设备观测默认 60 秒、最多 3 次,ADB 命令默认 10 秒;观测失败不会继续向模型发送占位图或旧元素索引。Flash 连续 3 次动作失败先重新观察再切换兜底,兜底仍失败则结束任务并保存原因。不能以提高步数或反复重提任务代替设备诊断。
|
||||
|
||||
`mobile_run_task(runtime_overrides={"timeout_seconds":1800,"observation_timeout_seconds":60,"observation_max_attempts":3,"device_command_timeout_seconds":10,"action_failure_attempts":3})` 可为单任务覆盖执行保护;其中 `model` 是 API 模型名,外层 `model` 仍是 Flash/Pro 模式。相同字段也支持批次的 `task_config`。全局默认通过网页功能配置或明确授权的 `mobile_config(section="capabilities", changes={"task_timeout_seconds":1800}, persist_defaults=true)` 保存,对后续任务生效,不接受密钥。
|
||||
|
||||
任务已经产生最终结果,但 SDK 线程或资源清理仍卡住时,默认最多再等待 30 秒后回收工作进程,避免继续占用队列。全局可用 `ARTEMIS_WORKER_CLEANUP_TIMEOUT_SECONDS` 或功能配置的 `worker_cleanup_timeout_seconds` 调整,任务 JSON 同名字段可覆盖。原有结果与截图保留,未完成保存的录屏尽力恢复。
|
||||
@@ -17,6 +17,7 @@
|
||||
"formats": ["docx", "xlsx"],
|
||||
"stop_on_failure": false,
|
||||
"timeout_seconds": 1800,
|
||||
"repeat_count": 1,
|
||||
"cases": [
|
||||
{
|
||||
"case_id": "DEMO-001",
|
||||
@@ -42,13 +43,15 @@
|
||||
|
||||
`create` 只保存已校验的草稿。检查返回批次编号和范围,用户已经授权执行时接着 `mobile_batch(action="start", batch_id=...)`;用户只要求准备方案时留在草稿,不启动。保存 `batch_id`,用 `get` 跟踪各项状态。
|
||||
|
||||
用户要求压测时,在 `batch.repeat_count` 设置正整数循环次数(默认 1),只向 `batch.cases` 提交用户选择的用例。每轮按原顺序执行整批,再进入下一轮;各次执行独立保存编号和报告,`get` 中的 job 包含 `iteration`、`repeat_count`。总执行数为用例数乘以轮数,默认上限 10000,由服务的 `ARTEMIS_BATCH_MAX_EXECUTIONS` 控制。不要重复调用 `start` 来实现循环,也不要将循环次数写入每项 `task_config`。失败即停止会跳过后续全部轮次;复制失败项时各失败执行只重跑一次,新的批次循环次数为 1。
|
||||
|
||||
创建请求超时可能已经落库。先 `lookup(request_id=...)`;需要重发时保留**相同 request_id 和相同内容**。服务会返回原批次,内容不同会拒绝。不要通过换编号“修复超时”,否则会形成重复批次。
|
||||
|
||||
## Excel 导入
|
||||
|
||||
`mobile_task_file(action="template")` 返回空白模板的本地路径。“任务”页七列依次为:用例编号、检测项目、测试子项、测试用例、前置约束提取、Artemis提示词、任务配置(JSON)。仅提示词必填;说明页有一条示例,不会导入执行。JSON 支持 `profile`、`model`、`reasoning_effort`、`device_serial`、`verification_level`、`explorer_mode`、`locked_app_package`、`record_video`、`analyze_video`、`request_timeout_seconds`、`max_retries`、`retry_interval_seconds`、`timeout_seconds`。未知字段或密钥被拒绝。每行独立,不支持公式、宏、外部链接。
|
||||
|
||||
`preview` 返回 `valid/tasks/errors`,不会执行。所有错误处理完后,将 `tasks` 中每项的预览字段 `row` 去掉,作为 `batch.cases` 提交。不要跳过错误行却声称全部导入成功。
|
||||
`preview` 返回 `valid/tasks/errors`,不会执行。网页默认全选,可取消用例;AI 也应按用户指定范围筛选 `tasks`。所有错误处理完后,将所选项的预览字段 `row` 去掉,作为 `batch.cases` 提交,并说明实际选中数量。不要跳过错误行却声称全部导入成功。
|
||||
|
||||
## 状态与异常
|
||||
|
||||
|
||||
+4
-20
@@ -2,32 +2,16 @@
|
||||
chcp 65001 >nul 2>&1
|
||||
setlocal DisableDelayedExpansion
|
||||
set "ARTEMIS_LAUNCH_LANG=zh-CN"
|
||||
title ARTEMIS 国内镜像启动
|
||||
title ARTEMIS
|
||||
|
||||
if /i "%~1"=="-Help" goto help
|
||||
if /i "%~1"=="--help" goto help
|
||||
|
||||
echo ======================================================
|
||||
echo ARTEMIS 中文启动 - 使用国内镜像
|
||||
echo ======================================================
|
||||
echo 正在检查已有环境、项目更新及依赖;首次启动可能需要下载组件。
|
||||
echo 镜像地址和下载超时可在 config\downloads.json 中调整。
|
||||
echo.
|
||||
call "%~dp0start.bat" -Mirror China %*
|
||||
set "ARTEMIS_CN_EXIT_CODE=%ERRORLEVEL%"
|
||||
if not "%ARTEMIS_CN_EXIT_CODE%"=="0" echo 启动未完成;请查看上方错误信息,并检查网络或镜像设置。
|
||||
endlocal & exit /b %ARTEMIS_CN_EXIT_CODE%
|
||||
|
||||
:help
|
||||
echo 用法:start-cn.bat [选项]
|
||||
echo.
|
||||
echo -SetupOnly 安装或检查环境,不启动网页
|
||||
echo -Port 8001 使用指定端口,默认 8000
|
||||
echo -NoOpen 启动服务后不自动打开浏览器
|
||||
echo -SkipUpdate 跳过 Git 源码更新检查
|
||||
echo -SkipMcpSync 仅启动网页,跳过 MCP 安装和更新
|
||||
echo -Help 显示本说明
|
||||
echo.
|
||||
echo 国内镜像设置:config\downloads.json
|
||||
echo 首次运行需联网;后续运行会检查源码、依赖,并同步已安装 AI 客户端的 MCP。
|
||||
endlocal & exit /b 0
|
||||
call "%~dp0start.bat" -Mirror China -Help
|
||||
set "ARTEMIS_CN_EXIT_CODE=%ERRORLEVEL%"
|
||||
endlocal & exit /b %ARTEMIS_CN_EXIT_CODE%
|
||||
@@ -15,16 +15,11 @@ rem limitations under the License.
|
||||
|
||||
chcp 65001 >nul 2>&1
|
||||
setlocal DisableDelayedExpansion
|
||||
if /i "%ARTEMIS_LAUNCH_LANG%"=="zh-CN" (title ARTEMIS 手机自动化测试) else (title Artemis Mobile Agent UI)
|
||||
title ARTEMIS
|
||||
|
||||
pushd "%~dp0" || exit /b 1
|
||||
|
||||
echo ======================================================
|
||||
if /i "%ARTEMIS_LAUNCH_LANG%"=="zh-CN" (echo ARTEMIS 手机自动化测试) else (echo Artemis Autonomous Mobile Agent UI)
|
||||
echo ======================================================
|
||||
echo.
|
||||
|
||||
rem First run installs uv/Python/.venv; later runs check Git, dependencies and existing MCP clients.
|
||||
rem First run installs uv/Python/.venv; later runs check Git, dependencies and Codex MCP.
|
||||
rem Use -SkipUpdate to skip the Git source check and run local code.
|
||||
rem Use start.bat -SetupOnly to prepare Python without launching the UI.
|
||||
rem Use start-cn.bat or start.bat -Mirror China for China download mirrors.
|
||||
@@ -33,7 +28,7 @@ set "ARTEMIS_EXIT_CODE=%ERRORLEVEL%"
|
||||
|
||||
if not "%ARTEMIS_EXIT_CODE%"=="0" (
|
||||
echo.
|
||||
if /i "%ARTEMIS_LAUNCH_LANG%"=="zh-CN" (echo ARTEMIS 启动失败,请查看上方详细信息。) else (echo An error occurred while starting Artemis.)
|
||||
echo ARTEMIS startup failed. Please see the details above.
|
||||
if not defined ARTEMIS_NO_PAUSE pause
|
||||
)
|
||||
popd
|
||||
|
||||
@@ -26,6 +26,20 @@ import pytest
|
||||
from artemis.drivers.mock.mock_driver import MockDeviceDriver
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def no_host_adb_discovery(monkeypatch, request):
|
||||
"""Deterministic tests must never connect to host emulators or remembered phones."""
|
||||
from artemis.runtime.adb_discovery import adb_device_discovery
|
||||
|
||||
if any(
|
||||
request.node.get_closest_marker(name)
|
||||
for name in ("android", "integration", "e2e", "manual")
|
||||
):
|
||||
return
|
||||
monkeypatch.setattr(adb_device_discovery, "refresh", lambda *args, **kwargs: [])
|
||||
monkeypatch.setattr(adb_device_discovery, "remember", lambda *args: True)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_driver():
|
||||
"""Provide an isolated mock mobile driver."""
|
||||
|
||||
@@ -185,6 +185,107 @@ def test_preferences_and_required_device(client):
|
||||
assert client.post("/api/automation/batches", json=payload(device_serial="")).status_code == 422
|
||||
|
||||
|
||||
def test_batch_repetitions_are_ordered_independent_and_idempotent(client, isolated):
|
||||
request = payload(repeat_count=3, request_id="repeat-test")
|
||||
created = client.post("/api/automation/batches", json=request)
|
||||
assert created.status_code == 200
|
||||
batch = created.json()
|
||||
assert (batch["case_count"], batch["repeat_count"], batch["total_executions"]) == (2, 3, 6)
|
||||
jobs = isolated.jobs(batch["id"])
|
||||
assert len({j["session_id"] for j in jobs}) == 6
|
||||
assert [j["position"] for j in jobs] == list(range(1, 7))
|
||||
assert [(j["iteration"], j["case_position"]) for j in jobs] == [
|
||||
(1, 1),
|
||||
(1, 2),
|
||||
(2, 1),
|
||||
(2, 2),
|
||||
(3, 1),
|
||||
(3, 2),
|
||||
]
|
||||
assert [j["case"]["goal"] for j in jobs] == ["观察设置", "观察首页"] * 3
|
||||
assert all(j["status"] == "pending" for j in jobs)
|
||||
assert client.post("/api/automation/batches", json=request).json()["id"] == batch["id"]
|
||||
assert len(isolated.jobs(batch["id"])) == 6
|
||||
assert (
|
||||
client.post("/api/automation/batches", json={**request, "repeat_count": 2}).status_code
|
||||
== 409
|
||||
)
|
||||
# Each selected failure is copied once, including failures from different rounds.
|
||||
for job in (jobs[0], jobs[4]):
|
||||
isolated.save_job({**job, "status": "failed"})
|
||||
retry = service.batch_action(batch["id"], "retry_failed")
|
||||
assert retry["repeat_count"] == 1
|
||||
assert len(isolated.jobs(retry["id"])) == 2
|
||||
report = reports.session_report(jobs[4]["session_id"])
|
||||
assert "第 3 / 3 轮" in report["name"]
|
||||
archive = reports.export_batch(batch["id"])
|
||||
with zipfile.ZipFile(archive) as z:
|
||||
assert len([n for n in z.namelist() if n.endswith(".xlsx")]) == 7
|
||||
assert len(set(z.namelist())) == len(z.namelist())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("count", [0, -1, 1.5, True, "3", None])
|
||||
def test_batch_rejects_invalid_repetitions(client, isolated, count):
|
||||
assert (
|
||||
client.post("/api/automation/batches", json=payload(repeat_count=count)).status_code == 422
|
||||
)
|
||||
assert isolated.records("batch") == []
|
||||
|
||||
|
||||
def test_batch_limit_is_checked_before_creating_records(client, isolated, monkeypatch):
|
||||
monkeypatch.setattr(service.settings, "ARTEMIS_BATCH_MAX_EXECUTIONS", 5)
|
||||
assert client.get("/api/automation/preferences").json()["batch_max_executions"] == 5
|
||||
response = client.post("/api/automation/batches", json=payload(repeat_count=3))
|
||||
assert response.status_code == 409
|
||||
assert "5" in response.json()["detail"]
|
||||
assert not isolated.records("batch")
|
||||
assert not isolated.jobs()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_loop_dispatch_continues_after_failure_and_resume_without_repeating(
|
||||
isolated, monkeypatch
|
||||
):
|
||||
from apps.admin_console import server
|
||||
from artemis.runtime.device_pool import DeviceStatus
|
||||
|
||||
batch = service.create_batch(payload(repeat_count=2))
|
||||
service.batch_action(batch["id"], "resume")
|
||||
monkeypatch.setattr(service, "state", type("State", (), {"is_paused": False})())
|
||||
enqueue = AsyncMock(return_value={"tasks": [{"device_serial": "test-device"}]})
|
||||
monkeypatch.setattr(server.task_queue_service, "enqueue_tasks", enqueue)
|
||||
monkeypatch.setattr(
|
||||
"artemis.runtime.device_pool.try_list_devices_async",
|
||||
AsyncMock(return_value=[DeviceStatus(serial="test-device", state="device")]),
|
||||
)
|
||||
for index in range(4):
|
||||
await service.tick_batches()
|
||||
await service.tick_batches() # Polling must not enqueue the same execution twice.
|
||||
assert enqueue.await_count == index + 1
|
||||
job = isolated.jobs(batch["id"])[index]
|
||||
assert enqueue.call_args.kwargs["session_id"] == job["session_id"]
|
||||
assert f"第 {job['iteration']} / 2 轮" in enqueue.call_args.kwargs["display_name"]
|
||||
isolated.save_job({**job, "status": "failed" if index == 0 else "completed"})
|
||||
if index == 1:
|
||||
service.batch_action(batch["id"], "pause")
|
||||
await service.tick_batches()
|
||||
assert enqueue.await_count == 2
|
||||
service.batch_action(batch["id"], "resume")
|
||||
await service.tick_batches()
|
||||
assert isolated.get("batch", batch["id"])["status"] == "completed"
|
||||
assert enqueue.await_count == 4
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_repeat_fail_fast_skips_future_rounds(isolated):
|
||||
batch = service.create_batch(payload(repeat_count=3, stop_on_failure=True))
|
||||
first = isolated.jobs(batch["id"])[0]
|
||||
isolated.save_job({**first, "status": "failed"})
|
||||
service.batch_action(batch["id"], "resume")
|
||||
await service.tick_batches()
|
||||
assert [j["status"] for j in isolated.jobs(batch["id"])] == ["failed"] + ["skipped"] * 5
|
||||
|
||||
|
||||
def test_batch_delete_removes_tasks_and_files_and_prevents_request_replay(client, isolated):
|
||||
created = client.post(
|
||||
"/api/automation/batches", json=payload(request_id="delete-example")
|
||||
@@ -300,6 +401,116 @@ def test_restart_never_repeats_started_work(isolated):
|
||||
assert isolated.jobs(retry["id"])[0]["session_id"] != job["session_id"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("liveness_source", ["pid", "device_lock"])
|
||||
def test_recovery_preserves_live_runner_and_batch(isolated, monkeypatch, liveness_source):
|
||||
import os
|
||||
from types import SimpleNamespace
|
||||
from artemis.runtime import DeviceExecutionLock
|
||||
|
||||
batch = service.create_batch(payload())
|
||||
service.batch_action(batch["id"], "resume")
|
||||
job = isolated.jobs(batch["id"])[0]
|
||||
isolated.save_job({**job, "status": "running"})
|
||||
if liveness_source == "pid":
|
||||
with sqlite3.connect(isolated.path) as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO sessions(session_id,initial_goal,start_time,status,device_info,pid) "
|
||||
"VALUES (?,?,?,?,?,?)",
|
||||
(job["session_id"], "goal", 1, "running", "{}", os.getpid()),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
DeviceExecutionLock,
|
||||
"get_active_owners",
|
||||
lambda: (
|
||||
{"device": SimpleNamespace(session_id=job["session_id"])}
|
||||
if liveness_source == "device_lock"
|
||||
else {}
|
||||
),
|
||||
)
|
||||
service.recover_batches()
|
||||
assert isolated.job(job["session_id"])["status"] == "running"
|
||||
assert not isolated.job(job["session_id"]).get("error")
|
||||
assert isolated.get("batch", batch["id"])["status"] == "running"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_natural_completion_resolves_old_recovery_error_in_job_report_and_history(
|
||||
client, isolated
|
||||
):
|
||||
job = isolated.jobs(service.create_batch(payload())["id"])[0]
|
||||
message = "服务中断;未完成任务需手动重跑"
|
||||
isolated.save_job({**job, "status": "interrupted", "error": message})
|
||||
await service.on_terminal({"session_id": job["session_id"]}, "completed")
|
||||
saved = isolated.job(job["session_id"])
|
||||
assert saved["status"] == "completed"
|
||||
assert not saved.get("error")
|
||||
assert saved["recovery_events"][0]["message"] == message
|
||||
assert reports.session_report(job["session_id"])["error"] == ""
|
||||
assert not client.get("/api/automation/history").json()["items"][0].get("error")
|
||||
|
||||
|
||||
def test_recovery_repairs_completed_legacy_warning_but_preserves_real_failure(isolated):
|
||||
batch = service.create_batch(payload())
|
||||
first, second = isolated.jobs(batch["id"])
|
||||
isolated.save_job({**first, "status": "completed", "error": "服务中断,需手动重跑"})
|
||||
isolated.save_job({**second, "status": "failed", "error": "任务执行超时(30 秒)"})
|
||||
assert reports.session_report(first["session_id"])["error"] == ""
|
||||
service.recover_batches()
|
||||
assert not isolated.job(first["session_id"]).get("error")
|
||||
assert "服务中断" in isolated.job(first["session_id"])["recovery_events"][0]["message"]
|
||||
assert "超时" in isolated.job(second["session_id"])["error"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_surviving_worker_is_finalized_when_it_exits_without_resubmission(
|
||||
isolated, monkeypatch
|
||||
):
|
||||
import os
|
||||
from artemis.runtime import DeviceExecutionLock
|
||||
|
||||
batch = service.create_batch(payload())
|
||||
service.batch_action(batch["id"], "resume")
|
||||
job = isolated.jobs(batch["id"])[0]
|
||||
isolated.save_job({**job, "status": "running"})
|
||||
monkeypatch.setattr(DeviceExecutionLock, "get_active_owners", lambda: {})
|
||||
with sqlite3.connect(isolated.path) as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO sessions(session_id,initial_goal,start_time,status,device_info,pid) "
|
||||
"VALUES (?,?,?,?,?,?)",
|
||||
(job["session_id"], "goal", time.time(), "running", "{}", os.getpid()),
|
||||
)
|
||||
service.recover_batches()
|
||||
await service.reconcile_recovered_jobs()
|
||||
assert isolated.job(job["session_id"])["status"] == "running"
|
||||
with sqlite3.connect(isolated.path) as conn:
|
||||
conn.execute(
|
||||
"UPDATE sessions SET pid=NULL,status='completed' WHERE session_id=?",
|
||||
(job["session_id"],),
|
||||
)
|
||||
await service.reconcile_recovered_jobs()
|
||||
saved = isolated.job(job["session_id"])
|
||||
assert saved["status"] == "completed"
|
||||
assert saved["report_ready"]
|
||||
assert not saved.get("recovery_waiting")
|
||||
assert not saved.get("error")
|
||||
assert len(isolated.jobs(batch["id"])) == 2
|
||||
assert isolated.jobs(batch["id"])[1]["status"] == "pending"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_surviving_worker_that_dies_without_result_is_interrupted(isolated, monkeypatch):
|
||||
from artemis.runtime import DeviceExecutionLock
|
||||
|
||||
job = isolated.jobs(service.create_batch(payload())["id"])[0]
|
||||
isolated.save_job({**job, "status": "running", "recovery_waiting": True})
|
||||
monkeypatch.setattr(DeviceExecutionLock, "get_active_owners", lambda: {})
|
||||
await service.reconcile_recovered_jobs()
|
||||
saved = isolated.job(job["session_id"])
|
||||
assert saved["status"] == "interrupted"
|
||||
assert "服务中断" in saved["error"]
|
||||
assert not saved.get("recovery_waiting")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_batch_admission_idempotent_and_bound_device(isolated, monkeypatch):
|
||||
from apps.admin_console import server
|
||||
|
||||
@@ -33,6 +33,12 @@ def isolated_settings(monkeypatch, tmp_path):
|
||||
"ARTEMIS_OUTPUTTER_ENABLED",
|
||||
"ARTEMIS_STEP_SUMMARIZER_ENABLED",
|
||||
"ARTEMIS_SCREENSHOT_LIMIT_ENABLED",
|
||||
"ARTEMIS_TASK_TIMEOUT_SECONDS",
|
||||
"ARTEMIS_OBSERVATION_TIMEOUT_SECONDS",
|
||||
"ARTEMIS_OBSERVATION_MAX_ATTEMPTS",
|
||||
"ARTEMIS_DEVICE_COMMAND_TIMEOUT_SECONDS",
|
||||
"ARTEMIS_ACTION_FAILURE_ATTEMPTS",
|
||||
"ARTEMIS_WORKER_CLEANUP_TIMEOUT_SECONDS",
|
||||
]
|
||||
for key in keys:
|
||||
monkeypatch.setattr(settings, key, getattr(settings, key))
|
||||
@@ -202,3 +208,26 @@ def test_responses_payload_has_reasoning_and_no_sdk_retry(monkeypatch, effort):
|
||||
assert factory.call_args.kwargs["use_responses_api"] is True
|
||||
ModelFactory.create_model(ModelEndpoint(api_key="test-only", reasoning_effort="default"))
|
||||
assert "reasoning_effort" not in factory.call_args.kwargs
|
||||
|
||||
|
||||
def test_execution_protection_saves_reload_without_touching_secret(isolated_settings):
|
||||
result = service.save_capability_settings(
|
||||
service.CapabilitySettings(
|
||||
task_timeout_seconds=3600,
|
||||
observation_timeout_seconds=45,
|
||||
observation_max_attempts=2,
|
||||
device_command_timeout_seconds=8,
|
||||
action_failure_attempts=4,
|
||||
worker_cleanup_timeout_seconds=15,
|
||||
)
|
||||
)
|
||||
reloaded = Settings(_env_file=isolated_settings)
|
||||
assert reloaded.ARTEMIS_TASK_TIMEOUT_SECONDS == result.task_timeout_seconds == 3600
|
||||
assert reloaded.ARTEMIS_OBSERVATION_TIMEOUT_SECONDS == 45
|
||||
assert reloaded.ARTEMIS_OBSERVATION_MAX_ATTEMPTS == 2
|
||||
assert reloaded.ARTEMIS_DEVICE_COMMAND_TIMEOUT_SECONDS == 8
|
||||
assert reloaded.ARTEMIS_ACTION_FAILURE_ATTEMPTS == 4
|
||||
assert reloaded.ARTEMIS_WORKER_CLEANUP_TIMEOUT_SECONDS == 15
|
||||
assert reloaded.OPENAI_API_KEY is None
|
||||
assert settings.OPENAI_API_KEY.get_secret_value() == "existing-test-secret"
|
||||
assert dotenv_values(isolated_settings)["UNRELATED"] == "keep"
|
||||
@@ -15,6 +15,7 @@
|
||||
import asyncio
|
||||
from contextlib import suppress
|
||||
import signal
|
||||
import socket
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
@@ -23,10 +24,55 @@ import uvicorn
|
||||
from apps.admin_console.core.state import state
|
||||
from apps.admin_console.routers.tasks import stream_events
|
||||
from apps.admin_console.server import ArtemisUvicornServer, app, on_shutdown
|
||||
from apps.admin_console import server as server_module
|
||||
|
||||
WINDOWS_FORCE_SIGNAL = getattr(signal, "SIGBREAK", signal.SIGTERM)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("reload", [False, True])
|
||||
def test_occupied_port_never_initializes_or_overwrites_server_metadata(
|
||||
tmp_path, monkeypatch, reload
|
||||
):
|
||||
from artemis.runtime import server_lifecycle
|
||||
|
||||
metadata = tmp_path / "server.json"
|
||||
metadata.write_text('{"pid":123,"lifecycle_token":"original"}', encoding="utf-8")
|
||||
monkeypatch.setattr(server_lifecycle, "get_server_info_file", lambda: metadata)
|
||||
before = metadata.read_bytes()
|
||||
with (
|
||||
socket.create_server(("127.0.0.1", 0)) as original,
|
||||
patch.object(server_module.ArtemisUvicornServer, "run") as run,
|
||||
patch.object(server_module, "write_server_info") as publish,
|
||||
):
|
||||
with pytest.raises(SystemExit, match="1"):
|
||||
server_module.run_ui_server("127.0.0.1", original.getsockname()[1], reload=reload)
|
||||
run.assert_not_called()
|
||||
publish.assert_not_called()
|
||||
assert metadata.read_bytes() == before
|
||||
|
||||
|
||||
def test_server_holds_port_before_running_lifespan(monkeypatch):
|
||||
monkeypatch.setattr(state, "port", 0, raising=False)
|
||||
monkeypatch.setattr(state, "host", "127.0.0.1", raising=False)
|
||||
observed = []
|
||||
|
||||
def run(_server, sockets):
|
||||
listener = sockets[0]
|
||||
port = listener.getsockname()[1]
|
||||
observed.append(listener)
|
||||
assert state.port == port
|
||||
with pytest.raises(OSError), socket.create_server(("127.0.0.1", port)):
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(server_module.ArtemisUvicornServer, "run", run)
|
||||
monkeypatch.setattr(server_module, "clear_server_info", lambda **kwargs: None)
|
||||
with patch.object(server_module, "write_server_info") as publish:
|
||||
server_module.run_ui_server("127.0.0.1", 0)
|
||||
publish.assert_not_called() # Publication belongs to the later lifespan.
|
||||
assert len(observed) == 1
|
||||
assert observed[0].fileno() == -1
|
||||
|
||||
|
||||
def _pending_queue_get_tasks():
|
||||
return {
|
||||
task
|
||||
|
||||
@@ -323,7 +323,9 @@ async def test_queue_worker_cmd_construction():
|
||||
endpoint = enqueue_result["tasks"][0]["adb_endpoint"]
|
||||
assert executed_kwargs[0]["env"]["ADB_HOST"] == endpoint["host"]
|
||||
assert executed_kwargs[0]["env"]["ADB_PORT"] == str(endpoint["port"])
|
||||
assert executed_kwargs[0]["env"]["ADB_SERVER_SOCKET"] == endpoint["socket"]
|
||||
assert executed_kwargs[0]["env"]["ADB_SERVER_SOCKET"] == (
|
||||
"tcp:localhost:5037" if endpoint["is_local_default"] else endpoint["socket"]
|
||||
)
|
||||
assert executed_kwargs[0]["env"]["ARTEMIS_ADB_ENDPOINT_ID"] == endpoint["identity"]
|
||||
if sys.platform == "win32":
|
||||
assert executed_kwargs[0]["creationflags"] == (
|
||||
|
||||
@@ -15,6 +15,9 @@
|
||||
"""Unit tests for Universal FlashRunner."""
|
||||
|
||||
import base64
|
||||
from io import BytesIO
|
||||
from PIL import Image
|
||||
from artemis.mcp.observation import DeviceObservationError
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, Mock, patch
|
||||
import pytest
|
||||
@@ -72,9 +75,18 @@ def test_flash_runner_tools_initialization(mock_context):
|
||||
# --- Post-action screenshot fallback (failed action / unknown tool) ----------------
|
||||
|
||||
|
||||
def _post_image():
|
||||
buffer = BytesIO()
|
||||
Image.new("RGB", (64, 64), "white").save(buffer, format="PNG")
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
_POST_IMG = _post_image()
|
||||
|
||||
|
||||
def _screen(elements):
|
||||
return SimpleNamespace(
|
||||
base64=base64.b64encode(b"POST-IMG").decode("ascii"),
|
||||
base64=base64.b64encode(_POST_IMG).decode("ascii"),
|
||||
elements=elements,
|
||||
width=1080,
|
||||
height=2400,
|
||||
@@ -120,7 +132,7 @@ async def test_fallback_observation_renders_the_indexed_ui_list(mock_context, tm
|
||||
exec_result, "click", frozenset({"click"}), state
|
||||
)
|
||||
|
||||
assert post == b"POST-IMG"
|
||||
assert post == _POST_IMG
|
||||
assert isinstance(exec_result.ui_elements_text, str)
|
||||
assert exec_result.ui_elements_text == "[1] Text: 'Settings' | Bounds: [37,50][962,112]"
|
||||
assert "{'text'" not in exec_result.ui_elements_text
|
||||
@@ -154,8 +166,8 @@ async def test_fallback_observation_is_skipped_for_non_action_tools(mock_context
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fallback_observation_keeps_the_executors_ui_list(mock_context, tmp_path):
|
||||
"""An action that reported a UI list but no screenshot keeps its own list."""
|
||||
async def test_fallback_observation_replaces_stale_executor_ui_list(mock_context, tmp_path):
|
||||
"""Fresh screenshots and element lists must describe the same observation."""
|
||||
with patch("artemis.controllers.unified_controller.get_driver"):
|
||||
runner = FlashRunner(mock_context, goal="g")
|
||||
runner.controller = Mock()
|
||||
@@ -175,12 +187,13 @@ async def test_fallback_observation_keeps_the_executors_ui_list(mock_context, tm
|
||||
exec_result, "click", frozenset({"click"}), None
|
||||
)
|
||||
|
||||
assert post == b"POST-IMG"
|
||||
assert exec_result.ui_elements_text == "[1] Text: 'Mine' | Bounds: [0,0][10,10]"
|
||||
assert post == _POST_IMG
|
||||
assert "Other" in exec_result.ui_elements_text
|
||||
assert "Mine" not in exec_result.ui_elements_text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fallback_observation_failure_is_contained(mock_context):
|
||||
async def test_fallback_observation_failure_stops_after_bounded_recovery(mock_context):
|
||||
with patch("artemis.controllers.unified_controller.get_driver"):
|
||||
runner = FlashRunner(mock_context, goal="g")
|
||||
runner.controller = Mock()
|
||||
@@ -189,11 +202,13 @@ async def test_fallback_observation_failure_is_contained(mock_context):
|
||||
state.latest_screenshot = "old.jpg"
|
||||
exec_result = _failed_click()
|
||||
|
||||
post = await runner._capture_post_screenshot(exec_result, "click", frozenset({"click"}), state)
|
||||
|
||||
assert post is None
|
||||
assert exec_result.ui_elements_text is None
|
||||
assert state.latest_screenshot == "old.jpg"
|
||||
with patch("artemis.mcp.observation.settings.ARTEMIS_OBSERVATION_MAX_ATTEMPTS", 3):
|
||||
with pytest.raises(DeviceObservationError, match="adb gone"):
|
||||
await runner._capture_post_screenshot(exec_result, "click", frozenset({"click"}), state)
|
||||
assert runner.controller.get_screen_data.await_count == 3
|
||||
assert state.latest_screenshot is None
|
||||
assert state.indexed_elements == []
|
||||
assert state.indexed_points == []
|
||||
|
||||
|
||||
def test_flash_runner_executor_follows_the_flash_explorer_tier(mock_context):
|
||||
|
||||
@@ -213,7 +213,8 @@ def test_observation_tail_has_pro_shape(mock_context):
|
||||
texts = [b["text"] for b in later.content]
|
||||
assert OBSERVATION_HEADER_RE.match(texts[0])
|
||||
assert "objective" not in "".join(texts).lower()
|
||||
assert texts[1:] == [
|
||||
assert "当前没有可用的元素索引" in texts[1]
|
||||
assert texts[2:] == [
|
||||
"nudge",
|
||||
"[INJECTED]",
|
||||
'User instruction: "stop"',
|
||||
@@ -408,6 +409,98 @@ def _report(status="completed", tc_id="tc-report", **extra):
|
||||
_INITIAL_OBSERVATION = ("shot0.png", b"IMG0", "[1] Settings")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("fallback_succeeds", [True, False])
|
||||
async def test_failed_actions_have_finite_fallback_and_restore_primary(
|
||||
mock_context, monkeypatch, fallback_succeeds
|
||||
):
|
||||
monkeypatch.setattr("artemis.agents.flash.runner.settings.ARTEMIS_ACTION_FAILURE_ATTEMPTS", 3)
|
||||
monkeypatch.setattr(
|
||||
"artemis.agents.flash.runner.settings.ARTEMIS_TOOL_FALLBACK_MAX_NO_PROGRESS_ATTEMPTS", 3
|
||||
)
|
||||
action_count = 4 if fallback_succeeds else 6
|
||||
responses = [
|
||||
AIMessage(
|
||||
content="try", tool_calls=[{"name": "click", "args": {"index": 1}, "id": f"tc-{i}"}]
|
||||
)
|
||||
for i in range(action_count)
|
||||
]
|
||||
if fallback_succeeds:
|
||||
responses.append(_report())
|
||||
with patch("artemis.controllers.unified_controller.get_driver"):
|
||||
runner = _make_runner(mock_context, responses)
|
||||
fallback = Mock()
|
||||
count = 0
|
||||
|
||||
def execute(name, args, tc_id, state, **kwargs):
|
||||
nonlocal count
|
||||
count += 1
|
||||
result = _exec_result(tc_id, name, b"current-screen")
|
||||
if count <= 3 or not fallback_succeeds:
|
||||
result.status = "error"
|
||||
result.text_summary = "目标不存在"
|
||||
return result
|
||||
|
||||
runner.executor.execute = AsyncMock(side_effect=execute)
|
||||
with (
|
||||
patch(
|
||||
"artemis.agents.flash.runner.capture_screenshot_and_parse_ui",
|
||||
AsyncMock(return_value=_INITIAL_OBSERVATION),
|
||||
) as observe,
|
||||
patch("artemis.agents.flash.runner.get_llm", return_value=fallback),
|
||||
):
|
||||
outcome = await runner.run(State(initial_goal="Open Settings"))
|
||||
primary = runner._init_llm.return_value
|
||||
assert all(call["llm"] is primary for call in runner.calls[:3])
|
||||
assert runner.calls[3]["llm"] is fallback
|
||||
assert observe.await_count == 2 # initial + fresh observation before fallback
|
||||
if fallback_succeeds:
|
||||
assert outcome["status"] == "completed"
|
||||
assert runner.calls[-1]["llm"] is primary
|
||||
else:
|
||||
assert outcome["status"] == "failed"
|
||||
assert "兜底模型连续 3" in outcome["explanation"]
|
||||
assert "目标不存在" in outcome["explanation"]
|
||||
assert len(runner.calls) == 6
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_empty_current_ui_clears_previous_turn_element_list(mock_context):
|
||||
response = AIMessage(
|
||||
content="tap", tool_calls=[{"name": "click", "args": {"index": 1}, "id": "tc"}]
|
||||
)
|
||||
with patch("artemis.controllers.unified_controller.get_driver"):
|
||||
runner = _make_runner(mock_context, [response, _report()])
|
||||
runner.executor.execute = AsyncMock(
|
||||
return_value=_exec_result("tc", "click", b"fresh-screen", ui="")
|
||||
)
|
||||
with patch(
|
||||
"artemis.agents.flash.runner.capture_screenshot_and_parse_ui",
|
||||
AsyncMock(return_value=_INITIAL_OBSERVATION),
|
||||
):
|
||||
await runner.run(State(initial_goal="Open Settings"))
|
||||
tail = runner.calls[-1]["messages"][-1]
|
||||
text = "\n".join(block.get("text", "") for block in tail.content)
|
||||
assert "当前没有可用的元素索引" in text
|
||||
assert "[1] Settings" not in text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unavailable_screen_ends_before_any_model_call(mock_context):
|
||||
from artemis.mcp.observation import DeviceObservationError
|
||||
|
||||
with patch("artemis.controllers.unified_controller.get_driver"):
|
||||
runner = _make_runner(mock_context, [])
|
||||
with patch(
|
||||
"artemis.agents.flash.runner.capture_screenshot_and_parse_ui",
|
||||
AsyncMock(side_effect=DeviceObservationError("设备断连")),
|
||||
):
|
||||
outcome = await runner.run(State(initial_goal="Open Settings"))
|
||||
assert outcome["code"] == "device_observation_failed"
|
||||
assert outcome["error"] == "设备断连"
|
||||
runner._invoke_model.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_builds_prompt_from_ledger_with_session_offsets(mock_context):
|
||||
"""Turn 2 must see: the static system prefix, the committed turn 1 (its
|
||||
|
||||
@@ -33,6 +33,17 @@ class DummyState:
|
||||
self.operator_replan_reason = operator_replan_reason
|
||||
|
||||
|
||||
import base64
|
||||
from io import BytesIO
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def _valid_screen_base64():
|
||||
buffer = BytesIO()
|
||||
Image.new("RGB", (64, 64), "white").save(buffer, format="PNG")
|
||||
return base64.b64encode(buffer.getvalue()).decode("ascii")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_context():
|
||||
ctx = Mock(spec=ArtemisContext)
|
||||
@@ -41,7 +52,7 @@ def mock_context():
|
||||
ctx.adb_client = Mock()
|
||||
ctx.ui_adb_client = Mock()
|
||||
mock_screen_data = Mock()
|
||||
mock_screen_data.base64 = "YmFzZTY0"
|
||||
mock_screen_data.base64 = _valid_screen_base64()
|
||||
mock_screen_data.elements = []
|
||||
mock_screen_data.width = 1080
|
||||
mock_screen_data.height = 2400
|
||||
|
||||
@@ -70,6 +70,34 @@ def test_adb_session_builds_explicit_endpoint_command_and_environment():
|
||||
assert environment[ADB_ENDPOINT_ID_ENV] == endpoint.identity
|
||||
|
||||
|
||||
@pytest.mark.parametrize("host", ["127.0.0.1", "localhost", "::1"])
|
||||
def test_local_endpoint_allows_adb_auto_start_without_changing_task_identity(host):
|
||||
endpoint = AdbServerEndpoint(host, 5037)
|
||||
session = AdbSession(endpoint, adb_path="adb")
|
||||
inherited = {
|
||||
"ADB_SERVER_SOCKET": "tcp:remote.example:5040",
|
||||
"ANDROID_ADB_SERVER_ADDRESS": "remote.example",
|
||||
"ANDROID_ADB_SERVER_PORT": "5040",
|
||||
}
|
||||
|
||||
assert session.command(["devices"]) == ["adb", "-H", "localhost", "-P", "5037", "devices"]
|
||||
environment = session.environment(inherited)
|
||||
assert environment["ADB_SERVER_SOCKET"] == "tcp:localhost:5037"
|
||||
assert environment["ADB_HOST"] == host
|
||||
assert environment[ADB_ENDPOINT_ID_ENV] == endpoint.identity
|
||||
assert inherited["ADB_SERVER_SOCKET"] == "tcp:remote.example:5040"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("host", "port"), [("127.0.0.1", 5038), ("::1", 5038), ("server.example", 5037)]
|
||||
)
|
||||
def test_forwarded_endpoint_never_uses_local_daemon_auto_start(host, port):
|
||||
endpoint = AdbServerEndpoint(host, port)
|
||||
session = AdbSession(endpoint, adb_path="adb")
|
||||
assert session.command(["devices"])[2] == host
|
||||
assert session.environment({})["ADB_SERVER_SOCKET"] == endpoint.socket
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_connect_activates_forwarded_server_after_success(monkeypatch):
|
||||
captured: dict[str, object] = {}
|
||||
@@ -253,7 +281,7 @@ async def test_use_local_server_restores_standard_endpoint(monkeypatch):
|
||||
assert result["success"] is True
|
||||
assert result["endpoint"] == AdbServerEndpoint("127.0.0.1", 5037).to_dict()
|
||||
assert settings.ADB_PORT == 5037
|
||||
assert os.environ["ADB_SERVER_SOCKET"] == "tcp:127.0.0.1:5037"
|
||||
assert os.environ["ADB_SERVER_SOCKET"] == "tcp:localhost:5037"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -282,6 +310,67 @@ async def test_remote_endpoint_blocks_local_wireless_connection(monkeypatch):
|
||||
assert "Switch to local ADB" in result["message"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_restart_reconnects_tcp_devices_after_server_started(monkeypatch):
|
||||
from artemis.runtime.adb_discovery import adb_device_discovery
|
||||
|
||||
monkeypatch.setattr(
|
||||
adb_server_connection, "current_endpoint", lambda: AdbServerEndpoint("127.0.0.1", 5037)
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"artemis.core.diagnostics.adb_keys.inspect_adb_keys",
|
||||
lambda: type("Keys", (), {"is_corrupted": False})(),
|
||||
)
|
||||
events = []
|
||||
|
||||
def run(args, **kwargs):
|
||||
events.append(args[-1])
|
||||
return subprocess.CompletedProcess(args, 0, "", "")
|
||||
|
||||
def reconnect(*args, **kwargs):
|
||||
events.append("reconnect")
|
||||
assert kwargs["force"] is True
|
||||
return [{"target": "127.0.0.1:16384", "success": True}]
|
||||
|
||||
monkeypatch.setattr(subprocess, "run", run)
|
||||
monkeypatch.setattr(adb_device_discovery, "refresh", reconnect)
|
||||
result = await ReadinessEngine().restart_adb_server()
|
||||
assert events == ["kill-server", "start-server", "reconnect"]
|
||||
assert result["automatic_connections"][0]["success"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_manual_tcp_connection_remembers_success_only(monkeypatch):
|
||||
from unittest.mock import Mock
|
||||
from artemis.runtime.adb_discovery import adb_device_discovery
|
||||
|
||||
monkeypatch.setattr(
|
||||
adb_server_connection, "current_endpoint", lambda: AdbServerEndpoint("127.0.0.1", 5037)
|
||||
)
|
||||
remember = Mock(return_value=True)
|
||||
monkeypatch.setattr(adb_device_discovery, "remember", remember)
|
||||
monkeypatch.setattr(
|
||||
subprocess,
|
||||
"run",
|
||||
lambda args, **kwargs: subprocess.CompletedProcess(
|
||||
args, 0, "connected to 192.0.2.10:5555", ""
|
||||
),
|
||||
)
|
||||
result = await ReadinessEngine().connect_wireless_adb("192.0.2.10", 5555)
|
||||
assert result["remembered"] is True
|
||||
remember.assert_called_once_with("192.0.2.10:5555")
|
||||
remember.reset_mock()
|
||||
monkeypatch.setattr(
|
||||
subprocess,
|
||||
"run",
|
||||
lambda args, **kwargs: subprocess.CompletedProcess(args, 1, "", "connection refused"),
|
||||
)
|
||||
result = await ReadinessEngine().connect_wireless_adb("192.0.2.11", 5555)
|
||||
assert result["success"] is False
|
||||
assert result["remembered"] is False
|
||||
remember.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_remote_endpoint_blocks_local_emulator_launch(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
|
||||
@@ -53,9 +53,14 @@ async def test_preview_is_read_only_and_create_is_draft(monkeypatch, tmp_path):
|
||||
with pytest.raises(ValueError):
|
||||
await tools.mobile_batch("create", batch={"name": "x"})
|
||||
request.assert_not_awaited()
|
||||
await tools.mobile_batch("create", request_id="stable-id", batch={"name": "x"})
|
||||
selected = [{"name": "选中用例", "goal": "观察设置"}]
|
||||
await tools.mobile_batch(
|
||||
"create", request_id="stable-id", batch={"name": "x", "cases": selected, "repeat_count": 3}
|
||||
)
|
||||
assert request.await_count == 1
|
||||
assert request.call_args.kwargs["json"]["request_id"] == "stable-id"
|
||||
assert request.call_args.kwargs["json"]["cases"] == selected
|
||||
assert request.call_args.kwargs["json"]["repeat_count"] == 3
|
||||
assert request.call_args.args[1] == "/api/automation/batches"
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
"""TCP discovery tests never touch real processes, ports, devices or user state."""
|
||||
|
||||
import importlib
|
||||
import json
|
||||
import struct
|
||||
import subprocess
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from artemis.config import settings
|
||||
from artemis.runtime.adb_endpoint import AdbEndpoint
|
||||
|
||||
module = importlib.import_module("artemis.runtime.adb_discovery")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def discovery(tmp_path, monkeypatch):
|
||||
instance = module.AdbDeviceDiscovery()
|
||||
monkeypatch.setattr(instance, "_directory", lambda: tmp_path)
|
||||
monkeypatch.setattr(module, "emulator_listeners", lambda: [])
|
||||
monkeypatch.setattr(
|
||||
module, "current_adb_endpoint", lambda: AdbEndpoint.create("127.0.0.1", 5037)
|
||||
)
|
||||
monkeypatch.setattr(settings, "ARTEMIS_ADB_AUTO_CONNECT", True)
|
||||
monkeypatch.setattr(settings, "ARTEMIS_ADB_DISCOVERY_TIMEOUT_SECONDS", 5)
|
||||
monkeypatch.setattr(settings, "ARTEMIS_ADB_DISCOVERY_INTERVAL_SECONDS", 10)
|
||||
return instance
|
||||
|
||||
|
||||
def fake_adb(monkeypatch, *, ready="", failures=()):
|
||||
calls = []
|
||||
connected = []
|
||||
|
||||
def run(self, arguments, **kwargs):
|
||||
calls.append(arguments)
|
||||
assert 0 < kwargs["timeout"] <= 5
|
||||
if arguments == ["devices"]:
|
||||
return subprocess.CompletedProcess(
|
||||
arguments,
|
||||
0,
|
||||
"List of devices attached\n"
|
||||
+ ready
|
||||
+ "".join(f"{target} device\n" for target in connected),
|
||||
"",
|
||||
)
|
||||
target = arguments[1]
|
||||
if target in failures:
|
||||
raise subprocess.TimeoutExpired(arguments, kwargs["timeout"])
|
||||
connected.append(target)
|
||||
return subprocess.CompletedProcess(arguments, 0, f"connected to {target}", "")
|
||||
|
||||
monkeypatch.setattr(module.AdbSession, "run", run)
|
||||
return calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"name",
|
||||
[
|
||||
"MuMuNxDevice.exe",
|
||||
"NemuHeadless.exe",
|
||||
"LdVBoxHeadless.exe",
|
||||
"NoxVMHandle.exe",
|
||||
"MEmuHeadless.exe",
|
||||
"HD-Player.exe",
|
||||
],
|
||||
)
|
||||
def test_supported_emulator_listener_ownership(monkeypatch, name):
|
||||
monkeypatch.setattr(
|
||||
module.psutil,
|
||||
"process_iter",
|
||||
lambda attrs: [
|
||||
SimpleNamespace(info={"pid": 4, "name": name, "exe": "vendor.exe"}),
|
||||
SimpleNamespace(info={"pid": 5, "name": "other.exe"}),
|
||||
],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
module.psutil,
|
||||
"net_connections",
|
||||
lambda kind: [
|
||||
SimpleNamespace(pid=pid, status="LISTEN", laddr=SimpleNamespace(ip=ip, port=port))
|
||||
for pid, ip, port in [
|
||||
(4, "0.0.0.0", 16384),
|
||||
(4, "127.0.0.1", 7555),
|
||||
(4, "192.0.2.1", 5555),
|
||||
(5, "0.0.0.0", 16385),
|
||||
]
|
||||
],
|
||||
)
|
||||
assert module.emulator_listeners() == [["127.0.0.1:16384", "127.0.0.1:7555"]]
|
||||
|
||||
|
||||
def test_generic_virtualbox_is_not_an_android_emulator(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
module.psutil,
|
||||
"process_iter",
|
||||
lambda attrs: [
|
||||
SimpleNamespace(
|
||||
info={"pid": 4, "name": "VBoxHeadless.exe", "exe": "VirtualBox/VBoxHeadless.exe"}
|
||||
)
|
||||
],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
module.psutil,
|
||||
"net_connections",
|
||||
lambda kind: pytest.fail("No known emulator; do not scan listeners"),
|
||||
)
|
||||
assert module.emulator_listeners() == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind,valid", [(b"CNXN", True), (b"AUTH", True), (b"HTTP", False)])
|
||||
def test_adbd_protocol_handles_fragmented_headers(monkeypatch, kind, valid):
|
||||
command = int.from_bytes(kind, "little")
|
||||
header = struct.pack("<6I", command, 1, 4096, 0, 0, command ^ 0xFFFFFFFF)
|
||||
stream = Mock()
|
||||
stream.__enter__ = Mock(return_value=stream)
|
||||
stream.__exit__ = Mock(return_value=False)
|
||||
stream.recv.side_effect = [header[:8], header[8:]]
|
||||
monkeypatch.setattr(module.socket, "create_connection", lambda *args, **kwargs: stream)
|
||||
assert module.is_adbd("127.0.0.1:16384", 0.3) is valid
|
||||
assert stream.sendall.call_args.args[0][:4] == b"CNXN"
|
||||
|
||||
|
||||
def test_discovery_connects_new_instance_without_duplicate_aliases(discovery, monkeypatch):
|
||||
calls = fake_adb(monkeypatch)
|
||||
monkeypatch.setattr(
|
||||
module,
|
||||
"emulator_listeners",
|
||||
lambda: [["127.0.0.1:16384", "127.0.0.1:7555"], ["127.0.0.1:16416"]],
|
||||
)
|
||||
monkeypatch.setattr(module, "is_adbd", lambda *args: True)
|
||||
results = discovery.refresh("adb")
|
||||
assert [r["target"] for r in results] == ["127.0.0.1:16384", "127.0.0.1:16416"]
|
||||
discovery.refresh("adb")
|
||||
assert len(calls) == 5 # cached: no subprocesses on repeated polling
|
||||
discovery.refresh("adb", force=True)
|
||||
assert len(calls) == 6 # force enumerates; connected instances are not reconnected
|
||||
|
||||
|
||||
def test_ready_and_unauthorized_emulators_are_not_probed(discovery, monkeypatch):
|
||||
calls = fake_adb(monkeypatch, ready="127.0.0.1:7555 device\n127.0.0.1:16416 unauthorized\n")
|
||||
monkeypatch.setattr(
|
||||
module,
|
||||
"emulator_listeners",
|
||||
lambda: [["127.0.0.1:16384", "127.0.0.1:7555"], ["127.0.0.1:16416"]],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
module, "is_adbd", lambda *args: pytest.fail("Do not touch an existing transport")
|
||||
)
|
||||
assert discovery.refresh("adb") == []
|
||||
assert calls == [["devices"]]
|
||||
|
||||
|
||||
def test_non_adb_port_is_not_connected(discovery, monkeypatch):
|
||||
calls = fake_adb(monkeypatch)
|
||||
monkeypatch.setattr(
|
||||
module, "emulator_listeners", lambda: [["127.0.0.1:23579", "127.0.0.1:16384"]]
|
||||
)
|
||||
monkeypatch.setattr(module, "is_adbd", lambda target, timeout: target.endswith(":16384"))
|
||||
assert discovery.refresh("adb")[0]["success"] is True
|
||||
assert calls == [["devices"], ["connect", "127.0.0.1:16384"], ["devices"]]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("port", [5038, 5040])
|
||||
def test_forwarded_adb_never_discovers_local_devices(discovery, monkeypatch, port):
|
||||
monkeypatch.setattr(
|
||||
module, "current_adb_endpoint", lambda: AdbEndpoint.create("127.0.0.1", port)
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
module.AdbSession,
|
||||
"run",
|
||||
lambda *args, **kwargs: pytest.fail("Remote endpoint must stay untouched"),
|
||||
)
|
||||
assert discovery.refresh("adb", force=True) == []
|
||||
|
||||
|
||||
def test_disabled_discovery_and_concurrent_call_do_not_connect(discovery, monkeypatch):
|
||||
monkeypatch.setattr(settings, "ARTEMIS_ADB_AUTO_CONNECT", False)
|
||||
monkeypatch.setattr(
|
||||
module.AdbSession, "run", lambda *args, **kwargs: pytest.fail("Must not spawn")
|
||||
)
|
||||
assert discovery.refresh("adb") == []
|
||||
monkeypatch.setattr(settings, "ARTEMIS_ADB_AUTO_CONNECT", True)
|
||||
with discovery._gate:
|
||||
assert discovery.refresh("adb") == []
|
||||
|
||||
|
||||
def test_remembered_phone_survives_process_restart_and_offline_peer(
|
||||
discovery, monkeypatch, tmp_path
|
||||
):
|
||||
assert discovery.remember("192.0.2.10:5555")
|
||||
assert discovery.remember("192.0.2.11:5555")
|
||||
second = module.AdbDeviceDiscovery()
|
||||
monkeypatch.setattr(second, "_directory", lambda: tmp_path)
|
||||
calls = fake_adb(monkeypatch, failures={"192.0.2.10:5555"})
|
||||
results = second.refresh("adb")
|
||||
assert len(results) == 2
|
||||
assert any(r["success"] and r["target"] == "192.0.2.11:5555" for r in results)
|
||||
assert len(calls) == 4
|
||||
|
||||
|
||||
def test_total_budget_stops_unlimited_connection_attempts(discovery, monkeypatch):
|
||||
clock = [0.0]
|
||||
monkeypatch.setattr(module.time, "monotonic", lambda: clock[0])
|
||||
monkeypatch.setattr(
|
||||
module, "emulator_listeners", lambda: [[f"127.0.0.1:{16384 + i}"] for i in range(100)]
|
||||
)
|
||||
|
||||
def probe(*args):
|
||||
clock[0] += 1
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(module, "is_adbd", probe)
|
||||
calls = fake_adb(monkeypatch)
|
||||
discovery.refresh("adb")
|
||||
assert len(calls) == 9 # listing plus four connects/readiness checks within 5s
|
||||
|
||||
|
||||
def test_corrupt_persistence_and_missing_process_permissions_are_nonfatal(
|
||||
discovery, monkeypatch, tmp_path
|
||||
):
|
||||
(tmp_path / "broken.json").write_text(json.dumps({"target": "bad"}))
|
||||
assert discovery._remembered() == []
|
||||
fake_adb(monkeypatch)
|
||||
monkeypatch.setattr(
|
||||
module, "emulator_listeners", Mock(side_effect=module.psutil.AccessDenied())
|
||||
)
|
||||
assert discovery.refresh("adb")[0]["success"] is False
|
||||
|
||||
|
||||
def test_listener_permission_failure_still_reconnects_saved_phone(discovery, monkeypatch):
|
||||
assert discovery.remember("192.0.2.10:5555")
|
||||
fake_adb(monkeypatch)
|
||||
monkeypatch.setattr(
|
||||
module, "emulator_listeners", Mock(side_effect=module.psutil.AccessDenied())
|
||||
)
|
||||
results = discovery.refresh("adb")
|
||||
assert results[-1]["target"] == "192.0.2.10:5555"
|
||||
assert results[-1]["success"] is True
|
||||
|
||||
|
||||
def test_localhost_alias_does_not_create_duplicate_transport(discovery, monkeypatch):
|
||||
assert discovery.remember("localhost:16384")
|
||||
calls = fake_adb(monkeypatch, ready="127.0.0.1:16384 device\n")
|
||||
assert discovery.refresh("adb") == []
|
||||
assert calls == [["devices"]]
|
||||
|
||||
|
||||
def test_connect_waits_until_transport_is_visible(monkeypatch):
|
||||
clock = [0.0]
|
||||
monkeypatch.setattr(module.time, "monotonic", lambda: clock[0])
|
||||
monkeypatch.setattr(
|
||||
module.time, "sleep", lambda seconds: clock.__setitem__(0, clock[0] + seconds)
|
||||
)
|
||||
responses = iter(
|
||||
["List of devices attached\n", "127.0.0.1:16384 offline\n", "127.0.0.1:16384 device\n"]
|
||||
)
|
||||
session = Mock()
|
||||
session.run.side_effect = lambda *args, **kwargs: subprocess.CompletedProcess(
|
||||
[], 0, next(responses), ""
|
||||
)
|
||||
assert module.AdbDeviceDiscovery._wait_for_transport(session, "localhost:16384", 1) == "device"
|
||||
assert session.run.call_count == 3
|
||||
|
||||
|
||||
def test_transport_settling_is_bounded(monkeypatch):
|
||||
clock = [0.0]
|
||||
monkeypatch.setattr(module.time, "monotonic", lambda: clock[0])
|
||||
monkeypatch.setattr(
|
||||
module.time, "sleep", lambda seconds: clock.__setitem__(0, clock[0] + seconds)
|
||||
)
|
||||
session = Mock()
|
||||
session.run.return_value = subprocess.CompletedProcess([], 0, "List of devices attached\n", "")
|
||||
assert module.AdbDeviceDiscovery._wait_for_transport(session, "127.0.0.1:16384", 0.2) is None
|
||||
assert clock[0] == 0.2
|
||||
|
||||
|
||||
def test_pending_transport_is_not_reported_as_failed_or_connected(discovery, monkeypatch):
|
||||
fake_adb(monkeypatch)
|
||||
monkeypatch.setattr(
|
||||
module, "emulator_listeners", lambda: [["127.0.0.1:16384", "127.0.0.1:7555"]]
|
||||
)
|
||||
monkeypatch.setattr(module, "is_adbd", lambda *args: True)
|
||||
monkeypatch.setattr(discovery, "_wait_for_transport", lambda *args: None)
|
||||
results = discovery.refresh("adb")
|
||||
assert len(results) == 1
|
||||
assert results[0]["pending"] is True
|
||||
assert results[0]["success"] is False
|
||||
assert "等待设备就绪" in results[0]["message"]
|
||||
@@ -93,6 +93,7 @@ def test_ensure_daemon_running_standalone_override(monkeypatch):
|
||||
def test_ensure_daemon_running_auto_spawns():
|
||||
with (
|
||||
patch("artemis.runtime.daemon_client.is_daemon_running", side_effect=[False, True]),
|
||||
patch("artemis.runtime.daemon_client.is_port_in_use", return_value=False),
|
||||
patch("artemis.runtime.daemon_client.spawn_daemon") as mock_spawn,
|
||||
):
|
||||
ok, base_url = ensure_daemon_running(timeout=1.0, wait_ready=True)
|
||||
@@ -101,6 +102,42 @@ def test_ensure_daemon_running_auto_spawns():
|
||||
mock_spawn.assert_called_once()
|
||||
|
||||
|
||||
def test_busy_live_daemon_is_reused_without_spawning():
|
||||
with (
|
||||
patch("artemis.runtime.daemon_client.is_daemon_running", return_value=False),
|
||||
patch("artemis.runtime.daemon_client.is_port_in_use", return_value=True),
|
||||
patch(
|
||||
"artemis.runtime.daemon_client.read_server_info",
|
||||
return_value={"host": "127.0.0.1", "port": 8000, "pid": 12345},
|
||||
),
|
||||
patch("artemis.runtime.daemon_client.pid_is_alive", return_value=True),
|
||||
patch("artemis.runtime.daemon_client.spawn_daemon") as spawn,
|
||||
):
|
||||
assert ensure_daemon_running() == (True, "http://127.0.0.1:8000")
|
||||
spawn.assert_not_called()
|
||||
|
||||
|
||||
def test_unknown_port_owner_is_not_overwritten():
|
||||
with (
|
||||
patch("artemis.runtime.daemon_client.is_daemon_running", return_value=False),
|
||||
patch("artemis.runtime.daemon_client.is_port_in_use", return_value=True),
|
||||
patch("artemis.runtime.daemon_client.read_server_info", return_value=None),
|
||||
patch("artemis.runtime.daemon_client.spawn_daemon") as spawn,
|
||||
):
|
||||
assert ensure_daemon_running() == (False, None)
|
||||
spawn.assert_not_called()
|
||||
|
||||
|
||||
def test_liveness_probe_uses_lightweight_endpoint_and_configured_timeout(monkeypatch):
|
||||
from artemis.config.settings import settings
|
||||
|
||||
monkeypatch.setattr(settings, "ARTEMIS_DAEMON_PROBE_TIMEOUT_SECONDS", 7.0)
|
||||
with patch("urllib.request.urlopen", return_value=_daemon_ok_response(b"{}")) as probe:
|
||||
assert is_daemon_running()
|
||||
assert probe.call_args.args[0].full_url.endswith("/api/system/server-status")
|
||||
assert probe.call_args.kwargs["timeout"] == 7.0
|
||||
|
||||
|
||||
def test_submit_task_to_daemon():
|
||||
mock_resp = MagicMock()
|
||||
mock_resp.status = 200
|
||||
|
||||
@@ -20,6 +20,7 @@ import pytest
|
||||
|
||||
from artemis.runtime.device_lock import DeviceExecutionLock
|
||||
from artemis.runtime.device_pool import DevicePool, DeviceStatus
|
||||
from artemis.config import settings
|
||||
|
||||
device_pool_module = importlib.import_module("artemis.runtime.device_pool")
|
||||
|
||||
@@ -245,6 +246,45 @@ def test_warm_up_without_adb_returns_false(monkeypatch):
|
||||
assert asyncio.run(pool.warm_up_async(settle_timeout=0.0)) is False
|
||||
|
||||
|
||||
def test_adb_warmup_does_not_start_local_server_for_remote_endpoint(monkeypatch):
|
||||
monkeypatch.setattr(settings, "ADB_HOST", "127.0.0.1")
|
||||
monkeypatch.setattr(settings, "ADB_PORT", 5038)
|
||||
|
||||
async def unexpected_spawn(*args, **kwargs):
|
||||
pytest.fail("A forwarded endpoint must not start a local ADB daemon")
|
||||
|
||||
monkeypatch.setattr(asyncio, "create_subprocess_exec", unexpected_spawn)
|
||||
asyncio.run(DevicePool(adb_path="adb")._start_adb_server(timeout=1.0))
|
||||
|
||||
|
||||
def test_adb_warmup_reports_failed_start_with_local_command(monkeypatch):
|
||||
monkeypatch.setattr(settings, "ADB_HOST", "127.0.0.1")
|
||||
monkeypatch.setattr(settings, "ADB_PORT", 5037)
|
||||
monkeypatch.setenv("ADB_SERVER_SOCKET", "tcp:remote.example:5040")
|
||||
captured = {}
|
||||
warnings = []
|
||||
|
||||
class FailedProcess:
|
||||
returncode = 1
|
||||
|
||||
async def communicate(self):
|
||||
return b"", b"cannot bind listener"
|
||||
|
||||
async def spawn(*args, **kwargs):
|
||||
captured["command"] = args
|
||||
captured["env"] = kwargs["env"]
|
||||
return FailedProcess()
|
||||
|
||||
monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn)
|
||||
monkeypatch.setattr(device_pool_module.logger, "warning", warnings.append)
|
||||
asyncio.run(DevicePool(adb_path="adb")._start_adb_server(timeout=1.0))
|
||||
assert captured["command"] == ("adb", "-H", "localhost", "-P", "5037", "start-server")
|
||||
assert captured["env"]["ADB_SERVER_SOCKET"] == "tcp:localhost:5037"
|
||||
assert len(warnings) == 1
|
||||
assert "exit 1" in warnings[0]
|
||||
assert "cannot bind listener" in warnings[0]
|
||||
|
||||
|
||||
def test_try_list_devices_distinguishes_failure_from_empty(monkeypatch):
|
||||
pool = DevicePool()
|
||||
monkeypatch.setattr(pool, "_query_adb_devices_sync", lambda timeout=None: None)
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Run just the ADB startup functions with fake commands; never touch host ADB."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not shutil.which("powershell.exe"), reason="Windows PowerShell required")
|
||||
@pytest.mark.parametrize("script_name", ["start.ps1", "install_deps.ps1"])
|
||||
@pytest.mark.parametrize("outcome", ["success", "failure", "exception"])
|
||||
def test_adb_startup_reports_failure_and_preserves_server_environment(
|
||||
tmp_path, script_name, outcome
|
||||
):
|
||||
harness = tmp_path / "adb-startup.ps1"
|
||||
harness.write_text(
|
||||
"""
|
||||
$ErrorActionPreference = 'Stop'
|
||||
[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
|
||||
$tokens = $null
|
||||
$parseErrors = $null
|
||||
$ast = [System.Management.Automation.Language.Parser]::ParseFile(
|
||||
$env:ADB_TEST_SCRIPT, [ref]$tokens, [ref]$parseErrors)
|
||||
if ($parseErrors.Count) { throw ($parseErrors | Out-String) }
|
||||
$function = $ast.Find({ param($node)
|
||||
$node -is [System.Management.Automation.Language.FunctionDefinitionAst] -and
|
||||
$node.Name -eq 'Start-LocalAdbServer'
|
||||
}, $true)
|
||||
Invoke-Expression $function.Extent.Text
|
||||
function Test-CommandExists { return $true }
|
||||
function adb {
|
||||
Write-Host ('ADB_ARGS=' + ($args -join '|'))
|
||||
if ($env:ADB_TEST_OUTCOME -eq 'exception') { throw 'fixture launch error' }
|
||||
Write-Error 'fixture stderr' -ErrorAction Continue
|
||||
$global:LASTEXITCODE = $(if ($env:ADB_TEST_OUTCOME -eq 'failure') { 7 } else { 0 })
|
||||
}
|
||||
Start-LocalAdbServer
|
||||
if ($env:ADB_SERVER_SOCKET -ne 'tcp:remote.example:5040') { throw 'Socket was changed' }
|
||||
if ($env:ANDROID_ADB_SERVER_ADDRESS -ne 'remote.example') { throw 'Host was changed' }
|
||||
if ($env:ANDROID_ADB_SERVER_PORT -ne '5040') { throw 'Port was changed' }
|
||||
if ($ErrorActionPreference -ne 'Stop') { throw 'Error preference was changed' }
|
||||
Write-Host 'HARNESS_OK'
|
||||
""",
|
||||
encoding="utf-8-sig",
|
||||
)
|
||||
result = subprocess.run(
|
||||
["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(harness)],
|
||||
env={
|
||||
**os.environ,
|
||||
"ADB_TEST_SCRIPT": str(ROOT / "scripts" / script_name),
|
||||
"ADB_TEST_OUTCOME": outcome,
|
||||
"ADB_SERVER_SOCKET": "tcp:remote.example:5040",
|
||||
"ANDROID_ADB_SERVER_ADDRESS": "remote.example",
|
||||
"ANDROID_ADB_SERVER_PORT": "5040",
|
||||
},
|
||||
capture_output=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
timeout=15,
|
||||
)
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
assert "ADB_ARGS=-H|localhost|-P|5037|start-server" in result.stdout
|
||||
assert "HARNESS_OK" in result.stdout
|
||||
if outcome == "success":
|
||||
assert "[警告]" not in result.stdout
|
||||
elif outcome == "failure":
|
||||
assert "退出码 7" in result.stdout
|
||||
assert "fixture stderr" in result.stdout
|
||||
else:
|
||||
assert "启动异常" in result.stdout
|
||||
assert "fixture launch error" in result.stdout
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Exercise CMD parsing and Windows PowerShell 5.1 without installing anything."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not shutil.which("cmd.exe") or not shutil.which("powershell.exe"),
|
||||
reason="Windows CMD and Windows PowerShell required",
|
||||
)
|
||||
|
||||
|
||||
def copy_launchers(root: Path, newline: bytes) -> None:
|
||||
root.mkdir()
|
||||
(root / "scripts").mkdir()
|
||||
for name in ("start.bat", "start-cn.bat"):
|
||||
content = (ROOT / name).read_bytes().replace(b"\r\n", b"\n")
|
||||
# ASCII batch wrappers remain safe even if a zip/editor changes EOLs.
|
||||
content.decode("ascii")
|
||||
(root / name).write_bytes(content.replace(b"\n", newline))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("newline", [b"\r\n", b"\n"])
|
||||
@pytest.mark.parametrize("exit_code", [0, 7])
|
||||
def test_launch_forwards_options_and_exit_code_without_cmd_garbling(tmp_path, newline, exit_code):
|
||||
root = tmp_path / "source with spaces"
|
||||
copy_launchers(root, newline)
|
||||
(root / "scripts" / "start.ps1").write_text(
|
||||
"""param([string]$Mirror, [int]$Port, [switch]$NoOpen, [switch]$SkipUpdate, [switch]$SkipMcpSync)
|
||||
[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
|
||||
Write-Host '镜像地址和下载超时可在 config\\downloads.json 中调整。'
|
||||
Write-Host ('ARGS=' + (@{mirror=$Mirror;port=$Port;no_open=[bool]$NoOpen;skip_update=[bool]$SkipUpdate;skip_mcp=[bool]$SkipMcpSync;language=$env:ARTEMIS_LAUNCH_LANG} | ConvertTo-Json -Compress))
|
||||
exit ([int]$env:LAUNCH_TEST_EXIT)
|
||||
""",
|
||||
encoding="utf-8-sig",
|
||||
)
|
||||
result = subprocess.run(
|
||||
[
|
||||
"cmd.exe",
|
||||
"/d",
|
||||
"/c",
|
||||
"start-cn.bat",
|
||||
"-Port",
|
||||
"8123",
|
||||
"-NoOpen",
|
||||
"-SkipUpdate",
|
||||
"-SkipMcpSync",
|
||||
],
|
||||
cwd=root,
|
||||
env={**os.environ, "ARTEMIS_NO_PAUSE": "1", "LAUNCH_TEST_EXIT": str(exit_code)},
|
||||
capture_output=True,
|
||||
encoding="utf-8",
|
||||
timeout=15,
|
||||
)
|
||||
assert result.returncode == exit_code, result.stdout + result.stderr
|
||||
assert result.stderr == ""
|
||||
assert "镜像地址和下载超时可在" in result.stdout
|
||||
args = json.loads(
|
||||
next(
|
||||
line.removeprefix("ARGS=")
|
||||
for line in result.stdout.splitlines()
|
||||
if line.startswith("ARGS=")
|
||||
)
|
||||
)
|
||||
assert args == {
|
||||
"mirror": "China",
|
||||
"port": 8123,
|
||||
"no_open": True,
|
||||
"skip_update": True,
|
||||
"skip_mcp": True,
|
||||
"language": "zh-CN",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("newline", [b"\r\n", b"\n"])
|
||||
@pytest.mark.parametrize("help_flag", ["-Help", "--help"])
|
||||
def test_actual_chinese_help_has_no_encoding_error_or_bootstrap(tmp_path, newline, help_flag):
|
||||
root = tmp_path / "source with spaces"
|
||||
copy_launchers(root, newline)
|
||||
shutil.copyfile(ROOT / "scripts" / "start.ps1", root / "scripts" / "start.ps1")
|
||||
assert (root / "scripts" / "start.ps1").read_bytes().startswith(b"\xef\xbb\xbf")
|
||||
result = subprocess.run(
|
||||
["cmd.exe", "/d", "/c", "start-cn.bat", help_flag],
|
||||
cwd=root,
|
||||
capture_output=True,
|
||||
encoding="utf-8",
|
||||
timeout=15,
|
||||
)
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
assert result.stderr == ""
|
||||
assert "用法:start-cn.bat [选项]" in result.stdout
|
||||
assert "仅启动网页,跳过 Codex MCP" in result.stdout
|
||||
assert "国内镜像设置:config\\downloads.json" in result.stdout
|
||||
assert "�" not in result.stdout
|
||||
assert not (root / ".venv").exists()
|
||||
|
||||
|
||||
def test_batch_files_are_ascii_and_powershell_text_has_bom():
|
||||
for name in ("start.bat", "start-cn.bat"):
|
||||
(ROOT / name).read_bytes().decode("ascii")
|
||||
assert (ROOT / "scripts" / "start.ps1").read_bytes().startswith(b"\xef\xbb\xbf")
|
||||
+37
-291
@@ -14,6 +14,8 @@
|
||||
|
||||
"""Unit tests for ARTEMIS Unified CLI application."""
|
||||
|
||||
import pytest
|
||||
|
||||
from typer.testing import CliRunner
|
||||
from artemis.interfaces.cli.main import app
|
||||
|
||||
@@ -169,56 +171,41 @@ def test_cli_mcp_help():
|
||||
assert "--generate-config" in result.output
|
||||
|
||||
|
||||
def test_cli_mcp_generate_config():
|
||||
"""Verify 'artemis mcp --generate-config cursor' produces valid configuration."""
|
||||
result = runner.invoke(app, ["mcp", "--generate-config", "cursor"])
|
||||
assert result.exit_code == 0
|
||||
assert "mcpServers" in result.output
|
||||
assert "mcp_server" in result.output
|
||||
|
||||
|
||||
def test_cli_mcp_generate_config_antigravity():
|
||||
"""Verify current Antigravity uses only documented, load-safe fields."""
|
||||
from artemis.interfaces.cli.commands.mcp import _get_config_snippet
|
||||
|
||||
result = runner.invoke(app, ["mcp", "--generate-config", "antigravity"])
|
||||
assert result.exit_code == 0
|
||||
assert "mcpServers" in result.output
|
||||
server_config = _get_config_snippet("antigravity", "python", "/project")["mcpServers"][
|
||||
"artemis"
|
||||
]
|
||||
assert server_config["disabledTools"] == []
|
||||
assert "tools" not in server_config
|
||||
|
||||
legacy_config = _get_config_snippet("jetski", "python", "/project")["mcpServers"]["artemis"]
|
||||
assert set(legacy_config["tools"]) == {
|
||||
"mobile_run_task",
|
||||
"mobile_manage_task",
|
||||
"mobile_get_device_state",
|
||||
"mobile_inspect_trace",
|
||||
"mobile_diagnose",
|
||||
"mobile_workspace",
|
||||
"mobile_config",
|
||||
"mobile_task_file",
|
||||
"mobile_batch",
|
||||
"mobile_search_history",
|
||||
"mobile_export_report",
|
||||
}
|
||||
assert all(tool["eager"] is True for tool in legacy_config["tools"].values())
|
||||
|
||||
|
||||
def test_cli_mcp_generate_config_all():
|
||||
"""Verify 'artemis mcp --generate-config all' includes every supported client."""
|
||||
result = runner.invoke(app, ["mcp", "--generate-config", "all"])
|
||||
assert result.exit_code == 0
|
||||
assert "antigravity" in result.output
|
||||
assert "cursor" in result.output
|
||||
assert "windsurf" in result.output
|
||||
assert "claude" in result.output
|
||||
assert "vscode" in result.output
|
||||
assert "cline" in result.output
|
||||
assert "roo" in result.output
|
||||
assert "codex" in result.output
|
||||
@pytest.mark.parametrize("option", ["--install", "--generate-config"])
|
||||
@pytest.mark.parametrize(
|
||||
"client",
|
||||
[
|
||||
"cursor",
|
||||
"vscode",
|
||||
"claude",
|
||||
"claude_code",
|
||||
"claude_desktop",
|
||||
"antigravity",
|
||||
"jetski",
|
||||
"windsurf",
|
||||
"cline",
|
||||
"roo",
|
||||
"roo_code",
|
||||
"openclaw",
|
||||
"all",
|
||||
],
|
||||
)
|
||||
def test_cli_mcp_rejects_other_clients_without_modifying_files(
|
||||
tmp_path, monkeypatch, option, client
|
||||
):
|
||||
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
|
||||
monkeypatch.setenv("CODEX_HOME", str(tmp_path / ".codex"))
|
||||
monkeypatch.setenv("APPDATA", str(tmp_path / "AppData/Roaming"))
|
||||
monkeypatch.setattr("mcp_server.utils.env_utils.get_project_root", lambda: str(tmp_path))
|
||||
sentinel = tmp_path / ".cursor/mcp.json"
|
||||
sentinel.parent.mkdir()
|
||||
sentinel.write_bytes(b"{invalid json with user data}")
|
||||
before = {p.relative_to(tmp_path): p.read_bytes() for p in tmp_path.rglob("*") if p.is_file()}
|
||||
result = runner.invoke(app, ["mcp", option, client])
|
||||
assert result.exit_code == 1
|
||||
assert "Codex" in result.output
|
||||
after = {p.relative_to(tmp_path): p.read_bytes() for p in tmp_path.rglob("*") if p.is_file()}
|
||||
assert after == before
|
||||
|
||||
|
||||
def test_cli_mcp_generate_config_codex():
|
||||
@@ -251,165 +238,6 @@ def test_cli_mcp_generate_config_codex():
|
||||
]
|
||||
|
||||
|
||||
def test_cli_mcp_install_antigravity(tmp_path, monkeypatch):
|
||||
"""Verify 'artemis mcp --install antigravity' writes configuration and global rules into target files."""
|
||||
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
|
||||
monkeypatch.setattr("mcp_server.utils.env_utils.get_project_root", lambda: str(tmp_path))
|
||||
result = runner.invoke(app, ["mcp", "--install", "antigravity"])
|
||||
assert result.exit_code == 0
|
||||
assert "Successfully installed ARTEMIS MCP server configuration & rules" in result.output
|
||||
jetski_file = tmp_path / ".gemini" / "jetski" / "mcp_config.json"
|
||||
assert jetski_file.exists()
|
||||
import json
|
||||
|
||||
data = json.loads(jetski_file.read_text())
|
||||
assert "artemis" in data["mcpServers"]
|
||||
assert "mobile_run_task" in data["mcpServers"]["artemis"]["tools"]
|
||||
assert "PYTHONPATH" in data["mcpServers"]["artemis"]["env"]
|
||||
|
||||
current_file = tmp_path / ".gemini" / "config" / "mcp_config.json"
|
||||
current_data = json.loads(current_file.read_text())
|
||||
assert current_data["mcpServers"]["artemis"]["disabledTools"] == []
|
||||
assert "tools" not in current_data["mcpServers"]["artemis"]
|
||||
|
||||
# Verify global rule file installed
|
||||
gemini_md = tmp_path / ".gemini" / "GEMINI.md"
|
||||
assert gemini_md.exists()
|
||||
assert "Mobile Testing Mindset" in gemini_md.read_text(encoding="utf-8")
|
||||
rule_file = tmp_path / ".gemini" / "rules" / "artemis.md"
|
||||
assert rule_file.exists()
|
||||
assert "Mobile Testing Mindset" in rule_file.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_cli_mcp_install_all(tmp_path, monkeypatch):
|
||||
"""Verify 'artemis mcp --install all' installs configs and global rules to all supported IDE locations."""
|
||||
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
|
||||
monkeypatch.setenv("APPDATA", str(tmp_path / "AppData" / "Roaming"))
|
||||
monkeypatch.setattr("mcp_server.utils.env_utils.get_project_root", lambda: str(tmp_path))
|
||||
result = runner.invoke(app, ["mcp", "--install", "all"])
|
||||
assert result.exit_code == 0
|
||||
assert "Successfully installed ARTEMIS MCP server configuration & rules" in result.output
|
||||
assert (tmp_path / ".cursor" / "mcp.json").exists()
|
||||
assert (tmp_path / ".codeium" / "windsurf" / "mcp_config.json").exists()
|
||||
assert (tmp_path / ".openclaw" / "openclaw.json").exists()
|
||||
assert (tmp_path / ".claude.json").exists()
|
||||
assert (tmp_path / ".codex" / "config.toml").exists()
|
||||
|
||||
import json
|
||||
|
||||
cursor_data = json.loads((tmp_path / ".cursor" / "mcp.json").read_text())
|
||||
assert cursor_data["mcpServers"]["artemis"]["command"]
|
||||
|
||||
windsurf_data = json.loads((tmp_path / ".codeium" / "windsurf" / "mcp_config.json").read_text())
|
||||
assert windsurf_data["mcpServers"]["artemis"]["command"]
|
||||
|
||||
claude_data = json.loads((tmp_path / ".claude.json").read_text())
|
||||
assert claude_data["mcpServers"]["artemis"]["type"] == "stdio"
|
||||
|
||||
from artemis.interfaces.cli.commands.mcp import _get_vscode_user_dir
|
||||
|
||||
vscode_data = json.loads((_get_vscode_user_dir() / "mcp.json").read_text())
|
||||
assert vscode_data["servers"]["artemis"]["type"] == "stdio"
|
||||
assert "mcpServers" not in vscode_data
|
||||
|
||||
copilot_data = json.loads((tmp_path / ".copilot" / "mcp-config.json").read_text())
|
||||
assert copilot_data["servers"]["artemis"]["type"] == "stdio"
|
||||
|
||||
openclaw_data = json.loads((tmp_path / ".openclaw" / "openclaw.json").read_text())
|
||||
assert openclaw_data["mcp"]["servers"]["artemis"]["enabled"] is True
|
||||
|
||||
cline_data = json.loads(
|
||||
(tmp_path / ".cline" / "data" / "settings" / "cline_mcp_settings.json").read_text()
|
||||
)
|
||||
assert cline_data["mcpServers"]["artemis"]["disabled"] is False
|
||||
|
||||
roo_data = json.loads((tmp_path / ".roo" / "mcp.json").read_text())
|
||||
assert roo_data["mcpServers"]["artemis"]["disabled"] is False
|
||||
|
||||
# Verify global rule files installed across IDEs
|
||||
assert (tmp_path / ".gemini" / "GEMINI.md").exists()
|
||||
assert (tmp_path / ".gemini" / "rules" / "artemis.md").exists()
|
||||
assert (tmp_path / ".cursorrules").exists()
|
||||
assert (tmp_path / ".cursor" / "rules" / "artemis.mdc").exists()
|
||||
# Claude Code loads both CLAUDE.md and rules/*.md, so rules are installed
|
||||
# only as the standalone rule file to avoid duplicated context.
|
||||
assert not (tmp_path / ".claude" / "CLAUDE.md").exists()
|
||||
assert (tmp_path / ".claude" / "rules" / "artemis.md").exists()
|
||||
assert (tmp_path / ".codeium" / "windsurf" / "memories" / "global_rules.md").exists()
|
||||
assert (tmp_path / ".codeium" / "windsurf" / "rules" / "artemis.md").exists()
|
||||
assert (tmp_path / ".vscode" / "rules" / "artemis.md").exists()
|
||||
assert (tmp_path / ".clinerules").exists()
|
||||
assert (tmp_path / ".cline" / "rules" / "artemis.md").exists()
|
||||
assert (tmp_path / ".roorules").exists()
|
||||
assert (tmp_path / ".roo" / "rules" / "artemis.md").exists()
|
||||
assert (tmp_path / ".openclaw" / "OPENCLAW.md").exists()
|
||||
assert (tmp_path / ".openclaw" / "rules" / "artemis.md").exists()
|
||||
assert (tmp_path / ".codex" / "AGENTS.md").exists()
|
||||
|
||||
|
||||
def test_cli_mcp_install_claude_migrates_legacy_claude_md(tmp_path, monkeypatch):
|
||||
"""Verify the claude target removes a previously injected CLAUDE.md block while preserving user content."""
|
||||
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
|
||||
monkeypatch.setenv("APPDATA", str(tmp_path / "AppData" / "Roaming"))
|
||||
monkeypatch.setattr("mcp_server.utils.env_utils.get_project_root", lambda: str(tmp_path))
|
||||
|
||||
claude_dir = tmp_path / ".claude"
|
||||
claude_dir.mkdir(parents=True)
|
||||
claude_md = claude_dir / "CLAUDE.md"
|
||||
claude_md.write_text(
|
||||
"# My own instructions\n\n"
|
||||
"<!-- BEGIN ARTEMIS MOBILE TESTING RULES -->\nold injected rules\n"
|
||||
"<!-- END ARTEMIS MOBILE TESTING RULES -->\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
result = runner.invoke(app, ["mcp", "--install", "claude"])
|
||||
assert result.exit_code == 0
|
||||
|
||||
remaining = claude_md.read_text(encoding="utf-8")
|
||||
assert "My own instructions" in remaining
|
||||
assert "ARTEMIS MOBILE TESTING RULES" not in remaining
|
||||
rule_file = claude_dir / "rules" / "artemis.md"
|
||||
assert rule_file.exists()
|
||||
assert "Mobile Testing Mindset" in rule_file.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_cli_mcp_install_claude_deletes_block_only_claude_md(tmp_path, monkeypatch):
|
||||
"""Verify a CLAUDE.md consisting solely of the injected block is deleted outright."""
|
||||
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
|
||||
monkeypatch.setenv("APPDATA", str(tmp_path / "AppData" / "Roaming"))
|
||||
monkeypatch.setattr("mcp_server.utils.env_utils.get_project_root", lambda: str(tmp_path))
|
||||
|
||||
claude_dir = tmp_path / ".claude"
|
||||
claude_dir.mkdir(parents=True)
|
||||
claude_md = claude_dir / "CLAUDE.md"
|
||||
claude_md.write_text(
|
||||
"<!-- BEGIN ARTEMIS MOBILE TESTING RULES -->\nold injected rules\n"
|
||||
"<!-- END ARTEMIS MOBILE TESTING RULES -->\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
result = runner.invoke(app, ["mcp", "--install", "claude"])
|
||||
assert result.exit_code == 0
|
||||
assert not claude_md.exists()
|
||||
assert (claude_dir / "rules" / "artemis.md").exists()
|
||||
|
||||
|
||||
def test_cli_mcp_install_claude_refuses_unparseable_claude_json(tmp_path, monkeypatch):
|
||||
"""Verify an unparseable ~/.claude.json is left untouched instead of being rewritten."""
|
||||
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
|
||||
monkeypatch.setenv("APPDATA", str(tmp_path / "AppData" / "Roaming"))
|
||||
monkeypatch.setattr("mcp_server.utils.env_utils.get_project_root", lambda: str(tmp_path))
|
||||
|
||||
corrupt = "{ this is not json at all"
|
||||
claude_json = tmp_path / ".claude.json"
|
||||
claude_json.write_text(corrupt, encoding="utf-8")
|
||||
|
||||
result = runner.invoke(app, ["mcp", "--install", "claude"])
|
||||
assert result.exit_code == 0
|
||||
assert claude_json.read_text(encoding="utf-8") == corrupt
|
||||
|
||||
|
||||
def test_cli_mcp_install_codex_preserves_config_and_is_idempotent(tmp_path, monkeypatch):
|
||||
"""Verify Codex TOML merging preserves other servers and updates only Artemis."""
|
||||
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
|
||||
@@ -461,88 +289,6 @@ def test_cli_mcp_install_codex_preserves_config_and_is_idempotent(tmp_path, monk
|
||||
assert agents_text.count("<!-- BEGIN ARTEMIS MOBILE TESTING RULES -->") == 1
|
||||
|
||||
|
||||
def test_cli_mcp_install_jsonc_and_backup(tmp_path, monkeypatch):
|
||||
"""Verify merging configuration preserves valid JSONC and creates .bak for unparseable JSON."""
|
||||
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
|
||||
monkeypatch.setattr("mcp_server.utils.env_utils.get_project_root", lambda: str(tmp_path))
|
||||
|
||||
cursor_dir = tmp_path / ".cursor"
|
||||
cursor_dir.mkdir(parents=True, exist_ok=True)
|
||||
mcp_json = cursor_dir / "mcp.json"
|
||||
|
||||
# 1. Valid JSONC with comments and trailing comma
|
||||
mcp_json.write_text(
|
||||
'{\n // My existing server\n "mcpServers": {\n "test": {"command": "echo"},\n }\n}',
|
||||
encoding="utf-8",
|
||||
)
|
||||
result = runner.invoke(app, ["mcp", "--install", "cursor"])
|
||||
assert result.exit_code == 0
|
||||
import json
|
||||
|
||||
data = json.loads(mcp_json.read_text(encoding="utf-8"))
|
||||
assert "test" in data["mcpServers"]
|
||||
assert "artemis" in data["mcpServers"]
|
||||
|
||||
# 2. Corrupt / unparseable file triggers backup
|
||||
mcp_json.write_text("INVALID JSON DATA {{{{", encoding="utf-8")
|
||||
result2 = runner.invoke(app, ["mcp", "--install", "cursor"])
|
||||
assert result2.exit_code == 0
|
||||
backup_file = cursor_dir / "mcp.json.bak"
|
||||
assert backup_file.exists()
|
||||
assert "INVALID JSON DATA" in backup_file.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_cli_mcp_install_refuses_rewrite_when_backup_fails(tmp_path, monkeypatch):
|
||||
"""Backup failure for an unparseable config must abort the rewrite instead of destroying it."""
|
||||
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
|
||||
monkeypatch.setattr("mcp_server.utils.env_utils.get_project_root", lambda: str(tmp_path))
|
||||
|
||||
cursor_dir = tmp_path / ".cursor"
|
||||
cursor_dir.mkdir(parents=True, exist_ok=True)
|
||||
mcp_json = cursor_dir / "mcp.json"
|
||||
original = "INVALID JSON DATA {{{{"
|
||||
mcp_json.write_text(original, encoding="utf-8")
|
||||
|
||||
import pathlib
|
||||
|
||||
real_write_text = pathlib.Path.write_text
|
||||
|
||||
def failing_bak_write(self, *args, **kwargs):
|
||||
if str(self).endswith(".bak"):
|
||||
raise OSError("disk full")
|
||||
return real_write_text(self, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr("pathlib.Path.write_text", failing_bak_write)
|
||||
|
||||
runner.invoke(app, ["mcp", "--install", "cursor"])
|
||||
|
||||
assert mcp_json.read_text(encoding="utf-8") == original
|
||||
assert not (cursor_dir / "mcp.json.bak").exists()
|
||||
|
||||
|
||||
def test_cli_mcp_install_openclaw_migrates_legacy_plugin_shape(tmp_path, monkeypatch):
|
||||
"""Verify reinstalling OpenClaw replaces the obsolete plugin wrapper with mcp.servers."""
|
||||
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
|
||||
monkeypatch.setattr("mcp_server.utils.env_utils.get_project_root", lambda: str(tmp_path))
|
||||
config_path = tmp_path / ".openclaw" / "openclaw.json"
|
||||
config_path.parent.mkdir(parents=True)
|
||||
config_path.write_text(
|
||||
'{"plugins":{"artemis_mcp":{"enabled":true},"keep":{"enabled":true}}}',
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
result = runner.invoke(app, ["mcp", "--install", "openclaw"])
|
||||
assert result.exit_code == 0
|
||||
|
||||
import json
|
||||
|
||||
data = json.loads(config_path.read_text(encoding="utf-8"))
|
||||
assert "artemis_mcp" not in data["plugins"]
|
||||
assert data["plugins"]["keep"]["enabled"] is True
|
||||
assert data["mcp"]["servers"]["artemis"]["enabled"] is True
|
||||
assert data["mcp"]["servers"]["artemis"]["command"]
|
||||
|
||||
|
||||
def test_cli_restart_help():
|
||||
"""Verify 'artemis restart --help' displays lifecycle options."""
|
||||
result = runner.invoke(app, ["restart", "--help"])
|
||||
|
||||
@@ -14,7 +14,9 @@
|
||||
|
||||
"""Unit tests for Unified Base Device Driver and implementations."""
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import threading
|
||||
from io import BytesIO
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
@@ -36,6 +38,48 @@ _ONE_PIXEL_PNG = base64.b64encode(
|
||||
).decode("ascii")
|
||||
|
||||
|
||||
def _valid_png():
|
||||
buffer = BytesIO()
|
||||
Image.new("RGB", (64, 64), "white").save(buffer, format="PNG")
|
||||
return base64.b64encode(buffer.getvalue()).decode("ascii")
|
||||
|
||||
|
||||
_VALID_PNG = _valid_png()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_android_driver_rejects_placeholder_without_returning_stale_screen():
|
||||
client = MagicMock()
|
||||
client.get_screen_data.return_value = SimpleNamespace(base64=_ONE_PIXEL_PNG)
|
||||
driver = AndroidAdbDriver("test-device", MagicMock(), ui_adb_client=client)
|
||||
with pytest.raises(RuntimeError, match="占位图"):
|
||||
await driver.get_screen_data(skip_settling=True)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_screen_capture_timeout_does_not_start_overlapping_sdk_calls(monkeypatch):
|
||||
released = threading.Event()
|
||||
client = MagicMock()
|
||||
|
||||
def blocked_capture():
|
||||
released.wait(2)
|
||||
return SimpleNamespace(base64=_VALID_PNG, width=64, height=64, elements=[])
|
||||
|
||||
client.get_screen_data.side_effect = blocked_capture
|
||||
driver = AndroidAdbDriver("test-device", MagicMock(), ui_adb_client=client)
|
||||
monkeypatch.setattr(
|
||||
"artemis.drivers.android.adb_driver.settings.ARTEMIS_OBSERVATION_TIMEOUT_SECONDS", 0.02
|
||||
)
|
||||
try:
|
||||
for _ in range(3):
|
||||
with pytest.raises(TimeoutError, match="观测超时"):
|
||||
await driver.get_screen_data(skip_settling=True)
|
||||
assert client.get_screen_data.call_count == 1
|
||||
finally:
|
||||
released.set()
|
||||
await asyncio.wait_for(driver._screen_capture_task, 2)
|
||||
|
||||
|
||||
def test_screenshot_limit_keeps_small_and_invalid_images_unchanged():
|
||||
small_image = base64.b64decode(_ONE_PIXEL_PNG)
|
||||
assert limit_screenshot_long_edge(small_image, 2048) is small_image
|
||||
@@ -100,16 +144,16 @@ async def test_android_driver_with_mock_adb():
|
||||
|
||||
# Test tap
|
||||
await driver.tap(540, 1200)
|
||||
mock_adb_device.shell.assert_called_with("input tap 540 1200")
|
||||
mock_adb_device.shell.assert_called_with("input tap 540 1200", timeout=10.0)
|
||||
|
||||
# Test multi-tap
|
||||
await driver.tap(540, 1200, times=3, delay_ms=100)
|
||||
expected_multi = "input tap 540 1200 && sleep 0.100 && input tap 540 1200 && sleep 0.100 && input tap 540 1200"
|
||||
mock_adb_device.shell.assert_called_with(expected_multi)
|
||||
mock_adb_device.shell.assert_called_with(expected_multi, timeout=10.0)
|
||||
|
||||
# Test press key
|
||||
await driver.press_key(KeyCode.BACK)
|
||||
mock_adb_device.shell.assert_called_with("input keyevent 4")
|
||||
mock_adb_device.shell.assert_called_with("input keyevent 4", timeout=10.0)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -132,7 +176,7 @@ async def test_android_driver_preserves_elements_from_combined_screen_data():
|
||||
},
|
||||
]
|
||||
mock_ui_client.get_screen_data.return_value = SimpleNamespace(
|
||||
base64=_ONE_PIXEL_PNG,
|
||||
base64=_VALID_PNG,
|
||||
hierarchy_xml="<hierarchy />",
|
||||
elements=expected_elements,
|
||||
width=1080,
|
||||
@@ -188,7 +232,7 @@ async def test_android_driver_parses_xml_hierarchy_fallback():
|
||||
mock_adb_client = MagicMock()
|
||||
mock_ui_client = MagicMock()
|
||||
mock_ui_client.get_screen_data.return_value = SimpleNamespace(
|
||||
base64=_ONE_PIXEL_PNG,
|
||||
base64=_VALID_PNG,
|
||||
width=1080,
|
||||
height=2400,
|
||||
)
|
||||
@@ -216,7 +260,7 @@ async def test_find_element_prefers_fresh_bounds_over_stale_center():
|
||||
driver.get_screen_data = AsyncMock(
|
||||
return_value=ScreenData(
|
||||
screenshot_bytes=base64.b64decode(_ONE_PIXEL_PNG),
|
||||
screenshot_base64=_ONE_PIXEL_PNG,
|
||||
screenshot_base64=_VALID_PNG,
|
||||
ui_elements=[
|
||||
{
|
||||
"resource_id": "app:id/digit_4",
|
||||
|
||||
@@ -53,18 +53,18 @@ def repos(tmp_path):
|
||||
|
||||
def test_fast_forward_update_preserves_env_and_is_repeatable(repos):
|
||||
installed, author = repos
|
||||
assert update.update_source(installed, port=1) == 10
|
||||
assert update.update_source(installed) == 10
|
||||
assert (installed / "source.txt").read_text() == "version2"
|
||||
assert (installed / ".env").read_text() == "secret stays local"
|
||||
assert git(installed, "rev-parse", "HEAD") == git(author, "rev-parse", "HEAD")
|
||||
assert update.update_source(installed, port=1) == 0
|
||||
assert update.update_source(installed) == 0
|
||||
|
||||
|
||||
def test_dirty_checkout_is_preserved(repos):
|
||||
installed, _ = repos
|
||||
before = git(installed, "rev-parse", "HEAD")
|
||||
(installed / "source.txt").write_text("user edits")
|
||||
assert update.update_source(installed, port=1) == 0
|
||||
assert update.update_source(installed) == 1
|
||||
assert git(installed, "rev-parse", "HEAD") == before
|
||||
assert (installed / "source.txt").read_text() == "user edits"
|
||||
|
||||
@@ -77,16 +77,32 @@ def test_diverged_checkout_is_not_merged(repos):
|
||||
git(installed, "add", "local.txt")
|
||||
git(installed, "commit", "-m", "local")
|
||||
before = git(installed, "rev-parse", "HEAD")
|
||||
assert update.update_source(installed, port=1) == 0
|
||||
assert update.update_source(installed) == 1
|
||||
assert git(installed, "rev-parse", "HEAD") == before
|
||||
|
||||
|
||||
def test_zip_install_continues_without_git_mutation(tmp_path, capsys):
|
||||
assert update.update_source(tmp_path, port=1) == 0
|
||||
def test_zip_install_fails_without_git_mutation(tmp_path, capsys):
|
||||
assert update.update_source(tmp_path) == 1
|
||||
assert not (tmp_path / ".git").exists()
|
||||
assert "Git" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_startup_check_reports_update_without_changing_source(repos):
|
||||
installed, _ = repos
|
||||
before = git(installed, "rev-parse", "HEAD")
|
||||
assert update.update_source(installed, check_only=True) == 10
|
||||
assert git(installed, "rev-parse", "HEAD") == before
|
||||
assert (installed / "source.txt").read_text() == "version1"
|
||||
|
||||
|
||||
def test_update_fetch_failure_is_not_reported_as_success(repos):
|
||||
installed, _ = repos
|
||||
before = git(installed, "rev-parse", "HEAD")
|
||||
git(installed, "remote", "set-url", "origin", str(installed / "missing-upstream"))
|
||||
assert update.update_source(installed) == 1
|
||||
assert git(installed, "rev-parse", "HEAD") == before
|
||||
|
||||
|
||||
def test_codex_refresh_preserves_credentials_restrictions_and_other_settings(tmp_path):
|
||||
root = tmp_path / "project"
|
||||
path = tmp_path / "config.toml"
|
||||
@@ -120,33 +136,7 @@ command = "leave-alone"
|
||||
assert path.with_name(path.name + ".artemis-update.bak").read_text(encoding="utf-8") == original
|
||||
|
||||
|
||||
def test_json_migrates_existing_standard_mcp_to_current_checkout(tmp_path):
|
||||
path = tmp_path / "mcp.json"
|
||||
root = tmp_path / "project"
|
||||
config = {
|
||||
"cwd": str(root),
|
||||
"command": "old",
|
||||
"args": ["-m", "mcp_server"],
|
||||
"disabled": True,
|
||||
"env": {"CUSTOM": "preserved"},
|
||||
"autoApprove": [],
|
||||
}
|
||||
path.write_text(json.dumps({"mcpServers": {"artemis": config, "other": {"command": "keep"}}}))
|
||||
moved_root = tmp_path / "new release"
|
||||
assert update.refresh_json(path, ("mcpServers",), moved_root, "new", ("mobile_batch",))
|
||||
result = json.loads(path.read_text())["mcpServers"]
|
||||
assert result["artemis"]["env"]["CUSTOM"] == "preserved"
|
||||
assert result["artemis"]["env"]["PYTHONPATH"] == str(moved_root)
|
||||
assert result["artemis"]["cwd"] == str(moved_root)
|
||||
assert result["artemis"]["disabled"] is True
|
||||
assert result["other"] == {"command": "keep"}
|
||||
assert not update.refresh_json(path, ("mcpServers",), moved_root, "new", ("mobile_batch",))
|
||||
missing = tmp_path / "not-installed.json"
|
||||
assert not update.refresh_json(missing, ("mcpServers",), root, "new", ())
|
||||
assert not missing.exists()
|
||||
|
||||
|
||||
def test_mcp_sync_installs_detected_clients_and_migrates_codex(tmp_path, monkeypatch):
|
||||
def test_mcp_sync_updates_only_codex_and_preserves_other_clients(tmp_path, monkeypatch):
|
||||
from artemis.interfaces.cli.commands import mcp as mcp_command
|
||||
|
||||
home = tmp_path / "home"
|
||||
@@ -170,8 +160,11 @@ def test_mcp_sync_installs_detected_clients_and_migrates_codex(tmp_path, monkeyp
|
||||
cursor_home = home / ".cursor"
|
||||
cursor_home.mkdir()
|
||||
(cursor_home / "mcp.json").write_text('{"mcpServers":{"other":{"command":"keep"}}}')
|
||||
vscode_home = home / "AppData/Code/User"
|
||||
vscode_home.mkdir(parents=True)
|
||||
vscode_config = vscode_home / "mcp.json"
|
||||
vscode_config.write_bytes(b"{invalid VS Code JSONC}")
|
||||
monkeypatch.setattr("pathlib.Path.home", lambda: home)
|
||||
monkeypatch.setattr(mcp_command, "_get_vscode_user_dir", lambda: home / "vscode-user")
|
||||
monkeypatch.setenv("CODEX_HOME", str(codex_home))
|
||||
monkeypatch.setenv("APPDATA", str(home / "AppData"))
|
||||
root = tmp_path / "new release"
|
||||
@@ -187,26 +180,31 @@ def test_mcp_sync_installs_detected_clients_and_migrates_codex(tmp_path, monkeyp
|
||||
assert entry["env"]["PYTHONPATH"] == str(root)
|
||||
assert entry["enabled_tools"] == list(mcp_command.ARTEMIS_MCP_TOOLS)
|
||||
cursor = json.loads((cursor_home / "mcp.json").read_text(encoding="utf-8"))
|
||||
assert cursor["mcpServers"]["artemis"]["env"]["PYTHONPATH"] == str(root)
|
||||
assert "artemis" not in cursor["mcpServers"]
|
||||
assert cursor["mcpServers"]["other"] == {"command": "keep"}
|
||||
assert vscode_config.read_bytes() == b"{invalid VS Code JSONC}"
|
||||
assert not vscode_config.with_name("mcp.json.artemis-update.bak").exists()
|
||||
first = codex_config.read_text(encoding="utf-8")
|
||||
assert update.refresh_mcp(root) == 0
|
||||
assert codex_config.read_text(encoding="utf-8") == first
|
||||
|
||||
|
||||
def test_mcp_sync_fails_on_invalid_detected_config_without_overwriting(tmp_path, monkeypatch):
|
||||
from artemis.interfaces.cli.commands import mcp as mcp_command
|
||||
|
||||
def test_mcp_sync_fails_on_invalid_codex_config_without_overwriting(tmp_path, monkeypatch, capsys):
|
||||
home = tmp_path / "home"
|
||||
cursor_home = home / ".cursor"
|
||||
cursor_home.mkdir(parents=True)
|
||||
config = cursor_home / "mcp.json"
|
||||
config.write_text("{invalid json", encoding="utf-8")
|
||||
codex_home = home / ".codex"
|
||||
codex_home.mkdir(parents=True)
|
||||
config = codex_home / "config.toml"
|
||||
original = b'model = "keep-secret"\n[mcp_servers.artemis\n'
|
||||
config.write_bytes(original)
|
||||
monkeypatch.setattr("pathlib.Path.home", lambda: home)
|
||||
monkeypatch.setattr(mcp_command, "_get_vscode_user_dir", lambda: home / "vscode-user")
|
||||
monkeypatch.delenv("CODEX_HOME", raising=False)
|
||||
monkeypatch.setenv("CODEX_HOME", str(codex_home))
|
||||
assert update.refresh_mcp(tmp_path / "project") == 1
|
||||
assert config.read_text(encoding="utf-8") == "{invalid json"
|
||||
assert config.read_bytes() == original
|
||||
assert not config.with_name(config.name + ".artemis-update.bak").exists()
|
||||
output = capsys.readouterr().out
|
||||
assert str(config) in output
|
||||
assert "Invalid TOML" in output
|
||||
assert "keep-secret" not in output
|
||||
|
||||
|
||||
def test_mcp_sync_installs_codex_when_client_directory_exists(tmp_path, monkeypatch):
|
||||
@@ -216,7 +214,6 @@ def test_mcp_sync_installs_codex_when_client_directory_exists(tmp_path, monkeypa
|
||||
codex_home = home / ".codex"
|
||||
codex_home.mkdir(parents=True)
|
||||
monkeypatch.setattr("pathlib.Path.home", lambda: home)
|
||||
monkeypatch.setattr(mcp_command, "_get_vscode_user_dir", lambda: home / "vscode-user")
|
||||
monkeypatch.setenv("CODEX_HOME", str(codex_home))
|
||||
root = tmp_path / "project"
|
||||
assert update.refresh_mcp(root) == 0
|
||||
@@ -225,6 +222,59 @@ def test_mcp_sync_installs_codex_when_client_directory_exists(tmp_path, monkeypa
|
||||
assert config["mcp_servers"]["artemis"]["enabled_tools"] == list(mcp_command.ARTEMIS_MCP_TOOLS)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("codex_home_setting", [None, "", "custom"])
|
||||
def test_codex_sync_reports_actual_path_and_ready_state(
|
||||
tmp_path, monkeypatch, capsys, codex_home_setting
|
||||
):
|
||||
home = tmp_path / "home"
|
||||
codex_home = home / ".codex" if codex_home_setting != "custom" else tmp_path / "custom Codex"
|
||||
codex_home.mkdir(parents=True)
|
||||
monkeypatch.setattr("pathlib.Path.home", lambda: home)
|
||||
monkeypatch.setenv("ARTEMIS_LAUNCH_LANG", "zh-CN")
|
||||
if codex_home_setting is None:
|
||||
monkeypatch.delenv("CODEX_HOME", raising=False)
|
||||
else:
|
||||
monkeypatch.setenv("CODEX_HOME", str(codex_home) if codex_home_setting == "custom" else "")
|
||||
root = tmp_path / "project"
|
||||
assert update.refresh_mcp(root) == 0
|
||||
first = capsys.readouterr().out
|
||||
assert str(codex_home / "config.toml") in first
|
||||
assert "已安装" in first
|
||||
assert update.refresh_mcp(root) == 0
|
||||
second = capsys.readouterr().out
|
||||
assert str(codex_home / "config.toml") in second
|
||||
assert "已是最新" in second
|
||||
if codex_home_setting == "custom":
|
||||
assert not (home / ".codex").exists()
|
||||
|
||||
|
||||
def test_codex_sync_reports_missing_directory_without_touching_other_clients(
|
||||
tmp_path, monkeypatch, capsys
|
||||
):
|
||||
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
|
||||
monkeypatch.delenv("CODEX_HOME", raising=False)
|
||||
monkeypatch.setenv("ARTEMIS_LAUNCH_LANG", "zh-CN")
|
||||
assert update.refresh_mcp(tmp_path / "project") == 0
|
||||
output = capsys.readouterr().out
|
||||
assert str(tmp_path / ".codex/config.toml") in output
|
||||
assert "未发现 Codex 配置目录" in output
|
||||
assert "--install codex" in output
|
||||
assert not (tmp_path / ".codex").exists()
|
||||
|
||||
|
||||
def test_custom_codex_command_is_preserved_and_reported(tmp_path, monkeypatch, capsys):
|
||||
codex_home = tmp_path / ".codex"
|
||||
codex_home.mkdir()
|
||||
config = codex_home / "config.toml"
|
||||
original = '[mcp_servers.artemis]\ncommand = "custom"\nargs = ["wrapper"]\n'
|
||||
config.write_text(original, encoding="utf-8")
|
||||
monkeypatch.setenv("CODEX_HOME", str(codex_home))
|
||||
monkeypatch.setenv("ARTEMIS_LAUNCH_LANG", "zh-CN")
|
||||
assert update.refresh_mcp(tmp_path / "project") == 0
|
||||
assert config.read_text(encoding="utf-8") == original
|
||||
assert "自定义" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_codex_install_preserves_existing_user_tables(tmp_path):
|
||||
path = tmp_path / "config.toml"
|
||||
path.write_text(
|
||||
@@ -277,25 +327,6 @@ def test_codex_inline_environment_sync_is_idempotent(tmp_path):
|
||||
)
|
||||
|
||||
|
||||
def test_custom_mcp_wrapper_is_left_unchanged(tmp_path):
|
||||
path = tmp_path / "mcp.json"
|
||||
original = '{"mcpServers":{"artemis":{"command":"uv","args":["run","custom"]}}}'
|
||||
path.write_text(original, encoding="utf-8")
|
||||
assert (
|
||||
update.refresh_json(
|
||||
path,
|
||||
("mcpServers",),
|
||||
tmp_path,
|
||||
"new-python",
|
||||
("mobile_run_task",),
|
||||
install_missing=True,
|
||||
template={"command": "new-python", "args": ["-m", "mcp_server"], "env": {}},
|
||||
)
|
||||
is None
|
||||
)
|
||||
assert path.read_text(encoding="utf-8") == original
|
||||
|
||||
|
||||
def test_frontend_fingerprint_detects_lock_source_and_deleted_assets(tmp_path):
|
||||
ui = tmp_path / "apps/showcase_ui"
|
||||
(ui / "src").mkdir(parents=True)
|
||||
|
||||
@@ -112,7 +112,7 @@ def test_unpacked_archive_fast_forwards(repository, tmp_path):
|
||||
git(root, "push", "test-upstream", "main")
|
||||
from scripts.update_installation import update_source
|
||||
|
||||
assert update_source(extracted, port=1) == 10
|
||||
assert update_source(extracted) == 10
|
||||
assert (extracted / "start.bat").read_text() == "updated"
|
||||
assert git(extracted, "status", "--porcelain") == ""
|
||||
|
||||
@@ -132,3 +132,23 @@ def test_packaging_rejects_uncommitted_changes_and_credentials(repository, tmp_p
|
||||
)
|
||||
with pytest.raises(ValueError, match="credential-free HTTPS"):
|
||||
module.package_source(root, tmp_path / "source.zip")
|
||||
|
||||
|
||||
def test_archive_checks_out_chinese_batch_with_crlf_and_clean_git(repository, tmp_path):
|
||||
root, _, _, _ = repository
|
||||
project_root = Path(__file__).resolve().parents[2]
|
||||
(root / ".gitattributes").write_bytes((project_root / ".gitattributes").read_bytes())
|
||||
# The Git blob uses LF; the archive must contain the CRLF working-tree form.
|
||||
content = (project_root / "start-cn.bat").read_bytes().replace(b"\r\n", b"\n")
|
||||
(root / "start-cn.bat").write_bytes(content)
|
||||
git(root, "add", "--", ".gitattributes", "start-cn.bat")
|
||||
git(root, "commit", "-m", "Windows launcher attributes")
|
||||
archive_path = tmp_path / "source.zip"
|
||||
module.package_source(root, archive_path)
|
||||
with zipfile.ZipFile(archive_path) as archive:
|
||||
packed = archive.read("artemis/start-cn.bat")
|
||||
assert b"\r\n" in packed
|
||||
assert b"\n" not in packed.replace(b"\r\n", b"")
|
||||
assert packed.decode("utf-8").startswith("@echo off\r\n")
|
||||
archive.extractall(tmp_path / "unpacked")
|
||||
assert git(tmp_path / "unpacked/artemis", "status", "--porcelain") == ""
|
||||
@@ -0,0 +1,194 @@
|
||||
"""Task deadlines must apply to every ingress and exclude waits."""
|
||||
|
||||
import json
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from artemis.runtime.task_limits import ExecutionBudget, task_timeout
|
||||
from artemis.runtime.task_result import save_failure_result
|
||||
|
||||
|
||||
def test_deadline_precedence_and_single_task_default(monkeypatch):
|
||||
monkeypatch.setattr("artemis.runtime.task_limits.settings.ARTEMIS_TASK_TIMEOUT_SECONDS", 1800)
|
||||
assert task_timeout({}) == 1800
|
||||
job = {"case": {"task_config": {"timeout_seconds": 120}}}
|
||||
assert task_timeout({}, job, {"timeout_seconds": 300}) == 120
|
||||
assert task_timeout({"runtime_overrides": {"timeout_seconds": 60}}, job) == 60
|
||||
assert task_timeout({}, {}, {"timeout_seconds": 300}) == 300
|
||||
|
||||
|
||||
def test_budget_excludes_device_queue_and_user_pause(monkeypatch):
|
||||
clock = Mock(return_value=0.0)
|
||||
monkeypatch.setattr("artemis.runtime.task_limits.time.monotonic", clock)
|
||||
budget = ExecutionBudget(30, _last=0)
|
||||
budget.update(excluded=True)
|
||||
clock.return_value = 3600
|
||||
assert budget.update(excluded=False) == 30
|
||||
clock.return_value = 3610
|
||||
assert budget.update(excluded=True) == 20
|
||||
clock.return_value = 7200
|
||||
assert budget.update(excluded=False) == 20
|
||||
clock.return_value = 7221
|
||||
assert budget.update() == 0
|
||||
|
||||
|
||||
def test_failure_report_replaces_empty_result_atomically(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("artemis.runtime.task_result.TRACES_PATH", tmp_path)
|
||||
directory = tmp_path / "test-task"
|
||||
directory.mkdir()
|
||||
(directory / "result.json").touch()
|
||||
save_failure_result("test-task", "设备截图失败:ADB gone", code="device_observation_failed")
|
||||
for name in ("result.json", "run_outcome.json"):
|
||||
payload = json.loads((directory / name).read_text(encoding="utf-8"))
|
||||
assert payload["task_status"] == "failed"
|
||||
assert "ADB gone" in payload["error"]
|
||||
assert not list(directory.glob("*.tmp"))
|
||||
(directory / "result.json").write_text(
|
||||
'{"tests":{"checkpoint":{"passed":false}}}', encoding="utf-8"
|
||||
)
|
||||
save_failure_result("test-task", "任务超时", code="task_timeout")
|
||||
payload = json.loads((directory / "result.json").read_text(encoding="utf-8"))
|
||||
assert payload["tests"]["checkpoint"]["passed"] is False
|
||||
|
||||
|
||||
def test_checker_outcome_cannot_trigger_worker_cleanup(tmp_path, monkeypatch):
|
||||
from artemis.runtime.task_result import read_worker_outcome
|
||||
|
||||
monkeypatch.setattr("artemis.runtime.task_result.TRACES_PATH", tmp_path)
|
||||
directory = tmp_path / "checking"
|
||||
directory.mkdir()
|
||||
for status in ("failed", "completed"):
|
||||
(directory / "run_outcome.json").write_text(
|
||||
json.dumps({"task_status": status}), encoding="utf-8"
|
||||
)
|
||||
assert read_worker_outcome("checking") == {}
|
||||
save_failure_result("checking", "设备故障")
|
||||
assert read_worker_outcome("checking")["worker_finalized"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_single_task_hung_worker_is_killed_and_records_timeout(tmp_path, monkeypatch):
|
||||
import asyncio
|
||||
from apps.admin_console.services.task_queue_service import TaskQueueService
|
||||
|
||||
monkeypatch.setattr("artemis.runtime.task_result.TRACES_PATH", tmp_path)
|
||||
monkeypatch.setattr(
|
||||
"apps.admin_console.services.automation_store.store", Mock(job=Mock(return_value=None))
|
||||
)
|
||||
monkeypatch.setattr("artemis.runtime.task_limits.task_timeout", lambda *args: 0)
|
||||
monkeypatch.setattr("artemis.runtime.task_control.read_state", lambda *args: {})
|
||||
monkeypatch.setattr(TaskQueueService, "_sync_control_states", lambda: None)
|
||||
stopped = asyncio.Event()
|
||||
|
||||
async def wait(proc):
|
||||
await stopped.wait()
|
||||
return -9
|
||||
|
||||
kill = AsyncMock(side_effect=lambda proc: stopped.set())
|
||||
monkeypatch.setattr(TaskQueueService, "_wait_for_worker_process", wait)
|
||||
monkeypatch.setattr(TaskQueueService, "_terminate_worker_process", kill)
|
||||
item = {"session_id": "hung-single"}
|
||||
assert (
|
||||
await asyncio.wait_for(
|
||||
TaskQueueService._await_worker_with_budget(Mock(), item, "hung-single"), 2
|
||||
)
|
||||
== -9
|
||||
)
|
||||
kill.assert_awaited_once()
|
||||
assert item["timed_out"]
|
||||
result = json.loads((tmp_path / "hung-single" / "result.json").read_text(encoding="utf-8"))
|
||||
assert result["code"] == "task_timeout"
|
||||
assert "不含暂停/排队" in result["error"]
|
||||
|
||||
|
||||
def test_standalone_mcp_worker_deadline_kills_before_report_write(monkeypatch):
|
||||
from mcp_server.tools import task_runner
|
||||
|
||||
proc = Mock(pid=999999, poll=Mock(return_value=None))
|
||||
monkeypatch.setattr(task_runner.trace_store, "read_status", lambda *_: {"status": "running"})
|
||||
monkeypatch.setattr(task_runner, "read_state", lambda *_: {"status": "running"})
|
||||
monkeypatch.setattr(
|
||||
task_runner.DeviceExecutionLock,
|
||||
"get_active_owners",
|
||||
lambda: {"device": Mock(session_id="mcp-hung")},
|
||||
)
|
||||
events = []
|
||||
monkeypatch.setattr(task_runner, "_kill_process_tree", lambda *_: events.append("kill"))
|
||||
|
||||
def fail_report(*args, **kwargs):
|
||||
events.append("report")
|
||||
raise OSError("disk full")
|
||||
|
||||
monkeypatch.setattr(task_runner, "save_failure_result", fail_report)
|
||||
task_runner._watch_execution(proc, "mcp-hung", 0)
|
||||
assert events == ["kill", "report"]
|
||||
|
||||
|
||||
def test_mcp_finalized_worker_is_reclaimed_without_overwriting_device_failure(monkeypatch):
|
||||
from mcp_server.tools import task_runner
|
||||
|
||||
outcome = {"task_status": "failed", "error": "设备断连", "code": "device_observation_failed"}
|
||||
monkeypatch.setattr(task_runner, "read_worker_outcome", lambda _: outcome)
|
||||
monkeypatch.setattr(task_runner.trace_store, "read_status", lambda _: {"status": "running"})
|
||||
updated = Mock()
|
||||
monkeypatch.setattr(task_runner.trace_store, "update_trace_status", updated)
|
||||
kill = Mock()
|
||||
monkeypatch.setattr(task_runner, "_kill_process_tree", kill)
|
||||
clock = Mock(side_effect=[0.0, 0.1])
|
||||
monkeypatch.setattr(task_runner.time, "monotonic", clock)
|
||||
task_runner._watch_execution(
|
||||
Mock(pid=123, poll=Mock(return_value=None)), "test-mcp", 1800, cleanup_limit=0.01
|
||||
)
|
||||
kill.assert_called_once_with(123)
|
||||
updated.assert_called_once_with("test-mcp", "failed", error="设备断连")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("finalized", [False, True])
|
||||
async def test_real_hung_process_stops_and_next_worker_can_complete(
|
||||
tmp_path, monkeypatch, finalized
|
||||
):
|
||||
import asyncio
|
||||
import sys
|
||||
from apps.admin_console.services.task_queue_service import TaskQueueService
|
||||
|
||||
monkeypatch.setattr("artemis.runtime.task_result.TRACES_PATH", tmp_path)
|
||||
monkeypatch.setattr(
|
||||
"apps.admin_console.services.automation_store.store", Mock(job=Mock(return_value=None))
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"artemis.runtime.task_limits.task_timeout",
|
||||
lambda item, *args: 0 if item["session_id"] == "hung" and not finalized else 30,
|
||||
)
|
||||
monkeypatch.setattr("artemis.runtime.task_control.read_state", lambda *args: {})
|
||||
monkeypatch.setattr(TaskQueueService, "_sync_control_states", lambda: None)
|
||||
item = {"session_id": "hung", "runtime_overrides": {"worker_cleanup_timeout_seconds": 0.01}}
|
||||
if finalized:
|
||||
save_failure_result("hung", "设备截图失效", code="device_observation_failed")
|
||||
hung = await asyncio.create_subprocess_exec(
|
||||
sys.executable, "-c", "import time; time.sleep(3600)"
|
||||
)
|
||||
try:
|
||||
code = await asyncio.wait_for(
|
||||
TaskQueueService._await_worker_with_budget(hung, item, "hung"), 10
|
||||
)
|
||||
assert code != 0
|
||||
assert hung.returncode is not None
|
||||
result = json.loads((tmp_path / "hung" / "result.json").read_text(encoding="utf-8"))
|
||||
assert result["code"] == ("device_observation_failed" if finalized else "task_timeout")
|
||||
assert bool(item.get("timed_out")) is not finalized
|
||||
next_worker = await asyncio.create_subprocess_exec(sys.executable, "-c", "pass")
|
||||
assert (
|
||||
await asyncio.wait_for(
|
||||
TaskQueueService._await_worker_with_budget(
|
||||
next_worker, {"session_id": "next"}, "next"
|
||||
),
|
||||
10,
|
||||
)
|
||||
== 0
|
||||
)
|
||||
finally:
|
||||
if hung.returncode is None:
|
||||
hung.kill()
|
||||
await hung.wait()
|
||||
@@ -146,3 +146,40 @@ def test_batch_preserves_exit_code_and_handles_space_and_exclamation_paths(tmp_p
|
||||
timeout=30,
|
||||
)
|
||||
assert result.returncode == exit_code, result.stdout + result.stderr
|
||||
|
||||
|
||||
@pytest.mark.parametrize("exit_code", [0, 7])
|
||||
def test_chinese_batch_prints_complete_lines_and_preserves_exit_code(tmp_path, exit_code):
|
||||
root = tmp_path / "source with spaces!"
|
||||
root.mkdir()
|
||||
shutil.copy2(ROOT / "start-cn.bat", root / "start-cn.bat")
|
||||
shutil.copy2(ROOT / "start.bat", root / "start.bat")
|
||||
(root / "scripts").mkdir()
|
||||
# Exercise the real Chinese banner/help prologue, stopping before installs,
|
||||
# update checks or downloads. Chinese now belongs to PowerShell, not CMD.
|
||||
prologue = (
|
||||
(ROOT / "scripts/start.ps1")
|
||||
.read_text(encoding="utf-8-sig")
|
||||
.split("# Ensure modern TLS", 1)[0]
|
||||
)
|
||||
(root / "scripts/start.ps1").write_text(
|
||||
prologue + f"\nif ($Mirror -ne 'China') {{ exit 20 }}\nexit {exit_code}\n",
|
||||
encoding="utf-8-sig",
|
||||
)
|
||||
result = subprocess.run(
|
||||
["cmd.exe", "/d", "/c", "call", str(root / "start-cn.bat")],
|
||||
env={**os.environ, "ARTEMIS_NO_PAUSE": "1"},
|
||||
capture_output=True,
|
||||
timeout=15,
|
||||
)
|
||||
assert result.returncode == exit_code, result.stdout + result.stderr
|
||||
assert not result.stderr, result.stderr
|
||||
assert "镜像地址和下载超时可在" in result.stdout.decode("utf-8")
|
||||
help_result = subprocess.run(
|
||||
["cmd.exe", "/d", "/c", "call", str(root / "start-cn.bat"), "-Help"],
|
||||
capture_output=True,
|
||||
timeout=15,
|
||||
)
|
||||
assert help_result.returncode == 0
|
||||
assert not help_result.stderr
|
||||
assert "Codex MCP" in help_result.stdout.decode("utf-8")
|
||||
@@ -0,0 +1,357 @@
|
||||
"""Verify frozen upgrades and process ownership in disposable Windows installations."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
pytestmark = pytest.mark.skipif(
|
||||
sys.platform != "win32" or not shutil.which("powershell.exe") or not shutil.which("uv"),
|
||||
reason="Windows PowerShell and uv required",
|
||||
)
|
||||
|
||||
|
||||
def powershell(script, *, env=None, cwd=None):
|
||||
return subprocess.run(
|
||||
["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(script)],
|
||||
cwd=cwd,
|
||||
env={**os.environ, **(env or {})},
|
||||
capture_output=True,
|
||||
encoding="utf-8",
|
||||
timeout=45,
|
||||
)
|
||||
|
||||
|
||||
def git(root, *args):
|
||||
return (
|
||||
subprocess.run(["git", "-C", str(root), *args], capture_output=True, check=True, timeout=15)
|
||||
.stdout.decode()
|
||||
.strip()
|
||||
)
|
||||
|
||||
|
||||
def make_venv(root):
|
||||
subprocess.run(
|
||||
["uv", "venv", "--offline", "--python", sys.executable, str(root / ".venv")],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
timeout=30,
|
||||
)
|
||||
return root / ".venv/Scripts/python.exe"
|
||||
|
||||
|
||||
def test_process_selection_is_scoped_and_includes_descendants(tmp_path):
|
||||
root = tmp_path / "project"
|
||||
|
||||
def process(pid, executable, command, name="python.exe", parent=0):
|
||||
return dict(
|
||||
ProcessId=pid,
|
||||
ParentProcessId=parent,
|
||||
ExecutablePath=executable,
|
||||
CommandLine=command,
|
||||
Name=name,
|
||||
)
|
||||
|
||||
processes = [
|
||||
process(10, str(root / ".venv/Scripts/python.exe"), "python -m artemis ui"),
|
||||
process(11, "C:\\Python\\python.exe", "python -m multiprocessing.spawn", parent=10),
|
||||
process(12, "C:\\tools\\ffmpeg.exe", "ffmpeg recording", "ffmpeg.exe", parent=11),
|
||||
process(13, "C:\\tools\\adb.exe", "adb server", "adb.exe", parent=10),
|
||||
process(14, "C:\\apps\\codex.exe", "codex", "codex.exe", parent=10),
|
||||
process(
|
||||
20,
|
||||
str(root.with_name("project-other") / ".venv/Scripts/python.exe"),
|
||||
"python -m artemis ui",
|
||||
),
|
||||
process(21, "C:\\Python\\python.exe", "python -m artemis ui"),
|
||||
process(22, "C:\\Python\\python.exe", f'python "{root}/mcp_server/__main__.py"'),
|
||||
process(23, "C:\\Python\\python.exe", f'python "{root}/unrelated.py"'),
|
||||
process(24, str(root / ".venv/Scripts/python.exe"), "protected updater"),
|
||||
process(25, "C:\\tools\\emulator.exe", "emulator", "emulator.exe", parent=10),
|
||||
]
|
||||
fixture = tmp_path / "processes.json"
|
||||
fixture.write_text(json.dumps(processes), encoding="utf-8")
|
||||
script = tmp_path / "select.ps1"
|
||||
script.write_text(
|
||||
"[Console]::OutputEncoding = New-Object Text.UTF8Encoding($false)\n"
|
||||
f". '{ROOT / 'scripts/upgrade_processes.ps1'}'\n"
|
||||
"$snapshot = Get-Content -Raw -LiteralPath $env:PROCESS_FIXTURE | ConvertFrom-Json\n"
|
||||
"$ids = @(Get-ArtemisUpgradeProcesses -ProjectRoot $env:PROJECT_ROOT -Processes $snapshot -ProtectedIds @(24) | ForEach-Object { [int]$_.ProcessId } | Sort-Object)\n"
|
||||
"ConvertTo-Json -InputObject $ids -Compress\n",
|
||||
encoding="ascii",
|
||||
)
|
||||
result = powershell(script, env={"PROCESS_FIXTURE": str(fixture), "PROJECT_ROOT": str(root)})
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
assert json.loads(result.stdout) == [10, 11, 12, 22]
|
||||
|
||||
|
||||
def test_real_project_process_tree_stops_but_unrelated_process_survives(tmp_path):
|
||||
import psutil
|
||||
|
||||
root = tmp_path / "project with spaces!"
|
||||
root.mkdir()
|
||||
python = make_venv(root)
|
||||
pid_file = root / "child.pid"
|
||||
sleeper = root / "sleeper.py"
|
||||
sleeper.write_text(
|
||||
"import pathlib, subprocess, sys, time\n"
|
||||
"child = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)'])\n"
|
||||
"pathlib.Path(sys.argv[1]).write_text(str(child.pid))\n"
|
||||
"time.sleep(60)\n",
|
||||
encoding="ascii",
|
||||
)
|
||||
project = subprocess.Popen([str(python), str(sleeper), str(pid_file)])
|
||||
unrelated = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
|
||||
child_pid = None
|
||||
try:
|
||||
for _ in range(100):
|
||||
if pid_file.exists():
|
||||
child_pid = int(pid_file.read_text())
|
||||
break
|
||||
time.sleep(0.05)
|
||||
assert child_pid is not None
|
||||
script = tmp_path / "stop.ps1"
|
||||
script.write_text(
|
||||
"$ErrorActionPreference = 'Stop'\n"
|
||||
f". '{ROOT / 'scripts/upgrade_processes.ps1'}'\n"
|
||||
"Stop-ArtemisUpgradeProcesses -ProjectRoot $env:PROJECT_ROOT\n",
|
||||
encoding="ascii",
|
||||
)
|
||||
result = powershell(script, env={"PROJECT_ROOT": str(root)})
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
project.wait(timeout=5)
|
||||
assert unrelated.poll() is None
|
||||
assert not psutil.pid_exists(child_pid)
|
||||
finally:
|
||||
for process in (project, unrelated):
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
process.wait(timeout=5)
|
||||
if child_pid and psutil.pid_exists(child_pid):
|
||||
psutil.Process(child_pid).kill()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("prepare_exit", [0, 7])
|
||||
def test_frozen_upgrade_survives_launcher_replacement_and_reports_setup_failure(
|
||||
tmp_path, prepare_exit
|
||||
):
|
||||
if not shutil.which("git"):
|
||||
pytest.skip("Git required")
|
||||
author = tmp_path / "author"
|
||||
(author / "scripts").mkdir(parents=True)
|
||||
for name in (
|
||||
"upgrade.ps1",
|
||||
"upgrade_processes.ps1",
|
||||
"installation_lock.ps1",
|
||||
"update_installation.py",
|
||||
):
|
||||
shutil.copyfile(ROOT / "scripts" / name, author / "scripts" / name)
|
||||
for name in ("update.bat", "update-cn.bat"):
|
||||
shutil.copyfile(ROOT / name, author / name)
|
||||
(author / ".gitignore").write_text(".env\n.venv/\nprepared.txt\n")
|
||||
(author / "scripts/start.ps1").write_text("exit 23\n", encoding="ascii")
|
||||
git(author, "init", "-b", "main")
|
||||
git(author, "config", "user.name", "Fixture")
|
||||
git(author, "config", "user.email", "fixture@example.test")
|
||||
git(author, "add", ".")
|
||||
git(author, "commit", "-m", "old version")
|
||||
installed = tmp_path / "installed with spaces!"
|
||||
git(tmp_path, "clone", "-b", "main", str(author), str(installed))
|
||||
make_venv(installed)
|
||||
(installed / ".env").write_text("secret stays local")
|
||||
# A running file AND both BAT wrappers are replaced during the merge.
|
||||
(author / "scripts/upgrade.ps1").write_text("throw 'new updater must not run in this turn'\n")
|
||||
(author / "scripts/upgrade_processes.ps1").write_text(
|
||||
"throw 'new process helper must not run'\n"
|
||||
)
|
||||
(author / "update.bat").write_text("@echo off\nexit /b 33\n")
|
||||
(author / "update-cn.bat").write_text("@echo off\nexit /b 34\n")
|
||||
(author / "scripts/start.ps1").write_text(
|
||||
"param([switch]$PrepareOnly, [switch]$SkipUpdate, [switch]$NoOpen, [string]$Mirror)\n"
|
||||
"if (-not ($PrepareOnly -and $SkipUpdate -and $NoOpen) -or $Mirror -ne 'China' -or $env:ARTEMIS_UPGRADE_CHILD -ne '1') { exit 35 }\n"
|
||||
"Set-Content -LiteralPath (Join-Path (Split-Path $PSScriptRoot -Parent) 'prepared.txt') -Value 'new version prepared'\n"
|
||||
f"exit {prepare_exit}\n",
|
||||
encoding="ascii",
|
||||
)
|
||||
git(author, "add", ".")
|
||||
git(author, "commit", "-m", "new version")
|
||||
result = subprocess.run(
|
||||
["cmd.exe", "/d", "/c", "update-cn.bat"],
|
||||
cwd=installed,
|
||||
capture_output=True,
|
||||
encoding="utf-8",
|
||||
timeout=45,
|
||||
)
|
||||
assert result.returncode == (0 if prepare_exit == 0 else 1), result.stdout + result.stderr
|
||||
assert result.stderr == ""
|
||||
assert (installed / "prepared.txt").read_text().strip() == "new version prepared"
|
||||
assert git(installed, "rev-parse", "HEAD") == git(author, "rev-parse", "HEAD")
|
||||
assert (installed / ".env").read_text() == "secret stays local"
|
||||
assert ("升级完成" in result.stdout) == (prepare_exit == 0)
|
||||
assert "new updater must not run" not in result.stdout
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["update.bat", "update-cn.bat"])
|
||||
@pytest.mark.parametrize("help_flag", ["-Help", "--help"])
|
||||
def test_upgrade_help_is_safe_and_wrappers_are_ascii(name, help_flag):
|
||||
(ROOT / name).read_bytes().decode("ascii")
|
||||
result = subprocess.run(
|
||||
["cmd.exe", "/d", "/c", name, help_flag],
|
||||
cwd=ROOT,
|
||||
capture_output=True,
|
||||
encoding="utf-8",
|
||||
timeout=15,
|
||||
)
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
assert result.stderr == ""
|
||||
assert "升级会终止本项目" in result.stdout
|
||||
|
||||
|
||||
def test_installation_lock_blocks_same_checkout_and_recovers_after_owner_crash(tmp_path):
|
||||
holder_script = tmp_path / "holder.ps1"
|
||||
holder_script.write_text(
|
||||
f". '{ROOT / 'scripts/installation_lock.ps1'}'\n"
|
||||
"$lock = Enter-ArtemisInstallationLock -ProjectRoot $env:PROJECT_ROOT\n"
|
||||
"Set-Content -LiteralPath $env:READY_FILE -Value 'ready'\n"
|
||||
"Start-Sleep -Seconds 60\n",
|
||||
encoding="ascii",
|
||||
)
|
||||
ready = tmp_path / "ready.txt"
|
||||
root = tmp_path / "project"
|
||||
holder = subprocess.Popen(
|
||||
["powershell.exe", "-NoProfile", "-File", str(holder_script)],
|
||||
env={**os.environ, "PROJECT_ROOT": str(root), "READY_FILE": str(ready)},
|
||||
)
|
||||
contender = tmp_path / "contender.ps1"
|
||||
contender.write_text(
|
||||
f". '{ROOT / 'scripts/installation_lock.ps1'}'\n"
|
||||
"try {\n"
|
||||
" $lock = Enter-ArtemisInstallationLock -ProjectRoot $env:PROJECT_ROOT\n"
|
||||
" Exit-ArtemisInstallationLock -Mutex $lock\n"
|
||||
" exit 0\n"
|
||||
"} catch { Write-Host 'LOCK_BUSY'; exit 37 }\n",
|
||||
encoding="ascii",
|
||||
)
|
||||
try:
|
||||
for _ in range(100):
|
||||
if ready.exists():
|
||||
break
|
||||
time.sleep(0.05)
|
||||
assert ready.exists()
|
||||
blocked = powershell(contender, env={"PROJECT_ROOT": str(root)})
|
||||
assert blocked.returncode == 37, blocked.stdout + blocked.stderr
|
||||
assert (
|
||||
powershell(contender, env={"PROJECT_ROOT": str(root.with_name("other"))}).returncode
|
||||
== 0
|
||||
)
|
||||
holder.kill()
|
||||
holder.wait(timeout=5)
|
||||
assert powershell(contender, env={"PROJECT_ROOT": str(root)}).returncode == 0
|
||||
finally:
|
||||
if holder.poll() is None:
|
||||
holder.kill()
|
||||
holder.wait(timeout=5)
|
||||
|
||||
|
||||
def test_actual_preparation_build_checks_run_without_launching_ui_or_adb(tmp_path):
|
||||
root = tmp_path / "prepared project"
|
||||
(root / "scripts").mkdir(parents=True)
|
||||
for name in ("start.ps1", "installation_lock.ps1"):
|
||||
shutil.copyfile(ROOT / "scripts" / name, root / "scripts" / name)
|
||||
(root / "scripts/download_config.ps1").write_text(
|
||||
"function Initialize-ArtemisDownloads { $script:ArtemisDownloads = @{mode='Official'} }\n",
|
||||
encoding="ascii",
|
||||
)
|
||||
(root / "scripts/bootstrap_python.ps1").write_text(
|
||||
"function Initialize-ArtemisPython { return $env:TEST_PYTHON }\n", encoding="ascii"
|
||||
)
|
||||
(root / "scripts/update_installation.py").write_text(
|
||||
"import pathlib, sys\n"
|
||||
"root = pathlib.Path(__file__).parent.parent\n"
|
||||
"with (root / 'checks.txt').open('a') as f: f.write(sys.argv[1] + '\\n')\n"
|
||||
"sys.exit(0)\n",
|
||||
encoding="ascii",
|
||||
)
|
||||
(root / ".env").write_text("keep credentials")
|
||||
index = root / "apps/showcase_ui/dist/frontend/browser/index.html"
|
||||
index.parent.mkdir(parents=True)
|
||||
index.write_text("built frontend")
|
||||
tools = root / "stub-tools"
|
||||
tools.mkdir()
|
||||
for name in ("adb", "scrcpy", "ffmpeg"):
|
||||
(tools / f"{name}.cmd").write_text("@echo off\nexit /b 91\n")
|
||||
result = subprocess.run(
|
||||
[
|
||||
"powershell.exe",
|
||||
"-NoProfile",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-File",
|
||||
str(root / "scripts/start.ps1"),
|
||||
"-PrepareOnly",
|
||||
"-SkipUpdate",
|
||||
"-NoOpen",
|
||||
],
|
||||
env={
|
||||
**os.environ,
|
||||
"TEST_PYTHON": sys.executable,
|
||||
"PATH": str(tools) + os.pathsep + os.environ["PATH"],
|
||||
},
|
||||
capture_output=True,
|
||||
encoding="utf-8",
|
||||
timeout=15,
|
||||
)
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
assert (root / "checks.txt").read_text().splitlines() == ["mcp", "frontend-check"]
|
||||
assert "Launching Artemis" not in result.stdout
|
||||
assert "ADB" not in result.stderr
|
||||
assert (root / ".env").read_text() == "keep credentials"
|
||||
|
||||
|
||||
def test_dirty_checkout_refuses_upgrade_before_stopping_processes(tmp_path):
|
||||
if not shutil.which("git"):
|
||||
pytest.skip("Git required")
|
||||
root = tmp_path / "dirty installation"
|
||||
(root / "scripts").mkdir(parents=True)
|
||||
for name in (
|
||||
"upgrade.ps1",
|
||||
"upgrade_processes.ps1",
|
||||
"installation_lock.ps1",
|
||||
"update_installation.py",
|
||||
):
|
||||
shutil.copyfile(ROOT / "scripts" / name, root / "scripts" / name)
|
||||
(root / ".gitignore").write_text(".venv/\n")
|
||||
source = root / "user.txt"
|
||||
source.write_text("original")
|
||||
git(root, "init", "-b", "main")
|
||||
git(root, "config", "user.name", "Fixture")
|
||||
git(root, "config", "user.email", "fixture@example.test")
|
||||
git(root, "add", ".")
|
||||
git(root, "commit", "-m", "initial")
|
||||
python = make_venv(root)
|
||||
source.write_text("user changes")
|
||||
worker = subprocess.Popen([str(python), "-c", "import time; time.sleep(60)"])
|
||||
try:
|
||||
result = powershell(root / "scripts/upgrade.ps1")
|
||||
assert result.returncode == 1, result.stdout + result.stderr
|
||||
assert "发现本地修改" in result.stdout
|
||||
assert "[STOP]" not in result.stdout
|
||||
assert worker.poll() is None
|
||||
assert source.read_text() == "user changes"
|
||||
finally:
|
||||
# Windows venv redirectors can have a second interpreter process.
|
||||
import psutil
|
||||
|
||||
if worker.poll() is None:
|
||||
children = psutil.Process(worker.pid).children(recursive=True)
|
||||
worker.kill()
|
||||
for child in children:
|
||||
if child.is_running():
|
||||
child.kill()
|
||||
worker.wait(timeout=5)
|
||||
@@ -47,6 +47,17 @@ else:
|
||||
del sys.modules["artemis.graph.state"]
|
||||
|
||||
|
||||
import base64
|
||||
from io import BytesIO
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def _valid_screen_base64():
|
||||
buffer = BytesIO()
|
||||
Image.new("RGB", (64, 64), "white").save(buffer, format="PNG")
|
||||
return base64.b64encode(buffer.getvalue()).decode("ascii")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_context():
|
||||
"""Create a mock ArtemisContext for testing."""
|
||||
@@ -70,6 +81,7 @@ def mock_context():
|
||||
|
||||
# Mock the ADB client for Android
|
||||
mock_response = Mock()
|
||||
mock_response.base64 = _valid_screen_base64()
|
||||
mock_response.json.return_value = {"elements": []}
|
||||
ctx.ui_adb_client.get_screen_data = Mock(return_value=mock_response)
|
||||
ctx.ui_adb_client.get_hierarchy = Mock(
|
||||
@@ -288,6 +300,7 @@ class TestFocusElementIfNeeded:
|
||||
focused_element["attributes"]["focused"] = "true"
|
||||
|
||||
mock_response = Mock()
|
||||
mock_response.base64 = _valid_screen_base64()
|
||||
mock_response.json.return_value = {"elements": [focused_element]}
|
||||
mock_context.ui_adb_client.get_screen_data = Mock(return_value=mock_response)
|
||||
mock_find_element.return_value = focused_element["attributes"]
|
||||
@@ -366,6 +379,7 @@ class TestFocusElementIfNeeded:
|
||||
}
|
||||
|
||||
mock_response = Mock()
|
||||
mock_response.base64 = _valid_screen_base64()
|
||||
mock_response.json.return_value = {"elements": [element_from_text]}
|
||||
mock_context.ui_adb_client.get_screen_data = Mock(return_value=mock_response)
|
||||
mock_find_id.return_value = element_from_id
|
||||
@@ -401,6 +415,7 @@ class TestFocusElementIfNeeded:
|
||||
}
|
||||
|
||||
mock_response = Mock()
|
||||
mock_response.base64 = _valid_screen_base64()
|
||||
mock_response.json.return_value = {"elements": [element_with_bounds]}
|
||||
mock_context.ui_adb_client.get_screen_data = Mock(return_value=mock_response)
|
||||
mock_find_text.return_value = element_with_bounds["attributes"]
|
||||
@@ -428,6 +443,7 @@ class TestFocusElementIfNeeded:
|
||||
"""Test failure when no locator can find an element."""
|
||||
|
||||
mock_response = Mock()
|
||||
mock_response.base64 = _valid_screen_base64()
|
||||
mock_response.json.return_value = {"elements": []}
|
||||
mock_context.ui_adb_client.get_screen_data = Mock(return_value=mock_response)
|
||||
with (
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
@echo off
|
||||
chcp 65001 >nul 2>&1
|
||||
setlocal DisableDelayedExpansion
|
||||
set "ARTEMIS_LAUNCH_LANG=zh-CN"
|
||||
if /i "%~1"=="--help" goto help
|
||||
call "%~dp0update.bat" -Mirror China %* & call exit /b %%ERRORLEVEL%%
|
||||
:help
|
||||
call "%~dp0update.bat" -Mirror China -Help & call exit /b %%ERRORLEVEL%%
|
||||
@@ -0,0 +1,7 @@
|
||||
@echo off
|
||||
chcp 65001 >nul 2>&1
|
||||
setlocal DisableDelayedExpansion
|
||||
if /i "%~1"=="--help" goto help
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0scripts\upgrade.ps1" %* & call exit /b %%ERRORLEVEL%%
|
||||
:help
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0scripts\upgrade.ps1" -Help & call exit /b %%ERRORLEVEL%%
|
||||
Reference in new issue
Block a user