feat(chat): add AstrBot dual-slot chat foundation
一些检测仍在等待运行
ci / Portable quality checks (push) Waiting to run
ci / Windows Tauri build (push) Waiting to run

这个提交存在于:
YokiiroBW 2026-07-20 11:31:41 +08:00
父节点 34a563c65b
当前提交 3d1d962461
共有 43 个文件被更改,包括 7081 次插入 和 2521 次删除

查看文件

@ -1,5 +1,9 @@
# Changelog # Changelog
## Unreleased
### Added
- AstrBot OpenAPI adapter foundation: SSE mapper, dual-slot runtime skeleton, credential enrollment IPC, transport-aware profiles (ADR-0005).
All notable changes to this project will be documented in this file. 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. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow Semantic Versioning.
@ -38,3 +42,4 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
- Kept real UNC writes, signing keys, updater keys, and release secrets outside P00. - 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. - 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. - Required explicit approval for insecure HTTP and kept slots, connections, and credential enrollment outside P01.

查看文件

@ -0,0 +1,456 @@
//! Real AstrBot OpenAPI/Dashboard wire types and SSE frame mapping.
//!
//! The provisional Desktop Gateway contract remains the internal normalized
//! model. This module translates observed AstrBot `/api/v1` chat SSE frames
//! into that model without claiming full product compatibility.
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;
use crate::{
EventMetadata, FinishReason, GatewayErrorPayload, GatewayEvent, GatewayEventBody,
HeartbeatPayload, MessageCompletedPayload, MessageDeltaPayload,
};
/// Wire transport used by a connection profile.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum TransportKind {
/// Provisional Mock / future Desktop Gateway (`/desktop/v1`).
#[default]
DesktopV1,
/// Real AstrBot OpenAPI surface (`/api/v1`).
AstrBotOpenApi,
}
impl TransportKind {
pub fn as_str(self) -> &'static str {
match self {
Self::DesktopV1 => "desktop-v1",
Self::AstrBotOpenApi => "astrbot-openapi",
}
}
pub fn parse(value: &str) -> Option<Self> {
match value {
"desktop-v1" => Some(Self::DesktopV1),
"astrbot-openapi" => Some(Self::AstrBotOpenApi),
_ => None,
}
}
}
/// JSON envelope used by most AstrBot dashboard/OpenAPI JSON responses.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AstrBotApiEnvelope<T> {
pub status: String,
#[serde(default)]
pub message: Option<String>,
#[serde(default)]
pub data: Option<T>,
}
impl<T> AstrBotApiEnvelope<T> {
pub fn is_ok(&self) -> bool {
self.status.eq_ignore_ascii_case("ok")
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AstrBotChatRequest {
pub message: Value,
#[serde(skip_serializing_if = "Option::is_none")]
pub session_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub conversation_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub username: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub config_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub platform_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub enable_streaming: Option<bool>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct AstrBotSessionListData {
#[serde(default)]
pub sessions: Vec<AstrBotSessionSummary>,
#[serde(default)]
pub page: Option<u64>,
#[serde(default)]
pub page_size: Option<u64>,
#[serde(default)]
pub total: Option<u64>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AstrBotSessionSummary {
pub session_id: String,
#[serde(default)]
pub platform_id: Option<String>,
#[serde(default)]
pub creator: Option<String>,
#[serde(default)]
pub display_name: Option<String>,
#[serde(default)]
pub is_group: Option<i64>,
#[serde(default)]
pub created_at: Option<String>,
#[serde(default)]
pub updated_at: Option<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct AstrBotConfigListData {
#[serde(default)]
pub configs: Vec<AstrBotConfigSummary>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AstrBotConfigSummary {
pub id: String,
#[serde(default)]
pub name: Option<String>,
#[serde(default)]
pub path: Option<String>,
#[serde(default)]
pub is_default: Option<bool>,
}
/// One decoded SSE unit from an AstrBot chat stream.
#[derive(Clone, Debug, PartialEq)]
pub enum AstrBotSseUnit {
HeartbeatComment,
Json(AstrBotStreamFrame),
Ignored,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AstrBotStreamFrame {
#[serde(rename = "type")]
pub frame_type: String,
#[serde(default)]
pub data: Value,
#[serde(default)]
pub session_id: Option<String>,
#[serde(default)]
pub streaming: Option<bool>,
#[serde(default)]
pub chain_type: Option<Value>,
#[serde(default)]
pub message_id: Option<String>,
}
#[derive(Debug, Error)]
pub enum AstrBotMapError {
#[error("invalid astrbot sse json: {0}")]
Json(#[from] serde_json::Error),
}
/// Parses a single SSE line (not including the blank separator).
pub fn parse_astrbot_sse_line(line: &str) -> Result<AstrBotSseUnit, AstrBotMapError> {
let trimmed = line.trim_end_matches('\r');
if trimmed.is_empty() {
return Ok(AstrBotSseUnit::Ignored);
}
if trimmed.starts_with(':') {
// AstrBot heartbeats are comment frames: ": heartbeat"
return Ok(AstrBotSseUnit::HeartbeatComment);
}
if let Some(data) = trimmed.strip_prefix("data:") {
let payload = data.trim_start();
if payload.is_empty() {
return Ok(AstrBotSseUnit::Ignored);
}
let frame: AstrBotStreamFrame = serde_json::from_str(payload)?;
return Ok(AstrBotSseUnit::Json(frame));
}
// event:/id: fields are currently unused by AstrBot chat streams.
Ok(AstrBotSseUnit::Ignored)
}
/// Stateful mapper that turns AstrBot chat SSE frames into Desktop Gateway events.
#[derive(Debug, Default)]
pub struct AstrBotStreamMapper {
server_instance_id: String,
session_id: Option<String>,
active_message_id: Option<String>,
accumulated: String,
delta_index: u32,
sequence: u64,
saw_assistant_delta: bool,
}
impl AstrBotStreamMapper {
pub fn new(server_instance_id: impl Into<String>) -> Self {
Self {
server_instance_id: server_instance_id.into(),
..Self::default()
}
}
pub fn session_id(&self) -> Option<&str> {
self.session_id.as_deref()
}
pub fn push_line(&mut self, line: &str) -> Result<Vec<GatewayEvent>, AstrBotMapError> {
match parse_astrbot_sse_line(line)? {
AstrBotSseUnit::Ignored => Ok(Vec::new()),
AstrBotSseUnit::HeartbeatComment => Ok(vec![self.heartbeat_event()]),
AstrBotSseUnit::Json(frame) => Ok(self.map_frame(frame)),
}
}
/// Call when the HTTP stream ends without a terminal server frame.
pub fn finish_stream(&mut self) -> Vec<GatewayEvent> {
self.complete_if_needed(FinishReason::Stop)
}
fn map_frame(&mut self, frame: AstrBotStreamFrame) -> Vec<GatewayEvent> {
match frame.frame_type.as_str() {
"session_id" => {
if let Some(session_id) = frame
.session_id
.clone()
.filter(|value| !value.trim().is_empty())
{
self.session_id = Some(session_id);
} else if let Some(session_id) = string_from_value(&frame.data) {
self.session_id = Some(session_id);
}
Vec::new()
}
"user_message_saved" => Vec::new(),
"plain" => self.map_plain(frame),
"agent_stats" => {
let detail = frame.data.to_string();
vec![self.event(
frame.message_id.clone(),
GatewayEventBody::AgentStatus(crate::AgentStatusPayload {
state: "running".into(),
detail: Some(detail),
}),
)]
}
"run_snapshot" => {
vec![self.event(
frame.message_id.clone(),
GatewayEventBody::AgentStatus(crate::AgentStatusPayload {
state: "snapshot".into(),
detail: Some(frame.data.to_string()),
}),
)]
}
"message_saved" | "end" => self.complete_if_needed(FinishReason::Stop),
"error" => {
let mut events = self.complete_if_needed(FinishReason::Error);
let message = string_from_value(&frame.data)
.unwrap_or_else(|| "AstrBot stream error".to_owned());
events.push(self.event(
frame.message_id,
GatewayEventBody::Error(GatewayErrorPayload {
code: "astrbotStreamError".into(),
message,
retryable: true,
}),
));
events
}
"attachment_saved" => Vec::new(),
_ => Vec::new(),
}
}
fn map_plain(&mut self, frame: AstrBotStreamFrame) -> Vec<GatewayEvent> {
let chunk = string_from_value(&frame.data).unwrap_or_default();
if chunk.is_empty() && frame.streaming.unwrap_or(false) {
// Keep empty streaming markers out of the UI unless they carry text.
return Vec::new();
}
if let Some(message_id) = frame.message_id.clone() {
if self
.active_message_id
.as_ref()
.is_some_and(|current| current != &message_id)
{
// New assistant message id: complete the previous accumulation first.
let mut events = self.complete_if_needed(FinishReason::Stop);
self.active_message_id = Some(message_id);
self.accumulated.clear();
self.delta_index = 0;
self.saw_assistant_delta = false;
events.extend(self.emit_delta(chunk));
return events;
}
self.active_message_id = Some(message_id);
}
self.emit_delta(chunk)
}
fn emit_delta(&mut self, chunk: String) -> Vec<GatewayEvent> {
if chunk.is_empty() {
return Vec::new();
}
self.accumulated.push_str(&chunk);
self.saw_assistant_delta = true;
let index = self.delta_index;
self.delta_index = self.delta_index.saturating_add(1);
vec![self.event(
self.active_message_id.clone(),
GatewayEventBody::MessageDelta(MessageDeltaPayload {
delta: chunk,
index,
}),
)]
}
fn complete_if_needed(&mut self, reason: FinishReason) -> Vec<GatewayEvent> {
if !self.saw_assistant_delta && self.accumulated.is_empty() {
return Vec::new();
}
let content = std::mem::take(&mut self.accumulated);
self.saw_assistant_delta = false;
self.delta_index = 0;
let message_id = self.active_message_id.clone();
vec![self.event(
message_id,
GatewayEventBody::MessageCompleted(MessageCompletedPayload {
finish_reason: reason,
content: Some(content),
}),
)]
}
fn heartbeat_event(&mut self) -> GatewayEvent {
self.event(
None,
GatewayEventBody::Heartbeat(HeartbeatPayload { interval_ms: 1_000 }),
)
}
fn event(&mut self, message_id: Option<String>, body: GatewayEventBody) -> GatewayEvent {
self.sequence = self.sequence.saturating_add(1);
let event_id = format!("astrbot-{}-{}", self.server_instance_id, self.sequence);
let mut metadata = EventMetadata::new(
event_id,
self.server_instance_id.clone(),
current_timestamp(),
self.sequence,
);
metadata.session_id = self.session_id.clone();
metadata.conversation_id = self.session_id.clone();
metadata.message_id = message_id.or_else(|| self.active_message_id.clone());
GatewayEvent { metadata, body }
}
}
fn string_from_value(value: &Value) -> Option<String> {
match value {
Value::Null => None,
Value::String(text) => Some(text.clone()),
Value::Number(number) => Some(number.to_string()),
Value::Bool(flag) => Some(flag.to_string()),
other => Some(other.to_string()),
}
}
fn current_timestamp() -> String {
// Protocol timestamps are opaque strings for consumers; keep a stable UTC-like form
// without adding a time dependency to the protocol crate.
"1970-01-01T00:00:00Z".into()
}
/// Derives a stable local server identity substitute when AstrBot has no server-info API.
pub fn derive_astrbot_server_instance_id(base_url: &str) -> String {
use std::hash::{Hash, Hasher};
let normalized = base_url.trim().trim_end_matches('/').to_ascii_lowercase();
let mut hasher = std::collections::hash_map::DefaultHasher::new();
normalized.hash(&mut hasher);
format!("astrbot-{:016x}", hasher.finish())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn maps_live_probe_style_plain_stream() {
let mut mapper = AstrBotStreamMapper::new("astrbot-test");
let lines = [
r#"data: {"type": "session_id", "data": null, "session_id": "desktop-companion-s1"}"#,
r#"data: {"type": "user_message_saved", "data": {"id": 1}}"#,
": heartbeat",
r#"data: {"type": "plain", "data": "Hello", "streaming": true, "message_id": "m1"}"#,
r#"data: {"type": "plain", "data": "!", "streaming": true, "message_id": "m1"}"#,
];
let mut events = Vec::new();
for line in lines {
events.extend(mapper.push_line(line).expect("parse"));
}
events.extend(mapper.finish_stream());
assert_eq!(mapper.session_id(), Some("desktop-companion-s1"));
assert!(
events
.iter()
.any(|event| event.body.event_type() == "system.heartbeat")
);
let deltas: Vec<_> = events
.iter()
.filter_map(|event| match &event.body {
GatewayEventBody::MessageDelta(payload) => Some(payload.delta.as_str()),
_ => None,
})
.collect();
assert_eq!(deltas, ["Hello", "!"]);
let completed = events
.iter()
.find_map(|event| match &event.body {
GatewayEventBody::MessageCompleted(payload) => payload.content.clone(),
_ => None,
})
.expect("completed");
assert_eq!(completed, "Hello!");
assert_eq!(
events.last().map(|e| e.body.event_type()),
Some("message.completed")
);
}
#[test]
fn maps_error_frames() {
let mut mapper = AstrBotStreamMapper::new("astrbot-test");
let events = mapper
.push_line(r#"data: {"type":"error","data":"provider missing"}"#)
.expect("parse");
assert_eq!(events.len(), 1);
match &events[0].body {
GatewayEventBody::Error(error) => {
assert_eq!(error.code, "astrbotStreamError");
assert!(error.message.contains("provider missing"));
}
other => panic!("unexpected {other:?}"),
}
}
#[test]
fn derives_stable_instance_ids() {
let a = derive_astrbot_server_instance_id("http://192.168.31.210:26285/");
let b = derive_astrbot_server_instance_id("http://192.168.31.210:26285");
let c = derive_astrbot_server_instance_id("http://192.168.31.210:26286");
assert_eq!(a, b);
assert_ne!(a, c);
assert!(a.starts_with("astrbot-"));
}
#[test]
fn protocol_version_constant_is_unchanged_for_internal_model() {
assert_eq!(crate::PROTOCOL_VERSION, "desktop-v1alpha1");
}
}

查看文件

@ -54,6 +54,9 @@ pub struct ConnectionProfile {
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub event_stream_url: Option<String>, pub event_stream_url: Option<String>,
pub authentication_type: AuthenticationType, 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")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub credential_reference: Option<String>, pub credential_reference: Option<String>,
#[serde(default)] #[serde(default)]
@ -74,6 +77,12 @@ pub struct ConnectionProfile {
pub local_tool_policy_id: Option<String>, pub local_tool_policy_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub last_connected_at: Option<String>, pub last_connected_at: Option<String>,
/// AstrBot WebChat username / session owner used by OpenAPI chat.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub remote_username: Option<String>,
/// Sticky AstrBot session id for reconnection continuity.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sticky_session_id: Option<String>,
pub created_at: String, pub created_at: String,
pub updated_at: String, pub updated_at: String,
} }
@ -112,3 +121,7 @@ impl ConnectionSlot {
} }
} }
} }
fn default_transport_kind() -> crate::TransportKind {
crate::TransportKind::DesktopV1
}

查看文件

@ -3,6 +3,7 @@
//! Types in this crate deliberately separate untrusted wire data from locally //! Types in this crate deliberately separate untrusted wire data from locally
//! bound desktop events. A server supplied `profileId` is never authoritative. //! bound desktop events. A server supplied `profileId` is never authoritative.
mod astrbot;
mod capabilities; mod capabilities;
mod connection; mod connection;
mod diagnostics; mod diagnostics;
@ -11,6 +12,7 @@ mod file_transfer;
mod http; mod http;
mod tools; mod tools;
pub use astrbot::*;
pub use capabilities::*; pub use capabilities::*;
pub use connection::*; pub use connection::*;
pub use diagnostics::*; pub use diagnostics::*;

查看文件

@ -0,0 +1,46 @@
# ADR-0005: Real AstrBot OpenAPI adapter over internal Desktop protocol
## Status
Accepted for foundation work on 2026-07-20.
## Context
P00/P01 defined a provisional Desktop Gateway contract (`/desktop/v1`) and dual Mock Gateway. Live probe of AstrBot `4.26.x` on `http://192.168.31.210:26285` showed the real server exposes Dashboard/OpenAPI routes under `/api` and `/api/v1`, with request-scoped chat SSE from `POST /api/v1/chat`, API Key or Dashboard JWT auth, and no Desktop-native long-lived event bus, ACK, `tool.proposal`, or `server-info` endpoints.
Rewriting the whole Desktop application around raw AstrBot internal APIs would discard working dual-slot isolation, Mock tests, and security boundaries.
## Decision
1. Keep the provisional Desktop Gateway event model as the **internal normalized contract**.
2. Add a Rust-owned **AstrBot OpenAPI adapter** that translates:
- Desktop chat send intent → `POST /api/v1/chat`
- AstrBot SSE frames → Desktop `GatewayEvent` (`message.delta`, `message.completed`, heartbeat, error)
3. Add `TransportKind` on ConnectionProfile:
- `desktop-v1` for Mock/provisional gateway
- `astrbot-openapi` for real AstrBot
4. Store secrets only in Windows Credential Manager; React may submit one-shot enrollment IPC but never receives stored secrets.
5. Use derived `server_instance_id` substitute (`astrbot-<hash(base_url)>`) until a stronger identity enrollment flow is approved.
6. Keep operations tool proposals Desktop-local; do not invent a fake server proposal channel.
## Consequences
### Positive
- Real chat connectivity can proceed without discarding Mock-based dual-slot tests.
- Security boundaries remain Rust-owned.
- UI and local storage continue to reason about normalized events and slots.
### Negative / costs
- Adapter must tolerate missing terminal SSE frames and synthesize completion.
- Capability/discovery surfaces differ by transport.
- Certificate pinning and JWT login remain open follow-ups.
## Follow-ups
- Live dual-slot chat UI rendering and history persistence
- Dashboard JWT login path
- Attachment upload (`/api/v1/file`)
- Optional WS chat path
- Stronger server identity enrollment (PD-0011) and TLS fingerprint binding (PD-0012)

查看文件

@ -0,0 +1,46 @@
# ADR-0006: 共享聊天运行时与桌宠展示层
## 状态
提议,作为 P03-P07 的实现顺序基线,2026-07-20。
## 背景
产品需要同时支持完整聊天页面、小型快速回复窗口和后续桌面气泡/桌宠。三者如果各自维护连接、会话和消息,会产生重复状态、窗口间不同步以及双槽位权限绕过风险。
Hermes 与 Codex 展示出相似的产品形态,但没有可直接复用的共同运行时或公开稳定 SDK。因此本项目需要自有 Tauri/React/Rust 实现,只借鉴交互模式和素材包组织方式。
## 隔离基线
账号、Profile、槽位和 Session 是不同层级:账号标识本地使用者,Profile 标识 AstrBot 连接,槽位标识本地职责,Session 标识聊天上下文。不同账号和不同槽位均不得共享本地消息、未读数、错误状态或本机权限。
## 决策
1. 建立单一 Rust-owned ChatRuntime,主窗口、快速窗口和气泡均作为展示层订阅它。
2. 快速窗口只支持一个可配置目标槽位:Companion 或 Operations。
3. 气泡默认不置顶;设置决定气泡点击打开主页面还是快速窗口。
4. 桌宠先实现状态模型、素材包校验、窗口控制器和多显示器几何模型;动画引擎和复杂素材格式后置。
5. 全屏浮动和游戏模式只能通过受限窗口策略和只读前台/显示器检测实现,不引入任意桌面控制能力。
6. 主窗口、快速窗口和气泡关闭时不销毁连接运行时;连接由 Rust 槽位生命周期管理。
## 结果
### 优点
- 三种 UI 共享消息状态,避免重复实现和串线。
- 窗口能力与本机工具权限分离,桌宠不会获得额外操作权。
- 可以先完成真实文字聊天,再逐步加入视觉和游戏陪伴能力。
- 未来替换 PNG/WebP 为 Live2D/Spine 时不会改变聊天协议。
### 代价
- 需要设计 Rust 到多个 Tauri 窗口的事件广播和生命周期管理。
- SQLite 需要新增会话、消息和窗口偏好迁移。
- 多显示器和游戏模式需要 Windows 专用测试矩阵。
## 后续影响
- Q1 必须先定义规范化 ChatEvent 和共享订阅语义。
- Q4 必须验证独立窗口与单实例/托盘行为。
- Q6 的 pet-pack manifest 必须是数据文件,不允许携带可执行逻辑。
- Q7 的游戏模式只能做位置和显示策略,不得扩展为输入注入或任意窗口控制。

查看文件

@ -90,3 +90,22 @@
- Requirement: a certificate identity change freezes local-tool permission and the affected connection; TLS validation must never be disabled. - 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. - 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. - 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.

查看文件

@ -111,3 +111,35 @@ Completion commit: `bcc08cf feat(connection): add persistent dual slot assignmen
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. 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. The next increment starts with the formal Rust-owned credential lifecycle. Real Gateway activation remains blocked until PD-0009 through PD-0012 are resolved.
### Real AstrBot adapter foundation (added 2026-07-20)
Completed outside the original pure-mock sequencing because live probe unblocked transport decisions:
1. Internal SSE mapper and TransportKind.
2. Credential enrollment lifecycle (enroll/clear/load-for-Rust-only).
3. DualSlotRuntime activate/probe/send skeleton for strbot-openapi and desktop-v1.
4. Frontend transport + one-shot credential enrollment UI.
Still reserved before claiming end-to-end product chat:
- Chat UI event rendering
- Auto-connect runtime start
- JWT login
- Identity confirmation UX
## Product queue after the real AstrBot foundation
The ordered queue is maintained in docs/implementation-queue.md. The next implementation target is Q1: a shared Rust-owned chat runtime and normalized AstrBot event subscription.
1. Q1 normalized chat runtime
2. Q2 chat/session persistence
3. Q3 main-page chat MVP
4. Q4 shared-state quick chat window
5. Q5 status bubble and tray integration
6. Q6 pet state/resource foundation
7. Q7 multi-monitor and game-mode strategy
8. Q8 voice, proactive messages, and game companionship
9. Q9 release hardening and acceptance build
The quick window and bubble are presentation surfaces over the same runtime; they must not create independent network clients or permission scopes.

145
docs/implementation-queue.md 普通文件
查看文件

@ -0,0 +1,145 @@
# AstrBot Desktop 后续开发队列
## 目标形态
产品采用一套共享聊天运行时,提供三种展示形态:
1. **主页面聊天**:类似 QQ / Telegram 的完整窗口,支持会话列表、双槽位、消息流、未读数、主动消息和设置入口。
2. **快速聊天窗口**:桌面小窗口,支持拖动和调整大小;与主页面共享会话、消息、连接和未读状态,不复制聊天逻辑。
3. **气泡/桌宠入口**:默认不置顶,可显示连接和代理状态;点击行为在设置中选择“打开主页面”或“打开快速聊天”。后续扩展为桌面宠物。
## 隔离基线
所有后续队列必须遵守以下五层边界:
- **账号与账号隔离**:不同本地账号的连接配置、凭据引用、聊天记录、长期记忆和权限互不共享。
- **槽位与槽位隔离**:同一账号下的 Companion 与 Operations 分别维护连接、SSE、会话、消息、未读数、错误状态和权限。
- **Profile 与 Profile 隔离**:每个 AstrBot 连接 Profile 固定绑定地址、凭据引用、server_instance_id 和远端身份。
- **Session 与 Session 隔离**:不同槽位使用不同 sticky session;本地消息键不能只使用 session_id 或 conversation_id。
- **权限与权限隔离**:Companion 默认无本机工具权限;Operations 的诊断或文件提案必须经过本地策略、风险判断和用户确认。
推荐的本地事件和消息归属字段为:
`account_id + profile_id + slot + server_instance_id + remote_username + session_id + message_id`
remote_username 用于远端聊天身份和会话命名,不作为本机权限判断依据;本机权限只由本地账号、Profile、槽位和策略引擎决定。
## 执行原则
- 先做真实 AstrBot OpenAPI 的文字聊天闭环,再做视觉增强。
- React 只消费 Rust 输出的规范化事件,不直接访问 AstrBot 原始接口。
- Companion 与 Operations 的消息、会话、未读数和错误状态始终隔离。
- 气泡、快速窗口和主窗口只改变展示方式,不改变消息权限和槽位权限。
- 桌宠动画、跨屏移动和游戏模式先做数据模型及控制器接口,避免提前绑定素材或第三方运行时。
- 不默认开启置顶;全屏浮动必须有显式设置和可关闭路径。
## 队列
### Q0:阶段收口与基础校验
- 检查当前 P02 未提交改动,消除意外的大范围格式或换行 diff。
- 完成 Rust fmt、Clippy、TypeScript、ESLint、Prettier、Vite build、Playwright 和适用的 Tauri 构建检查。
- 将测试 API Key 标记为待轮换,不再写入日志、快照或测试夹具。
- 保留 `desktop-v1` Mock 传输;真实 AstrBot 走 `astrbot-openapi` 适配器。
验收:现有连接基础可构建,敏感信息边界无回归,Mock 与真实适配器不会互相污染。
### Q1:统一聊天运行时与事件归一化
- 为每个槽位建立 Rust-owned `ChatRuntime`,绑定 `profile_id`、`server_instance_id`、`conversation_id`。
- 将 AstrBot SSE 映射为统一的消息增量、完成、错误、心跳和主动消息事件。
- 处理流式消息合并、重复事件、断线恢复、取消生成和请求失败。
- 明确 `remote_username` 与 sticky session 的会话恢复策略。
- 增加前端订阅 IPC/事件桥;React 不接触 API Key 和原始 HTTP 客户端。
验收:两个槽位可同时发送和接收文字消息;同一 `conversation_id` 在不同 Profile 下不会串线。
### Q2:聊天数据与历史持久化
- 新增会话、消息、消息块、发送状态、未读数和主动消息的 SQLite 表及迁移。
- 本地唯一键至少包含 `profile_id`、`server_instance_id`、`conversation_id`、`message_id`。
- 支持启动恢复、分页加载、失败重试、流式消息落盘和未读数清零。
- 对消息内容做长度限制和展示层安全处理;日志不得记录完整聊天内容或凭据。
验收:重启应用后可恢复两个槽位的会话和未完成消息状态,数据隔离测试通过。
### Q3:主页面聊天 MVP
- 将当前 bootstrap/Profile 骨架替换为应用壳:侧栏、槽位切换、会话列表和聊天区域。
- 支持双面板并排模式、单面板 Tab 模式、Focus Companion、Focus Operations。
- 支持文本消息、流式渲染、发送中/失败/重试、连接状态、未读标记和主动消息入口。
- Operations 的本机工具提案只显示安全确认卡片,不在聊天文本中伪装成已执行。
- Companion 默认隐藏本机工具入口;Operations 仍受本地策略引擎约束。
验收:主窗口能完成真实 AstrBot 文字聊天;布局切换不丢流式内容;主动消息能跳转到正确槽位。
### Q4:快速聊天窗口
- 增加独立 Tauri 窗口,初始尺寸适合快速回复。
- 支持拖动、调整大小、关闭后恢复位置和尺寸。
- 与主窗口共享 `ChatRuntime`、会话选择、消息缓存、未读数和发送队列。
- 设置中只提供一个快速聊天目标:`companion` 或 `operations`,二选一。
- 设置中提供气泡点击导向:主页面或快速聊天;不增加第三种导向模式。
- 处理主窗口关闭到托盘、快速窗口关闭、单实例和窗口重启恢复。
验收:从主窗口和快速窗口发送的消息进入同一会话;任一窗口关闭不影响连接和另一个窗口。
### Q5:状态气泡与托盘整合
- 增加非默认置顶的气泡窗口,显示连接状态、思考中、回复完成、错误和未读数。
- 允许用户关闭气泡或切换到仅应用 UI 模式。
- 气泡点击按设置打开主页面或快速聊天;右键菜单提供显示、隐藏、设置和退出。
- 明确窗口层级、焦点、点击穿透(如需要)和屏幕边界策略。
- 只在 Rust 窗口控制器中执行显示/隐藏/置顶,React 仅发出受限意图。
验收:气泡不默认置顶;两个槽位状态可区分;点击行为与设置一致;托盘隐藏主窗口后仍可恢复。
### Q6:桌宠基础模型与素材包
- 抽象 `CompanionState`:`idle`、`thinking`、`speaking`、`error`、`notification`、`offline`。
- 抽象 `PetRenderer`、`PetWindowController` 和 `PetInteractionPolicy`,先支持静态 PNG/WebP 和 spritesheet。
- 定义可校验的 `pet-pack/manifest.json`,包含尺寸、动画帧、状态映射和可选点击动作。
- 支持应用内显示模式与全屏浮动模式的设置模型,但首版只接入状态气泡/静态形象。
- 上传素材只进入沙箱目录,校验格式、尺寸、文件大小和 manifest,不执行脚本或插件代码。
验收:可加载一个本地安全素材包并根据聊天状态切换静态状态;错误素材被拒绝且不影响主 UI。
### Q7:多显示器与游戏模式控制器
- Rust 获取显示器工作区、主屏/副屏标识、DPI 和任务栏边界,形成稳定的 `MonitorGeometry`。
- 提供桌宠位置策略:自由、靠边、指定屏幕、跟随主窗口。
- 游戏模式只做策略层:优先选择副屏,无法识别时选择非当前游戏窗口所在屏幕;宠物限制在边缘安全区。
- 通过受限的窗口/进程检测判断前台游戏,不读取或注入游戏进程,不做鼠标键盘控制。
- 增加双屏断开、DPI 变化、全屏游戏和窗口切换的回退策略。
验收:双屏场景下位置计算稳定;游戏模式不会把宠物放到游戏中心;权限不足时安全降级为应用内模式。
### Q8:语音、主动消息与游戏陪伴接入
- 在统一聊天运行时之上接入 STT/TTS,不为快速窗口或桌宠复制语音管线。
- 明确语音目标槽位,默认 Companion;Operations 需要显式切换。
- 将主动消息映射为通知、气泡状态和未读数,并提供静默时段设置。
- 游戏模式接入截图/状态摘要前,先完成授权提示、频率限制和隐私开关。
### Q9:稳定性、发布与验收
- 覆盖网络切换、SSE 重连、托盘驻留、窗口恢复、凭据失效和数据库迁移。
- 完成日志脱敏、诊断包预览、崩溃恢复和更新流程。
- 完成 Windows release/installer、签名、版本号、CHANGELOG 和阶段总结。
- 通过全套阶段门槛后再进入主干合并和验收版本打包。
## 暂不进入实现
- 不复制 Hermes 或 Codex 的私有实现;只参考交互模式和资源组织方式。
- 不在首轮实现 Live2D、Spine、3D 桌宠或用户脚本插件。
- 不实现任意 Shell、PowerShell、CMD、鼠标键盘控制。
- 不把 AstrBot 的工具调用直接当成本机命令执行。
- 不在没有真实附件协议验证前承诺文件上传;附件单独做 Spike。
## 需要用户后续接入
- 测试容器 API Key 轮换。
- 真实双服务器或第二容器,用于两个不同 `server_instance_id` 的长期并行测试。
- 最终确定 Companion/Operations 的远端用户名命名规则。
- 首批桌宠素材或授权素材包;在此之前使用测试 PNG/WebP。
- 如需 HTTPS 证书指纹绑定,提供可验证的 HTTPS 入口并确认首次信任交互。

查看文件

@ -2,97 +2,93 @@
## Current phase ## Current phase
P01 foundation was merged through Forgejo PR #2 at `885abd1`. P02 is active on `feat/p02-dual-connections`. The second increment is complete: auto-connect validation, operations switch protection, and duplicate server-instance warnings. Real Gateway activation remains blocked until PD-0009 through PD-0012 are resolved. 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 ## Completed
- Read `AGENTS.md`, the architecture, implementation task, and Forgejo predevelopment workflow documents in full. ### Prior phases
- 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. - P00 bootstrap merged.
- Completed and merged P00 through Forgejo PR #1 at `b3420e4`. - P01 foundation merged through Forgejo PR #2.
- Created `feat/p01-foundation` from the merged `main`. - P02 first increment: persistent dual slot assignment (`bcc08cf`).
- Added persistent SQLite startup initialization with WAL, busy timeout, foreign-key enforcement, and transactional migrations. - P02 second increment: auto-connect validation and operations switch guard (`34a563c`).
- 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. ### Real-protocol foundation (this session)
- Added bounded Tauri Profile list/create/update/delete commands.
- Kept UUID and timestamp creation in Rust. - Reviewed local AstrBot clone and live probe target `http://192.168.31.210:26285`.
- Rejected credential-bearing URLs, URL query/fragment data, implicit HTTP, invalid certificate fingerprints, malformed IDs, unknown fields, and Token/password/API Key fields. - Confirmed API Key chat SSE works; dual usernames/session ids isolate cleanly.
- Preserved credential references and runtime-managed fields outside the editable P01 input. - Added internal mapping module `desktop-protocol::astrbot` for OpenAPI SSE → Desktop events.
- Added strict Zod Schemas for bootstrap and ConnectionProfile IPC payloads. - Added `TransportKind` (`desktop-v1` | `astrbot-openapi`) plus `remote_username` / `sticky_session_id` profile fields.
- Added a basic React Profile management UI for non-sensitive metadata only. - Migrated SQLite schema to v4.
- Added explicit deletion confirmation and browser-safe Tauri IPC fallback. - Added Rust `AstrBotClient` for probe/list/send chat stream.
- Added a redacting tracing writer that sanitizes structured fields and rendered message content. - Added `DualSlotRuntime` with activate/probe/send/deactivate skeleton.
- Retained tray, close-to-tray, explicit quit, and single-instance behavior. - Added bounded credential enrollment IPC (`enroll_profile_credential` / `clear_profile_credential`) using Windows Credential Manager; secrets never returned to React.
- Re-exported protocol Schemas without drift. - Added frontend transport fields and credential enrollment card.
- Re-ran a real Tauri development startup and reached the Windows executable. - Recorded ADR-0005 and live probe report.
- Rebuilt the Windows release executable and NSIS installer.
- Recorded the Profile boundary in PD-0008 and ADR-0004.
- Verified Forgejo PR #2 was merged at `885abd1553ed8f1428de7118a6f4b59f7e22a45c`.
- Fast-forwarded local `main` to the same remote merge commit without rewriting history.
- Created `feat/p02-dual-connections` from the updated `main`.
- Re-read `AGENTS.md`, the Forgejo workflow, architecture design, and implementation task documents in full for P02.
- Kept the approved HTTP Forgejo URL repository-local and prevented the machine-wide HTTP-to-SSH rewrite from changing this repository's transport.
- Added SQLite schema v3 with exactly two fixed connection slot rows.
- Added foreign-key cleanup so deleting a Profile clears its assigned slot.
- Enforced that one Profile cannot occupy both companion and operations slots.
- Added bounded Rust list/assign/clear slot commands that reject unknown fields and malformed Profile IDs.
- Added strict frontend slot Schemas and a minimal settings UI that does not activate network connections or read credentials.
- Added v1-to-current and v2-to-v3 migration coverage, slot persistence tests, duplicate-assignment tests, and frontend slot interaction coverage.
- Completed the first P02 increment in `bcc08cf`.
- Added auto-connect configuration validation: at most two auto-connect Profiles, distinct slots, and slot required only when auto-connect is enabled.
- Added in-process operations switch guard that blocks operations slot assign/clear while a runtime operations task is active; companion remains free.
- Added duplicate `server_instance_id` warnings without silent Profile merge.
- Exposed `connection_policy_status` IPC for lock status and warnings.
- Extended Profile create/update input with non-secret `autoConnect` and `autoConnectSlot` fields.
- Updated Profile UI for auto-connect controls, operations lock messaging, and duplicate-instance banners.
- Added Rust unit coverage for policy, runtime guards, and locked operations slot switches; extended Vitest coverage for auto-connect save, warning display, and operations select disablement.
## In progress ## In progress
- No product implementation is currently in progress after the second P02 increment. - User acceptance of real-protocol foundation.
- Next product increments: chat panel rendering, history persistence, JWT login path, stronger server identity UX.
## Remaining ## Remaining
- Implement the formal Rust-owned credential lifecycle without returning secret values to React. - Wire auto-connect startup to DualSlotRuntime without weakening secret boundary.
- Resolve first-contact server identity confirmation and certificate fingerprint binding without disabling TLS validation. - Dual chat UI panels consuming normalized runtime events.
- Implement two independent configured REST/SSE runtimes only against a reviewed contract; continue using the dual Mock Gateway for deterministic tests. - Message persistence for AstrBot mapped events.
- Run Forgejo CI when a compatible runner is available. - Dashboard JWT auth strategy.
- Execute a real UNC transaction only after an authorized disposable fixture is supplied. - File attachment OpenAPI path.
- Add the combined end-to-end test that keeps configured streams active while the real Tauri window is hidden to tray. - Certificate fingerprint binding.
- Full stage gate (fmt/clippy/typecheck/build/installer) before merge.
## Blockers ## Blockers / reserved for user
- Configured Forgejo SSH `localhost:18086` refuses connections. - Production API Key rotation after shared test key exposure in chat.
- LAN SSH `192.168.31.210:18086` responds but rejects the available public key. - Optional second AstrBot container if true dual-server soak is required.
- Approved HTTP Git push remains operational and is not blocked. - Product decision on companion/operations remote username naming convention.
- Forgejo runner labels/jobs could not be verified; the jobs API endpoint returned 404. - TLS-terminated HTTPS endpoint if pinning must be validated before release.
- Real AstrBot Gateway endpoints, authentication semantics, token refresh behavior, and server identity guarantees remain unavailable for compatibility verification.
- Certificate fingerprint extraction/pinning behavior must be designed without disabling TLS validation.
- These protocol items do not block the local P02 policy/guard increment.
- Cross-machine handoff is blocked before controller lookup because the global dev-handoff config references a missing VM identity file and missing known-hosts file; host-key verification also fails. No handoff ID or destination workspace exists.
## Test status ## Test status
- Frontend: Prettier, ESLint, TypeScript, 6 Vitest tests, and Vite production build passed. - `desktop-protocol` lib tests: 4 passed (AstrBot mapper).
- Playwright Chromium: passed 1/1. - `astrbot-desktop` lib tests: 58 passed.
- Rust fmt and Clippy with warnings denied: passed. - Vitest: 6 passed.
- `cargo test --workspace`: passed; 63 normal tests, 2 explicit manual tests ignored. - Live non-destructive probe artifacts retained under `docs/reports/` (secrets redacted).
- `cargo check --workspace --all-targets`: passed. - Full release build / Clippy gate / Playwright not re-run in this autonomous stretch.
- Changed-file secret scan: passed; no private-key header, long Bearer credential, AWS key, GitHub token, or OpenAI-style key pattern was found.
- Real Tauri development startup and Windows installer build were not rerun for this incremental checkpoint and are not claimed.
## Current branch ## Current branch
`feat/p02-dual-connections` - `feat/p02-dual-connections`
## Recent commits ## Next step after acceptance
- `bcc08cf feat(connection): add persistent dual slot assignment` 1. Chat panel MVP against AstrBot adapter.
- `73693b9 docs(p02): start dual connection phase` 2. Persist sticky session + message history under profile/server/session keys.
- `885abd1 Merge pull request 'feat(p01): add secure profile foundation and management UI' (#2) from feat/p01-foundation into main` 3. Optional auto-connect activation using enrolled credential references only.
- `b3420e4 Merge pull request 'feat(p00): bootstrap Tauri desktop and validate high-risk spikes' (#1)`
- `ed74342 feat(foundation): add persistent bootstrap safeguards`
## Next step
Implement the formal credential enrollment/update/delete lifecycle entirely in Rust, with opaque references only in SQLite and React. Do not enable real Gateway connections until PD-0009 through PD-0012 are resolved. ## 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.

查看文件

@ -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. 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. 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` - `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. The 30-minute dual-SSE soak is an explicit local Spike acceptance run and must be recorded separately; its result is not implied by unit tests.
## Real AstrBot transport note
As of the 2026-07-20 live probe, real AstrBot servers do **not** implement /desktop/v1.
Desktop keeps this protocol as the internal normalized model and maps AstrBot OpenAPI chat SSE through the Rust adapter (TransportKind::astrbot-openapi).
See docs/reports/astrbot-real-protocol-review.md and docs/decisions/ADR-0005-astrbot-openapi-adapter.md.

查看文件

@ -21,6 +21,21 @@
"api-key" "api-key"
], ],
"type": "string" "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", "$schema": "https://json-schema.org/draft/2020-12/schema",
@ -95,6 +110,13 @@
"null" "null"
] ]
}, },
"remoteUsername": {
"description": "AstrBot WebChat username / session owner used by OpenAPI chat.",
"type": [
"string",
"null"
]
},
"role": { "role": {
"$ref": "#/$defs/AstrBotProfileRole" "$ref": "#/$defs/AstrBotProfileRole"
}, },
@ -110,6 +132,18 @@
"null" "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": { "updatedAt": {
"type": "string" "type": "string"
} }

