thermark 0.33.0

Local sticker printing for pocket thermal printers over BLE/USB — QR links, inventory tags, badges, photos; no vendor app
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
//! Environment + printer readiness checks (`thermark doctor`).

use crate::config::ConnPref;
use crate::errors::Result;
use crate::print_task::PrintTask;
use crate::printer::{Heartbeat, RfidInfo};
use crate::profile::{PROFILES, SupportStatus};
use crate::protocol::Model;
use serde::Serialize;
use std::fmt;

use crate::transport::BleMatchMode;
// Only a transport actually talks to a printer, so with both features off these
// are dead. Gated rather than `#[allow(unused)]` so a genuinely unused import
// still gets reported.
#[cfg(any(feature = "ble", feature = "serial", test))]
use crate::printer::PrinterClient;
#[cfg(any(feature = "ble", feature = "serial", test))]
use crate::transport::Transport;
#[cfg(feature = "ble")]
use std::time::Duration;

#[cfg(feature = "serial")]
use crate::transport::SerialTransport;
#[cfg(feature = "ble")]
use crate::transport::{self, BleTransport};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum CheckStatus {
    Pass,
    Warn,
    Fail,
}

impl CheckStatus {
    pub fn icon(self) -> &'static str {
        match self {
            Self::Pass => "ok",
            Self::Warn => "warn",
            Self::Fail => "FAIL",
        }
    }

    pub fn worse(self, other: Self) -> Self {
        use CheckStatus::*;
        match (self, other) {
            (Fail, _) | (_, Fail) => Fail,
            (Warn, _) | (_, Warn) => Warn,
            _ => Pass,
        }
    }
}

#[derive(Debug, Clone)]
pub struct Check {
    pub name: String,
    pub status: CheckStatus,
    pub detail: String,
}

impl Check {
    pub fn new(name: impl Into<String>, status: CheckStatus, detail: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            status,
            detail: detail.into(),
        }
    }

    pub fn pass(name: impl Into<String>, detail: impl Into<String>) -> Self {
        Self::new(name, CheckStatus::Pass, detail)
    }

    pub fn warn(name: impl Into<String>, detail: impl Into<String>) -> Self {
        Self::new(name, CheckStatus::Warn, detail)
    }

    pub fn fail(name: impl Into<String>, detail: impl Into<String>) -> Self {
        Self::new(name, CheckStatus::Fail, detail)
    }
}

/// Classify one optional sensor reading into a [`Check`].
///
/// The heartbeat sensors differ only in which value is good and what to say
/// about it, so the `Option<u8>` match shape lives here once. `classify`
/// returning `None` means "value outside the documented range".
fn sensor_check(
    name: &'static str,
    value: Option<u8>,
    classify: impl Fn(u8) -> Option<(CheckStatus, String)>,
) -> Check {
    match value {
        Some(v) => match classify(v) {
            Some((status, detail)) => Check::new(name, status, detail),
            None => Check::warn(name, format!("unexpected {name} state {v}")),
        },
        None => Check::warn(name, "not reported in heartbeat"),
    }
}

impl fmt::Display for Check {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "[{:<4}] {:<22} {}",
            self.status.icon(),
            self.name,
            self.detail
        )
    }
}

#[derive(Debug, Clone)]
pub struct DoctorReport {
    pub checks: Vec<Check>,
}

#[derive(Serialize)]
struct SupportCheck {
    name: &'static str,
    status: CheckStatus,
}

#[derive(Serialize)]
struct SupportReport {
    schema_version: u8,
    thermark_version: &'static str,
    os: &'static str,
    arch: &'static str,
    features: Vec<&'static str>,
    overall: CheckStatus,
    privacy: &'static str,
    checks: Vec<SupportCheck>,
}

