bmux_client 0.0.1-alpha.0

Client component for bmux 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
#![cfg_attr(feature = "fail-on-warnings", deny(warnings))]
#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)]
#![allow(clippy::multiple_crate_versions)]
#![allow(clippy::cargo_common_metadata)]

//! Client component for bmux terminal multiplexer.

use bmux_config::{BmuxConfig, ConfigPaths};
pub use bmux_ipc::Event as ServerEvent;
use bmux_ipc::transport::{IpcTransportError, LocalIpcStream};
use bmux_ipc::{
    AttachGrant, ClientSummary, Envelope, EnvelopeKind, ErrorCode, IpcEndpoint, ProtocolVersion,
    Request, Response, ResponsePayload, ServerSnapshotStatus, SessionPermissionSummary,
    SessionRole, SessionSelector, SessionSummary, WindowSelector, WindowSummary, decode, encode,
};
use std::time::Duration;
use thiserror::Error;
use tracing::debug;
use uuid::Uuid;

/// Result type for client operations.
pub type Result<T> = std::result::Result<T, ClientError>;

/// Details returned when opening an attach stream.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AttachOpenInfo {
    pub session_id: Uuid,
    pub can_write: bool,
}

/// Server status details returned by status RPC.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ServerStatusInfo {
    pub running: bool,
    pub snapshot: ServerSnapshotStatus,
}

/// Summary returned by apply-restore operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ServerRestoreSummary {
    pub sessions: usize,
    pub windows: usize,
    pub roles: usize,
    pub follows: usize,
    pub selected_sessions: usize,
}

/// Typed client errors.
#[derive(Debug, Error)]
pub enum ClientError {
    #[error("transport error: {0}")]
    Transport(#[from] IpcTransportError),
    #[error("serialization error: {0}")]
    Serialization(#[from] postcard::Error),
    #[error("request timed out after {0:?}")]
    Timeout(Duration),
    #[error("request id mismatch (expected {expected}, got {actual})")]
    RequestIdMismatch { expected: u64, actual: u64 },
    #[error("unexpected envelope kind: expected {expected:?}, got {actual:?}")]
    UnexpectedEnvelopeKind {
        expected: EnvelopeKind,
        actual: EnvelopeKind,
    },
    #[error("server returned error {code:?}: {message}")]
    ServerError { code: ErrorCode, message: String },
    #[error("unexpected response payload: {0}")]
    UnexpectedResponse(&'static str),
    #[error("failed loading config: {0}")]
    ConfigLoad(#[from] bmux_config::ConfigError),
}

/// Main client API for communicating with bmux server.
#[derive(Debug)]
pub struct BmuxClient {
    stream: LocalIpcStream,
    timeout: Duration,
    next_request_id: u64,
}

impl BmuxClient {
    /// Connect to a server endpoint and complete protocol handshake.
    ///
    /// # Errors
    ///
    /// Returns an error if connection or handshake fails.
    pub async fn connect(
        endpoint: &IpcEndpoint,
        timeout: Duration,
        client_name: impl Into<String>,
    ) -> Result<Self> {
        let stream = LocalIpcStream::connect(endpoint).await?;
        let mut client = Self {
            stream,
            timeout,
            next_request_id: 1,
        };

        let hello_response = client
            .request(Request::Hello {
                protocol_version: ProtocolVersion::current(),
                client_name: client_name.into(),
            })
            .await?;

        match hello_response {
            ResponsePayload::ServerStatus { running: true, .. } => Ok(client),
            _ => Err(ClientError::UnexpectedResponse(
                "handshake expected running server status",
            )),
        }
    }

    /// Connect using endpoint derived from provided config paths.
    ///
    /// # Errors
    ///
    /// Returns an error if connection or handshake fails.
    pub async fn connect_with_paths(
        paths: &ConfigPaths,
        client_name: impl Into<String>,
    ) -> Result<Self> {
        let timeout = Duration::from_millis(BmuxConfig::load()?.general.server_timeout.max(1));
        let endpoint = endpoint_from_paths(paths);
        Self::connect(&endpoint, timeout, client_name).await
    }

    /// Connect using default config paths.
    ///
    /// # Errors
    ///
    /// Returns an error if connection or handshake fails.
    pub async fn connect_default(client_name: impl Into<String>) -> Result<Self> {
        Self::connect_with_paths(&ConfigPaths::default(), client_name).await
    }

    /// Ping the server.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn ping(&mut self) -> Result<()> {
        match self.request(Request::Ping).await? {
            ResponsePayload::Pong => Ok(()),
            _ => Err(ClientError::UnexpectedResponse("expected pong")),
        }
    }

    /// Return the server-assigned client UUID for this connection.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn whoami(&mut self) -> Result<Uuid> {
        match self.request(Request::WhoAmI).await? {
            ResponsePayload::ClientIdentity { id } => Ok(id),
            _ => Err(ClientError::UnexpectedResponse("expected client identity")),
        }
    }

    /// Retrieve server status.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn server_status(&mut self) -> Result<ServerStatusInfo> {
        match self.request(Request::ServerStatus).await? {
            ResponsePayload::ServerStatus { running, snapshot } => {
                Ok(ServerStatusInfo { running, snapshot })
            }
            _ => Err(ClientError::UnexpectedResponse("expected server status")),
        }
    }

    /// Trigger immediate server snapshot save.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn server_save(&mut self) -> Result<Option<String>> {
        match self.request(Request::ServerSave).await? {
            ResponsePayload::ServerSnapshotSaved { path } => Ok(path),
            _ => Err(ClientError::UnexpectedResponse(
                "expected server snapshot saved",
            )),
        }
    }

