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
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
use super::*;
use crate::outer_terminal::OuterTerminal;
use crate::pane_io::live_render::LivePaneRender;
use crate::pane_io::types::{pane_output_channel, AttachTarget, PaneOutputSender};
use rmux_core::PaneGeometry;
use rmux_proto::TerminalSize;
fn deep_coalescible_target(
    output: &PaneOutputSender,
    marker: u8,
    render_len: usize,
) -> AttachTarget {
    let size = TerminalSize { cols: 10, rows: 4 };
    let session = rmux_core::Session::new(
        rmux_proto::SessionName::new(format!("switch-{marker}")).expect("valid session name"),
        size,
    );
    let pane = session
        .window()
        .active_pane()
        .expect("session has an active pane")
        .clone();
    let transcript = crate::pane_transcript::PaneTranscript::shared(64, size);
    transcript
        .lock()
        .expect("pane transcript mutex must not be poisoned")
        .append_bytes(&[marker]);
    let live_pane = Some(
        LivePaneRender::new_from_transcript(
            transcript,
            session,
            rmux_core::OptionStore::new(),
            pane,
        )
        .expect("test target has a live render snapshot"),
    );
    let (pane_output_start_sequence, pane_output) = output.subscribe_live_from_now();
    AttachTarget {
        session_name: rmux_proto::SessionName::new(format!("switch-{marker}"))
            .expect("valid session name"),
        pane_master: None,
        pane_output,
        pane_output_start_sequence,
        render_frame: vec![marker; render_len.max(1)],
        outer_terminal: OuterTerminal::resolve(
            &rmux_core::OptionStore::default(),
            crate::outer_terminal::OuterTerminalContext::default(),
        ),
        client_title: None,
        cursor_style: 0,
        active_pane_geometry: PaneGeometry::new(0, 0, size.cols, size.rows),
        raw_passthrough: false,
        kitty_graphics_passthrough: false,
        sixel_passthrough: false,
        persistent_overlay_state_id: None,
        live_pane,
    }
}

#[test]
fn attach_control_sender_retains_only_latest_consecutive_deep_switch() {
    let (inner, mut receiver) = mpsc::unbounded_channel();
    let backlog = Arc::new(AtomicUsize::new(0));
    let sender = AttachControlSender::new(
        inner,
        Arc::clone(&backlog),
        64,
        Arc::new(AtomicBool::new(false)),
    );
    let second_producer = sender.clone();
    let output = pane_output_channel();

    for marker in 0_u8..64 {
        let producer = if marker % 2 == 0 {
            &sender
        } else {
            &second_producer
        };
        producer
            .send(AttachControl::switch(deep_coalescible_target(
                &output, marker, 32,
            )))
            .expect("replacement switch fits");
        assert_eq!(
            output.receiver_count_for_test(),
            1,
            "replacing marker {marker} must drop the previous deep target"
        );
    }

    assert_eq!(backlog.load(Ordering::Acquire), 1);
    let control = receiver.try_recv().expect("one coalesced switch is queued");
    assert_eq!(control.received_backlog_units(), 0);
    let AttachControl::Switch(target) = control else {
        panic!("expected a switch control");
    };
    let (target, switch_count) = target.into_target_with_count();
    assert_eq!(switch_count, 64, "render generations must remain aligned");
    assert_eq!(target.render_frame[0], 63);
    assert_eq!(backlog.load(Ordering::Acquire), 0);
    assert!(matches!(
        receiver.try_recv(),
        Err(mpsc::error::TryRecvError::Empty)
    ));
    drop(target);
    assert_eq!(output.receiver_count_for_test(), 0);
}

