mirror of
https://github.com/farion1231/cc-switch.git
synced 2026-07-26 06:24:32 +08:00
Compare commits
39 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b69a052009 | |||
| 1c739b7841 | |||
| dca1d822da | |||
| 65f50a0a29 | |||
| 3aa3f00251 | |||
| 7749e325a2 | |||
| 3b500be525 | |||
| 1dc1f86560 | |||
| 7574d049ff | |||
| d4487755bf | |||
| 3264d71a4d | |||
| b20e121013 | |||
| e98acf94fc | |||
| 304d14b1ab | |||
| d30562954a | |||
| 09a87c97b8 | |||
| d31531f88b | |||
| ae21754d50 | |||
| 7c1f13e4f3 | |||
| fd25c9949f | |||
| 6443dc897d | |||
| 7aa381cbb7 | |||
| 1de3f1b7f8 | |||
| edc71efe4c | |||
| 3faf22f1c9 | |||
| 0cb8b30f15 | |||
| be1c2ac76e | |||
| e7451bda22 | |||
| 5a3420932b | |||
| a2688603fb | |||
| 23a407544a | |||
| 2b34dc4ec9 | |||
| 529051f0e8 | |||
| 5d1eed563d | |||
| cc0b9352bc | |||
| 01d8bb53ac | |||
| 6e7547ef6e | |||
| d38fcd63ea | |||
| 824bf796a8 |
@@ -38,7 +38,7 @@ Get 10% OFF the GLM CODING PLAN with [this link](https://z.ai/subscribe?ic=8JVLJ
|
|||||||
|
|
||||||
<tr>
|
<tr>
|
||||||
<td width="180"><img src="assets/partners/logos/sds-en.png" alt="ShanDianShuo" width="150"></td>
|
<td width="180"><img src="assets/partners/logos/sds-en.png" alt="ShanDianShuo" width="150"></td>
|
||||||
<td>Thanks to ShanDianShuo for sponsoring this project! ShanDianShuo is a local-first AI voice input: Millisecond latency, data stays on device, 4x faster than typing, AI-powered correction, Privacy-first, completely free. Doubles your coding efficiency with Claude Code! <a href="shandianshuo.cn">Free download</a> for Mac/Win</td>
|
<td>Thanks to ShanDianShuo for sponsoring this project! ShanDianShuo is a local-first AI voice input: Millisecond latency, data stays on device, 4x faster than typing, AI-powered correction, Privacy-first, completely free. Doubles your coding efficiency with Claude Code! <a href="https://www.shandianshuo.cn">Free download</a> for Mac/Win</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|
||||||
</table>
|
</table>
|
||||||
|
|||||||
+1
-1
@@ -38,7 +38,7 @@ CC Switch 已经预设了智谱GLM,只需要填写 key 即可一键导入编
|
|||||||
|
|
||||||
<tr>
|
<tr>
|
||||||
<td width="180"><img src="assets/partners/logos/sds-zh.png" alt="ShanDianShuo" width="150"></td>
|
<td width="180"><img src="assets/partners/logos/sds-zh.png" alt="ShanDianShuo" width="150"></td>
|
||||||
<td>感谢闪电说赞助了本项目!闪电说是本地优先的 AI 语音输入法:毫秒级响应,数据不离设备;打字速度提升 4 倍,AI 智能纠错;绝对隐私安全,完全免费,配合 Claude Code 写代码效率翻倍!支持 Mac/Win 双平台,<a href="shandianshuo.cn">免费下载</a></td>
|
<td>感谢闪电说赞助了本项目!闪电说是本地优先的 AI 语音输入法:毫秒级响应,数据不离设备;打字速度提升 4 倍,AI 智能纠错;绝对隐私安全,完全免费,配合 Claude Code 写代码效率翻倍!支持 Mac/Win 双平台,<a href="https://www.shandianshuo.cn">免费下载</a></td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|
||||||
</table>
|
</table>
|
||||||
|
|||||||
+1041
File diff suppressed because it is too large
Load Diff
@@ -14,6 +14,7 @@ const KEEP_LIST = [
|
|||||||
'zhipu', 'chatglm', 'glm', 'minimax', 'mistral', 'cohere',
|
'zhipu', 'chatglm', 'glm', 'minimax', 'mistral', 'cohere',
|
||||||
'perplexity', 'huggingface', 'midjourney', 'stability',
|
'perplexity', 'huggingface', 'midjourney', 'stability',
|
||||||
'xai', 'grok', 'yi', 'zeroone', 'ollama',
|
'xai', 'grok', 'yi', 'zeroone', 'ollama',
|
||||||
|
'packycode',
|
||||||
|
|
||||||
// Cloud/Tools
|
// Cloud/Tools
|
||||||
'aws', 'googlecloud', 'huawei', 'cloudflare',
|
'aws', 'googlecloud', 'huawei', 'cloudflare',
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ const KNOWN_METADATA = {
|
|||||||
microsoft: { name: 'microsoft', displayName: 'Microsoft', category: 'ai-provider', keywords: ['copilot', 'azure'], defaultColor: '#00A4EF' },
|
microsoft: { name: 'microsoft', displayName: 'Microsoft', category: 'ai-provider', keywords: ['copilot', 'azure'], defaultColor: '#00A4EF' },
|
||||||
cohere: { name: 'cohere', displayName: 'Cohere', category: 'ai-provider', keywords: ['cohere'], defaultColor: '#39594D' },
|
cohere: { name: 'cohere', displayName: 'Cohere', category: 'ai-provider', keywords: ['cohere'], defaultColor: '#39594D' },
|
||||||
perplexity: { name: 'perplexity', displayName: 'Perplexity', category: 'ai-provider', keywords: ['perplexity'], defaultColor: '#20808D' },
|
perplexity: { name: 'perplexity', displayName: 'Perplexity', category: 'ai-provider', keywords: ['perplexity'], defaultColor: '#20808D' },
|
||||||
|
packycode: { name: 'packycode', displayName: 'PackyCode', category: 'ai-provider', keywords: ['packycode', 'packy', 'packyapi'], defaultColor: 'currentColor' },
|
||||||
mistral: { name: 'mistral', displayName: 'Mistral', category: 'ai-provider', keywords: ['mistral'], defaultColor: '#FF7000' },
|
mistral: { name: 'mistral', displayName: 'Mistral', category: 'ai-provider', keywords: ['mistral'], defaultColor: '#FF7000' },
|
||||||
huggingface: { name: 'huggingface', displayName: 'Hugging Face', category: 'ai-provider', keywords: ['huggingface', 'hf'], defaultColor: '#FFD21E' },
|
huggingface: { name: 'huggingface', displayName: 'Hugging Face', category: 'ai-provider', keywords: ['huggingface', 'hf'], defaultColor: '#FFD21E' },
|
||||||
aws: { name: 'aws', displayName: 'AWS', category: 'cloud', keywords: ['amazon', 'cloud'], defaultColor: '#FF9900' },
|
aws: { name: 'aws', displayName: 'AWS', category: 'cloud', keywords: ['amazon', 'cloud'], defaultColor: '#FF9900' },
|
||||||
|
|||||||
Generated
+70
-1
@@ -39,6 +39,18 @@ dependencies = [
|
|||||||
"version_check",
|
"version_check",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ahash"
|
||||||
|
version = "0.8.12"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"once_cell",
|
||||||
|
"version_check",
|
||||||
|
"zerocopy",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "aho-corasick"
|
name = "aho-corasick"
|
||||||
version = "1.1.3"
|
version = "1.1.3"
|
||||||
@@ -614,6 +626,7 @@ dependencies = [
|
|||||||
"chrono",
|
"chrono",
|
||||||
"dirs 5.0.1",
|
"dirs 5.0.1",
|
||||||
"futures",
|
"futures",
|
||||||
|
"indexmap 2.11.4",
|
||||||
"log",
|
"log",
|
||||||
"objc2 0.5.2",
|
"objc2 0.5.2",
|
||||||
"objc2-app-kit 0.2.2",
|
"objc2-app-kit 0.2.2",
|
||||||
@@ -621,6 +634,7 @@ dependencies = [
|
|||||||
"regex",
|
"regex",
|
||||||
"reqwest",
|
"reqwest",
|
||||||
"rquickjs",
|
"rquickjs",
|
||||||
|
"rusqlite",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"serde_yaml",
|
"serde_yaml",
|
||||||
@@ -1275,6 +1289,18 @@ dependencies = [
|
|||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "fallible-iterator"
|
||||||
|
version = "0.3.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "fallible-streaming-iterator"
|
||||||
|
version = "0.1.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "fastrand"
|
name = "fastrand"
|
||||||
version = "2.3.0"
|
version = "2.3.0"
|
||||||
@@ -1813,7 +1839,7 @@ version = "0.12.3"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
|
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"ahash",
|
"ahash 0.7.8",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1821,6 +1847,9 @@ name = "hashbrown"
|
|||||||
version = "0.14.5"
|
version = "0.14.5"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
|
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
|
||||||
|
dependencies = [
|
||||||
|
"ahash 0.8.12",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "hashbrown"
|
name = "hashbrown"
|
||||||
@@ -1828,6 +1857,15 @@ version = "0.16.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "5419bdc4f6a9207fbeba6d11b604d481addf78ecd10c11ad51e76c2f6482748d"
|
checksum = "5419bdc4f6a9207fbeba6d11b604d481addf78ecd10c11ad51e76c2f6482748d"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "hashlink"
|
||||||
|
version = "0.9.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"
|
||||||
|
dependencies = [
|
||||||
|
"hashbrown 0.14.5",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "heck"
|
name = "heck"
|
||||||
version = "0.4.1"
|
version = "0.4.1"
|
||||||
@@ -2398,6 +2436,17 @@ dependencies = [
|
|||||||
"redox_syscall",
|
"redox_syscall",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "libsqlite3-sys"
|
||||||
|
version = "0.28.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0c10584274047cb335c23d3e61bcef8e323adae7c5c8c760540f73610177fc3f"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
"pkg-config",
|
||||||
|
"vcpkg",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "linux-raw-sys"
|
name = "linux-raw-sys"
|
||||||
version = "0.11.0"
|
version = "0.11.0"
|
||||||
@@ -3849,6 +3898,20 @@ dependencies = [
|
|||||||
"cc",
|
"cc",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rusqlite"
|
||||||
|
version = "0.31.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b838eba278d213a8beaf485bd313fd580ca4505a00d5871caeb1457c55322cae"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 2.9.4",
|
||||||
|
"fallible-iterator",
|
||||||
|
"fallible-streaming-iterator",
|
||||||
|
"hashlink",
|
||||||
|
"libsqlite3-sys",
|
||||||
|
"smallvec",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rust-ini"
|
name = "rust-ini"
|
||||||
version = "0.21.3"
|
version = "0.21.3"
|
||||||
@@ -5567,6 +5630,12 @@ version = "1.11.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "943ce29a8a743eb10d6082545d861b24f9d1b160b7d741e0f2cdf726bec909c5"
|
checksum = "943ce29a8a743eb10d6082545d861b24f9d1b160b7d741e0f2cdf726bec909c5"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "vcpkg"
|
||||||
|
version = "0.2.15"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "version-compare"
|
name = "version-compare"
|
||||||
version = "0.2.0"
|
version = "0.2.0"
|
||||||
|
|||||||
@@ -51,6 +51,8 @@ url = "2.5"
|
|||||||
auto-launch = "0.5"
|
auto-launch = "0.5"
|
||||||
once_cell = "1.21.3"
|
once_cell = "1.21.3"
|
||||||
base64 = "0.22"
|
base64 = "0.22"
|
||||||
|
rusqlite = { version = "0.31", features = ["bundled", "backup"] }
|
||||||
|
indexmap = { version = "2", features = ["serde"] }
|
||||||
|
|
||||||
[target.'cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))'.dependencies]
|
[target.'cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))'.dependencies]
|
||||||
tauri-plugin-single-instance = "2"
|
tauri-plugin-single-instance = "2"
|
||||||
|
|||||||
@@ -494,8 +494,11 @@ impl MultiAppConfig {
|
|||||||
// 创建提示词对象
|
// 创建提示词对象
|
||||||
let timestamp = std::time::SystemTime::now()
|
let timestamp = std::time::SystemTime::now()
|
||||||
.duration_since(std::time::UNIX_EPOCH)
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
.unwrap()
|
.map(|d| d.as_secs() as i64)
|
||||||
.as_secs() as i64;
|
.unwrap_or_else(|_| {
|
||||||
|
log::warn!("Failed to get system time, using 0 as timestamp");
|
||||||
|
0
|
||||||
|
});
|
||||||
|
|
||||||
let id = format!("auto-imported-{timestamp}");
|
let id = format!("auto-imported-{timestamp}");
|
||||||
let prompt = crate::prompt::Prompt {
|
let prompt = crate::prompt::Prompt {
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ pub fn get_codex_config_path() -> PathBuf {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// 获取 Codex 供应商配置文件路径
|
/// 获取 Codex 供应商配置文件路径
|
||||||
|
#[allow(dead_code)]
|
||||||
pub fn get_codex_provider_paths(
|
pub fn get_codex_provider_paths(
|
||||||
provider_id: &str,
|
provider_id: &str,
|
||||||
provider_name: Option<&str>,
|
provider_name: Option<&str>,
|
||||||
@@ -44,6 +45,7 @@ pub fn get_codex_provider_paths(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// 删除 Codex 供应商配置文件
|
/// 删除 Codex 供应商配置文件
|
||||||
|
#[allow(dead_code)]
|
||||||
pub fn delete_codex_provider_config(
|
pub fn delete_codex_provider_config(
|
||||||
provider_id: &str,
|
provider_id: &str,
|
||||||
provider_name: &str,
|
provider_name: &str,
|
||||||
|
|||||||
@@ -141,11 +141,10 @@ pub async fn open_app_config_folder(handle: AppHandle) -> Result<bool, String> {
|
|||||||
pub async fn get_claude_common_config_snippet(
|
pub async fn get_claude_common_config_snippet(
|
||||||
state: tauri::State<'_, crate::store::AppState>,
|
state: tauri::State<'_, crate::store::AppState>,
|
||||||
) -> Result<Option<String>, String> {
|
) -> Result<Option<String>, String> {
|
||||||
let guard = state
|
state
|
||||||
.config
|
.db
|
||||||
.read()
|
.get_config_snippet("claude")
|
||||||
.map_err(|e| format!("读取配置锁失败: {e}"))?;
|
.map_err(|e| e.to_string())
|
||||||
Ok(guard.common_config_snippets.claude.clone())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 设置 Claude 通用配置片段(已废弃,使用 set_common_config_snippet)
|
/// 设置 Claude 通用配置片段(已废弃,使用 set_common_config_snippet)
|
||||||
@@ -154,24 +153,22 @@ pub async fn set_claude_common_config_snippet(
|
|||||||
snippet: String,
|
snippet: String,
|
||||||
state: tauri::State<'_, crate::store::AppState>,
|
state: tauri::State<'_, crate::store::AppState>,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
let mut guard = state
|
|
||||||
.config
|
|
||||||
.write()
|
|
||||||
.map_err(|e| format!("写入配置锁失败: {e}"))?;
|
|
||||||
|
|
||||||
// 验证是否为有效的 JSON(如果不为空)
|
// 验证是否为有效的 JSON(如果不为空)
|
||||||
if !snippet.trim().is_empty() {
|
if !snippet.trim().is_empty() {
|
||||||
serde_json::from_str::<serde_json::Value>(&snippet)
|
serde_json::from_str::<serde_json::Value>(&snippet)
|
||||||
.map_err(|e| format!("无效的 JSON 格式: {e}"))?;
|
.map_err(|e| format!("无效的 JSON 格式: {e}"))?;
|
||||||
}
|
}
|
||||||
|
|
||||||
guard.common_config_snippets.claude = if snippet.trim().is_empty() {
|
let value = if snippet.trim().is_empty() {
|
||||||
None
|
None
|
||||||
} else {
|
} else {
|
||||||
Some(snippet)
|
Some(snippet)
|
||||||
};
|
};
|
||||||
|
|
||||||
guard.save().map_err(|e| e.to_string())?;
|
state
|
||||||
|
.db
|
||||||
|
.set_config_snippet("claude", value)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -181,17 +178,10 @@ pub async fn get_common_config_snippet(
|
|||||||
app_type: String,
|
app_type: String,
|
||||||
state: tauri::State<'_, crate::store::AppState>,
|
state: tauri::State<'_, crate::store::AppState>,
|
||||||
) -> Result<Option<String>, String> {
|
) -> Result<Option<String>, String> {
|
||||||
use crate::app_config::AppType;
|
state
|
||||||
use std::str::FromStr;
|
.db
|
||||||
|
.get_config_snippet(&app_type)
|
||||||
let app = AppType::from_str(&app_type).map_err(|e| format!("无效的应用类型: {e}"))?;
|
.map_err(|e| e.to_string())
|
||||||
|
|
||||||
let guard = state
|
|
||||||
.config
|
|
||||||
.read()
|
|
||||||
.map_err(|e| format!("读取配置锁失败: {e}"))?;
|
|
||||||
|
|
||||||
Ok(guard.common_config_snippets.get(&app).cloned())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 设置通用配置片段(统一接口)
|
/// 设置通用配置片段(统一接口)
|
||||||
@@ -201,40 +191,31 @@ pub async fn set_common_config_snippet(
|
|||||||
snippet: String,
|
snippet: String,
|
||||||
state: tauri::State<'_, crate::store::AppState>,
|
state: tauri::State<'_, crate::store::AppState>,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
use crate::app_config::AppType;
|
|
||||||
use std::str::FromStr;
|
|
||||||
|
|
||||||
let app = AppType::from_str(&app_type).map_err(|e| format!("无效的应用类型: {e}"))?;
|
|
||||||
|
|
||||||
let mut guard = state
|
|
||||||
.config
|
|
||||||
.write()
|
|
||||||
.map_err(|e| format!("写入配置锁失败: {e}"))?;
|
|
||||||
|
|
||||||
// 验证格式(根据应用类型)
|
// 验证格式(根据应用类型)
|
||||||
if !snippet.trim().is_empty() {
|
if !snippet.trim().is_empty() {
|
||||||
match app {
|
match app_type.as_str() {
|
||||||
AppType::Claude | AppType::Gemini => {
|
"claude" | "gemini" => {
|
||||||
// 验证 JSON 格式
|
// 验证 JSON 格式
|
||||||
serde_json::from_str::<serde_json::Value>(&snippet)
|
serde_json::from_str::<serde_json::Value>(&snippet)
|
||||||
.map_err(|e| format!("无效的 JSON 格式: {e}"))?;
|
.map_err(|e| format!("无效的 JSON 格式: {e}"))?;
|
||||||
}
|
}
|
||||||
AppType::Codex => {
|
"codex" => {
|
||||||
// TOML 格式暂不验证(或可使用 toml crate)
|
// TOML 格式暂不验证(或可使用 toml crate)
|
||||||
// 注意:TOML 验证较为复杂,暂时跳过
|
// 注意:TOML 验证较为复杂,暂时跳过
|
||||||
}
|
}
|
||||||
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
guard.common_config_snippets.set(
|
let value = if snippet.trim().is_empty() {
|
||||||
&app,
|
None
|
||||||
if snippet.trim().is_empty() {
|
} else {
|
||||||
None
|
Some(snippet)
|
||||||
} else {
|
};
|
||||||
Some(snippet)
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
guard.save().map_err(|e| e.to_string())?;
|
state
|
||||||
|
.db
|
||||||
|
.set_config_snippet(&app_type, value)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
use crate::deeplink::{import_provider_from_deeplink, parse_deeplink_url, DeepLinkImportRequest};
|
use crate::deeplink::{
|
||||||
|
import_mcp_from_deeplink, import_prompt_from_deeplink, import_provider_from_deeplink,
|
||||||
|
import_skill_from_deeplink, parse_deeplink_url, DeepLinkImportRequest,
|
||||||
|
};
|
||||||
use crate::store::AppState;
|
use crate::store::AppState;
|
||||||
use tauri::State;
|
use tauri::State;
|
||||||
|
|
||||||
@@ -15,18 +18,18 @@ pub fn parse_deeplink(url: String) -> Result<DeepLinkImportRequest, String> {
|
|||||||
pub fn merge_deeplink_config(
|
pub fn merge_deeplink_config(
|
||||||
request: DeepLinkImportRequest,
|
request: DeepLinkImportRequest,
|
||||||
) -> Result<DeepLinkImportRequest, String> {
|
) -> Result<DeepLinkImportRequest, String> {
|
||||||
log::info!("Merging config for deep link request: {}", request.name);
|
log::info!("Merging config for deep link request: {:?}", request.name);
|
||||||
crate::deeplink::parse_and_merge_config(&request).map_err(|e| e.to_string())
|
crate::deeplink::parse_and_merge_config(&request).map_err(|e| e.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Import a provider from a deep link request (after user confirmation)
|
/// Import a provider from a deep link request (legacy, kept for compatibility)
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn import_from_deeplink(
|
pub fn import_from_deeplink(
|
||||||
state: State<AppState>,
|
state: State<AppState>,
|
||||||
request: DeepLinkImportRequest,
|
request: DeepLinkImportRequest,
|
||||||
) -> Result<String, String> {
|
) -> Result<String, String> {
|
||||||
log::info!(
|
log::info!(
|
||||||
"Importing provider from deep link: {} for app {}",
|
"Importing provider from deep link: {:?} for app {:?}",
|
||||||
request.name,
|
request.name,
|
||||||
request.app
|
request.app
|
||||||
);
|
);
|
||||||
@@ -37,3 +40,50 @@ pub fn import_from_deeplink(
|
|||||||
|
|
||||||
Ok(provider_id)
|
Ok(provider_id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Import resource from a deep link request (unified handler)
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn import_from_deeplink_unified(
|
||||||
|
state: State<'_, AppState>,
|
||||||
|
request: DeepLinkImportRequest,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
log::info!("Importing {} resource from deep link", request.resource);
|
||||||
|
|
||||||
|
match request.resource.as_str() {
|
||||||
|
"provider" => {
|
||||||
|
let provider_id =
|
||||||
|
import_provider_from_deeplink(&state, request).map_err(|e| e.to_string())?;
|
||||||
|
Ok(serde_json::json!({
|
||||||
|
"type": "provider",
|
||||||
|
"id": provider_id
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
"prompt" => {
|
||||||
|
let prompt_id =
|
||||||
|
import_prompt_from_deeplink(&state, request).map_err(|e| e.to_string())?;
|
||||||
|
Ok(serde_json::json!({
|
||||||
|
"type": "prompt",
|
||||||
|
"id": prompt_id
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
"mcp" => {
|
||||||
|
let result = import_mcp_from_deeplink(&state, request).map_err(|e| e.to_string())?;
|
||||||
|
// Add type field to the result
|
||||||
|
Ok(serde_json::json!({
|
||||||
|
"type": "mcp",
|
||||||
|
"importedCount": result.imported_count,
|
||||||
|
"importedIds": result.imported_ids,
|
||||||
|
"failed": result.failed
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
"skill" => {
|
||||||
|
let skill_key =
|
||||||
|
import_skill_from_deeplink(&state, request).map_err(|e| e.to_string())?;
|
||||||
|
Ok(serde_json::json!({
|
||||||
|
"type": "skill",
|
||||||
|
"key": skill_key
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
_ => Err(format!("Unsupported resource type: {}", request.resource)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -6,20 +6,22 @@ use tauri::State;
|
|||||||
use tauri_plugin_dialog::DialogExt;
|
use tauri_plugin_dialog::DialogExt;
|
||||||
|
|
||||||
use crate::error::AppError;
|
use crate::error::AppError;
|
||||||
use crate::services::ConfigService;
|
use crate::services::provider::ProviderService;
|
||||||
use crate::store::AppState;
|
use crate::store::AppState;
|
||||||
|
|
||||||
/// 导出配置文件
|
/// 导出数据库为 SQL 备份
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn export_config_to_file(
|
pub async fn export_config_to_file(
|
||||||
#[allow(non_snake_case)] filePath: String,
|
#[allow(non_snake_case)] filePath: String,
|
||||||
|
state: State<'_, AppState>,
|
||||||
) -> Result<Value, String> {
|
) -> Result<Value, String> {
|
||||||
|
let db = state.db.clone();
|
||||||
tauri::async_runtime::spawn_blocking(move || {
|
tauri::async_runtime::spawn_blocking(move || {
|
||||||
let target_path = PathBuf::from(&filePath);
|
let target_path = PathBuf::from(&filePath);
|
||||||
ConfigService::export_config_to_path(&target_path)?;
|
db.export_sql(&target_path)?;
|
||||||
Ok::<_, AppError>(json!({
|
Ok::<_, AppError>(json!({
|
||||||
"success": true,
|
"success": true,
|
||||||
"message": "Configuration exported successfully",
|
"message": "SQL exported successfully",
|
||||||
"filePath": filePath
|
"filePath": filePath
|
||||||
}))
|
}))
|
||||||
})
|
})
|
||||||
@@ -28,51 +30,49 @@ pub async fn export_config_to_file(
|
|||||||
.map_err(|e: AppError| e.to_string())
|
.map_err(|e: AppError| e.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 从文件导入配置
|
/// 从 SQL 备份导入数据库
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn import_config_from_file(
|
pub async fn import_config_from_file(
|
||||||
#[allow(non_snake_case)] filePath: String,
|
#[allow(non_snake_case)] filePath: String,
|
||||||
state: State<'_, AppState>,
|
state: State<'_, AppState>,
|
||||||
) -> Result<Value, String> {
|
) -> Result<Value, String> {
|
||||||
let (new_config, backup_id) = tauri::async_runtime::spawn_blocking(move || {
|
let db = state.db.clone();
|
||||||
|
let db_for_state = db.clone();
|
||||||
|
tauri::async_runtime::spawn_blocking(move || {
|
||||||
let path_buf = PathBuf::from(&filePath);
|
let path_buf = PathBuf::from(&filePath);
|
||||||
ConfigService::load_config_for_import(&path_buf)
|
let backup_id = db.import_sql(&path_buf)?;
|
||||||
|
|
||||||
|
// 导入后同步当前供应商到各自的 live 配置
|
||||||
|
let app_state = AppState::new(db_for_state);
|
||||||
|
if let Err(err) = ProviderService::sync_current_from_db(&app_state) {
|
||||||
|
log::warn!("导入后同步 live 配置失败: {err}");
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok::<_, AppError>(json!({
|
||||||
|
"success": true,
|
||||||
|
"message": "SQL imported successfully",
|
||||||
|
"backupId": backup_id
|
||||||
|
}))
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.map_err(|e| format!("导入配置失败: {e}"))?
|
.map_err(|e| format!("导入配置失败: {e}"))?
|
||||||
.map_err(|e: AppError| e.to_string())?;
|
.map_err(|e: AppError| e.to_string())
|
||||||
|
|
||||||
{
|
|
||||||
let mut guard = state
|
|
||||||
.config
|
|
||||||
.write()
|
|
||||||
.map_err(|e| AppError::from(e).to_string())?;
|
|
||||||
*guard = new_config;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(json!({
|
|
||||||
"success": true,
|
|
||||||
"message": "Configuration imported successfully",
|
|
||||||
"backupId": backup_id
|
|
||||||
}))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 同步当前供应商配置到对应的 live 文件
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn sync_current_providers_live(state: State<'_, AppState>) -> Result<Value, String> {
|
pub async fn sync_current_providers_live(state: State<'_, AppState>) -> Result<Value, String> {
|
||||||
{
|
let db = state.db.clone();
|
||||||
let mut config_state = state
|
tauri::async_runtime::spawn_blocking(move || {
|
||||||
.config
|
let app_state = AppState::new(db);
|
||||||
.write()
|
ProviderService::sync_current_from_db(&app_state)?;
|
||||||
.map_err(|e| AppError::from(e).to_string())?;
|
Ok::<_, AppError>(json!({
|
||||||
ConfigService::sync_current_providers_to_live(&mut config_state)
|
"success": true,
|
||||||
.map_err(|e| e.to_string())?;
|
"message": "Live configuration synchronized"
|
||||||
}
|
}))
|
||||||
|
})
|
||||||
Ok(json!({
|
.await
|
||||||
"success": true,
|
.map_err(|e| format!("同步当前供应商失败: {e}"))?
|
||||||
"message": "Live configuration synchronized"
|
.map_err(|e: AppError| e.to_string())
|
||||||
}))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 保存文件对话框
|
/// 保存文件对话框
|
||||||
@@ -84,7 +84,7 @@ pub async fn save_file_dialog<R: tauri::Runtime>(
|
|||||||
let dialog = app.dialog();
|
let dialog = app.dialog();
|
||||||
let result = dialog
|
let result = dialog
|
||||||
.file()
|
.file()
|
||||||
.add_filter("JSON", &["json"])
|
.add_filter("SQL", &["sql"])
|
||||||
.set_file_name(&defaultName)
|
.set_file_name(&defaultName)
|
||||||
.blocking_save_file();
|
.blocking_save_file();
|
||||||
|
|
||||||
@@ -99,7 +99,7 @@ pub async fn open_file_dialog<R: tauri::Runtime>(
|
|||||||
let dialog = app.dialog();
|
let dialog = app.dialog();
|
||||||
let result = dialog
|
let result = dialog
|
||||||
.file()
|
.file()
|
||||||
.add_filter("JSON", &["json"])
|
.add_filter("SQL", &["sql"])
|
||||||
.blocking_pick_file();
|
.blocking_pick_file();
|
||||||
|
|
||||||
Ok(result.map(|p| p.to_string()))
|
Ok(result.map(|p| p.to_string()))
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
#![allow(non_snake_case)]
|
#![allow(non_snake_case)]
|
||||||
|
|
||||||
|
use indexmap::IndexMap;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
@@ -82,12 +83,8 @@ pub async fn upsert_mcp_server_in_config(
|
|||||||
|
|
||||||
// 读取现有的服务器(如果存在)
|
// 读取现有的服务器(如果存在)
|
||||||
let existing_server = {
|
let existing_server = {
|
||||||
let cfg = state.config.read().map_err(|e| e.to_string())?;
|
let servers = state.db.get_all_mcp_servers().map_err(|e| e.to_string())?;
|
||||||
if let Some(servers) = &cfg.mcp.servers {
|
servers.get(&id).cloned()
|
||||||
servers.get(&id).cloned()
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// 构建新的统一服务器结构
|
// 构建新的统一服务器结构
|
||||||
@@ -165,7 +162,7 @@ use crate::app_config::McpServer;
|
|||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn get_mcp_servers(
|
pub async fn get_mcp_servers(
|
||||||
state: State<'_, AppState>,
|
state: State<'_, AppState>,
|
||||||
) -> Result<HashMap<String, McpServer>, String> {
|
) -> Result<IndexMap<String, McpServer>, String> {
|
||||||
McpService::get_all_servers(&state).map_err(|e| e.to_string())
|
McpService::get_all_servers(&state).map_err(|e| e.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use std::collections::HashMap;
|
use indexmap::IndexMap;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
|
||||||
use tauri::State;
|
use tauri::State;
|
||||||
@@ -12,7 +12,7 @@ use crate::store::AppState;
|
|||||||
pub async fn get_prompts(
|
pub async fn get_prompts(
|
||||||
app: String,
|
app: String,
|
||||||
state: State<'_, AppState>,
|
state: State<'_, AppState>,
|
||||||
) -> Result<HashMap<String, Prompt>, String> {
|
) -> Result<IndexMap<String, Prompt>, String> {
|
||||||
let app_type = AppType::from_str(&app).map_err(|e| e.to_string())?;
|
let app_type = AppType::from_str(&app).map_err(|e| e.to_string())?;
|
||||||
PromptService::get_prompts(&state, app_type).map_err(|e| e.to_string())
|
PromptService::get_prompts(&state, app_type).map_err(|e| e.to_string())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use std::collections::HashMap;
|
use indexmap::IndexMap;
|
||||||
use tauri::State;
|
use tauri::State;
|
||||||
|
|
||||||
use crate::app_config::AppType;
|
use crate::app_config::AppType;
|
||||||
@@ -13,7 +13,7 @@ use std::str::FromStr;
|
|||||||
pub fn get_providers(
|
pub fn get_providers(
|
||||||
state: State<'_, AppState>,
|
state: State<'_, AppState>,
|
||||||
app: String,
|
app: String,
|
||||||
) -> Result<HashMap<String, Provider>, String> {
|
) -> Result<IndexMap<String, Provider>, String> {
|
||||||
let app_type = AppType::from_str(&app).map_err(|e| e.to_string())?;
|
let app_type = AppType::from_str(&app).map_err(|e| e.to_string())?;
|
||||||
ProviderService::list(state.inner(), app_type).map_err(|e| e.to_string())
|
ProviderService::list(state.inner(), app_type).map_err(|e| e.to_string())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,16 +13,34 @@ pub async fn get_skills(
|
|||||||
service: State<'_, SkillServiceState>,
|
service: State<'_, SkillServiceState>,
|
||||||
app_state: State<'_, AppState>,
|
app_state: State<'_, AppState>,
|
||||||
) -> Result<Vec<Skill>, String> {
|
) -> Result<Vec<Skill>, String> {
|
||||||
let repos = {
|
let repos = app_state.db.get_skill_repos().map_err(|e| e.to_string())?;
|
||||||
let config = app_state.config.read().map_err(|e| e.to_string())?;
|
|
||||||
config.skills.repos.clone()
|
|
||||||
};
|
|
||||||
|
|
||||||
service
|
let skills = service
|
||||||
.0
|
.0
|
||||||
.list_skills(repos)
|
.list_skills(repos)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| e.to_string())
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
// 自动同步本地已安装的 skills 到数据库
|
||||||
|
// 这样用户在首次运行时,已有的 skills 会被自动记录
|
||||||
|
let existing_states = app_state.db.get_skills().unwrap_or_default();
|
||||||
|
|
||||||
|
for skill in &skills {
|
||||||
|
if skill.installed && !existing_states.contains_key(&skill.directory) {
|
||||||
|
// 本地有该 skill,但数据库中没有记录,自动添加
|
||||||
|
if let Err(e) = app_state.db.update_skill_state(
|
||||||
|
&skill.directory,
|
||||||
|
&SkillState {
|
||||||
|
installed: true,
|
||||||
|
installed_at: Utc::now(),
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
log::warn!("同步本地 skill {} 状态到数据库失败: {}", skill.directory, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(skills)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
@@ -32,10 +50,7 @@ pub async fn install_skill(
|
|||||||
app_state: State<'_, AppState>,
|
app_state: State<'_, AppState>,
|
||||||
) -> Result<bool, String> {
|
) -> Result<bool, String> {
|
||||||
// 先在不持有写锁的情况下收集仓库与技能信息
|
// 先在不持有写锁的情况下收集仓库与技能信息
|
||||||
let repos = {
|
let repos = app_state.db.get_skill_repos().map_err(|e| e.to_string())?;
|
||||||
let config = app_state.config.read().map_err(|e| e.to_string())?;
|
|
||||||
config.skills.repos.clone()
|
|
||||||
};
|
|
||||||
|
|
||||||
let skills = service
|
let skills = service
|
||||||
.0
|
.0
|
||||||
@@ -85,19 +100,16 @@ pub async fn install_skill(
|
|||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
}
|
}
|
||||||
|
|
||||||
{
|
app_state
|
||||||
let mut config = app_state.config.write().map_err(|e| e.to_string())?;
|
.db
|
||||||
|
.update_skill_state(
|
||||||
config.skills.skills.insert(
|
&directory,
|
||||||
directory.clone(),
|
&SkillState {
|
||||||
SkillState {
|
|
||||||
installed: true,
|
installed: true,
|
||||||
installed_at: Utc::now(),
|
installed_at: Utc::now(),
|
||||||
},
|
},
|
||||||
);
|
)
|
||||||
}
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
app_state.save().map_err(|e| e.to_string())?;
|
|
||||||
|
|
||||||
Ok(true)
|
Ok(true)
|
||||||
}
|
}
|
||||||
@@ -113,13 +125,17 @@ pub fn uninstall_skill(
|
|||||||
.uninstall_skill(directory.clone())
|
.uninstall_skill(directory.clone())
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
{
|
// Remove from database by setting installed = false
|
||||||
let mut config = app_state.config.write().map_err(|e| e.to_string())?;
|
app_state
|
||||||
|
.db
|
||||||
config.skills.skills.remove(&directory);
|
.update_skill_state(
|
||||||
}
|
&directory,
|
||||||
|
&SkillState {
|
||||||
app_state.save().map_err(|e| e.to_string())?;
|
installed: false,
|
||||||
|
installed_at: Utc::now(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
Ok(true)
|
Ok(true)
|
||||||
}
|
}
|
||||||
@@ -129,28 +145,19 @@ pub fn get_skill_repos(
|
|||||||
_service: State<'_, SkillServiceState>,
|
_service: State<'_, SkillServiceState>,
|
||||||
app_state: State<'_, AppState>,
|
app_state: State<'_, AppState>,
|
||||||
) -> Result<Vec<SkillRepo>, String> {
|
) -> Result<Vec<SkillRepo>, String> {
|
||||||
let config = app_state.config.read().map_err(|e| e.to_string())?;
|
app_state.db.get_skill_repos().map_err(|e| e.to_string())
|
||||||
|
|
||||||
Ok(config.skills.repos.clone())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn add_skill_repo(
|
pub fn add_skill_repo(
|
||||||
repo: SkillRepo,
|
repo: SkillRepo,
|
||||||
service: State<'_, SkillServiceState>,
|
_service: State<'_, SkillServiceState>,
|
||||||
app_state: State<'_, AppState>,
|
app_state: State<'_, AppState>,
|
||||||
) -> Result<bool, String> {
|
) -> Result<bool, String> {
|
||||||
{
|
app_state
|
||||||
let mut config = app_state.config.write().map_err(|e| e.to_string())?;
|
.db
|
||||||
|
.save_skill_repo(&repo)
|
||||||
service
|
.map_err(|e| e.to_string())?;
|
||||||
.0
|
|
||||||
.add_repo(&mut config.skills, repo)
|
|
||||||
.map_err(|e| e.to_string())?;
|
|
||||||
}
|
|
||||||
|
|
||||||
app_state.save().map_err(|e| e.to_string())?;
|
|
||||||
|
|
||||||
Ok(true)
|
Ok(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -158,19 +165,12 @@ pub fn add_skill_repo(
|
|||||||
pub fn remove_skill_repo(
|
pub fn remove_skill_repo(
|
||||||
owner: String,
|
owner: String,
|
||||||
name: String,
|
name: String,
|
||||||
service: State<'_, SkillServiceState>,
|
_service: State<'_, SkillServiceState>,
|
||||||
app_state: State<'_, AppState>,
|
app_state: State<'_, AppState>,
|
||||||
) -> Result<bool, String> {
|
) -> Result<bool, String> {
|
||||||
{
|
app_state
|
||||||
let mut config = app_state.config.write().map_err(|e| e.to_string())?;
|
.db
|
||||||
|
.delete_skill_repo(&owner, &name)
|
||||||
service
|
.map_err(|e| e.to_string())?;
|
||||||
.0
|
|
||||||
.remove_repo(&mut config.skills, owner, name)
|
|
||||||
.map_err(|e| e.to_string())?;
|
|
||||||
}
|
|
||||||
|
|
||||||
app_state.save().map_err(|e| e.to_string())?;
|
|
||||||
|
|
||||||
Ok(true)
|
Ok(true)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -79,6 +79,7 @@ pub fn get_app_config_path() -> PathBuf {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// 清理供应商名称,确保文件名安全
|
/// 清理供应商名称,确保文件名安全
|
||||||
|
#[allow(dead_code)]
|
||||||
pub fn sanitize_provider_name(name: &str) -> String {
|
pub fn sanitize_provider_name(name: &str) -> String {
|
||||||
name.chars()
|
name.chars()
|
||||||
.map(|c| match c {
|
.map(|c| match c {
|
||||||
@@ -90,6 +91,7 @@ pub fn sanitize_provider_name(name: &str) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// 获取供应商配置文件路径
|
/// 获取供应商配置文件路径
|
||||||
|
#[allow(dead_code)]
|
||||||
pub fn get_provider_config_path(provider_id: &str, provider_name: Option<&str>) -> PathBuf {
|
pub fn get_provider_config_path(provider_id: &str, provider_name: Option<&str>) -> PathBuf {
|
||||||
let base_name = provider_name
|
let base_name = provider_name
|
||||||
.map(sanitize_provider_name)
|
.map(sanitize_provider_name)
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
+938
-113
File diff suppressed because it is too large
Load Diff
@@ -50,6 +50,8 @@ pub enum AppError {
|
|||||||
zh: String,
|
zh: String,
|
||||||
en: String,
|
en: String,
|
||||||
},
|
},
|
||||||
|
#[error("数据库错误: {0}")]
|
||||||
|
Database(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AppError {
|
impl AppError {
|
||||||
|
|||||||
@@ -96,7 +96,20 @@ pub fn set_mcp_servers_map(
|
|||||||
obj = server_obj;
|
obj = server_obj;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 移除 UI 辅助字段
|
// Gemini CLI 格式转换:
|
||||||
|
// - Gemini 不使用 "type" 字段(从字段名推断传输类型)
|
||||||
|
// - HTTP 使用 "httpUrl" 字段,SSE 使用 "url" 字段
|
||||||
|
let transport_type = obj.get("type").and_then(|v| v.as_str());
|
||||||
|
if transport_type == Some("http") {
|
||||||
|
// HTTP streaming: 将 "url" 重命名为 "httpUrl"
|
||||||
|
if let Some(url_value) = obj.remove("url") {
|
||||||
|
obj.insert("httpUrl".to_string(), url_value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// SSE 保持 "url" 字段不变
|
||||||
|
|
||||||
|
// 移除 UI 辅助字段和 type 字段(Gemini 不需要)
|
||||||
|
obj.remove("type");
|
||||||
obj.remove("enabled");
|
obj.remove("enabled");
|
||||||
obj.remove("source");
|
obj.remove("source");
|
||||||
obj.remove("id");
|
obj.remove("id");
|
||||||
|
|||||||
@@ -13,7 +13,9 @@ fn cell() -> &'static RwLock<Option<InitErrorPayload>> {
|
|||||||
INIT_ERROR.get_or_init(|| RwLock::new(None))
|
INIT_ERROR.get_or_init(|| RwLock::new(None))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
pub fn set_init_error(payload: InitErrorPayload) {
|
pub fn set_init_error(payload: InitErrorPayload) {
|
||||||
|
#[allow(clippy::unwrap_used)]
|
||||||
if let Ok(mut guard) = cell().write() {
|
if let Ok(mut guard) = cell().write() {
|
||||||
*guard = Some(payload);
|
*guard = Some(payload);
|
||||||
}
|
}
|
||||||
|
|||||||
+191
-57
@@ -6,6 +6,7 @@ mod claude_plugin;
|
|||||||
mod codex_config;
|
mod codex_config;
|
||||||
mod commands;
|
mod commands;
|
||||||
mod config;
|
mod config;
|
||||||
|
mod database;
|
||||||
mod deeplink;
|
mod deeplink;
|
||||||
mod error;
|
mod error;
|
||||||
mod gemini_config; // 新增
|
mod gemini_config; // 新增
|
||||||
@@ -25,6 +26,7 @@ pub use app_config::{AppType, McpApps, McpServer, MultiAppConfig};
|
|||||||
pub use codex_config::{get_codex_auth_path, get_codex_config_path, write_codex_live_atomic};
|
pub use codex_config::{get_codex_auth_path, get_codex_config_path, write_codex_live_atomic};
|
||||||
pub use commands::*;
|
pub use commands::*;
|
||||||
pub use config::{get_claude_mcp_path, get_claude_settings_path, read_json_file};
|
pub use config::{get_claude_mcp_path, get_claude_settings_path, read_json_file};
|
||||||
|
pub use database::Database;
|
||||||
pub use deeplink::{import_provider_from_deeplink, parse_deeplink_url, DeepLinkImportRequest};
|
pub use deeplink::{import_provider_from_deeplink, parse_deeplink_url, DeepLinkImportRequest};
|
||||||
pub use error::AppError;
|
pub use error::AppError;
|
||||||
pub use mcp::{
|
pub use mcp::{
|
||||||
@@ -206,8 +208,6 @@ fn create_tray_menu(
|
|||||||
let app_settings = crate::settings::get_settings();
|
let app_settings = crate::settings::get_settings();
|
||||||
let tray_texts = TrayTexts::from_language(app_settings.language.as_deref().unwrap_or("zh"));
|
let tray_texts = TrayTexts::from_language(app_settings.language.as_deref().unwrap_or("zh"));
|
||||||
|
|
||||||
let config = app_state.config.read().map_err(AppError::from)?;
|
|
||||||
|
|
||||||
let mut menu_builder = MenuBuilder::new(app);
|
let mut menu_builder = MenuBuilder::new(app);
|
||||||
|
|
||||||
// 顶部:打开主界面
|
// 顶部:打开主界面
|
||||||
@@ -218,13 +218,20 @@ fn create_tray_menu(
|
|||||||
|
|
||||||
// 直接添加所有供应商到主菜单(扁平化结构,更简单可靠)
|
// 直接添加所有供应商到主菜单(扁平化结构,更简单可靠)
|
||||||
for section in TRAY_SECTIONS.iter() {
|
for section in TRAY_SECTIONS.iter() {
|
||||||
menu_builder = append_provider_section(
|
let app_type_str = section.app_type.as_str();
|
||||||
app,
|
let providers = app_state.db.get_all_providers(app_type_str)?;
|
||||||
menu_builder,
|
let current_id = app_state
|
||||||
config.get_manager(§ion.app_type),
|
.db
|
||||||
section,
|
.get_current_provider(app_type_str)?
|
||||||
&tray_texts,
|
.unwrap_or_default();
|
||||||
)?;
|
|
||||||
|
let manager = crate::provider::ProviderManager {
|
||||||
|
providers,
|
||||||
|
current: current_id,
|
||||||
|
};
|
||||||
|
|
||||||
|
menu_builder =
|
||||||
|
append_provider_section(app, menu_builder, Some(&manager), section, &tray_texts)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 分隔符和退出菜单
|
// 分隔符和退出菜单
|
||||||
@@ -308,7 +315,7 @@ fn handle_deeplink_url(
|
|||||||
match crate::deeplink::parse_deeplink_url(url_str) {
|
match crate::deeplink::parse_deeplink_url(url_str) {
|
||||||
Ok(request) => {
|
Ok(request) => {
|
||||||
log::info!(
|
log::info!(
|
||||||
"✓ Successfully parsed deep link: resource={}, app={}, name={}",
|
"✓ Successfully parsed deep link: resource={}, app={:?}, name={:?}",
|
||||||
request.resource,
|
request.resource,
|
||||||
request.app,
|
request.app,
|
||||||
request.name
|
request.name
|
||||||
@@ -489,24 +496,31 @@ pub fn run() {
|
|||||||
use objc2::runtime::AnyObject;
|
use objc2::runtime::AnyObject;
|
||||||
use objc2_app_kit::NSColor;
|
use objc2_app_kit::NSColor;
|
||||||
|
|
||||||
let ns_window_ptr = window.ns_window().unwrap();
|
match window.ns_window() {
|
||||||
let ns_window: Retained<AnyObject> =
|
Ok(ns_window_ptr) => {
|
||||||
unsafe { Retained::retain(ns_window_ptr as *mut AnyObject).unwrap() };
|
if let Some(ns_window) =
|
||||||
|
unsafe { Retained::retain(ns_window_ptr as *mut AnyObject) }
|
||||||
|
{
|
||||||
|
// 使用与主界面 banner 相同的蓝色 #3498db
|
||||||
|
// #3498db = RGB(52, 152, 219)
|
||||||
|
let bg_color = unsafe {
|
||||||
|
NSColor::colorWithRed_green_blue_alpha(
|
||||||
|
52.0 / 255.0, // R: 52
|
||||||
|
152.0 / 255.0, // G: 152
|
||||||
|
219.0 / 255.0, // B: 219
|
||||||
|
1.0, // Alpha: 1.0
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
// 使用与主界面 banner 相同的蓝色 #3498db
|
unsafe {
|
||||||
// #3498db = RGB(52, 152, 219)
|
use objc2::msg_send;
|
||||||
let bg_color = unsafe {
|
let _: () = msg_send![&*ns_window, setBackgroundColor: &*bg_color];
|
||||||
NSColor::colorWithRed_green_blue_alpha(
|
}
|
||||||
52.0 / 255.0, // R: 52
|
} else {
|
||||||
152.0 / 255.0, // G: 152
|
log::warn!("Failed to retain NSWindow reference");
|
||||||
219.0 / 255.0, // B: 219
|
}
|
||||||
1.0, // Alpha: 1.0
|
}
|
||||||
)
|
Err(e) => log::warn!("Failed to get NSWindow pointer: {e}"),
|
||||||
};
|
|
||||||
|
|
||||||
unsafe {
|
|
||||||
use objc2::msg_send;
|
|
||||||
let _: () = msg_send![&*ns_window, setBackgroundColor: &*bg_color];
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -523,42 +537,157 @@ pub fn run() {
|
|||||||
// 预先刷新 Store 覆盖配置,确保 AppState 初始化时可读取到最新路径
|
// 预先刷新 Store 覆盖配置,确保 AppState 初始化时可读取到最新路径
|
||||||
app_store::refresh_app_config_dir_override(app.handle());
|
app_store::refresh_app_config_dir_override(app.handle());
|
||||||
|
|
||||||
// 初始化应用状态(仅创建一次,并在本函数末尾注入 manage)
|
// 初始化数据库
|
||||||
// 如果配置解析失败,则向前端发送错误事件并提前结束 setup(不落盘、不覆盖配置)。
|
let app_config_dir = crate::config::get_app_config_dir();
|
||||||
let app_state = match AppState::try_new() {
|
let db_path = app_config_dir.join("cc-switch.db");
|
||||||
Ok(state) => state,
|
let json_path = app_config_dir.join("config.json");
|
||||||
Err(err) => {
|
|
||||||
let path = crate::config::get_app_config_path();
|
// Check if migration is needed (DB doesn't exist but JSON does)
|
||||||
let payload_json = serde_json::json!({
|
let migration_needed = !db_path.exists() && json_path.exists();
|
||||||
"path": path.display().to_string(),
|
|
||||||
"error": err.to_string(),
|
let db = match crate::database::Database::init() {
|
||||||
});
|
Ok(db) => Arc::new(db),
|
||||||
// 事件通知(可能早于前端订阅,不保证送达)
|
Err(e) => {
|
||||||
if let Err(e) = app.emit("configLoadError", payload_json) {
|
log::error!("Failed to init database: {e}");
|
||||||
log::error!("发射配置加载错误事件失败: {e}");
|
// 这里的错误处理比较棘手,因为 setup 返回 Result<Box<dyn Error>>
|
||||||
}
|
// 我们暂时记录日志并让应用继续运行(可能会崩溃)或者返回错误
|
||||||
// 同时缓存错误,供前端启动阶段主动拉取
|
return Err(Box::new(e));
|
||||||
crate::init_status::set_init_error(crate::init_status::InitErrorPayload {
|
|
||||||
path: path.display().to_string(),
|
|
||||||
error: err.to_string(),
|
|
||||||
});
|
|
||||||
// 不再继续构建托盘/命令依赖的状态,交由前端提示后退出。
|
|
||||||
return Ok(());
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if migration_needed {
|
||||||
|
log::info!("Starting migration from config.json to SQLite...");
|
||||||
|
match crate::app_config::MultiAppConfig::load() {
|
||||||
|
Ok(config) => {
|
||||||
|
if let Err(e) = db.migrate_from_json(&config) {
|
||||||
|
log::error!("Migration failed: {e}");
|
||||||
|
} else {
|
||||||
|
log::info!("Migration successful");
|
||||||
|
// Optional: Rename config.json
|
||||||
|
// let _ = std::fs::rename(&json_path, json_path.with_extension("json.bak"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => log::error!("Failed to load config.json for migration: {e}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
crate::settings::bind_db(db.clone());
|
||||||
|
let app_state = AppState::new(db);
|
||||||
|
|
||||||
|
// 检查是否需要首次导入(数据库为空)
|
||||||
|
let need_first_import = app_state
|
||||||
|
.db
|
||||||
|
.is_empty_for_first_import()
|
||||||
|
.unwrap_or_else(|e| {
|
||||||
|
log::warn!("Failed to check if database is empty: {e}");
|
||||||
|
false
|
||||||
|
});
|
||||||
|
|
||||||
|
if need_first_import {
|
||||||
|
// 数据库为空,尝试从用户现有的配置文件导入数据并初始化默认配置
|
||||||
|
log::info!(
|
||||||
|
"Empty database detected, importing existing configurations and initializing defaults..."
|
||||||
|
);
|
||||||
|
|
||||||
|
// 1. 初始化默认 Skills 仓库(3个)
|
||||||
|
match app_state.db.init_default_skill_repos() {
|
||||||
|
Ok(count) if count > 0 => {
|
||||||
|
log::info!("✓ Initialized {count} default skill repositories");
|
||||||
|
}
|
||||||
|
Ok(_) => log::debug!("No default skill repositories to initialize"),
|
||||||
|
Err(e) => log::warn!("✗ Failed to initialize default skill repos: {e}"),
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 导入供应商配置(从 live 配置文件)
|
||||||
|
for app in [
|
||||||
|
crate::app_config::AppType::Claude,
|
||||||
|
crate::app_config::AppType::Codex,
|
||||||
|
crate::app_config::AppType::Gemini,
|
||||||
|
] {
|
||||||
|
match crate::services::provider::ProviderService::import_default_config(
|
||||||
|
&app_state,
|
||||||
|
app.clone(),
|
||||||
|
) {
|
||||||
|
Ok(_) => {
|
||||||
|
log::info!("✓ Imported default provider for {}", app.as_str());
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
log::debug!(
|
||||||
|
"○ No default provider to import for {}: {}",
|
||||||
|
app.as_str(),
|
||||||
|
e
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 导入 MCP 服务器配置
|
||||||
|
match crate::services::mcp::McpService::import_from_claude(&app_state) {
|
||||||
|
Ok(count) if count > 0 => {
|
||||||
|
log::info!("✓ Imported {count} MCP server(s) from Claude");
|
||||||
|
}
|
||||||
|
Ok(_) => log::debug!("○ No Claude MCP servers found to import"),
|
||||||
|
Err(e) => log::warn!("✗ Failed to import Claude MCP: {e}"),
|
||||||
|
}
|
||||||
|
|
||||||
|
match crate::services::mcp::McpService::import_from_codex(&app_state) {
|
||||||
|
Ok(count) if count > 0 => {
|
||||||
|
log::info!("✓ Imported {count} MCP server(s) from Codex");
|
||||||
|
}
|
||||||
|
Ok(_) => log::debug!("○ No Codex MCP servers found to import"),
|
||||||
|
Err(e) => log::warn!("✗ Failed to import Codex MCP: {e}"),
|
||||||
|
}
|
||||||
|
|
||||||
|
match crate::services::mcp::McpService::import_from_gemini(&app_state) {
|
||||||
|
Ok(count) if count > 0 => {
|
||||||
|
log::info!("✓ Imported {count} MCP server(s) from Gemini");
|
||||||
|
}
|
||||||
|
Ok(_) => log::debug!("○ No Gemini MCP servers found to import"),
|
||||||
|
Err(e) => log::warn!("✗ Failed to import Gemini MCP: {e}"),
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 导入提示词文件
|
||||||
|
match crate::services::prompt::PromptService::import_from_file_on_first_launch(
|
||||||
|
&app_state,
|
||||||
|
crate::app_config::AppType::Claude,
|
||||||
|
) {
|
||||||
|
Ok(count) if count > 0 => {
|
||||||
|
log::info!("✓ Imported {count} prompt(s) from Claude");
|
||||||
|
}
|
||||||
|
Ok(_) => log::debug!("○ No Claude prompt file found to import"),
|
||||||
|
Err(e) => log::warn!("✗ Failed to import Claude prompt: {e}"),
|
||||||
|
}
|
||||||
|
|
||||||
|
match crate::services::prompt::PromptService::import_from_file_on_first_launch(
|
||||||
|
&app_state,
|
||||||
|
crate::app_config::AppType::Codex,
|
||||||
|
) {
|
||||||
|
Ok(count) if count > 0 => {
|
||||||
|
log::info!("✓ Imported {count} prompt(s) from Codex");
|
||||||
|
}
|
||||||
|
Ok(_) => log::debug!("○ No Codex prompt file found to import"),
|
||||||
|
Err(e) => log::warn!("✗ Failed to import Codex prompt: {e}"),
|
||||||
|
}
|
||||||
|
|
||||||
|
match crate::services::prompt::PromptService::import_from_file_on_first_launch(
|
||||||
|
&app_state,
|
||||||
|
crate::app_config::AppType::Gemini,
|
||||||
|
) {
|
||||||
|
Ok(count) if count > 0 => {
|
||||||
|
log::info!("✓ Imported {count} prompt(s) from Gemini");
|
||||||
|
}
|
||||||
|
Ok(_) => log::debug!("○ No Gemini prompt file found to import"),
|
||||||
|
Err(e) => log::warn!("✗ Failed to import Gemini prompt: {e}"),
|
||||||
|
}
|
||||||
|
|
||||||
|
log::info!("First-time import completed");
|
||||||
|
}
|
||||||
|
|
||||||
// 迁移旧的 app_config_dir 配置到 Store
|
// 迁移旧的 app_config_dir 配置到 Store
|
||||||
if let Err(e) = app_store::migrate_app_config_dir_from_settings(app.handle()) {
|
if let Err(e) = app_store::migrate_app_config_dir_from_settings(app.handle()) {
|
||||||
log::warn!("迁移 app_config_dir 失败: {e}");
|
log::warn!("迁移 app_config_dir 失败: {e}");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 确保配置结构就绪(已移除旧版本的副本迁移逻辑)
|
|
||||||
{
|
|
||||||
let mut config_guard = app_state.config.write().unwrap();
|
|
||||||
config_guard.ensure_app(&app_config::AppType::Claude);
|
|
||||||
config_guard.ensure_app(&app_config::AppType::Codex);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 启动阶段不再无条件保存,避免意外覆盖用户配置。
|
// 启动阶段不再无条件保存,避免意外覆盖用户配置。
|
||||||
|
|
||||||
// 注册 deep-link URL 处理器(使用正确的 DeepLinkExt API)
|
// 注册 deep-link URL 处理器(使用正确的 DeepLinkExt API)
|
||||||
@@ -611,7 +740,11 @@ pub fn run() {
|
|||||||
.show_menu_on_left_click(true);
|
.show_menu_on_left_click(true);
|
||||||
|
|
||||||
// 统一使用应用默认图标;待托盘模板图标就绪后再启用
|
// 统一使用应用默认图标;待托盘模板图标就绪后再启用
|
||||||
tray_builder = tray_builder.icon(app.default_window_icon().unwrap().clone());
|
if let Some(icon) = app.default_window_icon() {
|
||||||
|
tray_builder = tray_builder.icon(icon.clone());
|
||||||
|
} else {
|
||||||
|
log::warn!("Failed to get default window icon for tray");
|
||||||
|
}
|
||||||
|
|
||||||
let _tray = tray_builder.build(app)?;
|
let _tray = tray_builder.build(app)?;
|
||||||
// 将同一个实例注入到全局状态,避免重复创建导致的不一致
|
// 将同一个实例注入到全局状态,避免重复创建导致的不一致
|
||||||
@@ -708,6 +841,7 @@ pub fn run() {
|
|||||||
commands::parse_deeplink,
|
commands::parse_deeplink,
|
||||||
commands::merge_deeplink_config,
|
commands::merge_deeplink_config,
|
||||||
commands::import_from_deeplink,
|
commands::import_from_deeplink,
|
||||||
|
commands::import_from_deeplink_unified,
|
||||||
update_tray_menu,
|
update_tray_menu,
|
||||||
// Environment variable management
|
// Environment variable management
|
||||||
commands::check_env_conflicts,
|
commands::check_env_conflicts,
|
||||||
@@ -757,7 +891,7 @@ pub fn run() {
|
|||||||
match crate::deeplink::parse_deeplink_url(&url_str) {
|
match crate::deeplink::parse_deeplink_url(&url_str) {
|
||||||
Ok(request) => {
|
Ok(request) => {
|
||||||
log::info!(
|
log::info!(
|
||||||
"Successfully parsed deep link from RunEvent::Opened: resource={}, app={}",
|
"Successfully parsed deep link from RunEvent::Opened: resource={}, app={:?}",
|
||||||
request.resource,
|
request.resource,
|
||||||
request.app
|
request.app
|
||||||
);
|
);
|
||||||
|
|||||||
+29
-18
@@ -348,10 +348,7 @@ pub fn import_from_claude(config: &mut MultiAppConfig) -> Result<usize, AppError
|
|||||||
};
|
};
|
||||||
|
|
||||||
// 确保新结构存在
|
// 确保新结构存在
|
||||||
if config.mcp.servers.is_none() {
|
let servers = config.mcp.servers.get_or_insert_with(HashMap::new);
|
||||||
config.mcp.servers = Some(HashMap::new());
|
|
||||||
}
|
|
||||||
let servers = config.mcp.servers.as_mut().unwrap();
|
|
||||||
|
|
||||||
let mut changed = 0;
|
let mut changed = 0;
|
||||||
let mut errors = Vec::new();
|
let mut errors = Vec::new();
|
||||||
@@ -421,10 +418,7 @@ pub fn import_from_codex(config: &mut MultiAppConfig) -> Result<usize, AppError>
|
|||||||
.map_err(|e| AppError::McpValidation(format!("解析 ~/.codex/config.toml 失败: {e}")))?;
|
.map_err(|e| AppError::McpValidation(format!("解析 ~/.codex/config.toml 失败: {e}")))?;
|
||||||
|
|
||||||
// 确保新结构存在
|
// 确保新结构存在
|
||||||
if config.mcp.servers.is_none() {
|
let servers = config.mcp.servers.get_or_insert_with(HashMap::new);
|
||||||
config.mcp.servers = Some(HashMap::new());
|
|
||||||
}
|
|
||||||
let servers = config.mcp.servers.as_mut().unwrap();
|
|
||||||
|
|
||||||
let mut changed_total = 0usize;
|
let mut changed_total = 0usize;
|
||||||
|
|
||||||
@@ -449,7 +443,7 @@ pub fn import_from_codex(config: &mut MultiAppConfig) -> Result<usize, AppError>
|
|||||||
// 核心字段(需要手动处理的字段)
|
// 核心字段(需要手动处理的字段)
|
||||||
let core_fields = match typ {
|
let core_fields = match typ {
|
||||||
"stdio" => vec!["type", "command", "args", "env", "cwd"],
|
"stdio" => vec!["type", "command", "args", "env", "cwd"],
|
||||||
"http" | "sse" => vec!["type", "url", "headers"],
|
"http" | "sse" => vec!["type", "url", "http_headers"],
|
||||||
_ => vec!["type"],
|
_ => vec!["type"],
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -490,7 +484,13 @@ pub fn import_from_codex(config: &mut MultiAppConfig) -> Result<usize, AppError>
|
|||||||
if let Some(url) = entry_tbl.get("url").and_then(|v| v.as_str()) {
|
if let Some(url) = entry_tbl.get("url").and_then(|v| v.as_str()) {
|
||||||
spec.insert("url".into(), json!(url));
|
spec.insert("url".into(), json!(url));
|
||||||
}
|
}
|
||||||
if let Some(headers_tbl) = entry_tbl.get("headers").and_then(|v| v.as_table()) {
|
// Read from http_headers (correct Codex format) or headers (legacy) with priority to http_headers
|
||||||
|
let headers_tbl = entry_tbl
|
||||||
|
.get("http_headers")
|
||||||
|
.and_then(|v| v.as_table())
|
||||||
|
.or_else(|| entry_tbl.get("headers").and_then(|v| v.as_table()));
|
||||||
|
|
||||||
|
if let Some(headers_tbl) = headers_tbl {
|
||||||
let mut headers_json = serde_json::Map::new();
|
let mut headers_json = serde_json::Map::new();
|
||||||
for (k, v) in headers_tbl.iter() {
|
for (k, v) in headers_tbl.iter() {
|
||||||
if let Some(sv) = v.as_str() {
|
if let Some(sv) = v.as_str() {
|
||||||
@@ -718,10 +718,7 @@ pub fn import_from_gemini(config: &mut MultiAppConfig) -> Result<usize, AppError
|
|||||||
};
|
};
|
||||||
|
|
||||||
// 确保新结构存在
|
// 确保新结构存在
|
||||||
if config.mcp.servers.is_none() {
|
let servers = config.mcp.servers.get_or_insert_with(HashMap::new);
|
||||||
config.mcp.servers = Some(HashMap::new());
|
|
||||||
}
|
|
||||||
let servers = config.mcp.servers.as_mut().unwrap();
|
|
||||||
|
|
||||||
let mut changed = 0;
|
let mut changed = 0;
|
||||||
let mut errors = Vec::new();
|
let mut errors = Vec::new();
|
||||||
@@ -846,8 +843,22 @@ fn json_value_to_toml_item(value: &Value, field_name: &str) -> Option<toml_edit:
|
|||||||
for item in arr {
|
for item in arr {
|
||||||
match item {
|
match item {
|
||||||
Value::String(s) => toml_arr.push(s.as_str()),
|
Value::String(s) => toml_arr.push(s.as_str()),
|
||||||
Value::Number(n) if n.is_i64() => toml_arr.push(n.as_i64().unwrap()),
|
Value::Number(n) if n.is_i64() => {
|
||||||
Value::Number(n) if n.is_f64() => toml_arr.push(n.as_f64().unwrap()),
|
if let Some(i) = n.as_i64() {
|
||||||
|
toml_arr.push(i);
|
||||||
|
} else {
|
||||||
|
all_same_type = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Value::Number(n) if n.is_f64() => {
|
||||||
|
if let Some(f) = n.as_f64() {
|
||||||
|
toml_arr.push(f);
|
||||||
|
} else {
|
||||||
|
all_same_type = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
Value::Bool(b) => toml_arr.push(*b),
|
Value::Bool(b) => toml_arr.push(*b),
|
||||||
_ => {
|
_ => {
|
||||||
all_same_type = false;
|
all_same_type = false;
|
||||||
@@ -910,7 +921,7 @@ fn json_server_to_toml_table(spec: &Value) -> Result<toml_edit::Table, AppError>
|
|||||||
// 定义核心字段(已在下方处理,跳过通用转换)
|
// 定义核心字段(已在下方处理,跳过通用转换)
|
||||||
let core_fields = match typ {
|
let core_fields = match typ {
|
||||||
"stdio" => vec!["type", "command", "args", "env", "cwd"],
|
"stdio" => vec!["type", "command", "args", "env", "cwd"],
|
||||||
"http" | "sse" => vec!["type", "url", "headers"],
|
"http" | "sse" => vec!["type", "url", "http_headers"],
|
||||||
_ => vec!["type"],
|
_ => vec!["type"],
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -988,7 +999,7 @@ fn json_server_to_toml_table(spec: &Value) -> Result<toml_edit::Table, AppError>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !h_tbl.is_empty() {
|
if !h_tbl.is_empty() {
|
||||||
t["headers"] = Item::Table(h_tbl);
|
t["http_headers"] = Item::Table(h_tbl);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
use indexmap::IndexMap;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
@@ -64,7 +65,7 @@ impl Provider {
|
|||||||
/// 供应商管理器
|
/// 供应商管理器
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||||
pub struct ProviderManager {
|
pub struct ProviderManager {
|
||||||
pub providers: HashMap<String, Provider>,
|
pub providers: IndexMap<String, Provider>,
|
||||||
pub current: String,
|
pub current: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,7 +155,7 @@ pub struct ProviderMeta {
|
|||||||
|
|
||||||
impl ProviderManager {
|
impl ProviderManager {
|
||||||
/// 获取所有供应商
|
/// 获取所有供应商
|
||||||
pub fn get_all_providers(&self) -> &HashMap<String, Provider> {
|
pub fn get_all_providers(&self) -> &IndexMap<String, Provider> {
|
||||||
&self.providers
|
&self.providers
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -109,7 +109,17 @@ impl ConfigService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// 将外部配置文件内容加载并写入应用状态。
|
/// 将外部配置文件内容加载并写入应用状态。
|
||||||
pub fn import_config_from_path(file_path: &Path, state: &AppState) -> Result<String, AppError> {
|
/// TODO: 需要重构以使用数据库而不是 JSON 配置
|
||||||
|
pub fn import_config_from_path(
|
||||||
|
_file_path: &Path,
|
||||||
|
_state: &AppState,
|
||||||
|
) -> Result<String, AppError> {
|
||||||
|
// TODO: 实现基于数据库的导入逻辑
|
||||||
|
Err(AppError::Message(
|
||||||
|
"配置导入功能正在重构中,暂时不可用".to_string(),
|
||||||
|
))
|
||||||
|
|
||||||
|
/* 旧的实现,需要重构:
|
||||||
let (new_config, backup_id) = Self::load_config_for_import(file_path)?;
|
let (new_config, backup_id) = Self::load_config_for_import(file_path)?;
|
||||||
|
|
||||||
{
|
{
|
||||||
@@ -118,6 +128,7 @@ impl ConfigService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Ok(backup_id)
|
Ok(backup_id)
|
||||||
|
*/
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 同步当前供应商到对应的 live 配置。
|
/// 同步当前供应商到对应的 live 配置。
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
|
use indexmap::IndexMap;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use crate::app_config::{AppType, McpServer, MultiAppConfig};
|
use crate::app_config::{AppType, McpServer};
|
||||||
use crate::error::AppError;
|
use crate::error::AppError;
|
||||||
use crate::mcp;
|
use crate::mcp;
|
||||||
use crate::store::AppState;
|
use crate::store::AppState;
|
||||||
@@ -10,40 +11,13 @@ pub struct McpService;
|
|||||||
|
|
||||||
impl McpService {
|
impl McpService {
|
||||||
/// 获取所有 MCP 服务器(统一结构)
|
/// 获取所有 MCP 服务器(统一结构)
|
||||||
pub fn get_all_servers(state: &AppState) -> Result<HashMap<String, McpServer>, AppError> {
|
pub fn get_all_servers(state: &AppState) -> Result<IndexMap<String, McpServer>, AppError> {
|
||||||
let cfg = state.config.read()?;
|
state.db.get_all_mcp_servers()
|
||||||
|
|
||||||
// 如果是新结构,直接返回
|
|
||||||
if let Some(servers) = &cfg.mcp.servers {
|
|
||||||
return Ok(servers.clone());
|
|
||||||
}
|
|
||||||
|
|
||||||
// 理论上不应该走到这里,因为 load 时会自动迁移
|
|
||||||
Err(AppError::localized(
|
|
||||||
"mcp.old_structure",
|
|
||||||
"检测到旧版 MCP 结构,请重启应用完成迁移",
|
|
||||||
"Old MCP structure detected, please restart app to complete migration",
|
|
||||||
))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 添加或更新 MCP 服务器
|
/// 添加或更新 MCP 服务器
|
||||||
pub fn upsert_server(state: &AppState, server: McpServer) -> Result<(), AppError> {
|
pub fn upsert_server(state: &AppState, server: McpServer) -> Result<(), AppError> {
|
||||||
{
|
state.db.save_mcp_server(&server)?;
|
||||||
let mut cfg = state.config.write()?;
|
|
||||||
|
|
||||||
// 确保 servers 字段存在
|
|
||||||
if cfg.mcp.servers.is_none() {
|
|
||||||
cfg.mcp.servers = Some(HashMap::new());
|
|
||||||
}
|
|
||||||
|
|
||||||
let servers = cfg.mcp.servers.as_mut().unwrap();
|
|
||||||
let id = server.id.clone();
|
|
||||||
|
|
||||||
// 插入或更新
|
|
||||||
servers.insert(id, server.clone());
|
|
||||||
}
|
|
||||||
|
|
||||||
state.save()?;
|
|
||||||
|
|
||||||
// 同步到各个启用的应用
|
// 同步到各个启用的应用
|
||||||
Self::sync_server_to_apps(state, &server)?;
|
Self::sync_server_to_apps(state, &server)?;
|
||||||
@@ -53,18 +27,10 @@ impl McpService {
|
|||||||
|
|
||||||
/// 删除 MCP 服务器
|
/// 删除 MCP 服务器
|
||||||
pub fn delete_server(state: &AppState, id: &str) -> Result<bool, AppError> {
|
pub fn delete_server(state: &AppState, id: &str) -> Result<bool, AppError> {
|
||||||
let server = {
|
let server = state.db.get_all_mcp_servers()?.shift_remove(id);
|
||||||
let mut cfg = state.config.write()?;
|
|
||||||
|
|
||||||
if let Some(servers) = &mut cfg.mcp.servers {
|
|
||||||
servers.remove(id)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if let Some(server) = server {
|
if let Some(server) = server {
|
||||||
state.save()?;
|
state.db.delete_mcp_server(id)?;
|
||||||
|
|
||||||
// 从所有应用的 live 配置中移除
|
// 从所有应用的 live 配置中移除
|
||||||
Self::remove_server_from_all_apps(state, id, &server)?;
|
Self::remove_server_from_all_apps(state, id, &server)?;
|
||||||
@@ -81,27 +47,15 @@ impl McpService {
|
|||||||
app: AppType,
|
app: AppType,
|
||||||
enabled: bool,
|
enabled: bool,
|
||||||
) -> Result<(), AppError> {
|
) -> Result<(), AppError> {
|
||||||
let server = {
|
let mut servers = state.db.get_all_mcp_servers()?;
|
||||||
let mut cfg = state.config.write()?;
|
|
||||||
|
|
||||||
if let Some(servers) = &mut cfg.mcp.servers {
|
if let Some(server) = servers.get_mut(server_id) {
|
||||||
if let Some(server) = servers.get_mut(server_id) {
|
server.apps.set_enabled_for(&app, enabled);
|
||||||
server.apps.set_enabled_for(&app, enabled);
|
state.db.save_mcp_server(server)?;
|
||||||
Some(server.clone())
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if let Some(server) = server {
|
|
||||||
state.save()?;
|
|
||||||
|
|
||||||
// 同步到对应应用
|
// 同步到对应应用
|
||||||
if enabled {
|
if enabled {
|
||||||
Self::sync_server_to_app(state, &server, &app)?;
|
Self::sync_server_to_app(state, server, &app)?;
|
||||||
} else {
|
} else {
|
||||||
Self::remove_server_from_app(state, server_id, &app)?;
|
Self::remove_server_from_app(state, server_id, &app)?;
|
||||||
}
|
}
|
||||||
@@ -111,11 +65,9 @@ impl McpService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// 将 MCP 服务器同步到所有启用的应用
|
/// 将 MCP 服务器同步到所有启用的应用
|
||||||
fn sync_server_to_apps(state: &AppState, server: &McpServer) -> Result<(), AppError> {
|
fn sync_server_to_apps(_state: &AppState, server: &McpServer) -> Result<(), AppError> {
|
||||||
let cfg = state.config.read()?;
|
|
||||||
|
|
||||||
for app in server.apps.enabled_apps() {
|
for app in server.apps.enabled_apps() {
|
||||||
Self::sync_server_to_app_internal(&cfg, server, &app)?;
|
Self::sync_server_to_app_no_config(server, &app)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -123,28 +75,24 @@ impl McpService {
|
|||||||
|
|
||||||
/// 将 MCP 服务器同步到指定应用
|
/// 将 MCP 服务器同步到指定应用
|
||||||
fn sync_server_to_app(
|
fn sync_server_to_app(
|
||||||
state: &AppState,
|
_state: &AppState,
|
||||||
server: &McpServer,
|
server: &McpServer,
|
||||||
app: &AppType,
|
app: &AppType,
|
||||||
) -> Result<(), AppError> {
|
) -> Result<(), AppError> {
|
||||||
let cfg = state.config.read()?;
|
Self::sync_server_to_app_no_config(server, app)
|
||||||
Self::sync_server_to_app_internal(&cfg, server, app)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn sync_server_to_app_internal(
|
fn sync_server_to_app_no_config(server: &McpServer, app: &AppType) -> Result<(), AppError> {
|
||||||
cfg: &MultiAppConfig,
|
|
||||||
server: &McpServer,
|
|
||||||
app: &AppType,
|
|
||||||
) -> Result<(), AppError> {
|
|
||||||
match app {
|
match app {
|
||||||
AppType::Claude => {
|
AppType::Claude => {
|
||||||
mcp::sync_single_server_to_claude(cfg, &server.id, &server.server)?;
|
mcp::sync_single_server_to_claude(&Default::default(), &server.id, &server.server)?;
|
||||||
}
|
}
|
||||||
AppType::Codex => {
|
AppType::Codex => {
|
||||||
mcp::sync_single_server_to_codex(cfg, &server.id, &server.server)?;
|
// Codex uses TOML format, must use the correct function
|
||||||
|
mcp::sync_single_server_to_codex(&Default::default(), &server.id, &server.server)?;
|
||||||
}
|
}
|
||||||
AppType::Gemini => {
|
AppType::Gemini => {
|
||||||
mcp::sync_single_server_to_gemini(cfg, &server.id, &server.server)?;
|
mcp::sync_single_server_to_gemini(&Default::default(), &server.id, &server.server)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -233,28 +181,67 @@ impl McpService {
|
|||||||
|
|
||||||
/// 从 Claude 导入 MCP(v3.7.0 已更新为统一结构)
|
/// 从 Claude 导入 MCP(v3.7.0 已更新为统一结构)
|
||||||
pub fn import_from_claude(state: &AppState) -> Result<usize, AppError> {
|
pub fn import_from_claude(state: &AppState) -> Result<usize, AppError> {
|
||||||
let mut cfg = state.config.write()?;
|
// 创建临时 MultiAppConfig 用于导入
|
||||||
let count = mcp::import_from_claude(&mut cfg)?;
|
let mut temp_config = crate::app_config::MultiAppConfig::default();
|
||||||
drop(cfg);
|
|
||||||
state.save()?;
|
// 调用原有的导入逻辑(从 mcp.rs)
|
||||||
|
let count = crate::mcp::import_from_claude(&mut temp_config)?;
|
||||||
|
|
||||||
|
// 如果有导入的服务器,保存到数据库
|
||||||
|
if count > 0 {
|
||||||
|
if let Some(servers) = &temp_config.mcp.servers {
|
||||||
|
for server in servers.values() {
|
||||||
|
state.db.save_mcp_server(server)?;
|
||||||
|
// 同步到 Claude live 配置
|
||||||
|
Self::sync_server_to_apps(state, server)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Ok(count)
|
Ok(count)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 从 Codex 导入 MCP(v3.7.0 已更新为统一结构)
|
/// 从 Codex 导入 MCP(v3.7.0 已更新为统一结构)
|
||||||
pub fn import_from_codex(state: &AppState) -> Result<usize, AppError> {
|
pub fn import_from_codex(state: &AppState) -> Result<usize, AppError> {
|
||||||
let mut cfg = state.config.write()?;
|
// 创建临时 MultiAppConfig 用于导入
|
||||||
let count = mcp::import_from_codex(&mut cfg)?;
|
let mut temp_config = crate::app_config::MultiAppConfig::default();
|
||||||
drop(cfg);
|
|
||||||
state.save()?;
|
// 调用原有的导入逻辑(从 mcp.rs)
|
||||||
|
let count = crate::mcp::import_from_codex(&mut temp_config)?;
|
||||||
|
|
||||||
|
// 如果有导入的服务器,保存到数据库
|
||||||
|
if count > 0 {
|
||||||
|
if let Some(servers) = &temp_config.mcp.servers {
|
||||||
|
for server in servers.values() {
|
||||||
|
state.db.save_mcp_server(server)?;
|
||||||
|
// 同步到 Codex live 配置
|
||||||
|
Self::sync_server_to_apps(state, server)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Ok(count)
|
Ok(count)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 从 Gemini 导入 MCP(v3.7.0 已更新为统一结构)
|
/// 从 Gemini 导入 MCP(v3.7.0 已更新为统一结构)
|
||||||
pub fn import_from_gemini(state: &AppState) -> Result<usize, AppError> {
|
pub fn import_from_gemini(state: &AppState) -> Result<usize, AppError> {
|
||||||
let mut cfg = state.config.write()?;
|
// 创建临时 MultiAppConfig 用于导入
|
||||||
let count = mcp::import_from_gemini(&mut cfg)?;
|
let mut temp_config = crate::app_config::MultiAppConfig::default();
|
||||||
drop(cfg);
|
|
||||||
state.save()?;
|
// 调用原有的导入逻辑(从 mcp.rs)
|
||||||
|
let count = crate::mcp::import_from_gemini(&mut temp_config)?;
|
||||||
|
|
||||||
|
// 如果有导入的服务器,保存到数据库
|
||||||
|
if count > 0 {
|
||||||
|
if let Some(servers) = &temp_config.mcp.servers {
|
||||||
|
for server in servers.values() {
|
||||||
|
state.db.save_mcp_server(server)?;
|
||||||
|
// 同步到 Gemini live 配置
|
||||||
|
Self::sync_server_to_apps(state, server)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Ok(count)
|
Ok(count)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use std::collections::HashMap;
|
use indexmap::IndexMap;
|
||||||
|
|
||||||
use crate::app_config::AppType;
|
use crate::app_config::AppType;
|
||||||
use crate::config::write_text_file;
|
use crate::config::write_text_file;
|
||||||
@@ -7,40 +7,34 @@ use crate::prompt::Prompt;
|
|||||||
use crate::prompt_files::prompt_file_path;
|
use crate::prompt_files::prompt_file_path;
|
||||||
use crate::store::AppState;
|
use crate::store::AppState;
|
||||||
|
|
||||||
|
/// 安全地获取当前 Unix 时间戳
|
||||||
|
fn get_unix_timestamp() -> Result<i64, AppError> {
|
||||||
|
std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.map(|d| d.as_secs() as i64)
|
||||||
|
.map_err(|e| AppError::Message(format!("Failed to get system time: {e}")))
|
||||||
|
}
|
||||||
|
|
||||||
pub struct PromptService;
|
pub struct PromptService;
|
||||||
|
|
||||||
impl PromptService {
|
impl PromptService {
|
||||||
pub fn get_prompts(
|
pub fn get_prompts(
|
||||||
state: &AppState,
|
state: &AppState,
|
||||||
app: AppType,
|
app: AppType,
|
||||||
) -> Result<HashMap<String, Prompt>, AppError> {
|
) -> Result<IndexMap<String, Prompt>, AppError> {
|
||||||
let cfg = state.config.read()?;
|
state.db.get_prompts(app.as_str())
|
||||||
let prompts = match app {
|
|
||||||
AppType::Claude => &cfg.prompts.claude.prompts,
|
|
||||||
AppType::Codex => &cfg.prompts.codex.prompts,
|
|
||||||
AppType::Gemini => &cfg.prompts.gemini.prompts,
|
|
||||||
};
|
|
||||||
Ok(prompts.clone())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn upsert_prompt(
|
pub fn upsert_prompt(
|
||||||
state: &AppState,
|
state: &AppState,
|
||||||
app: AppType,
|
app: AppType,
|
||||||
id: &str,
|
_id: &str,
|
||||||
prompt: Prompt,
|
prompt: Prompt,
|
||||||
) -> Result<(), AppError> {
|
) -> Result<(), AppError> {
|
||||||
// 检查是否为已启用的提示词
|
// 检查是否为已启用的提示词
|
||||||
let is_enabled = prompt.enabled;
|
let is_enabled = prompt.enabled;
|
||||||
|
|
||||||
let mut cfg = state.config.write()?;
|
state.db.save_prompt(app.as_str(), &prompt)?;
|
||||||
let prompts = match app {
|
|
||||||
AppType::Claude => &mut cfg.prompts.claude.prompts,
|
|
||||||
AppType::Codex => &mut cfg.prompts.codex.prompts,
|
|
||||||
AppType::Gemini => &mut cfg.prompts.gemini.prompts,
|
|
||||||
};
|
|
||||||
prompts.insert(id.to_string(), prompt.clone());
|
|
||||||
drop(cfg);
|
|
||||||
state.save()?;
|
|
||||||
|
|
||||||
// 如果是已启用的提示词,同步更新到对应的文件
|
// 如果是已启用的提示词,同步更新到对应的文件
|
||||||
if is_enabled {
|
if is_enabled {
|
||||||
@@ -52,12 +46,7 @@ impl PromptService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn delete_prompt(state: &AppState, app: AppType, id: &str) -> Result<(), AppError> {
|
pub fn delete_prompt(state: &AppState, app: AppType, id: &str) -> Result<(), AppError> {
|
||||||
let mut cfg = state.config.write()?;
|
let prompts = state.db.get_prompts(app.as_str())?;
|
||||||
let prompts = match app {
|
|
||||||
AppType::Claude => &mut cfg.prompts.claude.prompts,
|
|
||||||
AppType::Codex => &mut cfg.prompts.codex.prompts,
|
|
||||||
AppType::Gemini => &mut cfg.prompts.gemini.prompts,
|
|
||||||
};
|
|
||||||
|
|
||||||
if let Some(prompt) = prompts.get(id) {
|
if let Some(prompt) = prompts.get(id) {
|
||||||
if prompt.enabled {
|
if prompt.enabled {
|
||||||
@@ -65,9 +54,7 @@ impl PromptService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
prompts.remove(id);
|
state.db.delete_prompt(app.as_str(), id)?;
|
||||||
drop(cfg);
|
|
||||||
state.save()?;
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -77,12 +64,7 @@ impl PromptService {
|
|||||||
if target_path.exists() {
|
if target_path.exists() {
|
||||||
if let Ok(live_content) = std::fs::read_to_string(&target_path) {
|
if let Ok(live_content) = std::fs::read_to_string(&target_path) {
|
||||||
if !live_content.trim().is_empty() {
|
if !live_content.trim().is_empty() {
|
||||||
let mut cfg = state.config.write()?;
|
let mut prompts = state.db.get_prompts(app.as_str())?;
|
||||||
let prompts = match app {
|
|
||||||
AppType::Claude => &mut cfg.prompts.claude.prompts,
|
|
||||||
AppType::Codex => &mut cfg.prompts.codex.prompts,
|
|
||||||
AppType::Gemini => &mut cfg.prompts.gemini.prompts,
|
|
||||||
};
|
|
||||||
|
|
||||||
// 尝试回填到当前已启用的提示词
|
// 尝试回填到当前已启用的提示词
|
||||||
if let Some((enabled_id, enabled_prompt)) = prompts
|
if let Some((enabled_id, enabled_prompt)) = prompts
|
||||||
@@ -90,15 +72,11 @@ impl PromptService {
|
|||||||
.find(|(_, p)| p.enabled)
|
.find(|(_, p)| p.enabled)
|
||||||
.map(|(id, p)| (id.clone(), p))
|
.map(|(id, p)| (id.clone(), p))
|
||||||
{
|
{
|
||||||
let timestamp = std::time::SystemTime::now()
|
let timestamp = get_unix_timestamp()?;
|
||||||
.duration_since(std::time::UNIX_EPOCH)
|
|
||||||
.unwrap()
|
|
||||||
.as_secs() as i64;
|
|
||||||
enabled_prompt.content = live_content.clone();
|
enabled_prompt.content = live_content.clone();
|
||||||
enabled_prompt.updated_at = Some(timestamp);
|
enabled_prompt.updated_at = Some(timestamp);
|
||||||
log::info!("回填 live 提示词内容到已启用项: {enabled_id}");
|
log::info!("回填 live 提示词内容到已启用项: {enabled_id}");
|
||||||
drop(cfg); // 释放锁后保存,避免死锁
|
state.db.save_prompt(app.as_str(), enabled_prompt)?;
|
||||||
state.save()?; // 第一次保存:回填后立即持久化
|
|
||||||
} else {
|
} else {
|
||||||
// 没有已启用的提示词,则创建一次备份(避免重复备份)
|
// 没有已启用的提示词,则创建一次备份(避免重复备份)
|
||||||
let content_exists = prompts
|
let content_exists = prompts
|
||||||
@@ -122,13 +100,8 @@ impl PromptService {
|
|||||||
created_at: Some(timestamp),
|
created_at: Some(timestamp),
|
||||||
updated_at: Some(timestamp),
|
updated_at: Some(timestamp),
|
||||||
};
|
};
|
||||||
prompts.insert(backup_id.clone(), backup_prompt);
|
|
||||||
log::info!("回填 live 提示词内容,创建备份: {backup_id}");
|
log::info!("回填 live 提示词内容,创建备份: {backup_id}");
|
||||||
drop(cfg); // 释放锁后保存
|
state.db.save_prompt(app.as_str(), &backup_prompt)?;
|
||||||
state.save()?; // 第一次保存:回填后立即持久化
|
|
||||||
} else {
|
|
||||||
// 即使内容已存在,也无需重复备份;但不需要保存任何更改
|
|
||||||
drop(cfg);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -136,12 +109,7 @@ impl PromptService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 启用目标提示词并写入文件
|
// 启用目标提示词并写入文件
|
||||||
let mut cfg = state.config.write()?;
|
let mut prompts = state.db.get_prompts(app.as_str())?;
|
||||||
let prompts = match app {
|
|
||||||
AppType::Claude => &mut cfg.prompts.claude.prompts,
|
|
||||||
AppType::Codex => &mut cfg.prompts.codex.prompts,
|
|
||||||
AppType::Gemini => &mut cfg.prompts.gemini.prompts,
|
|
||||||
};
|
|
||||||
|
|
||||||
for prompt in prompts.values_mut() {
|
for prompt in prompts.values_mut() {
|
||||||
prompt.enabled = false;
|
prompt.enabled = false;
|
||||||
@@ -150,12 +118,16 @@ impl PromptService {
|
|||||||
if let Some(prompt) = prompts.get_mut(id) {
|
if let Some(prompt) = prompts.get_mut(id) {
|
||||||
prompt.enabled = true;
|
prompt.enabled = true;
|
||||||
write_text_file(&target_path, &prompt.content)?; // 原子写入
|
write_text_file(&target_path, &prompt.content)?; // 原子写入
|
||||||
|
state.db.save_prompt(app.as_str(), prompt)?;
|
||||||
} else {
|
} else {
|
||||||
return Err(AppError::InvalidInput(format!("提示词 {id} 不存在")));
|
return Err(AppError::InvalidInput(format!("提示词 {id} 不存在")));
|
||||||
}
|
}
|
||||||
|
|
||||||
drop(cfg);
|
// Save all prompts to disable others
|
||||||
state.save()?; // 第二次保存:启用目标提示词并写入文件后
|
for (_, prompt) in prompts.iter() {
|
||||||
|
state.db.save_prompt(app.as_str(), prompt)?;
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -168,10 +140,7 @@ impl PromptService {
|
|||||||
|
|
||||||
let content =
|
let content =
|
||||||
std::fs::read_to_string(&file_path).map_err(|e| AppError::io(&file_path, e))?;
|
std::fs::read_to_string(&file_path).map_err(|e| AppError::io(&file_path, e))?;
|
||||||
let timestamp = std::time::SystemTime::now()
|
let timestamp = get_unix_timestamp()?;
|
||||||
.duration_since(std::time::UNIX_EPOCH)
|
|
||||||
.unwrap()
|
|
||||||
.as_secs() as i64;
|
|
||||||
|
|
||||||
let id = format!("imported-{timestamp}");
|
let id = format!("imported-{timestamp}");
|
||||||
let prompt = Prompt {
|
let prompt = Prompt {
|
||||||
@@ -200,4 +169,56 @@ impl PromptService {
|
|||||||
std::fs::read_to_string(&file_path).map_err(|e| AppError::io(&file_path, e))?;
|
std::fs::read_to_string(&file_path).map_err(|e| AppError::io(&file_path, e))?;
|
||||||
Ok(Some(content))
|
Ok(Some(content))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 首次启动时从现有提示词文件自动导入(如果存在)
|
||||||
|
/// 返回导入的数量
|
||||||
|
pub fn import_from_file_on_first_launch(
|
||||||
|
state: &AppState,
|
||||||
|
app: AppType,
|
||||||
|
) -> Result<usize, AppError> {
|
||||||
|
let file_path = prompt_file_path(&app)?;
|
||||||
|
|
||||||
|
// 检查文件是否存在
|
||||||
|
if !file_path.exists() {
|
||||||
|
return Ok(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 读取文件内容
|
||||||
|
let content = match std::fs::read_to_string(&file_path) {
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(e) => {
|
||||||
|
log::warn!("读取提示词文件失败: {file_path:?}, 错误: {e}");
|
||||||
|
return Ok(0);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 检查内容是否为空
|
||||||
|
if content.trim().is_empty() {
|
||||||
|
return Ok(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
log::info!("发现提示词文件,自动导入: {file_path:?}");
|
||||||
|
|
||||||
|
// 创建提示词对象
|
||||||
|
let timestamp = get_unix_timestamp()?;
|
||||||
|
let id = format!("auto-imported-{timestamp}");
|
||||||
|
let prompt = Prompt {
|
||||||
|
id: id.clone(),
|
||||||
|
name: format!(
|
||||||
|
"Auto-imported Prompt {}",
|
||||||
|
chrono::Local::now().format("%Y-%m-%d %H:%M")
|
||||||
|
),
|
||||||
|
content,
|
||||||
|
description: Some("Automatically imported on first launch".to_string()),
|
||||||
|
enabled: true, // 首次导入时自动启用
|
||||||
|
created_at: Some(timestamp),
|
||||||
|
updated_at: Some(timestamp),
|
||||||
|
};
|
||||||
|
|
||||||
|
// 保存到数据库
|
||||||
|
state.db.save_prompt(app.as_str(), &prompt)?;
|
||||||
|
|
||||||
|
log::info!("自动导入完成: {}", app.as_str());
|
||||||
|
Ok(1)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+162
-674
File diff suppressed because it is too large
Load Diff
@@ -231,7 +231,12 @@ impl SkillService {
|
|||||||
// 解析技能元数据
|
// 解析技能元数据
|
||||||
match self.parse_skill_metadata(&skill_md) {
|
match self.parse_skill_metadata(&skill_md) {
|
||||||
Ok(meta) => {
|
Ok(meta) => {
|
||||||
let directory = path.file_name().unwrap().to_string_lossy().to_string();
|
// 安全地获取目录名
|
||||||
|
let Some(dir_name) = path.file_name() else {
|
||||||
|
log::warn!("Failed to get directory name from path: {path:?}");
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let directory = dir_name.to_string_lossy().to_string();
|
||||||
|
|
||||||
// 构建 README URL(考虑 skillsPath)
|
// 构建 README URL(考虑 skillsPath)
|
||||||
let readme_path = if let Some(ref skills_path) = repo.skills_path {
|
let readme_path = if let Some(ref skills_path) = repo.skills_path {
|
||||||
@@ -305,7 +310,12 @@ impl SkillService {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
let directory = path.file_name().unwrap().to_string_lossy().to_string();
|
// 安全地获取目录名
|
||||||
|
let Some(dir_name) = path.file_name() else {
|
||||||
|
log::warn!("Failed to get directory name from path: {path:?}");
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let directory = dir_name.to_string_lossy().to_string();
|
||||||
|
|
||||||
// 更新已安装状态
|
// 更新已安装状态
|
||||||
let mut found = false;
|
let mut found = false;
|
||||||
|
|||||||
+77
-19
@@ -2,8 +2,9 @@ use serde::{Deserialize, Serialize};
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::sync::{OnceLock, RwLock};
|
use std::sync::{Arc, OnceLock, RwLock};
|
||||||
|
|
||||||
|
use crate::database::Database;
|
||||||
use crate::error::AppError;
|
use crate::error::AppError;
|
||||||
|
|
||||||
/// 自定义端点配置
|
/// 自定义端点配置
|
||||||
@@ -90,8 +91,7 @@ impl Default for AppSettings {
|
|||||||
|
|
||||||
impl AppSettings {
|
impl AppSettings {
|
||||||
fn settings_path() -> PathBuf {
|
fn settings_path() -> PathBuf {
|
||||||
// settings.json 必须使用固定路径,不能被 app_config_dir 覆盖
|
// settings.json 保留用于旧版本迁移和无数据库场景
|
||||||
// 否则会造成循环依赖:读取 settings 需要知道路径,但路径在 settings 中
|
|
||||||
dirs::home_dir()
|
dirs::home_dir()
|
||||||
.expect("无法获取用户主目录")
|
.expect("无法获取用户主目录")
|
||||||
.join(".cc-switch")
|
.join(".cc-switch")
|
||||||
@@ -128,7 +128,7 @@ impl AppSettings {
|
|||||||
.map(|s| s.to_string());
|
.map(|s| s.to_string());
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn load() -> Self {
|
fn load_from_file() -> Self {
|
||||||
let path = Self::settings_path();
|
let path = Self::settings_path();
|
||||||
if let Ok(content) = fs::read_to_string(&path) {
|
if let Ok(content) = fs::read_to_string(&path) {
|
||||||
match serde_json::from_str::<AppSettings>(&content) {
|
match serde_json::from_str::<AppSettings>(&content) {
|
||||||
@@ -149,26 +149,80 @@ impl AppSettings {
|
|||||||
Self::default()
|
Self::default()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn save(&self) -> Result<(), AppError> {
|
fn save_settings_file(settings: &AppSettings) -> Result<(), AppError> {
|
||||||
let mut normalized = self.clone();
|
let mut normalized = settings.clone();
|
||||||
normalized.normalize_paths();
|
normalized.normalize_paths();
|
||||||
let path = Self::settings_path();
|
let path = AppSettings::settings_path();
|
||||||
|
|
||||||
if let Some(parent) = path.parent() {
|
if let Some(parent) = path.parent() {
|
||||||
fs::create_dir_all(parent).map_err(|e| AppError::io(parent, e))?;
|
fs::create_dir_all(parent).map_err(|e| AppError::io(parent, e))?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let json = serde_json::to_string_pretty(&normalized)
|
let json = serde_json::to_string_pretty(&normalized)
|
||||||
.map_err(|e| AppError::JsonSerialize { source: e })?;
|
.map_err(|e| AppError::JsonSerialize { source: e })?;
|
||||||
fs::write(&path, json).map_err(|e| AppError::io(&path, e))?;
|
fs::write(&path, json).map_err(|e| AppError::io(&path, e))?;
|
||||||
Ok(())
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
static SETTINGS_STORE: OnceLock<RwLock<AppSettings>> = OnceLock::new();
|
||||||
|
|
||||||
|
fn settings_store() -> &'static RwLock<AppSettings> {
|
||||||
|
SETTINGS_STORE.get_or_init(|| RwLock::new(load_initial_settings()))
|
||||||
|
}
|
||||||
|
|
||||||
|
static SETTINGS_DB: OnceLock<Arc<Database>> = OnceLock::new();
|
||||||
|
const APP_SETTINGS_KEY: &str = "app_settings";
|
||||||
|
|
||||||
|
pub fn bind_db(db: Arc<Database>) {
|
||||||
|
if SETTINGS_DB.set(db).is_err() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(store) = SETTINGS_STORE.get() {
|
||||||
|
let mut guard = store.write().expect("写入设置锁失败");
|
||||||
|
*guard = load_initial_settings();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn settings_store() -> &'static RwLock<AppSettings> {
|
fn load_initial_settings() -> AppSettings {
|
||||||
static STORE: OnceLock<RwLock<AppSettings>> = OnceLock::new();
|
if let Some(db) = SETTINGS_DB.get() {
|
||||||
STORE.get_or_init(|| RwLock::new(AppSettings::load()))
|
if let Some(from_db) = load_from_db(db.as_ref()) {
|
||||||
|
return from_db;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 从文件迁移一次并写入数据库
|
||||||
|
let file_settings = AppSettings::load_from_file();
|
||||||
|
if let Err(e) = save_to_db(db.as_ref(), &file_settings) {
|
||||||
|
log::warn!("迁移设置到数据库失败,将继续使用内存副本: {e}");
|
||||||
|
}
|
||||||
|
return file_settings;
|
||||||
|
}
|
||||||
|
|
||||||
|
AppSettings::load_from_file()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_from_db(db: &Database) -> Option<AppSettings> {
|
||||||
|
let raw = db.get_setting(APP_SETTINGS_KEY).ok()??;
|
||||||
|
match serde_json::from_str::<AppSettings>(&raw) {
|
||||||
|
Ok(mut settings) => {
|
||||||
|
settings.normalize_paths();
|
||||||
|
Some(settings)
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
log::warn!("解析数据库中 app_settings 失败: {err}");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save_to_db(db: &Database, settings: &AppSettings) -> Result<(), AppError> {
|
||||||
|
let mut normalized = settings.clone();
|
||||||
|
normalized.normalize_paths();
|
||||||
|
let json =
|
||||||
|
serde_json::to_string(&normalized).map_err(|e| AppError::JsonSerialize { source: e })?;
|
||||||
|
db.set_setting(APP_SETTINGS_KEY, &json)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn resolve_override_path(raw: &str) -> PathBuf {
|
fn resolve_override_path(raw: &str) -> PathBuf {
|
||||||
@@ -195,7 +249,11 @@ pub fn get_settings() -> AppSettings {
|
|||||||
|
|
||||||
pub fn update_settings(mut new_settings: AppSettings) -> Result<(), AppError> {
|
pub fn update_settings(mut new_settings: AppSettings) -> Result<(), AppError> {
|
||||||
new_settings.normalize_paths();
|
new_settings.normalize_paths();
|
||||||
new_settings.save()?;
|
if let Some(db) = SETTINGS_DB.get() {
|
||||||
|
save_to_db(db, &new_settings)?;
|
||||||
|
} else {
|
||||||
|
save_settings_file(&new_settings)?;
|
||||||
|
}
|
||||||
|
|
||||||
let mut guard = settings_store().write().expect("写入设置锁失败");
|
let mut guard = settings_store().write().expect("写入设置锁失败");
|
||||||
*guard = new_settings;
|
*guard = new_settings;
|
||||||
|
|||||||
+5
-17
@@ -1,26 +1,14 @@
|
|||||||
use crate::app_config::MultiAppConfig;
|
use crate::database::Database;
|
||||||
use crate::error::AppError;
|
use std::sync::Arc;
|
||||||
use std::sync::RwLock;
|
|
||||||
|
|
||||||
/// 全局应用状态
|
/// 全局应用状态
|
||||||
pub struct AppState {
|
pub struct AppState {
|
||||||
pub config: RwLock<MultiAppConfig>,
|
pub db: Arc<Database>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AppState {
|
impl AppState {
|
||||||
/// 创建新的应用状态
|
/// 创建新的应用状态
|
||||||
/// 注意:仅在配置成功加载时返回;不会在失败时回退默认值。
|
pub fn new(db: Arc<Database>) -> Self {
|
||||||
pub fn try_new() -> Result<Self, AppError> {
|
Self { db }
|
||||||
let config = MultiAppConfig::load()?;
|
|
||||||
Ok(Self {
|
|
||||||
config: RwLock::new(config),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 保存配置到文件
|
|
||||||
pub fn save(&self) -> Result<(), AppError> {
|
|
||||||
let config = self.config.read().map_err(AppError::from)?;
|
|
||||||
|
|
||||||
config.save()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,46 +1,36 @@
|
|||||||
use std::sync::RwLock;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use cc_switch_lib::{
|
use cc_switch_lib::{import_provider_from_deeplink, parse_deeplink_url, AppState, Database};
|
||||||
import_provider_from_deeplink, parse_deeplink_url, AppState, AppType, MultiAppConfig,
|
|
||||||
};
|
|
||||||
|
|
||||||
#[path = "support.rs"]
|
#[path = "support.rs"]
|
||||||
mod support;
|
mod support;
|
||||||
use support::{ensure_test_home, reset_test_fs, test_mutex};
|
use support::{ensure_test_home, reset_test_fs, test_mutex};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn deeplink_import_claude_provider_persists_to_config() {
|
fn deeplink_import_claude_provider_persists_to_db() {
|
||||||
let _guard = test_mutex().lock().expect("acquire test mutex");
|
let _guard = test_mutex().lock().expect("acquire test mutex");
|
||||||
reset_test_fs();
|
reset_test_fs();
|
||||||
let home = ensure_test_home();
|
let _home = ensure_test_home();
|
||||||
|
|
||||||
let url = "ccswitch://v1/import?resource=provider&app=claude&name=DeepLink%20Claude&homepage=https%3A%2F%2Fexample.com&endpoint=https%3A%2F%2Fapi.example.com%2Fv1&apiKey=sk-test-claude-key&model=claude-sonnet-4";
|
let url = "ccswitch://v1/import?resource=provider&app=claude&name=DeepLink%20Claude&homepage=https%3A%2F%2Fexample.com&endpoint=https%3A%2F%2Fapi.example.com%2Fv1&apiKey=sk-test-claude-key&model=claude-sonnet-4&icon=claude";
|
||||||
let request = parse_deeplink_url(url).expect("parse deeplink url");
|
let request = parse_deeplink_url(url).expect("parse deeplink url");
|
||||||
|
|
||||||
let mut config = MultiAppConfig::default();
|
let db = Arc::new(Database::memory().expect("create memory db"));
|
||||||
config.ensure_app(&AppType::Claude);
|
|
||||||
|
|
||||||
let state = AppState {
|
let state = AppState { db: db.clone() };
|
||||||
config: RwLock::new(config),
|
|
||||||
};
|
|
||||||
|
|
||||||
let provider_id = import_provider_from_deeplink(&state, request.clone())
|
let provider_id = import_provider_from_deeplink(&state, request.clone())
|
||||||
.expect("import provider from deeplink");
|
.expect("import provider from deeplink");
|
||||||
|
|
||||||
// 验证内存状态
|
// Verify DB state
|
||||||
let guard = state.config.read().expect("read config");
|
let providers = db.get_all_providers("claude").expect("get providers");
|
||||||
let manager = guard
|
let provider = providers
|
||||||
.get_manager(&AppType::Claude)
|
|
||||||
.expect("claude manager should exist");
|
|
||||||
let provider = manager
|
|
||||||
.providers
|
|
||||||
.get(&provider_id)
|
.get(&provider_id)
|
||||||
.expect("provider created via deeplink");
|
.expect("provider created via deeplink");
|
||||||
assert_eq!(provider.name, request.name);
|
|
||||||
assert_eq!(
|
assert_eq!(provider.name, request.name.clone().unwrap());
|
||||||
provider.website_url.as_deref(),
|
assert_eq!(provider.website_url.as_deref(), request.homepage.as_deref());
|
||||||
Some(request.homepage.as_str())
|
assert_eq!(provider.icon.as_deref(), Some("claude"));
|
||||||
);
|
|
||||||
let auth_token = provider
|
let auth_token = provider
|
||||||
.settings_config
|
.settings_config
|
||||||
.pointer("/env/ANTHROPIC_AUTH_TOKEN")
|
.pointer("/env/ANTHROPIC_AUTH_TOKEN")
|
||||||
@@ -49,50 +39,34 @@ fn deeplink_import_claude_provider_persists_to_config() {
|
|||||||
.settings_config
|
.settings_config
|
||||||
.pointer("/env/ANTHROPIC_BASE_URL")
|
.pointer("/env/ANTHROPIC_BASE_URL")
|
||||||
.and_then(|v| v.as_str());
|
.and_then(|v| v.as_str());
|
||||||
assert_eq!(auth_token, Some(request.api_key.as_str()));
|
assert_eq!(auth_token, request.api_key.as_deref());
|
||||||
assert_eq!(base_url, Some(request.endpoint.as_str()));
|
assert_eq!(base_url, request.endpoint.as_deref());
|
||||||
drop(guard);
|
|
||||||
|
|
||||||
// 验证配置已持久化
|
|
||||||
let config_path = home.join(".cc-switch").join("config.json");
|
|
||||||
assert!(
|
|
||||||
config_path.exists(),
|
|
||||||
"importing provider from deeplink should persist config.json"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn deeplink_import_codex_provider_builds_auth_and_config() {
|
fn deeplink_import_codex_provider_builds_auth_and_config() {
|
||||||
let _guard = test_mutex().lock().expect("acquire test mutex");
|
let _guard = test_mutex().lock().expect("acquire test mutex");
|
||||||
reset_test_fs();
|
reset_test_fs();
|
||||||
let home = ensure_test_home();
|
let _home = ensure_test_home();
|
||||||
|
|
||||||
let url = "ccswitch://v1/import?resource=provider&app=codex&name=DeepLink%20Codex&homepage=https%3A%2F%2Fopenai.example&endpoint=https%3A%2F%2Fapi.openai.example%2Fv1&apiKey=sk-test-codex-key&model=gpt-4o";
|
let url = "ccswitch://v1/import?resource=provider&app=codex&name=DeepLink%20Codex&homepage=https%3A%2F%2Fopenai.example&endpoint=https%3A%2F%2Fapi.openai.example%2Fv1&apiKey=sk-test-codex-key&model=gpt-4o&icon=openai";
|
||||||
let request = parse_deeplink_url(url).expect("parse deeplink url");
|
let request = parse_deeplink_url(url).expect("parse deeplink url");
|
||||||
|
|
||||||
let mut config = MultiAppConfig::default();
|
let db = Arc::new(Database::memory().expect("create memory db"));
|
||||||
config.ensure_app(&AppType::Codex);
|
|
||||||
|
|
||||||
let state = AppState {
|
let state = AppState { db: db.clone() };
|
||||||
config: RwLock::new(config),
|
|
||||||
};
|
|
||||||
|
|
||||||
let provider_id = import_provider_from_deeplink(&state, request.clone())
|
let provider_id = import_provider_from_deeplink(&state, request.clone())
|
||||||
.expect("import provider from deeplink");
|
.expect("import provider from deeplink");
|
||||||
|
|
||||||
let guard = state.config.read().expect("read config");
|
let providers = db.get_all_providers("codex").expect("get providers");
|
||||||
let manager = guard
|
let provider = providers
|
||||||
.get_manager(&AppType::Codex)
|
|
||||||
.expect("codex manager should exist");
|
|
||||||
let provider = manager
|
|
||||||
.providers
|
|
||||||
.get(&provider_id)
|
.get(&provider_id)
|
||||||
.expect("provider created via deeplink");
|
.expect("provider created via deeplink");
|
||||||
assert_eq!(provider.name, request.name);
|
|
||||||
assert_eq!(
|
assert_eq!(provider.name, request.name.clone().unwrap());
|
||||||
provider.website_url.as_deref(),
|
assert_eq!(provider.website_url.as_deref(), request.homepage.as_deref());
|
||||||
Some(request.homepage.as_str())
|
assert_eq!(provider.icon.as_deref(), Some("openai"));
|
||||||
);
|
|
||||||
let auth_value = provider
|
let auth_value = provider
|
||||||
.settings_config
|
.settings_config
|
||||||
.pointer("/auth/OPENAI_API_KEY")
|
.pointer("/auth/OPENAI_API_KEY")
|
||||||
@@ -102,20 +76,13 @@ fn deeplink_import_codex_provider_builds_auth_and_config() {
|
|||||||
.get("config")
|
.get("config")
|
||||||
.and_then(|v| v.as_str())
|
.and_then(|v| v.as_str())
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
assert_eq!(auth_value, Some(request.api_key.as_str()));
|
assert_eq!(auth_value, request.api_key.as_deref());
|
||||||
assert!(
|
assert!(
|
||||||
config_text.contains(request.endpoint.as_str()),
|
config_text.contains(request.endpoint.as_deref().unwrap()),
|
||||||
"config.toml content should contain endpoint"
|
"config.toml content should contain endpoint"
|
||||||
);
|
);
|
||||||
assert!(
|
assert!(
|
||||||
config_text.contains("model = \"gpt-4o\""),
|
config_text.contains("model = \"gpt-4o\""),
|
||||||
"config.toml content should contain model setting"
|
"config.toml content should contain model setting"
|
||||||
);
|
);
|
||||||
drop(guard);
|
|
||||||
|
|
||||||
let config_path = home.join(".cc-switch").join("config.json");
|
|
||||||
assert!(
|
|
||||||
config_path.exists(),
|
|
||||||
"importing provider from deeplink should persist config.json"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { AppId } from "@/lib/api";
|
import type { AppId } from "@/lib/api";
|
||||||
import { ClaudeIcon, CodexIcon, GeminiIcon } from "./BrandIcons";
|
import { ProviderIcon } from "@/components/ProviderIcon";
|
||||||
|
|
||||||
interface AppSwitcherProps {
|
interface AppSwitcherProps {
|
||||||
activeApp: AppId;
|
activeApp: AppId;
|
||||||
@@ -11,6 +11,17 @@ export function AppSwitcher({ activeApp, onSwitch }: AppSwitcherProps) {
|
|||||||
if (app === activeApp) return;
|
if (app === activeApp) return;
|
||||||
onSwitch(app);
|
onSwitch(app);
|
||||||
};
|
};
|
||||||
|
const iconSize = 20;
|
||||||
|
const appIconName: Record<AppId, string> = {
|
||||||
|
claude: "claude",
|
||||||
|
codex: "openai",
|
||||||
|
gemini: "gemini",
|
||||||
|
};
|
||||||
|
const appDisplayName: Record<AppId, string> = {
|
||||||
|
claude: "Claude",
|
||||||
|
codex: "Codex",
|
||||||
|
gemini: "Gemini",
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="inline-flex bg-gray-100 dark:bg-gray-800 rounded-lg p-1 gap-1">
|
<div className="inline-flex bg-gray-100 dark:bg-gray-800 rounded-lg p-1 gap-1">
|
||||||
@@ -23,15 +34,17 @@ export function AppSwitcher({ activeApp, onSwitch }: AppSwitcherProps) {
|
|||||||
: "text-gray-500 hover:text-gray-900 hover:bg-white/50 dark:text-gray-400 dark:hover:text-gray-100 dark:hover:bg-gray-800/60"
|
: "text-gray-500 hover:text-gray-900 hover:bg-white/50 dark:text-gray-400 dark:hover:text-gray-100 dark:hover:bg-gray-800/60"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<ClaudeIcon
|
<ProviderIcon
|
||||||
size={16}
|
icon={appIconName.claude}
|
||||||
|
name={appDisplayName.claude}
|
||||||
|
size={iconSize}
|
||||||
className={
|
className={
|
||||||
activeApp === "claude"
|
activeApp === "claude"
|
||||||
? "text-foreground"
|
? "text-foreground"
|
||||||
: "text-gray-500 dark:text-gray-400 group-hover:text-foreground transition-colors"
|
: "text-gray-500 dark:text-gray-400 group-hover:text-foreground transition-colors"
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<span>Claude</span>
|
<span>{appDisplayName.claude}</span>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
@@ -43,15 +56,17 @@ export function AppSwitcher({ activeApp, onSwitch }: AppSwitcherProps) {
|
|||||||
: "text-gray-500 hover:text-gray-900 hover:bg-white/50 dark:text-gray-400 dark:hover:text-gray-100 dark:hover:bg-gray-800/60"
|
: "text-gray-500 hover:text-gray-900 hover:bg-white/50 dark:text-gray-400 dark:hover:text-gray-100 dark:hover:bg-gray-800/60"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<CodexIcon
|
<ProviderIcon
|
||||||
size={16}
|
icon={appIconName.codex}
|
||||||
|
name={appDisplayName.codex}
|
||||||
|
size={iconSize}
|
||||||
className={
|
className={
|
||||||
activeApp === "codex"
|
activeApp === "codex"
|
||||||
? "text-foreground"
|
? "text-foreground"
|
||||||
: "text-gray-500 dark:text-gray-400 group-hover:text-foreground transition-colors"
|
: "text-gray-500 dark:text-gray-400 group-hover:text-foreground transition-colors"
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<span>Codex</span>
|
<span>{appDisplayName.codex}</span>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
@@ -63,15 +78,17 @@ export function AppSwitcher({ activeApp, onSwitch }: AppSwitcherProps) {
|
|||||||
: "text-gray-500 hover:text-gray-900 hover:bg-white/50 dark:text-gray-400 dark:hover:text-gray-100 dark:hover:bg-gray-800/60"
|
: "text-gray-500 hover:text-gray-900 hover:bg-white/50 dark:text-gray-400 dark:hover:text-gray-100 dark:hover:bg-gray-800/60"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<GeminiIcon
|
<ProviderIcon
|
||||||
size={16}
|
icon={appIconName.gemini}
|
||||||
|
name={appDisplayName.gemini}
|
||||||
|
size={iconSize}
|
||||||
className={
|
className={
|
||||||
activeApp === "gemini"
|
activeApp === "gemini"
|
||||||
? "text-foreground"
|
? "text-foreground"
|
||||||
: "text-gray-500 dark:text-gray-400 group-hover:text-foreground transition-colors"
|
: "text-gray-500 dark:text-gray-400 group-hover:text-foreground transition-colors"
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<span>Gemini</span>
|
<span>{appDisplayName.gemini}</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -13,6 +13,10 @@ import { Button } from "@/components/ui/button";
|
|||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { useQueryClient } from "@tanstack/react-query";
|
import { useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { PromptConfirmation } from "./deeplink/PromptConfirmation";
|
||||||
|
import { McpConfirmation } from "./deeplink/McpConfirmation";
|
||||||
|
import { SkillConfirmation } from "./deeplink/SkillConfirmation";
|
||||||
|
import { ProviderIcon } from "./ProviderIcon";
|
||||||
|
|
||||||
interface DeeplinkError {
|
interface DeeplinkError {
|
||||||
url: string;
|
url: string;
|
||||||
@@ -26,6 +30,24 @@ export function DeepLinkImportDialog() {
|
|||||||
const [isImporting, setIsImporting] = useState(false);
|
const [isImporting, setIsImporting] = useState(false);
|
||||||
const [isOpen, setIsOpen] = useState(false);
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
|
|
||||||
|
// 容错判断:MCP 导入结果可能缺少 type 字段
|
||||||
|
const isMcpImportResult = (
|
||||||
|
value: unknown,
|
||||||
|
): value is {
|
||||||
|
importedCount: number;
|
||||||
|
importedIds: string[];
|
||||||
|
failed: Array<{ id: string; error: string }>;
|
||||||
|
type?: "mcp";
|
||||||
|
} => {
|
||||||
|
if (!value || typeof value !== "object") return false;
|
||||||
|
const v = value as Record<string, unknown>;
|
||||||
|
return (
|
||||||
|
typeof v.importedCount === "number" &&
|
||||||
|
Array.isArray(v.importedIds) &&
|
||||||
|
Array.isArray(v.failed)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Listen for deep link import events
|
// Listen for deep link import events
|
||||||
const unlistenImport = listen<DeepLinkImportRequest>(
|
const unlistenImport = listen<DeepLinkImportRequest>(
|
||||||
@@ -78,22 +100,89 @@ export function DeepLinkImportDialog() {
|
|||||||
setIsImporting(true);
|
setIsImporting(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await deeplinkApi.importFromDeeplink(request);
|
const result = await deeplinkApi.importFromDeeplink(request);
|
||||||
|
const refreshMcp = async (summary: {
|
||||||
|
importedCount: number;
|
||||||
|
importedIds: string[];
|
||||||
|
failed: Array<{ id: string; error: string }>;
|
||||||
|
}) => {
|
||||||
|
// 强制刷新 MCP 相关缓存,确保管理页重新从数据库加载
|
||||||
|
await queryClient.invalidateQueries({
|
||||||
|
queryKey: ["mcp", "all"],
|
||||||
|
refetchType: "all",
|
||||||
|
});
|
||||||
|
await queryClient.refetchQueries({
|
||||||
|
queryKey: ["mcp", "all"],
|
||||||
|
type: "all",
|
||||||
|
});
|
||||||
|
|
||||||
// Invalidate provider queries to refresh the list
|
if (summary.failed.length > 0) {
|
||||||
await queryClient.invalidateQueries({
|
toast.warning(`部分导入成功`, {
|
||||||
queryKey: ["providers", request.app],
|
description: `成功: ${summary.importedCount}, 失败: ${summary.failed.length}`,
|
||||||
});
|
});
|
||||||
|
} else {
|
||||||
|
toast.success("MCP Servers 导入成功", {
|
||||||
|
description: `成功导入 ${summary.importedCount} 个服务器`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
toast.success(t("deeplink.importSuccess"), {
|
// Handle different result types
|
||||||
description: t("deeplink.importSuccessDescription", {
|
if ("type" in result) {
|
||||||
name: request.name,
|
if (result.type === "provider") {
|
||||||
}),
|
await queryClient.invalidateQueries({
|
||||||
});
|
queryKey: ["providers", request.app],
|
||||||
|
});
|
||||||
|
toast.success(t("deeplink.importSuccess"), {
|
||||||
|
description: t("deeplink.importSuccessDescription", {
|
||||||
|
name: request.name,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
} else if (result.type === "prompt") {
|
||||||
|
// Prompts don't use React Query, trigger a custom event for refresh
|
||||||
|
window.dispatchEvent(
|
||||||
|
new CustomEvent("prompt-imported", {
|
||||||
|
detail: { app: request.app },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
toast.success("提示词导入成功", {
|
||||||
|
description: `已导入提示词: ${request.name}`,
|
||||||
|
});
|
||||||
|
} else if (result.type === "mcp") {
|
||||||
|
await refreshMcp(result);
|
||||||
|
} else if (result.type === "skill") {
|
||||||
|
// Refresh Skills with aggressive strategy
|
||||||
|
queryClient.invalidateQueries({
|
||||||
|
queryKey: ["skills"],
|
||||||
|
refetchType: "all",
|
||||||
|
});
|
||||||
|
await queryClient.refetchQueries({
|
||||||
|
queryKey: ["skills"],
|
||||||
|
type: "all",
|
||||||
|
});
|
||||||
|
toast.success("Skill 仓库添加成功", {
|
||||||
|
description: `已添加仓库: ${request.repo}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else if (isMcpImportResult(result)) {
|
||||||
|
// 兜底处理:旧版本后端可能未返回 type 字段
|
||||||
|
await refreshMcp(result);
|
||||||
|
} else {
|
||||||
|
// Legacy return type (string ID) - assume provider
|
||||||
|
await queryClient.invalidateQueries({
|
||||||
|
queryKey: ["providers", request.app],
|
||||||
|
});
|
||||||
|
toast.success(t("deeplink.importSuccess"), {
|
||||||
|
description: t("deeplink.importSuccessDescription", {
|
||||||
|
name: request.name,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close dialog after all refreshes complete
|
||||||
setIsOpen(false);
|
setIsOpen(false);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to import provider from deep link:", error);
|
console.error("Failed to import from deep link:", error);
|
||||||
toast.error(t("deeplink.importError"), {
|
toast.error(t("deeplink.importError"), {
|
||||||
description: error instanceof Error ? error.message : String(error),
|
description: error instanceof Error ? error.message : String(error),
|
||||||
});
|
});
|
||||||
@@ -189,6 +278,34 @@ export function DeepLinkImportDialog() {
|
|||||||
return value;
|
return value;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const getTitle = () => {
|
||||||
|
if (!request) return t("deeplink.confirmImport");
|
||||||
|
switch (request.resource) {
|
||||||
|
case "prompt":
|
||||||
|
return "导入提示词";
|
||||||
|
case "mcp":
|
||||||
|
return "导入 MCP Servers";
|
||||||
|
case "skill":
|
||||||
|
return "添加 Skill 仓库";
|
||||||
|
default:
|
||||||
|
return t("deeplink.confirmImport");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getDescription = () => {
|
||||||
|
if (!request) return t("deeplink.confirmImportDescription");
|
||||||
|
switch (request.resource) {
|
||||||
|
case "prompt":
|
||||||
|
return "请确认是否导入此系统提示词";
|
||||||
|
case "mcp":
|
||||||
|
return "请确认是否导入这些 MCP Servers";
|
||||||
|
case "skill":
|
||||||
|
return "请确认是否添加此 Skill 仓库";
|
||||||
|
default:
|
||||||
|
return t("deeplink.confirmImportDescription");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={isOpen && !!request} onOpenChange={setIsOpen}>
|
<Dialog open={isOpen && !!request} onOpenChange={setIsOpen}>
|
||||||
<DialogContent className="sm:max-w-[500px]" zIndex="top">
|
<DialogContent className="sm:max-w-[500px]" zIndex="top">
|
||||||
@@ -196,151 +313,197 @@ export function DeepLinkImportDialog() {
|
|||||||
<>
|
<>
|
||||||
{/* 标题显式左对齐,避免默认居中样式影响 */}
|
{/* 标题显式左对齐,避免默认居中样式影响 */}
|
||||||
<DialogHeader className="text-left sm:text-left">
|
<DialogHeader className="text-left sm:text-left">
|
||||||
<DialogTitle>{t("deeplink.confirmImport")}</DialogTitle>
|
<DialogTitle>{getTitle()}</DialogTitle>
|
||||||
<DialogDescription>
|
<DialogDescription>{getDescription()}</DialogDescription>
|
||||||
{t("deeplink.confirmImportDescription")}
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
|
|
||||||
{/* 主体内容整体右移,略大于标题内边距,让内容看起来不贴边 */}
|
{/* 主体内容整体右移,略大于标题内边距,让内容看起来不贴边 */}
|
||||||
<div className="space-y-4 px-8 py-4 max-h-[60vh] overflow-y-auto [scrollbar-width:thin] [&::-webkit-scrollbar]:w-1.5 [&::-webkit-scrollbar]:block [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-gray-200 dark:[&::-webkit-scrollbar-thumb]:bg-gray-700">
|
<div className="space-y-4 px-8 py-4 max-h-[60vh] overflow-y-auto [scrollbar-width:thin] [&::-webkit-scrollbar]:w-1.5 [&::-webkit-scrollbar]:block [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-gray-200 dark:[&::-webkit-scrollbar-thumb]:bg-gray-700">
|
||||||
{/* App Type */}
|
{request.resource === "prompt" && (
|
||||||
<div className="grid grid-cols-3 items-center gap-4">
|
<PromptConfirmation request={request} />
|
||||||
<div className="font-medium text-sm text-muted-foreground">
|
)}
|
||||||
{t("deeplink.app")}
|
{request.resource === "mcp" && (
|
||||||
</div>
|
<McpConfirmation request={request} />
|
||||||
<div className="col-span-2 text-sm font-medium capitalize">
|
)}
|
||||||
{request.app}
|
{request.resource === "skill" && (
|
||||||
</div>
|
<SkillConfirmation request={request} />
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Provider Name */}
|
|
||||||
<div className="grid grid-cols-3 items-center gap-4">
|
|
||||||
<div className="font-medium text-sm text-muted-foreground">
|
|
||||||
{t("deeplink.providerName")}
|
|
||||||
</div>
|
|
||||||
<div className="col-span-2 text-sm font-medium">
|
|
||||||
{request.name}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Homepage */}
|
|
||||||
<div className="grid grid-cols-3 items-center gap-4">
|
|
||||||
<div className="font-medium text-sm text-muted-foreground">
|
|
||||||
{t("deeplink.homepage")}
|
|
||||||
</div>
|
|
||||||
<div className="col-span-2 text-sm break-all text-blue-600 dark:text-blue-400">
|
|
||||||
{request.homepage}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* API Endpoint */}
|
|
||||||
<div className="grid grid-cols-3 items-center gap-4">
|
|
||||||
<div className="font-medium text-sm text-muted-foreground">
|
|
||||||
{t("deeplink.endpoint")}
|
|
||||||
</div>
|
|
||||||
<div className="col-span-2 text-sm break-all">
|
|
||||||
{request.endpoint}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* API Key (masked) */}
|
|
||||||
<div className="grid grid-cols-3 items-center gap-4">
|
|
||||||
<div className="font-medium text-sm text-muted-foreground">
|
|
||||||
{t("deeplink.apiKey")}
|
|
||||||
</div>
|
|
||||||
<div className="col-span-2 text-sm font-mono text-muted-foreground">
|
|
||||||
{maskedApiKey}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Model (if present) */}
|
|
||||||
{request.model && (
|
|
||||||
<div className="grid grid-cols-3 items-center gap-4">
|
|
||||||
<div className="font-medium text-sm text-muted-foreground">
|
|
||||||
{t("deeplink.model")}
|
|
||||||
</div>
|
|
||||||
<div className="col-span-2 text-sm font-mono">
|
|
||||||
{request.model}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Notes (if present) */}
|
{/* Legacy Provider View */}
|
||||||
{request.notes && (
|
{(request.resource === "provider" || !request.resource) && (
|
||||||
<div className="grid grid-cols-3 items-start gap-4">
|
<>
|
||||||
<div className="font-medium text-sm text-muted-foreground">
|
{/* Provider Icon - enlarge and center near the top */}
|
||||||
{t("deeplink.notes")}
|
{request.icon && (
|
||||||
</div>
|
<div className="flex justify-center pt-2 pb-1">
|
||||||
<div className="col-span-2 text-sm text-muted-foreground">
|
<ProviderIcon
|
||||||
{request.notes}
|
icon={request.icon}
|
||||||
</div>
|
name={request.name || request.icon}
|
||||||
</div>
|
size={80}
|
||||||
)}
|
className="drop-shadow-sm"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Config File Details (v3.8+) */}
|
{/* App Type */}
|
||||||
{hasConfigFile && (
|
|
||||||
<div className="space-y-3 pt-2 border-t border-border-default">
|
|
||||||
<div className="grid grid-cols-3 items-center gap-4">
|
<div className="grid grid-cols-3 items-center gap-4">
|
||||||
<div className="font-medium text-sm text-muted-foreground">
|
<div className="font-medium text-sm text-muted-foreground">
|
||||||
{t("deeplink.configSource")}
|
{t("deeplink.app")}
|
||||||
</div>
|
</div>
|
||||||
<div className="col-span-2 text-sm">
|
<div className="col-span-2 text-sm font-medium capitalize">
|
||||||
<span className="inline-flex items-center px-2 py-0.5 rounded-md bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 text-xs font-medium">
|
{request.app}
|
||||||
{configSource === "base64"
|
|
||||||
? t("deeplink.configEmbedded")
|
|
||||||
: t("deeplink.configRemote")}
|
|
||||||
</span>
|
|
||||||
{request.configFormat && (
|
|
||||||
<span className="ml-2 text-xs text-muted-foreground uppercase">
|
|
||||||
{request.configFormat}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Parsed Config Details */}
|
{/* Provider Name */}
|
||||||
{parsedConfig && (
|
<div className="grid grid-cols-3 items-center gap-4">
|
||||||
<div className="rounded-lg bg-muted/50 p-3 space-y-2">
|
<div className="font-medium text-sm text-muted-foreground">
|
||||||
<div className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
|
{t("deeplink.providerName")}
|
||||||
{t("deeplink.configDetails")}
|
</div>
|
||||||
</div>
|
<div className="col-span-2 text-sm font-medium">
|
||||||
|
{request.name}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Claude config */}
|
{/* Homepage */}
|
||||||
{parsedConfig.type === "claude" && parsedConfig.env && (
|
<div className="grid grid-cols-3 items-center gap-4">
|
||||||
<div className="space-y-1.5">
|
<div className="font-medium text-sm text-muted-foreground">
|
||||||
{Object.entries(parsedConfig.env).map(
|
{t("deeplink.homepage")}
|
||||||
([key, value]) => (
|
</div>
|
||||||
<div
|
<div className="col-span-2 text-sm break-all text-blue-600 dark:text-blue-400">
|
||||||
key={key}
|
{request.homepage}
|
||||||
className="grid grid-cols-2 gap-2 text-xs"
|
</div>
|
||||||
>
|
</div>
|
||||||
<span className="font-mono text-muted-foreground truncate">
|
|
||||||
{key}
|
{/* API Endpoint */}
|
||||||
</span>
|
<div className="grid grid-cols-3 items-center gap-4">
|
||||||
<span className="font-mono truncate">
|
<div className="font-medium text-sm text-muted-foreground">
|
||||||
{maskValue(key, String(value))}
|
{t("deeplink.endpoint")}
|
||||||
</span>
|
</div>
|
||||||
</div>
|
<div className="col-span-2 text-sm break-all">
|
||||||
),
|
{request.endpoint}
|
||||||
)}
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* API Key (masked) */}
|
||||||
|
<div className="grid grid-cols-3 items-center gap-4">
|
||||||
|
<div className="font-medium text-sm text-muted-foreground">
|
||||||
|
{t("deeplink.apiKey")}
|
||||||
|
</div>
|
||||||
|
<div className="col-span-2 text-sm font-mono text-muted-foreground">
|
||||||
|
{maskedApiKey}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Model Fields - 根据应用类型显示不同的模型字段 */}
|
||||||
|
{request.app === "claude" ? (
|
||||||
|
<>
|
||||||
|
{/* Claude 四种模型字段 */}
|
||||||
|
{request.haikuModel && (
|
||||||
|
<div className="grid grid-cols-3 items-center gap-4">
|
||||||
|
<div className="font-medium text-sm text-muted-foreground">
|
||||||
|
{t("deeplink.haikuModel")}
|
||||||
|
</div>
|
||||||
|
<div className="col-span-2 text-sm font-mono">
|
||||||
|
{request.haikuModel}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{request.sonnetModel && (
|
||||||
|
<div className="grid grid-cols-3 items-center gap-4">
|
||||||
|
<div className="font-medium text-sm text-muted-foreground">
|
||||||
|
{t("deeplink.sonnetModel")}
|
||||||
|
</div>
|
||||||
|
<div className="col-span-2 text-sm font-mono">
|
||||||
|
{request.sonnetModel}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{request.opusModel && (
|
||||||
|
<div className="grid grid-cols-3 items-center gap-4">
|
||||||
|
<div className="font-medium text-sm text-muted-foreground">
|
||||||
|
{t("deeplink.opusModel")}
|
||||||
|
</div>
|
||||||
|
<div className="col-span-2 text-sm font-mono">
|
||||||
|
{request.opusModel}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{request.model && (
|
||||||
|
<div className="grid grid-cols-3 items-center gap-4">
|
||||||
|
<div className="font-medium text-sm text-muted-foreground">
|
||||||
|
{t("deeplink.multiModel")}
|
||||||
|
</div>
|
||||||
|
<div className="col-span-2 text-sm font-mono">
|
||||||
|
{request.model}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{/* Codex 和 Gemini 使用通用 model 字段 */}
|
||||||
|
{request.model && (
|
||||||
|
<div className="grid grid-cols-3 items-center gap-4">
|
||||||
|
<div className="font-medium text-sm text-muted-foreground">
|
||||||
|
{t("deeplink.model")}
|
||||||
|
</div>
|
||||||
|
<div className="col-span-2 text-sm font-mono">
|
||||||
|
{request.model}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Codex config */}
|
{/* Notes (if present) */}
|
||||||
{parsedConfig.type === "codex" && (
|
{request.notes && (
|
||||||
<div className="space-y-2">
|
<div className="grid grid-cols-3 items-start gap-4">
|
||||||
{parsedConfig.auth &&
|
<div className="font-medium text-sm text-muted-foreground">
|
||||||
Object.keys(parsedConfig.auth).length > 0 && (
|
{t("deeplink.notes")}
|
||||||
|
</div>
|
||||||
|
<div className="col-span-2 text-sm text-muted-foreground">
|
||||||
|
{request.notes}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Config File Details (v3.8+) */}
|
||||||
|
{hasConfigFile && (
|
||||||
|
<div className="space-y-3 pt-2 border-t border-border-default">
|
||||||
|
<div className="grid grid-cols-3 items-center gap-4">
|
||||||
|
<div className="font-medium text-sm text-muted-foreground">
|
||||||
|
{t("deeplink.configSource")}
|
||||||
|
</div>
|
||||||
|
<div className="col-span-2 text-sm">
|
||||||
|
<span className="inline-flex items-center px-2 py-0.5 rounded-md bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 text-xs font-medium">
|
||||||
|
{configSource === "base64"
|
||||||
|
? t("deeplink.configEmbedded")
|
||||||
|
: t("deeplink.configRemote")}
|
||||||
|
</span>
|
||||||
|
{request.configFormat && (
|
||||||
|
<span className="ml-2 text-xs text-muted-foreground uppercase">
|
||||||
|
{request.configFormat}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Parsed Config Details */}
|
||||||
|
{parsedConfig && (
|
||||||
|
<div className="rounded-lg bg-muted/50 p-3 space-y-2">
|
||||||
|
<div className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
|
||||||
|
{t("deeplink.configDetails")}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Claude config */}
|
||||||
|
{parsedConfig.type === "claude" &&
|
||||||
|
parsedConfig.env && (
|
||||||
<div className="space-y-1.5">
|
<div className="space-y-1.5">
|
||||||
<div className="text-xs text-muted-foreground">
|
{Object.entries(parsedConfig.env).map(
|
||||||
Auth:
|
|
||||||
</div>
|
|
||||||
{Object.entries(parsedConfig.auth).map(
|
|
||||||
([key, value]) => (
|
([key, value]) => (
|
||||||
<div
|
<div
|
||||||
key={key}
|
key={key}
|
||||||
className="grid grid-cols-2 gap-2 text-xs pl-2"
|
className="grid grid-cols-2 gap-2 text-xs"
|
||||||
>
|
>
|
||||||
<span className="font-mono text-muted-foreground truncate">
|
<span className="font-mono text-muted-foreground truncate">
|
||||||
{key}
|
{key}
|
||||||
@@ -353,61 +516,92 @@ export function DeepLinkImportDialog() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{parsedConfig.tomlConfig && (
|
|
||||||
<div className="space-y-1">
|
{/* Codex config */}
|
||||||
<div className="text-xs text-muted-foreground">
|
{parsedConfig.type === "codex" && (
|
||||||
TOML Config:
|
<div className="space-y-2">
|
||||||
</div>
|
{parsedConfig.auth &&
|
||||||
<pre className="text-xs font-mono bg-background p-2 rounded overflow-x-auto max-h-24 whitespace-pre-wrap">
|
Object.keys(parsedConfig.auth).length > 0 && (
|
||||||
{parsedConfig.tomlConfig.substring(0, 300)}
|
<div className="space-y-1.5">
|
||||||
{parsedConfig.tomlConfig.length > 300 && "..."}
|
<div className="text-xs text-muted-foreground">
|
||||||
</pre>
|
Auth:
|
||||||
|
</div>
|
||||||
|
{Object.entries(parsedConfig.auth).map(
|
||||||
|
([key, value]) => (
|
||||||
|
<div
|
||||||
|
key={key}
|
||||||
|
className="grid grid-cols-2 gap-2 text-xs pl-2"
|
||||||
|
>
|
||||||
|
<span className="font-mono text-muted-foreground truncate">
|
||||||
|
{key}
|
||||||
|
</span>
|
||||||
|
<span className="font-mono truncate">
|
||||||
|
{maskValue(key, String(value))}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{parsedConfig.tomlConfig && (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<div className="text-xs text-muted-foreground">
|
||||||
|
TOML Config:
|
||||||
|
</div>
|
||||||
|
<pre className="text-xs font-mono bg-background p-2 rounded overflow-x-auto max-h-24 whitespace-pre-wrap">
|
||||||
|
{parsedConfig.tomlConfig.substring(0, 300)}
|
||||||
|
{parsedConfig.tomlConfig.length > 300 &&
|
||||||
|
"..."}
|
||||||
|
</pre>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Gemini config */}
|
{/* Gemini config */}
|
||||||
{parsedConfig.type === "gemini" && parsedConfig.env && (
|
{parsedConfig.type === "gemini" &&
|
||||||
<div className="space-y-1.5">
|
parsedConfig.env && (
|
||||||
{Object.entries(parsedConfig.env).map(
|
<div className="space-y-1.5">
|
||||||
([key, value]) => (
|
{Object.entries(parsedConfig.env).map(
|
||||||
<div
|
([key, value]) => (
|
||||||
key={key}
|
<div
|
||||||
className="grid grid-cols-2 gap-2 text-xs"
|
key={key}
|
||||||
>
|
className="grid grid-cols-2 gap-2 text-xs"
|
||||||
<span className="font-mono text-muted-foreground truncate">
|
>
|
||||||
{key}
|
<span className="font-mono text-muted-foreground truncate">
|
||||||
</span>
|
{key}
|
||||||
<span className="font-mono truncate">
|
</span>
|
||||||
{maskValue(key, String(value))}
|
<span className="font-mono truncate">
|
||||||
</span>
|
{maskValue(key, String(value))}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
),
|
)}
|
||||||
)}
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Config URL (if remote) */}
|
||||||
|
{request.configUrl && (
|
||||||
|
<div className="grid grid-cols-3 items-center gap-4">
|
||||||
|
<div className="font-medium text-sm text-muted-foreground">
|
||||||
|
{t("deeplink.configUrl")}
|
||||||
|
</div>
|
||||||
|
<div className="col-span-2 text-sm font-mono text-muted-foreground break-all">
|
||||||
|
{request.configUrl}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Config URL (if remote) */}
|
{/* Warning */}
|
||||||
{request.configUrl && (
|
<div className="rounded-lg bg-yellow-50 dark:bg-yellow-900/20 p-3 text-sm text-yellow-800 dark:text-yellow-200">
|
||||||
<div className="grid grid-cols-3 items-center gap-4">
|
{t("deeplink.warning")}
|
||||||
<div className="font-medium text-sm text-muted-foreground">
|
</div>
|
||||||
{t("deeplink.configUrl")}
|
</>
|
||||||
</div>
|
|
||||||
<div className="col-span-2 text-sm font-mono text-muted-foreground break-all">
|
|
||||||
{request.configUrl}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Warning */}
|
|
||||||
<div className="rounded-lg bg-yellow-50 dark:bg-yellow-900/20 p-3 text-sm text-yellow-800 dark:text-yellow-200">
|
|
||||||
{t("deeplink.warning")}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
|
|||||||
@@ -32,6 +32,9 @@ export const ProviderIcon: React.FC<ProviderIconProps> = ({
|
|||||||
return {
|
return {
|
||||||
width: sizeValue,
|
width: sizeValue,
|
||||||
height: sizeValue,
|
height: sizeValue,
|
||||||
|
// 内嵌 SVG 使用 1em 作为尺寸基准,这里同步 fontSize 让图标实际跟随 size 放大
|
||||||
|
fontSize: sizeValue,
|
||||||
|
lineHeight: 1,
|
||||||
};
|
};
|
||||||
}, [size]);
|
}, [size]);
|
||||||
|
|
||||||
@@ -57,6 +60,8 @@ export const ProviderIcon: React.FC<ProviderIconProps> = ({
|
|||||||
.join("")
|
.join("")
|
||||||
.toUpperCase()
|
.toUpperCase()
|
||||||
.slice(0, 2);
|
.slice(0, 2);
|
||||||
|
const fallbackFontSize =
|
||||||
|
typeof size === "number" ? `${Math.max(size * 0.5, 12)}px` : "0.5em";
|
||||||
return (
|
return (
|
||||||
<span
|
<span
|
||||||
className={cn(
|
className={cn(
|
||||||
@@ -68,7 +73,7 @@ export const ProviderIcon: React.FC<ProviderIconProps> = ({
|
|||||||
>
|
>
|
||||||
<span
|
<span
|
||||||
style={{
|
style={{
|
||||||
fontSize: `${typeof size === "number" ? size * 0.4 : 14}px`,
|
fontSize: fallbackFontSize,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{initials}
|
{initials}
|
||||||
|
|||||||
@@ -156,13 +156,14 @@ const UsageFooter: React.FC<UsageFooterProps> = ({
|
|||||||
{t("usage.remaining")}
|
{t("usage.remaining")}
|
||||||
</span>
|
</span>
|
||||||
<span
|
<span
|
||||||
className={`font-semibold tabular-nums ${isExpired
|
className={`font-semibold tabular-nums ${
|
||||||
|
isExpired
|
||||||
? "text-red-500 dark:text-red-400"
|
? "text-red-500 dark:text-red-400"
|
||||||
: firstUsage.remaining <
|
: firstUsage.remaining <
|
||||||
(firstUsage.total || firstUsage.remaining) * 0.1
|
(firstUsage.total || firstUsage.remaining) * 0.1
|
||||||
? "text-orange-500 dark:text-orange-400"
|
? "text-orange-500 dark:text-orange-400"
|
||||||
: "text-green-600 dark:text-green-400"
|
: "text-green-600 dark:text-green-400"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{firstUsage.remaining.toFixed(2)}
|
{firstUsage.remaining.toFixed(2)}
|
||||||
</span>
|
</span>
|
||||||
@@ -310,12 +311,13 @@ const UsagePlanItem: React.FC<{ data: UsageData }> = ({ data }) => {
|
|||||||
{t("usage.remaining")}
|
{t("usage.remaining")}
|
||||||
</span>
|
</span>
|
||||||
<span
|
<span
|
||||||
className={`font-semibold tabular-nums ${isExpired
|
className={`font-semibold tabular-nums ${
|
||||||
? "text-red-500 dark:text-red-400"
|
isExpired
|
||||||
: remaining < (total || remaining) * 0.1
|
? "text-red-500 dark:text-red-400"
|
||||||
? "text-orange-500 dark:text-orange-400"
|
: remaining < (total || remaining) * 0.1
|
||||||
: "text-green-600 dark:text-green-400"
|
? "text-orange-500 dark:text-orange-400"
|
||||||
}`}
|
: "text-green-600 dark:text-green-400"
|
||||||
|
}`}
|
||||||
>
|
>
|
||||||
{remaining.toFixed(2)}
|
{remaining.toFixed(2)}
|
||||||
</span>
|
</span>
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import { useMemo } from "react";
|
||||||
|
import { DeepLinkImportRequest } from "../../lib/api/deeplink";
|
||||||
|
import { decodeBase64Utf8 } from "../../lib/utils/base64";
|
||||||
|
|
||||||
|
export function McpConfirmation({
|
||||||
|
request,
|
||||||
|
}: {
|
||||||
|
request: DeepLinkImportRequest;
|
||||||
|
}) {
|
||||||
|
const mcpServers = useMemo(() => {
|
||||||
|
if (!request.config) return null;
|
||||||
|
try {
|
||||||
|
const decoded = decodeBase64Utf8(request.config);
|
||||||
|
const parsed = JSON.parse(decoded);
|
||||||
|
return parsed.mcpServers || {};
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Failed to parse MCP config:", e);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}, [request.config]);
|
||||||
|
|
||||||
|
const targetApps = request.apps?.split(",") || [];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<h3 className="text-lg font-semibold">批量导入 MCP Servers</h3>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-muted-foreground">
|
||||||
|
目标应用
|
||||||
|
</label>
|
||||||
|
<div className="mt-1 flex gap-2 flex-wrap">
|
||||||
|
{targetApps.map((app) => (
|
||||||
|
<span
|
||||||
|
key={app}
|
||||||
|
className="px-2 py-1 bg-primary/10 text-primary text-xs rounded capitalize"
|
||||||
|
>
|
||||||
|
{app.trim()}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-muted-foreground">
|
||||||
|
MCP Servers ({Object.keys(mcpServers || {}).length} 个)
|
||||||
|
</label>
|
||||||
|
<div className="mt-1 space-y-2 max-h-64 overflow-auto border rounded p-2 bg-muted/30">
|
||||||
|
{mcpServers &&
|
||||||
|
Object.entries(mcpServers).map(([id, spec]: [string, any]) => (
|
||||||
|
<div key={id} className="p-2 bg-background rounded border">
|
||||||
|
<div className="font-semibold text-sm">{id}</div>
|
||||||
|
<div className="text-xs text-muted-foreground mt-1 font-mono truncate">
|
||||||
|
{spec.command
|
||||||
|
? `Command: ${spec.command} `
|
||||||
|
: `URL: ${spec.url} `}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{request.enabled && (
|
||||||
|
<div className="text-yellow-600 dark:text-yellow-500 text-sm flex items-center gap-2">
|
||||||
|
<span>⚠️</span>
|
||||||
|
<span>导入后将立即写入所有指定应用的配置文件</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import { useMemo } from "react";
|
||||||
|
import { DeepLinkImportRequest } from "../../lib/api/deeplink";
|
||||||
|
import { decodeBase64Utf8 } from "../../lib/utils/base64";
|
||||||
|
|
||||||
|
export function PromptConfirmation({
|
||||||
|
request,
|
||||||
|
}: {
|
||||||
|
request: DeepLinkImportRequest;
|
||||||
|
}) {
|
||||||
|
const decodedContent = useMemo(() => {
|
||||||
|
if (!request.content) return "";
|
||||||
|
return decodeBase64Utf8(request.content);
|
||||||
|
}, [request.content]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<h3 className="text-lg font-semibold">导入系统提示词</h3>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-muted-foreground">
|
||||||
|
应用
|
||||||
|
</label>
|
||||||
|
<div className="mt-1 text-sm capitalize">{request.app}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-muted-foreground">
|
||||||
|
名称
|
||||||
|
</label>
|
||||||
|
<div className="mt-1 text-sm">{request.name}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{request.description && (
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-muted-foreground">
|
||||||
|
描述
|
||||||
|
</label>
|
||||||
|
<div className="mt-1 text-sm">{request.description}</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-muted-foreground">
|
||||||
|
内容预览
|
||||||
|
</label>
|
||||||
|
<pre className="mt-1 max-h-48 overflow-auto bg-muted/50 p-2 rounded text-xs whitespace-pre-wrap border">
|
||||||
|
{decodedContent.substring(0, 500)}
|
||||||
|
{decodedContent.length > 500 && "..."}
|
||||||
|
</pre>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{request.enabled && (
|
||||||
|
<div className="text-yellow-600 dark:text-yellow-500 text-sm flex items-center gap-2">
|
||||||
|
<span>⚠️</span>
|
||||||
|
<span>导入后将立即启用此提示词,其他提示词将被禁用</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import { DeepLinkImportRequest } from "../../lib/api/deeplink";
|
||||||
|
|
||||||
|
export function SkillConfirmation({
|
||||||
|
request,
|
||||||
|
}: {
|
||||||
|
request: DeepLinkImportRequest;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<h3 className="text-lg font-semibold">添加 Claude Skill 仓库</h3>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-muted-foreground">
|
||||||
|
GitHub 仓库
|
||||||
|
</label>
|
||||||
|
<div className="mt-1 text-sm font-mono bg-muted/50 p-2 rounded border">
|
||||||
|
{request.repo}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-muted-foreground">
|
||||||
|
目标目录
|
||||||
|
</label>
|
||||||
|
<div className="mt-1 text-sm font-mono bg-muted/50 p-2 rounded border">
|
||||||
|
{request.directory}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-muted-foreground">
|
||||||
|
分支
|
||||||
|
</label>
|
||||||
|
<div className="mt-1 text-sm">{request.branch || "main"}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{request.skillsPath && (
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-muted-foreground">
|
||||||
|
Skills 路径
|
||||||
|
</label>
|
||||||
|
<div className="mt-1 text-sm">{request.skillsPath}</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="text-blue-600 dark:text-blue-400 text-sm bg-blue-50 dark:bg-blue-950/30 p-3 rounded border border-blue-200 dark:border-blue-800">
|
||||||
|
<p>ℹ️ 此操作将添加 Skill 仓库到列表。</p>
|
||||||
|
<p className="mt-1">
|
||||||
|
添加后,您可以在 Skills 管理界面中选择安装具体的 Skill。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -43,6 +43,22 @@ const PromptPanel = React.forwardRef<PromptPanelHandle, PromptPanelProps>(
|
|||||||
if (open) reload();
|
if (open) reload();
|
||||||
}, [open, reload]);
|
}, [open, reload]);
|
||||||
|
|
||||||
|
// Listen for prompt import events from deep link
|
||||||
|
useEffect(() => {
|
||||||
|
const handlePromptImported = (event: Event) => {
|
||||||
|
const customEvent = event as CustomEvent;
|
||||||
|
// Reload if the import is for this app
|
||||||
|
if (customEvent.detail?.app === appId) {
|
||||||
|
reload();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener("prompt-imported", handlePromptImported);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("prompt-imported", handlePromptImported);
|
||||||
|
};
|
||||||
|
}, [appId, reload]);
|
||||||
|
|
||||||
const handleAdd = () => {
|
const handleAdd = () => {
|
||||||
setEditingId(null);
|
setEditingId(null);
|
||||||
setIsFormOpen(true);
|
setIsFormOpen(true);
|
||||||
|
|||||||
@@ -78,6 +78,8 @@ export function EditProviderDialog({
|
|||||||
async (values: ProviderFormValues) => {
|
async (values: ProviderFormValues) => {
|
||||||
if (!provider) return;
|
if (!provider) return;
|
||||||
|
|
||||||
|
// 注意:values.settingsConfig 已经是最终的配置字符串
|
||||||
|
// ProviderForm 已经为不同的 app 类型(Claude/Codex/Gemini)正确组装了配置
|
||||||
const parsedConfig = JSON.parse(values.settingsConfig) as Record<
|
const parsedConfig = JSON.parse(values.settingsConfig) as Record<
|
||||||
string,
|
string,
|
||||||
unknown
|
unknown
|
||||||
|
|||||||
@@ -141,12 +141,12 @@ export function ProviderCard({
|
|||||||
</button>
|
</button>
|
||||||
|
|
||||||
{/* 供应商图标 */}
|
{/* 供应商图标 */}
|
||||||
<div className="h-9 w-9 rounded-lg bg-white/5 flex items-center justify-center border border-gray-200 dark:border-white/10 group-hover:scale-105 transition-transform duration-300">
|
<div className="h-8 w-8 rounded-lg bg-white/5 flex items-center justify-center border border-gray-200 dark:border-white/10 group-hover:scale-105 transition-transform duration-300">
|
||||||
<ProviderIcon
|
<ProviderIcon
|
||||||
icon={provider.icon}
|
icon={provider.icon}
|
||||||
name={provider.name}
|
name={provider.name}
|
||||||
color={provider.iconColor}
|
color={provider.iconColor}
|
||||||
size={26}
|
size={20}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -84,7 +84,7 @@ export function BasicFormFields({ form }: BasicFormFieldsProps) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex-1 overflow-y-auto">
|
<div className="flex-1 overflow-y-auto">
|
||||||
<div className="space-y-6 mx-auto max-w-[56rem] px-6 py-6 w-full">
|
<div className="space-y-2 mx-auto max-w-[56rem] px-6 py-6 w-full">
|
||||||
<IconPicker
|
<IconPicker
|
||||||
value={currentIcon}
|
value={currentIcon}
|
||||||
onValueChange={handleIconSelect}
|
onValueChange={handleIconSelect}
|
||||||
|
|||||||
@@ -1,7 +1,21 @@
|
|||||||
import { useState, useEffect, forwardRef, useImperativeHandle } from "react";
|
import {
|
||||||
|
useState,
|
||||||
|
useEffect,
|
||||||
|
useMemo,
|
||||||
|
forwardRef,
|
||||||
|
useImperativeHandle,
|
||||||
|
} from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { RefreshCw } from "lucide-react";
|
import { Input } from "@/components/ui/input";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
import { RefreshCw, Search } from "lucide-react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { SkillCard } from "./SkillCard";
|
import { SkillCard } from "./SkillCard";
|
||||||
import { RepoManagerPanel } from "./RepoManagerPanel";
|
import { RepoManagerPanel } from "./RepoManagerPanel";
|
||||||
@@ -24,6 +38,10 @@ export const SkillsPage = forwardRef<SkillsPageHandle, SkillsPageProps>(
|
|||||||
const [repos, setRepos] = useState<SkillRepo[]>([]);
|
const [repos, setRepos] = useState<SkillRepo[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [repoManagerOpen, setRepoManagerOpen] = useState(false);
|
const [repoManagerOpen, setRepoManagerOpen] = useState(false);
|
||||||
|
const [searchQuery, setSearchQuery] = useState("");
|
||||||
|
const [filterStatus, setFilterStatus] = useState<
|
||||||
|
"all" | "installed" | "uninstalled"
|
||||||
|
>("all");
|
||||||
|
|
||||||
const loadSkills = async (afterLoad?: (data: Skill[]) => void) => {
|
const loadSkills = async (afterLoad?: (data: Skill[]) => void) => {
|
||||||
try {
|
try {
|
||||||
@@ -111,12 +129,12 @@ export const SkillsPage = forwardRef<SkillsPageHandle, SkillsPageProps>(
|
|||||||
const errorMessage =
|
const errorMessage =
|
||||||
error instanceof Error ? error.message : String(error);
|
error instanceof Error ? error.message : String(error);
|
||||||
|
|
||||||
// 使用错误解析器格式化错误,传入 "skills.uninstallFailed"
|
// 使用错误解析器格式化错误,传入 "skills.uninstallFailed"
|
||||||
const { title, description } = formatSkillError(
|
const { title, description } = formatSkillError(
|
||||||
errorMessage,
|
errorMessage,
|
||||||
t,
|
t,
|
||||||
"skills.uninstallFailed",
|
"skills.uninstallFailed",
|
||||||
);
|
);
|
||||||
|
|
||||||
toast.error(title, {
|
toast.error(title, {
|
||||||
description,
|
description,
|
||||||
@@ -162,6 +180,30 @@ export const SkillsPage = forwardRef<SkillsPageHandle, SkillsPageProps>(
|
|||||||
await Promise.all([loadRepos(), loadSkills()]);
|
await Promise.all([loadRepos(), loadSkills()]);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 过滤技能列表
|
||||||
|
const filteredSkills = useMemo(() => {
|
||||||
|
const byStatus = skills.filter((skill) => {
|
||||||
|
if (filterStatus === "installed") return skill.installed;
|
||||||
|
if (filterStatus === "uninstalled") return !skill.installed;
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!searchQuery.trim()) return byStatus;
|
||||||
|
|
||||||
|
const query = searchQuery.toLowerCase();
|
||||||
|
return byStatus.filter((skill) => {
|
||||||
|
const name = skill.name?.toLowerCase() || "";
|
||||||
|
const description = skill.description?.toLowerCase() || "";
|
||||||
|
const directory = skill.directory?.toLowerCase() || "";
|
||||||
|
|
||||||
|
return (
|
||||||
|
name.includes(query) ||
|
||||||
|
description.includes(query) ||
|
||||||
|
directory.includes(query)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}, [skills, searchQuery, filterStatus]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col h-full min-h-0 bg-background/50">
|
<div className="flex flex-col h-full min-h-0 bg-background/50">
|
||||||
{/* 顶部操作栏(固定区域)已移除,由 App.tsx 接管 */}
|
{/* 顶部操作栏(固定区域)已移除,由 App.tsx 接管 */}
|
||||||
@@ -190,16 +232,86 @@ export const SkillsPage = forwardRef<SkillsPageHandle, SkillsPageProps>(
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
<>
|
||||||
{skills.map((skill) => (
|
{/* 搜索框 */}
|
||||||
<SkillCard
|
<div className="mb-6 flex flex-col gap-3 md:flex-row md:items-center">
|
||||||
key={skill.key}
|
<div className="relative flex-1 min-w-0">
|
||||||
skill={skill}
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||||
onInstall={handleInstall}
|
<Input
|
||||||
onUninstall={handleUninstall}
|
type="text"
|
||||||
/>
|
placeholder={t("skills.searchPlaceholder")}
|
||||||
))}
|
value={searchQuery}
|
||||||
</div>
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
|
className="pl-9 pr-3"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="w-full md:w-48">
|
||||||
|
<Select
|
||||||
|
value={filterStatus}
|
||||||
|
onValueChange={(val) =>
|
||||||
|
setFilterStatus(
|
||||||
|
val as "all" | "installed" | "uninstalled",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<SelectTrigger className="bg-card border shadow-sm text-foreground">
|
||||||
|
<SelectValue
|
||||||
|
placeholder={t("skills.filter.placeholder")}
|
||||||
|
className="text-left"
|
||||||
|
/>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent className="bg-card text-foreground shadow-lg">
|
||||||
|
<SelectItem
|
||||||
|
value="all"
|
||||||
|
className="text-left pr-3 [&[data-state=checked]>span]:hidden"
|
||||||
|
>
|
||||||
|
{t("skills.filter.all")}
|
||||||
|
</SelectItem>
|
||||||
|
<SelectItem
|
||||||
|
value="installed"
|
||||||
|
className="text-left pr-3 [&[data-state=checked]>span]:hidden"
|
||||||
|
>
|
||||||
|
{t("skills.filter.installed")}
|
||||||
|
</SelectItem>
|
||||||
|
<SelectItem
|
||||||
|
value="uninstalled"
|
||||||
|
className="text-left pr-3 [&[data-state=checked]>span]:hidden"
|
||||||
|
>
|
||||||
|
{t("skills.filter.uninstalled")}
|
||||||
|
</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
{searchQuery && (
|
||||||
|
<p className="mt-2 text-sm text-muted-foreground">
|
||||||
|
{t("skills.count", { count: filteredSkills.length })}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 技能列表或无结果提示 */}
|
||||||
|
{filteredSkills.length === 0 ? (
|
||||||
|
<div className="flex flex-col items-center justify-center h-48 text-center">
|
||||||
|
<p className="text-lg font-medium text-gray-900 dark:text-gray-100">
|
||||||
|
{t("skills.noResults")}
|
||||||
|
</p>
|
||||||
|
<p className="mt-2 text-sm text-gray-500 dark:text-gray-400">
|
||||||
|
{t("skills.emptyDescription")}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||||
|
{filteredSkills.map((skill) => (
|
||||||
|
<SkillCard
|
||||||
|
key={skill.key}
|
||||||
|
skill={skill}
|
||||||
|
onInstall={handleInstall}
|
||||||
|
onUninstall={handleUninstall}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -78,7 +78,7 @@ export function useImportExport(
|
|||||||
if (!selectedFile) {
|
if (!selectedFile) {
|
||||||
toast.error(
|
toast.error(
|
||||||
t("settings.selectFileFailed", {
|
t("settings.selectFileFailed", {
|
||||||
defaultValue: "请选择有效的配置文件",
|
defaultValue: "请选择有效的 SQL 备份文件",
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
@@ -97,7 +97,7 @@ export function useImportExport(
|
|||||||
const message =
|
const message =
|
||||||
result.message ||
|
result.message ||
|
||||||
t("settings.configCorrupted", {
|
t("settings.configCorrupted", {
|
||||||
defaultValue: "配置文件已损坏或格式不正确",
|
defaultValue: "SQL 文件已损坏或格式不正确",
|
||||||
});
|
});
|
||||||
setErrorMessage(message);
|
setErrorMessage(message);
|
||||||
toast.error(message);
|
toast.error(message);
|
||||||
@@ -150,14 +150,14 @@ export function useImportExport(
|
|||||||
|
|
||||||
const exportConfig = useCallback(async () => {
|
const exportConfig = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
const defaultName = `cc-switch-config-${
|
const now = new Date();
|
||||||
new Date().toISOString().split("T")[0]
|
const stamp = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, "0")}${String(now.getDate()).padStart(2, "0")}_${String(now.getHours()).padStart(2, "0")}${String(now.getMinutes()).padStart(2, "0")}${String(now.getSeconds()).padStart(2, "0")}`;
|
||||||
}.json`;
|
const defaultName = `cc-switch-export-${stamp}.sql`;
|
||||||
const destination = await settingsApi.saveFileDialog(defaultName);
|
const destination = await settingsApi.saveFileDialog(defaultName);
|
||||||
if (!destination) {
|
if (!destination) {
|
||||||
toast.error(
|
toast.error(
|
||||||
t("settings.selectFileFailed", {
|
t("settings.selectFileFailed", {
|
||||||
defaultValue: "选择保存位置失败",
|
defaultValue: "请选择 SQL 备份保存路径",
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -145,10 +145,10 @@
|
|||||||
"themeLight": "Light",
|
"themeLight": "Light",
|
||||||
"themeDark": "Dark",
|
"themeDark": "Dark",
|
||||||
"themeSystem": "System",
|
"themeSystem": "System",
|
||||||
"importExport": "Import/Export Config",
|
"importExport": "SQL Import/Export",
|
||||||
"importExportHint": "Import or export CC Switch configuration for backup or migration.",
|
"importExportHint": "Import or export database SQL backups for migration or restore.",
|
||||||
"exportConfig": "Export Config to File",
|
"exportConfig": "Export SQL Backup",
|
||||||
"selectConfigFile": "Select Config File",
|
"selectConfigFile": "Select SQL File",
|
||||||
"noFileSelected": "No configuration file selected.",
|
"noFileSelected": "No configuration file selected.",
|
||||||
"import": "Import",
|
"import": "Import",
|
||||||
"importing": "Importing...",
|
"importing": "Importing...",
|
||||||
@@ -159,8 +159,8 @@
|
|||||||
"importPartialHint": "Please manually reselect the provider to refresh the live configuration.",
|
"importPartialHint": "Please manually reselect the provider to refresh the live configuration.",
|
||||||
"configExported": "Config exported to:",
|
"configExported": "Config exported to:",
|
||||||
"exportFailed": "Export failed",
|
"exportFailed": "Export failed",
|
||||||
"selectFileFailed": "Failed to select file",
|
"selectFileFailed": "Please choose a valid SQL backup file",
|
||||||
"configCorrupted": "Config file may be corrupted or invalid",
|
"configCorrupted": "SQL file may be corrupted or invalid",
|
||||||
"backupId": "Backup ID",
|
"backupId": "Backup ID",
|
||||||
"autoReload": "Data will refresh automatically in 2 seconds...",
|
"autoReload": "Data will refresh automatically in 2 seconds...",
|
||||||
"languageOptionChinese": "中文",
|
"languageOptionChinese": "中文",
|
||||||
@@ -735,7 +735,16 @@
|
|||||||
"removeSuccess": "Repository {{owner}}/{{name}} removed",
|
"removeSuccess": "Repository {{owner}}/{{name}} removed",
|
||||||
"removeFailed": "Failed to remove",
|
"removeFailed": "Failed to remove",
|
||||||
"skillCount": "{{count}} skills detected"
|
"skillCount": "{{count}} skills detected"
|
||||||
}
|
},
|
||||||
|
"search": "Search Skills",
|
||||||
|
"searchPlaceholder": "Search skill name or description...",
|
||||||
|
"filter": {
|
||||||
|
"placeholder": "Filter by status",
|
||||||
|
"all": "All",
|
||||||
|
"installed": "Installed",
|
||||||
|
"uninstalled": "Not installed"
|
||||||
|
},
|
||||||
|
"noResults": "No matching skills found"
|
||||||
},
|
},
|
||||||
"deeplink": {
|
"deeplink": {
|
||||||
"confirmImport": "Confirm Import Provider",
|
"confirmImport": "Confirm Import Provider",
|
||||||
@@ -745,7 +754,12 @@
|
|||||||
"homepage": "Homepage",
|
"homepage": "Homepage",
|
||||||
"endpoint": "API Endpoint",
|
"endpoint": "API Endpoint",
|
||||||
"apiKey": "API Key",
|
"apiKey": "API Key",
|
||||||
|
"icon": "Icon",
|
||||||
"model": "Model",
|
"model": "Model",
|
||||||
|
"haikuModel": "Haiku Model",
|
||||||
|
"sonnetModel": "Sonnet Model",
|
||||||
|
"opusModel": "Opus Model",
|
||||||
|
"multiModel": "Multi-Modal Model",
|
||||||
"notes": "Notes",
|
"notes": "Notes",
|
||||||
"import": "Import",
|
"import": "Import",
|
||||||
"importing": "Importing...",
|
"importing": "Importing...",
|
||||||
|
|||||||
@@ -145,10 +145,10 @@
|
|||||||
"themeLight": "浅色",
|
"themeLight": "浅色",
|
||||||
"themeDark": "深色",
|
"themeDark": "深色",
|
||||||
"themeSystem": "跟随系统",
|
"themeSystem": "跟随系统",
|
||||||
"importExport": "导入导出配置",
|
"importExport": "SQL 导入导出",
|
||||||
"importExportHint": "导入导出 CC Switch 配置,便于备份或迁移。",
|
"importExportHint": "导入/导出数据库 SQL 备份,便于备份或迁移。",
|
||||||
"exportConfig": "导出配置到文件",
|
"exportConfig": "导出 SQL 备份",
|
||||||
"selectConfigFile": "选择配置文件",
|
"selectConfigFile": "选择 SQL 文件",
|
||||||
"noFileSelected": "尚未选择配置文件。",
|
"noFileSelected": "尚未选择配置文件。",
|
||||||
"import": "导入",
|
"import": "导入",
|
||||||
"importing": "导入中...",
|
"importing": "导入中...",
|
||||||
@@ -159,8 +159,8 @@
|
|||||||
"importPartialHint": "请手动重新选择一次供应商以刷新对应配置。",
|
"importPartialHint": "请手动重新选择一次供应商以刷新对应配置。",
|
||||||
"configExported": "配置已导出到:",
|
"configExported": "配置已导出到:",
|
||||||
"exportFailed": "导出失败",
|
"exportFailed": "导出失败",
|
||||||
"selectFileFailed": "选择文件失败",
|
"selectFileFailed": "请选择有效的 SQL 备份文件",
|
||||||
"configCorrupted": "配置文件可能已损坏或格式不正确",
|
"configCorrupted": "SQL 文件可能已损坏或格式不正确",
|
||||||
"backupId": "备份ID",
|
"backupId": "备份ID",
|
||||||
"autoReload": "数据将在2秒后自动刷新...",
|
"autoReload": "数据将在2秒后自动刷新...",
|
||||||
"languageOptionChinese": "中文",
|
"languageOptionChinese": "中文",
|
||||||
@@ -735,7 +735,16 @@
|
|||||||
"removeSuccess": "仓库 {{owner}}/{{name}} 已删除",
|
"removeSuccess": "仓库 {{owner}}/{{name}} 已删除",
|
||||||
"removeFailed": "删除失败",
|
"removeFailed": "删除失败",
|
||||||
"skillCount": "识别到 {{count}} 个技能"
|
"skillCount": "识别到 {{count}} 个技能"
|
||||||
}
|
},
|
||||||
|
"search": "搜索技能",
|
||||||
|
"searchPlaceholder": "搜索技能名称或描述...",
|
||||||
|
"filter": {
|
||||||
|
"placeholder": "状态筛选",
|
||||||
|
"all": "全部",
|
||||||
|
"installed": "已安装",
|
||||||
|
"uninstalled": "未安装"
|
||||||
|
},
|
||||||
|
"noResults": "未找到匹配的技能"
|
||||||
},
|
},
|
||||||
"deeplink": {
|
"deeplink": {
|
||||||
"confirmImport": "确认导入供应商配置",
|
"confirmImport": "确认导入供应商配置",
|
||||||
@@ -745,7 +754,12 @@
|
|||||||
"homepage": "官网地址",
|
"homepage": "官网地址",
|
||||||
"endpoint": "API 端点",
|
"endpoint": "API 端点",
|
||||||
"apiKey": "API 密钥",
|
"apiKey": "API 密钥",
|
||||||
|
"icon": "图标",
|
||||||
"model": "模型",
|
"model": "模型",
|
||||||
|
"haikuModel": "Haiku 模型",
|
||||||
|
"sonnetModel": "Sonnet 模型",
|
||||||
|
"opusModel": "Opus 模型",
|
||||||
|
"multiModel": "多模态模型",
|
||||||
"notes": "备注",
|
"notes": "备注",
|
||||||
"import": "导入",
|
"import": "导入",
|
||||||
"importing": "导入中...",
|
"importing": "导入中...",
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -219,6 +219,13 @@ export const iconMetadata: Record<string, IconMetadata> = {
|
|||||||
keywords: ["gpt", "chatgpt"],
|
keywords: ["gpt", "chatgpt"],
|
||||||
defaultColor: "#00A67E",
|
defaultColor: "#00A67E",
|
||||||
},
|
},
|
||||||
|
packycode: {
|
||||||
|
name: "packycode",
|
||||||
|
displayName: "PackyCode",
|
||||||
|
category: "ai-provider",
|
||||||
|
keywords: ["packycode", "packy", "packyapi"],
|
||||||
|
defaultColor: "currentColor",
|
||||||
|
},
|
||||||
palm: {
|
palm: {
|
||||||
name: "palm",
|
name: "palm",
|
||||||
displayName: "palm",
|
displayName: "palm",
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 5.3 KiB |
+56
-15
@@ -1,25 +1,66 @@
|
|||||||
import { invoke } from "@tauri-apps/api/core";
|
import { invoke } from "@tauri-apps/api/core";
|
||||||
|
|
||||||
|
export type ResourceType = "provider" | "prompt" | "mcp" | "skill";
|
||||||
|
|
||||||
export interface DeepLinkImportRequest {
|
export interface DeepLinkImportRequest {
|
||||||
version: string;
|
version: string;
|
||||||
resource: string;
|
resource: ResourceType;
|
||||||
app: "claude" | "codex" | "gemini";
|
|
||||||
name: string;
|
// Common fields
|
||||||
homepage: string;
|
app?: "claude" | "codex" | "gemini";
|
||||||
endpoint: string;
|
name?: string;
|
||||||
apiKey: string;
|
enabled?: boolean;
|
||||||
|
|
||||||
|
// Provider fields
|
||||||
|
homepage?: string;
|
||||||
|
endpoint?: string;
|
||||||
|
apiKey?: string;
|
||||||
|
icon?: string;
|
||||||
model?: string;
|
model?: string;
|
||||||
notes?: string;
|
notes?: string;
|
||||||
// Claude 专用模型字段 (v3.7.1+)
|
|
||||||
haikuModel?: string;
|
haikuModel?: string;
|
||||||
sonnetModel?: string;
|
sonnetModel?: string;
|
||||||
opusModel?: string;
|
opusModel?: string;
|
||||||
// 配置文件导入字段 (v3.8+)
|
|
||||||
config?: string; // Base64 编码的配置内容
|
// Prompt fields
|
||||||
configFormat?: string; // json/toml
|
content?: string;
|
||||||
configUrl?: string; // 远程配置 URL
|
description?: string;
|
||||||
|
|
||||||
|
// MCP fields
|
||||||
|
apps?: string; // "claude,codex,gemini"
|
||||||
|
|
||||||
|
// Skill fields
|
||||||
|
repo?: string;
|
||||||
|
directory?: string;
|
||||||
|
branch?: string;
|
||||||
|
skillsPath?: string;
|
||||||
|
|
||||||
|
// Config file fields
|
||||||
|
config?: string;
|
||||||
|
configFormat?: string;
|
||||||
|
configUrl?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface McpImportResult {
|
||||||
|
importedCount: number;
|
||||||
|
importedIds: string[];
|
||||||
|
failed: Array<{
|
||||||
|
id: string;
|
||||||
|
error: string;
|
||||||
|
}>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ImportResult =
|
||||||
|
| { type: "provider"; id: string }
|
||||||
|
| { type: "prompt"; id: string }
|
||||||
|
| {
|
||||||
|
type: "mcp";
|
||||||
|
importedCount: number;
|
||||||
|
importedIds: string[];
|
||||||
|
failed: Array<{ id: string; error: string }>;
|
||||||
|
}
|
||||||
|
| { type: "skill"; key: string };
|
||||||
|
|
||||||
export const deeplinkApi = {
|
export const deeplinkApi = {
|
||||||
/**
|
/**
|
||||||
* Parse a deep link URL
|
* Parse a deep link URL
|
||||||
@@ -43,13 +84,13 @@ export const deeplinkApi = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Import a provider from a deep link request
|
* Import a resource from a deep link request (unified handler)
|
||||||
* @param request The deep link import request
|
* @param request The deep link import request
|
||||||
* @returns The ID of the imported provider
|
* @returns Import result based on resource type
|
||||||
*/
|
*/
|
||||||
importFromDeeplink: async (
|
importFromDeeplink: async (
|
||||||
request: DeepLinkImportRequest,
|
request: DeepLinkImportRequest,
|
||||||
): Promise<string> => {
|
): Promise<ImportResult> => {
|
||||||
return invoke("import_from_deeplink", { request });
|
return invoke("import_from_deeplink_unified", { request });
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
/**
|
||||||
|
* Decode Base64 encoded UTF-8 string
|
||||||
|
*
|
||||||
|
* This function handles various Base64 edge cases that can occur when
|
||||||
|
* Base64 strings are passed through URLs:
|
||||||
|
* - Spaces (URL parsing may convert '+' to space)
|
||||||
|
* - Missing padding ('=' characters)
|
||||||
|
* - Different Base64 variants
|
||||||
|
*
|
||||||
|
* @param str - Base64 encoded string
|
||||||
|
* @returns Decoded UTF-8 string
|
||||||
|
*/
|
||||||
|
export function decodeBase64Utf8(str: string): string {
|
||||||
|
try {
|
||||||
|
// Clean up the input: replace spaces with + (URL parsing may convert + to space)
|
||||||
|
let cleaned = str.trim().replace(/ /g, "+");
|
||||||
|
|
||||||
|
// Try to decode with standard Base64 first
|
||||||
|
try {
|
||||||
|
const binString = atob(cleaned);
|
||||||
|
const bytes = Uint8Array.from(binString, (m) => m.codePointAt(0)!);
|
||||||
|
return new TextDecoder("utf-8", { fatal: false }).decode(bytes);
|
||||||
|
} catch (e1) {
|
||||||
|
// If standard fails, try adding padding
|
||||||
|
const remainder = cleaned.length % 4;
|
||||||
|
if (remainder !== 0) {
|
||||||
|
cleaned += "=".repeat(4 - remainder);
|
||||||
|
}
|
||||||
|
const binString = atob(cleaned);
|
||||||
|
const bytes = Uint8Array.from(binString, (m) => m.codePointAt(0)!);
|
||||||
|
return new TextDecoder("utf-8", { fatal: false }).decode(bytes);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Base64 decode error:", e, "Input:", str);
|
||||||
|
// Last resort fallback using deprecated but sometimes working method
|
||||||
|
try {
|
||||||
|
return decodeURIComponent(escape(atob(str.replace(/ /g, "+"))));
|
||||||
|
} catch {
|
||||||
|
// If all else fails, return original string
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user