Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): keep window size stable when dragging task titles on Windows

zcinta051413845b53f04c
diff --git a/apps/desktop/native/windows-taskbar/src/lib.rs b/apps/desktop/native/windows-taskbar/src/lib.rs
index 6e05faac19..9981214984 100644
--- a/apps/desktop/native/windows-taskbar/src/lib.rs
+++ b/apps/desktop/native/windows-taskbar/src/lib.rs
@@ -5,7 +5,7 @@ use napi_derive::napi;
use windows::{
core::{w, PCWSTR},
Win32::{
- Foundation::{HWND, RPC_E_CHANGED_MODE},
+ Foundation::{HWND, POINT, RECT, RPC_E_CHANGED_MODE},
System::{
Com::{
CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_INPROC_SERVER,
@@ -13,11 +13,13 @@ use windows::{
},
Threading::GetCurrentProcessId,
},
+ Graphics::Gdi::{GetMonitorInfoW, MonitorFromPoint, MONITORINFO, MONITOR_DEFAULTTONEAREST},
UI::{
Shell::{ITaskbarList3, TaskbarList},
WindowsAndMessaging::{
CreateIconFromResourceEx, DestroyIcon, GetWindowThreadProcessId, IsWindow,
- RegisterWindowMessageW, HICON, LR_DEFAULTCOLOR,
+ RegisterWindowMessageW, GetCursorPos, GetWindowRect, SetWindowPos, HICON, LR_DEFAULTCOLOR,
+ SWP_NOACTIVATE, SWP_NOSIZE, SWP_NOZORDER,
},
},
},
@@ -119,6 +121,47 @@ pub fn set_overlay_icon(
}
}
+// Keep drag geometry in physical pixels. Electron's DIP bounds round-trip is
+// not idempotent at fractional DPI, even when the logical size is held fixed.
+#[napi(object)]
+pub struct WindowDragOffset {
+ pub x: i32,
+ pub y: i32,
+}
+
+#[napi]
+pub fn window_drag_offset(handle: Buffer) -> napi::Result<WindowDragOffset> {
+ let window = window_from_bytes(&handle)?;
+ let mut cursor = POINT::default();
+ let mut bounds = RECT::default();
+ unsafe {
+ GetCursorPos(&mut cursor).map_err(failure)?;
+ GetWindowRect(window, &mut bounds).map_err(failure)?;
+ }
+ Ok(WindowDragOffset { x: cursor.x - bounds.left, y: cursor.y - bounds.top })
+}
+
+#[napi]
+pub fn move_window_at_cursor(handle: Buffer, offset_x: i32, offset_y: i32) -> bool {
+ let Ok(window) = window_from_bytes(&handle) else { return false; };
+ let mut cursor = POINT::default();
+ let mut bounds = RECT::default();
+ unsafe {
+ if GetCursorPos(&mut cursor).is_err() || GetWindowRect(window, &mut bounds).is_err() {
+ return false;
+ }
+ let x = cursor.x - offset_x;
+ let mut y = cursor.y - offset_y;
+ let monitor = MonitorFromPoint(cursor, MONITOR_DEFAULTTONEAREST);
+ let mut info = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
+ if GetMonitorInfoW(monitor, &mut info).as_bool() {
+ y = y.max(info.rcWork.top);
+ }
+ if x == bounds.left && y == bounds.top { return true; }
+ SetWindowPos(window, HWND::default(), x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE).is_ok()
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/apps/desktop/src/main/__tests__/windowManualDrag.test.ts b/apps/desktop/src/main/__tests__/windowManualDrag.test.ts
index 91db34d34a..77fd70c16c 100644
--- a/apps/desktop/src/main/__tests__/windowManualDrag.test.ts
+++ b/apps/desktop/src/main/__tests__/windowManualDrag.test.ts
@@ -19,6 +19,7 @@ function makeWindow(x = 100, y = 100) {
maximized: false,
fullScreen: false,
position: [x, y] as [number, number],
+ size: [813, 607] as [number, number],
isDestroyed() {
return this.destroyed;
},
@@ -34,6 +35,13 @@ function makeWindow(x = 100, y = 100) {
setPosition(nx: number, ny: number) {
this.position = [nx, ny];
},
+ getBounds() {
+ return { x: this.position[0], y: this.position[1], width: this.size[0], height: this.size[1] };
+ },
+ setBounds(bounds: { x: number; y: number; width: number; height: number }) {
+ this.position = [bounds.x, bounds.y];
+ this.size = [bounds.width, bounds.height];
+ },
};
return win satisfies DragWindowLike & Record<string, unknown>;
}
@@ -69,6 +77,61 @@ describe('WindowManualDragController', () => {
expect(win.position).toEqual([300, 200]);
});
+ // #7860: the old position-only path repeatedly round-trips the native size at
+ // fractional DPI. Existing fakes only tracked position, hiding that feedback.
+ // Unit tier: model that native rounding and assert the public drag preserves size.
+ it('preserves the starting size through movement and stationary polling at fractional DPI', () => {
+ const { screen, cursor } = makeScreen();
+ const win = makeWindow();
+ const updates = vi.spyOn(win, 'setBounds');
+ win.setPosition = (x, y) => {
+ win.position = [x, y];
+ win.size = [win.size[0] + 1, win.size[1] + 1];
+ };
+ const controller = new WindowManualDragController(screen, 16);
+
+ controller.start(win);
+ cursor.x += 40;
+ cursor.y += 20;
+ vi.advanceTimersByTime(16);
+ expect(win.position).toEqual([140, 120]);
+ expect(win.size).toEqual([813, 607]);
+ vi.advanceTimersByTime(160);
+ expect(win.size).toEqual([813, 607]);
+ expect(updates).toHaveBeenCalledTimes(1);
+ controller.stop();
+
+ // A new gesture must capture a user's intervening resize, not an old size.
+ win.size = [901, 701];
+ controller.start(win);
+ cursor.x += 20;
+ vi.advanceTimersByTime(32);
+ expect(win.position).toEqual([160, 120]);
+ expect(win.size).toEqual([901, 701]);
+ controller.stop();
+ });
+
+ // #7860: native physical movement must never re-enter the DIP resize path.
+ it('delegates native movement until stop or native failure, without writing DIP bounds', () => {
+ const { screen } = makeScreen();
+ const win = makeWindow();
+ const bounds = vi.spyOn(win, 'setBounds');
+ const follow = vi.fn(() => true);
+ const controller = new WindowManualDragController(screen, 16, 1000, () => follow);
+ controller.start(win);
+ vi.advanceTimersByTime(16);
+ expect(follow).toHaveBeenCalledTimes(1);
+ controller.stop();
+ vi.advanceTimersByTime(32);
+ expect(follow).toHaveBeenCalledTimes(1);
+
+ controller.start(win);
+ follow.mockReturnValue(false);
+ vi.advanceTimersByTime(16);
+ expect(controller.isDragging()).toBe(false);
+ expect(bounds).not.toHaveBeenCalled();
+ });
+
it('clamps window y to the display workArea top (menu bar)', () => {
const { screen, cursor } = makeScreen(25);
const win = makeWindow(100, 100);
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index a387e9f860..fb343b879b 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -607,6 +607,7 @@ import { initAnalyticsSettingsService, noteAuthColdStartState } from './analytic
import { initLogUploadService, scheduleStartupBackfill } from './log-upload';
import { createOpenLogsMenuItem, openLogsDirectory } from './logSupport';
import { WindowManualDragController } from './windowManualDrag';
+import { loadWindowsTaskbarNative } from './windowsTaskbarNative';
import { issueWritableDirectoryPickerGrant } from './maker-ipc/writableDirectoryPickerGrant.js';
// 设备互联(跨设备远程控制): relay 连接 host + 开关/设备列表 IPC
import {
@@ -1648,6 +1649,7 @@ const rendererConsoleLog = createLogger('renderer-console');
const updatePresentationLog = createLogger('update-presentation');
const voicePowerBroadcastLog = createLogger('voice-input-power');
const sessionDragPreviewLog = createLogger('session-drag-preview');
+const windowDragLog = createLogger('window-drag');
const piSubagentLog = createLogger('pi-subagent');
let rendererBootGuard: RendererBootGuard | null = null;
@@ -5555,7 +5557,23 @@ const registerIpcHandlers = () => {
// 手动窗口拖拽:no-drag 元素(会话标题文字等,需要同时响应双击)按住移动
// 时由 renderer 发起,main 用光标位置驱动窗口跟随;pointerup 后 stop。
// 详见 windowManualDrag.ts 头注释。
- const windowManualDrag = new WindowManualDragController(screen);
+ let nativeWindowDrag: Awaited<ReturnType<typeof loadWindowsTaskbarNative>> | null = null;
+ if (process.platform === 'win32') {
+ void loadWindowsTaskbarNative().then((native) => {
+ nativeWindowDrag = native;
+ }).catch((error: unknown) => {
+ windowDragLog.warn('Windows native window drag unavailable; using DIP bounds fallback', error);
+ });
+ }
+ const windowManualDrag = new WindowManualDragController(screen, undefined, undefined,
+ process.platform === 'win32' ? (win) => {
+ const native = nativeWindowDrag;
+ const handle = win.getNativeWindowHandle?.();
+ if (!native || !handle) return null;
+ const offset = native.windowDragOffset(handle);
+ return () => native.moveWindowAtCursor(handle, offset.x, offset.y);
+ } : undefined);
+
// start / stop 都严格绑定 sender 窗口,解析不到(窗口销毁中)直接忽略,
// 不 fallback 主窗:多窗口下副窗的延迟消息若落到主窗上,start 会让主窗
// 意外粘附光标并误停他窗的合法拖拽,stop 会误停主窗拖拽。已销毁窗口的
diff --git a/apps/desktop/src/main/windowManualDrag.ts b/apps/desktop/src/main/windowManualDrag.ts
index 47504c5b1a..250d14d9c0 100644
--- a/apps/desktop/src/main/windowManualDrag.ts
+++ b/apps/desktop/src/main/windowManualDrag.ts
@@ -5,8 +5,9 @@
* 事件(macOS/Windows 实测连 mousedown 都收不到,见 electron#37789),因此
* "既能拖窗、又能响应双击"的元素(如会话标题文字)无法用原生拖拽区实现。
* 解法:元素标 no-drag 保留 DOM 事件,renderer 检测到按住移动后通过 IPC 请求
- * 本控制器接管——用光标屏幕坐标驱动 win.setPosition() 跟随,直到 renderer
- * 发 stop(pointerup / pointercancel)。
+ * 本控制器接管——用光标屏幕坐标驱动 win.setBounds() 跟随,直到 renderer
+ * 发 stop(pointerup / pointercancel)。Windows 优先由原生 bridge 在物理坐标下
+ * 使用 SWP_NOSIZE 移窗,避免分数 DPI 下宽高反复取整。
*
* 逻辑:start 时记录"光标 → 窗口原点"的偏移,之后按固定间隔把窗口移动到
* (cursor - offset)。窗口 y 以光标所在显示器的 workArea.y 为上限 clamp,
@@ -39,8 +40,9 @@ export interface DragWindowLike {
isDestroyed(): boolean;
isMaximized(): boolean;
isFullScreen(): boolean;
- getPosition(): number[];
- setPosition(x: number, y: number, animate?: boolean): void;
+ getNativeWindowHandle?(): Buffer;
+ getBounds(): { x: number; y: number; width: number; height: number };
+ setBounds(bounds: { x: number; y: number; width: number; height: number }, animate?: boolean): void;
}
/** 跟随间隔:~60fps,和原生拖拽手感对齐。 */
@@ -59,6 +61,7 @@ export class WindowManualDragController {
private readonly screen: ScreenLike,
private readonly intervalMs: number = FOLLOW_INTERVAL_MS,
private readonly maxDurationMs: number = MAX_DRAG_DURATION_MS,
+ private readonly nativeFollower?: (win: DragWindowLike) => (() => boolean) | null,
) {}
/**
@@ -74,11 +77,14 @@ export class WindowManualDragController {
this.stop();
if (win.isDestroyed() || win.isMaximized() || win.isFullScreen()) return;
+ const followNative = this.nativeFollower?.(win);
const cursor = this.screen.getCursorScreenPoint();
- const [winX, winY] = win.getPosition();
+ const { x: winX, y: winY, width, height } = win.getBounds();
const offsetX = cursor.x - winX;
const offsetY = cursor.y - winY;
const startedAt = Date.now();
+ let lastX = winX;
+ let lastY = winY;
this.activeWin = win;
this.timer = setInterval(() => {
@@ -86,9 +92,21 @@ export class WindowManualDragController {
this.stop();
return;
}
+ if (followNative) {
+ if (!followNative()) this.stop();
+ return;
+ }
const point = this.screen.getCursorScreenPoint();
const minY = this.screen.getDisplayNearestPoint(point).workArea.y;
- win.setPosition(point.x - offsetX, Math.max(minY, point.y - offsetY), false);
+ const x = point.x - offsetX;
+ const y = Math.max(minY, point.y - offsetY);
+ if (x === lastX && y === lastY) return;
+ // On Windows fractional DPI, setPosition round-trips the current native
+ // size through integer DIPs and can enlarge it on every tick (#7860).
+ // Keep the gesture's starting size instead of feeding that rounding back.
+ win.setBounds({ x, y, width, height }, false);
+ lastX = x;
+ lastY = y;
}, this.intervalMs);
}
diff --git a/apps/desktop/src/main/windowsTaskbarNative.ts b/apps/desktop/src/main/windowsTaskbarNative.ts
index 38e485746d..8d2671e54d 100644
--- a/apps/desktop/src/main/windowsTaskbarNative.ts
+++ b/apps/desktop/src/main/windowsTaskbarNative.ts
@@ -15,6 +15,8 @@ const binaryName = 'cindy-windows-taskbar.node';
export interface WindowsTaskbarNative {
setOverlayIcon(handle: Buffer, png: Buffer | null, description: string): void;
taskbarButtonCreatedMessage(): number;
+ windowDragOffset(handle: Buffer): { x: number; y: number };
+ moveWindowAtCursor(handle: Buffer, offsetX: number, offsetY: number): boolean;
}
let loading: Promise<WindowsTaskbarNative> | undefined;