1use 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 pub no_touch_test: bool,
34 pub fix_wifi: bool,
37}
38
39#[derive(Debug, Clone, Serialize)]
40pub struct Check {
41 pub check: &'static str,
42 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 locked: Option<bool>,
96}
97
98async fn lockdown_facts(provider: &dyn IdeviceProvider) -> LockdownFacts {
100 let mut facts = LockdownFacts { developer_mode: None, locked: None };
101 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
125async 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
146async 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
210fn 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 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 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) {
318 return c.detail(detail.join("; "));
319 }
320 if connection == Some("wifi") && network == Ok(false) {
321 detail.push("direct IP route selected; reachability is checked by the required checks".into());
322 return c.status("info").detail(detail.join("; "));
323 }
324 c = c.status("warn").detail(detail.join("; "));
325 if network.is_err() {
326 return c.action(
327 "usbmuxd에서 무선 연결 목록을 확인하지 못했습니다. 컴퓨터의 Apple 기기 연결 서비스와 USB 연결을 확인하고 `iph doctor`를 다시 실행하세요.",
328 "Could not query wireless connections from usbmuxd. Check the computer's Apple device service and USB connection, then run `iph doctor` again.",
329 );
330 }
331 match state {
332 Some(state) if state.enabled() => c.action(
333 "EnableWifiConnections와 EnableWifiDebugging은 모두 켜져 있지만 usbmuxd에 Network 연결이 없습니다. 폰과 컴퓨터가 같은 LAN에 있는지, 공유기의 AP/클라이언트 격리가 꺼져 있는지, mDNS/Bonjour(_apple-mobdev2._tcp.local.)가 차단되지 않는지 확인하세요. 폰 IP를 알면 `iph --udid <UDID> connect --ip <폰 IP>`로 직접 등록할 수 있습니다. 설정 직후라면 잠시 뒤 `iph doctor`를 다시 실행하세요.",
334 "EnableWifiConnections and EnableWifiDebugging are both on, but usbmuxd has no Network connection. Check the same LAN, AP/client isolation, and whether mDNS/Bonjour (_apple-mobdev2._tcp.local.) is blocked. If the phone IP is known, register it with `iph --udid <UDID> connect --ip <phone IP>`. If just enabled, run `iph doctor` again shortly.",
335 ),
336 _ => c.action(
337 "기기의 무선 플래그를 확인하지 못했습니다(원인은 detail 참고). USB로 연결하고 잠금을 풀어 '이 컴퓨터를 신뢰'를 확인한 뒤 `iph doctor`를 다시 실행하세요. 무선 설정은 Finder/Apple 기기 앱과 Xcode의 'Connect via network'에서도 확인할 수 있습니다.",
338 "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\".",
339 ),
340 }
341}
342
343async fn check_wifi(udid: &str, connection: Option<&str>, fix: bool) -> Check {
344 let all = match tokio::time::timeout(Duration::from_secs(3), conn::list_raw()).await {
345 Ok(Ok(all)) => all,
346 Ok(Err(e)) => return wifi_check(connection, None, Err(format!("{e:#}"))),
347 Err(_) => return wifi_check(connection, None, Err("ListDevices timed out".into())),
348 };
349 let mut network = Ok(wifi::has_network(&all, udid));
350 let mut state = None;
351 if let Some(usb) = wifi::usb_device(&all, udid) {
352 let addr = match conn::mux_addr() {
353 Ok(addr) => addr,
354 Err(e) => return wifi_check(connection, None, Err(format!("{e:#}"))),
355 };
356 let provider = usb.to_provider(addr, conn::LABEL);
357 state = Some(wifi::inspect(&provider, fix).await);
358 if fix && network == Ok(false)
359 && state.as_ref().is_some_and(|s| s.enabled() || !s.changed.is_empty()) {
360 network = wifi::discover(udid).await;
361 }
362 }
363 if connection.is_none() && state.is_none() && network == Ok(false) {
364 return Check::new("wifi", false).status("skipped").detail("phone not reachable");
365 }
366 wifi_check(connection, state.as_ref(), network)
367}
368
369pub async fn run(s: &mut Session, args: DoctorArgs) -> Res {
370 let mut checks: Vec<Check> = Vec::new();
371 let skip = |name: &'static str, required: bool, why: &str| {
372 Check::new(name, required).status("skipped").detail(why.to_string())
373 };
374
375 let paired = match conn::mux_connect().await {
377 Ok(mut mux) => with_timeout(mux.get_pair_record(&s.udid)).await.is_some_and(|r| r.is_ok()),
378 Err(_) => false,
379 };
380 checks.push(if paired {
381 Check::new("pairing", true)
382 } else {
383 Check::new("pairing", true).status("fail").action(
384 "USB로 연결하고 폰에서 '이 컴퓨터를 신뢰'를 누르세요.",
385 "Connect the phone by USB and tap \"Trust This Computer\" on it.",
386 )
387 });
388
389 let route = conn::route(&s.udid).await;
391 let connection = route.as_ref().ok().map(|r| r.connection.clone());
392 checks.push(match &route {
393 Ok(r) => Check::new("connection", true).detail(r.connection.clone()),
394 Err(e) => Check::new("connection", true)
395 .status("fail")
396 .detail(format!("{e:#}"))
397 .action(
398 "폰을 USB로 연결하거나 컴퓨터와 같은 LAN에 두고 화면을 켜 주세요. USB로 신뢰한 폰이 자동 검색되지 않으면 `iph --udid <UDID> connect --ip <폰 IP>`로 직접 주소를 등록할 수 있습니다.",
399 "Plug the phone in, or put it on the same LAN and wake its screen. If a USB-paired phone is not discovered, register its address with `iph --udid <UDID> connect --ip <phone IP>`.",
400 ),
401 });
402
403 let wifi = check_wifi(&s.udid, connection.as_deref(), args.fix_wifi).await;
406
407 let facts = match &route {
409 Ok(r) => Some(lockdown_facts(&*r.provider).await),
410 Err(_) => None,
411 };
412 let dev_mode = facts.as_ref().and_then(|f| f.developer_mode);
413 checks.push(match dev_mode {
414 Some(true) => Check::new("developer_mode", true),
415 Some(false) => {
416 let mut revealed = false;
417 if let Ok(r) = &route
418 && let Some(Ok(mut amfi)) = with_timeout(AmfiClient::connect(&*r.provider)).await {
419 revealed = with_timeout(amfi.reveal_developer_mode_option_in_ui())
420 .await
421 .is_some_and(|r| r.is_ok());
422 }
423 let mut c = Check::new("developer_mode", true).status("fail").action(
424 "설정 → 개인정보 보호 및 보안 → 개발자 모드 → 켜기 → 재시동 후 비밀번호를 입력하세요.",
425 "Settings → Privacy & Security → Developer Mode → turn on → restart, then enter the passcode.",
426 );
427 c.auto_fixed = revealed;
428 if revealed {
429 c = c.detail("the Developer Mode switch was made visible in Settings");
430 }
431 c
432 }
433 None if route.is_ok() => Check::new("developer_mode", true)
434 .status("warn")
435 .detail("could not ask the phone; judged by the services below"),
436 None => skip("developer_mode", true, "phone not reachable"),
437 });
438
439 let mut services_ok = false;
441 if route.is_ok() && dev_mode != Some(false) {
442 let mut missing = missing_services(s).await;
443 let mut mounted_from = None;
444 let mut mount_note = None;
445 if matches!(&missing, Ok(m) if !m.is_empty()) {
446 let cryptex = match s.ensure_tunnel().await {
450 Ok(tunnel) => match tokio::time::timeout(Duration::from_secs(300), crate::ddi::install(tunnel)).await {
451 Ok(r) => r,
452 Err(_) => Err(anyhow::anyhow!("timed out")),
453 },
454 Err(f) => Err(anyhow::anyhow!(f.message)),
455 };
456 match cryptex {
457 Ok(source) => mounted_from = Some(source),
458 Err(e) => {
459 let mut note = format!("cryptex install failed: {e:#}");
460 if let Ok(r) = &route {
461 match tokio::time::timeout(Duration::from_secs(180), mount_ddi(&*r.provider)).await {
462 Ok(Ok(())) => mounted_from = Some("Xcode".to_string()),
463 Ok(Err(e)) => note.push_str(&format!("; image mounter: {e:#}")),
464 Err(_) => note.push_str("; image mounter timed out"),
465 }
466 }
467 if mounted_from.is_none() {
468 mount_note = Some(note);
469 }
470 }
471 }
472 if mounted_from.is_some() {
473 s.reset();
474 tokio::time::sleep(Duration::from_secs(2)).await;
475 missing = missing_services(s).await;
476 }
477 }
478 let mounted_now = mounted_from.is_some();
479 match missing {
480 Ok(m) if m.is_empty() => {
481 services_ok = true;
482 let mut c = Check::new("developer_disk_image", true);
483 c.auto_fixed = mounted_now;
484 if let Some(from) = &mounted_from {
485 c = c.detail(format!("installed the developer disk image ({from})"));
486 }
487 checks.push(c);
488 }
489 Ok(m) => {
490 let mut detail = format!("missing services: {}", m.join(", "));
491 if let Some(note) = mount_note {
492 detail.push_str("; ");
493 detail.push_str(¬e);
494 }
495 checks.push(Check::new("developer_disk_image", true).status("fail").detail(detail).action(
496 "개발자 디스크 이미지를 연결하지 못했습니다. 인터넷 연결(애플 서명 서버, GitHub)을 확인하고 다시 `iph doctor`를 실행하세요. 맥이라면 Xcode의 창 → 기기 및 시뮬레이터에서 이 폰을 한 번 골라도 됩니다.",
497 "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.",
498 ));
499 }
500 Err(message) => checks.push(
501 Check::new("developer_disk_image", true)
502 .status("fail")
503 .detail(message)
504 .action(
505 "폰 잠금을 풀고 다시 시도하세요. 계속 실패하면 USB로 연결하세요.",
506 "Unlock the phone and try again. If it keeps failing, connect by USB.",
507 ),
508 ),
509 }
510 } else {
511 checks.push(skip(
512 "developer_disk_image",
513 true,
514 if route.is_ok() { "Developer Mode is off" } else { "phone not reachable" },
515 ));
516 }
517
518 checks.push(wifi);
520
521 let locked = facts.as_ref().and_then(|f| f.locked);
527 let mut front_ok = false;
528 let mut tree_reported = false;
529 if locked == Some(true) || services_ok {
530 let launched = if locked == Some(true) {
531 None
532 } else {
533 Some(match s.cmd_launch(LaunchArgs { app: SETTINGS.into(), restart: false }).await {
534 Ok(r) => Ok((
535 r.get("foreground").and_then(|v| v.as_bool()) == Some(true),
536 r.get("pid").and_then(|v| v.as_i64()),
537 )),
538 Err(f) => Err(f.message),
539 })
540 };
541 let read = match &launched {
543 None | Some(Ok((true, _))) => None,
544 Some(other) => {
545 let pid = other.as_ref().ok().and_then(|(_, pid)| *pid);
546 Some(match s.screen(Fresh::Force, false, BuildOptions::default()).await {
547 Ok((_, screen)) => Ok(pid.is_some_and(|p| screen.apps.iter().any(|a| a.pid == p))),
548 Err(f) => Err(f.message),
549 })
550 }
551 };
552 let launched = launched.map(|l| l.map(|(front, _)| front));
553 let (found, front) = front_checks(locked, launched, read);
554 tree_reported = found.iter().any(|c| c.check == "accessibility_tree");
555 front_ok = front;
556 checks.extend(found);
557 } else {
558 checks.push(skip("screen_unlocked", true, "developer services unavailable"));
559 }
560
561 let mut tree_ok = false;
563 if front_ok {
564 match s.screen(Fresh::Force, false, BuildOptions::default()).await {
565 Ok((_, screen)) if screen.elements.len() > 1 => {
566 tree_ok = true;
567 checks.push(
568 Check::new("accessibility_tree", true)
569 .detail(format!("{} elements", screen.elements.len())),
570 );
571 }
572 Ok(_) => checks.push(Check::new("accessibility_tree", true).status("fail").action(
573 "폰 화면이 켜져 있는지 확인하고 다시 시도하세요.",
574 "Make sure the phone's screen is on and try again.",
575 )),
576 Err(f) => checks.push(
577 Check::new("accessibility_tree", true)
578 .status("fail")
579 .detail(f.message)
580 .action(
581 "폰 화면이 켜져 있는지 확인하고 다시 시도하세요.",
582 "Make sure the phone's screen is on and try again.",
583 ),
584 ),
585 }
586 } else if !tree_reported {
587 checks.push(skip("accessibility_tree", true, "Settings is not in front"));
588 }
589
590 if args.no_touch_test {
592 checks.push(skip("touch_input", true, "--no-touch-test"));
593 } else if tree_ok {
594 let mut verdict: Option<Check> = None;
597 let mut last_detail = String::new();
598 for (there, back) in [("down", "up"), ("up", "down")] {
599 let moved = s
600 .cmd_scroll(ScrollArgs { direction: there.into(), until: None, max: None })
601 .await;
602 match &moved {
603 Ok(r) if r.get("screen_changed").and_then(|v| v.as_bool()) == Some(true) => {
604 let _ = s
606 .cmd_scroll(ScrollArgs { direction: back.into(), until: None, max: None })
607 .await;
608 let mut check = Check::new("touch_input", true);
609 if there == "up" {
610 check = check.detail("the first drag did not move the screen; the second did");
611 }
612 verdict = Some(check);
613 break;
614 }
615 Ok(_) => last_detail = "the drags were sent but the screen did not move".to_string(),
616 Err(f) => last_detail = f.message.clone(),
617 }
618 }
619 checks.push(verdict.unwrap_or_else(|| {
620 Check::new("touch_input", true).status("fail").detail(last_detail).action(
621 "설정 → 개발자 → 'UI 자동화 활성화'를 켜고 다시 시도하세요. 그래도 안 되면 폰을 재시동하세요.",
622 "Turn on Settings → Developer → Enable UI Automation and try again. If it still fails, restart the phone.",
623 )
624 }));
625 } else {
626 checks.push(skip("touch_input", true, "no accessibility tree"));
627 }
628
629 checks.push(Check::new("auto_lock", false).status("info").action(
631 "오래 쓸 때는 설정 → 디스플레이 및 밝기 → 자동 잠금 → '안 함'을 권합니다. 폰이 잠기면 읽기와 입력이 멈춥니다.",
632 "For long sessions set Settings → Display & Brightness → Auto-Lock → Never. Reading and input stop when the phone locks.",
633 ));
634
635 if let Some(left) = &s.dnd.record {
638 checks.push(
639 Check::new("do_not_disturb", false)
640 .status("info")
641 .detail(format!("on since {}, set by iph", left.at))
642 .action(
643 "`iph dnd on`으로 켠 방해금지 모드가 켜져 있습니다. `iph dnd off`로 원래대로 되돌릴 수 있습니다.",
644 "Do Not Disturb from `iph dnd on` is on. `iph dnd off` puts the earlier Focus back.",
645 ),
646 );
647 }
648
649 let ok = checks
650 .iter()
651 .all(|c| !c.required || c.status == "ok");
652 let failing: Vec<Value> = checks
653 .iter()
654 .filter(|c| c.required && c.status != "ok")
655 .map(|c| json!(c.check))
656 .collect();
657 Ok(fields! {
658 "ready": ok,
659 "udid": s.udid.clone(),
660 "connection": connection,
661 "failing": failing,
662 "checks": checks,
663 })
664}
665
666#[cfg(test)]
667mod tests {
668 use super::*;
669
670 fn wireless(values: [Option<bool>; 4]) -> wifi::Wireless {
671 wifi::Wireless { values, ..Default::default() }
672 }
673
674 #[test]
675 fn direct_wifi_route_does_not_claim_that_discovery_was_fixed() {
676 let c = wifi_check(Some("wifi"), None, Ok(false));
677 assert_eq!(c.status, "info");
678 assert!(!c.auto_fixed);
679 assert!(c.user_action.is_none());
680 let detail = c.detail.unwrap();
681 assert!(detail.contains("no usbmuxd Network entry"));
682 assert!(detail.contains("direct IP route selected"));
683 }
684
685 #[test]
686 fn disabled_wireless_flags_are_named_instead_of_blame_on_the_wifi() {
687 for values in [[true, false], [false, true], [false, false]] {
688 let state = wireless([Some(true), Some(true), Some(values[0]), Some(values[1])]);
689 let c = wifi_check(Some("usb"), Some(&state), Ok(false));
690 assert_eq!((c.status, c.required, c.auto_fixed), ("warn", false, false));
691 let action = c.user_action.unwrap();
692 for (i, key) in ["EnableWifiConnections", "EnableWifiDebugging"].iter().enumerate() {
693 if !values[i] { assert!(action.contains(key), "{action}"); }
694 }
695 assert!(action.contains("iph setup --fix-wifi") && action.contains("iph doctor --fix-wifi"));
696 assert!(action.contains("Finder") && action.contains("Connect via network"));
697 assert!(!action.contains("AP/") && !action.contains("mDNS"), "{action}");
698 }
699 }
700
701 #[test]
702 fn enabled_flags_without_network_point_to_subnet_isolation_and_mdns() {
703 let state = wireless([Some(true); 4]);
704 let c = wifi_check(Some("usb"), Some(&state), Ok(false));
705 assert_eq!(c.status, "warn");
706 let action = c.user_action.unwrap();
707 assert!(action.contains("EnableWifiConnections") && action.contains("EnableWifiDebugging"));
708 assert!(action.contains("AP/") && action.contains("_apple-mobdev2._tcp.local."));
709 let c = wifi_check(Some("usb"), Some(&state), Err("ListDevices timed out".into()));
710 assert!(c.detail.unwrap().contains("ListDevices timed out"));
711 assert!(!c.user_action.unwrap().contains("AP/"));
712 }
713
714 #[test]
715 fn unknown_or_unsupported_flags_are_not_called_disabled() {
716 let c = wifi_check(Some("usb"), Some(&wireless([None; 4])), Ok(false));
717 assert_eq!(c.status, "warn");
718 assert!(c.detail.unwrap().contains("EnableWifiDebugging=unknown"));
719 let c = wifi_check(Some("usb"), Some(&wireless([Some(false); 4])), Ok(false));
720 assert!(c.user_action.unwrap().contains("SupportsWifi"));
721 assert!(!c.auto_fixed);
722 }
723
724 #[test]
725 fn fixing_flags_does_not_pass_wifi_until_network_is_observed() {
726 let mut state = wireless([Some(true); 4]);
727 state.changed = vec!["EnableWifiDebugging"];
728 let c = wifi_check(Some("usb"), Some(&state), Ok(false));
729 assert_eq!(c.status, "warn");
730 assert!(c.auto_fixed);
731 let c = wifi_check(Some("usb"), Some(&state), Ok(true));
732 assert_eq!(c.status, "ok");
733 assert!(c.auto_fixed);
734 assert!(c.detail.as_ref().unwrap().contains("reachable over Wi-Fi as well as USB"));
735 let output = json!({ "ok": true, "ready": true, "checks": [c] });
736 assert_eq!(output["checks"][0]["auto_fixed"], true);
737 let human = crate::human::render("doctor", &output);
738 assert!(human.contains('✓') && human.contains("EnableWifiDebugging=true"));
739 assert!(human.contains("enabled and read back: EnableWifiDebugging"));
740 }
741
742 fn says(checks: &[Check]) -> String {
743 checks
744 .iter()
745 .map(|c| format!("{} {} {}", c.check, c.status, c.user_action.as_deref().unwrap_or("")))
746 .collect::<Vec<_>>()
747 .join("\n")
748 }
749
750 #[test]
751 fn an_unreadable_screen_on_an_unlocked_phone_is_not_called_a_lock() {
752 let (checks, front) = front_checks(
755 Some(false),
756 Some(Ok(false)),
757 Some(Err("no accessibility tree within 14000 ms (3 empty, 0 not understood)".into())),
758 );
759 let text = says(&checks);
760 assert!(!front);
761 assert!(!text.contains("잠금을 풀") && !text.contains("Unlock"), "{text}");
762 assert!(text.contains("screen_unlocked ok"), "{text}");
763 assert!(text.contains("accessibility_tree fail"), "{text}");
764 let (checks, _) = front_checks(None, Some(Ok(false)), Some(Err("ax_timeout".into())));
766 let text = says(&checks);
767 assert!(!text.contains("잠금을 풀") && !text.contains("Unlock"), "{text}");
768 assert!(text.contains("accessibility_tree fail"), "{text}");
769 }
770
771 #[test]
772 fn only_lockdown_makes_it_a_lock() {
773 let (checks, front) = front_checks(Some(true), None, None);
774 assert!(!front);
775 assert_eq!(checks.len(), 1);
776 assert_eq!(checks[0].check, "screen_unlocked");
777 assert_eq!(checks[0].status, "fail");
778 assert!(checks[0].user_action.is_some());
779 }
780
781 #[test]
782 fn another_screen_in_front_is_said_as_such() {
783 let (checks, front) = front_checks(Some(false), Some(Ok(false)), Some(Ok(false)));
784 let text = says(&checks);
785 assert!(!front);
786 assert!(text.contains("settings_in_front fail"), "{text}");
787 assert!(!text.contains("잠금을 풀") && !text.contains("Unlock"), "{text}");
788 }
789
790 #[test]
791 fn settings_in_front_passes() {
792 assert!(front_checks(Some(false), Some(Ok(true)), None).1);
793 assert!(front_checks(None, Some(Ok(false)), Some(Ok(true))).1);
795 }
796}