File size: 47,775 Bytes
1269259
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
// SPF Smart Gateway - Channel Hub: Universal Agent Communication
// Copyright 2026 Joseph Stone - All Rights Reserved
//
// Real-time group messaging for SPF agent networks.
// Central hub (orchestrator) + WebSocket clients (agents) = instant duplex push.
// Role-agnostic: any agent can send/receive regardless of role.
//
// Architecture:
//   Hub node runs ChannelHub + WS server (/ws/channel/{id})
//   Agent nodes connect via WsChannelClient (tokio-tungstenite)
//   MCP tool (spf_channel) is the LLM control interface
//   HTTP API (/api/channel/*) for control plane operations
//
// State: static CHANNEL_HUB global (same pattern as CHAT_ENGINE in mcp.rs)
//        — avoids modifying ServerState, handle_tool_call signature, dispatch::call
//
// Depends on: nothing for CH-1 (core types). CH-2+ adds http.rs routes.

use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;
use axum::extract::ws::{WebSocket, Message};
use futures_util::{SinkExt, StreamExt};

// ============================================================================
// GLOBAL STATE — static Mutex (same pattern as CHAT_ENGINE in mcp.rs)
// ============================================================================

/// Channel hub state — persists across tool calls.
/// Lazy-initialized on first access via get_or_insert_with().
pub static CHANNEL_HUB: Mutex<Option<ChannelHub>> = Mutex::new(None);

/// Monotonic message sequence counter — unique across all channels.
static MSG_SEQ: AtomicU64 = AtomicU64::new(0);

// ============================================================================
// MESSAGE FORMAT
// ============================================================================

/// Message type classification.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum MessageType {
    /// Regular text message from an agent
    Text,
    /// System notification (join, leave, channel created)
    System,
    /// Tool result shared in channel
    ToolResult,
}

/// A single message in a channel.
/// Serialized as JSON for WebSocket transport and HTTP API responses.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChannelMessage {
    /// Unique message ID: "msg-{timestamp_ms}-{seq}"
    pub id: String,
    /// Channel this message belongs to
    pub channel_id: String,
    /// Sender's full pub_key hex
    pub from: String,
    /// Sender's human-readable name
    pub from_name: String,
    /// Message text content
    pub text: String,
    /// Timestamp (RFC3339)
    pub timestamp: String,
    /// Message type
    pub msg_type: MessageType,
}

/// Generate a unique message ID using timestamp + atomic counter.
/// Format: "msg-{timestamp_ms}-{seq}"
fn new_message_id() -> String {
    let ts = chrono::Utc::now().timestamp_millis();
    let seq = MSG_SEQ.fetch_add(1, Ordering::Relaxed);
    format!("msg-{}-{}", ts, seq)
}

// ============================================================================
// PARTICIPANT
// ============================================================================

/// A participant in a channel.
/// The ws_sender is Some when the participant has an active WebSocket connection
/// to the hub. None means they joined via HTTP but aren't listening via WS yet.
#[derive(Debug, Clone)]
pub struct Participant {
    /// Full pub_key hex
    pub key: String,
    /// Human-readable display name
    pub name: String,
    /// WebSocket sender handle — None if not connected via WS.
    /// Uses tokio mpsc so broadcast doesn't block on slow receivers.
    pub ws_sender: Option<tokio::sync::mpsc::UnboundedSender<String>>,
}

// ============================================================================
// CHANNEL
// ============================================================================

/// Maximum messages retained in memory per channel.
const MAX_CHANNEL_HISTORY: usize = 1000;

/// A single communication channel.
/// Holds participants and a bounded message history buffer.
pub struct Channel {
    /// Unique channel identifier
    pub id: String,
    /// Human-readable channel name
    pub name: String,
    /// Who created this channel (pub_key hex)
    pub created_by: String,
    /// Creation timestamp (RFC3339)
    pub created_at: String,
    /// Current participants
    pub participants: Vec<Participant>,
    /// Message history — bounded VecDeque, oldest evicted at MAX_CHANNEL_HISTORY
    pub messages: VecDeque<ChannelMessage>,
}

impl Channel {
    /// Create a new channel.
    pub fn new(id: String, name: String, created_by: String) -> Self {
        Self {
            id,
            name,
            created_by,
            created_at: chrono::Utc::now().to_rfc3339(),
            participants: Vec::new(),
            messages: VecDeque::new(),
        }
    }

    /// Add a participant. Returns false if already present.
    pub fn add_participant(&mut self, key: &str, name: &str) -> bool {
        if self.participants.iter().any(|p| p.key == key) {
            return false;
        }
        self.participants.push(Participant {
            key: key.to_string(),
            name: name.to_string(),
            ws_sender: None,
        });
        true
    }

    /// Remove a participant by key. Returns true if found and removed.
    pub fn remove_participant(&mut self, key: &str) -> bool {
        let before = self.participants.len();
        self.participants.retain(|p| p.key != key);
        self.participants.len() < before
    }

    /// Check if a key is a participant.
    pub fn has_participant(&self, key: &str) -> bool {
        self.participants.iter().any(|p| p.key == key)
    }

    /// Set the WS sender for a participant. Returns false if participant not found.
    pub fn set_ws_sender(
        &mut self,
        key: &str,
        sender: tokio::sync::mpsc::UnboundedSender<String>,
    ) -> bool {
        if let Some(p) = self.participants.iter_mut().find(|p| p.key == key) {
            p.ws_sender = Some(sender);
            true
        } else {
            false
        }
    }

    /// Clear the WS sender for a participant (on disconnect).
    pub fn clear_ws_sender(&mut self, key: &str) {
        if let Some(p) = self.participants.iter_mut().find(|p| p.key == key) {
            p.ws_sender = None;
        }
    }

