diff --git a/.dockerignore b/.dockerignore index 6657576ea..ec8944c1e 100644 --- a/.dockerignore +++ b/.dockerignore @@ -13,3 +13,13 @@ dist traces .env *.log + +# Private environment variants and signing keys +.env.* +*.env +*.pem +*.key +!.env.example +!*.env.example + +.runtime diff --git a/.gitignore b/.gitignore index 31cf3e936..47c93660a 100644 --- a/.gitignore +++ b/.gitignore @@ -116,3 +116,10 @@ live_screenshot*.png .Trashes ehthumbs.db Thumbs.db + +# Local environment variants +*.env +!*.env.example + +# Local detector services and verification media +.runtime/ diff --git a/apps/admin_console/routers/sessions.py b/apps/admin_console/routers/sessions.py index 6d828b772..365a72279 100644 --- a/apps/admin_console/routers/sessions.py +++ b/apps/admin_console/routers/sessions.py @@ -237,3 +237,31 @@ async def delete_session_endpoint(session_id: str): } except Exception as e: raise HTTPException(status_code=500, detail=str(e)) + + +@router.get("/api/sessions/{session_id}/quality") +def get_quality_results(session_id: UUID): + from pathlib import Path + from artemis.tools.quality_tool import read_quality_results + + return read_quality_results(Path(TRACES_PATH) / str(session_id) / "quality") + + +@router.get("/api/sessions/{session_id}/quality/media/{digest}") +def get_quality_media(session_id: UUID, digest: str): + import re + from pathlib import Path + from fastapi.responses import FileResponse + from artemis.tools.quality_tool import read_quality_results + + if not re.fullmatch(r"[a-f0-9]{64}", digest): + raise HTTPException(404, "Evidence not found") + directory = Path(TRACES_PATH) / str(session_id) / "quality" + records = read_quality_results(directory) + record = next((r for r in records if r.get("evidence_digest") == digest), None) + path = directory / digest + if not record or not path.is_file() or path.is_symlink(): + raise HTTPException(404, "Evidence not found") + return FileResponse( + path, media_type=record["evidence_type"], headers={"X-Content-Type-Options": "nosniff"} + ) diff --git a/apps/admin_console/routers/tasks.py b/apps/admin_console/routers/tasks.py index 26fca4611..c1b7d5c38 100644 --- a/apps/admin_console/routers/tasks.py +++ b/apps/admin_console/routers/tasks.py @@ -13,11 +13,14 @@ # limitations under the License. import asyncio -from contextlib import suppress import json +from contextlib import suppress from typing import Any + from fastapi import APIRouter, HTTPException, Request from fastapi.responses import StreamingResponse +from pydantic import SecretStr + from artemis.core.diagnostics import readiness_engine from artemis.runtime import DeviceExecutionLock, device_pool @@ -67,7 +70,7 @@ async def get_task_catalog(): @router.post("/api/run") -async def run_task(request: RunRequest): +async def run_task(request: RunRequest, http_request: Request = None): incoming_goals = [] if request.goals: incoming_goals = request.goals @@ -80,6 +83,53 @@ async def run_task(request: RunRequest): detail="Either 'goal' or 'goals' list must be provided.", ) + model_options = {} + if request.model_override is not None: + if ( + http_request is None + or http_request.client is None + or http_request.client.host not in {"127.0.0.1", "::1"} + ): + raise HTTPException( + status_code=403, detail="Per-run model overrides require a local node agent" + ) + if not request.session_id or len(incoming_goals) != 1: + raise HTTPException( + status_code=422, detail="A model override requires one goal and a session ID" + ) + model_options = { + "model_override": request.model_override, + "model_key": SecretStr(http_request.headers.get("X-Artemis-Run-Model-Key", "")), + } + + from artemis.drivers.browser import ( + configured_browser, + installed_engines, + slot_headless, + slot_available, + ) + + is_browser = request.device_platform == "browser" + if is_browser: + if not request.browser or not configured_browser(request.device_serial): + raise HTTPException(422, "Configure a browser slot and provide browser settings") + if request.app_path or request.locked_app_package or request.quality_tools: + raise HTTPException( + 422, "Mobile app and quality capture tools are unavailable for browsers" + ) + if request.browser.engine not in installed_engines(): + raise HTTPException(422, "The requested browser engine is not installed on this node") + if request.browser.headless != slot_headless(request.device_serial): + raise HTTPException(422, "Browser launch mode does not match the configured slot") + if not slot_available(request.device_serial): + raise HTTPException(422, "Headed browser requires an available desktop DISPLAY") + model_options["browser"] = request.browser.model_dump() + elif request.browser or configured_browser(request.device_serial): + raise HTTPException(422, "Browser settings and slot require device_platform=browser") + + if request.quality_tools is not None: + model_options["quality_tools"] = request.quality_tools + # Idempotent SDK retries must never re-run device readiness checks. A task # can hold the device while its admission response is lost in transit; in # that state, probing the same device again may fail or block even though @@ -141,7 +191,17 @@ async def run_task(request: RunRequest): # prefers the diagnostics target preference, then any unlocked ready # device); the verified serial is bound below. target_serial = request.device_serial - device_probe = await readiness_engine.run_device_submission_probe(target_serial=target_serial) + from artemis.drivers.ios.appium_driver import configured_ios + + if request.device_platform == "ios" and not configured_ios(target_serial): + raise HTTPException(422, "iOS target is not configured on this execution engine") + if request.device_platform == "android" and configured_ios(target_serial): + raise HTTPException(422, "Device platform does not match configured iPhone") + device_probe = ( + None + if configured_ios(target_serial) or is_browser + else 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 = ( device_probe.metadata.get("active_device", {}).get("serial") or target_serial or "" @@ -178,6 +238,7 @@ async def run_task(request: RunRequest): ingress=request.ingress or "frontend", session_id=request.session_id, conversation_id=request.conversation_id, + **model_options, ) @@ -191,8 +252,19 @@ async def get_run_defaults(): from artemis.config import load_agent_config, verification_level_for_checker agent_cfg = load_agent_config() + from artemis.tools.quality_tool import configured_quality_tools + from artemis.drivers.browser import installed_engines, browser_slots, headed_slots + return { "verification_level": verification_level_for_checker(agent_cfg.checker), + "task_model_override": 1, + "ios_driver_version": 1, + "browser_driver_version": 2, + "browser_slots": browser_slots(), + "browser_headed_slots": headed_slots(), + "browser_engines": installed_engines(), + "quality_tools_version": 1, + "quality_tools_available": [tool.kind for tool in configured_quality_tools()], "explorer_mode": agent_cfg.explorer.resolve(profile="pro"), } diff --git a/apps/admin_console/schemas/task_schema.py b/apps/admin_console/schemas/task_schema.py index 144a97203..277c0fea7 100644 --- a/apps/admin_console/schemas/task_schema.py +++ b/apps/admin_console/schemas/task_schema.py @@ -12,10 +12,18 @@ # See the License for the specific language governing permissions and # limitations under the License. +from typing import Literal + from pydantic import BaseModel +from artemis.config.run_model import RunModel + + +from artemis.drivers.browser import BrowserConfig + class RunRequest(BaseModel): + browser: BrowserConfig | None = None goal: str | None = None goals: list[str] | None = None profile: str | None = "flash" @@ -29,9 +37,12 @@ class RunRequest(BaseModel): locked_app_package: str | None = None app_path: str | None = None device_serial: str | None = None + device_platform: Literal["android", "ios", "browser"] | None = None ingress: str | None = "frontend" session_id: str | None = None conversation_id: str | None = None + model_override: RunModel | None = None + quality_tools: list[Literal["visual", "audio"]] | None = None class ReplayRequest(BaseModel): diff --git a/apps/admin_console/services/task_queue_service.py b/apps/admin_console/services/task_queue_service.py index b99b4c919..832ce53f7 100644 --- a/apps/admin_console/services/task_queue_service.py +++ b/apps/admin_console/services/task_queue_service.py @@ -13,6 +13,7 @@ # limitations under the License. import asyncio +import json from datetime import datetime import logging import os @@ -41,6 +42,9 @@ TEST_OUTPUTS_DIR, WORKSPACE_ROOT, ) +from artemis.config.run_model import MODEL_ENV, MODEL_KEY_ENV, RunModel +from pydantic import SecretStr + from artemis.runtime import ( AdbEndpoint, AdbTarget, @@ -56,6 +60,16 @@ logger = logging.getLogger(__name__) +class _TaskWithModel(dict): + """Keep the credential on the in-memory item, outside its serializable fields.""" + + def __init__(self, task_item, model: RunModel, key: SecretStr | None): + super().__init__(task_item) + self.model = model + self.key = key + self["execution_model"] = model.model_dump(mode="json", include={"config_id", "revision"}) + + class TaskQueueService: """Service managing FIFO task execution, background worker, subprocess lifecycle, and startup tasks. @@ -510,6 +524,19 @@ def _build_worker_invocation( test_name = f"web_{int(time.time())}_{run_key[:8]}" env = os.environ.copy() + env.pop("ARTEMIS_QUALITY_TOOLS", None) + env.pop("ARTEMIS_BROWSER_CONFIG", None) + if task_item.get("browser") is not None: + env["ARTEMIS_BROWSER_CONFIG"] = json.dumps(task_item["browser"]) + if task_item.get("quality_tools") is not None: + env["ARTEMIS_QUALITY_TOOLS"] = json.dumps(task_item["quality_tools"]) + env.pop(MODEL_ENV, None) + env.pop(MODEL_KEY_ENV, None) + if isinstance(task_item, _TaskWithModel): + env[MODEL_ENV] = task_item.model.model_dump_json() + if task_item.key is not None: + env[MODEL_KEY_ENV] = task_item.key.get_secret_value() + task_item.key = None pythonpath_parts = [ str(WORKSPACE_ROOT), str(WORKSPACE_ROOT / "apps" / "admin_console"), @@ -1052,6 +1079,10 @@ async def enqueue_tasks( conversation_id: str | None = None, verification_level: str | None = None, explorer_mode: str | None = None, + model_override: RunModel | None = None, + model_key: SecretStr | None = None, + quality_tools: list[str] | None = None, + browser: dict | None = None, ) -> dict[str, Any]: """Enqueues one or more goals and wakes up the background worker. @@ -1106,6 +1137,12 @@ async def enqueue_tasks( verification_level=verification_level, explorer_mode=explorer_mode, ) + if browser is not None: + task_item["browser"] = browser + if quality_tools is not None: + task_item["quality_tools"] = list(dict.fromkeys(quality_tools)) + if model_override is not None: + task_item = _TaskWithModel(task_item, model_override, model_key) state.queue_items.append(task_item) enqueued_tasks.append(task_item) cls._broadcast_startup_progress( diff --git a/artemis/agents/checker/checker.py b/artemis/agents/checker/checker.py index 52dff2ca2..0ee98df9e 100644 --- a/artemis/agents/checker/checker.py +++ b/artemis/agents/checker/checker.py @@ -311,6 +311,20 @@ def build_checker_tools( *get_history_tools(ctx), get_read_note_tool_pure(ctx), ] + from artemis.tools.quality_tool import ( + configured_quality_tools, + quality_directory, + read_quality_results, + ) + + if configured_quality_tools(): + + @tool + def read_quality_checks() -> str: + """Read recorded quality checks. Missing/advisory/inconclusive checks cannot establish an explicit quality expectation as passed. Match criterion, step and full required interval.""" + return json.dumps(read_quality_results(quality_directory(ctx)), ensure_ascii=False) + + tools.append(read_quality_checks) if probes_enabled(ctx): tools.append(get_probe_tool(ctx)) return tools @@ -694,6 +708,9 @@ async def run_checkpoint_check( check_items=items, ) prompts = _load_prompts() + from artemis.tools.quality_tool import quality_guidance + + prompts["system"] = prompts.get("system", "") + quality_guidance() tools = build_checker_tools(ctx, "checkpoint") probe_registered = any(t.name == "probe_device" for t in tools) system_content = "\n\n".join( @@ -811,6 +828,9 @@ async def run_final_check( check_items=items, ) prompts = _load_prompts() + from artemis.tools.quality_tool import quality_guidance + + prompts["system"] = prompts.get("system", "") + quality_guidance() tools = build_checker_tools(ctx, "final") probe_registered = any(t.name == "probe_device" for t in tools) system_content = "\n\n".join( diff --git a/artemis/agents/flash/runner.py b/artemis/agents/flash/runner.py index 3ea3f6865..cf471eddf 100644 --- a/artemis/agents/flash/runner.py +++ b/artemis/agents/flash/runner.py @@ -211,6 +211,9 @@ def _get_tools(self) -> list: from artemis.tools.video_tool import VIDEO_ANALYZER_TOOL tools.append(VIDEO_ANALYZER_TOOL) + from artemis.tools.quality_tool import configured_quality_tools + + tools.extend(t.to_tool_declaration() for t in configured_quality_tools()) tools.append(REPORT_TASK_STATUS_TOOL) # With an actuator installed, drop declarations for device actions the # backend does not implement (and append its extension tools); without @@ -296,7 +299,12 @@ def _render_system_prompt(self, tools_declaration: list) -> str: prompt_path = Path(__file__).parent / "flash_runner.md" prompt_template = prompt_path.read_text(encoding="utf-8") available_tools = frozenset(t.name for t in tools_declaration) - return Template(prompt_template).render(goal=self.goal, available_tools=available_tools) + from artemis.tools.quality_tool import quality_guidance + + return ( + Template(prompt_template).render(goal=self.goal, available_tools=available_tools) + + quality_guidance() + ) # ------------------------------------------------------------------ # Per-turn helpers (observe / think) diff --git a/artemis/agents/operator/operator.py b/artemis/agents/operator/operator.py index d24536270..de775511a 100644 --- a/artemis/agents/operator/operator.py +++ b/artemis/agents/operator/operator.py @@ -58,6 +58,8 @@ logger = get_logger(__name__) DEFERRING_TOOLS = { + "check_visual_quality", + "check_audio_quality", "ask_diagnoser", "video_analyzer", "read_note", @@ -915,6 +917,24 @@ async def __call__(self, state: State): operator_shell_tool(name) for name in OPERATOR_SHELL_ORDER if name in available_actions ] + self.tools + actuator = getattr(self.ctx, "actuator", None) + if actuator is not None: + from langchain_core.tools import StructuredTool + + all_tools = [ + t for t in all_tools if t.name not in getattr(actuator, "unsupported_tools", ()) + ] + for ext in actuator.extensions(): + if "operator" in ext.targets: + all_tools.append( + StructuredTool( + name=ext.name, + description=ext.description, + args_schema=ext.input_schema, + func=lambda **kwargs: "Action Recorded", + ) + ) + # 5. Mount the task-output analyzer and collect background ADB task state. # The analyzer is always available: the "output truncated, use # analyze_task_output" hint arrives mid-turn, and tools are bound once per @@ -1090,6 +1110,19 @@ def _translate_and_validate_tool_inner( tool_name = tc["name"].split(":")[-1] if ":" in tc["name"] else tc["name"] args = tc["args"] + actuator = getattr(self.ctx, "actuator", None) + if actuator is not None and any( + e.name == tool_name and "operator" in e.targets for e in actuator.extensions() + ): + return [ + { + "action": tool_name, + "tool_args": args, + "target_text": args.get("name", ""), + "target_description": args.get("action", ""), + } + ], None + # Get device resolution fallbacks width = 1080 height = 2400 @@ -1252,6 +1285,20 @@ def target_fields(el: dict) -> dict: ) return actions, None + elif tool_name == "perform_gesture": + from artemis.mcp.gestures import validate_phases + + try: + phases = validate_phases(args.get("phases")) + description = args.get("target_description") + if not isinstance(description, str) or not description.strip(): + raise ValueError("target_description is required for a gesture") + except (ValueError, TypeError) as exc: + return [], f"Invalid gesture: {exc}" + return [ + {"action": "perform_gesture", "phases": phases, "target_description": description} + ], None + elif tool_name == "swipe": kind, target, parsed_duration = parse_swipe_parameters(args, default_duration=None) duration = args.get("duration") diff --git a/artemis/agents/operator/prompts.py b/artemis/agents/operator/prompts.py index e800de234..6d8e92e31 100644 --- a/artemis/agents/operator/prompts.py +++ b/artemis/agents/operator/prompts.py @@ -63,7 +63,13 @@ def load_operator_prompts() -> dict[str, str]: # tool set the rendered output is byte-identical to the pre-assembly literals. See # artemis/agents/prompt_assembly.py for the assembly rationale. -_PRE_DECISION_HELPER_TOOLS = ("ask_explorer", "ask_diagnoser", "video_analyzer") +_PRE_DECISION_HELPER_TOOLS = ( + "ask_explorer", + "ask_diagnoser", + "video_analyzer", + "check_visual_quality", + "check_audio_quality", +) _PRE_DECISION_ADB_TOOLS = ("run_adb_command", "manage_task") _PRE_DECISION_MEMORY_TOOLS = ( "read_note", @@ -83,6 +89,7 @@ def load_operator_prompts() -> dict[str, str]: _TURN_ENDING_ORDER = ( "click", "swipe", + "perform_gesture", "input_text", "long_press", "press_key", @@ -228,6 +235,10 @@ def resolve_operator_prompt_tools(ctx: ArtemisContext) -> frozenset[str]: except Exception as e: logger.warning(f"Failed to assemble prompt against actuator: {e}") + from artemis.tools.quality_tool import QUALITY_TOOL_NAMES, configured_quality_tools + + available.difference_update(QUALITY_TOOL_NAMES) + available.update(t.name for t in configured_quality_tools()) return frozenset(available) @@ -315,6 +326,9 @@ def render_transcript_static_system( ) available = resolve_operator_prompt_tools(ctx) + from artemis.tools.quality_tool import quality_guidance + + static_template += quality_guidance() static_template = apply_operator_prompt_contract(static_template, available_tools=available) return Template(static_template).render( initial_goal=state.initial_goal, @@ -368,6 +382,9 @@ async def __call__(self, builder: PromptBuilder, state: State, ctx: ArtemisConte **_grammar_render_context(ctx), ) + from artemis.tools.quality_tool import quality_guidance + + full_prompt = quality_guidance() + full_prompt parts = full_prompt.split("# CURRENT OBSERVATION") builder.add_system_text(parts[0] + f"# CURRENT OBSERVATION{_legacy_elapsed_suffix(ctx)}\n") diff --git a/artemis/agents/planner/planner.py b/artemis/agents/planner/planner.py index 02be5c7c4..3925df4d0 100644 --- a/artemis/agents/planner/planner.py +++ b/artemis/agents/planner/planner.py @@ -233,6 +233,10 @@ async def __call__(self, state: State): final_check=final, ) + from artemis.tools.quality_tool import quality_guidance + + system_message += quality_guidance() + # Get screenshot screenshot_b64 = None screenshot_path = state.latest_screenshot if hasattr(state, "latest_screenshot") else None diff --git a/artemis/agents/validator/action_execution.py b/artemis/agents/validator/action_execution.py index 215f757d4..28b60fcab 100644 --- a/artemis/agents/validator/action_execution.py +++ b/artemis/agents/validator/action_execution.py @@ -82,6 +82,16 @@ async def exec_action( await asyncio.sleep(time_in_ms / 1000.0) return True, "" + actuator = getattr(ctx, "actuator", None) + if actuator is not None and any(ext.name == action_name for ext in actuator.extensions()): + try: + result = await session.call(action_name, action_item.get("tool_args", {})) + if result.normalized_coordinates: + action_item["normalized_coordinates"] = result.normalized_coordinates + return result.ok, result.message + except Exception as exc: + return False, f"Browser tool failed: {exc}" + width = getattr(ctx.device, "device_width", 1080) if ctx.device else 1080 height = getattr(ctx.device, "device_height", 2400) if ctx.device else 2400 diff --git a/artemis/agents/validator/execution_loop.py b/artemis/agents/validator/execution_loop.py index cd3b7a4ae..0045e3341 100644 --- a/artemis/agents/validator/execution_loop.py +++ b/artemis/agents/validator/execution_loop.py @@ -182,7 +182,8 @@ async def _process_action( attempts_log = [] validation_passed = True - if not burst: + if not burst and action_name != "browser_action": + # Semantic browser locators enforce strict matching and actionability in Playwright. # 1. Pre-execution validation (Safety Net) original_coords = list(action_item.get("coordinates") or []) ( @@ -205,7 +206,11 @@ async def _process_action( if burst: max_local_retries = 1 else: - max_local_retries = 1 if action_name == "launch_app" else 2 + # A timed-out gesture may already be dispatched; never replay it. + # Keep the existing retry policy for every other action. + max_local_retries = ( + 1 if action_name in ("launch_app", "perform_gesture", "browser_action") else 2 + ) outcome.success, outcome.error_msg = await _attempt_local_execution( node, session, diff --git a/artemis/agents/validator/tool_declarations.py b/artemis/agents/validator/tool_declarations.py index fba8dd751..a8aed2c99 100644 --- a/artemis/agents/validator/tool_declarations.py +++ b/artemis/agents/validator/tool_declarations.py @@ -238,6 +238,8 @@ def normalize_coordinate_target(target: Any) -> int | list[int] | Any: SWIPE_TOOL = tool_declaration("swipe") +PERFORM_GESTURE_TOOL = tool_declaration("perform_gesture") + PRESS_KEY_TOOL = tool_declaration("press_key") READ_NOTE_TOOL = ToolDeclaration( @@ -324,6 +326,7 @@ def normalize_coordinate_target(target: Any) -> int | list[int] | Any: LONG_PRESS_TOOL, INPUT_TEXT_TOOL, SWIPE_TOOL, + PERFORM_GESTURE_TOOL, PRESS_KEY_TOOL, READ_NOTE_TOOL, LIST_NOTES_TOOL, diff --git a/artemis/clients/accessibility_client.py b/artemis/clients/accessibility_client.py index f14b8ab3c..7df5aa35f 100644 --- a/artemis/clients/accessibility_client.py +++ b/artemis/clients/accessibility_client.py @@ -413,6 +413,51 @@ def press_key(self, key: str) -> bool: def tap(self, x: float, y: float) -> bool: return self._rpc("tap", {"x": x, "y": y}) + def perform_gesture(self, phases: list[dict], request_id: str) -> dict[str, Any]: + from artemis.mcp.gestures import gesture_duration_bound_ms, validate_phases + + phases = validate_phases(phases) + info = json.loads(self._http("/ping").decode("utf-8")) + if "perform_gesture" not in info.get("capabilities", []): + return { + "success": False, + "status": "unsupported", + "error": "Upgrade Accessibility Helper: perform_gesture is not supported", + } + long_press_drag = phases[0].get("kind") == "long_press_drag" + if long_press_drag and "gesture_long_press_drag" not in info.get("capabilities", []): + return { + "success": False, + "status": "unsupported", + "error": "Upgrade Accessibility Helper: long-press dragging is not supported", + } + if any( + "control_points" in phase + or any("control_points" in p for p in phase.get("pointers", [])) + for phase in phases + ) and ("gesture_cubic_bezier" not in info.get("capabilities", [])): + return { + "success": False, + "status": "unsupported", + "error": "Upgrade Accessibility Helper: native cubic Bezier is not supported", + } + if (len(phases) > 1 or long_press_drag) and not info.get("gesture_continuation", False): + return { + "success": False, + "status": "unsupported", + "error": "Continuous gestures require Android 8.0+", + } + timeout = gesture_duration_bound_ms(phases) / 1000 + 10 + payload = {"cmd": "perform_gesture", "request_id": request_id, "phases": phases} + return json.loads(self._http("/action", payload, timeout=timeout).decode("utf-8")) + + def cancel_gesture(self, request_id: str) -> dict[str, Any]: + return json.loads( + self._http("/action", {"cmd": "cancel_gesture", "request_id": request_id}).decode( + "utf-8" + ) + ) + def swipe(self, x1: float, y1: float, x2: float, y2: float, duration_ms: int = 300) -> bool: return self._rpc("swipe", {"x1": x1, "y1": y1, "x2": x2, "y2": y2, "duration": duration_ms}) diff --git a/artemis/config/llm.py b/artemis/config/llm.py index 641d2e198..d3933efbd 100644 --- a/artemis/config/llm.py +++ b/artemis/config/llm.py @@ -23,6 +23,7 @@ AgentNode, ) from artemis.config.paths import ROOT_DIR, get_config_path +from artemis.config.run_model import current_run_model from artemis.utils.cython_compat import CyFunctionDetector from third_party.mobile_use.config import llm as base_llm_config from third_party.mobile_use.config.llm import ( @@ -93,6 +94,11 @@ class LLMConfig(LLMConfigBase): def validate_providers(self) -> None: """Validate credentials across all configured agent nodes.""" + # AgentConfigBuilder validates profiles again after initialization. + # Managed workers resolve every role through the scoped endpoint; + # node-local .env credentials are neither required nor authoritative. + if current_run_model() is not None: + return super().validate_providers() self.summarizer.validate_provider("Summarizer") self.operator.validate_provider("Operator") @@ -199,6 +205,24 @@ def _expand_default_into_nodes(config_dict: dict) -> dict: def parse_llm_config() -> LLMConfig: """Parse and instantiate LLMConfig from artemis.jsonc or llm-config.json.""" + if selected := current_run_model(): + model, _ = selected + primary = {"provider": model.api_schema, "model": model.model_id} + # The native roles require a fallback entry. Keep it on the selected model. + config = { + "default": {**primary, "fallback": primary}, + "nodes": { + role: primary + for role in ( + "history_analyzer", + "validator_pixel_safety_net", + "planner_validation", + "output_analyzer", + ) + }, + } + return LLMConfig.model_validate(_expand_default_into_nodes(config)) + config_path = None for candidate in ("artemis.jsonc", "artemis.json", LLM_CONFIG_FILENAME): try: @@ -222,6 +246,14 @@ def parse_llm_config() -> LLMConfig: def initialize_llm_config() -> LLMConfig: """Parse and validate credentials for LLMConfig.""" + if selected := current_run_model(): + # These credentials are scoped to the worker rather than node settings. + model, _ = selected + logger.info( + f"Using per-run model {model.api_schema}/{model.model_id} " + f"(configuration {model.config_id} revision {model.revision})" + ) + return parse_llm_config() return base_llm_config.initialize_llm_config(parse_llm_config) diff --git a/artemis/config/run_model.py b/artemis/config/run_model.py new file mode 100644 index 000000000..a7eeed0cb --- /dev/null +++ b/artemis/config/run_model.py @@ -0,0 +1,53 @@ +"""Model selection provided by the control plane for one worker process.""" + +import os +from functools import cache +from typing import Literal +from urllib.parse import urlsplit +from uuid import UUID + +from pydantic import BaseModel, ConfigDict, Field, SecretStr, model_validator + + +MODEL_ENV = "ARTEMIS_TASK_MODEL" +MODEL_KEY_ENV = "ARTEMIS_TASK_MODEL_KEY" + + +class RunModel(BaseModel): + model_config = ConfigDict(extra="forbid", hide_input_in_errors=True) + + config_id: UUID + revision: int = Field(ge=1) + model_id: str = Field(min_length=1, max_length=200) + api_schema: Literal["openai", "anthropic"] + url: str = Field(min_length=1, max_length=2000) + context_window: int = Field(ge=1024, le=10000000) + thinking_effort: Literal["default", "none", "minimal", "low", "medium", "high", "xhigh", "max"] + + @model_validator(mode="after") + def validate_endpoint(self): + url = urlsplit(self.url) + if ( + url.scheme not in {"http", "https"} + or not url.hostname + or url.username is not None + or url.password is not None + or url.query + or url.fragment + or any(c.isspace() or ord(c) < 32 for c in self.url) + or "\\" in self.url + or url.path.rstrip("/").endswith(("/chat/completions", "/messages", "/responses")) + ): + raise ValueError("Expected an HTTP(S) API base URL without credentials") + incompatible = {"max"} if self.api_schema == "openai" else {"minimal", "xhigh"} + if self.thinking_effort in incompatible: + raise ValueError("Thinking effort is incompatible with the selected API schema") + return self + + +@cache +def current_run_model() -> tuple[RunModel, SecretStr] | None: + # Consume the credential before subprocesses (e.g. local test tools) inherit it. + raw = os.environ.pop(MODEL_ENV, None) + key = os.environ.pop(MODEL_KEY_ENV, "") + return (RunModel.model_validate_json(raw), SecretStr(key)) if raw is not None else None diff --git a/artemis/context.py b/artemis/context.py index 57360c8c8..7e72ddef3 100644 --- a/artemis/context.py +++ b/artemis/context.py @@ -17,9 +17,7 @@ from __future__ import annotations import asyncio - -from pathlib import Path -from typing import Any, Literal, TYPE_CHECKING +from typing import TYPE_CHECKING, Any, Literal if TYPE_CHECKING: from artemis.data_engine.engine import DataEngine @@ -30,17 +28,14 @@ AdbClient = Any from pydantic import BaseModel, ConfigDict, Field, PrivateAttr -from artemis.utils.video import detect_video_tools_enabled - from artemis.config import ExplorerConfig, LLMConfig, OutputterConfig - - +from artemis.utils.video import detect_video_tools_enabled from third_party.mobile_use.context import ( - AppLaunchResult, - DeviceContext, + AppLaunchResult as AppLaunchResult, + DevicePlatform as DevicePlatform, DeviceClientAccessors, - DevicePlatform, + DeviceContext, ExecutionSetupBase, ) from third_party.mobile_use.utils.logger import get_logger @@ -277,6 +272,9 @@ async def __aexit__(self, exc_type, exc_val, exc_tb): self.mcp_client_ctx = None self.mcp_session = None + driver = getattr(self, "_active_driver", None) + if driver is not None and str(self.device.mobile_platform) in {"ios", "browser"}: + await driver.disconnect() if self.data_engine: try: await self.data_engine.shutdown() @@ -284,6 +282,6 @@ async def __aexit__(self, exc_type, exc_val, exc_tb): logger.debug(f"DataEngine shutdown failed; skipped: {exc}", exc_info=True) -from artemis.data_engine.engine import DataEngine +from artemis.data_engine.engine import DataEngine # noqa: E402 - resolves recursive model after definition ArtemisContext.model_rebuild() diff --git a/artemis/controllers/unified_controller.py b/artemis/controllers/unified_controller.py index d0dc1d035..791e9860c 100644 --- a/artemis/controllers/unified_controller.py +++ b/artemis/controllers/unified_controller.py @@ -56,6 +56,16 @@ def __init__(self, ctx: ArtemisContext): super().__init__(ctx, get_driver(ctx)) self._segment_cache: dict[tuple[str, int, float, float], VideoRecordingResult] = {} + async def perform_gesture(self, phases: list[dict]) -> dict: + method = getattr(self._driver, "perform_gesture", None) + if method is None: + return { + "success": False, + "status": "unsupported", + "error": "Driver has no continuous multi-touch support", + } + return await method(phases) + @staticmethod async def _spawn_scrcpy(command: list[str]) -> asyncio.subprocess.Process: kwargs: dict[str, Any] = { @@ -84,6 +94,103 @@ def _get_device_id(self) -> str: return self.ctx.device.device_id return getattr(self._driver, "device_id", None) or "default" + async def extract_quality_segment( + self, start_time: float, end_time: float + ) -> VideoRecordingResult: + """Session-relative capture with no synthetic black frames or silent audio. + + A rotation/restart boundary requires separate checks; unlike the visual + analyzer we never pad, resize, concatenate mismatched captures, or clamp. + """ + from artemis.utils.video import plan_timeline_pieces, get_ffmpeg_path + + session = get_active_session(self._get_device_id()) + if not session or not session.local_video_path: + return VideoRecordingResult(success=False, message="No active recording") + offset = max( + 0.0, session.start_time - (session.data_engine_start_time or session.start_time) + ) + start, end = start_time - offset, end_time - offset + current_time = time.time() + if start < 0 or end <= start or end > current_time - session.start_time - 0.5: + return VideoRecordingResult( + success=False, + message="Requested interval is not fully captured; wait for capture to finish", + ) + records = [dict(r) for r in session.android_segment_records] + active_start = session.android_segment_started_at or session.start_time + if session.local_video_path.exists(): + records.append( + dict( + path=session.local_video_path, + start=max(0.0, active_start - session.start_time), + end=current_time - session.start_time, + ) + ) + pieces = plan_timeline_pieces(records, start, end) + if len(pieces) != 1 or pieces[0][0] != "file": + return VideoRecordingResult( + success=False, + message="Recording has a gap or rotation boundary; check each continuous segment separately", + ) + _, source, local_start, local_end = pieces[0] + directory = Path( + tempfile.mkdtemp(prefix="quality-capture-", dir=get_temp_dir("trimmed_videos")) + ) + output = directory / "segment.mp4" + process = await asyncio.create_subprocess_exec( + get_ffmpeg_path(), + "-nostdin", + "-v", + "error", + "-ss", + str(local_start), + "-i", + str(source), + "-t", + str(local_end - local_start), + "-map", + "0:v:0", + "-map", + "0:a:0?", + "-c:v", + "libx264", + "-preset", + "veryfast", + "-crf", + "12", + "-c:a", + "alac", + "-movflags", + "+faststart", + str(output), + stdout=asyncio.subprocess.DEVNULL, + stderr=asyncio.subprocess.PIPE, + ) + try: + _, stderr = await asyncio.wait_for(process.communicate(), timeout=60) + if process.returncode or not output.exists(): + output.unlink(missing_ok=True) + directory.rmdir() + return VideoRecordingResult( + success=False, + message="Unable to extract original recording; no quality conclusion", + ) + return VideoRecordingResult( + success=True, + video_path=output, + actual_start_relative_time=start_time, + duration_seconds=end_time - start_time, + message="Original-size capture; existing audio preserved without synthetic silence", + ) + except BaseException: + if process.returncode is None: + process.kill() + await process.wait() + output.unlink(missing_ok=True) + directory.rmdir() + raise + async def extract_segment_metadata( self, start_time: float, diff --git a/artemis/drivers/android/adb_driver.py b/artemis/drivers/android/adb_driver.py index 360aa4862..a8ec1ee9b 100644 --- a/artemis/drivers/android/adb_driver.py +++ b/artemis/drivers/android/adb_driver.py @@ -254,6 +254,30 @@ async def tap( async def long_press(self, x: int, y: int, duration_ms: int = 1000) -> bool: return await self.tap(x=x, y=y, duration_ms=duration_ms) + async def perform_gesture(self, phases: list[dict]) -> dict: + from artemis.clients.accessibility_client import AccessibilityClient + from artemis.mcp.gestures import validate_phases + from uuid import uuid4 + + phases = validate_phases(phases) + client = AccessibilityClient(self.device_id, provision_on_connect=False) + request_id = uuid4().hex + task = asyncio.create_task(asyncio.to_thread(client.perform_gesture, phases, request_id)) + try: + return await asyncio.shield(task) + except asyncio.CancelledError: + # The action request is never replayed. Ask the device to finish the current + # phase and lift its held contacts, then wait for the terminal reply. + try: + await asyncio.shield(asyncio.to_thread(client.cancel_gesture, request_id)) + await asyncio.wait_for(asyncio.shield(task), timeout=10.0) + except Exception: + logger.warning( + "Gesture cancellation could not be confirmed; device needs reconciliation" + ) + task.add_done_callback(lambda t: t.exception() if not t.cancelled() else None) + raise + async def swipe( self, start_x: int, diff --git a/artemis/drivers/browser.py b/artemis/drivers/browser.py new file mode 100644 index 000000000..8de4b0fd2 --- /dev/null +++ b/artemis/drivers/browser.py @@ -0,0 +1,279 @@ +"""Per-attempt Playwright browser, with no persistent user profile or ADB dependency.""" + +import base64 +from concurrent.futures import ThreadPoolExecutor +from functools import lru_cache +import os +import sys +from pathlib import Path +from typing import Literal +from urllib.parse import urlsplit +from xml.etree.ElementTree import Element, SubElement, tostring + +from pydantic import BaseModel, ConfigDict, Field, field_validator + +from artemis.drivers.base import BaseDeviceDriver, ScreenData + + +class BrowserConfig(BaseModel): + model_config = ConfigDict(extra="forbid") + headless: bool = True + url: str = Field(max_length=2048) + engine: Literal["chromium", "firefox", "webkit"] = "chromium" + width: int = Field(default=1440, ge=320, le=3840) + height: int = Field(default=900, ge=240, le=2160) + + @field_validator("url") + @classmethod + def valid_url(cls, value): + parsed = urlsplit(value) + if ( + parsed.scheme not in {"http", "https"} + or not parsed.hostname + or parsed.username + or parsed.password + ): + raise ValueError("Use an HTTP(S) URL without embedded credentials") + return value + + @classmethod + def from_env(cls): + return cls.model_validate_json(os.environ["ARTEMIS_BROWSER_CONFIG"]) + + +def browser_slots(): + return [s.strip() for s in os.getenv("ARTEMIS_BROWSER_SLOTS", "").split(",") if s.strip()] + + +def headed_slots(): + slots = [ + s.strip() for s in os.getenv("ARTEMIS_BROWSER_HEADED_SLOTS", "").split(",") if s.strip() + ] + if not set(slots) <= set(browser_slots()): + raise ValueError("Headed slots must be included in ARTEMIS_BROWSER_SLOTS") + return slots + + +def slot_headless(serial): + return serial not in headed_slots() + + +def slot_available(serial): + return slot_headless(serial) or sys.platform != "linux" or bool(os.getenv("DISPLAY")) + + +def configured_browser(serial): + return bool(serial and serial in browser_slots()) + + +@lru_cache(maxsize=1) +def installed_engines(): + # The inventory is also called from async routes. Keep the sync Playwright probe + # off their loop; installation changes require an engine restart. + def inspect(): + try: + from playwright.sync_api import sync_playwright + + with sync_playwright() as p: + return [ + name + for name in ("chromium", "firefox", "webkit") + if Path(getattr(p, name).executable_path).is_file() + ] + except Exception: + return [] + + with ThreadPoolExecutor(max_workers=1) as pool: + return pool.submit(inspect).result() + + +class BrowserDriver(BaseDeviceDriver): + def __init__(self, serial, options=None, context=None): + self.serial = serial + self.execution_context = context + self.options = options or BrowserConfig.from_env() + self.playwright = self.browser = self.context = self.page = None + self.events = [] + + @property + def device_id(self): + return self.serial + + @property + def screen_size(self): + return self.options.width, self.options.height + + def record(self, kind, message): + # Bounded diagnostics; request/response bodies, headers and cookies are never collected. + if len(self.events) < 200: + self.events.append({"kind": kind, "message": str(message)[:1000]}) + + def bind_page(self, page): + page.on("pageerror", lambda error: self.record("page_error", error)) + page.on( + "console", + lambda message: ( + self.record("console", message.text) if message.type == "error" else None + ), + ) + page.on( + "requestfailed", + lambda req: self.record( + "request_failed", f"{req.method} {urlsplit(req.url).path}: {req.failure}" + ), + ) + page.on( + "response", + lambda res: ( + self.record("http_error", f"{res.status} {urlsplit(res.url).path}") + if res.status >= 400 + else None + ), + ) + # Native dialogs otherwise block all subsequent actions. Default dismissal is + # explicit evidence; tests needing acceptance configure the next dialog action. + page.on("dialog", self.handle_dialog) + + async def handle_dialog(self, dialog): + self.record("dialog", f"{dialog.type}: {dialog.message}") + mode, text = getattr(self, "next_dialog", ("dismiss", "")) + self.next_dialog = ("dismiss", "") + if mode == "accept": + await dialog.accept(text) + else: + await dialog.dismiss() + + async def connect(self): + if self.context is not None: + if not self.browser.is_connected() or self.page.is_closed(): + raise RuntimeError("Browser session was lost; a new attempt is required") + return + from playwright.async_api import async_playwright + + self.playwright = await async_playwright().start() + try: + self.browser = await getattr(self.playwright, self.options.engine).launch( + headless=self.options.headless + ) + self.context = await self.browser.new_context( + viewport={"width": self.options.width, "height": self.options.height}, + accept_downloads=False, + ) + self.context.set_default_timeout(10000) + self.context.set_default_navigation_timeout(30000) + self.context.on("page", self.bind_page) + self.page = await self.context.new_page() + await self.page.goto(self.options.url, wait_until="domcontentloaded") + except BaseException: + await self.disconnect() + raise + + async def disconnect(self): + if self.execution_context and self.execution_context.data_engine: + from artemis.utils.notes import save_note_content + + try: + save_note_content( + self.execution_context.data_engine.base_dir, + "browser_diagnostics", + "\n".join(f"{e['kind']}: {e['message']}" for e in self.events), + ) + except OSError: + pass # A failed diagnostic write must not leak the browser process. + try: + if self.context: + await self.context.close() + finally: + try: + if self.browser: + await self.browser.close() + finally: + if self.playwright: + await self.playwright.stop() + self.page = self.context = self.browser = self.playwright = None + + async def get_screen_data(self, skip_settling=False): + await self.connect() + image = await self.page.screenshot(type="png", animations="disabled") + # A read-only DOM snapshot supplies the same bounding boxes used by visual + # fallback actions. Native semantic locators are preferred for normal forms. + elements = await self.page.locator("body").evaluate("""body => Array.from(body.querySelectorAll('a,button,input,textarea,select,[role],label,h1,h2,h3,p')).map(e => { + const r=e.getBoundingClientRect(); return {text:(e.getAttribute('aria-label')||e.innerText||e.getAttribute('placeholder')||'').slice(0,500), + resource_id:e.getAttribute('data-testid')||e.id||'', class:e.tagName, + bounds:`[${Math.round(r.x)},${Math.round(r.y)}][${Math.round(r.right)},${Math.round(r.bottom)}]`, + center:[Math.round(r.x+r.width/2),Math.round(r.y+r.height/2)], + clickable:String(e.matches('a,button,input,select,textarea,[role="button"]')), + focused:String(e===document.activeElement),visible:r.width>0&&r.height>0&&r.bottom>0&&r.ye.visible).slice(0,400)""") + tree = Element("browser", url=self.page.url, title=await self.page.title()) + for element in elements: + SubElement(tree, "node", {k: str(v) for k, v in element.items() if k != "center"}) + return ScreenData( + screenshot_bytes=image, + screenshot_base64=base64.b64encode(image).decode(), + ui_hierarchy_xml=tostring(tree, encoding="unicode"), + ui_elements=elements, + width=self.options.width, + height=self.options.height, + platform="browser", + ) + + async def tap(self, x, y, duration_ms=100, times=1, delay_ms=100): + await self.connect() + await self.page.mouse.click(x, y, click_count=times, delay=delay_ms) + return True + + async def long_press(self, x, y, duration_ms=1000): + await self.connect() + await self.page.mouse.click(x, y, delay=duration_ms) + return True + + async def swipe(self, start_x, start_y, end_x, end_y, duration_ms=800): + await self.connect() + await self.page.mouse.move(start_x, start_y) + await self.page.mouse.down() + try: + await self.page.mouse.move(end_x, end_y, steps=20) + finally: + await self.page.mouse.up() + return True + + async def swipe_direction(self, direction, duration_ms=800): + await self.connect() + delta = {"up": (0, 600), "down": (0, -600), "left": (600, 0), "right": (-600, 0)}[ + str(direction) + ] + await self.page.mouse.wheel(*delta) + return True + + async def input_text(self, text, clear_existing=True): + await self.connect() + await self.page.locator(":focus").fill( + text + ) if clear_existing else await self.page.keyboard.insert_text(text) + return True + + async def press_key(self, key): + await self.connect() + keys = {"enter": "Enter", "delete": "Backspace", "back": "Escape"} + await self.page.keyboard.press(keys.get(str(key), str(key))) + return True + + async def get_current_package(self): + await self.connect() + return self.page.url + + async def launch_app(self, package_name): + raise NotImplementedError("Use browser_action navigate with an HTTP(S) URL") + + async def stop_app(self, package_name): + raise NotImplementedError("Browser lifecycle belongs to the execution attempt") + + async def execute_shell(self, command, timeout_seconds=15): + raise NotImplementedError("Browser sessions cannot execute device shell commands") + + async def start_video_recording(self, output_dir=None): + raise NotImplementedError("Browser reports capture step screenshots") + + async def stop_video_recording(self): + return None diff --git a/artemis/drivers/factory.py b/artemis/drivers/factory.py index d6283a1c6..98119eb16 100644 --- a/artemis/drivers/factory.py +++ b/artemis/drivers/factory.py @@ -33,6 +33,14 @@ def create_driver(ctx: "ArtemisContext") -> BaseDeviceDriver: """Instantiates the appropriate BaseDeviceDriver based on the runtime context.""" + if str(getattr(ctx.device, "mobile_platform", "")).lower() == "ios": + from artemis.drivers.ios.appium_driver import IOSAppiumDriver + + return IOSAppiumDriver(ctx.device.device_id) + if str(getattr(ctx.device, "mobile_platform", "")).lower() == "browser": + from artemis.drivers.browser import BrowserDriver + + return BrowserDriver(ctx.device.device_id, context=ctx) # 1. Cloud mode check. Cloud devices are reached through the gateway's # RemoteUIAutomatorClient; ARTEMIS_HIERARCHY_BACKEND does not apply there # because the Accessibility Helper needs a local adb forward. diff --git a/artemis/drivers/ios/__init__.py b/artemis/drivers/ios/__init__.py new file mode 100644 index 000000000..a3df6a1fe --- /dev/null +++ b/artemis/drivers/ios/__init__.py @@ -0,0 +1 @@ +"""iOS support through an explicitly configured, node-owned Appium session.""" diff --git a/artemis/drivers/ios/appium_driver.py b/artemis/drivers/ios/appium_driver.py new file mode 100644 index 000000000..7a7a6d8f1 --- /dev/null +++ b/artemis/drivers/ios/appium_driver.py @@ -0,0 +1,271 @@ +"""iOS driver. Install Kraken's packages/ios-device into this engine environment.""" + +import asyncio +import base64 +import os +import xml.etree.ElementTree as ET +from pathlib import Path + +from artemis.drivers.base import BaseDeviceDriver, ScreenData + + +def configured_ios(serial): + return bool(serial and serial == os.getenv("IOS_UDID")) + + +def client_for(serial): + if not configured_ios(serial): + raise ValueError("iPhone UDID is not explicitly configured in this engine") + try: + from kraken_ios import AppiumDevice + except ImportError as exc: + raise RuntimeError( + "Install Kraken packages/ios-device in the execution engine environment" + ) from exc + return AppiumDevice(serial) + + +def probe_ios(serial): + client = client_for(serial) + try: + client.attach() + if client.request("GET", "/appium/device/is_locked"): + raise RuntimeError("iPhone is locked; unlock it before execution") + return client.info() + finally: + client.close() + + +class IOSAppiumDriver(BaseDeviceDriver): + def __init__(self, device_id): + self._device_id = device_id + self.client = client_for(device_id) + self._frame = None + + @property + def device_id(self): + return self._device_id + + @property + def screen_size(self): + return (self._frame["width"], self._frame["height"]) if self._frame else (0, 0) + + async def connect(self): + await asyncio.to_thread(self.client.attach) + + async def disconnect(self): + self.client.close() # The node owns the session; never delete it here. + + async def get_screen_data(self, skip_settling=False): + await self.connect() + frame = await asyncio.to_thread(self.client.screenshot) + xml = await asyncio.to_thread(self.client.source) + geometry = await asyncio.to_thread(self.client.geometry) + if geometry["viewport"] != frame["viewport"]: + raise RuntimeError("iPhone rotated during observation; capture a new frame") + sx, sy = frame["width"] / geometry["width"], frame["height"] / geometry["height"] + elements = [] + root = ET.fromstring(xml) + for item in root.iter(): + a = item.attrib + if not all(k in a for k in ("x", "y", "width", "height")): + continue + if a.get("visible") == "false": + continue + x, y = ( + (float(a["x"]) - geometry.get("x", 0)) * sx, + (float(a["y"]) - geometry.get("y", 0)) * sy, + ) + w, h = float(a["width"]) * sx, float(a["height"]) * sy + elements.append( + { + "resource_id": a.get("name", ""), + "text": a.get("label") or a.get("value", ""), + "class": a.get("type", item.tag), + "bounds": f"[{round(x)},{round(y)}][{round(x + w)},{round(y + h)}]", + "clickable": a.get("enabled", "false"), + "visible": a.get("visible", "true"), + "focused": a.get("focused", "false"), + } + ) + self._frame = frame + return ScreenData( + screenshot_bytes=base64.b64decode(frame["png"]), + screenshot_base64=frame["png"], + ui_hierarchy_xml=xml, + ui_elements=elements, + width=frame["width"], + height=frame["height"], + platform="ios", + ) + + async def _input(self, payload): + await self.connect() + await asyncio.to_thread(self.client.execute, payload) + return True + + async def tap(self, x, y, duration_ms=100, times=1, delay_ms=100): + if not self._frame: + await self.get_screen_data() + width, height = self.screen_size + for i in range(times): + await self._input( + { + "kind": "tap", + "x": x / width, + "y": y / height, + "viewport": self._frame["viewport"], + "hold_ms": duration_ms, + } + ) + if i + 1 < times: + await asyncio.sleep(delay_ms / 1000) + return True + + async def long_press(self, x, y, duration_ms=1000): + return await self.tap(x, y, duration_ms=duration_ms) + + async def swipe(self, start_x, start_y, end_x, end_y, duration_ms=800, hold_ms=0): + if not self._frame: + await self.get_screen_data() + width, height = self.screen_size + return await self._input( + { + "kind": "swipe", + "x": start_x / width, + "y": start_y / height, + "x2": end_x / width, + "y2": end_y / height, + "duration_ms": duration_ms, + "hold_ms": hold_ms, + "viewport": self._frame["viewport"], + } + ) + + async def swipe_direction(self, direction, duration_ms=800): + if not self._frame: + await self.get_screen_data() + direction = getattr(direction, "value", direction) + points = { + "up": (0.5, 0.8, 0.5, 0.2), + "down": (0.5, 0.2, 0.5, 0.8), + "left": (0.8, 0.5, 0.2, 0.5), + "right": (0.2, 0.5, 0.8, 0.5), + }[direction] + width, height = self.screen_size + return await self.swipe( + *(round(p * (width if i % 2 == 0 else height)) for i, p in enumerate(points)), + duration_ms=duration_ms, + ) + + async def perform_gesture(self, phases): + from artemis.mcp.gestures import validate_phases + + phases = validate_phases(phases) + if not self._frame: + await self.get_screen_data() + geometry = await asyncio.to_thread(self.client.geometry) + if geometry["viewport"] != self._frame["viewport"]: + raise RuntimeError("iPhone orientation changed; capture a new frame") + + def point(p): + return { + "x": round(p[0] / 1000 * (geometry["width"] - 1) + geometry.get("x", 0)), + "y": round(p[1] / 1000 * (geometry["height"] - 1) + geometry.get("y", 0)), + } + + if phases[0].get("kind") == "long_press_drag": + p = phases[0] + if p.get("control_points"): + raise NotImplementedError( + "iOS supports straight continuous drags; Bezier paths are not enabled" + ) + actions = [ + {"type": "pointerMove", "duration": 0, "origin": "viewport", **point(p["start"])}, + {"type": "pointerDown", "button": 0}, + {"type": "pause", "duration": p.get("hold_ms", 1000)}, + { + "type": "pointerMove", + "duration": p["duration_ms"], + "origin": "viewport", + **point(p["end"]), + }, + {"type": "pause", "duration": p.get("release_delay_ms", 0)}, + ] + else: + if any( + len(p["pointers"]) != 1 or p["pointers"][0].get("control_points") for p in phases + ): + raise NotImplementedError( + "iOS currently supports one continuous touch pointer without Bezier controls" + ) + actions = [ + { + "type": "pointerMove", + "duration": 0, + "origin": "viewport", + **point(phases[0]["pointers"][0]["path"][0]), + }, + {"type": "pointerDown", "button": 0}, + ] + for phase in phases: + path = phase["pointers"][0]["path"] + if len(path) == 1: + actions.append({"type": "pause", "duration": phase["duration_ms"]}) + else: + for i, p in enumerate(path[1:]): + duration = phase["duration_ms"] // (len(path) - 1) + if i == len(path) - 2: + duration += phase["duration_ms"] % (len(path) - 1) + actions.append( + { + "type": "pointerMove", + "duration": duration, + "origin": "viewport", + **point(p), + } + ) + actions.append({"type": "pointerUp", "button": 0}) + await asyncio.to_thread(self.client.actions, actions) + return { + "success": True, + "status": "completed", + "release_confirmed": True, + "platform": "ios", + } + + async def input_text(self, text, clear_existing=True): + await self.connect() + if clear_existing: + element = await asyncio.to_thread(self.client.request, "GET", "/element/active") + eid = element["element-6066-11e4-a52e-4f735466cecf"] + await asyncio.to_thread(self.client.request, "POST", f"/element/{eid}/clear", {}) + return await self._input({"kind": "text", "text": text}) + + async def press_key(self, key): + return await self._input({"kind": "key", "key": str(getattr(key, "value", key)).upper()}) + + async def launch_app(self, package_name): + return await self._input( + {"kind": "device_command", "command": "app launch " + package_name} + ) + + async def stop_app(self, package_name): + return await self._input( + {"kind": "device_command", "command": "app terminate " + package_name} + ) + + async def get_current_package(self): + await self.connect() + return (await asyncio.to_thread(self.client.mobile, "activeAppInfo")).get("bundleId") + + async def execute_shell(self, command, timeout_seconds=15): + raise NotImplementedError("iOS does not provide Android shell commands; use device actions") + + async def start_video_recording(self, output_dir: Path | None = None): + raise NotImplementedError( + "iOS preview is not an execution recording; step screenshots are available" + ) + + async def stop_video_recording(self): + return None diff --git a/artemis/drivers/mock/mock_driver.py b/artemis/drivers/mock/mock_driver.py index c4b12c44b..b46c33366 100644 --- a/artemis/drivers/mock/mock_driver.py +++ b/artemis/drivers/mock/mock_driver.py @@ -106,6 +106,22 @@ async def long_press(self, x: int, y: int, duration_ms: int = 1000) -> bool: ) return True + async def perform_gesture(self, phases: list[dict]) -> dict: + from artemis.mcp.gestures import validate_phases + + phases = validate_phases(phases) + self.action_history.append({"action": "perform_gesture", "phases": phases}) + return { + "success": True, + "status": "completed", + "release_confirmed": True, + "phases_completed": ( + 2 + int(phases[0].get("release_delay_ms", 0) > 0) + if phases[0].get("kind") == "long_press_drag" + else len(phases) + ), + } + async def swipe( self, start_x: int, diff --git a/artemis/graph/graph.py b/artemis/graph/graph.py index 499739110..2ffcd1828 100644 --- a/artemis/graph/graph.py +++ b/artemis/graph/graph.py @@ -1008,7 +1008,10 @@ async def get_graph(ctx: ArtemisContext) -> CompiledStateGraph: " commands." ) + from artemis.tools.quality_tool import configured_quality_tools + operator_tools = operator_native_tools + operator_specialized_tools + operator_tools.extend(t.to_langchain_tool(ctx) for t in configured_quality_tools()) if ctx.execution_setup and ctx.execution_setup.video_recording_tools_enabled: operator_tools.append(get_video_analyzer_tool(ctx, role="operator")) diff --git a/artemis/interfaces/cli/commands/run.py b/artemis/interfaces/cli/commands/run.py index 89dca25ab..3f3114819 100644 --- a/artemis/interfaces/cli/commands/run.py +++ b/artemis/interfaces/cli/commands/run.py @@ -16,9 +16,14 @@ import asyncio import os +import signal from typing import Annotated +import typer from langchain_core.callbacks.base import Callbacks +from rich.console import Console +from rich.panel import Panel + from artemis.config import checker_overrides_for_level, settings from artemis.utils.startup_progress import publish_startup_progress from third_party.mobile_use.main import ( @@ -33,10 +38,6 @@ ) from third_party.mobile_use.utils.cli_helpers import display_local_device_status from third_party.mobile_use.utils.logger import get_logger -import signal -from rich.console import Console -from rich.panel import Panel -import typer logger = get_logger(__name__) @@ -147,8 +148,16 @@ async def execute_task( if target_serial: from artemis.context import DevicePlatform - - config.for_device(DevicePlatform.ANDROID, target_serial) + from artemis.drivers.ios.appium_driver import configured_ios + + config.for_device( + DevicePlatform.BROWSER + if os.getenv("ARTEMIS_BROWSER_CONFIG") + else DevicePlatform.IOS + if configured_ios(target_serial) + else DevicePlatform.ANDROID, + target_serial, + ) if graph_config_callbacks: config.with_graph_config_callbacks(graph_config_callbacks) @@ -297,7 +306,13 @@ def run_command( ] = False, ) -> None: """Run an autonomous UI automation task on the connected Android device.""" - ensure_video_recording_available(with_video_recording_tools) + from artemis.drivers.ios.appium_driver import configured_ios + + ios_target = configured_ios( + device_serial or settings.ADB_DEVICE_SERIAL or os.getenv("ADB_DEVICE_SERIAL") + ) + if not ios_target and not os.getenv("ARTEMIS_BROWSER_CONFIG"): + ensure_video_recording_available(with_video_recording_tools) console = Console() @@ -311,11 +326,12 @@ def run_command( if not is_worker and not is_standalone: try: import uuid + from artemis.runtime import ( ensure_daemon_running, + stop_task_on_daemon, submit_task_to_daemon, wait_for_daemon_task, - stop_task_on_daemon, ) console.print("[dim]Connecting to Artemis Daemon scheduler...[/dim]") @@ -390,7 +406,8 @@ def on_status(sess_info): f"[yellow]Daemon routing notice: {exc}. Falling back to local execution...[/yellow]" ) - display_local_device_status(console, host=settings.ADB_HOST, port=settings.ADB_PORT) + if not ios_target and not os.getenv("ARTEMIS_BROWSER_CONFIG"): + display_local_device_status(console, host=settings.ADB_HOST, port=settings.ADB_PORT) cancelled = False original_sigterm = None diff --git a/artemis/llm/router.py b/artemis/llm/router.py index f2e6b42b6..3e696dba3 100644 --- a/artemis/llm/router.py +++ b/artemis/llm/router.py @@ -20,6 +20,7 @@ """ from enum import StrEnum +from functools import cached_property import hashlib import os from typing import Any @@ -89,8 +90,11 @@ class ModelEndpoint(BaseModel): provider: ModelProvider = Field(default=ModelProvider.GOOGLE, description="Model provider") model_name: str = Field(default="gemini-2.5-flash", description="Model name identifier") - api_key: str | None = Field(default=None, description="API Key or secret") + api_key: str | None = Field( + default=None, repr=False, exclude=True, description="API Key or secret" + ) api_base: str | None = Field(default=None, description="Custom API endpoint base URL") + context_window: int | None = None temperature: float = Field(default=0.0, description="Sampling temperature") max_tokens: int | None = Field(default=None, description="Maximum completion tokens") timeout_seconds: float = Field(default=60.0, description="Request timeout in seconds") @@ -129,6 +133,7 @@ def cache_key(self) -> tuple: self.reasoning_effort, self.enable_grounding, self.api_base, + self.context_window, api_key_digest, ) @@ -195,6 +200,71 @@ def patched_process_tool_config(self, tool_choice, tool_config, formatted_tools) logger.warning(f"Could not patch ChatGoogleGenerativeAI._process_tool_config: {e}") +def _platform_chat_model(endpoint: ModelEndpoint) -> BaseChatModel: + """Use exactly the endpoint and credentials selected for this run.""" + import httpx + + key = endpoint.api_key + anthropic_schema = endpoint.provider == ModelProvider.ANTHROPIC + + def filter_headers(request: httpx.Request) -> None: + if anthropic_schema or not key: + request.headers.pop("Authorization", None) + if not key: + request.headers.pop("X-Api-Key", None) + + async def filter_async_headers(request: httpx.Request) -> None: + filter_headers(request) + + http = {"timeout": endpoint.timeout_seconds, "trust_env": False, "follow_redirects": False} + common = { + "model": endpoint.model_name, + "api_key": key or "no-key-configured", + "timeout": endpoint.timeout_seconds, + "profile": {"max_input_tokens": endpoint.context_window}, + "max_retries": 0, + } + if not anthropic_schema: + from langchain_openai import ChatOpenAI + + return ChatOpenAI( + **common, + base_url=endpoint.api_base, + use_responses_api=False, + reasoning_effort=endpoint.reasoning_effort, + http_client=httpx.Client(**http, event_hooks={"request": [filter_headers]}), + http_async_client=httpx.AsyncClient( + **http, event_hooks={"request": [filter_async_headers]} + ), + ) + + import anthropic + from langchain_anthropic import ChatAnthropic + + class PlatformAnthropic(ChatAnthropic): + @cached_property + def _client(self): + client = httpx.Client(**http, event_hooks={"request": [filter_headers]}) + return anthropic.Anthropic(**self._client_params, auth_token="", http_client=client) + + @cached_property + def _async_client(self): + client = httpx.AsyncClient(**http, event_hooks={"request": [filter_async_headers]}) + return anthropic.AsyncAnthropic( + **self._client_params, auth_token="", http_client=client + ) + + effort = endpoint.reasoning_effort + options = {} + if effort == "none": + options["thinking"] = {"type": "disabled"} + elif effort: + options = {"thinking": {"type": "adaptive"}, "output_config": {"effort": effort}} + return PlatformAnthropic( + **common, base_url=endpoint.api_base.rstrip("/").removesuffix("/v1"), **options + ) + + class ModelFactory: """Unified factory for instantiating and caching LangChain chat models across providers.""" @@ -209,6 +279,8 @@ def get_model(cls, endpoint: ModelEndpoint) -> BaseChatModel: @classmethod def create_model(cls, endpoint: ModelEndpoint) -> BaseChatModel: + if endpoint.context_window is not None: + return _platform_chat_model(endpoint) if os.environ.get("ARTEMIS_FAKE_LLM") == "1": from artemis.llm.fake_model import FakeChatModel diff --git a/artemis/mcp/action_executor.py b/artemis/mcp/action_executor.py index 79b399cda..37649ec09 100644 --- a/artemis/mcp/action_executor.py +++ b/artemis/mcp/action_executor.py @@ -71,7 +71,17 @@ #: Non-device tools executed agent-side (never behind the action server). AGENT_TOOL_NAMES: frozenset[str] = ( - frozenset({"read_note", "list_notes", "ask_explorer", "video_analyzer"}) | HISTORY_TOOL_NAMES + frozenset( + { + "read_note", + "list_notes", + "ask_explorer", + "video_analyzer", + "check_visual_quality", + "check_audio_quality", + } + ) + | HISTORY_TOOL_NAMES ) #: Actions whose ``target`` is a single point: an element index or an [x, y] pair. @@ -190,7 +200,14 @@ async def _execute_device_action( (b.text for b in raw_result.content if getattr(b, "type", "") == "text"), f"Extension tool '{raw_name}' completed.", ) - res = ActionResult.success(raw_name, message) + payload = raw_result.structuredContent or {} + if "ok" in payload and "action" in payload: + res = ActionResult.model_validate(payload) + message = res.message + elif raw_result.isError: + res = ActionResult.failure(raw_name, message) + else: + res = ActionResult.success(raw_name, message) else: res = await session.call(wire_name, wire_args) message = finalize(res) if finalize else res.message @@ -256,6 +273,8 @@ def _observe_despite_failure(raw_name: str, res: ActionResult) -> bool: Argument and package lookup errors do not require an observation. """ + if raw_name == "browser_action": + return True if raw_name == "manage_app": return res.code not in (ActionCode.PACKAGE_NOT_FOUND, ActionCode.INVALID_ARGS) if raw_name == "wait_for_text": @@ -351,6 +370,20 @@ def _translate( recorded, ) + if raw_name == "perform_gesture": + from artemis.mcp.gestures import validate_phases + + try: + phases = validate_phases(args.get("phases")) + except (ValueError, TypeError) as exc: + raise _ArgError(f"Invalid gesture: {exc}") from exc + return ( + "perform_gesture", + {"phases": phases}, + None, + self._require_description(args, raw_name), + ) + if raw_name == "swipe": return self._translate_swipe(args, state, index_elements=index_elements) @@ -647,6 +680,13 @@ async def _execute_agent_tool( args.get("time_description") or args.get("TimeDescription") or "", args.get("purpose") or args.get("Purpose") or "", ) + elif raw_name in {"check_visual_quality", "check_audio_quality"}: + from artemis.tools.quality_tool import QUALITY_TOOLS + + tool = next(t for t in QUALITY_TOOLS if t.name == raw_name) + result = await tool.execute(ctx=self.ctx, state=state, **args) + text = json.dumps(result, ensure_ascii=False) + ok = result["status"] == "completed" elif raw_name in HISTORY_TOOL_NAMES: text, blocks = await self._history_tool(raw_name, args) else: diff --git a/artemis/mcp/action_manifest.py b/artemis/mcp/action_manifest.py index 735024a83..582e5b1b7 100644 --- a/artemis/mcp/action_manifest.py +++ b/artemis/mcp/action_manifest.py @@ -79,6 +79,7 @@ "long_press", "input_text", "swipe", + "perform_gesture", "press_key", "manage_app", "wait_for_delay", @@ -121,6 +122,9 @@ "ask_diagnoser", "ask_committee", "video_analyzer", + "check_visual_quality", + "check_audio_quality", + "read_quality_checks", "run_adb_command", "manage_task", "analyze_task_output", @@ -291,7 +295,8 @@ def filter_declarations( for decl in declarations # Only device actions are gated. Backend-independent tools and anything the # manifest does not classify (e.g. an agent's own bespoke tool) pass through. - if _declaration_name(decl) not in DEVICE_ACTIONS or _declaration_name(decl) in available + if (_declaration_name(decl) not in DEVICE_ACTIONS or _declaration_name(decl) in available) + and _declaration_name(decl) not in getattr(actuator, "unsupported_tools", ()) ] for ext in actuator.extensions(): diff --git a/artemis/mcp/action_names.py b/artemis/mcp/action_names.py index 78cef0a5c..dcc76d6fa 100644 --- a/artemis/mcp/action_names.py +++ b/artemis/mcp/action_names.py @@ -35,6 +35,7 @@ "tap": "click", "long_press_on": "long_press", "swipe": "swipe", + "perform_gesture": "perform_gesture", "focus_and_input_text": "input_text", "focus_and_clear_text": "focus_and_clear_text", "erase_one_char": "erase_one_char", @@ -106,6 +107,11 @@ def to_canonical_call( "duration_ms": action_item.get("duration", 1000), } + if verb == "perform_gesture": + from artemis.mcp.gestures import validate_phases + + return "perform_gesture", {"phases": validate_phases(action_item.get("phases"))} + if verb == "swipe": coords = action_item.get("normalized_coordinates") if not (isinstance(coords, (list, tuple)) and len(coords) == 4): diff --git a/artemis/mcp/action_specs.py b/artemis/mcp/action_specs.py index 1ea69a11b..7011abe5e 100644 --- a/artemis/mcp/action_specs.py +++ b/artemis/mcp/action_specs.py @@ -64,7 +64,9 @@ from langchain_core.tools import StructuredTool from mcp.types import CallToolResult -from pydantic import Field, create_model +from pydantic import BaseModel, Field, create_model + +from artemis.mcp.gestures import GestureInput, validate_phases from artemis.core.tool_declaration import ToolDeclaration from artemis.mcp.action_types import ActionResult @@ -86,6 +88,21 @@ ] +GESTURE_DESCRIPTION = ( + "[ACTION] Perform continuous touch gestures that a normal swipe cannot express: " + "simultaneous multi-finger input, continuous holds and drags, or delayed release. " + "Coordinates use 0-1000 screen space. In explicit phases, pointers move together; " + "a one-point path holds still. Keep the same pointer IDs and join endpoints across " + "phases to maintain contact until the final release. Optional control_points " + "define a cubic Bezier path with two endpoints and two controls. " + "Alternatively, provide one long_press_drag entry with start and end coordinates " + "and optional control_points. The endpoint is freely chosen, including inside the screen. " + "duration_ms is movement time; " + "release_delay_ms is the endpoint hold before lifting (zero releases immediately). " + "Observe the screen afterward to verify the intended effect." +) + + # --- Spec structure ------------------------------------------------------------------ @@ -206,6 +223,10 @@ async def _wire_input_text(actuator: Any, a: dict[str, Any]) -> ActionResult: return await actuator.input_text(a["text"], norm, clear_exist=a["clear_exist"]) +async def _wire_perform_gesture(actuator: Any, a: dict[str, Any]) -> ActionResult: + return await actuator.perform_gesture(validate_phases(a["phases"])) + + async def _wire_swipe(actuator: Any, a: dict[str, Any]) -> ActionResult: start, end = a["start"], a["end"] return await actuator.swipe( @@ -463,6 +484,27 @@ async def _wire_focus_and_clear_text(actuator: Any, a: dict[str, Any]) -> Action " the wire; required only for coordinate targets." ), ), + ActionSpec( + name="perform_gesture", + operator=OperatorDialect( + description=GESTURE_DESCRIPTION + + " target_description states the intended surface/objects and gesture purpose, not a claimed observation.", + params=( + ParamSpec( + "phases", + list[GestureInput], + "Explicit continuous phases or a single native long_press_drag object.", + ), + ParamSpec("target_description", str, "Target surface/objects and gesture purpose."), + ), + ), + wire=WireDialect( + description=GESTURE_DESCRIPTION, + params=(ParamSpec("phases", list[GestureInput]),), + bind=_wire_perform_gesture, + ), + differences="target_description is recorded by the agent and is not sent to the helper.", + ), ActionSpec( name="swipe", operator=OperatorDialect( @@ -686,6 +728,7 @@ async def _wire_focus_and_clear_text(actuator: Any, a: dict[str, Any]) -> Action "click", "input_text", "swipe", + "perform_gesture", "press_key", "manage_app", "wait_for_delay", @@ -765,6 +808,20 @@ def _json_schema(annotation: Any) -> dict[str, Any]: ``required`` flag says so); they never appear in the projected schema, so the declaration carries no ``null`` alternatives or ``default`` noise. """ + if isinstance(annotation, type) and issubclass(annotation, BaseModel): + schema = annotation.model_json_schema() + definitions = schema.get("$defs", {}) + + def inline(value): + if isinstance(value, list): + return [inline(v) for v in value] + if not isinstance(value, dict): + return value + if "$ref" in value: + return inline(definitions[value["$ref"].split("/")[-1]]) + return {k: inline(v) for k, v in value.items() if k not in ("$defs", "title")} + + return inline(schema) origin = get_origin(annotation) if origin in (Union, types.UnionType): members = [a for a in get_args(annotation) if a is not type(None)] diff --git a/artemis/mcp/actuators/adb.py b/artemis/mcp/actuators/adb.py index 4580e436b..85fe3f940 100644 --- a/artemis/mcp/actuators/adb.py +++ b/artemis/mcp/actuators/adb.py @@ -186,6 +186,32 @@ async def long_press(self, nx: int, ny: int, duration_ms: int = 1000) -> ActionR duration_ms=duration_ms, ) + async def perform_gesture(self, phases: list[dict]) -> ActionResult: + from artemis.mcp.gestures import validate_phases + + phases = validate_phases(phases) + result = await self.controller.perform_gesture(phases) + if not ( + result.get("success") is True + and result.get("status") == "completed" + and result.get("release_confirmed") is True + ): + return ActionResult.failure( + "perform_gesture", + f"Gesture {result.get('status', 'failed')}: {result.get('error', 'input not completed')}", + code={ + "unsupported": ActionCode.UNSUPPORTED, + "invalid_arguments": ActionCode.INVALID_ARGS, + "timeout": ActionCode.TIMEOUT, + }.get(result.get("status"), ActionCode.DEVICE_ERROR), + detail=str(result), + ) + return ActionResult.success( + "perform_gesture", + "Gesture completed. Observe the screen to verify the intended effect.", + detail=str(result), + ) + async def input_text( self, text: str, diff --git a/artemis/mcp/actuators/base.py b/artemis/mcp/actuators/base.py index 1dd495531..f2b035761 100644 --- a/artemis/mcp/actuators/base.py +++ b/artemis/mcp/actuators/base.py @@ -75,6 +75,8 @@ async def input_text( clear_exist: bool = True, ) -> ActionResult: ... + async def perform_gesture(self, phases: list[dict]) -> ActionResult: ... + async def swipe( self, start: tuple[int, int], diff --git a/artemis/mcp/actuators/browser.py b/artemis/mcp/actuators/browser.py new file mode 100644 index 000000000..3ee943b3f --- /dev/null +++ b/artemis/mcp/actuators/browser.py @@ -0,0 +1,149 @@ +"""Semantic browser tools exposed to the planner, operator and checker.""" + +from typing import Literal +from mcp.types import CallToolResult, TextContent + +from artemis.drivers.browser import BrowserConfig +from artemis.drivers.factory import get_driver +from artemis.mcp.action_manifest import ExtensionTool +from artemis.mcp.action_types import ActionResult +from artemis.mcp.actuators.ios import IOSActuator + + +class BrowserActuator(IOSActuator): + unsupported_tools = IOSActuator.unsupported_tools | {"manage_app", "press_key", "open_link"} + + def capabilities(self): + return super().capabilities() - {"manage_app", "press_key", "perform_gesture"} + + def extensions(self): + return [ + ExtensionTool( + name="browser_action", + description="Operate this attempt's isolated browser. Prefer semantic locators: by=role with role and name, label, text, placeholder or test_id; use css only when needed. frame is an optional iframe CSS selector. Actions: navigate (HTTP(S) value), click, fill (value), select (value), press (keyboard value), hover, check/uncheck, observe (URL, title, accessibility tree), tabs, switch_tab (index), dialog (value accept/dismiss, text for prompt), diagnostics. Actions are not assertions: use assert/check tools against the resulting page and screenshot. Never use mobile app, ADB or phone keys for browser tests. Ambiguous locators fail instead of clicking an arbitrary match.", + input_schema={ + "type": "object", + "properties": { + "action": { + "type": "string", + "enum": [ + "navigate", + "click", + "fill", + "select", + "press", + "hover", + "check", + "uncheck", + "observe", + "tabs", + "switch_tab", + "dialog", + "diagnostics", + ], + }, + "by": { + "type": "string", + "enum": ["role", "label", "text", "placeholder", "test_id", "css"], + }, + "name": {"type": "string"}, + "role": {"type": "string"}, + "value": {"type": "string"}, + "frame": {"type": "string"}, + "index": {"type": "integer"}, + "text": {"type": "string"}, + }, + "required": ["action"], + }, + handler=self.browser_action, + ) + ] + + async def browser_action( + self, + action: Literal[ + "navigate", + "click", + "fill", + "select", + "press", + "hover", + "check", + "uncheck", + "observe", + "tabs", + "switch_tab", + "dialog", + "diagnostics", + ], + by: Literal["role", "label", "text", "placeholder", "test_id", "css"] = "role", + name: str = "", + role: str = "button", + value: str = "", + frame: str = "", + index: int = 0, + text: str = "", + ) -> CallToolResult: + driver = get_driver(self.ctx) + try: + await driver.connect() + page = driver.page + coordinates = None + if action == "navigate": + BrowserConfig.valid_url(value) + await page.goto(value, wait_until="domcontentloaded") + message = f"Navigated to {page.url}" + elif action == "observe": + message = f"URL: {page.url}\nTitle: {await page.title()}\n{(await page.locator('body').aria_snapshot())[:20000]}" + elif action == "diagnostics": + import json + + message = json.dumps(driver.events, ensure_ascii=False) + elif action == "tabs": + message = "\n".join(f"{i}: {p.url}" for i, p in enumerate(driver.context.pages)) + elif action == "switch_tab": + if index < 0 or index >= len(driver.context.pages): + raise ValueError("Unknown tab index; use tabs first") + driver.page = driver.context.pages[index] + message = f"Selected tab {index}: {driver.page.url}" + elif action == "dialog": + if value not in {"accept", "dismiss"}: + raise ValueError("Dialog value must be accept or dismiss") + driver.next_dialog = value, text + message = f"Next native dialog will {value}; trigger it in a subsequent action" + else: + scope = page.frame_locator(frame) if frame else page + if by == "role": + locator = scope.get_by_role(role, name=name, exact=True) + elif by == "css": + locator = scope.locator(name) + else: + locator = getattr(scope, f"get_by_{by}")( + name, **({} if by == "test_id" else {"exact": True}) + ) + await locator.scroll_into_view_if_needed() + box = await locator.bounding_box() + if box: + coordinates = [ + round((box["x"] + box["width"] / 2) * 1000 / driver.options.width), + round((box["y"] + box["height"] / 2) * 1000 / driver.options.height), + ] + method = "select_option" if action == "select" else action + await getattr(locator, method)(value) if action in { + "fill", + "select", + "press", + } else await getattr(locator, method)() + message = f"{action}: {by}={name}. Verify the resulting page against the expected outcome." + result = ActionResult.success( + "browser_action", message, normalized_coordinates=coordinates + ) + except Exception as exc: + result = ActionResult.failure( + "browser_action", f"Browser action {action} failed: {str(exc)[:1000]}" + ) + return CallToolResult( + content=[TextContent(type="text", text=result.message)], + structuredContent=result.model_dump(mode="json"), + isError=False, + ) diff --git a/artemis/mcp/actuators/ios.py b/artemis/mcp/actuators/ios.py new file mode 100644 index 000000000..db64bff89 --- /dev/null +++ b/artemis/mcp/actuators/ios.py @@ -0,0 +1,54 @@ +"""iOS actions through the shared controller, without Android shell fallbacks.""" + +from artemis.mcp.action_types import ActionResult +from artemis.mcp.actuators.adb import AdbActuator + + +class IOSActuator(AdbActuator): + # The inherited coordinate operations delegate to the platform driver. + unsupported_tools = frozenset( + { + "run_adb_command", + "manage_task", + "video_analyzer", + "check_visual_quality", + "check_audio_quality", + } + ) + + def capabilities(self): + return frozenset( + { + "click", + "click_sequence", + "long_press", + "swipe", + "perform_gesture", + "press_key", + "input_text", + "manage_app", + "wait_for_delay", + "wait_for_text", + "observe_screen", + "take_screenshot", + "get_ui_hierarchy", + } + ) + + async def input_text(self, text, target=None, clear_exist=True): + if target: + result = await self.click(*target) + if not result.ok: + return result + await self.controller.type_text(text, clear_existing=clear_exist) + return ActionResult.success("input_text", "Text entered. Observe the screen to verify it.") + + async def manage_app(self, action, app_name): + # Accept an explicit bundle ID; never infer an Android package or retry a mutation. + if action.lower() == "launch": + await self.controller.launch_app(app_name) + elif action.lower() == "stop": + await self.controller.terminate_app(app_name) + else: + return ActionResult.failure("manage_app", "Use launch or stop with an iOS bundle ID") + return ActionResult.success("manage_app", "App command accepted. Verify its screen state.") diff --git a/artemis/mcp/gestures.py b/artemis/mcp/gestures.py new file mode 100644 index 000000000..eee09e93c --- /dev/null +++ b/artemis/mcp/gestures.py @@ -0,0 +1,113 @@ +# 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. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Validated, executor-neutral continuous touch plans (0..1000 coordinates).""" + +from typing import Annotated, Any, Literal +from pydantic import BaseModel, ConfigDict, Field, StrictInt, model_validator + +Coordinate = Annotated[StrictInt, Field(ge=0, le=1000)] +Point = Annotated[list[Coordinate], Field(min_length=2, max_length=2)] + + +class GesturePointer(BaseModel): + model_config = ConfigDict(extra="forbid") + id: Annotated[StrictInt, Field(ge=0, le=9)] + path: Annotated[list[Point], Field(min_length=1, max_length=128)] + control_points: Annotated[list[Point], Field(min_length=2, max_length=2)] | None = Field( + default=None, + description="Two cubic Bezier control points. When supplied, path must contain only start and end; Android builds the curve natively.", + ) + + @model_validator(mode="after") + def curve_endpoints(self): + if self.control_points is not None and len(self.path) != 2: + raise ValueError("A cubic Bezier path requires exactly start and end") + return self + + +class GesturePhase(BaseModel): + model_config = ConfigDict(extra="forbid") + duration_ms: Annotated[StrictInt, Field(ge=1, le=5000)] + pointers: Annotated[list[GesturePointer], Field(min_length=1, max_length=10)] + + +class LongPressDrag(BaseModel): + """Hold, move to a caller-selected endpoint, optionally dwell, then release.""" + + model_config = ConfigDict(extra="forbid") + kind: Literal["long_press_drag"] + start: Point + end: Point + control_points: Annotated[list[Point], Field(min_length=2, max_length=2)] | None = Field( + default=None, + description="Two cubic Bezier controls between start and end. Omit for a straight path.", + ) + duration_ms: Annotated[StrictInt, Field(ge=1, le=5000)] = 800 + hold_ms: Annotated[StrictInt, Field(ge=1, le=5000)] | None = Field( + default=None, description="Omit to use the device long-press timeout plus 150ms." + ) + release_delay_ms: Annotated[StrictInt, Field(ge=0, le=5000)] = Field( + default=0, + description="Keep the same finger down at the endpoint for this long, then lift. Zero lifts immediately after moving; independent of movement duration.", + ) + + +GestureInput = GesturePhase | LongPressDrag + + +class GesturePlan(BaseModel): + model_config = ConfigDict(extra="forbid") + phases: Annotated[list[GestureInput], Field(min_length=1, max_length=32)] + + @model_validator(mode="after") + def continuous(self): + if any(isinstance(p, LongPressDrag) for p in self.phases): + if len(self.phases) != 1: + raise ValueError( + "long_press_drag must be the only entry; it includes hold, move and release" + ) + return self + if sum(p.duration_ms for p in self.phases) > 30000: + raise ValueError("Total gesture duration must not exceed 30000ms") + ends = None + for phase in self.phases: + ids = [p.id for p in phase.pointers] + if len(ids) != len(set(ids)): + raise ValueError("Pointer IDs must be unique within a phase") + if ends is not None: + if set(ids) != set(ends): + raise ValueError("Keep the same pointer IDs across all phases") + if any(p.path[0] != ends[p.id] for p in phase.pointers): + raise ValueError("Each continuation must start at the previous endpoint") + ends = {p.id: p.path[-1] for p in phase.pointers} + return self + + +def validate_phases(phases: Any) -> list[dict]: + """Validate before dispatch; never coerce strings/floats/bools into coordinates.""" + return GesturePlan(phases=phases).model_dump(exclude_none=True)["phases"] + + +def gesture_duration_bound_ms(phases: list[dict]) -> int: + """Bound transport timeout including APK-resolved hold and endpoint dwell.""" + return sum( + p["duration_ms"] + + ( + p.get("hold_ms", 5000) + p.get("release_delay_ms", 0) + if p.get("kind") == "long_press_drag" + else 0 + ) + for p in phases + ) diff --git a/artemis/runtime/device_pool.py b/artemis/runtime/device_pool.py index c67aa5381..d4afa3150 100644 --- a/artemis/runtime/device_pool.py +++ b/artemis/runtime/device_pool.py @@ -17,12 +17,12 @@ from __future__ import annotations import asyncio -from dataclasses import dataclass import os import shutil import subprocess import threading import time +from dataclasses import dataclass from typing import Any from artemis.runtime.device_lock import DeviceExecutionLock @@ -301,6 +301,28 @@ async def warm_up_async( def _build_statuses( self, raw_devices: list[tuple[str, str, str | None, str | None]] ) -> list[DeviceStatus]: + raw_devices = list(raw_devices) + ios_udid = os.getenv("IOS_UDID") + if ios_udid and not any(row[0] == ios_udid for row in raw_devices): + from artemis.drivers.ios.appium_driver import probe_ios + + try: + info = probe_ios(ios_udid) + raw_devices.append((ios_udid, "device", info.get("model", "iPhone"), "ios")) + except Exception: + raw_devices.append((ios_udid, "offline", "iPhone", "ios")) + from artemis.drivers.browser import browser_slots, installed_engines, slot_available + + available = installed_engines() + raw_devices.extend( + ( + slot, + "device" if available and slot_available(slot) else "offline", + "Browser slot", + "browser", + ) + for slot in browser_slots() + ) active_owners = DeviceExecutionLock.get_active_owners() devices: list[DeviceStatus] = [] @@ -349,19 +371,27 @@ async def list_devices_async(self) -> list[DeviceStatus]: to an empty list -- use try_list_devices_async when the caller must tell the two apart. """ - return self._build_statuses(await self._enumerate_async() or []) + return await asyncio.to_thread(self._build_statuses, await self._enumerate_async() or []) def try_list_devices(self) -> list[DeviceStatus] | None: """Like list_devices, but returns None when enumeration failed and no usable snapshot exists, so callers can distinguish "could not ask adb" from "adb answered: no devices attached".""" raw = self._enumerate_sync() - return None if raw is None else self._build_statuses(raw) + return ( + None + if raw is None and not os.getenv("IOS_UDID") and not os.getenv("ARTEMIS_BROWSER_SLOTS") + else self._build_statuses(raw or []) + ) async def try_list_devices_async(self) -> list[DeviceStatus] | None: """Async variant of try_list_devices.""" raw = await self._enumerate_async() - return None if raw is None else self._build_statuses(raw) + return ( + None + if raw is None and not os.getenv("IOS_UDID") and not os.getenv("ARTEMIS_BROWSER_SLOTS") + else await asyncio.to_thread(self._build_statuses, raw or []) + ) @staticmethod def _explicit_serial_error( @@ -448,6 +478,10 @@ async def select_device_async(self, preferred_serial: str | None = None) -> str def _pick_device( self, all_devs: list[DeviceStatus], preferred_serial: str | None ) -> str | None: + # Browser resources require explicit browser admission; never auto-select + # one for a legacy Android request. + if not preferred_serial: + all_devs = [d for d in all_devs if d.product != "browser"] ready_devs = [d for d in all_devs if d.state == "device"] if preferred_serial: diff --git a/artemis/sdk/agent.py b/artemis/sdk/agent.py index c0c0da08b..dc723dbe6 100644 --- a/artemis/sdk/agent.py +++ b/artemis/sdk/agent.py @@ -16,7 +16,6 @@ import inspect import os import re - import uuid from pathlib import Path @@ -46,9 +45,9 @@ from artemis.sdk.run_outcome import attach_test_summary, resolve_trace_suffix from artemis.sdk.types.agent import AgentConfig from artemis.utils.startup_progress import publish_startup_progress +from third_party.mobile_use.sdk.agent import AgentBase, TOutput from third_party.mobile_use.sdk.types.exceptions import AgentError from third_party.mobile_use.sdk.types.task import Task -from third_party.mobile_use.sdk.agent import AgentBase, TOutput from third_party.mobile_use.utils.logger import get_logger logger = get_logger(__name__) @@ -96,13 +95,22 @@ def __init__( session_id or os.getenv("ARTEMIS_SESSION_ID") or os.getenv("ARTEMIS_CLOUD_SESSION_ID") ) self._session_id: str | None = str(raw_sid).strip() if raw_sid else None - target_dev = device_serial or device_id + target_dev = device_serial or device_id or (config.device_id if config else None) + from artemis.drivers.ios.appium_driver import configured_ios + + platform = ( + DevicePlatform.BROWSER + if os.getenv("ARTEMIS_BROWSER_CONFIG") + else DevicePlatform.IOS + if configured_ios(target_dev) + else (config.device_platform if config else DevicePlatform.ANDROID) + ) if config is None: from artemis.sdk.builders import Builders builder = Builders.AgentConfig if target_dev: - builder.for_device(DevicePlatform.ANDROID, target_dev) + builder.for_device(platform, target_dev) if concurrency_mode: builder.with_concurrency_mode(concurrency_mode) if max_concurrency is not None: @@ -113,7 +121,7 @@ def __init__( updates = {} if target_dev: updates["device_id"] = target_dev - updates["device_platform"] = DevicePlatform.ANDROID + updates["device_platform"] = platform if concurrency_mode: updates["concurrency_mode"] = str(concurrency_mode).strip().lower() if max_concurrency is not None: @@ -126,6 +134,116 @@ def __init__( self._initialized = False self._task_lock = asyncio.Lock() + async def init( + self, api_key=None, device_id=None, device_serial=None, retry_count=5, retry_wait_seconds=5 + ): + target = device_serial or device_id or self._config.device_id + from artemis.drivers.ios.appium_driver import client_for, configured_ios + + if self._config.device_platform == DevicePlatform.BROWSER: + from artemis.drivers.browser import BrowserConfig + from artemis.platform import platform as host_platform + from third_party.mobile_use.context import DeviceContext + + options = BrowserConfig.from_env() + self._config = self._config.model_copy( + update={ + "device_id": target, + "disable_device_probes": True, + "video_recording_tools_enabled": False, + } + ) + self._adb_client = self._ui_adb_client = None + self._device_context = DeviceContext( + host_platform=host_platform.os_type.name, + mobile_platform=DevicePlatform.BROWSER, + device_id=target, + device_width=options.width, + device_height=options.height, + ) + self._initialized = True + return True + if self._config.device_platform != DevicePlatform.IOS and not configured_ios(target): + return await super().init( + api_key, device_id, device_serial, retry_count, retry_wait_seconds + ) + if not configured_ios(target): + raise AgentError("Configure IOS_UDID and the node-owned IOS_SESSION_FILE first") + from artemis.platform import platform as host_platform + from third_party.mobile_use.context import DeviceContext + + self._config = self._config.model_copy( + update={ + "device_id": target, + "device_platform": DevicePlatform.IOS, + "disable_device_probes": True, + "video_recording_tools_enabled": False, + } + ) + self._adb_client = self._ui_adb_client = None + client = client_for(target) + try: + await asyncio.to_thread(client.attach) + frame = await asyncio.to_thread(client.screenshot) + finally: + client.close() + self._device_context = DeviceContext( + host_platform=host_platform.os_type.name, + mobile_platform=DevicePlatform.IOS, + device_id=target, + device_width=frame["width"], + device_height=frame["height"], + ) + self._initialized = True + asyncio.create_task(self._prewarm_llm_connections(api_key)) + return True + + async def _prepare_app_lock(self, task, context): + if self._config.device_platform == DevicePlatform.BROWSER: + from artemis.drivers.factory import get_driver + + await get_driver(context).connect() + return + if self._config.device_platform != DevicePlatform.IOS: + return await super()._prepare_app_lock(task, context) + bundle = task.request.locked_app_package + if not bundle: + return + from artemis.context import AppLaunchResult + from artemis.drivers.factory import get_driver + + driver = get_driver(context) + current = await driver.get_current_package() + if current != bundle: + await driver.launch_app(bundle) # Single mutation; only observation is polled. + for _ in range(10): + current = await driver.get_current_package() + if current == bundle: + break + await asyncio.sleep(0.5) + if current != bundle: + raise AgentError("iOS target app did not become foreground; inspect the device") + context.execution_setup.app_lock_status = AppLaunchResult( + locked_app_package=bundle, + locked_app_initial_launch_success=True, + locked_app_initial_launch_error=None, + ) + + async def _prepare_app_installation(self, task): + if self._config.device_platform == DevicePlatform.BROWSER: + if task.request.app_path or task.request.locked_app_package: + raise AgentError( + "Browser execution does not accept mobile app installation or locking" + ) + return None + if self._config.device_platform == DevicePlatform.IOS: + if task.request.app_path: + raise AgentError( + "Install the signed iOS app before running the case; APK installation is unavailable" + ) + return None + return await super()._prepare_app_installation(task) + async def _prewarm_llm_connections(self, api_key: str | None = None): """Pre-warms the HTTP2/gRPC connection pools for both Native GenAI and LangChain clients in the background.""" if os.environ.get("ARTEMIS_FAKE_LLM") == "1": @@ -209,6 +327,13 @@ async def clean(self, force: bool = False): logger.info("✅ Artemis agent stopped.") async def _ensure_device_unlocked(self) -> None: + if getattr(self._device_context, "mobile_platform", None) == DevicePlatform.BROWSER: + return + if getattr(self._device_context, "mobile_platform", None) == DevicePlatform.IOS: + from artemis.drivers.ios.appium_driver import probe_ios + + await asyncio.to_thread(probe_ios, self._device_context.device_id) + return """Reject secure keyguard instead of allowing an agent to guess credentials.""" if self._adb_client is None: raise AgentError("ADB client is not initialized.") @@ -283,6 +408,15 @@ async def _prepare_device_environment(self, context: ArtemisContext): def _prepare_tracing(self, task: Task, context: ArtemisContext): """Prepare tracing and data engine setup.""" task_name = self._prepare_trace_paths(task) + if self._config.device_platform == DevicePlatform.IOS: + from artemis.mcp.actuators.ios import IOSActuator + + context.actuator = IOSActuator(context) + + if self._config.device_platform == DevicePlatform.BROWSER: + from artemis.mcp.actuators.browser import BrowserActuator + + context.actuator = BrowserActuator(context) context.execution_setup = ExecutionSetup( traces_path=self._tmp_traces_dir, diff --git a/artemis/services/llm.py b/artemis/services/llm.py index ec91e6fa0..4efc5bc98 100644 --- a/artemis/services/llm.py +++ b/artemis/services/llm.py @@ -870,6 +870,23 @@ async def acomplete_structured( ).__call__ +def _platform_endpoint() -> ModelEndpoint | None: + from artemis.config.run_model import current_run_model + + selected = current_run_model() + if selected is None: + return None + model, key = selected + return ModelEndpoint( + provider=ModelProvider.from_string(model.api_schema), + model_name=model.model_id, + api_base=model.url, + api_key=key.get_secret_value(), + reasoning_effort=model.thinking_effort if model.thinking_effort != "default" else None, + context_window=model.context_window, + ) + + # Backward compatible factory functions delegating to ModelFactory def get_google_llm( model_name: str = "gemini-3.8-flash", @@ -880,6 +897,8 @@ def get_google_llm( include_thoughts: bool | None = None, enable_grounding: bool = False, ) -> BaseChatModel: + if endpoint := _platform_endpoint(): + return ModelFactory.get_model(endpoint) ep = ModelEndpoint( provider=ModelProvider.GOOGLE, model_name=model_name, @@ -900,6 +919,8 @@ def _resolve_endpoint( use_fallback: bool = False, ) -> ModelEndpoint: """Cleanly resolves a ModelEndpoint from context llm_config.""" + if endpoint := _platform_endpoint(): + return endpoint if getattr(ctx, "llm_config", None) is None: try: ctx.llm_config = get_default_llm_config() diff --git a/artemis/tools/command_tool.py b/artemis/tools/command_tool.py index 96619f6bf..888b1e886 100644 --- a/artemis/tools/command_tool.py +++ b/artemis/tools/command_tool.py @@ -37,19 +37,19 @@ """ import asyncio -from asyncio.subprocess import Process as AsyncProcess -from collections import deque import os import shlex -from typing import Any, Literal import uuid +from asyncio.subprocess import Process as AsyncProcess +from collections import deque +from typing import Any, Literal from langchain_core.tools import BaseTool from pydantic import BaseModel, Field -from artemis.core.tool_failure import ToolFailure from artemis.agents.log_analyzer.output_analyzer import TaskOutputAnalyzerNode from artemis.context import ArtemisContext +from artemis.core.tool_failure import ToolFailure from artemis.data_engine.trace import trace_langchain_tool from artemis.drivers.base import BaseDeviceDriver from artemis.tools.base import ArtemisTool @@ -645,6 +645,8 @@ async def execute( Interactive: bool = False, **kwargs: Any, ) -> str: + if str(getattr(getattr(ctx, "device", None), "mobile_platform", "")) in {"ios", "browser"}: + return "Unsupported on this platform: Android shell commands are unavailable. Use platform actions." # Extract command line supporting alternative key formats cmd_line = ( CommandLine diff --git a/artemis/tools/quality_tool.py b/artemis/tools/quality_tool.py new file mode 100644 index 000000000..bb1cc1fb8 --- /dev/null +++ b/artemis/tools/quality_tool.py @@ -0,0 +1,259 @@ +"""Quality detectors as evidence-producing tools, shared by Pro and Flash. + +No ML runtime is imported here. Node-local workers own model weights and policy. +""" + +from __future__ import annotations + +import asyncio +import hashlib +import json +import os +from pathlib import Path +import time +from typing import Literal +from uuid import uuid4 + +import httpx +from pydantic import BaseModel, Field, model_validator + +from artemis.tools.base import ArtemisTool + +QUALITY_TOOL_NAMES = frozenset({"check_visual_quality", "check_audio_quality"}) +MAX_MEDIA_BYTES = 32 * 1024 * 1024 + + +class VisualQualityArgs(BaseModel): + source: Literal["screenshot", "recording"] = "screenshot" + purpose: str = Field( + min_length=1, + max_length=800, + description="The case expectation being checked; explain intentional black/silent intervals.", + ) + checks: list[str] = Field( + min_length=1, + max_length=10, + description="Required anomaly classes. Unsupported classes are inconclusive, never silently ignored.", + ) + start_seconds: float = Field(default=0, ge=0, allow_inf_nan=False) + end_seconds: float = Field( + default=0, + ge=0, + allow_inf_nan=False, + description="Session-relative end time. Recording ranges must be positive and at most 60 seconds; split longer checks.", + ) + + @model_validator(mode="after") + def range_valid(self): + if self.source == "recording" and not 0 < self.end_seconds - self.start_seconds <= 60: + raise ValueError("Recording range must be positive and at most 60 seconds") + return self + + +class AudioQualityArgs(BaseModel): + purpose: str = Field( + min_length=1, + max_length=800, + description="Expected audible content during this interval. Do not request silence_loss during intentional silence.", + ) + checks: list[str] = Field(min_length=1, max_length=7) + start_seconds: float = Field(ge=0, allow_inf_nan=False) + end_seconds: float = Field(ge=0, allow_inf_nan=False) + + @model_validator(mode="after") + def range_valid(self): + if not 0 < self.end_seconds - self.start_seconds <= 60: + raise ValueError("Recording range must be positive and at most 60 seconds") + return self + + +def quality_directory(ctx) -> Path: + engine = getattr(ctx, "data_engine", None) + if engine is None or not engine.current_session_id: + raise ValueError("An active evidence session is required") + directory = Path(engine.base_dir) / "quality" + directory.mkdir(parents=True, exist_ok=True) + return directory + + +def read_quality_results(directory: Path) -> list[dict]: + if not directory.is_dir(): + return [] + return sorted( + [json.loads(p.read_text()) for p in directory.glob("*.json")], key=lambda r: r["created_at"] + )[:200] + + +def configured_quality_tools(): + selected = json.loads(os.getenv("ARTEMIS_QUALITY_TOOLS", '["visual", "audio"]')) + return [ + tool + for tool in QUALITY_TOOLS + if tool.kind in selected and os.getenv(tool.env_name, "").strip() + ] + + +def quality_guidance() -> str: + names = [t.name for t in configured_quality_tools()] + if not names: + return "" + return ( + "\nQuality tools available: " + ", ".join(names) + ". " + "For explicit visual/audio technical quality expectations, plan and execute these checks. " + "Use original screenshots or the existing continuous recording; times are relative to the execution session start. " + "Check after the required media interval has elapsed, in ranges <=60 seconds, covering the full required interval. " + "A screenshot cannot prove absence of a transient fault over time. Select supported anomaly classes from tool descriptions. " + "Do not substitute UI observation for an explicit audio quality check. " + "An unavailable/error result, missing audio, unsampled intervals, or advisory policy cannot establish PASS. " + "Record the result ID and covered interval in the check evidence. " + "Exclude intentional black/silent intervals only when justified by the case. " + "Model scores are detector outputs, not calibrated certainty or proof of product failure." + ) + + +class QualityTool(ArtemisTool): + def __init__(self, kind): + self.kind = kind + self.env_name = "FRAMEGUARD_URL" if kind == "visual" else "AUDIOGUARD_URL" + classes = ( + "screen_corruption, black_screen, green_screen, blocking_artifact, mosaic, color_space_error" + if kind == "visual" + else "noise, harsh, clip_intermittent, distortion, hum, silence_loss, loudness_anomaly" + ) + super().__init__( + name=f"check_{kind}_quality", + args_schema=VisualQualityArgs if kind == "visual" else AudioQualityArgs, + description=f"[QUALITY] Check technical {kind} defects with a trained detector. Classes: {classes}. " + "Returns persisted evidence, model identity, covered interval and advisory/enforced verdict. " + "Call after capture; missing recording/audio/configuration is inconclusive. " + "Video sampling cannot rule out defects shorter than its sampling interval. No content understanding or AV-sync measurement.", + category="perception", + ) + + async def execute(self, driver=None, ctx=None, state=None, **kwargs): + args = self.args_schema.model_validate(kwargs) + directory = quality_directory(ctx) + if len(list(directory.glob("*.json"))) >= 200: + raise ValueError("Quality evidence limit reached (200 checks)") + result = dict( + id=uuid4().hex, + tool=self.name, + criterion=args.purpose, + status="unavailable", + verdict="inconclusive", + detector="FrameGuard" if self.kind == "visual" else "AudioGuard", + model_sha256="", + policy="advisory", + checks=args.checks, + events=[], + reason="", + evidence_digest=None, + evidence_type=None, + start_seconds=args.start_seconds, + end_seconds=args.end_seconds, + sample_interval_seconds=None, + step_number=getattr(getattr(ctx, "data_engine", None), "current_step_number", None), + created_at=time.time(), + ) + try: + endpoint = os.getenv(self.env_name, "").strip() + if not endpoint: + raise ValueError(f"{self.kind} detector is not configured") + if self.kind == "visual" and args.source == "screenshot": + # This is the original capture, before instruction overlays. + if driver is not None: + media = (await driver.get_screen_data(skip_settling=True)).screenshot_bytes + elif state and state.latest_screenshot: + media = Path(state.latest_screenshot).read_bytes() + else: + raise ValueError("No original screenshot available") + from io import BytesIO + from PIL import Image + + buf = BytesIO() + with Image.open(BytesIO(media)) as image: + image.convert("RGB").save(buf, "JPEG", quality=95) + media, media_type = buf.getvalue(), "image/jpeg" + else: + from artemis.controllers.controller_factory import get_controller + + segment = await get_controller(ctx).extract_quality_segment( + args.start_seconds, args.end_seconds + ) + if not segment.success or not segment.video_path: + raise ValueError( + segment.message or "No recording available for requested interval" + ) + path = Path(segment.video_path) + try: + if path.stat().st_size > MAX_MEDIA_BYTES: + raise ValueError("Recording exceeds 32 MiB; request a shorter interval") + media, media_type = path.read_bytes(), "video/mp4" + finally: + path.unlink(missing_ok=True) + path.parent.rmdir() + if not media or len(media) > MAX_MEDIA_BYTES: + raise ValueError("Empty media or media exceeds 32 MiB") + digest = hashlib.sha256(media).hexdigest() + asset = directory / digest + if not asset.exists(): + asset.write_bytes(media) + result.update(evidence_digest=digest, evidence_type=media_type) + async with httpx.AsyncClient(timeout=120, trust_env=False) as client: + response = await client.post( + endpoint.rstrip("/") + "/detect", + content=media, + params={"checks": ",".join(args.checks), "kind": self.kind}, + headers={"Content-Type": media_type}, + ) + if response.status_code == 422: + raise ValueError( + str(response.json().get("error", "Detector rejected media"))[:600] + ) + response.raise_for_status() + body = response.json() + # Strict normalized worker envelope. Do not trust a response's claimed verdict. + from artemis.tools.quality_types import DetectorResult + + detection = DetectorResult.model_validate(body) + if detection.detector != result["detector"] or set(detection.checks) != set( + args.checks + ): + raise ValueError("Detector response does not match this request") + result.update(detection.model_dump()) + if self.kind == "audio" or args.source == "recording": + if abs(detection.analyzed_seconds - (args.end_seconds - args.start_seconds)) > 0.5: + result.update( + status="inconclusive", + reason="Requested media interval was not fully analyzed", + ) + if any( + event.kind not in args.checks + or event.end_seconds > detection.analyzed_seconds + 0.5 + for event in detection.events + ): + raise ValueError("Detector returned invalid event labels or time bounds") + if result["status"] == "completed" and detection.policy == "enforced": + result["verdict"] = "failed" if detection.events else "passed" + else: + result["verdict"] = "inconclusive" + except asyncio.CancelledError: + result.update(status="error", reason="Detection cancelled; no conclusion") + _save(directory, result) + raise + except Exception as exc: + # Do not expose endpoint URLs/credentials in network exceptions. + reason = str(exc) if isinstance(exc, ValueError) else type(exc).__name__ + result.update(status="error", reason=reason[:600]) + _save(directory, result) + return result + + +def _save(directory, result): + target = directory / f"{result['id']}.json" + temporary = target.with_suffix(".tmp") + temporary.write_text(json.dumps(result, ensure_ascii=False)) + temporary.replace(target) + + +QUALITY_TOOLS = [QualityTool("visual"), QualityTool("audio")] diff --git a/artemis/tools/quality_types.py b/artemis/tools/quality_types.py new file mode 100644 index 000000000..3fefa754e --- /dev/null +++ b/artemis/tools/quality_types.py @@ -0,0 +1,32 @@ +"""Validated wire response from node-local quality workers.""" + +from typing import Literal +from pydantic import BaseModel, ConfigDict, Field, FiniteFloat, model_validator + + +class QualityEvent(BaseModel): + model_config = ConfigDict(extra="forbid") + kind: str = Field(max_length=80) + start_seconds: FiniteFloat = Field(ge=0) + end_seconds: FiniteFloat = Field(ge=0) + score: FiniteFloat | None = Field(default=None, ge=0, le=1) + + @model_validator(mode="after") + def ordered(self): + if self.end_seconds < self.start_seconds: + raise ValueError("Invalid event interval") + return self + + +class DetectorResult(BaseModel): + model_config = ConfigDict(extra="forbid") + detector: Literal["FrameGuard", "AudioGuard"] + status: Literal["completed", "inconclusive"] + model_sha256: str = Field(pattern=r"^[a-f0-9]{64}$") + policy: Literal["advisory", "enforced"] + checks: list[str] = Field(min_length=1, max_length=10) + events: list[QualityEvent] = Field(max_length=300) + reason: str = Field(max_length=600) + sample_interval_seconds: FiniteFloat | None = Field(default=None, gt=0) + analyzed_seconds: FiniteFloat = Field(ge=0) + threshold: FiniteFloat | None = Field(default=None, ge=0, le=1) diff --git a/docs/multi_touch.md b/docs/multi_touch.md new file mode 100644 index 000000000..6580a4cdc --- /dev/null +++ b/docs/multi_touch.md @@ -0,0 +1,124 @@ +# Advanced gesture input + +`perform_gesture` adds continuous and multi-finger input alongside the existing +`click` and `swipe` primitives. Use it when a normal swipe cannot express the +interaction. It uses the existing Operator, Validator, MCP and Android input path. + +Coordinates are integers from **0 to 1000**, relative to the current screen. Each +example below is a direct MCP call. Operator and Flash calls also require +`target_description`, describing the intended target and purpose. + +## Multi-touch + +All pointers in a phase start together. This example pinches inward; reverse the +paths to zoom outward. Add another pointer for a three-finger gesture. + +```json +{ + "action": "perform_gesture", + "phases": [{ + "duration_ms": 800, + "pointers": [ + {"id": 0, "path": [[300, 500], [450, 500]]}, + {"id": 1, "path": [[700, 500], [550, 500]]} + ] + }] +} +``` + +## Long press and drag + +Use `long_press_drag` to hold an object, move it to a chosen endpoint, optionally +hold there, then release. **The endpoint can be anywhere on screen.** + +```json +{ + "action": "perform_gesture", + "phases": [{ + "kind": "long_press_drag", + "start": [300, 400], + "end": [650, 550], + "hold_ms": 700, + "duration_ms": 800, + "release_delay_ms": 500 + }] +} +``` + +- `hold_ms`: initial long press, 1–5000 ms. If omitted, uses the device's configured + long-press timeout plus 150 ms. +- `duration_ms`: movement time, 1–5000 ms; default 800. +- `release_delay_ms`: time to stay pressed at `end`, 0–5000 ms; default 0. Zero + releases as soon as movement completes. A positive delay maintains contact + before release. + +For an edge dwell, choose an endpoint near the desired edge, such as +`"end": [980, 400]`, with a positive `release_delay_ms`. This is the same generic +drag operation. The target UI determines its edge activation region; inspect the +result afterward. + +### Curved drag + +Add two `control_points` for a cubic Bézier curve between the chosen `start` and +`end`. They shape the path; they do not replace or constrain its endpoint. + +```json +{ + "action": "perform_gesture", + "phases": [{ + "kind": "long_press_drag", + "start": [300, 400], + "end": [650, 550], + "control_points": [[400, 250], [600, 250]], + "duration_ms": 800, + "release_delay_ms": 500 + }] +} +``` + +Omit `control_points` for a straight path. The helper constructs the curve from +the supplied points. It never redirects the endpoint to an edge. + +## Explicit continuous phases + +For multiple pointers or intermediate waypoints, use explicit phases. Keep the +same pointer IDs across phases and start each path at its previous endpoint. +Contacts stay down between phases and lift after the final phase. A one-point +path holds still, allowing one pointer to hold while another moves. + +```json +{ + "action": "perform_gesture", + "phases": [ + {"duration_ms": 700, "pointers": [{"id": 0, "path": [[300, 400]]}]}, + {"duration_ms": 800, "pointers": [{"id": 0, "path": [[300, 400], [650, 550]]}]}, + {"duration_ms": 500, "pointers": [{"id": 0, "path": [[650, 550]]}]} + ] +} +``` + +An explicit pointer path may also contain `control_points: [[c1x,c1y],[c2x,c2y]]`; +then `path` must contain exactly the start and end. Do not mix a `long_press_drag` +entry with explicit phases in one call. + +Limits: 1–10 pointers, 1–32 phases, 1–128 path points per pointer, 1–5000 ms per +phase and at most 30000 ms total. Coordinates and controls must stay within +0–1000. Pointer IDs are unique integers from 0 to 9. Invalid plans are rejected +before input starts. + +## Compatibility and results + +The bundled helper is **v1.3.3 / version code 10**. Single-phase gestures support +Android 7+; continuous phases and `long_press_drag` require Android 8+. +Unsupported helpers return `UNSUPPORTED`. Multi-touch and continuous gestures +are never emulated with separate swipes. Ship the APK and its matching +`helper_manifest.json` together. + +Results use the existing `ActionResult` (`ok`, `code`, `message`). Success means +input completed; verify the intended UI effect afterward. A timeout does not +prove the input was never dispatched, so `perform_gesture` is not automatically +retried. Existing actions keep their retry and history behavior. + +Cancellation requests release of held contacts after the current bounded phase. +If release cannot be confirmed, the helper blocks further gesture injection until +recovery. This helper protection does not cover raw ADB input. diff --git a/integrations/quality/README.md b/integrations/quality/README.md new file mode 100644 index 000000000..ce7ee269b --- /dev/null +++ b/integrations/quality/README.md @@ -0,0 +1,58 @@ +# Quality detector tools + +The execution engine exposes `check_visual_quality` and `check_audio_quality` to both Pro and Flash. These are evidence tools; no PyTorch dependency is added to the engine. The planner receives capability guidance; the Checker can read persisted checks with the read-only `read_quality_checks` tool. + +## Node setup + +Install FrameGuard and AudioGuard in separate directories and install each repository's dependencies in its own Python environment. Provide compatible trained checkpoints; source repositories do not distribute weights. Run one worker per detector: + +```sh +/srv/frameguard/.venv/bin/python /srv/engine/integrations/quality/worker.py \ + --kind visual --repo /srv/frameguard \ + --checkpoint /srv/models/frameguard.pth --port 8071 +/srv/audioguard/.venv/bin/python /srv/engine/integrations/quality/worker.py \ + --kind audio --repo /srv/audioguard \ + --checkpoint /srv/models/audioguard.pt --port 8072 +``` + +Set these in the execution engine's local `.env` or service environment and restart its admin server before new tasks: + +```dotenv +FRAMEGUARD_URL=http://127.0.0.1:8071 +AUDIOGUARD_URL=http://127.0.0.1:8072 +``` + +Workers bind loopback by default, load weights once, use one CPU thread by default, and allow one in-flight analysis each. Busy workers return 503. Retry analysis rather than repeating device operations. Use a process supervisor for Linux deployment. No API keys or node tokens are needed. Do not publish workers on the Internet. + +Workers use the repository's checkpoint-compatible preprocessing. Both are offline inference paths; AudioGuard's historical per-clip-normalized checkpoint is not silently used as a streaming model. Worker requests are bounded to 32 MiB and contain media bytes, never arbitrary file paths or shell commands. `/health` reports the weight digest and policy. + +## Per-execution selection + +`POST /api/run` accepts `quality_tools: ["visual", "audio"]`; `[]` disables both. Omission retains standalone engine behavior (tools configured by node URLs). Each child process receives its own selection, so concurrent devices do not share mutable inference state. Kraken freezes this list in the batch definition and passes it through execution commands. + +Tool parameters express the testing intent and anomaly categories, not model URLs, weights, or thresholds. A natural-language case can say: “Play the sample and verify there is no black screen or unexpected audio interruption.” + +- Visual: `source=screenshot` captures original pixels before action overlays; `source=recording` analyzes a requested interval. +- Audio: analyzes an existing recording's actual audio track. No usable track is an error, not proof of silent playback. +- **Times are relative to execution session start**, matching the session history. A request must span 0–60 seconds; longer checks are split into bounded intervals after each has finished capturing. +- Continuous recording must be enabled before the relevant actions (the existing video-recording option). Tools do not retroactively manufacture missing recordings. +- Quality extraction is separate from the general video analyzer: native dimensions, no synthetic black gap fill, lossless audio re-encoding. Rotations/restarts crossing segment boundaries are inconclusive and require separate continuous segments. Frame extraction still involves video re-encoding; do not equate every codec artifact with a device rendering failure. +- FrameGuard inspects samples (default 0.2 s, maximum 300 samples). It returns anomaly sample times, not invented continuous durations; sub-interval faults can be missed. It uses per-frame predictions, not the video's majority label. +- AudioGuard returns detected anomaly intervals. Internal capture measures the digital audio chain, not physical speaker quality; external microphones/channel-to-SN assignment are not implemented here. + +## Verdict and evidence + +`status` describes analysis execution, independently of `verdict`. The default `advisory` policy always yields `inconclusive`, including when no selected anomaly is found. Use `--enforce` only after independent data validation and threshold calibration. Under enforced policy, complete analyzed samples with events are `failed`, without events `passed`; these are bounded observations, not proof outside the sampled interval. Match them against the case's expected state; intentional black/silent intervals must not be treated as failures. + +The final Checker is instructed to require recorded evidence for explicit quality expectations, match the full requested interval, and reject missing/advisory/incomplete checks as proof of PASS. This is evidence guidance in the existing agent judgment loop, **not a deterministic natural-language requirement parser or a guarantee that an LLM always invokes a tool**. The platform records individual quality verdicts separately from the engine's final functional verdict. + +Results are atomically saved under `/quality/.json`, media under its SHA-256 digest. Results include criterion, model SHA-256, policy, threshold, capture interval, sampling interval, events and step association. API: + +- `GET /api/sessions/{session_id}/quality` +- `GET /api/sessions/{session_id}/quality/media/{digest}` + +Kraken uploads both to the control plane, tied to an accepted physical execution command. Historical reports retain their original model/check data. The report shows original screenshots, playable clips, anomaly time navigation and the separate effect verdict. + +## Verification + +Unit tests: `tests/unit/tools/test_quality_tool.py` cover shared declarations, advisory/enforced semantics, invalid intervals, missing recordings, incomplete coverage, persistence and selection isolation. Task, agent and tool-manifest regressions also apply. Synthetic media + real checkpoints verify the integration path only; they are not a real-device accuracy benchmark. diff --git a/integrations/quality/worker.py b/integrations/quality/worker.py new file mode 100644 index 000000000..07f90485b --- /dev/null +++ b/integrations/quality/worker.py @@ -0,0 +1,268 @@ +"""Run with the detector repository's Python; no engine imports or model copies. + +One model per process, bounded single-flight inference. POST /detect accepts media +bytes, never caller-controlled paths, commands or checkpoint locations. +""" + +from __future__ import annotations +import argparse +import hashlib +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import threading +from urllib.parse import parse_qs, urlparse + +MAX_BYTES = 32 * 1024 * 1024 + + +class Detector: + def __init__(self, args): + sys.path.insert(0, str(Path(args.repo).resolve())) + import torch + + torch.set_num_threads(args.threads) + self.args = args + self.sha = hashlib.sha256(Path(args.checkpoint).read_bytes()).hexdigest() + self.device = torch.device("cpu") + if args.kind == "visual": + from src.predict import config_for_checkpoint, load_model, build_inference_transform + + config = config_for_checkpoint(args.checkpoint, None) + self.model = load_model(args.checkpoint, config, self.device) + self.transform = build_inference_transform( + tuple(config.data.image_size), + tuple(config.data.mean), + tuple(config.data.std), + bool(getattr(config.data, "letterbox", False)), + ) + names = config.model.class_names + if hasattr(names, "_data"): + names = names._data + self.names = {int(k): v for k, v in names.items()} + self.classes = set(self.names.values()) - {"normal"} + else: + from src.inference.offline import load_checkpoint + + self.config, self.model, self.thresholds, self.clip_thresholds = load_checkpoint( + args.checkpoint, self.device + ) + self.classes = set(self.config["classes"]) + + def detect(self, media, media_type, checks): + if not checks or set(checks) - self.classes: + raise ValueError( + "Unsupported or empty checks: " + ",".join(sorted(set(checks) - self.classes)) + ) + result = dict( + detector="FrameGuard" if self.args.kind == "visual" else "AudioGuard", + status="completed", + model_sha256=self.sha, + policy="enforced" if self.args.enforce else "advisory", + checks=checks, + events=[], + reason="Experimental model; validate on independent device samples before enforcing.", + sample_interval_seconds=None, + analyzed_seconds=0, + threshold=None, + ) + with tempfile.TemporaryDirectory(prefix="quality-") as tmp: + path = Path(tmp) / ("input.jpg" if media_type == "image/jpeg" else "input.mp4") + path.write_bytes(media) + if self.args.kind == "visual": + from src.predict import predict_image, predict_video + + if media_type == "image/jpeg": + frames = [ + predict_image( + str(path), self.model, self.transform, self.device, self.names + ) + ] + else: + data = predict_video( + str(path), + self.model, + self.transform, + self.device, + self.names, + max_frames=300, + frame_interval_sec=self.args.interval, + ) + frames = data["frame_results"] + from src.predict import get_video_info + + result["analyzed_seconds"] = float(get_video_info(str(path))[2]) + result["sample_interval_seconds"] = self.args.interval + if not frames: + raise ValueError("No decodable video frames") + # Sampling cap or decode gaps must not produce a clean verdict. + duration = result["analyzed_seconds"] + if ( + duration <= 0 + or frames[-1].get("timestamp", 0) + self.args.interval + 0.1 < duration + ): + result.update( + status="inconclusive", + reason="Video sample coverage is incomplete; use a shorter interval.", + ) + result["threshold"] = self.args.threshold + for frame in frames: + label = frame["class_name"] + score = float(frame["confidence"]) + if label in checks and score >= self.args.threshold: + at = float(frame.get("timestamp", 0)) + result["events"].append( + dict(kind=label, start_seconds=at, end_seconds=at, score=score) + ) + # Single-label predictions: report sampled points, not invented continuous durations. + else: + if media_type != "video/mp4": + raise ValueError("Audio check requires a recording with an audio track") + wav = Path(tmp) / "audio.wav" + converted = subprocess.run( + [ + "ffmpeg", + "-nostdin", + "-v", + "error", + "-i", + str(path), + "-map", + "0:a:0", + "-vn", + "-ac", + "1", + "-ar", + str(self.config["audio"]["sample_rate"]), + "-t", + "61", + str(wav), + ], + capture_output=True, + timeout=45, + ) + if converted.returncode: + raise ValueError( + "No usable audio track; capture was unavailable, not silent playback" + ) + from src.inference.offline import infer_file + + data = infer_file( + str(wav), + self.config, + self.model, + self.thresholds, + self.device, + clip_thresholds=self.clip_thresholds, + ) + result["analyzed_seconds"] = data["duration_s"] + if data["duration_s"] <= 0 or data["duration_s"] > 60.5: + raise ValueError("Audio duration outside supported range") + for segment in data["anomaly_segments"]: + if segment["class_name"] in checks: + result["events"].append( + dict( + kind=segment["class_name"], + start_seconds=segment["start_s"], + end_seconds=segment["end_s"], + score=None, + ) + ) + if len(result["events"]) > 300: + result.update( + status="inconclusive", reason="Event limit reached; inspect a shorter interval." + ) + result["events"] = result["events"][:300] + return result + + +def serve(detector, host, port): + lock = threading.Lock() + + class Handler(BaseHTTPRequestHandler): + def reply(self, status, data): + payload = json.dumps(data, ensure_ascii=False, allow_nan=False).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(payload))) + self.end_headers() + self.wfile.write(payload) + + def do_GET(self): + if self.path != "/health": + return self.reply(404, {"error": "Not found"}) + self.reply( + 200, + { + "kind": detector.args.kind, + "model_sha256": detector.sha, + "policy": "enforced" if detector.args.enforce else "advisory", + }, + ) + + def do_POST(self): + parsed = urlparse(self.path) + if parsed.path != "/detect": + return self.reply(404, {"error": "Not found"}) + query = parse_qs(parsed.query) + if query.get("kind", [""])[0] != detector.args.kind: + return self.reply(422, {"error": "Wrong detector kind"}) + content_type = self.headers.get("Content-Type") + if content_type not in {"image/jpeg", "video/mp4"}: + return self.reply(415, {"error": "Unsupported media"}) + try: + size = int(self.headers.get("Content-Length", "0")) + except ValueError: + size = 0 + if not 0 < size <= MAX_BYTES: + return self.reply(413, {"error": "Media must be 1 byte to 32 MiB"}) + if not lock.acquire(blocking=False): + return self.reply( + 503, {"error": "Detector busy; retry analysis without repeating device actions"} + ) + try: + self.connection.settimeout(120) + media = self.rfile.read(size) + if len(media) != size: + raise ValueError("Incomplete upload") + self.reply( + 200, + detector.detect(media, content_type, query.get("checks", [""])[0].split(",")), + ) + except Exception as exc: + self.reply( + 422, + { + "error": str(exc)[:500] + if isinstance(exc, ValueError) + else type(exc).__name__ + }, + ) + finally: + lock.release() + + ThreadingHTTPServer((host, port), Handler).serve_forever() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--kind", choices=["visual", "audio"], required=True) + parser.add_argument("--repo", required=True) + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--host", default="127.0.0.1") + parser.add_argument("--port", type=int, required=True) + parser.add_argument("--threads", type=int, default=1) + parser.add_argument("--interval", type=float, default=0.2) + parser.add_argument("--threshold", type=float, default=0.85) + parser.add_argument( + "--enforce", + action="store_true", + help="Only after independent validation and policy calibration", + ) + args = parser.parse_args() + if not 0 < args.interval <= 1 or not 0 <= args.threshold <= 1 or args.threads < 1: + parser.error("Invalid interval, threshold or thread count") + serve(Detector(args), args.host, args.port) diff --git a/packages/artemis-accessibility-helper/.gitignore b/packages/artemis-accessibility-helper/.gitignore index afc00f55c..7e1f85755 100644 --- a/packages/artemis-accessibility-helper/.gitignore +++ b/packages/artemis-accessibility-helper/.gitignore @@ -3,3 +3,4 @@ build/ .gradle/ *.class .DS_Store +local.properties diff --git a/packages/artemis-accessibility-helper/ArtemisAccessibilityHelper.apk b/packages/artemis-accessibility-helper/ArtemisAccessibilityHelper.apk index 16f448009..be68bfbfb 100644 Binary files a/packages/artemis-accessibility-helper/ArtemisAccessibilityHelper.apk and b/packages/artemis-accessibility-helper/ArtemisAccessibilityHelper.apk differ diff --git a/packages/artemis-accessibility-helper/app/build.gradle.kts b/packages/artemis-accessibility-helper/app/build.gradle.kts index ad802d617..3e0ff81ab 100644 --- a/packages/artemis-accessibility-helper/app/build.gradle.kts +++ b/packages/artemis-accessibility-helper/app/build.gradle.kts @@ -10,8 +10,8 @@ android { applicationId = "com.artemis.helper" minSdk = 24 targetSdk = 35 - versionCode = 6 - versionName = "1.2.0" + versionCode = 10 + versionName = "1.3.3" } buildTypes { @@ -23,6 +23,9 @@ android { ) } } + testOptions { + unitTests.isIncludeAndroidResources = true + } compileOptions { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 @@ -31,5 +34,7 @@ android { dependencies { // Pure standard Android SDK APIs (android.accessibilityservice, android.view.accessibility, org.json) - // Zero external dependencies to maximize stability, guarantee compatibility, and keep APK under 30KB. + // No runtime dependencies; the following dependencies are JVM test-only. + testImplementation("junit:junit:4.13.2") + testImplementation("org.robolectric:robolectric:4.14.1") } diff --git a/packages/artemis-accessibility-helper/app/src/main/java/com/artemis/helper/CommandServer.java b/packages/artemis-accessibility-helper/app/src/main/java/com/artemis/helper/CommandServer.java index 328f7174e..ed0fcfa0f 100644 --- a/packages/artemis-accessibility-helper/app/src/main/java/com/artemis/helper/CommandServer.java +++ b/packages/artemis-accessibility-helper/app/src/main/java/com/artemis/helper/CommandServer.java @@ -338,6 +338,10 @@ private JSONObject executeCommand(String cmd, JSONObject params) { resp.put("success", GestureController.longPress(service, lpx, lpy, lpDuration, 2500L)); } break; + case "perform_gesture": + return ContinuousGesture.execute(service, params); + case "cancel_gesture": + return ContinuousGesture.cancel(params.optString("request_id", "")); case "swipe": float x1 = (float) params.optDouble("x1", -1.0); float y1 = (float) params.optDouble("y1", -1.0); @@ -389,6 +393,10 @@ private JSONObject buildPing(boolean authed) throws Exception { r.put("version_name", service.getVersionName()); r.put("protocol_version", ArtemisAccessibilityService.PROTOCOL_VERSION); r.put("port", port); + r.put("capabilities", new org.json.JSONArray().put("perform_gesture") + .put("gesture_cubic_bezier").put("gesture_long_press_drag")); + r.put("gesture_continuation", android.os.Build.VERSION.SDK_INT >= 26); + r.put("gesture_max_pointers", Math.min(10, android.accessibilityservice.GestureDescription.getMaxStrokeCount())); r.put("auth_required", true); r.put("token_set", TokenStore.isSet()); r.put("authenticated", authed); diff --git a/packages/artemis-accessibility-helper/app/src/main/java/com/artemis/helper/ContinuousGesture.java b/packages/artemis-accessibility-helper/app/src/main/java/com/artemis/helper/ContinuousGesture.java new file mode 100644 index 000000000..fcab9ffca --- /dev/null +++ b/packages/artemis-accessibility-helper/app/src/main/java/com/artemis/helper/ContinuousGesture.java @@ -0,0 +1,287 @@ +package com.artemis.helper; + +import android.accessibilityservice.AccessibilityService; +import android.accessibilityservice.GestureDescription; +import android.graphics.Path; +import android.os.Build; +import android.os.Handler; +import android.os.Looper; +import android.os.SystemClock; +import android.util.DisplayMetrics; +import android.view.WindowManager; +import android.view.ViewConfiguration; +import org.json.JSONArray; +import org.json.JSONObject; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.TreeMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** One bounded transaction owns every contact until the final phase lifts it. */ +public final class ContinuousGesture { + private static final Handler MAIN = new Handler(Looper.getMainLooper()); + private static final LinkedHashSet CANCELLED = new LinkedHashSet<>(); + private static ContinuousGesture active; + private final AccessibilityService service; + private final String requestId; + private final List phases; + private final CountDownLatch done = new CountDownLatch(1); + private volatile boolean cancelRequested; + private volatile JSONObject result; + private volatile int completed; + private boolean dispatched; + private boolean releasing; + + static final class Phase { + final long duration; + final TreeMap paths; + final TreeMap ends; + GestureDescription.StrokeDescription[] strokes; + GestureDescription gesture; + Phase(long duration, TreeMap paths, TreeMap ends) { + this.duration = duration; this.paths = paths; this.ends = ends; + } + } + + private ContinuousGesture(AccessibilityService service, String requestId, List phases) { + this.service = service; this.requestId = requestId; this.phases = phases; + } + + static JSONObject reply(String id, String status, int count, boolean released, String error) { + JSONObject result = new JSONObject(); + try { + result.put("request_id", id); + result.put("success", "completed".equals(status)); + result.put("status", status); + result.put("phases_completed", count); + result.put("release_confirmed", released); + if (error != null) result.put("error", error); + } catch (Exception impossible) { throw new IllegalStateException(impossible); } + return result; + } + + private static int integer(Object value, int min, int max) { + if (!(value instanceof Integer || value instanceof Long)) + throw new IllegalArgumentException("Expected an integer"); + long n = ((Number) value).longValue(); + if (n < min || n > max) throw new IllegalArgumentException("Integer outside allowed range"); + return (int) n; + } + + // Validate the ENTIRE plan before building or dispatching any input. + static List parse(JSONArray input, int width, int height) throws Exception { + if (width < 1 || height < 1 || input == null || input.length() < 1 || input.length() > 32) + throw new IllegalArgumentException("Invalid display or phase count"); + if ("long_press_drag".equals(input.getJSONObject(0).optString("kind"))) { + if (input.length() != 1) + throw new IllegalArgumentException("long_press_drag must be the only entry"); + input = LongPressDrag.expand(input.getJSONObject(0), + ViewConfiguration.getLongPressTimeout()); + } + if (input.length() > 1 && Build.VERSION.SDK_INT < 26) + throw new UnsupportedOperationException("Continuous gestures require Android 8.0+"); + List phases = new ArrayList<>(); + TreeMap previousEnds = null; + long total = 0; + for (int i = 0; i < input.length(); i++) { + JSONObject raw = input.getJSONObject(i); + if (raw.length() != 2) throw new IllegalArgumentException("Unknown phase fields"); + int duration = integer(raw.get("duration_ms"), 1, 5000); + total += duration; + if (total > 30000 || total > GestureDescription.getMaxGestureDuration()) + throw new IllegalArgumentException("Gesture exceeds duration limit"); + JSONArray pointers = raw.getJSONArray("pointers"); + if (pointers.length() < 1 || pointers.length() > Math.min(10, GestureDescription.getMaxStrokeCount())) + throw new IllegalArgumentException("Invalid pointer count"); + TreeMap paths = new TreeMap<>(); + TreeMap ends = new TreeMap<>(); + TreeMap normalizedEnds = new TreeMap<>(); + for (int j = 0; j < pointers.length(); j++) { + JSONObject pointer = pointers.getJSONObject(j); + boolean curved = pointer.has("control_points"); + if (pointer.length() != (curved ? 3 : 2)) + throw new IllegalArgumentException("Unknown pointer fields"); + int id = integer(pointer.get("id"), 0, 9); + if (paths.containsKey(id)) throw new IllegalArgumentException("Duplicate pointer ID"); + JSONArray points = pointer.getJSONArray("path"); + if (points.length() < 1 || points.length() > 128) + throw new IllegalArgumentException("Invalid path length"); + float[] controls = null; + if (curved) { + JSONArray rawControls = pointer.getJSONArray("control_points"); + if (points.length() != 2 || rawControls.length() != 2) + throw new IllegalArgumentException("Cubic Bezier requires two endpoints and two control points"); + controls = new float[4]; + for (int c = 0; c < 2; c++) { + JSONArray point = rawControls.getJSONArray(c); + if (point.length() != 2) throw new IllegalArgumentException("Expected control [x,y]"); + controls[c * 2] = integer(point.get(0), 0, 1000) * (width - 1) / 1000f; + controls[c * 2 + 1] = integer(point.get(1), 0, 1000) * (height - 1) / 1000f; + } + } + Path path = new Path(); + for (int k = 0; k < points.length(); k++) { + JSONArray point = points.getJSONArray(k); + if (point.length() != 2) throw new IllegalArgumentException("Expected [x,y]"); + int nx = integer(point.get(0), 0, 1000); + int ny = integer(point.get(1), 0, 1000); + String normalized = nx + "," + ny; + if (k == 0 && previousEnds != null && !normalized.equals(previousEnds.get(id))) + throw new IllegalArgumentException("Discontinuous pointer path"); + float x = nx * (width - 1) / 1000f, y = ny * (height - 1) / 1000f; + if (k == 0) path.moveTo(x, y); + else if (curved) path.cubicTo(controls[0], controls[1], controls[2], controls[3], x, y); + else path.lineTo(x, y); + ends.put(id, new float[]{x, y}); + normalizedEnds.put(id, normalized); + } + paths.put(id, path); + } + if (previousEnds != null && !previousEnds.keySet().equals(paths.keySet())) + throw new IllegalArgumentException("Keep the same pointer IDs across phases"); + previousEnds = normalizedEnds; + phases.add(new Phase(duration, paths, ends)); + } + GestureDescription.StrokeDescription[] prior = null; + for (int i = 0; i < phases.size(); i++) { + Phase phase = phases.get(i); + boolean more = i + 1 < phases.size(); + phase.strokes = new GestureDescription.StrokeDescription[phase.paths.size()]; + GestureDescription.Builder builder = new GestureDescription.Builder(); + int j = 0; + for (Path path : phase.paths.values()) { + GestureDescription.StrokeDescription stroke; + if (prior != null) stroke = prior[j].continueStroke(path, 0, phase.duration, more); + else if (Build.VERSION.SDK_INT >= 26) stroke = new GestureDescription.StrokeDescription(path, 0, phase.duration, more); + else stroke = new GestureDescription.StrokeDescription(path, 0, phase.duration); + phase.strokes[j++] = stroke; + builder.addStroke(stroke); + } + phase.gesture = builder.build(); + prior = phase.strokes; + } + return phases; + } + + public static JSONObject execute(AccessibilityService service, JSONObject params) { + String id = params.optString("request_id", ""); + if (!id.matches("[A-Za-z0-9_-]{1,64}")) + return reply(id, "invalid_arguments", 0, true, "A bounded request_id is required"); + if (Looper.myLooper() == Looper.getMainLooper()) + return reply(id, "rejected", 0, true, "Call from a worker thread"); + final ContinuousGesture run; + try { + DisplayMetrics metrics = new DisplayMetrics(); + ((WindowManager) service.getSystemService(AccessibilityService.WINDOW_SERVICE)) + .getDefaultDisplay().getRealMetrics(metrics); + run = new ContinuousGesture(service, id, + parse(params.getJSONArray("phases"), metrics.widthPixels, metrics.heightPixels)); + } catch (UnsupportedOperationException e) { + return reply(id, "unsupported", 0, true, e.getMessage()); + } catch (Exception e) { + return reply(id, "invalid_arguments", 0, true, e.getMessage()); + } + synchronized (ContinuousGesture.class) { + if (CANCELLED.remove(id)) return reply(id, "cancelled", 0, true, "Cancelled before dispatch"); + if (!GestureController.INPUT_BUSY.compareAndSet(false, true)) + return reply(id, "busy", 0, true, "Another gesture is active or needs recovery"); + active = run; + } + long total = 0; + for (Phase p : run.phases) total += p.duration; + MAIN.post(() -> run.next()); + try { + if (run.done.await(total + 5000, TimeUnit.MILLISECONDS)) return run.result; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + run.cancelRequested = true; + // Do not unlock or replay: late callbacks still own and release held contacts. + return reply(id, "timeout", run.completed, false, + "Gesture outcome unknown; cancellation requested. Reconcile device before reuse."); + } + + public static synchronized JSONObject cancel(String id) { + if (id == null || !id.matches("[A-Za-z0-9_-]{1,64}")) + return reply(id, "invalid_arguments", 0, true, "Invalid request_id"); + if (active != null && active.requestId.equals(id)) { + active.cancelRequested = true; + return reply(id, "cancelling", active.completed, false, "Will release after the current bounded phase"); + } + // Covers cancellation racing the host's in-flight capability check / request. + CANCELLED.add(id); + while (CANCELLED.size() > 128) CANCELLED.remove(CANCELLED.iterator().next()); + return reply(id, "cancelled", 0, true, "No matching active gesture"); + } + + private void finish(String status, boolean released, String error) { + if (result != null) return; + result = reply(requestId, status, completed, released, error); + synchronized (ContinuousGesture.class) { + if (active == this) active = null; + } + // Unknown held contacts fence all further injected gestures until recovery. + if (released || !dispatched) GestureController.INPUT_BUSY.set(false); + done.countDown(); + } + + private void next() { + if (result != null) return; + if (cancelRequested) { release("cancelled"); return; } + if (completed == phases.size()) { finish("completed", true, null); return; } + Phase phase = phases.get(completed); + final long phaseEndsAt = SystemClock.uptimeMillis() + phase.duration; + try { + boolean accepted = service.dispatchGesture(phase.gesture, + new AccessibilityService.GestureResultCallback() { + @Override public void onCompleted(GestureDescription ignored) { + completed++; + if (completed == phases.size()) + finish(cancelRequested ? "cancelled" : "completed", true, + cancelRequested ? "Cancellation requested" : null); + else { + // Android completes a stationary continued stroke after DOWN: + // duplicate MOVE events are omitted and there is no UP yet. + // Keep contact held until its requested time before continuing. + MAIN.postAtTime(() -> next(), phaseEndsAt); + } + } + @Override public void onCancelled(GestureDescription ignored) { + // Android cancels this stream. Conservatively do not certify release. + finish("cancelled", false, "System cancelled gesture; reconcile device"); + } + }, MAIN); + if (!accepted) release("rejected"); else dispatched = true; + } catch (Exception e) { release("rejected"); } + } + + private void release(final String status) { + if (completed == 0 || completed == phases.size()) { + finish(status, !dispatched || completed == phases.size(), "Gesture " + status); + return; + } + if (releasing) return; + releasing = true; + try { + Phase previous = phases.get(completed - 1); + GestureDescription.Builder builder = new GestureDescription.Builder(); + int j = 0; + for (float[] endpoint : previous.ends.values()) { + Path still = new Path(); still.moveTo(endpoint[0], endpoint[1]); + builder.addStroke(previous.strokes[j++].continueStroke(still, 0, 1, false)); + } + boolean accepted = service.dispatchGesture(builder.build(), + new AccessibilityService.GestureResultCallback() { + @Override public void onCompleted(GestureDescription ignored) { + finish(status, true, "Gesture " + status + "; held contacts released"); + } + @Override public void onCancelled(GestureDescription ignored) { + finish(status, false, "Release cancelled; reconcile device"); + } + }, MAIN); + if (!accepted) finish(status, false, "Release rejected; reconcile device"); + } catch (Exception e) { finish(status, false, "Release failed; reconcile device"); } + } +} diff --git a/packages/artemis-accessibility-helper/app/src/main/java/com/artemis/helper/GestureController.java b/packages/artemis-accessibility-helper/app/src/main/java/com/artemis/helper/GestureController.java index 1714a634f..c77ba05f7 100644 --- a/packages/artemis-accessibility-helper/app/src/main/java/com/artemis/helper/GestureController.java +++ b/packages/artemis-accessibility-helper/app/src/main/java/com/artemis/helper/GestureController.java @@ -23,6 +23,9 @@ */ public final class GestureController { + // Owned only by ContinuousGesture; ordinary actions retain their dispatch semantics. + static final AtomicBoolean INPUT_BUSY = new AtomicBoolean(false); + private static final String TAG = "ArtemisGestureCtrl"; private static final Handler MAIN_HANDLER = new Handler(Looper.getMainLooper()); @@ -162,12 +165,18 @@ private static boolean dispatchSynchronous( final GestureDescription gesture, long timeoutMs ) { + if (INPUT_BUSY.get()) return false; final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean result = new AtomicBoolean(false); MAIN_HANDLER.post(new Runnable() { @Override public void run() { + // A continuous gesture may have started while this input was queued. + if (INPUT_BUSY.get()) { + latch.countDown(); + return; + } try { service.dispatchGesture(gesture, new AccessibilityService.GestureResultCallback() { @Override diff --git a/packages/artemis-accessibility-helper/app/src/main/java/com/artemis/helper/LongPressDrag.java b/packages/artemis-accessibility-helper/app/src/main/java/com/artemis/helper/LongPressDrag.java new file mode 100644 index 000000000..d877bea61 --- /dev/null +++ b/packages/artemis-accessibility-helper/app/src/main/java/com/artemis/helper/LongPressDrag.java @@ -0,0 +1,62 @@ +package com.artemis.helper; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; +import org.json.JSONArray; +import org.json.JSONObject; + +/** Expands a long-press drag; ContinuousGesture owns dispatch and release. */ +final class LongPressDrag { + private static final Set FIELDS = new HashSet<>(Arrays.asList( + "kind", "start", "end", "control_points", "duration_ms", "hold_ms", "release_delay_ms")); + + private static int integer(Object value, int min, int max) { + if (!(value instanceof Integer || value instanceof Long)) + throw new IllegalArgumentException("Expected an integer"); + long n = ((Number) value).longValue(); + if (n < min || n > max) throw new IllegalArgumentException("Integer outside allowed range"); + return (int) n; + } + + private static JSONArray point(JSONArray value) throws Exception { + if (value.length() != 2) throw new IllegalArgumentException("Expected [x,y]"); + return new JSONArray().put(integer(value.get(0), 0, 1000)) + .put(integer(value.get(1), 0, 1000)); + } + + private static JSONObject phase(int duration, JSONArray path, JSONArray controls) throws Exception { + JSONObject pointer = new JSONObject().put("id", 0).put("path", path); + if (controls != null) pointer.put("control_points", controls); + return new JSONObject().put("duration_ms", duration) + .put("pointers", new JSONArray().put(pointer)); + } + + static JSONArray expand(JSONObject args, int longPressMs) throws Exception { + for (Iterator keys = args.keys(); keys.hasNext();) + if (!FIELDS.contains(keys.next())) throw new IllegalArgumentException("Unknown long-press drag field"); + if (!"long_press_drag".equals(args.get("kind"))) + throw new IllegalArgumentException("Invalid long-press drag kind"); + JSONArray start = point(args.getJSONArray("start")); + JSONArray end = point(args.getJSONArray("end")); + JSONArray controls = null; + if (args.has("control_points")) { + JSONArray raw = args.getJSONArray("control_points"); + if (raw.length() != 2) + throw new IllegalArgumentException("Cubic Bezier requires two control points"); + controls = new JSONArray().put(point(raw.getJSONArray(0))).put(point(raw.getJSONArray(1))); + } + int duration = integer(args.has("duration_ms") ? args.get("duration_ms") : 800, 1, 5000); + // Do not silently shorten a device's configured long press to fit the budget. + int hold = integer(args.has("hold_ms") ? args.get("hold_ms") : (long) longPressMs + 150, 1, 5000); + int delay = integer(args.has("release_delay_ms") ? args.get("release_delay_ms") : 0, 0, 5000); + + JSONArray phases = new JSONArray() + .put(phase(hold, new JSONArray().put(start), null)) + .put(phase(duration, new JSONArray().put(start).put(end), controls)); + // Zero lifts on the movement stroke; a positive delay holds at the chosen endpoint. + if (delay > 0) phases.put(phase(delay, new JSONArray().put(end), null)); + return phases; + } +} diff --git a/packages/artemis-accessibility-helper/app/src/test/java/com/artemis/helper/ContinuousGestureTest.java b/packages/artemis-accessibility-helper/app/src/test/java/com/artemis/helper/ContinuousGestureTest.java new file mode 100644 index 000000000..0b7d5e343 --- /dev/null +++ b/packages/artemis-accessibility-helper/app/src/test/java/com/artemis/helper/ContinuousGestureTest.java @@ -0,0 +1,401 @@ +package com.artemis.helper; + +import static org.junit.Assert.*; +import static org.robolectric.Shadows.shadowOf; + +import android.accessibilityservice.AccessibilityService; +import android.accessibilityservice.GestureDescription; +import android.graphics.PathMeasure; +import android.os.Handler; +import android.os.Looper; +import android.view.accessibility.AccessibilityEvent; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.Robolectric; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.annotation.Config; +import org.robolectric.annotation.Implementation; +import org.robolectric.annotation.Implements; +import org.robolectric.annotation.LooperMode; +import org.robolectric.annotation.GraphicsMode; +import java.util.ArrayList; +import java.util.List; +import java.time.Duration; +import java.util.concurrent.*; + +@RunWith(RobolectricTestRunner.class) +@Config(sdk = 28, shadows = ContinuousGestureTest.InputShadow.class) +@LooperMode(LooperMode.Mode.PAUSED) +public class ContinuousGestureTest { + private ExecutorService worker; + private TestService service; + + public static class TestService extends AccessibilityService { + @Override public void onAccessibilityEvent(AccessibilityEvent event) {} + @Override public void onInterrupt() {} + } + + @Implements(AccessibilityService.class) + public static class InputShadow { + static final List inputs = new ArrayList<>(); + static final List callbacks = new ArrayList<>(); + static int rejectIndex = -1; + @Implementation + protected boolean dispatchGesture(GestureDescription gesture, + AccessibilityService.GestureResultCallback callback, Handler handler) { + inputs.add(gesture); callbacks.add(callback); + return inputs.size() - 1 != rejectIndex; + } + } + + @Before public void setup() { + InputShadow.inputs.clear(); InputShadow.callbacks.clear(); InputShadow.rejectIndex = -1; + GestureController.INPUT_BUSY.set(false); + service = Robolectric.buildService(TestService.class).create().get(); + worker = Executors.newSingleThreadExecutor(); + } + @After public void teardown() { worker.shutdownNow(); } + + private static JSONObject phase(int duration, int... points) throws Exception { + JSONArray path = new JSONArray(); + for (int i = 0; i < points.length; i += 2) + path.put(new JSONArray().put(points[i]).put(points[i + 1])); + return new JSONObject().put("duration_ms", duration).put("pointers", new JSONArray().put( + new JSONObject().put("id", 0).put("path", path))); + } + private static JSONArray drag() throws Exception { + return new JSONArray().put(phase(600, 300, 400)) + .put(phase(800, 300, 400, 980, 400)).put(phase(900, 980, 400)); + } + private Future execute(String id, JSONArray phases) throws Exception { + JSONObject args = new JSONObject().put("request_id", id).put("phases", phases); + return worker.submit(() -> ContinuousGesture.execute(service, args)); + } + private void awaitInputs(int count) throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (InputShadow.inputs.size() < count && System.nanoTime() < deadline) { + shadowOf(Looper.getMainLooper()).idle(); Thread.sleep(5); + } + assertEquals(count, InputShadow.inputs.size()); + } + private void complete(int index) { + InputShadow.callbacks.get(index).onCompleted(InputShadow.inputs.get(index)); + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis( + InputShadow.inputs.get(index).getStroke(0).getDuration())); + } + + @Test public void earlyDownCallbackCannotSkipLongPressTime() throws Exception { + Future result = execute("early-down", new JSONArray().put( + longPressDrag(0).put("hold_ms", 1500))); + awaitInputs(1); + InputShadow.callbacks.get(0).onCompleted(InputShadow.inputs.get(0)); + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(1499)); + assertEquals("Do not move while the icon is still being long-pressed", 1, InputShadow.inputs.size()); + assertTrue(GestureController.INPUT_BUSY.get()); + assertFalse(result.isDone()); + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(1)); + awaitInputs(2); + complete(1); + assertTrue(result.get(5, TimeUnit.SECONDS).getBoolean("release_confirmed")); + } + + @Test public void cancellationWhileWaitingForLongPressReleasesWithoutMoving() throws Exception { + Future result = execute("cancel-hold-wait", new JSONArray().put( + longPressDrag(0).put("hold_ms", 1500))); + awaitInputs(1); + InputShadow.callbacks.get(0).onCompleted(InputShadow.inputs.get(0)); + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(500)); + ContinuousGesture.cancel("cancel-hold-wait"); + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(1000)); + awaitInputs(2); + assertEquals(1, InputShadow.inputs.get(1).getStroke(0).getDuration()); + assertFalse(InputShadow.inputs.get(1).getStroke(0).willContinue()); + complete(1); + JSONObject receipt = result.get(5, TimeUnit.SECONDS); + assertEquals("cancelled", receipt.getString("status")); + assertTrue(receipt.getBoolean("release_confirmed")); + assertFalse(GestureController.INPUT_BUSY.get()); + } + + @Test public void allFingersAreSimultaneousAndLiftTogether() throws Exception { + JSONObject phase = phase(500, 100, 200, 100, 800); + JSONArray pointers = phase.getJSONArray("pointers"); + for (int id = 1; id < 3; id++) { + JSONObject p = new JSONObject(pointers.getJSONObject(0).toString()).put("id", id); + p.put("path", new JSONArray().put(new JSONArray().put(100 + id * 250).put(200)) + .put(new JSONArray().put(100 + id * 250).put(800))); + pointers.put(p); + } + GestureDescription gesture = ContinuousGesture.parse(new JSONArray().put(phase), 1080, 2400).get(0).gesture; + assertEquals(3, gesture.getStrokeCount()); + for (int i = 0; i < 3; i++) { + assertEquals(0, gesture.getStroke(i).getStartTime()); + assertEquals(500, gesture.getStroke(i).getDuration()); + assertFalse(gesture.getStroke(i).willContinue()); + } + } + + @Test public void dragKeepsContactUntilFinalPhase() throws Exception { + Future result = execute("drag", drag()); + for (int i = 0; i < 3; i++) { + awaitInputs(i + 1); + assertEquals(i < 2, InputShadow.inputs.get(i).getStroke(0).willContinue()); + assertTrue(GestureController.INPUT_BUSY.get()); + complete(i); + } + assertTrue(result.get(5, TimeUnit.SECONDS).getBoolean("success")); + assertFalse(GestureController.INPUT_BUSY.get()); + } + + private static JSONArray curvedDrag() throws Exception { + JSONArray phases = drag(); + phases.getJSONObject(1).getJSONArray("pointers").getJSONObject(0).put("control_points", + new JSONArray("[[450,200],[800,200]]")); + return phases; + } + + private static JSONObject longPressDrag(int delay) throws Exception { + return new JSONObject().put("kind", "long_press_drag").put("start", new JSONArray("[300,400]")) + .put("end", new JSONArray("[650,550]")).put("duration_ms", 800).put("release_delay_ms", delay); + } + + @Test public void zeroDelayLiftsOnMovementWithoutAnotherPhase() throws Exception { + Future result = execute("drag-immediate", new JSONArray().put(longPressDrag(0))); + awaitInputs(1); + assertTrue(InputShadow.inputs.get(0).getStroke(0).willContinue()); + complete(0); + awaitInputs(2); + GestureDescription.StrokeDescription movement = InputShadow.inputs.get(1).getStroke(0); + assertEquals(800, movement.getDuration()); + assertFalse(movement.willContinue()); + complete(1); + assertTrue(result.get(5, TimeUnit.SECONDS).getBoolean("release_confirmed")); + assertEquals(2, InputShadow.inputs.size()); + } + + @Test public void positiveDelayHoldsAtEndpointAndOnlyThenReleases() throws Exception { + Future result = execute("drag-delayed", new JSONArray().put(longPressDrag(1200))); + awaitInputs(1); complete(0); awaitInputs(2); + assertTrue(InputShadow.inputs.get(1).getStroke(0).willContinue()); + assertEquals(800, InputShadow.inputs.get(1).getStroke(0).getDuration()); + complete(1); awaitInputs(3); + GestureDescription.StrokeDescription dwell = InputShadow.inputs.get(2).getStroke(0); + assertEquals(1200, dwell.getDuration()); + assertFalse(dwell.willContinue()); + assertFalse(result.isDone()); + assertTrue(GestureController.INPUT_BUSY.get()); + complete(2); + assertTrue(result.get(5, TimeUnit.SECONDS).getBoolean("release_confirmed")); + assertFalse(GestureController.INPUT_BUSY.get()); + } + + @Test @GraphicsMode(GraphicsMode.Mode.NATIVE) + public void longPressDragPreservesChosenEndpointAndDeviceHold() throws Exception { + for (int[] endpoint : new int[][]{{650, 550}, {400, 200}, {20, 400}, {980, 400}}) { + for (int[] size : new int[][]{{1080, 2400}, {2400, 1080}}) { + JSONObject intent = longPressDrag(1200).put("end", new JSONArray(endpoint)) + .put("control_points", new JSONArray("[[400,250],[600,250]]")); + JSONArray raw = LongPressDrag.expand(intent, 1000); + assertEquals(1150, raw.getJSONObject(0).getInt("duration_ms")); + List parsed = ContinuousGesture.parse(raw, size[0], size[1]); + float[] end = parsed.get(1).ends.get(0); + int nx = endpoint[0], ny = endpoint[1]; + assertArrayEquals(new float[]{nx * (size[0] - 1) / 1000f, ny * (size[1] - 1) / 1000f}, end, 0.1f); + PathMeasure curve = new PathMeasure(parsed.get(1).paths.get(0), false); + float[] actualEnd = new float[2]; + assertTrue(curve.getPosTan(curve.getLength(), actualEnd, null)); + assertArrayEquals(end, actualEnd, 0.1f); + PathMeasure still = new PathMeasure(parsed.get(2).paths.get(0), false); + assertEquals(0f, still.getLength(), 0.01f); + assertArrayEquals(end, parsed.get(2).ends.get(0), 0.01f); + intent.put("hold_ms", 650); + assertEquals(650, LongPressDrag.expand(intent, 1000).getJSONObject(0).getInt("duration_ms")); + } + } + } + + @Test public void invalidReleaseDelayAndMixedPlansNeverTouchDevice() throws Exception { + for (Object value : new Object[]{-1, 5001, 1.5, true, "1000"}) { + JSONObject invalid = longPressDrag(0).put("release_delay_ms", value); + assertEquals("invalid_arguments", execute("bad-delay", new JSONArray().put(invalid)) + .get(5, TimeUnit.SECONDS).getString("status")); + } + assertEquals("invalid_arguments", execute("mixed", new JSONArray().put(longPressDrag(0)).put(phase(100, 300, 400))) + .get(5, TimeUnit.SECONDS).getString("status")); + assertTrue(InputShadow.inputs.isEmpty()); + } + + @Test public void invalidLongPressDragEndpointsAndControlsNeverTouchDevice() throws Exception { + JSONObject missingEnd = longPressDrag(0); + missingEnd.remove("end"); + JSONObject[] invalid = { + missingEnd, + longPressDrag(0).put("end", new JSONArray("[1001,500]")), + longPressDrag(0).put("end", new JSONArray("[500]")), + longPressDrag(0).put("end", new JSONArray("[true,500]")), + longPressDrag(0).put("control_points", new JSONArray("[[100,200]]")), + longPressDrag(0).put("control_points", new JSONArray("[[100,200],[300,1001]]")), + longPressDrag(0).put("direction", "left") + }; + for (int i = 0; i < invalid.length; i++) + assertEquals("invalid_arguments", execute("bad-drag-" + i, new JSONArray().put(invalid[i])) + .get(5, TimeUnit.SECONDS).getString("status")); + assertTrue(InputShadow.inputs.isEmpty()); + } + + @Test public void longPressDragWithoutControlsUsesAStraightPath() throws Exception { + JSONArray phases = LongPressDrag.expand(longPressDrag(0), 500); + JSONObject movement = phases.getJSONObject(1).getJSONArray("pointers").getJSONObject(0); + assertEquals("[[300,400],[650,550]]", movement.getJSONArray("path").toString()); + assertFalse(movement.has("control_points")); + } + + @Test public void cancelDuringEndpointDwellStillReleasesAndUnlocks() throws Exception { + Future result = execute("drag-cancel", new JSONArray().put(longPressDrag(1000))); + awaitInputs(1); complete(0); awaitInputs(2); complete(1); awaitInputs(3); + ContinuousGesture.cancel("drag-cancel"); + complete(2); + JSONObject receipt = result.get(5, TimeUnit.SECONDS); + assertEquals("cancelled", receipt.getString("status")); + assertTrue(receipt.getBoolean("release_confirmed")); + assertFalse(GestureController.INPUT_BUSY.get()); + } + + @Test @GraphicsMode(GraphicsMode.Mode.NATIVE) + public void cubicPathHasCurvatureAndScaledEndpointsWithoutLifting() throws Exception { + List phases = ContinuousGesture.parse(curvedDrag(), 1001, 2001); + PathMeasure measure = new PathMeasure(phases.get(1).paths.get(0), false); + assertTrue(measure.getLength() > 680); + float[] position = new float[2]; + assertTrue(measure.getPosTan(0, position, null)); + assertArrayEquals(new float[]{300, 800}, position, 0.1f); + assertTrue(measure.getPosTan(measure.getLength() / 2, position, null)); + assertTrue("Curve must bow above the straight horizontal path", position[1] < 700); + assertTrue(measure.getPosTan(measure.getLength(), position, null)); + assertArrayEquals(new float[]{980, 800}, position, 0.1f); + for (int i = 0; i < phases.size(); i++) + assertEquals(i < 2, phases.get(i).gesture.getStroke(0).willContinue()); + } + + @Test public void curvedDragCompletesHoldMoveDwellAsOneContact() throws Exception { + Future result = execute("curve", curvedDrag()); + for (int i = 0; i < 3; i++) { + awaitInputs(i + 1); + assertEquals(i < 2, InputShadow.inputs.get(i).getStroke(0).willContinue()); + complete(i); + } + JSONObject receipt = result.get(5, TimeUnit.SECONDS); + assertTrue(receipt.getBoolean("success")); + assertTrue(receipt.getBoolean("release_confirmed")); + } + + @Test public void malformedCurveInLaterPhaseNeverDispatchesHold() throws Exception { + String[] invalid = {"[]", "[[1,2]]", "[[1,2],[3,4],[5,6]]", "[[1001,2],[3,4]]", + "[[1.5,2],[3,4]]", "[[true,2],[3,4]]", "[[1,2,3],[4,5]]"}; + for (int i = 0; i < invalid.length; i++) { + JSONArray phases = curvedDrag(); + phases.getJSONObject(1).getJSONArray("pointers").getJSONObject(0) + .put("control_points", new JSONArray(invalid[i])); + assertEquals("invalid_arguments", execute("bad-curve-" + i, phases) + .get(5, TimeUnit.SECONDS).getString("status")); + } + JSONArray phases = curvedDrag(); + phases.getJSONObject(1).getJSONArray("pointers").getJSONObject(0) + .getJSONArray("path").put(new JSONArray("[980,400]")); + assertEquals("invalid_arguments", execute("extra-endpoint", phases) + .get(5, TimeUnit.SECONDS).getString("status")); + assertTrue(InputShadow.inputs.isEmpty()); + } + + @Test public void laterInvalidPhaseCannotCausePartialExecution() throws Exception { + JSONArray phases = drag(); + phases.getJSONObject(2).getJSONArray("pointers").getJSONObject(0) + .put("path", new JSONArray().put(new JSONArray().put(500).put(400))); + JSONObject result = execute("invalid", phases).get(5, TimeUnit.SECONDS); + assertEquals("invalid_arguments", result.getString("status")); + assertTrue(InputShadow.inputs.isEmpty()); + } + + @Test public void cancelHeldPhaseDispatchesOnlyReleaseThenUnlocks() throws Exception { + Future result = execute("cancel", drag()); + awaitInputs(1); + ContinuousGesture.cancel("cancel"); + complete(0); + awaitInputs(2); + GestureDescription release = InputShadow.inputs.get(1); + assertEquals(1, release.getStroke(0).getDuration()); + assertFalse(release.getStroke(0).willContinue()); + complete(1); + JSONObject reply = result.get(5, TimeUnit.SECONDS); + assertEquals("cancelled", reply.getString("status")); + assertTrue(reply.getBoolean("release_confirmed")); + assertFalse(GestureController.INPUT_BUSY.get()); + } + + @Test public void cancelBeforeRequestDoesNotTouchDevice() throws Exception { + ContinuousGesture.cancel("race"); + JSONObject result = execute("race", drag()).get(5, TimeUnit.SECONDS); + assertEquals("cancelled", result.getString("status")); + assertTrue(InputShadow.inputs.isEmpty()); + } + + @Test public void rejectedReleaseDoesNotAllowAnotherGesture() throws Exception { + Future result = execute("reject-release", drag()); + awaitInputs(1); + InputShadow.rejectIndex = 1; + ContinuousGesture.cancel("reject-release"); + complete(0); + JSONObject reply = result.get(5, TimeUnit.SECONDS); + assertFalse(reply.getBoolean("release_confirmed")); + assertTrue(GestureController.INPUT_BUSY.get()); + assertEquals("busy", execute("next", drag()).get(5, TimeUnit.SECONDS).getString("status")); + } + + @Test public void ordinaryTapRetainsSuccessAndCancellationResults() throws Exception { + Future tap = worker.submit(() -> GestureController.tap(service, 300, 400, 5000)); + awaitInputs(1); + assertFalse("Ordinary actions do not own continuous-input state", GestureController.INPUT_BUSY.get()); + complete(0); + assertTrue(tap.get(5, TimeUnit.SECONDS)); + + Future swipe = worker.submit(() -> GestureController.swipe(service, 300, 400, 650, 550, 800, 5000)); + awaitInputs(2); + InputShadow.callbacks.get(1).onCancelled(InputShadow.inputs.get(1)); + assertFalse(swipe.get(5, TimeUnit.SECONDS)); + assertFalse(GestureController.INPUT_BUSY.get()); + } + + @Test public void ordinaryCallbackCannotUnlockAnActiveContinuousGesture() throws Exception { + CompletableFuture tap = CompletableFuture.supplyAsync( + () -> GestureController.tap(service, 300, 400, 5000)); + awaitInputs(1); + Future gesture = execute("legacy-callback", drag()); + awaitInputs(2); + InputShadow.callbacks.get(0).onCompleted(InputShadow.inputs.get(0)); + assertTrue(tap.get(5, TimeUnit.SECONDS)); + assertTrue(GestureController.INPUT_BUSY.get()); + assertFalse(GestureController.tap(service, 600, 500, 100)); + assertFalse(GestureController.swipe(service, 300, 400, 650, 550, 800, 100)); + assertEquals(2, InputShadow.inputs.size()); + + ContinuousGesture.cancel("legacy-callback"); + complete(1); + awaitInputs(3); + complete(2); + assertTrue(gesture.get(5, TimeUnit.SECONDS).getBoolean("release_confirmed")); + assertFalse(GestureController.INPUT_BUSY.get()); + Future next = worker.submit(() -> GestureController.tap(service, 600, 500, 5000)); + awaitInputs(4); + complete(3); + assertTrue(next.get(5, TimeUnit.SECONDS)); + } + + @Test @Config(sdk = 24) public void android7RejectsContinuationButAllowsSinglePhase() throws Exception { + assertEquals(1, ContinuousGesture.parse(new JSONArray().put(phase(200, 100, 200)), 1080, 2400).size()); + assertThrows(UnsupportedOperationException.class, () -> ContinuousGesture.parse(drag(), 1080, 2400)); + } +} diff --git a/packages/artemis-accessibility-helper/gradle/wrapper/gradle-wrapper.jar b/packages/artemis-accessibility-helper/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..61285a659 Binary files /dev/null and b/packages/artemis-accessibility-helper/gradle/wrapper/gradle-wrapper.jar differ diff --git a/packages/artemis-accessibility-helper/gradle/wrapper/gradle-wrapper.properties b/packages/artemis-accessibility-helper/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..19a6bdeb8 --- /dev/null +++ b/packages/artemis-accessibility-helper/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.0-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/packages/artemis-accessibility-helper/gradlew b/packages/artemis-accessibility-helper/gradlew new file mode 100755 index 000000000..adff685a0 --- /dev/null +++ b/packages/artemis-accessibility-helper/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/packages/artemis-accessibility-helper/gradlew.bat b/packages/artemis-accessibility-helper/gradlew.bat new file mode 100644 index 000000000..e509b2dd8 --- /dev/null +++ b/packages/artemis-accessibility-helper/gradlew.bat @@ -0,0 +1,93 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/packages/artemis-accessibility-helper/helper_manifest.json b/packages/artemis-accessibility-helper/helper_manifest.json index f8d979ddb..651929260 100644 --- a/packages/artemis-accessibility-helper/helper_manifest.json +++ b/packages/artemis-accessibility-helper/helper_manifest.json @@ -1,7 +1,7 @@ { "package": "com.artemis.helper", - "version_code": 6, - "version_name": "1.2.0", - "sha256": "133e373fe03615c251cd74b03a38539c844d09a074954bca2d2dde6684561969", - "built_at": "2026-09-10T23:13:11+00:00" + "version_code": 10, + "version_name": "1.3.3", + "sha256": "dd625d467f16a432580022bb01b723aa78eac30647611b60c9937c7e8f352f74", + "built_at": "2026-09-29T11:19:03+00:00" } diff --git a/playground/backend_manager/README.md b/playground/backend_manager/README.md index b5f03c9dc..eb44da97c 100644 --- a/playground/backend_manager/README.md +++ b/playground/backend_manager/README.md @@ -93,7 +93,8 @@ playground/backend_manager/ | :--- | :--- | :--- | | `PORT` | `8000` | HTTP port to listen on | | `APP_ENV` | `development` | Environment mode (`development` / `production`) | -| `JWT_SECRET_KEY` | `artemis-...` | Secret key for signing JWT session tokens | +| `JWT_SECRET_KEY` | Required | Supply a private signing key of at least 32 characters through the environment or local .env | +| `DEV_MOCK_OTP` | Empty | Optional fixed OTP for an explicitly configured development environment | | `DOCKER_SOCKET_PATH` | `unix://var/run/docker.sock` | Path to host Docker daemon socket | | `DOCKER_NETWORK` | `artemis-net` | Shared bridge network for dynamic container routing | | `ARTEMIS_IMAGE` | `artemis:latest` | Docker image to spawn for Artemis instances | diff --git a/playground/backend_manager/app/config.py b/playground/backend_manager/app/config.py index d3e4524c6..53687093e 100644 --- a/playground/backend_manager/app/config.py +++ b/playground/backend_manager/app/config.py @@ -14,6 +14,7 @@ import os from pathlib import Path +from pydantic import Field from pydantic_settings import BaseSettings @@ -26,13 +27,13 @@ class Settings(BaseSettings): DEBUG: bool = True # Security & JWT Token Config - JWT_SECRET_KEY: str = "artemis-cos-production-super-secret-key-change-in-prod" + JWT_SECRET_KEY: str = Field(min_length=32) JWT_ALGORITHM: str = "HS256" JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 # 24 hours # OTP Authentication Config OTP_EXPIRE_SECONDS: int = 300 # 5 minutes - DEV_MOCK_OTP: str = "123456" # Bypass code for dev/test environments + DEV_MOCK_OTP: str = "" # Bypass code for dev/test environments # Docker Socket & Ephemeral Container Settings DOCKER_SOCKET_PATH: str = "unix://var/run/docker.sock" diff --git a/pyproject.toml b/pyproject.toml index e5cd095fe..b219757cf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -56,6 +56,7 @@ dependencies = [ "fastapi>=0.111.0", "uvicorn[standard]>=0.30.1", "httpx>=0.28.1", + "playwright>=1.61,<1.62", "requests>=2.31.0", "websockets>=12.0", "sseclient-py>=1.8.0", diff --git a/tests/fixtures/action_surfaces/action_server_manifest.json b/tests/fixtures/action_surfaces/action_server_manifest.json index 968aa5df6..93649d445 100644 --- a/tests/fixtures/action_surfaces/action_server_manifest.json +++ b/tests/fixtures/action_surfaces/action_server_manifest.json @@ -1439,5 +1439,295 @@ "type": "object" }, "outputSchema": null + }, + "perform_gesture": { + "description": "[ACTION] Perform continuous touch gestures that a normal swipe cannot express: simultaneous multi-finger input, continuous holds and drags, or delayed release. Coordinates use 0-1000 screen space. In explicit phases, pointers move together; a one-point path holds still. Keep the same pointer IDs and join endpoints across phases to maintain contact until the final release. Optional control_points define a cubic Bezier path with two endpoints and two controls. Alternatively, provide one long_press_drag entry with start and end coordinates and optional control_points. The endpoint is freely chosen, including inside the screen. duration_ms is movement time; release_delay_ms is the endpoint hold before lifting (zero releases immediately). Observe the screen afterward to verify the intended effect.", + "inputSchema": { + "$defs": { + "GesturePhase": { + "additionalProperties": false, + "properties": { + "duration_ms": { + "maximum": 5000, + "minimum": 1, + "title": "Duration Ms", + "type": "integer" + }, + "pointers": { + "items": { + "$ref": "#/$defs/GesturePointer" + }, + "maxItems": 10, + "minItems": 1, + "title": "Pointers", + "type": "array" + } + }, + "required": [ + "duration_ms", + "pointers" + ], + "title": "GesturePhase", + "type": "object" + }, + "GesturePointer": { + "additionalProperties": false, + "properties": { + "id": { + "maximum": 9, + "minimum": 0, + "title": "Id", + "type": "integer" + }, + "path": { + "items": { + "items": { + "maximum": 1000, + "minimum": 0, + "type": "integer" + }, + "maxItems": 2, + "minItems": 2, + "type": "array" + }, + "maxItems": 128, + "minItems": 1, + "title": "Path", + "type": "array" + }, + "control_points": { + "anyOf": [ + { + "items": { + "items": { + "maximum": 1000, + "minimum": 0, + "type": "integer" + }, + "maxItems": 2, + "minItems": 2, + "type": "array" + }, + "maxItems": 2, + "minItems": 2, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Two cubic Bezier control points. When supplied, path must contain only start and end; Android builds the curve natively.", + "title": "Control Points" + } + }, + "required": [ + "id", + "path" + ], + "title": "GesturePointer", + "type": "object" + }, + "LongPressDrag": { + "additionalProperties": false, + "description": "Hold, move to a caller-selected endpoint, optionally dwell, then release.", + "properties": { + "kind": { + "const": "long_press_drag", + "title": "Kind", + "type": "string" + }, + "start": { + "items": { + "maximum": 1000, + "minimum": 0, + "type": "integer" + }, + "maxItems": 2, + "minItems": 2, + "title": "Start", + "type": "array" + }, + "end": { + "items": { + "maximum": 1000, + "minimum": 0, + "type": "integer" + }, + "maxItems": 2, + "minItems": 2, + "title": "End", + "type": "array" + }, + "control_points": { + "anyOf": [ + { + "items": { + "items": { + "maximum": 1000, + "minimum": 0, + "type": "integer" + }, + "maxItems": 2, + "minItems": 2, + "type": "array" + }, + "maxItems": 2, + "minItems": 2, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Two cubic Bezier controls between start and end. Omit for a straight path.", + "title": "Control Points" + }, + "duration_ms": { + "default": 800, + "maximum": 5000, + "minimum": 1, + "title": "Duration Ms", + "type": "integer" + }, + "hold_ms": { + "anyOf": [ + { + "maximum": 5000, + "minimum": 1, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Omit to use the device long-press timeout plus 150ms.", + "title": "Hold Ms" + }, + "release_delay_ms": { + "default": 0, + "description": "Keep the same finger down at the endpoint for this long, then lift. Zero lifts immediately after moving; independent of movement duration.", + "maximum": 5000, + "minimum": 0, + "title": "Release Delay Ms", + "type": "integer" + } + }, + "required": [ + "kind", + "start", + "end" + ], + "title": "LongPressDrag", + "type": "object" + } + }, + "properties": { + "phases": { + "items": { + "anyOf": [ + { + "$ref": "#/$defs/GesturePhase" + }, + { + "$ref": "#/$defs/LongPressDrag" + } + ] + }, + "title": "Phases", + "type": "array" + } + }, + "required": [ + "phases" + ], + "title": "perform_gestureArguments", + "type": "object" + }, + "outputSchema": { + "$defs": { + "ActionCode": { + "description": "Machine-readable outcome classification for a device action.", + "enum": [ + "OK", + "INVALID_ARGS", + "TARGET_NOT_FOUND", + "DEVICE_ERROR", + "PACKAGE_NOT_FOUND", + "TIMEOUT", + "UNSUPPORTED" + ], + "title": "ActionCode", + "type": "string" + } + }, + "description": "Outcome of one device action, independent of any transport or agent.", + "properties": { + "ok": { + "title": "Ok", + "type": "boolean" + }, + "code": { + "$ref": "#/$defs/ActionCode" + }, + "action": { + "title": "Action", + "type": "string" + }, + "message": { + "title": "Message", + "type": "string" + }, + "detail": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Detail" + }, + "normalized_coordinates": { + "anyOf": [ + { + "items": { + "type": "integer" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Normalized Coordinates" + }, + "duration_ms": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Duration Ms" + } + }, + "required": [ + "ok", + "code", + "action", + "message" + ], + "title": "ActionResult", + "type": "object" + } } } diff --git a/tests/fixtures/action_surfaces/operator_shells.json b/tests/fixtures/action_surfaces/operator_shells.json index 6f3e6c815..3be0ba75f 100644 --- a/tests/fixtures/action_surfaces/operator_shells.json +++ b/tests/fixtures/action_surfaces/operator_shells.json @@ -347,5 +347,209 @@ "type": "object" } } + }, + "perform_gesture": { + "type": "function", + "function": { + "name": "perform_gesture", + "description": "[ACTION] Perform continuous touch gestures that a normal swipe cannot express: simultaneous multi-finger input, continuous holds and drags, or delayed release. Coordinates use 0-1000 screen space. In explicit phases, pointers move together; a one-point path holds still. Keep the same pointer IDs and join endpoints across phases to maintain contact until the final release. Optional control_points define a cubic Bezier path with two endpoints and two controls. Alternatively, provide one long_press_drag entry with start and end coordinates and optional control_points. The endpoint is freely chosen, including inside the screen. duration_ms is movement time; release_delay_ms is the endpoint hold before lifting (zero releases immediately). Observe the screen afterward to verify the intended effect. target_description states the intended surface/objects and gesture purpose, not a claimed observation.", + "parameters": { + "properties": { + "phases": { + "description": "Explicit continuous phases or a single native long_press_drag object.", + "items": { + "anyOf": [ + { + "additionalProperties": false, + "properties": { + "duration_ms": { + "maximum": 5000, + "minimum": 1, + "title": "Duration Ms", + "type": "integer" + }, + "pointers": { + "items": { + "additionalProperties": false, + "properties": { + "id": { + "maximum": 9, + "minimum": 0, + "title": "Id", + "type": "integer" + }, + "path": { + "items": { + "items": { + "maximum": 1000, + "minimum": 0, + "type": "integer" + }, + "maxItems": 2, + "minItems": 2, + "type": "array" + }, + "maxItems": 128, + "minItems": 1, + "title": "Path", + "type": "array" + }, + "control_points": { + "anyOf": [ + { + "items": { + "items": { + "maximum": 1000, + "minimum": 0, + "type": "integer" + }, + "maxItems": 2, + "minItems": 2, + "type": "array" + }, + "maxItems": 2, + "minItems": 2, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Two cubic Bezier control points. When supplied, path must contain only start and end; Android builds the curve natively.", + "title": "Control Points" + } + }, + "required": [ + "id", + "path" + ], + "title": "GesturePointer", + "type": "object" + }, + "maxItems": 10, + "minItems": 1, + "title": "Pointers", + "type": "array" + } + }, + "required": [ + "duration_ms", + "pointers" + ], + "title": "GesturePhase", + "type": "object" + }, + { + "additionalProperties": false, + "description": "Hold, move to a caller-selected endpoint, optionally dwell, then release.", + "properties": { + "kind": { + "const": "long_press_drag", + "title": "Kind", + "type": "string" + }, + "start": { + "items": { + "maximum": 1000, + "minimum": 0, + "type": "integer" + }, + "maxItems": 2, + "minItems": 2, + "title": "Start", + "type": "array" + }, + "end": { + "items": { + "maximum": 1000, + "minimum": 0, + "type": "integer" + }, + "maxItems": 2, + "minItems": 2, + "title": "End", + "type": "array" + }, + "control_points": { + "anyOf": [ + { + "items": { + "items": { + "maximum": 1000, + "minimum": 0, + "type": "integer" + }, + "maxItems": 2, + "minItems": 2, + "type": "array" + }, + "maxItems": 2, + "minItems": 2, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Two cubic Bezier controls between start and end. Omit for a straight path.", + "title": "Control Points" + }, + "duration_ms": { + "default": 800, + "maximum": 5000, + "minimum": 1, + "title": "Duration Ms", + "type": "integer" + }, + "hold_ms": { + "anyOf": [ + { + "maximum": 5000, + "minimum": 1, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Omit to use the device long-press timeout plus 150ms.", + "title": "Hold Ms" + }, + "release_delay_ms": { + "default": 0, + "description": "Keep the same finger down at the endpoint for this long, then lift. Zero lifts immediately after moving; independent of movement duration.", + "maximum": 5000, + "minimum": 0, + "title": "Release Delay Ms", + "type": "integer" + } + }, + "required": [ + "kind", + "start", + "end" + ], + "title": "LongPressDrag", + "type": "object" + } + ] + }, + "type": "array" + }, + "target_description": { + "description": "Target surface/objects and gesture purpose.", + "type": "string" + } + }, + "required": [ + "phases", + "target_description" + ], + "type": "object" + } + } } } diff --git a/tests/fixtures/action_surfaces/tool_declarations.json b/tests/fixtures/action_surfaces/tool_declarations.json index 33f5ac854..15a326939 100644 --- a/tests/fixtures/action_surfaces/tool_declarations.json +++ b/tests/fixtures/action_surfaces/tool_declarations.json @@ -310,5 +310,194 @@ ] } } + }, + "PERFORM_GESTURE_TOOL": { + "type": "function", + "function": { + "name": "perform_gesture", + "description": "[ACTION] Perform continuous touch gestures that a normal swipe cannot express: simultaneous multi-finger input, continuous holds and drags, or delayed release. Coordinates use 0-1000 screen space. In explicit phases, pointers move together; a one-point path holds still. Keep the same pointer IDs and join endpoints across phases to maintain contact until the final release. Optional control_points define a cubic Bezier path with two endpoints and two controls. Alternatively, provide one long_press_drag entry with start and end coordinates and optional control_points. The endpoint is freely chosen, including inside the screen. duration_ms is movement time; release_delay_ms is the endpoint hold before lifting (zero releases immediately). Observe the screen afterward to verify the intended effect. target_description states the intended surface/objects and gesture purpose, not a claimed observation.", + "parameters": { + "type": "object", + "properties": { + "phases": { + "type": "array", + "items": { + "anyOf": [ + { + "additionalProperties": false, + "properties": { + "duration_ms": { + "maximum": 5000, + "minimum": 1, + "type": "integer" + }, + "pointers": { + "items": { + "additionalProperties": false, + "properties": { + "id": { + "maximum": 9, + "minimum": 0, + "type": "integer" + }, + "path": { + "items": { + "items": { + "maximum": 1000, + "minimum": 0, + "type": "integer" + }, + "maxItems": 2, + "minItems": 2, + "type": "array" + }, + "maxItems": 128, + "minItems": 1, + "type": "array" + }, + "control_points": { + "anyOf": [ + { + "items": { + "items": { + "maximum": 1000, + "minimum": 0, + "type": "integer" + }, + "maxItems": 2, + "minItems": 2, + "type": "array" + }, + "maxItems": 2, + "minItems": 2, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Two cubic Bezier control points. When supplied, path must contain only start and end; Android builds the curve natively." + } + }, + "required": [ + "id", + "path" + ], + "type": "object" + }, + "maxItems": 10, + "minItems": 1, + "type": "array" + } + }, + "required": [ + "duration_ms", + "pointers" + ], + "type": "object" + }, + { + "additionalProperties": false, + "description": "Hold, move to a caller-selected endpoint, optionally dwell, then release.", + "properties": { + "kind": { + "const": "long_press_drag", + "type": "string" + }, + "start": { + "items": { + "maximum": 1000, + "minimum": 0, + "type": "integer" + }, + "maxItems": 2, + "minItems": 2, + "type": "array" + }, + "end": { + "items": { + "maximum": 1000, + "minimum": 0, + "type": "integer" + }, + "maxItems": 2, + "minItems": 2, + "type": "array" + }, + "control_points": { + "anyOf": [ + { + "items": { + "items": { + "maximum": 1000, + "minimum": 0, + "type": "integer" + }, + "maxItems": 2, + "minItems": 2, + "type": "array" + }, + "maxItems": 2, + "minItems": 2, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Two cubic Bezier controls between start and end. Omit for a straight path." + }, + "duration_ms": { + "default": 800, + "maximum": 5000, + "minimum": 1, + "type": "integer" + }, + "hold_ms": { + "anyOf": [ + { + "maximum": 5000, + "minimum": 1, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Omit to use the device long-press timeout plus 150ms." + }, + "release_delay_ms": { + "default": 0, + "description": "Keep the same finger down at the endpoint for this long, then lift. Zero lifts immediately after moving; independent of movement duration.", + "maximum": 5000, + "minimum": 0, + "type": "integer" + } + }, + "required": [ + "kind", + "start", + "end" + ], + "type": "object" + } + ] + }, + "description": "Explicit continuous phases or a single native long_press_drag object." + }, + "target_description": { + "type": "string", + "description": "Target surface/objects and gesture purpose." + } + }, + "required": [ + "phases", + "target_description" + ] + } + } } } diff --git a/tests/tools/operator/test_operator_tools.py b/tests/tools/operator/test_operator_tools.py index 8fe40927b..3f2481258 100644 --- a/tests/tools/operator/test_operator_tools.py +++ b/tests/tools/operator/test_operator_tools.py @@ -25,6 +25,10 @@ async def test_operator_shell_tools(): "click": {"target": 1, "times": 1, "delay_ms": 100}, "input_text": {"text": "hello", "target": 1, "clear_exist": True}, "swipe": {"gesture": "up"}, + "perform_gesture": { + "phases": [{"kind": "long_press_drag", "start": [300, 400], "end": [650, 550]}], + "target_description": "move the selected object", + }, "press_key": {"key": "ENTER"}, "manage_app": {"action": "launch", "app_name": "Settings"}, "wait_for_delay": {"time_in_ms": 1000}, diff --git a/tests/unit/agents/test_operator_transcript.py b/tests/unit/agents/test_operator_transcript.py index 0fa9b5b78..3d968523d 100644 --- a/tests/unit/agents/test_operator_transcript.py +++ b/tests/unit/agents/test_operator_transcript.py @@ -53,9 +53,10 @@ ) # SHA-256 snapshots of the legacy system message with the fixed inputs below. +# Updated for perform_gesture in the physical/turn-ending action lists. # Update these when an intentional template change alters the rendered prompt. -GOLDEN_EMPTY_PLAN = "513e0341014b9a2342f608ad4dd173b7dcf5704ce53ee028ba302a9a1b696f96" -GOLDEN_SENTINEL_PLAN = "012fe1b08645266d5a7e518023e20fc6fbfa65d4f2d985847ebb06e0184c67ee" +GOLDEN_EMPTY_PLAN = "5ce954de33ba8c77aa14597b1bd78539a48e3e11009626c70fc04fb98e157715" +GOLDEN_SENTINEL_PLAN = "561f3e0717a6a5e09dee0bb9b79c9b28ed96afa9221258295f02222ac92d3370" SCREENSHOT_B64 = base64.b64encode(b"fake-jpeg-bytes").decode("utf-8") @@ -77,7 +78,9 @@ async def _render_legacy_system(plan_and_history: str) -> str: @pytest.mark.asyncio -async def test_legacy_prompt_bytes_match_pre_split_golden(): +async def test_legacy_prompt_bytes_match_pre_split_golden(monkeypatch): + # The legacy golden excludes optional node-configured quality capabilities. + monkeypatch.setenv("ARTEMIS_QUALITY_TOOLS", "[]") empty = await _render_legacy_system("No plan or history yet.") sentinel = await _render_legacy_system("PLAN_AND_HISTORY_SENTINEL\nline2") assert hashlib.sha256(empty.encode("utf-8")).hexdigest() == GOLDEN_EMPTY_PLAN diff --git a/tests/unit/agents/test_prompt_assembly.py b/tests/unit/agents/test_prompt_assembly.py index f924f3d9c..f0acb4fa4 100644 --- a/tests/unit/agents/test_prompt_assembly.py +++ b/tests/unit/agents/test_prompt_assembly.py @@ -33,6 +33,7 @@ "click", "input_text", "swipe", + "perform_gesture", "press_key", "manage_app", "wait_for_delay", @@ -131,23 +132,25 @@ def test_reduced_enums_stay_well_formed(): available_tools=OPERATOR_PROMPT_TOOLSET - {"manage_app", "wait_for_delay"}, ) assert ( - "Physical device actions (`click`, `input_text`, `swipe`, `press_key`, `long_press`)" in out + "Physical device actions (`click`, `input_text`, `swipe`, `perform_gesture`, `press_key`, `long_press`)" + in out ) assert ( - "Turn-Ending Action (`click`, `swipe`, `input_text`, `long_press`, or `press_key`)" in out + "Turn-Ending Action (`click`, `swipe`, `perform_gesture`, `input_text`, `long_press`, or `press_key`)" + in out ) def test_full_set_enum_slots_render_verbatim(): - """With every tool present the historical enumeration wording is reproduced.""" + """The new primitive appears alongside the existing physical actions.""" template = load_operator_prompts()["main_template"] out = apply_operator_prompt_contract(template) assert ( - "Physical device actions (`click`, `input_text`, `swipe`, `press_key`," + "Physical device actions (`click`, `input_text`, `swipe`, `perform_gesture`, `press_key`," " `manage_app`, `wait_for_delay`, `long_press`)" in out ) assert ( - "Turn-Ending Action (`click`, `swipe`, `input_text`, `long_press`," + "Turn-Ending Action (`click`, `swipe`, `perform_gesture`, `input_text`, `long_press`," " `press_key`, `manage_app`, or `wait_for_delay`)" in out ) assert "Helper/Subagent tools (`ask_explorer`, `ask_diagnoser`, `video_analyzer`)" in out @@ -162,6 +165,21 @@ def test_full_set_enum_slots_render_verbatim(): assert "analyze_task_output" not in out +def test_without_gesture_the_upstream_action_enumerations_are_unchanged(): + out = apply_operator_prompt_contract( + load_operator_prompts()["main_template"], + available_tools=OPERATOR_PROMPT_TOOLSET - {"perform_gesture"}, + ) + assert ( + "Physical device actions (`click`, `input_text`, `swipe`, `press_key`," + " `manage_app`, `wait_for_delay`, `long_press`)" in out + ) + assert ( + "Turn-Ending Action (`click`, `swipe`, `input_text`, `long_press`," + " `press_key`, `manage_app`, or `wait_for_delay`)" in out + ) + + # --- Flash prompt assembly ----------------------------------------------------------- diff --git a/tests/unit/llm/test_platform_run_model.py b/tests/unit/llm/test_platform_run_model.py new file mode 100644 index 000000000..568d824eb --- /dev/null +++ b/tests/unit/llm/test_platform_run_model.py @@ -0,0 +1,117 @@ +"""Check the managed worker's actual HTTP request for both provider schemas.""" + +import json +import os +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from threading import Thread +from uuid import uuid4 + +import pytest + +from artemis.config import initialize_llm_config +from artemis.config.run_model import MODEL_ENV, MODEL_KEY_ENV, RunModel, current_run_model +from artemis.services.llm import _resolve_endpoint +from artemis.llm.router import ModelFactory + + +@pytest.mark.parametrize( + ("schema", "key"), [("openai", "scoped-key"), ("anthropic", ""), ("anthropic", "scoped-key")] +) +def test_platform_model_is_used_for_wire_request(monkeypatch, schema, key): + received = [] + + class Provider(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_POST(self): + payload = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + received.append((self.path, dict(self.headers), payload)) + if schema == "openai": + body = { + "id": "fixture", + "object": "chat.completion", + "created": 1, + "model": payload["model"], + "choices": [ + { + "index": 0, + "finish_reason": "stop", + "message": {"role": "assistant", "content": "OK"}, + } + ], + } + else: + body = { + "id": "fixture", + "type": "message", + "role": "assistant", + "model": payload["model"], + "stop_reason": "end_turn", + "content": [{"type": "text", "text": "OK"}], + "usage": {"input_tokens": 1, "output_tokens": 1}, + } + data = json.dumps(body).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + server = ThreadingHTTPServer(("127.0.0.1", 0), Provider) + thread = Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + spec = RunModel( + config_id=uuid4(), + revision=2, + model_id="fixture/platform-model", + api_schema=schema, + url=f"http://127.0.0.1:{server.server_port}/v1", + context_window=32768, + thinking_effort="high", + ) + current_run_model.cache_clear() + monkeypatch.setenv(MODEL_ENV, spec.model_dump_json()) + monkeypatch.setenv(MODEL_KEY_ENV, key) + monkeypatch.setenv("OPENAI_API_KEY", "unrelated-node-key") + monkeypatch.setenv("ANTHROPIC_API_KEY", "unrelated-node-key") + monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", "unrelated-auth-token") + config = initialize_llm_config() + assert config.planner.model == spec.model_id + from third_party.mobile_use.config.llm import settings + + monkeypatch.setattr(settings, "OPENAI_API_KEY", None) + monkeypatch.setattr(settings, "ANTHROPIC_API_KEY", None) + # The SDK builder repeats this validation after initialize_llm_config. + # A per-task credential must never require a node-local credential. + config.validate_providers() + assert MODEL_KEY_ENV not in os.environ + endpoint = _resolve_endpoint(None, "operator", use_fallback=True) + assert endpoint.model_name == spec.model_id and endpoint.api_base == spec.url + assert ModelFactory.create_model(endpoint).invoke("Reply OK").content == "OK" + path, headers, payload = received[0] + headers = {k.lower(): v for k, v in headers.items()} + assert payload["model"] == spec.model_id + assert "unrelated" not in json.dumps(headers) + if schema == "openai": + assert path == "/v1/chat/completions" + assert headers["authorization"] == f"Bearer {key}" + assert payload["reasoning_effort"] == "high" + else: + assert path == "/v1/messages" + assert headers.get("x-api-key") == (key or None) + assert "authorization" not in headers + assert payload["thinking"] == {"type": "adaptive"} + assert payload["output_config"]["effort"] == "high" + # Standalone runs must retain their original credential validation. + current_run_model.cache_clear() + monkeypatch.delenv("OPENAI_API_KEY", raising=False) + monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False) + with pytest.raises(Exception, match="requires"): + config.validate_providers() + finally: + current_run_model.cache_clear() + server.shutdown() + server.server_close() + thread.join() diff --git a/tests/unit/mcp/test_action_specs.py b/tests/unit/mcp/test_action_specs.py index d89c2777f..fb635d929 100644 --- a/tests/unit/mcp/test_action_specs.py +++ b/tests/unit/mcp/test_action_specs.py @@ -83,6 +83,7 @@ def test_tool_declarations_match_fixture(): "LONG_PRESS_TOOL": "long_press", "INPUT_TEXT_TOOL": "input_text", "SWIPE_TOOL": "swipe", + "PERFORM_GESTURE_TOOL": "perform_gesture", "PRESS_KEY_TOOL": "press_key", "MANAGE_APP_TOOL": "manage_app", "WAIT_FOR_DELAY_TOOL": "wait_for_delay", @@ -121,6 +122,7 @@ def test_validator_declaration_order_is_stable(): "long_press", "input_text", "swipe", + "perform_gesture", "press_key", "read_note", "list_notes", @@ -138,6 +140,18 @@ def _without_optional_noise(schema: dict) -> dict: ``default`` and the ``null`` alternative say "optional"; the declaration says that through ``required`` alone. """ + + # LangChain retains Pydantic titles inside array-item unions, while the + # declaration projector removes them. Compare semantics, retaining bounds, + # required fields, defaults inside models, and every union alternative. + def without_titles(value): + if isinstance(value, list): + return [without_titles(v) for v in value] + if isinstance(value, dict): + return {k: without_titles(v) for k, v in value.items() if k != "title"} + return value + + schema = without_titles(schema) out = {k: v for k, v in schema.items() if k not in ("anyOf", "default")} if "anyOf" in schema: members = [m for m in schema["anyOf"] if m.get("type") != "null"] diff --git a/tests/unit/mcp/test_gesture_compatibility.py b/tests/unit/mcp/test_gesture_compatibility.py new file mode 100644 index 000000000..b8fc3131a --- /dev/null +++ b/tests/unit/mcp/test_gesture_compatibility.py @@ -0,0 +1,201 @@ +# 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. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Pin existing action contracts and execution behavior while adding gestures.""" + +from copy import deepcopy +import hashlib +import json +from types import SimpleNamespace +from unittest.mock import AsyncMock, Mock, patch + +from langchain_core.utils.function_calling import convert_to_openai_tool +import pytest + +from artemis.agents.validator.action_execution import exec_action +from artemis.agents.validator.execution_loop import _process_action +from artemis.mcp.action_server import build_action_server +from artemis.mcp.action_specs import OPERATOR_SHELL_ORDER, operator_shell_tool, tool_declaration +from artemis.mcp.action_types import ActionCode, ActionResult +from artemis.mcp.actuators import MockActuator +from artemis.utils.task_tree import format_action_clean, format_action_intent, format_result_clean + + +# Canonical JSON digests of the upstream 351ca84 fixtures, before perform_gesture. +# These pins are independent of the new gesture fixture and require no Git at test time. +LEGACY_SCHEMAS = { + "operator": "51882b1d081f24fa0dc8e79cd74a94ed13ee3eccda84cdc233bbbd0515cf8ad0", + "declarations": "ba06a25d8587769f9c518329706f6f1f15826a071a4db995f41c85a73c9d796f", + "wire": "ea41842f9a3440dd2eef2ccb5e156c8a136fb13319e5c7751f3d0653daacdd85", +} + + +def digest(value): + return hashlib.sha256( + json.dumps(value, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest() + + +@pytest.mark.asyncio +async def test_existing_action_schemas_and_descriptions_match_upstream(): + operator = { + name: convert_to_openai_tool(operator_shell_tool(name)) + for name in OPERATOR_SHELL_ORDER + if name != "perform_gesture" + } + declarations = { + name.upper() + "_TOOL": dict(tool_declaration(name)) + for name in ( + "click", + "click_sequence", + "long_press", + "input_text", + "swipe", + "press_key", + "manage_app", + "wait_for_delay", + ) + } + tools = await build_action_server(MockActuator()).list_tools() + wire = { + t.name: { + "description": t.description, + "inputSchema": t.inputSchema, + "outputSchema": t.outputSchema, + } + for t in tools + if t.name != "perform_gesture" + } + assert digest(operator) == LEGACY_SCHEMAS["operator"] + assert digest(declarations) == LEGACY_SCHEMAS["declarations"] + assert digest(wire) == LEGACY_SCHEMAS["wire"] + + +LEGACY_ACTIONS = [ + ( + {"action": "tap", "normalized_coordinates": [300, 400]}, + "click", + {"target": [300, 400], "times": 1, "delay_ms": 100}, + ), + ( + {"action": "swipe", "normalized_coordinates": [300, 400, 650, 550], "duration": 800}, + "swipe", + {"start": [300, 400], "end": [650, 550], "duration_ms": 800}, + ), + ( + {"action": "focus_and_input_text", "normalized_coordinates": [300, 400], "text": "hello"}, + "input_text", + {"target": [300, 400], "text": "hello", "clear_exist": False}, + ), + ( + {"action": "launch_app", "app_name": "settings"}, + "manage_app", + {"action": "launch", "app_name": "settings"}, + ), + ({"action": "press_key", "keycode": "KEYCODE_HOME"}, "press_key", {"key": "home"}), + ({"action": "back"}, "press_key", {"key": "back"}), +] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("action,name,wire", LEGACY_ACTIONS) +@pytest.mark.parametrize("ok", [True, False]) +async def test_existing_action_results_do_not_add_history_fields(action, name, wire, ok): + original = deepcopy(action) + result = ( + ActionResult.success(name, "completed") + if ok + else ActionResult.failure(name, "outcome unknown", code=ActionCode.TIMEOUT) + ) + session = Mock(call=AsyncMock(return_value=result)) + assert await exec_action(SimpleNamespace(device=None), session, action) == ( + (True, "") if ok else (False, "outcome unknown") + ) + session.call.assert_awaited_once_with(name, wire) + assert action == original + assert format_result_clean({"status": "dispatched", "execution": [action]}) is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "action", ["tap", "swipe", "focus_and_input_text", "launch_app", "press_key", "perform_gesture"] +) +@pytest.mark.parametrize("burst", [False, True]) +@pytest.mark.parametrize("throws", [False, True]) +async def test_retry_change_is_scoped_to_perform_gesture(action, burst, throws): + execute = ( + AsyncMock(side_effect=TimeoutError("outcome unknown")) + if throws + else AsyncMock(return_value=(False, "outcome unknown")) + ) + node = SimpleNamespace(_exec_action=execute) + with ( + patch( + "artemis.agents.validator.execution_loop._run_precondition_gate", + AsyncMock(return_value=(True, None, "")), + ), + patch( + "artemis.agents.validator.execution_loop._capture_live_screenshot", + AsyncMock(return_value=None), + ), + patch("artemis.agents.validator.execution_loop.asyncio.sleep", AsyncMock()), + ): + outcome = await _process_action( + node, Mock(), Mock(), {"action": action}, action, "", burst=burst + ) + expected_attempts = 1 if burst or action in ("launch_app", "perform_gesture") else 2 + assert not outcome.success + assert execute.await_count == expected_attempts + assert outcome.action_item == { + "action": action, + "attempts": ["outcome unknown"] * expected_attempts, + } + + +@pytest.mark.parametrize( + "action,past,intent", + [ + ( + {"action": "click", "target": [300, 400], "target_description": "button"}, + "Tapped 'button' (self-described) at [300, 400]", + "tap 'button' (self-described) at [300, 400]", + ), + ( + {"action": "swipe", "coordinates": [300, 400, 650, 550], "duration": 800}, + "Swiped from [300, 400] to [650, 550] over 800ms", + "swipe from [300, 400] to [650, 550] over 800ms", + ), + ( + { + "action": "input_text", + "text": "hello", + "target": [300, 400], + "target_description": "search field", + }, + "Inputted 'hello' into 'search field' (self-described) at [300, 400]", + "type 'hello' into 'search field' (self-described) at [300, 400]", + ), + ({"action": "press_key", "key": "home"}, "Pressed key 'home'", "press key 'home'"), + ], +) +def test_existing_history_rendering_matches_upstream(action, past, intent): + assert format_action_clean(action) == past + assert format_action_intent(action) == intent + assert format_result_clean({"status": "dispatched", "execution": [action]}) is None + assert ( + format_result_clean( + {"status": "failed", "execution": [{**action, "attempts": ["timeout"]}]} + ) + == "Error: timeout" + ) diff --git a/tests/unit/mcp/test_gestures.py b/tests/unit/mcp/test_gestures.py new file mode 100644 index 000000000..218454423 --- /dev/null +++ b/tests/unit/mcp/test_gestures.py @@ -0,0 +1,452 @@ +# 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. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Multi-touch semantics, model reachability, and no-replay transport regressions.""" + +import asyncio +import json +from unittest.mock import AsyncMock, Mock, patch + +import pytest +from pydantic import ValidationError +from artemis.clients.accessibility_client import AccessibilityClient +from artemis.mcp.gestures import validate_phases +from artemis.mcp.action_names import to_canonical_call +from artemis.mcp.action_specs import operator_shell_tool, tool_declaration +from artemis.mcp.action_executor import McpActionExecutor, _ArgError +from artemis.mcp.action_session import ActionSession +from artemis.mcp.action_server import build_action_server +from artemis.mcp.actuators.mock import MockActuator +from artemis.mcp.action_types import ActionCode + + +def phase(points=None, duration=500): + return { + "duration_ms": duration, + "pointers": points + or [{"id": i, "path": [[x, 300], [x, 700]]} for i, x in enumerate([300, 500, 700])], + } + + +def drag(): + return [ + phase([{"id": 0, "path": [[300, 400]]}], 700), + phase([{"id": 0, "path": [[300, 400], [980, 400]]}], 800), + phase([{"id": 0, "path": [[980, 400]]}], 1000), + ] + + +def curved_drag(): + phases = drag() + phases[1]["pointers"][0]["control_points"] = [[450, 300], [800, 300]] + return phases + + +def long_press_drag(delay=0): + return [ + { + "kind": "long_press_drag", + "start": [300, 400], + "end": [650, 550], + "duration_ms": 800, + "release_delay_ms": delay, + } + ] + + +@pytest.mark.parametrize("delay", [0, 1200, 5000]) +def test_long_press_drag_keeps_endpoint_hold_distinct_from_movement(delay): + from artemis.mcp.gestures import gesture_duration_bound_ms + + plan = long_press_drag(delay) + assert validate_phases(plan) == plan + assert gesture_duration_bound_ms(plan) == 5000 + 800 + delay + plan[0]["hold_ms"] = 700 + assert gesture_duration_bound_ms(validate_phases(plan)) == 700 + 800 + delay + schema = json.dumps(tool_declaration("perform_gesture").parameters) + assert '"release_delay_ms"' in schema and '"long_press_drag"' in schema + + +@pytest.mark.parametrize( + "field,value", + [ + ("release_delay_ms", -1), + ("release_delay_ms", 5001), + ("release_delay_ms", True), + ("release_delay_ms", 0.5), + ("hold_ms", 0), + ("direction", "right"), + ("start", [1001, 0]), + ("end", [-1, 400]), + ("end", [400]), + ("duration_ms", 0), + ("control_points", [[100, 200]]), + ("control_points", [[100, 200], [300, 1001]]), + ], +) +def test_invalid_long_press_drag_rejected(field, value): + plan = long_press_drag() + plan[0][field] = value + with pytest.raises(ValidationError): + validate_phases(plan) + + +def test_long_press_drag_cannot_mix_with_manual_phases(): + with pytest.raises(ValidationError): + validate_phases(long_press_drag() + drag()) + with pytest.raises(ValidationError): + validate_phases(drag() + long_press_drag()) + + +@pytest.mark.parametrize("endpoint", [[650, 550], [400, 200], [20, 400], [980, 400]]) +def test_long_press_drag_keeps_caller_endpoint_and_bezier_controls(endpoint): + plan = long_press_drag(1200) + plan[0]["end"] = endpoint + plan[0]["control_points"] = [[400, 250], [600, 250]] + assert validate_phases(plan) == plan + executor = McpActionExecutor(Mock(), actuator=Mock()) + _, wire, _, _ = executor._translate( + "perform_gesture", {"phases": plan, "target_description": "drag selected object"}, Mock() + ) + assert wire["phases"] == plan + + +def test_long_press_drag_requires_an_explicit_endpoint(): + plan = long_press_drag() + del plan[0]["end"] + with pytest.raises(ValidationError): + validate_phases(plan) + + +def test_curve_controls_are_preserved_without_host_sampling(): + assert validate_phases(curved_drag()) == curved_drag() + schema = json.dumps(tool_declaration("perform_gesture").parameters) + assert "control_points" in schema + assert "Bezier" in operator_shell_tool("perform_gesture").description + + +@pytest.mark.parametrize( + "controls", + [ + [], + [[1, 2]], + [[1, 2]] * 3, + [[-1, 2], [3, 4]], + [[1.5, 2], [3, 4]], + [[True, 2], [3, 4]], + [[1, 2, 3], [3, 4]], + ], +) +def test_invalid_curve_controls_rejected(controls): + phases = curved_drag() + phases[1]["pointers"][0]["control_points"] = controls + with pytest.raises(ValidationError): + validate_phases(phases) + + +@pytest.mark.parametrize("path", [[[300, 400]], [[300, 400], [500, 400], [980, 400]]]) +def test_curve_requires_only_start_and_end(path): + phases = curved_drag() + phases[1]["pointers"][0]["path"] = path + with pytest.raises(ValidationError): + validate_phases(phases) + + +def test_three_fingers_and_continuous_drag_are_valid(): + assert len(validate_phases([phase()])[0]["pointers"]) == 3 + assert validate_phases(drag()) == drag() + + +@pytest.mark.parametrize( + "mutate", + [ + lambda p: p[0]["pointers"][0]["path"][0].__setitem__(0, True), + lambda p: p[0]["pointers"][0]["path"][0].__setitem__(0, 1.5), + lambda p: p[0]["pointers"][0]["path"][0].__setitem__(0, "30"), + lambda p: p[0]["pointers"][0]["path"][0].__setitem__(0, 1001), + lambda p: p[0]["pointers"][0].__setitem__("id", 1), + lambda p: p[0].__setitem__("duration_ms", 0), + lambda p: p[0].__setitem__("duration_ms", 5001), + lambda p: p[0].__setitem__("unexpected", True), + lambda p: p[0]["pointers"][0].__setitem__("path", []), + ], +) +def test_invalid_input_is_rejected(mutate): + p = [phase()] + mutate(p) + with pytest.raises(ValidationError): + validate_phases(p) + + +@pytest.mark.parametrize("change", ["jump", "ids", "budget"]) +def test_continuity_and_total_budget(change): + p = drag() + if change == "jump": + p[1]["pointers"][0]["path"][0][0] = 500 + elif change == "ids": + p[1]["pointers"][0]["id"] = 1 + else: + p = [phase([{"id": 0, "path": [[500, 500]]}], 5000)] * 7 + with pytest.raises(ValidationError): + validate_phases(p) + + +def test_model_schema_has_nested_paths_and_shared_semantics(): + shell = operator_shell_tool("perform_gesture") + args = shell.args_schema(phases=drag(), target_description="launcher icon") + assert validate_phases(args.phases) == drag() + declaration = tool_declaration("perform_gesture") + encoded = json.dumps(declaration.parameters) + assert "$ref" not in encoded and '"duration_ms"' in encoded and '"pointers"' in encoded + assert "maintain contact" in shell.description and "Observe the screen" in shell.description + + +@pytest.mark.parametrize("plan", [drag(), curved_drag(), long_press_drag(), long_press_drag(1200)]) +def test_pro_and_flash_lower_to_the_same_plan_without_early_execution(plan): + from artemis.agents.operator.operator import OperatorNode + + node = OperatorNode(Mock()) + arguments = {"phases": plan, "target_description": "launcher icon"} + decisions, error = node._translate_and_validate_tool( + {"name": "perform_gesture", "args": arguments}, Mock() + ) + assert error is None and decisions[0]["target_description"] == "launcher icon" + pro_name, pro_args = to_canonical_call(decisions[0]) + executor = McpActionExecutor(Mock(), actuator=Mock()) + name, wire, _, recorded = executor._translate("perform_gesture", arguments, Mock()) + assert (name, wire) == (pro_name, pro_args) + assert recorded["target_description"] == "launcher icon" + assert "target_description" not in wire + with pytest.raises(_ArgError): + executor._translate("perform_gesture", {"phases": drag()}, Mock()) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("plan", [drag(), long_press_drag(), long_press_drag(1200)]) +async def test_mcp_executes_all_phases_as_one_action(plan): + actuator = MockActuator() + session = ActionSession(build_action_server(actuator)) + await session.start() + try: + result = await session.call("perform_gesture", {"phases": plan}) + assert result.ok, result + actions = [a for a in actuator.action_history if a["action"] == "perform_gesture"] + assert actions == [{"action": "perform_gesture", "phases": plan}] + finally: + await session.aclose() + + +@pytest.mark.asyncio +async def test_missing_or_incomplete_helper_does_not_succeed(): + actuator = MockActuator() + actuator.controller.perform_gesture = AsyncMock( + return_value={"success": False, "status": "unsupported", "error": "old helper"} + ) + assert (await actuator.perform_gesture([phase()])).code == ActionCode.UNSUPPORTED + actuator.controller.perform_gesture.return_value = { + "success": True, + "status": "completed", + "release_confirmed": False, + } + assert not (await actuator.perform_gesture([phase()])).ok + + +def client_with_capabilities(): + client = AccessibilityClient("test-device") + client._http = Mock( + side_effect=[ + json.dumps( + {"capabilities": ["perform_gesture"], "gesture_continuation": True} + ).encode(), + json.dumps( + {"success": True, "status": "completed", "release_confirmed": True} + ).encode(), + ] + ) + return client + + +def test_helper_receives_one_plan_with_duration_aware_timeout(): + client = client_with_capabilities() + assert client.perform_gesture(drag(), "request-1")["success"] + args, kwargs = client._http.call_args + assert args == ( + "/action", + {"cmd": "perform_gesture", "request_id": "request-1", "phases": drag()}, + ) + assert kwargs["timeout"] == 12.5 + + +def test_helper_probe_prevents_actions_on_old_apk(): + client = client_with_capabilities() + client._http.side_effect = [b"{}"] + assert client.perform_gesture(drag(), "request-1")["status"] == "unsupported" + assert client._http.call_count == 1 + + +def test_old_helper_rejects_curve_before_any_touch(): + client = client_with_capabilities() + assert client.perform_gesture(curved_drag(), "curve")["status"] == "unsupported" + assert client._http.call_count == 1 + + +def test_old_helper_rejects_long_press_drag_without_input(): + client = client_with_capabilities() + assert client.perform_gesture(long_press_drag(), "long-press-drag")["status"] == "unsupported" + assert client._http.call_count == 1 + + +def test_long_press_drag_transmitted_without_host_geometry_and_with_full_timeout(): + client = client_with_capabilities() + client._http.side_effect = [ + b'{"capabilities":["perform_gesture","gesture_long_press_drag"],"gesture_continuation":true}', + b'{"success":true,"status":"completed","release_confirmed":true}', + ] + assert client.perform_gesture(long_press_drag(1200), "long-press-drag")["success"] + assert client._http.call_args.args[1]["phases"] == long_press_drag(1200) + assert client._http.call_args.kwargs["timeout"] == 17 + + +def test_curved_long_press_drag_checks_capability_before_input(): + client = client_with_capabilities() + client._http.side_effect = [ + b'{"capabilities":["perform_gesture","gesture_long_press_drag"],"gesture_continuation":true}', + ] + plan = long_press_drag() + plan[0]["control_points"] = [[400, 250], [600, 250]] + assert client.perform_gesture(plan, "curve")["status"] == "unsupported" + assert client._http.call_count == 1 + + +def test_curved_long_press_drag_reaches_helper_with_interior_endpoint(): + client = client_with_capabilities() + client._http.side_effect = [ + b'{"capabilities":["perform_gesture","gesture_long_press_drag","gesture_cubic_bezier"],"gesture_continuation":true}', + b'{"success":true,"status":"completed","release_confirmed":true}', + ] + plan = long_press_drag(1000) + plan[0]["control_points"] = [[400, 250], [600, 250]] + assert client.perform_gesture(plan, "curve")["success"] + assert client._http.call_args.args[1]["phases"] == plan + + +@pytest.mark.parametrize("plan", [drag(), long_press_drag()]) +def test_helper_without_continuation_rejects_before_input(plan): + client = client_with_capabilities() + client._http.side_effect = [ + b'{"capabilities":["perform_gesture","gesture_long_press_drag"],"gesture_continuation":false}', + ] + assert client.perform_gesture(plan, "android7")["status"] == "unsupported" + assert client._http.call_count == 1 + + +def test_curve_controls_reach_native_helper_unchanged(): + client = client_with_capabilities() + client._http.side_effect = [ + b'{"capabilities":["perform_gesture","gesture_cubic_bezier"],"gesture_continuation":true}', + b'{"success":true,"status":"completed","release_confirmed":true}', + ] + assert client.perform_gesture(curved_drag(), "curve")["success"] + assert client._http.call_args.args[1]["phases"] == curved_drag() + + +def test_lost_action_response_is_not_replayed(): + client = client_with_capabilities() + client._http.side_effect = [ + b'{"capabilities":["perform_gesture"],"gesture_continuation":true}', + TimeoutError(), + ] + with pytest.raises(TimeoutError): + client.perform_gesture(drag(), "request-1") + assert client._http.call_count == 2 + + +@pytest.mark.asyncio +async def test_driver_cancel_targets_the_same_request_and_waits_for_release(): + import threading + from artemis.drivers.android.adb_driver import AndroidAdbDriver + + started, released = threading.Event(), threading.Event() + ids = [] + + def execute(phases, request_id): + ids.append(request_id) + started.set() + assert released.wait(5) + return {"success": False, "status": "cancelled", "release_confirmed": True} + + def cancel(request_id): + assert request_id == ids[0] + released.set() + return {"status": "cancelling"} + + client = Mock() + client.perform_gesture.side_effect = execute + client.cancel_gesture.side_effect = cancel + driver = AndroidAdbDriver("test-device", Mock()) + with patch("artemis.clients.accessibility_client.AccessibilityClient", return_value=client): + task = asyncio.create_task(driver.perform_gesture(drag())) + assert await asyncio.to_thread(started.wait, 5) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert released.is_set() and client.perform_gesture.call_count == 1 + + +@pytest.mark.asyncio +async def test_gesture_uses_existing_result_without_mutating_history(): + from copy import deepcopy + from types import SimpleNamespace + from artemis.agents.validator.action_execution import exec_action + + actuator = MockActuator() + result = await actuator.perform_gesture(drag()) + assert result.ok and result.code == ActionCode.OK + assert result.message == "Gesture completed. Observe the screen to verify the intended effect." + assert "release_confirmed" in result.detail + assert "release_confirmed" not in result.message + session = Mock(call=AsyncMock(return_value=result)) + action = {"action": "perform_gesture", "phases": drag()} + original = deepcopy(action) + assert await exec_action(SimpleNamespace(device=None), session, action) == (True, "") + assert action == original + + +@pytest.mark.asyncio +async def test_continuous_gesture_is_not_automatically_retried_after_unknown_outcome(): + from types import SimpleNamespace + from artemis.agents.validator.execution_loop import _process_action + + node = SimpleNamespace(_exec_action=AsyncMock(return_value=(False, "outcome unknown"))) + with ( + patch( + "artemis.agents.validator.execution_loop._run_precondition_gate", + AsyncMock(return_value=(True, None, "")), + ), + patch( + "artemis.agents.validator.execution_loop._capture_live_screenshot", + AsyncMock(return_value=None), + ), + ): + outcome = await _process_action( + node, + Mock(), + Mock(), + {"action": "perform_gesture", "phases": drag()}, + "perform_gesture", + "", + burst=False, + ) + assert not outcome.success + assert node._exec_action.await_count == 1 diff --git a/tests/unit/test_browser_driver.py b/tests/unit/test_browser_driver.py new file mode 100644 index 000000000..097bc729e --- /dev/null +++ b/tests/unit/test_browser_driver.py @@ -0,0 +1,240 @@ +"""Real browser tests against a local fixture; no LLM or external site.""" + +import json +import os +import sys +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from threading import Thread +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest +from pydantic import ValidationError + +from artemis.context import ArtemisContext, DeviceContext, DevicePlatform +from artemis.drivers.browser import BrowserConfig, BrowserDriver +from artemis.drivers.factory import create_driver +from artemis.mcp.actuators.browser import BrowserActuator +from artemis.mcp.action_manifest import validate_actuator +from artemis.mcp.action_executor import McpActionExecutor + + +@pytest.fixture +def website(): + class Handler(BaseHTTPRequestHandler): + def do_GET(self): + self.send_response(200) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.end_headers() + self.wfile.write( + b"""Browser fixture + +

