From 73693b9909f76f1e5020666b8e17d646d006ac03 Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Sun, 19 Jul 2026 21:06:24 +0800 Subject: [PATCH 01/31] docs(p02): start dual connection phase --- docs/decisions/pending-decisions.md | 29 +++++++++++++++++++++++++ docs/implementation-plan.md | 33 ++++++++++++++++++++++++++++- docs/progress.md | 24 +++++++++++++++------ 3 files changed, 79 insertions(+), 7 deletions(-) diff --git a/docs/decisions/pending-decisions.md b/docs/decisions/pending-decisions.md index 4fc3fac..ed777f8 100644 --- a/docs/decisions/pending-decisions.md +++ b/docs/decisions/pending-decisions.md @@ -61,3 +61,32 @@ - Secret boundary: P01 commands accept no Token, password, API Key, Cookie, Authorization header, or NAS credential fields. SQLite stores only non-sensitive metadata and future opaque credential references. - Rationale: AGENTS.md gives the architecture document higher priority, and the selected split keeps runtime connection behavior out of P01. - ADR: `ADR-0004-profile-lifecycle-and-secret-boundary.md`. + +## PD-0009: Real AstrBot Desktop Gateway contract + +- Status: open; does not block local slot persistence or Mock-based tests +- Current contract: repository-local `/desktop/v1` and protocol `1.0` are provisional development contracts created during P00. +- Missing authority: no reviewed real AstrBot Gateway implementation or server-side contract is available for endpoint, error-code, capability, event-retention, ACK, and authentication compatibility. +- Safe interim rule: keep the protocol types and dual Mock Gateway deterministic, but do not claim real AstrBot compatibility or silently adapt to AstrBot internal APIs. +- Stop boundary: changes that would require modifying AstrBot core or bypassing the stable Gateway boundary require explicit review. + +## PD-0010: Credential enrollment and token lifecycle + +- Status: open before production connection activation +- Established boundary: credential values live only in Windows Credential Manager; SQLite stores opaque references; React never receives stored access or refresh tokens. +- Required decision: define enrollment/update/delete failure atomicity, whether user-entered bootstrap credentials may pass once through bounded Tauri IPC without entering React state, and how access/refresh token rotation updates secure storage. +- Safe interim rule: P02 slot persistence accepts no credential values and cannot activate a real connection. + +## PD-0011: Authoritative server identity enrollment + +- Status: open before first real connection activation +- Candidate source: `GET /desktop/v1/server-info` returns `server_instance_id`, matching the architecture and provisional protocol. +- Required decision: define the first-contact confirmation flow, duplicate-instance warning behavior, and whether a changed identity requires a separate Profile or an explicit rebind operation. +- Safe interim rule: never overwrite an existing `server_instance_id` during background connection or reconnection. + +## PD-0012: TLS certificate fingerprint binding + +- Status: open before enabling pinned HTTPS Profiles +- Requirement: a certificate identity change freezes local-tool permission and the affected connection; TLS validation must never be disabled. +- Required decision: select a maintained Rust TLS integration that can inspect the validated peer certificate without installing a permissive verifier, and define first-contact confirmation UX. +- Safe interim rule: preserve validated HTTPS behavior and do not claim certificate pinning until the peer certificate path is implemented and tested. diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index c236918..e4e1164 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -37,7 +37,7 @@ Establish a reproducible Tauri 2 + React + TypeScript + Rust baseline and comple - Forgejo runner labels/jobs remain unverified, so the committed workflow is not claimed successful. - Real UNC execution still requires a user-authorized disposable fixture. -## P01 Foundation (active) +## P01 Foundation (completed) ### Objective @@ -72,3 +72,34 @@ Turn the P00 Spike skeleton into a durable application foundation. Under the pro - Real Tauri development startup reached the Windows executable and was then deliberately terminated. - Windows release and NSIS bundling passed. - Forgejo CI remains unverified because a compatible runner/jobs endpoint is unavailable. + +## P02 Dual Connections (active) + +### Objective + +Add durable companion and operations slot assignment, then build two independent Rust-owned REST/SSE runtimes without weakening the P01 credential and profile boundaries. + +### Ordered work + +1. Persist the two fixed connection slots and enforce that one Profile cannot occupy both slots. +2. Add bounded slot list/assign/clear IPC and a minimal settings UI for slot selection. +3. Add auto-connect validation: at most two Profiles, one per slot, with no duplicate Profile assignment. +4. Add an operations-switch guard that blocks Profile changes while an operations task is active. +5. Add duplicate `server_instance_id` detection and surface a warning without silently merging Profile identity. +6. Define the production credential enrollment/update/delete lifecycle entirely in Rust, with opaque references in SQLite and no secret values returned to React. +7. Review the provisional Gateway contract before enabling real configured connections; keep real AstrBot compatibility explicitly unclaimed until the server contract is available. +8. Implement independent REST discovery/authentication and SSE runtimes, per-Profile cancellation, replay cursors, de-duplication, retry state, and error state. +9. Integrate the existing dual-instance Mock Gateway and verify that one instance failure or auth expiry does not affect the other. +10. Add frontend/Rust/integration coverage, update protocol and progress documents, run the full stage checks, and push the branch normally without merging `main`. + +### Safety gates + +- Slot work must not accept or expose Token, password, API Key, Cookie, Authorization header, or NAS credentials. +- A server-supplied `profile_id` is never trusted; the Rust connection object binds every event to its local Profile and slot. +- A changed `server_instance_id` or certificate identity freezes the affected connection instead of silently rebinding it. +- Companion Profiles never gain local-tool authority from slot assignment alone. +- The provisional `/desktop/v1` contract and Mock Gateway are not evidence of compatibility with an unreviewed real AstrBot Gateway. + +### First increment + +Implement SQLite schema v3 for the two fixed slot assignments, bounded list/assign/clear commands, database and command tests, and a minimal Profile-slot settings surface. This increment intentionally excludes network activation and credential values. diff --git a/docs/progress.md b/docs/progress.md index 9b410b4..4158fb9 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -2,7 +2,7 @@ ## Current phase -P01 foundation is complete and published on `feat/p01-foundation`. The option A boundary is resolved: basic non-sensitive Profile metadata CRUD belongs to P01, while slots and runtime connection behavior remain in P02. +P01 foundation was merged through Forgejo PR #2 at `885abd1`. Development now continues on `feat/p02-dual-connections`, starting with persistent companion/operations slot assignment and its local safety constraints. ## Completed @@ -27,14 +27,23 @@ P01 foundation is complete and published on `feat/p01-foundation`. The option A - Re-ran a real Tauri development startup and reached the Windows executable. - Rebuilt the Windows release executable and NSIS installer. - Recorded the Profile boundary in PD-0008 and ADR-0004. +- Verified Forgejo PR #2 was merged at `885abd1553ed8f1428de7118a6f4b59f7e22a45c`. +- Fast-forwarded local `main` to the same remote merge commit without rewriting history. +- Created `feat/p02-dual-connections` from the updated `main`. +- Re-read `AGENTS.md`, the Forgejo workflow, architecture design, and implementation task documents in full for P02. +- Kept the approved HTTP Forgejo URL repository-local and prevented the machine-wide HTTP-to-SSH rewrite from changing this repository's transport. ## In progress -- No code implementation is in progress; the branch is awaiting Forgejo PR review. +- P02 first increment: SQLite schema v3 and bounded companion/operations slot assignment. +- Protocol/security review for credential lifecycle, real Gateway authentication, authoritative server identity, and certificate-change freeze behavior. ## Remaining -- Create and review the P01 Forgejo PR; do not automatically merge `main`. +- Implement and verify the P02 slot persistence and UI increment. +- Implement auto-connect validation, operations switching protection, and duplicate server-instance warnings. +- Implement the formal Rust-owned credential lifecycle without returning secret values to React. +- Implement two independent configured REST/SSE runtimes only against a reviewed contract; continue using the dual Mock Gateway for deterministic tests. - Run Forgejo CI when a compatible runner is available. - Execute a real UNC transaction only after an authorized disposable fixture is supplied. - Add the combined end-to-end test that keeps configured streams active while the real Tauri window is hidden to tray. @@ -45,7 +54,9 @@ P01 foundation is complete and published on `feat/p01-foundation`. The option A - LAN SSH `192.168.31.210:18086` responds but rejects the available public key. - Approved HTTP Git push remains operational and is not blocked. - Forgejo runner labels/jobs could not be verified; the jobs API endpoint returned 404. -- No blocker remains for the selected P01 scope. +- Real AstrBot Gateway endpoints, authentication semantics, token refresh behavior, and server identity guarantees remain unavailable for compatibility verification. +- Certificate fingerprint extraction/pinning behavior must be designed without disabling TLS validation. +- These protocol items do not block the local P02 slot-persistence increment. ## Test status @@ -64,10 +75,11 @@ P01 foundation is complete and published on `feat/p01-foundation`. The option A ## Current branch -`feat/p01-foundation` +`feat/p02-dual-connections` ## Recent commits +- `885abd1 Merge pull request 'feat(p01): add secure profile foundation and management UI' (#2) from feat/p01-foundation into main` - `b3420e4 Merge pull request 'feat(p00): bootstrap Tauri desktop and validate high-risk spikes' (#1)` - `ed74342 feat(foundation): add persistent bootstrap safeguards` - `6a1eeab docs(p01): record foundation progress and profile boundary` @@ -78,4 +90,4 @@ P01 foundation is complete and published on `feat/p01-foundation`. The option A ## Next step -Open `feat/p01-foundation → main` as a Forgejo PR, review the recorded local verification, and run CI only when a compatible runner is available. +Complete the persistent companion/operations slot increment, run the relevant frontend and Rust checks, commit it as a focused Conventional Commit, and push `feat/p02-dual-connections` normally. From bcc08cf29c8d66007ebee32f6ce098e07ae0d18c Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Sun, 19 Jul 2026 21:37:10 +0800 Subject: [PATCH 02/31] 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; +} From 8eacb3652c1ad0bef6102389cf62c9382866a3cc Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Sun, 19 Jul 2026 21:39:18 +0800 Subject: [PATCH 03/31] docs(p02): record dual slot handoff checkpoint --- docs/implementation-plan.md | 6 +- docs/progress.md | 24 ++++++-- docs/reports/p02-dual-slots-handoff.md | 78 ++++++++++++++++++++++++++ 3 files changed, 102 insertions(+), 6 deletions(-) create mode 100644 docs/reports/p02-dual-slots-handoff.md diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index e4e1164..5140a59 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -100,6 +100,10 @@ Add durable companion and operations slot assignment, then build two independent - Companion Profiles never gain local-tool authority from slot assignment alone. - The provisional `/desktop/v1` contract and Mock Gateway are not evidence of compatibility with an unreviewed real AstrBot Gateway. -### First increment +### First increment (completed) Implement SQLite schema v3 for the two fixed slot assignments, bounded list/assign/clear commands, database and command tests, and a minimal Profile-slot settings surface. This increment intentionally excludes network activation and credential values. + +Completion commit: `bcc08cf feat(connection): add persistent dual slot assignment`. + +The next increment starts with auto-connect validation, operations switching protection, and duplicate server-instance warnings. Development is paused at this checkpoint for cross-machine handoff. diff --git a/docs/progress.md b/docs/progress.md index 4158fb9..25e3777 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -2,7 +2,7 @@ ## Current phase -P01 foundation was merged through Forgejo PR #2 at `885abd1`. Development now continues on `feat/p02-dual-connections`, starting with persistent companion/operations slot assignment and its local safety constraints. +P01 foundation was merged through Forgejo PR #2 at `885abd1`. The first P02 increment is complete on `feat/p02-dual-connections`: persistent companion/operations slot assignment and its local safety constraints. Further implementation is paused for cross-machine handoff. ## Completed @@ -32,15 +32,20 @@ P01 foundation was merged through Forgejo PR #2 at `885abd1`. Development now co - Created `feat/p02-dual-connections` from the updated `main`. - Re-read `AGENTS.md`, the Forgejo workflow, architecture design, and implementation task documents in full for P02. - Kept the approved HTTP Forgejo URL repository-local and prevented the machine-wide HTTP-to-SSH rewrite from changing this repository's transport. +- Added SQLite schema v3 with exactly two fixed connection slot rows. +- Added foreign-key cleanup so deleting a Profile clears its assigned slot. +- Enforced that one Profile cannot occupy both companion and operations slots. +- Added bounded Rust list/assign/clear slot commands that reject unknown fields and malformed Profile IDs. +- Added strict frontend slot Schemas and a minimal settings UI that does not activate network connections or read credentials. +- Added v1-to-current and v2-to-v3 migration coverage, slot persistence tests, duplicate-assignment tests, and frontend slot interaction coverage. +- Completed the first P02 increment in `bcc08cf`. ## In progress -- P02 first increment: SQLite schema v3 and bounded companion/operations slot assignment. -- Protocol/security review for credential lifecycle, real Gateway authentication, authoritative server identity, and certificate-change freeze behavior. +- Source-side handoff packaging only; no additional product implementation is in progress. ## Remaining -- Implement and verify the P02 slot persistence and UI increment. - Implement auto-connect validation, operations switching protection, and duplicate server-instance warnings. - Implement the formal Rust-owned credential lifecycle without returning secret values to React. - Implement two independent configured REST/SSE runtimes only against a reviewed contract; continue using the dual Mock Gateway for deterministic tests. @@ -72,6 +77,13 @@ P01 foundation was merged through Forgejo PR #2 at `885abd1`. Development now co - NSIS installer: passed; `0.1.0-alpha.1`, 3,827,899 bytes. - NSIS SHA-256: `90EB68CDB5EAEDEA675050DA0F30DDAB5E8A0345FF176690A31FA5F66C818740`. - Forgejo CI and a real UNC transaction were not executed and are not claimed successful. +- P02 frontend checks: passed; Prettier, ESLint, TypeScript, 4 Vitest tests, and Vite production build. +- P02 Playwright Chromium: passed 1/1. +- P02 Rust fmt, Clippy with warnings denied, and all-target check: passed. +- P02 Rust workspace tests: passed; 56 normal tests, 2 explicit manual tests ignored. +- P02 v2-to-v3 migration: passed without losing the existing Profile row. +- P02 changed-file secret scan: passed; no private-key header, long Bearer credential, AWS key, GitHub token, or OpenAI-style key pattern was found. +- Tauri development startup and Windows installer build were not rerun for this incremental checkpoint and are not claimed. ## Current branch @@ -79,6 +91,8 @@ P01 foundation was merged through Forgejo PR #2 at `885abd1`. Development now co ## Recent commits +- `bcc08cf feat(connection): add persistent dual slot assignment` +- `73693b9 docs(p02): start dual connection phase` - `885abd1 Merge pull request 'feat(p01): add secure profile foundation and management UI' (#2) from feat/p01-foundation into main` - `b3420e4 Merge pull request 'feat(p00): bootstrap Tauri desktop and validate high-risk spikes' (#1)` - `ed74342 feat(foundation): add persistent bootstrap safeguards` @@ -90,4 +104,4 @@ P01 foundation was merged through Forgejo PR #2 at `885abd1`. Development now co ## Next step -Complete the persistent companion/operations slot increment, run the relevant frontend and Rust checks, commit it as a focused Conventional Commit, and push `feat/p02-dual-connections` normally. +After the handoff destination accepts the exact pushed SHA, continue with auto-connect validation, operations switching protection, and duplicate server-instance warnings. Do not enable real Gateway connections until PD-0009 through PD-0012 are resolved. diff --git a/docs/reports/p02-dual-slots-handoff.md b/docs/reports/p02-dual-slots-handoff.md new file mode 100644 index 0000000..5cae499 --- /dev/null +++ b/docs/reports/p02-dual-slots-handoff.md @@ -0,0 +1,78 @@ +# P02 dual-slot checkpoint and handoff + +Date: 2026-07-19 + +## Source state + +- Branch: `feat/p02-dual-connections` +- Base merge: `885abd1553ed8f1428de7118a6f4b59f7e22a45c` +- Planning commit: `73693b9 docs(p02): start dual connection phase` +- Feature commit: `bcc08cf feat(connection): add persistent dual slot assignment` +- Remote transport: approved ordinary Forgejo HTTP push +- Force push, rebase, and automatic main merge: not used + +## Completed scope + +- SQLite schema v3 creates exactly two fixed rows: `companion` and `operations`. +- A foreign key clears slot assignment when a Profile is deleted. +- A unique Profile constraint prevents one Profile from occupying both slots. +- Rust exposes bounded list, assign, and clear commands. +- Slot requests reject unknown fields, malformed Profile IDs, missing Profiles, and duplicate cross-slot assignment. +- The frontend validates Rust payloads with strict Zod Schemas. +- The settings UI assigns or clears Profiles without activating REST/SSE or reading credentials. +- Stored `server_instance_id` is displayed as metadata only; the increment does not enroll or silently replace server identity. + +## Security boundary + +- No Token, password, API Key, Cookie, Authorization header, or NAS credential field was added to slot IPC. +- Slot assignment alone grants no local-tool permission. +- React does not receive stored credentials. +- Real Gateway compatibility, token refresh, identity enrollment, and certificate pinning remain explicitly unresolved in PD-0009 through PD-0012. + +## Verification + +- `npm.cmd --prefix H:\AstrBot-Desktop run check:frontend`: passed. + - Prettier: passed. + - ESLint: passed. + - TypeScript: passed. + - Vitest: 4 passed. + - Vite production build: passed. +- `npm.cmd --prefix H:\AstrBot-Desktop run test:e2e`: passed, Chromium 1/1. +- `cargo fmt --all --manifest-path H:\AstrBot-Desktop\Cargo.toml -- --check`: passed. +- `cargo clippy --workspace --all-targets --manifest-path H:\AstrBot-Desktop\Cargo.toml -- -D warnings`: passed. +- `cargo check --workspace --all-targets --manifest-path H:\AstrBot-Desktop\Cargo.toml`: passed. +- `cargo test --workspace --manifest-path H:\AstrBot-Desktop\Cargo.toml`: passed, 56 normal tests and 2 explicit manual tests ignored. +- Changed-file high-risk secret pattern scan: passed with no matches. + +Not rerun at this incremental checkpoint: + +- real Tauri development startup; +- Windows release or NSIS build; +- Forgejo Actions; +- real AstrBot Gateway compatibility; +- real UNC file transaction. + +No success is claimed for the items above. + +## Remaining P02 work + +1. Add auto-connect validation for at most two Profiles and one Profile per slot. +2. Block Operations Profile switching while an operations task is active. +3. Add duplicate `server_instance_id` warnings without silent identity merging. +4. Resolve the credential enrollment and rotation lifecycle. +5. Resolve first-contact server identity confirmation. +6. Implement validated certificate fingerprint binding without disabling TLS verification. +7. Only then enable two independent configured REST/SSE runtimes and Mock-backed failure tests. + +## Handoff status + +The first controller status call failed before project lookup because the global dev-handoff config references missing files: + +- identity file: `C:\Users\Administrator\Documents\Codex\2026-07-14\ke\work\ssh\astrbot_vm_ed25519` +- known-hosts file: `C:\Users\Administrator\Documents\Codex\2026-07-14\ke\work\ssh\known_hosts` + +The controller also reported host-key verification failure. No handoff ID, VM workspace, branch, or HAPI session has been created or claimed. + +## Next concrete step + +Restore or reconfigure the authorized VM SSH identity and known-hosts paths, rerun `dev-handoff status`, then send this exact pushed checkpoint to `vm-codex`. If the controller stops at `ready_to_accept`, report that state honestly and wait for the VM worker. From 34a563c65bece479c42fc5f14421d6d07e967c7a Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Mon, 20 Jul 2026 00:49:15 +0800 Subject: [PATCH 04/31] feat(connection): validate auto-connect and guard operations switches Add configuration-only auto-connect rules, runtime operations slot lock while tasks are active, and duplicate server-instance warnings without silent Profile merge. Surface policy status to the settings UI and cover the new boundaries with Rust and Vitest checks. --- CHANGELOG.md | 4 + docs/implementation-plan.md | 6 +- docs/progress.md | 49 ++-- docs/reports/p02-dual-slots-handoff.md | 2 + docs/reports/p02-policy-guards.md | 48 ++++ src-tauri/src/lib.rs | 23 ++ src-tauri/src/policy.rs | 279 +++++++++++++++++++++++ src-tauri/src/profiles.rs | 76 +++++- src-tauri/src/runtime_guards.rs | 117 ++++++++++ src-tauri/src/slots.rs | 112 ++++++++- src/App.test.tsx | 269 ++++++++++++++++++---- src/features/profiles/ProfileManager.tsx | 115 +++++++++- src/styles.css | 28 +++ src/types/connection.ts | 26 +++ src/types/profile.ts | 7 +- 15 files changed, 1069 insertions(+), 92 deletions(-) create mode 100644 docs/reports/p02-policy-guards.md create mode 100644 src-tauri/src/policy.rs create mode 100644 src-tauri/src/runtime_guards.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index c41668a..5f9d0ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,10 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and - Bounded Rust-owned Profile list/create/update/delete IPC with generated UUIDs and timestamps. - Strict frontend ConnectionProfile Schemas and a basic Profile management UI. - Migration, five-Profile CRUD, persistent reopen, secret-field rejection, and browser fallback tests. +- Persistent dual companion/operations slot assignment with SQLite schema v3 and bounded list/assign/clear IPC. +- Auto-connect configuration validation for at most two Profiles with distinct slots. +- Runtime operations switch guard that blocks operations slot changes while an operations task is active. +- Duplicate `server_instance_id` warnings without silently merging Profiles. ### Security diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index 5140a59..06f8699 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -106,4 +106,8 @@ Implement SQLite schema v3 for the two fixed slot assignments, bounded list/assi Completion commit: `bcc08cf feat(connection): add persistent dual slot assignment`. -The next increment starts with auto-connect validation, operations switching protection, and duplicate server-instance warnings. Development is paused at this checkpoint for cross-machine handoff. +### Second increment (completed) + +Implement auto-connect configuration validation, operations switch protection while a runtime operations task is active, and duplicate `server_instance_id` warnings without silent Profile merge. Auto-connect remains configuration-only and does not start REST/SSE. Operations task begin/end stay internal to Rust for this increment. + +The next increment starts with the formal Rust-owned credential lifecycle. Real Gateway activation remains blocked until PD-0009 through PD-0012 are resolved. diff --git a/docs/progress.md b/docs/progress.md index 25e3777..2f23687 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -2,7 +2,7 @@ ## Current phase -P01 foundation was merged through Forgejo PR #2 at `885abd1`. The first P02 increment is complete on `feat/p02-dual-connections`: persistent companion/operations slot assignment and its local safety constraints. Further implementation is paused for cross-machine handoff. +P01 foundation was merged through Forgejo PR #2 at `885abd1`. P02 is active on `feat/p02-dual-connections`. The second increment is complete: auto-connect validation, operations switch protection, and duplicate server-instance warnings. Real Gateway activation remains blocked until PD-0009 through PD-0012 are resolved. ## Completed @@ -39,15 +39,22 @@ P01 foundation was merged through Forgejo PR #2 at `885abd1`. The first P02 incr - Added strict frontend slot Schemas and a minimal settings UI that does not activate network connections or read credentials. - Added v1-to-current and v2-to-v3 migration coverage, slot persistence tests, duplicate-assignment tests, and frontend slot interaction coverage. - Completed the first P02 increment in `bcc08cf`. +- Added auto-connect configuration validation: at most two auto-connect Profiles, distinct slots, and slot required only when auto-connect is enabled. +- Added in-process operations switch guard that blocks operations slot assign/clear while a runtime operations task is active; companion remains free. +- Added duplicate `server_instance_id` warnings without silent Profile merge. +- Exposed `connection_policy_status` IPC for lock status and warnings. +- Extended Profile create/update input with non-secret `autoConnect` and `autoConnectSlot` fields. +- Updated Profile UI for auto-connect controls, operations lock messaging, and duplicate-instance banners. +- Added Rust unit coverage for policy, runtime guards, and locked operations slot switches; extended Vitest coverage for auto-connect save, warning display, and operations select disablement. ## In progress -- Source-side handoff packaging only; no additional product implementation is in progress. +- No product implementation is currently in progress after the second P02 increment. ## Remaining -- Implement auto-connect validation, operations switching protection, and duplicate server-instance warnings. - Implement the formal Rust-owned credential lifecycle without returning secret values to React. +- Resolve first-contact server identity confirmation and certificate fingerprint binding without disabling TLS validation. - Implement two independent configured REST/SSE runtimes only against a reviewed contract; continue using the dual Mock Gateway for deterministic tests. - Run Forgejo CI when a compatible runner is available. - Execute a real UNC transaction only after an authorized disposable fixture is supplied. @@ -61,29 +68,18 @@ P01 foundation was merged through Forgejo PR #2 at `885abd1`. The first P02 incr - Forgejo runner labels/jobs could not be verified; the jobs API endpoint returned 404. - Real AstrBot Gateway endpoints, authentication semantics, token refresh behavior, and server identity guarantees remain unavailable for compatibility verification. - Certificate fingerprint extraction/pinning behavior must be designed without disabling TLS validation. -- These protocol items do not block the local P02 slot-persistence increment. +- These protocol items do not block the local P02 policy/guard increment. +- Cross-machine handoff is blocked before controller lookup because the global dev-handoff config references a missing VM identity file and missing known-hosts file; host-key verification also fails. No handoff ID or destination workspace exists. ## Test status -- `npm run check:frontend`: passed; Prettier, ESLint, TypeScript, 3 Vitest tests, and Vite production build. -- `npm run test:e2e`: passed; 1 Chromium smoke test. -- Rust fmt/check/Clippy with warnings denied: passed. -- `cargo test --workspace`: passed; 50 normal tests, 2 explicit manual tests ignored. -- Profile persistence: passed; five Profile CRUD, close/reopen persistence, and v1-to-v2 migration preserve existing messages. -- Secret boundary: passed; unknown Token, password, and API Key input fields are rejected. -- Protocol Schema export: passed; no generated drift. -- Tauri development startup: passed; executable launched, then was deliberately terminated after verification. -- Tauri Windows release executable: passed. -- NSIS installer: passed; `0.1.0-alpha.1`, 3,827,899 bytes. -- NSIS SHA-256: `90EB68CDB5EAEDEA675050DA0F30DDAB5E8A0345FF176690A31FA5F66C818740`. -- Forgejo CI and a real UNC transaction were not executed and are not claimed successful. -- P02 frontend checks: passed; Prettier, ESLint, TypeScript, 4 Vitest tests, and Vite production build. -- P02 Playwright Chromium: passed 1/1. -- P02 Rust fmt, Clippy with warnings denied, and all-target check: passed. -- P02 Rust workspace tests: passed; 56 normal tests, 2 explicit manual tests ignored. -- P02 v2-to-v3 migration: passed without losing the existing Profile row. -- P02 changed-file secret scan: passed; no private-key header, long Bearer credential, AWS key, GitHub token, or OpenAI-style key pattern was found. -- Tauri development startup and Windows installer build were not rerun for this incremental checkpoint and are not claimed. +- Frontend: Prettier, ESLint, TypeScript, 6 Vitest tests, and Vite production build passed. +- Playwright Chromium: passed 1/1. +- Rust fmt and Clippy with warnings denied: passed. +- `cargo test --workspace`: passed; 63 normal tests, 2 explicit manual tests ignored. +- `cargo check --workspace --all-targets`: passed. +- Changed-file secret scan: passed; no private-key header, long Bearer credential, AWS key, GitHub token, or OpenAI-style key pattern was found. +- Real Tauri development startup and Windows installer build were not rerun for this incremental checkpoint and are not claimed. ## Current branch @@ -96,12 +92,7 @@ P01 foundation was merged through Forgejo PR #2 at `885abd1`. The first P02 incr - `885abd1 Merge pull request 'feat(p01): add secure profile foundation and management UI' (#2) from feat/p01-foundation into main` - `b3420e4 Merge pull request 'feat(p00): bootstrap Tauri desktop and validate high-risk spikes' (#1)` - `ed74342 feat(foundation): add persistent bootstrap safeguards` -- `6a1eeab docs(p01): record foundation progress and profile boundary` -- `02fd25a feat(profile): add secure profile persistence and IPC` -- `907a8a3 feat(profile-ui): add basic profile management` -- `5672585 chore(version): set P01 alpha version` -- `2154c3b docs(p01): resolve profile boundary and record verification` ## Next step -After the handoff destination accepts the exact pushed SHA, continue with auto-connect validation, operations switching protection, and duplicate server-instance warnings. Do not enable real Gateway connections until PD-0009 through PD-0012 are resolved. +Implement the formal credential enrollment/update/delete lifecycle entirely in Rust, with opaque references only in SQLite and React. Do not enable real Gateway connections until PD-0009 through PD-0012 are resolved. diff --git a/docs/reports/p02-dual-slots-handoff.md b/docs/reports/p02-dual-slots-handoff.md index 5cae499..08fc943 100644 --- a/docs/reports/p02-dual-slots-handoff.md +++ b/docs/reports/p02-dual-slots-handoff.md @@ -73,6 +73,8 @@ The first controller status call failed before project lookup because the global The controller also reported host-key verification failure. No handoff ID, VM workspace, branch, or HAPI session has been created or claimed. +After the source branch was clean and pushed, the formal `dev-handoff send --approve` call was also attempted with the verified test and secret-scan results. It failed before task creation with the same missing identity and host-key verification error. + ## Next concrete step Restore or reconfigure the authorized VM SSH identity and known-hosts paths, rerun `dev-handoff status`, then send this exact pushed checkpoint to `vm-codex`. If the controller stops at `ready_to_accept`, report that state honestly and wait for the VM worker. diff --git a/docs/reports/p02-policy-guards.md b/docs/reports/p02-policy-guards.md new file mode 100644 index 0000000..869fa57 --- /dev/null +++ b/docs/reports/p02-policy-guards.md @@ -0,0 +1,48 @@ +# P02 policy and operations-switch increment + +Date: 2026-07-20 + +## Source state + +- Branch: `feat/p02-dual-connections` +- Base feature commit: `bcc08cf feat(connection): add persistent dual slot assignment` +- Scope: auto-connect validation, operations switch protection, duplicate server-instance warnings + +## Completed scope + +- Profile create/update accepts non-secret `autoConnect` and `autoConnectSlot`. +- Auto-connect rules: auto-connect requires a slot; no slot when auto-connect is false; at most two auto-connect Profiles; distinct slots. +- `RuntimeGuards` tracks in-process operations tasks and locks operations slot assign/clear while any task remains. +- Companion slot remains mutable while operations work is active. +- Duplicate `server_instance_id` values surface as warnings only; Profiles stay separate. +- `connection_policy_status` returns lock status, active task count, and warnings. +- Profile UI shows auto-connect controls, operations lock messaging, and duplicate-instance banners. + +## Security boundary + +- No Token, password, API Key, Cookie, Authorization header, or NAS credential field was added. +- Auto-connect configuration does not open REST/SSE sessions in this increment. +- Operations begin/end task controls are not exposed as product IPC yet. +- Slot assignment still grants no local-tool permission. +- PD-0009 through PD-0012 remain unresolved; real Gateway activation is not claimed. + +## Verification + +- Frontend Prettier, ESLint, TypeScript, 6 Vitest tests, and Vite production build: passed. +- Playwright Chromium: passed 1/1. +- Rust fmt and Clippy (`-D warnings`): passed. +- `cargo test --workspace`: passed; 63 normal tests, 2 ignored. +- `cargo check --workspace --all-targets`: passed. +- Changed-file secret scan: passed. + +Not rerun for this checkpoint: + +- real Tauri development startup; +- Windows release or NSIS build; +- Forgejo Actions; +- real AstrBot Gateway compatibility; +- real UNC file transaction. + +## Next concrete step + +Implement formal credential enrollment/update/delete entirely in Rust with opaque references only. diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 613f4be..962a10b 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -3,12 +3,16 @@ pub mod diagnostics; pub mod file_transfer; pub mod logging; pub mod networking; +pub mod policy; pub mod profiles; +pub mod runtime_guards; pub mod secure_store; pub mod slots; pub mod windows; use database::ApplicationDatabase; +use policy::ConnectionPolicyStatus; +use runtime_guards::RuntimeGuards; use serde::Serialize; use tauri::{ @@ -44,6 +48,23 @@ fn bootstrap_status( }) } +#[tauri::command] +fn connection_policy_status( + database: tauri::State<'_, ApplicationDatabase>, + guards: tauri::State<'_, RuntimeGuards>, +) -> Result { + let switch = guards + .operations_switch_status() + .map_err(|_| "operations switch guard is unavailable".to_owned())?; + let warnings = policy::list_duplicate_server_instance_warnings(&database) + .map_err(|_| "database status is unavailable".to_owned())?; + Ok(ConnectionPolicyStatus { + operations_switch_locked: switch.locked, + active_operations_task_count: switch.active_task_count, + duplicate_server_instance_warnings: warnings, + }) +} + pub fn run() { logging::init(); @@ -60,6 +81,7 @@ pub fn run() { app.manage(ApplicationDatabase::open( app_data_dir.join("astrbot-desktop.sqlite3"), )?); + app.manage(RuntimeGuards::new()); let show = MenuItem::with_id(app, "show", "Show AstrBot Desktop", true, None::<&str>)?; let quit = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?; @@ -89,6 +111,7 @@ pub fn run() { }) .invoke_handler(tauri::generate_handler![ bootstrap_status, + connection_policy_status, profiles::list_connection_profiles, profiles::create_connection_profile, profiles::update_connection_profile, diff --git a/src-tauri/src/policy.rs b/src-tauri/src/policy.rs new file mode 100644 index 0000000..81245cc --- /dev/null +++ b/src-tauri/src/policy.rs @@ -0,0 +1,279 @@ +use desktop_protocol::{ActiveSlotKind, ConnectionProfile}; +use serde::Serialize; + +use crate::database::{ApplicationDatabase, DatabaseError}; + +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct DuplicateServerInstanceWarning { + pub code: &'static str, + pub server_instance_id: String, + pub profile_ids: Vec, + pub display_names: Vec, + pub message: &'static str, +} + +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct ConnectionPolicyStatus { + pub operations_switch_locked: bool, + pub active_operations_task_count: u32, + pub duplicate_server_instance_warnings: Vec, +} + +pub fn duplicate_server_instance_warnings( + profiles: &[ConnectionProfile], +) -> Vec { + let mut groups: Vec<(String, Vec<&ConnectionProfile>)> = Vec::new(); + + for profile in profiles { + let Some(server_instance_id) = profile + .server_instance_id + .as_deref() + .map(str::trim) + .filter(|value| !value.is_empty()) + else { + continue; + }; + + if let Some((_, members)) = groups + .iter_mut() + .find(|(existing, _)| existing == server_instance_id) + { + members.push(profile); + } else { + groups.push((server_instance_id.to_owned(), vec![profile])); + } + } + + groups + .into_iter() + .filter(|(_, members)| members.len() > 1) + .map(|(server_instance_id, members)| { + let mut ordered = members; + ordered.sort_by(|left, right| { + left.display_name + .cmp(&right.display_name) + .then_with(|| left.id.cmp(&right.id)) + }); + DuplicateServerInstanceWarning { + code: "duplicateServerInstance", + server_instance_id, + profile_ids: ordered.iter().map(|profile| profile.id.clone()).collect(), + display_names: ordered + .iter() + .map(|profile| profile.display_name.clone()) + .collect(), + message: "Multiple saved profiles point at the same server instance. Keep them separate and choose deliberately which profile to assign.", + } + }) + .collect() +} + +pub fn list_duplicate_server_instance_warnings( + database: &ApplicationDatabase, +) -> Result, DatabaseError> { + let profiles = database.list_profiles()?; + Ok(duplicate_server_instance_warnings(&profiles)) +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum AutoConnectValidationError { + SlotRequired, + SlotForbidden, + TooManyAutoConnectProfiles, + DuplicateAutoConnectSlot { slot: ActiveSlotKind }, +} + +impl AutoConnectValidationError { + pub fn message(self) -> &'static str { + match self { + Self::SlotRequired => { + "Automatic connection requires an explicit companion or operations slot." + } + Self::SlotForbidden => { + "A profile that is not set to auto-connect must not declare an auto-connect slot." + } + Self::TooManyAutoConnectProfiles => { + "At most two profiles may be configured for automatic connection." + } + Self::DuplicateAutoConnectSlot { .. } => { + "Two automatic-connection profiles cannot target the same slot." + } + } + } +} + +pub fn validate_auto_connect_configuration( + profiles: &[ConnectionProfile], + profile_id: Option<&str>, + auto_connect: bool, + auto_connect_slot: Option, +) -> Result<(), AutoConnectValidationError> { + if auto_connect { + let Some(slot) = auto_connect_slot else { + return Err(AutoConnectValidationError::SlotRequired); + }; + + let auto_connected = profiles + .iter() + .filter(|profile| profile_id != Some(profile.id.as_str())) + .filter(|profile| profile.auto_connect) + .collect::>(); + + if auto_connected.len() >= 2 { + return Err(AutoConnectValidationError::TooManyAutoConnectProfiles); + } + + if auto_connected + .iter() + .any(|profile| profile.auto_connect_slot == Some(slot)) + { + return Err(AutoConnectValidationError::DuplicateAutoConnectSlot { slot }); + } + } else if auto_connect_slot.is_some() { + return Err(AutoConnectValidationError::SlotForbidden); + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use desktop_protocol::{AstrBotProfileRole, AuthenticationType}; + + use super::*; + + fn profile( + id: &str, + name: &str, + auto_connect: bool, + slot: Option, + server_instance_id: Option<&str>, + ) -> ConnectionProfile { + ConnectionProfile { + id: id.into(), + display_name: name.into(), + role: AstrBotProfileRole::General, + base_url: "https://example.test/".into(), + event_stream_url: None, + authentication_type: AuthenticationType::DeviceToken, + credential_reference: None, + allow_insecure_http: false, + pinned_certificate_fingerprint: None, + auto_connect_slot: slot, + auto_connect, + server_instance_id: server_instance_id.map(str::to_owned), + 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 accepts_two_auto_connect_profiles_on_distinct_slots() { + let existing = vec![profile( + "00000000-0000-4000-8000-000000000001", + "Companion", + true, + Some(ActiveSlotKind::Companion), + None, + )]; + assert!( + validate_auto_connect_configuration( + &existing, + None, + true, + Some(ActiveSlotKind::Operations), + ) + .is_ok() + ); + } + + #[test] + fn rejects_a_third_auto_connect_profile_and_duplicate_slots() { + let existing = vec![ + profile( + "00000000-0000-4000-8000-000000000001", + "Companion", + true, + Some(ActiveSlotKind::Companion), + None, + ), + profile( + "00000000-0000-4000-8000-000000000002", + "Operations", + true, + Some(ActiveSlotKind::Operations), + None, + ), + ]; + assert!(matches!( + validate_auto_connect_configuration( + &existing, + None, + true, + Some(ActiveSlotKind::Companion), + ), + Err(AutoConnectValidationError::TooManyAutoConnectProfiles) + )); + + let one = vec![profile( + "00000000-0000-4000-8000-000000000001", + "Companion", + true, + Some(ActiveSlotKind::Companion), + None, + )]; + assert!(matches!( + validate_auto_connect_configuration(&one, None, true, Some(ActiveSlotKind::Companion),), + Err(AutoConnectValidationError::DuplicateAutoConnectSlot { + slot: ActiveSlotKind::Companion + }) + )); + } + + #[test] + fn reports_duplicate_server_instance_ids_without_merging_profiles() { + let profiles = vec![ + profile( + "00000000-0000-4000-8000-000000000002", + "Beta", + false, + None, + Some("server-shared"), + ), + profile( + "00000000-0000-4000-8000-000000000001", + "Alpha", + false, + None, + Some("server-shared"), + ), + profile( + "00000000-0000-4000-8000-000000000003", + "Gamma", + false, + None, + Some("server-unique"), + ), + ]; + let warnings = duplicate_server_instance_warnings(&profiles); + assert_eq!(warnings.len(), 1); + assert_eq!(warnings[0].server_instance_id, "server-shared"); + assert_eq!( + warnings[0].profile_ids, + vec![ + "00000000-0000-4000-8000-000000000001".to_owned(), + "00000000-0000-4000-8000-000000000002".to_owned(), + ] + ); + assert_eq!( + warnings[0].display_names, + vec!["Alpha".to_owned(), "Beta".to_owned()] + ); + } +} diff --git a/src-tauri/src/profiles.rs b/src-tauri/src/profiles.rs index 22916f4..f7bdf5d 100644 --- a/src-tauri/src/profiles.rs +++ b/src-tauri/src/profiles.rs @@ -1,10 +1,11 @@ -use desktop_protocol::{AstrBotProfileRole, AuthenticationType, ConnectionProfile}; +use desktop_protocol::{ActiveSlotKind, AstrBotProfileRole, AuthenticationType, ConnectionProfile}; use serde::{Deserialize, Serialize}; use time::{OffsetDateTime, format_description::well_known::Rfc3339}; use url::Url; use uuid::Uuid; use crate::database::{ApplicationDatabase, DatabaseError}; +use crate::policy::{self, AutoConnectValidationError}; const MAX_DISPLAY_NAME_CHARS: usize = 80; const MAX_URL_CHARS: usize = 2048; @@ -22,6 +23,10 @@ pub struct ConnectionProfileInput { pub allow_insecure_http: bool, #[serde(default)] pub pinned_certificate_fingerprint: Option, + #[serde(default)] + pub auto_connect: bool, + #[serde(default)] + pub auto_connect_slot: Option, } #[derive(Clone, Debug, Deserialize)] @@ -47,6 +52,13 @@ impl ProfileCommandError { } } + fn auto_connect(error: AutoConnectValidationError) -> Self { + Self { + code: "autoConnectInvalid", + message: error.message(), + } + } + fn database(error: DatabaseError) -> Self { match error { DatabaseError::ProfileNotFound => Self { @@ -105,6 +117,17 @@ fn create_profile( request: ConnectionProfileInput, ) -> Result { let normalized = normalize_input(request)?; + let existing = database + .list_profiles() + .map_err(ProfileCommandError::database)?; + policy::validate_auto_connect_configuration( + &existing, + None, + normalized.auto_connect, + normalized.auto_connect_slot, + ) + .map_err(ProfileCommandError::auto_connect)?; + let now = timestamp()?; let profile = ConnectionProfile { id: Uuid::new_v4().to_string(), @@ -116,8 +139,8 @@ fn create_profile( credential_reference: None, allow_insecure_http: normalized.allow_insecure_http, pinned_certificate_fingerprint: normalized.pinned_certificate_fingerprint, - auto_connect_slot: None, - auto_connect: false, + auto_connect_slot: normalized.auto_connect_slot, + auto_connect: normalized.auto_connect, server_instance_id: None, server_version: None, protocol_version: None, @@ -143,6 +166,17 @@ fn update_profile( .map_err(ProfileCommandError::database)? .ok_or_else(|| ProfileCommandError::database(DatabaseError::ProfileNotFound))?; + let existing = database + .list_profiles() + .map_err(ProfileCommandError::database)?; + policy::validate_auto_connect_configuration( + &existing, + Some(&request.id), + normalized.auto_connect, + normalized.auto_connect_slot, + ) + .map_err(ProfileCommandError::auto_connect)?; + profile.display_name = normalized.display_name; profile.role = normalized.role; profile.base_url = normalized.base_url; @@ -150,6 +184,8 @@ fn update_profile( profile.authentication_type = normalized.authentication_type; profile.allow_insecure_http = normalized.allow_insecure_http; profile.pinned_certificate_fingerprint = normalized.pinned_certificate_fingerprint; + profile.auto_connect = normalized.auto_connect; + profile.auto_connect_slot = normalized.auto_connect_slot; profile.updated_at = timestamp()?; database @@ -197,6 +233,8 @@ fn normalize_input( authentication_type: request.authentication_type, allow_insecure_http: request.allow_insecure_http, pinned_certificate_fingerprint, + auto_connect: request.auto_connect, + auto_connect_slot: request.auto_connect_slot, }) } @@ -290,6 +328,8 @@ mod tests { authentication_type: AuthenticationType::DeviceToken, allow_insecure_http: false, pinned_certificate_fingerprint: None, + auto_connect: false, + auto_connect_slot: None, } } @@ -316,11 +356,15 @@ mod tests { authentication_type: AuthenticationType::ApiKey, allow_insecure_http: false, pinned_certificate_fingerprint: None, + auto_connect: true, + auto_connect_slot: Some(ActiveSlotKind::Companion), }, }, ) .expect("update profile"); assert_eq!(updated.display_name, "Updated"); + assert!(updated.auto_connect); + assert_eq!(updated.auto_connect_slot, Some(ActiveSlotKind::Companion)); assert_eq!(list_profiles(&database).expect("list profiles").len(), 1); delete_profile(&database, &created.id).expect("delete profile"); @@ -350,4 +394,30 @@ mod tests { assert!(result.is_err()); } + + #[test] + fn enforces_auto_connect_slot_rules() { + let database = ApplicationDatabase::in_memory().expect("database"); + let mut companion = request("https://companion.example.test"); + companion.auto_connect = true; + companion.auto_connect_slot = Some(ActiveSlotKind::Companion); + create_profile(&database, companion).expect("create companion auto-connect"); + + let mut duplicate_slot = request("https://second.example.test"); + duplicate_slot.display_name = "Second".into(); + duplicate_slot.auto_connect = true; + duplicate_slot.auto_connect_slot = Some(ActiveSlotKind::Companion); + let error = create_profile(&database, duplicate_slot).expect_err("duplicate slot"); + assert_eq!(error.code, "autoConnectInvalid"); + + let mut missing_slot = request("https://missing-slot.example.test"); + missing_slot.display_name = "Missing Slot".into(); + missing_slot.auto_connect = true; + assert!(create_profile(&database, missing_slot).is_err()); + + let mut slot_without_flag = request("https://slot-only.example.test"); + slot_without_flag.display_name = "Slot Only".into(); + slot_without_flag.auto_connect_slot = Some(ActiveSlotKind::Operations); + assert!(create_profile(&database, slot_without_flag).is_err()); + } } diff --git a/src-tauri/src/runtime_guards.rs b/src-tauri/src/runtime_guards.rs new file mode 100644 index 0000000..834c0be --- /dev/null +++ b/src-tauri/src/runtime_guards.rs @@ -0,0 +1,117 @@ +use std::collections::HashSet; +use std::sync::Mutex; + +use serde::Serialize; + +/// Tracks runtime conditions that gate Profile and slot mutations. +/// +/// This does not execute tools. It only records whether an operations-side +/// task is currently active so slot assignment can refuse unsafe switches. +#[derive(Default)] +pub struct RuntimeGuards { + operations_tasks: Mutex>, +} + +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct OperationsSwitchGuardStatus { + pub locked: bool, + pub active_task_count: u32, + pub active_task_ids: Vec, +} + +impl RuntimeGuards { + pub fn new() -> Self { + Self::default() + } + + pub fn begin_operations_task( + &self, + task_id: impl Into, + ) -> Result<(), RuntimeGuardError> { + let task_id = task_id.into(); + if task_id.trim().is_empty() { + return Err(RuntimeGuardError::InvalidTaskId); + } + + let mut tasks = self + .operations_tasks + .lock() + .map_err(|_| RuntimeGuardError::LockPoisoned)?; + tasks.insert(task_id); + Ok(()) + } + + pub fn end_operations_task(&self, task_id: &str) -> Result { + let mut tasks = self + .operations_tasks + .lock() + .map_err(|_| RuntimeGuardError::LockPoisoned)?; + Ok(tasks.remove(task_id)) + } + + pub fn operations_switch_locked(&self) -> Result { + let tasks = self + .operations_tasks + .lock() + .map_err(|_| RuntimeGuardError::LockPoisoned)?; + Ok(!tasks.is_empty()) + } + + pub fn operations_switch_status( + &self, + ) -> Result { + let tasks = self + .operations_tasks + .lock() + .map_err(|_| RuntimeGuardError::LockPoisoned)?; + let mut active_task_ids = tasks.iter().cloned().collect::>(); + active_task_ids.sort(); + Ok(OperationsSwitchGuardStatus { + locked: !active_task_ids.is_empty(), + active_task_count: active_task_ids.len() as u32, + active_task_ids, + }) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RuntimeGuardError { + InvalidTaskId, + LockPoisoned, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tracks_operations_task_lifecycle() { + let guards = RuntimeGuards::new(); + assert!(!guards.operations_switch_locked().expect("status")); + + guards.begin_operations_task("task-a").expect("begin task"); + assert!(guards.operations_switch_locked().expect("status")); + assert_eq!( + guards + .operations_switch_status() + .expect("status") + .active_task_count, + 1 + ); + + assert!(guards.end_operations_task("task-a").expect("end task")); + assert!(!guards.operations_switch_locked().expect("status")); + } + + #[test] + fn keeps_lock_while_any_operations_task_remains() { + let guards = RuntimeGuards::new(); + guards.begin_operations_task("task-a").expect("begin a"); + guards.begin_operations_task("task-b").expect("begin b"); + assert!(guards.end_operations_task("task-a").expect("end a")); + assert!(guards.operations_switch_locked().expect("status")); + assert!(guards.end_operations_task("task-b").expect("end b")); + assert!(!guards.operations_switch_locked().expect("status")); + } +} diff --git a/src-tauri/src/slots.rs b/src-tauri/src/slots.rs index 53a6e7d..f700d97 100644 --- a/src-tauri/src/slots.rs +++ b/src-tauri/src/slots.rs @@ -4,6 +4,7 @@ use time::{OffsetDateTime, format_description::well_known::Rfc3339}; use uuid::Uuid; use crate::database::{ApplicationDatabase, DatabaseError}; +use crate::runtime_guards::RuntimeGuards; #[derive(Clone, Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -27,6 +28,13 @@ impl SlotCommandError { } } + fn operations_switch_locked() -> Self { + Self { + code: "operationsSwitchLocked", + message: "The operations profile cannot be changed while an operations task is active.", + } + } + fn database(error: DatabaseError) -> Self { match error { DatabaseError::ProfileNotFound => Self { @@ -59,17 +67,19 @@ pub fn list_connection_slots( #[tauri::command] pub fn assign_connection_slot( database: tauri::State<'_, ApplicationDatabase>, + guards: tauri::State<'_, RuntimeGuards>, request: AssignConnectionSlotRequest, ) -> Result { - assign_slot(&database, request) + assign_slot(&database, &guards, request) } #[tauri::command] pub fn clear_connection_slot( database: tauri::State<'_, ApplicationDatabase>, + guards: tauri::State<'_, RuntimeGuards>, slot: ActiveSlotKind, ) -> Result { - clear_slot(&database, slot) + clear_slot(&database, &guards, slot) } fn list_slots(database: &ApplicationDatabase) -> Result, SlotCommandError> { @@ -80,9 +90,11 @@ fn list_slots(database: &ApplicationDatabase) -> Result, Slo fn assign_slot( database: &ApplicationDatabase, + guards: &RuntimeGuards, request: AssignConnectionSlotRequest, ) -> Result { validate_profile_id(&request.profile_id)?; + ensure_operations_switch_allowed(guards, request.slot, Some(request.profile_id.as_str()))?; database .assign_connection_slot(request.slot, &request.profile_id, ×tamp()?) .map_err(SlotCommandError::database) @@ -90,13 +102,40 @@ fn assign_slot( fn clear_slot( database: &ApplicationDatabase, + guards: &RuntimeGuards, slot: ActiveSlotKind, ) -> Result { + ensure_operations_switch_allowed(guards, slot, None)?; database .clear_connection_slot(slot, ×tamp()?) .map_err(SlotCommandError::database) } +fn ensure_operations_switch_allowed( + guards: &RuntimeGuards, + slot: ActiveSlotKind, + next_profile_id: Option<&str>, +) -> Result<(), SlotCommandError> { + if slot != ActiveSlotKind::Operations { + return Ok(()); + } + + let locked = guards + .operations_switch_locked() + .map_err(|_| SlotCommandError { + code: "databaseUnavailable", + message: "The operations switch guard is unavailable.", + })?; + if locked { + return Err(SlotCommandError::operations_switch_locked()); + } + + // Companion may still change while operations work is idle; this check is + // intentionally scoped to the operations slot only. + let _ = next_profile_id; + Ok(()) +} + fn validate_profile_id(id: &str) -> Result<(), SlotCommandError> { if Uuid::parse_str(id).is_err() { return Err(SlotCommandError::validation( @@ -147,11 +186,13 @@ mod tests { #[test] fn assigns_and_clears_slots_through_the_bounded_service() { let database = ApplicationDatabase::in_memory().expect("database"); + let guards = RuntimeGuards::new(); let companion = profile(1); database.create_profile(&companion).expect("create profile"); let assigned = assign_slot( &database, + &guards, AssignConnectionSlotRequest { slot: ActiveSlotKind::Companion, profile_id: companion.id.clone(), @@ -160,7 +201,8 @@ mod tests { .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"); + let cleared = + clear_slot(&database, &guards, ActiveSlotKind::Companion).expect("clear slot"); assert!(cleared.profile_id.is_none()); } @@ -174,9 +216,11 @@ mod tests { assert!(parsed.is_err()); let database = ApplicationDatabase::in_memory().expect("database"); + let guards = RuntimeGuards::new(); assert!( assign_slot( &database, + &guards, AssignConnectionSlotRequest { slot: ActiveSlotKind::Operations, profile_id: "not-a-uuid".into(), @@ -185,4 +229,66 @@ mod tests { .is_err() ); } + + #[test] + fn blocks_operations_slot_changes_while_a_task_is_active() { + let database = ApplicationDatabase::in_memory().expect("database"); + let guards = RuntimeGuards::new(); + let first = profile(1); + let second = profile(2); + database.create_profile(&first).expect("create first"); + database.create_profile(&second).expect("create second"); + assign_slot( + &database, + &guards, + AssignConnectionSlotRequest { + slot: ActiveSlotKind::Operations, + profile_id: first.id.clone(), + }, + ) + .expect("assign operations"); + + guards + .begin_operations_task("ops-task-1") + .expect("begin task"); + + let blocked = assign_slot( + &database, + &guards, + AssignConnectionSlotRequest { + slot: ActiveSlotKind::Operations, + profile_id: second.id.clone(), + }, + ) + .expect_err("operations switch must be blocked"); + assert_eq!(blocked.code, "operationsSwitchLocked"); + + let blocked_clear = clear_slot(&database, &guards, ActiveSlotKind::Operations) + .expect_err("operations clear must be blocked"); + assert_eq!(blocked_clear.code, "operationsSwitchLocked"); + + // Companion remains mutable while operations work is active. + assign_slot( + &database, + &guards, + AssignConnectionSlotRequest { + slot: ActiveSlotKind::Companion, + profile_id: second.id.clone(), + }, + ) + .expect("companion remains assignable"); + + guards.end_operations_task("ops-task-1").expect("end task"); + // Free the second profile from companion before moving it to operations. + clear_slot(&database, &guards, ActiveSlotKind::Companion).expect("clear companion"); + assign_slot( + &database, + &guards, + AssignConnectionSlotRequest { + slot: ActiveSlotKind::Operations, + profile_id: second.id.clone(), + }, + ) + .expect("operations switch after unlock"); + } } diff --git a/src/App.test.tsx b/src/App.test.tsx index 8d23496..ae99cbe 100644 --- a/src/App.test.tsx +++ b/src/App.test.tsx @@ -6,6 +6,7 @@ import { App } from "./App"; import type { ActiveSlotKind, AssignConnectionSlotRequest, + ConnectionPolicyStatus, ConnectionSlot, } from "./types/connection"; import type { @@ -39,20 +40,71 @@ const emptySlots: ConnectionSlot[] = [ }, ]; +const emptyPolicy: ConnectionPolicyStatus = { + operationsSwitchLocked: false, + activeOperationsTaskCount: 0, + duplicateServerInstanceWarnings: [], +}; + +function mockBaseCommands(options?: { + profiles?: ConnectionProfile[]; + slots?: ConnectionSlot[]; + policy?: ConnectionPolicyStatus; +}) { + const profiles = options?.profiles ?? []; + let slots = options?.slots ?? emptySlots; + let policy = options?.policy ?? emptyPolicy; + + 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 === "connection_policy_status") { + return policy; + } + 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}`); + }); + + return { + setPolicy(next: ConnectionPolicyStatus) { + policy = next; + }, + getSlots() { + return slots; + }, + }; +} + describe("App", () => { beforeEach(() => { - vi.mocked(invoke).mockImplementation(async (command) => { - if (command === "bootstrap_status") { - return bootstrapStatus; - } - if (command === "list_connection_profiles") { - return []; - } - if (command === "list_connection_slots") { - return emptySlots; - } - throw new Error(`Unexpected command: ${command}`); - }); + mockBaseCommands(); }); it("renders the verified Rust bootstrap status", async () => { @@ -77,6 +129,9 @@ describe("App", () => { if (command === "list_connection_slots") { return emptySlots; } + if (command === "connection_policy_status") { + return emptyPolicy; + } throw new Error(`Unexpected command: ${command}`); }); @@ -98,12 +153,14 @@ describe("App", () => { if (command === "list_connection_slots") { return emptySlots; } + if (command === "connection_policy_status") { + return emptyPolicy; + } if (command === "create_connection_profile") { const { request } = args as { request: ConnectionProfileInput }; const created: ConnectionProfile = { id: "2bdedc10-d804-4da5-8e92-39dd7f175d7a", ...request, - autoConnect: false, createdAt: "2026-07-18T02:00:00Z", updatedAt: "2026-07-18T02:00:00Z", }; @@ -153,6 +210,14 @@ describe("App", () => { await screen.findByText("已创建 Profile:家庭运维"), ).toBeInTheDocument(); expect(screen.getByLabelText("编辑 家庭运维")).toBeEnabled(); + expect(invoke).toHaveBeenCalledWith( + "create_connection_profile", + expect.objectContaining({ + request: expect.objectContaining({ + autoConnect: false, + }), + }), + ); fireEvent.click(screen.getByLabelText("编辑 家庭运维")); fireEvent.change(screen.getByLabelText("显示名称"), { @@ -208,43 +273,8 @@ describe("App", () => { 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}`); - }); + mockBaseCommands({ profiles }); render(); @@ -268,4 +298,145 @@ describe("App", () => { }, }); }); + + it("saves auto-connect configuration without activating network sessions", async () => { + let profiles: ConnectionProfile[] = []; + 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 emptySlots; + } + if (command === "connection_policy_status") { + return emptyPolicy; + } + if (command === "create_connection_profile") { + const { request } = args as { request: ConnectionProfileInput }; + const created: ConnectionProfile = { + id: "2bdedc10-d804-4da5-8e92-39dd7f175d7a", + ...request, + createdAt: "2026-07-19T03:00:00Z", + updatedAt: "2026-07-19T03:00:00Z", + }; + profiles = [created]; + return created; + } + throw new Error(`Unexpected command: ${command}`); + }); + + render(); + expect(await screen.findByText("尚未保存 Profile。")).toBeInTheDocument(); + + fireEvent.change(screen.getByLabelText("显示名称"), { + target: { value: "自动陪伴" }, + }); + fireEvent.change(screen.getByLabelText("角色"), { + target: { value: "companion" }, + }); + fireEvent.change(screen.getByLabelText("REST 基础 URL"), { + target: { value: "https://companion.example.test" }, + }); + fireEvent.click( + screen.getByLabelText("启动时自动连接(不会在本阶段真正建立网络会话)"), + ); + fireEvent.change(screen.getByLabelText("自动连接槽位"), { + target: { value: "companion" }, + }); + fireEvent.click(screen.getByRole("button", { name: "保存 Profile" })); + + expect( + await screen.findByText("已创建 Profile:自动陪伴"), + ).toBeInTheDocument(); + expect(screen.getByText("自动连接:陪伴")).toBeInTheDocument(); + expect(invoke).toHaveBeenCalledWith("create_connection_profile", { + request: { + displayName: "自动陪伴", + role: "companion", + baseUrl: "https://companion.example.test", + authenticationType: "device-token", + allowInsecureHttp: false, + autoConnect: true, + autoConnectSlot: "companion", + }, + }); + }); + + it("shows duplicate server-instance warnings and locks the operations slot", 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, + serverInstanceId: "server-shared", + 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, + serverInstanceId: "server-shared", + createdAt: "2026-07-19T02:00:00Z", + updatedAt: "2026-07-19T02:00:00Z", + }, + ]; + + mockBaseCommands({ + profiles, + slots: [ + { + slot: "companion", + profileId: profiles[0].id, + state: "disconnected", + unreadCount: 0, + }, + { + slot: "operations", + profileId: profiles[1].id, + state: "disconnected", + unreadCount: 0, + }, + ], + policy: { + operationsSwitchLocked: true, + activeOperationsTaskCount: 1, + duplicateServerInstanceWarnings: [ + { + code: "duplicateServerInstance", + serverInstanceId: "server-shared", + profileIds: [profiles[0].id, profiles[1].id], + displayNames: ["陪伴实例", "运维实例"], + message: + "Multiple saved profiles point at the same server instance. Keep them separate and choose deliberately which profile to assign.", + }, + ], + }, + }); + + render(); + + expect( + await screen.findByLabelText("重复服务器实例提示"), + ).toBeInTheDocument(); + expect( + screen.getByText(/服务器实例 server-shared 被多个 Profile 引用/), + ).toBeInTheDocument(); + expect(screen.getByLabelText("运维 Profile")).toBeDisabled(); + expect(screen.getByLabelText("陪伴 Profile")).toBeEnabled(); + expect( + screen.getByText(/运维任务进行中,已锁定运维槽位切换(\s*1 个活动任务)/), + ).toBeInTheDocument(); + }); }); diff --git a/src/features/profiles/ProfileManager.tsx b/src/features/profiles/ProfileManager.tsx index 659953d..d712945 100644 --- a/src/features/profiles/ProfileManager.tsx +++ b/src/features/profiles/ProfileManager.tsx @@ -2,10 +2,12 @@ import { invoke } from "@tauri-apps/api/core"; import { useCallback, useEffect, useState, type FormEvent } from "react"; import { + connectionPolicyStatusSchema, connectionSlotListSchema, connectionSlotSchema, type ActiveSlotKind, type AssignConnectionSlotRequest, + type ConnectionPolicyStatus, type ConnectionSlot, } from "../../types/connection"; import { @@ -26,6 +28,8 @@ interface ProfileFormState { authenticationType: AuthenticationType; allowInsecureHttp: boolean; pinnedCertificateFingerprint: string; + autoConnect: boolean; + autoConnectSlot: "" | ActiveSlotKind; } const emptyForm: ProfileFormState = { @@ -36,11 +40,20 @@ const emptyForm: ProfileFormState = { authenticationType: "device-token", allowInsecureHttp: false, pinnedCertificateFingerprint: "", + autoConnect: false, + autoConnectSlot: "", +}; + +const emptyPolicy: ConnectionPolicyStatus = { + operationsSwitchLocked: false, + activeOperationsTaskCount: 0, + duplicateServerInstanceWarnings: [], }; export function ProfileManager() { const [profiles, setProfiles] = useState([]); const [slots, setSlots] = useState([]); + const [policy, setPolicy] = useState(emptyPolicy); const [form, setForm] = useState(emptyForm); const [editingId, setEditingId] = useState(null); const [busy, setBusy] = useState(false); @@ -49,12 +62,14 @@ export function ProfileManager() { const loadProfiles = useCallback(async () => { try { - const [profileResult, slotResult] = await Promise.all([ + const [profileResult, slotResult, policyResult] = await Promise.all([ invoke("list_connection_profiles"), invoke("list_connection_slots"), + invoke("connection_policy_status"), ]); setProfiles(connectionProfileListSchema.parse(profileResult)); setSlots(connectionSlotListSchema.parse(slotResult)); + setPolicy(connectionPolicyStatusSchema.parse(policyResult)); setError(null); } catch (reason) { setError(`Profile storage unavailable: ${errorMessage(reason)}`); @@ -90,6 +105,7 @@ export function ProfileManager() { saved, ]), ); + await refreshPolicy(); setNotice( editingId ? `已更新 Profile:${saved.displayName}` @@ -113,6 +129,8 @@ export function ProfileManager() { authenticationType: profile.authenticationType, allowInsecureHttp: profile.allowInsecureHttp, pinnedCertificateFingerprint: profile.pinnedCertificateFingerprint ?? "", + autoConnect: profile.autoConnect, + autoConnectSlot: profile.autoConnectSlot ?? "", }); setError(null); setNotice(null); @@ -121,7 +139,7 @@ export function ProfileManager() { async function deleteProfile(profile: ConnectionProfile) { if ( !window.confirm( - `删除 Profile“${profile.displayName}”?此操作不会删除凭据值,因为 P01 不接触凭据。`, + `删除 Profile“${profile.displayName}”?此操作不会删除凭据值,因为当前阶段不接触凭据。`, ) ) { return; @@ -142,6 +160,7 @@ export function ProfileManager() { : slot, ), ); + await refreshPolicy(); if (editingId === profile.id) { resetForm(); } @@ -170,6 +189,7 @@ export function ProfileManager() { setSlots((current) => current.map((item) => (item.slot === saved.slot ? saved : item)), ); + await refreshPolicy(); const profile = profiles.find((item) => item.id === saved.profileId); setNotice( profile @@ -183,6 +203,15 @@ export function ProfileManager() { } } + async function refreshPolicy() { + try { + const policyResult = await invoke("connection_policy_status"); + setPolicy(connectionPolicyStatusSchema.parse(policyResult)); + } catch { + // Keep the previous policy snapshot when only the refresh fails. + } + } + function resetForm() { setEditingId(null); setForm(emptyForm); @@ -212,7 +241,10 @@ export function ProfileManager() { {slotLabel(slot.slot)} Profile + setForm((current) => ({ + ...current, + autoConnect: event.target.checked, + autoConnectSlot: event.target.checked + ? current.autoConnectSlot || "companion" + : "", + })) + } + /> + 启动时自动连接(不会在本阶段真正建立网络会话) + + + +

