Skip to content

Conversation

@yyhhyyyyyy
Copy link
Collaborator

@yyhhyyyyyy yyhhyyyyyy commented Aug 12, 2025

Add persistent position storage for floating button with boundary validation to prevent button from disappearing outside visible screen areas.

Summary by CodeRabbit

  • New Features
    • The floating button window now remembers its size and position across app launches.
    • Default placement is updated to the bottom-right of the primary display with a small margin when no prior position exists.
    • The window opens at the last used location and dimensions, providing a consistent experience after you move or resize it.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 12, 2025

Walkthrough

Adds window state persistence to the floating button window using electron-window-state, initializes and manages size/position from a JSON state file, and replaces prior positioning logic with a default bottom-right placement. updateConfig now uses the new default position helper. Public API remains unchanged.

Changes

Cohort / File(s) Summary of changes
Floating Button window state & positioning
src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts
Integrates electron-window-state; initializes and binds window state; uses persisted x/y/width/height on creation; adds getDefaultPosition() using primary display workArea with margin; replaces calculatePosition() and multi-position logic; updateConfig applies default position when needed; public API unchanged.

Sequence Diagram(s)

sequenceDiagram
    participant App
    participant FloatingButtonWindow
    participant WindowState as electron-window-state
    participant BrowserWindow

    App->>FloatingButtonWindow: new FloatingButtonWindow(config)
    FloatingButtonWindow->>WindowState: init(file, defaults)
    WindowState-->>FloatingButtonWindow: { x, y, width, height }
    FloatingButtonWindow->>BrowserWindow: create({ x, y, width, height, flags })
    FloatingButtonWindow->>WindowState: manage(BrowserWindow)
    BrowserWindow-->>App: ready
Loading
sequenceDiagram
    participant App
    participant FloatingButtonWindow
    participant Display as Electron.Display
    participant BrowserWindow

    App->>FloatingButtonWindow: updateConfig(config)
    alt position/offset specified
        FloatingButtonWindow->>Display: getPrimaryDisplay().workArea
        Display-->>FloatingButtonWindow: workArea
        FloatingButtonWindow->>FloatingButtonWindow: getDefaultPosition()
        FloatingButtonWindow->>BrowserWindow: setBounds({ x, y, ... })
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

I nudged my window to the rightmost brink,
Saved my spot with a whisker’s wink.
State in a file, snug through the night,
Hop, hop—awake in the very same light.
Bottom-right cozy, margins just so—
A rabbit remembers where windows should go. 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/floating-button-position-memory

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.


// 获取悬浮按钮位置
getFloatingButtonPosition(): { x: number; y: number } | null {
return this.getSetting<{ x: number; y: number }>('floatingButtonPosition') || null
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

建议直接使用目前已经存在的窗口状态管理器来实现该功能
import windowStateManager from 'electron-window-state' // 窗口状态管理器

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已使用 electron-window-state

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f02aaaf and 72e8aa3.

📒 Files selected for processing (4)
  • src/main/presenter/configPresenter/index.ts (3 hunks)
  • src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts (4 hunks)
  • src/main/presenter/floatingButtonPresenter/index.ts (1 hunks)
  • src/main/presenter/floatingButtonPresenter/types.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{ts,tsx,js,jsx,vue}

📄 CodeRabbit Inference Engine (CLAUDE.md)

Use English for logs and comments

Files:

  • src/main/presenter/floatingButtonPresenter/types.ts
  • src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts
  • src/main/presenter/floatingButtonPresenter/index.ts
  • src/main/presenter/configPresenter/index.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (CLAUDE.md)

Strict type checking enabled for TypeScript

**/*.{ts,tsx}: 始终使用 try-catch 处理可能的错误
提供有意义的错误信息
记录详细的错误日志
优雅降级处理
日志应包含时间戳、日志级别、错误代码、错误描述、堆栈跟踪(如适用)、相关上下文信息
日志级别应包括 ERROR、WARN、INFO、DEBUG
不要吞掉错误
提供用户友好的错误信息
实现错误重试机制
避免记录敏感信息
使用结构化日志
设置适当的日志级别

Files:

  • src/main/presenter/floatingButtonPresenter/types.ts
  • src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts
  • src/main/presenter/floatingButtonPresenter/index.ts
  • src/main/presenter/configPresenter/index.ts
src/main/**/*.ts

📄 CodeRabbit Inference Engine (CLAUDE.md)

Main to Renderer: Use EventBus to broadcast events via mainWindow.webContents.send()

Use Electron's built-in APIs for file system and native dialogs

Files:

  • src/main/presenter/floatingButtonPresenter/types.ts
  • src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts
  • src/main/presenter/floatingButtonPresenter/index.ts
  • src/main/presenter/configPresenter/index.ts
src/main/presenter/**/*.ts

📄 CodeRabbit Inference Engine (CLAUDE.md)

One presenter per functional domain

Files:

  • src/main/presenter/floatingButtonPresenter/types.ts
  • src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts
  • src/main/presenter/floatingButtonPresenter/index.ts
  • src/main/presenter/configPresenter/index.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development-setup.mdc)

