fleetcom 0.3.0

A fleet-view supervisor for arbitrary 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
//! Client-to-core commands and core-to-client snapshots for the Unix socket.

use std::ffi::{OsStr, OsString};
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::path::{Path, PathBuf};
use std::time::Duration;

use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as B64;

use crate::frame::{KIND_CONTROL, KIND_HELLO, KIND_SCREEN};
use crate::task::Lifecycle;

/// Wire-protocol version; the handshake rejects mismatched peers.
pub const PROTOCOL_VERSION: u32 = 3;

/// Environment and working directory supplied by the launching client.
#[derive(Debug, Clone, PartialEq)]
pub struct LaunchContext {
    pub env: Vec<(OsString, OsString)>,
    /// Base directory for relative session-recipe paths.
    pub cwd: PathBuf,
}

impl LaunchContext {
    /// Capture this process's environment and current directory.
    pub fn here() -> LaunchContext {
        LaunchContext {
            env: std::env::vars_os().collect(),
            cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
        }
    }
}

/// A client→core request. Every mutation of the task set is one of these; the
/// client never touches a `Task` directly. Fire-and-forget: results come back
/// as `Event`s, never as return values. The handshake uses `KIND_HELLO`, not a
/// command.
#[derive(Debug, Clone, PartialEq)]
pub enum Command {
    /// Run `command` under `$SHELL -c` in `cwd`.
    Spawn { command: String, cwd: PathBuf },
    /// Signal-kill a live task's process group; it reaps into Completed.
    Kill { id: u64 },
    /// Drop a task from the set entirely (used on already-finished tasks).
    Remove { id: u64 },
    /// Re-run a *finished* task in place: a fresh spawn of the same command in
    /// the same cwd, keeping the id (so selection, watch, tag, and list
    /// position survive). Refused on a running task.
    Restart { id: u64 },
    /// Set the manual "in use" tag.
    Tag { id: u64, on: bool },
    /// Client terminal resized: `rows`×`cols` is the PTY *content* size. The
    /// client has already subtracted the row it reserves for its status bar.
    Resize { rows: u16, cols: u16 },
    /// Stream this task's screen (attach or peek), or `None` to stop.
    Watch { id: Option<u64> },
    /// Forward raw keystroke bytes to a task's PTY.
    Input { id: u64, bytes: Vec<u8> },
    /// Clipboard paste for a task. Kept distinct from `Input` because the
    /// encoding depends on state only the core can see: the task's vt100 screen
    /// knows whether the child enabled bracketed paste (DECSET 2004), which
    /// decides between wrapping in paste markers and newline conversion.
    Paste { id: u64, bytes: Vec<u8> },
    /// One mouse action over an attached task. `col`/`row` are 0-based pane
    /// cells. Routing is core-side for the same reason as `Paste`: the child's
    /// mouse-protocol mode, encoding, and alt-screen state live in its vt100
    /// screen, and they decide both whether the child hears about the action
    /// at all and in which byte encoding.
    Mouse {
        id: u64,
        kind: MouseKind,
        col: u16,
        row: u16,
    },
    /// Move a task's scrollback viewport.
    Scrollback { id: u64, action: ScrollAction },
    /// Write the current task set as a named `{dir: [cmds]}` recipe.
    SaveSession { name: String },
    /// Spawn every command in a named recipe, each in its (existing) dir.
    LoadSession { name: String },
    /// Kill every task (the quit path).
    Shutdown,
}

/// A `Command::Scrollback` movement in history rows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScrollAction {
    Up(u16),
    Down(u16),
    Top,
    Live,
}

/// A mouse button in a `Command::Mouse`. Values match xterm button codes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MouseBtn {
    Left = 0,
    Middle = 1,
    Right = 2,
}

/// What a `Command::Mouse` reports. Wheel notches carry no button; presses,
/// drags, and releases carry the button they happened with.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MouseKind {
    WheelUp,
    WheelDown,
    Press(MouseBtn),
    Drag(MouseBtn),
    Release(MouseBtn),
}

/// A core→client message. The client keeps a local mirror of the task set and
/// the watched screen, updated only by these.
#[derive(Debug, Clone, PartialEq)]
pub enum Event {
    /// The daemon accepted a compatible hello frame and stored its launch context.
    HelloOk,
    /// Full task-set snapshot; replaces the client's mirror wholesale.
    Tasks(Vec<TaskView>),
    /// The watched task's current screen (attach/peek source).
    Screen(ScreenView),
    /// A one-line notice for the status line (save/load result, spawn error).
    Status(String),
}