查看文件

@ -0,0 +1,38 @@
# AstrBot 双容器连接稳定性测试
- 日期:2026-07-20
- 范围:仅连接、认证、请求级 SSE 稳定性和会话隔离
- 禁止项:未修改远端配置,未删除数据,未调用工具或文件操作接口,未做重启
## 测试矩阵
- 两套远端 AstrBot:端口 26285、26385
- 每套两个逻辑槽位:companion、operations
- 3 轮低频并发
- 总请求数:12 次聊天 SSE 请求
- 每次请求使用独立的 desktop-stress-companion 或 desktop-stress-operations 用户名和固定 session id
- 请求内容为要求服务端仅回复 OK 的连通性探针
## 结果
| 系统 | 请求数 | HTTP 200 | SSE | user_message_saved | 错误 | 最大耗时 |
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
| 26285 | 6 | 6 | 6 | 6 | 0 | 15.44 秒 |
| 26385 | 6 | 6 | 6 | 6 | 0 | 9.38 秒 |
所有请求均返回 text/event-stream,认证成功,均收到 session_id 和 user_message_saved。部分响应没有 plain 帧,但没有出现 HTTP、SSE 或 API 错误。
## 隔离核对
两套系统分别查询两个用户名的会话列表,均只看到对应的 creator 和 session id:
- companion:desktop-stress-companion / desktop-stress-companion-s1
- operations:desktop-stress-operations / desktop-stress-operations-s1
未发现 companion 与 operations 串线,也未发现两台系统之间的会话串线。
## 结论
当前两套容器可以作为双连接开发测试环境。客户端可以在每个 Profile 内分别保存远端地址、API Key 引用、remote_username 和 sticky_session_id。该测试不等价于长时间 soak test,也不验证 JWT 过期、断网重连、服务重启或高并发压力。
API Key 未写入本报告;测试密钥仍建议在验收前轮换。

查看文件

