Skip to content

Conversation

@yyhhyyyyyy
Copy link
Collaborator

@yyhhyyyyyy yyhhyyyyyy commented Sep 4, 2025

add web search support with configurable options for dashscope
Implement the enable_search and search_options portion of #836.

Summary by CodeRabbit

  • New Features

    • Web Search controls for supported DashScope models: enable, force, and strategy (Turbo/Max).
    • Expanded supported DashScope models with additional Qwen/QWQ variants.
  • Bug Fixes

    • Safer defaults in model settings to prevent errors when a model config is missing.
  • Chores

    • Added UI translations for the new search settings across locales (en, fa, fr, ja, ko, ru, zh-CN, zh-HK, zh-TW).

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 4, 2025

Walkthrough

Adds DashScope web-search controls (enableSearch, forcedSearch, searchStrategy) to model config types, provider settings, UI, and i18n; propagates those fields into provider-specific configs and updates DashScope streaming to inject enable_search/forced_search/search_strategy when applicable.

Changes

Cohort / File(s) Summary
Model config schema & construction
src/main/presenter/configPresenter/modelConfig.ts, src/shared/types/presenters/legacy.presenters.d.ts
Extend ModelConfig/DefaultModelSetting with enableSearch, forcedSearch, searchStrategy; populate defaults (false, false, 'turbo') in user/provider/default resolution.
Provider model settings
src/main/presenter/configPresenter/providerModelSettings.ts
Add optional enableSearch/forcedSearch/searchStrategy to ProviderModelSetting; update provider entries, add new models, and propagate defaults; getProviderSpecificModelConfig returns new fields.
DashScope provider streaming
src/main/presenter/llmProviderPresenter/providers/dashscopeProvider.ts
Compute enable_thinking/enable_search; when applicable, wrap completions.create to inject enable_search, optional forced_search, search_strategy, and preserve thinking_budget; restore original client after streaming.
Settings UI
src/renderer/src/components/settings/ModelConfigDialog.vue
Add DashScope web-search UI (toggle, forced search, strategy select) gated by provider/model; initialize/load/reset new fields; add safety guard for thinkingBudgetRange.
i18n additions
src/renderer/src/i18n/*/settings.json
en-US, fa-IR, fr-FR, ja-JP, ko-KR, ru-RU, zh-CN, zh-HK, zh-TW
Add translation keys for enableSearch, forcedSearch, and searchStrategy (label/description, placeholder, options). No removals.
Presenter provider settings types
src/main/presenter/configPresenter/providerModelSettings.ts (interface)
ProviderModelSetting now includes optional enableSearch?: boolean, forcedSearch?: boolean, `searchStrategy?: 'turbo'

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant UI as ModelConfigDialog.vue
  participant CP as Config Presenter
  participant DSP as DashScope Provider
  participant API as DashScope API

  User->>UI: Toggle Web Search / set strategy
  UI->>CP: Save ModelConfig (enableSearch, forcedSearch, searchStrategy)
  User->>UI: Send prompt
  UI->>DSP: coreStream(modelConfig)
  DSP->>DSP: Evaluate modelConfig for enable_thinking / enable_search
  alt enable_thinking or enable_search
    note right of DSP #D3E4CD: Wrap completions.create to inject flags
    DSP->>API: completions.create({... enable_search, forced_search?, search_strategy?, thinking_budget? })
    API-->>DSP: Stream tokens
  else
    DSP->>API: completions.create(original request)
    API-->>DSP: Stream tokens
  end
  DSP-->>UI: Streamed response
  UI-->>User: Render response
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • zerob13

Poem

I thump my paws on wired ground,
Turbo winds or Max profound—
I sniff the web for freshest facts,
Toggle on, no steps to track.
Hop, fetch, stream — then nap, intact. 🐇

✨ 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/dashscope-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: 2

Caution

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

⚠️ Outside diff range comments (1)
src/shared/types/presenters/legacy.presenters.d.ts (1)

1046-1046: Typo breaks typing: use unknown not unknow.

This propagates bad types across the app.

-  env: Record<string, unknow>
+  env: Record<string, unknown>
🧹 Nitpick comments (20)
src/renderer/src/i18n/zh-HK/settings.json (1)

151-151: Nit: capitalize strategy names in description to match option labels

Use “Turbo/Max” (as in options) instead of lowercase to keep UI consistent.

Apply this minimal diff:

-        "description": "選擇搜尋性能模式:turbo 兼顧速度與效果,max 提供最優搜尋效果",
+        "description": "選擇搜尋性能模式:Turbo 兼顧速度與效果,Max 提供最優搜尋效果",
src/renderer/src/i18n/zh-CN/settings.json (1)

159-164: Unify capitalization of “Turbo/Max” in description to match option labels

Minor consistency nit: option labels use “Turbo/Max” (title case) while description uses “turbo/max” (lowercase).

-        "description": "选择搜索性能模式:turbo 兼顾速度与效果,max 提供最优搜索效果",
+        "description": "选择搜索性能模式:Turbo 兼顾速度与效果,Max 提供最优搜索效果",
src/renderer/src/i18n/zh-TW/settings.json (1)

151-156: Match “Turbo/Max” capitalization in description to option labels

Keep terminology consistent with options.

-        "description": "選擇搜尋性能模式:turbo 兼顧速度與效果,max 提供最優搜尋效果",
+        "description": "選擇搜尋性能模式:Turbo 兼顧速度與效果,Max 提供最優搜尋效果",
src/renderer/src/i18n/ru-RU/settings.json (1)

150-156: Use title case “Turbo/Max” in description for consistency

Align with option labels and other locales.

-        "description": "Выберите режим производительности поиска: turbo балансирует скорость и эффективность, max обеспечивает оптимальные результаты поиска",
+        "description": "Выберите режим производительности поиска: Turbo балансирует скорость и эффективность, Max обеспечивает оптимальные результаты поиска",
src/renderer/src/i18n/ja-JP/settings.json (1)

150-156: Title-case “Turbo/Max” in description to match option labels

Cosmetic consistency across locales.

-        "description": "検索パフォーマンスモードを選択:turboは速度と効果のバランス、maxは最適な検索結果を提供",
+        "description": "検索パフォーマンスモードを選択:Turbo は速度と効果のバランス、Max は最適な検索結果を提供",
src/renderer/src/i18n/en-US/settings.json (1)

150-156: Capitalize “Turbo/Max” in description for consistency with option labels

Minor copy polish.

-        "description": "Choose search performance mode: turbo balances speed and effectiveness, max provides optimal search results",
+        "description": "Choose search performance mode: Turbo balances speed and effectiveness, Max provides optimal search results",
src/renderer/src/i18n/ko-KR/settings.json (1)

141-157: New web-search i18n keys look consistent and correctly scoped.

Keys align with ModelConfig fields and option values (‘turbo’ | ‘max’). Minor copy tweak for clarity/politeness in Korean description.

Apply this small wording improvement:

-        "description": "모델이 웹 검색을 강제 수행하도록, 비활성화시 모델이 자동으로 결정"
+        "description": "모델의 웹 검색을 강제로 수행합니다. 비활성화 시에는 모델이 자동으로 결정합니다."
src/renderer/src/i18n/fa-IR/settings.json (1)

141-157: Farsi translations are accurate and match the config semantics.

Tiny punctuation improvement to read more naturally.

-        "description": "مدل را مجبور به انجام جستجوی وب کنید، در صورت غیرفعال بودن مدل خود تصمیم می‌گیرد"
+        "description": "مدل را مجبور به انجام جستجوی وب کنید؛ در صورت غیرفعال بودن، مدل خود تصمیم می‌گیرد"
src/renderer/src/i18n/fr-FR/settings.json (1)

141-157: French keys map correctly; suggest a small grammar fix.

Current phrasing is a bit awkward when disabled.

-        "description": "Forcer le modèle à effectuer une recherche web, désactivé le modèle décide automatiquement"
+        "description": "Forcer le modèle à effectuer une recherche web ; s'il est désactivé, le modèle décide automatiquement"
src/main/presenter/configPresenter/modelConfig.ts (2)

181-185: Backfill defaults for user/provider configs to avoid undefined fields.

When userConfig/providerConfig omit the new fields, finalConfig may carry undefineds. Backfill once before returning.

   // Add source information to the config
-    finalConfig.isUserDefined = hasUserConfig
+    // Backfill defaults for newly added search fields
+    if (finalConfig.enableSearch === undefined) finalConfig.enableSearch = false
+    if (finalConfig.forcedSearch === undefined) finalConfig.forcedSearch = false
+    if (finalConfig.searchStrategy !== 'turbo' && finalConfig.searchStrategy !== 'max') {
+      finalConfig.searchStrategy = 'turbo'
+    }
+    finalConfig.isUserDefined = hasUserConfig

7-7: No current ‘-_–’ collisions detected; consider optional delimiter escaping
A project-wide search for providerId/modelId values containing -_- returned no matches. While there’s no immediate conflict, it’s safest to either escape the separator in IDs (Option A) or switch to length-prefixed keys (Option B) to future-proof parseCacheKey.

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

132-135: Type additions look right; avoid string-literal duplication for strategy.

Define a reusable alias to keep ModelConfig and DefaultModelSetting in sync.

 export interface ModelConfig {
@@
-  searchStrategy?: 'turbo' | 'max'
+  searchStrategy?: SearchStrategy

Additional change outside this hunk (add once near other shared aliases):

export type SearchStrategy = 'turbo' | 'max'

1307-1310: Mirror the alias in DefaultModelSetting.

Keeps both types aligned if strategies expand later.

-  searchStrategy?: 'turbo' | 'max'
+  searchStrategy?: SearchStrategy
src/main/presenter/llmProviderPresenter/providers/dashscopeProvider.ts (2)

14-25: Use English for comments per repo guidelines.

Please convert the added Chinese comments to English to comply with “Write logs and comments in English” for all TS/JS files.


58-67: Tighten model matching to avoid false positives.

Using substring includes() may enable search for unsupported dated variants (e.g., older qwen-turbo builds). Prefer anchored equality or “prefix with dash” checks.

Apply:

-  return DashscopeProvider.ENABLE_SEARCH_MODELS.some((supportedModel) =>
-    normalizedModelId.includes(supportedModel)
-  )
+  return DashscopeProvider.ENABLE_SEARCH_MODELS.some((m) =>
+    normalizedModelId === m ||
+    normalizedModelId.startsWith(`${m}-`) ||         // e.g. qwen-plus-2025-07-14
+    normalizedModelId === `${m}-latest`
+  )
src/main/presenter/configPresenter/providerModelSettings.ts (2)

2217-2298: DashScope search defaults added — keep entries consistent and narrow matches.

  • Consistency: qwq-plus-latest sets enableSearch but omits forcedSearch/searchStrategy unlike other entries. Recommend adding them for uniformity.
  • Matching: since getProviderSpecificModelConfig uses substring includes, generic matches like qwen-turbo will also match dated variants (e.g., 2024-06-24). Consider anchoring or ordering guarantees to avoid unintended model configs leaking into dated variants.

Apply for consistency (example for qwq-plus-latest):

       {
         id: 'qwq-plus-latest',
         name: 'QwQ Plus Latest',
         temperature: 0.7,
         maxTokens: 4096,
         contextLength: 32768,
         match: ['qwq-plus-latest'],
         vision: false,
         functionCall: false,
         reasoning: true,
-        enableSearch: false
+        enableSearch: false,
+        forcedSearch: false,
+        searchStrategy: 'turbo'
       }

If you prefer to keep substring matching, ensure the more specific dated entries precede the generic ones, and add a brief comment explaining the ordering contract.

Also applies to: 2308-2312, 2313-2326, 2328-2340, 2350-2354, 2454-2467, 2477-2481, 2546-2550, 2671-2698


4-24: Use English comments.

Please translate the newly added/edited Chinese comments to English to align with repo logging/commenting rules.

src/renderer/src/components/settings/ModelConfigDialog.vue (3)

307-359: Nice UI gating; add a small UX guard for forcedSearch.

When users disable “Enable Search”, consider auto-clearing forcedSearch to avoid stale true values being saved invisibly.

Add:

watch(
  () => config.value.enableSearch,
  (enabled) => {
    if (!enabled) config.value.forcedSearch = false
  }
)

734-743: Reuse a single capability source or tighten prefix matching.

This hardcoded prefix list can drift from the provider’s allowlist. Prefer a shared helper in @shared (e.g., isDashScopeSearchCapable(modelId)) or tighten to anchored prefix checks to avoid enabling UI for unsupported dated models.

Example tightening:

-const supportedModels = ['qwen-max', 'qwen-plus', 'qwen-flash', 'qwen-turbo', 'qwq-plus']
-const isSupported = supportedModels.some((supportedModel) => modelId.includes(supportedModel))
+const supportedModels = ['qwen-max', 'qwen-plus', 'qwen-flash', 'qwen-turbo', 'qwq-plus']
+const isSupported = supportedModels.some((m) =>
+  modelId === m || modelId.startsWith(`${m}-`) || modelId === `${m}-latest`
+)

418-901: Use English comments and structured logging.

There are several newly added Chinese comments and console.error calls. Please:

  • Translate comments to English.
  • Wrap errors with structured logs (level, ts, code, message, stack) and avoid sensitive data.
📜 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 1c721d6 and 58e81b4.

📒 Files selected for processing (14)
  • src/main/presenter/configPresenter/modelConfig.ts (2 hunks)
  • src/main/presenter/configPresenter/providerModelSettings.ts (10 hunks)
  • src/main/presenter/llmProviderPresenter/providers/dashscopeProvider.ts (4 hunks)
  • src/renderer/src/components/settings/ModelConfigDialog.vue (4 hunks)
  • src/renderer/src/i18n/en-US/settings.json (1 hunks)
  • src/renderer/src/i18n/fa-IR/settings.json (1 hunks)
  • src/renderer/src/i18n/fr-FR/settings.json (1 hunks)
  • src/renderer/src/i18n/ja-JP/settings.json (1 hunks)
  • src/renderer/src/i18n/ko-KR/settings.json (1 hunks)
  • src/renderer/src/i18n/ru-RU/settings.json (1 hunks)
  • src/renderer/src/i18n/zh-CN/settings.json (1 hunks)
  • src/renderer/src/i18n/zh-HK/settings.json (1 hunks)
  • src/renderer/src/i18n/zh-TW/settings.json (1 hunks)
  • src/shared/types/presenters/legacy.presenters.d.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (20)
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/i18n/ru-RU/settings.json
  • src/renderer/src/i18n/zh-CN/settings.json
  • src/renderer/src/i18n/en-US/settings.json
  • src/renderer/src/i18n/ja-JP/settings.json
  • src/renderer/src/i18n/fr-FR/settings.json
  • src/renderer/src/i18n/ko-KR/settings.json
  • src/renderer/src/i18n/zh-HK/settings.json
  • src/renderer/src/i18n/fa-IR/settings.json
  • src/renderer/src/components/settings/ModelConfigDialog.vue
  • src/renderer/src/i18n/zh-TW/settings.json
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/i18n/ru-RU/settings.json
  • src/renderer/src/i18n/zh-CN/settings.json
  • src/renderer/src/i18n/en-US/settings.json
  • src/renderer/src/i18n/ja-JP/settings.json
  • src/renderer/src/i18n/fr-FR/settings.json
  • src/renderer/src/i18n/ko-KR/settings.json
  • src/renderer/src/i18n/zh-HK/settings.json
  • src/renderer/src/i18n/fa-IR/settings.json
  • src/renderer/src/components/settings/ModelConfigDialog.vue
  • src/renderer/src/i18n/zh-TW/settings.json
**/*.{js,jsx,ts,tsx}

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

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