- 槽位分配已由 Rust 和 SQLite 约束;自动连接与运行中切换保护将在后续 - P02 增量实现。 + 自动连接配置最多两个 Profile,且槽位不可重复;真正的 REST/SSE + 激活仍需等待协议与凭据边界确认。

@@ -387,7 +478,7 @@ export function ProfileManager() {
-

已保存 ({profiles.length})

+

已保存({profiles.length})

{profiles.length === 0 ? (

尚未保存 Profile。

) : ( @@ -405,6 +496,14 @@ export function ProfileManager() { {" · "} {profile.credentialReference ? "已登记" : "待登记"}

+

+ {profile.autoConnect + ? `自动连接:${slotLabel(profile.autoConnectSlot ?? "companion")}` + : "自动连接:关闭"} + {profile.serverInstanceId + ? ` · 服务器 ${profile.serverInstanceId}` + : ""} +

+
+
); diff --git a/src/features/chat/ChatPanel.tsx b/src/features/chat/ChatPanel.tsx new file mode 100644 index 0000000..c2eea7a --- /dev/null +++ b/src/features/chat/ChatPanel.tsx @@ -0,0 +1,283 @@ +import { invoke } from "@tauri-apps/api/core"; +import { useCallback, useEffect, useMemo, useState } from "react"; + +import { + boundRuntimeEventSchema, + connectionRuntimeStatusSchema, + type BoundRuntimeEvent, + type ChatMessage, + type ChatSlot, + type ConnectionRuntimeStatus, + storedChatMessageSchema, +} from "./types"; + +const emptyStatus: ConnectionRuntimeStatus = { + companion: { slot: "companion", state: "disconnected" }, + operations: { slot: "operations", state: "disconnected" }, +}; + +function payloadString( + event: BoundRuntimeEvent, + key: string, +): string | undefined { + if (!event.payload || typeof event.payload !== "object") return undefined; + const value = (event.payload as Record)[key]; + return typeof value === "string" ? value : undefined; +} + +export function ChatPanel() { + const [status, setStatus] = useState(emptyStatus); + const [messages, setMessages] = useState([]); + const [activeSlot, setActiveSlot] = useState("companion"); + const [draft, setDraft] = useState(""); + const [error, setError] = useState(null); + const activeMessages = useMemo( + () => messages.filter((item) => item.slot === activeSlot), + [messages, activeSlot], + ); + + const refresh = useCallback(async () => { + try { + const result = await invoke("connection_runtime_status"); + setStatus(connectionRuntimeStatusSchema.parse(result)); + setError(null); + return true; + } catch (reason) { + setError(reason instanceof Error ? reason.message : String(reason)); + return false; + } + }, []); + + const drainEvents = useCallback(async () => { + try { + const result = await invoke("drain_connection_runtime_events", { + request: { limit: 64 }, + }); + const events = boundRuntimeEventSchema.array().parse(result); + if (events.length > 0) + setMessages((current) => applyRuntimeEvents(current, events)); + } catch { + // Browser fallback keeps the shell usable without Rust IPC. + } + }, []); + + useEffect(() => { + const snapshot = status[activeSlot]; + if ( + !snapshot.profileId || + !snapshot.serverInstanceId || + !snapshot.activeSessionId + ) + return; + let cancelled = false; + void invoke("load_chat_messages", { + request: { + profileId: snapshot.profileId, + serverInstanceId: snapshot.serverInstanceId, + sessionId: snapshot.activeSessionId, + limit: 100, + }, + }) + .then((result) => { + if (cancelled) return; + const records = storedChatMessageSchema.array().parse(result); + setMessages((current) => { + const otherSlots = current.filter((item) => item.slot !== activeSlot); + const restored = records.map((record) => ({ + id: record.messageId, + slot: record.slot, + role: record.role, + content: record.content, + streaming: record.streaming, + error: record.error, + })); + return otherSlots.concat(restored); + }); + }) + .catch(() => undefined); + return () => { + cancelled = true; + }; + }, [activeSlot, status]); + + useEffect(() => { + let timer: number | undefined; + void refresh().then((available) => { + if (!available) return; + timer = window.setInterval(() => { + void refresh(); + void drainEvents(); + }, 500); + }); + return () => { + if (timer !== undefined) window.clearInterval(timer); + }; + }, [drainEvents, refresh]); + + const send = async () => { + const message = draft.trim(); + if (!message) return; + const id = "local-" + Date.now(); + setDraft(""); + setMessages((current) => + current.concat({ id, slot: activeSlot, role: "user", content: message }), + ); + try { + await invoke("send_connection_slot_message", { + request: { slot: activeSlot, message }, + }); + setError(null); + } catch (reason) { + setError(reason instanceof Error ? reason.message : String(reason)); + setMessages((current) => + current.map((item) => + item.id === id ? { ...item, error: true } : item, + ), + ); + } + }; + + return ( +
+
+
+

Q1 shared chat runtime

+

统一聊天运行时

+

+ 主页面、快速聊天和气泡共享同一套消息状态。 +

+
+
+ {(["companion", "operations"] as const).map((slot) => ( + + ))} +
+
+
+ Profile:{status[activeSlot].profileId ?? "未连接"} + Session:{status[activeSlot].activeSessionId ?? "未建立"} + 状态:{status[activeSlot].state} +
+
+ {activeMessages.length === 0 ? ( +

+ 当前槽位还没有消息。连接 Profile 后即可开始聊天。 +

+ ) : ( + activeMessages.map((message) => ( +
+ + {message.role === "user" + ? "我" + : message.role === "assistant" + ? "AstrBot" + : "系统"} + +

{message.content || "…"}

+ {message.streaming ? 生成中 : null} +
+ )) + )} +
+ {error ?

{error}

: null} +
{ + event.preventDefault(); + void send(); + }} + > +