Skip to content

Conversation

@yyhhyyyyyy
Copy link
Collaborator

@yyhhyyyyyy yyhhyyyyyy commented Aug 21, 2025

sync provider order changes across all tabs

CleanShot.2025-08-21.at.17.32.25.mp4

Summary by CodeRabbit

  • Bug Fixes

    • Provider ordering now persists reliably after you rearrange providers.
    • Saved provider order is correctly applied when providers change, ensuring consistent model lists.
  • Improvements

    • Enhanced messaging around provider changes for clearer feedback.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 21, 2025

Walkthrough

Adds saved provider ordering application on provider change and persists provider ordering updates. Enhances logging for provider change events. The settings store now calls loadSavedOrder() before refreshing models and saves the updated providers list via configP.setProviders() after order changes.

Changes

Cohort / File(s) Summary
Settings store: provider order load/persist
src/renderer/src/stores/settings.ts
On CONFIG_EVENTS.PROVIDER_CHANGED, replace log text and call loadSavedOrder() before model refresh. In updateProvidersOrder, persist current providers by calling configP.setProviders(providers.value) after updating in-memory order. No public API changes.

Sequence Diagram(s)

sequenceDiagram
  participant App
  participant SettingsStore
  participant Config as configP
  participant Models as ModelRefresher

  Note over App,SettingsStore: Provider changed event
  App->>SettingsStore: CONFIG_EVENTS.PROVIDER_CHANGED
  SettingsStore->>SettingsStore: loadSavedOrder()
  SettingsStore->>Models: refreshModels()

  Note over App,SettingsStore: Manual provider reordering
  App->>SettingsStore: updateProvidersOrder(newOrder)
  SettingsStore->>SettingsStore: update in-memory providers
  SettingsStore->>Config: setProviders(providers.value)
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Suggested reviewers

  • zerob13

Poem

I hop through configs, neat and tidy rows,
Shuffling providers where the saved breeze blows.
Click, clack—order sticks, no longer astray,
I stash it away for another day.
Models line up—thump-thump—ready to go! 🐇✨

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 Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/provider-order-sync-across-tabs

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

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/stores/settings.ts (1)

928-933: Fix identical branches: disabled providers aren’t moved to the disabled segment

Both branches set the same newOrder, so toggling enable=false won’t push the provider into the disabled block. This breaks expected ordering behavior.

Apply this diff:

-      if (enable) {
-        newOrder = [...enabledInOrder, providerId, ...disabledInOrder]
-      } else {
-        newOrder = [...enabledInOrder, providerId, ...disabledInOrder]
-      }
+      if (enable) {
+        // Move into the enabled segment
+        newOrder = [...enabledInOrder, providerId, ...disabledInOrder]
+      } else {
+        // Move into the disabled segment (after all currently enabled+disabled)
+        newOrder = [...enabledInOrder, ...disabledInOrder, providerId]
+      }
🧹 Nitpick comments (2)
src/renderer/src/stores/settings.ts (2)

1516-1519: Prefer emitting an explicit “order changed” event over rewriting providers

Using setProviders() as a broadcast mechanism is heavy and risks unnecessary churn. Consider emitting a dedicated CONFIG_EVENTS.PROVIDER_ORDER_CHANGED (or a generic SETTING_CHANGED for key 'providerOrder') from configPresenter when setSetting('providerOrder', ...) is called, and listen for that in the renderer. It keeps concerns separated and avoids rewriting provider configs just to notify other windows.


371-373: De-duplicate listener registration for setupProviderListener

setupProviderListener() is invoked inside initSettings() (Line 372) and again in onMounted() (Lines 1320–1321), which can register duplicate IPC handlers and cause double refreshes. Make it idempotent or call it only once.

Minimal change:

   onMounted(async () => {
     await initSettings()
-    await setupProviderListener()
+    // setupProviderListener() is already called inside initSettings()
   })

Also applies to: 1318-1321

📜 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 e18c500 and fd70da4.

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

📄 CodeRabbit inference engine (CLAUDE.md)

Use English for logs and comments

Files:

  • src/renderer/src/stores/settings.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Strict type checking enabled for TypeScript

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

Files:

  • src/renderer/src/stores/settings.ts
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/stores/settings.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development-setup.mdc)

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

Files:

  • src/renderer/src/stores/settings.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/renderer/src/stores/settings.ts
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/stores/settings.ts
src/renderer/src/stores/**/*.{vue,ts,tsx,js,jsx}

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

src/renderer/src/stores/**/*.{vue,ts,tsx,js,jsx}: Use modules to organize related state and actions
Implement proper state persistence for maintaining data across sessions
Use getters for computed state properties
Utilize actions for side effects and asynchronous operations
Keep the store focused on global state, not component-specific data

Files:

  • src/renderer/src/stores/settings.ts
src/renderer/**/*.{vue,ts,js,tsx,jsx}

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

渲染进程代码放在 src/renderer

Files:

  • src/renderer/src/stores/settings.ts
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/stores/settings.ts
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/stores/settings.ts
src/renderer/**/*.{vue,ts}

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

Implement lazy loading for routes and components.

Files:

  • src/renderer/src/stores/settings.ts
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/stores/settings.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/providers.ts : Add provider configuration in configPresenter/providers.ts when adding a new LLM provider

