rmux-server 0.1.1

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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
use super::{scripting_support::format_context_for_target, QueuedLifecycleEvent, RequestHandler};
use crate::format_runtime::render_runtime_template;
use crate::pane_io::AttachControl;
use rmux_core::{WINLINK_ACTIVITY, WINLINK_BELL, WINLINK_SILENCE};
use rmux_proto::{
    DisplayMessageRequest, HookName, KillWindowRequest, NewSessionExtRequest, NewSessionRequest,
    NewWindowRequest, NextWindowRequest, OptionName, PreviousWindowRequest, Request, Response,
    ScopeSelector, SessionName, SetOptionMode, SetOptionRequest, ShowMessagesRequest, Target,
    TerminalSize, WindowTarget,
};
#[cfg(unix)]
use rmux_proto::{PaneTarget, SendKeysRequest};
use tokio::sync::{broadcast, mpsc};
use tokio::time::{timeout, Duration};

fn session_name(value: &str) -> SessionName {
    SessionName::new(value).expect("valid session name")
}

async fn create_session(handler: &RequestHandler, name: &str) -> SessionName {
    let session = session_name(name);
    let response = handler
        .handle(Request::NewSession(NewSessionRequest {
            session_name: session.clone(),
            detached: true,
            size: Some(TerminalSize { cols: 80, rows: 24 }),
            environment: None,
        }))
        .await;
    assert!(matches!(response, Response::NewSession(_)));
    session
}

async fn create_window(handler: &RequestHandler, session: &SessionName) -> WindowTarget {
    let response = handler
        .handle(Request::NewWindow(NewWindowRequest {
            target: session.clone(),
            name: None,
            detached: true,
            start_directory: None,
            environment: None,
            command: None,
            target_window_index: None,
            insert_at_target: false,
        }))
        .await;
    let Response::NewWindow(response) = response else {
        panic!("expected new-window response");
    };
    response.target
}

async fn display_message(handler: &RequestHandler, target: Target, message: &str) -> String {
    let response = handler
        .handle(Request::DisplayMessage(DisplayMessageRequest {
            target: Some(target),
            print: true,
            message: Some(message.to_owned()),
        }))
        .await;
    let Response::DisplayMessage(response) = response else {
        panic!("expected display-message response");
    };
    let output = response
        .command_output()
        .expect("display-message -p returns output");
    String::from_utf8(output.stdout().to_vec())
        .expect("display-message stdout is utf-8")
        .trim_end()
        .to_owned()
}

async fn set_option(
    handler: &RequestHandler,
    scope: ScopeSelector,
    option: OptionName,
    value: &str,
) {
    let response = handler
        .handle(Request::SetOption(SetOptionRequest {
            scope,
            option,
            value: value.to_owned(),
            mode: SetOptionMode::Replace,
        }))
        .await;
    assert!(matches!(response, Response::SetOption(_)));
}

async fn recv_lifecycle(
    receiver: &mut broadcast::Receiver<QueuedLifecycleEvent>,
) -> QueuedLifecycleEvent {
    timeout(Duration::from_millis(500), receiver.recv())
        .await
        .expect("lifecycle event should arrive")
        .expect("lifecycle channel should stay open")
}

async fn recv_attach_control(
    receiver: &mut mpsc::UnboundedReceiver<AttachControl>,
) -> AttachControl {
    timeout(Duration::from_millis(500), receiver.recv())
        .await
        .expect("attach control should arrive")
        .expect("attach control channel should stay open")
}

async fn recv_non_switch_control(
    receiver: &mut mpsc::UnboundedReceiver<AttachControl>,
) -> AttachControl {
    loop {
        match recv_attach_control(receiver).await {
            AttachControl::Switch(_) => {}
            other => return other,
        }
    }
}

async fn assert_no_non_switch_control(receiver: &mut mpsc::UnboundedReceiver<AttachControl>) {
    let deadline = tokio::time::Instant::now() + Duration::from_millis(50);
    loop {
        let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
        if remaining.is_zero() {
            return;
        }
        match timeout(remaining, receiver.recv()).await {
            Err(_) | Ok(None) => return,
            Ok(Some(AttachControl::Switch(_))) => {}
            Ok(Some(other)) => panic!("unexpected attach control: {other:?}"),
        }
    }
}

