AstrBot-Desktop/src-tauri/src/networking/commands.rs
YokiiroBW 02ac2046d6 fix(chat): validate slot sends before writing history
send_connection_slot_message wrote the optimistic user row from the
runtime snapshot alone, then called send_slot_message, which can still
refuse the send for an empty message, a busy slot or a disconnected
slot. The rejected question stayed in history with no failure marker,
and because each attempt minted a fresh local- id, retrying appended a
second copy rather than replacing the first.

Add a read-only pre-flight, ensure_slot_can_send, and run it before any
database write. The conditions it checks are extracted into
slot_send_precondition, which send_slot_message now uses inside its own
critical section, so the two cannot drift. Mint the message id once so
the failure path can address the row it wrote.

A send that fails after AstrBot accepted it must keep its question:
cancelled and streamInterrupted both mean the message is already in the
remote conversation and a partial reply may already be stored. Those
two keep the row; every other code marks it failed. server_received
encodes that rule and is covered by a test that walks every
AstrBotClientError variant through astrbot_send_error, so a future
rename of an R2 error code cannot silently change the classification.

Marking rather than deleting keeps chat_sessions.last_message_id valid,
re-uses the idempotent upsert, and leaves unread counts alone since they
already ignore user rows. The queue sanctions either choice.

The R2 retry loop and its error mapping are untouched; all five R2
transport sentinels still pass.

Refs: F-18 (audit P2-3).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 00:20:09 +08:00

901 行
30 KiB
Rust

