Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

feat(qoder): align Qoder CLI with the other additive apps

Jasonb1236a1bcb67
diff --git a/docs/qoder-cli-integration-zh.md b/docs/qoder-cli-integration-zh.md
index afe52af8d..6900f2ee2 100644
--- a/docs/qoder-cli-integration-zh.md
+++ b/docs/qoder-cli-integration-zh.md
@@ -21,7 +21,7 @@
| 能力 | 原生位置或行为 |
| ------------ | ------------------------------------------------------------------------------------------------------------------------- |
| 官方账号登录 | 在「授权中心」新增多个官方账号、逐账号重新登录、选择使用或确认删除;国际版与国内版独立管理 |
-| 模型及供应商 | 在 CC Switch 的 Qoder 页面添加、编辑和删除原生自定义供应商;配置写入 `settings.json.providers`,默认模型写入 `model.name` |
+| 模型及供应商 | 累加式,和 Kimi 一样:卡片「添加」写入当前版本 `settings.json.providers`,「移除」只拿掉条目、卡片保留;默认模型写入 `model.name` |
| MCP | 数据目录下 `settings.json` 的 `mcpServers`;支持 stdio、HTTP、SSE |
| Skills | 数据目录下 `skills/`,通过统一 Skills 页面管理,写入当前所选版本 |
| 全局提示词 | 数据目录下 `AGENTS.md` |
@@ -35,22 +35,26 @@ CC Switch 不改写 `privacy` 下的任何设置:是否上报用量统计由
MCP 配置支持 JSONC 注释和尾随逗号,写入时保留注释、`cwd`、超时、工具筛选与 OAuth 等原生选项;切换传输类型时清理不再适用的启动字段。用户级配置对所有项目生效,不改变 Qoder 对项目级 MCP 的信任与审批设置。Skills 同步到所选版本的用户级 `skills/<目录>/SKILL.md`,支持 Qoder 原生目录结构与符号链接;启用时同时清理该技能在用户配置中的 `skills.disabled` 和 `skillOverrides: off`,保留其他技能的禁用状态。配置修改在新会话中加载。
-模型配置直接在 CC Switch 内完成,无需在 CLI 中配置。添加供应商时先显示与其他 CLI 共用的预设选择列表,支持按名称或网址搜索、厂商分类和套餐/地区版本选择;选择预设后自动填写连接信息与模型,也可选择「自定义配置」手动填写。列表只包含 Qoder 原生协议能够表达的预设。支持 OpenAI Chat Completions、OpenAI Responses、Anthropic Messages、Bearer/API Key 认证,以及每个模型的 ID、名称、上下文长度、最大输出 Token、工具调用、图片输入和思考模式。可以指定供应商的默认模型,并选择当前默认模型;删除当前供应商会切回 Qoder 内置的自动选择。
+Qoder 和 Kimi Code、CodeBuddy 一样是累加式应用,供应商页用与其他应用共用的列表、新增和编辑对话框。卡片存在 CC Switch 数据库里,分「已添加 / 可添加」两组:「已添加」按当前版本的 `settings.json.providers` 现算,「添加」把这张卡写进去,「移除」只从文件里拿掉、卡片保留;国际版和国内版共用同一套卡片,切换版本不搬配置,只是「已添加」换成新版本文件里的那几家。打开供应商页时,文件里已有、CC Switch 还没有的供应商自动导入成卡片。「设为默认」在卡片的「更多」菜单里,写入 `model.name`(`<供应商>/<模型>`),多个模型时展开子菜单选择;默认那家不能移除、不能删除,先把别的设为默认。
+
+添加供应商时先显示与其他 CLI 共用的预设选择列表,支持按名称或网址搜索、厂商分类和套餐/地区版本选择;选择预设后自动填写连接信息与模型,也可选择「自定义配置」手动填写,并可从上游拉取模型列表、按模型 ID 自动补全上下文长度等参数。列表只包含 Qoder 原生协议能够表达的预设。支持 OpenAI Chat Completions、OpenAI Responses、Anthropic Messages、Bearer/API Key 认证,以及每个模型的 ID、名称、上下文长度、最大输出 Token、工具调用、图片输入和思考模式;表单底部显示这条供应商在 `settings.json` 里的 JSON,可直接编辑。可以指定供应商的默认模型(「设为默认」没选具体模型时用它)。
+
+授权中心收录的每个官方账号在供应商页各有一张官方卡(CodeBuddy 的做法):Qoder 现在登着的那个号在「已添加」,点别的号的「添加」就是把 Qoder 切到那个号;官方卡的「设为默认」把 `model.name` 改成 `auto`(Qoder 内置自动选模)。官方卡不能移除(不替 Qoder 登出)、不能在供应商页删除,删号在授权中心;当前版本没有收录的号,它的卡片隐藏不删。
「授权中心」以账号列表管理官方账号,可以从侧栏直接进入;添加供应商中的「账号登录」预设及官方供应商卡片的编辑入口也进入同一页面。授权中心管理的是当前所选版本的账号;要管理另一个版本的账号,先在应用页切换版本。
-点击「登录 Qoder」或「添加账号」发起官方浏览器授权。新增授权在独立临时目录中完成,保留原生机器标识,但不复制当前登录;因此已登录时也能继续新增账号,取消或失败不会使原账号退出。首次登录成功后保存该版本的机器标识,后续新增账号继续使用同一标识,即使尚未启用任何账号,也能在多个已保存账号间切换。新增成功后留在本页,点击某一行的「使用此账号」才切换 Qoder 原生登录并启用官方自动选模,同时刷新该版本的供应商列表。每个账号右侧提供红色垃圾桶按钮,删除前显示确认窗口;删除只移除 CC Switch 保存的账号副本,不会在 Qoder 里登出,原生登录、其他账号、供应商、MCP、Skills 和会话文件保持原样。查看状态只刷新已收录账号的显示信息,不会自动收录:Qoder 当前登录的账号还不在列表里时,页面显示提示和「收录」按钮,由用户点击后才保存这个账号;收录前不能切换到其他已保存账号,免得这个登录在切换时丢失。
+点击「登录 Qoder」或「添加账号」发起官方浏览器授权。新增授权在独立临时目录中完成,保留原生机器标识,但不复制当前登录;因此已登录时也能继续新增账号,取消或失败不会使原账号退出。首次登录成功后保存该版本的机器标识,后续新增账号继续使用同一标识,即使尚未启用任何账号,也能在多个已保存账号间切换。新增成功后留在本页,点击某一行的「使用此账号」才切换 Qoder 原生登录(不改默认模型),同时刷新供应商页的官方卡。每个账号右侧提供红色垃圾桶按钮,删除前显示确认窗口;删除只移除 CC Switch 保存的账号副本,不会在 Qoder 里登出,原生登录、其他账号、供应商、MCP、Skills 和会话文件保持原样。查看状态只刷新已收录账号的显示信息,不会自动收录:Qoder 当前登录的账号还不在列表里时,页面显示提示和「收录」按钮,由用户点击后才保存这个账号;收录前不能切换到其他已保存账号,免得这个登录在切换时丢失。
每行的「重新登录」更新该账号原有的档案 ID,不新增重复条目。重新登录当前账号时同步更新原生登录;重新登录其他账号时保留当前登录。两种情况都保留当前模型、供应商和其他原生配置。登录期间账号已被删除或凭据发生变化时,拒绝覆盖;浏览器登录到另一个已保存的账号时,提示使用已有账号。写入账号档案失败时恢复原生凭据。授权中心返回后保留进入前的供应商页面;关闭授权中心或取消登录会清理待处理的授权流程。
浏览器授权、凭据加密和令牌续期仍使用 Qoder CLI 的官方 `login` / `status --output json` 流程,已按 1.1.76 分发包核对。CC Switch 在本机 `qoder_accounts.json` 中保存原生加密凭据快照及账号显示信息,按版本、原生配置目录和运行环境分别管理;加密凭据不写入供应商数据库,也不返回前端;界面只读取账号显示信息。切换和删除会检查原生凭据是否已被其他程序更改,并遵守 Qoder 的凭据事务锁。对应版本的 CLI 必须已安装。
-未使用的供应商卡片提供与其他应用一致的「切换」按钮,点击后使用该供应商配置的默认模型,未指定时使用第一个模型;当前供应商显示通用的「使用中」状态。模型也可通过卡片上的菜单选择;切回 Qoder 内置自动选择的入口放在当前供应商的更多菜单中。卡片的「配置用量查询」复用现有余额、Coding Plan 与自定义查询模板,并支持自动刷新。查询使用 Qoder 原生供应商中的地址与凭据,支持 `${ENV_NAME}` 引用;查询脚本等 CC Switch 元数据保存在本机数据库,独立于 Qoder 的配置文件和另一版本。
+模型卡的「配置用量查询」复用现有余额、Coding Plan 与自定义查询模板,并支持自动刷新。查询优先使用当前版本 `settings.json` 里这家的地址与凭据(在 Qoder 里改过 Key 也立即生效),支持 `${ENV_NAME}` 引用;查询脚本等 CC Switch 元数据保存在本机数据库,保存时不改写 Qoder 的配置文件。
用量页支持从两个版本各自的 `projects/` 会话日志导入请求数、输入/输出 Token、缓存 Token、供应商、模型与定价表估算费用。子代理日志 `projects/<project>/<session-id>/subagents/agent-*.jsonl` 的请求按日志中的 `sessionId` 计入主会话用量,包含普通、后台及 Workflow 子代理;主会话未更新时也会读取子代理新增的用量。仅有缓存 Token 的请求也参与统计。
流式快照、重复内容块、子代理继承的父会话消息、会话分叉和已汇总的历史记录会去重;未写完的最后一行留到下一轮读取。消息 ID 为空时继续使用有效的请求 ID 或 UUID,升级后会自动补扫旧日志,补入此前遗漏的请求。OpenAI/Responses 的输入 Token 含缓存,Anthropic 的输入 Token 不含缓存,统计按原生协议区分口径。自定义模型的费用来自本机定价表;Qoder 官方订阅使用 Credits,不以 Token 定价换算成账单费用,官方 Plan/Credits 额度仍由 Qoder 账号提供。Token 统计以原生日志提供的计数为准,无法推算官方模型隐藏的 Token 用量。
-原生格式已根据 Qoder CLI 1.1.76 分发包中的 `providers` 配置 schema 与模型加载器核对。保存保留 JSONC 注释、其他供应商、MCP、原生模型偏好及未编辑的扩展字段;编辑期间供应商被其他程序修改时拒绝覆盖并提示刷新。国际版和国内版的数据分别读写。新配置在 Qoder 重启后加载,自定义模型的运行权限仍取决于 Qoder 账号;CC Switch 不改写登录态或功能权限。Qoder 暂不接入本地路由,也不进托盘(托盘没有可切换的 Qoder 卡片,模型在 Qoder 页管理)。
+原生格式已根据 Qoder CLI 1.1.76 分发包中的 `providers` 配置 schema 与模型加载器核对。保存保留 JSONC 注释、其他供应商、MCP、原生模型偏好及未编辑的扩展字段;编辑期间供应商被其他程序修改时拒绝覆盖并提示刷新。国际版和国内版的数据分别读写。新配置在 Qoder 重启后加载,自定义模型的运行权限仍取决于 Qoder 账号;CC Switch 不改写登录态或功能权限。Qoder 暂不接入本地路由。托盘和其他累加式应用一样只加不减:点没勾的模型卡就添加,点官方卡跳到 Qoder 页。
依据 2026-10-22 核对的官方说明:[登录与认证](https://docs.qoder.com/cli/authentication)、[国际版安装与卸载](https://docs.qoder.com/cli/installation)、[国内版安装与卸载](https://docs.qoder.cn/cli/installation)、[自定义模型](https://docs.qoder.com/cli/custom-models)、[配置](https://docs.qoder.com/cli/settings)、[MCP](https://docs.qoder.com/cli/mcp-reference)、[Skills](https://docs.qoder.com/cli/Skills)、[会话](https://docs.qoder.com/cli/sessions)。
diff --git a/src-tauri/src/app_config.rs b/src-tauri/src/app_config.rs
index c57c314eb..674266043 100644
--- a/src-tauri/src/app_config.rs
+++ b/src-tauri/src/app_config.rs
@@ -496,10 +496,10 @@ impl AppType {
stack: false,
},
// 国际版、国内版是同一个应用,按设备设置 `qoderEdition` 选数据目录和 CLI。
- // 供应商直接在 Qoder 的 settings.json 里编辑,不进供应商表。
+ // 累加式(同 Kimi):卡片存库,「添加」写进所选版本 settings.json 的 providers。
AppType::Qoder => AppSpec {
id: "qoder",
- additive: false,
+ additive: true,
local_proxy: false,
route_mode: false,
stack: false,
diff --git a/src-tauri/src/commands/qoder.rs b/src-tauri/src/commands/qoder.rs
index b376c8c73..06e27059a 100644
--- a/src-tauri/src/commands/qoder.rs
+++ b/src-tauri/src/commands/qoder.rs
@@ -1,68 +1,18 @@
-//! Qoder CLI 的模型配置命令。国际版 / 国内版是同一个应用,命令都按设置里选的版本
-//! (`qoder_config::current_edition`)读写那一版的 `settings.json`。
-use crate::{
- app_config::AppType,
- qoder_config,
- qoder_models::{self, QoderModels},
-};
-use crate::{provider::UsageScript, store::AppState};
-use serde_json::Value;
+//! Qoder CLI 的供应商命令。卡片的增删改、添加 / 移除走通用供应商命令
+//! (`services::provider::qoder`),这里只有「设为默认」:Qoder 的一家供应商可以有多个模型,
+//! 要连模型一起选。
+use crate::services::ProviderService;
+use crate::store::AppState;
use tauri::State;
+/// 把所选版本的默认模型(`model.name`)设为这张卡:自带模型卡用 `model`(不传时用它的默认模型),
+/// 官方账号卡改回 `auto`。
#[tauri::command]
-pub fn get_qoder_models(state: State<'_, AppState>) -> Result<QoderModels, String> {
- qoder_models::get(qoder_config::current_edition())
- .and_then(|models| qoder_models::with_metadata(&state.db, models))
- .map_err(|error| error.to_string())
-}
-
-#[tauri::command]
-pub fn save_qoder_provider(
- state: State<'_, AppState>,
- id: String,
- provider: Value,
- expected: Option<Value>,
- make_default: bool,
-) -> Result<QoderModels, String> {
- qoder_models::save_provider(
- qoder_config::current_edition(),
- &id,
- provider,
- expected,
- make_default,
- )
- .and_then(|models| qoder_models::with_metadata(&state.db, models))
- .map_err(|error| error.to_string())
-}
-
-#[tauri::command]
-pub fn delete_qoder_provider(
- state: State<'_, AppState>,
- id: String,
- expected: Value,
-) -> Result<QoderModels, String> {
- let models = qoder_models::delete_provider(qoder_config::current_edition(), &id, expected)
- .map_err(|error| error.to_string())?;
- state
- .db
- .delete_provider(&AppType::Qoder, &id)
- .map_err(|error| error.to_string())?;
- qoder_models::with_metadata(&state.db, models).map_err(|error| error.to_string())
-}
-
-#[tauri::command]
-pub fn set_qoder_model(state: State<'_, AppState>, model: String) -> Result<QoderModels, String> {
- qoder_models::set_model(qoder_config::current_edition(), &model)
- .and_then(|models| qoder_models::with_metadata(&state.db, models))
- .map_err(|error| error.to_string())
-}
-
-#[tauri::command]
-pub fn save_qoder_usage_script(
+pub fn set_qoder_default_model(
state: State<'_, AppState>,
- id: String,
- script: UsageScript,
-) -> Result<QoderModels, String> {
- qoder_models::save_usage_script(&state.db, qoder_config::current_edition(), &id, script)
+ #[allow(non_snake_case)] providerId: String,
+ model: Option<String>,
+) -> Result<(), String> {
+ ProviderService::set_qoder_default(&state, &providerId, model.as_deref())
.map_err(|error| error.to_string())
}
diff --git a/src-tauri/src/commands/qoder_auth.rs b/src-tauri/src/commands/qoder_auth.rs
index d8d0674a9..b2cc3af73 100644
--- a/src-tauri/src/commands/qoder_auth.rs
+++ b/src-tauri/src/commands/qoder_auth.rs
@@ -284,6 +284,7 @@ pub async fn use_qoder_account(
#[tauri::command]
pub async fn delete_qoder_account(
state: State<'_, QoderAuthState>,
+ app_state: State<'_, crate::store::AppState>,
account_id: String,
) -> Result<QoderAuthStatus, String> {
let app = qoder_config::current_edition();
@@ -296,6 +297,8 @@ pub async fn delete_qoder_account(
let mut store = AccountStore::load()?;
store.remove(&scope, &account_id)?;
store.save()?;
+ // 供应商列表里这个号的官方卡跟着删
+ crate::services::provider::qoder::forget_official_card(&app_state, &account_id);
account_status(app).await
}
diff --git a/src-tauri/src/deeplink/provider.rs b/src-tauri/src/deeplink/provider.rs
index 35f012cf6..8a4ac4bd5 100644
--- a/src-tauri/src/deeplink/provider.rs
+++ b/src-tauri/src/deeplink/provider.rs
@@ -116,6 +116,7 @@ pub fn import_provider_from_deeplink(
| AppType::Dsh
| AppType::Omp
| AppType::ZCode
+ | AppType::Qoder
) {
// Display names may be Unicode, but these apps' native keys must pass their slug rules
// (DeepSeek Harness only takes lowercase hyphenated ids, MCode ASCII letters and digits,
@@ -286,6 +287,9 @@ impl ApiFormat {
(AppType::OpenClaw | AppType::Pi | AppType::Omp, GeminiNative) => {
Some("google-generative-ai")
}
+ (AppType::Qoder, Anthropic) => Some("anthropic"),
+ (AppType::Qoder, OpenAiChat) => Some("openai"),
+ (AppType::Qoder, OpenAiResponses) => Some("openai-responses"),
(AppType::Kimi, Anthropic) => Some("anthropic"),
(AppType::Kimi, OpenAiChat) => Some("openai"),
(AppType::Kimi, OpenAiResponses) => Some("openai_responses"),
@@ -443,11 +447,7 @@ pub(crate) fn build_provider_from_request(
AppType::OpenClaw => build_additive_app_settings(request, api_format),
AppType::Hermes => build_hermes_settings(request, api_format),
AppType::Pi => build_pi_settings(request, api_format)?,
- AppType::Qoder => {
- return Err(AppError::InvalidInput(
- "Manage Qoder custom models on the Qoder model settings page".into(),
- ));
- }
+ AppType::Qoder => build_qoder_settings(request, api_format)?,
AppType::Mcode | AppType::Dsh => {
build_custom_provider_settings(app_type, request, api_format)?
}
@@ -1285,6 +1285,24 @@ fn build_kimi_settings(
}))
}
+/// Qoder 的 `settings.json.providers` 节点:一家供应商、链接里的一个模型;Key 原样写入
+/// (也可以是 `${ENV}` 引用)。不支持的协议(Gemini 原生)在解析链接时就被拒。
+fn build_qoder_settings(
+ request: &DeepLinkImportRequest,
+ api_format: Option<ApiFormat>,
+) -> Result<serde_json::Value, AppError> {
+ let model = required_link_model(&AppType::Qoder, request)?;
+ let protocol = native_protocol(&AppType::Qoder, api_format);
+ Ok(json!({
+ "displayName": request.name.clone().unwrap_or_default(),
+ "protocol": protocol,
+ "baseUrl": get_primary_endpoint(request),
+ "apiKey": request.api_key.clone().unwrap_or_default(),
+ "model": model,
+ "models": [{"model": model}],
+ }))
+}
+
/// Kimi Code 的模型表是全局的,键和别家供应商撞了写入会被拒,所以键写成 `<供应商 id>/<模型>`,
/// 和预设一致。
fn namespace_kimi_models(settings: &mut serde_json::Value, id: &str) {
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index c1c62ce51..1ccd121d5 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -1699,11 +1699,7 @@ pub fn run() {
commands::delete_pi_prompt_template,
// Pi native provider and session views
commands::get_pi_current_state,
- commands::get_qoder_models,
- commands::save_qoder_provider,
- commands::delete_qoder_provider,
- commands::set_qoder_model,
- commands::save_qoder_usage_script,
+ commands::set_qoder_default_model,
commands::get_qoder_auth_status,
commands::start_qoder_login,
commands::poll_qoder_login,
diff --git a/src-tauri/src/qoder_accounts.rs b/src-tauri/src/qoder_accounts.rs
index 5616b9514..21e0a3786 100644
--- a/src-tauri/src/qoder_accounts.rs
+++ b/src-tauri/src/qoder_accounts.rs
@@ -474,6 +474,45 @@ impl AccountStore {
pub(crate) fn mark_active(&mut self, scope: &str, id: &str) {
self.active.insert(scope.into(), id.into());
}
+ /// 最近一次确认是 Qoder 当前登录的号(没确认过、或已删除时为空)
+ pub(crate) fn active(&self, scope: &str) -> Option<&str> {
+ let id = self.active.get(scope)?;
+ self.scopes
+ .get(scope)?
+ .iter()
+ .any(|account| &account.id == id)
+ .then_some(id.as_str())
+ }
+}
+
+/// 所选版本收录的账号和最近确认在用的那个号,供应商列表据此生成官方账号卡。
+/// 只读本机账号文件,不调用 Qoder CLI。
+pub(crate) fn saved_accounts(
+ edition: QoderEdition,
+) -> Result<(Vec<QoderAccount>, Option<String>), String> {
+ let root = absolute_root(edition)?;
+ let scope = scope(edition, &root);
+ let store = AccountStore::load()?;
+ let active = store.active(&scope).map(str::to_string);
+ Ok((store.accounts(&scope, None), active))
+}
+
+impl QoderAccount {
+ /// 卡片上显示的账号名:邮箱优先,其次用户名
+ pub(crate) fn display_name(&self) -> Option<&str> {
+ [&self.profile.email, &self.profile.username]
+ .into_iter()
+ .flatten()
+ .map(|value| value.trim())
+ .find(|value| !value.is_empty())
+ }
+ pub(crate) fn plan(&self) -> Option<&str> {
+ self.profile
+ .plan
+ .as_deref()
+ .map(str::trim)
+ .filter(|value| !value.is_empty())
+ }
}
#[cfg(test)]
diff --git a/src-tauri/src/qoder_config.rs b/src-tauri/src/qoder_config.rs
index e2f1f7d3d..a5cee3d20 100644
--- a/src-tauri/src/qoder_config.rs
+++ b/src-tauri/src/qoder_config.rs
@@ -39,21 +39,27 @@ pub fn current_edition() -> QoderEdition {
edition_for(&crate::settings::get_settings())
}
-/// 设置里没选版本时,中文界面默认国内版,其余默认国际版。
+/// 设置里没选版本时,中文界面默认国内版,其余默认国际版。没设过界面语言(首次安装)时
+/// 按系统区域判断,和前端 `getInitialLanguage`、托盘一致;否则中文系统的界面显示国内版,
+/// 后端却读写国际版的目录。
pub fn edition_for(settings: &crate::settings::AppSettings) -> QoderEdition {
settings.qoder_edition.unwrap_or_else(|| {
- if settings
+ let language = settings
.language
- .as_deref()
- .is_some_and(|language| language.to_ascii_lowercase().starts_with("zh"))
- {
- QoderEdition::Cn
- } else {
- QoderEdition::Global
- }
+ .clone()
+ .unwrap_or_else(|| crate::tray::detect_system_tray_language().to_string());
+ default_edition_for_language(&language)
})
}
+fn default_edition_for_language(language: &str) -> QoderEdition {
+ if language.to_ascii_lowercase().starts_with("zh") {
+ QoderEdition::Cn
+ } else {
+ QoderEdition::Global
+ }
+}
+
pub(crate) fn settings_write_lock(edition: QoderEdition) -> &'static Mutex<()> {
match edition {
QoderEdition::Cn => &CN_SETTINGS_LOCK,
@@ -192,6 +198,22 @@ fn enable_skill_file_and_commit<T>(
mod tests {
use super::*;
+ #[test]
+ fn qoder_edition_defaults_follow_the_interface_language() {
+ let mut settings = crate::settings::AppSettings {
+ language: Some("zh-TW".into()),
+ ..Default::default()
+ };
+ assert_eq!(edition_for(&settings), QoderEdition::Cn);
+ settings.language = Some("en".into());
+ assert_eq!(edition_for(&settings), QoderEdition::Global);
+ settings.qoder_edition = Some(QoderEdition::Cn);
+ assert_eq!(edition_for(&settings), QoderEdition::Cn);
+ // 没设过界面语言时按系统区域(和前端、托盘一致)
+ assert_eq!(default_edition_for_language("zh"), QoderEdition::Cn);
+ assert_eq!(default_edition_for_language("ja"), QoderEdition::Global);
+ }
+
#[test]
fn qoder_settings_writes_leave_user_privacy_choices_alone() {
let temp = tempfile::tempdir().unwrap();
diff --git a/src-tauri/src/qoder_models.rs b/src-tauri/src/qoder_models.rs
index 25399888f..5e8931d20 100644
--- a/src-tauri/src/qoder_models.rs
+++ b/src-tauri/src/qoder_models.rs
@@ -1,28 +1,25 @@
//! Qoder's native custom-provider schema (`settings.json.providers`).
-//! The account's runtime access remains Qoder's responsibility; this module
-//! edits local configuration without changing authentication or runtime access.
+//! 供应商卡片存在供应商表里(同 Kimi):「添加」把卡片写进所选版本的 `providers`,
+//! 「默认」是 `model.name`(`auto` 是 Qoder 官方自动选模,其余是 `<供应商>/<模型>`)。
+//! 账号的运行权限仍归 Qoder 管:这里只改本地配置,不碰登录态。
use crate::{
- app_config::AppType,
- database::Database,
error::AppError,
jsonc_document::JsoncDocument,
- provider::{Provider, ProviderMeta},
qoder_config::{self, QoderEdition},
};
-use serde::Serialize;
-use serde_json::{json, Map, Value};
+use indexmap::IndexMap;
+use serde_json::{json, Value};
use std::{
- collections::{HashMap, HashSet},
+ collections::HashSet,
fs,
- path::Path,
+ path::{Path, PathBuf},
};
-#[derive(Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct QoderModels {
- pub providers: Map<String, Value>,
- pub current_model: String,
- pub metadata: HashMap<String, ProviderMeta>,
+/// Qoder 官方自动选模。
+pub(crate) const AUTO_MODEL: &str = "auto";
+
+fn settings_path(edition: QoderEdition) -> PathBuf {
+ qoder_config::data_dir(edition).join("settings.json")
}
fn read(path: &Path) -> Result<JsoncDocument, AppError> {
@@ -77,176 +74,127 @@ fn read(path: &Path) -> Result<JsoncDocument, AppError> {
Ok(document)
}
-fn snapshot(document: &Value) -> QoderModels {
- QoderModels {
- metadata: HashMap::new(),
- providers: document
- .get("providers")
- .and_then(Value::as_object)
- .cloned()
- .unwrap_or_default(),
- current_model: document
- .pointer("/model/name")
- .and_then(Value::as_str)
- .filter(|value| !value.is_empty())
- .unwrap_or("auto")
- .into(),
- }
-}
-
-pub fn get(edition: QoderEdition) -> Result<QoderModels, AppError> {
- let _guard = qoder_config::settings_write_lock(edition)
+fn lock(edition: QoderEdition) -> Result<std::sync::MutexGuard<'static, ()>, AppError> {
+ qoder_config::settings_write_lock(edition)
.lock()
- .map_err(|error| AppError::Message(error.to_string()))?;
- Ok(snapshot(
- read(&qoder_config::data_dir(edition).join("settings.json"))?.value(),
- ))
+ .map_err(|error| AppError::Message(error.to_string()))
}
-pub(crate) fn with_metadata(
- db: &Database,
- mut models: QoderModels,
-) -> Result<QoderModels, AppError> {
- for (id, stored) in db.get_all_providers(&AppType::Qoder)? {
- if models.providers.contains_key(&id) {
- if let Some(meta) = stored.meta {
- models.metadata.insert(id, meta);
- }
- }
- }
- Ok(models)
+fn providers_in(document: &Value) -> IndexMap<String, Value> {
+ document
+ .get("providers")
+ .and_then(Value::as_object)
+ .map(|providers| {
+ providers
+ .iter()
+ .map(|(id, provider)| (id.clone(), provider.clone()))
+ .collect()
+ })
+ .unwrap_or_default()
}
-/// Credentials always come from the native file. CC Switch stores only its
-/// usage-query metadata in the database, without duplicating Qoder settings.
-pub(crate) fn usage_provider(
- db: &Database,
- edition: QoderEdition,
- id: &str,
-) -> Result<Provider, AppError> {
- let mut models = get(edition)?;
- let config = models
- .providers
- .remove(id)
- .ok_or_else(|| AppError::InvalidInput(format!("Qoder provider not found: {id}")))?;
- let name = config
- .get("displayName")
+fn current_model_in(document: &Value) -> String {
+ document
+ .pointer("/model/name")
.and_then(Value::as_str)
- .unwrap_or(id)
- .to_string();
- let mut provider = Provider::with_id(id.into(), name, config, None);
- provider.meta = db
- .get_provider_by_id(id, &AppType::Qoder)?
- .and_then(|stored| stored.meta);
- Ok(provider)
+ .filter(|value| !value.is_empty())
+ .unwrap_or(AUTO_MODEL)
+ .into()
}
-pub fn save_usage_script(
- db: &Database,
- edition: QoderEdition,
- id: &str,
- script: crate::provider::UsageScript,
-) -> Result<QoderModels, AppError> {
- crate::services::provider::validate_usage_script(&script)?;
- let mut provider = usage_provider(db, edition, id)?;
- provider
- .meta
- .get_or_insert_with(Default::default)
- .usage_script = Some(script);
- provider.settings_config = json!({});
- db.save_provider(&AppType::Qoder, &provider)?;
- with_metadata(db, get(edition)?)
+/// 所选版本 settings.json 里的自带供应商(按文件顺序)。
+pub(crate) fn providers(edition: QoderEdition) -> Result<IndexMap<String, Value>, AppError> {
+ let _guard = lock(edition)?;
+ Ok(providers_in(read(&settings_path(edition))?.value()))
+}
+
+/// 所选版本的默认模型(`model.name`,没写时是 `auto`)。
+pub(crate) fn current_model(edition: QoderEdition) -> Result<String, AppError> {
+ let _guard = lock(edition)?;
+ Ok(current_model_in(read(&settings_path(edition))?.value()))
}
-fn update(
+/// 默认模型属于哪家自带供应商:供应商 ID 不含 `/`,所以按第一个 `/` 切。
+pub(crate) fn model_owner(model: &str) -> Option<&str> {
+ model
+ .split_once('/')
+ .map(|(id, _)| id)
+ .filter(|id| !id.is_empty())
+}
+
+/// 保序改写所选版本的 settings.json,再提交库;提交失败时把文件还回去。
+pub(crate) fn change_and_commit<T>(
edition: QoderEdition,
change: impl FnOnce(&mut Value) -> Result<(), AppError>,
-) -> Result<QoderModels, AppError> {
- let _guard = qoder_config::settings_write_lock(edition)
- .lock()
- .map_err(|error| AppError::Message(error.to_string()))?;
- update_file(
- &qoder_config::data_dir(edition).join("settings.json"),
- change,
- )
+ commit: impl FnOnce() -> Result<T, AppError>,
+) -> Result<T, AppError> {
+ let _guard = lock(edition)?;
+ change_file_and_commit(&settings_path(edition), change, commit)
}
-fn update_file(
+fn change_file_and_commit<T>(
path: &Path,
change: impl FnOnce(&mut Value) -> Result<(), AppError>,
-) -> Result<QoderModels, AppError> {
- let mut document = read(path)?;
- let mut next = document.value().clone();
- change(&mut next)?;
- qoder_config::write_settings(path, &mut document, &mut next)?;
- Ok(snapshot(&next))
-}
-
-pub fn save_provider(
- edition: QoderEdition,
- id: &str,
- provider: Value,
- expected: Option<Value>,
- make_default: bool,
-) -> Result<QoderModels, AppError> {
- validate_provider(id, &provider)?;
- update(edition, |document| {
- save_provider_in(document, id, provider, expected.as_ref(), make_default)
- })
+ commit: impl FnOnce() -> Result<T, AppError>,
+) -> Result<T, AppError> {
+ crate::mcode_config::write_and_commit(
+ path,
+ || {
+ let mut document = read(path)?;
+ let mut next = document.value().clone();
+ change(&mut next)?;
+ qoder_config::write_settings(path, &mut document, &mut next)
+ },
+ commit,
+ )
}
-fn save_provider_in(
+/// 写入(或替换)一家供应商。默认模型指着它、但改完后它已经没有那个模型时,
+/// 改指向它的默认模型,免得 Qoder 启动时找不到模型。
+pub(crate) fn put_provider_in(
document: &mut Value,
id: &str,
provider: Value,
- expected: Option<&Value>,
- make_default: bool,
) -> Result<(), AppError> {
- check_expected(document, id, expected)?;
if document.get("providers").is_none() {
document["providers"] = json!({});
}
- let current = snapshot(document).current_model;
+ let current = current_model_in(document);
let default = default_model(&provider)
- .ok_or_else(|| AppError::InvalidInput("Add a Qoder model first".into()))?;
- let chosen = format!("{id}/{default}");
- let removed_active_model = current
+ .ok_or_else(|| AppError::InvalidInput("Add a Qoder model first".into()))?
+ .to_string();
+ let lost_default = current
.strip_prefix(&format!("{id}/"))
.is_some_and(|model| !has_model(&provider, model));
document["providers"][id] = provider;
- if make_default || removed_active_model {
- set_model_in(document, &chosen)?;
+ if lost_default {
+ set_model_in(document, &format!("{id}/{default}"))?;
}
Ok(())
}
-pub fn delete_provider(
- edition: QoderEdition,
- id: &str,
- expected: Value,
-) -> Result<QoderModels, AppError> {
- update(edition, |document| {
- check_expected(document, id, Some(&expected))?;
- if snapshot(document)
- .current_model
- .starts_with(&format!("{id}/"))
- {
- set_model_in(document, "auto")?;
- }
- if let Some(providers) = document.get_mut("providers").and_then(Value::as_object_mut) {
- providers.remove(id);
- }
- Ok(())
- })
+/// 从 settings.json 拿掉一家供应商;默认模型指着它时拒绝(先把别的设为默认)。
+pub(crate) fn remove_provider_in(document: &mut Value, id: &str) -> Result<(), AppError> {
+ if model_owner(&current_model_in(document)) == Some(id) {
+ return Err(AppError::localized(
+ "qoder.provider.defaultCannotRemove",
+ "这家是 Qoder 的默认模型,先把别的设为默认再移除",
+ "This provider holds Qoder's default model. Set another default before removing it",
+ ));
+ }
+ if let Some(providers) = document.get_mut("providers").and_then(Value::as_object_mut) {
+ providers.remove(id);
+ }
+ Ok(())
}
-pub fn set_model(edition: QoderEdition, model: &str) -> Result<QoderModels, AppError> {
- update(edition, |document| set_model_in(document, model))
+/// 改默认模型:`auto` 或 settings.json 里已有的 `<供应商>/<模型>`。
+pub(crate) fn set_model(edition: QoderEdition, model: &str) -> Result<(), AppError> {
+ change_and_commit(edition, |document| set_model_in(document, model), || Ok(()))
}
-fn set_model_in(document: &mut Value, model: &str) -> Result<(), AppError> {
- let current = snapshot(document).current_model;
- if model != "auto" && model != current {
+pub(crate) fn set_model_in(document: &mut Value, model: &str) -> Result<(), AppError> {
+ if model != AUTO_MODEL && model != current_model_in(document) {
let (id, model_id) = model
.split_once('/')
.ok_or_else(|| AppError::InvalidInput("Select an available Qoder model".into()))?;
@@ -254,14 +202,12 @@ fn set_model_in(document: &mut Value, model: &str) -> Result<(), AppError> {
.get("providers")
.and_then(|providers| providers.get(id))
.ok_or_else(|| {
- AppError::InvalidInput(
- "Qoder provider is no longer configured; refresh the model list".into(),
- )
+ AppError::InvalidInput("Add this provider to Qoder before using its model".into())
})?;
validate_provider(id, provider)?;
if !has_model(provider, model_id) {
return Err(AppError::InvalidInput(
- "Qoder model is no longer configured; refresh the model list".into(),
+ "Qoder model is no longer configured; refresh the provider list".into(),
));
}
}
@@ -272,20 +218,8 @@ fn set_model_in(document: &mut Value, model: &str) -> Result<(), AppError> {
Ok(())
}
-fn check_expected(document: &Value, id: &str, expected: Option<&Value>) -> Result<(), AppError> {
- let current = document
- .get("providers")
- .and_then(|providers| providers.get(id));
- if current != expected {
- return Err(AppError::InvalidInput(
- "Qoder provider changed outside this editor. Refresh and reopen it before saving"
- .into(),
- ));
- }
- Ok(())
-}
-
-fn default_model(provider: &Value) -> Option<&str> {
+/// 供应商的默认模型:`model`,没写时取模型列表的第一个。
+pub(crate) fn default_model(provider: &Value) -> Option<&str> {
provider
.get("model")
.and_then(Value::as_str)
@@ -300,7 +234,7 @@ fn default_model(provider: &Value) -> Option<&str> {
})
}
-fn has_model(provider: &Value, id: &str) -> bool {
+pub(crate) fn has_model(provider: &Value, id: &str) -> bool {
provider.get("model").and_then(Value::as_str) == Some(id)
|| provider
.get("models")
@@ -495,14 +429,19 @@ mod tests {
fs::write(&path, "{\n // native settings\n \"model\": {\"name\": \"auto\", \"reasoningEffort\": \"high\"},\n \"mcpServers\": {\"local\": {\"command\": \"node\"}},\n \"skills\": {\"custom\": true},\n \"modelConfigs\": {\"customModels\": [{\"provider\":\"legacy\"}]},\n \"providers\": {\"other\": {\"model\":\"native\",\"apiKey\":\"untouched\"}}\n}\n").unwrap();
let before = read(&path).unwrap().value().clone();
validate_provider("example", &provider()).unwrap();
- let state = update_file(&path, |document| {
- save_provider_in(document, "example", provider(), None, true)
- })
+ change_file_and_commit(
+ &path,
+ |document| {
+ put_provider_in(document, "example", provider())?;
+ set_model_in(document, "example/vendor/model-one")
+ },
+ || Ok(()),
+ )
.unwrap();
- assert_eq!(state.current_model, "example/vendor/model-one");
let source = fs::read_to_string(&path).unwrap();
assert!(source.contains("// native settings"));
let saved = read(&path).unwrap();
+ assert_eq!(current_model_in(saved.value()), "example/vendor/model-one");
for field in ["mcpServers", "skills", "modelConfigs"] {
assert_eq!(saved.value()[field], before[field]);
}
@@ -511,35 +450,34 @@ mod tests {
before["providers"]["other"]
);
assert_eq!(saved.value()["model"]["reasoningEffort"], "high");
- assert_eq!(saved.value()["privacy"], before["privacy"]);
assert_eq!(saved.value()["providers"]["example"], provider());
- assert!(saved.value()["providers"]["example"]["models"].is_array());
+ assert_eq!(
+ providers_in(saved.value()).keys().collect::<Vec<_>>(),
+ ["other", "example"]
+ );
}
#[test]
- fn qoder_model_editor_rejects_stale_snapshots_and_keeps_invalid_files() {
+ fn qoder_settings_survive_failed_commits_and_invalid_files() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("settings.json");
let original =
- json!({"providers":{"example":provider()},"model":{"name":"auto"}}).to_string();
+ json!({"providers":{"example":provider()},"model":{"name":"example/vendor/model-one"}})
+ .to_string();
fs::write(&path, &original).unwrap();
- let mut changed = provider();
- changed["apiKey"] = json!("changed-in-other-app");
- assert!(update_file(&path, |document| save_provider_in(
- document,
- "example",
- provider(),
- Some(&changed),
- true
- ))
+ // 默认模型指着的供应商不能移除
+ assert!(change_file_and_commit(
+ &path,
+ |document| remove_provider_in(document, "example"),
+ || Ok(())
+ )
.is_err());
- assert!(update_file(&path, |document| save_provider_in(
- document,
- "example",
- provider(),
- None,
- false
- ))
+ // 库提交失败时文件还原
+ assert!(change_file_and_commit(
+ &path,
+ |document| set_model_in(document, AUTO_MODEL),
+ || Err::<(), _>(AppError::Message("db".into()))
+ )
.is_err());
assert_eq!(fs::read_to_string(&path).unwrap(), original);
for malformed in [
@@ -549,7 +487,7 @@ mod tests {
"{\"providers\":{},\"providers\":{}}",
] {
fs::write(&path, malformed).unwrap();
- assert!(update_file(&path, |_| Ok(())).is_err());
+ assert!(change_file_and_commit(&path, |_| Ok(()), || Ok(())).is_err());
assert_eq!(fs::read_to_string(&path).unwrap(), malformed);
}
}
@@ -587,7 +525,7 @@ mod tests {
let mut edited = provider();
edited["model"] = json!("model-two");
edited["models"] = json!([{"model":"model-two"}]);
- save_provider_in(&mut document, "example", edited, Some(&provider()), false).unwrap();
+ put_provider_in(&mut document, "example", edited).unwrap();
assert_eq!(document["model"]["name"], "example/model-two");
assert_eq!(document["model"]["reasoningEffort"], "high");
let before = document.clone();
diff --git a/src-tauri/src/services/provider/live.rs b/src-tauri/src/services/provider/live.rs
index adc0afade..e88fd14df 100644
--- a/src-tauri/src/services/provider/live.rs
+++ b/src-tauri/src/services/provider/live.rs
@@ -41,6 +41,8 @@ pub(crate) fn provider_exists_in_live_config(
AppType::Omp => Ok(crate::omp_config::get_providers()?.contains_key(provider_id)),
AppType::Codebuddy => crate::codebuddy_config::provider_key_exists(provider_id),
AppType::Copilot => crate::copilot_config::provider_key_exists(provider_id),
+ AppType::Qoder => crate::qoder_models::providers(crate::qoder_config::current_edition())
+ .map(|providers| providers.contains_key(provider_id)),
AppType::WorkBuddy => crate::workbuddy_config::get_providers()
.map(|providers| providers.contains_key(provider_id)),
AppType::ZCode => crate::zcode_config::get_providers()
@@ -51,9 +53,7 @@ pub(crate) fn provider_exists_in_live_config(
| AppType::Codex
| AppType::Gemini
| AppType::GrokBuild
- | AppType::Agy
- // Qoder 的模型在它自己的 settings.json 里,由 Qoder 页的专用命令管理。
- | AppType::Qoder => Ok(false),
+ | AppType::Agy => Ok(false),
}
}
@@ -615,9 +615,10 @@ pub(crate) fn codex_managed_oauth_live_auth(
/// Write live configuration snapshot for a provider
pub(crate) fn write_live_snapshot(app_type: &AppType, provider: &Provider) -> Result<(), AppError> {
match app_type {
+ // Qoder 的条目和库由 `services::provider::qoder` 在同一个操作里提交
AppType::Qoder => {
return Err(AppError::InvalidInput(
- "Manage Qoder models on the Qoder page".into(),
+ "Qoder providers are written by the Qoder provider service".into(),
));
}
AppType::Claude => {
@@ -1207,7 +1208,9 @@ pub fn read_live_settings(app_type: AppType) -> Result<Value, AppError> {
}
AppType::Mcode => Ok(json!(crate::mcode_config::get_providers()?)),
AppType::ZCode => Ok(json!(crate::zcode_config::get_providers()?)),
- AppType::Qoder => Ok(json!({})),
+ AppType::Qoder => Ok(json!(crate::qoder_models::providers(
+ crate::qoder_config::current_edition()
+ )?)),
AppType::Kimi => Ok(json!(crate::kimi_config::get_providers()?)),
AppType::Dsh => Ok(json!(crate::dsh_config::get_providers()?)),
AppType::WorkBuddy => Ok(json!(crate::workbuddy_config::get_providers()?)),
@@ -1448,10 +1451,6 @@ pub fn import_default_config(state: &AppState, app_type: AppType) -> Result<bool
/// 这个应用是否从 live 导入 `default` 供应商:切换式应用都导入;累加式应用里只有 Copilot
/// (它的官方登录卡是启动式,从 settings.json 的模型导入,自带模型卡才是累加式)。
pub(crate) fn imports_default_config(app_type: &AppType) -> bool {
- // Qoder 的模型不进供应商表(表里只放用量脚本这类附加信息),没有「default」可导入。
- if matches!(app_type, AppType::Qoder) {
- return false;
- }
!app_type.spec().additive || matches!(app_type, AppType::Copilot)
}
diff --git a/src-tauri/src/services/provider/mod.rs b/src-tauri/src/services/provider/mod.rs
index e2fa5a184..69de68d98 100644
--- a/src-tauri/src/services/provider/mod.rs
+++ b/src-tauri/src/services/provider/mod.rs
@@ -27,6 +27,7 @@ mod omp;
#[cfg(test)]
mod opencode_tests;
mod pi;
+pub(crate) mod qoder;
mod usage;
use indexmap::IndexMap;
@@ -6028,9 +6029,8 @@ impl ProviderService {
state: &AppState,
app_type: AppType,
) -> Result<IndexMap<String, Provider>, AppError> {
- // Qoder 的供应商表只存用量脚本这类附加信息,卡片列表由 Qoder 页从 settings.json 读。
if app_type == AppType::Qoder {
- return Ok(IndexMap::new());
+ return qoder::list(state);
}
let _native_guard = lock_native_provider_operations(state, &app_type);
if app_type == AppType::Dsh {
@@ -6179,6 +6179,9 @@ impl ProviderService {
///
/// 对于累加模式应用(OpenCode, OpenClaw),不存在"当前供应商"概念,直接返回空字符串。
pub fn current(state: &AppState, app_type: AppType) -> Result<String, AppError> {
+ if app_type == AppType::Qoder {
+ return qoder::current();
+ }
if app_type == AppType::Kimi {
return crate::kimi_config::current_provider();
}
@@ -6336,6 +6339,9 @@ impl ProviderService {
if app_type == AppType::Pi {
return pi::add(state, provider, add_to_live);
}
+ if app_type == AppType::Qoder {
+ return qoder::add(state, provider, add_to_live);
+ }
// CodeBuddy 官方登录卡只绑定账号,永远不写进 models.json
let add_to_live = add_to_live && !Self::is_codebuddy_official(&app_type, &provider);
@@ -6971,6 +6977,10 @@ impl ProviderService {
return omp::update(state, original_id, provider);
}
+ if app_type == AppType::Qoder {
+ return qoder::update(state, original_id, provider);
+ }
+
let original_id = original_id.unwrap_or(provider.id.as_str()).to_string();
let provider_id_changed = original_id != provider.id;
// 读旧行、判断谁是当前供应商、存行、写 live 都在切换锁里:进入代理和切换都等这次
@@ -7263,6 +7273,15 @@ impl ProviderService {
Ok(true)
}
+ /// Qoder「设为默认」:见 [`qoder::set_default`]。
+ pub fn set_qoder_default(
+ state: &AppState,
+ id: &str,
+ model: Option<&str>,
+ ) -> Result<(), AppError> {
+ qoder::set_default(state, id, model)
+ }
+
pub(crate) fn update_pi_usage_script(
state: &AppState,
app_type: AppType,
@@ -7323,6 +7342,9 @@ impl ProviderService {
if app_type == AppType::Omp {
return omp::delete(state, id);
}
+ if app_type == AppType::Qoder {
+ return qoder::delete(state, id);
+ }
// Additive mode apps - no current provider concept
if app_type.spec().additive {
@@ -7434,6 +7456,9 @@ impl ProviderService {
if app_type == AppType::Copilot {
return Self::add_copilot_to_live(state, id);
}
+ if app_type == AppType::Qoder {
+ return qoder::add_to_live(state, id);
+ }
if app_type != AppType::Kimi {
return Err(AppError::InvalidInput(format!(
"{} adds providers through switch",
@@ -7530,6 +7555,9 @@ impl ProviderService {
if app_type == AppType::Omp {
return omp::remove(state, id);
}
+ if app_type == AppType::Qoder {
+ return qoder::remove(state, id);
+ }
if app_type == AppType::WorkBuddy {
if let Some(mut provider) = state.db.get_provider_by_id(id, &app_type)? {
@@ -7679,6 +7707,9 @@ impl ProviderService {
if app_type == AppType::Omp {
return omp::enable(state, id);
}
+ if app_type == AppType::Qoder {
+ return qoder::switch(state, id);
+ }
// Check if provider exists. 别的行读不出来不拦这次切换(它们在下面只用来找上一家;
// 上一家读不出来就和它不在库里一样处理);要切到的这一行读不出来则报错。
@@ -9019,11 +9050,10 @@ impl ProviderService {
));
}
}
- // Qoder 的模型由 Qoder 页的专用命令写进它自己的 settings.json,不经供应商表。
+ // 官方账号卡只绑定账号,不写进 settings.json
+ AppType::Qoder if qoder::is_official(provider) => {}
AppType::Qoder => {
- return Err(AppError::InvalidInput(
- "Manage Qoder models on the Qoder page".into(),
- ));
+ crate::qoder_models::validate_provider(&provider.id, &provider.settings_config)?
}
}
diff --git a/src-tauri/src/services/provider/qoder.rs b/src-tauri/src/services/provider/qoder.rs
new file mode 100644
index 000000000..c844deb03
--- /dev/null
+++ b/src-tauri/src/services/provider/qoder.rs
@@ -0,0 +1,519 @@
+//! Qoder CLI 的供应商卡片,和 Kimi Code 一样是累加式:
+//!
+//! - 自带模型卡存在供应商表里。「添加」把卡片写进所选版本 `settings.json` 的 `providers`,
+//! 「移除」只拿掉这一家的条目,卡片留着;「默认」是 `model.name`。打开列表时把文件里
+//! 已有、库里没有的供应商导入成卡片。国际版和国内版共用同一批卡片,「已添加」按当前版本的
+//! 文件现算,切版本不搬动任何配置。
+//! - 官方账号卡由授权中心收录的账号生成(每个号一张,`qoder-official-<账号 ID>`),只绑定账号、
+//! 不写文件。Qoder 同时只登录一个号:在用的那张算「已添加」,其他号的「添加」在前端走
+//! 授权中心的切号命令。默认模型是 `auto`(官方自动选模)时,在用的官方卡就是「默认」。
+//! 另一个版本或别的设备收录的账号卡留在库里、不显示(云同步下删掉会两台设备来回删)。
+use super::{ProviderService, SwitchResult};
+use crate::{
+ app_config::AppType,
+ error::AppError,
+ provider::{AuthBinding, AuthBindingSource, Provider, ProviderMeta},
+ qoder_accounts::{self, QoderAccount},
+ qoder_config::{self, QoderEdition},
+ qoder_models::{self, AUTO_MODEL},
+ store::AppState,
+};
+use indexmap::IndexMap;
+use serde_json::{json, Value};
+use std::{cell::RefCell, collections::HashSet};
+
+const APP: AppType = AppType::Qoder;
+const OFFICIAL_PREFIX: &str = "qoder-official-";
+pub(crate) const AUTH_PROVIDER: &str = "qoder_oauth";
+
+fn lock(state: &AppState) -> tokio::sync::OwnedMutexGuard<()> {
+ futures::executor::block_on(state.proxy_service.lock_switch_for_app(APP.as_str()))
+}
+
+pub(crate) fn official_card_id(account_id: &str) -> String {
+ format!("{OFFICIAL_PREFIX}{account_id}")
+}
+
+pub(crate) fn is_official(provider: &Provider) -> bool {
+ provider.category.as_deref() == Some("official")
+}
+
+fn bound_account(provider: &Provider) -> Option<String> {
+ provider
+ .meta
+ .as_ref()
+ .and_then(|meta| meta.managed_account_id_for(AUTH_PROVIDER))
+}
+
+fn official_name(edition: QoderEdition, account: &QoderAccount) -> String {
+ let app = match edition {
+ QoderEdition::Global => "Qoder",
+ QoderEdition::Cn => "Qoder CN",
+ };
+ match account.display_name() {
+ Some(name) => format!("{app} · {name}"),
+ None => app.into(),
+ }
+}
+
+fn official_website(edition: QoderEdition) -> &'static str {
+ match edition {
+ QoderEdition::Global => "https://qoder.com",
+ QoderEdition::Cn => "https://qoder.com.cn",
+ }
+}
+
+fn missing(id: &str) -> AppError {
+ AppError::Message(format!("供应商 {id} 不存在"))
+}
+
+fn official_managed_in_auth_center() -> AppError {
+ AppError::localized(
+ "qoder.official.managedInAuthCenter",
+ "Qoder 官方账号在授权中心添加和删除",
+ "Add and delete Qoder official accounts in the Authorization Center",
+ )
+}
+
+fn official_not_in_settings() -> AppError {
+ AppError::localized(
+ "qoder.official.notAModel",
+ "官方账号卡不写进 Qoder 的模型配置;点卡片上的「添加」会把 Qoder 切到这个账号",
+ "Official account cards are not written to Qoder's model settings; click Add on the card to switch Qoder to this account",
+ )
+}
+
+fn duplicate(id: &str) -> AppError {
+ AppError::InvalidInput(format!("qoder provider key '{id}' already exists"))
+}
+
+/// 自带模型卡保存前:校验原生格式,卡片名同步成 Qoder 里显示的 `displayName`。
+fn prepare(provider: &mut Provider) -> Result<(), AppError> {
+ if provider.id.starts_with(OFFICIAL_PREFIX) {
+ return Err(AppError::InvalidInput(
+ "Provider IDs starting with 'qoder-official-' are reserved".into(),
+ ));
+ }
+ // 导入的卡片名就是供应商 ID、文件里没写 displayName 时不补,免得只改用量脚本也改动文件
+ let name = provider.name.trim();
+ if !name.is_empty()
+ && provider.settings_config.is_object()
+ && (name != provider.id || provider.settings_config.get("displayName").is_some())
+ {
+ provider.settings_config["displayName"] = json!(name);
+ }
+ qoder_models::validate_provider(&provider.id, &provider.settings_config)?;
+ provider.in_failover_queue = false;
+ if provider.category.as_deref() == Some("official") {
+ provider.category = Some("custom".into());
+ }
+ Ok(())
+}
+
+fn row_changed(before: Option<&Provider>, after: &Provider) -> bool {
+ before
+ .is_none_or(|before| serde_json::to_value(before).ok() != serde_json::to_value(after).ok())
+}
+
+pub(super) fn list(state: &AppState) -> Result<IndexMap<String, Provider>, AppError> {
+ let _guard = lock(state);
+ let edition = qoder_config::current_edition();
+ let mut saved = match state.db.get_all_providers(&APP) {
+ Ok(saved) => saved,
+ // 有读不出来的行时不合并:按「库里没有」补存原生条目会盖掉那一行。
+ Err(error) => {
+ log::warn!("Not merging Qoder providers: {error}");
+ return Ok(state.db.get_provider_rows(&APP)?.readable);
+ }
+ };
+ match qoder_models::providers(edition) {
+ Ok(native) => sync_custom(state, &mut saved, &native)?,
+ // 读不了时保留上次的「已添加」状态:读失败不等于被移除。
+ Err(error) => log::warn!("Could not read Qoder settings.json: {error}"),
+ }
+ let visible = match qoder_accounts::saved_accounts(edition) {
+ Ok((accounts, active)) => {
+ sync_official(state, &mut saved, edition, &accounts, active.as_deref())?
+ }
+ Err(error) => {
+ log::warn!("Could not read saved Qoder accounts: {error}");
+ HashSet::new()
+ }
+ };
+ saved.retain(|id, provider| !is_official(provider) || visible.contains(id));
+ Ok(saved)
+}
+
+fn sync_custom(
+ state: &AppState,
+ saved: &mut IndexMap<String, Provider>,
+ native: &IndexMap<String, Value>,
+) -> Result<(), AppError> {
+ for (id, config) in native {
+ if !saved.contains_key(id) && !id.starts_with(OFFICIAL_PREFIX) {
+ let name = config
+ .get("displayName")
+ .and_then(Value::as_str)
+ .filter(|name| !name.trim().is_empty())
+ .unwrap_or(id);
+ let mut provider = Provider::with_id(id.clone(), name.into(), config.clone(), None);
+ provider.category = Some("custom".into());
+ ProviderService::set_provider_live_config_managed(&mut provider, true);
+ state.db.save_provider(&APP, &provider)?;
+ saved.insert(id.clone(), provider);
+ }
+ }
+ for (id, provider) in saved.iter_mut() {
+ if is_official(provider) {
+ continue;
+ }
+ let before = provider.clone();
+ if let Some(config) = native.get(id) {
+ provider.settings_config = config.clone();
+ if let Some(name) = config
+ .get("displayName")
+ .and_then(Value::as_str)
+ .filter(|name| !name.trim().is_empty())
+ {
+ provider.name = name.into();
+ }
+ }
+ ProviderService::set_provider_live_config_managed(provider, native.contains_key(id));
+ if row_changed(Some(&before), provider) {
+ state.db.save_provider(&APP, provider)?;
+ }
+ }
+ Ok(())
+}
+
+fn sync_official(
+ state: &AppState,
+ saved: &mut IndexMap<String, Provider>,
+ edition: QoderEdition,
+ accounts: &[QoderAccount],
+ active: Option<&str>,
+) -> Result<HashSet<String>, AppError> {
+ let mut visible = HashSet::new();
+ for account in accounts {
+ let id = official_card_id(&account.id);
+ let existing = saved.get(&id).cloned();
+ let mut provider = existing.clone().unwrap_or_else(|| {
+ let mut provider = Provider::with_id(
+ id.clone(),
+ official_name(edition, account),
+ json!({}),
+ Some(official_website(edition).into()),
+ );
+ provider.category = Some("official".into());
+ provider.icon = Some("qoder".into());
+ provider.meta = Some(ProviderMeta {
+ auth_binding: Some(AuthBinding {
+ source: AuthBindingSource::ManagedAccount,
+ auth_provider: Some(AUTH_PROVIDER.into()),
+ account_id: Some(account.id.clone()),
+ }),
+ ..Default::default()
+ });
+ provider
+ });
+ // 自动生成的名字跟着账号资料走,用户改过的名字保留
+ if provider.name.trim().is_empty() || provider.name.starts_with("Qoder") {
+ provider.name = official_name(edition, account);
+ }
+ if provider
+ .notes
+ .as_deref()
+ .is_none_or(|notes| notes.is_empty())
+ {
+ provider.notes = account.plan().map(str::to_string);
+ }
+ ProviderService::set_provider_live_config_managed(
+ &mut provider,
+ active == Some(account.id.as_str()),
+ );
+ if row_changed(existing.as_ref(), &provider) {
+ state.db.save_provider(&APP, &provider)?;
+ }
+ saved.insert(id.clone(), provider);
+ visible.insert(id);
+ }
+ Ok(visible)
+}
+
+/// 「默认」那家:`model.name` 是 `auto` 时是在用的官方账号卡,否则是模型所属的自带供应商。
+pub(super) fn current() -> Result<String, AppError> {
+ let edition = qoder_config::current_edition();
+ let model = match qoder_models::current_model(edition) {
+ Ok(model) => model,
+ Err(error) => {
+ log::warn!("读取 Qoder 默认模型失败: {error}");
+ return Ok(String::new());
+ }
+ };
+ if model == AUTO_MODEL {
+ return Ok(qoder_accounts::saved_accounts(edition)
+ .ok()
+ .and_then(|(_, active)| active)
+ .map(|account| official_card_id(&account))
+ .unwrap_or_default());
+ }
+ Ok(qoder_models::model_owner(&model)
+ .unwrap_or_default()
+ .to_string())
+}
+
+fn ensure_unused(state: &AppState, edition: QoderEdition, id: &str) -> Result<(), AppError> {
+ if state.db.get_provider_by_id(id, &APP)?.is_some()
+ || qoder_models::providers(edition)?.contains_key(id)
+ {
+ return Err(duplicate(id));
+ }
+ Ok(())
+}
+
+pub(super) fn add(
+ state: &AppState,
+ mut provider: Provider,
+ add_to_live: bool,
+) -> Result<bool, AppError> {
+ let _guard = lock(state);
+ if is_official(&provider) {
+ return Err(official_managed_in_auth_center());
+ }
+ prepare(&mut provider)?;
+ ProviderService::validate_provider_settings(&APP, &provider)?;
+ let edition = qoder_config::current_edition();
+ ensure_unused(state, edition, &provider.id)?;
+ ProviderService::set_provider_live_config_managed(&mut provider, add_to_live);
+ let commit = || {
+ state.db.save_provider(&APP, &provider)?;
+ Ok(true)
+ };
+ if !add_to_live {
+ return commit();
+ }
+ let (id, config) = (provider.id.clone(), provider.settings_config.clone());
+ qoder_models::change_and_commit(
+ edition,
+ |document| qoder_models::put_provider_in(document, &id, config),
+ commit,
+ )
+}
+
+pub(super) fn update(
+ state: &AppState,
+ original_id: Option<&str>,
+ mut provider: Provider,
+) -> Result<bool, AppError> {
+ let _guard = lock(state);
+ let id = original_id.unwrap_or(&provider.id).to_string();
+ let existing = state
+ .db
+ .get_provider_by_id(&id, &APP)?
+ .ok_or_else(|| missing(&id))?;
+ if provider.id != id {
+ return Err(AppError::InvalidInput(
+ "Qoder provider keys cannot be changed".into(),
+ ));
+ }
+ if is_official(&existing) {
+ // 官方卡的名字、备注、图标可以改;绑定的账号和「不写文件」不能改
+ provider.category = existing.category.clone();
+ provider.settings_config = json!({});
+ let meta = provider.meta.get_or_insert_with(Default::default);
+ let existing_meta = existing.meta.clone().unwrap_or_default();
+ meta.auth_binding = existing_meta.auth_binding;
+ meta.live_config_managed = existing_meta.live_config_managed;
+ state.db.save_provider(&APP, &provider)?;
+ return Ok(true);
+ }
+ prepare(&mut provider)?;
+ ProviderService::validate_provider_settings(&APP, &provider)?;
+ let edition = qoder_config::current_edition();
+ let native = qoder_models::providers(edition)?;
+ let live = native.contains_key(&id);
+ ProviderService::set_provider_live_config_managed(&mut provider, live);
+ // 只改了名字以外的卡片信息(如用量脚本)时不碰文件
+ if !live || native.get(&id) == Some(&provider.settings_config) {
+ state.db.save_provider(&APP, &provider)?;
+ return Ok(true);
+ }
+ let config = provider.settings_config.clone();
+ qoder_models::change_and_commit(
+ edition,
+ |document| qoder_models::put_provider_in(document, &id, config),
+ || {
+ state.db.save_provider(&APP, &provider)?;
+ Ok(true)
+ },
+ )
+}
+
+pub(super) fn delete(state: &AppState, id: &str) -> Result<(), AppError> {
+ let _guard = lock(state);
+ let existing = state
+ .db
+ .get_provider_by_id(id, &APP)?
+ .ok_or_else(|| missing(id))?;
+ if is_official(&existing) {
+ return Err(official_managed_in_auth_center());
+ }
+ let edition = qoder_config::current_edition();
+ if !qoder_models::providers(edition)?.contains_key(id) {
+ return state.db.delete_provider(&APP, id);
+ }
+ qoder_models::change_and_commit(
+ edition,
+ |document| qoder_models::remove_provider_in(document, id),
+ || state.db.delete_provider(&APP, id),
+ )
+}
+
+/// 「添加」:写进所选版本的 settings.json,不改默认模型;文件里已有这一家时原样保留(同 Kimi)。
+pub(super) fn add_to_live(state: &AppState, id: &str) -> Result<(), AppError> {
+ let _guard = lock(state);
+ let mut provider = state
+ .db
+ .get_provider_by_id(id, &APP)?
+ .ok_or_else(|| missing(id))?;
+ if is_official(&provider) {
+ return Err(official_not_in_settings());
+ }
+ let edition = qoder_config::current_edition();
+ ProviderService::set_provider_live_config_managed(&mut provider, true);
+ if let Some(native) = qoder_models::providers(edition)?.get(id) {
+ provider.settings_config = native.clone();
+ return state.db.save_provider(&APP, &provider);
+ }
+ qoder_models::validate_provider(id, &provider.settings_config)?;
+ let config = provider.settings_config.clone();
+ qoder_models::change_and_commit(
+ edition,
+ |document| qoder_models::put_provider_in(document, id, config),
+ || state.db.save_provider(&APP, &provider),
+ )
+}
+
+/// 「移除」:从 settings.json 拿掉这一家,卡片留着(带上文件里最新的配置);默认那家拒绝。
+pub(super) fn remove(state: &AppState, id: &str) -> Result<(), AppError> {
+ let _guard = lock(state);
+ let mut provider = state
+ .db
+ .get_provider_by_id(id, &APP)?
+ .ok_or_else(|| missing(id))?;
+ if is_official(&provider) {
+ return Err(official_not_in_settings());
+ }
+ let removed = RefCell::new(None);
+ qoder_models::change_and_commit(
+ qoder_config::current_edition(),
+ |document| {
+ *removed.borrow_mut() = document
+ .get("providers")
+ .and_then(|providers| providers.get(id))
+ .cloned();
+ qoder_models::remove_provider_in(document, id)
+ },
+ || {
+ if let Some(config) = removed.borrow_mut().take() {
+ provider.settings_config = config;
+ }
+ ProviderService::set_provider_live_config_managed(&mut provider, false);
+ state.db.save_provider(&APP, &provider)
+ },
+ )
+}
+
+/// 「设为默认」:自带模型卡改 `model.name` 为这一家的某个模型(不在文件里时先写进去),
+/// 官方账号卡改回 `auto`(只限 Qoder 正在登录的那个号)。
+pub(crate) fn set_default(state: &AppState, id: &str, model: Option<&str>) -> Result<(), AppError> {
+ let _guard = lock(state);
+ let mut provider = state
+ .db
+ .get_provider_by_id(id, &APP)?
+ .ok_or_else(|| missing(id))?;
+ let edition = qoder_config::current_edition();
+ if is_official(&provider) {
+ let active = qoder_accounts::saved_accounts(edition)
+ .map_err(AppError::Message)?
+ .1;
+ if active.is_none() || active != bound_account(&provider) {
+ return Err(AppError::localized(
+ "qoder.official.notSignedIn",
+ "Qoder 现在登录的不是这个账号,先点这张卡的「添加」切过去",
+ "Qoder is not signed in to this account. Click Add on this card to switch to it first",
+ ));
+ }
+ return qoder_models::set_model(edition, AUTO_MODEL);
+ }
+ let native = qoder_models::providers(edition)?;
+ let config = native
+ .get(id)
+ .cloned()
+ .unwrap_or_else(|| provider.settings_config.clone());
+ let model = match model {
+ Some(model) => model.to_string(),
+ None => qoder_models::default_model(&config)
+ .ok_or_else(|| AppError::InvalidInput("Add a Qoder model first".into()))?
+ .to_string(),
+ };
+ let in_file = native.contains_key(id);
+ if !in_file {
+ qoder_models::validate_provider(id, &config)?;
+ }
+ provider.settings_config = config.clone();
+ ProviderService::set_provider_live_config_managed(&mut provider, true);
+ qoder_models::change_and_commit(
+ edition,
+ |document| {
+ if !in_file {
+ qoder_models::put_provider_in(document, id, config)?;
+ }
+ qoder_models::set_model_in(document, &format!("{id}/{model}"))
+ },
+ || state.db.save_provider(&APP, &provider),
+ )
+}
+
+/// 通用「切换」(托盘、深链接等):自带模型卡设为默认,用它的默认模型。
+pub(super) fn switch(state: &AppState, id: &str) -> Result<SwitchResult, AppError> {
+ {
+ let _guard = lock(state);
+ let provider = state
+ .db
+ .get_provider_by_id(id, &APP)?
+ .ok_or_else(|| missing(id))?;
+ if is_official(&provider) {
+ return Err(official_not_in_settings());
+ }
+ }
+ set_default(state, id, None)?;
+ Ok(SwitchResult::default())
+}
+
+/// 托盘直接读库:去掉另一个版本(或别的设备)收录的账号卡,和列表同一口径。
+pub(crate) fn without_hidden_accounts(
+ mut rows: IndexMap<String, Provider>,
+) -> IndexMap<String, Provider> {
+ let visible: HashSet<String> = qoder_accounts::saved_accounts(qoder_config::current_edition())
+ .map(|(accounts, _)| {
+ accounts
+ .iter()
+ .map(|account| official_card_id(&account.id))
+ .collect()
+ })
+ .unwrap_or_default();
+ rows.retain(|id, provider| !is_official(provider) || visible.contains(id));
+ rows
+}
+
+/// 授权中心删号时连同它的官方卡一起删。
+pub(crate) fn forget_official_card(state: &AppState, account_id: &str) {
+ let _guard = lock(state);
+ if let Err(error) = state
+ .db
+ .delete_provider(&APP, &official_card_id(account_id))
+ {
+ log::warn!("删除 Qoder 账号卡片失败: {error}");
+ }
+}
diff --git a/src-tauri/src/services/provider/usage.rs b/src-tauri/src/services/provider/usage.rs
index bb55c9ca6..c78ddc9bf 100644
--- a/src-tauri/src/services/provider/usage.rs
+++ b/src-tauri/src/services/provider/usage.rs
@@ -129,25 +129,28 @@ fn resolve_script_credentials(
(api_key, base_url)
}
-/// Qoder 的卡片在它自己的 settings.json 里,库里只存用量脚本;其余应用直接读供应商表。
fn load_usage_provider(
state: &AppState,
app_type: &AppType,
provider_id: &str,
) -> Result<Option<crate::provider::Provider>, AppError> {
- if matches!(app_type, AppType::Qoder) {
- return crate::qoder_models::usage_provider(
- &state.db,
- crate::qoder_config::current_edition(),
- provider_id,
- )
- .map(Some);
- }
- Ok(state
+ let mut provider = state
.db
.get_provider_rows(app_type)?
.get(provider_id)?
- .cloned())
+ .cloned();
+ // Qoder 的地址和 Key 以 settings.json 为准:在 Qoder 里改过之后,不等刷新列表也按新的查。
+ if matches!(app_type, AppType::Qoder) {
+ if let Some(provider) = provider.as_mut() {
+ if let Some(native) =
+ crate::qoder_models::providers(crate::qoder_config::current_edition())?
+ .shift_remove(provider_id)
+ {
+ provider.settings_config = native;
+ }
+ }
+ }
+ Ok(provider)
}
/// Query provider usage (using saved script configuration)
diff --git a/src-tauri/src/services/session_usage_qoder.rs b/src-tauri/src/services/session_usage_qoder.rs
index 641aafd23..6fc64b4a2 100644
--- a/src-tauri/src/services/session_usage_qoder.rs
+++ b/src-tauri/src/services/session_usage_qoder.rs
@@ -39,8 +39,8 @@ pub fn sync_qoder_usage(
if !root.is_dir() {
continue;
}
- let providers = match crate::qoder_models::get(edition) {
- Ok(models) => models.providers,
+ let providers = match crate::qoder_models::providers(edition) {
+ Ok(providers) => providers.into_iter().collect::<serde_json::Map<_, _>>(),
Err(error) => {
result
.errors
diff --git a/src-tauri/src/services/stream_check.rs b/src-tauri/src/services/stream_check.rs
index 0f2c61aa7..b270c73b8 100644
--- a/src-tauri/src/services/stream_check.rs
+++ b/src-tauri/src/services/stream_check.rs
@@ -201,6 +201,15 @@ impl StreamCheckService {
.ok_or_else(|| {
AppError::Message("ZCode provider is missing options.baseURL".into())
}),
+ // Qoder 的卡片就是 settings.json 里 providers 的一条(顶层 baseUrl)
+ AppType::Qoder => provider
+ .settings_config
+ .get("baseUrl")
+ .and_then(|v| v.as_str())
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(|s| s.trim_end_matches('/').to_string())
+ .ok_or_else(|| AppError::Message("Qoder provider is missing baseUrl".into())),
AppType::ClaudeDesktop => ClaudeAdapter::new()
.extract_base_url(provider)
.map_err(|e| AppError::Message(format!("Failed to extract base_url: {e}"))),
@@ -730,6 +739,15 @@ mod tests {
);
let login = make_provider(serde_json::json!({ "env": { "COPILOT_MODEL": "auto" } }));
assert!(StreamCheckService::resolve_base_url(&AppType::Copilot, &login).is_err());
+
+ let qoder = make_provider(serde_json::json!({
+ "baseUrl": "https://api.example.com/v1/",
+ "apiKey": "${KEY}"
+ }));
+ assert_eq!(
+ StreamCheckService::resolve_base_url(&AppType::Qoder, &qoder).unwrap(),
+ "https://api.example.com/v1"
+ );
}
#[tokio::test]
diff --git a/src-tauri/src/tray.rs b/src-tauri/src/tray.rs
index 129abed8a..e5ac4d133 100644
--- a/src-tauri/src/tray.rs
+++ b/src-tauri/src/tray.rs
@@ -38,14 +38,8 @@ pub const TRAY_ID: &str = "cc-switch";
/// 进托盘的应用,顺序默认和侧栏一致(`APP_IDS`);实际显示哪些、什么顺序看
/// [`shown_tray_apps`]。累加式应用没有「当前供应商」,子菜单见 [`TrayMode::Additive`];
/// Antigravity 沿用供应商卡片切换。
-/// Qoder 不进托盘:它的模型在自己的 settings.json 里、由 Qoder 页管理,库里只有用量脚本,
-/// 托盘没有可切换的卡片。
-pub static TRAY_APPS: std::sync::LazyLock<Vec<AppType>> = std::sync::LazyLock::new(|| {
- AppType::ALL
- .into_iter()
- .filter(|app| *app != AppType::Qoder)
- .collect()
-});
+pub static TRAY_APPS: std::sync::LazyLock<Vec<AppType>> =
+ std::sync::LazyLock::new(|| AppType::ALL.into_iter().collect());
/// 托盘实际显示的应用:应用页里没隐藏的,按应用页排的顺序(`appOrder`)。
fn shown_tray_apps(settings: &crate::settings::AppSettings) -> Vec<AppType> {
@@ -204,7 +198,7 @@ fn map_locale_to_tray_language(locale: &str) -> &'static str {
}
/// 读取系统区域并映射为托盘语言码;取不到区域时回退到 `zh`。
-fn detect_system_tray_language() -> &'static str {
+pub(crate) fn detect_system_tray_language() -> &'static str {
sys_locale::get_locale()
.as_deref()
.map(map_locale_to_tray_language)
@@ -1840,6 +1834,8 @@ fn provider_opens_app(app: &AppType, provider: &Provider) -> bool {
}
AppType::WorkBuddy => crate::workbuddy_config::is_official_provider(provider),
AppType::Codebuddy => crate::codebuddy_config::is_official_provider(provider),
+ // Qoder 官方账号卡:换号要经授权中心,点了跳到应用页
+ AppType::Qoder => crate::services::provider::qoder::is_official(provider),
_ => false,
}
}
@@ -1883,6 +1879,9 @@ fn added_provider_ids(
}
AppType::ZCode => crate::zcode_config::get_providers()
.map(|providers| providers.keys().cloned().collect()),
+ // 两个版本共用卡片,按当前版本的 settings.json 现算
+ AppType::Qoder => crate::qoder_models::providers(crate::qoder_config::current_edition())
+ .map(|providers| providers.keys().cloned().collect()),
// 原生配置应用:标记跟着写入一起提交,不用读客户端文件。
_ => Ok(rows
.values()
@@ -1943,6 +1942,12 @@ fn collect_app_snapshot(
) -> Result<AppSnapshot, AppError> {
// 读不出来的行不进托盘(没有能切换的内容),也不拖垮整个菜单。
let rows = app_state.db.get_provider_rows(app)?.readable;
+ // 另一个版本收录的 Qoder 账号卡不显示(同主界面)
+ let rows = if *app == AppType::Qoder {
+ crate::services::provider::qoder::without_hidden_accounts(rows)
+ } else {
+ rows
+ };
let providers: Vec<ProviderEntry> = sort_providers(&rows)
.into_iter()
.map(|(_, provider)| provider_entry(app, provider, accounts))
diff --git a/src-tauri/src/tray/tests.rs b/src-tauri/src/tray/tests.rs
index 48da13060..70f605175 100644
--- a/src-tauri/src/tray/tests.rs
+++ b/src-tauri/src/tray/tests.rs
@@ -150,14 +150,11 @@ fn tray_lists_every_app_in_sidebar_order() {
"WorkBuddy",
"CodeBuddy",
"ZCode",
+ "Qoder CLI",
]
);
- // 新应用接进来时别再漏掉托盘。Qoder 是唯一的例外:它没有可在托盘切换的卡片。
- let all: Vec<AppType> = AppType::all().collect();
- assert!(all
- .iter()
- .all(|app| *app == AppType::Qoder || TRAY_APPS.contains(app)));
- assert!(!TRAY_APPS.contains(&AppType::Qoder));
+ // 新应用接进来时别再漏掉托盘。
+ assert!(AppType::all().all(|app| TRAY_APPS.contains(&app)));
}
#[test]
@@ -3106,6 +3103,7 @@ fn shown_tray_apps_follow_app_page_order_and_visibility() {
AppType::WorkBuddy,
AppType::Codebuddy,
AppType::ZCode,
+ AppType::Qoder,
AppType::Codex,
AppType::Gemini,
AppType::GrokBuild,
diff --git a/src-tauri/tests/integration/qoder_commands.rs b/src-tauri/tests/integration/qoder_commands.rs
index 0d325ae79..3b8002e4e 100644
--- a/src-tauri/tests/integration/qoder_commands.rs
+++ b/src-tauri/tests/integration/qoder_commands.rs
@@ -182,27 +182,19 @@ fn qoder_usage_metadata_stays_out_of_native_credentials() {
}
let before = fs::read(homes.settings("cn")).unwrap();
let script = serde_json::from_value(json!({"enabled":true,"language":"javascript","code":"({request:{url:'{{baseUrl}}/usage',method:'GET',headers:{Authorization:'Bearer {{apiKey}}'}},extractor:function(r){return r}})","autoQueryInterval":15})).unwrap();
- let models = cc_switch_lib::qoder_models::save_usage_script(
- &state.db,
- QoderEdition::Cn,
- "native",
- script,
- )
- .unwrap();
- assert!(
- models.metadata["native"]
- .usage_script
- .as_ref()
- .unwrap()
- .enabled
- );
+ // 打开列表时把 settings.json 里已有的供应商导入成卡片
+ let mut card = ProviderService::list(&state, AppType::Qoder).unwrap()["native"].clone();
+ card.meta.get_or_insert_with(Default::default).usage_script = Some(script);
+ ProviderService::update(&state, AppType::Qoder, None, card).unwrap();
+ // 只存用量脚本不碰 Qoder 的文件
assert_eq!(fs::read(homes.settings("cn")).unwrap(), before);
let stored = state
.db
.get_provider_by_id("native", &AppType::Qoder)
.unwrap()
.unwrap();
- assert_eq!(stored.settings_config, json!({}));
+ assert!(stored.meta.unwrap().usage_script.unwrap().enabled);
+ assert_eq!(stored.settings_config, native["providers"]["native"]);
assert_eq!(read(&homes.settings("global")), native);
// Query against a local fixture after credentials change outside CC Switch.
let listener = TcpListener::bind("localhost:0").unwrap();
@@ -334,61 +326,68 @@ fn qoder_skills_follow_the_selected_edition_and_preserve_native_skills() {
}
#[test]
-fn qoder_model_management_configures_each_edition_and_leaves_privacy_alone() {
- use cc_switch_lib::qoder_models;
+fn qoder_provider_cards_add_per_edition_and_leave_privacy_alone() {
let _guard = test_mutex().lock().unwrap();
reset_test_fs();
let homes = QoderHomes::new();
- let provider = json!({"displayName":"Custom","baseUrl":"https://example.test/v1","apiKey":"test-key","protocol":"anthropic","authType":"api-key","models":[{"model":"custom-model","contextWindow":200000,"maxOutputTokens":8192}],"model":"custom-model"});
- assert!(qoder_models::get(QoderEdition::Global)
+ let state = create_test_state().unwrap();
+ select_edition(QoderEdition::Global);
+ let config = json!({"displayName":"Custom","baseUrl":"https://example.test/v1","apiKey":"test-key","protocol":"anthropic","authType":"api-key","models":[{"model":"custom-model","contextWindow":200000,"maxOutputTokens":8192},{"model":"second"}],"model":"custom-model"});
+ let provider = Provider::with_id("custom".into(), "Custom".into(), config.clone(), None);
+ assert!(ProviderService::list(&state, AppType::Qoder)
.unwrap()
- .providers
.is_empty());
assert!(
!homes.settings("global").exists(),
"reading must not create settings"
);
- qoder_models::save_provider(QoderEdition::Global, "custom", provider.clone(), None, true)
- .unwrap();
- // 用户在 Qoder 里的隐私选择归 Qoder 自己,CC Switch 不改。
- assert!(read(&homes.settings("global")).get("privacy").is_none());
+ // 「添加」写进国际版,不改默认模型;用户在 Qoder 里的隐私选择不动
+ ProviderService::add(&state, AppType::Qoder, provider, true).unwrap();
+ let global = read(&homes.settings("global"));
+ assert_eq!(global["providers"]["custom"], config);
+ assert!(global.get("model").is_none());
+ assert!(global.get("privacy").is_none());
assert_eq!(
- qoder_models::get(QoderEdition::Global)
- .unwrap()
- .current_model,
- "custom/custom-model"
+ ProviderService::current(&state, AppType::Qoder).unwrap(),
+ ""
+ );
+
+ // 设为默认:连模型一起选
+ ProviderService::set_qoder_default(&state, "custom", Some("second")).unwrap();
+ assert_eq!(
+ read(&homes.settings("global"))["model"]["name"],
+ "custom/second"
);
- assert!(qoder_models::get(QoderEdition::Cn)
- .unwrap()
- .providers
- .is_empty());
- qoder_models::save_provider(QoderEdition::Cn, "custom", provider.clone(), None, false).unwrap();
- for folder in ["global", "cn"] {
- let mut settings = read(&homes.settings(folder));
- settings["privacy"]["usageStatisticsEnabled"] = json!(true);
- settings["privacy"]["otherOption"] = json!("keep");
- fs::write(homes.settings(folder), settings.to_string()).unwrap();
- }
- qoder_models::set_model(QoderEdition::Cn, "custom/custom-model").unwrap();
- qoder_models::delete_provider(QoderEdition::Global, "custom", provider.clone()).unwrap();
- for folder in ["global", "cn"] {
- let settings = read(&homes.settings(folder));
- assert_eq!(settings["privacy"]["usageStatisticsEnabled"], true);
- assert_eq!(settings["privacy"]["otherOption"], "keep");
- }
assert_eq!(
- qoder_models::get(QoderEdition::Global)
- .unwrap()
- .current_model,
- "auto"
+ ProviderService::current(&state, AppType::Qoder).unwrap(),
+ "custom"
);
- assert!(qoder_models::get(QoderEdition::Global)
+ // 默认那家不能移除
+ assert!(ProviderService::remove_from_live_config(&state, AppType::Qoder, "custom").is_err());
+
+ // 国内版共用同一批卡片:切过去后这张在「可添加」,文件里什么都没有
+ select_edition(QoderEdition::Cn);
+ let cards = ProviderService::list(&state, AppType::Qoder).unwrap();
+ assert_eq!(
+ cards["custom"].meta.as_ref().unwrap().live_config_managed,
+ Some(false)
+ );
+ assert!(!homes.settings("cn").exists());
+ ProviderService::add_to_live_config(&state, AppType::Qoder, "custom").unwrap();
+ let mut settings = read(&homes.settings("cn"));
+ assert_eq!(settings["providers"]["custom"], config);
+ settings["privacy"]["usageStatisticsEnabled"] = json!(true);
+ fs::write(homes.settings("cn"), settings.to_string()).unwrap();
+ ProviderService::remove_from_live_config(&state, AppType::Qoder, "custom").unwrap();
+ let settings = read(&homes.settings("cn"));
+ assert!(settings["providers"].get("custom").is_none());
+ assert_eq!(settings["privacy"]["usageStatisticsEnabled"], true);
+ // 卡片留着,国际版的配置也没动
+ assert!(ProviderService::list(&state, AppType::Qoder)
.unwrap()
- .providers
- .is_empty());
+ .contains_key("custom"));
assert_eq!(
- qoder_models::get(QoderEdition::Cn).unwrap().current_model,
- "custom/custom-model"
+ read(&homes.settings("global"))["providers"]["custom"],
+ config
);
- assert_eq!(read(&homes.settings("cn"))["providers"]["custom"], provider);
}
diff --git a/src/App.tsx b/src/App.tsx
index ed974b553..5db84772c 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -11,7 +11,6 @@ import {
import { useTranslation } from "react-i18next";
import { toast } from "@/lib/toast";
import { invoke } from "@tauri-apps/api/core";
-import { QoderPanel } from "@/components/providers/QoderPanel";
import { useQueryClient } from "@tanstack/react-query";
import {
ExternalLink,
@@ -263,10 +262,6 @@ function App() {
const [providerSearchOpen, setProviderSearchOpen] = useState(false);
const [connectionStatusSlot, setConnectionStatusSlot] =
useState<HTMLDivElement | null>(null);
- // Qoder 的模型卡在它自己的 settings.json 里,由 QoderPanel 管;页头按钮渲染到这里
- const [qoderActionSlot, setQoderActionSlot] = useState<HTMLDivElement | null>(
- null,
- );
const isQoder = activeApp === "qoder";
useEffect(() => {
setProviderSearchOpen(false);
@@ -412,7 +407,6 @@ function App() {
const currentModeView =
providerModeView?.app === activeApp ? providerModeView.view : undefined;
const openAddProvider = (modeView: AppMode | undefined) => {
- if (activeApp === "qoder") return;
setFormModeView(modeView);
setIsAddOpen(true);
};
@@ -479,7 +473,7 @@ function App() {
// Copilot CLI 的自带模型卡同理:「添加」只写进 providers.json,默认模型在 copilot 里用 /model 选
const handleAddNativeProvider = async (
provider: Provider,
- app: "kimi" | "copilot",
+ app: "kimi" | "copilot" | "qoder",
) => {
try {
await providersApi.addToLiveConfig(provider.id, app);
@@ -1580,7 +1574,6 @@ function App() {
</Button>
)}
{currentView === "providers" &&
- !isQoder &&
(settingsData?.showProviderSearch ?? true) && (
<HoverTip
content={t("provider.searchButtonTip", {
@@ -1599,7 +1592,7 @@ function App() {
</Button>
</HoverTip>
)}
- {currentView === "providers" && !isQoder && (
+ {currentView === "providers" && (
<Button
variant="solid"
size="regular"
@@ -1610,9 +1603,6 @@ function App() {
{t("provider.addProvider")}
</Button>
)}
- {currentView === "providers" && isQoder && (
- <div ref={setQoderActionSlot} className="flex items-center gap-2" />
- )}
{currentView === "hermesMemory" && (
<Suspense fallback={null}>
<HermesMemorySaveButton />
@@ -1685,7 +1675,6 @@ function App() {
};
const renderProviderList = () => {
- if (isQoder) return <QoderPanel actionSlot={qoderActionSlot} />;
if (modeAppId) {
const startupFailure = startupFailures.find(
(failure) => failure.appType === modeAppId,
@@ -1733,7 +1722,9 @@ function App() {
onSwitch={(provider) =>
void (appHas(activeApp, "piFamily")
? handleEnablePiProvider(provider, activeApp)
- : activeApp === "kimi" || activeApp === "copilot"
+ : activeApp === "kimi" ||
+ activeApp === "copilot" ||
+ activeApp === "qoder"
? handleAddNativeProvider(provider, activeApp)
: switchProvider(provider))
}
@@ -1749,7 +1740,9 @@ function App() {
activeApp === "opencode" ? handleDisableOmoSlim : undefined
}
onSetAsDefault={
- activeApp === "openclaw" || activeApp === "opencode"
+ activeApp === "openclaw" ||
+ activeApp === "opencode" ||
+ activeApp === "qoder"
? (provider, modelId) =>
void setAsDefaultModel(provider, modelId)
: activeApp === "hermes" || activeApp === "kimi"
diff --git a/src/components/providers/AddProviderDialog.tsx b/src/components/providers/AddProviderDialog.tsx
index 69f8a956a..e03065528 100644
--- a/src/components/providers/AddProviderDialog.tsx
+++ b/src/components/providers/AddProviderDialog.tsx
@@ -73,6 +73,7 @@ export function AddProviderDialog({
appId !== "mcode" &&
appId !== "dsh" &&
appId !== "kimi" &&
+ appId !== "qoder" &&
appId !== "copilot" &&
appId !== "workbuddy" &&
appId !== "codebuddy" &&
diff --git a/src/components/providers/EditProviderDialog.tsx b/src/components/providers/EditProviderDialog.tsx
index 5aef61ed0..d5ac25757 100644
--- a/src/components/providers/EditProviderDialog.tsx
+++ b/src/components/providers/EditProviderDialog.tsx
@@ -248,6 +248,7 @@ export function EditProviderDialog({
appId === "pi" ||
appId === "mcode" ||
appId === "kimi" ||
+ appId === "qoder" ||
appId === "dsh" ||
appId === "omp" ||
appId === "copilot" ||
diff --git a/src/components/providers/ProviderCard.tsx b/src/components/providers/ProviderCard.tsx
index 43094aed2..45859be3a 100644
--- a/src/components/providers/ProviderCard.tsx
+++ b/src/components/providers/ProviderCard.tsx
@@ -760,7 +760,7 @@ export function ProviderCard({
// CodeBuddy 的卡片 ID 就是 models.json 里的模型 id(发给上游的模型名),副本只能换一个
// 不存在的 id 且编辑时改不了;官方登录卡另建即可,所以 CodeBuddy 不提供复制
onDuplicate &&
- !(appId === "kimi" && isOfficial) &&
+ !((appId === "kimi" || appId === "qoder") && isOfficial) &&
appId !== "codebuddy"
? () => onDuplicate(provider)
: undefined
diff --git a/src/components/providers/ProviderEmptyState.tsx b/src/components/providers/ProviderEmptyState.tsx
index 81171f05a..194926aab 100644
--- a/src/components/providers/ProviderEmptyState.tsx
+++ b/src/components/providers/ProviderEmptyState.tsx
@@ -29,6 +29,7 @@ export function ProviderEmptyState({
appId === "mcode" ||
appId === "dsh" ||
appId === "kimi" ||
+ appId === "qoder" ||
appId === "omp" ||
appId === "workbuddy" ||
appId === "codebuddy"
diff --git a/src/components/providers/ProviderList.tsx b/src/components/providers/ProviderList.tsx
index 044d7159a..3459213c9 100644
--- a/src/components/providers/ProviderList.tsx
+++ b/src/components/providers/ProviderList.tsx
@@ -54,6 +54,7 @@ import { cn } from "@/lib/utils";
import { isTextEditableTarget } from "@/utils/domUtils";
import { extractProviderBaseUrl } from "@/utils/codexConfigUtils";
import { usePiCurrentState } from "@/lib/query/pi";
+import { useQoderOfficialCards } from "@/lib/query/qoder";
import { useCodebuddyOfficialCards } from "@/lib/query/codebuddy";
import { isOfficialAccount } from "@/utils/providerCapabilities";
import { isHermesReadOnlyProvider } from "@/config/hermesProviderMeta";
@@ -201,6 +202,14 @@ export function ProviderList({
);
const { state: codebuddyAccounts, switchAccount: switchCodebuddyAccount } =
useCodebuddyOfficialCards(hasCodebuddyOfficial);
+ // Qoder 官方账号卡:绑定的号是不是 Qoder 现在登着的号(决定「已添加 / 可添加」)、卡片上的「添加」
+ const hasQoderOfficial =
+ appId === "qoder" &&
+ Object.values(providers).some(
+ (provider) => provider.category === "official",
+ );
+ const { state: qoderAccounts, switchAccount: switchQoderAccount } =
+ useQoderOfficialCards(hasQoderOfficial);
// 累加式应用要等 live 里有哪些供应商读回来(成功或失败)才知道卡片该进哪个分区;
// 在那之前按加载中画骨架,不然卡片先全落进「可添加」,读回来再整体搬到「已添加」。
// 一张卡都没有时不用等,直接出空状态
@@ -215,6 +224,7 @@ export function ProviderList({
(provider: Provider): boolean => {
switch (appId) {
case "kimi":
+ case "qoder":
case "dsh":
case "mcode":
case "codebuddy":
@@ -481,6 +491,8 @@ export function ProviderList({
workbuddyOfficial,
codebuddyAccounts,
copilotDefaultId: appId === "copilot" ? currentProviderId : null,
+ qoderCurrentId: appId === "qoder" ? currentProviderId : null,
+ qoderAccounts,
extraAdded: showDshAccountCard ? 1 : 0,
actions: {
add: onSwitch,
@@ -496,7 +508,9 @@ export function ProviderList({
switchAccount: (provider) =>
appId === "codebuddy"
? switchCodebuddyAccount(provider)
- : void switchWorkBuddyAccount(provider),
+ : appId === "qoder"
+ ? switchQoderAccount(provider)
+ : void switchWorkBuddyAccount(provider),
openTerminal: (provider) => onOpenTerminal?.(provider),
},
});
@@ -520,6 +534,8 @@ export function ProviderList({
currentProviderId,
codebuddyAccounts,
switchCodebuddyAccount,
+ qoderAccounts,
+ switchQoderAccount,
showDshAccountCard,
onRemoveFromConfig,
onDelete,
@@ -615,6 +631,7 @@ export function ProviderList({
appHas(appId, "piFamily") ||
appId === "mcode" ||
appId === "kimi" ||
+ appId === "qoder" ||
appId === "dsh" ||
appId === "workbuddy" ||
appId === "codebuddy"
diff --git a/src/components/providers/QoderAccountLogin.tsx b/src/components/providers/QoderAccountLogin.tsx
index fb763cf8a..3f45db285 100644
--- a/src/components/providers/QoderAccountLogin.tsx
+++ b/src/components/providers/QoderAccountLogin.tsx
@@ -8,6 +8,7 @@ import { settingsApi } from "@/lib/api";
import { qoderApi, qoderKeys, type QoderAccount } from "@/lib/api/qoder";
import type { QoderEdition } from "@/config/qoder";
import { extractErrorMessage } from "@/utils/errorUtils";
+import { deliverLoginLink } from "@/lib/authLoginLink";
import { ConfirmDialog } from "@/components/ConfirmDialog";
import { HoverTip } from "@/components/ui/hover-tip";
import { cn } from "@/lib/utils";
@@ -36,6 +37,9 @@ export function QoderAccountLogin({ edition }: { edition: QoderEdition }) {
const [removing, setRemoving] = useState(false);
const [deleteError, setDeleteError] = useState("");
const generation = useRef(0);
+ // 每个收录的账号在供应商页有一张官方卡,登录、切号、删号后卡片跟着变
+ const invalidateCards = () =>
+ queryClient.invalidateQueries({ queryKey: ["providers", app] });
const activeFlow = useRef<string | null>(null);
const openedFlow = useRef<string | null>(null);
const completedFlow = useRef<string | null>(null);
@@ -77,7 +81,8 @@ export function QoderAccountLogin({ edition }: { edition: QoderEdition }) {
openedFlow.current !== flowId
) {
openedFlow.current = flowId;
- void openBrowser(result.authUrl);
+ // 和其他服务一样按授权中心「登录时自动打开浏览器」:关掉时只复制登录链接
+ void deliverLoginLink(result.authUrl, t);
}
if (result?.error || progress.error) {
setError(result?.error || extractErrorMessage(progress.error));
@@ -98,9 +103,7 @@ export function QoderAccountLogin({ edition }: { edition: QoderEdition }) {
const status = await qoderApi.getAuthStatus();
if (current !== generation.current) return;
queryClient.setQueryData(qoderKeys.auth(edition), status);
- await queryClient.invalidateQueries({
- queryKey: qoderKeys.models(edition),
- });
+ await invalidateCards();
if (
!status.accounts?.some((account) => account.id === result.accountId)
)
@@ -139,20 +142,14 @@ export function QoderAccountLogin({ edition }: { edition: QoderEdition }) {
}
};
- const select = async (accountId?: string) => {
+ const select = async (accountId: string) => {
if (working || removing) return;
setWorking(true);
setError("");
try {
- if (accountId) {
- const status = await qoderApi.useAccount(accountId);
- queryClient.setQueryData(qoderKeys.auth(edition), status);
- } else {
- await qoderApi.setModel("auto");
- }
- await queryClient.invalidateQueries({
- queryKey: qoderKeys.models(edition),
- });
+ const status = await qoderApi.useAccount(accountId);
+ queryClient.setQueryData(qoderKeys.auth(edition), status);
+ await invalidateCards();
} catch (cause) {
setError(extractErrorMessage(cause));
} finally {
@@ -167,9 +164,7 @@ export function QoderAccountLogin({ edition }: { edition: QoderEdition }) {
try {
const status = await qoderApi.deleteAccount(deleting.id);
queryClient.setQueryData(qoderKeys.auth(edition), status);
- await queryClient.invalidateQueries({
- queryKey: qoderKeys.models(edition),
- });
+ await invalidateCards();
setDeleting(null);
} catch (cause) {
setDeleteError(extractErrorMessage(cause));
@@ -184,9 +179,7 @@ export function QoderAccountLogin({ edition }: { edition: QoderEdition }) {
try {
const status = await qoderApi.importCurrentAccount();
queryClient.setQueryData(qoderKeys.auth(edition), status);
- await queryClient.invalidateQueries({
- queryKey: qoderKeys.models(edition),
- });
+ await invalidateCards();
} catch (cause) {
setError(extractErrorMessage(cause));
} finally {
@@ -420,32 +413,16 @@ export function QoderAccountLogin({ edition }: { edition: QoderEdition }) {
)}
</Notice>
)}
- {((accounts.length === 0 && auth.data?.loggedIn && !uncollected) ||
- starting ||
- flowId) && (
+ {(starting || flowId) && (
<div className="flex gap-2">
- {accounts.length === 0 && auth.data?.loggedIn && !uncollected && (
- <Button
- type="button"
- variant="solid"
- size="regular"
- disabled={working || removing || !auth.data?.installed}
- onClick={() => void select()}
- >
- {working && <Loader2 className="h-4 w-4 animate-spin" />}
- {t("qoder.useAccount")}
- </Button>
- )}
- {(starting || flowId) && (
- <Button
- type="button"
- variant="neutral"
- size="regular"
- onClick={() => void cancel()}
- >
- {t("common.cancel")}
- </Button>
- )}
+ <Button
+ type="button"
+ variant="neutral"
+ size="regular"
+ onClick={() => void cancel()}
+ >
+ {t("common.cancel")}
+ </Button>
</div>
)}
<ConfirmDialog
diff --git a/src/components/providers/QoderPanel.tsx b/src/components/providers/QoderPanel.tsx
deleted file mode 100644
index 3ae5ede21..000000000
--- a/src/components/providers/QoderPanel.tsx
+++ /dev/null
@@ -1,448 +0,0 @@
-import { useState } from "react";
-import { createPortal } from "react-dom";
-import { useTranslation } from "react-i18next";
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { Loader2, Plus, RefreshCw } from "lucide-react";
-import { Button } from "@/components/ui/button";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import {
- qoderApi,
- qoderKeys,
- type QoderModels,
- type QoderProvider,
-} from "@/lib/api/qoder";
-import { toast } from "@/lib/toast";
-import { extractErrorMessage } from "@/utils/errorUtils";
-import { QoderProviderDialog } from "./QoderProviderDialog";
-import { ProviderEmptyState } from "./ProviderEmptyState";
-import { ProviderCard } from "./ProviderCard";
-import type { CardPresentation } from "./presentation";
-import { settingsApi } from "@/lib/api";
-import UsageScriptModal from "@/components/UsageScriptModal";
-import type { Provider } from "@/types";
-import { APP_DISPLAY_NAME } from "@/components/shell/AppGlyph";
-import { AuthSettingsPanel } from "./AuthSettingsPanel";
-import type { AuthCenterTarget } from "@/lib/api";
-import { useQoderEdition } from "@/hooks/useQoderEdition";
-import type { QoderEdition } from "@/config/qoder";
-
-/** Qoder 的模型卡:读写设置里选的那个版本的 settings.json。 */
-export function QoderPanel({
- actionSlot,
-}: {
- actionSlot?: HTMLElement | null;
-}) {
- const edition = useQoderEdition();
- // 等设置读到再查:后端按已存的版本作答,换版本时整块重新挂载。
- return edition ? (
- <QoderEditionPanel
- key={edition}
- edition={edition}
- actionSlot={actionSlot}
- />
- ) : null;
-}
-
-function QoderEditionPanel({
- edition,
- actionSlot,
-}: {
- edition: QoderEdition;
- actionSlot?: HTMLElement | null;
-}) {
- const { t } = useTranslation();
- const app = "qoder" as const;
- const queryClient = useQueryClient();
- const query = useQuery({
- queryKey: qoderKeys.models(edition),
- queryFn: () => qoderApi.getModels(),
- });
- const auth = useQuery({
- queryKey: qoderKeys.auth(edition),
- queryFn: () => qoderApi.getAuthStatus(),
- retry: false,
- staleTime: 30_000,
- });
- const [editing, setEditing] = useState<{
- id?: string;
- provider?: QoderProvider;
- } | null>(null);
- const [authTarget, setAuthTarget] = useState<AuthCenterTarget | null>(null);
- const [deleting, setDeleting] = useState<{
- id: string;
- provider: QoderProvider;
- } | null>(null);
- const mutation = useMutation({
- mutationFn: (operation: () => Promise<QoderModels>) => operation(),
- onSuccess: (models) => {
- queryClient.setQueryData(qoderKeys.models(edition), models);
- toast.success(t("qoder.saved"));
- },
- });
- const [usageProvider, setUsageProvider] = useState<Provider | null>(null);
- const run = (operation: () => Promise<QoderModels>) =>
- mutation.mutateAsync(operation);
- const runAction = async (operation: () => Promise<QoderModels>) => {
- try {
- await run(operation);
- } catch (error) {
- toast.error(extractErrorMessage(error));
- }
- };
- const providers = query.data?.providers ?? {};
- const current = query.data?.currentModel ?? "auto";
- const models = Object.entries(providers).flatMap(([id, provider]) => {
- const declared = provider.models?.length
- ? [...provider.models]
- : provider.model
- ? [{ model: provider.model }]
- : [];
- if (
- provider.model &&
- !declared.some((model) => model.model === provider.model)
- )
- declared.push({ model: provider.model });
- return declared.map((model) => ({
- key: `${id}/${model.model}`,
- provider: id,
- name: model.displayName || model.model,
- }));
- });
- const busy = mutation.isPending;
- const importCurrent = async () => {
- const [result, account] = await Promise.all([
- query.refetch(),
- auth.refetch(),
- ]);
- if (result.error) {
- toast.error(extractErrorMessage(result.error));
- return;
- }
- toast.info(
- t(
- Object.keys(result.data?.providers ?? {}).length ||
- account.data?.loggedIn
- ? "qoder.imported"
- : "qoder.nothingToImport",
- ),
- );
- };
- const actions = (
- <>
- <Button
- variant="quiet"
- size="icon-compact"
- disabled={query.isFetching || auth.isFetching || busy}
- aria-label={t("common.refresh")}
- onClick={() => void Promise.all([query.refetch(), auth.refetch()])}
- >
- <RefreshCw
- className={
- query.isFetching || auth.isFetching
- ? "h-4 w-4 animate-spin"
- : "h-4 w-4"
- }
- />
- </Button>
- <Button
- variant="solid"
- size="regular"
- data-tour="add-provider"
- disabled={!query.data || busy}
- onClick={() => setEditing({})}
- >
- <Plus className="h-4 w-4" />
- {t("provider.addProvider")}
- </Button>
- </>
- );
- return (
- <div
- id="main-content"
- className="min-h-0 flex-1 overflow-y-auto scroll-stable px-6 pb-12 pt-4"
- >
- {actionSlot ? (
- createPortal(actions, actionSlot)
- ) : actionSlot === undefined ? (
- <div className="mb-4 flex justify-end gap-2">{actions}</div>
- ) : null}
- <div className="space-y-4">
- {query.isLoading && (
- <Loader2
- role="status"
- aria-label={t("common.loading")}
- className="h-5 w-5 animate-spin text-fg-2"
- />
- )}
- {query.isError && (
- <p role="alert" className="text-body text-danger-text">
- {extractErrorMessage(query.error)}
- </p>
- )}
- {query.data && (
- <>
- {Object.keys(providers).length === 0 && !auth.data?.loggedIn && (
- <ProviderEmptyState
- appId={app}
- onCreate={() => setEditing({})}
- onImport={() => void importCurrent()}
- />
- )}
- {auth.data?.loggedIn &&
- (() => {
- const active = !Object.keys(providers).some((id) =>
- current.startsWith(`${id}/`),
- );
- const websiteUrl =
- edition === "cn"
- ? "https://qoder.com.cn"
- : "https://qoder.com";
- return (
- <ProviderCard
- provider={{
- id: "_qoder_official",
- name:
- edition === "cn"
- ? `${APP_DISPLAY_NAME[app]} CN`
- : APP_DISPLAY_NAME[app],
- category: "official",
- icon: "qoder",
- settingsConfig: {},
- notes: [
- auth.data.email || auth.data.username,
- auth.data.plan,
- ]
- .filter(Boolean)
- .join(" · "),
- websiteUrl,
- }}
- appId={app}
- isCurrent={active}
- presentation={{
- tone: active ? "direct" : undefined,
- status: active
- ? {
- label: t("providerCard.status.inUse"),
- dot: "direct",
- }
- : undefined,
- chips: [
- {
- key: "official",
- label: t("providerCard.chip.official"),
- tone: "outline",
- },
- ],
- buttons: active
- ? []
- : [
- {
- key: "switch",
- label: t("providerCard.action.switch"),
- onClick: () =>
- void runAction(() => qoderApi.setModel("auto")),
- disabledReason: busy
- ? t("common.loading")
- : undefined,
- },
- ],
- editDisabledReason: busy
- ? t("common.loading")
- : undefined,
- deleteDisabledReason: t("qoder.accountManagedByQoder"),
- }}
- onEdit={() => setAuthTarget("qoder_oauth")}
- onDelete={() => {}}
- onOpenWebsite={(url) => void settingsApi.openExternal(url)}
- />
- );
- })()}
- {Object.entries(providers).map(([id, provider]) => {
- const providerModels = models.filter(
- (model) => model.provider === id,
- );
- const active = current.startsWith(`${id}/`);
- const defaultModel = provider.model
- ? `${id}/${provider.model}`
- : providerModels[0]?.key;
- const buttons: CardPresentation["buttons"] = [];
- const menuItems: CardPresentation["menuItems"] = [];
- if (!active) {
- buttons.push({
- key: "switch",
- label: t("providerCard.action.switch"),
- onClick: () => {
- if (defaultModel)
- void runAction(() => qoderApi.setModel(defaultModel));
- },
- disabledReason: busy
- ? t("common.loading")
- : !defaultModel
- ? t("providerCard.chip.noModels")
- : undefined,
- });
- }
- if (providerModels.length) {
- menuItems.push({
- key: "setDefault",
- label: t("qoder.selectModelAction"),
- onSelect: () => {},
- disabledReason: busy ? t("common.loading") : undefined,
- submenu: {
- title: t("qoder.selectModelAction"),
- options: providerModels.map((model) => ({
- key: model.key,
- label: model.name,
- detail: model.key,
- onSelect: () =>
- void runAction(() => qoderApi.setModel(model.key)),
- })),
- },
- });
- }
- if (active) {
- menuItems.push({
- key: "autoModel",
- label: t("qoder.autoModel"),
- disabledReason: busy ? t("common.loading") : undefined,
- onSelect: () =>
- void runAction(() => qoderApi.setModel("auto")),
- });
- }
- const presentation: CardPresentation = {
- tone: active ? "direct" : undefined,
- status: active
- ? { label: t("providerCard.status.inUse"), dot: "direct" }
- : undefined,
- chips: [
- {
- key: "protocol",
- label: provider.protocol || "openai",
- tone: "outline",
- },
- ],
- buttons,
- editDisabledReason: busy ? t("common.loading") : undefined,
- deleteDisabledReason: busy ? t("common.loading") : undefined,
- menuItems,
- };
- return (
- <ProviderCard
- key={id}
- provider={{
- id,
- name: provider.displayName || id,
- settingsConfig: provider,
- icon: "qoder",
- category: "custom",
- meta: query.data?.metadata?.[id],
- }}
- appId={app}
- isCurrent={active}
- onConfigureUsage={setUsageProvider}
- presentation={presentation}
- onEdit={() => {
- if (!busy) setEditing({ id, provider });
- }}
- onDelete={() => {
- if (!busy) setDeleting({ id, provider });
- }}
- onOpenWebsite={(url) => void settingsApi.openExternal(url)}
- />
- );
- })}
- </>
- )}
- </div>
- {usageProvider && (
- <UsageScriptModal
- provider={usageProvider}
- appId={app}
- isOpen
- onClose={() => setUsageProvider(null)}
- onSave={(script) =>
- void runAction(() =>
- qoderApi.saveUsageScript(usageProvider.id, script),
- )
- }
- />
- )}
- {editing && (
- <QoderProviderDialog
- edition={edition}
- id={editing.id}
- provider={editing.provider}
- providers={providers}
- currentModel={current}
- onClose={() => setEditing(null)}
- onSave={async (id, provider, makeDefault) => {
- await run(() =>
- qoderApi.saveProvider(
- id,
- provider,
- editing.provider ?? null,
- makeDefault,
- ),
- );
- }}
- />
- )}
- <AuthSettingsPanel
- target={authTarget}
- onClose={() => setAuthTarget(null)}
- />
- <Dialog
- open={Boolean(deleting)}
- onOpenChange={(open) => {
- if (!open && !busy) setDeleting(null);
- }}
- >
- <DialogContent className="max-w-md">
- <DialogHeader>
- <DialogTitle>{t("qoder.deleteProviderTitle")}</DialogTitle>
- <DialogDescription>
- {t("qoder.deleteProviderDescription", {
- name: deleting?.provider.displayName || deleting?.id,
- })}
- </DialogDescription>
- </DialogHeader>
- <DialogFooter>
- <Button
- variant="neutral"
- size="regular"
- disabled={busy}
- onClick={() => setDeleting(null)}
- >
- {t("common.cancel")}
- </Button>
- <Button
- variant="destructive"
- size="regular"
- disabled={busy}
- onClick={async () => {
- if (!deleting) return;
- try {
- await run(() =>
- qoderApi.deleteProvider(deleting.id, deleting.provider),
- );
- setDeleting(null);
- } catch (error) {
- toast.error(extractErrorMessage(error));
- }
- }}
- >
- {t("common.delete")}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- </div>
- );
-}
diff --git a/src/components/providers/QoderProviderDialog.tsx b/src/components/providers/QoderProviderDialog.tsx
deleted file mode 100644
index cbcaa695c..000000000
--- a/src/components/providers/QoderProviderDialog.tsx
+++ /dev/null
@@ -1,632 +0,0 @@
-import { useMemo, useState } from "react";
-import { useTranslation } from "react-i18next";
-import { Loader2, Plus, Trash2 } from "lucide-react";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { Checkbox } from "@/components/ui/checkbox";
-import { FullScreenPanel } from "@/components/common/FullScreenPanel";
-import { APP_DISPLAY_NAME } from "@/components/shell/AppGlyph";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
-import type { QoderModel, QoderProvider } from "@/lib/api/qoder";
-import type { QoderEdition } from "@/config/qoder";
-import { extractErrorMessage } from "@/utils/errorUtils";
-import {
- qoderProviderPresets,
- qoderAccountPreset,
- QODER_ACCOUNT_PRESET_ID,
-} from "@/config/qoderProviderPresets";
-import { AuthSettingsPanel } from "./AuthSettingsPanel";
-import type { AuthCenterTarget } from "@/lib/api";
-import { ProviderPresetSelector } from "./forms/ProviderPresetSelector";
-import { PresetStepContext, type PresetStepState } from "./forms/presetStep";
-
-const PRESETS = qoderProviderPresets.map((preset) => ({
- id: preset.providerKey,
- preset,
-}));
-
-const newModel = (): QoderModel => ({
- model: "",
- capabilities: { tools: true, vision: false },
-});
-
-function formConfig(provider?: QoderProvider): QoderProvider {
- const initial: QoderProvider = provider ?? {
- type: "openai-compatible",
- protocol: "openai",
- authType: "bearer",
- baseUrl: "",
- apiKey: "",
- };
- const models = initial.models?.length
- ? [...initial.models]
- : initial.model
- ? [{ model: initial.model }]
- : [newModel()];
- if (initial.model && !models.some((model) => model.model === initial.model))
- models.push({ model: initial.model });
- return {
- ...initial,
- baseUrl: typeof initial.baseUrl === "string" ? initial.baseUrl : "",
- apiKey: typeof initial.apiKey === "string" ? initial.apiKey : "",
- models: structuredClone(models),
- };
-}
-
-export function QoderProviderDialog({
- edition,
- id: originalId,
- provider,
- providers,
- currentModel,
- onSave,
- onClose,
-}: {
- edition: QoderEdition;
- id?: string;
- provider?: QoderProvider;
- providers: Record<string, QoderProvider>;
- currentModel: string;
- onSave: (
- id: string,
- provider: QoderProvider,
- makeDefault: boolean,
- ) => Promise<void>;
- onClose: () => void;
-}) {
- const { t } = useTranslation();
- const app = "qoder" as const;
- const [step, setStep] = useState<"pick" | "form">(
- originalId ? "form" : "pick",
- );
- const [pickerHost, setPickerHost] = useState<HTMLDivElement | null>(null);
- const [authTarget, setAuthTarget] = useState<AuthCenterTarget | null>(null);
- const [presetId, setPresetId] = useState("custom");
- const isAccountLogin = !originalId && presetId === QODER_ACCOUNT_PRESET_ID;
- const presetEntries = useMemo(
- () => [
- { id: QODER_ACCOUNT_PRESET_ID, preset: qoderAccountPreset(edition) },
- ...PRESETS,
- ],
- [edition],
- );
- const stepState = useMemo<PresetStepState>(
- () => ({
- appId: app,
- step,
- setStep,
- host: pickerHost,
- // Qoder always supplies its selector; no selector-count fallback is needed.
- registerSelector: () => () => {},
- }),
- [step, pickerHost],
- );
- const [id, setId] = useState(originalId ?? "");
- const [config, setConfig] = useState<QoderProvider>(() =>
- formConfig(provider),
- );
- const [makeDefault, setMakeDefault] = useState(
- currentModel === "auto" ||
- Boolean(originalId && currentModel.startsWith(`${originalId}/`)),
- );
- const [busy, setBusy] = useState(false);
- const [error, setError] = useState("");
- const models = config.models ?? [];
- const update = (patch: Partial<QoderProvider>) =>
- setConfig((previous) => ({ ...previous, ...patch }));
- const updateModel = (index: number, patch: Partial<QoderModel>) =>
- update({
- models: models.map((model, position) =>
- position === index ? { ...model, ...patch } : model,
- ),
- });
- const duplicateId =
- !originalId && Object.prototype.hasOwnProperty.call(providers, id);
- const validId =
- /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(id) &&
- !["qoder", "constructor", "prototype"].includes(id);
- const validLimits = models.every((model) =>
- [model.contextWindow, model.maxOutputTokens].every(
- (value) =>
- value === undefined || (Number.isSafeInteger(value) && value > 0),
- ),
- );
- const ready =
- validId &&
- !duplicateId &&
- Boolean(config.baseUrl.trim()) &&
- models.length > 0 &&
- models.every((model) => model.model.trim()) &&
- new Set(models.map((model) => model.model.trim())).size === models.length &&
- validLimits;
- const submit = async (event: React.FormEvent) => {
- event.preventDefault();
- if (isAccountLogin || !ready || busy) return;
- setBusy(true);
- setError("");
- try {
- const cleaned = models.map((model) => ({
- ...model,
- model: model.model.trim(),
- }));
- const defaultModel = cleaned.some((model) => model.model === config.model)
- ? config.model
- : cleaned[0].model;
- await onSave(
- id,
- {
- ...config,
- baseUrl: config.baseUrl.trim(),
- model: defaultModel,
- models: cleaned,
- },
- makeDefault,
- );
- onClose();
- } catch (cause) {
- setError(extractErrorMessage(cause));
- } finally {
- setBusy(false);
- }
- };
- const canReturnToPicker = !originalId && step === "form";
- const close = () => {
- if (authTarget) {
- setAuthTarget(null);
- return;
- }
- if (busy) return;
- if (canReturnToPicker) setStep("pick");
- else onClose();
- };
- return (
- <FullScreenPanel
- isOpen
- trackUnsavedChanges={step === "form" && !isAccountLogin}
- title={t(
- originalId ? "qoder.editProviderTitle" : "provider.addNewProvider",
- )}
- subtitle={APP_DISPLAY_NAME[app]}
- backLabel={
- canReturnToPicker
- ? t("providerPreset.backToPick")
- : t("provider.backToList")
- }
- onClose={close}
- contentClassName={
- step === "pick" ? "flex h-full flex-col space-y-0 p-0" : "pt-4"
- }
- footer={
- step === "form" && !isAccountLogin ? (
- <>
- <Button
- type="button"
- variant="neutral"
- size="regular"
- disabled={busy}
- onClick={onClose}
- >
- {t("common.cancel")}
- </Button>
- <Button
- type="submit"
- form="qoder-provider-form"
- variant="solid"
- size="regular"
- disabled={!ready || busy}
- >
- {busy && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
- {t("common.save")}
- </Button>
- </>
- ) : null
- }
- >
- <PresetStepContext.Provider value={stepState}>
- {step === "pick" && (
- <div ref={setPickerHost} className="min-h-0 flex-1" />
- )}
- <div hidden={step === "pick"}>
- <form
- id="qoder-provider-form"
- aria-label={t("qoder.editProviderTitle")}
- onSubmit={(event) => void submit(event)}
- >
- {!originalId && (
- <ProviderPresetSelector
- selectedPresetId={presetId}
- presetEntries={presetEntries}
- onPresetChange={(selectedId) => {
- const preset = presetEntries.find(
- (entry) => entry.id === selectedId,
- )?.preset;
- setPresetId(selectedId);
- if (selectedId === QODER_ACCOUNT_PRESET_ID) return;
- setId(preset?.providerKey ?? "");
- setConfig(
- formConfig(
- preset
- ? {
- ...structuredClone(preset.settingsConfig),
- displayName: preset.nameKey
- ? t(preset.nameKey)
- : preset.name,
- }
- : undefined,
- ),
- );
- setError("");
- }}
- />
- )}
- {isAccountLogin ? (
- step === "form" && (
- <div className="mt-6 space-y-3">
- <p className="text-body text-fg-2">
- {t("qoder.loginDescription")}
- </p>
- <Button
- type="button"
- variant="neutral"
- onClick={() => setAuthTarget("qoder_oauth")}
- >
- {t("qoder.manageAccounts")}
- </Button>
- </div>
- )
- ) : (
- <fieldset
- disabled={busy}
- className={originalId ? "space-y-4" : "mt-6 space-y-4"}
- >
- <div className="grid grid-cols-2 gap-4">
- <div className="space-y-1.5">
- <Label htmlFor="qoder-provider-name">
- {t("qoder.providerName")}
- </Label>
- <Input
- id="qoder-provider-name"
- value={config.displayName ?? ""}
- onChange={(event) =>
- update({ displayName: event.target.value })
- }
- />
- </div>
- <div className="space-y-1.5">
- <Label htmlFor="qoder-provider-id">
- {t("qoder.providerId")}
- </Label>
- <Input
- id="qoder-provider-id"
- value={id}
- readOnly={Boolean(originalId)}
- onChange={(event) => setId(event.target.value)}
- placeholder="my-provider"
- aria-invalid={duplicateId || (id !== "" && !validId)}
- />
- {(duplicateId || (id !== "" && !validId)) && (
- <p className="text-caption text-danger-text">
- {t(
- duplicateId
- ? "qoder.duplicateProvider"
- : "qoder.invalidProviderId",
- )}
- </p>
- )}
- </div>
- </div>
- <div className="grid grid-cols-2 gap-4">
- <div className="space-y-1.5">
- <Label htmlFor="qoder-provider-protocol">
- {t("qoder.protocol")}
- </Label>
- <Select
- value={config.protocol ?? "openai"}
- onValueChange={(
- value: NonNullable<QoderProvider["protocol"]>,
- ) =>
- update({
- protocol: value,
- authType:
- value === "anthropic" ? "api-key" : "bearer",
- })
- }
- >
- <SelectTrigger id="qoder-provider-protocol">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="openai">
- OpenAI Chat Completions
- </SelectItem>
- <SelectItem value="openai-responses">
- OpenAI Responses
- </SelectItem>
- <SelectItem value="anthropic">
- Anthropic Messages
- </SelectItem>
- </SelectContent>
- </Select>
- </div>
- <div className="space-y-1.5">
- <Label htmlFor="qoder-provider-auth">
- {t("qoder.authType")}
- </Label>
- <Select
- value={config.authType ?? "bearer"}
- onValueChange={(
- value: NonNullable<QoderProvider["authType"]>,
- ) => update({ authType: value })}
- >
- <SelectTrigger id="qoder-provider-auth">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="bearer">Bearer Token</SelectItem>
- <SelectItem value="api-key">
- API Key (x-api-key)
- </SelectItem>
- </SelectContent>
- </Select>
- </div>
- </div>
- <div className="space-y-1.5">
- <Label htmlFor="qoder-provider-url">
- {t("qoder.baseUrl")}
- </Label>
- <Input
- id="qoder-provider-url"
- type="url"
- required
- value={config.baseUrl}
- onChange={(event) =>
- update({ baseUrl: event.target.value })
- }
- placeholder="https://api.example.com/v1"
- />
- </div>
- <div className="space-y-1.5">
- <Label htmlFor="qoder-provider-key">API Key</Label>
- <Input
- id="qoder-provider-key"
- type="password"
- autoComplete="new-password"
- value={config.apiKey}
- onChange={(event) => update({ apiKey: event.target.value })}
- />
- <p className="text-caption text-fg-2">
- {t("qoder.apiKeyHint")}
- </p>
- </div>
- <div className="flex items-center justify-between">
- <Label>{t("qoder.models")}</Label>
- <Button
- type="button"
- variant="neutral"
- size="compact"
- onClick={() => update({ models: [...models, newModel()] })}
- >
- <Plus className="h-3.5 w-3.5" />
- {t("qoder.addModel")}
- </Button>
- </div>
- {models.map((model, index) => {
- const thinking = model.capabilities?.thinking;
- const mode =
- thinking?.preferredMode ?? thinking?.modes?.[0] ?? "off";
- return (
- <div
- key={index}
- role="group"
- aria-label={t("qoder.modelNumber", { number: index + 1 })}
- className="space-y-3 rounded-control border border-border p-3"
- >
- <div className="flex items-end gap-3">
- <div className="min-w-0 flex-1 space-y-1.5">
- <Label htmlFor={`qoder-model-id-${index}`}>
- {t("qoder.modelId")}
- </Label>
- <Input
- id={`qoder-model-id-${index}`}
- required
- value={model.model}
- onChange={(event) =>
- updateModel(index, { model: event.target.value })
- }
- placeholder="model-id"
- />
- </div>
- <div className="min-w-0 flex-1 space-y-1.5">
- <Label htmlFor={`qoder-model-name-${index}`}>
- {t("qoder.modelName")}
- </Label>
- <Input
- id={`qoder-model-name-${index}`}
- value={model.displayName ?? ""}
- onChange={(event) =>
- updateModel(index, {
- displayName: event.target.value,
- })
- }
- />
- </div>
- <Button
- type="button"
- variant="quiet"
- size="icon-compact"
- disabled={models.length <= 1}
- aria-label={t("qoder.removeModel", {
- number: index + 1,
- })}
- onClick={() =>
- update({
- models: models.filter(
- (_, position) => position !== index,
- ),
- })
- }
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- </div>
- <div className="grid grid-cols-2 gap-3">
- {(["contextWindow", "maxOutputTokens"] as const).map(
- (field) => (
- <div key={field} className="space-y-1.5">
- <Label htmlFor={`qoder-${field}-${index}`}>
- {t(`qoder.${field}`)}
- </Label>
- <Input
- id={`qoder-${field}-${index}`}
- type="number"
- min={1}
- step={1}
- value={model[field] ?? ""}
- onChange={(event) =>
- updateModel(index, {
- [field]:
- event.target.value === ""
- ? undefined
- : Number(event.target.value),
- })
- }
- />
- </div>
- ),
- )}
- </div>
- <div className="flex flex-wrap items-center gap-4">
- {(["tools", "vision"] as const).map((field) => (
- <label
- key={field}
- className="inline-flex items-center gap-2 text-body"
- >
- <Checkbox
- checked={
- model.capabilities?.[field] ?? field === "tools"
- }
- onCheckedChange={(checked) =>
- updateModel(index, {
- capabilities: {
- ...model.capabilities,
- [field]: checked === true,
- },
- })
- }
- />
- {t(`qoder.${field}`)}
- </label>
- ))}
- <div className="flex items-center gap-2">
- <Label htmlFor={`qoder-thinking-${index}`}>
- {t("qoder.thinking")}
- </Label>
- <Select
- value={mode}
- onValueChange={(value) =>
- updateModel(index, {
- capabilities: {
- ...model.capabilities,
- thinking: {
- ...thinking,
- modes: value === "off" ? [] : [value],
- preferredMode:
- value === "off" ? undefined : value,
- requiresBudgetForEnabled:
- value === "enabled" ? true : undefined,
- },
- },
- })
- }
- >
- <SelectTrigger
- id={`qoder-thinking-${index}`}
- className="w-32"
- >
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="off">
- {t("qoder.thinkingOff")}
- </SelectItem>
- <SelectItem value="enabled">
- {t("qoder.thinkingEnabled")}
- </SelectItem>
- <SelectItem value="adaptive">
- {t("qoder.thinkingAdaptive")}
- </SelectItem>
- </SelectContent>
- </Select>
- </div>
- </div>
- </div>
- );
- })}
- <div className="space-y-1.5">
- <Label htmlFor="qoder-provider-default">
- {t("qoder.providerDefaultModel")}
- </Label>
- <Select
- value={
- config.model &&
- models.some((model) => model.model === config.model)
- ? config.model
- : models[0]?.model || ""
- }
- onValueChange={(model) => update({ model })}
- >
- <SelectTrigger id="qoder-provider-default">
- <SelectValue
- placeholder={t("qoder.selectModelPlaceholder")}
- />
- </SelectTrigger>
- <SelectContent>
- {models
- .filter(
- (model, index) =>
- model.model.trim() &&
- models.findIndex(
- (entry) => entry.model === model.model,
- ) === index,
- )
- .map((model, index) => (
- <SelectItem key={index} value={model.model}>
- {model.displayName || model.model}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- <label className="flex items-center gap-2 text-body">
- <Checkbox
- checked={makeDefault}
- onCheckedChange={(checked) =>
- setMakeDefault(checked === true)
- }
- />
- {t("qoder.useAfterSave")}
- </label>
- {error && (
- <p role="alert" className="text-body text-danger-text">
- {error}
- </p>
- )}
- </fieldset>
- )}
- </form>
- </div>
- </PresetStepContext.Provider>
- <AuthSettingsPanel
- target={authTarget}
- onClose={() => setAuthTarget(null)}
- />
- </FullScreenPanel>
- );
-}
diff --git a/src/components/providers/forms/ProviderForm.tsx b/src/components/providers/forms/ProviderForm.tsx
index 6d63537a0..5ec0aa7b0 100644
--- a/src/components/providers/forms/ProviderForm.tsx
+++ b/src/components/providers/forms/ProviderForm.tsx
@@ -127,6 +127,7 @@ import { GrokBuildProviderForm } from "./GrokBuildProviderForm";
import { CodexFormFields } from "./CodexFormFields";
import { GeminiFormFields } from "./GeminiFormFields";
import { KimiProviderForm } from "./KimiProviderForm";
+import { QoderProviderForm } from "./QoderProviderForm";
import { CopilotProviderForm } from "./CopilotProviderForm";
import { AgyAccountSelect } from "./AgyOAuthSection";
import {
@@ -393,6 +394,7 @@ function CodexConfigEditorWithName({
export function ProviderForm(props: ProviderFormProps) {
if (props.appId === "kimi") return <KimiProviderForm {...props} />;
+ if (props.appId === "qoder") return <QoderProviderForm {...props} />;
if (props.appId === "copilot") return <CopilotProviderForm {...props} />;
if (props.appId === "mcode" || props.appId === "dsh")
return <McodeProviderForm {...props} />;
diff --git a/src/components/providers/forms/QoderProviderForm.tsx b/src/components/providers/forms/QoderProviderForm.tsx
new file mode 100644
index 000000000..8a655e658
--- /dev/null
+++ b/src/components/providers/forms/QoderProviderForm.tsx
@@ -0,0 +1,891 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useForm } from "react-hook-form";
+import { useTranslation } from "react-i18next";
+import { ChevronRight, Plus, Trash2 } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Form, FormLabel } from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { ImeSafeInput } from "@/components/ui/ime-safe-input";
+import { Label } from "@/components/ui/label";
+import { Switch } from "@/components/ui/switch";
+import { HelpTip } from "@/components/ui/help-tip";
+import { HoverTip } from "@/components/ui/hover-tip";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { useLatestRef } from "@/hooks/useLatestRef";
+import { useModelMetadataFill } from "@/hooks/useModelMetadataFill";
+import { useQoderEdition } from "@/hooks/useQoderEdition";
+import {
+ fetchModelsForConfig,
+ showFetchModelsError,
+ type FetchedModel,
+} from "@/lib/api/model-fetch";
+import type { QoderModel, QoderProvider } from "@/lib/api/qoder";
+import { toast } from "@/lib/toast";
+import { cn } from "@/lib/utils";
+import { useProvidersQuery } from "@/lib/query/queries";
+import type { ProviderFormData } from "@/lib/schemas/provider";
+import type { ProviderCategory } from "@/types";
+import {
+ qoderAccountPreset,
+ qoderProviderPresets,
+ QODER_ACCOUNT_PRESET_ID,
+} from "@/config/qoderProviderPresets";
+import { piPresetModelSources } from "@/config/presetModelMetadata";
+import { BasicFormFields, REQUIRED_LABEL } from "./BasicFormFields";
+import {
+ ApiKeySection,
+ EndpointField,
+ GptContextWindowHint,
+ ModelDropdown,
+ NativeConfigEditor,
+} from "./shared";
+import {
+ FetchedModelPicker,
+ type FetchedModelSelection,
+} from "./FetchedModelPicker";
+import { fillQoderModel, metadataFilledAnything } from "./modelMetadataFill";
+import { ProviderPresetSelector } from "./ProviderPresetSelector";
+import type { ProviderFormProps } from "./ProviderForm";
+import { usePresetStep } from "./presetStep";
+
+type Protocol = NonNullable<QoderProvider["protocol"]>;
+type AuthType = NonNullable<QoderProvider["authType"]>;
+type ThinkingMode = "off" | "enabled" | "adaptive";
+
+// 和 Pi、Kimi 的「接口格式」下拉用同一套叫法。
+const PROTOCOL_LABELS: Record<Protocol, string> = {
+ openai: "OpenAI Chat Completions",
+ "openai-responses": "OpenAI Responses",
+ anthropic: "Anthropic Messages",
+};
+const AUTH_TYPE_LABELS: Record<AuthType, string> = {
+ bearer: "Bearer Token",
+ "api-key": "API Key (x-api-key)",
+};
+// 拉模型列表时按协议选认证头:Anthropic 用 x-api-key。
+const MODEL_FETCH_API_FORMATS: Partial<Record<Protocol, string>> = {
+ anthropic: "anthropic-messages",
+};
+// 供应商 ID 是 settings.json 里 providers 的键:Qoder 认字母、数字、点、下划线和连字符;
+// 官方账号卡的 ID 前缀留给 CC Switch 用
+const RESERVED_IDS = new Set(["qoder", "constructor", "prototype"]);
+const OFFICIAL_ID_PREFIX = "qoder-official-";
+const isValidKey = (key: string) =>
+ /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(key) &&
+ !RESERVED_IDS.has(key) &&
+ !key.startsWith(OFFICIAL_ID_PREFIX);
+const normalizeKey = (value: string) => value.replace(/[^A-Za-z0-9._-]/g, "");
+
+const PRESETS = qoderProviderPresets.map((preset) => ({
+ id: preset.providerKey,
+ preset,
+}));
+
+const emptyConfig = (): QoderProvider => ({
+ type: "openai-compatible",
+ protocol: "openai",
+ authType: "bearer",
+ baseUrl: "",
+ apiKey: "",
+ models: [],
+});
+
+const newModel = (model = ""): QoderModel => ({
+ model,
+ capabilities: { tools: true, vision: false },
+});
+
+/** 表单里的供应商:模型统一放在 models 里,只写了 `model` 的旧写法补成一行。 */
+function formConfig(raw: unknown): QoderProvider {
+ const initial =
+ raw && typeof raw === "object" && !Array.isArray(raw)
+ ? (raw as QoderProvider)
+ : emptyConfig();
+ const models = Array.isArray(initial.models) ? [...initial.models] : [];
+ if (initial.model && !models.some((model) => model.model === initial.model))
+ models.push({ model: initial.model });
+ return {
+ ...initial,
+ baseUrl: typeof initial.baseUrl === "string" ? initial.baseUrl : "",
+ apiKey: typeof initial.apiKey === "string" ? initial.apiKey : "",
+ models: structuredClone(models),
+ };
+}
+
+const thinkingMode = (model: QoderModel): ThinkingMode => {
+ const thinking = model.capabilities?.thinking;
+ const mode = thinking?.preferredMode ?? thinking?.modes?.[0];
+ return mode === "enabled" || mode === "adaptive" ? mode : "off";
+};
+
+/** 存盘前:去掉模型 ID 两端的空白,默认模型不在列表里时用第一个。 */
+function finalize(config: QoderProvider, name: string): QoderProvider {
+ const models = (config.models ?? []).map((model) => ({
+ ...model,
+ model: model.model.trim(),
+ }));
+ const model = models.some((entry) => entry.model === config.model)
+ ? config.model
+ : models[0]?.model;
+ return {
+ ...config,
+ ...(name ? { displayName: name } : {}),
+ baseUrl: config.baseUrl.trim(),
+ model,
+ models,
+ };
+}
+
+export function QoderProviderForm({
+ providerId,
+ initialData,
+ onSubmit,
+ onCancel,
+ submitLabel,
+ showButtons = true,
+ onSubmittingChange,
+ onSubmitReadyChange,
+ onAccountLoginChange,
+ onManageAuthAccounts,
+}: ProviderFormProps) {
+ const { t } = useTranslation();
+ const edition = useQoderEdition() ?? "global";
+ const isEdit = Boolean(initialData);
+ // 官方账号卡:登录和删除都在授权中心,这里只改名字、备注这些卡片信息
+ const isOfficial = isEdit && initialData?.category === "official";
+ const [config, setConfig] = useState<QoderProvider>(() =>
+ formConfig(initialData?.settingsConfig),
+ );
+ const [providerKey, setProviderKey] = useState(providerId ?? "");
+ const [text, setText] = useState(() =>
+ JSON.stringify(formConfig(initialData?.settingsConfig), null, 2),
+ );
+ const [textError, setTextError] = useState<string | null>(null);
+ const [presetId, setPresetId] = useState("custom");
+ const [category, setCategory] = useState<ProviderCategory>(
+ initialData?.category ?? "custom",
+ );
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+ const { data: existing } = useProvidersQuery("qoder");
+ const step = usePresetStep();
+ const isAccountLogin = !isEdit && presetId === QODER_ACCOUNT_PRESET_ID;
+ const showAccountLogin = isAccountLogin && (!step || step.step === "form");
+ useEffect(() => {
+ onAccountLoginChange?.(showAccountLogin);
+ return () => onAccountLoginChange?.(false);
+ }, [showAccountLogin, onAccountLoginChange]);
+ const duplicate =
+ !isEdit &&
+ Object.prototype.hasOwnProperty.call(
+ existing?.providers ?? {},
+ providerKey,
+ );
+ const keyValid = isEdit || isValidKey(providerKey);
+ const preset = PRESETS.find((entry) => entry.id === presetId)?.preset;
+ const form = useForm<ProviderFormData>({
+ defaultValues: {
+ name: initialData?.name ?? "",
+ notes: initialData?.notes ?? "",
+ websiteUrl: initialData?.websiteUrl ?? "",
+ icon: initialData?.icon ?? "",
+ iconColor: initialData?.iconColor ?? "",
+ settingsConfig: text,
+ },
+ });
+ const name = form.watch("name");
+ const models = config.models ?? [];
+ const modelsValid =
+ models.length > 0 &&
+ models.every((model) => model.model.trim()) &&
+ new Set(models.map((model) => model.model.trim())).size === models.length &&
+ models.every((model) =>
+ [model.contextWindow, model.maxOutputTokens].every(
+ (value) =>
+ value === undefined || (Number.isSafeInteger(value) && value > 0),
+ ),
+ );
+ const ready = isOfficial
+ ? Boolean(name.trim())
+ : Boolean(
+ !isAccountLogin &&
+ !textError &&
+ name.trim() &&
+ keyValid &&
+ !duplicate &&
+ /^https?:\/\//.test(config.baseUrl.trim()) &&
+ modelsValid,
+ );
+ useEffect(() => {
+ onSubmitReadyChange?.(ready);
+ }, [ready, onSubmitReadyChange]);
+ const configRef = useLatestRef(config);
+ const update = (next: QoderProvider) => {
+ configRef.current = next;
+ setConfig(next);
+ setText(JSON.stringify(next, null, 2));
+ setTextError(null);
+ };
+ const updateProvider = (patch: Partial<QoderProvider>) =>
+ update({ ...configRef.current, ...patch });
+ const updateModel = (index: number, patch: Partial<QoderModel>) =>
+ update({
+ ...configRef.current,
+ models: (configRef.current.models ?? []).map((model, position) =>
+ position === index ? { ...model, ...patch } : model,
+ ),
+ });
+ const updateCapabilities = (
+ index: number,
+ patch: NonNullable<QoderModel["capabilities"]>,
+ ) => {
+ const model = configRef.current.models?.[index];
+ if (model)
+ updateModel(index, { capabilities: { ...model.capabilities, ...patch } });
+ };
+ const [expanded, setExpanded] = useState<Set<number>>(() => new Set());
+ const toggleExpanded = (index: number) =>
+ setExpanded((current) => {
+ const next = new Set(current);
+ if (!next.delete(index)) next.add(index);
+ return next;
+ });
+
+ const [fetchedModels, setFetchedModels] = useState<FetchedModel[]>([]);
+ const [isFetchingModels, setIsFetchingModels] = useState(false);
+ const modelFetchGeneration = useRef(0);
+ const protocol = config.protocol ?? "openai";
+ const { baseUrl, apiKey } = config;
+ useEffect(() => {
+ setFetchedModels((prev) => (prev.length === 0 ? prev : []));
+ setIsFetchingModels(false);
+ return () => {
+ // 地址、Key 或协议变了,旧请求的结果不再适用。
+ modelFetchGeneration.current += 1;
+ };
+ }, [protocol, baseUrl, apiKey]);
+ const handleFetchModels = useCallback(() => {
+ const endpoint = baseUrl.trim();
+ if (!endpoint || !apiKey) {
+ showFetchModelsError(null, t, {
+ hasApiKey: Boolean(apiKey),
+ hasBaseUrl: Boolean(endpoint),
+ });
+ return;
+ }
+ const generation = ++modelFetchGeneration.current;
+ setFetchedModels([]);
+ setIsFetchingModels(true);
+ fetchModelsForConfig(endpoint, apiKey, undefined, undefined, undefined, {
+ apiFormat: MODEL_FETCH_API_FORMATS[protocol],
+ })
+ .then((result) => {
+ if (generation !== modelFetchGeneration.current) return;
+ const fetched = [
+ ...new Map(result.map((model) => [model.id, model])).values(),
+ ];
+ setFetchedModels(fetched);
+ if (fetched.length === 0)
+ toast.info(t("providerForm.fetchModelsEmpty"));
+ })
+ .catch((err) => {
+ if (generation !== modelFetchGeneration.current) return;
+ console.warn("[ModelFetch] Failed:", err);
+ showFetchModelsError(err, t);
+ })
+ .finally(() => {
+ if (generation === modelFetchGeneration.current) {
+ setIsFetchingModels(false);
+ }
+ });
+ }, [apiKey, baseUrl, protocol, t]);
+
+ const fillModelMetadata = useModelMetadataFill({
+ baseUrl,
+ presets: piPresetModelSources,
+ prefetch: fetchedModels.length > 0,
+ });
+ // 补全可能晚到:读最新的配置,确认这一行仍是这个模型再补。
+ const fillModelMetadataFor = (index: number, id: string, silent?: boolean) =>
+ fillModelMetadata(
+ id,
+ (metadata) => {
+ const model = configRef.current.models?.[index];
+ if (model?.model !== id) return false;
+ const filled = fillQoderModel(model, metadata);
+ if (!metadataFilledAnything(model, filled)) return false;
+ updateModel(index, filled);
+ return true;
+ },
+ { silent },
+ );
+ const handleApplyFetchedModels = ({ add, remove }: FetchedModelSelection) => {
+ const removed = new Set(remove);
+ const kept = (configRef.current.models ?? []).filter(
+ (model) => !removed.has(model.model),
+ );
+ const configured = new Set(kept.map((model) => model.model));
+ const added = add.filter((id) => !configured.has(id));
+ update({
+ ...configRef.current,
+ models: [...kept, ...added.map((id) => newModel(id))],
+ });
+ setExpanded(new Set());
+ // 弹窗里已经显示过这些参数,补完不再提示。
+ added.forEach((id, offset) =>
+ fillModelMetadataFor(kept.length + offset, id, true),
+ );
+ };
+
+ const presetSelector = (
+ <ProviderPresetSelector
+ selectedPresetId={presetId}
+ presetEntries={[
+ { id: QODER_ACCOUNT_PRESET_ID, preset: qoderAccountPreset(edition) },
+ ...PRESETS,
+ ]}
+ presetCategoryLabels={{
+ custom: t("providerPreset.custom"),
+ cn_official: t("providerForm.categoryCnOfficial"),
+ third_party: t("providerPreset.group.thirdparty"),
+ aggregator: t("providerPreset.group.thirdparty"),
+ cloud_provider: t("providerPreset.group.cloud"),
+ local: t("providerPreset.group.local"),
+ }}
+ category={category}
+ onPresetChange={(id) => {
+ setPresetId(id);
+ if (id === QODER_ACCOUNT_PRESET_ID) return;
+ const next = PRESETS.find((entry) => entry.id === id)?.preset;
+ setCategory(next?.category ?? "custom");
+ update(formConfig(structuredClone(next?.settingsConfig)));
+ setExpanded(new Set());
+ setProviderKey(next?.providerKey ?? "");
+ form.reset({
+ name: next?.nameKey ? t(next.nameKey) : (next?.name ?? ""),
+ notes: "",
+ websiteUrl: next?.websiteUrl ?? "",
+ icon: next?.icon ?? "",
+ iconColor: next?.iconColor ?? "",
+ settingsConfig: "",
+ });
+ }}
+ />
+ );
+ const manageAccounts = (
+ <Button
+ type="button"
+ variant="neutral"
+ onClick={() => onManageAuthAccounts?.("qoder_oauth")}
+ >
+ {t("qoder.manageAccounts")}
+ </Button>
+ );
+ if (isAccountLogin) {
+ return (
+ <Form {...form}>
+ <form
+ id="provider-form"
+ className="space-y-6"
+ onSubmit={(event) => event.preventDefault()}
+ >
+ {presetSelector}
+ {showAccountLogin && (
+ <div className="space-y-3">
+ <p className="text-body text-fg-2">
+ {t("qoder.loginDescription")}
+ </p>
+ {manageAccounts}
+ </div>
+ )}
+ </form>
+ </Form>
+ );
+ }
+ const defaultModelOptions = models.filter(
+ (model, index) =>
+ model.model.trim() &&
+ models.findIndex((entry) => entry.model === model.model) === index,
+ );
+ return (
+ <Form {...form}>
+ <form
+ id="provider-form"
+ className="space-y-6"
+ onSubmit={form.handleSubmit(async (identity) => {
+ if (!ready || busy) return;
+ setBusy(true);
+ onSubmittingChange?.(true);
+ setError("");
+ try {
+ const trimmed = identity.name.trim();
+ await onSubmit({
+ ...identity,
+ name: trimmed,
+ providerKey: isEdit ? providerId! : providerKey,
+ meta: initialData?.meta,
+ presetCategory: category,
+ settingsConfig: JSON.stringify(
+ isOfficial ? {} : finalize(config, trimmed),
+ ),
+ });
+ } catch (cause) {
+ setError(String(cause));
+ } finally {
+ setBusy(false);
+ onSubmittingChange?.(false);
+ }
+ })}
+ >
+ {!isEdit && presetSelector}
+ {error && (
+ <p role="alert" className="text-sm text-destructive">
+ {error}
+ </p>
+ )}
+ <fieldset
+ disabled={busy || Boolean(textError)}
+ className="min-w-0 space-y-6 border-0 p-0 disabled:opacity-50"
+ >
+ <BasicFormFields
+ form={form}
+ beforeNameSlot={
+ isOfficial ? undefined : (
+ <div className="space-y-2">
+ <Label
+ htmlFor="qoder-provider-key"
+ className={REQUIRED_LABEL}
+ >
+ {t("opencode.providerKey")}
+ </Label>
+ <ImeSafeInput
+ id="qoder-provider-key"
+ value={providerKey}
+ disabled={isEdit}
+ normalize={normalizeKey}
+ onValueChange={setProviderKey}
+ placeholder={t("opencode.providerKeyPlaceholder")}
+ />
+ <p
+ className={
+ duplicate || (providerKey && !keyValid)
+ ? "text-xs text-destructive"
+ : "text-xs text-fg-2"
+ }
+ >
+ {duplicate
+ ? t("opencode.providerKeyDuplicate")
+ : isEdit
+ ? t("opencode.providerKeyLockedHint")
+ : t("qoder.invalidProviderId")}
+ </p>
+ </div>
+ )
+ }
+ />
+ {isOfficial ? (
+ <div className="space-y-3">
+ <p className="text-sm text-fg-2">
+ {t("qoder.officialCardManaged")}
+ </p>
+ {manageAccounts}
+ </div>
+ ) : (
+ <>
+ <div className="grid gap-4 sm:grid-cols-2">
+ <div className="space-y-2">
+ <FormLabel htmlFor="qoder-protocol">
+ {t("opencode.npmPackage")}
+ </FormLabel>
+ <Select
+ value={protocol}
+ onValueChange={(value) =>
+ updateProvider({
+ protocol: value as Protocol,
+ authType: value === "anthropic" ? "api-key" : "bearer",
+ })
+ }
+ >
+ <SelectTrigger id="qoder-protocol">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {(Object.keys(PROTOCOL_LABELS) as Protocol[]).map(
+ (value) => (
+ <SelectItem key={value} value={value}>
+ {PROTOCOL_LABELS[value]}
+ </SelectItem>
+ ),
+ )}
+ </SelectContent>
+ </Select>
+ </div>
+ <div className="space-y-2">
+ <FormLabel htmlFor="qoder-auth-type">
+ {t("qoder.authType")}
+ </FormLabel>
+ <Select
+ value={config.authType ?? "bearer"}
+ onValueChange={(value) =>
+ updateProvider({ authType: value as AuthType })
+ }
+ >
+ <SelectTrigger id="qoder-auth-type">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {(Object.keys(AUTH_TYPE_LABELS) as AuthType[]).map(
+ (value) => (
+ <SelectItem key={value} value={value}>
+ {AUTH_TYPE_LABELS[value]}
+ </SelectItem>
+ ),
+ )}
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+ <div className="space-y-1">
+ <ApiKeySection
+ id="qoder-api-key"
+ value={config.apiKey}
+ onChange={(value) => updateProvider({ apiKey: value })}
+ category={category}
+ shouldShowLink={Boolean(preset?.apiKeyUrl)}
+ websiteUrl={preset?.apiKeyUrl ?? ""}
+ isPartner={preset?.isPartner}
+ partnerPromotionKey={preset?.partnerPromotionKey}
+ required={false}
+ />
+ <p className="text-xs text-fg-2">{t("qoder.apiKeyHint")}</p>
+ </div>
+ <EndpointField
+ id="qoder-base-url"
+ label={t("opencode.baseUrl")}
+ value={config.baseUrl}
+ onChange={(value) => updateProvider({ baseUrl: value })}
+ placeholder="https://api.example.com/v1"
+ />
+ <div className="space-y-3 border-l border-border pl-3">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-1">
+ <FormLabel>{t("opencode.models")}</FormLabel>
+ <HelpTip title={t("opencode.models")}>
+ {t("qoder.modelSelectionHint")}
+ </HelpTip>
+ </div>
+ <div className="flex gap-1">
+ <FetchedModelPicker
+ models={fetchedModels}
+ configuredModelIds={models.map((model) => model.model)}
+ onApply={handleApplyFetchedModels}
+ onFetch={handleFetchModels}
+ isFetching={isFetchingModels}
+ metadataSource={{
+ baseUrl,
+ presets: piPresetModelSources,
+ }}
+ />
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="h-7 gap-1"
+ onClick={() =>
+ updateProvider({ models: [...models, newModel()] })
+ }
+ >
+ <Plus className="h-3.5 w-3.5" />
+ {t("opencode.addModel")}
+ </Button>
+ </div>
+ </div>
+ {models.length === 0 ? (
+ <p className="py-2 text-sm text-fg-2">
+ {t("opencode.noModels")}
+ </p>
+ ) : (
+ <div className="space-y-2">
+ <div className="mb-1 flex items-center gap-2 px-1 text-xs text-fg-2">
+ <span className="w-9" />
+ <span className={cn("flex-1", REQUIRED_LABEL)}>
+ {t("opencode.modelId")}
+ </span>
+ <span className="flex-1">{t("opencode.modelName")}</span>
+ <span className="w-9" />
+ </div>
+ {models.map((model, index) => (
+ <div key={index} className="space-y-2">
+ <div className="flex items-center gap-2">
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ onClick={() => toggleExpanded(index)}
+ aria-label={t("opencode.toggleModelDetails")}
+ aria-expanded={expanded.has(index)}
+ className="h-9 w-9 shrink-0"
+ >
+ <ChevronRight
+ className={cn(
+ "h-4 w-4 transition-transform motion-reduce:transition-none",
+ expanded.has(index) && "rotate-90",
+ )}
+ />
+ </Button>
+ <div className="flex min-w-0 flex-1 gap-1">
+ <Input
+ id={`qoder-model-${index}`}
+ value={model.model}
+ onChange={(event) =>
+ updateModel(index, {
+ model: event.target.value,
+ })
+ }
+ placeholder="model-id"
+ aria-label={t("opencode.modelId")}
+ className="min-w-0 flex-1"
+ />
+ {fetchedModels.length > 0 && (
+ <ModelDropdown
+ models={fetchedModels}
+ onSelect={(id) => {
+ updateModel(index, { model: id });
+ fillModelMetadataFor(index, id);
+ }}
+ />
+ )}
+ </div>
+ <Input
+ id={`qoder-model-name-${index}`}
+ value={model.displayName ?? ""}
+ onChange={(event) =>
+ updateModel(index, {
+ displayName: event.target.value || undefined,
+ })
+ }
+ placeholder={t("opencode.modelName")}
+ aria-label={t("opencode.modelName")}
+ className="min-w-0 flex-1"
+ />
+ <HoverTip content={t("common.delete")}>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ aria-label={t("common.delete")}
+ className="h-9 w-9 shrink-0 text-fg-2 hover:text-destructive"
+ onClick={() => {
+ updateProvider({
+ models: models.filter(
+ (_, position) => position !== index,
+ ),
+ });
+ setExpanded(new Set());
+ }}
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ </HoverTip>
+ </div>
+ {expanded.has(index) && (
+ <div className="ml-9 grid gap-3 border-l-2 border-muted pl-4 sm:grid-cols-2">
+ <div className="flex min-h-9 flex-wrap items-center gap-x-8 gap-y-2 sm:col-span-2">
+ {(["tools", "vision"] as const).map((field) => (
+ <div
+ key={field}
+ className="flex items-center gap-2.5"
+ >
+ <Label
+ htmlFor={`qoder-model-${field}-${index}`}
+ className="cursor-pointer"
+ >
+ {t(`qoder.${field}`)}
+ </Label>
+ <Switch
+ id={`qoder-model-${field}-${index}`}
+ checked={
+ model.capabilities?.[field] ??
+ field === "tools"
+ }
+ onCheckedChange={(checked) =>
+ updateCapabilities(index, {
+ [field]: checked,
+ })
+ }
+ />
+ </div>
+ ))}
+ <div className="flex items-center gap-2.5">
+ <Label htmlFor={`qoder-thinking-${index}`}>
+ {t("qoder.thinking")}
+ </Label>
+ <Select
+ value={thinkingMode(model)}
+ onValueChange={(value) => {
+ const thinking =
+ model.capabilities?.thinking;
+ updateCapabilities(index, {
+ thinking: {
+ ...thinking,
+ modes: value === "off" ? [] : [value],
+ preferredMode:
+ value === "off" ? undefined : value,
+ requiresBudgetForEnabled:
+ value === "enabled"
+ ? true
+ : undefined,
+ },
+ });
+ }}
+ >
+ <SelectTrigger
+ id={`qoder-thinking-${index}`}
+ className="w-36"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="off">
+ {t("qoder.thinkingOff")}
+ </SelectItem>
+ <SelectItem value="enabled">
+ {t("qoder.thinkingEnabled")}
+ </SelectItem>
+ <SelectItem value="adaptive">
+ {t("qoder.thinkingAdaptive")}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+ {(
+ ["contextWindow", "maxOutputTokens"] as const
+ ).map((field) => (
+ <div key={field} className="space-y-2">
+ <Label htmlFor={`qoder-${field}-${index}`}>
+ {t(`qoder.${field}`)}
+ </Label>
+ <Input
+ id={`qoder-${field}-${index}`}
+ type="number"
+ min={1}
+ step={1}
+ value={model[field] ?? ""}
+ onChange={(event) =>
+ updateModel(index, {
+ [field]:
+ event.target.value === ""
+ ? undefined
+ : Number(event.target.value),
+ })
+ }
+ />
+ {field === "contextWindow" && (
+ <GptContextWindowHint
+ modelId={model.model}
+ contextWindow={model.contextWindow}
+ />
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+ {defaultModelOptions.length > 1 && (
+ <div className="space-y-2">
+ <Label htmlFor="qoder-provider-default">
+ {t("qoder.providerDefaultModel")}
+ </Label>
+ <Select
+ value={
+ defaultModelOptions.some(
+ (model) => model.model === config.model,
+ )
+ ? config.model
+ : defaultModelOptions[0].model
+ }
+ onValueChange={(model) => updateProvider({ model })}
+ >
+ <SelectTrigger id="qoder-provider-default">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {defaultModelOptions.map((model) => (
+ <SelectItem key={model.model} value={model.model}>
+ {model.displayName || model.model}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <p className="text-xs text-fg-2">
+ {t("qoder.providerDefaultModelHint")}
+ </p>
+ </div>
+ )}
+ </div>
+ </>
+ )}
+ </fieldset>
+ {!isOfficial && (
+ <NativeConfigEditor
+ appId="qoder"
+ file="settings.json"
+ id="qoder-settings-config"
+ value={text}
+ onChange={(next) => {
+ setText(next);
+ try {
+ const parsed: unknown = JSON.parse(next);
+ if (
+ !parsed ||
+ typeof parsed !== "object" ||
+ Array.isArray(parsed)
+ ) {
+ setTextError(t("qoder.configJsonSchema"));
+ return;
+ }
+ setTextError(null);
+ const parsedConfig = formConfig(parsed);
+ configRef.current = parsedConfig;
+ setConfig(parsedConfig);
+ } catch (cause) {
+ setTextError(
+ t("providerForm.nativeConfig.invalid", {
+ format: "JSON",
+ error: String(cause),
+ }),
+ );
+ }
+ }}
+ error={textError}
+ />
+ )}
+ {showButtons && (
+ <div className="flex justify-end gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ disabled={busy}
+ onClick={onCancel}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button type="submit" disabled={busy || !ready}>
+ {submitLabel}
+ </Button>
+ </div>
+ )}
+ </form>
+ </Form>
+ );
+}
diff --git a/src/components/providers/forms/modelMetadataFill.ts b/src/components/providers/forms/modelMetadataFill.ts
index dc12e28f7..4eb71b9c1 100644
--- a/src/components/providers/forms/modelMetadataFill.ts
+++ b/src/components/providers/forms/modelMetadataFill.ts
@@ -15,6 +15,7 @@ import {
} from "@/config/workbuddyProviderPresets";
import type { CodebuddyModelConfig } from "@/config/codebuddyProviderPresets";
import type { KimiProviderConfig } from "@/config/kimiProviderPresets";
+import type { QoderModel } from "@/lib/api/qoder";
import {
PI_THINKING_LEVELS,
type PiThinkingLevelMap,
@@ -231,6 +232,30 @@ export function fillKimiModel(
return next;
}
+/**
+ * Qoder settings.json 里的一条模型:空着的上下文窗口和最大输出才补;图片输入只往
+ * 「支持」方向补。思考模式要按协议选(预算 / 自适应),不自动开。
+ */
+export function fillQoderModel(
+ model: QoderModel,
+ metadata: KnownModelMetadata,
+): QoderModel {
+ const next = { ...model };
+ if (isBlank(model.contextWindow) && metadata.contextWindow) {
+ next.contextWindow = metadata.contextWindow;
+ }
+ if (isBlank(model.maxOutputTokens) && metadata.maxOutputTokens) {
+ next.maxOutputTokens = metadata.maxOutputTokens;
+ }
+ if (
+ metadata.inputModalities?.includes("image") &&
+ !model.capabilities?.vision
+ ) {
+ next.capabilities = { ...model.capabilities, vision: true };
+ }
+ return next;
+}
+
/**
* CodeBuddy models.json 的一条模型:上下文窗口当作最大输入,空着的 token 上限才补;
* 图片输入和推理只往「支持」方向补。
diff --git a/src/components/providers/presentation.ts b/src/components/providers/presentation.ts
index 9949322dc..67b67342f 100644
--- a/src/components/providers/presentation.ts
+++ b/src/components/providers/presentation.ts
@@ -782,6 +782,10 @@ export interface AdditiveInput {
workbuddyOfficial?: WorkBuddyOfficialState;
/** CodeBuddy:官方登录卡绑定账号的状态(授权中心收录的账号 + CodeBuddy 现在登着的号) */
codebuddyAccounts?: CodebuddyAccountsState;
+ /** Qoder:settings.json 的 `model.name` 所属的卡(`auto` 时是当前登录账号的官方卡)。 */
+ qoderCurrentId?: string | null;
+ /** Qoder 官方账号卡:收录的账号、Qoder 现在登着的号 */
+ qoderAccounts?: QoderAccountsState;
/** Copilot CLI:settings.json 的 `model`(`<卡片 id>/<模型>`)所属的自带模型卡。 */
copilotDefaultId?: string | null;
/** 「已添加」里列表外另画的卡(DSH 的 DeepSeek 账号卡),计入标题数字 */
@@ -799,6 +803,17 @@ export interface AdditiveInput {
};
}
+export interface QoderAccountsState {
+ status: "loading" | "error" | "ready";
+ /** Qoder 现在登着的号 */
+ currentAccountId: string | null;
+ accountIds: string[];
+ /** Qoder 里登着、还没收录的号:切号会覆盖它,先收录 */
+ uncollectedLogin: string | null;
+ /** 正在添加(切号)的卡 */
+ switchingId?: string | null;
+}
+
export interface CodebuddyAccountsState {
status: "loading" | "error" | "ready";
/** CodeBuddy 现在登着的号 */
@@ -908,6 +923,182 @@ function codebuddyOfficialItem(
};
}
+/** Qoder 每家可选的模型(settings.json 里这家的 `models`),给「设为默认」的子菜单。 */
+function qoderModelOptions(p: Provider): { id: string; name?: string }[] {
+ const models = (p.settingsConfig as { models?: unknown })?.models;
+ if (!Array.isArray(models)) return [];
+ return models.flatMap((model) => {
+ const id = (model as { model?: unknown })?.model;
+ const name = (model as { displayName?: unknown })?.displayName;
+ return typeof id === "string" && id.trim()
+ ? [{ id, name: typeof name === "string" ? name : undefined }]
+ : [];
+ });
+}
+
+function setDefaultMenuItem(
+ t: TFunction,
+ p: Provider,
+ models: { id: string; name?: string }[],
+ setDefault: (provider: Provider, modelId?: string) => void,
+): CardMenuItem {
+ return {
+ key: "setDefault",
+ label: t("providerCard.action.setDefault"),
+ onSelect: () => setDefault(p, models[0]?.id),
+ submenu:
+ models.length > 1
+ ? {
+ title: t("openclaw.selectDefaultModel"),
+ options: models.map((model) => ({
+ key: model.id,
+ label: model.name?.trim() || model.id,
+ detail:
+ model.name?.trim() && model.name.trim() !== model.id
+ ? model.id
+ : undefined,
+ onSelect: () => setDefault(p, model.id),
+ })),
+ }
+ : undefined,
+ };
+}
+
+/**
+ * Qoder 的卡:模型卡和 Kimi 一样「添加」写进当前版本的 settings.json、「移除」拿掉条目留着卡;
+ * 官方账号卡和 CodeBuddy 一样每个收录的号一张,Qoder 登着的那个号在「已添加」,「添加」别的号就是切号。
+ * 「设为默认」改 `model.name`(官方卡是 `auto`),收在「更多」菜单里;默认那家不能移除、不能删。
+ */
+function qoderItem(
+ input: AdditiveInput,
+ p: Provider,
+): { added: boolean; item: ProviderSection["items"][number] } {
+ const { t, actions } = input;
+ const isDefault = p.id === input.qoderCurrentId;
+ const status = isDefault
+ ? { label: t("providerCard.status.default"), dot: "direct" as const }
+ : undefined;
+ const tone = isDefault ? ("direct" as const) : undefined;
+ if (p.category === "official") {
+ const chips: CardChip[] = [
+ {
+ key: "official",
+ label: t("providerCard.chip.official"),
+ tone: "outline",
+ },
+ ];
+ const state = input.qoderAccounts;
+ const accountId = resolveManagedAccountId(p.meta, "qoder_oauth");
+ const ready = state?.status === "ready";
+ const known = Boolean(accountId && state?.accountIds.includes(accountId));
+ const deleteDisabledReason = t("qoder.accountManagedByQoder");
+ if (ready && known && state.currentAccountId === accountId) {
+ return {
+ added: true,
+ item: {
+ provider: p,
+ presentation: {
+ tone,
+ status,
+ chips,
+ buttons: [
+ {
+ key: "remove",
+ label: t("providerCard.action.remove"),
+ onClick: () => {},
+ disabledReason: t("qoder.official.removeHint"),
+ },
+ ],
+ menuItems: isDefault
+ ? undefined
+ : [
+ {
+ key: "setDefault",
+ label: t("providerCard.action.setDefault"),
+ onSelect: () => actions.setDefault(p),
+ },
+ ],
+ deleteDisabledReason,
+ },
+ },
+ };
+ }
+ const disabledReason =
+ !state || state.status === "loading"
+ ? t("qoder.official.statusLoading")
+ : state.status === "error"
+ ? t("qoder.statusFailed")
+ : !known
+ ? t("qoder.official.accountMissing")
+ : state.uncollectedLogin
+ ? t("qoder.official.collectFirst", {
+ name: state.uncollectedLogin,
+ })
+ : state.switchingId
+ ? t("qoder.official.adding")
+ : undefined;
+ return {
+ added: false,
+ item: {
+ provider: p,
+ presentation: {
+ chips,
+ buttons: [
+ {
+ key: "add",
+ label: t("providerCard.action.add"),
+ onClick: () => actions.switchAccount?.(p),
+ disabledReason,
+ },
+ ],
+ deleteDisabledReason,
+ },
+ },
+ };
+ }
+ const live = input.isInConfig(p);
+ const buttons: CardButton[] = [];
+ const menuItems: CardMenuItem[] = [];
+ if (!live) {
+ buttons.push({
+ key: "add",
+ label: t("providerCard.action.add"),
+ onClick: () => actions.add(p),
+ });
+ } else {
+ if (!isDefault) {
+ const models = qoderModelOptions(p);
+ if (models.length > 0)
+ menuItems.push(setDefaultMenuItem(t, p, models, actions.setDefault));
+ }
+ buttons.push({
+ key: "remove",
+ label: t("providerCard.action.remove"),
+ disabledReason: isDefault
+ ? t("providerCard.reason.defaultCannotRemove")
+ : undefined,
+ onClick: () => actions.remove(p),
+ });
+ }
+ return {
+ added: live,
+ item: {
+ provider: p,
+ presentation: {
+ tone: live ? tone : undefined,
+ status: live ? status : undefined,
+ chips: [],
+ buttons,
+ menuItems: menuItems.length ? menuItems : undefined,
+ deleteDisabledReason:
+ live && isDefault
+ ? t("providerCard.reason.inUseCannotDelete")
+ : undefined,
+ },
+ },
+ };
+}
+
/**
* WorkBuddy 官方登录卡:和模型卡一样分进「已添加 / 可添加」,但同一时间只有一张在「已添加」——
* 绑定的账号就是 WorkBuddy 现在登着的号。「添加」= 把 WorkBuddy 的登录切到这张卡的账号(要先退出
@@ -1003,6 +1194,11 @@ export function buildAdditiveSections(input: AdditiveInput): ProviderSection[] {
(isAdded ? added : available).push(item);
continue;
}
+ if (app === "qoder") {
+ const { added: isAdded, item } = qoderItem(input, p);
+ (isAdded ? added : available).push(item);
+ continue;
+ }
if (app === "workbuddy" && isWorkBuddyOfficial(p)) {
const card = workbuddyOfficialCard(input, p);
(card.added ? added : available).push({
@@ -1236,26 +1432,7 @@ export function buildAdditiveSections(input: AdditiveInput): ProviderSection[] {
// 「设为默认」放「更多」菜单,不占卡片上的主操作位;多个模型时展开子菜单选。
// OpenCode 内置供应商可以不列模型(运行时才有),给不出选项就不显示
if (app === "openclaw" || models.length > 0) {
- menuItems.push({
- key: "setDefault",
- label: t("providerCard.action.setDefault"),
- onSelect: () => actions.setDefault(p, models[0]?.id),
- submenu:
- models.length > 1
- ? {
- title: t("openclaw.selectDefaultModel"),
- options: models.map((model) => ({
- key: model.id,
- label: model.name?.trim() || model.id,
- detail:
- model.name?.trim() && model.name.trim() !== model.id
- ? model.id
- : undefined,
- onSelect: () => actions.setDefault(p, model.id),
- })),
- }
- : undefined,
- });
+ menuItems.push(setDefaultMenuItem(t, p, models, actions.setDefault));
}
}
}
diff --git a/src/config/appSpecs.ts b/src/config/appSpecs.ts
index 15e8d37c8..c46c82dab 100644
--- a/src/config/appSpecs.ts
+++ b/src/config/appSpecs.ts
@@ -301,12 +301,12 @@ export const APP_SPECS = {
officialSubscription: false,
},
// Qoder CLI:国际版 / 国内版是同一个应用,设置里的 qoderEdition 决定读写哪个目录。
- // 模型卡在它自己的 settings.json 里,不走供应商表,也不进托盘。
+ // 累加式:卡片「添加」写进当前版本 settings.json 的 providers;官方账号卡一号一张,添加=切号。
qoder: {
localProxy: false,
routeMode: false,
stack: false,
- additive: false,
+ additive: true,
skills: true,
mcp: true,
prompts: true,
diff --git a/src/hooks/useProviderActions.ts b/src/hooks/useProviderActions.ts
index 51deab99b..75b1cecdc 100644
--- a/src/hooks/useProviderActions.ts
+++ b/src/hooks/useProviderActions.ts
@@ -32,6 +32,7 @@ import { usageKeys } from "@/lib/query/usage";
import { routeSwitchNotification } from "@/utils/routeSwitchNotification";
import { extractErrorMessage } from "@/utils/errorUtils";
import { openclawKeys } from "@/hooks/useOpenClaw";
+import { qoderApi } from "@/lib/api/qoder";
import { supportsOfficialProxyTakeover } from "@/utils/providerCapabilities";
import { getRoutingReason } from "@/utils/routingReason";
import { logFrontendInfo } from "@/lib/frontendLogger";
@@ -455,13 +456,38 @@ export function useProviderActions(
[queryClient, t],
);
- // Set provider as default model (OpenClaw / OpenCode)
+ // Set provider as default model (OpenClaw / OpenCode / Qoder)
const setAsDefaultModel = useCallback(
async (provider: Provider, modelId?: string) => {
if (activeApp === "opencode") {
await setOpenCodeDefaultModel(provider, modelId);
return;
}
+ if (activeApp === "qoder") {
+ // 自定义卡把 model.name 指到它的模型(没选就用它自己的默认模型),官方卡改成 auto
+ try {
+ await qoderApi.setDefaultModel(provider.id, modelId);
+ toast.success(
+ t("notifications.openclawDefaultModelSet", {
+ defaultValue: "已设为默认模型",
+ }),
+ { closeButton: true },
+ );
+ } catch (error) {
+ toast.error(
+ extractErrorMessage(error) ||
+ t("notifications.openclawDefaultModelSetFailed", {
+ defaultValue: "设置默认模型失败",
+ }),
+ );
+ } finally {
+ await queryClient.invalidateQueries({
+ queryKey: ["providers", "qoder"],
+ });
+ await providersApi.updateTrayMenu().catch(() => {});
+ }
+ return;
+ }
const config = provider.settingsConfig as OpenClawProviderConfig;
if (!config.models || config.models.length === 0) {
toast.error(
diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json
index b4bfcd5fa..6221bf53c 100644
--- a/src/i18n/locales/de.json
+++ b/src/i18n/locales/de.json
@@ -5745,11 +5745,8 @@
"accountCount": "Gespeicherte Konten: {{count}}",
"accountManagedByQoder": "Verwalten oder entfernen Sie dieses Konto im Autorisierungscenter.",
"addAccount": "Konto hinzufügen",
- "addModel": "Modell hinzufügen",
"apiKeyHint": "Für lokale Dienste ohne Authentifizierung leer lassen. Umgebungsverweise wie ${ENV_NAME} werden unterstützt.",
"authType": "Authentifizierung",
- "autoModel": "Automatisch (in Qoder integriert)",
- "baseUrl": "API-Endpunkt",
"chinaEdition": "China",
"collectAccount": "Zu CC Switch hinzufügen",
"contextWindow": "Kontextfenster",
@@ -5758,15 +5755,10 @@
"deleteAccountConfirm": "„{{name}}“ aus CC Switch entfernen? Gelöscht wird nur die von CC Switch gespeicherte Anmeldung; Qoder wird nicht abgemeldet. Andere Konten und Anbieterkonfigurationen bleiben erhalten.",
"deleteAccountTitle": "Qoder-Konto entfernen",
"deleteCurrentAccountConfirm": "Das aktuelle Konto „{{name}}“ aus CC Switch entfernen? Gelöscht wird nur die von CC Switch gespeicherte Anmeldung; Qoder bleibt mit diesem Konto angemeldet. Andere Konten und Anbieterkonfigurationen bleiben erhalten.",
- "deleteProviderDescription": "„{{name}}“ und seine Modelle löschen? Ist er gerade ausgewählt, kehrt das Standardmodell zur automatischen Auswahl zurück.",
- "deleteProviderTitle": "Anbieter löschen",
"deleteSessionHint": "Löschen Sie Sitzungen in Qoder CLI, damit Sitzungsstatus und Verlauf übereinstimmen.",
- "duplicateProvider": "Diese Anbieter-ID existiert bereits",
"edition": "Qoder-Edition",
"editionHint": "Verwaltet wird die Edition {{edition}}. Die Edition wechseln Sie auf der Seite „Apps“.",
- "editProviderTitle": "Anbieter bearbeiten",
"globalEdition": "International",
- "imported": "Aktuelle benutzerdefinierte Qoder-Anbieter geladen",
"invalidProviderId": "Mit einem Buchstaben oder einer Ziffer beginnen und nur Buchstaben, Ziffern, Punkte, Unterstriche und Bindestriche verwenden. Reservierte Namen sind nicht erlaubt.",
"loggedInAs": "Angemeldet als {{name}}",
"loginBrowserFailed": "Der Browser konnte nicht geöffnet werden. Versuchen Sie es mit der Schaltfläche unten erneut.",
@@ -5778,22 +5770,10 @@
"loginWithBrowser": "Bei Qoder anmelden",
"manageAccounts": "Konten verwalten",
"maxOutputTokens": "Maximale Ausgabe-Tokens",
- "modelId": "Modell-ID",
- "modelName": "Anzeigename",
- "modelNumber": "Modell {{number}}",
- "models": "Modelle",
- "nothingToImport": "Es sind keine benutzerdefinierten Anbieter konfiguriert. Legen Sie über „Anbieter hinzufügen“ einen an.",
"officialAccount": "Qoder-Konto",
"officialAccountCn": "Qoder-CN-Konto",
- "protocol": "API-Protokoll",
"providerDefaultModel": "Standardmodell des Anbieters",
- "providerId": "Anbieter-ID",
- "providerName": "Anbietername",
"refreshAccounts": "Qoder-Konten aktualisieren",
- "removeModel": "Modell {{number}} entfernen",
- "saved": "Qoder-Modellkonfiguration gespeichert",
- "selectModelAction": "Standardmodell auswählen",
- "selectModelPlaceholder": "Modell auswählen",
"signedIn": "Angemeldet",
"signedOut": "Abgemeldet",
"signInAgain": "Erneut anmelden",
@@ -5806,7 +5786,22 @@
"uncollectedLogin": "Qoder ist als {{name}} angemeldet, das Konto ist aber nicht in CC Switch gespeichert",
"uncollectedLoginHint": "CC Switch speichert Qoder-Anmeldungen nicht von selbst. Fügen Sie diese hinzu, um hier zwischen Konten zu wechseln.",
"useAccount": "Dieses Konto verwenden",
- "useAfterSave": "Nach dem Speichern das Standardmodell dieses Anbieters verwenden",
- "vision": "Bildeingabe"
+ "vision": "Bildeingabe",
+ "configJsonSchema": "Die Konfiguration muss ein JSON-Objekt sein",
+ "modelSelectionHint": "Diese Modelle erscheinen in der /model-Liste von Qoder. Über „Als Standard festlegen“ im Menü „Mehr“ wählst du das Standardmodell von Qoder.",
+ "officialCardManaged": "Diese Karte steht für ein Qoder-Konto im Autorisierungscenter. Anmelden und Konten entfernen erfolgt dort.",
+ "providerDefaultModelHint": "Wird verwendet, wenn du diesen Anbieter im Menü „Mehr“ als Standard festlegst, ohne ein Modell zu wählen.",
+ "empty": {
+ "title": "Noch keine Qoder-Anbieter",
+ "description": "Hinzugefügte Anbieter werden in die settings.json der aktuellen Qoder-Edition geschrieben. Offizielle Konten erscheinen hier, nachdem du dich im Autorisierungscenter angemeldet hast."
+ },
+ "official": {
+ "accountMissing": "Dieses Konto ist nicht mehr im Autorisierungscenter",
+ "added": "{{name}} hinzugefügt. Qoder verwendet jetzt dieses Konto",
+ "adding": "Wird hinzugefügt…",
+ "collectFirst": "Qoder ist als {{name}} angemeldet, das noch nicht gespeichert ist. Ein Wechsel würde diese Anmeldung überschreiben – speichere sie zuerst im Autorisierungscenter.",
+ "removeHint": "Qoder kann jeweils nur bei einem Konto angemeldet sein. Füge eine andere offizielle Karte hinzu, um zu wechseln",
+ "statusLoading": "Konten werden geladen…"
+ }
}
}
diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json
index 456c972ce..ccdcbbdf2 100644
--- a/src/i18n/locales/en.json
+++ b/src/i18n/locales/en.json
@@ -5745,11 +5745,8 @@
"accountCount": "Saved accounts: {{count}}",
"accountManagedByQoder": "Manage or remove this account in the Authorization Center.",
"addAccount": "Add account",
- "addModel": "Add model",
"apiKeyHint": "Leave empty for local services without authentication. Environment references such as ${ENV_NAME} are supported.",
"authType": "Authentication",
- "autoModel": "Automatic (Qoder built-in)",
- "baseUrl": "API endpoint",
"chinaEdition": "China",
"collectAccount": "Add to CC Switch",
"contextWindow": "Context window",
@@ -5758,15 +5755,10 @@
"deleteAccountConfirm": "Remove “{{name}}” from CC Switch? Only the sign-in saved by CC Switch is deleted; Qoder is not signed out. Other accounts and provider configurations are kept.",
"deleteAccountTitle": "Remove Qoder account",
"deleteCurrentAccountConfirm": "Remove the current account “{{name}}” from CC Switch? Only the sign-in saved by CC Switch is deleted; Qoder stays signed in with this account. Other accounts and provider configurations are kept.",
- "deleteProviderDescription": "Delete “{{name}}” and its models. If it is currently selected, the default model will return to automatic selection.",
- "deleteProviderTitle": "Delete provider",
"deleteSessionHint": "Delete sessions in Qoder CLI to keep session state and history consistent.",
- "duplicateProvider": "This provider ID already exists",
"edition": "Qoder edition",
"editionHint": "Managing the {{edition}} edition. Switch editions on the Apps page.",
- "editProviderTitle": "Edit provider",
"globalEdition": "Global",
- "imported": "Loaded the current Qoder custom providers",
"invalidProviderId": "Start with a letter or digit and use only letters, digits, dots, underscores and dashes. Reserved names are not allowed.",
"loggedInAs": "Signed in as {{name}}",
"loginBrowserFailed": "Could not open the browser. Use the button below to try again.",
@@ -5778,22 +5770,10 @@
"loginWithBrowser": "Sign in to Qoder",
"manageAccounts": "Manage accounts",
"maxOutputTokens": "Maximum output tokens",
- "modelId": "Model ID",
- "modelName": "Display name",
- "modelNumber": "Model {{number}}",
- "models": "Models",
- "nothingToImport": "No custom providers are configured. Use Add provider to create one.",
"officialAccount": "Qoder Account",
"officialAccountCn": "Qoder CN Account",
- "protocol": "API protocol",
"providerDefaultModel": "Provider default model",
- "providerId": "Provider ID",
- "providerName": "Provider name",
"refreshAccounts": "Refresh Qoder accounts",
- "removeModel": "Remove model {{number}}",
- "saved": "Qoder model configuration saved",
- "selectModelAction": "Select default model",
- "selectModelPlaceholder": "Select a model",
"signedIn": "Signed in",
"signedOut": "Signed out",
"signInAgain": "Sign in again",
@@ -5806,7 +5786,22 @@
"uncollectedLogin": "Qoder is signed in as {{name}}, which is not saved in CC Switch",
"uncollectedLoginHint": "CC Switch doesn't save Qoder sign-ins on its own. Add this one to switch between accounts here.",
"useAccount": "Use this account",
- "useAfterSave": "Use this provider’s default model after saving",
- "vision": "Image input"
+ "vision": "Image input",
+ "configJsonSchema": "The configuration must be a JSON object",
+ "modelSelectionHint": "These models appear in Qoder's /model list. Use Set as default in the More menu to choose Qoder's default.",
+ "officialCardManaged": "This card stands for a Qoder account in the Authorization Center. Sign in and remove accounts there.",
+ "providerDefaultModelHint": "Used when you set this provider as default from the More menu without picking a model.",
+ "empty": {
+ "title": "No Qoder providers yet",
+ "description": "Providers you add are written to settings.json of the current Qoder edition. Official accounts appear here after you sign in from the Authorization Center."
+ },
+ "official": {
+ "accountMissing": "This account is no longer in the Authorization Center",
+ "added": "Added {{name}}. Qoder now uses this account",
+ "adding": "Adding…",
+ "collectFirst": "Qoder is signed in as {{name}}, which isn't saved yet. Switching would overwrite that sign-in, so save it in the Authorization Center first.",
+ "removeHint": "Qoder can sign in to one account at a time. Add another official card to switch",
+ "statusLoading": "Loading accounts…"
+ }
}
}
diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json
index fbad11f9f..1e3c6a2d4 100644
--- a/src/i18n/locales/ja.json
+++ b/src/i18n/locales/ja.json
@@ -5745,11 +5745,8 @@
"accountCount": "保存済みアカウント: {{count}}",
"accountManagedByQoder": "認証センターでこのアカウントを管理または削除してください。",
"addAccount": "アカウントを追加",
- "addModel": "モデルを追加",
"apiKeyHint": "Leave empty for local services without authentication. Environment references such as ${ENV_NAME} are supported.",
"authType": "認証方式",
- "autoModel": "自動選択(Qoder 内蔵)",
- "baseUrl": "API エンドポイント",
"chinaEdition": "中国版",
"collectAccount": "CC Switch に追加",
"contextWindow": "コンテキスト長",
@@ -5758,15 +5755,10 @@
"deleteAccountConfirm": "「{{name}}」を CC Switch から削除しますか?CC Switch が保存したログイン情報だけを削除し、Qoder からはログアウトしません。他のアカウントとプロバイダー設定は残ります。",
"deleteAccountTitle": "Qoder アカウントを削除",
"deleteCurrentAccountConfirm": "現在のアカウント「{{name}}」を CC Switch から削除しますか?CC Switch が保存したログイン情報だけを削除し、Qoder はこのアカウントでログインしたままです。他のアカウントとプロバイダー設定は残ります。",
- "deleteProviderDescription": "Delete “{{name}}” and its models. If it is currently selected, the default model will return to automatic selection.",
- "deleteProviderTitle": "Delete provider",
"deleteSessionHint": "セッションの状態と履歴を整合させるため、Qoder CLI でセッションを削除してください。",
- "duplicateProvider": "This provider ID already exists",
"edition": "Qoder のエディション",
"editionHint": "{{edition}}のアカウントを管理しています。エディションは「アプリ」ページで切り替えます。",
- "editProviderTitle": "プロバイダーを編集",
"globalEdition": "国際版",
- "imported": "Qoder の現在のカスタムプロバイダーを読み込みました",
"invalidProviderId": "Start with a letter or digit and use only letters, digits, dots, underscores and dashes. Reserved names are not allowed.",
"loggedInAs": "ログイン中:{{name}}",
"loginBrowserFailed": "ブラウザーを開けませんでした。下のボタンで再試行してください。",
@@ -5778,22 +5770,10 @@
"loginWithBrowser": "Qoder にログイン",
"manageAccounts": "アカウントを管理",
"maxOutputTokens": "最大出力トークン",
- "modelId": "モデル ID",
- "modelName": "表示名",
- "modelNumber": "Model {{number}}",
- "models": "モデル一覧",
- "nothingToImport": "取り込めるカスタムプロバイダーがありません。「プロバイダーを追加」で作成してください。",
"officialAccount": "Qoder アカウント",
"officialAccountCn": "Qoder CN アカウント",
- "protocol": "API プロトコル",
"providerDefaultModel": "Provider default model",
- "providerId": "プロバイダー ID",
- "providerName": "プロバイダー名",
"refreshAccounts": "Qoder アカウントを更新",
- "removeModel": "Remove model {{number}}",
- "saved": "Qoder のモデル設定を保存しました",
- "selectModelAction": "既定のモデルを選択",
- "selectModelPlaceholder": "Select a model",
"signedIn": "ログイン済み",
"signedOut": "未ログイン",
"signInAgain": "再ログイン",
@@ -5806,7 +5786,22 @@
"uncollectedLogin": "Qoder は {{name}} でログイン中ですが、CC Switch には保存されていません",
"uncollectedLoginHint": "CC Switch は Qoder のログインを自動では保存しません。追加すると、ここでアカウントを切り替えられます。",
"useAccount": "このアカウントを使用",
- "useAfterSave": "Use this provider’s default model after saving",
- "vision": "画像入力"
+ "vision": "画像入力",
+ "configJsonSchema": "設定は JSON オブジェクトである必要があります",
+ "modelSelectionHint": "これらのモデルは Qoder の /model 一覧に表示されます。Qoder の既定モデルは「その他」メニューの「既定に設定」で選びます。",
+ "officialCardManaged": "このカードは認証センターの Qoder アカウントに対応します。ログインとアカウントの削除は認証センターで行います。",
+ "providerDefaultModelHint": "「その他」でこのプロバイダーを既定に設定し、モデルを選ばなかったときに使われます。",
+ "empty": {
+ "title": "Qoder のプロバイダーはまだありません",
+ "description": "追加したプロバイダーは現在の Qoder エディションの settings.json に書き込まれます。公式アカウントは認証センターでログインするとここに表示されます。"
+ },
+ "official": {
+ "accountMissing": "このアカウントは認証センターにありません",
+ "added": "{{name}} を追加しました。Qoder はこのアカウントに切り替わりました",
+ "adding": "追加中…",
+ "collectFirst": "Qoder は未登録の {{name}} でログイン中です。切り替えるとこのログインが上書きされるため、先に認証センターで登録してください。",
+ "removeHint": "Qoder は同時に 1 つのアカウントにしかログインできません。別の公式カードを追加すると切り替わります",
+ "statusLoading": "アカウントを読み込み中…"
+ }
}
}
diff --git a/src/i18n/locales/ko.json b/src/i18n/locales/ko.json
index e28e1cc08..69cf6dd76 100644
--- a/src/i18n/locales/ko.json
+++ b/src/i18n/locales/ko.json
@@ -5745,11 +5745,8 @@
"accountCount": "저장된 계정: {{count}}개",
"accountManagedByQoder": "인증 센터에서 이 계정을 관리하거나 제거하세요.",
"addAccount": "계정 추가",
- "addModel": "모델 추가",
"apiKeyHint": "인증이 없는 로컬 서비스는 비워 두세요. ${ENV_NAME} 같은 환경 변수 참조를 지원합니다.",
"authType": "인증 방식",
- "autoModel": "자동(Qoder 내장)",
- "baseUrl": "API 엔드포인트",
"chinaEdition": "중국판",
"collectAccount": "CC Switch에 추가",
"contextWindow": "컨텍스트 길이",
@@ -5758,15 +5755,10 @@
"deleteAccountConfirm": "CC Switch에서 “{{name}}”을(를) 제거할까요? CC Switch가 저장한 로그인 정보만 삭제되며 Qoder에서 로그아웃되지 않습니다. 다른 계정과 공급자 구성은 유지됩니다.",
"deleteAccountTitle": "Qoder 계정 제거",
"deleteCurrentAccountConfirm": "현재 계정 “{{name}}”을(를) CC Switch에서 제거할까요? CC Switch가 저장한 로그인 정보만 삭제되며 Qoder는 이 계정으로 로그인된 상태를 유지합니다. 다른 계정과 공급자 구성은 유지됩니다.",
- "deleteProviderDescription": "“{{name}}”과 해당 모델을 삭제합니다. 현재 선택된 공급자라면 기본 모델이 자동 선택으로 돌아갑니다.",
- "deleteProviderTitle": "공급자 삭제",
"deleteSessionHint": "세션 상태와 기록을 일치시키려면 Qoder CLI에서 세션을 삭제하세요.",
- "duplicateProvider": "이미 존재하는 공급자 ID입니다",
"edition": "Qoder 에디션",
"editionHint": "{{edition}} 계정을 관리하는 중입니다. 에디션은 앱 페이지에서 전환하세요.",
- "editProviderTitle": "공급자 편집",
"globalEdition": "글로벌판",
- "imported": "현재 Qoder 사용자 지정 공급자를 불러왔습니다",
"invalidProviderId": "영문자나 숫자로 시작하고 영문자, 숫자, 점, 밑줄, 하이픈만 사용하세요. 예약된 이름은 사용할 수 없습니다.",
"loggedInAs": "{{name}}(으)로 로그인됨",
"loginBrowserFailed": "브라우저를 열지 못했습니다. 아래 버튼으로 다시 시도하세요.",
@@ -5778,22 +5770,10 @@
"loginWithBrowser": "Qoder 로그인",
"manageAccounts": "계정 관리",
"maxOutputTokens": "최대 출력 토큰",
- "modelId": "모델 ID",
- "modelName": "표시 이름",
- "modelNumber": "모델 {{number}}",
- "models": "모델",
- "nothingToImport": "구성된 사용자 지정 공급자가 없습니다. 공급자 추가로 새로 만드세요.",
"officialAccount": "Qoder 계정",
"officialAccountCn": "Qoder CN 계정",
- "protocol": "API 프로토콜",
"providerDefaultModel": "공급자 기본 모델",
- "providerId": "공급자 ID",
- "providerName": "공급자 이름",
"refreshAccounts": "Qoder 계정 새로 고침",
- "removeModel": "모델 {{number}} 제거",
- "saved": "Qoder 모델 구성을 저장했습니다",
- "selectModelAction": "기본 모델 선택",
- "selectModelPlaceholder": "모델 선택",
"signedIn": "로그인됨",
"signedOut": "로그아웃됨",
"signInAgain": "다시 로그인",
@@ -5806,7 +5786,22 @@
"uncollectedLogin": "Qoder에 {{name}}(으)로 로그인되어 있지만 CC Switch에 저장되지 않았습니다",
"uncollectedLoginHint": "CC Switch는 Qoder 로그인을 자동으로 저장하지 않습니다. 추가하면 여기서 계정을 전환할 수 있습니다.",
"useAccount": "이 계정 사용",
- "useAfterSave": "저장 후 이 공급자의 기본 모델 사용",
- "vision": "이미지 입력"
+ "vision": "이미지 입력",
+ "configJsonSchema": "설정은 JSON 객체여야 합니다",
+ "modelSelectionHint": "이 모델들은 Qoder의 /model 목록에 표시됩니다. Qoder의 기본 모델은 「더 보기」 메뉴의 「기본값으로 설정」에서 고릅니다.",
+ "officialCardManaged": "이 카드는 인증 센터의 Qoder 계정 하나에 해당합니다. 로그인과 계정 삭제는 인증 센터에서 합니다.",
+ "providerDefaultModelHint": "「더 보기」에서 이 제공업체를 기본값으로 설정하면서 모델을 고르지 않았을 때 사용됩니다.",
+ "empty": {
+ "title": "아직 Qoder 제공업체가 없습니다",
+ "description": "추가한 제공업체는 현재 Qoder 에디션의 settings.json에 기록됩니다. 공식 계정은 인증 센터에서 로그인하면 여기에 표시됩니다."
+ },
+ "official": {
+ "accountMissing": "이 계정은 더 이상 인증 센터에 없습니다",
+ "added": "{{name}}을(를) 추가했습니다. Qoder가 이 계정으로 전환되었습니다",
+ "adding": "추가하는 중…",
+ "collectFirst": "Qoder가 아직 저장되지 않은 {{name}}(으)로 로그인되어 있습니다. 전환하면 이 로그인이 덮어써지므로 먼저 인증 센터에서 저장하세요.",
+ "removeHint": "Qoder는 한 번에 한 계정만 로그인할 수 있습니다. 다른 공식 카드를 추가하면 전환됩니다",
+ "statusLoading": "계정을 불러오는 중…"
+ }
}
}
diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json
index 4cd602e8b..54327763f 100644
--- a/src/i18n/locales/ru.json
+++ b/src/i18n/locales/ru.json
@@ -5743,11 +5743,8 @@
"accountCount": "Сохранено аккаунтов: {{count}}",
"accountManagedByQoder": "Управляйте этим аккаунтом или удалите его в центре авторизации.",
"addAccount": "Добавить аккаунт",
- "addModel": "Добавить модель",
"apiKeyHint": "Оставьте пустым для локальных сервисов без аутентификации. Поддерживаются ссылки на переменные окружения вида ${ENV_NAME}.",
"authType": "Аутентификация",
- "autoModel": "Автоматически (встроено в Qoder)",
- "baseUrl": "Адрес API",
"chinaEdition": "Китай",
"collectAccount": "Добавить в CC Switch",
"contextWindow": "Контекстное окно",
@@ -5756,15 +5753,10 @@
"deleteAccountConfirm": "Удалить «{{name}}» из CC Switch? Удаляются только данные входа, сохранённые CC Switch; выход из Qoder не выполняется. Другие аккаунты и конфигурации провайдеров сохраняются.",
"deleteAccountTitle": "Удалить аккаунт Qoder",
"deleteCurrentAccountConfirm": "Удалить текущий аккаунт «{{name}}» из CC Switch? Удаляются только данные входа, сохранённые CC Switch; Qoder останется авторизован под этим аккаунтом. Другие аккаунты и конфигурации провайдеров сохраняются.",
- "deleteProviderDescription": "Удалить «{{name}}» и его модели? Если он сейчас выбран, модель по умолчанию вернётся к автоматическому выбору.",
- "deleteProviderTitle": "Удалить провайдера",
"deleteSessionHint": "Удаляйте сессии в Qoder CLI, чтобы состояние и история сессий оставались согласованными.",
- "duplicateProvider": "Провайдер с таким ID уже существует",
"edition": "Редакция Qoder",
"editionHint": "Управляется редакция «{{edition}}». Редакцию можно сменить на странице «Приложения».",
- "editProviderTitle": "Изменить провайдера",
"globalEdition": "Международная",
- "imported": "Текущие пользовательские провайдеры Qoder загружены",
"invalidProviderId": "Начинайте с буквы или цифры и используйте только буквы, цифры, точки, подчёркивания и дефисы. Зарезервированные имена недопустимы.",
"loggedInAs": "Вход выполнен: {{name}}",
"loginBrowserFailed": "Не удалось открыть браузер. Повторите попытку кнопкой ниже.",
@@ -5776,22 +5768,10 @@
"loginWithBrowser": "Войти в Qoder",
"manageAccounts": "Управление аккаунтами",
"maxOutputTokens": "Максимум выходных токенов",
- "modelId": "ID модели",
- "modelName": "Отображаемое имя",
- "modelNumber": "Модель {{number}}",
- "models": "Модели",
- "nothingToImport": "Пользовательские провайдеры не настроены. Создайте их кнопкой «Добавить провайдера».",
"officialAccount": "Аккаунт Qoder",
"officialAccountCn": "Аккаунт Qoder CN",
- "protocol": "Протокол API",
"providerDefaultModel": "Модель провайдера по умолчанию",
- "providerId": "ID провайдера",
- "providerName": "Название провайдера",
"refreshAccounts": "Обновить аккаунты Qoder",
- "removeModel": "Удалить модель {{number}}",
- "saved": "Конфигурация моделей Qoder сохранена",
- "selectModelAction": "Выбрать модель по умолчанию",
- "selectModelPlaceholder": "Выберите модель",
"signedIn": "Вход выполнен",
"signedOut": "Вход не выполнен",
"signInAgain": "Войти снова",
@@ -5804,7 +5784,22 @@
"uncollectedLogin": "В Qoder выполнен вход как {{name}}, но этот аккаунт не сохранён в CC Switch",
"uncollectedLoginHint": "CC Switch не сохраняет входы Qoder автоматически. Добавьте этот вход, чтобы переключать аккаунты здесь.",
"useAccount": "Использовать этот аккаунт",
- "useAfterSave": "После сохранения использовать модель этого провайдера по умолчанию",
- "vision": "Ввод изображений"
+ "vision": "Ввод изображений",
+ "configJsonSchema": "Конфигурация должна быть JSON-объектом",
+ "modelSelectionHint": "Эти модели появятся в списке /model в Qoder. Модель по умолчанию выбирается через «Сделать по умолчанию» в меню «Ещё».",
+ "officialCardManaged": "Эта карточка соответствует аккаунту Qoder в центре авторизации. Входить и удалять аккаунты нужно там.",
+ "providerDefaultModelHint": "Используется, если сделать этого провайдера моделью по умолчанию в меню «Ещё», не выбрав модель.",
+ "empty": {
+ "title": "Провайдеров Qoder пока нет",
+ "description": "Добавленные провайдеры записываются в settings.json текущей редакции Qoder. Официальные аккаунты появятся здесь после входа в центре авторизации."
+ },
+ "official": {
+ "accountMissing": "Этого аккаунта больше нет в центре авторизации",
+ "added": "{{name}} добавлен. Qoder теперь использует этот аккаунт",
+ "adding": "Добавление…",
+ "collectFirst": "В Qoder выполнен вход как {{name}}, и этот аккаунт ещё не сохранён. Переключение перезапишет вход, поэтому сначала сохраните его в центре авторизации.",
+ "removeHint": "Qoder может быть авторизован только в одном аккаунте. Добавьте другую официальную карточку, чтобы переключиться",
+ "statusLoading": "Загрузка аккаунтов…"
+ }
}
}
diff --git a/src/i18n/locales/tr.json b/src/i18n/locales/tr.json
index 766fea853..0e88d3fab 100644
--- a/src/i18n/locales/tr.json
+++ b/src/i18n/locales/tr.json
@@ -5745,11 +5745,8 @@
"accountCount": "Kayıtlı hesaplar: {{count}}",
"accountManagedByQoder": "Bu hesabı Yetkilendirme Merkezi üzerinden yönetin veya kaldırın.",
"addAccount": "Hesap ekle",
- "addModel": "Model ekle",
"apiKeyHint": "Leave empty for local services without authentication. Environment references such as ${ENV_NAME} are supported.",
"authType": "Kimlik doğrulama",
- "autoModel": "Otomatik (Qoder yerleşik)",
- "baseUrl": "API adresi",
"chinaEdition": "Çin",
"collectAccount": "CC Switch'e ekle",
"contextWindow": "Bağlam penceresi",
@@ -5758,15 +5755,10 @@
"deleteAccountConfirm": "“{{name}}” CC Switch'ten kaldırılsın mı? Yalnızca CC Switch'in kaydettiği oturum bilgisi silinir; Qoder'dan çıkış yapılmaz. Diğer hesaplar ve sağlayıcı yapılandırmaları korunur.",
"deleteAccountTitle": "Qoder hesabını kaldır",
"deleteCurrentAccountConfirm": "Geçerli hesap “{{name}}” CC Switch'ten kaldırılsın mı? Yalnızca CC Switch'in kaydettiği oturum bilgisi silinir; Qoder bu hesapla oturum açık kalır. Diğer hesaplar ve sağlayıcı yapılandırmaları korunur.",
- "deleteProviderDescription": "Delete “{{name}}” and its models. If it is currently selected, the default model will return to automatic selection.",
- "deleteProviderTitle": "Delete provider",
"deleteSessionHint": "Oturum durumu ile geçmişi tutarlı tutmak için oturumları Qoder CLI içinde silin.",
- "duplicateProvider": "This provider ID already exists",
"edition": "Qoder sürümü",
"editionHint": "{{edition}} sürümü yönetiliyor. Sürümü Uygulamalar sayfasından değiştirin.",
- "editProviderTitle": "Sağlayıcıyı düzenle",
"globalEdition": "Global",
- "imported": "Qoder özel sağlayıcı yapılandırması yüklendi",
"invalidProviderId": "Start with a letter or digit and use only letters, digits, dots, underscores and dashes. Reserved names are not allowed.",
"loggedInAs": "Oturum açık: {{name}}",
"loginBrowserFailed": "Tarayıcı açılamadı. Aşağıdaki düğmeyle yeniden deneyin.",
@@ -5778,22 +5770,10 @@
"loginWithBrowser": "Qoder hesabına giriş yap",
"manageAccounts": "Hesapları yönet",
"maxOutputTokens": "En fazla çıktı tokenı",
- "modelId": "Model kimliği",
- "modelName": "Görünen ad",
- "modelNumber": "Model {{number}}",
- "models": "Modeller",
- "nothingToImport": "İçe aktarılacak özel sağlayıcı yok. Yeni bir sağlayıcı ekleyin.",
"officialAccount": "Qoder Hesabı",
"officialAccountCn": "Qoder CN Hesabı",
- "protocol": "API protokolü",
"providerDefaultModel": "Provider default model",
- "providerId": "Sağlayıcı kimliği",
- "providerName": "Sağlayıcı adı",
"refreshAccounts": "Qoder hesaplarını yenile",
- "removeModel": "Remove model {{number}}",
- "saved": "Qoder model yapılandırması kaydedildi",
- "selectModelAction": "Varsayılan modeli seç",
- "selectModelPlaceholder": "Select a model",
"signedIn": "Oturum açık",
"signedOut": "Giriş yapılmadı",
"signInAgain": "Yeniden giriş yap",
@@ -5806,7 +5786,22 @@
"uncollectedLogin": "Qoder'da {{name}} olarak oturum açık, ancak bu hesap CC Switch'e kaydedilmemiş",
"uncollectedLoginHint": "CC Switch, Qoder oturumlarını kendiliğinden kaydetmez. Hesaplar arasında buradan geçmek için bunu ekleyin.",
"useAccount": "Bu hesabı kullan",
- "useAfterSave": "Use this provider’s default model after saving",
- "vision": "Görsel girdisi"
+ "vision": "Görsel girdisi",
+ "configJsonSchema": "Yapılandırma bir JSON nesnesi olmalıdır",
+ "modelSelectionHint": "Bu modeller Qoder'ın /model listesinde görünür. Qoder'ın varsayılanını Diğer menüsündeki Varsayılan yap ile seçin.",
+ "officialCardManaged": "Bu kart Yetkilendirme Merkezi'ndeki bir Qoder hesabını temsil eder. Oturum açma ve hesap kaldırma orada yapılır.",
+ "providerDefaultModelHint": "Diğer menüsünden bu sağlayıcıyı model seçmeden varsayılan yaptığınızda kullanılır.",
+ "empty": {
+ "title": "Henüz Qoder sağlayıcısı yok",
+ "description": "Eklediğiniz sağlayıcılar geçerli Qoder sürümünün settings.json dosyasına yazılır. Resmi hesaplar Yetkilendirme Merkezi'nden oturum açtıktan sonra burada görünür."
+ },
+ "official": {
+ "accountMissing": "Bu hesap artık Yetkilendirme Merkezi'nde değil",
+ "added": "{{name}} eklendi. Qoder artık bu hesabı kullanıyor",
+ "adding": "Ekleniyor…",
+ "collectFirst": "Qoder henüz kaydedilmemiş {{name}} ile oturum açmış. Geçiş bu oturumun üzerine yazar; önce Yetkilendirme Merkezi'nde kaydedin.",
+ "removeHint": "Qoder aynı anda yalnızca bir hesapta oturum açabilir. Geçmek için başka bir resmi kart ekleyin",
+ "statusLoading": "Hesaplar yükleniyor…"
+ }
}
}
diff --git a/src/i18n/locales/zh-TW.json b/src/i18n/locales/zh-TW.json
index 401f8680e..763adf37e 100644
--- a/src/i18n/locales/zh-TW.json
+++ b/src/i18n/locales/zh-TW.json
@@ -5745,11 +5745,8 @@
"accountCount": "已儲存 {{count}} 個帳號",
"accountManagedByQoder": "請在授權中心管理或刪除此帳號。",
"addAccount": "新增帳號",
- "addModel": "新增模型",
"apiKeyHint": "本地免认证服务可留空,也支持 ${ENV_NAME} 环境变量引用。",
"authType": "认证方式",
- "autoModel": "自動選擇(Qoder 內建)",
- "baseUrl": "API 地址",
"chinaEdition": "國內版",
"collectAccount": "收錄到 CC Switch",
"contextWindow": "上下文長度",
@@ -5758,15 +5755,10 @@
"deleteAccountConfirm": "確定從 CC Switch 移除帳號「{{name}}」?只刪除 CC Switch 儲存的登入資訊,不會登出 Qoder,其他帳號和供應商設定保留。",
"deleteAccountTitle": "移除 Qoder 帳號",
"deleteCurrentAccountConfirm": "確定從 CC Switch 移除目前帳號「{{name}}」?只刪除 CC Switch 儲存的登入資訊,Qoder 仍保持此帳號登入,其他帳號和供應商設定保留。",
- "deleteProviderDescription": "删除“{{name}}”及其模型。若当前使用此供应商,默认模型将切回自动选择。",
- "deleteProviderTitle": "删除供应商",
"deleteSessionHint": "請在 Qoder CLI 中刪除工作階段,以同時更新工作階段狀態和歷史。",
- "duplicateProvider": "该供应商 ID 已存在",
"edition": "Qoder 版本",
"editionHint": "目前管理{{edition}}帳號,可在「應用」頁切換版本。",
- "editProviderTitle": "編輯供應商",
"globalEdition": "國際版",
- "imported": "已讀取 Qoder 目前的自訂供應商設定",
"invalidProviderId": "以字母或数字开头,只能包含字母、数字、点、下划线和连字符,不能使用保留名称。",
"loggedInAs": "已登入:{{name}}",
"loginBrowserFailed": "無法開啟瀏覽器,請點擊下方按鈕重試。",
@@ -5778,22 +5770,10 @@
"loginWithBrowser": "登入 Qoder",
"manageAccounts": "管理帳號",
"maxOutputTokens": "最大輸出 Token",
- "modelId": "模型 ID",
- "modelName": "显示名称",
- "modelNumber": "模型 {{number}}",
- "models": "模型清單",
- "nothingToImport": "目前沒有可匯入的自訂供應商,請點選「新增供應商」。",
"officialAccount": "Qoder 官方帳號",
"officialAccountCn": "Qoder 國內版官方帳號",
- "protocol": "API 协议",
"providerDefaultModel": "供应商默认模型",
- "providerId": "供應商 ID",
- "providerName": "供應商名稱",
"refreshAccounts": "重新整理 Qoder 帳號",
- "removeModel": "移除模型 {{number}}",
- "saved": "Qoder 模型設定已儲存",
- "selectModelAction": "選擇預設模型",
- "selectModelPlaceholder": "选择模型",
"signedIn": "已登入",
"signedOut": "尚未登入",
"signInAgain": "重新登入",
@@ -5806,7 +5786,22 @@
"uncollectedLogin": "Qoder 目前登入的 {{name}} 尚未收錄到 CC Switch",
"uncollectedLoginHint": "CC Switch 不會自動收錄 Qoder 的登入。收錄後即可在這裡切換帳號。",
"useAccount": "使用此帳號",
- "useAfterSave": "保存后将此供应商的默认模型设为当前模型",
- "vision": "圖片輸入"
+ "vision": "圖片輸入",
+ "configJsonSchema": "設定必須是一個 JSON 物件",
+ "modelSelectionHint": "這些模型會出現在 Qoder 的 /model 清單中。在「更多」選單的「設為預設」裡選擇 Qoder 預設使用哪一個。",
+ "officialCardManaged": "這張卡對應授權中心裡的一個 Qoder 帳號,登入和移除帳號都在授權中心。",
+ "providerDefaultModelHint": "在「更多」裡把這家設為預設、又沒選具體模型時使用它。",
+ "empty": {
+ "title": "還沒有 Qoder 供應商",
+ "description": "新增的模型供應商會寫入目前版本 Qoder 的 settings.json;官方帳號在授權中心登入後會出現在這裡。"
+ },
+ "official": {
+ "accountMissing": "這個帳號已不在授權中心",
+ "added": "已新增 {{name}},Qoder 已切換到這個帳號",
+ "adding": "正在新增…",
+ "collectFirst": "Qoder 目前登入的 {{name}} 尚未收錄,切換會覆蓋它的登入。請先在授權中心收錄。",
+ "removeHint": "Qoder 同時只能登入一個帳號,新增另一張官方卡即可切換",
+ "statusLoading": "正在讀取帳號…"
+ }
}
}
diff --git a/src/i18n/locales/zh.json b/src/i18n/locales/zh.json
index b14300e0d..fe72ad158 100644
--- a/src/i18n/locales/zh.json
+++ b/src/i18n/locales/zh.json
@@ -5745,11 +5745,8 @@
"accountCount": "已保存 {{count}} 个账号",
"accountManagedByQoder": "请在授权中心管理或删除此账号。",
"addAccount": "添加账号",
- "addModel": "添加模型",
"apiKeyHint": "本地免认证服务可留空,也支持 ${ENV_NAME} 环境变量引用。",
"authType": "认证方式",
- "autoModel": "自动选择(Qoder 内置)",
- "baseUrl": "API 地址",
"chinaEdition": "国内版",
"collectAccount": "收录到 CC Switch",
"contextWindow": "上下文长度",
@@ -5758,15 +5755,10 @@
"deleteAccountConfirm": "确定从 CC Switch 移除账号「{{name}}」?只删除 CC Switch 保存的登录信息,不会退出 Qoder,其他账号和供应商配置保留。",
"deleteAccountTitle": "移除 Qoder 账号",
"deleteCurrentAccountConfirm": "确定从 CC Switch 移除当前账号「{{name}}」?只删除 CC Switch 保存的登录信息,Qoder 仍保持此账号登录,其他账号和供应商配置保留。",
- "deleteProviderDescription": "删除“{{name}}”及其模型。若当前使用此供应商,默认模型将切回自动选择。",
- "deleteProviderTitle": "删除供应商",
"deleteSessionHint": "请在 Qoder CLI 中删除会话,以同时更新会话状态和历史。",
- "duplicateProvider": "该供应商 ID 已存在",
"edition": "Qoder 版本",
"editionHint": "当前管理{{edition}}账号,可在「应用」页切换版本。",
- "editProviderTitle": "编辑供应商",
"globalEdition": "国际版",
- "imported": "已读取 Qoder 当前自定义供应商配置",
"invalidProviderId": "以字母或数字开头,只能包含字母、数字、点、下划线和连字符,不能使用保留名称。",
"loggedInAs": "已登录:{{name}}",
"loginBrowserFailed": "未能打开浏览器,请点击下方按钮重试。",
@@ -5778,22 +5770,10 @@
"loginWithBrowser": "登录 Qoder",
"manageAccounts": "管理账号",
"maxOutputTokens": "最大输出 Token",
- "modelId": "模型 ID",
- "modelName": "显示名称",
- "modelNumber": "模型 {{number}}",
- "models": "模型列表",
- "nothingToImport": "当前没有可导入的自定义供应商,请点击“添加供应商”。",
"officialAccount": "Qoder 官方账号",
"officialAccountCn": "Qoder 国内版官方账号",
- "protocol": "API 协议",
"providerDefaultModel": "供应商默认模型",
- "providerId": "供应商 ID",
- "providerName": "供应商名称",
"refreshAccounts": "刷新 Qoder 账号",
- "removeModel": "移除模型 {{number}}",
- "saved": "Qoder 模型配置已保存",
- "selectModelAction": "选择默认模型",
- "selectModelPlaceholder": "选择模型",
"signedIn": "已登录",
"signedOut": "未登录",
"signInAgain": "重新登录",
@@ -5806,7 +5786,22 @@
"uncollectedLogin": "Qoder 当前登录的 {{name}} 尚未收录到 CC Switch",
"uncollectedLoginHint": "CC Switch 不会自动收录 Qoder 的登录。收录后即可在这里切换账号。",
"useAccount": "使用此账号",
- "useAfterSave": "保存后将此供应商的默认模型设为当前模型",
- "vision": "图片输入"
+ "vision": "图片输入",
+ "configJsonSchema": "配置必须是一个 JSON 对象",
+ "modelSelectionHint": "这些模型会出现在 Qoder 的 /model 列表里。在「更多」菜单的「设为默认」里选 Qoder 默认用哪个。",
+ "officialCardManaged": "这张卡对应授权中心里的一个 Qoder 账号,登录和移除账号都在授权中心。",
+ "providerDefaultModelHint": "在「更多」里把这家设为默认、又没选具体模型时用它。",
+ "empty": {
+ "title": "还没有 Qoder 供应商",
+ "description": "添加的模型供应商会写进当前版本 Qoder 的 settings.json;官方账号在授权中心登录后会出现在这里。"
+ },
+ "official": {
+ "accountMissing": "这个账号已不在授权中心",
+ "added": "已添加 {{name}},Qoder 已切换到这个账号",
+ "adding": "正在添加…",
+ "collectFirst": "Qoder 现在登着还没收录的 {{name}},切换会覆盖它的登录。请先在授权中心收录。",
+ "removeHint": "Qoder 同时只能登录一个账号,添加另一张官方卡即可切换",
+ "statusLoading": "正在读取账号…"
+ }
}
}
diff --git a/src/lib/api/qoder.ts b/src/lib/api/qoder.ts
index 1a0219518..221549e97 100644
--- a/src/lib/api/qoder.ts
+++ b/src/lib/api/qoder.ts
@@ -1,5 +1,4 @@
import { invoke } from "@tauri-apps/api/core";
-import type { ProviderMeta, UsageScript } from "@/types";
import type { QoderEdition } from "@/config/qoder";
export interface QoderModel {
@@ -30,12 +29,6 @@ export interface QoderProvider {
models?: QoderModel[];
[key: string]: unknown;
}
-export interface QoderModels {
- providers: Record<string, QoderProvider>;
- currentModel: string;
- metadata?: Record<string, ProviderMeta>;
-}
-
export interface QoderAuthStatus {
installed: boolean;
loggedIn: boolean;
@@ -68,7 +61,6 @@ export interface QoderLoginProgress {
*/
export const qoderKeys = {
all: ["qoder"] as const,
- models: (edition: QoderEdition) => ["qoder", "models", edition] as const,
auth: (edition: QoderEdition) => ["qoder", "auth", edition] as const,
login: (edition: QoderEdition, flowId: string | null) =>
["qoder", "login", edition, flowId] as const,
@@ -89,23 +81,10 @@ export const qoderApi = {
/** 只从 CC Switch 的账号列表里删掉,不会在 Qoder 里登出 */
deleteAccount: (accountId: string) =>
invoke<QoderAuthStatus>("delete_qoder_account", { accountId }),
- saveUsageScript: (id: string, script: UsageScript) =>
- invoke<QoderModels>("save_qoder_usage_script", { id, script }),
- getModels: () => invoke<QoderModels>("get_qoder_models"),
- saveProvider: (
- id: string,
- provider: QoderProvider,
- expected: QoderProvider | null,
- makeDefault: boolean,
- ) =>
- invoke<QoderModels>("save_qoder_provider", {
- id,
- provider,
- expected,
- makeDefault,
+ /** 设为默认:自定义卡把 `model.name` 指到它的模型(不传 model 用它自己的默认模型),官方卡改成 auto */
+ setDefaultModel: (providerId: string, model?: string) =>
+ invoke<void>("set_qoder_default_model", {
+ providerId,
+ model: model ?? null,
}),
- deleteProvider: (id: string, expected: QoderProvider) =>
- invoke<QoderModels>("delete_qoder_provider", { id, expected }),
- setModel: (model: string) =>
- invoke<QoderModels>("set_qoder_model", { model }),
};
diff --git a/src/lib/query/mutations.ts b/src/lib/query/mutations.ts
index b2791d3ec..ea50c6559 100644
--- a/src/lib/query/mutations.ts
+++ b/src/lib/query/mutations.ts
@@ -283,10 +283,10 @@ export const useUpdateProviderMutation = (appId: AppId) => {
await invalidatePiProviderCaches(queryClient, appId);
} else if (appId === "agy") {
await invalidateAgyLoginCaches(queryClient);
- } else if (appId === "kimi") {
- // 默认模型可能在 Kimi Code 里改过:失败时也重读,页面上的「默认」才跟得上
+ } else if (appId === "kimi" || appId === "qoder") {
+ // 默认模型可能在 Kimi Code / Qoder 里改过:失败时也重读,页面上的「默认」才跟得上
await queryClient.invalidateQueries({
- queryKey: ["providers", "kimi"],
+ queryKey: ["providers", appId],
});
} else if (appId === "grokbuild") {
// 保存当前绑号的 Grok 官方卡会把原 CLI 登录收进授权中心再写入绑定的号;
@@ -380,10 +380,10 @@ export const useDeleteProviderMutation = (appId: AppId) => {
onSettled: async () => {
if (appHas(appId, "piFamily")) {
await invalidatePiProviderCaches(queryClient, appId);
- } else if (appId === "kimi") {
- // 默认模型可能在 Kimi Code 里改过:失败时也重读,页面上的「默认」才跟得上
+ } else if (appId === "kimi" || appId === "qoder") {
+ // 默认模型可能在 Kimi Code / Qoder 里改过:失败时也重读,页面上的「默认」才跟得上
await queryClient.invalidateQueries({
- queryKey: ["providers", "kimi"],
+ queryKey: ["providers", appId],
});
}
},
diff --git a/src/lib/query/qoder.ts b/src/lib/query/qoder.ts
new file mode 100644
index 000000000..e01b36b79
--- /dev/null
+++ b/src/lib/query/qoder.ts
@@ -0,0 +1,83 @@
+import { useCallback, useMemo } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useTranslation } from "react-i18next";
+import { providersApi } from "@/lib/api";
+import { qoderApi, qoderKeys } from "@/lib/api/qoder";
+import { useQoderEdition } from "@/hooks/useQoderEdition";
+import { resolveManagedAccountId } from "@/lib/authBinding";
+import { toast } from "@/lib/toast";
+import type { Provider } from "@/types";
+import type { QoderAccountsState } from "@/components/providers/presentation";
+import { extractErrorMessage } from "@/utils/errorUtils";
+
+/**
+ * 供应商列表里 Qoder 官方账号卡要的东西:授权中心收录的账号、Qoder 现在登着的号(和授权中心
+ * 共用同一份查询),以及卡片上的「添加」=把 Qoder 的登录切到卡片绑定的号。
+ */
+export function useQoderOfficialCards(enabled: boolean): {
+ state: QoderAccountsState;
+ switchAccount: (provider: Provider) => void;
+} {
+ const { t } = useTranslation();
+ const queryClient = useQueryClient();
+ const edition = useQoderEdition();
+ const status = useQuery({
+ queryKey: qoderKeys.auth(edition ?? "global"),
+ queryFn: () => qoderApi.getAuthStatus(),
+ enabled: enabled && Boolean(edition),
+ retry: false,
+ staleTime: 30_000,
+ // Qoder 里 /login 换号也要跟上
+ refetchInterval: enabled ? 30_000 : false,
+ });
+
+ const mutation = useMutation({
+ mutationFn: async (provider: Provider) => {
+ const accountId = resolveManagedAccountId(provider.meta, "qoder_oauth");
+ if (!accountId) throw new Error(t("qoder.official.accountMissing"));
+ return qoderApi.useAccount(accountId);
+ },
+ onSuccess: (result, provider) => {
+ if (edition) queryClient.setQueryData(qoderKeys.auth(edition), result);
+ toast.success(t("qoder.official.added", { name: provider.name }), {
+ closeButton: true,
+ });
+ },
+ onError: (error) => {
+ toast.error(
+ t("notifications.addFailed", {
+ error: extractErrorMessage(error) || String(error),
+ }),
+ { closeButton: true },
+ );
+ },
+ onSettled: async () => {
+ await queryClient.invalidateQueries({ queryKey: ["providers", "qoder"] });
+ await providersApi.updateTrayMenu().catch(() => {});
+ },
+ });
+
+ const data = status.data;
+ const state = useMemo<QoderAccountsState>(
+ () => ({
+ status: status.isSuccess ? "ready" : status.isError ? "error" : "loading",
+ currentAccountId: data?.currentAccountId ?? null,
+ accountIds: (data?.accounts ?? []).map((account) => account.id),
+ uncollectedLogin: data?.uncollectedLogin ?? null,
+ switchingId: mutation.isPending ? mutation.variables?.id : null,
+ }),
+ [
+ status.isSuccess,
+ status.isError,
+ data,
+ mutation.isPending,
+ mutation.variables,
+ ],
+ );
+ const { mutate } = mutation;
+ const switchAccount = useCallback(
+ (provider: Provider) => mutate(provider),
+ [mutate],
+ );
+ return { state, switchAccount };
+}
diff --git a/tests/components/QoderAccountLogin.test.tsx b/tests/components/QoderAccountLogin.test.tsx
new file mode 100644
index 000000000..96e09305f
--- /dev/null
+++ b/tests/components/QoderAccountLogin.test.tsx
@@ -0,0 +1,777 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, render, screen, waitFor, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { AuthCenterPanel } from "@/components/settings/AuthCenterPanel";
+import { APP_IDS } from "@/config/appSpecs";
+import type { QoderEdition } from "@/config/qoder";
+import type { QoderAuthStatus, QoderLoginProgress } from "@/lib/api/qoder";
+import { writeAuthOpenBrowser } from "@/lib/authLoginLink";
+
+const mocks = vi.hoisted(() => ({ invoke: vi.fn(), copy: vi.fn() }));
+vi.mock("@tauri-apps/api/core", () => ({ invoke: mocks.invoke }));
+vi.mock("@/lib/clipboard", () => ({ copyText: mocks.copy }));
+
+// The backend serves whichever edition settings select; each edition keeps its
+// own saved accounts, so the fixtures hold one auth state per edition.
+let active: QoderEdition = "cn";
+let authState: Record<QoderEdition, QoderAuthStatus>;
+let loginProgress: Record<QoderEdition, QoderLoginProgress>;
+
+const editions = ["global", "cn"] as const;
+const otherEdition = (edition: QoderEdition): QoderEdition =>
+ edition === "global" ? "cn" : "global";
+
+/**
+ * Mount the Authorization Center with only Qoder visible in the sidebar, so the
+ * other services' cards stay out of the way.
+ */
+function mount(edition: QoderEdition = "cn") {
+ active = edition;
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ const invalidate = vi.spyOn(client, "invalidateQueries");
+ const view = render(
+ <QueryClientProvider client={client}>
+ <AuthCenterPanel />
+ </QueryClientProvider>,
+ );
+ return { ...view, client, invalidate };
+}
+
+const invalidatedProviderCards = (invalidate: {
+ mock: { calls: readonly unknown[][] };
+}) =>
+ invalidate.mock.calls.some(
+ ([filters]) =>
+ JSON.stringify((filters as { queryKey?: unknown })?.queryKey) ===
+ JSON.stringify(["providers", "qoder"]),
+ );
+
+function savedAccounts(edition: QoderEdition) {
+ authState[edition] = {
+ installed: true,
+ loggedIn: true,
+ username: "Existing account",
+ currentAccountId: "existing",
+ accounts: [
+ {
+ id: "existing",
+ username: "Existing account",
+ plan: "Pro",
+ isCurrent: true,
+ },
+ {
+ id: "saved",
+ username: "Saved account",
+ plan: "Free",
+ isCurrent: false,
+ },
+ ],
+ };
+}
+
+const accountRow = (name: string) =>
+ within(screen.getByRole("list"))
+ .getAllByRole("listitem")
+ .find((row) => within(row).queryByText(name))!;
+
+beforeAll(() => {
+ Element.prototype.scrollIntoView ??= vi.fn();
+ window.matchMedia ??= vi.fn().mockReturnValue({
+ matches: false,
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ });
+});
+
+beforeEach(() => {
+ authState = {
+ global: { installed: true, loggedIn: false },
+ cn: { installed: true, loggedIn: false },
+ };
+ loginProgress = {
+ global: { complete: false },
+ cn: { complete: false },
+ };
+ mocks.invoke
+ .mockReset()
+ .mockImplementation(
+ async (command: string, args: Record<string, unknown> = {}) => {
+ // Qoder is one app: the backend picks the edition, the UI never sends it.
+ if (command.includes("qoder")) {
+ expect(args).not.toHaveProperty("app");
+ expect(args).not.toHaveProperty("edition");
+ }
+ const edition = active;
+ if (command === "get_settings")
+ return {
+ qoderEdition: edition,
+ visibleApps: Object.fromEntries(
+ APP_IDS.map((app) => [app, app === "qoder"]),
+ ),
+ };
+ // Every card mounts once before settings arrive and hide the other
+ // services; their provider queries just need an empty answer.
+ if (command === "get_providers") return {};
+ if (command === "get_current_provider") return "";
+ if (command === "get_qoder_auth_status")
+ return structuredClone(authState[edition]);
+ if (command === "use_qoder_account") {
+ const account = authState[edition].accounts!.find(
+ (item) => item.id === args.accountId,
+ )!;
+ authState[edition] = {
+ ...authState[edition],
+ loggedIn: true,
+ username: account.username,
+ email: account.email,
+ plan: account.plan,
+ currentAccountId: account.id,
+ accounts: authState[edition].accounts!.map((item) => ({
+ ...item,
+ isCurrent: item.id === account.id,
+ })),
+ };
+ return structuredClone(authState[edition]);
+ }
+ if (command === "delete_qoder_account") {
+ const account = authState[edition].accounts!.find(
+ (item) => item.id === args.accountId,
+ )!;
+ authState[edition].accounts = authState[edition].accounts!.filter(
+ (item) => item.id !== account.id,
+ );
+ if (account.isCurrent)
+ Object.assign(authState[edition], {
+ loggedIn: false,
+ currentAccountId: null,
+ username: null,
+ email: null,
+ plan: null,
+ });
+ return structuredClone(authState[edition]);
+ }
+ if (command === "import_current_qoder_account") {
+ const name = authState[edition].uncollectedLogin!;
+ const account = {
+ id: "collected",
+ username: name,
+ email: null,
+ plan: null,
+ isCurrent: true,
+ };
+ authState[edition] = {
+ ...authState[edition],
+ uncollectedLogin: null,
+ loggedIn: true,
+ username: name,
+ currentAccountId: account.id,
+ accounts: [...(authState[edition].accounts ?? []), account],
+ };
+ return structuredClone(authState[edition]);
+ }
+ if (command === "start_qoder_login") return `${edition}-login`;
+ if (command === "poll_qoder_login")
+ return structuredClone(loginProgress[edition]);
+ if (command === "cancel_qoder_login" || command === "open_external")
+ return;
+ throw new Error(
+ `Unexpected command: ${command} ${JSON.stringify(args)}`,
+ );
+ },
+ );
+});
+
+describe("Qoder accounts in the Authorization Center", () => {
+ it.each(editions)(
+ "signs in a new %s account in the browser and refreshes the provider cards",
+ async (edition) => {
+ const url =
+ edition === "global"
+ ? "https://qoder.com/login?code=fixture"
+ : "https://qoder.com.cn/login?code=fixture";
+ loginProgress[edition] = { complete: false, authUrl: url };
+ const user = userEvent.setup();
+ const { invalidate } = mount(edition);
+ expect(await screen.findByText("qoder.signedOut")).toBeInTheDocument();
+ await user.click(
+ screen.getByRole("button", { name: "qoder.loginWithBrowser" }),
+ );
+ await waitFor(() =>
+ expect(mocks.invoke).toHaveBeenCalledWith("start_qoder_login", {
+ accountId: null,
+ }),
+ );
+ await waitFor(() =>
+ expect(mocks.invoke).toHaveBeenCalledWith("open_external", { url }),
+ );
+ expect(screen.getByText("qoder.loginWaiting")).toBeInTheDocument();
+ authState[edition] = {
+ installed: true,
+ loggedIn: false,
+ accounts: [
+ {
+ id: "new-account",
+ username: "Fixture Account",
+ plan: "Pro",
+ isCurrent: false,
+ },
+ ],
+ };
+ loginProgress[edition] = { complete: true, accountId: "new-account" };
+ await screen.findByText("Fixture Account", {}, { timeout: 4000 });
+ await waitFor(() =>
+ expect(
+ screen.queryByText("qoder.loginWaiting"),
+ ).not.toBeInTheDocument(),
+ );
+ expect(mocks.invoke).toHaveBeenCalledWith("cancel_qoder_login", {
+ flowId: `${edition}-login`,
+ });
+ expect(invalidatedProviderCards(invalidate)).toBe(true);
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+ // A new login never switches Qoder over by itself.
+ expect(mocks.invoke).not.toHaveBeenCalledWith(
+ "use_qoder_account",
+ expect.anything(),
+ );
+ invalidate.mockClear();
+ await user.click(
+ screen.getByRole("button", { name: "qoder.useAccount" }),
+ );
+ await waitFor(() =>
+ expect(mocks.invoke).toHaveBeenCalledWith("use_qoder_account", {
+ accountId: "new-account",
+ }),
+ );
+ await screen.findByText("qoder.currentAccount");
+ expect(invalidatedProviderCards(invalidate)).toBe(true);
+ expect(authState[otherEdition(edition)].loggedIn).toBe(false);
+ expect(
+ mocks.invoke.mock.calls.filter(
+ ([command]) => command === "open_external",
+ ),
+ ).toHaveLength(1);
+ },
+ );
+
+ it("only copies the login link when the Authorization Center keeps the browser closed", async () => {
+ const url = "https://qoder.com.cn/login?code=fixture";
+ loginProgress.cn = { complete: false, authUrl: url };
+ writeAuthOpenBrowser(false);
+ try {
+ const user = userEvent.setup();
+ mount("cn");
+ await user.click(
+ await screen.findByRole("button", { name: "qoder.loginWithBrowser" }),
+ );
+ await waitFor(() => expect(mocks.copy).toHaveBeenCalledWith(url));
+ expect(mocks.invoke).not.toHaveBeenCalledWith(
+ "open_external",
+ expect.anything(),
+ );
+ // 用户自己点「打开登录页面」时照样打开浏览器
+ await user.click(
+ await screen.findByRole("button", { name: "qoder.loginOpenBrowser" }),
+ );
+ await waitFor(() =>
+ expect(mocks.invoke).toHaveBeenCalledWith("open_external", { url }),
+ );
+ } finally {
+ writeAuthOpenBrowser(true);
+ }
+ });
+
+ it("reports a completed login whose account did not show up", async () => {
+ const user = userEvent.setup();
+ mount("cn");
+ await user.click(
+ await screen.findByRole("button", { name: "qoder.loginWithBrowser" }),
+ );
+ await waitFor(() =>
+ expect(mocks.invoke).toHaveBeenCalledWith("poll_qoder_login", {
+ flowId: "cn-login",
+ }),
+ );
+ loginProgress.cn = { complete: true, accountId: "missing" };
+ expect(
+ await screen.findByRole("alert", {}, { timeout: 4000 }),
+ ).toHaveTextContent("qoder.loginNotConfirmed");
+ expect(
+ screen.getByRole("button", { name: "qoder.loginWithBrowser" }),
+ ).toBeEnabled();
+ });
+
+ it.each(editions)(
+ "shows only the %s edition selected in settings",
+ async (edition) => {
+ const other = otherEdition(edition);
+ authState[edition].accounts = [
+ { id: "mine", username: "Selected account", isCurrent: false },
+ ];
+ authState[other].accounts = [
+ { id: "theirs", username: "Other edition account", isCurrent: false },
+ ];
+ const user = userEvent.setup();
+ mount(edition);
+ await screen.findByText("Selected account");
+ expect(
+ screen.queryByText("Other edition account"),
+ ).not.toBeInTheDocument();
+ // No in-page switcher: the edition is chosen on the Apps page.
+ expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
+ expect(screen.getByText("qoder.editionHint")).toBeInTheDocument();
+ expect(screen.getByText("qoder.accountCount")).toBeInTheDocument();
+ await user.click(
+ within(accountRow("Selected account")).getByRole("button", {
+ name: "qoder.useAccount",
+ }),
+ );
+ await waitFor(() =>
+ expect(mocks.invoke).toHaveBeenCalledWith("use_qoder_account", {
+ accountId: "mine",
+ }),
+ );
+ expect(authState[other].currentAccountId).toBeUndefined();
+ },
+ );
+
+ it("offers to collect a Qoder sign-in that CC Switch has not saved yet", async () => {
+ authState.cn = {
+ installed: true,
+ loggedIn: true,
+ username: "Native login",
+ uncollectedLogin: "Native login",
+ accounts: [{ id: "saved", username: "Saved account", isCurrent: false }],
+ };
+ const user = userEvent.setup();
+ const { invalidate } = mount("cn");
+ expect(
+ await screen.findByText("qoder.uncollectedLogin"),
+ ).toBeInTheDocument();
+ // Switching now would overwrite the uncollected login: collect it first.
+ const use = within(accountRow("Saved account")).getByRole("button", {
+ name: "qoder.useAccount",
+ });
+ expect(use).toBeDisabled();
+ expect(use).toHaveAttribute("title", "qoder.uncollectedLoginHint");
+ expect(
+ mocks.invoke.mock.calls.some(
+ ([command]) => command === "import_current_qoder_account",
+ ),
+ ).toBe(false);
+ await user.click(
+ screen.getByRole("button", { name: "qoder.collectAccount" }),
+ );
+ await waitFor(() =>
+ expect(mocks.invoke).toHaveBeenCalledWith("import_current_qoder_account"),
+ );
+ expect(await screen.findByText("Native login")).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "qoder.collectAccount" }),
+ ).not.toBeInTheDocument();
+ expect(invalidatedProviderCards(invalidate)).toBe(true);
+ expect(
+ within(accountRow("Saved account")).getByRole("button", {
+ name: "qoder.useAccount",
+ }),
+ ).toBeEnabled();
+ });
+
+ it("shows a Qoder login that matches no saved account without a switch action", async () => {
+ authState.cn = {
+ installed: true,
+ loggedIn: true,
+ email: "[email protected]",
+ plan: "Pro",
+ accounts: [],
+ };
+ mount("cn");
+ expect(await screen.findByText("qoder.loggedInAs")).toBeInTheDocument();
+ expect(screen.getByText("qoder.signedIn")).toBeInTheDocument();
+ expect(screen.getByText("Pro")).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "qoder.useAccount" }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "qoder.loginWithBrowser" }),
+ ).toBeEnabled();
+ });
+
+ it.each(editions)(
+ "reauthenticates the saved %s account without switching or creating another row",
+ async (edition) => {
+ savedAccounts(edition);
+ const user = userEvent.setup();
+ mount(edition);
+ await screen.findByText("Saved account");
+ await user.click(
+ within(accountRow("Saved account")).getByRole("button", {
+ name: "qoder.signInAgain",
+ }),
+ );
+ await waitFor(() =>
+ expect(mocks.invoke).toHaveBeenCalledWith("start_qoder_login", {
+ accountId: "saved",
+ }),
+ );
+ authState[edition].accounts![1].plan = "Pro";
+ loginProgress[edition] = { complete: true, accountId: "saved" };
+ await waitFor(
+ () =>
+ expect(
+ within(accountRow("Saved account")).getByText("Pro"),
+ ).toBeInTheDocument(),
+ { timeout: 4000 },
+ );
+ expect(authState[edition].accounts).toHaveLength(2);
+ expect(authState[edition].currentAccountId).toBe("existing");
+ expect(mocks.invoke).not.toHaveBeenCalledWith(
+ "use_qoder_account",
+ expect.anything(),
+ );
+ },
+ );
+
+ it("switches the Qoder login to a saved account and refreshes the provider cards", async () => {
+ savedAccounts("global");
+ const user = userEvent.setup();
+ const { invalidate } = mount("global");
+ await screen.findByText("Saved account");
+ expect(
+ within(accountRow("Existing account")).getByText("qoder.currentAccount"),
+ ).toBeInTheDocument();
+ await user.click(
+ within(accountRow("Saved account")).getByRole("button", {
+ name: "qoder.useAccount",
+ }),
+ );
+ await waitFor(() =>
+ expect(authState.global.currentAccountId).toBe("saved"),
+ );
+ await waitFor(() =>
+ expect(
+ within(accountRow("Saved account")).getByText("qoder.currentAccount"),
+ ).toBeInTheDocument(),
+ );
+ expect(
+ within(accountRow("Existing account")).queryByText(
+ "qoder.currentAccount",
+ ),
+ ).not.toBeInTheDocument();
+ expect(invalidatedProviderCards(invalidate)).toBe(true);
+ });
+
+ it("shows a failed switch without changing the current account", async () => {
+ savedAccounts("cn");
+ const invoke = mocks.invoke.getMockImplementation()!;
+ mocks.invoke.mockImplementation((command, args) =>
+ command === "use_qoder_account"
+ ? Promise.reject(new Error("Qoder is running a task"))
+ : invoke(command, args),
+ );
+ const user = userEvent.setup();
+ mount("cn");
+ await screen.findByText("Saved account");
+ await user.click(
+ within(accountRow("Saved account")).getByRole("button", {
+ name: "qoder.useAccount",
+ }),
+ );
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "Qoder is running a task",
+ );
+ expect(
+ within(accountRow("Existing account")).getByText("qoder.currentAccount"),
+ ).toBeInTheDocument();
+ expect(authState.cn.currentAccountId).toBe("existing");
+ });
+
+ it.each(editions)(
+ "adds another %s account without changing the current login",
+ async (edition) => {
+ savedAccounts(edition);
+ const user = userEvent.setup();
+ mount(edition);
+ await user.click(
+ await screen.findByRole("button", { name: "qoder.addAccount" }),
+ );
+ await waitFor(() =>
+ expect(mocks.invoke).toHaveBeenCalledWith("start_qoder_login", {
+ accountId: null,
+ }),
+ );
+ authState[edition].accounts!.push({
+ id: "added",
+ username: "Added account",
+ isCurrent: false,
+ });
+ loginProgress[edition] = { complete: true, accountId: "added" };
+ await screen.findByText("Added account", {}, { timeout: 4000 });
+ expect(authState[edition].currentAccountId).toBe("existing");
+ expect(authState[edition].accounts).toHaveLength(3);
+ expect(mocks.invoke).not.toHaveBeenCalledWith(
+ "use_qoder_account",
+ expect.anything(),
+ );
+ },
+ );
+
+ it.each(editions)(
+ "confirms removal of a saved %s account and preserves the current login and other edition",
+ async (edition) => {
+ savedAccounts(edition);
+ const other = otherEdition(edition);
+ savedAccounts(other);
+ const untouched = structuredClone(authState[other]);
+ const user = userEvent.setup();
+ const { invalidate } = mount(edition);
+ await screen.findByText("Saved account");
+ const trash = () =>
+ within(accountRow("Saved account")).getByRole("button", {
+ name: "qoder.deleteAccount",
+ });
+ await user.click(trash());
+ expect(await screen.findByRole("dialog")).toHaveTextContent(
+ "qoder.deleteAccountConfirm",
+ );
+ expect(mocks.invoke).not.toHaveBeenCalledWith(
+ "delete_qoder_account",
+ expect.anything(),
+ );
+ await user.click(
+ within(screen.getByRole("dialog")).getByRole("button", {
+ name: "common.cancel",
+ }),
+ );
+ expect(authState[edition].accounts).toHaveLength(2);
+ await user.click(trash());
+ await user.click(
+ within(screen.getByRole("dialog")).getByRole("button", {
+ name: "common.delete",
+ }),
+ );
+ await waitFor(() =>
+ expect(mocks.invoke).toHaveBeenCalledWith("delete_qoder_account", {
+ accountId: "saved",
+ }),
+ );
+ await waitFor(() =>
+ expect(screen.queryByText("Saved account")).not.toBeInTheDocument(),
+ );
+ expect(authState[edition].currentAccountId).toBe("existing");
+ expect(authState[other]).toEqual(untouched);
+ expect(invalidatedProviderCards(invalidate)).toBe(true);
+ },
+ );
+
+ it("warns before deleting the current account and keeps the account list usable afterwards", async () => {
+ savedAccounts("cn");
+ const user = userEvent.setup();
+ mount("cn");
+ await screen.findByText("Existing account");
+ await user.click(
+ within(accountRow("Existing account")).getByRole("button", {
+ name: "qoder.deleteAccount",
+ }),
+ );
+ expect(await screen.findByRole("dialog")).toHaveTextContent(
+ "qoder.deleteCurrentAccountConfirm",
+ );
+ await user.click(
+ within(screen.getByRole("dialog")).getByRole("button", {
+ name: "common.delete",
+ }),
+ );
+ await waitFor(() => expect(authState.cn.loggedIn).toBe(false));
+ await waitFor(() =>
+ expect(screen.queryByText("Existing account")).not.toBeInTheDocument(),
+ );
+ expect(screen.getByText("Saved account")).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "qoder.addAccount" }),
+ ).toBeEnabled();
+ });
+
+ it("keeps a failed deletion in its confirmation dialog for retry", async () => {
+ savedAccounts("cn");
+ const invoke = mocks.invoke.getMockImplementation()!;
+ let failing = true;
+ mocks.invoke.mockImplementation((command, args) =>
+ command === "delete_qoder_account" && failing
+ ? Promise.reject(new Error("Native credential is busy"))
+ : invoke(command, args),
+ );
+ const user = userEvent.setup();
+ mount("cn");
+ await screen.findByText("Saved account");
+ await user.click(
+ within(accountRow("Saved account")).getByRole("button", {
+ name: "qoder.deleteAccount",
+ }),
+ );
+ await user.click(
+ within(screen.getByRole("dialog")).getByRole("button", {
+ name: "common.delete",
+ }),
+ );
+ await waitFor(() =>
+ expect(screen.getByRole("dialog")).toHaveTextContent(
+ "Native credential is busy",
+ ),
+ );
+ expect(authState.cn.accounts).toHaveLength(2);
+ expect(authState.cn.currentAccountId).toBe("existing");
+ failing = false;
+ await user.click(
+ within(screen.getByRole("dialog")).getByRole("button", {
+ name: "common.delete",
+ }),
+ );
+ await waitFor(() =>
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),
+ );
+ expect(authState.cn.accounts).toHaveLength(1);
+ });
+
+ it("cancels the pending login when the user cancels it", async () => {
+ const user = userEvent.setup();
+ mount("global");
+ await user.click(
+ await screen.findByRole("button", { name: "qoder.loginWithBrowser" }),
+ );
+ await waitFor(() =>
+ expect(mocks.invoke).toHaveBeenCalledWith("poll_qoder_login", {
+ flowId: "global-login",
+ }),
+ );
+ await user.click(screen.getByRole("button", { name: "common.cancel" }));
+ await waitFor(() =>
+ expect(mocks.invoke).toHaveBeenCalledWith("cancel_qoder_login", {
+ flowId: "global-login",
+ }),
+ );
+ expect(screen.queryByText("qoder.loginWaiting")).not.toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "qoder.loginWithBrowser" }),
+ ).toBeEnabled();
+ });
+
+ it("cancels the selected edition's pending login when leaving the Authorization Center", async () => {
+ const user = userEvent.setup();
+ const { unmount } = mount("cn");
+ await user.click(
+ await screen.findByRole("button", { name: "qoder.loginWithBrowser" }),
+ );
+ await waitFor(() =>
+ expect(mocks.invoke).toHaveBeenCalledWith("poll_qoder_login", {
+ flowId: "cn-login",
+ }),
+ );
+ unmount();
+ await waitFor(() =>
+ expect(mocks.invoke).toHaveBeenCalledWith("cancel_qoder_login", {
+ flowId: "cn-login",
+ }),
+ );
+ });
+
+ it("cancels a late start response after leaving the account screen", async () => {
+ let resolveStart!: (id: string) => void;
+ const delayed = new Promise<string>((resolve) => {
+ resolveStart = resolve;
+ });
+ const invoke = mocks.invoke.getMockImplementation()!;
+ mocks.invoke.mockImplementation((command, args) =>
+ command === "start_qoder_login" ? delayed : invoke(command, args),
+ );
+ const user = userEvent.setup();
+ const { unmount } = mount("global");
+ await user.click(
+ await screen.findByRole("button", { name: "qoder.loginWithBrowser" }),
+ );
+ unmount();
+ await act(async () => resolveStart("late-login"));
+ await waitFor(() =>
+ expect(mocks.invoke).toHaveBeenCalledWith("cancel_qoder_login", {
+ flowId: "late-login",
+ }),
+ );
+ expect(mocks.invoke).not.toHaveBeenCalledWith(
+ "poll_qoder_login",
+ expect.anything(),
+ );
+ expect(mocks.invoke).not.toHaveBeenCalledWith(
+ "open_external",
+ expect.anything(),
+ );
+ });
+
+ it("shows native login failures and cancels the failed flow", async () => {
+ savedAccounts("cn");
+ loginProgress.cn = {
+ complete: false,
+ error: "Native browser login denied",
+ };
+ const user = userEvent.setup();
+ mount("cn");
+ await user.click(
+ await screen.findByRole("button", { name: "qoder.addAccount" }),
+ );
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "Native browser login denied",
+ );
+ await waitFor(() =>
+ expect(mocks.invoke).toHaveBeenCalledWith("cancel_qoder_login", {
+ flowId: "cn-login",
+ }),
+ );
+ expect(authState.cn.currentAccountId).toBe("existing");
+ expect(mocks.invoke).not.toHaveBeenCalledWith(
+ "open_external",
+ expect.anything(),
+ );
+ expect(
+ screen.getByRole("button", { name: "qoder.addAccount" }),
+ ).toBeEnabled();
+ });
+
+ it("requires the selected edition to be installed before starting browser login", async () => {
+ authState.cn.installed = false;
+ mount("cn");
+ expect(
+ await screen.findByText("qoder.loginInstallRequired"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("common.notInstalled")).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "qoder.loginWithBrowser" }),
+ ).toBeDisabled();
+ expect(mocks.invoke).not.toHaveBeenCalledWith(
+ "start_qoder_login",
+ expect.anything(),
+ );
+ });
+
+ it("shows a status error with a retry", async () => {
+ const invoke = mocks.invoke.getMockImplementation()!;
+ let failing = true;
+ mocks.invoke.mockImplementation((command, args) =>
+ command === "get_qoder_auth_status" && failing
+ ? Promise.reject(new Error("settings.json is unreadable"))
+ : invoke(command, args),
+ );
+ const user = userEvent.setup();
+ mount("cn");
+ expect(
+ await screen.findByText("settings.json is unreadable"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("qoder.statusFailed")).toBeInTheDocument();
+ failing = false;
+ await user.click(screen.getByRole("button", { name: "common.retry" }));
+ expect(await screen.findByText("qoder.signedOut")).toBeInTheDocument();
+ });
+});
diff --git a/tests/components/QoderPanel.test.tsx b/tests/components/QoderPanel.test.tsx
deleted file mode 100644
index d57325712..000000000
--- a/tests/components/QoderPanel.test.tsx
+++ /dev/null
@@ -1,1308 +0,0 @@
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import {
- act,
- cleanup,
- fireEvent,
- render,
- screen,
- waitFor,
- within,
-} from "@testing-library/react";
-import userEvent from "@testing-library/user-event";
-import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
-import { QoderPanel } from "@/components/providers/QoderPanel";
-import { AuthCenterPanel } from "@/components/settings/AuthCenterPanel";
-import type {
- QoderModels,
- QoderProvider,
- QoderAuthStatus,
- QoderLoginProgress,
-} from "@/lib/api/qoder";
-import { qoderProviderPresets } from "@/config/qoderProviderPresets";
-import type { UsageScript } from "@/types";
-
-const mocks = vi.hoisted(() => ({ invoke: vi.fn() }));
-vi.mock("@tauri-apps/api/core", () => ({ invoke: mocks.invoke }));
-vi.mock("@/components/providers/KimiAccountLogin", () => ({
- KimiAccountLogin: () => null,
-}));
-vi.mock("@/components/providers/forms/CopilotAuthSection", () => ({
- CopilotAuthSection: () => null,
-}));
-vi.mock("@/components/providers/forms/CodexOAuthSection", () => ({
- CodexOAuthSection: () => null,
-}));
-vi.mock("@/components/providers/forms/XaiOAuthSection", () => ({
- XaiOAuthSection: () => null,
-}));
-vi.mock("@/components/providers/forms/AgyOAuthSection", () => ({
- AgyOAuthSection: () => null,
-}));
-vi.mock("@/components/UsageScriptModal", () => ({
- default: ({
- onSave,
- onClose,
- }: {
- onSave: (script: UsageScript) => void;
- onClose: () => void;
- }) => (
- <div role="dialog" aria-label="usage editor">
- <button
- onClick={() => {
- onSave({
- enabled: true,
- language: "javascript",
- code: "return { remaining: 42 }",
- autoQueryInterval: 15,
- });
- onClose();
- }}
- >
- Save usage
- </button>
- </div>
- ),
-}));
-
-const provider: QoderProvider = {
- displayName: "Native provider",
- baseUrl: "https://example.test/v1",
- apiKey: "${NATIVE_API_KEY}",
- protocol: "anthropic",
- authType: "api-key",
- model: "model-one",
- routing: { summary: "model-one" },
- anthropic: { cache: { mode: "off", ttl: "1h" } },
- models: [
- {
- model: "model-one",
- displayName: "Model One",
- contextWindow: 200000,
- maxOutputTokens: 8192,
- capabilities: {
- tools: true,
- vision: true,
- thinking: { modes: ["adaptive"], supportedEffortLevels: ["high"] },
- },
- customNativeOption: "keep",
- },
- ],
-};
-// The backend serves whichever edition settings select; "qoder" stands for the
-// international edition and "qoder-cn" for the China edition in these fixtures.
-type QoderAppId = "qoder" | "qoder-cn";
-let active: QoderAppId = "qoder-cn";
-let state: Record<QoderAppId, QoderModels>;
-let authState: Record<QoderAppId, QoderAuthStatus>;
-let loginProgress: Record<QoderAppId, QoderLoginProgress>;
-
-function mount(app: QoderAppId = "qoder-cn", authCenter = false) {
- active = app;
- const client = new QueryClient({
- defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
- });
- return render(
- <QueryClientProvider client={client}>
- {authCenter ? <AuthCenterPanel /> : <QoderPanel />}
- </QueryClientProvider>,
- );
-}
-
-beforeAll(() => {
- Element.prototype.scrollIntoView ??= vi.fn();
- window.matchMedia ??= vi.fn().mockReturnValue({
- matches: false,
- addListener: vi.fn(),
- removeListener: vi.fn(),
- addEventListener: vi.fn(),
- removeEventListener: vi.fn(),
- });
-});
-beforeEach(() => {
- authState = {
- qoder: { installed: true, loggedIn: false },
- "qoder-cn": { installed: true, loggedIn: false },
- };
- loginProgress = {
- qoder: { complete: false },
- "qoder-cn": { complete: false },
- };
- state = {
- qoder: { providers: {}, currentModel: "auto" },
- "qoder-cn": { providers: {}, currentModel: "auto" },
- };
- mocks.invoke
- .mockReset()
- .mockImplementation(
- async (command: string, args: Record<string, unknown> = {}) => {
- if (command.includes("qoder")) expect(args).not.toHaveProperty("app");
- const app = active;
- if (command === "get_qoder_models") return structuredClone(state[app]);
- if (command === "get_qoder_auth_status")
- return structuredClone(authState[app]);
- if (command === "use_qoder_account") {
- const account = authState[app].accounts!.find(
- (item) => item.id === args.accountId,
- )!;
- authState[app] = {
- ...authState[app],
- loggedIn: true,
- username: account.username,
- email: account.email,
- plan: account.plan,
- currentAccountId: account.id,
- accounts: authState[app].accounts!.map((item) => ({
- ...item,
- isCurrent: item.id === account.id,
- })),
- };
- // Switching the login never changes the selected model.
- return structuredClone(authState[app]);
- }
- if (command === "delete_qoder_account") {
- const account = authState[app].accounts!.find(
- (item) => item.id === args.accountId,
- )!;
- authState[app].accounts = authState[app].accounts!.filter(
- (item) => item.id !== account.id,
- );
- if (account.isCurrent)
- Object.assign(authState[app], {
- loggedIn: false,
- currentAccountId: null,
- username: null,
- email: null,
- plan: null,
- });
- return structuredClone(authState[app]);
- }
- if (command === "import_current_qoder_account") {
- const name = authState[app].uncollectedLogin!;
- const account = {
- id: "collected",
- username: name,
- email: null,
- plan: null,
- isCurrent: true,
- };
- authState[app] = {
- ...authState[app],
- uncollectedLogin: null,
- loggedIn: true,
- username: name,
- currentAccountId: account.id,
- accounts: [...(authState[app].accounts ?? []), account],
- };
- return structuredClone(authState[app]);
- }
- if (command === "start_qoder_login") return `${app}-login`;
- if (command === "poll_qoder_login")
- return structuredClone(loginProgress[app]);
- if (command === "cancel_qoder_login" || command === "open_external")
- return;
- if (command === "get_settings")
- return {
- usageConfirmed: true,
- qoderEdition: app === "qoder-cn" ? "cn" : "global",
- };
- if (command === "queryProviderUsage")
- return {
- success: true,
- data: [{ remaining: 42, total: 100, used: 58, unit: "USD" }],
- };
- if (command === "save_qoder_usage_script") {
- state[app].metadata = {
- ...state[app].metadata,
- [args.id as string]: { usage_script: args.script as UsageScript },
- };
- return structuredClone(state[app]);
- }
- if (command === "save_qoder_provider") {
- state[app].providers[args.id as string] =
- args.provider as QoderProvider;
- if (args.makeDefault)
- state[app].currentModel =
- `${args.id}/${(args.provider as QoderProvider).model}`;
- return structuredClone(state[app]);
- }
- if (command === "set_qoder_model") {
- state[app].currentModel = args.model as string;
- return structuredClone(state[app]);
- }
- if (command === "delete_qoder_provider") {
- delete state[app].providers[args.id as string];
- state[app].currentModel = "auto";
- return structuredClone(state[app]);
- }
- throw new Error(`Unexpected command: ${command}`);
- },
- );
-});
-
-describe("Qoder model management", () => {
- async function openAccountLogin(app: QoderAppId) {
- const user = userEvent.setup();
- mount(app);
- await user.click(
- (
- await screen.findAllByRole("button", { name: "provider.addProvider" })
- )[0],
- );
- await user.click(
- screen.getByRole("button", { name: /^providerPreset.group.login / }),
- );
- await user.click(
- screen.getByRole("button", {
- name:
- app === "qoder-cn"
- ? "qoder.officialAccountCn"
- : "qoder.officialAccount",
- }),
- );
- await user.click(
- screen.getByRole("button", { name: "qoder.manageAccounts" }),
- );
- return user;
- }
-
- it.each(["qoder", "qoder-cn"] as const)(
- "signs in to the official %s account from the login category and enables native models",
- async (app) => {
- state[app] = {
- providers: { native: structuredClone(provider) },
- currentModel: "native/model-one",
- };
- const providersBefore = structuredClone(state[app].providers);
- const otherEdition = app === "qoder" ? "qoder-cn" : "qoder";
- const url =
- app === "qoder"
- ? "https://qoder.com/login?code=fixture"
- : "https://qoder.com.cn/login?code=fixture";
- loginProgress[app] = { complete: false, authUrl: url };
- const user = await openAccountLogin(app);
- expect(screen.queryByLabelText("qoder.baseUrl")).not.toBeInTheDocument();
- expect(screen.queryByLabelText("API Key")).not.toBeInTheDocument();
- await user.click(
- screen.getByRole("button", { name: "qoder.loginWithBrowser" }),
- );
- await waitFor(() =>
- expect(mocks.invoke).toHaveBeenCalledWith("start_qoder_login", {
- accountId: null,
- }),
- );
- await waitFor(() =>
- expect(mocks.invoke).toHaveBeenCalledWith("open_external", { url }),
- );
- authState[app] = {
- installed: true,
- loggedIn: false,
- accounts: [
- {
- id: "new-account",
- username: "Fixture Account",
- plan: "Pro",
- isCurrent: false,
- },
- ],
- };
- loginProgress[app] = { complete: true, accountId: "new-account" };
- await screen.findByText("Fixture Account", {}, { timeout: 4000 });
- expect(state[app].currentModel).toBe("native/model-one");
- await user.click(
- screen.getByRole("button", { name: "qoder.useAccount" }),
- );
- await waitFor(
- () =>
- expect(mocks.invoke).toHaveBeenCalledWith("use_qoder_account", {
- accountId: "new-account",
- }),
- { timeout: 4000 },
- );
- await screen.findByText("qoder.currentAccount");
- expect(screen.getByRole("heading", { name: "nav.auth" })).toBeVisible();
- await user.click(screen.getByRole("button", { name: "common.back" }));
- await user.click(
- screen.getByRole("button", { name: "providerPreset.backToPick" }),
- );
- await user.click(
- screen.getByRole("button", { name: "provider.backToList" }),
- );
- await waitFor(() =>
- expect(
- screen.queryByRole("heading", { name: "nav.auth" }),
- ).not.toBeInTheDocument(),
- );
- expect(screen.getByText("Fixture Account · Pro")).toBeInTheDocument();
- expect(state[app].providers).toEqual(providersBefore);
- expect(authState[otherEdition].loggedIn).toBe(false);
- expect(
- mocks.invoke.mock.calls.filter(
- ([command]) => command === "open_external",
- ),
- ).toHaveLength(1);
- expect(
- screen.queryByText("provider.addNewProvider"),
- ).not.toBeInTheDocument();
- },
- );
-
- function savedAccounts(app: QoderAppId) {
- authState[app] = {
- installed: true,
- loggedIn: true,
- username: "Existing account",
- currentAccountId: "existing",
- accounts: [
- {
- id: "existing",
- username: "Existing account",
- plan: "Pro",
- isCurrent: true,
- },
- {
- id: "saved",
- username: "Saved account",
- plan: "Free",
- isCurrent: false,
- },
- ],
- };
- state[app] = {
- providers: { native: structuredClone(provider) },
- currentModel: "native/model-one",
- };
- }
- const accountRow = (name: string) =>
- within(screen.getByRole("list"))
- .getAllByRole("listitem")
- .find((row) => within(row).queryByText(name))!;
-
- it.each(["qoder", "qoder-cn"] as const)(
- "shows only the %s edition selected in settings in the Authorization Center",
- async (app) => {
- const other = app === "qoder" ? "qoder-cn" : "qoder";
- authState[app].accounts = [
- { id: "mine", username: "Selected account", isCurrent: false },
- ];
- authState[other].accounts = [
- { id: "theirs", username: "Other edition account", isCurrent: false },
- ];
- const user = userEvent.setup();
- mount(app, true);
- await screen.findByText("Selected account");
- expect(
- screen.queryByText("Other edition account"),
- ).not.toBeInTheDocument();
- // No in-page switcher: the edition is chosen on the Apps page.
- expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
- expect(screen.getByText("qoder.editionHint")).toBeInTheDocument();
- await user.click(
- within(accountRow("Selected account")).getByRole("button", {
- name: "qoder.useAccount",
- }),
- );
- await waitFor(() =>
- expect(mocks.invoke).toHaveBeenCalledWith("use_qoder_account", {
- accountId: "mine",
- }),
- );
- expect(authState[other].currentAccountId).toBeUndefined();
- },
- );
-
- it("offers to collect a Qoder sign-in that CC Switch has not saved yet", async () => {
- authState["qoder-cn"] = {
- installed: true,
- loggedIn: true,
- username: "Native login",
- uncollectedLogin: "Native login",
- accounts: [],
- };
- const user = userEvent.setup();
- mount("qoder-cn", true);
- expect(
- await screen.findByText("qoder.uncollectedLogin"),
- ).toBeInTheDocument();
- expect(screen.getByText("qoder.uncollectedLoginHint")).toBeInTheDocument();
- for (const button of screen.queryAllByRole("button", {
- name: "qoder.useAccount",
- }))
- expect(button).toBeDisabled();
- expect(
- mocks.invoke.mock.calls.some(
- ([command]) => command === "import_current_qoder_account",
- ),
- ).toBe(false);
- await user.click(
- screen.getByRole("button", { name: "qoder.collectAccount" }),
- );
- await waitFor(() =>
- expect(mocks.invoke).toHaveBeenCalledWith("import_current_qoder_account"),
- );
- expect(await screen.findByText("Native login")).toBeInTheDocument();
- expect(
- screen.queryByRole("button", { name: "qoder.collectAccount" }),
- ).not.toBeInTheDocument();
- });
-
- it.each(["qoder", "qoder-cn"] as const)(
- "reauthenticates the selected %s account without switching models or creating another row",
- async (app) => {
- savedAccounts(app);
- const user = await openAccountLogin(app);
- await user.click(
- within(accountRow("Saved account")).getByRole("button", {
- name: "qoder.signInAgain",
- }),
- );
- await waitFor(() =>
- expect(mocks.invoke).toHaveBeenCalledWith("start_qoder_login", {
- accountId: "saved",
- }),
- );
- authState[app].accounts![1].plan = "Pro";
- loginProgress[app] = { complete: true, accountId: "saved" };
- await waitFor(
- () =>
- expect(
- within(accountRow("Saved account")).getByText("Pro"),
- ).toBeInTheDocument(),
- { timeout: 4000 },
- );
- expect(authState[app].accounts).toHaveLength(2);
- expect(authState[app].currentAccountId).toBe("existing");
- expect(state[app].currentModel).toBe("native/model-one");
- expect(screen.getByRole("heading", { name: "nav.auth" })).toBeVisible();
- },
- );
-
- it("keeps the selected provider and shows the new login after switching accounts in the Authorization Center", async () => {
- savedAccounts("qoder");
- const user = await openAccountLogin("qoder");
- await user.click(
- within(accountRow("Saved account")).getByRole("button", {
- name: "qoder.useAccount",
- }),
- );
- await waitFor(() => expect(authState.qoder.currentAccountId).toBe("saved"));
- await user.click(screen.getByRole("button", { name: "common.back" }));
- await user.click(
- screen.getByRole("button", { name: "providerPreset.backToPick" }),
- );
- await user.click(
- screen.getByRole("button", { name: "provider.backToList" }),
- );
- await waitFor(() =>
- expect(
- screen.queryByRole("heading", { name: "nav.auth" }),
- ).not.toBeInTheDocument(),
- );
- const native = within(
- screen
- .getByRole("heading", { name: "Native provider" })
- .closest(".group") as HTMLElement,
- );
- // A new login keeps the user's own provider selected.
- expect(native.getByText("providerCard.status.inUse")).toBeVisible();
- expect(state.qoder.currentModel).not.toBe("auto");
- expect(screen.getByText("Saved account · Free")).toBeInTheDocument();
- });
-
- it("returns to the account preset after Escape without closing the provider dialog", async () => {
- const user = await openAccountLogin("qoder");
- await user.keyboard("{Escape}");
- await waitFor(() =>
- expect(
- screen.queryByRole("heading", { name: "nav.auth" }),
- ).not.toBeInTheDocument(),
- );
- expect(
- screen.getByRole("heading", { name: "provider.addNewProvider" }),
- ).toBeVisible();
- expect(
- screen.getByRole("button", { name: "qoder.manageAccounts" }),
- ).toBeVisible();
- });
-
- it.each(["qoder", "qoder-cn"] as const)(
- "returns directly to the %s configuration page after editing official accounts",
- async (app) => {
- savedAccounts(app);
- const user = userEvent.setup();
- mount(app);
- const officialCard = within(
- (
- await screen.findByRole("heading", {
- name: app === "qoder" ? "Qoder CLI" : "Qoder CLI CN",
- })
- ).closest(".group") as HTMLElement,
- );
- await user.click(
- officialCard.getByRole("button", { name: "providerCard.action.edit" }),
- );
- expect(
- await screen.findByRole("button", { name: "qoder.addAccount" }),
- ).toBeInTheDocument();
- await user.click(screen.getByRole("button", { name: "common.back" }));
- await waitFor(() =>
- expect(
- screen.queryByRole("button", { name: "qoder.addAccount" }),
- ).not.toBeInTheDocument(),
- );
- expect(
- screen.queryByRole("textbox", {
- name: "providerPreset.searchAriaLabel",
- }),
- ).not.toBeInTheDocument();
- expect(
- screen.getByRole("heading", { name: "Native provider" }),
- ).toBeVisible();
- expect(
- screen.getByRole("button", { name: "provider.addProvider" }),
- ).toBeVisible();
- },
- );
-
- it.each(["qoder", "qoder-cn"] as const)(
- "adds another %s account on this page without changing the current login",
- async (app) => {
- savedAccounts(app);
- const user = await openAccountLogin(app);
- expect(screen.getByRole("heading", { name: "nav.auth" })).toBeVisible();
- await user.click(
- screen.getByRole("button", { name: "qoder.addAccount" }),
- );
- await waitFor(() =>
- expect(mocks.invoke).toHaveBeenCalledWith("start_qoder_login", {
- accountId: null,
- }),
- );
- authState[app].accounts!.push({
- id: "added",
- username: "Added account",
- isCurrent: false,
- });
- loginProgress[app] = { complete: true, accountId: "added" };
- await screen.findByText("Added account", {}, { timeout: 4000 });
- expect(screen.getByText("provider.addNewProvider")).toBeInTheDocument();
- expect(authState[app].currentAccountId).toBe("existing");
- expect(authState[app].accounts).toHaveLength(3);
- expect(state[app].currentModel).toBe("native/model-one");
- expect(mocks.invoke).not.toHaveBeenCalledWith(
- "use_qoder_account",
- expect.anything(),
- );
- },
- );
-
- it.each(["qoder", "qoder-cn"] as const)(
- "confirms removal of a saved %s account and preserves the current login and other edition",
- async (app) => {
- savedAccounts(app);
- const other = app === "qoder" ? "qoder-cn" : "qoder";
- savedAccounts(other);
- const untouched = structuredClone(authState[other]);
- const user = await openAccountLogin(app);
- const trash = () =>
- within(accountRow("Saved account")).getByRole("button", {
- name: "qoder.deleteAccount",
- });
- await user.click(trash());
- expect(await screen.findByRole("dialog")).toHaveTextContent(
- "qoder.deleteAccountConfirm",
- );
- expect(mocks.invoke).not.toHaveBeenCalledWith(
- "delete_qoder_account",
- expect.anything(),
- );
- await user.click(
- within(screen.getByRole("dialog")).getByRole("button", {
- name: "common.cancel",
- }),
- );
- expect(authState[app].accounts).toHaveLength(2);
- await user.click(trash());
- await user.click(
- within(screen.getByRole("dialog")).getByRole("button", {
- name: "common.delete",
- }),
- );
- await waitFor(() =>
- expect(mocks.invoke).toHaveBeenCalledWith("delete_qoder_account", {
- accountId: "saved",
- }),
- );
- expect(screen.queryByText("Saved account")).not.toBeInTheDocument();
- expect(authState[app].currentAccountId).toBe("existing");
- expect(authState[other]).toEqual(untouched);
- expect(state[app].currentModel).toBe("native/model-one");
- },
- );
-
- it("warns before deleting the current account and keeps the account page open afterwards", async () => {
- savedAccounts("qoder-cn");
- const user = await openAccountLogin("qoder-cn");
- await user.click(
- within(accountRow("Existing account")).getByRole("button", {
- name: "qoder.deleteAccount",
- }),
- );
- expect(await screen.findByRole("dialog")).toHaveTextContent(
- "qoder.deleteCurrentAccountConfirm",
- );
- await user.click(
- within(screen.getByRole("dialog")).getByRole("button", {
- name: "common.delete",
- }),
- );
- await waitFor(() => expect(authState["qoder-cn"].loggedIn).toBe(false));
- expect(screen.queryByText("Existing account")).not.toBeInTheDocument();
- expect(screen.getByText("Saved account")).toBeInTheDocument();
- expect(
- screen.getByRole("button", { name: "qoder.addAccount" }),
- ).toBeEnabled();
- });
-
- it("keeps a failed deletion in its confirmation dialog for retry", async () => {
- savedAccounts("qoder-cn");
- const invoke = mocks.invoke.getMockImplementation()!;
- mocks.invoke.mockImplementation((command, args) =>
- command === "delete_qoder_account"
- ? Promise.reject(new Error("Native credential is busy"))
- : invoke(command, args),
- );
- const user = await openAccountLogin("qoder-cn");
- await user.click(
- within(accountRow("Saved account")).getByRole("button", {
- name: "qoder.deleteAccount",
- }),
- );
- await user.click(
- within(screen.getByRole("dialog")).getByRole("button", {
- name: "common.delete",
- }),
- );
- await waitFor(() =>
- expect(screen.getByRole("dialog")).toHaveTextContent(
- "Native credential is busy",
- ),
- );
- expect(authState["qoder-cn"].accounts).toHaveLength(2);
- expect(authState["qoder-cn"].currentAccountId).toBe("existing");
- });
-
- it("cancels the selected edition's pending login when leaving the Authorization Center", async () => {
- const user = await openAccountLogin("qoder-cn");
- await user.click(
- screen.getByRole("button", { name: "qoder.loginWithBrowser" }),
- );
- await waitFor(() =>
- expect(mocks.invoke).toHaveBeenCalledWith("poll_qoder_login", {
- flowId: "qoder-cn-login",
- }),
- );
- await user.click(screen.getByRole("button", { name: "common.back" }));
- await waitFor(() =>
- expect(mocks.invoke).toHaveBeenCalledWith("cancel_qoder_login", {
- flowId: "qoder-cn-login",
- }),
- );
- expect(mocks.invoke).not.toHaveBeenCalledWith(
- "set_qoder_model",
- expect.anything(),
- );
- });
-
- it("cancels a late start response after leaving the account screen", async () => {
- let resolveStart!: (id: string) => void;
- const delayed = new Promise<string>((resolve) => {
- resolveStart = resolve;
- });
- const invoke = mocks.invoke.getMockImplementation()!;
- mocks.invoke.mockImplementation((command, args) =>
- command === "start_qoder_login" ? delayed : invoke(command, args),
- );
- const user = await openAccountLogin("qoder");
- await user.click(
- screen.getByRole("button", { name: "qoder.loginWithBrowser" }),
- );
- await user.click(screen.getByRole("button", { name: "common.back" }));
- await act(async () => resolveStart("late-login"));
- await waitFor(() =>
- expect(mocks.invoke).toHaveBeenCalledWith("cancel_qoder_login", {
- flowId: "late-login",
- }),
- );
- expect(mocks.invoke).not.toHaveBeenCalledWith(
- "open_external",
- expect.anything(),
- );
- expect(mocks.invoke).not.toHaveBeenCalledWith(
- "set_qoder_model",
- expect.anything(),
- );
- });
-
- it("shows native login failures without switching away from the current provider", async () => {
- state["qoder-cn"] = {
- providers: { native: structuredClone(provider) },
- currentModel: "native/model-one",
- };
- loginProgress["qoder-cn"] = {
- complete: false,
- error: "Native browser login denied",
- };
- const user = await openAccountLogin("qoder-cn");
- await user.click(
- screen.getByRole("button", { name: "qoder.loginWithBrowser" }),
- );
- expect(await screen.findByRole("alert")).toHaveTextContent(
- "Native browser login denied",
- );
- expect(state["qoder-cn"].currentModel).toBe("native/model-one");
- expect(mocks.invoke).not.toHaveBeenCalledWith(
- "set_qoder_model",
- expect.anything(),
- );
- });
-
- it("requires the selected edition to be installed before starting browser login", async () => {
- authState["qoder-cn"].installed = false;
- await openAccountLogin("qoder-cn");
- expect(
- await screen.findByText("qoder.loginInstallRequired"),
- ).toBeInTheDocument();
- expect(
- screen.getByRole("button", { name: "qoder.loginWithBrowser" }),
- ).toBeDisabled();
- expect(mocks.invoke).not.toHaveBeenCalledWith(
- "start_qoder_login",
- expect.anything(),
- );
- });
-
- it.each([
- ["qoder", true],
- ["qoder-cn", true],
- ["qoder", false],
- ["qoder-cn", false],
- ] as const)(
- "switches %s directly using its default model (declared: %s) and moves the active status",
- async (app, hasDefault) => {
- state[app] = {
- providers: {
- native: {
- ...structuredClone(provider),
- model: hasDefault ? "vendor/model-two" : undefined,
- models: [
- { model: "model-one", displayName: "Model One" },
- { model: "vendor/model-two", displayName: "Model Two" },
- ],
- },
- other: {
- ...structuredClone(provider),
- displayName: "Other provider",
- },
- },
- currentModel: "other/model-one",
- };
- const otherEdition = app === "qoder" ? "qoder-cn" : "qoder";
- state[otherEdition].providers.untouched = structuredClone(provider);
- const untouched = structuredClone(state[otherEdition]);
- const user = userEvent.setup();
- mount(app);
- const target = within(
- (
- await screen.findByRole("heading", { name: "Native provider" })
- ).closest(".group") as HTMLElement,
- );
- const previous = within(
- screen
- .getByRole("heading", { name: "Other provider" })
- .closest(".group") as HTMLElement,
- );
- expect(
- previous.getByText("providerCard.status.inUse"),
- ).toBeInTheDocument();
- expect(
- previous.queryByRole("button", { name: "providerCard.action.switch" }),
- ).not.toBeInTheDocument();
- await user.click(
- target.getByRole("button", { name: "providerCard.action.switch" }),
- );
- await waitFor(() =>
- expect(mocks.invoke).toHaveBeenCalledWith("set_qoder_model", {
- model: hasDefault ? "native/vendor/model-two" : "native/model-one",
- }),
- );
- await waitFor(() =>
- expect(
- target.getByText("providerCard.status.inUse"),
- ).toBeInTheDocument(),
- );
- expect(
- target.queryByRole("button", { name: "providerCard.action.switch" }),
- ).not.toBeInTheDocument();
- expect(
- previous.queryByText("providerCard.status.inUse"),
- ).not.toBeInTheDocument();
- expect(
- previous.getByRole("button", { name: "providerCard.action.switch" }),
- ).toBeInTheDocument();
- expect(state[otherEdition]).toEqual(untouched);
- },
- );
-
- it("prevents repeated switches while saving and keeps the active provider on failure", async () => {
- state["qoder-cn"] = {
- providers: {
- native: structuredClone(provider),
- other: { ...structuredClone(provider), displayName: "Other provider" },
- },
- currentModel: "other/model-one",
- };
- let rejectSwitch!: (error: Error) => void;
- const pending = new Promise<QoderModels>((_resolve, reject) => {
- rejectSwitch = reject;
- });
- const invoke = mocks.invoke.getMockImplementation()!;
- mocks.invoke.mockImplementation((command, args) =>
- command === "set_qoder_model" ? pending : invoke(command, args),
- );
- const user = userEvent.setup();
- mount();
- const button = await screen.findByRole("button", {
- name: "providerCard.action.switch",
- });
- await user.click(button);
- await waitFor(() =>
- expect(
- screen.getByRole("button", { name: "providerCard.action.switch" }),
- ).toHaveAttribute("aria-disabled", "true"),
- );
- await user.click(
- screen.getByRole("button", { name: "providerCard.action.switch" }),
- );
- expect(
- mocks.invoke.mock.calls.filter(
- ([command]) => command === "set_qoder_model",
- ),
- ).toHaveLength(1);
- await act(async () =>
- rejectSwitch(new Error("Could not save Qoder settings")),
- );
- await waitFor(() =>
- expect(
- screen.getByRole("button", { name: "providerCard.action.switch" }),
- ).not.toHaveAttribute("aria-disabled", "true"),
- );
- expect(state["qoder-cn"].currentModel).toBe("other/model-one");
- const previous = within(
- screen
- .getByRole("heading", { name: "Other provider" })
- .closest(".group") as HTMLElement,
- );
- expect(previous.getByText("providerCard.status.inUse")).toBeInTheDocument();
- });
-
- it.each(["qoder", "qoder-cn"] as const)(
- "uses the shared active status and configures usage for %s",
- async (app) => {
- state[app] = {
- providers: { native: structuredClone(provider) },
- currentModel: "native/model-one",
- };
- const user = userEvent.setup();
- mount(app);
- expect(
- await screen.findByText("providerCard.status.inUse"),
- ).toBeInTheDocument();
- expect(screen.queryByText("qoder.currentModel")).not.toBeInTheDocument();
- expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
- await user.click(
- screen.getByRole("button", { name: "providerCard.action.more" }),
- );
- await user.click(
- await screen.findByRole("menuitem", {
- name: "provider.configureUsage",
- }),
- );
- await user.click(screen.getByRole("button", { name: "Save usage" }));
- await waitFor(() =>
- expect(mocks.invoke).toHaveBeenCalledWith("save_qoder_usage_script", {
- id: "native",
- script: expect.objectContaining({
- enabled: true,
- autoQueryInterval: 15,
- }),
- }),
- );
- await waitFor(() =>
- expect(mocks.invoke).toHaveBeenCalledWith("queryProviderUsage", {
- app: "qoder",
- providerId: "native",
- }),
- );
- expect(state[app].providers.native).toEqual(provider);
- },
- );
- it("uses the common provider empty state and imports native configuration without CLI instructions", async () => {
- const user = userEvent.setup();
- mount();
- expect(
- await screen.findByRole("heading", { name: "provider.noProviders" }),
- ).toBeInTheDocument();
- expect(
- screen.getAllByRole("button", { name: "provider.addProvider" }),
- ).toHaveLength(2);
- expect(
- screen.queryByText("qoder.modelsDescription"),
- ).not.toBeInTheDocument();
- expect(
- screen.queryByText(/\/model|Add custom model/),
- ).not.toBeInTheDocument();
- state["qoder-cn"].providers.native = structuredClone(provider);
- await user.click(
- screen.getByRole("button", { name: "provider.importCurrent" }),
- );
- expect(
- await screen.findByRole("heading", { name: "Native provider" }),
- ).toBeInTheDocument();
- expect(mocks.invoke).toHaveBeenCalledWith("get_qoder_models");
- expect(
- mocks.invoke.mock.calls.some(([command]) =>
- /terminal|lifecycle|shell/.test(command),
- ),
- ).toBe(false);
- });
-
- it("creates and activates a native provider entirely through the form", async () => {
- const user = userEvent.setup();
- mount();
- await user.click(
- (
- await screen.findAllByRole("button", { name: "provider.addProvider" })
- )[0],
- );
- await user.click(
- screen.getByRole("button", { name: "providerPreset.custom" }),
- );
- const dialog = within(screen.getByRole("form"));
- await user.type(dialog.getByLabelText("qoder.providerName"), "My API");
- await user.type(dialog.getByLabelText("qoder.providerId"), "my-api");
- await user.type(
- dialog.getByLabelText("qoder.baseUrl"),
- "https://example.test/v1",
- );
- await user.type(dialog.getByLabelText("API Key"), "example-key");
- await user.type(dialog.getByLabelText("qoder.modelId"), "vendor/model");
- await user.type(dialog.getByLabelText("qoder.contextWindow"), "128000");
- await user.type(dialog.getByLabelText("qoder.maxOutputTokens"), "8192");
- await user.click(screen.getByRole("button", { name: "common.save" }));
- await waitFor(() =>
- expect(mocks.invoke).toHaveBeenCalledWith(
- "save_qoder_provider",
- expect.objectContaining({
- id: "my-api",
- expected: null,
- makeDefault: true,
- provider: expect.objectContaining({
- displayName: "My API",
- baseUrl: "https://example.test/v1",
- protocol: "openai",
- model: "vendor/model",
- models: [
- expect.objectContaining({
- model: "vendor/model",
- contextWindow: 128000,
- maxOutputTokens: 8192,
- }),
- ],
- }),
- }),
- ),
- );
- expect(
- await screen.findByRole("heading", { name: "My API" }),
- ).toBeInTheDocument();
- expect(screen.queryByRole("form")).not.toBeInTheDocument();
- expect(
- screen.queryByRole("combobox", { name: "qoder.currentModel" }),
- ).not.toBeInTheDocument();
- expect(screen.getByText("providerCard.status.inUse")).toBeInTheDocument();
- expect(
- mocks.invoke.mock.calls.some(([command]) =>
- /terminal|lifecycle|shell/.test(command),
- ),
- ).toBe(false);
- });
-
- it.each(["qoder", "qoder-cn"] as const)(
- "opens the shared picker first and saves the selected preset to %s",
- async (app) => {
- const user = userEvent.setup();
- mount(app);
- await screen.findByRole("heading", { name: "provider.noProviders" });
- const add = screen.getAllByRole("button", {
- name: "provider.addProvider",
- });
- // Cover both the header action and the empty-state entry.
- await user.click(app === "qoder" ? add[0] : add[1]);
- const search = screen.getByRole("textbox", {
- name: "providerPreset.searchAriaLabel",
- });
- const categories = screen.getByRole("group", {
- name: "providerPreset.categoriesLabel",
- });
- for (const group of ["vendor", "thirdparty", "cloud", "local"]) {
- expect(categories).toHaveTextContent(`providerPreset.group.${group}`);
- }
- expect(screen.queryByRole("form")).not.toBeInTheDocument();
- expect(
- screen.queryByRole("button", { name: "common.save" }),
- ).not.toBeInTheDocument();
- await user.type(search, "deepseek");
- await user.click(screen.getByRole("button", { name: "DeepSeek" }));
- const form = within(screen.getByRole("form"));
- const preset = qoderProviderPresets.find(
- (preset) => preset.name === "DeepSeek",
- )!;
- expect(form.getByLabelText("qoder.providerName")).toHaveValue("DeepSeek");
- expect(form.getByLabelText("qoder.providerId")).toHaveValue(
- preset.providerKey,
- );
- expect(form.getByLabelText("qoder.baseUrl")).toHaveValue(
- preset.settingsConfig.baseUrl,
- );
- expect(
- form
- .getAllByLabelText("qoder.modelId")
- .map((input) => (input as HTMLInputElement).value),
- ).toEqual(preset.settingsConfig.models!.map((model) => model.model));
- await user.type(form.getByLabelText("API Key"), "example-key");
- await user.click(screen.getByRole("button", { name: "common.save" }));
- await waitFor(() =>
- expect(mocks.invoke).toHaveBeenCalledWith("save_qoder_provider", {
- id: preset.providerKey,
- provider: { ...preset.settingsConfig, apiKey: "example-key" },
- expected: null,
- makeDefault: true,
- }),
- );
- expect(
- await screen.findByRole("heading", { name: "DeepSeek" }),
- ).toBeInTheDocument();
- },
- );
-
- it("filters by category and returns from the form to choose a custom configuration", async () => {
- const user = userEvent.setup();
- mount();
- await user.click(
- (
- await screen.findAllByRole("button", { name: "provider.addProvider" })
- )[0],
- );
- await user.click(
- screen.getByRole("button", { name: /^providerPreset.group.local / }),
- );
- expect(
- screen.queryByRole("button", { name: "DeepSeek" }),
- ).not.toBeInTheDocument();
- await user.click(screen.getByRole("button", { name: "Ollama" }));
- expect(screen.getByLabelText("qoder.baseUrl")).toHaveValue(
- "http://localhost:11434/v1",
- );
- await user.click(
- screen.getByRole("button", { name: "providerPreset.backToPick" }),
- );
- expect(
- screen.getByRole("textbox", { name: "providerPreset.searchAriaLabel" }),
- ).toBeVisible();
- await user.click(
- screen.getByRole("button", { name: "providerPreset.custom" }),
- );
- expect(screen.getByLabelText("qoder.providerName")).toHaveValue("");
- expect(screen.getByLabelText("qoder.providerId")).toHaveValue("");
- expect(screen.getByLabelText("qoder.baseUrl")).toHaveValue("");
- expect(screen.getAllByLabelText("qoder.modelId")).toHaveLength(1);
- expect(screen.getByLabelText("qoder.modelId")).toHaveValue("");
- await user.click(
- screen.getByRole("button", { name: "providerPreset.change" }),
- );
- await user.click(
- screen.getByRole("button", { name: "provider.backToList" }),
- );
- expect(
- screen.queryByRole("heading", { name: "provider.addNewProvider" }),
- ).not.toBeInTheDocument();
- });
-
- it("switches a supplier's region and plan using the common version controls", async () => {
- const user = userEvent.setup();
- mount();
- await user.click(
- (
- await screen.findAllByRole("button", { name: "provider.addProvider" })
- )[0],
- );
- await user.click(screen.getByRole("button", { name: "Kimi" }));
- expect(screen.getByLabelText("qoder.baseUrl")).toHaveValue(
- "https://api.moonshot.cn/v1",
- );
- const regions = within(
- screen.getByRole("group", { name: "providerPreset.regionLabel" }),
- ).getAllByRole("button");
- await user.click(regions[1]);
- expect(screen.getByLabelText("qoder.baseUrl")).toHaveValue(
- "https://api.moonshot.ai/v1",
- );
- const plans = within(
- screen.getByRole("group", { name: "providerPreset.planLabel" }),
- ).getAllByRole("button");
- await user.click(plans[1]);
- expect(screen.getByLabelText("qoder.providerId")).toHaveValue(
- "cc-switch-kimi-for-coding-global",
- );
- expect(screen.getByLabelText("qoder.baseUrl")).toHaveValue(
- "https://api.kimi.ai/coding",
- );
- expect(
- screen.getByRole("combobox", { name: "qoder.protocol" }),
- ).toHaveTextContent("Anthropic Messages");
- expect(
- screen.getByRole("combobox", { name: "qoder.authType" }),
- ).toHaveTextContent("API Key (x-api-key)");
- });
-
- it("edits native fields while retaining environment keys, model capabilities and unknown settings", async () => {
- state.qoder = {
- providers: { native: structuredClone(provider) },
- currentModel: "native/model-one",
- };
- const user = userEvent.setup();
- mount("qoder");
- await user.click(
- await screen.findByRole("button", { name: "providerCard.action.edit" }),
- );
- const dialog = within(screen.getByRole("form"));
- expect(dialog.getByLabelText("qoder.providerId")).toHaveAttribute(
- "readonly",
- );
- await user.clear(dialog.getByLabelText("qoder.providerName"));
- await user.type(
- dialog.getByLabelText("qoder.providerName"),
- "Updated provider",
- );
- await user.click(screen.getByRole("button", { name: "common.save" }));
- await waitFor(() =>
- expect(mocks.invoke).toHaveBeenCalledWith("save_qoder_provider", {
- id: "native",
- provider: { ...provider, displayName: "Updated provider" },
- expected: provider,
- makeDefault: true,
- }),
- );
- });
-
- it("selects a default model and deletes a provider without affecting the other edition", async () => {
- state["qoder-cn"].providers.native = structuredClone(provider);
- const user = userEvent.setup();
- mount();
- await user.click(
- await screen.findByRole("button", { name: "providerCard.action.more" }),
- );
- await user.click(
- await screen.findByRole("menuitem", { name: "qoder.selectModelAction" }),
- );
- fireEvent.keyDown(
- await screen.findByRole("menuitem", { name: /^Model One/ }),
- { key: "Enter" },
- );
- await waitFor(() =>
- expect(mocks.invoke).toHaveBeenCalledWith("set_qoder_model", {
- model: "native/model-one",
- }),
- );
- // fireEvent leaves Radix's keyboard-closed submenu state behind in jsdom,
- // so reopen the panel before using the card menu again.
- cleanup();
- mount();
- await user.click(
- await screen.findByRole("button", { name: "providerCard.action.more" }),
- );
- await user.click(
- await screen.findByRole("menuitem", { name: "common.delete" }),
- );
- await user.click(
- within(screen.getByRole("dialog")).getByRole("button", {
- name: "common.delete",
- }),
- );
- await waitFor(() =>
- expect(mocks.invoke).toHaveBeenCalledWith("delete_qoder_provider", {
- id: "native",
- expected: provider,
- }),
- );
- expect(
- await screen.findByRole("heading", { name: "provider.noProviders" }),
- ).toBeInTheDocument();
- expect(state.qoder.providers).toEqual({});
- expect(state.qoder.currentModel).toBe("auto");
- });
-
- it("keeps the editor open when a concurrent external update is reported", async () => {
- state.qoder.providers.native = structuredClone(provider);
- const invoke = mocks.invoke.getMockImplementation()!;
- mocks.invoke.mockImplementation((command, args) =>
- command === "save_qoder_provider"
- ? Promise.reject(new Error("Provider changed outside this editor"))
- : invoke(command, args),
- );
- const user = userEvent.setup();
- mount("qoder");
- await user.click(
- await screen.findByRole("button", { name: "providerCard.action.edit" }),
- );
- await user.click(screen.getByRole("button", { name: "common.save" }));
- expect(await screen.findByRole("alert")).toHaveTextContent(
- "Provider changed outside this editor",
- );
- expect(screen.getByRole("form")).toBeInTheDocument();
- });
-
- it("rejects duplicate model IDs and invalid token limits before saving", async () => {
- const user = userEvent.setup();
- state.qoder.providers.native = structuredClone(provider);
- mount("qoder");
- await user.click(
- await screen.findByRole("button", { name: "providerCard.action.edit" }),
- );
- const dialog = within(screen.getByRole("form"));
- fireEvent.change(dialog.getByLabelText("qoder.contextWindow"), {
- target: { value: "0" },
- });
- expect(screen.getByRole("button", { name: "common.save" })).toBeDisabled();
- fireEvent.change(dialog.getByLabelText("qoder.contextWindow"), {
- target: { value: "128000" },
- });
- await user.click(dialog.getByRole("button", { name: "qoder.addModel" }));
- const ids = dialog.getAllByLabelText("qoder.modelId");
- await user.type(ids[1], "model-one");
- expect(screen.getByRole("button", { name: "common.save" })).toBeDisabled();
- expect(mocks.invoke).not.toHaveBeenCalledWith(
- "save_qoder_provider",
- expect.anything(),
- );
- });
-
- it("marks the header add-provider button for the onboarding tour", async () => {
- state.qoder.providers.native = structuredClone(provider);
- mount("qoder");
- const addButton = await screen.findByRole("button", {
- name: "provider.addProvider",
- });
- expect(addButton).toHaveAttribute("data-tour", "add-provider");
- });
-});
diff --git a/tests/components/QoderProviderForm.test.tsx b/tests/components/QoderProviderForm.test.tsx
new file mode 100644
index 000000000..c5eddecc3
--- /dev/null
+++ b/tests/components/QoderProviderForm.test.tsx
@@ -0,0 +1,467 @@
+import { QueryClientProvider } from "@tanstack/react-query";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { http, HttpResponse } from "msw";
+import { beforeAll, describe, expect, it, vi } from "vitest";
+import { QoderProviderForm } from "@/components/providers/forms/QoderProviderForm";
+import type { ProviderFormProps } from "@/components/providers/forms/ProviderForm";
+import { qoderProviderPresets } from "@/config/qoderProviderPresets";
+import type { QoderProvider } from "@/lib/api/qoder";
+import { getSettings } from "../msw/state";
+import { server } from "../msw/server";
+import { createTestQueryClient } from "../utils/testQueryClient";
+
+beforeAll(() => {
+ Element.prototype.scrollIntoView ??= vi.fn();
+});
+
+vi.mock("@/components/JsonEditor", () => ({
+ default: ({
+ id,
+ value,
+ onChange,
+ }: {
+ id: string;
+ value: string;
+ onChange: (text: string) => void;
+ }) => (
+ <textarea
+ id={id}
+ value={value}
+ onChange={(event) => onChange(event.target.value)}
+ />
+ ),
+}));
+
+const nativeProvider: QoderProvider = {
+ displayName: "Native provider",
+ type: "openai-compatible",
+ baseUrl: "https://example.test/v1",
+ apiKey: "${NATIVE_API_KEY}",
+ protocol: "anthropic",
+ authType: "api-key",
+ model: "model-one",
+ routing: { summary: "model-one" },
+ anthropic: { cache: { mode: "off", ttl: "1h" } },
+ models: [
+ {
+ model: "model-one",
+ displayName: "Model One",
+ contextWindow: 200000,
+ maxOutputTokens: 8192,
+ capabilities: {
+ tools: true,
+ vision: true,
+ thinking: { modes: ["adaptive"], supportedEffortLevels: ["high"] },
+ },
+ customNativeOption: "keep",
+ },
+ ],
+};
+
+function setup(props: Partial<ProviderFormProps> = {}) {
+ const onSubmit = vi.fn();
+ const onAccountLoginChange = vi.fn();
+ const onManageAuthAccounts = vi.fn();
+ render(
+ <QueryClientProvider client={createTestQueryClient()}>
+ <QoderProviderForm
+ appId="qoder"
+ submitLabel="Save"
+ onSubmit={onSubmit}
+ onCancel={() => {}}
+ onAccountLoginChange={onAccountLoginChange}
+ onManageAuthAccounts={onManageAuthAccounts}
+ {...props}
+ />
+ </QueryClientProvider>,
+ );
+ return { onSubmit, onAccountLoginChange, onManageAuthAccounts };
+}
+
+const saveButton = () => screen.getByRole("button", { name: "Save" });
+const nativeEditor = () =>
+ screen.getByLabelText(
+ "providerForm.nativeConfig.title",
+ ) as HTMLTextAreaElement;
+const modelIds = () =>
+ screen
+ .getAllByLabelText("opencode.modelId")
+ .map((input) => (input as HTMLInputElement).value);
+
+/** A complete custom provider, so only the field under test decides validity. */
+async function fillCustomProvider(key: string) {
+ const user = userEvent.setup();
+ fireEvent.change(screen.getByLabelText("opencode.providerKey"), {
+ target: { value: key },
+ });
+ fireEvent.change(screen.getByLabelText("provider.name"), {
+ target: { value: "My API" },
+ });
+ fireEvent.change(screen.getByLabelText("opencode.baseUrl"), {
+ target: { value: "https://example.test/v1" },
+ });
+ fireEvent.change(screen.getByLabelText("API Key"), {
+ target: { value: "example-key" },
+ });
+ await user.click(screen.getByRole("button", { name: "opencode.addModel" }));
+ fireEvent.change(screen.getByLabelText("opencode.modelId"), {
+ target: { value: "vendor/model-a" },
+ });
+ return user;
+}
+
+describe("QoderProviderForm", () => {
+ it.each([
+ ["global", "qoder.officialAccount"],
+ ["cn", "qoder.officialAccountCn"],
+ ] as const)(
+ "sends the %s account preset to the Authorization Center",
+ async (edition, presetName) => {
+ server.use(
+ http.post("http://tauri.local/get_settings", () =>
+ HttpResponse.json({ ...getSettings(), qoderEdition: edition }),
+ ),
+ );
+ const user = userEvent.setup();
+ const { onAccountLoginChange, onManageAuthAccounts, onSubmit } = setup();
+ await user.click(
+ screen.getByRole("button", { name: /^providerPreset\.group\.login / }),
+ );
+ await user.click(await screen.findByRole("button", { name: presetName }));
+ expect(screen.getByText("qoder.loginDescription")).toBeInTheDocument();
+ // No API-key form for the official account: login lives in the Authorization Center.
+ expect(
+ screen.queryByLabelText("opencode.baseUrl"),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByLabelText("API Key")).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Save" }),
+ ).not.toBeInTheDocument();
+ expect(onAccountLoginChange).toHaveBeenLastCalledWith(true);
+ await user.click(
+ screen.getByRole("button", { name: "qoder.manageAccounts" }),
+ );
+ expect(onManageAuthAccounts).toHaveBeenCalledWith("qoder_oauth");
+ expect(onSubmit).not.toHaveBeenCalled();
+
+ // Leaving the account preset hands the dialog its own buttons back.
+ await user.click(
+ screen.getByRole("button", { name: "providerPreset.custom" }),
+ );
+ expect(onAccountLoginChange).toHaveBeenLastCalledWith(false);
+ expect(saveButton()).toBeDisabled();
+ },
+ );
+
+ it("creates a custom provider whose default model falls back to the first model", async () => {
+ const { onSubmit, onAccountLoginChange } = setup();
+ expect(onAccountLoginChange).toHaveBeenLastCalledWith(false);
+ expect(saveButton()).toBeDisabled();
+ const user = await fillCustomProvider("my-api");
+ await user.click(screen.getByRole("button", { name: "opencode.addModel" }));
+ fireEvent.change(screen.getAllByLabelText("opencode.modelId")[1], {
+ target: { value: " vendor/model-b " },
+ });
+ expect(screen.getByText("qoder.providerDefaultModel")).toBeInTheDocument();
+ expect(saveButton()).toBeEnabled();
+ await user.click(saveButton());
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledOnce());
+ const saved = onSubmit.mock.calls[0][0];
+ expect(saved).toMatchObject({
+ name: "My API",
+ providerKey: "my-api",
+ presetCategory: "custom",
+ });
+ expect(JSON.parse(saved.settingsConfig)).toEqual({
+ type: "openai-compatible",
+ displayName: "My API",
+ baseUrl: "https://example.test/v1",
+ apiKey: "example-key",
+ protocol: "openai",
+ authType: "bearer",
+ model: "vendor/model-a",
+ models: [
+ {
+ model: "vendor/model-a",
+ capabilities: { tools: true, vision: false },
+ },
+ {
+ model: "vendor/model-b",
+ capabilities: { tools: true, vision: false },
+ },
+ ],
+ });
+ });
+
+ it.each([
+ ["the official card prefix", "qoder-official-mine"],
+ ["the reserved app name", "qoder"],
+ ["a leading dot", ".hidden"],
+ ])("keeps save disabled for an id with %s", async (_, key) => {
+ const { onSubmit } = setup();
+ await fillCustomProvider(key);
+ expect(screen.getByLabelText("opencode.providerKey")).toHaveValue(key);
+ // 规则说明一直在,ID 不合规时标红
+ expect(screen.getByText("qoder.invalidProviderId")).toHaveClass(
+ "text-destructive",
+ );
+ expect(saveButton()).toBeDisabled();
+ fireEvent.change(screen.getByLabelText("opencode.providerKey"), {
+ target: { value: "my-api" },
+ });
+ expect(screen.getByText("qoder.invalidProviderId")).not.toHaveClass(
+ "text-destructive",
+ );
+ expect(saveButton()).toBeEnabled();
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+
+ it("drops characters Qoder does not accept in provider ids", async () => {
+ setup();
+ await fillCustomProvider("my api/v2");
+ expect(screen.getByLabelText("opencode.providerKey")).toHaveValue(
+ "myapiv2",
+ );
+ expect(saveButton()).toBeEnabled();
+ });
+
+ it("flags an id that another Qoder card already uses", async () => {
+ server.use(
+ http.post("http://tauri.local/get_providers", () =>
+ HttpResponse.json({
+ "my-api": { id: "my-api", name: "Mine", settingsConfig: {} },
+ }),
+ ),
+ );
+ const { onSubmit } = setup();
+ await fillCustomProvider("my-api");
+ expect(
+ await screen.findByText("opencode.providerKeyDuplicate"),
+ ).toBeInTheDocument();
+ expect(saveButton()).toBeDisabled();
+ fireEvent.change(screen.getByLabelText("opencode.providerKey"), {
+ target: { value: "my-api-2" },
+ });
+ expect(saveButton()).toBeEnabled();
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+
+ it("rejects duplicate model ids and non-positive token limits", async () => {
+ setup();
+ const user = await fillCustomProvider("my-api");
+ expect(saveButton()).toBeEnabled();
+ await user.click(screen.getByRole("button", { name: "opencode.addModel" }));
+ fireEvent.change(screen.getAllByLabelText("opencode.modelId")[1], {
+ target: { value: "vendor/model-a" },
+ });
+ expect(saveButton()).toBeDisabled();
+ await user.click(
+ screen.getAllByRole("button", { name: "common.delete" })[1],
+ );
+ expect(saveButton()).toBeEnabled();
+ await user.click(
+ screen.getByRole("button", { name: "opencode.toggleModelDetails" }),
+ );
+ fireEvent.change(screen.getByLabelText("qoder.contextWindow"), {
+ target: { value: "0" },
+ });
+ expect(saveButton()).toBeDisabled();
+ fireEvent.change(screen.getByLabelText("qoder.contextWindow"), {
+ target: { value: "128000" },
+ });
+ expect(saveButton()).toBeEnabled();
+ });
+
+ it("edits an official account card through its basic fields only", async () => {
+ const { onSubmit, onAccountLoginChange, onManageAuthAccounts } = setup({
+ providerId: "qoder-official-abc",
+ initialData: {
+ name: "Qoder · Pro",
+ settingsConfig: {},
+ category: "official",
+ meta: {
+ authBinding: {
+ source: "managed_account",
+ authProvider: "qoder_oauth",
+ accountId: "abc",
+ },
+ },
+ },
+ });
+ expect(screen.getByText("qoder.officialCardManaged")).toBeInTheDocument();
+ expect(
+ screen.queryByLabelText("opencode.providerKey"),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByLabelText("opencode.baseUrl")).not.toBeInTheDocument();
+ expect(screen.queryByLabelText("API Key")).not.toBeInTheDocument();
+ expect(
+ screen.queryByLabelText("providerForm.nativeConfig.title"),
+ ).not.toBeInTheDocument();
+ expect(onAccountLoginChange).not.toHaveBeenCalledWith(true);
+ const user = userEvent.setup();
+ await user.click(
+ screen.getByRole("button", { name: "qoder.manageAccounts" }),
+ );
+ expect(onManageAuthAccounts).toHaveBeenCalledWith("qoder_oauth");
+ fireEvent.change(screen.getByLabelText("provider.name"), {
+ target: { value: "Work account" },
+ });
+ await user.click(saveButton());
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledOnce());
+ expect(onSubmit.mock.calls[0][0]).toMatchObject({
+ name: "Work account",
+ providerKey: "qoder-official-abc",
+ presetCategory: "official",
+ settingsConfig: "{}",
+ meta: {
+ authBinding: { accountId: "abc", authProvider: "qoder_oauth" },
+ },
+ });
+ });
+
+ it("edits a native provider while keeping its unknown settings", async () => {
+ const { onSubmit } = setup({
+ providerId: "native",
+ initialData: {
+ name: "Native provider",
+ settingsConfig: structuredClone(nativeProvider),
+ category: "custom",
+ },
+ });
+ const key = screen.getByLabelText("opencode.providerKey");
+ expect(key).toHaveValue("native");
+ expect(key).toBeDisabled();
+ expect(
+ screen.getByText("opencode.providerKeyLockedHint"),
+ ).toBeInTheDocument();
+ expect(screen.getByLabelText("opencode.baseUrl")).toHaveValue(
+ nativeProvider.baseUrl,
+ );
+ fireEvent.change(screen.getByLabelText("provider.name"), {
+ target: { value: "Updated provider" },
+ });
+ const user = userEvent.setup();
+ await user.click(saveButton());
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledOnce());
+ expect(onSubmit.mock.calls[0][0].providerKey).toBe("native");
+ expect(JSON.parse(onSubmit.mock.calls[0][0].settingsConfig)).toEqual({
+ ...nativeProvider,
+ displayName: "Updated provider",
+ });
+ });
+
+ it("turns a provider that only names its model into a model row", () => {
+ setup({
+ providerId: "legacy",
+ initialData: {
+ name: "Legacy",
+ settingsConfig: {
+ baseUrl: "https://example.test/v1",
+ apiKey: "",
+ model: "solo-model",
+ },
+ },
+ });
+ expect(modelIds()).toEqual(["solo-model"]);
+ expect(saveButton()).toBeEnabled();
+ });
+
+ it("updates the form fields from the settings.json editor", () => {
+ setup();
+ const config: QoderProvider = {
+ type: "openai-compatible",
+ protocol: "anthropic",
+ authType: "api-key",
+ baseUrl: "https://edited.test/anthropic",
+ apiKey: "edited-key",
+ model: "model-y",
+ models: [{ model: "model-x" }, { model: "model-y" }],
+ };
+ fireEvent.change(nativeEditor(), {
+ target: { value: JSON.stringify(config, null, 2) },
+ });
+ expect(screen.getByLabelText("opencode.baseUrl")).toHaveValue(
+ config.baseUrl,
+ );
+ expect(screen.getByLabelText("API Key")).toHaveValue("edited-key");
+ expect(modelIds()).toEqual(["model-x", "model-y"]);
+ expect(document.getElementById("qoder-protocol")).toHaveTextContent(
+ "Anthropic Messages",
+ );
+ expect(document.getElementById("qoder-auth-type")).toHaveTextContent(
+ "API Key (x-api-key)",
+ );
+ // Editing a field writes back to the editor.
+ fireEvent.change(screen.getByLabelText("opencode.baseUrl"), {
+ target: { value: "https://other.test/v1" },
+ });
+ expect(JSON.parse(nativeEditor().value)).toMatchObject({
+ ...config,
+ baseUrl: "https://other.test/v1",
+ });
+ });
+
+ it.each([
+ ["broken JSON", "{", "providerForm.nativeConfig.invalid"],
+ ["a JSON array", "[]", "qoder.configJsonSchema"],
+ ])(
+ "blocks saving %s until the settings.json is corrected",
+ async (_, value, message) => {
+ const { onSubmit } = setup();
+ await fillCustomProvider("my-api");
+ expect(saveButton()).toBeEnabled();
+ const valid = nativeEditor().value;
+ fireEvent.change(nativeEditor(), { target: { value } });
+ expect(screen.getByRole("alert")).toHaveTextContent(message);
+ expect(saveButton()).toBeDisabled();
+ fireEvent.change(nativeEditor(), { target: { value: valid } });
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+ expect(saveButton()).toBeEnabled();
+ expect(onSubmit).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([
+ { group: "vendor", name: "DeepSeek" },
+ { group: "local", name: "Ollama" },
+ ])(
+ "fills $name from the Pi-derived $group preset",
+ async ({ group, name }) => {
+ const preset = qoderProviderPresets.find((entry) => entry.name === name)!;
+ expect(preset).toBeDefined();
+ const user = userEvent.setup();
+ const { onSubmit } = setup();
+ await user.click(
+ screen.getByRole("button", {
+ name: new RegExp(`^providerPreset\\.group\\.${group} `),
+ }),
+ );
+ await user.click(screen.getByRole("button", { name }));
+ expect(screen.getByLabelText("opencode.providerKey")).toHaveValue(
+ preset.providerKey,
+ );
+ expect(screen.getByLabelText("provider.name")).toHaveValue(name);
+ expect(screen.getByLabelText("opencode.baseUrl")).toHaveValue(
+ preset.settingsConfig.baseUrl,
+ );
+ expect(modelIds()).toEqual(
+ preset.settingsConfig.models!.map((model) => model.model),
+ );
+ fireEvent.change(screen.getByLabelText("API Key"), {
+ target: { value: "example-key" },
+ });
+ await user.click(saveButton());
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledOnce());
+ const saved = onSubmit.mock.calls[0][0];
+ expect(saved).toMatchObject({
+ providerKey: preset.providerKey,
+ presetCategory: preset.category,
+ });
+ expect(JSON.parse(saved.settingsConfig)).toEqual({
+ ...preset.settingsConfig,
+ apiKey: "example-key",
+ });
+ },
+ );
+});
diff --git a/tests/components/providerPresentation.test.ts b/tests/components/providerPresentation.test.ts
index 6197b7ea5..48f2bcc57 100644
--- a/tests/components/providerPresentation.test.ts
+++ b/tests/components/providerPresentation.test.ts
@@ -686,6 +686,139 @@ describe("buildAdditiveSections", () => {
]);
});
+ it("lists Qoder model cards like Kimi and official account cards like CodeBuddy", () => {
+ const account = (id: string, accountId: string) =>
+ provider(id, {
+ category: "official",
+ meta: {
+ authBinding: {
+ source: "managed_account",
+ authProvider: "qoder_oauth",
+ accountId,
+ },
+ },
+ });
+ const alice = account("qoder-official-alice", "alice");
+ const bob = account("qoder-official-bob", "bob");
+ const gone = account("qoder-official-gone", "gone");
+ const relay = provider("relay", {
+ settingsConfig: {
+ models: [{ model: "fast", displayName: "Fast" }, { model: "smart" }],
+ },
+ });
+ const single = provider("single", {
+ settingsConfig: { models: [{ model: "only" }] },
+ });
+ const spare = provider("spare");
+ const actions = { ...additiveActions(), switchAccount: vi.fn() };
+ const build = (
+ currentId: string | null,
+ accounts: Partial<
+ NonNullable<
+ Parameters<typeof buildAdditiveSections>[0]["qoderAccounts"]
+ >
+ > = {},
+ ) =>
+ buildAdditiveSections({
+ app: "qoder",
+ t,
+ providers: [relay, single, spare, alice, bob, gone],
+ isInConfig: (p) => p.id !== "spare",
+ qoderCurrentId: currentId,
+ qoderAccounts: {
+ status: "ready",
+ currentAccountId: "alice",
+ accountIds: ["alice", "bob"],
+ uncollectedLogin: null,
+ ...accounts,
+ },
+ actions,
+ });
+ const ids = (sections: ReturnType<typeof build>, key: string) =>
+ sections
+ .find((section) => section.key === key)!
+ .items.map((entry) => entry.provider.id);
+
+ // 默认是某个模型卡:它不能移除、不能删;Qoder 登着的官方卡在「已添加」
+ let sections = build("relay");
+ expect(ids(sections, "added")).toEqual([
+ "relay",
+ "single",
+ "qoder-official-alice",
+ ]);
+ expect(ids(sections, "available")).toEqual([
+ "spare",
+ "qoder-official-bob",
+ "qoder-official-gone",
+ ]);
+ expect(item(sections, "relay").status?.label).toBe(
+ "providerCard.status.default",
+ );
+ expect(button(sections, "relay", "remove").disabledReason).toBe(
+ "providerCard.reason.defaultCannotRemove",
+ );
+ expect(item(sections, "relay").deleteDisabledReason).toBe(
+ "providerCard.reason.inUseCannotDelete",
+ );
+ expect(item(sections, "relay").menuItems).toBeUndefined();
+
+ // 其他模型卡:「设为默认」在「更多」里,多个模型时展开子菜单
+ const singleDefault = item(sections, "single").menuItems![0];
+ expect(singleDefault.submenu).toBeUndefined();
+ singleDefault.onSelect();
+ expect(actions.setDefault).toHaveBeenCalledWith(single, "only");
+ button(sections, "single", "remove").onClick();
+ expect(actions.remove).toHaveBeenCalledWith(single);
+ button(sections, "spare", "add").onClick();
+ expect(actions.add).toHaveBeenCalledWith(spare);
+
+ // 登着的官方卡:不能移除(不替 Qoder 登出)、不能删;不是默认时可以设为默认(auto)
+ expect(
+ button(sections, "qoder-official-alice", "remove").disabledReason,
+ ).toBe("qoder.official.removeHint");
+ expect(item(sections, "qoder-official-alice").deleteDisabledReason).toBe(
+ "qoder.accountManagedByQoder",
+ );
+ item(sections, "qoder-official-alice").menuItems![0].onSelect();
+ expect(actions.setDefault).toHaveBeenLastCalledWith(alice);
+
+ // 别的号:「添加」就是切号;已不在授权中心的号不能加
+ button(sections, "qoder-official-bob", "add").onClick();
+ expect(actions.switchAccount).toHaveBeenCalledWith(bob);
+ expect(button(sections, "qoder-official-gone", "add").disabledReason).toBe(
+ "qoder.official.accountMissing",
+ );
+
+ // 默认是 auto(官方卡):模型卡都可以移除,官方卡显示「默认」、子菜单列出模型
+ sections = build("qoder-official-alice");
+ expect(item(sections, "qoder-official-alice").status?.label).toBe(
+ "providerCard.status.default",
+ );
+ expect(item(sections, "qoder-official-alice").menuItems).toBeUndefined();
+ expect(button(sections, "relay", "remove").disabledReason).toBeUndefined();
+ const submenu = item(sections, "relay").menuItems![0].submenu!;
+ expect(submenu.options.map((option) => option.label)).toEqual([
+ "Fast",
+ "smart",
+ ]);
+ submenu.options[1].onSelect();
+ expect(actions.setDefault).toHaveBeenLastCalledWith(relay, "smart");
+
+ // Qoder 登着还没收录的号:先收录才能切
+ sections = build(null, {
+ currentAccountId: null,
+ uncollectedLogin: "carol",
+ });
+ expect(ids(sections, "added")).not.toContain("qoder-official-alice");
+ expect(button(sections, "qoder-official-bob", "add").disabledReason).toBe(
+ "qoder.official.collectFirst",
+ );
+ sections = build(null, { status: "loading" });
+ expect(button(sections, "qoder-official-alice", "add").disabledReason).toBe(
+ "qoder.official.statusLoading",
+ );
+ });
+
it("splits added and available providers and keeps OMO to one at a time", () => {
const omo = provider("omo", { category: "omo" });
const otherOmo = provider("omo-2", { category: "omo" });
diff --git a/tests/config/appSpecs.json b/tests/config/appSpecs.json
index c89df8199..68f9c5227 100644
--- a/tests/config/appSpecs.json
+++ b/tests/config/appSpecs.json
@@ -127,7 +127,7 @@
},
{
"id": "qoder",
- "additive": false,
+ "additive": true,
"localProxy": false,
"routeMode": false,
"stack": false
diff --git a/tests/config/backendConstants.json b/tests/config/backendConstants.json
index 6083eae7f..779fd97d3 100644
--- a/tests/config/backendConstants.json
+++ b/tests/config/backendConstants.json
@@ -183,7 +183,8 @@
"copilot": false,
"workbuddy": false,
"codebuddy": false,
- "zcode": false
+ "zcode": false,
+ "qoder": false
}
},
{
@@ -214,7 +215,8 @@
"copilot": false,
"workbuddy": false,
"codebuddy": false,
- "zcode": false
+ "zcode": false,
+ "qoder": false
}
},
{
@@ -245,7 +247,8 @@
"copilot": false,
"workbuddy": false,
"codebuddy": false,
- "zcode": false
+ "zcode": false,
+ "qoder": false
}
},
{
@@ -276,7 +279,8 @@
"copilot": false,
"workbuddy": false,
"codebuddy": false,
- "zcode": false
+ "zcode": false,
+ "qoder": false
}
},
{
@@ -307,7 +311,8 @@
"copilot": false,
"workbuddy": false,
"codebuddy": false,
- "zcode": false
+ "zcode": false,
+ "qoder": false
}
},
{
@@ -341,7 +346,8 @@
"copilot": false,
"workbuddy": false,
"codebuddy": false,
- "zcode": false
+ "zcode": false,
+ "qoder": false
}
},
{
@@ -375,7 +381,8 @@
"copilot": false,
"workbuddy": false,
"codebuddy": false,
- "zcode": false
+ "zcode": false,
+ "qoder": false
}
},
{
@@ -406,7 +413,8 @@
"copilot": false,
"workbuddy": false,
"codebuddy": false,
- "zcode": false
+ "zcode": false,
+ "qoder": false
}
},
{
@@ -438,7 +446,8 @@
"copilot": false,
"workbuddy": false,
"codebuddy": false,
- "zcode": false
+ "zcode": false,
+ "qoder": false
}
}
],
diff --git a/tests/integration/App.test.tsx b/tests/integration/App.test.tsx
index ab2af7604..b0c85c382 100644
--- a/tests/integration/App.test.tsx
+++ b/tests/integration/App.test.tsx
@@ -315,27 +315,19 @@ describe("App integration with MSW", () => {
expect(toastSuccessMock).toHaveBeenCalled();
}, 10_000);
- it("opens Qoder's provider picker from the standard app header and continues to native configuration", async () => {
- let modelRequests = 0;
- server.use(
- http.post("http://tauri.local/get_qoder_models", () => {
- modelRequests += 1;
- return HttpResponse.json({ providers: {}, currentModel: "auto" });
- }),
- );
+ it("opens the shared add-provider dialog from Qoder's standard header", async () => {
const { default: App } = await import("@/App");
renderApp(App);
await waitFor(() =>
expect(screen.getByTestId("provider-list")).toBeInTheDocument(),
);
fireEvent.click(sidebarApp("Qoder CLI"));
- await waitFor(() => expect(modelRequests).toBeGreaterThan(0));
- expect(
- await screen.findByRole("heading", {
- name: /^(还没有供应商|provider.noProviders|No providers yet)$/,
- hidden: true,
- }),
- ).toBeInTheDocument();
+ // Qoder 现在用通用的页头、新增对话框和供应商列表(这里都是替身)
+ await waitFor(() =>
+ expect(
+ document.querySelector("#content-area header")?.textContent,
+ ).toContain("Qoder CLI"),
+ );
const header = document.querySelector(
"#content-area header",
) as HTMLElement;
@@ -346,25 +338,8 @@ describe("App integration with MSW", () => {
}),
);
expect(
- await screen.findByRole("textbox", {
- name: /^(搜索预设供应商|providerPreset.searchAriaLabel|Search provider presets)$/,
- hidden: true,
- }),
+ await screen.findByTestId("add-provider-dialog"),
).toBeInTheDocument();
- fireEvent.click(
- screen.getByRole("button", {
- name: /^(自定义配置|providerPreset.custom|Custom Configuration)$/,
- hidden: true,
- }),
- );
- expect(await screen.findByRole("form", { hidden: true })).toHaveAttribute(
- "id",
- "qoder-provider-form",
- );
- expect(screen.queryByTestId("add-provider-dialog")).not.toBeInTheDocument();
- expect(
- screen.queryByText(/\/model|Add custom model/),
- ).not.toBeInTheDocument();
}, 15_000);
it("refreshes the route pointer when the proxy fails over to another provider", async () => {