fleetcom 0.11.0

A fleet-view supervisor for concurrent shell commands.
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
use super::*;

/// Every command survives encode→frame-payload→decode unchanged, including
/// the `Watch{None}` null, raw `Input` bytes (0 and 255), and the no-field
/// `Shutdown`.
#[test]
fn command_round_trips() {
    let cases = [
        Command::Spawn {
            command: "echo hi".into(),
            cwd: PathBuf::from("/tmp"),
            group: None,
        },
        Command::Spawn {
            // Exercise byte-preserving serialization of a non-UTF-8 path.
            command: "ls".into(),
            cwd: PathBuf::from(OsString::from_vec(b"/tmp/\xff\xfe dir".to_vec())),
            group: None,
        },
        Command::Spawn {
            command: "make".into(),
            cwd: PathBuf::from("/tmp"),
            group: Some("build".into()),
        },
        Command::Kill { id: 7 },
        Command::Remove { id: 3 },
        Command::Restart { id: 4 },
        Command::Tag { id: 2, on: true },
        Command::SetGroup {
            id: 2,
            group: Some("infra".into()),
        },
        Command::SetGroup { id: 2, group: None },
        Command::SetName {
            id: 2,
            name: Some("api server".into()),
        },
        Command::SetName { id: 2, name: None },
        Command::Resize {
            rows: 30,
            cols: 100,
        },
        Command::Watch {
            id: Some(5),
            attached: true,
        },
        Command::Watch {
            id: Some(5),
            attached: false,
        },
        Command::Watch {
            id: None,
            attached: false,
        },
        Command::Input {
            id: 1,
            bytes: vec![0, 27, 91, 255],
        },
        Command::Paste {
            // Non-UTF-8 and marker-shaped bytes must survive: the core, not
            // the client, decides what the child receives.
            id: 6,
            bytes: b"line1\nline2\x1b[201~\xff".to_vec(),
        },
        Command::Mouse {
            id: 8,
            kind: MouseKind::WheelDown,
            col: 79,
            row: 23,
        },
        Command::Mouse {
            id: 8,
            kind: MouseKind::Press(MouseBtn::Left),
            col: 0,
            row: 0,
        },
        Command::Mouse {
            id: 8,
            kind: MouseKind::Drag(MouseBtn::Middle),
            col: 10,
            row: 5,
        },
        Command::Mouse {
            id: 8,
            kind: MouseKind::Release(MouseBtn::Right),
            col: 10,
            row: 5,
        },
        Command::Key {
            id: 9,
            code: Key::Char('λ'),
            mods: Mods::default(),
        },
        Command::Key {
            id: 9,
            code: Key::F(7),
            mods: Mods {
                ctrl: true,
                ..Mods::default()
            },
        },
        Command::Key {
            id: 9,
            // A modified arrow carries all three bits through the wire.
            code: Key::Left,
            mods: Mods {
                shift: true,
                alt: true,
                ctrl: true,
            },
        },
        Command::Key {
            id: 9,
            code: Key::Enter,
            mods: Mods::default(),
        },
        Command::Scrollback {
            id: 3,
            action: ScrollAction::Up(23),
        },
        Command::Scrollback {
            id: 3,
            action: ScrollAction::Down(1),
        },
        Command::Scrollback {
            id: 3,
            action: ScrollAction::Top,
        },
        Command::Scrollback {
            id: 3,
            action: ScrollAction::Live,
        },
        Command::SaveSession {
            name: "work".into(),
        },
        Command::LoadSession {
            name: "home".into(),
        },
        Command::LoadRecovery {
            stem: "20260714-093015-4242".into(),
        },
        Command::ListSessions,
        Command::Shutdown,
    ];
    for c in cases {
        let (k, p) = encode_command(&c);
        assert_eq!(decode_command(k, &p).as_ref(), Some(&c), "round-trip {c:?}");
    }
}