@ -0,0 +1,452 @@
=== companion ===
data: {"type": "session_id", "data": null, "session_id": "desktop-companion-s1"}
data: {"type": "user_message_saved", "data": {"id": 9, "created_at": "2026-07-19T18:37:36.326720+00:00", "llm_checkpoint_id": "07b7b73b-31b1-4d12-b991-97911fa8a7f4"}}
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
=== operations ===
data: {"type": "session_id", "data": null, "session_id": "desktop-operations-s1"}
data: {"type": "user_message_saved", "data": {"id": 10, "created_at": "2026-07-19T18:39:07.001542+00:00", "llm_checkpoint_id": "6dd71d85-c27e-4683-aca2-3678dc0f4a8d"}}
: heartbeat
: heartbeat
data: {"type": "plain", "data": "\n\n", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": "Hello", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " again", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": "!", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " 👋", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " \n\n", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": "I", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " see", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " you", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": "'re", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " saying", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " hello", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " with", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " a", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " \"", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": "3", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": "\"", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " -", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " is", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " there", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " something", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " specific", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " you", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": "'d", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " like", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " to", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " chat", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " about", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " or", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " need", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " help", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " with", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": "?", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " I", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": "'m", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " here", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " and", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " ready", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " to", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": " assist", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
data: {"type": "plain", "data": "!", "streaming": true, "chain_type": null, "message_id": "3c4fc646-8087-4869-a17f-6d1ef6d46c2e"}
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
: heartbeat
=== sessions companion ===
{"status":"ok","message":null,"data":{"sessions":[{"session_id":"desktop-companion-s1","platform_id":"webchat","creator":"desktop-companion","display_name":"desktop-probe companion","is_group":0,"created_at":"2026-07-19T18:30:39.417334+00:00","updated_at":"2026-07-19T18:35:11.994641+00:00"}],"page":1,"page_size":20,"total":1}}
=== sessions operations ===
{"status":"ok","message":null,"data":{"sessions":[{"session_id":"desktop-operations-s1","platform_id":"webchat","creator":"desktop-operations","display_name":"Desktop-Probe Operations","is_group":0,"created_at":"2026-07-19T18:30:46.775912+00:00","updated_at":"2026-07-19T18:31:03.599429+00:00"}],"page":1,"page_size":20,"total":1}}

查看文件

@ -0,0 +1,63 @@
{
"ok": true,
"base": "http://192.168.31.210:26285",
"companion": {
"contentType": "text/event-stream",
"saved": false,
"types": {
"user_message_saved": 1,
"session_id": 1
},
"length": 1602
},
"operations": {
"contentType": "text/event-stream",
"saved": false,
"types": {
"plain": 41,
"session_id": 1,
"user_message_saved": 1
},
"length": 7137
},
"sessionsCompanion": {
"status": "ok",
"message": null,
"data": {
"sessions": [
{
"session_id": "desktop-companion-s1",
"platform_id": "webchat",
"creator": "desktop-companion",
"display_name": "desktop-probe companion",
"is_group": 0,
"created_at": "2026-07-19T18:30:39.417334+00:00",
"updated_at": "2026-07-19T18:35:11.994641+00:00"
}
],
"page": 1,
"page_size": 20,
"total": 1
}
},
"sessionsOperations": {
"status": "ok",
"message": null,
"data": {
"sessions": [
{
"session_id": "desktop-operations-s1",
"platform_id": "webchat",
"creator": "desktop-operations",
"display_name": "Desktop-Probe Operations",
"is_group": 0,
"created_at": "2026-07-19T18:30:46.775912+00:00",
"updated_at": "2026-07-19T18:31:03.599429+00:00"
}
],
"page": 1,
"page_size": 20,
"total": 1
}
}
}

查看文件

@ -0,0 +1,362 @@
# AstrBot Real Protocol Review (vs Desktop provisional contract)
- Date: 2026-07-20
- Status: research complete; live container probe pending user-provided instance
- Conclusion: **do not claim compatibility** with `/desktop/v1`. Real AstrBot exposes Dashboard JWT + developer OpenAPI on `/api` and `/api/v1`. A desktop adapter layer is required.
## Sources
| Source | Path / URL | Role |
| --- | --- | --- |
| Local upstream clone | `C:\Users\Administrator\Documents\Codex\refs\AstrBot` | Code authority (no GitHub Apps used) |
| Package version | `pyproject.toml` → `4.26.7` | Observed clone version |
| Official OpenAPI docs | `docs/zh/dev/openapi.md`, `docs/en/dev/openapi.md` | Public developer API contract |
| Dashboard API code | `astrbot/dashboard/api/*`, `services/chat_service.py`, `services/auth_service.py` | Auth, SSE, WS, scopes |
| Compose defaults | `compose.yml` | Port `6185` WebUI/API |
| Desktop provisional contract | `docs/protocol/v1/*`, `docs/01_Architecture_Design.md`, PD-0009 | Current client assumption |
Upstream repo identity: [AstrBotDevs/AstrBot](https://github.com/AstrBotDevs/AstrBot). Docker image commonly `soulter/astrbot:latest`.
## What real AstrBot exposes
### Transport and base URLs
- Default container/WebUI port: **6185** (`compose.yml` maps `6185:6185`, Dockerfile `EXPOSE 6185`).
- API surface is **FastAPI / ASGI**, not a custom Desktop Gateway.
- Two parallel API styles coexist:
1. **v1 OpenAPI-style routes**: prefix `/api/v1` (`API_V1_PREFIX`).
2. **Legacy Dashboard routes**: prefixes like `/api/auth`, `/api/chat`, `/api/session`, etc.
- Interactive docs (when running): `http://<host>:6185/api/v1/docs`
- OpenAPI schema: `http://<host>:6185/api/v1/openapi.json`
### Authentication (two valid modes)
| Mode | How presented | Intended use | Notes |
| --- | --- | --- | --- |
| Dashboard JWT | `Authorization: Bearer <jwt>` or cookie `astrbot_dashboard_jwt` | WebUI / dashboard-user flows | Login via `POST /api/v1/auth/login` or legacy `POST /api/auth/login` with username/password (+ optional TOTP). JWT payload: `{ username, exp }` HS256, default **7 days**. **No refresh-token endpoint found** in current code. |
| Developer API Key | Official docs show `Authorization: Bearer abk_xxx` or `X-API-Key: abk_xxx`; code also accepts `ApiKey <key>`, query `api_key`/`key` | Machine integration | Scope-gated. Prefer header auth; avoid putting keys in query strings in Desktop. |
Response envelope for most JSON APIs:
```json
{ "status": "ok|error", "message": "...", "data": {} }
```
Login success data includes at least:
```json
{
"token": "<jwt>",
"username": "...",
"change_pwd_hint": false,
"md5_pwd_hint": false,
"password_upgrade_required": false
}
```
Fresh installs may print a random strong dashboard password in startup logs (default password policy changed).
### Chat / streaming (the critical path for Desktop text chat)
| Capability | Real AstrBot | Desktop provisional (`/desktop/v1`) |
| --- | --- | --- |
| Send message | `POST /api/v1/chat` (OpenAPI, SSE) or legacy `POST /api/chat/send` | `POST /desktop/v1/messages` |
| Session list | `GET /api/v1/chat/sessions` (API key path requires `username`) | Not modeled the same way |
| New session | Dashboard: `GET /api/v1/chat/sessions/new` / legacy `GET /api/chat/new_session` | Implicit/local |
| Streaming transport | **Request-scoped SSE** from chat send; also run attach `GET /api/v1/chat/runs/{run_id}/stream` | **Long-lived** `GET /desktop/v1/events/stream` with `Last-Event-ID` |
| Optional duplex | `WS /api/v1/chat/ws` (OpenAPI) and live-chat WS endpoints | Deferred WS for voice/game only |
| Event ACK | Not present as Desktop-style `POST /events/{id}/ack` | Required in provisional contract |
| Health / server-info / capabilities | **No** `/desktop/v1/health|server-info|capabilities` | Required discovery endpoints |
| Auth refresh | **No** refresh token pair found | `POST /desktop/v1/auth/refresh` |
| Tool proposal from server to desktop | **Not** present as `tool.proposal` | Core operations model |
| Local-action result callbacks | **Not** present as `/local-actions/*` | Required for ops tools |
#### OpenAPI chat request shape (`OpenApiChatRequest`)
```json
{
"message": "Hello" ,
"session_id": "uuid-or-omit",
"conversation_id": "alias-of-session_id",
"username": "required-for-api-key-mode",
"config_id": "optional",
"config_name": "optional",
"platform_id": "optional",
"enable_streaming": true,
"flags": {}
}
```
`message` may be:
1. plain string
2. message-segment array, e.g. `{ "type": "plain", "text": "..." }` plus attachment segments (`image`/`record`/`file`/`video` with `attachment_id`)
#### Observed SSE frame style (from `chat_service.py`)
- Media type: `text/event-stream`
- Frames are mostly `data: {json}\n\n`
- Heartbeat is **comment-style**: `: heartbeat\n\n` (not Desktop `system.heartbeat` event objects)
- Payload types observed in stream path include:
- `session_id`
- `user_message_saved`
- `run_snapshot`
- `agent_stats`
- `attachment_saved`
- `message_saved`
- `error`
- plus intermediate chunk payloads whose `type` can be message-chain types such as `plain` / attachment types and end markers from the internal queue
This is **not** the Desktop provisional event set:
```text
system.heartbeat
message.delta
message.completed
message.proactive
agent.status
tool.proposal
capabilities.changed
error
```
### Developer API Key scopes
Supported scopes in code/docs: `bot`, `provider`, `persona`, `im`, `config`, `chat`, `file`, `plugin`, `mcp`, `skill`.
Important:
- `config` implies `bot` + `provider`.
- Docs state developer keys do **not** currently expose some management scopes as first-class developer scopes (`tool`, `kb`, `data`, `system` called out as unsupported developer scopes in docs).
- Desktop “operations tool proposal” is **not** an AstrBot OpenAPI scope; it is a Desktop-local safety model.
### Dual-instance implications
AstrBot itself is one server process/instance with multi-session WebChat identities (`username` + `session_id` / platform session keys).
Desktop dual slots (`companion` / `operations`) remain a **client-side** concept:
- Two Desktop Profiles can point at the **same** AstrBot base URL with different roles/policies.
- Or two Profiles can point at two containers.
- Real server does not natively understand Desktop slot roles.
- Isolation keys on Desktop must still include local `profile_id` + observed `server_instance_id` substitute + conversation/session id.
There is **no first-class** `serverInstanceId` discovery endpoint equivalent to Desktop `server-info`. A safe substitute must be designed (e.g., hash of base URL + dashboard instance markers + TLS cert fingerprint + optional user-confirmed label). This is still an open protocol decision.
## Gap table (Desktop provisional vs real AstrBot)
| Area | Desktop design | Real AstrBot today | Risk if ignored | Can implement now? |
| --- | --- | --- | --- | --- |
| Base path | `/desktop/v1/*` | `/api/v1/*` + legacy `/api/*` | 100% connection failure | Adapter required |
| Auth model | access + refresh tokens | JWT (7d) and/or API Key; no refresh pair found | Refresh logic dead code / false security assumptions | Adapter: store JWT or API Key in Credential Manager |
| Credentials in React | forbidden | N/A | policy violation if mirrored | Keep Rust-only secret store |
| Health discovery | `/health` | not equivalent | mock-only health checks | Map to lightweight authenticated probe or WebUI reachability |
| Server identity | `/server-info.serverInstanceId` | missing | silent cross-instance mixups | Need substitute identity + user confirmation |
| Capabilities | `/capabilities` | partial via configs/plugins/bots lists; not Desktop schema | capability UI wrong | Map subset later |
| Chat send | REST message post | `POST /api/v1/chat` SSE | wrong client shape | Implement adapter |
| Event stream | long-lived SSE + Last-Event-ID | per-request SSE (+ optional run stream / WS) | reconnect/dedupe model invalid | Redesign stream manager |
| Event names | Desktop enum | different types | parser rejects everything | Map/normalize in adapter |
| ACK | required | absent | useless calls / noise | Make ACK optional/no-op for AstrBot backend |
| Proactive messages | `message.proactive` over long SSE | IM proactive API exists (`POST /api/v1/im/message`) but not Desktop push bus | wrong product assumption | Separate design |
| Ops tool.proposal | server pushes proposals | **not present** | operations panel cannot be driven by AstrBot core alone | Keep Desktop-local proposal engine / future plugin contract |
| Local-action callbacks | `/local-actions/*` | absent | cannot close tool loop to AstrBot | Local audit only, or future plugin |
| TLS / pinning | required by Desktop security model | container often HTTP on LAN | may force HTTP exception path | Prefer HTTPS reverse proxy; never disable TLS validation globally |
| Dual SSE slots | two long-lived streams | two chat runs / two API keys / two containers | architecture mismatch | Keep dual client slots; adapt transport |
## Architecture impact (important: not a total rewrite)
### Keep (still valid)
- Tauri + React + Rust boundary
- Dual Profile / dual slot isolation
- Credential Manager storage
- Mock Gateway for deterministic tests
- Local diagnostics / NAS transfer security pipeline (client-side)
- Provisional Desktop protocol as **internal normalized model**
### Must add
1. **`AstrBotAdapter` (Rust)** that translates:
- Desktop normalized commands → AstrBot REST/SSE/WS
- AstrBot stream frames → Desktop `GatewayEvent` (best-effort mapping)
2. **Auth strategies**:
- Strategy A: Dashboard username/password → JWT (short-lived session model, re-login on expiry)
- Strategy B: API Key with scopes `chat` (+ `file` if attachments; carefully limited admin scopes)
3. **Stream manager redesign**:
- Not one eternal server push bus
- Per send-stream + optional run re-attach + future WS for duplex
4. **Server identity substitute** decision (open item)
5. **Operations path**:
- Do **not** expect stock AstrBot to emit Desktop `tool.proposal`
- Either local-only ops tools, or a future explicit AstrBot plugin/contract
### Do **not** do
- Rewrite Desktop core to call random AstrBot internal Python APIs
- Claim `/desktop/v1` is real AstrBot
- Put API keys/JWT into React, SQLite plain fields, logs, or URL query strings
- Disable TLS validation to “make container work”
- Implement arbitrary shell execution because ops tools are missing server-side
## Live container probe plan (when you provide the instance)
Please provide (redact secrets in chat if needed; better paste into a local file path I can read, or supply a temporary throwaway password/API key):
1. Base URL, e.g. `http://192.168.x.x:6185`
2. Auth mode: dashboard password **or** API Key (`abk_...`)
3. Whether LLM provider is already configured (chat may stream errors without a model)
4. Network reachability from this Windows desktop host
Minimum probe sequence (no secrets logged in full):
1. `GET /` or WebUI reachability
2. `GET /api/v1/openapi.json` (schema presence/version markers)
3. Auth:
- login `POST /api/v1/auth/login` **or**
- API key header against `GET /api/v1/chat/sessions?username=...`
4. Create/send chat:
- `POST /api/v1/chat` with small plain message and capture first SSE frames
5. Confirm session list returns the session
6. Optional: WS `/api/v1/chat/ws` smoke
7. Record actual event type sequence into this report appendix
Success criteria for “connection is implementable”:
- Auth succeeds without Dashboard browser cookies as the only path
- One chat message produces parseable SSE frames
- Session id is stable enough to store under a Desktop Profile
- Dual Profiles can open two independent sessions without cross-talk
Failure that would force design pause:
- Only cookie-auth works and API key/JWT blocked
- Chat stream format unstable / undocumented and unusable
- No way to distinguish two server instances safely for dual-slot ops
- Requirement to modify AstrBot core for basic text chat
## Decision recommendation
| Decision | Recommendation |
| --- | --- |
| Is Desktop mock protocol wrong? | It is a **valid internal contract**, not a real server contract. |
| Should we throw away Desktop work? | **No.** Keep Mock + normalized events; add adapter. |
| First live integration target | Text chat via `POST /api/v1/chat` SSE + session APIs |
| Preferred auth for automation tests | API Key with minimal scopes (`chat`, maybe `file`) |
| Preferred auth for user login UX | Dashboard login → JWT in Credential Manager, re-login on 401/expiry |
| Operations tools MVP | Remain Desktop-local; do not depend on AstrBot emitting proposals yet |
| Protocol docs | Update PD-0009 / add ADR after first successful container probe |
## Can implement now / needs container / blocked
| Item | Status |
| --- | --- |
| Protocol research + gap table | **Done** (this document) |
| Adapter design sketch | **Ready** |
| Live endpoint/version confirmation against your container | **Needs container** |
| Real chat SSE fixture capture | **Needs container + model provider** |
| Dual-instance identity substitute finalization | **Needs probe + product decision** |
| Claiming production compatibility | **Blocked** until probe passes |
| Rewriting whole Desktop architecture | **Not required** based on current evidence |
## Next action
Provide the test AstrBot container endpoint and auth material. I will run a non-destructive probe, capture redacted SSE samples, and only then propose the minimal adapter implementation plan (likely ADR + protocol mapping tables, without expanding product scope).
## Live container probe (2026-07-20)
- Target: `http://192.168.31.210:26285`
- Auth: developer API Key (`abk_…`, redacted)
- Mode: non-destructive chat/session/config probes only
- Artifacts:
- `docs/reports/astrbot-live-probe-summary.json`
- `docs/reports/astrbot-live-probe-sse.raw.txt` (secrets redacted)
- `docs/reports/run-live-probe.ps1` (requires env key; no embedded secret)
### Connectivity results
| Check | Result |
| --- | --- |
| TCP `192.168.31.210:26285` | Reachable |
| `GET /` WebUI HTML | 200 |
| `GET /api/auth/setup-status` (no auth) | 200; `setup_required=false` |
| API Key on `GET /api/v1/chat/sessions?username=...` | 200 |
| Auth styles accepted | `Authorization: Bearer abk_…`, `X-API-Key`, `Authorization: ApiKey …`, query `api_key` (prefer headers only in Desktop) |
| `GET /api/v1/configs` | 200; one config `default` |
| `GET /api/v1/im/bots` | 200; `bot_ids=["napcat3"]` |
| `GET /api/v1/openapi.json` / `/docs` / several management routes | Often SPA-style HTML 404 page even when authenticated; **do not rely on OpenAPI UI path on this deployment** |
| Dashboard JWT login | Not exercised in this probe (API key path is sufficient for automation) |
### Chat SSE (authoritative live sample)
`POST /api/v1/chat` with:
```json
{
"message": "desktop-probe ...",
"username": "desktop-companion|desktop-operations",
"session_id": "desktop-*-s1",
"enable_streaming": true
}
```
Observed response:
- HTTP 200
- `Content-Type: text/event-stream`
- Initial frames:
1. `{"type":"session_id","data":null,"session_id":"..."}`
2. `{"type":"user_message_saved","data":{"id":N,"created_at":"...","llm_checkpoint_id":"..."}}`
3. Comment heartbeats: `: heartbeat`
4. Streamed assistant tokens:
`{"type":"plain","data":"Hello","streaming":true,"chain_type":null,"message_id":"..."}`
- `message_id` is stable across one assistant generation
- Client may close after idle heartbeats; server can keep heartbeating after partial generation
- Terminal `message_saved` / `end` frames were **not always observed** before client idle-close in this probe; adapter must tolerate incomplete terminal markers and reconstruct final text from accumulated `plain` frames + later session history fetch if needed
### Dual-slot isolation evidence
| Desktop-like identity | `username` | `session_id` | Session list total |
| --- | --- | --- | --- |
| Companion | `desktop-companion` | `desktop-companion-s1` | 1 |
| Operations | `desktop-operations` | `desktop-operations-s1` | 1 |
Session list responses were fully isolated by `username`. Same API key can drive both slots if Desktop binds different local usernames/session ids per Profile. Prefer separate API keys later for least privilege, but not required for MVP connectivity.
### Mapping recommendation (internal Desktop events)
| AstrBot live frame | Desktop normalized event |
| --- | --- |
| comment `: heartbeat` | local connection liveness only (optional `system.heartbeat`) |
| `session_id` | bind conversation/session identity |
| `user_message_saved` | local user message ack / persistence metadata |
| `plain` + `streaming=true` | `message.delta` (append `data`) |
| accumulated plain until idle/end | `message.completed` (client synthesized if server omits terminal frame) |
| `error` | `error` |
| no `tool.proposal` observed | keep operations tools Desktop-local for now |
### Implementability verdict
| Goal | Verdict |
| --- | --- |
| Text chat against real AstrBot | **Implementable now** via adapter |
| Dual companion/operations chat panels on one server | **Implementable** with per-slot `username` + `session_id` |
| Direct use of provisional `/desktop/v1` against this server | **Not possible** |
| Long-lived server push bus + ACK | **Not available**; redesign stream manager |
| Server-driven local tool proposals | **Not available** on stock API |
| Need to rewrite whole Desktop app | **No** |
### Remaining probe gaps (non-blocking for chat MVP)
- Dashboard password login / JWT expiry behavior not live-tested
- File upload (`POST /api/v1/file`) not tested
- WebSocket `/api/v1/chat/ws` not tested
- Re-attach `GET /api/v1/chat/runs/{run_id}/stream` not tested
- No durable `serverInstanceId` discovery endpoint; still needs identity substitute design
- This deployment returns SPA 404 HTML for some documented OpenAPI paths; adapter should feature-detect actual routes rather than assume full OpenAPI UI availability
### Security notes from probe
- API key worked and must stay in Windows Credential Manager only
- Never log full key; sample captures store `abk_[REDACTED]`
- Prefer header auth, not query-string key
- Target is plain HTTP on LAN; TLS pinning decision remains open for production Profiles

查看文件

@ -0,0 +1,61 @@
# Non-destructive AstrBot live probe helper.
# Usage:
# $env:ASTRBOT_PROBE_KEY = "abk_..."
# $env:ASTRBOT_PROBE_BASE = "http://host:port"
# powershell -NoProfile -ExecutionPolicy Bypass -File .\run-live-probe.ps1
$ErrorActionPreference = "Stop"
$base = if ($env:ASTRBOT_PROBE_BASE) { $env:ASTRBOT_PROBE_BASE } else { "http://127.0.0.1:6185" }
$key = $env:ASTRBOT_PROBE_KEY
if (-not $key) { throw "Set ASTRBOT_PROBE_KEY first" }
$outDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$sseFile = Join-Path $outDir "astrbot-live-probe-sse.raw.txt"
$sumFile = Join-Path $outDir "astrbot-live-probe-summary.json"
$logFile = Join-Path $outDir "astrbot-live-probe-run.log"
function Log($m) { Add-Content -Path $logFile -Value ("[{0}] {1}" -f (Get-Date -Format o), $m) -Encoding utf8 }
function Invoke-SseChat([string]$body, [string]$label, [int]$timeoutSec = 90) {
Log "chat $label begin"
$req = [System.Net.HttpWebRequest]::Create("$base/api/v1/chat")
$req.Method = "POST"; $req.Timeout = $timeoutSec * 1000; $req.ReadWriteTimeout = 20000
$req.ContentType = "application/json; charset=utf-8"; $req.Accept = "text/event-stream, application/json"
$req.Headers.Add("Authorization", "Bearer $key")
$bytes = [System.Text.Encoding]::UTF8.GetBytes($body)
$req.ContentLength = $bytes.Length
$rs = $req.GetRequestStream(); $rs.Write($bytes,0,$bytes.Length); $rs.Close()
$resp = $req.GetResponse(); $reader = New-Object System.IO.StreamReader($resp.GetResponseStream())
$sb = New-Object System.Text.StringBuilder
$deadline = [DateTime]::UtcNow.AddSeconds($timeoutSec)
$lastData = [DateTime]::UtcNow; $plain = 0; $saved = $false
while ([DateTime]::UtcNow -lt $deadline) {
if ($reader.EndOfStream) { break }
try { $line = $reader.ReadLine() } catch { break }
if ($null -eq $line) { break }
[void]$sb.AppendLine($line)
if ($line.StartsWith("data:")) {
$lastData = [DateTime]::UtcNow
if ($line -match '"type": "plain"') { $plain++ }
if ($line -match '"type": "message_saved"' -or $line -match '"type": "error"') { $saved = $true }
}
if ($plain -gt 0 -and (([DateTime]::UtcNow - $lastData).TotalSeconds -ge 8)) { break }
if ($saved -and (([DateTime]::UtcNow - $lastData).TotalSeconds -ge 2)) { break }
}
try { $reader.Close() } catch {}; try { $resp.Close() } catch {}
Log "chat $label done len=$($sb.Length) plain=$plain saved=$saved"
return [PSCustomObject]@{ Length=$sb.Length; Body=$sb.ToString(); Plain=$plain; Saved=$saved }
}
function Get-Json($uri) {
$req = [System.Net.HttpWebRequest]::Create($uri); $req.Method = "GET"; $req.Timeout = 20000
$req.Headers.Add("Authorization", "Bearer $key")
$resp = $req.GetResponse(); $r = New-Object System.IO.StreamReader($resp.GetResponseStream()); $t = $r.ReadToEnd(); $r.Close(); $resp.Close(); return $t
}
"" | Set-Content $logFile -Encoding utf8
Log "start base=$base"
$rA = Invoke-SseChat '{"message":"desktop-probe A","username":"desktop-companion","session_id":"desktop-companion-s1","enable_streaming":true}' "companion" 90
$rB = Invoke-SseChat '{"message":"desktop-probe B","username":"desktop-operations","session_id":"desktop-operations-s1","enable_streaming":true}' "operations" 90
$sessA = Get-Json "$base/api/v1/chat/sessions?username=desktop-companion&page=1&page_size=20"
$sessB = Get-Json "$base/api/v1/chat/sessions?username=desktop-operations&page=1&page_size=20"
$raw = "=== companion ===`n$($rA.Body)`n=== operations ===`n$($rB.Body)`n=== sessions companion ===`n$sessA`n=== sessions operations ===`n$sessB"
($raw -replace [regex]::Escape($key), "abk_[REDACTED]") | Set-Content $sseFile -Encoding utf8
function Types($b){ $m=@{}; foreach($x in [regex]::Matches($b,'"type"\s*:\s*"([^"]+)"')){ $k=$x.Groups[1].Value; if($m.ContainsKey($k)){$m[$k]++}else{$m[$k]=1}}; $m }
$summary = [ordered]@{ ok=$true; base=$base; companion=@{length=$rA.Length;plain=$rA.Plain;saved=$rA.Saved;types=(Types $rA.Body)}; operations=@{length=$rB.Length;plain=$rB.Plain;saved=$rB.Saved;types=(Types $rB.Body)}; sessionsCompanion=($sessA|ConvertFrom-Json); sessionsOperations=($sessB|ConvertFrom-Json) }
($summary | ConvertTo-Json -Depth 8) | Set-Content $sumFile -Encoding utf8
Log "done"

查看文件

@ -2,6 +2,6 @@
"$schema": "../gen/schemas/desktop-schema.json", "$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default", "identifier": "default",
"description": "Minimal capability set for the main AstrBot Desktop window.", "description": "Minimal capability set for the main AstrBot Desktop window.",
"windows": ["main"], "windows": ["main", "quick-chat", "status-bubble"],
"permissions": ["core:default"] "permissions": ["core:default"]
} }