/// A report may be assembled by library callers, so even check names cannot
/// be trusted as public-safe text. Unknown names keep their status under a
/// fixed label rather than passing arbitrary strings into the JSON.
fn support_check_name(name: &str) -> &'static str {
    match name {
        "thermark" => "thermark",
        "print_task" => "print_task",
        "fonts" => "fonts",
        "serial_ports" => "serial_ports",
        "bluetooth" => "bluetooth",
        "ble_scan" => "ble_scan",
        "ble_session" => "ble_session",
        "ble_connect" => "ble_connect",
        "ble_disconnect" => "ble_disconnect",
        "heartbeat" => "heartbeat",
        "cover" => "cover",
        "paper" => "paper",
        "rfid" => "rfid",
        "battery" => "battery",
        "rfid_tag" => "rfid_tag",
        "serial" => "serial",
        "support_matrix" => "support_matrix",
        "usb_open" => "usb_open",
        "usb" => "usb",
        _ => "other",
    }
}

impl DoctorReport {
    pub fn overall(&self) -> CheckStatus {
        self.checks
            .iter()
            .map(|c| c.status)
            .fold(CheckStatus::Pass, CheckStatus::worse)
    }

    pub fn exit_code(&self) -> i32 {
        match self.overall() {
            CheckStatus::Pass | CheckStatus::Warn => 0,
            CheckStatus::Fail => 1,
        }
    }

    /// Serialize a support report that is safe to attach to a public issue.
    ///
    /// Check names and details are public library data, so only canonical
    /// names and statuses enter this report. The human-readable doctor output
    /// retains the full detail for local diagnosis.
    pub fn support_json_pretty(&self) -> serde_json::Result<String> {
        let features = [
            ("ble", cfg!(feature = "ble")),
            ("serial", cfg!(feature = "serial")),
        ]
        .into_iter()
        .filter_map(|(name, enabled)| enabled.then_some(name))
        .collect();

        let checks = self
            .checks
            .iter()
            .map(|check| SupportCheck {
                name: support_check_name(&check.name),
                status: check.status,
            })
            .collect();

        serde_json::to_string_pretty(&SupportReport {
            schema_version: 1,
            thermark_version: env!("CARGO_PKG_VERSION"),
            os: std::env::consts::OS,
            arch: std::env::consts::ARCH,
            features,
            overall: self.overall(),
            privacy: "printer identifiers and local paths omitted",
            checks,
        })
    }
}

impl fmt::Display for DoctorReport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "thermark doctor")?;
        writeln!(f, "---------------")?;
        for c in &self.checks {
            writeln!(f, "{c}")?;
        }
        writeln!(f)?;
        match self.overall() {
            CheckStatus::Pass => writeln!(f, "Overall: ok — ready to print (if labels loaded)"),
            CheckStatus::Warn => {
                writeln!(f, "Overall: warnings — printing may work; review above")
            }
            CheckStatus::Fail => writeln!(f, "Overall: FAIL — fix failures before printing"),
        }
    }
}

/// Interpret heartbeat for readiness (shared with tests).
pub fn evaluate_heartbeat(hb: &Heartbeat) -> Vec<Check> {
    use CheckStatus::{Fail, Pass, Warn};
    vec![
        sensor_check("cover", hb.closing_state, |v| match v {
            0 => Some((Pass, "closed (0)".into())),
            1 => Some((Fail, "open (1) — close the lid fully".into())),
            _ => None,
        }),
        sensor_check("paper", hb.paper_state, |v| match v {
            0 => Some((Pass, "detected (0)".into())),
            1 => Some((Fail, "not detected (1) — load labels, 2–5mm out".into())),
            _ => None,
        }),
        sensor_check("rfid", hb.rfid_read_state, |v| match v {
            1 => Some((Pass, "ok (1)".into())),
            0 => Some((
                Warn,
                "not ok (0) — third-party media may print poorly".into(),
            )),
            _ => None,
        }),
        sensor_check("battery", hb.power_level, |v| {
            // Wording comes from `describe_battery` so info and doctor agree.
            let text = crate::printer::describe_battery(v);
            match v {
                0 => Some((Fail, text)),
                1 => Some((Warn, text)),
                _ => Some((Pass, text)),
            }
        }),
    ]
}

