feat(chat): add AstrBot dual-slot chat foundation
这个提交存在于:
父节点
34a563c65b
当前提交
3d1d962461
共有 43 个文件被更改,包括 7081 次插入 和 2521 次删除
|
|
@ -1,5 +1,9 @@
|
|||
# Changelog
|
||||
# Changelog
|
||||
|
||||
## Unreleased
|
||||
|
||||
### Added
|
||||
- AstrBot OpenAPI adapter foundation: SSE mapper, dual-slot runtime skeleton, credential enrollment IPC, transport-aware profiles (ADR-0005).
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow Semantic Versioning.
|
||||
|
|
@ -38,3 +42,4 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
|
|||
- Kept real UNC writes, signing keys, updater keys, and release secrets outside P00.
|
||||
- Rejected Token, password, API Key, URL credential, query-string credential, and unknown fields at the Profile IPC boundary.
|
||||
- Required explicit approval for insecure HTTP and kept slots, connections, and credential enrollment outside P01.
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,456 @@
|
|||
//! Real AstrBot OpenAPI/Dashboard wire types and SSE frame mapping.
|
||||
//!
|
||||
//! The provisional Desktop Gateway contract remains the internal normalized
|
||||
//! model. This module translates observed AstrBot `/api/v1` chat SSE frames
|
||||
//! into that model without claiming full product compatibility.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::{
|
||||
EventMetadata, FinishReason, GatewayErrorPayload, GatewayEvent, GatewayEventBody,
|
||||
HeartbeatPayload, MessageCompletedPayload, MessageDeltaPayload,
|
||||
};
|
||||
|
||||
/// Wire transport used by a connection profile.
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum TransportKind {
|
||||
/// Provisional Mock / future Desktop Gateway (`/desktop/v1`).
|
||||
#[default]
|
||||
DesktopV1,
|
||||
/// Real AstrBot OpenAPI surface (`/api/v1`).
|
||||
AstrBotOpenApi,
|
||||
}
|
||||
|
||||
impl TransportKind {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::DesktopV1 => "desktop-v1",
|
||||
Self::AstrBotOpenApi => "astrbot-openapi",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(value: &str) -> Option<Self> {
|
||||
match value {
|
||||
"desktop-v1" => Some(Self::DesktopV1),
|
||||
"astrbot-openapi" => Some(Self::AstrBotOpenApi),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// JSON envelope used by most AstrBot dashboard/OpenAPI JSON responses.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AstrBotApiEnvelope<T> {
|
||||
pub status: String,
|
||||
#[serde(default)]
|
||||
pub message: Option<String>,
|
||||
#[serde(default)]
|
||||
pub data: Option<T>,
|
||||
}
|
||||
|
||||
impl<T> AstrBotApiEnvelope<T> {
|
||||
pub fn is_ok(&self) -> bool {
|
||||
self.status.eq_ignore_ascii_case("ok")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AstrBotChatRequest {
|
||||
pub message: Value,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub session_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub conversation_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub username: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub config_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub platform_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub enable_streaming: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AstrBotSessionListData {
|
||||
#[serde(default)]
|
||||
pub sessions: Vec<AstrBotSessionSummary>,
|
||||
#[serde(default)]
|
||||
pub page: Option<u64>,
|
||||
#[serde(default)]
|
||||
pub page_size: Option<u64>,
|
||||
#[serde(default)]
|
||||
pub total: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AstrBotSessionSummary {
|
||||
pub session_id: String,
|
||||
#[serde(default)]
|
||||
pub platform_id: Option<String>,
|
||||
#[serde(default)]
|
||||
pub creator: Option<String>,
|
||||
#[serde(default)]
|
||||
pub display_name: Option<String>,
|
||||
#[serde(default)]
|
||||
pub is_group: Option<i64>,
|
||||
#[serde(default)]
|
||||
pub created_at: Option<String>,
|
||||
#[serde(default)]
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AstrBotConfigListData {
|
||||
#[serde(default)]
|
||||
pub configs: Vec<AstrBotConfigSummary>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AstrBotConfigSummary {
|
||||
pub id: String,
|
||||
#[serde(default)]
|
||||
pub name: Option<String>,
|
||||
#[serde(default)]
|
||||
pub path: Option<String>,
|
||||
#[serde(default)]
|
||||
pub is_default: Option<bool>,
|
||||
}
|
||||
|
||||
/// One decoded SSE unit from an AstrBot chat stream.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum AstrBotSseUnit {
|
||||
HeartbeatComment,
|
||||
Json(AstrBotStreamFrame),
|
||||
Ignored,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AstrBotStreamFrame {
|
||||
#[serde(rename = "type")]
|
||||
pub frame_type: String,
|
||||
#[serde(default)]
|
||||
pub data: Value,
|
||||
#[serde(default)]
|
||||
pub session_id: Option<String>,
|
||||
#[serde(default)]
|
||||
pub streaming: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub chain_type: Option<Value>,
|
||||
#[serde(default)]
|
||||
pub message_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum AstrBotMapError {
|
||||
#[error("invalid astrbot sse json: {0}")]
|
||||
Json(#[from] serde_json::Error),
|
||||
}
|
||||
|
||||
/// Parses a single SSE line (not including the blank separator).
|
||||
pub fn parse_astrbot_sse_line(line: &str) -> Result<AstrBotSseUnit, AstrBotMapError> {
|
||||
let trimmed = line.trim_end_matches('\r');
|
||||
if trimmed.is_empty() {
|
||||
return Ok(AstrBotSseUnit::Ignored);
|
||||
}
|
||||
if trimmed.starts_with(':') {
|
||||
// AstrBot heartbeats are comment frames: ": heartbeat"
|
||||
return Ok(AstrBotSseUnit::HeartbeatComment);
|
||||
}
|
||||
if let Some(data) = trimmed.strip_prefix("data:") {
|
||||
let payload = data.trim_start();
|
||||
if payload.is_empty() {
|
||||
return Ok(AstrBotSseUnit::Ignored);
|
||||
}
|
||||
let frame: AstrBotStreamFrame = serde_json::from_str(payload)?;
|
||||
return Ok(AstrBotSseUnit::Json(frame));
|
||||
}
|
||||
// event:/id: fields are currently unused by AstrBot chat streams.
|
||||
Ok(AstrBotSseUnit::Ignored)
|
||||
}
|
||||
|
||||
/// Stateful mapper that turns AstrBot chat SSE frames into Desktop Gateway events.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct AstrBotStreamMapper {
|
||||
server_instance_id: String,
|
||||
session_id: Option<String>,
|
||||
active_message_id: Option<String>,
|
||||
accumulated: String,
|
||||
delta_index: u32,
|
||||
sequence: u64,
|
||||
saw_assistant_delta: bool,
|
||||
}
|
||||
|
||||
impl AstrBotStreamMapper {
|
||||
pub fn new(server_instance_id: impl Into<String>) -> Self {
|
||||
Self {
|
||||
server_instance_id: server_instance_id.into(),
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn session_id(&self) -> Option<&str> {
|
||||
self.session_id.as_deref()
|
||||
}
|
||||
|
||||
pub fn push_line(&mut self, line: &str) -> Result<Vec<GatewayEvent>, AstrBotMapError> {
|
||||
match parse_astrbot_sse_line(line)? {
|
||||
AstrBotSseUnit::Ignored => Ok(Vec::new()),
|
||||
AstrBotSseUnit::HeartbeatComment => Ok(vec![self.heartbeat_event()]),
|
||||
AstrBotSseUnit::Json(frame) => Ok(self.map_frame(frame)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Call when the HTTP stream ends without a terminal server frame.
|
||||
pub fn finish_stream(&mut self) -> Vec<GatewayEvent> {
|
||||
self.complete_if_needed(FinishReason::Stop)
|
||||
}
|
||||
|
||||
fn map_frame(&mut self, frame: AstrBotStreamFrame) -> Vec<GatewayEvent> {
|
||||
match frame.frame_type.as_str() {
|
||||
"session_id" => {
|
||||
if let Some(session_id) = frame
|
||||
.session_id
|
||||
.clone()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
{
|
||||
self.session_id = Some(session_id);
|
||||
} else if let Some(session_id) = string_from_value(&frame.data) {
|
||||
self.session_id = Some(session_id);
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
"user_message_saved" => Vec::new(),
|
||||
"plain" => self.map_plain(frame),
|
||||
"agent_stats" => {
|
||||
let detail = frame.data.to_string();
|
||||
vec![self.event(
|
||||
frame.message_id.clone(),
|
||||
GatewayEventBody::AgentStatus(crate::AgentStatusPayload {
|
||||
state: "running".into(),
|
||||
detail: Some(detail),
|
||||
}),
|
||||
)]
|
||||
}
|
||||
"run_snapshot" => {
|
||||
vec![self.event(
|
||||
frame.message_id.clone(),
|
||||
GatewayEventBody::AgentStatus(crate::AgentStatusPayload {
|
||||
state: "snapshot".into(),
|
||||
detail: Some(frame.data.to_string()),
|
||||
}),
|
||||
)]
|
||||
}
|
||||
"message_saved" | "end" => self.complete_if_needed(FinishReason::Stop),
|
||||
"error" => {
|
||||
let mut events = self.complete_if_needed(FinishReason::Error);
|
||||
let message = string_from_value(&frame.data)
|
||||
.unwrap_or_else(|| "AstrBot stream error".to_owned());
|
||||
events.push(self.event(
|
||||
frame.message_id,
|
||||
GatewayEventBody::Error(GatewayErrorPayload {
|
||||
code: "astrbotStreamError".into(),
|
||||
message,
|
||||
retryable: true,
|
||||
}),
|
||||
));
|
||||
events
|
||||
}
|
||||
"attachment_saved" => Vec::new(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn map_plain(&mut self, frame: AstrBotStreamFrame) -> Vec<GatewayEvent> {
|
||||
let chunk = string_from_value(&frame.data).unwrap_or_default();
|
||||
if chunk.is_empty() && frame.streaming.unwrap_or(false) {
|
||||
// Keep empty streaming markers out of the UI unless they carry text.
|
||||
return Vec::new();
|
||||
}
|
||||
if let Some(message_id) = frame.message_id.clone() {
|
||||
if self
|
||||
.active_message_id
|
||||
.as_ref()
|
||||
.is_some_and(|current| current != &message_id)
|
||||
{
|
||||
// New assistant message id: complete the previous accumulation first.
|
||||
let mut events = self.complete_if_needed(FinishReason::Stop);
|
||||
self.active_message_id = Some(message_id);
|
||||
self.accumulated.clear();
|
||||
self.delta_index = 0;
|
||||
self.saw_assistant_delta = false;
|
||||
events.extend(self.emit_delta(chunk));
|
||||
return events;
|
||||
}
|
||||
self.active_message_id = Some(message_id);
|
||||
}
|
||||
self.emit_delta(chunk)
|
||||
}
|
||||
|
||||
fn emit_delta(&mut self, chunk: String) -> Vec<GatewayEvent> {
|
||||
if chunk.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
self.accumulated.push_str(&chunk);
|
||||
self.saw_assistant_delta = true;
|
||||
let index = self.delta_index;
|
||||
self.delta_index = self.delta_index.saturating_add(1);
|
||||
vec![self.event(
|
||||
self.active_message_id.clone(),
|
||||
GatewayEventBody::MessageDelta(MessageDeltaPayload {
|
||||
delta: chunk,
|
||||
index,
|
||||
}),
|
||||
)]
|
||||
}
|
||||
|
||||
fn complete_if_needed(&mut self, reason: FinishReason) -> Vec<GatewayEvent> {
|
||||
if !self.saw_assistant_delta && self.accumulated.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let content = std::mem::take(&mut self.accumulated);
|
||||
self.saw_assistant_delta = false;
|
||||
self.delta_index = 0;
|
||||
let message_id = self.active_message_id.clone();
|
||||
vec![self.event(
|
||||
message_id,
|
||||
GatewayEventBody::MessageCompleted(MessageCompletedPayload {
|
||||
finish_reason: reason,
|
||||
content: Some(content),
|
||||
}),
|
||||
)]
|
||||
}
|
||||
|
||||
fn heartbeat_event(&mut self) -> GatewayEvent {
|
||||
self.event(
|
||||
None,
|
||||
GatewayEventBody::Heartbeat(HeartbeatPayload { interval_ms: 1_000 }),
|
||||
)
|
||||
}
|
||||
|
||||
fn event(&mut self, message_id: Option<String>, body: GatewayEventBody) -> GatewayEvent {
|
||||
self.sequence = self.sequence.saturating_add(1);
|
||||
let event_id = format!("astrbot-{}-{}", self.server_instance_id, self.sequence);
|
||||
let mut metadata = EventMetadata::new(
|
||||
event_id,
|
||||
self.server_instance_id.clone(),
|
||||
current_timestamp(),
|
||||
self.sequence,
|
||||
);
|
||||
metadata.session_id = self.session_id.clone();
|
||||
metadata.conversation_id = self.session_id.clone();
|
||||
metadata.message_id = message_id.or_else(|| self.active_message_id.clone());
|
||||
GatewayEvent { metadata, body }
|
||||
}
|
||||
}
|
||||
|
||||
fn string_from_value(value: &Value) -> Option<String> {
|
||||
match value {
|
||||
Value::Null => None,
|
||||
Value::String(text) => Some(text.clone()),
|
||||
Value::Number(number) => Some(number.to_string()),
|
||||
Value::Bool(flag) => Some(flag.to_string()),
|
||||
other => Some(other.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn current_timestamp() -> String {
|
||||
// Protocol timestamps are opaque strings for consumers; keep a stable UTC-like form
|
||||
// without adding a time dependency to the protocol crate.
|
||||
"1970-01-01T00:00:00Z".into()
|
||||
}
|
||||
|
||||
/// Derives a stable local server identity substitute when AstrBot has no server-info API.
|
||||
pub fn derive_astrbot_server_instance_id(base_url: &str) -> String {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let normalized = base_url.trim().trim_end_matches('/').to_ascii_lowercase();
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
normalized.hash(&mut hasher);
|
||||
format!("astrbot-{:016x}", hasher.finish())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn maps_live_probe_style_plain_stream() {
|
||||
let mut mapper = AstrBotStreamMapper::new("astrbot-test");
|
||||
let lines = [
|
||||
r#"data: {"type": "session_id", "data": null, "session_id": "desktop-companion-s1"}"#,
|
||||
r#"data: {"type": "user_message_saved", "data": {"id": 1}}"#,
|
||||
": heartbeat",
|
||||
r#"data: {"type": "plain", "data": "Hello", "streaming": true, "message_id": "m1"}"#,
|
||||
r#"data: {"type": "plain", "data": "!", "streaming": true, "message_id": "m1"}"#,
|
||||
];
|
||||
|
||||
let mut events = Vec::new();
|
||||
for line in lines {
|
||||
events.extend(mapper.push_line(line).expect("parse"));
|
||||
}
|
||||
events.extend(mapper.finish_stream());
|
||||
|
||||
assert_eq!(mapper.session_id(), Some("desktop-companion-s1"));
|
||||
assert!(
|
||||
events
|
||||
.iter()
|
||||
.any(|event| event.body.event_type() == "system.heartbeat")
|
||||
);
|
||||
let deltas: Vec<_> = events
|
||||
.iter()
|
||||
.filter_map(|event| match &event.body {
|
||||
GatewayEventBody::MessageDelta(payload) => Some(payload.delta.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(deltas, ["Hello", "!"]);
|
||||
let completed = events
|
||||
.iter()
|
||||
.find_map(|event| match &event.body {
|
||||
GatewayEventBody::MessageCompleted(payload) => payload.content.clone(),
|
||||
_ => None,
|
||||
})
|
||||
.expect("completed");
|
||||
assert_eq!(completed, "Hello!");
|
||||
assert_eq!(
|
||||
events.last().map(|e| e.body.event_type()),
|
||||
Some("message.completed")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_error_frames() {
|
||||
let mut mapper = AstrBotStreamMapper::new("astrbot-test");
|
||||
let events = mapper
|
||||
.push_line(r#"data: {"type":"error","data":"provider missing"}"#)
|
||||
.expect("parse");
|
||||
assert_eq!(events.len(), 1);
|
||||
match &events[0].body {
|
||||
GatewayEventBody::Error(error) => {
|
||||
assert_eq!(error.code, "astrbotStreamError");
|
||||
assert!(error.message.contains("provider missing"));
|
||||
}
|
||||
other => panic!("unexpected {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derives_stable_instance_ids() {
|
||||
let a = derive_astrbot_server_instance_id("http://192.168.31.210:26285/");
|
||||
let b = derive_astrbot_server_instance_id("http://192.168.31.210:26285");
|
||||
let c = derive_astrbot_server_instance_id("http://192.168.31.210:26286");
|
||||
assert_eq!(a, b);
|
||||
assert_ne!(a, c);
|
||||
assert!(a.starts_with("astrbot-"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protocol_version_constant_is_unchanged_for_internal_model() {
|
||||
assert_eq!(crate::PROTOCOL_VERSION, "desktop-v1alpha1");
|
||||
}
|
||||
}
|
||||
|
|
@ -54,6 +54,9 @@ pub struct ConnectionProfile {
|
|||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub event_stream_url: Option<String>,
|
||||
pub authentication_type: AuthenticationType,
|
||||
/// Wire transport for this profile. Defaults to Desktop mock/gateway contract.
|
||||
#[serde(default = "default_transport_kind")]
|
||||
pub transport_kind: crate::TransportKind,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub credential_reference: Option<String>,
|
||||
#[serde(default)]
|
||||
|
|
@ -74,6 +77,12 @@ pub struct ConnectionProfile {
|
|||
pub local_tool_policy_id: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub last_connected_at: Option<String>,
|
||||
/// AstrBot WebChat username / session owner used by OpenAPI chat.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub remote_username: Option<String>,
|
||||
/// Sticky AstrBot session id for reconnection continuity.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub sticky_session_id: Option<String>,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
|
@ -112,3 +121,7 @@ impl ConnectionSlot {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_transport_kind() -> crate::TransportKind {
|
||||
crate::TransportKind::DesktopV1
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
//! Types in this crate deliberately separate untrusted wire data from locally
|
||||
//! bound desktop events. A server supplied `profileId` is never authoritative.
|
||||
|
||||
mod astrbot;
|
||||
mod capabilities;
|
||||
mod connection;
|
||||
mod diagnostics;
|
||||
|
|
@ -11,6 +12,7 @@ mod file_transfer;
|
|||
mod http;
|
||||
mod tools;
|
||||
|
||||
pub use astrbot::*;
|
||||
pub use capabilities::*;
|
||||
pub use connection::*;
|
||||
pub use diagnostics::*;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,46 @@
|
|||
# ADR-0005: Real AstrBot OpenAPI adapter over internal Desktop protocol
|
||||
|
||||
## Status
|
||||
|
||||
Accepted for foundation work on 2026-07-20.
|
||||
|
||||
## Context
|
||||
|
||||
P00/P01 defined a provisional Desktop Gateway contract (`/desktop/v1`) and dual Mock Gateway. Live probe of AstrBot `4.26.x` on `http://192.168.31.210:26285` showed the real server exposes Dashboard/OpenAPI routes under `/api` and `/api/v1`, with request-scoped chat SSE from `POST /api/v1/chat`, API Key or Dashboard JWT auth, and no Desktop-native long-lived event bus, ACK, `tool.proposal`, or `server-info` endpoints.
|
||||
|
||||
Rewriting the whole Desktop application around raw AstrBot internal APIs would discard working dual-slot isolation, Mock tests, and security boundaries.
|
||||
|
||||
## Decision
|
||||
|
||||
1. Keep the provisional Desktop Gateway event model as the **internal normalized contract**.
|
||||
2. Add a Rust-owned **AstrBot OpenAPI adapter** that translates:
|
||||
- Desktop chat send intent → `POST /api/v1/chat`
|
||||
- AstrBot SSE frames → Desktop `GatewayEvent` (`message.delta`, `message.completed`, heartbeat, error)
|
||||
3. Add `TransportKind` on ConnectionProfile:
|
||||
- `desktop-v1` for Mock/provisional gateway
|
||||
- `astrbot-openapi` for real AstrBot
|
||||
4. Store secrets only in Windows Credential Manager; React may submit one-shot enrollment IPC but never receives stored secrets.
|
||||
5. Use derived `server_instance_id` substitute (`astrbot-<hash(base_url)>`) until a stronger identity enrollment flow is approved.
|
||||
6. Keep operations tool proposals Desktop-local; do not invent a fake server proposal channel.
|
||||
|
||||
## Consequences
|
||||
|
||||
### Positive
|
||||
|
||||
- Real chat connectivity can proceed without discarding Mock-based dual-slot tests.
|
||||
- Security boundaries remain Rust-owned.
|
||||
- UI and local storage continue to reason about normalized events and slots.
|
||||
|
||||
### Negative / costs
|
||||
|
||||
- Adapter must tolerate missing terminal SSE frames and synthesize completion.
|
||||
- Capability/discovery surfaces differ by transport.
|
||||
- Certificate pinning and JWT login remain open follow-ups.
|
||||
|
||||
## Follow-ups
|
||||
|
||||
- Live dual-slot chat UI rendering and history persistence
|
||||
- Dashboard JWT login path
|
||||
- Attachment upload (`/api/v1/file`)
|
||||
- Optional WS chat path
|
||||
- Stronger server identity enrollment (PD-0011) and TLS fingerprint binding (PD-0012)
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
# ADR-0006: 共享聊天运行时与桌宠展示层
|
||||
|
||||
## 状态
|
||||
|
||||
提议,作为 P03-P07 的实现顺序基线,2026-07-20。
|
||||
|
||||
## 背景
|
||||
|
||||
产品需要同时支持完整聊天页面、小型快速回复窗口和后续桌面气泡/桌宠。三者如果各自维护连接、会话和消息,会产生重复状态、窗口间不同步以及双槽位权限绕过风险。
|
||||
|
||||
Hermes 与 Codex 展示出相似的产品形态,但没有可直接复用的共同运行时或公开稳定 SDK。因此本项目需要自有 Tauri/React/Rust 实现,只借鉴交互模式和素材包组织方式。
|
||||
|
||||
## 隔离基线
|
||||
|
||||
账号、Profile、槽位和 Session 是不同层级:账号标识本地使用者,Profile 标识 AstrBot 连接,槽位标识本地职责,Session 标识聊天上下文。不同账号和不同槽位均不得共享本地消息、未读数、错误状态或本机权限。
|
||||
|
||||
## 决策
|
||||
|
||||
1. 建立单一 Rust-owned ChatRuntime,主窗口、快速窗口和气泡均作为展示层订阅它。
|
||||
2. 快速窗口只支持一个可配置目标槽位:Companion 或 Operations。
|
||||
3. 气泡默认不置顶;设置决定气泡点击打开主页面还是快速窗口。
|
||||
4. 桌宠先实现状态模型、素材包校验、窗口控制器和多显示器几何模型;动画引擎和复杂素材格式后置。
|
||||
5. 全屏浮动和游戏模式只能通过受限窗口策略和只读前台/显示器检测实现,不引入任意桌面控制能力。
|
||||
6. 主窗口、快速窗口和气泡关闭时不销毁连接运行时;连接由 Rust 槽位生命周期管理。
|
||||
|
||||
## 结果
|
||||
|
||||
### 优点
|
||||
|
||||
- 三种 UI 共享消息状态,避免重复实现和串线。
|
||||
- 窗口能力与本机工具权限分离,桌宠不会获得额外操作权。
|
||||
- 可以先完成真实文字聊天,再逐步加入视觉和游戏陪伴能力。
|
||||
- 未来替换 PNG/WebP 为 Live2D/Spine 时不会改变聊天协议。
|
||||
|
||||
### 代价
|
||||
|
||||
- 需要设计 Rust 到多个 Tauri 窗口的事件广播和生命周期管理。
|
||||
- SQLite 需要新增会话、消息和窗口偏好迁移。
|
||||
- 多显示器和游戏模式需要 Windows 专用测试矩阵。
|
||||
|
||||
## 后续影响
|
||||
|
||||
- Q1 必须先定义规范化 ChatEvent 和共享订阅语义。
|
||||
- Q4 必须验证独立窗口与单实例/托盘行为。
|
||||
- Q6 的 pet-pack manifest 必须是数据文件,不允许携带可执行逻辑。
|
||||
- Q7 的游戏模式只能做位置和显示策略,不得扩展为输入注入或任意窗口控制。
|
||||
|
|
@ -90,3 +90,22 @@
|
|||
- Requirement: a certificate identity change freezes local-tool permission and the affected connection; TLS validation must never be disabled.
|
||||
- Required decision: select a maintained Rust TLS integration that can inspect the validated peer certificate without installing a permissive verifier, and define first-contact confirmation UX.
|
||||
- Safe interim rule: preserve validated HTTPS behavior and do not claim certificate pinning until the peer certificate path is implemented and tested.
|
||||
|
||||
## PD-0013: Real AstrBot transport mapping (OpenAPI/Dashboard vs `/desktop/v1`)
|
||||
|
||||
- Date noted: 2026-07-20
|
||||
- Status: open; research complete; live container probe pending
|
||||
- Source review: `docs/reports/astrbot-real-protocol-review.md`
|
||||
- Finding: Local AstrBot clone `4.26.7` exposes `/api/v1` developer OpenAPI (API Key + Dashboard JWT) and legacy `/api/*` routes. Chat streaming is request-scoped SSE from `POST /api/v1/chat` (plus optional run stream / WebSocket), not a long-lived Desktop Gateway event bus with ACK.
|
||||
- Missing on real server relative to provisional Desktop contract: `/desktop/v1/health|server-info|capabilities`, access/refresh token pair, event ACK, `tool.proposal`, and `/local-actions/*` callbacks.
|
||||
- Safe interim rule: keep provisional Desktop protocol as the internal normalized model and Mock Gateway contract; implement a Rust `AstrBotAdapter` for real servers. Do not claim compatibility and do not rewrite the whole client.
|
||||
- Open items requiring live container probe: actual SSE type sequence, JWT expiry handling in practice, server-instance identity substitute, dual-profile isolation against one or two containers, and whether operations tooling remains Desktop-local for MVP.
|
||||
- Stop boundary: if live probe proves only browser-cookie auth works, or requires AstrBot core changes for basic text chat, pause and escalate before coding the adapter.
|
||||
- Interaction with existing open items: updates assumptions in PD-0009 and PD-0011; credential storage remains governed by PD-0010.
|
||||
|
||||
### PD-0013 live probe update (2026-07-20)
|
||||
|
||||
- Live target `http://192.168.31.210:26285` accepted API Key auth and streamed chat SSE from `POST /api/v1/chat`.
|
||||
- Dual usernames/session ids remained isolated on one server instance.
|
||||
- Provisional `/desktop/v1` remains non-native; adapter approach confirmed.
|
||||
- Chat MVP connectivity is unblocked. Server identity substitute, JWT login path, file/WS paths, and operations proposal source remain open.
|
||||
|
|
|
|||
|
|
@ -1,113 +1,145 @@
|
|||
# Implementation Plan
|
||||
|
||||
## P00 Bootstrap (completed)
|
||||
|
||||
## Objective
|
||||
|
||||
Establish a reproducible Tauri 2 + React + TypeScript + Rust baseline and complete the high-risk technical Spikes required before formal feature development.
|
||||
|
||||
## Ordered work
|
||||
|
||||
1. Normalize repository documents and Git metadata on `main`.
|
||||
2. Verify Forgejo is empty before the first `main` push; never overwrite remote history.
|
||||
3. Create `feat/p00-bootstrap` from the pushed `main` baseline.
|
||||
4. Establish the Tauri 2 application and typed frontend-to-Rust IPC.
|
||||
5. Implement two independent REST/SSE clients and a dual-instance Mock Gateway.
|
||||
6. Verify Windows secure credential CRUD without exposing secret values to React or logs.
|
||||
7. Verify bounded Windows diagnostics: foreground window, UI Automation, selected-window capture, process information, event logs, ports, network targets, authorized log tails, configuration parsing, and redaction.
|
||||
8. Verify NAS transactions only in a dedicated generated fixture directory: dry run, temporary copy, size/hash verification, atomic commit, conflict handling, interruption recovery, and source preservation.
|
||||
9. Define protocol schemas and capability negotiation types.
|
||||
10. Add frontend, Rust, integration, and Forgejo CI checks.
|
||||
11. Run and record all checks, commit by independently verifiable increments, and push the feature branch without merging `main`.
|
||||
|
||||
## Safety gates
|
||||
|
||||
- No arbitrary command execution is exposed by product code.
|
||||
- No real credential is used in fixtures, logs, snapshots, or commits.
|
||||
- No NAS Spike touches an existing user file or directory.
|
||||
- No remote branch is changed until `git ls-remote` succeeds and remote history is reviewed.
|
||||
- No test or build is marked successful without captured execution results.
|
||||
|
||||
## Current handoff status
|
||||
|
||||
- Rust/MSVC/Tauri are verified and no longer block local work.
|
||||
- Git Credential Manager reauthentication succeeded and the non-forced HTTP push created the remote `main` baseline at `0d12b94`.
|
||||
- Forgejo PR #1 merged P00 into `main` at `b3420e4`; development now continues on `feat/p01-foundation`.
|
||||
- The configured SSH fetch endpoint still refuses connections and the LAN SSH endpoint rejects the available key, but the approved HTTP push URL is operational.
|
||||
- Forgejo runner labels/jobs remain unverified, so the committed workflow is not claimed successful.
|
||||
- Real UNC execution still requires a user-authorized disposable fixture.
|
||||
|
||||
## P01 Foundation (completed)
|
||||
|
||||
### Objective
|
||||
|
||||
Turn the P00 Spike skeleton into a durable application foundation. Under the project owner's option A decision, P01 includes basic non-sensitive Profile metadata CRUD while P02 retains all slot and runtime connection behavior.
|
||||
|
||||
### Ordered work
|
||||
|
||||
1. Initialize a persistent SQLite database in the Tauri application-data directory.
|
||||
2. Apply versioned, transactional, idempotent migrations and refuse unknown future schema versions.
|
||||
3. Validate Rust-to-TypeScript bootstrap payloads at runtime.
|
||||
4. Ensure tracing output passes through the shared redaction rules before it reaches a writer.
|
||||
5. Add SQLite schema v2 for canonical non-sensitive ConnectionProfile metadata.
|
||||
6. Add bounded Tauri list/create/update/delete commands that generate IDs and timestamps in Rust.
|
||||
7. Reject secret values, URL credentials, query-string credentials, unknown IPC fields, and implicit insecure HTTP.
|
||||
8. Add strict frontend Profile Schemas and a basic management UI without Token/password/API Key inputs.
|
||||
9. Test five saved Profiles, CRUD, persistent reopen, v1-to-v2 migration, future-version rejection, and browser fallback.
|
||||
10. Re-verify tray, single-instance, explicit exit, frontend, Rust, E2E, development startup, Schema export, and production build behavior.
|
||||
11. Record the decision in PD-0008 and ADR-0004, then commit and push the verified branch normally.
|
||||
|
||||
### P01 boundary
|
||||
|
||||
- Included: durable application database, schema migration, redacted logging, validated bootstrap IPC, basic Profile metadata CRUD, basic Profile management UI, tray, single-instance, and build/test foundations.
|
||||
- Excluded: slot assignment, active REST/SSE connections, auto-connect behavior, Profile switching protection, duplicate `server_instance_id` handling, and formal credential enrollment.
|
||||
|
||||
### Verification status
|
||||
|
||||
- Frontend formatting, ESLint, TypeScript, 3 Vitest tests, and Vite production build passed.
|
||||
- Playwright Chromium passed 1/1.
|
||||
- Rust fmt, Clippy with warnings denied, tests, and check passed.
|
||||
- Rust test suite passed 50 normal tests; 2 explicit manual tests remained ignored.
|
||||
- Protocol Schema export completed without drift.
|
||||
- Real Tauri development startup reached the Windows executable and was then deliberately terminated.
|
||||
- Windows release and NSIS bundling passed.
|
||||
- Forgejo CI remains unverified because a compatible runner/jobs endpoint is unavailable.
|
||||
|
||||
## P02 Dual Connections (active)
|
||||
|
||||
### Objective
|
||||
|
||||
Add durable companion and operations slot assignment, then build two independent Rust-owned REST/SSE runtimes without weakening the P01 credential and profile boundaries.
|
||||
|
||||
### Ordered work
|
||||
|
||||
1. Persist the two fixed connection slots and enforce that one Profile cannot occupy both slots.
|
||||
2. Add bounded slot list/assign/clear IPC and a minimal settings UI for slot selection.
|
||||
3. Add auto-connect validation: at most two Profiles, one per slot, with no duplicate Profile assignment.
|
||||
4. Add an operations-switch guard that blocks Profile changes while an operations task is active.
|
||||
5. Add duplicate `server_instance_id` detection and surface a warning without silently merging Profile identity.
|
||||
6. Define the production credential enrollment/update/delete lifecycle entirely in Rust, with opaque references in SQLite and no secret values returned to React.
|
||||
7. Review the provisional Gateway contract before enabling real configured connections; keep real AstrBot compatibility explicitly unclaimed until the server contract is available.
|
||||
8. Implement independent REST discovery/authentication and SSE runtimes, per-Profile cancellation, replay cursors, de-duplication, retry state, and error state.
|
||||
9. Integrate the existing dual-instance Mock Gateway and verify that one instance failure or auth expiry does not affect the other.
|
||||
10. Add frontend/Rust/integration coverage, update protocol and progress documents, run the full stage checks, and push the branch normally without merging `main`.
|
||||
|
||||
### Safety gates
|
||||
|
||||
- Slot work must not accept or expose Token, password, API Key, Cookie, Authorization header, or NAS credentials.
|
||||
- A server-supplied `profile_id` is never trusted; the Rust connection object binds every event to its local Profile and slot.
|
||||
- A changed `server_instance_id` or certificate identity freezes the affected connection instead of silently rebinding it.
|
||||
- Companion Profiles never gain local-tool authority from slot assignment alone.
|
||||
- The provisional `/desktop/v1` contract and Mock Gateway are not evidence of compatibility with an unreviewed real AstrBot Gateway.
|
||||
|
||||
### First increment (completed)
|
||||
|
||||
Implement SQLite schema v3 for the two fixed slot assignments, bounded list/assign/clear commands, database and command tests, and a minimal Profile-slot settings surface. This increment intentionally excludes network activation and credential values.
|
||||
|
||||
Completion commit: `bcc08cf feat(connection): add persistent dual slot assignment`.
|
||||
|
||||
### 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.
|
||||
# Implementation Plan
|
||||
|
||||
## P00 Bootstrap (completed)
|
||||
|
||||
## Objective
|
||||
|
||||
Establish a reproducible Tauri 2 + React + TypeScript + Rust baseline and complete the high-risk technical Spikes required before formal feature development.
|
||||
|
||||
## Ordered work
|
||||
|
||||
1. Normalize repository documents and Git metadata on `main`.
|
||||
2. Verify Forgejo is empty before the first `main` push; never overwrite remote history.
|
||||
3. Create `feat/p00-bootstrap` from the pushed `main` baseline.
|
||||
4. Establish the Tauri 2 application and typed frontend-to-Rust IPC.
|
||||
5. Implement two independent REST/SSE clients and a dual-instance Mock Gateway.
|
||||
6. Verify Windows secure credential CRUD without exposing secret values to React or logs.
|
||||
7. Verify bounded Windows diagnostics: foreground window, UI Automation, selected-window capture, process information, event logs, ports, network targets, authorized log tails, configuration parsing, and redaction.
|
||||
8. Verify NAS transactions only in a dedicated generated fixture directory: dry run, temporary copy, size/hash verification, atomic commit, conflict handling, interruption recovery, and source preservation.
|
||||
9. Define protocol schemas and capability negotiation types.
|
||||
10. Add frontend, Rust, integration, and Forgejo CI checks.
|
||||
11. Run and record all checks, commit by independently verifiable increments, and push the feature branch without merging `main`.
|
||||
|
||||
## Safety gates
|
||||
|
||||
- No arbitrary command execution is exposed by product code.
|
||||
- No real credential is used in fixtures, logs, snapshots, or commits.
|
||||
- No NAS Spike touches an existing user file or directory.
|
||||
- No remote branch is changed until `git ls-remote` succeeds and remote history is reviewed.
|
||||
- No test or build is marked successful without captured execution results.
|
||||
|
||||
## Current handoff status
|
||||
|
||||
- Rust/MSVC/Tauri are verified and no longer block local work.
|
||||
- Git Credential Manager reauthentication succeeded and the non-forced HTTP push created the remote `main` baseline at `0d12b94`.
|
||||
- Forgejo PR #1 merged P00 into `main` at `b3420e4`; development now continues on `feat/p01-foundation`.
|
||||
- The configured SSH fetch endpoint still refuses connections and the LAN SSH endpoint rejects the available key, but the approved HTTP push URL is operational.
|
||||
- Forgejo runner labels/jobs remain unverified, so the committed workflow is not claimed successful.
|
||||
- Real UNC execution still requires a user-authorized disposable fixture.
|
||||
|
||||
## P01 Foundation (completed)
|
||||
|
||||
### Objective
|
||||
|
||||
Turn the P00 Spike skeleton into a durable application foundation. Under the project owner's option A decision, P01 includes basic non-sensitive Profile metadata CRUD while P02 retains all slot and runtime connection behavior.
|
||||
|
||||
### Ordered work
|
||||
|
||||
1. Initialize a persistent SQLite database in the Tauri application-data directory.
|
||||
2. Apply versioned, transactional, idempotent migrations and refuse unknown future schema versions.
|
||||
3. Validate Rust-to-TypeScript bootstrap payloads at runtime.
|
||||
4. Ensure tracing output passes through the shared redaction rules before it reaches a writer.
|
||||
5. Add SQLite schema v2 for canonical non-sensitive ConnectionProfile metadata.
|
||||
6. Add bounded Tauri list/create/update/delete commands that generate IDs and timestamps in Rust.
|
||||
7. Reject secret values, URL credentials, query-string credentials, unknown IPC fields, and implicit insecure HTTP.
|
||||
8. Add strict frontend Profile Schemas and a basic management UI without Token/password/API Key inputs.
|
||||
9. Test five saved Profiles, CRUD, persistent reopen, v1-to-v2 migration, future-version rejection, and browser fallback.
|
||||
10. Re-verify tray, single-instance, explicit exit, frontend, Rust, E2E, development startup, Schema export, and production build behavior.
|
||||
11. Record the decision in PD-0008 and ADR-0004, then commit and push the verified branch normally.
|
||||
|
||||
### P01 boundary
|
||||
|
||||
- Included: durable application database, schema migration, redacted logging, validated bootstrap IPC, basic Profile metadata CRUD, basic Profile management UI, tray, single-instance, and build/test foundations.
|
||||
- Excluded: slot assignment, active REST/SSE connections, auto-connect behavior, Profile switching protection, duplicate `server_instance_id` handling, and formal credential enrollment.
|
||||
|
||||
### Verification status
|
||||
|
||||
- Frontend formatting, ESLint, TypeScript, 3 Vitest tests, and Vite production build passed.
|
||||
- Playwright Chromium passed 1/1.
|
||||
- Rust fmt, Clippy with warnings denied, tests, and check passed.
|
||||
- Rust test suite passed 50 normal tests; 2 explicit manual tests remained ignored.
|
||||
- Protocol Schema export completed without drift.
|
||||
- Real Tauri development startup reached the Windows executable and was then deliberately terminated.
|
||||
- Windows release and NSIS bundling passed.
|
||||
- Forgejo CI remains unverified because a compatible runner/jobs endpoint is unavailable.
|
||||
|
||||
## P02 Dual Connections (active)
|
||||
|
||||
### Objective
|
||||
|
||||
Add durable companion and operations slot assignment, then build two independent Rust-owned REST/SSE runtimes without weakening the P01 credential and profile boundaries.
|
||||
|
||||
### Ordered work
|
||||
|
||||
1. Persist the two fixed connection slots and enforce that one Profile cannot occupy both slots.
|
||||
2. Add bounded slot list/assign/clear IPC and a minimal settings UI for slot selection.
|
||||
3. Add auto-connect validation: at most two Profiles, one per slot, with no duplicate Profile assignment.
|
||||
4. Add an operations-switch guard that blocks Profile changes while an operations task is active.
|
||||
5. Add duplicate `server_instance_id` detection and surface a warning without silently merging Profile identity.
|
||||
6. Define the production credential enrollment/update/delete lifecycle entirely in Rust, with opaque references in SQLite and no secret values returned to React.
|
||||
7. Review the provisional Gateway contract before enabling real configured connections; keep real AstrBot compatibility explicitly unclaimed until the server contract is available.
|
||||
8. Implement independent REST discovery/authentication and SSE runtimes, per-Profile cancellation, replay cursors, de-duplication, retry state, and error state.
|
||||
9. Integrate the existing dual-instance Mock Gateway and verify that one instance failure or auth expiry does not affect the other.
|
||||
10. Add frontend/Rust/integration coverage, update protocol and progress documents, run the full stage checks, and push the branch normally without merging `main`.
|
||||
|
||||
### Safety gates
|
||||
|
||||
- Slot work must not accept or expose Token, password, API Key, Cookie, Authorization header, or NAS credentials.
|
||||
- A server-supplied `profile_id` is never trusted; the Rust connection object binds every event to its local Profile and slot.
|
||||
- A changed `server_instance_id` or certificate identity freezes the affected connection instead of silently rebinding it.
|
||||
- Companion Profiles never gain local-tool authority from slot assignment alone.
|
||||
- The provisional `/desktop/v1` contract and Mock Gateway are not evidence of compatibility with an unreviewed real AstrBot Gateway.
|
||||
|
||||
### First increment (completed)
|
||||
|
||||
Implement SQLite schema v3 for the two fixed slot assignments, bounded list/assign/clear commands, database and command tests, and a minimal Profile-slot settings surface. This increment intentionally excludes network activation and credential values.
|
||||
|
||||
Completion commit: `bcc08cf feat(connection): add persistent dual slot assignment`.
|
||||
|
||||
### 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.
|
||||
### Real AstrBot adapter foundation (added 2026-07-20)
|
||||
|
||||
Completed outside the original pure-mock sequencing because live probe unblocked transport decisions:
|
||||
|
||||
1. Internal SSE mapper and TransportKind.
|
||||
2. Credential enrollment lifecycle (enroll/clear/load-for-Rust-only).
|
||||
3. DualSlotRuntime activate/probe/send skeleton for strbot-openapi and desktop-v1.
|
||||
4. Frontend transport + one-shot credential enrollment UI.
|
||||
|
||||
Still reserved before claiming end-to-end product chat:
|
||||
|
||||
- Chat UI event rendering
|
||||
- Auto-connect runtime start
|
||||
- JWT login
|
||||
- Identity confirmation UX
|
||||
|
||||
|
||||
## Product queue after the real AstrBot foundation
|
||||
|
||||
The ordered queue is maintained in docs/implementation-queue.md. The next implementation target is Q1: a shared Rust-owned chat runtime and normalized AstrBot event subscription.
|
||||
|
||||
1. Q1 normalized chat runtime
|
||||
2. Q2 chat/session persistence
|
||||
3. Q3 main-page chat MVP
|
||||
4. Q4 shared-state quick chat window
|
||||
5. Q5 status bubble and tray integration
|
||||
6. Q6 pet state/resource foundation
|
||||
7. Q7 multi-monitor and game-mode strategy
|
||||
8. Q8 voice, proactive messages, and game companionship
|
||||
9. Q9 release hardening and acceptance build
|
||||
|
||||
The quick window and bubble are presentation surfaces over the same runtime; they must not create independent network clients or permission scopes.
|
||||
|
|
|
|||
145
docs/implementation-queue.md
普通文件
145
docs/implementation-queue.md
普通文件
|
|
@ -0,0 +1,145 @@
|
|||
# AstrBot Desktop 后续开发队列
|
||||
|
||||
## 目标形态
|
||||
|
||||
产品采用一套共享聊天运行时,提供三种展示形态:
|
||||
|
||||
1. **主页面聊天**:类似 QQ / Telegram 的完整窗口,支持会话列表、双槽位、消息流、未读数、主动消息和设置入口。
|
||||
2. **快速聊天窗口**:桌面小窗口,支持拖动和调整大小;与主页面共享会话、消息、连接和未读状态,不复制聊天逻辑。
|
||||
3. **气泡/桌宠入口**:默认不置顶,可显示连接和代理状态;点击行为在设置中选择“打开主页面”或“打开快速聊天”。后续扩展为桌面宠物。
|
||||
|
||||
## 隔离基线
|
||||
|
||||
所有后续队列必须遵守以下五层边界:
|
||||
|
||||
- **账号与账号隔离**:不同本地账号的连接配置、凭据引用、聊天记录、长期记忆和权限互不共享。
|
||||
- **槽位与槽位隔离**:同一账号下的 Companion 与 Operations 分别维护连接、SSE、会话、消息、未读数、错误状态和权限。
|
||||
- **Profile 与 Profile 隔离**:每个 AstrBot 连接 Profile 固定绑定地址、凭据引用、server_instance_id 和远端身份。
|
||||
- **Session 与 Session 隔离**:不同槽位使用不同 sticky session;本地消息键不能只使用 session_id 或 conversation_id。
|
||||
- **权限与权限隔离**:Companion 默认无本机工具权限;Operations 的诊断或文件提案必须经过本地策略、风险判断和用户确认。
|
||||
|
||||
推荐的本地事件和消息归属字段为:
|
||||
|
||||
`account_id + profile_id + slot + server_instance_id + remote_username + session_id + message_id`
|
||||
|
||||
remote_username 用于远端聊天身份和会话命名,不作为本机权限判断依据;本机权限只由本地账号、Profile、槽位和策略引擎决定。
|
||||
|
||||
## 执行原则
|
||||
|
||||
- 先做真实 AstrBot OpenAPI 的文字聊天闭环,再做视觉增强。
|
||||
- React 只消费 Rust 输出的规范化事件,不直接访问 AstrBot 原始接口。
|
||||
- Companion 与 Operations 的消息、会话、未读数和错误状态始终隔离。
|
||||
- 气泡、快速窗口和主窗口只改变展示方式,不改变消息权限和槽位权限。
|
||||
- 桌宠动画、跨屏移动和游戏模式先做数据模型及控制器接口,避免提前绑定素材或第三方运行时。
|
||||
- 不默认开启置顶;全屏浮动必须有显式设置和可关闭路径。
|
||||
|
||||
## 队列
|
||||
|
||||
### Q0:阶段收口与基础校验
|
||||
|
||||
- 检查当前 P02 未提交改动,消除意外的大范围格式或换行 diff。
|
||||
- 完成 Rust fmt、Clippy、TypeScript、ESLint、Prettier、Vite build、Playwright 和适用的 Tauri 构建检查。
|
||||
- 将测试 API Key 标记为待轮换,不再写入日志、快照或测试夹具。
|
||||
- 保留 `desktop-v1` Mock 传输;真实 AstrBot 走 `astrbot-openapi` 适配器。
|
||||
|
||||
验收:现有连接基础可构建,敏感信息边界无回归,Mock 与真实适配器不会互相污染。
|
||||
|
||||
### Q1:统一聊天运行时与事件归一化
|
||||
|
||||
- 为每个槽位建立 Rust-owned `ChatRuntime`,绑定 `profile_id`、`server_instance_id`、`conversation_id`。
|
||||
- 将 AstrBot SSE 映射为统一的消息增量、完成、错误、心跳和主动消息事件。
|
||||
- 处理流式消息合并、重复事件、断线恢复、取消生成和请求失败。
|
||||
- 明确 `remote_username` 与 sticky session 的会话恢复策略。
|
||||
- 增加前端订阅 IPC/事件桥;React 不接触 API Key 和原始 HTTP 客户端。
|
||||
|
||||
验收:两个槽位可同时发送和接收文字消息;同一 `conversation_id` 在不同 Profile 下不会串线。
|
||||
|
||||
### Q2:聊天数据与历史持久化
|
||||
|
||||
- 新增会话、消息、消息块、发送状态、未读数和主动消息的 SQLite 表及迁移。
|
||||
- 本地唯一键至少包含 `profile_id`、`server_instance_id`、`conversation_id`、`message_id`。
|
||||
- 支持启动恢复、分页加载、失败重试、流式消息落盘和未读数清零。
|
||||
- 对消息内容做长度限制和展示层安全处理;日志不得记录完整聊天内容或凭据。
|
||||
|
||||
验收:重启应用后可恢复两个槽位的会话和未完成消息状态,数据隔离测试通过。
|
||||
|
||||
### Q3:主页面聊天 MVP
|
||||
|
||||
- 将当前 bootstrap/Profile 骨架替换为应用壳:侧栏、槽位切换、会话列表和聊天区域。
|
||||
- 支持双面板并排模式、单面板 Tab 模式、Focus Companion、Focus Operations。
|
||||
- 支持文本消息、流式渲染、发送中/失败/重试、连接状态、未读标记和主动消息入口。
|
||||
- Operations 的本机工具提案只显示安全确认卡片,不在聊天文本中伪装成已执行。
|
||||
- Companion 默认隐藏本机工具入口;Operations 仍受本地策略引擎约束。
|
||||
|
||||
验收:主窗口能完成真实 AstrBot 文字聊天;布局切换不丢流式内容;主动消息能跳转到正确槽位。
|
||||
|
||||
### Q4:快速聊天窗口
|
||||
|
||||
- 增加独立 Tauri 窗口,初始尺寸适合快速回复。
|
||||
- 支持拖动、调整大小、关闭后恢复位置和尺寸。
|
||||
- 与主窗口共享 `ChatRuntime`、会话选择、消息缓存、未读数和发送队列。
|
||||
- 设置中只提供一个快速聊天目标:`companion` 或 `operations`,二选一。
|
||||
- 设置中提供气泡点击导向:主页面或快速聊天;不增加第三种导向模式。
|
||||
- 处理主窗口关闭到托盘、快速窗口关闭、单实例和窗口重启恢复。
|
||||
|
||||
验收:从主窗口和快速窗口发送的消息进入同一会话;任一窗口关闭不影响连接和另一个窗口。
|
||||
|
||||
### Q5:状态气泡与托盘整合
|
||||
|
||||
- 增加非默认置顶的气泡窗口,显示连接状态、思考中、回复完成、错误和未读数。
|
||||
- 允许用户关闭气泡或切换到仅应用 UI 模式。
|
||||
- 气泡点击按设置打开主页面或快速聊天;右键菜单提供显示、隐藏、设置和退出。
|
||||
- 明确窗口层级、焦点、点击穿透(如需要)和屏幕边界策略。
|
||||
- 只在 Rust 窗口控制器中执行显示/隐藏/置顶,React 仅发出受限意图。
|
||||
|
||||
验收:气泡不默认置顶;两个槽位状态可区分;点击行为与设置一致;托盘隐藏主窗口后仍可恢复。
|
||||
|
||||
### Q6:桌宠基础模型与素材包
|
||||
|
||||
- 抽象 `CompanionState`:`idle`、`thinking`、`speaking`、`error`、`notification`、`offline`。
|
||||
- 抽象 `PetRenderer`、`PetWindowController` 和 `PetInteractionPolicy`,先支持静态 PNG/WebP 和 spritesheet。
|
||||
- 定义可校验的 `pet-pack/manifest.json`,包含尺寸、动画帧、状态映射和可选点击动作。
|
||||
- 支持应用内显示模式与全屏浮动模式的设置模型,但首版只接入状态气泡/静态形象。
|
||||
- 上传素材只进入沙箱目录,校验格式、尺寸、文件大小和 manifest,不执行脚本或插件代码。
|
||||
|
||||
验收:可加载一个本地安全素材包并根据聊天状态切换静态状态;错误素材被拒绝且不影响主 UI。
|
||||
|
||||
### Q7:多显示器与游戏模式控制器
|
||||
|
||||
- Rust 获取显示器工作区、主屏/副屏标识、DPI 和任务栏边界,形成稳定的 `MonitorGeometry`。
|
||||
- 提供桌宠位置策略:自由、靠边、指定屏幕、跟随主窗口。
|
||||
- 游戏模式只做策略层:优先选择副屏,无法识别时选择非当前游戏窗口所在屏幕;宠物限制在边缘安全区。
|
||||
- 通过受限的窗口/进程检测判断前台游戏,不读取或注入游戏进程,不做鼠标键盘控制。
|
||||
- 增加双屏断开、DPI 变化、全屏游戏和窗口切换的回退策略。
|
||||
|
||||
验收:双屏场景下位置计算稳定;游戏模式不会把宠物放到游戏中心;权限不足时安全降级为应用内模式。
|
||||
|
||||
### Q8:语音、主动消息与游戏陪伴接入
|
||||
|
||||
- 在统一聊天运行时之上接入 STT/TTS,不为快速窗口或桌宠复制语音管线。
|
||||
- 明确语音目标槽位,默认 Companion;Operations 需要显式切换。
|
||||
- 将主动消息映射为通知、气泡状态和未读数,并提供静默时段设置。
|
||||
- 游戏模式接入截图/状态摘要前,先完成授权提示、频率限制和隐私开关。
|
||||
|
||||
### Q9:稳定性、发布与验收
|
||||
|
||||
- 覆盖网络切换、SSE 重连、托盘驻留、窗口恢复、凭据失效和数据库迁移。
|
||||
- 完成日志脱敏、诊断包预览、崩溃恢复和更新流程。
|
||||
- 完成 Windows release/installer、签名、版本号、CHANGELOG 和阶段总结。
|
||||
- 通过全套阶段门槛后再进入主干合并和验收版本打包。
|
||||
|
||||
## 暂不进入实现
|
||||
|
||||
- 不复制 Hermes 或 Codex 的私有实现;只参考交互模式和资源组织方式。
|
||||
- 不在首轮实现 Live2D、Spine、3D 桌宠或用户脚本插件。
|
||||
- 不实现任意 Shell、PowerShell、CMD、鼠标键盘控制。
|
||||
- 不把 AstrBot 的工具调用直接当成本机命令执行。
|
||||
- 不在没有真实附件协议验证前承诺文件上传;附件单独做 Spike。
|
||||
|
||||
## 需要用户后续接入
|
||||
|
||||
- 测试容器 API Key 轮换。
|
||||
- 真实双服务器或第二容器,用于两个不同 `server_instance_id` 的长期并行测试。
|
||||
- 最终确定 Companion/Operations 的远端用户名命名规则。
|
||||
- 首批桌宠素材或授权素材包;在此之前使用测试 PNG/WebP。
|
||||
- 如需 HTTPS 证书指纹绑定,提供可验证的 HTTPS 入口并确认首次信任交互。
|
||||
180
docs/progress.md
180
docs/progress.md
|
|
@ -1,98 +1,94 @@
|
|||
# Development Progress
|
||||
# Development Progress
|
||||
|
||||
## Current phase
|
||||
|
||||
P02 dual connections remains active on `feat/p02-dual-connections`.
|
||||
The foundation has been adjusted for real AstrBot OpenAPI transport after live container probe.
|
||||
Credential enrollment, dual-slot runtime skeleton, and AstrBot SSE mapping are implemented.
|
||||
Full product chat UI activation and production identity enrollment remain open for acceptance.
|
||||
|
||||
## Completed
|
||||
|
||||
### Prior phases
|
||||
|
||||
- P00 bootstrap merged.
|
||||
- P01 foundation merged through Forgejo PR #2.
|
||||
- P02 first increment: persistent dual slot assignment (`bcc08cf`).
|
||||
- P02 second increment: auto-connect validation and operations switch guard (`34a563c`).
|
||||
|
||||
### Real-protocol foundation (this session)
|
||||
|
||||
- Reviewed local AstrBot clone and live probe target `http://192.168.31.210:26285`.
|
||||
- Confirmed API Key chat SSE works; dual usernames/session ids isolate cleanly.
|
||||
- Added internal mapping module `desktop-protocol::astrbot` for OpenAPI SSE → Desktop events.
|
||||
- Added `TransportKind` (`desktop-v1` | `astrbot-openapi`) plus `remote_username` / `sticky_session_id` profile fields.
|
||||
- Migrated SQLite schema to v4.
|
||||
- Added Rust `AstrBotClient` for probe/list/send chat stream.
|
||||
- Added `DualSlotRuntime` with activate/probe/send/deactivate skeleton.
|
||||
- Added bounded credential enrollment IPC (`enroll_profile_credential` / `clear_profile_credential`) using Windows Credential Manager; secrets never returned to React.
|
||||
- Added frontend transport fields and credential enrollment card.
|
||||
- Recorded ADR-0005 and live probe report.
|
||||
|
||||
## In progress
|
||||
|
||||
- User acceptance of real-protocol foundation.
|
||||
- Next product increments: chat panel rendering, history persistence, JWT login path, stronger server identity UX.
|
||||
|
||||
## Remaining
|
||||
|
||||
- Wire auto-connect startup to DualSlotRuntime without weakening secret boundary.
|
||||
- Dual chat UI panels consuming normalized runtime events.
|
||||
- Message persistence for AstrBot mapped events.
|
||||
- Dashboard JWT auth strategy.
|
||||
- File attachment OpenAPI path.
|
||||
- Certificate fingerprint binding.
|
||||
- Full stage gate (fmt/clippy/typecheck/build/installer) before merge.
|
||||
|
||||
## Blockers / reserved for user
|
||||
|
||||
- Production API Key rotation after shared test key exposure in chat.
|
||||
- Optional second AstrBot container if true dual-server soak is required.
|
||||
- Product decision on companion/operations remote username naming convention.
|
||||
- TLS-terminated HTTPS endpoint if pinning must be validated before release.
|
||||
|
||||
## Test status
|
||||
|
||||
- `desktop-protocol` lib tests: 4 passed (AstrBot mapper).
|
||||
- `astrbot-desktop` lib tests: 58 passed.
|
||||
- Vitest: 6 passed.
|
||||
- Live non-destructive probe artifacts retained under `docs/reports/` (secrets redacted).
|
||||
- Full release build / Clippy gate / Playwright not re-run in this autonomous stretch.
|
||||
|
||||
## Current branch
|
||||
|
||||
- `feat/p02-dual-connections`
|
||||
|
||||
## Next step after acceptance
|
||||
|
||||
1. Chat panel MVP against AstrBot adapter.
|
||||
2. Persist sticky session + message history under profile/server/session keys.
|
||||
3. Optional auto-connect activation using enrolled credential references only.
|
||||
|
||||
|
||||
## Queue decision
|
||||
|
||||
- Q1-Q3 complete the real AstrBot text-chat path and main UI before visual polish.
|
||||
- Q4 adds the draggable/resizable quick window using the same chat state.
|
||||
- Q5 adds the status bubble and configurable click routing.
|
||||
- Q6-Q7 reserve pet assets, multi-monitor geometry, and game-mode policy without adding arbitrary desktop control.
|
||||
|
||||
## Current phase
|
||||
|
||||
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.
|
||||
## Autonomous queue increment
|
||||
|
||||
## Completed
|
||||
Completed in this increment:
|
||||
|
||||
- Read `AGENTS.md`, the architecture, implementation task, and Forgejo predevelopment workflow documents in full.
|
||||
- Verified the Windows, Git, Node.js, package-manager, WebView2, Rust, Tauri, and MSVC environment.
|
||||
- Initialized and normalized Git, established `main`, and pushed the baseline without force.
|
||||
- Completed and merged P00 through Forgejo PR #1 at `b3420e4`.
|
||||
- Created `feat/p01-foundation` from the merged `main`.
|
||||
- Added persistent SQLite startup initialization with WAL, busy timeout, foreign-key enforcement, and transactional migrations.
|
||||
- Added schema v2 with canonical non-sensitive `connection_profiles` metadata.
|
||||
- Added fresh-database, v1-to-v2, future-version, idempotent reopen, five-Profile, CRUD, and persistent-reopen coverage.
|
||||
- Added bounded Tauri Profile list/create/update/delete commands.
|
||||
- Kept UUID and timestamp creation in Rust.
|
||||
- Rejected credential-bearing URLs, URL query/fragment data, implicit HTTP, invalid certificate fingerprints, malformed IDs, unknown fields, and Token/password/API Key fields.
|
||||
- Preserved credential references and runtime-managed fields outside the editable P01 input.
|
||||
- Added strict Zod Schemas for bootstrap and ConnectionProfile IPC payloads.
|
||||
- Added a basic React Profile management UI for non-sensitive metadata only.
|
||||
- Added explicit deletion confirmation and browser-safe Tauri IPC fallback.
|
||||
- Added a redacting tracing writer that sanitizes structured fields and rendered message content.
|
||||
- Retained tray, close-to-tray, explicit quit, and single-instance behavior.
|
||||
- Re-exported protocol Schemas without drift.
|
||||
- Re-ran a real Tauri development startup and reached the Windows executable.
|
||||
- Rebuilt the Windows release executable and NSIS installer.
|
||||
- Recorded the Profile boundary in PD-0008 and ADR-0004.
|
||||
- Verified Forgejo PR #2 was merged at `885abd1553ed8f1428de7118a6f4b59f7e22a45c`.
|
||||
- Fast-forwarded local `main` to the same remote merge commit without rewriting history.
|
||||
- Created `feat/p02-dual-connections` from the updated `main`.
|
||||
- Re-read `AGENTS.md`, the Forgejo workflow, architecture design, and implementation task documents in full for P02.
|
||||
- Kept the approved HTTP Forgejo URL repository-local and prevented the machine-wide HTTP-to-SSH rewrite from changing this repository's transport.
|
||||
- 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`.
|
||||
- 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.
|
||||
- Q1: Rust-owned bounded runtime event drain IPC and normalized event identity fields.
|
||||
- Q2: SQLite schema v5 chat message persistence keyed by account/profile/slot/server/session/message.
|
||||
- Q3: main chat panel MVP with Companion/Operations switching, streaming event merge, send error state, and session history restore.
|
||||
- Q4: dynamic Tauri quick-chat window sharing the Rust runtime.
|
||||
- Q5: non-default-topmost status bubble window with runtime status display.
|
||||
- Q6: pet state, safe PNG/WebP manifest schema, monitor geometry, and safe-edge placement model.
|
||||
|
||||
## In progress
|
||||
Validation: Rust workspace tests passed (59 tests), Rust Clippy with warnings denied passed, Rust format check passed, TypeScript check passed, Vitest passed (6 tests), and Vite production build passed.
|
||||
|
||||
- No product implementation is currently in progress after the second P02 increment.
|
||||
|
||||
## Remaining
|
||||
|
||||
- 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.
|
||||
- Add the combined end-to-end test that keeps configured streams active while the real Tauri window is hidden to tray.
|
||||
|
||||
## Blockers
|
||||
|
||||
- Configured Forgejo SSH `localhost:18086` refuses connections.
|
||||
- LAN SSH `192.168.31.210:18086` responds but rejects the available public key.
|
||||
- Approved HTTP Git push remains operational and is not blocked.
|
||||
- Forgejo runner labels/jobs could not be verified; the jobs API endpoint returned 404.
|
||||
- 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 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
|
||||
|
||||
- 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
|
||||
|
||||
`feat/p02-dual-connections`
|
||||
|
||||
## Recent commits
|
||||
|
||||
- `bcc08cf feat(connection): add persistent dual slot assignment`
|
||||
- `73693b9 docs(p02): start dual connection phase`
|
||||
- `885abd1 Merge pull request 'feat(p01): add secure profile foundation and management UI' (#2) from feat/p01-foundation into main`
|
||||
- `b3420e4 Merge pull request 'feat(p00): bootstrap Tauri desktop and validate high-risk spikes' (#1)`
|
||||
- `ed74342 feat(foundation): add persistent bootstrap safeguards`
|
||||
|
||||
## Next step
|
||||
|
||||
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.
|
||||
Still not claimed complete: automatic startup activation, real Tauri multi-window manual UX, long-duration reconnect soak, JWT login, attachment protocol, certificate pinning, actual Windows multi-monitor/game-mode integration, voice, and release installer validation.
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
# AstrBot Desktop Gateway Protocol v1
|
||||
# AstrBot Desktop Gateway Protocol v1
|
||||
|
||||
Status: provisional P00 contract for desktop development and the local Mock Gateway.
|
||||
Compatibility with a real AstrBot Gateway must not be claimed until the server-side contract is reviewed.
|
||||
|
|
@ -47,3 +47,8 @@ Available fixed scenarios:
|
|||
- `auth-reject`
|
||||
|
||||
The 30-minute dual-SSE soak is an explicit local Spike acceptance run and must be recorded separately; its result is not implied by unit tests.
|
||||
## Real AstrBot transport note
|
||||
|
||||
As of the 2026-07-20 live probe, real AstrBot servers do **not** implement /desktop/v1.
|
||||
Desktop keeps this protocol as the internal normalized model and maps AstrBot OpenAPI chat SSE through the Rust adapter (TransportKind::astrbot-openapi).
|
||||
See docs/reports/astrbot-real-protocol-review.md and docs/decisions/ADR-0005-astrbot-openapi-adapter.md.
|
||||
|
|
|
|||
|
|
@ -21,6 +21,21 @@
|
|||
"api-key"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
"TransportKind": {
|
||||
"description": "Wire transport used by a connection profile.",
|
||||
"oneOf": [
|
||||
{
|
||||
"const": "desktop-v1",
|
||||
"description": "Provisional Mock / future Desktop Gateway (`/desktop/v1`).",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "astr-bot-open-api",
|
||||
"description": "Real AstrBot OpenAPI surface (`/api/v1`).",
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
|
|
@ -95,6 +110,13 @@
|
|||
"null"
|
||||
]
|
||||
},
|
||||
"remoteUsername": {
|
||||
"description": "AstrBot WebChat username / session owner used by OpenAPI chat.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"role": {
|
||||
"$ref": "#/$defs/AstrBotProfileRole"
|
||||
},
|
||||
|
|
@ -110,6 +132,18 @@
|
|||
"null"
|
||||
]
|
||||
},
|
||||
"stickySessionId": {
|
||||
"description": "Sticky AstrBot session id for reconnection continuity.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"transportKind": {
|
||||
"$ref": "#/$defs/TransportKind",
|
||||
"default": "desktop-v1",
|
||||
"description": "Wire transport for this profile. Defaults to Desktop mock/gateway contract."
|
||||
},
|
||||
"updatedAt": {
|
||||
"type": "string"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,38 @@
|
|||
# AstrBot 双容器连接稳定性测试
|
||||
|
||||
- 日期:2026-07-20
|
||||
- 范围:仅连接、认证、请求级 SSE 稳定性和会话隔离
|
||||
- 禁止项:未修改远端配置,未删除数据,未调用工具或文件操作接口,未做重启
|
||||
|
||||
## 测试矩阵
|
||||
|
||||
- 两套远端 AstrBot:端口 26285、26385
|
||||
- 每套两个逻辑槽位:companion、operations
|
||||
- 3 轮低频并发
|
||||
- 总请求数:12 次聊天 SSE 请求
|
||||
- 每次请求使用独立的 desktop-stress-companion 或 desktop-stress-operations 用户名和固定 session id
|
||||
- 请求内容为要求服务端仅回复 OK 的连通性探针
|
||||
|
||||
## 结果
|
||||
|
||||
| 系统 | 请求数 | HTTP 200 | SSE | user_message_saved | 错误 | 最大耗时 |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
|
||||
| 26285 | 6 | 6 | 6 | 6 | 0 | 15.44 秒 |
|
||||
| 26385 | 6 | 6 | 6 | 6 | 0 | 9.38 秒 |
|
||||
|
||||
所有请求均返回 text/event-stream,认证成功,均收到 session_id 和 user_message_saved。部分响应没有 plain 帧,但没有出现 HTTP、SSE 或 API 错误。
|
||||
|
||||
## 隔离核对
|
||||
|
||||
两套系统分别查询两个用户名的会话列表,均只看到对应的 creator 和 session id:
|
||||
|
||||
- companion:desktop-stress-companion / desktop-stress-companion-s1
|
||||
- operations:desktop-stress-operations / desktop-stress-operations-s1
|
||||
|
||||
未发现 companion 与 operations 串线,也未发现两台系统之间的会话串线。
|
||||
|
||||
## 结论
|
||||
|
||||
当前两套容器可以作为双连接开发测试环境。客户端可以在每个 Profile 内分别保存远端地址、API Key 引用、remote_username 和 sticky_session_id。该测试不等价于长时间 soak test,也不验证 JWT 过期、断网重连、服务重启或高并发压力。
|
||||
|
||||
API Key 未写入本报告;测试密钥仍建议在验收前轮换。
|
||||
|
|
@ -0,0 +1,452 @@
|
|||
=== companion ===
|
||||
data: {"type": "session_id", "data": null, "session_id": "desktop-companion-s1"}
|
||||
|
||||
data: {"type": "user_message_saved", "data": {"id": 9, "created_at": "2026-07-19T18:37:36.326720+00:00", "llm_checkpoint_id": "07b7b73b-31b1-4d12-b991-97911fa8a7f4"}}
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
=== operations ===
|
||||
data: {"type": "session_id", "data": null, "session_id": "desktop-operations-s1"}
|
||||
|
||||
data: {"type": "user_message_saved", "data": {"id": 10, "created_at": "2026-07-19T18:39:07.001542+00:00", "llm_checkpoint_id": "6dd71d85-c27e-4683-aca2-3678dc0f4a8d"}}
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
data: {"type": "plain", "data": "\n\n", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": "Hello", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " again", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": "!", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " 👋", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " \n\n", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": "I", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " see", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " you", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": "'re", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " saying", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " hello", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " with", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " a", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " \"", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": "3", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": "\"", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " -", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " is", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " there", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " something", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " specific", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " you", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": "'d", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " like", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " to", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " chat", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " about", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " or", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " need", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " help", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " with", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": "?", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " I", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": "'m", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " here", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " and", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " ready", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " to", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": " assist", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
data: {"type": "plain", "data": "!", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
: heartbeat
|
||||
|
||||
=== sessions companion ===
|
||||
{"status":"ok","message":null,"data":{"sessions":[{"session_id":"desktop-companion-s1","platform_id":"webchat","creator":"desktop-companion","display_name":"desktop-probe companion","is_group":0,"created_at":"2026-07-19T18:30:39.417334+00:00","updated_at":"2026-07-19T18:35:11.994641+00:00"}],"page":1,"page_size":20,"total":1}}
|
||||
|
||||
=== sessions operations ===
|
||||
{"status":"ok","message":null,"data":{"sessions":[{"session_id":"desktop-operations-s1","platform_id":"webchat","creator":"desktop-operations","display_name":"Desktop-Probe Operations","is_group":0,"created_at":"2026-07-19T18:30:46.775912+00:00","updated_at":"2026-07-19T18:31:03.599429+00:00"}],"page":1,"page_size":20,"total":1}}
|
||||
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
{
|
||||
"ok": true,
|
||||
"base": "http://192.168.31.210:26285",
|
||||
"companion": {
|
||||
"contentType": "text/event-stream",
|
||||
"saved": false,
|
||||
"types": {
|
||||
"user_message_saved": 1,
|
||||
"session_id": 1
|
||||
},
|
||||
"length": 1602
|
||||
},
|
||||
"operations": {
|
||||
"contentType": "text/event-stream",
|
||||
"saved": false,
|
||||
"types": {
|
||||
"plain": 41,
|
||||
"session_id": 1,
|
||||
"user_message_saved": 1
|
||||
},
|
||||
"length": 7137
|
||||
},
|
||||
"sessionsCompanion": {
|
||||
"status": "ok",
|
||||
"message": null,
|
||||
"data": {
|
||||
"sessions": [
|
||||
{
|
||||
"session_id": "desktop-companion-s1",
|
||||
"platform_id": "webchat",
|
||||
"creator": "desktop-companion",
|
||||
"display_name": "desktop-probe companion",
|
||||
"is_group": 0,
|
||||
"created_at": "2026-07-19T18:30:39.417334+00:00",
|
||||
"updated_at": "2026-07-19T18:35:11.994641+00:00"
|
||||
}
|
||||
],
|
||||
"page": 1,
|
||||
"page_size": 20,
|
||||
"total": 1
|
||||
}
|
||||
},
|
||||
"sessionsOperations": {
|
||||
"status": "ok",
|
||||
"message": null,
|
||||
"data": {
|
||||
"sessions": [
|
||||
{
|
||||
"session_id": "desktop-operations-s1",
|
||||
"platform_id": "webchat",
|
||||
"creator": "desktop-operations",
|
||||
"display_name": "Desktop-Probe Operations",
|
||||
"is_group": 0,
|
||||
"created_at": "2026-07-19T18:30:46.775912+00:00",
|
||||
"updated_at": "2026-07-19T18:31:03.599429+00:00"
|
||||
}
|
||||
],
|
||||
"page": 1,
|
||||
"page_size": 20,
|
||||
"total": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,362 @@
|
|||
# AstrBot Real Protocol Review (vs Desktop provisional contract)
|
||||
|
||||
- Date: 2026-07-20
|
||||
- Status: research complete; live container probe pending user-provided instance
|
||||
- Conclusion: **do not claim compatibility** with `/desktop/v1`. Real AstrBot exposes Dashboard JWT + developer OpenAPI on `/api` and `/api/v1`. A desktop adapter layer is required.
|
||||
|
||||
## Sources
|
||||
|
||||
| Source | Path / URL | Role |
|
||||
| --- | --- | --- |
|
||||
| Local upstream clone | `C:\Users\Administrator\Documents\Codex\refs\AstrBot` | Code authority (no GitHub Apps used) |
|
||||
| Package version | `pyproject.toml` → `4.26.7` | Observed clone version |
|
||||
| Official OpenAPI docs | `docs/zh/dev/openapi.md`, `docs/en/dev/openapi.md` | Public developer API contract |
|
||||
| Dashboard API code | `astrbot/dashboard/api/*`, `services/chat_service.py`, `services/auth_service.py` | Auth, SSE, WS, scopes |
|
||||
| Compose defaults | `compose.yml` | Port `6185` WebUI/API |
|
||||
| Desktop provisional contract | `docs/protocol/v1/*`, `docs/01_Architecture_Design.md`, PD-0009 | Current client assumption |
|
||||
|
||||
Upstream repo identity: [AstrBotDevs/AstrBot](https://github.com/AstrBotDevs/AstrBot). Docker image commonly `soulter/astrbot:latest`.
|
||||
|
||||
## What real AstrBot exposes
|
||||
|
||||
### Transport and base URLs
|
||||
|
||||
- Default container/WebUI port: **6185** (`compose.yml` maps `6185:6185`, Dockerfile `EXPOSE 6185`).
|
||||
- API surface is **FastAPI / ASGI**, not a custom Desktop Gateway.
|
||||
- Two parallel API styles coexist:
|
||||
1. **v1 OpenAPI-style routes**: prefix `/api/v1` (`API_V1_PREFIX`).
|
||||
2. **Legacy Dashboard routes**: prefixes like `/api/auth`, `/api/chat`, `/api/session`, etc.
|
||||
- Interactive docs (when running): `http://<host>:6185/api/v1/docs`
|
||||
- OpenAPI schema: `http://<host>:6185/api/v1/openapi.json`
|
||||
|
||||
### Authentication (two valid modes)
|
||||
|
||||
| Mode | How presented | Intended use | Notes |
|
||||
| --- | --- | --- | --- |
|
||||
| Dashboard JWT | `Authorization: Bearer <jwt>` or cookie `astrbot_dashboard_jwt` | WebUI / dashboard-user flows | Login via `POST /api/v1/auth/login` or legacy `POST /api/auth/login` with username/password (+ optional TOTP). JWT payload: `{ username, exp }` HS256, default **7 days**. **No refresh-token endpoint found** in current code. |
|
||||
| Developer API Key | Official docs show `Authorization: Bearer abk_xxx` or `X-API-Key: abk_xxx`; code also accepts `ApiKey <key>`, query `api_key`/`key` | Machine integration | Scope-gated. Prefer header auth; avoid putting keys in query strings in Desktop. |
|
||||
|
||||
Response envelope for most JSON APIs:
|
||||
|
||||
```json
|
||||
{ "status": "ok|error", "message": "...", "data": {} }
|
||||
```
|
||||
|
||||
Login success data includes at least:
|
||||
|
||||
```json
|
||||
{
|
||||
"token": "<jwt>",
|
||||
"username": "...",
|
||||
"change_pwd_hint": false,
|
||||
"md5_pwd_hint": false,
|
||||
"password_upgrade_required": false
|
||||
}
|
||||
```
|
||||
|
||||
Fresh installs may print a random strong dashboard password in startup logs (default password policy changed).
|
||||
|
||||
### Chat / streaming (the critical path for Desktop text chat)
|
||||
|
||||
| Capability | Real AstrBot | Desktop provisional (`/desktop/v1`) |
|
||||
| --- | --- | --- |
|
||||
| Send message | `POST /api/v1/chat` (OpenAPI, SSE) or legacy `POST /api/chat/send` | `POST /desktop/v1/messages` |
|
||||
| Session list | `GET /api/v1/chat/sessions` (API key path requires `username`) | Not modeled the same way |
|
||||
| New session | Dashboard: `GET /api/v1/chat/sessions/new` / legacy `GET /api/chat/new_session` | Implicit/local |
|
||||
| Streaming transport | **Request-scoped SSE** from chat send; also run attach `GET /api/v1/chat/runs/{run_id}/stream` | **Long-lived** `GET /desktop/v1/events/stream` with `Last-Event-ID` |
|
||||
| Optional duplex | `WS /api/v1/chat/ws` (OpenAPI) and live-chat WS endpoints | Deferred WS for voice/game only |
|
||||
| Event ACK | Not present as Desktop-style `POST /events/{id}/ack` | Required in provisional contract |
|
||||
| Health / server-info / capabilities | **No** `/desktop/v1/health|server-info|capabilities` | Required discovery endpoints |
|
||||
| Auth refresh | **No** refresh token pair found | `POST /desktop/v1/auth/refresh` |
|
||||
| Tool proposal from server to desktop | **Not** present as `tool.proposal` | Core operations model |
|
||||
| Local-action result callbacks | **Not** present as `/local-actions/*` | Required for ops tools |
|
||||
|
||||
#### OpenAPI chat request shape (`OpenApiChatRequest`)
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Hello" ,
|
||||
"session_id": "uuid-or-omit",
|
||||
"conversation_id": "alias-of-session_id",
|
||||
"username": "required-for-api-key-mode",
|
||||
"config_id": "optional",
|
||||
"config_name": "optional",
|
||||
"platform_id": "optional",
|
||||
"enable_streaming": true,
|
||||
"flags": {}
|
||||
}
|
||||
```
|
||||
|
||||
`message` may be:
|
||||
|
||||
1. plain string
|
||||
2. message-segment array, e.g. `{ "type": "plain", "text": "..." }` plus attachment segments (`image`/`record`/`file`/`video` with `attachment_id`)
|
||||
|
||||
#### Observed SSE frame style (from `chat_service.py`)
|
||||
|
||||
- Media type: `text/event-stream`
|
||||
- Frames are mostly `data: {json}\n\n`
|
||||
- Heartbeat is **comment-style**: `: heartbeat\n\n` (not Desktop `system.heartbeat` event objects)
|
||||
- Payload types observed in stream path include:
|
||||
- `session_id`
|
||||
- `user_message_saved`
|
||||
- `run_snapshot`
|
||||
- `agent_stats`
|
||||
- `attachment_saved`
|
||||
- `message_saved`
|
||||
- `error`
|
||||
- plus intermediate chunk payloads whose `type` can be message-chain types such as `plain` / attachment types and end markers from the internal queue
|
||||
|
||||
This is **not** the Desktop provisional event set:
|
||||
|
||||
```text
|
||||
system.heartbeat
|
||||
message.delta
|
||||
message.completed
|
||||
message.proactive
|
||||
agent.status
|
||||
tool.proposal
|
||||
capabilities.changed
|
||||
error
|
||||
```
|
||||
|
||||
### Developer API Key scopes
|
||||
|
||||
Supported scopes in code/docs: `bot`, `provider`, `persona`, `im`, `config`, `chat`, `file`, `plugin`, `mcp`, `skill`.
|
||||
|
||||
Important:
|
||||
|
||||
- `config` implies `bot` + `provider`.
|
||||
- Docs state developer keys do **not** currently expose some management scopes as first-class developer scopes (`tool`, `kb`, `data`, `system` called out as unsupported developer scopes in docs).
|
||||
- Desktop “operations tool proposal” is **not** an AstrBot OpenAPI scope; it is a Desktop-local safety model.
|
||||
|
||||
### Dual-instance implications
|
||||
|
||||
AstrBot itself is one server process/instance with multi-session WebChat identities (`username` + `session_id` / platform session keys).
|
||||
|
||||
Desktop dual slots (`companion` / `operations`) remain a **client-side** concept:
|
||||
|
||||
- Two Desktop Profiles can point at the **same** AstrBot base URL with different roles/policies.
|
||||
- Or two Profiles can point at two containers.
|
||||
- Real server does not natively understand Desktop slot roles.
|
||||
- Isolation keys on Desktop must still include local `profile_id` + observed `server_instance_id` substitute + conversation/session id.
|
||||
|
||||
There is **no first-class** `serverInstanceId` discovery endpoint equivalent to Desktop `server-info`. A safe substitute must be designed (e.g., hash of base URL + dashboard instance markers + TLS cert fingerprint + optional user-confirmed label). This is still an open protocol decision.
|
||||
|
||||
## Gap table (Desktop provisional vs real AstrBot)
|
||||
|
||||
| Area | Desktop design | Real AstrBot today | Risk if ignored | Can implement now? |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| Base path | `/desktop/v1/*` | `/api/v1/*` + legacy `/api/*` | 100% connection failure | Adapter required |
|
||||
| Auth model | access + refresh tokens | JWT (7d) and/or API Key; no refresh pair found | Refresh logic dead code / false security assumptions | Adapter: store JWT or API Key in Credential Manager |
|
||||
| Credentials in React | forbidden | N/A | policy violation if mirrored | Keep Rust-only secret store |
|
||||
| Health discovery | `/health` | not equivalent | mock-only health checks | Map to lightweight authenticated probe or WebUI reachability |
|
||||
| Server identity | `/server-info.serverInstanceId` | missing | silent cross-instance mixups | Need substitute identity + user confirmation |
|
||||
| Capabilities | `/capabilities` | partial via configs/plugins/bots lists; not Desktop schema | capability UI wrong | Map subset later |
|
||||
| Chat send | REST message post | `POST /api/v1/chat` SSE | wrong client shape | Implement adapter |
|
||||
| Event stream | long-lived SSE + Last-Event-ID | per-request SSE (+ optional run stream / WS) | reconnect/dedupe model invalid | Redesign stream manager |
|
||||
| Event names | Desktop enum | different types | parser rejects everything | Map/normalize in adapter |
|
||||
| ACK | required | absent | useless calls / noise | Make ACK optional/no-op for AstrBot backend |
|
||||
| Proactive messages | `message.proactive` over long SSE | IM proactive API exists (`POST /api/v1/im/message`) but not Desktop push bus | wrong product assumption | Separate design |
|
||||
| Ops tool.proposal | server pushes proposals | **not present** | operations panel cannot be driven by AstrBot core alone | Keep Desktop-local proposal engine / future plugin contract |
|
||||
| Local-action callbacks | `/local-actions/*` | absent | cannot close tool loop to AstrBot | Local audit only, or future plugin |
|
||||
| TLS / pinning | required by Desktop security model | container often HTTP on LAN | may force HTTP exception path | Prefer HTTPS reverse proxy; never disable TLS validation globally |
|
||||
| Dual SSE slots | two long-lived streams | two chat runs / two API keys / two containers | architecture mismatch | Keep dual client slots; adapt transport |
|
||||
|
||||
## Architecture impact (important: not a total rewrite)
|
||||
|
||||
### Keep (still valid)
|
||||
|
||||
- Tauri + React + Rust boundary
|
||||
- Dual Profile / dual slot isolation
|
||||
- Credential Manager storage
|
||||
- Mock Gateway for deterministic tests
|
||||
- Local diagnostics / NAS transfer security pipeline (client-side)
|
||||
- Provisional Desktop protocol as **internal normalized model**
|
||||
|
||||
### Must add
|
||||
|
||||
1. **`AstrBotAdapter` (Rust)** that translates:
|
||||
- Desktop normalized commands → AstrBot REST/SSE/WS
|
||||
- AstrBot stream frames → Desktop `GatewayEvent` (best-effort mapping)
|
||||
2. **Auth strategies**:
|
||||
- Strategy A: Dashboard username/password → JWT (short-lived session model, re-login on expiry)
|
||||
- Strategy B: API Key with scopes `chat` (+ `file` if attachments; carefully limited admin scopes)
|
||||
3. **Stream manager redesign**:
|
||||
- Not one eternal server push bus
|
||||
- Per send-stream + optional run re-attach + future WS for duplex
|
||||
4. **Server identity substitute** decision (open item)
|
||||
5. **Operations path**:
|
||||
- Do **not** expect stock AstrBot to emit Desktop `tool.proposal`
|
||||
- Either local-only ops tools, or a future explicit AstrBot plugin/contract
|
||||
|
||||
### Do **not** do
|
||||
|
||||
- Rewrite Desktop core to call random AstrBot internal Python APIs
|
||||
- Claim `/desktop/v1` is real AstrBot
|
||||
- Put API keys/JWT into React, SQLite plain fields, logs, or URL query strings
|
||||
- Disable TLS validation to “make container work”
|
||||
- Implement arbitrary shell execution because ops tools are missing server-side
|
||||
|
||||
## Live container probe plan (when you provide the instance)
|
||||
|
||||
Please provide (redact secrets in chat if needed; better paste into a local file path I can read, or supply a temporary throwaway password/API key):
|
||||
|
||||
1. Base URL, e.g. `http://192.168.x.x:6185`
|
||||
2. Auth mode: dashboard password **or** API Key (`abk_...`)
|
||||
3. Whether LLM provider is already configured (chat may stream errors without a model)
|
||||
4. Network reachability from this Windows desktop host
|
||||
|
||||
Minimum probe sequence (no secrets logged in full):
|
||||
|
||||
1. `GET /` or WebUI reachability
|
||||
2. `GET /api/v1/openapi.json` (schema presence/version markers)
|
||||
3. Auth:
|
||||
- login `POST /api/v1/auth/login` **or**
|
||||
- API key header against `GET /api/v1/chat/sessions?username=...`
|
||||
4. Create/send chat:
|
||||
- `POST /api/v1/chat` with small plain message and capture first SSE frames
|
||||
5. Confirm session list returns the session
|
||||
6. Optional: WS `/api/v1/chat/ws` smoke
|
||||
7. Record actual event type sequence into this report appendix
|
||||
|
||||
Success criteria for “connection is implementable”:
|
||||
|
||||
- Auth succeeds without Dashboard browser cookies as the only path
|
||||
- One chat message produces parseable SSE frames
|
||||
- Session id is stable enough to store under a Desktop Profile
|
||||
- Dual Profiles can open two independent sessions without cross-talk
|
||||
|
||||
Failure that would force design pause:
|
||||
|
||||
- Only cookie-auth works and API key/JWT blocked
|
||||
- Chat stream format unstable / undocumented and unusable
|
||||
- No way to distinguish two server instances safely for dual-slot ops
|
||||
- Requirement to modify AstrBot core for basic text chat
|
||||
|
||||
## Decision recommendation
|
||||
|
||||
| Decision | Recommendation |
|
||||
| --- | --- |
|
||||
| Is Desktop mock protocol wrong? | It is a **valid internal contract**, not a real server contract. |
|
||||
| Should we throw away Desktop work? | **No.** Keep Mock + normalized events; add adapter. |
|
||||
| First live integration target | Text chat via `POST /api/v1/chat` SSE + session APIs |
|
||||
| Preferred auth for automation tests | API Key with minimal scopes (`chat`, maybe `file`) |
|
||||
| Preferred auth for user login UX | Dashboard login → JWT in Credential Manager, re-login on 401/expiry |
|
||||
| Operations tools MVP | Remain Desktop-local; do not depend on AstrBot emitting proposals yet |
|
||||
| Protocol docs | Update PD-0009 / add ADR after first successful container probe |
|
||||
|
||||
## Can implement now / needs container / blocked
|
||||
|
||||
| Item | Status |
|
||||
| --- | --- |
|
||||
| Protocol research + gap table | **Done** (this document) |
|
||||
| Adapter design sketch | **Ready** |
|
||||
| Live endpoint/version confirmation against your container | **Needs container** |
|
||||
| Real chat SSE fixture capture | **Needs container + model provider** |
|
||||
| Dual-instance identity substitute finalization | **Needs probe + product decision** |
|
||||
| Claiming production compatibility | **Blocked** until probe passes |
|
||||
| Rewriting whole Desktop architecture | **Not required** based on current evidence |
|
||||
|
||||
## Next action
|
||||
|
||||
Provide the test AstrBot container endpoint and auth material. I will run a non-destructive probe, capture redacted SSE samples, and only then propose the minimal adapter implementation plan (likely ADR + protocol mapping tables, without expanding product scope).
|
||||
|
||||
## Live container probe (2026-07-20)
|
||||
|
||||
- Target: `http://192.168.31.210:26285`
|
||||
- Auth: developer API Key (`abk_…`, redacted)
|
||||
- Mode: non-destructive chat/session/config probes only
|
||||
- Artifacts:
|
||||
- `docs/reports/astrbot-live-probe-summary.json`
|
||||
- `docs/reports/astrbot-live-probe-sse.raw.txt` (secrets redacted)
|
||||
- `docs/reports/run-live-probe.ps1` (requires env key; no embedded secret)
|
||||
|
||||
### Connectivity results
|
||||
|
||||
| Check | Result |
|
||||
| --- | --- |
|
||||
| TCP `192.168.31.210:26285` | Reachable |
|
||||
| `GET /` WebUI HTML | 200 |
|
||||
| `GET /api/auth/setup-status` (no auth) | 200; `setup_required=false` |
|
||||
| API Key on `GET /api/v1/chat/sessions?username=...` | 200 |
|
||||
| Auth styles accepted | `Authorization: Bearer abk_…`, `X-API-Key`, `Authorization: ApiKey …`, query `api_key` (prefer headers only in Desktop) |
|
||||
| `GET /api/v1/configs` | 200; one config `default` |
|
||||
| `GET /api/v1/im/bots` | 200; `bot_ids=["napcat3"]` |
|
||||
| `GET /api/v1/openapi.json` / `/docs` / several management routes | Often SPA-style HTML 404 page even when authenticated; **do not rely on OpenAPI UI path on this deployment** |
|
||||
| Dashboard JWT login | Not exercised in this probe (API key path is sufficient for automation) |
|
||||
|
||||
### Chat SSE (authoritative live sample)
|
||||
|
||||
`POST /api/v1/chat` with:
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "desktop-probe ...",
|
||||
"username": "desktop-companion|desktop-operations",
|
||||
"session_id": "desktop-*-s1",
|
||||
"enable_streaming": true
|
||||
}
|
||||
```
|
||||
|
||||
Observed response:
|
||||
|
||||
- HTTP 200
|
||||
- `Content-Type: text/event-stream`
|
||||
- Initial frames:
|
||||
1. `{"type":"session_id","data":null,"session_id":"..."}`
|
||||
2. `{"type":"user_message_saved","data":{"id":N,"created_at":"...","llm_checkpoint_id":"..."}}`
|
||||
3. Comment heartbeats: `: heartbeat`
|
||||
4. Streamed assistant tokens:
|
||||
`{"type":"plain","data":"Hello","streaming":true,"chain_type":null,"message_id":"..."}`
|
||||
- `message_id` is stable across one assistant generation
|
||||
- Client may close after idle heartbeats; server can keep heartbeating after partial generation
|
||||
- Terminal `message_saved` / `end` frames were **not always observed** before client idle-close in this probe; adapter must tolerate incomplete terminal markers and reconstruct final text from accumulated `plain` frames + later session history fetch if needed
|
||||
|
||||
### Dual-slot isolation evidence
|
||||
|
||||
| Desktop-like identity | `username` | `session_id` | Session list total |
|
||||
| --- | --- | --- | --- |
|
||||
| Companion | `desktop-companion` | `desktop-companion-s1` | 1 |
|
||||
| Operations | `desktop-operations` | `desktop-operations-s1` | 1 |
|
||||
|
||||
Session list responses were fully isolated by `username`. Same API key can drive both slots if Desktop binds different local usernames/session ids per Profile. Prefer separate API keys later for least privilege, but not required for MVP connectivity.
|
||||
|
||||
### Mapping recommendation (internal Desktop events)
|
||||
|
||||
| AstrBot live frame | Desktop normalized event |
|
||||
| --- | --- |
|
||||
| comment `: heartbeat` | local connection liveness only (optional `system.heartbeat`) |
|
||||
| `session_id` | bind conversation/session identity |
|
||||
| `user_message_saved` | local user message ack / persistence metadata |
|
||||
| `plain` + `streaming=true` | `message.delta` (append `data`) |
|
||||
| accumulated plain until idle/end | `message.completed` (client synthesized if server omits terminal frame) |
|
||||
| `error` | `error` |
|
||||
| no `tool.proposal` observed | keep operations tools Desktop-local for now |
|
||||
|
||||
### Implementability verdict
|
||||
|
||||
| Goal | Verdict |
|
||||
| --- | --- |
|
||||
| Text chat against real AstrBot | **Implementable now** via adapter |
|
||||
| Dual companion/operations chat panels on one server | **Implementable** with per-slot `username` + `session_id` |
|
||||
| Direct use of provisional `/desktop/v1` against this server | **Not possible** |
|
||||
| Long-lived server push bus + ACK | **Not available**; redesign stream manager |
|
||||
| Server-driven local tool proposals | **Not available** on stock API |
|
||||
| Need to rewrite whole Desktop app | **No** |
|
||||
|
||||
### Remaining probe gaps (non-blocking for chat MVP)
|
||||
|
||||
- Dashboard password login / JWT expiry behavior not live-tested
|
||||
- File upload (`POST /api/v1/file`) not tested
|
||||
- WebSocket `/api/v1/chat/ws` not tested
|
||||
- Re-attach `GET /api/v1/chat/runs/{run_id}/stream` not tested
|
||||
- No durable `serverInstanceId` discovery endpoint; still needs identity substitute design
|
||||
- This deployment returns SPA 404 HTML for some documented OpenAPI paths; adapter should feature-detect actual routes rather than assume full OpenAPI UI availability
|
||||
|
||||
### Security notes from probe
|
||||
|
||||
- API key worked and must stay in Windows Credential Manager only
|
||||
- Never log full key; sample captures store `abk_[REDACTED]`
|
||||
- Prefer header auth, not query-string key
|
||||
- Target is plain HTTP on LAN; TLS pinning decision remains open for production Profiles
|
||||
61
docs/reports/run-live-probe.ps1
普通文件
61
docs/reports/run-live-probe.ps1
普通文件
|
|
@ -0,0 +1,61 @@
|
|||
# Non-destructive AstrBot live probe helper.
|
||||
# Usage:
|
||||
# $env:ASTRBOT_PROBE_KEY = "abk_..."
|
||||
# $env:ASTRBOT_PROBE_BASE = "http://host:port"
|
||||
# powershell -NoProfile -ExecutionPolicy Bypass -File .\run-live-probe.ps1
|
||||
$ErrorActionPreference = "Stop"
|
||||
$base = if ($env:ASTRBOT_PROBE_BASE) { $env:ASTRBOT_PROBE_BASE } else { "http://127.0.0.1:6185" }
|
||||
$key = $env:ASTRBOT_PROBE_KEY
|
||||
if (-not $key) { throw "Set ASTRBOT_PROBE_KEY first" }
|
||||
$outDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
$sseFile = Join-Path $outDir "astrbot-live-probe-sse.raw.txt"
|
||||
$sumFile = Join-Path $outDir "astrbot-live-probe-summary.json"
|
||||
$logFile = Join-Path $outDir "astrbot-live-probe-run.log"
|
||||
function Log($m) { Add-Content -Path $logFile -Value ("[{0}] {1}" -f (Get-Date -Format o), $m) -Encoding utf8 }
|
||||
function Invoke-SseChat([string]$body, [string]$label, [int]$timeoutSec = 90) {
|
||||
Log "chat $label begin"
|
||||
$req = [System.Net.HttpWebRequest]::Create("$base/api/v1/chat")
|
||||
$req.Method = "POST"; $req.Timeout = $timeoutSec * 1000; $req.ReadWriteTimeout = 20000
|
||||
$req.ContentType = "application/json; charset=utf-8"; $req.Accept = "text/event-stream, application/json"
|
||||
$req.Headers.Add("Authorization", "Bearer $key")
|
||||
$bytes = [System.Text.Encoding]::UTF8.GetBytes($body)
|
||||
$req.ContentLength = $bytes.Length
|
||||
$rs = $req.GetRequestStream(); $rs.Write($bytes,0,$bytes.Length); $rs.Close()
|
||||
$resp = $req.GetResponse(); $reader = New-Object System.IO.StreamReader($resp.GetResponseStream())
|
||||
$sb = New-Object System.Text.StringBuilder
|
||||
$deadline = [DateTime]::UtcNow.AddSeconds($timeoutSec)
|
||||
$lastData = [DateTime]::UtcNow; $plain = 0; $saved = $false
|
||||
while ([DateTime]::UtcNow -lt $deadline) {
|
||||
if ($reader.EndOfStream) { break }
|
||||
try { $line = $reader.ReadLine() } catch { break }
|
||||
if ($null -eq $line) { break }
|
||||
[void]$sb.AppendLine($line)
|
||||
if ($line.StartsWith("data:")) {
|
||||
$lastData = [DateTime]::UtcNow
|
||||
if ($line -match '"type": "plain"') { $plain++ }
|
||||
if ($line -match '"type": "message_saved"' -or $line -match '"type": "error"') { $saved = $true }
|
||||
}
|
||||
if ($plain -gt 0 -and (([DateTime]::UtcNow - $lastData).TotalSeconds -ge 8)) { break }
|
||||
if ($saved -and (([DateTime]::UtcNow - $lastData).TotalSeconds -ge 2)) { break }
|
||||
}
|
||||
try { $reader.Close() } catch {}; try { $resp.Close() } catch {}
|
||||
Log "chat $label done len=$($sb.Length) plain=$plain saved=$saved"
|
||||
return [PSCustomObject]@{ Length=$sb.Length; Body=$sb.ToString(); Plain=$plain; Saved=$saved }
|
||||
}
|
||||
function Get-Json($uri) {
|
||||
$req = [System.Net.HttpWebRequest]::Create($uri); $req.Method = "GET"; $req.Timeout = 20000
|
||||
$req.Headers.Add("Authorization", "Bearer $key")
|
||||
$resp = $req.GetResponse(); $r = New-Object System.IO.StreamReader($resp.GetResponseStream()); $t = $r.ReadToEnd(); $r.Close(); $resp.Close(); return $t
|
||||
}
|
||||
"" | Set-Content $logFile -Encoding utf8
|
||||
Log "start base=$base"
|
||||
$rA = Invoke-SseChat '{"message":"desktop-probe A","username":"desktop-companion","session_id":"desktop-companion-s1","enable_streaming":true}' "companion" 90
|
||||
$rB = Invoke-SseChat '{"message":"desktop-probe B","username":"desktop-operations","session_id":"desktop-operations-s1","enable_streaming":true}' "operations" 90
|
||||
$sessA = Get-Json "$base/api/v1/chat/sessions?username=desktop-companion&page=1&page_size=20"
|
||||
$sessB = Get-Json "$base/api/v1/chat/sessions?username=desktop-operations&page=1&page_size=20"
|
||||
$raw = "=== companion ===`n$($rA.Body)`n=== operations ===`n$($rB.Body)`n=== sessions companion ===`n$sessA`n=== sessions operations ===`n$sessB"
|
||||
($raw -replace [regex]::Escape($key), "abk_[REDACTED]") | Set-Content $sseFile -Encoding utf8
|
||||
function Types($b){ $m=@{}; foreach($x in [regex]::Matches($b,'"type"\s*:\s*"([^"]+)"')){ $k=$x.Groups[1].Value; if($m.ContainsKey($k)){$m[$k]++}else{$m[$k]=1}}; $m }
|
||||
$summary = [ordered]@{ ok=$true; base=$base; companion=@{length=$rA.Length;plain=$rA.Plain;saved=$rA.Saved;types=(Types $rA.Body)}; operations=@{length=$rB.Length;plain=$rB.Plain;saved=$rB.Saved;types=(Types $rB.Body)}; sessionsCompanion=($sessA|ConvertFrom-Json); sessionsOperations=($sessB|ConvertFrom-Json) }
|
||||
($summary | ConvertTo-Json -Depth 8) | Set-Content $sumFile -Encoding utf8
|
||||
Log "done"
|
||||
|
|
@ -2,6 +2,6 @@
|
|||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Minimal capability set for the main AstrBot Desktop window.",
|
||||
"windows": ["main"],
|
||||
"windows": ["main", "quick-chat", "status-bubble"],
|
||||
"permissions": ["core:default"]
|
||||
}
|
||||
|
|
|
|||
362
src-tauri/src/credentials/mod.rs
普通文件
362
src-tauri/src/credentials/mod.rs
普通文件
|
|
@ -0,0 +1,362 @@
|
|||
use desktop_protocol::AuthenticationType;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::database::{ApplicationDatabase, DatabaseError};
|
||||
use crate::secure_store::{
|
||||
CredentialReference, SecretCredential, SecureCredentialStore, SecureStoreError,
|
||||
WindowsCredentialStore,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct EnrollCredentialRequest {
|
||||
pub profile_id: String,
|
||||
pub authentication_type: AuthenticationType,
|
||||
/// One-shot secret. Never returned to React and never logged.
|
||||
pub secret: String,
|
||||
#[serde(default)]
|
||||
pub username: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CredentialEnrollmentResult {
|
||||
pub profile_id: String,
|
||||
pub credential_reference: String,
|
||||
pub authentication_type: AuthenticationType,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CredentialCommandError {
|
||||
pub code: &'static str,
|
||||
pub message: &'static str,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for CredentialCommandError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(self.message)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for CredentialCommandError {}
|
||||
|
||||
impl CredentialCommandError {
|
||||
fn validation(message: &'static str) -> Self {
|
||||
Self {
|
||||
code: "validationFailed",
|
||||
message,
|
||||
}
|
||||
}
|
||||
|
||||
fn not_found() -> Self {
|
||||
Self {
|
||||
code: "notFound",
|
||||
message: "The connection profile no longer exists.",
|
||||
}
|
||||
}
|
||||
|
||||
fn store() -> Self {
|
||||
Self {
|
||||
code: "secureStoreUnavailable",
|
||||
message: "Windows Credential Manager is unavailable.",
|
||||
}
|
||||
}
|
||||
|
||||
fn database() -> Self {
|
||||
Self {
|
||||
code: "databaseUnavailable",
|
||||
message: "The local profile database is unavailable.",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn enroll_profile_credential(
|
||||
database: tauri::State<'_, ApplicationDatabase>,
|
||||
request: EnrollCredentialRequest,
|
||||
) -> Result<CredentialEnrollmentResult, CredentialCommandError> {
|
||||
enroll_credential(&database, &WindowsCredentialStore, request)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn clear_profile_credential(
|
||||
database: tauri::State<'_, ApplicationDatabase>,
|
||||
profile_id: String,
|
||||
) -> Result<(), CredentialCommandError> {
|
||||
clear_credential(&database, &WindowsCredentialStore, &profile_id)
|
||||
}
|
||||
|
||||
pub fn enroll_credential(
|
||||
database: &ApplicationDatabase,
|
||||
store: &impl SecureCredentialStore,
|
||||
request: EnrollCredentialRequest,
|
||||
) -> Result<CredentialEnrollmentResult, CredentialCommandError> {
|
||||
if Uuid::parse_str(&request.profile_id).is_err() {
|
||||
return Err(CredentialCommandError::validation(
|
||||
"profile_id must be a UUID.",
|
||||
));
|
||||
}
|
||||
if request.secret.trim().is_empty() {
|
||||
return Err(CredentialCommandError::validation(
|
||||
"credential secret must not be empty.",
|
||||
));
|
||||
}
|
||||
if request.secret.len() > 2_560 {
|
||||
return Err(CredentialCommandError::validation(
|
||||
"credential secret exceeds the supported length.",
|
||||
));
|
||||
}
|
||||
|
||||
let mut profile = database
|
||||
.profile(&request.profile_id)
|
||||
.map_err(|_| CredentialCommandError::database())?
|
||||
.ok_or_else(CredentialCommandError::not_found)?;
|
||||
|
||||
// Replace any previous reference after a successful write.
|
||||
let reference = CredentialReference::new();
|
||||
let credential =
|
||||
SecretCredential::with_username(request.username.clone(), request.secret.into_bytes())
|
||||
.map_err(|error| match error {
|
||||
SecureStoreError::InvalidSecretLength | SecureStoreError::InvalidUsername => {
|
||||
CredentialCommandError::validation("credential secret is invalid.")
|
||||
}
|
||||
_ => CredentialCommandError::store(),
|
||||
})?;
|
||||
|
||||
store
|
||||
.write(reference, &credential)
|
||||
.map_err(|_| CredentialCommandError::store())?;
|
||||
|
||||
if let Some(previous) = profile
|
||||
.credential_reference
|
||||
.as_ref()
|
||||
.and_then(|value| Uuid::parse_str(value).ok())
|
||||
.map(CredentialReference::from_uuid)
|
||||
{
|
||||
let _ = store.delete(previous);
|
||||
}
|
||||
|
||||
profile.credential_reference = Some(reference.as_uuid().to_string());
|
||||
profile.authentication_type = request.authentication_type;
|
||||
profile.updated_at = current_timestamp();
|
||||
database
|
||||
.update_profile(&profile)
|
||||
.map_err(|error| match error {
|
||||
DatabaseError::ProfileNotFound => CredentialCommandError::not_found(),
|
||||
_ => CredentialCommandError::database(),
|
||||
})?;
|
||||
|
||||
Ok(CredentialEnrollmentResult {
|
||||
profile_id: profile.id,
|
||||
credential_reference: reference.as_uuid().to_string(),
|
||||
authentication_type: profile.authentication_type,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn clear_credential(
|
||||
database: &ApplicationDatabase,
|
||||
store: &impl SecureCredentialStore,
|
||||
profile_id: &str,
|
||||
) -> Result<(), CredentialCommandError> {
|
||||
if Uuid::parse_str(profile_id).is_err() {
|
||||
return Err(CredentialCommandError::validation(
|
||||
"profile_id must be a UUID.",
|
||||
));
|
||||
}
|
||||
let mut profile = database
|
||||
.profile(profile_id)
|
||||
.map_err(|_| CredentialCommandError::database())?
|
||||
.ok_or_else(CredentialCommandError::not_found)?;
|
||||
|
||||
if let Some(previous) = profile
|
||||
.credential_reference
|
||||
.as_ref()
|
||||
.and_then(|value| Uuid::parse_str(value).ok())
|
||||
.map(CredentialReference::from_uuid)
|
||||
{
|
||||
let _ = store.delete(previous);
|
||||
}
|
||||
profile.credential_reference = None;
|
||||
profile.updated_at = current_timestamp();
|
||||
database
|
||||
.update_profile(&profile)
|
||||
.map_err(|_| CredentialCommandError::database())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Loads a secret for Rust-owned networking only. Never exposed through Tauri commands.
|
||||
pub fn load_profile_secret(
|
||||
database: &ApplicationDatabase,
|
||||
store: &impl SecureCredentialStore,
|
||||
profile_id: &str,
|
||||
) -> Result<Option<SecretCredential>, CredentialCommandError> {
|
||||
let profile = database
|
||||
.profile(profile_id)
|
||||
.map_err(|_| CredentialCommandError::database())?
|
||||
.ok_or_else(CredentialCommandError::not_found)?;
|
||||
let Some(reference) = profile
|
||||
.credential_reference
|
||||
.as_ref()
|
||||
.and_then(|value| Uuid::parse_str(value).ok())
|
||||
.map(CredentialReference::from_uuid)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
store
|
||||
.read(reference)
|
||||
.map_err(|_| CredentialCommandError::store())
|
||||
}
|
||||
|
||||
fn current_timestamp() -> String {
|
||||
time::OffsetDateTime::now_utc()
|
||||
.format(&time::format_description::well_known::Rfc3339)
|
||||
.unwrap_or_else(|_| "1970-01-01T00:00:00Z".into())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use desktop_protocol::{AstrBotProfileRole, ConnectionProfile};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Mutex;
|
||||
|
||||
type MemoryCredential = (Option<String>, Vec<u8>);
|
||||
|
||||
#[derive(Default)]
|
||||
struct MemoryStore {
|
||||
values: Mutex<HashMap<Uuid, MemoryCredential>>,
|
||||
}
|
||||
|
||||
impl SecureCredentialStore for MemoryStore {
|
||||
fn write(
|
||||
&self,
|
||||
reference: CredentialReference,
|
||||
credential: &SecretCredential,
|
||||
) -> Result<(), SecureStoreError> {
|
||||
self.values.lock().expect("lock").insert(
|
||||
reference.as_uuid(),
|
||||
(
|
||||
credential.username().map(str::to_owned),
|
||||
credential.secret().to_vec(),
|
||||
),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read(
|
||||
&self,
|
||||
reference: CredentialReference,
|
||||
) -> Result<Option<SecretCredential>, SecureStoreError> {
|
||||
match self.values.lock().expect("lock").get(&reference.as_uuid()) {
|
||||
Some((username, secret)) => Ok(Some(SecretCredential::with_username(
|
||||
username.clone(),
|
||||
secret.clone(),
|
||||
)?)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn delete(&self, reference: CredentialReference) -> Result<bool, SecureStoreError> {
|
||||
Ok(self
|
||||
.values
|
||||
.lock()
|
||||
.expect("lock")
|
||||
.remove(&reference.as_uuid())
|
||||
.is_some())
|
||||
}
|
||||
}
|
||||
|
||||
fn sample_profile() -> ConnectionProfile {
|
||||
ConnectionProfile {
|
||||
id: "11111111-1111-1111-1111-111111111111".into(),
|
||||
display_name: "Probe".into(),
|
||||
role: AstrBotProfileRole::Companion,
|
||||
base_url: "http://127.0.0.1:26285/".into(),
|
||||
event_stream_url: None,
|
||||
authentication_type: AuthenticationType::ApiKey,
|
||||
transport_kind: desktop_protocol::TransportKind::AstrBotOpenApi,
|
||||
credential_reference: None,
|
||||
allow_insecure_http: true,
|
||||
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,
|
||||
remote_username: None,
|
||||
sticky_session_id: None,
|
||||
created_at: "2026-07-20T00:00:00Z".into(),
|
||||
updated_at: "2026-07-20T00:00:00Z".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enrolls_and_clears_credential_reference_without_returning_secret() {
|
||||
let database = ApplicationDatabase::in_memory().expect("db");
|
||||
let profile = sample_profile();
|
||||
database.create_profile(&profile).expect("create");
|
||||
let store = MemoryStore::default();
|
||||
|
||||
let enrolled = enroll_credential(
|
||||
&database,
|
||||
&store,
|
||||
EnrollCredentialRequest {
|
||||
profile_id: profile.id.clone(),
|
||||
authentication_type: AuthenticationType::ApiKey,
|
||||
secret: "abk_test_secret".into(),
|
||||
username: Some("desktop-companion".into()),
|
||||
},
|
||||
)
|
||||
.expect("enroll");
|
||||
assert!(!enrolled.credential_reference.is_empty());
|
||||
let stored = database
|
||||
.profile(&profile.id)
|
||||
.expect("profile")
|
||||
.expect("exists");
|
||||
assert_eq!(
|
||||
stored.credential_reference.as_deref(),
|
||||
Some(enrolled.credential_reference.as_str())
|
||||
);
|
||||
|
||||
let secret = load_profile_secret(&database, &store, &profile.id)
|
||||
.expect("load")
|
||||
.expect("secret");
|
||||
assert_eq!(secret.secret(), b"abk_test_secret");
|
||||
assert_eq!(secret.username(), Some("desktop-companion"));
|
||||
|
||||
clear_credential(&database, &store, &profile.id).expect("clear");
|
||||
let cleared = database
|
||||
.profile(&profile.id)
|
||||
.expect("profile")
|
||||
.expect("exists");
|
||||
assert!(cleared.credential_reference.is_none());
|
||||
assert!(
|
||||
load_profile_secret(&database, &store, &profile.id)
|
||||
.expect("load missing")
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_empty_secret() {
|
||||
let database = ApplicationDatabase::in_memory().expect("db");
|
||||
database.create_profile(&sample_profile()).expect("create");
|
||||
let store = MemoryStore::default();
|
||||
let error = enroll_credential(
|
||||
&database,
|
||||
&store,
|
||||
EnrollCredentialRequest {
|
||||
profile_id: "11111111-1111-1111-1111-111111111111".into(),
|
||||
authentication_type: AuthenticationType::ApiKey,
|
||||
secret: " ".into(),
|
||||
username: None,
|
||||
},
|
||||
)
|
||||
.expect_err("empty");
|
||||
assert_eq!(error.code, "validationFailed");
|
||||
}
|
||||
}
|
||||
|
|
@ -2,11 +2,12 @@ mod profiles;
|
|||
mod slots;
|
||||
|
||||
use std::{path::Path, sync::Mutex, time::Duration};
|
||||
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
|
||||
|
||||
use rusqlite::{Connection, OptionalExtension, params};
|
||||
use thiserror::Error;
|
||||
|
||||
pub const CURRENT_SCHEMA_VERSION: u32 = 3;
|
||||
pub const CURRENT_SCHEMA_VERSION: u32 = 5;
|
||||
|
||||
pub struct ApplicationDatabase {
|
||||
store: Mutex<ProfileMessageStore>,
|
||||
|
|
@ -32,6 +33,52 @@ impl ApplicationDatabase {
|
|||
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||
.schema_version()
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn upsert_chat_message(
|
||||
&self,
|
||||
account_id: &str,
|
||||
profile_id: &str,
|
||||
slot: &str,
|
||||
server_instance_id: &str,
|
||||
remote_username: Option<&str>,
|
||||
session_id: &str,
|
||||
message_id: &str,
|
||||
role: &str,
|
||||
content: &str,
|
||||
streaming: bool,
|
||||
error: bool,
|
||||
) -> Result<(), DatabaseError> {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||
.upsert_chat_message(
|
||||
account_id,
|
||||
profile_id,
|
||||
slot,
|
||||
server_instance_id,
|
||||
remote_username,
|
||||
session_id,
|
||||
message_id,
|
||||
role,
|
||||
content,
|
||||
streaming,
|
||||
error,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn list_chat_messages(
|
||||
&self,
|
||||
profile_id: &str,
|
||||
server_instance_id: &str,
|
||||
session_id: &str,
|
||||
limit: usize,
|
||||
) -> Result<Vec<StoredChatMessage>, DatabaseError> {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||
.list_chat_messages(profile_id, server_instance_id, session_id, limit)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ProfileMessageStore {
|
||||
|
|
@ -91,6 +138,63 @@ impl ProfileMessageStore {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn upsert_chat_message(
|
||||
&self,
|
||||
account_id: &str,
|
||||
profile_id: &str,
|
||||
slot: &str,
|
||||
server_instance_id: &str,
|
||||
remote_username: Option<&str>,
|
||||
session_id: &str,
|
||||
message_id: &str,
|
||||
role: &str,
|
||||
content: &str,
|
||||
streaming: bool,
|
||||
error: bool,
|
||||
) -> Result<(), DatabaseError> {
|
||||
let timestamp = OffsetDateTime::now_utc()
|
||||
.format(&Rfc3339)
|
||||
.map_err(|_| DatabaseError::InvalidStoredMessage)?;
|
||||
self.connection.execute(
|
||||
"INSERT INTO chat_messages (account_id, profile_id, slot, server_instance_id, remote_username, session_id, message_id, role, content, streaming, error, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12) ON CONFLICT(profile_id, server_instance_id, session_id, message_id) DO UPDATE SET content = excluded.content, streaming = excluded.streaming, error = excluded.error, updated_at = excluded.updated_at",
|
||||
params![account_id, profile_id, slot, server_instance_id, remote_username, session_id, message_id, role, content, streaming, error, timestamp],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn list_chat_messages(
|
||||
&self,
|
||||
profile_id: &str,
|
||||
server_instance_id: &str,
|
||||
session_id: &str,
|
||||
limit: usize,
|
||||
) -> Result<Vec<StoredChatMessage>, DatabaseError> {
|
||||
let limit = limit.clamp(1, 200) as i64;
|
||||
let mut statement = self.connection.prepare("SELECT account_id, profile_id, slot, server_instance_id, remote_username, session_id, message_id, role, content, streaming, error, updated_at FROM chat_messages WHERE profile_id = ?1 AND server_instance_id = ?2 AND session_id = ?3 ORDER BY updated_at ASC LIMIT ?4")?;
|
||||
let rows = statement.query_map(
|
||||
params![profile_id, server_instance_id, session_id, limit],
|
||||
|row| {
|
||||
Ok(StoredChatMessage {
|
||||
account_id: row.get(0)?,
|
||||
profile_id: row.get(1)?,
|
||||
slot: row.get(2)?,
|
||||
server_instance_id: row.get(3)?,
|
||||
remote_username: row.get(4)?,
|
||||
session_id: row.get(5)?,
|
||||
message_id: row.get(6)?,
|
||||
role: row.get(7)?,
|
||||
content: row.get(8)?,
|
||||
streaming: row.get::<_, i64>(9)? != 0,
|
||||
error: row.get::<_, i64>(10)? != 0,
|
||||
updated_at: row.get(11)?,
|
||||
})
|
||||
},
|
||||
)?;
|
||||
rows.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(DatabaseError::from)
|
||||
}
|
||||
|
||||
pub fn message_content(
|
||||
&self,
|
||||
profile_id: &str,
|
||||
|
|
@ -116,6 +220,23 @@ impl ProfileMessageStore {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct StoredChatMessage {
|
||||
pub account_id: String,
|
||||
pub profile_id: String,
|
||||
pub slot: String,
|
||||
pub server_instance_id: String,
|
||||
pub remote_username: Option<String>,
|
||||
pub session_id: String,
|
||||
pub message_id: String,
|
||||
pub role: String,
|
||||
pub content: String,
|
||||
pub streaming: bool,
|
||||
pub error: bool,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
fn configure_connection(connection: &Connection, persistent: bool) -> Result<(), DatabaseError> {
|
||||
connection.pragma_update(None, "foreign_keys", "ON")?;
|
||||
connection.busy_timeout(Duration::from_secs(5))?;
|
||||
|
|
@ -206,6 +327,37 @@ fn migrate(connection: &mut Connection) -> Result<(), DatabaseError> {
|
|||
transaction.commit()?;
|
||||
}
|
||||
|
||||
if found <= 3 {
|
||||
let transaction = connection.transaction()?;
|
||||
let has_transport: bool = transaction
|
||||
.prepare("PRAGMA table_info(connection_profiles)")?
|
||||
.query_map([], |row| row.get::<_, String>(1))?
|
||||
.filter_map(Result::ok)
|
||||
.any(|name| name == "transport_kind");
|
||||
if !has_transport {
|
||||
transaction.execute_batch(
|
||||
"
|
||||
ALTER TABLE connection_profiles
|
||||
ADD COLUMN transport_kind TEXT NOT NULL DEFAULT 'desktop-v1';
|
||||
ALTER TABLE connection_profiles
|
||||
ADD COLUMN remote_username TEXT;
|
||||
ALTER TABLE connection_profiles
|
||||
ADD COLUMN sticky_session_id TEXT;
|
||||
",
|
||||
)?;
|
||||
}
|
||||
transaction.pragma_update(None, "user_version", 4)?;
|
||||
transaction.commit()?;
|
||||
}
|
||||
|
||||
if found <= 4 {
|
||||
let transaction = connection.transaction()?;
|
||||
transaction.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS chat_messages (account_id TEXT NOT NULL, profile_id TEXT NOT NULL, slot TEXT NOT NULL CHECK(slot IN ('companion', 'operations')), server_instance_id TEXT NOT NULL, remote_username TEXT, session_id TEXT NOT NULL, message_id TEXT NOT NULL, role TEXT NOT NULL CHECK(role IN ('user', 'assistant', 'system')), content TEXT NOT NULL, streaming INTEGER NOT NULL DEFAULT 0 CHECK(streaming IN (0, 1)), error INTEGER NOT NULL DEFAULT 0 CHECK(error IN (0, 1)), updated_at TEXT NOT NULL, PRIMARY KEY (profile_id, server_instance_id, session_id, message_id)); CREATE INDEX IF NOT EXISTS chat_messages_account_session_idx ON chat_messages(account_id, session_id, updated_at); PRAGMA user_version = 5;",
|
||||
)?;
|
||||
transaction.commit()?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -221,6 +373,8 @@ pub enum DatabaseError {
|
|||
InvalidStoredProfile,
|
||||
#[error("database contains invalid connection slot data")]
|
||||
InvalidStoredSlot,
|
||||
#[error("database contains invalid chat message data")]
|
||||
InvalidStoredMessage,
|
||||
#[error("connection profile was not found")]
|
||||
ProfileNotFound,
|
||||
#[error("connection slot was not found")]
|
||||
|
|
@ -305,7 +459,7 @@ mod tests {
|
|||
drop(connection);
|
||||
|
||||
let store = ProfileMessageStore::open(&path).expect("migrate database");
|
||||
assert_eq!(store.schema_version().expect("schema version"), 3);
|
||||
assert_eq!(store.schema_version().expect("schema version"), 5);
|
||||
assert_eq!(
|
||||
store
|
||||
.message_content("profile-a", "server-a", "conversation-a", "message-a")
|
||||
|
|
@ -368,6 +522,8 @@ mod tests {
|
|||
.execute_batch(
|
||||
"
|
||||
DROP TABLE connection_slots;
|
||||
-- Keep only v2-era profile columns when present.
|
||||
-- Current schema may already include v4 columns; migration must tolerate that.
|
||||
PRAGMA user_version = 2;
|
||||
",
|
||||
)
|
||||
|
|
@ -375,7 +531,7 @@ mod tests {
|
|||
}
|
||||
|
||||
let reopened = ProfileMessageStore::open(&path).expect("migrate v2 database");
|
||||
assert_eq!(reopened.schema_version().expect("schema version"), 3);
|
||||
assert_eq!(reopened.schema_version().expect("schema version"), 5);
|
||||
let profile_count: u32 = reopened
|
||||
.connection
|
||||
.query_row(
|
||||
|
|
@ -408,9 +564,9 @@ mod tests {
|
|||
assert!(matches!(
|
||||
ProfileMessageStore::open(path),
|
||||
Err(DatabaseError::UnsupportedSchemaVersion {
|
||||
found: 4,
|
||||
found,
|
||||
supported: CURRENT_SCHEMA_VERSION
|
||||
})
|
||||
}) if found == CURRENT_SCHEMA_VERSION + 1
|
||||
));
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,349 +1,381 @@
|
|||
use desktop_protocol::{ActiveSlotKind, AstrBotProfileRole, AuthenticationType, ConnectionProfile};
|
||||
use rusqlite::{Row, params};
|
||||
|
||||
use super::{ApplicationDatabase, DatabaseError, ProfileMessageStore};
|
||||
|
||||
const PROFILE_COLUMNS: &str = "
|
||||
id,
|
||||
display_name,
|
||||
role,
|
||||
base_url,
|
||||
event_stream_url,
|
||||
authentication_type,
|
||||
credential_reference,
|
||||
allow_insecure_http,
|
||||
pinned_certificate_fingerprint,
|
||||
auto_connect_slot,
|
||||
auto_connect,
|
||||
server_instance_id,
|
||||
server_version,
|
||||
protocol_version,
|
||||
local_tool_policy_id,
|
||||
last_connected_at,
|
||||
created_at,
|
||||
updated_at
|
||||
";
|
||||
|
||||
impl ApplicationDatabase {
|
||||
pub fn list_profiles(&self) -> Result<Vec<ConnectionProfile>, DatabaseError> {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||
.list_profiles()
|
||||
}
|
||||
|
||||
pub fn profile(&self, id: &str) -> Result<Option<ConnectionProfile>, DatabaseError> {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||
.profile(id)
|
||||
}
|
||||
|
||||
pub fn create_profile(&self, profile: &ConnectionProfile) -> Result<(), DatabaseError> {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||
.create_profile(profile)
|
||||
}
|
||||
|
||||
pub fn update_profile(&self, profile: &ConnectionProfile) -> Result<(), DatabaseError> {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||
.update_profile(profile)
|
||||
}
|
||||
|
||||
pub fn delete_profile(&self, id: &str) -> Result<(), DatabaseError> {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||
.delete_profile(id)
|
||||
}
|
||||
}
|
||||
|
||||
impl ProfileMessageStore {
|
||||
fn list_profiles(&self) -> Result<Vec<ConnectionProfile>, DatabaseError> {
|
||||
let mut statement = self.connection.prepare(&format!(
|
||||
"SELECT {PROFILE_COLUMNS}
|
||||
FROM connection_profiles
|
||||
ORDER BY display_name COLLATE NOCASE, id"
|
||||
))?;
|
||||
let mut rows = statement.query([])?;
|
||||
let mut profiles = Vec::new();
|
||||
while let Some(row) = rows.next()? {
|
||||
profiles.push(profile_from_row(row)?);
|
||||
}
|
||||
Ok(profiles)
|
||||
}
|
||||
|
||||
fn profile(&self, id: &str) -> Result<Option<ConnectionProfile>, DatabaseError> {
|
||||
let mut statement = self.connection.prepare(&format!(
|
||||
"SELECT {PROFILE_COLUMNS}
|
||||
FROM connection_profiles
|
||||
WHERE id = ?1"
|
||||
))?;
|
||||
let mut rows = statement.query(params![id])?;
|
||||
match rows.next()? {
|
||||
Some(row) => Ok(Some(profile_from_row(row)?)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn create_profile(&self, profile: &ConnectionProfile) -> Result<(), DatabaseError> {
|
||||
self.connection.execute(
|
||||
"
|
||||
INSERT INTO connection_profiles (
|
||||
id,
|
||||
display_name,
|
||||
role,
|
||||
base_url,
|
||||
event_stream_url,
|
||||
authentication_type,
|
||||
credential_reference,
|
||||
allow_insecure_http,
|
||||
pinned_certificate_fingerprint,
|
||||
auto_connect_slot,
|
||||
auto_connect,
|
||||
server_instance_id,
|
||||
server_version,
|
||||
protocol_version,
|
||||
local_tool_policy_id,
|
||||
last_connected_at,
|
||||
created_at,
|
||||
updated_at
|
||||
) VALUES (
|
||||
?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9,
|
||||
?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18
|
||||
)
|
||||
",
|
||||
params![
|
||||
profile.id,
|
||||
profile.display_name,
|
||||
role_to_str(profile.role),
|
||||
profile.base_url,
|
||||
profile.event_stream_url,
|
||||
authentication_to_str(profile.authentication_type),
|
||||
profile.credential_reference,
|
||||
profile.allow_insecure_http,
|
||||
profile.pinned_certificate_fingerprint,
|
||||
profile.auto_connect_slot.map(slot_to_str),
|
||||
profile.auto_connect,
|
||||
profile.server_instance_id,
|
||||
profile.server_version,
|
||||
profile.protocol_version,
|
||||
profile.local_tool_policy_id,
|
||||
profile.last_connected_at,
|
||||
profile.created_at,
|
||||
profile.updated_at,
|
||||
],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn update_profile(&self, profile: &ConnectionProfile) -> Result<(), DatabaseError> {
|
||||
let changed = self.connection.execute(
|
||||
"
|
||||
UPDATE connection_profiles
|
||||
SET display_name = ?2,
|
||||
role = ?3,
|
||||
base_url = ?4,
|
||||
event_stream_url = ?5,
|
||||
authentication_type = ?6,
|
||||
credential_reference = ?7,
|
||||
allow_insecure_http = ?8,
|
||||
pinned_certificate_fingerprint = ?9,
|
||||
auto_connect_slot = ?10,
|
||||
auto_connect = ?11,
|
||||
server_instance_id = ?12,
|
||||
server_version = ?13,
|
||||
protocol_version = ?14,
|
||||
local_tool_policy_id = ?15,
|
||||
last_connected_at = ?16,
|
||||
created_at = ?17,
|
||||
updated_at = ?18
|
||||
WHERE id = ?1
|
||||
",
|
||||
params![
|
||||
profile.id,
|
||||
profile.display_name,
|
||||
role_to_str(profile.role),
|
||||
profile.base_url,
|
||||
profile.event_stream_url,
|
||||
authentication_to_str(profile.authentication_type),
|
||||
profile.credential_reference,
|
||||
profile.allow_insecure_http,
|
||||
profile.pinned_certificate_fingerprint,
|
||||
profile.auto_connect_slot.map(slot_to_str),
|
||||
profile.auto_connect,
|
||||
profile.server_instance_id,
|
||||
profile.server_version,
|
||||
profile.protocol_version,
|
||||
profile.local_tool_policy_id,
|
||||
profile.last_connected_at,
|
||||
profile.created_at,
|
||||
profile.updated_at,
|
||||
],
|
||||
)?;
|
||||
if changed == 0 {
|
||||
return Err(DatabaseError::ProfileNotFound);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn delete_profile(&self, id: &str) -> Result<(), DatabaseError> {
|
||||
if self
|
||||
.connection
|
||||
.execute("DELETE FROM connection_profiles WHERE id = ?1", params![id])?
|
||||
== 0
|
||||
{
|
||||
return Err(DatabaseError::ProfileNotFound);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn profile_from_row(row: &Row<'_>) -> Result<ConnectionProfile, DatabaseError> {
|
||||
let role = match row.get::<_, String>(2)?.as_str() {
|
||||
"companion" => AstrBotProfileRole::Companion,
|
||||
"operations" => AstrBotProfileRole::Operations,
|
||||
"general" => AstrBotProfileRole::General,
|
||||
_ => return Err(DatabaseError::InvalidStoredProfile),
|
||||
};
|
||||
let authentication_type = match row.get::<_, String>(5)?.as_str() {
|
||||
"device-token" => AuthenticationType::DeviceToken,
|
||||
"api-key" => AuthenticationType::ApiKey,
|
||||
_ => return Err(DatabaseError::InvalidStoredProfile),
|
||||
};
|
||||
let auto_connect_slot = match row.get::<_, Option<String>>(9)?.as_deref() {
|
||||
Some("companion") => Some(ActiveSlotKind::Companion),
|
||||
Some("operations") => Some(ActiveSlotKind::Operations),
|
||||
Some(_) => return Err(DatabaseError::InvalidStoredProfile),
|
||||
None => None,
|
||||
};
|
||||
|
||||
Ok(ConnectionProfile {
|
||||
id: row.get(0)?,
|
||||
display_name: row.get(1)?,
|
||||
role,
|
||||
base_url: row.get(3)?,
|
||||
event_stream_url: row.get(4)?,
|
||||
authentication_type,
|
||||
credential_reference: row.get(6)?,
|
||||
allow_insecure_http: row.get(7)?,
|
||||
pinned_certificate_fingerprint: row.get(8)?,
|
||||
auto_connect_slot,
|
||||
auto_connect: row.get(10)?,
|
||||
server_instance_id: row.get(11)?,
|
||||
server_version: row.get(12)?,
|
||||
protocol_version: row.get(13)?,
|
||||
local_tool_policy_id: row.get(14)?,
|
||||
last_connected_at: row.get(15)?,
|
||||
created_at: row.get(16)?,
|
||||
updated_at: row.get(17)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn role_to_str(role: AstrBotProfileRole) -> &'static str {
|
||||
match role {
|
||||
AstrBotProfileRole::Companion => "companion",
|
||||
AstrBotProfileRole::Operations => "operations",
|
||||
AstrBotProfileRole::General => "general",
|
||||
}
|
||||
}
|
||||
|
||||
fn authentication_to_str(authentication_type: AuthenticationType) -> &'static str {
|
||||
match authentication_type {
|
||||
AuthenticationType::DeviceToken => "device-token",
|
||||
AuthenticationType::ApiKey => "api-key",
|
||||
}
|
||||
}
|
||||
|
||||
fn slot_to_str(slot: ActiveSlotKind) -> &'static str {
|
||||
match slot {
|
||||
ActiveSlotKind::Companion => "companion",
|
||||
ActiveSlotKind::Operations => "operations",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
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-18T00:00:00Z".into(),
|
||||
updated_at: "2026-07-18T00:00:00Z".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stores_lists_updates_and_deletes_five_profiles() {
|
||||
let database = ApplicationDatabase::in_memory().expect("database");
|
||||
for index in 0..5 {
|
||||
database
|
||||
.create_profile(&profile(index))
|
||||
.expect("create profile");
|
||||
}
|
||||
assert_eq!(database.list_profiles().expect("list profiles").len(), 5);
|
||||
|
||||
let mut updated = database
|
||||
.profile(&profile(2).id)
|
||||
.expect("read profile")
|
||||
.expect("existing profile");
|
||||
updated.display_name = "Updated Profile".into();
|
||||
updated.updated_at = "2026-07-18T01:00:00Z".into();
|
||||
database.update_profile(&updated).expect("update profile");
|
||||
assert_eq!(
|
||||
database
|
||||
.profile(&updated.id)
|
||||
.expect("read updated profile")
|
||||
.expect("existing profile")
|
||||
.display_name,
|
||||
"Updated Profile"
|
||||
);
|
||||
|
||||
database
|
||||
.delete_profile(&updated.id)
|
||||
.expect("delete profile");
|
||||
assert_eq!(database.list_profiles().expect("list profiles").len(), 4);
|
||||
assert!(matches!(
|
||||
database.delete_profile(&updated.id),
|
||||
Err(DatabaseError::ProfileNotFound)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_metadata_persists_after_reopening_database() {
|
||||
let directory = tempfile::tempdir().expect("temporary directory");
|
||||
let path = directory.path().join("profiles.sqlite3");
|
||||
let expected = profile(7);
|
||||
|
||||
{
|
||||
let store = ProfileMessageStore::open(&path).expect("open database");
|
||||
store.create_profile(&expected).expect("create profile");
|
||||
}
|
||||
|
||||
let reopened = ProfileMessageStore::open(&path).expect("reopen database");
|
||||
let actual = reopened
|
||||
.profile(&expected.id)
|
||||
.expect("read profile")
|
||||
.expect("persisted profile");
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
}
|
||||
use desktop_protocol::{ActiveSlotKind, AstrBotProfileRole, AuthenticationType, ConnectionProfile};
|
||||
use rusqlite::{Row, params};
|
||||
|
||||
use super::{ApplicationDatabase, DatabaseError, ProfileMessageStore};
|
||||
|
||||
const PROFILE_COLUMNS: &str = "
|
||||
id,
|
||||
display_name,
|
||||
role,
|
||||
base_url,
|
||||
event_stream_url,
|
||||
authentication_type,
|
||||
transport_kind,
|
||||
credential_reference,
|
||||
allow_insecure_http,
|
||||
pinned_certificate_fingerprint,
|
||||
auto_connect_slot,
|
||||
auto_connect,
|
||||
server_instance_id,
|
||||
server_version,
|
||||
protocol_version,
|
||||
local_tool_policy_id,
|
||||
last_connected_at,
|
||||
remote_username,
|
||||
sticky_session_id,
|
||||
created_at,
|
||||
updated_at
|
||||
";
|
||||
|
||||
impl ApplicationDatabase {
|
||||
pub fn list_profiles(&self) -> Result<Vec<ConnectionProfile>, DatabaseError> {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||
.list_profiles()
|
||||
}
|
||||
|
||||
pub fn profile(&self, id: &str) -> Result<Option<ConnectionProfile>, DatabaseError> {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||
.profile(id)
|
||||
}
|
||||
|
||||
pub fn create_profile(&self, profile: &ConnectionProfile) -> Result<(), DatabaseError> {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||
.create_profile(profile)
|
||||
}
|
||||
|
||||
pub fn update_profile(&self, profile: &ConnectionProfile) -> Result<(), DatabaseError> {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||
.update_profile(profile)
|
||||
}
|
||||
|
||||
pub fn delete_profile(&self, id: &str) -> Result<(), DatabaseError> {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||
.delete_profile(id)
|
||||
}
|
||||
}
|
||||
|
||||
impl ProfileMessageStore {
|
||||
fn list_profiles(&self) -> Result<Vec<ConnectionProfile>, DatabaseError> {
|
||||
let mut statement = self.connection.prepare(&format!(
|
||||
"SELECT {PROFILE_COLUMNS}
|
||||
FROM connection_profiles
|
||||
ORDER BY display_name COLLATE NOCASE, id"
|
||||
))?;
|
||||
let mut rows = statement.query([])?;
|
||||
let mut profiles = Vec::new();
|
||||
while let Some(row) = rows.next()? {
|
||||
profiles.push(profile_from_row(row)?);
|
||||
}
|
||||
Ok(profiles)
|
||||
}
|
||||
|
||||
fn profile(&self, id: &str) -> Result<Option<ConnectionProfile>, DatabaseError> {
|
||||
let mut statement = self.connection.prepare(&format!(
|
||||
"SELECT {PROFILE_COLUMNS}
|
||||
FROM connection_profiles
|
||||
WHERE id = ?1"
|
||||
))?;
|
||||
let mut rows = statement.query(params![id])?;
|
||||
match rows.next()? {
|
||||
Some(row) => Ok(Some(profile_from_row(row)?)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn create_profile(&self, profile: &ConnectionProfile) -> Result<(), DatabaseError> {
|
||||
self.connection.execute(
|
||||
"
|
||||
INSERT INTO connection_profiles (
|
||||
id,
|
||||
display_name,
|
||||
role,
|
||||
base_url,
|
||||
event_stream_url,
|
||||
authentication_type,
|
||||
transport_kind,
|
||||
credential_reference,
|
||||
allow_insecure_http,
|
||||
pinned_certificate_fingerprint,
|
||||
auto_connect_slot,
|
||||
auto_connect,
|
||||
server_instance_id,
|
||||
server_version,
|
||||
protocol_version,
|
||||
local_tool_policy_id,
|
||||
last_connected_at,
|
||||
remote_username,
|
||||
sticky_session_id,
|
||||
created_at,
|
||||
updated_at
|
||||
) VALUES (
|
||||
?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9,
|
||||
?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18,
|
||||
?19, ?20, ?21
|
||||
)
|
||||
",
|
||||
params![
|
||||
profile.id,
|
||||
profile.display_name,
|
||||
role_to_str(profile.role),
|
||||
profile.base_url,
|
||||
profile.event_stream_url,
|
||||
authentication_to_str(profile.authentication_type),
|
||||
transport_to_str(profile.transport_kind),
|
||||
profile.credential_reference,
|
||||
profile.allow_insecure_http,
|
||||
profile.pinned_certificate_fingerprint,
|
||||
profile.auto_connect_slot.map(slot_to_str),
|
||||
profile.auto_connect,
|
||||
profile.server_instance_id,
|
||||
profile.server_version,
|
||||
profile.protocol_version,
|
||||
profile.local_tool_policy_id,
|
||||
profile.last_connected_at,
|
||||
profile.remote_username,
|
||||
profile.sticky_session_id,
|
||||
profile.created_at,
|
||||
profile.updated_at,
|
||||
],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn update_profile(&self, profile: &ConnectionProfile) -> Result<(), DatabaseError> {
|
||||
let changed = self.connection.execute(
|
||||
"
|
||||
UPDATE connection_profiles
|
||||
SET display_name = ?2,
|
||||
role = ?3,
|
||||
base_url = ?4,
|
||||
event_stream_url = ?5,
|
||||
authentication_type = ?6,
|
||||
transport_kind = ?7,
|
||||
credential_reference = ?8,
|
||||
allow_insecure_http = ?9,
|
||||
pinned_certificate_fingerprint = ?10,
|
||||
auto_connect_slot = ?11,
|
||||
auto_connect = ?12,
|
||||
server_instance_id = ?13,
|
||||
server_version = ?14,
|
||||
protocol_version = ?15,
|
||||
local_tool_policy_id = ?16,
|
||||
last_connected_at = ?17,
|
||||
remote_username = ?18,
|
||||
sticky_session_id = ?19,
|
||||
created_at = ?20,
|
||||
updated_at = ?21
|
||||
WHERE id = ?1
|
||||
",
|
||||
params![
|
||||
profile.id,
|
||||
profile.display_name,
|
||||
role_to_str(profile.role),
|
||||
profile.base_url,
|
||||
profile.event_stream_url,
|
||||
authentication_to_str(profile.authentication_type),
|
||||
transport_to_str(profile.transport_kind),
|
||||
profile.credential_reference,
|
||||
profile.allow_insecure_http,
|
||||
profile.pinned_certificate_fingerprint,
|
||||
profile.auto_connect_slot.map(slot_to_str),
|
||||
profile.auto_connect,
|
||||
profile.server_instance_id,
|
||||
profile.server_version,
|
||||
profile.protocol_version,
|
||||
profile.local_tool_policy_id,
|
||||
profile.last_connected_at,
|
||||
profile.remote_username,
|
||||
profile.sticky_session_id,
|
||||
profile.created_at,
|
||||
profile.updated_at,
|
||||
],
|
||||
)?;
|
||||
if changed == 0 {
|
||||
return Err(DatabaseError::ProfileNotFound);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn delete_profile(&self, id: &str) -> Result<(), DatabaseError> {
|
||||
if self
|
||||
.connection
|
||||
.execute("DELETE FROM connection_profiles WHERE id = ?1", params![id])?
|
||||
== 0
|
||||
{
|
||||
return Err(DatabaseError::ProfileNotFound);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn profile_from_row(row: &Row<'_>) -> Result<ConnectionProfile, DatabaseError> {
|
||||
let role = match row.get::<_, String>(2)?.as_str() {
|
||||
"companion" => AstrBotProfileRole::Companion,
|
||||
"operations" => AstrBotProfileRole::Operations,
|
||||
"general" => AstrBotProfileRole::General,
|
||||
_ => return Err(DatabaseError::InvalidStoredProfile),
|
||||
};
|
||||
let authentication_type = match row.get::<_, String>(5)?.as_str() {
|
||||
"device-token" => AuthenticationType::DeviceToken,
|
||||
"api-key" => AuthenticationType::ApiKey,
|
||||
_ => return Err(DatabaseError::InvalidStoredProfile),
|
||||
};
|
||||
let transport_kind = match row.get::<_, String>(6)?.as_str() {
|
||||
"desktop-v1" => desktop_protocol::TransportKind::DesktopV1,
|
||||
"astrbot-openapi" => desktop_protocol::TransportKind::AstrBotOpenApi,
|
||||
_ => return Err(DatabaseError::InvalidStoredProfile),
|
||||
};
|
||||
let auto_connect_slot = match row.get::<_, Option<String>>(10)? {
|
||||
Some(value) => Some(match value.as_str() {
|
||||
"companion" => ActiveSlotKind::Companion,
|
||||
"operations" => ActiveSlotKind::Operations,
|
||||
_ => return Err(DatabaseError::InvalidStoredProfile),
|
||||
}),
|
||||
None => None,
|
||||
};
|
||||
Ok(ConnectionProfile {
|
||||
id: row.get(0)?,
|
||||
display_name: row.get(1)?,
|
||||
role,
|
||||
base_url: row.get(3)?,
|
||||
event_stream_url: row.get(4)?,
|
||||
authentication_type,
|
||||
transport_kind,
|
||||
credential_reference: row.get(7)?,
|
||||
allow_insecure_http: row.get::<_, i64>(8)? != 0,
|
||||
pinned_certificate_fingerprint: row.get(9)?,
|
||||
auto_connect_slot,
|
||||
auto_connect: row.get::<_, i64>(11)? != 0,
|
||||
server_instance_id: row.get(12)?,
|
||||
server_version: row.get(13)?,
|
||||
protocol_version: row.get(14)?,
|
||||
local_tool_policy_id: row.get(15)?,
|
||||
last_connected_at: row.get(16)?,
|
||||
remote_username: row.get(17)?,
|
||||
sticky_session_id: row.get(18)?,
|
||||
created_at: row.get(19)?,
|
||||
updated_at: row.get(20)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn role_to_str(role: AstrBotProfileRole) -> &'static str {
|
||||
match role {
|
||||
AstrBotProfileRole::Companion => "companion",
|
||||
AstrBotProfileRole::Operations => "operations",
|
||||
AstrBotProfileRole::General => "general",
|
||||
}
|
||||
}
|
||||
|
||||
fn authentication_to_str(authentication_type: AuthenticationType) -> &'static str {
|
||||
match authentication_type {
|
||||
AuthenticationType::DeviceToken => "device-token",
|
||||
AuthenticationType::ApiKey => "api-key",
|
||||
}
|
||||
}
|
||||
|
||||
fn transport_to_str(transport_kind: desktop_protocol::TransportKind) -> &'static str {
|
||||
transport_kind.as_str()
|
||||
}
|
||||
|
||||
fn slot_to_str(slot: ActiveSlotKind) -> &'static str {
|
||||
match slot {
|
||||
ActiveSlotKind::Companion => "companion",
|
||||
ActiveSlotKind::Operations => "operations",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
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,
|
||||
transport_kind: desktop_protocol::TransportKind::DesktopV1,
|
||||
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,
|
||||
remote_username: None,
|
||||
sticky_session_id: None,
|
||||
created_at: "2026-07-18T00:00:00Z".into(),
|
||||
updated_at: "2026-07-18T00:00:00Z".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stores_lists_updates_and_deletes_five_profiles() {
|
||||
let database = ApplicationDatabase::in_memory().expect("database");
|
||||
for index in 0..5 {
|
||||
database
|
||||
.create_profile(&profile(index))
|
||||
.expect("create profile");
|
||||
}
|
||||
assert_eq!(database.list_profiles().expect("list profiles").len(), 5);
|
||||
|
||||
let mut updated = database
|
||||
.profile(&profile(2).id)
|
||||
.expect("read profile")
|
||||
.expect("existing profile");
|
||||
updated.display_name = "Updated Profile".into();
|
||||
updated.updated_at = "2026-07-18T01:00:00Z".into();
|
||||
database.update_profile(&updated).expect("update profile");
|
||||
assert_eq!(
|
||||
database
|
||||
.profile(&updated.id)
|
||||
.expect("read updated profile")
|
||||
.expect("existing profile")
|
||||
.display_name,
|
||||
"Updated Profile"
|
||||
);
|
||||
|
||||
database
|
||||
.delete_profile(&updated.id)
|
||||
.expect("delete profile");
|
||||
assert_eq!(database.list_profiles().expect("list profiles").len(), 4);
|
||||
assert!(matches!(
|
||||
database.delete_profile(&updated.id),
|
||||
Err(DatabaseError::ProfileNotFound)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_metadata_persists_after_reopening_database() {
|
||||
let directory = tempfile::tempdir().expect("temporary directory");
|
||||
let path = directory.path().join("profiles.sqlite3");
|
||||
let expected = profile(7);
|
||||
|
||||
{
|
||||
let store = ProfileMessageStore::open(&path).expect("open database");
|
||||
store.create_profile(&expected).expect("create profile");
|
||||
}
|
||||
|
||||
let reopened = ProfileMessageStore::open(&path).expect("reopen database");
|
||||
let actual = reopened
|
||||
.profile(&expected.id)
|
||||
.expect("read profile")
|
||||
.expect("persisted profile");
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,291 +1,294 @@
|
|||
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)
|
||||
));
|
||||
}
|
||||
}
|
||||
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,
|
||||
transport_kind: desktop_protocol::TransportKind::DesktopV1,
|
||||
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,
|
||||
remote_username: None,
|
||||
sticky_session_id: 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)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
pub mod credentials;
|
||||
pub mod database;
|
||||
pub mod diagnostics;
|
||||
pub mod file_transfer;
|
||||
pub mod logging;
|
||||
pub mod networking;
|
||||
pub mod pet;
|
||||
pub mod policy;
|
||||
pub mod profiles;
|
||||
pub mod runtime_guards;
|
||||
|
|
@ -11,12 +13,13 @@ pub mod slots;
|
|||
pub mod windows;
|
||||
|
||||
use database::ApplicationDatabase;
|
||||
use networking::DualSlotRuntime;
|
||||
use policy::ConnectionPolicyStatus;
|
||||
use runtime_guards::RuntimeGuards;
|
||||
use serde::Serialize;
|
||||
|
||||
use tauri::{
|
||||
Manager, WindowEvent,
|
||||
AppHandle, Manager, WebviewUrl, WebviewWindowBuilder, WindowEvent,
|
||||
menu::{Menu, MenuItem},
|
||||
tray::TrayIconBuilder,
|
||||
};
|
||||
|
|
@ -31,6 +34,50 @@ struct BootstrapStatus {
|
|||
protocol_version: &'static str,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn open_status_bubble_window(app: AppHandle) -> Result<(), String> {
|
||||
if let Some(window) = app.get_webview_window("status-bubble") {
|
||||
window.show().map_err(|error| error.to_string())?;
|
||||
return Ok(());
|
||||
}
|
||||
WebviewWindowBuilder::new(
|
||||
&app,
|
||||
"status-bubble",
|
||||
WebviewUrl::App("index.html?view=bubble".into()),
|
||||
)
|
||||
.title("AstrBot Status")
|
||||
.inner_size(108.0, 108.0)
|
||||
.resizable(false)
|
||||
.decorations(false)
|
||||
.transparent(true)
|
||||
.always_on_top(false)
|
||||
.skip_taskbar(true)
|
||||
.build()
|
||||
.map(|_| ())
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn open_quick_chat_window(app: AppHandle) -> Result<(), String> {
|
||||
if let Some(window) = app.get_webview_window("quick-chat") {
|
||||
window.show().map_err(|error| error.to_string())?;
|
||||
window.set_focus().map_err(|error| error.to_string())?;
|
||||
return Ok(());
|
||||
}
|
||||
WebviewWindowBuilder::new(
|
||||
&app,
|
||||
"quick-chat",
|
||||
WebviewUrl::App("index.html?view=quick".into()),
|
||||
)
|
||||
.title("AstrBot Quick Chat")
|
||||
.inner_size(420.0, 620.0)
|
||||
.min_inner_size(320.0, 420.0)
|
||||
.resizable(true)
|
||||
.build()
|
||||
.map(|_| ())
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn bootstrap_status(
|
||||
database: tauri::State<'_, ApplicationDatabase>,
|
||||
|
|
@ -82,6 +129,7 @@ pub fn run() {
|
|||
app_data_dir.join("astrbot-desktop.sqlite3"),
|
||||
)?);
|
||||
app.manage(RuntimeGuards::new());
|
||||
app.manage(DualSlotRuntime::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>)?;
|
||||
|
|
@ -111,6 +159,8 @@ pub fn run() {
|
|||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
bootstrap_status,
|
||||
open_quick_chat_window,
|
||||
open_status_bubble_window,
|
||||
connection_policy_status,
|
||||
profiles::list_connection_profiles,
|
||||
profiles::create_connection_profile,
|
||||
|
|
@ -119,6 +169,14 @@ pub fn run() {
|
|||
slots::list_connection_slots,
|
||||
slots::assign_connection_slot,
|
||||
slots::clear_connection_slot,
|
||||
credentials::enroll_profile_credential,
|
||||
credentials::clear_profile_credential,
|
||||
networking::commands::connection_runtime_status,
|
||||
networking::commands::drain_connection_runtime_events,
|
||||
networking::commands::load_chat_messages,
|
||||
networking::commands::probe_connection_slot,
|
||||
networking::commands::disconnect_connection_slot,
|
||||
networking::commands::send_connection_slot_message,
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("failed to run AstrBot Desktop");
|
||||
|
|
|
|||
|
|
@ -0,0 +1,444 @@
|
|||
use std::{collections::VecDeque, sync::Arc, time::Duration};
|
||||
|
||||
use desktop_protocol::{
|
||||
AstrBotApiEnvelope, AstrBotChatRequest, AstrBotConfigListData, AstrBotSessionListData,
|
||||
AstrBotStreamMapper, BoundGatewayEvent, ConnectionState, GatewayEvent, PROTOCOL_VERSION,
|
||||
derive_astrbot_server_instance_id,
|
||||
};
|
||||
use futures_util::StreamExt;
|
||||
use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, HeaderValue};
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
use serde_json::{Value, json};
|
||||
use thiserror::Error;
|
||||
use tokio::sync::{Mutex, mpsc, watch};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::{GatewayError, SlotKind};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AstrBotClientConfig {
|
||||
pub profile_id: String,
|
||||
pub slot: SlotKind,
|
||||
pub base_url: String,
|
||||
pub api_key: SecretString,
|
||||
/// Remote WebChat username used as session owner identity.
|
||||
pub remote_username: String,
|
||||
/// Optional sticky session id. When absent, the first chat response supplies one.
|
||||
pub session_id: Option<String>,
|
||||
/// Expected server identity substitute. Empty means accept first observed identity.
|
||||
pub expected_server_instance_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum AstrBotClientError {
|
||||
#[error("astrbot request failed")]
|
||||
Request(#[from] reqwest::Error),
|
||||
#[error("astrbot returned HTTP {0}")]
|
||||
HttpStatus(reqwest::StatusCode),
|
||||
#[error("astrbot api status error: {0}")]
|
||||
ApiStatus(String),
|
||||
#[error("invalid astrbot payload")]
|
||||
Json(#[from] serde_json::Error),
|
||||
#[error("astrbot stream mapping failed: {0}")]
|
||||
Map(String),
|
||||
#[error("server identity changed")]
|
||||
ServerIdentityChanged,
|
||||
#[error("astrbot event channel closed")]
|
||||
ChannelClosed,
|
||||
#[error("invalid configuration: {0}")]
|
||||
InvalidConfig(&'static str),
|
||||
}
|
||||
|
||||
impl From<AstrBotClientError> for GatewayError {
|
||||
fn from(value: AstrBotClientError) -> Self {
|
||||
match value {
|
||||
AstrBotClientError::Request(error) => GatewayError::Request(error),
|
||||
AstrBotClientError::HttpStatus(status) => GatewayError::HttpStatus(status),
|
||||
AstrBotClientError::Json(error) => GatewayError::Json(error),
|
||||
AstrBotClientError::ServerIdentityChanged => GatewayError::ServerIdentityChanged,
|
||||
AstrBotClientError::ChannelClosed => GatewayError::ChannelClosed,
|
||||
AstrBotClientError::ApiStatus(message) => GatewayError::Adapter(message),
|
||||
AstrBotClientError::Map(message) => GatewayError::Adapter(message),
|
||||
AstrBotClientError::InvalidConfig(message) => GatewayError::Adapter(message.to_owned()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_DEDUPLICATED_EVENTS: usize = 4_096;
|
||||
|
||||
#[derive(Default)]
|
||||
struct EventDeduplicator {
|
||||
ids: std::collections::HashSet<String>,
|
||||
order: VecDeque<String>,
|
||||
}
|
||||
|
||||
impl EventDeduplicator {
|
||||
fn insert(&mut self, event_id: String) -> bool {
|
||||
if !self.ids.insert(event_id.clone()) {
|
||||
return false;
|
||||
}
|
||||
self.order.push_back(event_id);
|
||||
if self.order.len() > MAX_DEDUPLICATED_EVENTS
|
||||
&& let Some(expired) = self.order.pop_front()
|
||||
{
|
||||
self.ids.remove(&expired);
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AstrBotClient {
|
||||
config: AstrBotClientConfig,
|
||||
http: reqwest::Client,
|
||||
seen_event_ids: Arc<Mutex<EventDeduplicator>>,
|
||||
session_id: Arc<Mutex<Option<String>>>,
|
||||
server_instance_id: Arc<Mutex<String>>,
|
||||
state_tx: watch::Sender<ConnectionState>,
|
||||
}
|
||||
|
||||
impl AstrBotClient {
|
||||
pub fn new(config: AstrBotClientConfig) -> Result<Self, AstrBotClientError> {
|
||||
if config.base_url.trim().is_empty() {
|
||||
return Err(AstrBotClientError::InvalidConfig("base_url is required"));
|
||||
}
|
||||
if config.remote_username.trim().is_empty() {
|
||||
return Err(AstrBotClientError::InvalidConfig(
|
||||
"remote_username is required",
|
||||
));
|
||||
}
|
||||
if config.api_key.expose_secret().trim().is_empty() {
|
||||
return Err(AstrBotClientError::InvalidConfig("api_key is required"));
|
||||
}
|
||||
|
||||
let base = config.base_url.trim_end_matches('/').to_owned();
|
||||
let derived = derive_astrbot_server_instance_id(&base);
|
||||
let initial_identity = config
|
||||
.expected_server_instance_id
|
||||
.clone()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.unwrap_or(derived);
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
let auth_value = format!("Bearer {}", config.api_key.expose_secret());
|
||||
headers.insert(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_str(&auth_value).map_err(|_| {
|
||||
AstrBotClientError::InvalidConfig("api_key has invalid header chars")
|
||||
})?,
|
||||
);
|
||||
|
||||
let http = reqwest::Client::builder()
|
||||
.default_headers(headers)
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.connect_timeout(Duration::from_secs(5))
|
||||
.timeout(Duration::from_secs(120))
|
||||
.build()?;
|
||||
|
||||
let (state_tx, _) = watch::channel(ConnectionState::Disconnected);
|
||||
let initial_session = config.session_id.clone();
|
||||
Ok(Self {
|
||||
config: AstrBotClientConfig {
|
||||
base_url: base,
|
||||
..config
|
||||
},
|
||||
http,
|
||||
seen_event_ids: Arc::new(Mutex::new(EventDeduplicator::default())),
|
||||
session_id: Arc::new(Mutex::new(initial_session)),
|
||||
server_instance_id: Arc::new(Mutex::new(initial_identity)),
|
||||
state_tx,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn state_receiver(&self) -> watch::Receiver<ConnectionState> {
|
||||
self.state_tx.subscribe()
|
||||
}
|
||||
|
||||
pub fn server_instance_id_blocking(&self) -> String {
|
||||
self.server_instance_id
|
||||
.try_lock()
|
||||
.map(|guard| guard.clone())
|
||||
.unwrap_or_else(|_| derive_astrbot_server_instance_id(&self.config.base_url))
|
||||
}
|
||||
|
||||
fn set_state(&self, state: ConnectionState) {
|
||||
self.state_tx.send_replace(state);
|
||||
}
|
||||
|
||||
fn url(&self, path: &str) -> String {
|
||||
format!("{}{}", self.config.base_url, path)
|
||||
}
|
||||
|
||||
pub async fn probe(&self) -> Result<Value, AstrBotClientError> {
|
||||
self.set_state(ConnectionState::Connecting);
|
||||
let response = self
|
||||
.http
|
||||
.get(self.url(&format!(
|
||||
"/api/v1/chat/sessions?username={}&page=1&page_size=1",
|
||||
urlencoding_username(&self.config.remote_username)
|
||||
)))
|
||||
.send()
|
||||
.await?;
|
||||
if response.status().as_u16() == 401 || response.status().as_u16() == 403 {
|
||||
self.set_state(ConnectionState::AuthExpired);
|
||||
return Err(AstrBotClientError::HttpStatus(response.status()));
|
||||
}
|
||||
if !response.status().is_success() {
|
||||
self.set_state(ConnectionState::ServerUnavailable);
|
||||
return Err(AstrBotClientError::HttpStatus(response.status()));
|
||||
}
|
||||
let envelope: AstrBotApiEnvelope<AstrBotSessionListData> = response.json().await?;
|
||||
if !envelope.is_ok() {
|
||||
self.set_state(ConnectionState::FatalError);
|
||||
return Err(AstrBotClientError::ApiStatus(
|
||||
envelope
|
||||
.message
|
||||
.unwrap_or_else(|| "chat sessions probe failed".into()),
|
||||
));
|
||||
}
|
||||
self.set_state(ConnectionState::Connected);
|
||||
Ok(json!({
|
||||
"status": "ok",
|
||||
"protocolVersion": PROTOCOL_VERSION,
|
||||
"transport": "astrbot-openapi",
|
||||
"serverInstanceId": self.server_instance_id.lock().await.clone(),
|
||||
"remoteUsername": self.config.remote_username,
|
||||
"sessionCount": envelope.data.map(|data| data.total.unwrap_or(0)).unwrap_or(0),
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn list_sessions(&self) -> Result<AstrBotSessionListData, AstrBotClientError> {
|
||||
let response = self
|
||||
.http
|
||||
.get(self.url(&format!(
|
||||
"/api/v1/chat/sessions?username={}&page=1&page_size=50",
|
||||
urlencoding_username(&self.config.remote_username)
|
||||
)))
|
||||
.send()
|
||||
.await?;
|
||||
if !response.status().is_success() {
|
||||
return Err(AstrBotClientError::HttpStatus(response.status()));
|
||||
}
|
||||
let envelope: AstrBotApiEnvelope<AstrBotSessionListData> = response.json().await?;
|
||||
if !envelope.is_ok() {
|
||||
return Err(AstrBotClientError::ApiStatus(
|
||||
envelope
|
||||
.message
|
||||
.unwrap_or_else(|| "list sessions failed".into()),
|
||||
));
|
||||
}
|
||||
Ok(envelope.data.unwrap_or(AstrBotSessionListData {
|
||||
sessions: Vec::new(),
|
||||
page: Some(1),
|
||||
page_size: Some(50),
|
||||
total: Some(0),
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn list_configs(&self) -> Result<AstrBotConfigListData, AstrBotClientError> {
|
||||
let response = self.http.get(self.url("/api/v1/configs")).send().await?;
|
||||
if !response.status().is_success() {
|
||||
return Err(AstrBotClientError::HttpStatus(response.status()));
|
||||
}
|
||||
let envelope: AstrBotApiEnvelope<AstrBotConfigListData> = response.json().await?;
|
||||
if !envelope.is_ok() {
|
||||
return Err(AstrBotClientError::ApiStatus(
|
||||
envelope
|
||||
.message
|
||||
.unwrap_or_else(|| "list configs failed".into()),
|
||||
));
|
||||
}
|
||||
Ok(envelope.data.unwrap_or(AstrBotConfigListData {
|
||||
configs: Vec::new(),
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn send_chat_stream(
|
||||
&self,
|
||||
message: &str,
|
||||
sender: &mpsc::Sender<super::gateway_client::BoundGatewayEvent>,
|
||||
cancellation: &CancellationToken,
|
||||
) -> Result<Option<String>, AstrBotClientError> {
|
||||
self.set_state(ConnectionState::Syncing);
|
||||
let session_id = self.session_id.lock().await.clone();
|
||||
let request = AstrBotChatRequest {
|
||||
message: Value::String(message.to_owned()),
|
||||
session_id: session_id.clone(),
|
||||
conversation_id: None,
|
||||
username: Some(self.config.remote_username.clone()),
|
||||
config_id: None,
|
||||
platform_id: None,
|
||||
enable_streaming: Some(true),
|
||||
};
|
||||
|
||||
let response = self
|
||||
.http
|
||||
.post(self.url("/api/v1/chat"))
|
||||
.header(ACCEPT, HeaderValue::from_static("text/event-stream"))
|
||||
.json(&request)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
if response.status().as_u16() == 401 || response.status().as_u16() == 403 {
|
||||
self.set_state(ConnectionState::AuthExpired);
|
||||
return Err(AstrBotClientError::HttpStatus(response.status()));
|
||||
}
|
||||
if !response.status().is_success() {
|
||||
self.set_state(ConnectionState::ServerUnavailable);
|
||||
return Err(AstrBotClientError::HttpStatus(response.status()));
|
||||
}
|
||||
|
||||
let server_instance_id = self.server_instance_id.lock().await.clone();
|
||||
if let Some(expected) = &self.config.expected_server_instance_id
|
||||
&& !expected.is_empty()
|
||||
&& expected != &server_instance_id
|
||||
{
|
||||
self.set_state(ConnectionState::CertificateChanged);
|
||||
return Err(AstrBotClientError::ServerIdentityChanged);
|
||||
}
|
||||
|
||||
let mut mapper = AstrBotStreamMapper::new(server_instance_id.clone());
|
||||
if let Some(existing) = session_id {
|
||||
let seed = serde_json::json!({
|
||||
"type": "session_id",
|
||||
"data": null,
|
||||
"session_id": existing,
|
||||
});
|
||||
let _ = mapper.push_line(&format!("data: {seed}"));
|
||||
}
|
||||
|
||||
let mut stream = response.bytes_stream();
|
||||
let mut buffer = String::new();
|
||||
self.set_state(ConnectionState::Connected);
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = cancellation.cancelled() => {
|
||||
self.set_state(ConnectionState::Disconnected);
|
||||
return Ok(mapper.session_id().map(str::to_owned));
|
||||
}
|
||||
next = stream.next() => {
|
||||
let Some(next) = next else { break; };
|
||||
let chunk = next?;
|
||||
buffer.push_str(&String::from_utf8_lossy(&chunk));
|
||||
while let Some(index) = buffer.find('\n') {
|
||||
let mut line = buffer[..index].to_owned();
|
||||
buffer.drain(..=index);
|
||||
if line.ends_with('\r') {
|
||||
line.pop();
|
||||
}
|
||||
let events = mapper
|
||||
.push_line(&line)
|
||||
.map_err(|error| AstrBotClientError::Map(error.to_string()))?;
|
||||
self.dispatch_events(events, sender).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !buffer.trim().is_empty() {
|
||||
let events = mapper
|
||||
.push_line(buffer.trim_end_matches('\r'))
|
||||
.map_err(|error| AstrBotClientError::Map(error.to_string()))?;
|
||||
self.dispatch_events(events, sender).await?;
|
||||
}
|
||||
let events = mapper.finish_stream();
|
||||
self.dispatch_events(events, sender).await?;
|
||||
|
||||
if let Some(session) = mapper.session_id() {
|
||||
*self.session_id.lock().await = Some(session.to_owned());
|
||||
}
|
||||
self.set_state(ConnectionState::Connected);
|
||||
Ok(self.session_id.lock().await.clone())
|
||||
}
|
||||
|
||||
async fn dispatch_events(
|
||||
&self,
|
||||
events: Vec<GatewayEvent>,
|
||||
sender: &mpsc::Sender<super::gateway_client::BoundGatewayEvent>,
|
||||
) -> Result<(), AstrBotClientError> {
|
||||
for event in events {
|
||||
if let Some(session_id) = event.metadata.session_id.clone() {
|
||||
*self.session_id.lock().await = Some(session_id);
|
||||
}
|
||||
let event_id = event.metadata.event_id.clone();
|
||||
let mut seen = self.seen_event_ids.lock().await;
|
||||
if !seen.insert(event_id.clone()) {
|
||||
continue;
|
||||
}
|
||||
drop(seen);
|
||||
|
||||
let payload = serde_json::to_value(&event.body)
|
||||
.map_err(|error| AstrBotClientError::Map(error.to_string()))?;
|
||||
let bound = BoundGatewayEvent {
|
||||
profile_id: self.config.profile_id.clone(),
|
||||
slot: protocol_slot(self.config.slot),
|
||||
event,
|
||||
};
|
||||
sender
|
||||
.send(super::gateway_client::BoundGatewayEvent {
|
||||
profile_id: bound.profile_id,
|
||||
slot: self.config.slot,
|
||||
event_id,
|
||||
event_type: bound.event.event_type().to_owned(),
|
||||
server_instance_id: bound.event.metadata.server_instance_id.clone(),
|
||||
session_id: bound.event.metadata.session_id.clone(),
|
||||
message_id: bound.event.metadata.message_id.clone(),
|
||||
payload,
|
||||
})
|
||||
.await
|
||||
.map_err(|_| AstrBotClientError::ChannelClosed)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn protocol_slot(slot: SlotKind) -> desktop_protocol::ActiveSlotKind {
|
||||
match slot {
|
||||
SlotKind::Companion => desktop_protocol::ActiveSlotKind::Companion,
|
||||
SlotKind::Operations => desktop_protocol::ActiveSlotKind::Operations,
|
||||
}
|
||||
}
|
||||
|
||||
fn urlencoding_username(username: &str) -> String {
|
||||
username
|
||||
.chars()
|
||||
.map(|ch| match ch {
|
||||
'A'..='Z' | 'a'..='z' | '0'..='9' | '-' | '_' | '.' | '~' => ch.to_string(),
|
||||
_ => format!("%{:02X}", ch as u8),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rejects_empty_api_key_and_username() {
|
||||
let result = AstrBotClient::new(AstrBotClientConfig {
|
||||
profile_id: "p".into(),
|
||||
slot: SlotKind::Companion,
|
||||
base_url: "http://127.0.0.1:1".into(),
|
||||
api_key: SecretString::from(String::new()),
|
||||
remote_username: "user".into(),
|
||||
session_id: None,
|
||||
expected_server_instance_id: None,
|
||||
});
|
||||
assert!(matches!(result, Err(AstrBotClientError::InvalidConfig(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derives_identity_from_base_url() {
|
||||
let client = AstrBotClient::new(AstrBotClientConfig {
|
||||
profile_id: "p".into(),
|
||||
slot: SlotKind::Companion,
|
||||
base_url: "http://192.168.31.210:26285/".into(),
|
||||
api_key: SecretString::from("abk_test".to_owned()),
|
||||
remote_username: "desktop-companion".into(),
|
||||
session_id: Some("s1".into()),
|
||||
expected_server_instance_id: None,
|
||||
})
|
||||
.expect("client");
|
||||
assert!(client.server_instance_id_blocking().starts_with("astrbot-"));
|
||||
}
|
||||
}
|
||||
320
src-tauri/src/networking/commands.rs
普通文件
320
src-tauri/src/networking/commands.rs
普通文件
|
|
@ -0,0 +1,320 @@
|
|||
// IPC wrappers for dual-slot runtime. Secrets never leave Rust.
|
||||
use desktop_protocol::TransportKind;
|
||||
use secrecy::SecretString;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
use tauri::State;
|
||||
|
||||
use super::{
|
||||
ConnectionRuntimeStatus, DualSlotRuntime, RuntimeCommandError, SlotActivationRequest, SlotKind,
|
||||
SlotRuntimeSnapshot,
|
||||
};
|
||||
use crate::credentials::{CredentialCommandError, load_profile_secret};
|
||||
use crate::database::ApplicationDatabase;
|
||||
use crate::secure_store::WindowsCredentialStore;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ProbeConnectionSlotRequest {
|
||||
pub slot: SlotKind,
|
||||
pub profile_id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct DisconnectConnectionSlotRequest {
|
||||
pub slot: SlotKind,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct SendConnectionSlotMessageRequest {
|
||||
pub slot: SlotKind,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct DrainConnectionRuntimeEventsRequest {
|
||||
pub limit: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct LoadChatMessagesRequest {
|
||||
pub profile_id: String,
|
||||
pub server_instance_id: String,
|
||||
pub session_id: String,
|
||||
pub limit: Option<usize>,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn connection_runtime_status(
|
||||
runtime: State<'_, DualSlotRuntime>,
|
||||
) -> Result<ConnectionRuntimeStatus, RuntimeCommandError> {
|
||||
Ok(runtime.status().await)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn drain_connection_runtime_events(
|
||||
database: State<'_, ApplicationDatabase>,
|
||||
runtime: State<'_, DualSlotRuntime>,
|
||||
request: DrainConnectionRuntimeEventsRequest,
|
||||
) -> Result<Vec<super::BoundGatewayEvent>, RuntimeCommandError> {
|
||||
let events = runtime.drain_events(request.limit.unwrap_or(64)).await;
|
||||
for event in &events {
|
||||
persist_runtime_event(&database, event);
|
||||
}
|
||||
Ok(events)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn load_chat_messages(
|
||||
database: State<'_, ApplicationDatabase>,
|
||||
request: LoadChatMessagesRequest,
|
||||
) -> Result<Vec<crate::database::StoredChatMessage>, RuntimeCommandError> {
|
||||
database
|
||||
.list_chat_messages(
|
||||
&request.profile_id,
|
||||
&request.server_instance_id,
|
||||
&request.session_id,
|
||||
request.limit.unwrap_or(100),
|
||||
)
|
||||
.map_err(|_| RuntimeCommandError {
|
||||
code: "databaseUnavailable",
|
||||
message: "Chat history is unavailable.",
|
||||
})
|
||||
}
|
||||
|
||||
fn persist_runtime_event(database: &ApplicationDatabase, event: &super::BoundGatewayEvent) {
|
||||
let Some(session_id) = event.session_id.as_deref() else {
|
||||
return;
|
||||
};
|
||||
let Some((role, content, streaming, message_id)) = (match event.event_type.as_str() {
|
||||
"message.delta" => Some((
|
||||
"assistant",
|
||||
event
|
||||
.payload
|
||||
.get("delta")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default(),
|
||||
true,
|
||||
event
|
||||
.message_id
|
||||
.as_deref()
|
||||
.unwrap_or(event.event_id.as_str()),
|
||||
)),
|
||||
"message.completed" => Some((
|
||||
"assistant",
|
||||
event
|
||||
.payload
|
||||
.get("content")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default(),
|
||||
false,
|
||||
event
|
||||
.message_id
|
||||
.as_deref()
|
||||
.unwrap_or(event.event_id.as_str()),
|
||||
)),
|
||||
"message.proactive" => Some((
|
||||
"assistant",
|
||||
event
|
||||
.payload
|
||||
.get("content")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default(),
|
||||
false,
|
||||
event.event_id.as_str(),
|
||||
)),
|
||||
"error" => Some((
|
||||
"system",
|
||||
event
|
||||
.payload
|
||||
.get("message")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("Connection error"),
|
||||
false,
|
||||
event.event_id.as_str(),
|
||||
)),
|
||||
_ => None,
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
let slot = match event.slot {
|
||||
SlotKind::Companion => "companion",
|
||||
SlotKind::Operations => "operations",
|
||||
};
|
||||
let _ = database.upsert_chat_message(
|
||||
"local-default",
|
||||
&event.profile_id,
|
||||
slot,
|
||||
&event.server_instance_id,
|
||||
None,
|
||||
session_id,
|
||||
message_id,
|
||||
role,
|
||||
content,
|
||||
streaming,
|
||||
event.event_type == "error",
|
||||
);
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn probe_connection_slot(
|
||||
database: State<'_, ApplicationDatabase>,
|
||||
runtime: State<'_, DualSlotRuntime>,
|
||||
request: ProbeConnectionSlotRequest,
|
||||
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
|
||||
let profile = database
|
||||
.profile(&request.profile_id)
|
||||
.map_err(|_| RuntimeCommandError {
|
||||
code: "databaseUnavailable",
|
||||
message: "The local profile database is unavailable.",
|
||||
})?
|
||||
.ok_or(RuntimeCommandError {
|
||||
code: "notFound",
|
||||
message: "The connection profile no longer exists.",
|
||||
})?;
|
||||
|
||||
if profile.transport_kind != TransportKind::AstrBotOpenApi
|
||||
&& profile.transport_kind != TransportKind::DesktopV1
|
||||
{
|
||||
return Err(RuntimeCommandError {
|
||||
code: "validationFailed",
|
||||
message: "Unsupported transport kind.",
|
||||
});
|
||||
}
|
||||
|
||||
let secret = load_profile_secret(&database, &WindowsCredentialStore, &profile.id).map_err(
|
||||
|error: CredentialCommandError| RuntimeCommandError {
|
||||
code: error.code,
|
||||
message: error.message,
|
||||
},
|
||||
)?;
|
||||
|
||||
let activation = match profile.transport_kind {
|
||||
TransportKind::AstrBotOpenApi => {
|
||||
let secret = secret.ok_or(RuntimeCommandError {
|
||||
code: "credentialMissing",
|
||||
message: "Enroll an API key before probing an AstrBot profile.",
|
||||
})?;
|
||||
let api_key =
|
||||
String::from_utf8(secret.secret().to_vec()).map_err(|_| RuntimeCommandError {
|
||||
code: "credentialInvalid",
|
||||
message: "Stored API key is not valid UTF-8.",
|
||||
})?;
|
||||
let remote_username = profile.remote_username.clone().ok_or(RuntimeCommandError {
|
||||
code: "validationFailed",
|
||||
message: "AstrBot profiles require remote_username.",
|
||||
})?;
|
||||
SlotActivationRequest {
|
||||
profile_id: profile.id.clone(),
|
||||
slot: request.slot,
|
||||
base_url: profile.base_url.clone(),
|
||||
transport: TransportKind::AstrBotOpenApi,
|
||||
api_key: Some(SecretString::from(api_key)),
|
||||
bearer_token: None,
|
||||
remote_username: Some(remote_username),
|
||||
session_id: profile.sticky_session_id.clone(),
|
||||
expected_server_instance_id: profile.server_instance_id.clone(),
|
||||
}
|
||||
}
|
||||
TransportKind::DesktopV1 => {
|
||||
let bearer = secret.and_then(|value| {
|
||||
String::from_utf8(value.secret().to_vec())
|
||||
.ok()
|
||||
.map(SecretString::from)
|
||||
});
|
||||
let expected = profile
|
||||
.server_instance_id
|
||||
.clone()
|
||||
.ok_or(RuntimeCommandError {
|
||||
code: "validationFailed",
|
||||
message: "Desktop gateway profiles require server_instance_id before probe.",
|
||||
})?;
|
||||
SlotActivationRequest {
|
||||
profile_id: profile.id.clone(),
|
||||
slot: request.slot,
|
||||
base_url: profile.base_url.clone(),
|
||||
transport: TransportKind::DesktopV1,
|
||||
api_key: None,
|
||||
bearer_token: bearer,
|
||||
remote_username: None,
|
||||
session_id: None,
|
||||
expected_server_instance_id: Some(expected),
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let snapshot = runtime.activate_slot(activation).await?;
|
||||
|
||||
// Persist observed identity / sticky session without exposing secrets.
|
||||
if let Ok(Some(mut stored)) = database.profile(&request.profile_id) {
|
||||
let mut dirty = false;
|
||||
if stored.server_instance_id.is_none()
|
||||
&& let Some(server_instance_id) = snapshot.server_instance_id.clone()
|
||||
{
|
||||
stored.server_instance_id = Some(server_instance_id);
|
||||
dirty = true;
|
||||
}
|
||||
if let Some(session_id) = snapshot.active_session_id.clone()
|
||||
&& stored.sticky_session_id.as_deref() != Some(session_id.as_str())
|
||||
{
|
||||
stored.sticky_session_id = Some(session_id);
|
||||
dirty = true;
|
||||
}
|
||||
if dirty {
|
||||
let _ = database.update_profile(&stored);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(snapshot)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn disconnect_connection_slot(
|
||||
runtime: State<'_, DualSlotRuntime>,
|
||||
request: DisconnectConnectionSlotRequest,
|
||||
) -> Result<(), RuntimeCommandError> {
|
||||
runtime.deactivate_slot(request.slot).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn send_connection_slot_message(
|
||||
database: State<'_, ApplicationDatabase>,
|
||||
runtime: State<'_, DualSlotRuntime>,
|
||||
request: SendConnectionSlotMessageRequest,
|
||||
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
|
||||
let status = runtime.status().await;
|
||||
let snapshot = match request.slot {
|
||||
SlotKind::Companion => status.companion,
|
||||
SlotKind::Operations => status.operations,
|
||||
};
|
||||
if let (Some(profile_id), Some(server_instance_id), Some(session_id)) = (
|
||||
snapshot.profile_id.as_deref(),
|
||||
snapshot.server_instance_id.as_deref(),
|
||||
snapshot.active_session_id.as_deref(),
|
||||
) {
|
||||
let slot = match request.slot {
|
||||
SlotKind::Companion => "companion",
|
||||
SlotKind::Operations => "operations",
|
||||
};
|
||||
let _ = database.upsert_chat_message(
|
||||
"local-default",
|
||||
profile_id,
|
||||
slot,
|
||||
server_instance_id,
|
||||
None,
|
||||
session_id,
|
||||
&format!("local-{}", uuid::Uuid::new_v4()),
|
||||
"user",
|
||||
&request.message,
|
||||
false,
|
||||
false,
|
||||
);
|
||||
}
|
||||
runtime
|
||||
.send_slot_message(request.slot, request.message)
|
||||
.await
|
||||
}
|
||||
|
|
@ -34,6 +34,8 @@ pub struct BoundGatewayEvent {
|
|||
pub event_id: String,
|
||||
pub event_type: String,
|
||||
pub server_instance_id: String,
|
||||
pub session_id: Option<String>,
|
||||
pub message_id: Option<String>,
|
||||
pub payload: Value,
|
||||
}
|
||||
|
||||
|
|
@ -53,6 +55,8 @@ pub enum GatewayError {
|
|||
ServerIdentityChanged,
|
||||
#[error("gateway event channel closed")]
|
||||
ChannelClosed,
|
||||
#[error("gateway adapter error: {0}")]
|
||||
Adapter(String),
|
||||
}
|
||||
|
||||
const MAX_DEDUPLICATED_EVENTS: usize = 4_096;
|
||||
|
|
@ -194,6 +198,8 @@ impl GatewayClient {
|
|||
event_id: event_id.clone(),
|
||||
event_type,
|
||||
server_instance_id,
|
||||
session_id: bound.event.metadata.session_id.clone(),
|
||||
message_id: bound.event.metadata.message_id.clone(),
|
||||
payload,
|
||||
})
|
||||
.await
|
||||
|
|
|
|||
|
|
@ -1,5 +1,19 @@
|
|||
mod astrbot_client;
|
||||
pub mod commands;
|
||||
mod gateway_client;
|
||||
mod manager;
|
||||
mod runtime;
|
||||
|
||||
pub use astrbot_client::{AstrBotClient, AstrBotClientConfig, AstrBotClientError};
|
||||
pub use commands::{
|
||||
DisconnectConnectionSlotRequest, DrainConnectionRuntimeEventsRequest,
|
||||
ProbeConnectionSlotRequest, SendConnectionSlotMessageRequest, connection_runtime_status,
|
||||
disconnect_connection_slot, drain_connection_runtime_events, probe_connection_slot,
|
||||
send_connection_slot_message,
|
||||
};
|
||||
pub use gateway_client::{BoundGatewayEvent, GatewayClient, GatewayClientConfig, GatewayError};
|
||||
pub use manager::{DualConnectionManager, SlotKind};
|
||||
pub use runtime::{
|
||||
ConnectionRuntimeStatus, DualSlotRuntime, RuntimeCommandError, SlotActivationRequest,
|
||||
SlotRuntimeSnapshot,
|
||||
};
|
||||
|
|
|
|||
410
src-tauri/src/networking/runtime.rs
普通文件
410
src-tauri/src/networking/runtime.rs
普通文件
|
|
@ -0,0 +1,410 @@
|
|||
use desktop_protocol::{ConnectionState, TransportKind};
|
||||
use secrecy::SecretString;
|
||||
use serde::Serialize;
|
||||
use tokio::sync::{Mutex, mpsc};
|
||||
|
||||
use super::{
|
||||
AstrBotClient, AstrBotClientConfig, BoundGatewayEvent, GatewayClient, GatewayClientConfig,
|
||||
GatewayError, SlotKind,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SlotRuntimeSnapshot {
|
||||
pub slot: SlotKind,
|
||||
pub profile_id: Option<String>,
|
||||
pub transport: Option<TransportKind>,
|
||||
pub state: ConnectionState,
|
||||
pub server_instance_id: Option<String>,
|
||||
pub active_session_id: Option<String>,
|
||||
pub last_error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ConnectionRuntimeStatus {
|
||||
pub companion: SlotRuntimeSnapshot,
|
||||
pub operations: SlotRuntimeSnapshot,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SlotActivationRequest {
|
||||
pub profile_id: String,
|
||||
pub slot: SlotKind,
|
||||
pub base_url: String,
|
||||
pub transport: TransportKind,
|
||||
pub api_key: Option<SecretString>,
|
||||
pub bearer_token: Option<SecretString>,
|
||||
pub remote_username: Option<String>,
|
||||
pub session_id: Option<String>,
|
||||
pub expected_server_instance_id: Option<String>,
|
||||
}
|
||||
|
||||
enum ActiveClient {
|
||||
Desktop(GatewayClient),
|
||||
AstrBot(AstrBotClient),
|
||||
}
|
||||
|
||||
struct SlotRuntime {
|
||||
snapshot: SlotRuntimeSnapshot,
|
||||
client: Option<ActiveClient>,
|
||||
}
|
||||
|
||||
impl SlotRuntime {
|
||||
fn empty(slot: SlotKind) -> Self {
|
||||
Self {
|
||||
snapshot: SlotRuntimeSnapshot {
|
||||
slot,
|
||||
profile_id: None,
|
||||
transport: None,
|
||||
state: ConnectionState::Disconnected,
|
||||
server_instance_id: None,
|
||||
active_session_id: None,
|
||||
last_error: None,
|
||||
},
|
||||
client: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// In-process dual-slot connection runtime.
|
||||
///
|
||||
/// Network activation is explicit and Rust-owned. React never receives secrets.
|
||||
pub struct DualSlotRuntime {
|
||||
inner: Mutex<DualSlotRuntimeInner>,
|
||||
event_tx: mpsc::Sender<BoundGatewayEvent>,
|
||||
event_rx: Mutex<mpsc::Receiver<BoundGatewayEvent>>,
|
||||
}
|
||||
|
||||
struct DualSlotRuntimeInner {
|
||||
companion: SlotRuntime,
|
||||
operations: SlotRuntime,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RuntimeCommandError {
|
||||
pub code: &'static str,
|
||||
pub message: &'static str,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for RuntimeCommandError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(self.message)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for RuntimeCommandError {}
|
||||
|
||||
impl RuntimeCommandError {
|
||||
pub fn validation(message: &'static str) -> Self {
|
||||
Self {
|
||||
code: "validationFailed",
|
||||
message,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unavailable(message: &'static str) -> Self {
|
||||
Self {
|
||||
code: "runtimeUnavailable",
|
||||
message,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DualSlotRuntime {
|
||||
pub fn new() -> Self {
|
||||
let (event_tx, event_rx) = mpsc::channel(256);
|
||||
Self {
|
||||
inner: Mutex::new(DualSlotRuntimeInner {
|
||||
companion: SlotRuntime::empty(SlotKind::Companion),
|
||||
operations: SlotRuntime::empty(SlotKind::Operations),
|
||||
}),
|
||||
event_tx,
|
||||
event_rx: Mutex::new(event_rx),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn status(&self) -> ConnectionRuntimeStatus {
|
||||
let guard = self.inner.lock().await;
|
||||
ConnectionRuntimeStatus {
|
||||
companion: guard.companion.snapshot.clone(),
|
||||
operations: guard.operations.snapshot.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn try_recv_event(&self) -> Option<BoundGatewayEvent> {
|
||||
let mut rx = self.event_rx.lock().await;
|
||||
rx.try_recv().ok()
|
||||
}
|
||||
|
||||
pub async fn drain_events(&self, limit: usize) -> Vec<BoundGatewayEvent> {
|
||||
let limit = limit.clamp(1, 256);
|
||||
let mut rx = self.event_rx.lock().await;
|
||||
let mut events = Vec::with_capacity(limit);
|
||||
while events.len() < limit {
|
||||
match rx.try_recv() {
|
||||
Ok(event) => events.push(event),
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
events
|
||||
}
|
||||
|
||||
pub async fn deactivate_slot(&self, slot: SlotKind) -> Result<(), RuntimeCommandError> {
|
||||
let mut guard = self.inner.lock().await;
|
||||
let runtime = slot_mut(&mut guard, slot);
|
||||
*runtime = SlotRuntime::empty(slot);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn activate_slot(
|
||||
&self,
|
||||
request: SlotActivationRequest,
|
||||
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
|
||||
if request.profile_id.trim().is_empty() {
|
||||
return Err(RuntimeCommandError::validation(
|
||||
"profile_id is required for activation.",
|
||||
));
|
||||
}
|
||||
if request.base_url.trim().is_empty() {
|
||||
return Err(RuntimeCommandError::validation(
|
||||
"base_url is required for activation.",
|
||||
));
|
||||
}
|
||||
|
||||
let mut guard = self.inner.lock().await;
|
||||
let runtime = slot_mut(&mut guard, request.slot);
|
||||
*runtime = SlotRuntime {
|
||||
snapshot: SlotRuntimeSnapshot {
|
||||
slot: request.slot,
|
||||
profile_id: Some(request.profile_id.clone()),
|
||||
transport: Some(request.transport),
|
||||
state: ConnectionState::Connecting,
|
||||
server_instance_id: None,
|
||||
active_session_id: request.session_id.clone(),
|
||||
last_error: None,
|
||||
},
|
||||
client: None,
|
||||
};
|
||||
|
||||
match request.transport {
|
||||
TransportKind::DesktopV1 => {
|
||||
let expected = request
|
||||
.expected_server_instance_id
|
||||
.clone()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.ok_or_else(|| {
|
||||
RuntimeCommandError::validation(
|
||||
"Desktop gateway activation requires expected_server_instance_id.",
|
||||
)
|
||||
})?;
|
||||
let client = GatewayClient::new(GatewayClientConfig {
|
||||
profile_id: request.profile_id.clone(),
|
||||
slot: request.slot,
|
||||
base_url: request.base_url.clone(),
|
||||
expected_server_instance_id: expected.clone(),
|
||||
bearer_token: request.bearer_token.clone(),
|
||||
})
|
||||
.map_err(|_| {
|
||||
RuntimeCommandError::unavailable("Desktop gateway client failed to start.")
|
||||
})?;
|
||||
match client.health().await {
|
||||
Ok(_) => {
|
||||
runtime.snapshot.state = ConnectionState::Connected;
|
||||
runtime.snapshot.server_instance_id = Some(expected);
|
||||
runtime.client = Some(ActiveClient::Desktop(client));
|
||||
}
|
||||
Err(GatewayError::HttpStatus(status)) if status.as_u16() == 401 => {
|
||||
runtime.snapshot.state = ConnectionState::AuthExpired;
|
||||
runtime.snapshot.last_error =
|
||||
Some("Desktop gateway authentication failed.".into());
|
||||
return Err(RuntimeCommandError::unavailable(
|
||||
"Desktop gateway authentication failed.",
|
||||
));
|
||||
}
|
||||
Err(_) => {
|
||||
runtime.snapshot.state = ConnectionState::ServerUnavailable;
|
||||
runtime.snapshot.last_error =
|
||||
Some("Desktop gateway health check failed.".into());
|
||||
return Err(RuntimeCommandError::unavailable(
|
||||
"Desktop gateway health check failed.",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
TransportKind::AstrBotOpenApi => {
|
||||
let api_key = request.api_key.clone().ok_or_else(|| {
|
||||
RuntimeCommandError::validation("AstrBot activation requires an API key.")
|
||||
})?;
|
||||
let remote_username = request
|
||||
.remote_username
|
||||
.clone()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.ok_or_else(|| {
|
||||
RuntimeCommandError::validation(
|
||||
"AstrBot activation requires remote_username.",
|
||||
)
|
||||
})?;
|
||||
let client = AstrBotClient::new(AstrBotClientConfig {
|
||||
profile_id: request.profile_id.clone(),
|
||||
slot: request.slot,
|
||||
base_url: request.base_url.clone(),
|
||||
api_key,
|
||||
remote_username,
|
||||
session_id: request.session_id.clone(),
|
||||
expected_server_instance_id: request.expected_server_instance_id.clone(),
|
||||
})
|
||||
.map_err(|_| RuntimeCommandError::unavailable("AstrBot client failed to start."))?;
|
||||
match client.probe().await {
|
||||
Ok(_) => {
|
||||
runtime.snapshot.state = ConnectionState::Connected;
|
||||
runtime.snapshot.server_instance_id =
|
||||
Some(client.server_instance_id_blocking());
|
||||
runtime.client = Some(ActiveClient::AstrBot(client));
|
||||
}
|
||||
Err(error) => {
|
||||
runtime.snapshot.state = match error {
|
||||
super::AstrBotClientError::HttpStatus(status)
|
||||
if status.as_u16() == 401 || status.as_u16() == 403 =>
|
||||
{
|
||||
ConnectionState::AuthExpired
|
||||
}
|
||||
_ => ConnectionState::ServerUnavailable,
|
||||
};
|
||||
runtime.snapshot.last_error = Some("AstrBot probe failed.".into());
|
||||
return Err(RuntimeCommandError::unavailable("AstrBot probe failed."));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(runtime.snapshot.clone())
|
||||
}
|
||||
|
||||
pub async fn send_slot_message(
|
||||
&self,
|
||||
slot: SlotKind,
|
||||
message: String,
|
||||
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
|
||||
if message.trim().is_empty() {
|
||||
return Err(RuntimeCommandError::validation(
|
||||
"message must not be empty.",
|
||||
));
|
||||
}
|
||||
|
||||
// Take the client out so we can await without holding the mutex across network IO.
|
||||
let (client, profile_id, transport, server_instance_id, session_id) = {
|
||||
let mut guard = self.inner.lock().await;
|
||||
let runtime = slot_mut(&mut guard, slot);
|
||||
let client = runtime.client.take().ok_or_else(|| {
|
||||
RuntimeCommandError::unavailable("The selected slot is not connected.")
|
||||
})?;
|
||||
runtime.snapshot.state = ConnectionState::Syncing;
|
||||
(
|
||||
client,
|
||||
runtime.snapshot.profile_id.clone(),
|
||||
runtime.snapshot.transport,
|
||||
runtime.snapshot.server_instance_id.clone(),
|
||||
runtime.snapshot.active_session_id.clone(),
|
||||
)
|
||||
};
|
||||
|
||||
let send_result = match client {
|
||||
ActiveClient::Desktop(client) => {
|
||||
// Desktop mock path remains stream-oriented; chat POST is a later wire-up.
|
||||
let restored = ActiveClient::Desktop(client);
|
||||
Err((
|
||||
restored,
|
||||
RuntimeCommandError::unavailable(
|
||||
"Desktop mock chat send is not activated in this runtime path yet.",
|
||||
),
|
||||
))
|
||||
}
|
||||
ActiveClient::AstrBot(client) => {
|
||||
let cancel = tokio_util::sync::CancellationToken::new();
|
||||
match client
|
||||
.send_chat_stream(&message, &self.event_tx, &cancel)
|
||||
.await
|
||||
{
|
||||
Ok(session) => Ok((ActiveClient::AstrBot(client), session)),
|
||||
Err(_) => Err((
|
||||
ActiveClient::AstrBot(client),
|
||||
RuntimeCommandError::unavailable("AstrBot chat send failed."),
|
||||
)),
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let mut guard = self.inner.lock().await;
|
||||
let runtime = slot_mut(&mut guard, slot);
|
||||
match send_result {
|
||||
Ok((client, session)) => {
|
||||
runtime.client = Some(client);
|
||||
runtime.snapshot.profile_id = profile_id;
|
||||
runtime.snapshot.transport = transport;
|
||||
runtime.snapshot.server_instance_id = server_instance_id;
|
||||
runtime.snapshot.active_session_id = session.or(session_id);
|
||||
runtime.snapshot.state = ConnectionState::Connected;
|
||||
runtime.snapshot.last_error = None;
|
||||
Ok(runtime.snapshot.clone())
|
||||
}
|
||||
Err((client, error)) => {
|
||||
runtime.client = Some(client);
|
||||
runtime.snapshot.profile_id = profile_id;
|
||||
runtime.snapshot.transport = transport;
|
||||
runtime.snapshot.server_instance_id = server_instance_id;
|
||||
runtime.snapshot.active_session_id = session_id;
|
||||
runtime.snapshot.state = ConnectionState::ServerUnavailable;
|
||||
runtime.snapshot.last_error = Some(error.message.to_owned());
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for DualSlotRuntime {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
fn slot_mut(inner: &mut DualSlotRuntimeInner, slot: SlotKind) -> &mut SlotRuntime {
|
||||
match slot {
|
||||
SlotKind::Companion => &mut inner.companion,
|
||||
SlotKind::Operations => &mut inner.operations,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_astrbot_activation_without_username_or_key() {
|
||||
let runtime = DualSlotRuntime::new();
|
||||
let error = runtime
|
||||
.activate_slot(SlotActivationRequest {
|
||||
profile_id: "11111111-1111-1111-1111-111111111111".into(),
|
||||
slot: SlotKind::Companion,
|
||||
base_url: "http://127.0.0.1:9".into(),
|
||||
transport: TransportKind::AstrBotOpenApi,
|
||||
api_key: None,
|
||||
bearer_token: None,
|
||||
remote_username: None,
|
||||
session_id: None,
|
||||
expected_server_instance_id: None,
|
||||
})
|
||||
.await
|
||||
.expect_err("should fail");
|
||||
assert_eq!(error.code, "validationFailed");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn status_starts_disconnected() {
|
||||
let runtime = DualSlotRuntime::new();
|
||||
let status = runtime.status().await;
|
||||
assert_eq!(status.companion.state, ConnectionState::Disconnected);
|
||||
assert_eq!(status.operations.state, ConnectionState::Disconnected);
|
||||
}
|
||||
}
|
||||
70
src-tauri/src/pet.rs
普通文件
70
src-tauri/src/pet.rs
普通文件
|
|
@ -0,0 +1,70 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MonitorGeometry {
|
||||
pub left: i32,
|
||||
pub top: i32,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub work_left: i32,
|
||||
pub work_top: i32,
|
||||
pub work_width: u32,
|
||||
pub work_height: u32,
|
||||
pub is_primary: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum PetPositionMode {
|
||||
Free,
|
||||
Edge,
|
||||
Monitor,
|
||||
FollowMainWindow,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PetPlacement {
|
||||
pub monitor_index: usize,
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
}
|
||||
|
||||
pub fn place_at_safe_edge(
|
||||
monitor: MonitorGeometry,
|
||||
pet_width: u32,
|
||||
pet_height: u32,
|
||||
margin: i32,
|
||||
) -> PetPlacement {
|
||||
let width = pet_width.min(monitor.work_width) as i32;
|
||||
let height = pet_height.min(monitor.work_height) as i32;
|
||||
PetPlacement {
|
||||
monitor_index: 0,
|
||||
x: monitor.work_left + (monitor.work_width as i32 - width - margin).max(0),
|
||||
y: monitor.work_top + (monitor.work_height as i32 - height - margin).max(0),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn keeps_pet_inside_work_area() {
|
||||
let monitor = MonitorGeometry {
|
||||
left: 0,
|
||||
top: 0,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
work_left: 0,
|
||||
work_top: 0,
|
||||
work_width: 1920,
|
||||
work_height: 1040,
|
||||
is_primary: true,
|
||||
};
|
||||
let placement = place_at_safe_edge(monitor, 120, 120, 16);
|
||||
assert_eq!(placement.x, 1784);
|
||||
assert_eq!(placement.y, 904);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,279 +1,282 @@
|
|||
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()]
|
||||
);
|
||||
}
|
||||
}
|
||||
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,
|
||||
transport_kind: desktop_protocol::TransportKind::DesktopV1,
|
||||
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,
|
||||
remote_username: None,
|
||||
sticky_session_id: 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,423 +1,454 @@
|
|||
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;
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ConnectionProfileInput {
|
||||
pub display_name: String,
|
||||
pub role: AstrBotProfileRole,
|
||||
pub base_url: String,
|
||||
#[serde(default)]
|
||||
pub event_stream_url: Option<String>,
|
||||
pub authentication_type: AuthenticationType,
|
||||
#[serde(default)]
|
||||
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)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct UpdateConnectionProfileRequest {
|
||||
pub id: String,
|
||||
#[serde(flatten)]
|
||||
pub profile: ConnectionProfileInput,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProfileCommandError {
|
||||
code: &'static str,
|
||||
message: &'static str,
|
||||
}
|
||||
|
||||
impl ProfileCommandError {
|
||||
fn validation(message: &'static str) -> Self {
|
||||
Self {
|
||||
code: "validationFailed",
|
||||
message,
|
||||
}
|
||||
}
|
||||
|
||||
fn auto_connect(error: AutoConnectValidationError) -> Self {
|
||||
Self {
|
||||
code: "autoConnectInvalid",
|
||||
message: error.message(),
|
||||
}
|
||||
}
|
||||
|
||||
fn database(error: DatabaseError) -> Self {
|
||||
match error {
|
||||
DatabaseError::ProfileNotFound => Self {
|
||||
code: "notFound",
|
||||
message: "The connection profile no longer exists.",
|
||||
},
|
||||
_ => Self {
|
||||
code: "databaseUnavailable",
|
||||
message: "The local profile database is unavailable.",
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn list_connection_profiles(
|
||||
database: tauri::State<'_, ApplicationDatabase>,
|
||||
) -> Result<Vec<ConnectionProfile>, ProfileCommandError> {
|
||||
list_profiles(&database)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn create_connection_profile(
|
||||
database: tauri::State<'_, ApplicationDatabase>,
|
||||
request: ConnectionProfileInput,
|
||||
) -> Result<ConnectionProfile, ProfileCommandError> {
|
||||
create_profile(&database, request)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn update_connection_profile(
|
||||
database: tauri::State<'_, ApplicationDatabase>,
|
||||
request: UpdateConnectionProfileRequest,
|
||||
) -> Result<ConnectionProfile, ProfileCommandError> {
|
||||
update_profile(&database, request)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn delete_connection_profile(
|
||||
database: tauri::State<'_, ApplicationDatabase>,
|
||||
id: String,
|
||||
) -> Result<(), ProfileCommandError> {
|
||||
delete_profile(&database, &id)
|
||||
}
|
||||
|
||||
fn list_profiles(
|
||||
database: &ApplicationDatabase,
|
||||
) -> Result<Vec<ConnectionProfile>, ProfileCommandError> {
|
||||
database
|
||||
.list_profiles()
|
||||
.map_err(ProfileCommandError::database)
|
||||
}
|
||||
|
||||
fn create_profile(
|
||||
database: &ApplicationDatabase,
|
||||
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(),
|
||||
display_name: normalized.display_name,
|
||||
role: normalized.role,
|
||||
base_url: normalized.base_url,
|
||||
event_stream_url: normalized.event_stream_url,
|
||||
authentication_type: normalized.authentication_type,
|
||||
credential_reference: None,
|
||||
allow_insecure_http: normalized.allow_insecure_http,
|
||||
pinned_certificate_fingerprint: normalized.pinned_certificate_fingerprint,
|
||||
auto_connect_slot: normalized.auto_connect_slot,
|
||||
auto_connect: normalized.auto_connect,
|
||||
server_instance_id: None,
|
||||
server_version: None,
|
||||
protocol_version: None,
|
||||
local_tool_policy_id: None,
|
||||
last_connected_at: None,
|
||||
created_at: now.clone(),
|
||||
updated_at: now,
|
||||
};
|
||||
database
|
||||
.create_profile(&profile)
|
||||
.map_err(ProfileCommandError::database)?;
|
||||
Ok(profile)
|
||||
}
|
||||
|
||||
fn update_profile(
|
||||
database: &ApplicationDatabase,
|
||||
request: UpdateConnectionProfileRequest,
|
||||
) -> Result<ConnectionProfile, ProfileCommandError> {
|
||||
validate_id(&request.id)?;
|
||||
let normalized = normalize_input(request.profile)?;
|
||||
let mut profile = database
|
||||
.profile(&request.id)
|
||||
.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;
|
||||
profile.event_stream_url = normalized.event_stream_url;
|
||||
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
|
||||
.update_profile(&profile)
|
||||
.map_err(ProfileCommandError::database)?;
|
||||
Ok(profile)
|
||||
}
|
||||
|
||||
fn delete_profile(database: &ApplicationDatabase, id: &str) -> Result<(), ProfileCommandError> {
|
||||
validate_id(id)?;
|
||||
database
|
||||
.delete_profile(id)
|
||||
.map_err(ProfileCommandError::database)
|
||||
}
|
||||
|
||||
fn normalize_input(
|
||||
request: ConnectionProfileInput,
|
||||
) -> Result<ConnectionProfileInput, ProfileCommandError> {
|
||||
let display_name = request.display_name.trim().to_owned();
|
||||
if display_name.is_empty()
|
||||
|| display_name.chars().count() > MAX_DISPLAY_NAME_CHARS
|
||||
|| display_name.chars().any(char::is_control)
|
||||
{
|
||||
return Err(ProfileCommandError::validation(
|
||||
"Display name must contain 1 to 80 visible characters.",
|
||||
));
|
||||
}
|
||||
|
||||
let base_url = normalize_url(&request.base_url, request.allow_insecure_http)?;
|
||||
let event_stream_url = request
|
||||
.event_stream_url
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(|value| normalize_url(value, request.allow_insecure_http))
|
||||
.transpose()?;
|
||||
let pinned_certificate_fingerprint =
|
||||
normalize_fingerprint(request.pinned_certificate_fingerprint)?;
|
||||
|
||||
Ok(ConnectionProfileInput {
|
||||
display_name,
|
||||
role: request.role,
|
||||
base_url,
|
||||
event_stream_url,
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
||||
fn normalize_url(value: &str, allow_insecure_http: bool) -> Result<String, ProfileCommandError> {
|
||||
let value = value.trim();
|
||||
if value.is_empty() || value.chars().count() > MAX_URL_CHARS {
|
||||
return Err(ProfileCommandError::validation(
|
||||
"Connection URL is empty or too long.",
|
||||
));
|
||||
}
|
||||
|
||||
let mut url = Url::parse(value)
|
||||
.map_err(|_| ProfileCommandError::validation("Connection URL is invalid."))?;
|
||||
if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
|
||||
return Err(ProfileCommandError::validation(
|
||||
"Connection URL must use HTTP or HTTPS and include a host.",
|
||||
));
|
||||
}
|
||||
if !url.username().is_empty() || url.password().is_some() {
|
||||
return Err(ProfileCommandError::validation(
|
||||
"Credentials must not be embedded in a connection URL.",
|
||||
));
|
||||
}
|
||||
if url.query().is_some() || url.fragment().is_some() {
|
||||
return Err(ProfileCommandError::validation(
|
||||
"Connection URLs must not contain query parameters or fragments.",
|
||||
));
|
||||
}
|
||||
if url.scheme() == "http" && !allow_insecure_http {
|
||||
return Err(ProfileCommandError::validation(
|
||||
"HTTP requires explicit insecure-transport approval.",
|
||||
));
|
||||
}
|
||||
url.set_fragment(None);
|
||||
Ok(url.to_string())
|
||||
}
|
||||
|
||||
fn normalize_fingerprint(value: Option<String>) -> Result<Option<String>, ProfileCommandError> {
|
||||
let Some(value) = value else {
|
||||
return Ok(None);
|
||||
};
|
||||
let normalized = value
|
||||
.trim()
|
||||
.chars()
|
||||
.filter(|character| *character != ':')
|
||||
.flat_map(char::to_uppercase)
|
||||
.collect::<String>();
|
||||
if normalized.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
if normalized.len() != 64
|
||||
|| !normalized
|
||||
.chars()
|
||||
.all(|character| character.is_ascii_hexdigit())
|
||||
{
|
||||
return Err(ProfileCommandError::validation(
|
||||
"Pinned certificate fingerprint must be a SHA-256 hex value.",
|
||||
));
|
||||
}
|
||||
Ok(Some(normalized))
|
||||
}
|
||||
|
||||
fn validate_id(id: &str) -> Result<(), ProfileCommandError> {
|
||||
if Uuid::parse_str(id).is_err() {
|
||||
return Err(ProfileCommandError::validation(
|
||||
"Connection profile ID is invalid.",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn timestamp() -> Result<String, ProfileCommandError> {
|
||||
OffsetDateTime::now_utc()
|
||||
.format(&Rfc3339)
|
||||
.map_err(|_| ProfileCommandError {
|
||||
code: "clockUnavailable",
|
||||
message: "The system clock could not produce a profile timestamp.",
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn request(base_url: &str) -> ConnectionProfileInput {
|
||||
ConnectionProfileInput {
|
||||
display_name: " Test Profile ".into(),
|
||||
role: AstrBotProfileRole::General,
|
||||
base_url: base_url.into(),
|
||||
event_stream_url: None,
|
||||
authentication_type: AuthenticationType::DeviceToken,
|
||||
allow_insecure_http: false,
|
||||
pinned_certificate_fingerprint: None,
|
||||
auto_connect: false,
|
||||
auto_connect_slot: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creates_updates_lists_and_deletes_profile_metadata() {
|
||||
let database = ApplicationDatabase::in_memory().expect("database");
|
||||
let created =
|
||||
create_profile(&database, request("https://example.test")).expect("create profile");
|
||||
assert_eq!(created.display_name, "Test Profile");
|
||||
assert_eq!(created.base_url, "https://example.test/");
|
||||
assert!(created.credential_reference.is_none());
|
||||
assert!(!created.auto_connect);
|
||||
assert!(created.auto_connect_slot.is_none());
|
||||
|
||||
let updated = update_profile(
|
||||
&database,
|
||||
UpdateConnectionProfileRequest {
|
||||
id: created.id.clone(),
|
||||
profile: ConnectionProfileInput {
|
||||
display_name: "Updated".into(),
|
||||
role: AstrBotProfileRole::Companion,
|
||||
base_url: "https://updated.example.test".into(),
|
||||
event_stream_url: Some("https://updated.example.test/events".into()),
|
||||
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");
|
||||
assert!(list_profiles(&database).expect("list profiles").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_insecure_or_credential_bearing_urls() {
|
||||
let database = ApplicationDatabase::in_memory().expect("database");
|
||||
assert!(create_profile(&database, request("http://example.test")).is_err());
|
||||
assert!(create_profile(&database, request("https://user:password@example.test")).is_err());
|
||||
assert!(create_profile(&database, request("https://example.test?token=fake")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_secret_values_and_unknown_fields_at_the_ipc_boundary() {
|
||||
let result = serde_json::from_value::<ConnectionProfileInput>(serde_json::json!({
|
||||
"displayName": "Test Profile",
|
||||
"role": "general",
|
||||
"baseUrl": "https://example.test",
|
||||
"authenticationType": "device-token",
|
||||
"allowInsecureHttp": false,
|
||||
"token": "[REDACTED]",
|
||||
"password": "[REDACTED]",
|
||||
"apiKey": "[REDACTED]"
|
||||
}));
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
use desktop_protocol::{
|
||||
ActiveSlotKind, AstrBotProfileRole, AuthenticationType, ConnectionProfile, TransportKind,
|
||||
};
|
||||
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;
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ConnectionProfileInput {
|
||||
pub display_name: String,
|
||||
pub role: AstrBotProfileRole,
|
||||
pub base_url: String,
|
||||
#[serde(default)]
|
||||
pub event_stream_url: Option<String>,
|
||||
pub authentication_type: AuthenticationType,
|
||||
#[serde(default)]
|
||||
pub transport_kind: TransportKind,
|
||||
#[serde(default)]
|
||||
pub allow_insecure_http: bool,
|
||||
#[serde(default)]
|
||||
pub remote_username: Option<String>,
|
||||
#[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)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct UpdateConnectionProfileRequest {
|
||||
pub id: String,
|
||||
#[serde(flatten)]
|
||||
pub profile: ConnectionProfileInput,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProfileCommandError {
|
||||
code: &'static str,
|
||||
message: &'static str,
|
||||
}
|
||||
|
||||
impl ProfileCommandError {
|
||||
fn validation(message: &'static str) -> Self {
|
||||
Self {
|
||||
code: "validationFailed",
|
||||
message,
|
||||
}
|
||||
}
|
||||
|
||||
fn auto_connect(error: AutoConnectValidationError) -> Self {
|
||||
Self {
|
||||
code: "autoConnectInvalid",
|
||||
message: error.message(),
|
||||
}
|
||||
}
|
||||
|
||||
fn database(error: DatabaseError) -> Self {
|
||||
match error {
|
||||
DatabaseError::ProfileNotFound => Self {
|
||||
code: "notFound",
|
||||
message: "The connection profile no longer exists.",
|
||||
},
|
||||
_ => Self {
|
||||
code: "databaseUnavailable",
|
||||
message: "The local profile database is unavailable.",
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn list_connection_profiles(
|
||||
database: tauri::State<'_, ApplicationDatabase>,
|
||||
) -> Result<Vec<ConnectionProfile>, ProfileCommandError> {
|
||||
list_profiles(&database)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn create_connection_profile(
|
||||
database: tauri::State<'_, ApplicationDatabase>,
|
||||
request: ConnectionProfileInput,
|
||||
) -> Result<ConnectionProfile, ProfileCommandError> {
|
||||
create_profile(&database, request)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn update_connection_profile(
|
||||
database: tauri::State<'_, ApplicationDatabase>,
|
||||
request: UpdateConnectionProfileRequest,
|
||||
) -> Result<ConnectionProfile, ProfileCommandError> {
|
||||
update_profile(&database, request)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn delete_connection_profile(
|
||||
database: tauri::State<'_, ApplicationDatabase>,
|
||||
id: String,
|
||||
) -> Result<(), ProfileCommandError> {
|
||||
delete_profile(&database, &id)
|
||||
}
|
||||
|
||||
fn list_profiles(
|
||||
database: &ApplicationDatabase,
|
||||
) -> Result<Vec<ConnectionProfile>, ProfileCommandError> {
|
||||
database
|
||||
.list_profiles()
|
||||
.map_err(ProfileCommandError::database)
|
||||
}
|
||||
|
||||
fn create_profile(
|
||||
database: &ApplicationDatabase,
|
||||
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(),
|
||||
display_name: normalized.display_name,
|
||||
role: normalized.role,
|
||||
base_url: normalized.base_url,
|
||||
event_stream_url: normalized.event_stream_url,
|
||||
authentication_type: normalized.authentication_type,
|
||||
transport_kind: normalized.transport_kind,
|
||||
credential_reference: None,
|
||||
allow_insecure_http: normalized.allow_insecure_http,
|
||||
pinned_certificate_fingerprint: normalized.pinned_certificate_fingerprint,
|
||||
auto_connect_slot: normalized.auto_connect_slot,
|
||||
auto_connect: normalized.auto_connect,
|
||||
server_instance_id: None,
|
||||
server_version: None,
|
||||
protocol_version: None,
|
||||
local_tool_policy_id: None,
|
||||
last_connected_at: None,
|
||||
remote_username: normalized.remote_username,
|
||||
sticky_session_id: None,
|
||||
created_at: now.clone(),
|
||||
updated_at: now,
|
||||
};
|
||||
database
|
||||
.create_profile(&profile)
|
||||
.map_err(ProfileCommandError::database)?;
|
||||
Ok(profile)
|
||||
}
|
||||
|
||||
fn update_profile(
|
||||
database: &ApplicationDatabase,
|
||||
request: UpdateConnectionProfileRequest,
|
||||
) -> Result<ConnectionProfile, ProfileCommandError> {
|
||||
validate_id(&request.id)?;
|
||||
let normalized = normalize_input(request.profile)?;
|
||||
let mut profile = database
|
||||
.profile(&request.id)
|
||||
.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;
|
||||
profile.event_stream_url = normalized.event_stream_url;
|
||||
profile.authentication_type = normalized.authentication_type;
|
||||
profile.transport_kind = normalized.transport_kind;
|
||||
profile.allow_insecure_http = normalized.allow_insecure_http;
|
||||
profile.remote_username = normalized.remote_username;
|
||||
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
|
||||
.update_profile(&profile)
|
||||
.map_err(ProfileCommandError::database)?;
|
||||
Ok(profile)
|
||||
}
|
||||
|
||||
fn delete_profile(database: &ApplicationDatabase, id: &str) -> Result<(), ProfileCommandError> {
|
||||
validate_id(id)?;
|
||||
database
|
||||
.delete_profile(id)
|
||||
.map_err(ProfileCommandError::database)
|
||||
}
|
||||
|
||||
fn normalize_input(
|
||||
request: ConnectionProfileInput,
|
||||
) -> Result<ConnectionProfileInput, ProfileCommandError> {
|
||||
let display_name = request.display_name.trim().to_owned();
|
||||
if display_name.is_empty()
|
||||
|| display_name.chars().count() > MAX_DISPLAY_NAME_CHARS
|
||||
|| display_name.chars().any(char::is_control)
|
||||
{
|
||||
return Err(ProfileCommandError::validation(
|
||||
"Display name must contain 1 to 80 visible characters.",
|
||||
));
|
||||
}
|
||||
|
||||
let base_url = normalize_url(&request.base_url, request.allow_insecure_http)?;
|
||||
let event_stream_url = request
|
||||
.event_stream_url
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(|value| normalize_url(value, request.allow_insecure_http))
|
||||
.transpose()?;
|
||||
let pinned_certificate_fingerprint =
|
||||
normalize_fingerprint(request.pinned_certificate_fingerprint)?;
|
||||
|
||||
let remote_username = request
|
||||
.remote_username
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(str::to_owned);
|
||||
if let Some(username) = &remote_username
|
||||
&& (username.chars().count() > 80 || username.chars().any(char::is_control))
|
||||
{
|
||||
return Err(ProfileCommandError::validation(
|
||||
"Remote username must contain 1 to 80 visible characters.",
|
||||
));
|
||||
}
|
||||
|
||||
Ok(ConnectionProfileInput {
|
||||
display_name,
|
||||
role: request.role,
|
||||
base_url,
|
||||
event_stream_url,
|
||||
authentication_type: request.authentication_type,
|
||||
transport_kind: request.transport_kind,
|
||||
allow_insecure_http: request.allow_insecure_http,
|
||||
remote_username,
|
||||
pinned_certificate_fingerprint,
|
||||
auto_connect: request.auto_connect,
|
||||
auto_connect_slot: request.auto_connect_slot,
|
||||
})
|
||||
}
|
||||
|
||||
fn normalize_url(value: &str, allow_insecure_http: bool) -> Result<String, ProfileCommandError> {
|
||||
let value = value.trim();
|
||||
if value.is_empty() || value.chars().count() > MAX_URL_CHARS {
|
||||
return Err(ProfileCommandError::validation(
|
||||
"Connection URL is empty or too long.",
|
||||
));
|
||||
}
|
||||
|
||||
let mut url = Url::parse(value)
|
||||
.map_err(|_| ProfileCommandError::validation("Connection URL is invalid."))?;
|
||||
if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
|
||||
return Err(ProfileCommandError::validation(
|
||||
"Connection URL must use HTTP or HTTPS and include a host.",
|
||||
));
|
||||
}
|
||||
if !url.username().is_empty() || url.password().is_some() {
|
||||
return Err(ProfileCommandError::validation(
|
||||
"Credentials must not be embedded in a connection URL.",
|
||||
));
|
||||
}
|
||||
if url.query().is_some() || url.fragment().is_some() {
|
||||
return Err(ProfileCommandError::validation(
|
||||
"Connection URLs must not contain query parameters or fragments.",
|
||||
));
|
||||
}
|
||||
if url.scheme() == "http" && !allow_insecure_http {
|
||||
return Err(ProfileCommandError::validation(
|
||||
"HTTP requires explicit insecure-transport approval.",
|
||||
));
|
||||
}
|
||||
url.set_fragment(None);
|
||||
Ok(url.to_string())
|
||||
}
|
||||
|
||||
fn normalize_fingerprint(value: Option<String>) -> Result<Option<String>, ProfileCommandError> {
|
||||
let Some(value) = value else {
|
||||
return Ok(None);
|
||||
};
|
||||
let normalized = value
|
||||
.trim()
|
||||
.chars()
|
||||
.filter(|character| *character != ':')
|
||||
.flat_map(char::to_uppercase)
|
||||
.collect::<String>();
|
||||
if normalized.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
if normalized.len() != 64
|
||||
|| !normalized
|
||||
.chars()
|
||||
.all(|character| character.is_ascii_hexdigit())
|
||||
{
|
||||
return Err(ProfileCommandError::validation(
|
||||
"Pinned certificate fingerprint must be a SHA-256 hex value.",
|
||||
));
|
||||
}
|
||||
Ok(Some(normalized))
|
||||
}
|
||||
|
||||
fn validate_id(id: &str) -> Result<(), ProfileCommandError> {
|
||||
if Uuid::parse_str(id).is_err() {
|
||||
return Err(ProfileCommandError::validation(
|
||||
"Connection profile ID is invalid.",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn timestamp() -> Result<String, ProfileCommandError> {
|
||||
OffsetDateTime::now_utc()
|
||||
.format(&Rfc3339)
|
||||
.map_err(|_| ProfileCommandError {
|
||||
code: "clockUnavailable",
|
||||
message: "The system clock could not produce a profile timestamp.",
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn request(base_url: &str) -> ConnectionProfileInput {
|
||||
ConnectionProfileInput {
|
||||
display_name: " Test Profile ".into(),
|
||||
role: AstrBotProfileRole::General,
|
||||
base_url: base_url.into(),
|
||||
event_stream_url: None,
|
||||
authentication_type: AuthenticationType::DeviceToken,
|
||||
transport_kind: TransportKind::DesktopV1,
|
||||
allow_insecure_http: false,
|
||||
remote_username: None,
|
||||
pinned_certificate_fingerprint: None,
|
||||
auto_connect: false,
|
||||
auto_connect_slot: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creates_updates_lists_and_deletes_profile_metadata() {
|
||||
let database = ApplicationDatabase::in_memory().expect("database");
|
||||
let created =
|
||||
create_profile(&database, request("https://example.test")).expect("create profile");
|
||||
assert_eq!(created.display_name, "Test Profile");
|
||||
assert_eq!(created.base_url, "https://example.test/");
|
||||
assert!(created.credential_reference.is_none());
|
||||
assert!(!created.auto_connect);
|
||||
assert!(created.auto_connect_slot.is_none());
|
||||
|
||||
let updated = update_profile(
|
||||
&database,
|
||||
UpdateConnectionProfileRequest {
|
||||
id: created.id.clone(),
|
||||
profile: ConnectionProfileInput {
|
||||
display_name: "Updated".into(),
|
||||
role: AstrBotProfileRole::Companion,
|
||||
base_url: "https://updated.example.test".into(),
|
||||
event_stream_url: Some("https://updated.example.test/events".into()),
|
||||
authentication_type: AuthenticationType::ApiKey,
|
||||
transport_kind: TransportKind::DesktopV1,
|
||||
allow_insecure_http: false,
|
||||
remote_username: None,
|
||||
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");
|
||||
assert!(list_profiles(&database).expect("list profiles").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_insecure_or_credential_bearing_urls() {
|
||||
let database = ApplicationDatabase::in_memory().expect("database");
|
||||
assert!(create_profile(&database, request("http://example.test")).is_err());
|
||||
assert!(create_profile(&database, request("https://user:password@example.test")).is_err());
|
||||
assert!(create_profile(&database, request("https://example.test?token=fake")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_secret_values_and_unknown_fields_at_the_ipc_boundary() {
|
||||
let result = serde_json::from_value::<ConnectionProfileInput>(serde_json::json!({
|
||||
"displayName": "Test Profile",
|
||||
"role": "general",
|
||||
"baseUrl": "https://example.test",
|
||||
"authenticationType": "device-token",
|
||||
"allowInsecureHttp": false,
|
||||
"token": "[REDACTED]",
|
||||
"password": "[REDACTED]",
|
||||
"apiKey": "[REDACTED]"
|
||||
}));
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,11 @@
|
|||
#[cfg(windows)]
|
||||
#[cfg(windows)]
|
||||
pub use crate::windows::credential_manager::{
|
||||
CredentialReference, SecureCredentialStore, WindowsCredentialStore,
|
||||
CredentialReference, SecretCredential, SecureCredentialStore, SecureStoreError,
|
||||
WindowsCredentialStore,
|
||||
};
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub use crate::windows::credential_manager::{
|
||||
CredentialReference, SecretCredential, SecureCredentialStore, SecureStoreError,
|
||||
WindowsCredentialStore,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,294 +1,297 @@
|
|||
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};
|
||||
use crate::runtime_guards::RuntimeGuards;
|
||||
|
||||
#[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 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 {
|
||||
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>,
|
||||
guards: tauri::State<'_, RuntimeGuards>,
|
||||
request: AssignConnectionSlotRequest,
|
||||
) -> Result<ConnectionSlot, SlotCommandError> {
|
||||
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, &guards, slot)
|
||||
}
|
||||
|
||||
fn list_slots(database: &ApplicationDatabase) -> Result<Vec<ConnectionSlot>, SlotCommandError> {
|
||||
database
|
||||
.list_connection_slots()
|
||||
.map_err(SlotCommandError::database)
|
||||
}
|
||||
|
||||
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, ×tamp()?)
|
||||
.map_err(SlotCommandError::database)
|
||||
}
|
||||
|
||||
fn clear_slot(
|
||||
database: &ApplicationDatabase,
|
||||
guards: &RuntimeGuards,
|
||||
slot: ActiveSlotKind,
|
||||
) -> Result<ConnectionSlot, SlotCommandError> {
|
||||
ensure_operations_switch_allowed(guards, slot, None)?;
|
||||
database
|
||||
.clear_connection_slot(slot, ×tamp()?)
|
||||
.map_err(SlotCommandError::database)
|
||||
}
|
||||
|
||||
fn ensure_operations_switch_allowed(
|
||||
guards: &RuntimeGuards,
|
||||
slot: ActiveSlotKind,
|
||||
next_profile_id: Option<&str>,
|
||||
) -> Result<(), SlotCommandError> {
|
||||
if slot != ActiveSlotKind::Operations {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let locked = guards
|
||||
.operations_switch_locked()
|
||||
.map_err(|_| SlotCommandError {
|
||||
code: "databaseUnavailable",
|
||||
message: "The operations switch guard is unavailable.",
|
||||
})?;
|
||||
if locked {
|
||||
return Err(SlotCommandError::operations_switch_locked());
|
||||
}
|
||||
|
||||
// Companion may still change while operations work is idle; this check is
|
||||
// intentionally scoped to the operations slot only.
|
||||
let _ = next_profile_id;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_profile_id(id: &str) -> Result<(), SlotCommandError> {
|
||||
if Uuid::parse_str(id).is_err() {
|
||||
return Err(SlotCommandError::validation(
|
||||
"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 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(),
|
||||
},
|
||||
)
|
||||
.expect("assign slot");
|
||||
assert_eq!(assigned.profile_id.as_deref(), Some(companion.id.as_str()));
|
||||
|
||||
let cleared =
|
||||
clear_slot(&database, &guards, 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");
|
||||
let guards = RuntimeGuards::new();
|
||||
assert!(
|
||||
assign_slot(
|
||||
&database,
|
||||
&guards,
|
||||
AssignConnectionSlotRequest {
|
||||
slot: ActiveSlotKind::Operations,
|
||||
profile_id: "not-a-uuid".into(),
|
||||
},
|
||||
)
|
||||
.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");
|
||||
}
|
||||
}
|
||||
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};
|
||||
use crate::runtime_guards::RuntimeGuards;
|
||||
|
||||
#[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 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 {
|
||||
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>,
|
||||
guards: tauri::State<'_, RuntimeGuards>,
|
||||
request: AssignConnectionSlotRequest,
|
||||
) -> Result<ConnectionSlot, SlotCommandError> {
|
||||
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, &guards, slot)
|
||||
}
|
||||
|
||||
fn list_slots(database: &ApplicationDatabase) -> Result<Vec<ConnectionSlot>, SlotCommandError> {
|
||||
database
|
||||
.list_connection_slots()
|
||||
.map_err(SlotCommandError::database)
|
||||
}
|
||||
|
||||
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, ×tamp()?)
|
||||
.map_err(SlotCommandError::database)
|
||||
}
|
||||
|
||||
fn clear_slot(
|
||||
database: &ApplicationDatabase,
|
||||
guards: &RuntimeGuards,
|
||||
slot: ActiveSlotKind,
|
||||
) -> Result<ConnectionSlot, SlotCommandError> {
|
||||
ensure_operations_switch_allowed(guards, slot, None)?;
|
||||
database
|
||||
.clear_connection_slot(slot, ×tamp()?)
|
||||
.map_err(SlotCommandError::database)
|
||||
}
|
||||
|
||||
fn ensure_operations_switch_allowed(
|
||||
guards: &RuntimeGuards,
|
||||
slot: ActiveSlotKind,
|
||||
next_profile_id: Option<&str>,
|
||||
) -> Result<(), SlotCommandError> {
|
||||
if slot != ActiveSlotKind::Operations {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let locked = guards
|
||||
.operations_switch_locked()
|
||||
.map_err(|_| SlotCommandError {
|
||||
code: "databaseUnavailable",
|
||||
message: "The operations switch guard is unavailable.",
|
||||
})?;
|
||||
if locked {
|
||||
return Err(SlotCommandError::operations_switch_locked());
|
||||
}
|
||||
|
||||
// Companion may still change while operations work is idle; this check is
|
||||
// intentionally scoped to the operations slot only.
|
||||
let _ = next_profile_id;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_profile_id(id: &str) -> Result<(), SlotCommandError> {
|
||||
if Uuid::parse_str(id).is_err() {
|
||||
return Err(SlotCommandError::validation(
|
||||
"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,
|
||||
transport_kind: desktop_protocol::TransportKind::DesktopV1,
|
||||
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,
|
||||
remote_username: None,
|
||||
sticky_session_id: 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 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(),
|
||||
},
|
||||
)
|
||||
.expect("assign slot");
|
||||
assert_eq!(assigned.profile_id.as_deref(), Some(companion.id.as_str()));
|
||||
|
||||
let cleared =
|
||||
clear_slot(&database, &guards, 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");
|
||||
let guards = RuntimeGuards::new();
|
||||
assert!(
|
||||
assign_slot(
|
||||
&database,
|
||||
&guards,
|
||||
AssignConnectionSlotRequest {
|
||||
slot: ActiveSlotKind::Operations,
|
||||
profile_id: "not-a-uuid".into(),
|
||||
},
|
||||
)
|
||||
.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");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
|
|
@ -161,6 +161,7 @@ describe("App", () => {
|
|||
const created: ConnectionProfile = {
|
||||
id: "2bdedc10-d804-4da5-8e92-39dd7f175d7a",
|
||||
...request,
|
||||
transportKind: "desktop-v1",
|
||||
createdAt: "2026-07-18T02:00:00Z",
|
||||
updatedAt: "2026-07-18T02:00:00Z",
|
||||
};
|
||||
|
|
@ -256,6 +257,7 @@ describe("App", () => {
|
|||
role: "companion",
|
||||
baseUrl: "https://companion.example.test/",
|
||||
authenticationType: "device-token",
|
||||
transportKind: "desktop-v1",
|
||||
allowInsecureHttp: false,
|
||||
autoConnect: false,
|
||||
createdAt: "2026-07-19T02:00:00Z",
|
||||
|
|
@ -267,6 +269,7 @@ describe("App", () => {
|
|||
role: "operations",
|
||||
baseUrl: "https://operations.example.test/",
|
||||
authenticationType: "api-key",
|
||||
transportKind: "desktop-v1",
|
||||
allowInsecureHttp: false,
|
||||
autoConnect: false,
|
||||
createdAt: "2026-07-19T02:00:00Z",
|
||||
|
|
@ -319,6 +322,7 @@ describe("App", () => {
|
|||
const created: ConnectionProfile = {
|
||||
id: "2bdedc10-d804-4da5-8e92-39dd7f175d7a",
|
||||
...request,
|
||||
transportKind: "desktop-v1",
|
||||
createdAt: "2026-07-19T03:00:00Z",
|
||||
updatedAt: "2026-07-19T03:00:00Z",
|
||||
};
|
||||
|
|
@ -358,6 +362,7 @@ describe("App", () => {
|
|||
role: "companion",
|
||||
baseUrl: "https://companion.example.test",
|
||||
authenticationType: "device-token",
|
||||
transportKind: "desktop-v1",
|
||||
allowInsecureHttp: false,
|
||||
autoConnect: true,
|
||||
autoConnectSlot: "companion",
|
||||
|
|
@ -373,6 +378,7 @@ describe("App", () => {
|
|||
role: "companion",
|
||||
baseUrl: "https://companion.example.test/",
|
||||
authenticationType: "device-token",
|
||||
transportKind: "desktop-v1",
|
||||
allowInsecureHttp: false,
|
||||
autoConnect: false,
|
||||
serverInstanceId: "server-shared",
|
||||
|
|
@ -385,6 +391,7 @@ describe("App", () => {
|
|||
role: "operations",
|
||||
baseUrl: "https://operations.example.test/",
|
||||
authenticationType: "api-key",
|
||||
transportKind: "desktop-v1",
|
||||
allowInsecureHttp: false,
|
||||
autoConnect: false,
|
||||
serverInstanceId: "server-shared",
|
||||
|
|
|
|||
35
src/App.tsx
35
src/App.tsx
|
|
@ -1,6 +1,8 @@
|
|||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
|
||||
import { ChatPanel } from "./features/chat/ChatPanel";
|
||||
import { StatusBubble } from "./features/chat/StatusBubble";
|
||||
import { ProfileManager } from "./features/profiles/ProfileManager";
|
||||
import { bootstrapStatusSchema, type BootstrapStatus } from "./types/bootstrap";
|
||||
|
||||
|
|
@ -9,10 +11,13 @@ const initialStatus: BootstrapStatus = {
|
|||
platform: "unknown",
|
||||
rustCore: "pending",
|
||||
protocolVersion: "desktop-v1alpha1",
|
||||
databaseSchemaVersion: 3,
|
||||
databaseSchemaVersion: 4,
|
||||
};
|
||||
|
||||
export function App() {
|
||||
const view = new URLSearchParams(window.location.search).get("view");
|
||||
const isQuickView = view === "quick";
|
||||
const isBubbleView = view === "bubble";
|
||||
const [status, setStatus] = useState(initialStatus);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
|
|
@ -30,13 +35,22 @@ export function App() {
|
|||
void refreshStatus();
|
||||
}, [refreshStatus]);
|
||||
|
||||
if (isBubbleView) return <StatusBubble />;
|
||||
if (isQuickView)
|
||||
return (
|
||||
<main className="quick-app-shell">
|
||||
<ChatPanel />
|
||||
</main>
|
||||
);
|
||||
|
||||
return (
|
||||
<main className="app-shell">
|
||||
<header className="hero">
|
||||
<p className="eyebrow">P02 · dual connections</p>
|
||||
<p className="eyebrow">P02 路 dual connections</p>
|
||||
<h1>AstrBot Desktop</h1>
|
||||
<p className="subtitle">
|
||||
双实例陪伴与本机助手的安全 Windows 客户端工程底座。
|
||||
鍙屽疄渚嬮櫔浼翠笌鏈満鍔╂墜鐨勫畨鍏?Windows
|
||||
瀹㈡埛绔伐绋嬪簳搴с€?{" "}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
|
|
@ -54,7 +68,7 @@ export function App() {
|
|||
{error ? <p className="error-banner">IPC unavailable: {error}</p> : null}
|
||||
|
||||
<section className="boundaries">
|
||||
<h2>安全边界</h2>
|
||||
<h2>瀹夊叏杈圭晫</h2>
|
||||
<ul>
|
||||
<li>凭据只在 Rust 与 Windows 安全存储之间流动。</li>
|
||||
<li>两个 REST/SSE 槽位保持独立状态与事件来源。</li>
|
||||
|
|
@ -62,10 +76,19 @@ export function App() {
|
|||
<li>文件事务默认保留源文件,且不会静默覆盖。</li>
|
||||
</ul>
|
||||
</section>
|
||||
<div className="chat-actions">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void invoke("open_quick_chat_window")}
|
||||
>
|
||||
打开快速聊天
|
||||
</button>
|
||||
</div>
|
||||
<ChatPanel />
|
||||
<ProfileManager />
|
||||
|
||||
<button type="button" onClick={() => void refreshStatus()}>
|
||||
重新检查 IPC
|
||||
閲嶆柊妫€鏌?IPC
|
||||
</button>
|
||||
</main>
|
||||
);
|
||||
|
|
|
|||
283
src/features/chat/ChatPanel.tsx
普通文件
283
src/features/chat/ChatPanel.tsx
普通文件
|
|
@ -0,0 +1,283 @@
|
|||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
|
||||
import {
|
||||
boundRuntimeEventSchema,
|
||||
connectionRuntimeStatusSchema,
|
||||
type BoundRuntimeEvent,
|
||||
type ChatMessage,
|
||||
type ChatSlot,
|
||||
type ConnectionRuntimeStatus,
|
||||
storedChatMessageSchema,
|
||||
} from "./types";
|
||||
|
||||
const emptyStatus: ConnectionRuntimeStatus = {
|
||||
companion: { slot: "companion", state: "disconnected" },
|
||||
operations: { slot: "operations", state: "disconnected" },
|
||||
};
|
||||
|
||||
function payloadString(
|
||||
event: BoundRuntimeEvent,
|
||||
key: string,
|
||||
): string | undefined {
|
||||
if (!event.payload || typeof event.payload !== "object") return undefined;
|
||||
const value = (event.payload as Record<string, unknown>)[key];
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
export function ChatPanel() {
|
||||
const [status, setStatus] = useState(emptyStatus);
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [activeSlot, setActiveSlot] = useState<ChatSlot>("companion");
|
||||
const [draft, setDraft] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const activeMessages = useMemo(
|
||||
() => messages.filter((item) => item.slot === activeSlot),
|
||||
[messages, activeSlot],
|
||||
);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
const result = await invoke<unknown>("connection_runtime_status");
|
||||
setStatus(connectionRuntimeStatusSchema.parse(result));
|
||||
setError(null);
|
||||
return true;
|
||||
} catch (reason) {
|
||||
setError(reason instanceof Error ? reason.message : String(reason));
|
||||
return false;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const drainEvents = useCallback(async () => {
|
||||
try {
|
||||
const result = await invoke<unknown>("drain_connection_runtime_events", {
|
||||
request: { limit: 64 },
|
||||
});
|
||||
const events = boundRuntimeEventSchema.array().parse(result);
|
||||
if (events.length > 0)
|
||||
setMessages((current) => applyRuntimeEvents(current, events));
|
||||
} catch {
|
||||
// Browser fallback keeps the shell usable without Rust IPC.
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const snapshot = status[activeSlot];
|
||||
if (
|
||||
!snapshot.profileId ||
|
||||
!snapshot.serverInstanceId ||
|
||||
!snapshot.activeSessionId
|
||||
)
|
||||
return;
|
||||
let cancelled = false;
|
||||
void invoke<unknown>("load_chat_messages", {
|
||||
request: {
|
||||
profileId: snapshot.profileId,
|
||||
serverInstanceId: snapshot.serverInstanceId,
|
||||
sessionId: snapshot.activeSessionId,
|
||||
limit: 100,
|
||||
},
|
||||
})
|
||||
.then((result) => {
|
||||
if (cancelled) return;
|
||||
const records = storedChatMessageSchema.array().parse(result);
|
||||
setMessages((current) => {
|
||||
const otherSlots = current.filter((item) => item.slot !== activeSlot);
|
||||
const restored = records.map((record) => ({
|
||||
id: record.messageId,
|
||||
slot: record.slot,
|
||||
role: record.role,
|
||||
content: record.content,
|
||||
streaming: record.streaming,
|
||||
error: record.error,
|
||||
}));
|
||||
return otherSlots.concat(restored);
|
||||
});
|
||||
})
|
||||
.catch(() => undefined);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [activeSlot, status]);
|
||||
|
||||
useEffect(() => {
|
||||
let timer: number | undefined;
|
||||
void refresh().then((available) => {
|
||||
if (!available) return;
|
||||
timer = window.setInterval(() => {
|
||||
void refresh();
|
||||
void drainEvents();
|
||||
}, 500);
|
||||
});
|
||||
return () => {
|
||||
if (timer !== undefined) window.clearInterval(timer);
|
||||
};
|
||||
}, [drainEvents, refresh]);
|
||||
|
||||
const send = async () => {
|
||||
const message = draft.trim();
|
||||
if (!message) return;
|
||||
const id = "local-" + Date.now();
|
||||
setDraft("");
|
||||
setMessages((current) =>
|
||||
current.concat({ id, slot: activeSlot, role: "user", content: message }),
|
||||
);
|
||||
try {
|
||||
await invoke("send_connection_slot_message", {
|
||||
request: { slot: activeSlot, message },
|
||||
});
|
||||
setError(null);
|
||||
} catch (reason) {
|
||||
setError(reason instanceof Error ? reason.message : String(reason));
|
||||
setMessages((current) =>
|
||||
current.map((item) =>
|
||||
item.id === id ? { ...item, error: true } : item,
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="chat-panel" aria-label="聊天面板">
|
||||
<div className="chat-heading">
|
||||
<div>
|
||||
<p className="eyebrow">Q1 shared chat runtime</p>
|
||||
<h2>统一聊天运行时</h2>
|
||||
<p className="chat-note">
|
||||
主页面、快速聊天和气泡共享同一套消息状态。
|
||||
</p>
|
||||
</div>
|
||||
<div className="chat-slot-tabs" role="tablist" aria-label="聊天槽位">
|
||||
{(["companion", "operations"] as const).map((slot) => (
|
||||
<button
|
||||
className={activeSlot === slot ? "chat-slot active" : "chat-slot"}
|
||||
key={slot}
|
||||
onClick={() => setActiveSlot(slot)}
|
||||
role="tab"
|
||||
aria-selected={activeSlot === slot}
|
||||
type="button"
|
||||
>
|
||||
{slot === "companion" ? "陪伴" : "运维"}
|
||||
<span>{status[slot].state}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="chat-runtime-strip">
|
||||
<span>Profile:{status[activeSlot].profileId ?? "未连接"}</span>
|
||||
<span>Session:{status[activeSlot].activeSessionId ?? "未建立"}</span>
|
||||
<span>状态:{status[activeSlot].state}</span>
|
||||
</div>
|
||||
<div className="chat-message-list" aria-live="polite">
|
||||
{activeMessages.length === 0 ? (
|
||||
<p className="chat-empty">
|
||||
当前槽位还没有消息。连接 Profile 后即可开始聊天。
|
||||
</p>
|
||||
) : (
|
||||
activeMessages.map((message) => (
|
||||
<article
|
||||
className={
|
||||
"chat-message " +
|
||||
message.role +
|
||||
(message.error ? " failed" : "")
|
||||
}
|
||||
key={message.id}
|
||||
>
|
||||
<span className="chat-message-role">
|
||||
{message.role === "user"
|
||||
? "我"
|
||||
: message.role === "assistant"
|
||||
? "AstrBot"
|
||||
: "系统"}
|
||||
</span>
|
||||
<p>{message.content || "…"}</p>
|
||||
{message.streaming ? <small>生成中</small> : null}
|
||||
</article>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
{error ? <p className="chat-error">{error}</p> : null}
|
||||
<form
|
||||
className="chat-composer"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
void send();
|
||||
}}
|
||||
>
|
||||
<textarea
|
||||
aria-label="聊天消息"
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
placeholder={
|
||||
activeSlot === "companion"
|
||||
? "和陪伴实例说点什么…"
|
||||
: "向运维实例描述问题…"
|
||||
}
|
||||
value={draft}
|
||||
rows={3}
|
||||
/>
|
||||
<button disabled={!draft.trim()} type="submit">
|
||||
发送
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function applyRuntimeEvents(
|
||||
current: ChatMessage[],
|
||||
events: BoundRuntimeEvent[],
|
||||
): ChatMessage[] {
|
||||
const next = current.map((item) => ({ ...item }));
|
||||
for (const event of events) {
|
||||
if (event.eventType === "message.delta") {
|
||||
const id =
|
||||
event.messageId || payloadString(event, "messageId") || event.eventId;
|
||||
const delta =
|
||||
payloadString(event, "delta") || payloadString(event, "content") || "";
|
||||
const existing = next.find(
|
||||
(item) => item.id === id && item.slot === event.slot,
|
||||
);
|
||||
if (existing) {
|
||||
existing.content += delta;
|
||||
existing.streaming = true;
|
||||
} else
|
||||
next.push({
|
||||
id,
|
||||
slot: event.slot,
|
||||
role: "assistant",
|
||||
content: delta,
|
||||
streaming: true,
|
||||
});
|
||||
} else if (event.eventType === "message.completed") {
|
||||
const id =
|
||||
event.messageId || payloadString(event, "messageId") || event.eventId;
|
||||
const existing = next.find(
|
||||
(item) => item.id === id && item.slot === event.slot,
|
||||
);
|
||||
if (existing) existing.streaming = false;
|
||||
else
|
||||
next.push({
|
||||
id,
|
||||
slot: event.slot,
|
||||
role: "assistant",
|
||||
content: payloadString(event, "content") || "",
|
||||
});
|
||||
} else if (event.eventType === "error") {
|
||||
next.push({
|
||||
id: event.eventId,
|
||||
slot: event.slot,
|
||||
role: "system",
|
||||
content: payloadString(event, "message") || "连接错误",
|
||||
error: true,
|
||||
});
|
||||
} else if (event.eventType === "message.proactive") {
|
||||
next.push({
|
||||
id: event.eventId,
|
||||
slot: event.slot,
|
||||
role: "assistant",
|
||||
content: payloadString(event, "content") || "",
|
||||
});
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import {
|
||||
connectionRuntimeStatusSchema,
|
||||
type ConnectionRuntimeStatus,
|
||||
} from "./types";
|
||||
|
||||
const initialStatus: ConnectionRuntimeStatus = {
|
||||
companion: { slot: "companion", state: "disconnected" },
|
||||
operations: { slot: "operations", state: "disconnected" },
|
||||
};
|
||||
|
||||
export function StatusBubble() {
|
||||
const [status, setStatus] = useState(initialStatus);
|
||||
useEffect(() => {
|
||||
const refresh = () =>
|
||||
invoke<unknown>("connection_runtime_status")
|
||||
.then((value) => setStatus(connectionRuntimeStatusSchema.parse(value)))
|
||||
.catch(() => undefined);
|
||||
refresh();
|
||||
const timer = window.setInterval(refresh, 1000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, []);
|
||||
const companion = status.companion.state;
|
||||
const operations = status.operations.state;
|
||||
const active = companion === "connected" || operations === "connected";
|
||||
return (
|
||||
<main className="status-bubble-shell" aria-label="连接状态气泡">
|
||||
<button
|
||||
className={active ? "status-bubble connected" : "status-bubble"}
|
||||
type="button"
|
||||
onClick={() => void invoke("open_quick_chat_window")}
|
||||
>
|
||||
<span className="status-bubble-orb" />
|
||||
<span className="status-bubble-label">{active ? "在线" : "离线"}</span>
|
||||
</button>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
72
src/features/chat/types.ts
普通文件
72
src/features/chat/types.ts
普通文件
|
|
@ -0,0 +1,72 @@
|
|||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
activeSlotKindSchema,
|
||||
connectionStateSchema,
|
||||
type ActiveSlotKind,
|
||||
} from "../../types/connection";
|
||||
|
||||
export const slotRuntimeSnapshotSchema = z
|
||||
.object({
|
||||
slot: activeSlotKindSchema,
|
||||
profileId: z.uuid().optional(),
|
||||
transport: z.enum(["desktop-v1", "astrbot-openapi"]).optional(),
|
||||
state: connectionStateSchema,
|
||||
serverInstanceId: z.string().min(1).optional(),
|
||||
activeSessionId: z.string().min(1).optional(),
|
||||
lastError: z.string().optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const connectionRuntimeStatusSchema = z
|
||||
.object({
|
||||
companion: slotRuntimeSnapshotSchema,
|
||||
operations: slotRuntimeSnapshotSchema,
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const boundRuntimeEventSchema = z
|
||||
.object({
|
||||
profileId: z.string().min(1),
|
||||
slot: activeSlotKindSchema,
|
||||
eventId: z.string().min(1),
|
||||
eventType: z.string().min(1),
|
||||
serverInstanceId: z.string().min(1),
|
||||
sessionId: z.string().min(1).optional(),
|
||||
messageId: z.string().min(1).optional(),
|
||||
payload: z.unknown(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type SlotRuntimeSnapshot = z.infer<typeof slotRuntimeSnapshotSchema>;
|
||||
export type ConnectionRuntimeStatus = z.infer<
|
||||
typeof connectionRuntimeStatusSchema
|
||||
>;
|
||||
export type BoundRuntimeEvent = z.infer<typeof boundRuntimeEventSchema>;
|
||||
export type ChatSlot = ActiveSlotKind;
|
||||
|
||||
export interface ChatMessage {
|
||||
id: string;
|
||||
slot: ChatSlot;
|
||||
role: "user" | "assistant" | "system";
|
||||
content: string;
|
||||
streaming?: boolean;
|
||||
error?: boolean;
|
||||
}
|
||||
|
||||
export const storedChatMessageSchema = z
|
||||
.object({
|
||||
accountId: z.string().min(1),
|
||||
profileId: z.string().min(1),
|
||||
slot: activeSlotKindSchema,
|
||||
serverInstanceId: z.string().min(1),
|
||||
remoteUsername: z.string().min(1).optional(),
|
||||
sessionId: z.string().min(1),
|
||||
messageId: z.string().min(1),
|
||||
role: z.enum(["user", "assistant", "system"]),
|
||||
content: z.string(),
|
||||
streaming: z.boolean(),
|
||||
error: z.boolean(),
|
||||
updatedAt: z.string().min(1),
|
||||
})
|
||||
.strict();
|
||||
56
src/features/pet/types.ts
普通文件
56
src/features/pet/types.ts
普通文件
|
|
@ -0,0 +1,56 @@
|
|||
import { z } from "zod";
|
||||
|
||||
export const companionStateSchema = z.enum([
|
||||
"idle",
|
||||
"thinking",
|
||||
"speaking",
|
||||
"error",
|
||||
"notification",
|
||||
"offline",
|
||||
]);
|
||||
|
||||
export const petDisplayModeSchema = z.enum(["app-ui", "desktop-floating"]);
|
||||
export const petPositionModeSchema = z.enum([
|
||||
"free",
|
||||
"edge",
|
||||
"指定屏幕",
|
||||
"follow-main-window",
|
||||
]);
|
||||
export const bubbleClickTargetSchema = z.enum(["main", "quick"]);
|
||||
|
||||
export const petAnimationSchema = z
|
||||
.object({
|
||||
state: companionStateSchema,
|
||||
frames: z.array(z.number().int().nonnegative()).min(1),
|
||||
fps: z.number().positive().max(60),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const petPackManifestSchema = z
|
||||
.object({
|
||||
format: z.literal("astrbot-pet-pack.v1"),
|
||||
name: z.string().min(1).max(80),
|
||||
version: z.string().min(1).max(32),
|
||||
image: z.string().regex(/^[^\\/:*?"<>|]+\\.(png|webp)$/i),
|
||||
width: z.number().int().positive().max(4096),
|
||||
height: z.number().int().positive().max(4096),
|
||||
animations: z.array(petAnimationSchema).min(1),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const companionPresentationSettingsSchema = z
|
||||
.object({
|
||||
enabled: z.boolean(),
|
||||
displayMode: petDisplayModeSchema,
|
||||
positionMode: petPositionModeSchema,
|
||||
bubbleClickTarget: bubbleClickTargetSchema,
|
||||
alwaysOnTop: z.boolean(),
|
||||
gameMode: z.boolean(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type CompanionState = z.infer<typeof companionStateSchema>;
|
||||
export type PetPackManifest = z.infer<typeof petPackManifestSchema>;
|
||||
export type CompanionPresentationSettings = z.infer<
|
||||
typeof companionPresentationSettingsSchema
|
||||
>;
|
||||
|
|
@ -0,0 +1,109 @@
|
|||
import { useState } from "react";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import type { AuthenticationType, ConnectionProfile } from "../../types/profile";
|
||||
|
||||
interface CredentialEnrollmentResult {
|
||||
profileId: string;
|
||||
credentialReference: string;
|
||||
authenticationType: AuthenticationType;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
profile: ConnectionProfile;
|
||||
onChanged: () => Promise<void> | void;
|
||||
}
|
||||
|
||||
export function CredentialEnrollmentCard({ profile, onChanged }: Props) {
|
||||
const [secret, setSecret] = useState("");
|
||||
const [username, setUsername] = useState(profile.remoteUsername ?? "");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
|
||||
async function enroll() {
|
||||
setBusy(true);
|
||||
setMessage(null);
|
||||
try {
|
||||
const result = await invoke<CredentialEnrollmentResult>(
|
||||
"enroll_profile_credential",
|
||||
{
|
||||
request: {
|
||||
profileId: profile.id,
|
||||
authenticationType: profile.authenticationType,
|
||||
secret,
|
||||
username: username.trim() || undefined,
|
||||
},
|
||||
},
|
||||
);
|
||||
setSecret("");
|
||||
setMessage(`已登记凭据引用 ${result.credentialReference}`);
|
||||
await onChanged();
|
||||
} catch (error) {
|
||||
setMessage(
|
||||
error instanceof Error ? error.message : "凭据登记失败(详情未包含密钥)。",
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function clearCredential() {
|
||||
setBusy(true);
|
||||
setMessage(null);
|
||||
try {
|
||||
await invoke("clear_profile_credential", { profileId: profile.id });
|
||||
setMessage("已清除凭据引用");
|
||||
await onChanged();
|
||||
} catch (error) {
|
||||
setMessage(
|
||||
error instanceof Error ? error.message : "清除凭据失败。",
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="credential-card" aria-label={`凭据登记 ${profile.displayName}`}>
|
||||
<h4>安全凭据登记</h4>
|
||||
<p>
|
||||
密钥只通过一次性 IPC 写入 Windows Credential Manager,不会进入 React 持久状态。
|
||||
</p>
|
||||
<label>
|
||||
用户名(可选,AstrBot 可用)
|
||||
<input
|
||||
value={username}
|
||||
onChange={(event) => setUsername(event.target.value)}
|
||||
disabled={busy}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
API Key / Token(一次性)
|
||||
<input
|
||||
type="password"
|
||||
value={secret}
|
||||
onChange={(event) => setSecret(event.target.value)}
|
||||
disabled={busy}
|
||||
autoComplete="off"
|
||||
/>
|
||||
</label>
|
||||
<div className="button-row">
|
||||
<button type="button" disabled={busy || !secret.trim()} onClick={() => void enroll()}>
|
||||
登记凭据
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || !profile.credentialReference}
|
||||
onClick={() => void clearCredential()}
|
||||
>
|
||||
清除凭据
|
||||
</button>
|
||||
</div>
|
||||
{profile.credentialReference ? (
|
||||
<p>当前引用:{profile.credentialReference}</p>
|
||||
) : (
|
||||
<p>尚未登记凭据</p>
|
||||
)}
|
||||
{message ? <p role="status">{message}</p> : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
文件差异内容过多而无法显示
加载差异
222
src/styles.css
222
src/styles.css
|
|
@ -418,3 +418,225 @@ select:focus {
|
|||
padding: 2rem 0;
|
||||
}
|
||||
}
|
||||
|
||||
.chat-panel {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
margin: 2rem 0;
|
||||
padding: 1.5rem;
|
||||
border: 1px solid rgb(137 175 232 / 28%);
|
||||
border-radius: 1rem;
|
||||
background: rgb(13 29 52 / 82%);
|
||||
box-shadow: 0 1rem 3rem rgb(0 0 0 / 18%);
|
||||
}
|
||||
|
||||
.chat-heading {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 1.5rem;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.chat-heading h2 {
|
||||
margin: 0.3rem 0;
|
||||
}
|
||||
|
||||
.chat-note,
|
||||
.chat-empty,
|
||||
.chat-error {
|
||||
color: #aebfda;
|
||||
}
|
||||
|
||||
.chat-note {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.chat-slot-tabs {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.55rem;
|
||||
}
|
||||
|
||||
.chat-slot {
|
||||
display: grid;
|
||||
gap: 0.25rem;
|
||||
min-width: 7rem;
|
||||
border-color: rgb(157 181 218 / 48%);
|
||||
background: #20314b;
|
||||
}
|
||||
|
||||
.chat-slot.active {
|
||||
border-color: #7db0ff;
|
||||
background: #24508c;
|
||||
}
|
||||
|
||||
.chat-slot span {
|
||||
color: #bcd0ef;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.chat-runtime-strip {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem 1.25rem;
|
||||
padding: 0.8rem 1rem;
|
||||
border: 1px solid rgb(137 175 232 / 22%);
|
||||
border-radius: 0.7rem;
|
||||
color: #b9c8e4;
|
||||
background: rgb(7 18 34 / 55%);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.chat-message-list {
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
min-height: 15rem;
|
||||
max-height: 28rem;
|
||||
padding: 0.75rem;
|
||||
overflow: auto;
|
||||
border: 1px solid rgb(137 175 232 / 22%);
|
||||
border-radius: 0.8rem;
|
||||
background: rgb(7 18 34 / 42%);
|
||||
}
|
||||
|
||||
.chat-empty {
|
||||
align-self: center;
|
||||
margin: auto;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.chat-message {
|
||||
max-width: 82%;
|
||||
padding: 0.8rem 1rem;
|
||||
border: 1px solid rgb(137 175 232 / 22%);
|
||||
border-radius: 0.85rem;
|
||||
background: rgb(22 47 80 / 80%);
|
||||
}
|
||||
|
||||
.chat-message.user {
|
||||
justify-self: end;
|
||||
background: rgb(34 77 130 / 82%);
|
||||
}
|
||||
|
||||
.chat-message.failed,
|
||||
.chat-error {
|
||||
border-color: rgb(255 122 122 / 55%);
|
||||
}
|
||||
|
||||
.chat-message-role {
|
||||
color: #8db9ff;
|
||||
font-size: 0.78rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.chat-message p {
|
||||
margin: 0.35rem 0 0;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.chat-message small {
|
||||
display: block;
|
||||
margin-top: 0.4rem;
|
||||
color: #aebfda;
|
||||
}
|
||||
|
||||
.chat-error {
|
||||
margin: 0;
|
||||
padding: 0.75rem 0.9rem;
|
||||
border: 1px solid rgb(255 122 122 / 55%);
|
||||
border-radius: 0.7rem;
|
||||
background: rgb(90 36 48 / 45%);
|
||||
}
|
||||
|
||||
.chat-composer {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr auto;
|
||||
gap: 0.75rem;
|
||||
align-items: end;
|
||||
}
|
||||
|
||||
.chat-composer textarea {
|
||||
width: 100%;
|
||||
min-height: 5rem;
|
||||
padding: 0.8rem;
|
||||
resize: vertical;
|
||||
border: 1px solid rgb(137 175 232 / 38%);
|
||||
border-radius: 0.65rem;
|
||||
color: inherit;
|
||||
background: #0b1b31;
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.chat-heading,
|
||||
.chat-composer {
|
||||
grid-template-columns: 1fr;
|
||||
display: grid;
|
||||
}
|
||||
|
||||
.chat-message {
|
||||
max-width: 95%;
|
||||
}
|
||||
}
|
||||
|
||||
.chat-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
margin: 1rem 0;
|
||||
}
|
||||
|
||||
.quick-app-shell {
|
||||
min-width: 320px;
|
||||
min-height: 100vh;
|
||||
padding: 1rem;
|
||||
background: #08111f;
|
||||
}
|
||||
|
||||
.quick-app-shell .chat-panel {
|
||||
margin: 0;
|
||||
min-height: calc(100vh - 2rem);
|
||||
}
|
||||
|
||||
.status-bubble-shell {
|
||||
display: grid;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
place-items: center;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.status-bubble {
|
||||
display: grid;
|
||||
width: 86px;
|
||||
height: 86px;
|
||||
place-items: center;
|
||||
gap: 0.2rem;
|
||||
padding: 0.7rem;
|
||||
border: 1px solid rgb(157 181 218 / 55%);
|
||||
border-radius: 50%;
|
||||
background: rgb(17 38 67 / 94%);
|
||||
box-shadow: 0 0.8rem 2rem rgb(0 0 0 / 35%);
|
||||
}
|
||||
|
||||
.status-bubble.connected {
|
||||
border-color: rgb(96 211 153 / 70%);
|
||||
}
|
||||
|
||||
.status-bubble-orb {
|
||||
width: 1.2rem;
|
||||
height: 1.2rem;
|
||||
border-radius: 50%;
|
||||
background: #ffbd67;
|
||||
box-shadow: 0 0 1rem rgb(255 189 103 / 65%);
|
||||
}
|
||||
|
||||
.status-bubble.connected .status-bubble-orb {
|
||||
background: #60d399;
|
||||
box-shadow: 0 0 1rem rgb(96 211 153 / 65%);
|
||||
}
|
||||
|
||||
.status-bubble-label {
|
||||
color: #eef3ff;
|
||||
font-size: 0.72rem;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,59 +1,67 @@
|
|||
import { z } from "zod";
|
||||
|
||||
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
|
||||
.object({
|
||||
id: z.uuid(),
|
||||
displayName: z.string().min(1).max(80),
|
||||
role: profileRoleSchema,
|
||||
baseUrl: z.url(),
|
||||
eventStreamUrl: z.url().optional(),
|
||||
authenticationType: authenticationTypeSchema,
|
||||
credentialReference: optionalIdentifier,
|
||||
allowInsecureHttp: z.boolean(),
|
||||
pinnedCertificateFingerprint: z
|
||||
.string()
|
||||
.regex(/^[A-F0-9]{64}$/)
|
||||
.optional(),
|
||||
autoConnectSlot: activeSlotKindSchema.optional(),
|
||||
autoConnect: z.boolean(),
|
||||
serverInstanceId: optionalIdentifier,
|
||||
serverVersion: optionalIdentifier,
|
||||
protocolVersion: optionalIdentifier,
|
||||
localToolPolicyId: optionalIdentifier,
|
||||
lastConnectedAt: optionalIdentifier,
|
||||
createdAt: z.string().min(1),
|
||||
updatedAt: z.string().min(1),
|
||||
})
|
||||
.strict();
|
||||
|
||||
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;
|
||||
role: ProfileRole;
|
||||
baseUrl: string;
|
||||
eventStreamUrl?: string;
|
||||
authenticationType: AuthenticationType;
|
||||
allowInsecureHttp: boolean;
|
||||
pinnedCertificateFingerprint?: string;
|
||||
autoConnect: boolean;
|
||||
autoConnectSlot?: ActiveSlotKind;
|
||||
}
|
||||
|
||||
export interface UpdateConnectionProfileRequest {
|
||||
id: string;
|
||||
profile: ConnectionProfileInput;
|
||||
}
|
||||
import { z } from "zod";
|
||||
|
||||
export const profileRoleSchema = z.enum(["companion", "operations", "general"]);
|
||||
|
||||
export const authenticationTypeSchema = z.enum(["device-token", "api-key"]);
|
||||
|
||||
export const transportKindSchema = z.enum(["desktop-v1", "astrbot-openapi"]);
|
||||
|
||||
export const activeSlotKindSchema = z.enum(["companion", "operations"]);
|
||||
|
||||
const optionalIdentifier = z.string().min(1).optional();
|
||||
|
||||
export const connectionProfileSchema = z
|
||||
.object({
|
||||
id: z.uuid(),
|
||||
displayName: z.string().min(1).max(80),
|
||||
role: profileRoleSchema,
|
||||
baseUrl: z.url(),
|
||||
eventStreamUrl: z.url().optional(),
|
||||
authenticationType: authenticationTypeSchema,
|
||||
transportKind: transportKindSchema.default("desktop-v1"),
|
||||
credentialReference: optionalIdentifier,
|
||||
allowInsecureHttp: z.boolean(),
|
||||
pinnedCertificateFingerprint: z
|
||||
.string()
|
||||
.regex(/^[A-F0-9]{64}$/)
|
||||
.optional(),
|
||||
autoConnectSlot: activeSlotKindSchema.optional(),
|
||||
autoConnect: z.boolean(),
|
||||
serverInstanceId: optionalIdentifier,
|
||||
serverVersion: optionalIdentifier,
|
||||
protocolVersion: optionalIdentifier,
|
||||
localToolPolicyId: optionalIdentifier,
|
||||
lastConnectedAt: optionalIdentifier,
|
||||
remoteUsername: optionalIdentifier,
|
||||
stickySessionId: optionalIdentifier,
|
||||
createdAt: z.string().min(1),
|
||||
updatedAt: z.string().min(1),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const connectionProfileListSchema = z.array(connectionProfileSchema);
|
||||
|
||||
export type ProfileRole = z.infer<typeof profileRoleSchema>;
|
||||
export type AuthenticationType = z.infer<typeof authenticationTypeSchema>;
|
||||
export type TransportKind = z.infer<typeof transportKindSchema>;
|
||||
export type ConnectionProfile = z.infer<typeof connectionProfileSchema>;
|
||||
export type ActiveSlotKind = z.infer<typeof activeSlotKindSchema>;
|
||||
|
||||
export interface ConnectionProfileInput {
|
||||
displayName: string;
|
||||
role: ProfileRole;
|
||||
baseUrl: string;
|
||||
eventStreamUrl?: string;
|
||||
authenticationType: AuthenticationType;
|
||||
transportKind?: TransportKind;
|
||||
allowInsecureHttp: boolean;
|
||||
remoteUsername?: string;
|
||||
pinnedCertificateFingerprint?: string;
|
||||
autoConnect: boolean;
|
||||
autoConnectSlot?: ActiveSlotKind;
|
||||
}
|
||||
|
||||
export interface UpdateConnectionProfileRequest {
|
||||
id: string;
|
||||
profile: ConnectionProfileInput;
|
||||
}
|
||||
|
|
|
|||
正在加载…
添加表格
在新工单中引用