fix(pet): read stored preferences and stop the pet from stealing focus
An audit of the destroy→hide change across four lenses raised 17 findings; 14 survived adversarial verification. Two of them were regressions that change introduced, and both had the same shape: code that only worked because the pet window used to not exist. show_pet_context_menu picked the pet window and fell back to main. While the pet rendered inside the app its window had been destroyed at startup, so the fallback happened to select the visible main window. Now that the window merely hides, the menu was being anchored to a hidden HWND, which Win32 cannot bring to the foreground. The visibility test is explicit now rather than incidental. DesktopPetView read the connection state in a mount effect and nothing emitted connection events, so destroy-and-rebuild was what re-read it. Without a remount the floating pet showed whatever was true at startup for the rest of the session. reveal_pet_window now emits pet-window-revealed and the view re-reads on it. The rest were already there. Every pet setting was decorative: the preferences were applied and then dropped, so reveal_pet_window had to invent an answer and hard-coded the first monitor, the safe edge and always-on-top — reverting the user's choices on every show. The pet view re-sent a fully hard-coded payload whenever game mode toggled, and the settings page initialised its controls from literals, so returning to the page and changing one thing pushed three stale defaults back onto the window. There is a session-scoped store now, a command to read it, and both frontends read before they write. Persisting it across restarts is F-75. Always-on-top is off by default, which is what the Q6 acceptance criterion asked for (F-35), and the window no longer takes focus when shown — it was activating on show and swallowing keystrokes meant for the main window. focusable is left alone on purpose: clearing it adds WS_EX_NOACTIVATE, which would re-break the context menu now anchored to that window. That is F-79. The pet also painted a solid dark rectangle before its assets arrived. The transparency rule is gated on a class that an effect inside the 5.2 MB lazy chunk added, so until that chunk ran the app's opaque background won. This is why the earlier hunt for "the rule that beats !important" found nothing: the class was not applied yet, so specificity was never the question. The pet now has its own entry document carrying the class statically. An inline script would not do — tauri-utils only nonces script[src^='http'], so it would pass in dev and be blocked by script-src 'self' in a release build. Rust tests 92 → 97, frontend 30 → 35. All 11 mutations of the new assertions were confirmed to fail. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
这个提交存在于:
父节点
3e03a4e8b6
当前提交
9b2ec64502
共有 12 个文件被更改,包括 507 次插入 和 84 次删除
12
CHANGELOG.md
12
CHANGELOG.md
|
|
@ -60,6 +60,18 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
|
||||||
by destroying its window, which forced every later open through a rebuild path that failed
|
by destroying its window, which forced every later open through a rebuild path that failed
|
||||||
outright; the pet window is now hidden and re-shown instead.
|
outright; the pet window is now hidden and re-shown instead.
|
||||||
- The desktop pet no longer sits inside an opaque dark card when rendered inside the application.
|
- The desktop pet no longer sits inside an opaque dark card when rendered inside the application.
|
||||||
|
- The desktop pet no longer appears as a solid dark rectangle before its assets finish loading. It
|
||||||
|
now has its own entry document, so the transparency rule applies before anything paints instead of
|
||||||
|
waiting on a lazily-imported chunk.
|
||||||
|
- The desktop pet no longer takes focus from the main window when it is shown, so keystrokes are no
|
||||||
|
longer delivered to a window with nothing to type into.
|
||||||
|
- The desktop pet is no longer pinned above every other window by default, and turning that off is
|
||||||
|
no longer undone the next time the pet is shown.
|
||||||
|
- The pet's monitor, position mode and always-on-top choices survive the pet being hidden and shown,
|
||||||
|
and the pet settings page now reflects what the window is actually doing rather than a fixed set
|
||||||
|
of defaults. They are not yet remembered across restarts.
|
||||||
|
- The desktop pet's animation now follows the connection again after the first time it is shown.
|
||||||
|
- The pet's context menu is anchored to a visible window again.
|
||||||
- One unreachable connection no longer freezes the whole application. The reachability probe now
|
- One unreachable connection no longer freezes the whole application. The reachability probe now
|
||||||
runs outside the runtime lock, so a slot that is connecting cannot block status, sending,
|
runs outside the runtime lock, so a slot that is connecting cannot block status, sending,
|
||||||
cancelling or disconnecting on the other slot, and the attempt itself can be interrupted.
|
cancelling or disconnecting on the other slot, and the attempt itself can be interrupted.
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
# AstrBot Desktop 修复队列
|
# AstrBot Desktop 修复队列
|
||||||
|
|
||||||
基于 2026-07-26 全源码审计 · 共 73 项 · 8 个批次
|
基于 2026-07-26 全源码审计 · 共 78 项 · 8 个批次
|
||||||
|
(原 73 项 + 2026-07-27 桌宠窗口审计补编 F-75 – F-79)
|
||||||
|
|
||||||
> 配套审计档案:[full-source-audit-2026-07-26.md](./full-source-audit-2026-07-26.md)。
|
> 配套审计档案:[full-source-audit-2026-07-26.md](./full-source-audit-2026-07-26.md)。
|
||||||
> 本文中的 `P0-1` / `P1-7` 等编号均指向该档案中的对应发现。
|
> 本文中的 `P0-1` / `P1-7` 等编号均指向该档案中的对应发现。
|
||||||
|
|
@ -290,6 +291,34 @@ AstrBot 在一次回复中**交错**投递两类 `plain` 帧:
|
||||||
| **N-11** | 切到「桌面悬浮」模式桌宠直接消失 | `close_pet_window` 用 `destroy()` 而非隐藏。应用启动时默认 `app-ui` 模式会立刻销毁配置创建的窗口(真机日志:启动时 `close_pet_window invoked window_existed=true` 出现两次,React StrictMode 双挂载),此后 `open_pet_window` 必走 `WebviewWindowBuilder::from_config` 重建分支,而**该分支整体失败**——日志显示 `open_pet_window invoked window_existed=false` 之后既无 `pet window revealed` 也无失败行,即在配置查找 / `from_config` / `build()` 三处裸 `?` 之一返回 Err 且无日志。改为 `hide()` 后每次打开都走「窗口已存在」这条已验证可用的分支 | 已修(`4f73c08`)。真机确认:`window_existed=true` → `pet window revealed monitors=2 monitor_work_area=3840x2088+0+0 position=3554,1742 size=270x330 visible=true`,右下角 16px 安全边距正确 |
|
| **N-11** | 切到「桌面悬浮」模式桌宠直接消失 | `close_pet_window` 用 `destroy()` 而非隐藏。应用启动时默认 `app-ui` 模式会立刻销毁配置创建的窗口(真机日志:启动时 `close_pet_window invoked window_existed=true` 出现两次,React StrictMode 双挂载),此后 `open_pet_window` 必走 `WebviewWindowBuilder::from_config` 重建分支,而**该分支整体失败**——日志显示 `open_pet_window invoked window_existed=false` 之后既无 `pet window revealed` 也无失败行,即在配置查找 / `from_config` / `build()` 三处裸 `?` 之一返回 Err 且无日志。改为 `hide()` 后每次打开都走「窗口已存在」这条已验证可用的分支 | 已修(`4f73c08`)。真机确认:`window_existed=true` → `pet window revealed monitors=2 monitor_work_area=3840x2088+0+0 position=3554,1742 size=270x330 visible=true`,右下角 16px 安全边距正确 |
|
||||||
| — | _N-11 排查中提出并被推翻的两条根因_ | ①「重建分支没调 `show()`」——是真实代码缺陷(配置声明 `"visible": false`),已修,但**不是本症状的原因**:修完桌宠依旧不出现。②「`DesktopPetView` 缺 Suspense 边界」——**变异测试直接推翻**,React 19 容忍无边界的 lazy 组件。教训:在拿到日志前不应给根因结论,这一条上我连错两次 | 已记录 |
|
| — | _N-11 排查中提出并被推翻的两条根因_ | ①「重建分支没调 `show()`」——是真实代码缺陷(配置声明 `"visible": false`),已修,但**不是本症状的原因**:修完桌宠依旧不出现。②「`DesktopPetView` 缺 Suspense 边界」——**变异测试直接推翻**,React 19 容忍无边界的 lazy 组件。教训:在拿到日志前不应给根因结论,这一条上我连错两次 | 已记录 |
|
||||||
|
|
||||||
|
### 桌宠窗口批 · N-12 – N-18(2026-07-27,四视角审计后)
|
||||||
|
|
||||||
|
N-11 落地后对「销毁改隐藏」这一改动做了四视角审计(透明链路 / 生命周期 / 多屏摆放 /
|
||||||
|
窗口姿态),每条发现再经一次对抗性复核。**17 条候选中 14 条成立、3 条被推翻**。其中
|
||||||
|
N-12、N-13 是 `4f73c08` **自身引入的回归**——把窗口从销毁改为隐藏,让两处依赖「窗口不存在」
|
||||||
|
的逻辑失去了原本偶然成立的前提。
|
||||||
|
|
||||||
|
| ID | 问题 | 根因 | 状态 |
|
||||||
|
| -------- | -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| **N-12** | 应用内模式下右键桌宠,菜单宿主是不可见窗口 | `show_pet_context_menu` 用 `get_webview_window(PET_WINDOW_ID).or_else(main)`。改隐藏之前,应用内模式下桌宠窗口已被启动时的 `close_pet_window` 销毁,所以 `or_else` 会**偶然**落到可见的主窗口上;改隐藏后该窗口恒存在,菜单被挂到一个隐藏 HWND 上,而 Win32 的 `TrackPopupMenu` 要求宿主可置前 | 已修:显式加 `.filter(is_visible)`,不再依赖「窗口不存在」这个偶然前提 |
|
||||||
|
| **N-13** | 浮动桌宠整个会话都显示启动时那一刻的连接状态 | `DesktopPetView` 的连接状态读取是 `[]` 依赖的挂载期 effect,且 Rust 侧从不发连接状态事件。改隐藏之前,销毁重建会顺带重新挂载并重读;改隐藏后 webview 永不重挂,启动后连接、掉线、鉴权过期都不会反映到桌宠上 | 已修:`reveal_pet_window` 发 `pet-window-revealed`,桌宠视图每次显示都重读;状态映射抽成 `petState.ts` 的纯函数并加测试 |
|
||||||
|
| **N-14** | 桌宠窗口首次加载时是一块不透明深色矩形 | 透明规则 `styles.css:1539` 以 `.pet-view` 为前置,而加这个类的 effect 在**懒加载 chunk 内部**——该 chunk 因 `?inline` 内联 3.9MB 精灵图而达 5.2MB。chunk 执行前,赢的是 `styles.css:2848` 的 `html, body, #root { background: var(--ui-bg) }`(`#091321`)。**这就是此前「`!important` 不生效」查不出的原因:类当时根本还没加上,与特异度无关** | 已修:新增 `pet.html` 入口,`class="pet-view"` 静态写在 `<html>` 上。**不能用内联脚本**:`tauri-utils/src/html.rs:153` 只给 `script[src^='http']` 注入 nonce,内联脚本在 `script-src 'self'` 下生产被拦、dev 无感 |
|
||||||
|
| **N-15** | 切到浮动模式时主窗口失去焦点,后续按键被丢弃 | 配置未声明 `focus`,tao 默认 `true`,于是每次 `show()` 走 `SW_SHOW` 激活分支。桌宠里只有一张 canvas,没有输入框,按键无处可去也无光标提示 | 已修:`"focus": false`。**未动 `focusable`**:设 `false` 会加上 `WS_EX_NOACTIVATE`,而浮动模式下右键菜单正挂在这个可见的桌宠窗口上,会把 N-12 重新引回来 → 记为 F-79 |
|
||||||
|
| **N-16** | 桌宠默认置顶,且用户关掉后每次重开又被打开 | = **F-35**。`tauri.conf.json` 写死 `alwaysOnTop: true`,且 `reveal_pet_window` 每次无条件 `set_always_on_top(true)` | 已修:配置改 `false`,`reveal_pet_window` 改读会话内偏好。默认值本身由单测 `the_pet_is_not_topmost_by_default` 钉住 |
|
||||||
|
| **N-17** | 显示器选择、位置模式、置顶开关全部是装饰——改完下一次显示就复原 | 偏好在 Rust 侧**从不留存**:`set_pet_window_preferences` 应用后即丢弃。于是 `reveal_pet_window` 只能自己编一个答案,写死了首个显示器 + 安全边缘 + 置顶;桌宠视图又在挂载和每次切游戏模式时回传一整份写死的载荷;设置页的四个控件是无持久化的 `useState`,其字面量初值会随下一次编辑被当作用户选择重新推给窗口 | 已修:Rust 侧加 `PetPreferencesState`(会话内),新增 `pet_window_preferences` 读取命令;桌宠视图改为「先读再只改 gameMode」并加 `embedded` 守卫;设置页从真实状态初始化。**跨重启仍不留存 → F-75** |
|
||||||
|
| **N-18** | 前端 `petPositionModeSchema` 与 Rust 契约不一致 | 前端写 `"follow-main-window"`(kebab),Rust `PetPositionMode` 是 `rename_all = "camelCase"` → `followMainWindow`。之所以从未炸过:它只被 `companionPresentationSettingsSchema` 引用,而后者**从未被任何代码消费** | 已修:改为 camelCase 与 Rust 对齐 |
|
||||||
|
|
||||||
|
**被推翻的 3 条**:①「隐藏后桌宠仍整会话跑动画定时器」——机制成立,但这正是改隐藏的明示意图
|
||||||
|
(保住监听与动画状态),无失效场景。②「`monitors.first()` 是 OS 枚举序而非主显示器」——机制成立
|
||||||
|
但无法据此构造失效。③「`PetPlacement.monitor_index` 写死 0」——引用行存在,但推不出错误行为。
|
||||||
|
|
||||||
|
**本批新增测试**:Rust +5(92 → 97)、前端 +5(30 → 35,新建 `petState.test.ts`、
|
||||||
|
`petEntry.test.ts`)。11 条变异全部被对应测试抓到(置顶默认翻转、游戏模式不再强制边缘、
|
||||||
|
索引不再钳制、`store()` 空操作、状态映射改错、兜底移除、`pet.html` 丢属性、加内联脚本、
|
||||||
|
窗口改回 `index.html`、配置重开置顶、配置放开 focus)。
|
||||||
|
|
||||||
|
**本批未修、已编号**:F-75 – F-79,见下。
|
||||||
|
|
||||||
## 功能空缺盘点(2026-07-27)
|
## 功能空缺盘点(2026-07-27)
|
||||||
|
|
||||||
用户询问语音聊天、窗口感知、游戏陪伴是否已有。三项**均在既定产品范围内**
|
用户询问语音聊天、窗口感知、游戏陪伴是否已有。三项**均在既定产品范围内**
|
||||||
|
|
@ -364,22 +393,37 @@ AstrBot 在一次回复中**交错**投递两类 `plain` 帧:
|
||||||
「同文件相邻改动合并进同一批」的编排原则归入 R5;放入 R4 会让两个可并行分支争夺同一文件。
|
「同文件相邻改动合并进同一批」的编排原则归入 R5;放入 R4 会让两个可并行分支争夺同一文件。
|
||||||
R5 因此由 9 项增至 13 项,与 R3、R4 仍无依赖关系。
|
R5 因此由 9 项增至 13 项,与 R3、R4 仍无依赖关系。
|
||||||
|
|
||||||
|
### F-75 – F-79 桌宠窗口补编(2026-07-27)
|
||||||
|
|
||||||
|
来自 N-11 闭环后的四视角审计。经对抗性复核成立但**本轮未修**的五项,全部归入 R6
|
||||||
|
(该批已 owns `tauri.conf.json` 与桌宠窗口姿态,F-35 即在其中):
|
||||||
|
|
||||||
|
| 新编号 | 位置与实质 | 为何本轮不修 | 验收 |
|
||||||
|
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
|
||||||
|
| **F-75** | `lib.rs` `PetPreferencesState` 只活在会话内。跨重启不留存,显示器/位置模式/置顶回到默认 | 需要落库或落配置文件,而 `window_states` 表没有这些列(`database/mod.rs`),属独立的持久化改动 | 选好显示器后重启应用,桌宠仍在该显示器上 |
|
||||||
|
| **F-76** | 拖动过的桌宠位置永不保存:`Moved` 持久化只对 `QUICK_WINDOW_ID` 生效(`lib.rs`),且下一次 `reveal` 会按 Edge 重新摆位 | 与 F-75 同源但需要额外的 `Moved` 处理与「自由位置时不覆盖」的判定。对照:应用内浮层的位置**是**存的(`localStorage` `astrbot.petPosition`),浮动窗口却丢,这个不一致本身要一并解决 | 拖到左上角后重启,桌宠仍在左上角 |
|
||||||
|
| **F-77** | `place_pet_on_monitor` 混用坐标空间:`outer_size()` 量的是**当前**显示器的物理尺寸,却拿去和**目标**显示器的物理工作区相减;`MonitorInfo.scale_factor` 在构造 `MonitorGeometry` 时被丢弃;16px 边距是物理像素,150% 缩放下视觉上只有约 11px | 跨 DPI 摆位要先想清楚是按逻辑像素还是物理像素表达边距,且需要双 DPI 真机才能验证 | 100% 与 150% 双屏之间切换显示器,桌宠不越出工作区,视觉边距一致 |
|
||||||
|
| **F-78** | 浮动模式下「关闭桌宠」(右键菜单或 Alt+F4)只隐藏窗口,`petDisplayMode` 仍是 `desktop-floating` 并被持久化。设置页继续显示「桌面浮动」、effect 因依赖未变不会重开、下次启动桌宠又回来 —— 「关闭」既不生效也不持久 | 需要先决定语义:「关闭」是切回应用内模式,还是新增一个「本次隐藏」状态。这是产品决策,不是实现细节 | 关闭桌宠后设置页与实际一致,且重启不自行恢复 |
|
||||||
|
| **F-79** | `focusable` 仍默认 `true`,所以点击桌宠会激活它,可能把全屏游戏切到后台 —— 与规划中的游戏陪伴直接冲突 | 设 `focusable: false` 会加上 `WS_EX_NOACTIVATE`,而右键菜单正挂在这个窗口上,会把 N-12 重新引回来。必须先把菜单宿主迁走(或改用非窗口宿主)才能设 | 全屏游戏中点击桌宠,游戏不失去焦点;右键菜单仍正常弹出并可选中 |
|
||||||
|
|
||||||
|
F-79 与 F-78 有顺序依赖:F-79 必须在菜单宿主迁移之后。F-75 与 F-76 建议同批实施(同一持久化载体)。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## R6 · 体验、无障碍与产品红线批
|
## R6 · 体验、无障碍与产品红线批
|
||||||
|
|
||||||
| ID | 来源 | 位置 | 动作 |
|
| ID | 来源 | 位置 | 动作 |
|
||||||
| -------- | ----- | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
|
| -------- | ----- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||||
| **F-35** | P2-30 | `DesktopPetView.tsx:139-148`;`tauri.conf.json` | **产品红线**:`alwaysOnTop` 默认改 `false`(隔离基线要求气泡/桌宠不默认置顶);embedded 模式跳过偏好写入;非 embedded 先读既有偏好再增量提交 |
|
| **F-35** | P2-30 | `DesktopPetView.tsx:139-148`;`tauri.conf.json` | **产品红线**:`alwaysOnTop` 默认改 `false`(隔离基线要求气泡/桌宠不默认置顶);embedded 模式跳过偏好写入;非 embedded 先读既有偏好再增量提交 **已于 2026-07-27 实施**(N-16 / N-17),三项要求全部落地 |
|
||||||
| **F-36** | P2-20 | `ChatPanel.tsx:73-74,181-187,264-293` | mark-read 完成后再重取会话列表;仅存在真实 `activeSessionId` 时标已读;非选中槽位监听事件递增未读 |
|
| **F-36** | P2-20 | `ChatPanel.tsx:73-74,181-187,264-293` | mark-read 完成后再重取会话列表;仅存在真实 `activeSessionId` 时标已读;非选中槽位监听事件递增未读 |
|
||||||
| **F-37** | P2-21 | `ChatPanel.tsx:468-475` | `retryMessage` 增加 `sessionId === activeSessionId` 过滤;`messageOverride` 与 draft 回退解耦 |
|
| **F-37** | P2-21 | `ChatPanel.tsx:468-475` | `retryMessage` 增加 `sessionId === activeSessionId` 过滤;`messageOverride` 与 draft 回退解耦 |
|
||||||
| **F-38** | P2-22 | `ChatPanel.tsx:435-457` | 按 `code === "cancelled"` 区分取消与真错误;停止时保留已收内容为正常消息,不标 error、不弹横幅 |
|
| **F-38** | P2-22 | `ChatPanel.tsx:435-457` | 按 `code === "cancelled"` 区分取消与真错误;停止时保留已收内容为正常消息,不标 error、不弹横幅 |
|
||||||
| **F-39** | P2-23 | `ChatPanel.tsx:920-925`;`chat/types.ts` | `ChatMessage` 补 `profileId`/`serverInstanceId` 并纳入所有 find/filter/去重键(对齐四元组规范) |
|
| **F-39** | P2-23 | `ChatPanel.tsx:920-925`;`chat/types.ts` | `ChatMessage` 补 `profileId`/`serverInstanceId` 并纳入所有 find/filter/去重键(对齐四元组规范) |
|
||||||
| **F-40** | P2-24 | `styles.css:3116-3139` | 去掉 `visibility:hidden`,仅用 opacity + pointer-events,解开键盘 focus-within 死锁 |
|
| **F-40** | P2-24 | `styles.css:3116-3139` | 去掉 `visibility:hidden`,仅用 opacity + pointer-events,解开键盘 focus-within 死锁 |
|
||||||
| **F-41** | P2-25 | `ChatPanel.tsx:607-620,711-717` | 箭头切换时 `focus()` 目标 tab;两个 panel id 常驻或动态 `aria-controls`;`aria-busy` 与 `aria-live` 分离 |
|
| **F-41** | P2-25 | `ChatPanel.tsx:607-620,711-717` | 箭头切换时 `focus()` 目标 tab;两个 panel id 常驻或动态 `aria-controls`;`aria-busy` 与 `aria-live` 分离 |
|
||||||
| **F-42** | P2-26 | `CredentialEnrollmentCard.tsx:34-80` | `finally` 中清空 secret/password/totp;两处 `invoke` 返回值补 zod schema |
|
| **F-42** | P2-26 | `CredentialEnrollmentCard.tsx:34-80` | `finally` 中清空 secret/password/totp;两处 `invoke` 返回值补 zod schema |
|
||||||
| **F-43** | P2-27 | `ChatPanel.tsx:343-354` | 首次 refresh 失败也建立退避轮询;snapshot schema strict 失败给可见告警而非静默离线 |
|
| **F-43** | P2-27 | `ChatPanel.tsx:343-354` | 首次 refresh 失败也建立退避轮询;snapshot schema strict 失败给可见告警而非静默离线 |
|
||||||
| **F-44** | P2-28 | `ChatPanel.tsx` | 消息列表底部锚点 +"接近底部才跟随";unmount 调 `recognition.stop()` / `speechSynthesis.cancel()`;朗读前 Markdown 转纯文本 |
|
| **F-44** | P2-28 | `ChatPanel.tsx` | 消息列表底部锚点 +"接近底部才跟随";unmount 调 `recognition.stop()` / `speechSynthesis.cancel()`;朗读前 Markdown 转纯文本 |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
||||||
30
pet.html
普通文件
30
pet.html
普通文件
|
|
@ -0,0 +1,30 @@
|
||||||
|
<!doctype html>
|
||||||
|
<!--
|
||||||
|
The desktop pet's own entry point.
|
||||||
|
|
||||||
|
It exists so that `class="pet-view"` is present before anything paints. The
|
||||||
|
transparency rule in styles.css is gated on that class, and it used to be
|
||||||
|
added by an effect inside the lazily-imported pet chunk — over 5 MB, because
|
||||||
|
the spritesheet is inlined — so the transparent, undecorated pet window was
|
||||||
|
shown while the app's opaque `html, body, #root` background still won, and
|
||||||
|
appeared on the desktop as a solid dark rectangle until the chunk executed.
|
||||||
|
|
||||||
|
An inline script in index.html would not work: tauri-utils only nonces
|
||||||
|
`script[src^='http']` (html.rs:153), so under this app's `script-src 'self'`
|
||||||
|
an inline script is blocked in a release build while working fine in dev.
|
||||||
|
|
||||||
|
`data-astrbot-pet` is what src/App.tsx already reads to select the pet view,
|
||||||
|
so no routing change is needed.
|
||||||
|
-->
|
||||||
|
<html lang="zh-CN" class="pet-view" data-astrbot-pet="true">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<meta name="color-scheme" content="dark light" />
|
||||||
|
<title>AstrBot Pet</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|
@ -53,7 +53,7 @@ struct MonitorInfo {
|
||||||
is_primary: bool,
|
is_primary: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||||
struct PetWindowPreferences {
|
struct PetWindowPreferences {
|
||||||
position_mode: pet::PetPositionMode,
|
position_mode: pet::PetPositionMode,
|
||||||
|
|
@ -62,6 +62,70 @@ struct PetWindowPreferences {
|
||||||
game_mode: bool,
|
game_mode: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Default for PetWindowPreferences {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
position_mode: pet::PetPositionMode::Edge,
|
||||||
|
monitor_index: None,
|
||||||
|
// Product baseline: the floating pet does not take the taskbar and
|
||||||
|
// is not topmost by default (docs/implementation-queue.md, Q6
|
||||||
|
// acceptance). Tracked as F-35.
|
||||||
|
always_on_top: false,
|
||||||
|
game_mode: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PetWindowPreferences {
|
||||||
|
/// The monitor to place the pet on, clamped to what is actually attached.
|
||||||
|
///
|
||||||
|
/// `None` means "wherever the pet already is", which on a fresh session is
|
||||||
|
/// the first monitor. A stored index outliving the monitor it named — a
|
||||||
|
/// display unplugged mid-session — clamps rather than placing the pet
|
||||||
|
/// nowhere.
|
||||||
|
fn monitor_slot(&self, monitor_count: usize) -> usize {
|
||||||
|
self.monitor_index
|
||||||
|
.unwrap_or(0)
|
||||||
|
.min(monitor_count.saturating_sub(1))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Game mode pins the pet to a screen edge regardless of the stored mode,
|
||||||
|
/// so it cannot end up over the middle of a fullscreen game.
|
||||||
|
fn effective_position_mode(&self) -> pet::PetPositionMode {
|
||||||
|
if self.game_mode {
|
||||||
|
pet::PetPositionMode::Edge
|
||||||
|
} else {
|
||||||
|
self.position_mode
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The pet window's last applied preferences, for the whole session.
|
||||||
|
///
|
||||||
|
/// The pet window is shown and hidden repeatedly, and every show has to place
|
||||||
|
/// it somewhere. With nothing stored, `reveal_pet_window` had to invent an
|
||||||
|
/// answer, and it hard-coded the first monitor, the safe edge and always-on-top
|
||||||
|
/// — silently reverting whatever the user had chosen on the pet page. Not yet
|
||||||
|
/// persisted across restarts; that is F-75.
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
struct PetPreferencesState(std::sync::Mutex<PetWindowPreferences>);
|
||||||
|
|
||||||
|
impl PetPreferencesState {
|
||||||
|
fn snapshot(&self) -> PetWindowPreferences {
|
||||||
|
self.0
|
||||||
|
.lock()
|
||||||
|
.map(|guard| *guard)
|
||||||
|
.unwrap_or_else(|poisoned| *poisoned.into_inner())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn store(&self, preferences: PetWindowPreferences) {
|
||||||
|
match self.0.lock() {
|
||||||
|
Ok(mut guard) => *guard = preferences,
|
||||||
|
Err(poisoned) => *poisoned.into_inner() = preferences,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||||
struct NetworkDiagnosticRequest {
|
struct NetworkDiagnosticRequest {
|
||||||
|
|
@ -343,14 +407,23 @@ fn open_pet_window_inner(app: &AppHandle) -> Result<(), String> {
|
||||||
/// Shared by both paths so a rebuilt window is treated exactly like one that
|
/// Shared by both paths so a rebuilt window is treated exactly like one that
|
||||||
/// was only hidden.
|
/// was only hidden.
|
||||||
fn reveal_pet_window(app: &AppHandle, window: &tauri::WebviewWindow) -> Result<(), String> {
|
fn reveal_pet_window(app: &AppHandle, window: &tauri::WebviewWindow) -> Result<(), String> {
|
||||||
|
// Read the session's preferences rather than re-deciding. This used to
|
||||||
|
// force always-on-top, the first monitor and the safe edge on every show,
|
||||||
|
// which reverted the user's choices each time the pet was reopened.
|
||||||
|
let preferences = app.state::<PetPreferencesState>().snapshot();
|
||||||
window
|
window
|
||||||
.set_always_on_top(true)
|
.set_always_on_top(preferences.always_on_top)
|
||||||
.map_err(|error| error.to_string())?;
|
.map_err(|error| error.to_string())?;
|
||||||
let monitors = available_monitor_info(app)?;
|
let monitors = available_monitor_info(app)?;
|
||||||
if let Some(monitor) = monitors.first() {
|
if let Some(monitor) = monitors.get(preferences.monitor_slot(monitors.len())) {
|
||||||
place_pet_on_monitor(window, monitor, pet::PetPositionMode::Edge)?;
|
place_pet_on_monitor(window, monitor, preferences.effective_position_mode())?;
|
||||||
}
|
}
|
||||||
window.show().map_err(|error| error.to_string())?;
|
window.show().map_err(|error| error.to_string())?;
|
||||||
|
// The pet webview is created once and only hidden between showings, so its
|
||||||
|
// mount-time effects never run again. Without this it would keep displaying
|
||||||
|
// the connection state it read at startup for the rest of the session.
|
||||||
|
app.emit_to(PET_WINDOW_ID, "pet-window-revealed", ())
|
||||||
|
.map_err(|error| error.to_string())?;
|
||||||
|
|
||||||
// At default level on purpose. The window is transparent and undecorated,
|
// At default level on purpose. The window is transparent and undecorated,
|
||||||
// so "it did not appear" covers a window placed off-screen, a window that
|
// so "it did not appear" covers a window placed off-screen, a window that
|
||||||
|
|
@ -384,6 +457,9 @@ fn set_pet_window_preferences(
|
||||||
app: AppHandle,
|
app: AppHandle,
|
||||||
preferences: PetWindowPreferences,
|
preferences: PetWindowPreferences,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
|
// Stored before the window lookup so a choice made while the pet is hidden
|
||||||
|
// still applies the next time it is shown.
|
||||||
|
app.state::<PetPreferencesState>().store(preferences);
|
||||||
let Some(window) = app.get_webview_window(PET_WINDOW_ID) else {
|
let Some(window) = app.get_webview_window(PET_WINDOW_ID) else {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
};
|
};
|
||||||
|
|
@ -391,21 +467,23 @@ fn set_pet_window_preferences(
|
||||||
.set_always_on_top(preferences.always_on_top)
|
.set_always_on_top(preferences.always_on_top)
|
||||||
.map_err(|error| error.to_string())?;
|
.map_err(|error| error.to_string())?;
|
||||||
let monitors = available_monitor_info(&app)?;
|
let monitors = available_monitor_info(&app)?;
|
||||||
let index = preferences
|
if let Some(monitor) = monitors.get(preferences.monitor_slot(monitors.len())) {
|
||||||
.monitor_index
|
place_pet_on_monitor(&window, monitor, preferences.effective_position_mode())?;
|
||||||
.unwrap_or(0)
|
|
||||||
.min(monitors.len().saturating_sub(1));
|
|
||||||
let mode = if preferences.game_mode {
|
|
||||||
pet::PetPositionMode::Edge
|
|
||||||
} else {
|
|
||||||
preferences.position_mode
|
|
||||||
};
|
|
||||||
if let Some(monitor) = monitors.get(index) {
|
|
||||||
place_pet_on_monitor(&window, monitor, mode)?;
|
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Reports the pet window's current preferences.
|
||||||
|
///
|
||||||
|
/// Without this the pet page initialised its controls from hard-coded literals,
|
||||||
|
/// so navigating away and back showed monitor 1 / edge / always-on-top no matter
|
||||||
|
/// what the window was actually doing — and the next edit re-sent those stale
|
||||||
|
/// values as if the user had chosen them.
|
||||||
|
#[tauri::command]
|
||||||
|
fn pet_window_preferences(app: AppHandle) -> PetWindowPreferences {
|
||||||
|
app.state::<PetPreferencesState>().snapshot()
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
fn inspect_foreground_window() -> Result<windows::foreground_window::ForegroundWindowSummary, String>
|
fn inspect_foreground_window() -> Result<windows::foreground_window::ForegroundWindowSummary, String>
|
||||||
{
|
{
|
||||||
|
|
@ -510,8 +588,14 @@ fn show_pet_context_menu(app: AppHandle) -> Result<(), String> {
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
.map_err(|error| error.to_string())?;
|
.map_err(|error| error.to_string())?;
|
||||||
|
// Only a visible window can own a popup menu: Win32 requires the owner to
|
||||||
|
// be brought to the foreground, which cannot happen for a hidden one. The
|
||||||
|
// pet window used to be destroyed while the pet rendered inside the app, so
|
||||||
|
// this fell through to the main window on its own; now that it is merely
|
||||||
|
// hidden, the visibility test has to be explicit.
|
||||||
let window = app
|
let window = app
|
||||||
.get_webview_window(PET_WINDOW_ID)
|
.get_webview_window(PET_WINDOW_ID)
|
||||||
|
.filter(|window| window.is_visible().unwrap_or(false))
|
||||||
.or_else(|| app.get_webview_window("main"))
|
.or_else(|| app.get_webview_window("main"))
|
||||||
.ok_or_else(|| "pet context menu window is unavailable".to_owned())?;
|
.ok_or_else(|| "pet context menu window is unavailable".to_owned())?;
|
||||||
window.popup_menu(&menu).map_err(|error| error.to_string())
|
window.popup_menu(&menu).map_err(|error| error.to_string())
|
||||||
|
|
@ -591,6 +675,7 @@ pub fn run() {
|
||||||
std::fs::write(&session_marker, std::process::id().to_string())?;
|
std::fs::write(&session_marker, std::process::id().to_string())?;
|
||||||
app.manage(SessionMarker(session_marker));
|
app.manage(SessionMarker(session_marker));
|
||||||
app.manage(RuntimeGuards::new());
|
app.manage(RuntimeGuards::new());
|
||||||
|
app.manage(PetPreferencesState::default());
|
||||||
app.manage(DualSlotRuntime::new());
|
app.manage(DualSlotRuntime::new());
|
||||||
|
|
||||||
let startup_handle = app.handle().clone();
|
let startup_handle = app.handle().clone();
|
||||||
|
|
@ -696,6 +781,7 @@ pub fn run() {
|
||||||
show_pet_context_menu,
|
show_pet_context_menu,
|
||||||
list_monitor_geometries,
|
list_monitor_geometries,
|
||||||
set_pet_window_preferences,
|
set_pet_window_preferences,
|
||||||
|
pet_window_preferences,
|
||||||
inspect_foreground_window,
|
inspect_foreground_window,
|
||||||
inspect_process,
|
inspect_process,
|
||||||
check_network_target,
|
check_network_target,
|
||||||
|
|
@ -727,3 +813,74 @@ pub fn run() {
|
||||||
.run(tauri::generate_context!())
|
.run(tauri::generate_context!())
|
||||||
.expect("failed to run AstrBot Desktop");
|
.expect("failed to run AstrBot Desktop");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
/// Product red line F-35: the floating pet must not be topmost by default.
|
||||||
|
///
|
||||||
|
/// `reveal_pet_window` used to call `set_always_on_top(true)` outright, so
|
||||||
|
/// every show re-pinned the window even after the user turned it off. The
|
||||||
|
/// default now comes from here, which makes this the sentinel for it.
|
||||||
|
#[test]
|
||||||
|
fn the_pet_is_not_topmost_by_default() {
|
||||||
|
assert!(!PetWindowPreferences::default().always_on_top);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_pet_defaults_to_the_safe_edge_of_the_first_monitor() {
|
||||||
|
let preferences = PetWindowPreferences::default();
|
||||||
|
assert_eq!(preferences.position_mode, pet::PetPositionMode::Edge);
|
||||||
|
assert_eq!(preferences.monitor_index, None);
|
||||||
|
assert_eq!(preferences.monitor_slot(2), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn game_mode_pins_the_pet_to_an_edge_whatever_the_stored_mode() {
|
||||||
|
let free = PetWindowPreferences {
|
||||||
|
position_mode: pet::PetPositionMode::Free,
|
||||||
|
game_mode: false,
|
||||||
|
..PetWindowPreferences::default()
|
||||||
|
};
|
||||||
|
assert_eq!(free.effective_position_mode(), pet::PetPositionMode::Free);
|
||||||
|
assert_eq!(
|
||||||
|
PetWindowPreferences {
|
||||||
|
game_mode: true,
|
||||||
|
..free
|
||||||
|
}
|
||||||
|
.effective_position_mode(),
|
||||||
|
pet::PetPositionMode::Edge
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A display unplugged after the choice was made must not leave the pet
|
||||||
|
/// unplaced, and must not index past the monitor list.
|
||||||
|
#[test]
|
||||||
|
fn a_stored_monitor_index_clamps_to_the_attached_displays() {
|
||||||
|
let on_third = PetWindowPreferences {
|
||||||
|
monitor_index: Some(2),
|
||||||
|
..PetWindowPreferences::default()
|
||||||
|
};
|
||||||
|
assert_eq!(on_third.monitor_slot(3), 2);
|
||||||
|
assert_eq!(on_third.monitor_slot(2), 1);
|
||||||
|
assert_eq!(on_third.monitor_slot(1), 0);
|
||||||
|
assert_eq!(on_third.monitor_slot(0), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The pet window is hidden rather than destroyed, and a preference set
|
||||||
|
/// while it is hidden has to survive until the next reveal reads it.
|
||||||
|
#[test]
|
||||||
|
fn stored_preferences_outlive_the_window_being_hidden() {
|
||||||
|
let state = PetPreferencesState::default();
|
||||||
|
assert!(!state.snapshot().always_on_top);
|
||||||
|
let chosen = PetWindowPreferences {
|
||||||
|
position_mode: pet::PetPositionMode::Free,
|
||||||
|
monitor_index: Some(1),
|
||||||
|
always_on_top: true,
|
||||||
|
game_mode: false,
|
||||||
|
};
|
||||||
|
state.store(chosen);
|
||||||
|
assert_eq!(state.snapshot(), chosen);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -26,14 +26,15 @@
|
||||||
{
|
{
|
||||||
"label": "desktop-pet",
|
"label": "desktop-pet",
|
||||||
"title": "AstrBot Pet",
|
"title": "AstrBot Pet",
|
||||||
"url": "index.html?view=pet",
|
"url": "pet.html",
|
||||||
"width": 180,
|
"width": 180,
|
||||||
"height": 220,
|
"height": 220,
|
||||||
"resizable": false,
|
"resizable": false,
|
||||||
"decorations": false,
|
"decorations": false,
|
||||||
"shadow": false,
|
"shadow": false,
|
||||||
"transparent": true,
|
"transparent": true,
|
||||||
"alwaysOnTop": true,
|
"alwaysOnTop": false,
|
||||||
|
"focus": false,
|
||||||
"skipTaskbar": true,
|
"skipTaskbar": true,
|
||||||
"visible": false,
|
"visible": false,
|
||||||
"x": 120,
|
"x": 120,
|
||||||
|
|
|
||||||
35
src/App.tsx
35
src/App.tsx
|
|
@ -11,6 +11,11 @@ import {
|
||||||
} from "react";
|
} from "react";
|
||||||
|
|
||||||
import { errorMessage } from "./lib/errorMessage";
|
import { errorMessage } from "./lib/errorMessage";
|
||||||
|
import {
|
||||||
|
petPositionModeSchema,
|
||||||
|
petWindowPreferencesSchema,
|
||||||
|
type PetPositionMode,
|
||||||
|
} from "./features/pet/types";
|
||||||
import { ChatPanel } from "./features/chat/ChatPanel";
|
import { ChatPanel } from "./features/chat/ChatPanel";
|
||||||
import { StatusBubble } from "./features/chat/StatusBubble";
|
import { StatusBubble } from "./features/chat/StatusBubble";
|
||||||
const ProfileManager = lazy(() =>
|
const ProfileManager = lazy(() =>
|
||||||
|
|
@ -548,8 +553,8 @@ function PetPage({
|
||||||
}>
|
}>
|
||||||
>([]);
|
>([]);
|
||||||
const [monitorIndex, setMonitorIndex] = useState(0);
|
const [monitorIndex, setMonitorIndex] = useState(0);
|
||||||
const [positionMode, setPositionMode] = useState("edge");
|
const [positionMode, setPositionMode] = useState<PetPositionMode>("edge");
|
||||||
const [alwaysOnTop, setAlwaysOnTop] = useState(true);
|
const [alwaysOnTop, setAlwaysOnTop] = useState(false);
|
||||||
const [gameMode, setGameMode] = useState(false);
|
const [gameMode, setGameMode] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|
@ -558,9 +563,31 @@ function PetPage({
|
||||||
.catch(() => setMonitors([]));
|
.catch(() => setMonitors([]));
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// Adopt what the window is actually doing. These controls used to start from
|
||||||
|
// literals, so leaving the page and coming back showed monitor 1 / safe edge
|
||||||
|
// / always-on-top regardless of the truth — and because every edit re-sends
|
||||||
|
// the whole payload, the next single change pushed those wrong values back
|
||||||
|
// onto the window as if the user had chosen them.
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
void invoke<unknown>("pet_window_preferences")
|
||||||
|
.then((value) => {
|
||||||
|
if (cancelled) return;
|
||||||
|
const preferences = petWindowPreferencesSchema.parse(value);
|
||||||
|
setMonitorIndex(preferences.monitorIndex ?? 0);
|
||||||
|
setPositionMode(preferences.positionMode);
|
||||||
|
setAlwaysOnTop(preferences.alwaysOnTop);
|
||||||
|
setGameMode(preferences.gameMode);
|
||||||
|
})
|
||||||
|
.catch(() => undefined);
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
const applyPetPreferences = (
|
const applyPetPreferences = (
|
||||||
next: Partial<{
|
next: Partial<{
|
||||||
positionMode: string;
|
positionMode: PetPositionMode;
|
||||||
monitorIndex: number;
|
monitorIndex: number;
|
||||||
alwaysOnTop: boolean;
|
alwaysOnTop: boolean;
|
||||||
gameMode: boolean;
|
gameMode: boolean;
|
||||||
|
|
@ -652,7 +679,7 @@ function PetPage({
|
||||||
<select
|
<select
|
||||||
value={positionMode}
|
value={positionMode}
|
||||||
onChange={(event) => {
|
onChange={(event) => {
|
||||||
const next = event.target.value;
|
const next = petPositionModeSchema.parse(event.target.value);
|
||||||
setPositionMode(next);
|
setPositionMode(next);
|
||||||
applyPetPreferences({ positionMode: next });
|
applyPetPreferences({ positionMode: next });
|
||||||
}}
|
}}
|
||||||
|
|
|
||||||
|
|
@ -4,10 +4,9 @@ import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
|
||||||
import { errorMessage } from "../../lib/errorMessage";
|
import { errorMessage } from "../../lib/errorMessage";
|
||||||
import {
|
import { boundRuntimeEventSchema } from "../chat/types";
|
||||||
boundRuntimeEventSchema,
|
import { petStateForConnection } from "./petState";
|
||||||
connectionRuntimeStatusSchema,
|
import { petWindowPreferencesSchema } from "./types";
|
||||||
} from "../chat/types";
|
|
||||||
import aemeathSpritesheet from "./assets/aemeath/aemeath-spritesheet.png?inline";
|
import aemeathSpritesheet from "./assets/aemeath/aemeath-spritesheet.png?inline";
|
||||||
|
|
||||||
const AEMEATH_SPRITESHEET = aemeathSpritesheet;
|
const AEMEATH_SPRITESHEET = aemeathSpritesheet;
|
||||||
|
|
@ -37,12 +36,6 @@ export function DesktopPetView({ embedded = false }: { embedded?: boolean }) {
|
||||||
const spriteImageRef = useRef<HTMLImageElement | null>(null);
|
const spriteImageRef = useRef<HTMLImageElement | null>(null);
|
||||||
const spriteCanvasRef = useRef<HTMLCanvasElement | 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);
|
const completionTimerRef = useRef<number | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|
@ -115,55 +108,61 @@ export function DesktopPetView({ embedded = false }: { embedded?: boolean }) {
|
||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// Re-read on every reveal, not only on mount. The pet window is created once
|
||||||
|
// and merely hidden between showings, so a connection that comes up or drops
|
||||||
|
// while the pet is hidden would otherwise leave it animating a state that has
|
||||||
|
// not been true since startup.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
void invoke<unknown>("connection_runtime_status")
|
let unlisten: (() => void) | undefined;
|
||||||
.then((value) => {
|
|
||||||
if (cancelled) return;
|
const refresh = () => {
|
||||||
try {
|
void invoke<unknown>("connection_runtime_status")
|
||||||
const result = connectionRuntimeStatusSchema.parse(value);
|
.then((value) => {
|
||||||
const state = result.companion.state;
|
if (cancelled) return;
|
||||||
if (
|
setState(petStateForConnection(value));
|
||||||
state === "authExpired" ||
|
})
|
||||||
state === "fatalError" ||
|
.catch(() => {
|
||||||
state === "incompatible"
|
if (!cancelled) setState("idle");
|
||||||
) {
|
});
|
||||||
setState("error");
|
};
|
||||||
} else if (
|
|
||||||
state === "syncing" ||
|
refresh();
|
||||||
state === "connecting" ||
|
void listen("pet-window-revealed", refresh)
|
||||||
state === "authenticating"
|
.then((cleanup) => {
|
||||||
) {
|
if (cancelled) {
|
||||||
setState("working");
|
cleanup();
|
||||||
} else if (state === "reconnecting") {
|
} else {
|
||||||
setState("speaking");
|
unlisten = cleanup;
|
||||||
} else if (state === "disconnected" || state === "offline") {
|
|
||||||
setState("resting");
|
|
||||||
} else {
|
|
||||||
setState("idle");
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
setState("idle");
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch(() => undefined);
|
||||||
if (!cancelled) setState("idle");
|
|
||||||
});
|
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
|
unlisten?.();
|
||||||
|
unlisten = undefined;
|
||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// Read the stored preferences and change only game mode. Sending a whole
|
||||||
|
// hard-coded payload reverted the monitor and always-on-top choices made on
|
||||||
|
// the pet page every time game mode was toggled, and re-pinned the window
|
||||||
|
// topmost against the product baseline. The embedded copy owns no window at
|
||||||
|
// all, so it must not write preferences (F-35).
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void invoke("set_pet_window_preferences", {
|
if (embedded) return;
|
||||||
preferences: {
|
void invoke<unknown>("pet_window_preferences")
|
||||||
positionMode: "edge",
|
.then((value) =>
|
||||||
monitorIndex: 0,
|
invoke("set_pet_window_preferences", {
|
||||||
alwaysOnTop: true,
|
preferences: {
|
||||||
gameMode,
|
...petWindowPreferencesSchema.parse(value),
|
||||||
},
|
gameMode,
|
||||||
}).catch(() => undefined);
|
},
|
||||||
}, [gameMode]);
|
}),
|
||||||
|
)
|
||||||
|
.catch(() => undefined);
|
||||||
|
}, [embedded, gameMode]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setFrameIndex(0);
|
setFrameIndex(0);
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,46 @@
|
||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The pet window's transparency rests entirely on `pet.html` carrying its
|
||||||
|
* marker attributes statically, and on the Tauri window config pointing at that
|
||||||
|
* file. Neither link is checked by the compiler: drop the attribute and the pet
|
||||||
|
* silently becomes an opaque rectangle, point the window back at `index.html`
|
||||||
|
* and the same thing happens with the file still sitting there looking correct.
|
||||||
|
*/
|
||||||
|
describe("the pet window entry point", () => {
|
||||||
|
const html = readFileSync("pet.html", "utf8");
|
||||||
|
|
||||||
|
it("marks the document before any script runs", () => {
|
||||||
|
const openingTag = html.match(/<html[^>]*>/)?.[0] ?? "";
|
||||||
|
// Not `html.includes(...)`: the point is that these sit on the <html> tag
|
||||||
|
// itself, which is parsed before the stylesheet can paint anything.
|
||||||
|
expect(openingTag).toContain('class="pet-view"');
|
||||||
|
expect(openingTag).toContain('data-astrbot-pet="true"');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("carries no inline script, which the app's CSP would block", () => {
|
||||||
|
// tauri-utils only nonces `script[src^='http']`, so an inline script is
|
||||||
|
// rejected under `script-src 'self'` in a release build while working in
|
||||||
|
// dev. Anything added here has to keep an src.
|
||||||
|
for (const tag of html.match(/<script[^>]*>/g) ?? []) {
|
||||||
|
expect(tag).toMatch(/\ssrc=/);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is the file the pet window actually loads", () => {
|
||||||
|
const config = JSON.parse(
|
||||||
|
readFileSync("src-tauri/tauri.conf.json", "utf8"),
|
||||||
|
) as { app: { windows: Array<Record<string, unknown>> } };
|
||||||
|
const pet = config.app.windows.find(
|
||||||
|
(window) => window.label === "desktop-pet",
|
||||||
|
);
|
||||||
|
expect(pet?.url).toBe("pet.html");
|
||||||
|
expect(pet?.transparent).toBe(true);
|
||||||
|
// Product baseline F-35, and the reason the pet stopped stealing keystrokes
|
||||||
|
// from the main window when it is shown.
|
||||||
|
expect(pet?.alwaysOnTop).toBe(false);
|
||||||
|
expect(pet?.focus).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -0,0 +1,40 @@
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import { petStateForConnection } from "./petState";
|
||||||
|
|
||||||
|
const snapshot = (state: string) => ({
|
||||||
|
companion: {
|
||||||
|
slot: "companion",
|
||||||
|
profileId: null,
|
||||||
|
transport: null,
|
||||||
|
state,
|
||||||
|
serverInstanceId: null,
|
||||||
|
activeSessionId: null,
|
||||||
|
lastError: null,
|
||||||
|
},
|
||||||
|
operations: {
|
||||||
|
slot: "operations",
|
||||||
|
profileId: null,
|
||||||
|
transport: null,
|
||||||
|
state: "disconnected",
|
||||||
|
serverInstanceId: null,
|
||||||
|
activeSessionId: null,
|
||||||
|
lastError: null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("petStateForConnection", () => {
|
||||||
|
it("distinguishes the states the pet is meant to communicate", () => {
|
||||||
|
expect(petStateForConnection(snapshot("connected"))).toBe("idle");
|
||||||
|
expect(petStateForConnection(snapshot("connecting"))).toBe("working");
|
||||||
|
expect(petStateForConnection(snapshot("reconnecting"))).toBe("speaking");
|
||||||
|
expect(petStateForConnection(snapshot("disconnected"))).toBe("resting");
|
||||||
|
expect(petStateForConnection(snapshot("authExpired"))).toBe("error");
|
||||||
|
expect(petStateForConnection(snapshot("fatalError"))).toBe("error");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to idle rather than throwing at an unusable payload", () => {
|
||||||
|
expect(petStateForConnection(undefined)).toBe("idle");
|
||||||
|
expect(petStateForConnection({ companion: {} })).toBe("idle");
|
||||||
|
});
|
||||||
|
});
|
||||||
38
src/features/pet/petState.ts
普通文件
38
src/features/pet/petState.ts
普通文件
|
|
@ -0,0 +1,38 @@
|
||||||
|
import { connectionRuntimeStatusSchema } from "../chat/types";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Maps a companion connection state onto the pet animation that shows it.
|
||||||
|
*
|
||||||
|
* Its own module rather than a second export from `DesktopPetView`, so Fast
|
||||||
|
* Refresh keeps working for that component. Worth isolating on its own merits:
|
||||||
|
* this mapping is the whole of what the floating pet communicates about the
|
||||||
|
* connection, and it silently went stale for an entire session before the
|
||||||
|
* reveal event gave it a reason to run again.
|
||||||
|
*/
|
||||||
|
export function petStateForConnection(
|
||||||
|
value: unknown,
|
||||||
|
): "idle" | "working" | "resting" | "speaking" | "error" {
|
||||||
|
let state;
|
||||||
|
try {
|
||||||
|
state = connectionRuntimeStatusSchema.parse(value).companion.state;
|
||||||
|
} catch {
|
||||||
|
return "idle";
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
state === "authExpired" ||
|
||||||
|
state === "fatalError" ||
|
||||||
|
state === "incompatible"
|
||||||
|
) {
|
||||||
|
return "error";
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
state === "syncing" ||
|
||||||
|
state === "connecting" ||
|
||||||
|
state === "authenticating"
|
||||||
|
) {
|
||||||
|
return "working";
|
||||||
|
}
|
||||||
|
if (state === "reconnecting") return "speaking";
|
||||||
|
if (state === "disconnected" || state === "offline") return "resting";
|
||||||
|
return "idle";
|
||||||
|
}
|
||||||
|
|
@ -10,12 +10,28 @@ export const companionStateSchema = z.enum([
|
||||||
]);
|
]);
|
||||||
|
|
||||||
export const petDisplayModeSchema = z.enum(["app-ui", "desktop-floating"]);
|
export const petDisplayModeSchema = z.enum(["app-ui", "desktop-floating"]);
|
||||||
|
|
||||||
|
// "followMainWindow", not "follow-main-window": the Rust `PetPositionMode` is
|
||||||
|
// `rename_all = "camelCase"`. The kebab-case spelling that used to be here was
|
||||||
|
// only ever read by `companionPresentationSettingsSchema`, which nothing
|
||||||
|
// consumes, so the mismatch never reached the IPC boundary.
|
||||||
export const petPositionModeSchema = z.enum([
|
export const petPositionModeSchema = z.enum([
|
||||||
"free",
|
"free",
|
||||||
"edge",
|
"edge",
|
||||||
"monitor",
|
"monitor",
|
||||||
"follow-main-window",
|
"followMainWindow",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
// Mirrors the Rust `PetWindowPreferences`, which is `deny_unknown_fields`, so a
|
||||||
|
// payload built from this schema is accepted verbatim on the way back.
|
||||||
|
export const petWindowPreferencesSchema = z
|
||||||
|
.object({
|
||||||
|
positionMode: petPositionModeSchema,
|
||||||
|
monitorIndex: z.number().int().nonnegative().nullable(),
|
||||||
|
alwaysOnTop: z.boolean(),
|
||||||
|
gameMode: z.boolean(),
|
||||||
|
})
|
||||||
|
.strict();
|
||||||
export const bubbleClickTargetSchema = z.enum(["main", "quick"]);
|
export const bubbleClickTargetSchema = z.enum(["main", "quick"]);
|
||||||
|
|
||||||
export const petMovementSchema = z.enum([
|
export const petMovementSchema = z.enum([
|
||||||
|
|
@ -66,6 +82,8 @@ export const companionPresentationSettingsSchema = z
|
||||||
.strict();
|
.strict();
|
||||||
|
|
||||||
export type CompanionState = z.infer<typeof companionStateSchema>;
|
export type CompanionState = z.infer<typeof companionStateSchema>;
|
||||||
|
export type PetPositionMode = z.infer<typeof petPositionModeSchema>;
|
||||||
|
export type PetWindowPreferences = z.infer<typeof petWindowPreferencesSchema>;
|
||||||
export type PetMovement = z.infer<typeof petMovementSchema>;
|
export type PetMovement = z.infer<typeof petMovementSchema>;
|
||||||
export type PetPackManifest = z.infer<typeof petPackManifestSchema>;
|
export type PetPackManifest = z.infer<typeof petPackManifestSchema>;
|
||||||
export type CompanionPresentationSettings = z.infer<
|
export type CompanionPresentationSettings = z.infer<
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,17 @@ export default defineConfig({
|
||||||
base: "./",
|
base: "./",
|
||||||
plugins: [react()],
|
plugins: [react()],
|
||||||
clearScreen: false,
|
clearScreen: false,
|
||||||
|
build: {
|
||||||
|
rollupOptions: {
|
||||||
|
// pet.html is a second entry so the pet webview can carry `pet-view` on
|
||||||
|
// <html> statically. Without listing it here the release bundle would not
|
||||||
|
// contain it and the pet window would 404.
|
||||||
|
input: {
|
||||||
|
main: "index.html",
|
||||||
|
pet: "pet.html",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
server: {
|
server: {
|
||||||
host: host ?? "127.0.0.1",
|
host: host ?? "127.0.0.1",
|
||||||
port: 1420,
|
port: 1420,
|
||||||
|
|
|
||||||
正在加载…
添加表格
在新工单中引用