pub fn evaluate_rfid(r: &RfidInfo) -> Check {
    if !r.tag_present {
        return Check::warn("rfid_tag", "no RFID tag data (ok for some media)");
    }
    Check::pass(
        "rfid_tag",
        format!(
            "barcode={} paper={}/{} type={}",
            if r.barcode.is_empty() {
                "-"
            } else {
                &r.barcode
            },
            r.used_paper,
            r.all_paper,
            r.consumables_type
        ),
    )
}

/// Report the task and connection a print would actually use, honouring an
/// explicit `--task`.
pub fn evaluate_print_task(model: Model, task: Option<PrintTask>, connection: ConnPref) -> Check {
    let Some(task) = task.or_else(|| PrintTask::for_model(model)) else {
        return Check::warn(
            "print_task",
            format!("model={model} has no verified default task"),
        );
    };
    let profile = crate::profile::profile_for_model(model);
    let support = profile.print_path_support(task, connection);
    let (status, label) = match support {
        SupportStatus::Tested => (CheckStatus::Pass, "hardware-tested"),
        SupportStatus::Experimental => (CheckStatus::Warn, "experimental"),
        SupportStatus::Unresolved => (CheckStatus::Warn, "unresolved"),
    };
    Check::new(
        "print_task",
        status,
        format!(
            "model={model} → task={task} over {connection} ({label}), max width {}px",
            profile.max_width_px
        ),
    )
}

/// Build a read-only diagnostic client, including for profiles whose print
/// task is unresolved. The fallback task is inert: doctor never sends print
/// commands, and connected support is evaluated only after identification.
#[cfg(any(feature = "ble", feature = "serial", test))]
fn diagnostic_client<T: Transport>(
    transport: T,
    configured_model: Model,
    explicit_task: Option<PrintTask>,
) -> PrinterClient<T> {
    let provisional_task = explicit_task
        .or_else(|| PrintTask::for_model(configured_model))
        .unwrap_or(PrintTask::B1);
    PrinterClient::new_with_task(transport, configured_model, provisional_task)
}

/// Identify connected hardware before claiming that its print path is tested.
#[cfg(any(feature = "ble", feature = "serial", test))]
async fn evaluate_connected_print_task<T: Transport>(
    client: &mut PrinterClient<T>,
    explicit_task: Option<PrintTask>,
    connection: ConnPref,
) -> Check {
    let identity = match client.identify_profile().await {
        Ok(identity) => identity,
        Err(error) => {
            return Check::fail(
                "print_task",
                format!("not evaluated — printer identity query failed: {error}"),
            );
        }
    };
    let model_id = identity.model_id;
    let detected_task = explicit_task.or_else(|| crate::profile::task_for_identity(&identity));
    let Some(profile) = client.apply_identity(&identity, explicit_task.is_none()) else {
        return Check::fail(
            "print_task",
            format!("not evaluated — printer model id {model_id} is not in the profile registry"),
        );
    };

    let mut check = evaluate_print_task(profile.model, detected_task, connection);
    check.detail = format!("detected model id {model_id}: {}", check.detail);
    check
}

#[cfg(any(feature = "ble", feature = "serial", test))]
fn replace_print_task_check(checks: &mut Vec<Check>, connected: Check) {
    if let Some(check) = checks.iter_mut().find(|check| check.name == "print_task") {
        *check = connected;
    } else {
        checks.push(connected);
    }
}

/// What to diagnose. `addr: None` means host-only checks (no connect).
#[derive(Debug, Clone, Default)]
pub struct DoctorOptions {
    pub addr: Option<String>,
    pub model: Model,
    pub task: Option<PrintTask>,
    pub scan_secs: u64,
    pub conn: ConnPref,
    pub match_mode: BleMatchMode,
}