Ready

+ + """ + ) + + def log_message(self, *args): + pass + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = Thread(target=server.serve_forever, daemon=True) + thread.start() + yield f"http://127.0.0.1:{server.server_port}/" + server.shutdown() + server.server_close() + thread.join() + + +def test_browser_options_reject_non_web_and_credentials(): + for url in ["file:///tmp/test", "javascript:alert(1)", "https://user:pass@example.com"]: + with pytest.raises(ValidationError): + BrowserConfig(url=url) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "headless", + [ + True, + pytest.param( + False, + marks=pytest.mark.skipif( + sys.platform == "linux" and not os.getenv("DISPLAY"), + reason="Real headed browser requires a desktop DISPLAY", + ), + ), + ], +) +async def test_browser_real_actions_screenshots_isolation_and_mcp( + website, monkeypatch, tmp_path, headless +): + monkeypatch.setenv( + "ARTEMIS_BROWSER_CONFIG", + json.dumps({"url": website, "width": 1000, "height": 700, "headless": headless}), + ) + ctx = ArtemisContext( + device=DeviceContext( + mobile_platform=DevicePlatform.BROWSER, + device_id="browser-test", + device_width=1000, + device_height=700, + ) + ) + actuator = BrowserActuator(ctx) + ctx.actuator = actuator + validate_actuator(actuator) + assert "run_adb_command" in actuator.unsupported_tools + assert "manage_app" not in actuator.capabilities() + driver = ctx._active_driver + other = BrowserDriver("browser-other", BrowserConfig(url=website, headless=headless)) + executor = McpActionExecutor(ctx, actuator=actuator) + state = SimpleNamespace(indexed_points=[], indexed_elements=[], latest_screenshot=None) + try: + await driver.connect() + driver.context.set_default_timeout(500) + result = await executor.execute( + "browser_action", + {"action": "fill", "by": "label", "name": "Name", "value": "中文用户"}, + "fill", + state, + ) + assert result.status == "success", result.text_summary + assert result.screenshot_bytes.startswith(b"\x89PNG") + result = await executor.execute( + "browser_action", {"action": "click", "by": "role", "name": "Submit"}, "submit", state + ) + assert result.status == "success", result.text_summary + assert result.metadata["normalized_coordinates"] + assert await driver.page.locator("#result").inner_text() == "Welcome 中文用户" + screen = await driver.get_screen_data() + assert screen.platform == "browser" and screen.width == 1000 + assert "Welcome 中文用户" in screen.ui_hierarchy_xml + assert any(e["kind"] == "console" for e in driver.events) + await other.connect() + assert await other.page.evaluate("localStorage.getItem('submitted')") is None + result = await executor.execute( + "browser_action", {"action": "click", "name": "Missing button"}, "missing", state + ) + assert ( + result.status == "error" and result.screenshot_bytes + ) # Failure is never success; keep evidence. + # Pro follows Operator -> Validator rather than the Flash executor. + from artemis.agents.operator.operator import OperatorNode + from artemis.agents.validator.action_execution import exec_action + + operator = object.__new__(OperatorNode) + operator.ctx = ctx + actions, error = operator._translate_and_validate_tool( + {"name": "browser_action", "args": {"action": "click", "name": "Submit"}}, state + ) + assert not error and actions[0]["action"] == "browser_action" + success, detail = await exec_action(ctx, executor._session, actions[0]) + assert success, detail + assert actions[0]["normalized_coordinates"] + frame = await actuator.browser_action("click", name="Frame action", frame="iframe") + assert frame.structuredContent["ok"] + async with driver.context.expect_page(): + await actuator.browser_action("click", name="New tab") + tabs = await actuator.browser_action("tabs") + assert "1:" in tabs.content[0].text + await actuator.browser_action("switch_tab", index=1) + assert driver.page == driver.context.pages[1] + finally: + if executor._session: + await executor._session.aclose() + await driver.disconnect() + await other.disconnect() + assert driver.browser is None + + +@pytest.mark.asyncio +async def test_browser_sdk_bypasses_android(monkeypatch): + from artemis.sdk.agent import Agent + from artemis.sdk.builders import Builders + from third_party.mobile_use.sdk.agent import AgentBase + + monkeypatch.setenv("ARTEMIS_BROWSER_CONFIG", '{"url":"http://localhost/"}') + monkeypatch.setattr(AgentBase, "init", AsyncMock(side_effect=AssertionError("Android init"))) + agent = Agent( + config=Builders.AgentConfig.build(validate_profiles=False), device_serial="browser-test" + ) + assert await agent.init() + assert agent._device_context.mobile_platform == DevicePlatform.BROWSER + await agent._ensure_device_unlocked() + ctx = ArtemisContext(device=agent._device_context) + assert isinstance(create_driver(ctx), BrowserDriver) + await agent.clean() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("headless", [True, False]) +async def test_browser_admission_and_worker_config_skip_mobile_probes(monkeypatch, headless): + from uuid import uuid4 + from apps.admin_console.routers import tasks + from apps.admin_console.schemas.task_schema import RunRequest + from apps.admin_console.services.task_queue_service import TaskQueueService + from artemis.drivers import browser + + monkeypatch.setenv("ARTEMIS_BROWSER_SLOTS", "browser-test") + monkeypatch.setenv("ARTEMIS_BROWSER_HEADED_SLOTS", "" if headless else "browser-test") + monkeypatch.setenv("DISPLAY", ":99") + monkeypatch.setattr(browser, "installed_engines", lambda: ["chromium"]) + monkeypatch.setattr(tasks.session_repo, "get_session_by_id", lambda _: None) + monkeypatch.setattr( + tasks.device_pool, "validate_explicit_serial_async", AsyncMock(return_value=None) + ) + monkeypatch.setattr( + tasks.readiness_engine, + "run_device_submission_probe", + AsyncMock(side_effect=AssertionError("Android probe")), + ) + enqueue = AsyncMock(return_value={"status": "queued"}) + monkeypatch.setattr(tasks.task_queue_service, "enqueue_tasks", enqueue) + request = RunRequest( + goal="Verify page", + session_id=str(uuid4()), + device_platform="browser", + device_serial="browser-test", + browser={"url": "http://localhost/", "headless": headless}, + ) + assert await tasks.run_task(request) == {"status": "queued"} + assert enqueue.call_args.kwargs["browser"]["url"] == "http://localhost/" + item = {"device_serial": "browser-test", "browser": request.browser.model_dump()} + command, env = TaskQueueService._build_worker_invocation( + item, "test", str(uuid4()), "Verify page", "pro", TaskQueueService._task_target(item) + ) + assert json.loads(env["ARTEMIS_BROWSER_CONFIG"])["engine"] == "chromium" + assert json.loads(env["ARTEMIS_BROWSER_CONFIG"])["headless"] is headless + from fastapi import HTTPException + + request.browser.headless = not headless + with pytest.raises(HTTPException, match="mode"): + await tasks.run_task(request) + assert enqueue.await_count == 1 + assert "browser-test" in command + from artemis.runtime.device_pool import DevicePool, DeviceStatus + + pool = DevicePool() + assert ( + pool._pick_device( + [DeviceStatus(serial="browser-test", state="device", product="browser")], None + ) + is None + ) + + +def test_linux_headed_slots_need_display_and_invalid_subset_rejected(monkeypatch): + from artemis.drivers import browser + + monkeypatch.setenv("ARTEMIS_BROWSER_SLOTS", "browser-hl,browser-gui") + monkeypatch.setenv("ARTEMIS_BROWSER_HEADED_SLOTS", "browser-gui") + monkeypatch.setattr(browser.sys, "platform", "linux") + monkeypatch.delenv("DISPLAY", raising=False) + assert browser.slot_available("browser-hl") + assert not browser.slot_available("browser-gui") + monkeypatch.setenv("DISPLAY", ":99") + assert browser.slot_available("browser-gui") + monkeypatch.setenv("ARTEMIS_BROWSER_HEADED_SLOTS", "browser-missing") + with pytest.raises(ValueError, match="Headed slots"): + browser.headed_slots() diff --git a/tests/unit/test_ios_driver.py b/tests/unit/test_ios_driver.py new file mode 100644 index 000000000..19df262f9 --- /dev/null +++ b/tests/unit/test_ios_driver.py @@ -0,0 +1,192 @@ +import base64 +import io +from unittest.mock import AsyncMock + +import pytest +from PIL import Image + +from artemis.context import ArtemisContext, DeviceContext, DevicePlatform +from artemis.drivers.ios import appium_driver + + +@pytest.fixture +def ios(monkeypatch): + monkeypatch.setenv("IOS_UDID", "MOCK-IOS-0001") + output = io.BytesIO() + Image.new("RGB", (780, 1688), "blue").save(output, "PNG") + frame = dict( + png=base64.b64encode(output.getvalue()).decode(), width=780, height=1688, viewport="a" * 24 + ) + calls = [] + + class Client: + def attach(self): + calls.append("attach") + + def screenshot(self): + return frame.copy() + + def source(self): + return '