fn drain_attach_controls(receiver: &mut mpsc::UnboundedReceiver<AttachControl>) {
    while receiver.try_recv().is_ok() {}
}

#[tokio::test]
async fn pane_alert_event_sets_bell_and_activity_flags_and_emits_alert_hooks() {
    let handler = RequestHandler::new();
    let session = create_session(&handler, "alerts").await;
    let window = create_window(&handler, &session).await;
    set_option(
        &handler,
        ScopeSelector::Window(window.clone()),
        OptionName::MonitorActivity,
        "on",
    )
    .await;

    let pane_id = {
        let state = handler.state.lock().await;
        state
            .sessions
            .session(&session)
            .and_then(|session| session.window_at(window.window_index()))
            .and_then(|window| window.pane(0))
            .expect("window pane exists")
            .id()
    };
    let mut lifecycle = handler.subscribe_lifecycle_events();

    handler.pane_alert_callback()(crate::pane_io::PaneAlertEvent {
        session_name: session.clone(),
        pane_id,
        bell_count: 1,
        generation: None,
    });

    let first = recv_lifecycle(&mut lifecycle).await;
    let second = recv_lifecycle(&mut lifecycle).await;
    let hook_names = [first.hook_name, second.hook_name];
    assert!(hook_names.contains(&HookName::AlertBell));
    assert!(hook_names.contains(&HookName::AlertActivity));

    let state = handler.state.lock().await;
    let session = state.sessions.session(&session).expect("session exists");
    let flags = session.winlink_alert_flags(window.window_index());
    assert!(flags.contains(WINLINK_BELL));
    assert!(flags.contains(WINLINK_ACTIVITY));
}

#[tokio::test]
async fn pane_alert_callback_can_be_invoked_from_reader_thread() {
    let handler = RequestHandler::new();
    let session = create_session(&handler, "alerts-reader-thread").await;
    set_option(
        &handler,
        ScopeSelector::Window(WindowTarget::with_window(session.clone(), 0)),
        OptionName::MonitorActivity,
        "on",
    )
    .await;
    set_option(
        &handler,
        ScopeSelector::Session(session.clone()),
        OptionName::ActivityAction,
        "any",
    )
    .await;
    let pane_id = {
        let state = handler.state.lock().await;
        state
            .sessions
            .session(&session)
            .and_then(|session| session.window_at(0))
            .and_then(|window| window.pane(0).map(|pane| pane.id()))
            .expect("window pane exists")
    };
    let mut lifecycle = handler.subscribe_lifecycle_events();
    let callback = handler.pane_alert_callback();

    std::thread::spawn(move || {
        callback(crate::pane_io::PaneAlertEvent {
            session_name: session,
            pane_id,
            bell_count: 0,
            generation: None,
        });
    })
    .join()
    .expect("reader-thread alert callback should not panic outside the Tokio runtime");

    let event = recv_lifecycle(&mut lifecycle).await;
    assert_eq!(event.hook_name, HookName::AlertActivity);
}

#[tokio::test]
async fn pane_exit_callback_can_be_invoked_from_reader_thread() {
    let handler = RequestHandler::new();
    let session = create_session(&handler, "exit-reader-thread").await;
    let pane_id = {
        let state = handler.state.lock().await;
        state
            .sessions
            .session(&session)
            .and_then(|session| session.window_at(0))
            .and_then(|window| window.pane(0).map(|pane| pane.id()))
            .expect("window pane exists")
    };
    let callback = handler.pane_exit_callback();

    std::thread::spawn(move || {
        callback(crate::pane_io::PaneExitEvent {
            session_name: session,
            pane_id,
            generation: None,
        });
    })
    .join()
    .expect("reader-thread exit callback should not panic outside the Tokio runtime");
}

