feat/p02-dual-connections #3
共有 9 个文件被更改,包括 909 次插入 和 13 次删除
|
|
@ -1,11 +1,12 @@
|
|||
mod profiles;
|
||||
mod slots;
|
||||
|
||||
use std::{path::Path, sync::Mutex, time::Duration};
|
||||
|
||||
use rusqlite::{Connection, OptionalExtension, params};
|
||||
use thiserror::Error;
|
||||
|
||||
pub const CURRENT_SCHEMA_VERSION: u32 = 2;
|
||||
pub const CURRENT_SCHEMA_VERSION: u32 = 3;
|
||||
|
||||
pub struct ApplicationDatabase {
|
||||
store: Mutex<ProfileMessageStore>,
|
||||
|
|
@ -184,6 +185,27 @@ fn migrate(connection: &mut Connection) -> Result<(), DatabaseError> {
|
|||
transaction.commit()?;
|
||||
}
|
||||
|
||||
if found <= 2 {
|
||||
let transaction = connection.transaction()?;
|
||||
transaction.execute_batch(
|
||||
"
|
||||
CREATE TABLE connection_slots (
|
||||
slot TEXT PRIMARY KEY NOT NULL
|
||||
CHECK(slot IN ('companion', 'operations')),
|
||||
profile_id TEXT UNIQUE
|
||||
REFERENCES connection_profiles(id) ON DELETE SET NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
INSERT INTO connection_slots (slot, profile_id, updated_at)
|
||||
VALUES
|
||||
('companion', NULL, '1970-01-01T00:00:00Z'),
|
||||
('operations', NULL, '1970-01-01T00:00:00Z');
|
||||
PRAGMA user_version = 3;
|
||||
",
|
||||
)?;
|
||||
transaction.commit()?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -197,8 +219,14 @@ pub enum DatabaseError {
|
|||
LockPoisoned,
|
||||
#[error("database contains invalid profile data")]
|
||||
InvalidStoredProfile,
|
||||
#[error("database contains invalid connection slot data")]
|
||||
InvalidStoredSlot,
|
||||
#[error("connection profile was not found")]
|
||||
ProfileNotFound,
|
||||
#[error("connection slot was not found")]
|
||||
SlotNotFound,
|
||||
#[error("connection profile is already assigned to another slot")]
|
||||
ProfileAlreadyAssigned,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
@ -277,7 +305,7 @@ mod tests {
|
|||
drop(connection);
|
||||
|
||||
let store = ProfileMessageStore::open(&path).expect("migrate database");
|
||||
assert_eq!(store.schema_version().expect("schema version"), 2);
|
||||
assert_eq!(store.schema_version().expect("schema version"), 3);
|
||||
assert_eq!(
|
||||
store
|
||||
.message_content("profile-a", "server-a", "conversation-a", "message-a")
|
||||
|
|
@ -295,6 +323,76 @@ mod tests {
|
|||
)
|
||||
.expect("query profile table");
|
||||
assert_eq!(profile_table_count, 1);
|
||||
let slot_count: u32 = store
|
||||
.connection
|
||||
.query_row("SELECT COUNT(*) FROM connection_slots", [], |row| {
|
||||
row.get(0)
|
||||
})
|
||||
.expect("query slot rows");
|
||||
assert_eq!(slot_count, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migrates_v2_to_v3_without_losing_profiles() {
|
||||
let directory = tempfile::tempdir().expect("temporary directory");
|
||||
let path = directory.path().join("v2.sqlite3");
|
||||
{
|
||||
let store = ProfileMessageStore::open(&path).expect("create current database");
|
||||
store
|
||||
.connection
|
||||
.execute(
|
||||
"
|
||||
INSERT INTO connection_profiles (
|
||||
id,
|
||||
display_name,
|
||||
role,
|
||||
base_url,
|
||||
authentication_type,
|
||||
created_at,
|
||||
updated_at
|
||||
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
|
||||
",
|
||||
params![
|
||||
"00000000-0000-4000-8000-000000000001",
|
||||
"Preserved Profile",
|
||||
"general",
|
||||
"https://example.test/",
|
||||
"device-token",
|
||||
"2026-07-19T00:00:00Z",
|
||||
"2026-07-19T00:00:00Z",
|
||||
],
|
||||
)
|
||||
.expect("insert profile");
|
||||
store
|
||||
.connection
|
||||
.execute_batch(
|
||||
"
|
||||
DROP TABLE connection_slots;
|
||||
PRAGMA user_version = 2;
|
||||
",
|
||||
)
|
||||
.expect("restore v2 shape");
|
||||
}
|
||||
|
||||
let reopened = ProfileMessageStore::open(&path).expect("migrate v2 database");
|
||||
assert_eq!(reopened.schema_version().expect("schema version"), 3);
|
||||
let profile_count: u32 = reopened
|
||||
.connection
|
||||
.query_row(
|
||||
"SELECT COUNT(*) FROM connection_profiles
|
||||
WHERE id = '00000000-0000-4000-8000-000000000001'",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.expect("query preserved profile");
|
||||
assert_eq!(profile_count, 1);
|
||||
let slot_count: u32 = reopened
|
||||
.connection
|
||||
.query_row("SELECT COUNT(*) FROM connection_slots", [], |row| {
|
||||
row.get(0)
|
||||
})
|
||||
.expect("query slot rows");
|
||||
assert_eq!(slot_count, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -310,7 +408,7 @@ mod tests {
|
|||
assert!(matches!(
|
||||
ProfileMessageStore::open(path),
|
||||
Err(DatabaseError::UnsupportedSchemaVersion {
|
||||
found: 3,
|
||||
found: 4,
|
||||
supported: CURRENT_SCHEMA_VERSION
|
||||
})
|
||||
));
|
||||
|
|
|
|||
291
src-tauri/src/database/slots.rs
普通文件
291
src-tauri/src/database/slots.rs
普通文件
|
|
@ -0,0 +1,291 @@
|
|||
use desktop_protocol::{ActiveSlotKind, ConnectionSlot, ConnectionState};
|
||||
use rusqlite::{OptionalExtension, Row, params};
|
||||
|
||||
use super::{ApplicationDatabase, DatabaseError, ProfileMessageStore};
|
||||
|
||||
impl ApplicationDatabase {
|
||||
pub fn list_connection_slots(&self) -> Result<Vec<ConnectionSlot>, DatabaseError> {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||
.list_connection_slots()
|
||||
}
|
||||
|
||||
pub fn assign_connection_slot(
|
||||
&self,
|
||||
slot: ActiveSlotKind,
|
||||
profile_id: &str,
|
||||
updated_at: &str,
|
||||
) -> Result<ConnectionSlot, DatabaseError> {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||
.set_connection_slot(slot, Some(profile_id), updated_at)
|
||||
}
|
||||
|
||||
pub fn clear_connection_slot(
|
||||
&self,
|
||||
slot: ActiveSlotKind,
|
||||
updated_at: &str,
|
||||
) -> Result<ConnectionSlot, DatabaseError> {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||
.set_connection_slot(slot, None, updated_at)
|
||||
}
|
||||
}
|
||||
|
||||
impl ProfileMessageStore {
|
||||
fn list_connection_slots(&self) -> Result<Vec<ConnectionSlot>, DatabaseError> {
|
||||
let mut statement = self.connection.prepare(
|
||||
"
|
||||
SELECT slots.slot, slots.profile_id, profiles.server_instance_id
|
||||
FROM connection_slots AS slots
|
||||
LEFT JOIN connection_profiles AS profiles
|
||||
ON profiles.id = slots.profile_id
|
||||
ORDER BY CASE slots.slot
|
||||
WHEN 'companion' THEN 0
|
||||
WHEN 'operations' THEN 1
|
||||
ELSE 2
|
||||
END
|
||||
",
|
||||
)?;
|
||||
let mut rows = statement.query([])?;
|
||||
let mut slots = Vec::with_capacity(2);
|
||||
while let Some(row) = rows.next()? {
|
||||
slots.push(slot_from_row(row)?);
|
||||
}
|
||||
if slots.len() != 2 {
|
||||
return Err(DatabaseError::InvalidStoredSlot);
|
||||
}
|
||||
Ok(slots)
|
||||
}
|
||||
|
||||
fn connection_slot(&self, slot: ActiveSlotKind) -> Result<ConnectionSlot, DatabaseError> {
|
||||
self.connection
|
||||
.query_row(
|
||||
"
|
||||
SELECT slots.slot, slots.profile_id, profiles.server_instance_id
|
||||
FROM connection_slots AS slots
|
||||
LEFT JOIN connection_profiles AS profiles
|
||||
ON profiles.id = slots.profile_id
|
||||
WHERE slots.slot = ?1
|
||||
",
|
||||
params![slot_to_str(slot)],
|
||||
slot_from_row,
|
||||
)
|
||||
.optional()?
|
||||
.ok_or(DatabaseError::SlotNotFound)
|
||||
}
|
||||
|
||||
fn set_connection_slot(
|
||||
&mut self,
|
||||
slot: ActiveSlotKind,
|
||||
profile_id: Option<&str>,
|
||||
updated_at: &str,
|
||||
) -> Result<ConnectionSlot, DatabaseError> {
|
||||
let transaction = self.connection.transaction()?;
|
||||
|
||||
if let Some(profile_id) = profile_id {
|
||||
let profile_exists = transaction
|
||||
.query_row(
|
||||
"SELECT 1 FROM connection_profiles WHERE id = ?1",
|
||||
params![profile_id],
|
||||
|row| row.get::<_, u8>(0),
|
||||
)
|
||||
.optional()?
|
||||
.is_some();
|
||||
if !profile_exists {
|
||||
return Err(DatabaseError::ProfileNotFound);
|
||||
}
|
||||
|
||||
let assigned_slot = transaction
|
||||
.query_row(
|
||||
"SELECT slot FROM connection_slots WHERE profile_id = ?1",
|
||||
params![profile_id],
|
||||
|row| row.get::<_, String>(0),
|
||||
)
|
||||
.optional()?;
|
||||
if assigned_slot
|
||||
.as_deref()
|
||||
.is_some_and(|assigned| assigned != slot_to_str(slot))
|
||||
{
|
||||
return Err(DatabaseError::ProfileAlreadyAssigned);
|
||||
}
|
||||
}
|
||||
|
||||
let changed = transaction.execute(
|
||||
"
|
||||
UPDATE connection_slots
|
||||
SET profile_id = ?2,
|
||||
updated_at = ?3
|
||||
WHERE slot = ?1
|
||||
",
|
||||
params![slot_to_str(slot), profile_id, updated_at],
|
||||
)?;
|
||||
if changed == 0 {
|
||||
return Err(DatabaseError::SlotNotFound);
|
||||
}
|
||||
transaction.commit()?;
|
||||
self.connection_slot(slot)
|
||||
}
|
||||
}
|
||||
|
||||
fn slot_from_row(row: &Row<'_>) -> Result<ConnectionSlot, rusqlite::Error> {
|
||||
let slot = match row.get::<_, String>(0)?.as_str() {
|
||||
"companion" => ActiveSlotKind::Companion,
|
||||
"operations" => ActiveSlotKind::Operations,
|
||||
_ => {
|
||||
return Err(rusqlite::Error::FromSqlConversionFailure(
|
||||
0,
|
||||
rusqlite::types::Type::Text,
|
||||
Box::new(DatabaseError::InvalidStoredSlot),
|
||||
));
|
||||
}
|
||||
};
|
||||
Ok(ConnectionSlot {
|
||||
slot,
|
||||
profile_id: row.get(1)?,
|
||||
state: ConnectionState::Disconnected,
|
||||
server_instance_id: row.get(2)?,
|
||||
active_conversation_id: None,
|
||||
unread_count: 0,
|
||||
last_event_id: None,
|
||||
last_connected_at: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn slot_to_str(slot: ActiveSlotKind) -> &'static str {
|
||||
match slot {
|
||||
ActiveSlotKind::Companion => "companion",
|
||||
ActiveSlotKind::Operations => "operations",
|
||||
}
|
||||
}
|
||||
|
||||
#[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,
|
||||
credential_reference: None,
|
||||
allow_insecure_http: false,
|
||||
pinned_certificate_fingerprint: None,
|
||||
auto_connect_slot: None,
|
||||
auto_connect: false,
|
||||
server_instance_id: Some(format!("server-{index}")),
|
||||
server_version: None,
|
||||
protocol_version: None,
|
||||
local_tool_policy_id: None,
|
||||
last_connected_at: None,
|
||||
created_at: "2026-07-19T00:00:00Z".into(),
|
||||
updated_at: "2026-07-19T00:00:00Z".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initializes_assigns_and_clears_two_fixed_slots() {
|
||||
let database = ApplicationDatabase::in_memory().expect("database");
|
||||
let initial = database
|
||||
.list_connection_slots()
|
||||
.expect("list initial slots");
|
||||
assert_eq!(initial.len(), 2);
|
||||
assert_eq!(initial[0].slot, ActiveSlotKind::Companion);
|
||||
assert_eq!(initial[1].slot, ActiveSlotKind::Operations);
|
||||
assert!(initial.iter().all(|slot| slot.profile_id.is_none()));
|
||||
|
||||
let companion = profile(1);
|
||||
let operations = profile(2);
|
||||
database
|
||||
.create_profile(&companion)
|
||||
.expect("create companion profile");
|
||||
database
|
||||
.create_profile(&operations)
|
||||
.expect("create operations profile");
|
||||
|
||||
let assigned_companion = database
|
||||
.assign_connection_slot(
|
||||
ActiveSlotKind::Companion,
|
||||
&companion.id,
|
||||
"2026-07-19T01:00:00Z",
|
||||
)
|
||||
.expect("assign companion");
|
||||
let assigned_operations = database
|
||||
.assign_connection_slot(
|
||||
ActiveSlotKind::Operations,
|
||||
&operations.id,
|
||||
"2026-07-19T01:00:00Z",
|
||||
)
|
||||
.expect("assign operations");
|
||||
assert_eq!(
|
||||
assigned_companion.profile_id.as_deref(),
|
||||
Some(companion.id.as_str())
|
||||
);
|
||||
assert_eq!(
|
||||
assigned_operations.profile_id.as_deref(),
|
||||
Some(operations.id.as_str())
|
||||
);
|
||||
assert_eq!(
|
||||
assigned_operations.server_instance_id.as_deref(),
|
||||
Some("server-2")
|
||||
);
|
||||
|
||||
let cleared = database
|
||||
.clear_connection_slot(ActiveSlotKind::Companion, "2026-07-19T02:00:00Z")
|
||||
.expect("clear companion");
|
||||
assert!(cleared.profile_id.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_one_profile_in_both_slots_and_clears_deleted_profiles() {
|
||||
let database = ApplicationDatabase::in_memory().expect("database");
|
||||
let shared = profile(3);
|
||||
database.create_profile(&shared).expect("create profile");
|
||||
database
|
||||
.assign_connection_slot(
|
||||
ActiveSlotKind::Companion,
|
||||
&shared.id,
|
||||
"2026-07-19T01:00:00Z",
|
||||
)
|
||||
.expect("assign companion");
|
||||
|
||||
assert!(matches!(
|
||||
database.assign_connection_slot(
|
||||
ActiveSlotKind::Operations,
|
||||
&shared.id,
|
||||
"2026-07-19T01:00:00Z",
|
||||
),
|
||||
Err(DatabaseError::ProfileAlreadyAssigned)
|
||||
));
|
||||
|
||||
database.delete_profile(&shared.id).expect("delete profile");
|
||||
assert!(
|
||||
database
|
||||
.list_connection_slots()
|
||||
.expect("list slots")
|
||||
.iter()
|
||||
.all(|slot| slot.profile_id.is_none())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_an_unknown_profile_assignment() {
|
||||
let database = ApplicationDatabase::in_memory().expect("database");
|
||||
assert!(matches!(
|
||||
database.assign_connection_slot(
|
||||
ActiveSlotKind::Operations,
|
||||
"00000000-0000-4000-8000-999999999999",
|
||||
"2026-07-19T01:00:00Z",
|
||||
),
|
||||
Err(DatabaseError::ProfileNotFound)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
|
@ -5,6 +5,7 @@ pub mod logging;
|
|||
pub mod networking;
|
||||
pub mod profiles;
|
||||
pub mod secure_store;
|
||||
pub mod slots;
|
||||
pub mod windows;
|
||||
|
||||
use database::ApplicationDatabase;
|
||||
|
|
@ -92,6 +93,9 @@ pub fn run() {
|
|||
profiles::create_connection_profile,
|
||||
profiles::update_connection_profile,
|
||||
profiles::delete_connection_profile,
|
||||
slots::list_connection_slots,
|
||||
slots::assign_connection_slot,
|
||||
slots::clear_connection_slot,
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("failed to run AstrBot Desktop");
|
||||
|
|
|
|||
188
src-tauri/src/slots.rs
普通文件
188
src-tauri/src/slots.rs
普通文件
|
|
@ -0,0 +1,188 @@
|
|||
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};
|
||||
|
||||
#[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 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>,
|
||||
request: AssignConnectionSlotRequest,
|
||||
) -> Result<ConnectionSlot, SlotCommandError> {
|
||||
assign_slot(&database, request)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn clear_connection_slot(
|
||||
database: tauri::State<'_, ApplicationDatabase>,
|
||||
slot: ActiveSlotKind,
|
||||
) -> Result<ConnectionSlot, SlotCommandError> {
|
||||
clear_slot(&database, slot)
|
||||
}
|
||||
|
||||
fn list_slots(database: &ApplicationDatabase) -> Result<Vec<ConnectionSlot>, SlotCommandError> {
|
||||
database
|
||||
.list_connection_slots()
|
||||
.map_err(SlotCommandError::database)
|
||||
}
|
||||
|
||||
fn assign_slot(
|
||||
database: &ApplicationDatabase,
|
||||
request: AssignConnectionSlotRequest,
|
||||
) -> Result<ConnectionSlot, SlotCommandError> {
|
||||
validate_profile_id(&request.profile_id)?;
|
||||
database
|
||||
.assign_connection_slot(request.slot, &request.profile_id, ×tamp()?)
|
||||
.map_err(SlotCommandError::database)
|
||||
}
|
||||
|
||||
fn clear_slot(
|
||||
database: &ApplicationDatabase,
|
||||
slot: ActiveSlotKind,
|
||||
) -> Result<ConnectionSlot, SlotCommandError> {
|
||||
database
|
||||
.clear_connection_slot(slot, ×tamp()?)
|
||||
.map_err(SlotCommandError::database)
|
||||
}
|
||||
|
||||
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,
|
||||
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,
|
||||
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 companion = profile(1);
|
||||
database.create_profile(&companion).expect("create profile");
|
||||
|
||||
let assigned = assign_slot(
|
||||
&database,
|
||||
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, 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");
|
||||
assert!(
|
||||
assign_slot(
|
||||
&database,
|
||||
AssignConnectionSlotRequest {
|
||||
slot: ActiveSlotKind::Operations,
|
||||
profile_id: "not-a-uuid".into(),
|
||||
},
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
115
src/App.test.tsx
115
src/App.test.tsx
|
|
@ -3,6 +3,11 @@ import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
|||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { App } from "./App";
|
||||
import type {
|
||||
ActiveSlotKind,
|
||||
AssignConnectionSlotRequest,
|
||||
ConnectionSlot,
|
||||
} from "./types/connection";
|
||||
import type {
|
||||
ConnectionProfile,
|
||||
ConnectionProfileInput,
|
||||
|
|
@ -18,9 +23,22 @@ const bootstrapStatus = {
|
|||
platform: "windows",
|
||||
rustCore: "ready",
|
||||
protocolVersion: "desktop-v1alpha1",
|
||||
databaseSchemaVersion: 2,
|
||||
databaseSchemaVersion: 3,
|
||||
};
|
||||
|
||||
const emptySlots: ConnectionSlot[] = [
|
||||
{
|
||||
slot: "companion",
|
||||
state: "disconnected",
|
||||
unreadCount: 0,
|
||||
},
|
||||
{
|
||||
slot: "operations",
|
||||
state: "disconnected",
|
||||
unreadCount: 0,
|
||||
},
|
||||
];
|
||||
|
||||
describe("App", () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(invoke).mockImplementation(async (command) => {
|
||||
|
|
@ -30,6 +48,9 @@ describe("App", () => {
|
|||
if (command === "list_connection_profiles") {
|
||||
return [];
|
||||
}
|
||||
if (command === "list_connection_slots") {
|
||||
return emptySlots;
|
||||
}
|
||||
throw new Error(`Unexpected command: ${command}`);
|
||||
});
|
||||
});
|
||||
|
|
@ -53,6 +74,9 @@ describe("App", () => {
|
|||
if (command === "list_connection_profiles") {
|
||||
return [];
|
||||
}
|
||||
if (command === "list_connection_slots") {
|
||||
return emptySlots;
|
||||
}
|
||||
throw new Error(`Unexpected command: ${command}`);
|
||||
});
|
||||
|
||||
|
|
@ -71,6 +95,9 @@ describe("App", () => {
|
|||
if (command === "list_connection_profiles") {
|
||||
return profiles;
|
||||
}
|
||||
if (command === "list_connection_slots") {
|
||||
return emptySlots;
|
||||
}
|
||||
if (command === "create_connection_profile") {
|
||||
const { request } = args as { request: ConnectionProfileInput };
|
||||
const created: ConnectionProfile = {
|
||||
|
|
@ -155,4 +182,90 @@ describe("App", () => {
|
|||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("assigns different profiles to the two fixed slots", async () => {
|
||||
const profiles: ConnectionProfile[] = [
|
||||
{
|
||||
id: "2bdedc10-d804-4da5-8e92-39dd7f175d7a",
|
||||
displayName: "陪伴实例",
|
||||
role: "companion",
|
||||
baseUrl: "https://companion.example.test/",
|
||||
authenticationType: "device-token",
|
||||
allowInsecureHttp: false,
|
||||
autoConnect: false,
|
||||
createdAt: "2026-07-19T02:00:00Z",
|
||||
updatedAt: "2026-07-19T02:00:00Z",
|
||||
},
|
||||
{
|
||||
id: "f272aef0-0a89-4f98-b950-b2f1f309631b",
|
||||
displayName: "运维实例",
|
||||
role: "operations",
|
||||
baseUrl: "https://operations.example.test/",
|
||||
authenticationType: "api-key",
|
||||
allowInsecureHttp: false,
|
||||
autoConnect: false,
|
||||
createdAt: "2026-07-19T02:00:00Z",
|
||||
updatedAt: "2026-07-19T02:00:00Z",
|
||||
},
|
||||
];
|
||||
let slots = emptySlots;
|
||||
|
||||
vi.mocked(invoke).mockImplementation(async (command, args) => {
|
||||
if (command === "bootstrap_status") {
|
||||
return bootstrapStatus;
|
||||
}
|
||||
if (command === "list_connection_profiles") {
|
||||
return profiles;
|
||||
}
|
||||
if (command === "list_connection_slots") {
|
||||
return slots;
|
||||
}
|
||||
if (command === "assign_connection_slot") {
|
||||
const { request } = args as { request: AssignConnectionSlotRequest };
|
||||
const saved: ConnectionSlot = {
|
||||
slot: request.slot,
|
||||
profileId: request.profileId,
|
||||
state: "disconnected",
|
||||
unreadCount: 0,
|
||||
};
|
||||
slots = slots.map((slot) =>
|
||||
slot.slot === request.slot ? saved : slot,
|
||||
);
|
||||
return saved;
|
||||
}
|
||||
if (command === "clear_connection_slot") {
|
||||
const { slot } = args as { slot: ActiveSlotKind };
|
||||
const saved: ConnectionSlot = {
|
||||
slot,
|
||||
state: "disconnected",
|
||||
unreadCount: 0,
|
||||
};
|
||||
slots = slots.map((item) => (item.slot === slot ? saved : item));
|
||||
return saved;
|
||||
}
|
||||
throw new Error(`Unexpected command: ${command}`);
|
||||
});
|
||||
|
||||
render(<App />);
|
||||
|
||||
fireEvent.change(await screen.findByLabelText("陪伴 Profile"), {
|
||||
target: { value: profiles[0].id },
|
||||
});
|
||||
expect(
|
||||
await screen.findByText("已将陪伴实例分配到陪伴槽位。"),
|
||||
).toBeInTheDocument();
|
||||
|
||||
fireEvent.change(screen.getByLabelText("运维 Profile"), {
|
||||
target: { value: profiles[1].id },
|
||||
});
|
||||
expect(
|
||||
await screen.findByText("已将运维实例分配到运维槽位。"),
|
||||
).toBeInTheDocument();
|
||||
expect(invoke).toHaveBeenCalledWith("assign_connection_slot", {
|
||||
request: {
|
||||
slot: "operations",
|
||||
profileId: profiles[1].id,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ const initialStatus: BootstrapStatus = {
|
|||
platform: "unknown",
|
||||
rustCore: "pending",
|
||||
protocolVersion: "desktop-v1alpha1",
|
||||
databaseSchemaVersion: 2,
|
||||
databaseSchemaVersion: 3,
|
||||
};
|
||||
|
||||
export function App() {
|
||||
|
|
@ -33,7 +33,7 @@ export function App() {
|
|||
return (
|
||||
<main className="app-shell">
|
||||
<header className="hero">
|
||||
<p className="eyebrow">P01 · foundation</p>
|
||||
<p className="eyebrow">P02 · dual connections</p>
|
||||
<h1>AstrBot Desktop</h1>
|
||||
<p className="subtitle">
|
||||
双实例陪伴与本机助手的安全 Windows 客户端工程底座。
|
||||
|
|
|
|||
|
|
@ -1,6 +1,13 @@
|
|||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { useCallback, useEffect, useState, type FormEvent } from "react";
|
||||
|
||||
import {
|
||||
connectionSlotListSchema,
|
||||
connectionSlotSchema,
|
||||
type ActiveSlotKind,
|
||||
type AssignConnectionSlotRequest,
|
||||
type ConnectionSlot,
|
||||
} from "../../types/connection";
|
||||
import {
|
||||
connectionProfileListSchema,
|
||||
connectionProfileSchema,
|
||||
|
|
@ -33,6 +40,7 @@ const emptyForm: ProfileFormState = {
|
|||
|
||||
export function ProfileManager() {
|
||||
const [profiles, setProfiles] = useState<ConnectionProfile[]>([]);
|
||||
const [slots, setSlots] = useState<ConnectionSlot[]>([]);
|
||||
const [form, setForm] = useState<ProfileFormState>(emptyForm);
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
|
@ -41,8 +49,12 @@ export function ProfileManager() {
|
|||
|
||||
const loadProfiles = useCallback(async () => {
|
||||
try {
|
||||
const result = await invoke<unknown>("list_connection_profiles");
|
||||
setProfiles(connectionProfileListSchema.parse(result));
|
||||
const [profileResult, slotResult] = await Promise.all([
|
||||
invoke<unknown>("list_connection_profiles"),
|
||||
invoke<unknown>("list_connection_slots"),
|
||||
]);
|
||||
setProfiles(connectionProfileListSchema.parse(profileResult));
|
||||
setSlots(connectionSlotListSchema.parse(slotResult));
|
||||
setError(null);
|
||||
} catch (reason) {
|
||||
setError(`Profile storage unavailable: ${errorMessage(reason)}`);
|
||||
|
|
@ -123,6 +135,13 @@ export function ProfileManager() {
|
|||
setProfiles((current) =>
|
||||
current.filter((item) => item.id !== profile.id),
|
||||
);
|
||||
setSlots((current) =>
|
||||
current.map((slot) =>
|
||||
slot.profileId === profile.id
|
||||
? { ...slot, profileId: undefined, serverInstanceId: undefined }
|
||||
: slot,
|
||||
),
|
||||
);
|
||||
if (editingId === profile.id) {
|
||||
resetForm();
|
||||
}
|
||||
|
|
@ -134,6 +153,36 @@ export function ProfileManager() {
|
|||
}
|
||||
}
|
||||
|
||||
async function updateSlot(slot: ActiveSlotKind, profileId: string) {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setNotice(null);
|
||||
try {
|
||||
const result = profileId
|
||||
? await invoke<unknown>("assign_connection_slot", {
|
||||
request: {
|
||||
slot,
|
||||
profileId,
|
||||
} satisfies AssignConnectionSlotRequest,
|
||||
})
|
||||
: await invoke<unknown>("clear_connection_slot", { slot });
|
||||
const saved = connectionSlotSchema.parse(result);
|
||||
setSlots((current) =>
|
||||
current.map((item) => (item.slot === saved.slot ? saved : item)),
|
||||
);
|
||||
const profile = profiles.find((item) => item.id === saved.profileId);
|
||||
setNotice(
|
||||
profile
|
||||
? `已将${profile.displayName}分配到${slotLabel(slot)}槽位。`
|
||||
: `已清空${slotLabel(slot)}槽位。`,
|
||||
);
|
||||
} catch (reason) {
|
||||
setError(`Slot update failed: ${errorMessage(reason)}`);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
function resetForm() {
|
||||
setEditingId(null);
|
||||
setForm(emptyForm);
|
||||
|
|
@ -143,7 +192,7 @@ export function ProfileManager() {
|
|||
<section className="profile-manager" aria-labelledby="profile-heading">
|
||||
<div className="section-heading">
|
||||
<div>
|
||||
<p className="eyebrow">P01 · foundation</p>
|
||||
<p className="eyebrow">P02 · dual connections</p>
|
||||
<h2 id="profile-heading">连接 Profile</h2>
|
||||
</div>
|
||||
<p>
|
||||
|
|
@ -152,6 +201,52 @@ export function ProfileManager() {
|
|||
</p>
|
||||
</div>
|
||||
|
||||
<div className="slot-grid" aria-label="活动连接槽位">
|
||||
{slots.map((slot) => (
|
||||
<article className="slot-card" key={slot.slot}>
|
||||
<div>
|
||||
<span>{slotLabel(slot.slot)}槽位</span>
|
||||
<strong>{connectionStateLabel(slot.state)}</strong>
|
||||
</div>
|
||||
<label>
|
||||
<span>{slotLabel(slot.slot)} Profile</span>
|
||||
<select
|
||||
aria-label={`${slotLabel(slot.slot)} Profile`}
|
||||
disabled={busy}
|
||||
value={slot.profileId ?? ""}
|
||||
onChange={(event) =>
|
||||
void updateSlot(slot.slot, event.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">未分配</option>
|
||||
{profiles.map((profile) => (
|
||||
<option
|
||||
key={profile.id}
|
||||
value={profile.id}
|
||||
disabled={slots.some(
|
||||
(other) =>
|
||||
other.slot !== slot.slot &&
|
||||
other.profileId === profile.id,
|
||||
)}
|
||||
>
|
||||
{profile.displayName} · {roleLabel(profile.role)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<p>
|
||||
{slot.serverInstanceId
|
||||
? `服务器:${slot.serverInstanceId}`
|
||||
: "当前仅保存本地槽位归属,尚未启动网络连接。"}
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<p className="slot-boundary-note">
|
||||
槽位分配不会授予本机工具权限,也不会读取凭据;正式连接激活将在协议与凭据生命周期确认后启用。
|
||||
</p>
|
||||
|
||||
<div className="profile-layout">
|
||||
<form className="profile-form" onSubmit={submitProfile}>
|
||||
<h3>{editingId ? "编辑 Profile" : "新建 Profile"}</h3>
|
||||
|
|
@ -270,7 +365,8 @@ export function ProfileManager() {
|
|||
</label>
|
||||
|
||||
<p className="form-note">
|
||||
槽位分配、自动连接和连接切换保护将在 P02 实现。
|
||||
槽位分配已由 Rust 和 SQLite 约束;自动连接与运行中切换保护将在后续
|
||||
P02 增量实现。
|
||||
</p>
|
||||
|
||||
<div className="button-row">
|
||||
|
|
@ -380,6 +476,14 @@ function roleLabel(role: ProfileRole) {
|
|||
}
|
||||
}
|
||||
|
||||
function slotLabel(slot: ActiveSlotKind) {
|
||||
return slot === "companion" ? "陪伴" : "运维";
|
||||
}
|
||||
|
||||
function connectionStateLabel(state: ConnectionSlot["state"]) {
|
||||
return state === "disconnected" ? "未连接" : state;
|
||||
}
|
||||
|
||||
function errorMessage(reason: unknown) {
|
||||
if (reason instanceof Error) {
|
||||
return reason.message;
|
||||
|
|
|
|||
|
|
@ -164,6 +164,50 @@ h1 {
|
|||
gap: 1rem;
|
||||
}
|
||||
|
||||
.slot-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.slot-card {
|
||||
display: grid;
|
||||
gap: 0.9rem;
|
||||
padding: 1rem;
|
||||
border: 1px solid rgb(106 163 255 / 35%);
|
||||
border-radius: 0.9rem;
|
||||
background: rgb(18 48 84 / 72%);
|
||||
}
|
||||
|
||||
.slot-card > div {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.slot-card > div span,
|
||||
.slot-card label > span {
|
||||
color: #8db9ff;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.slot-card label {
|
||||
display: grid;
|
||||
gap: 0.45rem;
|
||||
}
|
||||
|
||||
.slot-card p,
|
||||
.slot-boundary-note {
|
||||
margin: 0;
|
||||
color: #aebfda;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.slot-boundary-note {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.profile-form,
|
||||
.profile-list {
|
||||
padding: 1.2rem;
|
||||
|
|
@ -305,7 +349,8 @@ select:focus {
|
|||
|
||||
.profile-form,
|
||||
.profile-list,
|
||||
.profile-card {
|
||||
.profile-card,
|
||||
.slot-card {
|
||||
background: rgb(245 249 255 / 90%);
|
||||
}
|
||||
|
||||
|
|
@ -327,14 +372,17 @@ select:focus {
|
|||
.section-heading > p,
|
||||
.form-note,
|
||||
.empty-state,
|
||||
.profile-card p {
|
||||
.profile-card p,
|
||||
.slot-card p,
|
||||
.slot-boundary-note {
|
||||
color: #405775;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.section-heading,
|
||||
.profile-layout {
|
||||
.profile-layout,
|
||||
.slot-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
|
|
|
|||
50
src/types/connection.ts
普通文件
50
src/types/connection.ts
普通文件
|
|
@ -0,0 +1,50 @@
|
|||
import { z } from "zod";
|
||||
|
||||
export const activeSlotKindSchema = z.enum(["companion", "operations"]);
|
||||
|
||||
export const connectionStateSchema = z.enum([
|
||||
"disconnected",
|
||||
"connecting",
|
||||
"authenticating",
|
||||
"syncing",
|
||||
"connected",
|
||||
"reconnecting",
|
||||
"authExpired",
|
||||
"incompatible",
|
||||
"serverUnavailable",
|
||||
"offline",
|
||||
"certificateChanged",
|
||||
"fatalError",
|
||||
]);
|
||||
|
||||
export const connectionSlotSchema = z
|
||||
.object({
|
||||
slot: activeSlotKindSchema,
|
||||
profileId: z.uuid().optional(),
|
||||
state: connectionStateSchema,
|
||||
serverInstanceId: z.string().min(1).optional(),
|
||||
activeConversationId: z.string().min(1).optional(),
|
||||
unreadCount: z.number().int().nonnegative(),
|
||||
lastEventId: z.string().min(1).optional(),
|
||||
lastConnectedAt: z.string().min(1).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const connectionSlotListSchema = z
|
||||
.array(connectionSlotSchema)
|
||||
.length(2)
|
||||
.refine(
|
||||
(slots) =>
|
||||
new Set(slots.map((slot) => slot.slot)).size === 2 &&
|
||||
slots.some((slot) => slot.slot === "companion") &&
|
||||
slots.some((slot) => slot.slot === "operations"),
|
||||
"Both fixed connection slots are required.",
|
||||
);
|
||||
|
||||
export type ActiveSlotKind = z.infer<typeof activeSlotKindSchema>;
|
||||
export type ConnectionSlot = z.infer<typeof connectionSlotSchema>;
|
||||
|
||||
export interface AssignConnectionSlotRequest {
|
||||
slot: ActiveSlotKind;
|
||||
profileId: string;
|
||||
}
|
||||
正在加载…
添加表格
在新工单中引用