Applied to files:

  • src/renderer/src/stores/settings.ts
🔇 Additional comments (1)
src/renderer/src/stores/settings.ts (1)

656-661: Good: apply saved provider order before refreshing models

Calling loadSavedOrder() on PROVIDER_CHANGED ensures the current tab reflects the persisted ordering before model refresh. This is aligned with the PR goal to keep tabs in sync.

Comment on lines 656 to 661
window.electron.ipcRenderer.on(CONFIG_EVENTS.PROVIDER_CHANGED, async () => {
console.log('changed')
console.log('Provider changed - updating providers and order')
providers.value = await configP.getProviders()
await loadSavedOrder()
await refreshAllModels()
})
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

Wrap async IPC handler in try–catch and use structured logging

Per the repo’s TS guidelines, guard presenter calls with try–catch and log with context to avoid unhandled rejections from IPC failures.

Apply this diff:

-    window.electron.ipcRenderer.on(CONFIG_EVENTS.PROVIDER_CHANGED, async () => {
-      console.log('Provider changed - updating providers and order')
-      providers.value = await configP.getProviders()
-      await loadSavedOrder()
-      await refreshAllModels()
-    })
+    window.electron.ipcRenderer.on(CONFIG_EVENTS.PROVIDER_CHANGED, async () => {
+      try {
+        console.info('[settings][PROVIDER_CHANGED]', { ts: Date.now() })
+        providers.value = await configP.getProviders()
+        await loadSavedOrder()
+        await refreshAllModels()
+      } catch (error) {
+        console.error('[settings][PROVIDER_CHANGED][ERROR]', {
+          ts: Date.now(),
+          message: 'Failed to reload providers/order after provider change',
+          error
+        })
+      }
+    })
📝 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
window.electron.ipcRenderer.on(CONFIG_EVENTS.PROVIDER_CHANGED, async () => {
console.log('changed')
console.log('Provider changed - updating providers and order')
providers.value = await configP.getProviders()
await loadSavedOrder()
await refreshAllModels()
})
window.electron.ipcRenderer.on(CONFIG_EVENTS.PROVIDER_CHANGED, async () => {
try {
console.info('[settings][PROVIDER_CHANGED]', { ts: Date.now() })
providers.value = await configP.getProviders()
await loadSavedOrder()
await refreshAllModels()
} catch (error) {
console.error('[settings][PROVIDER_CHANGED][ERROR]', {
ts: Date.now(),
message: 'Failed to reload providers/order after provider change',
error
})
}
})
🤖 Prompt for AI Agents
In src/renderer/src/stores/settings.ts around lines 656 to 661, the async IPC
handler passed to window.electron.ipcRenderer.on is not wrapped in try–catch and
may produce unhandled promise rejections; update the handler to be an async
function wrapped in try { ... } catch (err) { logger.error({ context:
'PROVIDER_CHANGED handler', error: err }) } (or use the repo's structured
logger) and move calls to providers.value = await configP.getProviders(); await
loadSavedOrder(); await refreshAllModels(); inside the try block so any failure
is caught and logged with contextual information.

Comment on lines 1516 to 1519
// 强制更新 providers 以触发视图更新
providers.value = [...providers.value]
await configP.setProviders(providers.value)
} catch (error) {
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Sanitize before persisting providers to avoid leaking transient fields

Persisting providers.value directly may write large/ephemeral fields (e.g., websites) to config, which other code paths explicitly strip before saving. Save a sanitized, raw copy instead.

Apply this diff:

-      // 强制更新 providers 以触发视图更新
-      providers.value = [...providers.value]
-      await configP.setProviders(providers.value)
+      // 强制更新 providers 以触发视图更新
+      providers.value = [...providers.value]
+      // Persist a sanitized snapshot (strip transient fields like `websites`)
+      const sanitizedProviders = providers.value.map((p) => {
+        const raw = toRaw(p) as any
+        const { websites, ...rest } = raw
+        return rest
+      })
+      await configP.setProviders(sanitizedProviders)
📝 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
// 强制更新 providers 以触发视图更新
providers.value = [...providers.value]
await configP.setProviders(providers.value)
} catch (error) {
// 强制更新 providers 以触发视图更新
providers.value = [...providers.value]
// Persist a sanitized snapshot (strip transient fields like `websites`)
const sanitizedProviders = providers.value.map((p) => {
const raw = toRaw(p) as any
const { websites, ...rest } = raw
return rest
})
await configP.setProviders(sanitizedProviders)
🤖 Prompt for AI Agents
In src/renderer/src/stores/settings.ts around lines 1516 to 1519, the code
currently persists providers.value directly which can include large/ephemeral
fields (e.g., websites); before calling await configP.setProviders(...) create a
sanitized deep-copy (map over providers.value) that strips transient/large
fields (such as websites, caches, or runtime-only metadata) and persist that
sanitized array instead, while still updating providers.value for the UI;
replace setProviders(providers.value) with setProviders(sanitizedProviders).

@zerob13 zerob13 merged commit fb4d7f8 into dev Aug 21, 2025
2 checks passed
@zerob13 zerob13 mentioned this pull request Aug 26, 2025
@zerob13 zerob13 deleted the fix/provider-order-sync-across-tabs 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.

3 participants