marver 0.0.25

A TUI workspace for AI agent sessions: tmux orchestration, git worktree management, and repo control in one place.
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
//! The tmux control-mode protocol.
//!
//! [`Decoder`] is pure: lines in, [`Event`]s out. The transport is in
//! [`super::client`]. Three properties of the protocol, against tmux 3.6b:
//!
//! - Command output inside `%begin`/`%end` is opaque: `list-panes` returns
//!   lines like `%0`.
//! - `%output` payloads are octal-escaped (`\033`, `\015`, `\134`) and carry
//!   arbitrary bytes, so they stay `Vec<u8>`.
//! - The stream is wrapped in a DCS sequence: `\x1bP1000p` on attach.

/// One decoded protocol message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Event {
    /// Bytes a pane produced, already unescaped.
    Output {
        pane: String,
        data: Vec<u8>,
    },
    /// A command's reply, delivered whole when its block closes.
    CommandReply {
        number: u64,
        lines: Vec<String>,
        /// True when the block closed with `%error` rather than `%end`.
        error: bool,
    },
    SessionChanged {
        session: String,
        name: String,
    },
    SessionsChanged,
    SessionRenamed {
        session: String,
        name: String,
    },
    WindowAdd {
        window: String,
    },
    WindowClose {
        window: String,
    },
    WindowRenamed {
        window: String,
        name: String,
    },
    LayoutChange {
        window: String,
        layout: String,
    },
    PaneModeChanged {
        pane: String,
    },
    /// The server is going away. Terminal for this connection.
    Exit {
        reason: Option<String>,
    },
    /// A notification this decoder does not model. Kept rather than dropped so
    /// an unrecognised message is visible instead of silently ignored.
    Unknown {
        line: String,
    },
}

/// An in-progress `%begin` block.
#[derive(Debug)]
struct Block {
    number: u64,
    lines: Vec<String>,
}

#[derive(Debug, Default)]
pub struct Decoder {
    block: Option<Block>,
}

impl Decoder {
    pub fn new() -> Self {
        Self::default()
    }

    /// Whether a command block is currently open.
    pub fn in_block(&self) -> bool {
        self.block.is_some()
    }

    /// Feed one line. Returns an event when the line completes one.
    pub fn push(&mut self, line: impl AsRef<[u8]>) -> Option<Event> {
        let line = strip_wrapper(line.as_ref());

        // The only line that carries arbitrary bytes.
        if self.block.is_none()
            && let Some(rest) = line.strip_prefix(b"%output ".as_slice())
        {
            return Some(parse_output(rest));
        }

        let line = String::from_utf8_lossy(line);
        let line = line.as_ref();

        // Inside a block every line is literal until the block closes.
        if self.block.is_some() {
            if let Some(rest) = line.strip_prefix("%end ") {
                return self.close_block(rest, false);
            }
            if let Some(rest) = line.strip_prefix("%error ") {
                return self.close_block(rest, true);
            }
            if let Some(block) = self.block.as_mut() {
                block.lines.push(line.to_string());
            }
            return None;
        }

        if let Some(rest) = line.strip_prefix("%begin ") {
            self.block = Some(Block {
                // %begin <timestamp> <number> <flags>
                number: field(rest, 1).and_then(|f| f.parse().ok()).unwrap_or(0),
                lines: Vec::new(),
            });
            return None;
        }

        if !line.starts_with('%') {
            // Outside a block, tmux only emits notifications.
            return None;
        }

        Some(parse_notification(line))
    }

    fn close_block(&mut self, rest: &str, error: bool) -> Option<Event> {
        let block = self.block.take()?;
        // %end <timestamp> <number> <flags>; trust the closing number when
        // present, since it is what tmux correlates against.
        let number = field(rest, 1)
            .and_then(|f| f.parse().ok())
            .unwrap_or(block.number);
        Some(Event::CommandReply {
            number,
            lines: block.lines,
            error,
        })
    }
}

/// `%output %<pane> <escaped bytes>`, with the tag already stripped.
fn parse_output(rest: &[u8]) -> Event {
    match rest.iter().position(|&b| b == b' ') {
        Some(i) => Event::Output {
            pane: String::from_utf8_lossy(&rest[..i]).into_owned(),
            data: unescape(&rest[i + 1..]),
        },
        // A pane can emit nothing but a newline.
        None if !rest.is_empty() => Event::Output {
            pane: String::from_utf8_lossy(rest).into_owned(),
            data: Vec::new(),
        },
        None => Event::Unknown {
            line: "%output".to_string(),
        },
    }
}

