use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::Arc;
use incurs_codemode::McpClient;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio::sync::Mutex;
use crate::code::StdioMcpClient;
use crate::model::{ProviderConfig, ProviderKind, now_ms};
use super::DebuggerRunResult;
const APPLE_DEVICE_PROVIDER_NAME: &str = "apple_device";
const APPLE_DEVICE_PROVIDER_GENERATION: &str = "builtin-apple-device-v1";
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct AppleDeviceTarget {
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, Serialize, Deserialize, JsonSchema)]
pub struct AppleDeviceApp {
pub bundle_id: String,
pub name: String,
pub url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct AppleAttachRequest {
pub bundle_id: String,
pub platform: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub device: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pid: Option<u32>,
pub launch: bool,
pub attach_strategy: String,
pub attach_timeout_ms: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct AppleAttachResolution {
pub provider: String,
pub platform: String,
pub device_id: String,
pub bundle_id: String,
pub pid: u32,
pub attach_protocol: String,
#[serde(default)]
pub metadata: Value,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct AppleDebugProxy {
pub device_id: String,
pub port: u16,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct AppleAttachResult {
pub resolution: AppleAttachResolution,
pub selected_strategy: String,
pub attempted_strategies: Vec<String>,
#[serde(flatten)]
pub debugger: DebuggerRunResult,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum AppleAttachStrategy {
DeviceProcess,
GdbRemote,
}
impl AppleAttachStrategy {
pub(crate) fn as_str(self) -> &'static str {
match self {
Self::DeviceProcess => "device-process",
Self::GdbRemote => "gdb-remote",
}
}
}
pub(crate) fn apple_attach_strategy_order(
requested: &str,
resolution: &AppleAttachResolution,
) -> Result<Vec<AppleAttachStrategy>, String> {
let simulator = resolution
.metadata
.get("attach_environment")
.and_then(Value::as_str)
== Some("simulator");
match (requested, simulator) {
("auto" | "device-process", true) => Ok(vec![AppleAttachStrategy::DeviceProcess]),
("gdb-remote", true) => {
Err("gdb-remote attach is only supported for physical devices".to_string())
}
("auto", false) => Ok(vec![
AppleAttachStrategy::DeviceProcess,
AppleAttachStrategy::GdbRemote,
]),
("device-process", false) => Ok(vec![AppleAttachStrategy::DeviceProcess]),
("gdb-remote", false) => Ok(vec![AppleAttachStrategy::GdbRemote]),
_ => Err("attach_strategy must be auto, device-process, or gdb-remote".to_string()),
}
}
pub(crate) fn apple_dap_attach_arguments(
resolution: &AppleAttachResolution,
strategy: AppleAttachStrategy,
timeout_ms: u64,
debug_proxy_port: Option<u16>,
) -> Result<Value, String> {
let timeout_seconds = (timeout_ms / 1_000).max(1);
let simulator = resolution
.metadata
.get("attach_environment")
.and_then(Value::as_str)
== Some("simulator");
match strategy {
AppleAttachStrategy::DeviceProcess if simulator => Ok(serde_json::json!({
"pid":resolution.pid,
"waitFor":false,
"timeout":timeout_seconds
})),
AppleAttachStrategy::DeviceProcess => Ok(serde_json::json!({
"attachCommands":[
format!("device select {}", resolution.device_id),
format!("device process attach --pid {}", resolution.pid)
],
"timeout":timeout_seconds
})),
AppleAttachStrategy::GdbRemote => {
let port = debug_proxy_port
.ok_or_else(|| "gdb-remote attach requires a debug proxy port".to_string())?;
Ok(serde_json::json!({
"gdb-remote-port":port,
"gdb-remote-hostname":"127.0.0.1",
"pid":resolution.pid,
"timeout":timeout_seconds
}))
}
}
}
pub(crate) fn apple_stable_target(resolution: &AppleAttachResolution) -> String {
format!("apple:{}:pid:{}", resolution.device_id, resolution.pid)
}
#[derive(Clone, Default)]
pub struct AppleDeviceProvider {
client: Arc<Mutex<Option<Arc<StdioMcpClient>>>>,
}
impl AppleDeviceProvider {
pub async fn devices(&self, platform: &str) -> Result<Vec<AppleDeviceTarget>, String> {
self.call("devices", serde_json::json!({"platform":platform}))
.await
}
pub async fn apps(&self, device_id: &str) -> Result<Vec<AppleDeviceApp>, String> {
self.call("apps", serde_json::json!({"device_id":device_id}))
.await
}
pub async fn resolve(
&self,
request: AppleAttachRequest,
) -> Result<AppleAttachResolution, String> {
let arguments = serde_json::to_value(request).map_err(|error| error.to_string())?;
self.call("resolve", arguments).await
}
pub async fn debug_proxy(&self, device_id: &str) -> Result<AppleDebugProxy, String> {
self.call("debug_proxy", serde_json::json!({"device_id":device_id}))
.await
}
async fn call<T: serde::de::DeserializeOwned>(
&self,
tool: &str,
arguments: Value,
) -> Result<T, String> {
let client = self.client().await?;
let catalog = match client.list_tools().await {
Ok(catalog) => catalog,
Err(error) => {
self.discard(&client).await;
return Err(error);
}
};
let names = catalog
.iter()
.map(|entry| entry.name.clone())
.collect::<Vec<_>>();
let (method, arguments) = apple_provider_call(&names, tool, arguments)?;
match client.call_tool(&method, arguments).await {
Ok(value) => serde_json::from_value(value)
.map_err(|error| format!("Invalid {tool} result: {error}")),
Err(error) => {
self.discard(&client).await;
Err(error)
}
}
}
async fn client(&self) -> Result<Arc<StdioMcpClient>, String> {
let mut retained = self.client.lock().await;
if let Some(client) = retained.as_ref() {
return Ok(Arc::clone(client));
}
let client = Arc::new(StdioMcpClient::new(&provider_config()?)?);
*retained = Some(Arc::clone(&client));
Ok(client)
}
async fn discard(&self, failed: &Arc<StdioMcpClient>) {
let mut retained = self.client.lock().await;
if retained
.as_ref()
.is_some_and(|current| Arc::ptr_eq(current, failed))
{
*retained = None;
}
}
}
fn apple_provider_call(
catalog: &[String],
tool: &str,
arguments: Value,
) -> Result<(String, Value), String> {
if catalog.iter().any(|candidate| candidate == tool) {
return Ok((tool.to_string(), arguments));
}
let facade = if tool == "resolve" {
"call_write_tool"
} else {
"call_read_tool"
};
if catalog.iter().any(|candidate| candidate == facade) {
return Ok((
facade.to_string(),
serde_json::json!({"name":tool,"arguments":arguments}),
));
}
Err(format!(
"APPLE_DEVICE_PROVIDER_TOOL_UNAVAILABLE: provider exposes neither {tool} nor {facade}"
))
}
fn provider_config() -> Result<ProviderConfig, String> {
let executable = resolve_provider()?;
let now = now_ms();
Ok(ProviderConfig {
name: APPLE_DEVICE_PROVIDER_NAME.to_string(),
kind: ProviderKind::McpStdio,
url: None,
base_url: None,
command: Some(executable.to_string_lossy().into_owned()),
args: vec!["--mcp".to_string()],
cwd: executable
.parent()
.map(|parent| parent.to_string_lossy().into_owned()),
env: BTreeMap::new(),
secret_env: BTreeMap::new(),
headers: BTreeMap::new(),
secret_headers: BTreeMap::new(),
profile_mode: crate::model::ProfileMode::None,
profile_env: BTreeMap::new(),
profile_headers: BTreeMap::new(),
instructions: Some(
"Resolve Apple devices, simulators, installed apps, and DAP attach targets."
.to_string(),
),
enabled: true,
generation: APPLE_DEVICE_PROVIDER_GENERATION.to_string(),
created_at: now,
updated_at: now,
})
}
fn resolve_provider() -> Result<PathBuf, String> {
let configured = std::env::var_os("APOC_APPLE_DEVICE_PROVIDER").map(PathBuf::from);
let sibling = std::env::current_exe()
.ok()
.and_then(|path| path.parent().map(|parent| parent.join("apoc-apple-device")));
let repository = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
configured
.into_iter()
.chain(sibling)
.chain([
repository.join("extensions/apple-device/target/release/apoc-apple-device"),
repository.join("extensions/apple-device/target/debug/apoc-apple-device"),
])
.find(|path| path.is_file())
.ok_or_else(|| {
"APPLE_DEVICE_PROVIDER_UNAVAILABLE: install apoc-apple-device beside apoc or set APOC_APPLE_DEVICE_PROVIDER"
.to_string()
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn selects_direct_tools_for_legacy_providers_and_incurs_facades_before_dispatch() {
let arguments = serde_json::json!({"platform":"ios"});
let direct =
apple_provider_call(&["devices".to_string()], "devices", arguments.clone()).unwrap();
assert_eq!(direct, ("devices".to_string(), arguments.clone()));
let read = apple_provider_call(
&["call_read_tool".to_string(), "call_write_tool".to_string()],
"devices",
arguments.clone(),
)
.unwrap();
assert_eq!(read.0, "call_read_tool");
assert_eq!(
read.1,
serde_json::json!({"name":"devices","arguments":arguments})
);
let write = apple_provider_call(
&["call_read_tool".to_string(), "call_write_tool".to_string()],
"resolve",
serde_json::json!({"launch":true}),
)
.unwrap();
assert_eq!(write.0, "call_write_tool");
assert_eq!(write.1["name"], "resolve");
assert_eq!(write.1["arguments"]["launch"], true);
}
#[test]
fn omits_absent_optional_selectors_from_resolve_arguments() {
let request = AppleAttachRequest {
bundle_id: "com.example.app".to_string(),
platform: "ios".to_string(),
device: None,
pid: None,
launch: true,
attach_strategy: "auto".to_string(),
attach_timeout_ms: 45_000,
};
let arguments = serde_json::to_value(request).unwrap();
assert!(!arguments.as_object().unwrap().contains_key("device"));
assert!(!arguments.as_object().unwrap().contains_key("pid"));
}
}