    /// Add a message to history. Evicts oldest if over MAX_CHANNEL_HISTORY.
    pub fn push_message(&mut self, msg: ChannelMessage) {
        if self.messages.len() >= MAX_CHANNEL_HISTORY {
            self.messages.pop_front();
        }
        self.messages.push_back(msg);
    }

    /// Get last N messages from history.
    pub fn get_history(&self, limit: usize) -> Vec<&ChannelMessage> {
        let start = self.messages.len().saturating_sub(limit);
        self.messages.iter().skip(start).collect()
    }

    /// Broadcast a message to all participants with active WS connections.
    /// Skips the sender (don't echo back). Reaps dead senders on send failure.
    /// Returns the number of participants the message was delivered to.
    pub fn broadcast(&mut self, msg: &ChannelMessage) -> usize {
        let json = match serde_json::to_string(msg) {
            Ok(j) => j,
            Err(_) => return 0,
        };

        let mut delivered = 0;
        let mut dead_keys: Vec<String> = Vec::new();

        for participant in &self.participants {
            // Don't echo back to sender
            if participant.key == msg.from {
                continue;
            }
            if let Some(ref sender) = participant.ws_sender {
                if sender.send(json.clone()).is_ok() {
                    delivered += 1;
                } else {
                    dead_keys.push(participant.key.clone());
                }
            }
        }

        // Reap dead WS senders (not participants — they stay joined)
        for key in &dead_keys {
            self.clear_ws_sender(key);
        }

        delivered
    }

    /// Participant count.
    pub fn participant_count(&self) -> usize {
        self.participants.len()
    }

    /// Count of participants with active WS connections.
    pub fn connected_count(&self) -> usize {
        self.participants.iter().filter(|p| p.ws_sender.is_some()).count()
    }

    /// Message count.
    pub fn message_count(&self) -> usize {
        self.messages.len()
    }
}

// ============================================================================
// CHANNEL HUB — manages all channels
// ============================================================================

/// Central hub managing all communication channels.
/// One instance per node — orchestrator hosts the "real" hub,
/// worker nodes may run a local hub for testing.
pub struct ChannelHub {
    /// All channels indexed by ID
    channels: HashMap<String, Channel>,
    /// Monotonic channel ID counter
    next_id: u64,
}

impl ChannelHub {
    /// Create a new empty hub.
    pub fn new() -> Self {
        Self {
            channels: HashMap::new(),
            next_id: 1,
        }
    }

    /// Create a new channel. Returns the channel ID.
    /// The creator is automatically added as the first participant.
    pub fn create_channel(
        &mut self,
        name: &str,
        created_by: &str,
        created_by_name: &str,
    ) -> String {
        let id = format!("ch-{}", self.next_id);
        self.next_id += 1;

        let mut channel = Channel::new(id.clone(), name.to_string(), created_by.to_string());
        channel.add_participant(created_by, created_by_name);

        // System message: channel created
        let sys_msg = ChannelMessage {
            id: new_message_id(),
            channel_id: id.clone(),
            from: "system".to_string(),
            from_name: "System".to_string(),
            text: format!("Channel '{}' created by {}", name, created_by_name),
            timestamp: chrono::Utc::now().to_rfc3339(),
            msg_type: MessageType::System,
        };
        channel.push_message(sys_msg);

        self.channels.insert(id.clone(), channel);
        id
    }

    /// Join an existing channel. Returns Ok or Err if channel not found.
    pub fn join_channel(
        &mut self,
        channel_id: &str,
        key: &str,
        name: &str,
    ) -> Result<(), String> {
        let channel = self.channels.get_mut(channel_id)
            .ok_or_else(|| format!("Channel not found: {}", channel_id))?;

        if channel.has_participant(key) {
            return Ok(()); // Already joined — idempotent
        }

        channel.add_participant(key, name);

        // System message: participant joined
        let sys_msg = ChannelMessage {
            id: new_message_id(),
            channel_id: channel_id.to_string(),
            from: "system".to_string(),
            from_name: "System".to_string(),
            text: format!("{} joined the channel", name),
            timestamp: chrono::Utc::now().to_rfc3339(),
            msg_type: MessageType::System,
        };
        channel.broadcast(&sys_msg);
        channel.push_message(sys_msg);

        Ok(())
    }

    /// Leave a channel. Returns Ok or Err if channel/participant not found.
    pub fn leave_channel(
        &mut self,
        channel_id: &str,
        key: &str,
    ) -> Result<(), String> {
        let channel = self.channels.get_mut(channel_id)
            .ok_or_else(|| format!("Channel not found: {}", channel_id))?;

        let name = channel.participants.iter()
            .find(|p| p.key == key)
            .map(|p| p.name.clone())
            .unwrap_or_else(|| key[..8.min(key.len())].to_string());

        if !channel.remove_participant(key) {
            return Err(format!("Not a participant in channel {}", channel_id));
        }

        // System message: participant left
        let sys_msg = ChannelMessage {
            id: new_message_id(),
            channel_id: channel_id.to_string(),
            from: "system".to_string(),
            from_name: "System".to_string(),
            text: format!("{} left the channel", name),
            timestamp: chrono::Utc::now().to_rfc3339(),
            msg_type: MessageType::System,
        };
        channel.broadcast(&sys_msg);
        channel.push_message(sys_msg);

        Ok(())
    }

