feat(window): persist quick chat geometry
一些检测仍在等待运行
ci / Portable quality checks (push) Waiting to run
ci / Windows Tauri build (push) Waiting to run

这个提交存在于:
YokiiroBW 2026-07-20 14:59:55 +08:00
父节点 06e0b411ea
当前提交 e28614ad6a
共有 5 个文件被更改,包括 292 次插入 和 10 次删除

查看文件

@ -75,7 +75,8 @@ remote_username 用于远端聊天身份和会话命名,不作为本机权限
### Q4:快速聊天窗口
- 增加独立 Tauri 窗口,初始尺寸适合快速回复。
- 增加独立 Tauri 窗口,初始尺寸适合快速回复。
- 已完成:窗口单实例、拖动/调整大小、SQLite 几何状态持久化、屏幕工作区夹紧和显示器标识恢复。
- 支持拖动、调整大小、关闭后恢复位置和尺寸。
- 与主窗口共享 `ChatRuntime`、会话选择、消息缓存、未读数和发送队列。
- 设置中只提供一个快速聊天目标:`companion` 或 `operations`,二选一。

查看文件

@ -150,3 +150,12 @@ Still not claimed complete: automatic startup activation, real Tauri multi-windo
- Added slot-scoped remote session discovery and sticky session switching IPC.
- ChatPanel now displays remote sessions and reloads history after switching; message filtering includes sessionId.
- Validation: Rust workspace tests, Clippy, TypeScript, ESLint, Vitest, and Vite build passed.
## 2026-07-20: Q4 quick-chat window geometry persistence
- Completed: added the `window_states` SQLite table (schema v7) for quick-chat position, size, and monitor identity.
- Completed: restore geometry on open; fall back to the current primary monitor and clamp to its work area when a monitor is unavailable or the saved position is invalid.
- Completed: save geometry on move, resize, and close-to-tray; keep the quick window single-instance without destroying the shared chat runtime.
- Completed: added window bounds, monitor clamping, and database round-trip tests.
- Validation: Rust format, Clippy with warnings denied, and `astrbot-desktop` unit tests pass.
- Next: finish the remaining quick-window/status-bubble acceptance work, then continue with the pet asset and multi-monitor controller foundation.

查看文件

@ -7,7 +7,7 @@ use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use rusqlite::{Connection, OptionalExtension, params};
use thiserror::Error;
pub const CURRENT_SCHEMA_VERSION: u32 = 6;
pub const CURRENT_SCHEMA_VERSION: u32 = 7;
pub struct ApplicationDatabase {
store: Mutex<ProfileMessageStore>,
@ -102,6 +102,26 @@ impl ApplicationDatabase {
.map_err(|_| DatabaseError::LockPoisoned)?
.list_chat_messages(profile_id, server_instance_id, session_id, limit)
}
pub fn load_window_state(
&self,
window_id: &str,
) -> Result<Option<crate::quick_window::QuickWindowState>, DatabaseError> {
self.store
.lock()
.map_err(|_| DatabaseError::LockPoisoned)?
.load_window_state(window_id)
}
pub fn save_window_state(
&self,
window_id: &str,
state: &crate::quick_window::QuickWindowState,
) -> Result<(), DatabaseError> {
self.store
.lock()
.map_err(|_| DatabaseError::LockPoisoned)?
.save_window_state(window_id, state)
}
}
pub struct ProfileMessageStore {
@ -109,6 +129,50 @@ pub struct ProfileMessageStore {
}
impl ProfileMessageStore {
pub fn load_window_state(
&self,
window_id: &str,
) -> Result<Option<crate::quick_window::QuickWindowState>, DatabaseError> {
self.connection
.query_row(
"SELECT x, y, width, height, monitor_name FROM window_states WHERE window_id = ?1",
params![window_id],
|row| {
Ok(crate::quick_window::QuickWindowState {
x: row.get(0)?,
y: row.get(1)?,
width: row.get::<_, i64>(2)? as u32,
height: row.get::<_, i64>(3)? as u32,
monitor_name: row.get(4)?,
})
},
)
.optional()
.map_err(DatabaseError::from)
}
pub fn save_window_state(
&self,
window_id: &str,
state: &crate::quick_window::QuickWindowState,
) -> Result<(), DatabaseError> {
let updated_at = OffsetDateTime::now_utc()
.format(&Rfc3339)
.map_err(|_| DatabaseError::InvalidStoredMessage)?;
self.connection.execute(
"INSERT INTO window_states (window_id, x, y, width, height, monitor_name, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) ON CONFLICT(window_id) DO UPDATE SET x = excluded.x, y = excluded.y, width = excluded.width, height = excluded.height, monitor_name = excluded.monitor_name, updated_at = excluded.updated_at",
params![
window_id,
state.x,
state.y,
state.width,
state.height,
state.monitor_name,
updated_at,
],
)?;
Ok(())
}
pub fn list_chat_sessions(
&self,
profile_id: &str,
@ -449,6 +513,14 @@ fn migrate(connection: &mut Connection) -> Result<(), DatabaseError> {
transaction.commit()?;
}
if found <= 6 {
let transaction = connection.transaction()?;
transaction.execute_batch(
"CREATE TABLE IF NOT EXISTS window_states (window_id TEXT PRIMARY KEY NOT NULL, x INTEGER NOT NULL, y INTEGER NOT NULL, width INTEGER NOT NULL, height INTEGER NOT NULL, monitor_name TEXT, updated_at TEXT NOT NULL); PRAGMA user_version = 7;",
)?;
transaction.commit()?;
}
Ok(())
}
@ -797,4 +869,24 @@ mod tests {
Some("B")
);
}
#[test]
fn persists_quick_window_state_round_trip() {
let database = ApplicationDatabase::in_memory().expect("database");
let state = crate::quick_window::QuickWindowState {
x: 120,
y: 240,
width: 520,
height: 700,
monitor_name: Some("DISPLAY1".into()),
};
database
.save_window_state(crate::quick_window::QUICK_WINDOW_ID, &state)
.expect("save window state");
assert_eq!(
database
.load_window_state(crate::quick_window::QUICK_WINDOW_ID)
.expect("load window state"),
Some(state)
);
}
}

