diff --git a/CHANGELOG.md b/CHANGELOG.md index c41668a..ebba587 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. @@ -26,6 +30,10 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and - Bounded Rust-owned Profile list/create/update/delete IPC with generated UUIDs and timestamps. - Strict frontend ConnectionProfile Schemas and a basic Profile management UI. - Migration, five-Profile CRUD, persistent reopen, secret-field rejection, and browser fallback tests. +- Persistent dual companion/operations slot assignment with SQLite schema v3 and bounded list/assign/clear IPC. +- Auto-connect configuration validation for at most two Profiles with distinct slots. +- Runtime operations switch guard that blocks operations slot changes while an operations task is active. +- Duplicate `server_instance_id` warnings without silently merging Profiles. ### Security @@ -34,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. + diff --git a/Cargo.lock b/Cargo.lock index 0fac6f9..ed68165 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2441,6 +2441,16 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + [[package]] name = "minimal-lexical" version = "0.2.1" @@ -3328,6 +3338,7 @@ dependencies = [ "hyper-util", "js-sys", "log", + "mime_guess", "percent-encoding", "pin-project-lite", "quinn", @@ -4897,6 +4908,12 @@ dependencies = [ "unic-common", ] +[[package]] +name = "unicase" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" + [[package]] name = "unicode-ident" version = "1.0.24" diff --git a/Cargo.toml b/Cargo.toml index c50a8a7..f50e49c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,7 +20,7 @@ futures-util = "0.3.32" png = "0.18.1" quick-xml = "0.41.0" regex = "1.13.1" -reqwest = { version = "0.13.4", default-features = false, features = ["json", "rustls", "stream"] } +reqwest = { version = "0.13.4", default-features = false, features = ["json", "rustls", "stream", "multipart"] } rusqlite = { version = "0.40.1", features = ["bundled"] } schemars = { version = "1.2.1", features = ["uuid1"] } secrecy = "0.10.3" diff --git a/crates/desktop-protocol/src/astrbot.rs b/crates/desktop-protocol/src/astrbot.rs new file mode 100644 index 0000000..650a82f --- /dev/null +++ b/crates/desktop-protocol/src/astrbot.rs @@ -0,0 +1,518 @@ +//! 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 { + 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 { + pub status: String, + #[serde(default)] + pub message: Option, + #[serde(default)] + pub data: Option, +} + +impl AstrBotApiEnvelope { + 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, + #[serde(skip_serializing_if = "Option::is_none")] + pub conversation_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub username: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub nickname: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub config_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub attachments: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub platform_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub enable_streaming: Option, +} + +/// A model/provider configuration exposed by AstrBot. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct AstrBotModelOption { + pub id: String, + #[serde(default)] + pub name: Option, + #[serde(default)] + pub is_default: Option, +} + +/// Normalized attachment returned by the Rust upload boundary. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AstrBotAttachment { + pub attachment_id: String, + pub file_name: String, + pub mime_type: String, + pub size_bytes: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub url: Option, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AstrBotCapabilitySnapshot { + pub transport: String, + pub text_chat: bool, + pub streaming: bool, + pub model_selection: bool, + pub file_upload: bool, + pub image_input: bool, + pub models: Vec, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct AstrBotSessionListData { + #[serde(default)] + pub sessions: Vec, + #[serde(default)] + pub page: Option, + #[serde(default)] + pub page_size: Option, + #[serde(default)] + pub total: Option, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct AstrBotSessionSummary { + pub session_id: String, + #[serde(default)] + pub platform_id: Option, + #[serde(default)] + pub creator: Option, + #[serde(default)] + pub display_name: Option, + #[serde(default)] + pub is_group: Option, + #[serde(default)] + pub created_at: Option, + #[serde(default)] + pub updated_at: Option, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct AstrBotConfigListData { + #[serde(default)] + pub configs: Vec, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct AstrBotConfigSummary { + pub id: String, + #[serde(default)] + pub name: Option, + #[serde(default)] + pub path: Option, + #[serde(default)] + pub is_default: Option, +} + +/// 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, + #[serde(default)] + pub streaming: Option, + #[serde(default)] + pub chain_type: Option, + #[serde(default)] + pub message_id: Option, +} + +#[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 { + 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, + active_message_id: Option, + accumulated: String, + delta_index: u32, + sequence: u64, + saw_assistant_delta: bool, +} + +impl AstrBotStreamMapper { + pub fn new(server_instance_id: impl Into) -> 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, 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 { + self.complete_if_needed(FinishReason::Stop) + } + + fn map_frame(&mut self, frame: AstrBotStreamFrame) -> Vec { + 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 { + 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 { + 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 { + 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, 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 { + 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 chat_request_serializes_model_and_attachment_options() { + let request = AstrBotChatRequest { + message: Value::String("hello".into()), + session_id: Some("session-a".into()), + conversation_id: None, + username: Some("desktop".into()), + nickname: None, + config_id: Some("model-a".into()), + attachments: Some(vec![AstrBotAttachment { + attachment_id: "file-a".into(), + file_name: "image.png".into(), + mime_type: "image/png".into(), + size_bytes: 12, + url: None, + }]), + platform_id: None, + enable_streaming: Some(true), + }; + let value = serde_json::to_value(request).expect("request serializes"); + assert_eq!(value["config_id"], "model-a"); + assert_eq!(value["attachments"][0]["attachmentId"], "file-a"); + } + + #[test] + fn protocol_version_constant_is_unchanged_for_internal_model() { + assert_eq!(crate::PROTOCOL_VERSION, "desktop-v1alpha1"); + } +} diff --git a/crates/desktop-protocol/src/connection.rs b/crates/desktop-protocol/src/connection.rs index 66d2087..fe06fac 100644 --- a/crates/desktop-protocol/src/connection.rs +++ b/crates/desktop-protocol/src/connection.rs @@ -23,6 +23,7 @@ pub enum AstrBotProfileRole { pub enum AuthenticationType { DeviceToken, ApiKey, + Jwt, } #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] @@ -54,6 +55,9 @@ pub struct ConnectionProfile { #[serde(default, skip_serializing_if = "Option::is_none")] pub event_stream_url: Option, 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, #[serde(default)] @@ -74,6 +78,14 @@ pub struct ConnectionProfile { pub local_tool_policy_id: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub last_connected_at: Option, + /// AstrBot WebChat username / session owner used by OpenAPI chat. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub remote_username: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub remote_display_name: Option, + /// Sticky AstrBot session id for reconnection continuity. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sticky_session_id: Option, pub created_at: String, pub updated_at: String, } @@ -112,3 +124,7 @@ impl ConnectionSlot { } } } + +fn default_transport_kind() -> crate::TransportKind { + crate::TransportKind::DesktopV1 +} diff --git a/crates/desktop-protocol/src/lib.rs b/crates/desktop-protocol/src/lib.rs index abe21c7..edc1483 100644 --- a/crates/desktop-protocol/src/lib.rs +++ b/crates/desktop-protocol/src/lib.rs @@ -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::*; diff --git a/docs/decisions/ADR-0005-astrbot-openapi-adapter.md b/docs/decisions/ADR-0005-astrbot-openapi-adapter.md new file mode 100644 index 0000000..322d850 --- /dev/null +++ b/docs/decisions/ADR-0005-astrbot-openapi-adapter.md @@ -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-`) 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) diff --git a/docs/decisions/ADR-0006-chat-quick-window-and-pet-shell.md b/docs/decisions/ADR-0006-chat-quick-window-and-pet-shell.md new file mode 100644 index 0000000..19ef6db --- /dev/null +++ b/docs/decisions/ADR-0006-chat-quick-window-and-pet-shell.md @@ -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 的游戏模式只能做位置和显示策略,不得扩展为输入注入或任意窗口控制。 diff --git a/docs/decisions/ADR-0007-jwt-background-pet-and-remote-identity.md b/docs/decisions/ADR-0007-jwt-background-pet-and-remote-identity.md new file mode 100644 index 0000000..8b9e11b --- /dev/null +++ b/docs/decisions/ADR-0007-jwt-background-pet-and-remote-identity.md @@ -0,0 +1,26 @@ +# ADR-0007: JWT authentication, remote identity, and background pet windows + +## Context + +AstrBot Desktop must support both API-key automation and Dashboard user login. The pet must continue running after the main chat window is closed, without creating a separate Windows taskbar button. Users also need a stable remote chat identity and animated behavior. + +## Decision + +1. JWT login is a required capability, alongside API Key and device token. JWTs, API keys, passwords, and other credentials are accessed only by Rust and stored in Windows Credential Manager. React never receives plaintext credentials. +2. Remote identity consists of a nickname and an ID configured by the user. The nickname is for display and addressing the user; the ID is used as AstrBot `username` and for local isolation. IDs allow 3-32 ASCII letters and digits and must be unique within a local account. +3. Floating pet mode uses a borderless, skip-taskbar background window. Closing the main chat window leaves the application resident in the system tray. Floating mode is not topmost by default and is controlled by settings. +4. The first pet renderer uses PNG/WebP spritesheets and bounded animation clips. Animation state and movement control are separate. Initial clips include idle, working with a book, speaking, notification, resting walk, and error. Live2D, Spine, 3D, and user script plugins are deferred. + +## Rationale + +- JWT supports normal user login while API Key remains useful for automation and testing. +- Separating nickname and ID provides natural addressing without sacrificing stable session isolation. +- A skip-taskbar background window provides a clean desktop pet experience without changing local permission boundaries. +- Spritesheets provide animated and interactive behavior at lower implementation and security cost, while leaving room for a richer renderer later. + +## Consequences + +- Add JWT login, expiration, 401 re-login, and secure credential migration tests. +- Connect the existing pet display-range setting to the Rust window controller instead of leaving it as a frontend placeholder. +- Extend the pet-pack manifest with animation clips, state transitions, and bounded interaction actions. +- Defer game mode to Q7; do not implement game detection or game-window behavior in this decision. \ No newline at end of file diff --git a/docs/decisions/pending-decisions.md b/docs/decisions/pending-decisions.md index 4fc3fac..f18707f 100644 --- a/docs/decisions/pending-decisions.md +++ b/docs/decisions/pending-decisions.md @@ -61,3 +61,51 @@ - Secret boundary: P01 commands accept no Token, password, API Key, Cookie, Authorization header, or NAS credential fields. SQLite stores only non-sensitive metadata and future opaque credential references. - Rationale: AGENTS.md gives the architecture document higher priority, and the selected split keeps runtime connection behavior out of P01. - ADR: `ADR-0004-profile-lifecycle-and-secret-boundary.md`. + +## PD-0009: Real AstrBot Desktop Gateway contract + +- Status: open; does not block local slot persistence or Mock-based tests +- Current contract: repository-local `/desktop/v1` and protocol `1.0` are provisional development contracts created during P00. +- Missing authority: no reviewed real AstrBot Gateway implementation or server-side contract is available for endpoint, error-code, capability, event-retention, ACK, and authentication compatibility. +- Safe interim rule: keep the protocol types and dual Mock Gateway deterministic, but do not claim real AstrBot compatibility or silently adapt to AstrBot internal APIs. +- Stop boundary: changes that would require modifying AstrBot core or bypassing the stable Gateway boundary require explicit review. + +## PD-0010: Credential enrollment and token lifecycle + +- Status: open before production connection activation +- Established boundary: credential values live only in Windows Credential Manager; SQLite stores opaque references; React never receives stored access or refresh tokens. +- Required decision: define enrollment/update/delete failure atomicity, whether user-entered bootstrap credentials may pass once through bounded Tauri IPC without entering React state, and how access/refresh token rotation updates secure storage. +- Safe interim rule: P02 slot persistence accepts no credential values and cannot activate a real connection. + +## PD-0011: Authoritative server identity enrollment + +- Status: open before first real connection activation +- Candidate source: `GET /desktop/v1/server-info` returns `server_instance_id`, matching the architecture and provisional protocol. +- Required decision: define the first-contact confirmation flow, duplicate-instance warning behavior, and whether a changed identity requires a separate Profile or an explicit rebind operation. +- Safe interim rule: never overwrite an existing `server_instance_id` during background connection or reconnection. + +## PD-0012: TLS certificate fingerprint binding + +- Status: open before enabling pinned HTTPS Profiles +- Requirement: a certificate identity change freezes local-tool permission and the affected connection; TLS validation must never be disabled. +- Required decision: select a maintained Rust TLS integration that can inspect the validated peer certificate without installing a permissive verifier, and define first-contact confirmation UX. +- Safe interim rule: preserve validated HTTPS behavior and do not claim certificate pinning until the peer certificate path is implemented and tested. + +## 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. diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index c236918..579722e 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -1,74 +1,152 @@ -# Implementation Plan +# 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. -## P00 Bootstrap (completed) +## 2026-07-20 增量计划更新 -## 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 (active) - -### 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. +1. 启动时读取并校验自动连接 Profile。 +2. 按固定槽位独立激活 Rust-owned Runtime。 +3. 为失败槽位保留可诊断状态,不影响另一槽位。 +4. 补充检查结果并进入聊天运行时事件订阅。 diff --git a/docs/implementation-queue.md b/docs/implementation-queue.md new file mode 100644 index 0000000..d94259a --- /dev/null +++ b/docs/implementation-queue.md @@ -0,0 +1,202 @@ +# 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 窗口,初始尺寸适合快速回复。 +- 已完成:窗口单实例、拖动/调整大小、SQLite 几何状态持久化、屏幕工作区夹紧和显示器标识恢复。 +- 支持拖动、调整大小、关闭后恢复位置和尺寸。 +- 与主窗口共享 `ChatRuntime`、会话选择、消息缓存、未读数和发送队列。 +- 设置中只提供一个快速聊天目标:`companion` 或 `operations`,二选一。 +- 设置中提供气泡点击导向:主页面或快速聊天;不增加第三种导向模式。 +- 处理主窗口关闭到托盘、快速窗口关闭、单实例和窗口重启恢复。 +- 已修复:快捷窗口关闭按钮现在正常销毁窗口;主窗口仍保持关闭到托盘。 + +验收:从主窗口和快速窗口发送的消息进入同一会话;任一窗口关闭不影响连接和另一个窗口。 + +### Q5:状态气泡与托盘整合 + +- 增加非默认置顶的气泡窗口,显示连接状态、思考中、回复完成、错误和未读数。 +- 浮动桌宠窗口必须使用无装饰、跳过任务栏的后台窗口;主对话框关闭后应用继续由托盘驻留。 +- 已完成:修复气泡状态标签和无障碍名称的乱码,保持默认不置顶和设置导向逻辑不变。 +- 允许用户关闭气泡或切换到仅应用 UI 模式。 +- 气泡点击按设置打开主页面或快速聊天;右键菜单提供显示、隐藏、设置和退出。 +- 明确窗口层级、焦点、点击穿透(如需要)和屏幕边界策略。 +- 只在 Rust 窗口控制器中执行显示/隐藏/置顶,React 仅发出受限意图。 + +验收:气泡不默认置顶;两个槽位状态可区分;点击行为与设置一致;托盘隐藏主窗口后仍可恢复。 + +### Q6:桌宠基础模型与素材包 + +- 抽象 `CompanionState`:`idle`、`thinking`、`speaking`、`error`、 +otification`、`offline`。 +- 抽象 `PetRenderer`、`PetWindowController` 和 `PetInteractionPolicy`,先支持静态 PNG/WebP 和 spritesheet。 +- 定义可校验的 `pet-pack/manifest.json`,包含尺寸、动画帧、状态映射和可选点击动作。 +- 动作采用受限动画片段和状态机:待机、工作写字/看书、说话、通知、休息走动和错误状态;移动路径与渲染帧分离。 +- 支持应用内显示模式与全屏浮动模式的设置模型;浮动模式不占用任务栏、不默认置顶,首版接入 spritesheet 动画。 +- 上传素材只进入沙箱目录,校验格式、尺寸、文件大小和 manifest,不执行脚本或插件代码。 + +验收:可加载一个本地安全素材包并根据聊天状态切换静态状态;错误素材被拒绝且不影响主 UI。 + +### Q7:多显示器与游戏模式控制器 + +- Rust 获取显示器工作区、主屏/副屏标识、DPI 和任务栏边界,形成稳定的 `MonitorGeometry`。 +- 提供桌宠位置策略:自由、靠边、指定屏幕、跟随主窗口。 +- 游戏模式只做策略层:优先选择副屏,无法识别时选择非当前游戏窗口所在屏幕;宠物限制在边缘安全区。 +- 通过受限的窗口/进程检测判断前台游戏,不读取或注入游戏进程,不做鼠标键盘控制。 +- 增加双屏断开、DPI 变化、全屏游戏和窗口切换的回退策略。 + +验收:双屏场景下位置计算稳定;游戏模式不会把宠物放到游戏中心;权限不足时安全降级为应用内模式。 + +### Q8:语音、主动消息与游戏陪伴接入 + +- 在统一聊天运行时之上接入 STT/TTS,不为快速窗口或桌宠复制语音管线。 +- 必须支持 AstrBot Dashboard JWT 登录,并与 API Key / 设备 Token 作为并列认证方式,凭据统一存入 Windows Credential Manager。 +- 明确语音目标槽位,默认 Companion;Operations 需要显式切换。 +- 将主动消息映射为通知、气泡状态和未读数,并提供静默时段设置。 +- 游戏模式接入截图/状态摘要前,先完成授权提示、频率限制和隐私开关。 + +### Q9:稳定性、发布与验收 + +- 覆盖网络切换、SSE 重连、托盘驻留、窗口恢复、凭据失效和数据库迁移。 +- 完成日志脱敏、诊断包预览、崩溃恢复和更新流程。 +- 完成 Windows release/installer、签名、版本号、CHANGELOG 和阶段总结。 +- 通过全套阶段门槛后再进入主干合并和验收版本打包。 + +## 暂不进入实现 + +### 本轮已推进 + +- 远端身份已拆分为协议 ID(`remote_username`)与 BOT 称呼昵称(`remote_display_name`),两者不再共用字段。 +- 2D 纸片人桌宠已从 manifest 基础推进到可运行窗口:透明、无边框、跳过任务栏、关闭后回托盘,并预留状态动作循环。 +- JWT 运行时已支持 `exp` 过期识别、401/403 状态映射和聊天界面重新登录提示。 +- 桌宠窗口已接入双槽位运行状态:连接中工作、重连回应、断开休息、认证过期/致命错误提示。 +- 已接入 `aemeath_withclaude-2.0.8` 的 MIT 像素素材;保留来源署名,并将 spritesheet 动作行映射到当前桌宠状态。 + +- 不复制 Hermes 或 Codex 的私有实现;只参考交互模式和资源组织方式。 +- 不在首轮实现 Live2D、Spine、3D 桌宠或用户脚本插件。 +- 不实现任意 Shell、PowerShell、CMD、鼠标键盘控制。 +- 不把 AstrBot 的工具调用直接当成本机命令执行。 +- 不在没有真实附件协议验证前承诺文件上传;附件单独做 Spike。 + +## 需要用户后续接入 + +- 测试容器 API Key 轮换。 +- 真实双服务器或第二容器,用于两个不同 `server_instance_id` 的长期并行测试。 +- 最终确定 Companion/Operations 的远端用户名命名规则。 +- 首批桌宠素材或授权素材包;在此之前使用测试 PNG/WebP。 +- 如需 HTTPS 证书指纹绑定,提供可验证的 HTTPS 入口并确认首次信任交互。 + +## 2026-07-20 增量:启动自动连接 + +- 应用启动后由 Rust 读取已保存 Profile,仅处理 `auto_connect=true` 且绑定固定槽位的配置。 +- `companion` 与 `operations` 逐槽位独立尝试,不因一个 Profile 凭据缺失、认证失败或服务不可用而跳过另一个槽位。 +- API Key / Bearer Token 仍只在 Rust 启动任务和 Windows Credential Manager 之间流动;日志只记录 Profile、槽位和错误类别,不记录凭据或请求内容。 +- 启动任务复用现有双槽位 Runtime,不创建额外网络客户端或权限范围。 +- 当前仍未实现后台重连退避、JWT 登录和启动自动连接的前端可视化提示。 + + +## 2026-07-20??? 1-6 ???? + +???????????????? + +1. Q1 ?????????????????? +2. Q2 chat_sessions???????????? v6? +3. Q3 ???????????? +4. Q4 ??????????? +5. Q5 ????????? +6. Q6 ?? manifest ??????? + +??????????? Hook ?????????/??????????????????????????? + + +### Q3.1: Chat extensibility contract + +- Expose normalized AstrBot capability discovery through Rust-owned IPC. +- Expose model/provider configuration options as a slot-scoped selector; keep the server default when discovery is unavailable. +- Add a bounded 16 MiB multipart upload boundary at /api/v1/file; React receives only normalized attachment metadata. +- Carry optional configId and attachment metadata through the send request without exposing credentials or raw HTTP clients. +- Keep attachment wire mapping isolated in the AstrBot adapter so the internal chat runtime remains transport-neutral. + +Acceptance: the chat panel can discover model options, stage uploaded files, and submit a normalized message request; real server response-shape compatibility remains verified by the supplied AstrBot containers before claiming end-to-end multimodal support. + + +### Q3.2: Remote session navigation + +- Expose the active AstrBot session list through the slot runtime without creating a second network client. +- Allow switching the sticky session ID inside one slot and reload only that session history. +- Keep message identity scoped by slot and session ID so switching sessions cannot mix content. + +Acceptance: a connected slot can display remote sessions and switch between them without affecting the other slot. diff --git a/docs/progress.md b/docs/progress.md index 9b410b4..371f775 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -1,81 +1,254 @@ -# 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. -## Current phase +## 2026-07-20: remote identity and runnable paper pet increment -P01 foundation is complete and published on `feat/p01-foundation`. The option A boundary is resolved: basic non-sensitive Profile metadata CRUD belongs to P01, while slots and runtime connection behavior remain in P02. +- Added `remote_display_name` as a separate user-facing nickname; `remote_username` remains the validated ASCII protocol ID used for AstrBot session isolation. +- Migrated SQLite profiles to schema v9 without changing existing IDs or credentials. +- Passed the nickname through the Rust-owned AstrBot request boundary as an optional `nickname` field; secrets remain Rust-only. +- Added a transparent, borderless, skip-taskbar pet window with tray-resident hide-on-close behavior and a small CSS 2D paper-character state loop. +- Frontend checks pass; Rust test/build gate remains to be rerun after the final patch. + + +## 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. + + +## Autonomous queue increment + +Completed in this increment: + +- 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. + +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. + +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. + +## 2026-07-20:Q1 启动自动连接增量 + +- 已完成:在 Tauri 启动阶段读取已保存的 `auto_connect` Profile,并按 Companion / Operations 槽位独立激活。 +- 已完成:启动失败保留在对应 Runtime 状态,不阻断另一槽位;凭据仍由 Rust 读取,React 不接触秘密值。 +- 已完成:启动自动连接复用现有 AstrBot OpenAPI 与 Desktop Gateway 激活路径。 +- 验证:`cargo check --workspace --all-targets`、`cargo test --workspace`(59 项通过)、`cargo clippy --workspace --all-targets -- -D warnings`、`pnpm.cmd run typecheck` 通过。 +- 未完成:前端启动连接状态提示、自动重连退避、JWT 登录、聊天布局和快速窗口共享状态完善。 +- 当前工作区:本地未提交,等待下一项 Q1/Q2 增量完成后按用户指令提交。 + + +## 2026-07-20??? 1-6 ?????? + +- Q1???????????????????????????? +- Q2??? SQLite schema v6 ???????????????????????60 ? Rust ????? +- Q3?????????????/????/?????????????? Hook ????? +- Q4???????????????? URL ??? +- Q5????????????/???????????????????????????? +- Q6????? JSON manifest ???? UI?????????????PNG/WebP ?????????????? +- ?????`2e84ea5`?`5dfac59`?`e0b48c0`?`9f235a3`?`4f13581`?`1828c61` ???? Forgejo? -## Completed +## 2026-07-20?????????? -- 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. +- ????????????????????????????????????? +- ????????????????/????/???????????? +- ??????????????????????????????????????????? +- ??????????????/?????????????????? Windows ????? +- ?????TypeScript?ESLint?Vitest 6/6?Vite production build ??? -## In progress -- No code implementation is in progress; the branch is awaiting Forgejo PR review. +## 2026-07-20: chat extensibility contract -## Remaining +- Added Rust-owned AstrBot capability discovery, model configuration options, and slot-scoped IPC. +- Added a bounded 16 MiB multipart upload boundary and normalized attachment metadata. +- Extended chat send requests with optional configId and attachments; the existing dual-slot isolation remains the authority. +- Updated ChatPanel with model selection, attachment staging, upload state, and clean WebChat-style text labels. +- Validation: Rust workspace tests 60 passed; Vitest 6/6 passed; TypeScript, ESLint, cargo check, and Vite build passed. -- Create and review the P01 Forgejo PR; do not automatically merge `main`. -- 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 +## 2026-07-20: live chat extensibility probe -- 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. -- No blocker remains for the selected P01 scope. +- Both supplied containers returned status=ok for chat sessions and config discovery. +- Container 1 accepted a minimal multipart upload and returned attachment_id, filename, and type. +- No chat message or configuration mutation was performed. Full multimodal rendering remains reserved for an explicit send-message acceptance test. -## Test status -- `npm run check:frontend`: passed; Prettier, ESLint, TypeScript, 3 Vitest tests, and Vite production build. -- `npm run test:e2e`: passed; 1 Chromium smoke test. -- Rust fmt/check/Clippy with warnings denied: passed. -- `cargo test --workspace`: passed; 50 normal tests, 2 explicit manual tests ignored. -- Profile persistence: passed; five Profile CRUD, close/reopen persistence, and v1-to-v2 migration preserve existing messages. -- Secret boundary: passed; unknown Token, password, and API Key input fields are rejected. -- Protocol Schema export: passed; no generated drift. -- Tauri development startup: passed; executable launched, then was deliberately terminated after verification. -- Tauri Windows release executable: passed. -- NSIS installer: passed; `0.1.0-alpha.1`, 3,827,899 bytes. -- NSIS SHA-256: `90EB68CDB5EAEDEA675050DA0F30DDAB5E8A0345FF176690A31FA5F66C818740`. -- Forgejo CI and a real UNC transaction were not executed and are not claimed successful. +## 2026-07-20: live end-to-end chat acceptance -## Current branch +- First test container accepted text plus config selection and streamed a complete response with no error frame. +- The same session accepted text plus config selection plus the uploaded attachment and streamed a complete response with no error frame. +- This validates the current model/config and attachment request contract against a real AstrBot instance. -`feat/p01-foundation` -## Recent commits +## 2026-07-20: remote session navigation -- `b3420e4 Merge pull request 'feat(p00): bootstrap Tauri desktop and validate high-risk spikes' (#1)` -- `ed74342 feat(foundation): add persistent bootstrap safeguards` -- `6a1eeab docs(p01): record foundation progress and profile boundary` -- `02fd25a feat(profile): add secure profile persistence and IPC` -- `907a8a3 feat(profile-ui): add basic profile management` -- `5672585 chore(version): set P01 alpha version` -- `2154c3b docs(p01): resolve profile boundary and record verification` +- Added slot-scoped remote session discovery and sticky session switching IPC. +- ChatPanel now displays remote sessions and reloads history after switching; message filtering includes sessionId. +- Validation: Rust workspace tests, Clippy, TypeScript, ESLint, Vitest, and Vite build passed. -## Next step +## 2026-07-20: Q4 quick-chat window geometry persistence -Open `feat/p01-foundation → main` as a Forgejo PR, review the recorded local verification, and run CI only when a compatible runner is available. +- Completed: added the `window_states` SQLite table (schema v7) for quick-chat position, size, and monitor identity. +- Completed: restore geometry on open; fall back to the current primary monitor and clamp to its work area when a monitor is unavailable or the saved position is invalid. +- Completed: save geometry on move, resize, and close-to-tray; keep the quick window single-instance without destroying the shared chat runtime. +- Completed: added window bounds, monitor clamping, and database round-trip tests. +- Validation: Rust format, Clippy with warnings denied, and `astrbot-desktop` unit tests pass. +- Next: finish the remaining quick-window/status-bubble acceptance work, then continue with the pet asset and multi-monitor controller foundation. +## 2026-07-20: status bubble text cleanup + +- Fixed the remaining mojibake in status-bubble state labels and accessibility text. +- Validation: TypeScript, ESLint, and Vitest (6 tests) pass. +## 2026-07-20: quick-chat close behavior fix + +- Fixed the global close handler so the quick-chat window can be closed normally instead of being intercepted and only hidden. +- The main window keeps the existing tray behavior; quick-chat geometry is saved before destruction and restored when reopened. +- Validation: Rust Clippy and `astrbot-desktop` unit tests (64) pass. + +## 2026-07-20: JWT profile and 2D paper pet foundation + +- Added JWT as a persisted connection authentication type alongside API Key and device token; SQLite schema is now v8 and migrates existing profiles without losing slot assignments. +- Added remote ID validation: 3-32 ASCII letters or digits; the ID remains separate from the user-facing nickname field planned for the profile UI. +- Extended the pet-pack manifest with optional animation IDs, loop flags, and bounded movement modes for 2D paper-character actions. +- Updated the pet importer copy and JWT selection UI; full Dashboard login, JWT expiry handling, and background pet window controller remain next-stage work. +- Validation: Rust workspace tests, TypeScript, ESLint, Vitest (6), and Vite production build pass. + +## 2026-07-20: JWT login IPC + +- Added a Rust-owned login_profile_jwt command for AstrBot Dashboard login at /api/v1/auth/login. +- Dashboard username, password, and optional TOTP stay inside Rust; successful JWTs are written to Windows Credential Manager and the Profile is switched to JWT authentication. +- Added Profile UI fields for JWT login and retained API Key/device-token enrollment for non-JWT profiles. +- Full JWT expiry/401 re-login UX and nickname/remote-ID separation remain next increments. + +## 2026-07-20: JWT runtime expiry handling + +- AstrBot JWT profiles now pass their authentication type through the Rust runtime instead of being treated as API Key-only profiles. +- Rust checks the JWT `exp` claim before activation and maps expired credentials to `AuthExpired` without logging or returning the token. +- AstrBot 401/403 responses during probe or chat now preserve the affected slot and expose an `authExpired` runtime error. +- Chat UI shows a re-login warning for the affected slot; credentials remain managed by Windows Credential Manager. +- The floating 2D pet now polls the dual-slot runtime and switches between idle, work, reply, rest, and error states instead of running an isolated demo loop. + +## 2026-07-20: Aemeath pixel sprite integration + +- Reviewed `aemeath_withclaude-2.0.8`; the supplied repository and referenced pixel asset are MIT-licensed, not CC-licensed. +- Added the original 8-column, 192x208-frame WebP spritesheet as a project-local pet asset with preserved attribution. +- Added a validated pet manifest and mapped the source animation rows into idle, thinking, speaking, notification, error, and offline states. +- Replaced the CSS placeholder character in the floating pet view with the real pixel spritesheet renderer. +- Validation: Rust workspace tests (65), Clippy, TypeScript, ESLint, Vitest (6), and Vite build pass. + +## 2026-07-20: production pet renderer white-window fix + +- Replaced the floating pet CSS background-image crop with a clipped `` spritesheet renderer for more reliable WebView2/asset-protocol loading. +- Added explicit pet-view root sizing and transparent `html`/`body`/`#root` backgrounds so Tauri transparent windows do not fall back to an opaque blank surface. +- Validation: TypeScript, ESLint, Vitest (6), Vite build, Rust format, Clippy with warnings denied, Rust workspace tests (66), and NSIS bundle build pass. +- The already-running executable must be fully closed and relaunched; the generated installer is at `target/release/bundle/nsis/AstrBot Desktop_0.1.0-alpha.1_x64-setup.exe`. + +## 2026-07-20: tray quit reliability fix + +- Fixed the tray Quit action so it destroys the main, quick-chat, status-bubble, and pet windows before requesting process exit. +- This avoids the global close-to-tray handler intercepting shutdown and leaving the process resident. +- Validation: Rust format, Clippy with warnings denied, Rust workspace tests (66), TypeScript, ESLint, Vitest (6), and NSIS bundle build pass. + +## 2026-07-20: desktop pet rendering and tray exit follow-up + +- Fixed the pixel spritesheet crop by setting the sprite image transform origin to the top-left; the previous default center origin moved the selected frame outside the clipped viewport and produced a blank transparent pet window. +- Added an application exiting state so tray Quit allows all windows to close instead of the global close-to-tray handler hiding them and leaving an empty, non-interactive placeholder. +- Validation: frontend typecheck, Vitest (6), Vite production build, Rust format, Rust check, and Rust workspace tests (66) pass. + +## 2026-07-20: transparent pet and tray process exit hardening + +- Replaced the transparent-window spritesheet crop with a PNG-backed Canvas renderer; this avoids WebView2 transparent-window failures with the large WebP image and CSS transform cropping. +- Changed tray Quit to call Tauri cleanup and terminate the process immediately, ensuring the tray icon, hidden main window, and pet window cannot remain as orphaned UI surfaces. +- Rebuilt and launched the Release executable at 18:24:20 for manual verification. + +## 2026-07-20: wire pet display mode and render diagnostics + +- Connected the pet display-mode setting to persisted local UI state; `app-ui` now embeds the pet in the Pet page, while `desktop-floating` explicitly opens the transparent Tauri window. +- Added sprite loading and Canvas failure feedback instead of leaving a silent blank/white surface. +- Validation: TypeScript, Vitest (6), Vite build, Rust format/check, and Release bundle build pass. The rebuilt executable started at 18:35:29. + +## 2026-07-20: in-app draggable pet overlay + +- Promoted the app-ui pet from a static page preview to an application-level floating overlay, matching the Codex/Hermes-style in-window companion behavior. +- Added pointer dragging with clamped coordinates and local persistence; the overlay can be hidden without creating a native desktop window. +- Disabled the broken desktop-floating launch path in the Pet settings and provided a direct switch back to the in-app mode. +- Validation: TypeScript, Vitest (6), Vite build, Rust format/check, and Release bundle build pass. The rebuilt executable started at 18:44:43. + +## 2026-07-20: restore desktop floating pet transparency + +- Restored the desktop-floating display option and its `open_pet_window` action; it is no longer disabled. +- Fixed the Windows transparent WebView configuration by explicitly setting an RGBA-zero background and disabling undecorated window shadow, which could otherwise render a white rectangle around the pet. +- Preserved the app-ui draggable overlay implementation. +- Validation: TypeScript, Vitest (6), Rust format/check, Vite build, and Release bundle build pass. The rebuilt executable started at 18:50:25. diff --git a/docs/protocol/v1/README.md b/docs/protocol/v1/README.md index e1cc330..673a7eb 100644 --- a/docs/protocol/v1/README.md +++ b/docs/protocol/v1/README.md @@ -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. diff --git a/docs/protocol/v1/schemas/connection-profile.schema.json b/docs/protocol/v1/schemas/connection-profile.schema.json index 30e8cf7..3c6661e 100644 --- a/docs/protocol/v1/schemas/connection-profile.schema.json +++ b/docs/protocol/v1/schemas/connection-profile.schema.json @@ -18,9 +18,25 @@ "AuthenticationType": { "enum": [ "device-token", - "api-key" + "api-key", + "jwt" ], "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 +111,13 @@ "null" ] }, + "remoteUsername": { + "description": "AstrBot WebChat username / session owner used by OpenAPI chat.", + "type": [ + "string", + "null" + ] + }, "role": { "$ref": "#/$defs/AstrBotProfileRole" }, @@ -110,6 +133,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" } diff --git a/docs/reports/astrbot-chat-extensibility-probe-2026-07-20.md b/docs/reports/astrbot-chat-extensibility-probe-2026-07-20.md new file mode 100644 index 0000000..999d9c9 --- /dev/null +++ b/docs/reports/astrbot-chat-extensibility-probe-2026-07-20.md @@ -0,0 +1,38 @@ +# AstrBot chat extensibility probe + +Date: 2026-07-20 + +## Scope + +Non-destructive connectivity and response-shape verification for the two supplied AstrBot test containers. API keys and complete response bodies are intentionally omitted. No chat message was sent and no configuration was changed. + +## Results + +| Target | Sessions | Configs | File upload | +| --- | --- | --- | --- | +| Container 1 (:26285) | status=ok; existing webchat session returned | status=ok; one default config | POST /api/v1/file returned status=ok and an attachment_id | +| Container 2 (:26385) | status=ok; no sessions for the probe username | status=ok; config list returned | not uploaded during this probe | + +## Upload response shape + +The first container returned an envelope with these data keys: + +- attachment_id +- filename +- type + +The adapter already accepts attachment_id and preserves the client-side filename, MIME type, and byte size in normalized attachment metadata. + +## Implementation consequence + +The current capability and upload IPC contract matches the observed response shape. Model selection is represented by AstrBot config IDs; the first container exposes the default config and the second exposes a named workflow config. End-to-end image rendering and model behavior still require a real chat send with a user-approved test message. + + +## End-to-end send test + +Using the first container and the default config ID, two request-scoped SSE sends were completed: + +- Text plus config selection: HTTP 200; session_id, user_message_saved, 4 plain frames, complete; no error frame. +- Text plus config selection plus the previously uploaded attachment: HTTP 200; session_id, user_message_saved, 5 plain frames, complete; no error frame. + +This confirms the current configId and attachment request shape is accepted by the tested AstrBot instance. The test messages were intentionally limited to interface confirmation and did not request tools or configuration changes. diff --git a/docs/reports/astrbot-dual-stability-2026-07-20.md b/docs/reports/astrbot-dual-stability-2026-07-20.md new file mode 100644 index 0000000..d64ca54 --- /dev/null +++ b/docs/reports/astrbot-dual-stability-2026-07-20.md @@ -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 未写入本报告;测试密钥仍建议在验收前轮换。 diff --git a/docs/reports/astrbot-live-probe-sse.raw.txt b/docs/reports/astrbot-live-probe-sse.raw.txt new file mode 100644 index 0000000..12e6145 --- /dev/null +++ b/docs/reports/astrbot-live-probe-sse.raw.txt @@ -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}} + diff --git a/docs/reports/astrbot-live-probe-summary.json b/docs/reports/astrbot-live-probe-summary.json new file mode 100644 index 0000000..3ecab32 --- /dev/null +++ b/docs/reports/astrbot-live-probe-summary.json @@ -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 + } + } +} diff --git a/docs/reports/astrbot-real-protocol-review.md b/docs/reports/astrbot-real-protocol-review.md new file mode 100644 index 0000000..b2b244e --- /dev/null +++ b/docs/reports/astrbot-real-protocol-review.md @@ -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://:6185/api/v1/docs` +- OpenAPI schema: `http://:6185/api/v1/openapi.json` + +### Authentication (two valid modes) + +| Mode | How presented | Intended use | Notes | +| --- | --- | --- | --- | +| Dashboard JWT | `Authorization: Bearer ` 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 `, 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": "", + "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 diff --git a/docs/reports/p02-dual-slots-handoff.md b/docs/reports/p02-dual-slots-handoff.md new file mode 100644 index 0000000..08fc943 --- /dev/null +++ b/docs/reports/p02-dual-slots-handoff.md @@ -0,0 +1,80 @@ +# P02 dual-slot checkpoint and handoff + +Date: 2026-07-19 + +## Source state + +- Branch: `feat/p02-dual-connections` +- Base merge: `885abd1553ed8f1428de7118a6f4b59f7e22a45c` +- Planning commit: `73693b9 docs(p02): start dual connection phase` +- Feature commit: `bcc08cf feat(connection): add persistent dual slot assignment` +- Remote transport: approved ordinary Forgejo HTTP push +- Force push, rebase, and automatic main merge: not used + +## Completed scope + +- SQLite schema v3 creates exactly two fixed rows: `companion` and `operations`. +- A foreign key clears slot assignment when a Profile is deleted. +- A unique Profile constraint prevents one Profile from occupying both slots. +- Rust exposes bounded list, assign, and clear commands. +- Slot requests reject unknown fields, malformed Profile IDs, missing Profiles, and duplicate cross-slot assignment. +- The frontend validates Rust payloads with strict Zod Schemas. +- The settings UI assigns or clears Profiles without activating REST/SSE or reading credentials. +- Stored `server_instance_id` is displayed as metadata only; the increment does not enroll or silently replace server identity. + +## Security boundary + +- No Token, password, API Key, Cookie, Authorization header, or NAS credential field was added to slot IPC. +- Slot assignment alone grants no local-tool permission. +- React does not receive stored credentials. +- Real Gateway compatibility, token refresh, identity enrollment, and certificate pinning remain explicitly unresolved in PD-0009 through PD-0012. + +## Verification + +- `npm.cmd --prefix H:\AstrBot-Desktop run check:frontend`: passed. + - Prettier: passed. + - ESLint: passed. + - TypeScript: passed. + - Vitest: 4 passed. + - Vite production build: passed. +- `npm.cmd --prefix H:\AstrBot-Desktop run test:e2e`: passed, Chromium 1/1. +- `cargo fmt --all --manifest-path H:\AstrBot-Desktop\Cargo.toml -- --check`: passed. +- `cargo clippy --workspace --all-targets --manifest-path H:\AstrBot-Desktop\Cargo.toml -- -D warnings`: passed. +- `cargo check --workspace --all-targets --manifest-path H:\AstrBot-Desktop\Cargo.toml`: passed. +- `cargo test --workspace --manifest-path H:\AstrBot-Desktop\Cargo.toml`: passed, 56 normal tests and 2 explicit manual tests ignored. +- Changed-file high-risk secret pattern scan: passed with no matches. + +Not rerun at this incremental checkpoint: + +- real Tauri development startup; +- Windows release or NSIS build; +- Forgejo Actions; +- real AstrBot Gateway compatibility; +- real UNC file transaction. + +No success is claimed for the items above. + +## Remaining P02 work + +1. Add auto-connect validation for at most two Profiles and one Profile per slot. +2. Block Operations Profile switching while an operations task is active. +3. Add duplicate `server_instance_id` warnings without silent identity merging. +4. Resolve the credential enrollment and rotation lifecycle. +5. Resolve first-contact server identity confirmation. +6. Implement validated certificate fingerprint binding without disabling TLS verification. +7. Only then enable two independent configured REST/SSE runtimes and Mock-backed failure tests. + +## Handoff status + +The first controller status call failed before project lookup because the global dev-handoff config references missing files: + +- identity file: `C:\Users\Administrator\Documents\Codex\2026-07-14\ke\work\ssh\astrbot_vm_ed25519` +- known-hosts file: `C:\Users\Administrator\Documents\Codex\2026-07-14\ke\work\ssh\known_hosts` + +The controller also reported host-key verification failure. No handoff ID, VM workspace, branch, or HAPI session has been created or claimed. + +After the source branch was clean and pushed, the formal `dev-handoff send --approve` call was also attempted with the verified test and secret-scan results. It failed before task creation with the same missing identity and host-key verification error. + +## Next concrete step + +Restore or reconfigure the authorized VM SSH identity and known-hosts paths, rerun `dev-handoff status`, then send this exact pushed checkpoint to `vm-codex`. If the controller stops at `ready_to_accept`, report that state honestly and wait for the VM worker. diff --git a/docs/reports/p02-policy-guards.md b/docs/reports/p02-policy-guards.md new file mode 100644 index 0000000..869fa57 --- /dev/null +++ b/docs/reports/p02-policy-guards.md @@ -0,0 +1,48 @@ +# P02 policy and operations-switch increment + +Date: 2026-07-20 + +## Source state + +- Branch: `feat/p02-dual-connections` +- Base feature commit: `bcc08cf feat(connection): add persistent dual slot assignment` +- Scope: auto-connect validation, operations switch protection, duplicate server-instance warnings + +## Completed scope + +- Profile create/update accepts non-secret `autoConnect` and `autoConnectSlot`. +- Auto-connect rules: auto-connect requires a slot; no slot when auto-connect is false; at most two auto-connect Profiles; distinct slots. +- `RuntimeGuards` tracks in-process operations tasks and locks operations slot assign/clear while any task remains. +- Companion slot remains mutable while operations work is active. +- Duplicate `server_instance_id` values surface as warnings only; Profiles stay separate. +- `connection_policy_status` returns lock status, active task count, and warnings. +- Profile UI shows auto-connect controls, operations lock messaging, and duplicate-instance banners. + +## Security boundary + +- No Token, password, API Key, Cookie, Authorization header, or NAS credential field was added. +- Auto-connect configuration does not open REST/SSE sessions in this increment. +- Operations begin/end task controls are not exposed as product IPC yet. +- Slot assignment still grants no local-tool permission. +- PD-0009 through PD-0012 remain unresolved; real Gateway activation is not claimed. + +## Verification + +- Frontend Prettier, ESLint, TypeScript, 6 Vitest tests, and Vite production build: passed. +- Playwright Chromium: passed 1/1. +- Rust fmt and Clippy (`-D warnings`): passed. +- `cargo test --workspace`: passed; 63 normal tests, 2 ignored. +- `cargo check --workspace --all-targets`: passed. +- Changed-file secret scan: passed. + +Not rerun for this checkpoint: + +- real Tauri development startup; +- Windows release or NSIS build; +- Forgejo Actions; +- real AstrBot Gateway compatibility; +- real UNC file transaction. + +## Next concrete step + +Implement formal credential enrollment/update/delete entirely in Rust with opaque references only. diff --git a/docs/reports/run-live-probe.ps1 b/docs/reports/run-live-probe.ps1 new file mode 100644 index 0000000..1a5a5b1 --- /dev/null +++ b/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" diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index e60f440..07049f1 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -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"] } diff --git a/src-tauri/src/auth.rs b/src-tauri/src/auth.rs new file mode 100644 index 0000000..3971b98 --- /dev/null +++ b/src-tauri/src/auth.rs @@ -0,0 +1,215 @@ +use desktop_protocol::AuthenticationType; +use reqwest::StatusCode; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use time::{OffsetDateTime, format_description::well_known::Rfc3339}; +use uuid::Uuid; + +use crate::database::{ApplicationDatabase, DatabaseError}; +use crate::secure_store::{ + CredentialReference, SecretCredential, SecureCredentialStore, WindowsCredentialStore, +}; + +#[derive(Clone, Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct JwtLoginRequest { + pub profile_id: String, + pub username: String, + pub password: String, + #[serde(default)] + pub totp: Option, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct JwtLoginResult { + pub profile_id: String, + pub credential_reference: String, + pub dashboard_username: String, + pub authentication_type: AuthenticationType, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct JwtLoginError { + pub code: &'static str, + pub message: &'static str, +} + +impl JwtLoginError { + fn validation(message: &'static str) -> Self { + Self { + code: "validationFailed", + message, + } + } + fn network() -> Self { + Self { + code: "networkError", + message: "AstrBot login request failed.", + } + } + fn rejected() -> Self { + Self { + code: "loginRejected", + message: "AstrBot rejected the login credentials.", + } + } + fn response() -> Self { + Self { + code: "invalidResponse", + message: "AstrBot returned an invalid login response.", + } + } + fn database() -> Self { + Self { + code: "databaseUnavailable", + message: "The local profile database is unavailable.", + } + } + fn store() -> Self { + Self { + code: "secureStoreUnavailable", + message: "Windows Credential Manager is unavailable.", + } + } + fn not_found() -> Self { + Self { + code: "notFound", + message: "The connection profile no longer exists.", + } + } +} + +impl std::fmt::Display for JwtLoginError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(self.message) + } +} +impl std::error::Error for JwtLoginError {} + +#[tauri::command] +pub async fn login_profile_jwt( + database: tauri::State<'_, ApplicationDatabase>, + request: JwtLoginRequest, +) -> Result { + login_jwt(&database, &WindowsCredentialStore, request).await +} + +async fn login_jwt( + database: &ApplicationDatabase, + store: &impl SecureCredentialStore, + request: JwtLoginRequest, +) -> Result { + if Uuid::parse_str(&request.profile_id).is_err() { + return Err(JwtLoginError::validation("profile_id must be a UUID.")); + } + if request.username.trim().is_empty() || request.username.len() > 256 { + return Err(JwtLoginError::validation("dashboard username is invalid.")); + } + if request.password.is_empty() || request.password.len() > 1024 { + return Err(JwtLoginError::validation("dashboard password is invalid.")); + } + if request + .totp + .as_deref() + .is_some_and(|value| value.len() > 128) + { + return Err(JwtLoginError::validation("TOTP value is invalid.")); + } + + let profile = database + .profile(&request.profile_id) + .map_err(|_| JwtLoginError::database())? + .ok_or_else(JwtLoginError::not_found)?; + let base_url = profile.base_url.trim_end_matches('/'); + let mut payload = serde_json::json!({ + "username": request.username.trim(), + "password": request.password, + }); + if let Some(totp) = request + .totp + .as_deref() + .filter(|value| !value.trim().is_empty()) + { + payload["totp"] = Value::String(totp.trim().to_owned()); + } + + let response = reqwest::Client::builder() + .connect_timeout(std::time::Duration::from_secs(5)) + .timeout(std::time::Duration::from_secs(20)) + .build() + .map_err(|_| JwtLoginError::network())? + .post(format!("{base_url}/api/v1/auth/login")) + .json(&payload) + .send() + .await + .map_err(|_| JwtLoginError::network())?; + if response.status() == StatusCode::UNAUTHORIZED || response.status() == StatusCode::FORBIDDEN { + return Err(JwtLoginError::rejected()); + } + if !response.status().is_success() { + return Err(JwtLoginError::network()); + } + let body: Value = response + .json() + .await + .map_err(|_| JwtLoginError::response())?; + let token = body + .get("data") + .and_then(|data| data.get("token")) + .and_then(Value::as_str) + .or_else(|| body.get("token").and_then(Value::as_str)) + .filter(|value| !value.trim().is_empty()) + .ok_or_else(JwtLoginError::response)?; + if token.len() > 2_560 { + return Err(JwtLoginError::response()); + } + + let reference = CredentialReference::new(); + let credential = SecretCredential::with_username( + Some(request.username.trim().to_owned()), + token.as_bytes().to_vec(), + ) + .map_err(|_| JwtLoginError::store())?; + store + .write(reference, &credential) + .map_err(|_| JwtLoginError::store())?; + + let mut updated = profile; + if let Some(previous) = updated + .credential_reference + .as_ref() + .and_then(|value| Uuid::parse_str(value).ok()) + .map(CredentialReference::from_uuid) + { + let _ = store.delete(previous); + } + updated.credential_reference = Some(reference.as_uuid().to_string()); + updated.authentication_type = AuthenticationType::Jwt; + updated.updated_at = OffsetDateTime::now_utc() + .format(&Rfc3339) + .map_err(|_| JwtLoginError::database())?; + database + .update_profile(&updated) + .map_err(|error| match error { + DatabaseError::ProfileNotFound => JwtLoginError::not_found(), + _ => JwtLoginError::database(), + })?; + + Ok(JwtLoginResult { + profile_id: updated.id, + credential_reference: reference.as_uuid().to_string(), + dashboard_username: request.username.trim().to_owned(), + authentication_type: AuthenticationType::Jwt, + }) +} + +#[cfg(test)] +mod tests { + #[test] + fn extracts_token_from_nested_response() { + let body = serde_json::json!({ "status": "ok", "data": { "token": "jwt-value" } }); + assert_eq!(body["data"]["token"].as_str(), Some("jwt-value")); + } +} diff --git a/src-tauri/src/credentials/mod.rs b/src-tauri/src/credentials/mod.rs new file mode 100644 index 0000000..cf6237c --- /dev/null +++ b/src-tauri/src/credentials/mod.rs @@ -0,0 +1,363 @@ +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, +} + +#[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 { + 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 { + 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, 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, Vec); + + #[derive(Default)] + struct MemoryStore { + values: Mutex>, + } + + 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, 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 { + 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, + remote_display_name: 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"); + } +} diff --git a/src-tauri/src/database/mod.rs b/src-tauri/src/database/mod.rs index f837138..24ce20f 100644 --- a/src-tauri/src/database/mod.rs +++ b/src-tauri/src/database/mod.rs @@ -1,11 +1,13 @@ 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 = 2; +pub const CURRENT_SCHEMA_VERSION: u32 = 9; pub struct ApplicationDatabase { store: Mutex, @@ -31,6 +33,95 @@ 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_sessions( + &self, + profile_id: &str, + server_instance_id: &str, + ) -> Result, DatabaseError> { + self.store + .lock() + .map_err(|_| DatabaseError::LockPoisoned)? + .list_chat_sessions(profile_id, server_instance_id) + } + + pub fn mark_chat_session_read( + &self, + profile_id: &str, + server_instance_id: &str, + session_id: &str, + ) -> Result<(), DatabaseError> { + self.store + .lock() + .map_err(|_| DatabaseError::LockPoisoned)? + .mark_chat_session_read(profile_id, server_instance_id, session_id) + } + + pub fn list_chat_messages( + &self, + profile_id: &str, + server_instance_id: &str, + session_id: &str, + limit: usize, + ) -> Result, DatabaseError> { + self.store + .lock() + .map_err(|_| DatabaseError::LockPoisoned)? + .list_chat_messages(profile_id, server_instance_id, session_id, limit) + } + pub fn load_window_state( + &self, + window_id: &str, + ) -> Result, DatabaseError> { + self.store + .lock() + .map_err(|_| DatabaseError::LockPoisoned)? + .load_window_state(window_id) + } + + pub fn save_window_state( + &self, + window_id: &str, + state: &crate::quick_window::QuickWindowState, + ) -> Result<(), DatabaseError> { + self.store + .lock() + .map_err(|_| DatabaseError::LockPoisoned)? + .save_window_state(window_id, state) + } } pub struct ProfileMessageStore { @@ -38,6 +129,83 @@ pub struct ProfileMessageStore { } impl ProfileMessageStore { + pub fn load_window_state( + &self, + window_id: &str, + ) -> Result, DatabaseError> { + self.connection + .query_row( + "SELECT x, y, width, height, monitor_name FROM window_states WHERE window_id = ?1", + params![window_id], + |row| { + Ok(crate::quick_window::QuickWindowState { + x: row.get(0)?, + y: row.get(1)?, + width: row.get::<_, i64>(2)? as u32, + height: row.get::<_, i64>(3)? as u32, + monitor_name: row.get(4)?, + }) + }, + ) + .optional() + .map_err(DatabaseError::from) + } + + pub fn save_window_state( + &self, + window_id: &str, + state: &crate::quick_window::QuickWindowState, + ) -> Result<(), DatabaseError> { + let updated_at = OffsetDateTime::now_utc() + .format(&Rfc3339) + .map_err(|_| DatabaseError::InvalidStoredMessage)?; + self.connection.execute( + "INSERT INTO window_states (window_id, x, y, width, height, monitor_name, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) ON CONFLICT(window_id) DO UPDATE SET x = excluded.x, y = excluded.y, width = excluded.width, height = excluded.height, monitor_name = excluded.monitor_name, updated_at = excluded.updated_at", + params![ + window_id, + state.x, + state.y, + state.width, + state.height, + state.monitor_name, + updated_at, + ], + )?; + Ok(()) + } + pub fn list_chat_sessions( + &self, + profile_id: &str, + server_instance_id: &str, + ) -> Result, DatabaseError> { + let mut statement = self.connection.prepare("SELECT account_id, profile_id, slot, server_instance_id, remote_username, session_id, unread_count, last_message_id, last_message_at FROM chat_sessions WHERE profile_id = ?1 AND server_instance_id = ?2 ORDER BY last_message_at DESC")?; + let rows = statement.query_map(params![profile_id, server_instance_id], |row| { + Ok(StoredChatSession { + 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)?, + unread_count: row.get::<_, i64>(6)? as u32, + last_message_id: row.get(7)?, + last_message_at: row.get(8)?, + }) + })?; + rows.collect::, _>>() + .map_err(DatabaseError::from) + } + + pub fn mark_chat_session_read( + &self, + profile_id: &str, + server_instance_id: &str, + session_id: &str, + ) -> Result<(), DatabaseError> { + self.connection.execute("UPDATE chat_sessions SET unread_count = 0 WHERE profile_id = ?1 AND server_instance_id = ?2 AND session_id = ?3", params![profile_id, server_instance_id, session_id])?; + Ok(()) + } + pub fn open(path: impl AsRef) -> Result { Self::from_connection(Connection::open(path)?, true) } @@ -90,6 +258,76 @@ 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)?; + let was_streaming: Option = self + .connection + .query_row( + "SELECT streaming != 0 FROM chat_messages WHERE profile_id = ?1 AND server_instance_id = ?2 AND session_id = ?3 AND message_id = ?4", + params![profile_id, server_instance_id, session_id, message_id], + |row| row.get(0), + ) + .optional()?; + 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], + )?; + let unread = role != "user" && !streaming && !error && was_streaming != Some(false); + self.connection.execute( + "INSERT INTO chat_sessions (account_id, profile_id, slot, server_instance_id, remote_username, session_id, unread_count, last_message_id, last_message_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9) ON CONFLICT(account_id, profile_id, slot, server_instance_id, session_id) DO UPDATE SET remote_username = COALESCE(excluded.remote_username, chat_sessions.remote_username), unread_count = chat_sessions.unread_count + CASE WHEN ?10 = 1 THEN 1 ELSE 0 END, last_message_id = excluded.last_message_id, last_message_at = excluded.last_message_at", + params![account_id, profile_id, slot, server_instance_id, remote_username, session_id, if unread { 1 } else { 0 }, message_id, timestamp, if unread { 1 } else { 0 }], + )?; + Ok(()) + } + + pub fn list_chat_messages( + &self, + profile_id: &str, + server_instance_id: &str, + session_id: &str, + limit: usize, + ) -> Result, 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::, _>>() + .map_err(DatabaseError::from) + } + pub fn message_content( &self, profile_id: &str, @@ -115,6 +353,37 @@ 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, + pub session_id: String, + pub message_id: String, + pub role: String, + pub content: String, + pub streaming: bool, + pub error: bool, + pub updated_at: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct StoredChatSession { + pub account_id: String, + pub profile_id: String, + pub slot: String, + pub server_instance_id: String, + pub remote_username: Option, + pub session_id: String, + pub unread_count: u32, + pub last_message_id: Option, + pub last_message_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))?; @@ -162,7 +431,7 @@ fn migrate(connection: &mut Connection) -> Result<(), DatabaseError> { role TEXT NOT NULL CHECK(role IN ('companion', 'operations', 'general')), base_url TEXT NOT NULL, event_stream_url TEXT, - authentication_type TEXT NOT NULL CHECK(authentication_type IN ('device-token', 'api-key')), + authentication_type TEXT NOT NULL CHECK(authentication_type IN ('device-token', 'api-key', 'jwt')), credential_reference TEXT, allow_insecure_http INTEGER NOT NULL DEFAULT 0 CHECK(allow_insecure_http IN (0, 1)), pinned_certificate_fingerprint TEXT, @@ -184,6 +453,90 @@ fn migrate(connection: &mut Connection) -> Result<(), DatabaseError> { transaction.commit()?; } + if found <= 2 { + let transaction = connection.transaction()?; + transaction.execute_batch( + " + CREATE TABLE connection_slots ( + slot TEXT PRIMARY KEY NOT NULL + CHECK(slot IN ('companion', 'operations')), + profile_id TEXT UNIQUE + REFERENCES connection_profiles(id) ON DELETE SET NULL, + updated_at TEXT NOT NULL + ); + INSERT INTO connection_slots (slot, profile_id, updated_at) + VALUES + ('companion', NULL, '1970-01-01T00:00:00Z'), + ('operations', NULL, '1970-01-01T00:00:00Z'); + PRAGMA user_version = 3; + ", + )?; + transaction.commit()?; + } + + 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()?; + } + + if found <= 5 { + let transaction = connection.transaction()?; + transaction.execute_batch( + "CREATE TABLE IF NOT EXISTS chat_sessions (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, unread_count INTEGER NOT NULL DEFAULT 0 CHECK(unread_count >= 0), last_message_id TEXT, last_message_at TEXT NOT NULL, PRIMARY KEY (account_id, profile_id, slot, server_instance_id, session_id)); CREATE INDEX IF NOT EXISTS chat_sessions_profile_idx ON chat_sessions(profile_id, server_instance_id, last_message_at); PRAGMA user_version = 6;", + )?; + transaction.commit()?; + } + + if found <= 6 { + let transaction = connection.transaction()?; + transaction.execute_batch( + "CREATE TABLE IF NOT EXISTS window_states (window_id TEXT PRIMARY KEY NOT NULL, x INTEGER NOT NULL, y INTEGER NOT NULL, width INTEGER NOT NULL, height INTEGER NOT NULL, monitor_name TEXT, updated_at TEXT NOT NULL); PRAGMA user_version = 7;", + )?; + transaction.commit()?; + } + + if found <= 7 { + let transaction = connection.transaction()?; + transaction.execute_batch( + "ALTER TABLE connection_slots RENAME TO connection_slots_legacy; ALTER TABLE connection_profiles RENAME TO connection_profiles_legacy; DROP INDEX IF EXISTS connection_profiles_role_idx; CREATE TABLE connection_profiles (id TEXT PRIMARY KEY NOT NULL, display_name TEXT NOT NULL CHECK(length(display_name) BETWEEN 1 AND 80), role TEXT NOT NULL CHECK(role IN ('companion', 'operations', 'general')), base_url TEXT NOT NULL, event_stream_url TEXT, authentication_type TEXT NOT NULL CHECK(authentication_type IN ('device-token', 'api-key', 'jwt')), credential_reference TEXT, allow_insecure_http INTEGER NOT NULL DEFAULT 0 CHECK(allow_insecure_http IN (0, 1)), pinned_certificate_fingerprint TEXT, auto_connect_slot TEXT CHECK(auto_connect_slot IS NULL OR auto_connect_slot IN ('companion', 'operations')), auto_connect INTEGER NOT NULL DEFAULT 0 CHECK(auto_connect IN (0, 1)), server_instance_id TEXT, server_version TEXT, protocol_version TEXT, local_tool_policy_id TEXT, last_connected_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, transport_kind TEXT NOT NULL DEFAULT 'desktop-v1', remote_username TEXT, sticky_session_id TEXT); CREATE INDEX connection_profiles_role_idx ON connection_profiles(role); INSERT INTO connection_profiles SELECT 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, transport_kind, remote_username, sticky_session_id FROM connection_profiles_legacy; CREATE TABLE connection_slots (slot TEXT PRIMARY KEY NOT NULL CHECK(slot IN ('companion', 'operations')), profile_id TEXT UNIQUE REFERENCES connection_profiles(id) ON DELETE SET NULL, updated_at TEXT NOT NULL); INSERT INTO connection_slots SELECT slot, profile_id, updated_at FROM connection_slots_legacy; DROP TABLE connection_slots_legacy; DROP TABLE connection_profiles_legacy; PRAGMA user_version = 8;", + )?; + transaction.commit()?; + } + + if found <= 8 { + let transaction = connection.transaction()?; + transaction.execute_batch( + "ALTER TABLE connection_profiles ADD COLUMN remote_display_name TEXT CHECK(remote_display_name IS NULL OR length(remote_display_name) BETWEEN 1 AND 80); PRAGMA user_version = 9;", + )?; + transaction.commit()?; + } + Ok(()) } @@ -197,12 +550,100 @@ pub enum DatabaseError { LockPoisoned, #[error("database contains invalid profile data")] 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")] + SlotNotFound, + #[error("connection profile is already assigned to another slot")] + ProfileAlreadyAssigned, } #[cfg(test)] mod tests { + #[test] + fn tracks_chat_session_unread_count_and_read_state() { + let database = ApplicationDatabase::in_memory().expect("database"); + database + .upsert_chat_message( + "account-a", + "profile-a", + "companion", + "server-a", + Some("user"), + "session-a", + "user-1", + "user", + "hello", + false, + false, + ) + .expect("user message"); + database + .upsert_chat_message( + "account-a", + "profile-a", + "companion", + "server-a", + Some("user"), + "session-a", + "assistant-1", + "assistant", + "reply", + true, + false, + ) + .expect("streaming reply"); + database + .upsert_chat_message( + "account-a", + "profile-a", + "companion", + "server-a", + Some("user"), + "session-a", + "assistant-1", + "assistant", + "reply", + false, + false, + ) + .expect("completed reply"); + database + .upsert_chat_message( + "account-a", + "profile-a", + "companion", + "server-a", + Some("user"), + "session-a", + "assistant-1", + "assistant", + "reply", + false, + false, + ) + .expect("duplicate completion"); + let sessions = database + .list_chat_sessions("profile-a", "server-a") + .expect("sessions"); + assert_eq!(sessions.len(), 1); + assert_eq!(sessions[0].unread_count, 1); + database + .mark_chat_session_read("profile-a", "server-a", "session-a") + .expect("mark read"); + assert_eq!( + database + .list_chat_sessions("profile-a", "server-a") + .expect("sessions after read")[0] + .unread_count, + 0 + ); + } + use super::*; #[test] @@ -277,7 +718,10 @@ mod tests { drop(connection); let store = ProfileMessageStore::open(&path).expect("migrate database"); - assert_eq!(store.schema_version().expect("schema version"), 2); + assert_eq!( + store.schema_version().expect("schema version"), + CURRENT_SCHEMA_VERSION + ); assert_eq!( store .message_content("profile-a", "server-a", "conversation-a", "message-a") @@ -295,6 +739,81 @@ mod tests { ) .expect("query profile table"); assert_eq!(profile_table_count, 1); + let slot_count: u32 = store + .connection + .query_row("SELECT COUNT(*) FROM connection_slots", [], |row| { + row.get(0) + }) + .expect("query slot rows"); + assert_eq!(slot_count, 2); + } + + #[test] + fn migrates_v2_to_v3_without_losing_profiles() { + let directory = tempfile::tempdir().expect("temporary directory"); + let path = directory.path().join("v2.sqlite3"); + { + let store = ProfileMessageStore::open(&path).expect("create current database"); + store + .connection + .execute( + " + INSERT INTO connection_profiles ( + id, + display_name, + role, + base_url, + authentication_type, + created_at, + updated_at + ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) + ", + params![ + "00000000-0000-4000-8000-000000000001", + "Preserved Profile", + "general", + "https://example.test/", + "device-token", + "2026-07-19T00:00:00Z", + "2026-07-19T00:00:00Z", + ], + ) + .expect("insert profile"); + store + .connection + .execute_batch( + " + DROP TABLE connection_slots; + -- Keep only v2-era profile columns when present. + -- Current schema may already include v4 columns; migration must tolerate that. + PRAGMA user_version = 2; + ", + ) + .expect("restore v2 shape"); + } + + let reopened = ProfileMessageStore::open(&path).expect("migrate v2 database"); + assert_eq!( + reopened.schema_version().expect("schema version"), + CURRENT_SCHEMA_VERSION + ); + let profile_count: u32 = reopened + .connection + .query_row( + "SELECT COUNT(*) FROM connection_profiles + WHERE id = '00000000-0000-4000-8000-000000000001'", + [], + |row| row.get(0), + ) + .expect("query preserved profile"); + assert_eq!(profile_count, 1); + let slot_count: u32 = reopened + .connection + .query_row("SELECT COUNT(*) FROM connection_slots", [], |row| { + row.get(0) + }) + .expect("query slot rows"); + assert_eq!(slot_count, 2); } #[test] @@ -310,9 +829,9 @@ mod tests { assert!(matches!( ProfileMessageStore::open(path), Err(DatabaseError::UnsupportedSchemaVersion { - found: 3, + found, supported: CURRENT_SCHEMA_VERSION - }) + }) if found == CURRENT_SCHEMA_VERSION + 1 )); } @@ -366,4 +885,24 @@ mod tests { Some("B") ); } + #[test] + fn persists_quick_window_state_round_trip() { + let database = ApplicationDatabase::in_memory().expect("database"); + let state = crate::quick_window::QuickWindowState { + x: 120, + y: 240, + width: 520, + height: 700, + monitor_name: Some("DISPLAY1".into()), + }; + database + .save_window_state(crate::quick_window::QUICK_WINDOW_ID, &state) + .expect("save window state"); + assert_eq!( + database + .load_window_state(crate::quick_window::QUICK_WINDOW_ID) + .expect("load window state"), + Some(state) + ); + } } diff --git a/src-tauri/src/database/profiles.rs b/src-tauri/src/database/profiles.rs index 0628722..47b2c2b 100644 --- a/src-tauri/src/database/profiles.rs +++ b/src-tauri/src/database/profiles.rs @@ -1,349 +1,390 @@ -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, DatabaseError> { - self.store - .lock() - .map_err(|_| DatabaseError::LockPoisoned)? - .list_profiles() - } - - pub fn profile(&self, id: &str) -> Result, 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, 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, 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 { - 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, +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, + remote_display_name, + sticky_session_id, + created_at, + updated_at +"; + +impl ApplicationDatabase { + pub fn list_profiles(&self) -> Result, DatabaseError> { + self.store + .lock() + .map_err(|_| DatabaseError::LockPoisoned)? + .list_profiles() + } + + pub fn profile(&self, id: &str) -> Result, 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, 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, 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, + remote_display_name, + 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, ?22 + ) + ", + 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.remote_display_name, + 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, + remote_display_name = ?19, + sticky_session_id = ?20, + created_at = ?21, + updated_at = ?22 + 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.remote_display_name, + 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 { + 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>(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", + "jwt" => AuthenticationType::Jwt, + _ => 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>(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)?, + remote_display_name: row.get(18)?, + sticky_session_id: row.get(19)?, + created_at: row.get(20)?, + updated_at: row.get(21)?, + }) +} + +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); - } -} + AuthenticationType::Jwt => "jwt", + } +} + +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, + remote_display_name: 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); + } +} diff --git a/src-tauri/src/database/slots.rs b/src-tauri/src/database/slots.rs new file mode 100644 index 0000000..4818cde --- /dev/null +++ b/src-tauri/src/database/slots.rs @@ -0,0 +1,295 @@ +use desktop_protocol::{ActiveSlotKind, ConnectionSlot, ConnectionState}; +use rusqlite::{OptionalExtension, Row, params}; + +use super::{ApplicationDatabase, DatabaseError, ProfileMessageStore}; + +impl ApplicationDatabase { + pub fn list_connection_slots(&self) -> Result, DatabaseError> { + self.store + .lock() + .map_err(|_| DatabaseError::LockPoisoned)? + .list_connection_slots() + } + + pub fn assign_connection_slot( + &self, + slot: ActiveSlotKind, + profile_id: &str, + updated_at: &str, + ) -> Result { + self.store + .lock() + .map_err(|_| DatabaseError::LockPoisoned)? + .set_connection_slot(slot, Some(profile_id), updated_at) + } + + pub fn clear_connection_slot( + &self, + slot: ActiveSlotKind, + updated_at: &str, + ) -> Result { + self.store + .lock() + .map_err(|_| DatabaseError::LockPoisoned)? + .set_connection_slot(slot, None, updated_at) + } +} + +impl ProfileMessageStore { + fn list_connection_slots(&self) -> Result, DatabaseError> { + let mut statement = self.connection.prepare( + " + SELECT slots.slot, slots.profile_id, profiles.server_instance_id + FROM connection_slots AS slots + LEFT JOIN connection_profiles AS profiles + ON profiles.id = slots.profile_id + ORDER BY CASE slots.slot + WHEN 'companion' THEN 0 + WHEN 'operations' THEN 1 + ELSE 2 + END + ", + )?; + let mut rows = statement.query([])?; + let mut slots = Vec::with_capacity(2); + while let Some(row) = rows.next()? { + slots.push(slot_from_row(row)?); + } + if slots.len() != 2 { + return Err(DatabaseError::InvalidStoredSlot); + } + Ok(slots) + } + + fn connection_slot(&self, slot: ActiveSlotKind) -> Result { + self.connection + .query_row( + " + SELECT slots.slot, slots.profile_id, profiles.server_instance_id + FROM connection_slots AS slots + LEFT JOIN connection_profiles AS profiles + ON profiles.id = slots.profile_id + WHERE slots.slot = ?1 + ", + params![slot_to_str(slot)], + slot_from_row, + ) + .optional()? + .ok_or(DatabaseError::SlotNotFound) + } + + fn set_connection_slot( + &mut self, + slot: ActiveSlotKind, + profile_id: Option<&str>, + updated_at: &str, + ) -> Result { + let transaction = self.connection.transaction()?; + + if let Some(profile_id) = profile_id { + let profile_exists = transaction + .query_row( + "SELECT 1 FROM connection_profiles WHERE id = ?1", + params![profile_id], + |row| row.get::<_, u8>(0), + ) + .optional()? + .is_some(); + if !profile_exists { + return Err(DatabaseError::ProfileNotFound); + } + + let assigned_slot = transaction + .query_row( + "SELECT slot FROM connection_slots WHERE profile_id = ?1", + params![profile_id], + |row| row.get::<_, String>(0), + ) + .optional()?; + if assigned_slot + .as_deref() + .is_some_and(|assigned| assigned != slot_to_str(slot)) + { + return Err(DatabaseError::ProfileAlreadyAssigned); + } + } + + let changed = transaction.execute( + " + UPDATE connection_slots + SET profile_id = ?2, + updated_at = ?3 + WHERE slot = ?1 + ", + params![slot_to_str(slot), profile_id, updated_at], + )?; + if changed == 0 { + return Err(DatabaseError::SlotNotFound); + } + transaction.commit()?; + self.connection_slot(slot) + } +} + +fn slot_from_row(row: &Row<'_>) -> Result { + let slot = match row.get::<_, String>(0)?.as_str() { + "companion" => ActiveSlotKind::Companion, + "operations" => ActiveSlotKind::Operations, + _ => { + return Err(rusqlite::Error::FromSqlConversionFailure( + 0, + rusqlite::types::Type::Text, + Box::new(DatabaseError::InvalidStoredSlot), + )); + } + }; + Ok(ConnectionSlot { + slot, + profile_id: row.get(1)?, + state: ConnectionState::Disconnected, + server_instance_id: row.get(2)?, + active_conversation_id: None, + unread_count: 0, + last_event_id: None, + last_connected_at: None, + }) +} + +fn slot_to_str(slot: ActiveSlotKind) -> &'static str { + match slot { + ActiveSlotKind::Companion => "companion", + ActiveSlotKind::Operations => "operations", + } +} + +#[cfg(test)] +mod tests { + use desktop_protocol::{AstrBotProfileRole, AuthenticationType, ConnectionProfile}; + + use super::*; + + fn profile(index: usize) -> ConnectionProfile { + ConnectionProfile { + id: format!("00000000-0000-4000-8000-{index:012}"), + display_name: format!("Profile {index}"), + role: AstrBotProfileRole::General, + base_url: format!("https://example-{index}.test/"), + event_stream_url: None, + authentication_type: AuthenticationType::DeviceToken, + 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, + remote_display_name: 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) + )); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 1d879e8..01bdefa 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,21 +1,39 @@ +pub mod auth; +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 quick_window; +pub mod runtime_guards; pub mod secure_store; +pub mod slots; pub mod windows; use database::ApplicationDatabase; +use networking::{DualSlotRuntime, auto_connect_configured_slots}; +use policy::ConnectionPolicyStatus; +use quick_window::{ + DEFAULT_HEIGHT, DEFAULT_WIDTH, MAX_HEIGHT, MAX_WIDTH, MIN_HEIGHT, MIN_WIDTH, QUICK_WINDOW_ID, + QuickWindowState, +}; +use runtime_guards::RuntimeGuards; use serde::Serialize; use tauri::{ - Manager, WindowEvent, - menu::{Menu, MenuItem}, + AppHandle, Emitter, Manager, PhysicalPosition, PhysicalSize, WebviewUrl, WebviewWindowBuilder, + WindowEvent, + menu::{Menu, MenuItem, PredefinedMenuItem}, tray::TrayIconBuilder, + window::Color, }; +const PET_WINDOW_ID: &str = "desktop-pet"; + #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] struct BootstrapStatus { @@ -26,6 +44,231 @@ 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) + .shadow(false) + .transparent(true) + .background_color(Color(0, 0, 0, 0)) + .always_on_top(false) + .skip_taskbar(true) + .build() + .map(|_| ()) + .map_err(|error| error.to_string()) +} + +#[tauri::command] +fn open_quick_chat_window( + app: AppHandle, + slot: Option, +) -> Result<(), String> { + if let Some(window) = app.get_webview_window(QUICK_WINDOW_ID) { + window.show().map_err(|error| error.to_string())?; + window.set_focus().map_err(|error| error.to_string())?; + return Ok(()); + } + WebviewWindowBuilder::new( + &app, + QUICK_WINDOW_ID, + WebviewUrl::App(match slot { + Some(desktop_protocol::ActiveSlotKind::Companion) => { + "index.html?view=quick&slot=companion".into() + } + Some(desktop_protocol::ActiveSlotKind::Operations) => { + "index.html?view=quick&slot=operations".into() + } + None => "index.html?view=quick".into(), + }), + ) + .title("AstrBot Quick Chat") + .inner_size(DEFAULT_WIDTH as f64, DEFAULT_HEIGHT as f64) + .min_inner_size(MIN_WIDTH as f64, MIN_HEIGHT as f64) + .max_inner_size(MAX_WIDTH as f64, MAX_HEIGHT as f64) + .resizable(true) + .build() + .map_err(|error| error.to_string()) + .map(|window| { + restore_quick_window_state(&window, &app); + }) +} + +fn restore_quick_window_state(window: &tauri::WebviewWindow, app: &AppHandle) { + let database = app.state::(); + let Ok(Some(state)) = database.load_window_state(QUICK_WINDOW_ID) else { + return; + }; + let state = state.normalized(); + let monitor = state + .monitor_name + .as_deref() + .and_then(|name| { + window + .available_monitors() + .ok()? + .into_iter() + .find(|monitor| monitor.name().map(String::as_str) == Some(name)) + }) + .or_else(|| window.primary_monitor().ok().flatten()); + let Some(monitor) = monitor else { + return; + }; + let area = monitor.work_area(); + let state = state.clamp_to_work_area( + area.position.x, + area.position.y, + area.size.width, + area.size.height, + ); + let _ = window.set_size(PhysicalSize::new(state.width, state.height)); + let _ = window.set_position(PhysicalPosition::new(state.x, state.y)); +} + +fn save_quick_window_state(window: &tauri::Window, app: &AppHandle) { + let Ok(position) = window.outer_position() else { + return; + }; + let Ok(size) = window.inner_size() else { + return; + }; + let monitor_name = window + .current_monitor() + .ok() + .flatten() + .and_then(|monitor| monitor.name().cloned()); + let state = QuickWindowState { + x: position.x, + y: position.y, + width: size.width, + height: size.height, + monitor_name, + } + .normalized(); + let database = app.state::(); + let _ = database.save_window_state(QUICK_WINDOW_ID, &state); +} + +fn exit_application(app: &AppHandle) { + app.cleanup_before_exit(); + std::process::exit(0); +} + +#[tauri::command] +fn open_main_window(app: AppHandle) -> Result<(), String> { + let window = app + .get_webview_window("main") + .ok_or_else(|| "main window is unavailable".to_owned())?; + window.show().map_err(|error| error.to_string())?; + window.set_focus().map_err(|error| error.to_string()) +} + +#[tauri::command] +fn open_pet_window(app: AppHandle) -> Result<(), String> { + if let Some(window) = app.get_webview_window(PET_WINDOW_ID) { + window + .set_always_on_top(true) + .map_err(|error| error.to_string())?; + window + .set_position(PhysicalPosition::new(120, 120)) + .map_err(|error| error.to_string())?; + window.show().map_err(|error| error.to_string())?; + return Ok(()); + } + let config = app + .config() + .app + .windows + .iter() + .find(|window| window.label == PET_WINDOW_ID) + .ok_or_else(|| "pet window config is unavailable".to_owned())?; + WebviewWindowBuilder::from_config(&app, config) + .map_err(|error| error.to_string())? + .build() + .map(|_| ()) + .map_err(|error| error.to_string()) +} + +#[tauri::command] +fn close_pet_window(app: AppHandle) -> Result<(), String> { + if let Some(window) = app.get_webview_window(PET_WINDOW_ID) { + window.destroy().map_err(|error| error.to_string())?; + } + Ok(()) +} + +#[tauri::command] +fn show_pet_context_menu(app: AppHandle) -> Result<(), String> { + let open_main = MenuItem::with_id( + &app, + "pet-open-main", + "\u{6253}\u{5f00}\u{4e3b}\u{754c}\u{9762}", + true, + None::<&str>, + ) + .map_err(|error| error.to_string())?; + let open_quick = MenuItem::with_id( + &app, + "pet-open-quick", + "\u{6253}\u{5f00}\u{5feb}\u{6377}\u{804a}\u{5929}", + true, + None::<&str>, + ) + .map_err(|error| error.to_string())?; + let toggle_game = MenuItem::with_id( + &app, + "pet-game-mode", + "\u{5207}\u{6362}\u{6e38}\u{620f}\u{6a21}\u{5f0f}", + true, + None::<&str>, + ) + .map_err(|error| error.to_string())?; + let separator = PredefinedMenuItem::separator(&app).map_err(|error| error.to_string())?; + let hide_pet = MenuItem::with_id( + &app, + "pet-hide", + "\u{5173}\u{95ed}\u{684c}\u{5ba0}", + true, + None::<&str>, + ) + .map_err(|error| error.to_string())?; + let quit = MenuItem::with_id( + &app, + "pet-exit", + "\u{5173}\u{95ed}\u{7a0b}\u{5e8f}", + true, + None::<&str>, + ) + .map_err(|error| error.to_string())?; + let menu = Menu::with_items( + &app, + &[ + &open_main, + &open_quick, + &toggle_game, + &separator, + &hide_pet, + &quit, + ], + ) + .map_err(|error| error.to_string())?; + let window = app + .get_webview_window(PET_WINDOW_ID) + .or_else(|| app.get_webview_window("main")) + .ok_or_else(|| "pet context menu window is unavailable".to_owned())?; + window.popup_menu(&menu).map_err(|error| error.to_string()) +} + #[tauri::command] fn bootstrap_status( database: tauri::State<'_, ApplicationDatabase>, @@ -43,6 +286,23 @@ fn bootstrap_status( }) } +#[tauri::command] +fn connection_policy_status( + database: tauri::State<'_, ApplicationDatabase>, + guards: tauri::State<'_, RuntimeGuards>, +) -> Result { + let switch = guards + .operations_switch_status() + .map_err(|_| "operations switch guard is unavailable".to_owned())?; + let warnings = policy::list_duplicate_server_instance_warnings(&database) + .map_err(|_| "database status is unavailable".to_owned())?; + Ok(ConnectionPolicyStatus { + operations_switch_locked: switch.locked, + active_operations_task_count: switch.active_task_count, + duplicate_server_instance_warnings: warnings, + }) +} + pub fn run() { logging::init(); @@ -53,12 +313,38 @@ pub fn run() { let _ = window.set_focus(); } })) + .on_menu_event(|app, event| match event.id.as_ref() { + "pet-open-main" => { + let _ = open_main_window(app.clone()); + } + "pet-open-quick" => { + let _ = open_quick_chat_window(app.clone(), None); + } + "pet-game-mode" => { + let _ = app.emit("pet-game-mode-toggle", ()); + } + "pet-hide" => { + let _ = close_pet_window(app.clone()); + let _ = app.emit("pet-hide-requested", ()); + } + "pet-exit" => exit_application(app), + _ => {} + }) .setup(|app| { let app_data_dir = app.path().app_data_dir()?; std::fs::create_dir_all(&app_data_dir)?; app.manage(ApplicationDatabase::open( app_data_dir.join("astrbot-desktop.sqlite3"), )?); + app.manage(RuntimeGuards::new()); + app.manage(DualSlotRuntime::new()); + + let startup_handle = app.handle().clone(); + tauri::async_runtime::spawn(async move { + let database = startup_handle.state::(); + let runtime = startup_handle.state::(); + auto_connect_configured_slots(&database, &runtime).await; + }); let show = MenuItem::with_id(app, "show", "Show AstrBot Desktop", true, None::<&str>)?; let quit = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?; @@ -73,25 +359,66 @@ pub fn run() { let _ = window.set_focus(); } } - "quit" => app.exit(0), + "quit" => exit_application(app), _ => {} }) .build(app)?; Ok(()) }) - .on_window_event(|window, event| { - if let WindowEvent::CloseRequested { api, .. } = event { + .on_window_event(|window, event| match event { + WindowEvent::Moved(_) | WindowEvent::Resized(_) => { + if window.label() == QUICK_WINDOW_ID { + save_quick_window_state(window, window.app_handle()); + } + } + WindowEvent::CloseRequested { api, .. } => { + if window.label() == QUICK_WINDOW_ID { + save_quick_window_state(window, window.app_handle()); + return; + } + if window.label() == PET_WINDOW_ID { + api.prevent_close(); + let _ = window.hide(); + return; + } api.prevent_close(); let _ = window.hide(); } + _ => {} }) .invoke_handler(tauri::generate_handler![ + auth::login_profile_jwt, bootstrap_status, + open_quick_chat_window, + open_main_window, + open_status_bubble_window, + open_pet_window, + close_pet_window, + show_pet_context_menu, + connection_policy_status, profiles::list_connection_profiles, profiles::create_connection_profile, profiles::update_connection_profile, profiles::delete_connection_profile, + 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::list_chat_sessions, + networking::commands::mark_chat_session_read, + networking::commands::probe_connection_slot, + networking::commands::disconnect_connection_slot, + networking::commands::send_connection_slot_message, + networking::commands::connection_slot_capabilities, + networking::commands::connection_slot_sessions, + networking::commands::switch_connection_slot_session, + networking::commands::upload_connection_slot_file, + networking::commands::cancel_connection_slot_message, ]) .run(tauri::generate_context!()) .expect("failed to run AstrBot Desktop"); diff --git a/src-tauri/src/networking/astrbot_client.rs b/src-tauri/src/networking/astrbot_client.rs new file mode 100644 index 0000000..b720e76 --- /dev/null +++ b/src-tauri/src/networking/astrbot_client.rs @@ -0,0 +1,593 @@ +use std::{collections::VecDeque, sync::Arc, time::Duration}; + +use desktop_protocol::{ + AstrBotApiEnvelope, AstrBotAttachment, AstrBotCapabilitySnapshot, AstrBotChatRequest, + AstrBotConfigListData, AstrBotModelOption, AstrBotSessionListData, AstrBotStreamMapper, + AuthenticationType, 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, + pub remote_display_name: Option, + pub authentication_type: AuthenticationType, + /// Optional sticky session id. When absent, the first chat response supplies one. + pub session_id: Option, + /// Expected server identity substitute. Empty means accept first observed identity. + pub expected_server_instance_id: Option, +} + +#[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), + #[error("astrbot credential expired")] + CredentialExpired, +} + +impl From 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()), + AstrBotClientError::CredentialExpired => { + GatewayError::Adapter("AstrBot authentication has expired".into()) + } + } + } +} + +const MAX_DEDUPLICATED_EVENTS: usize = 4_096; + +#[derive(Default)] +struct EventDeduplicator { + ids: std::collections::HashSet, + order: VecDeque, +} + +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 + } +} + +#[derive(Clone)] +pub struct AstrBotClient { + config: AstrBotClientConfig, + http: reqwest::Client, + seen_event_ids: Arc>, + session_id: Arc>>, + server_instance_id: Arc>, + state_tx: watch::Sender, +} + +impl AstrBotClient { + pub fn new(config: AstrBotClientConfig) -> Result { + 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")); + } + if config.authentication_type == AuthenticationType::Jwt + && jwt_is_expired(config.api_key.expose_secret()) + { + return Err(AstrBotClientError::CredentialExpired); + } + + 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 { + 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 { + 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 = 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 set_session_id(&self, session_id: String) -> Result<(), AstrBotClientError> { + if session_id.trim().is_empty() { + return Err(AstrBotClientError::InvalidConfig("session_id is required")); + } + *self.session_id.lock().await = Some(session_id); + Ok(()) + } + + pub async fn list_sessions(&self) -> Result { + 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 = 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 { + 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 = 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 capabilities(&self) -> Result { + let configs = self.list_configs().await?; + let models = configs + .configs + .into_iter() + .map(|config| AstrBotModelOption { + id: config.id, + name: config.name, + is_default: config.is_default, + }) + .collect::>(); + Ok(AstrBotCapabilitySnapshot { + transport: "astrbot-openapi".to_owned(), + text_chat: true, + streaming: true, + model_selection: !models.is_empty(), + file_upload: true, + image_input: true, + models, + }) + } + + pub async fn upload_file( + &self, + file_name: &str, + mime_type: &str, + bytes: Vec, + ) -> Result { + if file_name.trim().is_empty() || mime_type.trim().is_empty() || bytes.is_empty() { + return Err(AstrBotClientError::InvalidConfig( + "file_name, mime_type, and file bytes are required", + )); + } + let part = reqwest::multipart::Part::bytes(bytes.clone()) + .file_name(file_name.to_owned()) + .mime_str(mime_type) + .map_err(|_| AstrBotClientError::InvalidConfig("invalid attachment mime type"))?; + let form = reqwest::multipart::Form::new().part("file", part); + let response = self + .http + .post(self.url("/api/v1/file")) + .multipart(form) + .send() + .await?; + if !response.status().is_success() { + return Err(AstrBotClientError::HttpStatus(response.status())); + } + let envelope: AstrBotApiEnvelope = response.json().await?; + if !envelope.is_ok() { + return Err(AstrBotClientError::ApiStatus( + envelope + .message + .unwrap_or_else(|| "file upload failed".into()), + )); + } + let data = envelope.data.unwrap_or(Value::Null); + let attachment_id = data + .get("id") + .or_else(|| data.get("file_id")) + .or_else(|| data.get("attachment_id")) + .and_then(Value::as_str) + .ok_or_else(|| AstrBotClientError::Map("upload response has no attachment id".into()))? + .to_owned(); + Ok(AstrBotAttachment { + attachment_id, + file_name: file_name.to_owned(), + mime_type: mime_type.to_owned(), + size_bytes: bytes.len() as u64, + url: data + .get("url") + .and_then(Value::as_str) + .map(ToOwned::to_owned), + }) + } + + pub async fn send_chat_stream( + &self, + message: &str, + config_id: Option, + attachments: Vec, + sender: &mpsc::Sender, + cancellation: &CancellationToken, + ) -> Result, 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()), + nickname: self.config.remote_display_name.clone(), + config_id, + attachments: (!attachments.is_empty()).then_some(attachments), + 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, + sender: &mpsc::Sender, + ) -> 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() +} + +fn jwt_is_expired(token: &str) -> bool { + let Some(payload) = token.split('.').nth(1).and_then(decode_base64url) else { + return false; + }; + let Ok(value) = serde_json::from_slice::(&payload) else { + return false; + }; + let Some(exp) = value.get("exp").and_then(Value::as_i64) else { + return false; + }; + exp <= time::OffsetDateTime::now_utc().unix_timestamp() +} + +fn decode_base64url(value: &str) -> Option> { + let mut output = Vec::with_capacity(value.len() * 3 / 4); + let mut buffer = 0u32; + let mut bits = 0u8; + for byte in value.bytes() { + let digit = match byte { + b'A'..=b'Z' => byte - b'A', + b'a'..=b'z' => byte - b'a' + 26, + b'0'..=b'9' => byte - b'0' + 52, + b'-' => 62, + b'_' => 63, + b'=' => break, + _ => return None, + }; + buffer = (buffer << 6) | u32::from(digit); + bits += 6; + if bits >= 8 { + bits -= 8; + output.push((buffer >> bits) as u8); + buffer &= (1 << bits) - 1; + } + } + Some(output) +} + +#[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(), + remote_display_name: None, + authentication_type: AuthenticationType::ApiKey, + 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(), + remote_display_name: Some("Desktop Companion".into()), + authentication_type: AuthenticationType::ApiKey, + session_id: Some("s1".into()), + expected_server_instance_id: None, + }) + .expect("client"); + assert!(client.server_instance_id_blocking().starts_with("astrbot-")); + } + + #[test] + fn detects_expired_jwt_without_logging_or_exposing_the_token() { + assert!(jwt_is_expired("e30.eyJleHAiOjF9.signature")); + assert!(!jwt_is_expired("not-a-jwt")); + } +} diff --git a/src-tauri/src/networking/commands.rs b/src-tauri/src/networking/commands.rs new file mode 100644 index 0000000..5c50720 --- /dev/null +++ b/src-tauri/src/networking/commands.rs @@ -0,0 +1,592 @@ +// 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 tracing::{info, warn}; + +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, + pub config_id: Option, + #[serde(default)] + pub attachments: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SlotFileUploadRequest { + pub slot: SlotKind, + pub file_name: String, + pub mime_type: String, + pub bytes: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SlotCapabilitiesRequest { + pub slot: SlotKind, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct DrainConnectionRuntimeEventsRequest { + pub limit: Option, +} + +#[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, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ListChatSessionsRequest { + pub profile_id: String, + pub server_instance_id: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct MarkChatSessionReadRequest { + pub profile_id: String, + pub server_instance_id: String, + pub session_id: String, +} + +#[tauri::command] +pub async fn connection_runtime_status( + runtime: State<'_, DualSlotRuntime>, +) -> Result { + Ok(runtime.status().await) +} + +/// Starts profiles explicitly marked for startup connection. +/// +/// Each slot is attempted independently. A failure is retained in that slot's +/// runtime snapshot and does not prevent the other configured slot from being attempted. +pub async fn auto_connect_configured_slots( + database: &ApplicationDatabase, + runtime: &DualSlotRuntime, +) { + let profiles = match database.list_profiles() { + Ok(profiles) => profiles, + Err(error) => { + warn!(error = %error, "startup auto-connect could not read profiles"); + return; + } + }; + + for profile in profiles.into_iter().filter(|profile| profile.auto_connect) { + let Some(active_slot) = profile.auto_connect_slot else { + warn!(profile_id = %profile.id, "startup auto-connect skipped profile without a slot"); + continue; + }; + let slot = match active_slot { + desktop_protocol::ActiveSlotKind::Companion => SlotKind::Companion, + desktop_protocol::ActiveSlotKind::Operations => SlotKind::Operations, + }; + let profile_id = profile.id.clone(); + let activation = match startup_activation_request(database, &profile, slot) { + Ok(request) => request, + Err(error) => { + warn!(profile_id = %profile_id, slot = ?slot, error = %error, "startup auto-connect skipped"); + continue; + } + }; + + match runtime.activate_slot(activation).await { + Ok(snapshot) => info!( + profile_id = %profile_id, + slot = ?slot, + state = ?snapshot.state, + "startup auto-connect completed" + ), + Err(error) => warn!( + profile_id = %profile_id, + slot = ?slot, + error = %error, + "startup auto-connect failed" + ), + } + } +} + +fn startup_activation_request( + database: &ApplicationDatabase, + profile: &desktop_protocol::ConnectionProfile, + slot: SlotKind, +) -> Result { + let secret = load_profile_secret(database, &WindowsCredentialStore, &profile.id).map_err( + |error: CredentialCommandError| RuntimeCommandError { + code: error.code, + message: error.message, + }, + )?; + + match profile.transport_kind { + TransportKind::AstrBotOpenApi => { + let secret = secret.ok_or(RuntimeCommandError { + code: "credentialMissing", + message: "Enroll an AstrBot credential before probing this 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.", + })?; + Ok(SlotActivationRequest { + profile_id: profile.id.clone(), + 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), + remote_display_name: profile.remote_display_name.clone(), + authentication_type: profile.authentication_type, + 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.", + })?; + Ok(SlotActivationRequest { + profile_id: profile.id.clone(), + slot, + base_url: profile.base_url.clone(), + transport: TransportKind::DesktopV1, + api_key: None, + bearer_token: bearer, + remote_username: None, + remote_display_name: None, + authentication_type: profile.authentication_type, + session_id: None, + expected_server_instance_id: Some(expected), + }) + } + } +} + +#[tauri::command] +pub async fn drain_connection_runtime_events( + database: State<'_, ApplicationDatabase>, + runtime: State<'_, DualSlotRuntime>, + request: DrainConnectionRuntimeEventsRequest, +) -> Result, 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 list_chat_sessions( + database: State<'_, ApplicationDatabase>, + request: ListChatSessionsRequest, +) -> Result, RuntimeCommandError> { + database + .list_chat_sessions(&request.profile_id, &request.server_instance_id) + .map_err(|_| RuntimeCommandError { + code: "databaseUnavailable", + message: "Chat sessions are unavailable.", + }) +} + +#[tauri::command] +pub async fn mark_chat_session_read( + database: State<'_, ApplicationDatabase>, + request: MarkChatSessionReadRequest, +) -> Result<(), RuntimeCommandError> { + database + .mark_chat_session_read( + &request.profile_id, + &request.server_instance_id, + &request.session_id, + ) + .map_err(|_| RuntimeCommandError { + code: "databaseUnavailable", + message: "Chat session state is unavailable.", + }) +} + +#[tauri::command] +pub async fn load_chat_messages( + database: State<'_, ApplicationDatabase>, + request: LoadChatMessagesRequest, +) -> Result, 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 { + 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), + remote_display_name: profile.remote_display_name.clone(), + authentication_type: profile.authentication_type, + 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, + remote_display_name: None, + authentication_type: profile.authentication_type, + 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 cancel_connection_slot_message( + runtime: State<'_, DualSlotRuntime>, + request: DisconnectConnectionSlotRequest, +) -> Result<(), RuntimeCommandError> { + runtime.cancel_slot_message(request.slot).await +} +#[derive(Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ChatRemoteSession { + pub session_id: String, + pub display_name: Option, + pub updated_at: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SwitchChatSessionRequest { + pub slot: SlotKind, + pub session_id: String, +} + +#[tauri::command] +pub async fn connection_slot_sessions( + runtime: State<'_, DualSlotRuntime>, + request: SlotCapabilitiesRequest, +) -> Result, RuntimeCommandError> { + let sessions = runtime.slot_sessions(request.slot).await?; + Ok(sessions + .sessions + .into_iter() + .map(|session| ChatRemoteSession { + session_id: session.session_id, + display_name: session.display_name, + updated_at: session.updated_at, + }) + .collect()) +} + +#[tauri::command] +pub async fn switch_connection_slot_session( + runtime: State<'_, DualSlotRuntime>, + request: SwitchChatSessionRequest, +) -> Result { + runtime + .switch_slot_session(request.slot, request.session_id) + .await +} + +#[tauri::command] +pub async fn connection_slot_capabilities( + runtime: State<'_, DualSlotRuntime>, + request: SlotCapabilitiesRequest, +) -> Result { + runtime.slot_capabilities(request.slot).await +} + +#[tauri::command] +pub async fn upload_connection_slot_file( + runtime: State<'_, DualSlotRuntime>, + request: SlotFileUploadRequest, +) -> Result { + if request.bytes.len() > 16 * 1024 * 1024 { + return Err(RuntimeCommandError::validation( + "Attachment exceeds the 16 MiB limit.", + )); + } + runtime + .upload_slot_file( + request.slot, + request.file_name, + request.mime_type, + request.bytes, + ) + .await +} + +#[tauri::command] +pub async fn send_connection_slot_message( + database: State<'_, ApplicationDatabase>, + runtime: State<'_, DualSlotRuntime>, + request: SendConnectionSlotMessageRequest, +) -> Result { + 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, + request.config_id, + request.attachments, + ) + .await +} diff --git a/src-tauri/src/networking/gateway_client.rs b/src-tauri/src/networking/gateway_client.rs index 1090320..b5723af 100644 --- a/src-tauri/src/networking/gateway_client.rs +++ b/src-tauri/src/networking/gateway_client.rs @@ -34,6 +34,8 @@ pub struct BoundGatewayEvent { pub event_id: String, pub event_type: String, pub server_instance_id: String, + pub session_id: Option, + pub message_id: Option, 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 diff --git a/src-tauri/src/networking/mod.rs b/src-tauri/src/networking/mod.rs index 8413b85..19b9617 100644 --- a/src-tauri/src/networking/mod.rs +++ b/src-tauri/src/networking/mod.rs @@ -1,5 +1,20 @@ +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, ListChatSessionsRequest, + MarkChatSessionReadRequest, ProbeConnectionSlotRequest, SendConnectionSlotMessageRequest, + auto_connect_configured_slots, cancel_connection_slot_message, 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, +}; diff --git a/src-tauri/src/networking/runtime.rs b/src-tauri/src/networking/runtime.rs new file mode 100644 index 0000000..0d23bd8 --- /dev/null +++ b/src-tauri/src/networking/runtime.rs @@ -0,0 +1,617 @@ +use desktop_protocol::{ + AstrBotAttachment, AstrBotCapabilitySnapshot, ConnectionState, TransportKind, +}; +use secrecy::SecretString; +use serde::Serialize; +use std::time::Duration; +use tokio::sync::{Mutex, mpsc}; + +use super::{ + AstrBotClient, AstrBotClientConfig, AstrBotClientError, BoundGatewayEvent, GatewayClient, + GatewayClientConfig, GatewayError, SlotKind, +}; + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SlotRuntimeSnapshot { + pub slot: SlotKind, + pub profile_id: Option, + pub transport: Option, + pub state: ConnectionState, + pub server_instance_id: Option, + pub active_session_id: Option, + pub last_error: Option, +} + +#[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, + pub bearer_token: Option, + pub remote_username: Option, + pub remote_display_name: Option, + pub authentication_type: desktop_protocol::AuthenticationType, + pub session_id: Option, + pub expected_server_instance_id: Option, +} + +enum ActiveClient { + Desktop(GatewayClient), + AstrBot(AstrBotClient), +} + +struct SlotRuntime { + snapshot: SlotRuntimeSnapshot, + client: Option, + cancellation: Option, +} + +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, + cancellation: None, + } + } +} + +/// In-process dual-slot connection runtime. +/// +/// Network activation is explicit and Rust-owned. React never receives secrets. +pub struct DualSlotRuntime { + inner: Mutex, + event_tx: mpsc::Sender, + event_rx: Mutex>, +} + +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 { + let mut rx = self.event_rx.lock().await; + rx.try_recv().ok() + } + + pub async fn drain_events(&self, limit: usize) -> Vec { + 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 { + 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, + cancellation: 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, + remote_display_name: request.remote_display_name.clone(), + authentication_type: request.authentication_type, + session_id: request.session_id.clone(), + expected_server_instance_id: request.expected_server_instance_id.clone(), + }) + .map_err(|error| match error { + AstrBotClientError::CredentialExpired => RuntimeCommandError { + code: "authExpired", + message: "AstrBot authentication has expired. Re-login is required.", + }, + _ => 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 cancel_slot_message(&self, slot: SlotKind) -> Result<(), RuntimeCommandError> { + let guard = self.inner.lock().await; + let runtime = slot_ref(&guard, slot); + let Some(cancellation) = runtime.cancellation.as_ref() else { + return Err(RuntimeCommandError::unavailable( + "No chat request is active.", + )); + }; + cancellation.cancel(); + Ok(()) + } + pub async fn slot_sessions( + &self, + slot: SlotKind, + ) -> Result { + let client = { + let guard = self.inner.lock().await; + match slot_ref(&guard, slot).client.as_ref() { + Some(ActiveClient::AstrBot(client)) => client.clone(), + Some(ActiveClient::Desktop(_)) => { + return Err(RuntimeCommandError::validation( + "Session lists are not available for the desktop mock transport.", + )); + } + None => { + return Err(RuntimeCommandError::unavailable( + "Activate the connection before loading sessions.", + )); + } + } + }; + client + .list_sessions() + .await + .map_err(|_| RuntimeCommandError::unavailable("AstrBot sessions are unavailable.")) + } + + pub async fn switch_slot_session( + &self, + slot: SlotKind, + session_id: String, + ) -> Result { + if session_id.trim().is_empty() { + return Err(RuntimeCommandError::validation("session_id is required.")); + } + let client = { + let guard = self.inner.lock().await; + match slot_ref(&guard, slot).client.as_ref() { + Some(ActiveClient::AstrBot(client)) => client.clone(), + Some(ActiveClient::Desktop(_)) => { + return Err(RuntimeCommandError::validation( + "Session switching is not available for the desktop mock transport.", + )); + } + None => { + return Err(RuntimeCommandError::unavailable( + "Activate the connection before switching sessions.", + )); + } + } + }; + client + .set_session_id(session_id.clone()) + .await + .map_err(|_| RuntimeCommandError::validation("The session id is invalid."))?; + let mut guard = self.inner.lock().await; + let runtime = slot_mut(&mut guard, slot); + runtime.snapshot.active_session_id = Some(session_id); + Ok(runtime.snapshot.clone()) + } + + pub async fn slot_capabilities( + &self, + slot: SlotKind, + ) -> Result { + let client = { + let guard = self.inner.lock().await; + match slot_ref(&guard, slot).client.as_ref() { + Some(ActiveClient::AstrBot(client)) => client.clone(), + Some(ActiveClient::Desktop(_)) => { + return Err(RuntimeCommandError::validation( + "Capabilities are not available for the desktop mock transport.", + )); + } + None => { + return Err(RuntimeCommandError::unavailable( + "Activate the connection before loading capabilities.", + )); + } + } + }; + client + .capabilities() + .await + .map_err(|_| RuntimeCommandError::unavailable("AstrBot capabilities are unavailable.")) + } + + pub async fn upload_slot_file( + &self, + slot: SlotKind, + file_name: String, + mime_type: String, + bytes: Vec, + ) -> Result { + let client = { + let guard = self.inner.lock().await; + match slot_ref(&guard, slot).client.as_ref() { + Some(ActiveClient::AstrBot(client)) => client.clone(), + Some(ActiveClient::Desktop(_)) => { + return Err(RuntimeCommandError::validation( + "File upload is not available for the desktop mock transport.", + )); + } + None => { + return Err(RuntimeCommandError::unavailable( + "Activate the connection before uploading a file.", + )); + } + } + }; + client + .upload_file(&file_name, &mime_type, bytes) + .await + .map_err(|_| RuntimeCommandError::unavailable("AstrBot file upload failed.")) + } + + pub async fn send_slot_message( + &self, + slot: SlotKind, + message: String, + config_id: Option, + attachments: Vec, + ) -> Result { + 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, cancellation) = { + 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.") + })?; + let cancellation = tokio_util::sync::CancellationToken::new(); + runtime.cancellation = Some(cancellation.clone()); + 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(), + cancellation, + ) + }; + + let send_result = match client { + ActiveClient::Desktop(client) => { + 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 mut attempts = 0; + loop { + match client + .send_chat_stream( + &message, + config_id.clone(), + attachments.clone(), + &self.event_tx, + &cancellation, + ) + .await + { + Ok(_session) if cancellation.is_cancelled() => { + break Err(( + ActiveClient::AstrBot(client), + RuntimeCommandError { + code: "cancelled", + message: "The chat request was cancelled.", + }, + )); + } + Ok(session) => break Ok((ActiveClient::AstrBot(client), session)), + Err(AstrBotClientError::HttpStatus(status)) + if status.as_u16() == 401 || status.as_u16() == 403 => + { + break Err(( + ActiveClient::AstrBot(client), + RuntimeCommandError { + code: "authExpired", + message: "AstrBot authentication has expired. Re-login is required.", + }, + )); + } + Err(error) if should_retry_astrbot(&error) && attempts < 2 => { + attempts += 1; + let mut guard = self.inner.lock().await; + slot_mut(&mut guard, slot).snapshot.state = + ConnectionState::Reconnecting; + drop(guard); + tokio::time::sleep(Duration::from_millis(250 * attempts)).await; + } + Err(_) => { + break 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 = if error.code == "authExpired" { + ConnectionState::AuthExpired + } else { + ConnectionState::ServerUnavailable + }; + runtime.snapshot.last_error = Some(error.message.to_owned()); + Err(error) + } + } + } +} + +impl Default for DualSlotRuntime { + fn default() -> Self { + Self::new() + } +} + +fn slot_ref(inner: &DualSlotRuntimeInner, slot: SlotKind) -> &SlotRuntime { + match slot { + SlotKind::Companion => &inner.companion, + SlotKind::Operations => &inner.operations, + } +} + +fn should_retry_astrbot(error: &AstrBotClientError) -> bool { + match error { + AstrBotClientError::Request(_) | AstrBotClientError::ChannelClosed => true, + AstrBotClientError::HttpStatus(status) => { + status.is_server_error() || status.as_u16() == 408 || status.as_u16() == 429 + } + _ => false, + } +} + +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, + remote_display_name: None, + authentication_type: desktop_protocol::AuthenticationType::DeviceToken, + 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); + } +} diff --git a/src-tauri/src/pet.rs b/src-tauri/src/pet.rs new file mode 100644 index 0000000..03ed72d --- /dev/null +++ b/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); + } +} diff --git a/src-tauri/src/policy.rs b/src-tauri/src/policy.rs new file mode 100644 index 0000000..c827dfe --- /dev/null +++ b/src-tauri/src/policy.rs @@ -0,0 +1,283 @@ +use desktop_protocol::{ActiveSlotKind, ConnectionProfile}; +use serde::Serialize; + +use crate::database::{ApplicationDatabase, DatabaseError}; + +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct DuplicateServerInstanceWarning { + pub code: &'static str, + pub server_instance_id: String, + pub profile_ids: Vec, + pub display_names: Vec, + pub message: &'static str, +} + +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct ConnectionPolicyStatus { + pub operations_switch_locked: bool, + pub active_operations_task_count: u32, + pub duplicate_server_instance_warnings: Vec, +} + +pub fn duplicate_server_instance_warnings( + profiles: &[ConnectionProfile], +) -> Vec { + let mut groups: Vec<(String, Vec<&ConnectionProfile>)> = Vec::new(); + + for profile in profiles { + let Some(server_instance_id) = profile + .server_instance_id + .as_deref() + .map(str::trim) + .filter(|value| !value.is_empty()) + else { + continue; + }; + + if let Some((_, members)) = groups + .iter_mut() + .find(|(existing, _)| existing == server_instance_id) + { + members.push(profile); + } else { + groups.push((server_instance_id.to_owned(), vec![profile])); + } + } + + groups + .into_iter() + .filter(|(_, members)| members.len() > 1) + .map(|(server_instance_id, members)| { + let mut ordered = members; + ordered.sort_by(|left, right| { + left.display_name + .cmp(&right.display_name) + .then_with(|| left.id.cmp(&right.id)) + }); + DuplicateServerInstanceWarning { + code: "duplicateServerInstance", + server_instance_id, + profile_ids: ordered.iter().map(|profile| profile.id.clone()).collect(), + display_names: ordered + .iter() + .map(|profile| profile.display_name.clone()) + .collect(), + message: "Multiple saved profiles point at the same server instance. Keep them separate and choose deliberately which profile to assign.", + } + }) + .collect() +} + +pub fn list_duplicate_server_instance_warnings( + database: &ApplicationDatabase, +) -> Result, DatabaseError> { + let profiles = database.list_profiles()?; + Ok(duplicate_server_instance_warnings(&profiles)) +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum AutoConnectValidationError { + SlotRequired, + SlotForbidden, + TooManyAutoConnectProfiles, + DuplicateAutoConnectSlot { slot: ActiveSlotKind }, +} + +impl AutoConnectValidationError { + pub fn message(self) -> &'static str { + match self { + Self::SlotRequired => { + "Automatic connection requires an explicit companion or operations slot." + } + Self::SlotForbidden => { + "A profile that is not set to auto-connect must not declare an auto-connect slot." + } + Self::TooManyAutoConnectProfiles => { + "At most two profiles may be configured for automatic connection." + } + Self::DuplicateAutoConnectSlot { .. } => { + "Two automatic-connection profiles cannot target the same slot." + } + } + } +} + +pub fn validate_auto_connect_configuration( + profiles: &[ConnectionProfile], + profile_id: Option<&str>, + auto_connect: bool, + auto_connect_slot: Option, +) -> Result<(), AutoConnectValidationError> { + if auto_connect { + let Some(slot) = auto_connect_slot else { + return Err(AutoConnectValidationError::SlotRequired); + }; + + let auto_connected = profiles + .iter() + .filter(|profile| profile_id != Some(profile.id.as_str())) + .filter(|profile| profile.auto_connect) + .collect::>(); + + if auto_connected.len() >= 2 { + return Err(AutoConnectValidationError::TooManyAutoConnectProfiles); + } + + if auto_connected + .iter() + .any(|profile| profile.auto_connect_slot == Some(slot)) + { + return Err(AutoConnectValidationError::DuplicateAutoConnectSlot { slot }); + } + } else if auto_connect_slot.is_some() { + return Err(AutoConnectValidationError::SlotForbidden); + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use desktop_protocol::{AstrBotProfileRole, AuthenticationType}; + + use super::*; + + fn profile( + id: &str, + name: &str, + auto_connect: bool, + slot: Option, + server_instance_id: Option<&str>, + ) -> ConnectionProfile { + ConnectionProfile { + id: id.into(), + display_name: name.into(), + role: AstrBotProfileRole::General, + base_url: "https://example.test/".into(), + event_stream_url: None, + authentication_type: AuthenticationType::DeviceToken, + 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, + remote_display_name: 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()] + ); + } +} diff --git a/src-tauri/src/profiles.rs b/src-tauri/src/profiles.rs index 22916f4..b26e5ef 100644 --- a/src-tauri/src/profiles.rs +++ b/src-tauri/src/profiles.rs @@ -1,353 +1,478 @@ -use desktop_protocol::{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}; - -const MAX_DISPLAY_NAME_CHARS: usize = 80; +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, +const REMOTE_USERNAME_PATTERN: &str = "ASCII letters and digits only, 3-32 characters."; + +#[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, + pub authentication_type: AuthenticationType, + #[serde(default)] + pub transport_kind: TransportKind, + #[serde(default)] + pub allow_insecure_http: bool, #[serde(default)] - pub event_stream_url: Option, - pub authentication_type: AuthenticationType, + pub remote_username: Option, #[serde(default)] - pub allow_insecure_http: bool, - #[serde(default)] - pub pinned_certificate_fingerprint: Option, -} - -#[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 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, ProfileCommandError> { - list_profiles(&database) -} - -#[tauri::command] -pub fn create_connection_profile( - database: tauri::State<'_, ApplicationDatabase>, - request: ConnectionProfileInput, -) -> Result { - create_profile(&database, request) -} - -#[tauri::command] -pub fn update_connection_profile( - database: tauri::State<'_, ApplicationDatabase>, - request: UpdateConnectionProfileRequest, -) -> Result { - 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, ProfileCommandError> { - database - .list_profiles() - .map_err(ProfileCommandError::database) -} - -fn create_profile( - database: &ApplicationDatabase, - request: ConnectionProfileInput, -) -> Result { - let normalized = normalize_input(request)?; - 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: 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: now.clone(), - updated_at: now, - }; - database - .create_profile(&profile) - .map_err(ProfileCommandError::database)?; - Ok(profile) -} - -fn update_profile( - database: &ApplicationDatabase, - request: UpdateConnectionProfileRequest, -) -> Result { - 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))?; - - 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.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 { - 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) + pub remote_display_name: Option, + #[serde(default)] + pub pinned_certificate_fingerprint: Option, + #[serde(default)] + pub auto_connect: bool, + #[serde(default)] + pub auto_connect_slot: Option, +} + +#[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, ProfileCommandError> { + list_profiles(&database) +} + +#[tauri::command] +pub fn create_connection_profile( + database: tauri::State<'_, ApplicationDatabase>, + request: ConnectionProfileInput, +) -> Result { + create_profile(&database, request) +} + +#[tauri::command] +pub fn update_connection_profile( + database: tauri::State<'_, ApplicationDatabase>, + request: UpdateConnectionProfileRequest, +) -> Result { + 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, ProfileCommandError> { + database + .list_profiles() + .map_err(ProfileCommandError::database) +} + +fn create_profile( + database: &ApplicationDatabase, + request: ConnectionProfileInput, +) -> Result { + let normalized = normalize_input(request)?; + let existing = database + .list_profiles() + .map_err(ProfileCommandError::database)?; + policy::validate_auto_connect_configuration( + &existing, + None, + normalized.auto_connect, + normalized.auto_connect_slot, + ) + .map_err(ProfileCommandError::auto_connect)?; + + let now = timestamp()?; + let profile = ConnectionProfile { + id: Uuid::new_v4().to_string(), + 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, + remote_display_name: normalized.remote_display_name, + 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 { + 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.remote_display_name = normalized.remote_display_name; + 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 { + 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.len() < 3 + || username.len() > 32 + || !username.bytes().all(|byte| byte.is_ascii_alphanumeric())) { - return Err(ProfileCommandError::validation( - "Display name must contain 1 to 80 visible characters.", - )); + return Err(ProfileCommandError::validation(REMOTE_USERNAME_PATTERN)); } - let base_url = normalize_url(&request.base_url, request.allow_insecure_http)?; - let event_stream_url = request - .event_stream_url + let remote_display_name = request + .remote_display_name .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, - }) -} - -fn normalize_url(value: &str, allow_insecure_http: bool) -> Result { - 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) -> Result, ProfileCommandError> { - let Some(value) = value else { - return Ok(None); - }; - let normalized = value - .trim() - .chars() - .filter(|character| *character != ':') - .flat_map(char::to_uppercase) - .collect::(); - if normalized.is_empty() { - return Ok(None); - } - if normalized.len() != 64 - || !normalized - .chars() - .all(|character| character.is_ascii_hexdigit()) + .map(str::to_owned); + if let Some(name) = &remote_display_name + && (name.chars().count() > MAX_DISPLAY_NAME_CHARS || name.chars().any(char::is_control)) { return Err(ProfileCommandError::validation( - "Pinned certificate fingerprint must be a SHA-256 hex value.", + "Remote nickname must contain 1 to 80 visible characters.", )); } - 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 { - 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, - } - } - - #[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/"); + 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, + remote_display_name, + 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 { + 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) -> Result, ProfileCommandError> { + let Some(value) = value else { + return Ok(None); + }; + let normalized = value + .trim() + .chars() + .filter(|character| *character != ':') + .flat_map(char::to_uppercase) + .collect::(); + 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 { + 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, + remote_display_name: Some("测试用户".into()), + 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, - }, - }, - ) - .expect("update profile"); - assert_eq!(updated.display_name, "Updated"); - 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::(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()); - } -} + assert_eq!(created.remote_display_name.as_deref(), Some("测试用户")); + 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, + remote_display_name: Some("更新昵称".into()), + 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!(updated.remote_display_name.as_deref(), Some("更新昵称")); + 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::(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()); + } +} diff --git a/src-tauri/src/quick_window.rs b/src-tauri/src/quick_window.rs new file mode 100644 index 0000000..75e6a42 --- /dev/null +++ b/src-tauri/src/quick_window.rs @@ -0,0 +1,107 @@ +use serde::{Deserialize, Serialize}; + +pub const QUICK_WINDOW_ID: &str = "quick-chat"; +pub const DEFAULT_WIDTH: u32 = 420; +pub const DEFAULT_HEIGHT: u32 = 620; +pub const MIN_WIDTH: u32 = 320; +pub const MIN_HEIGHT: u32 = 420; +pub const MAX_WIDTH: u32 = 900; +pub const MAX_HEIGHT: u32 = 1200; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct QuickWindowState { + pub x: i32, + pub y: i32, + pub width: u32, + pub height: u32, + pub monitor_name: Option, +} + +impl Default for QuickWindowState { + fn default() -> Self { + Self { + x: 0, + y: 0, + width: DEFAULT_WIDTH, + height: DEFAULT_HEIGHT, + monitor_name: None, + } + } +} + +impl QuickWindowState { + pub fn normalized(mut self) -> Self { + self.width = self.width.clamp(MIN_WIDTH, MAX_WIDTH); + self.height = self.height.clamp(MIN_HEIGHT, MAX_HEIGHT); + self + } + + pub fn clamp_to_work_area( + mut self, + area_x: i32, + area_y: i32, + area_width: u32, + area_height: u32, + ) -> Self { + self = self.normalized(); + let width = self.width.min(area_width.max(MIN_WIDTH)); + let height = self.height.min(area_height.max(MIN_HEIGHT)); + let max_x = area_x + area_width.saturating_sub(width) as i32; + let max_y = area_y + area_height.saturating_sub(height) as i32; + self.width = width; + self.height = height; + self.x = self.x.clamp(area_x, max_x.max(area_x)); + self.y = self.y.clamp(area_y, max_y.max(area_y)); + self + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn normalizes_invalid_size() { + let state = QuickWindowState { + x: 10, + y: 20, + width: 1, + height: 50_000, + monitor_name: None, + } + .normalized(); + + assert_eq!(state.width, MIN_WIDTH); + assert_eq!(state.height, MAX_HEIGHT); + } + + #[test] + fn clamps_position_to_work_area() { + let state = QuickWindowState { + x: -900, + y: 9000, + width: 500, + height: 600, + monitor_name: Some("DISPLAY1".into()), + } + .clamp_to_work_area(100, 200, 1600, 900); + + assert_eq!(state.x, 100); + assert_eq!(state.y, 500); + assert_eq!(state.monitor_name.as_deref(), Some("DISPLAY1")); + } + + #[test] + fn shrinks_window_when_work_area_is_smaller_than_limits() { + let state = QuickWindowState { + width: MAX_WIDTH, + height: MAX_HEIGHT, + ..Default::default() + } + .clamp_to_work_area(0, 0, 360, 460); + + assert_eq!(state.width, 360); + assert_eq!(state.height, 460); + } +} diff --git a/src-tauri/src/runtime_guards.rs b/src-tauri/src/runtime_guards.rs new file mode 100644 index 0000000..834c0be --- /dev/null +++ b/src-tauri/src/runtime_guards.rs @@ -0,0 +1,117 @@ +use std::collections::HashSet; +use std::sync::Mutex; + +use serde::Serialize; + +/// Tracks runtime conditions that gate Profile and slot mutations. +/// +/// This does not execute tools. It only records whether an operations-side +/// task is currently active so slot assignment can refuse unsafe switches. +#[derive(Default)] +pub struct RuntimeGuards { + operations_tasks: Mutex>, +} + +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct OperationsSwitchGuardStatus { + pub locked: bool, + pub active_task_count: u32, + pub active_task_ids: Vec, +} + +impl RuntimeGuards { + pub fn new() -> Self { + Self::default() + } + + pub fn begin_operations_task( + &self, + task_id: impl Into, + ) -> Result<(), RuntimeGuardError> { + let task_id = task_id.into(); + if task_id.trim().is_empty() { + return Err(RuntimeGuardError::InvalidTaskId); + } + + let mut tasks = self + .operations_tasks + .lock() + .map_err(|_| RuntimeGuardError::LockPoisoned)?; + tasks.insert(task_id); + Ok(()) + } + + pub fn end_operations_task(&self, task_id: &str) -> Result { + let mut tasks = self + .operations_tasks + .lock() + .map_err(|_| RuntimeGuardError::LockPoisoned)?; + Ok(tasks.remove(task_id)) + } + + pub fn operations_switch_locked(&self) -> Result { + let tasks = self + .operations_tasks + .lock() + .map_err(|_| RuntimeGuardError::LockPoisoned)?; + Ok(!tasks.is_empty()) + } + + pub fn operations_switch_status( + &self, + ) -> Result { + let tasks = self + .operations_tasks + .lock() + .map_err(|_| RuntimeGuardError::LockPoisoned)?; + let mut active_task_ids = tasks.iter().cloned().collect::>(); + active_task_ids.sort(); + Ok(OperationsSwitchGuardStatus { + locked: !active_task_ids.is_empty(), + active_task_count: active_task_ids.len() as u32, + active_task_ids, + }) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RuntimeGuardError { + InvalidTaskId, + LockPoisoned, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tracks_operations_task_lifecycle() { + let guards = RuntimeGuards::new(); + assert!(!guards.operations_switch_locked().expect("status")); + + guards.begin_operations_task("task-a").expect("begin task"); + assert!(guards.operations_switch_locked().expect("status")); + assert_eq!( + guards + .operations_switch_status() + .expect("status") + .active_task_count, + 1 + ); + + assert!(guards.end_operations_task("task-a").expect("end task")); + assert!(!guards.operations_switch_locked().expect("status")); + } + + #[test] + fn keeps_lock_while_any_operations_task_remains() { + let guards = RuntimeGuards::new(); + guards.begin_operations_task("task-a").expect("begin a"); + guards.begin_operations_task("task-b").expect("begin b"); + assert!(guards.end_operations_task("task-a").expect("end a")); + assert!(guards.operations_switch_locked().expect("status")); + assert!(guards.end_operations_task("task-b").expect("end b")); + assert!(!guards.operations_switch_locked().expect("status")); + } +} diff --git a/src-tauri/src/secure_store/mod.rs b/src-tauri/src/secure_store/mod.rs index 2bdd09d..a5969ed 100644 --- a/src-tauri/src/secure_store/mod.rs +++ b/src-tauri/src/secure_store/mod.rs @@ -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, +}; diff --git a/src-tauri/src/slots.rs b/src-tauri/src/slots.rs new file mode 100644 index 0000000..858fd34 --- /dev/null +++ b/src-tauri/src/slots.rs @@ -0,0 +1,298 @@ +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, SlotCommandError> { + list_slots(&database) +} + +#[tauri::command] +pub fn assign_connection_slot( + database: tauri::State<'_, ApplicationDatabase>, + guards: tauri::State<'_, RuntimeGuards>, + request: AssignConnectionSlotRequest, +) -> Result { + assign_slot(&database, &guards, request) +} + +#[tauri::command] +pub fn clear_connection_slot( + database: tauri::State<'_, ApplicationDatabase>, + guards: tauri::State<'_, RuntimeGuards>, + slot: ActiveSlotKind, +) -> Result { + clear_slot(&database, &guards, slot) +} + +fn list_slots(database: &ApplicationDatabase) -> Result, SlotCommandError> { + database + .list_connection_slots() + .map_err(SlotCommandError::database) +} + +fn assign_slot( + database: &ApplicationDatabase, + guards: &RuntimeGuards, + request: AssignConnectionSlotRequest, +) -> Result { + validate_profile_id(&request.profile_id)?; + ensure_operations_switch_allowed(guards, request.slot, Some(request.profile_id.as_str()))?; + database + .assign_connection_slot(request.slot, &request.profile_id, ×tamp()?) + .map_err(SlotCommandError::database) +} + +fn clear_slot( + database: &ApplicationDatabase, + guards: &RuntimeGuards, + slot: ActiveSlotKind, +) -> Result { + ensure_operations_switch_allowed(guards, slot, None)?; + database + .clear_connection_slot(slot, ×tamp()?) + .map_err(SlotCommandError::database) +} + +fn ensure_operations_switch_allowed( + guards: &RuntimeGuards, + slot: ActiveSlotKind, + next_profile_id: Option<&str>, +) -> Result<(), SlotCommandError> { + if slot != ActiveSlotKind::Operations { + return Ok(()); + } + + let locked = guards + .operations_switch_locked() + .map_err(|_| SlotCommandError { + code: "databaseUnavailable", + message: "The operations switch guard is unavailable.", + })?; + if locked { + return Err(SlotCommandError::operations_switch_locked()); + } + + // Companion may still change while operations work is idle; this check is + // intentionally scoped to the operations slot only. + let _ = next_profile_id; + Ok(()) +} + +fn validate_profile_id(id: &str) -> Result<(), SlotCommandError> { + if Uuid::parse_str(id).is_err() { + return Err(SlotCommandError::validation( + "Connection profile ID is invalid.", + )); + } + Ok(()) +} + +fn timestamp() -> Result { + OffsetDateTime::now_utc() + .format(&Rfc3339) + .map_err(|_| SlotCommandError { + code: "clockUnavailable", + message: "The system clock could not produce a slot timestamp.", + }) +} + +#[cfg(test)] +mod tests { + use desktop_protocol::{AstrBotProfileRole, AuthenticationType, ConnectionProfile}; + + use super::*; + + fn profile(index: usize) -> ConnectionProfile { + ConnectionProfile { + id: format!("00000000-0000-4000-8000-{index:012}"), + display_name: format!("Profile {index}"), + role: AstrBotProfileRole::General, + base_url: format!("https://example-{index}.test/"), + event_stream_url: None, + authentication_type: AuthenticationType::DeviceToken, + 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, + remote_display_name: 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::(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"); + } +} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 27b3b8e..3dd71ad 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,39 +1,58 @@ -{ - "$schema": "https://schema.tauri.app/config/2", - "productName": "AstrBot Desktop", - "version": "0.1.0-alpha.1", - "identifier": "com.yokiirobw.astrbot-desktop", - "build": { - "beforeDevCommand": "npm run dev", - "devUrl": "http://127.0.0.1:1420", - "beforeBuildCommand": "npm run build", - "frontendDist": "../dist" - }, - "app": { - "windows": [ - { - "label": "main", - "title": "AstrBot Desktop", - "width": 1100, - "height": 760, - "minWidth": 720, - "minHeight": 520, - "center": true, - "resizable": true - } - ], - "security": { - "csp": "default-src 'self'; connect-src ipc: http://ipc.localhost http://127.0.0.1:*; img-src 'self' asset: http://asset.localhost data:; style-src 'self' 'unsafe-inline'; script-src 'self'" - } - }, - "bundle": { - "active": true, - "targets": ["nsis"], - "icon": [ - "icons/32x32.png", - "icons/128x128.png", - "icons/128x128@2x.png", - "icons/icon.ico" - ] - } -} +{ + "$schema": "https://schema.tauri.app/config/2", + "productName": "AstrBot Desktop", + "version": "0.1.0-alpha.1", + "identifier": "com.yokiirobw.astrbot-desktop", + "build": { + "beforeDevCommand": "npm run dev", + "devUrl": "http://127.0.0.1:1420", + "beforeBuildCommand": "npm run build", + "frontendDist": "../dist" + }, + "app": { + "windows": [ + { + "label": "main", + "title": "AstrBot Desktop", + "width": 1100, + "height": 760, + "minWidth": 720, + "minHeight": 520, + "center": true, + "resizable": true + }, + { + "label": "desktop-pet", + "title": "AstrBot Pet", + "url": "index.html?view=pet", + "width": 180, + "height": 220, + "resizable": false, + "decorations": false, + "shadow": false, + "transparent": true, + "alwaysOnTop": true, + "skipTaskbar": true, + "visible": false, + "x": 120, + "y": 120, + "create": true + } + ], + "security": { + "csp": "default-src \u0027self\u0027; connect-src ipc: http://ipc.localhost http://127.0.0.1:*; img-src \u0027self\u0027 asset: http://asset.localhost data:; style-src \u0027self\u0027 \u0027unsafe-inline\u0027; script-src \u0027self\u0027" + } + }, + "bundle": { + "active": true, + "targets": [ + "nsis" + ], + "icon": [ + "icons/32x32.png", + "icons/128x128.png", + "icons/128x128@2x.png", + "icons/icon.ico" + ] + } +} diff --git a/src/App.test.tsx b/src/App.test.tsx index 0b29552..7644f6b 100644 --- a/src/App.test.tsx +++ b/src/App.test.tsx @@ -3,6 +3,12 @@ import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { App } from "./App"; +import type { + ActiveSlotKind, + AssignConnectionSlotRequest, + ConnectionPolicyStatus, + ConnectionSlot, +} from "./types/connection"; import type { ConnectionProfile, ConnectionProfileInput, @@ -18,27 +24,104 @@ const bootstrapStatus = { platform: "windows", rustCore: "ready", protocolVersion: "desktop-v1alpha1", - databaseSchemaVersion: 2, + databaseSchemaVersion: 3, }; +const emptySlots: ConnectionSlot[] = [ + { + slot: "companion", + state: "disconnected", + unreadCount: 0, + }, + { + slot: "operations", + state: "disconnected", + unreadCount: 0, + }, +]; + +const emptyPolicy: ConnectionPolicyStatus = { + operationsSwitchLocked: false, + activeOperationsTaskCount: 0, + duplicateServerInstanceWarnings: [], +}; + +function openConnectionsPage() { + fireEvent.click(screen.getByRole("button", { name: /连接/ })); +} + +function openDiagnosticsPage() { + fireEvent.click(screen.getByRole("button", { name: /诊断与设置/ })); +} + +function mockBaseCommands(options?: { + profiles?: ConnectionProfile[]; + slots?: ConnectionSlot[]; + policy?: ConnectionPolicyStatus; +}) { + const profiles = options?.profiles ?? []; + let slots = options?.slots ?? emptySlots; + let policy = options?.policy ?? emptyPolicy; + + vi.mocked(invoke).mockImplementation(async (command, args) => { + if (command === "bootstrap_status") { + return bootstrapStatus; + } + if (command === "list_connection_profiles") { + return profiles; + } + if (command === "list_connection_slots") { + return slots; + } + if (command === "connection_policy_status") { + return policy; + } + if (command === "assign_connection_slot") { + const { request } = args as { request: AssignConnectionSlotRequest }; + const saved: ConnectionSlot = { + slot: request.slot, + profileId: request.profileId, + state: "disconnected", + unreadCount: 0, + }; + slots = slots.map((slot) => (slot.slot === request.slot ? saved : slot)); + return saved; + } + if (command === "clear_connection_slot") { + const { slot } = args as { slot: ActiveSlotKind }; + const saved: ConnectionSlot = { + slot, + state: "disconnected", + unreadCount: 0, + }; + slots = slots.map((item) => (item.slot === slot ? saved : item)); + return saved; + } + throw new Error(`Unexpected command: ${command}`); + }); + + return { + setPolicy(next: ConnectionPolicyStatus) { + policy = next; + }, + getSlots() { + return slots; + }, + }; +} + describe("App", () => { beforeEach(() => { - vi.mocked(invoke).mockImplementation(async (command) => { - if (command === "bootstrap_status") { - return bootstrapStatus; - } - if (command === "list_connection_profiles") { - return []; - } - throw new Error(`Unexpected command: ${command}`); - }); + mockBaseCommands(); }); it("renders the verified Rust bootstrap status", async () => { render(); + openDiagnosticsPage(); expect(await screen.findByText("ready")).toBeInTheDocument(); expect(screen.getByText("desktop-v1alpha1")).toBeInTheDocument(); + openConnectionsPage(); expect(screen.getByText("连接 Profile")).toBeInTheDocument(); }); @@ -53,12 +136,18 @@ describe("App", () => { if (command === "list_connection_profiles") { return []; } + if (command === "list_connection_slots") { + return emptySlots; + } + if (command === "connection_policy_status") { + return emptyPolicy; + } throw new Error(`Unexpected command: ${command}`); }); render(); - expect(await screen.findByText(/IPC unavailable:/)).toBeInTheDocument(); + expect(await screen.findByText(/IPC .*不可用:/)).toBeInTheDocument(); expect(screen.queryByText("unexpected")).not.toBeInTheDocument(); }); @@ -71,12 +160,18 @@ describe("App", () => { if (command === "list_connection_profiles") { return profiles; } + if (command === "list_connection_slots") { + return emptySlots; + } + if (command === "connection_policy_status") { + return emptyPolicy; + } if (command === "create_connection_profile") { const { request } = args as { request: ConnectionProfileInput }; const created: ConnectionProfile = { id: "2bdedc10-d804-4da5-8e92-39dd7f175d7a", ...request, - autoConnect: false, + transportKind: "desktop-v1", createdAt: "2026-07-18T02:00:00Z", updatedAt: "2026-07-18T02:00:00Z", }; @@ -109,6 +204,7 @@ describe("App", () => { vi.spyOn(window, "confirm").mockReturnValue(true); render(); + openConnectionsPage(); expect(await screen.findByText("尚未保存 Profile。")).toBeInTheDocument(); fireEvent.change(screen.getByLabelText("显示名称"), { @@ -126,6 +222,14 @@ describe("App", () => { await screen.findByText("已创建 Profile:家庭运维"), ).toBeInTheDocument(); expect(screen.getByLabelText("编辑 家庭运维")).toBeEnabled(); + expect(invoke).toHaveBeenCalledWith( + "create_connection_profile", + expect.objectContaining({ + request: expect.objectContaining({ + autoConnect: false, + }), + }), + ); fireEvent.click(screen.getByLabelText("编辑 家庭运维")); fireEvent.change(screen.getByLabelText("显示名称"), { @@ -155,4 +259,205 @@ describe("App", () => { }), ); }); + + it("assigns different profiles to the two fixed slots", async () => { + const profiles: ConnectionProfile[] = [ + { + id: "2bdedc10-d804-4da5-8e92-39dd7f175d7a", + displayName: "陪伴实例", + role: "companion", + baseUrl: "https://companion.example.test/", + authenticationType: "device-token", + transportKind: "desktop-v1", + allowInsecureHttp: false, + autoConnect: false, + createdAt: "2026-07-19T02:00:00Z", + updatedAt: "2026-07-19T02:00:00Z", + }, + { + id: "f272aef0-0a89-4f98-b950-b2f1f309631b", + displayName: "运维实例", + role: "operations", + baseUrl: "https://operations.example.test/", + authenticationType: "api-key", + transportKind: "desktop-v1", + allowInsecureHttp: false, + autoConnect: false, + createdAt: "2026-07-19T02:00:00Z", + updatedAt: "2026-07-19T02:00:00Z", + }, + ]; + + mockBaseCommands({ profiles }); + + render(); + openConnectionsPage(); + + fireEvent.change(await screen.findByLabelText("陪伴 Profile"), { + target: { value: profiles[0].id }, + }); + expect( + await screen.findByText("已将陪伴实例分配到陪伴槽位。"), + ).toBeInTheDocument(); + + fireEvent.change(screen.getByLabelText("运维 Profile"), { + target: { value: profiles[1].id }, + }); + expect( + await screen.findByText("已将运维实例分配到运维槽位。"), + ).toBeInTheDocument(); + expect(invoke).toHaveBeenCalledWith("assign_connection_slot", { + request: { + slot: "operations", + profileId: profiles[1].id, + }, + }); + }); + + it("saves auto-connect configuration without activating network sessions", async () => { + let profiles: ConnectionProfile[] = []; + vi.mocked(invoke).mockImplementation(async (command, args) => { + if (command === "bootstrap_status") { + return bootstrapStatus; + } + if (command === "list_connection_profiles") { + return profiles; + } + if (command === "list_connection_slots") { + return emptySlots; + } + if (command === "connection_policy_status") { + return emptyPolicy; + } + if (command === "create_connection_profile") { + const { request } = args as { request: ConnectionProfileInput }; + const created: ConnectionProfile = { + id: "2bdedc10-d804-4da5-8e92-39dd7f175d7a", + ...request, + transportKind: "desktop-v1", + createdAt: "2026-07-19T03:00:00Z", + updatedAt: "2026-07-19T03:00:00Z", + }; + profiles = [created]; + return created; + } + throw new Error(`Unexpected command: ${command}`); + }); + + render(); + openConnectionsPage(); + expect(await screen.findByText("尚未保存 Profile。")).toBeInTheDocument(); + + fireEvent.change(screen.getByLabelText("显示名称"), { + target: { value: "自动陪伴" }, + }); + fireEvent.change(screen.getByLabelText("角色"), { + target: { value: "companion" }, + }); + fireEvent.change(screen.getByLabelText("REST 基础 URL"), { + target: { value: "https://companion.example.test" }, + }); + fireEvent.click( + screen.getByLabelText("启动时自动连接(不会在本阶段真正建立网络会话)"), + ); + fireEvent.change(screen.getByLabelText("自动连接槽位"), { + target: { value: "companion" }, + }); + fireEvent.click(screen.getByRole("button", { name: "保存 Profile" })); + + expect( + await screen.findByText("已创建 Profile:自动陪伴"), + ).toBeInTheDocument(); + expect(screen.getByText("自动连接:陪伴")).toBeInTheDocument(); + expect(invoke).toHaveBeenCalledWith("create_connection_profile", { + request: { + displayName: "自动陪伴", + role: "companion", + baseUrl: "https://companion.example.test", + authenticationType: "device-token", + transportKind: "desktop-v1", + allowInsecureHttp: false, + autoConnect: true, + autoConnectSlot: "companion", + }, + }); + }); + + it("shows duplicate server-instance warnings and locks the operations slot", async () => { + const profiles: ConnectionProfile[] = [ + { + id: "2bdedc10-d804-4da5-8e92-39dd7f175d7a", + displayName: "陪伴实例", + role: "companion", + baseUrl: "https://companion.example.test/", + authenticationType: "device-token", + transportKind: "desktop-v1", + allowInsecureHttp: false, + autoConnect: false, + serverInstanceId: "server-shared", + createdAt: "2026-07-19T02:00:00Z", + updatedAt: "2026-07-19T02:00:00Z", + }, + { + id: "f272aef0-0a89-4f98-b950-b2f1f309631b", + displayName: "运维实例", + role: "operations", + baseUrl: "https://operations.example.test/", + authenticationType: "api-key", + transportKind: "desktop-v1", + allowInsecureHttp: false, + autoConnect: false, + serverInstanceId: "server-shared", + createdAt: "2026-07-19T02:00:00Z", + updatedAt: "2026-07-19T02:00:00Z", + }, + ]; + + mockBaseCommands({ + profiles, + slots: [ + { + slot: "companion", + profileId: profiles[0].id, + state: "disconnected", + unreadCount: 0, + }, + { + slot: "operations", + profileId: profiles[1].id, + state: "disconnected", + unreadCount: 0, + }, + ], + policy: { + operationsSwitchLocked: true, + activeOperationsTaskCount: 1, + duplicateServerInstanceWarnings: [ + { + code: "duplicateServerInstance", + serverInstanceId: "server-shared", + profileIds: [profiles[0].id, profiles[1].id], + displayNames: ["陪伴实例", "运维实例"], + message: + "Multiple saved profiles point at the same server instance. Keep them separate and choose deliberately which profile to assign.", + }, + ], + }, + }); + + render(); + openConnectionsPage(); + + expect( + await screen.findByLabelText("重复服务器实例提示"), + ).toBeInTheDocument(); + expect( + screen.getByText(/服务器实例 server-shared 被多个 Profile 引用/), + ).toBeInTheDocument(); + expect(screen.getByLabelText("运维 Profile")).toBeDisabled(); + expect(screen.getByLabelText("陪伴 Profile")).toBeEnabled(); + expect( + screen.getByText(/运维任务进行中,已锁定运维槽位切换(\s*1 个活动任务)/), + ).toBeInTheDocument(); + }); }); diff --git a/src/App.tsx b/src/App.tsx index f5199ab..65be483 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,20 +1,75 @@ import { invoke } from "@tauri-apps/api/core"; -import { useCallback, useEffect, useState } from "react"; +import { listen } from "@tauri-apps/api/event"; +import { useCallback, useEffect, useRef, useState } from "react"; +import { ChatPanel } from "./features/chat/ChatPanel"; +import { StatusBubble } from "./features/chat/StatusBubble"; import { ProfileManager } from "./features/profiles/ProfileManager"; +import { PetPackImporter } from "./features/pet/PetPackImporter"; +import { connectionRuntimeStatusSchema } from "./features/chat/types"; +import aemeathSpritesheet from "./features/pet/assets/aemeath/aemeath-spritesheet.png?inline"; import { bootstrapStatusSchema, type BootstrapStatus } from "./types/bootstrap"; +type PageKey = "chat" | "connections" | "desktop" | "pet" | "diagnostics"; +type ChatLayout = "single" | "focus-companion" | "focus-operations"; +type ChatSlot = "companion" | "operations"; +type PetDisplayMode = "app-ui" | "desktop-floating"; + const initialStatus: BootstrapStatus = { appVersion: "unknown", platform: "unknown", rustCore: "pending", protocolVersion: "desktop-v1alpha1", - databaseSchemaVersion: 2, + databaseSchemaVersion: 4, }; +const AEMEATH_SPRITESHEET = aemeathSpritesheet; + +const AEMEATH_FRAMES: Record<"idle" | "working" | "resting" | "speaking" | "error", number[]> = { + idle: [0, 1, 2, 3, 4, 5], + working: [80, 81, 82, 83, 84, 85, 86, 87, 104, 105, 106, 107, 108, 109, 110, 111], + resting: [48, 49, 50, 51, 52, 53], + speaking: [72, 73, 74, 75, 76, 77, 78, 79], + error: [40, 41, 42, 43, 44, 45, 46, 47], +}; + +const navigation: Array<{ key: PageKey; label: string; description: string }> = + [ + { key: "chat", label: "聊天", description: "陪伴与运维对话" }, + { key: "connections", label: "连接", description: "实例与槽位管理" }, + { key: "desktop", label: "桌面行为", description: "快速聊天与状态气泡" }, + { key: "pet", label: "桌宠", description: "形象与活动范围" }, + { + key: "diagnostics", + label: "诊断与设置", + description: "运行状态与安全边界", + }, + ]; + export function App() { + const params = new URLSearchParams(window.location.search); + const view = params.get("view"); + const isQuickView = view === "quick"; + const isBubbleView = view === "bubble"; + const isPetView = view === "pet" || window.location.hash === "#pet" || document.documentElement.dataset.astrbotPet === "true"; + const quickSlot = params.get("slot"); + const [page, setPage] = useState("chat"); const [status, setStatus] = useState(initialStatus); const [error, setError] = useState(null); + const [chatLayout, setChatLayout] = useState("single"); + const [quickTarget, setQuickTarget] = useState(() => + localStorage.getItem("astrbot.quickTarget") === "operations" + ? "operations" + : "companion", + ); + const [bubbleTarget, setBubbleTarget] = useState<"main" | "quick">(() => + localStorage.getItem("astrbot.bubbleTarget") === "quick" ? "quick" : "main", + ); + const [petDisplayMode, setPetDisplayMode] = useState(() => + localStorage.getItem("astrbot.petDisplayMode") === "desktop-floating" + ? "desktop-floating" + : "app-ui", + ); const refreshStatus = useCallback(async () => { try { @@ -30,52 +85,647 @@ export function App() { void refreshStatus(); }, [refreshStatus]); + useEffect(() => { + if (isBubbleView || isPetView || isQuickView) return; + const command = petDisplayMode === "desktop-floating" ? "open_pet_window" : "close_pet_window"; + void invoke(command).catch((reason) => { + setError(reason instanceof Error ? reason.message : String(reason)); + }); + }, [isBubbleView, isPetView, isQuickView, petDisplayMode]); + + if (isBubbleView) return ; + if (isPetView) return ; + if (isQuickView) { + return ( +
+ +
+ ); + } + return (
-
-

P01 · foundation

-

AstrBot Desktop

-

- 双实例陪伴与本机助手的安全 Windows 客户端工程底座。 -

-
+ +
+ + {error ?

IPC 暂不可用:{error}

: null} + {page === "chat" ? ( + + void invoke("open_quick_chat_window", { slot: quickTarget }) + } + /> + ) : null} + {page === "connections" ? : null} + {page === "desktop" ? ( + { + setBubbleTarget(value); + localStorage.setItem("astrbot.bubbleTarget", value); + }} + onQuickTargetChange={(value) => { + setQuickTarget(value); + localStorage.setItem("astrbot.quickTarget", value); + }} + onOpenQuickChat={() => + void invoke("open_quick_chat_window", { slot: quickTarget }) + } + /> + ) : null} + {page === "pet" ? ( + { + setPetDisplayMode(value); + localStorage.setItem("astrbot.petDisplayMode", value); + }} + /> + ) : null} + {page === "diagnostics" ? ( + void refreshStatus()} + /> + ) : null} +
+ {petDisplayMode === "app-ui" ? : null} +
+ ); +} + +function InAppPetOverlay() { + const [visible, setVisible] = useState(true); + const [position, setPosition] = useState(() => { + try { + const saved = JSON.parse(localStorage.getItem("astrbot.petPosition") ?? "null"); + return saved && typeof saved.x === "number" && typeof saved.y === "number" + ? saved + : { x: 24, y: 96 }; + } catch { + return { x: 24, y: 96 }; + } + }); + const dragRef = useRef<{ pointerId: number; offsetX: number; offsetY: number } | null>(null); + + const savePosition = (x: number, y: number) => { + const next = { + x: Math.max(0, Math.min(x, window.innerWidth - 188)), + y: Math.max(0, Math.min(y, window.innerHeight - 226)), + }; + setPosition(next); + localStorage.setItem("astrbot.petPosition", JSON.stringify(next)); + }; + + useEffect(() => { + let unlisten: (() => void) | undefined; + void listen("pet-hide-requested", () => setVisible(false)).then((cleanup) => { + unlisten = cleanup; + }); + return () => unlisten?.(); + }, []); + + return visible ? ( +
{ + event.preventDefault(); + void invoke("show_pet_context_menu"); + }} + onPointerDown={(event) => { + if (event.button !== 0) return; + event.currentTarget.setPointerCapture(event.pointerId); + dragRef.current = { + pointerId: event.pointerId, + offsetX: event.clientX - position.x, + offsetY: event.clientY - position.y, + }; + }} + onPointerMove={(event) => { + if (dragRef.current?.pointerId !== event.pointerId) return; + savePosition( + event.clientX - dragRef.current.offsetX, + event.clientY - dragRef.current.offsetY, + ); + }} + onPointerUp={(event) => { + if (dragRef.current?.pointerId === event.pointerId) dragRef.current = null; + }} + onPointerCancel={() => { + dragRef.current = null; + }} + > + +
+ ) : null; +} + +function navIcon(page: PageKey) { + return { + chat: "⌁", + connections: "◎", + desktop: "◈", + pet: "✦", + diagnostics: "⚙", + }[page]; +} + +function PageHeader({ page }: { page: PageKey }) { + const current = navigation.find((item) => item.key === page) ?? navigation[0]; + return ( +
+
+

AstrBot Desktop

+

{current.label}

+

+ {current.description},所有本机能力都经过客户端权限边界。 +

+
+
+ + 双槽位架构 +
+
+ ); +} + +function ChatPage({ + chatLayout, + quickTarget, + onLayoutChange, + onOpenQuickChat, +}: { + chatLayout: ChatLayout; + quickTarget: ChatSlot; + onLayoutChange: (layout: ChatLayout) => void; + onOpenQuickChat: () => void; +}) { + return ( +
+
+
+ Conversation hub +

今天想和哪个实例聊天?

+

陪伴实例适合日常交流,运维实例用于经过确认的本机诊断提案。

+
+ +
+
+
+
+ Workspace view + 对话布局 +
+
+ onLayoutChange("single")} + > + 单面板 + + onLayoutChange("focus-companion")} + > + 聚焦陪伴 + + onLayoutChange("focus-operations")} + > + 聚焦运维 + +
+ + 快速聊天目标:{slotLabel(quickTarget)} + +
+ +
+
+ ); +} + +function LayoutButton({ + active, + children, + onClick, +}: { + active: boolean; + children: React.ReactNode; + onClick: () => void; +}) { + return ( + + ); +} + +function DesktopBehaviorPage({ + bubbleTarget, + quickTarget, + onBubbleTargetChange, + onQuickTargetChange, + onOpenQuickChat, +}: { + bubbleTarget: "main" | "quick"; + quickTarget: ChatSlot; + onBubbleTargetChange: (value: "main" | "quick") => void; + onQuickTargetChange: (value: ChatSlot) => void; + onOpenQuickChat: () => void; +}) { + return ( +
+
+ + + + + + +
+ + 气泡状态显示已预留 +
+
+
+
+ Desktop companion +

后续桌面能力

+
+ 托盘与单实例 + 窗口置顶开关 + 多显示器策略 + 游戏模式靠边活动 +
+

+ 这些能力先保留为独立设置区,后续接入 Rust + 本机能力层,不会与聊天状态混在一起。 +

+
+
+ ); +} + +function PetPage({ + displayMode, + onDisplayModeChange, +}: { + displayMode: PetDisplayMode; + onDisplayModeChange: (value: PetDisplayMode) => void; +}) { + return ( +
+ + {displayMode === "app-ui" ? ( +
+
+ App UI +

应用内活动桌宠

+

桌宠已叠加在主界面上,可直接拖动;关闭后可重新打开应用。

+
+
+ ) : null} +
+ + + + + + + + {displayMode === "desktop-floating" ? ( + + ) : ( + 应用内活动桌宠已显示,可直接拖动 + )} + +
+
+ ); +} + +function DesktopPetView({ embedded = false }: { embedded?: boolean }) { + const [state, setState] = useState<"idle" | "working" | "resting" | "speaking" | "error">("idle"); + const [frameIndex, setFrameIndex] = useState(0); + const [spriteReady, setSpriteReady] = useState(false); + const [spriteError, setSpriteError] = useState(null); + const [gameMode, setGameMode] = useState(false); + const spriteImageRef = useRef(null); + const spriteCanvasRef = useRef(null); + + useEffect(() => { + if (embedded) return; + document.documentElement.classList.add("pet-view"); + return () => document.documentElement.classList.remove("pet-view"); + }, [embedded]); + + useEffect(() => { + let unlisten: (() => void) | undefined; + void listen("pet-game-mode-toggle", () => setGameMode((current) => !current)).then((cleanup) => { + unlisten = cleanup; + }); + return () => unlisten?.(); + }, []); + + useEffect(() => { + const image = new Image(); + image.onload = () => { + spriteImageRef.current = image; + setSpriteError(null); + setSpriteReady(true); + }; + image.onerror = () => { + setSpriteError("????????"); + }; + image.src = AEMEATH_SPRITESHEET; + return () => { + image.onload = null; + }; + }, []); + + useEffect(() => { + let cancelled = false; + const refreshPetState = async () => { + try { + const result = connectionRuntimeStatusSchema.parse( + await invoke("connection_runtime_status"), + ); + if (cancelled) return; + const states = [result.companion.state, result.operations.state]; + if (states.includes("authExpired") || states.includes("fatalError")) { + setState("error"); + } else if (states.includes("syncing")) { + setState("working"); + } else if (states.includes("reconnecting")) { + setState("speaking"); + } else if (states.every((value) => value === "disconnected" || value === "offline")) { + setState("resting"); + } else { + setState("idle"); + } + } catch { + if (!cancelled) setState("idle"); + } + }; + void refreshPetState(); + const refreshTimer = window.setInterval(() => void refreshPetState(), 2000); + const timer = window.setInterval(() => { + setState((current) => (current === "idle" ? "resting" : current === "resting" ? "idle" : current)); + }, 4200); + return () => { + cancelled = true; + window.clearInterval(refreshTimer); + window.clearInterval(timer); + }; + }, []); + + useEffect(() => { + setFrameIndex(0); + const frames = AEMEATH_FRAMES[state]; + const timer = window.setInterval(() => { + setFrameIndex((current) => (current + 1) % frames.length); + }, state === "resting" ? 180 : 125); + return () => window.clearInterval(timer); + }, [state]); + + const frame = AEMEATH_FRAMES[state][frameIndex % AEMEATH_FRAMES[state].length]; + const frameRow = Math.floor(frame / 8); + const frameColumn = frame % 8; + + useEffect(() => { + const canvas = spriteCanvasRef.current; + const image = spriteImageRef.current; + if (!canvas || !image || !spriteReady) return; + const context = canvas.getContext("2d"); + if (!context) { + setSpriteError("?? Canvas ????"); + return; + } + try { + context.clearRect(0, 0, 192, 208); + context.imageSmoothingEnabled = false; + context.drawImage(image, frameColumn * 192, frameRow * 208, 192, 208, 0, 0, 192, 208); + } catch (reason) { + setSpriteError(reason instanceof Error ? reason.message : "??????"); + } + }, [frameColumn, frameRow, spriteReady]); + + return ( +
{ + event.preventDefault(); + void invoke("show_pet_context_menu"); + }} + > +
+ setSpriteReady(true)} + onError={() => setSpriteError("????????")} + style={{ + left: -(frameColumn * 192), + top: -(frameRow * 208), + }} + /> + +
+ {spriteError ? {spriteError} : null} + {!spriteReady && !spriteError ? Loading pet... : null} + {state === "working" ? "正在写写画画" : state === "resting" ? "休息中" : state === "speaking" ? "正在回应" : state === "error" ? "需要重新登录或检查连接" : "陪伴中"} +
+ ); +} + +function DiagnosticsPage({ + status, + onRefresh, +}: { + status: BootstrapStatus; + onRefresh: () => void; +}) { + return ( +
+
- - - {error ?

IPC unavailable: {error}

: null} -
-

安全边界

+ Security boundary +

本机能力保持可审计

  • 凭据只在 Rust 与 Windows 安全存储之间流动。
  • -
  • 两个 REST/SSE 槽位保持独立状态与事件来源。
  • -
  • 本机操作必须经过白名单、策略与用户授权。
  • -
  • 文件事务默认保留源文件,且不会静默覆盖。
  • +
  • 两个 REST/SSE 槽位保持独立状态、会话、消息与未读数。
  • +
  • 本机操作必须经过白名单、角色、路径和用户授权。
  • +
  • 文件事务默认保留源文件,不静默覆盖目标。
- - - - +
); } +function SettingCard({ + title, + description, + children, +}: { + title: string; + description: string; + children: React.ReactNode; +}) { + return ( +
+
+ Settings +

{title}

+

{description}

+
+
{children}
+
+ ); +} + +function slotLabel(slot: ChatSlot) { + return slot === "companion" ? "陪伴实例" : "运维实例"; +} + interface StatusCardProps { label: string; value: string; } - function StatusCard({ label, value }: StatusCardProps) { return (
diff --git a/src/features/chat/ChatPanel.tsx b/src/features/chat/ChatPanel.tsx new file mode 100644 index 0000000..b500349 --- /dev/null +++ b/src/features/chat/ChatPanel.tsx @@ -0,0 +1,631 @@ +import { invoke } from "@tauri-apps/api/core"; +import { useCallback, useEffect, useMemo, useState } from "react"; + +import { + astrbotAttachmentSchema, + astrbotCapabilitySnapshotSchema, + boundRuntimeEventSchema, + chatSessionSchema, + connectionRuntimeStatusSchema, + type AstrBotAttachment, + type AstrBotCapabilitySnapshot, + type AstrBotModelOption, + type BoundRuntimeEvent, + remoteChatSessionSchema, + type ChatMessage, + type ChatSlot, + type RemoteChatSession, + type ConnectionRuntimeStatus, + storedChatMessageSchema, +} from "./types"; + +const emptyStatus: ConnectionRuntimeStatus = { + companion: { slot: "companion", state: "disconnected" }, + operations: { slot: "operations", state: "disconnected" }, +}; + +function payloadString( + event: BoundRuntimeEvent, + key: string, +): string | undefined { + if (!event.payload || typeof event.payload !== "object") return undefined; + const value = (event.payload as Record)[key]; + return typeof value === "string" ? value : undefined; +} + +export interface ChatPanelProps { + fixedSlot?: ChatSlot; +} + +export function ChatPanel({ fixedSlot }: ChatPanelProps) { + const [status, setStatus] = useState(emptyStatus); + const [messages, setMessages] = useState([]); + const [remoteSessions, setRemoteSessions] = useState([]); + const [activeSlot, setActiveSlot] = useState( + fixedSlot ?? "companion", + ); + const selectedSlot = fixedSlot ?? activeSlot; + const selectedSnapshot = status[selectedSlot]; + const selectedProfileId = selectedSnapshot.profileId; + const selectedServerInstanceId = selectedSnapshot.serverInstanceId; + const selectedSessionId = selectedSnapshot.activeSessionId; + const selectedTransport = selectedSnapshot.transport; + const [draft, setDraft] = useState(""); + const [error, setError] = useState(null); + const [capabilities, setCapabilities] = + useState(null); + const [selectedModel, setSelectedModel] = useState(""); + const [pendingAttachments, setPendingAttachments] = useState< + AstrBotAttachment[] + >([]); + const [uploading, setUploading] = useState(false); + const [unreadCounts, setUnreadCounts] = useState>({ + companion: 0, + operations: 0, + }); + const activeMessages = useMemo( + () => + messages.filter( + (item) => + item.slot === selectedSlot && + (!status[selectedSlot].activeSessionId || + item.sessionId === status[selectedSlot].activeSessionId), + ), + [messages, selectedSlot, status], + ); + + const refresh = useCallback(async () => { + try { + const result = await invoke("connection_runtime_status"); + setStatus(connectionRuntimeStatusSchema.parse(result)); + setError(null); + return true; + } catch (reason) { + setError(reason instanceof Error ? reason.message : String(reason)); + return false; + } + }, []); + + const drainEvents = useCallback(async () => { + try { + const result = await invoke("drain_connection_runtime_events", { + request: { limit: 64 }, + }); + const events = boundRuntimeEventSchema.array().parse(result); + if (events.length > 0) + setMessages((current) => applyRuntimeEvents(current, events)); + } catch { + // Keep the browser preview usable without Rust IPC. + } + }, []); + + useEffect(() => { + const snapshot = { + profileId: selectedProfileId, + serverInstanceId: selectedServerInstanceId, + activeSessionId: selectedSessionId, + transport: selectedTransport, + }; + if (!snapshot.profileId || !snapshot.serverInstanceId) return; + let cancelled = false; + void invoke("list_chat_sessions", { + request: { + profileId: snapshot.profileId, + serverInstanceId: snapshot.serverInstanceId, + }, + }) + .then((result) => { + if (cancelled) return; + const sessions = chatSessionSchema.array().parse(result); + setUnreadCounts((current) => ({ + ...current, + [selectedSlot]: sessions.reduce( + (total, session) => total + session.unreadCount, + 0, + ), + })); + }) + .catch(() => undefined); + return () => { + cancelled = true; + }; + }, [ + selectedSlot, + selectedProfileId, + selectedServerInstanceId, + selectedSessionId, + selectedTransport, + ]); + + useEffect(() => { + const snapshot = { + profileId: selectedProfileId, + serverInstanceId: selectedServerInstanceId, + activeSessionId: selectedSessionId, + transport: selectedTransport, + }; + setRemoteSessions([]); + if (!snapshot.profileId) return; + let cancelled = false; + void invoke("connection_slot_sessions", { + request: { slot: selectedSlot }, + }) + .then((result) => { + if (cancelled) return; + setRemoteSessions(remoteChatSessionSchema.array().parse(result)); + }) + .catch(() => undefined); + return () => { + cancelled = true; + }; + }, [ + selectedSlot, + selectedProfileId, + selectedServerInstanceId, + selectedSessionId, + selectedTransport, + ]); + + useEffect(() => { + const snapshot = { + profileId: selectedProfileId, + serverInstanceId: selectedServerInstanceId, + activeSessionId: selectedSessionId, + transport: selectedTransport, + }; + setCapabilities(null); + setSelectedModel(""); + if (!snapshot.profileId || snapshot.transport !== "astrbot-openapi") return; + let cancelled = false; + void invoke("connection_slot_capabilities", { + request: { slot: selectedSlot }, + }) + .then((result) => { + if (cancelled) return; + const next = astrbotCapabilitySnapshotSchema.parse(result); + setCapabilities(next); + setSelectedModel( + next.models.find((model) => model.isDefault)?.id ?? + next.models[0]?.id ?? + "", + ); + }) + .catch(() => undefined); + return () => { + cancelled = true; + }; + }, [ + selectedSlot, + selectedProfileId, + selectedServerInstanceId, + selectedSessionId, + selectedTransport, + ]); + + useEffect(() => { + const snapshot = { + profileId: selectedProfileId, + serverInstanceId: selectedServerInstanceId, + activeSessionId: selectedSessionId, + transport: selectedTransport, + }; + if ( + !snapshot.profileId || + !snapshot.serverInstanceId || + !snapshot.activeSessionId + ) + return; + void invoke("mark_chat_session_read", { + request: { + profileId: snapshot.profileId, + serverInstanceId: snapshot.serverInstanceId, + sessionId: snapshot.activeSessionId, + }, + }).catch(() => undefined); + setUnreadCounts((current) => ({ ...current, [selectedSlot]: 0 })); + }, [ + selectedSlot, + selectedProfileId, + selectedServerInstanceId, + selectedSessionId, + selectedTransport, + ]); + + useEffect(() => { + const snapshot = { + profileId: selectedProfileId, + serverInstanceId: selectedServerInstanceId, + activeSessionId: selectedSessionId, + transport: selectedTransport, + }; + if ( + !snapshot.profileId || + !snapshot.serverInstanceId || + !snapshot.activeSessionId + ) + return; + let cancelled = false; + void invoke("load_chat_messages", { + request: { + profileId: snapshot.profileId, + serverInstanceId: snapshot.serverInstanceId, + sessionId: snapshot.activeSessionId, + limit: 100, + }, + }) + .then((result) => { + if (cancelled) return; + const records = storedChatMessageSchema.array().parse(result); + setMessages((current) => + current + .filter((item) => item.slot !== selectedSlot) + .concat( + records.map((record) => ({ + id: record.messageId, + sessionId: record.sessionId, + slot: record.slot, + role: record.role, + content: record.content, + streaming: record.streaming, + error: record.error, + })), + ), + ); + }) + .catch(() => undefined); + return () => { + cancelled = true; + }; + }, [ + selectedSlot, + selectedProfileId, + selectedServerInstanceId, + selectedSessionId, + selectedTransport, + ]); + + 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 uploadFiles = async (files: FileList | null) => { + if (!files?.length) return; + setUploading(true); + setError(null); + try { + const uploaded: AstrBotAttachment[] = []; + for (const file of Array.from(files)) { + if (file.size > 16 * 1024 * 1024) + throw new Error(`${file.name} 超过 16 MiB 限制`); + const bytes = Array.from(new Uint8Array(await file.arrayBuffer())); + const result = await invoke("upload_connection_slot_file", { + request: { + slot: selectedSlot, + fileName: file.name, + mimeType: file.type || "application/octet-stream", + bytes, + }, + }); + uploaded.push(astrbotAttachmentSchema.parse(result)); + } + setPendingAttachments((current) => current.concat(uploaded)); + } catch (reason) { + setError(reason instanceof Error ? reason.message : String(reason)); + } finally { + setUploading(false); + } + }; + + const send = async () => { + const message = + draft.trim() || + (pendingAttachments.length > 0 ? "请查看我发送的附件。" : ""); + if (!message || uploading) return; + const id = `local-${Date.now()}`; + const attachments = pendingAttachments; + setDraft(""); + setPendingAttachments([]); + setMessages((current) => + current.concat({ + id, + sessionId: status[selectedSlot].activeSessionId, + slot: selectedSlot, + role: "user", + content: message, + }), + ); + try { + await invoke("send_connection_slot_message", { + request: { + slot: selectedSlot, + message, + configId: selectedModel || undefined, + attachments, + }, + }); + setError(null); + } catch (reason) { + setError(reason instanceof Error ? reason.message : String(reason)); + setMessages((current) => + current.map((item) => + item.id === id ? { ...item, error: true } : item, + ), + ); + } + }; + + const currentModels: AstrBotModelOption[] = capabilities?.models ?? []; + return ( +
+
+
+

Shared chat runtime

+

统一聊天运行时

+

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

+
+
+ {(["companion", "operations"] as const).map((slot) => ( + + ))} +
+
+
+ Profile:{status[selectedSlot].profileId ?? "未连接"} + Session:{status[selectedSlot].activeSessionId ?? "未建立"} + 状态:{connectionStateLabel(status[selectedSlot].state)} +
+ {status[selectedSlot].state === "authExpired" ? ( +
+ 认证已过期 + 请到“连接”设置重新登录 AstrBot,当前槽位不会继续发送消息。 + +
+ ) : null} + {remoteSessions.length > 0 ? ( +
+ {remoteSessions.map((session) => ( + + ))} +
+ ) : null} +
+ {activeMessages.length === 0 ? ( +

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

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

{message.content || "(空消息)"}

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

{error}

: null} +
+ + + {uploading ? 上传中… : null} +
+ {pendingAttachments.length > 0 ? ( +
+ {pendingAttachments.map((attachment) => ( + + {attachment.fileName} + + + ))} +
+ ) : null} +
{ + event.preventDefault(); + void send(); + }} + > +