查看文件

@ -0,0 +1,362 @@
use desktop_protocol::AuthenticationType;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::database::{ApplicationDatabase, DatabaseError};
use crate::secure_store::{
CredentialReference, SecretCredential, SecureCredentialStore, SecureStoreError,
WindowsCredentialStore,
};
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct EnrollCredentialRequest {
pub profile_id: String,
pub authentication_type: AuthenticationType,
/// One-shot secret. Never returned to React and never logged.
pub secret: String,
#[serde(default)]
pub username: Option<String>,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CredentialEnrollmentResult {
pub profile_id: String,
pub credential_reference: String,
pub authentication_type: AuthenticationType,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CredentialCommandError {
pub code: &'static str,
pub message: &'static str,
}
impl std::fmt::Display for CredentialCommandError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.message)
}
}
impl std::error::Error for CredentialCommandError {}
impl CredentialCommandError {
fn validation(message: &'static str) -> Self {
Self {
code: "validationFailed",
message,
}
}
fn not_found() -> Self {
Self {
code: "notFound",
message: "The connection profile no longer exists.",
}
}
fn store() -> Self {
Self {
code: "secureStoreUnavailable",
message: "Windows Credential Manager is unavailable.",
}
}
fn database() -> Self {
Self {
code: "databaseUnavailable",
message: "The local profile database is unavailable.",
}
}
}
#[tauri::command]
pub fn enroll_profile_credential(
database: tauri::State<'_, ApplicationDatabase>,
request: EnrollCredentialRequest,
) -> Result<CredentialEnrollmentResult, CredentialCommandError> {
enroll_credential(&database, &WindowsCredentialStore, request)
}
#[tauri::command]
pub fn clear_profile_credential(
database: tauri::State<'_, ApplicationDatabase>,
profile_id: String,
) -> Result<(), CredentialCommandError> {
clear_credential(&database, &WindowsCredentialStore, &profile_id)
}
pub fn enroll_credential(
database: &ApplicationDatabase,
store: &impl SecureCredentialStore,
request: EnrollCredentialRequest,
) -> Result<CredentialEnrollmentResult, CredentialCommandError> {
if Uuid::parse_str(&request.profile_id).is_err() {
return Err(CredentialCommandError::validation(
"profile_id must be a UUID.",
));
}
if request.secret.trim().is_empty() {
return Err(CredentialCommandError::validation(
"credential secret must not be empty.",
));
}
if request.secret.len() > 2_560 {
return Err(CredentialCommandError::validation(
"credential secret exceeds the supported length.",
));
}
let mut profile = database
.profile(&request.profile_id)
.map_err(|_| CredentialCommandError::database())?
.ok_or_else(CredentialCommandError::not_found)?;
// Replace any previous reference after a successful write.
let reference = CredentialReference::new();
let credential =
SecretCredential::with_username(request.username.clone(), request.secret.into_bytes())
.map_err(|error| match error {
SecureStoreError::InvalidSecretLength | SecureStoreError::InvalidUsername => {
CredentialCommandError::validation("credential secret is invalid.")
}
_ => CredentialCommandError::store(),
})?;
store
.write(reference, &credential)
.map_err(|_| CredentialCommandError::store())?;
if let Some(previous) = profile
.credential_reference
.as_ref()
.and_then(|value| Uuid::parse_str(value).ok())
.map(CredentialReference::from_uuid)
{
let _ = store.delete(previous);
}
profile.credential_reference = Some(reference.as_uuid().to_string());
profile.authentication_type = request.authentication_type;
profile.updated_at = current_timestamp();
database
.update_profile(&profile)
.map_err(|error| match error {
DatabaseError::ProfileNotFound => CredentialCommandError::not_found(),
_ => CredentialCommandError::database(),
})?;
Ok(CredentialEnrollmentResult {
profile_id: profile.id,
credential_reference: reference.as_uuid().to_string(),
authentication_type: profile.authentication_type,
})
}
pub fn clear_credential(
database: &ApplicationDatabase,
store: &impl SecureCredentialStore,
profile_id: &str,
) -> Result<(), CredentialCommandError> {
if Uuid::parse_str(profile_id).is_err() {
return Err(CredentialCommandError::validation(
"profile_id must be a UUID.",
));
}
let mut profile = database
.profile(profile_id)
.map_err(|_| CredentialCommandError::database())?
.ok_or_else(CredentialCommandError::not_found)?;
if let Some(previous) = profile
.credential_reference
.as_ref()
.and_then(|value| Uuid::parse_str(value).ok())
.map(CredentialReference::from_uuid)
{
let _ = store.delete(previous);
}
profile.credential_reference = None;
profile.updated_at = current_timestamp();
database
.update_profile(&profile)
.map_err(|_| CredentialCommandError::database())?;
Ok(())
}
/// Loads a secret for Rust-owned networking only. Never exposed through Tauri commands.
pub fn load_profile_secret(
database: &ApplicationDatabase,
store: &impl SecureCredentialStore,
profile_id: &str,
) -> Result<Option<SecretCredential>, CredentialCommandError> {
let profile = database
.profile(profile_id)
.map_err(|_| CredentialCommandError::database())?
.ok_or_else(CredentialCommandError::not_found)?;
let Some(reference) = profile
.credential_reference
.as_ref()
.and_then(|value| Uuid::parse_str(value).ok())
.map(CredentialReference::from_uuid)
else {
return Ok(None);
};
store
.read(reference)
.map_err(|_| CredentialCommandError::store())
}
fn current_timestamp() -> String {
time::OffsetDateTime::now_utc()
.format(&time::format_description::well_known::Rfc3339)
.unwrap_or_else(|_| "1970-01-01T00:00:00Z".into())
}
#[cfg(test)]
mod tests {
use super::*;
use desktop_protocol::{AstrBotProfileRole, ConnectionProfile};
use std::collections::HashMap;
use std::sync::Mutex;
type MemoryCredential = (Option<String>, Vec<u8>);
#[derive(Default)]
struct MemoryStore {
values: Mutex<HashMap<Uuid, MemoryCredential>>,
}
impl SecureCredentialStore for MemoryStore {
fn write(
&self,
reference: CredentialReference,
credential: &SecretCredential,
) -> Result<(), SecureStoreError> {
self.values.lock().expect("lock").insert(
reference.as_uuid(),
(
credential.username().map(str::to_owned),
credential.secret().to_vec(),
),
);
Ok(())
}
fn read(
&self,
reference: CredentialReference,
) -> Result<Option<SecretCredential>, SecureStoreError> {
match self.values.lock().expect("lock").get(&reference.as_uuid()) {
Some((username, secret)) => Ok(Some(SecretCredential::with_username(
username.clone(),
secret.clone(),
)?)),
None => Ok(None),
}
}
fn delete(&self, reference: CredentialReference) -> Result<bool, SecureStoreError> {
Ok(self
.values
.lock()
.expect("lock")
.remove(&reference.as_uuid())
.is_some())
}
}
fn sample_profile() -> ConnectionProfile {
ConnectionProfile {
id: "11111111-1111-1111-1111-111111111111".into(),
display_name: "Probe".into(),
role: AstrBotProfileRole::Companion,
base_url: "http://127.0.0.1:26285/".into(),
event_stream_url: None,
authentication_type: AuthenticationType::ApiKey,
transport_kind: desktop_protocol::TransportKind::AstrBotOpenApi,
credential_reference: None,
allow_insecure_http: true,
pinned_certificate_fingerprint: None,
auto_connect_slot: None,
auto_connect: false,
server_instance_id: None,
server_version: None,
protocol_version: None,
local_tool_policy_id: None,
last_connected_at: None,
remote_username: None,
sticky_session_id: None,
created_at: "2026-07-20T00:00:00Z".into(),
updated_at: "2026-07-20T00:00:00Z".into(),
}
}
#[test]
fn enrolls_and_clears_credential_reference_without_returning_secret() {
let database = ApplicationDatabase::in_memory().expect("db");
let profile = sample_profile();
database.create_profile(&profile).expect("create");
let store = MemoryStore::default();
let enrolled = enroll_credential(
&database,
&store,
EnrollCredentialRequest {
profile_id: profile.id.clone(),
authentication_type: AuthenticationType::ApiKey,
secret: "abk_test_secret".into(),
username: Some("desktop-companion".into()),
},
)
.expect("enroll");
assert!(!enrolled.credential_reference.is_empty());
let stored = database
.profile(&profile.id)
.expect("profile")
.expect("exists");
assert_eq!(
stored.credential_reference.as_deref(),
Some(enrolled.credential_reference.as_str())
);
let secret = load_profile_secret(&database, &store, &profile.id)
.expect("load")
.expect("secret");
assert_eq!(secret.secret(), b"abk_test_secret");
assert_eq!(secret.username(), Some("desktop-companion"));
clear_credential(&database, &store, &profile.id).expect("clear");
let cleared = database
.profile(&profile.id)
.expect("profile")
.expect("exists");
assert!(cleared.credential_reference.is_none());
assert!(
load_profile_secret(&database, &store, &profile.id)
.expect("load missing")
.is_none()
);
}
#[test]
fn rejects_empty_secret() {
let database = ApplicationDatabase::in_memory().expect("db");
database.create_profile(&sample_profile()).expect("create");
let store = MemoryStore::default();
let error = enroll_credential(
&database,
&store,
EnrollCredentialRequest {
profile_id: "11111111-1111-1111-1111-111111111111".into(),
authentication_type: AuthenticationType::ApiKey,
secret: " ".into(),
username: None,
},
)
.expect_err("empty");
assert_eq!(error.code, "validationFailed");
}
}

查看文件

