Skip to main content

iphone_cli/
doctor.rs

1//! `iph doctor`: check, in order, everything the phone needs for iph to work,
2//! and say in one line what the user must do for each thing that is missing.
3//!
4//! Which checks are truly required was established on an iPhone 15 Pro Max
5//! with iOS 27.0.1; see docs/onboarding.md.
6
7use std::time::Duration;
8
9use idevice::{
10    IdeviceService, amfi::AmfiClient, lockdown::LockdownClient,
11    mobile_image_mounter::ImageMounter, provider::IdeviceProvider,
12};
13use serde::{Deserialize, Serialize};
14use serde_json::{Value, json};
15
16use crate::{
17    actions::{LaunchArgs, ScrollArgs},
18    ax::tree::BuildOptions,
19    device::{
20        ax, conn, wifi,
21        session::{Fresh, Session},
22    },
23    fields,
24    i18n::t,
25    reply::Res,
26};
27
28#[derive(Debug, Default, Deserialize)]
29#[serde(default, deny_unknown_fields)]
30pub struct DoctorArgs {
31    /// Skip the check that sends a real touch (it brings Settings to the front
32    /// and scrolls its list down and back).
33    pub no_touch_test: bool,
34    /// Enable disabled wireless lockdown flags through USB, then look for
35    /// the device's usbmuxd Network entry. Ordinary doctor only reads them.
36    pub fix_wifi: bool,
37}
38
39#[derive(Debug, Clone, Serialize)]
40pub struct Check {
41    pub check: &'static str,
42    /// "ok" | "fail" | "warn" | "skipped" | "info"
43    pub status: &'static str,
44    pub required: bool,
45    #[serde(skip_serializing_if = "Option::is_none")]
46    pub user_action: Option<String>,
47    pub auto_fixed: bool,
48    #[serde(skip_serializing_if = "Option::is_none")]
49    pub detail: Option<String>,
50}
51
52impl Check {
53    fn new(check: &'static str, required: bool) -> Self {
54        Self {
55            check,
56            status: "ok",
57            required,
58            user_action: None,
59            auto_fixed: false,
60            detail: None,
61        }
62    }
63
64    fn status(mut self, status: &'static str) -> Self {
65        self.status = status;
66        self
67    }
68
69    fn action(mut self, ko: &str, en: &str) -> Self {
70        self.user_action = Some(t(ko, en).to_string());
71        self
72    }
73
74    fn detail(mut self, detail: impl Into<String>) -> Self {
75        self.detail = Some(detail.into());
76        self
77    }
78}
79
80const SETTINGS: &str = "com.apple.Preferences";
81const NEEDED_SERVICES: &[&str] = &[
82    ax::SERVICE,
83    "com.apple.coredevice.displayservice",
84    "com.apple.coredevice.hid.universalhidservice",
85    "com.apple.coredevice.appservice",
86];
87
88async fn with_timeout<T>(fut: impl std::future::Future<Output = T>) -> Option<T> {
89    tokio::time::timeout(Duration::from_secs(15), fut).await.ok()
90}
91
92struct LockdownFacts {
93    developer_mode: Option<bool>,
94    /// `PasswordProtected`: true while the phone is locked with a passcode.
95    locked: Option<bool>,
96}
97
98/// What lockdown says about Developer Mode and the lock. Read-only.
99async fn lockdown_facts(provider: &dyn IdeviceProvider) -> LockdownFacts {
100    let mut facts = LockdownFacts { developer_mode: None, locked: None };
101    // The image mounter answers the Developer Mode question most reliably;
102    // the AMFI service closed the connection on iOS 27.0.1 over Wi-Fi.
103    if let Some(Ok(mut mounter)) = with_timeout(ImageMounter::connect(provider)).await {
104        facts.developer_mode = with_timeout(mounter.query_developer_mode_status())
105            .await
106            .and_then(|r| r.ok());
107    }
108    if let Some(Ok(mut lockdown)) = with_timeout(LockdownClient::connect(provider)).await {
109        if let Some(Ok(pairing)) = with_timeout(provider.get_pairing_file()).await {
110            let _ = with_timeout(lockdown.start_session(&pairing)).await;
111        }
112        if facts.developer_mode.is_none() {
113            facts.developer_mode = with_timeout(
114                lockdown.get_value(Some("DeveloperModeStatus"), Some("com.apple.security.mac.amfi")),
115            )
116            .await
117            .and_then(|r| r.ok())
118            .and_then(|v| v.as_boolean());
119        }
120    }
121    facts.locked = conn::passcode_locked(provider).await;
122    facts
123}
124
125/// Developer services the tunnel does not offer. `Err` when the tunnel itself
126/// cannot be opened.
127async fn missing_services(s: &mut Session) -> Result<Vec<&'static str>, String> {
128    match s.ensure_tunnel().await {
129        Ok(tunnel) => Ok(NEEDED_SERVICES
130            .iter()
131            .filter(|name| !tunnel.rsd.services.contains_key(**name))
132            .copied()
133            .collect()),
134        Err(f) => Err(f.message),
135    }
136}
137
138fn hex_field(v: Option<&plist::Value>) -> Option<u64> {
139    match v? {
140        plist::Value::String(s) => u64::from_str_radix(s.trim_start_matches("0x"), 16).ok(),
141        plist::Value::Integer(i) => i.as_unsigned(),
142        _ => None,
143    }
144}
145
146/// Mount the personalized developer disk image that Xcode keeps on this Mac.
147///
148/// Written from the documented flow (match the build identity to the phone's
149/// board and chip, have Apple sign it, upload, mount). It could not be tried
150/// on the test phone, whose image was already mounted.
151async fn mount_ddi(provider: &dyn IdeviceProvider) -> anyhow::Result<()> {
152    use anyhow::{Context, anyhow};
153    let restore = crate::ddi::xcode_restore()
154        .ok_or_else(|| anyhow!("no Xcode developer disk image on this computer"))?;
155
156    let manifest_bytes = std::fs::read(restore.join("BuildManifest.plist"))?;
157    let manifest: plist::Value = plist::from_bytes(&manifest_bytes).context("BuildManifest.plist")?;
158
159    let mut lockdown = LockdownClient::connect(provider)
160        .await
161        .map_err(|e| anyhow!("lockdown: {e:?}"))?;
162    if let Ok(pairing) = provider.get_pairing_file().await {
163        let _ = lockdown.start_session(&pairing).await;
164    }
165    let number = |v: plist::Value| v.as_unsigned_integer();
166    let board = lockdown.get_value(Some("BoardId"), None).await.ok().and_then(number);
167    let chip = lockdown.get_value(Some("ChipID"), None).await.ok().and_then(number);
168    let ecid = lockdown
169        .get_value(Some("UniqueChipID"), None)
170        .await
171        .ok()
172        .and_then(number)
173        .ok_or_else(|| anyhow!("the phone did not report its chip id"))?;
174
175    let identities = manifest
176        .as_dictionary()
177        .and_then(|d| d.get("BuildIdentities"))
178        .and_then(|v| v.as_array())
179        .ok_or_else(|| anyhow!("BuildManifest has no BuildIdentities"))?;
180    let identity = identities
181        .iter()
182        .filter_map(|i| i.as_dictionary())
183        .find(|i| hex_field(i.get("ApBoardID")) == board && hex_field(i.get("ApChipID")) == chip)
184        .ok_or_else(|| anyhow!("no Xcode developer disk image on this computer matches this phone model"))?;
185    let path_of = |component: &str| -> anyhow::Result<std::path::PathBuf> {
186        identity
187            .get("Manifest")
188            .and_then(|m| m.as_dictionary())
189            .and_then(|m| m.get(component))
190            .and_then(|c| c.as_dictionary())
191            .and_then(|c| c.get("Info"))
192            .and_then(|i| i.as_dictionary())
193            .and_then(|i| i.get("Path"))
194            .and_then(|p| p.as_string())
195            .map(|p| restore.join(p))
196            .ok_or_else(|| anyhow!("BuildManifest has no path for {component}"))
197    };
198    let image = std::fs::read(path_of("PersonalizedDMG")?)?;
199    let trust_cache = std::fs::read(path_of("LoadableTrustCache")?)?;
200
201    let mut mounter = ImageMounter::connect(provider)
202        .await
203        .map_err(|e| anyhow!("image mounter: {e:?}"))?;
204    mounter
205        .mount_personalized(provider, image, trust_cache, &manifest_bytes, None, ecid)
206        .await
207        .map_err(|e| anyhow!("mount: {e:?}"))
208}
209
210/// The checks for "the phone is unlocked and Settings is in front", and
211/// whether Settings is in front.
212///
213/// `locked`: lockdown's word. `launched`: whether the launch of Settings was
214/// seen in front, or why it failed; `None` when not tried. `read`: when it was
215/// not seen, a reading taken after: whether Settings is in front on it, or why
216/// it failed.
217fn front_checks(
218    locked: Option<bool>,
219    launched: Option<Result<bool, String>>,
220    read: Option<Result<bool, String>>,
221) -> (Vec<Check>, bool) {
222    let mut out = Vec::new();
223    if locked == Some(true) {
224        out.push(
225            Check::new("screen_unlocked", true)
226                .status("fail")
227                .detail("the phone reports that it is locked")
228                .action("폰 잠금을 풀어 주세요.", "Unlock the phone."),
229        );
230        return (out, false);
231    }
232    let unlocked = match locked {
233        Some(false) => Check::new("screen_unlocked", true).detail("lockdown: not locked"),
234        _ => Check::new("screen_unlocked", true).detail("lockdown did not say; Settings came to the front"),
235    };
236    if launched == Some(Ok(true)) || read == Some(Ok(true)) {
237        out.push(unlocked);
238        return (out, true);
239    }
240    match (&launched, &read) {
241        (_, Some(Err(why))) => {
242            // The screen cannot be read: that is what to report, lock or not.
243            out.push(match locked {
244                Some(false) => Check::new("screen_unlocked", true).detail("lockdown: not locked"),
245                _ => Check::new("screen_unlocked", true)
246                    .status("skipped")
247                    .detail("lockdown did not say, and the screen cannot be read"),
248            });
249            out.push(
250                Check::new("accessibility_tree", true)
251                    .status("fail")
252                    .detail(why.clone())
253                    .action(
254                        "화면 읽기 응답이 없습니다(폰의 화면 읽기 서비스 axauditd). iph가 그 서비스를 다시 띄웠거나 2분 안에 다시 띄웁니다. 잠시 뒤 `iph doctor`를 다시 실행하고, 계속되면 폰을 재시동하세요.",
255                        "No answer from the phone's screen reading (its axauditd service). iph has restarted it or will within 2 minutes. Run `iph doctor` again shortly; if it keeps failing, restart the phone.",
256                    ),
257            );
258        }
259        (Some(Err(why)), _) => {
260            out.push(unlocked);
261            out.push(
262                Check::new("settings_in_front", true)
263                    .status("fail")
264                    .detail(why.clone())
265                    .action("설정 앱을 열지 못했습니다. 폰 화면을 확인하고 다시 시도하세요.", "Settings could not be opened. Check the phone's screen and try again."),
266            );
267        }
268        _ => {
269            // The screen reads, and shows something else.
270            out.push(unlocked);
271            out.push(
272                Check::new("settings_in_front", true)
273                    .status("fail")
274                    .detail("Settings was launched but another screen is in front")
275                    .action(
276                        "설정 앱이 앞에 나오지 않았습니다. 다른 창이나 알림이 가리고 있는지 폰 화면을 확인하세요.",
277                        "Settings did not come to the front. Check the phone's screen for a window or alert in the way.",
278                    ),
279            );
280        }
281    }
282    (out, false)
283}
284
285fn wifi_check(
286    connection: Option<&str>,
287    state: Option<&wifi::Wireless>,
288    network: Result<bool, String>,
289) -> Check {
290    let mut c = Check::new("wifi", false);
291    let mut detail = Vec::new();
292    match &network {
293        Ok(true) if connection == Some("usb") => detail.push("reachable over Wi-Fi as well as USB".into()),
294        Ok(true) => detail.push("usbmuxd Network entry present".into()),
295        Ok(false) => detail.push("no usbmuxd Network entry".into()),
296        Err(e) => detail.push(format!("could not check usbmuxd Network entry: {e}")),
297    }
298    if let Some(state) = state {
299        detail.push(state.detail());
300        c.auto_fixed = !state.changed.is_empty();
301        if state.supported() == Some(false) && network != Ok(true) {
302            return c.status("warn").detail(detail.join("; ")).action(
303                "기기가 SupportsWifi와 SupportsWifiSyncing을 모두 false로 보고했습니다. 자동으로 무선 설정을 바꾸지 않았습니다. USB 연결을 사용하세요.",
304                "The device reports SupportsWifi=false and SupportsWifiSyncing=false. Wireless settings were not changed automatically. Use USB.",
305            );
306        }
307        let disabled = state.disabled();
308        if !disabled.is_empty() {
309            c = c.status("warn");
310            let keys = disabled.join(" / ");
311            return c.detail(detail.join("; ")).action(
312                &format!("기기의 무선 디버깅/Wi-Fi 연결 플래그({keys})가 꺼져 있습니다. USB 연결 상태에서 `iph setup --fix-wifi` 또는 `iph doctor --fix-wifi`를 실행하세요. 직접 설정하려면 Finder의 'Wi-Fi에 있을 때 이 iPhone 보기'(윈도: Apple 기기 앱)와 Xcode의 'Connect via network'를 확인하세요. 자동 설정 실패 원인은 detail에 표시됩니다."),
313                &format!("The device's wireless debugging/Wi-Fi connection flags ({keys}) are off. With USB connected, run `iph setup --fix-wifi` or `iph doctor --fix-wifi`. For manual setup, check Finder's \"Show this iPhone when on Wi-Fi\" (Apple Devices on Windows) and Xcode's \"Connect via network\". Any automatic setup failure is in detail."),
314            );
315        }
316    }
317    if network == Ok(true) || (network.is_ok() && state.is_none() && connection == Some("wifi")) {
318        return c.detail(detail.join("; "));
319    }
320    c = c.status("warn").detail(detail.join("; "));
321    if network.is_err() {
322        return c.action(
323            "usbmuxd에서 무선 연결 목록을 확인하지 못했습니다. 컴퓨터의 Apple 기기 연결 서비스와 USB 연결을 확인하고 `iph doctor`를 다시 실행하세요.",
324            "Could not query wireless connections from usbmuxd. Check the computer's Apple device service and USB connection, then run `iph doctor` again.",
325        );
326    }
327    match state {
328        Some(state) if state.enabled() => c.action(
329            "EnableWifiConnections와 EnableWifiDebugging은 모두 켜져 있지만 usbmuxd에 Network 연결이 없습니다. 폰과 컴퓨터가 같은 Wi-Fi 대역에 있는지, 공유기의 AP/클라이언트 격리가 꺼져 있는지, mDNS/Bonjour(_apple-mobdev2._tcp.local.)가 차단되지 않는지 확인하세요. 설정 직후라면 잠시 뒤 `iph doctor`를 다시 실행하세요.",
330            "EnableWifiConnections and EnableWifiDebugging are both on, but usbmuxd has no Network connection. Check the same Wi-Fi subnet, AP/client isolation, and whether mDNS/Bonjour (_apple-mobdev2._tcp.local.) is blocked. If just enabled, run `iph doctor` again shortly.",
331        ),
332        _ => c.action(
333            "기기의 무선 플래그를 확인하지 못했습니다(원인은 detail 참고). USB로 연결하고 잠금을 풀어 '이 컴퓨터를 신뢰'를 확인한 뒤 `iph doctor`를 다시 실행하세요. 무선 설정은 Finder/Apple 기기 앱과 Xcode의 'Connect via network'에서도 확인할 수 있습니다.",
334            "Could not confirm the device's wireless flags (see detail). Connect by USB, unlock and trust this computer, then run `iph doctor` again. Wireless settings can also be checked in Finder/Apple Devices and Xcode's \"Connect via network\".",
335        ),
336    }
337}
338
339async fn check_wifi(udid: &str, connection: Option<&str>, fix: bool) -> Check {
340    let all = match tokio::time::timeout(Duration::from_secs(3), conn::list_raw()).await {
341        Ok(Ok(all)) => all,
342        Ok(Err(e)) => return wifi_check(connection, None, Err(format!("{e:#}"))),
343        Err(_) => return wifi_check(connection, None, Err("ListDevices timed out".into())),
344    };
345    let mut network = Ok(wifi::has_network(&all, udid));
346    let mut state = None;
347    if let Some(usb) = wifi::usb_device(&all, udid) {
348        let addr = match conn::mux_addr() {
349            Ok(addr) => addr,
350            Err(e) => return wifi_check(connection, None, Err(format!("{e:#}"))),
351        };
352        let provider = usb.to_provider(addr, conn::LABEL);
353        state = Some(wifi::inspect(&provider, fix).await);
354        if fix && network == Ok(false)
355            && state.as_ref().is_some_and(|s| s.enabled() || !s.changed.is_empty()) {
356            network = wifi::discover(udid).await;
357        }
358    }
359    if connection.is_none() && state.is_none() && network == Ok(false) {
360        return Check::new("wifi", false).status("skipped").detail("phone not reachable");
361    }
362    wifi_check(connection, state.as_ref(), network)
363}
364
365pub async fn run(s: &mut Session, args: DoctorArgs) -> Res {
366    let mut checks: Vec<Check> = Vec::new();
367    let skip = |name: &'static str, required: bool, why: &str| {
368        Check::new(name, required).status("skipped").detail(why.to_string())
369    };
370
371    // 1. Pairing: the Mac holds a pairing record for this phone.
372    let paired = match conn::mux_connect().await {
373        Ok(mut mux) => with_timeout(mux.get_pair_record(&s.udid)).await.is_some_and(|r| r.is_ok()),
374        Err(_) => false,
375    };
376    checks.push(if paired {
377        Check::new("pairing", true)
378    } else {
379        Check::new("pairing", true).status("fail").action(
380            "USB로 연결하고 폰에서 '이 컴퓨터를 신뢰'를 누르세요.",
381            "Connect the phone by USB and tap \"Trust This Computer\" on it.",
382        )
383    });
384
385    // 2. Reachable at all, and how.
386    let route = conn::route(&s.udid).await;
387    let connection = route.as_ref().ok().map(|r| r.connection.clone());
388    checks.push(match &route {
389        Ok(r) => Check::new("connection", true).detail(r.connection.clone()),
390        Err(e) => Check::new("connection", true)
391            .status("fail")
392            .detail(format!("{e:#}"))
393            .action(
394                "폰을 USB로 연결하거나, 컴퓨터와 같은 Wi-Fi에 두고 화면을 켜 주세요.",
395                "Plug the phone in, or put it on the computer's Wi-Fi and wake its screen.",
396            ),
397    });
398
399    // Inspect (and, with --fix-wifi, configure) the USB transport before
400    // developer services: a missing image must not prevent wireless setup.
401    let wifi = check_wifi(&s.udid, connection.as_deref(), args.fix_wifi).await;
402
403    // 3. Developer Mode. If it is off, make the switch appear in Settings.
404    let facts = match &route {
405        Ok(r) => Some(lockdown_facts(&*r.provider).await),
406        Err(_) => None,
407    };
408    let dev_mode = facts.as_ref().and_then(|f| f.developer_mode);
409    checks.push(match dev_mode {
410        Some(true) => Check::new("developer_mode", true),
411        Some(false) => {
412            let mut revealed = false;
413            if let Ok(r) = &route
414                && let Some(Ok(mut amfi)) = with_timeout(AmfiClient::connect(&*r.provider)).await {
415                    revealed = with_timeout(amfi.reveal_developer_mode_option_in_ui())
416                        .await
417                        .is_some_and(|r| r.is_ok());
418                }
419            let mut c = Check::new("developer_mode", true).status("fail").action(
420                "설정 → 개인정보 보호 및 보안 → 개발자 모드 → 켜기 → 재시동 후 비밀번호를 입력하세요.",
421                "Settings → Privacy & Security → Developer Mode → turn on → restart, then enter the passcode.",
422            );
423            c.auto_fixed = revealed;
424            if revealed {
425                c = c.detail("the Developer Mode switch was made visible in Settings");
426            }
427            c
428        }
429        None if route.is_ok() => Check::new("developer_mode", true)
430            .status("warn")
431            .detail("could not ask the phone; judged by the services below"),
432        None => skip("developer_mode", true, "phone not reachable"),
433    });
434
435    // 4. Developer disk image: its services must be on offer over the tunnel.
436    let mut services_ok = false;
437    if route.is_ok() && dev_mode != Some(false) {
438        let mut missing = missing_services(s).await;
439        let mut mounted_from = None;
440        let mut mount_note = None;
441        if matches!(&missing, Ok(m) if !m.is_empty()) {
442            // Install the image through cryptexd (Xcode's copy, else one
443            // fetched once), then look again. Phones before iOS 17.4 take it
444            // through the image mounter instead, from Xcode's copy only.
445            let cryptex = match s.ensure_tunnel().await {
446                Ok(tunnel) => match tokio::time::timeout(Duration::from_secs(300), crate::ddi::install(tunnel)).await {
447                    Ok(r) => r,
448                    Err(_) => Err(anyhow::anyhow!("timed out")),
449                },
450                Err(f) => Err(anyhow::anyhow!(f.message)),
451            };
452            match cryptex {
453                Ok(source) => mounted_from = Some(source),
454                Err(e) => {
455                    let mut note = format!("cryptex install failed: {e:#}");
456                    if let Ok(r) = &route {
457                        match tokio::time::timeout(Duration::from_secs(180), mount_ddi(&*r.provider)).await {
458                            Ok(Ok(())) => mounted_from = Some("Xcode".to_string()),
459                            Ok(Err(e)) => note.push_str(&format!("; image mounter: {e:#}")),
460                            Err(_) => note.push_str("; image mounter timed out"),
461                        }
462                    }
463                    if mounted_from.is_none() {
464                        mount_note = Some(note);
465                    }
466                }
467            }
468            if mounted_from.is_some() {
469                s.reset();
470                tokio::time::sleep(Duration::from_secs(2)).await;
471                missing = missing_services(s).await;
472            }
473        }
474        let mounted_now = mounted_from.is_some();
475        match missing {
476            Ok(m) if m.is_empty() => {
477                services_ok = true;
478                let mut c = Check::new("developer_disk_image", true);
479                c.auto_fixed = mounted_now;
480                if let Some(from) = &mounted_from {
481                    c = c.detail(format!("installed the developer disk image ({from})"));
482                }
483                checks.push(c);
484            }
485            Ok(m) => {
486                let mut detail = format!("missing services: {}", m.join(", "));
487                if let Some(note) = mount_note {
488                    detail.push_str("; ");
489                    detail.push_str(&note);
490                }
491                checks.push(Check::new("developer_disk_image", true).status("fail").detail(detail).action(
492                    "개발자 디스크 이미지를 연결하지 못했습니다. 인터넷 연결(애플 서명 서버, GitHub)을 확인하고 다시 `iph doctor`를 실행하세요. 맥이라면 Xcode의 창 → 기기 및 시뮬레이터에서 이 폰을 한 번 골라도 됩니다.",
493                    "Could not install the developer disk image. Check the internet connection (Apple's signing server, GitHub) and run `iph doctor` again. On a Mac, selecting this phone once in Xcode → Window → Devices and Simulators also works.",
494                ));
495            }
496            Err(message) => checks.push(
497                Check::new("developer_disk_image", true)
498                    .status("fail")
499                    .detail(message)
500                    .action(
501                        "폰 잠금을 풀고 다시 시도하세요. 계속 실패하면 USB로 연결하세요.",
502                        "Unlock the phone and try again. If it keeps failing, connect by USB.",
503                    ),
504            ),
505        }
506    } else {
507        checks.push(skip(
508            "developer_disk_image",
509            true,
510            if route.is_ok() { "Developer Mode is off" } else { "phone not reachable" },
511        ));
512    }
513
514    // 5. Wi-Fi (recommended): works without the cable.
515    checks.push(wifi);
516
517    // 6. Unlocked, and Settings comes to the front. Only lockdown's word
518    // makes this a lock: a launch that cannot be seen in front can as well
519    // be a screen that cannot be read (2026-11-11: 25 minutes of "unlock the
520    // phone" on an unlocked phone whose accessibility daemon answered only
521    // with empty readings).
522    let locked = facts.as_ref().and_then(|f| f.locked);
523    let mut front_ok = false;
524    let mut tree_reported = false;
525    if locked == Some(true) || services_ok {
526        let launched = if locked == Some(true) {
527            None
528        } else {
529            Some(match s.cmd_launch(LaunchArgs { app: SETTINGS.into(), restart: false }).await {
530                Ok(r) => Ok((
531                    r.get("foreground").and_then(|v| v.as_bool()) == Some(true),
532                    r.get("pid").and_then(|v| v.as_i64()),
533                )),
534                Err(f) => Err(f.message),
535            })
536        };
537        // Not seen in front: is the screen readable at all, and what is on it?
538        let read = match &launched {
539            None | Some(Ok((true, _))) => None,
540            Some(other) => {
541                let pid = other.as_ref().ok().and_then(|(_, pid)| *pid);
542                Some(match s.screen(Fresh::Force, false, BuildOptions::default()).await {
543                    Ok((_, screen)) => Ok(pid.is_some_and(|p| screen.apps.iter().any(|a| a.pid == p))),
544                    Err(f) => Err(f.message),
545                })
546            }
547        };
548        let launched = launched.map(|l| l.map(|(front, _)| front));
549        let (found, front) = front_checks(locked, launched, read);
550        tree_reported = found.iter().any(|c| c.check == "accessibility_tree");
551        front_ok = front;
552        checks.extend(found);
553    } else {
554        checks.push(skip("screen_unlocked", true, "developer services unavailable"));
555    }
556
557    // 7. The accessibility tree arrives.
558    let mut tree_ok = false;
559    if front_ok {
560        match s.screen(Fresh::Force, false, BuildOptions::default()).await {
561            Ok((_, screen)) if screen.elements.len() > 1 => {
562                tree_ok = true;
563                checks.push(
564                    Check::new("accessibility_tree", true)
565                        .detail(format!("{} elements", screen.elements.len())),
566                );
567            }
568            Ok(_) => checks.push(Check::new("accessibility_tree", true).status("fail").action(
569                "폰 화면이 켜져 있는지 확인하고 다시 시도하세요.",
570                "Make sure the phone's screen is on and try again.",
571            )),
572            Err(f) => checks.push(
573                Check::new("accessibility_tree", true)
574                    .status("fail")
575                    .detail(f.message)
576                    .action(
577                        "폰 화면이 켜져 있는지 확인하고 다시 시도하세요.",
578                        "Make sure the phone's screen is on and try again.",
579                    ),
580            ),
581        }
582    } else if !tree_reported {
583        checks.push(skip("accessibility_tree", true, "Settings is not in front"));
584    }
585
586    // 8. Touch input really lands: scroll Settings down one step and back.
587    if args.no_touch_test {
588        checks.push(skip("touch_input", true, "--no-touch-test"));
589    } else if tree_ok {
590        // Down and back; if down does nothing (the list may be at its end, or
591        // the first drag of a new session was lost), up and back.
592        let mut verdict: Option<Check> = None;
593        let mut last_detail = String::new();
594        for (there, back) in [("down", "up"), ("up", "down")] {
595            let moved = s
596                .cmd_scroll(ScrollArgs { direction: there.into(), until: None, max: None })
597                .await;
598            match &moved {
599                Ok(r) if r.get("screen_changed").and_then(|v| v.as_bool()) == Some(true) => {
600                    // Put the list back where it was.
601                    let _ = s
602                        .cmd_scroll(ScrollArgs { direction: back.into(), until: None, max: None })
603                        .await;
604                    let mut check = Check::new("touch_input", true);
605                    if there == "up" {
606                        check = check.detail("the first drag did not move the screen; the second did");
607                    }
608                    verdict = Some(check);
609                    break;
610                }
611                Ok(_) => last_detail = "the drags were sent but the screen did not move".to_string(),
612                Err(f) => last_detail = f.message.clone(),
613            }
614        }
615        checks.push(verdict.unwrap_or_else(|| {
616            Check::new("touch_input", true).status("fail").detail(last_detail).action(
617                "설정 → 개발자 → 'UI 자동화 활성화'를 켜고 다시 시도하세요. 그래도 안 되면 폰을 재시동하세요.",
618                "Turn on Settings → Developer → Enable UI Automation and try again. If it still fails, restart the phone.",
619            )
620        }));
621    } else {
622        checks.push(skip("touch_input", true, "no accessibility tree"));
623    }
624
625    // 9. Auto-lock (recommended). Not read from the phone: just advice.
626    checks.push(Check::new("auto_lock", false).status("info").action(
627        "오래 쓸 때는 설정 → 디스플레이 및 밝기 → 자동 잠금 → '안 함'을 권합니다. 폰이 잠기면 읽기와 입력이 멈춥니다.",
628        "For long sessions set Settings → Display & Brightness → Auto-Lock → Never. Reading and input stop when the phone locks.",
629    ));
630
631    // 10. Do Not Disturb that `iph dnd on` left on. The phone's Focus is not
632    // touched here.
633    if let Some(left) = &s.dnd.record {
634        checks.push(
635            Check::new("do_not_disturb", false)
636                .status("info")
637                .detail(format!("on since {}, set by iph", left.at))
638                .action(
639                    "`iph dnd on`으로 켠 방해금지 모드가 켜져 있습니다. `iph dnd off`로 원래대로 되돌릴 수 있습니다.",
640                    "Do Not Disturb from `iph dnd on` is on. `iph dnd off` puts the earlier Focus back.",
641                ),
642        );
643    }
644
645    let ok = checks
646        .iter()
647        .all(|c| !c.required || c.status == "ok");
648    let failing: Vec<Value> = checks
649        .iter()
650        .filter(|c| c.required && c.status != "ok")
651        .map(|c| json!(c.check))
652        .collect();
653    Ok(fields! {
654        "ready": ok,
655        "udid": s.udid.clone(),
656        "connection": connection,
657        "failing": failing,
658        "checks": checks,
659    })
660}
661
662#[cfg(test)]
663mod tests {
664    use super::*;
665
666    fn wireless(values: [Option<bool>; 4]) -> wifi::Wireless {
667        wifi::Wireless { values, ..Default::default() }
668    }
669
670    #[test]
671    fn disabled_wireless_flags_are_named_instead_of_blame_on_the_wifi() {
672        for values in [[true, false], [false, true], [false, false]] {
673            let state = wireless([Some(true), Some(true), Some(values[0]), Some(values[1])]);
674            let c = wifi_check(Some("usb"), Some(&state), Ok(false));
675            assert_eq!((c.status, c.required, c.auto_fixed), ("warn", false, false));
676            let action = c.user_action.unwrap();
677            for (i, key) in ["EnableWifiConnections", "EnableWifiDebugging"].iter().enumerate() {
678                if !values[i] { assert!(action.contains(key), "{action}"); }
679            }
680            assert!(action.contains("iph setup --fix-wifi") && action.contains("iph doctor --fix-wifi"));
681            assert!(action.contains("Finder") && action.contains("Connect via network"));
682            assert!(!action.contains("AP/") && !action.contains("mDNS"), "{action}");
683        }
684    }
685
686    #[test]
687    fn enabled_flags_without_network_point_to_subnet_isolation_and_mdns() {
688        let state = wireless([Some(true); 4]);
689        let c = wifi_check(Some("usb"), Some(&state), Ok(false));
690        assert_eq!(c.status, "warn");
691        let action = c.user_action.unwrap();
692        assert!(action.contains("EnableWifiConnections") && action.contains("EnableWifiDebugging"));
693        assert!(action.contains("AP/") && action.contains("_apple-mobdev2._tcp.local."));
694        let c = wifi_check(Some("usb"), Some(&state), Err("ListDevices timed out".into()));
695        assert!(c.detail.unwrap().contains("ListDevices timed out"));
696        assert!(!c.user_action.unwrap().contains("AP/"));
697    }
698
699    #[test]
700    fn unknown_or_unsupported_flags_are_not_called_disabled() {
701        let c = wifi_check(Some("usb"), Some(&wireless([None; 4])), Ok(false));
702        assert_eq!(c.status, "warn");
703        assert!(c.detail.unwrap().contains("EnableWifiDebugging=unknown"));
704        let c = wifi_check(Some("usb"), Some(&wireless([Some(false); 4])), Ok(false));
705        assert!(c.user_action.unwrap().contains("SupportsWifi"));
706        assert!(!c.auto_fixed);
707    }
708
709    #[test]
710    fn fixing_flags_does_not_pass_wifi_until_network_is_observed() {
711        let mut state = wireless([Some(true); 4]);
712        state.changed = vec!["EnableWifiDebugging"];
713        let c = wifi_check(Some("usb"), Some(&state), Ok(false));
714        assert_eq!(c.status, "warn");
715        assert!(c.auto_fixed);
716        let c = wifi_check(Some("usb"), Some(&state), Ok(true));
717        assert_eq!(c.status, "ok");
718        assert!(c.auto_fixed);
719        assert!(c.detail.as_ref().unwrap().contains("reachable over Wi-Fi as well as USB"));
720        let output = json!({ "ok": true, "ready": true, "checks": [c] });
721        assert_eq!(output["checks"][0]["auto_fixed"], true);
722        let human = crate::human::render("doctor", &output);
723        assert!(human.contains('✓') && human.contains("EnableWifiDebugging=true"));
724        assert!(human.contains("enabled and read back: EnableWifiDebugging"));
725    }
726
727    fn says(checks: &[Check]) -> String {
728        checks
729            .iter()
730            .map(|c| format!("{} {} {}", c.check, c.status, c.user_action.as_deref().unwrap_or("")))
731            .collect::<Vec<_>>()
732            .join("\n")
733    }
734
735    #[test]
736    fn an_unreadable_screen_on_an_unlocked_phone_is_not_called_a_lock() {
737        // 2026-11-11: lockdown said unlocked, the launch could not be seen in
738        // front because no reading came, and doctor said "unlock the phone".
739        let (checks, front) = front_checks(
740            Some(false),
741            Some(Ok(false)),
742            Some(Err("no accessibility tree within 14000 ms (3 empty, 0 not understood)".into())),
743        );
744        let text = says(&checks);
745        assert!(!front);
746        assert!(!text.contains("잠금을 풀") && !text.contains("Unlock"), "{text}");
747        assert!(text.contains("screen_unlocked ok"), "{text}");
748        assert!(text.contains("accessibility_tree fail"), "{text}");
749        // Lockdown not answering is no reason to call it a lock either.
750        let (checks, _) = front_checks(None, Some(Ok(false)), Some(Err("ax_timeout".into())));
751        let text = says(&checks);
752        assert!(!text.contains("잠금을 풀") && !text.contains("Unlock"), "{text}");
753        assert!(text.contains("accessibility_tree fail"), "{text}");
754    }
755
756    #[test]
757    fn only_lockdown_makes_it_a_lock() {
758        let (checks, front) = front_checks(Some(true), None, None);
759        assert!(!front);
760        assert_eq!(checks.len(), 1);
761        assert_eq!(checks[0].check, "screen_unlocked");
762        assert_eq!(checks[0].status, "fail");
763        assert!(checks[0].user_action.is_some());
764    }
765
766    #[test]
767    fn another_screen_in_front_is_said_as_such() {
768        let (checks, front) = front_checks(Some(false), Some(Ok(false)), Some(Ok(false)));
769        let text = says(&checks);
770        assert!(!front);
771        assert!(text.contains("settings_in_front fail"), "{text}");
772        assert!(!text.contains("잠금을 풀") && !text.contains("Unlock"), "{text}");
773    }
774
775    #[test]
776    fn settings_in_front_passes() {
777        assert!(front_checks(Some(false), Some(Ok(true)), None).1);
778        // Seen only on the reading after the launch.
779        assert!(front_checks(None, Some(Ok(false)), Some(Ok(true))).1);
780    }
781}