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
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::time::Duration;

use rmux_core::LifecycleEvent;
use rmux_proto::{
    ControlMode, PaneKillRequest, PaneResizeRequest, PaneTargetRef, Request, ResizePaneAdjustment,
    Response, SessionName, TerminalSize,
};
use tokio::sync::{mpsc, oneshot};

use super::RequestHandler;
use crate::control::{ControlModeUpgrade, ControlServerEvent, CONTROL_SERVER_EVENT_CAPACITY};

#[path = "handler_layout_notification_tests/linked_transfer_aliases.rs"]
mod linked_transfer_aliases;

const CONTROL_NOTIFICATION_SETTLE: Duration = Duration::from_millis(100);
const CONTROL_NOTIFICATION_POLL: Duration = Duration::from_millis(10);

struct LayoutCommandCase {
    label: &'static str,
    setup: &'static [&'static str],
    warmup: Option<&'static str>,
    command: &'static str,
    expected: usize,
}

#[tokio::test]
async fn layout_command_sites_keep_one_canonical_notification_per_mutation_product_divergence() {
    // tmux 3.7b oracle, measured 2026-07-26 in control mode:
    // select-layout (same and different), next-layout and previous-layout
    // publish twice; move-pane publishes three times; resize-pane, swap-pane
    // and kill-pane publish once. RMUX intentionally has one canonical
    // WindowLayoutChanged producer for each committed mutation.
    let cases = [
        LayoutCommandCase {
            label: "select-layout-identical",
            setup: &["split-window -d -h -t {session}"],
            warmup: Some("select-layout -t {session} even-horizontal"),
            command: "select-layout -t {session} even-horizontal",
            expected: 1,
        },
        LayoutCommandCase {
            label: "select-layout-different",
            setup: &["split-window -d -h -t {session}"],
            warmup: None,
            command: "select-layout -t {session} even-vertical",
            expected: 1,
        },
        LayoutCommandCase {
            label: "next-layout",
            setup: &["split-window -d -h -t {session}"],
            warmup: None,
            command: "next-layout -t {session}",
            expected: 1,
        },
        LayoutCommandCase {
            label: "previous-layout",
            setup: &["split-window -d -h -t {session}"],
            warmup: None,
            command: "previous-layout -t {session}",
            expected: 1,
        },
        LayoutCommandCase {
            label: "resize-pane",
            setup: &["split-window -d -h -t {session}"],
            warmup: None,
            command: "resize-pane -t {session}:.0 -R 5",
            expected: 1,
        },
        LayoutCommandCase {
            label: "swap-pane",
            setup: &["split-window -d -h -t {session}"],
            warmup: None,
            command: "swap-pane -s {session}:.0 -t {session}:.1",
            expected: 1,
        },
        LayoutCommandCase {
            label: "move-pane",
            setup: &[
                "split-window -d -h -t {session}",
                "split-window -d -v -t {session}:.0",
            ],
            warmup: None,
            command: "move-pane -s {session}:.2 -t {session}:.1 -h",
            expected: 1,
        },
        LayoutCommandCase {
            label: "kill-pane",
            setup: &["split-window -d -h -t {session}"],
            warmup: None,
            command: "kill-pane -t {session}:.1",
            expected: 1,
        },
    ];

    let mut actual = Vec::with_capacity(cases.len());
    let mut expected = Vec::with_capacity(cases.len());
    for case in cases {
        let session =
            SessionName::new(format!("layout-notify-{}", case.label)).expect("test session name");
        let handler = RequestHandler::new();
        create_session(&handler, &session).await;
        for command in case.setup {
            run_detached_command(&handler, &render_command(command, &session)).await;
        }
        if let Some(command) = case.warmup {
            run_detached_command(&handler, &render_command(command, &session)).await;
        }
        let (control_pid, mut notifications) = register_control_client(&handler, &session).await;
        let _ = settle_control_notifications(&mut notifications).await;

        run_control_command(
            &handler,
            control_pid,
            &render_command(case.command, &session),
        )
        .await;
        let count = layout_change_count(&mut notifications).await;
        actual.push((case.label, count));
        expected.push((case.label, case.expected));
    }

    assert_eq!(actual, expected);
}