#[test]
fn interleaved_controls_cannot_open_unbounded_deep_switch_slots() {
    let (inner, mut receiver) = mpsc::unbounded_channel();
    let backlog = Arc::new(AtomicUsize::new(0));
    let closing = Arc::new(AtomicBool::new(false));
    let sender = AttachControlSender::new(inner, Arc::clone(&backlog), 16, Arc::clone(&closing));
    let second_producer = sender.clone();
    let output = pane_output_channel();

    for marker in 0..AttachControlSender::MAX_PENDING_DEEP_SWITCHES as u8 {
        let producer = if marker % 2 == 0 {
            &sender
        } else {
            &second_producer
        };
        producer
            .send(AttachControl::switch(deep_coalescible_target(
                &output, marker, 8,
            )))
            .expect("bounded coalesced slot fits");
        producer
            .send(AttachControl::Refresh)
            .expect("interleaved ordering boundary fits");
    }
    assert_eq!(
        sender.pending_deep_switches.load(Ordering::Acquire),
        AttachControlSender::MAX_PENDING_DEEP_SWITCHES
    );

    let rejected_marker = AttachControlSender::MAX_PENDING_DEEP_SWITCHES as u8;
    let error = second_producer
        .send(AttachControl::switch(deep_coalescible_target(
            &output,
            rejected_marker,
            8,
        )))
        .expect_err("interleaved controls cannot bypass the deep target cap");

    assert!(error.is_full());
    assert!(closing.load(Ordering::SeqCst));
    assert_eq!(
        output.receiver_count_for_test(),
        AttachControlSender::MAX_PENDING_DEEP_SWITCHES
    );
    assert_eq!(
        backlog.load(Ordering::Acquire),
        AttachControlSender::MAX_PENDING_DEEP_SWITCHES * 2 + 1,
        "each switch/boundary pair and one terminal detach remain accounted"
    );

    for marker in 0..AttachControlSender::MAX_PENDING_DEEP_SWITCHES as u8 {
        let AttachControl::Switch(target) = receiver.try_recv().expect("ordered switch") else {
            panic!("expected an ordered switch");
        };
        assert_eq!(target.into_target().render_frame[0], marker);
        let boundary = receiver.try_recv().expect("ordered refresh boundary");
        assert!(matches!(&boundary, AttachControl::Refresh));
        release_attach_control_backlog(&backlog, boundary.received_backlog_units());
    }
    assert_eq!(sender.pending_deep_switches.load(Ordering::Acquire), 0);
    let detach = receiver.try_recv().expect("terminal detach sentinel");
    assert!(matches!(&detach, AttachControl::Detach));
    release_attach_control_backlog(&backlog, detach.received_backlog_units());
    assert_eq!(backlog.load(Ordering::Acquire), 0);
}

#[test]
fn attach_control_sender_closes_switch_slot_at_interleaved_control() {
    let (inner, mut receiver) = mpsc::unbounded_channel();
    let backlog = Arc::new(AtomicUsize::new(0));
    let sender = AttachControlSender::new(
        inner,
        Arc::clone(&backlog),
        8,
        Arc::new(AtomicBool::new(false)),
    );
    let second_producer = sender.clone();
    let output = pane_output_channel();

    sender
        .send(AttachControl::switch(deep_coalescible_target(
            &output, 1, 8,
        )))
        .expect("first switch fits");
    second_producer
        .send(AttachControl::Write(b"boundary".to_vec()))
        .expect("interleaved boundary fits");
    sender
        .send(AttachControl::switch(deep_coalescible_target(
            &output, 2, 8,
        )))
        .expect("second switch fits");

    let AttachControl::Switch(first) = receiver.try_recv().expect("first switch") else {
        panic!("expected the first switch");
    };
    assert_eq!(first.into_target().render_frame[0], 1);
    let boundary = receiver.try_recv().expect("boundary control");
    assert!(matches!(&boundary, AttachControl::Write(bytes) if bytes == b"boundary"));
    release_attach_control_backlog(&backlog, boundary.received_backlog_units());
    let AttachControl::Switch(second) = receiver.try_recv().expect("second switch") else {
        panic!("expected the second switch");
    };
    assert_eq!(second.into_target().render_frame[0], 2);
    assert_eq!(backlog.load(Ordering::Acquire), 0);
}

