bmux_cli 0.0.1-alpha.0

Command-line interface for bmux terminal multiplexer
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
use super::{MIN_PANE_COLS, MIN_PANE_ROWS, PaneProcess, PaneRuntime, PaneState};
use crate::pane::{PaneId, Rect};
use crate::pty::extract_filtered_output;
use crate::runtime::terminal_protocol::{
    ProtocolProfile, SharedProtocolTraceBuffer, TerminalProtocolEngine,
};
use anyhow::{Context, Result};
use portable_pty::{CommandBuilder, PtySize, native_pty_system};
use std::collections::BTreeMap;
use std::io::{Read, Write};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Instant;
use vt100::Parser as VtParser;

pub(super) fn spawn_pane(
    pane_id: PaneId,
    shell: &str,
    scrollback_limit: usize,
    pane_term: &str,
    protocol_profile: ProtocolProfile,
    title: String,
    pane_inner: Rect,
    startup_deadline: Instant,
    user_input_seen: Arc<AtomicBool>,
    protocol_trace: Option<SharedProtocolTraceBuffer>,
) -> Result<PaneRuntime> {
    let state = Arc::new(PaneState {
        parser: Mutex::new(VtParser::new(
            pane_inner.height.max(MIN_PANE_ROWS),
            pane_inner.width.max(MIN_PANE_COLS),
            scrollback_limit,
        )),
        dirty: AtomicBool::new(true),
    });

    Ok(PaneRuntime {
        title: title.clone(),
        shell: shell.to_string(),
        process: Some(spawn_pane_process(
            shell,
            scrollback_limit,
            pane_term,
            protocol_profile,
            pane_id,
            title,
            pane_inner,
            startup_deadline,
            user_input_seen,
            Arc::clone(&state),
            protocol_trace,
        )?),
        state,
        closed: false,
        exit_code: None,
    })
}

pub(super) fn spawn_pane_process(
    shell: &str,
    scrollback_limit: usize,
    pane_term: &str,
    protocol_profile: ProtocolProfile,
    pane_id: PaneId,
    title: String,
    pane_inner: Rect,
    startup_deadline: Instant,
    user_input_seen: Arc<AtomicBool>,
    state: Arc<PaneState>,
    protocol_trace: Option<SharedProtocolTraceBuffer>,
) -> Result<PaneProcess> {
    let pty_system = native_pty_system();
    let pty_pair = pty_system
        .openpty(PtySize {
            rows: pane_inner.height.max(MIN_PANE_ROWS),
            cols: pane_inner.width.max(MIN_PANE_COLS),
            pixel_width: 0,
            pixel_height: 0,
        })
        .context("failed to open pane PTY")?;

    let mut command = CommandBuilder::new(shell);
    command.env("TERM", pane_term);
    let child = pty_pair
        .slave
        .spawn_command(command)
        .context("failed to spawn shell in pane")?;
    drop(pty_pair.slave);

    {
        let mut parser = state.parser.lock().expect("pane parser mutex poisoned");
        *parser = VtParser::new(
            pane_inner.height.max(MIN_PANE_ROWS),
            pane_inner.width.max(MIN_PANE_COLS),
            scrollback_limit,
        );
        parser.screen_mut().set_size(
            pane_inner.height.max(MIN_PANE_ROWS),
            pane_inner.width.max(MIN_PANE_COLS),
        );
    }
    state.dirty.store(true, Ordering::Relaxed);

    let mut reader = pty_pair
        .master
        .try_clone_reader()
        .context("failed to clone pane PTY reader")?;
    let writer = pty_pair
        .master
        .take_writer()
        .context("failed to open pane PTY writer")?;
    let writer = Arc::new(Mutex::new(writer));

    let state_for_thread = Arc::clone(&state);
    let writer_for_thread = Arc::clone(&writer);
    let output_thread = thread::Builder::new()
        .name(format!("bmux-pane-output-{title}"))
        .spawn(move || -> Result<()> {
            let mut buffer = [0_u8; 8192];
            let mut pending = Vec::new();
            let mut protocol_engine = if let Some(trace) = protocol_trace {
                TerminalProtocolEngine::with_trace(protocol_profile, pane_id.0, trace)
            } else {
                TerminalProtocolEngine::new(protocol_profile)
            };

            loop {
                let bytes_read = reader
                    .read(&mut buffer)
                    .context("failed reading pane PTY output")?;
                if bytes_read == 0 {
                    break;
                }

                pending.extend_from_slice(&buffer[..bytes_read]);
                let startup_guard_active =
                    !user_input_seen.load(Ordering::Relaxed) && Instant::now() < startup_deadline;

                let output = extract_filtered_output(&mut pending, startup_guard_active);

                if output.is_empty() {
                    continue;
                }

                let mut parser = state_for_thread
                    .parser
                    .lock()
                    .expect("pane parser mutex poisoned");
                parser.process(&output);
                let cursor_pos = parser.screen().cursor_position();
                state_for_thread.dirty.store(true, Ordering::Relaxed);
                drop(parser);

                let reply = protocol_engine.process_output(&output, cursor_pos);
                if !reply.is_empty() {
                    let mut writer = writer_for_thread
                        .lock()
                        .expect("pane PTY writer mutex poisoned");
                    writer
                        .write_all(&reply)
                        .and_then(|_| writer.flush())
                        .context("failed writing terminal protocol reply to pane")?;
                }
            }

            Ok(())
        })
        .context("failed to spawn pane output thread")?;

    Ok(PaneProcess {
        master: pty_pair.master,
        writer,
        child,
        output_thread: Some(output_thread),
    })
}