**/*.{js,jsx,ts,tsx}: 使用 OxLint 进行代码检查
Log和注释使用英文书写

Files:

  • src/main/presenter/floatingButtonPresenter/types.ts
  • src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts
  • src/main/presenter/floatingButtonPresenter/index.ts
  • src/main/presenter/configPresenter/index.ts
src/{main,renderer}/**/*.ts

📄 CodeRabbit Inference Engine (.cursor/rules/electron-best-practices.mdc)

src/{main,renderer}/**/*.ts: Use context isolation for improved security
Implement proper inter-process communication (IPC) patterns
Optimize application startup time with lazy loading
Implement proper error handling and logging for debugging

Files:

  • src/main/presenter/floatingButtonPresenter/types.ts
  • src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts
  • src/main/presenter/floatingButtonPresenter/index.ts
  • src/main/presenter/configPresenter/index.ts
src/main/**/*.{ts,js,tsx,jsx}

📄 CodeRabbit Inference Engine (.cursor/rules/project-structure.mdc)

主进程代码放在 src/main

Files:

  • src/main/presenter/floatingButtonPresenter/types.ts
  • src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts
  • src/main/presenter/floatingButtonPresenter/index.ts
  • src/main/presenter/configPresenter/index.ts
src/main/presenter/configPresenter/**/*.ts

📄 CodeRabbit Inference Engine (CLAUDE.md)

Centralize configuration in configPresenter/

Files:

  • src/main/presenter/configPresenter/index.ts
🧠 Learnings (1)
📚 Learning: 2025-07-21T01:45:33.790Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-21T01:45:33.790Z
Learning: Applies to src/main/presenter/configPresenter/**/*.ts : Centralize configuration in configPresenter/

Applied to files:

  • src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts
  • src/main/presenter/floatingButtonPresenter/index.ts
  • src/main/presenter/configPresenter/index.ts
🧬 Code Graph Analysis (1)
src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts (1)
src/main/presenter/index.ts (1)
  • presenter (184-184)
🔇 Additional comments (8)
src/main/presenter/floatingButtonPresenter/types.ts (2)

5-5: LGTM!

The extension of position union to include 'custom' aligns well with the persistent positioning feature.


11-15: LGTM!

The optional customPosition property with explicit coordinates supports the new custom positioning functionality.

src/main/presenter/configPresenter/index.ts (2)

49-49: LGTM!

The new optional property for floating button position follows the established type pattern and aligns with the PR objectives.


112-112: LGTM!

Setting the default value to undefined is appropriate for an optional configuration that should only be set when the user explicitly moves the button.

src/main/presenter/floatingButtonPresenter/index.ts (1)

25-35: LGTM!

The initialization logic correctly:

  • Retrieves the saved position from configuration
  • Applies it as a custom position when available
  • Maintains backward compatibility when no saved position exists
src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts (3)

6-6: LGTM!

The import is necessary to access the configuration presenter for position persistence.


182-185: LGTM!

The early return for custom positions with validation is well-implemented and maintains the existing calculation logic for predefined positions.


280-280: LGTM!

The position saving on move events enables automatic persistence of user-dragged positions.

