// 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> = 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>, } // ============================================================================ // 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, /// Message history — bounded VecDeque, oldest evicted at MAX_CHANNEL_HISTORY pub messages: VecDeque, } 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, ) -> 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 = 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, /// 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 { 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::(), delivered); Ok(msg) } /// Get message history for a channel. pub fn get_history( &self, channel_id: &str, limit: usize, ) -> Result, 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 { 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, ) -> 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::(); // Register WS sender in hub (auto-joins if not already participant) // NOTE: MutexGuard is !Send — must drop before any .await let register_err: Option = { 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 = { 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 { 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, /// Inbound message buffer: background task populates, MCP tool drains pub inbound: std::sync::Arc>>, /// Background task handle — abort on disconnect pub task_handle: tokio::task::JoinHandle<()>, /// Connected flag pub connected: std::sync::Arc, } /// Global WS client manager — keyed by "hub_url#channel_id". /// MCP tool accesses this to send/receive/connect/disconnect. pub static WS_CLIENTS: Mutex>> = 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 { 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::(); let inbound_buf: std::sync::Arc>> = 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::(&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, 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 = 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 { 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, 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()); } }