#[test]
fn attach_control_sender_does_not_coalesce_persistent_switches() {
    let (inner, mut receiver) = mpsc::unbounded_channel();
    let backlog = Arc::new(AtomicUsize::new(0));
    let sender = AttachControlSender::new(
        inner,
        Arc::clone(&backlog),
        8,
        Arc::new(AtomicBool::new(false)),
    );
    let output = pane_output_channel();
    for marker in [1_u8, 2] {
        let mut target = deep_coalescible_target(&output, marker, 8);
        target.persistent_overlay_state_id = Some(u64::from(marker));
        sender
            .send(AttachControl::switch(target))
            .expect("persistent switch fits");
    }

    for marker in [1_u8, 2] {
        let control = receiver
            .try_recv()
            .expect("persistent switch remains queued");
        release_attach_control_backlog(&backlog, control.received_backlog_units());
        let AttachControl::Switch(target) = control else {
            panic!("expected a persistent switch");
        };
        assert_eq!(target.into_target().render_frame[0], marker);
    }
    assert!(matches!(
        receiver.try_recv(),
        Err(mpsc::error::TryRecvError::Empty)
    ));
    assert_eq!(backlog.load(Ordering::Acquire), 0);
}

#[test]
fn attach_control_sender_bounds_non_coalescible_deep_switches() {
    let (inner, mut receiver) = mpsc::unbounded_channel();
    let backlog = Arc::new(AtomicUsize::new(0));
    let closing = Arc::new(AtomicBool::new(false));
    let sender = AttachControlSender::new(inner, Arc::clone(&backlog), 16, Arc::clone(&closing));
    let second_producer = sender.clone();
    let output = pane_output_channel();
    for marker in 0..AttachControlSender::MAX_PENDING_DEEP_SWITCHES as u8 {
        let mut target = deep_coalescible_target(&output, marker, 8);
        target.persistent_overlay_state_id = Some(u64::from(marker));
        let producer = if marker % 2 == 0 {
            &sender
        } else {
            &second_producer
        };
        producer
            .send(AttachControl::switch(target))
            .expect("bounded persistent switch fits");
    }
    assert_eq!(
        sender.pending_deep_switches.load(Ordering::Acquire),
        AttachControlSender::MAX_PENDING_DEEP_SWITCHES
    );

    let rejected_marker = AttachControlSender::MAX_PENDING_DEEP_SWITCHES as u8;
    let mut rejected = deep_coalescible_target(&output, rejected_marker, 8);
    rejected.persistent_overlay_state_id = Some(u64::from(rejected_marker));
    let error = second_producer
        .send(AttachControl::switch(rejected))
        .expect_err("deep non-coalescible retention is capped");

    assert!(error.is_full());
    assert!(closing.load(Ordering::SeqCst));
    assert_eq!(
        output.receiver_count_for_test(),
        AttachControlSender::MAX_PENDING_DEEP_SWITCHES,
        "the rejected deep target must be dropped immediately"
    );
    assert_eq!(
        backlog.load(Ordering::Acquire),
        AttachControlSender::MAX_PENDING_DEEP_SWITCHES + 1,
        "queued switches and one terminal detach remain accounted"
    );

    for marker in 0..AttachControlSender::MAX_PENDING_DEEP_SWITCHES as u8 {
        let control = receiver
            .try_recv()
            .expect("persistent switch remains ordered");
        release_attach_control_backlog(&backlog, control.received_backlog_units());
        let AttachControl::Switch(target) = control else {
            panic!("expected a persistent switch");
        };
        assert_eq!(target.into_target().render_frame[0], marker);
    }
    assert_eq!(sender.pending_deep_switches.load(Ordering::Acquire), 0);
    let detach = receiver.try_recv().expect("terminal detach sentinel");
    assert!(matches!(&detach, AttachControl::Detach));
    release_attach_control_backlog(&backlog, detach.received_backlog_units());
    assert_eq!(backlog.load(Ordering::Acquire), 0);
}

#[test]
fn dropping_attach_control_receiver_releases_coalesced_switch() {
    let (inner, receiver) = mpsc::unbounded_channel();
    let backlog = Arc::new(AtomicUsize::new(0));
    let sender = AttachControlSender::new(
        inner,
        Arc::clone(&backlog),
        8,
        Arc::new(AtomicBool::new(false)),
    );
    let output = pane_output_channel();
    sender
        .send(AttachControl::switch(deep_coalescible_target(
            &output, 1, 8,
        )))
        .expect("switch fits");
    assert_eq!(backlog.load(Ordering::Acquire), 1);
    assert_eq!(output.receiver_count_for_test(), 1);

    drop(receiver);

    assert_eq!(backlog.load(Ordering::Acquire), 0);
    assert_eq!(output.receiver_count_for_test(), 0);
    assert!(sender.is_closed());
}

