From 247a5f57ab952d00ce296cc4a2369fbe3534c2d5 Mon Sep 17 00:00:00 2001 From: SaladDay Date: Thu, 22 Oct 2026 18:37:35 +0800 Subject: [PATCH 01/23] fix(database): align schema migrations through upstream v22 (#528) --- ...skills.sql => upstream_v22_mcp_skills.sql} | 6 +- src-tauri/src/database/mod.rs | 2 +- src-tauri/src/database/schema.rs | 30 ++++++++ src-tauri/src/database/tests.rs | 71 +++++++++++++------ src-tauri/src/services/sync_protocol.rs | 4 +- 5 files changed, 88 insertions(+), 25 deletions(-) rename src-tauri/src/database/fixtures/{upstream_v20_mcp_skills.sql => upstream_v22_mcp_skills.sql} (85%) diff --git a/src-tauri/src/database/fixtures/upstream_v20_mcp_skills.sql b/src-tauri/src/database/fixtures/upstream_v22_mcp_skills.sql similarity index 85% rename from src-tauri/src/database/fixtures/upstream_v20_mcp_skills.sql rename to src-tauri/src/database/fixtures/upstream_v22_mcp_skills.sql index 888dc542..21d93d5f 100644 --- a/src-tauri/src/database/fixtures/upstream_v20_mcp_skills.sql +++ b/src-tauri/src/database/fixtures/upstream_v22_mcp_skills.sql @@ -1,5 +1,5 @@ -- MCP/Skills DDL from farion1231/cc-switch at --- d35726e28695844deaf0098450b34911f5be7b78 (schema 20). +-- e4873bc8aa2555225d4867ec2f04b1290f1d21d9 (schema 22). CREATE TABLE IF NOT EXISTS mcp_servers ( id TEXT PRIMARY KEY, name TEXT NOT NULL, server_config TEXT NOT NULL, description TEXT, homepage TEXT, docs TEXT, tags TEXT NOT NULL DEFAULT '[]', @@ -7,6 +7,8 @@ CREATE TABLE IF NOT EXISTS mcp_servers ( enabled_gemini BOOLEAN NOT NULL DEFAULT 0, enabled_grokbuild BOOLEAN NOT NULL DEFAULT 0, enabled_opencode BOOLEAN NOT NULL DEFAULT 0, enabled_mcode BOOLEAN NOT NULL DEFAULT 0, + enabled_agy BOOLEAN NOT NULL DEFAULT 0, + enabled_kimi BOOLEAN NOT NULL DEFAULT 0, enabled_hermes BOOLEAN NOT NULL DEFAULT 0, enabled_pi BOOLEAN NOT NULL DEFAULT 0 ); @@ -26,6 +28,8 @@ CREATE TABLE IF NOT EXISTS skills ( enabled_grokbuild BOOLEAN NOT NULL DEFAULT 0, enabled_opencode BOOLEAN NOT NULL DEFAULT 0, enabled_mcode BOOLEAN NOT NULL DEFAULT 0, + enabled_agy BOOLEAN NOT NULL DEFAULT 0, + enabled_kimi BOOLEAN NOT NULL DEFAULT 0, enabled_hermes BOOLEAN NOT NULL DEFAULT 0, installed_at INTEGER NOT NULL DEFAULT 0, content_hash TEXT, diff --git a/src-tauri/src/database/mod.rs b/src-tauri/src/database/mod.rs index 6ee2f8cf..a02ba53b 100644 --- a/src-tauri/src/database/mod.rs +++ b/src-tauri/src/database/mod.rs @@ -60,7 +60,7 @@ const USAGE_MAINTENANCE_INTERVAL_SECS: u64 = 24 * 60 * 60; /// 注意:本库 schema 与上游项目同步(WebDAV 亦会整库同步),本仓库不得自行 /// 加表/加列或提升版本号;本地新增的持久化需求一律放独立 sidecar 存储 /// (如 session_manager::scan_cache_store)。 -pub(crate) const SCHEMA_VERSION: i32 = 20; +pub(crate) const SCHEMA_VERSION: i32 = 22; fn database_open_flags() -> OpenFlags { OpenFlags::SQLITE_OPEN_READ_WRITE diff --git a/src-tauri/src/database/schema.rs b/src-tauri/src/database/schema.rs index 1b85f0e2..28ec8aa5 100644 --- a/src-tauri/src/database/schema.rs +++ b/src-tauri/src/database/schema.rs @@ -61,6 +61,8 @@ impl Database { enabled_gemini BOOLEAN NOT NULL DEFAULT 0, enabled_grokbuild BOOLEAN NOT NULL DEFAULT 0, enabled_opencode BOOLEAN NOT NULL DEFAULT 0, enabled_mcode BOOLEAN NOT NULL DEFAULT 0, + enabled_agy BOOLEAN NOT NULL DEFAULT 0, + enabled_kimi BOOLEAN NOT NULL DEFAULT 0, enabled_hermes BOOLEAN NOT NULL DEFAULT 0, enabled_pi BOOLEAN NOT NULL DEFAULT 0 )", @@ -92,6 +94,8 @@ impl Database { enabled_grokbuild BOOLEAN NOT NULL DEFAULT 0, enabled_opencode BOOLEAN NOT NULL DEFAULT 0, enabled_mcode BOOLEAN NOT NULL DEFAULT 0, + enabled_agy BOOLEAN NOT NULL DEFAULT 0, + enabled_kimi BOOLEAN NOT NULL DEFAULT 0, enabled_hermes BOOLEAN NOT NULL DEFAULT 0, installed_at INTEGER NOT NULL DEFAULT 0, content_hash TEXT, @@ -558,6 +562,32 @@ impl Database { } Self::set_user_version(conn, 20)?; } + 20 => { + for table in ["mcp_servers", "skills"] { + if Self::table_exists(conn, table)? { + Self::add_column_if_missing( + conn, + table, + "enabled_agy", + "BOOLEAN NOT NULL DEFAULT 0", + )?; + } + } + Self::set_user_version(conn, 21)?; + } + 21 => { + for table in ["mcp_servers", "skills"] { + if Self::table_exists(conn, table)? { + Self::add_column_if_missing( + conn, + table, + "enabled_kimi", + "BOOLEAN NOT NULL DEFAULT 0", + )?; + } + } + Self::set_user_version(conn, 22)?; + } _ => { return Err(AppError::Database(format!( "未知的数据库版本 {version},无法迁移到 {SCHEMA_VERSION}" diff --git a/src-tauri/src/database/tests.rs b/src-tauri/src/database/tests.rs index 36fdb814..bb3e11a3 100644 --- a/src-tauri/src/database/tests.rs +++ b/src-tauri/src/database/tests.rs @@ -314,8 +314,16 @@ fn schema_migration_sets_user_version_when_missing() { fn seed_upstream_mcp_skills(conn: &Connection, version: i32) { conn.execute_batch("DROP TABLE IF EXISTS mcp_servers; DROP TABLE IF EXISTS skills;") .expect("remove CLI tables"); - conn.execute_batch(include_str!("fixtures/upstream_v20_mcp_skills.sql")) + conn.execute_batch(include_str!("fixtures/upstream_v22_mcp_skills.sql")) .expect("create upstream tables"); + for (introduced, column) in [(21, "enabled_agy"), (22, "enabled_kimi")] { + if version < introduced { + for table in ["mcp_servers", "skills"] { + conn.execute_batch(&format!("ALTER TABLE {table} DROP COLUMN {column};")) + .expect("restore older upstream schema"); + } + } + } if version < 20 { conn.execute_batch("ALTER TABLE mcp_servers DROP COLUMN enabled_pi;") .expect("restore v19 MCP schema"); @@ -345,6 +353,14 @@ fn seed_upstream_mcp_skills(conn: &Connection, version: i32) { conn.execute_batch("UPDATE mcp_servers SET enabled_pi = 1;") .expect("enable Pi"); } + for (introduced, column) in [(21, "enabled_agy"), (22, "enabled_kimi")] { + if version >= introduced { + for table in ["mcp_servers", "skills"] { + conn.execute_batch(&format!("UPDATE {table} SET {column} = 1;")) + .expect("enable upstream app"); + } + } + } Database::set_user_version(conn, version).expect("set upstream version"); } @@ -354,6 +370,10 @@ fn assert_upstream_mcp_skills(conn: &Connection, original_version: i32) { ("mcp_servers", "enabled_mcode"), ("skills", "enabled_mcode"), ("mcp_servers", "enabled_pi"), + ("mcp_servers", "enabled_agy"), + ("skills", "enabled_agy"), + ("mcp_servers", "enabled_kimi"), + ("skills", "enabled_kimi"), ] { let info = get_column_info(conn, table, column); assert_eq!(info.r#type, "BOOLEAN"); @@ -366,14 +386,19 @@ fn assert_upstream_mcp_skills(conn: &Connection, original_version: i32) { |row| Ok((row.get(0)?, row.get(1)?)), ) .expect("read upstream flags"); - let introduced = if column == "enabled_pi" { 20 } else { 19 }; + let introduced = match column { + "enabled_pi" => 20, + "enabled_agy" => 21, + "enabled_kimi" => 22, + _ => 19, + }; assert_eq!(flags, (1, i64::from(original_version >= introduced))); } } #[test] -fn schema_migration_upstream_v18_v19_v20_preserves_data_and_is_idempotent() { - for version in [18, 19, 20] { +fn schema_migration_upstream_v18_through_v22_preserves_data_and_is_idempotent() { + for version in 18..=22 { let conn = Connection::open_in_memory().unwrap(); seed_upstream_mcp_skills(&conn, version); Database::apply_schema_migrations_on_conn(&conn).expect("migrate upstream schema"); @@ -385,20 +410,24 @@ fn schema_migration_upstream_v18_v19_v20_preserves_data_and_is_idempotent() { let conn = Connection::open_in_memory().unwrap(); Database::set_user_version(&conn, 18).unwrap(); Database::apply_schema_migrations_on_conn(&conn).expect("migrate absent tables"); - seed_upstream_mcp_skills(&conn, 20); + seed_upstream_mcp_skills(&conn, 22); Database::set_user_version(&conn, 18).unwrap(); Database::apply_schema_migrations_on_conn(&conn).expect("migrate existing columns"); - assert_upstream_mcp_skills(&conn, 20); + assert_upstream_mcp_skills(&conn, 22); } #[test] -fn schema_create_tables_matches_upstream_v20_flags() { +fn schema_create_tables_matches_upstream_v22_flags() { let conn = Connection::open_in_memory().unwrap(); Database::create_tables_on_conn(&conn).unwrap(); for (table, column) in [ ("mcp_servers", "enabled_mcode"), ("skills", "enabled_mcode"), ("mcp_servers", "enabled_pi"), + ("mcp_servers", "enabled_agy"), + ("skills", "enabled_agy"), + ("mcp_servers", "enabled_kimi"), + ("skills", "enabled_kimi"), ] { let info = get_column_info(&conn, table, column); assert_eq!(info.r#type, "BOOLEAN"); @@ -409,12 +438,12 @@ fn schema_create_tables_matches_upstream_v20_flags() { } #[test] -fn init_and_sync_import_accept_upstream_v18_v19_v20() { +fn init_and_sync_import_accept_upstream_v18_through_v22() { let home = tempfile::tempdir().unwrap(); let _env = crate::test_support::TestEnvGuard::isolated(home.path()); let config_dir = home.path().join(".cc-switch"); std::fs::create_dir_all(&config_dir).unwrap(); - for version in [18, 19, 20] { + for version in 18..=22 { let conn = Connection::open(config_dir.join("cc-switch.db")).unwrap(); Database::create_tables_on_conn(&conn).unwrap(); seed_upstream_mcp_skills(&conn, version); @@ -2318,8 +2347,8 @@ fn mcp_dao_roundtrip_preserves_upstream_enablement() { "INSERT INTO mcp_servers ( id, name, server_config, tags, enabled_claude, enabled_codex, enabled_gemini, enabled_grokbuild, - enabled_opencode, enabled_hermes, enabled_mcode, enabled_pi - ) VALUES (?1, ?2, ?3, ?4, 0, 0, 0, 1, 0, 1, 1, 1)", + enabled_opencode, enabled_hermes, enabled_mcode, enabled_pi, enabled_agy, enabled_kimi + ) VALUES (?1, ?2, ?3, ?4, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1)", params![ "remote-hermes", "Remote Hermes", @@ -2346,18 +2375,18 @@ fn mcp_dao_roundtrip_preserves_upstream_enablement() { server.description = Some("updated".to_string()); db.save_mcp_server(&server).expect("save mcp server"); - let hidden_enablement: (i64, i64, i64, i64) = { + let hidden_enablement: (i64, i64, i64, i64, i64, i64) = { let conn = db.conn.lock().expect("lock conn"); conn.query_row( - "SELECT enabled_grokbuild, enabled_hermes, enabled_mcode, enabled_pi FROM mcp_servers WHERE id = 'remote-hermes'", + "SELECT enabled_grokbuild, enabled_hermes, enabled_mcode, enabled_pi, enabled_agy, enabled_kimi FROM mcp_servers WHERE id = 'remote-hermes'", [], - |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)), + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?, row.get(4)?, row.get(5)?)), ) .expect("read hidden enablement after save") }; assert_eq!( hidden_enablement, - (1, 1, 1, 1), + (1, 1, 1, 1, 1, 1), "save should preserve hidden flags" ); } @@ -2369,8 +2398,8 @@ fn skill_dao_save_preserves_upstream_enablement() { let conn = db.conn.lock().expect("lock conn"); conn.execute( "INSERT INTO skills ( - id, name, directory, enabled_grokbuild, enabled_hermes, enabled_mcode, installed_at - ) VALUES ('remote-skill', 'Remote Skill', 'remote-skill', 1, 1, 1, 42)", + id, name, directory, enabled_grokbuild, enabled_hermes, enabled_mcode, enabled_agy, enabled_kimi, installed_at + ) VALUES ('remote-skill', 'Remote Skill', 'remote-skill', 1, 1, 1, 1, 1, 42)", [], ) .expect("seed grokbuild-enabled Skill"); @@ -2383,18 +2412,18 @@ fn skill_dao_save_preserves_upstream_enablement() { skill.description = Some("updated".to_string()); db.save_skill(&skill).expect("save Skill"); - let hidden_enablement: (i64, i64, i64) = { + let hidden_enablement: (i64, i64, i64, i64, i64) = { let conn = db.conn.lock().expect("lock conn"); conn.query_row( - "SELECT enabled_grokbuild, enabled_hermes, enabled_mcode FROM skills WHERE id = 'remote-skill'", + "SELECT enabled_grokbuild, enabled_hermes, enabled_mcode, enabled_agy, enabled_kimi FROM skills WHERE id = 'remote-skill'", [], - |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?, row.get(4)?)), ) .expect("read hidden enablement after save") }; assert_eq!( hidden_enablement, - (1, 1, 1), + (1, 1, 1, 1, 1), "save should preserve hidden flags" ); } diff --git a/src-tauri/src/services/sync_protocol.rs b/src-tauri/src/services/sync_protocol.rs index cc47830b..f93f4467 100644 --- a/src-tauri/src/services/sync_protocol.rs +++ b/src-tauri/src/services/sync_protocol.rs @@ -570,8 +570,8 @@ mod tests { } #[test] - fn upstream_v19_and_v20_database_schemas_are_accepted() { - for version in [19, 20] { + fn upstream_v19_through_v22_database_schemas_are_accepted() { + for version in 19..=22 { let sql = format!("PRAGMA user_version={version};\n"); assert!(validate_sql_user_version_for_import(&sql).is_ok()); } From a285cd7d02fe893a72e9b47340f3893908bcabb6 Mon Sep 17 00:00:00 2001 From: SaladDay Date: Thu, 22 Oct 2026 18:44:07 +0800 Subject: [PATCH 02/23] chore(release): prepare v5.11.3 and thank contributors (#529) --- CHANGELOG.md | 30 +++++++++++++++++++++++++++++ README.md | 2 +- README_JA.md | 2 +- README_ZH.md | 2 +- docs/CHANGELOG.md | 30 +++++++++++++++++++++++++++++ docs/releases/v5.11.3.md | 41 ++++++++++++++++++++++++++++++++++++++++ src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- 8 files changed, 106 insertions(+), 5 deletions(-) create mode 100644 docs/releases/v5.11.3.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c00e9c2..2619acff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,36 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [5.11.3] - 2026-10-22 + +### Fixed + +- **Database / Compatibility**: Support database schemas 21 and 22, fixing startup failures when opening a database created by a newer CC Switch desktop version. Align the migration steps and MCP/Skills fields with the shared schema, preserving existing data and application enablement flags through upgrades, edits, and WebDAV sync. Includes [#528](https://github.com/SaladDay/cc-switch-cli/pull/528), fixing [#526](https://github.com/SaladDay/cc-switch-cli/issues/526). + +### Upgrade notes + +- If startup reports database version 21 or 22 as unsupported, update to v5.11.3. The existing pre-migration backup runs before upgrading older databases; databases newer than schema 22 are still rejected. +- This release adds database compatibility, not CLI management for Antigravity or Kimi Code. After migration to schema 22, older CLI versions cannot open the upgraded database. +- Run `cc-switch update`, or use `brew upgrade cc-switch-cli` for Homebrew installations once the formula is updated. + +### Thanks + +Thank you to everyone who reported problems, proposed changes, shared diagnostics, reviewed code, or joined the discussions. The list below covers issues and pull requests active since v5.11.2, including earlier participants in those discussions and contributions that have not been merged. Being listed here does not mean a proposed feature is included in this release. + +| Contributor | Issues and pull requests | +| --- | --- | +| [@AtaraxiaEpiphany](https://github.com/AtaraxiaEpiphany) | [#517](https://github.com/SaladDay/cc-switch-cli/pull/517), [#522](https://github.com/SaladDay/cc-switch-cli/pull/522) | +| [@claude](https://github.com/claude) | [#517](https://github.com/SaladDay/cc-switch-cli/pull/517), [#521](https://github.com/SaladDay/cc-switch-cli/pull/521), [#522](https://github.com/SaladDay/cc-switch-cli/pull/522) | +| [@hao-lin-lwh](https://github.com/hao-lin-lwh) | [#525](https://github.com/SaladDay/cc-switch-cli/issues/525) | +| [@kelvkhiu](https://github.com/kelvkhiu) | [#526](https://github.com/SaladDay/cc-switch-cli/issues/526) | +| [@RGB-loop](https://github.com/RGB-loop) | [#481](https://github.com/SaladDay/cc-switch-cli/issues/481), [#521](https://github.com/SaladDay/cc-switch-cli/pull/521) | +| [@SaladDay](https://github.com/SaladDay) | [#528](https://github.com/SaladDay/cc-switch-cli/pull/528) | +| [@SanAntonio021](https://github.com/SanAntonio021) | [#523](https://github.com/SaladDay/cc-switch-cli/pull/523), [#524](https://github.com/SaladDay/cc-switch-cli/pull/524) | +| [@stone-w4tch3r](https://github.com/stone-w4tch3r) | [#481](https://github.com/SaladDay/cc-switch-cli/issues/481) | +| [@Xiao-Maker-droid](https://github.com/Xiao-Maker-droid) | [#527](https://github.com/SaladDay/cc-switch-cli/pull/527) | + +Thanks also to our sponsors, everyone supporting and using the project, and the CC-Switch maintainers and contributors whose shared migration implementations underpin this fix. + ## [5.11.2] - 2026-10-16 ### Added diff --git a/README.md b/README.md index b4ece61b..42df2157 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ **Manage Claude Code, Codex, Gemini, OpenCode, Hermes, OpenClaw, and Pi from one interactive TUI or scriptable CLI.** -[![Version](https://img.shields.io/badge/version-5.11.2-blue.svg)](https://github.com/saladday/cc-switch-cli/releases) +[![Version](https://img.shields.io/badge/version-5.11.3-blue.svg)](https://github.com/saladday/cc-switch-cli/releases) [![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-lightgrey.svg)](https://github.com/saladday/cc-switch-cli/releases) [![Built with Rust](https://img.shields.io/badge/built%20with-Rust-orange.svg)](https://www.rust-lang.org/) [![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE) diff --git a/README_JA.md b/README_JA.md index 9f5e6213..4566dcb8 100644 --- a/README_JA.md +++ b/README_JA.md @@ -6,7 +6,7 @@ **対話型 TUI またはスクリプトで利用できる CLI から、Claude Code、Codex、Gemini、OpenCode、Hermes、OpenClaw、Pi を一元管理できます。** -[![バージョン](https://img.shields.io/badge/version-5.11.2-blue.svg)](https://github.com/saladday/cc-switch-cli/releases) +[![バージョン](https://img.shields.io/badge/version-5.11.3-blue.svg)](https://github.com/saladday/cc-switch-cli/releases) [![対応プラットフォーム](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-lightgrey.svg)](https://github.com/saladday/cc-switch-cli/releases) [![Rust 製](https://img.shields.io/badge/built%20with-Rust-orange.svg)](https://www.rust-lang.org/) [![ライセンス](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE) diff --git a/README_ZH.md b/README_ZH.md index 42b138b7..c660bd60 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -6,7 +6,7 @@ **通过交互式 TUI 或脚本化 CLI,统一管理 Claude Code、Codex、Gemini、OpenCode、Hermes、OpenClaw 和 Pi。** -[![Version](https://img.shields.io/badge/version-5.11.2-blue.svg)](https://github.com/saladday/cc-switch-cli/releases) +[![Version](https://img.shields.io/badge/version-5.11.3-blue.svg)](https://github.com/saladday/cc-switch-cli/releases) [![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-lightgrey.svg)](https://github.com/saladday/cc-switch-cli/releases) [![Built with Rust](https://img.shields.io/badge/built%20with-Rust-orange.svg)](https://www.rust-lang.org/) [![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 9c00e9c2..2619acff 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -9,6 +9,36 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [5.11.3] - 2026-10-22 + +### Fixed + +- **Database / Compatibility**: Support database schemas 21 and 22, fixing startup failures when opening a database created by a newer CC Switch desktop version. Align the migration steps and MCP/Skills fields with the shared schema, preserving existing data and application enablement flags through upgrades, edits, and WebDAV sync. Includes [#528](https://github.com/SaladDay/cc-switch-cli/pull/528), fixing [#526](https://github.com/SaladDay/cc-switch-cli/issues/526). + +### Upgrade notes + +- If startup reports database version 21 or 22 as unsupported, update to v5.11.3. The existing pre-migration backup runs before upgrading older databases; databases newer than schema 22 are still rejected. +- This release adds database compatibility, not CLI management for Antigravity or Kimi Code. After migration to schema 22, older CLI versions cannot open the upgraded database. +- Run `cc-switch update`, or use `brew upgrade cc-switch-cli` for Homebrew installations once the formula is updated. + +### Thanks + +Thank you to everyone who reported problems, proposed changes, shared diagnostics, reviewed code, or joined the discussions. The list below covers issues and pull requests active since v5.11.2, including earlier participants in those discussions and contributions that have not been merged. Being listed here does not mean a proposed feature is included in this release. + +| Contributor | Issues and pull requests | +| --- | --- | +| [@AtaraxiaEpiphany](https://github.com/AtaraxiaEpiphany) | [#517](https://github.com/SaladDay/cc-switch-cli/pull/517), [#522](https://github.com/SaladDay/cc-switch-cli/pull/522) | +| [@claude](https://github.com/claude) | [#517](https://github.com/SaladDay/cc-switch-cli/pull/517), [#521](https://github.com/SaladDay/cc-switch-cli/pull/521), [#522](https://github.com/SaladDay/cc-switch-cli/pull/522) | +| [@hao-lin-lwh](https://github.com/hao-lin-lwh) | [#525](https://github.com/SaladDay/cc-switch-cli/issues/525) | +| [@kelvkhiu](https://github.com/kelvkhiu) | [#526](https://github.com/SaladDay/cc-switch-cli/issues/526) | +| [@RGB-loop](https://github.com/RGB-loop) | [#481](https://github.com/SaladDay/cc-switch-cli/issues/481), [#521](https://github.com/SaladDay/cc-switch-cli/pull/521) | +| [@SaladDay](https://github.com/SaladDay) | [#528](https://github.com/SaladDay/cc-switch-cli/pull/528) | +| [@SanAntonio021](https://github.com/SanAntonio021) | [#523](https://github.com/SaladDay/cc-switch-cli/pull/523), [#524](https://github.com/SaladDay/cc-switch-cli/pull/524) | +| [@stone-w4tch3r](https://github.com/stone-w4tch3r) | [#481](https://github.com/SaladDay/cc-switch-cli/issues/481) | +| [@Xiao-Maker-droid](https://github.com/Xiao-Maker-droid) | [#527](https://github.com/SaladDay/cc-switch-cli/pull/527) | + +Thanks also to our sponsors, everyone supporting and using the project, and the CC-Switch maintainers and contributors whose shared migration implementations underpin this fix. + ## [5.11.2] - 2026-10-16 ### Added diff --git a/docs/releases/v5.11.3.md b/docs/releases/v5.11.3.md new file mode 100644 index 00000000..92ec3997 --- /dev/null +++ b/docs/releases/v5.11.3.md @@ -0,0 +1,41 @@ +# CC Switch CLI v5.11.3 + +This patch release restores compatibility with database schemas 21 and 22 for local startup and WebDAV sync. + +## Fixed + +- **Database / Compatibility**: Support database schemas 21 and 22, fixing startup failures when opening a database created by a newer CC Switch desktop version. Align the migration steps and MCP/Skills fields with the shared schema, preserving existing data and application enablement flags through upgrades, edits, and WebDAV sync. Includes [#528](https://github.com/SaladDay/cc-switch-cli/pull/528), fixing [#526](https://github.com/SaladDay/cc-switch-cli/issues/526). + +## Upgrade notes + +- If startup reports database version 21 or 22 as unsupported, update to v5.11.3. The existing pre-migration backup runs before upgrading older databases; databases newer than schema 22 are still rejected. +- This release adds database compatibility, not CLI management for Antigravity or Kimi Code. After migration to schema 22, older CLI versions cannot open the upgraded database. +- Run `cc-switch update`, or use `brew upgrade cc-switch-cli` for Homebrew installations once the formula is updated. + +## Thanks + +Thank you to everyone who reported problems, proposed changes, shared diagnostics, reviewed code, or joined the discussions. The list below covers issues and pull requests active since v5.11.2, including earlier participants in those discussions and contributions that have not been merged. Being listed here does not mean a proposed feature is included in this release. + +| Contributor | Issues and pull requests | +| --- | --- | +| [@AtaraxiaEpiphany](https://github.com/AtaraxiaEpiphany) | [#517](https://github.com/SaladDay/cc-switch-cli/pull/517), [#522](https://github.com/SaladDay/cc-switch-cli/pull/522) | +| [@claude](https://github.com/claude) | [#517](https://github.com/SaladDay/cc-switch-cli/pull/517), [#521](https://github.com/SaladDay/cc-switch-cli/pull/521), [#522](https://github.com/SaladDay/cc-switch-cli/pull/522) | +| [@hao-lin-lwh](https://github.com/hao-lin-lwh) | [#525](https://github.com/SaladDay/cc-switch-cli/issues/525) | +| [@kelvkhiu](https://github.com/kelvkhiu) | [#526](https://github.com/SaladDay/cc-switch-cli/issues/526) | +| [@RGB-loop](https://github.com/RGB-loop) | [#481](https://github.com/SaladDay/cc-switch-cli/issues/481), [#521](https://github.com/SaladDay/cc-switch-cli/pull/521) | +| [@SaladDay](https://github.com/SaladDay) | [#528](https://github.com/SaladDay/cc-switch-cli/pull/528) | +| [@SanAntonio021](https://github.com/SanAntonio021) | [#523](https://github.com/SaladDay/cc-switch-cli/pull/523), [#524](https://github.com/SaladDay/cc-switch-cli/pull/524) | +| [@stone-w4tch3r](https://github.com/stone-w4tch3r) | [#481](https://github.com/SaladDay/cc-switch-cli/issues/481) | +| [@Xiao-Maker-droid](https://github.com/Xiao-Maker-droid) | [#527](https://github.com/SaladDay/cc-switch-cli/pull/527) | + +Thanks also to our sponsors, everyone supporting and using the project, and the CC-Switch maintainers and contributors whose shared migration implementations underpin this fix. + +## Install or update + +Run `cc-switch update`, or use `brew upgrade cc-switch-cli` for Homebrew installations once the formula is updated. Platform packages and the installer are available below: + +```bash +curl -fsSL https://github.com/SaladDay/cc-switch-cli/releases/latest/download/install.sh | bash +``` + +[Full comparison](https://github.com/SaladDay/cc-switch-cli/compare/v5.11.2...v5.11.3) diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index d68bd85f..57b87437 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -502,7 +502,7 @@ dependencies = [ [[package]] name = "cc-switch" -version = "5.11.2" +version = "5.11.3" dependencies = [ "anyhow", "async-stream", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 16151a30..9943ae78 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "cc-switch" -version = "5.11.2" +version = "5.11.3" description = "All-in-One Assistant for Claude Code, Codex, Gemini, OpenCode & OpenClaw" authors = ["Jason Young", "saladday"] license = "MIT" From 11bf812c98686736f837dba3b785b5770a94cd23 Mon Sep 17 00:00:00 2001 From: zydo Date: Sat, 24 Oct 2026 05:53:54 -0700 Subject: [PATCH 03/23] fix(tui): clarify managed Codex OAuth quota refresh controls --- src-tauri/src/cli/i18n.rs | 8 ++ src-tauri/src/cli/provider_quota.rs | 87 +++++++++++++++---- .../src/cli/tui/app/form_handlers/provider.rs | 2 +- src-tauri/src/cli/tui/form/provider_state.rs | 27 +++++- .../cli/tui/form/provider_state_loading.rs | 17 ++++ src-tauri/src/cli/tui/form/tests.rs | 40 +++++++++ src-tauri/src/cli/tui/help.rs | 12 +++ src-tauri/src/cli/tui/mod.rs | 9 ++ src-tauri/src/cli/tui/tests.rs | 22 +++++ src-tauri/src/cli/tui/ui/forms/provider.rs | 14 +++ 10 files changed, 220 insertions(+), 18 deletions(-) diff --git a/src-tauri/src/cli/i18n.rs b/src-tauri/src/cli/i18n.rs index 165df494..7d908623 100644 --- a/src-tauri/src/cli/i18n.rs +++ b/src-tauri/src/cli/i18n.rs @@ -3331,6 +3331,14 @@ pub mod texts { } } + pub fn tui_managed_codex_auto_refresh() -> &'static str { + if is_chinese() { + "内置 Codex OAuth / ChatGPT · 自动刷新" + } else { + "Built-in Codex OAuth / ChatGPT · Auto refresh" + } + } + pub fn tui_usage_query_enable() -> &'static str { if is_chinese() { "启用用量查询" diff --git a/src-tauri/src/cli/provider_quota.rs b/src-tauri/src/cli/provider_quota.rs index dfaef975..34f28870 100644 --- a/src-tauri/src/cli/provider_quota.rs +++ b/src-tauri/src/cli/provider_quota.rs @@ -98,6 +98,24 @@ pub(crate) fn quota_target_for_provider( .as_ref() .and_then(|meta| meta.usage_script.as_ref()); + if is_codex_oauth_provider(provider) { + return Some(QuotaTarget { + app_type: app_type.clone(), + provider_id: id.to_string(), + provider_name, + kind: QuotaTargetKind::CodexOAuth { + account_id: provider + .meta + .as_ref() + .and_then(|meta| meta.managed_account_id_for("codex_oauth")), + }, + auto_query_interval_minutes: usage_script + .filter(|script| script.enabled) + .and_then(|script| script.auto_query_interval) + .unwrap_or(0), + }); + } + if let Some(script) = usage_script.filter(|script| script.enabled) { let template = script .template_type @@ -136,21 +154,6 @@ pub(crate) fn quota_target_for_provider( } } - if is_codex_oauth_provider(provider) { - return Some(QuotaTarget { - app_type: app_type.clone(), - provider_id: id.to_string(), - provider_name, - kind: QuotaTargetKind::CodexOAuth { - account_id: provider - .meta - .as_ref() - .and_then(|meta| meta.managed_account_id_for("codex_oauth")), - }, - auto_query_interval_minutes: 5, - }); - } - None } @@ -404,6 +407,60 @@ mod tests { )); } + #[test] + fn managed_codex_quota_ignores_templates_and_preserves_account_scheduling() { + let mut keys = Vec::new(); + for account in ["acct-1", "acct-2"] { + let mut provider = test_provider("oauth", "Unrelated name", json!({})); + set_usage_script(&mut provider, true, "general"); + let meta = provider.meta.as_mut().unwrap(); + meta.provider_type = Some("codex_oauth".into()); + meta.auth_binding = Some(AuthBinding { + source: AuthBindingSource::ManagedAccount, + auth_provider: Some("codex_oauth".into()), + account_id: Some(account.into()), + }); + for interval in [0, 3] { + provider + .meta + .as_mut() + .unwrap() + .usage_script + .as_mut() + .unwrap() + .auto_query_interval = Some(interval); + let target = + quota_target_for_provider(&AppType::Claude, "oauth", &provider).unwrap(); + assert_eq!( + target.kind, + QuotaTargetKind::CodexOAuth { + account_id: Some(account.into()) + } + ); + assert_eq!(target.auto_query_interval_minutes, interval); + } + provider + .meta + .as_mut() + .unwrap() + .usage_script + .as_mut() + .unwrap() + .enabled = false; + assert_eq!( + quota_target_for_provider(&AppType::Claude, "oauth", &provider) + .unwrap() + .auto_query_interval_minutes, + 0 + ); + provider.meta.as_mut().unwrap().usage_script = None; + let target = quota_target_for_provider(&AppType::Claude, "oauth", &provider).unwrap(); + assert_eq!(target.auto_query_interval_minutes, 0); + keys.push(target.cache_key()); + } + assert_ne!(keys[0], keys[1]); + } + #[test] fn usage_display_hides_default_plan_name() { let item = UsageData { diff --git a/src-tauri/src/cli/tui/app/form_handlers/provider.rs b/src-tauri/src/cli/tui/app/form_handlers/provider.rs index 5178ec77..07b63aba 100644 --- a/src-tauri/src/cli/tui/app/form_handlers/provider.rs +++ b/src-tauri/src/cli/tui/app/form_handlers/provider.rs @@ -1336,7 +1336,7 @@ impl App { }; provider.open_usage_query_page(); - if self.usage_query_notice_confirmed { + if self.usage_query_notice_confirmed || provider.uses_managed_codex_quota() { return; } diff --git a/src-tauri/src/cli/tui/form/provider_state.rs b/src-tauri/src/cli/tui/form/provider_state.rs index 62f5220f..cda74aa0 100644 --- a/src-tauri/src/cli/tui/form/provider_state.rs +++ b/src-tauri/src/cli/tui/form/provider_state.rs @@ -626,7 +626,21 @@ impl ProviderAddFormState { .unwrap_or(0) } + pub fn uses_managed_codex_quota(&self) -> bool { + self.extra + .pointer("/meta/providerType") + .and_then(Value::as_str) + == Some("codex_oauth") + } + pub fn usage_query_fields(&self) -> Vec { + if self.uses_managed_codex_quota() { + let mut fields = vec![UsageQueryField::Enabled]; + if self.usage_query_enabled { + fields.push(UsageQueryField::AutoInterval); + } + return fields; + } let mut fields = vec![UsageQueryField::Enabled]; if !self.usage_query_enabled { @@ -1792,7 +1806,7 @@ impl ProviderAddFormState { } pub fn refresh_default_usage_query_template(&mut self) { - if self.usage_query_official_subscription { + if self.usage_query_official_subscription || self.uses_managed_codex_quota() { if self.usage_query_template != UsageQueryTemplate::OfficialSubscription { self.set_usage_query_template(UsageQueryTemplate::OfficialSubscription); } @@ -2026,7 +2040,7 @@ impl ProviderAddFormState { } pub fn available_usage_query_templates(&self) -> Vec { - if self.usage_query_official_subscription { + if self.usage_query_official_subscription || self.uses_managed_codex_quota() { return vec![UsageQueryTemplate::OfficialSubscription]; } @@ -2040,6 +2054,11 @@ impl ProviderAddFormState { pub fn set_usage_query_template(&mut self, template: UsageQueryTemplate) { self.clear_usage_query_field_error(UsageQueryField::Script); + let template = if self.uses_managed_codex_quota() { + UsageQueryTemplate::OfficialSubscription + } else { + template + }; self.usage_query_template = template; match template { UsageQueryTemplate::Custom => { @@ -2170,6 +2189,10 @@ impl ProviderAddFormState { } pub fn refresh_usage_query_provider_kind(&mut self) { + if self.uses_managed_codex_quota() { + self.set_usage_query_template(UsageQueryTemplate::OfficialSubscription); + return; + } let was_official = self.usage_query_official_subscription; let is_official = serde_json::from_value::(self.to_provider_json_value()) .ok() diff --git a/src-tauri/src/cli/tui/form/provider_state_loading.rs b/src-tauri/src/cli/tui/form/provider_state_loading.rs index aa74b454..1dadb1cf 100644 --- a/src-tauri/src/cli/tui/form/provider_state_loading.rs +++ b/src-tauri/src/cli/tui/form/provider_state_loading.rs @@ -66,6 +66,23 @@ fn populate_local_proxy_settings_form(form: &mut ProviderAddFormState, provider: } pub(super) fn populate_usage_query_form(form: &mut ProviderAddFormState, provider: &Provider) { + if provider.is_codex_oauth() { + form.set_usage_query_template(UsageQueryTemplate::OfficialSubscription); + let script = provider + .meta + .as_ref() + .and_then(|meta| meta.usage_script.as_ref()); + form.usage_query_enabled = script + .is_some_and(|script| script.enabled && script.auto_query_interval.unwrap_or(0) > 0); + form.usage_query_auto_interval.set( + script + .and_then(|script| script.auto_query_interval) + .filter(|interval| *interval > 0) + .unwrap_or(5) + .to_string(), + ); + return; + } form.usage_query_official_subscription = provider .official_subscription_tool(&form.app_type) .is_some(); diff --git a/src-tauri/src/cli/tui/form/tests.rs b/src-tauri/src/cli/tui/form/tests.rs index 645cb5d1..3ca3bfcf 100644 --- a/src-tauri/src/cli/tui/form/tests.rs +++ b/src-tauri/src/cli/tui/form/tests.rs @@ -8303,3 +8303,43 @@ fn claude_fallback_one_m_is_adjacent_and_resets_with_template() { assert!(!form.claude_fallback_one_m); assert!(form.claude_model.value.is_empty()); } + +#[test] +fn managed_codex_quota_form_preserves_binding_and_native_query() { + let provider: Provider = serde_json::from_value(json!({ + "id": "oauth", "name": "Account", "settingsConfig": {}, + "meta": {"providerType": "codex_oauth", "authBinding": { + "source": "managed_account", "authProvider": "codex_oauth", "accountId": "acct-1" + }} + })) + .unwrap(); + let mut form = ProviderAddFormState::from_provider(AppType::Claude, &provider); + form.open_usage_query_page(); + assert!(!form.usage_query_enabled); + assert_eq!(form.usage_query_fields(), vec![UsageQueryField::Enabled]); + assert!(form.to_provider_json_value()["meta"] + .get("usage_script") + .is_none()); + form.toggle_usage_query_enabled(); + assert_eq!( + form.usage_query_fields(), + vec![UsageQueryField::Enabled, UsageQueryField::AutoInterval] + ); + let saved = form.to_provider_json_value(); + assert_eq!( + saved["meta"]["authBinding"], + serde_json::to_value(&provider).unwrap()["meta"]["authBinding"] + ); + assert_eq!( + saved["meta"]["usage_script"]["templateType"], + "official_subscription" + ); + assert_eq!(saved["meta"]["usage_script"]["code"], ""); + let saved: Provider = serde_json::from_value(saved).unwrap(); + let mut reopened = ProviderAddFormState::from_provider(AppType::Claude, &saved); + reopened.open_usage_query_page(); + assert!(reopened.usage_query_enabled); + reopened.toggle_usage_query_enabled(); + let saved: Provider = serde_json::from_value(reopened.to_provider_json_value()).unwrap(); + assert!(!ProviderAddFormState::from_provider(AppType::Claude, &saved).usage_query_enabled); +} diff --git a/src-tauri/src/cli/tui/help.rs b/src-tauri/src/cli/tui/help.rs index 4c707af2..49aaffda 100644 --- a/src-tauri/src/cli/tui/help.rs +++ b/src-tauri/src/cli/tui/help.rs @@ -85,6 +85,7 @@ enum HelpTarget { template: UsageQueryTemplate, }, UsageQueryInstructions, + ManagedCodexQuota, S3Field { field: S3SyncField, }, @@ -217,6 +218,10 @@ fn current_help_target(app: &App) -> HelpTarget { return HelpTarget::Global; }; + if matches!(provider.page, ProviderFormPage::UsageQuery) && provider.uses_managed_codex_quota() + { + return HelpTarget::ManagedCodexQuota; + } if matches!(provider.page, ProviderFormPage::UsageQuery) { return match provider.focus { FormFocus::Fields => { @@ -421,6 +426,13 @@ fn help_for_target(target: HelpTarget, app: &App, data: &UiData) -> HelpContent HelpTarget::LocalProxySettingsField { field } => local_proxy_settings_field_help(field), HelpTarget::CodexModelCatalogField { field } => codex_model_catalog_field_help(field), HelpTarget::UsageQueryExtractor { template } => usage_query_extractor_help(template), + HelpTarget::ManagedCodexQuota => HelpContent::new( + texts::tui_managed_codex_auto_refresh(), + help_lines( + "使用绑定的 ChatGPT 账号查询订阅额度,无需余额模板。关闭自动刷新(或间隔为 0)后不会自动联网;仍可在供应商列表按 r 手动刷新。查询失败或登录过期与自动刷新开关无关。", + "Queries subscription quota for the bound ChatGPT account without a balance template. Disabling automatic refresh (or setting interval to 0) prevents automatic network queries; press r in the provider list to refresh manually. Query failures and expired credentials are separate from automatic refresh settings.", + ), + ), HelpTarget::UsageQueryInstructions => HelpContent::new( texts::tui_usage_query_script_help_title(), super::form::ProviderAddFormState::usage_query_script_help_lines(), diff --git a/src-tauri/src/cli/tui/mod.rs b/src-tauri/src/cli/tui/mod.rs index 04126bd0..6b6ddff1 100644 --- a/src-tauri/src/cli/tui/mod.rs +++ b/src-tauri/src/cli/tui/mod.rs @@ -292,6 +292,15 @@ fn queue_current_quota_refresh_if_due( return; }; + if matches!( + target.kind, + crate::cli::provider_quota::QuotaTargetKind::CodexOAuth { .. } + ) && target.auto_query_interval_minutes == 0 + { + app.quota_auto_target_key = None; + app.quota_last_auto_tick = None; + return; + } let target_key = target.cache_key(); let target_changed = app.quota_auto_target_key.as_deref() != Some(target_key.as_str()); let target_missing_state = data.quota.state_for(&target.provider_id).is_none(); diff --git a/src-tauri/src/cli/tui/tests.rs b/src-tauri/src/cli/tui/tests.rs index 3682832a..b57bb4a2 100644 --- a/src-tauri/src/cli/tui/tests.rs +++ b/src-tauri/src/cli/tui/tests.rs @@ -5799,3 +5799,25 @@ fn periodic_usage_sync_waits_one_interval_and_honors_the_opt_out() { queue_usage_session_sync_if_due(&mut app, Some(&tx), &mut tracker); assert!(rx.try_recv().is_err(), "opting out disables the re-sync"); } + +#[test] +fn managed_codex_quota_auto_off_skips_initial_query_but_manual_refresh_works() { + let mut app = App::new(Some(AppType::Claude)); + let mut data = UiData { + providers: official_claude_providers(), + ..UiData::default() + }; + let row = &mut data.providers.rows[0]; + let meta = row.provider.meta.as_mut().unwrap(); + meta.provider_type = Some("codex_oauth".into()); + meta.usage_script = None; + let provider_id = row.id.clone(); + let (tx, rx) = mpsc::channel(); + for tick in [0, 100 * TUI_TICKS_PER_MINUTE] { + app.tick = tick; + queue_current_quota_refresh_if_due(&mut app, &mut data, Some(&tx)); + assert!(rx.try_recv().is_err()); + } + queue_provider_quota_refresh(&mut app, &mut data, Some(&tx), &provider_id); + assert!(matches!(rx.try_recv(), Ok(QuotaReq::Refresh { .. }))); +} diff --git a/src-tauri/src/cli/tui/ui/forms/provider.rs b/src-tauri/src/cli/tui/ui/forms/provider.rs index dcfdb223..f26b7c28 100644 --- a/src-tauri/src/cli/tui/ui/forms/provider.rs +++ b/src-tauri/src/cli/tui/ui/forms/provider.rs @@ -1839,6 +1839,9 @@ pub(crate) fn usage_query_field_label_and_value( field: super::form::UsageQueryField, ) -> (String, String) { let label = match field { + super::form::UsageQueryField::Enabled if provider.uses_managed_codex_quota() => { + texts::tui_managed_codex_auto_refresh().to_string() + } super::form::UsageQueryField::Enabled => texts::tui_usage_query_enable().to_string(), super::form::UsageQueryField::Template => texts::tui_usage_query_template().to_string(), super::form::UsageQueryField::ApiKey => { @@ -2179,6 +2182,17 @@ pub(crate) fn provider_field_label_and_value( .copied() .unwrap_or_default() .to_string(), + ProviderAddField::UsageQuery if provider.uses_managed_codex_quota() => { + format!( + "{}: {} ›", + texts::tui_managed_codex_auto_refresh(), + if provider.usage_query_enabled { + texts::enabled() + } else { + texts::disabled() + } + ) + } ProviderAddField::UsageQuery => { if provider.usage_query_enabled { format!( From db41f8416a90562886053e72f50b5359d48608c4 Mon Sep 17 00:00:00 2001 From: SaladDay <92240037+SaladDay@users.noreply.github.com> Date: Sun, 25 Oct 2026 14:50:10 +0800 Subject: [PATCH 04/23] fix(tui): align managed OAuth quota controls with upstream --- src-tauri/src/cli/i18n.rs | 8 -- src-tauri/src/cli/provider_quota.rs | 88 ++++++------------- .../src/cli/tui/app/form_handlers/provider.rs | 2 +- src-tauri/src/cli/tui/form/provider_state.rs | 41 +++------ .../cli/tui/form/provider_state_loading.rs | 17 ---- src-tauri/src/cli/tui/form/tests.rs | 71 ++++++++------- src-tauri/src/cli/tui/help.rs | 16 +--- src-tauri/src/cli/tui/mod.rs | 9 -- src-tauri/src/cli/tui/tests.rs | 22 ----- src-tauri/src/cli/tui/ui/forms/provider.rs | 14 --- 10 files changed, 81 insertions(+), 207 deletions(-) diff --git a/src-tauri/src/cli/i18n.rs b/src-tauri/src/cli/i18n.rs index 7d908623..165df494 100644 --- a/src-tauri/src/cli/i18n.rs +++ b/src-tauri/src/cli/i18n.rs @@ -3331,14 +3331,6 @@ pub mod texts { } } - pub fn tui_managed_codex_auto_refresh() -> &'static str { - if is_chinese() { - "内置 Codex OAuth / ChatGPT · 自动刷新" - } else { - "Built-in Codex OAuth / ChatGPT · Auto refresh" - } - } - pub fn tui_usage_query_enable() -> &'static str { if is_chinese() { "启用用量查询" diff --git a/src-tauri/src/cli/provider_quota.rs b/src-tauri/src/cli/provider_quota.rs index 34f28870..5e06fbab 100644 --- a/src-tauri/src/cli/provider_quota.rs +++ b/src-tauri/src/cli/provider_quota.rs @@ -98,7 +98,7 @@ pub(crate) fn quota_target_for_provider( .as_ref() .and_then(|meta| meta.usage_script.as_ref()); - if is_codex_oauth_provider(provider) { + if provider.is_codex_oauth() { return Some(QuotaTarget { app_type: app_type.clone(), provider_id: id.to_string(), @@ -109,10 +109,7 @@ pub(crate) fn quota_target_for_provider( .as_ref() .and_then(|meta| meta.managed_account_id_for("codex_oauth")), }, - auto_query_interval_minutes: usage_script - .filter(|script| script.enabled) - .and_then(|script| script.auto_query_interval) - .unwrap_or(0), + auto_query_interval_minutes: 5, }); } @@ -135,8 +132,7 @@ pub(crate) fn quota_target_for_provider( }); } // Ignore an imported or hand-edited native template on a custom - // provider. Managed OAuth providers may still use their own quota - // path below. + // provider. } else { // Official providers expose only the native subscription template. // A stale script template must not bypass the opt-in switch. @@ -241,14 +237,6 @@ pub(crate) fn usage_number(value: f64) -> String { } } -fn is_codex_oauth_provider(provider: &Provider) -> bool { - provider - .meta - .as_ref() - .and_then(|meta| meta.provider_type.as_deref()) - .is_some_and(|value| value == "codex_oauth") -} - #[cfg(test)] mod tests { use serde_json::{json, Value}; @@ -408,55 +396,35 @@ mod tests { } #[test] - fn managed_codex_quota_ignores_templates_and_preserves_account_scheduling() { + fn codex_oauth_quota_ignores_usage_templates_and_keeps_account_refresh() { let mut keys = Vec::new(); for account in ["acct-1", "acct-2"] { - let mut provider = test_provider("oauth", "Unrelated name", json!({})); - set_usage_script(&mut provider, true, "general"); - let meta = provider.meta.as_mut().unwrap(); - meta.provider_type = Some("codex_oauth".into()); - meta.auth_binding = Some(AuthBinding { - source: AuthBindingSource::ManagedAccount, - auth_provider: Some("codex_oauth".into()), - account_id: Some(account.into()), - }); - for interval in [0, 3] { - provider - .meta - .as_mut() - .unwrap() - .usage_script - .as_mut() - .unwrap() - .auto_query_interval = Some(interval); - let target = - quota_target_for_provider(&AppType::Claude, "oauth", &provider).unwrap(); - assert_eq!( - target.kind, - QuotaTargetKind::CodexOAuth { - account_id: Some(account.into()) + for template in ["general", "balance", "official_subscription"] { + for enabled in [false, true] { + let mut provider = test_provider("oauth", "Unrelated name", json!({})); + set_usage_script(&mut provider, enabled, template); + let meta = provider.meta.as_mut().unwrap(); + meta.provider_type = Some("codex_oauth".into()); + meta.auth_binding = Some(AuthBinding { + source: AuthBindingSource::ManagedAccount, + auth_provider: Some("codex_oauth".into()), + account_id: Some(account.into()), + }); + meta.usage_script.as_mut().unwrap().auto_query_interval = Some(0); + let target = quota_target_for_provider(&AppType::Claude, "oauth", &provider) + .expect("native quota target"); + assert_eq!( + target.kind, + QuotaTargetKind::CodexOAuth { + account_id: Some(account.into()), + } + ); + assert_eq!(target.auto_query_interval_minutes, 5); + if template == "general" && enabled { + keys.push(target.cache_key()); } - ); - assert_eq!(target.auto_query_interval_minutes, interval); + } } - provider - .meta - .as_mut() - .unwrap() - .usage_script - .as_mut() - .unwrap() - .enabled = false; - assert_eq!( - quota_target_for_provider(&AppType::Claude, "oauth", &provider) - .unwrap() - .auto_query_interval_minutes, - 0 - ); - provider.meta.as_mut().unwrap().usage_script = None; - let target = quota_target_for_provider(&AppType::Claude, "oauth", &provider).unwrap(); - assert_eq!(target.auto_query_interval_minutes, 0); - keys.push(target.cache_key()); } assert_ne!(keys[0], keys[1]); } diff --git a/src-tauri/src/cli/tui/app/form_handlers/provider.rs b/src-tauri/src/cli/tui/app/form_handlers/provider.rs index 07b63aba..5178ec77 100644 --- a/src-tauri/src/cli/tui/app/form_handlers/provider.rs +++ b/src-tauri/src/cli/tui/app/form_handlers/provider.rs @@ -1336,7 +1336,7 @@ impl App { }; provider.open_usage_query_page(); - if self.usage_query_notice_confirmed || provider.uses_managed_codex_quota() { + if self.usage_query_notice_confirmed { return; } diff --git a/src-tauri/src/cli/tui/form/provider_state.rs b/src-tauri/src/cli/tui/form/provider_state.rs index cda74aa0..eaeb0c1f 100644 --- a/src-tauri/src/cli/tui/form/provider_state.rs +++ b/src-tauri/src/cli/tui/form/provider_state.rs @@ -598,8 +598,12 @@ impl ProviderAddFormState { AppType::Codex => fields.push(ProviderAddField::CodexQuickConfig), _ => {} } - fields.push(ProviderAddField::UsageQueryDivider); - fields.push(ProviderAddField::UsageQuery); + // Managed Codex OAuth uses the bound account's native quota, like the + // desktop provider card; generic usage templates do not apply. + if !self.is_claude_codex_oauth_provider() { + fields.push(ProviderAddField::UsageQueryDivider); + fields.push(ProviderAddField::UsageQuery); + } // Add mode leads with the template picker row plus its divider, so the // template reads as its own group above the real fields. Inserted last @@ -626,21 +630,7 @@ impl ProviderAddFormState { .unwrap_or(0) } - pub fn uses_managed_codex_quota(&self) -> bool { - self.extra - .pointer("/meta/providerType") - .and_then(Value::as_str) - == Some("codex_oauth") - } - pub fn usage_query_fields(&self) -> Vec { - if self.uses_managed_codex_quota() { - let mut fields = vec![UsageQueryField::Enabled]; - if self.usage_query_enabled { - fields.push(UsageQueryField::AutoInterval); - } - return fields; - } let mut fields = vec![UsageQueryField::Enabled]; if !self.usage_query_enabled { @@ -709,7 +699,8 @@ impl ProviderAddFormState { } pub fn usage_query_script_validation_error(&self) -> Option<&'static str> { - if !self.usage_query_enabled + if self.is_claude_codex_oauth_provider() + || !self.usage_query_enabled || matches!( self.usage_query_template, UsageQueryTemplate::GitHubCopilot @@ -1550,6 +1541,9 @@ impl ProviderAddFormState { } pub fn open_usage_query_page(&mut self) { + if self.is_claude_codex_oauth_provider() { + return; + } self.refresh_usage_query_provider_kind(); self.refresh_default_usage_query_template(); self.page = ProviderFormPage::UsageQuery; @@ -1806,7 +1800,7 @@ impl ProviderAddFormState { } pub fn refresh_default_usage_query_template(&mut self) { - if self.usage_query_official_subscription || self.uses_managed_codex_quota() { + if self.usage_query_official_subscription { if self.usage_query_template != UsageQueryTemplate::OfficialSubscription { self.set_usage_query_template(UsageQueryTemplate::OfficialSubscription); } @@ -2040,7 +2034,7 @@ impl ProviderAddFormState { } pub fn available_usage_query_templates(&self) -> Vec { - if self.usage_query_official_subscription || self.uses_managed_codex_quota() { + if self.usage_query_official_subscription { return vec![UsageQueryTemplate::OfficialSubscription]; } @@ -2054,11 +2048,6 @@ impl ProviderAddFormState { pub fn set_usage_query_template(&mut self, template: UsageQueryTemplate) { self.clear_usage_query_field_error(UsageQueryField::Script); - let template = if self.uses_managed_codex_quota() { - UsageQueryTemplate::OfficialSubscription - } else { - template - }; self.usage_query_template = template; match template { UsageQueryTemplate::Custom => { @@ -2189,10 +2178,6 @@ impl ProviderAddFormState { } pub fn refresh_usage_query_provider_kind(&mut self) { - if self.uses_managed_codex_quota() { - self.set_usage_query_template(UsageQueryTemplate::OfficialSubscription); - return; - } let was_official = self.usage_query_official_subscription; let is_official = serde_json::from_value::(self.to_provider_json_value()) .ok() diff --git a/src-tauri/src/cli/tui/form/provider_state_loading.rs b/src-tauri/src/cli/tui/form/provider_state_loading.rs index 1dadb1cf..aa74b454 100644 --- a/src-tauri/src/cli/tui/form/provider_state_loading.rs +++ b/src-tauri/src/cli/tui/form/provider_state_loading.rs @@ -66,23 +66,6 @@ fn populate_local_proxy_settings_form(form: &mut ProviderAddFormState, provider: } pub(super) fn populate_usage_query_form(form: &mut ProviderAddFormState, provider: &Provider) { - if provider.is_codex_oauth() { - form.set_usage_query_template(UsageQueryTemplate::OfficialSubscription); - let script = provider - .meta - .as_ref() - .and_then(|meta| meta.usage_script.as_ref()); - form.usage_query_enabled = script - .is_some_and(|script| script.enabled && script.auto_query_interval.unwrap_or(0) > 0); - form.usage_query_auto_interval.set( - script - .and_then(|script| script.auto_query_interval) - .filter(|interval| *interval > 0) - .unwrap_or(5) - .to_string(), - ); - return; - } form.usage_query_official_subscription = provider .official_subscription_tool(&form.app_type) .is_some(); diff --git a/src-tauri/src/cli/tui/form/tests.rs b/src-tauri/src/cli/tui/form/tests.rs index 3ca3bfcf..92d9e9e2 100644 --- a/src-tauri/src/cli/tui/form/tests.rs +++ b/src-tauri/src/cli/tui/form/tests.rs @@ -8305,41 +8305,44 @@ fn claude_fallback_one_m_is_adjacent_and_resets_with_template() { } #[test] -fn managed_codex_quota_form_preserves_binding_and_native_query() { +fn codex_oauth_hides_usage_query_and_preserves_binding_and_saved_script() { + for script in [ + serde_json::Value::Null, + json!({ + "enabled": true, "language": "javascript", "code": "invalid legacy script", + "templateType": "general", "autoQueryInterval": 0 + }), + ] { + let mut value = json!({ + "id": "oauth", "name": "Account", "settingsConfig": {}, + "meta": {"providerType": "codex_oauth", "authBinding": { + "source": "managed_account", "authProvider": "codex_oauth", "accountId": "acct-1" + }} + }); + if !script.is_null() { + value["meta"]["usage_script"] = script; + } + let provider: Provider = serde_json::from_value(value.clone()).unwrap(); + let mut form = ProviderAddFormState::from_provider(AppType::Claude, &provider); + assert!(!form.fields().contains(&ProviderAddField::UsageQuery)); + assert!(!form.fields().contains(&ProviderAddField::UsageQueryDivider)); + form.open_usage_query_page(); + assert!(matches!(form.page, ProviderFormPage::Main)); + assert!(form.usage_query_script_validation_error().is_none()); + form.name.set("Renamed account"); + let saved = form.to_provider_json_value(); + assert_eq!(saved["meta"]["authBinding"], value["meta"]["authBinding"]); + assert_eq!(saved["meta"]["usage_script"], value["meta"]["usage_script"]); + let reopened = ProviderAddFormState::from_provider( + AppType::Claude, + &serde_json::from_value(saved).unwrap(), + ); + assert!(!reopened.fields().contains(&ProviderAddField::UsageQuery)); + } let provider: Provider = serde_json::from_value(json!({ - "id": "oauth", "name": "Account", "settingsConfig": {}, - "meta": {"providerType": "codex_oauth", "authBinding": { - "source": "managed_account", "authProvider": "codex_oauth", "accountId": "acct-1" - }} + "id": "custom", "name": "Codex OAuth", "settingsConfig": {} })) .unwrap(); - let mut form = ProviderAddFormState::from_provider(AppType::Claude, &provider); - form.open_usage_query_page(); - assert!(!form.usage_query_enabled); - assert_eq!(form.usage_query_fields(), vec![UsageQueryField::Enabled]); - assert!(form.to_provider_json_value()["meta"] - .get("usage_script") - .is_none()); - form.toggle_usage_query_enabled(); - assert_eq!( - form.usage_query_fields(), - vec![UsageQueryField::Enabled, UsageQueryField::AutoInterval] - ); - let saved = form.to_provider_json_value(); - assert_eq!( - saved["meta"]["authBinding"], - serde_json::to_value(&provider).unwrap()["meta"]["authBinding"] - ); - assert_eq!( - saved["meta"]["usage_script"]["templateType"], - "official_subscription" - ); - assert_eq!(saved["meta"]["usage_script"]["code"], ""); - let saved: Provider = serde_json::from_value(saved).unwrap(); - let mut reopened = ProviderAddFormState::from_provider(AppType::Claude, &saved); - reopened.open_usage_query_page(); - assert!(reopened.usage_query_enabled); - reopened.toggle_usage_query_enabled(); - let saved: Provider = serde_json::from_value(reopened.to_provider_json_value()).unwrap(); - assert!(!ProviderAddFormState::from_provider(AppType::Claude, &saved).usage_query_enabled); + let form = ProviderAddFormState::from_provider(AppType::Claude, &provider); + assert!(form.fields().contains(&ProviderAddField::UsageQuery)); } diff --git a/src-tauri/src/cli/tui/help.rs b/src-tauri/src/cli/tui/help.rs index 49aaffda..239298a0 100644 --- a/src-tauri/src/cli/tui/help.rs +++ b/src-tauri/src/cli/tui/help.rs @@ -85,7 +85,6 @@ enum HelpTarget { template: UsageQueryTemplate, }, UsageQueryInstructions, - ManagedCodexQuota, S3Field { field: S3SyncField, }, @@ -218,10 +217,6 @@ fn current_help_target(app: &App) -> HelpTarget { return HelpTarget::Global; }; - if matches!(provider.page, ProviderFormPage::UsageQuery) && provider.uses_managed_codex_quota() - { - return HelpTarget::ManagedCodexQuota; - } if matches!(provider.page, ProviderFormPage::UsageQuery) { return match provider.focus { FormFocus::Fields => { @@ -426,13 +421,6 @@ fn help_for_target(target: HelpTarget, app: &App, data: &UiData) -> HelpContent HelpTarget::LocalProxySettingsField { field } => local_proxy_settings_field_help(field), HelpTarget::CodexModelCatalogField { field } => codex_model_catalog_field_help(field), HelpTarget::UsageQueryExtractor { template } => usage_query_extractor_help(template), - HelpTarget::ManagedCodexQuota => HelpContent::new( - texts::tui_managed_codex_auto_refresh(), - help_lines( - "使用绑定的 ChatGPT 账号查询订阅额度,无需余额模板。关闭自动刷新(或间隔为 0)后不会自动联网;仍可在供应商列表按 r 手动刷新。查询失败或登录过期与自动刷新开关无关。", - "Queries subscription quota for the bound ChatGPT account without a balance template. Disabling automatic refresh (or setting interval to 0) prevents automatic network queries; press r in the provider list to refresh manually. Query failures and expired credentials are separate from automatic refresh settings.", - ), - ), HelpTarget::UsageQueryInstructions => HelpContent::new( texts::tui_usage_query_script_help_title(), super::form::ProviderAddFormState::usage_query_script_help_lines(), @@ -843,8 +831,8 @@ fn provider_field_help(app_type: AppType, field: ProviderAddField) -> HelpConten ProviderAddField::CodexOAuthAccount => HelpContent::new( texts::tui_label_chatgpt_account(), help_lines( - "绑定 ChatGPT/Codex 官方登录账号。官方账号可用于 Codex 插件、移动端远程操作等官方能力。", - "Binds an official ChatGPT/Codex account. Official login can keep Codex plugins, mobile remote control, and other official app features available.", + "绑定 ChatGPT/Codex 官方登录账号。官方账号可用于 Codex 插件、移动端远程操作等官方能力。订阅额度通过绑定账号的内置查询显示,无需余额模板;可在供应商列表按 r 刷新。", + "Binds an official ChatGPT/Codex account. Official login can keep Codex plugins, mobile remote control, and other official app features available. Subscription quota uses the bound account's built-in query without a balance template; press r in the provider list to refresh.", ), ), ProviderAddField::CodexFastMode => HelpContent::new( diff --git a/src-tauri/src/cli/tui/mod.rs b/src-tauri/src/cli/tui/mod.rs index 6b6ddff1..04126bd0 100644 --- a/src-tauri/src/cli/tui/mod.rs +++ b/src-tauri/src/cli/tui/mod.rs @@ -292,15 +292,6 @@ fn queue_current_quota_refresh_if_due( return; }; - if matches!( - target.kind, - crate::cli::provider_quota::QuotaTargetKind::CodexOAuth { .. } - ) && target.auto_query_interval_minutes == 0 - { - app.quota_auto_target_key = None; - app.quota_last_auto_tick = None; - return; - } let target_key = target.cache_key(); let target_changed = app.quota_auto_target_key.as_deref() != Some(target_key.as_str()); let target_missing_state = data.quota.state_for(&target.provider_id).is_none(); diff --git a/src-tauri/src/cli/tui/tests.rs b/src-tauri/src/cli/tui/tests.rs index b57bb4a2..3682832a 100644 --- a/src-tauri/src/cli/tui/tests.rs +++ b/src-tauri/src/cli/tui/tests.rs @@ -5799,25 +5799,3 @@ fn periodic_usage_sync_waits_one_interval_and_honors_the_opt_out() { queue_usage_session_sync_if_due(&mut app, Some(&tx), &mut tracker); assert!(rx.try_recv().is_err(), "opting out disables the re-sync"); } - -#[test] -fn managed_codex_quota_auto_off_skips_initial_query_but_manual_refresh_works() { - let mut app = App::new(Some(AppType::Claude)); - let mut data = UiData { - providers: official_claude_providers(), - ..UiData::default() - }; - let row = &mut data.providers.rows[0]; - let meta = row.provider.meta.as_mut().unwrap(); - meta.provider_type = Some("codex_oauth".into()); - meta.usage_script = None; - let provider_id = row.id.clone(); - let (tx, rx) = mpsc::channel(); - for tick in [0, 100 * TUI_TICKS_PER_MINUTE] { - app.tick = tick; - queue_current_quota_refresh_if_due(&mut app, &mut data, Some(&tx)); - assert!(rx.try_recv().is_err()); - } - queue_provider_quota_refresh(&mut app, &mut data, Some(&tx), &provider_id); - assert!(matches!(rx.try_recv(), Ok(QuotaReq::Refresh { .. }))); -} diff --git a/src-tauri/src/cli/tui/ui/forms/provider.rs b/src-tauri/src/cli/tui/ui/forms/provider.rs index f26b7c28..dcfdb223 100644 --- a/src-tauri/src/cli/tui/ui/forms/provider.rs +++ b/src-tauri/src/cli/tui/ui/forms/provider.rs @@ -1839,9 +1839,6 @@ pub(crate) fn usage_query_field_label_and_value( field: super::form::UsageQueryField, ) -> (String, String) { let label = match field { - super::form::UsageQueryField::Enabled if provider.uses_managed_codex_quota() => { - texts::tui_managed_codex_auto_refresh().to_string() - } super::form::UsageQueryField::Enabled => texts::tui_usage_query_enable().to_string(), super::form::UsageQueryField::Template => texts::tui_usage_query_template().to_string(), super::form::UsageQueryField::ApiKey => { @@ -2182,17 +2179,6 @@ pub(crate) fn provider_field_label_and_value( .copied() .unwrap_or_default() .to_string(), - ProviderAddField::UsageQuery if provider.uses_managed_codex_quota() => { - format!( - "{}: {} ›", - texts::tui_managed_codex_auto_refresh(), - if provider.usage_query_enabled { - texts::enabled() - } else { - texts::disabled() - } - ) - } ProviderAddField::UsageQuery => { if provider.usage_query_enabled { format!( From 14d4b9837054074489920c53b03d488f8581582d Mon Sep 17 00:00:00 2001 From: saladday <1203511142@qq.com> Date: Sun, 25 Oct 2026 15:25:23 +0800 Subject: [PATCH 05/23] fix(codex): preserve provider authentication in forms --- src-tauri/src/cli/commands/provider_input.rs | 2 - src-tauri/src/cli/tui/form/codex_config.rs | 80 ++++++- src-tauri/src/cli/tui/form/provider_json.rs | 65 +++--- .../cli/tui/form/provider_state_loading.rs | 12 +- src-tauri/src/cli/tui/form/tests.rs | 211 ++++++++++++++++++ src-tauri/src/cli/tui/help.rs | 4 +- src-tauri/src/codex_config.rs | 26 +-- src-tauri/src/live/project/codex.rs | 2 +- 8 files changed, 326 insertions(+), 76 deletions(-) diff --git a/src-tauri/src/cli/commands/provider_input.rs b/src-tauri/src/cli/commands/provider_input.rs index 29676189..4a3e873b 100644 --- a/src-tauri/src/cli/commands/provider_input.rs +++ b/src-tauri/src/cli/commands/provider_input.rs @@ -2676,8 +2676,6 @@ pub(crate) fn build_codex_settings_config_from_prompt( base_url, model, "responses", - true, - "OPENAI_API_KEY", ); let mut settings_obj = current diff --git a/src-tauri/src/cli/tui/form/codex_config.rs b/src-tauri/src/cli/tui/form/codex_config.rs index ba6fe417..11c98c9b 100644 --- a/src-tauri/src/cli/tui/form/codex_config.rs +++ b/src-tauri/src/cli/tui/form/codex_config.rs @@ -61,17 +61,8 @@ pub(crate) fn update_codex_config_snippet( base_url: &str, model: &str, wire_api: CodexWireApi, - requires_openai_auth: bool, - env_key: &str, ) -> String { - crate::codex_config::update_codex_config_snippet( - original, - base_url, - model, - wire_api.as_str(), - requires_openai_auth, - env_key, - ) + crate::codex_config::update_codex_config_snippet(original, base_url, model, wire_api.as_str()) } pub(crate) fn build_codex_third_party_config_toml( @@ -88,6 +79,75 @@ pub(crate) fn build_codex_third_party_config_toml( ) } +// Match upstream useCodexConfigState: stored auth wins; bearer is a display fallback. +pub(super) fn codex_api_key(settings: &serde_json::Value) -> String { + settings + .get("auth") + .and_then(|auth| auth.get("OPENAI_API_KEY")) + .and_then(serde_json::Value::as_str) + .filter(|key| !key.is_empty()) + .map(str::to_string) + .or_else(|| { + let doc = settings + .get("config")? + .as_str()? + .parse::() + .ok()?; + let token = |item: &toml_edit::Item| { + item.as_str() + .map(str::trim) + .filter(|key| !key.is_empty()) + .map(str::to_string) + }; + doc.get("model_provider") + .and_then(|item| item.as_str()) + .map(str::trim) + .filter(|id| !id.is_empty() && !crate::live::project::codex::is_built_in_id(id)) + .and_then(|id| { + doc.get("model_providers")? + .get(id)? + .get("experimental_bearer_token") + }) + .and_then(token) + .or_else(|| doc.get("experimental_bearer_token").and_then(token)) + }) + .unwrap_or_default() +} + +// Match upstream updateCodexExperimentalBearerToken: update only an existing +// active-provider token, falling back to the root token. Never add a token. +pub(super) fn update_existing_codex_bearer(config: &str, key: &str) -> String { + let Ok(mut doc) = config.parse::() else { + return config.to_string(); + }; + let provider = doc + .get("model_provider") + .and_then(|item| item.as_str()) + .map(str::trim) + .filter(|id| !id.is_empty() && !crate::live::project::codex::is_built_in_id(id)) + .filter(|id| { + doc.get("model_providers") + .and_then(|item| item.get(*id)) + .and_then(|item| item.get("experimental_bearer_token")) + .is_some() + }) + .map(str::to_string); + let table = match provider { + Some(id) => doc["model_providers"][&id].as_table_like_mut(), + None => Some(doc.as_table_mut() as &mut dyn toml_edit::TableLike), + }; + if let Some(table) = table { + if let Some(token) = table.get_mut("experimental_bearer_token") { + if key.trim().is_empty() { + table.remove("experimental_bearer_token"); + } else { + *token = toml_edit::value(key.trim()); + } + } + } + doc.to_string() +} + #[cfg(test)] mod tests { use super::*; diff --git a/src-tauri/src/cli/tui/form/provider_json.rs b/src-tauri/src/cli/tui/form/provider_json.rs index de4dd5e9..c2086015 100644 --- a/src-tauri/src/cli/tui/form/provider_json.rs +++ b/src-tauri/src/cli/tui/form/provider_json.rs @@ -238,6 +238,13 @@ pub(crate) fn codex_settings_contain_common_config_for_form( } impl ProviderAddFormState { + fn codex_api_key_changed(&self) -> bool { + self.codex_api_key.value + != super::codex_config::codex_api_key( + self.extra.get("settingsConfig").unwrap_or(&Value::Null), + ) + } + pub(crate) fn existing_codex_config_text(&self) -> &str { self.extra .get("settingsConfig") @@ -342,14 +349,14 @@ impl ProviderAddFormState { } else { existing_config.to_string() }; - let mut config = update_codex_config_snippet( - &base_config, - base_url, - model, - self.codex_wire_api, - self.codex_requires_openai_auth, - self.codex_env_key.value.trim(), - ); + let mut config = + update_codex_config_snippet(&base_config, base_url, model, self.codex_wire_api); + if self.codex_api_key_changed() { + config = super::codex_config::update_existing_codex_bearer( + &config, + &self.codex_api_key.value, + ); + } if self.codex_goal_mode_touched { config = crate::codex_config::set_codex_goal_mode(&config, self.codex_goal_mode); } @@ -505,30 +512,32 @@ impl ProviderAddFormState { settings_obj.remove("modelCatalog"); } - let api_key = self.codex_api_key.value.trim(); - if api_key.is_empty() { - if let Some(auth_obj) = settings_obj - .get_mut("auth") - .and_then(|value| value.as_object_mut()) - { - auth_obj.remove("OPENAI_API_KEY"); - if auth_obj.is_empty() { + if self.codex_api_key_changed() { + let api_key = self.codex_api_key.value.trim(); + if api_key.is_empty() { + if let Some(auth_obj) = settings_obj + .get_mut("auth") + .and_then(|value| value.as_object_mut()) + { + auth_obj.remove("OPENAI_API_KEY"); + if auth_obj.is_empty() { + settings_obj.remove("auth"); + } + } else { settings_obj.remove("auth"); } } else { - settings_obj.remove("auth"); - } - } else { - let auth_value = settings_obj - .entry("auth".to_string()) - .or_insert_with(|| json!({})); - if !auth_value.is_object() { - *auth_value = json!({}); + let auth_value = settings_obj + .entry("auth".to_string()) + .or_insert_with(|| json!({})); + if !auth_value.is_object() { + *auth_value = json!({}); + } + let auth_obj = auth_value + .as_object_mut() + .expect("auth must be a JSON object"); + auth_obj.insert("OPENAI_API_KEY".to_string(), json!(api_key)); } - let auth_obj = auth_value - .as_object_mut() - .expect("auth must be a JSON object"); - auth_obj.insert("OPENAI_API_KEY".to_string(), json!(api_key)); } } } diff --git a/src-tauri/src/cli/tui/form/provider_state_loading.rs b/src-tauri/src/cli/tui/form/provider_state_loading.rs index aa74b454..0a1376d4 100644 --- a/src-tauri/src/cli/tui/form/provider_state_loading.rs +++ b/src-tauri/src/cli/tui/form/provider_state_loading.rs @@ -251,15 +251,9 @@ fn populate_codex_form(form: &mut ProviderAddFormState, provider: &Provider) { form.codex_remote_compaction = crate::codex_config::is_codex_remote_compaction_enabled(config); } - if let Some(auth) = provider - .settings_config - .get("auth") - .and_then(|value| value.as_object()) - { - if let Some(key) = auth.get("OPENAI_API_KEY").and_then(|value| value.as_str()) { - form.codex_api_key.set(key); - } - } + form.codex_api_key.set(super::codex_config::codex_api_key( + &provider.settings_config, + )); form.claude_api_format = parse_codex_api_format(provider); form.claude_api_key_field = provider .meta diff --git a/src-tauri/src/cli/tui/form/tests.rs b/src-tauri/src/cli/tui/form/tests.rs index 92d9e9e2..2ef8b8e7 100644 --- a/src-tauri/src/cli/tui/form/tests.rs +++ b/src-tauri/src/cli/tui/form/tests.rs @@ -8346,3 +8346,214 @@ fn codex_oauth_hides_usage_query_and_preserves_binding_and_saved_script() { let form = ProviderAddFormState::from_provider(AppType::Claude, &provider); assert!(form.fields().contains(&ProviderAddField::UsageQuery)); } + +#[test] +fn codex_auth_form_preserves_explicit_auth_and_bearer_on_unrelated_save() { + for auth in [ + json!({"tokens": {"account_id": "account"}}), + json!({"OPENAI_API_KEY": "sk-stored"}), + ] { + for directive in [ + "", + "requires_openai_auth = false", + "requires_openai_auth = true", + "requires_openai_auth = true\nenv_key = \"CUSTOM_KEY\"", + ] { + let config = format!("model_provider = \"custom\"\n[model_providers.custom]\nbase_url = \"https://example.com/v1\"\nexperimental_bearer_token = \"sk-bearer\"\n{directive}\n[model_providers.other]\nexperimental_bearer_token = \"sk-other\"\n"); + let provider = Provider::with_id( + "custom".into(), + "Custom".into(), + json!({"auth": auth, "config": config}), + None, + ); + let mut form = ProviderAddFormState::from_provider(AppType::Codex, &provider); + assert_eq!( + form.codex_api_key.value, + auth.get("OPENAI_API_KEY") + .and_then(Value::as_str) + .unwrap_or("sk-bearer") + ); + form.name.set("Renamed"); + let saved = form.to_provider_json_value(); + assert_eq!(saved["settingsConfig"]["auth"], auth); + let before: toml::Table = toml::from_str(&config).unwrap(); + let after: toml::Table = + toml::from_str(saved["settingsConfig"]["config"].as_str().unwrap()).unwrap(); + for key in [ + "requires_openai_auth", + "env_key", + "experimental_bearer_token", + ] { + assert_eq!( + after["model_providers"]["custom"].get(key), + before["model_providers"]["custom"].get(key), + "{directive}: {key}" + ); + } + assert_eq!( + after["model_providers"]["other"], + before["model_providers"]["other"] + ); + } + } +} + +#[test] +fn codex_auth_form_key_edits_update_or_clear_existing_bearer() { + for location in ["provider", "root", "absent"] { + let root = if location == "root" { + "experimental_bearer_token = \"sk-old\"\n" + } else { + "" + }; + let token = if location == "provider" { + "experimental_bearer_token = \"sk-old\"\n" + } else { + "" + }; + let config = format!("{root}model_provider = \"custom\"\n[model_providers.custom]\nbase_url = \"https://example.com/v1\"\nrequires_openai_auth = false\n{token}[model_providers.other]\nexperimental_bearer_token = \"sk-other\"\n"); + let provider = Provider::with_id( + "custom".into(), + "Custom".into(), + json!({"auth": {"OPENAI_API_KEY": "sk-old", "tokens": {"account_id": "account"}}, "config": config}), + None, + ); + for key in ["sk-new", ""] { + let mut form = ProviderAddFormState::from_provider(AppType::Codex, &provider); + form.codex_api_key.set(key); + let saved = form.to_provider_json_value(); + assert_eq!( + saved["settingsConfig"]["auth"]["tokens"]["account_id"], + "account" + ); + assert_eq!( + saved["settingsConfig"]["auth"] + .get("OPENAI_API_KEY") + .and_then(Value::as_str), + (!key.is_empty()).then_some(key) + ); + let after: toml::Table = + toml::from_str(saved["settingsConfig"]["config"].as_str().unwrap()).unwrap(); + let table = if location == "root" { + &after + } else { + after["model_providers"]["custom"].as_table().unwrap() + }; + assert_eq!( + table + .get("experimental_bearer_token") + .and_then(toml::Value::as_str), + (location != "absent" && !key.is_empty()).then_some(key) + ); + assert!(after["model_providers"]["custom"].get("env_key").is_none()); + assert_eq!( + after["model_providers"]["other"]["experimental_bearer_token"].as_str(), + Some("sk-other") + ); + let reopened: Provider = serde_json::from_value(saved).unwrap(); + assert_eq!( + ProviderAddFormState::from_provider(AppType::Codex, &reopened) + .codex_api_key + .value, + key + ); + } + } +} + +#[test] +fn codex_auth_form_bearer_fallback_accepts_inline_tables_and_empty_provider_tokens() { + for (config, expected) in [ + ( + r#"model_provider = "custom" +experimental_bearer_token = "sk-root" +[model_providers.custom] +base_url = "https://example.com/v1" +experimental_bearer_token = " " +"#, + "sk-root", + ), + ( + r#"model_provider = "custom" +model_providers = { custom = { base_url = "https://example.com/v1", experimental_bearer_token = "sk-inline" } } +"#, + "sk-inline", + ), + ] { + let provider = Provider::with_id( + "custom".into(), + "Custom".into(), + json!({"auth": {"tokens": {"account_id": "account"}}, "config": config}), + None, + ); + let mut form = ProviderAddFormState::from_provider(AppType::Codex, &provider); + assert_eq!(form.codex_api_key.value, expected); + form.name.set("Renamed"); + let saved = form.to_provider_json_value(); + assert_eq!( + saved["settingsConfig"]["auth"], + provider.settings_config["auth"] + ); + let reopened: Provider = serde_json::from_value(saved).unwrap(); + assert_eq!( + ProviderAddFormState::from_provider(AppType::Codex, &reopened) + .codex_api_key + .value, + expected + ); + } +} + +#[test] +fn codex_auth_form_uses_case_sensitive_current_builtin_ids() { + for (id, custom) in [ + ("OpenAI", true), + ("oss", true), + ("ollama-chat", true), + ("openai", false), + ("amazon-bedrock-runtime", false), + ] { + let config = format!("model_provider = \"{id}\"\nexperimental_bearer_token = \"sk-root\"\n[model_providers.{id}]\nbase_url = \"https://example.com/v1\"\nexperimental_bearer_token = \"sk-provider\"\n"); + let provider = Provider::with_id( + "custom".into(), + "Custom".into(), + json!({"config": config}), + None, + ); + let form = ProviderAddFormState::from_provider(AppType::Codex, &provider); + assert_eq!( + form.codex_api_key.value, + if custom { "sk-provider" } else { "sk-root" }, + "{id}" + ); + for key in ["sk-new", ""] { + let mut form = form.clone(); + form.codex_api_key.set(key); + let saved = form.to_provider_json_value(); + let after: toml::Table = + toml::from_str(saved["settingsConfig"]["config"].as_str().unwrap()).unwrap(); + let changed = if custom { + after["model_providers"][id].as_table().unwrap() + } else { + &after + }; + assert_eq!( + changed + .get("experimental_bearer_token") + .and_then(toml::Value::as_str), + (!key.is_empty()).then_some(key), + "{id}" + ); + let untouched = if custom { + &after + } else { + after["model_providers"][id].as_table().unwrap() + }; + assert_eq!( + untouched["experimental_bearer_token"].as_str(), + Some(if custom { "sk-root" } else { "sk-provider" }), + "{id}" + ); + } + } +} diff --git a/src-tauri/src/cli/tui/help.rs b/src-tauri/src/cli/tui/help.rs index 239298a0..b9462811 100644 --- a/src-tauri/src/cli/tui/help.rs +++ b/src-tauri/src/cli/tui/help.rs @@ -1065,8 +1065,8 @@ fn provider_preview_help(app_type: AppType, section: Option (AppType::Codex, Some(CodexPreviewSection::Auth)) => HelpContent::new( texts::tui_codex_auth_json_title(), help_lines( - "这里预览将保存的 Codex 认证配置。代理接管时,上游会强调这里是存储配置,不是运行中的 auth.json。", - "This previews the Codex auth config to be saved. During proxy takeover, upstream treats this as stored config, not the live auth.json.", + "这里预览保存在 CC Switch 中的认证配置,不是运行中的 auth.json。第三方 API Key 在切换时写入 config.toml;auth.json 用于官方登录。", + "This previews the auth config stored in CC Switch, not the live auth.json. Third-party API keys are written to config.toml on switch; auth.json is used for official login.", ), ), (AppType::Codex, Some(CodexPreviewSection::Config)) => HelpContent::new( diff --git a/src-tauri/src/codex_config.rs b/src-tauri/src/codex_config.rs index e4dbcb87..a405585f 100644 --- a/src-tauri/src/codex_config.rs +++ b/src-tauri/src/codex_config.rs @@ -1728,8 +1728,6 @@ pub fn update_codex_config_snippet( base_url: &str, model: &str, wire_api: &str, - requires_openai_auth: bool, - env_key: &str, ) -> String { let mut doc = match original.trim().parse::() { Ok(doc) => doc, @@ -1778,17 +1776,6 @@ pub fn update_codex_config_snippet( } section.insert("wire_api", toml_edit::value(wire_api)); - section.insert( - "requires_openai_auth", - toml_edit::value(requires_openai_auth), - ); - - if requires_openai_auth { - section.remove("env_key"); - } else { - let env_key = non_empty(env_key).unwrap_or("OPENAI_API_KEY"); - section.insert("env_key", toml_edit::value(env_key)); - } } else { if let Some(base_url) = non_empty(base_url) { doc["base_url"] = toml_edit::value(base_url); @@ -1797,13 +1784,6 @@ pub fn update_codex_config_snippet( } doc["wire_api"] = toml_edit::value(wire_api); - doc["requires_openai_auth"] = toml_edit::value(requires_openai_auth); - - if requires_openai_auth { - doc.remove("env_key"); - } else { - doc["env_key"] = toml_edit::value(non_empty(env_key).unwrap_or("OPENAI_API_KEY")); - } } let result = doc.to_string(); @@ -2331,8 +2311,6 @@ env_key = "OLD_API_KEY" "https://new.example.com/v1", "gpt-new", "responses", - true, - "OPENAI_API_KEY", ); let table = toml::from_str::(&updated).expect("parse updated config"); @@ -2352,9 +2330,9 @@ env_key = "OLD_API_KEY" table .get("requires_openai_auth") .and_then(|value| value.as_bool()), - Some(true) + Some(false) ); - assert!(table.get("env_key").is_none()); + assert_eq!(table["env_key"].as_str(), Some("OLD_API_KEY")); assert!(table.get("model_provider").is_none()); assert!(table.get("model_providers").is_none()); } diff --git a/src-tauri/src/live/project/codex.rs b/src-tauri/src/live/project/codex.rs index 7e729597..f95278e7 100644 --- a/src-tauri/src/live/project/codex.rs +++ b/src-tauri/src/live/project/codex.rs @@ -58,7 +58,7 @@ const ROW_TOP_FIELDS: &[&str] = &[ "disable_response_storage", ]; -fn is_built_in_id(id: &str) -> bool { +pub(crate) fn is_built_in_id(id: &str) -> bool { BUILT_IN_IDS.contains(&id) } From 73c6b34f9b2e406fcb00f5248b65525f3d122dc2 Mon Sep 17 00:00:00 2001 From: saladday <1203511142@qq.com> Date: Sun, 25 Oct 2026 15:36:45 +0800 Subject: [PATCH 06/23] test(tui): load Codex preview through provider form --- src-tauri/src/cli/tui/ui/tests.rs | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/src-tauri/src/cli/tui/ui/tests.rs b/src-tauri/src/cli/tui/ui/tests.rs index b34d5419..5fc0ade3 100644 --- a/src-tauri/src/cli/tui/ui/tests.rs +++ b/src-tauri/src/cli/tui/ui/tests.rs @@ -3220,18 +3220,21 @@ fn codex_provider_form_renders_toml_values_in_plaintext() { let mut app = App::new(Some(AppType::Codex)); app.route = Route::Providers; app.focus = Focus::Content; - let mut form = crate::cli::tui::form::ProviderAddFormState::new(AppType::Codex); - form.focus = FormFocus::JsonPreview; - form.codex_preview_section = crate::cli::tui::form::CodexPreviewSection::Config; - form.extra = json!({ - "settingsConfig": { + let provider = crate::provider::Provider::with_id( + "custom".into(), + "Custom".into(), + json!({ "auth": {}, "config": format!( "experimental_bearer_token = \"{secret}\"\nmodel = \"gpt-5.4\"\n\n[cookies]\nsession = \"{plural_container_secret}\"\n" ) - } - }); - form.codex_model.set("gpt-5.4"); + }), + None, + ); + let mut form = + crate::cli::tui::form::ProviderAddFormState::from_provider(AppType::Codex, &provider); + form.focus = FormFocus::JsonPreview; + form.codex_preview_section = crate::cli::tui::form::CodexPreviewSection::Config; app.form = Some(FormState::ProviderAdd(form)); let all = all_text(&render_with_size( From b54a1052752aa05abaca2451f6435dfe408ad57d Mon Sep 17 00:00:00 2001 From: SaladDay Date: Sun, 25 Oct 2026 22:25:41 +0800 Subject: [PATCH 07/23] fix(claude): align configuration editing with upstream (#536) --- README.md | 11 +- README_ZH.md | 11 +- src-tauri/src/cli/commands/config_common.rs | 140 +- src-tauri/src/cli/commands/provider.rs | 113 +- src-tauri/src/cli/commands/provider_input.rs | 4 +- src-tauri/src/cli/tui/app/app_state.rs | 1 + src-tauri/src/cli/tui/app/content_config.rs | 59 + .../src/cli/tui/app/form_handlers/provider.rs | 22 + .../cli/tui/app/overlay_handlers/dialogs.rs | 34 + src-tauri/src/cli/tui/app/tests.rs | 257 +- src-tauri/src/cli/tui/app/types.rs | 5 + src-tauri/src/cli/tui/form.rs | 3 + src-tauri/src/cli/tui/form/provider_json.rs | 129 +- src-tauri/src/cli/tui/form/provider_state.rs | 102 +- .../src/cli/tui/form/provider_templates.rs | 28 + src-tauri/src/cli/tui/form/tests.rs | 568 +--- src-tauri/src/cli/tui/help.rs | 5 +- .../tui/runtime_actions/claude_temp_launch.rs | 10 +- .../src/cli/tui/runtime_actions/editor.rs | 623 +---- src-tauri/src/cli/tui/ui/forms/provider.rs | 17 +- src-tauri/src/cli/tui/ui/forms/shared.rs | 1 + src-tauri/src/cli/tui/ui/overlay/basic.rs | 5 + src-tauri/src/cli/tui/ui/tests.rs | 20 +- .../src/services/provider/claude_editor.rs | 590 +++++ .../provider/claude_editor_service.rs | 162 ++ .../src/services/provider/common_config.rs | 22 +- .../src/services/provider/key_field_live.rs | 37 - src-tauri/src/services/provider/mod.rs | 13 +- src-tauri/src/services/provider/tests.rs | 2313 +++++------------ src-tauri/src/store.rs | 8 +- src-tauri/tests/provider_commands.rs | 10 +- 31 files changed, 2129 insertions(+), 3194 deletions(-) create mode 100644 src-tauri/src/services/provider/claude_editor.rs create mode 100644 src-tauri/src/services/provider/claude_editor_service.rs diff --git a/README.md b/README.md index 42df2157..6d450740 100644 --- a/README.md +++ b/README.md @@ -412,11 +412,14 @@ cc-switch config show # Display configuration cc-switch config path # Show config file paths cc-switch config validate # Validate config file -# Common snippet (shared settings across providers) -# Tries to refresh live config when applicable (`--apply` is kept only as a compatibility flag) +# Claude: open the TUI, edit a provider, then open its JSON editor +cc-switch --app claude +# Read a legacy common snippet to copy into the configuration editor if needed cc-switch --app claude config common show -cc-switch --app claude config common set --snippet '{"env":{"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC":1},"includeCoAuthoredBy":false}' -cc-switch --app claude config common clear + +# Codex / Gemini still support common snippets +cc-switch --app codex config common set --snippet 'model_reasoning_effort = "high"' +cc-switch --app codex config common clear # Backup cc-switch config backup # Create backup (auto-named) diff --git a/README_ZH.md b/README_ZH.md index c660bd60..e6f6f149 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -413,11 +413,14 @@ cc-switch config show # 显示配置 cc-switch config path # 显示配置文件路径 cc-switch config validate # 验证配置文件 -# 通用配置片段(跨所有供应商共享设置) -# 会在适用时尝试刷新 live config(`--apply` 仅保留为兼容参数) +# Claude:进入 TUI,编辑供应商,再打开 JSON 编辑器修改完整配置 +cc-switch --app claude +# 读取旧版通用片段,按需复制到配置编辑器 cc-switch --app claude config common show -cc-switch --app claude config common set --snippet '{"env":{"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC":1},"includeCoAuthoredBy":false}' -cc-switch --app claude config common clear + +# Codex / Gemini 仍支持通用片段 +cc-switch --app codex config common set --snippet 'model_reasoning_effort = "high"' +cc-switch --app codex config common clear # 备份 cc-switch config backup # 创建备份(自动命名) diff --git a/src-tauri/src/cli/commands/config_common.rs b/src-tauri/src/cli/commands/config_common.rs index dc0720ac..4e749d82 100644 --- a/src-tauri/src/cli/commands/config_common.rs +++ b/src-tauri/src/cli/commands/config_common.rs @@ -368,7 +368,7 @@ mod tests { use tempfile::TempDir; use crate::codex_config::{get_codex_config_dir, get_codex_config_path}; - use crate::config::{get_claude_settings_path, read_json_file, write_json_file}; + use crate::config::{get_claude_settings_path, write_json_file}; use crate::provider::{Provider, ProviderMeta}; use crate::services::ProviderService; use crate::test_support::TestEnvGuard; @@ -448,78 +448,19 @@ mod tests { #[test] #[serial] - fn set_stores_claude_snippet_without_enabling_provider_live_config() { - let (_temp_home, _env) = seed_current_claude_provider(); - - set( - AppType::Claude, - Some(r#"{"alwaysThinkingEnabled":false}"#), - None, - false, - ) - .expect("set should succeed"); - - let state = AppState::try_new().expect("reload state"); - let stored = state - .config - .read() - .expect("read config") - .common_config_snippets - .claude - .clone() - .expect("stored claude snippet"); - let stored_json: serde_json::Value = - serde_json::from_str(&stored).expect("stored snippet should be valid JSON"); - assert_eq!(stored_json["alwaysThinkingEnabled"], false); - - let live: serde_json::Value = - read_json_file(&get_claude_settings_path()).expect("read live settings"); - assert!( - live.get("alwaysThinkingEnabled").is_none(), - "setting a new common snippet must not opt the current provider into common config" - ); - } - - #[test] - #[serial] - fn set_updates_live_config_for_common_config_enabled_claude_provider() { - let (_temp_home, _env) = - seed_current_claude_provider_with_meta(Some(common_config_meta(true))); - - set( + fn claude_common_mutations_direct_users_to_the_editor_without_writing() { + let (_home, _env) = seed_current_claude_provider(); + let before = std::fs::read(get_claude_settings_path()).unwrap(); + assert!(set( AppType::Claude, - Some(r#"{"alwaysThinkingEnabled":false}"#), + Some(r#"{"language":"chinese"}"#), None, - false, - ) - .expect("set should succeed"); - - let live: serde_json::Value = - read_json_file(&get_claude_settings_path()).expect("read live settings"); - assert_eq!(live["alwaysThinkingEnabled"], false); - } - - #[test] - #[serial] - fn clear_updates_live_config_even_without_apply_flag() { - let (_temp_home, _env) = seed_current_claude_provider(); - let state = AppState::try_new().expect("reload state"); - - ProviderService::set_common_config_snippet( - &state, - AppType::Claude, - Some(r#"{"alwaysThinkingEnabled":false}"#.to_string()), + true ) - .expect("seed common snippet"); - - clear(AppType::Claude, false).expect("clear should succeed"); - - let live: serde_json::Value = - read_json_file(&get_claude_settings_path()).expect("read live settings"); - assert!( - live.get("alwaysThinkingEnabled").is_none(), - "clearing the common snippet should also clear it from live settings" - ); + .is_err()); + assert!(clear(AppType::Claude, true).is_err()); + assert_eq!(std::fs::read(get_claude_settings_path()).unwrap(), before); + assert!(show(AppType::Claude).is_ok()); } #[test] @@ -605,65 +546,6 @@ mod tests { ); } - #[test] - #[serial] - fn extract_from_settings_config_saves_common_snippet() { - let temp_home = TempDir::new().expect("create temp home"); - let _env = TestEnvGuard::isolated(temp_home.path()); - - extract( - AppType::Claude, - None, - Some( - r#"{ - "env": { - "ANTHROPIC_BASE_URL": "https://provider.example", - "ANTHROPIC_AUTH_TOKEN": "sk-test", - "CC_SWITCH_SHARED": "1" - } - }"#, - ), - None, - true, - ) - .expect("extract should succeed"); - - let state = AppState::try_new().expect("reload state"); - let stored = state - .config - .read() - .expect("read config") - .common_config_snippets - .claude - .clone() - .expect("stored claude snippet"); - let stored_json: serde_json::Value = - serde_json::from_str(&stored).expect("stored snippet should be valid JSON"); - assert_eq!(stored_json["env"]["CC_SWITCH_SHARED"], "1"); - assert!(stored_json["env"].get("ANTHROPIC_AUTH_TOKEN").is_none()); - } - - #[test] - #[serial] - fn extract_from_named_provider_saves_common_snippet() { - let (_temp_home, _env) = seed_current_claude_provider(); - - extract(AppType::Claude, Some("p1"), None, None, true).expect("extract should succeed"); - - let state = AppState::try_new().expect("reload state"); - let stored = state - .config - .read() - .expect("read config") - .common_config_snippets - .claude - .clone() - .expect("stored claude snippet"); - let stored_json: serde_json::Value = - serde_json::from_str(&stored).expect("stored snippet should be valid JSON"); - assert_eq!(stored_json, json!({})); - } - #[test] fn set_rejects_non_object_opencode_common_snippet() { let err = set(AppType::OpenCode, Some("[]"), None, false) diff --git a/src-tauri/src/cli/commands/provider.rs b/src-tauri/src/cli/commands/provider.rs index f61d0730..056b7cf9 100644 --- a/src-tauri/src/cli/commands/provider.rs +++ b/src-tauri/src/cli/commands/provider.rs @@ -1716,7 +1716,7 @@ fn edit_provider(app_type: AppType, id: &str) -> Result<(), AppError> { let manager = config .get_manager(&app_type) .ok_or_else(|| AppError::Message(texts::app_config_not_found(app_type.as_str())))?; - let original = manager + let mut original = manager .providers .get(id) .ok_or_else(|| { @@ -1728,6 +1728,36 @@ fn edit_provider(app_type: AppType, id: &str) -> Result<(), AppError> { let common_snippet = config.common_config_snippets.get(&app_type).cloned(); drop(config); + let claude_editor = if matches!(app_type, AppType::Claude) { + let view = ProviderService::claude_editor_view(&state, &original.settings_config)?; + original.settings_config = view.settings.clone(); + if !view.inactive.is_empty() { + for field in &view.inactive { + println!("{}: {}", field.path.join("."), field.value); + } + if Confirm::new(crate::t!( + "Copy these inactive fields into the editor?", + "将这些未应用字段复制到编辑器?" + )) + .with_default(false) + .prompt() + .map_err(|e| AppError::Message(e.to_string()))? + { + crate::services::provider::claude_editor::copy_inactive_fields( + &mut original.settings_config, + &view.inactive, + ); + } + } + Some(crate::services::provider::claude_editor::EditorSave { + base: view.settings, + draft: None, + on_conflict: Default::default(), + }) + } else { + None + }; + // 2. 显示当前配置 println!("\n{}", highlight(texts::current_config_header())); display_provider_summary(&original, &app_type); @@ -1817,8 +1847,13 @@ fn edit_provider(app_type: AppType, id: &str) -> Result<(), AppError> { return Ok(()); } - // 8. 调用 Service 层(upstream parity:干净写入,无冲突提示) - ProviderService::update(&state, app_type.clone(), updated)?; + if let Some(editor) = claude_editor { + if !save_claude_editor_interactive(&state, &updated, editor, None)? { + return Ok(()); + } + } else { + ProviderService::update(&state, app_type.clone(), updated)?; + } // 9. 成功消息 println!( @@ -1832,6 +1867,56 @@ fn edit_provider(app_type: AppType, id: &str) -> Result<(), AppError> { Ok(()) } +fn save_claude_editor_interactive( + state: &AppState, + provider: &Provider, + mut editor: crate::services::provider::claude_editor::EditorSave, + copy_source: Option<&str>, +) -> Result { + loop { + match ProviderService::save_claude_from_editor( + state, + provider.clone(), + editor.clone(), + copy_source.is_some(), + copy_source, + ) { + Ok(_) => return Ok(true), + Err(error) + if crate::services::provider::claude_editor::conflict_keys(&error).is_some() => + { + let choices = vec![ + crate::t!("Cancel", "取消"), + crate::t!("Keep my changes", "保留我的修改"), + crate::t!("Keep external changes", "保留外部修改"), + ]; + let keys = crate::services::provider::claude_editor::conflict_keys(&error) + .unwrap_or_default() + .join(", "); + let prompt = format!( + "{}: {keys}", + crate::t!( + "Fields changed outside the editor", + "以下字段已被其他程序修改" + ) + ); + let choice = inquire::Select::new(&prompt, choices.clone()) + .prompt() + .map_err(|e| AppError::Message(e.to_string()))?; + use crate::services::provider::claude_editor::ConflictPolicy; + editor.on_conflict = if choice == choices[1] { + ConflictPolicy::KeepMine + } else if choice == choices[2] { + ConflictPolicy::KeepTheirs + } else { + return Ok(false); + }; + } + Err(error) => return Err(error), + } + } +} + fn provider_copy_id(original_id: &str, existing_ids: &[String]) -> String { let base_id = format!("{}-copy", original_id.trim()); if !existing_ids.iter().any(|id| id == &base_id) { @@ -1922,7 +2007,18 @@ fn duplicate_provider_interactive(app_type: AppType, id: &str) -> Result<(), App let common_snippet = config.common_config_snippets.get(&app_type).cloned(); drop(config); - let draft = provider_duplicate_draft(&source, &existing_ids); + let mut draft = provider_duplicate_draft(&source, &existing_ids); + let claude_editor = if matches!(app_type, AppType::Claude) { + let view = ProviderService::claude_editor_view(&state, &draft.settings_config)?; + draft.settings_config = view.settings; + Some(crate::services::provider::claude_editor::EditorSave { + base: view.base_for_new, + draft: None, + on_conflict: Default::default(), + }) + } else { + None + }; println!("\n{}", highlight(texts::current_config_header())); display_provider_summary(&draft, &app_type); @@ -1994,7 +2090,14 @@ fn duplicate_provider_interactive(app_type: AppType, id: &str) -> Result<(), App return Ok(()); } - let duplicate = ProviderService::duplicate(&state, app_type, id, Some(copied))?; + let duplicate = if let Some(editor) = claude_editor { + if !save_claude_editor_interactive(&state, &copied, editor, Some(id))? { + return Ok(()); + } + copied + } else { + ProviderService::duplicate(&state, app_type, id, Some(copied))? + }; println!( "{}", success(&texts::provider_duplicated_success(id, &duplicate.id)) diff --git a/src-tauri/src/cli/commands/provider_input.rs b/src-tauri/src/cli/commands/provider_input.rs index 4a3e873b..c52d9621 100644 --- a/src-tauri/src/cli/commands/provider_input.rs +++ b/src-tauri/src/cli/commands/provider_input.rs @@ -126,7 +126,7 @@ impl SettingsConfigPromptResult { } pub fn supports_common_config(app_type: &AppType) -> bool { - matches!(app_type, AppType::Claude | AppType::Codex | AppType::Gemini) + matches!(app_type, AppType::Codex | AppType::Gemini) } pub fn common_snippet_has_effective_config( @@ -1151,7 +1151,7 @@ requires_openai_auth = true #[test] fn common_config_helpers_detect_and_mark_supported_provider() { - assert!(common_snippet_has_effective_config( + assert!(!common_snippet_has_effective_config( &AppType::Claude, Some(r#"{"env":{"CC_SWITCH_SHARED":"1"}}"#) )); diff --git a/src-tauri/src/cli/tui/app/app_state.rs b/src-tauri/src/cli/tui/app/app_state.rs index 97c15f24..7698e080 100644 --- a/src-tauri/src/cli/tui/app/app_state.rs +++ b/src-tauri/src/cli/tui/app/app_state.rs @@ -489,6 +489,7 @@ impl ConfigItem { pub(crate) fn listed_in_config_menu(&self, app_type: &AppType) -> bool { self.visible_for_app(app_type) + && !(matches!(app_type, AppType::Claude) && matches!(self, ConfigItem::CommonSnippet)) && !matches!( self, ConfigItem::OpenClawWorkspace diff --git a/src-tauri/src/cli/tui/app/content_config.rs b/src-tauri/src/cli/tui/app/content_config.rs index 1f6c1532..c8143222 100644 --- a/src-tauri/src/cli/tui/app/content_config.rs +++ b/src-tauri/src/cli/tui/app/content_config.rs @@ -1529,6 +1529,16 @@ impl App { initial_override: Option, source: CommonSnippetViewSource, ) { + if matches!(app_type, AppType::Claude) { + self.push_toast( + crate::t!( + "Edit Claude settings in the provider configuration editor.", + "请在供应商配置编辑器中修改 Claude 设置。" + ), + ToastKind::Warning, + ); + return; + } let snippet = initial_override.unwrap_or_else(|| { let snippet = self.common_snippet_text_for(&app_type, data); if snippet.trim().is_empty() { @@ -1566,6 +1576,52 @@ impl App { }); } + fn initialize_claude_editor(&mut self, data: &UiData) { + if !matches!(self.app_type, AppType::Claude) { + return; + } + let result = (|| -> Result<(), crate::error::AppError> { + let Some(FormState::ProviderAdd(form)) = self.form.as_mut() else { + return Ok(()); + }; + let mut provider: crate::provider::Provider = + serde_json::from_value(form.to_provider_json_value()) + .map_err(|e| crate::error::AppError::Message(e.to_string()))?; + let current = data + .providers + .rows + .iter() + .find(|row| row.is_current) + .map(|row| &row.provider); + let view = crate::services::provider::claude_editor::view_for_current( + &provider.settings_config, + current, + )?; + provider.settings_config = view.settings.clone(); + form.apply_provider_json_value_to_fields( + serde_json::to_value(&provider) + .map_err(|e| crate::error::AppError::Message(e.to_string()))?, + ) + .map_err(crate::error::AppError::Message)?; + form.claude_inactive = view.inactive; + form.capture_initial_snapshot(); + form.claude_editor = Some(crate::services::provider::claude_editor::EditorSave { + base: if form.mode.is_edit() { + view.settings + } else { + view.base_for_new + }, + draft: None, + on_conflict: Default::default(), + }); + Ok(()) + })(); + if let Err(error) = result { + self.form = None; + self.push_toast(error.to_string(), ToastKind::Error); + } + } + pub(crate) fn open_provider_add_form(&mut self, data: &UiData) { self.filter.active = false; self.overlay = Overlay::None; @@ -1577,6 +1633,7 @@ impl App { &data.config.common_snippet, ), )); + self.initialize_claude_editor(data); self.maybe_show_common_config_notice(); } @@ -1596,6 +1653,7 @@ impl App { &data.config.common_snippet, ), )); + self.initialize_claude_editor(data); self.maybe_show_common_config_notice(); } @@ -1616,6 +1674,7 @@ impl App { &data.existing_provider_ids(), ), )); + self.initialize_claude_editor(data); self.maybe_show_common_config_notice(); } diff --git a/src-tauri/src/cli/tui/app/form_handlers/provider.rs b/src-tauri/src/cli/tui/app/form_handlers/provider.rs index 5178ec77..295c2603 100644 --- a/src-tauri/src/cli/tui/app/form_handlers/provider.rs +++ b/src-tauri/src/cli/tui/app/form_handlers/provider.rs @@ -660,6 +660,28 @@ impl App { } Action::None } + ProviderAddField::ClaudeInactiveFields => { + if matches!(key.code, KeyCode::Enter) { + if let Some(FormState::ProviderAdd(form)) = self.form.as_ref() { + let fields = form + .claude_inactive + .iter() + .map(|field| format!("{}: {}", field.path.join("."), field.value)) + .collect::>() + .join("\n"); + self.overlay = Overlay::Confirm(ConfirmOverlay { + title: crate::t!( + "Copy inactive fields into editor?", + "将未应用字段复制到编辑器?" + ) + .to_string(), + message: fields, + action: ConfirmAction::ClaudeCopyInactive, + }); + } + } + Action::None + } ProviderAddField::CommonSnippet => { if matches!(key.code, KeyCode::Enter) { let Some(FormState::ProviderAdd(provider)) = self.form.as_ref() else { diff --git a/src-tauri/src/cli/tui/app/overlay_handlers/dialogs.rs b/src-tauri/src/cli/tui/app/overlay_handlers/dialogs.rs index 3fe35901..02963897 100644 --- a/src-tauri/src/cli/tui/app/overlay_handlers/dialogs.rs +++ b/src-tauri/src/cli/tui/app/overlay_handlers/dialogs.rs @@ -77,10 +77,44 @@ impl App { return None; }; let confirm = confirm.clone(); + if let ConfirmAction::ClaudeEditorConflict { submit, content } = confirm.action { + use crate::services::provider::claude_editor::ConflictPolicy; + let policy = match key.code { + KeyCode::Char('m') | KeyCode::Char('M') => ConflictPolicy::KeepMine, + KeyCode::Char('t') | KeyCode::Char('T') => ConflictPolicy::KeepTheirs, + KeyCode::Esc => { + self.close_overlay(); + return Some(Action::None); + } + _ => return Some(Action::None), + }; + if let Some(FormState::ProviderAdd(form)) = self.form.as_mut() { + if let Some(editor) = form.claude_editor.as_mut() { + editor.on_conflict = policy; + } + } + self.close_overlay(); + return Some(Action::EditorSubmit { submit, content }); + } let action = match key.code { KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => { let action = match &confirm.action { + ConfirmAction::ClaudeEditorConflict { .. } => Action::None, + ConfirmAction::ClaudeCopyInactive => { + if let Some(FormState::ProviderAdd(form)) = self.form.as_mut() { + let mut value = form.to_provider_json_value(); + crate::services::provider::claude_editor::copy_inactive_fields( + &mut value["settingsConfig"], + &form.claude_inactive, + ); + if let Ok(provider) = serde_json::from_value(value) { + form.apply_provider_json_to_fields(&provider); + form.claude_inactive.clear(); + } + } + Action::None + } ConfirmAction::Quit => Action::Quit, ConfirmAction::ProviderDelete { id } => { Action::ProviderDelete { id: id.clone() } diff --git a/src-tauri/src/cli/tui/app/tests.rs b/src-tauri/src/cli/tui/app/tests.rs index 64bc3bc0..3e0e00bd 100644 --- a/src-tauri/src/cli/tui/app/tests.rs +++ b/src-tauri/src/cli/tui/app/tests.rs @@ -1133,7 +1133,7 @@ mod tests { #[test] fn config_e_key_opens_common_snippet_editor_when_selected() { - let mut app = App::new(Some(AppType::Claude)); + let mut app = App::new(Some(AppType::Gemini)); app.route = Route::Config; app.focus = Focus::Content; app.config_idx = ConfigItem::ALL @@ -1148,7 +1148,7 @@ mod tests { Some(( EditorKind::Json, EditorSubmit::ConfigCommonSnippet { - app_type: AppType::Claude, + app_type: AppType::Gemini, source: CommonSnippetViewSource::Global } )) @@ -4771,7 +4771,7 @@ mod tests { #[test] fn config_common_snippet_opens_editor_directly() { - let mut app = App::new(Some(AppType::Claude)); + let mut app = App::new(Some(AppType::Gemini)); app.route = Route::Config; app.focus = Focus::Content; app.config_idx = ConfigItem::ALL @@ -4786,7 +4786,7 @@ mod tests { Some(( EditorKind::Json, EditorSubmit::ConfigCommonSnippet { - app_type: AppType::Claude, + app_type: AppType::Gemini, source: CommonSnippetViewSource::Global } )) @@ -4911,34 +4911,9 @@ mod tests { assert_eq!(section, super::super::form::CodexPreviewSection::Auth); } - #[test] - fn provider_add_form_common_snippet_row_opens_json_editor_claude() { - let mut app = App::new(Some(AppType::Claude)); - app.route = Route::Providers; - app.focus = Focus::Content; - - let data = data(); - app.on_key(key(KeyCode::Char('a')), &data); - apply_current_provider_template(&mut app, &data); // apply template -> fields - select_provider_common_snippet_row(&mut app); - - let action = app.on_key(key(KeyCode::Enter), &data); - assert!(matches!(action, Action::None)); - assert!(matches!( - app.editor.as_ref().map(|e| (&e.kind, &e.submit)), - Some(( - EditorKind::Json, - EditorSubmit::ConfigCommonSnippet { - app_type: AppType::Claude, - source: CommonSnippetViewSource::ProviderForm - } - )) - )); - } - #[test] fn common_snippet_editor_function_keys_trigger_format_and_extract() { - let mut app = App::new(Some(AppType::Claude)); + let mut app = App::new(Some(AppType::Gemini)); app.route = Route::Providers; app.focus = Focus::Content; @@ -4951,24 +4926,24 @@ mod tests { assert!(matches!( app.on_key(key(KeyCode::F(2)), &data), Action::EditorFormatCommonSnippet { - app_type: AppType::Claude + app_type: AppType::Gemini } )); assert!(matches!( app.on_key(key(KeyCode::F(4)), &data), Action::EditorExtractCommonSnippet { - app_type: AppType::Claude + app_type: AppType::Gemini } )); } #[test] fn global_common_snippet_editor_only_formats_not_extracts() { - let mut app = App::new(Some(AppType::Claude)); + let mut app = App::new(Some(AppType::Gemini)); app.route = Route::Config; app.focus = Focus::Content; app.open_common_snippet_editor( - AppType::Claude, + AppType::Gemini, &data(), Some(r#"{"env":{"COMMON_FLAG":"1"}}"#.to_string()), CommonSnippetViewSource::Global, @@ -4977,7 +4952,7 @@ mod tests { assert!(matches!( app.on_key(key(KeyCode::F(2)), &data()), Action::EditorFormatCommonSnippet { - app_type: AppType::Claude + app_type: AppType::Gemini } )); @@ -5041,7 +5016,7 @@ mod tests { #[test] fn provider_add_form_first_open_shows_common_config_notice_for_supported_apps() { - let mut app = App::new(Some(AppType::Claude)); + let mut app = App::new(Some(AppType::Gemini)); app.route = Route::Providers; app.focus = Focus::Content; app.common_config_notice_confirmed = false; @@ -5060,7 +5035,7 @@ mod tests { #[test] fn provider_add_form_skips_common_config_notice_after_confirmed() { - let mut app = App::new(Some(AppType::Claude)); + let mut app = App::new(Some(AppType::Gemini)); app.route = Route::Providers; app.focus = Focus::Content; @@ -5153,12 +5128,20 @@ mod tests { json!({ "env": { "ANTHROPIC_BASE_URL": "https://example.com", - "ANTHROPIC_AUTH_TOKEN": "sk-demo" + "ANTHROPIC_AUTH_TOKEN": "sk-demo", + "CLAUDE_CODE_MAX_CONTEXT_TOKENS": "120000", + "CLAUDE_CODE_AUTO_COMPACT_WINDOW": "102000" } }), None, ); original.sort_index = Some(4); + manager.current = original.id.clone(); + crate::config::write_json_file( + &crate::config::get_claude_settings_path(), + &original.settings_config, + ) + .expect("write current provider live config"); manager.providers.insert(original.id.clone(), original); let mut existing_copy = Provider::with_id( @@ -5201,6 +5184,15 @@ mod tests { "sk-demo" ); + assert_eq!( + copied.provider.settings_config["env"]["CLAUDE_CODE_MAX_CONTEXT_TOKENS"], + "120000" + ); + assert_eq!( + copied.provider.settings_config["env"]["CLAUDE_CODE_AUTO_COMPACT_WINDOW"], + "102000" + ); + let shifted = refreshed .providers .rows @@ -5212,7 +5204,7 @@ mod tests { #[test] fn provider_copy_confirm_preserves_first_common_config_notice() { - let mut app = App::new(Some(AppType::Claude)); + let mut app = App::new(Some(AppType::Gemini)); app.route = Route::Providers; app.focus = Focus::Content; app.common_config_notice_confirmed = false; @@ -13610,42 +13602,6 @@ mod tests { /// The common-snippet refresh moved into the picker's Enter arm; its /// failure path must still surface as a Warning toast. - #[test] - fn provider_template_picker_enter_warns_on_malformed_common_snippet() { - let mut form = ProviderAddFormState::new(AppType::Claude); - form.include_common_config = true; - - let mut app = App::new(Some(AppType::Claude)); - app.route = Route::Providers; - app.focus = Focus::Content; - app.form = Some(FormState::ProviderAdd(form)); - - let mut data = data(); - data.config.common_snippet = r#"{"env": {"#.to_string(); - app.on_key(key(KeyCode::Enter), &data); - assert!(matches!( - app.overlay, - Overlay::ProviderTemplatePicker { .. } - )); - - // Claude Official, so the apply path is a real template, not a reset. - app.on_key(key(KeyCode::Down), &data); - let action = app.on_key(key(KeyCode::Enter), &data); - assert!(matches!(action, Action::None)); - assert!(matches!(app.overlay, Overlay::None)); - assert_eq!(provider_form_focus(&app), FormFocus::Fields); - assert!( - matches!( - app.toast.as_ref(), - Some(Toast { - kind: ToastKind::Warning, - .. - }) - ), - "expected a Warning toast, got: {:?}", - app.toast - ); - } #[test] fn provider_template_picker_closes_when_form_is_gone() { @@ -16534,7 +16490,7 @@ mod tests { assert!(matches!( claude_app.form, Some(FormState::ProviderAdd(ref form)) - if !form.claude_teammates && !form.include_common_config + if form.claude_teammates && !form.include_common_config )); let codex_snippet = "[features]\ngoals = true\n"; @@ -16572,44 +16528,6 @@ mod tests { )); } - #[test] - fn provider_template_enter_preserves_effective_common_quick_config() { - let cases = [ - ( - AppType::Claude, - r#"{"env":{"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS":"1"}}"#, - ), - (AppType::Codex, "[features]\ngoals = true\n"), - ]; - - for (app_type, common_snippet) in cases { - let mut app = App::new(Some(app_type.clone())); - app.route = Route::Providers; - app.focus = Focus::Content; - app.form = Some(FormState::ProviderAdd( - ProviderAddFormState::new_with_common_snippet(app_type.clone(), common_snippet), - )); - let mut data = data(); - data.config.common_snippet = common_snippet.to_string(); - - // Go through the picker so the apply + common-snippet refresh path - // is genuinely exercised, not just the constructor's seed state. - apply_current_provider_template(&mut app, &data); - assert!(matches!(app.overlay, Overlay::None)); - - let Some(FormState::ProviderAdd(form)) = app.form.as_ref() else { - panic!("expected provider form for {app_type:?}"); - }; - assert_eq!(form.focus, FormFocus::Fields); - assert!(form.include_common_config); - match app_type { - AppType::Claude => assert!(form.claude_teammates), - AppType::Codex => assert!(form.codex_goal_mode), - _ => unreachable!(), - } - } - } - #[test] fn malformed_claude_common_snippet_allows_quick_edit_and_detaches_sharing() { let mut form = ProviderAddFormState::new(AppType::Claude); @@ -20939,3 +20857,114 @@ mod tests { )); } } + +#[test] +#[serial_test::serial] +fn claude_editor_open_projects_live_globals_and_inactive_fields() { + let home = tempfile::TempDir::new().unwrap(); + let _env = crate::test_support::TestEnvGuard::isolated(home.path()); + let live = serde_json::json!({"env":{"ANTHROPIC_AUTH_TOKEN":"current-key","GLOBAL_FLAG":"keep"},"language":"chinese"}); + crate::config::write_json_file(&crate::config::get_claude_settings_path(), &live).unwrap(); + let mut app = App::new(Some(AppType::Claude)); + let data = UiData::default(); + let row = super::data::ProviderRow { + id: "other".into(), + provider: crate::provider::Provider::with_id( + "other".into(), + "Other".into(), + serde_json::json!({"env":{"ANTHROPIC_AUTH_TOKEN":"other-key"},"language":"legacy","legacyOnly":true}), + None, + ), + api_url: None, + is_current: false, + is_in_config: true, + is_saved: true, + is_default_model: false, + primary_model_id: None, + default_model_id: None, + }; + app.open_provider_edit_form(&row, &data); + let Some(FormState::ProviderAdd(form)) = app.form.as_ref() else { + panic!("form should open") + }; + assert_eq!( + form.claude_editor.as_ref().unwrap().base["language"], + "chinese" + ); + assert_eq!( + form.to_provider_json_value()["settingsConfig"]["env"]["ANTHROPIC_AUTH_TOKEN"], + "other-key" + ); + assert_eq!(form.claude_inactive.len(), 2); + assert!(form.to_provider_json_value()["settingsConfig"] + .get("legacyOnly") + .is_none()); + assert!(!form.has_unsaved_changes()); + assert!(!visible_config_items(&app.filter, &app.app_type).contains(&ConfigItem::CommonSnippet)); + let before = std::fs::read(crate::config::get_claude_settings_path()).unwrap(); + app.overlay = Overlay::Confirm(ConfirmOverlay { + title: String::new(), + message: String::new(), + action: ConfirmAction::ClaudeCopyInactive, + }); + app.on_key( + crossterm::event::KeyEvent::new( + crossterm::event::KeyCode::Enter, + crossterm::event::KeyModifiers::NONE, + ), + &data, + ); + let Some(FormState::ProviderAdd(form)) = app.form.as_ref() else { + panic!("form should remain") + }; + assert_eq!( + form.to_provider_json_value()["settingsConfig"]["language"], + "legacy" + ); + assert_eq!( + form.claude_editor.as_ref().unwrap().base["language"], + "chinese" + ); + assert_eq!( + std::fs::read(crate::config::get_claude_settings_path()).unwrap(), + before + ); +} + +#[test] +fn claude_editor_conflict_choices_preserve_the_draft() { + use crate::services::provider::claude_editor::{ConflictPolicy, EditorSave}; + for (key, policy) in [ + ('m', ConflictPolicy::KeepMine), + ('t', ConflictPolicy::KeepTheirs), + ] { + let mut app = App::new(Some(AppType::Claude)); + let mut form = ProviderAddFormState::new(AppType::Claude); + form.claude_editor = Some(EditorSave { + base: serde_json::json!({}), + draft: None, + on_conflict: ConflictPolicy::Refuse, + }); + app.form = Some(FormState::ProviderAdd(form)); + app.overlay = Overlay::Confirm(ConfirmOverlay { + title: String::new(), + message: String::new(), + action: ConfirmAction::ClaudeEditorConflict { + submit: EditorSubmit::ProviderAdd, + content: "draft".into(), + }, + }); + let action = app.on_key( + crossterm::event::KeyEvent::new( + crossterm::event::KeyCode::Char(key), + crossterm::event::KeyModifiers::NONE, + ), + &UiData::default(), + ); + assert!(matches!(action,Action::EditorSubmit{content,..} if content=="draft")); + let Some(FormState::ProviderAdd(form)) = app.form else { + panic!("form should remain") + }; + assert_eq!(form.claude_editor.unwrap().on_conflict, policy); + } +} diff --git a/src-tauri/src/cli/tui/app/types.rs b/src-tauri/src/cli/tui/app/types.rs index 846f434f..632327c2 100644 --- a/src-tauri/src/cli/tui/app/types.rs +++ b/src-tauri/src/cli/tui/app/types.rs @@ -4347,6 +4347,11 @@ impl Toast { #[derive(Debug, Clone)] pub enum ConfirmAction { + ClaudeCopyInactive, + ClaudeEditorConflict { + submit: EditorSubmit, + content: String, + }, Quit, ProviderDelete { id: String, diff --git a/src-tauri/src/cli/tui/form.rs b/src-tauri/src/cli/tui/form.rs index 1d51acac..1d20232f 100644 --- a/src-tauri/src/cli/tui/form.rs +++ b/src-tauri/src/cli/tui/form.rs @@ -318,6 +318,7 @@ pub enum ProviderAddField { HermesRateLimitDelay, CommonConfigDivider, CommonSnippet, + ClaudeInactiveFields, IncludeCommonConfig, UsageQueryDivider, UsageQuery, @@ -541,6 +542,8 @@ pub struct ProviderAddFormState { pub app_type: AppType, pub mode: FormMode, pub copy_source_id: Option, + pub(crate) claude_inactive: Vec, + pub(crate) claude_editor: Option, pub focus: FormFocus, pub page: ProviderFormPage, pub template_idx: usize, diff --git a/src-tauri/src/cli/tui/form/provider_json.rs b/src-tauri/src/cli/tui/form/provider_json.rs index c2086015..a192a4df 100644 --- a/src-tauri/src/cli/tui/form/provider_json.rs +++ b/src-tauri/src/cli/tui/form/provider_json.rs @@ -56,26 +56,7 @@ pub(crate) fn normalize_gemini_common_config_for_form(snippet: &str) -> Result Value { - match value { - Value::Object(entries) => Value::Object( - entries - .into_iter() - .filter(|(key, _)| !CLAUDE_COMMON_CONFIG_FORBIDDEN_KEYS.contains(&key.as_str())) - .map(|(key, value)| (key, sanitize_claude_common_config_value_for_form(value))) - .collect(), - ), - Value::Array(items) => Value::Array( - items - .into_iter() - .map(sanitize_claude_common_config_value_for_form) - .collect(), - ), - value => value, - } -} +const COMMON_CONFIG_FORBIDDEN_KEYS: [&str; 3] = ["__proto__", "constructor", "prototype"]; fn pi_native_string_field_changed( original: Option<&serde_json::Map>, @@ -88,85 +69,12 @@ fn pi_native_string_field_changed( } } -pub(crate) fn sanitize_claude_common_config_for_form(snippet: &str) -> Result { - let value = serde_json::from_str::(snippet) - .map_err(|error| texts::common_config_snippet_invalid_json(&error.to_string()))?; - if !value.is_object() { - return Err(texts::common_config_snippet_not_object().to_string()); - } - Ok(sanitize_claude_common_config_value_for_form(value)) -} - -fn json_value_is_subset_for_form(target: &Value, source: &Value) -> bool { - match source { - Value::Object(source_map) => { - let Some(target_map) = target.as_object() else { - return false; - }; - source_map.iter().all(|(key, source_value)| { - target_map.get(key).is_some_and(|target_value| { - json_value_is_subset_for_form(target_value, source_value) - }) - }) - } - Value::Array(source_array) => { - let Some(target_array) = target.as_array() else { - return false; - }; - target_array.len() == source_array.len() - && target_array - .iter() - .zip(source_array) - .all(|(target_value, source_value)| { - json_value_is_subset_for_form(target_value, source_value) - }) - } - _ => target == source, - } -} - -fn json_deep_remove_for_form(target: &mut Value, source: &Value) { - let (Some(target_map), Some(source_map)) = (target.as_object_mut(), source.as_object()) else { - return; - }; - - for (key, source_value) in source_map { - let mut remove_key = false; - if let Some(target_value) = target_map.get_mut(key) { - if source_value.is_object() && target_value.is_object() { - json_deep_remove_for_form(target_value, source_value); - remove_key = target_value - .as_object() - .is_some_and(serde_json::Map::is_empty); - } else if json_value_is_subset_for_form(target_value, source_value) { - // Upstream's form utility treats arrays as atomic values: it - // removes the field only when length, order, and values all - // match, instead of deleting matching array members. - remove_key = true; - } - } - if remove_key { - target_map.remove(key); - } - } -} - -pub(crate) fn claude_settings_contain_common_config_for_form( - settings: &Value, - common_snippet: &str, -) -> bool { - sanitize_claude_common_config_for_form(common_snippet) - .ok() - .filter(|source| source.as_object().is_some_and(|object| !object.is_empty())) - .is_some_and(|source| json_value_is_subset_for_form(settings, &source)) -} - fn sanitize_toml_common_config_value_for_form(value: toml::Value) -> toml::Value { match value { toml::Value::Table(entries) => toml::Value::Table( entries .into_iter() - .filter(|(key, _)| !CLAUDE_COMMON_CONFIG_FORBIDDEN_KEYS.contains(&key.as_str())) + .filter(|(key, _)| !COMMON_CONFIG_FORBIDDEN_KEYS.contains(&key.as_str())) .map(|(key, value)| (key, sanitize_toml_common_config_value_for_form(value))) .collect(), ), @@ -908,15 +816,6 @@ impl ProviderAddFormState { ProviderService::validate_common_config_snippet_for_preview(&self.app_type, snippet) .map_err(|e| e.to_string())?; - let normalized_claude_snippet = if matches!(self.app_type, AppType::Claude) { - Some( - serde_json::to_string(&sanitize_claude_common_config_for_form(snippet)?) - .map_err(|error| texts::failed_to_serialize_json(&error.to_string()))?, - ) - } else { - None - }; - let snippet = normalized_claude_snippet.as_deref().unwrap_or(snippet); let settings = provider_value .get("settingsConfig") .cloned() @@ -1004,7 +903,19 @@ impl ProviderAddFormState { if should_write_common_config_meta { meta_obj.insert( "commonConfigEnabled".to_string(), - json!(self.include_common_config), + if matches!(self.app_type, AppType::Claude) { + if self.mode.is_edit() { + self.extra + .pointer("/meta/commonConfigEnabled") + .or_else(|| self.extra.pointer("/meta/applyCommonConfig")) + .cloned() + .unwrap_or(json!(true)) + } else { + json!(true) + } + } else { + json!(self.include_common_config) + }, ); } else { meta_obj.remove("commonConfigEnabled"); @@ -1274,7 +1185,8 @@ impl ProviderAddFormState { } fn should_write_common_config_meta(&self) -> bool { - ProviderAddFormState::supports_common_config(&self.app_type) + (ProviderAddFormState::supports_common_config(&self.app_type) + || matches!(self.app_type, AppType::Claude)) && (!self.mode.is_edit() || self.include_common_config_touched || self.has_common_config_meta()) @@ -1500,10 +1412,6 @@ pub(crate) fn strip_common_config_from_settings( } match app_type { - AppType::Claude => { - let source = sanitize_claude_common_config_for_form(snippet)?; - json_deep_remove_for_form(settings_value, &source); - } AppType::Gemini => { *settings_value = ProviderService::remove_common_config_from_settings_for_preview( app_type, @@ -1512,7 +1420,8 @@ pub(crate) fn strip_common_config_from_settings( ) .map_err(|e| e.to_string())?; } - AppType::OpenCode | AppType::Hermes | AppType::OpenClaw | AppType::Pi => {} + AppType::Claude | AppType::OpenCode | AppType::Hermes | AppType::OpenClaw | AppType::Pi => { + } AppType::Codex => { *settings_value = ProviderService::remove_common_config_from_settings_for_preview( app_type, diff --git a/src-tauri/src/cli/tui/form/provider_state.rs b/src-tauri/src/cli/tui/form/provider_state.rs index eaeb0c1f..481d7f27 100644 --- a/src-tauri/src/cli/tui/form/provider_state.rs +++ b/src-tauri/src/cli/tui/form/provider_state.rs @@ -11,9 +11,8 @@ use super::super::text_edit::{ }; use super::provider_json::{ - claude_settings_contain_common_config_for_form, codex_settings_contain_common_config_for_form, - merge_json_values, normalize_gemini_common_config_for_form, - sanitize_claude_common_config_for_form, should_hide_provider_field, + codex_settings_contain_common_config_for_form, merge_json_values, + normalize_gemini_common_config_for_form, should_hide_provider_field, strip_common_config_from_settings, }; use super::provider_state_loading::populate_form_from_provider; @@ -108,16 +107,8 @@ impl ProviderAddFormState { } pub fn new_with_common_snippet(app_type: AppType, common_snippet: &str) -> Self { - let include_common_config = if matches!(app_type, AppType::Claude) { - // The upstream new-provider effect checks the raw object's key - // count before its merge helper skips prototype-pollution keys. - serde_json::from_str::(common_snippet.trim()) - .ok() - .and_then(|value| value.as_object().cloned()) - .is_some_and(|object| !object.is_empty()) - } else { - Self::snippet_has_effective_common_config(&app_type, common_snippet) - }; + let include_common_config = + Self::snippet_has_effective_common_config(&app_type, common_snippet); let is_codex = matches!(app_type, AppType::Codex); let is_gemini = matches!(app_type, AppType::Gemini); let openclaw_api_default = match app_type { @@ -135,6 +126,8 @@ impl ProviderAddFormState { app_type, mode: FormMode::Add, copy_source_id: None, + claude_inactive: Vec::new(), + claude_editor: None, // The template is a field row now, and `fields()` puts it first in // Add mode, so the form opens with it selected. focus: FormFocus::Fields, @@ -350,7 +343,7 @@ impl ProviderAddFormState { } pub fn supports_common_config(app_type: &AppType) -> bool { - matches!(app_type, AppType::Claude | AppType::Codex | AppType::Gemini) + matches!(app_type, AppType::Codex | AppType::Gemini) } pub fn snippet_has_effective_common_config(app_type: &AppType, common_snippet: &str) -> bool { @@ -368,15 +361,15 @@ impl ProviderAddFormState { .parse::() .ok() .is_some_and(|doc| doc.as_table().iter().next().is_some()), - AppType::Claude => sanitize_claude_common_config_for_form(snippet) - .ok() - .and_then(|value| value.as_object().cloned()) - .is_some_and(|obj| !obj.is_empty()), AppType::Gemini => normalize_gemini_common_config_for_form(snippet) .ok() .and_then(|value| value.as_object().cloned()) .is_some_and(|env| !env.is_empty()), - AppType::OpenCode | AppType::Hermes | AppType::OpenClaw | AppType::Pi => false, + AppType::Claude + | AppType::OpenCode + | AppType::Hermes + | AppType::OpenClaw + | AppType::Pi => false, } } @@ -412,9 +405,6 @@ impl ProviderAddFormState { } match app_type { - AppType::Claude => { - claude_settings_contain_common_config_for_form(settings, common_snippet) - } AppType::Codex => { codex_settings_contain_common_config_for_form(settings, common_snippet) } @@ -432,7 +422,11 @@ impl ProviderAddFormState { app_type, settings, &snippet, ) } - AppType::OpenCode | AppType::Hermes | AppType::OpenClaw | AppType::Pi => false, + AppType::Claude + | AppType::OpenCode + | AppType::Hermes + | AppType::OpenClaw + | AppType::Pi => false, } } @@ -448,7 +442,7 @@ impl ProviderAddFormState { } } - fn capture_initial_snapshot(&mut self) { + pub(crate) fn capture_initial_snapshot(&mut self) { self.initial_snapshot = self.to_provider_json_value(); } @@ -584,6 +578,9 @@ impl ProviderAddFormState { } } + if !self.claude_inactive.is_empty() { + fields.push(ProviderAddField::ClaudeInactiveFields); + } if Self::supports_common_config(&self.app_type) { fields.push(ProviderAddField::CommonConfigDivider); fields.push(ProviderAddField::CommonSnippet); @@ -781,6 +778,7 @@ impl ProviderAddFormState { | ProviderAddField::HermesModels | ProviderAddField::HermesAdvancedDivider | ProviderAddField::CommonConfigDivider + | ProviderAddField::ClaudeInactiveFields | ProviderAddField::CommonSnippet | ProviderAddField::IncludeCommonConfig | ProviderAddField::UsageQueryDivider @@ -852,6 +850,7 @@ impl ProviderAddFormState { | ProviderAddField::HermesModels | ProviderAddField::HermesAdvancedDivider | ProviderAddField::CommonConfigDivider + | ProviderAddField::ClaudeInactiveFields | ProviderAddField::CommonSnippet | ProviderAddField::IncludeCommonConfig | ProviderAddField::UsageQueryDivider @@ -1173,7 +1172,7 @@ impl ProviderAddFormState { &mut self, common_snippet: &str, ) -> Result<(), String> { - if !self.include_common_config { + if !Self::supports_common_config(&self.app_type) || !self.include_common_config { return Ok(()); } @@ -2724,6 +2723,12 @@ impl ProviderAddFormState { next.include_common_config_touched = previous_include_common_config_touched; } + if !Self::supports_common_config(&self.app_type) { + next.include_common_config = false; + next.include_common_config_touched = false; + } + next.claude_inactive = self.claude_inactive.clone(); + next.claude_editor = self.claude_editor.clone(); next.mode = previous_mode.clone(); next.copy_source_id = previous_copy_source_id; next.focus = previous_focus; @@ -2833,6 +2838,12 @@ impl ProviderAddFormState { next.include_common_config_touched = previous_include_common_config_touched; } + if !Self::supports_common_config(&self.app_type) { + next.include_common_config = false; + next.include_common_config_touched = false; + } + next.claude_inactive = self.claude_inactive.clone(); + next.claude_editor = self.claude_editor.clone(); next.mode = previous_mode.clone(); next.copy_source_id = previous_copy_source_id; next.focus = previous_focus; @@ -2890,6 +2901,9 @@ impl ProviderAddFormState { } pub fn toggle_include_common_config(&mut self, common_snippet: &str) -> Result<(), String> { + if !Self::supports_common_config(&self.app_type) { + return Ok(()); + } let next_enabled = !self.include_common_config; if next_enabled { Self::validate_common_config_snippet_for_form(&self.app_type, common_snippet)?; @@ -2951,6 +2965,9 @@ impl ProviderAddFormState { previous_snippet: &str, next_snippet: &str, ) -> Result<(), String> { + if !Self::supports_common_config(&self.app_type) { + return Ok(()); + } if !self.include_common_config { if !next_snippet.trim().is_empty() { Self::validate_common_config_snippet_for_form(&self.app_type, next_snippet)?; @@ -2978,34 +2995,17 @@ impl ProviderAddFormState { Self::validate_common_config_snippet_for_form(&self.app_type, next_snippet)?; } - if let Err(previous_error) = - Self::validate_common_config_snippet_for_form(&self.app_type, previous_snippet) + if Self::validate_common_config_snippet_for_form(&self.app_type, previous_snippet).is_err() { - if matches!(self.app_type, AppType::Codex | AppType::Gemini) { - // Upstream skips removal when the previous Codex/Gemini - // snippet cannot be parsed, then applies the valid replacement - // (or simply disables sharing when the snippet was cleared). - let mut next = self.clone(); - next.include_common_config = false; - next.include_common_config_touched = true; - if !next_snippet.trim().is_empty() { - next.include_common_config = true; - next.refresh_quick_config_from_common_snippet(next_snippet)?; - } - *self = next; - return Ok(()); + let mut next = self.clone(); + next.include_common_config = false; + next.include_common_config_touched = true; + if !next_snippet.trim().is_empty() { + next.include_common_config = true; + next.refresh_quick_config_from_common_snippet(next_snippet)?; } - - // Claude ignores the malformed-old removal error when clearing, - // but a non-empty replacement reports it and its membership effect - // turns sharing off against the newly saved snippet. - self.include_common_config = false; - self.include_common_config_touched = true; - return if next_snippet.trim().is_empty() { - Ok(()) - } else { - Err(previous_error) - }; + *self = next; + return Ok(()); } let previous = self.clone(); diff --git a/src-tauri/src/cli/tui/form/provider_templates.rs b/src-tauri/src/cli/tui/form/provider_templates.rs index 3e00f482..32ef1af2 100644 --- a/src-tauri/src/cli/tui/form/provider_templates.rs +++ b/src-tauri/src/cli/tui/form/provider_templates.rs @@ -471,6 +471,34 @@ impl ProviderAddFormState { } pub fn apply_template(&mut self, idx: usize, existing_ids: &[String]) { + let before = self.claude_editor.as_ref().map(|_| self.clone()); + self.apply_template_fields(idx, existing_ids); + if let Some(before) = before { + use crate::live::project::claude::{project_onto, ClaudeProjection}; + let previous = before.to_provider_json_value()["settingsConfig"].clone(); + let mut value = self.to_provider_json_value(); + let result = project_onto( + &crate::config::get_claude_settings_path(), + &previous, + Some(&ClaudeProjection::of(&previous)), + &ClaudeProjection::of(&value["settingsConfig"]), + ) + .map_err(|error| error.to_string()) + .and_then(|settings| { + value["settingsConfig"] = settings; + self.apply_provider_json_value_to_fields(value) + }); + if let Err(message) = result { + *self = before; + self.field_errors.push(super::InlineFieldError { + field: super::ProviderAddField::Template, + message, + }); + } + } + } + + fn apply_template_fields(&mut self, idx: usize, existing_ids: &[String]) { let builtin_defs = provider_builtin_template_defs(&self.app_type); let sponsor_presets = provider_sponsor_presets(&self.app_type); let after_sponsor_defs = provider_after_sponsor_template_defs(&self.app_type); diff --git a/src-tauri/src/cli/tui/form/tests.rs b/src-tauri/src/cli/tui/form/tests.rs index 2ef8b8e7..baf49310 100644 --- a/src-tauri/src/cli/tui/form/tests.rs +++ b/src-tauri/src/cli/tui/form/tests.rs @@ -43,9 +43,8 @@ fn normalize_template_provider_json(mut value: serde_json::Value) -> serde_json: if let Some(obj) = value.as_object_mut() { obj.remove("inFailoverQueue"); if let Some(meta) = obj.get_mut("meta").and_then(|value| value.as_object_mut()) { - if meta.get("commonConfigEnabled") == Some(&json!(false)) { - meta.remove("commonConfigEnabled"); - } + // Compatibility metadata is assigned on save, not part of a template. + meta.remove("commonConfigEnabled"); if meta.is_empty() { obj.remove("meta"); } @@ -1925,7 +1924,7 @@ fn provider_add_form_claude_fields_include_model_config_entry() { } #[test] -fn provider_add_form_claude_places_quick_config_menu_below_common_config() { +fn provider_add_form_claude_places_quick_config_menu_after_model_config() { let form = ProviderAddFormState::new(AppType::Claude); let fields = form.fields(); let pos = |field: ProviderAddField| { @@ -1936,7 +1935,7 @@ fn provider_add_form_claude_places_quick_config_menu_below_common_config() { }; let advanced_divider_idx = pos(ProviderAddField::ClaudeAdvancedDivider); let model_cfg_idx = pos(ProviderAddField::ClaudeModelConfig); - let include_common_idx = pos(ProviderAddField::IncludeCommonConfig); + assert!(!fields.contains(&ProviderAddField::IncludeCommonConfig)); let quick_config_idx = pos(ProviderAddField::ClaudeQuickConfig); let usage_divider_idx = pos(ProviderAddField::UsageQueryDivider); @@ -1945,8 +1944,8 @@ fn provider_add_form_claude_places_quick_config_menu_below_common_config() { "model mapping should sit in the advanced section after the divider" ); assert!( - quick_config_idx == include_common_idx + 1, - "the quick-config menu should sit directly below the add-common-config toggle" + quick_config_idx > model_cfg_idx, + "the quick-config menu follows the model configuration" ); assert!( quick_config_idx < usage_divider_idx, @@ -2008,204 +2007,6 @@ fn provider_add_form_claude_quick_config_menu_opens_and_toggles() { assert!(matches!(form.page, super::ProviderFormPage::Main)); } -#[test] -fn provider_add_form_claude_quick_config_reflects_effective_common_config() { - use crate::provider::ProviderMeta; - - let common_snippet = r#"{ - "attribution": { "commit": "", "pr": "" }, - "env": { - "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1", - "ENABLE_TOOL_SEARCH": "true", - "CLAUDE_CODE_EFFORT_LEVEL": "max", - "DISABLE_AUTOUPDATER": "1" - } - }"#; - - let new_form = ProviderAddFormState::new_with_common_snippet(AppType::Claude, common_snippet); - assert!(new_form.include_common_config); - assert_eq!(new_form.claude_quick_config_enabled_count(), 5); - assert!(new_form.claude_effort_max); - assert!(!new_form.has_unsaved_changes()); - - let mut enabled_later = ProviderAddFormState::new(AppType::Claude); - enabled_later - .toggle_include_common_config(common_snippet) - .expect("common config should enable"); - assert_eq!(enabled_later.claude_quick_config_enabled_count(), 5); - - let mut provider = Provider::with_id( - "provider-1".to_string(), - "Provider One".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "sk-provider", - "ANTHROPIC_BASE_URL": "https://provider.example" - } - }), - None, - ); - provider.meta = Some(ProviderMeta { - apply_common_config: Some(true), - ..Default::default() - }); - - let form = ProviderAddFormState::from_provider_with_common_snippet( - AppType::Claude, - &provider, - common_snippet, - ); - assert_eq!(form.claude_quick_config_enabled_count(), 5); - assert!(!form.has_unsaved_changes()); - - let raw = form.to_provider_json_value(); - assert!(raw["settingsConfig"].get("attribution").is_none()); - assert!(raw["settingsConfig"]["env"] - .get("CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS") - .is_none()); - assert!(raw["settingsConfig"]["env"] - .get("CLAUDE_CODE_EFFORT_LEVEL") - .is_none()); -} - -#[test] -fn provider_edit_form_claude_can_disable_inherited_effort_max() { - use crate::provider::ProviderMeta; - - let common_snippet = r#"{"env":{"CLAUDE_CODE_EFFORT_LEVEL":"max"}}"#; - let mut provider = Provider::with_id( - "provider-1".to_string(), - "Provider One".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "sk-provider", - "ANTHROPIC_BASE_URL": "https://provider.example" - } - }), - None, - ); - provider.meta = Some(ProviderMeta { - apply_common_config: Some(true), - ..Default::default() - }); - - let mut form = ProviderAddFormState::from_provider_with_common_snippet( - AppType::Claude, - &provider, - common_snippet, - ); - assert!(form.claude_effort_max); - assert_eq!(form.claude_quick_config_enabled_count(), 1); - - form.toggle_claude_quick_config_field(ProviderAddField::ClaudeEffortMax, common_snippet) - .expect("inherited max effort should be editable"); - - assert!(!form.include_common_config); - assert!(!form.claude_effort_max); - let raw = form.to_provider_json_value(); - assert_eq!(raw["meta"]["commonConfigEnabled"], false); - assert!(raw["settingsConfig"]["env"] - .get("CLAUDE_CODE_EFFORT_LEVEL") - .is_none()); -} - -#[test] -fn provider_edit_form_claude_can_disable_inherited_quick_config() { - use crate::provider::ProviderMeta; - - let common_snippet = r#"{ - "attribution": { "commit": "", "pr": "" }, - "env": { - "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1", - "ENABLE_TOOL_SEARCH": "true", - "DISABLE_AUTOUPDATER": "1", - "SHARED_FLAG": "keep-me" - } - }"#; - let mut provider = Provider::with_id( - "provider-1".to_string(), - "Provider One".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "sk-provider", - "ANTHROPIC_BASE_URL": "https://provider.example" - } - }), - None, - ); - provider.meta = Some(ProviderMeta { - apply_common_config: Some(true), - ..Default::default() - }); - - let mut form = ProviderAddFormState::from_provider_with_common_snippet( - AppType::Claude, - &provider, - common_snippet, - ); - form.set_main_field_error(ProviderAddField::ClaudeBaseUrl, "invalid base URL"); - form.set_usage_query_field_error(UsageQueryField::ApiKey, "missing query key"); - form.toggle_claude_quick_config_field(ProviderAddField::ClaudeTeammates, common_snippet) - .expect("inherited quick config should be editable"); - - assert!(!form.include_common_config); - assert_eq!(form.claude_quick_config_enabled_count(), 3); - assert!(form.has_unsaved_changes()); - assert_eq!( - form.main_field_error(ProviderAddField::ClaudeBaseUrl), - Some("invalid base URL") - ); - assert_eq!( - form.usage_query_field_error(UsageQueryField::ApiKey), - Some("missing query key") - ); - - let saved = form.to_provider_json_value(); - assert_eq!(saved["meta"]["commonConfigEnabled"], false); - assert!(saved["settingsConfig"]["env"] - .get("CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS") - .is_none()); - assert_eq!(saved["settingsConfig"]["env"]["ENABLE_TOOL_SEARCH"], "true"); - assert_eq!(saved["settingsConfig"]["env"]["SHARED_FLAG"], "keep-me"); - assert_eq!( - saved["settingsConfig"]["attribution"], - json!({ "commit": "", "pr": "" }) - ); - - let saved_provider: Provider = - serde_json::from_value(saved).expect("saved provider should deserialize"); - let reopened = ProviderAddFormState::from_provider_with_common_snippet( - AppType::Claude, - &saved_provider, - common_snippet, - ); - assert!(!reopened.include_common_config); - assert!(!reopened.claude_teammates); - assert!(reopened.claude_hide_attribution); - assert!(reopened.claude_tool_search); - assert!(reopened.claude_disable_auto_upgrade); -} - -#[test] -fn provider_add_form_claude_can_override_conflicting_common_quick_config() { - let common_snippet = r#"{ - "env": { "ENABLE_TOOL_SEARCH": "false", "SHARED_FLAG": "keep-me" } - }"#; - let mut form = ProviderAddFormState::new_with_common_snippet(AppType::Claude, common_snippet); - assert!(form.include_common_config); - assert!(!form.claude_tool_search); - - form.toggle_claude_quick_config_field(ProviderAddField::ClaudeToolSearch, common_snippet) - .expect("conflicting common quick config should be overridable"); - - assert!(!form.include_common_config); - assert!(form.claude_tool_search); - let saved = form.to_provider_json_value(); - assert_eq!(saved["meta"]["commonConfigEnabled"], false); - assert_eq!(saved["settingsConfig"]["env"]["ENABLE_TOOL_SEARCH"], "true"); - assert_eq!(saved["settingsConfig"]["env"]["SHARED_FLAG"], "keep-me"); -} - #[test] fn provider_add_form_codex_collapses_quick_toggles_into_menu() { let mut form = ProviderAddFormState::new(AppType::Codex); @@ -5223,55 +5024,6 @@ fn provider_add_form_has_unsaved_changes_roundtrip_edit_returns_clean() { assert!(!form.has_unsaved_changes()); } -#[test] -fn provider_add_form_common_config_json_merges_into_preview_but_not_raw_submit_payload() { - let mut form = ProviderAddFormState::new(AppType::Claude); - form.id.set("p1"); - form.name.set("Provider One"); - form.include_common_config = true; - form.claude_base_url.set("https://provider.example"); - form.claude_api_key.set("sk-provider"); - - let raw = form.to_provider_json_value(); - let raw_settings = raw - .get("settingsConfig") - .expect("settingsConfig should exist"); - - assert!( - raw_settings.get("alwaysThinkingEnabled").is_none(), - "raw submit payload should not include common snippet scalar keys" - ); - assert_eq!( - raw_settings["env"]["ANTHROPIC_BASE_URL"], "https://provider.example", - "raw submit payload should still include provider-specific fields" - ); - assert_eq!(raw_settings["env"]["ANTHROPIC_AUTH_TOKEN"], "sk-provider"); - - let merged = form - .to_provider_json_value_with_common_config( - r#"{ - "alwaysThinkingEnabled": false, - "env": { - "ANTHROPIC_BASE_URL": "https://common.example", - "COMMON_FLAG": "1" - } - }"#, - ) - .expect("common config should merge"); - let settings = merged - .get("settingsConfig") - .expect("settingsConfig should exist"); - - assert_eq!(settings["alwaysThinkingEnabled"], false); - assert_eq!(settings["env"]["COMMON_FLAG"], "1"); - assert_eq!( - settings["env"]["ANTHROPIC_BASE_URL"], "https://common.example", - "common config should follow backend merge precedence" - ); - assert_eq!(settings["env"]["ANTHROPIC_AUTH_TOKEN"], "sk-provider"); - assert_eq!(merged["meta"]["commonConfigEnabled"], true); -} - #[test] fn provider_add_form_removes_legacy_apply_common_config_alias_from_meta() { let mut form = ProviderAddFormState::new(AppType::Claude); @@ -5376,8 +5128,8 @@ fn provider_add_form_defaults_common_config_from_effective_snippet_only() { r#"{"permissions":{"allow":["Bash"]}}"#, ); assert!( - with_snippet.include_common_config, - "new provider should attach common config when a usable snippet exists" + !with_snippet.include_common_config, + "Claude no longer attaches legacy common snippets" ); let blank_gemini = @@ -5401,7 +5153,7 @@ fn provider_add_form_empty_common_config_toggle_matches_upstream_apps() { claude .toggle_include_common_config("") .expect("upstream Claude permits explicitly enabling an empty snippet"); - assert!(claude.include_common_config); + assert!(!claude.include_common_config); for app_type in [AppType::Codex, AppType::Gemini] { let mut form = ProviderAddFormState::new(app_type); @@ -5489,7 +5241,6 @@ fn gemini_empty_effective_snippet_matches_upstream_ui_state_transitions() { #[test] fn provider_form_disabling_malformed_common_config_matches_upstream_apps() { for (app_type, malformed) in [ - (AppType::Claude, r#"{"env":{"#), (AppType::Codex, "[features\ngoals = true"), (AppType::Gemini, r#"{"BROKEN":"#), ] { @@ -5511,7 +5262,7 @@ fn provider_add_form_empty_content_snippet_replacement_keeps_upstream_enabled_st claude .replace_common_config_snippet(claude_previous, "{}") .expect("valid Claude replacement should succeed"); - assert!(claude.include_common_config); + assert!(!claude.include_common_config); assert!(!claude.claude_tool_search); let codex_previous = "[features]\ngoals = true\n"; @@ -5564,7 +5315,7 @@ fn provider_form_membership_rejects_valid_snippets_without_effective_content() { fn provider_form_array_membership_matches_upstream_ui_exactness() { let claude_snippet = r#"{"permissions":{"allow":["Bash"]}}"#; assert!( - ProviderAddFormState::settings_contain_common_config_for_form( + !ProviderAddFormState::settings_contain_common_config_for_form( &AppType::Claude, &json!({ "permissions": { "allow": ["Bash"] } }), claude_snippet, @@ -5616,89 +5367,6 @@ fn provider_form_array_membership_matches_upstream_ui_exactness() { ); } -#[test] -fn claude_form_common_config_removal_treats_arrays_as_atomic() { - let snippet = r#"{"permissions":{"allow":["Bash"]}}"#; - let mut provider_owned = json!({ - "permissions": { "allow": ["Read", "Bash"] } - }); - strip_common_config_from_settings(&AppType::Claude, &mut provider_owned, snippet) - .expect("valid snippet should be removable"); - assert_eq!( - provider_owned, - json!({ "permissions": { "allow": ["Read", "Bash"] } }) - ); - - let mut exact = json!({ - "permissions": { "allow": ["Bash"] }, - "env": { "PROVIDER_ONLY": "keep" } - }); - strip_common_config_from_settings(&AppType::Claude, &mut exact, snippet) - .expect("exact array should be removable"); - assert_eq!(exact, json!({ "env": { "PROVIDER_ONLY": "keep" } })); -} - -#[test] -fn claude_form_common_config_recursively_ignores_upstream_forbidden_keys() { - let mixed_snippet = r#"{ - "__proto__": {"COMMON": "drop"}, - "env": { - "SAFE": "1", - "constructor": {"COMMON": "drop"}, - "NESTED": [{"prototype": {"COMMON": "drop"}, "keep": "yes"}] - } - }"#; - let settings = json!({ - "__proto__": {"PROVIDER_ONLY": "keep"}, - "env": { - "SAFE": "1", - "constructor": {"PROVIDER_ONLY": "keep"}, - "NESTED": [{"keep": "yes"}] - } - }); - assert!( - ProviderAddFormState::settings_contain_common_config_for_form( - &AppType::Claude, - &settings, - mixed_snippet, - ) - ); - - let mut stripped = settings.clone(); - strip_common_config_from_settings(&AppType::Claude, &mut stripped, mixed_snippet) - .expect("valid sanitized snippet should be removable"); - assert_eq!( - stripped, - json!({ - "__proto__": {"PROVIDER_ONLY": "keep"}, - "env": {"constructor": {"PROVIDER_ONLY": "keep"}} - }) - ); - - let forbidden_only = r#"{"__proto__":{},"constructor":{},"prototype":{}}"#; - assert!( - !ProviderAddFormState::settings_contain_common_config_for_form( - &AppType::Claude, - &json!({}), - forbidden_only, - ) - ); - let mut new_form = - ProviderAddFormState::new_with_common_snippet(AppType::Claude, forbidden_only); - assert!( - new_form.include_common_config, - "upstream's new-form effect checks the raw object before merge filtering" - ); - let effective = new_form - .to_provider_json_value_with_common_config(forbidden_only) - .expect("forbidden-only snippet should be a no-op"); - assert!(effective["settingsConfig"].get("__proto__").is_none()); - new_form - .toggle_claude_quick_config_field(ProviderAddField::ClaudeToolSearch, forbidden_only) - .expect("a later settings edit should succeed"); - assert!(!new_form.include_common_config); -} - #[test] fn provider_edit_form_malformed_snippet_state_matches_upstream_apps() { let mut provider = Provider::with_id( @@ -5713,7 +5381,6 @@ fn provider_edit_form_malformed_snippet_state_matches_upstream_apps() { }); for (app_type, snippet) in [ - (AppType::Claude, r#"{"env":{"#), (AppType::Codex, "[features\ngoals = true"), (AppType::Gemini, r#"{"BROKEN":"#), ] { @@ -5738,7 +5405,7 @@ fn provider_edit_form_valid_empty_snippet_matches_upstream_effect_order() { let claude = ProviderAddFormState::from_provider_with_common_snippet(AppType::Claude, &provider, "{}"); - assert!(claude.include_common_config); + assert!(!claude.include_common_config); let codex = ProviderAddFormState::from_provider_with_common_snippet( AppType::Codex, @@ -5786,11 +5453,6 @@ fn codex_edit_form_preserves_text_fallback_membership_for_malformed_config() { #[test] fn disabled_form_reinfers_membership_after_common_snippet_replacement() { for (app_type, settings, next_snippet) in [ - ( - AppType::Claude, - json!({"env": {"SHARED": "claude"}}), - r#"{"env":{"SHARED":"claude"}}"#, - ), ( AppType::Codex, json!({"config": "[features]\ngoals = true\n"}), @@ -5838,7 +5500,6 @@ fn provider_form_malformed_snippet_replacement_matches_upstream_apps() { assert_eq!(effective["settingsConfig"]["env"]["SHARED"], "next"); for (app_type, malformed) in [ - (AppType::Claude, r#"{"env":{"#), (AppType::Codex, "[features\ngoals = true"), (AppType::Gemini, r#"{"BROKEN":"#), ] { @@ -5851,17 +5512,9 @@ fn provider_form_malformed_snippet_replacement_matches_upstream_apps() { "clearing should disable sharing for {app_type:?}" ); } - - let mut claude = ProviderAddFormState::new(AppType::Claude); - claude.include_common_config = true; - assert!(claude - .replace_common_config_snippet(r#"{"env":{"#, r#"{"env":{"ENABLE_TOOL_SEARCH":"true"}}"#,) - .is_err()); - assert!(!claude.include_common_config); } - #[test] -fn provider_edit_form_preserves_missing_common_config_meta_until_toggle() { +fn provider_edit_form_preserves_missing_common_config_meta_for_legacy_claude() { let provider = Provider::with_id( "legacy-provider".to_string(), "Legacy Provider".to_string(), @@ -5897,71 +5550,7 @@ fn provider_edit_form_preserves_missing_common_config_meta_until_toggle() { ) .expect("toggle should succeed"); let toggled = form.to_provider_json_value(); - assert_eq!(toggled["meta"]["commonConfigEnabled"], true); -} - -#[test] -fn provider_edit_form_missing_meta_inferrs_common_config_from_subset() { - let provider = Provider::with_id( - "legacy-provider".to_string(), - "Legacy Provider".to_string(), - json!({ - "env": { - "ANTHROPIC_BASE_URL": "https://provider.example", - "CC_SWITCH_SHARED": "1" - } - }), - None, - ); - - let form = ProviderAddFormState::from_provider_with_common_snippet( - AppType::Claude, - &provider, - r#"{"env":{"CC_SWITCH_SHARED":"1"}}"#, - ); - - assert!( - form.include_common_config, - "missing-meta edit should infer common config usage when provider settings contain the snippet" - ); - let raw = form.to_provider_json_value(); - assert!( - raw.get("meta") - .and_then(|meta| meta.get("commonConfigEnabled")) - .is_none(), - "inferred missing-meta usage should not force explicit meta until the user toggles" - ); -} - -#[test] -fn provider_edit_form_quick_edit_persists_inferred_common_config_opt_in() { - let common_snippet = r#"{"env":{"CC_SWITCH_SHARED":"1"}}"#; - let provider = Provider::with_id( - "legacy-provider".to_string(), - "Legacy Provider".to_string(), - json!({ - "env": { - "ANTHROPIC_BASE_URL": "https://provider.example", - "CC_SWITCH_SHARED": "1" - } - }), - None, - ); - - let mut form = ProviderAddFormState::from_provider_with_common_snippet( - AppType::Claude, - &provider, - common_snippet, - ); - assert!(form.include_common_config); - - form.toggle_claude_quick_config_field(ProviderAddField::ClaudeToolSearch, common_snippet) - .expect("provider-only quick edit should succeed"); - - let saved = form.to_provider_json_value(); - assert!(form.include_common_config); - assert!(form.claude_tool_search); - assert_eq!(saved["meta"]["commonConfigEnabled"], true); + assert!(toggled["meta"].get("commonConfigEnabled").is_none()); } #[test] @@ -6023,102 +5612,6 @@ fn provider_edit_form_apply_provider_json_keeps_locked_id() { assert_eq!(form.claude_base_url.value, "https://after.example"); } -#[test] -fn provider_add_form_disabling_common_config_strips_common_fields_from_json() { - let mut form = ProviderAddFormState::new(AppType::Claude); - form.id.set("p1"); - form.name.set("Provider One"); - form.include_common_config = true; - - let parsed = Provider::with_id( - "p1".to_string(), - "Provider One".to_string(), - json!({ - "alwaysThinkingEnabled": false, - "statusLine": { - "type": "command", - "command": "~/.claude/statusline.sh", - "padding": 0 - }, - "env": { - "ANTHROPIC_BASE_URL": "https://provider.example" - } - }), - None, - ); - form.apply_provider_json_to_fields(&parsed); - - let common = r#"{ - "alwaysThinkingEnabled": false, - "statusLine": { - "type": "command", - "command": "~/.claude/statusline.sh", - "padding": 0 - } - }"#; - form.toggle_include_common_config(common) - .expect("toggle should succeed"); - - assert!( - !form.include_common_config, - "toggle should disable include_common_config" - ); - let provider = form.to_provider_json_value(); - let settings = provider - .get("settingsConfig") - .expect("settingsConfig should exist"); - assert!( - settings.get("alwaysThinkingEnabled").is_none(), - "common scalar field should be removed after disabling common config" - ); - assert!( - settings.get("statusLine").is_none(), - "common nested field should be removed after disabling common config" - ); -} - -#[test] -fn provider_add_form_disabling_common_config_preserves_provider_specific_env_keys() { - let mut form = ProviderAddFormState::new(AppType::Claude); - form.id.set("p1"); - form.name.set("Provider One"); - form.include_common_config = true; - - let parsed = Provider::with_id( - "p1".to_string(), - "Provider One".to_string(), - json!({ - "env": { - "ANTHROPIC_BASE_URL": "https://common.example", - "ANTHROPIC_AUTH_TOKEN": "sk-provider" - } - }), - None, - ); - form.apply_provider_json_to_fields(&parsed); - - form.toggle_include_common_config(r#"{"env":{"ANTHROPIC_BASE_URL":"https://common.example"}}"#) - .expect("toggle should succeed"); - - let provider = form.to_provider_json_value(); - let env = provider - .get("settingsConfig") - .and_then(|settings| settings.get("env")) - .and_then(|value| value.as_object()) - .expect("env should exist"); - - assert!( - env.get("ANTHROPIC_BASE_URL").is_none(), - "common env keys should be removed" - ); - assert_eq!( - env.get("ANTHROPIC_AUTH_TOKEN") - .and_then(|value| value.as_str()), - Some("sk-provider"), - "provider-specific env keys should be preserved" - ); -} - #[test] fn provider_add_form_opencode_exposes_supported_sponsor_presets() { let form = ProviderAddFormState::new(AppType::OpenCode); @@ -8557,3 +8050,36 @@ fn codex_auth_form_uses_case_sensitive_current_builtin_ids() { } } } + +#[test] +fn claude_editor_context_and_global_values_survive_json_and_template_changes() { + let base = json!({"env":{"ANTHROPIC_AUTH_TOKEN":"key","ANTHROPIC_BASE_URL":"https://old.example","GLOBAL_ENV":"keep"},"language":"chinese","permissions":{"allow":["Read"]}}); + let provider = Provider::with_id("old".into(), "Old".into(), base.clone(), None); + let mut form = ProviderAddFormState::from_provider(AppType::Claude, &provider); + form.claude_editor = Some(crate::services::provider::claude_editor::EditorSave { + base: base.clone(), + draft: None, + on_conflict: Default::default(), + }); + let mut value = form.to_provider_json_value(); + value["settingsConfig"]["language"] = json!("english"); + value["settingsConfig"] + .as_object_mut() + .unwrap() + .remove("permissions"); + form.apply_provider_json_value_to_fields(value).unwrap(); + assert_eq!(form.claude_editor.as_ref().unwrap().base, base); + assert!(form.to_provider_json_value()["settingsConfig"] + .get("permissions") + .is_none()); + form.apply_template(0, &[]); + let settings = &form.to_provider_json_value()["settingsConfig"]; + assert_eq!(settings["language"], "english"); + assert_eq!(settings["env"]["GLOBAL_ENV"], "keep"); + assert!(settings.get("permissions").is_none()); + assert_eq!(form.claude_editor.as_ref().unwrap().base, base); + assert!(!form + .fields() + .contains(&ProviderAddField::IncludeCommonConfig)); + assert!(!form.fields().contains(&ProviderAddField::CommonSnippet)); +} diff --git a/src-tauri/src/cli/tui/help.rs b/src-tauri/src/cli/tui/help.rs index b9462811..10cf71cb 100644 --- a/src-tauri/src/cli/tui/help.rs +++ b/src-tauri/src/cli/tui/help.rs @@ -842,6 +842,7 @@ fn provider_field_help(app_type: AppType, field: ProviderAddField) -> HelpConten "Enables the priority service tier for Codex OAuth requests. It only affects accounts or services that support it.", ), ), + ProviderAddField::ClaudeInactiveFields => HelpContent::new(crate::t!("Inactive fields", "未应用字段"), help_lines("这些旧配置保存在供应商记录中,但不会随切换生效。可以复制到当前编辑内容,检查后保存。", "These legacy values remain in the provider record but are not applied when switching. Copy them into the editor, review, then save.")), ProviderAddField::CommonSnippet => HelpContent::new( texts::tui_config_item_common_snippet(), help_lines( @@ -1079,8 +1080,8 @@ fn provider_preview_help(app_type: AppType, section: Option (AppType::Claude, _) => HelpContent::new( texts::tui_provider_config_title(), help_lines( - "这里预览将保存的供应商配置。Proxy 开启时,Claude 实际读取的 settings.json 会由代理临时接管,因此会显示本地代理地址、占位凭据和模型映射,而不是这里的真实上游配置。按 Enter 可打开编辑器进行高级修改。", - "This previews the stored provider config. While Proxy is on, Claude's live settings.json is temporarily managed by the proxy, so it contains the local proxy URL, placeholder credentials, and model mappings instead of the real upstream config shown here. Press Enter to open the advanced editor.", + "这里展示切到此供应商后的 settings.json。密钥、模型和上下文限制随供应商保存;语言、权限等全局设置按修改直接写盘,编辑其他供应商时也会生效。外部修改发生冲突时会提示选择。代理开启时仍显示真实供应商配置,保存不会覆盖代理地址和占位凭据。按 Enter 编辑。旧通用片段仅保留兼容,可用 config common show 查看后按需复制。", + "This shows settings.json after switching to this provider. Keys, models and context limits belong to the provider; changed global settings such as language and permissions are written immediately, even when editing an inactive provider. Conflicting external edits require a choice. While proxying, the editor shows real provider settings and saving preserves the proxy route. Press Enter to edit. Legacy common snippets remain available through config common show for manual copying.", ), ), _ => HelpContent::new( diff --git a/src-tauri/src/cli/tui/runtime_actions/claude_temp_launch.rs b/src-tauri/src/cli/tui/runtime_actions/claude_temp_launch.rs index f9c76869..7ce4c351 100644 --- a/src-tauri/src/cli/tui/runtime_actions/claude_temp_launch.rs +++ b/src-tauri/src/cli/tui/runtime_actions/claude_temp_launch.rs @@ -380,13 +380,9 @@ mod tests { .expect("create ~/.claude (initialized)"); let state = crate::store::AppState::try_new().expect("create state"); - ProviderService::set_common_config_snippet( - &state, - AppType::Claude, - Some( - r#"{"env":{"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC":1},"includeCoAuthoredBy":false}"# - .to_string(), - ), + state.db.set_config_snippet( + "claude", + Some(r#"{"env":{"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC":1},"includeCoAuthoredBy":false}"#.to_string()), ) .expect("set common config snippet"); diff --git a/src-tauri/src/cli/tui/runtime_actions/editor.rs b/src-tauri/src/cli/tui/runtime_actions/editor.rs index 188481d5..3eff838e 100644 --- a/src-tauri/src/cli/tui/runtime_actions/editor.rs +++ b/src-tauri/src/cli/tui/runtime_actions/editor.rs @@ -992,6 +992,31 @@ fn submit_provider_form_apply_codex_config_toml( Ok(()) } +fn show_claude_editor_conflict( + ctx: &mut RuntimeActionContext<'_>, + error: &AppError, + submit: EditorSubmit, + content: String, +) -> bool { + let Some(keys) = crate::services::provider::claude_editor::conflict_keys(error) else { + return false; + }; + ctx.app.overlay = + crate::cli::tui::app::Overlay::Confirm(crate::cli::tui::app::ConfirmOverlay { + title: crate::t!("Configuration changed", "配置已被修改").to_string(), + message: format!( + "{}\n{}", + crate::t!( + "These fields were changed outside the editor:", + "编辑期间,以下字段被其他程序修改:" + ), + keys.join(", ") + ), + action: crate::cli::tui::app::ConfirmAction::ClaudeEditorConflict { submit, content }, + }); + true +} + fn submit_provider_add( ctx: &mut RuntimeActionContext<'_>, content: String, @@ -1038,7 +1063,23 @@ fn submit_provider_add( }; provider.id = provider_id; - let result = if let Some(copy_source_id) = copy_source_id { + let editor = match ctx.app.form.as_mut() { + Some(FormState::ProviderAdd(form)) => form.claude_editor.as_mut().map(|editor| { + let save = editor.clone(); + editor.on_conflict = Default::default(); + save + }), + _ => None, + }; + let result = if let Some(editor) = editor { + ProviderService::save_claude_from_editor( + &state, + provider, + editor, + true, + copy_source_id.as_deref(), + ) + } else if let Some(copy_source_id) = copy_source_id { ProviderService::duplicate( &state, ctx.app.app_type.clone(), @@ -1063,7 +1104,9 @@ fn submit_provider_add( .push_toast(texts::tui_toast_provider_add_failed(), ToastKind::Error); } Err(err) => { - ctx.app.push_toast(err.to_string(), ToastKind::Error); + if !show_claude_editor_conflict(ctx, &err, EditorSubmit::ProviderAdd, content) { + ctx.app.push_toast(err.to_string(), ToastKind::Error); + } } } @@ -1099,10 +1142,32 @@ fn submit_provider_edit( } let state = load_state()?; - let result = ProviderService::update(&state, ctx.app.app_type.clone(), provider); + let editor = match ctx.app.form.as_mut() { + Some(FormState::ProviderAdd(form)) => form.claude_editor.as_mut().map(|editor| { + let save = editor.clone(); + editor.on_conflict = Default::default(); + save + }), + _ => None, + }; + let result = if let Some(editor) = editor { + ProviderService::save_claude_from_editor(&state, provider, editor, false, None) + } else { + ProviderService::update(&state, ctx.app.app_type.clone(), provider) + }; if let Err(err) = result { - ctx.app.push_toast(err.to_string(), ToastKind::Error); + if !show_claude_editor_conflict( + ctx, + &err, + EditorSubmit::ProviderEdit { + id, + expected_pi_settings_config, + }, + content, + ) { + ctx.app.push_toast(err.to_string(), ToastKind::Error); + } return Ok(()); } @@ -1652,45 +1717,6 @@ mod tests { .is_some_and(|message| message.contains("return"))); } - #[test] - #[serial(home_settings)] - fn provider_json_apply_refreshes_effective_common_quick_config() { - let common_snippet = r#"{"env":{"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS":"1"}}"#; - let mut fixture = runtime_ctx(AppType::Claude); - fixture.data.config.common_snippet = common_snippet.to_string(); - fixture.app.form = Some(FormState::ProviderAdd( - crate::cli::tui::form::ProviderAddFormState::new_with_common_snippet( - AppType::Claude, - common_snippet, - ), - )); - - let mut ctx = runtime_action_ctx(&mut fixture); - super::submit( - &mut ctx, - EditorSubmit::ProviderFormApplyJson, - r#"{ - "env": { - "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1", - "PROVIDER_ONLY": "keep" - } - }"# - .to_string(), - ) - .expect("effective JSON should apply"); - - let Some(FormState::ProviderAdd(form)) = ctx.app.form.as_ref() else { - panic!("expected provider form"); - }; - assert!(form.include_common_config); - assert!(form.claude_teammates); - let raw = form.to_provider_json_value(); - assert!(raw["settingsConfig"]["env"] - .get("CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS") - .is_none()); - assert_eq!(raw["settingsConfig"]["env"]["PROVIDER_ONLY"], "keep"); - } - #[test] #[serial(home_settings)] fn gemini_form_effective_preview_does_not_read_live_settings() { @@ -1802,214 +1828,6 @@ mod tests { assert_eq!(raw["meta"]["commonConfigEnabled"], true); } - #[test] - #[serial(home_settings)] - fn provider_settings_edit_disables_sharing_when_common_values_are_removed() { - { - let claude_snippet = r#"{"env":{"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS":"1"}}"#; - let mut fixture = runtime_ctx(AppType::Claude); - fixture.data.config.common_snippet = claude_snippet.to_string(); - fixture.app.form = Some(FormState::ProviderAdd( - crate::cli::tui::form::ProviderAddFormState::new_with_common_snippet( - AppType::Claude, - claude_snippet, - ), - )); - let mut ctx = runtime_action_ctx(&mut fixture); - super::submit( - &mut ctx, - EditorSubmit::ProviderFormApplyJson, - r#"{"env":{"PROVIDER_ONLY":"keep"}}"#.to_string(), - ) - .expect("Claude JSON should apply"); - let Some(FormState::ProviderAdd(form)) = ctx.app.form.as_ref() else { - panic!("expected Claude provider form"); - }; - assert!(!form.include_common_config); - assert!(!form.claude_teammates); - assert_eq!( - form.to_provider_json_value()["meta"]["commonConfigEnabled"], - false - ); - } - - { - let codex_snippet = "[features]\ngoals = true\n"; - let mut fixture = runtime_ctx(AppType::Codex); - fixture.data.config.common_snippet = codex_snippet.to_string(); - fixture.app.form = Some(FormState::ProviderAdd( - crate::cli::tui::form::ProviderAddFormState::new_with_common_snippet( - AppType::Codex, - codex_snippet, - ), - )); - let mut ctx = runtime_action_ctx(&mut fixture); - super::submit( - &mut ctx, - EditorSubmit::ProviderFormApplyCodexConfigToml, - "model_provider = \"myco\"\n\n[features]\ngoals = false\n\n[model_providers.myco]\nname = \"My Codex\"\nbase_url = \"https://api.example.com/v1\"\nwire_api = \"responses\"\n" - .to_string(), - ) - .expect("Codex TOML should apply"); - let Some(FormState::ProviderAdd(form)) = ctx.app.form.as_ref() else { - panic!("expected Codex provider form"); - }; - assert!(!form.include_common_config); - assert!(!form.codex_goal_mode); - assert_eq!( - form.to_provider_json_value()["meta"]["commonConfigEnabled"], - false - ); - } - } - - #[test] - #[serial(home_settings)] - fn provider_settings_edit_reenables_sharing_when_common_values_are_added() { - { - let common_snippet = r#"{"env":{"SHARED":"claude"}}"#; - let mut fixture = runtime_ctx(AppType::Claude); - fixture.data.config.common_snippet = common_snippet.to_string(); - fixture.app.form = Some(FormState::ProviderAdd( - crate::cli::tui::form::ProviderAddFormState::new(AppType::Claude), - )); - let mut ctx = runtime_action_ctx(&mut fixture); - super::submit( - &mut ctx, - EditorSubmit::ProviderFormApplyJson, - r#"{"env":{"SHARED":"claude","PROVIDER_ONLY":"keep"}}"#.to_string(), - ) - .expect("Claude settings should apply"); - let Some(FormState::ProviderAdd(form)) = ctx.app.form.as_ref() else { - panic!("expected Claude provider form"); - }; - assert!(form.include_common_config); - let raw = form.to_provider_json_value(); - assert!(raw["settingsConfig"]["env"].get("SHARED").is_none()); - assert_eq!(raw["settingsConfig"]["env"]["PROVIDER_ONLY"], "keep"); - } - - { - let common_snippet = "[features]\ngoals = true\n"; - let mut fixture = runtime_ctx(AppType::Codex); - fixture.data.config.common_snippet = common_snippet.to_string(); - fixture.app.form = Some(FormState::ProviderAdd( - crate::cli::tui::form::ProviderAddFormState::new(AppType::Codex), - )); - let mut ctx = runtime_action_ctx(&mut fixture); - super::submit( - &mut ctx, - EditorSubmit::ProviderFormApplyCodexConfigToml, - "model = \"gpt-5.4\"\n\n[features]\ngoals = true\n".to_string(), - ) - .expect("Codex config should apply"); - let Some(FormState::ProviderAdd(form)) = ctx.app.form.as_ref() else { - panic!("expected Codex provider form"); - }; - assert!(form.include_common_config); - let raw = form.to_provider_json_value(); - let raw_config = raw["settingsConfig"]["config"] - .as_str() - .expect("raw Codex config"); - assert!(!crate::codex_config::is_codex_goal_mode_enabled(raw_config)); - } - - { - let common_snippet = r#"{"SHARED":"gemini"}"#; - let mut fixture = runtime_ctx(AppType::Gemini); - fixture.data.config.common_snippet = common_snippet.to_string(); - fixture.app.form = Some(FormState::ProviderAdd( - crate::cli::tui::form::ProviderAddFormState::new(AppType::Gemini), - )); - let mut ctx = runtime_action_ctx(&mut fixture); - super::submit( - &mut ctx, - EditorSubmit::ProviderFormApplyJson, - r#"{"env":{"SHARED":"gemini","PROVIDER_ONLY":"keep"},"config":{}}"#.to_string(), - ) - .expect("Gemini settings should apply"); - let Some(FormState::ProviderAdd(form)) = ctx.app.form.as_ref() else { - panic!("expected Gemini provider form"); - }; - assert!(form.include_common_config); - let raw = form.to_provider_json_value(); - assert!(raw["settingsConfig"]["env"].get("SHARED").is_none()); - assert_eq!(raw["settingsConfig"]["env"]["PROVIDER_ONLY"], "keep"); - } - } - - #[test] - #[serial(home_settings)] - fn provider_settings_edit_with_malformed_snippet_matches_upstream_disable_behavior() { - { - let mut fixture = runtime_ctx(AppType::Claude); - fixture.data.config.common_snippet = r#"{"env":{"#.to_string(); - let mut form = crate::cli::tui::form::ProviderAddFormState::new(AppType::Claude); - form.include_common_config = true; - fixture.app.form = Some(FormState::ProviderAdd(form)); - let mut ctx = runtime_action_ctx(&mut fixture); - super::submit( - &mut ctx, - EditorSubmit::ProviderFormApplyJson, - r#"{"env":{"PROVIDER_ONLY":"keep"}}"#.to_string(), - ) - .expect("Claude settings edit should proceed"); - let Some(FormState::ProviderAdd(form)) = ctx.app.form.as_ref() else { - panic!("expected Claude provider form"); - }; - assert!(!form.include_common_config); - assert_eq!( - form.to_provider_json_value()["settingsConfig"]["env"]["PROVIDER_ONLY"], - "keep" - ); - } - - { - let mut fixture = runtime_ctx(AppType::Codex); - fixture.data.config.common_snippet = "[features\ngoals = true".to_string(); - let mut form = crate::cli::tui::form::ProviderAddFormState::new(AppType::Codex); - form.include_common_config = true; - fixture.app.form = Some(FormState::ProviderAdd(form)); - let mut ctx = runtime_action_ctx(&mut fixture); - super::submit( - &mut ctx, - EditorSubmit::ProviderFormApplyCodexConfigToml, - "model = \"gpt-5.4\"\n".to_string(), - ) - .expect("Codex config edit should proceed"); - let Some(FormState::ProviderAdd(form)) = ctx.app.form.as_ref() else { - panic!("expected Codex provider form"); - }; - assert!(!form.include_common_config); - assert!(form.to_provider_json_value()["settingsConfig"]["config"] - .as_str() - .is_some_and(|config| config.contains("model = \"gpt-5.4\""))); - } - - { - let mut fixture = runtime_ctx(AppType::Gemini); - fixture.data.config.common_snippet = r#"{"BROKEN":"#.to_string(); - let mut form = crate::cli::tui::form::ProviderAddFormState::new(AppType::Gemini); - form.include_common_config = true; - fixture.app.form = Some(FormState::ProviderAdd(form)); - let mut ctx = runtime_action_ctx(&mut fixture); - super::submit( - &mut ctx, - EditorSubmit::ProviderFormApplyJson, - r#"{"env":{"PROVIDER_ONLY":"keep"}}"#.to_string(), - ) - .expect("Gemini settings edit should proceed"); - let Some(FormState::ProviderAdd(form)) = ctx.app.form.as_ref() else { - panic!("expected Gemini provider form"); - }; - assert!(!form.include_common_config); - assert_eq!( - form.to_provider_json_value()["settingsConfig"]["env"]["PROVIDER_ONLY"], - "keep" - ); - } - } - #[test] #[serial(home_settings)] fn submit_local_proxy_headers_keeps_editor_and_previous_state_on_invalid_input() { @@ -2148,75 +1966,6 @@ mod tests { } } - #[test] - #[serial(home_settings)] - fn submit_config_common_snippet_returns_to_form_without_view_overlay() { - let mut fixture = runtime_ctx(AppType::Claude); - let initial_snippet = r#"{"env":{"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS":"1"}}"#; - fixture.app.form = Some(FormState::ProviderAdd( - crate::cli::tui::form::ProviderAddFormState::new_with_common_snippet( - AppType::Claude, - initial_snippet, - ), - )); - - let mut ctx = RuntimeActionContext { - terminal: &mut fixture.terminal, - app: &mut fixture.app, - data: &mut fixture.data, - speedtest_req_tx: None, - stream_check_req_tx: None, - skills_req_tx: None, - proxy_req_tx: None, - proxy_loading: &mut fixture.proxy_loading, - local_env_req_tx: None, - session_req_tx: None, - webdav_req_tx: None, - webdav_loading: &mut fixture.webdav_loading, - update_req_tx: None, - update_check: &mut fixture.update_check, - model_fetch_req_tx: None, - managed_auth_req_tx: None, - }; - - super::submit( - &mut ctx, - EditorSubmit::ConfigCommonSnippet { - app_type: AppType::Claude, - source: crate::cli::tui::app::CommonSnippetViewSource::ProviderForm, - }, - r#"{"env":{"ENABLE_TOOL_SEARCH":"true"}}"#.to_string(), - ) - .expect("common snippet submit should succeed"); - - assert!(ctx.app.editor.is_none()); - assert!(matches!( - ctx.app.overlay, - crate::cli::tui::app::Overlay::None - )); - let Some(FormState::ProviderAdd(form)) = ctx.app.form.as_ref() else { - panic!("expected provider form"); - }; - assert!(!form.claude_teammates); - assert!(form.claude_tool_search); - - super::submit( - &mut ctx, - EditorSubmit::ConfigCommonSnippet { - app_type: AppType::Claude, - source: crate::cli::tui::app::CommonSnippetViewSource::ProviderForm, - }, - String::new(), - ) - .expect("clearing common snippet should succeed"); - let Some(FormState::ProviderAdd(form)) = ctx.app.form.as_ref() else { - panic!("expected provider form"); - }; - assert!(!form.include_common_config); - assert!(!form.claude_teammates); - assert!(!form.claude_tool_search); - } - #[test] #[serial(home_settings)] fn submit_common_snippet_reconciles_malformed_old_codex_form_to_saved_replacement() { @@ -2357,67 +2106,6 @@ mod tests { ); } - #[test] - #[serial(home_settings)] - fn extract_common_snippet_updates_editor_buffer_without_saving() { - let mut fixture = runtime_ctx(AppType::Claude); - - let mut form = crate::cli::tui::form::ProviderAddFormState::new(AppType::Claude); - form.name.set("Provider One"); - form.claude_base_url.set("https://provider.example"); - form.claude_api_key.set("sk-provider"); - form.extra = json!({ - "settingsConfig": { - "env": { - "ANTHROPIC_BASE_URL": "https://provider.example", - "ANTHROPIC_AUTH_TOKEN": "sk-provider", - "COMMON_FLAG": "1" - } - } - }); - fixture.app.form = Some(FormState::ProviderAdd(form)); - fixture.app.open_editor( - "Common Snippet", - crate::cli::tui::app::EditorKind::Json, - "{}", - EditorSubmit::ConfigCommonSnippet { - app_type: AppType::Claude, - source: crate::cli::tui::app::CommonSnippetViewSource::ProviderForm, - }, - ); - - let mut ctx = RuntimeActionContext { - terminal: &mut fixture.terminal, - app: &mut fixture.app, - data: &mut fixture.data, - speedtest_req_tx: None, - stream_check_req_tx: None, - skills_req_tx: None, - proxy_req_tx: None, - proxy_loading: &mut fixture.proxy_loading, - local_env_req_tx: None, - session_req_tx: None, - webdav_req_tx: None, - webdav_loading: &mut fixture.webdav_loading, - update_req_tx: None, - update_check: &mut fixture.update_check, - model_fetch_req_tx: None, - managed_auth_req_tx: None, - }; - - super::extract_common_snippet_into_editor(&mut ctx, AppType::Claude) - .expect("extract common snippet into editor"); - - let content = ctx.app.editor.as_ref().expect("editor remains open").text(); - assert!(content.contains("COMMON_FLAG")); - assert!(!content.contains("ANTHROPIC_BASE_URL")); - assert!(!content.contains("ANTHROPIC_AUTH_TOKEN")); - assert!( - ctx.data.config.common_snippet.trim().is_empty(), - "extracting into the editor should not persist before Ctrl+S" - ); - } - #[test] #[serial(home_settings)] fn submit_prompt_create_persists_prompt_and_refreshes_selection() { @@ -3947,177 +3635,4 @@ mod tests { Some(&Value::String("./workspace-next".to_string())) ); } - - #[test] - #[serial(home_settings)] - fn submit_provider_form_apply_json_keeps_common_snippet_out_of_raw_submit_payload() { - let mut fixture = runtime_ctx(AppType::Claude); - - fixture.data.config.common_snippet = r#"{ - "alwaysThinkingEnabled": false, - "env": { - "COMMON_FLAG": "1" - } - }"# - .to_string(); - - let mut form = crate::cli::tui::form::ProviderAddFormState::new(AppType::Claude); - form.id.set("p1"); - form.name.set("Provider One"); - form.include_common_config = true; - form.claude_base_url.set("https://provider.example"); - fixture.app.form = Some(FormState::ProviderAdd(form)); - - let mut ctx = RuntimeActionContext { - terminal: &mut fixture.terminal, - app: &mut fixture.app, - data: &mut fixture.data, - speedtest_req_tx: None, - stream_check_req_tx: None, - skills_req_tx: None, - proxy_req_tx: None, - proxy_loading: &mut fixture.proxy_loading, - local_env_req_tx: None, - session_req_tx: None, - webdav_req_tx: None, - webdav_loading: &mut fixture.webdav_loading, - update_req_tx: None, - update_check: &mut fixture.update_check, - model_fetch_req_tx: None, - managed_auth_req_tx: None, - }; - - submit_provider_form_apply_json( - &mut ctx, - r#"{ - "alwaysThinkingEnabled": false, - "env": { - "ANTHROPIC_BASE_URL": "https://edited.example", - "COMMON_FLAG": "1", - "EXTRA_FIELD": "kept" - } - }"# - .to_string(), - ) - .expect("apply should succeed"); - - let FormState::ProviderAdd(form) = ctx - .app - .form - .as_ref() - .expect("provider form should remain open") - else { - panic!("expected provider form"); - }; - let settings = form - .to_provider_json_value() - .get("settingsConfig") - .cloned() - .expect("settingsConfig should exist"); - - assert!( - settings.get("alwaysThinkingEnabled").is_none(), - "applying preview JSON should not persist top-level common snippet keys into raw form payload" - ); - assert!( - settings["env"].get("COMMON_FLAG").is_none(), - "applying preview JSON should not persist nested common snippet keys into raw form payload" - ); - assert_eq!( - settings["env"]["ANTHROPIC_BASE_URL"], "https://edited.example", - "provider-specific edits from the preview editor should still be preserved" - ); - assert_eq!( - settings["env"]["EXTRA_FIELD"], "kept", - "non-common keys introduced in the preview editor should still be preserved" - ); - } - - #[test] - #[serial(home_settings)] - fn submit_provider_form_apply_json_materializes_inferred_common_config_state() { - let mut fixture = runtime_ctx(AppType::Claude); - - fixture.data.config.common_snippet = r#"{ - "alwaysThinkingEnabled": false, - "env": { - "COMMON_FLAG": "1" - } - }"# - .to_string(); - - let provider = Provider::with_id( - "legacy-provider".to_string(), - "Legacy Provider".to_string(), - json!({ - "alwaysThinkingEnabled": false, - "env": { - "ANTHROPIC_BASE_URL": "https://provider.example", - "COMMON_FLAG": "1" - } - }), - None, - ); - fixture.app.form = Some(FormState::ProviderAdd( - crate::cli::tui::form::ProviderAddFormState::from_provider(AppType::Claude, &provider), - )); - - let mut ctx = RuntimeActionContext { - terminal: &mut fixture.terminal, - app: &mut fixture.app, - data: &mut fixture.data, - speedtest_req_tx: None, - stream_check_req_tx: None, - skills_req_tx: None, - proxy_req_tx: None, - proxy_loading: &mut fixture.proxy_loading, - local_env_req_tx: None, - session_req_tx: None, - webdav_req_tx: None, - webdav_loading: &mut fixture.webdav_loading, - update_req_tx: None, - update_check: &mut fixture.update_check, - model_fetch_req_tx: None, - managed_auth_req_tx: None, - }; - - submit_provider_form_apply_json( - &mut ctx, - r#"{ - "alwaysThinkingEnabled": false, - "env": { - "ANTHROPIC_BASE_URL": "https://edited.example", - "COMMON_FLAG": "1" - } - }"# - .to_string(), - ) - .expect("apply should succeed"); - - let FormState::ProviderAdd(form) = ctx - .app - .form - .as_ref() - .expect("provider form should remain open") - else { - panic!("expected provider form"); - }; - let raw = form.to_provider_json_value(); - assert_eq!( - raw["meta"]["commonConfigEnabled"], true, - "upstream materializes the inferred common config state when the provider form is edited" - ); - assert!( - raw["settingsConfig"].get("alwaysThinkingEnabled").is_none(), - "materialized sharing keeps common top-level values out of raw provider settings" - ); - assert!( - raw["settingsConfig"]["env"].get("COMMON_FLAG").is_none(), - "materialized sharing keeps common environment values out of raw provider settings" - ); - assert_eq!( - raw["settingsConfig"]["env"]["ANTHROPIC_BASE_URL"], "https://edited.example", - "provider-specific edits from the settings JSON editor should still be preserved" - ); - } } diff --git a/src-tauri/src/cli/tui/ui/forms/provider.rs b/src-tauri/src/cli/tui/ui/forms/provider.rs index dcfdb223..ce848c59 100644 --- a/src-tauri/src/cli/tui/ui/forms/provider.rs +++ b/src-tauri/src/cli/tui/ui/forms/provider.rs @@ -232,13 +232,15 @@ fn common_json_preview_value(app_type: &AppType, common_snippet: &str) -> Option } match app_type { - AppType::Claude => serde_json::from_str::(common_snippet).ok(), AppType::Gemini => serde_json::from_str::(common_snippet) .ok() .map(|env| json!({ "env": env })), - AppType::Codex | AppType::OpenCode | AppType::Hermes | AppType::OpenClaw | AppType::Pi => { - None - } + AppType::Claude + | AppType::Codex + | AppType::OpenCode + | AppType::Hermes + | AppType::OpenClaw + | AppType::Pi => None, } .filter(Value::is_object) } @@ -2017,6 +2019,9 @@ pub(crate) fn provider_field_label_and_value( ProviderAddField::CodexAdvancedDivider => "- - - - - - - - -".to_string(), ProviderAddField::HermesAdvancedDivider => "- - - - - - - - -".to_string(), ProviderAddField::CommonConfigDivider => "- - - - - - - - -".to_string(), + ProviderAddField::ClaudeInactiveFields => { + crate::t!("Inactive fields", "未应用字段").to_string() + } ProviderAddField::CommonSnippet => texts::tui_config_item_common_snippet().to_string(), ProviderAddField::IncludeCommonConfig => texts::tui_form_attach_common_config().to_string(), ProviderAddField::UsageQueryDivider => "- - - - - - - - -".to_string(), @@ -2168,7 +2173,9 @@ pub(crate) fn provider_field_label_and_value( } ProviderAddField::HermesAdvancedDivider => "- - - - - - - - - -".to_string(), ProviderAddField::CommonConfigDivider => "- - - - - - - - - -".to_string(), - ProviderAddField::CommonSnippet => format!("{} ›", texts::tui_key_open()), + ProviderAddField::ClaudeInactiveFields | ProviderAddField::CommonSnippet => { + format!("{} ›", texts::tui_key_open()) + } ProviderAddField::UsageQueryDivider => String::new(), ProviderAddField::TemplateDivider => String::new(), // Plain-text fallback; the row itself renders chip-styled spans and diff --git a/src-tauri/src/cli/tui/ui/forms/shared.rs b/src-tauri/src/cli/tui/ui/forms/shared.rs index 398d2e3c..91e96694 100644 --- a/src-tauri/src/cli/tui/ui/forms/shared.rs +++ b/src-tauri/src/cli/tui/ui/forms/shared.rs @@ -44,6 +44,7 @@ pub(crate) fn add_form_key_items( | ProviderAddField::CodexOAuthAccount | ProviderAddField::CodexLocalRouting | ProviderAddField::LocalProxySettings + | ProviderAddField::ClaudeInactiveFields | ProviderAddField::CommonSnippet | ProviderAddField::UsageQuery | ProviderAddField::OpenClawModels diff --git a/src-tauri/src/cli/tui/ui/overlay/basic.rs b/src-tauri/src/cli/tui/ui/overlay/basic.rs index f6f486b9..8286f240 100644 --- a/src-tauri/src/cli/tui/ui/overlay/basic.rs +++ b/src-tauri/src/cli/tui/ui/overlay/basic.rs @@ -45,6 +45,11 @@ pub(super) fn render_confirm_overlay( confirm: &crate::cli::tui::app::ConfirmOverlay, ) { let keys: &[(&str, &str)] = match &confirm.action { + ConfirmAction::ClaudeEditorConflict { .. } => &[ + ("M", crate::t!("Keep mine", "保留我的修改")), + ("T", crate::t!("Keep external", "保留外部修改")), + ("Esc", texts::tui_key_cancel()), + ], ConfirmAction::EditorSaveBeforeClose | ConfirmAction::FormSaveBeforeClose => &[ ("Enter", texts::tui_key_save_and_exit()), ("N", texts::tui_key_exit_without_save()), diff --git a/src-tauri/src/cli/tui/ui/tests.rs b/src-tauri/src/cli/tui/ui/tests.rs index 5fc0ade3..fe77a81e 100644 --- a/src-tauri/src/cli/tui/ui/tests.rs +++ b/src-tauri/src/cli/tui/ui/tests.rs @@ -4405,11 +4405,11 @@ fn provider_form_fields_show_dashed_divider_before_common_snippet() { let _lock = lock_env(); let _no_color = EnvGuard::remove("NO_COLOR"); - let mut app = App::new(Some(AppType::Claude)); + let mut app = App::new(Some(AppType::Gemini)); app.route = Route::Providers; app.focus = Focus::Content; app.form = Some(crate::cli::tui::form::FormState::ProviderAdd( - crate::cli::tui::form::ProviderAddFormState::new(AppType::Claude), + crate::cli::tui::form::ProviderAddFormState::new(AppType::Gemini), )); let data = minimal_data(&app.app_type); @@ -4507,20 +4507,18 @@ fn provider_form_json_preview_highlights_common_config_lines() { let _lock = lock_env(); let _no_color = EnvGuard::remove("NO_COLOR"); - let mut app = App::new(Some(AppType::Claude)); + let mut app = App::new(Some(AppType::Gemini)); app.route = Route::Providers; app.focus = Focus::Content; - let mut form = crate::cli::tui::form::ProviderAddFormState::new(AppType::Claude); + let mut form = crate::cli::tui::form::ProviderAddFormState::new(AppType::Gemini); form.focus = FormFocus::JsonPreview; form.include_common_config = true; - form.claude_api_key.set("sk-provider"); + form.gemini_api_key.set("sk-provider"); app.form = Some(FormState::ProviderAdd(form)); let mut data = minimal_data(&app.app_type); data.config.common_snippet = r#"{ - "env": { - "COMMON_FLAG": "1" - } + "COMMON_FLAG": "1" }"# .to_string(); @@ -4535,7 +4533,7 @@ fn provider_form_json_preview_highlights_common_config_lines() { common_bg = Some(buf[(x, y)].bg); common_indent_bg = x.checked_sub(1).map(|indent_x| buf[(indent_x, y)].bg); } - if let Some(x) = cell_column_of(&buf, y, "\"ANTHROPIC_AUTH_TOKEN\"") { + if let Some(x) = cell_column_of(&buf, y, "\"GEMINI_API_KEY\"") { provider_key_bg = Some(buf[(x, y)].bg); } } @@ -4930,7 +4928,7 @@ fn configuration_page_groups_actions_with_three_unlabeled_dividers() { let _lang = use_test_language(Language::English); let _no_color = EnvGuard::remove("NO_COLOR"); - let mut app = App::new(Some(AppType::Claude)); + let mut app = App::new(Some(AppType::Gemini)); app.route = Route::Config; app.focus = Focus::Content; @@ -4965,7 +4963,7 @@ fn configuration_page_hides_dividers_while_filtering() { let _lang = use_test_language(Language::English); let _no_color = EnvGuard::remove("NO_COLOR"); - let mut app = App::new(Some(AppType::Claude)); + let mut app = App::new(Some(AppType::Gemini)); app.route = Route::Config; app.focus = Focus::Content; app.filter.input.set("config".to_string()); diff --git a/src-tauri/src/services/provider/claude_editor.rs b/src-tauri/src/services/provider/claude_editor.rs new file mode 100644 index 00000000..f3b2ed32 --- /dev/null +++ b/src-tauri/src/services/provider/claude_editor.rs @@ -0,0 +1,590 @@ +//! Claude Code 供应商编辑器:底部 JSON 就是「切到这个供应商之后 settings.json 的样子」。 +//! +//! - 显示:在内存里对当前 live 做一次切换投影,和切换用同一个补丁:关键字段、独有字段 +//! 换成这个供应商的,其余部分是 live 原样。编辑当前的、非当前的、新增的供应商都一样。 +//! - 保存:关键字段、独有字段写回这个供应商的行(行里其余内容原样保留);其余部分的改动 +//! 是 Claude Code 的全局设置,经引擎写进 live,只改用户动过的键。编辑的是直连模式下的 +//! 当前供应商时,关键字段和独有字段在同一次写入里也换进 live。 +//! - 三方比较:每个改动都带着打开编辑器时的原值。live 里这个键已经被别的程序改成了第三个 +//! 值,就算冲突,由用户选保留哪一边;没改过的键不提交,也就不会覆盖别人的改动。 + +use std::path::Path; + +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +use crate::app_config::AppType; +use crate::database::Database; +use crate::error::AppError; +use crate::live::engine::read_current; +use crate::live::floor; +use crate::live::patch::json::{self as patch_json, JsonPatch}; +use crate::live::patch::{KeyPath, LivePatch, LiveWriteError}; +use crate::live::project::claude::{direct_patch, project_onto, store_into_row, ClaudeProjection}; +use crate::mode::operation::{AppWrite, FileChange}; +use crate::mode::state::{op, PendingTarget}; +use crate::provider::Provider; +use crate::store::AppState; + +fn settings_file() -> crate::live::engine::LiveFile { + crate::live::engine::LiveFile::private(crate::config::get_claude_settings_path()) +} + +/// 旧版存在 settings 里的内部字段:从不写进 live,也不算「不随切换生效的字段」。 +const INTERNAL_TOP: &[&str] = &[ + "api_format", + "apiFormat", + "openrouter_compat_mode", + "openrouterCompatMode", +]; + +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct EditorView { + /// 编辑器里显示的完整配置。 + pub settings: Value, + /// New/copy dialogs compare against the same live snapshot before applying their draft. + #[serde(skip)] + pub(crate) base_for_new: Value, + /// 行里保存着、但不随切换生效的字段(值和显示的不同才列出)。 + pub inactive: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct InactiveField { + /// 键路径,比如 `["env", "API_TIMEOUT_MS"]`、`["hooks"]`。 + pub path: Vec, + pub value: Value, +} + +/// Copy explicitly selected legacy values into an editor draft, without writing files. +pub(crate) fn copy_inactive_fields(settings: &mut Value, fields: &[InactiveField]) { + for field in fields { + let Some((last, parents)) = field.path.split_last() else { + continue; + }; + let mut target = &mut *settings; + for key in parents { + if !target[key].is_object() { + target[key] = Value::Object(Map::new()); + } + target = &mut target[key]; + } + target[last] = field.value.clone(); + } +} + +/// live 里的键在编辑期间被别的程序改过时怎么办。 +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum ConflictPolicy { + /// 报冲突,什么都不写。 + #[default] + Refuse, + /// 用编辑器里的值覆盖。 + KeepMine, + /// 冲突的键保留外部的值,其余改动照常写。 + KeepTheirs, +} + +pub(crate) fn conflict_keys(error: &AppError) -> Option> { + let AppError::Message(message) = error else { + return None; + }; + let value: Value = serde_json::from_str(message).ok()?; + if value["code"] != crate::live::patch::EDIT_CONFLICT_CODE { + return None; + } + serde_json::from_value(value["keys"].clone()).ok() +} + +impl ConflictPolicy { + /// 三方比较:`conflict` 给出冲突改动的显示名(live 里现在的值既不是打开编辑器时的, + /// 也不是要写的)。有冲突时按策略整体拒绝、跳过冲突的改动或照写;返回要写的改动。 + pub(crate) fn resolve<'c, C>( + self, + path: &Path, + changes: &'c [C], + conflict: impl Fn(&C) -> Option, + ) -> Result, LiveWriteError> { + let mut conflicts = Vec::new(); + let mut accepted = Vec::new(); + for change in changes { + if let Some(key) = conflict(change) { + conflicts.push(key); + if self == Self::KeepTheirs { + continue; + } + } + accepted.push(change); + } + if !conflicts.is_empty() && self == Self::Refuse { + return Err(LiveWriteError::EditConflict { + path: path.to_path_buf(), + keys: conflicts, + }); + } + Ok(accepted) + } +} + +/// 编辑器保存时随供应商一起提交的上下文。 +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct EditorSave { + /// 打开编辑器时显示的完整配置(新增对话框里是还没套预设的 live)。 + pub base: Value, + /// 新增对话框(Codex、Gemini CLI、Grok Build):投影成 `base` 的那份草稿(预设或模板)。 + /// 显示里有、草稿里没有的独有字段是从 live 带进来的,不归新供应商。 + #[serde(default)] + pub draft: Option, + #[serde(default)] + pub on_conflict: ConflictPolicy, +} + +/// 编辑器显示的内容。`settings_config` 是这个供应商的行(新增时是空对象)。 +pub fn view(state: &AppState, settings_config: &Value) -> Result { + let current = crate::settings::get_effective_current_provider(&state.db, &AppType::Claude)? + .map(|id| state.db.get_provider_by_id(&id, "claude")) + .transpose()? + .flatten(); + view_for_current(settings_config, current.as_ref()) +} + +/// The TUI already has the current provider in its provider-list snapshot. +pub(crate) fn view_for_current( + settings_config: &Value, + current: Option<&Provider>, +) -> Result { + let file = settings_file(); + let pre = read_current(&file.path)?; + let (live, _) = patch_json::parse(&file.path, pre.as_deref())?; + let mode = + crate::mode::state::mode_state(&crate::live::engine::DeviceStore::for_device(), "claude")?; + let prev = if mode.attached { + mode.contract + .map(|contract| ClaudeProjection { + exclusive: contract.exclusive, + ..Default::default() + }) + .or_else(|| current.map(|row| ClaudeProjection::of(&row.settings_config))) + } else { + current.map(|row| ClaudeProjection::of(&row.settings_config)) + }; + let settings = project_onto( + &file.path, + &live, + prev.as_ref(), + &ClaudeProjection::of(settings_config), + )?; + Ok(EditorView { + base_for_new: project_onto( + &file.path, + &live, + prev.as_ref(), + &ClaudeProjection::default(), + )?, + inactive: inactive_fields(settings_config, &settings), + settings, + }) +} + +fn inactive_fields(row: &Value, display: &Value) -> Vec { + let mut fields = Vec::new(); + if let Some(root) = row.as_object() { + for (key, value) in root { + if key == "env" || floor::claude_floor_top(key) || INTERNAL_TOP.contains(&key.as_str()) + { + continue; + } + if display.get(key) != Some(value) { + fields.push(InactiveField { + path: vec![key.clone()], + value: value.clone(), + }); + } + } + } + if let Some(env) = row.get("env").and_then(Value::as_object) { + for (key, value) in env { + if floor::claude_floor_env(key) || floor::claude_exclusive_env(key) { + continue; + } + if display.get("env").and_then(|env| env.get(key)) != Some(value) { + fields.push(InactiveField { + path: vec!["env".to_string(), key.clone()], + value: value.clone(), + }); + } + } + } + fields +} + +/// 编辑器里对 JSON 全局设置的一处改动。 +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct JsonChange { + pub path: KeyPath, + /// 打开编辑器时的值;`None` 表示当时没有这个键。 + pub before: Option, + /// 保存的值;`None` 表示删掉。 + pub after: Option, +} + +impl JsonChange { + /// live 里这个位置现在是 `now`:既不是打开编辑器时的值,也不是要写的值。 + pub(crate) fn conflicts_with(&self, now: Option<&Value>) -> Option { + (now != self.before.as_ref() && now != self.after.as_ref()).then(|| self.path.to_string()) + } + + /// 把要写的改动收成一个补丁。 + pub(crate) fn patch(changes: &[&Self]) -> JsonPatch { + let mut patch = JsonPatch::default(); + for change in changes { + match &change.after { + Some(value) => patch.set.push((change.path.clone(), value.clone())), + None => patch.remove.push(change.path.clone()), + } + } + patch + } +} + +/// 一次编辑器保存:存进行的内容,和要写进 live 的全局改动。 +#[derive(Debug, Clone)] +pub(crate) struct EditorPlan { + pub row_settings: Value, + changes: Vec, +} + +/// 把编辑器里的完整配置拆开:关键字段、独有字段换进 `stored_row`(新增时为 `None`), +/// 其余部分和 `base` 比,得出用户改过的全局设置。 +/// +/// 显示里有、行里没有的独有字段是从 live 带进来的(用户自己写的,或者上一家留下、值被 +/// 改过的),不归这个供应商:用户没动就不收进行,否则切走时会把用户自己的设置删掉;用户 +/// 删了就从 live 删。新增对话框的 `base` 是还没套预设的 live,预设带的独有字段不在里面。 +pub(crate) fn plan_save( + stored_row: Option<&Value>, + edited: &Value, + base: &Value, +) -> Result { + for (name, doc) in [("edited", edited), ("base", base)] { + let shaped = doc.is_object() + && doc + .get("env") + .is_none_or(|env| env.is_object() || env.is_null()); + if !shaped { + return Err(AppError::localized( + "provider.claude.editor.invalid_shape", + format!("Claude 配置必须是 JSON 对象,env 也必须是对象({name})"), + format!("Claude configuration and its env must be JSON objects ({name})"), + )); + } + } + let empty = Value::Object(Map::new()); + let stored = stored_row.unwrap_or(&empty); + let env_value = |doc: &Value, key: &str| doc.get("env").and_then(|env| env.get(key)).cloned(); + let from_live: Vec = base + .get("env") + .and_then(Value::as_object) + .into_iter() + .flat_map(Map::keys) + .filter(|key| floor::claude_exclusive_env(key) && env_value(stored, key).is_none()) + .cloned() + .collect(); + + let mut projection = ClaudeProjection::of(edited); + projection.exclusive.retain(|key, value| { + !from_live.contains(key) || env_value(base, key).as_ref() != Some(value) + }); + let removed_from_live: Vec = from_live + .into_iter() + .filter(|key| env_value(edited, key).is_none()) + .collect(); + Ok(EditorPlan { + row_settings: store_into_row(stored, &projection), + changes: global_changes(base, edited, &removed_from_live), + }) +} + +/// `removed_from_live`:用户删掉的、从 live 带进来的独有字段,从 live 删。其余独有字段 +/// 归供应商行,不算全局改动。 +fn global_changes(base: &Value, edited: &Value, removed_from_live: &[String]) -> Vec { + let top = |doc: &Value| doc.as_object().cloned().unwrap_or_default(); + let env = |doc: &Value| { + doc.get("env") + .and_then(Value::as_object) + .cloned() + .unwrap_or_default() + }; + + let mut changes = Vec::new(); + diff_level( + &KeyPath::root(), + &top(base), + &top(edited), + |key| key == "env" || floor::claude_floor_top(key) || INTERNAL_TOP.contains(&key), + &mut changes, + ); + diff_level( + &KeyPath::new(&["env"]), + &env(base), + &env(edited), + |key| { + floor::claude_floor_env(key) + || (floor::claude_exclusive_env(key) + && !removed_from_live.iter().any(|removed| removed == key)) + }, + &mut changes, + ); + changes +} + +/// 同一层里改过的键:先按原有顺序,新加的键按编辑器里的顺序排在后面。 +fn diff_level( + parent: &KeyPath, + before: &Map, + after: &Map, + skip: impl Fn(&str) -> bool, + changes: &mut Vec, +) { + let keys = before + .keys() + .chain(after.keys().filter(|key| !before.contains_key(*key))); + for key in keys { + if skip(key) || before.get(key) == after.get(key) { + continue; + } + changes.push(JsonChange { + path: parent.child(key), + before: before.get(key).cloned(), + after: after.get(key).cloned(), + }); + } +} + +struct EditorPatch<'a> { + changes: &'a [JsonChange], + on_conflict: ConflictPolicy, + key_fields: Option, +} + +impl LivePatch for EditorPatch<'_> { + fn apply(&self, path: &Path, pre: Option<&[u8]>) -> Result, LiveWriteError> { + let (mut doc, style) = patch_json::parse(path, pre)?; + let accepted = self.on_conflict.resolve(path, self.changes, |change| { + change.conflicts_with(patch_json::value_at(&doc, &change.path)) + })?; + JsonChange::patch(&accepted).apply_to(path, &mut doc)?; + if let Some(key_fields) = &self.key_fields { + key_fields.apply_to(path, &mut doc)?; + } + patch_json::serialize(path, &doc, &style) + } +} + +/// 要不要在同一次写入里把关键字段也换进 live。 +pub(crate) struct KeyFieldWrite<'a> { + /// live 现在对应的那一版行(编辑前的行;新增第一个供应商时为 `None`)。 + pub prev: Option<&'a Provider>, + pub target: &'a Provider, + /// 同时把当前供应商改成 `target`(新增第一个供应商)。 + pub set_pointer: bool, +} + +/// 把编辑器保存的改动写进 live。没有要写的就什么都不做。 +pub(crate) fn write_live( + db: &Database, + plan: &EditorPlan, + on_conflict: ConflictPolicy, + key_fields: Option>, +) -> Result<(), AppError> { + if plan.changes.is_empty() && key_fields.is_none() { + return Ok(()); + } + let pointer = key_fields + .as_ref() + .filter(|write| write.set_pointer) + .map(|write| write.target.id.clone()); + let key_patch = key_fields.map(|write| { + let prev = write + .prev + .map(|provider| ClaudeProjection::of(&provider.settings_config)); + direct_patch( + prev.as_ref(), + &ClaudeProjection::of(&write.target.settings_config), + ) + }); + let patch = EditorPatch { + changes: &plan.changes, + on_conflict, + key_fields: key_patch, + }; + + // 关键字段的补丁是按调用方读到的行算的:先补完上一次的操作。 + AppWrite::begin(db, AppType::Claude.as_str())?.run( + if pointer.is_some() { + op::SWITCH + } else { + op::APPLY + }, + &[FileChange { + file: settings_file(), + patch: &patch, + }], + PendingTarget::pointer(pointer), + )?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn apply( + changes: &[JsonChange], + policy: ConflictPolicy, + live: &Value, + ) -> Result { + let patch = EditorPatch { + changes, + on_conflict: policy, + key_fields: None, + }; + let out = patch.apply( + Path::new("settings.json"), + Some(live.to_string().as_bytes()), + )?; + Ok(serde_json::from_slice(&out).expect("json")) + } + + #[test] + fn only_global_settings_count_as_live_changes() { + let base = json!({ + "env": { "ANTHROPIC_BASE_URL": "https://a.example", "DEBUG": "1" }, + "hooks": { "Stop": [] } + }); + let edited = json!({ + "env": { + "ANTHROPIC_BASE_URL": "https://b.example", + "CLAUDE_CODE_DISABLE_ARTIFACT": "1", + "EXTRA": "x" + }, + "hooks": { "Stop": [] }, + "alwaysThinkingEnabled": false, + "apiFormat": "openai_chat" + }); + let changes = global_changes(&base, &edited, &[]); + assert_eq!( + changes, + vec![ + JsonChange { + path: KeyPath::new(&["alwaysThinkingEnabled"]), + before: None, + after: Some(json!(false)), + }, + JsonChange { + path: KeyPath::new(&["env", "DEBUG"]), + before: Some(json!("1")), + after: None, + }, + JsonChange { + path: KeyPath::new(&["env", "EXTRA"]), + before: None, + after: Some(json!("x")), + }, + ] + ); + } + + #[test] + fn saving_splits_the_row_from_the_global_settings() { + let stored = json!({ + "env": { "ANTHROPIC_BASE_URL": "https://old.example", "API_TIMEOUT_MS": "300000" }, + "hooks": { "Stop": ["from backfill"] } + }); + let base = json!({ "env": { "ANTHROPIC_BASE_URL": "https://old.example" } }); + let edited = json!({ + "env": { "ANTHROPIC_BASE_URL": "https://new.example", "DEBUG": "1" } + }); + let plan = plan_save(Some(&stored), &edited, &base).expect("plan"); + assert_eq!( + plan.row_settings, + json!({ + "env": { "ANTHROPIC_BASE_URL": "https://new.example", "API_TIMEOUT_MS": "300000" }, + "hooks": { "Stop": ["from backfill"] } + }) + ); + assert_eq!(plan.changes.len(), 1); + + let err = plan_save(None, &json!({ "env": "oops" }), &base).expect_err("bad shape"); + assert!(err.to_string().contains("env"), "{err}"); + } + + #[test] + fn a_key_changed_elsewhere_is_a_conflict_unless_the_user_picks_a_side() { + let changes = vec![ + JsonChange { + path: KeyPath::new(&["x"]), + before: Some(json!(1)), + after: Some(json!(2)), + }, + JsonChange { + path: KeyPath::new(&["y"]), + before: None, + after: Some(json!("mine")), + }, + ]; + // 窗口打开时 x=1,Claude Code 随后改成了 3;用户在旧窗口里改成 2。 + let live = json!({ "x": 3, "z": true }); + match apply(&changes, ConflictPolicy::Refuse, &live) { + Err(LiveWriteError::EditConflict { keys, .. }) => assert_eq!(keys, vec!["x"]), + other => panic!("expected a conflict, got {other:?}"), + } + assert_eq!( + apply(&changes, ConflictPolicy::KeepMine, &live).unwrap(), + json!({ "x": 2, "z": true, "y": "mine" }) + ); + assert_eq!( + apply(&changes, ConflictPolicy::KeepTheirs, &live).unwrap(), + json!({ "x": 3, "z": true, "y": "mine" }) + ); + // 外部已经改成了同样的值:不算冲突。 + assert_eq!( + apply(&changes, ConflictPolicy::Refuse, &json!({ "x": 2 })).unwrap(), + json!({ "x": 2, "y": "mine" }) + ); + } + + #[test] + fn inactive_fields_list_row_values_that_would_not_show_up() { + let row = json!({ + "env": { + "ANTHROPIC_BASE_URL": "https://a.example", + "API_TIMEOUT_MS": "300000", + "ENABLE_TOOL_SEARCH": "true" + }, + "hooks": { "Stop": [] }, + "theme": "dark", + "apiFormat": "anthropic" + }); + let display = json!({ + "env": { "ANTHROPIC_BASE_URL": "https://a.example", "ENABLE_TOOL_SEARCH": "true" }, + "hooks": { "Stop": [] } + }); + assert_eq!( + inactive_fields(&row, &display), + vec![ + InactiveField { + path: vec!["theme".into()], + value: json!("dark"), + }, + InactiveField { + path: vec!["env".into(), "API_TIMEOUT_MS".into()], + value: json!("300000"), + }, + ] + ); + } +} diff --git a/src-tauri/src/services/provider/claude_editor_service.rs b/src-tauri/src/services/provider/claude_editor_service.rs new file mode 100644 index 00000000..4b53f0aa --- /dev/null +++ b/src-tauri/src/services/provider/claude_editor_service.rs @@ -0,0 +1,162 @@ +//! CLI entry points for the upstream Claude editor. File diffing, ownership, +//! conflict decisions and durable publication are implemented in claude_editor. +use super::{claude_editor, live_projection_ownership, ProviderService}; +use crate::{app_config::AppType, error::AppError, provider::Provider, store::AppState}; +use serde_json::Value; + +impl ProviderService { + pub(crate) fn claude_editor_view( + state: &AppState, + settings: &Value, + ) -> Result { + claude_editor::view(state, settings) + } + + pub(crate) fn save_claude_from_editor( + state: &AppState, + mut provider: Provider, + editor: claude_editor::EditorSave, + add: bool, + copy_source: Option<&str>, + ) -> Result { + let app = AppType::Claude; + let _mutation = futures::executor::block_on( + crate::services::state_coordination::acquire_restore_mutation_guard(), + ) + .map_err(AppError::Message)?; + let _switch = + futures::executor::block_on(state.proxy_service.lock_switch_for_app("claude")); + if crate::mode::operation::settle(&state.db, "claude")?.is_some() { + state.reload_config_snapshot_from_db()?; + return Err(AppError::Message( + "An unfinished configuration write was recovered; reopen the editor before saving" + .into(), + )); + } + let copy_snapshot = if let Some(source_id) = copy_source { + state.reload_config_snapshot_from_db()?; + let snapshot = state.config.read().map_err(AppError::from)?.clone(); + let manager = snapshot + .get_manager(&app) + .ok_or_else(|| Self::app_not_found(&app))?; + let source = manager + .providers + .get(source_id) + .ok_or_else(|| AppError::Message(format!("Provider not found: {source_id}")))?; + provider = Self::duplicate_provider_with_overrides( + source, + Some(provider), + &manager.providers.keys().cloned().collect(), + ); + Some(snapshot) + } else { + None + }; + let existing = state.db.get_provider_by_id(&provider.id, "claude")?; + if add && existing.is_some() { + return Err(AppError::Message(format!( + "Provider ID already exists: {}", + provider.id + ))); + } + if !add && existing.is_none() { + return Err(AppError::Message(format!( + "Provider not found: {}", + provider.id + ))); + } + Self::normalize_provider_if_claude(&app, &mut provider); + let plan = claude_editor::plan_save( + existing.as_ref().map(|row| &row.settings_config), + &provider.settings_config, + &editor.base, + )?; + provider.settings_config = plan.row_settings.clone(); + if add { + Self::inject_coding_plan_usage_script(&app, &mut provider); + // Retain the compatibility marker for older clients. + provider + .meta + .get_or_insert_with(Default::default) + .apply_common_config = Some(true); + } + Self::validate_provider_settings(&app, &provider)?; + let current = crate::settings::get_effective_current_provider(&state.db, &app)?; + let ownership = live_projection_ownership(state, &app)?; + let first = add && current.is_none(); + let write_keys = + !ownership.takeover_active && (first || current.as_deref() == Some(&provider.id)); + if let (Some(original), Some(source_id)) = (©_snapshot, copy_source) { + Self::run_transaction_preserving_current_providers( + state, + &[AppType::Claude, AppType::Codex, AppType::Gemini], + |config| { + *config = original.clone(); + let manager = config + .get_manager_mut(&app) + .ok_or_else(|| Self::app_not_found(&app))?; + Self::shift_sort_indices_for_duplicate(manager, source_id, provider.sort_index); + manager + .providers + .insert(provider.id.clone(), provider.clone()); + Ok(((), None)) + }, + )?; + } else { + state.db.save_provider("claude", &provider)?; + } + let written = claude_editor::write_live( + &state.db, + &plan, + editor.on_conflict, + write_keys.then_some(claude_editor::KeyFieldWrite { + prev: existing.as_ref(), + target: &provider, + set_pointer: first, + }), + ) + .and_then(|()| { + state.reload_config_snapshot_from_db()?; + if ownership.takeover_active && current.as_deref() == Some(&provider.id) { + let config = state.config.read().map_err(AppError::from)?; + let mut action = Self::build_post_commit_action_for_current_provider( + &config, + &app, + &provider.id, + true, + ownership.live_taken_over, + ownership.refresh_stale_backup, + None, + )? + .expect("saved provider is present"); + action.previous_provider = existing.clone(); + // An editor save already separated globals from the row. + action.common_config_snippet = None; + drop(config); + let prepared = Self::prepare_post_commit_action(state, action)?; + Self::apply_prepared_post_commit_action(state, &prepared)?; + } + Ok(()) + }); + if let Err(error) = written { + if !crate::mode::operation::has_pending("claude") { + if let Some(original) = copy_snapshot { + Self::restore_config_only_preserving_current_providers( + state, + original, + &[AppType::Claude, AppType::Codex, AppType::Gemini], + )?; + } else { + match existing { + Some(ref row) => state.db.save_provider("claude", row)?, + None => state.db.delete_provider("claude", &provider.id)?, + } + } + } + state.reload_config_snapshot_from_db()?; + return Err(error); + } + state.reload_config_snapshot_from_db()?; + Ok(true) + } +} diff --git a/src-tauri/src/services/provider/common_config.rs b/src-tauri/src/services/provider/common_config.rs index d8b3733a..95fb17d8 100644 --- a/src-tauri/src/services/provider/common_config.rs +++ b/src-tauri/src/services/provider/common_config.rs @@ -626,7 +626,9 @@ pub(super) fn provider_uses_common_config( provider: &Provider, snippet: Option<&str>, ) -> bool { - let _ = app_type; + if matches!(app_type, AppType::Claude) { + return false; + } provider .meta .as_ref() @@ -646,12 +648,7 @@ pub(super) fn apply_common_config_to_settings( } match app_type { - AppType::Claude => { - let source = parse_json_object_snippet(app_type, trimmed)?; - let mut result = settings.clone(); - json_deep_merge(&mut result, &source); - Ok(result) - } + AppType::Claude => Ok(settings.clone()), AppType::Codex => { let mut result = settings.clone(); let config_toml = settings.get("config").and_then(Value::as_str).unwrap_or(""); @@ -858,11 +855,12 @@ pub(super) fn normalize_provider_common_config_for_storage( provider: &mut Provider, snippet: Option<&str>, ) -> Result<(), AppError> { - if provider - .meta - .as_ref() - .and_then(|meta| meta.apply_common_config) - != Some(true) + if matches!(app_type, AppType::Claude) + || provider + .meta + .as_ref() + .and_then(|meta| meta.apply_common_config) + != Some(true) { return Ok(()); } diff --git a/src-tauri/src/services/provider/key_field_live.rs b/src-tauri/src/services/provider/key_field_live.rs index 49b2c029..4edf90eb 100644 --- a/src-tauri/src/services/provider/key_field_live.rs +++ b/src-tauri/src/services/provider/key_field_live.rs @@ -73,7 +73,6 @@ pub(super) fn edit_common( current: Option<&str>, previous: Option<&str>, ) -> Result<(), AppError> { - use crate::live::patch::KeyPath; use serde_json::Value; fn parse(text: &str) -> Result { let value: Value = @@ -85,25 +84,6 @@ pub(super) fn edit_common( } Ok(value) } - fn entries(value: &Value, path: KeyPath, out: &mut Vec<(KeyPath, Value)>) { - if let Some(map) = value.as_object() { - for (key, value) in map { - entries(value, path.child(key), out); - } - } else { - out.push((path, value.clone())); - } - } - fn global_claude(path: &KeyPath) -> bool { - use crate::live::floor; - match path.0.as_slice() { - [top, key, ..] if top == "env" => { - !floor::claude_floor_env(key) && !floor::claude_exclusive_env(key) - } - [top, ..] => top != "env" && !floor::claude_floor_top(top), - _ => false, - } - } let current = current .map(parse) .transpose()? @@ -112,23 +92,6 @@ pub(super) fn edit_common( .and_then(|s| parse(s).ok()) .unwrap_or(serde_json::json!({})); match prepared { - PreparedLiveWrite::Claude { patch } => { - let mut set = Vec::new(); - entries(¤t, KeyPath::root(), &mut set); - // Explicit common edits may change global settings; provider keys - // retain the values selected by the provider projection. - set.retain(|(path, _)| { - global_claude(path) && !patch.set.iter().any(|(key, _)| key == path) - }); - patch.set.extend(set); - let mut old = Vec::new(); - entries(&previous, KeyPath::root(), &mut old); - patch.remove_if.extend( - old.into_iter() - .filter(|(path, _)| global_claude(path)) - .map(|(path, value)| (path, vec![value])), - ); - } PreparedLiveWrite::Gemini { env, .. } => { for (key, value) in current.as_object().unwrap() { if crate::live::floor::gemini_floor_env(key) { diff --git a/src-tauri/src/services/provider/mod.rs b/src-tauri/src/services/provider/mod.rs index 74c53f54..6c756b98 100644 --- a/src-tauri/src/services/provider/mod.rs +++ b/src-tauri/src/services/provider/mod.rs @@ -4,6 +4,8 @@ mod key_field_live; use std::collections::HashSet; mod claude; +pub(crate) mod claude_editor; +mod claude_editor_service; mod codex; pub(crate) mod codex_live; pub(crate) mod codex_login; @@ -1017,13 +1019,10 @@ impl ProviderService { } let effect = if action.edit_common_config && action.takeover_active - && matches!(action.app_type, AppType::Claude | AppType::Gemini) + && matches!(action.app_type, AppType::Gemini) { // Explicit CLI global edits must not replace an active proxy route. PreparedPostCommitEffect::Live(match action.app_type { - AppType::Claude => PreparedLiveWrite::Claude { - patch: Default::default(), - }, AppType::Gemini => PreparedLiveWrite::Gemini { env: Default::default(), settings: Default::default(), @@ -2201,6 +2200,12 @@ impl ProviderService { app_type: AppType, snippet: Option, ) -> Result<(), AppError> { + if matches!(app_type, AppType::Claude) { + return Err(AppError::Message(crate::t!( + "Claude settings are edited in the provider configuration editor; common snippets are retained only for older clients.", + "请在供应商配置编辑器中修改 Claude 设置;通用片段仅保留供旧版本读取。" + ).to_string())); + } let normalized_snippet = snippet.and_then(|value| { let trimmed = value.trim(); if trimmed.is_empty() { diff --git a/src-tauri/src/services/provider/tests.rs b/src-tauri/src/services/provider/tests.rs index ad10a6c1..60358d91 100644 --- a/src-tauri/src/services/provider/tests.rs +++ b/src-tauri/src/services/provider/tests.rs @@ -2266,263 +2266,6 @@ fn sync_current_to_live_prefers_effective_current_from_local_settings() { ); } -#[test] -#[serial] -fn updating_common_snippet_uses_db_current_without_fallback_healing_config() { - let temp_home = TempDir::new().expect("create temp home"); - let _env = TestEnvGuard::isolated(temp_home.path()); - std::fs::create_dir_all(crate::config::get_claude_config_dir()) - .expect("create ~/.claude (initialized)"); - - let mut config = MultiAppConfig::default(); - config.ensure_app(&AppType::Claude); - { - let manager = config - .get_manager_mut(&AppType::Claude) - .expect("claude manager"); - manager.current = "missing".to_string(); - - let mut p1 = with_common_enabled(Provider::with_id( - "p1".to_string(), - "First".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token1", - "ANTHROPIC_BASE_URL": "https://claude.one" - } - }), - None, - )); - p1.sort_index = Some(10); - - let mut p2 = with_common_enabled(Provider::with_id( - "p2".to_string(), - "Second".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token2", - "ANTHROPIC_BASE_URL": "https://claude.two" - } - }), - None, - )); - p2.sort_index = Some(0); - - manager.providers.insert("p1".to_string(), p1); - manager.providers.insert("p2".to_string(), p2); - } - - write_json_file( - &get_claude_settings_path(), - &json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token1", - "ANTHROPIC_BASE_URL": "https://claude.one", - "LOCAL_ONLY": "preserve-me" - } - }), - ) - .expect("seed live settings"); - - let state = state_from_config(config); - state - .db - .save_provider( - AppType::Claude.as_str(), - &with_common_enabled(Provider::with_id( - "p1".to_string(), - "First".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token1", - "ANTHROPIC_BASE_URL": "https://claude.one" - } - }), - None, - )), - ) - .expect("save first provider to db"); - state - .db - .save_provider( - AppType::Claude.as_str(), - &with_common_enabled(Provider::with_id( - "p2".to_string(), - "Second".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token2", - "ANTHROPIC_BASE_URL": "https://claude.two" - } - }), - None, - )), - ) - .expect("save second provider to db"); - state - .db - .set_current_provider(AppType::Claude.as_str(), "p1") - .expect("set db current provider"); - - ProviderService::set_common_config_snippet( - &state, - AppType::Claude, - Some(r#"{"includeCoAuthoredBy":false}"#.to_string()), - ) - .expect("update common snippet"); - - let cfg = state.config.read().expect("read config"); - let manager = cfg.get_manager(&AppType::Claude).expect("claude manager"); - assert_eq!( - manager.current, "missing", - "updating common snippet should not rewrite stale config.current while syncing live from db current" - ); - drop(cfg); - - let live: Value = read_json_file(&get_claude_settings_path()).expect("read live settings"); - assert_eq!( - live.get("includeCoAuthoredBy").and_then(Value::as_bool), - Some(false), - "new common snippet should be applied to the healed current live settings" - ); - let env = live - .get("env") - .and_then(Value::as_object) - .expect("live env should be object"); - assert_eq!( - env.get("ANTHROPIC_AUTH_TOKEN").and_then(Value::as_str), - Some("token1"), - "live settings should refresh from the effective current provider instead of fallback-healing config.current" - ); -} - -#[test] -#[serial] -fn updating_common_snippet_uses_db_current_when_config_snapshot_is_missing_current_provider() { - let temp_home = TempDir::new().expect("create temp home"); - let _env = TestEnvGuard::isolated(temp_home.path()); - std::fs::create_dir_all(crate::config::get_claude_config_dir()) - .expect("create ~/.claude (initialized)"); - - let mut config = MultiAppConfig::default(); - config.ensure_app(&AppType::Claude); - { - let manager = config - .get_manager_mut(&AppType::Claude) - .expect("claude manager"); - manager.current = "missing".to_string(); - manager.providers.insert( - "p2".to_string(), - Provider::with_id( - "p2".to_string(), - "Second".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token2", - "ANTHROPIC_BASE_URL": "https://claude.two" - } - }), - None, - ), - ); - } - - write_json_file( - &get_claude_settings_path(), - &json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token1", - "ANTHROPIC_BASE_URL": "https://claude.one", - "LOCAL_ONLY": "preserve-me" - } - }), - ) - .expect("seed live settings"); - - let state = state_from_config(config); - state - .db - .save_provider( - AppType::Claude.as_str(), - &with_common_enabled(Provider::with_id( - "p1".to_string(), - "First".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token1", - "ANTHROPIC_BASE_URL": "https://claude.one" - } - }), - None, - )), - ) - .expect("save current provider to db"); - state - .db - .save_provider( - AppType::Claude.as_str(), - &with_common_enabled(Provider::with_id( - "p2".to_string(), - "Second".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token2", - "ANTHROPIC_BASE_URL": "https://claude.two" - } - }), - None, - )), - ) - .expect("save non-current provider to db"); - state - .db - .set_current_provider(AppType::Claude.as_str(), "p1") - .expect("set db current provider"); - - ProviderService::set_common_config_snippet( - &state, - AppType::Claude, - Some(r#"{"includeCoAuthoredBy":false}"#.to_string()), - ) - .expect("update common snippet should use db current even when config snapshot is missing it"); - - let live: Value = read_json_file(&get_claude_settings_path()).expect("read live settings"); - assert_eq!( - live.get("includeCoAuthoredBy").and_then(Value::as_bool), - Some(false), - "new common snippet should be applied to live settings" - ); - let env = live - .get("env") - .and_then(Value::as_object) - .expect("live env should be object"); - assert_eq!( - env.get("ANTHROPIC_AUTH_TOKEN").and_then(Value::as_str), - Some("token1"), - "live settings should be refreshed from the db current provider even when config snapshot lacks it" - ); - - let cfg = state.config.read().expect("read config after update"); - let manager = cfg.get_manager(&AppType::Claude).expect("claude manager"); - assert_eq!( - manager.current, "missing", - "updating common snippet should not rewrite stale config.current even when hydrating the current provider snapshot from db" - ); - assert!( - manager.providers.contains_key("p1"), - "missing current provider snapshot should be hydrated from db before the common snippet update is persisted" - ); - - let db_providers = state - .db - .get_all_providers(AppType::Claude.as_str()) - .expect("read db providers after update"); - assert!( - db_providers.contains_key("p1"), - "db current provider should remain persisted after updating the common snippet" - ); -} - #[test] #[serial] fn claude_switch_does_not_replay_saved_common_snippet() { @@ -2582,78 +2325,23 @@ fn claude_switch_does_not_replay_saved_common_snippet() { } #[test] -fn build_effective_live_snapshot_merges_claude_common_config_with_upstream_precedence() { - let provider = with_common_enabled(Provider::with_id( - "p1".to_string(), - "First".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token", - "ANTHROPIC_BASE_URL": "https://provider.example" - }, - "includeCoAuthoredBy": true, - "permissions": { - "allow": ["Bash(git status)"] - } - }), - None, - )); - - let effective = ProviderService::build_effective_live_snapshot( - &AppType::Claude, - &provider, - Some( - r#"{"env":{"ANTHROPIC_BASE_URL":"https://common.example","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC":1},"includeCoAuthoredBy":false,"permissions":{"allow":["Bash(ls)"]}}"#, - ), - true, - ) - .expect("build effective snapshot"); - - assert_eq!( - effective["env"]["ANTHROPIC_AUTH_TOKEN"], - json!("token"), - "provider auth token should be preserved" - ); - assert_eq!( - effective["env"]["ANTHROPIC_BASE_URL"], - json!("https://common.example"), - "common config should follow upstream merge precedence" - ); - assert_eq!( - effective["env"]["CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"], - json!(1), - "common env values should still be merged" - ); - assert_eq!( - effective["includeCoAuthoredBy"], - json!(false), - "common top-level settings should follow upstream merge precedence" - ); - assert_eq!( - effective["permissions"]["allow"], - json!(["Bash(ls)"]), - "common nested settings should follow upstream merge precedence" - ); -} - -#[test] -#[serial] -fn startup_cleanup_scrubs_historical_gemini_credentials_without_schema_changes() { - let temp_home = TempDir::new().expect("create temp home"); - let _env = TestEnvGuard::isolated(temp_home.path()); - let env_path = crate::gemini_config::get_gemini_env_path(); - std::fs::create_dir_all(env_path.parent().expect("Gemini env parent")) - .expect("create Gemini directory"); - std::fs::write( - &env_path, - "# preserve\nGOOGLE_API_KEY=leaked-key\nUNRELATED=value\n", - ) - .expect("seed Gemini live env"); - - let db = Database::memory().expect("create memory database"); - let leaked_provider = Provider::with_id( - "victim".to_string(), - "Victim".to_string(), +#[serial] +fn startup_cleanup_scrubs_historical_gemini_credentials_without_schema_changes() { + let temp_home = TempDir::new().expect("create temp home"); + let _env = TestEnvGuard::isolated(temp_home.path()); + let env_path = crate::gemini_config::get_gemini_env_path(); + std::fs::create_dir_all(env_path.parent().expect("Gemini env parent")) + .expect("create Gemini directory"); + std::fs::write( + &env_path, + "# preserve\nGOOGLE_API_KEY=leaked-key\nUNRELATED=value\n", + ) + .expect("seed Gemini live env"); + + let db = Database::memory().expect("create memory database"); + let leaked_provider = Provider::with_id( + "victim".to_string(), + "Victim".to_string(), json!({ "env": { "GOOGLE_API_KEY": "leaked-key", @@ -3167,216 +2855,6 @@ fn common_config_snippet_can_be_disabled_per_provider_for_claude() { ); } -#[test] -#[serial] -fn provider_add_strips_common_snippet_before_claude_snapshot_persist() { - let temp_home = TempDir::new().expect("create temp home"); - let _env = TestEnvGuard::isolated(temp_home.path()); - std::fs::create_dir_all(crate::config::get_claude_config_dir()) - .expect("create ~/.claude (initialized)"); - - let mut config = MultiAppConfig::default(); - config.ensure_app(&AppType::Claude); - config.common_config_snippets.claude = Some( - r#"{"env":{"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC":1},"includeCoAuthoredBy":false}"# - .to_string(), - ); - - let state = state_from_config(config); - - let provider = with_common_enabled(Provider::with_id( - "p1".to_string(), - "First".to_string(), - json!({ - "includeCoAuthoredBy": false, - "env": { - "ANTHROPIC_AUTH_TOKEN": "token", - "ANTHROPIC_BASE_URL": "https://claude.example", - "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": 1 - } - }), - None, - )); - - ProviderService::add(&state, AppType::Claude, provider).expect("add should succeed"); - - let cfg = state.config.read().expect("read config after add"); - let provider = cfg - .get_manager(&AppType::Claude) - .expect("claude manager") - .providers - .get("p1") - .expect("p1 exists"); - assert!( - provider - .settings_config - .get("includeCoAuthoredBy") - .is_none(), - "common top-level keys should be stripped before persisting Claude snapshot" - ); - let env = provider - .settings_config - .get("env") - .and_then(Value::as_object) - .expect("provider env should be object"); - assert!( - !env.contains_key("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"), - "common env keys should be stripped before persisting Claude snapshot" - ); - assert_eq!( - env.get("ANTHROPIC_AUTH_TOKEN").and_then(Value::as_str), - Some("token"), - "provider-specific env keys should remain in the stored snapshot" - ); -} - -#[test] -#[cfg(feature = "cli")] -#[serial] -fn tui_claude_quick_config_round_trip_crosses_storage_normalization() { - let temp_home = TempDir::new().expect("create temp home"); - let _env = TestEnvGuard::isolated(temp_home.path()); - let common_snippet = r#"{ - "attribution": { "commit": "", "pr": "" }, - "env": { - "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1", - "ENABLE_TOOL_SEARCH": "true", - "CLAUDE_CODE_EFFORT_LEVEL": "max", - "DISABLE_AUTOUPDATER": "1" - } - }"#; - - let mut config = MultiAppConfig::default(); - config.ensure_app(&AppType::Claude); - config.common_config_snippets.claude = Some(common_snippet.to_string()); - let state = state_from_config(config); - - let mut form = crate::cli::tui::ProviderAddFormState::new_with_common_snippet( - AppType::Claude, - common_snippet, - ); - form.id.set("p1"); - form.name.set("Provider One"); - form.claude_base_url.set("https://claude.example"); - form.claude_api_key.set("sk-provider"); - assert_eq!(form.claude_quick_config_enabled_count(), 5); - - let provider: Provider = serde_json::from_value(form.to_provider_json_value()) - .expect("form payload should deserialize"); - ProviderService::add(&state, AppType::Claude, provider).expect("provider add should succeed"); - - let stored = state - .db - .get_provider_by_id("p1", AppType::Claude.as_str()) - .expect("read provider from database") - .expect("stored provider"); - assert_eq!( - stored - .meta - .as_ref() - .and_then(|meta| meta.apply_common_config), - Some(true) - ); - assert!(stored.settings_config.get("attribution").is_none()); - let stored_env = stored - .settings_config - .get("env") - .and_then(Value::as_object) - .expect("stored provider env"); - for common_key in [ - "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS", - "ENABLE_TOOL_SEARCH", - "CLAUDE_CODE_EFFORT_LEVEL", - "DISABLE_AUTOUPDATER", - ] { - assert!( - !stored_env.contains_key(common_key), - "{common_key} should remain common-owned in storage" - ); - } - - let reopened = crate::cli::tui::ProviderAddFormState::from_provider_with_common_snippet( - AppType::Claude, - &stored, - common_snippet, - ); - assert_eq!(reopened.claude_quick_config_enabled_count(), 5); - assert!(!reopened.has_unsaved_changes()); -} - -#[test] -#[cfg(feature = "cli")] -#[serial] -fn tui_claude_quick_edit_persists_legacy_inferred_common_config() { - let temp_home = TempDir::new().expect("create temp home"); - let _env = TestEnvGuard::isolated(temp_home.path()); - let common_snippet = r#"{"env":{"CC_SWITCH_SHARED":"1"}}"#; - - let mut config = MultiAppConfig::default(); - config.ensure_app(&AppType::Claude); - config.common_config_snippets.claude = Some(common_snippet.to_string()); - let state = state_from_config(config); - - let legacy_provider = Provider::with_id( - "legacy-provider".to_string(), - "Legacy Provider".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "sk-provider", - "ANTHROPIC_BASE_URL": "https://claude.example", - "CC_SWITCH_SHARED": "1" - } - }), - None, - ); - let mut form = crate::cli::tui::ProviderAddFormState::from_provider_with_common_snippet( - AppType::Claude, - &legacy_provider, - common_snippet, - ); - assert!(form.include_common_config); - - form.toggle_claude_quick_config_field( - crate::cli::tui::ProviderAddField::ClaudeToolSearch, - common_snippet, - ) - .expect("provider-only quick edit should succeed"); - let edited: Provider = serde_json::from_value(form.to_provider_json_value()) - .expect("edited form payload should deserialize"); - ProviderService::add(&state, AppType::Claude, edited).expect("provider add should succeed"); - - let stored = state - .db - .get_provider_by_id("legacy-provider", AppType::Claude.as_str()) - .expect("read provider from database") - .expect("stored provider"); - assert_eq!( - stored - .meta - .as_ref() - .and_then(|meta| meta.apply_common_config), - Some(true) - ); - let stored_env = stored - .settings_config - .get("env") - .and_then(Value::as_object) - .expect("stored provider env"); - assert!(!stored_env.contains_key("CC_SWITCH_SHARED")); - assert_eq!( - stored_env.get("ENABLE_TOOL_SEARCH").and_then(Value::as_str), - Some("true") - ); - - let reopened = crate::cli::tui::ProviderAddFormState::from_provider_with_common_snippet( - AppType::Claude, - &stored, - common_snippet, - ); - assert!(reopened.include_common_config); - assert!(reopened.claude_tool_search); -} - #[test] #[cfg(feature = "cli")] #[serial] @@ -3604,7 +3082,7 @@ fn provider_add_migrates_legacy_claude_model_to_provider_owned_roles() { #[test] #[serial] -fn provider_update_strips_common_snippet_before_claude_snapshot_persist() { +fn provider_update_does_not_infer_claude_common_config_opt_in() { let temp_home = TempDir::new().expect("create temp home"); let _env = TestEnvGuard::isolated(temp_home.path()); std::fs::create_dir_all(crate::config::get_claude_config_dir()) @@ -3639,7 +3117,7 @@ fn provider_update_strips_common_snippet_before_claude_snapshot_persist() { let state = state_from_config(config); - let provider = with_common_enabled(Provider::with_id( + let provider = Provider::with_id( "p1".to_string(), "First Updated".to_string(), json!({ @@ -3651,7 +3129,7 @@ fn provider_update_strips_common_snippet_before_claude_snapshot_persist() { } }), None, - )); + ); ProviderService::update(&state, AppType::Claude, provider).expect("update should succeed"); @@ -3662,32 +3140,29 @@ fn provider_update_strips_common_snippet_before_claude_snapshot_persist() { .providers .get("p1") .expect("p1 exists"); - assert!( + assert_eq!( provider - .settings_config - .get("includeCoAuthoredBy") - .is_none(), - "common top-level keys should be stripped before persisting updated Claude snapshot" - ); - let env = provider - .settings_config - .get("env") - .and_then(Value::as_object) - .expect("provider env should be object"); - assert!( - !env.contains_key("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"), - "common env keys should be stripped before persisting updated Claude snapshot" + .meta + .as_ref() + .and_then(|meta| meta.apply_common_config), + None, + "provider update must not infer common config opt-in from matching fields" ); assert_eq!( - env.get("ANTHROPIC_AUTH_TOKEN").and_then(Value::as_str), - Some("token-updated"), - "provider-specific env keys should remain in the updated stored snapshot" + provider + .settings_config + .get("includeCoAuthoredBy") + .and_then(Value::as_bool), + Some(false), + "matching common fields remain provider-owned when not explicitly enabled" ); } #[test] #[serial] -fn provider_update_does_not_infer_claude_common_config_opt_in() { +fn provider_update_overwrites_claude_live_for_current_provider() { + // Upstream parity: updating the current provider clean-writes the new + // effective config to settings.json (no conflict prompt / detection). let temp_home = TempDir::new().expect("create temp home"); let _env = TestEnvGuard::isolated(temp_home.path()); std::fs::create_dir_all(crate::config::get_claude_config_dir()) @@ -3695,10 +3170,6 @@ fn provider_update_does_not_infer_claude_common_config_opt_in() { let mut config = MultiAppConfig::default(); config.ensure_app(&AppType::Claude); - config.common_config_snippets.claude = Some( - r#"{"env":{"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC":1},"includeCoAuthoredBy":false}"# - .to_string(), - ); { let manager = config .get_manager_mut(&AppType::Claude) @@ -3711,8 +3182,8 @@ fn provider_update_does_not_infer_claude_common_config_opt_in() { "First".to_string(), json!({ "env": { - "ANTHROPIC_AUTH_TOKEN": "token", - "ANTHROPIC_BASE_URL": "https://claude.example" + "ANTHROPIC_AUTH_TOKEN": "token-old", + "ANTHROPIC_BASE_URL": "https://claude.old" } }), None, @@ -3720,98 +3191,22 @@ fn provider_update_does_not_infer_claude_common_config_opt_in() { ); } + write_json_file( + &get_claude_settings_path(), + &json!({ + "env": { + "ANTHROPIC_AUTH_TOKEN": "token-old", + "ANTHROPIC_BASE_URL": "https://claude.old" + } + }), + ) + .expect("seed live settings"); + let state = state_from_config(config); - - let provider = Provider::with_id( - "p1".to_string(), - "First Updated".to_string(), - json!({ - "includeCoAuthoredBy": false, - "env": { - "ANTHROPIC_AUTH_TOKEN": "token-updated", - "ANTHROPIC_BASE_URL": "https://claude.updated", - "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": 1 - } - }), - None, - ); - - ProviderService::update(&state, AppType::Claude, provider).expect("update should succeed"); - - let cfg = state.config.read().expect("read config after update"); - let provider = cfg - .get_manager(&AppType::Claude) - .expect("claude manager") - .providers - .get("p1") - .expect("p1 exists"); - assert_eq!( - provider - .meta - .as_ref() - .and_then(|meta| meta.apply_common_config), - None, - "provider update must not infer common config opt-in from matching fields" - ); - assert_eq!( - provider - .settings_config - .get("includeCoAuthoredBy") - .and_then(Value::as_bool), - Some(false), - "matching common fields remain provider-owned when not explicitly enabled" - ); -} - -#[test] -#[serial] -fn provider_update_overwrites_claude_live_for_current_provider() { - // Upstream parity: updating the current provider clean-writes the new - // effective config to settings.json (no conflict prompt / detection). - let temp_home = TempDir::new().expect("create temp home"); - let _env = TestEnvGuard::isolated(temp_home.path()); - std::fs::create_dir_all(crate::config::get_claude_config_dir()) - .expect("create ~/.claude (initialized)"); - - let mut config = MultiAppConfig::default(); - config.ensure_app(&AppType::Claude); - { - let manager = config - .get_manager_mut(&AppType::Claude) - .expect("claude manager"); - manager.current = "p1".to_string(); - manager.providers.insert( - "p1".to_string(), - Provider::with_id( - "p1".to_string(), - "First".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token-old", - "ANTHROPIC_BASE_URL": "https://claude.old" - } - }), - None, - ), - ); - } - - write_json_file( - &get_claude_settings_path(), - &json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token-old", - "ANTHROPIC_BASE_URL": "https://claude.old" - } - }), - ) - .expect("seed live settings"); - - let state = state_from_config(config); - state - .db - .set_current_provider(AppType::Claude.as_str(), "p1") - .expect("set db current provider"); + state + .db + .set_current_provider(AppType::Claude.as_str(), "p1") + .expect("set db current provider"); let provider = Provider::with_id( "p1".to_string(), @@ -4068,93 +3463,6 @@ async fn provider_update_waits_for_state_mutation_guard() { ); } -#[tokio::test] -#[serial] -async fn common_snippet_update_during_takeover_edits_live_globals() { - let temp_home = TempDir::new().expect("create temp home"); - let _env = TestEnvGuard::isolated(temp_home.path()); - std::fs::create_dir_all(crate::config::get_claude_config_dir()) - .expect("create ~/.claude (initialized)"); - - let provider = with_common_enabled(Provider::with_id( - "p1".to_string(), - "First".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token", - "ANTHROPIC_BASE_URL": "https://claude.example" - } - }), - None, - )); - let mut config = MultiAppConfig::default(); - config.ensure_app(&AppType::Claude); - config.common_config_snippets.claude = - Some(r#"{"includeCoAuthoredBy":true,"env":{"OLD_COMMON":"remove-me"}}"#.to_string()); - { - let manager = config - .get_manager_mut(&AppType::Claude) - .expect("claude manager"); - manager.current = "p1".to_string(); - manager.providers.insert("p1".to_string(), provider.clone()); - } - - let state = state_from_config(config); - let old_backup = ProviderService::build_live_backup_snapshot( - &AppType::Claude, - &provider, - Some(r#"{"includeCoAuthoredBy":true,"env":{"OLD_COMMON":"remove-me"}}"#), - true, - ) - .expect("build old effective backup"); - state - .db - .save_live_backup( - AppType::Claude.as_str(), - &serde_json::to_string(&old_backup).expect("serialize old backup"), - ) - .await - .expect("seed takeover backup"); - let takeover_live = json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "PROXY_MANAGED", - "ANTHROPIC_BASE_URL": "http://127.0.0.1:15721" - } - }); - write_json_file(&get_claude_settings_path(), &takeover_live) - .expect("seed takeover-owned live settings"); - assert!(!state.proxy_service.is_running().await); - - ProviderService::set_common_config_snippet( - &state, - AppType::Claude, - Some(r#"{"includeCoAuthoredBy":false}"#.to_string()), - ) - .expect("update common snippet during stopped takeover"); - - let backup = state - .db - .get_live_backup(AppType::Claude.as_str()) - .await - .expect("read refreshed backup") - .expect("takeover backup should remain"); - let backup: Value = - serde_json::from_str(&backup.original_config).expect("parse refreshed backup"); - assert_eq!( - backup, old_backup, - "global edits do not replay or rewrite legacy backups" - ); - let live: Value = read_json_file(&get_claude_settings_path()).expect("read takeover live"); - assert_eq!( - live["env"], takeover_live["env"], - "proxy fields stay attached" - ); - assert_eq!( - live["includeCoAuthoredBy"], false, - "explicit global edits apply immediately" - ); -} - #[tokio::test] #[serial] async fn provider_update_keeps_running_claude_takeover_and_refreshes_restore_backup() { @@ -4349,663 +3657,172 @@ requires_openai_auth = true .set_app_proxy_preferred_port(AppType::Codex.as_str(), 0) .expect("use an ephemeral proxy port"); state - .proxy_service - .set_takeover_for_app(AppType::Codex.as_str(), true) - .await - .expect("enable Codex takeover"); - - let mut updated = original.clone(); - updated.settings_config["config"] = json!( - r#"model_provider = "custom" -model = "gpt-5.4" - -[model_providers.custom] -name = "Codex A" -base_url = "https://api.updated.example/v1" -wire_api = "anthropic" -requires_openai_auth = true -"# - ); - updated.settings_config["modelCatalog"] = json!({ - "models": [{ "model": "gpt-5.4", "displayName": "GPT 5.4" }] - }); - - ProviderService::update(&state, AppType::Codex, updated.clone()) - .expect("update current Codex provider mapping"); - - let catalog: Value = read_json_file(&crate::codex_config::get_codex_model_catalog_path()) - .expect("read generated catalog"); - assert_eq!(catalog["models"][0]["slug"], "gpt-5.4"); - assert_eq!( - catalog["models"][0]["input_modalities"], - json!(["text", "image"]), - "unknown and GPT models must fail open to image input" - ); - let live_config = std::fs::read_to_string(crate::codex_config::get_codex_config_path()) - .expect("read Codex config.toml"); - assert!(live_config.contains("model_catalog_json")); - let live_toml: toml::Value = toml::from_str(&live_config).expect("parse live Codex config"); - assert_eq!( - live_toml["model_providers"]["custom"]["wire_api"].as_str(), - Some("responses"), - "Codex must speak Responses to the local proxy even for an Anthropic upstream" - ); - - updated.settings_config["modelCatalog"] = json!({ "models": [] }); - ProviderService::update(&state, AppType::Codex, updated) - .expect("remove current Codex provider mapping"); - - let live_config = std::fs::read_to_string(crate::codex_config::get_codex_config_path()) - .expect("read Codex config.toml after mapping removal"); - assert!( - !live_config.contains("model_catalog_json"), - "removing mappings during takeover must clear the stale catalog pointer" - ); - - state - .proxy_service - .set_takeover_for_app(AppType::Codex.as_str(), false) - .await - .expect("disable Codex takeover"); -} - -#[tokio::test] -#[serial] -async fn provider_update_uses_live_marker_as_takeover_ownership_when_proxy_is_stopped() { - let temp_home = TempDir::new().expect("create temp home"); - let _env = TestEnvGuard::isolated(temp_home.path()); - std::fs::create_dir_all(crate::config::get_claude_config_dir()) - .expect("create ~/.claude (initialized)"); - - let original = Provider::with_id( - "p1".to_string(), - "First".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token-old", - "ANTHROPIC_BASE_URL": "https://claude.old" - } - }), - None, - ); - let mut config = MultiAppConfig::default(); - config.ensure_app(&AppType::Claude); - { - let manager = config - .get_manager_mut(&AppType::Claude) - .expect("claude manager"); - manager.current = "p1".to_string(); - manager.providers.insert("p1".to_string(), original); - } - let state = state_from_config(config); - state.save().expect("persist config snapshot to db"); - state - .db - .set_current_provider(AppType::Claude.as_str(), "p1") - .expect("set db current provider"); - - let takeover_live = json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "PROXY_MANAGED", - "ANTHROPIC_BASE_URL": "http://127.0.0.1:15721" - }, - "permissions": { "allow": ["Bash"] } - }); - write_json_file(&get_claude_settings_path(), &takeover_live) - .expect("seed takeover-owned live settings"); - assert!(!state.proxy_service.is_running().await); - assert!(state - .db - .get_live_backup(AppType::Claude.as_str()) - .await - .expect("read initial backup") - .is_none()); - - let updated = Provider::with_id( - "p1".to_string(), - "First Updated".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token-new", - "ANTHROPIC_BASE_URL": "https://claude.new" - }, - "permissions": { "allow": ["Read"] } - }), - None, - ); - ProviderService::update(&state, AppType::Claude, updated) - .expect("update takeover-owned provider while proxy is stopped"); - ProviderService::sync_current_to_live(&state) - .expect("bulk live sync should preserve takeover ownership"); - - let live: Value = read_json_file(&get_claude_settings_path()).expect("read unchanged live"); - assert_eq!( - live, takeover_live, - "a stopped proxy must not trigger a normal live write over takeover placeholders" - ); - let backup = state - .db - .get_live_backup(AppType::Claude.as_str()) - .await - .expect("read refreshed backup") - .expect("refreshed backup should exist"); - let backup_value: Value = - serde_json::from_str(&backup.original_config).expect("parse refreshed backup"); - assert_eq!( - backup_value - .pointer("/env/ANTHROPIC_AUTH_TOKEN") - .and_then(Value::as_str), - Some("token-new") - ); - assert_eq!( - backup_value - .pointer("/env/ANTHROPIC_BASE_URL") - .and_then(Value::as_str), - Some("https://claude.new") - ); -} - -#[test] -#[serial] -fn provider_update_treats_settings_effective_current_as_current_for_live_write() { - let temp_home = TempDir::new().expect("create temp home"); - let _env = TestEnvGuard::isolated(temp_home.path()); - std::fs::create_dir_all(crate::config::get_claude_config_dir()) - .expect("create ~/.claude (initialized)"); - - let mut config = MultiAppConfig::default(); - config.ensure_app(&AppType::Claude); - { - let manager = config - .get_manager_mut(&AppType::Claude) - .expect("claude manager"); - manager.current = "p1".to_string(); - manager.providers.insert( - "p1".to_string(), - Provider::with_id( - "p1".to_string(), - "First".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token1", - "ANTHROPIC_BASE_URL": "https://claude.one" - } - }), - None, - ), - ); - manager.providers.insert( - "p2".to_string(), - Provider::with_id( - "p2".to_string(), - "Second".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token2", - "ANTHROPIC_BASE_URL": "https://claude.two" - } - }), - None, - ), - ); - } - let state = state_from_config(config); - state.save().expect("persist config snapshot to db"); - - write_json_file( - &get_claude_settings_path(), - &json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token1", - "ANTHROPIC_BASE_URL": "https://claude.one" - } - }), - ) - .expect("seed current live settings as p1"); - - crate::settings::set_current_provider(&AppType::Claude, Some("p2")) - .expect("set local effective current override to p2"); - - let provider = Provider::with_id( - "p2".to_string(), - "Second Updated".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token2-updated", - "ANTHROPIC_BASE_URL": "https://claude.two.updated" - } - }), - None, - ); - - ProviderService::update(&state, AppType::Claude, provider).expect("update should succeed"); - - let live: Value = read_json_file(&get_claude_settings_path()).expect("read live settings"); - let live_env = live - .get("env") - .and_then(Value::as_object) - .expect("live env should be object"); - assert_eq!( - live_env.get("ANTHROPIC_AUTH_TOKEN").and_then(Value::as_str), - Some("token2-updated"), - "update should treat settings effective current (p2) as current and rewrite live settings" - ); - assert_eq!( - live_env.get("ANTHROPIC_BASE_URL").and_then(Value::as_str), - Some("https://claude.two.updated"), - "live settings should reflect updated effective current provider" - ); -} - -#[test] -#[serial] -fn provider_update_clears_invalid_local_current_override_and_falls_back_to_stored_current() { - let temp_home = TempDir::new().expect("create temp home"); - let _env = TestEnvGuard::isolated(temp_home.path()); - std::fs::create_dir_all(crate::config::get_claude_config_dir()) - .expect("create ~/.claude (initialized)"); - - let mut config = MultiAppConfig::default(); - config.ensure_app(&AppType::Claude); - { - let manager = config - .get_manager_mut(&AppType::Claude) - .expect("claude manager"); - manager.current = "p1".to_string(); - manager.providers.insert( - "p1".to_string(), - Provider::with_id( - "p1".to_string(), - "First".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token1", - "ANTHROPIC_BASE_URL": "https://claude.one" - } - }), - None, - ), - ); - manager.providers.insert( - "p2".to_string(), - Provider::with_id( - "p2".to_string(), - "Second".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token2", - "ANTHROPIC_BASE_URL": "https://claude.two" - } - }), - None, - ), - ); - } - let state = state_from_config(config); - state.save().expect("persist config snapshot to db"); - - write_json_file( - &get_claude_settings_path(), - &json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token2", - "ANTHROPIC_BASE_URL": "https://claude.two" - } - }), - ) - .expect("seed current live settings as p2"); - - crate::settings::set_current_provider(&AppType::Claude, Some("missing")) - .expect("set invalid local current override"); - - let provider = Provider::with_id( - "p1".to_string(), - "First Updated".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token1-updated", - "ANTHROPIC_BASE_URL": "https://claude.one.updated" - } - }), - None, - ); - - ProviderService::update(&state, AppType::Claude, provider).expect("update should succeed"); - - assert_eq!( - crate::settings::get_current_provider(&AppType::Claude), - None, - "invalid local current override should be cleared during effective-current fallback" - ); - - let live: Value = read_json_file(&get_claude_settings_path()).expect("read live settings"); - let live_env = live - .get("env") - .and_then(Value::as_object) - .expect("live env should be object"); - assert_eq!( - live_env.get("ANTHROPIC_AUTH_TOKEN").and_then(Value::as_str), - Some("token1-updated"), - "update should fall back to stored current provider when local override is invalid" - ); - assert_eq!( - live_env.get("ANTHROPIC_BASE_URL").and_then(Value::as_str), - Some("https://claude.one.updated"), - "live settings should reflect stored current provider fallback" - ); -} - -#[test] -#[serial] -fn common_config_snippet_is_not_persisted_into_provider_snapshot_on_switch() { - let temp_home = TempDir::new().expect("create temp home"); - let _env = TestEnvGuard::isolated(temp_home.path()); - - let mut config = MultiAppConfig::default(); - config.ensure_app(&AppType::Claude); - config.common_config_snippets.claude = Some( - r#"{"env":{"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC":1},"includeCoAuthoredBy":false}"# - .to_string(), - ); - - let state = state_from_config(config); - - let p1 = Provider::with_id( - "p1".to_string(), - "First".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token1", - "ANTHROPIC_BASE_URL": "https://claude.one" - } - }), - None, - ); - let p2 = Provider::with_id( - "p2".to_string(), - "Second".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token2", - "ANTHROPIC_BASE_URL": "https://claude.two" - } - }), - None, - ); - - ProviderService::add(&state, AppType::Claude, p1).expect("add p1"); - ProviderService::add(&state, AppType::Claude, p2).expect("add p2"); - - ProviderService::switch(&state, AppType::Claude, "p2").expect("switch to p2"); - - let cfg = state.config.read().expect("read config"); - let manager = cfg.get_manager(&AppType::Claude).expect("claude manager"); - let p1_after = manager.providers.get("p1").expect("p1 exists"); - - assert!( - p1_after - .settings_config - .get("includeCoAuthoredBy") - .is_none(), - "common top-level keys should not be persisted into provider snapshot" - ); - - let env = p1_after - .settings_config - .get("env") - .and_then(Value::as_object) - .expect("provider env should be object"); - assert!( - !env.contains_key("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"), - "common env keys should not be persisted into provider snapshot" - ); - assert_eq!( - env.get("ANTHROPIC_AUTH_TOKEN").and_then(Value::as_str), - Some("token1"), - "provider-specific env should remain in snapshot" - ); -} - -#[test] -#[serial] -fn switch_backfill_preserves_matching_common_fields_when_meta_missing() { - let temp_home = TempDir::new().expect("create temp home"); - let _env = TestEnvGuard::isolated(temp_home.path()); - - let mut config = MultiAppConfig::default(); - config.ensure_app(&AppType::Claude); - config.common_config_snippets.claude = Some( - r#"{"env":{"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC":1},"includeCoAuthoredBy":false}"# - .to_string(), - ); - - let mut p1 = Provider::with_id( - "p1".to_string(), - "First".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token1", - "ANTHROPIC_BASE_URL": "https://claude.one", - "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": 1 - }, - "includeCoAuthoredBy": false - }), - None, - ); - p1.meta = None; - let p2 = Provider::with_id( - "p2".to_string(), - "Second".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token2", - "ANTHROPIC_BASE_URL": "https://claude.two" - } - }), - None, - ); - - let state = state_from_config(config); - ProviderService::add(&state, AppType::Claude, p1).expect("add p1"); - ProviderService::add(&state, AppType::Claude, p2).expect("add p2"); + .proxy_service + .set_takeover_for_app(AppType::Codex.as_str(), true) + .await + .expect("enable Codex takeover"); - write_json_file( - &get_claude_settings_path(), - &json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token1", - "ANTHROPIC_BASE_URL": "https://claude.one", - "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": 1 - }, - "includeCoAuthoredBy": false - }), - ) - .expect("seed live settings with provider-owned fields matching common snippet"); + let mut updated = original.clone(); + updated.settings_config["config"] = json!( + r#"model_provider = "custom" +model = "gpt-5.4" - ProviderService::switch(&state, AppType::Claude, "p2").expect("switch to p2"); +[model_providers.custom] +name = "Codex A" +base_url = "https://api.updated.example/v1" +wire_api = "anthropic" +requires_openai_auth = true +"# + ); + updated.settings_config["modelCatalog"] = json!({ + "models": [{ "model": "gpt-5.4", "displayName": "GPT 5.4" }] + }); - let cfg = state.config.read().expect("read config"); - let manager = cfg.get_manager(&AppType::Claude).expect("claude manager"); - let p1_after = manager.providers.get("p1").expect("p1 exists"); - let env = p1_after - .settings_config - .get("env") - .and_then(Value::as_object) - .expect("provider env should be object"); + ProviderService::update(&state, AppType::Codex, updated.clone()) + .expect("update current Codex provider mapping"); + let catalog: Value = read_json_file(&crate::codex_config::get_codex_model_catalog_path()) + .expect("read generated catalog"); + assert_eq!(catalog["models"][0]["slug"], "gpt-5.4"); assert_eq!( - p1_after.settings_config.get("includeCoAuthoredBy"), - Some(&json!(false)), - "matching top-level fields are provider-owned when common config was never explicitly enabled" + catalog["models"][0]["input_modalities"], + json!(["text", "image"]), + "unknown and GPT models must fail open to image input" ); + let live_config = std::fs::read_to_string(crate::codex_config::get_codex_config_path()) + .expect("read Codex config.toml"); + assert!(live_config.contains("model_catalog_json")); + let live_toml: toml::Value = toml::from_str(&live_config).expect("parse live Codex config"); assert_eq!( - env.get("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"), - Some(&json!(1)), - "matching env fields are provider-owned when common config was never explicitly enabled" + live_toml["model_providers"]["custom"]["wire_api"].as_str(), + Some("responses"), + "Codex must speak Responses to the local proxy even for an Anthropic upstream" ); - assert_eq!( - p1_after - .meta - .as_ref() - .and_then(|meta| meta.apply_common_config), - None, - "backfill must not silently opt missing-meta providers into common config" + + updated.settings_config["modelCatalog"] = json!({ "models": [] }); + ProviderService::update(&state, AppType::Codex, updated) + .expect("remove current Codex provider mapping"); + + let live_config = std::fs::read_to_string(crate::codex_config::get_codex_config_path()) + .expect("read Codex config.toml after mapping removal"); + assert!( + !live_config.contains("model_catalog_json"), + "removing mappings during takeover must clear the stale catalog pointer" ); + + state + .proxy_service + .set_takeover_for_app(AppType::Codex.as_str(), false) + .await + .expect("disable Codex takeover"); } -#[test] +#[tokio::test] #[serial] -fn updating_common_snippet_removes_stale_fields_from_other_claude_provider_snapshots() { +async fn provider_update_uses_live_marker_as_takeover_ownership_when_proxy_is_stopped() { let temp_home = TempDir::new().expect("create temp home"); let _env = TestEnvGuard::isolated(temp_home.path()); std::fs::create_dir_all(crate::config::get_claude_config_dir()) .expect("create ~/.claude (initialized)"); - let old_snippet = - r#"{"env":{"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC":1},"includeCoAuthoredBy":false}"#; - let new_snippet = r#"{"env":{"CLAUDE_CODE_USE_BEDROCK":1},"includeCoAuthoredBy":true}"#; - + let original = Provider::with_id( + "p1".to_string(), + "First".to_string(), + json!({ + "env": { + "ANTHROPIC_AUTH_TOKEN": "token-old", + "ANTHROPIC_BASE_URL": "https://claude.old" + } + }), + None, + ); let mut config = MultiAppConfig::default(); config.ensure_app(&AppType::Claude); - config.common_config_snippets.claude = Some(old_snippet.to_string()); { let manager = config .get_manager_mut(&AppType::Claude) .expect("claude manager"); manager.current = "p1".to_string(); - manager.providers.insert( - "p1".to_string(), - Provider::with_id( - "p1".to_string(), - "First".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token1", - "ANTHROPIC_BASE_URL": "https://claude.one" - } - }), - None, - ), - ); - manager.providers.insert( - "p2".to_string(), - Provider::with_id( - "p2".to_string(), - "Second".to_string(), - json!({ - "includeCoAuthoredBy": false, - "env": { - "ANTHROPIC_AUTH_TOKEN": "token2", - "ANTHROPIC_BASE_URL": "https://claude.two", - "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": 1 - } - }), - None, - ), - ); + manager.providers.insert("p1".to_string(), original); } - - write_json_file( - &get_claude_settings_path(), - &json!({ - "includeCoAuthoredBy": false, - "env": { - "ANTHROPIC_AUTH_TOKEN": "token1", - "ANTHROPIC_BASE_URL": "https://claude.one", - "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": 1 - } - }), - ) - .expect("seed current live settings"); - let state = state_from_config(config); state.save().expect("persist config snapshot to db"); + state + .db + .set_current_provider(AppType::Claude.as_str(), "p1") + .expect("set db current provider"); - ProviderService::set_common_config_snippet( - &state, - AppType::Claude, - Some(new_snippet.to_string()), - ) - .expect("update common snippet"); - - let cfg = state.config.read().expect("read config after update"); - assert_eq!( - cfg.common_config_snippets.claude.as_deref(), - Some(new_snippet), - "new snippet should be persisted into app config" - ); + let takeover_live = json!({ + "env": { + "ANTHROPIC_AUTH_TOKEN": "PROXY_MANAGED", + "ANTHROPIC_BASE_URL": "http://127.0.0.1:15721" + }, + "permissions": { "allow": ["Bash"] } + }); + write_json_file(&get_claude_settings_path(), &takeover_live) + .expect("seed takeover-owned live settings"); + assert!(!state.proxy_service.is_running().await); + assert!(state + .db + .get_live_backup(AppType::Claude.as_str()) + .await + .expect("read initial backup") + .is_none()); - let p2_after = cfg - .get_manager(&AppType::Claude) - .expect("claude manager") - .providers - .get("p2") - .expect("p2 exists"); - assert!( - p2_after - .settings_config - .get("includeCoAuthoredBy") - .is_none(), - "old top-level common keys should be stripped from other provider snapshots" - ); - let p2_env = p2_after - .settings_config - .get("env") - .and_then(Value::as_object) - .expect("p2 env should be object"); - assert!( - !p2_env.contains_key("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"), - "old common env keys should be stripped from other provider snapshots" - ); - assert_eq!( - p2_env.get("ANTHROPIC_AUTH_TOKEN").and_then(Value::as_str), - Some("token2"), - "provider-specific env keys should remain after migration" + let updated = Provider::with_id( + "p1".to_string(), + "First Updated".to_string(), + json!({ + "env": { + "ANTHROPIC_AUTH_TOKEN": "token-new", + "ANTHROPIC_BASE_URL": "https://claude.new" + }, + "permissions": { "allow": ["Read"] } + }), + None, ); - drop(cfg); + ProviderService::update(&state, AppType::Claude, updated) + .expect("update takeover-owned provider while proxy is stopped"); + ProviderService::sync_current_to_live(&state) + .expect("bulk live sync should preserve takeover ownership"); - let live: Value = read_json_file(&get_claude_settings_path()).expect("read live settings"); + let live: Value = read_json_file(&get_claude_settings_path()).expect("read unchanged live"); assert_eq!( - live.get("includeCoAuthoredBy").and_then(Value::as_bool), - Some(true), - "current live settings should reflect the new common snippet" + live, takeover_live, + "a stopped proxy must not trigger a normal live write over takeover placeholders" ); - let live_env = live - .get("env") - .and_then(Value::as_object) - .expect("live env should be object"); + let backup = state + .db + .get_live_backup(AppType::Claude.as_str()) + .await + .expect("read refreshed backup") + .expect("refreshed backup should exist"); + let backup_value: Value = + serde_json::from_str(&backup.original_config).expect("parse refreshed backup"); assert_eq!( - live_env - .get("CLAUDE_CODE_USE_BEDROCK") - .and_then(Value::as_i64), - None, - "global snippet edits must not switch provider-owned protocol selectors" - ); - assert!( - !live_env.contains_key("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"), - "old common env key should be removed from current live settings" + backup_value + .pointer("/env/ANTHROPIC_AUTH_TOKEN") + .and_then(Value::as_str), + Some("token-new") ); assert_eq!( - live_env.get("ANTHROPIC_AUTH_TOKEN").and_then(Value::as_str), - Some("token1"), - "current provider env should remain in live settings" + backup_value + .pointer("/env/ANTHROPIC_BASE_URL") + .and_then(Value::as_str), + Some("https://claude.new") ); } #[test] #[serial] -fn updating_common_snippet_preserves_migrated_provider_owned_claude_models() { +fn provider_update_treats_settings_effective_current_as_current_for_live_write() { let temp_home = TempDir::new().expect("create temp home"); let _env = TestEnvGuard::isolated(temp_home.path()); std::fs::create_dir_all(crate::config::get_claude_config_dir()) .expect("create ~/.claude (initialized)"); - let old_snippet = r#"{"env":{"ANTHROPIC_SMALL_FAST_MODEL":"claude-3-5-haiku-20241022"}}"#; - let new_snippet = r#"{"env":{"CLAUDE_CODE_USE_BEDROCK":1}}"#; - let mut config = MultiAppConfig::default(); config.ensure_app(&AppType::Claude); - config.common_config_snippets.claude = Some(old_snippet.to_string()); { let manager = config .get_manager_mut(&AppType::Claude) @@ -5033,16 +3850,15 @@ fn updating_common_snippet_preserves_migrated_provider_owned_claude_models() { json!({ "env": { "ANTHROPIC_AUTH_TOKEN": "token2", - "ANTHROPIC_BASE_URL": "https://claude.two", - "ANTHROPIC_DEFAULT_HAIKU_MODEL": "claude-3-5-haiku-20241022", - "ANTHROPIC_DEFAULT_SONNET_MODEL": "claude-3-5-haiku-20241022", - "ANTHROPIC_DEFAULT_OPUS_MODEL": "claude-3-5-haiku-20241022" + "ANTHROPIC_BASE_URL": "https://claude.two" } }), None, ), ); } + let state = state_from_config(config); + state.save().expect("persist config snapshot to db"); write_json_file( &get_claude_settings_path(), @@ -5053,63 +3869,52 @@ fn updating_common_snippet_preserves_migrated_provider_owned_claude_models() { } }), ) - .expect("seed current live settings"); + .expect("seed current live settings as p1"); - let state = state_from_config(config); + crate::settings::set_current_provider(&AppType::Claude, Some("p2")) + .expect("set local effective current override to p2"); + + let provider = Provider::with_id( + "p2".to_string(), + "Second Updated".to_string(), + json!({ + "env": { + "ANTHROPIC_AUTH_TOKEN": "token2-updated", + "ANTHROPIC_BASE_URL": "https://claude.two.updated" + } + }), + None, + ); - ProviderService::set_common_config_snippet( - &state, - AppType::Claude, - Some(new_snippet.to_string()), - ) - .expect("update common snippet"); + ProviderService::update(&state, AppType::Claude, provider).expect("update should succeed"); - let cfg = state.config.read().expect("read config after update"); - let p2_after = cfg - .get_manager(&AppType::Claude) - .expect("claude manager") - .providers - .get("p2") - .expect("p2 exists"); - let p2_env = p2_after - .settings_config + let live: Value = read_json_file(&get_claude_settings_path()).expect("read live settings"); + let live_env = live .get("env") .and_then(Value::as_object) - .expect("p2 env should be object"); - - for key in [ - "ANTHROPIC_DEFAULT_HAIKU_MODEL", - "ANTHROPIC_DEFAULT_SONNET_MODEL", - "ANTHROPIC_DEFAULT_OPUS_MODEL", - ] { - assert_eq!( - p2_env.get(key).and_then(Value::as_str), - Some("claude-3-5-haiku-20241022"), - "{key} should remain provider-owned after the old common snippet is retired" - ); - } + .expect("live env should be object"); assert_eq!( - p2_env.get("ANTHROPIC_AUTH_TOKEN").and_then(Value::as_str), - Some("token2"), - "provider-specific env keys should remain after migration" + live_env.get("ANTHROPIC_AUTH_TOKEN").and_then(Value::as_str), + Some("token2-updated"), + "update should treat settings effective current (p2) as current and rewrite live settings" + ); + assert_eq!( + live_env.get("ANTHROPIC_BASE_URL").and_then(Value::as_str), + Some("https://claude.two.updated"), + "live settings should reflect updated effective current provider" ); } #[test] #[serial] -fn updating_common_snippet_skips_providers_with_apply_common_config_disabled() { +fn provider_update_clears_invalid_local_current_override_and_falls_back_to_stored_current() { let temp_home = TempDir::new().expect("create temp home"); let _env = TestEnvGuard::isolated(temp_home.path()); std::fs::create_dir_all(crate::config::get_claude_config_dir()) .expect("create ~/.claude (initialized)"); - let old_snippet = - r#"{"env":{"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC":1},"includeCoAuthoredBy":false}"#; - let new_snippet = r#"{"env":{"CLAUDE_CODE_USE_BEDROCK":1},"includeCoAuthoredBy":true}"#; - let mut config = MultiAppConfig::default(); config.ensure_app(&AppType::Claude); - config.common_config_snippets.claude = Some(old_snippet.to_string()); { let manager = config .get_manager_mut(&AppType::Claude) @@ -5131,212 +3936,186 @@ fn updating_common_snippet_skips_providers_with_apply_common_config_disabled() { ); manager.providers.insert( "p2".to_string(), - serde_json::from_value(json!({ - "id": "p2", - "name": "Second", - "settingsConfig": { - "includeCoAuthoredBy": false, + Provider::with_id( + "p2".to_string(), + "Second".to_string(), + json!({ "env": { "ANTHROPIC_AUTH_TOKEN": "token2", - "ANTHROPIC_BASE_URL": "https://claude.two", - "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": 1 + "ANTHROPIC_BASE_URL": "https://claude.two" } - }, - "meta": { "applyCommonConfig": false } - })) - .expect("parse provider p2"), + }), + None, + ), ); } + let state = state_from_config(config); + state.save().expect("persist config snapshot to db"); write_json_file( &get_claude_settings_path(), &json!({ - "includeCoAuthoredBy": false, "env": { - "ANTHROPIC_AUTH_TOKEN": "token1", - "ANTHROPIC_BASE_URL": "https://claude.one", - "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": 1 + "ANTHROPIC_AUTH_TOKEN": "token2", + "ANTHROPIC_BASE_URL": "https://claude.two" } }), ) - .expect("seed current live settings"); + .expect("seed current live settings as p2"); - let state = state_from_config(config); + crate::settings::set_current_provider(&AppType::Claude, Some("missing")) + .expect("set invalid local current override"); - ProviderService::set_common_config_snippet( - &state, - AppType::Claude, - Some(new_snippet.to_string()), - ) - .expect("update common snippet"); + let provider = Provider::with_id( + "p1".to_string(), + "First Updated".to_string(), + json!({ + "env": { + "ANTHROPIC_AUTH_TOKEN": "token1-updated", + "ANTHROPIC_BASE_URL": "https://claude.one.updated" + } + }), + None, + ); + + ProviderService::update(&state, AppType::Claude, provider).expect("update should succeed"); - let cfg = state.config.read().expect("read config after update"); - let p2_after = cfg - .get_manager(&AppType::Claude) - .expect("claude manager") - .providers - .get("p2") - .expect("p2 exists"); assert_eq!( - p2_after - .settings_config - .get("includeCoAuthoredBy") - .and_then(Value::as_bool), - Some(false), - "applyCommonConfig=false provider should keep its stored top-level fields during migration" + crate::settings::get_current_provider(&AppType::Claude), + None, + "invalid local current override should be cleared during effective-current fallback" ); - let p2_env = p2_after - .settings_config + + let live: Value = read_json_file(&get_claude_settings_path()).expect("read live settings"); + let live_env = live .get("env") .and_then(Value::as_object) - .expect("p2 env should be object"); + .expect("live env should be object"); assert_eq!( - p2_env - .get("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC") - .and_then(Value::as_i64), - Some(1), - "applyCommonConfig=false provider should keep its stored common env keys during migration" + live_env.get("ANTHROPIC_AUTH_TOKEN").and_then(Value::as_str), + Some("token1-updated"), + "update should fall back to stored current provider when local override is invalid" ); assert_eq!( - p2_env.get("ANTHROPIC_AUTH_TOKEN").and_then(Value::as_str), - Some("token2"), - "provider-specific env keys should remain untouched" + live_env.get("ANTHROPIC_BASE_URL").and_then(Value::as_str), + Some("https://claude.one.updated"), + "live settings should reflect stored current provider fallback" ); } #[test] #[serial] -fn setting_claude_common_snippet_does_not_infer_existing_provider_opt_in() { +fn common_config_snippet_is_not_persisted_into_provider_snapshot_on_switch() { let temp_home = TempDir::new().expect("create temp home"); let _env = TestEnvGuard::isolated(temp_home.path()); - std::fs::create_dir_all(crate::config::get_claude_config_dir()) - .expect("create ~/.claude (initialized)"); - - let new_snippet = - r#"{"includeCoAuthoredBy":false,"env":{"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC":1}}"#; let mut config = MultiAppConfig::default(); config.ensure_app(&AppType::Claude); - { - let manager = config - .get_manager_mut(&AppType::Claude) - .expect("claude manager"); - manager.current = "p1".to_string(); - manager.providers.insert( - "p1".to_string(), - Provider::with_id( - "p1".to_string(), - "First".to_string(), - json!({ - "includeCoAuthoredBy": false, - "env": { - "ANTHROPIC_AUTH_TOKEN": "token1", - "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": 1 - } - }), - None, - ), - ); - } + config.common_config_snippets.claude = Some( + r#"{"env":{"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC":1},"includeCoAuthoredBy":false}"# + .to_string(), + ); let state = state_from_config(config); - ProviderService::set_common_config_snippet( - &state, - AppType::Claude, - Some(new_snippet.to_string()), - ) - .expect("set common snippet"); - - let cfg = state.config.read().expect("read config after update"); - let provider = cfg - .get_manager(&AppType::Claude) - .expect("claude manager") - .providers - .get("p1") - .expect("p1 exists"); - - assert_eq!( - provider - .meta - .as_ref() - .and_then(|meta| meta.apply_common_config), + let p1 = Provider::with_id( + "p1".to_string(), + "First".to_string(), + json!({ + "env": { + "ANTHROPIC_AUTH_TOKEN": "token1", + "ANTHROPIC_BASE_URL": "https://claude.one" + } + }), None, - "setting a new snippet must not silently enable common config on existing providers" ); - assert_eq!( - provider + let p2 = Provider::with_id( + "p2".to_string(), + "Second".to_string(), + json!({ + "env": { + "ANTHROPIC_AUTH_TOKEN": "token2", + "ANTHROPIC_BASE_URL": "https://claude.two" + } + }), + None, + ); + + ProviderService::add(&state, AppType::Claude, p1).expect("add p1"); + ProviderService::add(&state, AppType::Claude, p2).expect("add p2"); + + ProviderService::switch(&state, AppType::Claude, "p2").expect("switch to p2"); + + let cfg = state.config.read().expect("read config"); + let manager = cfg.get_manager(&AppType::Claude).expect("claude manager"); + let p1_after = manager.providers.get("p1").expect("p1 exists"); + + assert!( + p1_after .settings_config .get("includeCoAuthoredBy") - .and_then(Value::as_bool), - Some(false), - "new Claude common top-level fields should remain provider-owned without explicit opt-in" + .is_none(), + "common top-level keys should not be persisted into provider snapshot" ); - let env = provider + + let env = p1_after .settings_config .get("env") .and_then(Value::as_object) - .expect("stored claude env should be object"); - assert_eq!( - env.get("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC") - .and_then(Value::as_i64), - Some(1), - "new Claude common env fields should remain provider-owned without explicit opt-in" + .expect("provider env should be object"); + assert!( + !env.contains_key("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"), + "common env keys should not be persisted into provider snapshot" ); assert_eq!( env.get("ANTHROPIC_AUTH_TOKEN").and_then(Value::as_str), Some("token1"), - "provider-specific Claude env should remain after normalization" + "provider-specific env should remain in snapshot" ); } #[test] #[serial] -fn clearing_claude_common_snippet_tolerates_invalid_stored_snippet() { +fn switch_backfill_preserves_matching_common_fields_when_meta_missing() { let temp_home = TempDir::new().expect("create temp home"); let _env = TestEnvGuard::isolated(temp_home.path()); - std::fs::create_dir_all(crate::config::get_claude_config_dir()) - .expect("create ~/.claude (initialized)"); - - let invalid_old_snippet = r#"{"env":{"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC":1}"#; let mut config = MultiAppConfig::default(); config.ensure_app(&AppType::Claude); - config.common_config_snippets.claude = Some(invalid_old_snippet.to_string()); - { - let manager = config - .get_manager_mut(&AppType::Claude) - .expect("claude manager"); - manager.current = "p1".to_string(); - manager.providers.insert( - "p1".to_string(), - Provider::with_id( - "p1".to_string(), - "First".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token1", - "ANTHROPIC_BASE_URL": "https://claude.one" - } - }), - None, - ), - ); - manager.providers.insert( - "p2".to_string(), - Provider::with_id( - "p2".to_string(), - "Second".to_string(), - json!({ - "env": { - "ANTHROPIC_AUTH_TOKEN": "token2", - "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": 1 - } - }), - None, - ), - ); - } + config.common_config_snippets.claude = Some( + r#"{"env":{"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC":1},"includeCoAuthoredBy":false}"# + .to_string(), + ); + + let mut p1 = Provider::with_id( + "p1".to_string(), + "First".to_string(), + json!({ + "env": { + "ANTHROPIC_AUTH_TOKEN": "token1", + "ANTHROPIC_BASE_URL": "https://claude.one", + "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": 1 + }, + "includeCoAuthoredBy": false + }), + None, + ); + p1.meta = None; + let p2 = Provider::with_id( + "p2".to_string(), + "Second".to_string(), + json!({ + "env": { + "ANTHROPIC_AUTH_TOKEN": "token2", + "ANTHROPIC_BASE_URL": "https://claude.two" + } + }), + None, + ); + + let state = state_from_config(config); + ProviderService::add(&state, AppType::Claude, p1).expect("add p1"); + ProviderService::add(&state, AppType::Claude, p2).expect("add p2"); write_json_file( &get_claude_settings_path(), @@ -5345,37 +4124,40 @@ fn clearing_claude_common_snippet_tolerates_invalid_stored_snippet() { "ANTHROPIC_AUTH_TOKEN": "token1", "ANTHROPIC_BASE_URL": "https://claude.one", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": 1 - } + }, + "includeCoAuthoredBy": false }), ) - .expect("seed current live settings"); + .expect("seed live settings with provider-owned fields matching common snippet"); - let state = state_from_config(config); - state.save().expect("persist config snapshot to db"); + ProviderService::switch(&state, AppType::Claude, "p2").expect("switch to p2"); - ProviderService::clear_common_config_snippet(&state, AppType::Claude) - .expect("clear should recover from invalid stored snippet"); + let cfg = state.config.read().expect("read config"); + let manager = cfg.get_manager(&AppType::Claude).expect("claude manager"); + let p1_after = manager.providers.get("p1").expect("p1 exists"); + let env = p1_after + .settings_config + .get("env") + .and_then(Value::as_object) + .expect("provider env should be object"); - let cfg = state.config.read().expect("read config after clear"); assert_eq!( - cfg.common_config_snippets.claude, None, - "invalid stored snippet should not block clearing the saved common snippet" + p1_after.settings_config.get("includeCoAuthoredBy"), + Some(&json!(false)), + "matching top-level fields are provider-owned when common config was never explicitly enabled" ); - drop(cfg); - - let live: Value = read_json_file(&get_claude_settings_path()).expect("read live settings"); - let env = live - .get("env") - .and_then(Value::as_object) - .expect("live env should be object"); - assert!( - env.contains_key("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"), - "an unreadable old snippet cannot establish ownership of existing user settings" + assert_eq!( + env.get("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"), + Some(&json!(1)), + "matching env fields are provider-owned when common config was never explicitly enabled" ); assert_eq!( - env.get("ANTHROPIC_AUTH_TOKEN").and_then(Value::as_str), - Some("token1"), - "provider-specific Claude env should remain after recovery" + p1_after + .meta + .as_ref() + .and_then(|meta| meta.apply_common_config), + None, + "backfill must not silently opt missing-meta providers into common config" ); } @@ -7863,52 +6645,6 @@ fn key_field_gemini_invalid_settings_does_not_publish_env_or_pointer() { ); } -#[test] -#[serial] -fn key_field_common_edit_preserves_active_proxy_route() { - let (_home, _env, state) = setup_claude_switch_preview_state(json!({ - "env": {"ANTHROPIC_AUTH_TOKEN":"PROXY_MANAGED", "ANTHROPIC_BASE_URL":"http://127.0.0.1:15721"}, - "permissions": {"allow":["Read"]} - })); - { - let mut config = state.config.write().unwrap(); - let current = config - .get_manager_mut(&AppType::Claude) - .unwrap() - .providers - .get_mut("p1") - .unwrap(); - current.meta = Some(ProviderMeta { - apply_common_config: Some(true), - ..Default::default() - }); - } - state.save().unwrap(); - ProviderService::set_common_config_snippet( - &state, - AppType::Claude, - Some(r#"{"env":{"API_TIMEOUT_MS":"999"},"includeCoAuthoredBy":false}"#.into()), - ) - .expect("edit global settings while proxy is attached"); - let live: Value = read_json_file(&get_claude_settings_path()).unwrap(); - assert_eq!(live["env"]["ANTHROPIC_AUTH_TOKEN"], "PROXY_MANAGED"); - assert_eq!(live["env"]["ANTHROPIC_BASE_URL"], "http://127.0.0.1:15721"); - assert_eq!(live["env"]["API_TIMEOUT_MS"], "999"); - assert_eq!(live["includeCoAuthoredBy"], false); - assert_eq!(live["permissions"]["allow"], json!(["Read"])); - for env in [json!(null), json!("invalid"), json!([])] { - ProviderService::set_common_config_snippet( - &state, - AppType::Claude, - Some(json!({"env":env}).to_string()), - ) - .unwrap(); - let live: Value = read_json_file(&get_claude_settings_path()).unwrap(); - assert_eq!(live["env"]["ANTHROPIC_AUTH_TOKEN"], "PROXY_MANAGED"); - assert_eq!(live["env"]["ANTHROPIC_BASE_URL"], "http://127.0.0.1:15721"); - } -} - #[tokio::test] #[serial] async fn key_field_proxy_update_cleans_removed_exclusive_fields() { @@ -8276,3 +7012,356 @@ async fn key_field_gemini_removing_entire_config_does_not_restore_old_model() { assert!(settings.pointer("/model/name").is_none()); } } + +#[test] +#[serial] +fn claude_editor_saves_issue_530_fields_and_preserves_globals_on_switch() { + let home = TempDir::new().unwrap(); + let _env = TestEnvGuard::isolated(home.path()); + std::fs::create_dir_all(crate::config::get_claude_config_dir()).unwrap(); + let mut config = MultiAppConfig::default(); + config.ensure_app(&AppType::Claude); + let state = state_from_config(config); + let mut first = Provider::with_id( + "first".into(), + "First".into(), + json!({"env":{"ANTHROPIC_AUTH_TOKEN":"key-first","ANTHROPIC_BASE_URL":"https://first.example"}}), + None, + ); + let second = Provider::with_id( + "second".into(), + "Second".into(), + json!({"env":{"ANTHROPIC_AUTH_TOKEN":"key-second","ANTHROPIC_BASE_URL":"https://second.example"}}), + None, + ); + ProviderService::add(&state, AppType::Claude, first.clone()).unwrap(); + ProviderService::add(&state, AppType::Claude, second.clone()).unwrap(); + let view = ProviderService::claude_editor_view(&state, &first.settings_config).unwrap(); + first.settings_config = view.settings.clone(); + first.settings_config["env"]["CLAUDE_CODE_DISABLE_1M_CONTEXT"] = json!("1"); + first.settings_config["env"]["CLAUDE_CODE_MAX_CONTEXT_TOKENS"] = json!("120000"); + first.settings_config["env"]["CLAUDE_CODE_AUTO_COMPACT_WINDOW"] = json!("102000"); + first.settings_config["language"] = json!("chinese"); + first.settings_config["disableDeepLinkRegistration"] = json!("disable"); + ProviderService::save_claude_from_editor( + &state, + first, + claude_editor::EditorSave { + base: view.settings, + draft: None, + on_conflict: Default::default(), + }, + false, + None, + ) + .unwrap(); + let live: Value = read_json_file(&get_claude_settings_path()).unwrap(); + assert_eq!(live["env"]["CLAUDE_CODE_MAX_CONTEXT_TOKENS"], "120000"); + assert_eq!(live["env"]["CLAUDE_CODE_DISABLE_1M_CONTEXT"], "1"); + assert_eq!(live["env"]["CLAUDE_CODE_AUTO_COMPACT_WINDOW"], "102000"); + assert_eq!(live["language"], "chinese"); + assert_eq!(live["disableDeepLinkRegistration"], "disable"); + let stored = state + .db + .get_provider_by_id("first", "claude") + .unwrap() + .unwrap(); + assert!(stored.settings_config.get("language").is_none()); + assert_eq!( + stored.settings_config["env"]["CLAUDE_CODE_MAX_CONTEXT_TOKENS"], + "120000" + ); + ProviderService::switch(&state, AppType::Claude, "second").unwrap(); + let live: Value = read_json_file(&get_claude_settings_path()).unwrap(); + assert_eq!(live["language"], "chinese"); + assert!(live["env"].get("CLAUDE_CODE_MAX_CONTEXT_TOKENS").is_none()); + assert_eq!(live["env"]["ANTHROPIC_AUTH_TOKEN"], "key-second"); + ProviderService::switch(&state, AppType::Claude, "first").unwrap(); + let live: Value = read_json_file(&get_claude_settings_path()).unwrap(); + assert_eq!(live["env"]["CLAUDE_CODE_MAX_CONTEXT_TOKENS"], "120000"); +} + +#[test] +#[serial] +fn claude_editor_inactive_save_conflicts_are_explicit_and_row_is_rolled_back() { + use claude_editor::{ConflictPolicy, EditorSave}; + let home = TempDir::new().unwrap(); + let _env = TestEnvGuard::isolated(home.path()); + std::fs::create_dir_all(crate::config::get_claude_config_dir()).unwrap(); + let mut config = MultiAppConfig::default(); + config.ensure_app(&AppType::Claude); + let state = state_from_config(config); + let first = Provider::with_id( + "first".into(), + "First".into(), + json!({"env":{"ANTHROPIC_AUTH_TOKEN":"key-first"}}), + None, + ); + let mut second = Provider::with_id( + "second".into(), + "Second".into(), + json!({"env":{"ANTHROPIC_AUTH_TOKEN":"key-second"},"language":"legacy"}), + None, + ); + ProviderService::add(&state, AppType::Claude, first).unwrap(); + ProviderService::add(&state, AppType::Claude, second.clone()).unwrap(); + let view = ProviderService::claude_editor_view(&state, &second.settings_config).unwrap(); + assert_eq!(view.inactive.len(), 1); + assert!(view.settings.get("language").is_none()); + second.settings_config = view.settings.clone(); + second.settings_config["language"] = json!("mine"); + second.settings_config["env"]["ANTHROPIC_AUTH_TOKEN"] = json!("new-key"); + second.settings_config["permissions"] = json!({"allow":["Read"]}); + let path = get_claude_settings_path(); + let mut external: Value = read_json_file(&path).unwrap(); + external["language"] = json!("external"); + external["env"]["EXTERNAL_UNTOUCHED"] = json!("keep"); + std::fs::write(&path, serde_json::to_vec(&external).unwrap()).unwrap(); + let editor = EditorSave { + base: view.settings, + draft: None, + on_conflict: ConflictPolicy::Refuse, + }; + let before_copy = serde_json::to_value(state.db.get_all_providers("claude").unwrap()).unwrap(); + let copy_error = ProviderService::save_claude_from_editor( + &state, + second.clone(), + editor.clone(), + true, + Some("first"), + ) + .unwrap_err(); + assert!(claude_editor::conflict_keys(©_error).is_some()); + assert_eq!( + serde_json::to_value(state.db.get_all_providers("claude").unwrap()).unwrap(), + before_copy + ); + assert_eq!(read_json_file::(&path).unwrap(), external); + let error = ProviderService::save_claude_from_editor( + &state, + second.clone(), + editor.clone(), + false, + None, + ) + .unwrap_err(); + assert_eq!( + claude_editor::conflict_keys(&error).unwrap(), + vec!["language"] + ); + assert_eq!(read_json_file::(&path).unwrap(), external); + assert_eq!( + state + .db + .get_provider_by_id("second", "claude") + .unwrap() + .unwrap() + .settings_config["env"]["ANTHROPIC_AUTH_TOKEN"], + "key-second" + ); + ProviderService::save_claude_from_editor( + &state, + second.clone(), + EditorSave { + on_conflict: ConflictPolicy::KeepTheirs, + ..editor.clone() + }, + false, + None, + ) + .unwrap(); + let live: Value = read_json_file(&path).unwrap(); + assert_eq!(live["language"], "external"); + assert_eq!(live["permissions"]["allow"], json!(["Read"])); + assert_eq!(live["env"]["ANTHROPIC_AUTH_TOKEN"], "key-first"); + assert_eq!(live["env"]["EXTERNAL_UNTOUCHED"], "keep"); + ProviderService::save_claude_from_editor( + &state, + second, + EditorSave { + on_conflict: ConflictPolicy::KeepMine, + ..editor + }, + false, + None, + ) + .unwrap(); + assert_eq!(read_json_file::(&path).unwrap()["language"], "mine"); +} + +#[tokio::test] +#[serial] +async fn claude_editor_proxy_save_keeps_route_and_globals_after_restore() { + let (_home, _env, state) = setup_claude_switch_preview_state(json!({"env":{}})); + state.db.set_app_proxy_preferred_port("claude", 0).unwrap(); + state + .proxy_service + .set_takeover_for_app("claude", true) + .await + .unwrap(); + let mut provider = state + .db + .get_provider_by_id("p1", "claude") + .unwrap() + .unwrap(); + let view = ProviderService::claude_editor_view(&state, &provider.settings_config).unwrap(); + let expected_key = view.settings["env"]["ANTHROPIC_AUTH_TOKEN"].clone(); + assert_ne!(expected_key, json!("PROXY_MANAGED")); + provider.settings_config = view.settings.clone(); + provider.settings_config["language"] = json!("chinese"); + provider.settings_config["env"]["CLAUDE_CODE_MAX_CONTEXT_TOKENS"] = json!("120000"); + ProviderService::save_claude_from_editor( + &state, + provider, + claude_editor::EditorSave { + base: view.settings, + draft: None, + on_conflict: Default::default(), + }, + false, + None, + ) + .unwrap(); + let live: Value = read_json_file(&get_claude_settings_path()).unwrap(); + assert_eq!(live["env"]["ANTHROPIC_AUTH_TOKEN"], "PROXY_MANAGED"); + assert_eq!(live["env"]["CLAUDE_CODE_MAX_CONTEXT_TOKENS"], "120000"); + assert_eq!(live["language"], "chinese"); + state + .proxy_service + .set_takeover_for_app("claude", false) + .await + .unwrap(); + let live: Value = read_json_file(&get_claude_settings_path()).unwrap(); + assert_eq!(live["env"]["ANTHROPIC_AUTH_TOKEN"], expected_key); + assert_eq!(live["language"], "chinese"); + assert_eq!(live["env"]["CLAUDE_CODE_MAX_CONTEXT_TOKENS"], "120000"); +} + +#[test] +#[serial] +fn claude_editor_preserves_legacy_snippet_and_row_data_without_runtime_merging() { + let home = TempDir::new().unwrap(); + let _env = TestEnvGuard::isolated(home.path()); + let snippet = r#"{"env":{"CLAUDE_CODE_MAX_CONTEXT_TOKENS":"120000"},"language":"legacy"}"#; + let row = json!({"env":{"ANTHROPIC_AUTH_TOKEN":"key","CLAUDE_CODE_MAX_CONTEXT_TOKENS":"120000"},"language":"legacy"}); + let mut config = MultiAppConfig::default(); + config.ensure_app(&AppType::Claude); + config.common_config_snippets.claude = Some(snippet.into()); + let mut provider = with_common_enabled(Provider::with_id( + "p1".into(), + "First".into(), + row.clone(), + None, + )); + config + .get_manager_mut(&AppType::Claude) + .unwrap() + .providers + .insert("p1".into(), provider.clone()); + let state = state_from_config(config); + super::common_config::migrate_common_config_upstream_semantics_if_needed( + &state.db, + &mut state.config.write().unwrap(), + ) + .unwrap(); + assert_eq!( + state + .db + .get_provider_by_id("p1", "claude") + .unwrap() + .unwrap() + .settings_config, + row + ); + assert_eq!( + state.db.get_config_snippet("claude").unwrap().as_deref(), + Some(snippet) + ); + assert!( + ProviderService::set_common_config_snippet(&state, AppType::Claude, Some("{}".into())) + .is_err() + ); + assert_eq!( + state.db.get_config_snippet("claude").unwrap().as_deref(), + Some(snippet) + ); + let view = ProviderService::claude_editor_view(&state, &provider.settings_config).unwrap(); + assert!(view.settings.get("language").is_none()); + assert!(view + .inactive + .iter() + .any(|field| field.path == vec!["language"])); + provider.settings_config = view.settings.clone(); + provider.settings_config["language"] = json!("chinese"); + ProviderService::save_claude_from_editor( + &state, + provider, + claude_editor::EditorSave { + base: view.settings, + draft: None, + on_conflict: Default::default(), + }, + false, + None, + ) + .unwrap(); + let saved = state + .db + .get_provider_by_id("p1", "claude") + .unwrap() + .unwrap(); + assert_eq!(saved.settings_config["language"], "legacy"); + assert_eq!( + saved.settings_config["env"]["CLAUDE_CODE_MAX_CONTEXT_TOKENS"], + "120000" + ); + assert_eq!( + read_json_file::(&get_claude_settings_path()).unwrap()["language"], + "chinese" + ); +} + +#[test] +#[serial] +fn claude_editor_first_add_commits_pointer_and_compatibility_marker() { + let home = tempfile::TempDir::new().unwrap(); + let _env = TestEnvGuard::isolated(home.path()); + let mut config = MultiAppConfig::default(); + config.ensure_app(&AppType::Claude); + let state = state_from_config(config); + let view = ProviderService::claude_editor_view(&state, &json!({})).unwrap(); + let provider = Provider::with_id( + "first".into(), + "First".into(), + json!({"env":{"ANTHROPIC_AUTH_TOKEN":"first-key"},"language":"chinese"}), + None, + ); + ProviderService::save_claude_from_editor( + &state, + provider, + claude_editor::EditorSave { + base: view.settings, + draft: None, + on_conflict: Default::default(), + }, + true, + None, + ) + .unwrap(); + assert_eq!( + crate::settings::get_effective_current_provider(&state.db, &AppType::Claude) + .unwrap() + .as_deref(), + Some("first") + ); + let stored = state + .db + .get_provider_by_id("first", "claude") + .unwrap() + .unwrap(); + assert_eq!(stored.meta.unwrap().apply_common_config, Some(true)); + assert!(stored.settings_config.get("language").is_none()); + let live: Value = read_json_file(&get_claude_settings_path()).unwrap(); + assert_eq!(live["language"], "chinese"); + assert_eq!(live["env"]["ANTHROPIC_AUTH_TOKEN"], "first-key"); +} diff --git a/src-tauri/src/store.rs b/src-tauri/src/store.rs index 89f01708..6d2d4d3a 100644 --- a/src-tauri/src/store.rs +++ b/src-tauri/src/store.rs @@ -1303,11 +1303,9 @@ requires_openai_auth = true let state = AppState::try_new_with_startup_recovery().expect("first startup"); assert!(state.db.get_config_snippet("claude").unwrap().is_some()); - crate::services::provider::ProviderService::clear_common_config_snippet( - &state, - crate::app_config::AppType::Claude, - ) - .expect("clear snippet"); + // A previous-version client cleared this compatibility data. + state.db.set_config_snippet("claude", None).unwrap(); + state.db.set_config_snippet_cleared("claude", true).unwrap(); assert!(state.db.is_config_snippet_cleared("claude").unwrap()); assert!(state.db.get_config_snippet("claude").unwrap().is_none()); diff --git a/src-tauri/tests/provider_commands.rs b/src-tauri/tests/provider_commands.rs index 0982b702..49062575 100644 --- a/src-tauri/tests/provider_commands.rs +++ b/src-tauri/tests/provider_commands.rs @@ -406,7 +406,7 @@ fn provider_usage_query_set_rejects_enabled_script_without_return() { #[test] #[serial] -fn provider_export_writes_merged_claude_settings_to_default_path() { +fn provider_export_does_not_replay_legacy_claude_snippets() { let _guard = lock_test_mutex(); reset_test_fs(); let home = ensure_test_home(); @@ -476,15 +476,15 @@ fn provider_export_writes_merged_claude_settings_to_default_path() { .get("env") .and_then(|v| v.get("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC")) .and_then(|v| v.as_i64()), - Some(1), - "common config snippet should be merged into export" + None, + "legacy common snippets must not be replayed into exports" ); assert_eq!( exported .get("includeCoAuthoredBy") .and_then(|v| v.as_bool()), - Some(false), - "top-level common config should be present in export" + None, + "legacy global snippet values must not enter exports" ); assert_eq!( exported From c42a20fc3363370d815e4fb8c8633b8a0865c7d8 Mon Sep 17 00:00:00 2001 From: saladday <1203511142@qq.com> Date: Wed, 4 Nov 2026 22:43:07 +0800 Subject: [PATCH 08/23] docs: add IPWO as sixth sponsor --- README.md | 12 ++++++++++++ README_JA.md | 12 ++++++++++++ README_ZH.md | 12 ++++++++++++ assets/partners/logos/ipwo.png | Bin 0 -> 157433 bytes 4 files changed, 36 insertions(+) create mode 100644 assets/partners/logos/ipwo.png diff --git a/README.md b/README.md index 6d450740..82b80904 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,18 @@ This project is a **CLI fork** of [CC-Switch](https://github.com/farion1231/cc-s PackyCode provides special discounts for our software users: register via this link and use promo code cc-switch-cli when recharging to get 10% off. + + + + IPWO + + + + Thanks to IPWO for sponsoring this project! IPWO offers a free trial and access to over 90 million active residential IPs across 195+ countries and regions. It supports rotating, static, and unlimited-bandwidth residential proxies, with HTTP(S) and SOCKS5 compatibility.
+ From AI tool development and cross-region network access to API debugging and data collection, IPWO gives developers flexible residential proxy options for applications in different regions.
+ Visit IPWO and use promo code 0200 for 10% off. + + diff --git a/README_JA.md b/README_JA.md index 4566dcb8..3ded4984 100644 --- a/README_JA.md +++ b/README_JA.md @@ -77,6 +77,18 @@ CC-Switch CLI ユーザー向けの割引として、こちらのリンクから登録し、チャージ時にクーポンコード cc-switch-cli を入力すると、10% オフになります。 + + + + IPWO + + + + 本プロジェクトをご支援いただいている IPWO に感謝します!IPWO は無料でお試しいただける住宅用プロキシサービスで、195 以上の国と地域にわたる 9,000 万以上のアクティブな住宅用 IP を提供しています。ローテーション型、固定型、通信量無制限の住宅用プロキシに対応し、HTTP(S) と SOCKS5 を利用できます。
+ AI ツールの開発、地域をまたぐネットワークアクセス、API のデバッグ、データ収集など、さまざまな地域でのアプリケーション開発に向けて、柔軟な住宅用プロキシの選択肢を提供します。
+ こちらのリンクから IPWO にアクセスし、クーポンコード 0200 を入力すると、10% オフになります。 + + diff --git a/README_ZH.md b/README_ZH.md index e6f6f149..045fb331 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -72,6 +72,18 @@ 注册,并在充值时填写优惠码 cc-switch-cli,即可享受 9 折优惠。 + + + + IPWO + + + + 感谢 IPWO 赞助本项目!IPWO 可以免费测试,提供覆盖 195+ 个国家和地区的 9000 万+ 活跃住宅 IP 资源,支持动态住宅代理、静态住宅代理及不限量住宅代理,并兼容 HTTP(S) 和 SOCKS5 协议。
+ 无论是 AI 工具开发、跨区域网络访问,还是 API 调试与数据采集,IPWO 都能为开发者提供灵活的住宅代理选择,帮助拓展不同地区的网络应用场景。
+ 通过此链接访问 IPWO,使用优惠码 0200,即可减免 10%。 + + diff --git a/assets/partners/logos/ipwo.png b/assets/partners/logos/ipwo.png new file mode 100644 index 0000000000000000000000000000000000000000..e106671fa62ce20244944c2119eeec8cf57d7cba GIT binary patch literal 157433 zcmeEvc|4Wr`~Q88wW)AgP}$-{HAYHtETKV?N}G`Flwwl0WScBcqoUDJOi@HlQ<6et z7pGEEmKw4zM?{nD#8}GqyYA$;!k`JCIi z!*Kq0OTR-1%{SVjzZ)S53POCNg8c9s-O|kW@Si!ZTP)lWQj){}qj=xa@kB@l8R>7@ z>mAe8xXD?fy7o+qot*n|fp_Hhb>qLp;2;Q#UGGx`WD_ut0#3xYEL?Qih=MGGjr|NYOz zkFvyn|0~+L<$s%=X`cUidZtCt|KL5#B>#))*(O2%BeGdW`5$}FGRgl^)@+mfFHg_5 z$^Wg;_H?X z7hO+h=J<3|1iI+sP08;W#hrC>gky#eqr^Xe;gUAuc3l!N-(Ahn`I9l2uYNA`!qxV4 z0di%IVd!plF=zZAhG^EWu5eY|#Q{EY{-a?geV<3(n>U?sR`Kn1?RC?2?f+ogzj3D2 zWNisXeaB$pGFPkjbYTIrb`y^D#>;^}Af#20s3l=vup`y&cS$5vanp{~->BmeE*%y% zCxQpL_G(wTj(x~fhD);4e*VYlNFV2Rz{K-j>v4Cp+~(-U^0<~S9%`1R7PBrHr;mIV zY_E?y#CWo^ub>2XCyonm;pUD6ZX^yd)j{dYRi^ai8)6RVuye+3-kAT zrJ26n01G}+H%=Gs-Pun!T-*U0sBW+y61vp#gX12zx$t9J&7;P+LxQ6l$GcDdHRcwv zd|uYp)M60KVLj|}vCaDZDug&UlVraWL?=6U;a_>YT?@am)2C1n z@y4-koT10=9q*tQ*I$huK2T4urU}fn&hT=W?`;qJi^b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ju(O3%0AgEtaRLIe7R&{_DVJ zF}~pknoa8#Jky0VYfJf>(KQVJlw%~4(cT~WR~GsI6ny$?Y5(Z@t4|p<6~XLF8*b*e zI2kx(Bw!=hbu~q4Zfp%0U`lk5tL};J&iG?`mm%6!`bG~=H~Rmc4WcDJY=R{^0_ppD z8Z;24S1${Bt?c;5{kN}s8fknQhu0 zy(8|-4p#fQec63^p`q*8&j;KAIB{SaGX(QQbD9#Tjk@XF9pDYGy9`yWQ|{JK%5PRO zasIWt#Z_Bj>)_jN*lTbz1J6+7HDlU_0>4X5dLeCtz8~(TEmPEb*w?k)U0CCGwxgvG z-Y7J7P%)xAS#1SlK6#q%Zoh3?>JUcyaTeN}3G)x|Yj?Px?Wnl$C8Q($$wWzG=N$fh zQ)lXnFO6^bUjaw9iekd(Uq1WE{4}xi&;ItwFLQn&0p*jweEQ@6F8)*+ Date: Wed, 4 Nov 2026 07:29:11 -0800 Subject: [PATCH 09/23] fix(presets): refresh provider model templates to current lineups (#548) * fix(presets): refresh provider model templates to current lineups Mirror the desktop presets at farion1231/cc-switch e217bfc (2026-11-03) across the bundled Claude, Codex, Gemini, Pi, OpenCode, OpenClaw and Hermes templates. - Claude and Codex defaults move to claude-*-5-5, gpt-6.1-sol / gpt-6-luna, a 272000 OAuth context window, and gemini-3.8-flash. - DeepSeek V4.1 Flash, GLM-5.3, MiniMax-M3.1-Flash and MiMo V2.6 model rows, with matching reasoning levels, modalities and context windows. - Pi sponsor and gateway presets (OpenCode Go, Qiniu, OpenRouter) refreshed, including the Pi thinking maps and the 88API mirror. - Pricing seeds for the new models plus the GPT-5.6 Sol promotional tier with repair guards for both old built-in generations. * fix(presets): align upstream defaults and complete model pricing --------- Co-authored-by: saladday <1203511142@qq.com> --- src-tauri/src/cli/commands/provider.rs | 6 +- src-tauri/src/cli/commands/provider_input.rs | 102 +++--- .../src/cli/tui/form/provider_templates.rs | 19 +- src-tauri/src/cli/tui/form/tests.rs | 308 +++++++++++------- src-tauri/src/database/schema.rs | 218 ++++++++++++- src-tauri/src/database/tests.rs | 102 +++++- src-tauri/src/model_capabilities.rs | 12 + src-tauri/src/presets/88api.json | 45 ++- src-tauri/src/presets/README.md | 4 +- src-tauri/src/provider_preset_builtin.rs | 190 ++++++----- src-tauri/src/provider_preset_models.rs | 112 ++++--- src-tauri/src/provider_preset_pi.rs | 228 ++++++++----- src-tauri/src/proxy/providers/codex.rs | 15 +- src-tauri/src/services/provider/tests.rs | 2 +- src-tauri/src/services/usage_stats.rs | 6 +- .../tests/provider_add_noninteractive.rs | 24 +- 16 files changed, 971 insertions(+), 422 deletions(-) diff --git a/src-tauri/src/cli/commands/provider.rs b/src-tauri/src/cli/commands/provider.rs index 056b7cf9..45b0593b 100644 --- a/src-tauri/src/cli/commands/provider.rs +++ b/src-tauri/src/cli/commands/provider.rs @@ -2326,10 +2326,14 @@ mod tests { &mut prompt_result, ) .expect("build Codex settings"); + let default_model = format!( + "model = \"{}\"", + crate::provider_preset_models::CODEX_DEFAULT_MODEL + ); assert!(codex["config"] .as_str() .expect("Codex config should be TOML") - .contains("model = \"gpt-5.6-sol\"")); + .contains(&default_model)); let gemini = build_add_settings_config( &AppType::Gemini, diff --git a/src-tauri/src/cli/commands/provider_input.rs b/src-tauri/src/cli/commands/provider_input.rs index c52d9621..4c98f55c 100644 --- a/src-tauri/src/cli/commands/provider_input.rs +++ b/src-tauri/src/cli/commands/provider_input.rs @@ -12,8 +12,9 @@ use crate::error::AppError; use crate::provider::{AuthBinding, AuthBindingSource, ClaudeApiKeyField, Provider, ProviderMeta}; use crate::provider_preset_builtin::{builtin_provider_preset_value, BuiltinProviderPresetId}; use crate::provider_preset_models::{ - codex_oauth_claude_env, sponsor_hermes_models, sponsor_model_family, sponsor_openclaw_models, - sponsor_opencode_settings, SponsorModelFamily, CODEX_DEFAULT_MODEL, GEMINI_DEFAULT_MODEL, + codex_oauth_claude_env, sponsor_codex_model, sponsor_hermes_models, sponsor_model_family, + sponsor_openclaw_models, sponsor_opencode_settings, SponsorModelFamily, CODEX_DEFAULT_MODEL, + GEMINI_DEFAULT_MODEL, }; use crate::provider_preset_sponsors::{ sponsor_provider_preset, sponsor_provider_presets_for_app, SponsorProviderPreset, @@ -586,7 +587,7 @@ fn build_sponsor_template_settings_config( Ok(build_codex_settings_config( None, preset.codex_base_url, - CODEX_DEFAULT_MODEL, + sponsor_codex_model(preset.id), "responses", provider_name, )) @@ -628,7 +629,9 @@ fn build_sponsor_template_settings_config( SponsorModelFamily::Claude | SponsorModelFamily::RunApiClaude => { "anthropic_messages" } - SponsorModelFamily::Gpt => crate::hermes_config::HERMES_DEFAULT_API_MODE, + SponsorModelFamily::Gpt | SponsorModelFamily::GptAstra => { + crate::hermes_config::HERMES_DEFAULT_API_MODE + } }, preset.hermes_base_url, "", @@ -655,7 +658,7 @@ fn build_sponsor_template_settings_config( SponsorModelFamily::Claude | SponsorModelFamily::RunApiClaude => { "anthropic-messages" } - SponsorModelFamily::Gpt => { + SponsorModelFamily::Gpt | SponsorModelFamily::GptAstra => { crate::openclaw_config::OPENCLAW_DEFAULT_API_PROTOCOL } }, @@ -924,7 +927,7 @@ env_key = "OLD_API_KEY" .get("config") .and_then(Value::as_str) .expect("config should be present"); - assert!(config.contains("model = \"gpt-5.6-sol\"")); + assert!(config.contains("model = \"gpt-6.1-sol\"")); assert!(config.contains("base_url = \"https://api.example.com/v1\"")); } @@ -1384,19 +1387,19 @@ requires_openai_auth = true ); assert_eq!( provider.settings_config["env"]["ANTHROPIC_MODEL"], - "gpt-5.6-sol" + "gpt-6.1-sol" ); assert_eq!( provider.settings_config["env"]["ANTHROPIC_DEFAULT_HAIKU_MODEL"], - "gpt-5.6-luna" + "gpt-6-luna" ); assert_eq!( provider.settings_config["env"]["CLAUDE_CODE_MAX_CONTEXT_TOKENS"], - "372000" + "272000" ); assert_eq!( provider.settings_config["env"]["CLAUDE_CODE_AUTO_COMPACT_WINDOW"], - "372000" + "272000" ); assert!( provider.settings_config["env"] @@ -1479,7 +1482,7 @@ requires_openai_auth = true let config = codex.settings_config["config"] .as_str() .expect("PatewayAI Codex config should be TOML"); - assert!(config.contains("model = \"gpt-5.6-sol\"")); + assert!(config.contains("model = \"gpt-6.1-sol\"")); assert!(config.contains("base_url = \"https://api.pateway.ai/v1\"")); assert!(config.contains("name = \"patewayai\"")); assert!(config.contains("wire_api = \"responses\"")); @@ -1878,7 +1881,7 @@ requires_openai_auth = true .and_then(Value::as_str) .expect("DeepSeek Codex config should be TOML string"); assert!(config.contains("model_provider = \"custom\"")); - assert!(config.contains("model = \"deepseek-v4-flash\"")); + assert!(config.contains("model = \"deepseek-flash\"")); assert!(config.contains("disable_response_storage = true")); assert!(config.contains("[model_providers.custom]")); assert!(config.contains("name = \"deepseek\"")); @@ -1895,15 +1898,10 @@ requires_openai_auth = true json!({ "models": [ { - "model": "deepseek-v4-flash", - "displayName": "DeepSeek V4 Flash", - "contextWindow": 1048576, - "reasoningLevels": ["low", "high", "max"], - }, - { - "model": "deepseek-v4-pro", - "displayName": "DeepSeek V4 Pro", + "model": "deepseek-flash", + "displayName": "DeepSeek V4.1 Flash", "contextWindow": 1048576, + "inputModalities": ["text", "image"], "reasoningLevels": ["low", "high", "max"], }, ], @@ -1927,7 +1925,7 @@ requires_openai_auth = true .expect("Codex sponsor config should be TOML string"); assert_eq!(codex.name, "PackyCode"); assert!(codex_config.contains("base_url = \"https://www.packyapi.ai/v1\"")); - assert!(codex_config.contains("model = \"gpt-5.6-sol\"")); + assert!(codex_config.contains("model = \"gpt-6.1-sol\"")); assert!(codex_config.contains("wire_api = \"responses\"")); assert_eq!( codex @@ -1960,8 +1958,8 @@ requires_openai_auth = true "https://api.aicodemirror.ai/api/claudecode" ); assert_eq!( - opencode.settings_config["models"]["claude-opus-5"]["name"], - "Claude Opus 5" + opencode.settings_config["models"]["claude-opus-5-5"]["name"], + "Claude Opus 5.5" ); assert_eq!( opencode @@ -1983,9 +1981,9 @@ requires_openai_auth = true assert_eq!( hermes.settings_config["models"], json!([ - { "id": "claude-opus-5", "name": "Claude Opus 5" }, - { "id": "claude-sonnet-5", "name": "Claude Sonnet 5" }, - { "id": "claude-haiku-4-5-20251001", "name": "Claude Haiku 4.5" }, + { "id": "claude-opus-5-5", "name": "Claude Opus 5.5" }, + { "id": "claude-sonnet-5-5", "name": "Claude Sonnet 5.5" }, + { "id": "claude-haiku-5-5", "name": "Claude Haiku 5.5" }, ]) ); @@ -2001,16 +1999,22 @@ requires_openai_auth = true openclaw.settings_config["models"], json!([ { - "id": "claude-opus-5", - "name": "Claude Opus 5", + "id": "claude-opus-5-5", + "name": "Claude Opus 5.5", + "reasoning": true, + "input": ["text", "image"], "contextWindow": 1000000, - "cost": { "input": 5, "output": 25 }, + "maxTokens": 128000, + "cost": { "input": 4, "output": 20, "cacheRead": 0.2, "cacheWrite": 5 }, }, { - "id": "claude-sonnet-5", - "name": "Claude Sonnet 5", + "id": "claude-sonnet-5-5", + "name": "Claude Sonnet 5.5", + "reasoning": true, + "input": ["text", "image"], "contextWindow": 1000000, - "cost": { "input": 3, "output": 15 }, + "maxTokens": 128000, + "cost": { "input": 2, "output": 10, "cacheRead": 0.1, "cacheWrite": 2.5 }, }, ]) ); @@ -2073,7 +2077,7 @@ requires_openai_auth = true let codex_config = codex.settings_config["config"] .as_str() .expect("OpenModel Codex config should be TOML"); - assert!(codex_config.contains("model = \"gpt-5.6-sol\"")); + assert!(codex_config.contains("model = \"gpt-6.1-sol\"")); assert!(codex_config.contains("base_url = \"https://api.openmodel.ai/v1\"")); assert!(codex_config.contains("wire_api = \"responses\"")); assert!(codex_config.contains("requires_openai_auth = true")); @@ -2090,7 +2094,7 @@ requires_openai_auth = true json!({ "env": { "GOOGLE_GEMINI_BASE_URL": "https://api.openmodel.ai", - "GEMINI_MODEL": "gemini-3.6-flash", + "GEMINI_MODEL": "gemini-3.8-flash", }, }) ); @@ -2106,8 +2110,8 @@ requires_openai_auth = true assert_eq!( opencode.settings_config["models"], json!({ - "claude-sonnet-5": { "name": "Claude Sonnet 5" }, - "claude-opus-5": { "name": "Claude Opus 5" }, + "claude-sonnet-5-5": { "name": "Claude Sonnet 5.5" }, + "claude-opus-5-5": { "name": "Claude Opus 5.5" }, }) ); @@ -2122,9 +2126,9 @@ requires_openai_auth = true assert_eq!( hermes.settings_config["models"], json!([ - { "id": "claude-opus-5", "name": "Claude Opus 5" }, - { "id": "claude-sonnet-5", "name": "Claude Sonnet 5" }, - { "id": "claude-haiku-4-5-20251001", "name": "Claude Haiku 4.5" }, + { "id": "claude-opus-5-5", "name": "Claude Opus 5.5" }, + { "id": "claude-sonnet-5-5", "name": "Claude Sonnet 5.5" }, + { "id": "claude-haiku-5-5", "name": "Claude Haiku 5.5" }, ]) ); @@ -2140,16 +2144,22 @@ requires_openai_auth = true openclaw.settings_config["models"], json!([ { - "id": "claude-opus-5", - "name": "Claude Opus 5", + "id": "claude-opus-5-5", + "name": "Claude Opus 5.5", + "reasoning": true, + "input": ["text", "image"], "contextWindow": 1000000, - "cost": { "input": 5, "output": 25 }, + "maxTokens": 128000, + "cost": { "input": 4, "output": 20, "cacheRead": 0.2, "cacheWrite": 5 }, }, { - "id": "claude-sonnet-5", - "name": "Claude Sonnet 5", + "id": "claude-sonnet-5-5", + "name": "Claude Sonnet 5.5", + "reasoning": true, + "input": ["text", "image"], "contextWindow": 1000000, - "cost": { "input": 3, "output": 15 }, + "maxTokens": 128000, + "cost": { "input": 2, "output": 10, "cacheRead": 0.1, "cacheWrite": 2.5 }, }, ]) ); @@ -4327,7 +4337,7 @@ fn prompt_codex_config(current: Option<&Value>, provider_name: &str) -> Result { self.reset_codex_template_state(); self.codex_base_url.set(preset.codex_base_url); + self.codex_model.set(sponsor_codex_model(preset.id)); if preset.id == "patewayai" { self.extra["settingsConfig"] = json!({ "config": crate::codex_config::build_codex_third_party_config_toml( @@ -827,7 +828,9 @@ impl ProviderAddFormState { SponsorModelFamily::Claude | SponsorModelFamily::RunApiClaude => { "@ai-sdk/anthropic" } - SponsorModelFamily::Gpt => "@ai-sdk/openai-compatible", + SponsorModelFamily::Gpt | SponsorModelFamily::GptAstra => { + "@ai-sdk/openai-compatible" + } }); self.opencode_api_key.set(""); self.opencode_base_url.set(preset.opencode_base_url); @@ -857,7 +860,9 @@ impl ProviderAddFormState { SponsorModelFamily::Claude | SponsorModelFamily::RunApiClaude => { "anthropic_messages" } - SponsorModelFamily::Gpt => HERMES_DEFAULT_API_MODE, + SponsorModelFamily::Gpt | SponsorModelFamily::GptAstra => { + HERMES_DEFAULT_API_MODE + } } .to_string(); self.hermes_models = sponsor_hermes_models(family); @@ -878,7 +883,9 @@ impl ProviderAddFormState { SponsorModelFamily::Claude | SponsorModelFamily::RunApiClaude => { "anthropic-messages" } - SponsorModelFamily::Gpt => OPENCLAW_DEFAULT_API_PROTOCOL, + SponsorModelFamily::Gpt | SponsorModelFamily::GptAstra => { + OPENCLAW_DEFAULT_API_PROTOCOL + } }); self.openclaw_user_agent = false; self.openclaw_models = sponsor_openclaw_models(family); diff --git a/src-tauri/src/cli/tui/form/tests.rs b/src-tauri/src/cli/tui/form/tests.rs index baf49310..4aa35f65 100644 --- a/src-tauri/src/cli/tui/form/tests.rs +++ b/src-tauri/src/cli/tui/form/tests.rs @@ -365,82 +365,82 @@ fn provider_add_form_claude_builtin_presets_match_upstream_fields() { ( "DeepSeek", "https://api.deepseek.com/anthropic", - "deepseek-v4-pro", - "deepseek-v4-flash", - "deepseek-v4-pro", - "deepseek-v4-pro", + "deepseek-flash[1M]", + "deepseek-flash[1M]", + "deepseek-flash[1M]", + "deepseek-flash[1M]", ClaudeApiKeyField::AuthToken, ), ( "Zhipu GLM", "https://open.bigmodel.cn/api/anthropic", - "glm-5.1", - "glm-5.1", - "glm-5.1", - "glm-5.1", + "glm-5.3[1M]", + "glm-5.3[1M]", + "glm-5.3[1M]", + "glm-5.3[1M]", ClaudeApiKeyField::AuthToken, ), ( "Zhipu GLM en", "https://api.z.ai/api/anthropic", - "glm-5.1", - "glm-5.1", - "glm-5.1", - "glm-5.1", + "glm-5.3[1M]", + "glm-5.3[1M]", + "glm-5.3[1M]", + "glm-5.3[1M]", ClaudeApiKeyField::AuthToken, ), ( "ModelScope", "https://api-inference.modelscope.cn", - "ZhipuAI/GLM-5.2", - "ZhipuAI/GLM-5.2", - "ZhipuAI/GLM-5.2", - "ZhipuAI/GLM-5.2", + "ZhipuAI/GLM-5.2[1M]", + "ZhipuAI/GLM-5.2[1M]", + "ZhipuAI/GLM-5.2[1M]", + "ZhipuAI/GLM-5.2[1M]", ClaudeApiKeyField::AuthToken, ), ( "MiniMax", "https://api.minimaxi.com/anthropic", - "MiniMax-M2.7", - "MiniMax-M2.7", - "MiniMax-M2.7", - "MiniMax-M2.7", + "MiniMax-M3.1-Flash[1M]", + "MiniMax-M3.1-Flash[1M]", + "MiniMax-M3.1-Flash[1M]", + "MiniMax-M3[1M]", ClaudeApiKeyField::AuthToken, ), ( "Xiaomi MiMo", "https://api.xiaomimimo.com/anthropic", - "mimo-v2.5-pro", - "mimo-v2.5-pro", - "mimo-v2.5-pro", - "mimo-v2.5-pro", + "mimo-v2.6-pro[1M]", + "mimo-v2.6-pro[1M]", + "mimo-v2.6-pro[1M]", + "mimo-v2.6-pro[1M]", ClaudeApiKeyField::AuthToken, ), ( "Xiaomi MiMo Token Plan (China)", "https://token-plan-cn.xiaomimimo.com/anthropic", - "mimo-v2.5-pro", - "mimo-v2.5-pro", - "mimo-v2.5-pro", - "mimo-v2.5-pro", + "mimo-v2.6-pro[1M]", + "mimo-v2.6-pro[1M]", + "mimo-v2.6-pro[1M]", + "mimo-v2.6-pro[1M]", ClaudeApiKeyField::AuthToken, ), ( "OpenCode Go", "https://opencode.ai/zen/go", - "deepseek-v4-flash", - "deepseek-v4-flash", - "deepseek-v4-flash", - "deepseek-v4-flash", + "deepseek-v4.1-flash[1M]", + "deepseek-v4.1-flash[1M]", + "deepseek-v4.1-flash[1M]", + "deepseek-v4.1-flash[1M]", ClaudeApiKeyField::ApiKey, ), ( "OpenRouter", "https://openrouter.ai/api", - "anthropic/claude-sonnet-5", - "anthropic/claude-haiku-4.5", - "anthropic/claude-sonnet-5", - "anthropic/claude-opus-5", + "anthropic/claude-sonnet-5.5", + "anthropic/claude-haiku-5.5", + "anthropic/claude-sonnet-5.5", + "anthropic/claude-opus-5.5", ClaudeApiKeyField::AuthToken, ), ]; @@ -485,15 +485,15 @@ fn provider_add_form_codex_builtin_presets_match_upstream_fields() { "DeepSeek", "deepseek", "https://api.deepseek.com", - "deepseek-v4-flash", + "deepseek-flash", "openai_responses", - 2, + 1, ), ( "Zhipu GLM", "zhipu_glm", "https://open.bigmodel.cn/api/coding/paas/v4", - "glm-5.2", + "glm-5.3", "openai_chat", 1, ), @@ -501,7 +501,7 @@ fn provider_add_form_codex_builtin_presets_match_upstream_fields() { "Zhipu GLM en", "zhipu_glm_en", "https://api.z.ai/api/coding/paas/v4", - "glm-5.2", + "glm-5.3", "openai_chat", 1, ), @@ -517,23 +517,23 @@ fn provider_add_form_codex_builtin_presets_match_upstream_fields() { "MiniMax", "minimax", "https://api.minimaxi.com/v1", - "MiniMax-M3", + "MiniMax-M3.1-Flash", "openai_responses", - 1, + 2, ), ( "Xiaomi MiMo", "xiaomi_mimo", "https://api.xiaomimimo.com/v1", - "mimo-v2.5-pro", + "mimo-v2.6-pro", "openai_responses", - 2, + 3, ), ( "Xiaomi MiMo Token Plan (China)", "xiaomi_mimo_token_plan", "https://token-plan-cn.xiaomimimo.com/v1", - "mimo-v2.5-pro", + "mimo-v2.6-pro", "openai_responses", 2, ), @@ -541,15 +541,15 @@ fn provider_add_form_codex_builtin_presets_match_upstream_fields() { "OpenCode Go", "opencode_go", "https://opencode.ai/zen/go/v1", - "glm-5.2", + "glm-5.3", "openai_chat", - 6, + 5, ), ( "OpenRouter", "openrouter", "https://openrouter.ai/api/v1", - "gpt-5.6-sol", + "openai/gpt-6.1-sol", "openai_responses", 0, ), @@ -607,7 +607,7 @@ fn provider_add_form_codex_builtin_presets_match_upstream_fields() { "zen" ); assert_eq!( - opencode["settingsConfig"]["modelCatalog"]["models"][4]["reasoningLevels"], + opencode["settingsConfig"]["modelCatalog"]["models"][3]["reasoningLevels"], json!(["low", "high", "max"]) ); @@ -619,8 +619,48 @@ fn provider_add_form_codex_builtin_presets_match_upstream_fields() { assert_eq!(minimax_model["inputModalities"], json!(["text", "image"])); assert_eq!( minimax_model["baseInstructions"], - "You are Codex, a coding agent based on MiniMax-M3. You and the user share the same workspace and collaborate to achieve the user's goals." + "You are Codex, a coding agent based on MiniMax-M3.1-Flash. You and the user share the same workspace and collaborate to achieve the user's goals." ); + let m3 = &minimax["settingsConfig"]["modelCatalog"]["models"][1]; + assert_eq!(m3["model"], "MiniMax-M3"); + assert_eq!(m3["reasoningLevels"], json!(["none", "high"])); + assert_eq!(m3["contextWindow"], 1_000_000); + assert_eq!(m3["inputModalities"], json!(["text", "image"])); + assert_eq!(m3["supportsParallelToolCalls"], true); +} + +#[test] +fn qiniu_and_fenno_templates_keep_distinct_models_in_cli_and_tui() { + for (label, template, model) in [ + ("Qiniu", ProviderAddTemplate::Qiniu, "gpt-6-astra"), + ("FennoAI", ProviderAddTemplate::Fenno, "gpt-6.1-sol"), + ] { + for app in [ + AppType::Codex, + AppType::OpenCode, + AppType::Hermes, + AppType::OpenClaw, + ] { + let cli = build_provider_template_seed(&app, template, &[]).expect("CLI template"); + let mut form = ProviderAddFormState::new(app.clone()); + form.apply_template(template_index_by_label(app.clone(), label), &[]); + let tui = form.to_provider_json_value(); + for settings in [&cli.settings_config, &tui["settingsConfig"]] { + match app { + AppType::Codex => { + let config: toml::Value = + settings["config"].as_str().unwrap().parse().unwrap(); + assert_eq!(config["model"].as_str(), Some(model), "{label}"); + } + AppType::OpenCode => { + assert!(settings["models"].get(model).is_some(), "{label}"); + assert_eq!(settings["models"].as_object().unwrap().len(), 1); + } + _ => assert_eq!(settings["models"][0]["id"], model, "{label}"), + } + } + } + } } #[test] @@ -729,7 +769,7 @@ fn provider_add_form_codex_deepseek_template_matches_upstream_preset_values() { assert_eq!(form.name.value, "DeepSeek"); assert_eq!(form.website_url.value, "https://platform.deepseek.com"); assert_eq!(form.codex_base_url.value, "https://api.deepseek.com"); - assert_eq!(form.codex_model.value, "deepseek-v4-flash"); + assert_eq!(form.codex_model.value, "deepseek-flash"); assert_eq!(form.codex_wire_api, CodexWireApi::Responses); assert!(form.codex_requires_openai_auth); @@ -758,7 +798,7 @@ fn provider_add_form_codex_deepseek_template_matches_upstream_preset_values() { .as_str() .expect("settingsConfig.config should be TOML string"); assert!(cfg.contains("model_provider = \"custom\"")); - assert!(cfg.contains("model = \"deepseek-v4-flash\"")); + assert!(cfg.contains("model = \"deepseek-flash\"")); assert!(cfg.contains("disable_response_storage = true")); assert!(cfg.contains("[model_providers.custom]")); assert!(cfg.contains("name = \"deepseek\"")); @@ -774,15 +814,10 @@ fn provider_add_form_codex_deepseek_template_matches_upstream_preset_values() { json!({ "models": [ { - "model": "deepseek-v4-flash", - "displayName": "DeepSeek V4 Flash", - "contextWindow": 1048576, - "reasoningLevels": ["low", "high", "max"], - }, - { - "model": "deepseek-v4-pro", - "displayName": "DeepSeek V4 Pro", + "model": "deepseek-flash", + "displayName": "DeepSeek V4.1 Flash", "contextWindow": 1048576, + "inputModalities": ["text", "image"], "reasoningLevels": ["low", "high", "max"], }, ], @@ -809,10 +844,10 @@ fn provider_add_form_codex_oauth_template_matches_upstream_contract() { form.claude_api_format, crate::cli::tui::form::ClaudeApiFormat::OpenAiResponses ); - assert_eq!(form.claude_model.value, "gpt-5.6-sol"); - assert_eq!(form.claude_haiku_model.value, "gpt-5.6-luna"); - assert_eq!(form.claude_sonnet_model.value, "gpt-5.6-sol"); - assert_eq!(form.claude_opus_model.value, "gpt-5.6-sol"); + assert_eq!(form.claude_model.value, "gpt-6.1-sol"); + assert_eq!(form.claude_haiku_model.value, "gpt-6-luna"); + assert_eq!(form.claude_sonnet_model.value, "gpt-6.1-sol"); + assert_eq!(form.claude_opus_model.value, "gpt-6.1-sol"); assert!(!form.codex_fast_mode); assert!(form.claude_hide_attribution); @@ -845,11 +880,11 @@ fn provider_add_form_codex_oauth_template_matches_upstream_contract() { ); assert_eq!( provider["settingsConfig"]["env"]["CLAUDE_CODE_MAX_CONTEXT_TOKENS"], - "372000" + "272000" ); assert_eq!( provider["settingsConfig"]["env"]["CLAUDE_CODE_AUTO_COMPACT_WINDOW"], - "372000" + "272000" ); assert!( provider["settingsConfig"]["env"] @@ -1087,7 +1122,7 @@ fn provider_add_form_dds_template_codex_sets_base_url_and_partner_meta() { .as_str() .expect("settingsConfig.config should be string"); assert!(cfg.contains("base_url = \"https://www.ddshub.cc\"")); - assert!(cfg.contains("model = \"gpt-5.6-sol\"")); + assert!(cfg.contains("model = \"gpt-6.1-sol\"")); assert!(cfg.contains("wire_api = \"responses\"")); assert!(cfg.contains("requires_openai_auth = true")); let meta = provider["meta"] @@ -1183,7 +1218,7 @@ fn provider_add_form_cubence_template_gemini_sets_base_url_and_partner_meta() { ); assert_eq!( provider["settingsConfig"]["env"]["GEMINI_MODEL"], - "gemini-3.6-flash" + "gemini-3.8-flash" ); assert_eq!(provider["meta"]["isPartner"], true); assert_eq!(provider["meta"]["partnerPromotionKey"], "cubence"); @@ -1204,12 +1239,12 @@ fn provider_add_form_cubence_template_opencode_sets_base_url_and_partner_meta() "https://api.cubence.com/v1" ); assert_eq!( - provider["settingsConfig"]["models"]["claude-sonnet-5"]["name"], - "Claude Sonnet 5" + provider["settingsConfig"]["models"]["claude-sonnet-5-5"]["name"], + "Claude Sonnet 5.5" ); assert_eq!( - provider["settingsConfig"]["models"]["claude-opus-5"]["name"], - "Claude Opus 5" + provider["settingsConfig"]["models"]["claude-opus-5-5"]["name"], + "Claude Opus 5.5" ); assert_eq!(provider["meta"]["isPartner"], true); assert_eq!(provider["meta"]["partnerPromotionKey"], "cubence"); @@ -1233,11 +1268,11 @@ fn provider_add_form_cubence_template_hermes_sets_base_url_and_partner_meta() { assert_eq!( settings.get("models"), Some(&json!([ - { "id": "claude-opus-5", "name": "Claude Opus 5" }, - { "id": "claude-sonnet-5", "name": "Claude Sonnet 5" }, + { "id": "claude-opus-5-5", "name": "Claude Opus 5.5" }, + { "id": "claude-sonnet-5-5", "name": "Claude Sonnet 5.5" }, { - "id": "claude-haiku-4-5-20251001", - "name": "Claude Haiku 4.5" + "id": "claude-haiku-5-5", + "name": "Claude Haiku 5.5" }, ])) ); @@ -1263,16 +1298,22 @@ fn provider_add_form_cubence_template_openclaw_sets_base_url_and_partner_meta() provider["settingsConfig"]["models"], json!([ { - "id": "claude-opus-5", - "name": "Claude Opus 5", + "id": "claude-opus-5-5", + "name": "Claude Opus 5.5", + "reasoning": true, + "input": ["text", "image"], "contextWindow": 1000000, - "cost": { "input": 5, "output": 25 }, + "maxTokens": 128000, + "cost": { "input": 4, "output": 20, "cacheRead": 0.2, "cacheWrite": 5 }, }, { - "id": "claude-sonnet-5", - "name": "Claude Sonnet 5", + "id": "claude-sonnet-5-5", + "name": "Claude Sonnet 5.5", + "reasoning": true, + "input": ["text", "image"], "contextWindow": 1000000, - "cost": { "input": 3, "output": 15 }, + "maxTokens": 128000, + "cost": { "input": 2, "output": 10, "cacheRead": 0.1, "cacheWrite": 2.5 }, }, ]) ); @@ -1348,7 +1389,7 @@ fn provider_add_form_runapi_template_codex_sets_v1_base_url() { assert!(cfg.contains("[model_providers.custom]")); assert!(cfg.contains("name = \"RunAPI\"")); assert!(cfg.contains("base_url = \"https://runapi.co/v1\"")); - assert!(cfg.contains("model = \"gpt-5.6-sol\"")); + assert!(cfg.contains("model = \"gpt-6.1-sol\"")); assert!(cfg.contains("wire_api = \"responses\"")); assert_eq!(provider["meta"]["partnerPromotionKey"], "runapi"); } @@ -1373,13 +1414,16 @@ fn provider_add_form_runapi_template_opencode_matches_upstream_anthropic_shape() "blank OpenCode API keys should be omitted on save" ); assert_eq!( - settings["models"]["claude-sonnet-5"]["name"], - "Claude Sonnet 5" + settings["models"]["claude-sonnet-5-5"]["name"], + "Claude Sonnet 5.5" ); - assert_eq!(settings["models"]["claude-opus-5"]["name"], "Claude Opus 5"); assert_eq!( - settings["models"]["claude-haiku-4-5"]["name"], - "Claude Haiku 4.5" + settings["models"]["claude-opus-5-5"]["name"], + "Claude Opus 5.5" + ); + assert_eq!( + settings["models"]["claude-haiku-5-5"]["name"], + "Claude Haiku 5.5" ); assert_eq!(provider["meta"]["partnerPromotionKey"], "runapi"); } @@ -1405,9 +1449,9 @@ fn provider_add_form_runapi_template_hermes_matches_upstream_anthropic_shape() { assert_eq!( settings["models"], json!([ - { "id": "claude-sonnet-5", "name": "Claude Sonnet 5" }, - { "id": "claude-opus-5", "name": "Claude Opus 5" }, - { "id": "claude-haiku-4-5", "name": "Claude Haiku 4.5" }, + { "id": "claude-sonnet-5-5", "name": "Claude Sonnet 5.5" }, + { "id": "claude-opus-5-5", "name": "Claude Opus 5.5" }, + { "id": "claude-haiku-5-5", "name": "Claude Haiku 5.5" }, ]) ); assert_eq!(provider["meta"]["partnerPromotionKey"], "runapi"); @@ -1434,19 +1478,31 @@ fn provider_add_form_runapi_template_openclaw_matches_upstream_anthropic_shape() settings["models"], json!([ { - "id": "claude-sonnet-5", - "name": "Claude Sonnet 5", + "id": "claude-sonnet-5-5", + "name": "Claude Sonnet 5.5", + "reasoning": true, + "input": ["text", "image"], "contextWindow": 1000000, + "maxTokens": 128000, + "cost": { "input": 2, "output": 10, "cacheRead": 0.1, "cacheWrite": 2.5 }, }, { - "id": "claude-opus-5", - "name": "Claude Opus 5", + "id": "claude-opus-5-5", + "name": "Claude Opus 5.5", + "reasoning": true, + "input": ["text", "image"], "contextWindow": 1000000, + "maxTokens": 128000, + "cost": { "input": 4, "output": 20, "cacheRead": 0.2, "cacheWrite": 5 }, }, { - "id": "claude-haiku-4-5", - "name": "Claude Haiku 4.5", - "contextWindow": 200000, + "id": "claude-haiku-5-5", + "name": "Claude Haiku 5.5", + "reasoning": true, + "input": ["text", "image"], + "contextWindow": 1000000, + "maxTokens": 128000, + "cost": { "input": 0.1, "output": 0.5, "cacheRead": 0.01, "cacheWrite": 0.125 }, }, ]) ); @@ -2809,7 +2865,7 @@ fn provider_add_form_aicodemirror_template_codex_preserves_third_party_auth_beha .as_str() .expect("settingsConfig.config should be string"); assert!(cfg.contains("base_url = \"https://api.aicodemirror.ai/api/codex/backend-api/codex\"")); - assert!(cfg.contains("model = \"gpt-5.6-sol\"")); + assert!(cfg.contains("model = \"gpt-6.1-sol\"")); assert!(cfg.contains("wire_api = \"responses\"")); assert!(cfg.contains("requires_openai_auth = true")); assert!(form.codex_api_key.value.is_empty()); @@ -2834,7 +2890,7 @@ fn provider_add_form_codex_custom_defaults_to_upstream_model() { let form = ProviderAddFormState::new(AppType::Codex); assert_eq!(form.codex_base_url.value, ""); - assert_eq!(form.codex_model.value, "gpt-5.6-sol"); + assert_eq!(form.codex_model.value, "gpt-6.1-sol"); } #[test] @@ -5830,14 +5886,14 @@ fn provider_add_form_aicodemirror_template_opencode_matches_serializer_and_loade .keys() .map(String::as_str) .collect::>(); - assert_eq!(model_ids, ["claude-sonnet-5", "claude-opus-5"]); + assert_eq!(model_ids, ["claude-sonnet-5-5", "claude-opus-5-5"]); assert_eq!( - provider["settingsConfig"]["models"]["claude-sonnet-5"]["name"], - "Claude Sonnet 5" + provider["settingsConfig"]["models"]["claude-sonnet-5-5"]["name"], + "Claude Sonnet 5.5" ); assert_eq!( - provider["settingsConfig"]["models"]["claude-opus-5"]["name"], - "Claude Opus 5" + provider["settingsConfig"]["models"]["claude-opus-5-5"]["name"], + "Claude Opus 5.5" ); let mut parsed = Provider::with_id( @@ -5862,8 +5918,8 @@ fn provider_add_form_aicodemirror_template_opencode_matches_serializer_and_loade roundtrip_form.opencode_base_url.value, "https://api.aicodemirror.ai/api/claudecode" ); - assert_eq!(roundtrip_form.opencode_model_id.value, "claude-opus-5"); - assert_eq!(roundtrip_form.opencode_model_name.value, "Claude Opus 5"); + assert_eq!(roundtrip_form.opencode_model_id.value, "claude-opus-5-5"); + assert_eq!(roundtrip_form.opencode_model_name.value, "Claude Opus 5.5"); let roundtrip = roundtrip_form.to_provider_json_value(); assert!( @@ -5873,12 +5929,12 @@ fn provider_add_form_aicodemirror_template_opencode_matches_serializer_and_loade "OpenCode roundtrip should still omit blank API keys" ); assert_eq!( - roundtrip["settingsConfig"]["models"]["claude-sonnet-5"]["name"], - "Claude Sonnet 5" + roundtrip["settingsConfig"]["models"]["claude-sonnet-5-5"]["name"], + "Claude Sonnet 5.5" ); assert_eq!( - roundtrip["settingsConfig"]["models"]["claude-opus-5"]["name"], - "Claude Opus 5" + roundtrip["settingsConfig"]["models"]["claude-opus-5-5"]["name"], + "Claude Opus 5.5" ); } @@ -6185,21 +6241,31 @@ fn provider_add_form_aicodemirror_template_openclaw_matches_serializer_and_loade provider["settingsConfig"]["models"], json!([ { - "id": "claude-opus-5", - "name": "Claude Opus 5", + "id": "claude-opus-5-5", + "name": "Claude Opus 5.5", + "reasoning": true, + "input": ["text", "image"], "contextWindow": 1000000, + "maxTokens": 128000, "cost": { - "input": 5, - "output": 25 + "input": 4, + "output": 20, + "cacheRead": 0.2, + "cacheWrite": 5 } }, { - "id": "claude-sonnet-5", - "name": "Claude Sonnet 5", + "id": "claude-sonnet-5-5", + "name": "Claude Sonnet 5.5", + "reasoning": true, + "input": ["text", "image"], "contextWindow": 1000000, + "maxTokens": 128000, "cost": { - "input": 3, - "output": 15 + "input": 2, + "output": 10, + "cacheRead": 0.1, + "cacheWrite": 2.5 } } ]) @@ -6227,8 +6293,8 @@ fn provider_add_form_aicodemirror_template_openclaw_matches_serializer_and_loade roundtrip_form.opencode_base_url.value, "https://api.aicodemirror.ai/api/claudecode" ); - assert_eq!(roundtrip_form.opencode_model_id.value, "claude-opus-5"); - assert_eq!(roundtrip_form.opencode_model_name.value, "Claude Opus 5"); + assert_eq!(roundtrip_form.opencode_model_id.value, "claude-opus-5-5"); + assert_eq!(roundtrip_form.opencode_model_name.value, "Claude Opus 5.5"); assert_eq!(roundtrip_form.opencode_model_context_limit.value, "1000000"); let roundtrip = roundtrip_form.to_provider_json_value(); diff --git a/src-tauri/src/database/schema.rs b/src-tauri/src/database/schema.rs index 28ec8aa5..56cce7b3 100644 --- a/src-tauri/src/database/schema.rs +++ b/src-tauri/src/database/schema.rs @@ -1734,6 +1734,14 @@ impl Database { /// 注意: model_id 使用短横线格式(如 claude-haiku-4-5),与 API 返回的模型名称标准化后一致 fn seed_model_pricing(conn: &Connection) -> Result<(), AppError> { let pricing_data = [ + ( + "claude-fable-5-1", + "Claude Fable 5.1", + "10", + "50", + "0.25", + "12.50", + ), // Claude Fable 5(Opus 之上的新档) ( "claude-fable-5", @@ -1751,8 +1759,19 @@ impl Database { "1.00", "12.50", ), + // Claude Opus 5.5(2026-09-23 发布;缓存读为 0.05x = $0.20,非常规 0.1x) + ("claude-opus-5-5", "Claude Opus 5.5", "4", "20", "0.20", "5"), // Claude Opus 5(与 Opus 4.8 同价位;fast mode $10/$50 不入表) ("claude-opus-5", "Claude Opus 5", "5", "25", "0.50", "6.25"), + // Claude Sonnet 5.5(缓存读 0.05x = $0.10,非 Sonnet 5 的 $0.20) + ( + "claude-sonnet-5-5", + "Claude Sonnet 5.5", + "2", + "10", + "0.10", + "2.50", + ), // Claude 4.8 系列 ( "claude-opus-4-8", @@ -1838,6 +1857,16 @@ impl Database { "0.10", "1.25", ), + // Claude Haiku 5.5(2026-10-07 发布;按提示词长度分档,表内只存 + // 10 万 token 以内的标准档) + ( + "claude-haiku-5-5", + "Claude Haiku 5.5", + "0.10", + "0.50", + "0.01", + "0.125", + ), // Claude 4 系列 (Legacy Models) ( "claude-opus-4-20250514", @@ -1883,9 +1912,20 @@ impl Database { // GPT-6 Astra 标准价(USD / 1M tokens),与上游一致;不含长上下文和服务档位倍率。 // https://developers.openai.com/api/docs/models/gpt-6-astra ("gpt-6-astra", "GPT-6 Astra", "10", "50", "1", "12.5"), + // GPT-6.1 Sol(2026-09 发布):Standard 短上下文价,cached input 0.05×。 + // https://developers.openai.com/api/docs/models/gpt-6.1-sol + ("gpt-6.1-sol", "GPT-6.1 Sol", "2", "10", "0.10", "2.50"), + // GPT-6.1 Terra(2026-10-26 发布):Standard 短上下文价,cache write 取 + // 30 分钟档(12 小时档为 2 倍)。 + // https://developers.openai.com/api/docs/models/gpt-6.1-terra + ("gpt-6.1-terra", "GPT-6.1 Terra", "1", "5", "0.05", "1.25"), + ("gpt-6-sol", "GPT-6 Sol", "2", "10", "0.20", "2.50"), + ("gpt-6-luna", "GPT-6 Luna", "0.10", "0.50", "0.01", "0.125"), // GPT-5.6 系列(Sol / Terra / Luna,2026-06 发布) // 5.6 家族起 cache write 收 1.25× 输入价(此前 GPT 模型写缓存免费,勿回填旧系列) - ("gpt-5.6-sol", "GPT-5.6 Sol", "5", "30", "0.50", "6.25"), + // 2026-09-06 审计:Sol 改促销价 4/20/0.40/5(OpenAI 价页原文"至少持续到 + // 2026-11-21"),挂牌价 5/30/0.50/6.25。 + ("gpt-5.6-sol", "GPT-5.6 Sol", "4", "20", "0.40", "5"), // 2026-07-30 OpenAI 降价:luna -80%、terra -20%,sol 不变。 ("gpt-5.6-terra", "GPT-5.6 Terra", "2", "12", "0.20", "2.50"), ( @@ -1896,13 +1936,14 @@ impl Database { "0.02", "0.25", ), - // 裸名 gpt-5.6 是 Sol 的官方别名;effort 后缀与现有 GPT 系列保持一致。 - ("gpt-5.6", "GPT-5.6 Sol", "5", "30", "0.50", "6.25"), - ("gpt-5.6-low", "GPT-5.6 Sol", "5", "30", "0.50", "6.25"), - ("gpt-5.6-medium", "GPT-5.6 Sol", "5", "30", "0.50", "6.25"), - ("gpt-5.6-high", "GPT-5.6 Sol", "5", "30", "0.50", "6.25"), - ("gpt-5.6-xhigh", "GPT-5.6 Sol", "5", "30", "0.50", "6.25"), - ("gpt-5.6-minimal", "GPT-5.6 Sol", "5", "30", "0.50", "6.25"), + // 裸名 gpt-5.6 是 Sol 的官方别名;effort 后缀与现有 GPT 系列保持一致, + // 必须与 sol 同步改价,否则旧价会压过基础行。 + ("gpt-5.6", "GPT-5.6 Sol", "4", "20", "0.40", "5"), + ("gpt-5.6-low", "GPT-5.6 Sol", "4", "20", "0.40", "5"), + ("gpt-5.6-medium", "GPT-5.6 Sol", "4", "20", "0.40", "5"), + ("gpt-5.6-high", "GPT-5.6 Sol", "4", "20", "0.40", "5"), + ("gpt-5.6-xhigh", "GPT-5.6 Sol", "4", "20", "0.40", "5"), + ("gpt-5.6-minimal", "GPT-5.6 Sol", "4", "20", "0.40", "5"), // GPT-5.5 系列 ("gpt-5.5", "GPT-5.5", "5", "30", "0.50", "0"), ("gpt-5.5-low", "GPT-5.5", "5", "30", "0.50", "0"), @@ -2089,6 +2130,16 @@ impl Database { ("gpt-4.1", "GPT-4.1", "2", "8", "0.50", "0"), ("gpt-4.1-mini", "GPT-4.1 Mini", "0.40", "1.60", "0.10", "0"), ("gpt-4.1-nano", "GPT-4.1 Nano", "0.10", "0.40", "0.025", "0"), + // Gemini 3.8 Flash introduction pricing, valid through 2026-12-31; + // list price from 2027-01-01 is 1.50/7.50/0.15. + ( + "gemini-3.8-flash", + "Gemini 3.8 Flash", + "0.75", + "3.75", + "0.075", + "0", + ), // Gemini 3.7 Flash introduction pricing, valid through 2026-12-31. ( "gemini-3.7-flash", @@ -2295,6 +2346,22 @@ impl Database { "0.0056", "0", ), + ( + "deepseek-flash", + "DeepSeek V4.1 Flash", + "0.3", + "1.2", + "0.006", + "0", + ), + ( + "deepseek-v4.1-flash", + "DeepSeek V4.1 Flash", + "0.3", + "1.2", + "0.006", + "0", + ), // DeepSeek 系列 ( "deepseek-v3.2", @@ -2392,6 +2459,14 @@ impl Database { "0", ), ("kimi-k3", "Kimi K3", "3.00", "15.00", "0.30", "0"), + ( + "kimi-k3.1-pro", + "Kimi K3.1 Pro", + "2.00", + "10.00", + "0.20", + "2.00", + ), // Kimi For Coding 套餐里 K3 的裸名(无 kimi- 前缀),同标准 list 价 ("k3", "Kimi K3", "3.00", "15.00", "0.30", "0"), // 腾讯混元 (Tencent Hunyuan)(官方 CNY 1/4/0.25 按 1 USD ≈ 7.14 折算;Hy3 阶梯计价取最低档) @@ -2435,6 +2510,14 @@ impl Database { ), // MiniMax 官方 PAYG 标准档(≤512K);长上下文阶梯价格暂不由静态目录表达。 ("minimax-m3", "MiniMax M3", "0.30", "1.20", "0.06", "0"), + ( + "minimax-m3.1-flash", + "MiniMax M3.1 Flash", + "0.15", + "0.60", + "0.015", + "0", + ), // GLM (智谱) ("glm-4.7", "GLM-4.7", "0.6", "2.2", "0.11", "0"), ("glm-4.6", "GLM-4.6", "0.6", "2.2", "0.11", "0"), @@ -2443,6 +2526,15 @@ impl Database { ("glm-5.2", "GLM-5.2", "1.4", "4.4", "0.26", "0"), ("glm-5-turbo", "GLM-5-Turbo", "1.2", "4", "0.24", "0"), ("glm-5v-turbo", "GLM-5V-Turbo", "1.2", "4", "0.24", "0"), + ("glm-5.3", "GLM-5.3", "1.4", "4.4", "0.26", "0"), + ( + "glm-5.3-flash", + "GLM-5.3-Flash", + "0.15", + "0.50", + "0.03", + "0", + ), // MiMo (小米) ( "mimo-v2-flash", @@ -2462,6 +2554,30 @@ impl Database { "0.0036", "0", ), + ( + "mimo-v2.6-pro", + "MiMo V2.6 Pro", + "0.435", + "0.87", + "0.0036", + "0", + ), + ( + "mimo-v2.6-flash", + "MiMo V2.6 Flash", + "0.14", + "0.28", + "0.0028", + "0", + ), + ( + "mimo-v2.6-pro-ultraspeed", + "MiMo V2.6 Pro UltraSpeed", + "4.35", + "8.7", + "0.036", + "0", + ), // Qwen 系列 (阿里巴巴) ("qwen3.8-max", "Qwen3.8 Max", "2", "6", "0.25", "2.50"), ("qwen3.7-max", "Qwen3.7 Max", "2.50", "7.50", "0.25", "0"), @@ -2780,6 +2896,92 @@ impl Database { "0.50", "0", ), + // GPT-5.6 Sol 促销价 4/20/0.40/5(至少到 2026-11-21);裸名与 effort + // 后缀行同步,否则旧价会压过基础行。 + ( + "gpt-5.6-sol", + "GPT-5.6 Sol", + "4", + "20", + "0.40", + "5", + "5", + "30", + "0.50", + "6.25", + ), + ( + "gpt-5.6", + "GPT-5.6 Sol", + "4", + "20", + "0.40", + "5", + "5", + "30", + "0.50", + "6.25", + ), + ( + "gpt-5.6-low", + "GPT-5.6 Sol", + "4", + "20", + "0.40", + "5", + "5", + "30", + "0.50", + "6.25", + ), + ( + "gpt-5.6-medium", + "GPT-5.6 Sol", + "4", + "20", + "0.40", + "5", + "5", + "30", + "0.50", + "6.25", + ), + ( + "gpt-5.6-high", + "GPT-5.6 Sol", + "4", + "20", + "0.40", + "5", + "5", + "30", + "0.50", + "6.25", + ), + ( + "gpt-5.6-xhigh", + "GPT-5.6 Sol", + "4", + "20", + "0.40", + "5", + "5", + "30", + "0.50", + "6.25", + ), + ( + "gpt-5.6-minimal", + "GPT-5.6 Sol", + "4", + "20", + "0.40", + "5", + "5", + "30", + "0.50", + "6.25", + ), ( "gpt-5.6-terra", "GPT-5.6 Terra", diff --git a/src-tauri/src/database/tests.rs b/src-tauri/src/database/tests.rs index bb3e11a3..c9c557f8 100644 --- a/src-tauri/src/database/tests.rs +++ b/src-tauri/src/database/tests.rs @@ -3482,11 +3482,11 @@ fn model_pricing_seeds_gpt_5_6_family_and_aliases() { let conn = db.conn.lock().expect("lock conn"); let expected = [ - ("gpt-5.6-sol", "5", "30", "0.50", "6.25"), + ("gpt-5.6-sol", "4", "20", "0.40", "5"), ("gpt-5.6-terra", "2", "12", "0.20", "2.50"), ("gpt-5.6-luna", "0.20", "1.20", "0.02", "0.25"), - ("gpt-5.6", "5", "30", "0.50", "6.25"), - ("gpt-5.6-high", "5", "30", "0.50", "6.25"), + ("gpt-5.6", "4", "20", "0.40", "5"), + ("gpt-5.6-high", "4", "20", "0.40", "5"), ]; for (model_id, input, output, cache_read, cache_write) in expected { @@ -3519,6 +3519,24 @@ fn model_pricing_seeds_synced_upstream_catalog() { let expected = [ ("gpt-6-astra", "10", "50", "1", "12.5"), + ("gpt-6.1-sol", "2", "10", "0.10", "2.50"), + ("gpt-6.1-terra", "1", "5", "0.05", "1.25"), + ("gpt-6-sol", "2", "10", "0.20", "2.50"), + ("gpt-6-luna", "0.10", "0.50", "0.01", "0.125"), + ("claude-opus-5-5", "4", "20", "0.20", "5"), + ("claude-sonnet-5-5", "2", "10", "0.10", "2.50"), + ("claude-haiku-5-5", "0.10", "0.50", "0.01", "0.125"), + ("gemini-3.8-flash", "0.75", "3.75", "0.075", "0"), + ("claude-fable-5-1", "10", "50", "0.25", "12.50"), + ("deepseek-flash", "0.3", "1.2", "0.006", "0"), + ("deepseek-v4.1-flash", "0.3", "1.2", "0.006", "0"), + ("kimi-k3.1-pro", "2.00", "10.00", "0.20", "2.00"), + ("minimax-m3.1-flash", "0.15", "0.60", "0.015", "0"), + ("glm-5.3", "1.4", "4.4", "0.26", "0"), + ("glm-5.3-flash", "0.15", "0.50", "0.03", "0"), + ("mimo-v2.6-pro", "0.435", "0.87", "0.0036", "0"), + ("mimo-v2.6-flash", "0.14", "0.28", "0.0028", "0"), + ("mimo-v2.6-pro-ultraspeed", "4.35", "8.7", "0.036", "0"), ("claude-fable-5", "10", "50", "1.00", "12.50"), ("claude-opus-4-6", "5", "25", "0.50", "6.25"), ("claude-sonnet-4-6", "3", "15", "0.30", "3.75"), @@ -3570,6 +3588,59 @@ fn model_pricing_seeds_synced_upstream_catalog() { } } +#[test] +fn model_pricing_refreshed_presets_resolve_and_preserve_custom_prices() { + use crate::proxy::usage::calculator::lookup_model_pricing; + + let db = Database::memory().expect("create memory db"); + for model in [ + "claude-fable-5-1", + "deepseek-flash", + "deepseek-v4.1-flash", + "kimi-k3.1-pro", + "MiniMax-M3.1-Flash", + "glm-5.3", + "glm-5.3-flash", + "mimo-v2.6-pro", + "mimo-v2.6-flash", + "mimo-v2.6-pro-ultraspeed", + ] { + let decorated = format!("vendor/{model}[1M]"); + let pricing = lookup_model_pricing(&db, &decorated).expect(model); + assert!(pricing.input_cost_per_million > rust_decimal::Decimal::ZERO); + assert!(pricing.output_cost_per_million > rust_decimal::Decimal::ZERO); + + let custom = ModelPricingUpdate::new( + &model.to_ascii_lowercase(), + "Custom", + "123", + "456", + "7", + "8", + ) + .unwrap(); + db.upsert_model_pricing(&custom).unwrap(); + db.ensure_model_pricing_seeded().unwrap(); + let pricing = lookup_model_pricing(&db, &decorated).unwrap(); + assert_eq!( + pricing.input_cost_per_million, + rust_decimal::Decimal::from(123) + ); + assert_eq!( + pricing.output_cost_per_million, + rust_decimal::Decimal::from(456) + ); + assert_eq!( + pricing.cache_read_cost_per_million, + rust_decimal::Decimal::from(7) + ); + assert_eq!( + pricing.cache_creation_cost_per_million, + rust_decimal::Decimal::from(8) + ); + } +} + #[test] fn model_pricing_repairs_synced_values_without_overwriting_custom_prices() { let db = Database::memory().expect("create memory db"); @@ -3709,7 +3780,11 @@ fn model_pricing_repairs_only_untouched_upstream_gpt_5_6_seeds() { { let conn = db.conn.lock().expect("lock conn"); conn.execute( - "UPDATE model_pricing SET cache_creation_cost_per_million = '0' + "UPDATE model_pricing + SET input_cost_per_million = '5', + output_cost_per_million = '30', + cache_read_cost_per_million = '0.50', + cache_creation_cost_per_million = '0' WHERE model_id = 'gpt-5.6-sol'", [], ) @@ -3740,15 +3815,24 @@ fn model_pricing_repairs_only_untouched_upstream_gpt_5_6_seeds() { .expect("ensure pricing seeded"); let conn = db.conn.lock().expect("lock conn"); - let sol_cache_write: String = conn + let sol: (String, String, String, String) = conn .query_row( - "SELECT cache_creation_cost_per_million FROM model_pricing - WHERE model_id = 'gpt-5.6-sol'", + "SELECT input_cost_per_million, output_cost_per_million, + cache_read_cost_per_million, cache_creation_cost_per_million + FROM model_pricing WHERE model_id = 'gpt-5.6-sol'", [], - |row| row.get(0), + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)), ) .expect("query repaired Sol pricing"); - assert_eq!(sol_cache_write, "6.25"); + assert_eq!( + sol, + ( + "4".to_string(), + "20".to_string(), + "0.40".to_string(), + "5".to_string() + ) + ); let terra: (String, String, String, String) = conn .query_row( diff --git a/src-tauri/src/model_capabilities.rs b/src-tauri/src/model_capabilities.rs index 437bdf84..9b97a265 100644 --- a/src-tauri/src/model_capabilities.rs +++ b/src-tauri/src/model_capabilities.rs @@ -75,12 +75,16 @@ pub(crate) fn is_confirmed_text_only_model(model: &str) -> bool { "ark-code-latest", "deepseek-chat", "deepseek-reasoner", + // `deepseek-flash` and its `deepseek-v4.1-flash` alias are deliberately + // absent: the vendor's current catalog serves them with image input. "deepseek-v4-flash", "deepseek-v4-pro", "glm-5.1", // Exact rather than prefix matching: GLM visual models use a `v` // suffix (for example glm-5.2v), which must remain image-capable. + // GLM-5.3 is text-only; GLM-5.3-Flash is multimodal and stays out. "glm-5.2", + "glm-5.3", "kat-coder", "kat-coder-pro", "kat-coder-pro v1", @@ -216,7 +220,12 @@ mod tests { #[test] fn confirmed_text_only_registry_normalizes_namespaces_and_context_markers() { assert!(is_confirmed_text_only_model("deepseek/deepseek-v4-pro")); + assert!(!is_confirmed_text_only_model("deepseek-flash")); + assert!(!is_confirmed_text_only_model( + "opencode/deepseek-v4.1-flash" + )); assert!(is_confirmed_text_only_model("GLM-5.2[1M]")); + assert!(is_confirmed_text_only_model("z-ai/glm-5.3[1M]")); assert!(is_confirmed_text_only_model("qwen/qwen3-coder-plus")); assert!(is_confirmed_text_only_model( "Qwen/Qwen3-Coder-480B-A35B-Instruct" @@ -224,6 +233,9 @@ mod tests { assert!(is_confirmed_text_only_model("MiniMax-M2.7-Highspeed")); assert!(is_confirmed_text_only_model("step-3.5-flash-2603")); assert!(!is_confirmed_text_only_model("glm-5.2v")); + assert!(!is_confirmed_text_only_model("glm-5.3-flash")); + assert!(!is_confirmed_text_only_model("mimo-v2.6-pro")); + assert!(!is_confirmed_text_only_model("MiniMax-M3.1-Flash")); } #[test] diff --git a/src-tauri/src/presets/88api.json b/src-tauri/src/presets/88api.json index 1c568b6e..bfaecc61 100644 --- a/src-tauri/src/presets/88api.json +++ b/src-tauri/src/presets/88api.json @@ -55,9 +55,22 @@ ] } }, - "claude-haiku-4-5": { - "name": "Claude Haiku 4.5", - "reasoning": true + "claude-haiku-5-5": { + "name": "Claude Haiku 5.5", + "reasoning": true, + "limit": { + "context": 1000000, + "output": 128000 + }, + "modalities": { + "input": [ + "text", + "image" + ], + "output": [ + "text" + ] + } }, "claude-fable-5-1": { "name": "Claude Fable 5.1", @@ -106,9 +119,15 @@ "maxTokens": 128000 }, { - "id": "claude-haiku-4-5", - "name": "Claude Haiku 4.5", - "contextWindow": 200000 + "id": "claude-haiku-5-5", + "name": "Claude Haiku 5.5", + "reasoning": true, + "input": [ + "text", + "image" + ], + "contextWindow": 1000000, + "maxTokens": 128000 }, { "id": "claude-fable-5-1", @@ -140,9 +159,9 @@ "context_length": 1000000 }, { - "id": "claude-haiku-4-5", - "name": "Claude Haiku 4.5", - "context_length": 200000 + "id": "claude-haiku-5-5", + "name": "Claude Haiku 5.5", + "context_length": 1000000 }, { "id": "claude-fable-5-1", @@ -180,15 +199,15 @@ "maxTokens": 128000 }, { - "id": "claude-haiku-4-5", - "name": "Claude Haiku 4.5", + "id": "claude-haiku-5-5", + "name": "Claude Haiku 5.5", "reasoning": true, "input": [ "text", "image" ], - "contextWindow": 200000, - "maxTokens": 64000 + "contextWindow": 1000000, + "maxTokens": 128000 }, { "id": "claude-fable-5-1", diff --git a/src-tauri/src/presets/README.md b/src-tauri/src/presets/README.md index e94afde6..1794833f 100644 --- a/src-tauri/src/presets/README.md +++ b/src-tauri/src/presets/README.md @@ -1,12 +1,12 @@ # 88API preset data `88api.json` mirrors the native settings in `farion1231/cc-switch` at -`df40d53c36b604e044b4d5b9091aeb961aa56990`, from +`e217bfcbbbbbf82f4619ab62f08fb002635b7858`, from `src/config/{claude,gemini,opencode,openclaw,hermes,pi}ProviderPresets.ts`. Pi model capabilities are expanded from `src/config/piModelCatalog.ts`; TypeScript-only model catalog references are not native configuration fields. Codex uses the existing shared TOML builder with `88api`, -`https://api.88api.ai/v1`, and `gpt-5.6-sol`, matching the upstream preset. +`https://api.88api.ai/v1`, and `gpt-6.1-sol`, matching the upstream preset. The CLI uses its existing native configuration writers and form serialization. OpenClaw's separate suggested-defaults metadata is not a provider settings field; diff --git a/src-tauri/src/provider_preset_builtin.rs b/src-tauri/src/provider_preset_builtin.rs index 1494bd62..f2a27028 100644 --- a/src-tauri/src/provider_preset_builtin.rs +++ b/src-tauri/src/provider_preset_builtin.rs @@ -100,10 +100,10 @@ fn claude_provider_preset(preset: BuiltinProviderPresetId) -> Value { "https://platform.deepseek.com", "https://api.deepseek.com/anthropic", "ANTHROPIC_AUTH_TOKEN", - "deepseek-v4-pro", - "deepseek-v4-flash", - "deepseek-v4-pro", - "deepseek-v4-pro", + "deepseek-flash[1M]", + "deepseek-flash[1M]", + "deepseek-flash[1M]", + "deepseek-flash[1M]", "cn_official", "deepseek", "#1E88E5", @@ -114,10 +114,10 @@ fn claude_provider_preset(preset: BuiltinProviderPresetId) -> Value { "https://open.bigmodel.cn", "https://open.bigmodel.cn/api/anthropic", "ANTHROPIC_AUTH_TOKEN", - "glm-5.1", - "glm-5.1", - "glm-5.1", - "glm-5.1", + "glm-5.3[1M]", + "glm-5.3[1M]", + "glm-5.3[1M]", + "glm-5.3[1M]", "cn_official", "zhipu", "#0F62FE", @@ -128,10 +128,10 @@ fn claude_provider_preset(preset: BuiltinProviderPresetId) -> Value { "https://z.ai", "https://api.z.ai/api/anthropic", "ANTHROPIC_AUTH_TOKEN", - "glm-5.1", - "glm-5.1", - "glm-5.1", - "glm-5.1", + "glm-5.3[1M]", + "glm-5.3[1M]", + "glm-5.3[1M]", + "glm-5.3[1M]", "cn_official", "zhipu", "#0F62FE", @@ -142,10 +142,10 @@ fn claude_provider_preset(preset: BuiltinProviderPresetId) -> Value { "https://modelscope.cn", "https://api-inference.modelscope.cn", "ANTHROPIC_AUTH_TOKEN", - "ZhipuAI/GLM-5.2", - "ZhipuAI/GLM-5.2", - "ZhipuAI/GLM-5.2", - "ZhipuAI/GLM-5.2", + "ZhipuAI/GLM-5.2[1M]", + "ZhipuAI/GLM-5.2[1M]", + "ZhipuAI/GLM-5.2[1M]", + "ZhipuAI/GLM-5.2[1M]", "aggregator", "modelscope", "#624AFF", @@ -156,10 +156,10 @@ fn claude_provider_preset(preset: BuiltinProviderPresetId) -> Value { "https://platform.minimaxi.com", "https://api.minimaxi.com/anthropic", "ANTHROPIC_AUTH_TOKEN", - "MiniMax-M2.7", - "MiniMax-M2.7", - "MiniMax-M2.7", - "MiniMax-M2.7", + "MiniMax-M3.1-Flash[1M]", + "MiniMax-M3.1-Flash[1M]", + "MiniMax-M3.1-Flash[1M]", + "MiniMax-M3[1M]", "cn_official", "minimax", "#FF6B6B", @@ -173,10 +173,10 @@ fn claude_provider_preset(preset: BuiltinProviderPresetId) -> Value { "https://platform.xiaomimimo.com", "https://api.xiaomimimo.com/anthropic", "ANTHROPIC_AUTH_TOKEN", - "mimo-v2.5-pro", - "mimo-v2.5-pro", - "mimo-v2.5-pro", - "mimo-v2.5-pro", + "mimo-v2.6-pro[1M]", + "mimo-v2.6-pro[1M]", + "mimo-v2.6-pro[1M]", + "mimo-v2.6-pro[1M]", "cn_official", "xiaomimimo", "#000000", @@ -187,10 +187,10 @@ fn claude_provider_preset(preset: BuiltinProviderPresetId) -> Value { "https://platform.xiaomimimo.com/#/token-plan", "https://token-plan-cn.xiaomimimo.com/anthropic", "ANTHROPIC_AUTH_TOKEN", - "mimo-v2.5-pro", - "mimo-v2.5-pro", - "mimo-v2.5-pro", - "mimo-v2.5-pro", + "mimo-v2.6-pro[1M]", + "mimo-v2.6-pro[1M]", + "mimo-v2.6-pro[1M]", + "mimo-v2.6-pro[1M]", "cn_official", "xiaomimimo", "#000000", @@ -201,10 +201,10 @@ fn claude_provider_preset(preset: BuiltinProviderPresetId) -> Value { "https://opencode.ai/go", "https://opencode.ai/zen/go", "ANTHROPIC_API_KEY", - "deepseek-v4-flash", - "deepseek-v4-flash", - "deepseek-v4-flash", - "deepseek-v4-flash", + "deepseek-v4.1-flash[1M]", + "deepseek-v4.1-flash[1M]", + "deepseek-v4.1-flash[1M]", + "deepseek-v4.1-flash[1M]", "third_party", "opencode", "#211E1E", @@ -215,10 +215,10 @@ fn claude_provider_preset(preset: BuiltinProviderPresetId) -> Value { "https://openrouter.ai", "https://openrouter.ai/api", "ANTHROPIC_AUTH_TOKEN", - "anthropic/claude-sonnet-5", - "anthropic/claude-haiku-4.5", - "anthropic/claude-sonnet-5", - "anthropic/claude-opus-5", + "anthropic/claude-sonnet-5.5", + "anthropic/claude-haiku-5.5", + "anthropic/claude-sonnet-5.5", + "anthropic/claude-opus-5.5", "aggregator", "openrouter", "#6566F1", @@ -304,26 +304,43 @@ fn chat_reasoning( reasoning } -fn mimo_catalog() -> Vec { +fn mimo_catalog(include_ultraspeed: bool) -> Vec { let base_instructions = "You are MiMo, an AI assistant developed by Xiaomi. Today's date: {date} {week}. Your knowledge cutoff date is December 2024."; - vec![ + let mut models = vec![ json!({ - "model": "mimo-v2.5-pro", - "displayName": "MiMo V2.5 Pro", + "model": "mimo-v2.6-pro", + "displayName": "MiMo V2.6 Pro", "contextWindow": 1_048_576, - "inputModalities": ["text"], - "reasoningLevels": ["none", "high"], + "inputModalities": ["text", "image"], + "supportsParallelToolCalls": false, + "reasoningLevels": ["none", "low", "medium", "high"], + "defaultReasoningLevel": "low", "baseInstructions": base_instructions, }), json!({ - "model": "mimo-v2.5", - "displayName": "MiMo V2.5", + "model": "mimo-v2.6-flash", + "displayName": "MiMo V2.6 Flash", "contextWindow": 1_048_576, "inputModalities": ["text", "image"], - "reasoningLevels": ["none", "high"], + "supportsParallelToolCalls": false, + "reasoningLevels": ["none", "low", "medium", "high"], + "defaultReasoningLevel": "low", "baseInstructions": base_instructions, }), - ] + ]; + if include_ultraspeed { + models.push(json!({ + "model": "mimo-v2.6-pro-ultraspeed", + "displayName": "MiMo V2.6 Pro UltraSpeed", + "contextWindow": 1_048_576, + "inputModalities": ["text", "image"], + "supportsParallelToolCalls": false, + "reasoningLevels": ["none", "low", "medium", "high"], + "defaultReasoningLevel": "low", + "baseInstructions": base_instructions, + })); + } + models } fn codex_provider_preset(preset: BuiltinProviderPresetId) -> Value { @@ -335,25 +352,18 @@ fn codex_provider_preset(preset: BuiltinProviderPresetId) -> Value { "https://platform.deepseek.com", "deepseek", "https://api.deepseek.com", - "deepseek-v4-flash", + "deepseek-flash", "cn_official", "deepseek", "#1E88E5", Some("openai_responses"), - vec![ - json!({ - "model": "deepseek-v4-flash", - "displayName": "DeepSeek V4 Flash", - "contextWindow": 1_048_576, - "reasoningLevels": ["low", "high", "max"], - }), - json!({ - "model": "deepseek-v4-pro", - "displayName": "DeepSeek V4 Pro", - "contextWindow": 1_048_576, - "reasoningLevels": ["low", "high", "max"], - }), - ], + vec![json!({ + "model": "deepseek-flash", + "displayName": "DeepSeek V4.1 Flash", + "contextWindow": 1_048_576, + "inputModalities": ["text", "image"], + "reasoningLevels": ["low", "high", "max"], + })], None, ), ZhipuGlm | ZhipuGlmEn => { @@ -377,15 +387,15 @@ fn codex_provider_preset(preset: BuiltinProviderPresetId) -> Value { website, provider_name, base_url, - "glm-5.2", + "glm-5.3", "cn_official", "zhipu", "#0F62FE", Some("openai_chat"), vec![json!({ - "model": "glm-5.2", - "displayName": "GLM-5.2", - "contextWindow": 200_000, + "model": "glm-5.3", + "displayName": "GLM-5.3", + "contextWindow": 1_048_576, "reasoningLevels": ["none", "high"], })], Some(chat_reasoning("thinking", false, None)), @@ -413,20 +423,31 @@ fn codex_provider_preset(preset: BuiltinProviderPresetId) -> Value { "https://platform.minimaxi.com", "minimax", "https://api.minimaxi.com/v1", - "MiniMax-M3", + "MiniMax-M3.1-Flash", "cn_official", "minimax", "#FF6B6B", Some("openai_responses"), - vec![json!({ - "model": "MiniMax-M3", - "displayName": "MiniMax-M3", - "contextWindow": 1_000_000, - "reasoningLevels": ["none", "high"], - "supportsParallelToolCalls": true, - "inputModalities": ["text", "image"], - "baseInstructions": "You are Codex, a coding agent based on MiniMax-M3. You and the user share the same workspace and collaborate to achieve the user's goals.", - })], + vec![ + json!({ + "model": "MiniMax-M3.1-Flash", + "displayName": "MiniMax-M3.1-Flash", + "contextWindow": 1_000_000, + "reasoningLevels": ["low", "medium", "high", "xhigh", "max"], + "supportsParallelToolCalls": true, + "inputModalities": ["text", "image"], + "baseInstructions": "You are Codex, a coding agent based on MiniMax-M3.1-Flash. You and the user share the same workspace and collaborate to achieve the user's goals.", + }), + json!({ + "model": "MiniMax-M3", + "displayName": "MiniMax-M3", + "contextWindow": 1_000_000, + "reasoningLevels": ["none", "high"], + "supportsParallelToolCalls": true, + "inputModalities": ["text", "image"], + "baseInstructions": "You are Codex, a coding agent based on MiniMax-M3. You and the user share the same workspace and collaborate to achieve the user's goals.", + }), + ], None, ), XiaomiMimo | XiaomiMimoTokenPlan => { @@ -450,12 +471,12 @@ fn codex_provider_preset(preset: BuiltinProviderPresetId) -> Value { website, provider_name, base_url, - "mimo-v2.5-pro", + "mimo-v2.6-pro", "cn_official", "xiaomimimo", "#000000", Some("openai_responses"), - mimo_catalog(), + mimo_catalog(preset == XiaomiMimo), None, ) } @@ -464,18 +485,17 @@ fn codex_provider_preset(preset: BuiltinProviderPresetId) -> Value { "https://opencode.ai/go", "opencode_go", "https://opencode.ai/zen/go/v1", - "glm-5.2", + "glm-5.3", "third_party", "opencode", "#211E1E", Some("openai_chat"), vec![ - json!({ "model": "glm-5.2", "displayName": "GLM 5.2", "contextWindow": 204_800, "reasoningLevels": ["high", "max"] }), - json!({ "model": "glm-5.1", "displayName": "GLM 5.1", "contextWindow": 204_800 }), - json!({ "model": "kimi-k2.7-code", "displayName": "Kimi K2.7 Code", "contextWindow": 262_144 }), - json!({ "model": "deepseek-v4-pro", "displayName": "DeepSeek V4 Pro", "contextWindow": 1_048_576, "reasoningLevels": ["high", "max"] }), - json!({ "model": "deepseek-v4-flash", "displayName": "DeepSeek V4 Flash", "contextWindow": 1_048_576, "reasoningLevels": ["low", "high", "max"] }), - json!({ "model": "mimo-v2.5-pro", "displayName": "MiMo V2.5 Pro", "contextWindow": 1_048_576 }), + json!({ "model": "glm-5.3", "displayName": "GLM 5.3", "contextWindow": 1_000_000, "reasoningLevels": ["low", "high", "max"], "defaultReasoningLevel": "high" }), + json!({ "model": "glm-5.3-flash", "displayName": "GLM 5.3 Flash", "contextWindow": 1_000_000, "inputModalities": ["text", "image"], "reasoningLevels": ["low", "high", "max"], "defaultReasoningLevel": "high" }), + json!({ "model": "kimi-k3.1-pro", "displayName": "Kimi K3.1 Pro", "contextWindow": 1_048_576, "inputModalities": ["text", "image"], "reasoningLevels": ["max"] }), + json!({ "model": "deepseek-v4.1-flash", "displayName": "DeepSeek V4.1 Flash", "contextWindow": 1_048_576, "inputModalities": ["text", "image"], "reasoningLevels": ["low", "high", "max"] }), + json!({ "model": "mimo-v2.6-pro", "displayName": "MiMo V2.6 Pro", "contextWindow": 1_048_576, "inputModalities": ["text", "image"] }), ], Some(chat_reasoning("none", true, Some("zen"))), )), @@ -484,7 +504,7 @@ fn codex_provider_preset(preset: BuiltinProviderPresetId) -> Value { "https://openrouter.ai", "openrouter", "https://openrouter.ai/api/v1", - "gpt-5.6-sol", + "openai/gpt-6.1-sol", "aggregator", "openrouter", "#6566F1", diff --git a/src-tauri/src/provider_preset_models.rs b/src-tauri/src/provider_preset_models.rs index ce9c5a61..38403373 100644 --- a/src-tauri/src/provider_preset_models.rs +++ b/src-tauri/src/provider_preset_models.rs @@ -1,25 +1,27 @@ use serde_json::{json, Map, Value}; -pub(crate) const CLAUDE_OPUS_MODEL: &str = "claude-opus-5"; -pub(crate) const CLAUDE_OPUS_NAME: &str = "Claude Opus 5"; -pub(crate) const CLAUDE_SONNET_MODEL: &str = "claude-sonnet-5"; -pub(crate) const CLAUDE_SONNET_NAME: &str = "Claude Sonnet 5"; -pub(crate) const CLAUDE_HAIKU_MODEL: &str = "claude-haiku-4-5"; -pub(crate) const CLAUDE_HAIKU_DATED_MODEL: &str = "claude-haiku-4-5-20251001"; -pub(crate) const CLAUDE_HAIKU_NAME: &str = "Claude Haiku 4.5"; +pub(crate) const CLAUDE_OPUS_MODEL: &str = "claude-opus-5-5"; +pub(crate) const CLAUDE_OPUS_NAME: &str = "Claude Opus 5.5"; +pub(crate) const CLAUDE_SONNET_MODEL: &str = "claude-sonnet-5-5"; +pub(crate) const CLAUDE_SONNET_NAME: &str = "Claude Sonnet 5.5"; +pub(crate) const CLAUDE_HAIKU_MODEL: &str = "claude-haiku-5-5"; +pub(crate) const CLAUDE_HAIKU_NAME: &str = "Claude Haiku 5.5"; -pub(crate) const CODEX_DEFAULT_MODEL: &str = "gpt-5.6-sol"; -pub(crate) const CODEX_DEFAULT_MODEL_NAME: &str = "GPT-5.6 Sol"; -pub(crate) const CODEX_OAUTH_FAST_MODEL: &str = "gpt-5.6-luna"; -pub(crate) const CODEX_OAUTH_CONTEXT_TOKENS: &str = "372000"; +pub(crate) const CODEX_DEFAULT_MODEL: &str = "gpt-6.1-sol"; +pub(crate) const CODEX_DEFAULT_MODEL_NAME: &str = "GPT-6.1 Sol"; +pub(crate) const CODEX_OAUTH_FAST_MODEL: &str = "gpt-6-luna"; +// Codex 订阅后端把 GPT 系窗口封在 272K(超过 272K 输入按 2 倍计价), +// 与上游 cc-switch 的 GPT_CONTEXT_WINDOW_CAP 保持同值。 +pub(crate) const CODEX_OAUTH_CONTEXT_TOKENS: &str = "272000"; -pub(crate) const GEMINI_DEFAULT_MODEL: &str = "gemini-3.6-flash"; +pub(crate) const GEMINI_DEFAULT_MODEL: &str = "gemini-3.8-flash"; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum SponsorModelFamily { Claude, RunApiClaude, Gpt, + GptAstra, } impl SponsorModelFamily { @@ -28,6 +30,7 @@ impl SponsorModelFamily { Self::Claude => CLAUDE_OPUS_MODEL, Self::RunApiClaude => CLAUDE_SONNET_MODEL, Self::Gpt => CODEX_DEFAULT_MODEL, + Self::GptAstra => "gpt-6-astra", } } @@ -36,13 +39,14 @@ impl SponsorModelFamily { Self::Claude => CLAUDE_OPUS_NAME, Self::RunApiClaude => CLAUDE_SONNET_NAME, Self::Gpt => CODEX_DEFAULT_MODEL_NAME, + Self::GptAstra => "GPT-6 Astra", } } pub(crate) const fn primary_context_window(self) -> &'static str { match self { Self::Claude | Self::RunApiClaude => "1000000", - Self::Gpt => "400000", + Self::Gpt | Self::GptAstra => "272000", } } } @@ -51,11 +55,19 @@ pub(crate) fn sponsor_model_family(preset_id: &str) -> Option Some(SponsorModelFamily::Claude), "runapi" => Some(SponsorModelFamily::RunApiClaude), - "qiniu" | "fenno" => Some(SponsorModelFamily::Gpt), + "qiniu" => Some(SponsorModelFamily::GptAstra), + "fenno" => Some(SponsorModelFamily::Gpt), _ => None, } } +pub(crate) fn sponsor_codex_model(preset_id: &str) -> &'static str { + match sponsor_model_family(preset_id) { + Some(SponsorModelFamily::GptAstra) => SponsorModelFamily::GptAstra.primary_model(), + _ => CODEX_DEFAULT_MODEL, + } +} + pub(crate) fn codex_oauth_claude_env() -> Value { json!({ "ANTHROPIC_BASE_URL": "https://chatgpt.com/backend-api/codex", @@ -84,8 +96,12 @@ pub(crate) fn sponsor_opencode_settings( insert_named_model(&mut models, CLAUDE_OPUS_MODEL, CLAUDE_OPUS_NAME); insert_named_model(&mut models, CLAUDE_HAIKU_MODEL, CLAUDE_HAIKU_NAME); } - SponsorModelFamily::Gpt => { - insert_named_model(&mut models, CODEX_DEFAULT_MODEL, CODEX_DEFAULT_MODEL_NAME); + SponsorModelFamily::Gpt | SponsorModelFamily::GptAstra => { + insert_named_model( + &mut models, + family.primary_model(), + family.primary_model_name(), + ); } } @@ -94,7 +110,7 @@ pub(crate) fn sponsor_opencode_settings( SponsorModelFamily::Claude | SponsorModelFamily::RunApiClaude => { "@ai-sdk/anthropic" } - SponsorModelFamily::Gpt => "@ai-sdk/openai-compatible", + SponsorModelFamily::Gpt | SponsorModelFamily::GptAstra => "@ai-sdk/openai-compatible", }, "name": provider_name, "options": { @@ -110,7 +126,7 @@ pub(crate) fn sponsor_hermes_models(family: SponsorModelFamily) -> Vec { SponsorModelFamily::Claude => vec![ named_model(CLAUDE_OPUS_MODEL, CLAUDE_OPUS_NAME), named_model(CLAUDE_SONNET_MODEL, CLAUDE_SONNET_NAME), - named_model(CLAUDE_HAIKU_DATED_MODEL, CLAUDE_HAIKU_NAME), + named_model(CLAUDE_HAIKU_MODEL, CLAUDE_HAIKU_NAME), ], // Hermes derives model.default from the first entry. Upstream keeps a // separate suggested default for RunAPI, so put Sonnet first here to @@ -120,8 +136,11 @@ pub(crate) fn sponsor_hermes_models(family: SponsorModelFamily) -> Vec { named_model(CLAUDE_OPUS_MODEL, CLAUDE_OPUS_NAME), named_model(CLAUDE_HAIKU_MODEL, CLAUDE_HAIKU_NAME), ], - SponsorModelFamily::Gpt => { - vec![named_model(CODEX_DEFAULT_MODEL, CODEX_DEFAULT_MODEL_NAME)] + SponsorModelFamily::Gpt | SponsorModelFamily::GptAstra => { + vec![named_model( + family.primary_model(), + family.primary_model_name(), + )] } } } @@ -132,20 +151,20 @@ pub(crate) fn sponsor_openclaw_models(family: SponsorModelFamily) -> Vec json!({ "id": CLAUDE_OPUS_MODEL, "name": CLAUDE_OPUS_NAME, + "reasoning": true, + "input": ["text", "image"], "contextWindow": 1000000, - "cost": { - "input": 5, - "output": 25, - }, + "maxTokens": 128000, + "cost": { "input": 4, "output": 20, "cacheRead": 0.2, "cacheWrite": 5 }, }), json!({ "id": CLAUDE_SONNET_MODEL, "name": CLAUDE_SONNET_NAME, + "reasoning": true, + "input": ["text", "image"], "contextWindow": 1000000, - "cost": { - "input": 3, - "output": 15, - }, + "maxTokens": 128000, + "cost": { "input": 2, "output": 10, "cacheRead": 0.1, "cacheWrite": 2.5 }, }), ], // OpenClaw also derives the no-argument default from the first entry. @@ -154,23 +173,35 @@ pub(crate) fn sponsor_openclaw_models(family: SponsorModelFamily) -> Vec json!({ "id": CLAUDE_SONNET_MODEL, "name": CLAUDE_SONNET_NAME, + "reasoning": true, + "input": ["text", "image"], "contextWindow": 1000000, + "maxTokens": 128000, + "cost": { "input": 2, "output": 10, "cacheRead": 0.1, "cacheWrite": 2.5 }, }), json!({ "id": CLAUDE_OPUS_MODEL, "name": CLAUDE_OPUS_NAME, + "reasoning": true, + "input": ["text", "image"], "contextWindow": 1000000, + "maxTokens": 128000, + "cost": { "input": 4, "output": 20, "cacheRead": 0.2, "cacheWrite": 5 }, }), json!({ "id": CLAUDE_HAIKU_MODEL, "name": CLAUDE_HAIKU_NAME, - "contextWindow": 200000, + "reasoning": true, + "input": ["text", "image"], + "contextWindow": 1000000, + "maxTokens": 128000, + "cost": { "input": 0.1, "output": 0.5, "cacheRead": 0.01, "cacheWrite": 0.125 }, }), ], - SponsorModelFamily::Gpt => vec![json!({ - "id": CODEX_DEFAULT_MODEL, - "name": CODEX_DEFAULT_MODEL_NAME, - "contextWindow": 400000, + SponsorModelFamily::Gpt | SponsorModelFamily::GptAstra => vec![json!({ + "id": family.primary_model(), + "name": family.primary_model_name(), + "contextWindow": 272000, })], } } @@ -192,10 +223,12 @@ mod tests { #[test] fn upstream_default_model_ids_are_pinned() { - assert_eq!(CLAUDE_OPUS_MODEL, "claude-opus-5"); - assert_eq!(CLAUDE_SONNET_MODEL, "claude-sonnet-5"); - assert_eq!(CODEX_DEFAULT_MODEL, "gpt-5.6-sol"); - assert_eq!(GEMINI_DEFAULT_MODEL, "gemini-3.6-flash"); + assert_eq!(CLAUDE_OPUS_MODEL, "claude-opus-5-5"); + assert_eq!(CLAUDE_SONNET_MODEL, "claude-sonnet-5-5"); + assert_eq!(CLAUDE_HAIKU_MODEL, "claude-haiku-5-5"); + assert_eq!(CODEX_DEFAULT_MODEL, "gpt-6.1-sol"); + assert_eq!(CODEX_OAUTH_FAST_MODEL, "gpt-6-luna"); + assert_eq!(GEMINI_DEFAULT_MODEL, "gemini-3.8-flash"); } #[test] @@ -232,7 +265,10 @@ mod tests { sponsor_model_family("runapi"), Some(SponsorModelFamily::RunApiClaude) ); - assert_eq!(sponsor_model_family("qiniu"), Some(SponsorModelFamily::Gpt)); + assert_eq!( + sponsor_model_family("qiniu"), + Some(SponsorModelFamily::GptAstra) + ); assert_eq!(sponsor_model_family("fenno"), Some(SponsorModelFamily::Gpt)); } } diff --git a/src-tauri/src/provider_preset_pi.rs b/src-tauri/src/provider_preset_pi.rs index 657dcac3..df1a03ea 100644 --- a/src-tauri/src/provider_preset_pi.rs +++ b/src-tauri/src/provider_preset_pi.rs @@ -212,52 +212,55 @@ pub(crate) static PI_SPONSOR_PROVIDER_PRESETS: [PiProviderPreset; 8] = [ }, ]; -fn claude_sonnet(id: &str) -> Value { +fn claude_model(name: &str, id: &str) -> Value { json!({ - "name": "Claude Sonnet 5", + "name": name, "reasoning": true, "input": ["text", "image"], "contextWindow": 1_000_000, "maxTokens": 128_000, "id": id, - "thinkingLevelMap": { "xhigh": "xhigh", "max": "max" }, - "compat": { "forceAdaptiveThinking": true }, + "thinkingLevelMap": {}, }) } +/// Opus and Fable run adaptive thinking with no "off" level; Sonnet and Haiku +/// keep Pi's defaults. Mirrors the upstream pi thinking bindings. +fn claude_adaptive(name: &str, id: &str) -> Value { + let mut model = claude_model(name, id); + model["thinkingLevelMap"] = json!({ "off": null, "xhigh": "xhigh", "max": "max" }); + model["compat"] = json!({ "forceAdaptiveThinking": true }); + model +} + +fn claude_sonnet(id: &str) -> Value { + claude_model("Claude Sonnet 5.5", id) +} + fn claude_opus(id: &str) -> Value { - json!({ - "name": "Claude Opus 5", - "reasoning": true, - "input": ["text", "image"], - "contextWindow": 1_000_000, - "maxTokens": 128_000, - "id": id, - "thinkingLevelMap": { "xhigh": "xhigh", "max": "max" }, - "compat": { "forceAdaptiveThinking": true }, - }) + claude_adaptive("Claude Opus 5.5", id) } -fn gpt_5_6_sol() -> Value { +fn gpt_6_1_sol() -> Value { json!({ - "name": "GPT-5.6 Sol", + "name": "GPT-6.1 Sol", "reasoning": true, "input": ["text", "image"], "contextWindow": 272_000, "maxTokens": 128_000, - "id": "gpt-5.6-sol", + "id": "gpt-6.1-sol", "thinkingLevelMap": {}, }) } -fn glm_5_1() -> Value { +fn glm_5_3() -> Value { json!({ - "name": "GLM-5.1", + "name": "GLM-5.3", "reasoning": true, "input": ["text"], - "contextWindow": 200_000, + "contextWindow": 1_000_000, "maxTokens": 131_072, - "id": "glm-5.1", + "id": "glm-5.3", "thinkingLevelMap": {}, }) } @@ -269,8 +272,8 @@ fn anthropic_settings(name: &str, base_url: &str) -> Value { "api": "anthropic-messages", "apiKey": "", "models": [ - claude_sonnet("claude-sonnet-5"), - claude_opus("claude-opus-5"), + claude_sonnet("claude-sonnet-5-5"), + claude_opus("claude-opus-5-5"), ], }) } @@ -281,7 +284,7 @@ fn openai_gpt_settings(name: &str, base_url: &str) -> Value { "baseUrl": base_url, "api": "openai-completions", "apiKey": "", - "models": [gpt_5_6_sol()], + "models": [gpt_6_1_sol()], }) } @@ -302,20 +305,55 @@ fn runapi_settings() -> Value { settings["models"] .as_array_mut() .expect("Pi RunAPI models are an array") - .push(json!({ - "name": "Claude Haiku 4.5 (latest)", - "reasoning": true, - "input": ["text", "image"], - "contextWindow": 200_000, - "maxTokens": 64_000, - "id": "claude-haiku-4-5", - "thinkingLevelMap": {}, - })); + .push(claude_model("Claude Haiku 5.5", "claude-haiku-5-5")); settings } fn qiniu_settings() -> Value { - openai_gpt_settings("Qiniu", "https://api.qnaigc.com/v1") + json!({ + "name": "Qiniu", + "baseUrl": "https://api.qnaigc.com/v1", + "api": "openai-completions", + "apiKey": "", + "models": [ + { + "name": "GPT-6 Astra", + "reasoning": true, + "input": ["text", "image"], + "contextWindow": 272_000, + "maxTokens": 128_000, + "id": "gpt-6-astra", + "thinkingLevelMap": {}, + }, + { + "name": "Kimi K3", + "reasoning": true, + "input": ["text", "image"], + "contextWindow": 1_048_576, + "maxTokens": 131_072, + "id": "moonshotai/kimi-k3", + "thinkingLevelMap": {}, + }, + { + "name": "GLM-5.3", + "reasoning": true, + "input": ["text"], + "contextWindow": 1_048_576, + "maxTokens": 131_072, + "id": "z-ai/glm-5.3", + "thinkingLevelMap": {}, + }, + { + "name": "GLM-5.3 Flash", + "reasoning": true, + "input": ["text", "image"], + "contextWindow": 1_048_576, + "maxTokens": 131_072, + "id": "z-ai/glm-5.3-flash", + "thinkingLevelMap": {}, + }, + ], + }) } fn cubence_settings() -> Value { @@ -326,7 +364,7 @@ fn deepseek_model(name: &str, id: &str) -> Value { json!({ "name": name, "reasoning": true, - "input": ["text"], + "input": ["text", "image"], "contextWindow": 1_000_000, "maxTokens": 384_000, "id": id, @@ -346,10 +384,7 @@ fn deepseek_settings() -> Value { "baseUrl": "https://api.deepseek.com/v1", "api": "openai-completions", "apiKey": "", - "models": [ - deepseek_model("DeepSeek V4 Pro", "deepseek-v4-pro"), - deepseek_model("DeepSeek V4 Flash", "deepseek-v4-flash"), - ], + "models": [deepseek_model("DeepSeek V4.1 Flash", "deepseek-flash")], }) } @@ -359,7 +394,7 @@ fn zhipu_glm_settings() -> Value { "baseUrl": "https://open.bigmodel.cn/api/coding/paas/v4", "api": "openai-completions", "apiKey": "", - "models": [glm_5_1()], + "models": [glm_5_3()], }) } @@ -369,7 +404,7 @@ fn zhipu_glm_en_settings() -> Value { "baseUrl": "https://api.z.ai/api/coding/paas/v4", "api": "openai-completions", "apiKey": "", - "models": [glm_5_1()], + "models": [glm_5_3()], }) } @@ -398,13 +433,21 @@ fn minimax_settings() -> Value { "api": "openai-completions", "apiKey": "", "models": [{ - "name": "MiniMax-M2.7", + "name": "MiniMax-M3.1-Flash", "reasoning": true, - "input": ["text"], - "contextWindow": 204_800, + "input": ["text", "image"], + "contextWindow": 1_000_000, "maxTokens": 131_072, - "id": "MiniMax-M2.7", - "thinkingLevelMap": {}, + "id": "MiniMax-M3.1-Flash", + "thinkingLevelMap": { + "off": null, + "minimal": null, + "low": "low", + "medium": "medium", + "high": "high", + "xhigh": "xhigh", + "max": "max", + }, }], }) } @@ -435,8 +478,24 @@ fn xiaomi_mimo_settings() -> Value { "api": "openai-completions", "apiKey": "", "models": [ - xiaomi_model("MiMo-V2.5-Pro", "mimo-v2.5-pro", &["text"], true), - xiaomi_model("MiMo-V2.5", "mimo-v2.5", &["text", "image"], true), + xiaomi_model( + "MiMo V2.6 Pro", + "mimo-v2.6-pro", + &["text", "image"], + true, + ), + xiaomi_model( + "MiMo V2.6 Flash", + "mimo-v2.6-flash", + &["text", "image"], + true, + ), + xiaomi_model( + "MiMo V2.6 Pro UltraSpeed", + "mimo-v2.6-pro-ultraspeed", + &["text", "image"], + true, + ), ], }) } @@ -448,8 +507,8 @@ fn xiaomi_mimo_token_plan_settings() -> Value { "api": "openai-completions", "apiKey": "", "models": [ - xiaomi_model("MiMo-V2.5-Pro", "mimo-v2.5-pro", &["text"], false), - xiaomi_model("MiMo-V2.5", "mimo-v2.5", &["text", "image"], false), + xiaomi_model("MiMo V2.6 Pro", "mimo-v2.6-pro", &["text", "image"], true), + xiaomi_model("MiMo V2.6 Flash", "mimo-v2.6-flash", &["text", "image"], true), ], }) } @@ -481,12 +540,12 @@ fn opencode_go_settings() -> Value { "apiKey": "", "models": [ { - "name": "GLM 5.2", + "name": "GLM-5.3", "reasoning": true, "input": ["text"], - "contextWindow": 1_000_000, + "contextWindow": 1_048_576, "maxTokens": 131_072, - "id": "glm-5.2", + "id": "glm-5.3", "compat": opencode_compat(json!({})), "thinkingLevelMap": { "off": null, @@ -499,35 +558,32 @@ fn opencode_go_settings() -> Value { }, }, { - "name": "Kimi K2.7 Code", + "name": "GLM-5.3 Flash", "reasoning": true, "input": ["text", "image"], - "contextWindow": 262_144, - "maxTokens": 262_144, - "id": "kimi-k2.7-code", + "contextWindow": 1_048_576, + "maxTokens": 131_072, + "id": "glm-5.3-flash", "compat": opencode_compat(json!({})), "thinkingLevelMap": {}, }, { - "name": "DeepSeek V4 Pro", + "name": "Kimi K3.1 Pro", "reasoning": true, - "input": ["text"], - "contextWindow": 1_000_000, - "maxTokens": 384_000, - "id": "deepseek-v4-pro", - "compat": opencode_compat(json!({ - "requiresReasoningContentOnAssistantMessages": true, - "thinkingFormat": "deepseek", - })), - "thinkingLevelMap": thinking_levels.clone(), + "input": ["text", "image"], + "contextWindow": 1_048_576, + "maxTokens": 131_072, + "id": "kimi-k3.1-pro", + "compat": opencode_compat(json!({})), + "thinkingLevelMap": {}, }, { - "name": "DeepSeek V4 Flash", + "name": "DeepSeek V4.1 Flash", "reasoning": true, - "input": ["text"], + "input": ["text", "image"], "contextWindow": 1_000_000, "maxTokens": 384_000, - "id": "deepseek-v4-flash", + "id": "deepseek-v4.1-flash", "compat": opencode_compat(json!({ "requiresReasoningContentOnAssistantMessages": true, "thinkingFormat": "deepseek", @@ -535,12 +591,32 @@ fn opencode_go_settings() -> Value { "thinkingLevelMap": thinking_levels, }, { - "name": "MiMo-V2.5-Pro", + "name": "MiMo V2.6 Pro", "reasoning": true, - "input": ["text"], + "input": ["text", "image"], "contextWindow": 1_048_576, "maxTokens": 131_072, - "id": "mimo-v2.5-pro", + "id": "mimo-v2.6-pro", + "compat": opencode_compat(json!({})), + "thinkingLevelMap": {}, + }, + { + "name": "Qwen3.8 Max", + "reasoning": true, + "input": ["text", "image"], + "contextWindow": 983_616, + "maxTokens": 131_072, + "id": "qwen3.8-max", + "compat": opencode_compat(json!({})), + "thinkingLevelMap": {}, + }, + { + "name": "MiniMax-M3.1-Flash", + "reasoning": true, + "input": ["text", "image"], + "contextWindow": 1_000_000, + "maxTokens": 128_000, + "id": "minimax-m3.1-flash", "compat": opencode_compat(json!({})), "thinkingLevelMap": {}, }, @@ -555,8 +631,10 @@ fn openrouter_settings() -> Value { "api": "anthropic-messages", "apiKey": "", "models": [ - claude_sonnet("anthropic/claude-sonnet-5"), - claude_opus("anthropic/claude-opus-5"), + claude_opus("anthropic/claude-opus-5.5"), + claude_sonnet("anthropic/claude-sonnet-5.5"), + claude_model("Claude Haiku 5.5", "anthropic/claude-haiku-5.5"), + claude_adaptive("Claude Fable 5.1", "anthropic/claude-fable-5.1"), ], }) } diff --git a/src-tauri/src/proxy/providers/codex.rs b/src-tauri/src/proxy/providers/codex.rs index 383c1520..c0f4c059 100644 --- a/src-tauri/src/proxy/providers/codex.rs +++ b/src-tauri/src/proxy/providers/codex.rs @@ -1170,16 +1170,20 @@ wire_api = "chat" .expect("OpenCode Go preset"); let provider: Provider = serde_json::from_value(value).expect("valid provider preset"); - let glm = resolve_codex_chat_reasoning_config(&provider, &json!({ "model": "GLM-5.2" })) + let glm = resolve_codex_chat_reasoning_config(&provider, &json!({ "model": "glm-5.3" })) .expect("GLM reasoning config"); assert_eq!( glm.effort_levels, - Some(vec!["high".to_string(), "max".to_string()]) + Some(vec![ + "low".to_string(), + "high".to_string(), + "max".to_string() + ]) ); let flash = resolve_codex_chat_reasoning_config( &provider, - &json!({ "model": "deepseek-v4-flash" }), + &json!({ "model": "deepseek-v4.1-flash" }), ) .expect("DeepSeek reasoning config"); assert_eq!( @@ -1191,8 +1195,9 @@ wire_api = "chat" ]) ); - let toggle = resolve_codex_chat_reasoning_config(&provider, &json!({ "model": "glm-5.1" })) - .expect("toggle-only reasoning config"); + let toggle = + resolve_codex_chat_reasoning_config(&provider, &json!({ "model": "mimo-v2.6-pro" })) + .expect("toggle-only reasoning config"); assert!(toggle.effort_levels.is_none()); } diff --git a/src-tauri/src/services/provider/tests.rs b/src-tauri/src/services/provider/tests.rs index 60358d91..e918d28c 100644 --- a/src-tauri/src/services/provider/tests.rs +++ b/src-tauri/src/services/provider/tests.rs @@ -2717,7 +2717,7 @@ fn codex_oauth_backfill_strips_only_injected_context_defaults() { let live = json!({ "env": { "ANTHROPIC_MODEL": "gpt-5.6-sol", - "CLAUDE_CODE_MAX_CONTEXT_TOKENS": "372000", + "CLAUDE_CODE_MAX_CONTEXT_TOKENS": "272000", "CLAUDE_CODE_AUTO_COMPACT_WINDOW": "360000" } }); diff --git a/src-tauri/src/services/usage_stats.rs b/src-tauri/src/services/usage_stats.rs index 263aa29f..568fdeea 100644 --- a/src-tauri/src/services/usage_stats.rs +++ b/src-tauri/src/services/usage_stats.rs @@ -2318,9 +2318,9 @@ mod tests { [], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), )?; - assert_eq!(input_cost, "5.000000"); - assert_eq!(output_cost, "30.000000"); - assert_eq!(total_cost, "35.000000"); + assert_eq!(input_cost, "4.000000"); + assert_eq!(output_cost, "20.000000"); + assert_eq!(total_cost, "24.000000"); Ok(()) } diff --git a/src-tauri/tests/provider_add_noninteractive.rs b/src-tauri/tests/provider_add_noninteractive.rs index bf6043a8..c8bebbc0 100644 --- a/src-tauri/tests/provider_add_noninteractive.rs +++ b/src-tauri/tests/provider_add_noninteractive.rs @@ -514,7 +514,7 @@ fn add_packycode_template_is_scriptable_for_every_additive_app() { "https://www.packyapi.ai/v1" ); assert!(opencode.settings_config["models"] - .get("claude-opus-5") + .get("claude-opus-5-5") .is_some()); let hermes = saved_provider(AppType::Hermes, "packy-hermes"); @@ -524,7 +524,7 @@ fn add_packycode_template_is_scriptable_for_every_additive_app() { "https://www.packyapi.ai" ); assert_eq!(hermes.settings_config["api_mode"], "anthropic_messages"); - assert_eq!(hermes.settings_config["models"][0]["id"], "claude-opus-5"); + assert_eq!(hermes.settings_config["models"][0]["id"], "claude-opus-5-5"); let openclaw = saved_provider(AppType::OpenClaw, "packy-openclaw"); assert_eq!(openclaw.settings_config["apiKey"], "sk-packy"); @@ -533,7 +533,10 @@ fn add_packycode_template_is_scriptable_for_every_additive_app() { "https://www.packyapi.ai" ); assert_eq!(openclaw.settings_config["api"], "anthropic-messages"); - assert_eq!(openclaw.settings_config["models"][0]["id"], "claude-opus-5"); + assert_eq!( + openclaw.settings_config["models"][0]["id"], + "claude-opus-5-5" + ); } #[test] @@ -574,7 +577,7 @@ fn add_openmodel_template_is_scriptable_for_every_app() { let codex_config = codex.settings_config["config"] .as_str() .expect("OpenModel Codex config should be TOML"); - assert!(codex_config.contains("model = \"gpt-5.6-sol\"")); + assert!(codex_config.contains("model = \"gpt-6.1-sol\"")); assert!(codex_config.contains("base_url = \"https://api.openmodel.ai/v1\"")); assert!(codex_config.contains("wire_api = \"responses\"")); @@ -584,7 +587,7 @@ fn add_openmodel_template_is_scriptable_for_every_app() { env_str(&gemini, "GOOGLE_GEMINI_BASE_URL"), Some("https://api.openmodel.ai") ); - assert_eq!(env_str(&gemini, "GEMINI_MODEL"), Some("gemini-3.6-flash")); + assert_eq!(env_str(&gemini, "GEMINI_MODEL"), Some("gemini-3.8-flash")); let opencode = saved_provider(AppType::OpenCode, "openmodel-opencode"); assert_eq!(opencode.settings_config["options"]["apiKey"], "om-test"); @@ -593,7 +596,7 @@ fn add_openmodel_template_is_scriptable_for_every_app() { "https://api.openmodel.ai/v1" ); assert!(opencode.settings_config["models"] - .get("claude-opus-5") + .get("claude-opus-5-5") .is_some()); let hermes = saved_provider(AppType::Hermes, "openmodel-hermes"); @@ -603,7 +606,7 @@ fn add_openmodel_template_is_scriptable_for_every_app() { "https://api.openmodel.ai" ); assert_eq!(hermes.settings_config["api_mode"], "anthropic_messages"); - assert_eq!(hermes.settings_config["models"][0]["id"], "claude-opus-5"); + assert_eq!(hermes.settings_config["models"][0]["id"], "claude-opus-5-5"); let openclaw = saved_provider(AppType::OpenClaw, "openmodel-openclaw"); assert_eq!(openclaw.settings_config["apiKey"], "om-test"); @@ -612,7 +615,10 @@ fn add_openmodel_template_is_scriptable_for_every_app() { "https://api.openmodel.ai" ); assert_eq!(openclaw.settings_config["api"], "anthropic-messages"); - assert_eq!(openclaw.settings_config["models"][0]["id"], "claude-opus-5"); + assert_eq!( + openclaw.settings_config["models"][0]["id"], + "claude-opus-5-5" + ); } #[test] @@ -653,7 +659,7 @@ fn add_patewayai_template_uses_upstream_claude_and_codex_settings() { let config = codex.settings_config["config"] .as_str() .expect("PatewayAI Codex config should be TOML"); - assert!(config.contains("model = \"gpt-5.6-sol\"")); + assert!(config.contains("model = \"gpt-6.1-sol\"")); assert!(config.contains("base_url = \"https://api.pateway.ai/v1\"")); assert!(config.contains("name = \"patewayai\"")); assert!(config.contains("wire_api = \"responses\"")); From 15f55635b10c89472742c5bfeb5f6d2af5e63abe Mon Sep 17 00:00:00 2001 From: xioa <137432161+Xiao-Maker-droid@users.noreply.github.com> Date: Wed, 4 Nov 2026 23:48:23 +0800 Subject: [PATCH 10/23] fix(proxy): keep mid-conversation system messages in place for prefix cache (#527) * fix(proxy): keep mid-conversation system messages in place for prefix cache * style: rustfmt --- src-tauri/src/proxy/providers/transform.rs | 134 ++++++++++++--------- 1 file changed, 76 insertions(+), 58 deletions(-) diff --git a/src-tauri/src/proxy/providers/transform.rs b/src-tauri/src/proxy/providers/transform.rs index f3e33eaa..49a94a92 100644 --- a/src-tauri/src/proxy/providers/transform.rs +++ b/src-tauri/src/proxy/providers/transform.rs @@ -121,15 +121,20 @@ pub fn anthropic_to_openai_with_reasoning_content( messages.push(json!({"role": "system", "content": text})); } } else if let Some(arr) = system.as_array() { + // Merge the top-level system blocks into one message. Their content is + // fixed for the whole conversation, so this stays byte-stable across + // turns and does not disturb prefix caching. + let mut parts = Vec::new(); for msg in arr { if let Some(text) = msg.get("text").and_then(|t| t.as_str()) { - let Some(text) = sanitize_system_text(text) else { - continue; - }; - let system_message = json!({"role": "system", "content": text}); - messages.push(system_message); + if let Some(text) = sanitize_system_text(text) { + parts.push(text.into_owned()); + } } } + if !parts.is_empty() { + messages.push(json!({"role": "system", "content": parts.join("\n")})); + } } } @@ -145,7 +150,6 @@ pub fn anthropic_to_openai_with_reasoning_content( } } - normalize_openai_system_messages(&mut messages); result["messages"] = json!(messages); let model = body.get("model").and_then(|m| m.as_str()).unwrap_or(""); @@ -260,58 +264,6 @@ fn map_tool_choice_to_chat(tool_choice: &Value) -> Value { } } -fn normalize_openai_system_messages(messages: &mut Vec) { - let system_count = messages - .iter() - .filter(|message| message.get("role").and_then(|value| value.as_str()) == Some("system")) - .count(); - - if system_count == 0 { - return; - } - - if system_count == 1 { - if let Some(index) = messages.iter().position(|message| { - message.get("role").and_then(|value| value.as_str()) == Some("system") - }) { - if index > 0 { - let message = messages.remove(index); - messages.insert(0, message); - } - } - return; - } - - let mut parts = Vec::new(); - messages.retain(|message| { - if message.get("role").and_then(|value| value.as_str()) != Some("system") { - return true; - } - - match message.get("content") { - Some(Value::String(text)) if !text.is_empty() => parts.push(text.clone()), - Some(Value::Array(content_parts)) => { - let text = content_parts - .iter() - .filter_map(|part| part.get("text").and_then(|value| value.as_str())) - .collect::>() - .join("\n"); - if !text.is_empty() { - parts.push(text); - } - } - _ => {} - } - - false - }); - - if !parts.is_empty() { - let merged = json!({"role": "system", "content": parts.join("\n")}); - messages.insert(0, merged); - } -} - fn convert_message_to_openai( role: &str, content: Option<&Value>, @@ -1494,4 +1446,70 @@ mod tests { assert_eq!(msg["tool_calls"][0]["id"], "call_date"); assert_eq!(msg["tool_calls"][0]["function"]["name"], "get_date"); } + + #[test] + fn anthropic_to_openai_preserves_mid_conversation_system_in_place() { + // Claude Code injects a system message every turn (environment and + // system-reminder blocks). Hoisting or merging them into the head + // rewrites the prompt prefix each turn and defeats upstream prefix + // caching, so they must stay exactly where the client put them. + let input = json!({ + "model": "claude-3-sonnet", + "max_tokens": 1024, + "system": "You are Claude Code.", + "messages": [ + {"role": "user", "content": "Hello"}, + {"role": "system", "content": "# Environment\ncwd=/tmp"}, + {"role": "assistant", "content": "Hi there!"}, + {"role": "user", "content": "Continue"} + ] + }); + + let result = anthropic_to_openai(input, None).unwrap(); + let messages = result["messages"].as_array().unwrap(); + + assert_eq!(messages.len(), 5); + assert_eq!(messages[0]["role"], "system"); + assert_eq!(messages[0]["content"], "You are Claude Code."); + assert_eq!(messages[2]["role"], "system"); + assert_eq!(messages[2]["content"], "# Environment\ncwd=/tmp"); + } + + #[test] + fn anthropic_to_openai_keeps_prefix_stable_when_a_turn_is_appended() { + // The serialized messages of one turn must remain a prefix of the next + // turn; otherwise the upstream prompt cache can never hit. + let turn_one = json!({ + "model": "claude-3-sonnet", + "max_tokens": 1024, + "system": [{"type": "text", "text": "You are Claude Code."}], + "messages": [ + {"role": "user", "content": "Hello"}, + {"role": "system", "content": "# Environment\ncwd=/tmp"} + ] + }); + let turn_two = json!({ + "model": "claude-3-sonnet", + "max_tokens": 1024, + "system": [{"type": "text", "text": "You are Claude Code."}], + "messages": [ + {"role": "user", "content": "Hello"}, + {"role": "system", "content": "# Environment\ncwd=/tmp"}, + {"role": "assistant", "content": "Hi there!"}, + {"role": "user", "content": "Continue"}, + {"role": "system", "content": "# Environment\ncwd=/tmp"} + ] + }); + + let first = anthropic_to_openai(turn_one, None).unwrap(); + let second = anthropic_to_openai(turn_two, None).unwrap(); + let first_messages = first["messages"].as_array().unwrap(); + let second_messages = second["messages"].as_array().unwrap(); + + assert_eq!(second_messages.len(), 6); + assert_eq!( + &second_messages[..first_messages.len()], + &first_messages[..] + ); + } } From 12e4613e276ca94e3025a1d81c78d000688d497f Mon Sep 17 00:00:00 2001 From: LiBai <91311486+RGB-loop@users.noreply.github.com> Date: Thu, 5 Nov 2026 01:23:50 +0800 Subject: [PATCH 11/23] fix(codex): omit unsupported MCP type field from generated TOML (#512) Codex does not accept a `type` key on [mcp_servers.*] entries; it warns about it and fails under --strict-config. Codex infers the transport from `command`/`url`, and import_from_codex already infers `type` the same way when it is absent, so the field can be dropped from generated TOML without losing round-trip information. Closes #496 --- src-tauri/src/mcp.rs | 41 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/src-tauri/src/mcp.rs b/src-tauri/src/mcp.rs index 83329577..2b05c183 100644 --- a/src-tauri/src/mcp.rs +++ b/src-tauri/src/mcp.rs @@ -1105,7 +1105,8 @@ fn json_value_to_toml_item(value: &Value, field_name: &str) -> Option Result { @@ -1113,7 +1114,11 @@ fn json_server_to_toml_table(spec: &Value) -> Result let mut t = Table::new(); let typ = spec.get("type").and_then(|v| v.as_str()).unwrap_or("stdio"); - t["type"] = toml_edit::value(typ); + // Codex 的 `[mcp_servers.]` 不认识 `type` 字段:普通模式下会告警 + // "is ignored",`--strict-config` 下直接校验失败。传输方式由 Codex 根据 + // `command`(stdio)或 `url`(streamable HTTP)自行推断,导入侧 + // (`import_from_codex`)在缺少 `type` 时也按同样规则推断,因此这里不写出 + // `type`,只用它来决定写哪些核心字段。 // 定义核心字段(已在下方处理,跳过通用转换) let core_fields = match typ { @@ -1813,6 +1818,38 @@ mod codex_mcp_tests { assert_eq!(doc.to_string(), "mcp_servers = 42\n"); } + #[test] + fn codex_toml_omits_unsupported_type_field() { + // Codex rejects `mcp_servers..type` under `--strict-config` and warns + // about it otherwise; the transport is inferred from `command` / `url`. + for (spec, expect_command, expect_url) in [ + ( + json!({ "type": "stdio", "command": "npx", "args": ["-y", "x"] }), + true, + false, + ), + (json!({ "command": "npx" }), true, false), + ( + json!({ "type": "http", "url": "https://mcp.example.com/mcp" }), + false, + true, + ), + ( + json!({ "type": "sse", "url": "https://mcp.example.com/sse" }), + false, + true, + ), + ] { + let table = json_server_to_toml_table(&spec).expect("server table"); + assert!( + table.get("type").is_none(), + "`type` must not be written to Codex TOML for {spec}" + ); + assert_eq!(table.contains_key("command"), expect_command, "{spec}"); + assert_eq!(table.contains_key("url"), expect_url, "{spec}"); + } + } + #[test] fn http_headers_are_only_written_to_codex_http_headers() { let table = json_server_to_toml_table(&json!({ From 8a038881a04a6907341fd2d77f729807226057a6 Mon Sep 17 00:00:00 2001 From: SaladDay Date: Thu, 5 Nov 2026 12:59:43 +0800 Subject: [PATCH 12/23] fix(codex): bind managed ChatGPT accounts to official providers (#550) --- src-tauri/src/cli/codex_temp_launch.rs | 33 + src-tauri/src/cli/i18n.rs | 9 + src-tauri/src/cli/tui/form/provider_json.rs | 10 +- src-tauri/src/cli/tui/form/provider_state.rs | 4 +- .../cli/tui/form/provider_state_loading.rs | 6 + src-tauri/src/cli/tui/form/tests.rs | 30 + src-tauri/src/cli/tui/help.rs | 4 +- src-tauri/src/cli/tui/ui/forms/provider.rs | 8 +- src-tauri/src/cli/tui/ui/overlay/pickers.rs | 4 +- src-tauri/src/codex_config.rs | 5 + src-tauri/src/codex_config/managed_auth.rs | 513 +++++++++++++++ src-tauri/src/database/dao/providers.rs | 87 +++ .../src/proxy/providers/codex_oauth_auth.rs | 590 +++++++++++++++++- src-tauri/src/services/codex_oauth.rs | 120 +++- src-tauri/src/services/provider/codex.rs | 18 +- src-tauri/src/services/provider/codex_live.rs | 104 ++- .../provider/codex_openai_auth_tests.rs | 101 +++ src-tauri/src/services/provider/live.rs | 12 + src-tauri/src/services/provider/mod.rs | 10 + 19 files changed, 1646 insertions(+), 22 deletions(-) create mode 100644 src-tauri/src/codex_config/managed_auth.rs diff --git a/src-tauri/src/cli/codex_temp_launch.rs b/src-tauri/src/cli/codex_temp_launch.rs index 139e85d8..21824c2a 100644 --- a/src-tauri/src/cli/codex_temp_launch.rs +++ b/src-tauri/src/cli/codex_temp_launch.rs @@ -204,6 +204,18 @@ struct CodexLaunchSettings<'a> { } fn parse_launch_settings(provider: &Provider) -> Result, AppError> { + if provider + .meta + .as_ref() + .and_then(|meta| meta.managed_account_id_for("codex_oauth")) + .is_some() + { + return Err(AppError::localized( + "codex.temp_launch_managed_account", + "托管 ChatGPT 账号暂不支持独立目录启动。请先切换到该供应商,再运行 codex。", + "Managed ChatGPT accounts do not support isolated launches. Switch to this provider first, then run codex.", + )); + } let settings = provider.settings_config.as_object().ok_or_else(|| { AppError::localized( "codex.temp_launch_settings_not_object", @@ -623,4 +635,25 @@ mod tests { assert!(err.to_string().contains("codex")); } + #[test] + fn codex_managed_binding_rejects_isolated_launches_before_writing_files() { + let temp = TempDir::new().unwrap(); + let mut provider = provider_with("", Some(serde_json::json!({}))); + provider.meta = Some( + serde_json::from_value(serde_json::json!({ + "codexOfficial": true, "authBinding": { + "source": "managed_account", "authProvider": "codex_oauth", "accountId": "alice" + } + })) + .unwrap(), + ); + // Shared-session launches also call preview_launch_with before preparing their home. + let preview = + preview_launch_with(&provider, temp.path(), || Ok(PathBuf::from("/bin/true"))); + assert!(preview.err().unwrap().to_string().contains("codex")); + assert!( + prepare_launch_with(&provider, temp.path(), || Ok(PathBuf::from("/bin/true"))).is_err() + ); + assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 0); + } } diff --git a/src-tauri/src/cli/i18n.rs b/src-tauri/src/cli/i18n.rs index 165df494..4075070d 100644 --- a/src-tauri/src/cli/i18n.rs +++ b/src-tauri/src/cli/i18n.rs @@ -4946,6 +4946,15 @@ pub mod texts { } } + /// Native Codex keeps its own login when no managed account is bound. + pub fn tui_codex_native_login() -> &'static str { + if is_chinese() { + "使用 Codex 原生登录(不托管)" + } else { + "Use native Codex login (unmanaged)" + } + } + pub fn tui_managed_accounts_follow_default() -> &'static str { if is_chinese() { "跟随默认账号" diff --git a/src-tauri/src/cli/tui/form/provider_json.rs b/src-tauri/src/cli/tui/form/provider_json.rs index a192a4df..e2153fd0 100644 --- a/src-tauri/src/cli/tui/form/provider_json.rs +++ b/src-tauri/src/cli/tui/form/provider_json.rs @@ -406,7 +406,7 @@ impl ProviderAddFormState { let auth_value = settings_obj .entry("auth".to_string()) .or_insert_with(|| json!({})); - if !auth_value.is_object() { + if self.codex_oauth_account_id.is_some() || !auth_value.is_object() { *auth_value = json!({}); } settings_obj.remove("modelCatalog"); @@ -1065,7 +1065,9 @@ impl ProviderAddFormState { meta_obj.remove("localProxyRequestOverrides"); } - if is_codex_oauth { + if is_codex_oauth + || (self.is_codex_official_provider() && self.codex_oauth_account_id.is_some()) + { meta_obj.insert("providerType".to_string(), json!("codex_oauth")); meta_obj.insert( "authBinding".to_string(), @@ -1083,7 +1085,9 @@ impl ProviderAddFormState { auth_binding.remove("accountId"); } } - meta_obj.insert("codexFastMode".to_string(), json!(self.codex_fast_mode)); + if is_codex_oauth { + meta_obj.insert("codexFastMode".to_string(), json!(self.codex_fast_mode)); + } } else { if meta_obj .get("providerType") diff --git a/src-tauri/src/cli/tui/form/provider_state.rs b/src-tauri/src/cli/tui/form/provider_state.rs index 481d7f27..a6603dd5 100644 --- a/src-tauri/src/cli/tui/form/provider_state.rs +++ b/src-tauri/src/cli/tui/form/provider_state.rs @@ -516,7 +516,9 @@ impl ProviderAddFormState { } } AppType::Codex => { - if !self.is_codex_official_provider() { + if self.is_codex_official_provider() { + fields.push(ProviderAddField::CodexOAuthAccount); + } else { fields.push(ProviderAddField::CodexBaseUrl); fields.push(ProviderAddField::CodexApiKey); // No standalone model field (matches upstream): the model is diff --git a/src-tauri/src/cli/tui/form/provider_state_loading.rs b/src-tauri/src/cli/tui/form/provider_state_loading.rs index 0a1376d4..520b038e 100644 --- a/src-tauri/src/cli/tui/form/provider_state_loading.rs +++ b/src-tauri/src/cli/tui/form/provider_state_loading.rs @@ -30,6 +30,12 @@ pub(super) fn populate_form_from_provider( AppType::OpenClaw => populate_openclaw_form(form, provider), AppType::Pi => populate_openclaw_form(form, provider), } + if matches!(app_type, AppType::Codex) && provider.is_codex_official() { + form.codex_oauth_account_id = provider + .meta + .as_ref() + .and_then(|meta| meta.managed_account_id_for("codex_oauth")); + } form.is_full_url = form.supports_full_url_mode() && provider .meta diff --git a/src-tauri/src/cli/tui/form/tests.rs b/src-tauri/src/cli/tui/form/tests.rs index 4aa35f65..fe8cb04b 100644 --- a/src-tauri/src/cli/tui/form/tests.rs +++ b/src-tauri/src/cli/tui/form/tests.rs @@ -8149,3 +8149,33 @@ fn claude_editor_context_and_global_values_survive_json_and_template_changes() { .contains(&ProviderAddField::IncludeCommonConfig)); assert!(!form.fields().contains(&ProviderAddField::CommonSnippet)); } + +#[test] +fn codex_official_managed_account_binding_round_trip() { + let mut form = ProviderAddFormState::new(AppType::Codex); + form.apply_template( + template_index_by_label(AppType::Codex, "OpenAI Official"), + &[], + ); + assert!(form.fields().contains(&ProviderAddField::CodexOAuthAccount)); + assert!(!form.fields().contains(&ProviderAddField::CodexFastMode)); + assert!(form.to_provider_json_value()["meta"] + .get("authBinding") + .is_none()); + form.set_codex_oauth_account_id(Some("account-b".into())); + let value = form.to_provider_json_value(); + assert_eq!(value["meta"]["authBinding"]["accountId"], "account-b"); + assert_eq!(value["meta"]["providerType"], "codex_oauth"); + assert_eq!(value["settingsConfig"]["auth"], serde_json::json!({})); + let provider: crate::provider::Provider = serde_json::from_value(value).unwrap(); + let mut reopened = ProviderAddFormState::from_provider(AppType::Codex, &provider); + assert_eq!( + reopened.codex_oauth_account_id.as_deref(), + Some("account-b") + ); + reopened.set_codex_oauth_account_id(None); + let native = reopened.to_provider_json_value(); + assert!(native["meta"].get("authBinding").is_none()); + assert!(native["meta"].get("providerType").is_none()); + assert_eq!(native["meta"]["codexOfficial"], true); +} diff --git a/src-tauri/src/cli/tui/help.rs b/src-tauri/src/cli/tui/help.rs index 10cf71cb..58dad450 100644 --- a/src-tauri/src/cli/tui/help.rs +++ b/src-tauri/src/cli/tui/help.rs @@ -831,8 +831,8 @@ fn provider_field_help(app_type: AppType, field: ProviderAddField) -> HelpConten ProviderAddField::CodexOAuthAccount => HelpContent::new( texts::tui_label_chatgpt_account(), help_lines( - "绑定 ChatGPT/Codex 官方登录账号。官方账号可用于 Codex 插件、移动端远程操作等官方能力。订阅额度通过绑定账号的内置查询显示,无需余额模板;可在供应商列表按 r 刷新。", - "Binds an official ChatGPT/Codex account. Official login can keep Codex plugins, mobile remote control, and other official app features available. Subscription quota uses the bound account's built-in query without a balance template; press r in the provider list to refresh.", + "Codex 的 OpenAI Official 可选择托管账号,直接写入本机登录,无需开启路由;选择“不托管”则使用 Codex 原生登录。Claude 下的 Codex 模板仍通过本地代理使用绑定账号。官方账号可用于 Codex 插件、移动端远程操作等官方能力。订阅额度通过绑定账号的内置查询显示,无需余额模板;可在供应商列表按 r 刷新。", + "Codex OpenAI Official writes the selected managed account to the local login without requiring routing. Choose unmanaged to use the native Codex login. The Codex template under Claude uses the bound account through the local proxy. Official login can keep Codex plugins, mobile remote control, and other official app features available. Subscription quota uses the bound account's built-in query without a balance template; press r in the provider list to refresh.", ), ), ProviderAddField::CodexFastMode => HelpContent::new( diff --git a/src-tauri/src/cli/tui/ui/forms/provider.rs b/src-tauri/src/cli/tui/ui/forms/provider.rs index ce848c59..96b852d1 100644 --- a/src-tauri/src/cli/tui/ui/forms/provider.rs +++ b/src-tauri/src/cli/tui/ui/forms/provider.rs @@ -223,7 +223,13 @@ fn codex_oauth_account_for_display(provider: &super::form::ProviderAddFormState) .as_deref() .map(bounded_trimmed_text_for_display) .filter(|value| !value.is_empty()) - .unwrap_or_else(|| texts::tui_managed_accounts_follow_default().to_string()) + .unwrap_or_else(|| { + if provider.is_codex_official_provider() { + texts::tui_codex_native_login().to_string() + } else { + texts::tui_managed_accounts_follow_default().to_string() + } + }) } fn common_json_preview_value(app_type: &AppType, common_snippet: &str) -> Option { diff --git a/src-tauri/src/cli/tui/ui/overlay/pickers.rs b/src-tauri/src/cli/tui/ui/overlay/pickers.rs index f06a0073..04fb6607 100644 --- a/src-tauri/src/cli/tui/ui/overlay/pickers.rs +++ b/src-tauri/src/cli/tui/ui/overlay/pickers.rs @@ -807,7 +807,9 @@ pub(super) fn render_managed_account_picker_overlay( }; return Some(ListItem::new(Line::raw(format!( "{marker} {}", - texts::tui_managed_accounts_follow_default() + if matches!(app.form.as_ref(), Some(crate::cli::tui::form::FormState::ProviderAdd(provider)) if provider.is_codex_official_provider()) { + texts::tui_codex_native_login() + } else { texts::tui_managed_accounts_follow_default() } )))); } diff --git a/src-tauri/src/codex_config.rs b/src-tauri/src/codex_config.rs index a405585f..47026737 100644 --- a/src-tauri/src/codex_config.rs +++ b/src-tauri/src/codex_config.rs @@ -1,3 +1,6 @@ +mod managed_auth; +pub(crate) use managed_auth::*; + use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; use std::path::PathBuf; @@ -1204,6 +1207,7 @@ pub(crate) fn write_codex_provider_live_with_catalog_and_db( &prepared.config_text, &rows, None, + None, )?; plan.config.catalog = prepared.model_catalog.is_some(); crate::services::provider::codex_live::apply( @@ -1578,6 +1582,7 @@ pub fn write_codex_live_for_provider( config_text.unwrap_or_default(), &[], None, + None, )?; crate::services::provider::codex_live::apply(&plan, None, None) } diff --git a/src-tauri/src/codex_config/managed_auth.rs b/src-tauri/src/codex_config/managed_auth.rs new file mode 100644 index 00000000..e922e11a --- /dev/null +++ b/src-tauri/src/codex_config/managed_auth.rs @@ -0,0 +1,513 @@ +//! Managed Codex login ownership and refresh synchronization, aligned with upstream. +use super::*; +use serde::{Deserialize, Serialize}; + +const CODEX_MANAGED_OAUTH_LIVE_AUTH_MARKER_FILENAME: &str = "codex_managed_oauth_live_auth.json"; + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct CodexManagedOAuthLiveAuthMarker { + version: u32, + /// cc-switch 本地托管账号 ID,用于区分同一 ChatGPT workspace 下的登录。 + account_id: String, + /// 原生 auth.json 的 `tokens.account_id`,即 ChatGPT workspace ID。 + #[serde(default, skip_serializing_if = "Option::is_none")] + chatgpt_account_id: Option, + /// id_token 中跨刷新稳定的用户身份,防止同 workspace 的原生登录串号。 + #[serde(default, skip_serializing_if = "Option::is_none")] + user_identity: Option, +} + +pub(crate) struct CodexManagedLiveRefresh { + pub(crate) refresh_token: String, + pub(crate) id_token: Option, + pub(crate) last_refresh_ms: Option, + pub(crate) chatgpt_account_id: String, +} + +pub(crate) fn get_codex_managed_oauth_live_auth_marker_path() -> PathBuf { + crate::config::get_app_config_dir().join(CODEX_MANAGED_OAUTH_LIVE_AUTH_MARKER_FILENAME) +} + +fn extract_codex_managed_oauth_account_id(auth: &Value) -> Option { + let auth_obj = auth.as_object()?; + + if auth_obj.keys().any(|key| { + !matches!( + key.as_str(), + "auth_mode" | "OPENAI_API_KEY" | "tokens" | "last_refresh" + ) + }) { + return None; + } + + if auth.get("auth_mode").and_then(|value| value.as_str()) != Some("chatgpt") { + return None; + } + + let api_key_is_clearable = auth + .get("OPENAI_API_KEY") + .is_none_or(|value| value.is_null() || value.as_str() == Some("PROXY_MANAGED")); + if !api_key_is_clearable { + return None; + } + + let tokens = auth.get("tokens").and_then(|value| value.as_object())?; + + if tokens.keys().any(|key| { + !matches!( + key.as_str(), + "access_token" | "account_id" | "id_token" | "refresh_token" + ) + }) { + return None; + } + + let account_id = tokens + .get("account_id") + .and_then(|value| value.as_str()) + .map(str::trim) + .filter(|id| !id.is_empty())?; + tokens + .get("access_token") + .and_then(|value| value.as_str()) + .map(str::trim) + .filter(|token| !token.is_empty())?; + + Some(account_id.to_string()) +} + +pub fn codex_managed_oauth_auth_value( + account_id: &str, + access_token: &str, + id_token: Option<&str>, + refresh_token: &str, + last_refresh: &str, +) -> Value { + let mut tokens = serde_json::Map::new(); + if let Some(id_token) = id_token { + tokens.insert("id_token".to_string(), Value::String(id_token.to_string())); + } + tokens.insert( + "access_token".to_string(), + Value::String(access_token.to_string()), + ); + tokens.insert( + "refresh_token".to_string(), + Value::String(refresh_token.to_string()), + ); + tokens.insert( + "account_id".to_string(), + Value::String(account_id.to_string()), + ); + json!({ + "auth_mode": "chatgpt", + "OPENAI_API_KEY": null, + "tokens": Value::Object(tokens), + "last_refresh": last_refresh, + }) +} + +pub(crate) fn codex_managed_oauth_marker_bytes( + auth: &Value, + managed_account_id: &str, +) -> Result>, AppError> { + let managed_account_id = managed_account_id.trim(); + let Some(chatgpt_account_id) = extract_codex_managed_oauth_account_id(auth) else { + return Ok(None); + }; + if managed_account_id.is_empty() { + return Ok(None); + } + let user_identity = extract_codex_auth_user_identity(auth).ok_or_else(|| { + AppError::Message( + "Codex 托管 OAuth auth.json 的 id_token 缺少稳定用户身份,无法安全记录账号所有权" + .to_string(), + ) + })?; + let marker = CodexManagedOAuthLiveAuthMarker { + version: 3, + account_id: managed_account_id.to_string(), + chatgpt_account_id: Some(chatgpt_account_id), + user_identity: Some(user_identity), + }; + serde_json::to_vec_pretty(&marker) + .map(Some) + .map_err(|e| AppError::Message(format!("序列化 Codex 托管账号标记失败: {e}"))) +} + +pub fn record_codex_managed_oauth_live_auth( + auth: &Value, + managed_account_id: &str, +) -> Result<(), AppError> { + let managed_account_id = managed_account_id.trim(); + let Some(chatgpt_account_id) = extract_codex_managed_oauth_account_id(auth) else { + return Ok(()); + }; + if managed_account_id.is_empty() { + return Ok(()); + } + let user_identity = extract_codex_auth_user_identity(auth).ok_or_else(|| { + AppError::Message( + "Codex 托管 OAuth auth.json 的 id_token 缺少稳定用户身份,无法安全记录账号所有权" + .to_string(), + ) + })?; + + let marker = CodexManagedOAuthLiveAuthMarker { + version: 3, + account_id: managed_account_id.to_string(), + chatgpt_account_id: Some(chatgpt_account_id), + user_identity: Some(user_identity), + }; + crate::config::write_json_file(&get_codex_managed_oauth_live_auth_marker_path(), &marker) +} + +fn migrate_legacy_codex_managed_oauth_live_auth_marker( + auth: &Value, + managed_account_id: &str, + managed_id_token: Option<&str>, +) -> Result<(), AppError> { + let marker_path = get_codex_managed_oauth_live_auth_marker_path(); + if !marker_path.exists() { + return Ok(()); + } + let marker: CodexManagedOAuthLiveAuthMarker = read_json_file(&marker_path)?; + if !matches!(marker.version, 1 | 2) || marker.account_id != managed_account_id { + return Ok(()); + } + + let auth_account_id = extract_codex_managed_oauth_account_id(auth); + let auth_user_identity = extract_codex_auth_user_identity(auth); + let managed_user_identity = managed_id_token.and_then(extract_codex_id_token_user_identity); + if auth_account_id.as_deref() != Some(managed_account_id) + || auth_user_identity.as_deref() != managed_user_identity.as_deref() + || managed_user_identity.is_none() + { + return Err(AppError::Message(format!( + "旧版 Codex OAuth 账号 {managed_account_id} 无法通过稳定用户身份确认磁盘凭据所有权;为避免覆盖或串用 auth.json,本次操作已取消,请在认证中心重新登录该账号" + ))); + } + + record_codex_managed_oauth_live_auth(auth, managed_account_id) +} + +pub fn codex_auth_matches_recorded_managed_oauth( + auth: &Value, + account_id: &str, +) -> Result { + let account_id = account_id.trim(); + if account_id.is_empty() { + return Ok(false); + } + + let Some(auth_account_id) = extract_codex_managed_oauth_account_id(auth) else { + return Ok(false); + }; + let auth_user_identity = extract_codex_auth_user_identity(auth); + let marker_path = get_codex_managed_oauth_live_auth_marker_path(); + // No marker is the normal state for a native ChatGPT login (no managed + // account ever wrote auth.json, or it was cleaned up when switching away); + // only a marker that exists but cannot be read is worth a warning. + if !marker_path.exists() { + return Ok(false); + } + let marker: CodexManagedOAuthLiveAuthMarker = match read_json_file(&marker_path) { + Ok(marker) => marker, + Err(err) => { + log::warn!( + "Failed to read Codex managed OAuth auth marker at {}: {err}", + marker_path.display() + ); + return Ok(false); + } + }; + + // v1/v2 markers do not carry a stable user identity. Since multiple users + // can share one workspace, those markers cannot safely authorize adopting + // or deleting credentials. The next explicit activation replaces them + // with a v3 marker. + Ok(marker.account_id == account_id + && match marker.version { + 3 => { + marker.chatgpt_account_id.as_deref() == Some(auth_account_id.as_str()) + && marker + .user_identity + .as_deref() + .is_some_and(|identity| auth_user_identity.as_deref() == Some(identity)) + } + _ => false, + }) +} + +pub fn ensure_codex_live_auth_unchanged_for_managed_account( + account_id: &str, + expected_refresh_token: &str, +) -> Result<(), AppError> { + let auth_path = get_codex_auth_path(); + if !auth_path.exists() { + return Err(AppError::Message(format!( + "Codex CLI 账号 {account_id} 的 live auth 已在切换期间被移除,请重试" + ))); + } + let auth: Value = read_json_file(&auth_path)?; + let current_refresh_token = auth + .pointer("/tokens/refresh_token") + .and_then(Value::as_str) + .map(str::trim); + if !codex_live_auth_is_managed_chatgpt_login(&auth, account_id) + || current_refresh_token != Some(expected_refresh_token.trim()) + { + return Err(AppError::Message(format!( + "Codex CLI 账号 {account_id} 的 live 凭据在切换期间已刷新;为避免覆盖新 refresh token,本次操作已取消,请重试" + ))); + } + Ok(()) +} + +pub fn codex_live_auth_is_managed_chatgpt_login(auth: &Value, account_id: &str) -> bool { + codex_auth_matches_recorded_managed_oauth(auth, account_id).unwrap_or(false) +} + +pub fn read_codex_live_auth_refresh_for_account( + account_id: &str, +) -> Option<(String, Option, Option)> { + let account_id = account_id.trim(); + if account_id.is_empty() { + return None; + } + let auth_path = get_codex_auth_path(); + if !auth_path.exists() { + return None; + } + let auth: Value = read_json_file(&auth_path).ok()?; + // 仅在磁盘上确是「该 account_id 的 ChatGPT 登录」时才采纳其 refresh_token, + // 避免从非 chatgpt/异常 auth 里误取 token。 + if !codex_live_auth_is_managed_chatgpt_login(&auth, account_id) { + return None; + } + let tokens = auth.get("tokens")?.as_object()?; + let refresh_token = tokens.get("refresh_token")?.as_str()?.trim().to_string(); + if refresh_token.is_empty() { + return None; + } + let id_token = tokens + .get("id_token") + .and_then(|value| value.as_str()) + .map(|token| token.to_string()); + let last_refresh_ms = auth + .get("last_refresh") + .and_then(Value::as_str) + .and_then(|value| chrono::DateTime::parse_from_rfc3339(value).ok()) + .map(|value| value.timestamp_millis()); + Some((refresh_token, id_token, last_refresh_ms)) +} + +pub(crate) fn read_codex_live_auth_refresh_for_managed_account( + account_id: &str, + managed_id_token: Option<&str>, +) -> Result, AppError> { + let account_id = account_id.trim(); + if account_id.is_empty() || !get_codex_managed_oauth_live_auth_marker_path().exists() { + return Ok(None); + } + let auth_path = get_codex_auth_path(); + if !auth_path.exists() { + return Ok(None); + } + let auth: Value = read_json_file(&auth_path)?; + migrate_legacy_codex_managed_oauth_live_auth_marker(&auth, account_id, managed_id_token)?; + if !codex_auth_matches_recorded_managed_oauth(&auth, account_id)? { + return Ok(None); + } + let Some((refresh_token, id_token, last_refresh_ms)) = + read_codex_live_auth_refresh_for_account(account_id) + else { + return Ok(None); + }; + let chatgpt_account_id = extract_codex_managed_oauth_account_id(&auth) + .ok_or_else(|| AppError::Message("Codex live auth 缺少 workspace ID".to_string()))?; + Ok(Some(CodexManagedLiveRefresh { + refresh_token, + id_token, + last_refresh_ms, + chatgpt_account_id, + })) +} + +pub fn sync_codex_managed_oauth_live_auth_after_refresh( + account_id: &str, + expected_refresh_token: &str, + refreshed_auth: &Value, +) -> Result { + let account_id = account_id.trim(); + let expected_refresh_token = expected_refresh_token.trim(); + if account_id.is_empty() || expected_refresh_token.is_empty() { + return Ok(false); + } + + let auth_path = get_codex_auth_path(); + if !auth_path.exists() { + return Ok(false); + } + let current_auth: Value = read_json_file(&auth_path)?; + if !codex_live_auth_is_managed_chatgpt_login(¤t_auth, account_id) { + return Ok(false); + } + let current_refresh_token = current_auth + .pointer("/tokens/refresh_token") + .and_then(Value::as_str) + .map(str::trim); + if current_refresh_token != Some(expected_refresh_token) { + return Ok(false); + } + + let marker_path = get_codex_managed_oauth_live_auth_marker_path(); + let was_recorded_managed = marker_path.exists() + && codex_auth_matches_recorded_managed_oauth(¤t_auth, account_id)?; + + let bytes = serde_json::to_vec_pretty(refreshed_auth) + .map_err(|source| AppError::JsonSerialize { source })?; + crate::config::atomic_write_private(&auth_path, &bytes)?; + if was_recorded_managed { + record_codex_managed_oauth_live_auth(refreshed_auth, account_id)?; + } + Ok(true) +} + +pub(crate) fn prepare_codex_live_auth_for_managed_account_removal( + managed_account_id: &str, + managed_id_token: Option<&str>, +) -> Result<(), AppError> { + if !get_codex_managed_oauth_live_auth_marker_path().exists() { + return Ok(()); + } + let auth_path = get_codex_auth_path(); + if !auth_path.exists() { + return Ok(()); + } + let auth: Value = read_json_file(&auth_path)?; + migrate_legacy_codex_managed_oauth_live_auth_marker(&auth, managed_account_id, managed_id_token) +} + +pub(crate) fn clear_codex_managed_oauth_live_auth_marker_for_account( + account_id: &str, +) -> Result<(), AppError> { + let marker_path = get_codex_managed_oauth_live_auth_marker_path(); + if !marker_path.exists() { + return Ok(()); + } + let marker: CodexManagedOAuthLiveAuthMarker = match read_json_file(&marker_path) { + Ok(marker) => marker, + Err(error) => { + log::warn!( + "Failed to read Codex managed OAuth auth marker at {} while cleaning account {}: {error}", + marker_path.display(), + account_id + ); + // A malformed marker cannot establish ownership for any account + // and is unusable for rollback/synchronization; remove the stale + // bookkeeping file while leaving non-matching live auth untouched. + return delete_file(&marker_path); + } + }; + if marker.account_id == account_id.trim() { + delete_file(&marker_path)?; + } + Ok(()) +} + +pub fn clear_codex_live_auth_for_managed_account(account_id: &str) -> Result<(), AppError> { + if !get_codex_managed_oauth_live_auth_marker_path().exists() { + return Ok(()); + } + clear_codex_live_auth_for_managed_account_if_unchanged(account_id, None) +} + +pub fn clear_codex_live_auth_for_managed_account_if_unchanged( + account_id: &str, + expected_refresh_token: Option<&str>, +) -> Result<(), AppError> { + let auth_path = get_codex_auth_path(); + let mut removed_matching_auth = false; + if auth_path.exists() { + let auth: Value = read_json_file(&auth_path)?; + if codex_live_auth_is_managed_chatgpt_login(&auth, account_id) { + if let Some(expected_refresh_token) = expected_refresh_token { + let current_refresh_token = auth + .pointer("/tokens/refresh_token") + .and_then(Value::as_str) + .map(str::trim); + if current_refresh_token != Some(expected_refresh_token.trim()) { + return Err(AppError::Message(format!( + "Codex CLI 账号 {account_id} 的 live 凭据在切换期间已刷新;为避免删除新 refresh token,本次操作已取消,请重试" + ))); + } + } + delete_file(&auth_path)?; + removed_matching_auth = true; + } + } + + if removed_matching_auth { + // Once the matching live file is gone, any marker is stale regardless + // of version or parseability. + delete_file(&get_codex_managed_oauth_live_auth_marker_path())?; + } else { + clear_codex_managed_oauth_live_auth_marker_for_account(account_id)?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn managed_ownership_distinguishes_members_of_the_same_workspace() { + let temp = tempfile::tempdir().unwrap(); + let _env = crate::test_support::TestEnvGuard::isolated(temp.path()); + let auth = codex_managed_oauth_auth_value( + "workspace", + "access-a", + Some(&test_codex_id_token("alice")), + "refresh-a", + "2026-11-05T00:00:00Z", + ); + crate::config::write_json_file(&get_codex_auth_path(), &auth).unwrap(); + assert!(!codex_live_auth_is_managed_chatgpt_login(&auth, "local-a")); + record_codex_managed_oauth_live_auth(&auth, "local-a").unwrap(); + assert!(codex_live_auth_is_managed_chatgpt_login(&auth, "local-a")); + assert!(!codex_live_auth_is_managed_chatgpt_login(&auth, "local-b")); + let mut other_user = auth.clone(); + other_user["tokens"]["id_token"] = json!(test_codex_id_token("bob")); + assert!(!codex_live_auth_is_managed_chatgpt_login( + &other_user, + "local-a" + )); + let mut refreshed = auth.clone(); + refreshed["tokens"]["refresh_token"] = json!("refresh-b"); + assert!(!sync_codex_managed_oauth_live_auth_after_refresh( + "local-a", + "wrong-generation", + &refreshed + ) + .unwrap()); + assert_eq!( + read_json_file::(&get_codex_auth_path()).unwrap(), + auth + ); + assert!(sync_codex_managed_oauth_live_auth_after_refresh( + "local-a", + "refresh-a", + &refreshed + ) + .unwrap()); + assert_eq!( + read_json_file::(&get_codex_auth_path()).unwrap(), + refreshed + ); + assert!( + ensure_codex_live_auth_unchanged_for_managed_account("local-a", "refresh-a").is_err() + ); + } +} diff --git a/src-tauri/src/database/dao/providers.rs b/src-tauri/src/database/dao/providers.rs index 404aa1e9..958f90d5 100644 --- a/src-tauri/src/database/dao/providers.rs +++ b/src-tauri/src/database/dao/providers.rs @@ -12,6 +12,93 @@ use sha2::{Digest, Sha256}; use std::collections::{HashMap, HashSet}; impl Database { + pub(crate) fn unbind_codex_managed_accounts( + &self, + account_ids: &[String], + ) -> Result, AppError> { + if account_ids.is_empty() { + return Ok(Vec::new()); + } + let mut conn = lock_conn!(self.conn); + let tx = conn + .transaction() + .map_err(|e| AppError::Database(e.to_string()))?; + let rows = { + let mut stmt = tx + .prepare( + "SELECT id, meta, settings_config, category, + trim(json_extract(meta, '$.authBinding.accountId')) FROM providers + WHERE app_type = 'codex' + AND json_extract(meta, '$.authBinding.source') = 'managed_account' + AND json_extract(meta, '$.authBinding.authProvider') = 'codex_oauth' + ORDER BY id", + ) + .map_err(|e| AppError::Database(e.to_string()))?; + let rows = stmt + .query_map([], |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, String>(1)?, + row.get::<_, String>(2)?, + row.get::<_, Option>(3)?, + row.get::<_, Option>(4)?, + )) + }) + .map_err(|e| AppError::Database(e.to_string()))?; + rows.collect::, _>>() + .map_err(|e| AppError::Database(e.to_string()))? + }; + let mut affected = Vec::new(); + for (id, meta_text, settings_text, category, bound) in rows { + if !bound.is_some_and(|bound| account_ids.iter().any(|id| id.trim() == bound)) { + continue; + } + let parse_error = |error: serde_json::Error| { + AppError::Database(format!("供应商 {id} 配置无效: {error}")) + }; + let mut meta: serde_json::Value = + serde_json::from_str(&meta_text).map_err(parse_error)?; + let mut settings: serde_json::Value = + serde_json::from_str(&settings_text).map_err(parse_error)?; + let mut provider = Provider::with_id(id.clone(), String::new(), settings.clone(), None); + provider.category = category; + provider.meta = Some(serde_json::from_value(meta.clone()).map_err(parse_error)?); + if provider.category.is_none() && provider.is_codex_official() { + provider.category = Some("official".to_string()); + } + meta.as_object_mut() + .ok_or_else(|| AppError::Config(format!("供应商 {id} 的 meta 必须是对象")))? + .remove("authBinding"); + // The CLI uses providerType to opt into managed quota queries. An + // unbound official row must not start querying the default account. + if meta.get("providerType").and_then(serde_json::Value::as_str) == Some("codex_oauth") { + meta.as_object_mut() + .expect("validated metadata") + .remove("providerType"); + } + settings + .as_object_mut() + .ok_or_else(|| { + AppError::Config(format!("供应商 {id} 的 settings_config 必须是对象")) + })? + .insert("auth".to_string(), serde_json::json!({})); + tx.execute( + "UPDATE providers SET meta = ?1, settings_config = ?2, category = ?3 + WHERE app_type = 'codex' AND id = ?4", + params![ + meta.to_string(), + settings.to_string(), + provider.category, + id + ], + ) + .map_err(|e| AppError::Database(e.to_string()))?; + affected.push(id); + } + tx.commit().map_err(|e| AppError::Database(e.to_string()))?; + Ok(affected) + } + /// 获取指定应用类型的所有供应商 pub fn get_all_providers( &self, diff --git a/src-tauri/src/proxy/providers/codex_oauth_auth.rs b/src-tauri/src/proxy/providers/codex_oauth_auth.rs index d69d50c4..5f02100e 100644 --- a/src-tauri/src/proxy/providers/codex_oauth_auth.rs +++ b/src-tauri/src/proxy/providers/codex_oauth_auth.rs @@ -200,6 +200,62 @@ impl CachedAccessToken { } } +#[derive(Debug, Clone)] +enum RefreshTokenAdoptionMode { + /// Normal CLI synchronization: different token material must carry a + /// strictly newer live timestamp before it can replace manager state. + TimestampChecked, + /// The OAuth server has just rejected the manager refresh token. A + /// different same-account token observed on disk is therefore the only + /// viable recovery generation and may bypass timestamp ambiguity. + RejectedManagerToken, +} + +#[derive(Debug, Clone)] +enum RefreshTokenAdoptionOutcome { + /// The live and manager token material already describe the same + /// generation. Timestamp bookkeeping is persisted independently. + Synchronized, + /// Different live token material was accepted as the newer generation. + Adopted, + /// Different live token material carries a timestamp strictly older than + /// the manager generation and may therefore be overwritten or removed. + ProvablyOlder, + /// Different token material could not be ordered safely. Callers that are + /// about to overwrite/delete auth.json must abort instead of guessing. + Ambiguous, + /// The account is not owned by this manager. + NotManaged, +} + +#[derive(Debug, Clone)] +pub(crate) enum CodexLiveAuthSwitchGuard { + ExistingAccount(Option), + MissingAccount, +} + +#[derive(Debug, Clone)] +pub(crate) struct ManagedTokenBundle { + pub chatgpt_account_id: String, + pub access_token: String, + pub id_token: Option, + pub refresh_token: String, + /// access_token 的真实获取时间,RFC3339 纳秒精度 + `Z`(与原生 auth.json 的 + /// `last_refresh` 形状一致)。反映 token 何时真正刷新,而非写盘时刻。 + pub last_refresh: String, +} + +impl CodexLiveAuthSwitchGuard { + pub(crate) fn ensure_unchanged(&self, account_id: &str) -> Result<(), crate::error::AppError> { + if let Self::ExistingAccount(Some(token)) = self { + crate::codex_config::ensure_codex_live_auth_unchanged_for_managed_account( + account_id, token, + )?; + } + Ok(()) + } +} + /// 进行中的 Device Code 条目,带过期时间以便清理放弃的登录流程 #[derive(Debug, Clone)] struct PendingDeviceCode { @@ -710,6 +766,332 @@ impl CodexOAuthManager { Ok(self.resolve_valid_cached_token(account_id).await?.token) } + async fn read_managed_live_auth_refresh_for_account( + &self, + account_id: &str, + ) -> Result, Option)>, CodexOAuthError> { + let (managed_id_token, managed_workspace) = { + let accounts = self.accounts.read().await; + let account = accounts + .get(account_id) + .ok_or_else(|| CodexOAuthError::AccountNotFound(account_id.to_string()))?; + let workspace = account.chatgpt_account_id.clone().ok_or_else(|| { + CodexOAuthError::ParseError(format!( + "账号 {account_id} 缺少 workspace 身份,请重新认证" + )) + })?; + (account.id_token.clone(), workspace) + }; + let Some(live_refresh) = + crate::codex_config::read_codex_live_auth_refresh_for_managed_account( + account_id, + managed_id_token.as_deref(), + ) + .map_err(|error| CodexOAuthError::TokenFetchFailed(error.to_string()))? + else { + return Ok(None); + }; + + if managed_workspace != live_refresh.chatgpt_account_id { + return Err(CodexOAuthError::TokenFetchFailed(format!( + "Codex OAuth 账号 {account_id} 的 workspace 与磁盘凭据不一致,本次操作已取消" + ))); + } + Ok(Some(( + live_refresh.refresh_token, + live_refresh.id_token, + live_refresh.last_refresh_ms, + ))) + } + + pub(crate) async fn get_valid_token_bundle_for_account( + &self, + account_id: &str, + ) -> Result { + let _lifecycle = self.lifecycle_lock.read().await; + self.ensure_account_ready_for_use(account_id).await?; + let refresh_lock = self.get_refresh_lock(account_id).await; + let _refresh_guard = refresh_lock.lock().await; + + // Resolve and read every persistent token field while holding the same + // account generation lock. Otherwise an adoption between these reads + // can create an invalid A0 + R1/ID1 mixed bundle. + let cached = self + .resolve_valid_cached_token_under_lock(account_id) + .await?; + + // A managed bundle is about to overwrite auth.json. Re-read under the + // same manager generation lock after token resolution so an ambiguous + // same-account disk generation can never be hidden by a valid cached + // access token. Keeping this check after resolution also preserves the + // RefreshTokenInvalid recovery path: the server may disprove manager R0, + // force-adopt disk R1, and only then produce a safe bundle. + if let Some((live_refresh, live_id_token, live_last_refresh_ms)) = self + .read_managed_live_auth_refresh_for_account(account_id) + .await? + { + let outcome = self + .adopt_account_refresh_token_under_lock( + account_id, + live_refresh, + live_id_token, + live_last_refresh_ms, + RefreshTokenAdoptionMode::TimestampChecked, + ) + .await?; + match outcome { + RefreshTokenAdoptionOutcome::Synchronized + | RefreshTokenAdoptionOutcome::ProvablyOlder => {} + RefreshTokenAdoptionOutcome::Ambiguous => { + return Err(Self::ambiguous_live_refresh_error(account_id)); + } + RefreshTokenAdoptionOutcome::Adopted => { + return Err(CodexOAuthError::TokenFetchFailed(format!( + "Codex CLI 账号 {account_id} 的磁盘凭据在准备写入期间已刷新;为避免写入混合 token bundle,本次操作已取消,请重试" + ))); + } + RefreshTokenAdoptionOutcome::NotManaged => { + return Err(CodexOAuthError::AccountNotFound(account_id.to_string())); + } + } + } + let last_refresh = + chrono::DateTime::::from_timestamp_millis(cached.obtained_at_ms) + .unwrap_or_else(chrono::Utc::now) + .to_rfc3339_opts(chrono::SecondsFormat::Nanos, true); + let (chatgpt_account_id, id_token, refresh_token) = { + let accounts = self.accounts.read().await; + let account = accounts + .get(account_id) + .ok_or_else(|| CodexOAuthError::AccountNotFound(account_id.to_string()))?; + ( + account.chatgpt_account_id.clone().ok_or_else(|| { + CodexOAuthError::ParseError( + "账号缺少 chatgpt_account_id,请重新认证".to_string(), + ) + })?, + account.id_token.clone(), + account.refresh_token.clone(), + ) + }; + Ok(ManagedTokenBundle { + chatgpt_account_id, + access_token: cached.token, + id_token, + refresh_token, + last_refresh, + }) + } + + fn ambiguous_live_refresh_error(account_id: &str) -> CodexOAuthError { + CodexOAuthError::TokenFetchFailed(format!( + "Codex CLI 账号 {account_id} 的磁盘凭据已变化,但无法安全判断 refresh token 新旧;为避免覆盖或删除有效登录,本次操作已取消。请先在认证中心重新登录该账号;若仍失败,请移除后重新登录" + )) + } + + pub(crate) async fn prepare_live_auth_for_account_switch_away( + &self, + account_id: &str, + ) -> Result { + let _lifecycle = self.lifecycle_lock.read().await; + let refresh_lock = self.get_refresh_lock(account_id).await; + let _guard = refresh_lock.lock().await; + if !self.accounts.read().await.contains_key(account_id) { + self.ensure_account_absent_from_store(account_id).await?; + return Ok(CodexLiveAuthSwitchGuard::MissingAccount); + } + let Some((live_refresh, live_id_token, live_last_refresh_ms)) = self + .read_managed_live_auth_refresh_for_account(account_id) + .await? + else { + return Ok(CodexLiveAuthSwitchGuard::ExistingAccount(None)); + }; + + let outcome = self + .adopt_account_refresh_token_under_lock( + account_id, + live_refresh.clone(), + live_id_token, + live_last_refresh_ms, + RefreshTokenAdoptionMode::TimestampChecked, + ) + .await?; + + match outcome { + RefreshTokenAdoptionOutcome::Synchronized + | RefreshTokenAdoptionOutcome::Adopted + | RefreshTokenAdoptionOutcome::ProvablyOlder => Ok( + CodexLiveAuthSwitchGuard::ExistingAccount(Some(live_refresh)), + ), + RefreshTokenAdoptionOutcome::Ambiguous => { + Err(Self::ambiguous_live_refresh_error(account_id)) + } + RefreshTokenAdoptionOutcome::NotManaged => { + Err(CodexOAuthError::AccountNotFound(account_id.to_string())) + } + } + } + + async fn adopt_account_refresh_token_under_lock( + &self, + account_id: &str, + refresh_token: String, + id_token: Option, + last_refresh_ms: Option, + mode: RefreshTokenAdoptionMode, + ) -> Result { + let incoming_id_token = id_token.filter(|token| !token.trim().is_empty()); + let mut changed = false; + let mut material_replaced = false; + let outcome; + { + let mut accounts = self.accounts.write().await; + let Some(account) = accounts.get_mut(account_id) else { + // 不是本 manager 托管的账号:不接管、不落盘。 + return Ok(RefreshTokenAdoptionOutcome::NotManaged); + }; + + // A manager refresh may already have advanced the token generation + // while auth.json still contains the older one. Never roll that + // state back during the preflight/write double-build sequence. + let refresh_changed = account.refresh_token != refresh_token; + let id_token_changed = incoming_id_token + .as_ref() + .is_some_and(|token| account.id_token.as_deref() != Some(token.as_str())); + let material_changed = refresh_changed || id_token_changed; + let manager_was_undated = account.token_updated_at_ms <= 0; + // Once the manager has a dated generation, any different token + // material must carry a *strictly newer* live timestamp. Equality is + // ambiguous at millisecond precision and therefore cannot authorize + // replacing the manager generation either. Stores upgraded from + // before generation timestamps existed keep a different live + // generation ambiguous across retries; only matching material may + // establish a timestamp. The server-rejected mode is the sole + // exception because it has disproved the manager generation. + let observed_order = + last_refresh_ms.map(|observed| observed.cmp(&account.token_updated_at_ms)); + let should_adopt = material_changed + && (matches!(mode, RefreshTokenAdoptionMode::RejectedManagerToken) + || (!manager_was_undated + && matches!(observed_order, Some(std::cmp::Ordering::Greater)))); + + if !material_changed { + outcome = RefreshTokenAdoptionOutcome::Synchronized; + } else if should_adopt { + if refresh_changed { + account.refresh_token = refresh_token; + changed = true; + material_replaced = true; + } + if let Some(id_token) = incoming_id_token { + if account.id_token.as_deref() != Some(id_token.as_str()) { + account.id_token = Some(id_token); + changed = true; + material_replaced = true; + } + } + outcome = RefreshTokenAdoptionOutcome::Adopted; + } else if !manager_was_undated + && matches!(observed_order, Some(std::cmp::Ordering::Less)) + { + outcome = RefreshTokenAdoptionOutcome::ProvablyOlder; + } else { + outcome = RefreshTokenAdoptionOutcome::Ambiguous; + } + + if matches!(outcome, RefreshTokenAdoptionOutcome::Adopted) + && matches!(mode, RefreshTokenAdoptionMode::RejectedManagerToken) + { + let adopted_at = last_refresh_ms + .filter(|observed| *observed > account.token_updated_at_ms) + .unwrap_or_else(|| { + chrono::Utc::now() + .timestamp_millis() + .max(account.token_updated_at_ms.saturating_add(1)) + }); + if account.token_updated_at_ms != adopted_at { + account.token_updated_at_ms = adopted_at; + changed = true; + } + } else if matches!(outcome, RefreshTokenAdoptionOutcome::Adopted) { + if let Some(observed) = last_refresh_ms { + if account.token_updated_at_ms != observed { + account.token_updated_at_ms = observed; + changed = true; + } + } + } else if matches!(outcome, RefreshTokenAdoptionOutcome::Synchronized) { + if manager_was_undated { + // Matching material establishes one generation, so dating + // it cannot turn an unresolved R0/R1 conflict into a false + // "live is older" decision on the next retry. + account.token_updated_at_ms = last_refresh_ms + .filter(|observed| *observed > 0) + .unwrap_or_else(|| chrono::Utc::now().timestamp_millis()); + changed = true; + } else if let Some(observed) = last_refresh_ms { + if observed > account.token_updated_at_ms { + account.token_updated_at_ms = observed; + changed = true; + } + } + } + // 采纳了 CLI 轮换后的 refresh_token:与之配套的旧 access_token 可能已被 + // 服务端提前失效。在同一 accounts 写锁内(accounts -> access_tokens 顺序) + // 清缓存,避免释放锁后被快路径读到旧 token;下次按新 refresh_token 重取。 + if material_replaced { + self.access_tokens.write().await.remove(account_id); + } + } + if changed { + self.save_to_disk().await?; + } + Ok(outcome) + } + + async fn ensure_account_absent_from_store( + &self, + account_id: &str, + ) -> Result<(), CodexOAuthError> { + let _persist = self.storage_lock.lock().await; + if !self.storage_path.try_exists()? { + if self.accounts.read().await.is_empty() { + return Ok(()); + } + return Err(CodexOAuthError::TokenFetchFailed( + "Codex 账号存储缺失但内存中仍有账号,请重启应用后重试".to_string(), + )); + } + let raw: serde_json::Value = serde_json::from_str(&fs::read_to_string(&self.storage_path)?) + .map_err(|error| CodexOAuthError::ParseError(error.to_string()))?; + if !raw + .get("accounts") + .is_some_and(serde_json::Value::is_object) + { + return Err(CodexOAuthError::ParseError( + "Codex 账号存储缺少有效 accounts 字段".to_string(), + )); + } + let store: CodexOAuthStore = serde_json::from_value(raw) + .map_err(|error| CodexOAuthError::ParseError(error.to_string()))?; + if !matches!(store.version, 1 | 2) + || store + .accounts + .iter() + .any(|(key, account)| key.trim().is_empty() || key != &account.account_id) + { + return Err(CodexOAuthError::ParseError( + "Codex 账号存储版本或账号索引无效".to_string(), + )); + } + if store.accounts.contains_key(account_id) { + return Err(CodexOAuthError::TokenFetchFailed( + "Codex 账号仍在磁盘存储中,请重启应用后重试".to_string(), + )); + } + Ok(()) + } + async fn ensure_account_ready_for_use(&self, account_id: &str) -> Result<(), CodexOAuthError> { let accounts = self.accounts.read().await; let account = accounts @@ -770,6 +1152,23 @@ impl CodexOAuthManager { &self, account_id: &str, ) -> Result { + // Codex CLI may have advanced the shared refresh-token generation since + // this manager last used the account. Reload it under the same per-account + // lock before deciding whether a network refresh is necessary. + if let Some((live_refresh, live_id_token, live_last_refresh_ms)) = self + .read_managed_live_auth_refresh_for_account(account_id) + .await? + { + self.adopt_account_refresh_token_under_lock( + account_id, + live_refresh, + live_id_token, + live_last_refresh_ms, + RefreshTokenAdoptionMode::TimestampChecked, + ) + .await?; + } + // double-check(同样在 accounts 读锁下) { let accounts = self.accounts.read().await; @@ -784,7 +1183,7 @@ impl CodexOAuthManager { } } - let refresh_token = { + let mut refresh_token = { let accounts = self.accounts.read().await; accounts .get(account_id) @@ -792,13 +1191,41 @@ impl CodexOAuthManager { .ok_or_else(|| CodexOAuthError::AccountNotFound(account_id.to_string()))? }; - let new_tokens = self.refresh_with_token(&refresh_token).await?; + let new_tokens = match self.refresh_with_token(&refresh_token).await { + Err(CodexOAuthError::RefreshTokenInvalid) => { + // If Codex CLI refreshed between our pre-read and request, reload + // its newer generation and retry exactly once. Error-code handling + // includes OpenAI's `refresh_token_reused` response. + let Some((live_refresh, live_id_token, live_last_refresh_ms)) = self + .read_managed_live_auth_refresh_for_account(account_id) + .await? + .filter(|(token, _, _)| token.trim() != refresh_token.as_str()) + else { + return Err(CodexOAuthError::RefreshTokenInvalid); + }; + let adoption = self + .adopt_account_refresh_token_under_lock( + account_id, + live_refresh.clone(), + live_id_token, + live_last_refresh_ms, + RefreshTokenAdoptionMode::RejectedManagerToken, + ) + .await?; + if !matches!(adoption, RefreshTokenAdoptionOutcome::Adopted) { + return Err(CodexOAuthError::RefreshTokenInvalid); + } + refresh_token = live_refresh; + self.refresh_with_token(&refresh_token).await? + } + result => result?, + }; let obtained_at_ms = chrono::Utc::now().timestamp_millis(); // 如果服务端返回了新的 refresh_token 或 id_token,更新存储 let mut needs_save = false; - { + let (stored_refresh_token, stored_id_token, chatgpt_account_id) = { let mut accounts = self.accounts.write().await; let account = accounts .get_mut(account_id) @@ -830,16 +1257,49 @@ impl CodexOAuthManager { account.token_updated_at_ms = obtained_at_ms; needs_save = true; } + ( + account.refresh_token.clone(), + account.id_token.clone(), + account.chatgpt_account_id.clone(), + ) }; if needs_save { self.save_to_disk().await?; } + let chatgpt_account_id = chatgpt_account_id.ok_or_else(|| { + CodexOAuthError::ParseError( + "无法从刷新后的 token 中提取 chatgpt_account_id".to_string(), + ) + })?; + let cached = CachedAccessToken { token: new_tokens.access_token.clone(), expires_at_ms: compute_expires_at_ms(new_tokens.expires_in), obtained_at_ms, }; + let last_refresh = chrono::DateTime::::from_timestamp_millis(obtained_at_ms) + .unwrap_or_else(chrono::Utc::now) + .to_rfc3339_opts(chrono::SecondsFormat::Nanos, true); + let refreshed_auth = crate::codex_config::codex_managed_oauth_auth_value( + &chatgpt_account_id, + &cached.token, + stored_id_token.as_deref(), + &stored_refresh_token, + &last_refresh, + ); + if let Err(err) = crate::codex_config::sync_codex_managed_oauth_live_auth_after_refresh( + account_id, + &refresh_token, + &refreshed_auth, + ) { + // The manager token remains valid; a later provider write will + // retry the live synchronization without rolling it back. + log::warn!( + "[CodexOAuth] 同步刷新后的 Codex live auth 失败(account={account_id}): {err}" + ); + } + // 在 accounts 读锁下确认账号仍存在,再写缓存:与 remove/clear(持 accounts // 写锁并原子清缓存)互斥,杜绝把已删账号的 token 写回缓存。 { @@ -898,9 +1358,27 @@ impl CodexOAuthManager { // have been removed as one lifecycle transition. let _lifecycle = self.lifecycle_lock.write().await; - if !self.accounts.read().await.contains_key(account_id) { - return Err(CodexOAuthError::AccountNotFound(account_id.to_string())); - } + let managed_id_token = { + let accounts = self.accounts.read().await; + accounts + .get(account_id) + .ok_or_else(|| CodexOAuthError::AccountNotFound(account_id.to_string()))? + .id_token + .clone() + }; + + // Explicit Auth Center removal means credentials for this managed + // account must leave the machine. Content matching intentionally also + // claims a native `codex login` of the same account; that is the same + // account-scoped credential the user just chose to remove. + crate::codex_config::prepare_codex_live_auth_for_managed_account_removal( + account_id, + managed_id_token.as_deref(), + ) + .map_err(|error| CodexOAuthError::TokenFetchFailed(error.to_string()))?; + crate::codex_config::clear_codex_live_auth_for_managed_account(account_id) + .map_err(|error| CodexOAuthError::IoError(error.to_string()))?; + { // 在 accounts 写锁内原子清除该账号的 token 缓存(accounts -> access_tokens // 顺序),确保不存在「账号已删但缓存仍在」的窗口。 @@ -956,6 +1434,25 @@ impl CodexOAuthManager { // the clear has committed. let _lifecycle = self.lifecycle_lock.write().await; + let accounts_to_clear = self + .accounts + .read() + .await + .iter() + .map(|(account_id, account)| (account_id.clone(), account.id_token.clone())) + .collect::>(); + for (account_id, id_token) in &accounts_to_clear { + crate::codex_config::prepare_codex_live_auth_for_managed_account_removal( + account_id, + id_token.as_deref(), + ) + .map_err(|error| CodexOAuthError::TokenFetchFailed(error.to_string()))?; + } + for (account_id, _) in &accounts_to_clear { + crate::codex_config::clear_codex_live_auth_for_managed_account(account_id) + .map_err(|error| CodexOAuthError::IoError(error.to_string()))?; + } + // 与 save_to_disk 共用持久化锁:确保「清内存 + 删文件」相对于并发保存原子, // 不会被一个持有旧快照的 save 复活已清除的账号。 let _persist = self.storage_lock.lock().await; @@ -2595,3 +3092,84 @@ mod tests { assert_eq!(extract_refresh_error_code("not json"), None); } } + +#[cfg(test)] +mod managed_live_tests { + use super::*; + + #[test] + fn managed_bundle_and_switch_away_reconcile_cli_token_generations() { + let temp = tempfile::tempdir().unwrap(); + let _env = crate::test_support::TestEnvGuard::isolated(temp.path()); + let runtime = tokio::runtime::Runtime::new().unwrap(); + runtime.block_on(async { + let manager = CodexOAuthManager::new(temp.path().join("manager")); + manager + .add_test_account_with_user_identity("local", "access", "alice") + .await + .unwrap(); + let bundle = manager + .get_valid_token_bundle_for_account("local") + .await + .unwrap(); + let auth = crate::codex_config::codex_managed_oauth_auth_value( + &bundle.chatgpt_account_id, + &bundle.access_token, + bundle.id_token.as_deref(), + &bundle.refresh_token, + &bundle.last_refresh, + ); + crate::config::write_json_file(&crate::codex_config::get_codex_auth_path(), &auth) + .unwrap(); + crate::codex_config::record_codex_managed_oauth_live_auth(&auth, "local").unwrap(); + let mut rotated = auth.clone(); + rotated["tokens"]["refresh_token"] = serde_json::json!("cli-rotated"); + // An undated generation cannot authorize replacement or deletion. + rotated.as_object_mut().unwrap().remove("last_refresh"); + crate::config::write_json_file(&crate::codex_config::get_codex_auth_path(), &rotated) + .unwrap(); + assert!(manager + .get_valid_token_bundle_for_account("local") + .await + .is_err()); + assert!(manager + .prepare_live_auth_for_account_switch_away("local") + .await + .is_err()); + assert_eq!( + manager + .test_refresh_token_for_account("local") + .await + .as_deref(), + Some("test-refresh-token") + ); + rotated["last_refresh"] = + serde_json::json!((chrono::Utc::now() + chrono::Duration::seconds(5)).to_rfc3339()); + crate::config::write_json_file(&crate::codex_config::get_codex_auth_path(), &rotated) + .unwrap(); + let guard = manager + .prepare_live_auth_for_account_switch_away("local") + .await + .unwrap(); + guard.ensure_unchanged("local").unwrap(); + assert_eq!( + manager + .test_refresh_token_for_account("local") + .await + .as_deref(), + Some("cli-rotated") + ); + assert!(!manager.access_tokens.read().await.contains_key("local")); + manager.remove_account("local").await.unwrap(); + assert!(matches!( + manager + .prepare_live_auth_for_account_switch_away("local") + .await + .unwrap(), + CodexLiveAuthSwitchGuard::MissingAccount + )); + assert!(!crate::codex_config::get_codex_auth_path().exists()); + assert!(!crate::codex_config::get_codex_managed_oauth_live_auth_marker_path().exists()); + }); + } +} diff --git a/src-tauri/src/services/codex_oauth.rs b/src-tauri/src/services/codex_oauth.rs index 6b6df12e..0236c45b 100644 --- a/src-tauri/src/services/codex_oauth.rs +++ b/src-tauri/src/services/codex_oauth.rs @@ -156,7 +156,11 @@ impl CodexOAuthService { } pub async fn remove_account(account_id: &str) -> Result<(), CodexOAuthError> { - Self::manager().remove_account(account_id).await + let _guard = super::state_coordination::acquire_restore_mutation_guard() + .await + .map_err(CodexOAuthError::TokenFetchFailed)?; + Self::manager().remove_account(account_id).await?; + Self::unbind_deleted_accounts(&[account_id.to_string()]) } pub async fn set_default_account(account_id: &str) -> Result<(), CodexOAuthError> { @@ -164,7 +168,32 @@ impl CodexOAuthService { } pub async fn clear_auth() -> Result<(), CodexOAuthError> { - Self::manager().clear_auth().await + let _guard = super::state_coordination::acquire_restore_mutation_guard() + .await + .map_err(CodexOAuthError::TokenFetchFailed)?; + let manager = Self::manager(); + let accounts = manager + .list_accounts() + .await + .into_iter() + .map(|account| account.id) + .collect::>(); + manager.clear_auth().await?; + Self::unbind_deleted_accounts(&accounts) + } + + fn unbind_deleted_accounts(accounts: &[String]) -> Result<(), CodexOAuthError> { + if accounts.is_empty() { + return Ok(()); + } + crate::Database::init() + .and_then(|db| db.unbind_codex_managed_accounts(accounts)) + .map(|_| ()) + .map_err(|error| { + CodexOAuthError::TokenFetchFailed(format!( + "账号已删除,但 Codex 供应商解绑失败;请编辑供应商重新选择账号: {error}" + )) + }) } pub async fn get_status() -> CodexOAuthStatus { @@ -294,3 +323,90 @@ impl CodexOAuthService { .await } } + +#[cfg(test)] +mod managed_removal_tests { + use super::*; + use serde_json::json; + + #[test] + fn codex_removal_clears_owned_login_and_detaches_only_deleted_accounts() { + let temp = tempfile::tempdir().unwrap(); + let _env = crate::test_support::TestEnvGuard::isolated(temp.path()); + let runtime = tokio::runtime::Runtime::new().unwrap(); + let db = crate::Database::init().unwrap(); + let manager = CodexOAuthService::manager(); + for account in ["alice", "bob"] { + runtime + .block_on(manager.add_test_account_with_workspace_and_access_token( + account, + "workspace", + "access", + Some(&crate::codex_config::test_codex_id_token(account)), + )) + .unwrap(); + let provider = serde_json::from_value(json!({ + "id": account, "name": account, "category": "official", + "settingsConfig": {"auth": {}, "config": ""}, + "meta": {"codexOfficial": true, "providerType": "codex_oauth", "authBinding": { + "source": "managed_account", "authProvider": "codex_oauth", "accountId": account + }} + })) + .unwrap(); + db.save_provider("codex", &provider).unwrap(); + } + let alice = crate::codex_config::codex_managed_oauth_auth_value( + "workspace", + "access", + Some(&crate::codex_config::test_codex_id_token("alice")), + "refresh", + "2026-11-05T00:00:00Z", + ); + crate::config::write_json_file(&crate::codex_config::get_codex_auth_path(), &alice) + .unwrap(); + crate::codex_config::record_codex_managed_oauth_live_auth(&alice, "alice").unwrap(); + runtime + .block_on(CodexOAuthService::remove_account("alice")) + .unwrap(); + assert!(!crate::codex_config::get_codex_auth_path().exists()); + assert!(!crate::codex_config::get_codex_managed_oauth_live_auth_marker_path().exists()); + let rows = db.get_all_providers("codex").unwrap(); + assert!(rows["alice"].meta.as_ref().unwrap().auth_binding.is_none()); + assert!(!rows["alice"].is_codex_oauth()); + assert_eq!( + rows["bob"] + .meta + .as_ref() + .unwrap() + .managed_account_id_for("codex_oauth") + .as_deref(), + Some("bob") + ); + // A native login of another member in the same workspace survives logout. + let bob = crate::codex_config::codex_managed_oauth_auth_value( + "workspace", + "access", + Some(&crate::codex_config::test_codex_id_token("bob")), + "refresh", + "2026-11-05T00:00:00Z", + ); + crate::codex_config::record_codex_managed_oauth_live_auth(&bob, "bob").unwrap(); + crate::config::write_json_file(&crate::codex_config::get_codex_auth_path(), &alice) + .unwrap(); + runtime.block_on(CodexOAuthService::clear_auth()).unwrap(); + assert_eq!( + crate::config::read_json_file::( + &crate::codex_config::get_codex_auth_path() + ) + .unwrap(), + alice + ); + assert!(!crate::codex_config::get_codex_managed_oauth_live_auth_marker_path().exists()); + assert!(db.get_all_providers("codex").unwrap()["bob"] + .meta + .as_ref() + .unwrap() + .auth_binding + .is_none()); + } +} diff --git a/src-tauri/src/services/provider/codex.rs b/src-tauri/src/services/provider/codex.rs index a2a0872d..c327df6e 100644 --- a/src-tauri/src/services/provider/codex.rs +++ b/src-tauri/src/services/provider/codex.rs @@ -25,6 +25,15 @@ impl ProviderService { provider_id: &str, codex_home: &Path, ) -> Result<(), AppError> { + if db + .get_all_providers("codex")? + .get(provider_id) + .and_then(|provider| provider.meta.as_ref()) + .and_then(|meta| meta.managed_account_id_for("codex_oauth")) + .is_some() + { + return Ok(()); + } let auth_path = codex_home.join("auth.json"); let auth = if auth_path.exists() { read_json_file::(&auth_path)? @@ -513,7 +522,14 @@ impl ProviderService { clean_config_text }; - let mut plan = codex_live::prepare(is_official, auth, &live_config_text, rows, previous)?; + let mut plan = codex_live::prepare( + is_official, + auth, + &live_config_text, + rows, + previous, + Some(provider), + )?; plan.config.catalog = prepared_config.model_catalog.is_some(); Ok(PreparedLiveWrite::Codex { plan, diff --git a/src-tauri/src/services/provider/codex_live.rs b/src-tauri/src/services/provider/codex_live.rs index 85192a67..366fb6cf 100644 --- a/src-tauri/src/services/provider/codex_live.rs +++ b/src-tauri/src/services/provider/codex_live.rs @@ -1,8 +1,7 @@ use super::codex_login::*; use serde_json::Value; // CLI entry-point adapter for upstream codex_login, CodexProjection and the -// durable live-file engine. Upstream managed accounts and Stack are not exposed -// by this CLI. Credential decisions and file recovery use upstream code. +// durable live-file engine. Credential decisions and file recovery use upstream code. pub(crate) fn stash_path() -> std::path::PathBuf { crate::live::engine::DeviceStore::for_device().file(STASH_FILENAME) } @@ -31,6 +30,7 @@ pub(crate) fn prepare( config: &str, rows: &[crate::provider::Provider], previous: Option<&crate::provider::Provider>, + target: Option<&crate::provider::Provider>, ) -> Result { use super::ProviderService; use crate::codex_config::*; @@ -77,6 +77,62 @@ pub(crate) fn prepare( false, ), }; + // Resolve credentials before taking the live-file lock, as upstream does. + let account_id = |p: &crate::provider::Provider| { + p.meta + .as_ref() + .and_then(|meta| meta.managed_account_id_for("codex_oauth")) + }; + let target_account = target.filter(|_| official).and_then(account_id); + let outgoing_account = previous + .and_then(account_id) + .filter(|account| Some(account) != target_account.as_ref()); + let target_id = target_account.clone(); + let outgoing_id = outgoing_account.clone(); + let (target_auth, outgoing) = if target_id.is_some() || outgoing_id.is_some() { + std::thread::spawn(move || { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|error| crate::error::AppError::Message(error.to_string()))?; + runtime.block_on(async move { + let manager = crate::services::codex_oauth::CodexOAuthService::manager(); + let target_auth = if let Some(id) = target_id { + let bundle = manager + .get_valid_token_bundle_for_account(&id) + .await + .map_err(|error| crate::error::AppError::Message(error.to_string()))?; + Some(codex_managed_oauth_auth_value( + &bundle.chatgpt_account_id, + &bundle.access_token, + bundle.id_token.as_deref(), + &bundle.refresh_token, + &bundle.last_refresh, + )) + } else { + None + }; + let outgoing = if let Some(id) = outgoing_id { + Some( + manager + .prepare_live_auth_for_account_switch_away(&id) + .await + .map_err(|error| crate::error::AppError::Message(error.to_string()))?, + ) + } else { + None + }; + Ok::<_, crate::error::AppError>((target_auth, outgoing)) + }) + }) + .join() + .map_err(|_| crate::error::AppError::Message("Codex OAuth worker failed".into()))?? + } else { + (None, None) + }; + if let (Some(account), Some(guard)) = (&outgoing_account, &outgoing) { + guard.ensure_unchanged(account)?; + } let path = get_codex_auth_path(); let (auth_bytes, auth_readable) = match crate::live::engine::read_current(&path) { Ok(bytes) => (bytes, true), @@ -93,14 +149,24 @@ pub(crate) fn prepare( let proxy = !official && extract_codex_auth_api_key(row_auth).as_deref() == Some(crate::live::project::codex::PROXY_TOKEN_PLACEHOLDER); + use crate::proxy::providers::codex_oauth_auth::CodexLiveAuthSwitchGuard; + let outgoing_missing = matches!(outgoing, Some(CodexLiveAuthSwitchGuard::MissingAccount)); + let live_is_managed = live.as_ref().is_some_and(|auth| { + target_account + .iter() + .chain(outgoing_account.iter().filter(|_| !outgoing_missing)) + .any(|account| codex_live_auth_is_managed_chatgpt_login(auth, account)) + }); let mut plan = plan(AuthInput { live: live.as_ref(), - live_is_managed: false, + live_is_managed, third_party_keys: &keys, leaving_official: previous - .filter(|p| is_official(p)) + .filter(|p| is_official(p) && account_id(p).is_none()) .and_then(|p| p.settings_config.get("auth")), - target: if official { + target: if let Some(auth) = target_auth.as_ref() { + AuthTarget::Managed { auth } + } else if official { AuthTarget::Official { row_auth } } else if proxy { AuthTarget::ProxyThirdParty @@ -165,7 +231,26 @@ pub(crate) fn prepare( }) .map(|p| p.exclusive) .unwrap_or_default(); + let marker_pre = + crate::live::engine::read_current(&get_codex_managed_oauth_live_auth_marker_path())?; + let marker = match (&target_account, &target_auth, &plan.auth) { + (Some(account), Some(auth), Some(Some(written))) if auth == written => { + codex_managed_oauth_marker_bytes(auth, account)? + .map(crate::live::patch::WholeFile::Write) + } + _ if marker_pre.is_some() + && ((live_is_managed && plan.auth == Some(None)) || outgoing_missing) => + { + Some(crate::live::patch::WholeFile::Delete) + } + _ => None, + } + .map(|then| crate::live::patch::Guarded { + expected_pre: crate::live::engine::digest(marker_pre.as_deref()), + then, + }); Ok(Prepared { + marker, common: Default::default(), auth: plan, auth_pre, @@ -184,6 +269,7 @@ pub(crate) fn prepare( #[derive(Clone)] pub(crate) struct Prepared { + pub marker: Option, pub common: crate::live::patch::toml::TomlPatch, pub auth: AuthPlan, pub auth_pre: Option, @@ -268,6 +354,14 @@ pub(crate) fn apply( patch, }); } + if let Some(patch) = &prepared.marker { + changes.push(operation::FileChange { + file: LiveFile::private( + crate::codex_config::get_codex_managed_oauth_live_auth_marker_path(), + ), + patch, + }); + } operation::run( &store, &guard, diff --git a/src-tauri/src/services/provider/codex_openai_auth_tests.rs b/src-tauri/src/services/provider/codex_openai_auth_tests.rs index 03294226..79f59266 100644 --- a/src-tauri/src/services/provider/codex_openai_auth_tests.rs +++ b/src-tauri/src/services/provider/codex_openai_auth_tests.rs @@ -799,3 +799,104 @@ fn malformed_or_unreadable_auth_does_not_block_upstream_route_switching() { } } } + +fn managed_official(id: &str, account: Option<&str>) -> Provider { + serde_json::from_value(json!({ + "id": id, "name": id, "category": "official", + "settingsConfig": {"auth": {}, "config": ""}, + "meta": {"codexOfficial": true, "authBinding": account.map(|account| json!({ + "source": "managed_account", "authProvider": "codex_oauth", "accountId": account + }))} + })) + .unwrap() +} + +#[test] +#[serial] +fn codex_managed_accounts_switch_and_restore_native_login_without_storing_tokens() { + let temp = TempDir::new().unwrap(); + let _env = TestEnvGuard::isolated(temp.path()); + std::fs::create_dir_all(crate::codex_config::get_codex_config_dir()).unwrap(); + let runtime = tokio::runtime::Runtime::new().unwrap(); + let manager = crate::services::codex_oauth::CodexOAuthService::manager(); + for account in ["alice", "bob"] { + runtime + .block_on(manager.add_test_account_with_user_identity( + account, + &format!("access-{account}"), + account, + )) + .unwrap(); + } + let native = json!({"auth_mode": "chatgpt", "tokens": { + "account_id": "native", "id_token": crate::codex_config::test_codex_id_token("native"), + "access_token": "native-access", "refresh_token": "native-refresh" + }}); + write_json_file(&get_codex_auth_path(), &native).unwrap(); + let mut config = MultiAppConfig::default(); + config.ensure_app(&AppType::Codex); + for (id, account) in [ + ("native", None), + ("alice", Some("alice")), + ("bob", Some("bob")), + ] { + config + .get_manager_mut(&AppType::Codex) + .unwrap() + .providers + .insert(id.into(), managed_official(id, account)); + } + let state = state_from_config(config); + for account in ["alice", "bob", "alice"] { + ProviderService::switch(&state, AppType::Codex, account).unwrap(); + let live: Value = read_json_file(&get_codex_auth_path()).unwrap(); + assert_eq!(live["tokens"]["account_id"], account); + assert_eq!(live["tokens"]["access_token"], format!("access-{account}")); + assert!(live["tokens"]["refresh_token"].is_string()); + assert!(live["last_refresh"].is_string()); + assert!(crate::codex_config::codex_live_auth_is_managed_chatgpt_login(&live, account)); + assert_eq!( + state.db.get_all_providers("codex").unwrap()[account].settings_config["auth"], + json!({}) + ); + } + ProviderService::switch(&state, AppType::Codex, "native").unwrap(); + assert_eq!( + read_json_file::(&get_codex_auth_path()).unwrap(), + native + ); + // Upstream may keep the marker after restoring a different native login; + // ownership must no longer match the managed account. + assert!(!crate::codex_config::codex_live_auth_is_managed_chatgpt_login(&native, "alice")); +} + +#[test] +#[serial] +fn codex_managed_missing_target_leaves_login_and_selection_unchanged() { + let temp = TempDir::new().unwrap(); + let _env = TestEnvGuard::isolated(temp.path()); + std::fs::create_dir_all(crate::codex_config::get_codex_config_dir()).unwrap(); + let native = json!({"OPENAI_API_KEY": "native-key"}); + write_json_file(&get_codex_auth_path(), &native).unwrap(); + let mut config = MultiAppConfig::default(); + config.ensure_app(&AppType::Codex); + let providers = &mut config.get_manager_mut(&AppType::Codex).unwrap().providers; + providers.insert("native".into(), managed_official("native", None)); + providers.insert( + "missing".into(), + managed_official("missing", Some("removed")), + ); + let state = state_from_config(config); + ProviderService::switch(&state, AppType::Codex, "native").unwrap(); + let before = std::fs::read(get_codex_config_path()).unwrap(); + assert!(ProviderService::switch(&state, AppType::Codex, "missing").is_err()); + assert_eq!( + ProviderService::current(&state, AppType::Codex).unwrap(), + "native" + ); + assert_eq!( + read_json_file::(&get_codex_auth_path()).unwrap(), + native + ); + assert_eq!(std::fs::read(get_codex_config_path()).unwrap(), before); +} diff --git a/src-tauri/src/services/provider/live.rs b/src-tauri/src/services/provider/live.rs index c66e4d07..191f8944 100644 --- a/src-tauri/src/services/provider/live.rs +++ b/src-tauri/src/services/provider/live.rs @@ -20,6 +20,7 @@ pub(super) enum LiveSnapshot { auth_readable: bool, config: Option, stash: Option>, + marker: Option>, }, Gemini { env: Option>, @@ -52,8 +53,16 @@ impl LiveSnapshot { auth_readable, config, stash, + marker, } => { super::codex_live::restore_stash(stash.as_deref())?; + let marker_path = + crate::codex_config::get_codex_managed_oauth_live_auth_marker_path(); + match marker { + Some(bytes) => crate::config::atomic_write_private(&marker_path, bytes)?, + None if marker_path.exists() => delete_file(&marker_path)?, + None => {} + } let auth_path = get_codex_auth_path(); let config_path = get_codex_config_path(); if *auth_readable { @@ -151,6 +160,9 @@ pub(super) fn capture_live_snapshot(app_type: &AppType) -> Result { diff --git a/src-tauri/src/services/provider/mod.rs b/src-tauri/src/services/provider/mod.rs index 6c756b98..8c359ef6 100644 --- a/src-tauri/src/services/provider/mod.rs +++ b/src-tauri/src/services/provider/mod.rs @@ -1842,6 +1842,16 @@ impl ProviderService { provider: &mut Provider, common_config_snippet: Option<&str>, ) -> Result<(), AppError> { + if matches!(app_type, AppType::Codex) + && provider.is_codex_official() + && provider + .meta + .as_ref() + .and_then(|meta| meta.managed_account_id_for("codex_oauth")) + .is_some() + { + provider.settings_config["auth"] = json!({}); + } common_config::normalize_provider_common_config_for_storage( app_type, provider, From 0d95f37004e19c35de4c82ccda55afb52dd9006e Mon Sep 17 00:00:00 2001 From: LiBai <91311486+RGB-loop@users.noreply.github.com> Date: Thu, 5 Nov 2026 15:43:36 +0800 Subject: [PATCH 13/23] fix(proxy): emit response.incomplete for incomplete Codex responses (#551) Converted Anthropic Messages and Chat Completions streams already set response.status to "incomplete" (max_tokens, refusal, truncation, finish_reason=length), but always sent the terminal event as response.completed. Codex only reads incomplete_details from a response.incomplete event, so these responses were treated as normal completions. Pick the terminal event name from the response status, and let the usage parser, Codex OAuth SSE aggregation and Chat history recorder accept response.incomplete so usage and history are not lost. Fixes #546 Co-authored-by: Claude Opus 5.5 --- src-tauri/src/proxy/handlers.rs | 24 +++++++- .../src/proxy/providers/codex_chat_history.rs | 29 +++++++++- .../proxy/providers/codex_responses_sse.rs | 18 +++--- .../providers/streaming_codex_anthropic.rs | 49 +++++++++++++++- .../proxy/providers/streaming_codex_chat.rs | 58 ++++++++++++++----- src-tauri/src/proxy/usage/parser.rs | 34 +++++++++-- 6 files changed, 179 insertions(+), 33 deletions(-) diff --git a/src-tauri/src/proxy/handlers.rs b/src-tauri/src/proxy/handlers.rs index 60ca7fb1..424d515d 100644 --- a/src-tauri/src/proxy/handlers.rs +++ b/src-tauri/src/proxy/handlers.rs @@ -518,7 +518,7 @@ fn responses_sse_to_response_value(body: &str) -> Result { output_items.push(item.clone()); } } - "response.completed" => { + "response.completed" | "response.incomplete" => { completed_response = Some(data.get("response").cloned().unwrap_or(data)); } "response.failed" => { @@ -533,13 +533,15 @@ fn responses_sse_to_response_value(body: &str) -> Result { } let mut response = completed_response.ok_or_else(|| { - ProxyError::TransformError("No response.completed event in upstream SSE".to_string()) + ProxyError::TransformError( + "No response.completed or response.incomplete event in upstream SSE".to_string(), + ) })?; if !output_items.is_empty() { let Some(response) = response.as_object_mut() else { return Err(ProxyError::TransformError( - "response.completed payload is not an object".to_string(), + "terminal response payload is not an object".to_string(), )); }; response.insert("output".to_string(), Value::Array(output_items)); @@ -1912,4 +1914,20 @@ data: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"message\"}}\n assert!(responses_sse_to_response_value(sse).is_err()); } + + #[test] + fn responses_sse_to_response_value_accepts_incomplete_terminal_event() { + let sse = "event: response.output_item.done\n\ +data: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"partial\"}]}}\n\n\ +event: response.incomplete\n\ +data: {\"type\":\"response.incomplete\",\"response\":{\"id\":\"resp_inc\",\"status\":\"incomplete\",\"incomplete_details\":{\"reason\":\"max_output_tokens\"},\"output\":[],\"usage\":{\"input_tokens\":10,\"output_tokens\":2}}}\n\n"; + + let response = responses_sse_to_response_value(sse).unwrap(); + assert_eq!(response["status"], "incomplete"); + assert_eq!( + response["incomplete_details"]["reason"], + "max_output_tokens" + ); + assert_eq!(response["output"][0]["content"][0]["text"], "partial"); + } } diff --git a/src-tauri/src/proxy/providers/codex_chat_history.rs b/src-tauri/src/proxy/providers/codex_chat_history.rs index 256b697b..d5cbc5e4 100644 --- a/src-tauri/src/proxy/providers/codex_chat_history.rs +++ b/src-tauri/src/proxy/providers/codex_chat_history.rs @@ -432,7 +432,7 @@ async fn inspect_sse_block( .await; } } - Some("response.completed") => { + Some("response.completed" | "response.incomplete") => { if let Some(response) = value.get("response") { history.record_response(response).await; } @@ -806,4 +806,31 @@ mod tests { assert_eq!(history.enrich_request(&mut request).await, 1); assert_eq!(request["input"][0]["reasoning_content"], "Need a file."); } + + #[tokio::test] + async fn records_function_calls_from_incomplete_terminal_event() { + let history = Arc::new(CodexChatHistoryStore::default()); + let stream = futures::stream::iter(vec![Ok::<_, std::io::Error>(Bytes::from_static( + b"event: response.incomplete\ndata: {\"type\":\"response.incomplete\",\"response\":{\"id\":\"resp_incomplete\",\"status\":\"incomplete\",\"incomplete_details\":{\"reason\":\"max_output_tokens\"},\"output\":[{\"type\":\"function_call\",\"call_id\":\"call_inc\",\"name\":\"read_file\",\"arguments\":\"{}\",\"reasoning_content\":\"Need a file.\"}]}}\n\n", + ))]); + + let output = record_responses_sse_stream(stream, history.clone()) + .collect::>() + .await; + assert_eq!(output.len(), 1); + + let mut request = json!({ + "previous_response_id": "resp_incomplete", + "input": [ + { + "type": "function_call_output", + "call_id": "call_inc", + "output": "ok" + } + ] + }); + + assert_eq!(history.enrich_request(&mut request).await, 1); + assert_eq!(request["input"][0]["reasoning_content"], "Need a file."); + } } diff --git a/src-tauri/src/proxy/providers/codex_responses_sse.rs b/src-tauri/src/proxy/providers/codex_responses_sse.rs index d347e8a4..63bb4745 100644 --- a/src-tauri/src/proxy/providers/codex_responses_sse.rs +++ b/src-tauri/src/proxy/providers/codex_responses_sse.rs @@ -25,7 +25,7 @@ pub(crate) fn sse_event(event: &str, data: Value) -> Bytes { } // --------------------------------------------------------------------------- -// Response lifecycle (created / in_progress / completed / failed) +// Response lifecycle (created / in_progress / completed or incomplete / failed) // --------------------------------------------------------------------------- /// `response.created`, wrapping a caller-built `response` object (usage/created_at differ @@ -45,12 +45,16 @@ pub(crate) fn response_in_progress(response: &Value) -> Bytes { ) } -/// `response.completed`. -pub(crate) fn response_completed(response: &Value) -> Bytes { - sse_event( - "response.completed", - json!({ "type": "response.completed", "response": response }), - ) +/// Terminal event for a finished response: `response.incomplete` when its `status` is +/// `incomplete`, otherwise `response.completed`. Codex reads `incomplete_details` only +/// from a `response.incomplete` event and treats `response.completed` as success. +pub(crate) fn response_terminal(response: &Value) -> Bytes { + let event = if response.get("status").and_then(Value::as_str) == Some("incomplete") { + "response.incomplete" + } else { + "response.completed" + }; + sse_event(event, json!({ "type": event, "response": response })) } /// `response.failed`. diff --git a/src-tauri/src/proxy/providers/streaming_codex_anthropic.rs b/src-tauri/src/proxy/providers/streaming_codex_anthropic.rs index 1a4cd1d5..a7b78d5a 100644 --- a/src-tauri/src/proxy/providers/streaming_codex_anthropic.rs +++ b/src-tauri/src/proxy/providers/streaming_codex_anthropic.rs @@ -482,7 +482,7 @@ impl AnthropicToResponsesState { response["incomplete_details"] = json!({ "reason": reason }); } - events.push(sse::response_completed(&response)); + events.push(sse::response_terminal(&response)); self.completed = true; events } @@ -907,13 +907,58 @@ mod tests { ); let merged = run(input).await; assert!(merged.contains("\"delta\":\"partial\"")); - assert!(merged.contains("event: response.completed")); + assert!(merged.contains("event: response.incomplete")); + assert!(!merged.contains("event: response.completed")); // The top-level response is incomplete (message output items keep their own // "completed" status, but the response status must not be "completed"). assert!(merged.contains("\"status\":\"incomplete\"")); assert!(merged.contains("\"reason\":\"max_output_tokens\"")); } + #[tokio::test] + async fn test_incomplete_stop_reasons_emit_response_incomplete_event() { + // Codex reads incomplete_details only from a response.incomplete event. + for (stop_reason, reason) in [ + ("max_tokens", "max_output_tokens"), + ("refusal", "content_filter"), + ] { + let input = format!( + concat!( + "event: message_start\n", + "data: {{\"type\":\"message_start\",\"message\":{{\"id\":\"msg_inc\",\"model\":\"claude\",\"usage\":{{\"input_tokens\":4}}}}}}\n\n", + "event: content_block_start\n", + "data: {{\"type\":\"content_block_start\",\"index\":0,\"content_block\":{{\"type\":\"text\",\"text\":\"\"}}}}\n\n", + "event: content_block_delta\n", + "data: {{\"type\":\"content_block_delta\",\"index\":0,\"delta\":{{\"type\":\"text_delta\",\"text\":\"partial\"}}}}\n\n", + "event: content_block_stop\n", + "data: {{\"type\":\"content_block_stop\",\"index\":0}}\n\n", + "event: message_delta\n", + "data: {{\"type\":\"message_delta\",\"delta\":{{\"stop_reason\":\"{}\"}},\"usage\":{{\"output_tokens\":8}}}}\n\n", + "event: message_stop\n", + "data: {{\"type\":\"message_stop\"}}\n\n" + ), + stop_reason + ); + let merged = run(&input).await; + assert!( + merged.contains("event: response.incomplete"), + "{stop_reason}: {merged}" + ); + assert!( + merged.contains("\"type\":\"response.incomplete\""), + "{stop_reason}" + ); + assert!( + !merged.contains("event: response.completed"), + "{stop_reason}" + ); + assert!( + merged.contains(&format!("\"reason\":\"{reason}\"")), + "{stop_reason}" + ); + } + } + #[tokio::test] async fn test_truncated_tool_call_is_not_marked_completed() { let input = concat!( diff --git a/src-tauri/src/proxy/providers/streaming_codex_chat.rs b/src-tauri/src/proxy/providers/streaming_codex_chat.rs index fec31473..f3f94ccf 100644 --- a/src-tauri/src/proxy/providers/streaming_codex_chat.rs +++ b/src-tauri/src/proxy/providers/streaming_codex_chat.rs @@ -4,6 +4,7 @@ use super::{ codex_chat_common::{ extract_reasoning_field_text, split_leading_think_block, strip_leading_think_open_tag, }, + codex_responses_sse::response_terminal, transform_codex_chat::{ chat_usage_to_responses_usage, custom_tool_input_from_chat_arguments, response_id_from_chat_id, response_status_from_finish_reason, @@ -564,13 +565,7 @@ impl ChatToResponsesState { } else { let mut response = self.base_response("incomplete", output); response["incomplete_details"] = json!({ "reason": "stream_truncated" }); - events.push(sse_event( - "response.completed", - json!({ - "type": "response.completed", - "response": response - }), - )); + events.push(response_terminal(&response)); } self.completed = true; return events; @@ -582,13 +577,7 @@ impl ChatToResponsesState { response["incomplete_details"] = json!({ "reason": "max_output_tokens" }); } - events.push(sse_event( - "response.completed", - json!({ - "type": "response.completed", - "response": response - }), - )); + events.push(response_terminal(&response)); self.completed = true; events } @@ -1441,6 +1430,47 @@ mod tests { assert!(output.contains("\"query\":\"Gmail search emails\"")); } + #[tokio::test] + async fn length_finish_reason_emits_response_incomplete_event() { + let output = collect(vec![ + "data: {\"id\":\"chatcmpl_len\",\"model\":\"gpt-5.4\",\"choices\":[{\"delta\":{\"content\":\"partial\"},\"finish_reason\":\"length\"}]}\n\n", + "data: [DONE]\n\n", + ]) + .await; + let events = parse_sse_events(&output); + let terminal = events + .iter() + .find(|event| event["type"] == "response.incomplete") + .unwrap(); + + assert!(output.contains("event: response.incomplete")); + assert!(!output.contains("event: response.completed")); + assert_eq!(terminal["response"]["status"], "incomplete"); + assert_eq!( + terminal["response"]["incomplete_details"]["reason"], + "max_output_tokens" + ); + } + + #[tokio::test] + async fn truncated_stream_with_output_emits_response_incomplete_event() { + let output = collect(vec![ + "data: {\"id\":\"chatcmpl_cut\",\"model\":\"gpt-5.4\",\"choices\":[{\"delta\":{\"content\":\"partial\"}}]}\n\n", + ]) + .await; + let events = parse_sse_events(&output); + let terminal = events + .iter() + .find(|event| event["type"] == "response.incomplete") + .unwrap(); + + assert!(!output.contains("event: response.completed")); + assert_eq!( + terminal["response"]["incomplete_details"]["reason"], + "stream_truncated" + ); + } + #[tokio::test] async fn stream_error_emits_failed_without_completed() { let upstream = stream::iter(vec![Err::(std::io::Error::other( diff --git a/src-tauri/src/proxy/usage/parser.rs b/src-tauri/src/proxy/usage/parser.rs index b78cce10..46f721fd 100644 --- a/src-tauri/src/proxy/usage/parser.rs +++ b/src-tauri/src/proxy/usage/parser.rs @@ -532,15 +532,15 @@ impl TokenUsage { for event in events { if let Some(event_type) = event.get("type").and_then(|v| v.as_str()) { log::debug!("[Codex] 事件类型: {event_type}"); - if event_type == "response.completed" { + if matches!(event_type, "response.completed" | "response.incomplete") { if let Some(response) = event.get("response") { - log::debug!("[Codex] 找到 response.completed 事件,解析 usage"); + log::debug!("[Codex] 找到 {event_type} 事件,解析 usage"); return Self::from_codex_response_adjusted(response); } } } } - log::debug!("[Codex] 未找到 response.completed 事件"); + log::debug!("[Codex] 未找到 response.completed/response.incomplete 事件"); None } @@ -572,12 +572,12 @@ impl TokenUsage { pub fn from_codex_stream_events_auto(events: &[Value]) -> Option { log::debug!("[Codex] 智能解析流式事件,共 {} 个事件", events.len()); - // 先尝试 Codex Responses API 格式 (response.completed 事件) + // 先尝试 Codex Responses API 格式 (response.completed / response.incomplete 事件) for event in events { if let Some(event_type) = event.get("type").and_then(|v| v.as_str()) { - if event_type == "response.completed" { + if matches!(event_type, "response.completed" | "response.incomplete") { if let Some(response) = event.get("response") { - log::debug!("[Codex] 找到 response.completed 事件"); + log::debug!("[Codex] 找到 {event_type} 事件"); return Self::from_codex_response_auto(response); } } @@ -1233,6 +1233,28 @@ mod tests { assert_eq!(usage.model, Some("o3".to_string())); } + #[test] + fn test_codex_stream_events_read_usage_from_incomplete_event() { + let events = vec![json!({ + "type": "response.incomplete", + "response": { + "model": "o3", + "status": "incomplete", + "incomplete_details": { "reason": "max_output_tokens" }, + "usage": { + "input_tokens": 100, + "output_tokens": 8192 + } + } + })]; + + let usage = TokenUsage::from_codex_stream_events_auto(&events).unwrap(); + assert_eq!(usage.input_tokens, 100); + assert_eq!(usage.output_tokens, 8192); + let usage = TokenUsage::from_codex_stream_events(&events).unwrap(); + assert_eq!(usage.output_tokens, 8192); + } + #[test] fn test_codex_stream_events_auto_openai_format() { // OpenAI Chat Completions 流式格式 (最后一个 chunk 包含 usage) From 4dfe82f4b8794211375283f1e5e494a390181aa0 Mon Sep 17 00:00:00 2001 From: SaladDay Date: Thu, 5 Nov 2026 17:17:04 +0800 Subject: [PATCH 14/23] fix(sessions): allow Windows snapshot publication and cleanup (#552) * fix(sessions): close child lock handles before renaming cache directories * ci: use a block scalar for the Windows manifest test command --- .github/workflows/rust-ci.yml | 5 +- .../src/session_manager/paged_manifest.rs | 61 +++++++++++++++++-- 2 files changed, 58 insertions(+), 8 deletions(-) diff --git a/.github/workflows/rust-ci.yml b/.github/workflows/rust-ci.yml index eb37ac70..c9046576 100644 --- a/.github/workflows/rust-ci.yml +++ b/.github/workflows/rust-ci.yml @@ -82,11 +82,12 @@ jobs: cargo check --lib --no-default-features cargo test --lib --no-default-features --no-run - - name: Test Windows session cache file synchronization + - name: Test Windows session manifest publication and cleanup if: runner.os == 'Windows' working-directory: src-tauri # These tests use only their own temporary directories. - run: cargo test --lib --no-default-features session_manager::paged_manifest::tests::sync_private_file -- --nocapture + run: | + cargo test --lib --no-default-features session_manager::paged_manifest::tests:: -- --test-threads=1 --nocapture - name: Check default Windows CLI build if: runner.os == 'Windows' diff --git a/src-tauri/src/session_manager/paged_manifest.rs b/src-tauri/src/session_manager/paged_manifest.rs index 3f8c07eb..df2012f1 100644 --- a/src-tauri/src/session_manager/paged_manifest.rs +++ b/src-tauri/src/session_manager/paged_manifest.rs @@ -356,6 +356,9 @@ impl Drop for NamespaceCleanup { // namespace. Leave it intact; the next CLI startup will retry. return Ok(None); }; + // The root lock prevents new namespace leases until retirement is + // complete. Close the child handle before moving its directory on Windows. + drop(namespace_lock); let mut batch = None; let mut sequence = 0usize; quarantine_into_batch( @@ -364,7 +367,6 @@ impl Drop for NamespaceCleanup { &mut batch, &mut sequence, ); - drop(namespace_lock); if self.namespace_root.exists() { return Err(ManifestError::Corrupt( "namespace quarantine rename did not complete".to_string(), @@ -1238,8 +1240,9 @@ impl PagedManifestStore { let Ok(Some(lease)) = FileLock::try_exclusive(&lease_path) else { continue; }; - quarantine_into_batch(&from, &scope_dir, &mut batch, &mut sequence); + // New reader leases require the scope lock held above. drop(lease); + quarantine_into_batch(&from, &scope_dir, &mut batch, &mut sequence); } batch }; @@ -1705,6 +1708,9 @@ impl PagedManifestBuilder { } } + // The scope lock now protects staging from cleanup through pointer + // publication. Windows requires closing its child handles before rename. + self.owner_lock.take(); fs::rename(&self.staging_dir, &final_dir) .map_err(|error| ManifestError::io(&self.staging_dir, error))?; let mut pointer_updated = false; @@ -1737,7 +1743,6 @@ impl PagedManifestBuilder { let reader = match publication { Ok(reader) => reader, Err(error) => { - self.owner_lock.take(); if !pointer_updated { fs::remove_dir_all(&final_dir) .map_err(|cleanup| ManifestError::io(&final_dir, cleanup))?; @@ -1771,7 +1776,6 @@ impl PagedManifestBuilder { } reader }; - self.owner_lock.take(); self.store .collect_old_generations(&self.scope, &self.generation); Ok(PublishedManifest { @@ -2522,8 +2526,9 @@ fn cleanup_cli_namespaces_locked(cli_root: &Path, active_namespace: &str) -> Vec let lease_path = entry.path().join(NAMESPACE_LOCK_FILE); match FileLock::try_exclusive(&lease_path) { Ok(Some(lease)) => { - quarantine_into_batch(&entry.path(), cli_root, &mut batch, &mut sequence); + // The caller holds the root lock, excluding new namespace leases. drop(lease); + quarantine_into_batch(&entry.path(), cli_root, &mut batch, &mut sequence); } Ok(None) => {} Err(error) => log::debug!( @@ -2580,8 +2585,9 @@ fn cleanup_leased_namespaces_locked( let lease_path = entry.path().join(NAMESPACE_LOCK_FILE); match FileLock::try_exclusive(&lease_path) { Ok(Some(lease)) => { - quarantine_into_batch(&entry.path(), namespace_root, &mut batch, &mut sequence); + // The caller holds the root lock, excluding new namespace leases. drop(lease); + quarantine_into_batch(&entry.path(), namespace_root, &mut batch, &mut sequence); } Ok(None) => {} Err(error) => log::debug!( @@ -3545,6 +3551,19 @@ mod tests { let old_second = old_reader.load_page(1).expect("leased old page"); assert_eq!(old_second.rows.len(), 1); assert_eq!(old_second.generation, old_generation); + + drop(first_publication); + drop(old_reader); + let current = store.open_reader("claude").expect("current reader"); + store.collect_old_generations("claude", current.generation()); + assert!( + !store.generation_dir("claude", &old_generation).exists(), + "an old generation must be retired once its last reader releases it" + ); + assert_eq!( + current.load_page(0).expect("current page").rows[0].session_id, + "new-2" + ); } #[test] @@ -3809,6 +3828,36 @@ mod tests { ); } + #[test] + fn query_startup_cleans_only_unleased_namespaces() { + let temp = tempdir().expect("tempdir"); + let query_root = temp.path().join(QUERY_ROOT_DIR); + let abandoned_root = query_root.join("tui-abandoned"); + create_private_dir(&abandoned_root).expect("namespace"); + let lease = FileLock::shared(&abandoned_root.join(NAMESPACE_LOCK_FILE)).expect("lease"); + + let active = QueryManifestStore::open_at( + temp.path(), + &QueryManifestNamespace::for_test("tui-active"), + ) + .expect("active query store"); + assert!(abandoned_root.is_dir(), "a live lease must prevent cleanup"); + + // Model a crashed process: its lease is released without namespace cleanup. + drop(lease); + let _next = + QueryManifestStore::open_at(temp.path(), &QueryManifestNamespace::for_test("tui-next")) + .expect("next query store"); + assert!( + !abandoned_root.exists(), + "the abandoned namespace must retire" + ); + assert!( + active.inner.root.is_dir(), + "the active namespace must remain" + ); + } + #[test] fn open_is_fixed_cost_and_begin_build_cleans_only_unowned_artifacts() { let (temp, store) = test_store(); From dca66200e75fb5a8f8728b7959134842394df97c Mon Sep 17 00:00:00 2001 From: SaladDay Date: Thu, 12 Nov 2026 16:23:33 +0800 Subject: [PATCH 15/23] fix(claude): align proxy placeholder authentication with upstream (#556) --- src-tauri/src/live/project/claude.rs | 66 +++++++++++++++++++++------- src-tauri/src/services/proxy.rs | 62 +++++++++++++++++++++++--- src-tauri/tests/provider_commands.rs | 5 ++- src-tauri/tests/proxy_service.rs | 3 +- src-tauri/tests/proxy_takeover.rs | 14 ++++-- 5 files changed, 121 insertions(+), 29 deletions(-) diff --git a/src-tauri/src/live/project/claude.rs b/src-tauri/src/live/project/claude.rs index b289f270..e509e2b7 100644 --- a/src-tauri/src/live/project/claude.rs +++ b/src-tauri/src/live/project/claude.rs @@ -209,9 +209,12 @@ pub(crate) const ONE_M_MARKER_FOR_CLIENT: &str = "[1M]"; /// 代理契约里怎么写凭据。 #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ProxyAuth { - /// 路由供应商的行里有 `ANTHROPIC_AUTH_TOKEN` / `ANTHROPIC_API_KEY` 就沿用同名键写占位 - /// 符,都没有就写 `ANTHROPIC_AUTH_TOKEN`。 - FollowRow, + /// 非托管路由:本地跳(客户端 → 本地代理)只写 `ANTHROPIC_AUTH_TOKEN` 占位符。 + /// 行里即便配的是 `ANTHROPIC_API_KEY`(如 OpenCode Go 预设,供上游跳用 x-api-key), + /// 本地配置也不能带这个键——Claude Code 会把它当成用户自定义 API key 弹确认框, + /// 默认拒绝后就是未登录会话;两个键都写还会触发「Both ... set」警告(#4919)。 + /// 上游跳用哪种头由路由按行内凭据注入(proxy/providers/claude.rs),与占位符键名无关。 + AuthToken, /// 托管账号(Copilot、Codex、xAI):只写一个键,两个都在会触发 Claude Code 的 /// 「Both ANTHROPIC_AUTH_TOKEN and ANTHROPIC_API_KEY set」警告(#4919)。 /// - Codex 系要 `ANTHROPIC_AUTH_TOKEN`,缺了会弹登录提示(#3784); @@ -259,17 +262,8 @@ pub fn proxy_projection( } let placeholder = Value::String(PROXY_TOKEN_PLACEHOLDER.to_string()); match auth { - ProxyAuth::FollowRow => { - let mut wrote_any = false; - for key in ["ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY"] { - if route.env.contains_key(key) { - env.insert(key.to_string(), placeholder.clone()); - wrote_any = true; - } - } - if !wrote_any { - env.insert("ANTHROPIC_AUTH_TOKEN".to_string(), placeholder); - } + ProxyAuth::AuthToken => { + env.insert("ANTHROPIC_AUTH_TOKEN".to_string(), placeholder); } ProxyAuth::Managed { auth_token } => { let key = if auth_token { @@ -719,7 +713,7 @@ mod tests { let stacked = proxy_projection( &route, "http://127.0.0.1:15721", - ProxyAuth::FollowRow, + ProxyAuth::AuthToken, Some(StackRoleModel { id: "ccs-claude-z--glm-5.2[1M]", name: "GLM 5.2", @@ -746,11 +740,51 @@ mod tests { assert_eq!(env("ANTHROPIC_AUTH_TOKEN"), Some(PROXY_TOKEN_PLACEHOLDER)); // 路由模式照旧写 `claude-*` 别名和行里的子代理模型。 - let routed = proxy_projection(&route, "http://127.0.0.1:15721", ProxyAuth::FollowRow, None); + let routed = proxy_projection(&route, "http://127.0.0.1:15721", ProxyAuth::AuthToken, None); assert_eq!( routed.env["ANTHROPIC_DEFAULT_SONNET_MODEL"], "claude-sonnet-5[1M]" ); assert_eq!(routed.env["CLAUDE_CODE_SUBAGENT_MODEL"], "glm-4.7-air"); } + #[test] + fn route_mode_always_places_the_placeholder_in_auth_token() { + // #8104:行里只有 `ANTHROPIC_API_KEY`(如 OpenCode Go 预设,供上游跳用 + // x-api-key)时,本地占位符也不能落在这个键上——Claude Code 会把它当成 + // 用户自定义 API key 弹确认框,默认拒绝后就是未登录会话。上游跳用哪种 + // 头由路由按行内凭据注入,与占位符键名无关。 + let api_key_only = ClaudeProjection::of(&json!({ "env": { + "ANTHROPIC_BASE_URL": "https://opencode.ai/zen/go", + "ANTHROPIC_API_KEY": "sk-go" + }})); + let projected = proxy_projection( + &api_key_only, + "http://127.0.0.1:15721", + ProxyAuth::AuthToken, + None, + ); + assert_eq!( + projected.env["ANTHROPIC_AUTH_TOKEN"], + PROXY_TOKEN_PLACEHOLDER + ); + assert!( + !projected.env.contains_key("ANTHROPIC_API_KEY"), + "route mode must not present the placeholder as a custom API key" + ); + + // 两个键都在也不写 API_KEY:避开 Claude Code 的 + // 「Both ANTHROPIC_AUTH_TOKEN and ANTHROPIC_API_KEY set」警告(#4919)。 + let both = ClaudeProjection::of(&json!({ "env": { + "ANTHROPIC_BASE_URL": "https://relay.example", + "ANTHROPIC_AUTH_TOKEN": "sk-bearer", + "ANTHROPIC_API_KEY": "sk-x-api" + }})); + let projected = + proxy_projection(&both, "http://127.0.0.1:15721", ProxyAuth::AuthToken, None); + assert_eq!( + projected.env["ANTHROPIC_AUTH_TOKEN"], + PROXY_TOKEN_PLACEHOLDER + ); + assert!(!projected.env.contains_key("ANTHROPIC_API_KEY")); + } } diff --git a/src-tauri/src/services/proxy.rs b/src-tauri/src/services/proxy.rs index abcbc54f..8d4884b6 100644 --- a/src-tauri/src/services/proxy.rs +++ b/src-tauri/src/services/proxy.rs @@ -37,7 +37,7 @@ const PROXY_RUNTIME_SESSION_TOKEN_ENV_KEY: &str = "CC_SWITCH_PROXY_SESSION_TOKEN #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum ClaudeTakeoverAuthPolicy { - PreserveExistingOrAuthToken, + AuthToken, } #[derive(Debug, Clone, Copy, Default)] @@ -239,7 +239,7 @@ impl ProxyService { Self::apply_claude_takeover_fields_with_policy( config, proxy_url, - ClaudeTakeoverAuthPolicy::PreserveExistingOrAuthToken, + ClaudeTakeoverAuthPolicy::AuthToken, ); } @@ -256,7 +256,7 @@ impl ProxyService { auth_token: !provider.is_github_copilot() || !provider.claude_uses_api_key_field(), } } else { - ProxyAuth::FollowRow + ProxyAuth::AuthToken }; let target = proxy_projection( &ClaudeProjection::of(&provider.settings_config), @@ -276,7 +276,7 @@ impl ProxyService { proxy_projection, store_into_row, ClaudeProjection, ProxyAuth, }; let auth = match auth_policy { - ClaudeTakeoverAuthPolicy::PreserveExistingOrAuthToken => ProxyAuth::FollowRow, + ClaudeTakeoverAuthPolicy::AuthToken => ProxyAuth::AuthToken, }; let target = proxy_projection(&ClaudeProjection::of(config), proxy_url, auth, None); *config = store_into_row(config, &target); @@ -3342,7 +3342,7 @@ impl ProxyService { Self::apply_claude_takeover_fields_with_policy( live, proxy_url, - ClaudeTakeoverAuthPolicy::PreserveExistingOrAuthToken, + ClaudeTakeoverAuthPolicy::AuthToken, ); } } @@ -4367,7 +4367,7 @@ mod tests { } #[test] - fn copilot_claude_takeover_defaults_to_auth_token_placeholder() { + fn copilot_claude_takeover_defaults_to_auth_token_and_honors_explicit_api_key() { let mut provider = Provider::with_id( "copilot".to_string(), "GitHub Copilot".to_string(), @@ -4403,6 +4403,16 @@ mod tests { assert_env_str(env, "ANTHROPIC_AUTH_TOKEN", Some(PROXY_TOKEN_PLACEHOLDER)); assert_env_str(env, "OPENROUTER_API_KEY", Some("stale-openrouter-key")); assert_env_str(env, "OPENAI_API_KEY", Some("stale-openai-key")); + + provider.meta.as_mut().unwrap().api_key_field = Some("ANTHROPIC_API_KEY".into()); + ProxyService::apply_claude_takeover_fields_for_provider( + &mut live_config, + "http://127.0.0.1:15721", + &provider, + ); + let env = env_object(&live_config); + assert_env_str(env, "ANTHROPIC_API_KEY", Some(PROXY_TOKEN_PLACEHOLDER)); + assert_env_str(env, "ANTHROPIC_AUTH_TOKEN", None); } #[test] @@ -4616,6 +4626,43 @@ mod tests { assert_env_str(env, "CLAUDE_CODE_SUBAGENT_MODEL", Some("provider-subagent")); } + #[test] + fn normal_claude_takeover_keeps_api_key_rows_off_the_local_hop() { + // #8104:OpenCode Go 这类预设把凭据存在 `ANTHROPIC_API_KEY`(上游跳要 + // x-api-key),路由模式的本地占位符只能写 `ANTHROPIC_AUTH_TOKEN`; + // 残留的 `ANTHROPIC_API_KEY` 一并清掉,否则 Claude Code 弹自定义 key + // 确认框,默认拒绝后就是未登录会话。 + let provider = Provider::with_id( + "opencode-go".to_string(), + "OpenCode Go".to_string(), + json!({ + "env": { + "ANTHROPIC_BASE_URL": "https://opencode.ai/zen/go", + "ANTHROPIC_API_KEY": "sk-go" + } + }), + None, + ); + let mut live_config = json!({ + "env": { + "ANTHROPIC_BASE_URL": "https://stale.example.com", + "ANTHROPIC_API_KEY": "stale-key" + } + }); + ProxyService::apply_claude_takeover_fields_for_provider( + &mut live_config, + "http://127.0.0.1:15721", + &provider, + ); + + let env = live_config + .get("env") + .and_then(|value| value.as_object()) + .expect("env should exist"); + assert_env_str(env, "ANTHROPIC_AUTH_TOKEN", Some(PROXY_TOKEN_PLACEHOLDER)); + assert_env_str(env, "ANTHROPIC_API_KEY", None); + } + #[test] fn normal_claude_takeover_without_token_keeps_auth_token_fallback() { let mut live_config = json!({ @@ -9402,7 +9449,8 @@ requires_openai_auth = true "ANTHROPIC_BASE_URL", Some(format!("http://127.0.0.1:{preferred_port}").as_str()), ); - assert_env_str(env, "ANTHROPIC_API_KEY", Some(PROXY_TOKEN_PLACEHOLDER)); + assert_env_str(env, "ANTHROPIC_AUTH_TOKEN", Some(PROXY_TOKEN_PLACEHOLDER)); + assert_env_str(env, "ANTHROPIC_API_KEY", None); assert_env_str(env, "LOCAL_ONLY", Some("kept")); } diff --git a/src-tauri/tests/provider_commands.rs b/src-tauri/tests/provider_commands.rs index 49062575..63525155 100644 --- a/src-tauri/tests/provider_commands.rs +++ b/src-tauri/tests/provider_commands.rs @@ -1906,11 +1906,14 @@ async fn switch_provider_under_takeover_refreshes_claude_restore_backup_to_selec assert_eq!( live_during_takeover .get("env") - .and_then(|env| env.get("ANTHROPIC_API_KEY")) + .and_then(|env| env.get("ANTHROPIC_AUTH_TOKEN")) .and_then(|value| value.as_str()), Some("PROXY_MANAGED"), "provider switch under takeover should keep the managed placeholder in Claude live config" ); + assert!(live_during_takeover + .pointer("/env/ANTHROPIC_API_KEY") + .is_none()); let backup_after_switch = state .db diff --git a/src-tauri/tests/proxy_service.rs b/src-tauri/tests/proxy_service.rs index 64d89b70..a33a2ccd 100644 --- a/src-tauri/tests/proxy_service.rs +++ b/src-tauri/tests/proxy_service.rs @@ -1042,11 +1042,12 @@ async fn proxy_service_stop_preserves_takeover_state_until_explicit_restore() { assert_eq!( live_after_stop .get("env") - .and_then(|env| env.get("ANTHROPIC_API_KEY")) + .and_then(|env| env.get("ANTHROPIC_AUTH_TOKEN")) .and_then(|value| value.as_str()), Some("PROXY_MANAGED"), "stop should not restore the original Claude token" ); + assert!(live_after_stop.pointer("/env/ANTHROPIC_API_KEY").is_none()); state .proxy_service diff --git a/src-tauri/tests/proxy_takeover.rs b/src-tauri/tests/proxy_takeover.rs index 33c9ae5d..7eaff3c7 100644 --- a/src-tauri/tests/proxy_takeover.rs +++ b/src-tauri/tests/proxy_takeover.rs @@ -189,11 +189,12 @@ async fn manual_takeover_can_rewrite_and_restore_claude_live_config() { assert_eq!( taken_over .get("env") - .and_then(|env| env.get("ANTHROPIC_API_KEY")) + .and_then(|env| env.get("ANTHROPIC_AUTH_TOKEN")) .and_then(|value| value.as_str()), Some("PROXY_MANAGED"), "takeover should replace the live Claude token with a managed placeholder" ); + assert!(taken_over.pointer("/env/ANTHROPIC_API_KEY").is_none()); let app_proxy = db .get_proxy_config_for_app("claude") @@ -743,11 +744,12 @@ async fn disabling_managed_proxy_session_restores_current_app_takeover_state() { assert_eq!( taken_over .get("env") - .and_then(|env| env.get("ANTHROPIC_API_KEY")) + .and_then(|env| env.get("ANTHROPIC_AUTH_TOKEN")) .and_then(|value| value.as_str()), Some("PROXY_MANAGED"), "managed proxy start should rewrite Claude live config into takeover mode" ); + assert!(taken_over.pointer("/env/ANTHROPIC_API_KEY").is_none()); state .proxy_service @@ -825,11 +827,12 @@ async fn startup_recovery_skips_owned_managed_session_when_probe_is_unreachable( assert_eq!( taken_over .get("env") - .and_then(|env| env.get("ANTHROPIC_API_KEY")) + .and_then(|env| env.get("ANTHROPIC_AUTH_TOKEN")) .and_then(|value| value.as_str()), Some("PROXY_MANAGED"), "managed startup should place Claude in proxy takeover mode" ); + assert!(taken_over.pointer("/env/ANTHROPIC_API_KEY").is_none()); let runtime_session_raw = state .db @@ -880,11 +883,14 @@ async fn startup_recovery_skips_owned_managed_session_when_probe_is_unreachable( assert_eq!( live_after_restart .get("env") - .and_then(|env| env.get("ANTHROPIC_API_KEY")) + .and_then(|env| env.get("ANTHROPIC_AUTH_TOKEN")) .and_then(|value| value.as_str()), Some("PROXY_MANAGED"), "startup recovery must not restore live config while managed runtime still exists" ); + assert!(live_after_restart + .pointer("/env/ANTHROPIC_API_KEY") + .is_none()); assert!( recovered .db From 3fc71671bb75c5751d0f47dd922dd88556ef72e8 Mon Sep 17 00:00:00 2001 From: StanleyLei <72687968+stan-lei@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:23:01 +0800 Subject: [PATCH 16/23] =?UTF-8?q?fix(database):=20support=20upstream=20sch?= =?UTF-8?q?emas=2023=E2=80=9326=20for=20sync=20restore=20(#549)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(webdav): support upstream schemas 23 and 24 for WebDAV/S3 restore CLI v5.11.3 supports database schema 22 while the desktop app writes schema 24, so WebDAV/S3 restore rejects the snapshot in validate_sql_user_version_for_import. Align the fresh-table DDL and migrations with upstream v23/v24, switch the Claude cursor update to an upsert so parser_state is not reset, and extend tests and fixtures through schema 24. * fix(database): align upstream schema compatibility through v26 --------- Co-authored-by: saladday <1203511142@qq.com> --- CHANGELOG.md | 9 + docs/CHANGELOG.md | 9 + ...skills.sql => upstream_v26_mcp_skills.sql} | 11 +- src-tauri/src/database/mod.rs | 9 +- src-tauri/src/database/schema.rs | 92 +++++++++- src-tauri/src/database/tests.rs | 165 ++++++++++++++++-- src-tauri/src/services/session_usage.rs | 35 +++- src-tauri/src/services/sync_protocol.rs | 4 +- src-tauri/src/services/webdav_sync/mod.rs | 19 +- 9 files changed, 325 insertions(+), 28 deletions(-) rename src-tauri/src/database/fixtures/{upstream_v22_mcp_skills.sql => upstream_v26_mcp_skills.sql} (77%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2619acff..44217a29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed + +- **Database / Compatibility**: Support database schemas 23 through 26 from upstream, fixing WebDAV/S3 restore failures with `Remote database schema is too new (24); this app supports up to 22`. Align the migration steps, MCP/Skills enablement columns, and session-log parser state with the shared schema while preserving upstream flags and parser state through upgrades, edits, runtime cursor updates, and sync round-trips. + +### Upgrade notes + +- Databases newer than schema 26 are still rejected. After migrating to schema 26, older CLI versions (v5.11.3 and earlier) cannot open the upgraded database. +- This release adds database compatibility, not CLI management for Oh My Pi, DeepSeek Harness, GitHub Copilot CLI, or WorkBuddy. + ## [5.11.3] - 2026-10-22 ### Fixed diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 2619acff..44217a29 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -9,6 +9,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed + +- **Database / Compatibility**: Support database schemas 23 through 26 from upstream, fixing WebDAV/S3 restore failures with `Remote database schema is too new (24); this app supports up to 22`. Align the migration steps, MCP/Skills enablement columns, and session-log parser state with the shared schema while preserving upstream flags and parser state through upgrades, edits, runtime cursor updates, and sync round-trips. + +### Upgrade notes + +- Databases newer than schema 26 are still rejected. After migrating to schema 26, older CLI versions (v5.11.3 and earlier) cannot open the upgraded database. +- This release adds database compatibility, not CLI management for Oh My Pi, DeepSeek Harness, GitHub Copilot CLI, or WorkBuddy. + ## [5.11.3] - 2026-10-22 ### Fixed diff --git a/src-tauri/src/database/fixtures/upstream_v22_mcp_skills.sql b/src-tauri/src/database/fixtures/upstream_v26_mcp_skills.sql similarity index 77% rename from src-tauri/src/database/fixtures/upstream_v22_mcp_skills.sql rename to src-tauri/src/database/fixtures/upstream_v26_mcp_skills.sql index 21d93d5f..fb2a5b5e 100644 --- a/src-tauri/src/database/fixtures/upstream_v22_mcp_skills.sql +++ b/src-tauri/src/database/fixtures/upstream_v26_mcp_skills.sql @@ -1,5 +1,5 @@ -- MCP/Skills DDL from farion1231/cc-switch at --- e4873bc8aa2555225d4867ec2f04b1290f1d21d9 (schema 22). +-- cf341a8aebc4660782a6e7ce362e5fb16635f684 (schema 26). CREATE TABLE IF NOT EXISTS mcp_servers ( id TEXT PRIMARY KEY, name TEXT NOT NULL, server_config TEXT NOT NULL, description TEXT, homepage TEXT, docs TEXT, tags TEXT NOT NULL DEFAULT '[]', @@ -9,8 +9,12 @@ CREATE TABLE IF NOT EXISTS mcp_servers ( enabled_mcode BOOLEAN NOT NULL DEFAULT 0, enabled_agy BOOLEAN NOT NULL DEFAULT 0, enabled_kimi BOOLEAN NOT NULL DEFAULT 0, + enabled_dsh BOOLEAN NOT NULL DEFAULT 0, + enabled_copilot BOOLEAN NOT NULL DEFAULT 0, + enabled_workbuddy BOOLEAN NOT NULL DEFAULT 0, enabled_hermes BOOLEAN NOT NULL DEFAULT 0, - enabled_pi BOOLEAN NOT NULL DEFAULT 0 + enabled_pi BOOLEAN NOT NULL DEFAULT 0, + enabled_omp BOOLEAN NOT NULL DEFAULT 0 ); CREATE TABLE IF NOT EXISTS skills ( @@ -30,6 +34,9 @@ CREATE TABLE IF NOT EXISTS skills ( enabled_mcode BOOLEAN NOT NULL DEFAULT 0, enabled_agy BOOLEAN NOT NULL DEFAULT 0, enabled_kimi BOOLEAN NOT NULL DEFAULT 0, + enabled_dsh BOOLEAN NOT NULL DEFAULT 0, + enabled_copilot BOOLEAN NOT NULL DEFAULT 0, + enabled_workbuddy BOOLEAN NOT NULL DEFAULT 0, enabled_hermes BOOLEAN NOT NULL DEFAULT 0, installed_at INTEGER NOT NULL DEFAULT 0, content_hash TEXT, diff --git a/src-tauri/src/database/mod.rs b/src-tauri/src/database/mod.rs index a02ba53b..0663cfb3 100644 --- a/src-tauri/src/database/mod.rs +++ b/src-tauri/src/database/mod.rs @@ -57,10 +57,11 @@ const USAGE_MAINTENANCE_INTERVAL_SECS: u64 = 24 * 60 * 60; /// 当前 Schema 版本号 /// 每次修改表结构时递增,并在 schema.rs 中添加相应的迁移逻辑 /// -/// 注意:本库 schema 与上游项目同步(WebDAV 亦会整库同步),本仓库不得自行 -/// 加表/加列或提升版本号;本地新增的持久化需求一律放独立 sidecar 存储 -/// (如 session_manager::scan_cache_store)。 -pub(crate) const SCHEMA_VERSION: i32 = 22; +/// 注意:本库 schema 与上游项目保持一致(WebDAV 亦会整库同步),只跟随上游 +/// 已有的迁移推进版本(当前 v26), +/// 本仓库不得自行加表/加列或提升版本号;本地新增的持久化需求一律放独立 +/// sidecar 存储(如 session_manager::scan_cache_store)。 +pub(crate) const SCHEMA_VERSION: i32 = 26; fn database_open_flags() -> OpenFlags { OpenFlags::SQLITE_OPEN_READ_WRITE diff --git a/src-tauri/src/database/schema.rs b/src-tauri/src/database/schema.rs index 56cce7b3..176ea4bd 100644 --- a/src-tauri/src/database/schema.rs +++ b/src-tauri/src/database/schema.rs @@ -63,8 +63,12 @@ impl Database { enabled_mcode BOOLEAN NOT NULL DEFAULT 0, enabled_agy BOOLEAN NOT NULL DEFAULT 0, enabled_kimi BOOLEAN NOT NULL DEFAULT 0, + enabled_dsh BOOLEAN NOT NULL DEFAULT 0, + enabled_copilot BOOLEAN NOT NULL DEFAULT 0, + enabled_workbuddy BOOLEAN NOT NULL DEFAULT 0, enabled_hermes BOOLEAN NOT NULL DEFAULT 0, - enabled_pi BOOLEAN NOT NULL DEFAULT 0 + enabled_pi BOOLEAN NOT NULL DEFAULT 0, + enabled_omp BOOLEAN NOT NULL DEFAULT 0 )", [], ) @@ -96,6 +100,9 @@ impl Database { enabled_mcode BOOLEAN NOT NULL DEFAULT 0, enabled_agy BOOLEAN NOT NULL DEFAULT 0, enabled_kimi BOOLEAN NOT NULL DEFAULT 0, + enabled_dsh BOOLEAN NOT NULL DEFAULT 0, + enabled_copilot BOOLEAN NOT NULL DEFAULT 0, + enabled_workbuddy BOOLEAN NOT NULL DEFAULT 0, enabled_hermes BOOLEAN NOT NULL DEFAULT 0, installed_at INTEGER NOT NULL DEFAULT 0, content_hash TEXT, @@ -325,12 +332,16 @@ impl Database { last_line_offset INTEGER NOT NULL DEFAULT 0, last_synced_at INTEGER NOT NULL, last_byte_offset INTEGER, - last_tail_fingerprint INTEGER + last_tail_fingerprint INTEGER, + parser_state TEXT )", [], ) .map_err(|e| AppError::Database(e.to_string()))?; + // 修复跑过未发布开发版 v24 的库:parser_state 随 v24 定稿,不单独 bump 版本 + Self::add_column_if_missing(conn, "session_log_sync", "parser_state", "TEXT")?; + // Session detail rows are pruned after rollup, so request IDs needed // for fork/rewrite deduplication live in a compact durable ledger. // The CLI does not consume Pi sessions yet, but this table must match @@ -588,6 +599,83 @@ impl Database { } Self::set_user_version(conn, 22)?; } + 22 => { + // Oh My Pi:只有 MCP 存开关;Skills 的启用状态按原生目录现算(同 Pi)。 + if Self::table_exists(conn, "mcp_servers")? { + Self::add_column_if_missing( + conn, + "mcp_servers", + "enabled_omp", + "BOOLEAN NOT NULL DEFAULT 0", + )?; + } + Self::set_user_version(conn, 23)?; + } + 23 => { + for table in ["mcp_servers", "skills"] { + if Self::table_exists(conn, table)? { + Self::add_column_if_missing( + conn, + table, + "enabled_dsh", + "BOOLEAN NOT NULL DEFAULT 0", + )?; + } + } + // DSH 用量导入:游标处未完成请求的解析上下文 + if Self::table_exists(conn, "session_log_sync")? { + Self::add_column_if_missing( + conn, + "session_log_sync", + "parser_state", + "TEXT", + )?; + } + Self::set_user_version(conn, 24)?; + } + 24 => { + // GitHub Copilot CLI:MCP 与 Skills 均在 SSOT 中保存独立开关。 + for table in ["mcp_servers", "skills"] { + if Self::table_exists(conn, table)? { + Self::add_column_if_missing( + conn, + table, + "enabled_copilot", + "BOOLEAN NOT NULL DEFAULT 0", + )?; + } + } + Self::set_user_version(conn, 25)?; + } + 25 => { + // WorkBuddy:MCP 与 Skills 都存开关。 + // 早期开发版曾把 enabled_workbuddy 记作 v23(缺 enabled_omp)、v24 + // (缺上游 v24 的 enabled_dsh)或 v25(缺上游 v25 的 enabled_copilot), + // 这里顺带补齐这些列;所有列都按"缺失才加"处理,保证幂等。 + if Self::table_exists(conn, "mcp_servers")? { + Self::add_column_if_missing( + conn, + "mcp_servers", + "enabled_omp", + "BOOLEAN NOT NULL DEFAULT 0", + )?; + } + for table in ["mcp_servers", "skills"] { + if Self::table_exists(conn, table)? { + for column in + ["enabled_dsh", "enabled_copilot", "enabled_workbuddy"] + { + Self::add_column_if_missing( + conn, + table, + column, + "BOOLEAN NOT NULL DEFAULT 0", + )?; + } + } + } + Self::set_user_version(conn, 26)?; + } _ => { return Err(AppError::Database(format!( "未知的数据库版本 {version},无法迁移到 {SCHEMA_VERSION}" diff --git a/src-tauri/src/database/tests.rs b/src-tauri/src/database/tests.rs index c9c557f8..c5e87959 100644 --- a/src-tauri/src/database/tests.rs +++ b/src-tauri/src/database/tests.rs @@ -314,9 +314,15 @@ fn schema_migration_sets_user_version_when_missing() { fn seed_upstream_mcp_skills(conn: &Connection, version: i32) { conn.execute_batch("DROP TABLE IF EXISTS mcp_servers; DROP TABLE IF EXISTS skills;") .expect("remove CLI tables"); - conn.execute_batch(include_str!("fixtures/upstream_v22_mcp_skills.sql")) + conn.execute_batch(include_str!("fixtures/upstream_v26_mcp_skills.sql")) .expect("create upstream tables"); - for (introduced, column) in [(21, "enabled_agy"), (22, "enabled_kimi")] { + for (introduced, column) in [ + (21, "enabled_agy"), + (22, "enabled_kimi"), + (24, "enabled_dsh"), + (25, "enabled_copilot"), + (26, "enabled_workbuddy"), + ] { if version < introduced { for table in ["mcp_servers", "skills"] { conn.execute_batch(&format!("ALTER TABLE {table} DROP COLUMN {column};")) @@ -324,6 +330,10 @@ fn seed_upstream_mcp_skills(conn: &Connection, version: i32) { } } } + if version < 23 { + conn.execute_batch("ALTER TABLE mcp_servers DROP COLUMN enabled_omp;") + .expect("restore v22 MCP schema"); + } if version < 20 { conn.execute_batch("ALTER TABLE mcp_servers DROP COLUMN enabled_pi;") .expect("restore v19 MCP schema"); @@ -353,7 +363,13 @@ fn seed_upstream_mcp_skills(conn: &Connection, version: i32) { conn.execute_batch("UPDATE mcp_servers SET enabled_pi = 1;") .expect("enable Pi"); } - for (introduced, column) in [(21, "enabled_agy"), (22, "enabled_kimi")] { + for (introduced, column) in [ + (21, "enabled_agy"), + (22, "enabled_kimi"), + (24, "enabled_dsh"), + (25, "enabled_copilot"), + (26, "enabled_workbuddy"), + ] { if version >= introduced { for table in ["mcp_servers", "skills"] { conn.execute_batch(&format!("UPDATE {table} SET {column} = 1;")) @@ -361,6 +377,10 @@ fn seed_upstream_mcp_skills(conn: &Connection, version: i32) { } } } + if version >= 23 { + conn.execute_batch("UPDATE mcp_servers SET enabled_omp = 1;") + .expect("enable Oh My Pi"); + } Database::set_user_version(conn, version).expect("set upstream version"); } @@ -374,6 +394,13 @@ fn assert_upstream_mcp_skills(conn: &Connection, original_version: i32) { ("skills", "enabled_agy"), ("mcp_servers", "enabled_kimi"), ("skills", "enabled_kimi"), + ("mcp_servers", "enabled_omp"), + ("mcp_servers", "enabled_dsh"), + ("skills", "enabled_dsh"), + ("mcp_servers", "enabled_copilot"), + ("skills", "enabled_copilot"), + ("mcp_servers", "enabled_workbuddy"), + ("skills", "enabled_workbuddy"), ] { let info = get_column_info(conn, table, column); assert_eq!(info.r#type, "BOOLEAN"); @@ -390,6 +417,10 @@ fn assert_upstream_mcp_skills(conn: &Connection, original_version: i32) { "enabled_pi" => 20, "enabled_agy" => 21, "enabled_kimi" => 22, + "enabled_omp" => 23, + "enabled_dsh" => 24, + "enabled_copilot" => 25, + "enabled_workbuddy" => 26, _ => 19, }; assert_eq!(flags, (1, i64::from(original_version >= introduced))); @@ -397,8 +428,8 @@ fn assert_upstream_mcp_skills(conn: &Connection, original_version: i32) { } #[test] -fn schema_migration_upstream_v18_through_v22_preserves_data_and_is_idempotent() { - for version in 18..=22 { +fn schema_migration_upstream_v18_through_v26_preserves_data_and_is_idempotent() { + for version in 18..=26 { let conn = Connection::open_in_memory().unwrap(); seed_upstream_mcp_skills(&conn, version); Database::apply_schema_migrations_on_conn(&conn).expect("migrate upstream schema"); @@ -410,14 +441,49 @@ fn schema_migration_upstream_v18_through_v22_preserves_data_and_is_idempotent() let conn = Connection::open_in_memory().unwrap(); Database::set_user_version(&conn, 18).unwrap(); Database::apply_schema_migrations_on_conn(&conn).expect("migrate absent tables"); - seed_upstream_mcp_skills(&conn, 22); + seed_upstream_mcp_skills(&conn, 26); Database::set_user_version(&conn, 18).unwrap(); Database::apply_schema_migrations_on_conn(&conn).expect("migrate existing columns"); - assert_upstream_mcp_skills(&conn, 22); + assert_upstream_mcp_skills(&conn, 26); } #[test] -fn schema_create_tables_matches_upstream_v22_flags() { +fn schema_migration_repairs_legacy_workbuddy_versions() { + for version in 23..=25 { + let conn = Connection::open_in_memory().unwrap(); + seed_upstream_mcp_skills(&conn, 26); + conn.execute_batch("ALTER TABLE mcp_servers DROP COLUMN enabled_omp;") + .unwrap(); + for table in ["mcp_servers", "skills"] { + for column in ["enabled_dsh", "enabled_copilot"] { + conn.execute_batch(&format!("ALTER TABLE {table} DROP COLUMN {column};")) + .unwrap(); + } + } + Database::set_user_version(&conn, version).unwrap(); + for _ in 0..2 { + Database::apply_schema_migrations_on_conn(&conn).unwrap(); + assert_eq!(Database::get_user_version(&conn).unwrap(), 26); + for table in ["mcp_servers", "skills"] { + let flags: (i64, i64, i64, i64) = conn + .query_row( + &format!("SELECT enabled_codex, enabled_dsh, enabled_copilot, enabled_workbuddy FROM {table}"), + [], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)), + ) + .unwrap(); + assert_eq!(flags, (1, 0, 0, 1), "legacy v{version}: {table}"); + } + let omp: i64 = conn + .query_row("SELECT enabled_omp FROM mcp_servers", [], |row| row.get(0)) + .unwrap(); + assert_eq!(omp, 0); + } + } +} + +#[test] +fn schema_create_tables_matches_upstream_v26_flags() { let conn = Connection::open_in_memory().unwrap(); Database::create_tables_on_conn(&conn).unwrap(); for (table, column) in [ @@ -428,22 +494,31 @@ fn schema_create_tables_matches_upstream_v22_flags() { ("skills", "enabled_agy"), ("mcp_servers", "enabled_kimi"), ("skills", "enabled_kimi"), + ("mcp_servers", "enabled_omp"), + ("mcp_servers", "enabled_dsh"), + ("skills", "enabled_dsh"), + ("mcp_servers", "enabled_copilot"), + ("skills", "enabled_copilot"), + ("mcp_servers", "enabled_workbuddy"), + ("skills", "enabled_workbuddy"), ] { let info = get_column_info(&conn, table, column); assert_eq!(info.r#type, "BOOLEAN"); assert_eq!(info.notnull, 1); assert_eq!(normalize_default(&info.default).as_deref(), Some("0")); } + assert!(Database::has_column(&conn, "session_log_sync", "parser_state").unwrap()); assert!(!Database::has_column(&conn, "skills", "enabled_pi").unwrap()); + assert!(!Database::has_column(&conn, "skills", "enabled_omp").unwrap()); } #[test] -fn init_and_sync_import_accept_upstream_v18_through_v22() { +fn init_and_sync_import_accept_upstream_v18_through_v26() { let home = tempfile::tempdir().unwrap(); let _env = crate::test_support::TestEnvGuard::isolated(home.path()); let config_dir = home.path().join(".cc-switch"); std::fs::create_dir_all(&config_dir).unwrap(); - for version in 18..=22 { + for version in 18..=26 { let conn = Connection::open(config_dir.join("cc-switch.db")).unwrap(); Database::create_tables_on_conn(&conn).unwrap(); seed_upstream_mcp_skills(&conn, version); @@ -469,6 +544,39 @@ fn init_and_sync_import_accept_upstream_v18_through_v22() { } } +#[test] +fn sync_import_preserves_local_parser_state() { + let local = Database::memory().expect("create local db"); + { + let conn = local.conn.lock().expect("lock conn"); + conn.execute( + r#"INSERT INTO session_log_sync + (file_path, last_modified, last_line_offset, last_synced_at, parser_state) + VALUES ('session.jsonl', 1, 0, 1, '{"step":7}')"#, + [], + ) + .expect("seed local parser state"); + } + + let remote = Database::memory().expect("create remote db"); + let sql = remote + .export_sql_string_for_sync() + .expect("export upstream sync sql"); + local + .import_sql_string_for_sync(&sql) + .expect("import upstream sync snapshot"); + + let conn = local.conn.lock().expect("lock conn"); + let parser_state: Option = conn + .query_row( + "SELECT parser_state FROM session_log_sync WHERE file_path = 'session.jsonl'", + [], + |row| row.get(0), + ) + .expect("read parser state after import"); + assert_eq!(parser_state.as_deref(), Some(r#"{"step":7}"#)); +} + #[test] fn schema_migration_rejects_future_version() { let conn = Connection::open_in_memory().expect("open memory db"); @@ -2347,8 +2455,9 @@ fn mcp_dao_roundtrip_preserves_upstream_enablement() { "INSERT INTO mcp_servers ( id, name, server_config, tags, enabled_claude, enabled_codex, enabled_gemini, enabled_grokbuild, - enabled_opencode, enabled_hermes, enabled_mcode, enabled_pi, enabled_agy, enabled_kimi - ) VALUES (?1, ?2, ?3, ?4, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1)", + enabled_opencode, enabled_hermes, enabled_mcode, enabled_pi, enabled_agy, enabled_kimi, + enabled_omp, enabled_dsh, enabled_copilot, enabled_workbuddy + ) VALUES (?1, ?2, ?3, ?4, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1)", params![ "remote-hermes", "Remote Hermes", @@ -2389,6 +2498,20 @@ fn mcp_dao_roundtrip_preserves_upstream_enablement() { (1, 1, 1, 1, 1, 1), "save should preserve hidden flags" ); + let upstream_flags: (i64, i64, i64, i64) = { + let conn = db.conn.lock().expect("lock conn"); + conn.query_row( + "SELECT enabled_omp, enabled_dsh, enabled_copilot, enabled_workbuddy FROM mcp_servers WHERE id = 'remote-hermes'", + [], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)), + ) + .expect("read upstream enablement after save") + }; + assert_eq!( + upstream_flags, + (1, 1, 1, 1), + "save should preserve upstream flags" + ); } #[test] @@ -2398,8 +2521,8 @@ fn skill_dao_save_preserves_upstream_enablement() { let conn = db.conn.lock().expect("lock conn"); conn.execute( "INSERT INTO skills ( - id, name, directory, enabled_grokbuild, enabled_hermes, enabled_mcode, enabled_agy, enabled_kimi, installed_at - ) VALUES ('remote-skill', 'Remote Skill', 'remote-skill', 1, 1, 1, 1, 1, 42)", + id, name, directory, enabled_grokbuild, enabled_hermes, enabled_mcode, enabled_agy, enabled_kimi, enabled_dsh, enabled_copilot, enabled_workbuddy, installed_at + ) VALUES ('remote-skill', 'Remote Skill', 'remote-skill', 1, 1, 1, 1, 1, 1, 1, 1, 42)", [], ) .expect("seed grokbuild-enabled Skill"); @@ -2426,6 +2549,20 @@ fn skill_dao_save_preserves_upstream_enablement() { (1, 1, 1, 1, 1), "save should preserve hidden flags" ); + let upstream_flags: (i64, i64, i64) = { + let conn = db.conn.lock().expect("lock conn"); + conn.query_row( + "SELECT enabled_dsh, enabled_copilot, enabled_workbuddy FROM skills WHERE id = 'remote-skill'", + [], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), + ) + .expect("read upstream enablement after save") + }; + assert_eq!( + upstream_flags, + (1, 1, 1), + "save should preserve upstream flags" + ); } #[test] diff --git a/src-tauri/src/services/session_usage.rs b/src-tauri/src/services/session_usage.rs index c3493ad5..6ff72d80 100644 --- a/src-tauri/src/services/session_usage.rs +++ b/src-tauri/src/services/session_usage.rs @@ -1201,10 +1201,16 @@ fn update_claude_sync_state_conn( .unwrap_or(0); conn.prepare_cached( - "INSERT OR REPLACE INTO session_log_sync + "INSERT INTO session_log_sync (file_path, last_modified, last_line_offset, last_synced_at, last_byte_offset, last_tail_fingerprint) - VALUES (?1, ?2, 0, ?3, ?4, ?5)", + VALUES (?1, ?2, 0, ?3, ?4, ?5) + ON CONFLICT(file_path) DO UPDATE SET + last_modified = excluded.last_modified, + last_line_offset = excluded.last_line_offset, + last_synced_at = excluded.last_synced_at, + last_byte_offset = excluded.last_byte_offset, + last_tail_fingerprint = excluded.last_tail_fingerprint", ) .and_then(|mut stmt| { stmt.execute(rusqlite::params![ @@ -1439,6 +1445,31 @@ pub(crate) fn delete_session_logs_covered_by_proxy_log( mod tests { use super::*; + #[test] + fn claude_cursor_update_preserves_upstream_parser_state() { + let conn = rusqlite::Connection::open_in_memory().expect("open memory db"); + Database::create_tables_on_conn(&conn).expect("create tables"); + conn.execute( + r#"INSERT INTO session_log_sync + (file_path, last_modified, last_line_offset, last_synced_at, parser_state) + VALUES ('session.jsonl', 1, 0, 1, '{"step":7}')"#, + [], + ) + .expect("seed upstream parser state"); + + update_claude_sync_state_conn(&conn, "session.jsonl", 2, 128, Some(9)) + .expect("update claude cursor"); + + let parser_state: Option = conn + .query_row( + "SELECT parser_state FROM session_log_sync WHERE file_path = 'session.jsonl'", + [], + |row| row.get(0), + ) + .expect("read parser state"); + assert_eq!(parser_state.as_deref(), Some(r#"{"step":7}"#)); + } + #[test] fn memory_database_session_guard_does_not_create_a_lock_file() -> Result<(), AppError> { let home = tempfile::tempdir().expect("isolated test home"); diff --git a/src-tauri/src/services/sync_protocol.rs b/src-tauri/src/services/sync_protocol.rs index f93f4467..89f99f57 100644 --- a/src-tauri/src/services/sync_protocol.rs +++ b/src-tauri/src/services/sync_protocol.rs @@ -570,8 +570,8 @@ mod tests { } #[test] - fn upstream_v19_through_v22_database_schemas_are_accepted() { - for version in 19..=22 { + fn upstream_v19_through_current_database_schemas_are_accepted() { + for version in 19..=SCHEMA_VERSION { let sql = format!("PRAGMA user_version={version};\n"); assert!(validate_sql_user_version_for_import(&sql).is_ok()); } diff --git a/src-tauri/src/services/webdav_sync/mod.rs b/src-tauri/src/services/webdav_sync/mod.rs index 9581ca12..ac2522f7 100644 --- a/src-tauri/src/services/webdav_sync/mod.rs +++ b/src-tauri/src/services/webdav_sync/mod.rs @@ -807,7 +807,7 @@ mod tests { } #[test] - fn apply_snapshot_accepts_current_schema_v13_sync_export() -> Result<(), AppError> { + fn apply_snapshot_accepts_current_schema_sync_export() -> Result<(), AppError> { let temp = tempfile::tempdir().expect("create temp dir"); let _env = crate::test_support::TestEnvGuard::isolated(temp.path()); @@ -825,7 +825,7 @@ mod tests { } let db_sql = remote_db .export_sql_string_for_sync() - .expect("export v13 sync sql"); + .expect("export current-schema sync sql"); let zip_path = temp.path().join("remote-skills.zip"); { @@ -855,6 +855,21 @@ mod tests { ) .expect("count imported provider"); assert_eq!(provider_count, 1); + for (table, column) in [ + ("mcp_servers", "enabled_omp"), + ("mcp_servers", "enabled_dsh"), + ("skills", "enabled_dsh"), + ("mcp_servers", "enabled_copilot"), + ("skills", "enabled_copilot"), + ("mcp_servers", "enabled_workbuddy"), + ("skills", "enabled_workbuddy"), + ("session_log_sync", "parser_state"), + ] { + assert!( + Database::has_column(&conn, table, column).unwrap(), + "restored upstream v{SCHEMA_VERSION} snapshot should keep {table}.{column}" + ); + } assert!( crate::services::skill::SkillService::get_ssot_dir() .expect("ssot dir") From c6ae6fa94d58096897773f75b1a1e4656651dbf1 Mon Sep 17 00:00:00 2001 From: SaladDay Date: Thu, 12 Nov 2026 21:28:19 +0800 Subject: [PATCH 17/23] fix(tui): exit when the input terminal hangs up (#558) --- .github/workflows/rust-ci.yml | 15 ++ CHANGELOG.md | 1 + docs/CHANGELOG.md | 1 + src-tauri/src/cli/tui/mod.rs | 5 + src-tauri/src/cli/tui/terminal_hangup.rs | 69 ++++++++++ src-tauri/tests/tui_terminal_hangup.rs | 168 +++++++++++++++++++++++ 6 files changed, 259 insertions(+) create mode 100644 src-tauri/src/cli/tui/terminal_hangup.rs create mode 100644 src-tauri/tests/tui_terminal_hangup.rs diff --git a/.github/workflows/rust-ci.yml b/.github/workflows/rust-ci.yml index c9046576..2f63c371 100644 --- a/.github/workflows/rust-ci.yml +++ b/.github/workflows/rust-ci.yml @@ -248,3 +248,18 @@ jobs: export XDG_STATE_HOME="$sandbox_home/.state" export RUST_TEST_THREADS=1 cargo test --test proxy_database -- --nocapture + + - name: Terminal hangup + working-directory: src-tauri + run: | + sandbox_home="$(mktemp -d)" + export HOME="$sandbox_home" + export USERPROFILE="$sandbox_home" + export CC_SWITCH_CONFIG_DIR="$sandbox_home/.cc-switch" + export CLAUDE_CONFIG_DIR="$sandbox_home/.claude" + export CODEX_HOME="$sandbox_home/.codex" + export XDG_CONFIG_HOME="$sandbox_home/.config" + export XDG_RUNTIME_DIR="$sandbox_home/.runtime" + export XDG_STATE_HOME="$sandbox_home/.state" + export RUST_TEST_THREADS=1 + cargo test --test tui_terminal_hangup -- --nocapture diff --git a/CHANGELOG.md b/CHANGELOG.md index 44217a29..5749db53 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **TUI**: Exit when the input terminal hangs up, including terminal proxies that do not deliver SIGHUP, instead of leaving a process spinning at full CPU. - **Database / Compatibility**: Support database schemas 23 through 26 from upstream, fixing WebDAV/S3 restore failures with `Remote database schema is too new (24); this app supports up to 22`. Align the migration steps, MCP/Skills enablement columns, and session-log parser state with the shared schema while preserving upstream flags and parser state through upgrades, edits, runtime cursor updates, and sync round-trips. ### Upgrade notes diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 44217a29..5749db53 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **TUI**: Exit when the input terminal hangs up, including terminal proxies that do not deliver SIGHUP, instead of leaving a process spinning at full CPU. - **Database / Compatibility**: Support database schemas 23 through 26 from upstream, fixing WebDAV/S3 restore failures with `Remote database schema is too new (24); this app supports up to 22`. Align the migration steps, MCP/Skills enablement columns, and session-log parser state with the shared schema while preserving upstream flags and parser state through upgrades, edits, runtime cursor updates, and sync round-trips. ### Upgrade notes diff --git a/src-tauri/src/cli/tui/mod.rs b/src-tauri/src/cli/tui/mod.rs index 04126bd0..2b48fff5 100644 --- a/src-tauri/src/cli/tui/mod.rs +++ b/src-tauri/src/cli/tui/mod.rs @@ -13,6 +13,8 @@ mod runtime_actions; mod runtime_skills; mod runtime_systems; mod terminal; +#[cfg(unix)] +mod terminal_hangup; #[cfg(test)] mod tests; mod text_edit; @@ -3049,6 +3051,9 @@ fn is_lightweight_preseed_app(app_type: &AppType) -> bool { } pub fn run(app_override: Option) -> Result<(), AppError> { + #[cfg(unix)] + let _hangup_guard = + terminal_hangup::HangupGuard::start().map_err(|e| AppError::Message(e.to_string()))?; let _panic_hook = PanicRestoreHookGuard::install(); let mut terminal = TuiTerminal::new()?; let (mut app, mut data) = diff --git a/src-tauri/src/cli/tui/terminal_hangup.rs b/src-tauri/src/cli/tui/terminal_hangup.rs new file mode 100644 index 00000000..b76b26ea --- /dev/null +++ b/src-tauri/src/cli/tui/terminal_hangup.rs @@ -0,0 +1,69 @@ +use std::fs::File; +use std::io; +use std::os::fd::{AsFd, AsRawFd}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use std::thread::{self, JoinHandle}; + +/// Crossterm 0.29 can spin inside poll/read after a PTY hangs up, so checking +/// from the UI loop cannot stop it. Observe hangup independently without +/// consuming input or changing signal handlers. +pub(super) struct HangupGuard { + stopped: Arc, + worker: Option>, +} + +impl HangupGuard { + pub(super) fn start() -> io::Result { + // Interactive mode already requires stdin/stdout to be terminals. + let terminal = File::from(io::stdin().as_fd().try_clone_to_owned()?); + let stopped = Arc::new(AtomicBool::new(false)); + let worker_stopped = Arc::clone(&stopped); + let worker = thread::Builder::new() + .name("tui-terminal-hangup".into()) + .spawn(move || { + let mut fd = libc::pollfd { + fd: terminal.as_raw_fd(), + // HUP is reported regardless of requested events. Normal + // input must not wake this observer or be consumed by it. + events: 0, + revents: 0, + }; + while !worker_stopped.load(Ordering::Relaxed) { + // SAFETY: fd points to a live pollfd and terminal owns its + // descriptor for the entire lifetime of this thread. + let result = unsafe { libc::poll(&mut fd, 1, 100) }; + if result < 0 { + if io::Error::last_os_error().kind() == io::ErrorKind::Interrupted { + continue; + } + break; + } + if fd.revents & libc::POLLHUP != 0 { + // The terminal is gone and the input thread may never + // return. Exit as a hangup would, even when a terminal + // proxy did not deliver SIGHUP. This cannot depend on + // the stuck reader unwinding; ordinary exits still use + // TuiTerminal::drop. + std::process::exit(128 + libc::SIGHUP); + } + if fd.revents & (libc::POLLERR | libc::POLLNVAL) != 0 { + break; + } + } + })?; + Ok(Self { + stopped, + worker: Some(worker), + }) + } +} + +impl Drop for HangupGuard { + fn drop(&mut self) { + self.stopped.store(true, Ordering::Relaxed); + if let Some(worker) = self.worker.take() { + let _ = worker.join(); + } + } +} diff --git a/src-tauri/tests/tui_terminal_hangup.rs b/src-tauri/tests/tui_terminal_hangup.rs new file mode 100644 index 00000000..387be91f --- /dev/null +++ b/src-tauri/tests/tui_terminal_hangup.rs @@ -0,0 +1,168 @@ +#![cfg(unix)] + +use std::fs::File; +use std::io::{Read, Write}; +use std::os::fd::{AsRawFd, FromRawFd}; +use std::os::unix::process::CommandExt; +use std::process::{Child, Command, ExitStatus}; +use std::time::{Duration, Instant}; + +#[path = "support.rs"] +mod support; + +struct RunningTui(Child); + +impl Drop for RunningTui { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} + +fn start_tui() -> (RunningTui, File, File) { + support::reset_test_fs(); + let mut master = -1; + let mut slave = -1; + let mut size = libc::winsize { + ws_row: 40, + ws_col: 120, + ws_xpixel: 0, + ws_ypixel: 0, + }; + // SAFETY: openpty initializes both descriptors and reads the supplied size. + assert_eq!( + unsafe { + libc::openpty( + &mut master, + &mut slave, + std::ptr::null_mut(), + std::ptr::null_mut(), + &mut size, + ) + }, + 0 + ); + // SAFETY: these are fresh, owned descriptors returned by openpty. + let (mut master, slave) = unsafe { (File::from_raw_fd(master), File::from_raw_fd(slave)) }; + // Do not let the child inherit the master; otherwise closing it in the + // parent cannot hang up the PTY. Nonblocking reads drain the TUI's output. + for fd in [master.as_raw_fd(), slave.as_raw_fd()] { + // SAFETY: both files are live and fcntl takes integer flags here. + assert_eq!( + unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) }, + 0 + ); + } + // SAFETY: master remains open for the call. + assert_eq!( + unsafe { libc::fcntl(master.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK) }, + 0 + ); + + let mut command = Command::new(env!("CARGO_BIN_EXE_cc-switch")); + command + .arg("interactive") + .env("TERM", "xterm-256color") + .env_remove("CC_SWITCH_DAEMON_SOCKET") + .env_remove("CC_SWITCH_LEGACY_TUI") + .stdin(slave.try_clone().unwrap()) + .stdout(slave.try_clone().unwrap()) + .stderr(slave.try_clone().unwrap()); + // SAFETY: the pre-exec hook only calls async-signal-safe libc functions. + unsafe { + command.pre_exec(move || { + if libc::setsid() < 0 { + return Err(std::io::Error::last_os_error()); + } + // Reproduce a terminal proxy that leaves its child without SIGHUP. + libc::signal(libc::SIGHUP, libc::SIG_IGN); + Ok(()) + }); + } + let mut child = RunningTui(command.spawn().expect("spawn isolated TUI")); + let deadline = Instant::now() + Duration::from_secs(10); + let mut output = Vec::new(); + while !output.windows(6).any(|w| w == b"\x1b[?25l") { + assert!( + child.0.try_wait().unwrap().is_none(), + "TUI exited: {output:?}" + ); + assert!( + Instant::now() < deadline, + "TUI did not activate: {output:?}" + ); + drain_output(&mut master, &mut output); + std::thread::sleep(Duration::from_millis(10)); + } + // Let startup finish and the input loop enter poll. Keep draining output so + // the test exercises input hangup, not a terminal write blocked at startup. + let settled = Instant::now() + Duration::from_secs(4); + while Instant::now() < settled { + drain_output(&mut master, &mut output); + std::thread::sleep(Duration::from_millis(10)); + } + assert!(child.0.try_wait().unwrap().is_none()); + (child, master, slave) +} + +fn drain_output(master: &mut File, output: &mut Vec) { + let mut buffer = [0; 8192]; + while let Ok(count) = master.read(&mut buffer) { + if count == 0 { + break; + } + output.extend_from_slice(&buffer[..count]); + } +} + +fn wait_for_exit(child: &mut RunningTui) -> ExitStatus { + let deadline = Instant::now() + Duration::from_secs(3); + loop { + if let Some(status) = child.0.try_wait().unwrap() { + return status; + } + assert!( + Instant::now() < deadline, + "TUI failed to exit after terminal hangup/quit" + ); + std::thread::sleep(Duration::from_millis(10)); + } +} + +#[test] +fn tui_exits_after_pty_hangup_without_sighup() { + let _lock = support::lock_test_mutex(); + let (mut child, master, _slave) = start_tui(); + drop(master); + assert!(!wait_for_exit(&mut child).success()); +} + +#[test] +fn connected_terminal_keeps_keyboard_input_and_normal_restore() { + let _lock = support::lock_test_mutex(); + let (mut child, mut master, slave) = start_tui(); + master + .write_all(b"\x03") + .expect("send Ctrl-C as terminal input"); + assert!(wait_for_exit(&mut child).success()); + let mut output = Vec::new(); + drain_output(&mut master, &mut output); + assert!( + output.windows(8).any(|w| w == b"\x1b[?1049l"), + "leave alternate screen" + ); + let mut settings = std::mem::MaybeUninit::uninit(); + // SAFETY: slave is live and tcgetattr initializes settings on success. + assert_eq!( + unsafe { libc::tcgetattr(slave.as_raw_fd(), settings.as_mut_ptr()) }, + 0 + ); + // SAFETY: tcgetattr succeeded. + let settings = unsafe { settings.assume_init() }; + assert_ne!( + settings.c_lflag & libc::ICANON, + 0, + "restore canonical input" + ); + assert_ne!(settings.c_lflag & libc::ECHO, 0, "restore echo"); +} From 65c2c83b228ce3ecc0efb400c54f1b7c64ee8a6e Mon Sep 17 00:00:00 2001 From: SaladDay Date: Thu, 12 Nov 2026 23:52:30 +0800 Subject: [PATCH 18/23] fix(webdav-sync): keep file symlink names in skills archives (#559) * fix(webdav-sync): keep file symlink names in skills archives A skill with file symlinks such as CLAUDE.md -> AGENTS.md named every alias after its target, so the skills zip got duplicate entries and WebDAV/S3 upload failed with "Duplicate filename". File entries now use the link's own path and read content from the target. Directories keep canonical names, so traversal and cycle detection are unchanged. Ports farion1231/cc-switch#9197. * test(webdav-sync): cover outside-root links and plain-file alias entries --- src-tauri/src/services/webdav_sync/archive.rs | 95 ++++++++++++++++--- 1 file changed, 84 insertions(+), 11 deletions(-) diff --git a/src-tauri/src/services/webdav_sync/archive.rs b/src-tauri/src/services/webdav_sync/archive.rs index 138b9267..51e55c26 100644 --- a/src-tauri/src/services/webdav_sync/archive.rs +++ b/src-tauri/src/services/webdav_sync/archive.rs @@ -205,19 +205,20 @@ pub fn zip_dir_recursive( Err(_) => path.clone(), }; - let rel = real_path - .strip_prefix(root) - .or_else(|_| path.strip_prefix(root)) - .map_err(|e| { - localized( - "webdav.sync.zip_relative_path_failed", - format!("生成 ZIP 相对路径失败: {e}"), - format!("Failed to build relative ZIP path: {e}"), - ) - })?; + let is_dir = real_path.is_dir(); + // File aliases keep their own names while their contents come from real_path. + // Directories keep canonical names to match traversal and deduplication. + let archive_path = if is_dir { &real_path } else { &path }; + let rel = archive_path.strip_prefix(root).map_err(|e| { + localized( + "webdav.sync.zip_relative_path_failed", + format!("生成 ZIP 相对路径失败: {e}"), + format!("Failed to build relative ZIP path: {e}"), + ) + })?; let rel_str = rel.to_string_lossy().replace('\\', "/"); - if real_path.is_dir() { + if is_dir { // 跳过已访问的目录(符号链接循环检测) if !mark_visited_dir(&real_path, visited)? { log::warn!( @@ -453,6 +454,78 @@ mod tests { use crate::settings::{update_settings, AppSettings}; use tempfile::tempdir; + #[cfg(unix)] + fn zip_test_dir(source: &Path, destination: &Path) -> zip::ZipArchive { + let root = fs::canonicalize(source).unwrap(); + let mut writer = zip::ZipWriter::new(fs::File::create(destination).unwrap()); + let mut visited = HashSet::new(); + mark_visited_dir(&root, &mut visited).unwrap(); + zip_dir_recursive(&root, &root, &mut writer, zip_file_options(), &mut visited).unwrap(); + writer.finish().unwrap(); + zip::ZipArchive::new(fs::File::open(destination).unwrap()).unwrap() + } + + #[cfg(unix)] + #[test] + fn zip_preserves_file_symlink_names_and_contents() { + let temp = tempdir().unwrap(); + let skill = temp.path().join("skills").join("example"); + fs::create_dir_all(&skill).unwrap(); + fs::write(skill.join("AGENTS.md"), "shared instructions").unwrap(); + // Aliases sorted both before and after the target file. + for name in ["00-alias.md", "CLAUDE.md", "GEMINI.md"] { + std::os::unix::fs::symlink("AGENTS.md", skill.join(name)).unwrap(); + } + + let mut archive = zip_test_dir(&temp.path().join("skills"), &temp.path().join("s.zip")); + assert_eq!(archive.len(), 5); + for name in ["00-alias.md", "AGENTS.md", "CLAUDE.md", "GEMINI.md"] { + let mut entry = archive.by_name(&format!("example/{name}")).unwrap(); + let mut content = String::new(); + entry.read_to_string(&mut content).unwrap(); + assert_eq!(content, "shared instructions"); + assert!(!entry.is_symlink()); + } + } + + #[cfg(unix)] + #[test] + fn zip_skips_file_symlinks_outside_root() { + let temp = tempdir().unwrap(); + let source = temp.path().join("skills"); + fs::create_dir(&source).unwrap(); + fs::write(source.join("inside.md"), "included").unwrap(); + fs::write(temp.path().join("outside.md"), "excluded").unwrap(); + std::os::unix::fs::symlink("../outside.md", source.join("outside.md")).unwrap(); + + let mut archive = zip_test_dir(&source, &temp.path().join("s.zip")); + assert_eq!(archive.len(), 1); + assert_eq!(archive.by_index(0).unwrap().name(), "inside.md"); + } + + #[cfg(unix)] + #[test] + fn zip_keeps_canonical_directory_names_and_skips_cycles() { + let temp = tempdir().unwrap(); + let source = temp.path().join("skills"); + let target = source.join("target"); + fs::create_dir_all(&target).unwrap(); + fs::write(target.join("AGENTS.md"), "instructions").unwrap(); + std::os::unix::fs::symlink("target", source.join("alias")).unwrap(); + std::os::unix::fs::symlink("..", target.join("loop")).unwrap(); + + let mut archive = zip_test_dir(&source, &temp.path().join("s.zip")); + assert_eq!(archive.len(), 2); + assert!(archive.by_name("target/").unwrap().is_dir()); + let mut content = String::new(); + archive + .by_name("target/AGENTS.md") + .unwrap() + .read_to_string(&mut content) + .unwrap(); + assert_eq!(content, "instructions"); + } + #[test] fn zip_output_is_stable_for_same_content() { let tmp = tempdir().expect("create temp dir"); From 3b52a3cae68e0f230ec4a81239e92db3b6fa1530 Mon Sep 17 00:00:00 2001 From: SaladDay Date: Fri, 13 Nov 2026 02:13:17 +0800 Subject: [PATCH 19/23] docs: unify the blind review gate (#560) Replace the blind review protocol in AGENTS.md and CLAUDE.md with a tiered review gate: one blind reviewer by default and two for high-risk changes, follow-up rounds on the new changes only, at most three rounds before a design reassessment, and unfixed findings recorded in the final report. Documentation-only changes skip it. --- AGENTS.md | 27 ++++++++++++++++++--------- CLAUDE.md | 27 ++++++++++++++++++--------- 2 files changed, 36 insertions(+), 18 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 12dc3290..6082b69b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -92,15 +92,24 @@ The proxy command surface is in `src/cli/commands/proxy.rs`, orchestration lives Request handling flows through `HandlerContext`, `ProviderRouter`, `RequestForwarder`, provider adapters in `src/proxy/providers/`, and response builders/handlers in `src/proxy/response*.rs`. Claude `/v1/messages` traffic may be transformed between Anthropic and OpenAI-compatible formats; Codex/OpenAI, Gemini, Copilot, and streaming-response routes are handled by provider-specific adapters. Proxy tests are split across focused integration targets such as `proxy_claude_streaming`, `proxy_claude_openai_chat`, `proxy_claude_response_parity`, `proxy_claude_forwarder_alignment`, `proxy_multi_app_passthrough`, `proxy_takeover`, `proxy_service`, and `proxy_daemon`. -## Blind review protocol - -- Before development, define the requirements, acceptance criteria, and task boundaries. Keep changes minimal and avoid unrelated refactoring or behavior changes. -- After implementation and local validation are complete, send the full change set to one new subagent for blind review. -- Start every reviewer with fresh context, without inheriting the development conversation. Provide only the user's goal, intended behavior, acceptance criteria, task boundaries, relevant constraints, repository location, and comparison baseline. Before review begins, tell the user the requirements, criteria, and boundaries given to the reviewer. -- Do not disclose implementation details, change summaries, self-assessments, or findings from prior review rounds. Ask the reviewer to independently inspect all current modifications and report correctness, regression, security, performance, UX, and test-coverage issues. -- Validate every finding against the code. Make minimal fixes for confirmed issues within scope, run the relevant checks, then start another blind review with a new subagent under the same context rules. -- If a confirmed finding also exists upstream, fixing it would expand the task, and compatibility is the intended behavior, it may remain unchanged. Record that decision and prefer upstream parity over an unrelated local fix. -- If review and repair keep cycling without convergence, stop patching and reconsider the overall design and task boundaries. If that still cannot produce a sound resolution, stop expanding the change set and report the unresolved issues, tradeoffs, and evidence to the user. +## Independent blind review gate + +Before development, define the requirements, acceptance criteria, and task boundaries. Keep changes minimal and avoid unrelated refactoring or behavior changes. When a confirmed issue also exists upstream and fixing it would expand the task, prefer upstream parity over an unrelated local fix. + +Apply this gate after any code change, before declaring the work complete. Changes limited to documentation, comments, formatting or translated text skip it. + +1. Freeze a review range (normally `main...HEAD`) and make sure the worktree is clean enough that every in-scope modification is visible to reviewers. +2. Choose reviewers by risk. By default, start one fresh, independent subagent with no inherited conversation context. Start two such reviewers when the change touches database schema or migrations, writes to live app configuration files, proxy routing or failover, concurrency, credentials or other security-sensitive paths, or import, export and sync of user data. Every reviewer inspects that round's complete range. +3. Give each reviewer detailed but neutral context: the user's goal, intended behavior, acceptance criteria, task boundaries, relevant constraints, repository layout, architectural boundaries, authoritative contracts or documentation, the exact review range, relevant validation commands, and the dimensions to inspect (correctness, regressions, data integrity, concurrency, security, performance, compatibility, UI state, i18n, and tests). Before the review starts, tell the user the requirements, criteria and boundaries given to the reviewer. +4. Do not tell reviewers the implementation approach, what changes or fixes were made, the chosen design rationale, known concerns, prior review findings, or another reviewer's conclusions. Reviewers must independently infer how the code attempts to meet the stated requirements. +5. Reviewers are read-only. Require prioritized findings with severity, confidence, an exact file and line, a concrete failure scenario, reasoning, and a recommended direction. Require an explicit "no findings" result when applicable. Style-only comments are not findings unless they create a maintenance or correctness risk. +6. The primary agent must independently validate every finding against the source and tests. Do not apply reviewer suggestions mechanically. When a validated finding is deliberately left unfixed, such as to keep upstream-compatible behavior, record the decision and its reason and list it in the final report. Later reviewers receive it as intended behavior among the constraints in step 3, not as a finding. Leaving a finding unfixed never satisfies step 10: an unfixed validated blocker or high-severity finding still blocks completion. +7. Fix confirmed issues, confirm each fixed failure scenario with a test or a reproduction, and run proportionate regression tests. After material fixes, freeze a new range covering the changes made since the reviewed range and review it with one new blind reviewer under the same context rules. +8. Track findings by underlying invariant or failure scenario, not wording. Run at most three review rounds for one implementation. If validated blocker, high-severity or data-integrity findings remain after the third round, or earlier if review and repair begin cycling, patches contradict earlier patches, or the same invariant repeatedly fails, stop patching and reassess the overall design: ownership, boundaries, state model, data flow, contracts, and test strategy. A design-level correction goes through this gate as a new implementation. If only lower-severity findings remain after the third round, finish without another round: fix the small, localized ones, verify them with tests, and list the rest in the final report. +9. If the design-level correction still does not converge within three rounds, stop and report the unresolved condition, review history, conflicting constraints, and viable options instead of continuing. +10. Completion requires no validated blocker or high-severity finding, all relevant checks passing, and a final primary-agent audit of the complete diff. + +The reviewer count is a review-quality gate, not a requirement to split the implementation into multiple pull requests. ## Testing requirements diff --git a/CLAUDE.md b/CLAUDE.md index 47153f4a..7ba02b22 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -92,15 +92,24 @@ The proxy command surface is in `src/cli/commands/proxy.rs`, orchestration lives Request handling flows through `HandlerContext`, `ProviderRouter`, `RequestForwarder`, provider adapters in `src/proxy/providers/`, and response builders/handlers in `src/proxy/response*.rs`. Claude `/v1/messages` traffic may be transformed between Anthropic and OpenAI-compatible formats; Codex/OpenAI, Gemini, Copilot, and streaming-response routes are handled by provider-specific adapters. Proxy tests are split across focused integration targets such as `proxy_claude_streaming`, `proxy_claude_openai_chat`, `proxy_claude_response_parity`, `proxy_claude_forwarder_alignment`, `proxy_multi_app_passthrough`, `proxy_takeover`, `proxy_service`, and `proxy_daemon`. -## Blind review protocol - -- Before development, define the requirements, acceptance criteria, and task boundaries. Keep changes minimal and avoid unrelated refactoring or behavior changes. -- After implementation and local validation are complete, send the full change set to one new subagent for blind review. -- Start every reviewer with fresh context, without inheriting the development conversation. Provide only the user's goal, intended behavior, acceptance criteria, task boundaries, relevant constraints, repository location, and comparison baseline. Before review begins, tell the user the requirements, criteria, and boundaries given to the reviewer. -- Do not disclose implementation details, change summaries, self-assessments, or findings from prior review rounds. Ask the reviewer to independently inspect all current modifications and report correctness, regression, security, performance, UX, and test-coverage issues. -- Validate every finding against the code. Make minimal fixes for confirmed issues within scope, run the relevant checks, then start another blind review with a new subagent under the same context rules. -- If a confirmed finding also exists upstream, fixing it would expand the task, and compatibility is the intended behavior, it may remain unchanged. Record that decision and prefer upstream parity over an unrelated local fix. -- If review and repair keep cycling without convergence, stop patching and reconsider the overall design and task boundaries. If that still cannot produce a sound resolution, stop expanding the change set and report the unresolved issues, tradeoffs, and evidence to the user. +## Independent blind review gate + +Before development, define the requirements, acceptance criteria, and task boundaries. Keep changes minimal and avoid unrelated refactoring or behavior changes. When a confirmed issue also exists upstream and fixing it would expand the task, prefer upstream parity over an unrelated local fix. + +Apply this gate after any code change, before declaring the work complete. Changes limited to documentation, comments, formatting or translated text skip it. + +1. Freeze a review range (normally `main...HEAD`) and make sure the worktree is clean enough that every in-scope modification is visible to reviewers. +2. Choose reviewers by risk. By default, start one fresh, independent subagent with no inherited conversation context. Start two such reviewers when the change touches database schema or migrations, writes to live app configuration files, proxy routing or failover, concurrency, credentials or other security-sensitive paths, or import, export and sync of user data. Every reviewer inspects that round's complete range. +3. Give each reviewer detailed but neutral context: the user's goal, intended behavior, acceptance criteria, task boundaries, relevant constraints, repository layout, architectural boundaries, authoritative contracts or documentation, the exact review range, relevant validation commands, and the dimensions to inspect (correctness, regressions, data integrity, concurrency, security, performance, compatibility, UI state, i18n, and tests). Before the review starts, tell the user the requirements, criteria and boundaries given to the reviewer. +4. Do not tell reviewers the implementation approach, what changes or fixes were made, the chosen design rationale, known concerns, prior review findings, or another reviewer's conclusions. Reviewers must independently infer how the code attempts to meet the stated requirements. +5. Reviewers are read-only. Require prioritized findings with severity, confidence, an exact file and line, a concrete failure scenario, reasoning, and a recommended direction. Require an explicit "no findings" result when applicable. Style-only comments are not findings unless they create a maintenance or correctness risk. +6. The primary agent must independently validate every finding against the source and tests. Do not apply reviewer suggestions mechanically. When a validated finding is deliberately left unfixed, such as to keep upstream-compatible behavior, record the decision and its reason and list it in the final report. Later reviewers receive it as intended behavior among the constraints in step 3, not as a finding. Leaving a finding unfixed never satisfies step 10: an unfixed validated blocker or high-severity finding still blocks completion. +7. Fix confirmed issues, confirm each fixed failure scenario with a test or a reproduction, and run proportionate regression tests. After material fixes, freeze a new range covering the changes made since the reviewed range and review it with one new blind reviewer under the same context rules. +8. Track findings by underlying invariant or failure scenario, not wording. Run at most three review rounds for one implementation. If validated blocker, high-severity or data-integrity findings remain after the third round, or earlier if review and repair begin cycling, patches contradict earlier patches, or the same invariant repeatedly fails, stop patching and reassess the overall design: ownership, boundaries, state model, data flow, contracts, and test strategy. A design-level correction goes through this gate as a new implementation. If only lower-severity findings remain after the third round, finish without another round: fix the small, localized ones, verify them with tests, and list the rest in the final report. +9. If the design-level correction still does not converge within three rounds, stop and report the unresolved condition, review history, conflicting constraints, and viable options instead of continuing. +10. Completion requires no validated blocker or high-severity finding, all relevant checks passing, and a final primary-agent audit of the complete diff. + +The reviewer count is a review-quality gate, not a requirement to split the implementation into multiple pull requests. ## Testing requirements From b1fa06ebabac9bc3dcb04b72cee10c91faafbc56 Mon Sep 17 00:00:00 2001 From: SaladDay Date: Fri, 13 Nov 2026 02:43:52 +0800 Subject: [PATCH 20/23] docs: refine the blind review gate (#561) Keep fixes and blocking findings within the task boundaries while treating problems the change causes as in scope, end the gate in two explicit cases after the third round, define the severity scale and a reproducible review range for uncommitted work, and brief follow-up reviewers like the first. --- AGENTS.md | 22 ++++++++++++---------- CLAUDE.md | 22 ++++++++++++---------- 2 files changed, 24 insertions(+), 20 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 6082b69b..db44ef60 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -98,16 +98,18 @@ Before development, define the requirements, acceptance criteria, and task bound Apply this gate after any code change, before declaring the work complete. Changes limited to documentation, comments, formatting or translated text skip it. -1. Freeze a review range (normally `main...HEAD`) and make sure the worktree is clean enough that every in-scope modification is visible to reviewers. -2. Choose reviewers by risk. By default, start one fresh, independent subagent with no inherited conversation context. Start two such reviewers when the change touches database schema or migrations, writes to live app configuration files, proxy routing or failover, concurrency, credentials or other security-sensitive paths, or import, export and sync of user data. Every reviewer inspects that round's complete range. -3. Give each reviewer detailed but neutral context: the user's goal, intended behavior, acceptance criteria, task boundaries, relevant constraints, repository layout, architectural boundaries, authoritative contracts or documentation, the exact review range, relevant validation commands, and the dimensions to inspect (correctness, regressions, data integrity, concurrency, security, performance, compatibility, UI state, i18n, and tests). Before the review starts, tell the user the requirements, criteria and boundaries given to the reviewer. -4. Do not tell reviewers the implementation approach, what changes or fixes were made, the chosen design rationale, known concerns, prior review findings, or another reviewer's conclusions. Reviewers must independently infer how the code attempts to meet the stated requirements. -5. Reviewers are read-only. Require prioritized findings with severity, confidence, an exact file and line, a concrete failure scenario, reasoning, and a recommended direction. Require an explicit "no findings" result when applicable. Style-only comments are not findings unless they create a maintenance or correctness risk. -6. The primary agent must independently validate every finding against the source and tests. Do not apply reviewer suggestions mechanically. When a validated finding is deliberately left unfixed, such as to keep upstream-compatible behavior, record the decision and its reason and list it in the final report. Later reviewers receive it as intended behavior among the constraints in step 3, not as a finding. Leaving a finding unfixed never satisfies step 10: an unfixed validated blocker or high-severity finding still blocks completion. -7. Fix confirmed issues, confirm each fixed failure scenario with a test or a reproduction, and run proportionate regression tests. After material fixes, freeze a new range covering the changes made since the reviewed range and review it with one new blind reviewer under the same context rules. -8. Track findings by underlying invariant or failure scenario, not wording. Run at most three review rounds for one implementation. If validated blocker, high-severity or data-integrity findings remain after the third round, or earlier if review and repair begin cycling, patches contradict earlier patches, or the same invariant repeatedly fails, stop patching and reassess the overall design: ownership, boundaries, state model, data flow, contracts, and test strategy. A design-level correction goes through this gate as a new implementation. If only lower-severity findings remain after the third round, finish without another round: fix the small, localized ones, verify them with tests, and list the rest in the final report. -9. If the design-level correction still does not converge within three rounds, stop and report the unresolved condition, review history, conflicting constraints, and viable options instead of continuing. -10. Completion requires no validated blocker or high-severity finding, all relevant checks passing, and a final primary-agent audit of the complete diff. +1. Freeze a review range the reviewer can reproduce, and do not commit or edit while a reviewer is running: normally `main...HEAD` for committed work, or, for uncommitted work, the working tree against its merge base with `main`, with new files marked by `git add -N`. Make sure every in-scope modification is visible in that range. +2. Choose reviewers for an implementation's first round by risk. By default, start one fresh, independent subagent with no inherited conversation context. Start two such reviewers when the change touches database schema or migrations, writes to live app configuration files, proxy routing or failover, concurrency, credentials or other security-sensitive paths, or import, export and sync of user data. Every reviewer inspects that round's complete range. +3. Give each reviewer detailed but neutral context: the user's goal, intended behavior, acceptance criteria, task boundaries, relevant constraints, the repository path, repository layout, architectural boundaries, authoritative contracts or documentation, the exact review range, relevant read-only validation commands, and the dimensions to inspect (correctness, regressions, data integrity, concurrency, security, performance, compatibility, UI state, i18n, and tests). Before the review starts, tell the user the requirements, criteria and boundaries given to the reviewer. +4. Do not tell reviewers the implementation approach, what changes or fixes were made, the chosen design rationale, a self-assessment, known concerns, prior review findings, or another reviewer's conclusions. Reviewers must independently infer how the code attempts to meet the stated requirements. +5. Reviewers are read-only. Require prioritized findings with severity (blocker, high, medium or low; data integrity is a category at any severity), confidence, an exact file and line, a concrete failure scenario, reasoning, and a recommended direction. Require an explicit "no findings" result when applicable. Style-only comments are not findings unless they create a maintenance or correctness risk. +6. The primary agent must independently validate every finding against the source and tests. Do not apply reviewer suggestions mechanically. A problem the change causes or worsens is in scope wherever it appears. A validated pre-existing or unrelated problem that cannot be fixed within the task boundaries is recorded and reported to the user instead of fixed, and does not block completion. When an in-scope finding is deliberately left unfixed, such as to keep upstream-compatible behavior, record the decision and its reason and list it in the final report. Later reviewers receive deliberate decisions as intended behavior, and known out-of-boundary problems as task boundaries, among the constraints in step 3. Leaving an in-scope finding unfixed never satisfies step 10: an unfixed validated blocker, high-severity or data-integrity finding still blocks completion. +7. Fix confirmed in-scope issues, confirm each fixed failure scenario with a test or a reproduction, and run proportionate regression tests. After fixing a blocker, high-severity or data-integrity finding, or after any other material fix, review the changes made since the reviewed range with one new blind reviewer, started and briefed as in steps 2 to 5; when uncommitted new changes cannot be separated, review the whole working-tree range again. +8. Track findings by underlying invariant or failure scenario, not wording. Run at most three review rounds for one implementation, and end the gate in one of two ways: + - If the third round's validated in-scope findings are all medium or low and none concerns data integrity, finish without another round: fix the small, localized findings, confirm each with a test or a reproduction, and list the rest in the final report. + - If the third round reports a validated in-scope blocker, high-severity or data-integrity finding, or earlier if review and repair begin cycling, patches contradict earlier patches, or the same invariant repeatedly fails, stop patching and reassess the design: ownership, component boundaries, state model, data flow, contracts, and test strategy. A corrected design that fits within the task boundaries, which come from the user, goes through this gate once as a new implementation. If the design holds, or the task boundaries themselves look wrong, stop and report to the user. +9. If the design-level correction reaches either condition of the second case, stop and report the unresolved condition, review history, conflicting constraints, and viable options. Never start a second correction or broaden the task. +10. Completion requires no validated in-scope blocker, high-severity or data-integrity finding, all relevant checks passing, and a final primary-agent audit of the complete diff. The reviewer count is a review-quality gate, not a requirement to split the implementation into multiple pull requests. diff --git a/CLAUDE.md b/CLAUDE.md index 7ba02b22..c3020039 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -98,16 +98,18 @@ Before development, define the requirements, acceptance criteria, and task bound Apply this gate after any code change, before declaring the work complete. Changes limited to documentation, comments, formatting or translated text skip it. -1. Freeze a review range (normally `main...HEAD`) and make sure the worktree is clean enough that every in-scope modification is visible to reviewers. -2. Choose reviewers by risk. By default, start one fresh, independent subagent with no inherited conversation context. Start two such reviewers when the change touches database schema or migrations, writes to live app configuration files, proxy routing or failover, concurrency, credentials or other security-sensitive paths, or import, export and sync of user data. Every reviewer inspects that round's complete range. -3. Give each reviewer detailed but neutral context: the user's goal, intended behavior, acceptance criteria, task boundaries, relevant constraints, repository layout, architectural boundaries, authoritative contracts or documentation, the exact review range, relevant validation commands, and the dimensions to inspect (correctness, regressions, data integrity, concurrency, security, performance, compatibility, UI state, i18n, and tests). Before the review starts, tell the user the requirements, criteria and boundaries given to the reviewer. -4. Do not tell reviewers the implementation approach, what changes or fixes were made, the chosen design rationale, known concerns, prior review findings, or another reviewer's conclusions. Reviewers must independently infer how the code attempts to meet the stated requirements. -5. Reviewers are read-only. Require prioritized findings with severity, confidence, an exact file and line, a concrete failure scenario, reasoning, and a recommended direction. Require an explicit "no findings" result when applicable. Style-only comments are not findings unless they create a maintenance or correctness risk. -6. The primary agent must independently validate every finding against the source and tests. Do not apply reviewer suggestions mechanically. When a validated finding is deliberately left unfixed, such as to keep upstream-compatible behavior, record the decision and its reason and list it in the final report. Later reviewers receive it as intended behavior among the constraints in step 3, not as a finding. Leaving a finding unfixed never satisfies step 10: an unfixed validated blocker or high-severity finding still blocks completion. -7. Fix confirmed issues, confirm each fixed failure scenario with a test or a reproduction, and run proportionate regression tests. After material fixes, freeze a new range covering the changes made since the reviewed range and review it with one new blind reviewer under the same context rules. -8. Track findings by underlying invariant or failure scenario, not wording. Run at most three review rounds for one implementation. If validated blocker, high-severity or data-integrity findings remain after the third round, or earlier if review and repair begin cycling, patches contradict earlier patches, or the same invariant repeatedly fails, stop patching and reassess the overall design: ownership, boundaries, state model, data flow, contracts, and test strategy. A design-level correction goes through this gate as a new implementation. If only lower-severity findings remain after the third round, finish without another round: fix the small, localized ones, verify them with tests, and list the rest in the final report. -9. If the design-level correction still does not converge within three rounds, stop and report the unresolved condition, review history, conflicting constraints, and viable options instead of continuing. -10. Completion requires no validated blocker or high-severity finding, all relevant checks passing, and a final primary-agent audit of the complete diff. +1. Freeze a review range the reviewer can reproduce, and do not commit or edit while a reviewer is running: normally `main...HEAD` for committed work, or, for uncommitted work, the working tree against its merge base with `main`, with new files marked by `git add -N`. Make sure every in-scope modification is visible in that range. +2. Choose reviewers for an implementation's first round by risk. By default, start one fresh, independent subagent with no inherited conversation context. Start two such reviewers when the change touches database schema or migrations, writes to live app configuration files, proxy routing or failover, concurrency, credentials or other security-sensitive paths, or import, export and sync of user data. Every reviewer inspects that round's complete range. +3. Give each reviewer detailed but neutral context: the user's goal, intended behavior, acceptance criteria, task boundaries, relevant constraints, the repository path, repository layout, architectural boundaries, authoritative contracts or documentation, the exact review range, relevant read-only validation commands, and the dimensions to inspect (correctness, regressions, data integrity, concurrency, security, performance, compatibility, UI state, i18n, and tests). Before the review starts, tell the user the requirements, criteria and boundaries given to the reviewer. +4. Do not tell reviewers the implementation approach, what changes or fixes were made, the chosen design rationale, a self-assessment, known concerns, prior review findings, or another reviewer's conclusions. Reviewers must independently infer how the code attempts to meet the stated requirements. +5. Reviewers are read-only. Require prioritized findings with severity (blocker, high, medium or low; data integrity is a category at any severity), confidence, an exact file and line, a concrete failure scenario, reasoning, and a recommended direction. Require an explicit "no findings" result when applicable. Style-only comments are not findings unless they create a maintenance or correctness risk. +6. The primary agent must independently validate every finding against the source and tests. Do not apply reviewer suggestions mechanically. A problem the change causes or worsens is in scope wherever it appears. A validated pre-existing or unrelated problem that cannot be fixed within the task boundaries is recorded and reported to the user instead of fixed, and does not block completion. When an in-scope finding is deliberately left unfixed, such as to keep upstream-compatible behavior, record the decision and its reason and list it in the final report. Later reviewers receive deliberate decisions as intended behavior, and known out-of-boundary problems as task boundaries, among the constraints in step 3. Leaving an in-scope finding unfixed never satisfies step 10: an unfixed validated blocker, high-severity or data-integrity finding still blocks completion. +7. Fix confirmed in-scope issues, confirm each fixed failure scenario with a test or a reproduction, and run proportionate regression tests. After fixing a blocker, high-severity or data-integrity finding, or after any other material fix, review the changes made since the reviewed range with one new blind reviewer, started and briefed as in steps 2 to 5; when uncommitted new changes cannot be separated, review the whole working-tree range again. +8. Track findings by underlying invariant or failure scenario, not wording. Run at most three review rounds for one implementation, and end the gate in one of two ways: + - If the third round's validated in-scope findings are all medium or low and none concerns data integrity, finish without another round: fix the small, localized findings, confirm each with a test or a reproduction, and list the rest in the final report. + - If the third round reports a validated in-scope blocker, high-severity or data-integrity finding, or earlier if review and repair begin cycling, patches contradict earlier patches, or the same invariant repeatedly fails, stop patching and reassess the design: ownership, component boundaries, state model, data flow, contracts, and test strategy. A corrected design that fits within the task boundaries, which come from the user, goes through this gate once as a new implementation. If the design holds, or the task boundaries themselves look wrong, stop and report to the user. +9. If the design-level correction reaches either condition of the second case, stop and report the unresolved condition, review history, conflicting constraints, and viable options. Never start a second correction or broaden the task. +10. Completion requires no validated in-scope blocker, high-severity or data-integrity finding, all relevant checks passing, and a final primary-agent audit of the complete diff. The reviewer count is a review-quality gate, not a requirement to split the implementation into multiple pull requests. From bfdb1aa4fe1da081e62b2d84eecec23bbea6b690 Mon Sep 17 00:00:00 2001 From: saladday <1203511142@qq.com> Date: Tue, 17 Nov 2026 14:48:27 +0800 Subject: [PATCH 21/23] chore(release): prepare v5.11.4 --- CHANGELOG.md | 77 ++++++++++++++++++++++++++++++++-- README.md | 2 +- README_JA.md | 2 +- README_ZH.md | 2 +- docs/CHANGELOG.md | 77 ++++++++++++++++++++++++++++++++-- docs/releases/v5.11.4.md | 90 ++++++++++++++++++++++++++++++++++++++++ src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- 8 files changed, 241 insertions(+), 13 deletions(-) create mode 100644 docs/releases/v5.11.4.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 5749db53..3fb2ccdc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,15 +9,84 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [5.11.4] - 2026-11-17 + +### Added + +- **Codex / Official Accounts**: Select a managed ChatGPT account in the OpenAI Official provider form, or keep the native Codex login. Account activation preserves the previous native login and follows upstream credential ownership and refresh behavior. Includes [#550](https://github.com/SaladDay/cc-switch-cli/pull/550), fixing [#547](https://github.com/SaladDay/cc-switch-cli/issues/547). +- **Sponsors**: Add IPWO to the sixth README sponsor position across the English, Chinese and Japanese documentation. + +### Changed + +- **Claude / Configuration Editing**: Edit the complete Claude configuration, saving provider fields to the provider record and global settings to the live configuration, with conflict handling for external changes. Legacy Claude common snippets remain readable but are no longer merged at runtime or newly written. Includes [#536](https://github.com/SaladDay/cc-switch-cli/pull/536), addressing [#530](https://github.com/SaladDay/cc-switch-cli/issues/530). +- **Presets / Pricing**: Refresh bundled model templates, model capabilities and pricing seeds against upstream. Existing custom prices are preserved; historical built-in prices are repaired only when they still match known defaults. Includes [#548](https://github.com/SaladDay/cc-switch-cli/pull/548). + ### Fixed -- **TUI**: Exit when the input terminal hangs up, including terminal proxies that do not deliver SIGHUP, instead of leaving a process spinning at full CPU. -- **Database / Compatibility**: Support database schemas 23 through 26 from upstream, fixing WebDAV/S3 restore failures with `Remote database schema is too new (24); this app supports up to 22`. Align the migration steps, MCP/Skills enablement columns, and session-log parser state with the shared schema while preserving upstream flags and parser state through upgrades, edits, runtime cursor updates, and sync round-trips. +- **Database / Compatibility**: Support upstream database schemas 23 through 26 for local startup and WebDAV/S3 restore, including snapshots from CC Switch desktop v4.0.33. Preserve upstream MCP/Skills enablement flags and session parser state through migrations, edits and sync round-trips. Includes [#549](https://github.com/SaladDay/cc-switch-cli/pull/549), fixing [#553](https://github.com/SaladDay/cc-switch-cli/issues/553) and addressing [#564](https://github.com/SaladDay/cc-switch-cli/issues/564). +- **WebDAV / Skills**: Preserve each file symlink's own name in skills archives, avoiding duplicate ZIP entries such as `CLAUDE.md -> AGENTS.md`. Directory cycle detection and outside-root restrictions remain intact. Includes [#559](https://github.com/SaladDay/cc-switch-cli/pull/559). +- **TUI / Terminal Hangup**: Exit the Unix TUI when its terminal disconnects, preventing an input polling loop from consuming a CPU core. Normal connected-terminal exits still restore terminal state. Includes [#558](https://github.com/SaladDay/cc-switch-cli/pull/558), fixing [#555](https://github.com/SaladDay/cc-switch-cli/issues/555). +- **Windows / Sessions**: Release child lock handles before publishing or retiring session snapshot directories, fixing `Access is denied (os error 5)` while preserving reader protection. Includes [#552](https://github.com/SaladDay/cc-switch-cli/pull/552), fixing [#542](https://github.com/SaladDay/cc-switch-cli/issues/542). +- **Claude / Proxy Authentication**: Use `ANTHROPIC_AUTH_TOKEN` for ordinary proxy-route placeholders and clear stale `ANTHROPIC_API_KEY` values, avoiding custom-key confirmation and conflicting credential warnings. Includes [#556](https://github.com/SaladDay/cc-switch-cli/pull/556), fixing [#554](https://github.com/SaladDay/cc-switch-cli/issues/554). +- **Proxy / Responses**: Emit `response.incomplete` for incomplete converted Codex responses and retain their usage and Chat history, so truncated turns are not reported as successful completions. Includes [#551](https://github.com/SaladDay/cc-switch-cli/pull/551), fixing [#546](https://github.com/SaladDay/cc-switch-cli/issues/546). +- **Proxy / Prompt Caching**: Keep mid-conversation system messages in their original positions during Anthropic-to-Chat conversion, preserving stable prompt prefixes across turns. Includes [#527](https://github.com/SaladDay/cc-switch-cli/pull/527). +- **Codex / Configuration**: Preserve explicit authentication settings and existing bearer credentials when editing provider forms. Omit the unsupported MCP `type` field from generated Codex TOML. Includes [#535](https://github.com/SaladDay/cc-switch-cli/pull/535) and [#512](https://github.com/SaladDay/cc-switch-cli/pull/512), addressing [#532](https://github.com/SaladDay/cc-switch-cli/issues/532) and [#496](https://github.com/SaladDay/cc-switch-cli/issues/496). +- **Codex OAuth / Quotas**: Use the bound account's native quota query for managed OAuth providers and hide the conflicting generic usage-template control in the Claude provider form. Existing automatic and manual refresh behavior is preserved. Includes [#534](https://github.com/SaladDay/cc-switch-cli/pull/534), fixing [#533](https://github.com/SaladDay/cc-switch-cli/issues/533). ### Upgrade notes -- Databases newer than schema 26 are still rejected. After migrating to schema 26, older CLI versions (v5.11.3 and earlier) cannot open the upgraded database. -- This release adds database compatibility, not CLI management for Oh My Pi, DeepSeek Harness, GitHub Copilot CLI, or WorkBuddy. +- Upgrade all CLI devices and containers before sharing a schema-26 database. CLI v5.11.3 and earlier cannot open it. Existing pre-migration backups remain in place; databases newer than schema 26, including upstream development schema 27, are still rejected. +- Database compatibility does not add CLI management for Oh My Pi, DeepSeek Harness, GitHub Copilot CLI or WorkBuddy. +- Managed ChatGPT accounts are not supported by isolated launches (`start`, TUI temporary launch or `--shared-sessions`). Switch to the bound official provider first, then run `codex`. +- Claude global settings should be edited through the complete configuration editor. Codex and Gemini common-snippet behavior is unchanged. Incomplete Codex responses can now surface a truncation or refusal error instead of silently completing. +- Run `cc-switch update`, or use `brew upgrade cc-switch-cli` for Homebrew installations once the formula is updated. + +### Thanks + +Thank you to everyone who opened an issue or pull request, shared diagnostics, reviewed code, or joined a discussion. The list below covers issues and pull requests active since v5.11.3, including earlier participants in those discussions and commit co-authors. Contributions that remain open or were not merged are included in these thanks, not in the release's feature list. + +| Contributor | Issues and pull requests | +| --- | --- | +| [@3aKHP](https://github.com/3aKHP) | [#496](https://github.com/SaladDay/cc-switch-cli/issues/496) | +| [@Alemax067](https://github.com/Alemax067) | [#547](https://github.com/SaladDay/cc-switch-cli/issues/547) | +| [@AloneAtWar](https://github.com/AloneAtWar) | [#135](https://github.com/SaladDay/cc-switch-cli/pull/135) | +| [@AtaraxiaEpiphany](https://github.com/AtaraxiaEpiphany) | [#522](https://github.com/SaladDay/cc-switch-cli/pull/522) | +| [@badcodebuilder](https://github.com/badcodebuilder) | [#554](https://github.com/SaladDay/cc-switch-cli/issues/554) | +| [@bytemain](https://github.com/bytemain) | [#467](https://github.com/SaladDay/cc-switch-cli/pull/467) | +| [@claude](https://github.com/claude) | [#551](https://github.com/SaladDay/cc-switch-cli/pull/551) | +| [@CodeCatMeow](https://github.com/CodeCatMeow) | [#403](https://github.com/SaladDay/cc-switch-cli/issues/403) | +| [@cxwx](https://github.com/cxwx) | [#526](https://github.com/SaladDay/cc-switch-cli/issues/526) | +| [@Cyclonekid](https://github.com/Cyclonekid) | [#530](https://github.com/SaladDay/cc-switch-cli/issues/530) | +| [@feicai922](https://github.com/feicai922) | [#516](https://github.com/SaladDay/cc-switch-cli/issues/516) | +| [@fengyunzaidushi](https://github.com/fengyunzaidushi) | [#8](https://github.com/SaladDay/cc-switch-cli/issues/8), [#532](https://github.com/SaladDay/cc-switch-cli/issues/532) | +| [@GalaxyKW](https://github.com/GalaxyKW) | [#514](https://github.com/SaladDay/cc-switch-cli/pull/514) | +| [@GOTOgxy](https://github.com/GOTOgxy) | [#564](https://github.com/SaladDay/cc-switch-cli/issues/564) | +| [@hao-lin-lwh](https://github.com/hao-lin-lwh) | [#525](https://github.com/SaladDay/cc-switch-cli/issues/525) | +| [@HappyLiang12](https://github.com/HappyLiang12) | [#539](https://github.com/SaladDay/cc-switch-cli/issues/539) | +| [@heydryft](https://github.com/heydryft) | [#545](https://github.com/SaladDay/cc-switch-cli/pull/545) | +| [@Holmestime](https://github.com/Holmestime) | [#8](https://github.com/SaladDay/cc-switch-cli/issues/8) | +| [@jiwei-dot](https://github.com/jiwei-dot) | [#546](https://github.com/SaladDay/cc-switch-cli/issues/546) | +| [@kelvkhiu](https://github.com/kelvkhiu) | [#403](https://github.com/SaladDay/cc-switch-cli/issues/403), [#526](https://github.com/SaladDay/cc-switch-cli/issues/526), [#553](https://github.com/SaladDay/cc-switch-cli/issues/553) | +| [@kimjinzhan](https://github.com/kimjinzhan) | [#562](https://github.com/SaladDay/cc-switch-cli/issues/562) | +| [@laughmaker2024](https://github.com/laughmaker2024) | [#555](https://github.com/SaladDay/cc-switch-cli/issues/555) | +| [@lztxwd6666](https://github.com/lztxwd6666) | [#563](https://github.com/SaladDay/cc-switch-cli/pull/563) | +| [@RGB-loop](https://github.com/RGB-loop) | [#496](https://github.com/SaladDay/cc-switch-cli/issues/496), [#512](https://github.com/SaladDay/cc-switch-cli/pull/512), [#521](https://github.com/SaladDay/cc-switch-cli/pull/521), [#551](https://github.com/SaladDay/cc-switch-cli/pull/551) | +| [@SaladDay](https://github.com/SaladDay) | [#8](https://github.com/SaladDay/cc-switch-cli/issues/8), [#467](https://github.com/SaladDay/cc-switch-cli/pull/467), [#496](https://github.com/SaladDay/cc-switch-cli/issues/496), [#512](https://github.com/SaladDay/cc-switch-cli/pull/512), [#516](https://github.com/SaladDay/cc-switch-cli/issues/516), [#526](https://github.com/SaladDay/cc-switch-cli/issues/526), [#527](https://github.com/SaladDay/cc-switch-cli/pull/527), [#530](https://github.com/SaladDay/cc-switch-cli/issues/530), [#531](https://github.com/SaladDay/cc-switch-cli/pull/531), [#532](https://github.com/SaladDay/cc-switch-cli/issues/532), [#534](https://github.com/SaladDay/cc-switch-cli/pull/534), [#535](https://github.com/SaladDay/cc-switch-cli/pull/535), [#536](https://github.com/SaladDay/cc-switch-cli/pull/536), [#537](https://github.com/SaladDay/cc-switch-cli/issues/537), [#539](https://github.com/SaladDay/cc-switch-cli/issues/539), [#540](https://github.com/SaladDay/cc-switch-cli/issues/540), [#541](https://github.com/SaladDay/cc-switch-cli/issues/541), [#542](https://github.com/SaladDay/cc-switch-cli/issues/542), [#545](https://github.com/SaladDay/cc-switch-cli/pull/545), [#546](https://github.com/SaladDay/cc-switch-cli/issues/546), [#547](https://github.com/SaladDay/cc-switch-cli/issues/547), [#548](https://github.com/SaladDay/cc-switch-cli/pull/548), [#549](https://github.com/SaladDay/cc-switch-cli/pull/549), [#550](https://github.com/SaladDay/cc-switch-cli/pull/550), [#551](https://github.com/SaladDay/cc-switch-cli/pull/551), [#552](https://github.com/SaladDay/cc-switch-cli/pull/552), [#553](https://github.com/SaladDay/cc-switch-cli/issues/553), [#554](https://github.com/SaladDay/cc-switch-cli/issues/554), [#555](https://github.com/SaladDay/cc-switch-cli/issues/555), [#556](https://github.com/SaladDay/cc-switch-cli/pull/556), [#557](https://github.com/SaladDay/cc-switch-cli/pull/557), [#558](https://github.com/SaladDay/cc-switch-cli/pull/558), [#559](https://github.com/SaladDay/cc-switch-cli/pull/559), [#560](https://github.com/SaladDay/cc-switch-cli/pull/560), [#561](https://github.com/SaladDay/cc-switch-cli/pull/561), [#564](https://github.com/SaladDay/cc-switch-cli/issues/564) | +| [@SanAntonio021](https://github.com/SanAntonio021) | [#523](https://github.com/SaladDay/cc-switch-cli/pull/523), [#524](https://github.com/SaladDay/cc-switch-cli/pull/524), [#531](https://github.com/SaladDay/cc-switch-cli/pull/531) | +| [@sermady](https://github.com/sermady) | [#541](https://github.com/SaladDay/cc-switch-cli/issues/541) | +| [@stan-lei](https://github.com/stan-lei) | [#549](https://github.com/SaladDay/cc-switch-cli/pull/549), [#553](https://github.com/SaladDay/cc-switch-cli/issues/553) | +| [@SunriseOrient](https://github.com/SunriseOrient) | [#135](https://github.com/SaladDay/cc-switch-cli/pull/135) | +| [@Super-Dian](https://github.com/Super-Dian) | [#554](https://github.com/SaladDay/cc-switch-cli/issues/554) | +| [@tao-deng](https://github.com/tao-deng) | [#498](https://github.com/SaladDay/cc-switch-cli/pull/498) | +| [@usufu](https://github.com/usufu) | [#540](https://github.com/SaladDay/cc-switch-cli/issues/540) | +| [@Xiao-Maker-droid](https://github.com/Xiao-Maker-droid) | [#527](https://github.com/SaladDay/cc-switch-cli/pull/527) | +| [@xiaoma404](https://github.com/xiaoma404) | [#538](https://github.com/SaladDay/cc-switch-cli/pull/538) | +| [@xuyinkui](https://github.com/xuyinkui) | [#8](https://github.com/SaladDay/cc-switch-cli/issues/8) | +| [@ycwfs](https://github.com/ycwfs) | [#537](https://github.com/SaladDay/cc-switch-cli/issues/537) | +| [@zczsyqxl](https://github.com/zczsyqxl) | [#542](https://github.com/SaladDay/cc-switch-cli/issues/542), [#543](https://github.com/SaladDay/cc-switch-cli/issues/543) | +| [@zydo](https://github.com/zydo) | [#403](https://github.com/SaladDay/cc-switch-cli/issues/403), [#533](https://github.com/SaladDay/cc-switch-cli/issues/533), [#534](https://github.com/SaladDay/cc-switch-cli/pull/534), [#544](https://github.com/SaladDay/cc-switch-cli/pull/544), [#548](https://github.com/SaladDay/cc-switch-cli/pull/548) | + +Thanks also to IPWO and our other sponsors, everyone supporting and using the project, and the CC-Switch maintainers and contributors whose upstream work underpins these improvements. ## [5.11.3] - 2026-10-22 diff --git a/README.md b/README.md index 82b80904..5439391a 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ **Manage Claude Code, Codex, Gemini, OpenCode, Hermes, OpenClaw, and Pi from one interactive TUI or scriptable CLI.** -[![Version](https://img.shields.io/badge/version-5.11.3-blue.svg)](https://github.com/saladday/cc-switch-cli/releases) +[![Version](https://img.shields.io/badge/version-5.11.4-blue.svg)](https://github.com/saladday/cc-switch-cli/releases) [![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-lightgrey.svg)](https://github.com/saladday/cc-switch-cli/releases) [![Built with Rust](https://img.shields.io/badge/built%20with-Rust-orange.svg)](https://www.rust-lang.org/) [![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE) diff --git a/README_JA.md b/README_JA.md index 3ded4984..f8a9c605 100644 --- a/README_JA.md +++ b/README_JA.md @@ -6,7 +6,7 @@ **対話型 TUI またはスクリプトで利用できる CLI から、Claude Code、Codex、Gemini、OpenCode、Hermes、OpenClaw、Pi を一元管理できます。** -[![バージョン](https://img.shields.io/badge/version-5.11.3-blue.svg)](https://github.com/saladday/cc-switch-cli/releases) +[![バージョン](https://img.shields.io/badge/version-5.11.4-blue.svg)](https://github.com/saladday/cc-switch-cli/releases) [![対応プラットフォーム](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-lightgrey.svg)](https://github.com/saladday/cc-switch-cli/releases) [![Rust 製](https://img.shields.io/badge/built%20with-Rust-orange.svg)](https://www.rust-lang.org/) [![ライセンス](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE) diff --git a/README_ZH.md b/README_ZH.md index 045fb331..825aab47 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -6,7 +6,7 @@ **通过交互式 TUI 或脚本化 CLI,统一管理 Claude Code、Codex、Gemini、OpenCode、Hermes、OpenClaw 和 Pi。** -[![Version](https://img.shields.io/badge/version-5.11.3-blue.svg)](https://github.com/saladday/cc-switch-cli/releases) +[![Version](https://img.shields.io/badge/version-5.11.4-blue.svg)](https://github.com/saladday/cc-switch-cli/releases) [![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-lightgrey.svg)](https://github.com/saladday/cc-switch-cli/releases) [![Built with Rust](https://img.shields.io/badge/built%20with-Rust-orange.svg)](https://www.rust-lang.org/) [![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 5749db53..3fb2ccdc 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -9,15 +9,84 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [5.11.4] - 2026-11-17 + +### Added + +- **Codex / Official Accounts**: Select a managed ChatGPT account in the OpenAI Official provider form, or keep the native Codex login. Account activation preserves the previous native login and follows upstream credential ownership and refresh behavior. Includes [#550](https://github.com/SaladDay/cc-switch-cli/pull/550), fixing [#547](https://github.com/SaladDay/cc-switch-cli/issues/547). +- **Sponsors**: Add IPWO to the sixth README sponsor position across the English, Chinese and Japanese documentation. + +### Changed + +- **Claude / Configuration Editing**: Edit the complete Claude configuration, saving provider fields to the provider record and global settings to the live configuration, with conflict handling for external changes. Legacy Claude common snippets remain readable but are no longer merged at runtime or newly written. Includes [#536](https://github.com/SaladDay/cc-switch-cli/pull/536), addressing [#530](https://github.com/SaladDay/cc-switch-cli/issues/530). +- **Presets / Pricing**: Refresh bundled model templates, model capabilities and pricing seeds against upstream. Existing custom prices are preserved; historical built-in prices are repaired only when they still match known defaults. Includes [#548](https://github.com/SaladDay/cc-switch-cli/pull/548). + ### Fixed -- **TUI**: Exit when the input terminal hangs up, including terminal proxies that do not deliver SIGHUP, instead of leaving a process spinning at full CPU. -- **Database / Compatibility**: Support database schemas 23 through 26 from upstream, fixing WebDAV/S3 restore failures with `Remote database schema is too new (24); this app supports up to 22`. Align the migration steps, MCP/Skills enablement columns, and session-log parser state with the shared schema while preserving upstream flags and parser state through upgrades, edits, runtime cursor updates, and sync round-trips. +- **Database / Compatibility**: Support upstream database schemas 23 through 26 for local startup and WebDAV/S3 restore, including snapshots from CC Switch desktop v4.0.33. Preserve upstream MCP/Skills enablement flags and session parser state through migrations, edits and sync round-trips. Includes [#549](https://github.com/SaladDay/cc-switch-cli/pull/549), fixing [#553](https://github.com/SaladDay/cc-switch-cli/issues/553) and addressing [#564](https://github.com/SaladDay/cc-switch-cli/issues/564). +- **WebDAV / Skills**: Preserve each file symlink's own name in skills archives, avoiding duplicate ZIP entries such as `CLAUDE.md -> AGENTS.md`. Directory cycle detection and outside-root restrictions remain intact. Includes [#559](https://github.com/SaladDay/cc-switch-cli/pull/559). +- **TUI / Terminal Hangup**: Exit the Unix TUI when its terminal disconnects, preventing an input polling loop from consuming a CPU core. Normal connected-terminal exits still restore terminal state. Includes [#558](https://github.com/SaladDay/cc-switch-cli/pull/558), fixing [#555](https://github.com/SaladDay/cc-switch-cli/issues/555). +- **Windows / Sessions**: Release child lock handles before publishing or retiring session snapshot directories, fixing `Access is denied (os error 5)` while preserving reader protection. Includes [#552](https://github.com/SaladDay/cc-switch-cli/pull/552), fixing [#542](https://github.com/SaladDay/cc-switch-cli/issues/542). +- **Claude / Proxy Authentication**: Use `ANTHROPIC_AUTH_TOKEN` for ordinary proxy-route placeholders and clear stale `ANTHROPIC_API_KEY` values, avoiding custom-key confirmation and conflicting credential warnings. Includes [#556](https://github.com/SaladDay/cc-switch-cli/pull/556), fixing [#554](https://github.com/SaladDay/cc-switch-cli/issues/554). +- **Proxy / Responses**: Emit `response.incomplete` for incomplete converted Codex responses and retain their usage and Chat history, so truncated turns are not reported as successful completions. Includes [#551](https://github.com/SaladDay/cc-switch-cli/pull/551), fixing [#546](https://github.com/SaladDay/cc-switch-cli/issues/546). +- **Proxy / Prompt Caching**: Keep mid-conversation system messages in their original positions during Anthropic-to-Chat conversion, preserving stable prompt prefixes across turns. Includes [#527](https://github.com/SaladDay/cc-switch-cli/pull/527). +- **Codex / Configuration**: Preserve explicit authentication settings and existing bearer credentials when editing provider forms. Omit the unsupported MCP `type` field from generated Codex TOML. Includes [#535](https://github.com/SaladDay/cc-switch-cli/pull/535) and [#512](https://github.com/SaladDay/cc-switch-cli/pull/512), addressing [#532](https://github.com/SaladDay/cc-switch-cli/issues/532) and [#496](https://github.com/SaladDay/cc-switch-cli/issues/496). +- **Codex OAuth / Quotas**: Use the bound account's native quota query for managed OAuth providers and hide the conflicting generic usage-template control in the Claude provider form. Existing automatic and manual refresh behavior is preserved. Includes [#534](https://github.com/SaladDay/cc-switch-cli/pull/534), fixing [#533](https://github.com/SaladDay/cc-switch-cli/issues/533). ### Upgrade notes -- Databases newer than schema 26 are still rejected. After migrating to schema 26, older CLI versions (v5.11.3 and earlier) cannot open the upgraded database. -- This release adds database compatibility, not CLI management for Oh My Pi, DeepSeek Harness, GitHub Copilot CLI, or WorkBuddy. +- Upgrade all CLI devices and containers before sharing a schema-26 database. CLI v5.11.3 and earlier cannot open it. Existing pre-migration backups remain in place; databases newer than schema 26, including upstream development schema 27, are still rejected. +- Database compatibility does not add CLI management for Oh My Pi, DeepSeek Harness, GitHub Copilot CLI or WorkBuddy. +- Managed ChatGPT accounts are not supported by isolated launches (`start`, TUI temporary launch or `--shared-sessions`). Switch to the bound official provider first, then run `codex`. +- Claude global settings should be edited through the complete configuration editor. Codex and Gemini common-snippet behavior is unchanged. Incomplete Codex responses can now surface a truncation or refusal error instead of silently completing. +- Run `cc-switch update`, or use `brew upgrade cc-switch-cli` for Homebrew installations once the formula is updated. + +### Thanks + +Thank you to everyone who opened an issue or pull request, shared diagnostics, reviewed code, or joined a discussion. The list below covers issues and pull requests active since v5.11.3, including earlier participants in those discussions and commit co-authors. Contributions that remain open or were not merged are included in these thanks, not in the release's feature list. + +| Contributor | Issues and pull requests | +| --- | --- | +| [@3aKHP](https://github.com/3aKHP) | [#496](https://github.com/SaladDay/cc-switch-cli/issues/496) | +| [@Alemax067](https://github.com/Alemax067) | [#547](https://github.com/SaladDay/cc-switch-cli/issues/547) | +| [@AloneAtWar](https://github.com/AloneAtWar) | [#135](https://github.com/SaladDay/cc-switch-cli/pull/135) | +| [@AtaraxiaEpiphany](https://github.com/AtaraxiaEpiphany) | [#522](https://github.com/SaladDay/cc-switch-cli/pull/522) | +| [@badcodebuilder](https://github.com/badcodebuilder) | [#554](https://github.com/SaladDay/cc-switch-cli/issues/554) | +| [@bytemain](https://github.com/bytemain) | [#467](https://github.com/SaladDay/cc-switch-cli/pull/467) | +| [@claude](https://github.com/claude) | [#551](https://github.com/SaladDay/cc-switch-cli/pull/551) | +| [@CodeCatMeow](https://github.com/CodeCatMeow) | [#403](https://github.com/SaladDay/cc-switch-cli/issues/403) | +| [@cxwx](https://github.com/cxwx) | [#526](https://github.com/SaladDay/cc-switch-cli/issues/526) | +| [@Cyclonekid](https://github.com/Cyclonekid) | [#530](https://github.com/SaladDay/cc-switch-cli/issues/530) | +| [@feicai922](https://github.com/feicai922) | [#516](https://github.com/SaladDay/cc-switch-cli/issues/516) | +| [@fengyunzaidushi](https://github.com/fengyunzaidushi) | [#8](https://github.com/SaladDay/cc-switch-cli/issues/8), [#532](https://github.com/SaladDay/cc-switch-cli/issues/532) | +| [@GalaxyKW](https://github.com/GalaxyKW) | [#514](https://github.com/SaladDay/cc-switch-cli/pull/514) | +| [@GOTOgxy](https://github.com/GOTOgxy) | [#564](https://github.com/SaladDay/cc-switch-cli/issues/564) | +| [@hao-lin-lwh](https://github.com/hao-lin-lwh) | [#525](https://github.com/SaladDay/cc-switch-cli/issues/525) | +| [@HappyLiang12](https://github.com/HappyLiang12) | [#539](https://github.com/SaladDay/cc-switch-cli/issues/539) | +| [@heydryft](https://github.com/heydryft) | [#545](https://github.com/SaladDay/cc-switch-cli/pull/545) | +| [@Holmestime](https://github.com/Holmestime) | [#8](https://github.com/SaladDay/cc-switch-cli/issues/8) | +| [@jiwei-dot](https://github.com/jiwei-dot) | [#546](https://github.com/SaladDay/cc-switch-cli/issues/546) | +| [@kelvkhiu](https://github.com/kelvkhiu) | [#403](https://github.com/SaladDay/cc-switch-cli/issues/403), [#526](https://github.com/SaladDay/cc-switch-cli/issues/526), [#553](https://github.com/SaladDay/cc-switch-cli/issues/553) | +| [@kimjinzhan](https://github.com/kimjinzhan) | [#562](https://github.com/SaladDay/cc-switch-cli/issues/562) | +| [@laughmaker2024](https://github.com/laughmaker2024) | [#555](https://github.com/SaladDay/cc-switch-cli/issues/555) | +| [@lztxwd6666](https://github.com/lztxwd6666) | [#563](https://github.com/SaladDay/cc-switch-cli/pull/563) | +| [@RGB-loop](https://github.com/RGB-loop) | [#496](https://github.com/SaladDay/cc-switch-cli/issues/496), [#512](https://github.com/SaladDay/cc-switch-cli/pull/512), [#521](https://github.com/SaladDay/cc-switch-cli/pull/521), [#551](https://github.com/SaladDay/cc-switch-cli/pull/551) | +| [@SaladDay](https://github.com/SaladDay) | [#8](https://github.com/SaladDay/cc-switch-cli/issues/8), [#467](https://github.com/SaladDay/cc-switch-cli/pull/467), [#496](https://github.com/SaladDay/cc-switch-cli/issues/496), [#512](https://github.com/SaladDay/cc-switch-cli/pull/512), [#516](https://github.com/SaladDay/cc-switch-cli/issues/516), [#526](https://github.com/SaladDay/cc-switch-cli/issues/526), [#527](https://github.com/SaladDay/cc-switch-cli/pull/527), [#530](https://github.com/SaladDay/cc-switch-cli/issues/530), [#531](https://github.com/SaladDay/cc-switch-cli/pull/531), [#532](https://github.com/SaladDay/cc-switch-cli/issues/532), [#534](https://github.com/SaladDay/cc-switch-cli/pull/534), [#535](https://github.com/SaladDay/cc-switch-cli/pull/535), [#536](https://github.com/SaladDay/cc-switch-cli/pull/536), [#537](https://github.com/SaladDay/cc-switch-cli/issues/537), [#539](https://github.com/SaladDay/cc-switch-cli/issues/539), [#540](https://github.com/SaladDay/cc-switch-cli/issues/540), [#541](https://github.com/SaladDay/cc-switch-cli/issues/541), [#542](https://github.com/SaladDay/cc-switch-cli/issues/542), [#545](https://github.com/SaladDay/cc-switch-cli/pull/545), [#546](https://github.com/SaladDay/cc-switch-cli/issues/546), [#547](https://github.com/SaladDay/cc-switch-cli/issues/547), [#548](https://github.com/SaladDay/cc-switch-cli/pull/548), [#549](https://github.com/SaladDay/cc-switch-cli/pull/549), [#550](https://github.com/SaladDay/cc-switch-cli/pull/550), [#551](https://github.com/SaladDay/cc-switch-cli/pull/551), [#552](https://github.com/SaladDay/cc-switch-cli/pull/552), [#553](https://github.com/SaladDay/cc-switch-cli/issues/553), [#554](https://github.com/SaladDay/cc-switch-cli/issues/554), [#555](https://github.com/SaladDay/cc-switch-cli/issues/555), [#556](https://github.com/SaladDay/cc-switch-cli/pull/556), [#557](https://github.com/SaladDay/cc-switch-cli/pull/557), [#558](https://github.com/SaladDay/cc-switch-cli/pull/558), [#559](https://github.com/SaladDay/cc-switch-cli/pull/559), [#560](https://github.com/SaladDay/cc-switch-cli/pull/560), [#561](https://github.com/SaladDay/cc-switch-cli/pull/561), [#564](https://github.com/SaladDay/cc-switch-cli/issues/564) | +| [@SanAntonio021](https://github.com/SanAntonio021) | [#523](https://github.com/SaladDay/cc-switch-cli/pull/523), [#524](https://github.com/SaladDay/cc-switch-cli/pull/524), [#531](https://github.com/SaladDay/cc-switch-cli/pull/531) | +| [@sermady](https://github.com/sermady) | [#541](https://github.com/SaladDay/cc-switch-cli/issues/541) | +| [@stan-lei](https://github.com/stan-lei) | [#549](https://github.com/SaladDay/cc-switch-cli/pull/549), [#553](https://github.com/SaladDay/cc-switch-cli/issues/553) | +| [@SunriseOrient](https://github.com/SunriseOrient) | [#135](https://github.com/SaladDay/cc-switch-cli/pull/135) | +| [@Super-Dian](https://github.com/Super-Dian) | [#554](https://github.com/SaladDay/cc-switch-cli/issues/554) | +| [@tao-deng](https://github.com/tao-deng) | [#498](https://github.com/SaladDay/cc-switch-cli/pull/498) | +| [@usufu](https://github.com/usufu) | [#540](https://github.com/SaladDay/cc-switch-cli/issues/540) | +| [@Xiao-Maker-droid](https://github.com/Xiao-Maker-droid) | [#527](https://github.com/SaladDay/cc-switch-cli/pull/527) | +| [@xiaoma404](https://github.com/xiaoma404) | [#538](https://github.com/SaladDay/cc-switch-cli/pull/538) | +| [@xuyinkui](https://github.com/xuyinkui) | [#8](https://github.com/SaladDay/cc-switch-cli/issues/8) | +| [@ycwfs](https://github.com/ycwfs) | [#537](https://github.com/SaladDay/cc-switch-cli/issues/537) | +| [@zczsyqxl](https://github.com/zczsyqxl) | [#542](https://github.com/SaladDay/cc-switch-cli/issues/542), [#543](https://github.com/SaladDay/cc-switch-cli/issues/543) | +| [@zydo](https://github.com/zydo) | [#403](https://github.com/SaladDay/cc-switch-cli/issues/403), [#533](https://github.com/SaladDay/cc-switch-cli/issues/533), [#534](https://github.com/SaladDay/cc-switch-cli/pull/534), [#544](https://github.com/SaladDay/cc-switch-cli/pull/544), [#548](https://github.com/SaladDay/cc-switch-cli/pull/548) | + +Thanks also to IPWO and our other sponsors, everyone supporting and using the project, and the CC-Switch maintainers and contributors whose upstream work underpins these improvements. ## [5.11.3] - 2026-10-22 diff --git a/docs/releases/v5.11.4.md b/docs/releases/v5.11.4.md new file mode 100644 index 00000000..5a3a7ad0 --- /dev/null +++ b/docs/releases/v5.11.4.md @@ -0,0 +1,90 @@ +# CC Switch CLI v5.11.4 + +This release restores database compatibility with CC Switch desktop v4.0.33 (schema 26), adds managed ChatGPT account selection for Codex, and fixes configuration, proxy, session and terminal issues. + +## Added + +- **Codex / Official Accounts**: Select a managed ChatGPT account in the OpenAI Official provider form, or keep the native Codex login. Account activation preserves the previous native login and follows upstream credential ownership and refresh behavior. Includes [#550](https://github.com/SaladDay/cc-switch-cli/pull/550), fixing [#547](https://github.com/SaladDay/cc-switch-cli/issues/547). +- **Sponsors**: Add IPWO to the sixth README sponsor position across the English, Chinese and Japanese documentation. + +## Changed + +- **Claude / Configuration Editing**: Edit the complete Claude configuration, saving provider fields to the provider record and global settings to the live configuration, with conflict handling for external changes. Legacy Claude common snippets remain readable but are no longer merged at runtime or newly written. Includes [#536](https://github.com/SaladDay/cc-switch-cli/pull/536), addressing [#530](https://github.com/SaladDay/cc-switch-cli/issues/530). +- **Presets / Pricing**: Refresh bundled model templates, model capabilities and pricing seeds against upstream. Existing custom prices are preserved; historical built-in prices are repaired only when they still match known defaults. Includes [#548](https://github.com/SaladDay/cc-switch-cli/pull/548). + +## Fixed + +- **Database / Compatibility**: Support upstream database schemas 23 through 26 for local startup and WebDAV/S3 restore, including snapshots from CC Switch desktop v4.0.33. Preserve upstream MCP/Skills enablement flags and session parser state through migrations, edits and sync round-trips. Includes [#549](https://github.com/SaladDay/cc-switch-cli/pull/549), fixing [#553](https://github.com/SaladDay/cc-switch-cli/issues/553) and addressing [#564](https://github.com/SaladDay/cc-switch-cli/issues/564). +- **WebDAV / Skills**: Preserve each file symlink's own name in skills archives, avoiding duplicate ZIP entries such as `CLAUDE.md -> AGENTS.md`. Directory cycle detection and outside-root restrictions remain intact. Includes [#559](https://github.com/SaladDay/cc-switch-cli/pull/559). +- **TUI / Terminal Hangup**: Exit the Unix TUI when its terminal disconnects, preventing an input polling loop from consuming a CPU core. Normal connected-terminal exits still restore terminal state. Includes [#558](https://github.com/SaladDay/cc-switch-cli/pull/558), fixing [#555](https://github.com/SaladDay/cc-switch-cli/issues/555). +- **Windows / Sessions**: Release child lock handles before publishing or retiring session snapshot directories, fixing `Access is denied (os error 5)` while preserving reader protection. Includes [#552](https://github.com/SaladDay/cc-switch-cli/pull/552), fixing [#542](https://github.com/SaladDay/cc-switch-cli/issues/542). +- **Claude / Proxy Authentication**: Use `ANTHROPIC_AUTH_TOKEN` for ordinary proxy-route placeholders and clear stale `ANTHROPIC_API_KEY` values, avoiding custom-key confirmation and conflicting credential warnings. Includes [#556](https://github.com/SaladDay/cc-switch-cli/pull/556), fixing [#554](https://github.com/SaladDay/cc-switch-cli/issues/554). +- **Proxy / Responses**: Emit `response.incomplete` for incomplete converted Codex responses and retain their usage and Chat history, so truncated turns are not reported as successful completions. Includes [#551](https://github.com/SaladDay/cc-switch-cli/pull/551), fixing [#546](https://github.com/SaladDay/cc-switch-cli/issues/546). +- **Proxy / Prompt Caching**: Keep mid-conversation system messages in their original positions during Anthropic-to-Chat conversion, preserving stable prompt prefixes across turns. Includes [#527](https://github.com/SaladDay/cc-switch-cli/pull/527). +- **Codex / Configuration**: Preserve explicit authentication settings and existing bearer credentials when editing provider forms. Omit the unsupported MCP `type` field from generated Codex TOML. Includes [#535](https://github.com/SaladDay/cc-switch-cli/pull/535) and [#512](https://github.com/SaladDay/cc-switch-cli/pull/512), addressing [#532](https://github.com/SaladDay/cc-switch-cli/issues/532) and [#496](https://github.com/SaladDay/cc-switch-cli/issues/496). +- **Codex OAuth / Quotas**: Use the bound account's native quota query for managed OAuth providers and hide the conflicting generic usage-template control in the Claude provider form. Existing automatic and manual refresh behavior is preserved. Includes [#534](https://github.com/SaladDay/cc-switch-cli/pull/534), fixing [#533](https://github.com/SaladDay/cc-switch-cli/issues/533). + +## Upgrade notes + +- Upgrade all CLI devices and containers before sharing a schema-26 database. CLI v5.11.3 and earlier cannot open it. Existing pre-migration backups remain in place; databases newer than schema 26, including upstream development schema 27, are still rejected. +- Database compatibility does not add CLI management for Oh My Pi, DeepSeek Harness, GitHub Copilot CLI or WorkBuddy. +- Managed ChatGPT accounts are not supported by isolated launches (`start`, TUI temporary launch or `--shared-sessions`). Switch to the bound official provider first, then run `codex`. +- Claude global settings should be edited through the complete configuration editor. Codex and Gemini common-snippet behavior is unchanged. Incomplete Codex responses can now surface a truncation or refusal error instead of silently completing. +- Run `cc-switch update`, or use `brew upgrade cc-switch-cli` for Homebrew installations once the formula is updated. + +## Thanks + +Thank you to everyone who opened an issue or pull request, shared diagnostics, reviewed code, or joined a discussion. The list below covers issues and pull requests active since v5.11.3, including earlier participants in those discussions and commit co-authors. Contributions that remain open or were not merged are included in these thanks, not in the release's feature list. + +| Contributor | Issues and pull requests | +| --- | --- | +| [@3aKHP](https://github.com/3aKHP) | [#496](https://github.com/SaladDay/cc-switch-cli/issues/496) | +| [@Alemax067](https://github.com/Alemax067) | [#547](https://github.com/SaladDay/cc-switch-cli/issues/547) | +| [@AloneAtWar](https://github.com/AloneAtWar) | [#135](https://github.com/SaladDay/cc-switch-cli/pull/135) | +| [@AtaraxiaEpiphany](https://github.com/AtaraxiaEpiphany) | [#522](https://github.com/SaladDay/cc-switch-cli/pull/522) | +| [@badcodebuilder](https://github.com/badcodebuilder) | [#554](https://github.com/SaladDay/cc-switch-cli/issues/554) | +| [@bytemain](https://github.com/bytemain) | [#467](https://github.com/SaladDay/cc-switch-cli/pull/467) | +| [@claude](https://github.com/claude) | [#551](https://github.com/SaladDay/cc-switch-cli/pull/551) | +| [@CodeCatMeow](https://github.com/CodeCatMeow) | [#403](https://github.com/SaladDay/cc-switch-cli/issues/403) | +| [@cxwx](https://github.com/cxwx) | [#526](https://github.com/SaladDay/cc-switch-cli/issues/526) | +| [@Cyclonekid](https://github.com/Cyclonekid) | [#530](https://github.com/SaladDay/cc-switch-cli/issues/530) | +| [@feicai922](https://github.com/feicai922) | [#516](https://github.com/SaladDay/cc-switch-cli/issues/516) | +| [@fengyunzaidushi](https://github.com/fengyunzaidushi) | [#8](https://github.com/SaladDay/cc-switch-cli/issues/8), [#532](https://github.com/SaladDay/cc-switch-cli/issues/532) | +| [@GalaxyKW](https://github.com/GalaxyKW) | [#514](https://github.com/SaladDay/cc-switch-cli/pull/514) | +| [@GOTOgxy](https://github.com/GOTOgxy) | [#564](https://github.com/SaladDay/cc-switch-cli/issues/564) | +| [@hao-lin-lwh](https://github.com/hao-lin-lwh) | [#525](https://github.com/SaladDay/cc-switch-cli/issues/525) | +| [@HappyLiang12](https://github.com/HappyLiang12) | [#539](https://github.com/SaladDay/cc-switch-cli/issues/539) | +| [@heydryft](https://github.com/heydryft) | [#545](https://github.com/SaladDay/cc-switch-cli/pull/545) | +| [@Holmestime](https://github.com/Holmestime) | [#8](https://github.com/SaladDay/cc-switch-cli/issues/8) | +| [@jiwei-dot](https://github.com/jiwei-dot) | [#546](https://github.com/SaladDay/cc-switch-cli/issues/546) | +| [@kelvkhiu](https://github.com/kelvkhiu) | [#403](https://github.com/SaladDay/cc-switch-cli/issues/403), [#526](https://github.com/SaladDay/cc-switch-cli/issues/526), [#553](https://github.com/SaladDay/cc-switch-cli/issues/553) | +| [@kimjinzhan](https://github.com/kimjinzhan) | [#562](https://github.com/SaladDay/cc-switch-cli/issues/562) | +| [@laughmaker2024](https://github.com/laughmaker2024) | [#555](https://github.com/SaladDay/cc-switch-cli/issues/555) | +| [@lztxwd6666](https://github.com/lztxwd6666) | [#563](https://github.com/SaladDay/cc-switch-cli/pull/563) | +| [@RGB-loop](https://github.com/RGB-loop) | [#496](https://github.com/SaladDay/cc-switch-cli/issues/496), [#512](https://github.com/SaladDay/cc-switch-cli/pull/512), [#521](https://github.com/SaladDay/cc-switch-cli/pull/521), [#551](https://github.com/SaladDay/cc-switch-cli/pull/551) | +| [@SaladDay](https://github.com/SaladDay) | [#8](https://github.com/SaladDay/cc-switch-cli/issues/8), [#467](https://github.com/SaladDay/cc-switch-cli/pull/467), [#496](https://github.com/SaladDay/cc-switch-cli/issues/496), [#512](https://github.com/SaladDay/cc-switch-cli/pull/512), [#516](https://github.com/SaladDay/cc-switch-cli/issues/516), [#526](https://github.com/SaladDay/cc-switch-cli/issues/526), [#527](https://github.com/SaladDay/cc-switch-cli/pull/527), [#530](https://github.com/SaladDay/cc-switch-cli/issues/530), [#531](https://github.com/SaladDay/cc-switch-cli/pull/531), [#532](https://github.com/SaladDay/cc-switch-cli/issues/532), [#534](https://github.com/SaladDay/cc-switch-cli/pull/534), [#535](https://github.com/SaladDay/cc-switch-cli/pull/535), [#536](https://github.com/SaladDay/cc-switch-cli/pull/536), [#537](https://github.com/SaladDay/cc-switch-cli/issues/537), [#539](https://github.com/SaladDay/cc-switch-cli/issues/539), [#540](https://github.com/SaladDay/cc-switch-cli/issues/540), [#541](https://github.com/SaladDay/cc-switch-cli/issues/541), [#542](https://github.com/SaladDay/cc-switch-cli/issues/542), [#545](https://github.com/SaladDay/cc-switch-cli/pull/545), [#546](https://github.com/SaladDay/cc-switch-cli/issues/546), [#547](https://github.com/SaladDay/cc-switch-cli/issues/547), [#548](https://github.com/SaladDay/cc-switch-cli/pull/548), [#549](https://github.com/SaladDay/cc-switch-cli/pull/549), [#550](https://github.com/SaladDay/cc-switch-cli/pull/550), [#551](https://github.com/SaladDay/cc-switch-cli/pull/551), [#552](https://github.com/SaladDay/cc-switch-cli/pull/552), [#553](https://github.com/SaladDay/cc-switch-cli/issues/553), [#554](https://github.com/SaladDay/cc-switch-cli/issues/554), [#555](https://github.com/SaladDay/cc-switch-cli/issues/555), [#556](https://github.com/SaladDay/cc-switch-cli/pull/556), [#557](https://github.com/SaladDay/cc-switch-cli/pull/557), [#558](https://github.com/SaladDay/cc-switch-cli/pull/558), [#559](https://github.com/SaladDay/cc-switch-cli/pull/559), [#560](https://github.com/SaladDay/cc-switch-cli/pull/560), [#561](https://github.com/SaladDay/cc-switch-cli/pull/561), [#564](https://github.com/SaladDay/cc-switch-cli/issues/564) | +| [@SanAntonio021](https://github.com/SanAntonio021) | [#523](https://github.com/SaladDay/cc-switch-cli/pull/523), [#524](https://github.com/SaladDay/cc-switch-cli/pull/524), [#531](https://github.com/SaladDay/cc-switch-cli/pull/531) | +| [@sermady](https://github.com/sermady) | [#541](https://github.com/SaladDay/cc-switch-cli/issues/541) | +| [@stan-lei](https://github.com/stan-lei) | [#549](https://github.com/SaladDay/cc-switch-cli/pull/549), [#553](https://github.com/SaladDay/cc-switch-cli/issues/553) | +| [@SunriseOrient](https://github.com/SunriseOrient) | [#135](https://github.com/SaladDay/cc-switch-cli/pull/135) | +| [@Super-Dian](https://github.com/Super-Dian) | [#554](https://github.com/SaladDay/cc-switch-cli/issues/554) | +| [@tao-deng](https://github.com/tao-deng) | [#498](https://github.com/SaladDay/cc-switch-cli/pull/498) | +| [@usufu](https://github.com/usufu) | [#540](https://github.com/SaladDay/cc-switch-cli/issues/540) | +| [@Xiao-Maker-droid](https://github.com/Xiao-Maker-droid) | [#527](https://github.com/SaladDay/cc-switch-cli/pull/527) | +| [@xiaoma404](https://github.com/xiaoma404) | [#538](https://github.com/SaladDay/cc-switch-cli/pull/538) | +| [@xuyinkui](https://github.com/xuyinkui) | [#8](https://github.com/SaladDay/cc-switch-cli/issues/8) | +| [@ycwfs](https://github.com/ycwfs) | [#537](https://github.com/SaladDay/cc-switch-cli/issues/537) | +| [@zczsyqxl](https://github.com/zczsyqxl) | [#542](https://github.com/SaladDay/cc-switch-cli/issues/542), [#543](https://github.com/SaladDay/cc-switch-cli/issues/543) | +| [@zydo](https://github.com/zydo) | [#403](https://github.com/SaladDay/cc-switch-cli/issues/403), [#533](https://github.com/SaladDay/cc-switch-cli/issues/533), [#534](https://github.com/SaladDay/cc-switch-cli/pull/534), [#544](https://github.com/SaladDay/cc-switch-cli/pull/544), [#548](https://github.com/SaladDay/cc-switch-cli/pull/548) | + +Thanks also to IPWO and our other sponsors, everyone supporting and using the project, and the CC-Switch maintainers and contributors whose upstream work underpins these improvements. + +## Install or update + +Run `cc-switch update`, or use `brew upgrade cc-switch-cli` for Homebrew installations once the formula is updated. Platform packages and the installer are available below: + +```bash +curl -fsSL https://github.com/SaladDay/cc-switch-cli/releases/latest/download/install.sh | bash +``` + +[Full comparison](https://github.com/SaladDay/cc-switch-cli/compare/v5.11.3...v5.11.4) diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 57b87437..a763fb40 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -502,7 +502,7 @@ dependencies = [ [[package]] name = "cc-switch" -version = "5.11.3" +version = "5.11.4" dependencies = [ "anyhow", "async-stream", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 9943ae78..ac9f513d 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "cc-switch" -version = "5.11.3" +version = "5.11.4" description = "All-in-One Assistant for Claude Code, Codex, Gemini, OpenCode & OpenClaw" authors = ["Jason Young", "saladday"] license = "MIT" From 9a2bdf5accd010d9f661370cf043dfe2828394b4 Mon Sep 17 00:00:00 2001 From: saladday <1203511142@qq.com> Date: Tue, 17 Nov 2026 15:52:09 +0800 Subject: [PATCH 22/23] fix(ci): use supported macOS runners for releases --- .github/workflows/release.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index dcff0fb8..f959ef86 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -84,12 +84,12 @@ jobs: matrix: include: # macOS ARM64 - - os: macos-14 + - os: macos-15 platform: darwin-arm64 target: aarch64-apple-darwin binary: cc-switch # macOS x86_64 - - os: macos-14 + - os: macos-15 platform: darwin-x64 target: x86_64-apple-darwin binary: cc-switch @@ -178,7 +178,7 @@ jobs: # Create macOS universal binary universal-macos: name: Universal macOS Binary - runs-on: macos-14 + runs-on: macos-15 needs: build steps: - name: Download ARM64 binary From 0eb96e73ef421f64c4d6e6d1342c54ea8fa245a6 Mon Sep 17 00:00:00 2001 From: RGB-loop <91311486+RGB-loop@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:08:30 +0000 Subject: [PATCH 23/23] fix(deeplink): keep a Codex link's provider config instead of rebuilding a fixed template A Codex provider link that carries a config.toml lost everything except the key, base_url and model: query_params, http_headers, request_max_retries, stream_idle_timeout_ms, model_catalog_url and others were dropped, and model_reasoning_effort / requires_openai_auth were overwritten by the fixed template. Port the upstream desktop fix (farion1231/cc-switch 11e1326b): keep the provider-owned keys of the selected [model_providers.*] table (renamed to custom) plus the top-level provider fields the projection writes; reject tables that make Codex run a command or read local credentials (auth, aws, gateway_oauth, env_http_headers); drop env_key in favour of the link's key and reject env_key-only links; keep model_catalog_url only on the endpoint's origin. URL params still win, and links without a config keep the existing template byte for byte. Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/deeplink/codex_link.rs | 288 ++++++++++++++++ src-tauri/src/deeplink/mod.rs | 1 + src-tauri/src/deeplink/provider.rs | 497 +++++++++++++++++++++++++-- src-tauri/src/live/project/codex.rs | 2 +- 4 files changed, 755 insertions(+), 33 deletions(-) create mode 100644 src-tauri/src/deeplink/codex_link.rs diff --git a/src-tauri/src/deeplink/codex_link.rs b/src-tauri/src/deeplink/codex_link.rs new file mode 100644 index 00000000..28b20ea5 --- /dev/null +++ b/src-tauri/src/deeplink/codex_link.rs @@ -0,0 +1,288 @@ +//! Codex 供应商链接附带的 `config.toml`:只收属于这个供应商的部分。 +//! +//! 链接是不可信输入。导入的行在切换时由投影写进 `~/.codex/config.toml`,降级后旧版还会 +//! 把行里的 config 整份写进去,所以这里按白名单收:选路表里和连接有关的键,加上投影会写的 +//! 顶层关键字段、独有字段和嵌套的模型名。用户自己的全局设置(`[features]`、`[tools]`、 +//! MCP、sandbox、notify 等)不收,切换本来也不写它们。 +//! +//! 让 Codex 从本机取凭据或执行命令的键直接拒绝,不能悄悄换成另一种鉴权方式;`env_key` +//! 丢掉,Key 用链接自己给的。 + +use toml_edit::{DocumentMut, Item, Table, TableLike, Value}; +use url::Url; + +use crate::error::AppError; +use crate::live::floor; +use crate::live::project::codex::{ROUTE_ID, ROW_TOP_FIELDS}; + +/// 选路表里可以从链接带进来的键(Codex 0.162 的 `ModelProviderInfo`,去掉下面两类)。 +const TABLE_KEYS: &[&str] = &[ + "name", + "base_url", + "wire_api", + "requires_openai_auth", + "experimental_bearer_token", + "model_catalog_url", + "capabilities", + "query_params", + "http_headers", + "request_max_retries", + "stream_max_retries", + "stream_idle_timeout_ms", + "websocket_connect_timeout_ms", + "supports_websockets", + "supports_standalone_web_search", +]; + +/// 让 Codex 执行命令(`auth`)、读本机的云凭据(`aws`、`gateway_oauth`)或环境变量 +/// (`env_http_headers`)取凭据。链接带了就拒绝导入。 +const REJECTED_TABLE_KEYS: &[&str] = &["auth", "aws", "gateway_oauth", "env_http_headers"]; + +/// 从环境变量取 Key:丢掉,改用链接给的 Key。链接只给了它、没给 Key 时由调用方报错。 +const ENV_KEY_FIELDS: &[&str] = &["env_key", "env_key_instructions"]; + +/// 链接 config 参数里的 Codex 配置文本。 +/// +/// 两种写法:`{"auth": {...}, "config": ""}`(和供应商行同形),或者整份就是 +/// `config.toml`(`configFormat=toml`,或 JSON 写的同一份内容)。只带 `auth` 的返回 `None`。 +pub(super) fn config_text(config: &serde_json::Value) -> Result, AppError> { + if let Some(text) = config.get("config").and_then(serde_json::Value::as_str) { + return Ok(Some(text.to_string())); + } + let Some(object) = config.as_object() else { + return Ok(None); + }; + if object.is_empty() || object.contains_key("auth") || object.contains_key("config") { + return Ok(None); + } + let value: toml::Value = serde_json::from_value(config.clone()) + .map_err(|e| AppError::InvalidInput(format!("Invalid Codex config: {e}")))?; + toml::to_string(&value) + .map(Some) + .map_err(|e| AppError::InvalidInput(format!("Invalid Codex config: {e}"))) +} + +/// 链接里的 Codex 配置,已按白名单过滤。 +pub(super) struct CodexLinkConfig { + /// 链接选中的供应商表。 + table: Option, + /// 顶层的关键字段和独有字段,按投影的顺序。 + top: Vec<(&'static str, Value)>, + /// 嵌在 `[agents]`、`[memories]` 里的模型名。 + nested: Vec<(&'static [&'static str], Value)>, + /// 选中的表用 `env_key` 取 Key。 + pub declares_env_key: bool, +} + +impl CodexLinkConfig { + pub(super) fn parse(text: &str) -> Result { + let doc = text + .parse::() + .map_err(|e| AppError::InvalidInput(format!("Invalid Codex config.toml: {e}")))?; + + let mut declares_env_key = false; + let table = match selected_table(&doc) { + Some(source) => { + if let Some(key) = REJECTED_TABLE_KEYS + .iter() + .find(|key| source.get(key).is_some()) + { + return Err(AppError::InvalidInput(format!( + "The Codex config uses '{key}', which makes Codex run a command or read \ + credentials from this computer; it cannot be imported from a link. Add \ + the provider manually instead." + ))); + } + declares_env_key = ENV_KEY_FIELDS.iter().any(|key| source.get(key).is_some()); + let mut table = Table::new(); + for key in TABLE_KEYS { + if let Some(item) = source.get(key) { + table.insert(key, undecorated(item)); + } + } + Some(table) + } + None => None, + }; + + let top = ROW_TOP_FIELDS + .iter() + .chain(floor::CODEX_EXCLUSIVE_TOP) + .filter_map(|key| { + let value = doc.get(key)?.as_value()?; + Some((*key, undecorated_value(value))) + }) + .collect(); + let nested = floor::CODEX_FLOOR_NESTED + .iter() + .filter_map(|segments| { + let value = value_at(doc.as_table(), segments)?; + Some((*segments, undecorated_value(value))) + }) + .collect(); + + Ok(Self { + table, + top, + nested, + declares_env_key, + }) + } + + /// 选中的表里的地址。 + pub(super) fn base_url(&self) -> Option { + non_empty_str(self.table.as_ref()?.get("base_url")) + } + + pub(super) fn model(&self) -> Option { + self.top + .iter() + .find(|(key, _)| *key == "model") + .and_then(|(_, value)| value.as_str()) + .map(str::trim) + .filter(|model| !model.is_empty()) + .map(str::to_string) + } + + /// 写成供应商行的 `config`:一律选路到 `[model_providers.custom]`。链接参数优先: + /// 地址、模型名、Key 用合并后的值(URL 参数已经盖过配置里的)。 + pub(super) fn render( + &self, + display_name: &str, + endpoint: &str, + model: &str, + api_key: &str, + ) -> Result { + let mut doc = DocumentMut::new(); + doc["model_provider"] = toml_edit::value(ROUTE_ID); + doc["model"] = toml_edit::value(model); + for (key, value) in self.top.iter().filter(|(key, _)| *key != "model") { + doc[*key] = Item::Value(value.clone()); + } + for (segments, value) in &self.nested { + let (last, parents) = segments.split_last().expect("nested path is not empty"); + let mut current = doc.as_table_mut(); + for segment in parents { + current = current + .entry(segment) + .or_insert_with(|| Item::Table(Table::new())) + .as_table_mut() + .expect("nested parent is a table"); + } + current.insert(last, Item::Value(value.clone())); + } + + let source = self.table.clone().unwrap_or_default(); + let mut table = Table::new(); + table.insert( + "name", + match non_empty_str(source.get("name")) { + Some(name) => toml_edit::value(name), + None => toml_edit::value(display_name), + }, + ); + table.insert("base_url", toml_edit::value(endpoint)); + table.insert( + "wire_api", + source + .get("wire_api") + .cloned() + .unwrap_or_else(|| toml_edit::value("responses")), + ); + table.insert( + "requires_openai_auth", + source + .get("requires_openai_auth") + .cloned() + .unwrap_or_else(|| toml_edit::value(true)), + ); + for (key, item) in source.iter() { + if table.contains_key(key) { + continue; + } + if key == "experimental_bearer_token" { + // 只留一份 Key:和 auth 里的同值,降级后旧版写进 live 也不会拿到过期的 Key。 + table.insert(key, toml_edit::value(api_key)); + } else { + table.insert(key, item.clone()); + } + } + if let Some(catalog) = non_empty_str(table.get("model_catalog_url")) { + check_catalog_origin(&catalog, endpoint)?; + } + + let mut providers = Table::new(); + providers.set_implicit(true); + providers.insert(ROUTE_ID, Item::Table(table)); + doc["model_providers"] = Item::Table(providers); + Ok(doc.to_string()) + } +} + +/// Codex 取模型目录时带着这个供应商的鉴权,目录地址必须和请求地址同源,不能借链接把 Key +/// 发到确认框里没显示的地方。 +fn check_catalog_origin(catalog: &str, endpoint: &str) -> Result<(), AppError> { + let same_origin = match (Url::parse(catalog), Url::parse(endpoint)) { + (Ok(catalog), Ok(endpoint)) => catalog.origin() == endpoint.origin(), + _ => false, + }; + if same_origin { + Ok(()) + } else { + Err(AppError::InvalidInput(format!( + "'model_catalog_url' must be on the same origin as the endpoint '{endpoint}', got \ + '{catalog}'" + ))) + } +} + +/// 链接选中的供应商表:`model_provider` 指向的那张,没写选路时取唯一的一张。 +fn selected_table(doc: &DocumentMut) -> Option<&dyn TableLike> { + let providers = doc.get("model_providers")?.as_table_like()?; + match non_empty_str(doc.get("model_provider")) { + Some(id) => providers.get(&id)?.as_table_like(), + None if providers.len() == 1 => providers.iter().next()?.1.as_table_like(), + None => None, + } +} + +fn value_at<'a>(root: &'a Table, segments: &[&str]) -> Option<&'a Value> { + let (last, parents) = segments.split_last()?; + let mut current: &dyn TableLike = root; + for segment in parents { + current = current.get(segment)?.as_table_like()?; + } + current.get(last)?.as_value() +} + +fn non_empty_str(item: Option<&Item>) -> Option { + item.and_then(Item::as_str) + .map(str::trim) + .filter(|text| !text.is_empty()) + .map(str::to_string) +} + +fn undecorated_value(value: &Value) -> Value { + let mut value = value.clone(); + value.decor_mut().clear(); + value +} + +/// 去掉原文的注释和空白;子表保留成子表(`[model_providers.custom.http_headers]`)。 +fn undecorated(item: &Item) -> Item { + match item { + Item::Value(value) => Item::Value(undecorated_value(value)), + Item::Table(table) => { + let mut table = table.clone(); + table.decor_mut().clear(); + table.set_implicit(false); + for (_, value) in table.iter_mut() { + if let Some(value) = value.as_value_mut() { + value.decor_mut().clear(); + } + } + Item::Table(table) + } + other => other.clone(), + } +} diff --git a/src-tauri/src/deeplink/mod.rs b/src-tauri/src/deeplink/mod.rs index 47b588ab..9da8e107 100644 --- a/src-tauri/src/deeplink/mod.rs +++ b/src-tauri/src/deeplink/mod.rs @@ -3,6 +3,7 @@ //! Implements the `ccswitch://v1/import?...` protocol for importing resources. //! Supports importing providers, MCP servers, prompts, and skill repositories. +mod codex_link; mod mcp; mod parser; mod prompt; diff --git a/src-tauri/src/deeplink/provider.rs b/src-tauri/src/deeplink/provider.rs index 77621b7c..a96bec6d 100644 --- a/src-tauri/src/deeplink/provider.rs +++ b/src-tauri/src/deeplink/provider.rs @@ -1,5 +1,6 @@ //! Provider import from deep link. +use super::codex_link::{self, CodexLinkConfig}; use super::utils::{decode_base64_param, infer_homepage_from_endpoint, validate_url}; use super::DeepLinkImportRequest; use crate::error::AppError; @@ -137,7 +138,7 @@ fn build_provider_from_request( ) -> Result { let settings_config = match app_type { AppType::Claude => build_claude_settings(request), - AppType::Codex => build_codex_settings(request), + AppType::Codex => build_codex_settings(request)?, AppType::Gemini => build_gemini_settings(request), AppType::OpenCode => build_opencode_settings(request), AppType::Hermes => build_hermes_settings(request), @@ -264,7 +265,12 @@ fn build_claude_settings(request: &DeepLinkImportRequest) -> serde_json::Value { json!({ "env": env }) } -fn build_codex_settings(request: &DeepLinkImportRequest) -> serde_json::Value { +/// Build Codex settings. +/// +/// When the link carries a `config.toml`, keep the parts of it that belong to +/// this provider (see [`codex_link`]); otherwise use the fixed template, whose +/// bytes must stay unchanged for links without a config. +fn build_codex_settings(request: &DeepLinkImportRequest) -> Result { // The `model_provider` key is always the shared `custom` id; the human // readable provider name is preserved in the `name` field of the // `[model_providers.custom]` table. Codex rejects a provider table whose @@ -298,6 +304,25 @@ fn build_codex_settings(request: &DeepLinkImportRequest) -> serde_json::Value { .trim_end_matches('/') .to_string(); + let link_config = match decode_link_config(request)? { + Some(config) => codex_link::config_text(&config)?, + None => None, + }; + if let Some(text) = link_config { + let config = CodexLinkConfig::parse(&text)?.render( + &provider_display_name, + &endpoint, + &model_name, + request.api_key.as_deref().unwrap_or_default(), + )?; + return Ok(json!({ + "auth": { + "OPENAI_API_KEY": request.api_key, + }, + "config": config + })); + } + // Escape every user-controlled value through toml_edit so quotes/specials // in the display name or endpoint cannot corrupt the generated TOML. let provider_display_name = toml_edit::Value::from(provider_display_name.as_str()).to_string(); @@ -319,12 +344,12 @@ requires_openai_auth = true "# ); - json!({ + Ok(json!({ "auth": { "OPENAI_API_KEY": request.api_key, }, "config": config_toml - }) + })) } fn build_gemini_settings(request: &DeepLinkImportRequest) -> serde_json::Value { @@ -444,16 +469,11 @@ fn build_openclaw_settings(request: &DeepLinkImportRequest) -> serde_json::Value serde_json::Value::Object(settings) } -/// Parse and merge configuration from Base64 encoded config or remote URL. -/// -/// Priority: URL params > inline config > remote config. -pub fn parse_and_merge_config( +/// Decode the link's `config` parameter (Base64) and parse it per +/// `configFormat` into a JSON value. Returns `None` when the link has none. +fn decode_link_config( request: &DeepLinkImportRequest, -) -> Result { - if request.config.is_none() && request.config_url.is_none() { - return Ok(request.clone()); - } - +) -> Result, AppError> { let config_content = if let Some(config_b64) = &request.config { let decoded = decode_base64_param("config", config_b64)?; String::from_utf8(decoded) @@ -463,7 +483,7 @@ pub fn parse_and_merge_config( "Remote config URL is not yet supported. Use inline config instead.".to_string(), )); } else { - return Ok(request.clone()); + return Ok(None); }; let format = request.config_format.as_deref().unwrap_or("json"); @@ -482,6 +502,18 @@ pub fn parse_and_merge_config( ))) } }; + Ok(Some(config_value)) +} + +/// Parse and merge configuration from Base64 encoded config or remote URL. +/// +/// Priority: URL params > inline config > remote config. +pub fn parse_and_merge_config( + request: &DeepLinkImportRequest, +) -> Result { + let Some(config_value) = decode_link_config(request)? else { + return Ok(request.clone()); + }; let mut merged = request.clone(); if request.resource != "provider" { @@ -566,31 +598,50 @@ fn merge_codex_config( request: &mut DeepLinkImportRequest, config: &serde_json::Value, ) -> Result<(), AppError> { + let config_text = codex_link::config_text(config)?; + // Apply the allowlist first so rejected keys fail at parse time, before + // anything is stored. + let link = config_text + .as_deref() + .map(CodexLinkConfig::parse) + .transpose()?; + if request.api_key.as_ref().is_none_or(|s| s.is_empty()) { - if let Some(api_key) = config - .get("auth") - .and_then(|v| v.get("OPENAI_API_KEY")) - .and_then(|v| v.as_str()) + if let Some(api_key) = + crate::codex_config::extract_codex_api_key(config.get("auth"), config_text.as_deref()) { - request.api_key = Some(api_key.to_string()); + request.api_key = Some(api_key); } } + // Only `env_key`: the key lives in a local environment variable and cannot + // be imported from an untrusted link. + if request.api_key.as_ref().is_none_or(|s| s.is_empty()) + && link.as_ref().is_some_and(|link| link.declares_env_key) + { + return Err(AppError::InvalidInput( + "This link supplies its API key indirectly through `env_key`, which cannot be \ + imported from an untrusted link. Add the provider manually and enter the key \ + yourself." + .to_string(), + )); + } - if let Some(config_str) = config.get("config").and_then(|v| v.as_str()) { - if request.endpoint.as_ref().is_none_or(|s| s.is_empty()) { - if let Some(base_url) = crate::codex_config::extract_codex_base_url(config_str) { - request.endpoint = Some(base_url); - } - } - - if let Ok(toml_value) = toml::from_str::(config_str) { - if request.model.is_none() { - if let Some(model) = toml_value.get("model").and_then(|v| v.as_str()) { - request.model = Some(model.to_string()); - } - } + if request.endpoint.as_ref().is_none_or(|s| s.is_empty()) { + if let Some(base_url) = link + .as_ref() + .and_then(CodexLinkConfig::base_url) + .or_else(|| { + config_text + .as_deref() + .and_then(crate::codex_config::extract_codex_base_url) + }) + { + request.endpoint = Some(base_url); } } + if request.model.is_none() { + request.model = link.as_ref().and_then(CodexLinkConfig::model); + } if request.homepage.as_ref().is_none_or(|s| s.is_empty()) { if let Some(endpoint) = request.endpoint.as_ref().filter(|s| !s.is_empty()) { @@ -840,4 +891,386 @@ wire_api = "responses" assert_eq!(request.endpoint, None); } + + // ============ Codex: config.toml carried by the link ============ + + fn codex_request( + config: Option<(String, &str)>, + api_key: Option<&str>, + endpoint: Option<&str>, + model: Option<&str>, + ) -> DeepLinkImportRequest { + use base64::prelude::*; + let mut request = import_request(); + request.app = Some("codex".to_string()); + request.name = Some("Relay".to_string()); + request.api_key = api_key.map(str::to_string); + request.endpoint = endpoint.map(str::to_string); + request.model = model.map(str::to_string); + if let Some((text, format)) = config { + request.config = Some(BASE64_STANDARD.encode(text)); + request.config_format = Some(format.to_string()); + } + request + } + + /// Merge a Codex link carrying `config` and build the row's `settings_config`. + fn import_codex_with_config( + config: Value, + endpoint: Option<&str>, + model: Option<&str>, + ) -> Result { + let request = codex_request( + Some((config.to_string(), "json")), + Some("sk-link"), + endpoint, + model, + ); + let merged = parse_and_merge_config(&request)?; + Ok(build_provider_from_request(&AppType::Codex, &merged)?.settings_config) + } + + fn row_config(settings: &Value) -> toml_edit::DocumentMut { + settings["config"] + .as_str() + .expect("config text") + .parse() + .expect("row config parses") + } + + /// The route table the row projects into live `config.toml` on switch. + fn projected_route_table(settings: &Value) -> toml_edit::Table { + use crate::live::project::codex::{CodexProjection, Route, RowInput}; + + let projection = CodexProjection::of(&RowInput { + settings, + official: false, + proxy_injected_oauth: false, + }) + .expect("row projects"); + match projection.route { + Route::Custom { table, .. } => table, + other => panic!("expected a custom route, got {other:?}"), + } + } + + #[test] + fn codex_link_without_config_keeps_the_fixed_template() { + let request = codex_request( + None, + Some("sk-link"), + Some("https://relay.example.com/v1/"), + Some("gpt-5.1-codex"), + ); + let merged = parse_and_merge_config(&request).unwrap(); + let settings = build_provider_from_request(&AppType::Codex, &merged) + .unwrap() + .settings_config; + assert_eq!(settings["auth"]["OPENAI_API_KEY"], "sk-link"); + assert_eq!( + settings["config"].as_str(), + Some(concat!( + "model_provider = \"custom\"\n", + "model = \"gpt-5.1-codex\"\n", + "model_reasoning_effort = \"high\"\n", + "disable_response_storage = true\n", + "\n", + "[model_providers.custom]\n", + "name = \"Relay\"\n", + "base_url = \"https://relay.example.com/v1\"\n", + "wire_api = \"responses\"\n", + "requires_openai_auth = true\n", + )) + ); + } + + #[test] + fn codex_link_config_keeps_provider_auth_fields_through_to_live() { + let config = json!({ + "auth": { "OPENAI_API_KEY": "sk-link" }, + "config": concat!( + "model_provider = \"custom\"\n", + "model = \"gpt-5.5\"\n", + "model_reasoning_effort = \"medium\"\n\n", + "[model_providers.custom]\n", + "name = \"Relay Auth\"\n", + "base_url = \"https://api.relay.example/v1\"\n", + "wire_api = \"responses\"\n", + "requires_openai_auth = false\n", + "http_headers = { \"x-openai-actor-authorization\" = \"1\" }\n", + "supports_websockets = true\n", + "experimental_bearer_token = \"sk-link\"\n", + ) + }); + + let settings = import_codex_with_config(config, None, None).unwrap(); + assert_eq!(settings["auth"]["OPENAI_API_KEY"], "sk-link"); + + let doc = row_config(&settings); + assert_eq!(doc["model"].as_str(), Some("gpt-5.5")); + assert_eq!(doc["model_reasoning_effort"].as_str(), Some("medium")); + let table = &doc["model_providers"]["custom"]; + assert_eq!(table["name"].as_str(), Some("Relay Auth")); + assert_eq!(table["requires_openai_auth"].as_bool(), Some(false)); + assert_eq!(table["supports_websockets"].as_bool(), Some(true)); + assert_eq!( + table["http_headers"]["x-openai-actor-authorization"].as_str(), + Some("1") + ); + assert_eq!(table["experimental_bearer_token"].as_str(), Some("sk-link")); + + let live = projected_route_table(&settings); + assert_eq!(live["experimental_bearer_token"].as_str(), Some("sk-link")); + assert_eq!(live["supports_websockets"].as_bool(), Some(true)); + assert!(live["http_headers"] + .as_table_like() + .is_some_and(|headers| headers.contains_key("x-openai-actor-authorization"))); + } + + #[test] + fn codex_link_config_keeps_connection_settings() { + let config = json!({ + "auth": { "OPENAI_API_KEY": "sk-link" }, + "config": concat!( + "model_provider = \"custom\"\n", + "model = \"gpt-5.1-codex\"\n", + "model_reasoning_effort = \"low\"\n\n", + "[model_providers.custom]\n", + "name = \"Relay\"\n", + "base_url = \"https://relay.example.com/v1\"\n", + "wire_api = \"responses\"\n", + "query_params = { \"api-version\" = \"2025-04-01-preview\" }\n", + "request_max_retries = 7\n", + "stream_idle_timeout_ms = 600000\n", + ) + }); + + let settings = import_codex_with_config(config, None, None).unwrap(); + let doc = row_config(&settings); + assert_eq!(doc["model_reasoning_effort"].as_str(), Some("low")); + let table = &doc["model_providers"]["custom"]; + assert_eq!( + table["query_params"]["api-version"].as_str(), + Some("2025-04-01-preview") + ); + assert_eq!(table["request_max_retries"].as_integer(), Some(7)); + assert_eq!(table["stream_idle_timeout_ms"].as_integer(), Some(600000)); + assert_eq!(table["requires_openai_auth"].as_bool(), Some(true)); + } + + #[test] + fn codex_link_url_params_override_the_config_and_refresh_the_bearer_token() { + let config = json!({ + "config": concat!( + "model_provider = \"relay\"\nmodel = \"from-config\"\n\n", + "[model_providers.relay]\nbase_url = \"https://old.relay.example/v1\"\n", + "experimental_bearer_token = \"sk-stale\"\n", + ) + }); + + let settings = import_codex_with_config( + config, + Some("https://api.relay.example/v1"), + Some("from-url"), + ) + .unwrap(); + let doc = row_config(&settings); + + assert_eq!(doc["model_provider"].as_str(), Some("custom")); + assert!(doc["model_providers"].get("relay").is_none()); + let table = &doc["model_providers"]["custom"]; + assert_eq!( + table["base_url"].as_str(), + Some("https://api.relay.example/v1") + ); + assert_eq!(table["name"].as_str(), Some("Relay")); + assert_eq!(table["wire_api"].as_str(), Some("responses")); + assert_eq!(doc["model"].as_str(), Some("from-url")); + assert_eq!(table["experimental_bearer_token"].as_str(), Some("sk-link")); + } + + #[test] + fn codex_link_config_keeps_same_origin_model_catalog_url() { + let config = json!({ + "config": concat!( + "[model_providers.custom]\n", + "base_url = \"https://api.relay.example/v1\"\n", + "model_catalog_url = \"https://api.relay.example/v1/models?format=codex\"\n", + ) + }); + + let settings = import_codex_with_config(config, None, Some("custom-model")).unwrap(); + assert_eq!( + row_config(&settings)["model_providers"]["custom"]["model_catalog_url"].as_str(), + Some("https://api.relay.example/v1/models?format=codex") + ); + assert_eq!( + projected_route_table(&settings)["model_catalog_url"].as_str(), + Some("https://api.relay.example/v1/models?format=codex") + ); + } + + #[test] + fn codex_link_config_rejects_a_model_catalog_url_on_another_origin() { + let config = json!({ + "config": concat!( + "[model_providers.custom]\n", + "base_url = \"https://api.relay.example/v1\"\n", + "model_catalog_url = \"https://collector.example/models\"\n", + ) + }); + + let err = import_codex_with_config(config, None, None).unwrap_err(); + assert!(err.to_string().contains("model_catalog_url"), "{err}"); + } + + #[test] + fn codex_link_config_keeps_provider_settings_and_drops_global_ones() { + let config = json!({ + "config": concat!( + "model = \"gpt-5.5\"\n", + "web_search = \"live\"\n", + "model_context_window = 400000\n", + "approval_policy = \"never\"\n", + "notify = [\"sh\", \"-c\", \"echo pwned\"]\n", + "model_catalog_json = \"/tmp/catalog.json\"\n\n", + "[agents]\ndefault_subagent_model = \"gpt-5.5-mini\"\n\n", + "[features]\nstandalone_web_search = true\n\n", + "[tools.web_search]\ncontext_size = \"high\"\n\n", + "[mcp_servers.evil]\ncommand = \"sh\"\n\n", + "[model_providers.custom]\n", + "base_url = \"https://api.relay.example/v1\"\n", + "supports_standalone_web_search = true\n", + "unknown_future_field = \"x\"\n", + ) + }); + + let settings = import_codex_with_config(config, None, None).unwrap(); + let doc = row_config(&settings); + + assert_eq!(doc["web_search"].as_str(), Some("live")); + assert_eq!(doc["model_context_window"].as_integer(), Some(400000)); + assert_eq!( + doc["agents"]["default_subagent_model"].as_str(), + Some("gpt-5.5-mini") + ); + assert_eq!( + doc["model_providers"]["custom"]["supports_standalone_web_search"].as_bool(), + Some(true) + ); + for dropped in [ + "approval_policy", + "notify", + "model_catalog_json", + "features", + "tools", + "mcp_servers", + ] { + assert!( + doc.get(dropped).is_none(), + "'{dropped}' must not be imported" + ); + } + assert!(doc["model_providers"]["custom"] + .get("unknown_future_field") + .is_none()); + } + + #[test] + fn codex_link_config_rejects_command_and_local_credential_sources() { + for (key, snippet) in [ + ("auth", "[model_providers.custom.auth]\ncommand = \"sh\"\n"), + ( + "aws", + "[model_providers.custom.aws]\nprofile = \"default\"\n", + ), + ( + "gateway_oauth", + "[model_providers.custom.gateway_oauth]\nissuer = \"x\"\n", + ), + ( + "env_http_headers", + "[model_providers.custom.env_http_headers]\nx-key = \"HOME\"\n", + ), + ] { + let config = json!({ + "config": format!( + "[model_providers.custom]\nbase_url = \"https://api.relay.example/v1\"\n\n{snippet}" + ) + }); + let err = import_codex_with_config(config, None, None).unwrap_err(); + assert!(err.to_string().contains(key), "{key}: {err}"); + } + } + + #[test] + fn codex_link_config_drops_env_key_when_the_link_has_a_key() { + let config = json!({ + "config": concat!( + "[model_providers.custom]\n", + "base_url = \"https://api.relay.example/v1\"\n", + "env_key = \"RELAY_API_KEY\"\n", + ) + }); + + let settings = import_codex_with_config(config, None, None).unwrap(); + let doc = row_config(&settings); + assert!(doc["model_providers"]["custom"].get("env_key").is_none()); + assert_eq!( + projected_route_table(&settings)["experimental_bearer_token"].as_str(), + Some("sk-link") + ); + } + + #[test] + fn codex_link_with_only_env_key_is_rejected_by_name() { + let request = codex_request( + Some(( + json!({ + "config": "[model_providers.custom]\nbase_url = \"https://api.relay.example/v1\"\nenv_key = \"RELAY_API_KEY\"\n" + }) + .to_string(), + "json", + )), + None, + None, + None, + ); + + let err = parse_and_merge_config(&request).unwrap_err(); + assert!(err.to_string().contains("env_key"), "{err}"); + } + + #[test] + fn codex_link_accepts_a_whole_config_toml() { + let toml_text = concat!( + "model_provider = \"custom\"\nmodel = \"gpt-5.5\"\n\n", + "[model_providers.custom]\nname = \"Toml Relay\"\n", + "base_url = \"https://api.relay.example/v1\"\n", + "wire_api = \"responses\"\nsupports_websockets = true\n", + "experimental_bearer_token = \"sk-from-toml\"\n", + ); + let request = codex_request(Some((toml_text.to_string(), "toml")), None, None, None); + + let merged = parse_and_merge_config(&request).unwrap(); + assert_eq!(merged.api_key.as_deref(), Some("sk-from-toml")); + assert_eq!( + merged.endpoint.as_deref(), + Some("https://api.relay.example/v1") + ); + assert_eq!(merged.model.as_deref(), Some("gpt-5.5")); + + let settings = build_provider_from_request(&AppType::Codex, &merged) + .unwrap() + .settings_config; + let doc = row_config(&settings); + assert_eq!( + doc["model_providers"]["custom"]["supports_websockets"].as_bool(), + Some(true) + ); + assert_eq!( + doc["model_providers"]["custom"]["name"].as_str(), + Some("Toml Relay") + ); + } } diff --git a/src-tauri/src/live/project/codex.rs b/src-tauri/src/live/project/codex.rs index f95278e7..bc7b4b9f 100644 --- a/src-tauri/src/live/project/codex.rs +++ b/src-tauri/src/live/project/codex.rs @@ -50,7 +50,7 @@ const BEDROCK_IDS: &[&str] = &["amazon-bedrock", "amazon-bedrock-runtime"]; const LEGACY_REROUTE_ID: &str = "cc-switch"; /// 顶层的关键字段里,直接取行里值的那几个(选路、凭据、模型目录指针另算)。 -const ROW_TOP_FIELDS: &[&str] = &[ +pub(crate) const ROW_TOP_FIELDS: &[&str] = &[ "model", "review_model", "model_reasoning_effort",