    /// Send a message to a channel. Broadcasts to all connected participants.
    /// Returns the created message or Err if channel not found / not a participant.
    pub fn send_message(
        &mut self,
        channel_id: &str,
        from: &str,
        from_name: &str,
        text: &str,
        msg_type: MessageType,
    ) -> Result<ChannelMessage, String> {
        let channel = self.channels.get_mut(channel_id)
            .ok_or_else(|| format!("Channel not found: {}", channel_id))?;

        if !channel.has_participant(from) {
            return Err(format!("Not a participant in channel {}", channel_id));
        }

        let msg = ChannelMessage {
            id: new_message_id(),
            channel_id: channel_id.to_string(),
            from: from.to_string(),
            from_name: from_name.to_string(),
            text: text.to_string(),
            timestamp: chrono::Utc::now().to_rfc3339(),
            msg_type,
        };

        let delivered = channel.broadcast(&msg);
        channel.push_message(msg.clone());

        eprintln!("[SPF-CHANNEL] {} → #{}: '{}' (delivered to {})",
            from_name, channel_id,
            text.chars().take(50).collect::<String>(),
            delivered);

        Ok(msg)
    }

    /// Get message history for a channel.
    pub fn get_history(
        &self,
        channel_id: &str,
        limit: usize,
    ) -> Result<Vec<&ChannelMessage>, String> {
        let channel = self.channels.get(channel_id)
            .ok_or_else(|| format!("Channel not found: {}", channel_id))?;
        Ok(channel.get_history(limit))
    }

    /// Get a mutable reference to a channel (for WS sender management).
    pub fn get_channel_mut(&mut self, channel_id: &str) -> Option<&mut Channel> {
        self.channels.get_mut(channel_id)
    }

    /// Get an immutable reference to a channel.
    pub fn get_channel(&self, channel_id: &str) -> Option<&Channel> {
        self.channels.get(channel_id)
    }

    /// Check if a channel exists.
    pub fn has_channel(&self, channel_id: &str) -> bool {
        self.channels.contains_key(channel_id)
    }

    /// List all channels with summary info.
    pub fn list_channels(&self) -> Vec<ChannelSummary> {
        self.channels.values().map(|ch| ChannelSummary {
            id: ch.id.clone(),
            name: ch.name.clone(),
            created_by: ch.created_by.clone(),
            created_at: ch.created_at.clone(),
            participants: ch.participants.iter().map(|p| ParticipantInfo {
                key: p.key.clone(),
                name: p.name.clone(),
                connected: p.ws_sender.is_some(),
            }).collect(),
            participant_count: ch.participant_count(),
            connected_count: ch.connected_count(),
            message_count: ch.message_count(),
        }).collect()
    }

    /// Total channel count.
    pub fn channel_count(&self) -> usize {
        self.channels.len()
    }

    /// Remove a channel entirely. Returns true if it existed.
    pub fn remove_channel(&mut self, channel_id: &str) -> bool {
        self.channels.remove(channel_id).is_some()
    }

    /// Register a WS sender for a participant in a channel.
    /// Auto-joins if not already a participant.
    /// Returns Ok or Err if channel not found.
    pub fn register_ws(
        &mut self,
        channel_id: &str,
        key: &str,
        name: &str,
        sender: tokio::sync::mpsc::UnboundedSender<String>,
    ) -> Result<(), String> {
        let channel = self.channels.get_mut(channel_id)
            .ok_or_else(|| format!("Channel not found: {}", channel_id))?;

        // Auto-join if not already a participant
        if !channel.has_participant(key) {
            channel.add_participant(key, name);
            let sys_msg = ChannelMessage {
                id: new_message_id(),
                channel_id: channel_id.to_string(),
                from: "system".to_string(),
                from_name: "System".to_string(),
                text: format!("{} joined the channel", name),
                timestamp: chrono::Utc::now().to_rfc3339(),
                msg_type: MessageType::System,
            };
            channel.broadcast(&sys_msg);
            channel.push_message(sys_msg);
        }

        channel.set_ws_sender(key, sender);
        eprintln!("[SPF-CHANNEL] WS registered: {} ({}) on #{}",
            name, &key[..8.min(key.len())], channel_id);
        Ok(())
    }

    /// Unregister a WS sender for a participant (on WS disconnect).
    /// Does NOT remove the participant — they stay joined.
    pub fn unregister_ws(&mut self, channel_id: &str, key: &str) {
        if let Some(channel) = self.channels.get_mut(channel_id) {
            channel.clear_ws_sender(key);
            eprintln!("[SPF-CHANNEL] WS disconnected: {} on #{}",
                &key[..8.min(key.len())], channel_id);
        }
    }
}

// ============================================================================
// CH-2: WEBSOCKET SERVER — hub-side WS handler for agent connections
// ============================================================================

/// WebSocket message envelope for channel protocol.
/// Agents send these over WS; hub parses and routes to ChannelHub methods.
#[derive(Debug, Deserialize)]
struct WsInbound {
    /// Action: "send", "join", "leave", "history"
    action: String,
    /// Message text (for "send")
    #[serde(default)]
    text: String,
    /// Message type (for "send") — defaults to "text"
    #[serde(default = "default_msg_type")]
    msg_type: MessageType,
    /// History limit (for "history") — defaults to 50
    #[serde(default = "default_history_limit")]
    limit: usize,
}

fn default_msg_type() -> MessageType { MessageType::Text }
fn default_history_limit() -> usize { 50 }

/// WebSocket outbound envelope — hub sends these to agents.
#[derive(Debug, Serialize)]
struct WsOutbound {
    /// "message", "system", "error", "history"
    #[serde(rename = "type")]
    resp_type: String,
    /// Payload — ChannelMessage for message/system, array for history, string for error
    data: serde_json::Value,
}