#[test]
fn dropping_attach_control_receiver_releases_deep_switch_permit() {
    let (inner, receiver) = mpsc::unbounded_channel();
    let backlog = Arc::new(AtomicUsize::new(0));
    let sender = AttachControlSender::new(
        inner,
        Arc::clone(&backlog),
        8,
        Arc::new(AtomicBool::new(false)),
    );
    let output = pane_output_channel();
    let mut target = deep_coalescible_target(&output, 1, 8);
    target.persistent_overlay_state_id = Some(1);
    sender
        .send(AttachControl::switch(target))
        .expect("persistent switch fits");
    assert_eq!(sender.pending_deep_switches.load(Ordering::Acquire), 1);
    assert_eq!(backlog.load(Ordering::Acquire), 1);

    drop(receiver);

    assert_eq!(sender.pending_deep_switches.load(Ordering::Acquire), 0);
    assert_eq!(backlog.load(Ordering::Acquire), 0);
    assert_eq!(output.receiver_count_for_test(), 0);
    assert!(sender.is_closed());
}

#[test]
fn growing_coalesced_switch_still_enforces_weighted_limit() {
    let (inner, mut receiver) = mpsc::unbounded_channel();
    let backlog = Arc::new(AtomicUsize::new(0));
    let closing = Arc::new(AtomicBool::new(false));
    let sender = AttachControlSender::new(inner, Arc::clone(&backlog), 1, Arc::clone(&closing));
    let output = pane_output_channel();
    sender
        .send(AttachControl::switch(deep_coalescible_target(
            &output, 1, 8,
        )))
        .expect("small switch fits");

    let error = sender
        .send(AttachControl::switch(deep_coalescible_target(
            &output,
            2,
            AttachControl::BACKLOG_UNIT_BYTES,
        )))
        .expect_err("larger replacement exceeds the weighted limit");

    assert!(error.is_full());
    assert!(closing.load(Ordering::SeqCst));
    assert_eq!(
        output.receiver_count_for_test(),
        1,
        "the rejected replacement is dropped while the earlier queued target survives"
    );
    assert_eq!(
        backlog.load(Ordering::Acquire),
        2,
        "the original slot and one terminal detach sentinel remain accounted"
    );
    let AttachControl::Switch(target) = receiver.try_recv().expect("original switch") else {
        panic!("expected the original switch");
    };
    assert_eq!(target.into_target().render_frame[0], 1);
    let detach = receiver.try_recv().expect("terminal detach sentinel");
    assert!(matches!(&detach, AttachControl::Detach));
    release_attach_control_backlog(&backlog, detach.received_backlog_units());
    assert_eq!(backlog.load(Ordering::Acquire), 0);
}

#[test]
fn attach_control_sender_shares_one_weighted_budget_across_payload_types() {
    let (inner, mut receiver) = mpsc::unbounded_channel();
    let backlog = Arc::new(AtomicUsize::new(0));
    let closing = Arc::new(AtomicBool::new(false));
    let sender = AttachControlSender::new(inner, Arc::clone(&backlog), 3, Arc::clone(&closing));

    sender
        .send(AttachControl::Refresh)
        .expect("one small control fits");
    sender
        .send(AttachControl::Overlay(OverlayFrame::new(
            vec![b'x'; AttachControl::BACKLOG_UNIT_BYTES],
            0,
            0,
        )))
        .expect("two-unit overlay fills the shared budget");
    assert_eq!(backlog.load(Ordering::Acquire), 3);

    let received = receiver.try_recv().expect("receive first control");
    release_attach_control_backlog(&backlog, received.backlog_units());
    assert_eq!(backlog.load(Ordering::Acquire), 2);
    sender
        .send(AttachControl::ClipboardWrite {
            bytes: vec![b'y'],
            reservation: None,
        })
        .expect("released control capacity is reusable");
    assert_eq!(backlog.load(Ordering::Acquire), 3);

    assert!(sender.send(AttachControl::Refresh).is_err());
    assert!(closing.load(Ordering::SeqCst));
    assert_eq!(
        backlog.load(Ordering::Acquire),
        4,
        "one accounted unit of terminal headroom is added exactly once"
    );
    assert!(sender.send(AttachControl::Refresh).is_err());
    assert_eq!(backlog.load(Ordering::Acquire), 4);

    while let Ok(control) = receiver.try_recv() {
        release_attach_control_backlog(&backlog, control.received_backlog_units());
        drop(control);
    }
    assert_eq!(backlog.load(Ordering::Acquire), 0);
}