// IPC wrappers for dual-slot runtime. Secrets never leave Rust.
use desktop_protocol::{ActiveSlotKind, ConnectionSlot, TransportKind};
use secrecy::SecretString;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tauri::State;
use tracing::{info, warn};
use super::{
ConnectionRuntimeStatus, DualSlotRuntime, RuntimeCommandError, SlotActivationRequest, SlotKind,
SlotRuntimeSnapshot, server_received,
};
use crate::credentials::{CredentialCommandError, load_profile_secret};
use crate::database::ApplicationDatabase;
use crate::runtime_guards::RuntimeGuards;
use crate::secure_store::WindowsCredentialStore;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ProbeConnectionSlotRequest {
pub slot: SlotKind,
pub profile_id: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DisconnectConnectionSlotRequest {
pub slot: SlotKind,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SendConnectionSlotMessageRequest {
pub slot: SlotKind,
pub message: String,
pub config_id: Option<String>,
#[serde(default)]
pub attachments: Vec<desktop_protocol::AstrBotAttachment>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SlotFileUploadRequest {
pub slot: SlotKind,
pub file_name: String,
pub mime_type: String,
pub bytes: Vec<u8>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DownloadConnectionSlotAttachmentRequest {
pub slot: SlotKind,
pub attachment_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DownloadConnectionSlotAttachmentResponse {
pub mime_type: String,
pub bytes: Vec<u8>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SlotCapabilitiesRequest {
pub slot: SlotKind,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DrainConnectionRuntimeEventsRequest {
pub limit: Option<usize>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LoadChatMessagesRequest {
pub profile_id: String,
pub slot: SlotKind,
pub server_instance_id: String,
pub session_id: String,
pub limit: Option<usize>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ListChatSessionsRequest {
pub profile_id: String,
pub slot: SlotKind,
pub server_instance_id: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct MarkChatSessionReadRequest {
pub profile_id: String,
pub slot: SlotKind,
pub server_instance_id: String,
pub session_id: String,
}
fn slot_name(slot: SlotKind) -> &'static str {
match slot {
SlotKind::Companion => "companion",
SlotKind::Operations => "operations",
}
}
fn active_slot_kind(slot: SlotKind) -> ActiveSlotKind {
match slot {
SlotKind::Companion => ActiveSlotKind::Companion,
SlotKind::Operations => ActiveSlotKind::Operations,
}
}
/// Rejects activating a profile that the persisted slot table binds elsewhere.
///
/// Deliberately a negative rule. `auto_connect_configured_slots` activates from
/// `profile.auto_connect_slot` and never writes `connection_slots`, so a
/// positive rule — "the profile must be assigned to the slot it is activating"
/// — would break reconnect for every auto-connected profile.
fn ensure_profile_not_bound_elsewhere(
slots: &[ConnectionSlot],
slot: SlotKind,
profile_id: &str,
) -> Result<(), RuntimeCommandError> {
let requested = active_slot_kind(slot);
let bound_elsewhere = slots
.iter()
.any(|entry| entry.slot != requested && entry.profile_id.as_deref() == Some(profile_id));
if bound_elsewhere {
return Err(RuntimeCommandError::profile_already_assigned());
}
Ok(())
}
/// Blocks operations-slot changes while an operations task is running.
///
/// Mirrors `slots::ensure_operations_switch_allowed`, extended to the runtime
/// commands. A probe is only blocked when it would change which profile the
/// operations slot holds, so reconnecting the profile already in that slot
/// still works during a task; a disconnect is blocked outright.
fn ensure_operations_runtime_change_allowed(
guards: &RuntimeGuards,
slot: SlotKind,
current_profile_id: Option<&str>,
next_profile_id: Option<&str>,
) -> Result<(), RuntimeCommandError> {
if slot != SlotKind::Operations {
return Ok(());
}
if next_profile_id.is_some() && next_profile_id == current_profile_id {
return Ok(());
}
let locked = guards
.operations_switch_locked()
.map_err(|_| RuntimeCommandError {
code: "guardUnavailable",
message: "The operations switch guard is unavailable.",
})?;
if locked {
return Err(RuntimeCommandError {
code: "operationsSwitchLocked",
message: "The operations profile cannot be changed while an operations task is active.",
});
}
Ok(())
}
fn persist_session_identity(database: &ApplicationDatabase, snapshot: &SlotRuntimeSnapshot) {
let Some(profile_id) = snapshot.profile_id.as_deref() else {
return;
};
let Some(session_id) = snapshot.active_session_id.as_deref() else {
return;
};
let Ok(Some(mut profile)) = database.profile(profile_id) else {
return;
};
let mut dirty = false;
if profile.sticky_session_id.as_deref() != Some(session_id) {
profile.sticky_session_id = Some(session_id.to_owned());
dirty = true;
}
if profile.server_instance_id.is_none()
&& let Some(server_instance_id) = snapshot.server_instance_id.as_deref()
{
profile.server_instance_id = Some(server_instance_id.to_owned());
dirty = true;
}
if dirty {
let _ = database.update_profile(&profile);
}
}
#[tauri::command]
pub async fn connection_runtime_status(
runtime: State<'_, DualSlotRuntime>,
) -> Result<ConnectionRuntimeStatus, RuntimeCommandError> {
Ok(runtime.status().await)
}
/// Starts profiles explicitly marked for startup connection.
///
/// Each slot is attempted independently. A failure is retained in that slot's
/// runtime snapshot and does not prevent the other configured slot from being attempted.
pub async fn auto_connect_configured_slots(
database: &ApplicationDatabase,
runtime: &DualSlotRuntime,
) {
let profiles = match database.list_profiles() {
Ok(profiles) => profiles,
Err(error) => {
warn!(error = %error, "startup auto-connect could not read profiles");
return;
}
};
for profile in profiles.into_iter().filter(|profile| profile.auto_connect) {
let Some(active_slot) = profile.auto_connect_slot else {
warn!(profile_id = %profile.id, "startup auto-connect skipped profile without a slot");
continue;
};
let slot = match active_slot {
desktop_protocol::ActiveSlotKind::Companion => SlotKind::Companion,
desktop_protocol::ActiveSlotKind::Operations => SlotKind::Operations,
};
let profile_id = profile.id.clone();
let activation = match startup_activation_request(database, &profile, slot) {
Ok(request) => request,
Err(error) => {
warn!(profile_id = %profile_id, slot = ?slot, error = %error, "startup auto-connect skipped");
continue;
}
};
match runtime.activate_slot(activation).await {
Ok(snapshot) => {
persist_session_identity(database, &snapshot);
info!(
profile_id = %profile_id,
slot = ?slot,
state = ?snapshot.state,
"startup auto-connect completed"
);
}
Err(error) => warn!(
profile_id = %profile_id,
slot = ?slot,
error = %error,
"startup auto-connect failed"
),
}
}
}
fn startup_activation_request(
database: &ApplicationDatabase,
profile: &desktop_protocol::ConnectionProfile,
slot: SlotKind,
) -> Result<SlotActivationRequest, RuntimeCommandError> {
let secret = load_profile_secret(database, &WindowsCredentialStore, &profile.id).map_err(
|error: CredentialCommandError| RuntimeCommandError {
code: error.code,
message: error.message,
},
)?;
match profile.transport_kind {
TransportKind::AstrBotOpenApi => {
let secret = secret.ok_or(RuntimeCommandError {
code: "credentialMissing",
message: "Enroll an AstrBot credential before probing this profile.",
})?;
let api_key =
String::from_utf8(secret.secret().to_vec()).map_err(|_| RuntimeCommandError {
code: "credentialInvalid",
message: "Stored API key is not valid UTF-8.",
})?;
let remote_username = profile.remote_username.clone().ok_or(RuntimeCommandError {
code: "validationFailed",
message: "AstrBot profiles require remote_username.",
})?;
Ok(SlotActivationRequest {
profile_id: profile.id.clone(),
slot,
base_url: profile.base_url.clone(),
transport: TransportKind::AstrBotOpenApi,
api_key: Some(SecretString::from(api_key)),
bearer_token: None,
remote_username: Some(remote_username),
remote_display_name: profile.remote_display_name.clone(),
authentication_type: profile.authentication_type,
session_id: profile.sticky_session_id.clone(),
expected_server_instance_id: profile.server_instance_id.clone(),
})
}
TransportKind::DesktopV1 => {
let bearer = secret.and_then(|value| {
String::from_utf8(value.secret().to_vec())
.ok()
.map(SecretString::from)
});
let expected = profile
.server_instance_id
.clone()
.ok_or(RuntimeCommandError {
code: "validationFailed",
message: "Desktop gateway profiles require server_instance_id before probe.",
})?;
Ok(SlotActivationRequest {
profile_id: profile.id.clone(),
slot,
base_url: profile.base_url.clone(),
transport: TransportKind::DesktopV1,
api_key: None,
bearer_token: bearer,
remote_username: None,
remote_display_name: None,
authentication_type: profile.authentication_type,
session_id: None,
expected_server_instance_id: Some(expected),
})
}
}
}
#[tauri::command]
pub async fn drain_connection_runtime_events(
database: State<'_, ApplicationDatabase>,
runtime: State<'_, DualSlotRuntime>,
request: DrainConnectionRuntimeEventsRequest,
) -> Result<Vec<super::BoundGatewayEvent>, RuntimeCommandError> {
let events = runtime.drain_events(request.limit.unwrap_or(64)).await;
for event in &events {
persist_runtime_event(&database, event);
}
Ok(events)
}
#[tauri::command]
pub async fn list_chat_sessions(
database: State<'_, ApplicationDatabase>,
request: ListChatSessionsRequest,
) -> Result<Vec<crate::database::StoredChatSession>, RuntimeCommandError> {
database
.list_chat_sessions(
&request.profile_id,
slot_name(request.slot),
&request.server_instance_id,
)
.map_err(|_| RuntimeCommandError {
code: "databaseUnavailable",
message: "Chat sessions are unavailable.",
})
}
#[tauri::command]
pub async fn mark_chat_session_read(
database: State<'_, ApplicationDatabase>,
request: MarkChatSessionReadRequest,
) -> Result<(), RuntimeCommandError> {
database
.mark_chat_session_read(
&request.profile_id,
slot_name(request.slot),
&request.server_instance_id,
&request.session_id,
)
.map_err(|_| RuntimeCommandError {
code: "databaseUnavailable",
message: "Chat session state is unavailable.",
})
}
#[tauri::command]
pub async fn load_chat_messages(
database: State<'_, ApplicationDatabase>,
request: LoadChatMessagesRequest,
) -> Result<Vec<crate::database::StoredChatMessage>, RuntimeCommandError> {
database
.list_chat_messages(
&request.profile_id,
slot_name(request.slot),
&request.server_instance_id,
&request.session_id,
request.limit.unwrap_or(100),
)
.map_err(|_| RuntimeCommandError {
code: "databaseUnavailable",
message: "Chat history is unavailable.",
})
}
pub(crate) fn persist_runtime_event(
database: &ApplicationDatabase,
event: &super::BoundGatewayEvent,
) {
let Some(session_id) = event.session_id.as_deref() else {
return;
};
let Some((role, content, streaming, message_id)) = (match event.event_type.as_str() {
"message.delta" => Some((
"assistant",
event
.payload
.get("delta")
.and_then(Value::as_str)
.unwrap_or_default(),
true,
event
.message_id
.as_deref()
.unwrap_or(event.event_id.as_str()),
)),
"message.completed" => Some((
"assistant",
event
.payload
.get("content")
.and_then(Value::as_str)
.unwrap_or_default(),
false,
event
.message_id
.as_deref()
.unwrap_or(event.event_id.as_str()),
)),
"message.proactive" => Some((
"assistant",
event
.payload
.get("content")
.and_then(Value::as_str)
.unwrap_or_default(),
false,
event.event_id.as_str(),
)),
"error" => Some((
"system",
event
.payload
.get("message")
.and_then(Value::as_str)
.unwrap_or("Connection error"),
false,
event.event_id.as_str(),
)),
_ => None,
}) else {
return;
};
let slot = match event.slot {
SlotKind::Companion => "companion",
SlotKind::Operations => "operations",
};
let _ = database.upsert_chat_message(
"local-default",
&event.profile_id,
slot,
&event.server_instance_id,
None,
session_id,
message_id,
role,
content,
streaming,
event.event_type == "error",
);
}
#[tauri::command]
pub async fn probe_connection_slot(
database: State<'_, ApplicationDatabase>,
runtime: State<'_, DualSlotRuntime>,
guards: State<'_, RuntimeGuards>,
request: ProbeConnectionSlotRequest,
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
let current = match request.slot {
SlotKind::Companion => runtime.status().await.companion,
SlotKind::Operations => runtime.status().await.operations,
};
ensure_operations_runtime_change_allowed(
&guards,
request.slot,
current.profile_id.as_deref(),
Some(request.profile_id.as_str()),
)?;
if let Ok(slots) = database.list_connection_slots() {
ensure_profile_not_bound_elsewhere(&slots, request.slot, &request.profile_id)?;
}
let profile = database
.profile(&request.profile_id)
.map_err(|_| RuntimeCommandError {
code: "databaseUnavailable",
message: "The local profile database is unavailable.",
})?
.ok_or(RuntimeCommandError {
code: "notFound",
message: "The connection profile no longer exists.",
})?;
if profile.transport_kind != TransportKind::AstrBotOpenApi
&& profile.transport_kind != TransportKind::DesktopV1
{
return Err(RuntimeCommandError {
code: "validationFailed",
message: "Unsupported transport kind.",
});
}
let secret = load_profile_secret(&database, &WindowsCredentialStore, &profile.id).map_err(
|error: CredentialCommandError| RuntimeCommandError {
code: error.code,
message: error.message,
},
)?;
let activation = match profile.transport_kind {
TransportKind::AstrBotOpenApi => {
let secret = secret.ok_or(RuntimeCommandError {
code: "credentialMissing",
message: "Enroll an API key before probing an AstrBot profile.",
})?;
let api_key =
String::from_utf8(secret.secret().to_vec()).map_err(|_| RuntimeCommandError {
code: "credentialInvalid",
message: "Stored API key is not valid UTF-8.",
})?;
let remote_username = profile.remote_username.clone().ok_or(RuntimeCommandError {
code: "validationFailed",
message: "AstrBot profiles require remote_username.",
})?;
SlotActivationRequest {
profile_id: profile.id.clone(),
slot: request.slot,
base_url: profile.base_url.clone(),
transport: TransportKind::AstrBotOpenApi,
api_key: Some(SecretString::from(api_key)),
bearer_token: None,
remote_username: Some(remote_username),
remote_display_name: profile.remote_display_name.clone(),
authentication_type: profile.authentication_type,
session_id: profile.sticky_session_id.clone(),
expected_server_instance_id: profile.server_instance_id.clone(),
}
}
TransportKind::DesktopV1 => {
let bearer = secret.and_then(|value| {
String::from_utf8(value.secret().to_vec())
.ok()
.map(SecretString::from)
});
let expected = profile
.server_instance_id
.clone()
.ok_or(RuntimeCommandError {
code: "validationFailed",
message: "Desktop gateway profiles require server_instance_id before probe.",
})?;
SlotActivationRequest {
profile_id: profile.id.clone(),
slot: request.slot,
base_url: profile.base_url.clone(),
transport: TransportKind::DesktopV1,
api_key: None,
bearer_token: bearer,
remote_username: None,
remote_display_name: None,
authentication_type: profile.authentication_type,
session_id: None,
expected_server_instance_id: Some(expected),
}
}
};
let snapshot = runtime.activate_slot(activation).await?;
// Persist observed identity / sticky session without exposing secrets.
if let Ok(Some(mut stored)) = database.profile(&request.profile_id) {
let mut dirty = false;
if stored.server_instance_id.is_none()
&& let Some(server_instance_id) = snapshot.server_instance_id.clone()
{
stored.server_instance_id = Some(server_instance_id);
dirty = true;
}
if let Some(session_id) = snapshot.active_session_id.clone()
&& stored.sticky_session_id.as_deref() != Some(session_id.as_str())
{
stored.sticky_session_id = Some(session_id);
dirty = true;
}
if dirty {
let _ = database.update_profile(&stored);
}
}
Ok(snapshot)
}
#[tauri::command]
pub async fn disconnect_connection_slot(
runtime: State<'_, DualSlotRuntime>,
guards: State<'_, RuntimeGuards>,
request: DisconnectConnectionSlotRequest,
) -> Result<(), RuntimeCommandError> {
ensure_operations_runtime_change_allowed(&guards, request.slot, None, None)?;
runtime.deactivate_slot(request.slot).await
}
#[tauri::command]
pub async fn cancel_connection_slot_message(
runtime: State<'_, DualSlotRuntime>,
request: DisconnectConnectionSlotRequest,
) -> Result<(), RuntimeCommandError> {
runtime.cancel_slot_message(request.slot).await
}
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatRemoteSession {
pub session_id: String,
pub display_name: Option<String>,
pub updated_at: Option<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SwitchChatSessionRequest {
pub slot: SlotKind,
pub session_id: String,
}
#[tauri::command]
pub async fn connection_slot_sessions(
runtime: State<'_, DualSlotRuntime>,
request: SlotCapabilitiesRequest,
) -> Result<Vec<ChatRemoteSession>, RuntimeCommandError> {
let sessions = runtime.slot_sessions(request.slot).await?;
Ok(sessions
.sessions
.into_iter()
.map(|session| ChatRemoteSession {
session_id: session.session_id,
display_name: session.display_name,
updated_at: session.updated_at,
})
.collect())
}
#[tauri::command]
pub async fn switch_connection_slot_session(
database: State<'_, ApplicationDatabase>,
runtime: State<'_, DualSlotRuntime>,
request: SwitchChatSessionRequest,
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
let snapshot = runtime
.switch_slot_session(request.slot, request.session_id)
.await?;
persist_session_identity(&database, &snapshot);
Ok(snapshot)
}
#[tauri::command]
pub async fn connection_slot_capabilities(
runtime: State<'_, DualSlotRuntime>,
request: SlotCapabilitiesRequest,
) -> Result<desktop_protocol::AstrBotCapabilitySnapshot, RuntimeCommandError> {
runtime.slot_capabilities(request.slot).await
}
#[tauri::command]
pub async fn download_connection_slot_attachment(
runtime: State<'_, DualSlotRuntime>,
request: DownloadConnectionSlotAttachmentRequest,
) -> Result<DownloadConnectionSlotAttachmentResponse, RuntimeCommandError> {
let (mime_type, bytes) = runtime
.download_slot_attachment(request.slot, request.attachment_id)
.await?;
Ok(DownloadConnectionSlotAttachmentResponse { mime_type, bytes })
}
#[tauri::command]
pub async fn upload_connection_slot_file(
runtime: State<'_, DualSlotRuntime>,
request: SlotFileUploadRequest,
) -> Result<desktop_protocol::AstrBotAttachment, RuntimeCommandError> {
if request.bytes.len() > 16 * 1024 * 1024 {
return Err(RuntimeCommandError::validation(
"Attachment exceeds the 16 MiB limit.",
));
}
runtime
.upload_slot_file(
request.slot,
request.file_name,
request.mime_type,
request.bytes,
)
.await
}
#[tauri::command]
pub async fn send_connection_slot_message(
database: State<'_, ApplicationDatabase>,
runtime: State<'_, DualSlotRuntime>,
request: SendConnectionSlotMessageRequest,
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
// Validate before touching history. This used to run the other way round,
// so a send rejected for an empty message, a busy slot, or a disconnected
// slot still left an unmarked `user` row behind — and each retry minted a
// fresh `local-` id, appending another copy of the same question.
runtime
.ensure_slot_can_send(request.slot, &request.message)
.await?;
let message_for_history = request.message.clone();
let status = runtime.status().await;
let initial_session = match request.slot {
SlotKind::Companion => status.companion,
SlotKind::Operations => status.operations,
};
// One id for this send, so the failure path can address the row it wrote.
let message_id = format!("local-{}", uuid::Uuid::new_v4());
let persisted = match (
initial_session.profile_id.as_deref(),
initial_session.server_instance_id.as_deref(),
initial_session.active_session_id.as_deref(),
) {
(Some(profile_id), Some(server_instance_id), Some(session_id)) => {
let _ = database.upsert_chat_message(
"local-default",
profile_id,
slot_name(request.slot),
server_instance_id,
None,
session_id,
&message_id,
"user",
&message_for_history,
false,
false,
);
Some((
profile_id.to_owned(),
server_instance_id.to_owned(),
session_id.to_owned(),
))
}
_ => None,
};
let result = runtime
.send_slot_message(
request.slot,
request.message,
request.config_id,
request.attachments,
)
.await;
if persisted.is_none()
&& let Ok(snapshot) = &result
&& let (Some(profile_id), Some(server_instance_id), Some(session_id)) = (
snapshot.profile_id.as_deref(),
snapshot.server_instance_id.as_deref(),
snapshot.active_session_id.as_deref(),
)
{
let _ = database.upsert_chat_message(
"local-default",
profile_id,
slot_name(request.slot),
server_instance_id,
None,
session_id,
&message_id,
"user",
&message_for_history,
false,
false,
);
}
// A send the server never accepted must not leave a clean-looking row.
// Marking rather than deleting keeps `chat_sessions.last_message_id` valid
// and re-uses the idempotent upsert; unread counts ignore `user` rows.
if let (Some((profile_id, server_instance_id, session_id)), Err(error)) = (&persisted, &result)
&& !server_received(error.code)
{
let _ = database.upsert_chat_message(
"local-default",
profile_id,
slot_name(request.slot),
server_instance_id,
None,
session_id,
&message_id,
"user",
&message_for_history,
false,
true,
);
}
if let Ok(snapshot) = &result {
persist_session_identity(&database, snapshot);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
const PROFILE_A: &str = "11111111-1111-1111-1111-111111111111";
const PROFILE_B: &str = "22222222-2222-2222-2222-222222222222";
const PROFILE_C: &str = "33333333-3333-3333-3333-333333333333";
fn slots_with(companion: Option<&str>, operations: Option<&str>) -> Vec<ConnectionSlot> {
let mut companion_slot = ConnectionSlot::empty(ActiveSlotKind::Companion);
companion_slot.profile_id = companion.map(str::to_owned);
let mut operations_slot = ConnectionSlot::empty(ActiveSlotKind::Operations);
operations_slot.profile_id = operations.map(str::to_owned);
vec![companion_slot, operations_slot]
}
#[test]
fn probing_a_profile_bound_to_the_other_slot_is_rejected() {
let slots = slots_with(Some(PROFILE_A), None);
let error = ensure_profile_not_bound_elsewhere(&slots, SlotKind::Operations, PROFILE_A)
.expect_err("a profile assigned to companion must not activate into operations");
assert_eq!(error.code, "profileAlreadyAssigned");
}
#[test]
fn a_profile_may_reconnect_the_slot_it_already_owns() {
let slots = slots_with(Some(PROFILE_A), Some(PROFILE_B));
ensure_profile_not_bound_elsewhere(&slots, SlotKind::Companion, PROFILE_A)
.expect("reconnecting the slot the profile already owns must stay allowed");
// A profile the slot table does not mention at all must also pass:
// startup auto-connect activates from `auto_connect_slot` and never
// writes `connection_slots`, so a positive rule would brick reconnect.
ensure_profile_not_bound_elsewhere(&slots, SlotKind::Companion, PROFILE_C)
.expect("an unassigned profile must not be blocked");
}
#[test]
fn operations_runtime_changes_are_blocked_while_a_task_runs() {
let guards = RuntimeGuards::new();
guards
.begin_operations_task("task-a")
.expect("begin a task");
let error = ensure_operations_runtime_change_allowed(
&guards,
SlotKind::Operations,
Some(PROFILE_A),
Some(PROFILE_B),
)
.expect_err("switching the operations profile during a task must be refused");
assert_eq!(error.code, "operationsSwitchLocked");
let error =
ensure_operations_runtime_change_allowed(&guards, SlotKind::Operations, None, None)
.expect_err("disconnecting operations during a task must be refused");
assert_eq!(error.code, "operationsSwitchLocked");
ensure_operations_runtime_change_allowed(
&guards,
SlotKind::Operations,
Some(PROFILE_A),
Some(PROFILE_A),
)
.expect("reconnecting the profile the slot already holds must stay allowed");
ensure_operations_runtime_change_allowed(
&guards,
SlotKind::Companion,
Some(PROFILE_A),
Some(PROFILE_B),
)
.expect("the companion slot is not gated by the operations guard");
guards.end_operations_task("task-a").expect("end the task");
ensure_operations_runtime_change_allowed(
&guards,
SlotKind::Operations,
Some(PROFILE_A),
Some(PROFILE_B),
)
.expect("the guard must release once no operations task remains");
}
}