rmux-server 0.10.0

Tokio daemon and request dispatcher for the RMUX 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
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
use rmux_core::TerminalPaletteIndex;

#[derive(Debug, Clone, PartialEq, Eq)]
pub(in crate::handler) enum TerminalResponseDecode {
    NotResponse,
    Partial,
    PaneBound {
        size: usize,
    },
    PaletteResponse {
        size: usize,
        index: TerminalPaletteIndex,
    },
    ClipboardResponse {
        size: usize,
        selection: Option<u8>,
        content: Vec<u8>,
    },
    Matched {
        size: usize,
        event: Option<TerminalControlEvent>,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::handler) enum TerminalControlEvent {
    FocusIn,
    FocusOut,
    ClientLightTheme,
    ClientDarkTheme,
}

#[cfg(test)]
pub(super) fn decode_attached_terminal_control(
    input: &[u8],
    focus_passthrough: bool,
) -> TerminalResponseDecode {
    decode_attached_terminal_control_after_append(input, focus_passthrough, 0)
}

pub(in crate::handler) fn decode_attached_terminal_control_after_append(
    input: &[u8],
    focus_passthrough: bool,
    new_input_at: usize,
) -> TerminalResponseDecode {
    // `new_input_at` is the retained length before the current append. Each
    // decoder backs up only as far as its split terminator requires.
    match decode_osc_sequence(input, new_input_at) {
        TerminalResponseDecode::NotResponse => {}
        matched => return matched,
    }

    if !focus_passthrough {
        match decode_focus_response(input) {
            TerminalResponseDecode::NotResponse => {}
            matched => return matched,
        }
    }

    decode_terminal_response_after_append(input, new_input_at)
}

#[cfg(test)]
pub(super) fn decode_terminal_response(input: &[u8]) -> TerminalResponseDecode {
    decode_terminal_response_after_append(input, 0)
}

fn decode_terminal_response_after_append(
    input: &[u8],
    new_input_at: usize,
) -> TerminalResponseDecode {
    if !input.starts_with(b"\x1b[") {
        return TerminalResponseDecode::NotResponse;
    }

    let search_at = new_input_at.max(2).min(input.len());
    let mut final_index = None;
    for (offset, byte) in input[search_at..].iter().copied().enumerate() {
        if is_csi_final(byte) {
            final_index = Some(search_at + offset);
            break;
        }
        // A CSI body may contain only parameter/intermediate bytes before its
        // final byte. Treat C0 controls, DEL, ESC, and non-ASCII bytes as raw
        // pane input immediately instead of retaining a "terminal response"
        // that the pending-escape scheduler correctly cannot classify.
        if !(0x20..=0x3f).contains(&byte) {
            return TerminalResponseDecode::NotResponse;
        }
    }
    let Some(final_index) = final_index else {
        return if is_plausible_terminal_response_prefix(input) {
            TerminalResponseDecode::Partial
        } else {
            TerminalResponseDecode::NotResponse
        };
    };
    match input[final_index] {
        b'n' => matched(final_index + 1, decode_theme_report(input, final_index)),
        b'c' | b't' => matched(final_index + 1, None),
        b'y' if is_decrpm_response(input, final_index) => matched(final_index + 1, None),
        b'R' => TerminalResponseDecode::PaneBound {
            size: final_index + 1,
        },
        _ => TerminalResponseDecode::NotResponse,
    }
}

const fn matched(size: usize, event: Option<TerminalControlEvent>) -> TerminalResponseDecode {
    TerminalResponseDecode::Matched { size, event }
}

fn is_decrpm_response(input: &[u8], final_index: usize) -> bool {
    final_index > 2 && input.get(final_index - 1) == Some(&b'$')
}

pub(super) fn decode_focus_event(input: &[u8]) -> Option<TerminalControlEvent> {
    if input.starts_with(b"\x1b[I") {
        return Some(TerminalControlEvent::FocusIn);
    }
    if input.starts_with(b"\x1b[O") {
        return Some(TerminalControlEvent::FocusOut);
    }
    None
}

fn decode_focus_response(input: &[u8]) -> TerminalResponseDecode {
    match decode_focus_event(input) {
        Some(event) => matched(3, Some(event)),
        None => TerminalResponseDecode::NotResponse,
    }
}

fn decode_theme_report(input: &[u8], final_index: usize) -> Option<TerminalControlEvent> {
    match &input[..=final_index] {
        b"\x1b[?997;1n" => Some(TerminalControlEvent::ClientDarkTheme),
        b"\x1b[?997;2n" => Some(TerminalControlEvent::ClientLightTheme),
        _ => None,
    }
}

fn decode_osc_sequence(input: &[u8], new_input_at: usize) -> TerminalResponseDecode {
    if !input.starts_with(b"\x1b]") {
        return TerminalResponseDecode::NotResponse;
    }
    const CONSUMED_OSC_PREFIXES: &[&[u8]] = &[
        b"\x1b]4;",
        b"\x1b]10;",
        b"\x1b]11;",
        b"\x1b]12;",
        b"\x1b]52;",
    ];
    if CONSUMED_OSC_PREFIXES
        .iter()
        .any(|prefix| input.len() < prefix.len() && prefix.starts_with(input))
    {
        return TerminalResponseDecode::Partial;
    }
    if !CONSUMED_OSC_PREFIXES
        .iter()
        .any(|prefix| input.starts_with(prefix))
    {
        return TerminalResponseDecode::NotResponse;
    }

    let mut index = new_input_at.saturating_sub(1).max(2).min(input.len());
    while index < input.len() {
        match input[index] {
            b'\x07' => return decode_complete_osc_sequence(input, index, index + 1),
            b'\x1b' if input.get(index + 1) == Some(&b'\\') => {
                return decode_complete_osc_sequence(input, index, index + 2);
            }
            _ => index += 1,
        }
    }
    TerminalResponseDecode::Partial
}

fn decode_complete_osc_sequence(
    input: &[u8],
    body_end: usize,
    size: usize,
) -> TerminalResponseDecode {
    if input.starts_with(b"\x1b]4;") {
        if let Some(index) = decode_palette_response_body(&input[b"\x1b]4;".len()..body_end]) {
            return TerminalResponseDecode::PaletteResponse { size, index };
        }
    }
    if let Some(body) = input
        .strip_prefix(b"\x1b]52;")
        .and_then(|body| body.get(..body_end.saturating_sub(b"\x1b]52;".len())))
    {
        if let Some(response) = crate::clipboard_protocol::decode_clipboard_response_body(body) {
            return TerminalResponseDecode::ClipboardResponse {
                size,
                selection: response.selection,
                content: response.content,
            };
        }
    }
    matched(size, None)
}

fn decode_palette_response_body(body: &[u8]) -> Option<TerminalPaletteIndex> {
    let separator = body.iter().position(|byte| *byte == b';')?;
    let (index, value) = body.split_at(separator);
    let index = std::str::from_utf8(index)
        .ok()
        .and_then(TerminalPaletteIndex::parse)?;
    let rgb = value.get(1..)?.strip_prefix(b"rgb:")?;
    let mut channels = rgb.split(|byte| *byte == b'/');
    for _ in 0..3 {
        let channel = channels.next()?;
        if channel.is_empty() || channel.len() > 4 || !channel.iter().all(u8::is_ascii_hexdigit) {
            return None;
        }
    }
    if channels.next().is_some() {
        return None;
    }
    Some(index)
}

fn is_plausible_terminal_response_prefix(input: &[u8]) -> bool {
    input
        .get(2)
        .is_some_and(|byte| *byte == b'?' || *byte == b'>' || byte.is_ascii_digit())
}

fn is_csi_final(byte: u8) -> bool {
    (0x40..=0x7e).contains(&byte)
}

#[cfg(test)]
mod tests {
    use super::{
        decode_attached_terminal_control, decode_attached_terminal_control_after_append,
        decode_focus_event, decode_terminal_response, TerminalControlEvent, TerminalPaletteIndex,
        TerminalResponseDecode,
    };

