feat/p02-dual-connections #3

已合并
YokiiroBW 已将来自 feat/p02-dual-connections 的 31 提交合并入 main 2026-07-21 14:40:19 +08:00
共有 15 个文件被更改,包括 1069 次插入 和 92 次删除
仅显示提交 34a563c65b 的更改 - 显示所有提交

查看文件

@ -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

查看文件

@ -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.

查看文件

@ -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.

查看文件

@ -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.

查看文件

@ -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.

查看文件

@ -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<ConnectionPolicyStatus, String> {
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,

279
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<String>,
pub display_names: Vec<String>,
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<DuplicateServerInstanceWarning>,
}
pub fn duplicate_server_instance_warnings(
profiles: &[ConnectionProfile],
) -> Vec<DuplicateServerInstanceWarning> {
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<Vec<DuplicateServerInstanceWarning>, 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<ActiveSlotKind>,
) -> 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::<Vec<_>>();
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<ActiveSlotKind>,
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()]
);
}
}

查看文件

@ -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<String>,
#[serde(default)]
pub auto_connect: bool,
#[serde(default)]
pub auto_connect_slot: Option<ActiveSlotKind>,
}
#[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<ConnectionProfile, ProfileCommandError> {
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());
}
}

查看文件

@ -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<HashSet<String>>,
}
#[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<String>,
}
impl RuntimeGuards {
pub fn new() -> Self {
Self::default()
}
pub fn begin_operations_task(
&self,
task_id: impl Into<String>,
) -> 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<bool, RuntimeGuardError> {
let mut tasks = self
.operations_tasks
.lock()
.map_err(|_| RuntimeGuardError::LockPoisoned)?;
Ok(tasks.remove(task_id))
}
pub fn operations_switch_locked(&self) -> Result<bool, RuntimeGuardError> {
let tasks = self
.operations_tasks
.lock()
.map_err(|_| RuntimeGuardError::LockPoisoned)?;
Ok(!tasks.is_empty())
}
pub fn operations_switch_status(
&self,
) -> Result<OperationsSwitchGuardStatus, RuntimeGuardError> {
let tasks = self
.operations_tasks
.lock()
.map_err(|_| RuntimeGuardError::LockPoisoned)?;
let mut active_task_ids = tasks.iter().cloned().collect::<Vec<_>>();
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"));
}
}

查看文件

@ -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<ConnectionSlot, SlotCommandError> {
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<ConnectionSlot, SlotCommandError> {
clear_slot(&database, slot)
clear_slot(&database, &guards, slot)
}
fn list_slots(database: &ApplicationDatabase) -> Result<Vec<ConnectionSlot>, SlotCommandError> {
@ -80,9 +90,11 @@ fn list_slots(database: &ApplicationDatabase) -> Result<Vec<ConnectionSlot>, Slo
fn assign_slot(
database: &ApplicationDatabase,
guards: &RuntimeGuards,
request: AssignConnectionSlotRequest,
) -> Result<ConnectionSlot, SlotCommandError> {
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, &timestamp()?)
.map_err(SlotCommandError::database)
@ -90,13 +102,40 @@ fn assign_slot(
fn clear_slot(
database: &ApplicationDatabase,
guards: &RuntimeGuards,
slot: ActiveSlotKind,
) -> Result<ConnectionSlot, SlotCommandError> {
ensure_operations_switch_allowed(guards, slot, None)?;
database
.clear_connection_slot(slot, &timestamp()?)
.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");
}
}

查看文件

@ -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(<App />);
@ -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(<App />);
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(<App />);
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();
});
});

查看文件