#[tokio::test]
async fn custom_layout_resize_has_one_layout_notification_not_two() {
    let handler = RequestHandler::new();
    let session = SessionName::new("layout-notify-custom-resize").expect("test session name");
    create_session(&handler, &session).await;
    run_detached_command(&handler, &format!("split-window -d -h -t {session}")).await;
    run_detached_command(&handler, &format!("resize-window -t {session} -x 60 -y 20")).await;
    let small_layout = {
        let state = handler.state.lock().await;
        state
            .sessions
            .session(&session)
            .expect("test session")
            .window()
            .layout_dump()
    };
    run_detached_command(&handler, &format!("resize-window -t {session} -x 80 -y 24")).await;

    let (control_pid, mut notifications) = register_control_client(&handler, &session).await;
    let _ = settle_control_notifications(&mut notifications).await;
    let mut lifecycle_events = handler.subscribe_lifecycle_events();
    run_control_command(
        &handler,
        control_pid,
        &format!("select-layout -t {session} \"{small_layout}\""),
    )
    .await;

    assert_eq!(layout_change_count(&mut notifications).await, 1);
    let events = std::iter::from_fn(|| lifecycle_events.try_recv().ok())
        .map(|event| event.event)
        .collect::<Vec<_>>();
    assert_eq!(
        events
            .iter()
            .filter(|event| matches!(event, LifecycleEvent::WindowLayoutChanged { .. }))
            .count(),
        1
    );
    assert_eq!(
        events
            .iter()
            .filter(|event| matches!(event, LifecycleEvent::WindowResized { .. }))
            .count(),
        1,
        "deduplicating the layout producer must keep the resize hook"
    );
}

#[tokio::test]
async fn join_and_move_reflow_minimum_target_and_publish_resize_product_divergence() {
    // tmux 3.7b rejects every width-one case below with
    // "size or position no space for a new pane". RMUX deliberately expands
    // the target to the viable three-column minimum. Both engines accept the
    // width-three neighborhood, where RMUX must not publish a spurious resize.
    for operation in ["join-pane", "move-pane"] {
        for route in ["same", "cross"] {
            for (initial_width, expected_resize_events) in [(1, 1), (3, 0)] {
                let label = format!("{operation}-{route}-{initial_width}");
                let target = SessionName::new(format!("transfer-resize-target-{label}"))
                    .expect("target session");
                let source = SessionName::new(format!("transfer-resize-source-{label}"))
                    .expect("source session");
                let handler = RequestHandler::new();
                let lifecycle_dispatch = handler
                    .take_lifecycle_dispatch_receiver()
                    .expect("test owns lifecycle dispatch");
                let (hook_shutdown_tx, hook_shutdown_rx) = oneshot::channel();
                let hook_handler = handler.clone();
                let hook_task = tokio::spawn(async move {
                    hook_handler
                        .consume_lifecycle_hooks(lifecycle_dispatch, hook_shutdown_rx)
                        .await;
                });
                create_session(&handler, &target).await;
                run_detached_command(
                    &handler,
                    &format!("set-window-option -t {target}:0 window-size manual"),
                )
                .await;
                run_detached_command(
                    &handler,
                    &format!("resize-window -t {target}:0 -x {initial_width} -y 1"),
                )
                .await;

                let source_target = if route == "same" {
                    // `sleep` is not a Windows command, so cmd.exe would exit at
                    // once and destroy `:9` before the transfer. The shared
                    // stdin-discard command blocks on the pane's own terminal
                    // instead, which keeps the source window alive on both
                    // platforms.
                    run_detached_command(
                        &handler,
                        &format!(
                            "new-window -d -t {target}:9 {}",
                            crate::test_shell::command_quote(
                                &crate::test_shell::stdin_discard_command()
                            )
                        ),
                    )
                    .await;
                    format!("{target}:9.0")
                } else {
                    create_session(&handler, &source).await;
                    format!("{source}:0.0")
                };
                run_detached_command(&handler, "set-buffer -b transfer-events ''").await;
                run_detached_command(
                    &handler,
                    "set-hook -g window-layout-changed 'set-buffer -a -b transfer-events L'",
                )
                .await;
                run_detached_command(
                    &handler,
                    "set-hook -g window-resized 'set-buffer -a -b transfer-events R'",
                )
                .await;

                let (control_pid, mut notifications) =
                    register_control_client(&handler, &target).await;
                let _ = settle_control_notifications(&mut notifications).await;
                run_detached_command(&handler, "set-buffer -b transfer-events ''").await;
                let mut lifecycle_events = handler.subscribe_lifecycle_events();

                let command = format!("{} -h -d -s {source_target} -t {target}:0.0", operation);
                run_control_command(&handler, control_pid, &command).await;
                let control_lines = settle_control_notifications(&mut notifications).await;
                let expected_hook_events = if expected_resize_events == 0 {
                    "LL"
                } else {
                    "LLR"
                };
                let hook_events =
                    wait_for_buffer_text(&handler, "transfer-events", expected_hook_events).await;
                let mut events = Vec::new();
                while let Ok(Ok(event)) =
                    tokio::time::timeout(CONTROL_NOTIFICATION_POLL, lifecycle_events.recv()).await
                {
                    events.push(event.event);
                }

                let (target_size, target_panes) = {
                    let state = handler.state.lock().await;
                    let window = state
                        .sessions
                        .session(&target)
                        .expect("target session")
                        .window_at(0)
                        .expect("target window");
                    (window.size(), window.pane_count())
                };
                assert_eq!(
                    (target_size, target_panes),
                    (TerminalSize { cols: 3, rows: 1 }, 2),
                    "{label}"
                );
                assert_eq!(
                    control_lines
                        .iter()
                        .filter(|line| line.starts_with("%layout-change "))
                        .count(),
                    1,
                    "{label}: tmux 3.7b sends one control layout for the surviving target window"
                );
                assert_eq!(
                    events
                        .iter()
                        .filter(|event| matches!(event, LifecycleEvent::WindowLayoutChanged { .. }))
                        .count(),
                    2,
                    "{label}"
                );
                assert_eq!(
                    events
                        .iter()
                        .filter(|event| {
                            matches!(
                                event,
                                LifecycleEvent::WindowResized { target: resized }
                                    if resized.session_name() == &target
                                        && resized.window_index() == 0
                            )
                        })
                        .count(),
                    expected_resize_events,
                    "{label}: hooks={hook_events:?}, lifecycle={events:?}"
                );
                assert_eq!(
                    hook_events,
                    Some(expected_hook_events.to_owned()),
                    "{label}: lifecycle hooks must observe the same committed resize"
                );

                let _ = hook_shutdown_tx.send(());
                hook_task.await.expect("lifecycle hook task");
            }
        }
    }
}