/// Handle a WebSocket connection for a channel.
/// Called after auth + upgrade in http.rs ws_channel_upgrade handler.
///
/// Protocol:
///   - Hub sends ChannelMessage JSON when other agents post
///   - Agent sends WsInbound JSON to send/join/leave/get history
///   - Hub auto-registers agent's WS sender on connect, unregisters on disconnect
///
/// Uses tokio::select! to simultaneously:
///   1. Forward hub broadcasts (mpsc rx) → WebSocket
///   2. Process agent commands (WebSocket rx) → ChannelHub
pub async fn handle_channel_ws(
    mut socket: WebSocket,
    channel_id: String,
    peer_key: String,
    peer_name: String,
) {
    // Create mpsc channel for hub → this WS connection
    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<String>();

    // Register WS sender in hub (auto-joins if not already participant)
    // NOTE: MutexGuard is !Send — must drop before any .await
    let register_err: Option<String> = {
        let mut guard = CHANNEL_HUB.lock().unwrap();
        let hub = guard.get_or_insert_with(ChannelHub::new);
        match hub.register_ws(&channel_id, &peer_key, &peer_name, tx) {
            Ok(()) => None,
            Err(e) => Some(serde_json::to_string(&WsOutbound {
                resp_type: "error".to_string(),
                data: serde_json::Value::String(e),
            }).unwrap_or_default()),
        }
    }; // guard dropped here
    if let Some(err_json) = register_err {
        let _ = socket.send(Message::Text(err_json.into())).await;
        return;
    }

    eprintln!("[SPF-CHANNEL] WS connected: {} ({}) on #{}",
        peer_name, &peer_key[..8.min(peer_key.len())], channel_id);

    // Send recent history on connect so agent has context
    // NOTE: serialize inside lock, send outside lock (.await requires Send)
    let history_json: Option<String> = {
        let guard = CHANNEL_HUB.lock().unwrap();
        if let Some(hub) = guard.as_ref() {
            if let Ok(history) = hub.get_history(&channel_id, 50) {
                let msgs: Vec<&ChannelMessage> = history;
                let envelope = WsOutbound {
                    resp_type: "history".to_string(),
                    data: serde_json::to_value(&msgs).unwrap_or_default(),
                };
                serde_json::to_string(&envelope).ok()
            } else { None }
        } else { None }
    }; // guard dropped here
    if let Some(json) = history_json {
        let _ = socket.send(Message::Text(json.into())).await;
    }

    // Main loop: select between hub→agent (mpsc) and agent→hub (WS)
    loop {
        tokio::select! {
            // Hub broadcast → forward to agent via WS
            msg = rx.recv() => {
                match msg {
                    Some(text) => {
                        if socket.send(Message::Text(text.into())).await.is_err() {
                            break; // WS send failed — agent disconnected
                        }
                    }
                    None => break, // mpsc closed — hub dropped sender
                }
            }

            // Agent command → process via ChannelHub
            ws_msg = socket.recv() => {
                match ws_msg {
                    Some(Ok(Message::Text(text))) => {
                        let response = process_ws_command(
                            &text, &channel_id, &peer_key, &peer_name
                        );
                        if let Some(resp_json) = response {
                            if socket.send(Message::Text(resp_json.into())).await.is_err() {
                                break;
                            }
                        }
                    }
                    Some(Ok(Message::Ping(data))) => {
                        if socket.send(Message::Pong(data)).await.is_err() {
                            break;
                        }
                    }
                    Some(Ok(Message::Close(_))) | Some(Err(_)) | None => break,
                    _ => {} // Binary, Pong — ignore
                }
            }
        }
    }

    // Cleanup: unregister WS sender (participant stays joined)
    {
        let mut guard = CHANNEL_HUB.lock().unwrap();
        if let Some(hub) = guard.as_mut() {
            hub.unregister_ws(&channel_id, &peer_key);
        }
    }

    eprintln!("[SPF-CHANNEL] WS disconnected: {} ({}) from #{}",
        peer_name, &peer_key[..8.min(peer_key.len())], channel_id);
}

/// Process an inbound WS command from an agent.
/// Returns Some(json_string) if there's a response to send back, None otherwise.
fn process_ws_command(
    text: &str,
    channel_id: &str,
    peer_key: &str,
    peer_name: &str,
) -> Option<String> {
    let cmd: WsInbound = match serde_json::from_str(text) {
        Ok(c) => c,
        Err(e) => {
            return Some(serde_json::to_string(&WsOutbound {
                resp_type: "error".to_string(),
                data: serde_json::Value::String(format!("Invalid JSON: {}", e)),
            }).unwrap_or_default());
        }
    };

    let mut guard = CHANNEL_HUB.lock().unwrap();
    let hub = guard.get_or_insert_with(ChannelHub::new);

    match cmd.action.as_str() {
        "send" => {
            match hub.send_message(channel_id, peer_key, peer_name, &cmd.text, cmd.msg_type) {
                Ok(msg) => Some(serde_json::to_string(&WsOutbound {
                    resp_type: "ack".to_string(),
                    data: serde_json::to_value(&msg).unwrap_or_default(),
                }).unwrap_or_default()),
                Err(e) => Some(serde_json::to_string(&WsOutbound {
                    resp_type: "error".to_string(),
                    data: serde_json::Value::String(e),
                }).unwrap_or_default()),
            }
        }

        "history" => {
            match hub.get_history(channel_id, cmd.limit) {
                Ok(msgs) => Some(serde_json::to_string(&WsOutbound {
                    resp_type: "history".to_string(),
                    data: serde_json::to_value(&msgs).unwrap_or_default(),
                }).unwrap_or_default()),
                Err(e) => Some(serde_json::to_string(&WsOutbound {
                    resp_type: "error".to_string(),
                    data: serde_json::Value::String(e),
                }).unwrap_or_default()),
            }
        }

        "join" => {
            // Already joined via register_ws, but allow explicit re-join
            match hub.join_channel(channel_id, peer_key, peer_name) {
                Ok(()) => Some(serde_json::to_string(&WsOutbound {
                    resp_type: "system".to_string(),
                    data: serde_json::Value::String("Joined".to_string()),
                }).unwrap_or_default()),
                Err(e) => Some(serde_json::to_string(&WsOutbound {
                    resp_type: "error".to_string(),
                    data: serde_json::Value::String(e),
                }).unwrap_or_default()),
            }
        }

        "leave" => {
            match hub.leave_channel(channel_id, peer_key) {
                Ok(()) => Some(serde_json::to_string(&WsOutbound {
                    resp_type: "system".to_string(),
                    data: serde_json::Value::String("Left channel".to_string()),
                }).unwrap_or_default()),
                Err(e) => Some(serde_json::to_string(&WsOutbound {
                    resp_type: "error".to_string(),
                    data: serde_json::Value::String(e),
                }).unwrap_or_default()),
            }
        }

        other => {
            Some(serde_json::to_string(&WsOutbound {
                resp_type: "error".to_string(),
                data: serde_json::Value::String(format!("Unknown action: {}", other)),
            }).unwrap_or_default())
        }
    }
}

