bmux_pane_runtime_plugin 0.0.1-alpha.3

Shipped pane-runtime plugin for bmux (declares capabilities + typed services)
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
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
//! Typed handlers for the `pane-runtime-commands` interface.
//!
//! Each handler decodes its `...Args` wire struct, dispatches through
//! the registered `SessionRuntimeManagerHandle`, and serializes the
//! BPDL result type. When the manager handle is not registered
//! (`session_runtime_handle()` returns `None`), the handler reports a
//! `PaneCommandError::Failed { reason }` / `SessionRuntimeCommandError::Failed`.

use bmux_attach_layout_protocol::{
    PaneFocusDirection, PaneLaunchCommand, PaneSelector, PaneSplitDirection,
};
use bmux_pane_runtime_plugin_api::pane_runtime_commands::{
    FloatingPaneAck, PaneAck, PaneCommandError, SessionAck, SessionRuntimeCommandError,
};
use bmux_pane_runtime_plugin_api::pane_runtime_events::{self, AttachViewComponent, PaneEvent};
use bmux_pane_runtime_state::{
    FloatingPaneLayer, FloatingPaneScope, LayoutRect, PaneResizeDirection,
};
use bmux_presentation_state::{
    PresentationEntityRef, PresentationFact, PresentationFactRole, PresentationFactSnapshot,
    global_presentation_fact_host_service,
};
use bmux_session_models::{ClientId, SessionId};
use bmux_sessions_plugin_api::sessions_events::{self, SessionEvent};
use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicU64, Ordering};
use tracing::warn;
use uuid::Uuid;