    /// Validate snapshot readability and schema without mutating runtime state.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn server_restore_dry_run(&mut self) -> Result<(bool, String)> {
        match self.request(Request::ServerRestoreDryRun).await? {
            ResponsePayload::ServerSnapshotRestoreDryRun { ok, message } => Ok((ok, message)),
            _ => Err(ClientError::UnexpectedResponse(
                "expected server snapshot restore dry-run",
            )),
        }
    }

    /// Apply snapshot restore, replacing current in-memory server state.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn server_restore_apply(&mut self) -> Result<ServerRestoreSummary> {
        match self.request(Request::ServerRestoreApply).await? {
            ResponsePayload::ServerSnapshotRestored {
                sessions,
                windows,
                roles,
                follows,
                selected_sessions,
            } => Ok(ServerRestoreSummary {
                sessions,
                windows,
                roles,
                follows,
                selected_sessions,
            }),
            _ => Err(ClientError::UnexpectedResponse(
                "expected server snapshot restored",
            )),
        }
    }

    /// Ask server to stop gracefully.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn stop_server(&mut self) -> Result<()> {
        match self.request(Request::ServerStop).await? {
            ResponsePayload::ServerStopping => Ok(()),
            _ => Err(ClientError::UnexpectedResponse("expected server stopping")),
        }
    }

    /// Create a new session.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn new_session(&mut self, name: Option<String>) -> Result<Uuid> {
        match self.request(Request::NewSession { name }).await? {
            ResponsePayload::SessionCreated { id, .. } => Ok(id),
            _ => Err(ClientError::UnexpectedResponse("expected session created")),
        }
    }

    /// List sessions.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn list_sessions(&mut self) -> Result<Vec<SessionSummary>> {
        match self.request(Request::ListSessions).await? {
            ResponsePayload::SessionList { sessions } => Ok(sessions),
            _ => Err(ClientError::UnexpectedResponse("expected session list")),
        }
    }

    /// List currently connected clients.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn list_clients(&mut self) -> Result<Vec<ClientSummary>> {
        match self.request(Request::ListClients).await? {
            ResponsePayload::ClientList { clients } => Ok(clients),
            _ => Err(ClientError::UnexpectedResponse("expected client list")),
        }
    }

    /// List explicit role assignments for a session.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn list_permissions(
        &mut self,
        session: SessionSelector,
    ) -> Result<Vec<SessionPermissionSummary>> {
        match self.request(Request::ListPermissions { session }).await? {
            ResponsePayload::PermissionsList { permissions, .. } => Ok(permissions),
            _ => Err(ClientError::UnexpectedResponse("expected permissions list")),
        }
    }

    /// Grant a role to a client within a session.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn grant_role(
        &mut self,
        session: SessionSelector,
        client_id: Uuid,
        role: SessionRole,
    ) -> Result<()> {
        match self
            .request(Request::GrantRole {
                session,
                client_id,
                role,
            })
            .await?
        {
            ResponsePayload::RoleGranted { .. } => Ok(()),
            _ => Err(ClientError::UnexpectedResponse("expected role granted")),
        }
    }

    /// Revoke a client's explicit role assignment (fallback to observer).
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn revoke_role(&mut self, session: SessionSelector, client_id: Uuid) -> Result<()> {
        match self
            .request(Request::RevokeRole { session, client_id })
            .await?
        {
            ResponsePayload::RoleRevoked { .. } => Ok(()),
            _ => Err(ClientError::UnexpectedResponse("expected role revoked")),
        }
    }

    /// Kill a session selected by name or UUID.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn kill_session(&mut self, selector: SessionSelector) -> Result<Uuid> {
        match self.request(Request::KillSession { selector }).await? {
            ResponsePayload::SessionKilled { id } => Ok(id),
            _ => Err(ClientError::UnexpectedResponse("expected session killed")),
        }
    }

    /// Create a new window in a session.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn new_window(
        &mut self,
        session: Option<SessionSelector>,
        name: Option<String>,
    ) -> Result<Uuid> {
        match self.request(Request::NewWindow { session, name }).await? {
            ResponsePayload::WindowCreated { id, .. } => Ok(id),
            _ => Err(ClientError::UnexpectedResponse("expected window created")),
        }
    }

    /// List windows in a session. If `session` is `None`, uses attached session context.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn list_windows(
        &mut self,
        session: Option<SessionSelector>,
    ) -> Result<Vec<WindowSummary>> {
        match self.request(Request::ListWindows { session }).await? {
            ResponsePayload::WindowList { windows } => Ok(windows),
            _ => Err(ClientError::UnexpectedResponse("expected window list")),
        }
    }

    /// Kill a window selected by id/name/active.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn kill_window(
        &mut self,
        session: Option<SessionSelector>,
        target: WindowSelector,
    ) -> Result<Uuid> {
        match self
            .request(Request::KillWindow { session, target })
            .await?
        {
            ResponsePayload::WindowKilled { id, .. } => Ok(id),
            _ => Err(ClientError::UnexpectedResponse("expected window killed")),
        }
    }

    /// Switch active window selected by id/name/active.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn switch_window(
        &mut self,
        session: Option<SessionSelector>,
        target: WindowSelector,
    ) -> Result<Uuid> {
        match self
            .request(Request::SwitchWindow { session, target })
            .await?
        {
            ResponsePayload::WindowSwitched { id, .. } => Ok(id),
            _ => Err(ClientError::UnexpectedResponse("expected window switched")),
        }
    }

    /// Follow another client's active session focus.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn follow_client(&mut self, target_client_id: Uuid, global: bool) -> Result<()> {
        match self
            .request(Request::FollowClient {
                target_client_id,
                global,
            })
            .await?
        {
            ResponsePayload::FollowStarted { .. } => Ok(()),
            _ => Err(ClientError::UnexpectedResponse("expected follow started")),
        }
    }

    /// Stop following any current follow target.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn unfollow(&mut self) -> Result<()> {
        match self.request(Request::Unfollow).await? {
            ResponsePayload::FollowStopped { .. } => Ok(()),
            _ => Err(ClientError::UnexpectedResponse("expected follow stopped")),
        }
    }

    /// Attach client to a session selected by name or UUID.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn attach(&mut self, selector: SessionSelector) -> Result<Uuid> {
        let grant = self.attach_grant(selector).await?;
        Ok(grant.session_id)
    }

    /// Request attach grant token for a session.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn attach_grant(&mut self, selector: SessionSelector) -> Result<AttachGrant> {
        match self.request(Request::Attach { selector }).await? {
            ResponsePayload::Attached { grant } => Ok(grant),
            _ => Err(ClientError::UnexpectedResponse(
                "expected attached response",
            )),
        }
    }

    /// Validate and consume attach grant token.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn open_attach_stream(&mut self, grant: &AttachGrant) -> Result<Uuid> {
        let info = self.open_attach_stream_info(grant).await?;
        Ok(info.session_id)
    }

    /// Validate and consume attach grant token and return role metadata.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn open_attach_stream_info(&mut self, grant: &AttachGrant) -> Result<AttachOpenInfo> {
        match self
            .request(Request::AttachOpen {
                session_id: grant.session_id,
                attach_token: grant.attach_token,
            })
            .await?
        {
            ResponsePayload::AttachReady {
                session_id,
                can_write,
            } => Ok(AttachOpenInfo {
                session_id,
                can_write,
            }),
            _ => Err(ClientError::UnexpectedResponse(
                "expected attach ready response",
            )),
        }
    }

    /// Detach from currently attached session.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn detach(&mut self) -> Result<()> {
        match self.request(Request::Detach).await? {
            ResponsePayload::Detached => Ok(()),
            _ => Err(ClientError::UnexpectedResponse(
                "expected detached response",
            )),
        }
    }

    /// Send bytes to an attached session runtime.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn attach_input(&mut self, session_id: Uuid, data: Vec<u8>) -> Result<usize> {
        match self
            .request(Request::AttachInput { session_id, data })
            .await?
        {
            ResponsePayload::AttachInputAccepted { bytes } => Ok(bytes),
            _ => Err(ClientError::UnexpectedResponse(
                "expected attach input accepted response",
            )),
        }
    }

    /// Read bytes from an attached session runtime.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn attach_output(&mut self, session_id: Uuid, max_bytes: usize) -> Result<Vec<u8>> {
        match self
            .request(Request::AttachOutput {
                session_id,
                max_bytes,
            })
            .await?
        {
            ResponsePayload::AttachOutput { data } => Ok(data),
            _ => Err(ClientError::UnexpectedResponse(
                "expected attach output response",
            )),
        }
    }

    /// Subscribe this client to server lifecycle events.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn subscribe_events(&mut self) -> Result<()> {
        match self.request(Request::SubscribeEvents).await? {
            ResponsePayload::EventsSubscribed => Ok(()),
            _ => Err(ClientError::UnexpectedResponse(
                "expected events subscribed response",
            )),
        }
    }

    /// Poll server lifecycle events for this client subscription.
    ///
    /// # Errors
    ///
    /// Returns an error if request or response validation fails.
    pub async fn poll_events(&mut self, max_events: usize) -> Result<Vec<ServerEvent>> {
        match self.request(Request::PollEvents { max_events }).await? {
            ResponsePayload::EventBatch { events } => Ok(events),
            _ => Err(ClientError::UnexpectedResponse(
                "expected event batch response",
            )),
        }
    }

    async fn request(&mut self, request: Request) -> Result<ResponsePayload> {
        let request_id = self.take_request_id();
        let payload = encode(&request)?;
        let envelope = Envelope::new(request_id, EnvelopeKind::Request, payload);

        tokio::time::timeout(self.timeout, self.stream.send_envelope(&envelope))
            .await
            .map_err(|_| ClientError::Timeout(self.timeout))??;

        let response_envelope = tokio::time::timeout(self.timeout, self.stream.recv_envelope())
            .await
            .map_err(|_| ClientError::Timeout(self.timeout))??;

        if response_envelope.request_id != request_id {
            return Err(ClientError::RequestIdMismatch {
                expected: request_id,
                actual: response_envelope.request_id,
            });
        }
        if response_envelope.kind != EnvelopeKind::Response {
            return Err(ClientError::UnexpectedEnvelopeKind {
                expected: EnvelopeKind::Response,
                actual: response_envelope.kind,
            });
        }

        let response: Response = decode(&response_envelope.payload)?;
        match response {
            Response::Ok(payload) => Ok(payload),
            Response::Err(error) => {
                debug!("server returned error {:?}: {}", error.code, error.message);
                Err(ClientError::ServerError {
                    code: error.code,
                    message: error.message,
                })
            }
        }
    }

    fn take_request_id(&mut self) -> u64 {
        let request_id = self.next_request_id;
        self.next_request_id = self.next_request_id.wrapping_add(1).max(1);
        request_id
    }
}

