Skip to content

Conversation

@yyhhyyyyyy
Copy link
Collaborator

@yyhhyyyyyy yyhhyyyyyy commented Sep 5, 2025

add web search support with configurable options for dashscope
CleanShot 2025-09-05 at 10 59 02@2x
CleanShot 2025-09-05 at 10 59 34@2x

Summary by CodeRabbit

  • New Features

    • Search Configuration for supported DashScope/Qwen models: enable search, force search, and choose strategy (Turbo or Max).
    • Settings exposed in chat UI (thread creation, chat settings, title view) and applied when starting or continuing streams.
    • Model defaults seed per-conversation settings, which users can override per thread.
  • Chores

    • Conversation storage schema and import updated to persist the new search settings while preserving compatibility.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 5, 2025

Walkthrough

Adds search configuration (enableSearch, forcedSearch, searchStrategy) across provider defaults, presenters, UI, types, and SQLite persistence; extends startStreamCompletion signature to accept and forward these options; bumps DB schema to version 7 and updates import/exchange paths.

Changes

Cohort / File(s) Summary
Provider model defaults
src/main/presenter/configPresenter/providerModelSettings.ts
Adds search fields for qwen-turbo-latest; switches enableSearch/forcedSearch defaulting to nullish coalescing (??).
Streaming presenter API
src/main/presenter/llmProviderPresenter/index.ts
Adds optional params enableSearch, forcedSearch, searchStrategy to startStreamCompletion and assigns them into modelConfig when provided.
Thread presenter wiring
src/main/presenter/threadPresenter/index.ts
Reads conversation.settings.{enableSearch,forcedSearch,searchStrategy} and passes them to startStreamCompletion at all stream call sites.
SQLite schema & table
src/main/presenter/sqlitePresenter/tables/conversations.ts
Bumps schema to v7; adds columns enable_search, forced_search, search_strategy; persists, selects, lists, and updates these fields; maps to Conversation.settings.
SQLite import
src/main/presenter/sqlitePresenter/importData.ts
SELECTs new columns when available, falls back to legacy projection otherwise; inserts into conversations with new columns when possible using nullish coalescing for explicit false.
Renderer — Chat config UI
src/renderer/src/components/ChatConfig.vue
Adds props/emits for enableSearch/forcedSearch/searchStrategy; conditionally shows search UI for allowed Dashscope models (duplicate UI blocks present).
Renderer — Thread creation UI
src/renderer/src/components/NewThread.vue
Adds reactive state and v-model bindings for search fields, seeds from model defaults, includes them in new-thread payload.
Renderer — Title view integration
src/renderer/src/components/TitleView.vue
Adds local refs, watchers, and v-model bindings to propagate search fields between UI and chat store.
Renderer — Store
src/renderer/src/stores/chat.ts
Initializes settings.enableSearch, settings.forcedSearch, settings.searchStrategy to undefined.
Shared/public types
src/shared/types/presenters/legacy.presenters.d.ts, .../llmprovider.presenter.d.ts, .../thread.presenter.d.ts
Extends ILlmProviderPresenter.startStreamCompletion signature with enableSearch/forcedSearch/searchStrategy; adds those fields to CONVERSATION_SETTINGS and DefaultModelSetting types.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant UI as UI (TitleView/NewThread/ChatConfig)
  participant TP as ThreadPresenter
  participant DB as ConversationsTable (SQLite v7)
  participant LLM as LLMProviderPresenter
  participant Prov as Provider (DashScope)

  UI->>TP: user starts stream / creates thread
  TP->>DB: get(conversationId)
  DB-->>TP: settings { enableSearch, forcedSearch, searchStrategy, ... }
  TP->>LLM: startStreamCompletion(..., verbosity, enableSearch?, forcedSearch?, searchStrategy?)
  Note over TP,LLM: new params forwarded into modelConfig
  LLM->>Prov: stream request (modelConfig with search options)
  Prov-->>LLM: tokens / events
  LLM-->>TP: streaming callbacks
  TP-->>UI: render updates
Loading
sequenceDiagram
  autonumber
  participant Import as ImportData
  participant SrcDB as Source DB
  participant Tgt as ConversationsTable (v7)

  Import->>SrcDB: SELECT ... enable_search, forced_search, search_strategy
  alt columns exist
    SrcDB-->>Import: rows with search fields
  else legacy schema
    SrcDB-->>Import: rows without search fields
    Note over Import: fill search fields as null/undefined
  end
  Import->>Tgt: create(..., settings with enableSearch/forcedSearch/searchStrategy)
  Tgt-->>Import: persisted
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • zerob13

Poem

I hop through configs, toggles in my paw,
Turbo gusts or max—I'll nudge the draw.
From UI to DB, I carry seeds,
Streaming paths and threaded deeds.
Carrot-coded flags, persisted with a cheer 🥕✨

✨ 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/chat-components-search-support

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 or @coderabbit 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: 5

Caution

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

⚠️ Outside diff range comments (1)
src/main/presenter/threadPresenter/index.ts (1)

1756-1760: Guard potential undefined modelConfig before dereferencing .functionCall.

this.configPresenter.getModelConfig(...) can return undefined. Passing modelConfig.functionCall will NPE at runtime and violate strict TS. Use optional chaining with a sane default.

Apply:

-        modelConfig.functionCall
+        modelConfig?.functionCall ?? false
🧹 Nitpick comments (18)
src/main/presenter/configPresenter/providerModelSettings.ts (1)

2505-2508: Deduplicate dashscope search defaults with a shared constant

These three flags repeat across many dashscope models. Suggest extracting a shared constant and spreading it to reduce drift.

Example:

+// DashScope-wide default search flags
+export const dashscopeSearchDefaults = {
+  enableSearch: false,
+  forcedSearch: false,
+  searchStrategy: 'turbo' as const,
+}
...
       id: 'qwen-max-latest',
       name: 'Qwen Max Latest',
       temperature: 0.7,
       contextLength: 131072,
       maxTokens: 8192,
       match: ['qwen-max-latest'],
       vision: false,
       functionCall: true,
-      reasoning: false,
-      enableSearch: false,
-      forcedSearch: false,
-      searchStrategy: 'turbo'
+      reasoning: false,
+      ...dashscopeSearchDefaults
src/shared/types/presenters/thread.presenter.d.ts (1)

25-27: Add brief JSDoc to clarify precedence and semantics

