mirror of
https://github.com/farion1231/cc-switch.git
synced 2026-07-25 21:54:58 +08:00
Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2af8c82977 | |||
| d4286ab90a | |||
| f7c6947220 | |||
| 8fccc2a286 |
@@ -5,64 +5,6 @@ All notable changes to CC Switch will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [3.9.0-3] - 2025-12-29
|
||||
|
||||
### Beta Release
|
||||
|
||||
Third beta release with important bug fixes for Windows compatibility, UI improvements, and new features.
|
||||
|
||||
### Added
|
||||
|
||||
- **Universal Provider** - Support for universal provider configurations (#348)
|
||||
- **Provider Search Filter** - Quick filter to find providers by name (#435)
|
||||
- **Keyboard Shortcut** - Open settings with Command+comma / Ctrl+comma (#436)
|
||||
- **Xiaomi MiMo Icon** - Added MiMo icon and Claude provider configuration (#470)
|
||||
- **Usage Model Extraction** - Extract model info from usage statistics (#455)
|
||||
- **Skip First-Run Confirmation** - Option to skip Claude Code first-run confirmation dialog
|
||||
- **Exit Animations** - Added exit animation to FullScreenPanel dialogs
|
||||
- **Fade Transitions** - Smooth fade transitions for app/view/panel switching
|
||||
|
||||
### Fixed
|
||||
|
||||
#### Windows
|
||||
- Wrap npx/npm commands with `cmd /c` for MCP export
|
||||
- Prevent terminal windows from appearing during version check
|
||||
|
||||
#### macOS
|
||||
- Use .app bundle path for autostart to prevent terminal window popup
|
||||
|
||||
#### UI
|
||||
- Resolve Dialog/Modal not opening on first click (#492)
|
||||
- Improve dark mode text contrast for form labels
|
||||
- Reduce header spacing and fix layout shift on view switch
|
||||
- Prevent header layout shift when switching views
|
||||
|
||||
#### Database & Schema
|
||||
- Add missing base columns migration for proxy_config
|
||||
- Add backward compatibility check for proxy_config seed insert
|
||||
|
||||
#### Other
|
||||
- Use local timezone and robust DST handling in usage stats (#500)
|
||||
- Remove deprecated `sync_enabled_to_codex` call
|
||||
- Gracefully handle invalid Codex config.toml during MCP sync
|
||||
- Add missing translations for reasoning model and OpenRouter compat mode
|
||||
|
||||
### Improved
|
||||
|
||||
- **macOS Tray** - Use macOS tray template icon
|
||||
- **Header Alignment** - Remove macOS titlebar tint, align custom header
|
||||
- **Shadow Removal** - Cleaner UI by removing shadow styles
|
||||
- **Code Inspector** - Added code-inspector-plugin for development
|
||||
- **i18n** - Complete internationalization for usage panel and settings
|
||||
- **Sponsor Logos** - Made sponsor logos clickable
|
||||
|
||||
### Stats
|
||||
|
||||
- 35 commits since v3.9.0-2
|
||||
- 5 files changed in test/lint fixes
|
||||
|
||||
---
|
||||
|
||||
## [3.9.0-1] - 2025-12-18
|
||||
|
||||
### Beta Release
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cc-switch",
|
||||
"version": "3.9.0-3",
|
||||
"version": "3.9.0-2",
|
||||
"description": "All-in-One Assistant for Claude Code, Codex & Gemini CLI",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
Generated
+1
-1
@@ -701,7 +701,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cc-switch"
|
||||
version = "3.9.0-3"
|
||||
version = "3.9.0-2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-stream",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "cc-switch"
|
||||
version = "3.9.0-3"
|
||||
version = "3.9.0-2"
|
||||
description = "All-in-One Assistant for Claude Code, Codex & Gemini CLI"
|
||||
authors = ["Jason Young"]
|
||||
license = "MIT"
|
||||
|
||||
@@ -7,64 +7,6 @@ use std::path::{Path, PathBuf};
|
||||
use crate::config::{atomic_write, get_claude_mcp_path, get_default_claude_mcp_path};
|
||||
use crate::error::AppError;
|
||||
|
||||
/// 需要在 Windows 上用 cmd /c 包装的命令
|
||||
/// 这些命令在 Windows 上实际是 .cmd 批处理文件,需要通过 cmd /c 来执行
|
||||
#[cfg(windows)]
|
||||
const WINDOWS_WRAP_COMMANDS: &[&str] = &["npx", "npm", "yarn", "pnpm", "node", "bun", "deno"];
|
||||
|
||||
/// Windows 平台:将 `npx args...` 转换为 `cmd /c npx args...`
|
||||
/// 解决 Claude Code /doctor 报告的 "Windows requires 'cmd /c' wrapper to execute npx" 警告
|
||||
#[cfg(windows)]
|
||||
fn wrap_command_for_windows(obj: &mut Map<String, Value>) {
|
||||
// 只处理 stdio 类型(默认或显式)
|
||||
let server_type = obj.get("type").and_then(|v| v.as_str()).unwrap_or("stdio");
|
||||
if server_type != "stdio" {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(cmd) = obj.get("command").and_then(|v| v.as_str()) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// 已经是 cmd 的不重复包装
|
||||
if cmd.eq_ignore_ascii_case("cmd") || cmd.eq_ignore_ascii_case("cmd.exe") {
|
||||
return;
|
||||
}
|
||||
|
||||
// 提取命令名(去掉 .cmd 后缀和路径)
|
||||
let cmd_name = Path::new(cmd)
|
||||
.file_stem()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or(cmd);
|
||||
|
||||
let needs_wrap = WINDOWS_WRAP_COMMANDS
|
||||
.iter()
|
||||
.any(|&c| cmd_name.eq_ignore_ascii_case(c));
|
||||
|
||||
if !needs_wrap {
|
||||
return;
|
||||
}
|
||||
|
||||
// 构建新的 args: ["/c", "原命令", ...原args]
|
||||
let original_args = obj
|
||||
.get("args")
|
||||
.and_then(|v| v.as_array())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
let mut new_args = vec![Value::String("/c".into()), Value::String(cmd.into())];
|
||||
new_args.extend(original_args);
|
||||
|
||||
obj.insert("command".into(), Value::String("cmd".into()));
|
||||
obj.insert("args".into(), Value::Array(new_args));
|
||||
}
|
||||
|
||||
/// 非 Windows 平台无需处理
|
||||
#[cfg(not(windows))]
|
||||
fn wrap_command_for_windows(_obj: &mut Map<String, Value>) {
|
||||
// 非 Windows 平台不做任何处理
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct McpStatus {
|
||||
@@ -397,9 +339,6 @@ pub fn set_mcp_servers_map(
|
||||
obj.remove("homepage");
|
||||
obj.remove("docs");
|
||||
|
||||
// Windows 平台自动包装 npx/npm 等命令为 cmd /c 格式
|
||||
wrap_command_for_windows(&mut obj);
|
||||
|
||||
out.insert(id.clone(), Value::Object(obj));
|
||||
}
|
||||
|
||||
@@ -413,136 +352,3 @@ pub fn set_mcp_servers_map(
|
||||
write_json_value(&path, &root)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
/// 测试 Windows 命令包装功能
|
||||
/// 由于使用条件编译,在非 Windows 平台上测试的是空函数
|
||||
#[test]
|
||||
fn test_wrap_command_for_windows_npx() {
|
||||
let mut obj = json!({"command": "npx", "args": ["-y", "@upstash/context7-mcp"]})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone();
|
||||
wrap_command_for_windows(&mut obj);
|
||||
|
||||
#[cfg(windows)]
|
||||
{
|
||||
assert_eq!(obj["command"], "cmd");
|
||||
assert_eq!(
|
||||
obj["args"],
|
||||
json!(["/c", "npx", "-y", "@upstash/context7-mcp"])
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
// 非 Windows 平台不做任何处理
|
||||
assert_eq!(obj["command"], "npx");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wrap_command_for_windows_npm() {
|
||||
let mut obj = json!({"command": "npm", "args": ["run", "start"]})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone();
|
||||
wrap_command_for_windows(&mut obj);
|
||||
|
||||
#[cfg(windows)]
|
||||
{
|
||||
assert_eq!(obj["command"], "cmd");
|
||||
assert_eq!(obj["args"], json!(["/c", "npm", "run", "start"]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wrap_command_for_windows_already_cmd() {
|
||||
// 已经是 cmd 的不应该重复包装
|
||||
let mut obj = json!({"command": "cmd", "args": ["/c", "npx", "-y", "foo"]})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone();
|
||||
wrap_command_for_windows(&mut obj);
|
||||
|
||||
assert_eq!(obj["command"], "cmd");
|
||||
// args 应该保持不变,不会变成 ["/c", "cmd", "/c", "npx", ...]
|
||||
assert_eq!(obj["args"], json!(["/c", "npx", "-y", "foo"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wrap_command_for_windows_http_type_skipped() {
|
||||
// http 类型不应该被处理
|
||||
let mut obj = json!({"type": "http", "url": "https://example.com/mcp"})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone();
|
||||
wrap_command_for_windows(&mut obj);
|
||||
|
||||
assert!(!obj.contains_key("command"));
|
||||
assert_eq!(obj["url"], "https://example.com/mcp");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wrap_command_for_windows_other_command_skipped() {
|
||||
// 非目标命令(如 python)不应该被包装
|
||||
let mut obj = json!({"command": "python", "args": ["server.py"]})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone();
|
||||
wrap_command_for_windows(&mut obj);
|
||||
|
||||
// python 不在 WINDOWS_WRAP_COMMANDS 列表中,不应该被包装
|
||||
assert_eq!(obj["command"], "python");
|
||||
assert_eq!(obj["args"], json!(["server.py"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wrap_command_for_windows_no_args() {
|
||||
// 没有 args 的情况
|
||||
let mut obj = json!({"command": "npx"}).as_object().unwrap().clone();
|
||||
wrap_command_for_windows(&mut obj);
|
||||
|
||||
#[cfg(windows)]
|
||||
{
|
||||
assert_eq!(obj["command"], "cmd");
|
||||
assert_eq!(obj["args"], json!(["/c", "npx"]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wrap_command_for_windows_with_cmd_suffix() {
|
||||
// 处理 npx.cmd 格式
|
||||
let mut obj = json!({"command": "npx.cmd", "args": ["-y", "foo"]})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone();
|
||||
wrap_command_for_windows(&mut obj);
|
||||
|
||||
#[cfg(windows)]
|
||||
{
|
||||
assert_eq!(obj["command"], "cmd");
|
||||
assert_eq!(obj["args"], json!(["/c", "npx.cmd", "-y", "foo"]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wrap_command_for_windows_case_insensitive() {
|
||||
// 大小写不敏感
|
||||
let mut obj = json!({"command": "NPX", "args": ["-y", "foo"]})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone();
|
||||
wrap_command_for_windows(&mut obj);
|
||||
|
||||
#[cfg(windows)]
|
||||
{
|
||||
assert_eq!(obj["command"], "cmd");
|
||||
assert_eq!(obj["args"], json!(["/c", "NPX", "-y", "foo"]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -248,18 +248,12 @@ fn scan_cli_version(tool: &str) -> (Option<String>, Option<String>) {
|
||||
if tool_path.exists() {
|
||||
// 构建 PATH 环境变量,确保 node 可被找到
|
||||
let current_path = std::env::var("PATH").unwrap_or_default();
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
let new_path = format!("{};{}", path.display(), current_path);
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
let new_path = format!("{}:{}", path.display(), current_path);
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
let output = {
|
||||
// 使用 cmd /C 包装执行,确保子进程也在隐藏的控制台中运行
|
||||
Command::new("cmd")
|
||||
.args(["/C", &format!("\"{}\" --version", tool_path.display())])
|
||||
Command::new(&tool_path)
|
||||
.arg("--version")
|
||||
.env("PATH", &new_path)
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.output()
|
||||
|
||||
@@ -53,6 +53,7 @@ const LEGACY_SCHEMA_SQL: &str = r#"
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ColumnInfo {
|
||||
name: String,
|
||||
r#type: String,
|
||||
notnull: i64,
|
||||
default: Option<String>,
|
||||
@@ -64,9 +65,10 @@ fn get_column_info(conn: &Connection, table: &str, column: &str) -> ColumnInfo {
|
||||
.expect("prepare pragma");
|
||||
let mut rows = stmt.query([]).expect("query pragma");
|
||||
while let Some(row) = rows.next().expect("read row") {
|
||||
let column_name: String = row.get(1).expect("name");
|
||||
if column_name.eq_ignore_ascii_case(column) {
|
||||
let name: String = row.get(1).expect("name");
|
||||
if name.eq_ignore_ascii_case(column) {
|
||||
return ColumnInfo {
|
||||
name,
|
||||
r#type: row.get::<_, String>(2).expect("type"),
|
||||
notnull: row.get::<_, i64>(3).expect("notnull"),
|
||||
default: row.get::<_, Option<String>>(4).ok().flatten(),
|
||||
@@ -294,10 +296,9 @@ fn dry_run_validates_schema_compatibility() {
|
||||
},
|
||||
);
|
||||
|
||||
let manager = ProviderManager {
|
||||
providers,
|
||||
current: "test-provider".to_string(),
|
||||
};
|
||||
let mut manager = ProviderManager::default();
|
||||
manager.providers = providers;
|
||||
manager.current = "test-provider".to_string();
|
||||
|
||||
let mut apps = HashMap::new();
|
||||
apps.insert("claude".to_string(), manager);
|
||||
|
||||
@@ -375,7 +375,7 @@ fn test_parse_prompt_deeplink() {
|
||||
assert_eq!(request.name.unwrap(), "test");
|
||||
assert_eq!(request.content.unwrap(), content_b64);
|
||||
assert_eq!(request.description.unwrap(), "desc");
|
||||
assert!(request.enabled.unwrap());
|
||||
assert_eq!(request.enabled.unwrap(), true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -391,13 +391,13 @@ fn test_parse_mcp_deeplink() {
|
||||
assert_eq!(request.resource, "mcp");
|
||||
assert_eq!(request.apps.unwrap(), "claude,codex");
|
||||
assert_eq!(request.config.unwrap(), config_b64);
|
||||
assert!(request.enabled.unwrap());
|
||||
assert_eq!(request.enabled.unwrap(), true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_skill_deeplink() {
|
||||
let url = "ccswitch://v1/import?resource=skill&repo=owner/repo&directory=skills&branch=dev";
|
||||
let request = parse_deeplink_url(url).unwrap();
|
||||
let request = parse_deeplink_url(&url).unwrap();
|
||||
|
||||
assert_eq!(request.resource, "skill");
|
||||
assert_eq!(request.repo.unwrap(), "owner/repo");
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
use crate::database::{lock_conn, Database};
|
||||
use crate::error::AppError;
|
||||
use chrono::{Duration, Local, TimeZone};
|
||||
use chrono::{Duration, Utc};
|
||||
use rusqlite::{params, Connection, OptionalExtension};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
@@ -186,17 +186,8 @@ impl Database {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
if days <= 1 {
|
||||
let today = Local::now().date_naive();
|
||||
let start_of_today = today.and_hms_opt(0, 0, 0).unwrap();
|
||||
// 使用 earliest() 处理 DST 切换时的歧义时间,fallback 到当前时间减一天
|
||||
let start_ts = Local
|
||||
.from_local_datetime(&start_of_today)
|
||||
.earliest()
|
||||
.unwrap_or_else(|| Local::now() - Duration::days(1))
|
||||
.timestamp();
|
||||
|
||||
let sql = "SELECT
|
||||
strftime('%Y-%m-%dT%H:00:00', datetime(created_at, 'unixepoch', 'localtime')) as bucket,
|
||||
strftime('%Y-%m-%dT%H:00:00Z', datetime(created_at, 'unixepoch')) as bucket,
|
||||
COUNT(*) as request_count,
|
||||
COALESCE(SUM(CAST(total_cost_usd AS REAL)), 0) as total_cost,
|
||||
COALESCE(SUM(input_tokens + output_tokens), 0) as total_tokens,
|
||||
@@ -205,12 +196,12 @@ impl Database {
|
||||
COALESCE(SUM(cache_creation_tokens), 0) as total_cache_creation_tokens,
|
||||
COALESCE(SUM(cache_read_tokens), 0) as total_cache_read_tokens
|
||||
FROM proxy_request_logs
|
||||
WHERE created_at >= ?
|
||||
WHERE created_at >= strftime('%s', 'now', '-1 day')
|
||||
GROUP BY bucket
|
||||
ORDER BY bucket ASC";
|
||||
|
||||
let mut stmt = conn.prepare(sql)?;
|
||||
let rows = stmt.query_map([start_ts], |row| {
|
||||
let rows = stmt.query_map([], |row| {
|
||||
Ok(DailyStats {
|
||||
date: row.get(0)?,
|
||||
request_count: row.get::<_, i64>(1)? as u64,
|
||||
@@ -230,11 +221,12 @@ impl Database {
|
||||
}
|
||||
|
||||
let mut stats = Vec::new();
|
||||
let today = Utc::now().date_naive();
|
||||
for hour in 0..24 {
|
||||
let bucket = today
|
||||
.and_hms_opt(hour, 0, 0)
|
||||
.unwrap()
|
||||
.format("%Y-%m-%dT%H:00:00")
|
||||
.format("%Y-%m-%dT%H:00:00Z")
|
||||
.to_string();
|
||||
|
||||
if let Some(stat) = buckets.remove(&bucket) {
|
||||
@@ -254,18 +246,8 @@ impl Database {
|
||||
}
|
||||
Ok(stats)
|
||||
} else {
|
||||
let today = Local::now().date_naive();
|
||||
let start_day = today - Duration::days((days.saturating_sub(1)) as i64);
|
||||
let start_of_window = start_day.and_hms_opt(0, 0, 0).unwrap();
|
||||
// 使用 earliest() 处理 DST 切换时的歧义时间,fallback 到当前时间减 days 天
|
||||
let start_ts = Local
|
||||
.from_local_datetime(&start_of_window)
|
||||
.earliest()
|
||||
.unwrap_or_else(|| Local::now() - Duration::days(days as i64))
|
||||
.timestamp();
|
||||
|
||||
let sql = "SELECT
|
||||
strftime('%Y-%m-%dT00:00:00', datetime(created_at, 'unixepoch', 'localtime')) as bucket,
|
||||
date(created_at, 'unixepoch') as bucket,
|
||||
COUNT(*) as request_count,
|
||||
COALESCE(SUM(CAST(total_cost_usd AS REAL)), 0) as total_cost,
|
||||
COALESCE(SUM(input_tokens + output_tokens), 0) as total_tokens,
|
||||
@@ -274,12 +256,12 @@ impl Database {
|
||||
COALESCE(SUM(cache_creation_tokens), 0) as total_cache_creation_tokens,
|
||||
COALESCE(SUM(cache_read_tokens), 0) as total_cache_read_tokens
|
||||
FROM proxy_request_logs
|
||||
WHERE created_at >= ?
|
||||
WHERE created_at >= strftime('%s', 'now', ?)
|
||||
GROUP BY bucket
|
||||
ORDER BY bucket ASC";
|
||||
|
||||
let mut stmt = conn.prepare(sql)?;
|
||||
let rows = stmt.query_map([start_ts], |row| {
|
||||
let rows = stmt.query_map([format!("-{days} days")], |row| {
|
||||
Ok(DailyStats {
|
||||
date: row.get(0)?,
|
||||
request_count: row.get::<_, i64>(1)? as u64,
|
||||
@@ -299,10 +281,12 @@ impl Database {
|
||||
}
|
||||
|
||||
let mut stats = Vec::new();
|
||||
let start_day =
|
||||
Utc::now().date_naive() - Duration::days((days.saturating_sub(1)) as i64);
|
||||
|
||||
for i in 0..days {
|
||||
let day = start_day + Duration::days(i as i64);
|
||||
let key = day.format("%Y-%m-%dT00:00:00").to_string();
|
||||
let key = day.format("%Y-%m-%d").to_string();
|
||||
if let Some(stat) = map.remove(&key) {
|
||||
stats.push(stat);
|
||||
} else {
|
||||
@@ -633,7 +617,7 @@ impl Database {
|
||||
"SELECT COALESCE(SUM(CAST(total_cost_usd AS REAL)), 0)
|
||||
FROM proxy_request_logs
|
||||
WHERE provider_id = ? AND app_type = ?
|
||||
AND date(datetime(created_at, 'unixepoch', 'localtime')) = date('now', 'localtime')",
|
||||
AND date(created_at, 'unixepoch') = date('now')",
|
||||
params![provider_id, app_type],
|
||||
|row| row.get(0),
|
||||
)
|
||||
@@ -645,7 +629,7 @@ impl Database {
|
||||
"SELECT COALESCE(SUM(CAST(total_cost_usd AS REAL)), 0)
|
||||
FROM proxy_request_logs
|
||||
WHERE provider_id = ? AND app_type = ?
|
||||
AND strftime('%Y-%m', datetime(created_at, 'unixepoch', 'localtime')) = strftime('%Y-%m', 'now', 'localtime')",
|
||||
AND strftime('%Y-%m', created_at, 'unixepoch') = strftime('%Y-%m', 'now')",
|
||||
params![provider_id, app_type],
|
||||
|row| row.get(0),
|
||||
)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "CC Switch",
|
||||
"version": "3.9.0-3",
|
||||
"version": "3.9.0-2",
|
||||
"identifier": "com.ccswitch.desktop",
|
||||
"build": {
|
||||
"frontendDist": "../dist",
|
||||
|
||||
@@ -49,7 +49,6 @@ pub fn test_mutex() -> &'static Mutex<()> {
|
||||
}
|
||||
|
||||
/// 创建测试用的 AppState,包含一个空的数据库
|
||||
#[allow(dead_code)]
|
||||
pub fn create_test_state() -> Result<AppState, Box<dyn std::error::Error>> {
|
||||
let db = Arc::new(Database::init()?);
|
||||
let proxy_service = ProxyService::new(db.clone());
|
||||
@@ -57,7 +56,6 @@ pub fn create_test_state() -> Result<AppState, Box<dyn std::error::Error>> {
|
||||
}
|
||||
|
||||
/// 创建测试用的 AppState,并从 MultiAppConfig 迁移数据
|
||||
#[allow(dead_code)]
|
||||
pub fn create_test_state_with_config(
|
||||
config: &MultiAppConfig,
|
||||
) -> Result<AppState, Box<dyn std::error::Error>> {
|
||||
|
||||
+18
-7
@@ -26,7 +26,6 @@ import {
|
||||
import { checkAllEnvConflicts, checkEnvConflicts } from "@/lib/api/env";
|
||||
import { useProviderActions } from "@/hooks/useProviderActions";
|
||||
import { useProxyStatus } from "@/hooks/useProxyStatus";
|
||||
import { useLastValidValue } from "@/hooks/useLastValidValue";
|
||||
import { extractErrorMessage } from "@/utils/errorUtils";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { AppSwitcher } from "@/components/AppSwitcher";
|
||||
@@ -74,9 +73,21 @@ function App() {
|
||||
const [envConflicts, setEnvConflicts] = useState<EnvConflict[]>([]);
|
||||
const [showEnvBanner, setShowEnvBanner] = useState(false);
|
||||
|
||||
// 使用 Hook 保存最后有效值,用于动画退出期间保持内容显示
|
||||
const effectiveEditingProvider = useLastValidValue(editingProvider);
|
||||
const effectiveUsageProvider = useLastValidValue(usageProvider);
|
||||
// 保存最后一个有效的 provider,用于动画退出期间显示内容
|
||||
const lastUsageProviderRef = useRef<Provider | null>(null);
|
||||
const lastEditingProviderRef = useRef<Provider | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (usageProvider) {
|
||||
lastUsageProviderRef.current = usageProvider;
|
||||
}
|
||||
}, [usageProvider]);
|
||||
|
||||
useEffect(() => {
|
||||
if (editingProvider) {
|
||||
lastEditingProviderRef.current = editingProvider;
|
||||
}
|
||||
}, [editingProvider]);
|
||||
|
||||
const promptPanelRef = useRef<any>(null);
|
||||
const mcpPanelRef = useRef<any>(null);
|
||||
@@ -707,7 +718,7 @@ function App() {
|
||||
|
||||
<EditProviderDialog
|
||||
open={Boolean(editingProvider)}
|
||||
provider={effectiveEditingProvider}
|
||||
provider={lastEditingProviderRef.current}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setEditingProvider(null);
|
||||
@@ -718,9 +729,9 @@ function App() {
|
||||
isProxyTakeover={isProxyRunning && isCurrentAppTakeoverActive}
|
||||
/>
|
||||
|
||||
{effectiveUsageProvider && (
|
||||
{lastUsageProviderRef.current && (
|
||||
<UsageScriptModal
|
||||
provider={effectiveUsageProvider}
|
||||
provider={lastUsageProviderRef.current}
|
||||
appId={activeApp}
|
||||
isOpen={Boolean(usageProvider)}
|
||||
onClose={() => setUsageProvider(null)}
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
import { useRef } from "react";
|
||||
|
||||
/**
|
||||
* 保存最后一个非 null/undefined 的值
|
||||
* 用于 Dialog 关闭动画期间保持内容显示
|
||||
*
|
||||
* @param value 当前值
|
||||
* @returns 当前值(如果有效)或最后一个有效值
|
||||
*/
|
||||
export function useLastValidValue<T>(value: T | null | undefined): T | null {
|
||||
const ref = useRef<T | null>(null);
|
||||
|
||||
// 同步更新 ref(在渲染期间,不在 useEffect 中)
|
||||
if (value != null) {
|
||||
ref.current = value;
|
||||
}
|
||||
|
||||
// 返回当前值或最后有效值
|
||||
return value ?? ref.current;
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Suspense, type ComponentType } from "react";
|
||||
import { Suspense } from "react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { render, screen, waitFor, fireEvent } from "@testing-library/react";
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import App from "@/App";
|
||||
import { resetProviderState } from "../msw/state";
|
||||
import { emitTauriEvent } from "../msw/tauriMocks";
|
||||
|
||||
@@ -108,6 +109,20 @@ vi.mock("@/components/ConfirmDialog", () => ({
|
||||
) : null,
|
||||
}));
|
||||
|
||||
vi.mock("@/components/settings/SettingsPage", () => ({
|
||||
SettingsPage: ({ open, onOpenChange, onImportSuccess }: any) =>
|
||||
open ? (
|
||||
<div data-testid="settings-dialog">
|
||||
<button onClick={() => onImportSuccess?.()}>
|
||||
trigger-import-success
|
||||
</button>
|
||||
<button onClick={() => onOpenChange(false)}>close-settings</button>
|
||||
</div>
|
||||
) : (
|
||||
<button onClick={() => onOpenChange(true)}>open-settings</button>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("@/components/AppSwitcher", () => ({
|
||||
AppSwitcher: ({ activeApp, onSwitch }: any) => (
|
||||
<div data-testid="app-switcher">
|
||||
@@ -135,12 +150,12 @@ vi.mock("@/components/mcp/McpPanel", () => ({
|
||||
),
|
||||
}));
|
||||
|
||||
const renderApp = (AppComponent: ComponentType) => {
|
||||
const renderApp = () => {
|
||||
const client = new QueryClient();
|
||||
return render(
|
||||
<QueryClientProvider client={client}>
|
||||
<Suspense fallback={<div data-testid="loading">loading</div>}>
|
||||
<AppComponent />
|
||||
<App />
|
||||
</Suspense>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
@@ -154,8 +169,7 @@ describe("App integration with MSW", () => {
|
||||
});
|
||||
|
||||
it("covers basic provider flows via real hooks", async () => {
|
||||
const { default: App } = await import("@/App");
|
||||
renderApp(App);
|
||||
renderApp();
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId("provider-list").textContent).toContain(
|
||||
@@ -163,6 +177,11 @@ describe("App integration with MSW", () => {
|
||||
),
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByText("update-badge"));
|
||||
expect(screen.getByTestId("settings-dialog")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByText("trigger-import-success"));
|
||||
fireEvent.click(screen.getByText("close-settings"));
|
||||
|
||||
fireEvent.click(screen.getByText("switch-codex"));
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId("provider-list").textContent).toContain(
|
||||
|
||||
Reference in New Issue
Block a user