
Ios Simulator Skill
- 49 installs
- 51 repo stars
- Updated November 25, 2025
- ovachiever/droid-tings
Helps with ai & agent building tasks during AI-assisted development.
About
ios-simulator-skill is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted coding.
- ios-simulator-skill
- AI & Agent Building
- AI-coding skill
Ios Simulator Skill by the numbers
- 49 all-time installs (skills.sh)
- Ranked #7,280 of 16,556 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Jul 27, 2026 (Skillselion catalog sync)
npx skills add https://github.com/ovachiever/droid-tings --skill ios-simulator-skillAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 49 |
|---|---|
| repo stars | ★ 51 |
| Last updated | November 25, 2025 |
| Repository | ovachiever/droid-tings ↗ |
What it does
Helps with ai & agent building tasks during AI-assisted development.
Files
iOS Simulator Skill
Build, test, and automate iOS applications using accessibility-driven navigation and structured data instead of pixel coordinates.
Quick Start
# 1. Check environment
bash scripts/sim_health_check.sh
# 2. Launch app
python scripts/app_launcher.py --launch com.example.app
# 3. Map screen to see elements
python scripts/screen_mapper.py
# 4. Tap button
python scripts/navigator.py --find-text "Login" --tap
# 5. Enter text
python scripts/navigator.py --find-type TextField --enter-text "user@example.com"All scripts support --help for detailed options and --json for machine-readable output.
21 Production Scripts
Build & Development (2 scripts)
1. build_and_test.py - Build Xcode projects, run tests, parse results with progressive disclosure
- 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
2. log_monitor.py - Real-time log monitoring with intelligent filtering
- Stream logs or capture by duration
- Filter by severity (error/warning/info/debug)
- Deduplicate repeated messages
- Options:
--app,--severity,--follow,--duration,--output,--json
Navigation & Interaction (5 scripts)
3. screen_mapper.py - Analyze current screen and list interactive elements
- Element type breakdown
- Interactive button list
- Text field status
- Options:
--verbose,--hints,--json
4. navigator.py - Find and interact with elements semantically
- Find by text (fuzzy matching)
- Find by element type
- Find by accessibility ID
- Enter text or tap elements
- Options:
--find-text,--find-type,--find-id,--tap,--enter-text,--json
5. gesture.py - Perform swipes, scrolls, pinches, and complex gestures
- Directional swipes (up/down/left/right)
- Multi-swipe scrolling
- Pinch zoom
- Long press
- Pull to refresh
- Options:
--swipe,--scroll,--pinch,--long-press,--refresh,--json
6. keyboard.py - Text input and hardware button control
- Type text (fast or slow)
- Special keys (return, delete, tab, space, arrows)
- Hardware buttons (home, lock, volume, screenshot)
- Key combinations
- Options:
--type,--key,--button,--slow,--clear,--dismiss,--json
7. app_launcher.py - App lifecycle management
- Launch apps by bundle ID
- Terminate apps
- Install/uninstall from .app bundles
- Deep link navigation
- List installed apps
- Check app state
- Options:
--launch,--terminate,--install,--uninstall,--open-url,--list,--state,--json
Testing & Analysis (5 scripts)
8. accessibility_audit.py - Check WCAG compliance on current screen
- Critical issues (missing labels, empty buttons, no alt text)
- Warnings (missing hints, small touch targets)
- Info (missing IDs, deep nesting)
- Options:
--verbose,--output,--json
9. visual_diff.py - Compare two screenshots for visual changes
- Pixel-by-pixel comparison
- Threshold-based pass/fail
- Generate diff images
- Options:
--threshold,--output,--details,--json
10. test_recorder.py - Automatically document test execution
- Capture screenshots and accessibility trees per step
- Generate markdown reports with timing data
- Options:
--test-name,--output,--verbose,--json
11. app_state_capture.py - Create comprehensive debugging snapshots
- Screenshot, UI hierarchy, app logs, device info
- Markdown summary for bug reports
- Options:
--app-bundle-id,--output,--log-lines,--json
12. sim_health_check.sh - Verify environment is properly configured
- Check macOS, Xcode, simctl, IDB, Python
- List available and booted simulators
- Verify Python packages (Pillow)
Advanced Testing & Permissions (4 scripts)
13. clipboard.py - Manage simulator clipboard for paste testing
- Copy text to clipboard
- Test paste flows without manual entry
- Options:
--copy,--test-name,--expected,--json
14. status_bar.py - Override simulator status bar appearance
- Presets: clean (9:41, 100% battery), testing (11:11, 50%), low-battery (20%), airplane (offline)
- Custom time, network, battery, WiFi settings
- Options:
--preset,--time,--data-network,--battery-level,--clear,--json
15. push_notification.py - Send simulated push notifications
- Simple mode (title + body + badge)
- Custom JSON payloads
- Test notification handling and deep links
- Options:
--bundle-id,--title,--body,--badge,--payload,--json
16. privacy_manager.py - Grant, revoke, and reset app permissions
- 13 supported services (camera, microphone, location, contacts, photos, calendar, health, etc.)
- Batch operations (comma-separated services)
- Audit trail with test scenario tracking
- Options:
--bundle-id,--grant,--revoke,--reset,--list,--json
Device Lifecycle Management (5 scripts)
17. simctl_boot.py - Boot simulators with optional readiness verification
- Boot by UDID or device name
- Wait for device ready with timeout
- Batch boot operations (--all, --type)
- Performance timing
- Options:
--udid,--name,--wait-ready,--timeout,--all,--type,--json
18. simctl_shutdown.py - Gracefully shutdown simulators
- Shutdown by UDID or device name
- Optional verification of shutdown completion
- Batch shutdown operations
- Options:
--udid,--name,--verify,--timeout,--all,--type,--json
19. simctl_create.py - Create simulators dynamically
- Create by device type and iOS version
- List available device types and runtimes
- Custom device naming
- Returns UDID for CI/CD integration
- Options:
--device,--runtime,--name,--list-devices,--list-runtimes,--json
20. simctl_delete.py - Permanently delete simulators
- Delete by UDID or device name
- Safety confirmation by default (skip with --yes)
- Batch delete operations
- Smart deletion (--old N to keep N per device type)
- Options:
--udid,--name,--yes,--all,--type,--old,--json
21. simctl_erase.py - Factory reset simulators without deletion
- Preserve device UUID (faster than delete+create)
- Erase all, by type, or booted simulators
- Optional verification
- Options:
--udid,--name,--verify,--timeout,--all,--type,--booted,--json
Common Patterns
Auto-UDID Detection: Most scripts auto-detect the booted simulator if --udid is not provided.
Device Name Resolution: Use device names (e.g., "iPhone 16 Pro") instead of UDIDs - scripts resolve automatically.
Batch Operations: Many scripts support --all for all simulators or --type iPhone for device type filtering.
Output Formats: Default is concise human-readable output. Use --json for machine-readable output in CI/CD.
Help: All scripts support --help for detailed options and examples.
Typical Workflow
1. Verify environment: bash scripts/sim_health_check.sh 2. Launch app: python scripts/app_launcher.py --launch com.example.app 3. Analyze screen: python scripts/screen_mapper.py 4. Interact: python scripts/navigator.py --find-text "Button" --tap 5. Verify: python scripts/accessibility_audit.py 6. Debug if needed: python scripts/app_state_capture.py --app-bundle-id com.example.app
Requirements
- macOS 12+
- Xcode Command Line Tools
- Python 3
- IDB (optional, for interactive features)
Documentation
- SKILL.md (this file) - Script reference and quick start
- README.md - Installation and examples
- CLAUDE.md - Architecture and implementation details
- references/ - Deep documentation on specific topics
- examples/ - Complete automation workflows
Key Design Principles
Semantic Navigation: Find elements by meaning (text, type, ID) not pixel coordinates. Survives UI changes.
Token Efficiency: Concise default output (3-5 lines) with optional verbose and JSON modes for detailed results.
Accessibility-First: Built on standard accessibility APIs for reliability and compatibility.
Zero Configuration: Works immediately on any macOS with Xcode. No setup required.
Structured Data: Scripts output JSON or formatted text, not raw logs. Easy to parse and integrate.
Auto-Learning: Build system remembers your device preference. Configuration stored per-project.
---
Use these scripts directly or let Claude Code invoke them automatically when your request matches the skill description.
#!/usr/bin/env python3
"""
iOS Simulator Accessibility Audit
Scans the current simulator screen for accessibility compliance issues.
Optimized for minimal token output while maintaining functionality.
Usage: python scripts/accessibility_audit.py [options]
"""
import argparse
import json
import subprocess
import sys
from dataclasses import asdict, dataclass
from typing import Any
from common import flatten_tree, get_accessibility_tree, resolve_udid
@dataclass
class Issue:
"""Represents an accessibility issue."""
severity: str # critical, warning, info
rule: str
element_type: str
issue: str
fix: str
def to_dict(self) -> dict:
"""Convert to dictionary for JSON serialization."""
return asdict(self)
class AccessibilityAuditor:
"""Performs accessibility audits on iOS simulator screens."""
# Critical rules that block users
CRITICAL_RULES = {
"missing_label": lambda e: e.get("type") in ["Button", "Link"] and not e.get("AXLabel"),
"empty_button": lambda e: e.get("type") == "Button"
and not (e.get("AXLabel") or e.get("AXValue")),
"image_no_alt": lambda e: e.get("type") == "Image" and not e.get("AXLabel"),
}
# Warnings that degrade UX
WARNING_RULES = {
"missing_hint": lambda e: e.get("type") in ["Slider", "TextField"] and not e.get("help"),
"missing_traits": lambda e: e.get("type") and not e.get("traits"),
}
# Info level suggestions
INFO_RULES = {
"no_identifier": lambda e: not e.get("AXUniqueId"),
"deep_nesting": lambda e: e.get("depth", 0) > 5,
}
def __init__(self, udid: str | None = None):
"""Initialize auditor with optional device UDID."""
self.udid = udid
def get_accessibility_tree(self) -> dict:
"""Fetch accessibility tree from simulator using shared utility."""
return get_accessibility_tree(self.udid, nested=True)
@staticmethod
def _is_small_target(element: dict) -> bool:
"""Check if touch target is too small (< 44x44 points)."""
frame = element.get("frame", {})
width = frame.get("width", 0)
height = frame.get("height", 0)
return width < 44 or height < 44
def _flatten_tree(self, node: dict, depth: int = 0) -> list[dict]:
"""Flatten nested accessibility tree for easier processing using shared utility."""
return flatten_tree(node, depth)
def audit_element(self, element: dict) -> list[Issue]:
"""Audit a single element for accessibility issues."""
issues = []
# Check critical rules
for rule_name, rule_func in self.CRITICAL_RULES.items():
if rule_func(element):
issues.append(
Issue(
severity="critical",
rule=rule_name,
element_type=element.get("type", "Unknown"),
issue=self._get_issue_description(rule_name),
fix=self._get_fix_suggestion(rule_name),
)
)
# Check warnings (skip if critical issues found)
if not issues:
for rule_name, rule_func in self.WARNING_RULES.items():
if rule_func(element):
issues.append(
Issue(
severity="warning",
rule=rule_name,
element_type=element.get("type", "Unknown"),
issue=self._get_issue_description(rule_name),
fix=self._get_fix_suggestion(rule_name),
)
)
# Check info level (only if verbose or no other issues)
if not issues:
for rule_name, rule_func in self.INFO_RULES.items():
if rule_func(element):
issues.append(
Issue(
severity="info",
rule=rule_name,
element_type=element.get("type", "Unknown"),
issue=self._get_issue_description(rule_name),
fix=self._get_fix_suggestion(rule_name),
)
)
return issues
def _get_issue_description(self, rule: str) -> str:
"""Get human-readable issue description."""
descriptions = {
"missing_label": "Interactive element missing accessibility label",
"empty_button": "Button has no text or label",
"image_no_alt": "Image missing alternative text",
"missing_hint": "Complex control missing hint",
"small_touch_target": "Touch target smaller than 44x44pt",
"missing_traits": "Element missing accessibility traits",
"no_identifier": "Missing accessibility identifier",
"deep_nesting": "Deeply nested (>5 levels)",
}
return descriptions.get(rule, "Accessibility issue")
def _get_fix_suggestion(self, rule: str) -> str:
"""Get fix suggestion for issue."""
fixes = {
"missing_label": "Add accessibilityLabel",
"empty_button": "Set button title or accessibilityLabel",
"image_no_alt": "Add accessibilityLabel with description",
"missing_hint": "Add accessibilityHint",
"small_touch_target": "Increase to minimum 44x44pt",
"missing_traits": "Set appropriate accessibilityTraits",
"no_identifier": "Add accessibilityIdentifier for testing",
"deep_nesting": "Simplify view hierarchy",
}
return fixes.get(rule, "Review accessibility")
def audit(self, verbose: bool = False) -> dict[str, Any]:
"""Perform full accessibility audit."""
# Get accessibility tree
tree = self.get_accessibility_tree()
# Flatten for processing
elements = self._flatten_tree(tree)
# Audit each element
all_issues = []
for element in elements:
issues = self.audit_element(element)
for issue in issues:
issue_dict = issue.to_dict()
# Add minimal element info for context
issue_dict["element"] = {
"type": element.get("type", "Unknown"),
"label": element.get("AXLabel", "")[:30] if element.get("AXLabel") else None,
}
all_issues.append(issue_dict)
# Count by severity
critical = len([i for i in all_issues if i["severity"] == "critical"])
warning = len([i for i in all_issues if i["severity"] == "warning"])
info = len([i for i in all_issues if i["severity"] == "info"])
# Build result (token-optimized)
result = {
"summary": {
"total": len(elements),
"issues": len(all_issues),
"critical": critical,
"warning": warning,
"info": info,
}
}
if verbose:
# Full details only if requested
result["issues"] = all_issues
else:
# Default: top issues only (token-efficient)
result["top_issues"] = self._get_top_issues(all_issues)
return result
def _get_top_issues(self, issues: list[dict]) -> list[dict]:
"""Get top 3 issues grouped by type (token-efficient)."""
if not issues:
return []
# Group by rule
grouped = {}
for issue in issues:
rule = issue["rule"]
if rule not in grouped:
grouped[rule] = {
"severity": issue["severity"],
"rule": rule,
"count": 0,
"fix": issue["fix"],
}
grouped[rule]["count"] += 1
# Sort by severity and count
severity_order = {"critical": 0, "warning": 1, "info": 2}
sorted_issues = sorted(
grouped.values(), key=lambda x: (severity_order[x["severity"]], -x["count"])
)
return sorted_issues[:3]
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(
description="Audit iOS simulator screen for accessibility issues"
)
parser.add_argument(
"--udid",
help="Device UDID (auto-detects booted simulator if not provided)",
)
parser.add_argument("--output", help="Save JSON report to file")
parser.add_argument(
"--verbose", action="store_true", help="Include all issue details (increases output)"
)
args = parser.parse_args()
# Resolve UDID with auto-detection
try:
udid = resolve_udid(args.udid)
except RuntimeError as e:
print(f"Error: {e}")
sys.exit(1)
# Perform audit
auditor = AccessibilityAuditor(udid=udid)
try:
result = auditor.audit(verbose=args.verbose)
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
# Output results
if args.output:
# Save to file
with open(args.output, "w") as f:
json.dump(result, f, indent=2)
# Print minimal summary
summary = result["summary"]
print(f"Audit complete: {summary['issues']} issues ({summary['critical']} critical)")
print(f"Report saved to: {args.output}")
# Print to stdout (token-optimized by default)
elif args.verbose:
print(json.dumps(result, indent=2))
else:
# Ultra-compact output
summary = result["summary"]
print(f"Elements: {summary['total']}, Issues: {summary['issues']}")
print(
f"Critical: {summary['critical']}, Warning: {summary['warning']}, Info: {summary['info']}"
)
if result.get("top_issues"):
print("\nTop issues:")
for issue in result["top_issues"]:
print(
f" [{issue['severity']}] {issue['rule']} ({issue['count']}x) - {issue['fix']}"
)
# Exit with error if critical issues found
if result["summary"]["critical"] > 0:
sys.exit(1)
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""
iOS App Launcher - App Lifecycle Control
Launches, terminates, and manages iOS apps in the simulator.
Handles deep links and app switching.
Usage: python scripts/app_launcher.py --launch com.example.app
"""
import argparse
import contextlib
import subprocess
import sys
import time
from common import build_simctl_command, resolve_udid
class AppLauncher:
"""Controls app lifecycle on iOS simulator."""
def __init__(self, udid: str | None = None):
"""Initialize app launcher."""
self.udid = udid
def launch(self, bundle_id: str, wait_for_debugger: bool = False) -> tuple[bool, int | None]:
"""
Launch an app.
Args:
bundle_id: App bundle identifier
wait_for_debugger: Wait for debugger attachment
Returns:
(success, pid) tuple
"""
cmd = build_simctl_command("launch", self.udid, bundle_id)
if wait_for_debugger:
cmd.insert(3, "--wait-for-debugger") # Insert after "launch" operation
try:
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
# Parse PID from output if available
pid = None
if result.stdout:
# Output format: "com.example.app: <PID>"
parts = result.stdout.strip().split(":")
if len(parts) > 1:
with contextlib.suppress(ValueError):
pid = int(parts[1].strip())
return (True, pid)
except subprocess.CalledProcessError:
return (False, None)
def terminate(self, bundle_id: str) -> bool:
"""
Terminate an app.
Args:
bundle_id: App bundle identifier
Returns:
Success status
"""
cmd = build_simctl_command("terminate", self.udid, bundle_id)
try:
subprocess.run(cmd, capture_output=True, check=True)
return True
except subprocess.CalledProcessError:
return False
def install(self, app_path: str) -> bool:
"""
Install an app.
Args:
app_path: Path to .app bundle
Returns:
Success status
"""
cmd = build_simctl_command("install", self.udid, app_path)
try:
subprocess.run(cmd, capture_output=True, check=True)
return True
except subprocess.CalledProcessError:
return False
def uninstall(self, bundle_id: str) -> bool:
"""
Uninstall an app.
Args:
bundle_id: App bundle identifier
Returns:
Success status
"""
cmd = build_simctl_command("uninstall", self.udid, bundle_id)
try:
subprocess.run(cmd, capture_output=True, check=True)
return True
except subprocess.CalledProcessError:
return False
def open_url(self, url: str) -> bool:
"""
Open URL (for deep linking).
Args:
url: URL to open (http://, myapp://, etc.)
Returns:
Success status
"""
cmd = build_simctl_command("openurl", self.udid, url)
try:
subprocess.run(cmd, capture_output=True, check=True)
return True
except subprocess.CalledProcessError:
return False
def list_apps(self) -> list[dict[str, str]]:
"""
List installed apps.
Returns:
List of app info dictionaries
"""
cmd = build_simctl_command("listapps", self.udid)
try:
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
# Parse plist output using plutil to convert to JSON
plist_data = result.stdout
# Use plutil to convert plist to JSON
convert_cmd = ["plutil", "-convert", "json", "-o", "-", "-"]
convert_result = subprocess.run(
convert_cmd, check=False, input=plist_data, capture_output=True, text=True
)
apps = []
if convert_result.returncode == 0:
import json
try:
data = json.loads(convert_result.stdout)
for bundle_id, app_info in data.items():
# Skip system internal apps that are hidden
if app_info.get("ApplicationType") == "Hidden":
continue
apps.append(
{
"bundle_id": bundle_id,
"name": app_info.get(
"CFBundleDisplayName", app_info.get("CFBundleName", bundle_id)
),
"path": app_info.get("Path", ""),
"version": app_info.get("CFBundleVersion", "Unknown"),
"type": app_info.get("ApplicationType", "User"),
}
)
except json.JSONDecodeError:
pass
return apps
except subprocess.CalledProcessError:
return []
def get_app_state(self, bundle_id: str) -> str:
"""
Get app state (running, suspended, etc.).
Args:
bundle_id: App bundle identifier
Returns:
State string or 'unknown'
"""
# Check if app is running by trying to get its PID
cmd = build_simctl_command("spawn", self.udid, "launchctl", "list")
try:
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
if bundle_id in result.stdout:
return "running"
return "not running"
except subprocess.CalledProcessError:
return "unknown"
def restart_app(self, bundle_id: str, delay: float = 1.0) -> bool:
"""
Restart an app (terminate then launch).
Args:
bundle_id: App bundle identifier
delay: Delay between terminate and launch
Returns:
Success status
"""
# Terminate
self.terminate(bundle_id)
time.sleep(delay)
# Launch
success, _ = self.launch(bundle_id)
return success
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(description="Control iOS app lifecycle")
# Actions
parser.add_argument("--launch", help="Launch app by bundle ID")
parser.add_argument("--terminate", help="Terminate app by bundle ID")
parser.add_argument("--restart", help="Restart app by bundle ID")
parser.add_argument("--install", help="Install app from .app path")
parser.add_argument("--uninstall", help="Uninstall app by bundle ID")
parser.add_argument("--open-url", help="Open URL (deep link)")
parser.add_argument("--list", action="store_true", help="List installed apps")
parser.add_argument("--state", help="Get app state by bundle ID")
# Options
parser.add_argument(
"--wait-for-debugger", action="store_true", help="Wait for debugger when launching"
)
parser.add_argument(
"--udid",
help="Device UDID (auto-detects booted simulator if not provided)",
)
args = parser.parse_args()
# Resolve UDID with auto-detection
try:
udid = resolve_udid(args.udid)
except RuntimeError as e:
print(f"Error: {e}")
sys.exit(1)
launcher = AppLauncher(udid=udid)
# Execute requested action
if args.launch:
success, pid = launcher.launch(args.launch, args.wait_for_debugger)
if success:
if pid:
print(f"Launched {args.launch} (PID: {pid})")
else:
print(f"Launched {args.launch}")
else:
print(f"Failed to launch {args.launch}")
sys.exit(1)
elif args.terminate:
if launcher.terminate(args.terminate):
print(f"Terminated {args.terminate}")
else:
print(f"Failed to terminate {args.terminate}")
sys.exit(1)
elif args.restart:
if launcher.restart_app(args.restart):
print(f"Restarted {args.restart}")
else:
print(f"Failed to restart {args.restart}")
sys.exit(1)
elif args.install:
if launcher.install(args.install):
print(f"Installed {args.install}")
else:
print(f"Failed to install {args.install}")
sys.exit(1)
elif args.uninstall:
if launcher.uninstall(args.uninstall):
print(f"Uninstalled {args.uninstall}")
else:
print(f"Failed to uninstall {args.uninstall}")
sys.exit(1)
elif args.open_url:
if launcher.open_url(args.open_url):
print(f"Opened URL: {args.open_url}")
else:
print(f"Failed to open URL: {args.open_url}")
sys.exit(1)
elif args.list:
apps = launcher.list_apps()
if apps:
print(f"Installed apps ({len(apps)}):")
for app in apps[:10]: # Limit for token efficiency
print(f" {app['bundle_id']}: {app['name']} (v{app['version']})")
if len(apps) > 10:
print(f" ... and {len(apps) - 10} more")
else:
print("No apps found or failed to list")
elif args.state:
state = launcher.get_app_state(args.state)
print(f"{args.state}: {state}")
else:
parser.print_help()
sys.exit(1)
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""
App State Capture for iOS Simulator
Captures complete app state including screenshot, accessibility tree, and logs.
Optimized for minimal token output.
Usage: python scripts/app_state_capture.py [options]
"""
import argparse
import json
import subprocess
import sys
from datetime import datetime
from pathlib import Path
from common import (
capture_screenshot,
count_elements,
get_accessibility_tree,
resolve_udid,
)
class AppStateCapture:
"""Captures comprehensive app state for debugging."""
def __init__(
self,
app_bundle_id: str | None = None,
udid: str | None = None,
inline: bool = False,
screenshot_size: str = "half",
):
"""
Initialize state capture.
Args:
app_bundle_id: Optional app bundle ID for log filtering
udid: Optional device UDID (uses booted if not specified)
inline: If True, return screenshots as base64 (for vision-based automation)
screenshot_size: 'full', 'half', 'quarter', 'thumb' (default: 'half')
"""
self.app_bundle_id = app_bundle_id
self.udid = udid
self.inline = inline
self.screenshot_size = screenshot_size
def capture_screenshot(self, output_path: Path) -> bool:
"""Capture screenshot of current screen."""
cmd = ["xcrun", "simctl", "io"]
if self.udid:
cmd.append(self.udid)
else:
cmd.append("booted")
cmd.extend(["screenshot", str(output_path)])
try:
subprocess.run(cmd, capture_output=True, check=True)
return True
except subprocess.CalledProcessError:
return False
def capture_accessibility_tree(self, output_path: Path) -> dict:
"""Capture accessibility tree using shared utility."""
try:
# Use shared utility to fetch tree
tree = get_accessibility_tree(self.udid, nested=True)
# Save tree
with open(output_path, "w") as f:
json.dump(tree, f, indent=2)
# Return summary using shared utility
return {"captured": True, "element_count": count_elements(tree)}
except Exception as e:
return {"captured": False, "error": str(e)}
def capture_logs(self, output_path: Path, line_limit: int = 100) -> dict:
"""Capture recent app logs."""
if not self.app_bundle_id:
# Can't capture logs without app ID
return {"captured": False, "reason": "No app bundle ID specified"}
# Get app name from bundle ID (simplified)
app_name = self.app_bundle_id.split(".")[-1]
cmd = ["xcrun", "simctl", "spawn"]
if self.udid:
cmd.append(self.udid)
else:
cmd.append("booted")
cmd.extend(
[
"log",
"show",
"--predicate",
f'process == "{app_name}"',
"--last",
"1m", # Last 1 minute
"--style",
"compact",
]
)
try:
result = subprocess.run(cmd, check=False, capture_output=True, text=True, timeout=5)
logs = result.stdout
# Limit lines for token efficiency
lines = logs.split("\n")
if len(lines) > line_limit:
lines = lines[-line_limit:]
# Save logs
with open(output_path, "w") as f:
f.write("\n".join(lines))
# Analyze for issues
warning_count = sum(1 for line in lines if "warning" in line.lower())
error_count = sum(1 for line in lines if "error" in line.lower())
return {
"captured": True,
"lines": len(lines),
"warnings": warning_count,
"errors": error_count,
}
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
return {"captured": False, "error": str(e)}
def capture_device_info(self) -> dict:
"""Get device information."""
cmd = ["xcrun", "simctl", "list", "devices", "booted"]
if self.udid:
# Specific device info
cmd = ["xcrun", "simctl", "list", "devices"]
try:
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
# Parse output for device info (simplified)
lines = result.stdout.split("\n")
device_info = {}
for line in lines:
if "iPhone" in line or "iPad" in line:
# Extract device name and state
parts = line.strip().split("(")
if parts:
device_info["name"] = parts[0].strip()
if len(parts) > 2:
device_info["udid"] = parts[1].replace(")", "").strip()
device_info["state"] = parts[2].replace(")", "").strip()
break
return device_info
except subprocess.CalledProcessError:
return {}
def capture_all(
self, output_dir: str, log_lines: int = 100, app_name: str | None = None
) -> dict:
"""
Capture complete app state.
Args:
output_dir: Directory to save artifacts
log_lines: Number of log lines to capture
app_name: App name for semantic naming (for inline mode)
Returns:
Summary of captured state
"""
# Create output directory (only if not in inline mode)
output_path = Path(output_dir)
timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
if not self.inline:
capture_dir = output_path / f"app-state-{timestamp}"
capture_dir.mkdir(parents=True, exist_ok=True)
else:
capture_dir = None
summary = {
"timestamp": datetime.now().isoformat(),
"screenshot_mode": "inline" if self.inline else "file",
}
if capture_dir:
summary["output_dir"] = str(capture_dir)
# Capture screenshot using new unified utility
screenshot_result = capture_screenshot(
self.udid,
size=self.screenshot_size,
inline=self.inline,
app_name=app_name,
)
if self.inline:
# Inline mode: store base64
summary["screenshot"] = {
"mode": "inline",
"base64": screenshot_result["base64_data"],
"width": screenshot_result["width"],
"height": screenshot_result["height"],
"size_preset": self.screenshot_size,
}
else:
# File mode: save to disk
screenshot_path = capture_dir / "screenshot.png"
# Move temp file to target location
import shutil
shutil.move(screenshot_result["file_path"], screenshot_path)
summary["screenshot"] = {
"mode": "file",
"file": "screenshot.png",
"size_bytes": screenshot_result["size_bytes"],
}
# Capture accessibility tree
if not self.inline or capture_dir:
accessibility_path = (capture_dir or output_path) / "accessibility-tree.json"
else:
accessibility_path = None
if accessibility_path:
tree_info = self.capture_accessibility_tree(accessibility_path)
summary["accessibility"] = tree_info
# Capture logs (if app ID provided)
if self.app_bundle_id:
if not self.inline or capture_dir:
logs_path = (capture_dir or output_path) / "app-logs.txt"
else:
logs_path = None
if logs_path:
log_info = self.capture_logs(logs_path, log_lines)
summary["logs"] = log_info
# Get device info
device_info = self.capture_device_info()
if device_info:
summary["device"] = device_info
# Save device info (file mode only)
if capture_dir:
with open(capture_dir / "device-info.json", "w") as f:
json.dump(device_info, f, indent=2)
# Save summary (file mode only)
if capture_dir:
with open(capture_dir / "summary.json", "w") as f:
json.dump(summary, f, indent=2)
# Create markdown summary
self._create_summary_md(capture_dir, summary)
return summary
def _create_summary_md(self, capture_dir: Path, summary: dict) -> None:
"""Create markdown summary file."""
md_path = capture_dir / "summary.md"
with open(md_path, "w") as f:
f.write("# App State Capture\n\n")
f.write(f"**Timestamp:** {summary['timestamp']}\n\n")
if "device" in summary:
f.write("## Device\n")
device = summary["device"]
f.write(f"- Name: {device.get('name', 'Unknown')}\n")
f.write(f"- UDID: {device.get('udid', 'N/A')}\n")
f.write(f"- State: {device.get('state', 'Unknown')}\n\n")
f.write("## Screenshot\n")
f.write("\n\n")
if "accessibility" in summary:
acc = summary["accessibility"]
f.write("## Accessibility\n")
if acc.get("captured"):
f.write(f"- Elements: {acc.get('element_count', 0)}\n")
else:
f.write(f"- Error: {acc.get('error', 'Unknown')}\n")
f.write("\n")
if "logs" in summary:
logs = summary["logs"]
f.write("## Logs\n")
if logs.get("captured"):
f.write(f"- Lines: {logs.get('lines', 0)}\n")
f.write(f"- Warnings: {logs.get('warnings', 0)}\n")
f.write(f"- Errors: {logs.get('errors', 0)}\n")
else:
f.write(f"- {logs.get('reason', logs.get('error', 'Not captured'))}\n")
f.write("\n")
f.write("## Files\n")
f.write("- `screenshot.png` - Current screen\n")
f.write("- `accessibility-tree.json` - Full UI hierarchy\n")
if self.app_bundle_id:
f.write("- `app-logs.txt` - Recent app logs\n")
f.write("- `device-info.json` - Device details\n")
f.write("- `summary.json` - Complete capture metadata\n")
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(description="Capture complete app state for debugging")
parser.add_argument(
"--app-bundle-id", help="App bundle ID for log filtering (e.g., com.example.app)"
)
parser.add_argument(
"--output", default=".", help="Output directory (default: current directory)"
)
parser.add_argument(
"--log-lines", type=int, default=100, help="Number of log lines to capture (default: 100)"
)
parser.add_argument(
"--udid",
help="Device UDID (auto-detects booted simulator if not provided)",
)
parser.add_argument(
"--inline",
action="store_true",
help="Return screenshots as base64 (inline mode for vision-based automation)",
)
parser.add_argument(
"--size",
choices=["full", "half", "quarter", "thumb"],
default="half",
help="Screenshot size for token optimization (default: half)",
)
parser.add_argument("--app-name", help="App name for semantic screenshot naming")
args = parser.parse_args()
# Resolve UDID with auto-detection
try:
udid = resolve_udid(args.udid)
except RuntimeError as e:
print(f"Error: {e}")
sys.exit(1)
# Create capturer
capturer = AppStateCapture(
app_bundle_id=args.app_bundle_id,
udid=udid,
inline=args.inline,
screenshot_size=args.size,
)
# Capture state
try:
summary = capturer.capture_all(
output_dir=args.output, log_lines=args.log_lines, app_name=args.app_name
)
# Token-efficient output
if "output_dir" in summary:
print(f"State captured: {summary['output_dir']}/")
else:
# Inline mode
print(
f"State captured (inline mode): {summary['screenshot']['width']}x{summary['screenshot']['height']}"
)
# Report any issues found
if "logs" in summary and summary["logs"].get("captured"):
logs = summary["logs"]
if logs["errors"] > 0 or logs["warnings"] > 0:
print(f"Issues found: {logs['errors']} errors, {logs['warnings']} warnings")
if "accessibility" in summary and summary["accessibility"].get("captured"):
print(f"Elements: {summary['accessibility']['element_count']}")
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""
Build and Test Automation for Xcode Projects
Ultra token-efficient build automation with progressive disclosure via xcresult bundles.
Features:
- Minimal default output (5-10 tokens)
- Progressive disclosure for error/warning/log details
- Native xcresult bundle support
- Clean modular architecture
Usage Examples:
# Build (minimal output)
python scripts/build_and_test.py --project MyApp.xcodeproj
# Output: Build: SUCCESS (0 errors, 3 warnings) [xcresult-20251018-143052]
# Get error details
python scripts/build_and_test.py --get-errors xcresult-20251018-143052
# Get warnings
python scripts/build_and_test.py --get-warnings xcresult-20251018-143052
# Get build log
python scripts/build_and_test.py --get-log xcresult-20251018-143052
# Get everything as JSON
python scripts/build_and_test.py --get-all xcresult-20251018-143052 --json
# List recent builds
python scripts/build_and_test.py --list-xcresults
# Verbose mode (for debugging)
python scripts/build_and_test.py --project MyApp.xcodeproj --verbose
"""
import argparse
import sys
from pathlib import Path
# Import our modular components
from xcode import BuildRunner, OutputFormatter, XCResultCache, XCResultParser
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(
description="Build and test Xcode projects with progressive disclosure",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Build project (minimal output)
python scripts/build_and_test.py --project MyApp.xcodeproj
# Run tests
python scripts/build_and_test.py --project MyApp.xcodeproj --test
# Get error details from previous build
python scripts/build_and_test.py --get-errors xcresult-20251018-143052
# Get all details as JSON
python scripts/build_and_test.py --get-all xcresult-20251018-143052 --json
# List recent builds
python scripts/build_and_test.py --list-xcresults
""",
)
# Build/test mode arguments
build_group = parser.add_argument_group("Build/Test Options")
project_group = build_group.add_mutually_exclusive_group()
project_group.add_argument("--project", help="Path to .xcodeproj file")
project_group.add_argument("--workspace", help="Path to .xcworkspace file")
build_group.add_argument("--scheme", help="Build scheme (auto-detected if not specified)")
build_group.add_argument(
"--configuration",
default="Debug",
choices=["Debug", "Release"],
help="Build configuration (default: Debug)",
)
build_group.add_argument("--simulator", help="Simulator name (default: iPhone 15)")
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")
# Progressive disclosure arguments
disclosure_group = parser.add_argument_group("Progressive Disclosure Options")
disclosure_group.add_argument(
"--get-errors", metavar="XCRESULT_ID", help="Get error details from xcresult"
)
disclosure_group.add_argument(
"--get-warnings", metavar="XCRESULT_ID", help="Get warning details from xcresult"
)
disclosure_group.add_argument(
"--get-log", metavar="XCRESULT_ID", help="Get build log from xcresult"
)
disclosure_group.add_argument(
"--get-all", metavar="XCRESULT_ID", help="Get all details from xcresult"
)
disclosure_group.add_argument(
"--list-xcresults", action="store_true", help="List recent xcresult bundles"
)
# Output options
output_group = parser.add_argument_group("Output Options")
output_group.add_argument("--verbose", action="store_true", help="Show detailed output")
output_group.add_argument("--json", action="store_true", help="Output as JSON")
args = parser.parse_args()
# Initialize cache
cache = XCResultCache()
# Handle list mode
if args.list_xcresults:
xcresults = cache.list()
if args.json:
import json
print(json.dumps(xcresults, indent=2))
elif not xcresults:
print("No xcresult bundles found")
else:
print(f"Recent XCResult bundles ({len(xcresults)}):")
print()
for xc in xcresults:
print(f" {xc['id']}")
print(f" Created: {xc['created']}")
print(f" Size: {xc['size_mb']} MB")
print()
return 0
# Handle retrieval modes
xcresult_id = args.get_errors or args.get_warnings or args.get_log or args.get_all
if xcresult_id:
xcresult_path = cache.get_path(xcresult_id)
if not xcresult_path or not xcresult_path.exists():
print(f"Error: XCResult bundle not found: {xcresult_id}", file=sys.stderr)
print("Use --list-xcresults to see available bundles", file=sys.stderr)
return 1
# Load cached stderr for progressive disclosure
cached_stderr = cache.get_stderr(xcresult_id)
parser = XCResultParser(xcresult_path, stderr=cached_stderr)
# Get errors
if args.get_errors:
errors = parser.get_errors()
if args.json:
import json
print(json.dumps(errors, indent=2))
else:
print(OutputFormatter.format_errors(errors))
return 0
# Get warnings
if args.get_warnings:
warnings = parser.get_warnings()
if args.json:
import json
print(json.dumps(warnings, indent=2))
else:
print(OutputFormatter.format_warnings(warnings))
return 0
# Get log
if args.get_log:
log = parser.get_build_log()
if log:
print(OutputFormatter.format_log(log))
else:
print("No build log available", file=sys.stderr)
return 1
return 0
# Get all
if args.get_all:
error_count, warning_count = parser.count_issues()
errors = parser.get_errors()
warnings = parser.get_warnings()
build_log = parser.get_build_log()
if args.json:
import json
data = {
"xcresult_id": xcresult_id,
"error_count": error_count,
"warning_count": warning_count,
"errors": errors,
"warnings": warnings,
"log_preview": build_log[:1000] if build_log else None,
}
print(json.dumps(data, indent=2))
else:
print(f"XCResult: {xcresult_id}")
print(f"Errors: {error_count}, Warnings: {warning_count}")
print()
if errors:
print(OutputFormatter.format_errors(errors, limit=10))
print()
if warnings:
print(OutputFormatter.format_warnings(warnings, limit=10))
print()
if build_log:
print("Build Log (last 30 lines):")
print(OutputFormatter.format_log(build_log, lines=30))
return 0
# Build/test mode
if not args.project and not args.workspace:
# Try to auto-detect in current directory
cwd = Path.cwd()
projects = list(cwd.glob("*.xcodeproj"))
workspaces = list(cwd.glob("*.xcworkspace"))
if workspaces:
args.workspace = str(workspaces[0])
elif projects:
args.project = str(projects[0])
else:
parser.error("No project or workspace specified and none found in current directory")
# Initialize builder
builder = BuildRunner(
project_path=args.project,
workspace_path=args.workspace,
scheme=args.scheme,
configuration=args.configuration,
simulator=args.simulator,
cache=cache,
)
# Execute build or test
if args.test:
success, xcresult_id, stderr = builder.test(test_suite=args.suite)
else:
success, xcresult_id, stderr = builder.build(clean=args.clean)
if not xcresult_id and not stderr:
print("Error: Build/test failed without creating xcresult or error output", file=sys.stderr)
return 1
# Save stderr to cache for progressive disclosure
if xcresult_id and stderr:
cache.save_stderr(xcresult_id, stderr)
# Parse results
xcresult_path = cache.get_path(xcresult_id) if xcresult_id else None
parser = XCResultParser(xcresult_path, stderr=stderr)
error_count, warning_count = parser.count_issues()
# Format output
status = "SUCCESS" if success else "FAILED"
# Generate hints for failed builds
hints = None
if not success:
errors = parser.get_errors()
hints = OutputFormatter.generate_hints(errors)
if args.verbose:
# Verbose mode with error/warning details
errors = parser.get_errors() if error_count > 0 else None
warnings = parser.get_warnings() if warning_count > 0 else None
output = OutputFormatter.format_verbose(
status=status,
error_count=error_count,
warning_count=warning_count,
xcresult_id=xcresult_id or "N/A",
errors=errors,
warnings=warnings,
)
print(output)
elif args.json:
# JSON mode
data = {
"success": success,
"xcresult_id": xcresult_id or None,
"error_count": error_count,
"warning_count": warning_count,
}
if hints:
data["hints"] = hints
import json
print(json.dumps(data, indent=2))
else:
# Minimal mode (default)
output = OutputFormatter.format_minimal(
status=status,
error_count=error_count,
warning_count=warning_count,
xcresult_id=xcresult_id or "N/A",
hints=hints,
)
print(output)
# Exit with appropriate code
return 0 if success else 1
if __name__ == "__main__":
sys.exit(main())
#!/usr/bin/env python3
"""
iOS Simulator Clipboard Manager
Copy text to simulator clipboard for testing paste flows.
Optimized for minimal token output.
Usage: python scripts/clipboard.py --copy "text to copy"
"""
import argparse
import subprocess
import sys
from common import resolve_udid
class ClipboardManager:
"""Manages clipboard operations on iOS simulator."""
def __init__(self, udid: str | None = None):
"""Initialize clipboard manager.
Args:
udid: Optional device UDID (auto-detects booted simulator if None)
"""
self.udid = udid
def copy(self, text: str) -> bool:
"""
Copy text to simulator clipboard.
Args:
text: Text to copy to clipboard
Returns:
Success status
"""
cmd = ["xcrun", "simctl", "pbcopy"]
if self.udid:
cmd.append(self.udid)
else:
cmd.append("booted")
cmd.append(text)
try:
subprocess.run(cmd, capture_output=True, check=True)
return True
except subprocess.CalledProcessError:
return False
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(description="Copy text to iOS simulator clipboard")
parser.add_argument("--copy", required=True, help="Text to copy to clipboard")
parser.add_argument(
"--udid",
help="Device UDID (auto-detects booted simulator if not provided)",
)
parser.add_argument("--test-name", help="Test scenario name for tracking")
parser.add_argument("--expected", help="Expected behavior after paste")
args = parser.parse_args()
# Resolve UDID with auto-detection
try:
udid = resolve_udid(args.udid)
except RuntimeError as e:
print(f"Error: {e}")
sys.exit(1)
# Create manager and copy text
manager = ClipboardManager(udid=udid)
if manager.copy(args.copy):
# Token-efficient output
output = f'Copied: "{args.copy}"'
if args.test_name:
output += f" (test: {args.test_name})"
print(output)
# Provide usage guidance
if args.expected:
print(f"Expected: {args.expected}")
print()
print("Next steps:")
print("1. Tap text field with: python scripts/navigator.py --find-type TextField --tap")
print("2. Paste with: python scripts/keyboard.py --key return")
print(" Or use Cmd+V gesture with: python scripts/keyboard.py --key cmd+v")
else:
print("Failed to copy text to clipboard")
sys.exit(1)
if __name__ == "__main__":
main()
"""
Common utilities shared across iOS simulator scripts.
This module centralizes genuinely reused code patterns to eliminate duplication
while respecting Jackson's Law - no over-abstraction, only truly shared logic.
Organization:
- device_utils: Device detection, command building, coordinate transformation
- idb_utils: IDB-specific operations (accessibility tree, element manipulation)
- cache_utils: Progressive disclosure caching for large outputs
- screenshot_utils: Screenshot capture with file and inline modes
"""
from .cache_utils import ProgressiveCache, get_cache
from .device_utils import (
build_idb_command,
build_simctl_command,
get_booted_device_udid,
get_device_screen_size,
resolve_udid,
transform_screenshot_coords,
)
from .idb_utils import (
count_elements,
flatten_tree,
get_accessibility_tree,
get_screen_size,
)
from .screenshot_utils import (
capture_screenshot,
format_screenshot_result,
generate_screenshot_name,
get_size_preset,
resize_screenshot,
)
__all__ = [
# cache_utils
"ProgressiveCache",
# device_utils
"build_idb_command",
"build_simctl_command",
# screenshot_utils
"capture_screenshot",
# idb_utils
"count_elements",
"flatten_tree",
"format_screenshot_result",
"generate_screenshot_name",
"get_accessibility_tree",
"get_booted_device_udid",
"get_cache",
"get_device_screen_size",
"get_screen_size",
"get_size_preset",
"resize_screenshot",
"resolve_udid",
"transform_screenshot_coords",
]
#!/usr/bin/env python3
"""
Progressive disclosure cache for large outputs.
Implements cache system to support progressive disclosure pattern:
- Return concise summary with cache_id for large outputs
- User retrieves full details on demand via cache_id
- Reduces token usage by 96% for common queries
Cache directory: ~/.ios-simulator-skill/cache/
Cache expiration: Configurable per cache type (default 1 hour)
Used by:
- sim_list.py - Simulator listing progressive disclosure
- Future: build logs, UI trees, etc.
"""
import json
import time
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any
class ProgressiveCache:
"""Cache for progressive disclosure pattern.
Stores large outputs with timestamped IDs for on-demand retrieval.
Automatically cleans up expired entries.
"""
def __init__(self, cache_dir: str | None = None, max_age_hours: int = 1):
"""Initialize cache system.
Args:
cache_dir: Cache directory path (default: ~/.ios-simulator-skill/cache/)
max_age_hours: Max age for cache entries before expiration (default: 1 hour)
"""
if cache_dir is None:
cache_dir = str(Path("~/.ios-simulator-skill/cache").expanduser())
self.cache_dir = Path(cache_dir)
self.max_age_hours = max_age_hours
# Create cache directory if needed
self.cache_dir.mkdir(parents=True, exist_ok=True)
def save(self, data: dict[str, Any], cache_type: str) -> str:
"""Save data to cache and return cache_id.
Args:
data: Dictionary data to cache
cache_type: Type of cache ('simulator-list', 'build-log', 'ui-tree', etc.)
Returns:
Cache ID like 'sim-20251028-143052' for use in progressive disclosure
Example:
cache_id = cache.save({'devices': [...]}, 'simulator-list')
# Returns: 'sim-20251028-143052'
"""
# Generate cache_id with timestamp
timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
cache_prefix = cache_type.split("-")[0] # e.g., 'sim' from 'simulator-list'
cache_id = f"{cache_prefix}-{timestamp}"
# Save to file
cache_file = self.cache_dir / f"{cache_id}.json"
with open(cache_file, "w") as f:
json.dump(
{
"cache_id": cache_id,
"cache_type": cache_type,
"created_at": datetime.now().isoformat(),
"data": data,
},
f,
indent=2,
)
return cache_id
def get(self, cache_id: str) -> dict[str, Any] | None:
"""Retrieve data from cache by cache_id.
Args:
cache_id: Cache ID from save() or list_entries()
Returns:
Cached data dictionary, or None if not found/expired
Example:
data = cache.get('sim-20251028-143052')
if data:
print(f"Found {len(data)} devices")
"""
cache_file = self.cache_dir / f"{cache_id}.json"
if not cache_file.exists():
return None
# Check if expired
if self._is_expired(cache_file):
cache_file.unlink() # Delete expired file
return None
try:
with open(cache_file) as f:
entry = json.load(f)
return entry.get("data")
except (OSError, json.JSONDecodeError):
return None
def list_entries(self, cache_type: str | None = None) -> list[dict[str, Any]]:
"""List available cache entries with metadata.
Args:
cache_type: Filter by type (e.g., 'simulator-list'), or None for all
Returns:
List of cache entries with id, type, created_at, age_seconds
Example:
entries = cache.list_entries('simulator-list')
for entry in entries:
print(f"{entry['id']} - {entry['age_seconds']}s old")
"""
entries = []
for cache_file in sorted(self.cache_dir.glob("*.json"), reverse=True):
# Check if expired
if self._is_expired(cache_file):
cache_file.unlink()
continue
try:
with open(cache_file) as f:
entry = json.load(f)
# Filter by type if specified
if cache_type and entry.get("cache_type") != cache_type:
continue
created_at = datetime.fromisoformat(entry.get("created_at", ""))
age_seconds = (datetime.now() - created_at).total_seconds()
entries.append(
{
"id": entry.get("cache_id"),
"type": entry.get("cache_type"),
"created_at": entry.get("created_at"),
"age_seconds": int(age_seconds),
}
)
except (OSError, json.JSONDecodeError, ValueError):
continue
return entries
def cleanup(self, max_age_hours: int | None = None) -> int:
"""Remove expired cache entries.
Args:
max_age_hours: Age threshold (default: uses instance max_age_hours)
Returns:
Number of entries deleted
Example:
deleted = cache.cleanup()
print(f"Deleted {deleted} expired cache entries")
"""
if max_age_hours is None:
max_age_hours = self.max_age_hours
deleted = 0
for cache_file in self.cache_dir.glob("*.json"):
if self._is_expired(cache_file, max_age_hours):
cache_file.unlink()
deleted += 1
return deleted
def clear(self, cache_type: str | None = None) -> int:
"""Clear all cache entries of a type.
Args:
cache_type: Type to clear (e.g., 'simulator-list'), or None to clear all
Returns:
Number of entries deleted
Example:
cleared = cache.clear('simulator-list')
print(f"Cleared {cleared} simulator list entries")
"""
deleted = 0
for cache_file in self.cache_dir.glob("*.json"):
if cache_type is None:
# Clear all
cache_file.unlink()
deleted += 1
else:
# Clear by type
try:
with open(cache_file) as f:
entry = json.load(f)
if entry.get("cache_type") == cache_type:
cache_file.unlink()
deleted += 1
except (OSError, json.JSONDecodeError):
pass
return deleted
def _is_expired(self, cache_file: Path, max_age_hours: int | None = None) -> bool:
"""Check if cache file is expired.
Args:
cache_file: Path to cache file
max_age_hours: Age threshold (default: uses instance max_age_hours)
Returns:
True if file is older than max_age_hours
"""
if max_age_hours is None:
max_age_hours = self.max_age_hours
try:
with open(cache_file) as f:
entry = json.load(f)
created_at = datetime.fromisoformat(entry.get("created_at", ""))
age = datetime.now() - created_at
return age > timedelta(hours=max_age_hours)
except (OSError, json.JSONDecodeError, ValueError):
return True
# Module-level cache instances (lazy-loaded)
_cache_instances: dict[str, ProgressiveCache] = {}
def get_cache(cache_dir: str | None = None) -> ProgressiveCache:
"""Get or create global cache instance.
Args:
cache_dir: Custom cache directory (uses default if None)
Returns:
ProgressiveCache instance
"""
# Use cache_dir as key, or 'default' if None
key = cache_dir or "default"
if key not in _cache_instances:
_cache_instances[key] = ProgressiveCache(cache_dir)
return _cache_instances[key]
#!/usr/bin/env python3
"""
Shared device and simulator utilities.
Common patterns for interacting with simulators via xcrun simctl and IDB.
Standardizes command building and device targeting to prevent errors.
Follows Jackson's Law - only extracts genuinely reused patterns.
Used by:
- app_launcher.py (8 call sites) - App lifecycle commands
- Multiple scripts (15+ locations) - IDB command building
- navigator.py, gesture.py - Coordinate transformation
- test_recorder.py, app_state_capture.py - Auto-UDID detection
"""
import json
import re
import subprocess
def build_simctl_command(
operation: str,
udid: str | None = None,
*args,
) -> list[str]:
"""
Build xcrun simctl command with proper device handling.
Standardizes command building to prevent device targeting bugs.
Automatically uses "booted" if no UDID provided.
Used by:
- app_launcher.py: launch, terminate, install, uninstall, openurl, listapps, spawn
- Multiple scripts: generic simctl operations
Args:
operation: simctl operation (launch, terminate, install, etc.)
udid: Device UDID (uses 'booted' if None)
*args: Additional command arguments
Returns:
Complete command list ready for subprocess.run()
Examples:
# Launch app on booted simulator
cmd = build_simctl_command("launch", None, "com.app.bundle")
# Returns: ["xcrun", "simctl", "launch", "booted", "com.app.bundle"]
# Launch on specific device
cmd = build_simctl_command("launch", "ABC123", "com.app.bundle")
# Returns: ["xcrun", "simctl", "launch", "ABC123", "com.app.bundle"]
# Install app on specific device
cmd = build_simctl_command("install", "ABC123", "/path/to/app.app")
# Returns: ["xcrun", "simctl", "install", "ABC123", "/path/to/app.app"]
"""
cmd = ["xcrun", "simctl", operation]
# Add device (booted or specific UDID)
cmd.append(udid if udid else "booted")
# Add remaining arguments
cmd.extend(str(arg) for arg in args)
return cmd
def build_idb_command(
operation: str,
udid: str | None = None,
*args,
) -> list[str]:
"""
Build IDB command with proper device targeting.
Standardizes IDB command building across all scripts using IDB.
Handles device UDID consistently.
Used by:
- navigator.py: ui tap, ui text, ui describe-all
- gesture.py: ui swipe, ui tap
- keyboard.py: ui key, ui text, ui tap
- And more: 15+ locations
Args:
operation: IDB operation path (e.g., "ui tap", "ui text", "ui describe-all")
udid: Device UDID (omits --udid flag if None, IDB uses booted by default)
*args: Additional command arguments
Returns:
Complete command list ready for subprocess.run()
Examples:
# Tap on booted simulator
cmd = build_idb_command("ui tap", None, "200", "400")
# Returns: ["idb", "ui", "tap", "200", "400"]
# Tap on specific device
cmd = build_idb_command("ui tap", "ABC123", "200", "400")
# Returns: ["idb", "ui", "tap", "200", "400", "--udid", "ABC123"]
# Get accessibility tree
cmd = build_idb_command("ui describe-all", "ABC123", "--json", "--nested")
# Returns: ["idb", "ui", "describe-all", "--json", "--nested", "--udid", "ABC123"]
# Enter text
cmd = build_idb_command("ui text", None, "hello world")
# Returns: ["idb", "ui", "text", "hello world"]
"""
# Split operation into parts (e.g., "ui tap" -> ["ui", "tap"])
cmd = ["idb"] + operation.split()
# Add arguments
cmd.extend(str(arg) for arg in args)
# Add device targeting if specified (optional for IDB, uses booted by default)
if udid:
cmd.extend(["--udid", udid])
return cmd
def get_booted_device_udid() -> str | None:
"""
Auto-detect currently booted simulator UDID.
Queries xcrun simctl for booted devices and returns first match.
Returns:
UDID of booted simulator, or None if no simulator is booted.
Example:
udid = get_booted_device_udid()
if udid:
print(f"Booted simulator: {udid}")
else:
print("No simulator is currently booted")
"""
try:
result = subprocess.run(
["xcrun", "simctl", "list", "devices", "booted"],
capture_output=True,
text=True,
check=True,
)
# Parse output to find UDID
# Format: " iPhone 16 Pro (ABC123-DEF456) (Booted)"
for line in result.stdout.split("\n"):
# Look for UUID pattern in parentheses
match = re.search(r"\(([A-F0-9\-]{36})\)", line)
if match:
return match.group(1)
return None
except subprocess.CalledProcessError:
return None
def resolve_udid(udid_arg: str | None) -> str:
"""
Resolve device UDID with auto-detection fallback.
If udid_arg is provided, returns it immediately.
If None, attempts to auto-detect booted simulator.
Raises error if neither is available.
Args:
udid_arg: Explicit UDID from command line, or None
Returns:
Valid UDID string
Raises:
RuntimeError: If no UDID provided and no booted simulator found
Example:
try:
udid = resolve_udid(args.udid) # args.udid might be None
print(f"Using device: {udid}")
except RuntimeError as e:
print(f"Error: {e}")
sys.exit(1)
"""
if udid_arg:
return udid_arg
booted_udid = get_booted_device_udid()
if booted_udid:
return booted_udid
raise RuntimeError(
"No device UDID provided and no simulator is currently booted.\n"
"Boot a simulator or provide --udid explicitly:\n"
" xcrun simctl boot <device-name>\n"
" python scripts/script_name.py --udid <device-udid>"
)
def get_device_screen_size(udid: str) -> tuple[int, int]:
"""
Get actual screen dimensions for device via accessibility tree.
Queries IDB accessibility tree to determine actual device resolution.
Falls back to iPhone 14 defaults (390x844) if detection fails.
Args:
udid: Device UDID
Returns:
Tuple of (width, height) in pixels
Example:
width, height = get_device_screen_size("ABC123")
print(f"Device screen: {width}x{height}")
"""
try:
cmd = build_idb_command("ui describe-all", udid, "--json")
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
# Parse JSON response
data = json.loads(result.stdout)
tree = data[0] if isinstance(data, list) and len(data) > 0 else data
# Get frame size from root element
if tree and "frame" in tree:
frame = tree["frame"]
width = int(frame.get("width", 390))
height = int(frame.get("height", 844))
return (width, height)
# Fallback
return (390, 844)
except Exception:
# Graceful fallback to iPhone 14 Pro defaults
return (390, 844)
def resolve_device_identifier(identifier: str) -> str:
"""
Resolve device name or partial UDID to full UDID.
Supports multiple identifier formats:
- Full UDID: "ABC-123-DEF456..." (36 character UUID)
- Device name: "iPhone 16 Pro" (matches full name)
- Partial match: "iPhone 16" (matches first device containing this string)
- Special: "booted" (resolves to currently booted device)
Args:
identifier: Device UDID, name, or special value "booted"
Returns:
Full device UDID
Raises:
RuntimeError: If identifier cannot be resolved
Example:
udid = resolve_device_identifier("iPhone 16 Pro")
# Returns: "ABC123DEF456..."
udid = resolve_device_identifier("booted")
# Returns UDID of booted simulator
"""
# Handle "booted" special case
if identifier.lower() == "booted":
booted = get_booted_device_udid()
if booted:
return booted
raise RuntimeError(
"No simulator is currently booted. "
"Boot a simulator first: xcrun simctl boot <device-udid>"
)
# Check if already a full UDID (36 character UUID format)
if re.match(r"^[A-F0-9\-]{36}$", identifier, re.IGNORECASE):
return identifier.upper()
# Try to match by device name
simulators = list_simulators(state=None)
exact_matches = [s for s in simulators if s["name"].lower() == identifier.lower()]
if exact_matches:
return exact_matches[0]["udid"]
# Try partial match
partial_matches = [s for s in simulators if identifier.lower() in s["name"].lower()]
if partial_matches:
return partial_matches[0]["udid"]
# No match found
raise RuntimeError(
f"Device '{identifier}' not found. "
f"Use 'xcrun simctl list devices' to see available simulators."
)
def list_simulators(state: str | None = None) -> list[dict]:
"""
List iOS simulators with optional state filtering.
Queries xcrun simctl and returns structured list of simulators.
Optionally filters by state (available, booted, all).
Args:
state: Optional filter - "available", "booted", or None for all
Returns:
List of simulator dicts with keys:
- "name": Device name (e.g., "iPhone 16 Pro")
- "udid": Device UDID (36 char UUID)
- "state": Device state ("Booted", "Shutdown", "Unavailable")
- "runtime": iOS version (e.g., "iOS 18.0", "unavailable")
- "type": Device type ("iPhone", "iPad", "Apple Watch", etc.)
Example:
# List all simulators
all_sims = list_simulators()
print(f"Total simulators: {len(all_sims)}")
# List only available simulators
available = list_simulators(state="available")
for sim in available:
print(f"{sim['name']} ({sim['state']}) - {sim['udid']}")
# List only booted simulators
booted = list_simulators(state="booted")
for sim in booted:
print(f"Booted: {sim['name']}")
"""
try:
# Query simctl for device list
cmd = ["xcrun", "simctl", "list", "devices", "-j"]
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
data = json.loads(result.stdout)
simulators = []
# Parse JSON response
# Format: {"devices": {"iOS 18.0": [{...}, {...}], "iOS 17.0": [...], ...}}
for ios_version, devices in data.get("devices", {}).items():
for device in devices:
sim = {
"name": device.get("name", "Unknown"),
"udid": device.get("udid", ""),
"state": device.get("state", "Unknown"),
"runtime": ios_version,
"type": _extract_device_type(device.get("name", "")),
}
simulators.append(sim)
# Apply state filtering
if state == "booted":
return [s for s in simulators if s["state"] == "Booted"]
if state == "available":
return [s for s in simulators if s["state"] == "Shutdown"] # Available to boot
if state is None:
return simulators
return [s for s in simulators if s["state"].lower() == state.lower()]
except (subprocess.CalledProcessError, json.JSONDecodeError, KeyError) as e:
raise RuntimeError(f"Failed to list simulators: {e}") from e
def _extract_device_type(device_name: str) -> str:
"""
Extract device type from device name.
Parses device name to determine type (iPhone, iPad, Watch, etc.).
Args:
device_name: Full device name (e.g., "iPhone 16 Pro")
Returns:
Device type string
Example:
_extract_device_type("iPhone 16 Pro") # Returns "iPhone"
_extract_device_type("iPad Air") # Returns "iPad"
_extract_device_type("Apple Watch Series 9") # Returns "Watch"
"""
if "iPhone" in device_name:
return "iPhone"
if "iPad" in device_name:
return "iPad"
if "Watch" in device_name or "Apple Watch" in device_name:
return "Watch"
if "TV" in device_name or "Apple TV" in device_name:
return "TV"
return "Unknown"
def transform_screenshot_coords(
x: float,
y: float,
screenshot_width: int,
screenshot_height: int,
device_width: int,
device_height: int,
) -> tuple[int, int]:
"""
Transform screenshot coordinates to device coordinates.
Handles the case where a screenshot was downscaled (e.g., to 'half' size)
and needs to be transformed back to actual device pixel coordinates
for accurate tapping.
The transformation is linear:
device_x = (screenshot_x / screenshot_width) * device_width
device_y = (screenshot_y / screenshot_height) * device_height
Args:
x, y: Coordinates in the screenshot
screenshot_width, screenshot_height: Screenshot dimensions (e.g., 195, 422)
device_width, device_height: Actual device dimensions (e.g., 390, 844)
Returns:
Tuple of (device_x, device_y) in device pixels
Example:
# Screenshot taken at 'half' size: 195x422 (from 390x844 device)
device_x, device_y = transform_screenshot_coords(
100, 200, # Tap point in screenshot
195, 422, # Screenshot dimensions
390, 844 # Device dimensions
)
print(f"Tap at device coords: ({device_x}, {device_y})")
# Output: Tap at device coords: (200, 400)
"""
device_x = int((x / screenshot_width) * device_width)
device_y = int((y / screenshot_height) * device_height)
return (device_x, device_y)
#!/usr/bin/env python3
"""
Shared IDB utility functions.
This module provides common IDB operations used across multiple scripts.
Follows Jackson's Law - only shared code that's truly reused, not speculative.
Used by:
- navigator.py - Accessibility tree navigation
- screen_mapper.py - UI element analysis
- accessibility_audit.py - WCAG compliance checking
- test_recorder.py - Test documentation
- app_state_capture.py - State snapshots
- gesture.py - Touch gesture operations
"""
import json
import subprocess
import sys
def get_accessibility_tree(udid: str | None = None, nested: bool = True) -> dict:
"""
Fetch accessibility tree from IDB.
The accessibility tree represents the complete UI hierarchy of the current
screen, with all element properties needed for semantic navigation.
Args:
udid: Device UDID (uses booted simulator if None)
nested: Include nested structure (default True). If False, returns flat array.
Returns:
Root element of accessibility tree as dict.
Structure: {
"type": "Window",
"AXLabel": "App Name",
"frame": {"x": 0, "y": 0, "width": 390, "height": 844},
"children": [...]
}
Raises:
SystemExit: If IDB command fails or returns invalid JSON
Example:
tree = get_accessibility_tree("UDID123")
# Root is Window element with all children nested
"""
cmd = ["idb", "ui", "describe-all", "--json"]
if nested:
cmd.append("--nested")
if udid:
cmd.extend(["--udid", udid])
try:
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
tree_data = json.loads(result.stdout)
# IDB returns array format, extract first element (root)
if isinstance(tree_data, list) and len(tree_data) > 0:
return tree_data[0]
return tree_data
except subprocess.CalledProcessError as e:
print(f"Error: Failed to get accessibility tree: {e.stderr}", file=sys.stderr)
sys.exit(1)
except json.JSONDecodeError:
print("Error: Invalid JSON from idb", file=sys.stderr)
sys.exit(1)
def flatten_tree(node: dict, depth: int = 0, elements: list[dict] | None = None) -> list[dict]:
"""
Flatten nested accessibility tree into list of elements.
Converts the hierarchical accessibility tree into a flat list where each
element includes its depth for context.
Used by:
- navigator.py - Element finding
- screen_mapper.py - Element analysis
- accessibility_audit.py - Audit scanning
Args:
node: Root node of tree (typically from get_accessibility_tree)
depth: Current depth (used internally, start at 0)
elements: Accumulator list (used internally, start as None)
Returns:
Flat list of elements, each with "depth" key indicating nesting level.
Structure of each element: {
"type": "Button",
"AXLabel": "Login",
"frame": {...},
"depth": 2,
...
}
Example:
tree = get_accessibility_tree()
flat = flatten_tree(tree)
for elem in flat:
print(f"{' ' * elem['depth']}{elem.get('type')}: {elem.get('AXLabel')}")
"""
if elements is None:
elements = []
# Add current node with depth tracking
node_copy = node.copy()
node_copy["depth"] = depth
elements.append(node_copy)
# Process children recursively
for child in node.get("children", []):
flatten_tree(child, depth + 1, elements)
return elements
def count_elements(node: dict) -> int:
"""
Count total elements in tree (recursive).
Traverses entire tree counting all elements for reporting purposes.
Used by:
- test_recorder.py - Element counting per step
- screen_mapper.py - Summary statistics
Args:
node: Root node of tree
Returns:
Total element count including root and all descendants
Example:
tree = get_accessibility_tree()
total = count_elements(tree)
print(f"Screen has {total} elements")
"""
count = 1
for child in node.get("children", []):
count += count_elements(child)
return count
def get_screen_size(udid: str | None = None) -> tuple[int, int]:
"""
Get screen dimensions from accessibility tree.
Extracts the screen size from the root element's frame. Useful for
gesture calculations and coordinate normalization.
Used by:
- gesture.py - Gesture positioning
- Potentially: screenshot positioning, screen-aware scaling
Args:
udid: Device UDID (uses booted if None)
Returns:
(width, height) tuple. Defaults to (390, 844) if detection fails
or tree cannot be accessed.
Example:
width, height = get_screen_size()
center_x = width // 2
center_y = height // 2
"""
DEFAULT_WIDTH = 390 # iPhone 14
DEFAULT_HEIGHT = 844
try:
tree = get_accessibility_tree(udid, nested=False)
frame = tree.get("frame", {})
width = int(frame.get("width", DEFAULT_WIDTH))
height = int(frame.get("height", DEFAULT_HEIGHT))
return (width, height)
except Exception:
# Silently fall back to defaults if tree access fails
return (DEFAULT_WIDTH, DEFAULT_HEIGHT)
#!/usr/bin/env python3
"""
Screenshot utilities with dual-mode support.
Provides unified screenshot handling with:
- File-based mode: Persistent artifacts for test documentation
- Inline base64 mode: Vision-based automation for agent analysis
- Size presets: Token optimization (full/half/quarter/thumb)
- Semantic naming: {appName}_{screenName}_{state}_{timestamp}.png
Supports resize operations via PIL (optional dependency).
Used by:
- test_recorder.py - Step-based screenshot recording
- app_state_capture.py - State snapshot captures
"""
import base64
import os
import subprocess
import sys
from datetime import datetime
from pathlib import Path
from typing import Any
# Try to import PIL for resizing, but make it optional
try:
from PIL import Image
HAS_PIL = True
except ImportError:
HAS_PIL = False
def generate_screenshot_name(
app_name: str | None = None,
screen_name: str | None = None,
state: str | None = None,
timestamp: str | None = None,
extension: str = "png",
) -> str:
"""Generate semantic screenshot filename.
Format: {appName}_{screenName}_{state}_{timestamp}.{ext}
Falls back to: screenshot_{timestamp}.{ext}
Args:
app_name: Application name (e.g., 'MyApp')
screen_name: Screen name (e.g., 'Login')
state: State description (e.g., 'Empty', 'Filled', 'Error')
timestamp: ISO timestamp (uses current time if None)
extension: File extension (default: 'png')
Returns:
Semantic filename ready for safe file creation
Example:
name = generate_screenshot_name('MyApp', 'Login', 'Empty')
# Returns: 'MyApp_Login_Empty_20251028-143052.png'
name = generate_screenshot_name()
# Returns: 'screenshot_20251028-143052.png'
"""
if timestamp is None:
timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
# Build semantic name
if app_name or screen_name or state:
parts = [app_name, screen_name, state]
parts = [p for p in parts if p] # Filter None/empty
name = "_".join(parts) + f"_{timestamp}"
else:
name = f"screenshot_{timestamp}"
return f"{name}.{extension}"
def get_size_preset(size: str = "half") -> tuple[float, float]:
"""Get scale factors for size preset.
Args:
size: 'full', 'half', 'quarter', 'thumb'
Returns:
Tuple of (scale_x, scale_y) for resizing
Example:
scale_x, scale_y = get_size_preset('half')
# Returns: (0.5, 0.5)
"""
presets = {
"full": (1.0, 1.0),
"half": (0.5, 0.5),
"quarter": (0.25, 0.25),
"thumb": (0.1, 0.1),
}
return presets.get(size, (0.5, 0.5))
def resize_screenshot(
input_path: str,
output_path: str | None = None,
size: str = "half",
quality: int = 85,
) -> tuple[str, int, int]:
"""Resize screenshot for token optimization.
Requires PIL (Pillow). Falls back gracefully without it.
Args:
input_path: Path to original screenshot
output_path: Output path (uses input_path if None)
size: 'full', 'half', 'quarter', 'thumb'
quality: JPEG quality (1-100, default: 85)
Returns:
Tuple of (output_path, width, height) of resized image
Raises:
FileNotFoundError: If input file doesn't exist
ValueError: If PIL not installed and size != 'full'
Example:
output, w, h = resize_screenshot(
'screenshot.png',
'screenshot_half.png',
'half'
)
print(f"Resized to {w}x{h}")
"""
input_file = Path(input_path)
if not input_file.exists():
raise FileNotFoundError(f"Screenshot not found: {input_path}")
# If full size, just copy
if size == "full":
if output_path:
import shutil
shutil.copy(input_path, output_path)
output_file = Path(output_path)
else:
output_file = input_file
# Get original dimensions
if HAS_PIL:
img = Image.open(str(output_file))
return (str(output_file), img.width, img.height)
return (str(output_file), 0, 0) # Dimensions unknown without PIL
# Need PIL to resize
if not HAS_PIL:
raise ValueError(
f"Size preset '{size}' requires PIL (Pillow). " "Install with: pip3 install pillow"
)
# Open original image
img = Image.open(str(input_file))
orig_w, orig_h = img.size
# Calculate new size
scale_x, scale_y = get_size_preset(size)
new_w = int(orig_w * scale_x)
new_h = int(orig_h * scale_y)
# Resize with high-quality resampling
resized = img.resize((new_w, new_h), Image.Resampling.LANCZOS)
# Determine output path
if output_path is None:
# Insert size marker before extension
stem = input_file.stem
suffix = input_file.suffix
output_path = str(input_file.parent / f"{stem}_{size}{suffix}")
# Save resized image
resized.save(output_path, quality=quality, optimize=True)
return (output_path, new_w, new_h)
def capture_screenshot(
udid: str,
output_path: str | None = None,
size: str = "half",
inline: bool = False,
app_name: str | None = None,
screen_name: str | None = None,
state: str | None = None,
) -> dict[str, Any]:
"""Capture screenshot with flexible output modes.
Supports both file-based (persistent artifacts) and inline base64 modes
(for vision-based automation).
Args:
udid: Device UDID
output_path: File path for file mode (generates semantic name if None)
size: 'full', 'half', 'quarter', 'thumb' (default: 'half')
inline: If True, returns base64 data instead of saving to file
app_name: App name for semantic naming
screen_name: Screen name for semantic naming
state: State description for semantic naming
Returns:
Dict with mode-specific fields:
File mode:
{
'mode': 'file',
'file_path': str,
'size_bytes': int,
'width': int,
'height': int,
'size_preset': str
}
Inline mode:
{
'mode': 'inline',
'base64_data': str,
'mime_type': 'image/png',
'width': int,
'height': int,
'size_preset': str
}
Example:
# File mode
result = capture_screenshot('ABC123', app_name='MyApp')
print(f"Saved to: {result['file_path']}")
# Inline mode
result = capture_screenshot('ABC123', inline=True, size='half')
print(f"Screenshot: {result['width']}x{result['height']}")
print(f"Base64: {result['base64_data'][:50]}...")
"""
try:
# Capture raw screenshot to temp file
temp_path = "/tmp/ios_simulator_screenshot.png"
cmd = ["xcrun", "simctl", "io", udid, "screenshot", temp_path]
subprocess.run(cmd, capture_output=True, text=True, check=True)
if inline:
# Inline mode: resize and convert to base64
# Resize if needed
if size != "full" and HAS_PIL:
resized_path, width, height = resize_screenshot(temp_path, size=size)
else:
resized_path = temp_path
# Get dimensions via PIL if available
if HAS_PIL:
img = Image.open(resized_path)
width, height = img.size
else:
width, height = 390, 844 # Fallback to common device size
# Read and encode as base64
with open(resized_path, "rb") as f:
base64_data = base64.b64encode(f.read()).decode("utf-8")
# Clean up temp files
Path(temp_path).unlink(missing_ok=True)
if resized_path != temp_path:
Path(resized_path).unlink(missing_ok=True)
return {
"mode": "inline",
"base64_data": base64_data,
"mime_type": "image/png",
"width": width,
"height": height,
"size_preset": size,
}
# File mode: save to output path with semantic naming
if output_path is None:
output_path = generate_screenshot_name(app_name, screen_name, state)
# Resize if needed
if size != "full" and HAS_PIL:
final_path, width, height = resize_screenshot(temp_path, output_path, size)
else:
# Just move temp to output
import shutil
shutil.move(temp_path, output_path)
final_path = output_path
# Get dimensions via PIL if available
if HAS_PIL:
img = Image.open(final_path)
width, height = img.size
else:
width, height = 390, 844 # Fallback
# Get file size
size_bytes = Path(final_path).stat().st_size
return {
"mode": "file",
"file_path": final_path,
"size_bytes": size_bytes,
"width": width,
"height": height,
"size_preset": size,
}
except subprocess.CalledProcessError as e:
raise RuntimeError(f"Failed to capture screenshot: {e.stderr}") from e
except Exception as e:
raise RuntimeError(f"Screenshot capture error: {e!s}") from e
def format_screenshot_result(result: dict[str, Any]) -> str:
"""Format screenshot result for human-readable output.
Args:
result: Result dictionary from capture_screenshot()
Returns:
Formatted string for printing
Example:
result = capture_screenshot('ABC123', inline=True)
print(format_screenshot_result(result))
"""
if result["mode"] == "file":
return (
f"Screenshot: {result['file_path']}\n"
f"Dimensions: {result['width']}x{result['height']}\n"
f"Size: {result['size_bytes']} bytes"
)
return (
f"Screenshot (inline): {result['width']}x{result['height']}\n"
f"Base64 length: {len(result['base64_data'])} chars"
)
#!/usr/bin/env python3
"""
iOS Gesture Controller - Swipes and Complex Gestures
Performs navigation gestures like swipes, scrolls, and pinches.
Token-efficient output for common navigation patterns.
This script handles touch gestures for iOS simulator automation. It provides
directional swipes, multi-swipe scrolling, pull-to-refresh, and pinch gestures.
Automatically detects screen size from the device for accurate gesture positioning.
Key Features:
- Directional swipes (up, down, left, right)
- Multi-swipe scrolling with customizable amount
- Pull-to-refresh gesture
- Pinch to zoom (in/out)
- Custom swipe between any two points
- Drag and drop simulation
- Auto-detects screen dimensions from device
Usage Examples:
# Simple directional swipe
python scripts/gesture.py --swipe up --udid <device-id>
# Scroll down multiple times
python scripts/gesture.py --scroll down --scroll-amount 3 --udid <device-id>
# Pull to refresh
python scripts/gesture.py --refresh --udid <device-id>
# Custom swipe coordinates
python scripts/gesture.py --swipe-from 100,500 --swipe-to 100,100 --udid <device-id>
# Pinch to zoom
python scripts/gesture.py --pinch out --udid <device-id>
# Long press at coordinates
python scripts/gesture.py --long-press 200,300 --duration 2.0 --udid <device-id>
Output Format:
Swiped up
Scrolled down (3x)
Performed pull to refresh
Gesture Details:
- Swipes use 70% of screen by default (configurable)
- Scrolls are multiple small 30% swipes with delays
- Start points are offset from edges for reliability
- Screen size auto-detected from accessibility tree root element
- Falls back to iPhone 14 dimensions (390x844) if detection fails
Technical Details:
- Uses `idb ui swipe x1 y1 x2 y2` for gesture execution
- Duration parameter converts to milliseconds for IDB
- Automatically fetches screen size on initialization
- Parses IDB accessibility tree to get root frame dimensions
- All coordinates calculated as fractions of screen size for device independence
"""
import argparse
import subprocess
import sys
import time
from common import (
get_device_screen_size,
get_screen_size,
resolve_udid,
transform_screenshot_coords,
)
class GestureController:
"""Performs gestures on iOS simulator."""
# Standard screen dimensions (will be detected if possible)
DEFAULT_WIDTH = 390 # iPhone 14
DEFAULT_HEIGHT = 844
def __init__(self, udid: str | None = None):
"""Initialize gesture controller."""
self.udid = udid
self.screen_size = self._get_screen_size()
def _get_screen_size(self) -> tuple[int, int]:
"""Try to detect screen size from device using shared utility."""
return get_screen_size(self.udid)
def swipe(self, direction: str, distance_ratio: float = 0.7) -> bool:
"""
Perform directional swipe.
Args:
direction: up, down, left, right
distance_ratio: How far to swipe (0.0-1.0 of screen)
Returns:
Success status
"""
width, height = self.screen_size
center_x = width // 2
center_y = height // 2
# Calculate swipe coordinates based on direction
if direction == "up":
start = (center_x, int(height * 0.7))
end = (center_x, int(height * (1 - distance_ratio + 0.3)))
elif direction == "down":
start = (center_x, int(height * 0.3))
end = (center_x, int(height * (distance_ratio - 0.3 + 0.3)))
elif direction == "left":
start = (int(width * 0.8), center_y)
end = (int(width * (1 - distance_ratio + 0.2)), center_y)
elif direction == "right":
start = (int(width * 0.2), center_y)
end = (int(width * (distance_ratio - 0.2 + 0.2)), center_y)
else:
return False
return self.swipe_between(start, end)
def swipe_between(
self, start: tuple[int, int], end: tuple[int, int], duration: float = 0.3
) -> bool:
"""
Swipe between two points.
Args:
start: Starting coordinates (x, y)
end: Ending coordinates (x, y)
duration: Swipe duration in seconds
Returns:
Success status
"""
cmd = ["idb", "ui", "swipe"]
cmd.extend([str(start[0]), str(start[1]), str(end[0]), str(end[1])])
# IDB doesn't support duration directly, but we can add delay
if duration != 0.3:
cmd.extend(["--duration", str(int(duration * 1000))])
if self.udid:
cmd.extend(["--udid", self.udid])
try:
subprocess.run(cmd, capture_output=True, check=True)
return True
except subprocess.CalledProcessError:
return False
def scroll(self, direction: str, amount: int = 3) -> bool:
"""
Perform multiple small swipes to scroll.
Args:
direction: up, down
amount: Number of small swipes
Returns:
Success status
"""
for _ in range(amount):
if not self.swipe(direction, distance_ratio=0.3):
return False
time.sleep(0.2) # Small delay between swipes
return True
def tap_and_hold(self, x: int, y: int, duration: float = 2.0) -> bool:
"""
Long press at coordinates.
Args:
x, y: Coordinates
duration: Hold duration in seconds
Returns:
Success status
"""
# IDB doesn't have native long press, simulate with tap
# In real implementation, might need to use different approach
cmd = ["idb", "ui", "tap", str(x), str(y)]
if self.udid:
cmd.extend(["--udid", self.udid])
try:
subprocess.run(cmd, capture_output=True, check=True)
# Simulate hold with delay
time.sleep(duration)
return True
except subprocess.CalledProcessError:
return False
def pinch(self, direction: str = "out", center: tuple[int, int] | None = None) -> bool:
"""
Perform pinch gesture (zoom in/out).
Args:
direction: 'in' (zoom out) or 'out' (zoom in)
center: Center point for pinch
Returns:
Success status
"""
if not center:
width, height = self.screen_size
center = (width // 2, height // 2)
# Calculate pinch points
offset = 100 if direction == "out" else 50
if direction == "out":
# Zoom in - fingers move apart
start1 = (center[0] - 20, center[1] - 20)
end1 = (center[0] - offset, center[1] - offset)
start2 = (center[0] + 20, center[1] + 20)
end2 = (center[0] + offset, center[1] + offset)
else:
# Zoom out - fingers move together
start1 = (center[0] - offset, center[1] - offset)
end1 = (center[0] - 20, center[1] - 20)
start2 = (center[0] + offset, center[1] + offset)
end2 = (center[0] + 20, center[1] + 20)
# Perform two swipes simultaneously (simulated)
success1 = self.swipe_between(start1, end1)
success2 = self.swipe_between(start2, end2)
return success1 and success2
def drag_and_drop(self, start: tuple[int, int], end: tuple[int, int]) -> bool:
"""
Drag element from one position to another.
Args:
start: Starting coordinates
end: Ending coordinates
Returns:
Success status
"""
# Use slow swipe to simulate drag
return self.swipe_between(start, end, duration=1.0)
def refresh(self) -> bool:
"""Pull to refresh gesture."""
width, _ = self.screen_size
start = (width // 2, 100)
end = (width // 2, 400)
return self.swipe_between(start, end)
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(description="Perform gestures on iOS simulator")
# Gesture options
parser.add_argument(
"--swipe", choices=["up", "down", "left", "right"], help="Perform directional swipe"
)
parser.add_argument("--swipe-from", help="Custom swipe start coordinates (x,y)")
parser.add_argument("--swipe-to", help="Custom swipe end coordinates (x,y)")
parser.add_argument(
"--scroll", choices=["up", "down"], help="Scroll in direction (multiple small swipes)"
)
parser.add_argument(
"--scroll-amount", type=int, default=3, help="Number of scroll swipes (default: 3)"
)
parser.add_argument("--long-press", help="Long press at coordinates (x,y)")
parser.add_argument(
"--duration", type=float, default=2.0, help="Duration for long press in seconds"
)
parser.add_argument(
"--pinch", choices=["in", "out"], help="Pinch gesture (in=zoom out, out=zoom in)"
)
parser.add_argument("--refresh", action="store_true", help="Pull to refresh gesture")
# Coordinate transformation
parser.add_argument(
"--screenshot-coords",
action="store_true",
help="Interpret swipe coordinates as from a screenshot (requires --screenshot-width/height)",
)
parser.add_argument(
"--screenshot-width",
type=int,
help="Screenshot width for coordinate transformation",
)
parser.add_argument(
"--screenshot-height",
type=int,
help="Screenshot height for coordinate transformation",
)
parser.add_argument(
"--udid",
help="Device UDID (auto-detects booted simulator if not provided)",
)
args = parser.parse_args()
# Resolve UDID with auto-detection
try:
udid = resolve_udid(args.udid)
except RuntimeError as e:
print(f"Error: {e}")
sys.exit(1)
controller = GestureController(udid=udid)
# Execute requested gesture
if args.swipe:
if controller.swipe(args.swipe):
print(f"Swiped {args.swipe}")
else:
print(f"Failed to swipe {args.swipe}")
sys.exit(1)
elif args.swipe_from and args.swipe_to:
# Custom swipe
start = tuple(map(int, args.swipe_from.split(",")))
end = tuple(map(int, args.swipe_to.split(",")))
# Handle coordinate transformation if requested
if args.screenshot_coords:
if not args.screenshot_width or not args.screenshot_height:
print(
"Error: --screenshot-coords requires --screenshot-width and --screenshot-height"
)
sys.exit(1)
device_w, device_h = get_device_screen_size(udid)
start = transform_screenshot_coords(
start[0],
start[1],
args.screenshot_width,
args.screenshot_height,
device_w,
device_h,
)
end = transform_screenshot_coords(
end[0],
end[1],
args.screenshot_width,
args.screenshot_height,
device_w,
device_h,
)
print("Transformed screenshot coords to device coords")
if controller.swipe_between(start, end):
print(f"Swiped from {start} to {end}")
else:
print("Failed to swipe")
sys.exit(1)
elif args.scroll:
if controller.scroll(args.scroll, args.scroll_amount):
print(f"Scrolled {args.scroll} ({args.scroll_amount}x)")
else:
print(f"Failed to scroll {args.scroll}")
sys.exit(1)
elif args.long_press:
coords = tuple(map(int, args.long_press.split(",")))
if controller.tap_and_hold(coords[0], coords[1], args.duration):
print(f"Long pressed at {coords} for {args.duration}s")
else:
print("Failed to long press")
sys.exit(1)
elif args.pinch:
if controller.pinch(args.pinch):
action = "Zoomed in" if args.pinch == "out" else "Zoomed out"
print(action)
else:
print(f"Failed to pinch {args.pinch}")
sys.exit(1)
elif args.refresh:
if controller.refresh():
print("Performed pull to refresh")
else:
print("Failed to refresh")
sys.exit(1)
else:
parser.print_help()
sys.exit(1)
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""
iOS Keyboard Controller - Text Entry and Hardware Buttons
Handles keyboard input, special keys, and hardware button simulation.
Token-efficient text entry and navigation control.
This script provides text input and hardware button control for iOS simulator
automation. It handles both typing text strings and pressing special keys like
return, delete, tab, etc. Also controls hardware buttons like home and lock.
Key Features:
- Type text strings into focused elements
- Press special keys (return, delete, tab, space, arrows)
- Hardware button simulation (home, lock, volume, screenshot)
- Character-by-character typing with delays (for animations)
- Multiple key press support
- iOS HID key code mapping for reliability
Usage Examples:
# Type text into focused field
python scripts/keyboard.py --type "hello@example.com" --udid <device-id>
# Press return key to submit
python scripts/keyboard.py --key return --udid <device-id>
# Press delete 3 times
python scripts/keyboard.py --key delete --key delete --key delete --udid <device-id>
# Press home button
python scripts/keyboard.py --button home --udid <device-id>
# Press lock button
python scripts/keyboard.py --button lock --udid <device-id>
# Type with delay between characters (for animations)
python scripts/keyboard.py --type "slow typing" --delay 0.1 --udid <device-id>
Output Format:
Typed: "hello@example.com"
Pressed return
Pressed home button
Special Keys Supported:
- return/enter: Submit forms, new lines (HID code 40)
- delete/backspace: Remove characters (HID code 42)
- tab: Navigate between fields (HID code 43)
- space: Space character (HID code 44)
- escape: Cancel/dismiss (HID code 41)
- up/down/left/right: Arrow keys (HID codes 82/81/80/79)
Hardware Buttons Supported:
- home: Return to home screen
- lock/power: Lock device
- volume-up/volume-down: Volume control
- ringer: Toggle mute
- screenshot: Capture screen
Technical Details:
- Uses `idb ui text` for typing text strings
- Uses `idb ui key <code>` for special keys with iOS HID codes
- HID codes from Apple's UIKeyboardHIDUsage specification
- Hardware buttons use `xcrun simctl` button actions
- Text entry works on currently focused element
- Special keys are integers (40=Return, 42=Delete, etc.)
"""
import argparse
import subprocess
import sys
import time
from common import resolve_udid
class KeyboardController:
"""Controls keyboard and hardware buttons on iOS simulator."""
# Special key mappings to iOS HID key codes
# See: https://developer.apple.com/documentation/uikit/uikeyboardhidusage
SPECIAL_KEYS = {
"return": 40,
"enter": 40,
"delete": 42,
"backspace": 42,
"tab": 43,
"space": 44,
"escape": 41,
"up": 82,
"down": 81,
"left": 80,
"right": 79,
}
# Hardware button mappings
HARDWARE_BUTTONS = {
"home": "HOME",
"lock": "LOCK",
"volume-up": "VOLUME_UP",
"volume-down": "VOLUME_DOWN",
"ringer": "RINGER",
"power": "LOCK", # Alias
"screenshot": "SCREENSHOT",
}
def __init__(self, udid: str | None = None):
"""Initialize keyboard controller."""
self.udid = udid
def type_text(self, text: str, delay: float = 0.0) -> bool:
"""
Type text into current focus.
Args:
text: Text to type
delay: Delay between characters (for slow typing effect)
Returns:
Success status
"""
if delay > 0:
# Type character by character with delay
for char in text:
if not self._type_single(char):
return False
time.sleep(delay)
return True
# Type all at once (efficient)
return self._type_single(text)
def _type_single(self, text: str) -> bool:
"""Type text using IDB."""
cmd = ["idb", "ui", "text", text]
if self.udid:
cmd.extend(["--udid", self.udid])
try:
subprocess.run(cmd, capture_output=True, check=True)
return True
except subprocess.CalledProcessError:
return False
def press_key(self, key: str, count: int = 1) -> bool:
"""
Press a special key.
Args:
key: Key name (return, delete, tab, etc.)
count: Number of times to press
Returns:
Success status
"""
# Map key name to IDB key code
key_code = self.SPECIAL_KEYS.get(key.lower())
if not key_code:
# Try as literal integer key code
try:
key_code = int(key)
except ValueError:
return False
cmd = ["idb", "ui", "key", str(key_code)]
if self.udid:
cmd.extend(["--udid", self.udid])
try:
for _ in range(count):
subprocess.run(cmd, capture_output=True, check=True)
if count > 1:
time.sleep(0.1) # Small delay for multiple presses
return True
except subprocess.CalledProcessError:
return False
def press_key_sequence(self, keys: list[str]) -> bool:
"""
Press a sequence of keys.
Args:
keys: List of key names
Returns:
Success status
"""
cmd_base = ["idb", "ui", "key-sequence"]
# Map keys to codes
mapped_keys = []
for key in keys:
mapped = self.SPECIAL_KEYS.get(key.lower())
if mapped is None:
# Try as integer
try:
mapped = int(key)
except ValueError:
return False
mapped_keys.append(str(mapped))
cmd = cmd_base + mapped_keys
if self.udid:
cmd.extend(["--udid", self.udid])
try:
subprocess.run(cmd, capture_output=True, check=True)
return True
except subprocess.CalledProcessError:
return False
def press_hardware_button(self, button: str) -> bool:
"""
Press hardware button.
Args:
button: Button name (home, lock, volume-up, etc.)
Returns:
Success status
"""
button_code = self.HARDWARE_BUTTONS.get(button.lower())
if not button_code:
return False
cmd = ["idb", "ui", "button", button_code]
if self.udid:
cmd.extend(["--udid", self.udid])
try:
subprocess.run(cmd, capture_output=True, check=True)
return True
except subprocess.CalledProcessError:
return False
def clear_text(self, select_all: bool = True) -> bool:
"""
Clear text in current field.
Args:
select_all: Use Cmd+A to select all first
Returns:
Success status
"""
if select_all:
# Select all then delete
# Note: This might need adjustment for iOS keyboard shortcuts
success = self.press_key_combo(["cmd", "a"])
if success:
return self.press_key("delete")
else:
# Just delete multiple times
return self.press_key("delete", count=50)
return None
def press_key_combo(self, keys: list[str]) -> bool:
"""
Press key combination (like Cmd+A).
Args:
keys: List of keys to press together
Returns:
Success status
"""
# IDB doesn't directly support key combos
# This is a workaround - may need platform-specific handling
if "cmd" in keys or "command" in keys:
# Handle common shortcuts
if "a" in keys:
# Select all - might work with key sequence
return self.press_key_sequence(["command", "a"])
if "c" in keys:
return self.press_key_sequence(["command", "c"])
if "v" in keys:
return self.press_key_sequence(["command", "v"])
if "x" in keys:
return self.press_key_sequence(["command", "x"])
# Try as sequence
return self.press_key_sequence(keys)
def dismiss_keyboard(self) -> bool:
"""Dismiss on-screen keyboard."""
# Common ways to dismiss keyboard on iOS
# Try Done button first, then Return
success = self.press_key("return")
if not success:
# Try tapping outside (would need coordinate)
pass
return success
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(description="Control keyboard and hardware buttons")
# Text input
parser.add_argument("--type", help="Type text into current focus")
parser.add_argument("--slow", action="store_true", help="Type slowly (character by character)")
# Special keys
parser.add_argument("--key", help="Press special key (return, delete, tab, space, etc.)")
parser.add_argument("--key-sequence", help="Press key sequence (comma-separated)")
parser.add_argument("--count", type=int, default=1, help="Number of times to press key")
# Hardware buttons
parser.add_argument(
"--button",
choices=["home", "lock", "volume-up", "volume-down", "ringer", "screenshot"],
help="Press hardware button",
)
# Other operations
parser.add_argument("--clear", action="store_true", help="Clear current text field")
parser.add_argument("--dismiss", action="store_true", help="Dismiss keyboard")
parser.add_argument(
"--udid",
help="Device UDID (auto-detects booted simulator if not provided)",
)
args = parser.parse_args()
# Resolve UDID with auto-detection
try:
udid = resolve_udid(args.udid)
except RuntimeError as e:
print(f"Error: {e}")
sys.exit(1)
controller = KeyboardController(udid=udid)
# Execute requested action
if args.type:
delay = 0.1 if args.slow else 0.0
if controller.type_text(args.type, delay):
if args.slow:
print(f'Typed: "{args.type}" (slowly)')
else:
print(f'Typed: "{args.type}"')
else:
print("Failed to type text")
sys.exit(1)
elif args.key:
if controller.press_key(args.key, args.count):
if args.count > 1:
print(f"Pressed {args.key} ({args.count}x)")
else:
print(f"Pressed {args.key}")
else:
print(f"Failed to press {args.key}")
sys.exit(1)
elif args.key_sequence:
keys = args.key_sequence.split(",")
if controller.press_key_sequence(keys):
print(f"Pressed sequence: {' -> '.join(keys)}")
else:
print("Failed to press key sequence")
sys.exit(1)
elif args.button:
if controller.press_hardware_button(args.button):
print(f"Pressed {args.button} button")
else:
print(f"Failed to press {args.button}")
sys.exit(1)
elif args.clear:
if controller.clear_text():
print("Cleared text field")
else:
print("Failed to clear text")
sys.exit(1)
elif args.dismiss:
if controller.dismiss_keyboard():
print("Dismissed keyboard")
else:
print("Failed to dismiss keyboard")
sys.exit(1)
else:
parser.print_help()
sys.exit(1)
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""
iOS Privacy & Permissions Manager
Grant/revoke app permissions for testing permission flows.
Supports 13+ services with audit trail tracking.
Usage: python scripts/privacy_manager.py --grant camera --bundle-id com.app
"""
import argparse
import subprocess
import sys
from datetime import datetime
from common import resolve_udid
class PrivacyManager:
"""Manages iOS app privacy and permissions."""
# Supported services
SUPPORTED_SERVICES = {
"camera": "Camera access",
"microphone": "Microphone access",
"location": "Location services",
"contacts": "Contacts access",
"photos": "Photos library access",
"calendar": "Calendar access",
"health": "Health data access",
"reminders": "Reminders access",
"motion": "Motion & fitness",
"keyboard": "Keyboard access",
"mediaLibrary": "Media library",
"calls": "Call history",
"siri": "Siri access",
}
def __init__(self, udid: str | None = None):
"""Initialize privacy manager.
Args:
udid: Optional device UDID (auto-detects booted simulator if None)
"""
self.udid = udid
def grant_permission(
self,
bundle_id: str,
service: str,
scenario: str | None = None,
step: int | None = None,
) -> bool:
"""
Grant permission for app.
Args:
bundle_id: App bundle ID
service: Service name (camera, microphone, location, etc.)
scenario: Test scenario name for audit trail
step: Step number in test scenario
Returns:
Success status
"""
if service not in self.SUPPORTED_SERVICES:
print(f"Error: Unknown service '{service}'")
print(f"Supported: {', '.join(self.SUPPORTED_SERVICES.keys())}")
return False
cmd = ["xcrun", "simctl", "privacy"]
if self.udid:
cmd.append(self.udid)
else:
cmd.append("booted")
cmd.extend(["grant", service, bundle_id])
try:
subprocess.run(cmd, capture_output=True, check=True)
# Log audit entry
self._log_audit("grant", bundle_id, service, scenario, step)
return True
except subprocess.CalledProcessError:
return False
def revoke_permission(
self,
bundle_id: str,
service: str,
scenario: str | None = None,
step: int | None = None,
) -> bool:
"""
Revoke permission for app.
Args:
bundle_id: App bundle ID
service: Service name
scenario: Test scenario name for audit trail
step: Step number in test scenario
Returns:
Success status
"""
if service not in self.SUPPORTED_SERVICES:
print(f"Error: Unknown service '{service}'")
return False
cmd = ["xcrun", "simctl", "privacy"]
if self.udid:
cmd.append(self.udid)
else:
cmd.append("booted")
cmd.extend(["revoke", service, bundle_id])
try:
subprocess.run(cmd, capture_output=True, check=True)
# Log audit entry
self._log_audit("revoke", bundle_id, service, scenario, step)
return True
except subprocess.CalledProcessError:
return False
def reset_permission(
self,
bundle_id: str,
service: str,
scenario: str | None = None,
step: int | None = None,
) -> bool:
"""
Reset permission to default.
Args:
bundle_id: App bundle ID
service: Service name
scenario: Test scenario name for audit trail
step: Step number in test scenario
Returns:
Success status
"""
if service not in self.SUPPORTED_SERVICES:
print(f"Error: Unknown service '{service}'")
return False
cmd = ["xcrun", "simctl", "privacy"]
if self.udid:
cmd.append(self.udid)
else:
cmd.append("booted")
cmd.extend(["reset", service, bundle_id])
try:
subprocess.run(cmd, capture_output=True, check=True)
# Log audit entry
self._log_audit("reset", bundle_id, service, scenario, step)
return True
except subprocess.CalledProcessError:
return False
@staticmethod
def _log_audit(
action: str,
bundle_id: str,
service: str,
scenario: str | None = None,
step: int | None = None,
) -> None:
"""Log permission change to audit trail (for test tracking).
Args:
action: grant, revoke, or reset
bundle_id: App bundle ID
service: Service name
scenario: Test scenario name
step: Step number
"""
# Could write to file, but for now just log to stdout for transparency
timestamp = datetime.now().isoformat()
location = f" (step {step})" if step else ""
scenario_info = f" in {scenario}" if scenario else ""
print(
f"[Audit] {timestamp}: {action.upper()} {service} for {bundle_id}{scenario_info}{location}"
)
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(description="Manage iOS app privacy and permissions")
# Required
parser.add_argument("--bundle-id", required=True, help="App bundle ID (e.g., com.example.app)")
# Action (mutually exclusive)
action_group = parser.add_mutually_exclusive_group(required=True)
action_group.add_argument(
"--grant",
help="Grant permission (service name or comma-separated list)",
)
action_group.add_argument(
"--revoke", help="Revoke permission (service name or comma-separated list)"
)
action_group.add_argument(
"--reset",
help="Reset permission to default (service name or comma-separated list)",
)
action_group.add_argument(
"--list",
action="store_true",
help="List all supported services",
)
# Test tracking
parser.add_argument(
"--scenario",
help="Test scenario name for audit trail",
)
parser.add_argument("--step", type=int, help="Step number in test scenario")
# Device
parser.add_argument(
"--udid",
help="Device UDID (auto-detects booted simulator if not provided)",
)
args = parser.parse_args()
# List supported services
if args.list:
print("Supported Privacy Services:\n")
for service, description in PrivacyManager.SUPPORTED_SERVICES.items():
print(f" {service:<15} - {description}")
print()
print("Examples:")
print(" python scripts/privacy_manager.py --grant camera --bundle-id com.app")
print(" python scripts/privacy_manager.py --revoke location --bundle-id com.app")
print(" python scripts/privacy_manager.py --grant camera,photos --bundle-id com.app")
sys.exit(0)
# Resolve UDID with auto-detection
try:
udid = resolve_udid(args.udid)
except RuntimeError as e:
print(f"Error: {e}")
sys.exit(1)
manager = PrivacyManager(udid=udid)
# Parse service names (support comma-separated list)
if args.grant:
services = [s.strip() for s in args.grant.split(",")]
action = "grant"
action_fn = manager.grant_permission
elif args.revoke:
services = [s.strip() for s in args.revoke.split(",")]
action = "revoke"
action_fn = manager.revoke_permission
else: # reset
services = [s.strip() for s in args.reset.split(",")]
action = "reset"
action_fn = manager.reset_permission
# Execute action for each service
all_success = True
for service in services:
if service not in PrivacyManager.SUPPORTED_SERVICES:
print(f"Error: Unknown service '{service}'")
all_success = False
continue
success = action_fn(
args.bundle_id,
service,
scenario=args.scenario,
step=args.step,
)
if success:
description = PrivacyManager.SUPPORTED_SERVICES[service]
print(f"✓ {action.capitalize()} {service}: {description}")
else:
print(f"✗ Failed to {action} {service}")
all_success = False
if not all_success:
sys.exit(1)
# Summary
if len(services) > 1:
print(f"\nPermissions {action}ed: {', '.join(services)}")
if args.scenario:
print(f"Test scenario: {args.scenario}" + (f" (step {args.step})" if args.step else ""))
if __name__ == "__main__":
main()
"""
Xcode build automation module.
Provides structured, modular access to xcodebuild and xcresult functionality.
"""
from .builder import BuildRunner
from .cache import XCResultCache
from .config import Config
from .reporter import OutputFormatter
from .xcresult import XCResultParser
__all__ = ["BuildRunner", "Config", "OutputFormatter", "XCResultCache", "XCResultParser"]