AstrBot-Desktop/src-tauri/src/slots.rs

299 行
9.9 KiB
Rust

use desktop_protocol::{ActiveSlotKind, ConnectionSlot};
use serde::{Deserialize, Serialize};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use uuid::Uuid;
use crate::database::{ApplicationDatabase, DatabaseError};
use crate::runtime_guards::RuntimeGuards;
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AssignConnectionSlotRequest {
pub slot: ActiveSlotKind,
pub profile_id: String,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SlotCommandError {
code: &'static str,
message: &'static str,
}
impl SlotCommandError {
fn validation(message: &'static str) -> Self {
Self {
code: "validationFailed",
message,
}
}
fn operations_switch_locked() -> Self {
Self {
code: "operationsSwitchLocked",
message: "The operations profile cannot be changed while an operations task is active.",
}
}
fn database(error: DatabaseError) -> Self {
match error {
DatabaseError::ProfileNotFound => Self {
code: "profileNotFound",
message: "The selected connection profile no longer exists.",
},
DatabaseError::ProfileAlreadyAssigned => Self {
code: "profileAlreadyAssigned",
message: "One connection profile cannot occupy both active slots.",
},
DatabaseError::SlotNotFound | DatabaseError::InvalidStoredSlot => Self {
code: "invalidSlotState",
message: "The local connection slot state is invalid.",
},
_ => Self {
code: "databaseUnavailable",
message: "The local connection slot database is unavailable.",
},
}
}
}
#[tauri::command]
pub fn list_connection_slots(
database: tauri::State<'_, ApplicationDatabase>,
) -> Result<Vec<ConnectionSlot>, SlotCommandError> {
list_slots(&database)
}
#[tauri::command]
pub fn assign_connection_slot(
database: tauri::State<'_, ApplicationDatabase>,
guards: tauri::State<'_, RuntimeGuards>,
request: AssignConnectionSlotRequest,
) -> Result<ConnectionSlot, SlotCommandError> {
assign_slot(&database, &guards, request)
}
#[tauri::command]
pub fn clear_connection_slot(
database: tauri::State<'_, ApplicationDatabase>,
guards: tauri::State<'_, RuntimeGuards>,
slot: ActiveSlotKind,
) -> Result<ConnectionSlot, SlotCommandError> {
clear_slot(&database, &guards, slot)
}
fn list_slots(database: &ApplicationDatabase) -> Result<Vec<ConnectionSlot>, SlotCommandError> {
database
.list_connection_slots()
.map_err(SlotCommandError::database)
}
fn assign_slot(
database: &ApplicationDatabase,
guards: &RuntimeGuards,
request: AssignConnectionSlotRequest,
) -> Result<ConnectionSlot, SlotCommandError> {
validate_profile_id(&request.profile_id)?;
ensure_operations_switch_allowed(guards, request.slot, Some(request.profile_id.as_str()))?;
database
.assign_connection_slot(request.slot, &request.profile_id, &timestamp()?)
.map_err(SlotCommandError::database)
}
fn clear_slot(
database: &ApplicationDatabase,
guards: &RuntimeGuards,
slot: ActiveSlotKind,
) -> Result<ConnectionSlot, SlotCommandError> {
ensure_operations_switch_allowed(guards, slot, None)?;
database
.clear_connection_slot(slot, &timestamp()?)
.map_err(SlotCommandError::database)
}
fn ensure_operations_switch_allowed(
guards: &RuntimeGuards,
slot: ActiveSlotKind,
next_profile_id: Option<&str>,
) -> Result<(), SlotCommandError> {
if slot != ActiveSlotKind::Operations {
return Ok(());
}
let locked = guards
.operations_switch_locked()
.map_err(|_| SlotCommandError {
code: "databaseUnavailable",
message: "The operations switch guard is unavailable.",
})?;
if locked {
return Err(SlotCommandError::operations_switch_locked());
}
// Companion may still change while operations work is idle; this check is
// intentionally scoped to the operations slot only.
let _ = next_profile_id;
Ok(())
}
fn validate_profile_id(id: &str) -> Result<(), SlotCommandError> {
if Uuid::parse_str(id).is_err() {
return Err(SlotCommandError::validation(
"Connection profile ID is invalid.",
));
}
Ok(())
}
fn timestamp() -> Result<String, SlotCommandError> {
OffsetDateTime::now_utc()
.format(&Rfc3339)
.map_err(|_| SlotCommandError {
code: "clockUnavailable",
message: "The system clock could not produce a slot timestamp.",
})
}
#[cfg(test)]
mod tests {
use desktop_protocol::{AstrBotProfileRole, AuthenticationType, ConnectionProfile};
use super::*;
fn profile(index: usize) -> ConnectionProfile {
ConnectionProfile {
id: format!("00000000-0000-4000-8000-{index:012}"),
display_name: format!("Profile {index}"),
role: AstrBotProfileRole::General,
base_url: format!("https://example-{index}.test/"),
event_stream_url: None,
authentication_type: AuthenticationType::DeviceToken,
transport_kind: desktop_protocol::TransportKind::DesktopV1,
credential_reference: None,
allow_insecure_http: false,
pinned_certificate_fingerprint: None,
auto_connect_slot: None,
auto_connect: false,
server_instance_id: None,
server_version: None,
protocol_version: None,
local_tool_policy_id: None,
last_connected_at: None,
remote_username: None,
remote_display_name: None,
sticky_session_id: None,
created_at: "2026-07-19T00:00:00Z".into(),
updated_at: "2026-07-19T00:00:00Z".into(),
}
}
#[test]
fn assigns_and_clears_slots_through_the_bounded_service() {
let database = ApplicationDatabase::in_memory().expect("database");
let guards = RuntimeGuards::new();
let companion = profile(1);
database.create_profile(&companion).expect("create profile");
let assigned = assign_slot(
&database,
&guards,
AssignConnectionSlotRequest {
slot: ActiveSlotKind::Companion,
profile_id: companion.id.clone(),
},
)
.expect("assign slot");
assert_eq!(assigned.profile_id.as_deref(), Some(companion.id.as_str()));
let cleared =
clear_slot(&database, &guards, ActiveSlotKind::Companion).expect("clear slot");
assert!(cleared.profile_id.is_none());
}
#[test]
fn rejects_unknown_fields_and_malformed_profile_ids() {
let parsed = serde_json::from_value::<AssignConnectionSlotRequest>(serde_json::json!({
"slot": "companion",
"profileId": "00000000-0000-4000-8000-000000000001",
"token": "[REDACTED]"
}));
assert!(parsed.is_err());
let database = ApplicationDatabase::in_memory().expect("database");
let guards = RuntimeGuards::new();
assert!(
assign_slot(
&database,
&guards,
AssignConnectionSlotRequest {
slot: ActiveSlotKind::Operations,
profile_id: "not-a-uuid".into(),
},
)
.is_err()
);
}
#[test]
fn blocks_operations_slot_changes_while_a_task_is_active() {
let database = ApplicationDatabase::in_memory().expect("database");
let guards = RuntimeGuards::new();
let first = profile(1);
let second = profile(2);
database.create_profile(&first).expect("create first");
database.create_profile(&second).expect("create second");
assign_slot(
&database,
&guards,
AssignConnectionSlotRequest {
slot: ActiveSlotKind::Operations,
profile_id: first.id.clone(),
},
)
.expect("assign operations");
guards
.begin_operations_task("ops-task-1")
.expect("begin task");
let blocked = assign_slot(
&database,
&guards,
AssignConnectionSlotRequest {
slot: ActiveSlotKind::Operations,
profile_id: second.id.clone(),
},
)
.expect_err("operations switch must be blocked");
assert_eq!(blocked.code, "operationsSwitchLocked");
let blocked_clear = clear_slot(&database, &guards, ActiveSlotKind::Operations)
.expect_err("operations clear must be blocked");
assert_eq!(blocked_clear.code, "operationsSwitchLocked");
// Companion remains mutable while operations work is active.
assign_slot(
&database,
&guards,
AssignConnectionSlotRequest {
slot: ActiveSlotKind::Companion,
profile_id: second.id.clone(),
},
)
.expect("companion remains assignable");
guards.end_operations_task("ops-task-1").expect("end task");
// Free the second profile from companion before moving it to operations.
clear_slot(&database, &guards, ActiveSlotKind::Companion).expect("clear companion");
assign_slot(
&database,
&guards,
AssignConnectionSlotRequest {
slot: ActiveSlotKind::Operations,
profile_id: second.id.clone(),
},
)
.expect("operations switch after unlock");
}
}