/// Run diagnostic checks. Without an address, only host + scan checks run.
pub async fn run_doctor(opts: &DoctorOptions) -> Result<DoctorReport> {
    let DoctorOptions {
        model,
        scan_secs,
        match_mode,
        ..
    } = *opts;
    let addr = opts.addr.as_deref();
    let mut checks = Vec::new();

    // Build / crate
    checks.push(Check::pass(
        "thermark",
        format!("v{}", env!("CARGO_PKG_VERSION")),
    ));

    // Without a connection only the requested/configured profile is available.
    // Connected paths add this check after applying the detected identity.
    if addr.is_none() {
        checks.push(evaluate_print_task(model, opts.task, opts.conn));
    } else {
        checks.push(Check::fail(
            "print_task",
            "not evaluated — connected printer identity unavailable",
        ));
    }

    // Fonts
    let fonts = crate::font::list_available_fonts();
    if fonts.is_empty() {
        checks.push(Check::warn(
            "fonts",
            "no system TTF candidates found — pass --font",
        ));
    } else {
        checks.push(Check::pass(
            "fonts",
            format!("{} candidate(s), e.g. {}", fonts.len(), fonts[0].display()),
        ));
    }

    // Serial ports (informational)
    #[cfg(feature = "serial")]
    match SerialTransport::list_ports() {
        Ok(ports) if ports.is_empty() => checks.push(Check::warn(
            "serial_ports",
            "none listed (BLE-only is fine)",
        )),
        Ok(ports) => checks.push(Check::pass(
            "serial_ports",
            format!("{} port(s): {}", ports.len(), ports.join(", ")),
        )),
        Err(e) => checks.push(Check::warn("serial_ports", format!("could not list: {e}"))),
    }
    #[cfg(not(feature = "serial"))]
    checks.push(Check::warn(
        "serial_ports",
        "serial feature disabled at build time",
    ));

    match opts.conn {
        ConnPref::Ble => {
            doctor_ble(&mut checks, addr, model, opts.task, scan_secs, match_mode).await?;
        }
        ConnPref::Usb => {
            doctor_usb(&mut checks, addr, model, opts.task).await?;
        }
    }

    // Support matrix tip
    let tested: Vec<_> = PROFILES
        .iter()
        .filter_map(|profile| {
            (profile.support_status == SupportStatus::Tested)
                .then_some(profile.tested_connection)
                .flatten()
                .map(|connection| format!("{} over {connection}", profile.display_name))
        })
        .collect();
    checks.push(Check::pass(
        "support_matrix",
        format!(
            "hardware-tested paths: {} — run `thermark tasks`",
            tested.join(", ")
        ),
    ));

    Ok(DoctorReport { checks })
}

#[cfg(feature = "ble")]
async fn doctor_ble(
    checks: &mut Vec<Check>,
    addr: Option<&str>,
    model: Model,
    task: Option<PrintTask>,
    scan_secs: u64,
    match_mode: BleMatchMode,
) -> Result<()> {
    match transport::bluetooth_available().await {
        Ok(info) => checks.push(Check::pass("bluetooth", info)),
        Err(e) => {
            checks.push(Check::fail("bluetooth", format!("{e}")));
            return Ok(());
        }
    }

    let scan_for = Duration::from_secs(scan_secs.max(1));
    match BleTransport::scan(scan_for).await {
        Ok(devs) if devs.is_empty() => {
            checks.push(Check::fail(
                "ble_scan",
                format!("no printers in {scan_secs}s — power on, quit vendor apps, move closer"),
            ));
            #[cfg(all(target_os = "macos", feature = "serial"))]
            if let Some(selector) = addr
                && let Some(path) = transport::serial_port_for_selector(selector)
            {
                checks.push(Check::warn(
                    "ble_session",
                    format!(
                        "macOS exposes matching serial endpoint {path}; another Bluetooth client may own the printer. Disconnect it in Bluetooth settings and quit vendor apps before retrying BLE"
                    ),
                ));
            }
            if addr.is_none() {
                return Ok(());
            }
        }
        Ok(devs) => {
            let names: Vec<_> = devs.iter().map(|d| d.candidate.to_string()).collect();
            checks.push(Check::pass(
                "ble_scan",
                format!("{} device(s): {}", devs.len(), names.join("; ")),
            ));
        }
        Err(e) => {
            checks.push(Check::fail("ble_scan", format!("{e}")));
            return Ok(());
        }
    }

    if let Some(selector) = addr {
        match BleTransport::connect_with(selector, scan_for, match_mode).await {
            Ok(ble) => {
                checks.push(Check::pass(
                    "ble_connect",
                    format!("connected via '{selector}' ({match_mode:?})"),
                ));
                let mut client = diagnostic_client(ble, model, task);
                let print_task =
                    evaluate_connected_print_task(&mut client, task, ConnPref::Ble).await;
                replace_print_task_check(checks, print_task);
                match client.heartbeat().await {
                    Ok(hb) => {
                        checks.push(Check::pass("heartbeat", format!("{} bytes", hb.raw_len)));
                        checks.extend(evaluate_heartbeat(&hb));
                    }
                    Err(e) => checks.push(Check::fail("heartbeat", format!("{e}"))),
                }
                match client.rfid_info().await {
                    Ok(r) => checks.push(evaluate_rfid(&r)),
                    Err(e) => checks.push(Check::warn("rfid_tag", format!("query failed: {e}"))),
                }
                if let Ok(serial) = client
                    .get_info(crate::protocol::InfoKey::DeviceSerial)
                    .await
                {
                    checks.push(Check::pass("serial", serial.to_string()));
                }
                if let Err(e) = client.close().await {
                    checks.push(Check::warn("ble_disconnect", format!("{e}")));
                }
            }
            Err(e) => checks.push(Check::fail("ble_connect", format!("{e}"))),
        }
    } else {
        checks.push(Check::warn(
            "ble_connect",
            "skipped — pass -a \"PrinterName\" to test connect + sensors",
        ));
    }
    Ok(())
}