// ============================================================================
// CH-3: HTTP API HANDLERS — called from http.rs route handlers
// ============================================================================

/// POST /api/channel/create — Create a new channel.
/// Body: { "name": "ops", "key": "abc...", "name_display": "ALPHA" }
pub fn api_create_channel(name: &str, key: &str, display_name: &str) -> serde_json::Value {
    let mut guard = CHANNEL_HUB.lock().unwrap();
    let hub = guard.get_or_insert_with(ChannelHub::new);
    let id = hub.create_channel(name, key, display_name);
    serde_json::json!({
        "ok": true,
        "channel_id": id,
        "name": name,
        "created_by": display_name
    })
}

/// POST /api/channel/join — Join an existing channel.
/// Body: { "channel_id": "ch-1", "key": "abc...", "name": "BRAVO" }
pub fn api_join_channel(channel_id: &str, key: &str, name: &str) -> serde_json::Value {
    let mut guard = CHANNEL_HUB.lock().unwrap();
    let hub = guard.get_or_insert_with(ChannelHub::new);
    match hub.join_channel(channel_id, key, name) {
        Ok(()) => serde_json::json!({ "ok": true, "channel_id": channel_id }),
        Err(e) => serde_json::json!({ "ok": false, "error": e }),
    }
}

/// POST /api/channel/leave — Leave a channel.
/// Body: { "channel_id": "ch-1", "key": "abc..." }
pub fn api_leave_channel(channel_id: &str, key: &str) -> serde_json::Value {
    let mut guard = CHANNEL_HUB.lock().unwrap();
    let hub = guard.get_or_insert_with(ChannelHub::new);
    match hub.leave_channel(channel_id, key) {
        Ok(()) => serde_json::json!({ "ok": true, "channel_id": channel_id }),
        Err(e) => serde_json::json!({ "ok": false, "error": e }),
    }
}

/// POST /api/channel/send — Send a message.
/// Body: { "channel_id": "ch-1", "key": "abc...", "name": "ALPHA", "text": "hello", "msg_type": "text" }
pub fn api_send_message(
    channel_id: &str,
    key: &str,
    name: &str,
    text: &str,
    msg_type: MessageType,
) -> serde_json::Value {
    let mut guard = CHANNEL_HUB.lock().unwrap();
    let hub = guard.get_or_insert_with(ChannelHub::new);
    match hub.send_message(channel_id, key, name, text, msg_type) {
        Ok(msg) => serde_json::json!({
            "ok": true,
            "message": msg
        }),
        Err(e) => serde_json::json!({ "ok": false, "error": e }),
    }
}

/// GET /api/channel/list — List all channels.
pub fn api_list_channels() -> serde_json::Value {
    let guard = CHANNEL_HUB.lock().unwrap();
    match guard.as_ref() {
        Some(hub) => serde_json::json!({
            "ok": true,
            "channels": hub.list_channels(),
            "count": hub.channel_count()
        }),
        None => serde_json::json!({
            "ok": true,
            "channels": [],
            "count": 0
        }),
    }
}

/// GET /api/channel/:id/history — Get channel message history.
pub fn api_channel_history(channel_id: &str, limit: usize) -> serde_json::Value {
    let guard = CHANNEL_HUB.lock().unwrap();
    match guard.as_ref() {
        Some(hub) => match hub.get_history(channel_id, limit) {
            Ok(msgs) => serde_json::json!({
                "ok": true,
                "channel_id": channel_id,
                "messages": msgs,
                "count": msgs.len()
            }),
            Err(e) => serde_json::json!({ "ok": false, "error": e }),
        },
        None => serde_json::json!({ "ok": false, "error": "No channels exist" }),
    }
}

// ============================================================================
// CH-4: WEBSOCKET CLIENT — agent-side WS connection to hub
// ============================================================================

/// Message received from the hub via WebSocket.
/// Buffered in VecDeque for MCP tool polling (spf_channel listen action).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InboundMessage {
    /// Envelope type from hub: "message", "system", "history", "ack", "error"
    #[serde(rename = "type")]
    pub msg_type: String,
    /// Payload — varies by type
    pub data: serde_json::Value,
}