#[test]
fn attach_control_sender_rolls_back_reservation_when_receiver_closed() {
    let (inner, receiver) = mpsc::unbounded_channel();
    let backlog = Arc::new(AtomicUsize::new(0));
    let closing = Arc::new(AtomicBool::new(false));
    let sender = AttachControlSender::new(inner, Arc::clone(&backlog), 4, Arc::clone(&closing));
    sender
        .send(AttachControl::Refresh)
        .expect("queued control reserves one unit");
    assert_eq!(backlog.load(Ordering::Acquire), 1);
    drop(receiver);

    assert!(sender
        .send(AttachControl::Write(vec![
            b'x';
            AttachControl::BACKLOG_UNIT_BYTES
        ]))
        .is_err());
    assert_eq!(backlog.load(Ordering::Acquire), 0);
    assert!(closing.load(Ordering::SeqCst));
}

#[test]
fn payload_control_cannot_release_a_later_control_reservation() {
    let (inner, mut receiver) = mpsc::unbounded_channel();
    let backlog = Arc::new(AtomicUsize::new(0));
    let sender = AttachControlSender::new(
        inner,
        Arc::clone(&backlog),
        4,
        Arc::new(AtomicBool::new(false)),
    );

    sender
        .send(AttachControl::Write(b"payload".to_vec()))
        .expect("payload control fits");
    sender
        .send(AttachControl::Refresh)
        .expect("refresh control fits");
    assert_eq!(backlog.load(Ordering::Acquire), 2);

    let payload = receiver.try_recv().expect("payload arrives first");
    release_attach_control_backlog(&backlog, payload.received_backlog_units());
    assert_eq!(backlog.load(Ordering::Acquire), 1);
    let refresh = receiver.try_recv().expect("refresh remains queued");
    assert!(matches!(&refresh, AttachControl::Refresh));
    release_attach_control_backlog(&backlog, refresh.received_backlog_units());
    assert_eq!(backlog.load(Ordering::Acquire), 0);
}

#[test]
fn receiver_deferred_clipboard_cannot_release_a_later_control_reservation() {
    let (inner, mut receiver) = mpsc::unbounded_channel();
    let backlog = Arc::new(AtomicUsize::new(0));
    let sender = AttachControlSender::new(
        inner,
        Arc::clone(&backlog),
        4,
        Arc::new(AtomicBool::new(false)),
    );

    sender
        .send(AttachControl::ClipboardWrite {
            bytes: vec![b'x'],
            reservation: None,
        })
        .expect("clipboard control fits");
    sender
        .send(AttachControl::Refresh)
        .expect("later refresh control fits");
    assert_eq!(backlog.load(Ordering::Acquire), 2);

    let clipboard = receiver.try_recv().expect("clipboard control arrives");
    assert_eq!(clipboard.received_backlog_units(), 0);
    release_attach_control_backlog(&backlog, clipboard.received_backlog_units());
    assert_eq!(backlog.load(Ordering::Acquire), 2);
    drop(clipboard);
    assert_eq!(
        backlog.load(Ordering::Acquire),
        1,
        "the later refresh keeps its own reservation"
    );
    let refresh = receiver.try_recv().expect("refresh remains queued");
    release_attach_control_backlog(&backlog, refresh.received_backlog_units());
    assert_eq!(backlog.load(Ordering::Acquire), 0);
}

