diff --git a/src-tauri/src/networking/commands.rs b/src-tauri/src/networking/commands.rs index 9eaeb4e..080489c 100644 --- a/src-tauri/src/networking/commands.rs +++ b/src-tauri/src/networking/commands.rs @@ -1,5 +1,5 @@ // IPC wrappers for dual-slot runtime. Secrets never leave Rust. -use desktop_protocol::TransportKind; +use desktop_protocol::{ActiveSlotKind, ConnectionSlot, TransportKind}; use secrecy::SecretString; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -12,6 +12,7 @@ use super::{ }; use crate::credentials::{CredentialCommandError, load_profile_secret}; use crate::database::ApplicationDatabase; +use crate::runtime_guards::RuntimeGuards; use crate::secure_store::WindowsCredentialStore; #[derive(Debug, Deserialize)] @@ -106,6 +107,67 @@ fn slot_name(slot: SlotKind) -> &'static str { } } +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; @@ -412,8 +474,24 @@ pub(crate) fn persist_runtime_event( pub async fn probe_connection_slot( database: State<'_, ApplicationDatabase>, runtime: State<'_, DualSlotRuntime>, + guards: State<'_, RuntimeGuards>, request: ProbeConnectionSlotRequest, ) -> Result { + 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 { @@ -527,8 +605,10 @@ pub async fn probe_connection_slot( #[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 } @@ -689,3 +769,91 @@ pub async fn send_connection_slot_message( } 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 { + 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"); + } +} diff --git a/src-tauri/src/networking/runtime.rs b/src-tauri/src/networking/runtime.rs index 99d98ed..b802113 100644 --- a/src-tauri/src/networking/runtime.rs +++ b/src-tauri/src/networking/runtime.rs @@ -133,6 +133,22 @@ impl RuntimeCommandError { message, } } + + /// Shares the wire code with `slots::SlotCommandError`, so the frontend + /// needs no separate branch for the runtime-side rejection. + pub fn profile_already_assigned() -> Self { + Self { + code: "profileAlreadyAssigned", + message: "One connection profile cannot occupy both runtime slots.", + } + } +} + +fn other_slot(slot: SlotKind) -> SlotKind { + match slot { + SlotKind::Companion => SlotKind::Operations, + SlotKind::Operations => SlotKind::Companion, + } } /// A client that has been constructed but not yet published into its slot. @@ -319,6 +335,21 @@ impl DualSlotRuntime { // be interrupted by `deactivate_slot`. let (generation, cancellation) = { let mut guard = self.inner.lock().await; + + // One profile may not occupy both runtime slots. The rule is + // deliberately negative — it only inspects the *other* slot — so + // re-activating the same slot with the same profile (a reconnect) + // is unaffected. Enforcing it here rather than at the command layer + // also covers startup auto-connect, which calls this directly. + if slot_ref(&guard, other_slot(request.slot)) + .snapshot + .profile_id + .as_deref() + == Some(request.profile_id.as_str()) + { + return Err(RuntimeCommandError::profile_already_assigned()); + } + let runtime = slot_mut(&mut guard, request.slot); if let Some(cancellation) = runtime.connection_cancellation.take() { cancellation.cancel(); @@ -981,6 +1012,39 @@ mod tests { assert!(companion.profile_id.is_none()); } + #[tokio::test] + async fn rejects_the_same_profile_in_both_runtime_slots() { + let base_url = spawn_unresponsive_server().await; + let runtime = Arc::new(DualSlotRuntime::new()); + + let activation = { + let runtime = Arc::clone(&runtime); + let base_url = base_url.clone(); + tokio::spawn(async move { + runtime + .activate_slot(astrbot_request(SlotKind::Companion, PROFILE_A, &base_url)) + .await + }) + }; + + wait_for_connecting(&runtime, SlotKind::Companion).await; + + // The rejection must land before any network work, which is only + // observable because the snapshot is published ahead of the probe. + let error = tokio::time::timeout( + Duration::from_secs(2), + runtime.activate_slot(astrbot_request(SlotKind::Operations, PROFILE_A, &base_url)), + ) + .await + .expect("the rejection must not wait on a probe") + .expect_err("one profile must not occupy both runtime slots"); + assert_eq!(error.code, "profileAlreadyAssigned"); + + assert!(runtime.status().await.operations.profile_id.is_none()); + + activation.abort(); + } + #[tokio::test] async fn invalid_activation_leaves_the_slot_untouched() { let runtime = DualSlotRuntime::new();