// ── Wire-format argument structs ─────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SplitPaneArgs {
    pub session_id: Uuid,
    #[serde(default)]
    pub target: Option<Uuid>,
    pub direction: String,
    pub ratio_percent: u8,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LaunchPaneArgs {
    pub session_id: Uuid,
    #[serde(default)]
    pub target: Option<Uuid>,
    pub direction: String,
    pub ratio_percent: u8,
    #[serde(default)]
    pub name: Option<String>,
    pub program: String,
    #[serde(default)]
    pub args: Vec<String>,
    #[serde(default)]
    pub cwd: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FocusPaneArgs {
    pub session_id: Uuid,
    #[serde(default)]
    pub target: Option<Uuid>,
    pub direction: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResizePaneArgs {
    pub session_id: Uuid,
    #[serde(default)]
    pub target: Option<Uuid>,
    pub direction: String,
    #[serde(default = "default_resize_cells")]
    pub cells: u16,
}

const fn default_resize_cells() -> u16 {
    1
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClosePaneArgs {
    pub session_id: Uuid,
    #[serde(default)]
    pub target: Option<Uuid>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionPaneInputArgs {
    pub session_id: Uuid,
    pub pane_id: Uuid,
    pub data: Vec<u8>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionPaneTargetArgs {
    pub session_id: Uuid,
    pub pane_id: Uuid,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnsureExecutionPaneArgs {
    pub session_id: Uuid,
    pub pane_id: Uuid,
    #[serde(default)]
    pub name: Option<String>,
    pub program: String,
    #[serde(default)]
    pub args: Vec<String>,
    #[serde(default)]
    pub cwd: Option<String>,
    #[serde(default)]
    pub env: Vec<bmux_pane_runtime_plugin_api::pane_runtime_commands::EnvironmentEntry>,
    pub rows: u16,
    pub cols: u16,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaneSetPtySizeArgs {
    pub session_id: Uuid,
    pub pane_id: Uuid,
    pub rows: u16,
    pub cols: u16,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaneSignalArgs {
    pub session_id: Uuid,
    pub pane_id: Uuid,
    pub signal: bmux_pane_runtime_plugin_api::pane_runtime_commands::PaneProcessSignal,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RestartPaneArgs {
    pub session_id: Uuid,
    #[serde(default)]
    pub target: Option<Uuid>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ZoomPaneArgs {
    pub session_id: Uuid,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateFloatingPaneArgs {
    pub session_id: Uuid,
    #[serde(default)]
    pub target: Option<Uuid>,
    #[serde(default)]
    pub anchor_pane_id: Option<Uuid>,
    #[serde(default)]
    pub context_id: Option<Uuid>,
    #[serde(default)]
    pub client_id: Option<Uuid>,
    #[serde(default)]
    pub x: Option<u16>,
    #[serde(default)]
    pub y: Option<u16>,
    #[serde(default)]
    pub w: Option<u16>,
    #[serde(default)]
    pub h: Option<u16>,
    #[serde(default)]
    pub z: Option<i32>,
    #[serde(default)]
    pub layer: Option<String>,
    #[serde(default)]
    pub scope: Option<String>,
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub program: Option<String>,
    #[serde(default)]
    pub args: Vec<String>,
    #[serde(default)]
    pub cwd: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FloatingPaneTargetArgs {
    pub session_id: Uuid,
    pub pane_id: Uuid,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MoveFloatingPaneArgs {
    pub session_id: Uuid,
    pub pane_id: Uuid,
    pub x: u16,
    pub y: u16,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResizeFloatingPaneArgs {
    pub session_id: Uuid,
    pub pane_id: Uuid,
    pub w: u16,
    pub h: u16,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SetFloatingPaneZArgs {
    pub session_id: Uuid,
    pub pane_id: Uuid,
    pub z: i32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SetFloatingPaneLayerArgs {
    pub session_id: Uuid,
    pub pane_id: Uuid,
    pub layer: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaneDirectInputArgs {
    pub session_id: Uuid,
    pub pane_id: Uuid,
    #[serde(with = "bmux_plugin_sdk::codec::serde_bytes_vec")]
    pub data: Vec<u8>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SetClientWritePermissionArgs {
    pub session_id: Uuid,
    pub client_id: Uuid,
    pub allowed: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewSessionArgs {
    #[serde(default)]
    pub name: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KillSessionArgs {
    pub session_id: Uuid,
    pub force_local: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RestoreSessionArgs {
    pub session_id: Uuid,
    pub snapshot_payload: Vec<u8>,
}

// ── Handler bodies ───────────────────────────────────────────────

fn failed_command(reason: impl Into<String>) -> PaneCommandError {
    PaneCommandError::Failed {
        reason: reason.into(),
    }
}

fn failed_session(reason: impl Into<String>) -> SessionRuntimeCommandError {
    SessionRuntimeCommandError::Failed {
        reason: reason.into(),
    }
}

/// Enforce the operation-specific policy at the execution owner. Only an
/// absent permissions plugin enables the local single-user fallback.
fn ensure_session_mutation_allowed(
    ctx: &bmux_plugin_sdk::NativeServiceContext,
    session_id: SessionId,
    action: &str,
) -> Result<(), PaneCommandError> {
    super::spawn::authorize_session(ctx, session_id.0, action).map_err(|error| {
        let reason = match error {
            bmux_pane_runtime_plugin_api::pane_runtime_spawn_v1::SpawnError::Denied { reason } => {
                reason
            }
            other => format!("session policy check failed: {other:?}"),
        };
        PaneCommandError::Denied { reason }
    })
}

fn parse_split_direction(raw: &str) -> Result<PaneSplitDirection, PaneCommandError> {
    match raw {
        "horizontal" => Ok(PaneSplitDirection::Horizontal),
        "vertical" => Ok(PaneSplitDirection::Vertical),
        other => Err(failed_command(format!(
            "invalid split direction: '{other}' (expected horizontal|vertical)"
        ))),
    }
}

fn parse_focus_direction(raw: &str) -> Result<Option<PaneFocusDirection>, PaneCommandError> {
    match raw {
        "next" => Ok(Some(PaneFocusDirection::Next)),
        "prev" | "previous" => Ok(Some(PaneFocusDirection::Prev)),
        "" => Ok(None),
        other => Err(failed_command(format!(
            "invalid focus direction: '{other}'"
        ))),
    }
}

fn parse_resize_direction(raw: &str) -> Result<PaneResizeDirection, PaneCommandError> {
    match raw {
        "increase" => Ok(PaneResizeDirection::Increase),
        "decrease" => Ok(PaneResizeDirection::Decrease),
        "left" => Ok(PaneResizeDirection::Left),
        "right" => Ok(PaneResizeDirection::Right),
        "up" => Ok(PaneResizeDirection::Up),
        "down" => Ok(PaneResizeDirection::Down),
        other => Err(failed_command(format!(
            "invalid resize direction: '{other}' (expected increase|decrease|left|right|up|down)"
        ))),
    }
}

fn parse_floating_scope(raw: Option<&str>) -> Result<FloatingPaneScope, PaneCommandError> {
    match raw.unwrap_or("per_window") {
        "per_pane" | "pane" => Ok(FloatingPaneScope::PerPane),
        "per_window" | "per_tab" | "window" | "tab" => Ok(FloatingPaneScope::PerWindow),
        "per_session" | "session" => Ok(FloatingPaneScope::PerSession),
        "client_global" | "client" => Ok(FloatingPaneScope::ClientGlobal),
        "server_global" | "global" | "server" => Ok(FloatingPaneScope::ServerGlobal),
        other => Err(failed_command(format!(
            "invalid floating pane scope: '{other}'"
        ))),
    }
}

fn parse_floating_layer(raw: Option<&str>) -> Result<FloatingPaneLayer, PaneCommandError> {
    match raw.unwrap_or("floating_pane") {
        "pane" => Ok(FloatingPaneLayer::Pane),
        "overlay" => Ok(FloatingPaneLayer::Overlay),
        "floating" | "floating_pane" => Ok(FloatingPaneLayer::FloatingPane),
        "tooltip" | "top" => Ok(FloatingPaneLayer::Tooltip),
        other => Err(failed_command(format!(
            "invalid floating pane layer: '{other}'"
        ))),
    }
}

fn floating_ack(
    session_id: SessionId,
    summary: bmux_pane_runtime_state::FloatingPaneRuntimeSummary,
) -> FloatingPaneAck {
    FloatingPaneAck {
        session_id: session_id.0,
        pane_id: summary.pane_id,
        surface_id: summary.id,
    }
}

fn target_selector(target: Option<Uuid>) -> Option<PaneSelector> {
    target.map(PaneSelector::ById)
}

fn publish_session_removed_event(session_id: SessionId) {
    let _ = bmux_plugin::global_event_bus().emit(
        &sessions_events::EVENT_KIND,
        SessionEvent::Removed {
            session_id: session_id.0,
        },
    );
}

fn publish_pane_event(event: PaneEvent) {
    let _ = bmux_plugin::global_event_bus().emit(&pane_runtime_events::EVENT_KIND, event);
}

static PANE_FACT_REVISION: AtomicU64 = AtomicU64::new(0);

pub(crate) fn publish_pane_lifecycle_facts() {
    let Some(handle) = super::session_runtime_handle() else {
        return;
    };
    let facts = handle
        .0
        .active_session_ids()
        .into_iter()
        .flat_map(|session_id| handle.0.list_panes(session_id).unwrap_or_default())
        .map(|pane| PresentationFact {
            entity: PresentationEntityRef::new("bmux.panes", pane.id.to_string()),
            key: "lifecycle".to_string(),
            role: if matches!(pane.state, bmux_attach_layout_protocol::PaneState::Exited) {
                PresentationFactRole::Error
            } else {
                PresentationFactRole::Active
            },
            short_text: if matches!(pane.state, bmux_attach_layout_protocol::PaneState::Exited) {
                "exited".to_string()
            } else {
                "running".to_string()
            },
            detail_text: pane.state_reason,
            icon_id: Some(
                if matches!(pane.state, bmux_attach_layout_protocol::PaneState::Exited) {
                    "pane.exited"
                } else {
                    "pane.running"
                }
                .to_string(),
            ),
            priority: 100,
        })
        .collect();
    let _ = global_presentation_fact_host_service()
        .registry()
        .publish_authorized(
            "bmux.pane_runtime",
            "bmux.pane_runtime",
            PresentationFactSnapshot {
                revision: PANE_FACT_REVISION
                    .fetch_add(1, Ordering::Relaxed)
                    .wrapping_add(1),
                facts,
            },
        );
}

/// Bump a session's attach-view revision and publish the scene
/// component update. Mirrors the server's
/// `emit_attach_view_changed_for_layout` helper so plugin-side
/// handlers keep parity with the old IPC-handler behavior.
///
/// Also republishes the pane-runtime-focus state channel so
/// subscribers (decoration plugin, future status bars) see the
/// current focused pane without polling.
fn emit_attach_view_changed_scene(session_id: SessionId) {
    let Some(handle) = super::session_runtime_handle() else {
        return;
    };
    let Some(revision) = handle.0.bump_attach_view_revision(session_id) else {
        return;
    };
    publish_pane_event(PaneEvent::AttachViewChanged {
        context_id: None,
        session_id: session_id.0,
        revision,
        components: vec![AttachViewComponent::Scene],
    });
    super::publish_focus_state_snapshot();
    publish_pane_lifecycle_facts();
}

fn emit_attach_view_changed_scene_all() {
    let Some(handle) = super::session_runtime_handle() else {
        return;
    };
    for session_id in handle.0.active_session_ids() {
        emit_attach_view_changed_scene(session_id);
    }
}

pub fn split_pane(
    req: &SplitPaneArgs,
    ctx: &bmux_plugin_sdk::NativeServiceContext,
) -> Result<PaneAck, PaneCommandError> {
    let handle = super::session_runtime_handle()
        .ok_or_else(|| failed_command("pane-runtime manager handle not registered"))?;
    let direction = parse_split_direction(&req.direction)?;
    let session_id = SessionId(req.session_id);
    ensure_session_mutation_allowed(ctx, session_id, "pane.split")?;
    let pane_id = handle
        .0
        .split_pane(session_id, target_selector(req.target), direction)
        .map_err(|e| failed_command(e.to_string()))?;
    emit_attach_view_changed_scene(session_id);
    Ok(PaneAck {
        session_id: req.session_id,
        pane_id,
    })
}

pub fn launch_pane(
    req: LaunchPaneArgs,
    ctx: &bmux_plugin_sdk::NativeServiceContext,
) -> Result<PaneAck, PaneCommandError> {
    let handle = super::session_runtime_handle()
        .ok_or_else(|| failed_command("pane-runtime manager handle not registered"))?;
    let direction = parse_split_direction(&req.direction)?;
    let command = PaneLaunchCommand {
        program: req.program,
        args: req.args,
        cwd: req.cwd,
        env: std::collections::BTreeMap::new(),
    };
    let session_id = SessionId(req.session_id);
    ensure_session_mutation_allowed(ctx, session_id, "pane.launch")?;
    let pane_id = handle
        .0
        .launch_pane(
            session_id,
            target_selector(req.target),
            direction,
            req.name,
            command,
        )
        .map_err(|e| failed_command(e.to_string()))?;
    emit_attach_view_changed_scene(session_id);
    Ok(PaneAck {
        session_id: req.session_id,
        pane_id,
    })
}

pub fn focus_pane(
    req: &FocusPaneArgs,
    ctx: &bmux_plugin_sdk::NativeServiceContext,
) -> Result<PaneAck, PaneCommandError> {
    let handle = super::session_runtime_handle()
        .ok_or_else(|| failed_command("pane-runtime manager handle not registered"))?;
    let session_id = SessionId(req.session_id);
    ensure_session_mutation_allowed(ctx, session_id, "pane.focus")?;
    let pane_id = match (req.target, parse_focus_direction(&req.direction)?) {
        (Some(t), None) => handle
            .0
            .focus_pane_target(session_id, &PaneSelector::ById(t)),
        (None, Some(dir)) => handle.0.focus_pane(session_id, dir),
        (None, None) => handle
            .0
            .focus_pane_target(session_id, &PaneSelector::Active),
        (Some(_), Some(_)) => {
            return Err(failed_command(
                "focus-pane cannot use target and direction together",
            ));
        }
    }
    .map_err(|e| failed_command(e.to_string()))?;
    emit_attach_view_changed_scene(session_id);
    Ok(PaneAck {
        session_id: req.session_id,
        pane_id,
    })
}

pub fn resize_pane(
    req: &ResizePaneArgs,
    ctx: &bmux_plugin_sdk::NativeServiceContext,
) -> Result<SessionAck, PaneCommandError> {
    let handle = super::session_runtime_handle()
        .ok_or_else(|| failed_command("pane-runtime manager handle not registered"))?;
    let session_id = SessionId(req.session_id);
    ensure_session_mutation_allowed(ctx, session_id, "pane.resize")?;
    let direction = parse_resize_direction(&req.direction)?;
    handle
        .0
        .resize_pane(
            session_id,
            target_selector(req.target),
            direction,
            req.cells.max(1),
        )
        .map_err(|e| failed_command(e.to_string()))?;
    emit_attach_view_changed_scene(session_id);
    Ok(SessionAck {
        session_id: req.session_id,
    })
}

pub fn close_pane(
    req: &ClosePaneArgs,
    ctx: &bmux_plugin_sdk::NativeServiceContext,
) -> Result<PaneAck, PaneCommandError> {
    use bmux_plugin::global_plugin_state_registry;

    let handle = super::session_runtime_handle()
        .ok_or_else(|| failed_command("pane-runtime manager handle not registered"))?;
    let session_id = SessionId(req.session_id);
    ensure_session_mutation_allowed(ctx, session_id, "pane.close")?;
    if handle
        .0
        .list_panes(session_id)
        .map_err(|e| failed_command(e.to_string()))?
        .len()
        <= 1
    {
        return Err(PaneCommandError::Denied {
            reason: "cannot close the final pane without choosing a new target or quitting"
                .to_string(),
        });
    }
    let (pane_id, removed_runtime) = handle
        .0
        .close_pane(session_id, target_selector(req.target))
        .map_err(|e| failed_command(e.to_string()))?;

    // When closing the last pane removes the whole session, tear down
    // every associated piece (session-manager entry, context
    // mappings, follow-state selections, attach tokens) and emit the
    // session-level wire events. Mirrors the server's legacy
    // `Request::ClosePane` orchestration.
    let session_closed = removed_runtime.is_some();
    if let Some(removed) = removed_runtime {
        let had_attached_clients = !removed.attached_clients.is_empty();
        handle.0.shutdown_removed_runtime(removed);

        if let Some(session_handle) = global_plugin_state_registry()
            .get::<bmux_session_state::SessionManagerHandle>()
            .and_then(|arc| arc.read().ok().map(|g| (*g).clone()))
        {
            let _ = session_handle.0.remove_session(session_id);
        }
        if let Some(context_handle) = global_plugin_state_registry()
            .get::<bmux_context_state::ContextStateHandle>()
            .and_then(|arc| arc.read().ok().map(|g| (*g).clone()))
        {
            let _ = context_handle.0.remove_contexts_for_session(session_id);
        }
        if let Some(follow_handle) = global_plugin_state_registry()
            .get::<bmux_client_state::FollowStateHandle>()
            .and_then(|arc| arc.read().ok().map(|g| (*g).clone()))
        {
            follow_handle.0.clear_selections_for_session(session_id);
        }
        if let Some(attach_tokens) = global_plugin_state_registry()
            .get::<bmux_attach_token_state::AttachTokenManagerHandle>()
            .and_then(|arc| arc.read().ok().map(|g| (*g).clone()))
        {
            attach_tokens.0.remove_for_session(session_id);
        }

        if had_attached_clients {
            publish_pane_event(PaneEvent::ClientDetached {
                session_id: session_id.0,
            });
        }
        publish_session_removed_event(session_id);
    }

    if !session_closed {
        emit_attach_view_changed_scene(session_id);
    }

    Ok(PaneAck {
        session_id: req.session_id,
        pane_id,
    })
}

pub fn restart_pane(
    req: &RestartPaneArgs,
    ctx: &bmux_plugin_sdk::NativeServiceContext,
) -> Result<PaneAck, PaneCommandError> {
    let handle = super::session_runtime_handle()
        .ok_or_else(|| failed_command("pane-runtime manager handle not registered"))?;
    let session_id = SessionId(req.session_id);
    ensure_session_mutation_allowed(ctx, session_id, "pane.restart")?;
    let pane_id = handle
        .0
        .restart_pane(session_id, target_selector(req.target))
        .map_err(|e| failed_command(e.to_string()))?;
    publish_pane_event(PaneEvent::Restarted {
        session_id: session_id.0,
        pane_id,
    });
    emit_attach_view_changed_scene(session_id);
    Ok(PaneAck {
        session_id: req.session_id,
        pane_id,
    })
}

pub fn zoom_pane(
    req: &ZoomPaneArgs,
    ctx: &bmux_plugin_sdk::NativeServiceContext,
) -> Result<PaneAck, PaneCommandError> {
    let handle = super::session_runtime_handle()
        .ok_or_else(|| failed_command("pane-runtime manager handle not registered"))?;
    let session_id = SessionId(req.session_id);
    ensure_session_mutation_allowed(ctx, session_id, "pane.zoom")?;
    let (pane_id, _zoomed) = handle
        .0
        .toggle_zoom(session_id)
        .map_err(|e| failed_command(e.to_string()))?;
    emit_attach_view_changed_scene(session_id);
    Ok(PaneAck {
        session_id: req.session_id,
        pane_id,
    })
}

pub fn create_floating_pane(
    req: CreateFloatingPaneArgs,
    ctx: &bmux_plugin_sdk::NativeServiceContext,
) -> Result<FloatingPaneAck, PaneCommandError> {
    let handle = super::session_runtime_handle()
        .ok_or_else(|| failed_command("pane-runtime manager handle not registered"))?;
    let session_id = SessionId(req.session_id);
    ensure_session_mutation_allowed(ctx, session_id, "pane.floating.create")?;
    let command = req.program.map(|program| PaneLaunchCommand {
        program,
        args: req.args,
        cwd: req.cwd,
        env: std::collections::BTreeMap::new(),
    });
    let summary = handle
        .0
        .create_floating_pane(
            session_id,
            target_selector(req.target),
            LayoutRect {
                x: req.x.unwrap_or(2),
                y: req.y.unwrap_or(2),
                w: req.w.unwrap_or(80).max(1),
                h: req.h.unwrap_or(24).max(1),
            },
            parse_floating_scope(req.scope.as_deref())?,
            parse_floating_layer(req.layer.as_deref())?,
            req.z.unwrap_or(0),
            req.name,
            command,
            req.anchor_pane_id,
            req.context_id,
            req.client_id.or(ctx.caller_client_id).map(ClientId),
        )
        .map_err(|e| failed_command(e.to_string()))?;
    emit_attach_view_changed_scene_all();
    Ok(floating_ack(session_id, summary))
}

pub fn move_floating_pane(
    req: &MoveFloatingPaneArgs,
    ctx: &bmux_plugin_sdk::NativeServiceContext,
) -> Result<FloatingPaneAck, PaneCommandError> {
    let handle = super::session_runtime_handle()
        .ok_or_else(|| failed_command("pane-runtime manager handle not registered"))?;
    let session_id = SessionId(req.session_id);
    ensure_session_mutation_allowed(ctx, session_id, "pane.floating.move")?;
    let summary = handle
        .0
        .move_floating_pane(session_id, req.pane_id, req.x, req.y)
        .map_err(|e| failed_command(e.to_string()))?;
    emit_attach_view_changed_scene_all();
    Ok(floating_ack(session_id, summary))
}

pub fn resize_floating_pane(
    req: &ResizeFloatingPaneArgs,
    ctx: &bmux_plugin_sdk::NativeServiceContext,
) -> Result<FloatingPaneAck, PaneCommandError> {
    let handle = super::session_runtime_handle()
        .ok_or_else(|| failed_command("pane-runtime manager handle not registered"))?;
    let session_id = SessionId(req.session_id);
    ensure_session_mutation_allowed(ctx, session_id, "pane.floating.resize")?;
    let summary = handle
        .0
        .resize_floating_pane(session_id, req.pane_id, req.w.max(1), req.h.max(1))
        .map_err(|e| failed_command(e.to_string()))?;
    emit_attach_view_changed_scene_all();
    Ok(floating_ack(session_id, summary))
}

fn mutate_floating_target(
    req: &FloatingPaneTargetArgs,
    ctx: &bmux_plugin_sdk::NativeServiceContext,
    action: &str,
    mutate: impl FnOnce(
        &bmux_pane_runtime_state::SessionRuntimeManagerHandle,
        SessionId,
        Uuid,
    ) -> anyhow::Result<bmux_pane_runtime_state::FloatingPaneRuntimeSummary>,
) -> Result<FloatingPaneAck, PaneCommandError> {
    let handle = super::session_runtime_handle()
        .ok_or_else(|| failed_command("pane-runtime manager handle not registered"))?;
    let session_id = SessionId(req.session_id);
    ensure_session_mutation_allowed(ctx, session_id, action)?;
    let summary =
        mutate(&handle, session_id, req.pane_id).map_err(|e| failed_command(e.to_string()))?;
    emit_attach_view_changed_scene_all();
    Ok(floating_ack(session_id, summary))
}

pub fn focus_floating_pane(
    req: &FloatingPaneTargetArgs,
    ctx: &bmux_plugin_sdk::NativeServiceContext,
) -> Result<FloatingPaneAck, PaneCommandError> {
    mutate_floating_target(
        req,
        ctx,
        "pane.floating.focus",
        |handle, session_id, pane_id| handle.0.focus_floating_pane(session_id, pane_id),
    )
}

pub fn raise_floating_pane(
    req: &FloatingPaneTargetArgs,
    ctx: &bmux_plugin_sdk::NativeServiceContext,
) -> Result<FloatingPaneAck, PaneCommandError> {
    mutate_floating_target(
        req,
        ctx,
        "pane.floating.raise",
        |handle, session_id, pane_id| handle.0.raise_floating_pane(session_id, pane_id),
    )
}

pub fn lower_floating_pane(
    req: &FloatingPaneTargetArgs,
    ctx: &bmux_plugin_sdk::NativeServiceContext,
) -> Result<FloatingPaneAck, PaneCommandError> {
    mutate_floating_target(
        req,
        ctx,
        "pane.floating.lower",
        |handle, session_id, pane_id| handle.0.lower_floating_pane(session_id, pane_id),
    )
}

pub fn set_floating_pane_z(
    req: &SetFloatingPaneZArgs,
    ctx: &bmux_plugin_sdk::NativeServiceContext,
) -> Result<FloatingPaneAck, PaneCommandError> {
    let handle = super::session_runtime_handle()
        .ok_or_else(|| failed_command("pane-runtime manager handle not registered"))?;
    let session_id = SessionId(req.session_id);
    ensure_session_mutation_allowed(ctx, session_id, "pane.floating.set_z")?;
    let summary = handle
        .0
        .set_floating_pane_z(session_id, req.pane_id, req.z)
        .map_err(|e| failed_command(e.to_string()))?;
    emit_attach_view_changed_scene_all();
    Ok(floating_ack(session_id, summary))
}

pub fn set_floating_pane_layer(
    req: &SetFloatingPaneLayerArgs,
    ctx: &bmux_plugin_sdk::NativeServiceContext,
) -> Result<FloatingPaneAck, PaneCommandError> {
    let handle = super::session_runtime_handle()
        .ok_or_else(|| failed_command("pane-runtime manager handle not registered"))?;
    let session_id = SessionId(req.session_id);
    ensure_session_mutation_allowed(ctx, session_id, "pane.floating.set_layer")?;
    let summary = handle
        .0
        .set_floating_pane_layer(
            session_id,
            req.pane_id,
            parse_floating_layer(Some(&req.layer))?,
        )
        .map_err(|e| failed_command(e.to_string()))?;
    emit_attach_view_changed_scene_all();
    Ok(floating_ack(session_id, summary))
}

pub fn close_floating_pane(
    req: &FloatingPaneTargetArgs,
    ctx: &bmux_plugin_sdk::NativeServiceContext,
) -> Result<FloatingPaneAck, PaneCommandError> {
    let ack = close_pane(
        &ClosePaneArgs {
            session_id: req.session_id,
            target: Some(req.pane_id),
        },
        ctx,
    )?;
    emit_attach_view_changed_scene_all();
    Ok(FloatingPaneAck {
        session_id: ack.session_id,
        pane_id: ack.pane_id,
        surface_id: Uuid::nil(),
    })
}

pub fn pane_direct_input(
    req: PaneDirectInputArgs,
    ctx: &bmux_plugin_sdk::NativeServiceContext,
) -> Result<PaneAck, PaneCommandError> {
    let handle = super::session_runtime_handle()
        .ok_or_else(|| failed_command("pane-runtime manager handle not registered"))?;
    let session_id = SessionId(req.session_id);
    let client_id = ctx
        .caller_client_id
        .map(bmux_session_models::ClientId)
        .ok_or_else(|| {
            warn!(session_id = %req.session_id, pane_id = %req.pane_id, "pane direct input rejected: missing caller client id");
            failed_command("pane direct input requires a caller client id")
        })?;
    if !handle.0.client_can_write(session_id, client_id) {
        warn!(session_id = %req.session_id, pane_id = %req.pane_id, client_id = %client_id.0, "pane direct input rejected: client lacks write permission");
        return Err(PaneCommandError::Denied {
            reason: "client does not have write permission for this attach stream".to_string(),
        });
    }
    match handle
        .0
        .write_input_to_pane(session_id, client_id, req.pane_id, req.data)
    {
        Ok(_) => {}
        Err(error) => {
            let reason = handle
                .0
                .pane_state_reason(session_id, req.pane_id)
                .unwrap_or_else(|| error.to_string());
            warn!(session_id = %req.session_id, pane_id = %req.pane_id, client_id = %client_id.0, %error, %reason, "pane direct input failed");
            return Err(failed_command(reason));
        }
    }
    Ok(PaneAck {
        session_id: req.session_id,
        pane_id: req.pane_id,
    })
}

pub fn execution_pane_input(req: ExecutionPaneInputArgs) -> Result<PaneAck, PaneCommandError> {
    let handle = super::session_runtime_handle()
        .ok_or_else(|| failed_command("pane-runtime manager handle not registered"))?;
    handle
        .0
        .write_input_to_pane(
            SessionId(req.session_id),
            ClientId(Uuid::nil()),
            req.pane_id,
            req.data,
        )
        .map_err(|error| failed_command(error.to_string()))?;
    Ok(PaneAck {
        session_id: req.session_id,
        pane_id: req.pane_id,
    })
}

pub fn destroy_execution_pane(req: &ExecutionPaneTargetArgs) -> Result<PaneAck, PaneCommandError> {
    let handle = super::session_runtime_handle()
        .ok_or_else(|| failed_command("pane-runtime manager handle not registered"))?;
    let session_id = SessionId(req.session_id);
    if handle
        .0
        .pane_process_identity(session_id, req.pane_id)
        .is_none()
    {
        return Err(failed_command("execution pane is missing"));
    }
    let removed = handle
        .0
        .remove_runtime(session_id)
        .ok_or_else(|| failed_command("execution runtime is missing"))?;
    handle.0.shutdown_removed_runtime(removed);
    Ok(PaneAck {
        session_id: req.session_id,
        pane_id: req.pane_id,
    })
}

pub fn ensure_execution_pane(req: EnsureExecutionPaneArgs) -> Result<PaneAck, PaneCommandError> {
    let handle = super::session_runtime_handle()
        .ok_or_else(|| failed_command("pane-runtime manager handle not registered"))?;
    if req.rows == 0 || req.cols == 0 || req.program.trim().is_empty() {
        return Err(failed_command(
            "execution pane requires a program and positive dimensions",
        ));
    }
    let session_id = SessionId(req.session_id);
    if handle.0.session_exists(session_id) {
        return handle
            .0
            .pane_process_identity(session_id, req.pane_id)
            .map(|_| PaneAck {
                session_id: req.session_id,
                pane_id: req.pane_id,
            })
            .ok_or_else(|| {
                failed_command("execution session exists without its deterministic pane")
            });
    }
    let pane = bmux_pane_runtime_state::PaneRuntimeMeta {
        id: req.pane_id,
        name: req.name,
        shell: req.program.clone(),
        launch: Some(bmux_pane_runtime_state::PaneLaunchSpec {
            program: req.program,
            args: req.args,
            cwd: req.cwd,
            env: req
                .env
                .into_iter()
                .map(|entry| (entry.key, entry.value))
                .collect(),
        }),
        resurrection: bmux_pane_runtime_state::PaneResurrectionSnapshot::default(),
    };
    handle
        .0
        .restore_runtime(
            session_id,
            &[pane],
            bmux_pane_runtime_state::RestoreRuntimeRequest::with_focus(req.pane_id).layout_root(
                Some(bmux_pane_runtime_state::PaneLayoutNode::Leaf {
                    pane_id: req.pane_id,
                }),
            ),
        )
        .map_err(|error| failed_command(error.to_string()))?;
    handle
        .0
        .set_pane_pty_size(session_id, req.pane_id, req.rows, req.cols)
        .map_err(|error| failed_command(error.to_string()))?;
    Ok(PaneAck {
        session_id: req.session_id,
        pane_id: req.pane_id,
    })
}

pub fn pane_set_pty_size(req: &PaneSetPtySizeArgs) -> Result<PaneAck, PaneCommandError> {
    let handle = super::session_runtime_handle()
        .ok_or_else(|| failed_command("pane-runtime manager handle not registered"))?;
    handle
        .0
        .set_pane_pty_size(SessionId(req.session_id), req.pane_id, req.rows, req.cols)
        .map_err(|error| failed_command(error.to_string()))?;
    Ok(PaneAck {
        session_id: req.session_id,
        pane_id: req.pane_id,
    })
}

pub fn pane_signal(req: &PaneSignalArgs) -> Result<PaneAck, PaneCommandError> {
    let handle = super::session_runtime_handle()
        .ok_or_else(|| failed_command("pane-runtime manager handle not registered"))?;
    let signal = match req.signal {
        bmux_pane_runtime_plugin_api::pane_runtime_commands::PaneProcessSignal::Interrupt => {
            bmux_pane_runtime_state::PaneProcessSignal::Interrupt
        }
        bmux_pane_runtime_plugin_api::pane_runtime_commands::PaneProcessSignal::Terminate => {
            bmux_pane_runtime_state::PaneProcessSignal::Terminate
        }
        bmux_pane_runtime_plugin_api::pane_runtime_commands::PaneProcessSignal::Kill => {
            bmux_pane_runtime_state::PaneProcessSignal::Kill
        }
        bmux_pane_runtime_plugin_api::pane_runtime_commands::PaneProcessSignal::Hangup => {
            bmux_pane_runtime_state::PaneProcessSignal::Hangup
        }
    };
    handle
        .0
        .signal_pane_process(SessionId(req.session_id), req.pane_id, signal)
        .map_err(|error| failed_command(error.to_string()))?;
    Ok(PaneAck {
        session_id: req.session_id,
        pane_id: req.pane_id,
    })
}

pub fn set_client_write_permission(
    req: &SetClientWritePermissionArgs,
) -> Result<u8, PaneCommandError> {
    let handle = super::session_runtime_handle()
        .ok_or_else(|| failed_command("pane-runtime manager handle not registered"))?;
    handle.0.set_client_write_permission(
        SessionId(req.session_id),
        bmux_session_models::ClientId(req.client_id),
        req.allowed,
    );
    Ok(u8::from(req.allowed))
}

pub fn new_session_with_runtime(
    req: &NewSessionArgs,
) -> Result<SessionAck, SessionRuntimeCommandError> {
    use bmux_plugin::global_plugin_state_registry;

    let runtime_handle = super::session_runtime_handle()
        .ok_or_else(|| failed_session("pane-runtime manager handle not registered"))?;
    let session_handle = global_plugin_state_registry()
        .get::<bmux_session_state::SessionManagerHandle>()
        .and_then(|arc| arc.read().ok().map(|g| (*g).clone()))
        .ok_or_else(|| failed_session("session manager handle not registered"))?;

    // Sessions are identified by UUID. Names are display hints that
    // may be duplicated deliberately by the caller — the handler
    // does not reject a session just because another session shares
    // its name. The `name-already-exists` error variant was removed
    // from the BPDL wire type for this reason.

    let session_id = session_handle
        .0
        .create_session(req.name.clone())
        .map_err(|error| failed_session(format!("failed creating session: {error:#}")))?;

    if let Err(error) = runtime_handle.0.start_runtime(session_id) {
        return Err(runtime_creation_failure(
            session_id,
            &error,
            session_handle.0.remove_session(session_id),
        ));
    }

    // NOTE: this handler deliberately does NOT create a context for the
    // new session. Context lifecycle is owned by `bmux.contexts`
    // plugin's `create_context_local`, which is the caller that drives
    // this function via `sessions-commands::new-session` ->
    // `pane-runtime-commands::new-session-with-runtime`. Creating a
    // second context here (with a nil caller client id) produced a
    // "shadow tab" duplicated per keystroke (see the bmux
    // `context_state.create` trace). Keep this function focused on
    // session + runtime allocation; let the caller own context
    // creation.

    Ok(SessionAck {
        session_id: session_id.0,
    })
}

fn runtime_creation_failure(
    session_id: SessionId,
    startup_error: &anyhow::Error,
    rollback: Result<(), impl std::fmt::Display>,
) -> SessionRuntimeCommandError {
    let reason = match rollback {
        Ok(()) => format!("failed creating session runtime: {startup_error:#}"),
        Err(cleanup_error) => format!(
            "failed creating session runtime: {startup_error:#}; \
             failed rolling back newly created session {}: {cleanup_error}",
            session_id.0
        ),
    };
    failed_session(reason)
}

pub fn kill_session_runtime(
    req: &KillSessionArgs,
) -> Result<SessionAck, SessionRuntimeCommandError> {
    use bmux_plugin::global_plugin_state_registry;

    let runtime_handle = super::session_runtime_handle()
        .ok_or_else(|| failed_session("pane-runtime manager handle not registered"))?;
    let session_handle = global_plugin_state_registry()
        .get::<bmux_session_state::SessionManagerHandle>()
        .and_then(|arc| arc.read().ok().map(|g| (*g).clone()))
        .ok_or_else(|| failed_session("session manager handle not registered"))?;
    let context_handle = global_plugin_state_registry()
        .get::<bmux_context_state::ContextStateHandle>()
        .and_then(|arc| arc.read().ok().map(|g| (*g).clone()))
        .ok_or_else(|| failed_session("context state handle not registered"))?;
    let attach_token_handle = global_plugin_state_registry()
        .get::<bmux_attach_token_state::AttachTokenManagerHandle>()
        .and_then(|arc| arc.read().ok().map(|g| (*g).clone()))
        .ok_or_else(|| failed_session("attach-token manager handle not registered"))?;
    let follow_handle = global_plugin_state_registry()
        .get::<bmux_client_state::FollowStateHandle>()
        .and_then(|arc| arc.read().ok().map(|g| (*g).clone()))
        .ok_or_else(|| failed_session("follow state handle not registered"))?;
    let session_id = SessionId(req.session_id);
    let _ = req.force_local; // admin-principal gate + remote tear-down remain server-side for now.

    if session_handle.0.remove_session(session_id).is_err() {
        return Err(SessionRuntimeCommandError::SessionNotFound);
    }

    let _removed_contexts = context_handle.0.remove_contexts_for_session(session_id);
    follow_handle.0.clear_selections_for_session(session_id);

    let Some(removed_runtime) = runtime_handle.0.remove_runtime(session_id) else {
        return Err(failed_session(format!(
            "failed stopping session runtime: session {} not found",
            session_id.0
        )));
    };

    let had_attached_clients = !removed_runtime.attached_clients.is_empty();
    runtime_handle.0.shutdown_removed_runtime(removed_runtime);
    attach_token_handle.0.remove_for_session(session_id);

    if had_attached_clients {
        publish_pane_event(PaneEvent::ClientDetached {
            session_id: session_id.0,
        });
    }

    publish_session_removed_event(session_id);

    Ok(SessionAck {
        session_id: req.session_id,
    })
}

pub fn restore_session_runtime() -> Result<SessionAck, SessionRuntimeCommandError> {
    Err(failed_session(
        "restore-session-runtime is driven by the snapshot orchestrator on startup; \
         clients should not invoke it directly",
    ))
}

#[cfg(test)]
mod creation_failure_tests {
    use super::*;

    #[test]
    fn rollback_failure_preserves_both_errors_and_resource_identity() {
        let session_id = SessionId(Uuid::new_v4());
        let error = runtime_creation_failure(
            session_id,
            &anyhow::anyhow!("runtime unavailable"),
            Err("storage unavailable"),
        );
        let SessionRuntimeCommandError::Failed { reason } = error else {
            panic!("expected explicit failure");
        };
        assert!(reason.contains("runtime unavailable"));
        assert!(reason.contains("storage unavailable"));
        assert!(reason.contains(&session_id.0.to_string()));
    }

    #[test]
    fn successful_rollback_does_not_claim_cleanup_failed() {
        let error = runtime_creation_failure(
            SessionId(Uuid::new_v4()),
            &anyhow::anyhow!("runtime unavailable"),
            Ok::<(), String>(()),
        );
        let SessionRuntimeCommandError::Failed { reason } = error else {
            panic!("expected startup failure");
        };
        assert_eq!(
            reason,
            "failed creating session runtime: runtime unavailable"
        );
    }
}