use std::fmt::{Display, Formatter};
use std::path::PathBuf;
use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
const PROVIDER: &str = "apple_device";
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Platform {
#[default]
Auto,
Ios,
Tvos,
Watchos,
Visionos,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct DeviceTarget {
pub kind: String,
pub platform: String,
pub booted: bool,
pub identifier: String,
#[serde(default)]
pub udid: Option<String>,
pub name: String,
#[serde(default)]
pub runtime: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct AppRecord {
pub bundle_id: String,
pub name: String,
pub url: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, incurs::Options)]
pub struct AttachRequest {
pub bundle_id: String,
#[serde(default)]
pub platform: Platform,
#[serde(default)]
pub device: Option<String>,
#[serde(default)]
pub pid: Option<u32>,
#[serde(default)]
pub launch: bool,
#[serde(default = "default_attach_strategy")]
pub attach_strategy: String,
#[serde(default = "default_attach_timeout_ms")]
pub attach_timeout_ms: u64,
}
fn default_attach_strategy() -> String {
"auto".to_string()
}
fn default_attach_timeout_ms() -> u64 {
45_000
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct AttachResolution {
pub provider: String,
pub platform: String,
pub device_id: String,
pub bundle_id: String,
pub pid: u32,
pub attach_protocol: String,
pub metadata: Value,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProviderError {
pub code: String,
pub message: String,
#[serde(default)]
pub details: Value,
}
impl ProviderError {
fn new(code: &str, message: impl Into<String>) -> Self {
Self {
code: code.to_string(),
message: message.into(),
details: json!({}),
}
}
fn with_details(mut self, details: Value) -> Self {
self.details = details;
self
}
}
impl Display for ProviderError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
write!(formatter, "{}: {}", self.code, self.message)
}
}
impl std::error::Error for ProviderError {}
pub trait AppleCommandRunner: Send + Sync {
fn xcrun(&self, args: &[String]) -> Result<String, String>;
fn devicectl(&self, args: &[String]) -> Result<Value, String>;
fn system_log(&self, args: &[String]) -> Result<String, String>;
}
#[derive(Debug, Clone, Default)]
pub struct SystemRunner;
impl AppleCommandRunner for SystemRunner {
fn xcrun(&self, args: &[String]) -> Result<String, String> {
run_output(&xcrun_binary(), args)
}
fn devicectl(&self, args: &[String]) -> Result<Value, String> {
static NEXT_FILE: AtomicU64 = AtomicU64::new(1);
let path = std::env::temp_dir().join(format!(
"apoc-devicectl-{}-{}.json",
std::process::id(),
NEXT_FILE.fetch_add(1, Ordering::Relaxed)
));
let mut command_args = vec!["devicectl".to_string()];
command_args.extend_from_slice(args);
command_args.push("--json-output".to_string());
command_args.push(path.to_string_lossy().into_owned());
let result = run_output(&xcrun_binary(), &command_args);
if let Err(error) = result {
let _ = std::fs::remove_file(&path);
return Err(error);
}
let text = std::fs::read_to_string(&path)
.map_err(|error| format!("devicectl did not produce JSON output: {error}"));
let _ = std::fs::remove_file(&path);
let value = serde_json::from_str::<Value>(&text?)
.map_err(|error| format!("devicectl produced invalid JSON output: {error}"))?;
let outcome = value.pointer("/info/outcome").and_then(Value::as_str);
if outcome != Some("success") {
return Err(format!(
"devicectl returned outcome '{}'",
outcome.unwrap_or("unknown")
));
}
value
.get("result")
.cloned()
.ok_or_else(|| "devicectl returned no result payload".to_string())
}
fn system_log(&self, args: &[String]) -> Result<String, String> {
let executable = std::env::var("LOG_PATH").unwrap_or_else(|_| "log".to_string());
run_output(&executable, args)
}
}
fn xcrun_binary() -> String {
std::env::var("XCRUN_PATH").unwrap_or_else(|_| "xcrun".to_string())
}
fn run_output(executable: &str, args: &[String]) -> Result<String, String> {
let output = Command::new(executable)
.args(args)
.output()
.map_err(|error| format!("could not run {executable}: {error}"))?;
if !output.status.success() {
let detail = collapse_whitespace(&String::from_utf8_lossy(&output.stderr));
return Err(format!(
"{executable} {} failed: {}",
args.join(" "),
if detail.is_empty() {
format!("exit status {}", output.status)
} else {
detail
}
));
}
String::from_utf8(output.stdout).map_err(|error| error.to_string())
}
pub struct AppleDeviceService<R> {
runner: R,
}
impl<R: AppleCommandRunner> AppleDeviceService<R> {
pub fn new(runner: R) -> Self {
Self { runner }
}
pub fn devices(&self, platform: Platform) -> Result<Vec<DeviceTarget>, ProviderError> {
self.assert_host()?;
let mut candidates = Vec::new();
if let Ok(devices) = self.physical_devices(&platform) {
candidates.extend(devices);
}
if let Ok(simulators) = self.simulator_devices(&platform) {
candidates.extend(simulators);
}
sort_targets(&mut candidates);
Ok(candidates)
}
pub fn apps(&self, device_id: &str) -> Result<Vec<AppRecord>, ProviderError> {
self.assert_host()?;
if device_id.trim().is_empty() {
return Err(ProviderError::new(
"invalid_request",
"device_id is required",
));
}
let value = self
.runner
.devicectl(&strings(&["device", "info", "apps", "--device", device_id]))
.map_err(provider_failure)?;
Ok(value
.get("apps")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(parse_app)
.collect())
}
pub fn resolve(&self, request: AttachRequest) -> Result<AttachResolution, ProviderError> {
self.assert_host()?;
if request.bundle_id.trim().is_empty() {
return Err(ProviderError::new(
"invalid_request",
"bundle_id is required",
));
}
if !matches!(
request.attach_strategy.as_str(),
"auto" | "device-process" | "gdb-remote"
) {
return Err(ProviderError::new(
"invalid_request",
"attach_strategy must be auto, device-process, or gdb-remote",
));
}
let mut candidates = self.devices(request.platform.clone())?;
if let Some(selector) = request.device.as_deref() {
candidates = select_targets(candidates, selector)?;
} else {
let booted = candidates
.iter()
.filter(|candidate| candidate.booted)
.cloned()
.collect::<Vec<_>>();
if !booted.is_empty() {
candidates = booted;
}
if mixed_kinds(&candidates) {
return Err(ProviderError::new(
"ambiguous_device_selection",
"multiple booted Apple targets found across simulator and physical device; specify device",
)
.with_details(json!({"available_devices":candidates})));
}
}
if candidates.is_empty() {
return Err(ProviderError::new(
"device_not_found",
"no Apple devices or simulators found",
));
}
let mut errors = Vec::new();
for candidate in candidates {
let result = if candidate.kind == "device" {
self.resolve_physical(&candidate, &request)
} else {
self.resolve_simulator(&candidate, &request)
};
match result {
Ok(resolution) => return Ok(resolution),
Err(error) => errors.push(error),
}
}
for code in ["process_not_running", "app_not_installed"] {
if let Some(error) = errors.iter().find(|error| error.code == code) {
return Err(error.clone());
}
}
Err(errors.into_iter().next().unwrap_or_else(|| {
ProviderError::new("provider_error", "failed to resolve attach target")
}))
}
pub fn debug_proxy(&self, device_id: &str) -> Result<u16, ProviderError> {
self.assert_host()?;
let device_id = device_id.trim();
if device_id.is_empty() {
return Err(ProviderError::new(
"invalid_request",
"device_id is required",
));
}
let predicate_id = device_id.replace('"', "\\\"");
let logs = self
.runner
.system_log(&strings(&[
"show",
"--style",
"compact",
"--last",
"15m",
"--predicate",
&format!(
"eventMessage CONTAINS[c] \"debugproxy\" AND eventMessage CONTAINS[c] \"{predicate_id}\""
),
]))
.map_err(provider_failure)?;
parse_debug_proxy_port(&logs).ok_or_else(|| {
ProviderError::new(
"provider_error",
format!("unable to discover CoreDevice debugproxy port for device {device_id}"),
)
})
}
fn assert_host(&self) -> Result<(), ProviderError> {
if !cfg!(target_os = "macos") && std::env::var_os("XCRUN_PATH").is_none() {
return Err(ProviderError::new(
"invalid_request",
"apple-device provider requires macOS",
));
}
self.runner
.xcrun(&strings(&["--version"]))
.map(|_| ())
.map_err(|error| {
ProviderError::new(
"invalid_request",
"apple-device provider requires Xcode command line tools (xcrun)",
)
.with_details(json!({"error":error}))
})
}
fn physical_devices(&self, platform: &Platform) -> Result<Vec<DeviceTarget>, ProviderError> {
let value = self
.runner
.devicectl(&strings(&["list", "devices"]))
.map_err(provider_failure)?;
Ok(value
.get("devices")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|device| {
let resolved = platform_from_label(
device
.pointer("/hardwareProperties/platform")
.and_then(Value::as_str)?,
)?;
if !platform_matches(platform, &resolved) {
return None;
}
let identifier = device.get("identifier")?.as_str()?.to_string();
Some(DeviceTarget {
kind: "device".to_string(),
platform: resolved,
booted: device
.pointer("/deviceProperties/bootState")
.and_then(Value::as_str)
.is_some_and(|state| state.eq_ignore_ascii_case("booted")),
identifier: identifier.clone(),
udid: device
.pointer("/hardwareProperties/udid")
.and_then(Value::as_str)
.map(ToString::to_string),
name: device
.pointer("/deviceProperties/name")
.and_then(Value::as_str)
.unwrap_or(&identifier)
.to_string(),
runtime: None,
})
})
.collect())
}
fn simulator_devices(&self, platform: &Platform) -> Result<Vec<DeviceTarget>, ProviderError> {
let output = self
.runner
.xcrun(&strings(&["simctl", "list", "devices", "--json"]))
.map_err(provider_failure)?;
let value = serde_json::from_str::<Value>(&output)
.map_err(|error| ProviderError::new("provider_error", error.to_string()))?;
let mut devices = Vec::new();
for (runtime, entries) in value
.get("devices")
.and_then(Value::as_object)
.into_iter()
.flatten()
{
let Some(resolved) = platform_from_runtime(runtime) else {
continue;
};
if !platform_matches(platform, &resolved) {
continue;
}
for entry in entries.as_array().into_iter().flatten() {
if entry.get("isAvailable").and_then(Value::as_bool) == Some(false) {
continue;
}
let Some(identifier) = entry.get("udid").and_then(Value::as_str) else {
continue;
};
devices.push(DeviceTarget {
kind: "simulator".to_string(),
platform: resolved.clone(),
booted: entry
.get("state")
.and_then(Value::as_str)
.is_some_and(|state| state.eq_ignore_ascii_case("booted")),
identifier: identifier.to_string(),
udid: None,
name: entry
.get("name")
.and_then(Value::as_str)
.unwrap_or(identifier)
.to_string(),
runtime: Some(runtime.clone()),
});
}
}
Ok(devices)
}
fn resolve_physical(
&self,
target: &DeviceTarget,
request: &AttachRequest,
) -> Result<AttachResolution, ProviderError> {
let apps = self.apps(&target.identifier)?;
let app = apps
.iter()
.find(|app| app.bundle_id == request.bundle_id)
.ok_or_else(|| {
ProviderError::new(
"app_not_installed",
format!(
"app '{}' is not installed on device {}",
request.bundle_id, target.identifier
),
)
})?;
let mut started_stopped = false;
let (pid, executable, matched_by) = if request.launch && request.pid.is_none() {
let value = self
.runner
.devicectl(&strings(&[
"device",
"process",
"launch",
"--device",
&target.identifier,
"--start-stopped",
"--terminate-existing",
&request.bundle_id,
]))
.map_err(provider_failure)?;
started_stopped = true;
let pid = value
.pointer("/process/processIdentifier")
.and_then(Value::as_u64)
.and_then(|pid| u32::try_from(pid).ok())
.filter(|pid| *pid > 0);
if let Some(pid) = pid {
(
pid,
value
.pointer("/process/executable")
.and_then(Value::as_str)
.unwrap_or("")
.to_string(),
"pid".to_string(),
)
} else {
self.resolve_physical_process(target, app, None)?
}
} else {
self.resolve_physical_process(target, app, request.pid)?
};
Ok(AttachResolution {
provider: PROVIDER.to_string(),
platform: target.platform.clone(),
device_id: target.identifier.clone(),
bundle_id: request.bundle_id.clone(),
pid,
attach_protocol: "dap".to_string(),
metadata: json!({
"attach_environment":"device",
"device_name":target.name,
"app_name":app.name,
"executable":executable,
"matched_by":matched_by,
"started_stopped":started_stopped,
"attach_strategy":request.attach_strategy,
"attach_timeout_ms":request.attach_timeout_ms
}),
})
}
fn resolve_physical_process(
&self,
target: &DeviceTarget,
app: &AppRecord,
override_pid: Option<u32>,
) -> Result<(u32, String, String), ProviderError> {
let value = self
.runner
.devicectl(&strings(&[
"device",
"info",
"processes",
"--device",
&target.identifier,
]))
.map_err(provider_failure)?;
let mut processes = value
.get("runningProcesses")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|process| {
Some((
u32::try_from(process.get("processIdentifier")?.as_u64()?).ok()?,
decode_path(process.get("executable")?.as_str()?),
))
})
.collect::<Vec<_>>();
if let Some(pid) = override_pid {
return processes
.into_iter()
.find(|process| process.0 == pid)
.map(|(pid, executable)| (pid, executable, "pid".to_string()))
.ok_or_else(|| {
ProviderError::new(
"process_not_running",
format!("process pid {pid} is not running on target device"),
)
});
}
processes.sort_by_key(|process| std::cmp::Reverse(process.0));
let app_dir = decode_path(&app.url).trim_end_matches('/').to_string();
if let Some((pid, executable)) = processes
.iter()
.find(|process| process.1.starts_with(&format!("{app_dir}/")))
{
return Ok((*pid, executable.clone(), "app_path".to_string()));
}
let needle = format!("{}.app/", app.name);
processes
.into_iter()
.find(|process| process.1.contains(&needle))
.map(|(pid, executable)| (pid, executable, "app_name".to_string()))
.ok_or_else(|| {
ProviderError::new(
"process_not_running",
format!("no running process found for app '{}'", app.bundle_id),
)
})
}
fn resolve_simulator(
&self,
target: &DeviceTarget,
request: &AttachRequest,
) -> Result<AttachResolution, ProviderError> {
let container = self
.runner
.xcrun(&strings(&[
"simctl",
"get_app_container",
&target.identifier,
&request.bundle_id,
"app",
]))
.map(|value| value.trim().to_string())
.map_err(|_| {
ProviderError::new(
"app_not_installed",
format!(
"app '{}' is not installed on simulator {}",
request.bundle_id, target.identifier
),
)
})?;
let mut matched_by = "bundle_id".to_string();
let mut pid = None;
if request.pid.is_none() && request.launch {
let output = self
.runner
.xcrun(&strings(&[
"simctl",
"launch",
&target.identifier,
&request.bundle_id,
]))
.map_err(provider_failure)?;
pid = parse_launch_pid(&output);
if pid.is_some() {
matched_by = "launch".to_string();
}
}
if pid.is_none() {
let output = self
.runner
.xcrun(&strings(&[
"simctl",
"spawn",
&target.identifier,
"ps",
"-axo",
"pid=,command=",
]))
.map_err(provider_failure)?;
let mut processes = parse_processes(&output);
pid = if let Some(pid) = request.pid {
if processes.iter().any(|process| process.0 == pid) {
matched_by = "pid".to_string();
Some(pid)
} else {
return Err(ProviderError::new(
"process_not_running",
format!("process pid {pid} is not running on target simulator"),
));
}
} else {
processes.sort_by_key(|process| std::cmp::Reverse(process.0));
processes
.iter()
.find(|process| process.1.contains(&request.bundle_id))
.map(|process| process.0)
.or_else(|| {
let container = decode_path(&container);
let result = processes
.iter()
.find(|process| process.1.contains(&container))
.map(|process| process.0);
if result.is_some() {
matched_by = "app_container".to_string();
}
result
})
.or_else(|| {
let app_name = PathBuf::from(decode_path(&container))
.file_stem()
.and_then(|value| value.to_str())
.unwrap_or("")
.to_string();
let result = processes
.iter()
.find(|process| process.1.contains(&format!("{app_name}.app/")))
.map(|process| process.0);
if result.is_some() {
matched_by = "app_name".to_string();
}
result
})
};
}
let pid = pid.ok_or_else(|| {
ProviderError::new(
"process_not_running",
format!(
"no running process found for app '{}' on simulator {}",
request.bundle_id, target.identifier
),
)
})?;
Ok(AttachResolution {
provider: PROVIDER.to_string(),
platform: target.platform.clone(),
device_id: target.identifier.clone(),
bundle_id: request.bundle_id.clone(),
pid,
attach_protocol: "dap".to_string(),
metadata: json!({
"attach_environment":"simulator",
"device_name":target.name,
"app_container":container,
"matched_by":matched_by,
"started_stopped":false,
"attach_strategy":request.attach_strategy,
"attach_timeout_ms":request.attach_timeout_ms
}),
})
}
}
fn provider_failure(error: String) -> ProviderError {
ProviderError::new("provider_error", error)
}
fn strings(values: &[&str]) -> Vec<String> {
values.iter().map(|value| (*value).to_string()).collect()
}
fn parse_app(value: &Value) -> Option<AppRecord> {
Some(AppRecord {
bundle_id: value.get("bundleIdentifier")?.as_str()?.to_string(),
name: value.get("name")?.as_str()?.to_string(),
url: value.get("url")?.as_str()?.to_string(),
})
}
fn platform_from_label(value: &str) -> Option<String> {
let value = value.to_ascii_lowercase();
if value.contains("vision") {
Some("visionos".to_string())
} else if value.contains("watch") {
Some("watchos".to_string())
} else if value.contains("tv") {
Some("tvos".to_string())
} else if value.contains("ios") {
Some("ios".to_string())
} else {
None
}
}
fn platform_from_runtime(runtime: &str) -> Option<String> {
let lower = runtime.to_ascii_lowercase();
if lower.contains(".visionos-") || lower.contains(".xros-") || lower.contains(".realityos-") {
Some("visionos".to_string())
} else if lower.contains(".ios-") {
Some("ios".to_string())
} else if lower.contains(".tvos-") {
Some("tvos".to_string())
} else if lower.contains(".watchos-") {
Some("watchos".to_string())
} else {
None
}
}
fn platform_matches(requested: &Platform, resolved: &str) -> bool {
match requested {
Platform::Auto => true,
Platform::Ios => resolved == "ios",
Platform::Tvos => resolved == "tvos",
Platform::Watchos => resolved == "watchos",
Platform::Visionos => resolved == "visionos",
}
}
fn sort_targets(targets: &mut [DeviceTarget]) {
targets.sort_by(|left, right| {
right
.booted
.cmp(&left.booted)
.then_with(|| left.kind.cmp(&right.kind))
.then_with(|| left.name.cmp(&right.name))
.then_with(|| left.identifier.cmp(&right.identifier))
});
}
fn select_targets(
targets: Vec<DeviceTarget>,
selector: &str,
) -> Result<Vec<DeviceTarget>, ProviderError> {
let trimmed = selector.trim();
let lower = trimmed.to_ascii_lowercase();
let (kind, needle) = if lower.starts_with("sim:") {
(Some("simulator"), &trimmed[4..])
} else if lower.starts_with("device:") {
(Some("device"), &trimmed[7..])
} else if lower.starts_with("dev:") {
(Some("device"), &trimmed[4..])
} else {
(None, trimmed)
};
let selected = targets
.into_iter()
.filter(|target| kind.is_none_or(|kind| target.kind == kind))
.filter(|target| {
target.identifier == needle
|| target.name == needle
|| target.udid.as_deref() == Some(needle)
})
.collect::<Vec<_>>();
if selected.is_empty() {
return Err(ProviderError::new(
"device_not_found",
format!("device or simulator '{trimmed}' not found"),
));
}
Ok(selected)
}
fn mixed_kinds(targets: &[DeviceTarget]) -> bool {
targets.iter().any(|target| target.kind == "device")
&& targets.iter().any(|target| target.kind == "simulator")
}
fn parse_processes(output: &str) -> Vec<(u32, String)> {
output
.lines()
.filter_map(|line| {
let line = line.trim();
let split = line.find(char::is_whitespace)?;
let pid = line[..split].parse::<u32>().ok().filter(|pid| *pid > 0)?;
Some((pid, line[split..].trim().to_string()))
})
.collect()
}
pub fn parse_launch_pid(output: &str) -> Option<u32> {
if let Some((_, tail)) = output.rsplit_once(':')
&& let Ok(pid) = tail.trim().parse::<u32>()
&& pid > 0
{
return Some(pid);
}
let lower = output.to_ascii_lowercase();
if let Some(index) = lower.find("pid") {
let digits = output[index + 3..]
.chars()
.skip_while(|character| !character.is_ascii_digit())
.take_while(char::is_ascii_digit)
.collect::<String>();
if let Ok(pid) = digits.parse::<u32>()
&& pid > 0
{
return Some(pid);
}
}
let values = output
.split(|character: char| !character.is_ascii_digit())
.filter(|value| !value.is_empty())
.filter_map(|value| value.parse::<u32>().ok())
.collect::<Vec<_>>();
(values.len() == 1).then_some(values[0])
}
pub fn parse_debug_proxy_port(logs: &str) -> Option<u16> {
for line in logs.lines().rev() {
let lower = line.to_ascii_lowercase();
if !lower.contains("debugproxy") {
continue;
}
for marker in ["tcp:", "port ", "port:"] {
let Some(index) = lower.find(marker) else {
continue;
};
let digits = line[index + marker.len()..]
.chars()
.skip_while(|character| !character.is_ascii_digit())
.take_while(char::is_ascii_digit)
.collect::<String>();
if let Ok(port) = digits.parse::<u16>()
&& port > 0
{
return Some(port);
}
}
}
None
}
fn decode_path(value: &str) -> String {
let value = value.strip_prefix("file://").unwrap_or(value);
let bytes = value.as_bytes();
let mut output = Vec::with_capacity(bytes.len());
let mut index = 0;
while index < bytes.len() {
if bytes[index] == b'%'
&& index + 2 < bytes.len()
&& let (Some(high), Some(low)) = (hex(bytes[index + 1]), hex(bytes[index + 2]))
{
output.push(high * 16 + low);
index += 3;
continue;
}
output.push(bytes[index]);
index += 1;
}
String::from_utf8_lossy(&output).into_owned()
}
fn hex(value: u8) -> Option<u8> {
match value {
b'0'..=b'9' => Some(value - b'0'),
b'a'..=b'f' => Some(value - b'a' + 10),
b'A'..=b'F' => Some(value - b'A' + 10),
_ => None,
}
}
fn collapse_whitespace(value: &str) -> String {
value.split_whitespace().collect::<Vec<_>>().join(" ")
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Clone, Default)]
struct SimulatorLaunchRunner {
calls: std::sync::Arc<std::sync::Mutex<Vec<Vec<String>>>>,
}
impl AppleCommandRunner for SimulatorLaunchRunner {
fn xcrun(&self, args: &[String]) -> Result<String, String> {
self.calls.lock().unwrap().push(args.to_vec());
match args {
[version] if version == "--version" => Ok("xcrun version 1".to_string()),
[simctl, list, devices, json]
if simctl == "simctl"
&& list == "list"
&& devices == "devices"
&& json == "--json" =>
{
Ok(serde_json::json!({
"devices": {
"com.apple.CoreSimulator.SimRuntime.iOS-27-0": [{
"isAvailable": true,
"name": "iPhone Test",
"state": "Booted",
"udid": "SIM-1"
}]
}
})
.to_string())
}
[simctl, get_app_container, identifier, bundle_id, app]
if simctl == "simctl"
&& get_app_container == "get_app_container"
&& identifier == "SIM-1"
&& bundle_id == "com.example.app"
&& app == "app" =>
{
Ok("/tmp/Example.app\n".to_string())
}
[simctl, launch, identifier, bundle_id]
if simctl == "simctl"
&& launch == "launch"
&& identifier == "SIM-1"
&& bundle_id == "com.example.app" =>
{
Ok("com.example.app: 777\n".to_string())
}
_ => Err(format!("unexpected xcrun call: {args:?}")),
}
}
fn devicectl(&self, args: &[String]) -> Result<Value, String> {
if args == strings(&["list", "devices"]) {
Ok(serde_json::json!({"devices": []}))
} else {
Err(format!("unexpected devicectl call: {args:?}"))
}
}
fn system_log(&self, args: &[String]) -> Result<String, String> {
Err(format!("unexpected log call: {args:?}"))
}
}
#[test]
fn parses_launch_and_debug_proxy_identifiers() {
assert_eq!(parse_launch_pid("com.example: 777"), Some(777));
assert_eq!(parse_launch_pid("launched with pid 888"), Some(888));
assert_eq!(
parse_debug_proxy_port("debugproxy listening on tcp:62078 for device"),
Some(62078)
);
}
#[test]
fn maps_all_simulator_runtime_platforms() {
assert_eq!(
platform_from_runtime("com.apple.CoreSimulator.SimRuntime.iOS-18-0"),
Some("ios".to_string())
);
assert_eq!(
platform_from_runtime("com.apple.CoreSimulator.SimRuntime.xrOS-2-1"),
Some("visionos".to_string())
);
}
#[test]
fn resolves_launched_simulator_pid_without_process_listing() {
let runner = SimulatorLaunchRunner::default();
let calls = runner.calls.clone();
let service = AppleDeviceService::new(runner);
let resolution = service
.resolve(AttachRequest {
bundle_id: "com.example.app".to_string(),
platform: Platform::Ios,
device: Some("sim:SIM-1".to_string()),
pid: None,
launch: true,
attach_strategy: "auto".to_string(),
attach_timeout_ms: 45_000,
})
.unwrap();
assert_eq!(resolution.pid, 777);
assert_eq!(resolution.metadata["matched_by"], "launch");
assert!(
!calls
.lock()
.unwrap()
.iter()
.any(|args| { args.starts_with(&strings(&["simctl", "spawn", "SIM-1", "ps"])) })
);
}
}