#[test]
fn every_attach_control_variant_has_a_positive_backlog_cost() {
    let shell = AttachShellCommand::new("cmd".to_owned(), "sh".to_owned(), "/".to_owned());
    let controls = [
        AttachControl::Detach,
        AttachControl::Exited,
        AttachControl::DetachKill,
        AttachControl::DetachExecShellCommand(shell.clone()),
        AttachControl::InteractiveInput,
        AttachControl::Refresh,
        AttachControl::AdvancePersistentOverlayState(1),
        AttachControl::Overlay(OverlayFrame::new(Vec::new(), 0, 0)),
        AttachControl::Write(Vec::new()),
        AttachControl::ClipboardWrite {
            bytes: Vec::new(),
            reservation: None,
        },
        AttachControl::LockShellCommand(shell),
        AttachControl::Suspend,
    ];

    for control in controls {
        assert_eq!(control.backlog_units(), 1, "{control:?}");
    }

    let large = vec![b'x'; AttachControl::BACKLOG_UNIT_BYTES];
    let large_text = "x".repeat(AttachControl::BACKLOG_UNIT_BYTES);
    let weighted_payloads = [
        AttachControl::Overlay(OverlayFrame::new(large.clone(), 0, 0)),
        AttachControl::Write(large.clone()),
        AttachControl::ClipboardWrite {
            bytes: large,
            reservation: None,
        },
        AttachControl::DetachExecShellCommand(AttachShellCommand::new(
            large_text.clone(),
            String::new(),
            String::new(),
        )),
        AttachControl::LockShellCommand(AttachShellCommand::new(
            large_text,
            String::new(),
            String::new(),
        )),
    ];
    for control in weighted_payloads {
        assert_eq!(
            control.backlog_units(),
            2,
            "{:?}",
            std::mem::discriminant(&control)
        );
    }

    let output = pane_output_channel();
    let (pane_output_start_sequence, pane_output) = output.subscribe_live_from_now();
    let target = AttachTarget {
        session_name: rmux_proto::SessionName::new("backlog-cost").expect("valid session name"),
        pane_master: None,
        pane_output,
        pane_output_start_sequence,
        render_frame: vec![b'x'; AttachControl::BACKLOG_UNIT_BYTES],
        outer_terminal: OuterTerminal::resolve(
            &rmux_core::OptionStore::default(),
            crate::outer_terminal::OuterTerminalContext::default(),
        ),
        client_title: None,
        cursor_style: 0,
        active_pane_geometry: PaneGeometry::new(0, 0, 80, 24),
        raw_passthrough: false,
        kitty_graphics_passthrough: false,
        sixel_passthrough: false,
        persistent_overlay_state_id: None,
        live_pane: None,
    };
    assert_eq!(AttachControl::switch(target).backlog_units(), 2);
}

/// A plain render refresh with no title still replaces its predecessor in the
/// sender's coalescing slot: only the newest frame is worth drawing.
#[test]
fn a_titleless_switch_is_still_replaced_by_a_later_refresh() {
    let (inner, mut receiver) = mpsc::unbounded_channel();
    let backlog = Arc::new(AtomicUsize::new(0));
    let sender = AttachControlSender::new(
        inner,
        Arc::clone(&backlog),
        64,
        Arc::new(AtomicBool::new(false)),
    );
    let output = pane_output_channel();

    for marker in 0_u8..3 {
        let mut target = deep_coalescible_target(&output, marker, 32);
        target.live_pane = None;
        assert!(target.is_coalescible_render_refresh());
        sender
            .send(AttachControl::switch(target))
            .expect("refresh fits");
    }

    let AttachControl::Switch(queued) = receiver.try_recv().expect("one switch is queued") else {
        panic!("expected a switch control");
    };
    assert_eq!(queued.into_target_with_count().0.render_frame[0], 2);
    assert!(matches!(
        receiver.try_recv(),
        Err(mpsc::error::TryRecvError::Empty)
    ));
}