fn parse_notification(line: &str) -> Event {
    let (tag, rest) = match line.split_once(' ') {
        Some((tag, rest)) => (tag, rest),
        None => (line, ""),
    };

    match tag {
        "%session-changed" => two(rest)
            .map(|(session, name)| Event::SessionChanged { session, name })
            .unwrap_or_else(|| unknown(line)),
        "%session-renamed" => two(rest)
            .map(|(session, name)| Event::SessionRenamed { session, name })
            .unwrap_or_else(|| unknown(line)),
        "%sessions-changed" => Event::SessionsChanged,
        "%window-add" => Event::WindowAdd {
            window: rest.trim().to_string(),
        },
        "%window-close" | "%unlinked-window-close" => Event::WindowClose {
            window: rest.trim().to_string(),
        },
        "%window-renamed" => two(rest)
            .map(|(window, name)| Event::WindowRenamed { window, name })
            .unwrap_or_else(|| unknown(line)),
        "%layout-change" => two(rest)
            .map(|(window, layout)| Event::LayoutChange { window, layout })
            .unwrap_or_else(|| unknown(line)),
        "%pane-mode-changed" => Event::PaneModeChanged {
            pane: rest.trim().to_string(),
        },
        "%exit" => Event::Exit {
            reason: (!rest.trim().is_empty()).then(|| rest.trim().to_string()),
        },
        _ => unknown(line),
    }
}

fn unknown(line: &str) -> Event {
    Event::Unknown {
        line: line.to_string(),
    }
}

/// Split into exactly two whitespace-separated parts, the second possibly
/// containing spaces.
fn two(rest: &str) -> Option<(String, String)> {
    let (a, b) = rest.split_once(' ')?;
    Some((a.to_string(), b.to_string()))
}

fn field(s: &str, index: usize) -> Option<&str> {
    s.split_whitespace().nth(index)
}

/// Remove the pty's trailing `\r` and the DCS wrapper tmux emits around the
/// control stream.
fn strip_wrapper(line: &[u8]) -> &[u8] {
    let line = line.strip_suffix(b"\n").unwrap_or(line);
    let line = line.strip_suffix(b"\r").unwrap_or(line);
    let line = line.strip_prefix(b"\x1bP1000p".as_slice()).unwrap_or(line);
    line.strip_suffix(b"\x1b\\".as_slice()).unwrap_or(line)
}