#[tokio::test]
async fn pane_alert_event_updates_automatic_window_name_without_disabling_auto_rename() {
    let handler = RequestHandler::new();
    let session = create_session(&handler, "alerts-name").await;
    set_option(
        &handler,
        ScopeSelector::Window(WindowTarget::with_window(session.clone(), 0)),
        OptionName::AutomaticRenameFormat,
        "updated-name",
    )
    .await;
    let pane_id = {
        let state = handler.state.lock().await;
        state
            .sessions
            .session(&session)
            .and_then(|session| session.window_at(0))
            .and_then(|window| window.pane(0).map(|pane| pane.id()))
            .expect("window pane exists")
    };

    handler
        .handle_pane_alert_event(crate::pane_io::PaneAlertEvent {
            session_name: session.clone(),
            pane_id,
            bell_count: 0,
            generation: None,
        })
        .await;

    let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
    loop {
        {
            let state = handler.state.lock().await;
            let window = state
                .sessions
                .session(&session)
                .and_then(|session| session.window_at(0))
                .expect("window exists");
            if window.name() == Some("updated-name") && state.tracks_auto_named_window(&session, 0)
            {
                break;
            }
        }

        assert!(
            tokio::time::Instant::now() < deadline,
            "automatic window name was not updated before timeout"
        );
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
}

#[tokio::test]
async fn pane_alert_event_updates_grouped_session_window_names() {
    let handler = RequestHandler::new();
    let alpha = create_session(&handler, "alerts-group-alpha").await;
    let beta = session_name("alerts-group-beta");
    let response = handler
        .handle(Request::NewSessionExt(NewSessionExtRequest {
            session_name: Some(beta.clone()),
            working_directory: None,
            detached: true,
            size: Some(TerminalSize { cols: 80, rows: 24 }),
            environment: None,
            group_target: Some(alpha.clone()),
            attach_if_exists: false,
            detach_other_clients: false,
            kill_other_clients: false,
            flags: None,
            window_name: None,
            print_session_info: false,
            print_format: None,
            command: None,
        }))
        .await;
    assert!(matches!(response, Response::NewSession(_)));
    set_option(
        &handler,
        ScopeSelector::Window(WindowTarget::with_window(alpha.clone(), 0)),
        OptionName::AutomaticRenameFormat,
        "updated-name",
    )
    .await;

    let pane_id = {
        let state = handler.state.lock().await;
        state
            .sessions
            .session(&alpha)
            .and_then(|session| session.window_at(0))
            .and_then(|window| window.pane(0).map(|pane| pane.id()))
            .expect("window pane exists")
    };

    handler
        .handle_pane_alert_event(crate::pane_io::PaneAlertEvent {
            session_name: alpha.clone(),
            pane_id,
            bell_count: 0,
            generation: None,
        })
        .await;

    let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
    loop {
        {
            let state = handler.state.lock().await;
            let alpha_name = state
                .sessions
                .session(&alpha)
                .and_then(|session| session.window_at(0))
                .and_then(|window| window.name())
                .map(str::to_owned);
            let beta_name = state
                .sessions
                .session(&beta)
                .and_then(|session| session.window_at(0))
                .and_then(|window| window.name())
                .map(str::to_owned);
            if alpha_name.as_deref() == Some("updated-name")
                && beta_name.as_deref() == Some("updated-name")
            {
                break;
            }
        }

        assert!(
            tokio::time::Instant::now() < deadline,
            "grouped sessions did not share the automatic window name before timeout"
        );
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
}

#[cfg(unix)]
#[tokio::test]
async fn shell_input_updates_window_name_and_foreground_process_formats() {
    let handler = RequestHandler::new();
    let session = create_session(&handler, "alerts-foreground").await;
    let target = PaneTarget::with_window(session.clone(), 0, 0);
    let expected_path = std::fs::canonicalize("/tmp")
        .unwrap_or_else(|_| std::path::PathBuf::from("/tmp"))
        .to_string_lossy()
        .into_owned();
    let expected = format!("sleep|{expected_path}|sleep");

    let response = handler
        .handle(Request::SendKeys(SendKeysRequest {
            target: target.clone(),
            keys: vec!["cd /tmp && sleep 30".to_owned(), "Enter".to_owned()],
        }))
        .await;
    assert!(matches!(response, Response::SendKeys(_)));

    let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
    loop {
        let rendered = display_message(
            &handler,
            Target::Pane(target.clone()),
            "#{window_name}|#{pane_current_path}|#{pane_current_command}",
        )
        .await;
        if rendered == expected {
            break;
        }

        assert!(
            tokio::time::Instant::now() < deadline,
            "foreground formats did not update before timeout; last={rendered:?}"
        );
        tokio::time::sleep(Duration::from_millis(20)).await;
    }
}

#[tokio::test]
async fn visual_bell_modes_dispatch_overlay_write_and_action_gating() {
    let handler = RequestHandler::new();
    let session = create_session(&handler, "visual").await;
    let other_window = create_window(&handler, &session).await;
    let (control_tx, mut control_rx) = mpsc::unbounded_channel();
    let _attach_id = handler
        .register_attach(42, session.clone(), control_tx)
        .await;
    drain_attach_controls(&mut control_rx);
    let current_window = WindowTarget::new(session.clone());

    set_option(
        &handler,
        ScopeSelector::Session(session.clone()),
        OptionName::VisualBell,
        "off",
    )
    .await;
    handler
        .alerts_queue_window(current_window.clone(), rmux_core::WINDOW_BELL)
        .await;
    match recv_non_switch_control(&mut control_rx).await {
        AttachControl::Write(bytes) => assert_eq!(bytes, vec![0x07]),
        other => panic!("expected bell write, got {other:?}"),
    }
    assert_no_non_switch_control(&mut control_rx).await;

    set_option(
        &handler,
        ScopeSelector::Session(session.clone()),
        OptionName::VisualBell,
        "on",
    )
    .await;
    handler
        .alerts_queue_window(current_window.clone(), rmux_core::WINDOW_BELL)
        .await;
    match recv_non_switch_control(&mut control_rx).await {
        AttachControl::Overlay(frame) => {
            let rendered = String::from_utf8_lossy(&frame.frame);
            assert!(rendered.contains("Bell in current window"));
        }
        other => panic!("expected overlay, got {other:?}"),
    }
    assert_no_non_switch_control(&mut control_rx).await;

    set_option(
        &handler,
        ScopeSelector::Session(session.clone()),
        OptionName::VisualBell,
        "both",
    )
    .await;
    handler
        .alerts_queue_window(current_window, rmux_core::WINDOW_BELL)
        .await;
    let first = recv_non_switch_control(&mut control_rx).await;
    let second = recv_non_switch_control(&mut control_rx).await;
    assert!(matches!(first, AttachControl::Write(_)) || matches!(second, AttachControl::Write(_)));
    assert!(
        matches!(first, AttachControl::Overlay(_)) || matches!(second, AttachControl::Overlay(_))
    );

    set_option(
        &handler,
        ScopeSelector::Session(session.clone()),
        OptionName::BellAction,
        "other",
    )
    .await;
    handler
        .alerts_queue_window(WindowTarget::new(session.clone()), rmux_core::WINDOW_BELL)
        .await;
    assert_no_non_switch_control(&mut control_rx).await;

    handler
        .alerts_queue_window(other_window.clone(), rmux_core::WINDOW_BELL)
        .await;
    let delivered = recv_non_switch_control(&mut control_rx).await;
    assert!(matches!(
        delivered,
        AttachControl::Write(_) | AttachControl::Overlay(_)
    ));
    let state = handler.state.lock().await;
    let flags = state
        .sessions
        .session(&session)
        .expect("session exists")
        .winlink_alert_flags(other_window.window_index());
    assert!(flags.contains(WINLINK_BELL));
}

#[tokio::test]
async fn silence_monitor_sets_flags_after_idle() {
    let handler = RequestHandler::new();
    let session = create_session(&handler, "silence").await;
    let window = create_window(&handler, &session).await;
    set_option(
        &handler,
        ScopeSelector::Window(window.clone()),
        OptionName::MonitorSilence,
        "1",
    )
    .await;

    let mut lifecycle = handler.subscribe_lifecycle_events();
    let event = timeout(Duration::from_secs(4), lifecycle.recv())
        .await
        .expect("silence alert should fire")
        .expect("lifecycle channel should stay open");
    assert_eq!(event.hook_name, HookName::AlertSilence);

    let state = handler.state.lock().await;
    let flags = state
        .sessions
        .session(&session)
        .expect("session exists")
        .winlink_alert_flags(window.window_index());
    assert!(flags.contains(WINLINK_SILENCE));
}

#[tokio::test]
async fn show_messages_formats_log_and_terminal_info_and_prunes_to_limit() {
    let handler = RequestHandler::new();
    let session = create_session(&handler, "messages").await;
    let (control_tx, _control_rx) = mpsc::unbounded_channel();
    let _attach_id = handler
        .register_attach(77, session.clone(), control_tx)
        .await;

    {
        let mut state = handler.state.lock().await;
        state.add_message("one");
        state.add_message("two");
    }
    set_option(
        &handler,
        ScopeSelector::Global,
        OptionName::MessageLimit,
        "1",
    )
    .await;

    let response = handler
        .handle(Request::ShowMessages(ShowMessagesRequest {
            jobs: false,
            terminals: false,
            target_client: None,
        }))
        .await;
    let Response::ShowMessages(response) = response else {
        panic!("expected show-messages response");
    };
    let rendered = String::from_utf8_lossy(response.output.stdout()).into_owned();
    assert!(rendered.contains(": two"));
    assert!(!rendered.contains(": one"));

    let response = handler
        .handle(Request::ShowMessages(ShowMessagesRequest {
            jobs: false,
            terminals: true,
            target_client: Some("77".to_owned()),
        }))
        .await;
    let Response::ShowMessages(response) = response else {
        panic!("expected show-messages response");
    };
    let rendered = String::from_utf8_lossy(response.output.stdout()).into_owned();
    assert!(rendered.contains("Terminal 0:"));
    assert!(rendered.contains("client 77"));
    assert!(!rendered.contains(": two"));

    let response = handler
        .handle(Request::ShowMessages(ShowMessagesRequest {
            jobs: true,
            terminals: false,
            target_client: Some("77".to_owned()),
        }))
        .await;
    let Response::ShowMessages(response) = response else {
        panic!("expected show-messages response");
    };
    assert!(response.output.stdout().is_empty());

    set_option(
        &handler,
        ScopeSelector::Global,
        OptionName::MessageLimit,
        "0",
    )
    .await;
    let state = handler.state.lock().await;
    assert!(state.message_log.is_empty());
}

#[tokio::test]
async fn format_variables_focus_clearing_and_alert_navigation_follow_winlink_flags() {
    let handler = RequestHandler::new();
    let session = create_session(&handler, "formats").await;
    let window_one = create_window(&handler, &session).await;
    let window_two = create_window(&handler, &session).await;

    {
        let mut state = handler.state.lock().await;
        let session = state
            .sessions
            .session_mut(&session)
            .expect("session exists");
        let combined = WINLINK_ACTIVITY.union(WINLINK_BELL).union(WINLINK_SILENCE);
        assert!(session.add_winlink_alert_flags(window_one.window_index(), combined));
        assert!(session.add_winlink_alert_flags(window_two.window_index(), WINLINK_BELL));
        assert!(session.add_winlink_alert_flags(0, WINLINK_ACTIVITY));
    }

    let rendered = {
        let state = handler.state.lock().await;
        let session_context =
            format_context_for_target(&state, &Target::Session(session.clone()), 0).unwrap();
        let window_context =
            format_context_for_target(&state, &Target::Window(window_one.clone()), 0).unwrap();
        (
            render_runtime_template(
                "#{session_alerts}|#{session_activity_flag}|#{session_bell_flag}|#{session_silence_flag}",
                &session_context,
                false,
            ),
            render_runtime_template(
                "#{window_activity_flag}|#{window_bell_flag}|#{window_silence_flag}",
                &window_context,
                false,
            ),
        )
    };
    assert_eq!(rendered.0, "0#,1#!~,2!|1|1|1");
    assert_eq!(rendered.1, "1|1|1");

    let next = handler
        .handle(Request::NextWindow(NextWindowRequest {
            target: session.clone(),
            alerts_only: true,
        }))
        .await;
    assert_eq!(
        next,
        Response::NextWindow(rmux_proto::NextWindowResponse {
            target: window_one.clone(),
        })
    );
    {
        let state = handler.state.lock().await;
        let session = state.sessions.session(&session).expect("session exists");
        assert!(session
            .winlink_alert_flags(window_one.window_index())
            .is_empty());
    }

    let previous = handler
        .handle(Request::PreviousWindow(PreviousWindowRequest {
            target: session.clone(),
            alerts_only: true,
        }))
        .await;
    assert_eq!(
        previous,
        Response::PreviousWindow(rmux_proto::PreviousWindowResponse {
            target: WindowTarget::new(session.clone()),
        })
    );

    let wrapped_previous = handler
        .handle(Request::PreviousWindow(PreviousWindowRequest {
            target: session.clone(),
            alerts_only: true,
        }))
        .await;
    assert_eq!(
        wrapped_previous,
        Response::PreviousWindow(rmux_proto::PreviousWindowResponse { target: window_two })
    );
}

#[tokio::test]
async fn activity_deduplication_skips_second_alert_on_same_winlink() {
    let handler = RequestHandler::new();
    let session = create_session(&handler, "dedup").await;
    let window = create_window(&handler, &session).await;
    set_option(
        &handler,
        ScopeSelector::Window(window.clone()),
        OptionName::MonitorActivity,
        "on",
    )
    .await;

    let mut lifecycle = handler.subscribe_lifecycle_events();

    // First activity fires the hook.
    handler
        .alerts_queue_window(window.clone(), rmux_core::WINDOW_ACTIVITY)
        .await;
    let event = recv_lifecycle(&mut lifecycle).await;
    assert_eq!(event.hook_name, HookName::AlertActivity);

    // Second activity on the same winlink is suppressed (flag already set).
    handler
        .alerts_queue_window(window.clone(), rmux_core::WINDOW_ACTIVITY)
        .await;
    let deadline = tokio::time::Instant::now() + Duration::from_millis(100);
    loop {
        let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
        if remaining.is_zero() {
            break;
        }
        match timeout(remaining, lifecycle.recv()).await {
            Err(_) | Ok(Err(_)) => break,
            Ok(Ok(event)) => {
                assert_ne!(
                    event.hook_name,
                    HookName::AlertActivity,
                    "duplicate activity alert should not fire"
                );
            }
        }
    }

    // Bell on the same winlink still fires (bells are never deduplicated).
    handler
        .alerts_queue_window(window.clone(), rmux_core::WINDOW_BELL)
        .await;
    let bell_event = recv_lifecycle(&mut lifecycle).await;
    assert_eq!(bell_event.hook_name, HookName::AlertBell);
}

#[tokio::test]
async fn action_none_blocks_all_delivery() {
    let handler = RequestHandler::new();
    let session = create_session(&handler, "none-action").await;
    let (control_tx, mut control_rx) = mpsc::unbounded_channel();
    let _attach_id = handler
        .register_attach(55, session.clone(), control_tx)
        .await;
    drain_attach_controls(&mut control_rx);

    set_option(
        &handler,
        ScopeSelector::Session(session.clone()),
        OptionName::BellAction,
        "none",
    )
    .await;

    handler
        .alerts_queue_window(WindowTarget::new(session.clone()), rmux_core::WINDOW_BELL)
        .await;
    assert_no_non_switch_control(&mut control_rx).await;

    // Winlink flags are not set on the current window when clients are attached
    // (tmux clears flags on the current window on every client activity check).
    let state = handler.state.lock().await;
    let session_obj = state.sessions.session(&session).expect("session exists");
    let flags = session_obj.winlink_alert_flags(0);
    assert!(
        !flags.contains(WINLINK_BELL),
        "bell flag should not be set on the current window with attached clients"
    );
}

#[tokio::test]
async fn action_none_on_non_current_window_still_sets_winlink_flags() {
    let handler = RequestHandler::new();
    let session = create_session(&handler, "none-noncurr").await;
    let other_window = create_window(&handler, &session).await;
    let (control_tx, mut control_rx) = mpsc::unbounded_channel();
    let _attach_id = handler
        .register_attach(56, session.clone(), control_tx)
        .await;
    drain_attach_controls(&mut control_rx);

    set_option(
        &handler,
        ScopeSelector::Session(session.clone()),
        OptionName::BellAction,
        "none",
    )
    .await;

    let mut lifecycle = handler.subscribe_lifecycle_events();

    handler
        .alerts_queue_window(other_window.clone(), rmux_core::WINDOW_BELL)
        .await;
    // action=none blocks delivery (no bell, no overlay, no hook).
    assert_no_non_switch_control(&mut control_rx).await;

    // No lifecycle/hook event should fire with action=none.
    let deadline = tokio::time::Instant::now() + Duration::from_millis(100);
    loop {
        let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
        if remaining.is_zero() {
            break;
        }
        match timeout(remaining, lifecycle.recv()).await {
            Err(_) | Ok(Err(_)) => break,
            Ok(Ok(event)) => {
                assert_ne!(
                    event.hook_name,
                    HookName::AlertBell,
                    "alert-bell hook should not fire with action=none"
                );
            }
        }
    }

    // But winlink flags are still set — action only gates delivery, not flag persistence.
    // This matches tmux: the status line shows the alert indicator even with action=none.
    let state = handler.state.lock().await;
    let session_obj = state.sessions.session(&session).expect("session exists");
    let flags = session_obj.winlink_alert_flags(other_window.window_index());
    assert!(
        flags.contains(WINLINK_BELL),
        "bell flag should be set on a non-current window even with action=none"
    );
}

#[tokio::test]
async fn empty_session_alerts_when_no_windows_are_alerted() {
    let handler = RequestHandler::new();
    let session = create_session(&handler, "empty-alerts").await;
    let _window = create_window(&handler, &session).await;

    let rendered = {
        let state = handler.state.lock().await;
        let context =
            format_context_for_target(&state, &Target::Session(session.clone()), 0).unwrap();
        render_runtime_template("#{session_alerts}", &context, false)
    };
    assert_eq!(rendered, "");
}

#[tokio::test]
async fn next_window_alert_errors_when_no_alerted_windows_exist() {
    let handler = RequestHandler::new();
    let session = create_session(&handler, "no-alert-nav").await;
    let _window = create_window(&handler, &session).await;

    let response = handler
        .handle(Request::NextWindow(NextWindowRequest {
            target: session.clone(),
            alerts_only: true,
        }))
        .await;
    assert!(matches!(response, Response::Error(_)));

    let response = handler
        .handle(Request::PreviousWindow(PreviousWindowRequest {
            target: session.clone(),
            alerts_only: true,
        }))
        .await;
    assert!(matches!(response, Response::Error(_)));
}

#[tokio::test]
async fn alert_message_logged_even_without_attached_clients() {
    let handler = RequestHandler::new();
    let session = create_session(&handler, "detached-log").await;
    let window = create_window(&handler, &session).await;

    set_option(
        &handler,
        ScopeSelector::Session(session.clone()),
        OptionName::VisualBell,
        "on",
    )
    .await;

    handler
        .alerts_queue_window(window.clone(), rmux_core::WINDOW_BELL)
        .await;

    // Give async tasks time to complete.
    tokio::time::sleep(Duration::from_millis(50)).await;

    let state = handler.state.lock().await;
    assert!(
        !state.message_log.is_empty(),
        "alert message should be logged even with no attached clients"
    );
    let last_message = &state.message_log.back().unwrap().msg;
    assert!(
        last_message.contains("Bell"),
        "logged message should mention the alert kind"
    );
}

#[tokio::test]
async fn kill_window_clears_alert_flags_for_removed_window() {
    let handler = RequestHandler::new();
    let session = create_session(&handler, "kill-alert").await;
    let window = create_window(&handler, &session).await;

    {
        let mut state = handler.state.lock().await;
        let session_obj = state
            .sessions
            .session_mut(&session)
            .expect("session exists");
        session_obj.add_winlink_alert_flags(window.window_index(), WINLINK_BELL);
    }

    let response = handler
        .handle(Request::KillWindow(KillWindowRequest {
            target: window.clone(),
            kill_all_others: false,
        }))
        .await;
    assert!(matches!(response, Response::KillWindow(_)));

    let state = handler.state.lock().await;
    let session_obj = state.sessions.session(&session).expect("session exists");
    // The killed window's alert flags should not exist.
    let flags = session_obj.winlink_alert_flags(window.window_index());
    assert!(
        flags.is_empty(),
        "alert flags should be cleared after killing window"
    );
    // Session-level alert flags should not include the killed window's bell.
    let session_flags = session_obj.session_alert_flags();
    assert!(
        !session_flags.contains(WINLINK_BELL),
        "session-level bell flag should be cleared after killing the only alerted window"
    );
}

#[tokio::test]
async fn silence_deduplication_skips_second_silence_on_same_winlink() {
    let handler = RequestHandler::new();
    let session = create_session(&handler, "silence-dedup").await;
    let window = create_window(&handler, &session).await;
    set_option(
        &handler,
        ScopeSelector::Window(window.clone()),
        OptionName::MonitorSilence,
        "1",
    )
    .await;

    let mut lifecycle = handler.subscribe_lifecycle_events();

    // First silence fires the hook.
    handler
        .alerts_queue_window(window.clone(), rmux_core::WINDOW_SILENCE)
        .await;
    let event = recv_lifecycle(&mut lifecycle).await;
    assert_eq!(event.hook_name, HookName::AlertSilence);

    // Second silence on the same winlink is suppressed (flag already set).
    handler
        .alerts_queue_window(window.clone(), rmux_core::WINDOW_SILENCE)
        .await;
    let deadline = tokio::time::Instant::now() + Duration::from_millis(100);
    loop {
        let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
        if remaining.is_zero() {
            break;
        }
        match timeout(remaining, lifecycle.recv()).await {
            Err(_) | Ok(Err(_)) => break,
            Ok(Ok(event)) => {
                assert_ne!(
                    event.hook_name,
                    HookName::AlertSilence,
                    "duplicate silence alert should not fire"
                );
            }
        }
    }
}

#[tokio::test]
async fn show_messages_invalid_target_client_returns_error() {
    let handler = RequestHandler::new();
    let _session = create_session(&handler, "bad-target").await;

    let response = handler
        .handle(Request::ShowMessages(ShowMessagesRequest {
            jobs: false,
            terminals: true,
            target_client: Some("not-a-number".to_owned()),
        }))
        .await;
    assert!(
        matches!(response, Response::Error(_)),
        "non-numeric target client should produce an error"
    );
}

#[tokio::test]
async fn select_window_clears_alert_flags_on_newly_selected_window() {
    let handler = RequestHandler::new();
    let session = create_session(&handler, "select-clear").await;
    let window_one = create_window(&handler, &session).await;

    {
        let mut state = handler.state.lock().await;
        let session_obj = state
            .sessions
            .session_mut(&session)
            .expect("session exists");
        session_obj.add_winlink_alert_flags(
            window_one.window_index(),
            WINLINK_BELL.union(WINLINK_ACTIVITY),
        );
    }

    // Selecting the alerted window should clear its flags.
    let response = handler
        .handle(Request::NextWindow(NextWindowRequest {
            target: session.clone(),
            alerts_only: false,
        }))
        .await;
    let Response::NextWindow(next) = &response else {
        panic!("expected next-window response, got {response:?}");
    };
    assert_eq!(next.target.window_index(), window_one.window_index());

    let state = handler.state.lock().await;
    let session_obj = state.sessions.session(&session).expect("session exists");
    assert_eq!(session_obj.active_window_index(), window_one.window_index());
    let flags = session_obj.winlink_alert_flags(window_one.window_index());
    assert!(
        flags.is_empty(),
        "alert flags should be cleared when selecting a window via next-window"
    );
}