Comment on lines 215 to 258
/**
* 验证并修正位置,确保窗口不会完全移出可见区域
*/
private validatePosition(position: { x: number; y: number }): { x: number; y: number } {
const displays = screen.getAllDisplays()

// 检查位置是否在任何显示器的可见区域内
let isVisible = false
for (const display of displays) {
const {
x: displayX,
y: displayY,
width: displayWidth,
height: displayHeight
} = display.workArea
const windowRight = position.x + this.config.size.width
const windowBottom = position.y + this.config.size.height

// 检查窗口是否与显示器区域有交集(至少部分可见)
if (
position.x < displayX + displayWidth &&
windowRight > displayX &&
position.y < displayY + displayHeight &&
windowBottom > displayY
) {
isVisible = true
break
}
}

if (isVisible) {
return position
}

// 如果窗口不可见,将其移动到主显示器的默认位置(右下角)
logger.warn('Floating button position is out of bounds, correcting to default position')
const primaryDisplay = screen.getPrimaryDisplay()
const { workArea } = primaryDisplay

return {
x: workArea.width - this.config.size.width - 20,
y: workArea.height - this.config.size.height - 20
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Enhance the validation logic and error handling.

The position validation is good but could be improved:

  1. The boundary check logic should consider partial visibility requirements more explicitly
  2. Error handling could be more robust
  3. The corrected position should use workArea coordinates properly

Apply this improvement to the validation logic:

  private validatePosition(position: { x: number; y: number }): { x: number; y: number } {
    const displays = screen.getAllDisplays()

    // 检查位置是否在任何显示器的可见区域内
    let isVisible = false
    for (const display of displays) {
-      const {
-        x: displayX,
-        y: displayY,
-        width: displayWidth,
-        height: displayHeight
-      } = display.workArea
+      const { x: displayX, y: displayY, width: displayWidth, height: displayHeight } = display.workArea
      const windowRight = position.x + this.config.size.width
      const windowBottom = position.y + this.config.size.height

-      // 检查窗口是否与显示器区域有交集(至少部分可见)
+      // Ensure at least 25% of the button is visible within the display
+      const minVisibleWidth = this.config.size.width * 0.25
+      const minVisibleHeight = this.config.size.height * 0.25
+      const visibleWidth = Math.min(windowRight, displayX + displayWidth) - Math.max(position.x, displayX)
+      const visibleHeight = Math.min(windowBottom, displayY + displayHeight) - Math.max(position.y, displayY)
+      
       if (
-        position.x < displayX + displayWidth &&
-        windowRight > displayX &&
-        position.y < displayY + displayHeight &&
-        windowBottom > displayY
+        visibleWidth >= minVisibleWidth && visibleHeight >= minVisibleHeight
       ) {
         isVisible = true
         break
       }
     }

     if (isVisible) {
       return position
     }

-    // 如果窗口不可见,将其移动到主显示器的默认位置(右下角)
+    // Move to primary display's bottom-right corner if position is invalid
     logger.warn('Floating button position is out of bounds, correcting to default position')
     const primaryDisplay = screen.getPrimaryDisplay()
-    const { workArea } = primaryDisplay
+    const { x: workX, y: workY, width: workWidth, height: workHeight } = primaryDisplay.workArea

     return {
-      x: workArea.width - this.config.size.width - 20,
-      y: workArea.height - this.config.size.height - 20
+      x: workX + workWidth - this.config.size.width - 20,
+      y: workY + workHeight - this.config.size.height - 20
     }
   }
🤖 Prompt for AI Agents
In src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts around
lines 215 to 258, the validatePosition method needs to explicitly enforce
partial-visibility rules, use display.workArea x/y offsets when computing
corrected coordinates, and add basic error handling; update the visibility check
to require at least a minimum visible area (e.g., width/height overlap > 1 px or
configurable threshold) by computing overlapWidth = min(windowRight,
displayX+displayWidth) - max(position.x, displayX) and overlapHeight similarly
and treat visible if both > 0, wrap the routine in try/catch to log any
unexpected errors with details, and when correcting position use workArea.x +
(workArea.width - this.config.size.width - 20) and workArea.y + (workArea.height
- this.config.size.height - 20) (or clamp each coordinate between workArea.x and
workArea.x + workArea.width - windowWidth) so the returned position is within
the primary display's workArea.

Comment on lines 287 to 303
/**
* 保存当前位置到配置
*/
private savePosition(position: { x: number; y: number }): void {
try {
if (this.savePositionTimer) {
clearTimeout(this.savePositionTimer)
}
this.savePositionTimer = setTimeout(() => {
presenter.configPresenter.setFloatingButtonPosition(position)
logger.debug(`Floating button position saved: ${position.x}, ${position.y}`)
}, 500)
} catch (error) {
logger.error('Failed to save floating button position:', error)
}
}
private savePositionTimer: NodeJS.Timeout | null = null
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve the position saving implementation.

The debounced saving is a good approach, but there are some improvements needed:

  1. The timer property should be declared before it's used
  2. Error handling could provide more context
  3. Consider making the debounce delay configurable

Move the timer property declaration and improve the implementation:

+  private savePositionTimer: NodeJS.Timeout | null = null
+  
   /**
    * 保存当前位置到配置
    */
   private savePosition(position: { x: number; y: number }): void {
     try {
       if (this.savePositionTimer) {
         clearTimeout(this.savePositionTimer)
       }
+      
+      const SAVE_DEBOUNCE_DELAY = 500
       this.savePositionTimer = setTimeout(() => {
         presenter.configPresenter.setFloatingButtonPosition(position)
         logger.debug(`Floating button position saved: ${position.x}, ${position.y}`)
-      }, 500)
+        this.savePositionTimer = null
+      }, SAVE_DEBOUNCE_DELAY)
     } catch (error) {
-      logger.error('Failed to save floating button position:', error)
+      logger.error(`Failed to save floating button position (${position.x}, ${position.y}):`, error)
     }
   }
