diff --git a/CHANGELOG.md b/CHANGELOG.md index 555cf10..1b90a05 100644 --- a/CHANGELOG.md +++ b/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 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 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 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. diff --git a/docs/reports/fix-queue-2026-07-26.md b/docs/reports/fix-queue-2026-07-26.md index c9b977f..a2fe979 100644 --- a/docs/reports/fix-queue-2026-07-26.md +++ b/docs/reports/fix-queue-2026-07-26.md @@ -1,6 +1,7 @@ # 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)。 > 本文中的 `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 排查中提出并被推翻的两条根因_ | ①「重建分支没调 `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"` 静态写在 `` 上。**不能用内联脚本**:`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) 用户询问语音聊天、窗口感知、游戏陪伴是否已有。三项**均在既定产品范围内** @@ -364,22 +393,37 @@ AstrBot 在一次回复中**交错**投递两类 `plain` 帧: 「同文件相邻改动合并进同一批」的编排原则归入 R5;放入 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 · 体验、无障碍与产品红线批 -| ID | 来源 | 位置 | 动作 | -| -------- | ----- | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | -| **F-35** | P2-30 | `DesktopPetView.tsx:139-148`;`tauri.conf.json` | **产品红线**:`alwaysOnTop` 默认改 `false`(隔离基线要求气泡/桌宠不默认置顶);embedded 模式跳过偏好写入;非 embedded 先读既有偏好再增量提交 | -| **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-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-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-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-44** | P2-28 | `ChatPanel.tsx` | 消息列表底部锚点 +"接近底部才跟随";unmount 调 `recognition.stop()` / `speechSynthesis.cancel()`;朗读前 Markdown 转纯文本 | +| ID | 来源 | 位置 | 动作 | +| -------- | ----- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| **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-37** | P2-21 | `ChatPanel.tsx:468-475` | `retryMessage` 增加 `sessionId === activeSessionId` 过滤;`messageOverride` 与 draft 回退解耦 | +| **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-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-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-44** | P2-28 | `ChatPanel.tsx` | 消息列表底部锚点 +"接近底部才跟随";unmount 调 `recognition.stop()` / `speechSynthesis.cancel()`;朗读前 Markdown 转纯文本 | --- diff --git a/pet.html b/pet.html new file mode 100644 index 0000000..a8d1d72 --- /dev/null +++ b/pet.html @@ -0,0 +1,30 @@ + + + + + + + + AstrBot Pet + + +
+ + + diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index cb8bf05..0761a1d 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -53,7 +53,7 @@ struct MonitorInfo { is_primary: bool, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct PetWindowPreferences { position_mode: pet::PetPositionMode, @@ -62,6 +62,70 @@ struct PetWindowPreferences { 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); + +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)] #[serde(rename_all = "camelCase", deny_unknown_fields)] 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 /// was only hidden. 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::().snapshot(); window - .set_always_on_top(true) + .set_always_on_top(preferences.always_on_top) .map_err(|error| error.to_string())?; let monitors = available_monitor_info(app)?; - if let Some(monitor) = monitors.first() { - place_pet_on_monitor(window, monitor, pet::PetPositionMode::Edge)?; + if let Some(monitor) = monitors.get(preferences.monitor_slot(monitors.len())) { + place_pet_on_monitor(window, monitor, preferences.effective_position_mode())?; } 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, // 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, preferences: PetWindowPreferences, ) -> 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::().store(preferences); let Some(window) = app.get_webview_window(PET_WINDOW_ID) else { return Ok(()); }; @@ -391,21 +467,23 @@ fn set_pet_window_preferences( .set_always_on_top(preferences.always_on_top) .map_err(|error| error.to_string())?; let monitors = available_monitor_info(&app)?; - let index = preferences - .monitor_index - .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)?; + if let Some(monitor) = monitors.get(preferences.monitor_slot(monitors.len())) { + place_pet_on_monitor(&window, monitor, preferences.effective_position_mode())?; } 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::().snapshot() +} + #[tauri::command] fn inspect_foreground_window() -> Result { @@ -510,8 +588,14 @@ fn show_pet_context_menu(app: AppHandle) -> Result<(), 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 .get_webview_window(PET_WINDOW_ID) + .filter(|window| window.is_visible().unwrap_or(false)) .or_else(|| app.get_webview_window("main")) .ok_or_else(|| "pet context menu window is unavailable".to_owned())?; window.popup_menu(&menu).map_err(|error| error.to_string()) @@ -591,6 +675,7 @@ pub fn run() { std::fs::write(&session_marker, std::process::id().to_string())?; app.manage(SessionMarker(session_marker)); app.manage(RuntimeGuards::new()); + app.manage(PetPreferencesState::default()); app.manage(DualSlotRuntime::new()); let startup_handle = app.handle().clone(); @@ -696,6 +781,7 @@ pub fn run() { show_pet_context_menu, list_monitor_geometries, set_pet_window_preferences, + pet_window_preferences, inspect_foreground_window, inspect_process, check_network_target, @@ -727,3 +813,74 @@ pub fn run() { .run(tauri::generate_context!()) .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); + } +} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index ba35737..c41277a 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -26,14 +26,15 @@ { "label": "desktop-pet", "title": "AstrBot Pet", - "url": "index.html?view=pet", + "url": "pet.html", "width": 180, "height": 220, "resizable": false, "decorations": false, "shadow": false, "transparent": true, - "alwaysOnTop": true, + "alwaysOnTop": false, + "focus": false, "skipTaskbar": true, "visible": false, "x": 120, diff --git a/src/App.tsx b/src/App.tsx index 6605baf..d62c07a 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -11,6 +11,11 @@ import { } from "react"; import { errorMessage } from "./lib/errorMessage"; +import { + petPositionModeSchema, + petWindowPreferencesSchema, + type PetPositionMode, +} from "./features/pet/types"; import { ChatPanel } from "./features/chat/ChatPanel"; import { StatusBubble } from "./features/chat/StatusBubble"; const ProfileManager = lazy(() => @@ -548,8 +553,8 @@ function PetPage({ }> >([]); const [monitorIndex, setMonitorIndex] = useState(0); - const [positionMode, setPositionMode] = useState("edge"); - const [alwaysOnTop, setAlwaysOnTop] = useState(true); + const [positionMode, setPositionMode] = useState("edge"); + const [alwaysOnTop, setAlwaysOnTop] = useState(false); const [gameMode, setGameMode] = useState(false); useEffect(() => { @@ -558,9 +563,31 @@ function PetPage({ .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("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 = ( next: Partial<{ - positionMode: string; + positionMode: PetPositionMode; monitorIndex: number; alwaysOnTop: boolean; gameMode: boolean; @@ -652,7 +679,7 @@ function PetPage({