/// A connected WS client to a remote channel hub.
/// One per channel connection. Holds:
///   - Background task handle (reads WS, buffers messages)
///   - mpsc sender to push outbound messages through WS
///   - VecDeque buffer of inbound messages for MCP polling
pub struct WsClientConnection {
    /// Channel ID on the hub
    pub channel_id: String,
    /// Hub URL (for display/reconnect)
    pub hub_url: String,
    /// Sender: MCP tool → background task → WS → hub
    pub outbound_tx: tokio::sync::mpsc::UnboundedSender<String>,
    /// Inbound message buffer: background task populates, MCP tool drains
    pub inbound: std::sync::Arc<std::sync::Mutex<VecDeque<InboundMessage>>>,
    /// Background task handle — abort on disconnect
    pub task_handle: tokio::task::JoinHandle<()>,
    /// Connected flag
    pub connected: std::sync::Arc<std::sync::atomic::AtomicBool>,
}

/// Global WS client manager — keyed by "hub_url#channel_id".
/// MCP tool accesses this to send/receive/connect/disconnect.
pub static WS_CLIENTS: Mutex<Option<HashMap<String, WsClientConnection>>> = Mutex::new(None);

/// Build a client key from hub URL and channel ID.
fn client_key(hub_url: &str, channel_id: &str) -> String {
    format!("{}#{}", hub_url, channel_id)
}

/// Connect to a remote channel hub via WebSocket.
/// Spawns a background tokio task that:
///   1. Reads from WS → buffers into inbound VecDeque
///   2. Reads from outbound mpsc → writes to WS
///
/// Returns Ok(client_key) on success.
/// Requires a tokio runtime handle (from ServerState.tokio_handle).
pub fn ws_client_connect(
    handle: &tokio::runtime::Handle,
    hub_url: &str,
    channel_id: &str,
    api_key: &str,
    peer_key: &str,
    peer_name: &str,
) -> Result<String, String> {
    let key = client_key(hub_url, channel_id);

    // Check if already connected
    {
        let guard = WS_CLIENTS.lock().unwrap();
        if let Some(clients) = guard.as_ref() {
            if let Some(conn) = clients.get(&key) {
                if conn.connected.load(std::sync::atomic::Ordering::Relaxed) {
                    return Ok(key);
                }
            }
        }
    }

    // Build WS URL: http→ws, https→wss
    let ws_url = format!(
        "{}/ws/channel/{}?key={}&name={}",
        hub_url.replace("http://", "ws://").replace("https://", "wss://"),
        channel_id,
        peer_key,
        urlencoding(peer_name),
    );

    let (outbound_tx, mut outbound_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
    let inbound_buf: std::sync::Arc<std::sync::Mutex<VecDeque<InboundMessage>>>
        = std::sync::Arc::new(std::sync::Mutex::new(VecDeque::new()));
    let connected = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));

    let inbound_clone = inbound_buf.clone();
    let connected_clone = connected.clone();
    let api_key_owned = api_key.to_string();
    let ws_url_owned = ws_url.clone();
    let key_clone = key.clone();
    let hub_url_owned = hub_url.to_string();
    let channel_id_owned = channel_id.to_string();

    const MAX_INBOUND_BUFFER: usize = 500;

    // Spawn background WS task on the tokio runtime
    let task_handle = handle.spawn(async move {
        // Build request with auth header
        let request = match http::Request::builder()
            .uri(&ws_url_owned)
            .header("x-spf-key", &api_key_owned)
            .header("sec-websocket-key", tokio_tungstenite::tungstenite::handshake::client::generate_key())
            .header("sec-websocket-version", "13")
            .header("connection", "Upgrade")
            .header("upgrade", "websocket")
            .header("host", extract_host(&hub_url_owned))
            .body(())
        {
            Ok(r) => r,
            Err(e) => {
                eprintln!("[SPF-CHANNEL-CLIENT] Request build error: {}", e);
                return;
            }
        };

        let ws_stream = match tokio_tungstenite::connect_async(request).await {
            Ok((stream, _)) => stream,
            Err(e) => {
                eprintln!("[SPF-CHANNEL-CLIENT] Connect failed to {}: {}", ws_url_owned, e);
                return;
            }
        };

        connected_clone.store(true, std::sync::atomic::Ordering::Relaxed);
        eprintln!("[SPF-CHANNEL-CLIENT] Connected to {} #{}", hub_url_owned, channel_id_owned);

        let (mut ws_sink, mut ws_stream_rx) = ws_stream.split();

        loop {
            tokio::select! {
                // Hub → agent: read from WS, buffer for MCP polling
                ws_msg = ws_stream_rx.next() => {
                    match ws_msg {
                        Some(Ok(tokio_tungstenite::tungstenite::Message::Text(text))) => {
                            if let Ok(msg) = serde_json::from_str::<InboundMessage>(&text) {
                                let mut buf = inbound_clone.lock().unwrap();
                                if buf.len() >= MAX_INBOUND_BUFFER {
                                    buf.pop_front(); // evict oldest
                                }
                                buf.push_back(msg);
                            }
                        }
                        Some(Ok(tokio_tungstenite::tungstenite::Message::Close(_))) => break,
                        Some(Err(e)) => {
                            eprintln!("[SPF-CHANNEL-CLIENT] WS error: {}", e);
                            break;
                        }
                        None => break,
                        _ => {} // Binary, Ping, Pong handled by tungstenite
                    }
                }

                // Agent → hub: forward outbound messages through WS
                out_msg = outbound_rx.recv() => {
                    match out_msg {
                        Some(text) => {
                            if ws_sink.send(tokio_tungstenite::tungstenite::Message::Text(text.into())).await.is_err() {
                                break;
                            }
                        }
                        None => break, // outbound channel closed
                    }
                }
            }
        }

        connected_clone.store(false, std::sync::atomic::Ordering::Relaxed);
        eprintln!("[SPF-CHANNEL-CLIENT] Disconnected from {} #{}", hub_url_owned, channel_id_owned);

        // Cleanup from global map
        let mut guard = WS_CLIENTS.lock().unwrap();
        if let Some(clients) = guard.as_mut() {
            clients.remove(&key_clone);
        }
    });

    // Register in global map
    let conn = WsClientConnection {
        channel_id: channel_id.to_string(),
        hub_url: hub_url.to_string(),
        outbound_tx,
        inbound: inbound_buf,
        task_handle,
        connected,
    };

    let mut guard = WS_CLIENTS.lock().unwrap();
    let clients = guard.get_or_insert_with(HashMap::new);
    clients.insert(key.clone(), conn);

    Ok(key)
}