#[test]
fn hello_ok_round_trips() {
    let ack = Event::HelloOk;
    let (k, p) = encode_event(&ack);
    assert_eq!(k, KIND_CONTROL);
    assert_eq!(decode_event(k, &p), Some(ack));
}

/// Handshake environment entries and the cwd round-trip byte-for-byte,
/// including non-UTF-8 bytes in both.
#[test]
fn hello_round_trips() {
    let ctx = LaunchContext {
        env: vec![
            ("PATH".into(), "/usr/bin:/bin".into()),
            (
                OsString::from_vec(b"BAD\xff\xfe".to_vec()),
                OsString::from_vec(b"v\xff".to_vec()),
            ),
        ],
        cwd: PathBuf::from(OsString::from_vec(b"/home/x\xff\xfe".to_vec())),
    };
    let (k, p) = encode_hello(&ctx);
    assert_eq!(k, KIND_HELLO);
    assert_eq!(decode_hello(k, &p), Some((PROTOCOL_VERSION, ctx)));

    let empty = LaunchContext {
        env: Vec::new(),
        cwd: PathBuf::from("/"),
    };
    let (k, p) = encode_hello(&empty);
    assert_eq!(decode_hello(k, &p), Some((PROTOCOL_VERSION, empty)));
}

/// A hello payload is valid only in a hello frame.
#[test]
fn hello_requires_its_own_frame_kind() {
    let (_, p) = encode_hello(&LaunchContext {
        env: Vec::new(),
        cwd: PathBuf::from("/"),
    });
    assert_eq!(decode_hello(KIND_CONTROL, &p), None);
    assert_eq!(decode_command(KIND_CONTROL, &p), None);
}

