2026-07-20 11:31:41 +08:00
|
|
|
// IPC wrappers for dual-slot runtime. Secrets never leave Rust.
|
fix(net): reject one profile occupying both runtime slots
probe_connection_slot never consulted the slot assignment table, so the
same profile could be activated into both runtime slots at once. That
bypasses the ProfileAlreadyAssigned policy the database enforces, and
both slots then race to overwrite the same sticky_session_id.
Enforce it in three places. The runtime invariant lives inside
activate_slot's claim phase, so it also covers startup auto-connect,
which calls activate_slot directly and would bypass a command-layer
check. The command adds a cross-check against connection_slots. And the
operations switch guard now covers probe and disconnect, not just slot
assignment.
Both rules are deliberately negative — they ask whether the profile is
bound to the *other* slot, never whether it is bound to this one.
auto_connect_configured_slots activates from profile.auto_connect_slot
and never writes connection_slots, so a positive rule would break
reconnect for every auto-connected profile. For the same reason the
probe guard only refuses a change of profile, so reconnecting the
profile the operations slot already holds still works during a task.
The operations guard has no production writer yet (F-74, audit P3-7),
so it is inert at runtime. It ships with a test that flips the guard
directly rather than as an unexercised branch.
Refs: F-19 (audit P2-4).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 00:16:33 +08:00
|
|
|
use desktop_protocol::{ActiveSlotKind, ConnectionSlot, TransportKind};
|
2026-07-20 11:31:41 +08:00
|
|
|
use secrecy::SecretString;
|
2026-07-22 02:52:31 +08:00
|
|
|
use serde::{Deserialize, Serialize};
|
2026-07-20 11:31:41 +08:00
|
|
|
use serde_json::Value;
|
|
|
|
|
use tauri::State;
|
2026-07-20 12:01:18 +08:00
|
|
|
use tracing::{info, warn};
|
2026-07-20 11:31:41 +08:00
|
|
|
|
|
|
|
|
use super::{
|
|
|
|
|
ConnectionRuntimeStatus, DualSlotRuntime, RuntimeCommandError, SlotActivationRequest, SlotKind,
|
|
|
|
|
SlotRuntimeSnapshot,
|
|
|
|
|
};
|
|
|
|
|
use crate::credentials::{CredentialCommandError, load_profile_secret};
|
|
|
|
|
use crate::database::ApplicationDatabase;
|
fix(net): reject one profile occupying both runtime slots
probe_connection_slot never consulted the slot assignment table, so the
same profile could be activated into both runtime slots at once. That
bypasses the ProfileAlreadyAssigned policy the database enforces, and
both slots then race to overwrite the same sticky_session_id.
Enforce it in three places. The runtime invariant lives inside
activate_slot's claim phase, so it also covers startup auto-connect,
which calls activate_slot directly and would bypass a command-layer
check. The command adds a cross-check against connection_slots. And the
operations switch guard now covers probe and disconnect, not just slot
assignment.
Both rules are deliberately negative — they ask whether the profile is
bound to the *other* slot, never whether it is bound to this one.
auto_connect_configured_slots activates from profile.auto_connect_slot
and never writes connection_slots, so a positive rule would break
reconnect for every auto-connected profile. For the same reason the
probe guard only refuses a change of profile, so reconnecting the
profile the operations slot already holds still works during a task.
The operations guard has no production writer yet (F-74, audit P3-7),
so it is inert at runtime. It ships with a test that flips the guard
directly rather than as an unexercised branch.
Refs: F-19 (audit P2-4).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 00:16:33 +08:00
|
|
|
use crate::runtime_guards::RuntimeGuards;
|
2026-07-20 11:31:41 +08:00
|
|
|
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,
|
2026-07-20 13:30:29 +08:00
|
|
|
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>,
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-22 02:52:31 +08:00
|
|
|
#[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>,
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-20 13:30:29 +08:00
|
|
|
#[derive(Debug, Deserialize)]
|
|
|
|
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
|
|
|
|
pub struct SlotCapabilitiesRequest {
|
|
|
|
|
pub slot: SlotKind,
|
2026-07-20 11:31:41 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[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,
|
2026-07-21 14:43:14 +08:00
|
|
|
pub slot: SlotKind,
|
2026-07-20 11:31:41 +08:00
|
|
|
pub server_instance_id: String,
|
|
|
|
|
pub session_id: String,
|
|
|
|
|
pub limit: Option<usize>,
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-20 12:25:08 +08:00
|
|
|
#[derive(Debug, Deserialize)]
|
|
|
|
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
|
|
|
|
pub struct ListChatSessionsRequest {
|
|
|
|
|
pub profile_id: String,
|
2026-07-21 14:43:14 +08:00
|
|
|
pub slot: SlotKind,
|
2026-07-20 12:25:08 +08:00
|
|
|
pub server_instance_id: String,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
|
|
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
|
|
|
|
pub struct MarkChatSessionReadRequest {
|
|
|
|
|
pub profile_id: String,
|
2026-07-21 14:43:14 +08:00
|
|
|
pub slot: SlotKind,
|
2026-07-20 12:25:08 +08:00
|
|
|
pub server_instance_id: String,
|
|
|
|
|
pub session_id: String,
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-21 14:43:14 +08:00
|
|
|
fn slot_name(slot: SlotKind) -> &'static str {
|
|
|
|
|
match slot {
|
|
|
|
|
SlotKind::Companion => "companion",
|
|
|
|
|
SlotKind::Operations => "operations",
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
fix(net): reject one profile occupying both runtime slots
probe_connection_slot never consulted the slot assignment table, so the
same profile could be activated into both runtime slots at once. That
bypasses the ProfileAlreadyAssigned policy the database enforces, and
both slots then race to overwrite the same sticky_session_id.
Enforce it in three places. The runtime invariant lives inside
activate_slot's claim phase, so it also covers startup auto-connect,
which calls activate_slot directly and would bypass a command-layer
check. The command adds a cross-check against connection_slots. And the
operations switch guard now covers probe and disconnect, not just slot
assignment.
Both rules are deliberately negative — they ask whether the profile is
bound to the *other* slot, never whether it is bound to this one.
auto_connect_configured_slots activates from profile.auto_connect_slot
and never writes connection_slots, so a positive rule would break
reconnect for every auto-connected profile. For the same reason the
probe guard only refuses a change of profile, so reconnecting the
profile the operations slot already holds still works during a task.
The operations guard has no production writer yet (F-74, audit P3-7),
so it is inert at runtime. It ships with a test that flips the guard
directly rather than as an unexercised branch.
Refs: F-19 (audit P2-4).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 00:16:33 +08:00
|
|
|
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(())
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-22 02:52:31 +08:00
|
|
|
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);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-20 11:31:41 +08:00
|
|
|
#[tauri::command]
|
|
|
|
|
pub async fn connection_runtime_status(
|
|
|
|
|
runtime: State<'_, DualSlotRuntime>,
|
|
|
|
|
) -> Result<ConnectionRuntimeStatus, RuntimeCommandError> {
|
|
|
|
|
Ok(runtime.status().await)
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-20 12:01:18 +08:00
|
|
|
/// 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 {
|
2026-07-22 02:52:31 +08:00
|
|
|
Ok(snapshot) => {
|
|
|
|
|
persist_session_identity(database, &snapshot);
|
|
|
|
|
info!(
|
|
|
|
|
profile_id = %profile_id,
|
|
|
|
|
slot = ?slot,
|
|
|
|
|
state = ?snapshot.state,
|
|
|
|
|
"startup auto-connect completed"
|
|
|
|
|
);
|
|
|
|
|
}
|
2026-07-20 12:01:18 +08:00
|
|
|
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",
|
2026-07-20 16:52:29 +08:00
|
|
|
message: "Enroll an AstrBot credential before probing this profile.",
|
2026-07-20 12:01:18 +08:00
|
|
|
})?;
|
|
|
|
|
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),
|
2026-07-20 16:28:42 +08:00
|
|
|
remote_display_name: profile.remote_display_name.clone(),
|
2026-07-20 16:52:29 +08:00
|
|
|
authentication_type: profile.authentication_type,
|
2026-07-20 12:01:18 +08:00
|
|
|
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,
|
2026-07-20 16:28:42 +08:00
|
|
|
remote_display_name: None,
|
2026-07-20 16:52:29 +08:00
|
|
|
authentication_type: profile.authentication_type,
|
2026-07-20 12:01:18 +08:00
|
|
|
session_id: None,
|
|
|
|
|
expected_server_instance_id: Some(expected),
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-20 11:31:41 +08:00
|
|
|
#[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)
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-20 12:25:08 +08:00
|
|
|
#[tauri::command]
|
|
|
|
|
pub async fn list_chat_sessions(
|
|
|
|
|
database: State<'_, ApplicationDatabase>,
|
|
|
|
|
request: ListChatSessionsRequest,
|
|
|
|
|
) -> Result<Vec<crate::database::StoredChatSession>, RuntimeCommandError> {
|
|
|
|
|
database
|
2026-07-21 14:43:14 +08:00
|
|
|
.list_chat_sessions(
|
|
|
|
|
&request.profile_id,
|
|
|
|
|
slot_name(request.slot),
|
|
|
|
|
&request.server_instance_id,
|
|
|
|
|
)
|
2026-07-20 12:25:08 +08:00
|
|
|
.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,
|
2026-07-21 14:43:14 +08:00
|
|
|
slot_name(request.slot),
|
2026-07-20 12:25:08 +08:00
|
|
|
&request.server_instance_id,
|
|
|
|
|
&request.session_id,
|
|
|
|
|
)
|
|
|
|
|
.map_err(|_| RuntimeCommandError {
|
|
|
|
|
code: "databaseUnavailable",
|
|
|
|
|
message: "Chat session state is unavailable.",
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-20 11:31:41 +08:00
|
|
|
#[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,
|
2026-07-21 14:43:14 +08:00
|
|
|
slot_name(request.slot),
|
2026-07-20 11:31:41 +08:00
|
|
|
&request.server_instance_id,
|
|
|
|
|
&request.session_id,
|
|
|
|
|
request.limit.unwrap_or(100),
|
|
|
|
|
)
|
|
|
|
|
.map_err(|_| RuntimeCommandError {
|
|
|
|
|
code: "databaseUnavailable",
|
|
|
|
|
message: "Chat history is unavailable.",
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-21 14:43:14 +08:00
|
|
|
pub(crate) fn persist_runtime_event(
|
|
|
|
|
database: &ApplicationDatabase,
|
|
|
|
|
event: &super::BoundGatewayEvent,
|
|
|
|
|
) {
|
2026-07-20 11:31:41 +08:00
|
|
|
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>,
|
fix(net): reject one profile occupying both runtime slots
probe_connection_slot never consulted the slot assignment table, so the
same profile could be activated into both runtime slots at once. That
bypasses the ProfileAlreadyAssigned policy the database enforces, and
both slots then race to overwrite the same sticky_session_id.
Enforce it in three places. The runtime invariant lives inside
activate_slot's claim phase, so it also covers startup auto-connect,
which calls activate_slot directly and would bypass a command-layer
check. The command adds a cross-check against connection_slots. And the
operations switch guard now covers probe and disconnect, not just slot
assignment.
Both rules are deliberately negative — they ask whether the profile is
bound to the *other* slot, never whether it is bound to this one.
auto_connect_configured_slots activates from profile.auto_connect_slot
and never writes connection_slots, so a positive rule would break
reconnect for every auto-connected profile. For the same reason the
probe guard only refuses a change of profile, so reconnecting the
profile the operations slot already holds still works during a task.
The operations guard has no production writer yet (F-74, audit P3-7),
so it is inert at runtime. It ships with a test that flips the guard
directly rather than as an unexercised branch.
Refs: F-19 (audit P2-4).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 00:16:33 +08:00
|
|
|
guards: State<'_, RuntimeGuards>,
|
2026-07-20 11:31:41 +08:00
|
|
|
request: ProbeConnectionSlotRequest,
|
|
|
|
|
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
|
fix(net): reject one profile occupying both runtime slots
probe_connection_slot never consulted the slot assignment table, so the
same profile could be activated into both runtime slots at once. That
bypasses the ProfileAlreadyAssigned policy the database enforces, and
both slots then race to overwrite the same sticky_session_id.
Enforce it in three places. The runtime invariant lives inside
activate_slot's claim phase, so it also covers startup auto-connect,
which calls activate_slot directly and would bypass a command-layer
check. The command adds a cross-check against connection_slots. And the
operations switch guard now covers probe and disconnect, not just slot
assignment.
Both rules are deliberately negative — they ask whether the profile is
bound to the *other* slot, never whether it is bound to this one.
auto_connect_configured_slots activates from profile.auto_connect_slot
and never writes connection_slots, so a positive rule would break
reconnect for every auto-connected profile. For the same reason the
probe guard only refuses a change of profile, so reconnecting the
profile the operations slot already holds still works during a task.
The operations guard has no production writer yet (F-74, audit P3-7),
so it is inert at runtime. It ships with a test that flips the guard
directly rather than as an unexercised branch.
Refs: F-19 (audit P2-4).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 00:16:33 +08:00
|
|
|
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)?;
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-20 11:31:41 +08:00
|
|
|
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),
|
2026-07-20 16:28:42 +08:00
|
|
|
remote_display_name: profile.remote_display_name.clone(),
|
2026-07-20 16:52:29 +08:00
|
|
|
authentication_type: profile.authentication_type,
|
2026-07-20 11:31:41 +08:00
|
|
|
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,
|
2026-07-20 16:28:42 +08:00
|
|
|
remote_display_name: None,
|
2026-07-20 16:52:29 +08:00
|
|
|
authentication_type: profile.authentication_type,
|
2026-07-20 11:31:41 +08:00
|
|
|
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>,
|
fix(net): reject one profile occupying both runtime slots
probe_connection_slot never consulted the slot assignment table, so the
same profile could be activated into both runtime slots at once. That
bypasses the ProfileAlreadyAssigned policy the database enforces, and
both slots then race to overwrite the same sticky_session_id.
Enforce it in three places. The runtime invariant lives inside
activate_slot's claim phase, so it also covers startup auto-connect,
which calls activate_slot directly and would bypass a command-layer
check. The command adds a cross-check against connection_slots. And the
operations switch guard now covers probe and disconnect, not just slot
assignment.
Both rules are deliberately negative — they ask whether the profile is
bound to the *other* slot, never whether it is bound to this one.
auto_connect_configured_slots activates from profile.auto_connect_slot
and never writes connection_slots, so a positive rule would break
reconnect for every auto-connected profile. For the same reason the
probe guard only refuses a change of profile, so reconnecting the
profile the operations slot already holds still works during a task.
The operations guard has no production writer yet (F-74, audit P3-7),
so it is inert at runtime. It ships with a test that flips the guard
directly rather than as an unexercised branch.
Refs: F-19 (audit P2-4).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 00:16:33 +08:00
|
|
|
guards: State<'_, RuntimeGuards>,
|
2026-07-20 11:31:41 +08:00
|
|
|
request: DisconnectConnectionSlotRequest,
|
|
|
|
|
) -> Result<(), RuntimeCommandError> {
|
fix(net): reject one profile occupying both runtime slots
probe_connection_slot never consulted the slot assignment table, so the
same profile could be activated into both runtime slots at once. That
bypasses the ProfileAlreadyAssigned policy the database enforces, and
both slots then race to overwrite the same sticky_session_id.
Enforce it in three places. The runtime invariant lives inside
activate_slot's claim phase, so it also covers startup auto-connect,
which calls activate_slot directly and would bypass a command-layer
check. The command adds a cross-check against connection_slots. And the
operations switch guard now covers probe and disconnect, not just slot
assignment.
Both rules are deliberately negative — they ask whether the profile is
bound to the *other* slot, never whether it is bound to this one.
auto_connect_configured_slots activates from profile.auto_connect_slot
and never writes connection_slots, so a positive rule would break
reconnect for every auto-connected profile. For the same reason the
probe guard only refuses a change of profile, so reconnecting the
profile the operations slot already holds still works during a task.
The operations guard has no production writer yet (F-74, audit P3-7),
so it is inert at runtime. It ships with a test that flips the guard
directly rather than as an unexercised branch.
Refs: F-19 (audit P2-4).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 00:16:33 +08:00
|
|
|
ensure_operations_runtime_change_allowed(&guards, request.slot, None, None)?;
|
2026-07-20 11:31:41 +08:00
|
|
|
runtime.deactivate_slot(request.slot).await
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[tauri::command]
|
2026-07-20 12:08:06 +08:00
|
|
|
pub async fn cancel_connection_slot_message(
|
|
|
|
|
runtime: State<'_, DualSlotRuntime>,
|
|
|
|
|
request: DisconnectConnectionSlotRequest,
|
|
|
|
|
) -> Result<(), RuntimeCommandError> {
|
|
|
|
|
runtime.cancel_slot_message(request.slot).await
|
|
|
|
|
}
|
2026-07-20 14:32:07 +08:00
|
|
|
#[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(
|
2026-07-22 02:52:31 +08:00
|
|
|
database: State<'_, ApplicationDatabase>,
|
2026-07-20 14:32:07 +08:00
|
|
|
runtime: State<'_, DualSlotRuntime>,
|
|
|
|
|
request: SwitchChatSessionRequest,
|
|
|
|
|
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
|
2026-07-22 02:52:31 +08:00
|
|
|
let snapshot = runtime
|
2026-07-20 14:32:07 +08:00
|
|
|
.switch_slot_session(request.slot, request.session_id)
|
2026-07-22 02:52:31 +08:00
|
|
|
.await?;
|
|
|
|
|
persist_session_identity(&database, &snapshot);
|
|
|
|
|
Ok(snapshot)
|
2026-07-20 14:32:07 +08:00
|
|
|
}
|
|
|
|
|
|
2026-07-20 13:30:29 +08:00
|
|
|
#[tauri::command]
|
|
|
|
|
pub async fn connection_slot_capabilities(
|
|
|
|
|
runtime: State<'_, DualSlotRuntime>,
|
|
|
|
|
request: SlotCapabilitiesRequest,
|
|
|
|
|
) -> Result<desktop_protocol::AstrBotCapabilitySnapshot, RuntimeCommandError> {
|
|
|
|
|
runtime.slot_capabilities(request.slot).await
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-22 02:52:31 +08:00
|
|
|
#[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 })
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-20 13:30:29 +08:00
|
|
|
#[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
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-20 12:25:08 +08:00
|
|
|
#[tauri::command]
|
2026-07-20 11:31:41 +08:00
|
|
|
pub async fn send_connection_slot_message(
|
|
|
|
|
database: State<'_, ApplicationDatabase>,
|
|
|
|
|
runtime: State<'_, DualSlotRuntime>,
|
|
|
|
|
request: SendConnectionSlotMessageRequest,
|
|
|
|
|
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
|
2026-07-21 14:43:14 +08:00
|
|
|
let message_for_history = request.message.clone();
|
2026-07-20 11:31:41 +08:00
|
|
|
let status = runtime.status().await;
|
2026-07-21 14:43:14 +08:00
|
|
|
let initial_session = match request.slot {
|
2026-07-20 11:31:41 +08:00
|
|
|
SlotKind::Companion => status.companion,
|
|
|
|
|
SlotKind::Operations => status.operations,
|
|
|
|
|
};
|
|
|
|
|
if let (Some(profile_id), Some(server_instance_id), Some(session_id)) = (
|
2026-07-21 14:43:14 +08:00
|
|
|
initial_session.profile_id.as_deref(),
|
|
|
|
|
initial_session.server_instance_id.as_deref(),
|
|
|
|
|
initial_session.active_session_id.as_deref(),
|
2026-07-20 11:31:41 +08:00
|
|
|
) {
|
|
|
|
|
let _ = database.upsert_chat_message(
|
|
|
|
|
"local-default",
|
|
|
|
|
profile_id,
|
2026-07-21 14:43:14 +08:00
|
|
|
slot_name(request.slot),
|
2026-07-20 11:31:41 +08:00
|
|
|
server_instance_id,
|
|
|
|
|
None,
|
|
|
|
|
session_id,
|
|
|
|
|
&format!("local-{}", uuid::Uuid::new_v4()),
|
|
|
|
|
"user",
|
2026-07-21 14:43:14 +08:00
|
|
|
&message_for_history,
|
2026-07-20 11:31:41 +08:00
|
|
|
false,
|
|
|
|
|
false,
|
|
|
|
|
);
|
|
|
|
|
}
|
2026-07-21 14:43:14 +08:00
|
|
|
let result = runtime
|
2026-07-20 13:30:29 +08:00
|
|
|
.send_slot_message(
|
|
|
|
|
request.slot,
|
|
|
|
|
request.message,
|
|
|
|
|
request.config_id,
|
|
|
|
|
request.attachments,
|
|
|
|
|
)
|
2026-07-21 14:43:14 +08:00
|
|
|
.await;
|
|
|
|
|
if initial_session.active_session_id.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,
|
|
|
|
|
&format!("local-{}", uuid::Uuid::new_v4()),
|
|
|
|
|
"user",
|
|
|
|
|
&message_for_history,
|
|
|
|
|
false,
|
|
|
|
|
false,
|
|
|
|
|
);
|
|
|
|
|
}
|
2026-07-22 02:52:31 +08:00
|
|
|
if let Ok(snapshot) = &result {
|
|
|
|
|
persist_session_identity(&database, snapshot);
|
|
|
|
|
}
|
2026-07-21 14:43:14 +08:00
|
|
|
result
|
2026-07-20 11:31:41 +08:00
|
|
|
}
|
fix(net): reject one profile occupying both runtime slots
probe_connection_slot never consulted the slot assignment table, so the
same profile could be activated into both runtime slots at once. That
bypasses the ProfileAlreadyAssigned policy the database enforces, and
both slots then race to overwrite the same sticky_session_id.
Enforce it in three places. The runtime invariant lives inside
activate_slot's claim phase, so it also covers startup auto-connect,
which calls activate_slot directly and would bypass a command-layer
check. The command adds a cross-check against connection_slots. And the
operations switch guard now covers probe and disconnect, not just slot
assignment.
Both rules are deliberately negative — they ask whether the profile is
bound to the *other* slot, never whether it is bound to this one.
auto_connect_configured_slots activates from profile.auto_connect_slot
and never writes connection_slots, so a positive rule would break
reconnect for every auto-connected profile. For the same reason the
probe guard only refuses a change of profile, so reconnecting the
profile the operations slot already holds still works during a task.
The operations guard has no production writer yet (F-74, audit P3-7),
so it is inert at runtime. It ships with a test that flips the guard
directly rather than as an unexercised branch.
Refs: F-19 (audit P2-4).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 00:16:33 +08:00
|
|
|
|
|
|
|
|
#[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");
|
|
|
|
|
}
|
|
|
|
|
}
|