AstrBot-Desktop/src-tauri/src/networking/runtime.rs

618 行
23 KiB
Rust

use desktop_protocol::{
AstrBotAttachment, AstrBotCapabilitySnapshot, ConnectionState, TransportKind,
};
use secrecy::SecretString;
use serde::Serialize;
use std::time::Duration;
use tokio::sync::{Mutex, mpsc};
use super::{
AstrBotClient, AstrBotClientConfig, AstrBotClientError, BoundGatewayEvent, GatewayClient,
GatewayClientConfig, GatewayError, SlotKind,
};
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SlotRuntimeSnapshot {
pub slot: SlotKind,
pub profile_id: Option<String>,
pub transport: Option<TransportKind>,
pub state: ConnectionState,
pub server_instance_id: Option<String>,
pub active_session_id: Option<String>,
pub last_error: Option<String>,
}
#[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<SecretString>,
pub bearer_token: Option<SecretString>,
pub remote_username: Option<String>,
pub remote_display_name: Option<String>,
pub authentication_type: desktop_protocol::AuthenticationType,
pub session_id: Option<String>,
pub expected_server_instance_id: Option<String>,
}
enum ActiveClient {
Desktop(GatewayClient),
AstrBot(AstrBotClient),
}
struct SlotRuntime {
snapshot: SlotRuntimeSnapshot,
client: Option<ActiveClient>,
cancellation: Option<tokio_util::sync::CancellationToken>,
}
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,
cancellation: None,
}
}
}
/// In-process dual-slot connection runtime.
///
/// Network activation is explicit and Rust-owned. React never receives secrets.
pub struct DualSlotRuntime {
inner: Mutex<DualSlotRuntimeInner>,
event_tx: mpsc::Sender<BoundGatewayEvent>,
event_rx: Mutex<mpsc::Receiver<BoundGatewayEvent>>,
}
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<BoundGatewayEvent> {
let mut rx = self.event_rx.lock().await;
rx.try_recv().ok()
}
pub async fn drain_events(&self, limit: usize) -> Vec<BoundGatewayEvent> {
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<SlotRuntimeSnapshot, RuntimeCommandError> {
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,
cancellation: 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,
remote_display_name: request.remote_display_name.clone(),
authentication_type: request.authentication_type,
session_id: request.session_id.clone(),
expected_server_instance_id: request.expected_server_instance_id.clone(),
})
.map_err(|error| match error {
AstrBotClientError::CredentialExpired => RuntimeCommandError {
code: "authExpired",
message: "AstrBot authentication has expired. Re-login is required.",
},
_ => 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 cancel_slot_message(&self, slot: SlotKind) -> Result<(), RuntimeCommandError> {
let guard = self.inner.lock().await;
let runtime = slot_ref(&guard, slot);
let Some(cancellation) = runtime.cancellation.as_ref() else {
return Err(RuntimeCommandError::unavailable(
"No chat request is active.",
));
};
cancellation.cancel();
Ok(())
}
pub async fn slot_sessions(
&self,
slot: SlotKind,
) -> Result<desktop_protocol::AstrBotSessionListData, RuntimeCommandError> {
let client = {
let guard = self.inner.lock().await;
match slot_ref(&guard, slot).client.as_ref() {
Some(ActiveClient::AstrBot(client)) => client.clone(),
Some(ActiveClient::Desktop(_)) => {
return Err(RuntimeCommandError::validation(
"Session lists are not available for the desktop mock transport.",
));
}
None => {
return Err(RuntimeCommandError::unavailable(
"Activate the connection before loading sessions.",
));
}
}
};
client
.list_sessions()
.await
.map_err(|_| RuntimeCommandError::unavailable("AstrBot sessions are unavailable."))
}
pub async fn switch_slot_session(
&self,
slot: SlotKind,
session_id: String,
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
if session_id.trim().is_empty() {
return Err(RuntimeCommandError::validation("session_id is required."));
}
let client = {
let guard = self.inner.lock().await;
match slot_ref(&guard, slot).client.as_ref() {
Some(ActiveClient::AstrBot(client)) => client.clone(),
Some(ActiveClient::Desktop(_)) => {
return Err(RuntimeCommandError::validation(
"Session switching is not available for the desktop mock transport.",
));
}
None => {
return Err(RuntimeCommandError::unavailable(
"Activate the connection before switching sessions.",
));
}
}
};
client
.set_session_id(session_id.clone())
.await
.map_err(|_| RuntimeCommandError::validation("The session id is invalid."))?;
let mut guard = self.inner.lock().await;
let runtime = slot_mut(&mut guard, slot);
runtime.snapshot.active_session_id = Some(session_id);
Ok(runtime.snapshot.clone())
}
pub async fn slot_capabilities(
&self,
slot: SlotKind,
) -> Result<AstrBotCapabilitySnapshot, RuntimeCommandError> {
let client = {
let guard = self.inner.lock().await;
match slot_ref(&guard, slot).client.as_ref() {
Some(ActiveClient::AstrBot(client)) => client.clone(),
Some(ActiveClient::Desktop(_)) => {
return Err(RuntimeCommandError::validation(
"Capabilities are not available for the desktop mock transport.",
));
}
None => {
return Err(RuntimeCommandError::unavailable(
"Activate the connection before loading capabilities.",
));
}
}
};
client
.capabilities()
.await
.map_err(|_| RuntimeCommandError::unavailable("AstrBot capabilities are unavailable."))
}
pub async fn upload_slot_file(
&self,
slot: SlotKind,
file_name: String,
mime_type: String,
bytes: Vec<u8>,
) -> Result<AstrBotAttachment, RuntimeCommandError> {
let client = {
let guard = self.inner.lock().await;
match slot_ref(&guard, slot).client.as_ref() {
Some(ActiveClient::AstrBot(client)) => client.clone(),
Some(ActiveClient::Desktop(_)) => {
return Err(RuntimeCommandError::validation(
"File upload is not available for the desktop mock transport.",
));
}
None => {
return Err(RuntimeCommandError::unavailable(
"Activate the connection before uploading a file.",
));
}
}
};
client
.upload_file(&file_name, &mime_type, bytes)
.await
.map_err(|_| RuntimeCommandError::unavailable("AstrBot file upload failed."))
}
pub async fn send_slot_message(
&self,
slot: SlotKind,
message: String,
config_id: Option<String>,
attachments: Vec<AstrBotAttachment>,
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
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, cancellation) = {
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.")
})?;
let cancellation = tokio_util::sync::CancellationToken::new();
runtime.cancellation = Some(cancellation.clone());
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(),
cancellation,
)
};
let send_result = match client {
ActiveClient::Desktop(client) => {
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 mut attempts = 0;
loop {
match client
.send_chat_stream(
&message,
config_id.clone(),
attachments.clone(),
&self.event_tx,
&cancellation,
)
.await
{
Ok(_session) if cancellation.is_cancelled() => {
break Err((
ActiveClient::AstrBot(client),
RuntimeCommandError {
code: "cancelled",
message: "The chat request was cancelled.",
},
));
}
Ok(session) => break Ok((ActiveClient::AstrBot(client), session)),
Err(AstrBotClientError::HttpStatus(status))
if status.as_u16() == 401 || status.as_u16() == 403 =>
{
break Err((
ActiveClient::AstrBot(client),
RuntimeCommandError {
code: "authExpired",
message: "AstrBot authentication has expired. Re-login is required.",
},
));
}
Err(error) if should_retry_astrbot(&error) && attempts < 2 => {
attempts += 1;
let mut guard = self.inner.lock().await;
slot_mut(&mut guard, slot).snapshot.state =
ConnectionState::Reconnecting;
drop(guard);
tokio::time::sleep(Duration::from_millis(250 * attempts)).await;
}
Err(_) => {
break 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 = if error.code == "authExpired" {
ConnectionState::AuthExpired
} else {
ConnectionState::ServerUnavailable
};
runtime.snapshot.last_error = Some(error.message.to_owned());
Err(error)
}
}
}
}
impl Default for DualSlotRuntime {
fn default() -> Self {
Self::new()
}
}
fn slot_ref(inner: &DualSlotRuntimeInner, slot: SlotKind) -> &SlotRuntime {
match slot {
SlotKind::Companion => &inner.companion,
SlotKind::Operations => &inner.operations,
}
}
fn should_retry_astrbot(error: &AstrBotClientError) -> bool {
match error {
AstrBotClientError::Request(_) | AstrBotClientError::ChannelClosed => true,
AstrBotClientError::HttpStatus(status) => {
status.is_server_error() || status.as_u16() == 408 || status.as_u16() == 429
}
_ => false,
}
}
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,
remote_display_name: None,
authentication_type: desktop_protocol::AuthenticationType::DeviceToken,
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);
}
}