    #[test]
    fn matches_primary_device_attributes_response() {
        assert_eq!(
            decode_terminal_response(b"\x1b[?62;52;ctail"),
            TerminalResponseDecode::Matched {
                size: 10,
                event: None
            }
        );
    }

    #[test]
    fn marks_cursor_position_response_as_pane_bound() {
        assert_eq!(
            decode_terminal_response(b"\x1b[12;40R"),
            TerminalResponseDecode::PaneBound { size: 8 }
        );
    }

    #[test]
    fn matches_decrpm_response() {
        assert_eq!(
            decode_terminal_response(b"\x1b[?2004;1$y"),
            TerminalResponseDecode::Matched {
                size: 11,
                event: None
            }
        );
    }

    #[test]
    fn matches_theme_reports() {
        assert_eq!(
            decode_terminal_response(b"\x1b[?997;1n"),
            TerminalResponseDecode::Matched {
                size: 9,
                event: Some(TerminalControlEvent::ClientDarkTheme)
            }
        );
        assert_eq!(
            decode_terminal_response(b"\x1b[?997;2n"),
            TerminalResponseDecode::Matched {
                size: 9,
                event: Some(TerminalControlEvent::ClientLightTheme)
            }
        );
        assert_eq!(
            decode_terminal_response(b"\x1b[?2031;1$y"),
            TerminalResponseDecode::Matched {
                size: 11,
                event: None
            }
        );
    }