/// A read-only snapshot of one task: everything a dashboard row needs, with no
/// handle into the live process. Time is pre-reduced to `started_ago` and
/// `lifecycle` is pre-computed by the core (it owns the clock and the idle
/// threshold), so nothing here depends on a process-local `Instant` that a
/// socket peer could not interpret.
#[derive(Debug, Clone, PartialEq)]
pub struct TaskView {
    pub id: u64,
    pub command: String,
    pub cwd: PathBuf,
    pub tagged: bool,
    pub lifecycle: Lifecycle,
    pub preview: String,
    pub started_ago: Duration,
}

/// The watched task's screen, in both forms the UI needs: `lines` for the peek
/// overlay's plain-text box, `formatted` (+cursor) for full attached rendering.
/// Only ever produced for the single watched task, so carrying both is cheap.
#[derive(Debug, Clone, PartialEq)]
pub struct ScreenView {
    pub id: u64,
    pub lines: Vec<String>,
    pub formatted: Vec<u8>,
    pub cursor: (u16, u16),
    pub hide_cursor: bool,
    /// Whether the child requested a mouse protocol.
    pub wants_mouse: bool,
    /// Whether the child is on the alternate screen. Without mouse capture,
    /// this determines whether alternate scroll is enabled.
    pub alt_screen: bool,
    /// Rows the viewport is scrolled back from live output.
    pub scrollback: usize,
}

// --- wire format -------------------------------------------------------------
//
// Control messages (every `Command`, and the `Tasks`/`Status` events) go over as
// jzon: low-frequency and human-debuggable. The `Screen` event is the exception:
// its `contents_formatted` bytes are the high-frequency firehose, so they ride a
// raw tail after a small jzon header rather than bloating into a JSON number
// array. A socket peer is just `decode_*(read_frame(...))`.

/// Encode paths as lossy UTF-8 strings for the protocol.
fn ps(p: &Path) -> String {
    p.to_string_lossy().into_owned()
}

/// Encode an `OsStr` as lossless base64 for a JSON string.
fn os_b64(s: &OsStr) -> String {
    B64.encode(s.as_bytes())
}

/// Decode a strictly valid base64 JSON string as an `OsString`.
fn os_from_b64(v: &jzon::JsonValue) -> Option<OsString> {
    Some(OsString::from_vec(B64.decode(v.as_str()?).ok()?))
}

fn lifecycle_str(l: Lifecycle) -> &'static str {
    match l {
        Lifecycle::Active => "active",
        Lifecycle::Idle => "idle",
        Lifecycle::Ok => "ok",
        Lifecycle::Failed => "failed",
    }
}

fn lifecycle_from(s: &str) -> Option<Lifecycle> {
    match s {
        "active" => Some(Lifecycle::Active),
        "idle" => Some(Lifecycle::Idle),
        "ok" => Some(Lifecycle::Ok),
        "failed" => Some(Lifecycle::Failed),
        _ => None,
    }
}

/// Serialize a launch context as a `KIND_HELLO` frame.
pub fn encode_hello(ctx: &LaunchContext) -> (u8, Vec<u8>) {
    let mut o = jzon::JsonValue::new_object();
    let _ = o.insert("v", PROTOCOL_VERSION);
    let _ = o.insert("cwd", ps(&ctx.cwd));
    let mut pairs = jzon::JsonValue::new_array();
    for (k, v) in &ctx.env {
        let mut pair = jzon::JsonValue::new_array();
        let _ = pair.push(os_b64(k));
        let _ = pair.push(os_b64(v));
        let _ = pairs.push(pair);
    }
    let _ = o.insert("env", pairs);
    (KIND_HELLO, o.dump().into_bytes())
}

/// Parse a `KIND_HELLO` frame into `(version, context)`.
/// Returns `None` for malformed frames or environment entries.
pub fn decode_hello(kind: u8, payload: &[u8]) -> Option<(u32, LaunchContext)> {
    if kind != KIND_HELLO {
        return None;
    }
    let v = jzon::parse(std::str::from_utf8(payload).ok()?).ok()?;
    let mut env = Vec::new();
    for pair in v["env"].members() {
        env.push((os_from_b64(&pair[0])?, os_from_b64(&pair[1])?));
    }
    Some((
        v["v"].as_u32()?,
        LaunchContext {
            env,
            cwd: PathBuf::from(v["cwd"].as_str()?),
        },
    ))
}