/// Send a message through a connected WS client.
pub fn ws_client_send(
    client_key: &str,
    text: &str,
    msg_type: &str,
) -> Result<(), String> {
    let guard = WS_CLIENTS.lock().unwrap();
    let clients = guard.as_ref().ok_or("No client connections")?;
    let conn = clients.get(client_key).ok_or("Not connected")?;

    if !conn.connected.load(std::sync::atomic::Ordering::Relaxed) {
        return Err("Connection lost".to_string());
    }

    let cmd = serde_json::json!({
        "action": "send",
        "text": text,
        "msg_type": msg_type,
    });
    conn.outbound_tx.send(cmd.to_string())
        .map_err(|e| format!("Send failed: {}", e))
}

/// Drain inbound message buffer — returns all buffered messages.
/// Called by MCP tool `spf_channel listen` action.
pub fn ws_client_drain(client_key: &str) -> Result<Vec<InboundMessage>, String> {
    let guard = WS_CLIENTS.lock().unwrap();
    let clients = guard.as_ref().ok_or("No client connections")?;
    let conn = clients.get(client_key).ok_or("Not connected")?;

    let mut buf = conn.inbound.lock().unwrap();
    let messages: Vec<InboundMessage> = buf.drain(..).collect();
    Ok(messages)
}

/// Disconnect a WS client.
pub fn ws_client_disconnect(client_key: &str) -> Result<(), String> {
    let mut guard = WS_CLIENTS.lock().unwrap();
    let clients = guard.as_mut().ok_or("No client connections")?;

    if let Some(conn) = clients.remove(client_key) {
        conn.task_handle.abort();
        Ok(())
    } else {
        Err("Not connected".to_string())
    }
}

/// List all active WS client connections.
pub fn ws_client_list() -> Vec<serde_json::Value> {
    let guard = WS_CLIENTS.lock().unwrap();
    match guard.as_ref() {
        Some(clients) => clients.iter().map(|(key, conn)| {
            serde_json::json!({
                "key": key,
                "channel_id": conn.channel_id,
                "hub_url": conn.hub_url,
                "connected": conn.connected.load(std::sync::atomic::Ordering::Relaxed),
                "buffered": conn.inbound.lock().unwrap().len(),
            })
        }).collect(),
        None => Vec::new(),
    }
}

/// Simple URL-encode for query params (spaces, special chars).
fn urlencoding(s: &str) -> String {
    s.chars().map(|c| match c {
        'A'..='Z' | 'a'..='z' | '0'..='9' | '-' | '_' | '.' | '~' => c.to_string(),
        ' ' => "%20".to_string(),
        _ => format!("%{:02X}", c as u32),
    }).collect()
}

/// Extract host from URL for WebSocket Host header.
fn extract_host(url: &str) -> String {
    url.trim_start_matches("http://")
       .trim_start_matches("https://")
       .split('/')
       .next()
       .unwrap_or("localhost")
       .to_string()
}

// ============================================================================
// SUMMARY TYPES — for API responses
// ============================================================================

/// Channel summary for list/status responses.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChannelSummary {
    pub id: String,
    pub name: String,
    pub created_by: String,
    pub created_at: String,
    pub participants: Vec<ParticipantInfo>,
    pub participant_count: usize,
    pub connected_count: usize,
    pub message_count: usize,
}

/// Participant info for API responses.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParticipantInfo {
    pub key: String,
    pub name: String,
    pub connected: bool,
}