    #[test]
    fn retains_fragmented_responses() {
        assert_eq!(
            decode_terminal_response(b"\x1b[?62;52"),
            TerminalResponseDecode::Partial
        );
    }

    #[test]
    fn invalid_csi_body_bytes_are_never_retained_as_terminal_responses() {
        for leader in [b'?', b'>', b'1'] {
            for invalid in [b'\0', b'\r', b'\x1b', b'\x7f', b'\x80', b'\xff'] {
                let input = [b'\x1b', b'[', leader, invalid];
                assert_eq!(
                    decode_attached_terminal_control_after_append(&input, false, 3),
                    TerminalResponseDecode::NotResponse,
                    "leader={leader:#04x}, invalid={invalid:#04x}"
                );
            }
        }
    }

    #[test]
    fn leaves_arrow_keys_for_key_decoder() {
        assert_eq!(
            decode_terminal_response(b"\x1b[A"),
            TerminalResponseDecode::NotResponse
        );
    }

    #[test]
    fn leaves_extended_keys_for_key_decoder() {
        assert_eq!(
            decode_terminal_response(b"\x1b[27;2;65u"),
            TerminalResponseDecode::NotResponse
        );
    }

    #[test]
    fn attached_terminal_control_consumes_focus_events_by_default() {
        assert_eq!(
            decode_attached_terminal_control(b"\x1b[Irest", false),
            TerminalResponseDecode::Matched {
                size: 3,
                event: Some(TerminalControlEvent::FocusIn)
            }
        );
        assert_eq!(
            decode_attached_terminal_control(b"\x1b[Orest", false),
            TerminalResponseDecode::Matched {
                size: 3,
                event: Some(TerminalControlEvent::FocusOut)
            }
        );
        assert_eq!(
            decode_focus_event(b"\x1b[Irest"),
            Some(TerminalControlEvent::FocusIn)
        );
    }

    #[test]
    fn attached_terminal_control_preserves_focus_events_for_focus_mode() {
        assert_eq!(
            decode_attached_terminal_control(b"\x1b[Irest", true),
            TerminalResponseDecode::NotResponse
        );
        assert_eq!(
            decode_attached_terminal_control(b"\x1b[Orest", true),
            TerminalResponseDecode::NotResponse
        );
    }

    #[test]
    fn attached_terminal_control_consumes_osc_sequences() {
        assert_eq!(
            decode_attached_terminal_control(b"\x1b]52;c;AAAA\x07tail", false),
            TerminalResponseDecode::ClipboardResponse {
                size: 12,
                selection: Some(b'c'),
                content: vec![0, 0, 0],
            }
        );
        assert_eq!(
            decode_attached_terminal_control(b"\x1b]52;c;AAAA\x1b\\tail", false),
            TerminalResponseDecode::ClipboardResponse {
                size: 13,
                selection: Some(b'c'),
                content: vec![0, 0, 0],
            }
        );
        assert_eq!(
            decode_attached_terminal_control(b"\x1b]52;c;AAAA", false),
            TerminalResponseDecode::Partial
        );
    }

    #[test]
    fn decodes_bounded_palette_responses_with_bel_or_st() {
        for (response, index) in [
            (b"\x1b]4;0;rgb:0000/1111/ffff\x07".as_slice(), 0),
            (b"\x1b]4;255;rgb:0/a/FFFF\x1b\\".as_slice(), 255),
        ] {
            assert_eq!(
                decode_attached_terminal_control(response, false),
                TerminalResponseDecode::PaletteResponse {
                    size: response.len(),
                    index: TerminalPaletteIndex::from(index),
                }
            );
        }
    }

