比较提交

..

2 提交

作者 SHA1 备注 提交日期
d100da324d fix(chat): prevent duplicate history on session switch
一些检测仍在等待运行
ci / Portable quality checks (push) Waiting to run
ci / Windows Tauri build (push) Waiting to run
2026-07-22 02:52:31 +08:00
02dfb618b9 refactor(ui): complete desktop frontend redesign 2026-07-22 00:27:06 +08:00
共有 23 个文件被更改,包括 2786 次插入 和 666 次删除

查看文件

@ -213,6 +213,11 @@ pub fn parse_astrbot_sse_line(line: &str) -> Result<AstrBotSseUnit, AstrBotMapEr
} }
/// Stateful mapper that turns AstrBot chat SSE frames into Desktop Gateway events. /// Stateful mapper that turns AstrBot chat SSE frames into Desktop Gateway events.
#[derive(Debug, Clone, PartialEq, Eq)]
struct PendingMedia {
media_type: String,
}
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct AstrBotStreamMapper { pub struct AstrBotStreamMapper {
server_instance_id: String, server_instance_id: String,
@ -222,6 +227,7 @@ pub struct AstrBotStreamMapper {
delta_index: u32, delta_index: u32,
sequence: u64, sequence: u64,
saw_assistant_delta: bool, saw_assistant_delta: bool,
pending_media: Option<PendingMedia>,
} }
impl AstrBotStreamMapper { impl AstrBotStreamMapper {
@ -265,6 +271,7 @@ impl AstrBotStreamMapper {
} }
"user_message_saved" => Vec::new(), "user_message_saved" => Vec::new(),
"plain" => self.map_plain(frame), "plain" => self.map_plain(frame),
"image" | "record" | "file" | "video" => self.map_media(frame),
"complete" => self.map_complete(frame), "complete" => self.map_complete(frame),
"agent_stats" => { "agent_stats" => {
let detail = frame.data.to_string(); let detail = frame.data.to_string();
@ -300,11 +307,51 @@ impl AstrBotStreamMapper {
)); ));
events events
} }
"attachment_saved" => Vec::new(), "attachment_saved" => self.map_attachment_saved(frame),
_ => Vec::new(), _ => Vec::new(),
} }
} }
fn map_media(&mut self, frame: AstrBotStreamFrame) -> Vec<GatewayEvent> {
let mut events = Vec::new();
if let Some(message_id) = frame.message_id {
if self
.active_message_id
.as_ref()
.is_some_and(|current| current != &message_id)
{
events = self.complete_if_needed(FinishReason::Stop);
self.accumulated.clear();
self.delta_index = 0;
self.saw_assistant_delta = false;
}
self.active_message_id = Some(message_id);
}
self.pending_media = Some(PendingMedia {
media_type: frame.frame_type,
});
events
}
fn map_attachment_saved(&mut self, frame: AstrBotStreamFrame) -> Vec<GatewayEvent> {
let Some(media) = self.pending_media.take() else {
return Vec::new();
};
let Some(attachment_id) = frame
.data
.get("id")
.or_else(|| frame.data.get("attachment_id"))
.and_then(Value::as_str)
.filter(|value| !value.trim().is_empty())
else {
return Vec::new();
};
if media.media_type != "image" {
return Vec::new();
}
self.emit_delta(format!("![image](astrbot-attachment://{attachment_id})"))
}
fn map_plain(&mut self, frame: AstrBotStreamFrame) -> Vec<GatewayEvent> { fn map_plain(&mut self, frame: AstrBotStreamFrame) -> Vec<GatewayEvent> {
let chunk = text_from_value(&frame.data).unwrap_or_default(); let chunk = text_from_value(&frame.data).unwrap_or_default();
if chunk.is_empty() && frame.streaming.unwrap_or(false) { if chunk.is_empty() && frame.streaming.unwrap_or(false) {
@ -564,6 +611,28 @@ mod tests {
} }
} }
#[test]
fn maps_image_frames_to_persistable_attachment_markers() {
let mut mapper = AstrBotStreamMapper::new("astrbot-test");
assert!(
mapper
.push_line(r#"data: {"type":"image","data":"[IMAGE]happy.png","message_id":"m1"}"#)
.expect("image frame")
.is_empty()
);
let events = mapper
.push_line(r#"data: {"type":"attachment_saved","data":{"id":"att-1","type":"image"},"message_id":"m1"}"#)
.expect("attachment frame");
let delta = events
.iter()
.find_map(|event| match &event.body {
GatewayEventBody::MessageDelta(payload) => Some(payload.delta.as_str()),
_ => None,
})
.expect("image delta");
assert_eq!(delta, "![image](astrbot-attachment://att-1)");
}
#[test] #[test]
fn derives_stable_instance_ids() { fn derives_stable_instance_ids() {
let a = derive_astrbot_server_instance_id("http://192.168.31.210:26285/"); let a = derive_astrbot_server_instance_id("http://192.168.31.210:26285/");

查看文件

@ -308,3 +308,40 @@ Still not claimed complete: automatic startup activation, real Tauri multi-windo
- Added responsive runtime metadata and chat layout refinements; preserved the existing pet event bus for Q13 state synchronization. - Added responsive runtime metadata and chat layout refinements; preserved the existing pet event bus for Q13 state synchronization.
- Updated frontend test mocks for runtime status schema changes. - Updated frontend test mocks for runtime status schema changes.
- Validation: Vitest (6), TypeScript, ESLint, and targeted Prettier checks pass. - Validation: Vitest (6), TypeScript, ESLint, and targeted Prettier checks pass.
## 2026-07-21: frontend UI audit and chat-page visual increment
- Completed the Impeccable audit and recorded the P0-P3 findings in `docs/reports/ui-audit-2026-07-21.md`.
- Recorded the P0-P2 redesign queue and preserved contracts in `docs/ui-redesign-plan.md`.
- Refined the chat page visual layer in `src/styles.css` only: added shared UI tokens, visible focus states, clearer slot/runtime hierarchy, calmer surfaces, responsive composer layout, and reduced-motion fallback.
- No IPC command, event name, route key, profile/slot/session/message schema, or security boundary changed.
- Frontend validation after the increment: typecheck passed, lint passed, Vitest 6 passed, Vite build passed; build still reports the existing large JS chunk warning.
- Browser preview at 1280x720 confirmed no horizontal overflow on the chat page. In-browser IPC fallback remains expected outside Tauri.
## 2026-07-21: chat page accessibility and polish increment
- Added chat slot tab relationships, keyboard left/right switching, selected-tab focus order, message tabpanel semantics, busy state, and alert semantics for send/runtime errors.
- Kept the existing chat state, invoke/listen calls, session switching, attachment upload, voice input, retry, copy, read-aloud, and stop-generation interactions unchanged.
- Refined chat-only typography, scroll behavior, focus treatment, disabled states, voice active state, file input focusability, touch targets, and narrow-window layout without adding motion.
- Frontend validation passed: Prettier on `src/features/chat/ChatPanel.tsx`, typecheck, lint, Vitest 6 tests, and Vite production build.
- Browser preview passed at 1280x720 with no horizontal overflow; slot arrow-key switching selected the adjacent tab. Existing pet overlay/navigation overlap remains outside this batch.
## 2026-07-21: P1-P3 frontend hardening increment
- Added lazy-loaded chunks for ProfileManager and PetPackImporter, with a status fallback and async test waiting.
- Added visible diagnostic field labels, global IPC alert semantics, and a safe desktop-pet left boundary that keeps the main navigation clear on desktop widths.
- Consolidated the visual layer through shared UI tokens, Windows-native typography, reduced card shadows, calmer surfaces, consistent focus/disabled/error states, and narrow-window session layout.
- Preserved existing routes, page keys, IPC command/event names, connection slots, profile/session/message data, and security boundaries.
- Validation: typecheck, lint, Vitest 6 tests, targeted Prettier checks, Vite build, and 1280x720 browser preview passed. Build now emits ProfileManager and PetPackImporter async chunks; the existing large main JS chunk warning remains.
- Normalized persisted in-app pet coordinates on mount and window resize so stale positions cannot remain over the sidebar after an upgrade or window-size change.
- Final frontend validation after the normalization: targeted Prettier, typecheck, lint, Vitest 6, `git diff --check`, and Vite production build passed. Node 24.14.0 still emits the repository's existing engine warning for the `>=24.17.0` requirement.
## 2026-07-22: complete frontend UI redesign queue P1-P3
- Completed P1 core-page work: ProfileManager credential form labels and feedback, StatusBubble semantic status tones, DesktopBehaviorPage grouping, DiagnosticsPage field labels and async feedback.
- Completed P2 code splitting: moved DesktopBehaviorPage and DiagnosticsPage to `src/pages/SettingsPages.tsx`; moved DesktopPetView and sprite loading to `src/features/pet/DesktopPetView.tsx`; kept ProfileManager and PetPackImporter lazy-loaded.
- Reduced the initial JavaScript chunk from approximately 5.54 MB raw / 4.02 MB gzip to approximately 305.93 kB raw / 91.43 kB gzip. The pet renderer remains an intentional lazy chunk because its inline sprite asset is approximately 5.23 MB.
- Completed P2 consistency work: added shared status colors, numeric typography, responsive 1280/1024/680px rules, reduced-motion fallback, async diagnostic status feedback, visible focus and disabled states, and bounded diagnostic result rendering.
- Added `tests/e2e/ui-polish.spec.ts` for desktop shell overflow checks at 1280px, 1024px, and 680px plus diagnostic keyboard accessibility.
- Completed P3 polish pass for desktop shell hierarchy, status messaging, profile credentials, diagnostics, desktop pet boundary, empty/error/loading states, and dark/light token usage without adding marketing-style animation.
- Validation: targeted Prettier, ESLint, TypeScript, Vitest 6/6, Vite production build, Playwright 5/5, Rust fmt, Clippy with warnings denied, Rust workspace tests (67), and Rust workspace check all passed.
- Known non-blocking warnings: Node is `24.14.0` while the package requires `>=24.17.0`; Vite reports the intentional lazy `DesktopPetView` chunk above 500 kB.

查看文件

@ -0,0 +1,62 @@
# AstrBot Desktop 前端 UI 审计
日期:2026-07-21
范围:`src/App.tsx`、`src/styles.css`、`src/features/**`、前端测试与构建配置
## 审计方式
- 读取 `docs/01_Architecture_Design.md`、`docs/02_Codex_Implementation_Tasks.md` 和现有前端实现。
- 按 Impeccable technical audit 的 Accessibility、Performance、Theming、Responsive、Anti-patterns 五个维度检查。
- 运行本地 detector:`node C:\Users\Administrator\.agents\skills\impeccable\scripts\detect.mjs --json src/App.tsx src/styles.css src/features`;未返回结构化命中项,因此以下结论以源码和基线检查为准。
- 基线:`pnpm run typecheck`、`pnpm run lint`、`pnpm run test`、`pnpm run build` 均通过;Node 版本有 `24.14.0` vs 要求 `>=24.17.0` 的警告。
## Health score
| 维度 | 分数 | 结论 |
| ------------- | --------: | --------------------------------------------------------------------------------------- |
| Accessibility | 2/4 | 已有主导航、部分 ARIA 和 live region,但焦点、键盘 tab 语义、表单标签及窗口控件仍不完整 |
| Performance | 2/4 | 聊天状态集中在大组件,生产 JS gzip 约 4.0 MB,存在按页面拆分和减少无关重渲染空间 |
| Theming | 2/4 | 有 dark/light 主题,但大量颜色、渐变和阴影直接写在 CSS,主题 token 未形成单一来源 |
| Responsive | 2/4 | 有 900/760/680px 断点,但聊天会话列表、工具栏、桌面窗口尺寸和 44px 触控目标仍需验证 |
| Anti-patterns | 2/4 | 不是营销页式 AI slop,但存在渐变背景、重复卡片、过度圆角/阴影和全局大标题层级偏重 |
| **总分** | **10/20** | **Acceptable:需要系统性重构,但不需要改写业务架构** |
## P0:阻塞项
当前没有确认会阻塞任务完成的 P0 功能问题。
## P1:发布前必须处理
1. **聊天页信息层级不稳定** — `src/features/chat/ChatPanel.tsx:577`;运行时状态、槽位切换、会话列表、消息流和输入区堆在同一面板,主任务入口不够突出。
2. **主题令牌不完整** — `src/styles.css:1`、`src/styles.css:1804`;深浅色主题依赖大量重复选择器和硬编码色值,新增页面容易产生视觉漂移。
3. **焦点和键盘状态不完整** — `src/styles.css:246` 只覆盖输入框/选择框;导航按钮、槽位 tab、消息操作和窗口控件缺少统一 `:focus-visible` 样式。
4. **表单标签与可读性不一致** — `src/App.tsx:945`、`src/App.tsx:950`、`src/App.tsx:973` 使用 `aria-label` 代替可见标签;`CredentialEnrollmentCard` 的 label 结构也需要统一间距和错误提示。
5. **聊天构建体积过大** — `pnpm run build` 输出 `index-D8Ql9rJN.js` 约 5.6 MB(gzip 约 4.0 MB);页面级懒加载和资源边界应纳入 P2,若继续增加桌宠/诊断功能则应提前拆分。
6. **状态反馈缺少统一视觉语义** — 连接、加载、错误、空会话和上传状态分散在多个 class,颜色和文案没有统一 token/状态等级。
7. **桌宠浮层遮挡主导航** — 浏览器预览中 pp-pet-overlay 覆盖左侧导航项,桌宠可见时会降低页面可操作性;应限制浮层层级/停靠区,或提供不遮挡导航的安全边界。
## P2:下一批处理
1. 统一桌面工作区的密度、间距、圆角和阴影,减少重复 `card` 包裹。
2. 修正 680px 以下布局:会话列表、聊天工具条、输入框按钮和长文本溢出。
3. 给所有异步按钮补充进行中、失败、恢复动作和 `aria-live` 反馈。
4. 给聊天消息操作、附件移除、窗口控制补充 tooltip/可见焦点,不依赖符号字符表达含义。
5. 引入 `text-wrap: balance/pretty`、`font-variant-numeric: tabular-nums` 和统一字体回退链。
6. 增加 `prefers-reduced-motion` 覆盖,保留桌宠状态动画但避免普通 UI 无限动画扩散。
## 不可改变的产品边界
- 技术栈继续使用 Tauri 2、React、TypeScript、Vite、Rust、SQLite、REST + SSE。
- 保留页面 key:`chat`、`connections`、`desktop`、`pet`、`diagnostics`。
- 不改变 Tauri IPC command/event 名称、Rust 权限边界、profile/slot/session/message 数据结构。
- 不改变 `companion` 与 `operations` 两个槽位的隔离规则,不把 `conversation_id` 单独作为本地唯一键。
- 不让 React 直接读取凭据、任意文件或执行 Shell;不修改后端协议和数据库迁移。
## 首批建议
先重构 `ChatPage` / `ChatPanel` 的视觉层:保留所有 state、invoke/listen、session、attachment、voice 和发送逻辑,只调整信息分组、CSS token、状态展示和响应式布局。
## 外部技能可用性
- 已使用本地 Impeccable audit 规范与 detector。
- 已读取本机 `redesign-existing-projects` 与 `design-taste-frontend` 技能说明,并将其约束应用于方案;它们没有独立可执行命令或额外 CLI。

65
docs/ui-redesign-plan.md 普通文件
查看文件

@ -0,0 +1,65 @@
# AstrBot Desktop UI 重构方案
## Design read
这是一个 Windows 桌面工具型应用,面向需要同时管理陪伴实例和运维实例的用户;视觉应偏安静、可信、信息密度可控的工作台,而不是营销网站或 SaaS 落地页。
## 设计原则
- 保留业务逻辑和交互路径,先重构视觉层和布局层。
- 采用单一冷色中性 token 系统,蓝色只承担交互和连接状态,不使用紫蓝渐变。
- 主任务优先:聊天输入和当前槽位最突出,诊断/连接元信息作为次级层。
- 让错误、离线、空会话、上传中、重连中都能在同一位置理解和恢复。
- 桌面优先,窄窗口可收缩;不把移动端营销布局套进桌面工具。
- 普通 UI 不增加动画;桌宠既有状态动画保留,并加入 reduced-motion 兜底。
## 不变合同
| 范畴 | 保留内容 |
| ---- | ---------------------------------------------------------------------- |
| 页面 | `chat`、`connections`、`desktop`、`pet`、`diagnostics` |
| 连接 | `companion` / `operations` 独立 REST、SSE、Token、会话、消息、未读状态 |
| 数据 | `profile_id`、`server_instance_id`、`conversation_id` 及现有 schema |
| IPC | 现有 `invoke()` commands 和 `listen()` event names |
| 安全 | Rust 持有凭据和本机权限;React 不获得任意文件/命令执行能力 |
| 测试 | 保留现有 Vitest、Playwright、Rust workspace 检查入口 |
## 分阶段队列
### P0 — 先稳定工作台骨架
- `src/styles.css`:抽取颜色、边框、间距、状态和 z-index tokens;补全统一 `:focus-visible`、disabled、error、loading 语义。
- `src/App.tsx`:保持页面 key 和事件逻辑不变,清理页面头部层级与导航可读性。
- `src/features/chat/ChatPanel.tsx`:把运行时状态、槽位 tabs、会话列表、消息流、composer 分成明确的语义区域。
- 验证:Vitest、typecheck、lint、Vite build;聊天页新增关键交互回归断言。
### P1 — 完善核心页面
- `src/features/profiles/ProfileManager.tsx`、`CredentialEnrollmentCard.tsx`:统一表单布局、字段标签、错误/成功反馈和敏感信息说明。
- `src/features/chat/StatusBubble.tsx`:统一连接状态颜色、读屏文本和小窗口窄尺寸。
- `src/App.tsx` 的 `DesktopBehaviorPage`、`DiagnosticsPage`:减少重复卡片,建立明确的设置/诊断分组。
- 验证:表单与槽位隔离测试、键盘导航检查、窄窗口 Playwright。
### P2 — 性能与一致性
- 页面级拆分 `App.tsx` 中非聊天视图,降低首屏 JS 体积。
- 清理重复主题覆盖,保留 dark/light 两套可验证 token。
- 统一消息、状态、按钮、表单的可访问名称与 tooltip;补齐 reduced motion。
- 验证:生产构建体积对比、Playwright 截图/溢出检查、完整 Rust + frontend gate。
## 首批实施范围
只改聊天页视觉层,具体文件:
- `src/features/chat/ChatPanel.tsx`:仅在需要时补充语义属性或可见标签,不改变数据处理。
- `src/styles.css`:新增/调整 chat 相关 token 与布局规则,保留现有 class 兼容。
- `src/App.tsx`:如需调整聊天页外壳,只改 `ChatPage` 的呈现结构,不改导航和 IPC。
- `src/App.test.tsx`:补充聊天页视觉相关的可访问名称/状态回归,不重写现有业务测试。
## 完成标准
- 聊天发送、切槽位、切会话、附件、语音、重连、停止生成、打开快捷窗口行为不变。
- 主聊天区域在 1280px、1024px、680px 窗口下无横向溢出。
- 键盘能到达导航、槽位 tabs、会话、消息操作、输入和发送按钮,焦点可见。
- 深浅色主题对比度满足 WCAG AA;错误和连接状态不只依赖颜色。
- 前端 typecheck、lint、unit test、build 通过。

查看文件

@ -662,6 +662,7 @@ pub fn run() {
networking::commands::connection_slot_sessions, networking::commands::connection_slot_sessions,
networking::commands::switch_connection_slot_session, networking::commands::switch_connection_slot_session,
networking::commands::upload_connection_slot_file, networking::commands::upload_connection_slot_file,
networking::commands::download_connection_slot_attachment,
networking::commands::cancel_connection_slot_message, networking::commands::cancel_connection_slot_message,
]) ])
.run(tauri::generate_context!()) .run(tauri::generate_context!())

查看文件

@ -7,7 +7,7 @@ use desktop_protocol::{
derive_astrbot_server_instance_id, derive_astrbot_server_instance_id,
}; };
use futures_util::StreamExt; use futures_util::StreamExt;
use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, HeaderValue}; use reqwest::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE, HeaderMap, HeaderValue};
use secrecy::{ExposeSecret, SecretString}; use secrecy::{ExposeSecret, SecretString};
use serde_json::{Value, json}; use serde_json::{Value, json};
use thiserror::Error; use thiserror::Error;
@ -349,6 +349,46 @@ impl AstrBotClient {
}) })
} }
pub async fn download_attachment(
&self,
attachment_id: &str,
) -> Result<(String, Vec<u8>), AstrBotClientError> {
if attachment_id.is_empty()
|| attachment_id.len() > 200
|| !attachment_id
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
{
return Err(AstrBotClientError::InvalidConfig("invalid attachment id"));
}
let response = self
.http
.get(self.url(&format!("/api/v1/files/{attachment_id}/content")))
.send()
.await?;
if response.status().as_u16() == 401 || response.status().as_u16() == 403 {
return Err(AstrBotClientError::HttpStatus(response.status()));
}
if !response.status().is_success() {
return Err(AstrBotClientError::HttpStatus(response.status()));
}
let mime_type = response
.headers()
.get(CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.split(';').next())
.filter(|value| !value.trim().is_empty())
.unwrap_or("application/octet-stream")
.to_owned();
let bytes = response.bytes().await?.to_vec();
if bytes.is_empty() || bytes.len() > 16 * 1024 * 1024 {
return Err(AstrBotClientError::InvalidConfig(
"attachment size is outside the supported range",
));
}
Ok((mime_type, bytes))
}
pub async fn send_chat_stream( pub async fn send_chat_stream(
&self, &self,
message: &str, message: &str,

查看文件

@ -1,7 +1,7 @@
// IPC wrappers for dual-slot runtime. Secrets never leave Rust. // IPC wrappers for dual-slot runtime. Secrets never leave Rust.
use desktop_protocol::TransportKind; use desktop_protocol::TransportKind;
use secrecy::SecretString; use secrecy::SecretString;
use serde::Deserialize; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
use tauri::State; use tauri::State;
use tracing::{info, warn}; use tracing::{info, warn};
@ -46,6 +46,20 @@ pub struct SlotFileUploadRequest {
pub bytes: Vec<u8>, pub bytes: Vec<u8>,
} }
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DownloadConnectionSlotAttachmentRequest {
pub slot: SlotKind,
pub attachment_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DownloadConnectionSlotAttachmentResponse {
pub mime_type: String,
pub bytes: Vec<u8>,
}
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)] #[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SlotCapabilitiesRequest { pub struct SlotCapabilitiesRequest {
@ -92,6 +106,32 @@ fn slot_name(slot: SlotKind) -> &'static str {
} }
} }
fn persist_session_identity(database: &ApplicationDatabase, snapshot: &SlotRuntimeSnapshot) {
let Some(profile_id) = snapshot.profile_id.as_deref() else {
return;
};
let Some(session_id) = snapshot.active_session_id.as_deref() else {
return;
};
let Ok(Some(mut profile)) = database.profile(profile_id) else {
return;
};
let mut dirty = false;
if profile.sticky_session_id.as_deref() != Some(session_id) {
profile.sticky_session_id = Some(session_id.to_owned());
dirty = true;
}
if profile.server_instance_id.is_none()
&& let Some(server_instance_id) = snapshot.server_instance_id.as_deref()
{
profile.server_instance_id = Some(server_instance_id.to_owned());
dirty = true;
}
if dirty {
let _ = database.update_profile(&profile);
}
}
#[tauri::command] #[tauri::command]
pub async fn connection_runtime_status( pub async fn connection_runtime_status(
runtime: State<'_, DualSlotRuntime>, runtime: State<'_, DualSlotRuntime>,
@ -134,12 +174,15 @@ pub async fn auto_connect_configured_slots(
}; };
match runtime.activate_slot(activation).await { match runtime.activate_slot(activation).await {
Ok(snapshot) => info!( Ok(snapshot) => {
persist_session_identity(database, &snapshot);
info!(
profile_id = %profile_id, profile_id = %profile_id,
slot = ?slot, slot = ?slot,
state = ?snapshot.state, state = ?snapshot.state,
"startup auto-connect completed" "startup auto-connect completed"
), );
}
Err(error) => warn!( Err(error) => warn!(
profile_id = %profile_id, profile_id = %profile_id,
slot = ?slot, slot = ?slot,
@ -530,12 +573,15 @@ pub async fn connection_slot_sessions(
#[tauri::command] #[tauri::command]
pub async fn switch_connection_slot_session( pub async fn switch_connection_slot_session(
database: State<'_, ApplicationDatabase>,
runtime: State<'_, DualSlotRuntime>, runtime: State<'_, DualSlotRuntime>,
request: SwitchChatSessionRequest, request: SwitchChatSessionRequest,
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> { ) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
runtime let snapshot = runtime
.switch_slot_session(request.slot, request.session_id) .switch_slot_session(request.slot, request.session_id)
.await .await?;
persist_session_identity(&database, &snapshot);
Ok(snapshot)
} }
#[tauri::command] #[tauri::command]
@ -546,6 +592,17 @@ pub async fn connection_slot_capabilities(
runtime.slot_capabilities(request.slot).await runtime.slot_capabilities(request.slot).await
} }
#[tauri::command]
pub async fn download_connection_slot_attachment(
runtime: State<'_, DualSlotRuntime>,
request: DownloadConnectionSlotAttachmentRequest,
) -> Result<DownloadConnectionSlotAttachmentResponse, RuntimeCommandError> {
let (mime_type, bytes) = runtime
.download_slot_attachment(request.slot, request.attachment_id)
.await?;
Ok(DownloadConnectionSlotAttachmentResponse { mime_type, bytes })
}
#[tauri::command] #[tauri::command]
pub async fn upload_connection_slot_file( pub async fn upload_connection_slot_file(
runtime: State<'_, DualSlotRuntime>, runtime: State<'_, DualSlotRuntime>,
@ -627,5 +684,8 @@ pub async fn send_connection_slot_message(
false, false,
); );
} }
if let Ok(snapshot) = &result {
persist_session_identity(&database, snapshot);
}
result result
} }

查看文件

@ -6,11 +6,11 @@ mod runtime;
pub use astrbot_client::{AstrBotClient, AstrBotClientConfig, AstrBotClientError}; pub use astrbot_client::{AstrBotClient, AstrBotClientConfig, AstrBotClientError};
pub use commands::{ pub use commands::{
DisconnectConnectionSlotRequest, DrainConnectionRuntimeEventsRequest, ListChatSessionsRequest, DisconnectConnectionSlotRequest, DownloadConnectionSlotAttachmentRequest,
MarkChatSessionReadRequest, ProbeConnectionSlotRequest, SendConnectionSlotMessageRequest, DrainConnectionRuntimeEventsRequest, ListChatSessionsRequest, MarkChatSessionReadRequest,
auto_connect_configured_slots, cancel_connection_slot_message, connection_runtime_status, ProbeConnectionSlotRequest, SendConnectionSlotMessageRequest, auto_connect_configured_slots,
disconnect_connection_slot, drain_connection_runtime_events, probe_connection_slot, cancel_connection_slot_message, connection_runtime_status, disconnect_connection_slot,
send_connection_slot_message, 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};

查看文件

@ -502,6 +502,33 @@ impl DualSlotRuntime {
.map_err(|_| RuntimeCommandError::unavailable("AstrBot capabilities are unavailable.")) .map_err(|_| RuntimeCommandError::unavailable("AstrBot capabilities are unavailable."))
} }
pub async fn download_slot_attachment(
&self,
slot: SlotKind,
attachment_id: String,
) -> Result<(String, Vec<u8>), RuntimeCommandError> {
let client = {
let guard = self.inner.lock().await;
match slot_ref(&guard, slot).client.as_ref() {
Some(ActiveClient::AstrBot(client)) => client.clone(),
Some(ActiveClient::Desktop(_)) => {
return Err(RuntimeCommandError::validation(
"Attachment download is not available for the desktop mock transport.",
));
}
None => {
return Err(RuntimeCommandError::unavailable(
"Activate the connection before downloading an attachment.",
));
}
}
};
client
.download_attachment(&attachment_id)
.await
.map_err(|_| RuntimeCommandError::unavailable("AstrBot attachment download failed."))
}
pub async fn upload_slot_file( pub async fn upload_slot_file(
&self, &self,
slot: SlotKind, slot: SlotKind,

查看文件

@ -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";
@ -46,12 +46,13 @@ const emptyPolicy: ConnectionPolicyStatus = {
duplicateServerInstanceWarnings: [], duplicateServerInstanceWarnings: [],
}; };
function openConnectionsPage() { async function openConnectionsPage() {
fireEvent.click(screen.getByRole("button", { name: /连接/ })); fireEvent.click(screen.getByRole("button", { name: /◎连接/ }));
await screen.findByRole("heading", { level: 2 }, { timeout: 5000 });
} }
function openDiagnosticsPage() { function openDiagnosticsPage() {
fireEvent.click(screen.getByRole("button", { name: /诊断与设置/ })); fireEvent.click(screen.getByRole("button", { name: /⚙诊断与设置/ }));
} }
function mockBaseCommands(options?: { function mockBaseCommands(options?: {
@ -140,7 +141,7 @@ describe("App", () => {
openDiagnosticsPage(); openDiagnosticsPage();
expect(await screen.findByText("ready")).toBeInTheDocument(); expect(await screen.findByText("ready")).toBeInTheDocument();
expect(screen.getByText("desktop-v1alpha1")).toBeInTheDocument(); expect(screen.getByText("desktop-v1alpha1")).toBeInTheDocument();
openConnectionsPage(); await openConnectionsPage();
expect(screen.getByText("连接 Profile")).toBeInTheDocument(); expect(screen.getByText("连接 Profile")).toBeInTheDocument();
}); });
@ -223,7 +224,7 @@ describe("App", () => {
vi.spyOn(window, "confirm").mockReturnValue(true); vi.spyOn(window, "confirm").mockReturnValue(true);
render(<App />); render(<App />);
openConnectionsPage(); await openConnectionsPage();
expect(await screen.findByText("尚未保存 Profile。")).toBeInTheDocument(); expect(await screen.findByText("尚未保存 Profile。")).toBeInTheDocument();
fireEvent.change(screen.getByLabelText("显示名称"), { fireEvent.change(screen.getByLabelText("显示名称"), {
@ -310,7 +311,7 @@ describe("App", () => {
mockBaseCommands({ profiles }); mockBaseCommands({ profiles });
render(<App />); render(<App />);
openConnectionsPage(); await openConnectionsPage();
fireEvent.change(await screen.findByLabelText("陪伴 Profile"), { fireEvent.change(await screen.findByLabelText("陪伴 Profile"), {
target: { value: profiles[0].id }, target: { value: profiles[0].id },
@ -364,7 +365,7 @@ describe("App", () => {
}); });
render(<App />); render(<App />);
openConnectionsPage(); await openConnectionsPage();
expect(await screen.findByText("尚未保存 Profile。")).toBeInTheDocument(); expect(await screen.findByText("尚未保存 Profile。")).toBeInTheDocument();
fireEvent.change(screen.getByLabelText("显示名称"), { fireEvent.change(screen.getByLabelText("显示名称"), {
@ -465,7 +466,7 @@ describe("App", () => {
}); });
render(<App />); render(<App />);
openConnectionsPage(); await openConnectionsPage();
expect( expect(
await screen.findByLabelText("重复服务器实例提示"), await screen.findByLabelText("重复服务器实例提示"),

查看文件

@ -1,17 +1,42 @@
import { invoke } from "@tauri-apps/api/core"; import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event"; import { listen } from "@tauri-apps/api/event";
import { getCurrentWindow } from "@tauri-apps/api/window"; import { getCurrentWindow } from "@tauri-apps/api/window";
import { useCallback, useEffect, useRef, useState } from "react"; import {
lazy,
Suspense,
useCallback,
useEffect,
useRef,
useState,
} from "react";
import { ChatPanel } from "./features/chat/ChatPanel"; import { ChatPanel } from "./features/chat/ChatPanel";
import { StatusBubble } from "./features/chat/StatusBubble"; import { StatusBubble } from "./features/chat/StatusBubble";
import { ProfileManager } from "./features/profiles/ProfileManager"; const ProfileManager = lazy(() =>
import { PetPackImporter } from "./features/pet/PetPackImporter"; import("./features/profiles/ProfileManager").then(({ ProfileManager }) => ({
import { default: ProfileManager,
boundRuntimeEventSchema, })),
connectionRuntimeStatusSchema, );
} from "./features/chat/types"; const PetPackImporter = lazy(() =>
import aemeathSpritesheet from "./features/pet/assets/aemeath/aemeath-spritesheet.png?inline"; import("./features/pet/PetPackImporter").then(({ PetPackImporter }) => ({
default: PetPackImporter,
})),
);
const DesktopBehaviorPage = lazy(() =>
import("./pages/SettingsPages").then(({ DesktopBehaviorPage }) => ({
default: DesktopBehaviorPage,
})),
);
const DesktopPetView = lazy(() =>
import("./features/pet/DesktopPetView").then(({ DesktopPetView }) => ({
default: DesktopPetView,
})),
);
const DiagnosticsPage = lazy(() =>
import("./pages/SettingsPages").then(({ DiagnosticsPage }) => ({
default: DiagnosticsPage,
})),
);
import { bootstrapStatusSchema, type BootstrapStatus } from "./types/bootstrap"; import { bootstrapStatusSchema, type BootstrapStatus } from "./types/bootstrap";
type PageKey = "chat" | "connections" | "desktop" | "pet" | "diagnostics"; type PageKey = "chat" | "connections" | "desktop" | "pet" | "diagnostics";
@ -27,22 +52,6 @@ const initialStatus: BootstrapStatus = {
databaseSchemaVersion: 4, databaseSchemaVersion: 4,
}; };
const AEMEATH_SPRITESHEET = aemeathSpritesheet;
const PET_TARGET_SLOT = "companion" as const;
const AEMEATH_FRAMES: Record<
"idle" | "working" | "resting" | "speaking" | "error",
number[]
> = {
idle: [0, 1, 2, 3, 4, 5],
working: [
80, 81, 82, 83, 84, 85, 86, 87, 104, 105, 106, 107, 108, 109, 110, 111,
],
resting: [48, 49, 50, 51, 52, 53],
speaking: [72, 73, 74, 75, 76, 77, 78, 79],
error: [40, 41, 42, 43, 44, 45, 46, 47],
};
const navigation: Array<{ key: PageKey; label: string; description: string }> = const navigation: Array<{ key: PageKey; label: string; description: string }> =
[ [
{ key: "chat", label: "聊天", description: "陪伴与运维对话" }, { key: "chat", label: "聊天", description: "陪伴与运维对话" },
@ -179,7 +188,12 @@ export function App() {
} }
> >
{page === "chat" ? null : <PageHeader page={page} />} {page === "chat" ? null : <PageHeader page={page} />}
{error ? <p className="error-banner">IPC 暂不可用:{error}</p> : null} {error ? (
<p className="error-banner" role="alert">
IPC 暂不可用:{error}
</p>
) : null}
<Suspense fallback={<PageLoading />}>
{page === "chat" ? <ChatPage /> : null} {page === "chat" ? <ChatPage /> : null}
{page === "connections" ? <ProfileManager /> : null} {page === "connections" ? <ProfileManager /> : null}
{page === "desktop" ? ( {page === "desktop" ? (
@ -214,9 +228,14 @@ export function App() {
onRefresh={() => void refreshStatus()} onRefresh={() => void refreshStatus()}
/> />
) : null} ) : null}
</Suspense>
</section> </section>
</div> </div>
{petDisplayMode === "app-ui" ? <InAppPetOverlay /> : null} {petDisplayMode === "app-ui" ? (
<Suspense fallback={null}>
<InAppPetOverlay />
</Suspense>
) : null}
</main> </main>
); );
} }
@ -255,7 +274,14 @@ function WindowChrome({
data-tauri-drag-region data-tauri-drag-region
onDoubleClick={() => void toggleMaximize()} onDoubleClick={() => void toggleMaximize()}
onMouseDown={(event) => { onMouseDown={(event) => {
if (event.button === 0) void currentWindow?.startDragging(); if (
event.button === 0 &&
!(event.target as HTMLElement).closest(
'[data-tauri-drag-region="false"]',
)
) {
void currentWindow?.startDragging();
}
}} }}
> >
<span className="window-chrome-title">AstrBot Desktop</span> <span className="window-chrome-title">AstrBot Desktop</span>
@ -323,9 +349,9 @@ function InAppPetOverlay() {
); );
return saved && typeof saved.x === "number" && typeof saved.y === "number" return saved && typeof saved.x === "number" && typeof saved.y === "number"
? saved ? saved
: { x: 24, y: 96 }; : { x: window.innerWidth >= 720 ? 280 : 24, y: 96 };
} catch { } catch {
return { x: 24, y: 96 }; return { x: window.innerWidth >= 720 ? 280 : 24, y: 96 };
} }
}); });
const dragRef = useRef<{ const dragRef = useRef<{
@ -334,15 +360,34 @@ function InAppPetOverlay() {
offsetY: number; offsetY: number;
} | null>(null); } | null>(null);
const savePosition = (x: number, y: number) => { const clampPosition = useCallback((x: number, y: number) => {
const next = { const safeLeft = window.innerWidth >= 720 ? 248 : 0;
x: Math.max(0, Math.min(x, window.innerWidth - 188)), const maxX = Math.max(safeLeft, window.innerWidth - 188);
return {
x: Math.max(safeLeft, Math.min(x, maxX)),
y: Math.max(0, Math.min(y, window.innerHeight - 226)), y: Math.max(0, Math.min(y, window.innerHeight - 226)),
}; };
}, []);
const savePosition = (x: number, y: number) => {
const next = clampPosition(x, y);
setPosition(next); setPosition(next);
localStorage.setItem("astrbot.petPosition", JSON.stringify(next)); localStorage.setItem("astrbot.petPosition", JSON.stringify(next));
}; };
useEffect(() => {
const normalizePosition = () => {
const next = clampPosition(position.x, position.y);
if (next.x === position.x && next.y === position.y) return;
setPosition(next);
localStorage.setItem("astrbot.petPosition", JSON.stringify(next));
};
normalizePosition();
window.addEventListener("resize", normalizePosition);
return () => window.removeEventListener("resize", normalizePosition);
}, [clampPosition, position.x, position.y]);
useEffect(() => { useEffect(() => {
let unlisten: (() => void) | undefined; let unlisten: (() => void) | undefined;
void listen("pet-hide-requested", () => setVisible(false)).then( void listen("pet-hide-requested", () => setVisible(false)).then(
@ -400,6 +445,14 @@ function navIcon(page: PageKey) {
}[page]; }[page];
} }
function PageLoading() {
return (
<p className="loading-state" role="status" aria-live="polite">
Loading?
</p>
);
}
function PageHeader({ page }: { page: PageKey }) { function PageHeader({ page }: { page: PageKey }) {
const current = navigation.find((item) => item.key === page) ?? navigation[0]; const current = navigation.find((item) => item.key === page) ?? navigation[0];
return ( return (
@ -427,103 +480,6 @@ function ChatPage() {
); );
} }
function DesktopBehaviorPage({
bubbleTarget,
quickTarget,
onBubbleTargetChange,
onQuickTargetChange,
onOpenQuickChat,
}: {
bubbleTarget: "main" | "quick";
quickTarget: ChatSlot;
onBubbleTargetChange: (value: "main" | "quick") => void;
onQuickTargetChange: (value: ChatSlot) => void;
onOpenQuickChat: () => void;
}) {
const [quietHours, setQuietHours] = useState(
() => localStorage.getItem("astrbot.quietHours") ?? "off",
);
return (
<div className="page-stack">
<section className="settings-grid">
<SettingCard
title="快速聊天"
description="设置气泡或快捷入口打开哪个实例。"
>
<label>
<span>默认目标槽位</span>
<select
value={quickTarget}
onChange={(event) =>
onQuickTargetChange(event.target.value as ChatSlot)
}
>
<option value="companion">陪伴实例</option>
<option value="operations">运维实例</option>
</select>
</label>
<button type="button" onClick={onOpenQuickChat}>
立即打开快速聊天
</button>
</SettingCard>
<SettingCard
title="状态气泡"
description="气泡显示连接状态,并根据这里的设置响应点击。"
>
<label>
<span>点击气泡时</span>
<select
value={bubbleTarget}
onChange={(event) =>
onBubbleTargetChange(event.target.value as "main" | "quick")
}
>
<option value="main">打开主界面</option>
<option value="quick">打开快速聊天</option>
</select>
</label>
<div className="status-preview">
<span className="connection-dot" />
气泡状态显示已预留
</div>
</SettingCard>
</section>
<section className="info-card">
<span className="section-kicker">Desktop companion</span>
<h2>后续桌面能力</h2>
<div className="feature-list">
<span>托盘与单实例</span>
<span>窗口置顶开关</span>
<span>多显示器策略</span>
<span>游戏模式靠边活动</span>
</div>
<p>
这些能力先保留为独立设置区,后续接入 Rust
本机能力层,不会与聊天状态混在一起。
</p>
</section>
<section className="settings-grid">
<SettingCard
title="主动消息静默时段"
description="静默时段只抑制气泡提醒,不会删除消息,也不会影响聊天未读数。"
>
<select
value={quietHours}
onChange={(event) => {
const next = event.target.value;
setQuietHours(next);
localStorage.setItem("astrbot.quietHours", next);
}}
>
<option value="off">关闭</option>
<option value="night">每天 22:00–07:00</option>
</select>
</SettingCard>
</section>
</div>
);
}
function PetPage({ function PetPage({
displayMode, displayMode,
onDisplayModeChange, onDisplayModeChange,
@ -691,343 +647,6 @@ function PetPage({
); );
} }
function DesktopPetView({ embedded = false }: { embedded?: boolean }) {
const [state, setState] = useState<
"idle" | "working" | "resting" | "speaking" | "error"
>("idle");
const [frameIndex, setFrameIndex] = useState(0);
const [spriteReady, setSpriteReady] = useState(false);
const [spriteError, setSpriteError] = useState<string | null>(null);
const [gameMode, setGameMode] = useState(false);
const spriteImageRef = useRef<HTMLImageElement | null>(null);
const spriteCanvasRef = useRef<HTMLCanvasElement | null>(null);
useEffect(() => {
if (embedded) return;
document.documentElement.classList.add("pet-view");
return () => document.documentElement.classList.remove("pet-view");
}, [embedded]);
const completionTimerRef = useRef<number | null>(null);
useEffect(() => {
let unlisten: (() => void) | undefined;
let unlistenRuntime: (() => void) | undefined;
void listen("pet-game-mode-toggle", () =>
setGameMode((current) => !current),
).then((cleanup) => {
unlisten = cleanup;
});
void listen<unknown>("connection-runtime-event", (event) => {
const parsed = boundRuntimeEventSchema.safeParse(event.payload);
if (!parsed.success || parsed.data.slot !== PET_TARGET_SLOT) return;
if (completionTimerRef.current !== null) {
window.clearTimeout(completionTimerRef.current);
completionTimerRef.current = null;
}
if (parsed.data.eventType === "message.delta") setState("working");
if (parsed.data.eventType === "message.proactive") setState("speaking");
if (parsed.data.eventType === "message.completed") {
setState("speaking");
completionTimerRef.current = window.setTimeout(() => {
completionTimerRef.current = null;
setState("idle");
}, 2200);
}
if (parsed.data.eventType === "error") setState("error");
}).then((cleanup) => {
unlistenRuntime = cleanup;
});
return () => {
unlisten?.();
unlistenRuntime?.();
if (completionTimerRef.current !== null) {
window.clearTimeout(completionTimerRef.current);
completionTimerRef.current = null;
}
};
}, []);
useEffect(() => {
const image = new Image();
image.onload = () => {
spriteImageRef.current = image;
setSpriteError(null);
setSpriteReady(true);
};
image.onerror = () => {
setSpriteError("????????");
};
image.src = AEMEATH_SPRITESHEET;
return () => {
image.onload = null;
};
}, []);
useEffect(() => {
let cancelled = false;
void invoke<unknown>("connection_runtime_status")
.then((value) => {
if (cancelled) return;
try {
const result = connectionRuntimeStatusSchema.parse(value);
const state = result.companion.state;
if (
state === "authExpired" ||
state === "fatalError" ||
state === "incompatible"
) {
setState("error");
} else if (
state === "syncing" ||
state === "connecting" ||
state === "authenticating"
) {
setState("working");
} else if (state === "reconnecting") {
setState("speaking");
} else if (state === "disconnected" || state === "offline") {
setState("resting");
} else {
setState("idle");
}
} catch {
setState("idle");
}
})
.catch(() => {
if (!cancelled) setState("idle");
});
return () => {
cancelled = true;
};
}, []);
useEffect(() => {
void invoke("set_pet_window_preferences", {
preferences: {
positionMode: "edge",
monitorIndex: 0,
alwaysOnTop: true,
gameMode,
},
}).catch(() => undefined);
}, [gameMode]);
useEffect(() => {
setFrameIndex(0);
const frames = AEMEATH_FRAMES[state];
const timer = window.setInterval(
() => {
setFrameIndex((current) => (current + 1) % frames.length);
},
state === "resting" ? 180 : 125,
);
return () => window.clearInterval(timer);
}, [state]);
const frame =
AEMEATH_FRAMES[state][frameIndex % AEMEATH_FRAMES[state].length];
const frameRow = Math.floor(frame / 8);
const frameColumn = frame % 8;
useEffect(() => {
const canvas = spriteCanvasRef.current;
const image = spriteImageRef.current;
if (!canvas || !image || !spriteReady) return;
const context = canvas.getContext("2d");
if (!context) {
setSpriteError("???? Canvas ?????");
return;
}
try {
context.clearRect(0, 0, 192, 208);
context.imageSmoothingEnabled = false;
context.drawImage(
image,
frameColumn * 192,
frameRow * 208,
192,
208,
0,
0,
192,
208,
);
} catch (reason) {
setSpriteError(reason instanceof Error ? reason.message : "??????");
}
}, [frameColumn, frameRow, spriteReady]);
return (
<main
className={`pet-window pet-window-${state}${gameMode ? " pet-window-game" : ""}${embedded ? " pet-window-embedded" : ""}`}
aria-label="AstrBot ??"
data-tauri-drag-region={!embedded ? "true" : undefined}
onMouseDown={(event) => {
if (embedded || event.button !== 0) return;
void getCurrentWindow().startDragging();
}}
onContextMenu={(event) => {
event.preventDefault();
void invoke("show_pet_context_menu");
}}
>
<div
className={`aemeath-pet-frame aemeath-pet-${state}`}
role="img"
aria-label={`桌宠状态:${state}`}
>
<canvas
ref={spriteCanvasRef}
className="aemeath-pet-sprite"
width={192}
height={208}
role="img"
aria-label={`pet-${state}`}
/>
</div>
{spriteError ? (
<span className="pet-render-error">{spriteError}</span>
) : null}
{!spriteReady && !spriteError ? (
<span className="pet-render-loading">Loading pet...</span>
) : null}
<span className="pet-window-status">
{state === "working"
? "正在写写画画"
: state === "resting"
? "休息中"
: state === "speaking"
? "正在回应"
: state === "error"
? "需要重新登录或检查连接"
: "陪伴中"}
</span>
</main>
);
}
function DiagnosticsTools() {
const [result, setResult] = useState("");
const [host, setHost] = useState("127.0.0.1");
const [port, setPort] = useState("80");
const [processId, setProcessId] = useState("0");
const run = async (command: string, request?: Record<string, unknown>) => {
try {
const value = await invoke<unknown>(
command,
request ? { request } : undefined,
);
setResult(JSON.stringify(value, null, 2));
} catch (reason) {
setResult(reason instanceof Error ? reason.message : String(reason));
}
};
return (
<>
<section className="settings-grid">
<SettingCard
title="前台窗口"
description="读取当前前台窗口的标题、类名和进程身份。"
>
<button
type="button"
onClick={() => void run("inspect_foreground_window")}
>
检查前台窗口
</button>
</SettingCard>
<SettingCard
title="网络连通性"
description="只检查一个明确的主机和端口,不执行扫描。"
>
<input
value={host}
onChange={(event) => setHost(event.target.value)}
aria-label="网络主机"
/>
<input
value={port}
onChange={(event) => setPort(event.target.value)}
aria-label="网络端口"
inputMode="numeric"
/>
<button
type="button"
onClick={() =>
void run("check_network_target", {
host,
port: Number(port),
timeoutSeconds: 3,
})
}
>
检查端口
</button>
</SettingCard>
<SettingCard
title="指定进程"
description="输入进程 ID 后读取有限的进程摘要,不枚举全部进程。"
>
<input
value={processId}
onChange={(event) => setProcessId(event.target.value)}
aria-label="进程 ID"
inputMode="numeric"
/>
<button
type="button"
onClick={() =>
void run("inspect_process", { processId: Number(processId) })
}
>
检查进程
</button>
</SettingCard>
</section>
{result ? <pre className="diagnostic-result">{result}</pre> : null}
</>
);
}
function DiagnosticsPage({
status,
onRefresh,
}: {
status: BootstrapStatus;
onRefresh: () => void;
}) {
return (
<div className="page-stack">
<section className="status-grid" aria-label="bootstrap status">
<StatusCard label="Rust Core" value={status.rustCore} />
<StatusCard label="Platform" value={status.platform} />
<StatusCard label="App Version" value={status.appVersion} />
<StatusCard label="Protocol" value={status.protocolVersion} />
<StatusCard
label="Database Schema"
value={String(status.databaseSchemaVersion)}
/>
</section>
<DiagnosticsTools />
<section className="boundaries">
<span className="section-kicker">Security boundary</span>
<h2>本机能力保持可审计</h2>
<ul>
<li>凭据只在 Rust 与 Windows 安全存储之间流动。</li>
<li>两个 REST/SSE 槽位保持独立状态、会话、消息与未读数。</li>
<li>本机操作必须经过白名单、角色、路径和用户授权。</li>
<li>文件事务默认保留源文件,不静默覆盖目标。</li>
</ul>
</section>
<button type="button" onClick={onRefresh}>
刷新 IPC 状态
</button>
</div>
);
}
function SettingCard({ function SettingCard({
title, title,
description, description,
@ -1048,16 +667,3 @@ function SettingCard({
</section> </section>
); );
} }
interface StatusCardProps {
label: string;
value: string;
}
function StatusCard({ label, value }: StatusCardProps) {
return (
<article className="status-card">
<span>{label}</span>
<strong>{value}</strong>
</article>
);
}

查看文件

@ -13,6 +13,8 @@ import {
type AstrBotAttachment, type AstrBotAttachment,
type AstrBotCapabilitySnapshot, type AstrBotCapabilitySnapshot,
type BoundRuntimeEvent, type BoundRuntimeEvent,
type ChatSession,
mergeLoadedChatMessages,
remoteChatSessionSchema, remoteChatSessionSchema,
type ChatMessage, type ChatMessage,
type ChatSlot, type ChatSlot,
@ -54,6 +56,12 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
const [status, setStatus] = useState(emptyStatus); const [status, setStatus] = useState(emptyStatus);
const [messages, setMessages] = useState<ChatMessage[]>([]); const [messages, setMessages] = useState<ChatMessage[]>([]);
const [remoteSessions, setRemoteSessions] = useState<RemoteChatSession[]>([]); const [remoteSessions, setRemoteSessions] = useState<RemoteChatSession[]>([]);
const [storedSessions, setStoredSessions] = useState<
Record<ChatSlot, ChatSession[]>
>({
companion: [],
operations: [],
});
const [activeSlot, setActiveSlot] = useState<ChatSlot>( const [activeSlot, setActiveSlot] = useState<ChatSlot>(
fixedSlot ?? "companion", fixedSlot ?? "companion",
); );
@ -62,6 +70,8 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
const selectedProfileId = selectedSnapshot.profileId; const selectedProfileId = selectedSnapshot.profileId;
const selectedServerInstanceId = selectedSnapshot.serverInstanceId; const selectedServerInstanceId = selectedSnapshot.serverInstanceId;
const selectedSessionId = selectedSnapshot.activeSessionId; const selectedSessionId = selectedSnapshot.activeSessionId;
const historySessionId =
selectedSessionId ?? storedSessions[selectedSlot][0]?.sessionId;
const selectedTransport = selectedSnapshot.transport; const selectedTransport = selectedSnapshot.transport;
const [draft, setDraft] = useState(""); const [draft, setDraft] = useState("");
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
@ -105,6 +115,15 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
[activeMessages], [activeMessages],
); );
const displaySessions =
remoteSessions.length > 0
? remoteSessions
: storedSessions[selectedSlot].map((session) => ({
sessionId: session.sessionId,
displayName: undefined,
updatedAt: session.lastMessageAt,
}));
const refresh = useCallback(async () => { const refresh = useCallback(async () => {
try { try {
const result = await invoke<unknown>("connection_runtime_status"); const result = await invoke<unknown>("connection_runtime_status");
@ -154,6 +173,11 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
.then((result) => { .then((result) => {
if (cancelled) return; if (cancelled) return;
const sessions = chatSessionSchema.array().parse(result); const sessions = chatSessionSchema.array().parse(result);
setStoredSessions((current) => ({
...current,
[selectedSlot]: sessions,
}));
setUnreadCounts((current) => ({ setUnreadCounts((current) => ({
...current, ...current,
[selectedSlot]: sessions.reduce( [selectedSlot]: sessions.reduce(
@ -171,6 +195,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
selectedProfileId, selectedProfileId,
selectedServerInstanceId, selectedServerInstanceId,
selectedSessionId, selectedSessionId,
historySessionId,
selectedTransport, selectedTransport,
]); ]);
@ -200,6 +225,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
selectedProfileId, selectedProfileId,
selectedServerInstanceId, selectedServerInstanceId,
selectedSessionId, selectedSessionId,
historySessionId,
selectedTransport, selectedTransport,
]); ]);
@ -231,6 +257,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
selectedProfileId, selectedProfileId,
selectedServerInstanceId, selectedServerInstanceId,
selectedSessionId, selectedSessionId,
historySessionId,
selectedTransport, selectedTransport,
]); ]);
@ -238,7 +265,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
const snapshot = { const snapshot = {
profileId: selectedProfileId, profileId: selectedProfileId,
serverInstanceId: selectedServerInstanceId, serverInstanceId: selectedServerInstanceId,
activeSessionId: selectedSessionId, activeSessionId: historySessionId,
transport: selectedTransport, transport: selectedTransport,
}; };
if ( if (
@ -261,6 +288,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
selectedProfileId, selectedProfileId,
selectedServerInstanceId, selectedServerInstanceId,
selectedSessionId, selectedSessionId,
historySessionId,
selectedTransport, selectedTransport,
]); ]);
@ -268,7 +296,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
const snapshot = { const snapshot = {
profileId: selectedProfileId, profileId: selectedProfileId,
serverInstanceId: selectedServerInstanceId, serverInstanceId: selectedServerInstanceId,
activeSessionId: selectedSessionId, activeSessionId: historySessionId,
transport: selectedTransport, transport: selectedTransport,
}; };
if ( if (
@ -290,32 +318,14 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
.then((result) => { .then((result) => {
if (cancelled) return; if (cancelled) return;
const records = storedChatMessageSchema.array().parse(result); const records = storedChatMessageSchema.array().parse(result);
setMessages((current) => { setMessages((current) =>
const localUserMessages = current.filter( mergeLoadedChatMessages(
(item) => current,
(item.id.startsWith("local-") || item.streaming) && records,
item.slot === selectedSlot && selectedSlot,
item.sessionId === snapshot.activeSessionId, snapshot.activeSessionId,
),
); );
return current
.filter(
(item) =>
item.slot !== selectedSlot ||
item.sessionId !== snapshot.activeSessionId,
)
.concat(localUserMessages)
.concat(
records.map((record) => ({
id: record.messageId,
sessionId: record.sessionId,
slot: record.slot,
role: record.role,
content: record.content,
streaming: record.streaming,
error: record.error,
})),
);
});
}) })
.catch(() => undefined); .catch(() => undefined);
return () => { return () => {
@ -326,6 +336,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
selectedProfileId, selectedProfileId,
selectedServerInstanceId, selectedServerInstanceId,
selectedSessionId, selectedSessionId,
historySessionId,
selectedTransport, selectedTransport,
]); ]);
@ -450,7 +461,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
await navigator.clipboard.writeText(content); await navigator.clipboard.writeText(content);
setError(null); setError(null);
} catch { } catch {
setError("Copy failed. Check clipboard permissions."); setError("复制失败,请检查剪贴板权限。");
} }
}; };
@ -577,7 +588,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
<section className="chat-panel" aria-label="聊天面板"> <section className="chat-panel" aria-label="聊天面板">
<div className="chat-heading"> <div className="chat-heading">
<div> <div>
<p className="eyebrow">Shared chat runtime</p> <p className="eyebrow">共享聊天运行时</p>
<h2>统一聊天运行时</h2> <h2>统一聊天运行时</h2>
<p className="chat-note"> <p className="chat-note">
主界面、快速聊天和气泡共享同一套消息状态。 主界面、快速聊天和气泡共享同一套消息状态。
@ -592,6 +603,22 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
onClick={() => setActiveSlot(slot)} onClick={() => setActiveSlot(slot)}
role="tab" role="tab"
aria-selected={activeSlot === slot} aria-selected={activeSlot === slot}
aria-controls={`chat-panel-${slot}`}
tabIndex={fixedSlot || activeSlot === slot ? 0 : -1}
onKeyDown={(event) => {
if (event.key !== "ArrowRight" && event.key !== "ArrowLeft")
return;
event.preventDefault();
setActiveSlot(
slot === "companion" ? "operations" : "companion",
);
}}
type="button" type="button"
> >
{slot === "companion" ? "陪伴" : "运维"} {slot === "companion" ? "陪伴" : "运维"}
@ -605,35 +632,33 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
</div> </div>
<div className="chat-runtime-strip"> <div className="chat-runtime-strip">
<div> <div>
<span>Profile</span> <span>配置</span>
<strong>{status[selectedSlot].profileId ?? "Not connected"}</strong> <strong>{status[selectedSlot].profileId ?? "未连接"}</strong>
</div> </div>
<div> <div>
<span>Session</span> <span>会话</span>
<strong> <strong>{status[selectedSlot].activeSessionId ?? "新会话"}</strong>
{status[selectedSlot].activeSessionId ?? "New session"}
</strong>
</div> </div>
<div> <div>
<span>Status</span> <span>状态</span>
<strong>{connectionStateLabel(status[selectedSlot].state)}</strong> <strong>{connectionStateLabel(status[selectedSlot].state)}</strong>
</div> </div>
<div className="chat-runtime-actions"> <div className="chat-runtime-actions">
<button type="button" onClick={() => void refreshConnection()}> <button type="button" onClick={() => void refreshConnection()}>
Refresh 刷新
</button> </button>
<button type="button" onClick={() => void reconnectConnection()}> <button type="button" onClick={() => void reconnectConnection()}>
Reconnect 重连
</button> </button>
<button <button
type="button" type="button"
onClick={() => void disconnectConnection()} onClick={() => void disconnectConnection()}
disabled={status[selectedSlot].state === "disconnected"} disabled={status[selectedSlot].state === "disconnected"}
> >
Disconnect 断开
</button> </button>
<button type="button" onClick={() => void startNewSession()}> <button type="button" onClick={() => void startNewSession()}>
New chat 新对话
</button> </button>
</div> </div>
</div> </div>
@ -653,9 +678,9 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
</button> </button>
</div> </div>
) : null} ) : null}
{remoteSessions.length > 0 ? ( {displaySessions.length > 0 ? (
<div className="chat-session-list" aria-label="Chat sessions"> <div className="chat-session-list" aria-label="Chat sessions">
{remoteSessions.map((session) => ( {displaySessions.map((session, index) => (
<button <button
className={ className={
session.sessionId === status[selectedSlot].activeSessionId session.sessionId === status[selectedSlot].activeSessionId
@ -663,6 +688,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
: "chat-session" : "chat-session"
} }
key={session.sessionId} key={session.sessionId}
title={`会话标识:${session.sessionId}`}
type="button" type="button"
onClick={() => { onClick={() => {
void invoke("switch_connection_slot_session", { void invoke("switch_connection_slot_session", {
@ -676,16 +702,23 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
); );
}} }}
> >
<strong>{session.displayName || session.sessionId}</strong> <strong>{session.displayName || `会话 ${index + 1}`}</strong>
<small>{session.updatedAt || "Remote session"}</small> <small>{formatSessionTime(session.updatedAt)}</small>
</button> </button>
))} ))}
</div> </div>
) : null} ) : null}
<div className="chat-message-list" aria-live="polite"> <div
id={`chat-panel-${selectedSlot}`}
className="chat-message-list"
role="tabpanel"
aria-label={`${selectedSlot} messages`}
aria-busy={sending[selectedSlot]}
aria-live="polite"
>
{visibleMessages.length === 0 ? ( {visibleMessages.length === 0 ? (
<p className="chat-empty"> <p className="chat-empty">
No messages in this slot yet. Connect a Profile to start chatting. 当前槽位还没有消息。连接 Profile 后即可开始聊天。
</p> </p>
) : ( ) : (
visibleMessages.map((message) => { visibleMessages.map((message) => {
@ -701,43 +734,63 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
? "A" ? "A"
: "!"} : "!"}
</div> </div>
<div className="chat-message-content">
<div className="chat-bubble"> <div className="chat-bubble">
<div className="chat-bubble-header"> <div className="chat-bubble-header">
<span> <span>
{message.role === "user" {message.role === "user"
? "You" ? "你"
: message.role === "assistant" : message.role === "assistant"
? "AstrBot" ? "AstrBot"
: "System"} : "系统"}
</span> </span>
{message.streaming ? <small>Generating</small> : null} {message.streaming ? <small>生成中</small> : null}
</div> </div>
{message.content ? ( {message.content ? (
<MessageContent content={message.content} /> <MessageContent content={message.content} slot={selectedSlot} />
) : ( ) : (
<p className="message-placeholder">Generating?</p> <p className="message-placeholder">正在生成…</p>
)} )}
</div>
{message.role === "assistant" && {message.role === "assistant" &&
message.content && message.content &&
!message.streaming ? ( !message.streaming ? (
<div className="chat-message-actions"> <div className="chat-message-actions" aria-label="消息操作">
<button <button
type="button" type="button"
aria-label="复制消息"
title="复制消息"
onClick={() => void copyMessage(message.content)} onClick={() => void copyMessage(message.content)}
> >
Copy <span
className="message-action-icon icon-copy"
aria-hidden="true"
/>
<span>复制</span>
</button> </button>
<button <button
type="button" type="button"
aria-label="重试消息"
title="重试消息"
onClick={() => retryMessage(message.id)} onClick={() => retryMessage(message.id)}
> >
Retry <span
className="message-action-icon icon-retry"
aria-hidden="true"
/>
<span>重试</span>
</button> </button>
<button <button
type="button" type="button"
aria-label="朗读消息"
title="朗读消息"
onClick={() => speakMessage(message.content)} onClick={() => speakMessage(message.content)}
> >
Read aloud <span
className="message-action-icon icon-read"
aria-hidden="true"
/>
<span>朗读</span>
</button> </button>
</div> </div>
) : null} ) : null}
@ -747,7 +800,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
type="button" type="button"
onClick={() => void stopGeneration()} onClick={() => void stopGeneration()}
> >
Stop generating 停止生成
</button> </button>
) : null} ) : null}
</div> </div>
@ -756,11 +809,16 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
}) })
)} )}
</div> </div>
{error ? <p className="chat-error">{error}</p> : null} {error ? (
<p className="chat-error" role="alert">
{error}
</p>
) : null}
<div className="chat-composer-toolbar"> <div className="chat-composer-toolbar">
<label className="file-picker"> <label className="file-picker">
<span>添加图片/文件</span> <span>添加图片/文件</span>
<input <input
className="file-picker-input"
type="file" type="file"
multiple multiple
onChange={(event) => { onChange={(event) => {
@ -776,6 +834,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
type="button" type="button"
onClick={toggleVoiceInput} onClick={toggleVoiceInput}
className={voiceListening ? "voice-button active" : "voice-button"} className={voiceListening ? "voice-button active" : "voice-button"}
aria-pressed={voiceListening}
> >
{voiceListening ? "停止录音" : "语音输入"} {voiceListening ? "停止录音" : "语音输入"}
</button> </button>
@ -814,19 +873,33 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
onChange={(event) => setDraft(event.target.value)} onChange={(event) => setDraft(event.target.value)}
placeholder={ placeholder={
selectedSlot === "companion" selectedSlot === "companion"
? "和陪伴实例说点什么…" ? "和陪伴实例说点什么…(Enter 发送,Shift+Enter 换行)"
: "向运维实例描述问题…" : "向运维实例描述问题…(Enter 发送,Shift+Enter 换行)"
} }
value={draft} value={draft}
rows={3} rows={3}
onKeyDown={(event) => {
if (
event.key !== "Enter" ||
event.shiftKey ||
event.nativeEvent.isComposing
)
return;
event.preventDefault();
void send();
}}
/> />
<button <button
className="chat-send-button"
disabled={ disabled={
(!draft.trim() && pendingAttachments.length === 0) || uploading (!draft.trim() && pendingAttachments.length === 0) || uploading
} }
type="submit" type="submit"
> >
发送 <span className="send-button-icon" aria-hidden="true">
↑
</span>
<span>发送</span>
</button> </button>
</form> </form>
</section> </section>
@ -911,6 +984,18 @@ function applyRuntimeEvents(
return next; return next;
} }
function formatSessionTime(value?: string): string {
if (!value) return "本地历史";
const date = new Date(value);
if (Number.isNaN(date.getTime())) return "本地历史";
return new Intl.DateTimeFormat("zh-CN", {
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
}).format(date);
}
function connectionStateLabel( function connectionStateLabel(
state: ConnectionRuntimeStatus["companion"]["state"], state: ConnectionRuntimeStatus["companion"]["state"],
): string { ): string {

查看文件

@ -1,13 +1,62 @@
import { Fragment, type ReactNode } from "react"; import { Fragment, useEffect, useState, type ReactNode } from "react";
import { invoke } from "@tauri-apps/api/core";
import type { ChatSlot } from "./types";
type MessageContentProps = { type MessageContentProps = {
content: string; content: string;
slot: ChatSlot;
}; };
function renderInline(text: string, keyPrefix: string): ReactNode[] { type DownloadedAttachment = {
const tokens = text.split(/(`[^`]+`|\*\*[^*]+\*\*|\[[^\]]+\]\([^)]+\))/g); mimeType?: unknown;
bytes?: unknown;
};
const emotionLabels: Record<string, string> = {
happy: "【开心】",
sad: "【难过】",
angry: "【生气】",
surprised: "【惊讶】",
confused: "【困惑】",
crying: "【哭泣】",
love: "【喜欢】",
};
function normalizeContent(content: string): string {
return content.replace(/&&([a-zA-Z_-]+)&&/g, (_, name: string) =>
emotionLabels[name.toLowerCase()] ?? "",
);
}
function renderInline(
text: string,
keyPrefix: string,
imageUrls: Record<string, string>,
): ReactNode[] {
const tokens = text.split(
/(!\[[^\]]*\]\(astrbot-attachment:\/\/[A-Za-z0-9._-]+\)|`[^`]+`|\*\*[^*]+\*\*|\[[^\]]+\]\([^)]+\))/g,
);
return tokens.map((token, index) => { return tokens.map((token, index) => {
const key = `${keyPrefix}-${index}`; const key = `${keyPrefix}-${index}`;
const image = token.match(
/^!\[([^\]]*)\]\(astrbot-attachment:\/\/([A-Za-z0-9._-]+)\)$/,
);
if (image) {
const source = imageUrls[image[2]];
return source ? (
<img
className="message-attachment-image"
key={key}
src={source}
alt={image[1] || "image"}
/>
) : (
<span className="message-attachment-placeholder" key={key}>
image loading
</span>
);
}
if (token.startsWith("`") && token.endsWith("`")) { if (token.startsWith("`") && token.endsWith("`")) {
return <code key={key}>{token.slice(1, -1)}</code>; return <code key={key}>{token.slice(1, -1)}</code>;
} }
@ -26,8 +75,65 @@ function renderInline(text: string, keyPrefix: string): ReactNode[] {
}); });
} }
export function MessageContent({ content }: MessageContentProps) { export function MessageContent({ content, slot }: MessageContentProps) {
const lines = content.replaceAll("\r\n", "\n").split("\n"); const [imageUrls, setImageUrls] = useState<Record<string, string>>({});
const attachmentIds = Array.from(
content.matchAll(
/!\[[^\]]*\]\(astrbot-attachment:\/\/([A-Za-z0-9._-]+)\)/g,
),
(match) => match[1],
);
const attachmentKey = attachmentIds.join("|");
useEffect(() => {
let cancelled = false;
const createdUrls: string[] = [];
setImageUrls({});
const ids = attachmentKey ? attachmentKey.split("|") : [];
if (!ids.length) return undefined;
void Promise.all(
ids.map(async (attachmentId) => {
try {
const result = await invoke<unknown>(
"download_connection_slot_attachment",
{ request: { slot, attachmentId } },
);
const payload = result as DownloadedAttachment;
const bytes =
payload.bytes instanceof Uint8Array
? payload.bytes
: Array.isArray(payload.bytes)
? new Uint8Array(payload.bytes.filter((item): item is number => typeof item === "number"))
: null;
if (!bytes || cancelled) return;
const blob = new Blob([bytes.buffer as ArrayBuffer], {
type:
typeof payload.mimeType === "string"
? payload.mimeType
: "application/octet-stream",
});
const url = URL.createObjectURL(blob);
createdUrls.push(url);
if (!cancelled) {
setImageUrls((current) => ({ ...current, [attachmentId]: url }));
}
} catch {
// Keep an inline placeholder when the attachment is no longer available.
}
}),
);
return () => {
cancelled = true;
createdUrls.forEach((url) => URL.revokeObjectURL(url));
};
}, [attachmentKey, slot]);
const lines = normalizeContent(content)
.replaceAll("\r\n", "\n")
.split("\n");
const blocks: ReactNode[] = []; const blocks: ReactNode[] = [];
let codeLines: string[] | null = null; let codeLines: string[] | null = null;
let codeLanguage = ""; let codeLanguage = "";
@ -38,7 +144,7 @@ export function MessageContent({ content }: MessageContentProps) {
if (!paragraph.length) return; if (!paragraph.length) return;
blocks.push( blocks.push(
<p key={`paragraph-${blocks.length}`}> <p key={`paragraph-${blocks.length}`}>
{renderInline(paragraph.join(" "), `paragraph-${blocks.length}`)} {renderInline(paragraph.join(" "), `paragraph-${blocks.length}`, imageUrls)}
</p>, </p>,
); );
paragraph = []; paragraph = [];
@ -49,7 +155,7 @@ export function MessageContent({ content }: MessageContentProps) {
<ul key={`list-${blocks.length}`}> <ul key={`list-${blocks.length}`}>
{list.map((item, index) => ( {list.map((item, index) => (
<li key={`list-${blocks.length}-${index}`}> <li key={`list-${blocks.length}-${index}`}>
{renderInline(item, `list-${blocks.length}-${index}`)} {renderInline(item, `list-${blocks.length}-${index}`, imageUrls)}
</li> </li>
))} ))}
</ul>, </ul>,
@ -92,7 +198,7 @@ export function MessageContent({ content }: MessageContentProps) {
const Heading = `h${level}` as "h1" | "h2" | "h3"; const Heading = `h${level}` as "h1" | "h2" | "h3";
blocks.push( blocks.push(
<Heading key={`heading-${index}`}> <Heading key={`heading-${index}`}>
{renderInline(heading[2], `heading-${index}`)} {renderInline(heading[2], `heading-${index}`, imageUrls)}
</Heading>, </Heading>,
); );
return; return;

查看文件

@ -56,6 +56,7 @@ export function StatusBubble() {
const companion = status.companion.state; const companion = status.companion.state;
const operations = status.operations.state; const operations = status.operations.state;
const active = companion === "connected" || operations === "connected"; const active = companion === "connected" || operations === "connected";
const statusDescription = `${slotLabel(companion, "陪伴实例")};${slotLabel(operations, "运维实例")}`;
const visibleState = quiet const visibleState = quiet
? "静默中" ? "静默中"
: active : active
@ -64,7 +65,9 @@ export function StatusBubble() {
return ( return (
<main className="status-bubble-shell" aria-label="连接状态气泡"> <main className="status-bubble-shell" aria-label="连接状态气泡">
<button <button
className={active ? "status-bubble connected" : "status-bubble"} aria-label={`打开 AstrBot Desktop,当前状态:${visibleState}`}
aria-describedby="status-bubble-description"
className={`${active ? "status-bubble connected" : "status-bubble"} status-bubble-${statusTone(companion, operations)}`}
type="button" type="button"
onClick={() => { onClick={() => {
const target = const target =
@ -82,16 +85,45 @@ export function StatusBubble() {
} }
}} }}
> >
<span className="status-bubble-orb" /> <span className="status-bubble-orb" aria-hidden="true" />
<span className="status-bubble-label">{visibleState}</span> <span className="status-bubble-label">{visibleState}</span>
{unread > 0 && !quiet ? ( {unread > 0 && !quiet ? (
<span className="status-bubble-unread">{unread}</span> <span className="status-bubble-unread">{unread}</span>
) : null} ) : null}
</button> </button>
<span id="status-bubble-description" className="sr-only" role="status">
{statusDescription}
{quiet
? ",当前处于静默时段"
: unread > 0
? `,${unread} 条未读消息`
: ""}
</span>
</main> </main>
); );
} }
function slotLabel(
state: ConnectionRuntimeStatus["companion"]["state"],
name: string,
) {
return `${name}${state === "connected" ? "在线" : stateLabel(state, state)}`;
}
function statusTone(
companion: ConnectionRuntimeStatus["companion"]["state"],
operations: ConnectionRuntimeStatus["operations"]["state"],
) {
if (companion === "connected" || operations === "connected") return "online";
if (companion === "connecting" || operations === "connecting")
return "pending";
if (companion === "authExpired" || operations === "authExpired")
return "auth";
if (companion === "serverUnavailable" || operations === "serverUnavailable")
return "error";
return "offline";
}
function stateLabel( function stateLabel(
companion: ConnectionRuntimeStatus["companion"]["state"], companion: ConnectionRuntimeStatus["companion"]["state"],
operations: ConnectionRuntimeStatus["operations"]["state"], operations: ConnectionRuntimeStatus["operations"]["state"],

查看文件

@ -0,0 +1,85 @@
import { describe, expect, it } from "vitest";
import {
chatSessionSchema,
mergeLoadedChatMessages,
storedChatMessageSchema,
} from "./types";
describe("chat persistence IPC schemas", () => {
it("accepts nullable Rust fields in stored sessions", () => {
expect(
chatSessionSchema.parse({
accountId: "local-default",
profileId: "profile-1",
slot: "companion",
serverInstanceId: "server-1",
remoteUsername: null,
sessionId: "session-1",
unreadCount: 0,
lastMessageId: null,
lastMessageAt: "2026-07-20T12:00:00Z",
}),
).toMatchObject({ sessionId: "session-1" });
});
it("accepts nullable remote usernames in stored messages", () => {
expect(
storedChatMessageSchema.parse({
accountId: "local-default",
profileId: "profile-1",
slot: "companion",
serverInstanceId: "server-1",
remoteUsername: null,
sessionId: "session-1",
messageId: "message-1",
role: "user",
content: "hello",
streaming: false,
error: false,
updatedAt: "2026-07-20T12:00:00Z",
}),
).toMatchObject({ content: "hello" });
});
it("replaces loaded session messages without duplicating optimistic users", () => {
const record = {
accountId: "local-default",
profileId: "profile-1",
slot: "companion" as const,
serverInstanceId: "server-1",
remoteUsername: null,
sessionId: "session-1",
messageId: "stored-user-1",
role: "user" as const,
content: "hello",
streaming: false,
error: false,
updatedAt: "2026-07-20T12:00:00Z",
};
const result = mergeLoadedChatMessages(
[
{
id: "local-temp-1",
sessionId: "session-1",
slot: "companion",
role: "user",
content: "hello",
},
{
id: "stored-user-1",
sessionId: "session-1",
slot: "companion",
role: "user",
content: "hello",
},
],
[record],
"companion",
"session-1",
);
expect(result).toHaveLength(1);
expect(result[0]?.id).toBe("stored-user-1");
});
});

查看文件

@ -49,10 +49,10 @@ export const chatSessionSchema = z
profileId: z.string().min(1), profileId: z.string().min(1),
slot: activeSlotKindSchema, slot: activeSlotKindSchema,
serverInstanceId: z.string().min(1), serverInstanceId: z.string().min(1),
remoteUsername: z.string().min(1).optional(), remoteUsername: z.string().min(1).nullish(),
sessionId: z.string().min(1), sessionId: z.string().min(1),
unreadCount: z.number().int().nonnegative(), unreadCount: z.number().int().nonnegative(),
lastMessageId: z.string().min(1).optional(), lastMessageId: z.string().min(1).nullish(),
lastMessageAt: z.string().min(1), lastMessageAt: z.string().min(1),
}) })
.strict(); .strict();
@ -84,7 +84,7 @@ export const storedChatMessageSchema = z
profileId: z.string().min(1), profileId: z.string().min(1),
slot: activeSlotKindSchema, slot: activeSlotKindSchema,
serverInstanceId: z.string().min(1), serverInstanceId: z.string().min(1),
remoteUsername: z.string().min(1).optional(), remoteUsername: z.string().min(1).nullish(),
sessionId: z.string().min(1), sessionId: z.string().min(1),
messageId: z.string().min(1), messageId: z.string().min(1),
role: z.enum(["user", "assistant", "system"]), role: z.enum(["user", "assistant", "system"]),
@ -95,6 +95,62 @@ export const storedChatMessageSchema = z
}) })
.strict(); .strict();
export type StoredChatMessage = z.infer<typeof storedChatMessageSchema>;
export function mergeLoadedChatMessages(
current: ChatMessage[],
records: StoredChatMessage[],
slot: ChatSlot,
sessionId: string,
): ChatMessage[] {
const sessionMessages = current.filter(
(message) => message.slot === slot && message.sessionId === sessionId,
);
const persistedUserCounts = new Map<string, number>();
for (const record of records) {
if (record.role !== "user") continue;
persistedUserCounts.set(
record.content,
(persistedUserCounts.get(record.content) ?? 0) + 1,
);
}
const optimisticMessages = sessionMessages.filter((message) => {
if (!message.id.startsWith("local-") || message.role !== "user") {
return false;
}
const count = persistedUserCounts.get(message.content) ?? 0;
if (count === 0) return true;
persistedUserCounts.set(message.content, count - 1);
return false;
});
const streamingMessages = sessionMessages.filter(
(message) => message.streaming && !message.id.startsWith("local-"),
);
const loadedMessages = records.map((record) => ({
id: record.messageId,
sessionId: record.sessionId,
slot: record.slot,
role: record.role,
content: record.content,
streaming: record.streaming,
error: record.error,
}));
const next = current
.filter(
(message) => message.slot !== slot || message.sessionId !== sessionId,
)
.concat(loadedMessages, streamingMessages, optimisticMessages);
const seen = new Set<string>();
return next.filter((message) => {
const key = message.slot + ":" + (message.sessionId ?? "") + ":" + message.id;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
export const astrbotModelOptionSchema = z.object({ export const astrbotModelOptionSchema = z.object({
id: z.string().min(1), id: z.string().min(1),
name: z.string().min(1).optional(), name: z.string().min(1).optional(),

查看文件

@ -0,0 +1,242 @@
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { useEffect, useRef, useState } from "react";
import {
boundRuntimeEventSchema,
connectionRuntimeStatusSchema,
} from "../chat/types";
import aemeathSpritesheet from "./assets/aemeath/aemeath-spritesheet.png?inline";
const AEMEATH_SPRITESHEET = aemeathSpritesheet;
const PET_TARGET_SLOT = "companion" as const;
const AEMEATH_FRAMES: Record<
"idle" | "working" | "resting" | "speaking" | "error",
number[]
> = {
idle: [0, 1, 2, 3, 4, 5],
working: [
80, 81, 82, 83, 84, 85, 86, 87, 104, 105, 106, 107, 108, 109, 110, 111,
],
resting: [48, 49, 50, 51, 52, 53],
speaking: [72, 73, 74, 75, 76, 77, 78, 79],
error: [40, 41, 42, 43, 44, 45, 46, 47],
};
export function DesktopPetView({ embedded = false }: { embedded?: boolean }) {
const [state, setState] = useState<
"idle" | "working" | "resting" | "speaking" | "error"
>("idle");
const [frameIndex, setFrameIndex] = useState(0);
const [spriteReady, setSpriteReady] = useState(false);
const [spriteError, setSpriteError] = useState<string | null>(null);
const [gameMode, setGameMode] = useState(false);
const spriteImageRef = useRef<HTMLImageElement | null>(null);
const spriteCanvasRef = useRef<HTMLCanvasElement | null>(null);
useEffect(() => {
if (embedded) return;
document.documentElement.classList.add("pet-view");
return () => document.documentElement.classList.remove("pet-view");
}, [embedded]);
const completionTimerRef = useRef<number | null>(null);
useEffect(() => {
let unlisten: (() => void) | undefined;
let unlistenRuntime: (() => void) | undefined;
void listen("pet-game-mode-toggle", () =>
setGameMode((current) => !current),
).then((cleanup) => {
unlisten = cleanup;
});
void listen<unknown>("connection-runtime-event", (event) => {
const parsed = boundRuntimeEventSchema.safeParse(event.payload);
if (!parsed.success || parsed.data.slot !== PET_TARGET_SLOT) return;
if (completionTimerRef.current !== null) {
window.clearTimeout(completionTimerRef.current);
completionTimerRef.current = null;
}
if (parsed.data.eventType === "message.delta") setState("working");
if (parsed.data.eventType === "message.proactive") setState("speaking");
if (parsed.data.eventType === "message.completed") {
setState("speaking");
completionTimerRef.current = window.setTimeout(() => {
completionTimerRef.current = null;
setState("idle");
}, 2200);
}
if (parsed.data.eventType === "error") setState("error");
}).then((cleanup) => {
unlistenRuntime = cleanup;
});
return () => {
unlisten?.();
unlistenRuntime?.();
if (completionTimerRef.current !== null) {
window.clearTimeout(completionTimerRef.current);
completionTimerRef.current = null;
}
};
}, []);
useEffect(() => {
const image = new Image();
image.onload = () => {
spriteImageRef.current = image;
setSpriteError(null);
setSpriteReady(true);
};
image.onerror = () => {
setSpriteError("????????");
};
image.src = AEMEATH_SPRITESHEET;
return () => {
image.onload = null;
};
}, []);
useEffect(() => {
let cancelled = false;
void invoke<unknown>("connection_runtime_status")
.then((value) => {
if (cancelled) return;
try {
const result = connectionRuntimeStatusSchema.parse(value);
const state = result.companion.state;
if (
state === "authExpired" ||
state === "fatalError" ||
state === "incompatible"
) {
setState("error");
} else if (
state === "syncing" ||
state === "connecting" ||
state === "authenticating"
) {
setState("working");
} else if (state === "reconnecting") {
setState("speaking");
} else if (state === "disconnected" || state === "offline") {
setState("resting");
} else {
setState("idle");
}
} catch {
setState("idle");
}
})
.catch(() => {
if (!cancelled) setState("idle");
});
return () => {
cancelled = true;
};
}, []);
useEffect(() => {
void invoke("set_pet_window_preferences", {
preferences: {
positionMode: "edge",
monitorIndex: 0,
alwaysOnTop: true,
gameMode,
},
}).catch(() => undefined);
}, [gameMode]);
useEffect(() => {
setFrameIndex(0);
const frames = AEMEATH_FRAMES[state];
const timer = window.setInterval(
() => {
setFrameIndex((current) => (current + 1) % frames.length);
},
state === "resting" ? 180 : 125,
);
return () => window.clearInterval(timer);
}, [state]);
const frame =
AEMEATH_FRAMES[state][frameIndex % AEMEATH_FRAMES[state].length];
const frameRow = Math.floor(frame / 8);
const frameColumn = frame % 8;
useEffect(() => {
const canvas = spriteCanvasRef.current;
const image = spriteImageRef.current;
if (!canvas || !image || !spriteReady) return;
const context = canvas.getContext("2d");
if (!context) {
setSpriteError("???? Canvas ?????");
return;
}
try {
context.clearRect(0, 0, 192, 208);
context.imageSmoothingEnabled = false;
context.drawImage(
image,
frameColumn * 192,
frameRow * 208,
192,
208,
0,
0,
192,
208,
);
} catch (reason) {
setSpriteError(reason instanceof Error ? reason.message : "??????");
}
}, [frameColumn, frameRow, spriteReady]);
return (
<main
className={`pet-window pet-window-${state}${gameMode ? " pet-window-game" : ""}${embedded ? " pet-window-embedded" : ""}`}
aria-label="AstrBot ??"
data-tauri-drag-region={!embedded ? "true" : undefined}
onMouseDown={(event) => {
if (embedded || event.button !== 0) return;
void getCurrentWindow().startDragging();
}}
onContextMenu={(event) => {
event.preventDefault();
void invoke("show_pet_context_menu");
}}
>
<div
className={`aemeath-pet-frame aemeath-pet-${state}`}
role="img"
aria-label={`桌宠状态:${state}`}
>
<canvas
ref={spriteCanvasRef}
className="aemeath-pet-sprite"
width={192}
height={208}
role="img"
aria-label={`pet-${state}`}
/>
</div>
{spriteError ? (
<span className="pet-render-error">{spriteError}</span>
) : null}
{!spriteReady && !spriteError ? (
<span className="pet-render-loading">Loading pet...</span>
) : null}
<span className="pet-window-status">
{state === "working"
? "正在写写画画"
: state === "resting"
? "休息中"
: state === "speaking"
? "正在回应"
: state === "error"
? "需要重新登录或检查连接"
: "陪伴中"}
</span>
</main>
);
}

查看文件

@ -12,14 +12,18 @@ export function PetPackImporter() {
setManifest(null); setManifest(null);
setError(null); setError(null);
if (!file.name.toLowerCase().endsWith(".json") || file.size > 256 * 1024) { if (!file.name.toLowerCase().endsWith(".json") || file.size > 256 * 1024) {
setError("文件必须是 256 KiB 以内的 JSON manifest。若要导入图片,请先放入素材包目录。 "); setError(
"文件必须是 256 KiB 以内的 JSON manifest。若要导入图片,请先放入素材包目录。 ",
);
return; return;
} }
try { try {
const parsed = petPackManifestSchema.parse(JSON.parse(await file.text())); const parsed = petPackManifestSchema.parse(JSON.parse(await file.text()));
setManifest(parsed); setManifest(parsed);
} catch (reason) { } catch (reason) {
setError(reason instanceof Error ? reason.message : "无法读取桌宠 manifest。 "); setError(
reason instanceof Error ? reason.message : "无法读取桌宠 manifest。 ",
);
} }
}; };
@ -42,7 +46,11 @@ export function PetPackImporter() {
}} }}
/> />
{fileName ? <p className="form-note">已选择:{fileName}</p> : null} {fileName ? <p className="form-note">已选择:{fileName}</p> : null}
{error ? <p className="error-banner">{error}</p> : null} {error ? (
<p className="error-banner" role="alert">
{error}
</p>
) : null}
{manifest ? ( {manifest ? (
<div className="pet-pack-preview"> <div className="pet-pack-preview">
<strong>{manifest.name}</strong> <strong>{manifest.name}</strong>
@ -52,7 +60,12 @@ export function PetPackImporter() {
</span> </span>
<span>{manifest.animations.length} 个动作片段</span> <span>{manifest.animations.length} 个动作片段</span>
<span> <span>
{manifest.animations.filter((animation) => animation.movement !== "stationary").length} 个移动动作 {
manifest.animations.filter(
(animation) => animation.movement !== "stationary",
).length
}{" "}
个移动动作
</span> </span>
</div> </div>
) : null} ) : null}

查看文件

@ -1,11 +1,26 @@
import { useState } from "react"; import { useState } from "react";
import { invoke } from "@tauri-apps/api/core"; import { invoke } from "@tauri-apps/api/core";
import type { AuthenticationType, ConnectionProfile } from "../../types/profile"; import type {
AuthenticationType,
ConnectionProfile,
} from "../../types/profile";
interface CredentialEnrollmentResult { profileId: string; credentialReference: string; authenticationType: AuthenticationType; } interface CredentialEnrollmentResult {
interface JwtLoginResult { profileId: string; credentialReference: string; dashboardUsername: string; authenticationType: "jwt"; } profileId: string;
interface Props { profile: ConnectionProfile; onChanged: () => Promise<void> | void; } credentialReference: string;
authenticationType: AuthenticationType;
}
interface JwtLoginResult {
profileId: string;
credentialReference: string;
dashboardUsername: string;
authenticationType: "jwt";
}
interface Props {
profile: ConnectionProfile;
onChanged: () => Promise<void> | void;
}
export function CredentialEnrollmentCard({ profile, onChanged }: Props) { export function CredentialEnrollmentCard({ profile, onChanged }: Props) {
const [secret, setSecret] = useState(""); const [secret, setSecret] = useState("");
@ -17,51 +32,163 @@ export function CredentialEnrollmentCard({ profile, onChanged }: Props) {
const [message, setMessage] = useState<string | null>(null); const [message, setMessage] = useState<string | null>(null);
async function enroll() { async function enroll() {
setBusy(true); setMessage(null); setBusy(true);
setMessage(null);
try { try {
const result = await invoke<CredentialEnrollmentResult>("enroll_profile_credential", { request: { profileId: profile.id, authenticationType: profile.authenticationType, secret, username: remoteId.trim() || undefined } }); const result = await invoke<CredentialEnrollmentResult>(
setSecret(""); setMessage(`已登记凭据引用 ${result.credentialReference}`); await onChanged(); "enroll_profile_credential",
} catch (error) { setMessage(error instanceof Error ? error.message : "凭据登记失败。"); } {
finally { setBusy(false); } request: {
profileId: profile.id,
authenticationType: profile.authenticationType,
secret,
username: remoteId.trim() || undefined,
},
},
);
setSecret("");
setMessage(`已登记凭据引用 ${result.credentialReference}`);
await onChanged();
} catch (error) {
setMessage(error instanceof Error ? error.message : "凭据登记失败。");
} finally {
setBusy(false);
}
} }
async function loginJwt() { async function loginJwt() {
setBusy(true); setMessage(null); setBusy(true);
setMessage(null);
try { try {
const result = await invoke<JwtLoginResult>("login_profile_jwt", { request: { profileId: profile.id, username: dashboardUsername.trim(), password: dashboardPassword, totp: totp.trim() || undefined } }); const result = await invoke<JwtLoginResult>("login_profile_jwt", {
setDashboardPassword(""); setTotp(""); setMessage(`JWT 登录成功,凭据引用 ${result.credentialReference}`); await onChanged(); request: {
} catch (error) { setMessage(error instanceof Error ? error.message : "JWT 登录失败。"); } profileId: profile.id,
finally { setBusy(false); } username: dashboardUsername.trim(),
password: dashboardPassword,
totp: totp.trim() || undefined,
},
});
setDashboardPassword("");
setTotp("");
setMessage(`JWT 登录成功,凭据引用 ${result.credentialReference}`);
await onChanged();
} catch (error) {
setMessage(error instanceof Error ? error.message : "JWT 登录失败。");
} finally {
setBusy(false);
}
} }
async function clearCredential() { async function clearCredential() {
setBusy(true); setMessage(null); setBusy(true);
try { await invoke("clear_profile_credential", { profileId: profile.id }); setMessage("已清除凭据引用"); await onChanged(); } setMessage(null);
catch (error) { setMessage(error instanceof Error ? error.message : "清除凭据失败。"); } try {
finally { setBusy(false); } await invoke("clear_profile_credential", { profileId: profile.id });
setMessage("已清除凭据引用");
await onChanged();
} catch (error) {
setMessage(error instanceof Error ? error.message : "清除凭据失败。");
} finally {
setBusy(false);
}
} }
return ( return (
<section className="credential-card" aria-label={`凭据登记 ${profile.displayName}`}> <section
className="credential-card"
aria-label={`凭据登记 ${profile.displayName}`}
>
<h4>安全凭据登记</h4> <h4>安全凭据登记</h4>
<p>凭据只通过一次性 IPC 写入 Windows Credential Manager,不会进入 React 持久状态。</p> <p className="form-note">
<label>远端 ID(英文数字)<input value={remoteId} onChange={(event) => setRemoteId(event.target.value)} disabled={busy} placeholder="yokiiro01" /></label> 凭据只通过一次性 IPC 写入 Windows Credential Manager,不会进入 React
持久状态。
</p>
<label>
<span>远端 ID(英文数字)</span>
<input
value={remoteId}
onChange={(event) => setRemoteId(event.target.value)}
disabled={busy}
placeholder="yokiiro01"
/>
</label>
{profile.authenticationType === "jwt" ? ( {profile.authenticationType === "jwt" ? (
<> <>
<label>AstrBot Dashboard 用户名<input value={dashboardUsername} onChange={(event) => setDashboardUsername(event.target.value)} disabled={busy} autoComplete="username" /></label> <label>
<label>Dashboard 密码<input type="password" value={dashboardPassword} onChange={(event) => setDashboardPassword(event.target.value)} disabled={busy} autoComplete="current-password" /></label> <span>AstrBot Dashboard 用户名</span>
<label>TOTP(可选)<input value={totp} onChange={(event) => setTotp(event.target.value)} disabled={busy} inputMode="numeric" /></label> <input
<button type="button" disabled={busy || !dashboardUsername.trim() || !dashboardPassword} onClick={() => void loginJwt()}>登录 AstrBot Dashboard</button> value={dashboardUsername}
onChange={(event) => setDashboardUsername(event.target.value)}
disabled={busy}
autoComplete="username"
/>
</label>
<label>
<span>Dashboard 密码</span>
<input
type="password"
value={dashboardPassword}
onChange={(event) => setDashboardPassword(event.target.value)}
disabled={busy}
autoComplete="current-password"
/>
</label>
<label>
<span>TOTP(可选)</span>
<input
value={totp}
onChange={(event) => setTotp(event.target.value)}
disabled={busy}
inputMode="numeric"
/>
</label>
<button
type="button"
disabled={busy || !dashboardUsername.trim() || !dashboardPassword}
onClick={() => void loginJwt()}
>
{busy ? "登录中…" : "登录 AstrBot Dashboard"}
</button>
</> </>
) : ( ) : (
<> <>
<label>API Key / Token(一次性)<input type="password" value={secret} onChange={(event) => setSecret(event.target.value)} disabled={busy} autoComplete="off" /></label> <label>
<button type="button" disabled={busy || !secret.trim()} onClick={() => void enroll()}>登记凭据</button> <span>API Key / Token(一次性)</span>
<input
type="password"
value={secret}
onChange={(event) => setSecret(event.target.value)}
disabled={busy}
autoComplete="off"
/>
</label>
<button
type="button"
disabled={busy || !secret.trim()}
onClick={() => void enroll()}
>
{busy ? "登记中…" : "登记凭据"}
</button>
</> </>
)} )}
<button type="button" disabled={busy || !profile.credentialReference} onClick={() => void clearCredential()}>清除凭据</button> <button
{profile.credentialReference ? <p>当前引用:{profile.credentialReference}</p> : <p>尚未登记凭据</p>} type="button"
{message ? <p role="status">{message}</p> : null} className="button-danger"
disabled={busy || !profile.credentialReference}
onClick={() => void clearCredential()}
>
清除凭据
</button>
<p className="form-note">
{profile.credentialReference
? `当前引用:${profile.credentialReference}`
: "尚未登记凭据"}
</p>
{message ? (
<p className="notice-banner" role="status" aria-live="polite">
{message}
</p>
) : null}
</section> </section>
); );
} }

277
src/pages/SettingsPages.tsx 普通文件
查看文件

@ -0,0 +1,277 @@
import { invoke } from "@tauri-apps/api/core";
import { useState } from "react";
import type { BootstrapStatus } from "../types/bootstrap";
export type SettingsChatSlot = "companion" | "operations";
export function DesktopBehaviorPage({
bubbleTarget,
quickTarget,
onBubbleTargetChange,
onQuickTargetChange,
onOpenQuickChat,
}: {
bubbleTarget: "main" | "quick";
quickTarget: SettingsChatSlot;
onBubbleTargetChange: (value: "main" | "quick") => void;
onQuickTargetChange: (value: SettingsChatSlot) => void;
onOpenQuickChat: () => void;
}) {
const [quietHours, setQuietHours] = useState(
() => localStorage.getItem("astrbot.quietHours") ?? "off",
);
return (
<div className="page-stack">
<section className="settings-grid">
<SettingCard
title="快速聊天"
description="设置气泡或快捷入口打开哪个实例。"
>
<label>
<span>默认目标槽位</span>
<select
value={quickTarget}
onChange={(event) =>
onQuickTargetChange(event.target.value as SettingsChatSlot)
}
>
<option value="companion">陪伴实例</option>
<option value="operations">运维实例</option>
</select>
</label>
<button type="button" onClick={onOpenQuickChat}>
立即打开快速聊天
</button>
</SettingCard>
<SettingCard
title="状态气泡"
description="气泡显示连接状态,并根据这里的设置响应点击。"
>
<label>
<span>点击气泡时</span>
<select
value={bubbleTarget}
onChange={(event) =>
onBubbleTargetChange(event.target.value as "main" | "quick")
}
>
<option value="main">打开主界面</option>
<option value="quick">打开快速聊天</option>
</select>
</label>
<div className="status-preview">
<span className="connection-dot" />
气泡状态显示已预留
</div>
</SettingCard>
</section>
<section className="info-card">
<span className="section-kicker">Desktop companion</span>
<h2>后续桌面能力</h2>
<div className="feature-list">
<span>托盘与单实例</span>
<span>窗口置顶开关</span>
<span>多显示器策略</span>
<span>游戏模式靠边活动</span>
</div>
<p>
这些能力先保留为独立设置区,后续接入 Rust
本机能力层,不会与聊天状态混在一起。
</p>
</section>
<section className="settings-grid">
<SettingCard
title="主动消息静默时段"
description="静默时段只抑制气泡提醒,不会删除消息,也不会影响聊天未读数。"
>
<select
value={quietHours}
onChange={(event) => {
const next = event.target.value;
setQuietHours(next);
localStorage.setItem("astrbot.quietHours", next);
}}
>
<option value="off">关闭</option>
<option value="night">每天 22:00–07:00</option>
</select>
</SettingCard>
</section>
</div>
);
}
function DiagnosticsTools() {
const [result, setResult] = useState("");
const [busy, setBusy] = useState(false);
const [host, setHost] = useState("127.0.0.1");
const [port, setPort] = useState("80");
const [processId, setProcessId] = useState("0");
const run = async (command: string, request?: Record<string, unknown>) => {
setBusy(true);
try {
const value = await invoke<unknown>(
command,
request ? { request } : undefined,
);
setResult(JSON.stringify(value, null, 2));
} catch (reason) {
setResult(reason instanceof Error ? reason.message : String(reason));
} finally {
setBusy(false);
}
};
return (
<>
<section className="settings-grid">
<SettingCard
title="前台窗口"
description="读取当前前台窗口的标题、类名和进程身份。"
>
<button
type="button"
disabled={busy}
onClick={() => void run("inspect_foreground_window")}
>
{busy ? "检查中…" : "检查前台窗口"}
</button>
</SettingCard>
<SettingCard
title="网络连通性"
description="只检查一个明确的主机和端口,不执行扫描。"
>
<label className="diagnostic-field">
<span>主机</span>
<input
value={host}
onChange={(event) => setHost(event.target.value)}
aria-label="主机"
/>
</label>
<label className="diagnostic-field">
<span>端口</span>
<input
value={port}
onChange={(event) => setPort(event.target.value)}
aria-label="端口"
inputMode="numeric"
/>
</label>
<button
type="button"
disabled={busy}
onClick={() =>
void run("check_network_target", {
host,
port: Number(port),
timeoutSeconds: 3,
})
}
>
{busy ? "检查中…" : "检查端口"}
</button>
</SettingCard>
<SettingCard
title="指定进程"
description="输入进程 ID 后读取有限的进程摘要,不枚举全部进程。"
>
<label className="diagnostic-field">
<span>进程 ID</span>
<input
value={processId}
onChange={(event) => setProcessId(event.target.value)}
aria-label="进程 ID"
inputMode="numeric"
/>
</label>
<button
type="button"
disabled={busy}
onClick={() =>
void run("inspect_process", { processId: Number(processId) })
}
>
{busy ? "检查中…" : "检查进程"}
</button>
</SettingCard>
</section>
{result ? (
<pre className="diagnostic-result" role="status" aria-live="polite">
{result}
</pre>
) : null}
</>
);
}
export function DiagnosticsPage({
status,
onRefresh,
}: {
status: BootstrapStatus;
onRefresh: () => void;
}) {
return (
<div className="page-stack">
<section className="status-grid" aria-label="bootstrap status">
<StatusCard label="Rust Core" value={status.rustCore} />
<StatusCard label="Platform" value={status.platform} />
<StatusCard label="App Version" value={status.appVersion} />
<StatusCard label="Protocol" value={status.protocolVersion} />
<StatusCard
label="Database Schema"
value={String(status.databaseSchemaVersion)}
/>
</section>
<DiagnosticsTools />
<section className="boundaries">
<span className="section-kicker">Security boundary</span>
<h2>本机能力保持可审计</h2>
<ul>
<li>凭据只在 Rust 与 Windows 安全存储之间流动。</li>
<li>两个 REST/SSE 槽位保持独立状态、会话、消息与未读数。</li>
<li>本机操作必须经过白名单、角色、路径和用户授权。</li>
<li>文件事务默认保留源文件,不静默覆盖目标。</li>
</ul>
</section>
<button type="button" onClick={onRefresh}>
刷新 IPC 状态
</button>
</div>
);
}
export function SettingCard({
title,
description,
children,
}: {
title: string;
description: string;
children: React.ReactNode;
}) {
return (
<section className="setting-card">
<div>
<span className="section-kicker">Settings</span>
<h2>{title}</h2>
<p>{description}</p>
</div>
<div className="setting-card-controls">{children}</div>
</section>
);
}
interface StatusCardProps {
label: string;
value: string;
}
function StatusCard({ label, value }: StatusCardProps) {
return (
<article className="status-card">
<span>{label}</span>
<strong>{value}</strong>
</article>
);
}

文件差异内容过多而无法显示 加载差异

查看文件

@ -1,4 +1,4 @@
import { expect, test } from "@playwright/test"; import { expect, test } from "@playwright/test";
test("renders the bootstrap shell and safe browser fallback", async ({ test("renders the bootstrap shell and safe browser fallback", async ({
page, page,
@ -6,19 +6,17 @@ test("renders the bootstrap shell and safe browser fallback", async ({
await page.goto("/"); await page.goto("/");
await expect( await expect(
page.getByRole("heading", { name: "AstrBot Desktop" }), page.getByText("AstrBot Desktop", { exact: true }).first(),
).toBeVisible(); ).toBeVisible();
await expect(page.getByText("desktop-v1alpha1")).toBeVisible();
await expect( await expect(
page.getByText("IPC unavailable:", { exact: false }), page.getByRole("heading", { name: "统一聊天运行时" }),
).toBeVisible(); ).toBeVisible();
await expect(
page.getByText("IPC 暂不可用:", { exact: false }),
).toBeVisible();
await page.getByRole("button", { name: "◎ 连接 实例与槽位管理" }).click();
await expect( await expect(
page.getByRole("heading", { name: "连接 Profile" }), page.getByRole("heading", { name: "连接 Profile" }),
).toBeVisible(); ).toBeVisible();
await expect(
page.getByText("Profile storage unavailable:", { exact: false }),
).toBeVisible();
await expect(
page.getByRole("button", { name: "重新检查 IPC" }),
).toBeEnabled();
}); });

43
tests/e2e/ui-polish.spec.ts 普通文件
查看文件

@ -0,0 +1,43 @@
import { expect, test } from "@playwright/test";
const viewports = [
{ width: 1280, height: 720 },
{ width: 1024, height: 720 },
{ width: 680, height: 720 },
];
for (const viewport of viewports) {
test(`keeps the desktop shell usable at ${viewport.width}px`, async ({
page,
}) => {
await page.setViewportSize(viewport);
await page.goto("/");
await expect(
page.getByText("AstrBot Desktop", { exact: true }).first(),
).toBeVisible();
await expect(page.getByRole("button", { name: /⌁ 聊天/ })).toBeVisible();
const dimensions = (await page.evaluate(
"({ clientWidth: document.documentElement.clientWidth, scrollWidth: document.documentElement.scrollWidth })",
)) as { clientWidth: number; scrollWidth: number };
expect(dimensions.scrollWidth).toBeLessThanOrEqual(
dimensions.clientWidth + 1,
);
});
}
test("keeps page navigation and diagnostic fields accessible", async ({
page,
}) => {
await page.goto("/");
await page.getByRole("button", { name: /诊断与设置/ }).click();
await expect(page.getByText("Rust Core")).toBeVisible();
await expect(page.getByLabel("主机")).toBeVisible();
await expect(page.getByLabel("端口")).toBeVisible();
await expect(page.getByLabel("进程 ID")).toBeVisible();
await page.keyboard.press("Tab");
await expect(page.locator(":focus")).toBeVisible();
});