diff --git a/src-tauri/src/claude_mcp.rs b/src-tauri/src/claude_mcp.rs index 7d2938b07..d65499831 100644 --- a/src-tauri/src/claude_mcp.rs +++ b/src-tauri/src/claude_mcp.rs @@ -1,6 +1,4 @@ -use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; -use std::env; use std::fs; use std::path::{Path, PathBuf}; @@ -65,14 +63,6 @@ fn wrap_command_for_windows(_obj: &mut Map) { // 非 Windows 平台不做任何处理 } -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct McpStatus { - pub user_config_path: String, - pub user_config_exists: bool, - pub server_count: usize, -} - fn user_config_path() -> PathBuf { get_claude_mcp_path() } @@ -95,23 +85,6 @@ fn write_json_value(path: &Path, value: &Value) -> Result<(), AppError> { atomic_write(path, json.as_bytes()) } -pub fn get_mcp_status() -> Result { - let path = user_config_path(); - let (exists, count) = if path.exists() { - let v = read_json_value(&path)?; - let servers = v.get("mcpServers").and_then(|x| x.as_object()); - (true, servers.map(|m| m.len()).unwrap_or(0)) - } else { - (false, 0) - }; - - Ok(McpStatus { - user_config_path: path.to_string_lossy().to_string(), - user_config_exists: exists, - server_count: count, - }) -} - pub fn read_mcp_json() -> Result, AppError> { let path = user_config_path(); if !path.exists() { @@ -170,63 +143,6 @@ pub fn clear_has_completed_onboarding() -> Result { Ok(true) } -pub fn delete_mcp_server(id: &str) -> Result { - if id.trim().is_empty() { - return Err(AppError::InvalidInput("MCP 服务器 ID 不能为空".into())); - } - let path = user_config_path(); - if !path.exists() { - return Ok(false); - } - let mut root = read_json_value(&path)?; - let Some(servers) = root.get_mut("mcpServers").and_then(|v| v.as_object_mut()) else { - return Ok(false); - }; - let existed = servers.remove(id).is_some(); - if !existed { - return Ok(false); - } - write_json_value(&path, &root)?; - Ok(true) -} - -pub fn validate_command_in_path(cmd: &str) -> Result { - if cmd.trim().is_empty() { - return Ok(false); - } - // 如果包含路径分隔符,直接判断是否存在可执行文件 - if cmd.contains('/') || cmd.contains('\\') { - return Ok(Path::new(cmd).exists()); - } - - let path_var = env::var_os("PATH").unwrap_or_default(); - let paths = env::split_paths(&path_var); - - #[cfg(windows)] - let exts: Vec = env::var("PATHEXT") - .unwrap_or(".COM;.EXE;.BAT;.CMD".into()) - .split(';') - .map(|s| s.trim().to_uppercase()) - .collect(); - - for p in paths { - let candidate = p.join(cmd); - if candidate.is_file() { - return Ok(true); - } - #[cfg(windows)] - { - for ext in &exts { - let cand = p.join(format!("{}{}", cmd, ext)); - if cand.is_file() { - return Ok(true); - } - } - } - } - Ok(false) -} - /// 读取 ~/.claude.json 中的 mcpServers 映射 pub fn read_mcp_servers_map() -> Result, AppError> { let path = user_config_path(); diff --git a/src-tauri/src/commands/mcp.rs b/src-tauri/src/commands/mcp.rs index b097257df..416e5fc72 100644 --- a/src-tauri/src/commands/mcp.rs +++ b/src-tauri/src/commands/mcp.rs @@ -2,14 +2,12 @@ use crate::error::AppError; use indexmap::IndexMap; -use std::collections::HashMap; +use std::str::FromStr; -use serde::Serialize; use tauri::State; use super::run_db_task; use crate::app_config::AppType; -use crate::claude_mcp; use crate::services::McpService; use crate::store::AppState; @@ -38,54 +36,6 @@ pub fn cancel_mcp_connectivity_checks(batch_id: String) { crate::services::mcp_connectivity::cancel_checks(&batch_id); } -#[tauri::command] -pub async fn get_claude_mcp_status() -> Result { - claude_mcp::get_mcp_status() -} - -/// 读取 mcp.json 文本内容 -#[tauri::command] -pub async fn read_claude_mcp_config() -> Result, AppError> { - claude_mcp::read_mcp_json() -} - -#[tauri::command] -pub async fn delete_claude_mcp_server(id: String) -> Result { - claude_mcp::delete_mcp_server(&id) -} - -/// 校验命令是否在 PATH 中可用(不执行) -#[tauri::command] -pub async fn validate_mcp_command(cmd: String) -> Result { - claude_mcp::validate_command_in_path(&cmd) -} - -#[derive(Serialize)] -pub struct McpConfigResponse { - pub config_path: String, - pub servers: HashMap, -} - -/// 获取 MCP 配置(来自 ~/.cc-switch/config.json) -use std::str::FromStr; - -#[tauri::command] -#[allow(deprecated)] // 兼容层命令,内部调用已废弃的 Service 方法 -pub async fn get_mcp_config( - state: State<'_, AppState>, - app: String, -) -> Result { - let config_path = crate::config::get_app_config_path() - .to_string_lossy() - .to_string(); - let app_ty = AppType::from_str(&app)?; - let servers = McpService::get_servers(&state, app_ty)?; - Ok(McpConfigResponse { - config_path, - servers, - }) -} - // ============================================================================ // v3.7.0 新增:统一 MCP 管理命令 // ============================================================================ diff --git a/src-tauri/src/commands/provider.rs b/src-tauri/src/commands/provider.rs index f5cde4468..2307965f8 100644 --- a/src-tauri/src/commands/provider.rs +++ b/src-tauri/src/commands/provider.rs @@ -996,17 +996,6 @@ pub async fn get_universal_providers( run_db_task(&state, ProviderService::list_universal).await } -#[tauri::command] -pub async fn get_universal_provider( - state: State<'_, AppState>, - id: String, -) -> Result, String> { - run_db_task(&state, move |state| { - ProviderService::get_universal(state, &id) - }) - .await -} - /// 保存 / 删除是读整份映射再写回,同步按映射重写子供应商:主线程不再替它们排队, /// 连点「复制」会读到同一份旧映射、后写者覆盖前者,同步与删除交错会留下孤儿子供应商。 pub(super) static UNIVERSAL_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); diff --git a/src-tauri/src/commands/skill.rs b/src-tauri/src/commands/skill.rs index 463d0d675..a6d45af25 100644 --- a/src-tauri/src/commands/skill.rs +++ b/src-tauri/src/commands/skill.rs @@ -6,10 +6,9 @@ use super::run_db_task; use crate::app_config::{AppType, InstalledSkill, UnmanagedSkill}; -use crate::error::format_skill_error; use crate::error::AppError; use crate::services::skill::{ - DiscoverableSkill, ImportSkillSelection, MigrationResult, Skill, SkillAppSyncOutcome, + DiscoverableSkill, ImportSkillSelection, MigrationResult, SkillAppSyncOutcome, SkillBackupEntry, SkillDiscoveryResult, SkillRepo, SkillService, SkillStorageLocation, SkillUninstallResult, SkillUpdateCheckResult, SkillsShSearchResult, ZipInstallResult, }; @@ -286,121 +285,6 @@ pub async fn search_skills_sh( .map_err(|e| e.to_string()) } -// ========== 兼容旧 API 的命令 ========== - -/// 获取技能列表(兼容旧 API) -#[tauri::command] -pub async fn get_skills( - service: State<'_, SkillServiceState>, - app_state: State<'_, AppState>, -) -> Result, String> { - let repos = app_state.db.get_skill_repos()?; - service - .0 - .list_skills(repos, &app_state.db) - .await - .map_err(|e| e.to_string()) -} - -/// 获取指定应用的技能列表(兼容旧 API) -#[tauri::command] -pub async fn get_skills_for_app( - app: String, - service: State<'_, SkillServiceState>, - app_state: State<'_, AppState>, -) -> Result, String> { - // 新版本不再区分应用,统一返回所有技能 - let _ = parse_app_type(&app)?; // 验证 app 参数有效 - get_skills(service, app_state).await -} - -/// 安装技能(兼容旧 API) -#[tauri::command] -pub async fn install_skill( - directory: String, - service: State<'_, SkillServiceState>, - app_state: State<'_, AppState>, -) -> Result { - install_skill_for_app("claude".to_string(), directory, service, app_state).await -} - -/// 安装指定应用的技能(兼容旧 API) -#[tauri::command] -pub async fn install_skill_for_app( - app: String, - directory: String, - service: State<'_, SkillServiceState>, - app_state: State<'_, AppState>, -) -> Result { - let app_type = parse_app_type(&app)?; - - // 先获取技能信息 - let repos = app_state.db.get_skill_repos()?; - let skills = service - .0 - .discover_available(repos) - .await - .map_err(|e| e.to_string())?; - - let skill = skills - .into_iter() - .find(|s| { - let install_name = std::path::Path::new(&s.directory) - .file_name() - .map(|n| n.to_string_lossy().to_string()) - .unwrap_or_else(|| s.directory.clone()); - install_name.eq_ignore_ascii_case(&directory) - || s.directory.eq_ignore_ascii_case(&directory) - }) - .ok_or_else(|| { - format_skill_error( - "SKILL_NOT_FOUND", - &[("directory", &directory)], - Some("checkRepoUrl"), - ) - })?; - - service - .0 - .install(&app_state.db, &skill, &app_type) - .await - .map_err(|e| e.to_string())?; - - Ok(true) -} - -/// 卸载技能(兼容旧 API) -#[tauri::command] -pub async fn uninstall_skill( - directory: String, - app_state: State<'_, AppState>, -) -> Result { - uninstall_skill_for_app("claude".to_string(), directory, app_state).await -} - -/// 卸载指定应用的技能(兼容旧 API) -#[tauri::command] -pub async fn uninstall_skill_for_app( - app: String, - directory: String, - app_state: State<'_, AppState>, -) -> Result { - let _ = parse_app_type(&app)?; // 验证参数 - - run_db_task(&app_state, move |state| { - // 通过 directory 找到对应的 skill id - let skills = SkillService::get_all_installed(&state.db).map_err(|e| e.to_string())?; - - let skill = skills - .into_iter() - .find(|s| s.directory.eq_ignore_ascii_case(&directory)) - .ok_or_else(|| format!("未找到已安装的 Skill: {directory}"))?; - - SkillService::uninstall(&state.db, &skill.id).map_err(|e| e.to_string()) - }) - .await -} - // ========== 仓库管理命令 ========== #[tauri::command] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 17bd5a57f..a8c82eb40 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1670,10 +1670,6 @@ pub fn run() { commands::apply_claude_onboarding_skip, commands::clear_claude_onboarding_skip, // Claude MCP management - commands::get_claude_mcp_status, - commands::read_claude_mcp_config, - commands::delete_claude_mcp_server, - commands::validate_mcp_command, // usage query commands::queryProviderUsage, commands::testUsageScript, @@ -1686,7 +1682,6 @@ pub fn run() { commands::get_coding_plan_quota, commands::get_balance, // New MCP via config.json (SSOT) - commands::get_mcp_config, // Unified MCP management commands::get_mcp_servers, commands::start_mcp_connectivity_checks, @@ -1797,12 +1792,6 @@ pub fn run() { commands::open_skill_dir, commands::search_skills_sh, // Skill management (legacy API compatibility) - commands::get_skills, - commands::get_skills_for_app, - commands::install_skill, - commands::install_skill_for_app, - commands::uninstall_skill, - commands::uninstall_skill_for_app, commands::get_skill_repos, commands::add_skill_repo, commands::remove_skill_repo, @@ -1897,7 +1886,6 @@ pub fn run() { commands::open_provider_terminal, // Universal Provider management commands::get_universal_providers, - commands::get_universal_provider, commands::upsert_universal_provider, commands::delete_universal_provider, commands::sync_universal_provider, diff --git a/src-tauri/src/services/mcp.rs b/src-tauri/src/services/mcp.rs index 834570dfc..3e153d074 100644 --- a/src-tauri/src/services/mcp.rs +++ b/src-tauri/src/services/mcp.rs @@ -1,5 +1,4 @@ use indexmap::IndexMap; -use std::collections::HashMap; use crate::app_config::{AppType, McpServer}; use crate::error::AppError; @@ -628,40 +627,6 @@ impl McpService { ))) } - // ======================================================================== - // 兼容层:支持旧的 v3.6.x 命令(已废弃,将在 v4.0 移除) - // ======================================================================== - - /// [已废弃] 获取指定应用的 MCP 服务器(兼容旧 API) - #[deprecated(since = "3.7.0", note = "Use get_all_servers instead")] - pub fn get_servers( - state: &AppState, - app: AppType, - ) -> Result, AppError> { - let all_servers = Self::get_all_servers(state)?; - let mut result = HashMap::new(); - - for (id, server) in all_servers { - if server.apps.is_enabled_for(&app) { - result.insert(id, server.server); - } - } - - Ok(result) - } - - /// [已废弃] 设置 MCP 服务器在指定应用的启用状态(兼容旧 API) - #[deprecated(since = "3.7.0", note = "Use toggle_app instead")] - pub fn set_enabled( - state: &AppState, - app: AppType, - id: &str, - enabled: bool, - ) -> Result { - Self::toggle_app(state, id, app, enabled)?; - Ok(true) - } - /// 从 Claude 导入 MCP(v3.7.0 已更新为统一结构) pub fn import_from_claude(state: &AppState) -> Result { // 创建临时 MultiAppConfig 用于导入 diff --git a/src-tauri/src/services/mod.rs b/src-tauri/src/services/mod.rs index b6641959f..2742a891b 100644 --- a/src-tauri/src/services/mod.rs +++ b/src-tauri/src/services/mod.rs @@ -56,7 +56,7 @@ pub use prompt::PromptService; pub use provider::{ProviderService, ProviderSortUpdate, SwitchResult}; pub use proxy::ProxyService; #[allow(unused_imports)] -pub use skill::{DiscoverableSkill, Skill, SkillRepo, SkillService}; +pub use skill::{DiscoverableSkill, SkillRepo, SkillService}; pub use speedtest::{EndpointLatency, SpeedtestService}; pub use usage_cache::UsageCache; #[allow(unused_imports)] diff --git a/src-tauri/src/services/provider/mod.rs b/src-tauri/src/services/provider/mod.rs index f2b16405a..47652f098 100644 --- a/src-tauri/src/services/provider/mod.rs +++ b/src-tauri/src/services/provider/mod.rs @@ -8446,14 +8446,6 @@ impl ProviderService { state.db.get_all_universal_providers() } - /// 获取单个统一供应商 - pub fn get_universal( - state: &AppState, - id: &str, - ) -> Result, AppError> { - state.db.get_universal_provider(id) - } - /// 添加或更新统一供应商(不自动同步,需手动调用 sync_universal_to_apps) pub fn upsert_universal( state: &AppState, diff --git a/src-tauri/src/services/skill.rs b/src-tauri/src/services/skill.rs index eebdbd32e..155863b3a 100644 --- a/src-tauri/src/services/skill.rs +++ b/src-tauri/src/services/skill.rs @@ -98,33 +98,6 @@ pub struct DiscoverableSkill { pub repo_branch: String, } -/// 技能对象(兼容旧 API,内部使用 DiscoverableSkill) -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Skill { - /// 唯一标识: "owner/name:directory" 或 "local:directory" - pub key: String, - /// 显示名称 (从 SKILL.md 解析) - pub name: String, - /// 技能描述 - pub description: String, - /// 目录名称 (安装路径的最后一段) - pub directory: String, - /// GitHub README URL - #[serde(rename = "readmeUrl")] - pub readme_url: Option, - /// 是否已安装 - pub installed: bool, - /// 仓库所有者 - #[serde(rename = "repoOwner")] - pub repo_owner: Option, - /// 仓库名称 - #[serde(rename = "repoName")] - pub repo_name: Option, - /// 分支名称 - #[serde(rename = "repoBranch")] - pub repo_branch: Option, -} - /// 仓库配置 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SkillRepo { @@ -3381,73 +3354,6 @@ impl SkillService { Ok(SkillDiscoveryResult { skills, failures }) } - /// 列出所有技能(兼容旧 API) - pub async fn list_skills( - &self, - repos: Vec, - db: &Arc, - ) -> Result> { - // 获取可发现的技能 - let discoverable = self.discover_available(repos).await?; - - // 获取已安装的技能 - let installed = db.get_all_installed_skills()?; - let installed_dirs: HashSet = - installed.values().map(|s| s.directory.clone()).collect(); - - // 转换为 Skill 格式 - let mut skills: Vec = discoverable - .into_iter() - .map(|d| { - let install_name = Path::new(&d.directory) - .file_name() - .map(|s| s.to_string_lossy().to_string()) - .unwrap_or_else(|| d.directory.clone()); - - Skill { - key: d.key, - name: d.name, - description: d.description, - directory: d.directory, - readme_url: d.readme_url, - installed: installed_dirs.contains(&install_name), - repo_owner: Some(d.repo_owner), - repo_name: Some(d.repo_name), - repo_branch: Some(d.repo_branch), - } - }) - .collect(); - - // 添加本地已安装但不在仓库中的技能 - for skill in installed.values() { - let already_in_list = skills.iter().any(|s| { - let s_install_name = Path::new(&s.directory) - .file_name() - .map(|n| n.to_string_lossy().to_string()) - .unwrap_or_else(|| s.directory.clone()); - s_install_name == skill.directory - }); - - if !already_in_list { - skills.push(Skill { - key: skill.id.clone(), - name: skill.name.clone(), - description: skill.description.clone().unwrap_or_default(), - directory: skill.directory.clone(), - readme_url: skill.readme_url.clone(), - installed: true, - repo_owner: skill.repo_owner.clone(), - repo_name: skill.repo_name.clone(), - repo_branch: skill.repo_branch.clone(), - }); - } - } - - skills.sort_by_key(|skill| skill.name.to_lowercase()); - - Ok(skills) - } - /// 只发现一个仓库(添加、重新启用仓库时用),不碰其它仓库。 pub async fn discover_repo(&self, repo: &SkillRepo) -> SkillDiscoveryResult { if !repo.enabled { diff --git a/src-tauri/tests/integration/mcp_commands.rs b/src-tauri/tests/integration/mcp_commands.rs index 4c9c0e6a9..4c9accab9 100644 --- a/src-tauri/tests/integration/mcp_commands.rs +++ b/src-tauri/tests/integration/mcp_commands.rs @@ -4,9 +4,9 @@ use std::fs; use serde_json::json; use cc_switch_lib::{ - get_claude_mcp_path, get_claude_mcp_status, get_claude_settings_path, get_grok_config_path, - import_default_config_test_hook, read_claude_mcp_config, update_settings, AppError, - AppSettings, AppType, McpApps, McpServer, McpService, MultiAppConfig, ProviderService, + get_claude_mcp_path, get_claude_settings_path, get_grok_config_path, + import_default_config_test_hook, update_settings, AppError, AppSettings, AppType, McpApps, + McpServer, McpService, MultiAppConfig, ProviderService, }; use crate::support::{ @@ -1716,61 +1716,6 @@ fn custom_claude_dir_sync_does_not_copy_default_profile() { ); } -#[test] -fn custom_claude_dir_read_only_mcp_queries_do_not_create_profile() { - let _guard = test_mutex().lock().unwrap_or_else(|e| e.into_inner()); - reset_test_fs(); - let home = ensure_test_home(); - let home_mcp_path = home.join(".claude.json"); - fs::write( - &home_mcp_path, - serde_json::to_string_pretty(&json!({ - "mcpServers": { - "home-only": { - "type": "stdio", - "command": "home-command" - } - }, - "profileSentinel": "home-profile" - })) - .expect("serialize default profile"), - ) - .expect("seed default Claude profile"); - - let custom_dir = home.join("profiles").join("work").join(".claude"); - fs::create_dir_all(&custom_dir).expect("create custom claude dir"); - update_settings(AppSettings { - claude_config_dir: Some(custom_dir.to_string_lossy().to_string()), - ..AppSettings::default() - }) - .expect("set custom claude config dir"); - - let expected_mcp_path = custom_dir.join(".claude.json"); - assert!( - !expected_mcp_path.exists(), - "custom profile should start without a live MCP file" - ); - - let status = - futures::executor::block_on(get_claude_mcp_status()).expect("get Claude MCP status"); - assert_eq!( - status.user_config_path, - expected_mcp_path.to_string_lossy(), - "status should report the custom profile MCP path" - ); - assert!( - !status.user_config_exists, - "status should report missing custom profile MCP file" - ); - let text = - futures::executor::block_on(read_claude_mcp_config()).expect("read Claude MCP config"); - assert_eq!(text, None, "missing custom profile should read as None"); - assert!( - !expected_mcp_path.exists(), - "read-only MCP queries should not copy or create the custom profile" - ); -} - #[test] fn sync_all_enabled_removes_known_disabled_but_preserves_unknown_live_entries() { let _guard = test_mutex().lock().unwrap_or_else(|e| e.into_inner()); diff --git a/src/lib/api/mcp.ts b/src/lib/api/mcp.ts index 19da8cb74..db92ffd1b 100644 --- a/src/lib/api/mcp.ts +++ b/src/lib/api/mcp.ts @@ -1,10 +1,5 @@ import { Channel, invoke } from "@tauri-apps/api/core"; -import type { - McpConfigResponse, - McpServer, - McpServersMap, - McpStatus, -} from "@/types"; +import type { McpServer, McpServersMap } from "@/types"; import type { AppId } from "./types"; export interface McpConnectivityResult { @@ -30,29 +25,6 @@ export const mcpApi = { await invoke("cancel_mcp_connectivity_checks", { batchId }); }, - async getStatus(): Promise { - return await invoke("get_claude_mcp_status"); - }, - - async readConfig(): Promise { - return await invoke("read_claude_mcp_config"); - }, - - async deleteServer(id: string): Promise { - return await invoke("delete_claude_mcp_server", { id }); - }, - - async validateCommand(cmd: string): Promise { - return await invoke("validate_mcp_command", { cmd }); - }, - - /** - * @deprecated 使用 getAllServers() 代替(v3.7.0+) - */ - async getConfig(app: AppId = "claude"): Promise { - return await invoke("get_mcp_config", { app }); - }, - // ======================================================================== // v3.7.0 新增:统一 MCP 管理 API // ======================================================================== diff --git a/src/lib/api/providers.ts b/src/lib/api/providers.ts index deb0d2d01..ac2a0c3ad 100644 --- a/src/lib/api/providers.ts +++ b/src/lib/api/providers.ts @@ -317,13 +317,6 @@ export const universalProvidersApi = { return await invoke("get_universal_providers"); }, - /** - * 获取单个统一供应商 - */ - async get(id: string): Promise { - return await invoke("get_universal_provider", { id }); - }, - /** * 添加或更新统一供应商 */ diff --git a/src/lib/api/skills.ts b/src/lib/api/skills.ts index bb82d66fc..e01f9f140 100644 --- a/src/lib/api/skills.ts +++ b/src/lib/api/skills.ts @@ -95,19 +95,6 @@ export interface ImportSkillSelection { apps: SkillApps; } -/** 技能对象(兼容旧 API) */ -export interface Skill { - key: string; - name: string; - description: string; - directory: string; - readmeUrl?: string; - installed: boolean; - repoOwner?: string; - repoName?: string; - repoBranch?: string; -} - /** Skill 更新信息 */ export interface SkillUpdateInfo { id: string; @@ -319,35 +306,6 @@ export const skillsApi = { return await invoke("search_skills_sh", { query, limit, offset }); }, - // ========== 兼容旧 API ========== - - /** 获取技能列表(兼容旧 API) */ - async getAll(app: AppId = "claude"): Promise { - if (app === "claude") { - return await invoke("get_skills"); - } - return await invoke("get_skills_for_app", { app }); - }, - - /** 安装技能(兼容旧 API) */ - async install(directory: string, app: AppId = "claude"): Promise { - if (app === "claude") { - return await invoke("install_skill", { directory }); - } - return await invoke("install_skill_for_app", { app, directory }); - }, - - /** 卸载技能(兼容旧 API) */ - async uninstall( - directory: string, - app: AppId = "claude", - ): Promise { - if (app === "claude") { - return await invoke("uninstall_skill", { directory }); - } - return await invoke("uninstall_skill_for_app", { app, directory }); - }, - // ========== 仓库管理 ========== /** 获取仓库列表 */ diff --git a/src/lib/api/vscode.ts b/src/lib/api/vscode.ts index 5506048d5..7904654aa 100644 --- a/src/lib/api/vscode.ts +++ b/src/lib/api/vscode.ts @@ -57,26 +57,4 @@ export const vscodeApi = { url, }); }, - - async exportConfigToFile(filePath: string) { - return await invoke("export_config_to_file", { - filePath, - }); - }, - - async importConfigFromFile(filePath: string) { - return await invoke("import_config_from_file", { - filePath, - }); - }, - - async saveFileDialog(defaultName: string): Promise { - return await invoke("save_file_dialog", { - defaultName, - }); - }, - - async openFileDialog(): Promise { - return await invoke("open_file_dialog"); - }, }; diff --git a/src/types.ts b/src/types.ts index 3eb6a3986..f8466025c 100644 --- a/src/types.ts +++ b/src/types.ts @@ -867,19 +867,6 @@ export interface McpServer { // MCP 服务器映射(id -> McpServer) export type McpServersMap = Record; -// MCP 配置状态 -export interface McpStatus { - userConfigPath: string; - userConfigExists: boolean; - serverCount: number; -} - -// 新:来自 config.json 的 MCP 列表响应 -export interface McpConfigResponse { - configPath: string; - servers: Record; -} - // ============================================================================ // 统一供应商(Universal Provider)- 跨应用共享配置 // ============================================================================ diff --git a/tests/lib/registeredCommands.test.ts b/tests/lib/registeredCommands.test.ts index 3dbbccfeb..004f0ae5c 100644 --- a/tests/lib/registeredCommands.test.ts +++ b/tests/lib/registeredCommands.test.ts @@ -1,5 +1,6 @@ import { readFileSync, readdirSync } from "node:fs"; import path from "node:path"; +import ts from "typescript"; import { describe, expect, it } from "vitest"; const ROOT = path.resolve(__dirname, "../.."); @@ -13,38 +14,171 @@ function registeredCommands(): string[] { ); } -function frontendSources(dir: string): string[] { +function frontendFiles(dir: string): ts.SourceFile[] { return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { const full = path.join(dir, entry.name); - if (entry.isDirectory()) return frontendSources(full); - return /\.(ts|tsx)$/.test(entry.name) ? [readFileSync(full, "utf8")] : []; + if (entry.isDirectory()) return frontendFiles(full); + if (!/\.(ts|tsx)$/.test(entry.name) || /\.test\.tsx?$/.test(entry.name)) + return []; + return [ + ts.createSourceFile( + full, + readFileSync(full, "utf8"), + ts.ScriptTarget.Latest, + true, + entry.name.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS, + ), + ]; }); } +function walk(node: ts.Node, visit: (node: ts.Node) => void) { + visit(node); + node.forEachChild((child) => walk(child, visit)); +} + +/** The named function a string sits in: `api.method`, `function name`, `const name = () =>`. */ +interface Wrapper { + object?: string; + name: ts.Identifier; +} + +function enclosingWrapper(node: ts.Node): Wrapper | undefined { + for (let n = node.parent; n; n = n.parent) { + let name: ts.Node | undefined; + let member: ts.Node | undefined; + if (ts.isFunctionDeclaration(n)) name = n.name; + else if (ts.isMethodDeclaration(n)) [name, member] = [n.name, n]; + else if (ts.isArrowFunction(n) || ts.isFunctionExpression(n)) { + if (ts.isPropertyAssignment(n.parent)) + [name, member] = [n.parent.name, n.parent]; + else if (ts.isVariableDeclaration(n.parent)) name = n.parent.name; + } + if (!name || !ts.isIdentifier(name)) continue; + const literal = member?.parent; + const holder = literal?.parent; + return holder && + ts.isVariableDeclaration(holder) && + ts.isIdentifier(holder.name) + ? { object: holder.name.text, name } + : { name }; + } + return undefined; +} + +function identifiersByName(files: ts.SourceFile[]) { + const index = new Map(); + for (const file of files) + walk(file, (node) => { + if (!ts.isIdentifier(node)) return; + const named = index.get(node.text) ?? []; + named.push(node); + index.set(node.text, named); + }); + return index; +} + +/** `mcpApi` used as a value (passed around), so its members may be called as `api.x`. */ +function escapes(object: string, index: Map) { + return (index.get(object) ?? []).some((node) => { + const parent = node.parent; + return !( + (ts.isPropertyAccessExpression(parent) && parent.expression === node) || + (ts.isVariableDeclaration(parent) && parent.name === node) || + ts.isImportSpecifier(parent) || + ts.isExportSpecifier(parent) || + ts.isTypeQueryNode(parent) + ); + }); +} + +/** Whether anything in src/ (outside tests) uses the wrapper. */ +function isReferenced( + wrapper: Wrapper, + index: Map, +): boolean { + const { object, name } = wrapper; + const anyAccess = object === undefined || escapes(object, index); + return (index.get(name.text) ?? []).some((node) => { + if (node === name) return false; + if (object === undefined) return true; + const parent = node.parent; + if (ts.isPropertyAccessExpression(parent) && parent.name === node) { + const owner = parent.expression; + return ( + anyAccess || + owner.kind === ts.SyntaxKind.ThisKeyword || + (ts.isIdentifier(owner) && owner.text === object) + ); + } + if (ts.isBindingElement(parent)) { + const holder = parent.parent.parent; + return ( + ts.isVariableDeclaration(holder) && + !!holder.initializer && + ts.isIdentifier(holder.initializer) && + holder.initializer.text === object + ); + } + return false; + }); +} + +/** Each string literal or template naming a command, as a matcher. */ +function commandStrings(files: ts.SourceFile[]) { + const sites: { matches: (name: string) => boolean; node: ts.Node }[] = []; + for (const file of files) { + walk(file, (node) => { + if ( + ts.isStringLiteral(node) || + ts.isNoSubstitutionTemplateLiteral(node) + ) { + const text = node.text; + sites.push({ matches: (name) => text === name, node }); + } else if ( + ts.isTemplateExpression(node) && + ts.isCallExpression(node.parent) && + node.parent.arguments[0] === node && + node.parent.expression.getText() === "invoke" + ) { + // invoke(`get_${app}_current_state`) and similar. + const parts = [ + node.head.text, + ...node.templateSpans.map((s) => s.literal.text), + ]; + const pattern = new RegExp( + `^${parts.map((p) => p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("\\w+")}$`, + ); + sites.push({ matches: (name) => pattern.test(name), node }); + } + }); + } + return sites; +} + describe("Tauri command registry", () => { - it("registers only commands the frontend invokes", () => { - const sources = frontendSources(path.join(ROOT, "src")); - // invoke(`get_${app}_current_state`) and similar: turn each template into a pattern. - const templates = sources.flatMap((source) => - [...source.matchAll(/invoke(?:<[^>]*>)?\(\s*`([^`]*)`/g)].map( - (m) => - new RegExp( - `^${m[1] - .split(/\$\{[^}]*\}/) - .map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")) - .join("\\w+")}$`, - ), - ), - ); - const uncalled = registeredCommands().filter( - (name) => - !sources.some((source) => - new RegExp(`["'\`/]${name}["'\`]`).test(source), - ) && !templates.some((pattern) => pattern.test(name)), - ); + it("registers only commands the frontend reaches through a used wrapper", () => { + const files = frontendFiles(path.join(ROOT, "src")); + const sites = commandStrings(files); + const index = identifiersByName(files); + const unreached = registeredCommands().flatMap((command) => { + const wrappers = sites + .filter((site) => site.matches(command)) + .map((site) => enclosingWrapper(site.node)); + const reached = wrappers.some( + (wrapper) => wrapper === undefined || isReferenced(wrapper, index), + ); + if (reached) return []; + const via = wrappers.map( + (w) => (w!.object ? `${w!.object}.` : "") + w!.name.text, + ); + return [ + via.length ? `${command} (only via unused ${via.join(", ")})` : command, + ]; + }); expect( - uncalled, - "These commands are registered in lib.rs generate_handler! but nothing under src/ invokes them. Delete the command (and its registration), or call it from the frontend.", + unreached, + "These commands are registered in lib.rs generate_handler! but nothing under src/ reaches them: either no string names them, or every function naming them is itself never used. Delete the command (and its registration and wrapper), or call it from the frontend.", ).toEqual([]); }); }); diff --git a/tests/msw/handlers.ts b/tests/msw/handlers.ts index 66c2f37e0..b0a339c4a 100644 --- a/tests/msw/handlers.ts +++ b/tests/msw/handlers.ts @@ -23,7 +23,6 @@ import { setSettings, getAppConfigDirOverride, setAppConfigDirOverrideState, - getMcpConfig, listCustomIcons, addCustomIcon, renameCustomIcon, @@ -238,13 +237,6 @@ export const handlers = [ }), // MCP APIs - http.post(`${TAURI_ENDPOINT}/get_mcp_config`, async ({ request }) => { - const { app } = await withJson<{ app: AppId }>(request); - return success(getMcpConfig(app)); - }), - - http.post(`${TAURI_ENDPOINT}/import_mcp_from_claude`, () => success(1)), - http.post(`${TAURI_ENDPOINT}/import_mcp_from_codex`, () => success(1)), http.post(`${TAURI_ENDPOINT}/resync_mcp_to_apps`, async ({ request }) => { const { apps } = await withJson<{ apps?: AppId[] | null }>(request); const targets = apps?.length @@ -320,18 +312,6 @@ export const handlers = [ http.post(`${TAURI_ENDPOINT}/is_portable_mode`, () => success(false)), - http.post( - `${TAURI_ENDPOINT}/select_config_directory`, - async ({ request }) => { - const { defaultPath, default_path } = await withJson<{ - defaultPath?: string; - default_path?: string; - }>(request); - const initial = defaultPath ?? default_path; - return success(initial ? `${initial}/picked` : "/mock/selected-dir"); - }, - ), - http.post(`${TAURI_ENDPOINT}/pick_directory`, async ({ request }) => { const { defaultPath, default_path } = await withJson<{ defaultPath?: string; @@ -455,8 +435,6 @@ export const handlers = [ http.post(`${TAURI_ENDPOINT}/remove_from_failover_queue`, () => success(true), ), - http.post(`${TAURI_ENDPOINT}/reorder_failover_queue`, () => success(true)), - http.post(`${TAURI_ENDPOINT}/set_failover_item_enabled`, () => success(true)), http.post(`${TAURI_ENDPOINT}/get_provider_health`, () => success({ diff --git a/tests/msw/state.ts b/tests/msw/state.ts index 5ca463050..2a9153e6e 100644 --- a/tests/msw/state.ts +++ b/tests/msw/state.ts @@ -1,6 +1,5 @@ import type { AppId } from "@/lib/api/types"; import type { - McpServer, Provider, SessionContentHit, SessionMessage, @@ -15,7 +14,6 @@ import { type ProvidersByApp = Record>; type CurrentProviderState = Record; -type McpConfigState = Record>; type LiveProviderIdsByApp = Record< "opencode" | "openclaw" | "hermes", string[] @@ -173,60 +171,6 @@ const createDefaultSessionMessages = (): Record => ({ let sessionsState = createDefaultSessions(); let sessionMessagesState = createDefaultSessionMessages(); -let mcpConfigs: McpConfigState = { - claude: { - sample: { - id: "sample", - name: "Sample Claude Server", - enabled: true, - apps: { - claude: true, - codex: false, - gemini: false, - opencode: false, - openclaw: false, - hermes: false, - }, - server: { - type: "stdio", - command: "claude-server", - }, - }, - }, - "claude-desktop": {}, - codex: { - httpServer: { - id: "httpServer", - name: "HTTP Codex Server", - enabled: false, - apps: { - claude: false, - codex: true, - gemini: false, - opencode: false, - openclaw: false, - hermes: false, - }, - server: { - type: "http", - url: "http://localhost:3000", - }, - }, - }, - gemini: {}, - grokbuild: {}, - opencode: {}, - openclaw: {}, - hermes: {}, - pi: {}, - mcode: {}, - kimi: {}, - dsh: {}, - agy: {}, - omp: {}, - copilot: {}, - workbuddy: {}, -}; const cloneProviders = (value: ProvidersByApp) => deepClone(value) as ProvidersByApp; @@ -322,60 +266,6 @@ export const resetProviderState = () => { language: "zh", }; appConfigDirOverride = null; - mcpConfigs = { - claude: { - sample: { - id: "sample", - name: "Sample Claude Server", - enabled: true, - apps: { - claude: true, - codex: false, - gemini: false, - opencode: false, - openclaw: false, - hermes: false, - }, - server: { - type: "stdio", - command: "claude-server", - }, - }, - }, - "claude-desktop": {}, - codex: { - httpServer: { - id: "httpServer", - name: "HTTP Codex Server", - enabled: false, - apps: { - claude: false, - codex: true, - gemini: false, - opencode: false, - openclaw: false, - hermes: false, - }, - server: { - type: "http", - url: "http://localhost:3000", - }, - }, - }, - gemini: {}, - grokbuild: {}, - opencode: {}, - openclaw: {}, - hermes: {}, - pi: {}, - mcode: {}, - kimi: {}, - dsh: {}, - agy: {}, - omp: {}, - copilot: {}, - workbuddy: {}, - }; }; export const getProviders = (appType: AppId) => @@ -455,17 +345,6 @@ export const setAppConfigDirOverrideState = (value: string | null) => { appConfigDirOverride = value; }; -export const getMcpConfig = (appType: AppId) => { - const servers = deepClone(mcpConfigs[appType] ?? {}) as Record< - string, - McpServer - >; - return { - configPath: `/mock/${appType}.mcp.json`, - servers, - }; -}; - export const listSessions = () => deepClone(sessionsState) as SessionMeta[]; export const getSessionMessages = (providerId: string, sourcePath: string) =>