Skip to content

Conversation

@yyhhyyyyyy
Copy link
Collaborator

@yyhhyyyyyy yyhhyyyyyy commented Aug 25, 2025

implement auto-scroll to latest message and scroll-to-bottom button

Summary by CodeRabbit

  • New Features

    • Added a “Scroll to bottom” button in the Message Navigation sidebar to quickly jump to the latest messages (shown only when not searching and there are unseen messages).
  • Improvements

    • Automatically scrolls to the latest messages when new messages arrive or when opening the sidebar (when not in search mode).
    • Smoother, more reliable scrolling behavior for long message lists.
    • Button visibility intelligently updates based on whether you’re at the bottom of the list.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 25, 2025

Walkthrough

Adds programmatic scroll-to-bottom behavior to MessageNavigationSidebar.vue using refs, a hidden anchor, and an IntersectionObserver. Introduces a bottom “scroll to bottom” button shown when not searching and there are unseen messages. Hooks into lifecycle and watchers (messages.length, isOpen) to auto-scroll and manage observer setup/cleanup.

Changes

Cohort / File(s) Summary of edits
Message navigation sidebar behaviors
src/renderer/src/components/MessageNavigationSidebar.vue
Added refs for messages container and hidden scroll anchor; implemented scrollToBottom with nextTick; introduced IntersectionObserver to toggle a bottom button; watchers on messages.length and isOpen for auto-scroll and observer setup; lifecycle mount/unmount handling; container class adjusted for smooth scrolling; imports extended.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor U as User
  participant M as MessageNavigationSidebar
  participant DOM as DOM/Refs
  participant IO as IntersectionObserver

  rect rgb(245,248,255)
    note over M: Mount / Open
    M->>DOM: init refs (messagesContainer, scrollAnchor)
    M->>IO: setupScrollObserver(root=messagesContainer)
    alt isOpen and not searching
      M->>M: nextTick()
      M->>DOM: scrollAnchor.scrollIntoView(end, instant)
    end
  end

  rect rgb(245,255,245)
    note over M: New message arrives
    M->>M: watch(messages.length)
    alt not searching
      M->>M: nextTick()
      M->>DOM: scrollAnchor.scrollIntoView(end, instant)
    end
  end

  rect rgb(255,248,240)
    note over IO: Visibility changes
    IO-->>M: scrollAnchor intersecting?
    M->>M: toggle showScrollToBottomButton
  end

  U->>M: Click "Scroll to bottom"
  M->>M: scrollToBottom()
  M->>DOM: scrollAnchor.scrollIntoView(end, instant)

  note over M: onUnmounted -> IO.disconnect()
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • zerob13

Poem

I hop through threads where messages flow,
A carrot of code makes anchors go.
Buttons appear when scroll won’t land,
I nudge the view with a gentle hand.
Down we whisk, to the chat’s bright end—
Boop! 🥕 Scroll achieved, my friend.

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/navigation-scroll-to-bottom

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.

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: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/renderer/src/components/MessageNavigationSidebar.vue (1)

86-88: Avoid v-html on untrusted message content (XSS risk)

v-html renders raw HTML. Since message previews come from user/assistant content, malicious markup could execute. Either render tokenized text nodes (preferred) or at minimum escape HTML before wrapping highlights.

Minimal mitigation (escape then highlight):