Files:

  • src/shared/types/presenters/legacy.presenters.d.ts
  • src/main/presenter/configPresenter/modelConfig.ts
  • src/main/presenter/configPresenter/providerModelSettings.ts
  • src/main/presenter/llmProviderPresenter/providers/dashscopeProvider.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/legacy.presenters.d.ts
  • src/main/presenter/configPresenter/modelConfig.ts
  • src/main/presenter/configPresenter/providerModelSettings.ts
  • src/main/presenter/llmProviderPresenter/providers/dashscopeProvider.ts
src/shared/**/*.{ts,tsx,d.ts}

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

共享类型定义放在 shared 目录

Files:

  • 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/legacy.presenters.d.ts
  • src/main/presenter/configPresenter/modelConfig.ts
  • src/main/presenter/configPresenter/providerModelSettings.ts
  • src/renderer/src/components/settings/ModelConfigDialog.vue
  • src/main/presenter/llmProviderPresenter/providers/dashscopeProvider.ts
src/shared/**/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

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

Files:

  • 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/modelConfig.ts
  • src/main/presenter/configPresenter/providerModelSettings.ts
  • src/main/presenter/llmProviderPresenter/providers/dashscopeProvider.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/modelConfig.ts
  • src/main/presenter/configPresenter/providerModelSettings.ts
  • src/main/presenter/llmProviderPresenter/providers/dashscopeProvider.ts
