比较提交
没有共同的提交。d100da324dde2553b28bc187cef944f822e8d190 和 ea332257acd0783140ee10607d1186e7f8c0825c 的历史完全不同。
d100da324d
...
ea332257ac
共有 23 个文件被更改,包括 666 次插入 和 2786 次删除
|
|
@ -213,11 +213,6 @@ pub fn parse_astrbot_sse_line(line: &str) -> Result<AstrBotSseUnit, AstrBotMapEr
|
|||
}
|
||||
|
||||
/// 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)]
|
||||
pub struct AstrBotStreamMapper {
|
||||
server_instance_id: String,
|
||||
|
|
@ -227,7 +222,6 @@ pub struct AstrBotStreamMapper {
|
|||
delta_index: u32,
|
||||
sequence: u64,
|
||||
saw_assistant_delta: bool,
|
||||
pending_media: Option<PendingMedia>,
|
||||
}
|
||||
|
||||
impl AstrBotStreamMapper {
|
||||
|
|
@ -271,7 +265,6 @@ impl AstrBotStreamMapper {
|
|||
}
|
||||
"user_message_saved" => Vec::new(),
|
||||
"plain" => self.map_plain(frame),
|
||||
"image" | "record" | "file" | "video" => self.map_media(frame),
|
||||
"complete" => self.map_complete(frame),
|
||||
"agent_stats" => {
|
||||
let detail = frame.data.to_string();
|
||||
|
|
@ -307,51 +300,11 @@ impl AstrBotStreamMapper {
|
|||
));
|
||||
events
|
||||
}
|
||||
"attachment_saved" => self.map_attachment_saved(frame),
|
||||
"attachment_saved" => 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!(""))
|
||||
}
|
||||
|
||||
fn map_plain(&mut self, frame: AstrBotStreamFrame) -> Vec<GatewayEvent> {
|
||||
let chunk = text_from_value(&frame.data).unwrap_or_default();
|
||||
if chunk.is_empty() && frame.streaming.unwrap_or(false) {
|
||||
|
|
@ -611,28 +564,6 @@ 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, "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derives_stable_instance_ids() {
|
||||
let a = derive_astrbot_server_instance_id("http://192.168.31.210:26285/");
|
||||
|
|
|
|||
|
|
@ -308,40 +308,3 @@ 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.
|
||||
- Updated frontend test mocks for runtime status schema changes.
|
||||
- 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.
|
||||
|
|
|
|||
|
|
@ -1,62 +0,0 @@
|
|||
# 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。
|
||||
|
|
@ -1,65 +0,0 @@
|
|||
# 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,7 +662,6 @@ pub fn run() {
|
|||
networking::commands::connection_slot_sessions,
|
||||
networking::commands::switch_connection_slot_session,
|
||||
networking::commands::upload_connection_slot_file,
|
||||
networking::commands::download_connection_slot_attachment,
|
||||
networking::commands::cancel_connection_slot_message,
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ use desktop_protocol::{
|
|||
derive_astrbot_server_instance_id,
|
||||
};
|
||||
use futures_util::StreamExt;
|
||||
use reqwest::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE, HeaderMap, HeaderValue};
|
||||
use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, HeaderValue};
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
use serde_json::{Value, json};
|
||||
use thiserror::Error;
|
||||
|
|
@ -349,46 +349,6 @@ 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(
|
||||
&self,
|
||||
message: &str,
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
// IPC wrappers for dual-slot runtime. Secrets never leave Rust.
|
||||
use desktop_protocol::TransportKind;
|
||||
use secrecy::SecretString;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
use tauri::State;
|
||||
use tracing::{info, warn};
|
||||
|
|
@ -46,20 +46,6 @@ pub struct SlotFileUploadRequest {
|
|||
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)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct SlotCapabilitiesRequest {
|
||||
|
|
@ -106,32 +92,6 @@ 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]
|
||||
pub async fn connection_runtime_status(
|
||||
runtime: State<'_, DualSlotRuntime>,
|
||||
|
|
@ -174,15 +134,12 @@ pub async fn auto_connect_configured_slots(
|
|||
};
|
||||
|
||||
match runtime.activate_slot(activation).await {
|
||||
Ok(snapshot) => {
|
||||
persist_session_identity(database, &snapshot);
|
||||
info!(
|
||||
Ok(snapshot) => info!(
|
||||
profile_id = %profile_id,
|
||||
slot = ?slot,
|
||||
state = ?snapshot.state,
|
||||
"startup auto-connect completed"
|
||||
);
|
||||
}
|
||||
),
|
||||
Err(error) => warn!(
|
||||
profile_id = %profile_id,
|
||||
slot = ?slot,
|
||||
|
|
@ -573,15 +530,12 @@ pub async fn connection_slot_sessions(
|
|||
|
||||
#[tauri::command]
|
||||
pub async fn switch_connection_slot_session(
|
||||
database: State<'_, ApplicationDatabase>,
|
||||
runtime: State<'_, DualSlotRuntime>,
|
||||
request: SwitchChatSessionRequest,
|
||||
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
|
||||
let snapshot = runtime
|
||||
runtime
|
||||
.switch_slot_session(request.slot, request.session_id)
|
||||
.await?;
|
||||
persist_session_identity(&database, &snapshot);
|
||||
Ok(snapshot)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
|
|
@ -592,17 +546,6 @@ pub async fn connection_slot_capabilities(
|
|||
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]
|
||||
pub async fn upload_connection_slot_file(
|
||||
runtime: State<'_, DualSlotRuntime>,
|
||||
|
|
@ -684,8 +627,5 @@ pub async fn send_connection_slot_message(
|
|||
false,
|
||||
);
|
||||
}
|
||||
if let Ok(snapshot) = &result {
|
||||
persist_session_identity(&database, snapshot);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,11 +6,11 @@ mod runtime;
|
|||
|
||||
pub use astrbot_client::{AstrBotClient, AstrBotClientConfig, AstrBotClientError};
|
||||
pub use commands::{
|
||||
DisconnectConnectionSlotRequest, DownloadConnectionSlotAttachmentRequest,
|
||||
DrainConnectionRuntimeEventsRequest, ListChatSessionsRequest, MarkChatSessionReadRequest,
|
||||
ProbeConnectionSlotRequest, SendConnectionSlotMessageRequest, auto_connect_configured_slots,
|
||||
cancel_connection_slot_message, connection_runtime_status, disconnect_connection_slot,
|
||||
drain_connection_runtime_events, probe_connection_slot, send_connection_slot_message,
|
||||
DisconnectConnectionSlotRequest, DrainConnectionRuntimeEventsRequest, ListChatSessionsRequest,
|
||||
MarkChatSessionReadRequest, ProbeConnectionSlotRequest, SendConnectionSlotMessageRequest,
|
||||
auto_connect_configured_slots, cancel_connection_slot_message, connection_runtime_status,
|
||||
disconnect_connection_slot, drain_connection_runtime_events, probe_connection_slot,
|
||||
send_connection_slot_message,
|
||||
};
|
||||
pub use gateway_client::{BoundGatewayEvent, GatewayClient, GatewayClientConfig, GatewayError};
|
||||
pub use manager::{DualConnectionManager, SlotKind};
|
||||
|
|
|
|||
|
|
@ -502,33 +502,6 @@ impl DualSlotRuntime {
|
|||
.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(
|
||||
&self,
|
||||
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 { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
|
|
@ -46,13 +46,12 @@ const emptyPolicy: ConnectionPolicyStatus = {
|
|||
duplicateServerInstanceWarnings: [],
|
||||
};
|
||||
|
||||
async function openConnectionsPage() {
|
||||
fireEvent.click(screen.getByRole("button", { name: /◎连接/ }));
|
||||
await screen.findByRole("heading", { level: 2 }, { timeout: 5000 });
|
||||
function openConnectionsPage() {
|
||||
fireEvent.click(screen.getByRole("button", { name: /连接/ }));
|
||||
}
|
||||
|
||||
function openDiagnosticsPage() {
|
||||
fireEvent.click(screen.getByRole("button", { name: /⚙诊断与设置/ }));
|
||||
fireEvent.click(screen.getByRole("button", { name: /诊断与设置/ }));
|
||||
}
|
||||
|
||||
function mockBaseCommands(options?: {
|
||||
|
|
@ -141,7 +140,7 @@ describe("App", () => {
|
|||
openDiagnosticsPage();
|
||||
expect(await screen.findByText("ready")).toBeInTheDocument();
|
||||
expect(screen.getByText("desktop-v1alpha1")).toBeInTheDocument();
|
||||
await openConnectionsPage();
|
||||
openConnectionsPage();
|
||||
expect(screen.getByText("连接 Profile")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
|
@ -224,7 +223,7 @@ describe("App", () => {
|
|||
vi.spyOn(window, "confirm").mockReturnValue(true);
|
||||
|
||||
render(<App />);
|
||||
await openConnectionsPage();
|
||||
openConnectionsPage();
|
||||
expect(await screen.findByText("尚未保存 Profile。")).toBeInTheDocument();
|
||||
|
||||
fireEvent.change(screen.getByLabelText("显示名称"), {
|
||||
|
|
@ -311,7 +310,7 @@ describe("App", () => {
|
|||
mockBaseCommands({ profiles });
|
||||
|
||||
render(<App />);
|
||||
await openConnectionsPage();
|
||||
openConnectionsPage();
|
||||
|
||||
fireEvent.change(await screen.findByLabelText("陪伴 Profile"), {
|
||||
target: { value: profiles[0].id },
|
||||
|
|
@ -365,7 +364,7 @@ describe("App", () => {
|
|||
});
|
||||
|
||||
render(<App />);
|
||||
await openConnectionsPage();
|
||||
openConnectionsPage();
|
||||
expect(await screen.findByText("尚未保存 Profile。")).toBeInTheDocument();
|
||||
|
||||
fireEvent.change(screen.getByLabelText("显示名称"), {
|
||||
|
|
@ -466,7 +465,7 @@ describe("App", () => {
|
|||
});
|
||||
|
||||
render(<App />);
|
||||
await openConnectionsPage();
|
||||
openConnectionsPage();
|
||||
|
||||
expect(
|
||||
await screen.findByLabelText("重复服务器实例提示"),
|
||||
|
|
|
|||
564
src/App.tsx
564
src/App.tsx
|
|
@ -1,42 +1,17 @@
|
|||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||
import {
|
||||
lazy,
|
||||
Suspense,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { ChatPanel } from "./features/chat/ChatPanel";
|
||||
import { StatusBubble } from "./features/chat/StatusBubble";
|
||||
const ProfileManager = lazy(() =>
|
||||
import("./features/profiles/ProfileManager").then(({ ProfileManager }) => ({
|
||||
default: ProfileManager,
|
||||
})),
|
||||
);
|
||||
const PetPackImporter = lazy(() =>
|
||||
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 { ProfileManager } from "./features/profiles/ProfileManager";
|
||||
import { PetPackImporter } from "./features/pet/PetPackImporter";
|
||||
import {
|
||||
boundRuntimeEventSchema,
|
||||
connectionRuntimeStatusSchema,
|
||||
} from "./features/chat/types";
|
||||
import aemeathSpritesheet from "./features/pet/assets/aemeath/aemeath-spritesheet.png?inline";
|
||||
import { bootstrapStatusSchema, type BootstrapStatus } from "./types/bootstrap";
|
||||
|
||||
type PageKey = "chat" | "connections" | "desktop" | "pet" | "diagnostics";
|
||||
|
|
@ -52,6 +27,22 @@ const initialStatus: BootstrapStatus = {
|
|||
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 }> =
|
||||
[
|
||||
{ key: "chat", label: "聊天", description: "陪伴与运维对话" },
|
||||
|
|
@ -188,12 +179,7 @@ export function App() {
|
|||
}
|
||||
>
|
||||
{page === "chat" ? null : <PageHeader page={page} />}
|
||||
{error ? (
|
||||
<p className="error-banner" role="alert">
|
||||
IPC 暂不可用:{error}
|
||||
</p>
|
||||
) : null}
|
||||
<Suspense fallback={<PageLoading />}>
|
||||
{error ? <p className="error-banner">IPC 暂不可用:{error}</p> : null}
|
||||
{page === "chat" ? <ChatPage /> : null}
|
||||
{page === "connections" ? <ProfileManager /> : null}
|
||||
{page === "desktop" ? (
|
||||
|
|
@ -228,14 +214,9 @@ export function App() {
|
|||
onRefresh={() => void refreshStatus()}
|
||||
/>
|
||||
) : null}
|
||||
</Suspense>
|
||||
</section>
|
||||
</div>
|
||||
{petDisplayMode === "app-ui" ? (
|
||||
<Suspense fallback={null}>
|
||||
<InAppPetOverlay />
|
||||
</Suspense>
|
||||
) : null}
|
||||
{petDisplayMode === "app-ui" ? <InAppPetOverlay /> : null}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
|
@ -274,14 +255,7 @@ function WindowChrome({
|
|||
data-tauri-drag-region
|
||||
onDoubleClick={() => void toggleMaximize()}
|
||||
onMouseDown={(event) => {
|
||||
if (
|
||||
event.button === 0 &&
|
||||
!(event.target as HTMLElement).closest(
|
||||
'[data-tauri-drag-region="false"]',
|
||||
)
|
||||
) {
|
||||
void currentWindow?.startDragging();
|
||||
}
|
||||
if (event.button === 0) void currentWindow?.startDragging();
|
||||
}}
|
||||
>
|
||||
<span className="window-chrome-title">AstrBot Desktop</span>
|
||||
|
|
@ -349,9 +323,9 @@ function InAppPetOverlay() {
|
|||
);
|
||||
return saved && typeof saved.x === "number" && typeof saved.y === "number"
|
||||
? saved
|
||||
: { x: window.innerWidth >= 720 ? 280 : 24, y: 96 };
|
||||
: { x: 24, y: 96 };
|
||||
} catch {
|
||||
return { x: window.innerWidth >= 720 ? 280 : 24, y: 96 };
|
||||
return { x: 24, y: 96 };
|
||||
}
|
||||
});
|
||||
const dragRef = useRef<{
|
||||
|
|
@ -360,34 +334,15 @@ function InAppPetOverlay() {
|
|||
offsetY: number;
|
||||
} | null>(null);
|
||||
|
||||
const clampPosition = useCallback((x: number, y: number) => {
|
||||
const safeLeft = window.innerWidth >= 720 ? 248 : 0;
|
||||
const maxX = Math.max(safeLeft, window.innerWidth - 188);
|
||||
return {
|
||||
x: Math.max(safeLeft, Math.min(x, maxX)),
|
||||
const savePosition = (x: number, y: number) => {
|
||||
const next = {
|
||||
x: Math.max(0, Math.min(x, window.innerWidth - 188)),
|
||||
y: Math.max(0, Math.min(y, window.innerHeight - 226)),
|
||||
};
|
||||
}, []);
|
||||
|
||||
const savePosition = (x: number, y: number) => {
|
||||
const next = clampPosition(x, y);
|
||||
setPosition(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(() => {
|
||||
let unlisten: (() => void) | undefined;
|
||||
void listen("pet-hide-requested", () => setVisible(false)).then(
|
||||
|
|
@ -445,14 +400,6 @@ function navIcon(page: PageKey) {
|
|||
}[page];
|
||||
}
|
||||
|
||||
function PageLoading() {
|
||||
return (
|
||||
<p className="loading-state" role="status" aria-live="polite">
|
||||
Loading?
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
function PageHeader({ page }: { page: PageKey }) {
|
||||
const current = navigation.find((item) => item.key === page) ?? navigation[0];
|
||||
return (
|
||||
|
|
@ -480,6 +427,103 @@ 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({
|
||||
displayMode,
|
||||
onDisplayModeChange,
|
||||
|
|
@ -647,6 +691,343 @@ 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({
|
||||
title,
|
||||
description,
|
||||
|
|
@ -667,3 +1048,16 @@ function SettingCard({
|
|||
</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,8 +13,6 @@ import {
|
|||
type AstrBotAttachment,
|
||||
type AstrBotCapabilitySnapshot,
|
||||
type BoundRuntimeEvent,
|
||||
type ChatSession,
|
||||
mergeLoadedChatMessages,
|
||||
remoteChatSessionSchema,
|
||||
type ChatMessage,
|
||||
type ChatSlot,
|
||||
|
|
@ -56,12 +54,6 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
const [status, setStatus] = useState(emptyStatus);
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [remoteSessions, setRemoteSessions] = useState<RemoteChatSession[]>([]);
|
||||
const [storedSessions, setStoredSessions] = useState<
|
||||
Record<ChatSlot, ChatSession[]>
|
||||
>({
|
||||
companion: [],
|
||||
operations: [],
|
||||
});
|
||||
const [activeSlot, setActiveSlot] = useState<ChatSlot>(
|
||||
fixedSlot ?? "companion",
|
||||
);
|
||||
|
|
@ -70,8 +62,6 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
const selectedProfileId = selectedSnapshot.profileId;
|
||||
const selectedServerInstanceId = selectedSnapshot.serverInstanceId;
|
||||
const selectedSessionId = selectedSnapshot.activeSessionId;
|
||||
const historySessionId =
|
||||
selectedSessionId ?? storedSessions[selectedSlot][0]?.sessionId;
|
||||
const selectedTransport = selectedSnapshot.transport;
|
||||
const [draft, setDraft] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
|
@ -115,15 +105,6 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
[activeMessages],
|
||||
);
|
||||
|
||||
const displaySessions =
|
||||
remoteSessions.length > 0
|
||||
? remoteSessions
|
||||
: storedSessions[selectedSlot].map((session) => ({
|
||||
sessionId: session.sessionId,
|
||||
displayName: undefined,
|
||||
updatedAt: session.lastMessageAt,
|
||||
}));
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
const result = await invoke<unknown>("connection_runtime_status");
|
||||
|
|
@ -173,11 +154,6 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
.then((result) => {
|
||||
if (cancelled) return;
|
||||
const sessions = chatSessionSchema.array().parse(result);
|
||||
setStoredSessions((current) => ({
|
||||
...current,
|
||||
[selectedSlot]: sessions,
|
||||
}));
|
||||
|
||||
setUnreadCounts((current) => ({
|
||||
...current,
|
||||
[selectedSlot]: sessions.reduce(
|
||||
|
|
@ -195,7 +171,6 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
selectedProfileId,
|
||||
selectedServerInstanceId,
|
||||
selectedSessionId,
|
||||
historySessionId,
|
||||
selectedTransport,
|
||||
]);
|
||||
|
||||
|
|
@ -225,7 +200,6 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
selectedProfileId,
|
||||
selectedServerInstanceId,
|
||||
selectedSessionId,
|
||||
historySessionId,
|
||||
selectedTransport,
|
||||
]);
|
||||
|
||||
|
|
@ -257,7 +231,6 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
selectedProfileId,
|
||||
selectedServerInstanceId,
|
||||
selectedSessionId,
|
||||
historySessionId,
|
||||
selectedTransport,
|
||||
]);
|
||||
|
||||
|
|
@ -265,7 +238,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
const snapshot = {
|
||||
profileId: selectedProfileId,
|
||||
serverInstanceId: selectedServerInstanceId,
|
||||
activeSessionId: historySessionId,
|
||||
activeSessionId: selectedSessionId,
|
||||
transport: selectedTransport,
|
||||
};
|
||||
if (
|
||||
|
|
@ -288,7 +261,6 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
selectedProfileId,
|
||||
selectedServerInstanceId,
|
||||
selectedSessionId,
|
||||
historySessionId,
|
||||
selectedTransport,
|
||||
]);
|
||||
|
||||
|
|
@ -296,7 +268,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
const snapshot = {
|
||||
profileId: selectedProfileId,
|
||||
serverInstanceId: selectedServerInstanceId,
|
||||
activeSessionId: historySessionId,
|
||||
activeSessionId: selectedSessionId,
|
||||
transport: selectedTransport,
|
||||
};
|
||||
if (
|
||||
|
|
@ -318,14 +290,32 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
.then((result) => {
|
||||
if (cancelled) return;
|
||||
const records = storedChatMessageSchema.array().parse(result);
|
||||
setMessages((current) =>
|
||||
mergeLoadedChatMessages(
|
||||
current,
|
||||
records,
|
||||
selectedSlot,
|
||||
snapshot.activeSessionId,
|
||||
),
|
||||
setMessages((current) => {
|
||||
const localUserMessages = current.filter(
|
||||
(item) =>
|
||||
(item.id.startsWith("local-") || item.streaming) &&
|
||||
item.slot === selectedSlot &&
|
||||
item.sessionId === 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);
|
||||
return () => {
|
||||
|
|
@ -336,7 +326,6 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
selectedProfileId,
|
||||
selectedServerInstanceId,
|
||||
selectedSessionId,
|
||||
historySessionId,
|
||||
selectedTransport,
|
||||
]);
|
||||
|
||||
|
|
@ -461,7 +450,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
await navigator.clipboard.writeText(content);
|
||||
setError(null);
|
||||
} catch {
|
||||
setError("复制失败,请检查剪贴板权限。");
|
||||
setError("Copy failed. Check clipboard permissions.");
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -588,7 +577,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
<section className="chat-panel" aria-label="聊天面板">
|
||||
<div className="chat-heading">
|
||||
<div>
|
||||
<p className="eyebrow">共享聊天运行时</p>
|
||||
<p className="eyebrow">Shared chat runtime</p>
|
||||
<h2>统一聊天运行时</h2>
|
||||
<p className="chat-note">
|
||||
主界面、快速聊天和气泡共享同一套消息状态。
|
||||
|
|
@ -603,22 +592,6 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
onClick={() => setActiveSlot(slot)}
|
||||
role="tab"
|
||||
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"
|
||||
>
|
||||
{slot === "companion" ? "陪伴" : "运维"}
|
||||
|
|
@ -632,33 +605,35 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
</div>
|
||||
<div className="chat-runtime-strip">
|
||||
<div>
|
||||
<span>配置</span>
|
||||
<strong>{status[selectedSlot].profileId ?? "未连接"}</strong>
|
||||
<span>Profile</span>
|
||||
<strong>{status[selectedSlot].profileId ?? "Not connected"}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>会话</span>
|
||||
<strong>{status[selectedSlot].activeSessionId ?? "新会话"}</strong>
|
||||
<span>Session</span>
|
||||
<strong>
|
||||
{status[selectedSlot].activeSessionId ?? "New session"}
|
||||
</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>状态</span>
|
||||
<span>Status</span>
|
||||
<strong>{connectionStateLabel(status[selectedSlot].state)}</strong>
|
||||
</div>
|
||||
<div className="chat-runtime-actions">
|
||||
<button type="button" onClick={() => void refreshConnection()}>
|
||||
刷新
|
||||
Refresh
|
||||
</button>
|
||||
<button type="button" onClick={() => void reconnectConnection()}>
|
||||
重连
|
||||
Reconnect
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void disconnectConnection()}
|
||||
disabled={status[selectedSlot].state === "disconnected"}
|
||||
>
|
||||
断开
|
||||
Disconnect
|
||||
</button>
|
||||
<button type="button" onClick={() => void startNewSession()}>
|
||||
新对话
|
||||
New chat
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -678,9 +653,9 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
{displaySessions.length > 0 ? (
|
||||
{remoteSessions.length > 0 ? (
|
||||
<div className="chat-session-list" aria-label="Chat sessions">
|
||||
{displaySessions.map((session, index) => (
|
||||
{remoteSessions.map((session) => (
|
||||
<button
|
||||
className={
|
||||
session.sessionId === status[selectedSlot].activeSessionId
|
||||
|
|
@ -688,7 +663,6 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
: "chat-session"
|
||||
}
|
||||
key={session.sessionId}
|
||||
title={`会话标识:${session.sessionId}`}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
void invoke("switch_connection_slot_session", {
|
||||
|
|
@ -702,23 +676,16 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
);
|
||||
}}
|
||||
>
|
||||
<strong>{session.displayName || `会话 ${index + 1}`}</strong>
|
||||
<small>{formatSessionTime(session.updatedAt)}</small>
|
||||
<strong>{session.displayName || session.sessionId}</strong>
|
||||
<small>{session.updatedAt || "Remote session"}</small>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<div
|
||||
id={`chat-panel-${selectedSlot}`}
|
||||
className="chat-message-list"
|
||||
role="tabpanel"
|
||||
aria-label={`${selectedSlot} messages`}
|
||||
aria-busy={sending[selectedSlot]}
|
||||
aria-live="polite"
|
||||
>
|
||||
<div className="chat-message-list" aria-live="polite">
|
||||
{visibleMessages.length === 0 ? (
|
||||
<p className="chat-empty">
|
||||
当前槽位还没有消息。连接 Profile 后即可开始聊天。
|
||||
No messages in this slot yet. Connect a Profile to start chatting.
|
||||
</p>
|
||||
) : (
|
||||
visibleMessages.map((message) => {
|
||||
|
|
@ -734,63 +701,43 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
? "A"
|
||||
: "!"}
|
||||
</div>
|
||||
<div className="chat-message-content">
|
||||
<div className="chat-bubble">
|
||||
<div className="chat-bubble-header">
|
||||
<span>
|
||||
{message.role === "user"
|
||||
? "你"
|
||||
? "You"
|
||||
: message.role === "assistant"
|
||||
? "AstrBot"
|
||||
: "系统"}
|
||||
: "System"}
|
||||
</span>
|
||||
{message.streaming ? <small>生成中</small> : null}
|
||||
{message.streaming ? <small>Generating</small> : null}
|
||||
</div>
|
||||
{message.content ? (
|
||||
<MessageContent content={message.content} slot={selectedSlot} />
|
||||
<MessageContent content={message.content} />
|
||||
) : (
|
||||
<p className="message-placeholder">正在生成…</p>
|
||||
<p className="message-placeholder">Generating?</p>
|
||||
)}
|
||||
</div>
|
||||
{message.role === "assistant" &&
|
||||
message.content &&
|
||||
!message.streaming ? (
|
||||
<div className="chat-message-actions" aria-label="消息操作">
|
||||
<div className="chat-message-actions">
|
||||
<button
|
||||
type="button"
|
||||
aria-label="复制消息"
|
||||
title="复制消息"
|
||||
onClick={() => void copyMessage(message.content)}
|
||||
>
|
||||
<span
|
||||
className="message-action-icon icon-copy"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span>复制</span>
|
||||
Copy
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="重试消息"
|
||||
title="重试消息"
|
||||
onClick={() => retryMessage(message.id)}
|
||||
>
|
||||
<span
|
||||
className="message-action-icon icon-retry"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span>重试</span>
|
||||
Retry
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="朗读消息"
|
||||
title="朗读消息"
|
||||
onClick={() => speakMessage(message.content)}
|
||||
>
|
||||
<span
|
||||
className="message-action-icon icon-read"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span>朗读</span>
|
||||
Read aloud
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
|
|
@ -800,7 +747,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
type="button"
|
||||
onClick={() => void stopGeneration()}
|
||||
>
|
||||
停止生成
|
||||
Stop generating
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
|
|
@ -809,16 +756,11 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
})
|
||||
)}
|
||||
</div>
|
||||
{error ? (
|
||||
<p className="chat-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
{error ? <p className="chat-error">{error}</p> : null}
|
||||
<div className="chat-composer-toolbar">
|
||||
<label className="file-picker">
|
||||
<span>添加图片/文件</span>
|
||||
<input
|
||||
className="file-picker-input"
|
||||
type="file"
|
||||
multiple
|
||||
onChange={(event) => {
|
||||
|
|
@ -834,7 +776,6 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
type="button"
|
||||
onClick={toggleVoiceInput}
|
||||
className={voiceListening ? "voice-button active" : "voice-button"}
|
||||
aria-pressed={voiceListening}
|
||||
>
|
||||
{voiceListening ? "停止录音" : "语音输入"}
|
||||
</button>
|
||||
|
|
@ -873,33 +814,19 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
onChange={(event) => setDraft(event.target.value)}
|
||||
placeholder={
|
||||
selectedSlot === "companion"
|
||||
? "和陪伴实例说点什么…(Enter 发送,Shift+Enter 换行)"
|
||||
: "向运维实例描述问题…(Enter 发送,Shift+Enter 换行)"
|
||||
? "和陪伴实例说点什么…"
|
||||
: "向运维实例描述问题…"
|
||||
}
|
||||
value={draft}
|
||||
rows={3}
|
||||
onKeyDown={(event) => {
|
||||
if (
|
||||
event.key !== "Enter" ||
|
||||
event.shiftKey ||
|
||||
event.nativeEvent.isComposing
|
||||
)
|
||||
return;
|
||||
event.preventDefault();
|
||||
void send();
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
className="chat-send-button"
|
||||
disabled={
|
||||
(!draft.trim() && pendingAttachments.length === 0) || uploading
|
||||
}
|
||||
type="submit"
|
||||
>
|
||||
<span className="send-button-icon" aria-hidden="true">
|
||||
↑
|
||||
</span>
|
||||
<span>发送</span>
|
||||
发送
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
|
|
@ -984,18 +911,6 @@ function applyRuntimeEvents(
|
|||
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(
|
||||
state: ConnectionRuntimeStatus["companion"]["state"],
|
||||
): string {
|
||||
|
|
|
|||
|
|
@ -1,62 +1,13 @@
|
|||
import { Fragment, useEffect, useState, type ReactNode } from "react";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
|
||||
import type { ChatSlot } from "./types";
|
||||
import { Fragment, type ReactNode } from "react";
|
||||
|
||||
type MessageContentProps = {
|
||||
content: string;
|
||||
slot: ChatSlot;
|
||||
};
|
||||
|
||||
type DownloadedAttachment = {
|
||||
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,
|
||||
);
|
||||
function renderInline(text: string, keyPrefix: string): ReactNode[] {
|
||||
const tokens = text.split(/(`[^`]+`|\*\*[^*]+\*\*|\[[^\]]+\]\([^)]+\))/g);
|
||||
return tokens.map((token, 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("`")) {
|
||||
return <code key={key}>{token.slice(1, -1)}</code>;
|
||||
}
|
||||
|
|
@ -75,65 +26,8 @@ function renderInline(
|
|||
});
|
||||
}
|
||||
|
||||
export function MessageContent({ content, slot }: MessageContentProps) {
|
||||
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");
|
||||
export function MessageContent({ content }: MessageContentProps) {
|
||||
const lines = content.replaceAll("\r\n", "\n").split("\n");
|
||||
const blocks: ReactNode[] = [];
|
||||
let codeLines: string[] | null = null;
|
||||
let codeLanguage = "";
|
||||
|
|
@ -144,7 +38,7 @@ export function MessageContent({ content, slot }: MessageContentProps) {
|
|||
if (!paragraph.length) return;
|
||||
blocks.push(
|
||||
<p key={`paragraph-${blocks.length}`}>
|
||||
{renderInline(paragraph.join(" "), `paragraph-${blocks.length}`, imageUrls)}
|
||||
{renderInline(paragraph.join(" "), `paragraph-${blocks.length}`)}
|
||||
</p>,
|
||||
);
|
||||
paragraph = [];
|
||||
|
|
@ -155,7 +49,7 @@ export function MessageContent({ content, slot }: MessageContentProps) {
|
|||
<ul key={`list-${blocks.length}`}>
|
||||
{list.map((item, index) => (
|
||||
<li key={`list-${blocks.length}-${index}`}>
|
||||
{renderInline(item, `list-${blocks.length}-${index}`, imageUrls)}
|
||||
{renderInline(item, `list-${blocks.length}-${index}`)}
|
||||
</li>
|
||||
))}
|
||||
</ul>,
|
||||
|
|
@ -198,7 +92,7 @@ export function MessageContent({ content, slot }: MessageContentProps) {
|
|||
const Heading = `h${level}` as "h1" | "h2" | "h3";
|
||||
blocks.push(
|
||||
<Heading key={`heading-${index}`}>
|
||||
{renderInline(heading[2], `heading-${index}`, imageUrls)}
|
||||
{renderInline(heading[2], `heading-${index}`)}
|
||||
</Heading>,
|
||||
);
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -56,7 +56,6 @@ export function StatusBubble() {
|
|||
const companion = status.companion.state;
|
||||
const operations = status.operations.state;
|
||||
const active = companion === "connected" || operations === "connected";
|
||||
const statusDescription = `${slotLabel(companion, "陪伴实例")};${slotLabel(operations, "运维实例")}`;
|
||||
const visibleState = quiet
|
||||
? "静默中"
|
||||
: active
|
||||
|
|
@ -65,9 +64,7 @@ export function StatusBubble() {
|
|||
return (
|
||||
<main className="status-bubble-shell" aria-label="连接状态气泡">
|
||||
<button
|
||||
aria-label={`打开 AstrBot Desktop,当前状态:${visibleState}`}
|
||||
aria-describedby="status-bubble-description"
|
||||
className={`${active ? "status-bubble connected" : "status-bubble"} status-bubble-${statusTone(companion, operations)}`}
|
||||
className={active ? "status-bubble connected" : "status-bubble"}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const target =
|
||||
|
|
@ -85,45 +82,16 @@ export function StatusBubble() {
|
|||
}
|
||||
}}
|
||||
>
|
||||
<span className="status-bubble-orb" aria-hidden="true" />
|
||||
<span className="status-bubble-orb" />
|
||||
<span className="status-bubble-label">{visibleState}</span>
|
||||
{unread > 0 && !quiet ? (
|
||||
<span className="status-bubble-unread">{unread}</span>
|
||||
) : null}
|
||||
</button>
|
||||
<span id="status-bubble-description" className="sr-only" role="status">
|
||||
{statusDescription}
|
||||
{quiet
|
||||
? ",当前处于静默时段"
|
||||
: unread > 0
|
||||
? `,${unread} 条未读消息`
|
||||
: ""}
|
||||
</span>
|
||||
</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(
|
||||
companion: ConnectionRuntimeStatus["companion"]["state"],
|
||||
operations: ConnectionRuntimeStatus["operations"]["state"],
|
||||
|
|
|
|||
|
|
@ -1,85 +0,0 @@
|
|||
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),
|
||||
slot: activeSlotKindSchema,
|
||||
serverInstanceId: z.string().min(1),
|
||||
remoteUsername: z.string().min(1).nullish(),
|
||||
remoteUsername: z.string().min(1).optional(),
|
||||
sessionId: z.string().min(1),
|
||||
unreadCount: z.number().int().nonnegative(),
|
||||
lastMessageId: z.string().min(1).nullish(),
|
||||
lastMessageId: z.string().min(1).optional(),
|
||||
lastMessageAt: z.string().min(1),
|
||||
})
|
||||
.strict();
|
||||
|
|
@ -84,7 +84,7 @@ export const storedChatMessageSchema = z
|
|||
profileId: z.string().min(1),
|
||||
slot: activeSlotKindSchema,
|
||||
serverInstanceId: z.string().min(1),
|
||||
remoteUsername: z.string().min(1).nullish(),
|
||||
remoteUsername: z.string().min(1).optional(),
|
||||
sessionId: z.string().min(1),
|
||||
messageId: z.string().min(1),
|
||||
role: z.enum(["user", "assistant", "system"]),
|
||||
|
|
@ -95,62 +95,6 @@ export const storedChatMessageSchema = z
|
|||
})
|
||||
.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({
|
||||
id: z.string().min(1),
|
||||
name: z.string().min(1).optional(),
|
||||
|
|
|
|||
|
|
@ -1,242 +0,0 @@
|
|||
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,18 +12,14 @@ export function PetPackImporter() {
|
|||
setManifest(null);
|
||||
setError(null);
|
||||
if (!file.name.toLowerCase().endsWith(".json") || file.size > 256 * 1024) {
|
||||
setError(
|
||||
"文件必须是 256 KiB 以内的 JSON manifest。若要导入图片,请先放入素材包目录。 ",
|
||||
);
|
||||
setError("文件必须是 256 KiB 以内的 JSON manifest。若要导入图片,请先放入素材包目录。 ");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const parsed = petPackManifestSchema.parse(JSON.parse(await file.text()));
|
||||
setManifest(parsed);
|
||||
} catch (reason) {
|
||||
setError(
|
||||
reason instanceof Error ? reason.message : "无法读取桌宠 manifest。 ",
|
||||
);
|
||||
setError(reason instanceof Error ? reason.message : "无法读取桌宠 manifest。 ");
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -46,11 +42,7 @@ export function PetPackImporter() {
|
|||
}}
|
||||
/>
|
||||
{fileName ? <p className="form-note">已选择:{fileName}</p> : null}
|
||||
{error ? (
|
||||
<p className="error-banner" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
{error ? <p className="error-banner">{error}</p> : null}
|
||||
{manifest ? (
|
||||
<div className="pet-pack-preview">
|
||||
<strong>{manifest.name}</strong>
|
||||
|
|
@ -60,12 +52,7 @@ export function PetPackImporter() {
|
|||
</span>
|
||||
<span>{manifest.animations.length} 个动作片段</span>
|
||||
<span>
|
||||
{
|
||||
manifest.animations.filter(
|
||||
(animation) => animation.movement !== "stationary",
|
||||
).length
|
||||
}{" "}
|
||||
个移动动作
|
||||
{manifest.animations.filter((animation) => animation.movement !== "stationary").length} 个移动动作
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
|
|
|
|||
|
|
@ -1,26 +1,11 @@
|
|||
import { useState } from "react";
|
||||
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 JwtLoginResult {
|
||||
profileId: string;
|
||||
credentialReference: string;
|
||||
dashboardUsername: string;
|
||||
authenticationType: "jwt";
|
||||
}
|
||||
interface Props {
|
||||
profile: ConnectionProfile;
|
||||
onChanged: () => Promise<void> | void;
|
||||
}
|
||||
interface CredentialEnrollmentResult { profileId: string; 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) {
|
||||
const [secret, setSecret] = useState("");
|
||||
|
|
@ -32,163 +17,51 @@ export function CredentialEnrollmentCard({ profile, onChanged }: Props) {
|
|||
const [message, setMessage] = useState<string | null>(null);
|
||||
|
||||
async function enroll() {
|
||||
setBusy(true);
|
||||
setMessage(null);
|
||||
setBusy(true); setMessage(null);
|
||||
try {
|
||||
const result = await invoke<CredentialEnrollmentResult>(
|
||||
"enroll_profile_credential",
|
||||
{
|
||||
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);
|
||||
}
|
||||
const result = await invoke<CredentialEnrollmentResult>("enroll_profile_credential", { 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() {
|
||||
setBusy(true);
|
||||
setMessage(null);
|
||||
setBusy(true); setMessage(null);
|
||||
try {
|
||||
const result = await invoke<JwtLoginResult>("login_profile_jwt", {
|
||||
request: {
|
||||
profileId: profile.id,
|
||||
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);
|
||||
}
|
||||
const result = await invoke<JwtLoginResult>("login_profile_jwt", { request: { profileId: profile.id, 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() {
|
||||
setBusy(true);
|
||||
setMessage(null);
|
||||
try {
|
||||
await invoke("clear_profile_credential", { profileId: profile.id });
|
||||
setMessage("已清除凭据引用");
|
||||
await onChanged();
|
||||
} catch (error) {
|
||||
setMessage(error instanceof Error ? error.message : "清除凭据失败。");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
setBusy(true); setMessage(null);
|
||||
try { await invoke("clear_profile_credential", { profileId: profile.id }); setMessage("已清除凭据引用"); await onChanged(); }
|
||||
catch (error) { setMessage(error instanceof Error ? error.message : "清除凭据失败。"); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
|
||||
return (
|
||||
<section
|
||||
className="credential-card"
|
||||
aria-label={`凭据登记 ${profile.displayName}`}
|
||||
>
|
||||
<section className="credential-card" aria-label={`凭据登记 ${profile.displayName}`}>
|
||||
<h4>安全凭据登记</h4>
|
||||
<p className="form-note">
|
||||
凭据只通过一次性 IPC 写入 Windows Credential Manager,不会进入 React
|
||||
持久状态。
|
||||
</p>
|
||||
<label>
|
||||
<span>远端 ID(英文数字)</span>
|
||||
<input
|
||||
value={remoteId}
|
||||
onChange={(event) => setRemoteId(event.target.value)}
|
||||
disabled={busy}
|
||||
placeholder="yokiiro01"
|
||||
/>
|
||||
</label>
|
||||
<p>凭据只通过一次性 IPC 写入 Windows Credential Manager,不会进入 React 持久状态。</p>
|
||||
<label>远端 ID(英文数字)<input value={remoteId} onChange={(event) => setRemoteId(event.target.value)} disabled={busy} placeholder="yokiiro01" /></label>
|
||||
{profile.authenticationType === "jwt" ? (
|
||||
<>
|
||||
<label>
|
||||
<span>AstrBot Dashboard 用户名</span>
|
||||
<input
|
||||
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>AstrBot Dashboard 用户名<input value={dashboardUsername} onChange={(event) => setDashboardUsername(event.target.value)} disabled={busy} autoComplete="username" /></label>
|
||||
<label>Dashboard 密码<input type="password" value={dashboardPassword} onChange={(event) => setDashboardPassword(event.target.value)} disabled={busy} autoComplete="current-password" /></label>
|
||||
<label>TOTP(可选)<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()}>登录 AstrBot Dashboard</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<label>
|
||||
<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>
|
||||
<label>API Key / Token(一次性)<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()}>登记凭据</button>
|
||||
</>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
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}
|
||||
<button type="button" disabled={busy || !profile.credentialReference} onClick={() => void clearCredential()}>清除凭据</button>
|
||||
{profile.credentialReference ? <p>当前引用:{profile.credentialReference}</p> : <p>尚未登记凭据</p>}
|
||||
{message ? <p role="status">{message}</p> : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,277 +0,0 @@
|
|||
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>
|
||||
);
|
||||
}
|
||||
1090
src/styles.css
1090
src/styles.css
文件差异内容过多而无法显示
加载差异
|
|
@ -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 ({
|
||||
page,
|
||||
|
|
@ -6,17 +6,19 @@ test("renders the bootstrap shell and safe browser fallback", async ({
|
|||
await page.goto("/");
|
||||
|
||||
await expect(
|
||||
page.getByText("AstrBot Desktop", { exact: true }).first(),
|
||||
page.getByRole("heading", { name: "AstrBot Desktop" }),
|
||||
).toBeVisible();
|
||||
await expect(page.getByText("desktop-v1alpha1")).toBeVisible();
|
||||
await expect(
|
||||
page.getByRole("heading", { name: "统一聊天运行时" }),
|
||||
page.getByText("IPC unavailable:", { exact: false }),
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
page.getByText("IPC 暂不可用:", { exact: false }),
|
||||
).toBeVisible();
|
||||
|
||||
await page.getByRole("button", { name: "◎ 连接 实例与槽位管理" }).click();
|
||||
await expect(
|
||||
page.getByRole("heading", { name: "连接 Profile" }),
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
page.getByText("Profile storage unavailable:", { exact: false }),
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
page.getByRole("button", { name: "重新检查 IPC" }),
|
||||
).toBeEnabled();
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,43 +0,0 @@
|
|||
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();
|
||||
});
|
||||
正在加载…
添加表格
在新工单中引用