fn endpoint_from_paths(paths: &ConfigPaths) -> IpcEndpoint {
    #[cfg(unix)]
    {
        IpcEndpoint::unix_socket(paths.server_socket())
    }

    #[cfg(windows)]
    {
        IpcEndpoint::windows_named_pipe(paths.server_named_pipe())
    }
}

#[cfg(test)]
mod tests {
    use super::{BmuxClient, ServerEvent};
    use bmux_ipc::{IpcEndpoint, SessionRole, SessionSelector, WindowSelector};
    use bmux_server::BmuxServer;
    use std::path::PathBuf;
    use std::time::Duration;
    use tokio::time::sleep;
    use uuid::Uuid;

    #[cfg(unix)]
    #[tokio::test]
    async fn client_can_create_list_attach_detach_and_kill_session() {
        let (server_task, socket_path, endpoint) = start_server().await;
        let mut client = BmuxClient::connect(&endpoint, Duration::from_secs(2), "client-test")
            .await
            .expect("client should connect");

        client.ping().await.expect("ping should pass");
        assert!(
            client
                .server_status()
                .await
                .expect("status should succeed")
                .running
        );

        let session_id = client
            .new_session(Some("dev".to_string()))
            .await
            .expect("new-session should succeed");

        client
            .subscribe_events()
            .await
            .expect("event subscribe should succeed");

        let sessions = client
            .list_sessions()
            .await
            .expect("list-sessions should succeed");
        assert_eq!(sessions.len(), 1);
        assert_eq!(sessions[0].id, session_id);
        assert_eq!(sessions[0].name.as_deref(), Some("dev"));

        let initial_windows = client
            .list_windows(Some(SessionSelector::ById(session_id)))
            .await
            .expect("list windows should succeed");
        assert_eq!(initial_windows.len(), 1);
        let primary_window = initial_windows
            .iter()
            .find(|window| window.active)
            .expect("expected active window")
            .id;

        let secondary_window = client
            .new_window(
                Some(SessionSelector::ById(session_id)),
                Some("secondary".to_string()),
            )
            .await
            .expect("new window should succeed");

        let switched = client
            .switch_window(
                Some(SessionSelector::ById(session_id)),
                WindowSelector::ById(secondary_window),
            )
            .await
            .expect("switch window should succeed");
        assert_eq!(switched, secondary_window);

        let windows_after_switch = client
            .list_windows(Some(SessionSelector::ById(session_id)))
            .await
            .expect("list windows after switch should succeed");
        assert_eq!(windows_after_switch.len(), 2);
        assert!(
            windows_after_switch
                .iter()
                .any(|window| window.id == secondary_window && window.active)
        );

        let removed = client
            .kill_window(
                Some(SessionSelector::ById(session_id)),
                WindowSelector::ById(secondary_window),
            )
            .await
            .expect("kill window should succeed");
        assert_eq!(removed, secondary_window);

        let windows_after_kill = client
            .list_windows(Some(SessionSelector::ById(session_id)))
            .await
            .expect("list windows after kill should succeed");
        assert_eq!(windows_after_kill.len(), 1);
        assert!(
            windows_after_kill
                .iter()
                .any(|window| window.id == primary_window && window.active)
        );

        let grant = client
            .attach_grant(SessionSelector::ByName("dev".to_string()))
            .await
            .expect("attach should succeed");
        let attached_id = client
            .open_attach_stream(&grant)
            .await
            .expect("attach open should succeed");
        assert_eq!(attached_id, session_id);

        let marker = format!("bmux-marker-{}", Uuid::new_v4());
        let command = format!("printf '{marker}\\n'\\n");
        let bytes_sent = client
            .attach_input(session_id, command.as_bytes().to_vec())
            .await
            .expect("attach input should succeed");
        assert_eq!(bytes_sent, command.len());

        let mut collected = Vec::new();
        for _ in 0..20 {
            let output = client
                .attach_output(session_id, 4096)
                .await
                .expect("attach output should succeed");
            if !output.is_empty() {
                collected.extend_from_slice(&output);
                if String::from_utf8_lossy(&collected).contains(&marker) {
                    break;
                }
            }
            sleep(Duration::from_millis(25)).await;
        }
        assert!(
            String::from_utf8_lossy(&collected).contains(&marker),
            "expected marker in PTY output"
        );

        let events = client
            .poll_events(10)
            .await
            .expect("event poll should succeed");
        assert!(events.iter().any(|event| {
            matches!(
                event,
                ServerEvent::ClientAttached { id } if *id == session_id
            )
        }));

        client.detach().await.expect("detach should succeed");

        let killed_id = client
            .kill_session(SessionSelector::ById(session_id))
            .await
            .expect("kill should succeed");
        assert_eq!(killed_id, session_id);
        assert!(
            client
                .list_sessions()
                .await
                .expect("list after kill should succeed")
                .is_empty()
        );

        client.stop_server().await.expect("stop should succeed");
        server_task
            .await
            .expect("server task should join")
            .expect("server should stop cleanly");

        if socket_path.exists() {
            std::fs::remove_file(&socket_path).expect("socket cleanup should succeed");
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn client_follow_and_unfollow_succeeds() {
        let (server_task, socket_path, endpoint) = start_server().await;
        let mut leader = BmuxClient::connect(&endpoint, Duration::from_secs(2), "leader-test")
            .await
            .expect("leader should connect");
        let mut follower = BmuxClient::connect(&endpoint, Duration::from_secs(2), "follower-test")
            .await
            .expect("follower should connect");

        follower
            .subscribe_events()
            .await
            .expect("event subscribe should succeed");

        let session_id = leader
            .new_session(Some("follow-leader".to_string()))
            .await
            .expect("leader session should be created");

        leader
            .attach_grant(SessionSelector::ById(session_id))
            .await
            .expect("leader attach grant should succeed");

        let leader_client_id = leader
            .list_clients()
            .await
            .expect("list clients should succeed")
            .into_iter()
            .find(|client| client.selected_session_id == Some(session_id))
            .map(|client| client.id)
            .expect("leader client id should be listed");

        follower
            .follow_client(leader_client_id, true)
            .await
            .expect("follow should succeed");
        follower.unfollow().await.expect("unfollow should succeed");

        leader.stop_server().await.expect("stop should succeed");
        server_task
            .await
            .expect("server task should join")
            .expect("server should stop cleanly");

        if socket_path.exists() {
            std::fs::remove_file(&socket_path).expect("socket cleanup should succeed");
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn open_attach_stream_info_reports_read_only_for_secondary_attacher() {
        let (server_task, socket_path, endpoint) = start_server().await;
        let mut owner = BmuxClient::connect(&endpoint, Duration::from_secs(2), "owner-test")
            .await
            .expect("owner should connect");
        let mut observer = BmuxClient::connect(&endpoint, Duration::from_secs(2), "observer-test")
            .await
            .expect("observer should connect");

        let session_id = owner
            .new_session(Some("attach-role".to_string()))
            .await
            .expect("session should be created");

        let owner_grant = owner
            .attach_grant(SessionSelector::ById(session_id))
            .await
            .expect("owner grant should succeed");
        let owner_info = owner
            .open_attach_stream_info(&owner_grant)
            .await
            .expect("owner open should succeed");
        assert_eq!(owner_info.session_id, session_id);
        assert!(owner_info.can_write);

        let observer_grant = observer
            .attach_grant(SessionSelector::ById(session_id))
            .await
            .expect("observer grant should succeed");
        let observer_info = observer
            .open_attach_stream_info(&observer_grant)
            .await
            .expect("observer open should succeed");
        assert_eq!(observer_info.session_id, session_id);
        assert!(!observer_info.can_write);

        owner.stop_server().await.expect("stop should succeed");
        server_task
            .await
            .expect("server task should join")
            .expect("server should stop cleanly");

        if socket_path.exists() {
            std::fs::remove_file(&socket_path).expect("socket cleanup should succeed");
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn client_can_grant_list_and_revoke_roles() {
        let (server_task, socket_path, endpoint) = start_server().await;
        let mut owner = BmuxClient::connect(&endpoint, Duration::from_secs(2), "owner-perm")
            .await
            .expect("owner should connect");
        let mut member = BmuxClient::connect(&endpoint, Duration::from_secs(2), "member-perm")
            .await
            .expect("member should connect");

        let session_id = owner
            .new_session(Some("perm-session".to_string()))
            .await
            .expect("session should be created");
        owner
            .subscribe_events()
            .await
            .expect("owner event subscribe should succeed");

        let member_id = member.whoami().await.expect("member whoami should succeed");
        owner
            .grant_role(
                SessionSelector::ById(session_id),
                member_id,
                SessionRole::Writer,
            )
            .await
            .expect("grant role should succeed");

        let permissions = owner
            .list_permissions(SessionSelector::ById(session_id))
            .await
            .expect("list permissions should succeed");
        assert!(
            permissions
                .iter()
                .any(|entry| entry.client_id == member_id && entry.role == SessionRole::Writer)
        );

        owner
            .revoke_role(SessionSelector::ById(session_id), member_id)
            .await
            .expect("revoke role should succeed");

        let events = owner
            .poll_events(20)
            .await
            .expect("poll role events should succeed");
        assert!(events.iter().any(|event| {
            matches!(
                event,
                ServerEvent::RoleChanged {
                    session_id: changed_session,
                    client_id: changed_client,
                    role: SessionRole::Writer,
                    ..
                } if *changed_session == session_id && *changed_client == member_id
            )
        }));
        assert!(events.iter().any(|event| {
            matches!(
                event,
                ServerEvent::RoleChanged {
                    session_id: changed_session,
                    client_id: changed_client,
                    role: SessionRole::Observer,
                    ..
                } if *changed_session == session_id && *changed_client == member_id
            )
        }));

        owner.stop_server().await.expect("stop should succeed");
        server_task
            .await
            .expect("server task should join")
            .expect("server should stop cleanly");

        if socket_path.exists() {
            std::fs::remove_file(&socket_path).expect("socket cleanup should succeed");
        }
    }

    #[cfg(unix)]
    async fn start_server() -> (
        tokio::task::JoinHandle<anyhow::Result<()>>,
        PathBuf,
        IpcEndpoint,
    ) {
        let socket_path = std::env::temp_dir().join(format!("bmux-client-{}.sock", Uuid::new_v4()));
        let endpoint = IpcEndpoint::unix_socket(&socket_path);
        let server = BmuxServer::new(endpoint.clone());
        let server_task = tokio::spawn(async move { server.run().await });
        wait_for_server(&endpoint).await;
        (server_task, socket_path, endpoint)
    }

    #[cfg(unix)]
    async fn wait_for_server(endpoint: &IpcEndpoint) {
        for _ in 0..100 {
            if bmux_ipc::transport::LocalIpcStream::connect(endpoint)
                .await
                .is_ok()
            {
                return;
            }
            sleep(Duration::from_millis(20)).await;
        }
        panic!("server failed to start in time");
    }
}