-// 高亮搜索关键词
-const highlightSearchQuery = (text: string): string => {
-  if (!searchQuery.value.trim()) {
-    return text
-  }
-
-  const query = searchQuery.value.trim()
-  const regex = new RegExp(`(${query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi')
-  return text.replace(
-    regex,
-    '<mark class="bg-yellow-200 dark:bg-yellow-800 px-1 rounded">$1</mark>'
-  )
-}
+// Highlight search query with HTML-escaped content to avoid XSS
+const escapeHtml = (s: string) =>
+  s
+    .replace(/&/g, '&amp;')
+    .replace(/</g, '&lt;')
+    .replace(/>/g, '&gt;')
+    .replace(/"/g, '&quot;')
+    .replace(/'/g, '&#039;')
+
+const highlightSearchQuery = (text: string): string => {
+  const escaped = escapeHtml(text)
+  if (!searchQuery.value.trim()) return escaped
+  const query = searchQuery.value.trim()
+  const regex = new RegExp(`(${query.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')})`, 'gi')
+  return escaped.replace(
+    regex,
+    '<mark class="bg-yellow-200 dark:bg-yellow-800 px-1 rounded">$1</mark>'
+  )
+}

Preferred (no v-html): split text into parts and render with <span v-for>; I can provide a patch if you want that approach.

🧹 Nitpick comments (7)
src/renderer/src/components/MessageNavigationSidebar.vue (7)

105-115: Add i18n’d a11y labels and use smooth scroll only on user click

Make the button accessible and intentional: add aria-label/title via i18n and call scrollToBottom({ smooth: true }). Consider hiding the button when there are no messages.

-      <div v-if="showScrollToBottomButton && !searchQuery.trim()" class="absolute bottom-4 right-4">
+      <div v-if="showScrollToBottomButton && !searchQuery.trim() && messages.length > 0" class="absolute bottom-4 right-4">
         <Button
           variant="outline"
           size="icon"
           class="h-8 w-8 rounded-full shadow-lg bg-background border"
-          @click="scrollToBottom"
+          :aria-label="t('chat.navigation.scrollToBottom')"
+          :title="t('chat.navigation.scrollToBottom')"
+          @click="scrollToBottom({ smooth: true })"
         >
           <Icon icon="lucide:arrow-down" class="h-4 w-4" />
         </Button>
       </div>

Follow-up: add the new i18n key chat.navigation.scrollToBottom in your locales.


264-275: Auto-scroll only if panel is open and user is already at bottom

Current logic will yank the viewport to the bottom even if the user scrolled up to read earlier messages. Gate on props.isOpen and only scroll when the bottom anchor is visible (i.e., !showScrollToBottomButton). Also avoid the outer nextTick since scrollToBottom already schedules one.

 watch(
   () => props.messages.length,
   (newLength, oldLength) => {
     // 只在新增消息时滚动,避免过度滚动
-    if (newLength > oldLength && !searchQuery.value.trim()) {
-      nextTick(() => {
-        scrollToBottom()
-      })
-    }
+    if (
+      newLength > oldLength &&
+      !searchQuery.value.trim() &&
+      props.isOpen &&
+      !showScrollToBottomButton.value
+    ) {
+      scrollToBottom({ smooth: false })
+    }
   }
 )

276-290: Initialize observer before scrolling and pause it when panel closes

Create the observer first so its state is accurate, then scroll (if needed). When the panel closes (isOpen → false), disconnect to save work.

 watch(
   () => props.isOpen,
   (newIsOpen) => {
-    if (newIsOpen && !searchQuery.value.trim()) {
-      nextTick(() => {
-        scrollToBottom()
-        setupScrollObserver()
-      })
-    } else if (newIsOpen) {
-      nextTick(() => {
-        setupScrollObserver()
-      })
-    }
+    if (newIsOpen) {
+      nextTick(() => {
+        setupScrollObserver()
+        if (!searchQuery.value.trim()) {
+          scrollToBottom({ smooth: false })
+        }
+      })
+    } else {
+      if (intersectionObserver) {
+        intersectionObserver.disconnect()
+      }
+    }
   }
 )

294-314: Harden IntersectionObserver setup

Guard against missing refs and fall back to viewport as the root if the container is not yet ready. Also nullify the old instance to avoid accidental reuse.

 const setupScrollObserver = () => {
   if (intersectionObserver) {
-    intersectionObserver.disconnect()
+    intersectionObserver.disconnect()
+    intersectionObserver = null
   }
 
-  intersectionObserver = new IntersectionObserver(
+  // Guard: ensure target exists
+  if (!scrollAnchor.value) return
+
+  intersectionObserver = new IntersectionObserver(
     (entries) => {
       const entry = entries[0]
       showScrollToBottomButton.value = !entry.isIntersecting
     },
     {
-      root: messagesContainer.value,
+      // Fallback to viewport if container is not yet ready
+      root: messagesContainer.value ?? null,
       rootMargin: '0px 0px 20px 0px',
       threshold: 0
     }
   )
 
-  if (scrollAnchor.value) {
-    intersectionObserver.observe(scrollAnchor.value)
-  }
+  intersectionObserver.observe(scrollAnchor.value)
 }

316-329: Order of operations: observer first, then scroll

This avoids a brief flicker of the button state on mount and removes one nextTick layer.

-// 组件挂载时滚动到底部
 onMounted(() => {
-  if (props.isOpen && !searchQuery.value.trim()) {
-    nextTick(() => {
-      scrollToBottom()
-      setupScrollObserver()
-    })
-  } else {
-    nextTick(() => {
-      setupScrollObserver()
-    })
-  }
+  nextTick(() => {
+    setupScrollObserver()
+    if (props.isOpen && !searchQuery.value.trim()) {
+      scrollToBottom({ smooth: false })
+    }
+  })
 })

153-156: Type refs as nullable and initialize to null

This avoids undefined vs null ambiguity and plays nicer with strict TS inference in Vue templates.

-const messagesContainer = ref<HTMLDivElement>()
-const scrollAnchor = ref<HTMLDivElement>()
+const messagesContainer = ref<HTMLDivElement | null>(null)
+const scrollAnchor = ref<HTMLDivElement | null>(null)
 const showScrollToBottomButton = ref(false)

102-106: Use English comments to match repo guidelines

The repository guidelines require English for logs and comments. Update the newly added comments.

-      <!-- 滚动锚点 -->
+      <!-- Scroll anchor -->
-      <!-- 滚动到底部按钮 -->
+      <!-- Scroll-to-bottom button -->
-// 滚动到底部
+// Scroll to bottom
-// 组件挂载时滚动到底部
+// Scroll to bottom on mount (when open)
-// 清理观察器
+// Cleanup observer

Also applies to: 330-336, 249-249, 316-316

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 448471d and f949636.

📒 Files selected for processing (1)
  • src/renderer/src/components/MessageNavigationSidebar.vue (5 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{ts,tsx,js,jsx,vue}

📄 CodeRabbit inference engine (CLAUDE.md)

Use English for logs and comments

Files:

  • src/renderer/src/components/MessageNavigationSidebar.vue
src/renderer/src/**/*.vue

📄 CodeRabbit inference engine (CLAUDE.md)

src/renderer/src/**/*.vue: Use Composition API for all Vue 3 components
Use Tailwind CSS with scoped styles for styling
Organize components by feature in src/renderer/src/
Follow existing component patterns in src/renderer/src/ when creating new UI components
Use Composition API with proper TypeScript typing for new UI components
Implement responsive design with Tailwind CSS for new UI components
Add proper error handling and loading states for new UI components

Use scoped styles to prevent CSS conflicts between components

Files:

  • src/renderer/src/components/MessageNavigationSidebar.vue
src/renderer/src/**/*.{ts,tsx,vue}

📄 CodeRabbit inference engine (CLAUDE.md)

src/renderer/src/**/*.{ts,tsx,vue}: Use Pinia for frontend state management
Renderer to Main: Use usePresenter.ts composable for direct presenter method calls

Files:

  • src/renderer/src/components/MessageNavigationSidebar.vue
src/renderer/src/**/*

📄 CodeRabbit inference engine (.cursor/rules/i18n.mdc)

src/renderer/src/**/*: All user-facing strings must use i18n keys (avoid hardcoded user-visible text in code)
Use the 'vue-i18n' framework for all internationalization in the renderer
Ensure all user-visible text in the renderer uses the translation system

Files:

  • src/renderer/src/components/MessageNavigationSidebar.vue
src/renderer/**/*.{vue,ts,js,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

渲染进程代码放在 src/renderer

Files:

  • src/renderer/src/components/MessageNavigationSidebar.vue
src/renderer/src/**/*.{vue,ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/vue-best-practices.mdc)

src/renderer/src/**/*.{vue,ts,tsx,js,jsx}: Use the Composition API for better code organization and reusability
Implement proper state management with Pinia
Utilize Vue Router for navigation and route management
Leverage Vue's built-in reactivity system for efficient data handling

Files:

  • src/renderer/src/components/MessageNavigationSidebar.vue
src/renderer/**/*.{ts,tsx,vue}

📄 CodeRabbit inference engine (.cursor/rules/vue-shadcn.mdc)

src/renderer/**/*.{ts,tsx,vue}: Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
Use TypeScript for all code; prefer types over interfaces.
Avoid enums; use const objects instead.
Use arrow functions for methods and computed properties.
Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements.

Files:

  • src/renderer/src/components/MessageNavigationSidebar.vue
src/renderer/**/*.{vue,ts}

📄 CodeRabbit inference engine (.cursor/rules/vue-shadcn.mdc)

Implement lazy loading for routes and components.

Files:

  • src/renderer/src/components/MessageNavigationSidebar.vue
src/renderer/**/*.{ts,vue}

📄 CodeRabbit inference engine (.cursor/rules/vue-shadcn.mdc)

src/renderer/**/*.{ts,vue}: Use useFetch and useAsyncData for data fetching.
Implement SEO best practices using Nuxt's useHead and useSeoMeta.

Files:

  • src/renderer/src/components/MessageNavigationSidebar.vue
🧠 Learnings (5)
📚 Learning: 2025-07-23T00:45:57.322Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: .cursor/rules/vue-shadcn.mdc:0-0
Timestamp: 2025-07-23T00:45:57.322Z
Learning: Applies to src/renderer/**/*.{vue} : Import Icon component from Iconify/Vue.

Applied to files:

  • src/renderer/src/components/MessageNavigationSidebar.vue
📚 Learning: 2025-07-23T00:45:57.322Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: .cursor/rules/vue-shadcn.mdc:0-0
Timestamp: 2025-07-23T00:45:57.322Z
Learning: Applies to src/renderer/**/*.{vue} : Use Iconify/Vue for icon implementation.

Applied to files:

  • src/renderer/src/components/MessageNavigationSidebar.vue
📚 Learning: 2025-07-23T00:45:57.322Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: .cursor/rules/vue-shadcn.mdc:0-0
Timestamp: 2025-07-23T00:45:57.322Z
Learning: Applies to src/renderer/**/*.{vue} : Leverage ref, reactive, and computed for reactive state management.

Applied to files:

  • src/renderer/src/components/MessageNavigationSidebar.vue
📚 Learning: 2025-07-23T00:45:57.322Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: .cursor/rules/vue-shadcn.mdc:0-0
Timestamp: 2025-07-23T00:45:57.322Z
Learning: Applies to src/renderer/**/*.{vue} : Use <script setup> syntax for concise component definitions.

Applied to files:

  • src/renderer/src/components/MessageNavigationSidebar.vue
📚 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/renderer/src/**/*.vue : Use Composition API with proper TypeScript typing for new UI components

Applied to files:

  • src/renderer/src/components/MessageNavigationSidebar.vue
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build-check (x64)
🔇 Additional comments (3)
src/renderer/src/components/MessageNavigationSidebar.vue (3)

127-127: Imports look good

The added lifecycle and reactivity imports (watch, nextTick, onMounted, onUnmounted) fit the new behavior.


48-49: Container wiring LGTM

Using a ref on the scroll container is the right choice; relative is necessary for absolutely positioning the button.


331-336: Cleanup is correct

Observer is disconnected and nulled on unmount.

Comment on lines +249 to +258
// 滚动到底部
const scrollToBottom = () => {
nextTick(() => {
scrollAnchor.value?.scrollIntoView({
behavior: 'instant',
block: 'end'
})
})
}

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

⚠️ Potential issue

Fix non‑standard scrollIntoView option and add smooth/auto mode

behavior: 'instant' is not a valid ScrollBehavior (valid: 'auto' | 'smooth'), so browsers may ignore it. Also, you’ll likely want smooth scrolling for the button click and non-animated scrolling for auto-scroll on new messages. Expose an options param and switch behavior accordingly.

Apply this diff:

-// 滚动到底部
-const scrollToBottom = () => {
-  nextTick(() => {
-    scrollAnchor.value?.scrollIntoView({
-      behavior: 'instant',
-      block: 'end'
-    })
-  })
-}
+// Scroll to bottom
+type ScrollToBottomOpts = { smooth?: boolean }
+const scrollToBottom = (opts: ScrollToBottomOpts = {}) => {
+  nextTick(() => {
+    const container = messagesContainer.value
+    const smooth = !!opts.smooth
+    const prevBehavior = container?.style.scrollBehavior
+    // If container has CSS 'scroll-behavior: smooth', force instant for programmatic auto-scrolls
+    if (!smooth && container) container.style.scrollBehavior = 'auto'
+    scrollAnchor.value?.scrollIntoView({
+      behavior: smooth ? 'smooth' : 'auto',
+      block: 'end'
+    })
+    if (!smooth && container) container.style.scrollBehavior = prevBehavior ?? ''
+  })
+}
📝 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
// 滚动到底部
const scrollToBottom = () => {
nextTick(() => {
scrollAnchor.value?.scrollIntoView({
behavior: 'instant',
block: 'end'
})
})
}
// Scroll to bottom
type ScrollToBottomOpts = { smooth?: boolean }
const scrollToBottom = (opts: ScrollToBottomOpts = {}) => {
nextTick(() => {
const container = messagesContainer.value
const smooth = !!opts.smooth
const prevBehavior = container?.style.scrollBehavior
// If container has CSS 'scroll-behavior: smooth', force instant for programmatic auto-scrolls
if (!smooth && container) container.style.scrollBehavior = 'auto'
scrollAnchor.value?.scrollIntoView({
behavior: smooth ? 'smooth' : 'auto',
block: 'end'
})
if (!smooth && container) container.style.scrollBehavior = prevBehavior ?? ''
})
}
🤖 Prompt for AI Agents
In src/renderer/src/components/MessageNavigationSidebar.vue around lines 249 to
258, the scrollToBottom function uses a non‑standard behavior value ('instant')
for scrollIntoView; change it to accept an options parameter (e.g. mode: 'auto'
| 'smooth' with a default) and call scrollAnchor.value?.scrollIntoView({
behavior: mode, block: 'end' }) inside nextTick; update all callers so the
button click passes 'smooth' and automatic/new‑message calls pass 'auto' (or
rely on the default) to ensure valid values and the desired animated vs
non‑animated scrolling.

@yyhhyyyyyy yyhhyyyyyy merged commit de18362 into dev Aug 25, 2025
2 checks passed
@zerob13 zerob13 deleted the feat/navigation-scroll-to-bottom branch January 6, 2026 12:16
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.

2 participants