    #[test]
    fn fragmented_palette_response_is_partial_until_its_terminator() {
        let response = b"\x1b]4;7;rgb:1111/2222/3333\x1b\\";
        for split in 2..response.len() {
            assert_eq!(
                decode_attached_terminal_control(&response[..split], false),
                TerminalResponseDecode::Partial,
                "palette response split at byte {split}"
            );
        }
        assert_eq!(
            decode_attached_terminal_control(response, false),
            TerminalResponseDecode::PaletteResponse {
                size: response.len(),
                index: TerminalPaletteIndex::from(7),
            }
        );
    }

    #[test]
    fn malformed_or_out_of_range_palette_sequences_are_consumed_not_forwarded() {
        for response in [
            b"\x1b]4;256;rgb:0000/0000/0000\x07".as_slice(),
            b"\x1b]4;0;not-rgb\x07".as_slice(),
            b"\x1b]4;0;rgb:00000/0/0\x07".as_slice(),
            b"\x1b]4;0;rgb:0/0/0;echo\x07".as_slice(),
        ] {
            assert_eq!(
                decode_attached_terminal_control(response, false),
                TerminalResponseDecode::Matched {
                    size: response.len(),
                    event: None,
                },
                "malformed OSC 4 must stay at the attach boundary: {response:?}"
            );
        }
    }

    #[test]
    fn incremental_osc_search_finds_terminators_at_append_boundary() {
        let bell_terminated = b"\x1b]52;c;AAAA\x07tail";
        let bell_at = b"\x1b]52;c;AAAA".len();
        assert_eq!(
            decode_attached_terminal_control_after_append(bell_terminated, false, bell_at),
            TerminalResponseDecode::ClipboardResponse {
                size: bell_at + 1,
                selection: Some(b'c'),
                content: vec![0, 0, 0],
            }
        );

        let string_terminated = b"\x1b]52;c;AAAA\x1b\\tail";
        let terminator_at = b"\x1b]52;c;AAAA".len();
        assert_eq!(
            decode_attached_terminal_control_after_append(
                string_terminated,
                false,
                terminator_at + 1,
            ),
            TerminalResponseDecode::ClipboardResponse {
                size: terminator_at + 2,
                selection: Some(b'c'),
                content: vec![0, 0, 0],
            }
        );
    }

    #[test]
    fn incremental_control_search_starts_at_the_append_boundary_overlap() {
        // Earlier final bytes are impossible in retained partial state. They
        // are sentinels that expose any scan which restarts before the cursor.
        let osc = b"\x1b]52;c;old\x07padding-padding-new\x07tail";
        let osc_new_input_at = b"\x1b]52;c;old\x07padding-padding-new".len();
        assert_eq!(
            decode_attached_terminal_control_after_append(osc, false, osc_new_input_at),
            TerminalResponseDecode::Matched {
                size: osc_new_input_at + 1,
                event: None,
            }
        );

        let csi = b"\x1b[?62;52cpadding-padding997;1n";
        let csi_new_input_at = b"\x1b[?62;52cpadding-padding".len();
        assert_eq!(
            decode_attached_terminal_control_after_append(csi, false, csi_new_input_at),
            TerminalResponseDecode::Matched {
                size: csi.len(),
                event: None,
            }
        );
    }

    #[test]
    fn attached_terminal_control_retains_ambiguous_alt_right_bracket_prefix() {
        assert_eq!(
            decode_attached_terminal_control(b"\x1b]", false),
            TerminalResponseDecode::Partial
        );
        assert_eq!(
            decode_attached_terminal_control(b"\x1b]X\x07", false),
            TerminalResponseDecode::NotResponse
        );
    }

    #[test]
    fn attached_terminal_control_retains_every_fragmented_osc52_prefix() {
        let response = b"\x1b]52;c;AAAA\x07";
        for split in 2..b"\x1b]52;".len() {
            assert_eq!(
                decode_attached_terminal_control(&response[..split], false),
                TerminalResponseDecode::Partial,
                "OSC52 prefix split at byte {split}"
            );
        }
    }
}