/// A frame carrying OSC 0 must survive the sender's coalescing slot. The render
/// path commits the title to the client's remembered identity when it builds
/// the frame, and the next render deduplicates against that memory — so a
/// silently replaced frame leaves the outer terminal on the previous title with
/// nothing left to correct it (issue #182).
///
/// This runs at the queue layer on purpose: every render-level test still sees
/// the title in the frame it built, so only the queue can prove the frame is
/// actually delivered.
#[test]
fn a_title_carrying_switch_is_not_replaced_by_a_later_refresh() {
    let (inner, mut receiver) = mpsc::unbounded_channel();
    let backlog = Arc::new(AtomicUsize::new(0));
    let sender = AttachControlSender::new(
        inner,
        Arc::clone(&backlog),
        64,
        Arc::new(AtomicBool::new(false)),
    );
    let output = pane_output_channel();

    let terminal = OuterTerminal::resolve(
        &rmux_core::OptionStore::new(),
        crate::outer_terminal::OuterTerminalContext::from_pairs(&[("TERM", "tmux-256color")]),
    );
    let update = crate::outer_terminal::ClientTitleUpdate {
        resolved: Some("QUEUED-TITLE"),
        path: crate::outer_terminal::ClientPathUpdate::Unread,
        previous: None,
    };
    let mut carrying = deep_coalescible_target(&output, 0, 32);
    carrying.live_pane = None;
    carrying.render_frame = terminal.render_client_title(update);
    carrying.client_title = terminal.rendered_client_title(update);
    carrying.outer_terminal = terminal;
    assert!(
        !carrying.render_frame.is_empty(),
        "the fixture terminal must advertise the title capability"
    );
    assert!(
        !carrying.is_coalescible_render_refresh(),
        "a frame that carries OSC 0 must not be a replaceable refresh"
    );
    // It is still a re-render of the same pane. Only queue replaceability is
    // withdrawn — live-output continuity (`preserves_live_output`, exercised on
    // Unix in pane_io::tests) must not be, or a title change would drop the
    // pane's buffered kitty/sixel passthroughs.
    assert!(
        carrying.is_plain_render_refresh(),
        "withdrawing replaceability must not make this look like a pane switch"
    );

    sender
        .send(AttachControl::switch(carrying))
        .expect("title switch fits");
    // The follow-up deduplicated the title away, exactly as the next render does.
    let mut follow_up = deep_coalescible_target(&output, 1, 32);
    follow_up.live_pane = None;
    sender
        .send(AttachControl::switch(follow_up))
        .expect("follow-up refresh fits");

    let AttachControl::Switch(first) = receiver.try_recv().expect("the title switch is queued")
    else {
        panic!("expected a switch control");
    };
    let first = first.into_target_with_count().0;
    assert_eq!(
        String::from_utf8_lossy(&first.render_frame),
        "\u{1b}]0;QUEUED-TITLE\u{7}",
        "the title-carrying frame must reach the client"
    );

    let AttachControl::Switch(second) = receiver.try_recv().expect("the follow-up is queued")
    else {
        panic!("expected a switch control");
    };
    assert_eq!(second.into_target_with_count().0.render_frame[0], 1);
}

/// Withdrawing queue replaceability must not cost the pane's live output.
///
/// `preserves_live_output` decides whether the passthroughs buffered behind the
/// current target (kitty graphics, sixel) are re-emitted or dropped as if the
/// client had switched panes. A title-carrying frame re-renders the very same
/// pane, so they must survive — coupling that decision to the queue gate would
/// silently drop graphics on every title change (issue #182).
///
/// `pane_io::tests` covers the same invariant on Unix; this keeps it under
/// Windows native authority, where that module is not compiled.
#[test]
fn a_title_carrying_refresh_keeps_the_pane_live_output() {
    let output = pane_output_channel();
    let mut current = deep_coalescible_target(&output, 0, 32);
    current.live_pane = None;
    let current =
        crate::pane_io::wire::open_attach_target(current, false).expect("the current target opens");

    let terminal = OuterTerminal::resolve(
        &rmux_core::OptionStore::new(),
        crate::outer_terminal::OuterTerminalContext::from_pairs(&[("TERM", "tmux-256color")]),
    );
    let mut carrying = deep_coalescible_target(&output, 1, 32);
    carrying.live_pane = None;
    carrying.client_title =
        terminal.rendered_client_title(crate::outer_terminal::ClientTitleUpdate {
            resolved: Some("LIVE-OUTPUT-TITLE"),
            path: crate::outer_terminal::ClientPathUpdate::Unread,
            previous: None,
        });
    assert!(!carrying.is_coalescible_render_refresh());

    assert!(
        crate::pane_io::control::preserves_live_output(&current, &carrying),
        "a title-carrying refresh of the same pane must keep its live output"
    );
}