src/main/**/*.{ts,js,tsx,jsx}

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

主进程代码放在 src/main

Files:

  • src/main/presenter/configPresenter/modelConfig.ts
  • src/main/presenter/configPresenter/providerModelSettings.ts
  • src/main/presenter/llmProviderPresenter/providers/dashscopeProvider.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/modelConfig.ts
  • src/main/presenter/configPresenter/providerModelSettings.ts
  • src/main/presenter/llmProviderPresenter/providers/dashscopeProvider.ts
src/main/presenter/configPresenter/**

📄 CodeRabbit inference engine (CLAUDE.md)

Centralize configuration logic under configPresenter/

Files:

  • src/main/presenter/configPresenter/modelConfig.ts
  • src/main/presenter/configPresenter/providerModelSettings.ts
src/renderer/**/*.{vue,ts,js,tsx,jsx}

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

渲染进程代码放在 src/renderer

Files:

  • src/renderer/src/components/settings/ModelConfigDialog.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/settings/ModelConfigDialog.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/settings/ModelConfigDialog.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/settings/ModelConfigDialog.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/settings/ModelConfigDialog.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/components/settings/ModelConfigDialog.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/settings/ModelConfigDialog.vue
src/main/presenter/llmProviderPresenter/providers/*.ts

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

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.
Provider implementations must use a coreStream method that yields standardized stream events to decouple the main loop from provider-specific details.
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.
Provider files should implement helper methods such as formatMessages, convertToProviderTools, parseFunctionCalls, and prepareFunctionCallPrompt as needed for provider-specific logic.
All provider implementations must parse provider-specific data chunks and yield standardized events for text, reasoning, tool calls, usage, errors, stop reasons, and image data.
When a provider does not support native function calling, it must prepare messages using prompt wrapping (e.g., prepareFunctionCallPrompt) before making the API call.
When a provider supports native function calling, MCP tools must be converted to the provider's format (e.g., using convertToProviderTools) and included in the API request.
Provider implementations should aggregate and yield usage events as part of the standardized stream.
Provider implementations should yield image data events in the standardized format when applicable.
Provider implementations should yield reasoning events in the standardized format when applicable.
Provider implementations should yield tool call events (tool_call_start, tool_call_chunk, tool_call_end) in the standardized format.
Provider implementations should yield stop events with appropriate stop_reason in the standardized format.
Provider implementations should yield error events in the standardized format...

Files:

  • src/main/presenter/llmProviderPresenter/providers/dashscopeProvider.ts
🧠 Learnings (5)
📚 Learning: 2025-07-21T01:46:30.354Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: .cursor/rules/i18n.mdc:0-0
Timestamp: 2025-07-21T01:46:30.354Z
Learning: Applies to src/renderer/src/i18n/common.json : Shared translation keys must be placed in 'src/renderer/src/i18n/common.json'

Applied to files:

  • src/renderer/src/i18n/ru-RU/settings.json
  • src/renderer/src/i18n/zh-CN/settings.json
📚 Learning: 2025-07-21T01:46:30.354Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: .cursor/rules/i18n.mdc:0-0
Timestamp: 2025-07-21T01:46:30.354Z
Learning: Applies to src/renderer/src/i18n/*.json : Maintain consistent structure across all translation files

Applied to files:

  • src/renderer/src/i18n/ru-RU/settings.json
📚 Learning: 2025-07-21T01:46:30.354Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: .cursor/rules/i18n.mdc:0-0
Timestamp: 2025-07-21T01:46:30.354Z
Learning: Applies to src/renderer/src/i18n/*.json : When adding new translations, add shared keys to 'common.json' and language-specific keys to the respective language file; keep all language files' keys consistent

Applied to files:

  • src/renderer/src/i18n/ru-RU/settings.json
  • src/renderer/src/i18n/zh-CN/settings.json
📚 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/modelConfig.ts
  • src/main/presenter/configPresenter/providerModelSettings.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/main/presenter/llmProviderPresenter/providers/dashscopeProvider.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 (16)
src/renderer/src/i18n/zh-HK/settings.json (2)

141-157: LGTM: new search config translations fit modelConfig structure

Keys, nesting, and tone are consistent with adjacent entries. No blocking issues.


141-157: Locale parity verified
enableSearch, forcedSearch, and searchStrategy are present in every settings.json across all locales.

src/renderer/src/i18n/zh-CN/settings.json (2)

149-165: LGTM: new web-search model config keys are correctly added and localized

Keys (enableSearch, forcedSearch, searchStrategy) align with the PR’s data model and UI usage. Structure and placement under model.modelConfig look consistent.


149-165: All locales include the new search keys
Parity verified: every settings.json under src/renderer/src/i18n/* defines enableSearch, forcedSearch, and searchStrategy (with label, description, placeholder, options.turbo, and options.max).

src/renderer/src/i18n/zh-TW/settings.json (1)

141-157: LGTM: zh-TW translations added with correct structure

Entries mirror en-US and zh-CN; keys and shapes are consistent.

src/renderer/src/i18n/ru-RU/settings.json (1)

141-157: LGTM: RU locale keys added and mapped correctly

Structure matches other locales; wording is clear for end users.

src/renderer/src/i18n/ja-JP/settings.json (1)

141-157: LGTM: JP locale entries are present and correctly structured

Keys and shapes match the rest of locales; copy reads well.

src/renderer/src/i18n/en-US/settings.json (1)

141-157: LGTM: English keys added with clear wording and correct shape

Text and structure align with UI and data model changes.

src/main/presenter/configPresenter/modelConfig.ts (1)

170-173: Safe defaults cover new fields.

Good: guarantees deterministic values when no match/provider/user config exists.

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

588-617: Ensure search flags are applied via ModelConfig in all providers
dashscopeProvider’s coreStream already pulls enableSearch, forcedSearch and searchStrategy from modelConfig and injects them into requests; verify every other provider implementation likewise fetches and applies these flags or extend their method signatures.

src/main/presenter/llmProviderPresenter/providers/dashscopeProvider.ts (2)

27-40: Model allowlist looks good.

Clear, explicit allowlist for search-capable models. No functional issues spotted here.


83-85: Guard flags are fine.

The flags correctly gate thinking/search injection off the UI config.

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

21-23: New search-related fields on ProviderModelSetting look correct.

Types and docstrings are clear. Solid addition.


3072-3076: Good: provider config → ModelConfig projection includes search fields with sane defaults.

The defaulting strategy (false/'turbo') avoids undefineds downstream.

src/renderer/src/components/settings/ModelConfigDialog.vue (2)

480-484: Defaults extended with search fields — LGTM.

Sensible defaults and types.


518-522: Fallback defaults also cover search fields — LGTM.

Keeps renderer stable when config retrieval fails.

Comment on lines +86 to 112
if (shouldAddEnableThinking || shouldAddEnableSearch) {
// 原始的 create 方法
const originalCreate = this.openai.chat.completions.create.bind(this.openai.chat.completions)
// 替换 create 方法以添加 enable_thinking 参数
// 替换 create 方法以添加 enable_thinking 和 enable_search 参数
this.openai.chat.completions.create = ((params: any, options?: any) => {
const modifiedParams = {
...params,
enable_thinking: true
const modifiedParams = { ...params }

if (shouldAddEnableThinking) {
modifiedParams.enable_thinking = true
if (modelConfig?.thinkingBudget) {
modifiedParams.thinking_budget = modelConfig.thinkingBudget
}
}
if (modelConfig?.thinkingBudget) {
modifiedParams.thinking_budget = modelConfig.thinkingBudget

if (shouldAddEnableSearch) {
modifiedParams.enable_search = true
if (modelConfig?.forcedSearch) {
modifiedParams.forced_search = true
}
if (modelConfig?.searchStrategy) {
modifiedParams.search_strategy = modelConfig.searchStrategy
}
}

return originalCreate(modifiedParams, options)
}) as any

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Avoid monkey-patching the SDK method — race condition and cross-request leakage.

Overriding this.openai.chat.completions.create on a shared client is not concurrency-safe. Parallel streams can stomp each other’s overrides, yielding wrong params or leaving the client in a patched state. Also, errors in the inner call currently bubble without structured logging.

Proposed safer approach hierarchy (prefer top-most feasible):

  1. Refactor OpenAICompatibleProvider to let subclasses inject extra request params (e.g., protected buildExtraParams(...): object). Then override here and eliminate monkey-patch entirely.

  2. If (1) is not immediately feasible, at minimum:

    • Serialize the patch per provider instance (simple lock) to prevent concurrent overrides.
    • Add a catch to log structured error context, then rethrow.
    • Keep the try/finally restore.

Diff within this block:

-    if (shouldAddEnableThinking || shouldAddEnableSearch) {
+    if (shouldAddEnableThinking || shouldAddEnableSearch) {
+      // Prevent concurrent patching on the shared client
+      if ((this as any)._createPatchInProgress) {
+        // Fallback: skip overrides rather than risking cross-request leakage
+        yield* super.coreStream(messages, modelId, modelConfig, temperature, maxTokens, mcpTools)
+        return
+      }
+      ;(this as any)._createPatchInProgress = true
       // 原始的 create 方法
       const originalCreate = this.openai.chat.completions.create.bind(this.openai.chat.completions)
       // 替换 create 方法以添加 enable_thinking 和 enable_search 参数
       this.openai.chat.completions.create = ((params: any, options?: any) => {
         const modifiedParams = { ...params }
 
         if (shouldAddEnableThinking) {
           modifiedParams.enable_thinking = true
           if (modelConfig?.thinkingBudget) {
             modifiedParams.thinking_budget = modelConfig.thinkingBudget
           }
         }
 
         if (shouldAddEnableSearch) {
           modifiedParams.enable_search = true
           if (modelConfig?.forcedSearch) {
             modifiedParams.forced_search = true
           }
           if (modelConfig?.searchStrategy) {
             modifiedParams.search_strategy = modelConfig.searchStrategy
           }
         }
 
         return originalCreate(modifiedParams, options)
       }) as any
 
       try {
         const effectiveModelConfig = {
           ...modelConfig,
           reasoning: false,
           enableSearch: false
         }
-        yield* super.coreStream(
+        try {
+          yield* super.coreStream(
             messages,
             modelId,
             effectiveModelConfig,
             temperature,
             maxTokens,
             mcpTools
-        )
+          )
+        } catch (err: any) {
+          // Structured logging; avoid sensitive values
+          console.error(JSON.stringify({
+            level: 'ERROR',
+            ts: new Date().toISOString(),
+            where: 'DashscopeProvider.coreStream',
+            code: 'DASHSCOPE_SEARCH_PATCH_ERROR',
+            modelId,
+            enableThinking: !!shouldAddEnableThinking,
+            enableSearch: !!shouldAddEnableSearch,
+            message: err?.message || 'unknown error',
+            stack: err?.stack
+          }))
+          throw err
+        }
       } finally {
         this.openai.chat.completions.create = originalCreate
+        ;(this as any)._createPatchInProgress = false
       }

And add this class field (outside the patch block, near other fields) to make intent explicit:

// NOTE: serialized to avoid concurrent monkey-patches on shared client
private _createPatchInProgress?: boolean

Long-term, please replace the monkey-patch with an overridable param-construction hook in the base provider. I can sketch that change if helpful.

Also applies to: 114-119

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

🧹 Nitpick comments (1)
src/main/presenter/configPresenter/providerModelSettings.ts (1)

21-23: Consider standardizing the naming convention for search-related fields

The new search-related fields follow different naming patterns - enableSearch vs forcedSearch. Consider renaming forcedSearch to forceSearch for consistency with the enableSearch pattern.

-  forcedSearch?: boolean // 是否强制联网搜索
+  forceSearch?: boolean // 是否强制联网搜索
📜 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 58e81b4 and a337704.

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

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

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

Files:

  • src/main/presenter/configPresenter/providerModelSettings.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/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
**/*.{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/configPresenter/providerModelSettings.ts
src/main/**/*.{ts,js,tsx,jsx}

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

主进程代码放在 src/main

Files:

  • src/main/presenter/configPresenter/providerModelSettings.ts
**/*.{ts,tsx,js,jsx,vue}

📄 CodeRabbit inference engine (CLAUDE.md)

Write logs and comments in English

Files:

  • src/main/presenter/configPresenter/providerModelSettings.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/configPresenter/**

📄 CodeRabbit inference engine (CLAUDE.md)

Centralize configuration logic under configPresenter/

Files:

  • src/main/presenter/configPresenter/providerModelSettings.ts
🧠 Learnings (1)
📚 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
⏰ 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 (8)
src/main/presenter/configPresenter/providerModelSettings.ts (8)

2225-2229: LGTM! Search feature properly integrated for qwen-turbo-latest

The search configuration is correctly added to the model with appropriate defaults.


2285-2298: LGTM! New model entry with search support added correctly

The new qwen-turbo-2025-07-15 model is properly configured with search capabilities.


2313-2340: LGTM! New Qwen Flash models properly configured

The new Qwen Flash models (qwen-flash and qwen-flash-2025-07-28) are correctly added with appropriate search configurations and generous token limits.


2454-2481: LGTM! New Qwen Plus dated models added with search support

The new Qwen Plus models (qwen-plus-2025-07-14 and qwen-plus-2025-07-28) are properly configured with search capabilities. Note that qwen-plus-2025-07-28 has the same 1M context length as qwen-plus-latest.


2686-2712: LGTM! QwQ reasoning models added with appropriate configuration

The new QwQ models (qwq-plus and qwq-plus-latest) are correctly configured as reasoning models with reasoning: true and functionCall: false. The qwq-plus-latest model is missing the forcedSearch and searchStrategy fields - verify if this is intentional.

Should qwq-plus-latest also have the forcedSearch and searchStrategy fields like qwq-plus?


3087-3089: Ensure consistent default values in the return statement

The function correctly returns the search-related fields with appropriate defaults. Ensure these defaults match what's expected by the consuming code.


2303-2312: Update qwen-turbo contextLength and maxTokens to match DashScope spec

File: src/main/presenter/configPresenter/providerModelSettings.ts (lines 2303–2312):

  • Change contextLength from 131072 to 1000000
  • Change maxTokens from 16384 to 8192
⛔ Skipped due to learnings
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

2345-2346: Approved: parameters match official Alibaba Cloud specs

The qwen-plus-latest model supports a 1,000,000-token context window and a 32,768-token max output limit, exactly as configured (alibabacloud.com).

@zerob13 zerob13 merged commit f9b62ff 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/dashscope-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