@ -2,11 +2,12 @@ mod profiles;
mod slots; mod slots;
use std::{path::Path, sync::Mutex, time::Duration}; use std::{path::Path, sync::Mutex, time::Duration};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use rusqlite::{Connection, OptionalExtension, params}; use rusqlite::{Connection, OptionalExtension, params};
use thiserror::Error; use thiserror::Error;
pub const CURRENT_SCHEMA_VERSION: u32 = 3; pub const CURRENT_SCHEMA_VERSION: u32 = 5;
pub struct ApplicationDatabase { pub struct ApplicationDatabase {
store: Mutex<ProfileMessageStore>, store: Mutex<ProfileMessageStore>,
@ -32,6 +33,52 @@ impl ApplicationDatabase {
.map_err(|_| DatabaseError::LockPoisoned)? .map_err(|_| DatabaseError::LockPoisoned)?
.schema_version() .schema_version()
} }
#[allow(clippy::too_many_arguments)]
pub fn upsert_chat_message(
&self,
account_id: &str,
profile_id: &str,
slot: &str,
server_instance_id: &str,
remote_username: Option<&str>,
session_id: &str,
message_id: &str,
role: &str,
content: &str,
streaming: bool,
error: bool,
) -> Result<(), DatabaseError> {
self.store
.lock()
.map_err(|_| DatabaseError::LockPoisoned)?
.upsert_chat_message(
account_id,
profile_id,
slot,
server_instance_id,
remote_username,
session_id,
message_id,
role,
content,
streaming,
error,
)
}
pub fn list_chat_messages(
&self,
profile_id: &str,
server_instance_id: &str,
session_id: &str,
limit: usize,
) -> Result<Vec<StoredChatMessage>, DatabaseError> {
self.store
.lock()
.map_err(|_| DatabaseError::LockPoisoned)?
.list_chat_messages(profile_id, server_instance_id, session_id, limit)
}
} }
pub struct ProfileMessageStore { pub struct ProfileMessageStore {
@ -91,6 +138,63 @@ impl ProfileMessageStore {
Ok(()) Ok(())
} }
#[allow(clippy::too_many_arguments)]
pub fn upsert_chat_message(
&self,
account_id: &str,
profile_id: &str,
slot: &str,
server_instance_id: &str,
remote_username: Option<&str>,
session_id: &str,
message_id: &str,
role: &str,
content: &str,
streaming: bool,
error: bool,
) -> Result<(), DatabaseError> {
let timestamp = OffsetDateTime::now_utc()
.format(&Rfc3339)
.map_err(|_| DatabaseError::InvalidStoredMessage)?;
self.connection.execute(
"INSERT INTO chat_messages (account_id, profile_id, slot, server_instance_id, remote_username, session_id, message_id, role, content, streaming, error, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12) ON CONFLICT(profile_id, server_instance_id, session_id, message_id) DO UPDATE SET content = excluded.content, streaming = excluded.streaming, error = excluded.error, updated_at = excluded.updated_at",
params![account_id, profile_id, slot, server_instance_id, remote_username, session_id, message_id, role, content, streaming, error, timestamp],
)?;
Ok(())
}
pub fn list_chat_messages(
&self,
profile_id: &str,
server_instance_id: &str,
session_id: &str,
limit: usize,
) -> Result<Vec<StoredChatMessage>, DatabaseError> {
let limit = limit.clamp(1, 200) as i64;
let mut statement = self.connection.prepare("SELECT account_id, profile_id, slot, server_instance_id, remote_username, session_id, message_id, role, content, streaming, error, updated_at FROM chat_messages WHERE profile_id = ?1 AND server_instance_id = ?2 AND session_id = ?3 ORDER BY updated_at ASC LIMIT ?4")?;
let rows = statement.query_map(
params![profile_id, server_instance_id, session_id, limit],
|row| {
Ok(StoredChatMessage {
account_id: row.get(0)?,
profile_id: row.get(1)?,
slot: row.get(2)?,
server_instance_id: row.get(3)?,
remote_username: row.get(4)?,
session_id: row.get(5)?,
message_id: row.get(6)?,
role: row.get(7)?,
content: row.get(8)?,
streaming: row.get::<_, i64>(9)? != 0,
error: row.get::<_, i64>(10)? != 0,
updated_at: row.get(11)?,
})
},
)?;
rows.collect::<Result<Vec<_>, _>>()
.map_err(DatabaseError::from)
}
pub fn message_content( pub fn message_content(
&self, &self,
profile_id: &str, profile_id: &str,
@ -116,6 +220,23 @@ impl ProfileMessageStore {
} }
} }
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StoredChatMessage {
pub account_id: String,
pub profile_id: String,
pub slot: String,
pub server_instance_id: String,
pub remote_username: Option<String>,
pub session_id: String,
pub message_id: String,
pub role: String,
pub content: String,
pub streaming: bool,
pub error: bool,
pub updated_at: String,
}
fn configure_connection(connection: &Connection, persistent: bool) -> Result<(), DatabaseError> { fn configure_connection(connection: &Connection, persistent: bool) -> Result<(), DatabaseError> {
connection.pragma_update(None, "foreign_keys", "ON")?; connection.pragma_update(None, "foreign_keys", "ON")?;
connection.busy_timeout(Duration::from_secs(5))?; connection.busy_timeout(Duration::from_secs(5))?;
@ -206,6 +327,37 @@ fn migrate(connection: &mut Connection) -> Result<(), DatabaseError> {
transaction.commit()?; transaction.commit()?;
} }
if found <= 3 {
let transaction = connection.transaction()?;
let has_transport: bool = transaction
.prepare("PRAGMA table_info(connection_profiles)")?
.query_map([], |row| row.get::<_, String>(1))?
.filter_map(Result::ok)
.any(|name| name == "transport_kind");
if !has_transport {
transaction.execute_batch(
"
ALTER TABLE connection_profiles
ADD COLUMN transport_kind TEXT NOT NULL DEFAULT 'desktop-v1';
ALTER TABLE connection_profiles
ADD COLUMN remote_username TEXT;
ALTER TABLE connection_profiles
ADD COLUMN sticky_session_id TEXT;
",
)?;
}
transaction.pragma_update(None, "user_version", 4)?;
transaction.commit()?;
}
if found <= 4 {
let transaction = connection.transaction()?;
transaction.execute_batch(
"CREATE TABLE IF NOT EXISTS chat_messages (account_id TEXT NOT NULL, profile_id TEXT NOT NULL, slot TEXT NOT NULL CHECK(slot IN ('companion', 'operations')), server_instance_id TEXT NOT NULL, remote_username TEXT, session_id TEXT NOT NULL, message_id TEXT NOT NULL, role TEXT NOT NULL CHECK(role IN ('user', 'assistant', 'system')), content TEXT NOT NULL, streaming INTEGER NOT NULL DEFAULT 0 CHECK(streaming IN (0, 1)), error INTEGER NOT NULL DEFAULT 0 CHECK(error IN (0, 1)), updated_at TEXT NOT NULL, PRIMARY KEY (profile_id, server_instance_id, session_id, message_id)); CREATE INDEX IF NOT EXISTS chat_messages_account_session_idx ON chat_messages(account_id, session_id, updated_at); PRAGMA user_version = 5;",
)?;
transaction.commit()?;
}
Ok(()) Ok(())
} }
@ -221,6 +373,8 @@ pub enum DatabaseError {
InvalidStoredProfile, InvalidStoredProfile,
#[error("database contains invalid connection slot data")] #[error("database contains invalid connection slot data")]
InvalidStoredSlot, InvalidStoredSlot,
#[error("database contains invalid chat message data")]
InvalidStoredMessage,
#[error("connection profile was not found")] #[error("connection profile was not found")]
ProfileNotFound, ProfileNotFound,
#[error("connection slot was not found")] #[error("connection slot was not found")]
@ -305,7 +459,7 @@ mod tests {
drop(connection); drop(connection);
let store = ProfileMessageStore::open(&path).expect("migrate database"); let store = ProfileMessageStore::open(&path).expect("migrate database");
assert_eq!(store.schema_version().expect("schema version"), 3); assert_eq!(store.schema_version().expect("schema version"), 5);
assert_eq!( assert_eq!(
store store
.message_content("profile-a", "server-a", "conversation-a", "message-a") .message_content("profile-a", "server-a", "conversation-a", "message-a")
@ -368,6 +522,8 @@ mod tests {
.execute_batch( .execute_batch(
" "
DROP TABLE connection_slots; 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; PRAGMA user_version = 2;
", ",
) )
@ -375,7 +531,7 @@ mod tests {
} }
let reopened = ProfileMessageStore::open(&path).expect("migrate v2 database"); let reopened = ProfileMessageStore::open(&path).expect("migrate v2 database");
assert_eq!(reopened.schema_version().expect("schema version"), 3); assert_eq!(reopened.schema_version().expect("schema version"), 5);
let profile_count: u32 = reopened let profile_count: u32 = reopened
.connection .connection
.query_row( .query_row(
@ -408,9 +564,9 @@ mod tests {
assert!(matches!( assert!(matches!(
ProfileMessageStore::open(path), ProfileMessageStore::open(path),
Err(DatabaseError::UnsupportedSchemaVersion { Err(DatabaseError::UnsupportedSchemaVersion {
found: 4, found,
supported: CURRENT_SCHEMA_VERSION supported: CURRENT_SCHEMA_VERSION
}) }) if found == CURRENT_SCHEMA_VERSION + 1
)); ));
} }

查看文件

@ -10,6 +10,7 @@ const PROFILE_COLUMNS: &str = "
base_url, base_url,
event_stream_url, event_stream_url,
authentication_type, authentication_type,
transport_kind,
credential_reference, credential_reference,
allow_insecure_http, allow_insecure_http,
pinned_certificate_fingerprint, pinned_certificate_fingerprint,
@ -20,6 +21,8 @@ const PROFILE_COLUMNS: &str = "
protocol_version, protocol_version,
local_tool_policy_id, local_tool_policy_id,
last_connected_at, last_connected_at,
remote_username,
sticky_session_id,
created_at, created_at,
updated_at updated_at
"; ";
@ -99,6 +102,7 @@ impl ProfileMessageStore {
base_url, base_url,
event_stream_url, event_stream_url,
authentication_type, authentication_type,
transport_kind,
credential_reference, credential_reference,
allow_insecure_http, allow_insecure_http,
pinned_certificate_fingerprint, pinned_certificate_fingerprint,
@ -109,11 +113,14 @@ impl ProfileMessageStore {
protocol_version, protocol_version,
local_tool_policy_id, local_tool_policy_id,
last_connected_at, last_connected_at,
remote_username,
sticky_session_id,
created_at, created_at,
updated_at updated_at
) VALUES ( ) VALUES (
?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9,
?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18 ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18,
?19, ?20, ?21
) )
", ",
params![ params![
@ -123,6 +130,7 @@ impl ProfileMessageStore {
profile.base_url, profile.base_url,
profile.event_stream_url, profile.event_stream_url,
authentication_to_str(profile.authentication_type), authentication_to_str(profile.authentication_type),
transport_to_str(profile.transport_kind),
profile.credential_reference, profile.credential_reference,
profile.allow_insecure_http, profile.allow_insecure_http,
profile.pinned_certificate_fingerprint, profile.pinned_certificate_fingerprint,
@ -133,6 +141,8 @@ impl ProfileMessageStore {
profile.protocol_version, profile.protocol_version,
profile.local_tool_policy_id, profile.local_tool_policy_id,
profile.last_connected_at, profile.last_connected_at,
profile.remote_username,
profile.sticky_session_id,
profile.created_at, profile.created_at,
profile.updated_at, profile.updated_at,
], ],
@ -149,18 +159,21 @@ impl ProfileMessageStore {
base_url = ?4, base_url = ?4,
event_stream_url = ?5, event_stream_url = ?5,
authentication_type = ?6, authentication_type = ?6,
credential_reference = ?7, transport_kind = ?7,
allow_insecure_http = ?8, credential_reference = ?8,
pinned_certificate_fingerprint = ?9, allow_insecure_http = ?9,
auto_connect_slot = ?10, pinned_certificate_fingerprint = ?10,
auto_connect = ?11, auto_connect_slot = ?11,
server_instance_id = ?12, auto_connect = ?12,
server_version = ?13, server_instance_id = ?13,
protocol_version = ?14, server_version = ?14,
local_tool_policy_id = ?15, protocol_version = ?15,
last_connected_at = ?16, local_tool_policy_id = ?16,
created_at = ?17, last_connected_at = ?17,
updated_at = ?18 remote_username = ?18,
sticky_session_id = ?19,
created_at = ?20,
updated_at = ?21
WHERE id = ?1 WHERE id = ?1
", ",
params![ params![
@ -170,6 +183,7 @@ impl ProfileMessageStore {
profile.base_url, profile.base_url,
profile.event_stream_url, profile.event_stream_url,
authentication_to_str(profile.authentication_type), authentication_to_str(profile.authentication_type),
transport_to_str(profile.transport_kind),
profile.credential_reference, profile.credential_reference,
profile.allow_insecure_http, profile.allow_insecure_http,
profile.pinned_certificate_fingerprint, profile.pinned_certificate_fingerprint,
@ -180,6 +194,8 @@ impl ProfileMessageStore {
profile.protocol_version, profile.protocol_version,
profile.local_tool_policy_id, profile.local_tool_policy_id,
profile.last_connected_at, profile.last_connected_at,
profile.remote_username,
profile.sticky_session_id,
profile.created_at, profile.created_at,
profile.updated_at, profile.updated_at,
], ],
@ -214,13 +230,19 @@ fn profile_from_row(row: &Row<'_>) -> Result<ConnectionProfile, DatabaseError> {
"api-key" => AuthenticationType::ApiKey, "api-key" => AuthenticationType::ApiKey,
_ => return Err(DatabaseError::InvalidStoredProfile), _ => return Err(DatabaseError::InvalidStoredProfile),
}; };
let auto_connect_slot = match row.get::<_, Option<String>>(9)?.as_deref() { let transport_kind = match row.get::<_, String>(6)?.as_str() {
Some("companion") => Some(ActiveSlotKind::Companion), "desktop-v1" => desktop_protocol::TransportKind::DesktopV1,
Some("operations") => Some(ActiveSlotKind::Operations), "astrbot-openapi" => desktop_protocol::TransportKind::AstrBotOpenApi,
Some(_) => return Err(DatabaseError::InvalidStoredProfile), _ => return Err(DatabaseError::InvalidStoredProfile),
};
let auto_connect_slot = match row.get::<_, Option<String>>(10)? {
Some(value) => Some(match value.as_str() {
"companion" => ActiveSlotKind::Companion,
"operations" => ActiveSlotKind::Operations,
_ => return Err(DatabaseError::InvalidStoredProfile),
}),
None => None, None => None,
}; };
Ok(ConnectionProfile { Ok(ConnectionProfile {
id: row.get(0)?, id: row.get(0)?,
display_name: row.get(1)?, display_name: row.get(1)?,
@ -228,18 +250,21 @@ fn profile_from_row(row: &Row<'_>) -> Result<ConnectionProfile, DatabaseError> {
base_url: row.get(3)?, base_url: row.get(3)?,
event_stream_url: row.get(4)?, event_stream_url: row.get(4)?,
authentication_type, authentication_type,
credential_reference: row.get(6)?, transport_kind,
allow_insecure_http: row.get(7)?, credential_reference: row.get(7)?,
pinned_certificate_fingerprint: row.get(8)?, allow_insecure_http: row.get::<_, i64>(8)? != 0,
pinned_certificate_fingerprint: row.get(9)?,
auto_connect_slot, auto_connect_slot,
auto_connect: row.get(10)?, auto_connect: row.get::<_, i64>(11)? != 0,
server_instance_id: row.get(11)?, server_instance_id: row.get(12)?,
server_version: row.get(12)?, server_version: row.get(13)?,
protocol_version: row.get(13)?, protocol_version: row.get(14)?,
local_tool_policy_id: row.get(14)?, local_tool_policy_id: row.get(15)?,
last_connected_at: row.get(15)?, last_connected_at: row.get(16)?,
created_at: row.get(16)?, remote_username: row.get(17)?,
updated_at: row.get(17)?, sticky_session_id: row.get(18)?,
created_at: row.get(19)?,
updated_at: row.get(20)?,
}) })
} }
@ -258,6 +283,10 @@ fn authentication_to_str(authentication_type: AuthenticationType) -> &'static st
} }
} }
fn transport_to_str(transport_kind: desktop_protocol::TransportKind) -> &'static str {
transport_kind.as_str()
}
fn slot_to_str(slot: ActiveSlotKind) -> &'static str { fn slot_to_str(slot: ActiveSlotKind) -> &'static str {
match slot { match slot {
ActiveSlotKind::Companion => "companion", ActiveSlotKind::Companion => "companion",
@ -277,6 +306,7 @@ mod tests {
base_url: format!("https://example-{index}.test/"), base_url: format!("https://example-{index}.test/"),
event_stream_url: None, event_stream_url: None,
authentication_type: AuthenticationType::DeviceToken, authentication_type: AuthenticationType::DeviceToken,
transport_kind: desktop_protocol::TransportKind::DesktopV1,
credential_reference: None, credential_reference: None,
allow_insecure_http: false, allow_insecure_http: false,
pinned_certificate_fingerprint: None, pinned_certificate_fingerprint: None,
@ -287,6 +317,8 @@ mod tests {
protocol_version: None, protocol_version: None,
local_tool_policy_id: None, local_tool_policy_id: None,
last_connected_at: None, last_connected_at: None,
remote_username: None,
sticky_session_id: None,
created_at: "2026-07-18T00:00:00Z".into(), created_at: "2026-07-18T00:00:00Z".into(),
updated_at: "2026-07-18T00:00:00Z".into(), updated_at: "2026-07-18T00:00:00Z".into(),
} }

查看文件

@ -176,6 +176,7 @@ mod tests {
base_url: format!("https://example-{index}.test/"), base_url: format!("https://example-{index}.test/"),
event_stream_url: None, event_stream_url: None,
authentication_type: AuthenticationType::DeviceToken, authentication_type: AuthenticationType::DeviceToken,
transport_kind: desktop_protocol::TransportKind::DesktopV1,
credential_reference: None, credential_reference: None,
allow_insecure_http: false, allow_insecure_http: false,
pinned_certificate_fingerprint: None, pinned_certificate_fingerprint: None,
@ -186,6 +187,8 @@ mod tests {
protocol_version: None, protocol_version: None,
local_tool_policy_id: None, local_tool_policy_id: None,
last_connected_at: None, last_connected_at: None,
remote_username: None,
sticky_session_id: None,
created_at: "2026-07-19T00:00:00Z".into(), created_at: "2026-07-19T00:00:00Z".into(),
updated_at: "2026-07-19T00:00:00Z".into(), updated_at: "2026-07-19T00:00:00Z".into(),
} }

查看文件

@ -1,8 +1,10 @@
pub mod credentials;
pub mod database; pub mod database;
pub mod diagnostics; pub mod diagnostics;
pub mod file_transfer; pub mod file_transfer;
pub mod logging; pub mod logging;
pub mod networking; pub mod networking;
pub mod pet;
pub mod policy; pub mod policy;
pub mod profiles; pub mod profiles;
pub mod runtime_guards; pub mod runtime_guards;
@ -11,12 +13,13 @@ pub mod slots;
pub mod windows; pub mod windows;
use database::ApplicationDatabase; use database::ApplicationDatabase;
use networking::DualSlotRuntime;
use policy::ConnectionPolicyStatus; use policy::ConnectionPolicyStatus;
use runtime_guards::RuntimeGuards; use runtime_guards::RuntimeGuards;
use serde::Serialize; use serde::Serialize;
use tauri::{ use tauri::{
Manager, WindowEvent, AppHandle, Manager, WebviewUrl, WebviewWindowBuilder, WindowEvent,
menu::{Menu, MenuItem}, menu::{Menu, MenuItem},
tray::TrayIconBuilder, tray::TrayIconBuilder,
}; };
@ -31,6 +34,50 @@ struct BootstrapStatus {
protocol_version: &'static str, protocol_version: &'static str,
} }
#[tauri::command]
fn open_status_bubble_window(app: AppHandle) -> Result<(), String> {
if let Some(window) = app.get_webview_window("status-bubble") {
window.show().map_err(|error| error.to_string())?;
return Ok(());
}
WebviewWindowBuilder::new(
&app,
"status-bubble",
WebviewUrl::App("index.html?view=bubble".into()),
)
.title("AstrBot Status")
.inner_size(108.0, 108.0)
.resizable(false)
.decorations(false)
.transparent(true)
.always_on_top(false)
.skip_taskbar(true)
.build()
.map(|_| ())
.map_err(|error| error.to_string())
}
#[tauri::command]
fn open_quick_chat_window(app: AppHandle) -> Result<(), String> {
if let Some(window) = app.get_webview_window("quick-chat") {
window.show().map_err(|error| error.to_string())?;
window.set_focus().map_err(|error| error.to_string())?;
return Ok(());
}
WebviewWindowBuilder::new(
&app,
"quick-chat",
WebviewUrl::App("index.html?view=quick".into()),
)
.title("AstrBot Quick Chat")
.inner_size(420.0, 620.0)
.min_inner_size(320.0, 420.0)
.resizable(true)
.build()
.map(|_| ())
.map_err(|error| error.to_string())
}
#[tauri::command] #[tauri::command]
fn bootstrap_status( fn bootstrap_status(
database: tauri::State<'_, ApplicationDatabase>, database: tauri::State<'_, ApplicationDatabase>,
@ -82,6 +129,7 @@ pub fn run() {
app_data_dir.join("astrbot-desktop.sqlite3"), app_data_dir.join("astrbot-desktop.sqlite3"),
)?); )?);
app.manage(RuntimeGuards::new()); app.manage(RuntimeGuards::new());
app.manage(DualSlotRuntime::new());
let show = MenuItem::with_id(app, "show", "Show AstrBot Desktop", true, None::<&str>)?; let show = MenuItem::with_id(app, "show", "Show AstrBot Desktop", true, None::<&str>)?;
let quit = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?; let quit = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?;
@ -111,6 +159,8 @@ pub fn run() {
}) })
.invoke_handler(tauri::generate_handler![ .invoke_handler(tauri::generate_handler![
bootstrap_status, bootstrap_status,
open_quick_chat_window,
open_status_bubble_window,
connection_policy_status, connection_policy_status,
profiles::list_connection_profiles, profiles::list_connection_profiles,
profiles::create_connection_profile, profiles::create_connection_profile,
@ -119,6 +169,14 @@ pub fn run() {
slots::list_connection_slots, slots::list_connection_slots,
slots::assign_connection_slot, slots::assign_connection_slot,
slots::clear_connection_slot, slots::clear_connection_slot,
credentials::enroll_profile_credential,
credentials::clear_profile_credential,
networking::commands::connection_runtime_status,
networking::commands::drain_connection_runtime_events,
networking::commands::load_chat_messages,
networking::commands::probe_connection_slot,
networking::commands::disconnect_connection_slot,
networking::commands::send_connection_slot_message,
]) ])
.run(tauri::generate_context!()) .run(tauri::generate_context!())
.expect("failed to run AstrBot Desktop"); .expect("failed to run AstrBot Desktop");

查看文件

@ -0,0 +1,444 @@
use std::{collections::VecDeque, sync::Arc, time::Duration};
use desktop_protocol::{
AstrBotApiEnvelope, AstrBotChatRequest, AstrBotConfigListData, AstrBotSessionListData,
AstrBotStreamMapper, BoundGatewayEvent, ConnectionState, GatewayEvent, PROTOCOL_VERSION,
derive_astrbot_server_instance_id,
};
use futures_util::StreamExt;
use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, HeaderValue};
use secrecy::{ExposeSecret, SecretString};
use serde_json::{Value, json};
use thiserror::Error;
use tokio::sync::{Mutex, mpsc, watch};
use tokio_util::sync::CancellationToken;
use super::{GatewayError, SlotKind};
#[derive(Debug, Clone)]
pub struct AstrBotClientConfig {
pub profile_id: String,
pub slot: SlotKind,
pub base_url: String,
pub api_key: SecretString,
/// Remote WebChat username used as session owner identity.
pub remote_username: String,
/// Optional sticky session id. When absent, the first chat response supplies one.
pub session_id: Option<String>,
/// Expected server identity substitute. Empty means accept first observed identity.
pub expected_server_instance_id: Option<String>,
}
#[derive(Debug, Error)]
pub enum AstrBotClientError {
#[error("astrbot request failed")]
Request(#[from] reqwest::Error),
#[error("astrbot returned HTTP {0}")]
HttpStatus(reqwest::StatusCode),
#[error("astrbot api status error: {0}")]
ApiStatus(String),
#[error("invalid astrbot payload")]
Json(#[from] serde_json::Error),
#[error("astrbot stream mapping failed: {0}")]
Map(String),
#[error("server identity changed")]
ServerIdentityChanged,
#[error("astrbot event channel closed")]
ChannelClosed,
#[error("invalid configuration: {0}")]
InvalidConfig(&'static str),
}
impl From<AstrBotClientError> for GatewayError {
fn from(value: AstrBotClientError) -> Self {
match value {
AstrBotClientError::Request(error) => GatewayError::Request(error),
AstrBotClientError::HttpStatus(status) => GatewayError::HttpStatus(status),
AstrBotClientError::Json(error) => GatewayError::Json(error),
AstrBotClientError::ServerIdentityChanged => GatewayError::ServerIdentityChanged,
AstrBotClientError::ChannelClosed => GatewayError::ChannelClosed,
AstrBotClientError::ApiStatus(message) => GatewayError::Adapter(message),
AstrBotClientError::Map(message) => GatewayError::Adapter(message),
AstrBotClientError::InvalidConfig(message) => GatewayError::Adapter(message.to_owned()),
}
}
}
const MAX_DEDUPLICATED_EVENTS: usize = 4_096;
#[derive(Default)]
struct EventDeduplicator {
ids: std::collections::HashSet<String>,
order: VecDeque<String>,
}
impl EventDeduplicator {
fn insert(&mut self, event_id: String) -> bool {
if !self.ids.insert(event_id.clone()) {
return false;
}
self.order.push_back(event_id);
if self.order.len() > MAX_DEDUPLICATED_EVENTS
&& let Some(expired) = self.order.pop_front()
{
self.ids.remove(&expired);
}
true
}
}
pub struct AstrBotClient {
config: AstrBotClientConfig,
http: reqwest::Client,
seen_event_ids: Arc<Mutex<EventDeduplicator>>,
session_id: Arc<Mutex<Option<String>>>,
server_instance_id: Arc<Mutex<String>>,
state_tx: watch::Sender<ConnectionState>,
}
impl AstrBotClient {
pub fn new(config: AstrBotClientConfig) -> Result<Self, AstrBotClientError> {
if config.base_url.trim().is_empty() {
return Err(AstrBotClientError::InvalidConfig("base_url is required"));
}
if config.remote_username.trim().is_empty() {
return Err(AstrBotClientError::InvalidConfig(
"remote_username is required",
));
}
if config.api_key.expose_secret().trim().is_empty() {
return Err(AstrBotClientError::InvalidConfig("api_key is required"));
}
let base = config.base_url.trim_end_matches('/').to_owned();
let derived = derive_astrbot_server_instance_id(&base);
let initial_identity = config
.expected_server_instance_id
.clone()
.filter(|value| !value.trim().is_empty())
.unwrap_or(derived);
let mut headers = HeaderMap::new();
let auth_value = format!("Bearer {}", config.api_key.expose_secret());
headers.insert(
AUTHORIZATION,
HeaderValue::from_str(&auth_value).map_err(|_| {
AstrBotClientError::InvalidConfig("api_key has invalid header chars")
})?,
);
let http = reqwest::Client::builder()
.default_headers(headers)
.redirect(reqwest::redirect::Policy::none())
.connect_timeout(Duration::from_secs(5))
.timeout(Duration::from_secs(120))
.build()?;
let (state_tx, _) = watch::channel(ConnectionState::Disconnected);
let initial_session = config.session_id.clone();
Ok(Self {
config: AstrBotClientConfig {
base_url: base,
..config
},
http,
seen_event_ids: Arc::new(Mutex::new(EventDeduplicator::default())),
session_id: Arc::new(Mutex::new(initial_session)),
server_instance_id: Arc::new(Mutex::new(initial_identity)),
state_tx,
})
}
pub fn state_receiver(&self) -> watch::Receiver<ConnectionState> {
self.state_tx.subscribe()
}
pub fn server_instance_id_blocking(&self) -> String {
self.server_instance_id
.try_lock()
.map(|guard| guard.clone())
.unwrap_or_else(|_| derive_astrbot_server_instance_id(&self.config.base_url))
}
fn set_state(&self, state: ConnectionState) {
self.state_tx.send_replace(state);
}
fn url(&self, path: &str) -> String {
format!("{}{}", self.config.base_url, path)
}
pub async fn probe(&self) -> Result<Value, AstrBotClientError> {
self.set_state(ConnectionState::Connecting);
let response = self
.http
.get(self.url(&format!(
"/api/v1/chat/sessions?username={}&page=1&page_size=1",
urlencoding_username(&self.config.remote_username)
)))
.send()
.await?;
if response.status().as_u16() == 401 || response.status().as_u16() == 403 {
self.set_state(ConnectionState::AuthExpired);
return Err(AstrBotClientError::HttpStatus(response.status()));
}
if !response.status().is_success() {
self.set_state(ConnectionState::ServerUnavailable);
return Err(AstrBotClientError::HttpStatus(response.status()));
}
let envelope: AstrBotApiEnvelope<AstrBotSessionListData> = response.json().await?;
if !envelope.is_ok() {
self.set_state(ConnectionState::FatalError);
return Err(AstrBotClientError::ApiStatus(
envelope
.message
.unwrap_or_else(|| "chat sessions probe failed".into()),
));
}
self.set_state(ConnectionState::Connected);
Ok(json!({
"status": "ok",
"protocolVersion": PROTOCOL_VERSION,
"transport": "astrbot-openapi",
"serverInstanceId": self.server_instance_id.lock().await.clone(),
"remoteUsername": self.config.remote_username,
"sessionCount": envelope.data.map(|data| data.total.unwrap_or(0)).unwrap_or(0),
}))
}
pub async fn list_sessions(&self) -> Result<AstrBotSessionListData, AstrBotClientError> {
let response = self
.http
.get(self.url(&format!(
"/api/v1/chat/sessions?username={}&page=1&page_size=50",
urlencoding_username(&self.config.remote_username)
)))
.send()
.await?;
if !response.status().is_success() {
return Err(AstrBotClientError::HttpStatus(response.status()));
}
let envelope: AstrBotApiEnvelope<AstrBotSessionListData> = response.json().await?;
if !envelope.is_ok() {
return Err(AstrBotClientError::ApiStatus(
envelope
.message
.unwrap_or_else(|| "list sessions failed".into()),
));
}
Ok(envelope.data.unwrap_or(AstrBotSessionListData {
sessions: Vec::new(),
page: Some(1),
page_size: Some(50),
total: Some(0),
}))
}
pub async fn list_configs(&self) -> Result<AstrBotConfigListData, AstrBotClientError> {
let response = self.http.get(self.url("/api/v1/configs")).send().await?;
if !response.status().is_success() {
return Err(AstrBotClientError::HttpStatus(response.status()));
}
let envelope: AstrBotApiEnvelope<AstrBotConfigListData> = response.json().await?;
if !envelope.is_ok() {
return Err(AstrBotClientError::ApiStatus(
envelope
.message
.unwrap_or_else(|| "list configs failed".into()),
));
}
Ok(envelope.data.unwrap_or(AstrBotConfigListData {
configs: Vec::new(),
}))
}
pub async fn send_chat_stream(
&self,
message: &str,
sender: &mpsc::Sender<super::gateway_client::BoundGatewayEvent>,
cancellation: &CancellationToken,
) -> Result<Option<String>, AstrBotClientError> {
self.set_state(ConnectionState::Syncing);
let session_id = self.session_id.lock().await.clone();
let request = AstrBotChatRequest {
message: Value::String(message.to_owned()),
session_id: session_id.clone(),
conversation_id: None,
username: Some(self.config.remote_username.clone()),
config_id: None,
platform_id: None,
enable_streaming: Some(true),
};
let response = self
.http
.post(self.url("/api/v1/chat"))
.header(ACCEPT, HeaderValue::from_static("text/event-stream"))
.json(&request)
.send()
.await?;
if response.status().as_u16() == 401 || response.status().as_u16() == 403 {
self.set_state(ConnectionState::AuthExpired);
return Err(AstrBotClientError::HttpStatus(response.status()));
}
if !response.status().is_success() {
self.set_state(ConnectionState::ServerUnavailable);
return Err(AstrBotClientError::HttpStatus(response.status()));
}
let server_instance_id = self.server_instance_id.lock().await.clone();
if let Some(expected) = &self.config.expected_server_instance_id
&& !expected.is_empty()
&& expected != &server_instance_id
{
self.set_state(ConnectionState::CertificateChanged);
return Err(AstrBotClientError::ServerIdentityChanged);
}
let mut mapper = AstrBotStreamMapper::new(server_instance_id.clone());
if let Some(existing) = session_id {
let seed = serde_json::json!({
"type": "session_id",
"data": null,
"session_id": existing,
});
let _ = mapper.push_line(&format!("data: {seed}"));
}
let mut stream = response.bytes_stream();
let mut buffer = String::new();
self.set_state(ConnectionState::Connected);
loop {
tokio::select! {
_ = cancellation.cancelled() => {
self.set_state(ConnectionState::Disconnected);
return Ok(mapper.session_id().map(str::to_owned));
}
next = stream.next() => {
let Some(next) = next else { break; };
let chunk = next?;
buffer.push_str(&String::from_utf8_lossy(&chunk));
while let Some(index) = buffer.find('\n') {
let mut line = buffer[..index].to_owned();
buffer.drain(..=index);
if line.ends_with('\r') {
line.pop();
}
let events = mapper
.push_line(&line)
.map_err(|error| AstrBotClientError::Map(error.to_string()))?;
self.dispatch_events(events, sender).await?;
}
}
}
}
if !buffer.trim().is_empty() {
let events = mapper
.push_line(buffer.trim_end_matches('\r'))
.map_err(|error| AstrBotClientError::Map(error.to_string()))?;
self.dispatch_events(events, sender).await?;
}
let events = mapper.finish_stream();
self.dispatch_events(events, sender).await?;
if let Some(session) = mapper.session_id() {
*self.session_id.lock().await = Some(session.to_owned());
}
self.set_state(ConnectionState::Connected);
Ok(self.session_id.lock().await.clone())
}
async fn dispatch_events(
&self,
events: Vec<GatewayEvent>,
sender: &mpsc::Sender<super::gateway_client::BoundGatewayEvent>,
) -> Result<(), AstrBotClientError> {
for event in events {
if let Some(session_id) = event.metadata.session_id.clone() {
*self.session_id.lock().await = Some(session_id);
}
let event_id = event.metadata.event_id.clone();
let mut seen = self.seen_event_ids.lock().await;
if !seen.insert(event_id.clone()) {
continue;
}
drop(seen);
let payload = serde_json::to_value(&event.body)
.map_err(|error| AstrBotClientError::Map(error.to_string()))?;
let bound = BoundGatewayEvent {
profile_id: self.config.profile_id.clone(),
slot: protocol_slot(self.config.slot),
event,
};
sender
.send(super::gateway_client::BoundGatewayEvent {
profile_id: bound.profile_id,
slot: self.config.slot,
event_id,
event_type: bound.event.event_type().to_owned(),
server_instance_id: bound.event.metadata.server_instance_id.clone(),
session_id: bound.event.metadata.session_id.clone(),
message_id: bound.event.metadata.message_id.clone(),
payload,
})
.await
.map_err(|_| AstrBotClientError::ChannelClosed)?;
}
Ok(())
}
}
fn protocol_slot(slot: SlotKind) -> desktop_protocol::ActiveSlotKind {
match slot {
SlotKind::Companion => desktop_protocol::ActiveSlotKind::Companion,
SlotKind::Operations => desktop_protocol::ActiveSlotKind::Operations,
}
}
fn urlencoding_username(username: &str) -> String {
username
.chars()
.map(|ch| match ch {
'A'..='Z' | 'a'..='z' | '0'..='9' | '-' | '_' | '.' | '~' => ch.to_string(),
_ => format!("%{:02X}", ch as u8),
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejects_empty_api_key_and_username() {
let result = AstrBotClient::new(AstrBotClientConfig {
profile_id: "p".into(),
slot: SlotKind::Companion,
base_url: "http://127.0.0.1:1".into(),
api_key: SecretString::from(String::new()),
remote_username: "user".into(),
session_id: None,
expected_server_instance_id: None,
});
assert!(matches!(result, Err(AstrBotClientError::InvalidConfig(_))));
}
#[test]
fn derives_identity_from_base_url() {
let client = AstrBotClient::new(AstrBotClientConfig {
profile_id: "p".into(),
slot: SlotKind::Companion,
base_url: "http://192.168.31.210:26285/".into(),
api_key: SecretString::from("abk_test".to_owned()),
remote_username: "desktop-companion".into(),
session_id: Some("s1".into()),
expected_server_instance_id: None,
})
.expect("client");
assert!(client.server_instance_id_blocking().starts_with("astrbot-"));
}
}

查看文件

@ -0,0 +1,320 @@
// IPC wrappers for dual-slot runtime. Secrets never leave Rust.
use desktop_protocol::TransportKind;
use secrecy::SecretString;
use serde::Deserialize;
use serde_json::Value;
use tauri::State;
use super::{
ConnectionRuntimeStatus, DualSlotRuntime, RuntimeCommandError, SlotActivationRequest, SlotKind,
SlotRuntimeSnapshot,
};
use crate::credentials::{CredentialCommandError, load_profile_secret};
use crate::database::ApplicationDatabase;
use crate::secure_store::WindowsCredentialStore;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ProbeConnectionSlotRequest {
pub slot: SlotKind,
pub profile_id: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DisconnectConnectionSlotRequest {
pub slot: SlotKind,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SendConnectionSlotMessageRequest {
pub slot: SlotKind,
pub message: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DrainConnectionRuntimeEventsRequest {
pub limit: Option<usize>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LoadChatMessagesRequest {
pub profile_id: String,
pub server_instance_id: String,
pub session_id: String,
pub limit: Option<usize>,
}
#[tauri::command]
pub async fn connection_runtime_status(
runtime: State<'_, DualSlotRuntime>,
) -> Result<ConnectionRuntimeStatus, RuntimeCommandError> {
Ok(runtime.status().await)
}
#[tauri::command]
pub async fn drain_connection_runtime_events(
database: State<'_, ApplicationDatabase>,
runtime: State<'_, DualSlotRuntime>,
request: DrainConnectionRuntimeEventsRequest,
) -> Result<Vec<super::BoundGatewayEvent>, RuntimeCommandError> {
let events = runtime.drain_events(request.limit.unwrap_or(64)).await;
for event in &events {
persist_runtime_event(&database, event);
}
Ok(events)
}
#[tauri::command]
pub async fn load_chat_messages(
database: State<'_, ApplicationDatabase>,
request: LoadChatMessagesRequest,
) -> Result<Vec<crate::database::StoredChatMessage>, RuntimeCommandError> {
database
.list_chat_messages(
&request.profile_id,
&request.server_instance_id,
&request.session_id,
request.limit.unwrap_or(100),
)
.map_err(|_| RuntimeCommandError {
code: "databaseUnavailable",
message: "Chat history is unavailable.",
})
}
fn persist_runtime_event(database: &ApplicationDatabase, event: &super::BoundGatewayEvent) {
let Some(session_id) = event.session_id.as_deref() else {
return;
};
let Some((role, content, streaming, message_id)) = (match event.event_type.as_str() {
"message.delta" => Some((
"assistant",
event
.payload
.get("delta")
.and_then(Value::as_str)
.unwrap_or_default(),
true,
event
.message_id
.as_deref()
.unwrap_or(event.event_id.as_str()),
)),
"message.completed" => Some((
"assistant",
event
.payload
.get("content")
.and_then(Value::as_str)
.unwrap_or_default(),
false,
event
.message_id
.as_deref()
.unwrap_or(event.event_id.as_str()),
)),
"message.proactive" => Some((
"assistant",
event
.payload
.get("content")
.and_then(Value::as_str)
.unwrap_or_default(),
false,
event.event_id.as_str(),
)),
"error" => Some((
"system",
event
.payload
.get("message")
.and_then(Value::as_str)
.unwrap_or("Connection error"),
false,
event.event_id.as_str(),
)),
_ => None,
}) else {
return;
};
let slot = match event.slot {
SlotKind::Companion => "companion",
SlotKind::Operations => "operations",
};
let _ = database.upsert_chat_message(
"local-default",
&event.profile_id,
slot,
&event.server_instance_id,
None,
session_id,
message_id,
role,
content,
streaming,
event.event_type == "error",
);
}
#[tauri::command]
pub async fn probe_connection_slot(
database: State<'_, ApplicationDatabase>,
runtime: State<'_, DualSlotRuntime>,
request: ProbeConnectionSlotRequest,
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
let profile = database
.profile(&request.profile_id)
.map_err(|_| RuntimeCommandError {
code: "databaseUnavailable",
message: "The local profile database is unavailable.",
})?
.ok_or(RuntimeCommandError {
code: "notFound",
message: "The connection profile no longer exists.",
})?;
if profile.transport_kind != TransportKind::AstrBotOpenApi
&& profile.transport_kind != TransportKind::DesktopV1
{
return Err(RuntimeCommandError {
code: "validationFailed",
message: "Unsupported transport kind.",
});
}
let secret = load_profile_secret(&database, &WindowsCredentialStore, &profile.id).map_err(
|error: CredentialCommandError| RuntimeCommandError {
code: error.code,
message: error.message,
},
)?;
let activation = match profile.transport_kind {
TransportKind::AstrBotOpenApi => {
let secret = secret.ok_or(RuntimeCommandError {
code: "credentialMissing",
message: "Enroll an API key before probing an AstrBot profile.",
})?;
let api_key =
String::from_utf8(secret.secret().to_vec()).map_err(|_| RuntimeCommandError {
code: "credentialInvalid",
message: "Stored API key is not valid UTF-8.",
})?;
let remote_username = profile.remote_username.clone().ok_or(RuntimeCommandError {
code: "validationFailed",
message: "AstrBot profiles require remote_username.",
})?;
SlotActivationRequest {
profile_id: profile.id.clone(),
slot: request.slot,
base_url: profile.base_url.clone(),
transport: TransportKind::AstrBotOpenApi,
api_key: Some(SecretString::from(api_key)),
bearer_token: None,
remote_username: Some(remote_username),
session_id: profile.sticky_session_id.clone(),
expected_server_instance_id: profile.server_instance_id.clone(),
}
}
TransportKind::DesktopV1 => {
let bearer = secret.and_then(|value| {
String::from_utf8(value.secret().to_vec())
.ok()
.map(SecretString::from)
});
let expected = profile
.server_instance_id
.clone()
.ok_or(RuntimeCommandError {
code: "validationFailed",
message: "Desktop gateway profiles require server_instance_id before probe.",
})?;
SlotActivationRequest {
profile_id: profile.id.clone(),
slot: request.slot,
base_url: profile.base_url.clone(),
transport: TransportKind::DesktopV1,
api_key: None,
bearer_token: bearer,
remote_username: None,
session_id: None,
expected_server_instance_id: Some(expected),
}
}
};
let snapshot = runtime.activate_slot(activation).await?;
// Persist observed identity / sticky session without exposing secrets.
if let Ok(Some(mut stored)) = database.profile(&request.profile_id) {
let mut dirty = false;
if stored.server_instance_id.is_none()
&& let Some(server_instance_id) = snapshot.server_instance_id.clone()
{
stored.server_instance_id = Some(server_instance_id);
dirty = true;
}
if let Some(session_id) = snapshot.active_session_id.clone()
&& stored.sticky_session_id.as_deref() != Some(session_id.as_str())
{
stored.sticky_session_id = Some(session_id);
dirty = true;
}
if dirty {
let _ = database.update_profile(&stored);
}
}
Ok(snapshot)
}
#[tauri::command]
pub async fn disconnect_connection_slot(
runtime: State<'_, DualSlotRuntime>,
request: DisconnectConnectionSlotRequest,
) -> Result<(), RuntimeCommandError> {
runtime.deactivate_slot(request.slot).await
}
#[tauri::command]
pub async fn send_connection_slot_message(
database: State<'_, ApplicationDatabase>,
runtime: State<'_, DualSlotRuntime>,
request: SendConnectionSlotMessageRequest,
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
let status = runtime.status().await;
let snapshot = match request.slot {
SlotKind::Companion => status.companion,
SlotKind::Operations => status.operations,
};
if let (Some(profile_id), Some(server_instance_id), Some(session_id)) = (
snapshot.profile_id.as_deref(),
snapshot.server_instance_id.as_deref(),
snapshot.active_session_id.as_deref(),
) {
let slot = match request.slot {
SlotKind::Companion => "companion",
SlotKind::Operations => "operations",
};
let _ = database.upsert_chat_message(
"local-default",
profile_id,
slot,
server_instance_id,
None,
session_id,
&format!("local-{}", uuid::Uuid::new_v4()),
"user",
&request.message,
false,
false,
);
}
runtime
.send_slot_message(request.slot, request.message)
.await
}

查看文件

@ -34,6 +34,8 @@ pub struct BoundGatewayEvent {
pub event_id: String, pub event_id: String,
pub event_type: String, pub event_type: String,
pub server_instance_id: String, pub server_instance_id: String,
pub session_id: Option<String>,
pub message_id: Option<String>,
pub payload: Value, pub payload: Value,
} }
@ -53,6 +55,8 @@ pub enum GatewayError {
ServerIdentityChanged, ServerIdentityChanged,
#[error("gateway event channel closed")] #[error("gateway event channel closed")]
ChannelClosed, ChannelClosed,
#[error("gateway adapter error: {0}")]
Adapter(String),
} }
const MAX_DEDUPLICATED_EVENTS: usize = 4_096; const MAX_DEDUPLICATED_EVENTS: usize = 4_096;
@ -194,6 +198,8 @@ impl GatewayClient {
event_id: event_id.clone(), event_id: event_id.clone(),
event_type, event_type,
server_instance_id, server_instance_id,
session_id: bound.event.metadata.session_id.clone(),
message_id: bound.event.metadata.message_id.clone(),
payload, payload,
}) })
.await .await

查看文件

@ -1,5 +1,19 @@
mod astrbot_client;
pub mod commands;
mod gateway_client; mod gateway_client;
mod manager; mod manager;
mod runtime;
pub use astrbot_client::{AstrBotClient, AstrBotClientConfig, AstrBotClientError};
pub use commands::{
DisconnectConnectionSlotRequest, DrainConnectionRuntimeEventsRequest,
ProbeConnectionSlotRequest, SendConnectionSlotMessageRequest, connection_runtime_status,
disconnect_connection_slot, drain_connection_runtime_events, probe_connection_slot,
send_connection_slot_message,
};
pub use gateway_client::{BoundGatewayEvent, GatewayClient, GatewayClientConfig, GatewayError}; pub use gateway_client::{BoundGatewayEvent, GatewayClient, GatewayClientConfig, GatewayError};
pub use manager::{DualConnectionManager, SlotKind}; pub use manager::{DualConnectionManager, SlotKind};
pub use runtime::{
ConnectionRuntimeStatus, DualSlotRuntime, RuntimeCommandError, SlotActivationRequest,
SlotRuntimeSnapshot,
};

查看文件

@ -0,0 +1,410 @@
use desktop_protocol::{ConnectionState, TransportKind};
use secrecy::SecretString;
use serde::Serialize;
use tokio::sync::{Mutex, mpsc};
use super::{
AstrBotClient, AstrBotClientConfig, BoundGatewayEvent, GatewayClient, GatewayClientConfig,
GatewayError, SlotKind,
};
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SlotRuntimeSnapshot {
pub slot: SlotKind,
pub profile_id: Option<String>,
pub transport: Option<TransportKind>,
pub state: ConnectionState,
pub server_instance_id: Option<String>,
pub active_session_id: Option<String>,
pub last_error: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ConnectionRuntimeStatus {
pub companion: SlotRuntimeSnapshot,
pub operations: SlotRuntimeSnapshot,
}
#[derive(Debug, Clone)]
pub struct SlotActivationRequest {
pub profile_id: String,
pub slot: SlotKind,
pub base_url: String,
pub transport: TransportKind,
pub api_key: Option<SecretString>,
pub bearer_token: Option<SecretString>,
pub remote_username: Option<String>,
pub session_id: Option<String>,
pub expected_server_instance_id: Option<String>,
}
enum ActiveClient {
Desktop(GatewayClient),
AstrBot(AstrBotClient),
}
struct SlotRuntime {
snapshot: SlotRuntimeSnapshot,
client: Option<ActiveClient>,
}
impl SlotRuntime {
fn empty(slot: SlotKind) -> Self {
Self {
snapshot: SlotRuntimeSnapshot {
slot,
profile_id: None,
transport: None,
state: ConnectionState::Disconnected,
server_instance_id: None,
active_session_id: None,
last_error: None,
},
client: None,
}
}
}
/// In-process dual-slot connection runtime.
///
/// Network activation is explicit and Rust-owned. React never receives secrets.
pub struct DualSlotRuntime {
inner: Mutex<DualSlotRuntimeInner>,
event_tx: mpsc::Sender<BoundGatewayEvent>,
event_rx: Mutex<mpsc::Receiver<BoundGatewayEvent>>,
}
struct DualSlotRuntimeInner {
companion: SlotRuntime,
operations: SlotRuntime,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RuntimeCommandError {
pub code: &'static str,
pub message: &'static str,
}
impl std::fmt::Display for RuntimeCommandError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.message)
}
}
impl std::error::Error for RuntimeCommandError {}
impl RuntimeCommandError {
pub fn validation(message: &'static str) -> Self {
Self {
code: "validationFailed",
message,
}
}
pub fn unavailable(message: &'static str) -> Self {
Self {
code: "runtimeUnavailable",
message,
}
}
}
impl DualSlotRuntime {
pub fn new() -> Self {
let (event_tx, event_rx) = mpsc::channel(256);
Self {
inner: Mutex::new(DualSlotRuntimeInner {
companion: SlotRuntime::empty(SlotKind::Companion),
operations: SlotRuntime::empty(SlotKind::Operations),
}),
event_tx,
event_rx: Mutex::new(event_rx),
}
}
pub async fn status(&self) -> ConnectionRuntimeStatus {
let guard = self.inner.lock().await;
ConnectionRuntimeStatus {
companion: guard.companion.snapshot.clone(),
operations: guard.operations.snapshot.clone(),
}
}
pub async fn try_recv_event(&self) -> Option<BoundGatewayEvent> {
let mut rx = self.event_rx.lock().await;
rx.try_recv().ok()
}
pub async fn drain_events(&self, limit: usize) -> Vec<BoundGatewayEvent> {
let limit = limit.clamp(1, 256);
let mut rx = self.event_rx.lock().await;
let mut events = Vec::with_capacity(limit);
while events.len() < limit {
match rx.try_recv() {
Ok(event) => events.push(event),
Err(_) => break,
}
}
events
}
pub async fn deactivate_slot(&self, slot: SlotKind) -> Result<(), RuntimeCommandError> {
let mut guard = self.inner.lock().await;
let runtime = slot_mut(&mut guard, slot);
*runtime = SlotRuntime::empty(slot);
Ok(())
}
pub async fn activate_slot(
&self,
request: SlotActivationRequest,
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
if request.profile_id.trim().is_empty() {
return Err(RuntimeCommandError::validation(
"profile_id is required for activation.",
));
}
if request.base_url.trim().is_empty() {
return Err(RuntimeCommandError::validation(
"base_url is required for activation.",
));
}
let mut guard = self.inner.lock().await;
let runtime = slot_mut(&mut guard, request.slot);
*runtime = SlotRuntime {
snapshot: SlotRuntimeSnapshot {
slot: request.slot,
profile_id: Some(request.profile_id.clone()),
transport: Some(request.transport),
state: ConnectionState::Connecting,
server_instance_id: None,
active_session_id: request.session_id.clone(),
last_error: None,
},
client: None,
};
match request.transport {
TransportKind::DesktopV1 => {
let expected = request
.expected_server_instance_id
.clone()
.filter(|value| !value.trim().is_empty())
.ok_or_else(|| {
RuntimeCommandError::validation(
"Desktop gateway activation requires expected_server_instance_id.",
)
})?;
let client = GatewayClient::new(GatewayClientConfig {
profile_id: request.profile_id.clone(),
slot: request.slot,
base_url: request.base_url.clone(),
expected_server_instance_id: expected.clone(),
bearer_token: request.bearer_token.clone(),
})
.map_err(|_| {
RuntimeCommandError::unavailable("Desktop gateway client failed to start.")
})?;
match client.health().await {
Ok(_) => {
runtime.snapshot.state = ConnectionState::Connected;
runtime.snapshot.server_instance_id = Some(expected);
runtime.client = Some(ActiveClient::Desktop(client));
}
Err(GatewayError::HttpStatus(status)) if status.as_u16() == 401 => {
runtime.snapshot.state = ConnectionState::AuthExpired;
runtime.snapshot.last_error =
Some("Desktop gateway authentication failed.".into());
return Err(RuntimeCommandError::unavailable(
"Desktop gateway authentication failed.",
));
}
Err(_) => {
runtime.snapshot.state = ConnectionState::ServerUnavailable;
runtime.snapshot.last_error =
Some("Desktop gateway health check failed.".into());
return Err(RuntimeCommandError::unavailable(
"Desktop gateway health check failed.",
));
}
}
}
TransportKind::AstrBotOpenApi => {
let api_key = request.api_key.clone().ok_or_else(|| {
RuntimeCommandError::validation("AstrBot activation requires an API key.")
})?;
let remote_username = request
.remote_username
.clone()
.filter(|value| !value.trim().is_empty())
.ok_or_else(|| {
RuntimeCommandError::validation(
"AstrBot activation requires remote_username.",
)
})?;
let client = AstrBotClient::new(AstrBotClientConfig {
profile_id: request.profile_id.clone(),
slot: request.slot,
base_url: request.base_url.clone(),
api_key,
remote_username,
session_id: request.session_id.clone(),
expected_server_instance_id: request.expected_server_instance_id.clone(),
})
.map_err(|_| RuntimeCommandError::unavailable("AstrBot client failed to start."))?;
match client.probe().await {
Ok(_) => {
runtime.snapshot.state = ConnectionState::Connected;
runtime.snapshot.server_instance_id =
Some(client.server_instance_id_blocking());
runtime.client = Some(ActiveClient::AstrBot(client));
}
Err(error) => {
runtime.snapshot.state = match error {
super::AstrBotClientError::HttpStatus(status)
if status.as_u16() == 401 || status.as_u16() == 403 =>
{
ConnectionState::AuthExpired
}
_ => ConnectionState::ServerUnavailable,
};
runtime.snapshot.last_error = Some("AstrBot probe failed.".into());
return Err(RuntimeCommandError::unavailable("AstrBot probe failed."));
}
}
}
}
Ok(runtime.snapshot.clone())
}
pub async fn send_slot_message(
&self,
slot: SlotKind,
message: String,
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
if message.trim().is_empty() {
return Err(RuntimeCommandError::validation(
"message must not be empty.",
));
}
// Take the client out so we can await without holding the mutex across network IO.
let (client, profile_id, transport, server_instance_id, session_id) = {
let mut guard = self.inner.lock().await;
let runtime = slot_mut(&mut guard, slot);
let client = runtime.client.take().ok_or_else(|| {
RuntimeCommandError::unavailable("The selected slot is not connected.")
})?;
runtime.snapshot.state = ConnectionState::Syncing;
(
client,
runtime.snapshot.profile_id.clone(),
runtime.snapshot.transport,
runtime.snapshot.server_instance_id.clone(),
runtime.snapshot.active_session_id.clone(),
)
};
let send_result = match client {
ActiveClient::Desktop(client) => {
// Desktop mock path remains stream-oriented; chat POST is a later wire-up.
let restored = ActiveClient::Desktop(client);
Err((
restored,
RuntimeCommandError::unavailable(
"Desktop mock chat send is not activated in this runtime path yet.",
),
))
}
ActiveClient::AstrBot(client) => {
let cancel = tokio_util::sync::CancellationToken::new();
match client
.send_chat_stream(&message, &self.event_tx, &cancel)
.await
{
Ok(session) => Ok((ActiveClient::AstrBot(client), session)),
Err(_) => Err((
ActiveClient::AstrBot(client),
RuntimeCommandError::unavailable("AstrBot chat send failed."),
)),
}
}
};
let mut guard = self.inner.lock().await;
let runtime = slot_mut(&mut guard, slot);
match send_result {
Ok((client, session)) => {
runtime.client = Some(client);
runtime.snapshot.profile_id = profile_id;
runtime.snapshot.transport = transport;
runtime.snapshot.server_instance_id = server_instance_id;
runtime.snapshot.active_session_id = session.or(session_id);
runtime.snapshot.state = ConnectionState::Connected;
runtime.snapshot.last_error = None;
Ok(runtime.snapshot.clone())
}
Err((client, error)) => {
runtime.client = Some(client);
runtime.snapshot.profile_id = profile_id;
runtime.snapshot.transport = transport;
runtime.snapshot.server_instance_id = server_instance_id;
runtime.snapshot.active_session_id = session_id;
runtime.snapshot.state = ConnectionState::ServerUnavailable;
runtime.snapshot.last_error = Some(error.message.to_owned());
Err(error)
}
}
}
}
impl Default for DualSlotRuntime {
fn default() -> Self {
Self::new()
}
}
fn slot_mut(inner: &mut DualSlotRuntimeInner, slot: SlotKind) -> &mut SlotRuntime {
match slot {
SlotKind::Companion => &mut inner.companion,
SlotKind::Operations => &mut inner.operations,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn rejects_astrbot_activation_without_username_or_key() {
let runtime = DualSlotRuntime::new();
let error = runtime
.activate_slot(SlotActivationRequest {
profile_id: "11111111-1111-1111-1111-111111111111".into(),
slot: SlotKind::Companion,
base_url: "http://127.0.0.1:9".into(),
transport: TransportKind::AstrBotOpenApi,
api_key: None,
bearer_token: None,
remote_username: None,
session_id: None,
expected_server_instance_id: None,
})
.await
.expect_err("should fail");
assert_eq!(error.code, "validationFailed");
}
#[tokio::test]
async fn status_starts_disconnected() {
let runtime = DualSlotRuntime::new();
let status = runtime.status().await;
assert_eq!(status.companion.state, ConnectionState::Disconnected);
assert_eq!(status.operations.state, ConnectionState::Disconnected);
}
}

70
src-tauri/src/pet.rs 普通文件
查看文件

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

查看文件

@ -158,6 +158,7 @@ mod tests {
base_url: "https://example.test/".into(), base_url: "https://example.test/".into(),
event_stream_url: None, event_stream_url: None,
authentication_type: AuthenticationType::DeviceToken, authentication_type: AuthenticationType::DeviceToken,
transport_kind: desktop_protocol::TransportKind::DesktopV1,
credential_reference: None, credential_reference: None,
allow_insecure_http: false, allow_insecure_http: false,
pinned_certificate_fingerprint: None, pinned_certificate_fingerprint: None,
@ -168,6 +169,8 @@ mod tests {
protocol_version: None, protocol_version: None,
local_tool_policy_id: None, local_tool_policy_id: None,
last_connected_at: None, last_connected_at: None,
remote_username: None,
sticky_session_id: None,
created_at: "2026-07-19T00:00:00Z".into(), created_at: "2026-07-19T00:00:00Z".into(),
updated_at: "2026-07-19T00:00:00Z".into(), updated_at: "2026-07-19T00:00:00Z".into(),
} }

查看文件

@ -1,4 +1,6 @@
use desktop_protocol::{ActiveSlotKind, AstrBotProfileRole, AuthenticationType, ConnectionProfile}; use desktop_protocol::{
ActiveSlotKind, AstrBotProfileRole, AuthenticationType, ConnectionProfile, TransportKind,
};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use time::{OffsetDateTime, format_description::well_known::Rfc3339}; use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use url::Url; use url::Url;
@ -20,8 +22,12 @@ pub struct ConnectionProfileInput {
pub event_stream_url: Option<String>, pub event_stream_url: Option<String>,
pub authentication_type: AuthenticationType, pub authentication_type: AuthenticationType,
#[serde(default)] #[serde(default)]
pub transport_kind: TransportKind,
#[serde(default)]
pub allow_insecure_http: bool, pub allow_insecure_http: bool,
#[serde(default)] #[serde(default)]
pub remote_username: Option<String>,
#[serde(default)]
pub pinned_certificate_fingerprint: Option<String>, pub pinned_certificate_fingerprint: Option<String>,
#[serde(default)] #[serde(default)]
pub auto_connect: bool, pub auto_connect: bool,
@ -136,6 +142,7 @@ fn create_profile(
base_url: normalized.base_url, base_url: normalized.base_url,
event_stream_url: normalized.event_stream_url, event_stream_url: normalized.event_stream_url,
authentication_type: normalized.authentication_type, authentication_type: normalized.authentication_type,
transport_kind: normalized.transport_kind,
credential_reference: None, credential_reference: None,
allow_insecure_http: normalized.allow_insecure_http, allow_insecure_http: normalized.allow_insecure_http,
pinned_certificate_fingerprint: normalized.pinned_certificate_fingerprint, pinned_certificate_fingerprint: normalized.pinned_certificate_fingerprint,
@ -146,6 +153,8 @@ fn create_profile(
protocol_version: None, protocol_version: None,
local_tool_policy_id: None, local_tool_policy_id: None,
last_connected_at: None, last_connected_at: None,
remote_username: normalized.remote_username,
sticky_session_id: None,
created_at: now.clone(), created_at: now.clone(),
updated_at: now, updated_at: now,
}; };
@ -182,7 +191,9 @@ fn update_profile(
profile.base_url = normalized.base_url; profile.base_url = normalized.base_url;
profile.event_stream_url = normalized.event_stream_url; profile.event_stream_url = normalized.event_stream_url;
profile.authentication_type = normalized.authentication_type; profile.authentication_type = normalized.authentication_type;
profile.transport_kind = normalized.transport_kind;
profile.allow_insecure_http = normalized.allow_insecure_http; profile.allow_insecure_http = normalized.allow_insecure_http;
profile.remote_username = normalized.remote_username;
profile.pinned_certificate_fingerprint = normalized.pinned_certificate_fingerprint; profile.pinned_certificate_fingerprint = normalized.pinned_certificate_fingerprint;
profile.auto_connect = normalized.auto_connect; profile.auto_connect = normalized.auto_connect;
profile.auto_connect_slot = normalized.auto_connect_slot; profile.auto_connect_slot = normalized.auto_connect_slot;
@ -225,13 +236,29 @@ fn normalize_input(
let pinned_certificate_fingerprint = let pinned_certificate_fingerprint =
normalize_fingerprint(request.pinned_certificate_fingerprint)?; normalize_fingerprint(request.pinned_certificate_fingerprint)?;
let remote_username = request
.remote_username
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.map(str::to_owned);
if let Some(username) = &remote_username
&& (username.chars().count() > 80 || username.chars().any(char::is_control))
{
return Err(ProfileCommandError::validation(
"Remote username must contain 1 to 80 visible characters.",
));
}
Ok(ConnectionProfileInput { Ok(ConnectionProfileInput {
display_name, display_name,
role: request.role, role: request.role,
base_url, base_url,
event_stream_url, event_stream_url,
authentication_type: request.authentication_type, authentication_type: request.authentication_type,
transport_kind: request.transport_kind,
allow_insecure_http: request.allow_insecure_http, allow_insecure_http: request.allow_insecure_http,
remote_username,
pinned_certificate_fingerprint, pinned_certificate_fingerprint,
auto_connect: request.auto_connect, auto_connect: request.auto_connect,
auto_connect_slot: request.auto_connect_slot, auto_connect_slot: request.auto_connect_slot,
@ -326,7 +353,9 @@ mod tests {
base_url: base_url.into(), base_url: base_url.into(),
event_stream_url: None, event_stream_url: None,
authentication_type: AuthenticationType::DeviceToken, authentication_type: AuthenticationType::DeviceToken,
transport_kind: TransportKind::DesktopV1,
allow_insecure_http: false, allow_insecure_http: false,
remote_username: None,
pinned_certificate_fingerprint: None, pinned_certificate_fingerprint: None,
auto_connect: false, auto_connect: false,
auto_connect_slot: None, auto_connect_slot: None,
@ -354,7 +383,9 @@ mod tests {
base_url: "https://updated.example.test".into(), base_url: "https://updated.example.test".into(),
event_stream_url: Some("https://updated.example.test/events".into()), event_stream_url: Some("https://updated.example.test/events".into()),
authentication_type: AuthenticationType::ApiKey, authentication_type: AuthenticationType::ApiKey,
transport_kind: TransportKind::DesktopV1,
allow_insecure_http: false, allow_insecure_http: false,
remote_username: None,
pinned_certificate_fingerprint: None, pinned_certificate_fingerprint: None,
auto_connect: true, auto_connect: true,
auto_connect_slot: Some(ActiveSlotKind::Companion), auto_connect_slot: Some(ActiveSlotKind::Companion),

查看文件

@ -1,4 +1,11 @@
#[cfg(windows)] #[cfg(windows)]
pub use crate::windows::credential_manager::{ 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,
}; };

查看文件

@ -168,6 +168,7 @@ mod tests {
base_url: format!("https://example-{index}.test/"), base_url: format!("https://example-{index}.test/"),
event_stream_url: None, event_stream_url: None,
authentication_type: AuthenticationType::DeviceToken, authentication_type: AuthenticationType::DeviceToken,
transport_kind: desktop_protocol::TransportKind::DesktopV1,
credential_reference: None, credential_reference: None,
allow_insecure_http: false, allow_insecure_http: false,
pinned_certificate_fingerprint: None, pinned_certificate_fingerprint: None,
@ -178,6 +179,8 @@ mod tests {
protocol_version: None, protocol_version: None,
local_tool_policy_id: None, local_tool_policy_id: None,
last_connected_at: None, last_connected_at: None,
remote_username: None,
sticky_session_id: None,
created_at: "2026-07-19T00:00:00Z".into(), created_at: "2026-07-19T00:00:00Z".into(),
updated_at: "2026-07-19T00:00:00Z".into(), updated_at: "2026-07-19T00:00:00Z".into(),
} }

查看文件

@ -1,4 +1,4 @@
import { invoke } from "@tauri-apps/api/core"; import { invoke } from "@tauri-apps/api/core";
import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest"; import { beforeEach, describe, expect, it, vi } from "vitest";
@ -161,6 +161,7 @@ describe("App", () => {
const created: ConnectionProfile = { const created: ConnectionProfile = {
id: "2bdedc10-d804-4da5-8e92-39dd7f175d7a", id: "2bdedc10-d804-4da5-8e92-39dd7f175d7a",
...request, ...request,
transportKind: "desktop-v1",
createdAt: "2026-07-18T02:00:00Z", createdAt: "2026-07-18T02:00:00Z",
updatedAt: "2026-07-18T02:00:00Z", updatedAt: "2026-07-18T02:00:00Z",
}; };
@ -256,6 +257,7 @@ describe("App", () => {
role: "companion", role: "companion",
baseUrl: "https://companion.example.test/", baseUrl: "https://companion.example.test/",
authenticationType: "device-token", authenticationType: "device-token",
transportKind: "desktop-v1",
allowInsecureHttp: false, allowInsecureHttp: false,
autoConnect: false, autoConnect: false,
createdAt: "2026-07-19T02:00:00Z", createdAt: "2026-07-19T02:00:00Z",
@ -267,6 +269,7 @@ describe("App", () => {
role: "operations", role: "operations",
baseUrl: "https://operations.example.test/", baseUrl: "https://operations.example.test/",
authenticationType: "api-key", authenticationType: "api-key",
transportKind: "desktop-v1",
allowInsecureHttp: false, allowInsecureHttp: false,
autoConnect: false, autoConnect: false,
createdAt: "2026-07-19T02:00:00Z", createdAt: "2026-07-19T02:00:00Z",
@ -319,6 +322,7 @@ describe("App", () => {
const created: ConnectionProfile = { const created: ConnectionProfile = {
id: "2bdedc10-d804-4da5-8e92-39dd7f175d7a", id: "2bdedc10-d804-4da5-8e92-39dd7f175d7a",
...request, ...request,
transportKind: "desktop-v1",
createdAt: "2026-07-19T03:00:00Z", createdAt: "2026-07-19T03:00:00Z",
updatedAt: "2026-07-19T03:00:00Z", updatedAt: "2026-07-19T03:00:00Z",
}; };
@ -358,6 +362,7 @@ describe("App", () => {
role: "companion", role: "companion",
baseUrl: "https://companion.example.test", baseUrl: "https://companion.example.test",
authenticationType: "device-token", authenticationType: "device-token",
transportKind: "desktop-v1",
allowInsecureHttp: false, allowInsecureHttp: false,
autoConnect: true, autoConnect: true,
autoConnectSlot: "companion", autoConnectSlot: "companion",
@ -373,6 +378,7 @@ describe("App", () => {
role: "companion", role: "companion",
baseUrl: "https://companion.example.test/", baseUrl: "https://companion.example.test/",
authenticationType: "device-token", authenticationType: "device-token",
transportKind: "desktop-v1",
allowInsecureHttp: false, allowInsecureHttp: false,
autoConnect: false, autoConnect: false,
serverInstanceId: "server-shared", serverInstanceId: "server-shared",
@ -385,6 +391,7 @@ describe("App", () => {
role: "operations", role: "operations",
baseUrl: "https://operations.example.test/", baseUrl: "https://operations.example.test/",
authenticationType: "api-key", authenticationType: "api-key",
transportKind: "desktop-v1",
allowInsecureHttp: false, allowInsecureHttp: false,
autoConnect: false, autoConnect: false,
serverInstanceId: "server-shared", serverInstanceId: "server-shared",

查看文件

@ -1,6 +1,8 @@
import { invoke } from "@tauri-apps/api/core"; import { invoke } from "@tauri-apps/api/core";
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import { ChatPanel } from "./features/chat/ChatPanel";
import { StatusBubble } from "./features/chat/StatusBubble";
import { ProfileManager } from "./features/profiles/ProfileManager"; import { ProfileManager } from "./features/profiles/ProfileManager";
import { bootstrapStatusSchema, type BootstrapStatus } from "./types/bootstrap"; import { bootstrapStatusSchema, type BootstrapStatus } from "./types/bootstrap";
@ -9,10 +11,13 @@ const initialStatus: BootstrapStatus = {
platform: "unknown", platform: "unknown",
rustCore: "pending", rustCore: "pending",
protocolVersion: "desktop-v1alpha1", protocolVersion: "desktop-v1alpha1",
databaseSchemaVersion: 3, databaseSchemaVersion: 4,
}; };
export function App() { export function App() {
const view = new URLSearchParams(window.location.search).get("view");
const isQuickView = view === "quick";
const isBubbleView = view === "bubble";
const [status, setStatus] = useState(initialStatus); const [status, setStatus] = useState(initialStatus);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
@ -30,13 +35,22 @@ export function App() {
void refreshStatus(); void refreshStatus();
}, [refreshStatus]); }, [refreshStatus]);
if (isBubbleView) return <StatusBubble />;
if (isQuickView)
return (
<main className="quick-app-shell">
<ChatPanel />
</main>
);
return ( return (
<main className="app-shell"> <main className="app-shell">
<header className="hero"> <header className="hero">
<p className="eyebrow">P02 · dual connections</p> <p className="eyebrow">P02 路 dual connections</p>
<h1>AstrBot Desktop</h1> <h1>AstrBot Desktop</h1>
<p className="subtitle"> <p className="subtitle">
双实例陪伴与本机助手的安全 Windows 客户端工程底座。 鍙屽疄渚嬮櫔浼翠笌鏈満鍔╂墜鐨勫畨鍏?Windows
瀹㈡埛绔伐绋嬪簳搴с€?{" "}
</p> </p>
</header> </header>
@ -54,7 +68,7 @@ export function App() {
{error ? <p className="error-banner">IPC unavailable: {error}</p> : null} {error ? <p className="error-banner">IPC unavailable: {error}</p> : null}
<section className="boundaries"> <section className="boundaries">
<h2>安全边界</h2> <h2>瀹夊叏杈圭晫</h2>
<ul> <ul>
<li>凭据只在 Rust 与 Windows 安全存储之间流动。</li> <li>凭据只在 Rust 与 Windows 安全存储之间流动。</li>
<li>两个 REST/SSE 槽位保持独立状态与事件来源。</li> <li>两个 REST/SSE 槽位保持独立状态与事件来源。</li>
@ -62,10 +76,19 @@ export function App() {
<li>文件事务默认保留源文件,且不会静默覆盖。</li> <li>文件事务默认保留源文件,且不会静默覆盖。</li>
</ul> </ul>
</section> </section>
<div className="chat-actions">
<button
type="button"
onClick={() => void invoke("open_quick_chat_window")}
>
打开快速聊天
</button>
</div>
<ChatPanel />
<ProfileManager /> <ProfileManager />
<button type="button" onClick={() => void refreshStatus()}> <button type="button" onClick={() => void refreshStatus()}>
重新检查 IPC 閲嶆柊妫€鏌?IPC
</button> </button>
</main> </main>
); );

查看文件

@ -0,0 +1,283 @@
import { invoke } from "@tauri-apps/api/core";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
boundRuntimeEventSchema,
connectionRuntimeStatusSchema,
type BoundRuntimeEvent,
type ChatMessage,
type ChatSlot,
type ConnectionRuntimeStatus,
storedChatMessageSchema,
} from "./types";
const emptyStatus: ConnectionRuntimeStatus = {
companion: { slot: "companion", state: "disconnected" },
operations: { slot: "operations", state: "disconnected" },
};
function payloadString(
event: BoundRuntimeEvent,
key: string,
): string | undefined {
if (!event.payload || typeof event.payload !== "object") return undefined;
const value = (event.payload as Record<string, unknown>)[key];
return typeof value === "string" ? value : undefined;
}
export function ChatPanel() {
const [status, setStatus] = useState(emptyStatus);
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [activeSlot, setActiveSlot] = useState<ChatSlot>("companion");
const [draft, setDraft] = useState("");
const [error, setError] = useState<string | null>(null);
const activeMessages = useMemo(
() => messages.filter((item) => item.slot === activeSlot),
[messages, activeSlot],
);
const refresh = useCallback(async () => {
try {
const result = await invoke<unknown>("connection_runtime_status");
setStatus(connectionRuntimeStatusSchema.parse(result));
setError(null);
return true;
} catch (reason) {
setError(reason instanceof Error ? reason.message : String(reason));
return false;
}
}, []);
const drainEvents = useCallback(async () => {
try {
const result = await invoke<unknown>("drain_connection_runtime_events", {
request: { limit: 64 },
});
const events = boundRuntimeEventSchema.array().parse(result);
if (events.length > 0)
setMessages((current) => applyRuntimeEvents(current, events));
} catch {
// Browser fallback keeps the shell usable without Rust IPC.
}
}, []);
useEffect(() => {
const snapshot = status[activeSlot];
if (
!snapshot.profileId ||
!snapshot.serverInstanceId ||
!snapshot.activeSessionId
)
return;
let cancelled = false;
void invoke<unknown>("load_chat_messages", {
request: {
profileId: snapshot.profileId,
serverInstanceId: snapshot.serverInstanceId,
sessionId: snapshot.activeSessionId,
limit: 100,
},
})
.then((result) => {
if (cancelled) return;
const records = storedChatMessageSchema.array().parse(result);
setMessages((current) => {
const otherSlots = current.filter((item) => item.slot !== activeSlot);
const restored = records.map((record) => ({
id: record.messageId,
slot: record.slot,
role: record.role,
content: record.content,
streaming: record.streaming,
error: record.error,
}));
return otherSlots.concat(restored);
});
})
.catch(() => undefined);
return () => {
cancelled = true;
};
}, [activeSlot, status]);
useEffect(() => {
let timer: number | undefined;
void refresh().then((available) => {
if (!available) return;
timer = window.setInterval(() => {
void refresh();
void drainEvents();
}, 500);
});
return () => {
if (timer !== undefined) window.clearInterval(timer);
};
}, [drainEvents, refresh]);
const send = async () => {
const message = draft.trim();
if (!message) return;
const id = "local-" + Date.now();
setDraft("");
setMessages((current) =>
current.concat({ id, slot: activeSlot, role: "user", content: message }),
);
try {
await invoke("send_connection_slot_message", {
request: { slot: activeSlot, message },
});
setError(null);
} catch (reason) {
setError(reason instanceof Error ? reason.message : String(reason));
setMessages((current) =>
current.map((item) =>
item.id === id ? { ...item, error: true } : item,
),
);
}
};
return (
<section className="chat-panel" aria-label="聊天面板">
<div className="chat-heading">
<div>
<p className="eyebrow">Q1 shared chat runtime</p>
<h2>统一聊天运行时</h2>
<p className="chat-note">
主页面、快速聊天和气泡共享同一套消息状态。
</p>
</div>
<div className="chat-slot-tabs" role="tablist" aria-label="聊天槽位">
{(["companion", "operations"] as const).map((slot) => (
<button
className={activeSlot === slot ? "chat-slot active" : "chat-slot"}
key={slot}
onClick={() => setActiveSlot(slot)}
role="tab"
aria-selected={activeSlot === slot}
type="button"
>
{slot === "companion" ? "陪伴" : "运维"}
<span>{status[slot].state}</span>
</button>
))}
</div>
</div>
<div className="chat-runtime-strip">
<span>Profile:{status[activeSlot].profileId ?? "未连接"}</span>
<span>Session:{status[activeSlot].activeSessionId ?? "未建立"}</span>
<span>状态:{status[activeSlot].state}</span>
</div>
<div className="chat-message-list" aria-live="polite">
{activeMessages.length === 0 ? (
<p className="chat-empty">
当前槽位还没有消息。连接 Profile 后即可开始聊天。
</p>
) : (
activeMessages.map((message) => (
<article
className={
"chat-message " +
message.role +
(message.error ? " failed" : "")
}
key={message.id}
>
<span className="chat-message-role">
{message.role === "user"
? "我"
: message.role === "assistant"
? "AstrBot"
: "系统"}
</span>
<p>{message.content || "…"}</p>
{message.streaming ? <small>生成中</small> : null}
</article>
))
)}
</div>
{error ? <p className="chat-error">{error}</p> : null}
<form
className="chat-composer"
onSubmit={(event) => {
event.preventDefault();
void send();
}}
>
<textarea
aria-label="聊天消息"
onChange={(event) => setDraft(event.target.value)}
placeholder={
activeSlot === "companion"
? "和陪伴实例说点什么…"
: "向运维实例描述问题…"
}
value={draft}
rows={3}
/>
<button disabled={!draft.trim()} type="submit">
发送
</button>
</form>
</section>
);
}
function applyRuntimeEvents(
current: ChatMessage[],
events: BoundRuntimeEvent[],
): ChatMessage[] {
const next = current.map((item) => ({ ...item }));
for (const event of events) {
if (event.eventType === "message.delta") {
const id =
event.messageId || payloadString(event, "messageId") || event.eventId;
const delta =
payloadString(event, "delta") || payloadString(event, "content") || "";
const existing = next.find(
(item) => item.id === id && item.slot === event.slot,
);
if (existing) {
existing.content += delta;
existing.streaming = true;
} else
next.push({
id,
slot: event.slot,
role: "assistant",
content: delta,
streaming: true,
});
} else if (event.eventType === "message.completed") {
const id =
event.messageId || payloadString(event, "messageId") || event.eventId;
const existing = next.find(
(item) => item.id === id && item.slot === event.slot,
);
if (existing) existing.streaming = false;
else
next.push({
id,
slot: event.slot,
role: "assistant",
content: payloadString(event, "content") || "",
});
} else if (event.eventType === "error") {
next.push({
id: event.eventId,
slot: event.slot,
role: "system",
content: payloadString(event, "message") || "连接错误",
error: true,
});
} else if (event.eventType === "message.proactive") {
next.push({
id: event.eventId,
slot: event.slot,
role: "assistant",
content: payloadString(event, "content") || "",
});
}
}
return next;
}

查看文件

@ -0,0 +1,40 @@
import { invoke } from "@tauri-apps/api/core";
import { useEffect, useState } from "react";
import {
connectionRuntimeStatusSchema,
type ConnectionRuntimeStatus,
} from "./types";
const initialStatus: ConnectionRuntimeStatus = {
companion: { slot: "companion", state: "disconnected" },
operations: { slot: "operations", state: "disconnected" },
};
export function StatusBubble() {
const [status, setStatus] = useState(initialStatus);
useEffect(() => {
const refresh = () =>
invoke<unknown>("connection_runtime_status")
.then((value) => setStatus(connectionRuntimeStatusSchema.parse(value)))
.catch(() => undefined);
refresh();
const timer = window.setInterval(refresh, 1000);
return () => window.clearInterval(timer);
}, []);
const companion = status.companion.state;
const operations = status.operations.state;
const active = companion === "connected" || operations === "connected";
return (
<main className="status-bubble-shell" aria-label="连接状态气泡">
<button
className={active ? "status-bubble connected" : "status-bubble"}
type="button"
onClick={() => void invoke("open_quick_chat_window")}
>
<span className="status-bubble-orb" />
<span className="status-bubble-label">{active ? "在线" : "离线"}</span>
</button>
</main>
);
}

72
src/features/chat/types.ts 普通文件
查看文件

@ -0,0 +1,72 @@
import { z } from "zod";
import {
activeSlotKindSchema,
connectionStateSchema,
type ActiveSlotKind,
} from "../../types/connection";
export const slotRuntimeSnapshotSchema = z
.object({
slot: activeSlotKindSchema,
profileId: z.uuid().optional(),
transport: z.enum(["desktop-v1", "astrbot-openapi"]).optional(),
state: connectionStateSchema,
serverInstanceId: z.string().min(1).optional(),
activeSessionId: z.string().min(1).optional(),
lastError: z.string().optional(),
})
.strict();
export const connectionRuntimeStatusSchema = z
.object({
companion: slotRuntimeSnapshotSchema,
operations: slotRuntimeSnapshotSchema,
})
.strict();
export const boundRuntimeEventSchema = z
.object({
profileId: z.string().min(1),
slot: activeSlotKindSchema,
eventId: z.string().min(1),
eventType: z.string().min(1),
serverInstanceId: z.string().min(1),
sessionId: z.string().min(1).optional(),
messageId: z.string().min(1).optional(),
payload: z.unknown(),
})
.strict();
export type SlotRuntimeSnapshot = z.infer<typeof slotRuntimeSnapshotSchema>;
export type ConnectionRuntimeStatus = z.infer<
typeof connectionRuntimeStatusSchema
>;
export type BoundRuntimeEvent = z.infer<typeof boundRuntimeEventSchema>;
export type ChatSlot = ActiveSlotKind;
export interface ChatMessage {
id: string;
slot: ChatSlot;
role: "user" | "assistant" | "system";
content: string;
streaming?: boolean;
error?: boolean;
}
export const storedChatMessageSchema = z
.object({
accountId: z.string().min(1),
profileId: z.string().min(1),
slot: activeSlotKindSchema,
serverInstanceId: z.string().min(1),
remoteUsername: z.string().min(1).optional(),
sessionId: z.string().min(1),
messageId: z.string().min(1),
role: z.enum(["user", "assistant", "system"]),
content: z.string(),
streaming: z.boolean(),
error: z.boolean(),
updatedAt: z.string().min(1),
})
.strict();

56
src/features/pet/types.ts 普通文件
查看文件

@ -0,0 +1,56 @@
import { z } from "zod";
export const companionStateSchema = z.enum([
"idle",
"thinking",
"speaking",
"error",
"notification",
"offline",
]);
export const petDisplayModeSchema = z.enum(["app-ui", "desktop-floating"]);
export const petPositionModeSchema = z.enum([
"free",
"edge",
"指定屏幕",
"follow-main-window",
]);
export const bubbleClickTargetSchema = z.enum(["main", "quick"]);
export const petAnimationSchema = z
.object({
state: companionStateSchema,
frames: z.array(z.number().int().nonnegative()).min(1),
fps: z.number().positive().max(60),
})
.strict();
export const petPackManifestSchema = z
.object({
format: z.literal("astrbot-pet-pack.v1"),
name: z.string().min(1).max(80),
version: z.string().min(1).max(32),
image: z.string().regex(/^[^\\/:*?"<>|]+\\.(png|webp)$/i),
width: z.number().int().positive().max(4096),
height: z.number().int().positive().max(4096),
animations: z.array(petAnimationSchema).min(1),
})
.strict();
export const companionPresentationSettingsSchema = z
.object({
enabled: z.boolean(),
displayMode: petDisplayModeSchema,
positionMode: petPositionModeSchema,
bubbleClickTarget: bubbleClickTargetSchema,
alwaysOnTop: z.boolean(),
gameMode: z.boolean(),
})
.strict();
export type CompanionState = z.infer<typeof companionStateSchema>;
export type PetPackManifest = z.infer<typeof petPackManifestSchema>;
export type CompanionPresentationSettings = z.infer<
typeof companionPresentationSettingsSchema
>;

查看文件

@ -0,0 +1,109 @@
import { useState } from "react";
import { invoke } from "@tauri-apps/api/core";
import type { AuthenticationType, ConnectionProfile } from "../../types/profile";
interface CredentialEnrollmentResult {
profileId: string;
credentialReference: string;
authenticationType: AuthenticationType;
}
interface Props {
profile: ConnectionProfile;
onChanged: () => Promise<void> | void;
}
export function CredentialEnrollmentCard({ profile, onChanged }: Props) {
const [secret, setSecret] = useState("");
const [username, setUsername] = useState(profile.remoteUsername ?? "");
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState<string | null>(null);
async function enroll() {
setBusy(true);
setMessage(null);
try {
const result = await invoke<CredentialEnrollmentResult>(
"enroll_profile_credential",
{
request: {
profileId: profile.id,
authenticationType: profile.authenticationType,
secret,
username: username.trim() || undefined,
},
},
);
setSecret("");
setMessage(`已登记凭据引用 ${result.credentialReference}`);
await onChanged();
} catch (error) {
setMessage(
error instanceof Error ? error.message : "凭据登记失败(详情未包含密钥)。",
);
} finally {
setBusy(false);
}
}
async function clearCredential() {
setBusy(true);
setMessage(null);
try {
await invoke("clear_profile_credential", { profileId: profile.id });
setMessage("已清除凭据引用");
await onChanged();
} catch (error) {
setMessage(
error instanceof Error ? error.message : "清除凭据失败。",
);
} finally {
setBusy(false);
}
}
return (
<section className="credential-card" aria-label={`凭据登记 ${profile.displayName}`}>
<h4>安全凭据登记</h4>
<p>
密钥只通过一次性 IPC 写入 Windows Credential Manager,不会进入 React 持久状态。
</p>
<label>
用户名(可选,AstrBot 可用)
<input
value={username}
onChange={(event) => setUsername(event.target.value)}
disabled={busy}
/>
</label>
<label>
API Key / Token(一次性)
<input
type="password"
value={secret}
onChange={(event) => setSecret(event.target.value)}
disabled={busy}
autoComplete="off"
/>
</label>
<div className="button-row">
<button type="button" disabled={busy || !secret.trim()} onClick={() => void enroll()}>
登记凭据
</button>
<button
type="button"
disabled={busy || !profile.credentialReference}
onClick={() => void clearCredential()}
>
清除凭据
</button>
</div>
{profile.credentialReference ? (
<p>当前引用:{profile.credentialReference}</p>
) : (
<p>尚未登记凭据</p>
)}
{message ? <p role="status">{message}</p> : null}
</section>
);
}

查看文件

@ -17,8 +17,10 @@ import {
type ConnectionProfile, type ConnectionProfile,
type ConnectionProfileInput, type ConnectionProfileInput,
type ProfileRole, type ProfileRole,
type TransportKind,
type UpdateConnectionProfileRequest, type UpdateConnectionProfileRequest,
} from "../../types/profile"; } from "../../types/profile";
import { CredentialEnrollmentCard } from "./CredentialEnrollmentCard";
interface ProfileFormState { interface ProfileFormState {
displayName: string; displayName: string;
@ -26,6 +28,8 @@ interface ProfileFormState {
baseUrl: string; baseUrl: string;
eventStreamUrl: string; eventStreamUrl: string;
authenticationType: AuthenticationType; authenticationType: AuthenticationType;
transportKind: TransportKind;
remoteUsername: string;
allowInsecureHttp: boolean; allowInsecureHttp: boolean;
pinnedCertificateFingerprint: string; pinnedCertificateFingerprint: string;
autoConnect: boolean; autoConnect: boolean;
@ -38,6 +42,8 @@ const emptyForm: ProfileFormState = {
baseUrl: "https://", baseUrl: "https://",
eventStreamUrl: "", eventStreamUrl: "",
authenticationType: "device-token", authenticationType: "device-token",
transportKind: "desktop-v1",
remoteUsername: "",
allowInsecureHttp: false, allowInsecureHttp: false,
pinnedCertificateFingerprint: "", pinnedCertificateFingerprint: "",
autoConnect: false, autoConnect: false,
@ -127,6 +133,8 @@ export function ProfileManager() {
baseUrl: profile.baseUrl, baseUrl: profile.baseUrl,
eventStreamUrl: profile.eventStreamUrl ?? "", eventStreamUrl: profile.eventStreamUrl ?? "",
authenticationType: profile.authenticationType, authenticationType: profile.authenticationType,
transportKind: profile.transportKind ?? "desktop-v1",
remoteUsername: profile.remoteUsername ?? "",
allowInsecureHttp: profile.allowInsecureHttp, allowInsecureHttp: profile.allowInsecureHttp,
pinnedCertificateFingerprint: profile.pinnedCertificateFingerprint ?? "", pinnedCertificateFingerprint: profile.pinnedCertificateFingerprint ?? "",
autoConnect: profile.autoConnect, autoConnect: profile.autoConnect,
@ -417,7 +425,38 @@ export function ProfileManager() {
<span>明确允许不安全 HTTP(仅限受信任网络)</span> <span>明确允许不安全 HTTP(仅限受信任网络)</span>
</label> </label>
<label className="checkbox-field">
<label>
传输协议
<select
value={form.transportKind}
onChange={(event) =>
setForm((current) => ({
...current,
transportKind: event.target.value as TransportKind,
}))
}
>
<option value="desktop-v1">Desktop Mock/Gateway</option>
<option value="astrbot-openapi">AstrBot OpenAPI</option>
</select>
</label>
{form.transportKind === "astrbot-openapi" ? (
<label>
AstrBot 用户名
<input
value={form.remoteUsername}
onChange={(event) =>
setForm((current) => ({
...current,
remoteUsername: event.target.value,
}))
}
placeholder="desktop-companion"
/>
</label>
) : null}
<label className="checkbox-field">
<input <input
name="autoConnect" name="autoConnect"
type="checkbox" type="checkbox"
@ -524,7 +563,12 @@ export function ProfileManager() {
删除 删除
</button> </button>
</div> </div>
</article>
<CredentialEnrollmentCard
profile={profile}
onChanged={loadProfiles}
/>
</article>
)) ))
)} )}
</div> </div>
@ -553,6 +597,8 @@ function toProfileInput(form: ProfileFormState): ConnectionProfileInput {
baseUrl: form.baseUrl.trim(), baseUrl: form.baseUrl.trim(),
eventStreamUrl: eventStreamUrl || undefined, eventStreamUrl: eventStreamUrl || undefined,
authenticationType: form.authenticationType, authenticationType: form.authenticationType,
transportKind: form.transportKind,
remoteUsername: form.remoteUsername.trim() || undefined,
allowInsecureHttp: form.allowInsecureHttp, allowInsecureHttp: form.allowInsecureHttp,
pinnedCertificateFingerprint: fingerprint || undefined, pinnedCertificateFingerprint: fingerprint || undefined,
autoConnect: form.autoConnect, autoConnect: form.autoConnect,

查看文件

@ -418,3 +418,225 @@ select:focus {
padding: 2rem 0; padding: 2rem 0;
} }
} }
.chat-panel {
display: grid;
gap: 1rem;
margin: 2rem 0;
padding: 1.5rem;
border: 1px solid rgb(137 175 232 / 28%);
border-radius: 1rem;
background: rgb(13 29 52 / 82%);
box-shadow: 0 1rem 3rem rgb(0 0 0 / 18%);
}
.chat-heading {
display: flex;
justify-content: space-between;
gap: 1.5rem;
align-items: start;
}
.chat-heading h2 {
margin: 0.3rem 0;
}
.chat-note,
.chat-empty,
.chat-error {
color: #aebfda;
}
.chat-note {
margin: 0;
}
.chat-slot-tabs {
display: flex;
flex-wrap: wrap;
gap: 0.55rem;
}
.chat-slot {
display: grid;
gap: 0.25rem;
min-width: 7rem;
border-color: rgb(157 181 218 / 48%);
background: #20314b;
}
.chat-slot.active {
border-color: #7db0ff;
background: #24508c;
}
.chat-slot span {
color: #bcd0ef;
font-size: 0.75rem;
}
.chat-runtime-strip {
display: flex;
flex-wrap: wrap;
gap: 0.75rem 1.25rem;
padding: 0.8rem 1rem;
border: 1px solid rgb(137 175 232 / 22%);
border-radius: 0.7rem;
color: #b9c8e4;
background: rgb(7 18 34 / 55%);
font-size: 0.85rem;
}
.chat-message-list {
display: grid;
gap: 0.75rem;
min-height: 15rem;
max-height: 28rem;
padding: 0.75rem;
overflow: auto;
border: 1px solid rgb(137 175 232 / 22%);
border-radius: 0.8rem;
background: rgb(7 18 34 / 42%);
}
.chat-empty {
align-self: center;
margin: auto;
text-align: center;
}
.chat-message {
max-width: 82%;
padding: 0.8rem 1rem;
border: 1px solid rgb(137 175 232 / 22%);
border-radius: 0.85rem;
background: rgb(22 47 80 / 80%);
}
.chat-message.user {
justify-self: end;
background: rgb(34 77 130 / 82%);
}
.chat-message.failed,
.chat-error {
border-color: rgb(255 122 122 / 55%);
}
.chat-message-role {
color: #8db9ff;
font-size: 0.78rem;
font-weight: 700;
}
.chat-message p {
margin: 0.35rem 0 0;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.chat-message small {
display: block;
margin-top: 0.4rem;
color: #aebfda;
}
.chat-error {
margin: 0;
padding: 0.75rem 0.9rem;
border: 1px solid rgb(255 122 122 / 55%);
border-radius: 0.7rem;
background: rgb(90 36 48 / 45%);
}
.chat-composer {
display: grid;
grid-template-columns: 1fr auto;
gap: 0.75rem;
align-items: end;
}
.chat-composer textarea {
width: 100%;
min-height: 5rem;
padding: 0.8rem;
resize: vertical;
border: 1px solid rgb(137 175 232 / 38%);
border-radius: 0.65rem;
color: inherit;
background: #0b1b31;
font: inherit;
}
@media (max-width: 760px) {
.chat-heading,
.chat-composer {
grid-template-columns: 1fr;
display: grid;
}
.chat-message {
max-width: 95%;
}
}
.chat-actions {
display: flex;
justify-content: flex-end;
margin: 1rem 0;
}
.quick-app-shell {
min-width: 320px;
min-height: 100vh;
padding: 1rem;
background: #08111f;
}
.quick-app-shell .chat-panel {
margin: 0;
min-height: calc(100vh - 2rem);
}
.status-bubble-shell {
display: grid;
width: 100vw;
height: 100vh;
place-items: center;
background: transparent;
}
.status-bubble {
display: grid;
width: 86px;
height: 86px;
place-items: center;
gap: 0.2rem;
padding: 0.7rem;
border: 1px solid rgb(157 181 218 / 55%);
border-radius: 50%;
background: rgb(17 38 67 / 94%);
box-shadow: 0 0.8rem 2rem rgb(0 0 0 / 35%);
}
.status-bubble.connected {
border-color: rgb(96 211 153 / 70%);
}
.status-bubble-orb {
width: 1.2rem;
height: 1.2rem;
border-radius: 50%;
background: #ffbd67;
box-shadow: 0 0 1rem rgb(255 189 103 / 65%);
}
.status-bubble.connected .status-bubble-orb {
background: #60d399;
box-shadow: 0 0 1rem rgb(96 211 153 / 65%);
}
.status-bubble-label {
color: #eef3ff;
font-size: 0.72rem;
}

查看文件

@ -4,6 +4,8 @@ export const profileRoleSchema = z.enum(["companion", "operations", "general"]);
export const authenticationTypeSchema = z.enum(["device-token", "api-key"]); export const authenticationTypeSchema = z.enum(["device-token", "api-key"]);
export const transportKindSchema = z.enum(["desktop-v1", "astrbot-openapi"]);
export const activeSlotKindSchema = z.enum(["companion", "operations"]); export const activeSlotKindSchema = z.enum(["companion", "operations"]);
const optionalIdentifier = z.string().min(1).optional(); const optionalIdentifier = z.string().min(1).optional();
@ -16,6 +18,7 @@ export const connectionProfileSchema = z
baseUrl: z.url(), baseUrl: z.url(),
eventStreamUrl: z.url().optional(), eventStreamUrl: z.url().optional(),
authenticationType: authenticationTypeSchema, authenticationType: authenticationTypeSchema,
transportKind: transportKindSchema.default("desktop-v1"),
credentialReference: optionalIdentifier, credentialReference: optionalIdentifier,
allowInsecureHttp: z.boolean(), allowInsecureHttp: z.boolean(),
pinnedCertificateFingerprint: z pinnedCertificateFingerprint: z
@ -29,6 +32,8 @@ export const connectionProfileSchema = z
protocolVersion: optionalIdentifier, protocolVersion: optionalIdentifier,
localToolPolicyId: optionalIdentifier, localToolPolicyId: optionalIdentifier,
lastConnectedAt: optionalIdentifier, lastConnectedAt: optionalIdentifier,
remoteUsername: optionalIdentifier,
stickySessionId: optionalIdentifier,
createdAt: z.string().min(1), createdAt: z.string().min(1),
updatedAt: z.string().min(1), updatedAt: z.string().min(1),
}) })
@ -38,6 +43,7 @@ export const connectionProfileListSchema = z.array(connectionProfileSchema);
export type ProfileRole = z.infer<typeof profileRoleSchema>; export type ProfileRole = z.infer<typeof profileRoleSchema>;
export type AuthenticationType = z.infer<typeof authenticationTypeSchema>; export type AuthenticationType = z.infer<typeof authenticationTypeSchema>;
export type TransportKind = z.infer<typeof transportKindSchema>;
export type ConnectionProfile = z.infer<typeof connectionProfileSchema>; export type ConnectionProfile = z.infer<typeof connectionProfileSchema>;
export type ActiveSlotKind = z.infer<typeof activeSlotKindSchema>; export type ActiveSlotKind = z.infer<typeof activeSlotKindSchema>;
@ -47,7 +53,9 @@ export interface ConnectionProfileInput {
baseUrl: string; baseUrl: string;
eventStreamUrl?: string; eventStreamUrl?: string;
authenticationType: AuthenticationType; authenticationType: AuthenticationType;
transportKind?: TransportKind;
allowInsecureHttp: boolean; allowInsecureHttp: boolean;
remoteUsername?: string;
pinnedCertificateFingerprint?: string; pinnedCertificateFingerprint?: string;
autoConnect: boolean; autoConnect: boolean;
autoConnectSlot?: ActiveSlotKind; autoConnectSlot?: ActiveSlotKind;