-  private savePositionTimer: NodeJS.Timeout | null = null
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/**
* 保存当前位置到配置
*/
private savePosition(position: { x: number; y: number }): void {
try {
if (this.savePositionTimer) {
clearTimeout(this.savePositionTimer)
}
this.savePositionTimer = setTimeout(() => {
presenter.configPresenter.setFloatingButtonPosition(position)
logger.debug(`Floating button position saved: ${position.x}, ${position.y}`)
}, 500)
} catch (error) {
logger.error('Failed to save floating button position:', error)
}
}
private savePositionTimer: NodeJS.Timeout | null = null
private savePositionTimer: NodeJS.Timeout | null = null
/**
* 保存当前位置到配置
*/
private savePosition(position: { x: number; y: number }): void {
try {
if (this.savePositionTimer) {
clearTimeout(this.savePositionTimer)
}
const SAVE_DEBOUNCE_DELAY = 500
this.savePositionTimer = setTimeout(() => {
presenter.configPresenter.setFloatingButtonPosition(position)
logger.debug(`Floating button position saved: ${position.x}, ${position.y}`)
this.savePositionTimer = null
}, SAVE_DEBOUNCE_DELAY)
} catch (error) {
logger.error(`Failed to save floating button position (${position.x}, ${position.y}):`, error)
}
}
🤖 Prompt for AI Agents
In src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts around
lines 287 to 303, move the savePositionTimer property declaration above the
savePosition method so it's defined before use, make the debounce delay
configurable (e.g., read from a constant or
presenter.configPresenter.getFloatingButtonDebounceMs()) instead of hardcoding
500, and improve the catch logging to include the position being saved and the
error details for context (e.g., logger.error with a message that contains
position.x and position.y and the error). Ensure the timer type remains
NodeJS.Timeout | null and that clearing/setting the timeout uses the configured
delay.

@zerob13
Copy link
Collaborator

zerob13 commented Aug 12, 2025

LGTM

@zerob13 zerob13 merged commit a336ea0 into dev Aug 12, 2025
1 of 2 checks passed
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🔭 Outside diff range comments (1)
src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts (1)

213-219: Add position saving with debouncing for persistence.

The moved event listener should save the position to ensure persistence across application restarts, which is a key requirement of the PR.

Add position saving functionality:

+  private savePositionTimer: NodeJS.Timeout | null = null
+
   // 窗口移动事件
   this.window.on('moved', () => {
     if (this.window) {
       const bounds = this.window.getBounds()
       this.state.bounds.x = bounds.x
       this.state.bounds.y = bounds.y
+      
+      // Save position with debouncing to avoid excessive saves during drag
+      this.savePosition({ x: bounds.x, y: bounds.y })
     }
   })
+
+  /**
+   * 保存当前位置到配置
+   */
+  private savePosition(position: { x: number; y: number }): void {
+    try {
+      if (this.savePositionTimer) {
+        clearTimeout(this.savePositionTimer)
+      }
+      
+      const SAVE_DEBOUNCE_DELAY = 500
+      this.savePositionTimer = setTimeout(() => {
+        // Save to windowState manager
+        if (this.windowState) {
+          this.windowState.x = position.x
+          this.windowState.y = position.y
+        }
+        logger.debug(`Floating button position saved: ${position.x}, ${position.y}`)
+        this.savePositionTimer = null
+      }, SAVE_DEBOUNCE_DELAY)
+    } catch (error) {
+      logger.error(`Failed to save floating button position (${position.x}, ${position.y}):`, error)
+    }
+  }
♻️ Duplicate comments (2)
src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts (2)

188-196: Fix coordinate calculation using workArea offset.

The position calculation incorrectly uses workArea.width and workArea.height directly instead of considering the workArea's x/y offsets. This can cause the button to appear in wrong positions on multi-monitor setups.

