use desktop_protocol::{ConnectionState, TransportKind}; use secrecy::SecretString; use serde::Serialize; use tokio::sync::{Mutex, mpsc}; use super::{ AstrBotClient, AstrBotClientConfig, BoundGatewayEvent, GatewayClient, GatewayClientConfig, GatewayError, SlotKind, }; #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct SlotRuntimeSnapshot { pub slot: SlotKind, pub profile_id: Option, pub transport: Option, pub state: ConnectionState, pub server_instance_id: Option, pub active_session_id: Option, pub last_error: Option, } #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct ConnectionRuntimeStatus { pub companion: SlotRuntimeSnapshot, pub operations: SlotRuntimeSnapshot, } #[derive(Debug, Clone)] pub struct SlotActivationRequest { pub profile_id: String, pub slot: SlotKind, pub base_url: String, pub transport: TransportKind, pub api_key: Option, pub bearer_token: Option, pub remote_username: Option, pub session_id: Option, pub expected_server_instance_id: Option, } enum ActiveClient { Desktop(GatewayClient), AstrBot(AstrBotClient), } struct SlotRuntime { snapshot: SlotRuntimeSnapshot, client: Option, } impl SlotRuntime { fn empty(slot: SlotKind) -> Self { Self { snapshot: SlotRuntimeSnapshot { slot, profile_id: None, transport: None, state: ConnectionState::Disconnected, server_instance_id: None, active_session_id: None, last_error: None, }, client: None, } } } /// In-process dual-slot connection runtime. /// /// Network activation is explicit and Rust-owned. React never receives secrets. pub struct DualSlotRuntime { inner: Mutex, event_tx: mpsc::Sender, event_rx: Mutex>, } struct DualSlotRuntimeInner { companion: SlotRuntime, operations: SlotRuntime, } #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct RuntimeCommandError { pub code: &'static str, pub message: &'static str, } impl std::fmt::Display for RuntimeCommandError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.message) } } impl std::error::Error for RuntimeCommandError {} impl RuntimeCommandError { pub fn validation(message: &'static str) -> Self { Self { code: "validationFailed", message, } } pub fn unavailable(message: &'static str) -> Self { Self { code: "runtimeUnavailable", message, } } } impl DualSlotRuntime { pub fn new() -> Self { let (event_tx, event_rx) = mpsc::channel(256); Self { inner: Mutex::new(DualSlotRuntimeInner { companion: SlotRuntime::empty(SlotKind::Companion), operations: SlotRuntime::empty(SlotKind::Operations), }), event_tx, event_rx: Mutex::new(event_rx), } } pub async fn status(&self) -> ConnectionRuntimeStatus { let guard = self.inner.lock().await; ConnectionRuntimeStatus { companion: guard.companion.snapshot.clone(), operations: guard.operations.snapshot.clone(), } } pub async fn try_recv_event(&self) -> Option { let mut rx = self.event_rx.lock().await; rx.try_recv().ok() } pub async fn drain_events(&self, limit: usize) -> Vec { let limit = limit.clamp(1, 256); let mut rx = self.event_rx.lock().await; let mut events = Vec::with_capacity(limit); while events.len() < limit { match rx.try_recv() { Ok(event) => events.push(event), Err(_) => break, } } events } pub async fn deactivate_slot(&self, slot: SlotKind) -> Result<(), RuntimeCommandError> { let mut guard = self.inner.lock().await; let runtime = slot_mut(&mut guard, slot); *runtime = SlotRuntime::empty(slot); Ok(()) } pub async fn activate_slot( &self, request: SlotActivationRequest, ) -> Result { if request.profile_id.trim().is_empty() { return Err(RuntimeCommandError::validation( "profile_id is required for activation.", )); } if request.base_url.trim().is_empty() { return Err(RuntimeCommandError::validation( "base_url is required for activation.", )); } let mut guard = self.inner.lock().await; let runtime = slot_mut(&mut guard, request.slot); *runtime = SlotRuntime { snapshot: SlotRuntimeSnapshot { slot: request.slot, profile_id: Some(request.profile_id.clone()), transport: Some(request.transport), state: ConnectionState::Connecting, server_instance_id: None, active_session_id: request.session_id.clone(), last_error: None, }, client: None, }; match request.transport { TransportKind::DesktopV1 => { let expected = request .expected_server_instance_id .clone() .filter(|value| !value.trim().is_empty()) .ok_or_else(|| { RuntimeCommandError::validation( "Desktop gateway activation requires expected_server_instance_id.", ) })?; let client = GatewayClient::new(GatewayClientConfig { profile_id: request.profile_id.clone(), slot: request.slot, base_url: request.base_url.clone(), expected_server_instance_id: expected.clone(), bearer_token: request.bearer_token.clone(), }) .map_err(|_| { RuntimeCommandError::unavailable("Desktop gateway client failed to start.") })?; match client.health().await { Ok(_) => { runtime.snapshot.state = ConnectionState::Connected; runtime.snapshot.server_instance_id = Some(expected); runtime.client = Some(ActiveClient::Desktop(client)); } Err(GatewayError::HttpStatus(status)) if status.as_u16() == 401 => { runtime.snapshot.state = ConnectionState::AuthExpired; runtime.snapshot.last_error = Some("Desktop gateway authentication failed.".into()); return Err(RuntimeCommandError::unavailable( "Desktop gateway authentication failed.", )); } Err(_) => { runtime.snapshot.state = ConnectionState::ServerUnavailable; runtime.snapshot.last_error = Some("Desktop gateway health check failed.".into()); return Err(RuntimeCommandError::unavailable( "Desktop gateway health check failed.", )); } } } TransportKind::AstrBotOpenApi => { let api_key = request.api_key.clone().ok_or_else(|| { RuntimeCommandError::validation("AstrBot activation requires an API key.") })?; let remote_username = request .remote_username .clone() .filter(|value| !value.trim().is_empty()) .ok_or_else(|| { RuntimeCommandError::validation( "AstrBot activation requires remote_username.", ) })?; let client = AstrBotClient::new(AstrBotClientConfig { profile_id: request.profile_id.clone(), slot: request.slot, base_url: request.base_url.clone(), api_key, remote_username, session_id: request.session_id.clone(), expected_server_instance_id: request.expected_server_instance_id.clone(), }) .map_err(|_| RuntimeCommandError::unavailable("AstrBot client failed to start."))?; match client.probe().await { Ok(_) => { runtime.snapshot.state = ConnectionState::Connected; runtime.snapshot.server_instance_id = Some(client.server_instance_id_blocking()); runtime.client = Some(ActiveClient::AstrBot(client)); } Err(error) => { runtime.snapshot.state = match error { super::AstrBotClientError::HttpStatus(status) if status.as_u16() == 401 || status.as_u16() == 403 => { ConnectionState::AuthExpired } _ => ConnectionState::ServerUnavailable, }; runtime.snapshot.last_error = Some("AstrBot probe failed.".into()); return Err(RuntimeCommandError::unavailable("AstrBot probe failed.")); } } } } Ok(runtime.snapshot.clone()) } pub async fn send_slot_message( &self, slot: SlotKind, message: String, ) -> Result { if message.trim().is_empty() { return Err(RuntimeCommandError::validation( "message must not be empty.", )); } // Take the client out so we can await without holding the mutex across network IO. let (client, profile_id, transport, server_instance_id, session_id) = { let mut guard = self.inner.lock().await; let runtime = slot_mut(&mut guard, slot); let client = runtime.client.take().ok_or_else(|| { RuntimeCommandError::unavailable("The selected slot is not connected.") })?; runtime.snapshot.state = ConnectionState::Syncing; ( client, runtime.snapshot.profile_id.clone(), runtime.snapshot.transport, runtime.snapshot.server_instance_id.clone(), runtime.snapshot.active_session_id.clone(), ) }; let send_result = match client { ActiveClient::Desktop(client) => { // Desktop mock path remains stream-oriented; chat POST is a later wire-up. let restored = ActiveClient::Desktop(client); Err(( restored, RuntimeCommandError::unavailable( "Desktop mock chat send is not activated in this runtime path yet.", ), )) } ActiveClient::AstrBot(client) => { let cancel = tokio_util::sync::CancellationToken::new(); match client .send_chat_stream(&message, &self.event_tx, &cancel) .await { Ok(session) => Ok((ActiveClient::AstrBot(client), session)), Err(_) => Err(( ActiveClient::AstrBot(client), RuntimeCommandError::unavailable("AstrBot chat send failed."), )), } } }; let mut guard = self.inner.lock().await; let runtime = slot_mut(&mut guard, slot); match send_result { Ok((client, session)) => { runtime.client = Some(client); runtime.snapshot.profile_id = profile_id; runtime.snapshot.transport = transport; runtime.snapshot.server_instance_id = server_instance_id; runtime.snapshot.active_session_id = session.or(session_id); runtime.snapshot.state = ConnectionState::Connected; runtime.snapshot.last_error = None; Ok(runtime.snapshot.clone()) } Err((client, error)) => { runtime.client = Some(client); runtime.snapshot.profile_id = profile_id; runtime.snapshot.transport = transport; runtime.snapshot.server_instance_id = server_instance_id; runtime.snapshot.active_session_id = session_id; runtime.snapshot.state = ConnectionState::ServerUnavailable; runtime.snapshot.last_error = Some(error.message.to_owned()); Err(error) } } } } impl Default for DualSlotRuntime { fn default() -> Self { Self::new() } } fn slot_mut(inner: &mut DualSlotRuntimeInner, slot: SlotKind) -> &mut SlotRuntime { match slot { SlotKind::Companion => &mut inner.companion, SlotKind::Operations => &mut inner.operations, } } #[cfg(test)] mod tests { use super::*; #[tokio::test] async fn rejects_astrbot_activation_without_username_or_key() { let runtime = DualSlotRuntime::new(); let error = runtime .activate_slot(SlotActivationRequest { profile_id: "11111111-1111-1111-1111-111111111111".into(), slot: SlotKind::Companion, base_url: "http://127.0.0.1:9".into(), transport: TransportKind::AstrBotOpenApi, api_key: None, bearer_token: None, remote_username: None, session_id: None, expected_server_instance_id: None, }) .await .expect_err("should fail"); assert_eq!(error.code, "validationFailed"); } #[tokio::test] async fn status_starts_disconnected() { let runtime = DualSlotRuntime::new(); let status = runtime.status().await; assert_eq!(status.companion.state, ConnectionState::Disconnected); assert_eq!(status.operations.state, ConnectionState::Disconnected); } }