/// Malformed environment entries reject the entire hello frame.
#[test]
fn hello_with_malformed_env_is_rejected() {
    for env in [
        r#"[["P@TH","L2Jpbg=="]]"#,    // invalid base64 character
        r#"[["QUFBQUE","L2Jpbg=="]]"#, // truncated: missing padding
        r#"[["UEFUSA==","AAAA="]]"#,   // bad padding length
        r#"[[[80],[65]]]"#,            // env pairs must contain base64 strings
        r#"["PATH=/bin"]"#,            // flat string pair
    ] {
        // Keep the cwd valid so each case isolates env validation.
        let json = format!(r#"{{"v":4,"cwd":"Lw==","env":{env}}}"#);
        assert_eq!(
            decode_hello(KIND_HELLO, json.as_bytes()),
            None,
            "should reject env {env}"
        );
    }
}

/// A hello with a non-base64 cwd is rejected.
#[test]
fn hello_with_malformed_cwd_is_rejected() {
    let json = r#"{"v":3,"cwd":"/home/user","env":[]}"#;
    assert_eq!(decode_hello(KIND_HELLO, json.as_bytes()), None);
}

/// Out-of-range numeric fields reject the whole command.
#[test]
fn out_of_range_numerics_are_rejected() {
    for json in [
        r#"{"t":"resize","rows":65536,"cols":100}"#,
        r#"{"t":"resize","rows":30,"cols":65536}"#,
        r#"{"t":"mouse","id":1,"k":"wu","col":65536,"row":0}"#,
        r#"{"t":"mouse","id":1,"k":"wu","col":0,"row":65536}"#,
        r#"{"t":"sb","id":1,"a":"u","n":65536}"#,
        r#"{"t":"sb","id":1,"a":"d","n":-1}"#,
    ] {
        assert_eq!(
            decode_command(KIND_CONTROL, json.as_bytes()),
            None,
            "should reject {json}"
        );
    }
}

/// Invalid base64 and non-string byte or path fields reject the command.
#[test]
fn invalid_base64_is_rejected() {
    for json in [
        r#"{"t":"input","id":1,"bytes":"!!!"}"#,
        r#"{"t":"input","id":1,"bytes":[0,27]}"#, // bytes must be a base64 string
        r#"{"t":"paste","id":1,"bytes":"AAAA="}"#, // bad padding length
        r#"{"t":"spawn","command":"ls","cwd":"/tmp/x"}"#, // plain path
    ] {
        assert_eq!(
            decode_command(KIND_CONTROL, json.as_bytes()),
            None,
            "should reject {json}"
        );
    }
}

/// Build a `KIND_SCREEN` payload with a raw header and an empty byte tail.
fn screen_payload(header: &str) -> Vec<u8> {
    let mut p = Vec::with_capacity(4 + header.len());
    p.extend_from_slice(&(header.len() as u32).to_be_bytes());
    p.extend_from_slice(header.as_bytes());
    p
}

/// Build the neutral task view used by exact wire-format assertions.
fn tv(id: u64) -> TaskView {
    TaskView {
        id,
        command: "x".into(),
        cwd: PathBuf::from("/"),
        tagged: false,
        group: None,
        name: None,
        lifecycle: Lifecycle::Ok,
        parked: false,
        preview: Preview::floor(String::new()),
        started_ago: Duration::from_millis(0),
        quiet_ago: None,
        finished_ago: None,
    }
}

/// A mistyped member in `lines`, `tasks`, or `names` rejects the whole
/// event, keeping decoded rows aligned with their encoded positions.
#[test]
fn mistyped_event_members_are_rejected() {
    for header in [
        // Numeric member in `lines`.
        r#"{"id":1,"cursor":[0,0],"hide":false,"mouse":false,"alt":false,"ascr":false,"sb":0,"lines":["ok",5]}"#,
        // Out-of-range cursor cell.
        r#"{"id":1,"cursor":[65536,0],"hide":false,"mouse":false,"alt":false,"ascr":false,"sb":0,"lines":[]}"#,
    ] {
        assert_eq!(
            decode_event(KIND_SCREEN, &screen_payload(header)),
            None,
            "should reject header {header}"
        );
    }
    for json in [
        r#"{"t":"tasks","tasks":[{"id":"nope"}]}"#,
        // The cwd must be a base64 string.
        r#"{"t":"tasks","tasks":[{"id":1,"command":"x","cwd":"/x","tagged":true,"life":"ok","preview":"","started_ms":0}]}"#,
        // A present group must be a string; only missing/null means unassigned.
        r#"{"t":"tasks","tasks":[{"id":1,"command":"x","cwd":"Lw==","tagged":true,"life":"ok","preview":"","started_ms":0,"group":5}]}"#,
        // A present name must be a string.
        r#"{"t":"tasks","tasks":[{"id":1,"command":"x","cwd":"Lw==","tagged":true,"life":"ok","preview":"","started_ms":0,"name":5}]}"#,
        r#"{"t":"tasks","tasks":["flat"]}"#,
        // Numeric member in `names`.
        r#"{"t":"sessions","names":["ok",5]}"#,
    ] {
        assert_eq!(
            decode_event(KIND_CONTROL, json.as_bytes()),
            None,
            "should reject {json}"
        );
    }
}

/// Screen events without the required alternate-scroll field are rejected.
#[test]
fn screen_header_without_alt_scroll_is_rejected() {
    let header =
        r#"{"id":1,"cursor":[0,0],"hide":false,"mouse":false,"alt":true,"sb":0,"lines":[]}"#;
    assert_eq!(decode_event(KIND_SCREEN, &screen_payload(header)), None);
}

#[test]
fn tasks_and_status_round_trip() {
    let tasks = Event::Tasks(vec![
        TaskView {
            id: 1,
            command: "vim".into(),
            cwd: PathBuf::from("/home/x"),
            tagged: true,
            group: Some("x".into()),
            name: Some("editor".into()),
            lifecycle: Lifecycle::Idle,
            parked: false,
            preview: Preview {
                text: "~ line".into(),
                source: PreviewSource::Title,
                rule: None,
                frozen: false,
            },
            started_ago: Duration::from_millis(4200),
            quiet_ago: Some(Duration::from_millis(700)),
            finished_ago: None,
        },
        TaskView {
            command: "make".into(),
            // Exercise byte-preserving task-path serialization.
            cwd: PathBuf::from(OsString::from_vec(b"/srv/\xff\xfe".to_vec())),
            lifecycle: Lifecycle::Active,
            started_ago: Duration::from_millis(10),
            ..tv(2)
        },
    ]);
    let (k, p) = encode_event(&tasks);
    assert_eq!(k, KIND_CONTROL);
    assert_eq!(decode_event(k, &p), Some(tasks));

    let status = Event::Status("saved 'x'".into());
    let (k, p) = encode_event(&status);
    assert_eq!(decode_event(k, &p), Some(status));
}

/// `SetGroup` emits `"g"` only for an assignment. A missing or null `"g"`
/// decodes as a clear.
#[test]
fn set_group_wire_form() {
    let (k, p) = encode_command(&Command::SetGroup {
        id: 3,
        group: Some("infra".into()),
    });
    assert_eq!(k, KIND_CONTROL);
    assert_eq!(
        std::str::from_utf8(&p).unwrap(),
        r#"{"t":"group","id":3,"g":"infra"}"#
    );
    let (_, p) = encode_command(&Command::SetGroup { id: 3, group: None });
    assert!(!String::from_utf8(p).unwrap().contains("\"g\""));
    // An explicit null clears, same as an omitted key.
    assert_eq!(
        decode_command(KIND_CONTROL, br#"{"t":"group","id":3,"g":null}"#),
        Some(Command::SetGroup { id: 3, group: None })
    );
    // A present group must be a string.
    assert_eq!(
        decode_command(KIND_CONTROL, br#"{"t":"group","id":3,"g":5}"#),
        None
    );
}

/// `SetName` omits `"n"` when clearing; a missing or null `"n"` decodes as
/// a clear.
#[test]
fn set_name_wire_form() {
    let (k, p) = encode_command(&Command::SetName {
        id: 3,
        name: Some("api".into()),
    });
    assert_eq!(k, KIND_CONTROL);
    assert_eq!(
        std::str::from_utf8(&p).unwrap(),
        r#"{"t":"name","id":3,"n":"api"}"#
    );
    let (_, p) = encode_command(&Command::SetName { id: 3, name: None });
    assert!(!String::from_utf8(p).unwrap().contains("\"n\""));
    // An explicit null clears, same as an omitted key.
    assert_eq!(
        decode_command(KIND_CONTROL, br#"{"t":"name","id":3,"n":null}"#),
        Some(Command::SetName { id: 3, name: None })
    );
    // A present name must be a string.
    assert_eq!(
        decode_command(KIND_CONTROL, br#"{"t":"name","id":3,"n":5}"#),
        None
    );
}

/// Task frames omit `"group"` when unassigned; an absent key decodes as
/// `None`.
#[test]
fn tasks_frame_group_key_is_optional() {
    // "Lw==" is the base64 encoding of "/".
    let ungrouped = r#"{"t":"tasks","tasks":[{"id":1,"command":"x","cwd":"Lw==","tagged":false,"life":"ok","preview":"","src":"floor","frozen":false,"started_ms":0,"parked":false}]}"#;
    match decode_event(KIND_CONTROL, ungrouped.as_bytes()) {
        Some(Event::Tasks(v)) => assert_eq!(v[0].group, None),
        other => panic!("expected tasks event, got {other:?}"),
    }
    // Encoding an unassigned task omits the group key.
    let (_, p) = encode_event(&Event::Tasks(vec![tv(1)]));
    assert_eq!(std::str::from_utf8(&p).unwrap(), ungrouped);

    let grouped = r#"{"t":"tasks","tasks":[{"id":1,"command":"x","cwd":"Lw==","tagged":false,"group":"infra","life":"ok","preview":"","started_ms":0}]}"#;
    match decode_event(KIND_CONTROL, grouped.as_bytes()) {
        Some(Event::Tasks(v)) => assert_eq!(v[0].group.as_deref(), Some("infra")),
        other => panic!("expected tasks event, got {other:?}"),
    }
}

/// Task frames omit `"name"` when unnamed; an absent key decodes as
/// `None`.
#[test]
fn tasks_frame_name_key_is_optional() {
    // "Lw==" is the base64 encoding of "/".
    let unnamed = r#"{"t":"tasks","tasks":[{"id":1,"command":"x","cwd":"Lw==","tagged":false,"life":"ok","preview":"","src":"floor","frozen":false,"started_ms":0,"parked":false}]}"#;
    match decode_event(KIND_CONTROL, unnamed.as_bytes()) {
        Some(Event::Tasks(v)) => assert_eq!(v[0].name, None),
        other => panic!("expected tasks event, got {other:?}"),
    }
    // Encoding an unnamed task omits the name key.
    let (_, p) = encode_event(&Event::Tasks(vec![tv(1)]));
    assert_eq!(std::str::from_utf8(&p).unwrap(), unnamed);

    let named = r#"{"t":"tasks","tasks":[{"id":1,"command":"x","cwd":"Lw==","tagged":false,"name":"build","life":"ok","preview":"","started_ms":0}]}"#;
    match decode_event(KIND_CONTROL, named.as_bytes()) {
        Some(Event::Tasks(v)) => assert_eq!(v[0].name.as_deref(), Some("build")),
        other => panic!("expected tasks event, got {other:?}"),
    }
}

/// Live parked and finished views encode only their applicable age field.
#[test]
fn parked_and_age_fields_round_trip() {
    let tasks = Event::Tasks(vec![
        TaskView {
            command: "top".into(),
            lifecycle: Lifecycle::Idle,
            parked: true,
            started_ago: Duration::from_millis(60_000),
            quiet_ago: Some(Duration::from_millis(12_000)),
            ..tv(1)
        },
        TaskView {
            command: "make".into(),
            started_ago: Duration::from_millis(60_000),
            finished_ago: Some(Duration::from_millis(3_000)),
            ..tv(2)
        },
    ]);
    let (k, p) = encode_event(&tasks);
    let s = std::str::from_utf8(&p).unwrap();
    assert_eq!(s.matches("\"quiet_ms\"").count(), 1, "frame was {s}");
    assert_eq!(s.matches("\"finished_ms\"").count(), 1, "frame was {s}");
    assert_eq!(decode_event(k, &p), Some(tasks));
}

/// Missing parked and age fields use lifecycle-derived and unknown defaults.
#[test]
fn tasks_frame_without_parked_keys_decodes_with_defaults() {
    let old = r#"{"t":"tasks","tasks":[{"id":1,"command":"x","cwd":"Lw==","tagged":false,"life":"idle","preview":"","started_ms":0},{"id":2,"command":"y","cwd":"Lw==","tagged":false,"life":"active","preview":"","started_ms":0}]}"#;
    match decode_event(KIND_CONTROL, old.as_bytes()) {
        Some(Event::Tasks(v)) => {
            assert!(v[0].parked, "idle derives parked");
            assert!(!v[1].parked, "active derives not-parked");
            assert_eq!((v[0].quiet_ago, v[0].finished_ago), (None, None));
            assert_eq!((v[1].quiet_ago, v[1].finished_ago), (None, None));
        }
        other => panic!("expected tasks event, got {other:?}"),
    }
}

/// Every preview source round-trips with its frozen flag, and `rule`
/// never crosses the wire: an encoded `Some` decodes as `None`.
#[test]
fn preview_source_and_frozen_round_trip() {
    let base = TaskView {
        lifecycle: Lifecycle::Active,
        preview: Preview::floor("p".into()),
        quiet_ago: Some(Duration::from_millis(1)),
        ..tv(1)
    };
    let tasks = Event::Tasks(vec![
        base.clone(),
        TaskView {
            id: 2,
            preview: Preview {
                source: PreviewSource::Marker,
                ..base.preview.clone()
            },
            ..base.clone()
        },
        TaskView {
            id: 3,
            preview: Preview {
                source: PreviewSource::Title,
                frozen: true,
                ..base.preview.clone()
            },
            ..base.clone()
        },
        TaskView {
            id: 4,
            preview: Preview {
                source: PreviewSource::Anchor,
                ..base.preview.clone()
            },
            ..base.clone()
        },
    ]);
    let (k, p) = encode_event(&tasks);
    assert_eq!(decode_event(k, &p), Some(tasks));

    // Encoding omits the process-local matcher rule.
    let ruled = Event::Tasks(vec![TaskView {
        preview: Preview {
            source: PreviewSource::Anchor,
            rule: Some("claude-status"),
            ..base.preview.clone()
        },
        ..base.clone()
    }]);
    let (k, p) = encode_event(&ruled);
    assert!(
        !String::from_utf8(p.clone())
            .unwrap()
            .contains("claude-status")
    );
    match decode_event(k, &p) {
        Some(Event::Tasks(v)) => {
            assert_eq!(v[0].preview.source, PreviewSource::Anchor);
            assert_eq!(v[0].preview.rule, None, "rule must stay daemon-side");
        }
        other => panic!("expected tasks event, got {other:?}"),
    }
}

/// Missing preview metadata decodes to an unfrozen Floor source.
#[test]
fn tasks_frame_without_preview_keys_decodes_with_floor_defaults() {
    let old = r#"{"t":"tasks","tasks":[{"id":1,"command":"x","cwd":"Lw==","tagged":false,"life":"active","preview":"p","started_ms":0,"parked":false}]}"#;
    match decode_event(KIND_CONTROL, old.as_bytes()) {
        Some(Event::Tasks(v)) => {
            assert_eq!(v[0].preview.source, PreviewSource::Floor);
            assert!(!v[0].preview.frozen);
            assert_eq!(v[0].preview.rule, None);
        }
        other => panic!("expected tasks event, got {other:?}"),
    }
    // A present source must be a known label.
    let bad = r#"{"t":"tasks","tasks":[{"id":1,"command":"x","cwd":"Lw==","tagged":false,"life":"active","preview":"p","src":"vibes","frozen":false,"started_ms":0,"parked":false}]}"#;
    assert_eq!(decode_event(KIND_CONTROL, bad.as_bytes()), None);
}

/// `Sessions` carries the picker's names verbatim: several names, an empty
/// list, and names with spaces and non-ASCII all round-trip.
#[test]
fn sessions_event_round_trips() {
    for names in [
        vec!["alpha".to_string(), "beta".to_string(), "gamma".to_string()],
        Vec::new(),
        vec!["my session".to_string(), "café ☕".to_string()],
    ] {
        let ev = Event::Sessions {
            names,
            recovery: Vec::new(),
        };
        let (k, p) = encode_event(&ev);
        assert_eq!(k, KIND_CONTROL);
        assert_eq!(decode_event(k, &p).as_ref(), Some(&ev), "round-trip {ev:?}");
    }
}

/// Recovery entries round-trip with their exact wire fields.
#[test]
fn sessions_recovery_entries_round_trip_and_pin_the_wire_shape() {
    let ev = Event::Sessions {
        names: vec!["work".to_string()],
        recovery: vec![
            RecoveryEntry {
                stem: "20260715-070000-22".into(),
                label: "autosaved 2026-07-15 07:00".into(),
                tasks: 3,
                age_secs: 42,
            },
            RecoveryEntry {
                stem: "20260714-093015-11".into(),
                label: "autosaved 2026-07-14 09:30".into(),
                tasks: 1,
                age_secs: 90_000,
            },
        ],
    };
    let (k, p) = encode_event(&ev);
    assert_eq!(k, KIND_CONTROL);
    assert_eq!(
        std::str::from_utf8(&p).unwrap(),
        r#"{"t":"sessions","names":["work"],"recovery":[{"stem":"20260715-070000-22","label":"autosaved 2026-07-15 07:00","tasks":3,"age":42},{"stem":"20260714-093015-11","label":"autosaved 2026-07-14 09:30","tasks":1,"age":90000}]}"#
    );
    assert_eq!(decode_event(k, &p), Some(ev));
}

/// A missing or non-array `recovery` value decodes as an empty list.
#[test]
fn sessions_frame_without_recovery_key_decodes_empty() {
    for json in [
        r#"{"t":"sessions","names":["a"]}"#,
        r#"{"t":"sessions","names":["a"],"recovery":null}"#,
        r#"{"t":"sessions","names":["a"],"recovery":"junk"}"#,
    ] {
        assert_eq!(
            decode_event(KIND_CONTROL, json.as_bytes()),
            Some(Event::Sessions {
                names: vec!["a".to_string()],
                recovery: Vec::new(),
            }),
            "should tolerate {json}"
        );
    }
}

/// Malformed recovery members are skipped without dropping valid entries.
#[test]
fn malformed_recovery_members_drop_without_rejecting_the_event() {
    let json = r#"{"t":"sessions","names":[],"recovery":[
        {"stem":5,"label":"x","tasks":1,"age":0},
        {"label":"x","tasks":1,"age":0},
        {"stem":"s1","tasks":1,"age":0},
        {"stem":"s2","label":7,"tasks":1,"age":0},
        {"stem":"s3","label":"x","age":0},
        {"stem":"s4","label":"x","tasks":4294967296,"age":0},
        {"stem":"s5","label":"x","tasks":-1,"age":0},
        {"stem":"s6","label":"x","tasks":1,"age":-3},
        {"stem":"s7","label":"x","tasks":1},
        "flat",
        {"stem":"good","label":"autosaved","tasks":2,"age":7}
    ]}"#;
    assert_eq!(
        decode_event(KIND_CONTROL, json.as_bytes()),
        Some(Event::Sessions {
            names: Vec::new(),
            recovery: vec![RecoveryEntry {
                stem: "good".into(),
                label: "autosaved".into(),
                tasks: 2,
                age_secs: 7,
            }],
        })
    );
}

/// Watch frames require a Boolean `attached` field.
#[test]
fn watch_wire_form_requires_the_attached_flag() {
    let (k, p) = encode_command(&Command::Watch {
        id: Some(5),
        attached: true,
    });
    assert_eq!(k, KIND_CONTROL);
    assert_eq!(
        std::str::from_utf8(&p).unwrap(),
        r#"{"t":"watch","id":5,"attached":true}"#
    );
    let (_, p) = encode_command(&Command::Watch {
        id: None,
        attached: false,
    });
    assert_eq!(
        std::str::from_utf8(&p).unwrap(),
        r#"{"t":"watch","id":null,"attached":false}"#
    );
    for json in [
        r#"{"t":"watch","id":5}"#,                 // missing flag
        r#"{"t":"watch","id":null}"#,              // missing flag on unwatch
        r#"{"t":"watch","id":5,"attached":null}"#, // null is not a kind
        r#"{"t":"watch","id":5,"attached":1}"#,    // flag must be a boolean
    ] {
        assert_eq!(
            decode_command(KIND_CONTROL, json.as_bytes()),
            None,
            "should reject {json}"
        );
    }
}

/// `LoadRecovery` requires a string stem in its wire representation.
#[test]
fn load_recovery_wire_form() {
    let (k, p) = encode_command(&Command::LoadRecovery {
        stem: "20260714-093015-4242".into(),
    });
    assert_eq!(k, KIND_CONTROL);
    assert_eq!(
        std::str::from_utf8(&p).unwrap(),
        r#"{"t":"recover","stem":"20260714-093015-4242"}"#
    );
    for json in [
        r#"{"t":"recover"}"#,
        r#"{"t":"recover","stem":5}"#,
        r#"{"t":"recover","stem":null}"#,
    ] {
        assert_eq!(
            decode_command(KIND_CONTROL, json.as_bytes()),
            None,
            "should reject {json}"
        );
    }
}

/// A `Screen` event preserves formatted bytes, including non-UTF-8 values.
#[test]
fn screen_round_trips_raw_bytes() {
    let screen = Event::Screen(ScreenView {
        id: 9,
        lines: vec!["row0".into(), "row1".into()],
        formatted: vec![0x1b, b'[', b'm', 0, 255, b'x'],
        cursor: (3, 12),
        hide_cursor: false,
        wants_mouse: true,
        alt_screen: false,
        // The wire encodes this field independently of `alt_screen`.
        alt_scroll: true,
        scrollback: 42,
    });
    let (k, p) = encode_event(&screen);
    assert_eq!(k, KIND_SCREEN);
    assert_eq!(decode_event(k, &p), Some(screen));
}

/// Clipboard events preserve their source, target, and text.
#[test]
fn clipboard_copy_round_trips() {
    for ev in [
        Event::ClipboardCopy {
            id: 1,
            kind: ClipboardKind::Clipboard,
            text: "hello".into(),
        },
        Event::ClipboardCopy {
            id: 1 << 40,
            kind: ClipboardKind::Selection,
            text: "sélection λ 🦀".into(),
        },
        Event::ClipboardCopy {
            id: 2,
            kind: ClipboardKind::Primary,
            text: "primary".into(),
        },
        Event::ClipboardCopy {
            id: 7,
            kind: ClipboardKind::Clipboard,
            // Exercise control characters and paste-marker-shaped text.
            text: "line1\nline2\tcol\u{0}\u{1b}[201~end".into(),
        },
    ] {
        let (k, p) = encode_event(&ev);
        assert_eq!(k, KIND_CONTROL);
        assert_eq!(decode_event(k, &p), Some(ev));
    }
}

/// Clipboard events encode every target with its OSC 52 selector.
#[test]
fn clipboard_copy_wire_form() {
    for (kind, wire) in [
        (
            ClipboardKind::Clipboard,
            r#"{"t":"clip","id":5,"k":"c","text":"aGk="}"#,
        ),
        (
            ClipboardKind::Primary,
            r#"{"t":"clip","id":5,"k":"p","text":"aGk="}"#,
        ),
        (
            ClipboardKind::Selection,
            r#"{"t":"clip","id":5,"k":"s","text":"aGk="}"#,
        ),
    ] {
        let (k, p) = encode_event(&Event::ClipboardCopy {
            id: 5,
            kind,
            text: "hi".into(),
        });
        assert_eq!(k, KIND_CONTROL);
        assert_eq!(std::str::from_utf8(&p).unwrap(), wire);
    }
}

/// Malformed clipboard event frames are rejected.
#[test]
fn malformed_clipboard_copy_is_rejected() {
    for json in [
        r#"{"t":"clip","id":1,"text":"aGk="}"#,  // missing kind
        r#"{"t":"clip","id":1,"k":"c"}"#,        // missing text
        r#"{"t":"clip","k":"c","text":"aGk="}"#, // missing id
        r#"{"t":"clip","id":"1","k":"c","text":"aGk="}"#, // id must be a number
        r#"{"t":"clip","id":1,"k":"x","text":"aGk="}"#, // unknown kind string
        r#"{"t":"clip","id":1,"k":"c","text":"!!!"}"#, // invalid base64
        r#"{"t":"clip","id":1,"k":"c","text":"/w=="}"#, // 0xFF: not UTF-8
        r#"{"t":"clip","id":1,"k":"c","text":["aGk="]}"#, // text must be a string
    ] {
        assert_eq!(
            decode_event(KIND_CONTROL, json.as_bytes()),
            None,
            "should reject {json}"
        );
    }
}