Apply this diff to fix the coordinate calculation:

   private getDefaultPosition(): { x: number; y: number } {
     const primaryDisplay = screen.getPrimaryDisplay()
-    const { workArea } = primaryDisplay
+    const { x: workX, y: workY, width: workWidth, height: workHeight } = primaryDisplay.workArea
 
     return {
-      x: workArea.width - this.config.size.width - 20,
-      y: workArea.height - this.config.size.height - 20
+      x: workX + workWidth - this.config.size.width - 20,
+      y: workY + workHeight - this.config.size.height - 20
     }
   }

188-196: Add boundary validation for position persistence.

The current implementation lacks validation to ensure the persisted position remains within visible screen bounds. This is critical for the PR objective of preventing the button from disappearing outside visible areas.

Add position validation by introducing a validatePosition method:

   private getDefaultPosition(): { x: number; y: number } {
     const primaryDisplay = screen.getPrimaryDisplay()
     const { x: workX, y: workY, width: workWidth, height: workHeight } = primaryDisplay.workArea
 
-    return {
+    const position = {
       x: workX + workWidth - this.config.size.width - 20,
       y: workY + workHeight - this.config.size.height - 20
     }
+    
+    return this.validatePosition(position)
+  }
+
+  /**
+   * 验证位置是否在屏幕可视区域内
+   */
+  private validatePosition(position: { x: number; y: number }): { x: number; y: number } {
+    const displays = screen.getAllDisplays()
+
+    // Check if position is within any display's visible area
+    let isVisible = false
+    for (const display of displays) {
+      const { x: displayX, y: displayY, width: displayWidth, height: displayHeight } = display.workArea
+      const windowRight = position.x + this.config.size.width
+      const windowBottom = position.y + this.config.size.height
+
+      // Ensure at least 25% of the button is visible
+      const minVisibleWidth = this.config.size.width * 0.25
+      const minVisibleHeight = this.config.size.height * 0.25
+      const visibleWidth = Math.min(windowRight, displayX + displayWidth) - Math.max(position.x, displayX)
+      const visibleHeight = Math.min(windowBottom, displayY + displayHeight) - Math.max(position.y, displayY)
+      
+      if (visibleWidth >= minVisibleWidth && visibleHeight >= minVisibleHeight) {
+        isVisible = true
+        break
+      }
+    }
+
+    if (isVisible) {
+      return position
+    }
+
+    // Move to primary display's bottom-right corner if position is invalid
+    logger.warn('Floating button position is out of bounds, correcting to default position')
+    const primaryDisplay = screen.getPrimaryDisplay()
+    const { x: workX, y: workY, width: workWidth, height: workHeight } = primaryDisplay.workArea
+
+    return {
+      x: workX + workWidth - this.config.size.width - 20,
+      y: workY + workHeight - this.config.size.height - 20
+    }
   }
🧹 Nitpick comments (1)
src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts (1)

6-6: Import the correct windowStateManager type.

The import statement lacks proper TypeScript typing for electron-window-state.

Apply this diff to improve the import with proper typing:

-import windowStateManager from 'electron-window-state'
+import windowStateManager, { State as WindowState } from 'electron-window-state'
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 72e8aa3 and 20bb883.

📒 Files selected for processing (1)
  • src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts (6 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{ts,tsx,js,jsx,vue}

📄 CodeRabbit Inference Engine (CLAUDE.md)

Use English for logs and comments

Files:

  • src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (CLAUDE.md)

Strict type checking enabled for TypeScript

**/*.{ts,tsx}: 始终使用 try-catch 处理可能的错误
提供有意义的错误信息
记录详细的错误日志
优雅降级处理
日志应包含时间戳、日志级别、错误代码、错误描述、堆栈跟踪(如适用)、相关上下文信息
日志级别应包括 ERROR、WARN、INFO、DEBUG
不要吞掉错误
提供用户友好的错误信息
实现错误重试机制
避免记录敏感信息
使用结构化日志
设置适当的日志级别

Files:

  • src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts
src/main/**/*.ts

📄 CodeRabbit Inference Engine (CLAUDE.md)

Main to Renderer: Use EventBus to broadcast events via mainWindow.webContents.send()

Use Electron's built-in APIs for file system and native dialogs

Files:

  • src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts
src/main/presenter/**/*.ts

📄 CodeRabbit Inference Engine (CLAUDE.md)

One presenter per functional domain

Files:

  • src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development-setup.mdc)

**/*.{js,jsx,ts,tsx}: 使用 OxLint 进行代码检查
Log和注释使用英文书写

Files:

  • src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts
src/{main,renderer}/**/*.ts

📄 CodeRabbit Inference Engine (.cursor/rules/electron-best-practices.mdc)

src/{main,renderer}/**/*.ts: Use context isolation for improved security
Implement proper inter-process communication (IPC) patterns
Optimize application startup time with lazy loading
Implement proper error handling and logging for debugging

Files:

  • src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts
src/main/**/*.{ts,js,tsx,jsx}

📄 CodeRabbit Inference Engine (.cursor/rules/project-structure.mdc)

主进程代码放在 src/main

Files:

  • src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts
🧠 Learnings (1)
📚 Learning: 2025-07-21T01:45:33.790Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-21T01:45:33.790Z
Learning: Applies to src/main/presenter/configPresenter/**/*.ts : Centralize configuration in configPresenter/

Applied to files:

  • src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts
🧬 Code Graph Analysis (1)
src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts (1)
src/main/presenter/floatingButtonPresenter/types.ts (2)
  • FloatingButtonConfig (1-20)
  • FloatingButtonState (22-32)
🔇 Additional comments (3)
src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts (3)

26-31: LGTM! Good window state initialization.

The window state manager initialization follows best practices with proper file naming and default dimensions from configuration.


47-50: LGTM! Proper window state integration.

The window creation now correctly uses the persisted state for position and dimensions, which addresses the PR objective of position persistence.


73-73: LGTM! Window state management is properly bound.

The this.windowState.manage(this.window) call correctly binds the window to the state manager for automatic persistence.

private window: BrowserWindow | null = null
private config: FloatingButtonConfig
private state: FloatingButtonState
private windowState: any
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Use proper TypeScript typing for windowState property.

The windowState property should use a proper type instead of any to enable better type safety and IntelliSense support.

Apply this diff to add proper typing:

-  private windowState: any
+  private windowState: WindowState
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private windowState: any
private windowState: WindowState
🤖 Prompt for AI Agents
In src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts around
line 12, change the windowState property from type any to a proper typed
interface (e.g. import and use the State type from the electron-window-state
package or declare an explicit interface with x, y, width, height, isMaximized,
isMinimized, etc.) and make it nullable if it can be uninitialized (e.g. State |
null). Update the top of the file to import the State type (import { State }
from 'electron-window-state') or add the inline interface, then replace "private
windowState: any" with "private windowState: State | null" (or your chosen
interface) and update any usages to handle the nullable type if needed.