#[tokio::test]
async fn layout_no_ops_are_silent_on_cli_and_stable_id_paths() {
    // tmux 3.7b emits no %layout-change for a directional resize in a
    // one-pane window, resize-pane -T, or a pane swapped with itself.
    let handler = RequestHandler::new();
    let session = SessionName::new("layout-notify-no-op").expect("test session name");
    create_session(&handler, &session).await;
    let (control_pid, mut notifications) = register_control_client(&handler, &session).await;
    let _ = settle_control_notifications(&mut notifications).await;

    for command in [
        format!("resize-pane -t {session}:.0 -R 5"),
        format!("resize-pane -t {session}:.0 -T"),
    ] {
        run_control_command(&handler, control_pid, &command).await;
        assert_eq!(
            layout_change_count(&mut notifications).await,
            0,
            "{command}"
        );
    }

    run_detached_command(&handler, &format!("split-window -d -h -t {session}")).await;
    let _ = settle_control_notifications(&mut notifications).await;
    let swap_self = format!("swap-pane -s {session}:.0 -t {session}:.0");
    run_control_command(&handler, control_pid, &swap_self).await;
    assert_eq!(
        layout_change_count(&mut notifications).await,
        0,
        "{swap_self}"
    );

    let pane_id = {
        let state = handler.state.lock().await;
        state
            .sessions
            .session(&session)
            .expect("test session")
            .window()
            .pane(0)
            .expect("test pane")
            .id()
    };
    let response = handler
        .handle(Request::PaneResize(PaneResizeRequest {
            target: PaneTargetRef::by_id(session.clone(), pane_id),
            adjustment: ResizePaneAdjustment::Left { cells: 250 },
        }))
        .await;
    assert!(matches!(response, Response::ResizePane(_)), "{response:?}");
    let _ = settle_control_notifications(&mut notifications).await;

    let response = handler
        .handle(Request::PaneResize(PaneResizeRequest {
            target: PaneTargetRef::by_id(session.clone(), pane_id),
            adjustment: ResizePaneAdjustment::Left { cells: 1 },
        }))
        .await;
    assert!(matches!(response, Response::ResizePane(_)), "{response:?}");
    assert_eq!(layout_change_count(&mut notifications).await, 0);
}