Document that undefined defers to model/provider defaults, and that forcedSearch implies search regardless of enableSearch.

 export type CONVERSATION_SETTINGS = {
   systemPrompt: string
   temperature: number
   contextLength: number
   maxTokens: number
   providerId: string
   modelId: string
   artifacts: 0 | 1
   enabledMcpTools?: string[]
   thinkingBudget?: number
-  enableSearch?: boolean
-  forcedSearch?: boolean
-  searchStrategy?: 'turbo' | 'max'
+  /** If true, enables web search; if undefined, use model/provider default. */
+  enableSearch?: boolean
+  /** If true, always perform web search for this turn, ignoring enableSearch. */
+  forcedSearch?: boolean
+  /** Search strategy; if undefined, default to provider/model config (usually 'turbo'). */
+  searchStrategy?: 'turbo' | 'max'
src/shared/types/presenters/llmprovider.presenter.d.ts (1)

154-158: Move optional startStreamCompletion parameters into a StartStreamOptions bag
This refactor will affect numerous call sites across tests (test/main/presenter/llmProviderPresenter.test.ts), the chat store (renderer/src/stores/chat.ts), and presenter implementations/types (main/presenter/**, shared/types/presenters/**/*.d.ts); ensure every invocation is updated or an overload is provided for backward compatibility.

src/shared/types/presenters/legacy.presenters.d.ts (1)

615-619: Keep legacy presenter in sync; plan migration to options object

Mirror the options-bag approach here when you adopt it in the main presenter to avoid interface drift across public types.

Use the same verification script from the core presenter to locate impacted call sites.

src/main/presenter/sqlitePresenter/importData.ts (2)

110-117: Also default the new fields in the legacy SELECT fallback.

Without this, the new INSERT (above) may error when old DBs are imported.

         conversations = conversations.map((conv) => ({
           ...conv,
           enabled_mcp_tools: null,
           thinking_budget: null,
           reasoning_effort: null,
-          verbosity: null
+          verbosity: null,
+          enable_search: null,
+          forced_search: null,
+          search_strategy: null
         }))

36-39: Escape PRAGMA key passwords.

A single quote in sourcePassword/targetPassword breaks the PRAGMA. Replace ' with ''.

-      this.sourceDb.pragma(`key='${sourcePassword}'`)
+      this.sourceDb.pragma(`key='${String(sourcePassword).replaceAll("'", "''")}'`)
-        this.targetDb.pragma(`key='${targetPassword}'`)
+        this.targetDb.pragma(`key='${String(targetPassword).replaceAll("'", "''")}'`)

Also applies to: 48-51

src/renderer/src/components/NewThread.vue (3)

170-173: Deduplicate SearchStrategy typing by reusing a shared type.

To avoid drift, import a shared SearchStrategy type (e.g., from @shared/types) instead of hardcoding 'turbo' | 'max'.


433-439: Tighten types; avoid casting the payload to any.

Add enableSearch/forcedSearch/searchStrategy to the thread creation payload type so this cast isn’t needed.

Example minimal change (types file, not shown here):

  • extend CONVERSATION_SETTINGS with enableSearch?: boolean; forcedSearch?: boolean; searchStrategy?: 'turbo' | 'max'
  • update createThread signature accordingly

261-262: Use English for logs per repo guidelines.

Replace the Chinese log message with an English one for consistency.

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

712-714: English user-facing error message.

Repo requires English logs/strings; also likely surfaced in UI.

-      yield { type: 'error', data: { eventId, error: '已达到最大并发流数量限制' } }
+      yield { type: 'error', data: { eventId, error: 'Max concurrent stream limit reached' } }

1260-1272: Standardize error text to English and avoid non-English templates.

Multiple emitted strings are Chinese. Please convert to English to meet the logging/comment policy.

Also applies to: 1296-1307, 1313-1345

src/renderer/src/components/TitleView.vue (2)

134-137: State sync is correct; consider centralizing SearchStrategy type.

Everything syncs cleanly between UI and store. As a small improvement, import a shared SearchStrategy type to avoid repeating the union.

Also applies to: 183-196, 300-311, 338-367, 397-400


183-196: Comment language consistency.

Replace Chinese comments with English per codebase rules.

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

2076-2080: Two search mechanisms risk user confusion; confirm intent.

(userMessage.content as UserMessageContent).search is driven by global input_webSearch, while the new per-conversation enableSearch/forcedSearch/searchStrategy only affect provider-side search. If that’s intentional (local browser vs. provider-native search), consider renaming UI copy to disambiguate and/or add a tooltip.

Would you like a small copy update proposal for the i18n keys?


962-964: Use English for logs/comments per repo guidelines.

Several new/updated logs remain in Chinese (e.g., “设置搜索引擎失败”). Please switch logs/comments to English consistently.

src/renderer/src/components/ChatConfig.vue (2)

115-139: Avoid hard-coded model allowlist inside computed; centralize and reuse.

Inline array re-allocates every compute and is brittle as models evolve. Move allowlist to a top-level constant or (preferably) derive from model metadata/config.

Apply this diff here, and add the constant near the top of the script:

-  // 支持搜索的模型列表
-  const enableSearchModels = [
-    'qwen-max',
-    'qwen-plus',
-    'qwen-plus-latest',
-    'qwen-plus-2025-07-14',
-    'qwen-flash',
-    'qwen-flash-2025-07-28',
-    'qwen-turbo',
-    'qwen-turbo-latest',
-    'qwen-turbo-2025-07-15',
-    'qwq-plus'
-  ]
-
-  return enableSearchModels.some((modelName) =>
+  return ENABLE_SEARCH_MODELS.some((modelName) =>
     props.modelId?.toLowerCase().includes(modelName.toLowerCase())
   )

Add (outside the component script):

const ENABLE_SEARCH_MODELS = [
  'qwen-max',
  'qwen-plus',
  'qwen-plus-latest',
  'qwen-plus-2025-07-14',
  'qwen-flash',
  'qwen-flash-2025-07-28',
  'qwen-turbo',
  'qwen-turbo-latest',
  'qwen-turbo-2025-07-15',
  'qwq-plus',
] as const

115-117: Comments/logs should be in English.

Per guidelines, translate inline comments like “是否显示搜索配置 - 支持 Dashscope 的特定模型”.

Also applies to: 542-542

src/main/presenter/sqlitePresenter/tables/conversations.ts (1)

168-172: Potential “'NULL' string” bug on enabled_mcp_tools.

This inserts the literal string 'NULL' when empty, not SQL NULL. Prefer null so reads don’t get "NULL".

Would you like a quick patch for this as well?

📜 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 f9b62ff and 1256d41.

📒 Files selected for processing (12)
  • src/main/presenter/configPresenter/providerModelSettings.ts (2 hunks)
  • src/main/presenter/llmProviderPresenter/index.ts (2 hunks)
  • src/main/presenter/sqlitePresenter/importData.ts (1 hunks)
  • src/main/presenter/sqlitePresenter/tables/conversations.ts (9 hunks)
  • src/main/presenter/threadPresenter/index.ts (6 hunks)
  • src/renderer/src/components/ChatConfig.vue (4 hunks)
  • src/renderer/src/components/NewThread.vue (4 hunks)
  • src/renderer/src/components/TitleView.vue (10 hunks)
  • src/renderer/src/stores/chat.ts (1 hunks)
  • src/shared/types/presenters/legacy.presenters.d.ts (2 hunks)
  • src/shared/types/presenters/llmprovider.presenter.d.ts (1 hunks)
  • src/shared/types/presenters/thread.presenter.d.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (21)
**/*.{js,jsx,ts,tsx}

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

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

Files:

  • src/shared/types/presenters/thread.presenter.d.ts
  • src/main/presenter/configPresenter/providerModelSettings.ts
  • src/renderer/src/stores/chat.ts
  • src/main/presenter/sqlitePresenter/importData.ts
  • src/shared/types/presenters/llmprovider.presenter.d.ts
  • src/main/presenter/llmProviderPresenter/index.ts
  • src/shared/types/presenters/legacy.presenters.d.ts
  • src/main/presenter/sqlitePresenter/tables/conversations.ts
  • src/main/presenter/threadPresenter/index.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/error-logging.mdc)

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

Enable and adhere to strict TypeScript type checking across the codebase

Files:

  • src/shared/types/presenters/thread.presenter.d.ts
  • src/main/presenter/configPresenter/providerModelSettings.ts
  • src/renderer/src/stores/chat.ts
  • src/main/presenter/sqlitePresenter/importData.ts
  • src/shared/types/presenters/llmprovider.presenter.d.ts
  • src/main/presenter/llmProviderPresenter/index.ts
  • src/shared/types/presenters/legacy.presenters.d.ts
  • src/main/presenter/sqlitePresenter/tables/conversations.ts
  • src/main/presenter/threadPresenter/index.ts
src/shared/**/*.{ts,tsx,d.ts}

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

共享类型定义放在 shared 目录

Files:

  • src/shared/types/presenters/thread.presenter.d.ts
  • src/shared/types/presenters/llmprovider.presenter.d.ts
  • src/shared/types/presenters/legacy.presenters.d.ts
**/*.{ts,tsx,js,jsx,vue}

📄 CodeRabbit inference engine (CLAUDE.md)

Write logs and comments in English

Files:

  • src/shared/types/presenters/thread.presenter.d.ts
  • src/main/presenter/configPresenter/providerModelSettings.ts
  • src/renderer/src/stores/chat.ts
  • src/main/presenter/sqlitePresenter/importData.ts
  • src/shared/types/presenters/llmprovider.presenter.d.ts
  • src/renderer/src/components/NewThread.vue
  • src/main/presenter/llmProviderPresenter/index.ts
  • src/shared/types/presenters/legacy.presenters.d.ts
  • src/main/presenter/sqlitePresenter/tables/conversations.ts
  • src/main/presenter/threadPresenter/index.ts
  • src/renderer/src/components/TitleView.vue
  • src/renderer/src/components/ChatConfig.vue
src/shared/**/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Keep shared types, utilities, constants, and IPC contracts under src/shared/

Files:

  • src/shared/types/presenters/thread.presenter.d.ts
  • src/shared/types/presenters/llmprovider.presenter.d.ts
  • src/shared/types/presenters/legacy.presenters.d.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/configPresenter/providerModelSettings.ts
  • src/renderer/src/stores/chat.ts
  • src/main/presenter/sqlitePresenter/importData.ts
  • src/main/presenter/llmProviderPresenter/index.ts
  • src/main/presenter/sqlitePresenter/tables/conversations.ts
  • src/main/presenter/threadPresenter/index.ts
src/main/**/*.ts

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

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

Files:

  • src/main/presenter/configPresenter/providerModelSettings.ts
  • src/main/presenter/sqlitePresenter/importData.ts
  • src/main/presenter/llmProviderPresenter/index.ts
  • src/main/presenter/sqlitePresenter/tables/conversations.ts
  • src/main/presenter/threadPresenter/index.ts
src/main/**/*.{ts,js,tsx,jsx}

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

主进程代码放在 src/main

Files:

  • src/main/presenter/configPresenter/providerModelSettings.ts
  • src/main/presenter/sqlitePresenter/importData.ts
  • src/main/presenter/llmProviderPresenter/index.ts
  • src/main/presenter/sqlitePresenter/tables/conversations.ts
  • src/main/presenter/threadPresenter/index.ts
src/main/presenter/**/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Maintain one Presenter per functional domain under src/main/presenter/

Files:

  • src/main/presenter/configPresenter/providerModelSettings.ts
  • src/main/presenter/sqlitePresenter/importData.ts
  • src/main/presenter/llmProviderPresenter/index.ts
  • src/main/presenter/sqlitePresenter/tables/conversations.ts
  • src/main/presenter/threadPresenter/index.ts
src/main/presenter/configPresenter/**

📄 CodeRabbit inference engine (CLAUDE.md)

Centralize configuration logic under configPresenter/

Files:

  • src/main/presenter/configPresenter/providerModelSettings.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/chat.ts
  • src/renderer/src/components/NewThread.vue
  • src/renderer/src/components/TitleView.vue
  • src/renderer/src/components/ChatConfig.vue
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/chat.ts
src/renderer/**/*.{vue,ts,js,tsx,jsx}

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

渲染进程代码放在 src/renderer

Files:

  • src/renderer/src/stores/chat.ts
  • src/renderer/src/components/NewThread.vue
  • src/renderer/src/components/TitleView.vue
  • src/renderer/src/components/ChatConfig.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/stores/chat.ts
  • src/renderer/src/components/NewThread.vue
  • src/renderer/src/components/TitleView.vue
  • src/renderer/src/components/ChatConfig.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/stores/chat.ts
  • src/renderer/src/components/NewThread.vue
  • src/renderer/src/components/TitleView.vue
  • src/renderer/src/components/ChatConfig.vue
src/renderer/**/*.{vue,ts}

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

Implement lazy loading for routes and components.

Files:

  • src/renderer/src/stores/chat.ts
  • src/renderer/src/components/NewThread.vue
  • src/renderer/src/components/TitleView.vue
  • src/renderer/src/components/ChatConfig.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.

Use Pinia for frontend state management

Files:

  • src/renderer/src/stores/chat.ts
  • src/renderer/src/components/NewThread.vue
  • src/renderer/src/components/TitleView.vue
  • src/renderer/src/components/ChatConfig.vue
src/renderer/src/**

📄 CodeRabbit inference engine (CLAUDE.md)

Place full application UI functionality (tab content) under src/renderer/src/ organized by feature

Files:

  • src/renderer/src/stores/chat.ts
  • src/renderer/src/components/NewThread.vue
  • src/renderer/src/components/TitleView.vue
  • src/renderer/src/components/ChatConfig.vue
src/renderer/src/**/*.vue

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

Use scoped styles to prevent CSS conflicts between components

Files:

  • src/renderer/src/components/NewThread.vue
  • src/renderer/src/components/TitleView.vue
  • src/renderer/src/components/ChatConfig.vue
src/renderer/**/*.vue

📄 CodeRabbit inference engine (CLAUDE.md)

src/renderer/**/*.vue: Use Vue 3 Composition API for all Vue components
Use Tailwind CSS with scoped styles for component styling
When creating new UI components, use Composition API with proper TypeScript typing, ensure responsive design (Tailwind), and include error/loading states

Files:

  • src/renderer/src/components/NewThread.vue
  • src/renderer/src/components/TitleView.vue
  • src/renderer/src/components/ChatConfig.vue
src/main/presenter/llmProviderPresenter/index.ts

📄 CodeRabbit inference engine (.cursor/rules/llm-agent-loop.mdc)

src/main/presenter/llmProviderPresenter/index.ts: src/main/presenter/llmProviderPresenter/index.ts should manage the overall Agent loop, conversation history, tool execution via McpPresenter, and frontend communication via eventBus.
The main Agent loop in llmProviderPresenter/index.ts should handle multi-round LLM calls and tool usage, maintaining conversation state and controlling the loop with needContinueConversation and toolCallCount.
The main Agent loop should send standardized STREAM_EVENTS (RESPONSE, END, ERROR) to the frontend via eventBus.
The main Agent loop should buffer text content, handle tool call events, format tool results for the next LLM call, and manage conversation continuation logic.

Implement the Agent Loop layer in llmProviderPresenter/index.ts

Files:

  • src/main/presenter/llmProviderPresenter/index.ts
🧠 Learnings (13)
📚 Learning: 2025-09-01T09:16:58.043Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-01T09:16:58.043Z
Learning: Applies to src/main/presenter/configPresenter/providers.ts : Add new provider configuration entries in configPresenter/providers.ts

Applied to files:

  • src/main/presenter/configPresenter/providerModelSettings.ts
📚 Learning: 2025-09-01T09:16:58.043Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-01T09:16:58.043Z
Learning: Applies to src/main/presenter/llmProviderPresenter/providers/*.ts : Each LLM provider must implement a coreStream method following the standardized event interface

Applied to files:

  • src/shared/types/presenters/llmprovider.presenter.d.ts
  • src/main/presenter/llmProviderPresenter/index.ts
📚 Learning: 2025-07-21T01:46:52.880Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: .cursor/rules/llm-agent-loop.mdc:0-0
Timestamp: 2025-07-21T01:46:52.880Z
Learning: Applies to src/main/presenter/llmProviderPresenter/streamEvents.ts : Standardized stream events should conform to the `LLMCoreStreamEvent` interface, ideally defined in a shared file such as `src/main/presenter/llmProviderPresenter/streamEvents.ts`.

Applied to files:

  • src/shared/types/presenters/llmprovider.presenter.d.ts
📚 Learning: 2025-07-21T01:46:52.880Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: .cursor/rules/llm-agent-loop.mdc:0-0
Timestamp: 2025-07-21T01:46:52.880Z
Learning: Applies to src/main/presenter/llmProviderPresenter/providers/*.ts : The `coreStream` method in each Provider must perform a single streaming API request per conversation round and must not contain multi-round tool call loop logic.

Applied to files:

  • src/shared/types/presenters/llmprovider.presenter.d.ts
  • src/main/presenter/llmProviderPresenter/index.ts
  • src/main/presenter/threadPresenter/index.ts
📚 Learning: 2025-07-21T01:46:52.880Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: .cursor/rules/llm-agent-loop.mdc:0-0
Timestamp: 2025-07-21T01:46:52.880Z
Learning: Applies to src/main/presenter/llmProviderPresenter/providers/*.ts : Provider implementations must use a `coreStream` method that yields standardized stream events to decouple the main loop from provider-specific details.

Applied to files:

  • src/shared/types/presenters/llmprovider.presenter.d.ts
  • src/main/presenter/llmProviderPresenter/index.ts
📚 Learning: 2025-07-21T01:46:52.880Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: .cursor/rules/llm-agent-loop.mdc:0-0
Timestamp: 2025-07-21T01:46:52.880Z
Learning: Applies to src/main/presenter/llmProviderPresenter/index.ts : The main Agent loop in `llmProviderPresenter/index.ts` should handle multi-round LLM calls and tool usage, maintaining conversation state and controlling the loop with `needContinueConversation` and `toolCallCount`.

Applied to files:

  • src/main/presenter/llmProviderPresenter/index.ts
📚 Learning: 2025-07-21T01:46:52.880Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: .cursor/rules/llm-agent-loop.mdc:0-0
Timestamp: 2025-07-21T01:46:52.880Z
Learning: Applies to src/main/presenter/llmProviderPresenter/index.ts : The main Agent loop should buffer text content, handle tool call events, format tool results for the next LLM call, and manage conversation continuation logic.

Applied to files:

  • src/main/presenter/llmProviderPresenter/index.ts
📚 Learning: 2025-07-21T01:46:52.880Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: .cursor/rules/llm-agent-loop.mdc:0-0
Timestamp: 2025-07-21T01:46:52.880Z
Learning: Applies to src/main/presenter/llmProviderPresenter/index.ts : `src/main/presenter/llmProviderPresenter/index.ts` should manage the overall Agent loop, conversation history, tool execution via `McpPresenter`, and frontend communication via `eventBus`.

Applied to files:

  • src/main/presenter/llmProviderPresenter/index.ts
📚 Learning: 2025-09-01T09:16:58.043Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-01T09:16:58.043Z
Learning: Applies to src/main/presenter/llmProviderPresenter/index.ts : Implement the Agent Loop layer in llmProviderPresenter/index.ts

Applied to files:

  • src/main/presenter/llmProviderPresenter/index.ts
📚 Learning: 2025-07-21T01:46:52.880Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: .cursor/rules/llm-agent-loop.mdc:0-0
Timestamp: 2025-07-21T01:46:52.880Z
Learning: Applies to src/main/presenter/llmProviderPresenter/providers/*.ts : Provider files should implement helper methods such as `formatMessages`, `convertToProviderTools`, `parseFunctionCalls`, and `prepareFunctionCallPrompt` as needed for provider-specific logic.

Applied to files:

  • src/main/presenter/llmProviderPresenter/index.ts
📚 Learning: 2025-07-21T01:46:52.880Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: .cursor/rules/llm-agent-loop.mdc:0-0
Timestamp: 2025-07-21T01:46:52.880Z
Learning: Applies to src/main/presenter/llmProviderPresenter/providers/*.ts : Each file in `src/main/presenter/llmProviderPresenter/providers/*.ts` should handle interaction with a specific LLM API, including request/response formatting, tool definition conversion, native/non-native tool call management, and standardizing output streams to a common event format.

Applied to files:

  • src/main/presenter/llmProviderPresenter/index.ts
📚 Learning: 2025-09-04T11:03:30.150Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: .cursor/rules/provider-guidelines.mdc:0-0
Timestamp: 2025-09-04T11:03:30.150Z
Learning: Integrate via the llmProviderPresenter entry point (src/main/presenter/llmProviderPresenter/index.ts) as the related implementation entry

Applied to files:

  • src/main/presenter/llmProviderPresenter/index.ts
📚 Learning: 2025-07-21T01:46:52.880Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: .cursor/rules/llm-agent-loop.mdc:0-0
Timestamp: 2025-07-21T01:46:52.880Z
Learning: Applies to src/main/presenter/llmProviderPresenter/index.ts : The main Agent loop should send standardized `STREAM_EVENTS` (`RESPONSE`, `END`, `ERROR`) to the frontend via `eventBus`.

Applied to files:

  • src/main/presenter/llmProviderPresenter/index.ts
⏰ 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 (22)
src/main/presenter/configPresenter/providerModelSettings.ts (1)

3090-3092: Good: nullish coalescing preserves explicit false

Using ?? false for enableSearch/forcedSearch avoids clobbering false with defaults. This is the right behavior.

src/shared/types/presenters/legacy.presenters.d.ts (1)

686-689: Conversation search fields added: LGTM

The added fields align with the shared types and provider config.

src/renderer/src/components/NewThread.vue (2)

94-97: Good addition: wires new search options into ChatConfig.

Bindings look consistent with v-model naming.


194-197: LGTM: respect model defaults only when user hasn't set a value.

This prevents clobbering user choices.

src/renderer/src/components/TitleView.vue (1)

73-76: Good: plumbed v-model and emits for search options.

Consistent with ChatConfig API; update handlers are scoped.

Also applies to: 88-91

src/main/presenter/threadPresenter/index.ts (6)

1905-1909: Propagating new search options in continue flow — good.

Keeps behavior consistent across initial/continue paths.


1980-1984: Same signature risk here as well. See earlier comment; keep params aligned and optional.


4026-4030: Resume path also destructures new fields — consistent.

OK.


4087-4091: Resume path startStreamCompletion args — ensure provider handles undefineds.

If providers differentiate between “unset” and explicit false, ensure undefined is forwarded, not coerced.


1781-1785: Settings type parity verified: The optional fields enableSearch, forcedSearch, searchStrategy, and verbosity are defined in CONVERSATION_SETTINGS (thread.presenter.d.ts:25–29) and the startStreamCompletion signature in llmProviderPresenter/index.ts (lines 692–707) includes them as optional parameters.


1796-1800: Signature alignment confirmed: startStreamCompletion in llmprovider.presenter.d.ts and its implementation in llmProviderPresenter declare the four new optional parameters (verbosity, enableSearch, forcedSearch, searchStrategy) in the same order, and the call in threadPresenter matches this order.

src/renderer/src/components/ChatConfig.vue (3)

29-31: New props for search options — OK.

Types look right and optional, matching presenter/database.


61-64: Emits wired correctly.

Events follow the existing v-model-style update pattern.


542-617: Missing i18n entries; duplicate label

  • No definitions found for settings.model.modelConfig.enableSearch.label|description, forcedSearch.label, or any searchStrategy.* keys in your locale JSONs—add them (in src/renderer/src/i18n/common.json).
  • The section title and the first toggle both use the same translation key; introduce a distinct key for the header to avoid duplication.
src/main/presenter/sqlitePresenter/tables/conversations.ts (8)

24-27: Type shape extended correctly.

enable_search, forced_search, search_strategy columns added to row type — OK.


125-125: Version bump to 7 — OK.


147-153: INSERT column list updated — count/order must match VALUES.

Looks consistent with the appended fields; keep this in sync if columns change.


203-206: SELECT includes new columns — OK.


236-242: Mapping to public settings — OK.

Booleans and union types mapped correctly.


369-373: List SELECT includes new columns — OK.


402-406: List mapping — OK.

Matches get() mapping.


112-119: Migration v7 runner verified — no changes needed
getLatestVersion() returns 7 for conversations and migrate() applies the ALTER statements on startup, so any legacy DB or dump will have the new search columns added before use.

Comment on lines +704 to 708
verbosity?: 'low' | 'medium' | 'high',
enableSearch?: boolean,
forcedSearch?: boolean,
searchStrategy?: 'turbo' | 'max'
): AsyncGenerator<LLMAgentEvent, void, unknown> {
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

Avoid mutating shared modelConfig; use a per-request copy.

getModelConfig may return a shared object; in concurrent streams these mutations can leak across requests. Clone before overriding.

-    const modelConfig = this.configPresenter.getModelConfig(modelId, providerId)
+    const modelConfig = { ...this.configPresenter.getModelConfig(modelId, providerId) }

Also applies to: 730-738

🤖 Prompt for AI Agents
In src/main/presenter/llmProviderPresenter/index.ts around lines 704-708 (and
similarly 730-738), getModelConfig may return a shared object that is currently
mutated for each request; clone the returned modelConfig into a per-request copy
before applying overrides (e.g., const modelConfig = structuredClone(await
getModelConfig(...)) or use a deep-clone helper if structuredClone isn't
available), then mutate that local copy and pass it down so the original shared
config is never modified and concurrent streams cannot leak state across
requests; ensure the cloned object preserves the expected type/interface before
using.

Comment on lines +173 to 177
settings.verbosity !== undefined ? settings.verbosity : null,
settings.enableSearch !== undefined ? (settings.enableSearch ? 1 : 0) : null,
settings.forcedSearch !== undefined ? (settings.forcedSearch ? 1 : 0) : null,
settings.searchStrategy !== undefined ? settings.searchStrategy : 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

Tri-state semantics: allow reverting to NULL.

Create supports NULL (inherit defaults), but update path below only writes 0/1 and cannot clear back to NULL. This breaks “use provider default” after a user toggled the setting once.

Apply:

-      settings.enableSearch !== undefined ? (settings.enableSearch ? 1 : 0) : null,
-      settings.forcedSearch !== undefined ? (settings.forcedSearch ? 1 : 0) : null,
+      settings.enableSearch !== undefined ? (settings.enableSearch ? 1 : 0) : null,
+      settings.forcedSearch !== undefined ? (settings.forcedSearch ? 1 : 0) : null,
       settings.searchStrategy !== undefined ? settings.searchStrategy : null

And mirror the same tri-state logic in update() (see next comment) by supporting explicit NULL assignment.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/main/presenter/sqlitePresenter/tables/conversations.ts around lines
173-177, the create path already allows tri-state (value/0/1 or NULL) but the
update path currently only writes 0/1 and cannot clear to NULL; update the
update() assignments to mirror the create ternary logic so explicit NULL can be
stored when the incoming settings property is undefined vs. intentionally null —
specifically: for verbosity and searchStrategy assign settings.verbosity !==
undefined ? settings.verbosity : null and settings.searchStrategy !== undefined
? settings.searchStrategy : null, and for enableSearch and forcedSearch assign
settings.enableSearch !== undefined ? (settings.enableSearch ? 1 : 0) : null and
settings.forcedSearch !== undefined ? (settings.forcedSearch ? 1 : 0) : null so
update can clear back to NULL (use provider default).

Comment on lines +310 to +321
if (data.settings.enableSearch !== undefined) {
updates.push('enable_search = ?')
params.push(data.settings.enableSearch ? 1 : 0)
}
if (data.settings.forcedSearch !== undefined) {
updates.push('forced_search = ?')
params.push(data.settings.forcedSearch ? 1 : 0)
}
if (data.settings.searchStrategy !== undefined) {
updates.push('search_strategy = ?')
params.push(data.settings.searchStrategy)
}
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

Update path cannot clear values back to NULL.

Currently only true/false writes are possible; no way to “unset”. Support null (meaning revert to SQL NULL) in updates.

Apply:

-      if (data.settings.enableSearch !== undefined) {
+      if ('enableSearch' in data.settings) {
         updates.push('enable_search = ?')
-        params.push(data.settings.enableSearch ? 1 : 0)
+        params.push(
+          data.settings.enableSearch === null
+            ? null
+            : data.settings.enableSearch
+            ? 1
+            : 0
+        )
       }
-      if (data.settings.forcedSearch !== undefined) {
+      if ('forcedSearch' in data.settings) {
         updates.push('forced_search = ?')
-        params.push(data.settings.forcedSearch ? 1 : 0)
+        params.push(
+          data.settings.forcedSearch === null
+            ? null
+            : data.settings.forcedSearch
+            ? 1
+            : 0
+        )
       }
-      if (data.settings.searchStrategy !== undefined) {
+      if ('searchStrategy' in data.settings) {
         updates.push('search_strategy = ?')
-        params.push(data.settings.searchStrategy)
+        params.push(data.settings.searchStrategy ?? null)
       }

Follow-up: allow null in the corresponding TypeScript types used for updates.

📝 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
if (data.settings.enableSearch !== undefined) {
updates.push('enable_search = ?')
params.push(data.settings.enableSearch ? 1 : 0)
}
if (data.settings.forcedSearch !== undefined) {
updates.push('forced_search = ?')
params.push(data.settings.forcedSearch ? 1 : 0)
}
if (data.settings.searchStrategy !== undefined) {
updates.push('search_strategy = ?')
params.push(data.settings.searchStrategy)
}
if ('enableSearch' in data.settings) {
updates.push('enable_search = ?')
params.push(
data.settings.enableSearch === null
? null
: data.settings.enableSearch
? 1
: 0
)
}
if ('forcedSearch' in data.settings) {
updates.push('forced_search = ?')
params.push(
data.settings.forcedSearch === null
? null
: data.settings.forcedSearch
? 1
: 0
)
}
if ('searchStrategy' in data.settings) {
updates.push('search_strategy = ?')
params.push(data.settings.searchStrategy ?? null)
}

Comment on lines +63 to 66
enableSearch: undefined,
forcedSearch: undefined,
searchStrategy: undefined,
reasoningEffort: undefined,
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

Avoid persisting undefined fields that can clobber saved settings

saveChatConfig() passes the entire chatConfig.value to updateConversationSettings(...). If the main layer naively merges objects, undefined values for enableSearch/forcedSearch/searchStrategy can overwrite existing DB values.

Two fixes (apply both for safety):

  • Do not include these keys until the user picks values.
-    enableSearch: undefined,
-    forcedSearch: undefined,
-    searchStrategy: undefined,
+    // Search-related settings omitted by default to inherit model/provider defaults
  • And send only defined keys when saving (outside the selected range, illustrative):
// In saveChatConfig()
const payload = Object.fromEntries(
  Object.entries(chatConfig.value).filter(([, v]) => v !== undefined)
) as Partial<CONVERSATION_SETTINGS>
await threadP.updateConversationSettings(getActiveThreadId()!, payload)
🤖 Prompt for AI Agents
In src/renderer/src/stores/chat.ts around lines 63-66, the chatConfig object
contains keys set to undefined (enableSearch, forcedSearch, searchStrategy,
reasoningEffort) which can clobber saved DB settings when passed directly to
updateConversationSettings; remove those keys from chatConfig until the user
explicitly picks values (i.e., don't initialize them to undefined or delete them
when unset) and, in saveChatConfig(), build the payload by filtering out entries
with undefined values so only defined keys are sent to
threadP.updateConversationSettings(getActiveThreadId()!, payload).

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/main/presenter/sqlitePresenter/importData.ts (1)

36-39: Password quoting in PRAGMA can break (and is unsafe) when the passphrase contains quotes.

Interpolate via JSON.stringify to ensure proper escaping.

-      this.sourceDb.pragma(`cipher='sqlcipher'`)
-      this.sourceDb.pragma(`key='${sourcePassword}'`)
+      this.sourceDb.pragma("cipher='sqlcipher'")
+      this.sourceDb.pragma(`key = ${JSON.stringify(sourcePassword)}`)
-        this.targetDb.pragma(`cipher='sqlcipher'`)
-        this.targetDb.pragma(`key='${targetPassword}'`)
+        this.targetDb.pragma("cipher='sqlcipher'")
+        this.targetDb.pragma(`key = ${JSON.stringify(targetPassword)}`)

Also applies to: 48-51

♻️ Duplicate comments (1)
src/main/presenter/sqlitePresenter/importData.ts (1)

174-176: Resolved: search fields now persisted on INSERT (addresses prior review).

The INSERT column list includes enable_search, forced_search, and search_strategy with matching placeholders. This fixes the earlier data loss on import.

🧹 Nitpick comments (3)
src/main/presenter/sqlitePresenter/importData.ts (3)

5-8: Translate comments to English per repo guidelines.

Current comments are in Chinese; guidelines require English logs/comments.

Example:

-/**
- * 数据导入类
- * 用于从外部SQLite数据库导入数据到当前数据库
- */
+/**
+ * Data Importer
+ * Imports data from an external SQLite database into the current database.
+ */

71-73: Avoid any[]; define a typed Conversation shape matching schema v7.

Improves safety when binding values and reduces silent coercion bugs (like the verbosity issue).

Minimal example:

type ConversationRow = {
  conv_id: string; title: string; created_at: number; updated_at: number;
  system_prompt: string | null; temperature: number | null;
  context_length: number | null; max_tokens: number | null;
  provider_id: string | null; model_id: string | null;
  is_pinned: 0 | 1; is_new: 0 | 1; artifacts: 0 | 1;
  enabled_mcp_tools: string | null; thinking_budget: number | null;
  reasoning_effort: string | null; verbosity: number | null;
  enable_search: 0 | 1 | null; forced_search: 0 | 1 | null;
  search_strategy: string | null;
}

Then use .all() as ConversationRow[].

Also applies to: 93-94


266-270: Verify parent-child ordering; children may precede parents.

If parent messages can appear later in order_seq, unresolved parents become empty-string, breaking the tree. Consider a two-pass link or a deferred fix-up map.

📜 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 1256d41 and 9377c48.

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

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

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

Files:

  • src/main/presenter/sqlitePresenter/importData.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/sqlitePresenter/importData.ts
src/main/**/*.ts

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

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

Files:

  • src/main/presenter/sqlitePresenter/importData.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/error-logging.mdc)

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

Enable and adhere to strict TypeScript type checking across the codebase

Files:

  • src/main/presenter/sqlitePresenter/importData.ts
src/main/**/*.{ts,js,tsx,jsx}

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

主进程代码放在 src/main

Files:

  • src/main/presenter/sqlitePresenter/importData.ts
**/*.{ts,tsx,js,jsx,vue}

📄 CodeRabbit inference engine (CLAUDE.md)

Write logs and comments in English

Files:

  • src/main/presenter/sqlitePresenter/importData.ts
src/main/presenter/**/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Maintain one Presenter per functional domain under src/main/presenter/

Files:

  • src/main/presenter/sqlitePresenter/importData.ts
⏰ 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 (2)
src/main/presenter/sqlitePresenter/importData.ts (2)

87-91: New conversation fields SELECT looks correct and backward-compatible.

Selecting verbosity, enable_search, forced_search, and search_strategy here aligns with schema v7 and is properly guarded by the outer try/catch.


116-120: Good legacy fallback defaults.

Providing nulls for the new fields in the old-schema path preserves import continuity without fabricating values.

Comment on lines +195 to +198
conv.verbosity || null,
conv.enable_search ?? null,
conv.forced_search ?? null,
conv.search_strategy ?? null
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

Bug: verbosity may be dropped when value is 0 due to || null.

Use nullish coalescing to preserve 0. Current code would store NULL instead of 0.

Apply:

-          conv.verbosity || null,
+          conv.verbosity ?? 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
conv.verbosity || null,
conv.enable_search ?? null,
conv.forced_search ?? null,
conv.search_strategy ?? null
conv.verbosity ?? null,
conv.enable_search ?? null,
conv.forced_search ?? null,
conv.search_strategy ?? null
🤖 Prompt for AI Agents
In src/main/presenter/sqlitePresenter/importData.ts around lines 195 to 198, the
code uses "conv.verbosity || null" which will coerce falsy values like 0 to
null; change that to use nullish coalescing (conv.verbosity ?? null) so numeric
zero is preserved, leaving the other fields (enable_search, forced_search,
search_strategy) unchanged.

@zerob13 zerob13 merged commit 0060f53 into dev Sep 5, 2025
2 checks passed
zerob13 added a commit that referenced this pull request Sep 9, 2025
* fix: chat confg need sync to new value when change model in chat (#823)

* fix: gemini nano banana not read image from chatinput

* fix: remove file-type ,this will mark html as audio (#824)

* fix: Solve the problem of the window becoming larger when dragging floating button under Windows (#826)

* fix: improve OpenAI compatible provider compatibility with third-party services

* chore: update vue-renderer-markdown to v0.0.35 (#827)

* refactor: remove custom-prompts-server and decouple prompts from MCP lifecycle (#829)

- Remove custom-prompts-server service entirely including configuration
- Implement data source merging in MCP store to load prompts from both config and MCP
- Add upgrade migration logic for versions < 0.3.5 to clean up old configurations
- Ensure @ operations work independently of MCP state through config data source
- Update CLAUDE.md with prompt management guidelines

The @ prompt functionality now works completely independently of MCP,
loading custom prompts directly from config storage while maintaining
full compatibility with existing MCP prompt sources.

* chore: add better log for mcp tool name

* feat: ux update (#831)

* feat: ux update

* chore: format

* feat: setting provider ux update (#832)

* feat: add current datetime to system prompt

- Add current date and time information to user's system prompt when not empty
- Include complete datetime with timezone, year, month, day, hour, minute, second
- Apply to both preparePromptContent and buildContinueToolCallContext methods
- Update token calculation to use processed system prompt for accuracy
- Skip datetime addition for image generation models and empty prompts

* refactor: extract system prompt datetime enhancement to common method

- Add enhanceSystemPromptWithDateTime private method to reduce code duplication
- Update both preparePromptContent and buildContinueToolCallContext to use common method
- Improve code maintainability and ensure consistency across all system prompt processing
- Add comprehensive JSDoc documentation for the new method

* fix(markdown): auto-wrap hide scroll (#833)

* feat: add enable_thinking parameter support for siliconcloud (#835)

* chore: bump deps (#834)

* chore: bump up deps

* fix: change win arm to wasm32 sharp

* chore: revert sharp config

* feat: drop windows arm support

* fix(coderabbitai): remove action for windows arm64

* refactor: adjust scroll-to-bottom button glow effect (#837)

* feat: add mutual exclusive confirmation dialogs for DeepSeek-V3.1 (#838)

* feat: add sanitizeText utility for clipboard data handling (#843)

* feat: support canary upgrade (#840)

* feat: support canary upgrade

* feat: add update channel selection for stable/canary versions

- Add update channel configuration to config presenter
- Implement dynamic URL switching for version checks and downloads
- Add UI selector in AboutUsSettings for channel selection
- Support stable and canary update channels with different endpoints
- Add internationalization support for channel selection

* chore: change contributors charts to openomy

* refactor: improve update channel handling and network resilience

- Sanitize update channel input to prevent invalid values
- Add 10-second timeout to version check requests to prevent hanging
- Treat unknown channels as 'upgrade' (stable) for robustness
- Improve error handling for network timeouts and invalid channels

* feat: implement thinking parameter support for doubao models (#842)

* feat: implement dedicated DashScope provider with enable_thinking support (#844)

* feat: implement dedicated DashScope provider with enable_thinking support

* refactor: remove unnecessary API key status check methods from DashscopeProvider

* fix: prioritize provider.id over apiType in createProviderInstance (#846)

* feat: add qwen3 thinking budget support (#848)

* feat: add qwen3 thinking budget support

* fix: add missing gemini.onlySupported key in zh-CN locale

* refactor: merge duplicate silicon case statements in provider creation

* feat: add qwen3 thinking budget support in ChatConfig (#849)

* refactor(types): 🚀split monolithic presenter.d.ts into strict per-domain *.presenter.d.ts + typed core layer  (#847)

* docs: Add strong-typed message architecture and implementation guidelines

- Update message-architecture.md with strong-typed design, remove compatibility compromises
- Add event-to-UI mapping table and rendering checklist for contract compliance
- Create presenter-split-plan.md for type system refactoring
- Add implementation-tasks.md with phased rollout plan
- Create .cursor/rules/provider-guidelines.mdc for provider implementation guidance

This establishes a foundation for strong-typed, maintainable message architecture without legacy compatibility debt.

* types(core): add strong-typed core types and barrel exports\n\n- Add usage.ts (UsageStats, RateLimitInfo)\n- Add llm-events.ts (discriminated union + factories + guards)\n- Add agent-events.ts (LLMAgentEvent*, shared types)\n- Add chat.ts (Message/AssistantMessageBlock/UserMessageContent)\n- Add mcp.ts (MCP content/response/definition)\n- Add types/index.d.ts barrel exports\n\nNo compatibility shims included by design.

* refactor(types): move legacy presenters and add @shared/presenter stub; keep legacy exports in types/index to maintain build\n\n- Move legacy presenters to src/shared/types/presenters/legacy.presenters.d.ts\n- Add src/shared/presenter.d.ts re-export stub\n- Temporarily export only legacy presenters from types/index.d.ts to avoid type mismatches\n- Update implementation-tasks.md (Stage 2 done)\n\nNext: progressive import updates to new cores, then flip barrel to new types and delete legacy.

* refactor(types): alias legacy core message types to strong-typed core (B-plan)\n\n- legacy.presenters.d.ts now re-exports ChatMessage/ChatMessageContent/LLMAgentEvent/LLMAgentEventData/LLMCoreStreamEvent from core\n- Prepares for flipping interfaces without changing import sites

* docs(tasks): mark Phase 3 as completed\n\n- Successfully implemented B-plan approach with type aliasing\n- Unified core message types (ChatMessage, LLMAgentEvent, LLMCoreStreamEvent)\n- Created core model types and maintained build compatibility\n- All type checks passing with no breaking changes

* fix(types): revert to legacy-only exports and fix MESSAGE_ROLE\n\n- Revert types/index.d.ts to only export legacy presenters\n- Remove 'function' from MESSAGE_ROLE to match core definition\n- Maintain build stability while preserving type unification work

* feat(provider): implement factory functions for LLMCoreStreamEvent\n\n- Replace all manual event creation with createStreamEvent factory functions\n- Ensures type safety and consistent event structure\n- Updated OpenAICompatibleProvider with strong-typed events:\n  - text, reasoning, toolCallStart, toolCallChunk, toolCallEnd\n  - error, usage, stop, imageData events\n- All type checks passing\n- Phase 4.1 completed: Provider now outputs LLMCoreStreamEvent with factory construction

* feat(provider): update OllamaProvider with factory functions\n\n- Replace all manual event creation with createStreamEvent factory functions\n- Ensures consistent tool_call_start → tool_call_chunk → tool_call_end sequence\n- Updated all event types: text, reasoning, toolCall*, usage, stop, error\n- Maintains proper tool call ID aggregation and sequencing\n- Phase 4.2 completed: Tool call sequences now strictly follow start/chunk/end pattern

* docs(tasks): update Phase 4 progress\n\n- Completed Provider strong-typed event output with factory functions\n- Completed tool_call_* strict start/chunk/end sequences\n- Completed usage event sent before stop in all providers\n- Updated implementation tasks document with current progress

* feat(phase4): complete Provider strong-typed event integration\n\n- Added factory functions import to AwsBedrockProvider\n- Updated error handling to use createStreamEvent.error() + createStreamEvent.stop('error')\n- Created comprehensive unit tests for LLMCoreStreamEvent factory functions\n- Tests validate: event creation, tool call sequences, error+stop patterns, type guards\n- All 12 core event tests passing ✅\n\n## Phase 4 Completed:\n- ✅ Provider strong-typed event output (factory construction)\n- ✅ tool_call_* strict start/chunk/end sequences with ID aggregation\n- ✅ Usage events sent before stop in all providers\n- ✅ Rate limit events (handled at Presenter layer)\n- ✅ Unified error + stop event patterns\n- ✅ Comprehensive unit tests for sequences/fields/boundaries

* feat(phase5): complete Agent & UI alignment

## Phase 5 Completed: Agent & UI Alignment ✅

### 1. Agent Layer Enhancement
- ✅ Agent consumes only CoreEvent and outputs LLMAgentEvent
- ✅ Strict separation of response/error/end event types
- ✅ Added rate_limit event handling in Agent layer
- ✅ Maintained proper event transformation pipeline

### 2. UI Layer Unification
- ✅ Removed standalone tool_call_permission type
- ✅ Unified to action + action_type pattern
- ✅ Updated all UI components and thread presenter logic
- ✅ Preserved backward compatibility with conditional rendering

### 3. Renderer Mapping & Testing
- ✅ Created comprehensive renderer contract tests (17 tests)
- ✅ Added message block data structure snapshot tests (14 tests)
- ✅ Validated event-to-UI block mapping compliance
- ✅ Ensured consistent status transitions and type safety

### Key Technical Achievements:
- **Type Safety**: All event transformations now type-safe
- **Consistency**: Unified action_type handling across codebase
- **Testing**: 31 new tests covering contracts and snapshots
- **Architecture**: Clean separation between Agent/UI concerns
- **Quality**: All lint, format, and type checks passing ✅

### Files Modified:
- Agent layer: llmProviderPresenter/index.ts
- UI components: MessageItemAssistant.vue
- Thread logic: threadPresenter/index.ts
- Type definitions: shared/chat.d.ts
- Tests: rendererContract.test.ts, messageBlockSnapshot.test.ts

Ready for Phase 6: Quality & Tools 🚀

* feat(phase6): complete Quality & Tools phase

## Phase 6 Completed: Quality & Tools ✅

### 1. Table-Driven Contract Tests
- ✅ Created comprehensive event mapping contract tests (25 test cases)
- ✅ Validated all event types from architecture mapping table
- ✅ Verified status transitions and type constraints
- ✅ Added tool call ID aggregation and lifecycle validation
- ✅ Implemented error recovery pattern testing

### 2. Performance Evaluation & Stress Testing
- ✅ Large text content processing (50KB < 10ms)
- ✅ Large reasoning content handling (100KB < 15ms)
- ✅ Large image data processing (1MB < 20ms)
- ✅ Batch image processing (100 images < 50ms)
- ✅ High-frequency event processing (1000 events < 100ms)
- ✅ Mixed event type handling (500 events < 80ms)
- ✅ Memory leak prevention (5000 events < 500ms)
- ✅ Extreme parameter handling (10KB params < 5ms)
- ✅ Concurrent processing simulation (10 workers < 100ms)

### Key Technical Achievements:
- **Comprehensive Testing**: 67 tests passing across all scenarios
- **Performance Validation**: All benchmarks meet performance targets
- **Type Safety**: Full TypeScript compliance (0 errors)
- **Code Quality**: Lint and format checks passing ✅
- **Architecture Compliance**: All mapping table rules verified
- **Stress Testing**: System handles extreme loads efficiently

### Test Coverage Summary:
- Event mapping contract tests: 25 tests ✅
- Renderer contract tests: 17 tests ✅
- Performance evaluation tests: 9 tests ✅
- Core event factory tests: 12 tests ✅
- Message block snapshot tests: 14 tests ✅
- Shell integration tests: 8 tests ✅

### Files Added:
- test/renderer/message/eventMappingTable.test.ts (comprehensive mapping validation)
- test/renderer/message/performanceEvaluation.test.ts (stress & performance testing)

Ready for production deployment with full quality assurance! 🚀

* fix(providers): complete strong-typed event integration across all providers

* fix(vitest): modify test case

* fix: default settings

* chore: update doc

* fix(ci): remove duplicate check in pr ci

* feat: add pnpm cache for pr check

* fix(ci): pr check with pnpm cache

* fix(ci): change cache key to package.json

* ci: remove pnpm cache

* feat: add glow breathing effect to scroll-to-bottom button (#850)

* feat: add glow breathing effect to scroll-to-bottom button

* fix: ensure exclusive display between MessageList and ArtifactDialog

* fix: refine MessageList–ArtifactDialog interaction logic; correct z-order between dialog and ArtifactDialog

* chore: prettier .vue

* feat: add web search support with configurable options for dashscope (#851)

* feat: add web search support with configurable options for dashscope

* fix: correct qwen model parameters to match official documentation

* feat: add web search support with configurable options for dashscope (#852)

* feat: add web search support with configurable options for dashscope

* fix: correct qwen model parameters to match official documentation

* feat: add search configuration support to ChatConfig components

* fix: fix enableSearch state sync and parameter passing issues

* fix: preserve search settings during data import

* feat: add dashscope commercial models to enable_thinking support (#853)

* feat: add search capability icon for model list (#854)

* feat: add search capability icon for model list

* fix: clear search settings when creating new conversation

* feat(markdown): Thinking panel now supports LaTeX compilation for mathematical formulas & markdown performance optimization (#857)

* feat(markdown): 思考栏支持数学公式latex编译显示 & markdown 性能优化
close: #845

* chore: lint

* chore(ai): update claude code rules and agents

* fix(ui): revert Dialog z-index to z-50 to fix dropdown visibility

Reverts DialogContent z-index from z-[100] back to z-50 to resolve issue where Select and EmojiPicker dropdowns were not appearing. This maintains proper layering hierarchy without breaking other UI components.

* feat: upgrade vue-renderer-markdown & vue-use-monaco (#862)

1. ignore math-block warning
2. Compatible with the syntax issues of mermaid produced by AI, greatly reducing the probability of mermaid rendering errors

* feat(dashscope): add qwen3-max-preview model (#865)

* fix: mcp params support more types (#861)

* feat(mcp): enhance tool parameter display with enum type support

- Add enum parameter type detection and enhanced display
- Show enum parameters with distinct blue badge styling (enum(string), array[enum(string)])
- Display allowed values for both direct enum and array item enum parameters
- Add i18n support for "allowedValues" and "arrayItemValues" labels
- Maintain consistent UI design with existing parameter display patterns
- Improve developer experience when debugging MCP tools with constrained parameters

* fix: enum params support

* fix(context-menu): handle local file paths in image save functionality

- Fix URL parsing error when saving images from local file paths
- Add proper handling for http/https URLs, file:// URLs, and direct file paths
- Use fs.promises for reading local files instead of net.fetch for invalid URLs
- Prevent "Failed to parse URL from" error when saving local images

* fix(context-menu): improve URL handling robustness in image save

- Add try-catch around net.fetch to handle invalid URLs gracefully
- Implement fallback methods for file:// URLs and local file paths
- Add debug logging to track source URL values for troubleshooting
- Prevent "Failed to parse URL from" errors with comprehensive URL validation

* fix(context-menu): handle empty srcURL in image save functionality

- Add comprehensive URL detection when srcURL is empty
- Implement fallback URL sources (linkURL, pageURL) for better compatibility
- Add debug logging to track all available context menu parameters
- Prevent "Failed to parse URL from" errors caused by empty URLs
- Provide clear error message when no valid URL can be found

* chore: format code

* fix: ai review

* fix: prevent @ symbol remaining when deleting mentions (#867)

* Merge commit from fork

* feat: implement separated system and custom prompt management (#868)

* feat: implement separated system and custom prompt management

* style: code fmt

* fix: add migration for legacy default_system_prompt to system_prompts

* feat: add Moonshot model configurations (#869)

* refactor: translate all cn comments and log to en (#871)

* refactor: translate all cn comments and log to en

* fix: revert translate in params

* feat: add reasoning support for Grok thinking models (#873)

* feat: add reasoning support for Grok thinking models

* fix: code lint

* fix: escaping character issue

---------

Co-authored-by: zerob13 <zerob13@gmail.com>

---------

Co-authored-by: hllshiro <40970081+hllshiro@users.noreply.github.com>
Co-authored-by: yyhhyyyyyy <yyhhyyyyyy8@gmail.com>
Co-authored-by: xiaomo <wegi866@gmail.com>
Co-authored-by: Simon He <57086651+Simon-He95@users.noreply.github.com>
Co-authored-by: luy <12696648@qq.com>
@zerob13 zerob13 deleted the feat/chat-components-search-support branch January 6, 2026 12:17
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