if (config.position || config.offset) {
const position = this.calculatePosition()
const position = this.getDefaultPosition()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Verify position calculation logic change.

The change from calculatePosition() to getDefaultPosition() alters the positioning behavior. The new implementation always uses bottom-right positioning, while the old logic likely supported multiple position options based on config.position.

Run the following script to verify if the removed calculatePosition method handled multiple position types:


🏁 Script executed:

#!/bin/bash
# Description: Check if calculatePosition method existed and how it handled different position types

# Search for any references to calculatePosition in the codebase
rg -A 10 -B 5 "calculatePosition"

# Search for position-related logic that might have been removed
rg -A 5 -B 5 "(top-left|top-right|bottom-left|bottom-right)" --type ts

Length of output: 5898


🏁 Script executed:

#!/bin/bash
# Inspect getDefaultPosition and surrounding logic in FloatingButtonWindow.ts

rg -C 10 "getDefaultPosition" --glob "src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts"

Length of output: 4044


Re-enable configurable positioning for the floating button

The current call to getDefaultPosition() always places the window bottom-right with a hard-coded 20px offset, ignoring both config.position and config.offset. We need to restore the branching logic so that 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' (and any custom offsets) are respected.

• File: src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts
– In the block
ts if (config.position || config.offset) { const position = this.getDefaultPosition() … }
replace getDefaultPosition() with a calculatePosition() method that:
• Switches on this.config.position
• Applies this.config.offset.x/.y instead of the fixed 20px
• Falls back to bottom-right when unspecified

• Implement a new private calculatePosition(): { x: number; y: number } (or enhance getDefaultPosition) akin to the one in FloatingChatWindow.ts, for example:

- private getDefaultPosition(): { x: number; y: number } {
-   const { workArea } = screen.getPrimaryDisplay()
-   return {
-     x: workArea.width - this.config.size.width - 20,
-     y: workArea.height - this.config.size.height - 20
-   }
- }
+ private calculatePosition(): { x: number; y: number } {
+   const { workArea } = screen.getPrimaryDisplay()
+   const { width, height } = this.config.size
+   const { x: ox, y: oy } = this.config.offset
+   let x: number, y: number
+   switch (this.config.position) {
+     case 'top-left':
+       x = workArea.x + ox;  y = workArea.y + oy;  break
+     case 'top-right':
+       x = workArea.width  - width  - ox; y = workArea.y + oy;  break
+     case 'bottom-left':
+       x = workArea.x + ox;  y = workArea.height - height - oy;  break
+     default: // 'bottom-right'
+       x = workArea.width  - width  - ox; y = workArea.height - height - oy;  
+   }
+   return { x, y }
+ }

• Update the call site to use this.calculatePosition() instead of getDefaultPosition() when config.position or config.offset is set.

This will ensure all four corner options and custom offsets behave as intended.

🤖 Prompt for AI Agents
In src/main/presenter/floatingButtonPresenter/FloatingButtonWindow.ts around
line 151, the code always uses getDefaultPosition() which hardcodes bottom-right
with a 20px offset and ignores config.position and config.offset; replace that
call with a new private calculatePosition() that switches on
this.config.position ('top-left'|'top-right'|'bottom-left'|'bottom-right'),
applies offsets from this.config.offset.x and .y (falling back to 20px only when
offsets are undefined), and returns {x,y}; update the block that currently
checks if (config.position || config.offset) to call this.calculatePosition()
instead of getDefaultPosition(), ensuring the fallback remains bottom-right when
position is unspecified.

zerob13 added a commit that referenced this pull request Aug 13, 2025
* fix: add AlertDialogDescription to resolve accessibility warning (#706)

* fix: resolve focus flicker when creating new windows with Ctrl+Shift+N (#707)

* feat: enhance window management by implementing main window ID handling (#709)

* docs: update zhipu developer doc website link (#715)

Co-authored-by: gongchao <chao.gong@aminer.cn>

* refactor: better translate (#716)

* chore: en-us i18n

* chore(i18n): polish ja-JP translations across UI; keep chat.input.placeholder unchanged

* chore(i18n): polish fr-FR translations; keep chat.input.placeholder unchanged

* chore(i18n): refine fr-FR MCP & Settings copy; idiomatic, concise, brand-consistent

* chore(i18n): polish ru-RU translations across UI; keep chat.input.placeholder unchanged

* chore(i18n): polish fa-IR translations across UI; keep chat.input.placeholder unchanged

* chore: fix format

* chore: fix i18n

* chore: lock rolldown-vite version

* feat: add GPT-5 series model support (#717)

* ci(vite): Bundle the main file into a single file to speed up loading. (#718)

* fix(math): parser by upgrade vue-renderer-markdown (#722)

* chore: bump deps (#721)

* chore: bump deps

* fix: rolldown-vite 7.1.0 and duckdb bundle issue

* chore: back to vite

* chore: update electron

* chore: update versions

* fix(math): parser by upgrade vue-renderer-markdown (#722)

* chore: bump deps

---------

Co-authored-by: Simon He <57086651+Simon-He95@users.noreply.github.com>

* fix: add scrollable support to PopoverContent to prevent overflow (#720)

* feat: implement floating chat window system with performance optimization (#724)

* feat: add mcp sync and modelscope provider #615 (#723)

* wip: add modelscope provider

* feat: add mcp sync to modelscope

* fix: add scrollable support to PopoverContent to prevent overflow (#720)

* feat: implement floating chat window system with performance optimization (#724)

* chore: i18n and format

* feat: better style

* fix: mcp tool display

---------

Co-authored-by: yyhhyyyyyy <yyhhyyyyyy8@gmail.com>

* fix: move_files newPath parse issue (#725)

* fix: move_files newPath 参数计算规则

* fix: move_files 移动前需要判断dest是目录还是文件

* feat: add Claude Opus 4.1 to anthropic default model list (#726)

* feat: Add mcprouter's MCP marketplace api support (#727)

* wip: add mcp market

* feat: mcp market install

* wip: mcp install status sync

* feat: mcp server config mask

* chore: remove working doc

* chore: add translate

* feat: add ESC key to close floating chat window (#728)

* feat: add floating button position persistence with boundary validation (#729)

* feat: add floating button position persistence with boundary validation

* feat: refactor floating button to use electron-window-state

* chore: bump to 0.3.0

* feat: add reasoning_effort parameter support for gpt-oss models (#731)

* feat: add reasoning_effort parameter support for gpt-oss models

- add reasoning effort UI support across all components

* fix: preserve user reasoning effort settings and improve display logic

* fix: artifacts code not streaming (#732)

* fix: artifact react load failed

* chore: remove log

* fix: artifacts code not stream

* fix: format

---------

Co-authored-by: yyhhyyyyyy <yyhhyyyyyy8@gmail.com>
Co-authored-by: hllshiro <40970081+hllshiro@users.noreply.github.com>
Co-authored-by: tomsun28 <tomsun28@outlook.com>
Co-authored-by: gongchao <chao.gong@aminer.cn>
Co-authored-by: Simon He <57086651+Simon-He95@users.noreply.github.com>
Co-authored-by: wanna <wanna.w@binarywalk.com>
zerob13 added a commit that referenced this pull request Aug 13, 2025
* fix: add AlertDialogDescription to resolve accessibility warning (#706)

* fix: resolve focus flicker when creating new windows with Ctrl+Shift+N (#707)

* feat: enhance window management by implementing main window ID handling (#709)

* docs: update zhipu developer doc website link (#715)

Co-authored-by: gongchao <chao.gong@aminer.cn>

* refactor: better translate (#716)

* chore: en-us i18n

* chore(i18n): polish ja-JP translations across UI; keep chat.input.placeholder unchanged

* chore(i18n): polish fr-FR translations; keep chat.input.placeholder unchanged

* chore(i18n): refine fr-FR MCP & Settings copy; idiomatic, concise, brand-consistent

* chore(i18n): polish ru-RU translations across UI; keep chat.input.placeholder unchanged

* chore(i18n): polish fa-IR translations across UI; keep chat.input.placeholder unchanged

* chore: fix format

* chore: fix i18n

* chore: lock rolldown-vite version

* feat: add GPT-5 series model support (#717)

* ci(vite): Bundle the main file into a single file to speed up loading. (#718)

* fix(math): parser by upgrade vue-renderer-markdown (#722)

* chore: bump deps (#721)

* chore: bump deps

* fix: rolldown-vite 7.1.0 and duckdb bundle issue

* chore: back to vite

* chore: update electron

* chore: update versions

* fix(math): parser by upgrade vue-renderer-markdown (#722)

* chore: bump deps

---------

Co-authored-by: Simon He <57086651+Simon-He95@users.noreply.github.com>

* fix: add scrollable support to PopoverContent to prevent overflow (#720)

* feat: implement floating chat window system with performance optimization (#724)

* feat: add mcp sync and modelscope provider #615 (#723)

* wip: add modelscope provider

* feat: add mcp sync to modelscope

* fix: add scrollable support to PopoverContent to prevent overflow (#720)

* feat: implement floating chat window system with performance optimization (#724)

* chore: i18n and format

* feat: better style

* fix: mcp tool display

---------

Co-authored-by: yyhhyyyyyy <yyhhyyyyyy8@gmail.com>

* fix: move_files newPath parse issue (#725)

* fix: move_files newPath 参数计算规则

* fix: move_files 移动前需要判断dest是目录还是文件

* feat: add Claude Opus 4.1 to anthropic default model list (#726)

* feat: Add mcprouter's MCP marketplace api support (#727)

* wip: add mcp market

* feat: mcp market install

* wip: mcp install status sync

* feat: mcp server config mask

* chore: remove working doc

* chore: add translate

* feat: add ESC key to close floating chat window (#728)

* feat: add floating button position persistence with boundary validation (#729)

* feat: add floating button position persistence with boundary validation

* feat: refactor floating button to use electron-window-state

* chore: bump to 0.3.0

* feat: add reasoning_effort parameter support for gpt-oss models (#731)

* feat: add reasoning_effort parameter support for gpt-oss models

- add reasoning effort UI support across all components

* fix: preserve user reasoning effort settings and improve display logic

* fix: artifacts code not streaming (#732)

* fix: artifact react load failed

* chore: remove log

* fix: artifacts code not stream

* fix: format

* feat: disable automatic model enabling for better UX (#734)

* feat: sync provider sorting from settings to model selection (#736)

* feat: sync provider sorting from settings to model selection

* feat: refactor ModelSelect to use computed providers for better reactivity

---------

Co-authored-by: yyhhyyyyyy <yyhhyyyyyy8@gmail.com>
Co-authored-by: hllshiro <40970081+hllshiro@users.noreply.github.com>
Co-authored-by: tomsun28 <tomsun28@outlook.com>
Co-authored-by: gongchao <chao.gong@aminer.cn>
Co-authored-by: Simon He <57086651+Simon-He95@users.noreply.github.com>
Co-authored-by: wanna <wanna.w@binarywalk.com>
@zerob13 zerob13 deleted the feat/floating-button-position-memory branch November 23, 2025 13:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants