diff --git a/README.md b/README.md index e3b08e2..5df473c 100644 --- a/README.md +++ b/README.md @@ -176,6 +176,8 @@ python scripts/build_and_test.py --get-warnings xcresult-20251018-143052 python scripts/build_and_test.py --get-log xcresult-20251018-143052 ``` +Add `--run` to build, install and launch in one call (`Launched: com.example.MyApp on iPhone 17 Pro (pid 4410)`). If Xcode's parallel test clones can't boot, `--test` reports `Tests: NOT RUN` instead of a misleading FAIL; `--no-parallel` runs tests on one simulator. + This keeps agent conversations focused — no walls of build output unless you ask for them. ### Simulator Navigation via Accessibility @@ -234,7 +236,7 @@ Every script supports `--help` and `--json`. See **SKILL.md** for the complete r | Script | What it does | Key flags | |--------|-------------|-----------| -| `build_and_test.py` | Build Xcode projects, run tests, parse xcresult bundles | `--project`, `--scheme`, `--test`, `--get-errors`, `--get-warnings` | +| `build_and_test.py` | Build Xcode projects, run tests, parse xcresult bundles | `--project`, `--scheme`, `--test`, `--run`, `--no-parallel`, `--get-errors`, `--get-warnings` | | `log_monitor.py` | Real-time log monitoring with severity filtering | `--app`, `--severity`, `--follow`, `--duration` | #### Device State diff --git a/ios-simulator-skill/.claude-plugin/plugin.json b/ios-simulator-skill/.claude-plugin/plugin.json index 207a3e8..2ce8b73 100644 --- a/ios-simulator-skill/.claude-plugin/plugin.json +++ b/ios-simulator-skill/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "ios-simulator-skill", - "version": "1.7.2", + "version": "1.8.0", "description": "30 scripts for iOS app building, testing, and simulator automation. Semantic UI navigation via the accessibility tree, xcodebuild with progressive error disclosure, accessibility audits, hang detection, and simulator lifecycle management.", "author": { "name": "Conor Luddy" diff --git a/ios-simulator-skill/.codex-plugin/plugin.json b/ios-simulator-skill/.codex-plugin/plugin.json index 1ae5f1b..277ec5a 100644 --- a/ios-simulator-skill/.codex-plugin/plugin.json +++ b/ios-simulator-skill/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "ios-simulator-skill", - "version": "1.7.2", + "version": "1.8.0", "description": "30 scripts for iOS app building, testing, and simulator automation. Semantic UI navigation via the accessibility tree, xcodebuild with progressive error disclosure, accessibility audits, hang detection, and simulator lifecycle management.", "author": { "name": "Conor Luddy", diff --git a/ios-simulator-skill/skills/ios-simulator-skill/SKILL.md b/ios-simulator-skill/skills/ios-simulator-skill/SKILL.md index e0edda5..997c8c6 100644 --- a/ios-simulator-skill/skills/ios-simulator-skill/SKILL.md +++ b/ios-simulator-skill/skills/ios-simulator-skill/SKILL.md @@ -1,6 +1,6 @@ --- name: ios-simulator-skill -version: 1.7.2 +version: 1.8.0 description: Build, test, and drive iOS apps in the Simulator with 30 token-efficient scripts. Use when asked to build or test an Xcode project, launch an app on a simulator, tap/type/swipe through its UI by accessibility label, take screenshots or visual diffs, audit accessibility, read logs or diagnose hangs, or manage simulators (boot, erase, permissions, location, push, appearance). macOS only; needs Xcode, Python 3.12+ and idb. --- @@ -52,7 +52,9 @@ Screenshots cost 1,600–6,300 tokens depending on size. The accessibility tree - Build with live result streaming - Parse errors and warnings from xcresult bundles - Retrieve detailed build logs on demand - - Options: `--project`, `--scheme`, `--clean`, `--test`, `--verbose`, `--json` + - `--run` builds, installs and launches the app in one call: `Launched: on (pid N)` + - Tests that never started (parallel clone failed to boot) report `Tests: NOT RUN`, not FAIL; retry with `--no-parallel` + - Options: `--project`, `--scheme`, `--clean`, `--test`, `--run`, `--no-parallel`, `--verbose`, `--json` 2. **log_monitor.py** - Real-time log monitoring with intelligent filtering - Stream logs or capture by duration diff --git a/ios-simulator-skill/skills/ios-simulator-skill/scripts/build_and_test.py b/ios-simulator-skill/skills/ios-simulator-skill/scripts/build_and_test.py index 2e7e9a3..2c02522 100755 --- a/ios-simulator-skill/skills/ios-simulator-skill/scripts/build_and_test.py +++ b/ios-simulator-skill/skills/ios-simulator-skill/scripts/build_and_test.py @@ -36,15 +36,62 @@ import argparse import sys +import time from pathlib import Path +from app_launcher import AppLauncher + # Import our modular components from common.env_config import env_int +from simctl_boot import SimulatorBooter from xcode import BuildRunner, OutputFormatter, XCResultCache, XCResultParser +from xcode.reporter import is_runner_failure BUILD_LOG_PREVIEW_CHARS = env_int("IOS_SIM_BUILD_LOG_PREVIEW", 4000) BUILD_JSON_CAP = env_int("IOS_SIM_BUILD_JSON_CAP", 50) +LAUNCH_RETRY_DELAY_S = 1.0 + + +def run_built_app(builder: BuildRunner) -> tuple[dict | None, str]: + """Install and launch the app a successful build produced. + + Returns (run info, message): info is None on failure and the message is one line + naming the failed step and what to do next. + """ + built_app = builder.get_built_app() + if not built_app: + return None, f"Run failed: no .app target in scheme {builder.scheme} (is it a framework?)" + app_path, bundle_id = built_app + + udid = builder.get_destination_udid() + if not udid: + return ( + None, + "Run failed: no simulator to run on; pass --simulator '' (see sim_list.py)", + ) + + booted, boot_message = SimulatorBooter(udid).boot(wait_ready=True) + if not booted and "Booted" not in boot_message: + return None, f"Run failed: could not boot {udid}: {boot_message}" + + launcher = AppLauncher(udid) + if not launcher.install(app_path): + return None, f"Run failed: could not install {app_path}; retry or try --clean" + launched, pid = launcher.launch(bundle_id) + if not launched: + # Seen once right after a fresh install; a second attempt succeeded. + time.sleep(LAUNCH_RETRY_DELAY_S) + launched, pid = launcher.launch(bundle_id) + if not launched: + return None, f"Run failed: installed {bundle_id} but launch failed; check log_monitor.py" + + device_name = builder._extract_simulator_name_from_destination( + builder.get_simulator_destination() + ) + pid_text = f"pid {pid}" if pid else "pid unknown" + info = {"bundle_id": bundle_id, "app_path": app_path, "udid": udid, "pid": pid} + return info, f"Launched: {bundle_id} on {device_name} ({pid_text})" def main(): @@ -92,6 +139,14 @@ def main(): build_group.add_argument("--clean", action="store_true", help="Clean before building") build_group.add_argument("--test", action="store_true", help="Run tests") build_group.add_argument("--suite", help="Specific test suite to run") + build_group.add_argument( + "--run", action="store_true", help="After a successful build, install and launch the app" + ) + build_group.add_argument( + "--no-parallel", + action="store_true", + help="Run tests on one simulator (no parallel clones)", + ) # Progressive disclosure arguments disclosure_group = parser.add_argument_group("Progressive Disclosure Options") @@ -117,6 +172,9 @@ def main(): output_group.add_argument("--json", action="store_true", help="Output as JSON") args = parser.parse_args() + if args.run and args.test: + print("Error: --run builds and launches the app; it can't be combined with --test") + return 1 # Initialize cache cache = XCResultCache() @@ -248,7 +306,9 @@ def main(): # Execute build or test if args.test: - success, xcresult_id, stderr = builder.test(test_suite=args.suite) + success, xcresult_id, stderr = builder.test( + test_suite=args.suite, parallel=not args.no_parallel + ) else: success, xcresult_id, stderr = builder.build(clean=args.clean) @@ -297,6 +357,14 @@ def main(): if not success: failed_tests = parser.get_failed_tests() + runner_failed = args.test and not success and is_runner_failure(errors, test_info) + + run_info = None + run_message = None + if args.run and success: + run_info, run_message = run_built_app(builder) + success = run_info is not None + if args.verbose: # Verbose mode with error/warning details verbose_errors = errors if error_count > 0 else None @@ -327,6 +395,12 @@ def main(): data["errors"] = errors[:BUILD_JSON_CAP] if failed_tests: data["failed_tests"] = failed_tests[:BUILD_JSON_CAP] + if runner_failed: + data["status"] = "not_run" + if run_info: + data["run"] = run_info + elif run_message: + data["run_error"] = run_message if hints: data["hints"] = hints import json @@ -343,8 +417,11 @@ def main(): hints=hints, errors=errors, failed_tests=failed_tests, + runner_failed=runner_failed, ) print(output) + if run_message and not args.json: + print(run_message) # Exit with appropriate code return 0 if success else 1 diff --git a/ios-simulator-skill/skills/ios-simulator-skill/scripts/xcode/builder.py b/ios-simulator-skill/skills/ios-simulator-skill/scripts/xcode/builder.py index a8fb3c5..2122c0a 100644 --- a/ios-simulator-skill/skills/ios-simulator-skill/scripts/xcode/builder.py +++ b/ios-simulator-skill/skills/ios-simulator-skill/scripts/xcode/builder.py @@ -167,32 +167,68 @@ def _find_simulator_os(self, name: str, os_version: str | None = None) -> str | With os_version, only that runtime counts. None when no device matches. """ + device = self._find_simulator(name, os_version) + return device[0] if device else None + + def _find_simulator(self, name: str, os_version: str | None = None) -> tuple[str, str] | None: + """Return (iOS version, udid) of the newest available device named exactly `name`.""" + matches = [ + (version, device.get("udid", "")) + for version, device in _available_ios_devices() + if device.get("name") == name and (not os_version or version == os_version) + ] + if not matches: + return None + return max(matches, key=lambda match: _version_key(match[0])) + + def get_destination_udid(self) -> str | None: + """Return the UDID of the simulator the destination names, or None if generic/unknown.""" + destination = self.get_simulator_destination() + name = self._extract_simulator_name_from_destination(destination) + if not name: + return None + os_match = re.search(r"OS=([^,]+)", destination) + device = self._find_simulator(name, os_match.group(1).strip() if os_match else None) + return device[1] if device and device[1] else None + + def get_built_app(self) -> tuple[str, str] | None: + """Return (app path, bundle ID) of the scheme's .app product, or None if there isn't one.""" + cmd = ["xcodebuild", "-showBuildSettings", "-json", *self._project_args()] + cmd.extend( + [ + "-scheme", + self.scheme or "", + "-configuration", + self.configuration, + "-destination", + self.get_simulator_destination(), + ] + ) try: result = subprocess.run( - ["xcrun", "simctl", "list", "devices", "available", "-j"], - capture_output=True, - text=True, - check=True, - timeout=INTROSPECT_TIMEOUT, + cmd, capture_output=True, text=True, check=True, timeout=INTROSPECT_TIMEOUT ) - runtimes = json.loads(result.stdout).get("devices", {}) + targets = json.loads(result.stdout) except (subprocess.SubprocessError, OSError, json.JSONDecodeError): return None - matching_versions = [] - for runtime_id, devices in runtimes.items(): - version_match = re.search(r"SimRuntime\.iOS-([\d-]+)$", runtime_id) - if not version_match: - continue - version = version_match.group(1).replace("-", ".") - if os_version and version != os_version: + for target in targets: + settings = target.get("buildSettings", {}) + if settings.get("WRAPPER_EXTENSION") != "app": continue - if any(device.get("name") == name for device in devices): - matching_versions.append(version) + build_dir = settings.get("TARGET_BUILD_DIR") + product = settings.get("FULL_PRODUCT_NAME") + bundle_id = settings.get("PRODUCT_BUNDLE_IDENTIFIER") + if build_dir and product and bundle_id: + return (str(Path(build_dir) / product), bundle_id) + return None - if not matching_versions: - return None - return max(matching_versions, key=lambda v: tuple(int(part) for part in v.split("."))) + def _project_args(self) -> list[str]: + if self.workspace_path: + return ["-workspace", self.workspace_path] + if self.project_path: + return ["-project", self.project_path] + return [] def _extract_simulator_name_from_destination(self, destination: str) -> str | None: """ @@ -351,12 +387,13 @@ def build(self, clean: bool = False) -> tuple[bool, str, str]: print(f"Error executing build: {e}", file=sys.stderr) return (False, "", str(e)) - def test(self, test_suite: str | None = None) -> tuple[bool, str, str]: + def test(self, test_suite: str | None = None, parallel: bool = True) -> tuple[bool, str, str]: """ Run tests. Args: test_suite: Specific test suite to run + parallel: False runs tests on one simulator (-parallel-testing-enabled NO) Returns: Tuple of (success: bool, xcresult_id: str, stderr: str) @@ -396,6 +433,8 @@ def test(self, test_suite: str | None = None) -> tuple[bool, str, str]: if test_suite: cmd.extend(["-only-testing", test_suite]) + if not parallel: + cmd.extend(["-parallel-testing-enabled", "NO"]) # Execute tests try: @@ -437,3 +476,33 @@ def test(self, test_suite: str | None = None) -> tuple[bool, str, str]: except Exception as e: print(f"Error executing tests: {e}", file=sys.stderr) return (False, "", str(e)) + + +# === HELPERS === + + +def _available_ios_devices() -> list[tuple[str, dict]]: + """Return (iOS version, device) for every available simulator; empty if simctl fails.""" + try: + result = subprocess.run( + ["xcrun", "simctl", "list", "devices", "available", "-j"], + capture_output=True, + text=True, + check=True, + timeout=INTROSPECT_TIMEOUT, + ) + runtimes = json.loads(result.stdout).get("devices", {}) + except (subprocess.SubprocessError, OSError, json.JSONDecodeError): + return [] + + devices = [] + for runtime_id, runtime_devices in runtimes.items(): + version_match = re.search(r"SimRuntime\.iOS-([\d-]+)$", runtime_id) + if version_match: + version = version_match.group(1).replace("-", ".") + devices.extend((version, device) for device in runtime_devices) + return devices + + +def _version_key(version: str) -> tuple[int, ...]: + return tuple(int(part) for part in version.split(".")) diff --git a/ios-simulator-skill/skills/ios-simulator-skill/scripts/xcode/reporter.py b/ios-simulator-skill/skills/ios-simulator-skill/scripts/xcode/reporter.py index 6001a3d..f1d27d5 100644 --- a/ios-simulator-skill/skills/ios-simulator-skill/scripts/xcode/reporter.py +++ b/ios-simulator-skill/skills/ios-simulator-skill/scripts/xcode/reporter.py @@ -12,6 +12,23 @@ BUILD_VERBOSE_CAP = env_int("IOS_SIM_BUILD_VERBOSE_CAP", 100) BUILD_LOG_TAIL = env_int("IOS_SIM_LOG_TAIL", 200) +# Messages xcodebuild emits when the test runner (often a parallel clone) can't start. +RUNNER_FAILURE_PATTERNS = ( + "failed to prepare device", + "timed out trying to boot", + "no matching device", +) + + +def is_runner_failure(errors: list[dict] | None, test_info: dict | None) -> bool: + """True when no test passed and every error says the test runner couldn't start.""" + if not errors or (test_info or {}).get("passed", 0) > 0: + return False + return all( + any(pattern in error.get("message", "").lower() for pattern in RUNNER_FAILURE_PATTERNS) + for error in errors + ) + class OutputFormatter: """ @@ -30,6 +47,7 @@ def format_minimal( hints: list[str] | None = None, errors: list[dict] | None = None, failed_tests: list[dict] | None = None, + runner_failed: bool = False, ) -> str: """ Format ultra-minimal output (5-10 tokens on success, more on failure). @@ -46,13 +64,19 @@ def format_minimal( hints: Optional list of actionable hints errors: Optional error list to surface on failure failed_tests: Optional failed test list to surface on failure + runner_failed: Tests never ran because the runner couldn't start (is_runner_failure) Returns: Minimal formatted string """ lines = [] - if test_info: + if runner_failed: + lines.append( + f"Tests: NOT RUN (test runner couldn't start on the simulator) [{xcresult_id}]" + ) + hints = ["Retry, or run tests on one simulator: --no-parallel"] + elif test_info: # Test mode total = test_info.get("total", 0) passed = test_info.get("passed", 0) @@ -264,7 +288,9 @@ def generate_hints(errors: list[dict]) -> list[str]: hints.append( ' • For simulator builds, use CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO' ) - hints.append(" • Or specify simulator explicitly: --simulator 'iPhone 16 Pro'") + hints.append( + " • Or specify simulator explicitly: --simulator '' (names: python scripts/sim_list.py)" + ) if "signing" in error_types: hints.append("Code signing issue detected:") @@ -277,7 +303,9 @@ def generate_hints(errors: list[dict]) -> list[str]: if any("destination" in error.get("message", "").lower() for error in errors): hints.append("Device selection issue detected:") hints.append(" • List available simulators: xcrun simctl list devices available") - hints.append(" • Specify simulator: --simulator 'iPhone 16 Pro'") + hints.append( + " • Specify simulator: --simulator '' (names: python scripts/sim_list.py)" + ) return hints diff --git a/pyproject.toml b/pyproject.toml index cb82ea2..6832d85 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "ios-simulator-skill" -version = "1.7.2" +version = "1.8.0" description = "Build, test, and automate iOS apps with accessibility-driven navigation" readme = "README.md" requires-python = ">=3.12" diff --git a/tests/test_build_reporter.py b/tests/test_build_reporter.py new file mode 100644 index 0000000..87d2f08 --- /dev/null +++ b/tests/test_build_reporter.py @@ -0,0 +1,57 @@ +"""Unit tests for build/test output: runner failures reported as NOT RUN, and hints.""" + +from xcode.reporter import OutputFormatter, is_runner_failure + +CLONE_TIMEOUT = ( + "Failed to prepare device 'Clone 1 of iPhone 17 Pro' for impending launch. " + "(Underlying Error: Timed out trying to boot simulator after waiting 60.00s.))" +) +CLONE_MISSING = ( + "No matching device (8DDBB245-5BF6-4A64-A2FF-C2E177139A86) in set at " + "/Users/me/Library/Developer/XCTestDevices" +) +NO_TESTS_PASSED = {"total": 2, "passed": 0, "failed": 2, "duration": 61.0} + + +def test_clone_boot_errors_with_nothing_passed_are_a_runner_failure(): + errors = [{"message": CLONE_TIMEOUT}, {"message": CLONE_MISSING}] + assert is_runner_failure(errors, NO_TESTS_PASSED) + + +def test_runner_failure_without_test_results_still_counts(): + assert is_runner_failure([{"message": CLONE_TIMEOUT}], None) + + +def test_a_real_assertion_failure_is_not_a_runner_failure(): + errors = [{"message": CLONE_TIMEOUT}, {"message": "XCTAssertEqual failed: (1) is not (2)"}] + assert not is_runner_failure(errors, NO_TESTS_PASSED) + + +def test_some_tests_passing_is_not_a_runner_failure(): + passed_one = {**NO_TESTS_PASSED, "passed": 1} + assert not is_runner_failure([{"message": CLONE_TIMEOUT}], passed_one) + + +def test_runner_failure_prints_not_run_with_no_parallel_hint(): + output = OutputFormatter.format_minimal( + status="FAILED", + error_count=1, + warning_count=0, + xcresult_id="xcresult-1", + test_info=NO_TESTS_PASSED, + errors=[{"message": CLONE_TIMEOUT}], + runner_failed=True, + ) + assert output.startswith("Tests: NOT RUN (test runner couldn't start on the simulator)") + assert "FAIL (" not in output + assert "--no-parallel" in output + + +def test_hints_name_no_specific_device(): + errors = [ + {"type": "provisioning", "message": "x"}, + {"type": "build", "message": "Unable to find a destination"}, + ] + hints = "\n".join(OutputFormatter.generate_hints(errors)) + assert "--simulator ''" in hints + assert "iPhone" not in hints diff --git a/tests/test_build_run.py b/tests/test_build_run.py new file mode 100644 index 0000000..3b321d7 --- /dev/null +++ b/tests/test_build_run.py @@ -0,0 +1,75 @@ +"""Unit tests for BuildRunner's --run introspection: built app and destination UDID.""" + +import json +import subprocess + +from xcode.builder import BuildRunner + +SIMCTL_DEVICES = { + "devices": { + "com.apple.CoreSimulator.SimRuntime.iOS-26-5": [{"name": "iPhone 17 Pro", "udid": "OLD"}], + "com.apple.CoreSimulator.SimRuntime.iOS-27-0": [{"name": "iPhone 17 Pro", "udid": "NEW"}], + } +} + + +def _settings(extension: str, product: str, bundle_id: str) -> dict: + return { + "target": product, + "buildSettings": { + "WRAPPER_EXTENSION": extension, + "TARGET_BUILD_DIR": "/DerivedData/Build/Products/Debug-iphonesimulator", + "FULL_PRODUCT_NAME": f"{product}.{extension}", + "PRODUCT_BUNDLE_IDENTIFIER": bundle_id, + }, + } + + +def _fake_run(monkeypatch, build_settings: list[dict] | None = None): + def run(cmd, **_kwargs): + payload = build_settings if "-showBuildSettings" in cmd else SIMCTL_DEVICES + return subprocess.CompletedProcess(cmd, 0, stdout=json.dumps(payload), stderr="") + + monkeypatch.setattr(subprocess, "run", run) + + +def _runner(**kwargs) -> BuildRunner: + return BuildRunner(project_path="My.xcodeproj", scheme="MyApp", **kwargs) + + +def test_built_app_reports_app_path_and_bundle_id(monkeypatch): + _fake_run(monkeypatch, [_settings("app", "MyApp", "com.example.MyApp")]) + assert _runner(simulator="iPhone 17 Pro").get_built_app() == ( + "/DerivedData/Build/Products/Debug-iphonesimulator/MyApp.app", + "com.example.MyApp", + ) + + +def test_built_app_picks_the_app_target_among_several(monkeypatch): + _fake_run( + monkeypatch, + [ + _settings("framework", "Core", "com.example.Core"), + _settings("app", "MyApp", "com.example.MyApp"), + _settings("xctest", "MyAppTests", "com.example.MyAppTests"), + ], + ) + assert _runner(simulator="iPhone 17 Pro").get_built_app()[1] == "com.example.MyApp" + + +def test_built_app_is_none_without_an_app_target(monkeypatch): + _fake_run(monkeypatch, [_settings("framework", "Core", "com.example.Core")]) + assert _runner(simulator="iPhone 17 Pro").get_built_app() is None + + +def test_destination_udid_matches_name_and_pinned_os(monkeypatch): + _fake_run(monkeypatch) + assert _runner(simulator="iPhone 17 Pro", os_version="26.5").get_destination_udid() == "OLD" + assert _runner(simulator="iPhone 17 Pro").get_destination_udid() == "NEW" + + +def test_generic_destination_has_no_udid(monkeypatch): + _fake_run(monkeypatch) + runner = _runner() + runner._destination = "generic/platform=iOS Simulator" + assert runner.get_destination_udid() is None