比较提交
2 提交
73693b9909
...
8eacb3652c
| 作者 | SHA1 | 提交日期 | |
|---|---|---|---|
| 8eacb3652c | |||
| bcc08cf29c |
共有 12 个文件被更改,包括 1011 次插入 和 19 次删除
|
|
@ -100,6 +100,10 @@ Add durable companion and operations slot assignment, then build two independent
|
||||||
- Companion Profiles never gain local-tool authority from slot assignment alone.
|
- Companion Profiles never gain local-tool authority from slot assignment alone.
|
||||||
- The provisional `/desktop/v1` contract and Mock Gateway are not evidence of compatibility with an unreviewed real AstrBot Gateway.
|
- The provisional `/desktop/v1` contract and Mock Gateway are not evidence of compatibility with an unreviewed real AstrBot Gateway.
|
||||||
|
|
||||||
### First increment
|
### First increment (completed)
|
||||||
|
|
||||||
Implement SQLite schema v3 for the two fixed slot assignments, bounded list/assign/clear commands, database and command tests, and a minimal Profile-slot settings surface. This increment intentionally excludes network activation and credential values.
|
Implement SQLite schema v3 for the two fixed slot assignments, bounded list/assign/clear commands, database and command tests, and a minimal Profile-slot settings surface. This increment intentionally excludes network activation and credential values.
|
||||||
|
|
||||||
|
Completion commit: `bcc08cf feat(connection): add persistent dual slot assignment`.
|
||||||
|
|
||||||
|
The next increment starts with auto-connect validation, operations switching protection, and duplicate server-instance warnings. Development is paused at this checkpoint for cross-machine handoff.
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
## Current phase
|
## Current phase
|
||||||
|
|
||||||
P01 foundation was merged through Forgejo PR #2 at `885abd1`. Development now continues on `feat/p02-dual-connections`, starting with persistent companion/operations slot assignment and its local safety constraints.
|
P01 foundation was merged through Forgejo PR #2 at `885abd1`. The first P02 increment is complete on `feat/p02-dual-connections`: persistent companion/operations slot assignment and its local safety constraints. Further implementation is paused for cross-machine handoff.
|
||||||
|
|
||||||
## Completed
|
## Completed
|
||||||
|
|
||||||
|
|
@ -32,15 +32,20 @@ P01 foundation was merged through Forgejo PR #2 at `885abd1`. Development now co
|
||||||
- Created `feat/p02-dual-connections` from the updated `main`.
|
- Created `feat/p02-dual-connections` from the updated `main`.
|
||||||
- Re-read `AGENTS.md`, the Forgejo workflow, architecture design, and implementation task documents in full for P02.
|
- Re-read `AGENTS.md`, the Forgejo workflow, architecture design, and implementation task documents in full for P02.
|
||||||
- Kept the approved HTTP Forgejo URL repository-local and prevented the machine-wide HTTP-to-SSH rewrite from changing this repository's transport.
|
- Kept the approved HTTP Forgejo URL repository-local and prevented the machine-wide HTTP-to-SSH rewrite from changing this repository's transport.
|
||||||
|
- Added SQLite schema v3 with exactly two fixed connection slot rows.
|
||||||
|
- Added foreign-key cleanup so deleting a Profile clears its assigned slot.
|
||||||
|
- Enforced that one Profile cannot occupy both companion and operations slots.
|
||||||
|
- Added bounded Rust list/assign/clear slot commands that reject unknown fields and malformed Profile IDs.
|
||||||
|
- Added strict frontend slot Schemas and a minimal settings UI that does not activate network connections or read credentials.
|
||||||
|
- Added v1-to-current and v2-to-v3 migration coverage, slot persistence tests, duplicate-assignment tests, and frontend slot interaction coverage.
|
||||||
|
- Completed the first P02 increment in `bcc08cf`.
|
||||||
|
|
||||||
## In progress
|
## In progress
|
||||||
|
|
||||||
- P02 first increment: SQLite schema v3 and bounded companion/operations slot assignment.
|
- Source-side handoff packaging only; no additional product implementation is in progress.
|
||||||
- Protocol/security review for credential lifecycle, real Gateway authentication, authoritative server identity, and certificate-change freeze behavior.
|
|
||||||
|
|
||||||
## Remaining
|
## Remaining
|
||||||
|
|
||||||
- Implement and verify the P02 slot persistence and UI increment.
|
|
||||||
- Implement auto-connect validation, operations switching protection, and duplicate server-instance warnings.
|
- Implement auto-connect validation, operations switching protection, and duplicate server-instance warnings.
|
||||||
- Implement the formal Rust-owned credential lifecycle without returning secret values to React.
|
- Implement the formal Rust-owned credential lifecycle without returning secret values to React.
|
||||||
- Implement two independent configured REST/SSE runtimes only against a reviewed contract; continue using the dual Mock Gateway for deterministic tests.
|
- Implement two independent configured REST/SSE runtimes only against a reviewed contract; continue using the dual Mock Gateway for deterministic tests.
|
||||||
|
|
@ -72,6 +77,13 @@ P01 foundation was merged through Forgejo PR #2 at `885abd1`. Development now co
|
||||||
- NSIS installer: passed; `0.1.0-alpha.1`, 3,827,899 bytes.
|
- NSIS installer: passed; `0.1.0-alpha.1`, 3,827,899 bytes.
|
||||||
- NSIS SHA-256: `90EB68CDB5EAEDEA675050DA0F30DDAB5E8A0345FF176690A31FA5F66C818740`.
|
- NSIS SHA-256: `90EB68CDB5EAEDEA675050DA0F30DDAB5E8A0345FF176690A31FA5F66C818740`.
|
||||||
- Forgejo CI and a real UNC transaction were not executed and are not claimed successful.
|
- Forgejo CI and a real UNC transaction were not executed and are not claimed successful.
|
||||||
|
- P02 frontend checks: passed; Prettier, ESLint, TypeScript, 4 Vitest tests, and Vite production build.
|
||||||
|
- P02 Playwright Chromium: passed 1/1.
|
||||||
|
- P02 Rust fmt, Clippy with warnings denied, and all-target check: passed.
|
||||||
|
- P02 Rust workspace tests: passed; 56 normal tests, 2 explicit manual tests ignored.
|
||||||
|
- P02 v2-to-v3 migration: passed without losing the existing Profile row.
|
||||||
|
- P02 changed-file secret scan: passed; no private-key header, long Bearer credential, AWS key, GitHub token, or OpenAI-style key pattern was found.
|
||||||
|
- Tauri development startup and Windows installer build were not rerun for this incremental checkpoint and are not claimed.
|
||||||
|
|
||||||
## Current branch
|
## Current branch
|
||||||
|
|
||||||
|
|
@ -79,6 +91,8 @@ P01 foundation was merged through Forgejo PR #2 at `885abd1`. Development now co
|
||||||
|
|
||||||
## Recent commits
|
## Recent commits
|
||||||
|
|
||||||
|
- `bcc08cf feat(connection): add persistent dual slot assignment`
|
||||||
|
- `73693b9 docs(p02): start dual connection phase`
|
||||||
- `885abd1 Merge pull request 'feat(p01): add secure profile foundation and management UI' (#2) from feat/p01-foundation into main`
|
- `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)`
|
- `b3420e4 Merge pull request 'feat(p00): bootstrap Tauri desktop and validate high-risk spikes' (#1)`
|
||||||
- `ed74342 feat(foundation): add persistent bootstrap safeguards`
|
- `ed74342 feat(foundation): add persistent bootstrap safeguards`
|
||||||
|
|
@ -90,4 +104,4 @@ P01 foundation was merged through Forgejo PR #2 at `885abd1`. Development now co
|
||||||
|
|
||||||
## Next step
|
## Next step
|
||||||
|
|
||||||
Complete the persistent companion/operations slot increment, run the relevant frontend and Rust checks, commit it as a focused Conventional Commit, and push `feat/p02-dual-connections` normally.
|
After the handoff destination accepts the exact pushed SHA, continue with auto-connect validation, operations switching protection, and duplicate server-instance warnings. Do not enable real Gateway connections until PD-0009 through PD-0012 are resolved.
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,78 @@
|
||||||
|
# P02 dual-slot checkpoint and handoff
|
||||||
|
|
||||||
|
Date: 2026-07-19
|
||||||
|
|
||||||
|
## Source state
|
||||||
|
|
||||||
|
- Branch: `feat/p02-dual-connections`
|
||||||
|
- Base merge: `885abd1553ed8f1428de7118a6f4b59f7e22a45c`
|
||||||
|
- Planning commit: `73693b9 docs(p02): start dual connection phase`
|
||||||
|
- Feature commit: `bcc08cf feat(connection): add persistent dual slot assignment`
|
||||||
|
- Remote transport: approved ordinary Forgejo HTTP push
|
||||||
|
- Force push, rebase, and automatic main merge: not used
|
||||||
|
|
||||||
|
## Completed scope
|
||||||
|
|
||||||
|
- SQLite schema v3 creates exactly two fixed rows: `companion` and `operations`.
|
||||||
|
- A foreign key clears slot assignment when a Profile is deleted.
|
||||||
|
- A unique Profile constraint prevents one Profile from occupying both slots.
|
||||||
|
- Rust exposes bounded list, assign, and clear commands.
|
||||||
|
- Slot requests reject unknown fields, malformed Profile IDs, missing Profiles, and duplicate cross-slot assignment.
|
||||||
|
- The frontend validates Rust payloads with strict Zod Schemas.
|
||||||
|
- The settings UI assigns or clears Profiles without activating REST/SSE or reading credentials.
|
||||||
|
- Stored `server_instance_id` is displayed as metadata only; the increment does not enroll or silently replace server identity.
|
||||||
|
|
||||||
|
## Security boundary
|
||||||
|
|
||||||
|
- No Token, password, API Key, Cookie, Authorization header, or NAS credential field was added to slot IPC.
|
||||||
|
- Slot assignment alone grants no local-tool permission.
|
||||||
|
- React does not receive stored credentials.
|
||||||
|
- Real Gateway compatibility, token refresh, identity enrollment, and certificate pinning remain explicitly unresolved in PD-0009 through PD-0012.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
- `npm.cmd --prefix H:\AstrBot-Desktop run check:frontend`: passed.
|
||||||
|
- Prettier: passed.
|
||||||
|
- ESLint: passed.
|
||||||
|
- TypeScript: passed.
|
||||||
|
- Vitest: 4 passed.
|
||||||
|
- Vite production build: passed.
|
||||||
|
- `npm.cmd --prefix H:\AstrBot-Desktop run test:e2e`: passed, Chromium 1/1.
|
||||||
|
- `cargo fmt --all --manifest-path H:\AstrBot-Desktop\Cargo.toml -- --check`: passed.
|
||||||
|
- `cargo clippy --workspace --all-targets --manifest-path H:\AstrBot-Desktop\Cargo.toml -- -D warnings`: passed.
|
||||||
|
- `cargo check --workspace --all-targets --manifest-path H:\AstrBot-Desktop\Cargo.toml`: passed.
|
||||||
|
- `cargo test --workspace --manifest-path H:\AstrBot-Desktop\Cargo.toml`: passed, 56 normal tests and 2 explicit manual tests ignored.
|
||||||
|
- Changed-file high-risk secret pattern scan: passed with no matches.
|
||||||
|
|
||||||
|
Not rerun at this incremental checkpoint:
|
||||||
|
|
||||||
|
- real Tauri development startup;
|
||||||
|
- Windows release or NSIS build;
|
||||||
|
- Forgejo Actions;
|
||||||
|
- real AstrBot Gateway compatibility;
|
||||||
|
- real UNC file transaction.
|
||||||
|
|
||||||
|
No success is claimed for the items above.
|
||||||
|
|
||||||
|
## Remaining P02 work
|
||||||
|
|
||||||
|
1. Add auto-connect validation for at most two Profiles and one Profile per slot.
|
||||||
|
2. Block Operations Profile switching while an operations task is active.
|
||||||
|
3. Add duplicate `server_instance_id` warnings without silent identity merging.
|
||||||
|
4. Resolve the credential enrollment and rotation lifecycle.
|
||||||
|
5. Resolve first-contact server identity confirmation.
|
||||||
|
6. Implement validated certificate fingerprint binding without disabling TLS verification.
|
||||||
|
7. Only then enable two independent configured REST/SSE runtimes and Mock-backed failure tests.
|
||||||
|
|
||||||
|
## Handoff status
|
||||||
|
|
||||||
|
The first controller status call failed before project lookup because the global dev-handoff config references missing files:
|
||||||
|
|
||||||
|
- identity file: `C:\Users\Administrator\Documents\Codex\2026-07-14\ke\work\ssh\astrbot_vm_ed25519`
|
||||||
|
- known-hosts file: `C:\Users\Administrator\Documents\Codex\2026-07-14\ke\work\ssh\known_hosts`
|
||||||
|
|
||||||
|
The controller also reported host-key verification failure. No handoff ID, VM workspace, branch, or HAPI session has been created or claimed.
|
||||||
|
|
||||||
|
## Next concrete step
|
||||||
|
|
||||||
|
Restore or reconfigure the authorized VM SSH identity and known-hosts paths, rerun `dev-handoff status`, then send this exact pushed checkpoint to `vm-codex`. If the controller stops at `ready_to_accept`, report that state honestly and wait for the VM worker.
|
||||||
|
|
@ -1,11 +1,12 @@
|
||||||
mod profiles;
|
mod profiles;
|
||||||
|
mod slots;
|
||||||
|
|
||||||
use std::{path::Path, sync::Mutex, time::Duration};
|
use std::{path::Path, sync::Mutex, time::Duration};
|
||||||
|
|
||||||
use rusqlite::{Connection, OptionalExtension, params};
|
use rusqlite::{Connection, OptionalExtension, params};
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
pub const CURRENT_SCHEMA_VERSION: u32 = 2;
|
pub const CURRENT_SCHEMA_VERSION: u32 = 3;
|
||||||
|
|
||||||
pub struct ApplicationDatabase {
|
pub struct ApplicationDatabase {
|
||||||
store: Mutex<ProfileMessageStore>,
|
store: Mutex<ProfileMessageStore>,
|
||||||
|
|
@ -184,6 +185,27 @@ fn migrate(connection: &mut Connection) -> Result<(), DatabaseError> {
|
||||||
transaction.commit()?;
|
transaction.commit()?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if found <= 2 {
|
||||||
|
let transaction = connection.transaction()?;
|
||||||
|
transaction.execute_batch(
|
||||||
|
"
|
||||||
|
CREATE TABLE connection_slots (
|
||||||
|
slot TEXT PRIMARY KEY NOT NULL
|
||||||
|
CHECK(slot IN ('companion', 'operations')),
|
||||||
|
profile_id TEXT UNIQUE
|
||||||
|
REFERENCES connection_profiles(id) ON DELETE SET NULL,
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
INSERT INTO connection_slots (slot, profile_id, updated_at)
|
||||||
|
VALUES
|
||||||
|
('companion', NULL, '1970-01-01T00:00:00Z'),
|
||||||
|
('operations', NULL, '1970-01-01T00:00:00Z');
|
||||||
|
PRAGMA user_version = 3;
|
||||||
|
",
|
||||||
|
)?;
|
||||||
|
transaction.commit()?;
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -197,8 +219,14 @@ pub enum DatabaseError {
|
||||||
LockPoisoned,
|
LockPoisoned,
|
||||||
#[error("database contains invalid profile data")]
|
#[error("database contains invalid profile data")]
|
||||||
InvalidStoredProfile,
|
InvalidStoredProfile,
|
||||||
|
#[error("database contains invalid connection slot data")]
|
||||||
|
InvalidStoredSlot,
|
||||||
#[error("connection profile was not found")]
|
#[error("connection profile was not found")]
|
||||||
ProfileNotFound,
|
ProfileNotFound,
|
||||||
|
#[error("connection slot was not found")]
|
||||||
|
SlotNotFound,
|
||||||
|
#[error("connection profile is already assigned to another slot")]
|
||||||
|
ProfileAlreadyAssigned,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|
@ -277,7 +305,7 @@ mod tests {
|
||||||
drop(connection);
|
drop(connection);
|
||||||
|
|
||||||
let store = ProfileMessageStore::open(&path).expect("migrate database");
|
let store = ProfileMessageStore::open(&path).expect("migrate database");
|
||||||
assert_eq!(store.schema_version().expect("schema version"), 2);
|
assert_eq!(store.schema_version().expect("schema version"), 3);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
store
|
store
|
||||||
.message_content("profile-a", "server-a", "conversation-a", "message-a")
|
.message_content("profile-a", "server-a", "conversation-a", "message-a")
|
||||||
|
|
@ -295,6 +323,76 @@ mod tests {
|
||||||
)
|
)
|
||||||
.expect("query profile table");
|
.expect("query profile table");
|
||||||
assert_eq!(profile_table_count, 1);
|
assert_eq!(profile_table_count, 1);
|
||||||
|
let slot_count: u32 = store
|
||||||
|
.connection
|
||||||
|
.query_row("SELECT COUNT(*) FROM connection_slots", [], |row| {
|
||||||
|
row.get(0)
|
||||||
|
})
|
||||||
|
.expect("query slot rows");
|
||||||
|
assert_eq!(slot_count, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn migrates_v2_to_v3_without_losing_profiles() {
|
||||||
|
let directory = tempfile::tempdir().expect("temporary directory");
|
||||||
|
let path = directory.path().join("v2.sqlite3");
|
||||||
|
{
|
||||||
|
let store = ProfileMessageStore::open(&path).expect("create current database");
|
||||||
|
store
|
||||||
|
.connection
|
||||||
|
.execute(
|
||||||
|
"
|
||||||
|
INSERT INTO connection_profiles (
|
||||||
|
id,
|
||||||
|
display_name,
|
||||||
|
role,
|
||||||
|
base_url,
|
||||||
|
authentication_type,
|
||||||
|
created_at,
|
||||||
|
updated_at
|
||||||
|
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
|
||||||
|
",
|
||||||
|
params![
|
||||||
|
"00000000-0000-4000-8000-000000000001",
|
||||||
|
"Preserved Profile",
|
||||||
|
"general",
|
||||||
|
"https://example.test/",
|
||||||
|
"device-token",
|
||||||
|
"2026-07-19T00:00:00Z",
|
||||||
|
"2026-07-19T00:00:00Z",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.expect("insert profile");
|
||||||
|
store
|
||||||
|
.connection
|
||||||
|
.execute_batch(
|
||||||
|
"
|
||||||
|
DROP TABLE connection_slots;
|
||||||
|
PRAGMA user_version = 2;
|
||||||
|
",
|
||||||
|
)
|
||||||
|
.expect("restore v2 shape");
|
||||||
|
}
|
||||||
|
|
||||||
|
let reopened = ProfileMessageStore::open(&path).expect("migrate v2 database");
|
||||||
|
assert_eq!(reopened.schema_version().expect("schema version"), 3);
|
||||||
|
let profile_count: u32 = reopened
|
||||||
|
.connection
|
||||||
|
.query_row(
|
||||||
|
"SELECT COUNT(*) FROM connection_profiles
|
||||||
|
WHERE id = '00000000-0000-4000-8000-000000000001'",
|
||||||
|
[],
|
||||||
|
|row| row.get(0),
|
||||||
|
)
|
||||||
|
.expect("query preserved profile");
|
||||||
|
assert_eq!(profile_count, 1);
|
||||||
|
let slot_count: u32 = reopened
|
||||||
|
.connection
|
||||||
|
.query_row("SELECT COUNT(*) FROM connection_slots", [], |row| {
|
||||||
|
row.get(0)
|
||||||
|
})
|
||||||
|
.expect("query slot rows");
|
||||||
|
assert_eq!(slot_count, 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -310,7 +408,7 @@ mod tests {
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
ProfileMessageStore::open(path),
|
ProfileMessageStore::open(path),
|
||||||
Err(DatabaseError::UnsupportedSchemaVersion {
|
Err(DatabaseError::UnsupportedSchemaVersion {
|
||||||
found: 3,
|
found: 4,
|
||||||
supported: CURRENT_SCHEMA_VERSION
|
supported: CURRENT_SCHEMA_VERSION
|
||||||
})
|
})
|
||||||
));
|
));
|
||||||
|
|
|
||||||
291
src-tauri/src/database/slots.rs
普通文件
291
src-tauri/src/database/slots.rs
普通文件
|
|
@ -0,0 +1,291 @@
|
||||||
|
use desktop_protocol::{ActiveSlotKind, ConnectionSlot, ConnectionState};
|
||||||
|
use rusqlite::{OptionalExtension, Row, params};
|
||||||
|
|
||||||
|
use super::{ApplicationDatabase, DatabaseError, ProfileMessageStore};
|
||||||
|
|
||||||
|
impl ApplicationDatabase {
|
||||||
|
pub fn list_connection_slots(&self) -> Result<Vec<ConnectionSlot>, DatabaseError> {
|
||||||
|
self.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||||
|
.list_connection_slots()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn assign_connection_slot(
|
||||||
|
&self,
|
||||||
|
slot: ActiveSlotKind,
|
||||||
|
profile_id: &str,
|
||||||
|
updated_at: &str,
|
||||||
|
) -> Result<ConnectionSlot, DatabaseError> {
|
||||||
|
self.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||||
|
.set_connection_slot(slot, Some(profile_id), updated_at)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear_connection_slot(
|
||||||
|
&self,
|
||||||
|
slot: ActiveSlotKind,
|
||||||
|
updated_at: &str,
|
||||||
|
) -> Result<ConnectionSlot, DatabaseError> {
|
||||||
|
self.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||||
|
.set_connection_slot(slot, None, updated_at)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProfileMessageStore {
|
||||||
|
fn list_connection_slots(&self) -> Result<Vec<ConnectionSlot>, DatabaseError> {
|
||||||
|
let mut statement = self.connection.prepare(
|
||||||
|
"
|
||||||
|
SELECT slots.slot, slots.profile_id, profiles.server_instance_id
|
||||||
|
FROM connection_slots AS slots
|
||||||
|
LEFT JOIN connection_profiles AS profiles
|
||||||
|
ON profiles.id = slots.profile_id
|
||||||
|
ORDER BY CASE slots.slot
|
||||||
|
WHEN 'companion' THEN 0
|
||||||
|
WHEN 'operations' THEN 1
|
||||||
|
ELSE 2
|
||||||
|
END
|
||||||
|
",
|
||||||
|
)?;
|
||||||
|
let mut rows = statement.query([])?;
|
||||||
|
let mut slots = Vec::with_capacity(2);
|
||||||
|
while let Some(row) = rows.next()? {
|
||||||
|
slots.push(slot_from_row(row)?);
|
||||||
|
}
|
||||||
|
if slots.len() != 2 {
|
||||||
|
return Err(DatabaseError::InvalidStoredSlot);
|
||||||
|
}
|
||||||
|
Ok(slots)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn connection_slot(&self, slot: ActiveSlotKind) -> Result<ConnectionSlot, DatabaseError> {
|
||||||
|
self.connection
|
||||||
|
.query_row(
|
||||||
|
"
|
||||||
|
SELECT slots.slot, slots.profile_id, profiles.server_instance_id
|
||||||
|
FROM connection_slots AS slots
|
||||||
|
LEFT JOIN connection_profiles AS profiles
|
||||||
|
ON profiles.id = slots.profile_id
|
||||||
|
WHERE slots.slot = ?1
|
||||||
|
",
|
||||||
|
params![slot_to_str(slot)],
|
||||||
|
slot_from_row,
|
||||||
|
)
|
||||||
|
.optional()?
|
||||||
|
.ok_or(DatabaseError::SlotNotFound)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_connection_slot(
|
||||||
|
&mut self,
|
||||||
|
slot: ActiveSlotKind,
|
||||||
|
profile_id: Option<&str>,
|
||||||
|
updated_at: &str,
|
||||||
|
) -> Result<ConnectionSlot, DatabaseError> {
|
||||||
|
let transaction = self.connection.transaction()?;
|
||||||
|
|
||||||
|
if let Some(profile_id) = profile_id {
|
||||||
|
let profile_exists = transaction
|
||||||
|
.query_row(
|
||||||
|
"SELECT 1 FROM connection_profiles WHERE id = ?1",
|
||||||
|
params![profile_id],
|
||||||
|
|row| row.get::<_, u8>(0),
|
||||||
|
)
|
||||||
|
.optional()?
|
||||||
|
.is_some();
|
||||||
|
if !profile_exists {
|
||||||
|
return Err(DatabaseError::ProfileNotFound);
|
||||||
|
}
|
||||||
|
|
||||||
|
let assigned_slot = transaction
|
||||||
|
.query_row(
|
||||||
|
"SELECT slot FROM connection_slots WHERE profile_id = ?1",
|
||||||
|
params![profile_id],
|
||||||
|
|row| row.get::<_, String>(0),
|
||||||
|
)
|
||||||
|
.optional()?;
|
||||||
|
if assigned_slot
|
||||||
|
.as_deref()
|
||||||
|
.is_some_and(|assigned| assigned != slot_to_str(slot))
|
||||||
|
{
|
||||||
|
return Err(DatabaseError::ProfileAlreadyAssigned);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let changed = transaction.execute(
|
||||||
|
"
|
||||||
|
UPDATE connection_slots
|
||||||
|
SET profile_id = ?2,
|
||||||
|
updated_at = ?3
|
||||||
|
WHERE slot = ?1
|
||||||
|
",
|
||||||
|
params![slot_to_str(slot), profile_id, updated_at],
|
||||||
|
)?;
|
||||||
|
if changed == 0 {
|
||||||
|
return Err(DatabaseError::SlotNotFound);
|
||||||
|
}
|
||||||
|
transaction.commit()?;
|
||||||
|
self.connection_slot(slot)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn slot_from_row(row: &Row<'_>) -> Result<ConnectionSlot, rusqlite::Error> {
|
||||||
|
let slot = match row.get::<_, String>(0)?.as_str() {
|
||||||
|
"companion" => ActiveSlotKind::Companion,
|
||||||
|
"operations" => ActiveSlotKind::Operations,
|
||||||
|
_ => {
|
||||||
|
return Err(rusqlite::Error::FromSqlConversionFailure(
|
||||||
|
0,
|
||||||
|
rusqlite::types::Type::Text,
|
||||||
|
Box::new(DatabaseError::InvalidStoredSlot),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Ok(ConnectionSlot {
|
||||||
|
slot,
|
||||||
|
profile_id: row.get(1)?,
|
||||||
|
state: ConnectionState::Disconnected,
|
||||||
|
server_instance_id: row.get(2)?,
|
||||||
|
active_conversation_id: None,
|
||||||
|
unread_count: 0,
|
||||||
|
last_event_id: None,
|
||||||
|
last_connected_at: None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn slot_to_str(slot: ActiveSlotKind) -> &'static str {
|
||||||
|
match slot {
|
||||||
|
ActiveSlotKind::Companion => "companion",
|
||||||
|
ActiveSlotKind::Operations => "operations",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use desktop_protocol::{AstrBotProfileRole, AuthenticationType, ConnectionProfile};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn profile(index: usize) -> ConnectionProfile {
|
||||||
|
ConnectionProfile {
|
||||||
|
id: format!("00000000-0000-4000-8000-{index:012}"),
|
||||||
|
display_name: format!("Profile {index}"),
|
||||||
|
role: AstrBotProfileRole::General,
|
||||||
|
base_url: format!("https://example-{index}.test/"),
|
||||||
|
event_stream_url: None,
|
||||||
|
authentication_type: AuthenticationType::DeviceToken,
|
||||||
|
credential_reference: None,
|
||||||
|
allow_insecure_http: false,
|
||||||
|
pinned_certificate_fingerprint: None,
|
||||||
|
auto_connect_slot: None,
|
||||||
|
auto_connect: false,
|
||||||
|
server_instance_id: Some(format!("server-{index}")),
|
||||||
|
server_version: None,
|
||||||
|
protocol_version: None,
|
||||||
|
local_tool_policy_id: None,
|
||||||
|
last_connected_at: None,
|
||||||
|
created_at: "2026-07-19T00:00:00Z".into(),
|
||||||
|
updated_at: "2026-07-19T00:00:00Z".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn initializes_assigns_and_clears_two_fixed_slots() {
|
||||||
|
let database = ApplicationDatabase::in_memory().expect("database");
|
||||||
|
let initial = database
|
||||||
|
.list_connection_slots()
|
||||||
|
.expect("list initial slots");
|
||||||
|
assert_eq!(initial.len(), 2);
|
||||||
|
assert_eq!(initial[0].slot, ActiveSlotKind::Companion);
|
||||||
|
assert_eq!(initial[1].slot, ActiveSlotKind::Operations);
|
||||||
|
assert!(initial.iter().all(|slot| slot.profile_id.is_none()));
|
||||||
|
|
||||||
|
let companion = profile(1);
|
||||||
|
let operations = profile(2);
|
||||||
|
database
|
||||||
|
.create_profile(&companion)
|
||||||
|
.expect("create companion profile");
|
||||||
|
database
|
||||||
|
.create_profile(&operations)
|
||||||
|
.expect("create operations profile");
|
||||||
|
|
||||||
|
let assigned_companion = database
|
||||||
|
.assign_connection_slot(
|
||||||
|
ActiveSlotKind::Companion,
|
||||||
|
&companion.id,
|
||||||
|
"2026-07-19T01:00:00Z",
|
||||||
|
)
|
||||||
|
.expect("assign companion");
|
||||||
|
let assigned_operations = database
|
||||||
|
.assign_connection_slot(
|
||||||
|
ActiveSlotKind::Operations,
|
||||||
|
&operations.id,
|
||||||
|
"2026-07-19T01:00:00Z",
|
||||||
|
)
|
||||||
|
.expect("assign operations");
|
||||||
|
assert_eq!(
|
||||||
|
assigned_companion.profile_id.as_deref(),
|
||||||
|
Some(companion.id.as_str())
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
assigned_operations.profile_id.as_deref(),
|
||||||
|
Some(operations.id.as_str())
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
assigned_operations.server_instance_id.as_deref(),
|
||||||
|
Some("server-2")
|
||||||
|
);
|
||||||
|
|
||||||
|
let cleared = database
|
||||||
|
.clear_connection_slot(ActiveSlotKind::Companion, "2026-07-19T02:00:00Z")
|
||||||
|
.expect("clear companion");
|
||||||
|
assert!(cleared.profile_id.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_one_profile_in_both_slots_and_clears_deleted_profiles() {
|
||||||
|
let database = ApplicationDatabase::in_memory().expect("database");
|
||||||
|
let shared = profile(3);
|
||||||
|
database.create_profile(&shared).expect("create profile");
|
||||||
|
database
|
||||||
|
.assign_connection_slot(
|
||||||
|
ActiveSlotKind::Companion,
|
||||||
|
&shared.id,
|
||||||
|
"2026-07-19T01:00:00Z",
|
||||||
|
)
|
||||||
|
.expect("assign companion");
|
||||||
|
|
||||||
|
assert!(matches!(
|
||||||
|
database.assign_connection_slot(
|
||||||
|
ActiveSlotKind::Operations,
|
||||||
|
&shared.id,
|
||||||
|
"2026-07-19T01:00:00Z",
|
||||||
|
),
|
||||||
|
Err(DatabaseError::ProfileAlreadyAssigned)
|
||||||
|
));
|
||||||
|
|
||||||
|
database.delete_profile(&shared.id).expect("delete profile");
|
||||||
|
assert!(
|
||||||
|
database
|
||||||
|
.list_connection_slots()
|
||||||
|
.expect("list slots")
|
||||||
|
.iter()
|
||||||
|
.all(|slot| slot.profile_id.is_none())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_an_unknown_profile_assignment() {
|
||||||
|
let database = ApplicationDatabase::in_memory().expect("database");
|
||||||
|
assert!(matches!(
|
||||||
|
database.assign_connection_slot(
|
||||||
|
ActiveSlotKind::Operations,
|
||||||
|
"00000000-0000-4000-8000-999999999999",
|
||||||
|
"2026-07-19T01:00:00Z",
|
||||||
|
),
|
||||||
|
Err(DatabaseError::ProfileNotFound)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -5,6 +5,7 @@ pub mod logging;
|
||||||
pub mod networking;
|
pub mod networking;
|
||||||
pub mod profiles;
|
pub mod profiles;
|
||||||
pub mod secure_store;
|
pub mod secure_store;
|
||||||
|
pub mod slots;
|
||||||
pub mod windows;
|
pub mod windows;
|
||||||
|
|
||||||
use database::ApplicationDatabase;
|
use database::ApplicationDatabase;
|
||||||
|
|
@ -92,6 +93,9 @@ pub fn run() {
|
||||||
profiles::create_connection_profile,
|
profiles::create_connection_profile,
|
||||||
profiles::update_connection_profile,
|
profiles::update_connection_profile,
|
||||||
profiles::delete_connection_profile,
|
profiles::delete_connection_profile,
|
||||||
|
slots::list_connection_slots,
|
||||||
|
slots::assign_connection_slot,
|
||||||
|
slots::clear_connection_slot,
|
||||||
])
|
])
|
||||||
.run(tauri::generate_context!())
|
.run(tauri::generate_context!())
|
||||||
.expect("failed to run AstrBot Desktop");
|
.expect("failed to run AstrBot Desktop");
|
||||||
|
|
|
||||||
188
src-tauri/src/slots.rs
普通文件
188
src-tauri/src/slots.rs
普通文件
|
|
@ -0,0 +1,188 @@
|
||||||
|
use desktop_protocol::{ActiveSlotKind, ConnectionSlot};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use crate::database::{ApplicationDatabase, DatabaseError};
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||||
|
pub struct AssignConnectionSlotRequest {
|
||||||
|
pub slot: ActiveSlotKind,
|
||||||
|
pub profile_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct SlotCommandError {
|
||||||
|
code: &'static str,
|
||||||
|
message: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SlotCommandError {
|
||||||
|
fn validation(message: &'static str) -> Self {
|
||||||
|
Self {
|
||||||
|
code: "validationFailed",
|
||||||
|
message,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn database(error: DatabaseError) -> Self {
|
||||||
|
match error {
|
||||||
|
DatabaseError::ProfileNotFound => Self {
|
||||||
|
code: "profileNotFound",
|
||||||
|
message: "The selected connection profile no longer exists.",
|
||||||
|
},
|
||||||
|
DatabaseError::ProfileAlreadyAssigned => Self {
|
||||||
|
code: "profileAlreadyAssigned",
|
||||||
|
message: "One connection profile cannot occupy both active slots.",
|
||||||
|
},
|
||||||
|
DatabaseError::SlotNotFound | DatabaseError::InvalidStoredSlot => Self {
|
||||||
|
code: "invalidSlotState",
|
||||||
|
message: "The local connection slot state is invalid.",
|
||||||
|
},
|
||||||
|
_ => Self {
|
||||||
|
code: "databaseUnavailable",
|
||||||
|
message: "The local connection slot database is unavailable.",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn list_connection_slots(
|
||||||
|
database: tauri::State<'_, ApplicationDatabase>,
|
||||||
|
) -> Result<Vec<ConnectionSlot>, SlotCommandError> {
|
||||||
|
list_slots(&database)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn assign_connection_slot(
|
||||||
|
database: tauri::State<'_, ApplicationDatabase>,
|
||||||
|
request: AssignConnectionSlotRequest,
|
||||||
|
) -> Result<ConnectionSlot, SlotCommandError> {
|
||||||
|
assign_slot(&database, request)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn clear_connection_slot(
|
||||||
|
database: tauri::State<'_, ApplicationDatabase>,
|
||||||
|
slot: ActiveSlotKind,
|
||||||
|
) -> Result<ConnectionSlot, SlotCommandError> {
|
||||||
|
clear_slot(&database, slot)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn list_slots(database: &ApplicationDatabase) -> Result<Vec<ConnectionSlot>, SlotCommandError> {
|
||||||
|
database
|
||||||
|
.list_connection_slots()
|
||||||
|
.map_err(SlotCommandError::database)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assign_slot(
|
||||||
|
database: &ApplicationDatabase,
|
||||||
|
request: AssignConnectionSlotRequest,
|
||||||
|
) -> Result<ConnectionSlot, SlotCommandError> {
|
||||||
|
validate_profile_id(&request.profile_id)?;
|
||||||
|
database
|
||||||
|
.assign_connection_slot(request.slot, &request.profile_id, ×tamp()?)
|
||||||
|
.map_err(SlotCommandError::database)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clear_slot(
|
||||||
|
database: &ApplicationDatabase,
|
||||||
|
slot: ActiveSlotKind,
|
||||||
|
) -> Result<ConnectionSlot, SlotCommandError> {
|
||||||
|
database
|
||||||
|
.clear_connection_slot(slot, ×tamp()?)
|
||||||
|
.map_err(SlotCommandError::database)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_profile_id(id: &str) -> Result<(), SlotCommandError> {
|
||||||
|
if Uuid::parse_str(id).is_err() {
|
||||||
|
return Err(SlotCommandError::validation(
|
||||||
|
"Connection profile ID is invalid.",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn timestamp() -> Result<String, SlotCommandError> {
|
||||||
|
OffsetDateTime::now_utc()
|
||||||
|
.format(&Rfc3339)
|
||||||
|
.map_err(|_| SlotCommandError {
|
||||||
|
code: "clockUnavailable",
|
||||||
|
message: "The system clock could not produce a slot timestamp.",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use desktop_protocol::{AstrBotProfileRole, AuthenticationType, ConnectionProfile};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn profile(index: usize) -> ConnectionProfile {
|
||||||
|
ConnectionProfile {
|
||||||
|
id: format!("00000000-0000-4000-8000-{index:012}"),
|
||||||
|
display_name: format!("Profile {index}"),
|
||||||
|
role: AstrBotProfileRole::General,
|
||||||
|
base_url: format!("https://example-{index}.test/"),
|
||||||
|
event_stream_url: None,
|
||||||
|
authentication_type: AuthenticationType::DeviceToken,
|
||||||
|
credential_reference: None,
|
||||||
|
allow_insecure_http: false,
|
||||||
|
pinned_certificate_fingerprint: None,
|
||||||
|
auto_connect_slot: None,
|
||||||
|
auto_connect: false,
|
||||||
|
server_instance_id: None,
|
||||||
|
server_version: None,
|
||||||
|
protocol_version: None,
|
||||||
|
local_tool_policy_id: None,
|
||||||
|
last_connected_at: None,
|
||||||
|
created_at: "2026-07-19T00:00:00Z".into(),
|
||||||
|
updated_at: "2026-07-19T00:00:00Z".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn assigns_and_clears_slots_through_the_bounded_service() {
|
||||||
|
let database = ApplicationDatabase::in_memory().expect("database");
|
||||||
|
let companion = profile(1);
|
||||||
|
database.create_profile(&companion).expect("create profile");
|
||||||
|
|
||||||
|
let assigned = assign_slot(
|
||||||
|
&database,
|
||||||
|
AssignConnectionSlotRequest {
|
||||||
|
slot: ActiveSlotKind::Companion,
|
||||||
|
profile_id: companion.id.clone(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.expect("assign slot");
|
||||||
|
assert_eq!(assigned.profile_id.as_deref(), Some(companion.id.as_str()));
|
||||||
|
|
||||||
|
let cleared = clear_slot(&database, ActiveSlotKind::Companion).expect("clear slot");
|
||||||
|
assert!(cleared.profile_id.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_unknown_fields_and_malformed_profile_ids() {
|
||||||
|
let parsed = serde_json::from_value::<AssignConnectionSlotRequest>(serde_json::json!({
|
||||||
|
"slot": "companion",
|
||||||
|
"profileId": "00000000-0000-4000-8000-000000000001",
|
||||||
|
"token": "[REDACTED]"
|
||||||
|
}));
|
||||||
|
assert!(parsed.is_err());
|
||||||
|
|
||||||
|
let database = ApplicationDatabase::in_memory().expect("database");
|
||||||
|
assert!(
|
||||||
|
assign_slot(
|
||||||
|
&database,
|
||||||
|
AssignConnectionSlotRequest {
|
||||||
|
slot: ActiveSlotKind::Operations,
|
||||||
|
profile_id: "not-a-uuid".into(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
115
src/App.test.tsx
115
src/App.test.tsx
|
|
@ -3,6 +3,11 @@ import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
import { App } from "./App";
|
import { App } from "./App";
|
||||||
|
import type {
|
||||||
|
ActiveSlotKind,
|
||||||
|
AssignConnectionSlotRequest,
|
||||||
|
ConnectionSlot,
|
||||||
|
} from "./types/connection";
|
||||||
import type {
|
import type {
|
||||||
ConnectionProfile,
|
ConnectionProfile,
|
||||||
ConnectionProfileInput,
|
ConnectionProfileInput,
|
||||||
|
|
@ -18,9 +23,22 @@ const bootstrapStatus = {
|
||||||
platform: "windows",
|
platform: "windows",
|
||||||
rustCore: "ready",
|
rustCore: "ready",
|
||||||
protocolVersion: "desktop-v1alpha1",
|
protocolVersion: "desktop-v1alpha1",
|
||||||
databaseSchemaVersion: 2,
|
databaseSchemaVersion: 3,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const emptySlots: ConnectionSlot[] = [
|
||||||
|
{
|
||||||
|
slot: "companion",
|
||||||
|
state: "disconnected",
|
||||||
|
unreadCount: 0,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
slot: "operations",
|
||||||
|
state: "disconnected",
|
||||||
|
unreadCount: 0,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
describe("App", () => {
|
describe("App", () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.mocked(invoke).mockImplementation(async (command) => {
|
vi.mocked(invoke).mockImplementation(async (command) => {
|
||||||
|
|
@ -30,6 +48,9 @@ describe("App", () => {
|
||||||
if (command === "list_connection_profiles") {
|
if (command === "list_connection_profiles") {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
if (command === "list_connection_slots") {
|
||||||
|
return emptySlots;
|
||||||
|
}
|
||||||
throw new Error(`Unexpected command: ${command}`);
|
throw new Error(`Unexpected command: ${command}`);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
@ -53,6 +74,9 @@ describe("App", () => {
|
||||||
if (command === "list_connection_profiles") {
|
if (command === "list_connection_profiles") {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
if (command === "list_connection_slots") {
|
||||||
|
return emptySlots;
|
||||||
|
}
|
||||||
throw new Error(`Unexpected command: ${command}`);
|
throw new Error(`Unexpected command: ${command}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -71,6 +95,9 @@ describe("App", () => {
|
||||||
if (command === "list_connection_profiles") {
|
if (command === "list_connection_profiles") {
|
||||||
return profiles;
|
return profiles;
|
||||||
}
|
}
|
||||||
|
if (command === "list_connection_slots") {
|
||||||
|
return emptySlots;
|
||||||
|
}
|
||||||
if (command === "create_connection_profile") {
|
if (command === "create_connection_profile") {
|
||||||
const { request } = args as { request: ConnectionProfileInput };
|
const { request } = args as { request: ConnectionProfileInput };
|
||||||
const created: ConnectionProfile = {
|
const created: ConnectionProfile = {
|
||||||
|
|
@ -155,4 +182,90 @@ describe("App", () => {
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("assigns different profiles to the two fixed slots", async () => {
|
||||||
|
const profiles: ConnectionProfile[] = [
|
||||||
|
{
|
||||||
|
id: "2bdedc10-d804-4da5-8e92-39dd7f175d7a",
|
||||||
|
displayName: "陪伴实例",
|
||||||
|
role: "companion",
|
||||||
|
baseUrl: "https://companion.example.test/",
|
||||||
|
authenticationType: "device-token",
|
||||||
|
allowInsecureHttp: false,
|
||||||
|
autoConnect: false,
|
||||||
|
createdAt: "2026-07-19T02:00:00Z",
|
||||||
|
updatedAt: "2026-07-19T02:00:00Z",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "f272aef0-0a89-4f98-b950-b2f1f309631b",
|
||||||
|
displayName: "运维实例",
|
||||||
|
role: "operations",
|
||||||
|
baseUrl: "https://operations.example.test/",
|
||||||
|
authenticationType: "api-key",
|
||||||
|
allowInsecureHttp: false,
|
||||||
|
autoConnect: false,
|
||||||
|
createdAt: "2026-07-19T02:00:00Z",
|
||||||
|
updatedAt: "2026-07-19T02:00:00Z",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
let slots = emptySlots;
|
||||||
|
|
||||||
|
vi.mocked(invoke).mockImplementation(async (command, args) => {
|
||||||
|
if (command === "bootstrap_status") {
|
||||||
|
return bootstrapStatus;
|
||||||
|
}
|
||||||
|
if (command === "list_connection_profiles") {
|
||||||
|
return profiles;
|
||||||
|
}
|
||||||
|
if (command === "list_connection_slots") {
|
||||||
|
return slots;
|
||||||
|
}
|
||||||
|
if (command === "assign_connection_slot") {
|
||||||
|
const { request } = args as { request: AssignConnectionSlotRequest };
|
||||||
|
const saved: ConnectionSlot = {
|
||||||
|
slot: request.slot,
|
||||||
|
profileId: request.profileId,
|
||||||
|
state: "disconnected",
|
||||||
|
unreadCount: 0,
|
||||||
|
};
|
||||||
|
slots = slots.map((slot) =>
|
||||||
|
slot.slot === request.slot ? saved : slot,
|
||||||
|
);
|
||||||
|
return saved;
|
||||||
|
}
|
||||||
|
if (command === "clear_connection_slot") {
|
||||||
|
const { slot } = args as { slot: ActiveSlotKind };
|
||||||
|
const saved: ConnectionSlot = {
|
||||||
|
slot,
|
||||||
|
state: "disconnected",
|
||||||
|
unreadCount: 0,
|
||||||
|
};
|
||||||
|
slots = slots.map((item) => (item.slot === slot ? saved : item));
|
||||||
|
return saved;
|
||||||
|
}
|
||||||
|
throw new Error(`Unexpected command: ${command}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
render(<App />);
|
||||||
|
|
||||||
|
fireEvent.change(await screen.findByLabelText("陪伴 Profile"), {
|
||||||
|
target: { value: profiles[0].id },
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
await screen.findByText("已将陪伴实例分配到陪伴槽位。"),
|
||||||
|
).toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.change(screen.getByLabelText("运维 Profile"), {
|
||||||
|
target: { value: profiles[1].id },
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
await screen.findByText("已将运维实例分配到运维槽位。"),
|
||||||
|
).toBeInTheDocument();
|
||||||
|
expect(invoke).toHaveBeenCalledWith("assign_connection_slot", {
|
||||||
|
request: {
|
||||||
|
slot: "operations",
|
||||||
|
profileId: profiles[1].id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ const initialStatus: BootstrapStatus = {
|
||||||
platform: "unknown",
|
platform: "unknown",
|
||||||
rustCore: "pending",
|
rustCore: "pending",
|
||||||
protocolVersion: "desktop-v1alpha1",
|
protocolVersion: "desktop-v1alpha1",
|
||||||
databaseSchemaVersion: 2,
|
databaseSchemaVersion: 3,
|
||||||
};
|
};
|
||||||
|
|
||||||
export function App() {
|
export function App() {
|
||||||
|
|
@ -33,7 +33,7 @@ export function App() {
|
||||||
return (
|
return (
|
||||||
<main className="app-shell">
|
<main className="app-shell">
|
||||||
<header className="hero">
|
<header className="hero">
|
||||||
<p className="eyebrow">P01 · foundation</p>
|
<p className="eyebrow">P02 · dual connections</p>
|
||||||
<h1>AstrBot Desktop</h1>
|
<h1>AstrBot Desktop</h1>
|
||||||
<p className="subtitle">
|
<p className="subtitle">
|
||||||
双实例陪伴与本机助手的安全 Windows 客户端工程底座。
|
双实例陪伴与本机助手的安全 Windows 客户端工程底座。
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,13 @@
|
||||||
import { invoke } from "@tauri-apps/api/core";
|
import { invoke } from "@tauri-apps/api/core";
|
||||||
import { useCallback, useEffect, useState, type FormEvent } from "react";
|
import { useCallback, useEffect, useState, type FormEvent } from "react";
|
||||||
|
|
||||||
|
import {
|
||||||
|
connectionSlotListSchema,
|
||||||
|
connectionSlotSchema,
|
||||||
|
type ActiveSlotKind,
|
||||||
|
type AssignConnectionSlotRequest,
|
||||||
|
type ConnectionSlot,
|
||||||
|
} from "../../types/connection";
|
||||||
import {
|
import {
|
||||||
connectionProfileListSchema,
|
connectionProfileListSchema,
|
||||||
connectionProfileSchema,
|
connectionProfileSchema,
|
||||||
|
|
@ -33,6 +40,7 @@ const emptyForm: ProfileFormState = {
|
||||||
|
|
||||||
export function ProfileManager() {
|
export function ProfileManager() {
|
||||||
const [profiles, setProfiles] = useState<ConnectionProfile[]>([]);
|
const [profiles, setProfiles] = useState<ConnectionProfile[]>([]);
|
||||||
|
const [slots, setSlots] = useState<ConnectionSlot[]>([]);
|
||||||
const [form, setForm] = useState<ProfileFormState>(emptyForm);
|
const [form, setForm] = useState<ProfileFormState>(emptyForm);
|
||||||
const [editingId, setEditingId] = useState<string | null>(null);
|
const [editingId, setEditingId] = useState<string | null>(null);
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
|
|
@ -41,8 +49,12 @@ export function ProfileManager() {
|
||||||
|
|
||||||
const loadProfiles = useCallback(async () => {
|
const loadProfiles = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
const result = await invoke<unknown>("list_connection_profiles");
|
const [profileResult, slotResult] = await Promise.all([
|
||||||
setProfiles(connectionProfileListSchema.parse(result));
|
invoke<unknown>("list_connection_profiles"),
|
||||||
|
invoke<unknown>("list_connection_slots"),
|
||||||
|
]);
|
||||||
|
setProfiles(connectionProfileListSchema.parse(profileResult));
|
||||||
|
setSlots(connectionSlotListSchema.parse(slotResult));
|
||||||
setError(null);
|
setError(null);
|
||||||
} catch (reason) {
|
} catch (reason) {
|
||||||
setError(`Profile storage unavailable: ${errorMessage(reason)}`);
|
setError(`Profile storage unavailable: ${errorMessage(reason)}`);
|
||||||
|
|
@ -123,6 +135,13 @@ export function ProfileManager() {
|
||||||
setProfiles((current) =>
|
setProfiles((current) =>
|
||||||
current.filter((item) => item.id !== profile.id),
|
current.filter((item) => item.id !== profile.id),
|
||||||
);
|
);
|
||||||
|
setSlots((current) =>
|
||||||
|
current.map((slot) =>
|
||||||
|
slot.profileId === profile.id
|
||||||
|
? { ...slot, profileId: undefined, serverInstanceId: undefined }
|
||||||
|
: slot,
|
||||||
|
),
|
||||||
|
);
|
||||||
if (editingId === profile.id) {
|
if (editingId === profile.id) {
|
||||||
resetForm();
|
resetForm();
|
||||||
}
|
}
|
||||||
|
|
@ -134,6 +153,36 @@ export function ProfileManager() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function updateSlot(slot: ActiveSlotKind, profileId: string) {
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
setNotice(null);
|
||||||
|
try {
|
||||||
|
const result = profileId
|
||||||
|
? await invoke<unknown>("assign_connection_slot", {
|
||||||
|
request: {
|
||||||
|
slot,
|
||||||
|
profileId,
|
||||||
|
} satisfies AssignConnectionSlotRequest,
|
||||||
|
})
|
||||||
|
: await invoke<unknown>("clear_connection_slot", { slot });
|
||||||
|
const saved = connectionSlotSchema.parse(result);
|
||||||
|
setSlots((current) =>
|
||||||
|
current.map((item) => (item.slot === saved.slot ? saved : item)),
|
||||||
|
);
|
||||||
|
const profile = profiles.find((item) => item.id === saved.profileId);
|
||||||
|
setNotice(
|
||||||
|
profile
|
||||||
|
? `已将${profile.displayName}分配到${slotLabel(slot)}槽位。`
|
||||||
|
: `已清空${slotLabel(slot)}槽位。`,
|
||||||
|
);
|
||||||
|
} catch (reason) {
|
||||||
|
setError(`Slot update failed: ${errorMessage(reason)}`);
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function resetForm() {
|
function resetForm() {
|
||||||
setEditingId(null);
|
setEditingId(null);
|
||||||
setForm(emptyForm);
|
setForm(emptyForm);
|
||||||
|
|
@ -143,7 +192,7 @@ export function ProfileManager() {
|
||||||
<section className="profile-manager" aria-labelledby="profile-heading">
|
<section className="profile-manager" aria-labelledby="profile-heading">
|
||||||
<div className="section-heading">
|
<div className="section-heading">
|
||||||
<div>
|
<div>
|
||||||
<p className="eyebrow">P01 · foundation</p>
|
<p className="eyebrow">P02 · dual connections</p>
|
||||||
<h2 id="profile-heading">连接 Profile</h2>
|
<h2 id="profile-heading">连接 Profile</h2>
|
||||||
</div>
|
</div>
|
||||||
<p>
|
<p>
|
||||||
|
|
@ -152,6 +201,52 @@ export function ProfileManager() {
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="slot-grid" aria-label="活动连接槽位">
|
||||||
|
{slots.map((slot) => (
|
||||||
|
<article className="slot-card" key={slot.slot}>
|
||||||
|
<div>
|
||||||
|
<span>{slotLabel(slot.slot)}槽位</span>
|
||||||
|
<strong>{connectionStateLabel(slot.state)}</strong>
|
||||||
|
</div>
|
||||||
|
<label>
|
||||||
|
<span>{slotLabel(slot.slot)} Profile</span>
|
||||||
|
<select
|
||||||
|
aria-label={`${slotLabel(slot.slot)} Profile`}
|
||||||
|
disabled={busy}
|
||||||
|
value={slot.profileId ?? ""}
|
||||||
|
onChange={(event) =>
|
||||||
|
void updateSlot(slot.slot, event.target.value)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<option value="">未分配</option>
|
||||||
|
{profiles.map((profile) => (
|
||||||
|
<option
|
||||||
|
key={profile.id}
|
||||||
|
value={profile.id}
|
||||||
|
disabled={slots.some(
|
||||||
|
(other) =>
|
||||||
|
other.slot !== slot.slot &&
|
||||||
|
other.profileId === profile.id,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{profile.displayName} · {roleLabel(profile.role)}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<p>
|
||||||
|
{slot.serverInstanceId
|
||||||
|
? `服务器:${slot.serverInstanceId}`
|
||||||
|
: "当前仅保存本地槽位归属,尚未启动网络连接。"}
|
||||||
|
</p>
|
||||||
|
</article>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="slot-boundary-note">
|
||||||
|
槽位分配不会授予本机工具权限,也不会读取凭据;正式连接激活将在协议与凭据生命周期确认后启用。
|
||||||
|
</p>
|
||||||
|
|
||||||
<div className="profile-layout">
|
<div className="profile-layout">
|
||||||
<form className="profile-form" onSubmit={submitProfile}>
|
<form className="profile-form" onSubmit={submitProfile}>
|
||||||
<h3>{editingId ? "编辑 Profile" : "新建 Profile"}</h3>
|
<h3>{editingId ? "编辑 Profile" : "新建 Profile"}</h3>
|
||||||
|
|
@ -270,7 +365,8 @@ export function ProfileManager() {
|
||||||
</label>
|
</label>
|
||||||
|
|
||||||
<p className="form-note">
|
<p className="form-note">
|
||||||
槽位分配、自动连接和连接切换保护将在 P02 实现。
|
槽位分配已由 Rust 和 SQLite 约束;自动连接与运行中切换保护将在后续
|
||||||
|
P02 增量实现。
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<div className="button-row">
|
<div className="button-row">
|
||||||
|
|
@ -380,6 +476,14 @@ function roleLabel(role: ProfileRole) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function slotLabel(slot: ActiveSlotKind) {
|
||||||
|
return slot === "companion" ? "陪伴" : "运维";
|
||||||
|
}
|
||||||
|
|
||||||
|
function connectionStateLabel(state: ConnectionSlot["state"]) {
|
||||||
|
return state === "disconnected" ? "未连接" : state;
|
||||||
|
}
|
||||||
|
|
||||||
function errorMessage(reason: unknown) {
|
function errorMessage(reason: unknown) {
|
||||||
if (reason instanceof Error) {
|
if (reason instanceof Error) {
|
||||||
return reason.message;
|
return reason.message;
|
||||||
|
|
|
||||||
|
|
@ -164,6 +164,50 @@ h1 {
|
||||||
gap: 1rem;
|
gap: 1rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.slot-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 1rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.slot-card {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.9rem;
|
||||||
|
padding: 1rem;
|
||||||
|
border: 1px solid rgb(106 163 255 / 35%);
|
||||||
|
border-radius: 0.9rem;
|
||||||
|
background: rgb(18 48 84 / 72%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.slot-card > div {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.slot-card > div span,
|
||||||
|
.slot-card label > span {
|
||||||
|
color: #8db9ff;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.slot-card label {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.45rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.slot-card p,
|
||||||
|
.slot-boundary-note {
|
||||||
|
margin: 0;
|
||||||
|
color: #aebfda;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.slot-boundary-note {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
.profile-form,
|
.profile-form,
|
||||||
.profile-list {
|
.profile-list {
|
||||||
padding: 1.2rem;
|
padding: 1.2rem;
|
||||||
|
|
@ -305,7 +349,8 @@ select:focus {
|
||||||
|
|
||||||
.profile-form,
|
.profile-form,
|
||||||
.profile-list,
|
.profile-list,
|
||||||
.profile-card {
|
.profile-card,
|
||||||
|
.slot-card {
|
||||||
background: rgb(245 249 255 / 90%);
|
background: rgb(245 249 255 / 90%);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -327,14 +372,17 @@ select:focus {
|
||||||
.section-heading > p,
|
.section-heading > p,
|
||||||
.form-note,
|
.form-note,
|
||||||
.empty-state,
|
.empty-state,
|
||||||
.profile-card p {
|
.profile-card p,
|
||||||
|
.slot-card p,
|
||||||
|
.slot-boundary-note {
|
||||||
color: #405775;
|
color: #405775;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 760px) {
|
@media (max-width: 760px) {
|
||||||
.section-heading,
|
.section-heading,
|
||||||
.profile-layout {
|
.profile-layout,
|
||||||
|
.slot-grid {
|
||||||
grid-template-columns: 1fr;
|
grid-template-columns: 1fr;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
50
src/types/connection.ts
普通文件
50
src/types/connection.ts
普通文件
|
|
@ -0,0 +1,50 @@
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
export const activeSlotKindSchema = z.enum(["companion", "operations"]);
|
||||||
|
|
||||||
|
export const connectionStateSchema = z.enum([
|
||||||
|
"disconnected",
|
||||||
|
"connecting",
|
||||||
|
"authenticating",
|
||||||
|
"syncing",
|
||||||
|
"connected",
|
||||||
|
"reconnecting",
|
||||||
|
"authExpired",
|
||||||
|
"incompatible",
|
||||||
|
"serverUnavailable",
|
||||||
|
"offline",
|
||||||
|
"certificateChanged",
|
||||||
|
"fatalError",
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const connectionSlotSchema = z
|
||||||
|
.object({
|
||||||
|
slot: activeSlotKindSchema,
|
||||||
|
profileId: z.uuid().optional(),
|
||||||
|
state: connectionStateSchema,
|
||||||
|
serverInstanceId: z.string().min(1).optional(),
|
||||||
|
activeConversationId: z.string().min(1).optional(),
|
||||||
|
unreadCount: z.number().int().nonnegative(),
|
||||||
|
lastEventId: z.string().min(1).optional(),
|
||||||
|
lastConnectedAt: z.string().min(1).optional(),
|
||||||
|
})
|
||||||
|
.strict();
|
||||||
|
|
||||||
|
export const connectionSlotListSchema = z
|
||||||
|
.array(connectionSlotSchema)
|
||||||
|
.length(2)
|
||||||
|
.refine(
|
||||||
|
(slots) =>
|
||||||
|
new Set(slots.map((slot) => slot.slot)).size === 2 &&
|
||||||
|
slots.some((slot) => slot.slot === "companion") &&
|
||||||
|
slots.some((slot) => slot.slot === "operations"),
|
||||||
|
"Both fixed connection slots are required.",
|
||||||
|
);
|
||||||
|
|
||||||
|
export type ActiveSlotKind = z.infer<typeof activeSlotKindSchema>;
|
||||||
|
export type ConnectionSlot = z.infer<typeof connectionSlotSchema>;
|
||||||
|
|
||||||
|
export interface AssignConnectionSlotRequest {
|
||||||
|
slot: ActiveSlotKind;
|
||||||
|
profileId: string;
|
||||||
|
}
|
||||||
正在加载…
添加表格
在新工单中引用