// ============================================================================
// TESTS
// ============================================================================

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

    #[test]
    fn test_message_id_unique() {
        let id1 = new_message_id();
        let id2 = new_message_id();
        assert_ne!(id1, id2);
        assert!(id1.starts_with("msg-"));
    }

    #[test]
    fn test_create_channel() {
        let mut hub = ChannelHub::new();
        let id = hub.create_channel("ops", "key_aaa", "ALPHA");
        assert_eq!(id, "ch-1");
        assert!(hub.has_channel("ch-1"));
        assert_eq!(hub.channel_count(), 1);

        let ch = hub.get_channel("ch-1").unwrap();
        assert_eq!(ch.name, "ops");
        assert_eq!(ch.created_by, "key_aaa");
        assert_eq!(ch.participant_count(), 1);
        assert!(ch.has_participant("key_aaa"));
        assert_eq!(ch.message_count(), 1); // system "created" msg
    }

    #[test]
    fn test_join_leave() {
        let mut hub = ChannelHub::new();
        let id = hub.create_channel("ops", "key_aaa", "ALPHA");

        hub.join_channel(&id, "key_bbb", "BRAVO").unwrap();
        let ch = hub.get_channel(&id).unwrap();
        assert_eq!(ch.participant_count(), 2);
        assert!(ch.has_participant("key_bbb"));

        // Idempotent join
        hub.join_channel(&id, "key_bbb", "BRAVO").unwrap();
        assert_eq!(hub.get_channel(&id).unwrap().participant_count(), 2);

        hub.leave_channel(&id, "key_bbb").unwrap();
        assert_eq!(hub.get_channel(&id).unwrap().participant_count(), 1);
        assert!(!hub.get_channel(&id).unwrap().has_participant("key_bbb"));
    }

    #[test]
    fn test_join_nonexistent() {
        let mut hub = ChannelHub::new();
        let result = hub.join_channel("ch-999", "key_aaa", "ALPHA");
        assert!(result.is_err());
    }

    #[test]
    fn test_send_message() {
        let mut hub = ChannelHub::new();
        let id = hub.create_channel("ops", "key_aaa", "ALPHA");
        hub.join_channel(&id, "key_bbb", "BRAVO").unwrap();

        let msg = hub.send_message(&id, "key_aaa", "ALPHA", "hello team", MessageType::Text).unwrap();
        assert_eq!(msg.channel_id, id);
        assert_eq!(msg.from, "key_aaa");
        assert_eq!(msg.text, "hello team");
        assert_eq!(msg.msg_type, MessageType::Text);

        // 1 system (created) + 1 system (bravo joined) + 1 text
        assert_eq!(hub.get_channel(&id).unwrap().message_count(), 3);
    }

    #[test]
    fn test_send_not_participant() {
        let mut hub = ChannelHub::new();
        let id = hub.create_channel("ops", "key_aaa", "ALPHA");
        let result = hub.send_message(&id, "key_zzz", "STRANGER", "hi", MessageType::Text);
        assert!(result.is_err());
    }

    #[test]
    fn test_history_limit() {
        let mut hub = ChannelHub::new();
        let id = hub.create_channel("ops", "key_aaa", "ALPHA");

        for i in 0..10 {
            hub.send_message(&id, "key_aaa", "ALPHA", &format!("msg {}", i), MessageType::Text).unwrap();
        }

        let history = hub.get_history(&id, 3).unwrap();
        assert_eq!(history.len(), 3);
        assert!(history[2].text.contains("msg 9"));
    }

    #[test]
    fn test_eviction() {
        let mut channel = Channel::new("test".to_string(), "Test".to_string(), "key".to_string());
        for i in 0..(MAX_CHANNEL_HISTORY + 10) {
            channel.push_message(ChannelMessage {
                id: format!("msg-{}", i),
                channel_id: "test".to_string(),
                from: "key".to_string(),
                from_name: "Test".to_string(),
                text: format!("message {}", i),
                timestamp: "2026-04-07T00:00:00Z".to_string(),
                msg_type: MessageType::Text,
            });
        }
        assert_eq!(channel.message_count(), MAX_CHANNEL_HISTORY);
        assert!(channel.messages.front().unwrap().text.contains("message 10"));
    }

    #[test]
    fn test_list_channels() {
        let mut hub = ChannelHub::new();
        hub.create_channel("ops", "key_aaa", "ALPHA");
        hub.create_channel("research", "key_bbb", "BRAVO");

        let list = hub.list_channels();
        assert_eq!(list.len(), 2);
        let names: Vec<&str> = list.iter().map(|s| s.name.as_str()).collect();
        assert!(names.contains(&"ops"));
        assert!(names.contains(&"research"));
    }

    #[test]
    fn test_remove_channel() {
        let mut hub = ChannelHub::new();
        let id = hub.create_channel("temp", "key_aaa", "ALPHA");
        assert!(hub.remove_channel(&id));
        assert!(!hub.has_channel(&id));
        assert!(!hub.remove_channel(&id));
    }

    #[test]
    fn test_ids_increment() {
        let mut hub = ChannelHub::new();
        assert_eq!(hub.create_channel("a", "k", "n"), "ch-1");
        assert_eq!(hub.create_channel("b", "k", "n"), "ch-2");
        assert_eq!(hub.create_channel("c", "k", "n"), "ch-3");
    }

    #[test]
    fn test_register_ws_auto_joins() {
        let mut hub = ChannelHub::new();
        let id = hub.create_channel("ops", "key_aaa", "ALPHA");

        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        hub.register_ws(&id, "key_bbb", "BRAVO", tx).unwrap();

        let ch = hub.get_channel(&id).unwrap();
        assert_eq!(ch.participant_count(), 2);
        assert!(ch.has_participant("key_bbb"));
        assert_eq!(ch.connected_count(), 1);
    }

    #[test]
    fn test_unregister_ws_keeps_participant() {
        let mut hub = ChannelHub::new();
        let id = hub.create_channel("ops", "key_aaa", "ALPHA");

        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        hub.register_ws(&id, "key_aaa", "ALPHA", tx).unwrap();
        assert_eq!(hub.get_channel(&id).unwrap().connected_count(), 1);

        hub.unregister_ws(&id, "key_aaa");
        let ch = hub.get_channel(&id).unwrap();
        assert_eq!(ch.connected_count(), 0);
        assert!(ch.has_participant("key_aaa"));
    }

    #[test]
    fn test_broadcast_skips_sender() {
        let mut hub = ChannelHub::new();
        let id = hub.create_channel("ops", "key_aaa", "ALPHA");

        let (tx_a, mut rx_a) = tokio::sync::mpsc::unbounded_channel();
        let (tx_b, mut rx_b) = tokio::sync::mpsc::unbounded_channel();

        hub.register_ws(&id, "key_aaa", "ALPHA", tx_a).unwrap();
        hub.register_ws(&id, "key_bbb", "BRAVO", tx_b).unwrap();

        // ALPHA sends — should NOT echo to ALPHA, SHOULD deliver to BRAVO
        hub.send_message(&id, "key_aaa", "ALPHA", "test", MessageType::Text).unwrap();

        // BRAVO should have received
        assert!(rx_b.try_recv().is_ok());
        // ALPHA should NOT have received (no echo)
        assert!(rx_a.try_recv().is_err());
    }
}