pub(super) fn refresh_exit_codes(panes: &mut BTreeMap<PaneId, PaneRuntime>) -> Result<()> {
    for pane in panes.values_mut() {
        let Some(process) = pane.process.as_mut() else {
            continue;
        };

        if let Some(status) = process
            .child
            .try_wait()
            .context("failed to poll pane shell status")?
        {
            pane.exit_code = Some(super::exit_code_from_u32(status.exit_code()));
            stop_pane_process(pane, false)?;
            pane.closed = false;
            pane.state.dirty.store(true, Ordering::Relaxed);
        }
    }

    Ok(())
}

pub(super) fn stop_pane_process(pane: &mut PaneRuntime, kill: bool) -> Result<()> {
    if let Some(mut process) = pane.process.take() {
        if kill {
            let _ = process.child.kill();
        }

        let _ = process.child.wait();

        if let Some(output_thread) = process.output_thread.take() {
            match output_thread.join() {
                Ok(result) => result.context("PTY output thread failed")?,
                Err(_) => return Err(anyhow::anyhow!("PTY output thread panicked")),
            }
        }
    }

    Ok(())
}

pub(super) fn pane_is_running(pane: &PaneRuntime) -> bool {
    pane.process.is_some()
}

pub(super) fn any_running_panes(panes: &BTreeMap<PaneId, PaneRuntime>) -> bool {
    panes.values().any(pane_is_running)
}

pub(super) fn first_running_pane_id(
    pane_order: &[PaneId],
    panes: &BTreeMap<PaneId, PaneRuntime>,
) -> Option<PaneId> {
    pane_order
        .iter()
        .find(|pane_id| panes.get(pane_id).is_some_and(pane_is_running))
        .copied()
}

pub(super) fn next_focusable_pane_id(
    pane_order: &[PaneId],
    panes: &BTreeMap<PaneId, PaneRuntime>,
    current: PaneId,
) -> PaneId {
    if pane_order.is_empty() {
        return current;
    }

    let current_index = pane_order
        .iter()
        .position(|pane_id| *pane_id == current)
        .unwrap_or(0);

    for offset in 1..=pane_order.len() {
        let index = (current_index + offset) % pane_order.len();
        let candidate = pane_order[index];
        if panes.get(&candidate).is_some_and(pane_is_running) {
            return candidate;
        }
    }

    current
}