查看文件

@ -7,6 +7,7 @@ pub mod networking;
pub mod pet;
pub mod policy;
pub mod profiles;
pub mod quick_window;
pub mod runtime_guards;
pub mod secure_store;
pub mod slots;
@ -15,11 +16,16 @@ pub mod windows;
use database::ApplicationDatabase;
use networking::{DualSlotRuntime, auto_connect_configured_slots};
use policy::ConnectionPolicyStatus;
use quick_window::{
DEFAULT_HEIGHT, DEFAULT_WIDTH, MAX_HEIGHT, MAX_WIDTH, MIN_HEIGHT, MIN_WIDTH, QUICK_WINDOW_ID,
QuickWindowState,
};
use runtime_guards::RuntimeGuards;
use serde::Serialize;
use tauri::{
AppHandle, Manager, WebviewUrl, WebviewWindowBuilder, WindowEvent,
AppHandle, Manager, PhysicalPosition, PhysicalSize, WebviewUrl, WebviewWindowBuilder,
WindowEvent,
menu::{Menu, MenuItem},
tray::TrayIconBuilder,
};
@ -62,14 +68,14 @@ fn open_quick_chat_window(
app: AppHandle,
slot: Option<desktop_protocol::ActiveSlotKind>,
) -> Result<(), String> {
if let Some(window) = app.get_webview_window("quick-chat") {
if let Some(window) = app.get_webview_window(QUICK_WINDOW_ID) {
window.show().map_err(|error| error.to_string())?;
window.set_focus().map_err(|error| error.to_string())?;
return Ok(());
}
WebviewWindowBuilder::new(
&app,
"quick-chat",
QUICK_WINDOW_ID,
WebviewUrl::App(match slot {
Some(desktop_protocol::ActiveSlotKind::Companion) => {
"index.html?view=quick&slot=companion".into()
@ -81,12 +87,70 @@ fn open_quick_chat_window(
}),
)
.title("AstrBot Quick Chat")
.inner_size(420.0, 620.0)
.min_inner_size(320.0, 420.0)
.inner_size(DEFAULT_WIDTH as f64, DEFAULT_HEIGHT as f64)
.min_inner_size(MIN_WIDTH as f64, MIN_HEIGHT as f64)
.max_inner_size(MAX_WIDTH as f64, MAX_HEIGHT as f64)
.resizable(true)
.build()
.map(|_| ())
.map_err(|error| error.to_string())
.map(|window| {
restore_quick_window_state(&window, &app);
})
}
fn restore_quick_window_state(window: &tauri::WebviewWindow, app: &AppHandle) {
let database = app.state::<ApplicationDatabase>();
let Ok(Some(state)) = database.load_window_state(QUICK_WINDOW_ID) else {
return;
};
let state = state.normalized();
let monitor = state
.monitor_name
.as_deref()
.and_then(|name| {
window
.available_monitors()
.ok()?
.into_iter()
.find(|monitor| monitor.name().map(String::as_str) == Some(name))
})
.or_else(|| window.primary_monitor().ok().flatten());
let Some(monitor) = monitor else {
return;
};
let area = monitor.work_area();
let state = state.clamp_to_work_area(
area.position.x,
area.position.y,
area.size.width,
area.size.height,
);
let _ = window.set_size(PhysicalSize::new(state.width, state.height));
let _ = window.set_position(PhysicalPosition::new(state.x, state.y));
}
fn save_quick_window_state(window: &tauri::Window, app: &AppHandle) {
let Ok(position) = window.outer_position() else {
return;
};
let Ok(size) = window.inner_size() else {
return;
};
let monitor_name = window
.current_monitor()
.ok()
.flatten()
.and_then(|monitor| monitor.name().cloned());
let state = QuickWindowState {
x: position.x,
y: position.y,
width: size.width,
height: size.height,
monitor_name,
}
.normalized();
let database = app.state::<ApplicationDatabase>();
let _ = database.save_window_state(QUICK_WINDOW_ID, &state);
}
#[tauri::command]
@ -178,11 +242,20 @@ pub fn run() {
Ok(())
})
.on_window_event(|window, event| {
if let WindowEvent::CloseRequested { api, .. } = event {
.on_window_event(|window, event| match event {
WindowEvent::Moved(_) | WindowEvent::Resized(_) => {
if window.label() == QUICK_WINDOW_ID {
save_quick_window_state(window, window.app_handle());
}
}
WindowEvent::CloseRequested { api, .. } => {
if window.label() == QUICK_WINDOW_ID {
save_quick_window_state(window, window.app_handle());
}
api.prevent_close();
let _ = window.hide();
}
_ => {}
})
.invoke_handler(tauri::generate_handler![
bootstrap_status,

查看文件

@ -0,0 +1,107 @@
use serde::{Deserialize, Serialize};
pub const QUICK_WINDOW_ID: &str = "quick-chat";
pub const DEFAULT_WIDTH: u32 = 420;
pub const DEFAULT_HEIGHT: u32 = 620;
pub const MIN_WIDTH: u32 = 320;
pub const MIN_HEIGHT: u32 = 420;
pub const MAX_WIDTH: u32 = 900;
pub const MAX_HEIGHT: u32 = 1200;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct QuickWindowState {
pub x: i32,
pub y: i32,
pub width: u32,
pub height: u32,
pub monitor_name: Option<String>,
}
impl Default for QuickWindowState {
fn default() -> Self {
Self {
x: 0,
y: 0,
width: DEFAULT_WIDTH,
height: DEFAULT_HEIGHT,
monitor_name: None,
}
}
}
impl QuickWindowState {
pub fn normalized(mut self) -> Self {
self.width = self.width.clamp(MIN_WIDTH, MAX_WIDTH);
self.height = self.height.clamp(MIN_HEIGHT, MAX_HEIGHT);
self
}
pub fn clamp_to_work_area(
mut self,
area_x: i32,
area_y: i32,
area_width: u32,
area_height: u32,
) -> Self {
self = self.normalized();
let width = self.width.min(area_width.max(MIN_WIDTH));
let height = self.height.min(area_height.max(MIN_HEIGHT));
let max_x = area_x + area_width.saturating_sub(width) as i32;
let max_y = area_y + area_height.saturating_sub(height) as i32;
self.width = width;
self.height = height;
self.x = self.x.clamp(area_x, max_x.max(area_x));
self.y = self.y.clamp(area_y, max_y.max(area_y));
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn normalizes_invalid_size() {
let state = QuickWindowState {
x: 10,
y: 20,
width: 1,
height: 50_000,
monitor_name: None,
}
.normalized();
assert_eq!(state.width, MIN_WIDTH);
assert_eq!(state.height, MAX_HEIGHT);
}
#[test]
fn clamps_position_to_work_area() {
let state = QuickWindowState {
x: -900,
y: 9000,
width: 500,
height: 600,
monitor_name: Some("DISPLAY1".into()),
}
.clamp_to_work_area(100, 200, 1600, 900);
assert_eq!(state.x, 100);
assert_eq!(state.y, 500);
assert_eq!(state.monitor_name.as_deref(), Some("DISPLAY1"));
}
#[test]
fn shrinks_window_when_work_area_is_smaller_than_limits() {
let state = QuickWindowState {
width: MAX_WIDTH,
height: MAX_HEIGHT,
..Default::default()
}
.clamp_to_work_area(0, 0, 360, 460);
assert_eq!(state.width, 360);
assert_eq!(state.height, 460);
}
}