#[cfg(not(feature = "ble"))]
#[expect(
    clippy::unused_async,
    reason = "matches the async signature of the enabled transport diagnostic"
)]
async fn doctor_ble(
    checks: &mut Vec<Check>,
    _addr: Option<&str>,
    _model: Model,
    _task: Option<PrintTask>,
    _scan_secs: u64,
    _match_mode: BleMatchMode,
) -> Result<()> {
    checks.push(Check::fail(
        "bluetooth",
        "ble feature disabled at build time",
    ));
    Ok(())
}

#[cfg(feature = "serial")]
async fn doctor_usb(
    checks: &mut Vec<Check>,
    addr: Option<&str>,
    model: Model,
    task: Option<PrintTask>,
) -> Result<()> {
    let Some(path) = addr else {
        checks.push(Check::fail(
            "usb",
            "USB doctor requires -a /dev/cu.… (see thermark ports)",
        ));
        return Ok(());
    };
    match SerialTransport::open(path) {
        Ok(ser) => {
            checks.push(Check::pass("usb_open", path));
            let mut client = diagnostic_client(ser, model, task);
            let print_task = evaluate_connected_print_task(&mut client, task, ConnPref::Usb).await;
            replace_print_task_check(checks, print_task);
            match client.heartbeat().await {
                Ok(hb) => {
                    checks.push(Check::pass("heartbeat", format!("{} bytes", hb.raw_len)));
                    checks.extend(evaluate_heartbeat(&hb));
                }
                Err(e) => checks.push(Check::fail("heartbeat", format!("{e}"))),
            }
        }
        Err(e) => checks.push(Check::fail("usb_open", format!("{e}"))),
    }
    Ok(())
}

