From bcc08cf29c8d66007ebee32f6ce098e07ae0d18c Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Sun, 19 Jul 2026 21:37:10 +0800 Subject: [PATCH] feat(connection): add persistent dual slot assignment --- src-tauri/src/database/mod.rs | 104 +++++++- src-tauri/src/database/slots.rs | 291 +++++++++++++++++++++++ src-tauri/src/lib.rs | 4 + src-tauri/src/slots.rs | 188 +++++++++++++++ src/App.test.tsx | 115 ++++++++- src/App.tsx | 4 +- src/features/profiles/ProfileManager.tsx | 112 ++++++++- src/styles.css | 54 ++++- src/types/connection.ts | 50 ++++ 9 files changed, 909 insertions(+), 13 deletions(-) create mode 100644 src-tauri/src/database/slots.rs create mode 100644 src-tauri/src/slots.rs create mode 100644 src/types/connection.ts diff --git a/src-tauri/src/database/mod.rs b/src-tauri/src/database/mod.rs index f837138..8362c5d 100644 --- a/src-tauri/src/database/mod.rs +++ b/src-tauri/src/database/mod.rs @@ -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, @@ -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 }) )); diff --git a/src-tauri/src/database/slots.rs b/src-tauri/src/database/slots.rs new file mode 100644 index 0000000..b47e351 --- /dev/null +++ b/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, 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 { + 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 { + self.store + .lock() + .map_err(|_| DatabaseError::LockPoisoned)? + .set_connection_slot(slot, None, updated_at) + } +} + +impl ProfileMessageStore { + fn list_connection_slots(&self) -> Result, 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 { + 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 { + 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 { + 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) + )); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 1d879e8..613f4be 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -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"); diff --git a/src-tauri/src/slots.rs b/src-tauri/src/slots.rs new file mode 100644 index 0000000..53a6e7d --- /dev/null +++ b/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, SlotCommandError> { + list_slots(&database) +} + +#[tauri::command] +pub fn assign_connection_slot( + database: tauri::State<'_, ApplicationDatabase>, + request: AssignConnectionSlotRequest, +) -> Result { + assign_slot(&database, request) +} + +#[tauri::command] +pub fn clear_connection_slot( + database: tauri::State<'_, ApplicationDatabase>, + slot: ActiveSlotKind, +) -> Result { + clear_slot(&database, slot) +} + +fn list_slots(database: &ApplicationDatabase) -> Result, SlotCommandError> { + database + .list_connection_slots() + .map_err(SlotCommandError::database) +} + +fn assign_slot( + database: &ApplicationDatabase, + request: AssignConnectionSlotRequest, +) -> Result { + 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 { + 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 { + 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::(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() + ); + } +} diff --git a/src/App.test.tsx b/src/App.test.tsx index 0b29552..8d23496 100644 --- a/src/App.test.tsx +++ b/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(); + + 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, + }, + }); + }); }); diff --git a/src/App.tsx b/src/App.tsx index f5199ab..7f0ba09 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -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 (
-

P01 · foundation

+

P02 · dual connections

AstrBot Desktop

双实例陪伴与本机助手的安全 Windows 客户端工程底座。 diff --git a/src/features/profiles/ProfileManager.tsx b/src/features/profiles/ProfileManager.tsx index 16d46d4..659953d 100644 --- a/src/features/profiles/ProfileManager.tsx +++ b/src/features/profiles/ProfileManager.tsx @@ -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([]); + const [slots, setSlots] = useState([]); const [form, setForm] = useState(emptyForm); const [editingId, setEditingId] = useState(null); const [busy, setBusy] = useState(false); @@ -41,8 +49,12 @@ export function ProfileManager() { const loadProfiles = useCallback(async () => { try { - const result = await invoke("list_connection_profiles"); - setProfiles(connectionProfileListSchema.parse(result)); + const [profileResult, slotResult] = await Promise.all([ + invoke("list_connection_profiles"), + invoke("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("assign_connection_slot", { + request: { + slot, + profileId, + } satisfies AssignConnectionSlotRequest, + }) + : await invoke("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() {

-

P01 · foundation

+

P02 · dual connections

连接 Profile

@@ -152,6 +201,52 @@ export function ProfileManager() {

+
+ {slots.map((slot) => ( +
+
+ {slotLabel(slot.slot)}槽位 + {connectionStateLabel(slot.state)} +
+ +

+ {slot.serverInstanceId + ? `服务器:${slot.serverInstanceId}` + : "当前仅保存本地槽位归属,尚未启动网络连接。"} +

+
+ ))} +
+ +

+ 槽位分配不会授予本机工具权限,也不会读取凭据;正式连接激活将在协议与凭据生命周期确认后启用。 +

+

{editingId ? "编辑 Profile" : "新建 Profile"}

@@ -270,7 +365,8 @@ export function ProfileManager() {

- 槽位分配、自动连接和连接切换保护将在 P02 实现。 + 槽位分配已由 Rust 和 SQLite 约束;自动连接与运行中切换保护将在后续 + P02 增量实现。

@@ -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; diff --git a/src/styles.css b/src/styles.css index 0ddf472..1528fa3 100644 --- a/src/styles.css +++ b/src/styles.css @@ -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; } diff --git a/src/types/connection.ts b/src/types/connection.ts new file mode 100644 index 0000000..f7b2579 --- /dev/null +++ b/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; +export type ConnectionSlot = z.infer; + +export interface AssignConnectionSlotRequest { + slot: ActiveSlotKind; + profileId: string; +}