@ -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<ConnectionProfile[]>([]);
const [slots, setSlots] = useState<ConnectionSlot[]>([]);
const [policy, setPolicy] = useState<ConnectionPolicyStatus>(emptyPolicy);
const [form, setForm] = useState<ProfileFormState>(emptyForm);
const [editingId, setEditingId] = useState<string | null>(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<unknown>("list_connection_profiles"),
invoke<unknown>("list_connection_slots"),
invoke<unknown>("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<unknown>("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() {
<span>{slotLabel(slot.slot)} Profile</span>
<select
aria-label={`${slotLabel(slot.slot)} Profile`}
disabled={busy}
disabled={
busy ||
(slot.slot === "operations" && policy.operationsSwitchLocked)
}
value={slot.profileId ?? ""}
onChange={(event) =>
void updateSlot(slot.slot, event.target.value)
@ -239,6 +271,12 @@ export function ProfileManager() {
? `服务器:${slot.serverInstanceId}`
: "当前仅保存本地槽位归属,尚未启动网络连接。"}
</p>
{slot.slot === "operations" && policy.operationsSwitchLocked ? (
<p className="warning-inline">
运维任务进行中,已锁定运维槽位切换(
{policy.activeOperationsTaskCount} 个活动任务)。
</p>
) : null}
</article>
))}
</div>
@ -247,6 +285,21 @@ export function ProfileManager() {
槽位分配不会授予本机工具权限,也不会读取凭据;正式连接激活将在协议与凭据生命周期确认后启用。
</p>
{policy.duplicateServerInstanceWarnings.length > 0 ? (
<div
className="warning-banner"
role="status"
aria-label="重复服务器实例提示"
>
{policy.duplicateServerInstanceWarnings.map((warning) => (
<p key={warning.serverInstanceId}>
服务器实例 {warning.serverInstanceId} 被多个 Profile 引用:
{warning.displayNames.join("、")}。它们保持独立,不会静默合并。
</p>
))}
</div>
) : null}
<div className="profile-layout">
<form className="profile-form" onSubmit={submitProfile}>
<h3>{editingId ? "编辑 Profile" : "新建 Profile"}</h3>
@ -364,9 +417,47 @@ export function ProfileManager() {
<span>明确允许不安全 HTTP(仅限受信任网络)</span>
</label>
<label className="checkbox-field">
<input
name="autoConnect"
type="checkbox"
checked={form.autoConnect}
onChange={(event) =>
setForm((current) => ({
...current,
autoConnect: event.target.checked,
autoConnectSlot: event.target.checked
? current.autoConnectSlot || "companion"
: "",
}))
}
/>
<span>启动时自动连接(不会在本阶段真正建立网络会话)</span>
</label>
<label>
<span>自动连接槽位</span>
<select
name="autoConnectSlot"
aria-label="自动连接槽位"
disabled={!form.autoConnect}
value={form.autoConnectSlot}
onChange={(event) =>
setForm((current) => ({
...current,
autoConnectSlot: event.target.value as "" | ActiveSlotKind,
}))
}
>
<option value="">不自动连接</option>
<option value="companion">陪伴槽位</option>
<option value="operations">运维槽位</option>
</select>
</label>
<p className="form-note">
槽位分配已由 Rust 和 SQLite 约束;自动连接与运行中切换保护将在后续
P02 增量实现。
自动连接配置最多两个 Profile,且槽位不可重复;真正的 REST/SSE
激活仍需等待协议与凭据边界确认。
</p>
<div className="button-row">
@ -387,7 +478,7 @@ export function ProfileManager() {
</form>
<div className="profile-list" aria-label="已保存 Profile">
<h3>已保存 ({profiles.length})</h3>
<h3>已保存({profiles.length})</h3>
{profiles.length === 0 ? (
<p className="empty-state">尚未保存 Profile。</p>
) : (
@ -405,6 +496,14 @@ export function ProfileManager() {
{" · "}
{profile.credentialReference ? "已登记" : "待登记"}
</p>
<p>
{profile.autoConnect
? `自动连接:${slotLabel(profile.autoConnectSlot ?? "companion")}`
: "自动连接:关闭"}
{profile.serverInstanceId
? ` · 服务器 ${profile.serverInstanceId}`
: ""}
</p>
<div className="button-row">
<button
type="button"
@ -456,6 +555,10 @@ function toProfileInput(form: ProfileFormState): ConnectionProfileInput {
authenticationType: form.authenticationType,
allowInsecureHttp: form.allowInsecureHttp,
pinnedCertificateFingerprint: fingerprint || undefined,
autoConnect: form.autoConnect,
autoConnectSlot: form.autoConnect
? form.autoConnectSlot || undefined
: undefined,
};
}

查看文件

@ -324,6 +324,34 @@ select:focus {
background: rgb(20 83 57 / 45%);
}
.warning-banner,
.warning-inline {
border: 1px solid rgb(255 196 96 / 48%);
color: #ffe4b0;
background: rgb(94 63 16 / 48%);
}
.warning-banner {
margin: 0 0 1rem;
padding: 1rem;
border-radius: 0.8rem;
}
.warning-banner p {
margin: 0;
}
.warning-banner p + p {
margin-top: 0.55rem;
}
.warning-inline {
margin: 0;
padding: 0.65rem 0.75rem;
border-radius: 0.65rem;
font-size: 0.88rem;
}
@media (prefers-color-scheme: light) {
:root {
color: #102039;

查看文件

@ -41,8 +41,34 @@ export const connectionSlotListSchema = z
"Both fixed connection slots are required.",
);
export const duplicateServerInstanceWarningSchema = z
.object({
code: z.literal("duplicateServerInstance"),
serverInstanceId: z.string().min(1),
profileIds: z.array(z.uuid()).min(2),
displayNames: z.array(z.string().min(1)).min(2),
message: z.string().min(1),
})
.strict();
export const connectionPolicyStatusSchema = z
.object({
operationsSwitchLocked: z.boolean(),
activeOperationsTaskCount: z.number().int().nonnegative(),
duplicateServerInstanceWarnings: z.array(
duplicateServerInstanceWarningSchema,
),
})
.strict();
export type ActiveSlotKind = z.infer<typeof activeSlotKindSchema>;
export type ConnectionSlot = z.infer<typeof connectionSlotSchema>;
export type ConnectionPolicyStatus = z.infer<
typeof connectionPolicyStatusSchema
>;
export type DuplicateServerInstanceWarning = z.infer<
typeof duplicateServerInstanceWarningSchema
>;
export interface AssignConnectionSlotRequest {
slot: ActiveSlotKind;

查看文件

@ -4,6 +4,8 @@ export const profileRoleSchema = z.enum(["companion", "operations", "general"]);
export const authenticationTypeSchema = z.enum(["device-token", "api-key"]);
export const activeSlotKindSchema = z.enum(["companion", "operations"]);
const optionalIdentifier = z.string().min(1).optional();
export const connectionProfileSchema = z
@ -20,7 +22,7 @@ export const connectionProfileSchema = z
.string()
.regex(/^[A-F0-9]{64}$/)
.optional(),
autoConnectSlot: z.enum(["companion", "operations"]).optional(),
autoConnectSlot: activeSlotKindSchema.optional(),
autoConnect: z.boolean(),
serverInstanceId: optionalIdentifier,
serverVersion: optionalIdentifier,
@ -37,6 +39,7 @@ export const connectionProfileListSchema = z.array(connectionProfileSchema);
export type ProfileRole = z.infer<typeof profileRoleSchema>;
export type AuthenticationType = z.infer<typeof authenticationTypeSchema>;
export type ConnectionProfile = z.infer<typeof connectionProfileSchema>;
export type ActiveSlotKind = z.infer<typeof activeSlotKindSchema>;
export interface ConnectionProfileInput {
displayName: string;
@ -46,6 +49,8 @@ export interface ConnectionProfileInput {
authenticationType: AuthenticationType;
allowInsecureHttp: boolean;
pinnedCertificateFingerprint?: string;
autoConnect: boolean;
autoConnectSlot?: ActiveSlotKind;
}
export interface UpdateConnectionProfileRequest {