/// Serialize a command to `(kind, payload)` for [`crate::frame::write_frame`].
/// Every command is a jzon control frame tagged by a `"t"` discriminant.
pub fn encode_command(cmd: &Command) -> (u8, Vec<u8>) {
    let mut o = jzon::JsonValue::new_object();
    match cmd {
        Command::Spawn { command, cwd } => {
            let _ = o.insert("t", "spawn");
            let _ = o.insert("command", command.as_str());
            let _ = o.insert("cwd", ps(cwd));
        }
        Command::Kill { id } => {
            let _ = o.insert("t", "kill");
            let _ = o.insert("id", *id);
        }
        Command::Remove { id } => {
            let _ = o.insert("t", "remove");
            let _ = o.insert("id", *id);
        }
        Command::Restart { id } => {
            let _ = o.insert("t", "restart");
            let _ = o.insert("id", *id);
        }
        Command::Tag { id, on } => {
            let _ = o.insert("t", "tag");
            let _ = o.insert("id", *id);
            let _ = o.insert("on", *on);
        }
        Command::Resize { rows, cols } => {
            let _ = o.insert("t", "resize");
            let _ = o.insert("rows", *rows as u64);
            let _ = o.insert("cols", *cols as u64);
        }
        Command::Watch { id } => {
            let _ = o.insert("t", "watch");
            match id {
                Some(n) => {
                    let _ = o.insert("id", *n);
                }
                None => {
                    let _ = o.insert("id", jzon::JsonValue::Null);
                }
            }
        }
        Command::Input { id, bytes } => {
            let _ = o.insert("t", "input");
            let _ = o.insert("id", *id);
            let mut arr = jzon::JsonValue::new_array();
            for b in bytes {
                let _ = arr.push(*b as u64);
            }
            let _ = o.insert("bytes", arr);
        }
        Command::Paste { id, bytes } => {
            let _ = o.insert("t", "paste");
            let _ = o.insert("id", *id);
            let mut arr = jzon::JsonValue::new_array();
            for b in bytes {
                let _ = arr.push(*b as u64);
            }
            let _ = o.insert("bytes", arr);
        }
        Command::Mouse { id, kind, col, row } => {
            let _ = o.insert("t", "mouse");
            let _ = o.insert("id", *id);
            let (k, btn) = match kind {
                MouseKind::WheelUp => ("wu", None),
                MouseKind::WheelDown => ("wd", None),
                MouseKind::Press(b) => ("p", Some(*b)),
                MouseKind::Drag(b) => ("d", Some(*b)),
                MouseKind::Release(b) => ("r", Some(*b)),
            };
            let _ = o.insert("k", k);
            if let Some(b) = btn {
                let _ = o.insert("b", b as u64);
            }
            let _ = o.insert("col", *col as u64);
            let _ = o.insert("row", *row as u64);
        }
        Command::Scrollback { id, action } => {
            let _ = o.insert("t", "sb");
            let _ = o.insert("id", *id);
            let (a, n) = match action {
                ScrollAction::Up(n) => ("u", Some(*n)),
                ScrollAction::Down(n) => ("d", Some(*n)),
                ScrollAction::Top => ("t", None),
                ScrollAction::Live => ("l", None),
            };
            let _ = o.insert("a", a);
            if let Some(n) = n {
                let _ = o.insert("n", n as u64);
            }
        }
        Command::SaveSession { name } => {
            let _ = o.insert("t", "save");
            let _ = o.insert("name", name.as_str());
        }
        Command::LoadSession { name } => {
            let _ = o.insert("t", "load");
            let _ = o.insert("name", name.as_str());
        }
        Command::Shutdown => {
            let _ = o.insert("t", "shutdown");
        }
    }
    (KIND_CONTROL, o.dump().into_bytes())
}