#[tokio::test]
async fn stable_id_resize_and_kill_keep_required_layout_notifications() {
    let handler = RequestHandler::new();
    let session = SessionName::new("layout-notify-stable-id").expect("test session name");
    create_session(&handler, &session).await;
    run_detached_command(&handler, &format!("split-window -d -h -t {session}")).await;
    let (first_pane_id, second_pane_id) = {
        let state = handler.state.lock().await;
        let window = state
            .sessions
            .session(&session)
            .expect("test session")
            .window();
        (
            window.pane(0).expect("first test pane").id(),
            window.pane(1).expect("second test pane").id(),
        )
    };
    let (_control_pid, mut notifications) = register_control_client(&handler, &session).await;
    let _ = settle_control_notifications(&mut notifications).await;

    let response = handler
        .handle(Request::PaneResize(PaneResizeRequest {
            target: PaneTargetRef::by_id(session.clone(), first_pane_id),
            adjustment: ResizePaneAdjustment::Right { cells: 2 },
        }))
        .await;
    assert!(matches!(response, Response::ResizePane(_)), "{response:?}");
    assert_eq!(layout_change_count(&mut notifications).await, 1);

    let response = handler
        .handle(Request::PaneKill(PaneKillRequest {
            target: PaneTargetRef::by_id(session, second_pane_id),
            kill_all_except: false,
        }))
        .await;
    assert!(matches!(response, Response::KillPane(_)), "{response:?}");
    assert_eq!(layout_change_count(&mut notifications).await, 1);
}

async fn create_session(handler: &RequestHandler, session: &SessionName) {
    run_detached_command(handler, &format!("new-session -d -s {session} -x 80 -y 24")).await;
}

async fn run_detached_command(handler: &RequestHandler, command: &str) {
    let parsed = handler
        .parse_control_commands(command)
        .await
        .unwrap_or_else(|error| panic!("failed to parse {command:?}: {error}"));
    handler
        .execute_parsed_commands_for_test(std::process::id(), parsed)
        .await
        .unwrap_or_else(|error| panic!("failed to execute {command:?}: {error}"));
}

async fn run_control_command(handler: &RequestHandler, control_pid: u32, command: &str) {
    let parsed = handler
        .parse_control_commands(command)
        .await
        .unwrap_or_else(|error| panic!("failed to parse {command:?}: {error}"));
    let result = handler.execute_control_commands(control_pid, parsed).await;
    assert!(
        result.error.is_none(),
        "failed to execute {command:?}: {:?}",
        result.error
    );
}

async fn register_control_client(
    handler: &RequestHandler,
    session: &SessionName,
) -> (u32, mpsc::Receiver<ControlServerEvent>) {
    let control_pid = std::process::id();
    let (event_tx, event_rx) = mpsc::channel(CONTROL_SERVER_EVENT_CAPACITY);
    handler
        .register_control_with_closing(
            control_pid,
            ControlModeUpgrade {
                initial_command_count: 0,
                mode: ControlMode::Plain,
                terminal_context: crate::outer_terminal::OuterTerminalContext::default(),
            },
            event_tx,
            Arc::new(AtomicBool::new(false)),
        )
        .await;
    handler
        .set_control_session(control_pid, Some(session.clone()))
        .await
        .expect("set test control session");
    (control_pid, event_rx)
}

async fn layout_change_count(notifications: &mut mpsc::Receiver<ControlServerEvent>) -> usize {
    settle_control_notifications(notifications)
        .await
        .iter()
        .filter(|line| line.starts_with("%layout-change "))
        .count()
}

async fn settle_control_notifications(
    notifications: &mut mpsc::Receiver<ControlServerEvent>,
) -> Vec<String> {
    let mut deadline = tokio::time::Instant::now() + CONTROL_NOTIFICATION_SETTLE;
    let mut lines = Vec::new();
    while tokio::time::Instant::now() < deadline {
        match tokio::time::timeout(CONTROL_NOTIFICATION_POLL, notifications.recv()).await {
            Ok(Some(ControlServerEvent::Notification(line))) => {
                deadline = tokio::time::Instant::now() + CONTROL_NOTIFICATION_SETTLE;
                lines.push(line);
            }
            Ok(Some(_)) | Err(_) => {}
            Ok(None) => break,
        }
    }
    lines
}

async fn wait_for_buffer_text(
    handler: &RequestHandler,
    name: &str,
    expected: &str,
) -> Option<String> {
    let deadline = tokio::time::Instant::now() + Duration::from_millis(500);
    loop {
        let content = {
            let state = handler.state.lock().await;
            state
                .buffers
                .show(Some(name))
                .ok()
                .map(|(_, content)| String::from_utf8_lossy(content).into_owned())
        };
        if content.as_deref() == Some(expected) || tokio::time::Instant::now() >= deadline {
            return content;
        }
        tokio::time::sleep(CONTROL_NOTIFICATION_POLL).await;
    }
}

fn render_command(command: &str, session: &SessionName) -> String {
    command.replace("{session}", session.as_str())
}