/// Decode tmux's octal escaping of pane output.
fn unescape(bytes: &[u8]) -> Vec<u8> {
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'\\' && i + 3 < bytes.len() {
            let digits = &bytes[i + 1..i + 4];
            if digits.iter().all(|b| (b'0'..=b'7').contains(b)) {
                let value = digits
                    .iter()
                    .fold(0u32, |acc, b| acc * 8 + u32::from(b - b'0'));
                if value <= 0xff {
                    out.push(value as u8);
                    i += 4;
                    continue;
                }
            }
        }
        out.push(bytes[i]);
        i += 1;
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    fn decode(lines: &[&str]) -> Vec<Event> {
        let mut decoder = Decoder::new();
        lines.iter().filter_map(|l| decoder.push(l)).collect()
    }

    #[test]
    fn unescapes_octal_payloads() {
        // Taken verbatim from a tmux 3.6b transcript.
        let events = decode(&[r"%output %0 \033[1m\033[7m%\033[27m\015 \015"]);
        let Event::Output { pane, data } = &events[0] else {
            panic!("expected output, got {events:?}");
        };
        assert_eq!(pane, "%0");
        assert_eq!(data, b"\x1b[1m\x1b[7m%\x1b[27m\r \r");
    }

    #[test]
    fn a_literal_backslash_arrives_as_octal() {
        let events = decode([r"%output %0 \033k/tmp\033\134"].as_ref());
        let Event::Output { data, .. } = &events[0] else {
            panic!("expected output");
        };
        assert_eq!(data, b"\x1bk/tmp\x1b\\");
    }

    #[test]
    fn payloads_may_be_invalid_utf8() {
        let events = decode(&[r"%output %0 \377\376"]);
        let Event::Output { data, .. } = &events[0] else {
            panic!("expected output");
        };
        assert_eq!(data, &[0xff, 0xfe]);
    }

    #[test]
    fn raw_high_bytes_survive_the_decoder() {
        // The real wire format, unlike the escaped form above: tmux escapes
        // only bytes below 0x20 and the backslash, so anything from 0x80 up
        // arrives raw.
        let mut line = b"%output %0 A".to_vec();
        line.extend_from_slice(&[0xff, 0xfe]);
        line.extend_from_slice(b"B");

        let mut decoder = Decoder::new();
        let Some(Event::Output { data, .. }) = decoder.push(&line) else {
            panic!("expected output");
        };
        assert_eq!(data, b"A\xff\xfeB");
    }

    #[test]
    fn a_character_split_across_two_lines_is_not_corrupted() {
        // tmux chunks %output at a fixed size with no regard for character
        // boundaries, so this is the common case, not the exotic one.
        let heart = "\u{2764}".as_bytes();
        let mut decoder = Decoder::new();

        let mut first = b"%output %0 ".to_vec();
        first.extend_from_slice(&heart[..2]);
        let mut second = b"%output %0 ".to_vec();
        second.extend_from_slice(&heart[2..]);

        let mut all = Vec::new();
        for line in [first, second] {
            let Some(Event::Output { data, .. }) = decoder.push(&line) else {
                panic!("expected output");
            };
            all.extend(data);
        }
        assert_eq!(String::from_utf8(all).unwrap(), "\u{2764}");
    }

    #[test]
    fn a_lone_backslash_is_preserved() {
        let events = decode(&[r"%output %0 a\zb"]);
        let Event::Output { data, .. } = &events[0] else {
            panic!("expected output");
        };
        assert_eq!(data, b"a\\zb", "malformed escapes must not lose bytes");
    }

    #[test]
    fn command_output_starting_with_percent_is_not_a_notification() {
        // The exact hazard: `list-panes -F '#{pane_id}'` returns `%0`.
        let events = decode(&[
            "%begin 1785856377 280 1",
            "%0",
            "%1",
            "%end 1785856377 280 1",
        ]);
        assert_eq!(
            events,
            [Event::CommandReply {
                number: 280,
                lines: vec!["%0".into(), "%1".into()],
                error: false,
            }]
        );
    }

    #[test]
    fn even_output_notifications_inside_a_block_stay_literal() {
        let events = decode(&["%begin 1 5 0", "%output %0 not-really", "%end 1 5 0"]);
        assert_eq!(
            events,
            [Event::CommandReply {
                number: 5,
                lines: vec!["%output %0 not-really".into()],
                error: false,
            }]
        );
    }

    #[test]
    fn a_failed_command_is_flagged() {
        let events = decode(&["%begin 1 7 0", "no such window", "%error 1 7 0"]);
        assert_eq!(
            events,
            [Event::CommandReply {
                number: 7,
                lines: vec!["no such window".into()],
                error: true,
            }]
        );
    }

    #[test]
    fn an_empty_reply_still_arrives() {
        let events = decode(&["%begin 1 275 0", "%end 1 275 0"]);
        assert_eq!(
            events,
            [Event::CommandReply {
                number: 275,
                lines: vec![],
                error: false,
            }]
        );
    }

    #[test]
    fn block_state_is_observable() {
        let mut decoder = Decoder::new();
        assert!(!decoder.in_block());
        decoder.push("%begin 1 2 0");
        assert!(decoder.in_block());
        decoder.push("%end 1 2 0");
        assert!(!decoder.in_block());
    }

    #[test]
    fn strips_the_dcs_wrapper_and_carriage_returns() {
        let events = decode(&[
            "\x1bP1000p%begin 1785856377 275 0\r",
            "%end 1785856377 275 0\r",
        ]);
        assert_eq!(
            events,
            [Event::CommandReply {
                number: 275,
                lines: vec![],
                error: false,
            }]
        );
    }

    #[test]
    fn parses_session_and_window_notifications() {
        let events = decode(&[
            "%session-changed $0 demo",
            "%sessions-changed",
            "%window-add @3",
            "%window-close @3",
            "%window-renamed @1 editor",
            "%layout-change @1 bb62,80x24,0,0,1",
            "%pane-mode-changed %4",
        ]);
        assert_eq!(
            events,
            [
                Event::SessionChanged {
                    session: "$0".into(),
                    name: "demo".into()
                },
                Event::SessionsChanged,
                Event::WindowAdd {
                    window: "@3".into()
                },
                Event::WindowClose {
                    window: "@3".into()
                },
                Event::WindowRenamed {
                    window: "@1".into(),
                    name: "editor".into()
                },
                Event::LayoutChange {
                    window: "@1".into(),
                    layout: "bb62,80x24,0,0,1".into()
                },
                Event::PaneModeChanged { pane: "%4".into() },
            ]
        );
    }

    #[test]
    fn exit_carries_its_reason_when_there_is_one() {
        assert_eq!(
            decode(&["%exit"]),
            [Event::Exit { reason: None }],
            "a bare exit has no reason"
        );
        assert_eq!(
            decode(&["%exit server exited"]),
            [Event::Exit {
                reason: Some("server exited".into())
            }]
        );
    }

    #[test]
    fn unmodelled_notifications_are_surfaced_not_dropped() {
        let events = decode(&["%subscription-changed foo $0 @0 %0 : value"]);
        assert!(matches!(events[0], Event::Unknown { .. }));
    }

    #[test]
    fn echoed_input_outside_a_block_is_ignored() {
        // The pty echoes commands we write; they are not protocol.
        assert!(decode(&[r##"list-panes -F "#{pane_id}""##]).is_empty());
    }

    #[test]
    fn a_real_transcript_decodes_end_to_end() {
        let events = decode(&[
            r##"list-panes -F "#{pane_id}""##,
            "\x1bP1000p%begin 1785856377 275 0\r",
            "%end 1785856377 275 0\r",
            "%session-changed $0 demo\r",
            "%begin 1785856377 280 1\r",
            "%0\r",
            "%end 1785856377 280 1\r",
            r"%output %0 ABC\015",
            "%exit\r",
        ]);

        assert_eq!(events.len(), 5, "{events:#?}");
        assert!(matches!(events[0], Event::CommandReply { number: 275, .. }));
        assert!(matches!(events[1], Event::SessionChanged { .. }));
        let Event::CommandReply { lines, .. } = &events[2] else {
            panic!("expected the list-panes reply");
        };
        assert_eq!(lines, &["%0"]);
        assert!(matches!(events[3], Event::Output { .. }));
        assert_eq!(events[4], Event::Exit { reason: None });
    }
}