pub(super) fn resize_panes(
    panes: &mut BTreeMap<PaneId, PaneRuntime>,
    pane_rects: &BTreeMap<PaneId, Rect>,
) -> Result<()> {
    for (pane_id, pane) in panes.iter_mut() {
        let Some(rect) = pane_rects.get(pane_id) else {
            continue;
        };
        let inner = rect.inner();

        if let Some(process) = pane.process.as_mut() {
            process
                .master
                .resize(PtySize {
                    rows: inner.height.max(MIN_PANE_ROWS),
                    cols: inner.width.max(MIN_PANE_COLS),
                    pixel_width: 0,
                    pixel_height: 0,
                })
                .context("failed to resize pane PTY")?;
        }

        let mut parser = pane
            .state
            .parser
            .lock()
            .expect("pane parser mutex poisoned");
        parser.screen_mut().set_size(
            inner.height.max(MIN_PANE_ROWS),
            inner.width.max(MIN_PANE_COLS),
        );
        pane.state.dirty.store(true, Ordering::Relaxed);
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::TerminalProtocolEngine;
    use crate::runtime::terminal_protocol::ProtocolProfile;
    use vt100::Parser as VtParser;

    struct ReplayFixture {
        profile: ProtocolProfile,
        chunks: Vec<Vec<u8>>,
        expected_reply: Vec<u8>,
        expected_render_contains: String,
    }

    fn process_chunks(profile: ProtocolProfile, chunks: &[&[u8]]) -> (String, Vec<u8>) {
        let mut parser = VtParser::new(10, 40, 100);
        let mut engine = TerminalProtocolEngine::new(profile);
        let mut replies = Vec::new();

        for chunk in chunks {
            parser.process(chunk);
            let cursor = parser.screen().cursor_position();
            replies.extend(engine.process_output(chunk, cursor));
        }

        (parser.screen().contents().to_string(), replies)
    }

    fn process_fixture(fixture: &ReplayFixture) -> (String, Vec<u8>) {
        let chunks: Vec<&[u8]> = fixture.chunks.iter().map(Vec::as_slice).collect();
        process_chunks(fixture.profile, &chunks)
    }

    fn parse_fixture(source: &str) -> ReplayFixture {
        let mut profile = ProtocolProfile::Conservative;
        let mut chunks = Vec::new();
        let mut expected_reply = Vec::new();
        let mut expected_render_contains = String::new();

        for raw_line in source.lines() {
            let line = raw_line.trim();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }

            if let Some(value) = line.strip_prefix("PROFILE:") {
                profile = match value.trim() {
                    "bmux" => ProtocolProfile::Bmux,
                    "xterm" => ProtocolProfile::Xterm,
                    "screen" => ProtocolProfile::Screen,
                    _ => ProtocolProfile::Conservative,
                };
                continue;
            }

            if let Some(value) = line.strip_prefix("CHUNK:") {
                chunks.push(unescape(value.trim()));
                continue;
            }

            if let Some(value) = line.strip_prefix("EXPECT_REPLY:") {
                expected_reply = unescape(value.trim());
                continue;
            }

            if let Some(value) = line.strip_prefix("EXPECT_RENDER_CONTAINS:") {
                expected_render_contains = value.trim().to_string();
            }
        }

        ReplayFixture {
            profile,
            chunks,
            expected_reply,
            expected_render_contains,
        }
    }

    fn unescape(value: &str) -> Vec<u8> {
        let mut out = Vec::new();
        let bytes = value.as_bytes();
        let mut i = 0;
        while i < bytes.len() {
            if bytes[i] == b'\\' && i + 1 < bytes.len() {
                match bytes[i + 1] {
                    b'x' if i + 3 < bytes.len() => {
                        let hi = bytes[i + 2] as char;
                        let lo = bytes[i + 3] as char;
                        let hex = format!("{hi}{lo}");
                        if let Ok(byte) = u8::from_str_radix(&hex, 16) {
                            out.push(byte);
                            i += 4;
                            continue;
                        }
                    }
                    b'n' => {
                        out.push(b'\n');
                        i += 2;
                        continue;
                    }
                    b'r' => {
                        out.push(b'\r');
                        i += 2;
                        continue;
                    }
                    b't' => {
                        out.push(b'\t');
                        i += 2;
                        continue;
                    }
                    b'\\' => {
                        out.push(b'\\');
                        i += 2;
                        continue;
                    }
                    _ => {}
                }
            }
            out.push(bytes[i]);
            i += 1;
        }
        out
    }

    #[test]
    fn mixed_output_and_queries_keeps_rendered_text_contiguous() {
        let (contents, replies) = process_chunks(
            ProtocolProfile::Xterm,
            &[b"hello ", b"\x1b[5n", b"world", b"\x1b[>c"],
        );

        assert!(contents.contains("hello world"));
        assert_eq!(replies, b"\x1b[0n\x1b[>0;115;0c");
    }

    #[test]
    fn split_query_sequences_preserve_text_and_reply_once() {
        let (contents, replies) = process_chunks(
            ProtocolProfile::Screen,
            &[b"ab", b"\x1b", b"[", b"?25$p", b"cd"],
        );

        assert!(contents.contains("abcd"));
        assert_eq!(replies, b"\x1b[?25;1$y");
    }

    #[test]
    fn replays_fish_startup_fixture() {
        let fixture = parse_fixture(include_str!("fixtures/fish_startup.trace"));
        let (contents, replies) = process_fixture(&fixture);
        assert!(contents.contains(&fixture.expected_render_contains));
        assert_eq!(replies, fixture.expected_reply);
    }

    #[test]
    fn replays_vim_startup_fixture() {
        let fixture = parse_fixture(include_str!("fixtures/vim_startup.trace"));
        let (contents, replies) = process_fixture(&fixture);
        assert!(contents.contains(&fixture.expected_render_contains));
        assert_eq!(replies, fixture.expected_reply);
    }

    #[test]
    fn replays_fzf_startup_fixture() {
        let fixture = parse_fixture(include_str!("fixtures/fzf_startup.trace"));
        let (contents, replies) = process_fixture(&fixture);
        assert!(contents.contains(&fixture.expected_render_contains));
        assert_eq!(replies, fixture.expected_reply);
    }

    #[test]
    fn replays_less_startup_fixture() {
        let fixture = parse_fixture(include_str!("fixtures/less_startup.trace"));
        let (contents, replies) = process_fixture(&fixture);
        assert!(contents.contains(&fixture.expected_render_contains));
        assert_eq!(replies, fixture.expected_reply);
    }
}