/// Parse a command from a received frame. `None` on a wrong kind, non-UTF-8/
/// non-JSON payload, unknown discriminant, or a missing/mistyped field. The
/// daemon drops a malformed command rather than trusting it.
pub fn decode_command(kind: u8, payload: &[u8]) -> Option<Command> {
    if kind != KIND_CONTROL {
        return None;
    }
    let v = jzon::parse(std::str::from_utf8(payload).ok()?).ok()?;
    let cmd = match v["t"].as_str()? {
        "spawn" => Command::Spawn {
            command: v["command"].as_str()?.to_string(),
            cwd: PathBuf::from(v["cwd"].as_str()?),
        },
        "kill" => Command::Kill {
            id: v["id"].as_u64()?,
        },
        "remove" => Command::Remove {
            id: v["id"].as_u64()?,
        },
        "restart" => Command::Restart {
            id: v["id"].as_u64()?,
        },
        "tag" => Command::Tag {
            id: v["id"].as_u64()?,
            on: v["on"].as_bool()?,
        },
        "resize" => Command::Resize {
            rows: v["rows"].as_u64()? as u16,
            cols: v["cols"].as_u64()? as u16,
        },
        "watch" => Command::Watch {
            id: if v["id"].is_null() {
                None
            } else {
                Some(v["id"].as_u64()?)
            },
        },
        "input" => Command::Input {
            id: v["id"].as_u64()?,
            bytes: v["bytes"]
                .members()
                .filter_map(|m| m.as_u64().map(|n| n as u8))
                .collect(),
        },
        "paste" => Command::Paste {
            id: v["id"].as_u64()?,
            bytes: v["bytes"]
                .members()
                .filter_map(|m| m.as_u64().map(|n| n as u8))
                .collect(),
        },
        "mouse" => {
            let btn = || -> Option<MouseBtn> {
                match v["b"].as_u64()? {
                    0 => Some(MouseBtn::Left),
                    1 => Some(MouseBtn::Middle),
                    2 => Some(MouseBtn::Right),
                    _ => None,
                }
            };
            Command::Mouse {
                id: v["id"].as_u64()?,
                kind: match v["k"].as_str()? {
                    "wu" => MouseKind::WheelUp,
                    "wd" => MouseKind::WheelDown,
                    "p" => MouseKind::Press(btn()?),
                    "d" => MouseKind::Drag(btn()?),
                    "r" => MouseKind::Release(btn()?),
                    _ => return None,
                },
                col: v["col"].as_u64()? as u16,
                row: v["row"].as_u64()? as u16,
            }
        }
        "sb" => Command::Scrollback {
            id: v["id"].as_u64()?,
            action: match v["a"].as_str()? {
                "u" => ScrollAction::Up(v["n"].as_u64()? as u16),
                "d" => ScrollAction::Down(v["n"].as_u64()? as u16),
                "t" => ScrollAction::Top,
                "l" => ScrollAction::Live,
                _ => return None,
            },
        },
        "save" => Command::SaveSession {
            name: v["name"].as_str()?.to_string(),
        },
        "load" => Command::LoadSession {
            name: v["name"].as_str()?.to_string(),
        },
        "shutdown" => Command::Shutdown,
        _ => return None,
    };
    Some(cmd)
}

/// Serialize an event to `(kind, payload)`. `Tasks`/`Status` are jzon control
/// frames; `Screen` is a `KIND_SCREEN` frame (`[u32 header_len][jzon header]
/// [raw formatted bytes]`), so the formatted firehose stays raw.
pub fn encode_event(ev: &Event) -> (u8, Vec<u8>) {
    match ev {
        Event::HelloOk => {
            let mut o = jzon::JsonValue::new_object();
            let _ = o.insert("t", "hello_ok");
            (KIND_CONTROL, o.dump().into_bytes())
        }
        Event::Tasks(views) => {
            let mut arr = jzon::JsonValue::new_array();
            for tv in views {
                let mut o = jzon::JsonValue::new_object();
                let _ = o.insert("id", tv.id);
                let _ = o.insert("command", tv.command.as_str());
                let _ = o.insert("cwd", ps(&tv.cwd));
                let _ = o.insert("tagged", tv.tagged);
                let _ = o.insert("life", lifecycle_str(tv.lifecycle));
                let _ = o.insert("preview", tv.preview.as_str());
                let _ = o.insert("started_ms", tv.started_ago.as_millis() as u64);
                let _ = arr.push(o);
            }
            let mut root = jzon::JsonValue::new_object();
            let _ = root.insert("t", "tasks");
            let _ = root.insert("tasks", arr);
            (KIND_CONTROL, root.dump().into_bytes())
        }
        Event::Status(msg) => {
            let mut o = jzon::JsonValue::new_object();
            let _ = o.insert("t", "status");
            let _ = o.insert("msg", msg.as_str());
            (KIND_CONTROL, o.dump().into_bytes())
        }
        Event::Screen(sv) => {
            let mut header = jzon::JsonValue::new_object();
            let _ = header.insert("id", sv.id);
            let mut cur = jzon::JsonValue::new_array();
            let _ = cur.push(sv.cursor.0 as u64);
            let _ = cur.push(sv.cursor.1 as u64);
            let _ = header.insert("cursor", cur);
            let _ = header.insert("hide", sv.hide_cursor);
            let _ = header.insert("mouse", sv.wants_mouse);
            let _ = header.insert("alt", sv.alt_screen);
            let _ = header.insert("sb", sv.scrollback as u64);
            let mut lines = jzon::JsonValue::new_array();
            for l in &sv.lines {
                let _ = lines.push(l.as_str());
            }
            let _ = header.insert("lines", lines);
            let hbytes = header.dump().into_bytes();

            let mut payload = Vec::with_capacity(4 + hbytes.len() + sv.formatted.len());
            payload.extend_from_slice(&(hbytes.len() as u32).to_be_bytes());
            payload.extend_from_slice(&hbytes);
            payload.extend_from_slice(&sv.formatted);
            (KIND_SCREEN, payload)
        }
    }
}