#[cfg(not(feature = "serial"))]
#[expect(
    clippy::unused_async,
    reason = "matches the async signature of the enabled transport diagnostic"
)]
async fn doctor_usb(
    checks: &mut Vec<Check>,
    _addr: Option<&str>,
    _model: Model,
    _task: Option<PrintTask>,
) -> Result<()> {
    checks.push(Check::fail("usb", "serial feature disabled at build time"));
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mock::MockTransport;
    use crate::printer::Heartbeat;

    #[test]
    fn support_json_keeps_results_and_omits_identifiers() {
        let report = DoctorReport {
            checks: vec![
                Check::pass("serial", "PRIVATE-SERIAL-123"),
                Check::pass("ble_connect", "connected via 'PRIVATE-PRINTER'"),
                Check::warn("battery", "PRIVATE-PATH-/Users/me/labels"),
                Check::fail("print_task", "identity query failed: PRIVATE-PRINTER"),
                Check::warn("PRIVATE-NAME", "PRIVATE-DETAIL"),
            ],
        };

        let body = report.support_json_pretty().unwrap();
        assert!(!body.contains("PRIVATE-SERIAL-123"));
        assert!(!body.contains("PRIVATE-PRINTER"));
        assert!(!body.contains("PRIVATE-PATH"));
        assert!(!body.contains("PRIVATE-NAME"));
        assert!(!body.contains("PRIVATE-DETAIL"));

        let json: serde_json::Value = serde_json::from_str(&body).unwrap();
        assert_eq!(json["schema_version"], 1);
        assert_eq!(json["overall"], "fail");
        assert_eq!(
            json["privacy"],
            "printer identifiers and local paths omitted"
        );
        assert_eq!(json["checks"][0]["name"], "serial");
        assert!(json["checks"][0].get("detail").is_none());
        assert_eq!(json["checks"][2]["name"], "battery");
        assert!(json["checks"][2].get("detail").is_none());
        assert_eq!(json["checks"][3]["status"], "fail");
        assert_eq!(json["checks"][4]["name"], "other");
    }

    #[test]
    fn heartbeat_ready_all_pass() {
        let hb = Heartbeat {
            closing_state: Some(0),
            power_level: Some(3),
            paper_state: Some(0),
            rfid_read_state: Some(1),
            raw_len: 13,
        };
        let checks = evaluate_heartbeat(&hb);
        assert!(checks.iter().all(|c| c.status == CheckStatus::Pass));
    }

    #[test]
    fn heartbeat_open_cover_fails() {
        let hb = Heartbeat {
            closing_state: Some(1),
            power_level: Some(3),
            paper_state: Some(0),
            rfid_read_state: Some(1),
            raw_len: 13,
        };
        let checks = evaluate_heartbeat(&hb);
        let cover = checks.iter().find(|c| c.name == "cover").unwrap();
        assert_eq!(cover.status, CheckStatus::Fail);
    }

    #[test]
    fn heartbeat_no_paper_fails() {
        let hb = Heartbeat {
            closing_state: Some(0),
            power_level: Some(2),
            paper_state: Some(1),
            rfid_read_state: Some(1),
            raw_len: 13,
        };
        let checks = evaluate_heartbeat(&hb);
        assert!(
            checks
                .iter()
                .any(|c| c.name == "paper" && c.status == CheckStatus::Fail)
        );
    }

    #[test]
    fn overall_fail_dominates() {
        let r = DoctorReport {
            checks: vec![
                Check::pass("a", String::new()),
                Check::fail("b", String::new()),
            ],
        };
        assert_eq!(r.overall(), CheckStatus::Fail);
        assert_eq!(r.exit_code(), 1);
    }

    #[test]
    fn print_task_b1_is_pass() {
        let c = evaluate_print_task(Model::B1, None, ConnPref::Ble);
        assert_eq!(c.status, CheckStatus::Pass);
    }

    #[test]
    fn b1_usb_path_is_not_reported_as_hardware_tested() {
        let c = evaluate_print_task(Model::B1, None, ConnPref::Usb);
        assert_eq!(c.status, CheckStatus::Warn);
        assert!(c.detail.contains("over usb"), "{}", c.detail);
        assert!(c.detail.contains("experimental"), "{}", c.detail);
    }

    #[test]
    fn b1_task_does_not_mark_an_experimental_profile_as_tested() {
        let c = evaluate_print_task(Model::B21Pro, Some(PrintTask::B1), ConnPref::Ble);
        assert_eq!(c.status, CheckStatus::Warn);
        assert!(c.detail.contains("experimental"));
    }

    #[tokio::test]
    async fn connected_task_support_uses_detected_profile_and_default_task() {
        let mut transport = MockTransport::new();
        transport.set_model_id(4097); // B1 Pro
        let mut client = diagnostic_client(transport, Model::B1, None);

        let check = evaluate_connected_print_task(&mut client, None, ConnPref::Ble).await;

        assert_eq!(check.name, "print_task");
        assert_eq!(check.status, CheckStatus::Warn);
        assert!(check.detail.contains("model=b1pro"), "{}", check.detail);
        assert!(check.detail.contains("task=d110mv4"), "{}", check.detail);
        assert!(check.detail.contains("experimental"), "{}", check.detail);
        assert!(
            !check.detail.contains("hardware-tested"),
            "{}",
            check.detail
        );
    }

    #[tokio::test]
    async fn configured_b18_doctor_is_unresolved_without_panicking_or_printing() {
        let mut transport = MockTransport::new();
        transport.set_model_id(3584); // B18
        let mut client = diagnostic_client(transport, Model::B18, None);

        let check = evaluate_connected_print_task(&mut client, None, ConnPref::Ble).await;

        assert_eq!(check.name, "print_task");
        assert_eq!(check.status, CheckStatus::Warn);
        assert!(check.detail.contains("model=b18"), "{}", check.detail);
        assert!(
            check.detail.contains("no verified default task"),
            "{}",
            check.detail
        );
        assert!(client.transport().tx_cmds().iter().all(|cmd| !matches!(
            *cmd,
            0x01 | 0x03 | 0x13 | 0x15 | 0x20 | 0x21 | 0x23 | 0x83..=0x85 | 0xe3 | 0xf3
        )));
    }

    #[tokio::test]
    async fn connected_doctor_preserves_explicit_task_for_detected_profile() {
        let mut transport = MockTransport::new();
        transport.set_model_id(4097); // B1 Pro
        let mut client = diagnostic_client(transport, Model::B1, Some(PrintTask::B1));

        let check =
            evaluate_connected_print_task(&mut client, Some(PrintTask::B1), ConnPref::Ble).await;

        assert_eq!(check.status, CheckStatus::Warn);
        assert!(check.detail.contains("model=b1pro"), "{}", check.detail);
        assert!(check.detail.contains("task=b1"), "{}", check.detail);
        assert_eq!(client.print_task(), PrintTask::B1);
    }

    #[tokio::test]
    async fn connected_unknown_model_cannot_inherit_configured_support() {
        let mut transport = MockTransport::new();
        transport.set_model_id(0xffff);
        let mut client = diagnostic_client(transport, Model::B1, None);

        let check = evaluate_connected_print_task(&mut client, None, ConnPref::Ble).await;

        assert_eq!(check.status, CheckStatus::Fail);
        assert!(check.detail.contains("model id 65535"), "{}", check.detail);
        assert!(
            !check.detail.contains("hardware-tested"),
            "{}",
            check.detail
        );
    }

    #[tokio::test]
    async fn failed_identity_query_cannot_inherit_configured_support() {
        let mut transport = MockTransport::new();
        transport.mute_cmd(crate::protocol::Cmd::PrinterInfo as u8);
        let mut client = diagnostic_client(transport, Model::B1, None)
            .with_pacing(crate::printer::Pacing::INSTANT);

        let check = evaluate_connected_print_task(&mut client, None, ConnPref::Ble).await;

        assert_eq!(check.status, CheckStatus::Fail);
        assert!(
            check.detail.contains("identity query failed"),
            "{}",
            check.detail
        );
        assert!(
            !check.detail.contains("hardware-tested"),
            "{}",
            check.detail
        );
    }

    #[test]
    fn connected_placeholder_preserves_the_print_task_check_surface() {
        let mut checks = vec![Check::fail(
            "print_task",
            "not evaluated — connected printer identity unavailable",
        )];
        replace_print_task_check(
            &mut checks,
            Check::warn("print_task", "detected experimental path"),
        );

        assert_eq!(checks.len(), 1);
        assert_eq!(checks[0].status, CheckStatus::Warn);
        assert_eq!(checks[0].detail, "detected experimental path");
    }
}