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
+ {slot.slot === "operations" && policy.operationsSwitchLocked ? (
+
+ 运维任务进行中,已锁定运维槽位切换(
+ {policy.activeOperationsTaskCount} 个活动任务)。
+
+ ) : null}
))}
@@ -247,6 +285,21 @@ export function ProfileManager() {
槽位分配不会授予本机工具权限,也不会读取凭据;正式连接激活将在协议与凭据生命周期确认后启用。
+ {policy.duplicateServerInstanceWarnings.length > 0 ? (
+
+ {policy.duplicateServerInstanceWarnings.map((warning) => (
+
+ 服务器实例 {warning.serverInstanceId} 被多个 Profile 引用:
+ {warning.displayNames.join("、")}。它们保持独立,不会静默合并。
+
+ ))}
+
+ ) : null}
+