/// Parse an event from a received frame. `None` on any malformed input, mirroring
/// [`decode_command`].
pub fn decode_event(kind: u8, payload: &[u8]) -> Option<Event> {
    match kind {
        KIND_CONTROL => {
            let v = jzon::parse(std::str::from_utf8(payload).ok()?).ok()?;
            match v["t"].as_str()? {
                "hello_ok" => Some(Event::HelloOk),
                "tasks" => {
                    let mut views = Vec::new();
                    for tv in v["tasks"].members() {
                        views.push(TaskView {
                            id: tv["id"].as_u64()?,
                            command: tv["command"].as_str()?.to_string(),
                            cwd: PathBuf::from(tv["cwd"].as_str()?),
                            tagged: tv["tagged"].as_bool()?,
                            lifecycle: lifecycle_from(tv["life"].as_str()?)?,
                            preview: tv["preview"].as_str()?.to_string(),
                            started_ago: Duration::from_millis(tv["started_ms"].as_u64()?),
                        });
                    }
                    Some(Event::Tasks(views))
                }
                "status" => Some(Event::Status(v["msg"].as_str()?.to_string())),
                _ => None,
            }
        }
        KIND_SCREEN => {
            let hlen = u32::from_be_bytes(payload.get(0..4)?.try_into().ok()?) as usize;
            let header_bytes = payload.get(4..4 + hlen)?;
            let formatted = payload.get(4 + hlen..)?.to_vec();
            let h = jzon::parse(std::str::from_utf8(header_bytes).ok()?).ok()?;
            let cursor = (
                h["cursor"][0].as_u64()? as u16,
                h["cursor"][1].as_u64()? as u16,
            );
            let lines = h["lines"]
                .members()
                .filter_map(|m| m.as_str().map(str::to_string))
                .collect();
            Some(Event::Screen(ScreenView {
                id: h["id"].as_u64()?,
                lines,
                formatted,
                cursor,
                hide_cursor: h["hide"].as_bool()?,
                wants_mouse: h["mouse"].as_bool()?,
                alt_screen: h["alt"].as_bool()?,
                scrollback: h["sb"].as_u64()? as usize,
            }))
        }
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    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"),
            },
            Command::Kill { id: 7 },
            Command::Remove { id: 3 },
            Command::Restart { id: 4 },
            Command::Tag { id: 2, on: true },
            Command::Resize {
                rows: 30,
                cols: 100,
            },
            Command::Watch { id: Some(5) },
            Command::Watch { id: None },
            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::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::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 round-trip byte-for-byte.
    #[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("/home/x"),
        };
        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]]]"#,            // v2 number arrays are not v3
            r#"["PATH=/bin"]"#,            // flat string pair
        ] {
            let json = format!(r#"{{"v":3,"cwd":"/","env":{env}}}"#);
            assert_eq!(
                decode_hello(KIND_HELLO, json.as_bytes()),
                None,
                "should reject env {env}"
            );
        }
    }

    #[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,
            lifecycle: Lifecycle::Idle,
            preview: "~ line".into(),
            started_ago: Duration::from_millis(4200),
        }]);
        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));
    }

    /// The `Screen` event keeps its formatted bytes intact through the raw tail,
    /// including non-UTF-8 bytes (0xFF) an ANSI stream really contains.
    #[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,
            scrollback: 42,
        });
        let (k, p) = encode_event(&screen);
        assert_eq!(k, KIND_SCREEN);
        assert_eq!(decode_event(k, &p), Some(screen));
    }
}