Compare commits

..
21 Commits
Author SHA1 Message Date
yynxxxxx 8661ce85a1 test(routing): cover both external-selection shutdown orders 2026-10-17 00:18:33 +08:00
yynxxxxx 0381c5351d Release v0.3.27 2026-10-17 00:01:38 +08:00
yynxxxxx f7aa94cb1b feat: improve balance presentation and add manual refresh 2026-10-16 21:25:19 +08:00
yynxxxxx d1f0df031d feat: refine desktop language and add provider balances 2026-10-16 21:07:30 +08:00
yynxxxxx ecde8c1344 fix: simplify Codex Chinese language setting 2026-10-16 15:11:18 +08:00
yynxxxxx f6feba9a8d feat: improve session sync and add Codex language compatibility 2026-10-16 01:18:50 +08:00
yynxxxxx 19222f9cc9 Release v0.3.26 2026-10-09 20:46:51 +08:00
yynxxxxx e6e68f8d92 test(routing): await stream worker completion before checking error state 2026-10-09 20:43:15 +08:00
yynxxxxx 4c56b05894 ci(windows): run prepared harness without relinking its manifest 2026-10-09 20:10:58 +08:00
yynxxxxx a107ad22f8 ci(windows): supply missing test manifest definition identity 2026-10-09 19:59:57 +08:00
yynxxxxx 3e2e27b77e ci(windows): give test harness the Common Controls v6 manifest 2026-10-09 19:47:14 +08:00
yynxxxxx 2babfa6ced ci(windows): retain loader diagnostics without bypassing tests 2026-10-09 19:33:42 +08:00
yynxxxxx e9c52aa8cb ci(windows): pin verified Rust toolchain for release tests 2026-10-09 19:19:14 +08:00
yynxxxxx 26ebeb8618 Release v0.3.25 2026-10-09 19:08:27 +08:00
yynxxxxx e5634c3204 fix(updater): recover signed checks and downloads through official API 2026-10-09 18:14:54 +08:00
yynxxxxx 14885c9a0e fix(providers): add User-Agent presets and contextual header examples (#53) 2026-10-08 16:11:13 +08:00
yynxxxxx 918ad405b6 feat(routing): bridge Chat, Claude and Gemini upstream protocols (#68) 2026-10-08 14:34:20 +08:00
yynxxxxx 5368e2dad3 feat(providers): add editable HTTP headers with safe TOML updates (#53) 2026-10-08 13:58:44 +08:00
yynxxxxx 5a9ec0581c fix(config): repair official history aliases with precise diagnostics (#67) 2026-10-08 13:54:32 +08:00
yynxxxxxandzjjszmx 726de0fe63 Release v0.3.24
Include the Windows index replacement compatibility fix and the verified
large-session and directory-browser changes. Keep v0.3.23 unpublished.

Co-authored-by: zjjszmx <81135758+zjjszmx@users.noreply.github.com>
2026-10-01 14:59:10 +08:00
yynxxxxxandzjjszmx 7d0b2891b9 fix(sessions): release index handles before Windows replacement
Close both owned index handles before atomic installation and retain the
final snapshot verification. Test birth timestamps at Windows SystemTime
precision and run the full Windows suite in the shipping release profile.

Co-authored-by: zjjszmx <81135758+zjjszmx@users.noreply.github.com>
2026-10-01 14:57:27 +08:00
103 changed files with 17875 additions and 669 deletions
+35 -1
View File
@@ -186,6 +186,16 @@ jobs:
with:
ref: ${{ needs.prepare.outputs.tag }}
- name: Checkout Windows test harness tooling
if: matrix.platform == 'windows-latest'
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
with:
ref: ${{ github.sha }}
path: .ci-tools
sparse-checkout: scripts/ensure-test-common-controls.ps1
sparse-checkout-cone-mode: false
persist-credentials: false
- name: Install Linux dependencies
if: matrix.platform == 'ubuntu-22.04'
run: |
@@ -221,9 +231,33 @@ jobs:
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Check frontend types and regressions
run: |
pnpm --dir apps/desktop typecheck
node --test apps/desktop/tests/*.test.mjs
- name: Verify Windows SDK test tooling
if: matrix.platform == 'windows-latest'
run: |
command -v openssl
openssl version
- name: Test Windows filesystem compatibility
if: matrix.platform == 'windows-latest'
run: cargo test --manifest-path apps/desktop/src-tauri/Cargo.toml --lib --locked -- --test-threads=1
shell: pwsh
run: |
$artifacts = Join-Path $env:RUNNER_TEMP 'codexx-test-artifacts.json'
cargo test --release --manifest-path apps/desktop/src-tauri/Cargo.toml --lib --locked --no-run --message-format=json > $artifacts
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$harness = ./.ci-tools/scripts/ensure-test-common-controls.ps1 -CargoJson $artifacts -OutputDirectory $env:RUNNER_TEMP | ConvertFrom-Json
Write-Host "Running all tests in $($harness.testExecutable)"
$env:PATH = "$(Split-Path -Parent $harness.testExecutable);$env:PATH"
Push-Location apps/desktop/src-tauri
try {
& $harness.testExecutable --test-threads=1
$testExitCode = $LASTEXITCODE
} finally { Pop-Location }
if ($testExitCode -ne 0) { exit $testExitCode }
- name: Import Apple signing certificate and notarization key
if: matrix.macos
+30 -1
View File
@@ -39,7 +39,36 @@ jobs:
cache-on-failure: true
- run: pnpm install --frozen-lockfile
- run: pnpm --dir apps/desktop typecheck
- run: cargo test --manifest-path apps/desktop/src-tauri/Cargo.toml --lib --locked -- --test-threads=1
- run: node --test apps/desktop/tests/*.test.mjs
- name: Verify SDK TLS fixture tooling
run: |
$openssl = Get-Command openssl -ErrorAction Stop
& $openssl.Source version
- name: Run Windows release tests
run: |
$artifacts = Join-Path $env:RUNNER_TEMP 'codexx-test-artifacts.json'
cargo test --release --manifest-path apps/desktop/src-tauri/Cargo.toml --lib --locked --no-run --message-format=json > $artifacts
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$harness = ./scripts/ensure-test-common-controls.ps1 -CargoJson $artifacts -OutputDirectory $env:RUNNER_TEMP | ConvertFrom-Json
Write-Host "Running all tests in $($harness.testExecutable)"
$env:PATH = "$(Split-Path -Parent $harness.testExecutable);$env:PATH"
Push-Location apps/desktop/src-tauri
try {
& $harness.testExecutable --test-threads=1
$testExitCode = $LASTEXITCODE
} finally { Pop-Location }
if ($testExitCode -ne 0) { exit $testExitCode }
- name: Diagnose failed Windows test loader
if: failure()
run: ./scripts/windows-dll-diagnostics.ps1 -RunHarnessList
- name: Retain Windows loader diagnostics
if: failure()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: windows-loader-diagnostics
path: ${{ runner.temp }}/codexx-dll-diagnostics
retention-days: 7
if-no-files-found: warn
- name: Build test installer without publishing or release signing credentials
run: |
Set-Content -Path "$env:RUNNER_TEMP\installer-check.json" -Value '{"bundle":{"createUpdaterArtifacts":false}}' -Encoding utf8
+26 -1
View File
@@ -2,13 +2,38 @@
记录 Codex-X 的新功能、体验改进和问题修复。
## [v0.3.23] - 2026-10-01
## [v0.3.27] - 2026-10-17
- 会话同步期间可启用或切换供应商;每次同步固定开始时的目标,完成后按当前供应商更新状态。
- 识别 Codex 保留 `.jsonl` 逻辑路径、实际使用 `.jsonl.zst` 的压缩会话;同步、预览、导出及删除兼容压缩存储,保留流式处理、备份和并发修改保护。
- 状态检查省去整文件改写快照与重压,减少同步中重复的完整日志扫描。
- 会话按历史工作目录分组时保留原路径拼写,不再探测或打开项目目录,减少触发“文稿”等目录的权限提示。
- 新增「Codex 简体中文」开关,读取 Codex 实际语言配置,重启后应用待生效的选择,关闭时恢复原语言或自动检测;支持 macOS,以及经过官方身份验证的 Windows Store 版和独立安装版(Store 版仅支持默认 `CODEX_HOME`)。
- 统一设置页和操作提示中的「重启 Codex」入口,同时应用待生效的语言设置;改进进程退出与启动确认,减少首次重启失败、再次点击才成功的问题。
- 供应商卡片新增 DeepSeek、OpenRouter、硅基流动和 Moonshot 余额查询,区分账户余额与 Key 剩余额度,支持后台定时更新、手动刷新和查看最近查询时间。
- 余额刷新复用同一凭据的并发请求,按实际查询时间安排后续刷新,避免手动查询或读取缓存推迟后台更新;金额保留十进制精度,查询失败时保留此前余额并显示失败状态。
- 官方账号编辑支持读取单个标准 `auth.json` 文件到编辑区,校验后由用户保存。
- 重启 Codex 失败时保留错误详情,支持手动关闭,便于定位失败原因。
## [v0.3.26] - 2026-10-09
- 安装版在线更新的主通道失败后,自动通过官方 GitHub API 获取更新清单和安装包,继续由原生更新器检查版本、平台和签名;不再因一次检查失败就静默改为仅手动下载。
- 供应商新增上游协议选择,本地路由可将 Chat Completions、Claude Messages 和 Gemini 原生请求/响应转换为 Codex 使用的 Responses,支持图片、工具调用及流式输出。
- 模型获取和连接检测按所选协议发送认证与 Headers;从 CC Switch 导入时保留显式协议选择。
- 配置检查显示文件、行列、参数和具体处理建议;切回官方账号后可安全修复旧会话缺失的供应商定义。
- 供应商页面新增自定义 Headers 编辑,支持固定值和环境变量,并在对应行显示校验错误;可选择 Claude Code / Kilo Code 的 User-Agent 预设,填写提示按请求头用途区分。
- 使用协议转换时,退出和更新保留本地路由与恢复记录,重开后恢复相同协议;关闭路由前提示切回原生 Responses/官方,避免无效直连。
## [v0.3.24] - 2026-10-01
- 会话管理新增工作文件夹侧栏、文件夹与会话置顶,并使用虚拟列表减少大量会话的渲染开销。
- 会话日志改为流式读取和磁盘快照处理,大日志及超长单条记录也能同步;读取、写入或复查失败时明确报错并执行安全回滚,避免日志、数据库索引与同步状态不一致。
- 修复文件夹路径大小写混淆导致显示错误会话、置顶联动和缓存串用的问题,按实际文件系统身份区分目录或合并同目录别名。
- 置顶按 Codex 配置目录分别保存,文件夹暂时不可读或重建后按原始路径保留置顶。旧 PR 预览版的 v1 置顶缓存不自动迁移,需重新置顶。
- 修复 Windows 下会话索引原子替换被文件句柄阻止的问题。
## [v0.3.22] - 2026-09-30
- 修复第三方模型被错误识别为“仅文本”而无法输入图片的问题,并自动升级旧版生成的模型目录。需供应商模型本身支持图片,更新菜单后重启 Codex 生效。
+2 -1
View File
@@ -238,7 +238,8 @@ Codex-X 现在不只是“几套内置 Prompt”的启动器,而是一个可
- 保存多个可命名的官方 Codex 登录配置与第三方供应商,随时查看当前正在使用哪一个
- 点击“复制”直接新增独立副本,无需确认或进入编辑页;名称可稍后修改
- 切换前可检测连接,并可获取模型进行测试
- 在同一页面编辑 Base URL、API Key、Model、Wire API 和完整 TOML
- 在同一页面编辑 Base URL、API Key、Model、上游接口协议、Headers 和完整 TOML
- 本地路由支持 Responses、Chat Completions、Claude Messages、Gemini 原生接口,使用方式与边界见[供应商协议说明](docs/PROVIDER_PROTOCOLS.md)
- 从 cc-switch 导入时自动区分新增、更新、合并与跳过;相同 URL + Key 不再重复显示
- 切回 OpenAI Official 时保留当前官方登录态,第三方配置也不会凭空消失
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "codex-x",
"version": "0.3.23",
"version": "0.3.27",
"private": true,
"description": "Codex Switch & Instruct desktop manager",
"type": "module",
+74 -1
View File
@@ -492,7 +492,7 @@ dependencies = [
[[package]]
name = "codex-x"
version = "0.3.23"
version = "0.3.27"
dependencies = [
"base64 0.22.1",
"chrono",
@@ -518,6 +518,7 @@ dependencies = [
"thiserror 2.0.18",
"tokio",
"toml_edit 0.22.27",
"tungstenite",
"ureq",
"windows-sys 0.61.2",
"zip 2.4.2",
@@ -719,6 +720,12 @@ dependencies = [
"syn 2.0.118",
]
[[package]]
name = "data-encoding"
version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
[[package]]
name = "dbus"
version = "0.9.12"
@@ -2720,6 +2727,15 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
[[package]]
name = "ppv-lite86"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
dependencies = [
"zerocopy",
]
[[package]]
name = "precomputed-hash"
version = "0.1.1"
@@ -2817,6 +2833,35 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
dependencies = [
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
dependencies = [
"getrandom 0.3.4",
]
[[package]]
name = "raw-window-handle"
version = "0.6.2"
@@ -3388,6 +3433,17 @@ dependencies = [
"stable_deref_trait",
]
[[package]]
name = "sha1"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "sha2"
version = "0.10.9"
@@ -4394,6 +4450,23 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "tungstenite"
version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8628dcc84e5a09eb3d8423d6cb682965dea9133204e8fb3efee74c2a0c259442"
dependencies = [
"bytes",
"data-encoding",
"http",
"httparse",
"log",
"rand",
"sha1",
"thiserror 2.0.18",
"utf-8",
]
[[package]]
name = "typeid"
version = "1.0.3"
+6 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "codex-x"
version = "0.3.23"
version = "0.3.27"
description = "Codex Switch & Instruct desktop manager"
authors = ["yynxxxxx"]
license = "MIT"
@@ -19,7 +19,7 @@ tauri = { version = "2.8.2", features = ["tray-icon"] }
tauri-plugin-process = "2.3.1"
tauri-plugin-updater = "2.10.1"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde_json = { version = "1.0", features = ["arbitrary_precision"] }
base64 = "0.22"
toml_edit = "0.22"
chrono = { version = "0.4", features = ["serde"] }
@@ -46,6 +46,10 @@ tokio = { version = "1", features = ["rt-multi-thread", "time", "net"] }
flate2 = "1"
zstd = "0.13"
tempfile = "3.27"
tungstenite = { version = "0.28", default-features = false, features = ["handshake"] }
[dev-dependencies]
tauri = { version = "2.8.2", features = ["test"] }
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "=0.61.2", features = ["Win32_Foundation", "Win32_Storage_FileSystem"] }
+122 -1
View File
@@ -7,7 +7,7 @@ use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};
use std::time::Duration;
const APP_DB_SCHEMA_VERSION: i64 = 8;
const APP_DB_SCHEMA_VERSION: i64 = 9;
struct DatabaseInitializer {
migration_lock: Mutex<()>,
@@ -149,6 +149,7 @@ fn initialize_schema(conn: &Connection) -> Result<()> {
wire_api TEXT NOT NULL DEFAULT 'responses',
requires_openai_auth INTEGER NOT NULL DEFAULT 1,
model_mappings_json TEXT NOT NULL DEFAULT '[]',
upstream_api TEXT,
source TEXT NOT NULL DEFAULT 'manual',
source_id TEXT,
created_at TEXT NOT NULL,
@@ -260,6 +261,12 @@ fn initialize_schema(conn: &Connection) -> Result<()> {
"model_mappings_json",
"ALTER TABLE providers ADD COLUMN model_mappings_json TEXT NOT NULL DEFAULT '[]'",
)?;
ensure_sqlite_column(
conn,
"providers",
"upstream_api",
"ALTER TABLE providers ADD COLUMN upstream_api TEXT",
)?;
conn.execute_batch(
"CREATE UNIQUE INDEX IF NOT EXISTS idx_providers_source_identity
ON providers(source, source_id)
@@ -499,6 +506,120 @@ mod tests {
remove_test_db(&path);
}
#[test]
fn version_eight_migration_keeps_provider_data_and_defaults_upstream_api_to_null() {
let path = test_db_path("provider-upstream-api-v9");
fs::create_dir_all(path.parent().unwrap()).unwrap();
let legacy = Connection::open(&path).unwrap();
legacy
.execute_batch(
"CREATE TABLE providers (
id TEXT PRIMARY KEY,
provider_name TEXT NOT NULL,
base_url TEXT NOT NULL,
model TEXT NOT NULL,
api_key TEXT,
toml_config TEXT,
wire_api TEXT NOT NULL DEFAULT 'responses',
requires_openai_auth INTEGER NOT NULL DEFAULT 1,
model_mappings_json TEXT NOT NULL DEFAULT '[]',
source TEXT NOT NULL DEFAULT 'manual',
source_id TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
INSERT INTO providers
(id, provider_name, base_url, model, api_key, toml_config, wire_api,
requires_openai_auth, model_mappings_json, source, source_id,
created_at, updated_at)
VALUES
('legacy-responses', 'Existing Responses provider', 'https://responses.fixture/v1',
'existing-model', 'fixture-secret', 'model_provider = \"custom\"', 'responses',
1, '[{\"displayName\":\"Mapped model\",\"model\":\"upstream-model\"}]',
'cc-switch', 'fixture-source-row', 'original-created', 'original-updated'),
('legacy-chat', 'Existing Chat provider', 'https://chat.fixture/v1',
'chat-model', NULL, NULL, 'chat',
0, '[]', 'manual', NULL, 'chat-created', 'chat-updated');
PRAGMA user_version = 8;",
)
.unwrap();
assert_eq!(schema_version(&legacy).unwrap(), 8);
assert!(!table_column_set(&legacy, "providers")
.unwrap()
.contains("upstream_api"));
let snapshot = |conn: &Connection| {
let mut statement = conn
.prepare(
"SELECT id, provider_name, base_url, model, api_key, toml_config,
wire_api, requires_openai_auth, model_mappings_json,
source, source_id, created_at, updated_at
FROM providers ORDER BY id",
)
.unwrap();
let rows = statement
.query_map([], |row| {
(0..13)
.map(|index| row.get::<_, rusqlite::types::Value>(index))
.collect::<rusqlite::Result<Vec<_>>>()
})
.unwrap();
rows.collect::<rusqlite::Result<Vec<_>>>().unwrap()
};
let before = snapshot(&legacy);
drop(legacy);
let initializer = DatabaseInitializer::new();
let migrated = initializer.open_at(&path).unwrap();
assert_eq!(schema_version(&migrated).unwrap(), 9);
assert!(table_column_set(&migrated, "providers")
.unwrap()
.contains("upstream_api"));
assert_eq!(
snapshot(&migrated),
before,
"all pre-existing provider columns must survive migration unchanged"
);
let upstream_values = migrated
.prepare("SELECT upstream_api FROM providers ORDER BY id")
.unwrap()
.query_map([], |row| row.get::<_, Option<String>>(0))
.unwrap()
.collect::<rusqlite::Result<Vec<_>>>()
.unwrap();
assert_eq!(upstream_values, vec![None, None]);
let providers = crate::providers::list_saved_providers_on_connection(&migrated).unwrap();
assert_eq!(providers.len(), 2);
let responses = providers
.iter()
.find(|provider| provider.id == "legacy-responses")
.unwrap();
assert!(responses.upstream_api.is_none());
assert_eq!(responses.api_key.as_deref(), Some("fixture-secret"));
assert_eq!(responses.model_mappings.len(), 1);
assert_eq!(responses.model_mappings[0].model, "upstream-model");
drop(migrated);
let reopened = DatabaseInitializer::new().open_at(&path).unwrap();
assert_eq!(schema_version(&reopened).unwrap(), 9);
assert_eq!(
snapshot(&reopened),
before,
"reopening must leave migrated provider data unchanged"
);
assert_eq!(
reopened
.query_row(
"SELECT COUNT(*) FROM providers WHERE upstream_api IS NULL",
[],
|row| row.get::<_, i64>(0)
)
.unwrap(),
2
);
drop(reopened);
remove_test_db(&path);
}
#[test]
fn version_one_database_migrates_new_metadata_tables_without_data_loss() {
let path = test_db_path("skills-mcp-notes-migration");
+279 -65
View File
@@ -6,7 +6,7 @@ use serde::Serialize;
use std::fs::{self, File, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use std::sync::Mutex;
use std::time::Duration;
use tauri::{ipc::Channel, Manager, ResourceId, Webview};
@@ -17,8 +17,32 @@ use tauri_plugin_updater::Update;
mod windows;
static UPDATING: AtomicBool = AtomicBool::new(false);
// 0: not installing, 1: installer preparation/write, 2: Windows handoff.
static INSTALLATION_PHASE: AtomicU8 = AtomicU8::new(0);
const DOWNLOAD_TIMEOUT_MS: u64 = 10 * 60 * 1000;
struct InstallationExitGuard<'a>(&'a AtomicU8);
impl<'a> InstallationExitGuard<'a> {
fn begin(phase: &'a AtomicU8) -> Self {
phase.store(1, Ordering::Release);
Self(phase)
}
#[cfg(any(test, target_os = "windows"))]
fn handed_off(self) {
self.0.store(2, Ordering::Release);
std::mem::forget(self);
}
}
impl Drop for InstallationExitGuard<'_> {
fn drop(&mut self) {
self.0.store(0, Ordering::Release);
}
}
pub(crate) fn defer_exit_during_installation() -> bool {
INSTALLATION_PHASE.load(Ordering::Acquire) == 1
}
#[derive(Clone, Serialize)]
#[serde(tag = "event", content = "data")]
pub(crate) enum AppUpdateEvent {
@@ -95,6 +119,24 @@ fn failure(stage: FailureStage, message: &str, log: Option<&UpdateLog>) -> Updat
}
}
/// Check before changing the installed application on every platform. The
/// converted supplier cannot resume through a raw Responses endpoint after exit.
fn install_with_route_preflight<T>(
check: impl FnOnce() -> Result<(), ()>,
install: impl FnOnce() -> Result<T, UpdateFailure>,
log: &UpdateLog,
) -> Result<T, UpdateFailure> {
if check().is_err() {
log.record("routing_recovery_preflight_failed");
return Err(failure(
FailureStage::Prepare,
"更新前未能确认连接配置可恢复,安装尚未开始。请检查路由配置后重试。",
Some(log),
));
}
install()
}
/// This log contains only our fixed stage names and version, never URLs,
/// headers, auth/config contents or raw network/parser error messages.
struct UpdateLog {
@@ -142,6 +184,115 @@ fn timeout_ms(value: Option<u64>) -> u64 {
.clamp(30_000, DOWNLOAD_TIMEOUT_MS)
}
enum DownloadAttemptFailure {
Transport,
Verification,
}
async fn download_attempt(
update: &Update,
on_event: &Channel<AppUpdateEvent>,
log: &UpdateLog,
) -> Result<Vec<u8>, DownloadAttemptFailure> {
let finished = AtomicBool::new(false);
let mut started = false;
update
.download(
|chunk_length, content_length| {
if !started {
started = true;
let _ = on_event.send(AppUpdateEvent::Started { content_length });
}
let _ = on_event.send(AppUpdateEvent::Progress { chunk_length });
},
|| {
finished.store(true, Ordering::Release);
log.record("verifying_signature");
let _ = on_event.send(AppUpdateEvent::Verifying);
},
)
.await
.map_err(|_| {
if finished.load(Ordering::Acquire) {
DownloadAttemptFailure::Verification
} else {
DownloadAttemptFailure::Transport
}
})
}
async fn download_with_recovery(
update: &Update,
mut candidates: Vec<reqwest::Url>,
on_event: &Channel<AppUpdateEvent>,
log: &UpdateLog,
) -> Result<Vec<u8>, UpdateFailure> {
match download_attempt(update, on_event, log).await {
Ok(bytes) => return Ok(bytes),
Err(DownloadAttemptFailure::Verification) => {
log.record("signature_verification_failed");
return Err(failure(
FailureStage::Verify,
"更新包校验未通过,未启动安装。请重新检查在线更新。",
Some(log),
));
}
Err(DownloadAttemptFailure::Transport) => log.record("primary_download_transport_failed"),
}
if candidates.is_empty() {
match crate::app_update_channel::discover_download_candidates(update).await {
Ok(found) => candidates = found,
Err(_) => log.record("official_api_asset_lookup_failed"),
}
}
for candidate in candidates {
let alternate = match crate::app_update_channel::api_download_update(update, &candidate) {
Ok(alternate) => alternate,
Err(_) => continue,
};
log.record("retrying_download_via_official_api");
match download_attempt(&alternate, on_event, log).await {
Ok(bytes) => {
log.record("official_api_download_verified");
return Ok(bytes);
}
Err(DownloadAttemptFailure::Verification) => {
log.record("signature_verification_failed");
return Err(failure(
FailureStage::Verify,
"更新包校验未通过,未启动安装。请重新检查在线更新。",
Some(log),
));
}
Err(DownloadAttemptFailure::Transport) => {
log.record("official_api_download_transport_failed")
}
}
}
Err(failure(
FailureStage::Download,
"在线更新的主通道和官方备用通道均未能完成下载。请检查网络或代理后重试。",
Some(log),
))
}
#[cfg(test)]
pub(crate) async fn verify_download_recovery_for_test(
update: &Update,
candidates: Vec<reqwest::Url>,
) -> Result<Vec<u8>, UpdateFailure> {
let temporary = tempfile::tempdir().expect("temporary updater test log");
let log = UpdateLog::create(temporary.path(), &update.version).expect("updater test log");
let channel = Channel::new(|_| Ok(()));
let bytes = download_with_recovery(update, candidates, &channel, &log).await?;
// Exercise the Windows staging handoff with verified fixture bytes only.
// Dropping this private temporary file never executes an installer.
let staged = windows::StagedInstaller::create(&bytes)
.expect("verified synthetic Windows packet stages successfully");
drop(staged);
Ok(bytes)
}
/// No installer is launched until all preparation succeeds. If launch fails,
/// restore routing while the original app and single-instance lock still live.
#[cfg(any(test, target_os = "windows"))]
@@ -201,18 +352,26 @@ pub(crate) async fn install_app_update(
headers: Option<Vec<(String, String)>>,
) -> Result<InstallResult, UpdateFailure> {
let _lease = UpdateLease::acquire(&UPDATING)?;
let update = webview
.resources_table()
.get::<Update>(update_rid)
.map_err(|_| {
failure(
FailureStage::Prepare,
"更新信息已失效,请重新检查更新。",
None,
)
})?;
let mut update = (*update).clone();
// The 15s metadata-check timeout must not become the package-download limit.
let (mut update, download_candidates) = if let Ok(owned) =
webview
.resources_table()
.get::<crate::app_update_channel::OwnedOnlineUpdate>(update_rid)
{
(owned.update.clone(), owned.download_candidates.clone())
} else {
let update = webview
.resources_table()
.get::<Update>(update_rid)
.map_err(|_| {
failure(
FailureStage::Prepare,
"更新信息已失效,请重新检查更新。",
None,
)
})?;
((*update).clone(), Vec::new())
};
// The metadata-check timeout must not become the package-download limit.
update.timeout = Some(Duration::from_millis(timeout_ms(timeout)));
if let Some(headers) = headers {
update.headers.clear();
@@ -235,47 +394,14 @@ pub(crate) async fn install_app_update(
)
})?;
log.record("download_started");
let finished = AtomicBool::new(false);
let mut started = false;
let bytes = update
.download(
|chunk_length, content_length| {
if !started {
started = true;
let _ = on_event.send(AppUpdateEvent::Started { content_length });
}
let _ = on_event.send(AppUpdateEvent::Progress { chunk_length });
},
|| {
finished.store(true, Ordering::Release);
log.record("verifying_signature");
let _ = on_event.send(AppUpdateEvent::Verifying);
},
)
.await
.map_err(|_| {
if finished.load(Ordering::Acquire) {
log.record("signature_verification_failed");
failure(
FailureStage::Verify,
"更新包校验未通过,安装尚未启动。请重新下载或前往下载页。",
Some(&log),
)
} else {
log.record("download_failed");
failure(
FailureStage::Download,
"更新下载未完成或连接超时。请检查网络后重试。",
Some(&log),
)
}
})?;
let bytes = download_with_recovery(&update, download_candidates, &on_event, &log).await?;
log.record("signature_verified");
let exit_guard = InstallationExitGuard::begin(&INSTALLATION_PHASE);
#[cfg(target_os = "windows")]
{
let app = webview.app_handle().clone();
let result = install_windows(app, bytes, on_event, log).await;
let result = install_windows(app, bytes, on_event, log, exit_guard).await;
if result.is_ok() {
_lease.handoff();
}
@@ -283,17 +409,33 @@ pub(crate) async fn install_app_update(
}
#[cfg(not(target_os = "windows"))]
{
let _ = on_event.send(AppUpdateEvent::Installing);
log.record("install_started");
let _ = on_event.send(AppUpdateEvent::Preparing);
tauri::async_runtime::spawn_blocking(move || {
update.install(bytes).map_err(|_| {
log.record("install_failed");
failure(
FailureStage::Install,
"安装更新未完成,请重试或前往下载页安装。",
Some(&log),
)
})?;
let _exit_guard = exit_guard;
install_with_route_preflight(
|| crate::failover::begin_update_handoff().map_err(|_| ()),
|| {
let _ = on_event.send(AppUpdateEvent::Installing);
log.record("install_started");
update.install(bytes).map_err(|_| {
log.record("install_failed");
if crate::failover::resume_after_failed_update().is_err() {
log.record("routing_resume_failed");
}
failure(
FailureStage::Install,
"安装更新未完成,请重试或前往下载页安装。",
Some(&log),
)
})
},
&log,
)?;
// The application bytes are already installed. A recovery warning
// must not turn this into an install retry or a second installer.
if crate::failover::resume_after_failed_update().is_err() {
log.record("routing_resume_failed_after_install_restart_required");
}
log.record("install_finished_restart_required");
Ok(InstallResult {
restart_required: true,
@@ -301,6 +443,7 @@ pub(crate) async fn install_app_update(
})
.await
.map_err(|_| {
let _ = crate::failover::resume_after_failed_update();
failure(
FailureStage::Install,
"安装更新未完成,请重新打开软件后检查更新。",
@@ -319,6 +462,7 @@ async fn install_windows(
bytes: Vec<u8>,
on_event: Channel<AppUpdateEvent>,
log: UpdateLog,
exit_guard: InstallationExitGuard<'static>,
) -> Result<InstallResult, UpdateFailure> {
tauri::async_runtime::spawn_blocking(move || {
// Stage bytes before changing live routes. Only signed .exe payloads
@@ -332,20 +476,27 @@ async fn install_windows(
})?;
let _ = on_event.send(AppUpdateEvent::Preparing);
log.record("preparing_route_shutdown");
prepared_install(
|| crate::failover::shutdown_all().map_err(|_| ()),
install_with_route_preflight(
|| crate::failover::ensure_shutdown_allowed().map_err(|_| ()),
|| {
let _ = on_event.send(AppUpdateEvent::Installing);
log.record("launching_installer");
installer.launch(std::process::id()).map_err(|_| ())
prepared_install(
|| crate::failover::shutdown_all().map_err(|_| ()),
|| {
let _ = on_event.send(AppUpdateEvent::Installing);
log.record("launching_installer");
installer.launch(std::process::id()).map_err(|_| ())
},
|| crate::failover::resume_after_failed_update().map_err(|_| ()),
&log,
)
},
|| crate::failover::resume_after_failed_update().map_err(|_| ()),
&log,
)?;
log.record("installer_handed_off");
let _ = on_event.send(AppUpdateEvent::HandedOff);
// Normal Tauri exit destroys windows/tray/single-instance lock. The
// new installer waits for this PID before touching installed files.
exit_guard.handed_off();
app.exit(0);
Ok(InstallResult {
restart_required: false,
@@ -366,6 +517,69 @@ mod tests {
use super::*;
use std::cell::RefCell;
#[test]
fn installation_exit_guard_releases_on_failure_and_allows_windows_handoff() {
let phase = AtomicU8::new(0);
{
let _guard = InstallationExitGuard::begin(&phase);
assert_eq!(phase.load(Ordering::Acquire), 1);
}
assert_eq!(phase.load(Ordering::Acquire), 0);
InstallationExitGuard::begin(&phase).handed_off();
assert_eq!(phase.load(Ordering::Acquire), 2);
assert_ne!(phase.load(Ordering::Acquire), 1);
}
#[test]
fn invalid_recovery_preflight_blocks_install_before_application_bytes_change() {
let temp = tempfile::tempdir().unwrap();
let log = UpdateLog::create(temp.path(), "0.4.0").unwrap();
let app = temp.path().join("fixture-app");
fs::write(&app, b"original fixture").unwrap();
let error = install_with_route_preflight(
|| Err(()),
|| {
fs::write(&app, b"replacement fixture").unwrap();
Ok(())
},
&log,
)
.unwrap_err();
assert_eq!(error.stage, FailureStage::Prepare);
assert!(error.message.contains("可恢复"));
assert!(error.message.contains("安装尚未开始"));
assert_eq!(fs::read(&app).unwrap(), b"original fixture");
let stages = fs::read_to_string(&log.path).unwrap();
assert!(stages.contains("routing_recovery_preflight_failed"));
assert!(!stages.contains("install_started"));
}
#[test]
fn native_route_preflight_installs_once_and_preserves_installer_errors() {
let temp = tempfile::tempdir().unwrap();
let log = UpdateLog::create(temp.path(), "0.4.0").unwrap();
let calls = RefCell::new(vec![]);
let error = install_with_route_preflight(
|| {
calls.borrow_mut().push("check");
Ok(())
},
|| {
calls.borrow_mut().push("install");
Err::<(), _>(failure(
FailureStage::Install,
"fixture install error",
Some(&log),
))
},
&log,
)
.unwrap_err();
assert_eq!(*calls.borrow(), vec!["check", "install"]);
assert_eq!(error.stage, FailureStage::Install);
assert_eq!(error.message, "fixture install error");
}
#[test]
fn one_update_at_a_time_and_errors_release_the_guard() {
let flag = AtomicBool::new(false);
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,488 @@
//! Windows desktop discovery and activation. This module deliberately uses
//! Windows' registered package/signature/process APIs, never executable names
//! alone, before stopping a process or attaching to its debugging endpoint.
#![cfg_attr(not(target_os = "windows"), allow(dead_code))]
use base64::Engine;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};
#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct WindowsDesktopApp {
pub(crate) path: PathBuf,
pub(crate) executable: PathBuf,
pub(crate) bundle_id: String,
pub(crate) name: String,
pub(crate) version: String,
}
fn stamps() -> &'static Mutex<HashMap<u32, String>> {
static STAMPS: OnceLock<Mutex<HashMap<u32, String>>> = OnceLock::new();
STAMPS.get_or_init(|| Mutex::new(HashMap::new()))
}
fn powershell(script: &str, data: Value, timeout: Duration) -> Result<Value, String> {
let system_root = std::env::var_os("SystemRoot").ok_or("无法定位 Windows 系统目录")?;
let executable =
PathBuf::from(system_root).join("System32/WindowsPowerShell/v1.0/powershell.exe");
let encoded = base64::engine::general_purpose::STANDARD
.encode(serde_json::to_vec(&data).map_err(|_| "无法编码 Windows 客户端操作参数")?);
// All variable input is JSON data. Paths and config values are never
// interpolated as PowerShell source or passed through a command shell.
let source = format!(
"$ErrorActionPreference='Stop'; $ProgressPreference='SilentlyContinue'; \
[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false); \
$data=([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('{encoded}')) | ConvertFrom-Json);\n\
{COMMON}\n{script}"
);
let output = crate::platform::desktop_command_output(
&executable,
&[
"-NoLogo",
"-NoProfile",
"-NonInteractive",
"-Command",
&source,
],
timeout,
)?;
if !output.status.success() {
let details = String::from_utf8_lossy(&output.stderr)
.chars()
.take(1800)
.collect::<String>();
return Err(format!("Windows Codex 操作未完成:{}", details.trim()));
}
serde_json::from_slice(&output.stdout).map_err(|_| "Windows 未返回有效的客户端操作结果".into())
}
const COMMON: &str = r#"
function FullPath($path) { [IO.Path]::GetFullPath([string]$path).TrimEnd('\') }
function SamePath($left, $right) {
[string]::Equals((FullPath $left), (FullPath $right), [StringComparison]::OrdinalIgnoreCase)
}
function ProcessStamp($process) {
if ($null -eq $process.CreationDate) { throw 'Cannot verify the process creation time.' }
$process.CreationDate.ToUniversalTime().Ticks.ToString([Globalization.CultureInfo]::InvariantCulture)
}
function AppProcesses($exe) {
$processes=@(Get-CimInstance Win32_Process -Filter "Name='Codex.exe' OR Name='ChatGPT.exe'")
if (@($processes | Where-Object { -not $_.ExecutablePath }).Count -gt 0) {
throw 'A Codex/ChatGPT process path is inaccessible. Use matching non-elevated permissions before restarting.'
}
@($processes | Where-Object { SamePath $_.ExecutablePath $exe })
}
function MainProcesses($exe) {
@(AppProcesses $exe | Where-Object {
if ($null -eq $_.CommandLine) { throw 'Cannot verify the desktop process command line.' }
$_.CommandLine -notmatch '(?i)(?:^|\s)--type(?:=|\s)' -and
$_.CommandLine -notmatch '(?i)(?:^|\s)--crashpad-handler(?:\s|$)'
})
}
function BoundProcess($entry, $exe) {
$process=Get-Process -Id $entry.ProcessId -ErrorAction SilentlyContinue
if ($null -eq $process) { return $null }
try {
# Holding this handle pins the process object/PID through the subsequent
# identity checks and CloseMainWindow/Kill call.
$null=$process.Handle
$created=$process.StartTime.ToUniversalTime().Ticks
$expected=[long](ProcessStamp $entry)
if (-not (SamePath $process.MainModule.FileName $exe) -or
[Math]::Abs($created-$expected) -ge 10) { $process.Dispose(); return $null }
# CIM timestamps have microsecond precision, while StartTime has 100ns.
return $process
} catch { $process.Dispose(); return $null }
}
function IsDesktopExe($exe) {
$leaf=[IO.Path]::GetFileName([string]$exe)
($leaf -ieq 'Codex.exe' -or $leaf -ieq 'ChatGPT.exe') -and
(Test-Path -LiteralPath $exe -PathType Leaf) -and
(Test-Path -LiteralPath (Join-Path ([IO.Path]::GetDirectoryName($exe)) 'resources\app.asar') -PathType Leaf)
}
function TrustedStandalone($exe) {
if (-not (IsDesktopExe $exe)) { return $false }
$signature=Get-AuthenticodeSignature -LiteralPath $exe
if ($signature.Status -ne 'Valid' -or $null -eq $signature.SignerCertificate) { return $false }
$publisher=$signature.SignerCertificate.GetNameInfo([Security.Cryptography.X509Certificates.X509NameType]::SimpleName,$false)
@('OpenAI OpCo, LLC','OpenAI, L.L.C.') -ccontains $publisher
}
function TrustedPackage($package) {
$null -ne $package -and
@('OpenAI.Codex','OpenAI.CodexBeta','OpenAI.ChatGPT-Desktop') -ccontains [string]$package.Name -and
[string]$package.PublisherId -ceq '2p2nqsd0c76g0' -and
[string]$package.PackageFamilyName -ceq ($package.Name+'_2p2nqsd0c76g0') -and
[string]$package.Status -eq 'Ok' -and [string]$package.SignatureKind -eq 'Store' -and
-not $package.IsDevelopmentMode
}
function PackageApp($package) {
$root=FullPath $package.InstallLocation
$manifest=Get-AppxPackageManifest -Package $package.PackageFullName
foreach ($entry in @($manifest.Package.Applications.Application)) {
if (-not $entry.Executable -or -not $entry.Id) { continue }
$exe=FullPath (Join-Path $root ([string]$entry.Executable))
if (-not $exe.StartsWith($root+'\',[StringComparison]::OrdinalIgnoreCase)) { continue }
if (-not (IsDesktopExe $exe)) { continue }
return [pscustomobject]@{path=$root;executable=$exe;bundleId=($package.PackageFamilyName+'!'+$entry.Id);
name=$(if($package.Name -eq 'OpenAI.ChatGPT-Desktop'){'ChatGPT'}else{'Codex'});version=[string]$package.Version}
}
return $null
}
function ValidateApp($app) {
if (-not (IsDesktopExe $app.executable)) { throw 'The selected path is not the official Electron desktop application.' }
if ([string]$app.bundleId -eq 'OpenAI.Codex.Standalone') {
if (-not (SamePath ([IO.Path]::GetDirectoryName($app.executable)) $app.path) -or
-not (TrustedStandalone $app.executable)) { throw 'The desktop executable has no valid OpenAI publisher signature.' }
return
}
$principal=[Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent())
if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
throw 'Microsoft Store activation requires Codex-X to run without administrator elevation. No client was stopped.'
}
$family=([string]$app.bundleId).Split('!')[0]
$package=@(Get-AppxPackage | Where-Object { [string]$_.PackageFamilyName -ceq $family }) | Select-Object -First 1
if (-not (TrustedPackage $package)) { throw 'The official signed Microsoft Store package is no longer registered.' }
$registered=PackageApp $package
if ($null -eq $registered -or $registered.bundleId -cne $app.bundleId -or
-not (SamePath $registered.path $app.path) -or
-not (SamePath $registered.executable $app.executable)) { throw 'The registered Store application identity has changed.' }
}
function Emit($result) { ConvertTo-Json -InputObject $result -Depth 6 -Compress }
"#;
pub(crate) fn detect() -> Result<WindowsDesktopApp, String> {
type Cached = (Instant, Result<WindowsDesktopApp, String>);
static CACHE: OnceLock<Mutex<Option<Cached>>> = OnceLock::new();
let mut cache = CACHE
.get_or_init(|| Mutex::new(None))
.lock()
.map_err(|_| "Windows 客户端检测状态忙")?;
if let Some((recorded, value)) = cache.as_ref() {
let ttl = if value.is_ok() { 30 } else { 10 };
if recorded.elapsed() < Duration::from_secs(ttl) {
return value.clone();
}
}
let value = detect_fresh();
*cache = Some((Instant::now(), value.clone()));
value
}
pub(crate) fn detect_fresh() -> Result<WindowsDesktopApp, String> {
let result = powershell(
r#"
$candidates=New-Object 'System.Collections.Generic.List[object]'
foreach ($package in @(Get-AppxPackage | Sort-Object -Property Version -Descending)) {
if (-not (TrustedPackage $package)) { continue }
try { $app=PackageApp $package } catch { continue }
if ($null -ne $app) { $candidates.Add($app) }
}
if ($env:LOCALAPPDATA) {
$roots=@('OpenAI\Codex\bin','OpenAI\Codex','Programs\OpenAI\Codex','Programs\Codex')
$seen=@{}
foreach ($relative in $roots) {
$root=Join-Path $env:LOCALAPPDATA $relative
$directories=@($root,(Join-Path $root 'app'))
if (Test-Path -LiteralPath $root -PathType Container) {
foreach ($child in @(Get-ChildItem -LiteralPath $root -Directory -ErrorAction SilentlyContinue | Select-Object -First 32)) {
$directories+=@($child.FullName,(Join-Path $child.FullName 'app'))
}
}
foreach ($directory in $directories) {
foreach ($leaf in @('Codex.exe','ChatGPT.exe')) {
$exe=Join-Path $directory $leaf
$key=$exe.ToLowerInvariant()
if ($seen.ContainsKey($key)) { continue }; $seen[$key]=$true
if (-not (TrustedStandalone $exe)) { continue }
$version=(Get-Item -LiteralPath $exe).VersionInfo.ProductVersion
$candidates.Add([pscustomobject]@{path=(FullPath $directory);executable=(FullPath $exe);
bundleId='OpenAI.Codex.Standalone';name='Codex';version=[string]$version})
}
}
}
}
$running=@()
foreach ($app in $candidates) {
$main=@(MainProcesses $app.executable)
if ($main.Count -gt 1) { throw 'Multiple desktop instances are running. Keep one instance before restarting.' }
if ($main.Count -eq 1) { $running+=,$app }
}
if ($running.Count -gt 1) { throw 'Multiple official desktop installations are running. Keep one before restarting.' }
if ($running.Count -eq 1) { Emit $running[0]; exit }
if ($candidates.Count -eq 0) { throw 'No verified OpenAI Codex Store package or signed standalone installation was found.' }
Emit $candidates[0]
"#,
Value::Null,
Duration::from_secs(25),
)?;
serde_json::from_value(result).map_err(|_| "Windows 客户端安装信息无效".into())
}
pub(crate) fn validate(app: &WindowsDesktopApp) -> Result<(), String> {
powershell(
"ValidateApp $data.app; Emit $true",
json!({"app":app}),
Duration::from_secs(15),
)
.map(|_| ())
}
pub(crate) fn validate_launch(app: &WindowsDesktopApp, home: &Path) -> Result<(), String> {
if app.bundle_id != "OpenAI.Codex.Standalone" {
let default = dirs::home_dir()
.ok_or("无法确认 Windows 默认 Codex 配置目录")?
.join(".codex");
let requested = crate::paths::normalized_path_scope(home);
let expected = crate::paths::normalized_path_scope(&default);
if requested != expected {
return Err("Windows Store 版无法通过安全激活传入自定义 CODEX_HOME;请使用默认 .codex 目录或官方独立安装版。客户端尚未退出。".into());
}
}
Ok(())
}
pub(crate) fn pids(app: &WindowsDesktopApp) -> Result<Vec<u32>, String> {
let value = powershell(
"Emit @(AppProcesses $data.app.executable | ForEach-Object { [uint32]$_.ProcessId })",
json!({"app":app}),
Duration::from_secs(8),
)?;
serde_json::from_value(value).map_err(|_| "无法确认 Windows 客户端进程".into())
}
pub(crate) fn quit(app: &WindowsDesktopApp) -> Result<(), String> {
powershell(
r#"
ValidateApp $data.app
$main=@(MainProcesses $data.app.executable)
if ($main.Count -gt 1) { throw 'Multiple desktop instances are running; none was stopped.' }
foreach ($entry in $main) {
$process=BoundProcess $entry $data.app.executable
if ($null -ne $process) {
try { $null=$process.CloseMainWindow() } finally { $process.Dispose() }
}
}
$grace=[DateTime]::UtcNow.AddSeconds(2)
while ([DateTime]::UtcNow -lt $grace -and @(AppProcesses $data.app.executable).Count -gt 0) { Start-Sleep -Milliseconds 100 }
# The user explicitly requested a restart. If a tray/renderer remains, stop
# only processes whose live executable path still matches this verified app.
foreach ($entry in @(AppProcesses $data.app.executable)) {
$process=BoundProcess $entry $data.app.executable
if ($null -ne $process) {
try { $process.Kill() } catch { } finally { $process.Dispose() }
}
}
$deadline=[DateTime]::UtcNow.AddSeconds(8); $emptySince=$null
do {
if (@(AppProcesses $data.app.executable).Count -eq 0) {
if ($null -eq $emptySince) { $emptySince=[DateTime]::UtcNow }
if (([DateTime]::UtcNow-$emptySince).TotalMilliseconds -ge 500) { Emit $true; exit }
} else { $emptySince=$null }
Start-Sleep -Milliseconds 100
} while ([DateTime]::UtcNow -lt $deadline)
throw 'The selected desktop processes did not stop; relaunch was cancelled.'
"#,
json!({"app":app}),
Duration::from_secs(20),
)
.map(|_| ())
}
pub(crate) fn launch(
app: &WindowsDesktopApp,
home: Option<&Path>,
port: Option<u16>,
) -> Result<u32, String> {
if let Some(home) = home {
validate_launch(app, home)?;
}
if app.bundle_id == "OpenAI.Codex.Standalone" {
return launch_standalone(app, home, port);
}
let result = powershell(
r#"
ValidateApp $data.app
if (@(AppProcesses $data.app.executable).Count -gt 0) { throw 'The desktop application is still stopping; no duplicate instance was launched.' }
$arguments=''
if ($null -ne $data.port) { $arguments='--remote-debugging-port='+[string]$data.port+' --remote-debugging-address=127.0.0.1' }
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
[ComImport, Guid("2e941141-7f97-4756-ba1d-9decde894a3d"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface ICodexActivationManager {
[PreserveSig] int ActivateApplication([MarshalAs(UnmanagedType.LPWStr)] string appId,
[MarshalAs(UnmanagedType.LPWStr)] string arguments, uint options, out uint processId);
}
public static class CodexPackageActivation {
public static uint Start(string appId, string arguments) {
var manager=(ICodexActivationManager)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("45ba127d-10a8-46ea-8ab7-56ea9078943c")));
try { uint processId; int result=manager.ActivateApplication(appId, arguments, 0, out processId);
Marshal.ThrowExceptionForHR(result); return processId; }
finally { Marshal.FinalReleaseComObject(manager); }
}
}
'@ | Out-Null
$started=[CodexPackageActivation]::Start([string]$data.app.bundleId,$arguments)
if ($started -eq 0) { throw 'Windows did not return an activated process id.' }
$created=''; $deadline=[DateTime]::UtcNow.AddSeconds(5)
do {
$process=Get-CimInstance Win32_Process -Filter ('ProcessId='+$started)
if ($null -ne $process -and $process.ExecutablePath) {
if (-not (SamePath $process.ExecutablePath $data.app.executable)) { throw 'Windows activated a different executable; no debugging connection was made.' }
$created=ProcessStamp $process; break
}
Start-Sleep -Milliseconds 100
} while ([DateTime]::UtcNow -lt $deadline)
if (-not $created) { throw 'Windows activation returned but the official desktop process did not start.' }
Emit @{pid=$started;created=$created}
"#,
json!({"app":app,"home":home,"port":port}),
Duration::from_secs(20),
)?;
remember_started(result)
}
fn remember_started(result: Value) -> Result<u32, String> {
let pid = result["pid"]
.as_u64()
.and_then(|value| u32::try_from(value).ok())
.filter(|pid| *pid != 0)
.ok_or("Windows 未确认已启动的客户端进程")?;
let created = result["created"]
.as_str()
.filter(|value| !value.is_empty())
.ok_or("Windows 未确认客户端进程身份")?;
let mut tracked = stamps().lock().map_err(|_| "Windows 进程状态忙")?;
if tracked.len() >= 16 {
tracked.clear();
}
tracked.insert(pid, created.to_owned());
Ok(pid)
}
fn launch_standalone(
app: &WindowsDesktopApp,
home: Option<&Path>,
port: Option<u16>,
) -> Result<u32, String> {
powershell(
"ValidateApp $data.app; if (@(AppProcesses $data.app.executable).Count -gt 0) { throw 'The desktop is still stopping; no duplicate was launched.' }; Emit $true",
json!({"app":app}),
Duration::from_secs(15),
)?;
let arguments = port
.map(|port| {
vec![
format!("--remote-debugging-port={port}"),
"--remote-debugging-address=127.0.0.1".to_owned(),
]
})
.unwrap_or_default();
let args: Vec<_> = arguments.iter().map(String::as_str).collect();
let mut command = crate::platform::program_command(&app.executable, &args);
command
.current_dir(&app.path)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
if let Some(home) = home {
command.env("CODEX_HOME", home);
}
let mut child = command
.spawn()
.map_err(|_| "无法启动已验证的 Windows Codex 客户端")?;
let pid = child.id();
let result = powershell(
r#"
$deadline=[DateTime]::UtcNow.AddSeconds(5)
do {
$process=Get-CimInstance Win32_Process -Filter ('ProcessId='+[uint32]$data.pid)
if ($null -ne $process -and $process.ExecutablePath) {
if (-not (SamePath $process.ExecutablePath $data.app.executable)) { throw 'The newly started process has an unexpected executable.' }
Emit @{pid=[uint32]$data.pid;created=(ProcessStamp $process)}; exit
}
Start-Sleep -Milliseconds 100
} while ([DateTime]::UtcNow -lt $deadline)
throw 'The signed desktop executable did not remain running.'
"#,
json!({"app":app,"pid":pid}),
Duration::from_secs(10),
).and_then(remember_started);
if result.is_err() {
// Child owns the original Windows process handle, so cleanup cannot
// terminate an unrelated process after a recycled PID.
let _ = child.kill();
let _ = child.try_wait();
}
// Windows has no zombie-process wait requirement. Dropping Child releases
// our process/thread handles while the GUI keeps its own lifetime.
drop(child);
result
}
pub(crate) fn verify_process(app: &WindowsDesktopApp, pid: u32) -> Result<(), String> {
let created = stamps()
.lock()
.map_err(|_| "Windows 进程状态忙")?
.get(&pid)
.cloned()
.ok_or("该客户端进程不属于本次受控启动")?;
powershell(
r#"
$process=Get-CimInstance Win32_Process -Filter ('ProcessId='+[uint32]$data.pid)
if ($null -eq $process -or -not $process.ExecutablePath -or
-not (SamePath $process.ExecutablePath $data.app.executable) -or
(ProcessStamp $process) -cne [string]$data.created) { throw 'The activated desktop process identity has changed.' }
Emit $true
"#,
json!({"app":app,"pid":pid,"created":created}),
Duration::from_secs(8),
)
.map(|_| ())
}
pub(crate) fn verify_listener(app: &WindowsDesktopApp, pid: u32, port: u16) -> Result<(), String> {
let created = stamps()
.lock()
.map_err(|_| "Windows 进程状态忙")?
.get(&pid)
.cloned()
.ok_or("该客户端进程不属于本次受控启动")?;
powershell(
r#"
$process=Get-CimInstance Win32_Process -Filter ('ProcessId='+[uint32]$data.pid)
if ($null -eq $process -or -not $process.ExecutablePath -or
-not (SamePath $process.ExecutablePath $data.app.executable) -or
(ProcessStamp $process) -cne [string]$data.created) { throw 'The activated desktop process identity has changed.' }
$listeners=@(Get-NetTCPConnection -State Listen -LocalPort ([uint16]$data.port) -ErrorAction SilentlyContinue)
if ($listeners.Count -eq 0) { throw 'The official desktop has not opened its debugging port.' }
foreach ($listener in $listeners) {
if ($listener.LocalAddress -cne '127.0.0.1' -or [uint32]$listener.OwningProcess -ne [uint32]$data.pid) {
throw 'The debugging port is not exclusively owned by the activated process on 127.0.0.1.'
}
}
$after=Get-CimInstance Win32_Process -Filter ('ProcessId='+[uint32]$data.pid)
if ($null -eq $after -or -not $after.ExecutablePath -or
-not (SamePath $after.ExecutablePath $data.app.executable) -or
(ProcessStamp $after) -cne [string]$data.created) { throw 'The desktop process changed while its port was being verified.' }
Emit $true
"#,
json!({"app":app,"pid":pid,"port":port,"created":created}),
Duration::from_secs(8),
)
.map(|_| ())
}
pub(crate) fn restart() -> Result<(String, bool), String> {
let app = detect_fresh()?;
validate(&app)?;
let was_running = !pids(&app)?.is_empty();
quit(&app)?;
launch(&app, None, None)?;
Ok((app.name, was_running))
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,280 @@
use serde::Deserialize;
use serde_json::{json, Value};
use std::io::Read;
use std::net::{Ipv4Addr, SocketAddr, TcpStream};
use std::time::{Duration, Instant};
use tungstenite::{client, Message, WebSocket};
const MAX_RESPONSE: usize = 512 * 1024;
#[derive(Clone, Deserialize)]
pub(super) struct Target {
pub(super) id: String,
#[serde(rename = "type")]
kind: String,
url: String,
#[serde(rename = "webSocketDebuggerUrl")]
socket: Option<String>,
}
pub(super) fn app_origin(url: &str) -> bool {
reqwest::Url::parse(url).is_ok_and(|url| {
url.scheme() == "app"
&& url.host_str() == Some("-")
&& url.port().is_none()
&& url.username().is_empty()
&& url.password().is_none()
&& matches!(url.path(), "/" | "/index.html")
})
}
fn socket_url(value: &str, port: u16) -> Result<reqwest::Url, String> {
let url = reqwest::Url::parse(value).map_err(|_| "调试目标地址无效")?;
if url.scheme() != "ws"
|| url.host_str() != Some("127.0.0.1")
|| url.port() != Some(port)
|| !url.username().is_empty()
|| url.password().is_some()
|| url.query().is_some()
|| url.fragment().is_some()
|| !url.path().starts_with("/devtools/page/")
|| url.path().trim_start_matches("/devtools/page/").is_empty()
{
return Err("调试目标超出指定本机端口,未执行语言脚本。".into());
}
Ok(url)
}
pub(super) fn targets(port: u16) -> Result<Vec<Target>, String> {
crate::remote::ensure_crypto_provider();
let client = reqwest::blocking::Client::builder()
.no_proxy()
.redirect(reqwest::redirect::Policy::none())
.timeout(Duration::from_secs(2))
.build()
.map_err(|_| "无法初始化本机语言兼容连接")?;
let response = client
.get(format!("http://127.0.0.1:{port}/json/list"))
.send()
.map_err(|_| "客户端未开放本机调试通道;此版本可能不支持兼容模式。")?;
if !response.status().is_success() {
return Err("客户端调试通道尚未就绪".into());
}
let mut bytes = Vec::new();
response
.take((MAX_RESPONSE + 1) as u64)
.read_to_end(&mut bytes)
.map_err(|_| "无法读取调试目标")?;
if bytes.len() > MAX_RESPONSE {
return Err("客户端返回的调试目标超过安全限制".into());
}
let targets: Vec<Target> =
serde_json::from_slice(&bytes).map_err(|_| "客户端未返回有效的调试目标")?;
if targets.len() > 128 {
return Err("客户端调试目标过多,未继续连接".into());
}
Ok(targets
.into_iter()
.filter(|target| {
target.kind == "page" && app_origin(&target.url) && target.socket.is_some()
})
.collect())
}
pub(super) struct Session {
socket: WebSocket<TcpStream>,
next_id: u64,
script: String,
}
impl Session {
pub(super) fn connect(target: &Target, port: u16) -> Result<Self, String> {
if target.kind != "page" || !app_origin(&target.url) {
return Err("不是官方客户端的本地界面目标".into());
}
let url = socket_url(target.socket.as_deref().ok_or("目标没有调试连接")?, port)?;
let stream = TcpStream::connect_timeout(
&SocketAddr::from((Ipv4Addr::LOCALHOST, port)),
Duration::from_secs(2),
)
.map_err(|_| "本机调试连接未建立")?;
stream
.set_read_timeout(Some(Duration::from_secs(2)))
.map_err(|_| "无法设置调试读取超时")?;
stream
.set_write_timeout(Some(Duration::from_secs(2)))
.map_err(|_| "无法设置调试写入超时")?;
let (mut socket, _) = client(url.as_str(), stream)
.map_err(|_| "客户端拒绝了安全调试连接;未降低客户端安全设置。")?;
socket.set_config(|config| {
config.max_message_size = Some(MAX_RESPONSE);
config.max_frame_size = Some(MAX_RESPONSE);
});
Ok(Self {
socket,
next_id: 0,
script: String::new(),
})
}
pub(super) fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
self.next_id += 1;
let id = self.next_id;
self.socket
.send(Message::Text(
json!({"id":id,"method":method,"params":params})
.to_string()
.into(),
))
.map_err(|_| "语言兼容命令发送失败")?;
let deadline = Instant::now() + Duration::from_secs(4);
while Instant::now() < deadline {
match self.socket.read().map_err(|_| "语言兼容连接中断或超时")? {
Message::Text(text) => {
if text.len() > MAX_RESPONSE {
return Err("调试返回内容超过限制".into());
}
let event: Value =
serde_json::from_str(&text).map_err(|_| "调试返回格式无效")?;
if event.get("id").and_then(Value::as_u64) != Some(id) {
continue;
}
if event.get("error").is_some() {
return Err("当前客户端不支持所需的界面兼容命令".into());
}
return Ok(event.get("result").cloned().unwrap_or(Value::Null));
}
Message::Ping(bytes) => {
self.socket
.send(Message::Pong(bytes))
.map_err(|_| "调试连接中断")?;
}
Message::Close(_) => return Err("客户端关闭了语言兼容连接".into()),
_ => {}
}
}
Err("等待界面兼容结果超时".into())
}
pub(super) fn install(&mut self, source: &str) -> Result<(), String> {
let origin=self.evaluate("(()=>{try{const u=new URL(location.href);return {allowed:window===window.top&&u.protocol==='app:'&&u.host==='-'&&!u.username&&!u.password&&['/','/index.html'].includes(u.pathname)};}catch{return {allowed:false};}})()")?;
if origin.get("allowed").and_then(Value::as_bool) != Some(true) {
return Err("目标页面来源在连接后已改变,未注册脚本或重载页面。".into());
}
self.call("Page.enable", json!({}))?;
let result = self.call(
"Page.addScriptToEvaluateOnNewDocument",
json!({"source":source}),
)?;
self.script = result
.get("identifier")
.and_then(Value::as_str)
.ok_or("客户端未确认兼容脚本注册")?
.to_owned();
self.call("Page.reload", json!({"ignoreCache":false}))?;
Ok(())
}
pub(super) fn evaluate(&mut self, source: &str) -> Result<Value, String> {
let result=self.call("Runtime.evaluate",json!({"expression":source,"returnByValue":true,"awaitPromise":true,"userGesture":false}))?;
if result.get("exceptionDetails").is_some() {
return Err("客户端界面不支持此语言兼容模式,未报告应用成功。".into());
}
Ok(result
.pointer("/result/value")
.cloned()
.unwrap_or(Value::Null))
}
}
impl Drop for Session {
fn drop(&mut self) {
if !self.script.is_empty() {
let script = self.script.clone();
let _ = self.call(
"Page.removeScriptToEvaluateOnNewDocument",
json!({"identifier":script}),
);
}
let _ = self.socket.close(None);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejects_browser_targets_remote_websockets_and_credentials() {
assert!(app_origin("app://-/index.html?initialRoute=%2Fsettings"));
for origin in [
"https://chatgpt.com/",
"http://127.0.0.1/index.html",
"app://other/index.html",
"app://user@-/index.html",
"app://-/browser.html",
] {
assert!(!app_origin(origin));
}
assert!(socket_url("ws://127.0.0.1:4567/devtools/page/fixture", 4567).is_ok());
for url in [
"ws://localhost:4567/devtools/page/x",
"ws://127.0.0.1:4568/devtools/page/x",
"ws://127.0.0.1:4567/devtools/browser/x",
"ws://user@127.0.0.1:4567/devtools/page/x",
"wss://127.0.0.1:4567/devtools/page/x",
] {
assert!(socket_url(url, 4567).is_err());
}
}
#[test]
fn simulated_cdp_registers_main_world_script_and_returns_only_fixture_status() {
let listener = std::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
let port = listener.local_addr().unwrap().port();
let server = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let mut socket = tungstenite::accept(stream).unwrap();
for (index, expected) in [
"Runtime.evaluate",
"Page.enable",
"Page.addScriptToEvaluateOnNewDocument",
"Page.reload",
"Runtime.evaluate",
"Page.removeScriptToEvaluateOnNewDocument",
]
.into_iter()
.enumerate()
{
let Message::Text(text) = socket.read().unwrap() else {
panic!("expected command")
};
let request: Value = serde_json::from_str(&text).unwrap();
assert_eq!(request["method"], expected);
let result = match expected {
"Page.addScriptToEvaluateOnNewDocument" => {
assert!(request["params"].get("worldName").is_none());
json!({"identifier":"fixture-script"})
}
"Runtime.evaluate" if index == 0 => {
json!({"result":{"value":{"allowed":true}}})
}
"Runtime.evaluate" => json!({"result":{"value":{"ready":true}}}),
_ => json!({}),
};
socket
.send(Message::Text(
json!({"id":request["id"],"result":result})
.to_string()
.into(),
))
.unwrap();
}
});
let target = Target {
id: "fixture".into(),
kind: "page".into(),
url: "app://-/index.html".into(),
socket: Some(format!("ws://127.0.0.1:{port}/devtools/page/fixture")),
};
{
let mut session = Session::connect(&target, port).unwrap();
session.install("/* fixture i18n script */").unwrap();
assert_eq!(session.evaluate("fixtureStatus()").unwrap()["ready"], true);
}
server.join().unwrap();
}
}
@@ -0,0 +1,332 @@
//! The locale compatibility launcher never modifies or re-signs the app bundle.
use std::path::{Path, PathBuf};
#[cfg(test)]
static REAPED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
fn process_reaper() -> Result<&'static std::sync::mpsc::Sender<std::process::Child>, String> {
static REAPER: std::sync::OnceLock<
Result<std::sync::mpsc::Sender<std::process::Child>, String>,
> = std::sync::OnceLock::new();
REAPER
.get_or_init(|| {
let (sender, receiver) = std::sync::mpsc::channel::<std::process::Child>();
std::thread::Builder::new()
.name("codex-language-process-reaper".into())
.spawn(move || {
let mut children: Vec<std::process::Child> = Vec::new();
loop {
match receiver.recv_timeout(std::time::Duration::from_millis(200)) {
Ok(child) => children.push(child),
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
Err(_) => break,
}
children.retain_mut(|child| match child.try_wait() {
Ok(None) => true,
Ok(Some(_)) => {
#[cfg(test)]
REAPED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
false
}
Err(_) => false,
});
}
})
.map_err(|_| "无法初始化客户端进程回收线程,尚未退出客户端。".to_owned())?;
Ok(sender)
})
.as_ref()
.map_err(Clone::clone)
}
pub(crate) fn prepare_launch() -> Result<(), String> {
process_reaper().map(|_| ())
}
#[derive(Clone)]
pub(crate) struct DesktopApp {
pub(crate) path: PathBuf,
pub(crate) executable: PathBuf,
pub(crate) bundle_id: String,
pub(crate) name: String,
pub(crate) version: String,
}
#[cfg(target_os = "windows")]
fn windows_app(app: &DesktopApp) -> crate::platform::desktop_windows::WindowsDesktopApp {
crate::platform::desktop_windows::WindowsDesktopApp {
path: app.path.clone(),
executable: app.executable.clone(),
bundle_id: app.bundle_id.clone(),
name: app.name.clone(),
version: app.version.clone(),
}
}
#[cfg(target_os = "macos")]
fn command(program: &str, args: &[&str]) -> Result<String, String> {
let output = crate::platform::locale_platform_command(Path::new(program), args)?;
Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
}
pub(crate) fn detect() -> Result<DesktopApp, String> {
#[cfg(target_os = "macos")]
{
let app = crate::platform::locale_desktop_app()?;
Ok(DesktopApp {
path: app.0,
executable: app.1,
bundle_id: app.2,
name: app.3,
version: app.4,
})
}
#[cfg(target_os = "windows")]
{
let app = crate::platform::desktop_windows::detect()?;
Ok(DesktopApp {
path: app.path,
executable: app.executable,
bundle_id: app.bundle_id,
name: app.name,
version: app.version,
})
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
{
Err("当前平台尚未实现可验证官方进程的界面语言启动器。".into())
}
}
pub(crate) fn detect_for_operation() -> Result<DesktopApp, String> {
#[cfg(target_os = "windows")]
{
let app = crate::platform::desktop_windows::detect_fresh()?;
Ok(DesktopApp {
path: app.path,
executable: app.executable,
bundle_id: app.bundle_id,
name: app.name,
version: app.version,
})
}
#[cfg(not(target_os = "windows"))]
{
detect()
}
}
pub(crate) fn validate(app: &DesktopApp) -> Result<(), String> {
#[cfg(target_os = "macos")]
{
if !matches!(
app.bundle_id.as_str(),
"com.openai.codex" | "com.openai.codex.beta"
) {
return Err("不是受支持的官方 Codex 客户端".into());
}
let path = app.path.to_str().ok_or("客户端路径无效")?;
crate::platform::locale_platform_command(
Path::new("/usr/bin/codesign"),
&["--verify", "--strict", path],
)?;
let details = crate::platform::locale_platform_command(
Path::new("/usr/bin/codesign"),
&["--display", "--verbose=4", path],
)?;
let info = String::from_utf8_lossy(&details.stderr);
if !info.lines().any(|line| line == "TeamIdentifier=2DC432GLL2") {
return Err("无法确认客户端为 OpenAI 官方签名,未重启或连接客户端。".into());
}
Ok(())
}
#[cfg(target_os = "windows")]
{
crate::platform::desktop_windows::validate(&windows_app(app))
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
{
let _ = app;
Err("当前平台不支持安全的语言兼容启动".into())
}
}
pub(crate) fn validate_launch(app: &DesktopApp, home: &Path) -> Result<(), String> {
#[cfg(target_os = "windows")]
{
crate::platform::desktop_windows::validate_launch(&windows_app(app), home)
}
#[cfg(not(target_os = "windows"))]
{
let _ = (app, home);
Ok(())
}
}
pub(crate) fn quit(app: &DesktopApp) -> Result<(), String> {
#[cfg(target_os = "macos")]
{
crate::platform::locale_quit_desktop(&app.executable, &app.bundle_id)
}
#[cfg(target_os = "windows")]
{
crate::platform::desktop_windows::quit(&windows_app(app))
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
{
let _ = app;
Err("当前平台不支持安全的语言兼容启动".into())
}
}
pub(crate) fn ensure_stopped(app: &DesktopApp) -> Result<(), String> {
#[cfg(target_os = "macos")]
{
if !crate::platform::locale_desktop_pids(&app.executable)?.is_empty() {
return Err("客户端在保存语言前重新启动,已取消写入;请完全退出后重试。".into());
}
Ok(())
}
#[cfg(target_os = "windows")]
{
if !crate::platform::desktop_windows::pids(&windows_app(app))?.is_empty() {
return Err("客户端在保存语言前重新启动,已取消写入;请完全退出后重试。".into());
}
Ok(())
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
{
let _ = app;
Err("当前平台不支持安全的语言兼容启动".into())
}
}
pub(crate) fn quit_spawned(app: &DesktopApp, pid: u32) -> Result<(), String> {
#[cfg(target_os = "macos")]
{
if !crate::platform::locale_desktop_pids(&app.executable)?.contains(&pid) {
return Err("刚启动的官方进程身份已改变,未自动退出其它实例;请手动恢复。".into());
}
quit(app)
}
#[cfg(target_os = "windows")]
{
crate::platform::desktop_windows::verify_process(&windows_app(app), pid)?;
quit(app)
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
{
let _ = (app, pid);
Err("当前平台不支持安全的客户端恢复".into())
}
}
pub(crate) fn launch(app: &DesktopApp, home: &Path, port: Option<u16>) -> Result<u32, String> {
#[cfg(target_os = "windows")]
{
return crate::platform::desktop_windows::launch(&windows_app(app), Some(home), port);
}
#[cfg(not(target_os = "windows"))]
{
let mut command = std::process::Command::new(&app.executable);
command
.env("CODEX_HOME", home)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
if let Some(port) = port {
command.args([
format!("--remote-debugging-port={port}"),
"--remote-debugging-address=127.0.0.1".into(),
]);
}
let reaper = process_reaper()?;
let child = command
.spawn()
.map_err(|_| "无法启动官方客户端,请手动打开客户端后重试。")?;
let pid = child.id();
reaper
.send(child)
.map_err(|_| "客户端已启动,但进程监督不可用;请手动恢复并重试。")?;
Ok(pid)
}
}
pub(crate) fn verify_listener(app: &DesktopApp, pid: u32, port: u16) -> Result<(), String> {
#[cfg(target_os = "macos")]
{
let ids = crate::platform::locale_desktop_pids(&app.executable)?;
if !ids.contains(&pid) {
return Err("官方客户端进程已经改变,已停止语言兼容连接。".into());
}
let output = command(
"/usr/sbin/lsof",
&["-nP", &format!("-iTCP:{port}"), "-sTCP:LISTEN", "-Fpn"],
)?;
verify_listener_output(&output, pid, port)
}
#[cfg(target_os = "windows")]
{
crate::platform::desktop_windows::verify_listener(&windows_app(app), pid, port)
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
{
let _ = (app, pid, port);
Err("当前平台无法验证调试端口归属".into())
}
}
fn verify_listener_output(output: &str, pid: u32, port: u16) -> Result<(), String> {
let mut current = None;
let mut verified = false;
for line in output.lines() {
if let Some(p) = line.strip_prefix('p') {
current = p.parse::<u32>().ok();
}
if let Some(address) = line.strip_prefix('n') {
if current != Some(pid) || address != format!("127.0.0.1:{port}") {
return Err("调试端口不属于指定官方进程或未限制在本机,未执行任何注入。".into());
}
verified = true;
}
}
if !verified {
return Err("官方客户端尚未开放可验证的本机调试端口;此构建可能不支持运行时兼容。".into());
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn listener_must_match_pid_and_ipv4_loopback() {
assert!(verify_listener_output("p123\nn127.0.0.1:4567\n", 123, 4567).is_ok());
for input in [
"p456\nn127.0.0.1:4567\n",
"p123\nn*:4567\n",
"p123\nn192.168.1.2:4567\n",
"p123\nn127.0.0.1:8888\n",
"",
] {
assert!(verify_listener_output(input, 123, 4567).is_err());
}
}
#[test]
fn spawned_fixture_children_are_waited_by_the_reaper() {
let before = REAPED.load(std::sync::atomic::Ordering::Relaxed);
let child = std::process::Command::new(std::env::current_exe().unwrap())
.arg("--list")
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.unwrap();
process_reaper().unwrap().send(child).unwrap();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
while REAPED.load(std::sync::atomic::Ordering::Relaxed) <= before
&& std::time::Instant::now() < deadline
{
std::thread::sleep(std::time::Duration::from_millis(25));
}
assert!(REAPED.load(std::sync::atomic::Ordering::Relaxed) > before);
}
}
@@ -0,0 +1,197 @@
/* Independently implemented locale compatibility. No application files change. */
(function (options) {
"use strict";
let page;
try { page = new URL(location.href); } catch { return { installed: false, reason: "unsupported_origin" }; }
if (page.protocol !== "app:" || page.hostname !== "-" || page.port || page.username || page.password ||
!["/", "/index.html"].includes(page.pathname) || window !== window.top) {
return { installed: false, reason: "unsupported_origin" };
}
if (!options || !["zh-CN", "en-US"].includes(options.locale) ||
typeof options.owner !== "string" || !/^[a-f0-9]{64}$/.test(options.owner)) {
return { installed: false, reason: "invalid_options" };
}
const marker = "__CODEXX_LOCALE_RUNTIME_V1__";
if (window[marker]?.owner === options.owner) return window[marker].status();
if (window[marker]) return { installed: false, reason: "another_owner" };
const layerName = "72216192";
const changes = [];
const clients = new Map();
const views = new WeakMap();
const registries = new WeakSet();
const observed = new WeakMap();
let enabled = true;
let timer;
let messagesSeen = false;
function isMessages(name) {
try { const url = new URL(name); return url.protocol === "app:" && url.host === "-" && !url.username && !url.password && /^\/assets\/zh-CN-[a-zA-Z0-9_-]+\.js$/.test(url.pathname); }
catch { return false; }
}
const resourceObserver = typeof PerformanceObserver === "function" ? new PerformanceObserver(list => {
messagesSeen ||= list.getEntries().some(entry => isMessages(entry.name));
}) : null;
try { resourceObserver?.observe({ type: "resource", buffered: true }); } catch { /* optional API */ }
function change(object, name, value) {
const descriptor = Object.getOwnPropertyDescriptor(object, name);
if (descriptor && !descriptor.configurable && !descriptor.writable) return false;
try {
Object.defineProperty(object, name, descriptor && !descriptor.configurable ? { value } : { configurable: true, writable: true, value });
changes.push(() => {
if (object[name] !== value) return;
if (descriptor) Object.defineProperty(object, name, descriptor);
else delete object[name];
});
return true;
} catch { return false; }
}
function translatedLayer(layer) {
if (!layer || typeof layer.get !== "function") return layer;
if (views.has(layer)) return views.get(layer);
const read = layer.get.bind(layer);
const translatedRead = (parameter, ...args) =>
enabled && parameter === "enable_i18n" ? true : read(parameter, ...args);
const methods = new Map();
// A forwarding facade also works for frozen SDK results. A proxy directly
// wrapping a frozen own `get` would violate JavaScript proxy invariants.
const view = new Proxy(Object.create(Object.getPrototypeOf(layer)), {
get(_target, key) {
if (key === "get") return translatedRead;
const result = Reflect.get(layer, key, layer);
if (typeof result !== "function") return result;
if (methods.get(key)?.original !== result) methods.set(key, { original: result, bound: result.bind(layer) });
return methods.get(key).bound;
},
has(_target, key) { return key in layer; },
ownKeys() { return Reflect.ownKeys(layer); },
getOwnPropertyDescriptor(_target, key) {
const descriptor = Object.getOwnPropertyDescriptor(layer, key);
return descriptor ? { ...descriptor, configurable: true } : undefined;
},
});
views.set(layer, view);
return view;
}
function hook(client) {
if (!enabled) return;
if (!client || typeof client !== "object") return;
const previous = clients.get(client);
if (previous?.waiting) return;
if (previous && previous.replacement === client.getLayer) return;
// The SDK registers its client from the base constructor, before the
// derived constructor assigns getLayer. Intercept that later assignment so
// React's first memoized language evaluation already sees the override.
if (typeof client.getLayer !== "function") {
const descriptor = Object.getOwnPropertyDescriptor(client, "getLayer");
if (descriptor && !descriptor.configurable) return;
let raw;
let wrapped;
const getter = () => wrapped;
const setter = next => {
raw = next;
wrapped = typeof next === "function" ? wrap(client, next) : next;
clients.set(client, { replacement: wrapped, waiting: false });
};
Object.defineProperty(client, "getLayer", { configurable: true, enumerable: descriptor?.enumerable ?? true, get: getter, set: setter });
clients.set(client, { waiting: true });
changes.push(() => {
if (Object.getOwnPropertyDescriptor(client, "getLayer")?.get !== getter) return;
if (descriptor && Object.hasOwn(descriptor, "value")) Object.defineProperty(client, "getLayer", { ...descriptor, value: raw });
else if (descriptor) Object.defineProperty(client, "getLayer", descriptor);
else if (raw === undefined) delete client.getLayer;
else Object.defineProperty(client, "getLayer", { configurable: true, enumerable: true, writable: true, value: raw });
});
return;
}
const original = client.getLayer;
const replacement = wrap(client, original);
if (change(client, "getLayer", replacement)) {
clients.set(client, { replacement });
try { client.$emt?.({ name: "values_updated" }); } catch { /* optional SDK hook */ }
}
}
function wrap(_client, original) {
return function (name, ...args) {
const result = original.call(this, name, ...args);
return enabled && name === layerName ? translatedLayer(result) : result;
};
}
function observe(object, key, receive) {
let keys = observed.get(object);
if (keys?.has(key)) { receive(object[key]); return; }
const descriptor = Object.getOwnPropertyDescriptor(object, key);
if (descriptor && !descriptor.configurable) { receive(object[key]); return; }
if (!keys) { keys = new Set(); observed.set(object, keys); }
keys.add(key);
let current = object[key];
const getter = () => current;
const setter = next => {
if (descriptor?.set) descriptor.set.call(object, next);
current = descriptor?.get ? descriptor.get.call(object) : next;
if (enabled) receive(current);
};
Object.defineProperty(object, key, { configurable: true, enumerable: descriptor?.enumerable ?? true, get: getter, set: setter });
changes.push(() => {
if (Object.getOwnPropertyDescriptor(object, key)?.get !== getter) return;
if (descriptor && !Object.hasOwn(descriptor, "value")) Object.defineProperty(object, key, descriptor);
else if (descriptor) Object.defineProperty(object, key, { ...descriptor, value: current });
else if (current === undefined) delete object[key];
else Object.defineProperty(object, key, { configurable: true, enumerable: true, writable: true, value: current });
});
receive(current);
}
function registryAppeared(registry) {
if (!enabled || !registry || typeof registry !== "object" || registries.has(registry)) return;
registries.add(registry);
observe(registry, "firstInstance", hook);
observe(registry, "instances", instances => {
if (!instances || typeof instances !== "object") return;
// Observe SDK registration without changing the dictionary's identity.
for (const [key, client] of Object.entries(instances).slice(0, 16)) {
hook(client);
observe(instances, key, hook);
}
});
}
function scan() {
const current = new Set();
if (!enabled) return current;
const registry = window.__STATSIG__;
if (!registry || typeof registry !== "object") return current;
if (registry.firstInstance) { hook(registry.firstInstance); current.add(registry.firstInstance); }
if (registry.instances && typeof registry.instances === "object") {
for (const client of Object.values(registry.instances).slice(0, 16)) { hook(client); current.add(client); }
}
return current;
}
const state = {
owner: options.owner,
status() {
const current = scan();
let gate = false;
for (const client of current) {
try { gate ||= client.getLayer(layerName, { disableExposureLog: true }).get("enable_i18n", false) === true; }
catch { /* unsupported client instance */ }
}
const language = document.documentElement?.lang || "";
const normalized = String(language).replace(/_/g, "-").toLowerCase();
const locale = options.locale === "zh-CN" ? ["zh-cn", "zh-hans", "zh-hans-cn"].includes(normalized) : /^en(?:-|$)/i.test(normalized);
const messages = options.locale === "en-US" || messagesSeen || performance.getEntriesByType("resource").some(entry => isMessages(entry.name));
return { installed: enabled, ready: enabled && gate && locale && messages,
locale: options.locale, clients: current.size, gate, languageMatches: locale, messagesLoaded: messages };
},
restore() {
enabled = false;
clearInterval(timer);
resourceObserver?.disconnect();
for (const undo of changes.reverse()) { try { undo(); } catch { /* preserve later changes */ } }
if (window[marker] === state) delete window[marker];
return { restored: true };
},
};
Object.defineProperty(window, marker, { configurable: true, value: state });
observe(window, "__STATSIG__", registryAppeared);
scan();
timer = setInterval(scan, 100);
return state.status();
})(__CODEXX_LANGUAGE_CONFIG__)
+583 -64
View File
@@ -13,7 +13,7 @@ use std::fs;
use std::io::Read;
use std::path::Path;
use std::time::Duration;
use toml_edit::{value, DocumentMut, Item, TableLike};
use toml_edit::{value, DocumentMut, ImDocument, Item, Key, Table, TableLike};
const MAX_CONFIG_BYTES: u64 = 2 * 1024 * 1024;
const BUILTIN_PROVIDERS: &[&str] = &[
@@ -31,6 +31,11 @@ pub(crate) struct ConfigHealthIssue {
pub(crate) title: String,
pub(crate) description: String,
pub(crate) repairable: bool,
pub(crate) path: String,
pub(crate) line: Option<usize>,
pub(crate) column: Option<usize>,
pub(crate) key: String,
pub(crate) suggestion: String,
}
#[derive(Debug, Clone, Serialize)]
@@ -277,18 +282,35 @@ fn fingerprint(
format!("{:x}", digest.finalize())
}
fn key_path(parts: &[&str]) -> String {
parts
.iter()
.map(|part| Key::new(*part).to_string())
.collect::<Vec<_>>()
.join(".")
}
fn add_issue(
report: &mut ConfigHealthReport,
code: &str,
title: &str,
description: &str,
repair: Option<&str>,
key: &[&str],
suggestion: &str,
) {
report.issues.push(ConfigHealthIssue {
code: code.to_string(),
title: title.to_string(),
description: description.to_string(),
repairable: repair.is_some(),
path: config_path(Path::new(&report.codex_dir))
.display()
.to_string(),
line: None,
column: None,
key: key_path(key),
suggestion: suggestion.to_string(),
});
if let Some(summary) = repair {
if !report
@@ -301,6 +323,136 @@ fn add_issue(
}
}
fn line_column(text: &str, offset: usize) -> (usize, usize) {
let mut offset = offset.min(text.len());
while !text.is_char_boundary(offset) {
offset -= 1;
}
let prefix = &text[..offset];
(
prefix.bytes().filter(|byte| *byte == b'\n').count() + 1,
prefix
.rsplit('\n')
.next()
.unwrap_or_default()
.chars()
.count()
+ 1,
)
}
fn locate_issues(report: &mut ConfigHealthReport, source: &ImDocument<&str>) {
for issue in &mut report.issues {
let Ok(keys) = Key::parse(&issue.key) else {
continue;
};
let mut item = source.as_item();
let mut offset = None;
for (index, key) in keys.iter().enumerate() {
let Some(table) = item.as_table_like() else {
offset = None;
break;
};
let Some(next) = table.get(key.get()) else {
offset = None;
break;
};
if index + 1 == keys.len() {
offset = table
.key(key.get())
.and_then(Key::span)
.map(|span| span.start)
.or_else(|| next.span().map(|span| span.start));
}
item = next;
}
if let Some(offset) = offset {
let (line, column) = line_column(source.raw(), offset);
issue.line = Some(line);
issue.column = Some(column);
}
}
}
// Recover only TOML key names, never values or the parser's source-line display.
// An invalid key/header is identified as document syntax rather than guessed.
fn delimiter_outside_quotes(text: &str, delimiter: char) -> Option<usize> {
let mut quote = None;
let mut escaped = false;
for (offset, character) in text.char_indices() {
if escaped {
escaped = false;
continue;
}
if quote == Some('"') && character == '\\' {
escaped = true;
continue;
}
if quote == Some(character) {
quote = None;
continue;
}
if quote.is_some() {
continue;
}
if character == '\'' || character == '"' {
quote = Some(character);
} else if character == delimiter {
return Some(offset);
} else if character == '#' {
return None;
}
}
None
}
fn syntax_key(text: &str, offset: usize) -> Vec<String> {
let error_line = line_column(text, offset).0;
let mut section: Vec<String> = Vec::new();
let mut current = vec!["<TOML 文档结构>".to_string()];
for line in text.lines().take(error_line) {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
if line.starts_with('[') {
let body = line.trim_start_matches('[');
let candidate = delimiter_outside_quotes(body, ']').map_or(body, |end| &body[..end]);
if let Ok(keys) = Key::parse(candidate) {
section = keys.iter().map(|key| key.get().to_string()).collect();
current = section.clone();
} else {
current = vec!["<TOML 表头>".to_string()];
}
} else if let Some(equal) = delimiter_outside_quotes(line, '=') {
if let Ok(keys) = Key::parse(line[..equal].trim()) {
current = section
.iter()
.cloned()
.chain(keys.iter().map(|key| key.get().to_string()))
.collect();
}
}
}
current
}
fn syntax_suggestion(message: &str) -> &'static str {
if message.contains("duplicate") {
"同一配置范围内的参数或表重复定义;保留一处正确定义,合并需要保留的内容后重新检查。"
} else if message.contains("string") || message.contains("quote") {
"检查此参数的引号是否成对;单行字符串不能直接换行,需换行时使用 TOML 三引号字符串。"
} else if message.contains("array") || message.contains("expected `]`") {
"检查此参数的数组是否以 ] 结束,各元素之间是否有逗号;修正后重新检查。"
} else if message.contains("table") || message.contains("expected `.`") {
"检查表头的方括号与点分参数名;例如 [model_providers.custom],同一张表不能重复定义。"
} else if message.contains("expected `=`") {
"参数必须写成 参数名 = 值;补齐等号并使用 TOML 支持的值格式后重新检查。"
} else {
"检查标记位置的引号、逗号和括号是否配对,参数应写成 参数名 = 值;修正后重新检查。"
}
}
fn bool_replacement(item: &Item) -> Option<bool> {
match item.as_str()?.trim().to_ascii_lowercase().as_str() {
"true" => Some(true),
@@ -336,8 +488,10 @@ fn check_provider_table(
report,
"provider-table-type",
"供应商配置格式不正确",
"有一条供应商配置不是有效的配置表,请在供应商页面重新检查配置。",
"此供应商的定义不是 TOML 配置表。",
None,
&["model_providers", id],
"将此项改为 [model_providers.供应商标识] 配置表,并恢复原有参数;现有值无法确定,需手动确认。",
);
return;
};
@@ -355,8 +509,10 @@ fn check_provider_table(
report,
"provider-name-missing",
"供应商配置缺少名称",
"有一条供应商配置没有填写名称,可使用它现有的标识补齐显示名称。",
"此供应商的 name 缺失或为空。",
(!id.trim().is_empty()).then_some("根据供应商标识补齐缺失的显示名称"),
&["model_providers", id, "name"],
&format!("补齐 name = {},保留供应商标识与其他参数。", value(id)),
);
}
for key in ["name", "base_url"] {
@@ -365,8 +521,14 @@ fn check_provider_table(
report,
"provider-text-type",
"供应商文字配置格式不正确",
"供应商名称或接口地址应为文字,暂时无法自动判断正确内容。",
&format!("{key} 应为 TOML 字符串,现有值的类型不正确。"),
None,
&["model_providers", id, key],
if key == "name" {
"将 name 改为带引号的供应商显示名称,例如 name = \"My API\"。"
} else {
"将 base_url 改为带引号的接口地址,例如 base_url = \"https://供应商地址/v1\";地址需向供应商确认。"
},
);
}
}
@@ -386,16 +548,20 @@ fn check_provider_table(
report,
"provider-boolean-text",
"供应商开关格式不正确",
"有一项开关被写成了文字,可能导致 Codex 无法加载配置。",
&format!("{key} 被写成了字符串,Codex 需要布尔值。"),
Some("将写成文字的开关恢复为正确格式"),
&["model_providers", id, key],
&format!("将 {key} 改为 {replacement}(不带引号),保留当前开关含义。"),
);
} else {
add_issue(
report,
"provider-boolean-type",
"供应商开关无法识别",
"有一项开关不是有效的开启或关闭值,需要手动确认。",
&format!("{key} 不是布尔值,也无法确定其开启或关闭含义。"),
None,
&["model_providers", id, key],
&format!("确认所需状态后将 {key} 写为 true 或 false(不带引号)。"),
);
}
}
@@ -420,6 +586,8 @@ fn check_provider_table(
"DeepSeek 的连接方式需要调整",
"DeepSeek 官方接口不支持当前开启的 WebSocket 连接,可能先报错并多次重试,再正常回复。",
Some("将 DeepSeek 官方接口改用 HTTP 连接,避免发送消息时反复重试"),
&["model_providers", id, "supports_websockets"],
"将 supports_websockets 改为 false,让 DeepSeek 官方接口使用 HTTP。",
);
}
if let Some(item) = table.get_mut("wire_api") {
@@ -439,6 +607,8 @@ fn check_provider_table(
"供应商接口格式拼写不正确",
"接口格式中存在多余空格或大小写错误,可能导致 Codex 无法加载配置。",
Some("修正接口格式的空格或大小写"),
&["model_providers", id, "wire_api"],
"将 wire_api 规范为 \"responses\",去掉多余空格并使用小写。",
);
} else {
add_issue(
@@ -447,6 +617,8 @@ fn check_provider_table(
"供应商接口格式不受支持",
"当前 Codex 需要 Responses 接口。请向供应商确认支持的接口,或使用兼容的转接服务。",
None,
&["model_providers", id, "wire_api"],
"先向供应商确认支持 Responses API;支持时设置 wire_api = \"responses\",否则选择兼容供应商。不能仅改名称来转换协议。",
);
}
}
@@ -462,6 +634,8 @@ fn check_provider_table(
"官方登录的认证设置不完整",
"已发现官方登录信息,但这条官方供应商配置没有启用登录认证。",
Some("为官方登录补齐认证开关"),
&["model_providers", id, "requires_openai_auth"],
"设置 requires_openai_auth = true,使用已确认的 ChatGPT 登录信息。",
);
}
}
@@ -487,6 +661,64 @@ fn complete_alias_candidate(item: &Item) -> bool {
|| table.get("requires_openai_auth").and_then(Item::as_bool) == Some(true))
}
// A historical provider ID may be routed to the user's explicitly selected
// official login only when neither root nor provider fields select other auth
// or endpoints. No saved accounts, backups or credentials are borrowed.
fn official_history_alias(doc: &DocumentMut, chatgpt_auth: bool) -> Option<Item> {
if !chatgpt_auth
|| [
"base_url",
"experimental_bearer_token",
"auth",
"env_key",
"env_key_instructions",
"http_headers",
"env_http_headers",
"query_params",
"api_base",
"chatgpt_base_url",
"api_key",
"openai_api_key",
"auth_mode",
"tokens",
"env_vars",
]
.iter()
.any(|key| doc.contains_key(key))
{
return None;
}
let providers = match doc.get("model_providers") {
None => None,
Some(item) => Some(item.as_table_like()?),
};
let selected = match doc.get("model_provider") {
Some(item) => item.as_str()?,
None => "openai",
};
if doc
.get("forced_login_method")
.is_some_and(|item| item.as_str() != Some("chatgpt"))
{
return None;
}
if let Some(item) = providers.and_then(|providers| providers.get(selected)) {
let table = item.as_table_like()?;
return (is_official_login_table(table, chatgpt_auth)
&& !table.contains_key("query_params")
&& complete_alias_candidate(item))
.then(|| item.clone());
}
if selected != "openai" {
return None;
}
let mut table = Table::new();
table.insert("name", value("OpenAI"));
table.insert("requires_openai_auth", value(true));
table.insert("wire_api", value("responses"));
Some(Item::Table(table))
}
fn collect_provider_reference(
item: Option<&Item>,
references: &mut Vec<String>,
@@ -500,6 +732,8 @@ fn collect_provider_reference(
"选用的供应商设置不正确",
"供应商标识应为非空文字,请在供应商页面重新选择后保存。",
None,
&["model_provider"],
"将 model_provider 设置为已定义的非空供应商标识,例如 \"openai\" 或 [model_providers.custom] 对应的 \"custom\";需先确认所选供应商。",
);
return;
};
@@ -538,6 +772,8 @@ fn analyze(
"暂时无法检查配置",
message,
None,
&["<配置文件>"],
"检查显示路径对应文件的存在性、文件类型、读取权限与大小后重试。",
);
return (report, None);
}
@@ -549,45 +785,36 @@ fn analyze(
&mut report,
"config-encoding",
"配置文件的文字编码不正确",
"配置文件需要使用 UTF-8 编码,请手动检查后保存。",
"配置文件需要使用 UTF-8 编码。",
None,
&["<文件编码>"],
"在文本编辑器中按原编码打开此文件,再以 UTF-8 编码保存;编码无法可靠判断,不能自动转换。",
);
return (report, None);
};
let mut doc = match text.parse::<DocumentMut>() {
let source = match ImDocument::parse(text) {
Ok(doc) => doc,
Err(error) => {
report.status = "issues";
// TOML's normal Display embeds entire source lines, including credentials.
let description = error
.span()
.map(|span| {
let mut offset = span.start.min(text.len());
while !text.is_char_boundary(offset) {
offset -= 1;
}
let prefix = &text[..offset];
let line = prefix.bytes().filter(|byte| *byte == b'\n').count() + 1;
let column = prefix
.rsplit('\n')
.next()
.unwrap_or_default()
.chars()
.count()
+ 1;
format!("配置文件第 {line} 行、第 {column} 列附近有格式错误,需要手动检查。")
})
.unwrap_or_else(|| "配置文件中存在格式错误,需要手动检查。".to_string());
let offset = error.span().map_or(0, |span| span.start);
let (line, column) = line_column(text, offset);
let keys = syntax_key(text, offset);
let keys: Vec<_> = keys.iter().map(String::as_str).collect();
add_issue(
&mut report,
"config-syntax",
"配置文件格式不正确",
&description,
&format!("配置文件第 {line} 行、第 {column} 列附近存在 TOML 语法错误。"),
None,
&keys,
syntax_suggestion(error.message()),
);
report.issues[0].line = Some(line);
report.issues[0].column = Some(column);
return (report, None);
}
};
let mut doc = source.clone().into_mut();
let mut references = Vec::new();
collect_provider_reference(doc.get("model_provider"), &mut references, &mut report);
// Profile loading changed between Codex versions. Leave legacy inline
@@ -602,8 +829,10 @@ fn analyze(
&mut report,
"providers-table-type",
"供应商列表格式不正确",
"model_providers 应为配置表,暂时无法自动恢复原有供应商。",
"model_providers 应为 TOML 配置表,现有值的类型不正确。",
None,
&["model_providers"],
"恢复 [model_providers.供应商标识] 配置表与原有参数;现有内容无法可靠还原,需手动确认。",
);
}
}
@@ -640,9 +869,27 @@ fn analyze(
.filter(|id| !BUILTIN_PROVIDERS.contains(id))
.and_then(|id| providers.and_then(|providers| providers.get(id)))
.is_some_and(complete_alias_candidate);
if missing.len() == 1 && candidates.len() == 1 && (!history_only || selected_custom_exists)
{
let source_name: String = candidates[0]
let official_alias = history_only
.then(|| official_history_alias(&doc, chatgpt_auth))
.flatten();
let selected_official_style = doc
.get("model_provider")
.and_then(Item::as_str)
.and_then(|id| providers.and_then(|providers| providers.get(id)))
.and_then(Item::as_table_like)
.is_some_and(|table| {
table.get("name").and_then(Item::as_str) == Some("OpenAI")
&& !table.contains_key("base_url")
});
let source = official_alias.clone().or_else(|| {
(missing.len() == 1
&& candidates.len() == 1
&& (!history_only || (selected_custom_exists && !selected_official_style)))
.then(|| candidates[0].clone())
});
let first_routing_summary = report.repair_summary.len();
if let Some(source) = source {
let source_name: String = source
.as_table_like()
.and_then(|table| table.get("name"))
.and_then(Item::as_str)
@@ -651,38 +898,51 @@ fn analyze(
.filter(|ch| !ch.is_control())
.take(60)
.collect();
doc.get_mut("model_providers")
.and_then(Item::as_table_like_mut)
.expect("candidate implies table")
.insert(&missing[0], candidates[0].clone());
if history_only {
let summary =
format!("让受影响的旧会话沿用当前供应商「{source_name}」,并保留原会话");
add_issue(&mut report, "session-provider-definition-missing", "旧会话使用的供应商缺少配置", &format!("有些旧会话仍引用已缺失的供应商。修复后,这些会话将沿用当前供应商「{source_name}」,原会话会保留。"), Some(&summary));
} else {
let summary = format!("使用现有供应商「{source_name}」的配置补齐缺失的对应关系");
add_issue(&mut report, "provider-definition-missing", "选用的供应商缺少配置", &format!("供应商标识与现有配置不对应。将使用现有供应商「{source_name}」的配置补齐对应关系,并保留原配置。"), Some(&summary));
if doc.get("model_providers").is_none() {
doc.as_table_mut()
.insert("model_providers", Item::Table(Table::new()));
}
// Keep routing decisions visible in the compact startup notice.
if let Some(summary) = report.repair_summary.pop() {
report.repair_summary.insert(0, summary);
for id in &missing {
doc.get_mut("model_providers")
.and_then(Item::as_table_like_mut)
.expect("safe source requires a valid provider table")
.insert(id, source.clone());
let summary = if history_only {
format!("补齐 [model_providers.{}],让旧会话沿用当前供应商「{source_name}」,并保留原会话", Key::new(id.as_str()))
} else {
format!(
"使用现有供应商「{source_name}」补齐 [model_providers.{}],并保留原配置",
Key::new(id.as_str())
)
};
let description = if history_only {
format!("旧会话仍引用供应商标识 {},但 config.toml 中缺少对应的配置表。修复后,这些会话将沿用当前供应商「{source_name}」。", Key::new(id.as_str()))
} else {
format!(
"model_provider 选中的供应商 {} 缺少对应的配置表。",
Key::new(id.as_str())
)
};
add_issue(&mut report,
if history_only { "session-provider-definition-missing" } else { "provider-definition-missing" },
if history_only { "旧会话使用的供应商缺少配置" } else { "选用的供应商缺少配置" },
&description, Some(&summary), &["model_providers", id],
&format!("新增 {},复制已确认的当前{}供应商「{source_name}」参数;保留 model_provider、原有表和会话数据库。",
key_path(&["model_providers", id]), if official_alias.is_some() { "官方登录" } else { "" }));
}
// Keep all routing decisions before smaller value corrections.
let routing = report.repair_summary.split_off(first_routing_summary);
report.repair_summary.splice(0..0, routing);
} else {
add_issue(
&mut report,
if history_only {
"session-provider-definition-missing"
} else {
"provider-definition-missing"
},
if history_only {
"旧会话使用的供应商缺少配置"
} else {
"选用的供应商缺少配置"
},
"未找到唯一可确认的供应商配置,请在供应商页面重新选择并启用,或手动补齐原配置。",
None,
);
for id in &missing {
add_issue(&mut report,
if history_only { "session-provider-definition-missing" } else { "provider-definition-missing" },
if history_only { "旧会话使用的供应商缺少配置" } else { "选用的供应商缺少配置" },
&format!("{} 引用了供应商标识 {},但 {} 未定义,且无法确认应使用哪个来源。",
if history_only { "旧会话" } else { "model_provider" }, Key::new(id.as_str()), key_path(&["model_providers", id])),
None, &["model_providers", id],
&format!("手动补齐 [{}] 的原供应商参数;若希望旧会话改用官方,请先启用官方配置并完成 ChatGPT 登录后重新检查。多个中转来源不会自动合并。", key_path(&["model_providers", id])));
}
}
}
report.status = if report.issues.is_empty() {
@@ -704,10 +964,13 @@ fn analyze(
&mut report,
"config-linked-file",
"配置文件由链接指向其他位置",
"请打开原配置文件进行修改,以保留已有的文件链接。",
"此 config.toml 是文件链接,不能安全替换链接本身。",
None,
&["<文件链接>"],
"使用「查看配置」打开链接指向的原文件,按上述参数建议修复后重新检查。",
);
}
locate_issues(&mut report, &source);
let replacement = report.can_repair.then(|| doc.to_string());
(report, replacement)
}
@@ -1163,7 +1426,263 @@ mod tests {
assert_eq!(report.status, "issues");
assert!(json.contains("第 2 行"));
assert!(!json.contains("super-private-secret"));
assert!(!json.contains("experimental_bearer_token"));
let issue = &report.issues[0];
assert_eq!(issue.path, config_path(&fixture.0).display().to_string());
assert_eq!(issue.line, Some(2));
assert!(issue.column.is_some_and(|column| column > 0));
assert_eq!(issue.key, "experimental_bearer_token");
assert!(!issue.suggestion.is_empty());
assert!(!issue.repairable);
}
#[test]
fn diagnostics_locate_the_original_parameter_and_give_an_exact_fix() {
let fixture = Fixture::new("# 注释\nmodel_provider='custom'\n[model_providers.custom]\nname='My API'\nbase_url='https://fixture.example/v1'\n supports_websockets = 'TRUE' # 保留\nwire_api = 'chat'\n");
let report = fixture.check();
let boolean = report
.issues
.iter()
.find(|issue| issue.code == "provider-boolean-text")
.unwrap();
assert_eq!(boolean.path, config_path(&fixture.0).display().to_string());
assert_eq!((boolean.line, boolean.column), (Some(6), Some(3)));
assert_eq!(boolean.key, "model_providers.custom.supports_websockets");
assert!(boolean.suggestion.contains("supports_websockets 改为 true"));
let protocol = report
.issues
.iter()
.find(|issue| issue.code == "provider-protocol-unsupported")
.unwrap();
assert_eq!((protocol.line, protocol.column), (Some(7), Some(1)));
assert_eq!(protocol.key, "model_providers.custom.wire_api");
assert!(protocol.suggestion.contains("Responses API"));
assert!(!protocol.repairable);
}
#[test]
fn dotted_inline_and_quoted_provider_keys_keep_precise_locations() {
for (text, line, column) in [
("model_providers.\"with.dot\".name=9\n", 1, 28),
("model_providers = { \"with.dot\" = { name = 9 } }\n", 1, 36),
("[model_providers.\"with.dot\"]\nname=9\n", 2, 1),
] {
let fixture = Fixture::new(text);
let report = fixture.check();
let issue = report
.issues
.iter()
.find(|issue| issue.code == "provider-text-type")
.unwrap();
assert_eq!(issue.key, "model_providers.\"with.dot\".name");
assert_eq!(
(issue.line, issue.column),
(Some(line), Some(column)),
"{text}"
);
}
}
#[test]
fn missing_definition_has_no_invented_line_and_names_each_provider() {
let fixture = Fixture::new("model_provider='openai'\n");
fixture.sessions(&["old_proxy_a", "old_proxy_b"]);
let report = fixture.check();
assert_eq!(report.issues.len(), 2);
assert!(!report.can_repair);
for issue in &report.issues {
assert_eq!(issue.path, config_path(&fixture.0).display().to_string());
assert_eq!((issue.line, issue.column), (None, None));
assert!(issue.key.starts_with("model_providers.old_proxy_"));
assert!(issue.description.contains(&issue.key));
assert!(issue.suggestion.contains(&issue.key));
}
}
#[test]
fn syntax_errors_include_parameter_context_and_safe_actionable_suggestions() {
let text = "model_provider='custom'\n[model_providers.custom]\nname='OpenAI'\nexperimental_bearer_token = 'never-echo-this-secret\n";
let fixture = Fixture::new(text);
let report = fixture.check();
let issue = &report.issues[0];
assert_eq!(
issue.key,
"model_providers.custom.experimental_bearer_token"
);
assert_eq!(issue.line, Some(4));
assert!(issue.column.is_some());
assert!(issue.suggestion.contains("引号"));
assert!(!serde_json::to_string(&report)
.unwrap()
.contains("never-echo-this-secret"));
assert!(!fixture.repair(&report).changed);
assert_eq!(fixture.text(), text);
assert!(!fixture.0.join(".codexx-test-backups").exists());
}
#[test]
fn syntax_context_respects_delimiters_inside_quoted_keys() {
let text = "[model_providers.\"name]with=chars\"]\n\"key=with]chars\" = 'secret-without-closing-quote\n";
let keys = syntax_key(text, text.len() - 1);
assert_eq!(
keys,
["model_providers", "name]with=chars", "key=with]chars"]
);
assert!(!key_path(&keys.iter().map(String::as_str).collect::<Vec<_>>()).contains("secret"));
}
#[test]
fn builtin_official_login_can_repair_all_missing_history_aliases_without_touching_sessions() {
for selection in ["model_provider='openai'\n", ""] {
let original = format!(
"{selection}model='official-model'\n[mcp_servers.fixture]\ncommand='fixture-mcp'\n"
);
let fixture = Fixture::new(&original);
fixture.login();
fixture.sessions(&["old_proxy_a", "old_proxy_b", "openai"]);
let db_before = fs::read(fixture.0.join("state_5.sqlite")).unwrap();
let auth_before = fs::read(auth_path(&fixture.0)).unwrap();
let report = fixture.check();
assert!(report.can_repair);
assert_eq!(report.issues.len(), 2);
assert!(report
.repair_summary
.iter()
.all(|summary| summary.contains("OpenAI")));
assert_eq!(fixture.text(), original);
let repaired = fixture.repair(&report);
assert!(repaired.changed);
assert_eq!(repaired.report.status, "healthy");
let backup = fixture
.0
.join(".codexx-test-backups")
.join(repaired.backup_id.unwrap())
.join("config.toml");
assert_eq!(fs::read_to_string(backup).unwrap(), original);
let doc = fixture.text().parse::<DocumentMut>().unwrap();
assert_eq!(
doc.get("model_provider").and_then(Item::as_str),
if selection.is_empty() {
None
} else {
Some("openai")
}
);
assert_eq!(doc["model"].as_str(), Some("official-model"));
assert_eq!(
doc["mcp_servers"]["fixture"]["command"].as_str(),
Some("fixture-mcp")
);
for id in ["old_proxy_a", "old_proxy_b"] {
assert_eq!(doc["model_providers"][id]["name"].as_str(), Some("OpenAI"));
assert_eq!(
doc["model_providers"][id]["wire_api"].as_str(),
Some("responses")
);
assert_eq!(
doc["model_providers"][id]["requires_openai_auth"].as_bool(),
Some(true)
);
assert!(doc["model_providers"][id]
.as_table_like()
.unwrap()
.get("base_url")
.is_none());
}
assert_eq!(
fs::read(fixture.0.join("state_5.sqlite")).unwrap(),
db_before
);
assert_eq!(fs::read(auth_path(&fixture.0)).unwrap(), auth_before);
assert!(!fixture.repair(&repaired.report).changed);
}
}
#[test]
fn selected_custom_official_login_can_repair_history_with_multiple_inactive_sources() {
let original = "model_provider='custom'\n[model_providers.custom]\nname='OpenAI'\nrequires_openai_auth=true\nsupports_websockets=true\nwire_api='responses'\n[model_providers.inactive]\nname='Inactive proxy'\nbase_url='https://inactive.fixture/v1'\n";
let fixture = Fixture::new(original);
fixture.login();
fixture.sessions(&["old_proxy_a", "old_proxy_b"]);
let report = fixture.check();
assert!(report.can_repair);
assert_eq!(fixture.repair(&report).report.status, "healthy");
let doc = fixture.text().parse::<DocumentMut>().unwrap();
assert_eq!(doc["model_provider"].as_str(), Some("custom"));
assert_eq!(
doc["model_providers"]["old_proxy_a"]["supports_websockets"].as_bool(),
Some(true)
);
assert_eq!(
doc["model_providers"]["inactive"]["base_url"].as_str(),
Some("https://inactive.fixture/v1")
);
}
#[test]
fn official_history_repair_requires_login_and_unambiguous_current_routing() {
for text in [
"model_provider='openai'\n",
"model_provider='custom'\n[model_providers.custom]\nname='OpenAI'\nrequires_openai_auth=true\nwire_api='responses'\n",
] {
let fixture = Fixture::new(text);
fixture.sessions(&["old_proxy"]);
assert!(!fixture.check().can_repair, "{text}");
assert_eq!(fixture.text(), text);
}
for root in [
"base_url='https://proxy.fixture'",
"env_key='FIXTURE_API_KEY'",
"http_headers={Authorization='Bearer fixture'}",
"forced_login_method='api'",
"model_provider=5",
] {
let original = if root.starts_with("model_provider") {
format!("{root}\n")
} else {
format!("model_provider='openai'\n{root}\n")
};
let fixture = Fixture::new(&original);
fixture.login();
fixture.sessions(&["old_proxy"]);
let report = fixture.check();
assert!(!report.can_repair, "{root}");
assert!(!fixture.repair(&report).changed);
assert_eq!(fixture.text(), original);
}
for extra in [
"env_key='FIXTURE_API_KEY'",
"http_headers={Authorization='Bearer fixture'}",
"query_params={token='fixture'}",
] {
let original = format!("model_provider='custom'\n[model_providers.custom]\nname='OpenAI'\nrequires_openai_auth=true\nwire_api='responses'\n{extra}\n");
let fixture = Fixture::new(&original);
fixture.login();
fixture.sessions(&["old_proxy"]);
assert!(!fixture.check().can_repair, "{extra}");
assert_eq!(fixture.text(), original);
}
}
#[test]
fn login_removal_and_external_edit_cancel_official_alias_repairs() {
let original = "model_provider='openai'\n";
let fixture = Fixture::new(original);
fixture.login();
fixture.sessions(&["old_proxy"]);
let report = fixture.check();
assert!(report.can_repair);
let result = repair_with_before_write(&fixture.0, &report.fingerprint, || {
fs::remove_file(auth_path(&fixture.0)).unwrap();
});
assert!(result.is_err());
assert_eq!(fixture.text(), original);
fixture.login();
let report = fixture.check();
let result = repair_with_before_write(&fixture.0, &report.fingerprint, || {
fs::write(config_path(&fixture.0), "# external edit\n").unwrap();
});
assert!(result.is_err());
assert_eq!(fixture.text(), "# external edit\n");
}
#[test]
@@ -141,6 +141,13 @@ pub(crate) fn report_failover_lifecycle_error(app: &tauri::AppHandle, title: &st
pub(crate) fn handle_run_event(app: &tauri::AppHandle, event: tauri::RunEvent) {
if let tauri::RunEvent::ExitRequested { api, .. } = &event {
if crate::app_update::defer_exit_during_installation() {
// The installed bundle or updater handoff is being changed. A
// normal Quit must not interrupt it; Windows marks its authorized
// handoff before requesting process exit.
api.prevent_exit();
return;
}
if let Err(error) = crate::failover::shutdown_all() {
// Keep the listener alive when restoring the direct route failed.
// Exiting here would strand Codex on a local address with no server.
@@ -149,7 +156,9 @@ pub(crate) fn handle_run_event(app: &tauri::AppHandle, event: tauri::RunEvent) {
report_failover_lifecycle_error(
app,
"暂时无法退出 Codex-X",
&format!("自动切换的连接配置还未恢复,Codex-X 将继续运行。\n\n{error}\n\n请检查配置文件是否被占用,再重试退出。"),
&format!(
"路由仍需保持可用,Codex-X 将继续运行。\n\n{error}\n\n请按提示处理后再退出。"
),
);
}
}
+213 -20
View File
@@ -4,6 +4,7 @@
use super::config::{self, RoutingTuning, MAX_QUEUE, ROUTE_GENERATION_HEADER, ROUTE_TOKEN_HEADER};
use super::native_official;
use super::protocol::UpstreamApi;
use super::proxy::{ProxyHandle, ProxyOptions, ProxyRoute, ProxySelectionEvent, ProxySnapshot};
use crate::error::{CodexxError, Result};
use crate::file_io::parse_toml_document;
@@ -84,6 +85,8 @@ struct ProxyJournal {
table_existed: bool,
#[serde(default = "default_true")]
providers_existed: bool,
#[serde(default)]
requires_conversion: bool,
}
#[derive(Default, Clone, Serialize, Deserialize)]
@@ -552,9 +555,8 @@ fn provider_models(provider: &SavedProvider) -> Vec<String> {
}
fn route(provider: &SavedProvider) -> Result<ProxyRoute> {
if provider.wire_api != "responses" {
return Err(CodexxError::Config("需要支持 Responses 的供应商".into()));
}
let protocol =
UpstreamApi::from_provider(provider.upstream_api.as_deref(), &provider.wire_api)?;
let url = reqwest::Url::parse(provider.base_url.trim())
.map_err(|_| CodexxError::Config("供应商地址无效".into()))?;
if !matches!(url.scheme(), "http" | "https")
@@ -624,9 +626,6 @@ fn route(provider: &SavedProvider) -> Result<ProxyRoute> {
);
}
}
if provider.requires_openai_auth && api_key.is_none() {
return Err(CodexxError::Config("请先填写该供应商的 API Key".into()));
}
if let Some(key) = &api_key {
reqwest::header::HeaderValue::from_str(&format!("Bearer {key}"))
.map_err(|_| CodexxError::Config("供应商 API Key 格式不正确".into()))?;
@@ -643,7 +642,6 @@ fn route(provider: &SavedProvider) -> Result<ProxyRoute> {
| "content-length"
| "transfer-encoding"
| "cookie"
| "authorization"
| "proxy-authorization"
| "origin"
) {
@@ -670,7 +668,21 @@ fn route(provider: &SavedProvider) -> Result<ProxyRoute> {
}
}
}
if provider.requires_openai_auth
&& api_key.is_none()
&& !headers.iter().any(|(name, _)| {
matches!(
name.to_ascii_lowercase().as_str(),
"authorization" | "x-api-key" | "x-goog-api-key"
)
})
{
return Err(CodexxError::Config(
"请先填写该供应商的 API Key 或认证请求头".into(),
));
}
Ok(ProxyRoute {
protocol,
official: None,
id: provider.id.clone(),
name: provider.provider_name.clone(),
@@ -900,6 +912,7 @@ fn attach_route(dir: &Path, record: &mut Record, runtime: &mut Running) -> Resul
official: primary.official.is_some(),
table_existed: original.is_some(),
providers_existed: direct.get("model_providers").is_some(),
requires_conversion: primary.protocol.requires_routing(),
};
replace_table(
&mut direct,
@@ -1155,7 +1168,10 @@ pub(crate) fn get_status(config_dir: Option<String>) -> Result<FailoverStatus> {
let dir = directory(config_dir)?;
let mut runtimes = lock_manager()?;
let mut record = load_record(&dir)?;
if let Some(runtime) = runtimes.get_mut(&dir) {
if let Some(runtime) = runtimes
.get_mut(&dir)
.filter(|_| !SHUTTING_DOWN.load(Ordering::Acquire))
{
inspect_external_change(&dir, &mut record, runtime)?;
}
status_locked(&dir, record, runtimes.get(&dir))
@@ -1177,6 +1193,14 @@ pub(crate) fn save_settings(
if let Some(runtime) = runtimes.get_mut(&dir) {
inspect_external_change(&dir, &mut old, runtime)?;
}
if (!settings.router_enabled || !settings.takeover_enabled)
&& runtimes
.get(&dir)
.and_then(|runtime| runtime.journal.as_ref())
.is_some_and(|journal| journal.requires_conversion)
{
return Err(CodexxError::Config("当前供应商需要协议转换。请先切换到 Responses 供应商或官方账号,再关闭 Codex 接管或路由服务。".into()));
}
if let Some(runtime) = runtimes.get(&dir) {
if settings.router_enabled
&& (config::listen_ip(&settings.listen_address)? != runtime.proxy.listen_address()
@@ -1289,27 +1313,47 @@ pub(crate) fn with_provider_change<T>(
) -> Result<T> {
let dir = directory(config_dir)?;
let mut runtimes = lock_manager()?;
if SHUTTING_DOWN.load(Ordering::Acquire) {
return Err(CodexxError::Config(
"Codex-X 正在退出或交接更新,未更改供应商配置".into(),
));
}
let mut record = load_record(&dir)?;
let Some(runtime) = runtimes.get_mut(&dir) else {
drop(runtimes);
recover_stale_route(Some(dir.display().to_string()))?;
// A converted stale route cannot be restored to a supplier's raw URL.
// The explicit provider action can replace it with a new valid route.
if !record
.journals
.iter()
.any(|journal| journal.requires_conversion)
{
recover_stale_route(Some(dir.display().to_string()))?;
}
return action();
};
let reconnect = runtime.journal.is_some() && record.settings.takeover_enabled;
let checkpoint = FileCheckpoint::capture(&dir)?;
let old_record = record.clone();
let old_journal = runtime.journal.clone();
let old_routes = runtime.routes.clone();
let old_options = runtime.options.clone();
if reconnect {
detach_route(&dir, &record, runtime)?;
}
let result = action();
if reconnect {
if let Err(error) = attach_route(&dir, &mut record, runtime) {
record.settings.takeover_enabled = false;
record.message = Some(format!(
"供应商操作已结束,但重新接管失败;当前使用直连:{error}"
));
save_record(&dir, &record)?;
let expected = FileCheckpoint::capture(&dir)?;
checkpoint.restore(&dir, &expected)?;
save_record(&dir, &old_record)?;
runtime.journal = old_journal;
update_runtime(runtime, old_routes, old_options)?;
changed(&dir);
return match result {
Ok(_) => Err(CodexxError::Config(record.message.unwrap())),
Ok(_) => Err(CodexxError::Config(format!(
"供应商重新接管失败,已恢复原配置和路由:{error}"
))),
Err(original) => Err(original),
};
}
@@ -1318,11 +1362,53 @@ pub(crate) fn with_provider_change<T>(
result
}
/// Call at the IPC boundary before with_provider_change acquires the manager
/// lock. Internal P1/failover changes already run under validated takeover.
pub(crate) fn ensure_conversion_route(
config_dir: Option<String>,
provider: &SavedProvider,
) -> Result<()> {
let conversion =
UpstreamApi::from_provider(provider.upstream_api.as_deref(), &provider.wire_api)?
.requires_routing();
let dir = directory(config_dir)?;
let runtimes = lock_manager()?;
let record = load_record(&dir)?;
if runtimes
.get(&dir)
.is_some_and(|runtime| runtime.journal.is_some())
{
route(provider)?;
}
if !conversion {
return Ok(());
}
if !record.settings.router_enabled
|| !record.settings.takeover_enabled
|| runtimes
.get(&dir)
.is_none_or(|runtime| runtime.journal.is_none())
{
return Err(CodexxError::Config(
"该供应商需要协议转换。请先开启路由总开关和 Codex 请求接管,再启用该供应商。".into(),
));
}
Ok(())
}
pub(crate) fn recover_stale_route(config_dir: Option<String>) -> Result<()> {
let dir = directory(config_dir)?;
let record = load_record(&dir)?;
if dir.exists() && !record.journals.is_empty() {
let _guard = acquire_live_config_lock(&dir)?;
let doc = read_document(&dir)?.1;
if record
.journals
.iter()
.any(|journal| journal.requires_conversion && owned_route(&doc, journal))
{
return Err(CodexxError::Config("当前供应商需要协议转换,不能恢复为直连。请重新启动路由服务,或切换到 Responses 供应商/官方账号。".into()));
}
restore_owned_locked(&dir, &record)?;
}
Ok(())
@@ -1337,6 +1423,16 @@ fn refresh_routes_locked(dir: &Path, record: &mut Record, runtime: &mut Running)
{
Ok(()) => Ok(()),
Err(error) => {
if runtime
.journal
.as_ref()
.is_some_and(|journal| journal.requires_conversion)
{
record.message=Some(format!("协议转换供应商配置不可用,已保留原路由;请修正配置或切换到 Responses 供应商:{error}"));
save_record(dir, record)?;
changed(dir);
return Ok(());
}
detach_route(dir, record, runtime)?;
record.settings.takeover_enabled = false;
record.message = Some(format!("当前供应商配置不可用,已恢复直连:{error}"));
@@ -1348,6 +1444,11 @@ fn refresh_routes_locked(dir: &Path, record: &mut Record, runtime: &mut Running)
}
pub(crate) fn refresh_saved_routes() -> Result<()> {
let mut runtimes = lock_manager()?;
if SHUTTING_DOWN.load(Ordering::Acquire) {
return Err(CodexxError::Config(
"Codex-X 正在退出或交接更新,未更改路由配置".into(),
));
}
for (dir, runtime) in runtimes.iter_mut() {
let mut record = load_record(dir)?;
refresh_routes_locked(dir, &mut record, runtime)?;
@@ -1370,6 +1471,9 @@ fn record_selection(
notice: SelectionNotice,
runtimes: &mut HashMap<PathBuf, Running>,
) -> Result<()> {
if SHUTTING_DOWN.load(Ordering::Acquire) {
return Ok(());
}
let Some(runtime) = runtimes.get_mut(&notice.dir) else {
return Ok(());
};
@@ -1425,6 +1529,9 @@ fn record_selection(
*original.as_table_mut() = table;
let mut next = journal.clone();
next.primary_id = provider.id.clone();
next.requires_conversion =
UpstreamApi::from_provider(provider.upstream_api.as_deref(), &provider.wire_api)?
.requires_routing();
next.original_table = original.to_string();
next.lease_id = Some(random_token()?);
let _guard = acquire_live_config_lock(&notice.dir)?;
@@ -1506,7 +1613,16 @@ pub(crate) fn initialize() -> Result<()> {
}
let mut record = load_record(&dir)?;
let desired = record.settings.takeover_enabled;
if !record.journals.is_empty() && dir.exists() {
let converted_owned = if dir.exists() {
let doc = read_document(&dir)?.1;
record
.journals
.iter()
.any(|journal| journal.requires_conversion && owned_route(&doc, journal))
} else {
false
};
if !converted_owned && !record.journals.is_empty() && dir.exists() {
let _guard = acquire_live_config_lock(&dir)?;
restore_owned_locked(&dir, &record)?;
}
@@ -1518,6 +1634,11 @@ pub(crate) fn initialize() -> Result<()> {
match normalized_settings(record.settings.clone()) {
Ok(settings) => record.settings = settings,
Err(error) => {
if converted_owned {
record.message=Some(format!("协议转换路由无法启动,已保留本地接管配置;请检查端口或切换到 Responses 供应商:{error}"));
save_record(&dir, &record)?;
continue;
}
record.settings.router_enabled = false;
record.settings.takeover_enabled = false;
record.message = Some(format!("路由设置需要检查,当前使用直连:{error}"));
@@ -1548,6 +1669,11 @@ pub(crate) fn initialize() -> Result<()> {
saved?;
}
Err(error) => {
if converted_owned {
record.message=Some(format!("协议转换路由无法启动,已保留本地接管配置;请检查端口或切换到 Responses 供应商:{error}"));
save_record(&dir, &record)?;
continue;
}
record.settings.router_enabled = false;
record.settings.takeover_enabled = false;
record.message = Some(format!("路由未启动,当前使用直连:{error}"));
@@ -1567,6 +1693,9 @@ fn ensure_watcher() {
let Ok(mut runtimes) = lock_manager() else {
continue;
};
if SHUTTING_DOWN.load(Ordering::Acquire) {
continue;
}
let events: Vec<_> = notices()
.1
.lock()
@@ -1592,17 +1721,82 @@ fn ensure_watcher() {
});
});
}
fn shutdown_allowed_locked(runtimes: &HashMap<PathBuf, Running>) -> Result<()> {
for (dir, runtime) in runtimes {
let Some(journal) = runtime.journal.as_ref() else {
continue;
};
let doc = read_document(dir)?.1;
if journal.requires_conversion && owned_route(&doc, journal) {
let record = load_record(dir)?;
let persisted=record.journals.iter().find(|saved| saved.requires_conversion && saved.primary_id==journal.primary_id && saved.provider_key==journal.provider_key && saved.token==journal.token && saved.lease_id==journal.lease_id && owned_route(&doc,saved))
.ok_or_else(||CodexxError::Config("转换路由的恢复记录缺失,服务继续运行;请重新启用 Codex 接管后重试退出或更新。".into()))?;
original_table(persisted)?;
} else if !journal.requires_conversion {
// Validate the existing native restore projection without writing.
restored_document(&doc, journal)?;
}
}
Ok(())
}
/// Read-only check for exit/update callers before they modify the application.
pub(crate) fn ensure_shutdown_allowed() -> Result<()> {
let runtimes = lock_manager()?;
shutdown_allowed_locked(&runtimes)
}
/// Freeze configuration mutations during an update while keeping active
/// requests and the listener alive until the installer needs the process exit.
pub(crate) fn begin_update_handoff() -> Result<()> {
let runtimes = lock_manager()?;
shutdown_allowed_locked(&runtimes)?;
SHUTTING_DOWN.store(true, Ordering::Release);
Ok(())
}
pub(crate) fn shutdown_all() -> Result<()> {
SHUTTING_DOWN.store(true, Ordering::Release);
let result = (|| -> Result<()> {
let mut runtimes = lock_manager()?;
shutdown_allowed_locked(&runtimes)?;
let dirs: Vec<_> = runtimes.keys().cloned().collect();
for dir in dirs {
let record = load_record(&dir)?;
let mut record = load_record(&dir)?;
if let Some(runtime) = runtimes.get_mut(&dir) {
detach_route(&dir, &record, runtime)?;
if let Some(journal) = runtime
.journal
.as_ref()
.filter(|journal| journal.requires_conversion)
{
let previous_settings = record.settings.clone();
let previous_message = record.message.clone();
let doc = read_document(&dir)?.1;
if !selected_owned_route(&doc, journal) {
// An explicit external selection is kept exactly as it
// is; the next launch must not take it over implicitly.
record.settings.takeover_enabled = false;
record.message = Some(
"退出时检测到外部供应商配置,已原样保留;下次启动不会自动接管该配置。"
.into(),
);
} else {
record.settings.router_enabled = true;
record.settings.takeover_enabled = true;
record.settings.listen_address = runtime.proxy.listen_address().to_string();
record.settings.listen_port = runtime.proxy.port();
}
if record.settings != previous_settings || record.message != previous_message {
save_record(&dir, &record)?;
}
// Keep the owned loopback overlay and recovery journal.
// initialize reconnects it on the next app launch. Restoring
// this supplier's raw URL would send an invalid /responses.
} else {
detach_route(&dir, &record, runtime)?;
}
}
// Keep desired settings for next launch; restore first, stop last.
// All required writes/validation finish before stopping a listener.
if let Some(runtime) = runtimes.remove(&dir) {
runtime.proxy.shutdown();
}
@@ -1617,7 +1811,6 @@ pub(crate) fn shutdown_all() -> Result<()> {
/// Only an update handoff that has not launched an installer may resume the
/// saved routes. A successful handoff keeps the shutdown gate closed until exit.
#[cfg(any(test, target_os = "windows"))]
pub(crate) fn resume_after_failed_update() -> Result<()> {
SHUTTING_DOWN.store(false, Ordering::Release);
let expected: Vec<_> = stored_directories()?
+5 -4
View File
@@ -2,13 +2,14 @@ mod circuit_breaker;
pub(crate) mod config;
mod controller;
pub(crate) mod native_official;
pub(crate) mod protocol;
mod proxy;
#[cfg(any(test, target_os = "windows"))]
pub(crate) use controller::resume_after_failed_update;
pub(crate) use controller::{
attach_app_handle, direct_document, get_status, initialize, recover_stale_route,
refresh_saved_routes, reset_health, save_settings, shutdown_all, with_provider_change,
FailoverSettings, FailoverStatus,
attach_app_handle, begin_update_handoff, direct_document, ensure_conversion_route,
ensure_shutdown_allowed, get_status, initialize, recover_stale_route, refresh_saved_routes,
reset_health, save_settings, shutdown_all, with_provider_change, FailoverSettings,
FailoverStatus,
};
@@ -182,6 +182,7 @@ pub(crate) fn route_for_current(dir: &Path) -> Result<Option<ProxyRoute>> {
.into_iter()
.collect::<HashSet<_>>();
Ok(Some(ProxyRoute {
protocol: super::protocol::UpstreamApi::Responses,
id: format!("official:{profile_id}"),
name,
base_url,
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,455 @@
use super::{encode_thinking, ToolContext, UpstreamApi};
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
pub(crate) fn error_message(value: &Value) -> Option<String> {
let error = value.get("error").filter(|v| !v.is_null()).or_else(|| {
(value.get("type").and_then(Value::as_str) == Some("error")).then_some(value)
})?;
Some(
error
.as_str()
.map(str::to_owned)
.or_else(|| {
error
.get("message")
.or_else(|| error.get("detail"))
.and_then(Value::as_str)
.map(str::to_owned)
})
.unwrap_or_else(|| error.to_string()),
)
}
pub(crate) fn convert_response(
api: UpstreamApi,
body: &Value,
context: &ToolContext,
requested_model: &str,
) -> std::result::Result<Value, String> {
if let Some(error) = error_message(body) {
return Err(error);
}
match api {
UpstreamApi::Responses => Ok(body.clone()),
UpstreamApi::ChatCompletions => chat_response(body, context, requested_model),
UpstreamApi::AnthropicMessages => anthropic_response(body, context, requested_model),
UpstreamApi::Gemini => gemini_response(body, context, requested_model),
}
}
pub(super) fn response_id(id: Option<&str>) -> String {
if let Some(id) = id.filter(|s| !s.is_empty()) {
let digest = Sha256::digest(id.as_bytes());
return format!(
"resp_codexx_{}",
digest
.iter()
.take(12)
.map(|b| format!("{b:02x}"))
.collect::<String>()
);
}
format!(
"resp_codexx_{}",
chrono::Utc::now().timestamp_nanos_opt().unwrap_or_default()
)
}
pub(super) fn envelope(
id: &str,
model: &str,
status: &str,
output: Vec<Value>,
usage: Value,
reason: Option<&str>,
) -> Value {
let mut value = json!({"id":id,"object":"response","created_at":chrono::Utc::now().timestamp(),"model":model,"status":status,"output":output,"usage":usage,"error":null,"incomplete_details":null});
if let Some(reason) = reason {
value["incomplete_details"] = json!({"reason":reason});
}
value
}
pub(super) fn text_item(id: &str, text: &str) -> Value {
json!({"id":id,"type":"message","role":"assistant","status":"completed","content":[{"type":"output_text","text":text,"annotations":[]}]})
}
pub(super) fn reasoning_item(id: &str, text: &str, state: Option<Value>) -> Value {
let mut value = json!({"id":id,"type":"reasoning","summary":if text.is_empty(){json!([])}else{json!([{"type":"summary_text","text":text}])}});
if let Some(state) = state {
value["encrypted_content"] = json!(encode_thinking(&state));
}
value
}
pub(super) fn tool_item(
context: &ToolContext,
id: &str,
call_id: &str,
upstream_name: &str,
arguments: &str,
) -> std::result::Result<Value, String> {
if upstream_name.is_empty() {
return Err("上游工具调用缺少名称".into());
}
let spec = context.names.get(upstream_name);
let mut value = if spec.is_some_and(|s| s.custom) {
let arguments: Value =
serde_json::from_str(arguments).map_err(|_| "上游 custom 工具参数不是有效的 JSON")?;
let input = arguments
.get("input")
.and_then(Value::as_str)
.ok_or("上游 custom 工具参数缺少 input 文字")?;
json!({"id":id,"type":"custom_tool_call","call_id":call_id,"name":spec.unwrap().name,"input":input,"status":"completed"})
} else {
let parsed: Value =
serde_json::from_str(arguments).map_err(|_| "上游工具参数不是有效的 JSON")?;
if !parsed.is_object() {
return Err("上游工具参数须是 JSON 对象".into());
}
json!({"id":id,"type":"function_call","call_id":call_id,"name":spec.map_or(upstream_name,|s|s.name.as_str()),"arguments":arguments,"status":"completed"})
};
if let Some(namespace) = spec.and_then(|s| s.namespace.as_deref()) {
value["namespace"] = json!(namespace);
}
Ok(value)
}
pub(super) fn terminal(
api: UpstreamApi,
reason: Option<&str>,
) -> (&'static str, Option<&'static str>) {
match (api, reason) {
(_, Some("length" | "max_tokens" | "MAX_TOKENS" | "model_context_window_exceeded")) => {
("incomplete", Some("max_output_tokens"))
}
(
_,
Some(
"content_filter" | "refusal" | "SAFETY" | "BLOCKLIST" | "PROHIBITED_CONTENT"
| "RECITATION" | "SPII" | "IMAGE_SAFETY",
),
) => ("incomplete", Some("content_filter")),
(_, Some("MALFORMED_FUNCTION_CALL" | "UNEXPECTED_TOOL_CALL")) => {
("incomplete", Some("tool_call_error"))
}
_ => ("completed", None),
}
}
fn tokens(value: Option<&Value>) -> u64 {
value.and_then(Value::as_u64).unwrap_or(0)
}
pub(super) fn usage(api: UpstreamApi, value: Option<&Value>) -> Value {
let empty = json!({});
let u = value.unwrap_or(&empty);
let (input, output, cached, reasoning, write) = match api {
UpstreamApi::ChatCompletions => (
tokens(u.get("prompt_tokens")),
tokens(u.get("completion_tokens")),
tokens(u.pointer("/prompt_tokens_details/cached_tokens"))
.max(tokens(u.get("prompt_cache_hit_tokens"))),
tokens(u.pointer("/completion_tokens_details/reasoning_tokens")),
tokens(u.get("cache_creation_input_tokens")),
),
UpstreamApi::AnthropicMessages => {
let cached = tokens(u.get("cache_read_input_tokens"));
let write = tokens(u.get("cache_creation_input_tokens"));
(
tokens(u.get("input_tokens"))
.saturating_add(cached)
.saturating_add(write),
tokens(u.get("output_tokens")),
cached,
tokens(u.get("thinking_tokens")),
write,
)
}
UpstreamApi::Gemini => {
let reasoning = tokens(u.get("thoughtsTokenCount"));
(
tokens(u.get("promptTokenCount")),
tokens(u.get("candidatesTokenCount")).saturating_add(reasoning),
tokens(u.get("cachedContentTokenCount")),
reasoning,
0,
)
}
UpstreamApi::Responses => return u.clone(),
};
json!({"input_tokens":input,"output_tokens":output,"total_tokens":input.saturating_add(output),"input_tokens_details":{"cached_tokens":cached,"cache_write_tokens":write},"output_tokens_details":{"reasoning_tokens":reasoning}})
}
fn chat_response(
body: &Value,
context: &ToolContext,
model: &str,
) -> std::result::Result<Value, String> {
let choice = body
.get("choices")
.and_then(Value::as_array)
.and_then(|v| v.first())
.ok_or("Chat 响应缺少 choices")?;
let message = choice.get("message").ok_or("Chat 响应缺少 message")?;
let id = response_id(body.get("id").and_then(Value::as_str));
let mut output = Vec::new();
if let Some(thinking) = chat_reasoning(message) {
output.push(reasoning_item(&format!("rs_{id}"), &thinking, None));
}
let text = match message.get("content") {
Some(Value::String(text)) => text.clone(),
Some(Value::Array(parts)) => {
let mut text = String::new();
for part in parts {
if matches!(
part.get("type").and_then(Value::as_str),
Some("text" | "output_text")
) {
text.push_str(
part.get("text")
.and_then(Value::as_str)
.ok_or("Chat 文字内容缺少 text")?,
);
} else {
return Err("Chat 响应含不能转换的非文字内容".into());
}
}
text
}
_ => String::new(),
};
if !text.is_empty() {
output.push(text_item(&format!("msg_{id}"), &text));
}
if let Some(refusal) = message.get("refusal").and_then(Value::as_str) {
output.push(json!({"id":format!("msg_refusal_{id}"),"type":"message","role":"assistant","status":"completed","content":[{"type":"refusal","refusal":refusal}]}));
}
if let Some(calls) = message.get("tool_calls").and_then(Value::as_array) {
for (index, call) in calls.iter().enumerate() {
let function = call.get("function").ok_or("Chat 工具调用缺少 function")?;
let call_id = call
.get("id")
.and_then(Value::as_str)
.map(str::to_owned)
.unwrap_or_else(|| format!("call_{id}_{index}"));
output.push(tool_item(
context,
&format!("fc_{id}_{index}"),
&call_id,
function.get("name").and_then(Value::as_str).unwrap_or(""),
function
.get("arguments")
.and_then(Value::as_str)
.unwrap_or("{}"),
)?);
}
}
if let Some(call) = message.get("function_call") {
output.push(tool_item(
context,
&format!("fc_{id}_legacy"),
&format!("call_{id}_legacy"),
call.get("name").and_then(Value::as_str).unwrap_or(""),
call.get("arguments")
.and_then(Value::as_str)
.unwrap_or("{}"),
)?);
}
let reason = choice
.get("finish_reason")
.and_then(Value::as_str)
.ok_or("Chat 响应缺少 finish_reason,无法确认完整完成")?;
let (status, incomplete) = terminal(UpstreamApi::ChatCompletions, Some(reason));
Ok(envelope(
&id,
body.get("model").and_then(Value::as_str).unwrap_or(model),
status,
output,
usage(UpstreamApi::ChatCompletions, body.get("usage")),
incomplete,
))
}
pub(super) fn chat_reasoning(value: &Value) -> Option<String> {
value
.get("reasoning_content")
.or_else(|| value.get("reasoning"))
.and_then(|v| match v {
Value::String(s) if !s.is_empty() => Some(s.clone()),
Value::Array(items) => Some(
items
.iter()
.filter_map(|v| v.get("text").and_then(Value::as_str))
.collect::<Vec<_>>()
.join(""),
),
_ => None,
})
}
fn anthropic_response(
body: &Value,
context: &ToolContext,
model: &str,
) -> std::result::Result<Value, String> {
let blocks = body
.get("content")
.and_then(Value::as_array)
.ok_or("Anthropic 响应缺少 content")?;
let id = response_id(body.get("id").and_then(Value::as_str));
let mut output = Vec::new();
for (index, block) in blocks.iter().enumerate() {
match block.get("type").and_then(Value::as_str) {
Some("text") => output.push(text_item(
&format!("msg_{id}_{index}"),
block.get("text").and_then(Value::as_str).unwrap_or(""),
)),
Some("thinking" | "redacted_thinking") => output.push(reasoning_item(
&format!("rs_{id}_{index}"),
block.get("thinking").and_then(Value::as_str).unwrap_or(""),
Some(json!({"protocol":"anthropic","block":block})),
)),
Some("tool_use") => {
let call_id = block
.get("id")
.and_then(Value::as_str)
.ok_or("Anthropic tool_use 缺少 id")?;
output.push(tool_item(
context,
&format!("fc_{id}_{index}"),
call_id,
block.get("name").and_then(Value::as_str).unwrap_or(""),
&block
.get("input")
.cloned()
.unwrap_or_else(|| json!({}))
.to_string(),
)?);
}
Some(other) => return Err(format!("无法转换 Anthropic 输出类型 {other}")),
None => return Err("Anthropic content 缺少类型".into()),
}
}
let reason = body
.get("stop_reason")
.and_then(Value::as_str)
.ok_or("Anthropic 响应缺少 stop_reason,无法确认完整完成")?;
let (status, incomplete) = terminal(UpstreamApi::AnthropicMessages, Some(reason));
Ok(envelope(
&id,
body.get("model").and_then(Value::as_str).unwrap_or(model),
status,
output,
usage(UpstreamApi::AnthropicMessages, body.get("usage")),
incomplete,
))
}
fn gemini_response(
body: &Value,
context: &ToolContext,
model: &str,
) -> std::result::Result<Value, String> {
if let Some(block) = body
.pointer("/promptFeedback/blockReason")
.and_then(Value::as_str)
{
return Err(format!("Gemini 拒绝了输入:{block}"));
}
let candidate = body
.get("candidates")
.and_then(Value::as_array)
.and_then(|v| v.first())
.ok_or("Gemini 响应缺少 candidates")?;
let parts = candidate
.pointer("/content/parts")
.and_then(Value::as_array);
if context.single_tool
&& parts
.into_iter()
.flatten()
.filter(|part| part.get("functionCall").is_some())
.count()
> 1
{
return Err("Gemini 返回了多个并行工具调用,而本次请求禁止并行;未向 Codex 返回任何可执行工具,请重试".into());
}
let id = response_id(body.get("responseId").and_then(Value::as_str));
let mut output = Vec::new();
let signed: Vec<Value> = parts
.into_iter()
.flatten()
.enumerate()
.filter(|(_, part)| {
part.get("thoughtSignature").is_some()
&& part.get("thought").and_then(Value::as_bool) != Some(true)
})
.map(|(index, part)| {
let mut part = part.clone();
if part.get("text").is_some() {
part["codex_item_id"] = json!(format!("msg_{id}_{index}"));
}
if part.get("functionCall").is_some() && part.pointer("/functionCall/id").is_none() {
part["functionCall"]["id"] = json!(format!("call_{id}_{index}"));
}
part
})
.collect();
if !signed.is_empty() {
output.push(reasoning_item(
&format!("rs_sig_{id}"),
"",
Some(json!({"protocol":"gemini","parts":signed})),
));
}
for (index, part) in parts.into_iter().flatten().enumerate() {
if let Some(text) = part.get("text").and_then(Value::as_str) {
output.push(
if part.get("thought").and_then(Value::as_bool) == Some(true) {
reasoning_item(
&format!("rs_{id}_{index}"),
text,
Some(json!({"protocol":"gemini","parts":[part]})),
)
} else {
text_item(&format!("msg_{id}_{index}"), text)
},
);
} else if let Some(call) = part.get("functionCall") {
let call_id = call
.get("id")
.and_then(Value::as_str)
.map(str::to_owned)
.unwrap_or_else(|| format!("call_{id}_{index}"));
output.push(tool_item(
context,
&format!("fc_{id}_{index}"),
&call_id,
call.get("name").and_then(Value::as_str).unwrap_or(""),
&call
.get("args")
.cloned()
.unwrap_or_else(|| json!({}))
.to_string(),
)?);
} else if part.get("thoughtSignature").is_none() {
return Err("Gemini 返回了不能转换为 Codex 输出的多模态内容".into());
}
}
let reason = candidate
.get("finishReason")
.and_then(Value::as_str)
.ok_or("Gemini 响应缺少 finishReason,无法确认完整完成")?;
let (status, incomplete) = terminal(UpstreamApi::Gemini, Some(reason));
Ok(envelope(
&id,
body.get("modelVersion")
.and_then(Value::as_str)
.unwrap_or(model),
status,
output,
usage(UpstreamApi::Gemini, body.get("usageMetadata")),
incomplete,
))
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,484 @@
use super::*;
use std::io::{self, Read};
fn prepared(api: UpstreamApi, body: Value) -> PreparedRequest {
prepare(api, &serde_json::to_vec(&body).unwrap(), false).unwrap()
}
fn request(api: UpstreamApi, body: Value) -> Value {
serde_json::from_slice(&prepared(api, body).bytes).unwrap()
}
fn events(text: &str) -> Vec<Value> {
text.lines()
.filter_map(|line| line.strip_prefix("data: "))
.map(|line| serde_json::from_str(line).unwrap())
.collect()
}
struct ByteReader(Vec<u8>, usize);
impl Read for ByteReader {
fn read(&mut self, output: &mut [u8]) -> io::Result<usize> {
if self.1 == self.0.len() {
return Ok(0);
}
output[0] = self.0[self.1];
self.1 += 1;
Ok(1)
}
}
fn streamed(api: UpstreamApi, input: &str, context: ToolContext) -> String {
let mut reader = ResponseStream::new(
ByteReader(input.as_bytes().to_vec(), 0),
api,
context,
"fixture".into(),
);
let mut text = String::new();
reader.read_to_string(&mut text).unwrap();
text
}
#[test]
fn request_conversions_preserve_roles_media_tools_and_parallel_results() {
let body = json!({"model":"fixture","instructions":"system instruction","max_output_tokens":7000,"input":[
{"role":"developer","content":"developer instruction"},
{"role":"user","content":[{"type":"input_text","text":"inspect this"},{"type":"input_image","image_url":"data:image/png;base64,aGVsbG8="}]},
{"type":"function_call","call_id":"call-1","namespace":"functions","name":"read","arguments":"{\"path\":\"x\"}"},
{"type":"custom_tool_call","call_id":"call-2","name":"apply_patch","input":"*** Begin Patch\n*** End Patch"},
{"type":"function_call_output","call_id":"call-1","output":"file text"},
{"type":"custom_tool_call_output","call_id":"call-2","output":[{"type":"input_text","text":"patched"},{"type":"input_image","image_url":"data:image/png;base64,aGVsbG8="}]}
],"tools":[{"type":"namespace","name":"functions","tools":[{"type":"function","name":"read","parameters":{"type":"object","properties":{"path":{"type":"string"}}}}]},{"type":"custom","name":"apply_patch","description":"Apply a patch","format":{"type":"grammar","syntax":"lark","definition":"start: /.+/"}}]});
let chat = request(UpstreamApi::ChatCompletions, body.clone());
assert_eq!(chat["messages"][0]["role"], "system");
assert_eq!(chat["messages"][1]["role"], "system");
assert_eq!(
chat["messages"][2]["content"][1]["image_url"]["url"],
"data:image/png;base64,aGVsbG8="
);
assert_eq!(
chat["messages"][3]["tool_calls"].as_array().unwrap().len(),
2
);
assert_eq!(chat["messages"][4]["tool_call_id"], "call-1");
assert_eq!(chat["messages"][5]["tool_call_id"], "call-2");
assert_eq!(chat["messages"][6]["role"], "user");
assert!(chat["tools"][0]["function"]["name"]
.as_str()
.unwrap()
.starts_with("functions__read_"));
assert!(chat["tools"][1]["function"]["description"]
.as_str()
.unwrap()
.contains("grammar"));
let anthropic = request(UpstreamApi::AnthropicMessages, body.clone());
assert!(anthropic["system"]
.as_str()
.unwrap()
.contains("developer instruction"));
assert_eq!(anthropic["max_tokens"], 7000);
assert_eq!(
anthropic["messages"][0]["content"][1]["source"]["media_type"],
"image/png"
);
assert_eq!(
anthropic["messages"][1]["content"]
.as_array()
.unwrap()
.len(),
2
);
assert_eq!(
anthropic["messages"][2]["content"][1]["content"][1]["type"],
"image"
);
let gemini = request(UpstreamApi::Gemini, body);
assert_eq!(
gemini["systemInstruction"]["parts"]
.as_array()
.unwrap()
.len(),
2
);
assert_eq!(
gemini["contents"][0]["parts"][1]["inlineData"]["mimeType"],
"image/png"
);
assert_eq!(
gemini["contents"][1]["parts"][0]["functionCall"]["id"],
"call-1"
);
assert_eq!(
gemini["contents"][2]["parts"][0]["functionResponse"]["id"],
"call-1"
);
assert_eq!(
gemini["contents"][2]["parts"][0]["functionResponse"]["name"],
gemini["contents"][1]["parts"][0]["functionCall"]["name"]
);
}
#[test]
fn unsupported_responses_server_state_is_explicit_and_native_bytes_are_unchanged() {
for api in [
UpstreamApi::ChatCompletions,
UpstreamApi::AnthropicMessages,
UpstreamApi::Gemini,
] {
for body in [
json!({"model":"fixture","input":"x","previous_response_id":"resp-remote"}),
json!({"model":"fixture","input":[{"type":"reasoning","encrypted_content":"opaque-upstream-ciphertext"}]}),
json!({"model":"fixture","input":[{"type":"item_reference","id":"remote-item"}]}),
] {
let bytes = serde_json::to_vec(&body).unwrap();
assert!(prepare(api, &bytes, false).is_err());
assert_eq!(
prepare(UpstreamApi::Responses, &bytes, false)
.unwrap()
.bytes,
bytes
);
}
assert!(prepare(api, br#"{"model":"fixture","input":"x"}"#, true)
.unwrap_err()
.contains("compact"));
}
}
#[test]
fn namespace_and_custom_tools_restore_original_codex_shapes() {
let prepared = prepared(
UpstreamApi::ChatCompletions,
json!({"model":"fixture","input":"x","tools":[{"type":"namespace","name":"functions","tools":[{"type":"function","name":"read"}]},{"type":"custom","name":"apply_patch"}]}),
);
let name = prepared.context.upstream_name("read", Some("functions"));
let body = json!({"id":"chat-1","choices":[{"finish_reason":"tool_calls","message":{"tool_calls":[{"id":"a","function":{"name":name,"arguments":"{}"}},{"id":"b","function":{"name":"apply_patch","arguments":"{\"input\":\"patch text\"}"}}]}}],"usage":{"prompt_tokens":3,"completion_tokens":4}});
let converted = convert_response(
UpstreamApi::ChatCompletions,
&body,
&prepared.context,
"fixture",
)
.unwrap();
assert_eq!(converted["output"][0]["namespace"], "functions");
assert_eq!(converted["output"][0]["name"], "read");
assert_eq!(converted["output"][1]["type"], "custom_tool_call");
assert_eq!(converted["output"][1]["input"], "patch text");
assert_eq!(converted["usage"]["total_tokens"], 7);
}
#[test]
fn chat_sse_crosses_utf8_crlf_and_fragmented_function_json() {
let context = prepared(
UpstreamApi::ChatCompletions,
json!({"model":"fixture","input":"x","tools":[{"type":"function","name":"read"}]}),
)
.context;
let input=concat!("data: {\"id\":\"c\",\"choices\":[{\"delta\":{\"content\":\"中文🙂\"}}]}\r\n\r\n", "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call-x\",\"function\":{\"name\":\"read\",\"arguments\":\"{\\\"x\\\":\"}}]}}]}\r\n\r\n", "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"1}\"}}]},\"finish_reason\":\"tool_calls\"}]}\r\n\r\n", "data: {\"choices\":[],\"usage\":{\"prompt_tokens\":5,\"completion_tokens\":2}}\r\n\r\n", "data: [DONE]\r\n\r\n");
let output = streamed(UpstreamApi::ChatCompletions, input, context);
let events = events(&output);
assert!(events
.iter()
.any(|v| v["type"] == "response.output_text.delta" && v["delta"] == "中文🙂"));
let response = &events.last().unwrap()["response"];
assert_eq!(response["status"], "completed");
assert_eq!(response["output"][1]["call_id"], "call-x");
assert_eq!(response["output"][1]["arguments"], "{\"x\":1}");
assert_eq!(response["usage"]["total_tokens"], 7);
}
#[test]
fn stream_error_before_output_returns_error_and_after_output_emits_failed() {
let error = "event: error\ndata: {\"error\":{\"message\":\"fixture outage\"}}\n\n";
let mut early = ResponseStream::new(
io::Cursor::new(error),
UpstreamApi::ChatCompletions,
ToolContext::default(),
"fixture".into(),
);
let mut bytes = Vec::new();
assert!(early.read_to_end(&mut bytes).is_err());
assert!(bytes.is_empty());
let output = streamed(
UpstreamApi::ChatCompletions,
&format!("data: {{\"choices\":[{{\"delta\":{{\"content\":\"partial\"}}}}]}}\n\n{error}"),
ToolContext::default(),
);
let events = events(&output);
assert_eq!(events.last().unwrap()["type"], "response.failed");
assert!(events.iter().all(|v| v["type"] != "response.completed"));
}
#[test]
fn stream_eof_without_terminal_signal_is_incomplete() {
for (api, input) in [
(
UpstreamApi::ChatCompletions,
"data: {\"choices\":[{\"delta\":{\"content\":\"partial\"}}]}\n\n",
),
(
UpstreamApi::Gemini,
"data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"partial\"}]}}]}\n\n",
),
] {
let output = streamed(api, input, ToolContext::default());
let events = events(&output);
assert_eq!(events.last().unwrap()["type"], "response.incomplete");
assert_eq!(
events.last().unwrap()["response"]["incomplete_details"]["reason"],
"stream_truncated"
);
}
}
#[test]
fn anthropic_thinking_signature_and_gemini_tool_signature_round_trip() {
let ctx = prepared(
UpstreamApi::Gemini,
json!({"model":"fixture","input":"x","tools":[{"type":"function","name":"read"}]}),
)
.context;
let anthropic = json!({"id":"m","type":"message","content":[{"type":"thinking","thinking":"analysis","signature":"signed-thinking"},{"type":"tool_use","id":"call-a","name":"read","input":{}}],"stop_reason":"tool_use","usage":{"input_tokens":2,"output_tokens":3,"cache_read_input_tokens":5}});
let response =
convert_response(UpstreamApi::AnthropicMessages, &anthropic, &ctx, "fixture").unwrap();
assert_eq!(response["usage"]["input_tokens"], 7);
let mut history = vec![json!({"role":"user","content":"inspect"})];
history.extend(response["output"].as_array().unwrap().clone());
history.push(json!({"type":"function_call_output","call_id":"call-a","output":"done"}));
let anthropic_req = request(
UpstreamApi::AnthropicMessages,
json!({"model":"fixture","input":history}),
);
assert_eq!(
anthropic_req["messages"][1]["content"][0]["signature"],
"signed-thinking"
);
let gemini = json!({"responseId":"g","candidates":[{"content":{"parts":[{"functionCall":{"name":"read","args":{}},"thoughtSignature":"signed-function"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":2,"candidatesTokenCount":3,"thoughtsTokenCount":4}});
let response = convert_response(UpstreamApi::Gemini, &gemini, &ctx, "fixture").unwrap();
let call = response["output"]
.as_array()
.unwrap()
.iter()
.find(|v| v["type"] == "function_call")
.unwrap();
let mut history = vec![json!({"role":"user","content":"inspect"})];
history.extend(response["output"].as_array().unwrap().clone());
history.push(json!({"type":"function_call_output","call_id":call["call_id"],"output":"done"}));
let request = request(
UpstreamApi::Gemini,
json!({"model":"fixture","input":history}),
);
assert_eq!(request["contents"][1]["parts"].as_array().unwrap().len(), 1);
assert_eq!(
request["contents"][1]["parts"][0]["thoughtSignature"],
"signed-function"
);
assert_eq!(response["usage"]["output_tokens"], 7);
}
#[test]
fn stream_json_fallback_and_length_reason_are_truthful() {
let input = r#"{"id":"chat","choices":[{"message":{"content":"truncated"},"finish_reason":"length"}],"usage":{"prompt_tokens":2,"completion_tokens":3}}"#;
let output = streamed(UpstreamApi::ChatCompletions, input, ToolContext::default());
let events = events(&output);
assert_eq!(events.last().unwrap()["type"], "response.incomplete");
assert_eq!(
events.last().unwrap()["response"]["incomplete_details"]["reason"],
"max_output_tokens"
);
}
#[test]
fn gemini_signed_text_chunks_replay_on_the_matching_assistant_message() {
let input="data: {\"responseId\":\"g\",\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"hello \"}]}}]}\n\ndata: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"world\",\"thoughtSignature\":\"signature\"}]},\"finishReason\":\"STOP\"}]}\n\n";
let output = streamed(UpstreamApi::Gemini, input, ToolContext::default());
let ev = events(&output);
let response = &ev.last().unwrap()["response"];
let mut history = vec![json!({"role":"user","content":"hello world"})];
history.extend(response["output"].as_array().unwrap().clone());
history.push(json!({"role":"user","content":"continue"}));
let converted = request(
UpstreamApi::Gemini,
json!({"model":"gemini-2.5-pro","input":history}),
);
assert!(converted["contents"][0]["parts"][0]
.get("thoughtSignature")
.is_none());
assert_eq!(converted["contents"][1]["parts"][0]["text"], "hello world");
assert_eq!(
converted["contents"][1]["parts"][0]["thoughtSignature"],
"signature"
);
let mut history = vec![json!({"role":"user","content":"OK"})];
for (id, sig) in [("g1", "sig1"), ("g2", "sig2")] {
let converted=convert_response(UpstreamApi::Gemini,&json!({"responseId":id,"candidates":[{"content":{"parts":[{"text":"OK","thoughtSignature":sig}]},"finishReason":"STOP"}]}),&ToolContext::default(),"fixture").unwrap();
history.extend(converted["output"].as_array().unwrap().clone());
history.push(json!({"role":"user","content":"OK"}));
}
let converted = request(
UpstreamApi::Gemini,
json!({"model":"fixture","input":history}),
);
assert_eq!(
converted["contents"][1]["parts"][0]["thoughtSignature"],
"sig1"
);
assert_eq!(
converted["contents"][3]["parts"][0]["thoughtSignature"],
"sig2"
);
}
#[test]
fn gemini_single_tool_constraint_buffers_tools_and_rejects_parallel_execution() {
let prepared = prepared(
UpstreamApi::Gemini,
json!({"model":"gemini-2.5-pro","input":"x","parallel_tool_calls":false,"tools":[{"type":"function","name":"read"}]}),
);
let request: Value = serde_json::from_slice(&prepared.bytes).unwrap();
assert!(request["systemInstruction"]["parts"][0]["text"]
.as_str()
.unwrap()
.contains("at most one"));
let response = json!({"candidates":[{"content":{"parts":[{"functionCall":{"name":"read","args":{}}},{"functionCall":{"name":"read","args":{}}}]},"finishReason":"STOP"}]});
assert!(
convert_response(UpstreamApi::Gemini, &response, &prepared.context, "fixture").is_err()
);
let input = format!("data: {response}\n\n");
let mut stream = ResponseStream::new(
ByteReader(input.into_bytes(), 0),
UpstreamApi::Gemini,
prepared.context.clone(),
"fixture".into(),
);
let mut bytes = Vec::new();
assert!(stream.read_to_end(&mut bytes).is_err());
assert!(bytes.is_empty());
let input=format!("data: {{\"candidates\":[{{\"content\":{{\"parts\":[{{\"text\":\"planning\"}}]}}}}]}}\n\ndata: {response}\n\n");
let output = streamed(UpstreamApi::Gemini, &input, prepared.context.clone());
let ev = events(&output);
assert_eq!(ev.last().unwrap()["type"], "response.failed");
assert!(ev
.iter()
.all(|v| v["type"] != "response.output_item.done" || v["item"]["type"] != "function_call"));
let single="data: {\"candidates\":[{\"content\":{\"parts\":[{\"functionCall\":{\"name\":\"read\",\"args\":{}}}]},\"finishReason\":\"STOP\"}]}\n\n";
let output = streamed(UpstreamApi::Gemini, single, prepared.context);
assert_eq!(
events(&output).last().unwrap()["type"],
"response.completed"
);
}
#[test]
fn chat_parallel_results_keep_media_after_all_tool_responses_and_reasoning_on_call() {
let body = json!({"model":"fixture","input":[{"role":"user","content":"x"},{"type":"reasoning","summary":[{"text":"analysis"}]},{"role":"assistant","content":"Let me check"},{"type":"function_call","call_id":"a","name":"read","arguments":"{}"},{"type":"function_call","call_id":"b","name":"read","arguments":"{}"},{"type":"function_call_output","call_id":"a","output":[{"type":"input_image","image_url":"data:image/png;base64,aGVsbG8="}]},{"type":"function_call_output","call_id":"b","output":"done"}]});
let converted = request(UpstreamApi::ChatCompletions, body);
let messages = converted["messages"].as_array().unwrap();
assert_eq!(messages[1]["reasoning_content"], "analysis");
assert_eq!(messages[1]["content"][0]["text"], "Let me check");
assert_eq!(messages[1]["tool_calls"].as_array().unwrap().len(), 2);
assert_eq!(messages[2]["tool_call_id"], "a");
assert_eq!(messages[3]["tool_call_id"], "b");
assert_eq!(messages[4]["role"], "user");
}
#[test]
fn structured_output_and_unsupported_parameters_are_explicit() {
let body = json!({"model":"fixture","input":"x","text":{"format":{"type":"json_schema","name":"test","strict":true,"schema":{"type":"object","properties":{"ok":{"type":"boolean"}}}}}});
let chat = request(UpstreamApi::ChatCompletions, body.clone());
assert_eq!(chat["response_format"]["json_schema"]["strict"], true);
let anth = request(UpstreamApi::AnthropicMessages, body.clone());
assert_eq!(anth["output_config"]["format"]["schema"]["type"], "object");
let gem = request(UpstreamApi::Gemini, body);
assert_eq!(
gem["generationConfig"]["responseMimeType"],
"application/json"
);
assert_eq!(
gem["generationConfig"]["responseJsonSchema"]["type"],
"object"
);
for body in [
json!({"model":"fixture","input":"x","unknown_setting":1}),
json!({"model":"fixture","input":"x","tools":{}}),
json!({"model":"fixture","input":"x","tool_choice":"required"}),
json!({"model":"fixture","input":"x","tools":[{"type":"function","name":"read"},{"type":"function","name":"read"}]}),
] {
assert!(prepare(
UpstreamApi::ChatCompletions,
&serde_json::to_vec(&body).unwrap(),
false
)
.is_err());
}
assert!(prepare(
UpstreamApi::AnthropicMessages,
&serde_json::to_vec(
&json!({"model":"fixture","input":"x","temperature":0.2,"reasoning":{"effort":"high"}})
)
.unwrap(),
false
)
.unwrap_err()
.contains("temperature"));
let ultra = request(
UpstreamApi::AnthropicMessages,
json!({"model":"fixture","input":"x","max_output_tokens":80000,"reasoning":{"effort":"ultra"}}),
);
assert_eq!(ultra["thinking"]["budget_tokens"], 32768);
}
#[test]
fn terminal_sse_does_not_consume_late_error_or_transport_reset() {
struct ResetAfter(Vec<Vec<u8>>, usize);
impl Read for ResetAfter {
fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {
if self.1 == self.0.len() {
return Err(io::Error::new(io::ErrorKind::ConnectionReset, "late reset"));
}
let chunk = &self.0[self.1];
bytes[..chunk.len()].copy_from_slice(chunk);
self.1 += 1;
Ok(chunk.len())
}
}
let chunks = vec![
b"data: {\"choices\":[{\"delta\":{\"content\":\"hello\"}}]}\n\n".to_vec(),
b"data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n"
.to_vec(),
b"event: error\ndata: {\"error\":{\"message\":\"late\"}}\n\n".to_vec(),
];
let mut stream = ResponseStream::new(
ResetAfter(chunks, 0),
UpstreamApi::ChatCompletions,
ToolContext::default(),
"fixture".into(),
);
let mut output = String::new();
stream.read_to_string(&mut output).unwrap();
let ev = events(&output);
assert_eq!(
ev.iter()
.filter(|v| v["type"] == "response.completed")
.count(),
1
);
assert!(ev.iter().all(|v| v["type"] != "response.failed"));
}
#[test]
fn json_stream_fallback_has_empty_added_items_before_deltas() {
let input = r#"{"id":"chat","choices":[{"message":{"content":"hello","tool_calls":[{"id":"a","function":{"name":"read","arguments":"{\"x\":1}"}}]},"finish_reason":"tool_calls"}]}"#;
let output = streamed(UpstreamApi::ChatCompletions, input, ToolContext::default());
let ev = events(&output);
let added = ev
.iter()
.filter(|v| v["type"] == "response.output_item.added")
.collect::<Vec<_>>();
assert_eq!(added[0]["item"]["status"], "in_progress");
assert_eq!(added[0]["item"]["content"], json!([]));
assert_eq!(added[1]["item"]["arguments"], "");
let part = ev
.iter()
.find(|v| v["type"] == "response.content_part.added")
.unwrap();
assert_eq!(part["part"]["text"], "");
}
+492 -26
View File
@@ -4,6 +4,7 @@
use super::circuit_breaker::{CircuitBreaker, CircuitBreakerConfig};
use super::config::RoutingTuning;
use super::native_official::{OfficialRequestAuth, OfficialRouteSpec};
use super::protocol::{self, UpstreamApi};
use crate::error::{CodexxError, Result};
use serde::Serialize;
use serde_json::{json, Value};
@@ -35,6 +36,7 @@ pub(crate) struct ProxyRoute {
pub(crate) headers: Vec<(String, String)>,
pub(crate) models: HashSet<String>,
pub(crate) official: Option<OfficialRouteSpec>,
pub(crate) protocol: UpstreamApi,
}
#[derive(Debug, Clone, Default, Serialize)]
@@ -435,6 +437,7 @@ fn reject_self_routes(routes: &[ProxyRoute], address: IpAddr, port: u16) -> Resu
fn same_transport(left: &ProxyRoute, right: &ProxyRoute) -> bool {
left.base_url == right.base_url
&& left.protocol == right.protocol
&& left.api_key == right.api_key
&& left.headers == right.headers
&& left.models == right.models
@@ -1026,7 +1029,64 @@ fn upstream_url(route: &ProxyRoute, data: &RequestData) -> Option<String> {
let base_path = url.path().trim_end_matches('/');
// Saved base_url is the API prefix, matching Codex's own /responses join.
// Do not invent /v1 for vendor endpoints that deliberately omit it.
url.set_path(&format!("{base_path}/{}", data.suffix));
let path = match route.protocol {
UpstreamApi::Responses => format!("{base_path}/{}", data.suffix),
UpstreamApi::ChatCompletions => {
if base_path.ends_with("/chat/completions") {
base_path.to_owned()
} else {
format!(
"{}/chat/completions",
if base_path.is_empty() {
"/v1"
} else {
base_path
}
)
}
}
UpstreamApi::AnthropicMessages => {
if base_path.ends_with("/messages") {
base_path.to_owned()
} else if base_path.ends_with("/v1") {
format!("{base_path}/messages")
} else {
format!("{base_path}/v1/messages")
}
}
UpstreamApi::Gemini => {
let model = data
.model
.as_deref()?
.strip_prefix("models/")
.unwrap_or(data.model.as_deref()?);
if model.is_empty() || model.contains('/') || model.contains(':') {
return None;
}
let model =
percent_encoding::utf8_percent_encode(model, percent_encoding::NON_ALPHANUMERIC)
.to_string();
let method = if data.streaming {
"streamGenerateContent"
} else {
"generateContent"
};
if base_path.contains("/models/") {
let (prefix, _) = base_path.rsplit_once("/models/")?;
format!("{prefix}/models/{model}:{method}")
} else {
format!(
"{}/models/{model}:{method}",
if base_path.is_empty() {
"/v1beta"
} else {
base_path
}
)
}
}
};
url.set_path(&path);
let query = match (url.query(), data.query.as_deref()) {
(Some(base), Some(request)) if !base.is_empty() && !request.is_empty() => {
Some(format!("{base}&{request}"))
@@ -1036,6 +1096,9 @@ fn upstream_url(route: &ProxyRoute, data: &RequestData) -> Option<String> {
(None, None) => None,
};
url.set_query(query.as_deref());
if route.protocol == UpstreamApi::Gemini && data.streaming {
url.query_pairs_mut().append_pair("alt", "sse");
}
Some(url.into())
}
@@ -1108,6 +1171,7 @@ struct UpstreamResponse {
headers: reqwest::header::HeaderMap,
deadline: Option<Instant>,
next_timeout: Option<Duration>,
idle_timeout: Option<Duration>,
pending: Vec<u8>,
offset: usize,
}
@@ -1123,6 +1187,7 @@ impl Read for UpstreamResponse {
let count = bytes.len().min(self.pending.len() - self.offset);
bytes[..count].copy_from_slice(&self.pending[self.offset..self.offset + count]);
self.offset += count;
self.next_timeout = self.idle_timeout;
return Ok(count);
}
let deadline = match (self.deadline, idle_deadline) {
@@ -1167,6 +1232,7 @@ fn request_upstream(
data: &RequestData,
timing: RequestTimeouts,
official: Option<&OfficialRequestAuth>,
body: &[u8],
) -> std::result::Result<UpstreamResponse, ()> {
let mut effective = route.clone();
if let Some(auth) = official {
@@ -1216,11 +1282,61 @@ fn request_upstream(
reqwest::header::HeaderValue::from_str(account).map_err(|_| ())?,
);
}
} else if let Some(key) = route.api_key.as_deref().filter(|key| !key.is_empty()) {
let mut value =
reqwest::header::HeaderValue::from_str(&format!("Bearer {key}")).map_err(|_| ())?;
value.set_sensitive(true);
headers.insert(reqwest::header::AUTHORIZATION, value);
} else {
// Supplier credentials belong to its route snapshot. Neither local
// router authentication nor another protocol's default key is reused.
for name in [
"authorization",
"x-api-key",
"x-goog-api-key",
"chatgpt-account-id",
] {
headers.remove(name);
}
if route.protocol == UpstreamApi::AnthropicMessages {
headers.insert(
"anthropic-version",
reqwest::header::HeaderValue::from_static("2023-06-01"),
);
}
let custom_auth = route.headers.iter().any(|(name, _)| {
matches!(
name.to_ascii_lowercase().as_str(),
"authorization" | "x-api-key" | "x-goog-api-key"
)
});
if let Some(key) = route
.api_key
.as_deref()
.filter(|key| !key.is_empty() && !custom_auth)
{
let (name, text) = match route.protocol {
UpstreamApi::Responses | UpstreamApi::ChatCompletions => {
("authorization", format!("Bearer {key}"))
}
UpstreamApi::AnthropicMessages => ("x-api-key", key.to_owned()),
UpstreamApi::Gemini => ("x-goog-api-key", key.to_owned()),
};
let mut value = reqwest::header::HeaderValue::from_str(&text).map_err(|_| ())?;
value.set_sensitive(true);
headers.insert(
reqwest::header::HeaderName::from_bytes(name.as_bytes()).map_err(|_| ())?,
value,
);
}
// Explicit supplier headers override defaults. Client headers are
// restricted independently and cannot override supplier credentials.
for (name, value) in &route.headers {
if !forbidden_upstream_header(name)
&& !name.eq_ignore_ascii_case(super::config::ROUTE_TOKEN_HEADER)
&& !name.eq_ignore_ascii_case(super::config::ROUTE_GENERATION_HEADER)
{
headers.insert(
reqwest::header::HeaderName::from_bytes(name.as_bytes()).map_err(|_| ())?,
reqwest::header::HeaderValue::from_str(value).map_err(|_| ())?,
);
}
}
}
headers.insert(
reqwest::header::CONTENT_TYPE,
@@ -1241,7 +1357,7 @@ fn request_upstream(
let request = if data.model.is_none() {
client.get(&url)
} else {
client.post(&url).body(data.bytes.clone())
client.post(&url).body(body.to_vec())
}
.headers(headers);
let started = Instant::now();
@@ -1275,6 +1391,7 @@ fn request_upstream(
} else {
None
},
idle_timeout: if data.streaming { timing.idle } else { None },
pending: Vec::new(),
offset: 0,
})
@@ -1328,6 +1445,82 @@ fn buffered_response(mut response: UpstreamResponse) -> io::Result<BufferedRespo
})
}
fn bridge_buffered(
mut response: BufferedResponse,
route: &ProxyRoute,
prepared: &protocol::PreparedRequest,
) -> io::Result<BufferedResponse> {
if route.protocol == UpstreamApi::Responses {
return Ok(response);
}
let body: Value = serde_json::from_slice(&response.bytes)
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "上游响应不是有效的 JSON"))?;
if response.status >= 300 {
let message = protocol::error_message(&body).unwrap_or_else(|| body.to_string());
response.bytes = serde_json::to_vec(
&json!({"error":{"type":"upstream_error","code":"upstream_error","message":message}}),
)
.unwrap_or_default();
} else {
let body =
protocol::convert_response(route.protocol, &body, &prepared.context, &prepared.model)
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
response.bytes = serde_json::to_vec(&body).map_err(io::Error::other)?;
}
response
.headers
.retain(|(name, _)| !name.eq_ignore_ascii_case("content-type"));
response
.headers
.push(("content-type".into(), "application/json".into()));
Ok(response)
}
fn bridge_nonstream_sse(
response: UpstreamResponse,
route: &ProxyRoute,
prepared: &protocol::PreparedRequest,
) -> io::Result<BufferedResponse> {
let mut headers = downstream_headers(&response);
let mut reader = protocol::ResponseStream::new(
response,
route.protocol,
prepared.context.clone(),
prepared.model.clone(),
);
let bytes = read_bounded(&mut reader, MAX_BODY_BYTES)?;
let text = std::str::from_utf8(&bytes)
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "转换后的 SSE 不是 UTF-8"))?;
let event = text
.lines()
.rev()
.filter_map(|line| line.strip_prefix("data: "))
.filter_map(|data| serde_json::from_str::<Value>(data).ok())
.find(|v| {
matches!(
v.get("type").and_then(Value::as_str),
Some("response.completed" | "response.incomplete" | "response.failed")
)
})
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "上游 SSE 缺少完成事件"))?;
if event["type"] == "response.failed" {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
event
.pointer("/response/error/message")
.and_then(Value::as_str)
.unwrap_or("上游 SSE 失败"),
));
}
headers.retain(|(name, _)| !name.eq_ignore_ascii_case("content-type"));
headers.push(("content-type".into(), "application/json".into()));
Ok(BufferedResponse {
status: 200,
headers,
bytes: serde_json::to_vec(&event["response"]).map_err(io::Error::other)?,
})
}
struct Permit {
breaker: Option<Arc<CircuitBreaker>>,
half_open: bool,
@@ -1520,6 +1713,17 @@ fn handle_request(mut request: Request, shared: &Arc<Shared>) {
}
return;
}
if data.model.is_none()
&& config
.routes
.first()
.is_some_and(|route| route.protocol.requires_routing())
{
let mut models: Vec<_> = config.routes[0].models.iter().cloned().collect();
models.sort();
respond_buffered(request,BufferedResponse {status:200,headers:vec![("content-type".into(),"application/json".into())],bytes:serde_json::to_vec(&json!({"object":"list","data":models.into_iter().map(|id|json!({"id":id,"object":"model","owned_by":"supplier"})).collect::<Vec<_>>()})).unwrap_or_default()});
return;
}
let automatic = config.options.auto_failover_enabled && !official;
let max_attempts = if automatic {
config.options.tuning.max_retries.saturating_add(1) as usize
@@ -1529,6 +1733,7 @@ fn handle_request(mut request: Request, shared: &Arc<Shared>) {
let timing = timeouts(shared, &config.options, official);
let mut attempted = 0;
let mut last_response = None;
let mut last_bridge_error = None;
for (index, route) in config.routes.iter().enumerate() {
if shared.stopped.load(Ordering::Acquire) {
fail_request(shared);
@@ -1541,11 +1746,37 @@ fn handle_request(mut request: Request, shared: &Arc<Shared>) {
if index > 0 && (!automatic || data.primary_only) {
break;
}
let prepared = match if data.model.is_none() {
Ok(protocol::PreparedRequest {
bytes: data.bytes.clone(),
context: protocol::ToolContext::default(),
model: String::new(),
})
} else {
protocol::prepare(
route.protocol,
&data.bytes,
data.suffix == "responses/compact",
)
} {
Ok(prepared) => prepared,
Err(message) => {
fail_request(shared);
respond_error(request, 400, &message);
return;
}
};
let Some(mut permit) = Permit::acquire(&breakers, route, automatic) else {
continue;
};
attempted += 1;
let mut response = match request_upstream(route, &data, timing, official_auth.as_ref()) {
let response = match request_upstream(
route,
&data,
timing,
official_auth.as_ref(),
&prepared.bytes,
) {
Ok(response) => response,
Err(()) => {
set_attempt_failure(
@@ -1572,7 +1803,7 @@ fn handle_request(mut request: Request, shared: &Arc<Shared>) {
Some(status),
"供应商暂时不可用",
);
last_response = Some(response);
last_response = Some((response, route.clone(), prepared));
continue;
}
if (300..=399).contains(&status) {
@@ -1595,7 +1826,9 @@ fn handle_request(mut request: Request, shared: &Arc<Shared>) {
if let Some(health) = lock(&shared.statistics).health.get_mut(&route.id) {
health.last_status = Some(status);
}
match buffered_response(response) {
match buffered_response(response)
.and_then(|response| bridge_buffered(response, route, &prepared))
{
Ok(response) => respond_buffered(request, response),
Err(_) => respond_error(request, 502, "供应商响应无法读取"),
};
@@ -1614,11 +1847,49 @@ fn handle_request(mut request: Request, shared: &Arc<Shared>) {
.trim()
.eq_ignore_ascii_case("text/event-stream")
});
if !data.streaming && streaming && route.protocol.requires_routing() {
match bridge_nonstream_sse(response, route, &prepared) {
Ok(response) => {
set_success(shared, &config, route, &mut permit, index, status);
respond_buffered(request, response);
return;
}
Err(error) => {
last_bridge_error = Some(error.to_string());
set_attempt_failure(
shared,
&config,
route,
&mut permit,
Some(status),
"供应商 SSE 返回无法转换为完整 JSON",
);
continue;
}
}
}
if streaming {
let headers = downstream_headers(&response);
let mut headers = downstream_headers(&response);
if route.protocol.requires_routing() {
headers.retain(|(name, _)| !name.eq_ignore_ascii_case("content-type"));
headers.push(("content-type".into(), "text/event-stream".into()));
}
let mut bridge_failure = None;
let mut reader: Box<dyn Read + Send + Sync> = if route.protocol.requires_routing() {
let converted = protocol::ResponseStream::new(
response,
route.protocol,
prepared.context,
prepared.model,
);
bridge_failure = Some(converted.failure_flag());
Box::new(converted)
} else {
Box::new(response)
};
let mut first = [0; 16 * 1024];
let count = match response.read(&mut first) {
Ok(0) | Err(_) => {
let count = match reader.read(&mut first) {
Ok(0) => {
set_attempt_failure(
shared,
&config,
@@ -1632,20 +1903,31 @@ fn handle_request(mut request: Request, shared: &Arc<Shared>) {
}
continue;
}
Err(error) => {
if route.protocol.requires_routing() {
last_bridge_error = Some(error.to_string());
}
set_attempt_failure(
shared,
&config,
route,
&mut permit,
Some(status),
"供应商首包读取或协议转换失败",
);
if official {
break;
}
continue;
}
Ok(count) => count,
};
response.next_timeout = timing.idle;
set_success(shared, &config, route, &mut permit, index, status);
if matches!(
stream_response(
request,
status,
headers,
&first[..count],
Box::new(response)
),
stream_response(request, status, headers, &first[..count], reader),
StreamOutcome::UpstreamFailure
) {
) || bridge_failure.is_some_and(|flag| flag.load(Ordering::Acquire))
{
// Like CC Switch, after the committed first chunk this is a
// downstream stream failure, never a fresh provider attempt.
let mut stats = lock(&shared.statistics);
@@ -1653,13 +1935,18 @@ fn handle_request(mut request: Request, shared: &Arc<Shared>) {
}
return;
}
match buffered_response(response) {
match buffered_response(response)
.and_then(|response| bridge_buffered(response, route, &prepared))
{
Ok(response) => {
set_success(shared, &config, route, &mut permit, index, status);
respond_buffered(request, response);
return;
}
Err(_) => {
Err(error) => {
if route.protocol.requires_routing() {
last_bridge_error = Some(error.to_string());
}
set_attempt_failure(
shared,
&config,
@@ -1675,11 +1962,15 @@ fn handle_request(mut request: Request, shared: &Arc<Shared>) {
}
}
fail_request(shared);
if let Some(response) = last_response {
match buffered_response(response) {
if let Some((response, route, prepared)) = last_response {
match buffered_response(response)
.and_then(|response| bridge_buffered(response, &route, &prepared))
{
Ok(response) => respond_buffered(request, response),
Err(_) => respond_error(request, 502, "暂时无法连接可用供应商,请稍后重试"),
}
} else if let Some(error) = last_bridge_error {
respond_error(request, 502, &format!("上游协议转换失败:{error}"));
} else if attempted > 0 {
respond_error(request, 502, "暂时无法连接可用供应商,请稍后重试");
} else {
@@ -1928,6 +2219,7 @@ mod tests {
headers: Vec::new(),
models: HashSet::from([MODEL.to_string()]),
official: None,
protocol: UpstreamApi::Responses,
}
}
@@ -1935,6 +2227,180 @@ mod tests {
ProxyHandle::start_with_timeout(0, TOKEN.into(), routes, Duration::from_secs(2)).unwrap()
}
#[test]
fn protocol_bridges_use_correct_endpoints_auth_and_codex_json() {
for (api, reply) in [
(
UpstreamApi::ChatCompletions,
r#"{"id":"chat","model":"fixture-model","choices":[{"message":{"content":"chat reply"},"finish_reason":"stop"}],"usage":{"prompt_tokens":2,"completion_tokens":3}}"#,
),
(
UpstreamApi::AnthropicMessages,
r#"{"id":"anth","model":"fixture-model","type":"message","content":[{"type":"text","text":"anthropic reply"}],"stop_reason":"end_turn","usage":{"input_tokens":2,"output_tokens":3}}"#,
),
(
UpstreamApi::Gemini,
r#"{"responseId":"gem","candidates":[{"content":{"parts":[{"text":"gemini reply"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":2,"candidatesTokenCount":3}}"#,
),
] {
let upstream = Upstream::json(200, reply);
let mut supplier = route("converted", &upstream, "fixture-secret");
supplier.protocol = api;
let proxy = start(vec![supplier]);
let body: Value =
serde_json::from_str(&request(&proxy, &payload()).into_string().unwrap()).unwrap();
assert_eq!(body["object"], "response");
assert_eq!(body["status"], "completed");
assert_eq!(body["usage"]["total_tokens"], 5);
let calls = upstream.observed();
let seen = &calls[0];
let converted: Value = serde_json::from_slice(&seen.body).unwrap();
match api {
UpstreamApi::ChatCompletions => {
assert_eq!(seen.target, "/v1/chat/completions");
assert_eq!(seen.headers["authorization"], "Bearer fixture-secret");
assert_eq!(converted["messages"][0]["content"], "fixture prompt");
}
UpstreamApi::AnthropicMessages => {
assert_eq!(seen.target, "/v1/messages");
assert_eq!(seen.headers["x-api-key"], "fixture-secret");
assert_eq!(seen.headers["anthropic-version"], "2023-06-01");
assert!(!seen.headers.contains_key("authorization"));
assert_eq!(converted["max_tokens"], 8192);
}
UpstreamApi::Gemini => {
assert!(seen.target.starts_with("/v1beta/models/fixture"));
assert!(seen.target.ends_with(":generateContent"));
assert_eq!(seen.headers["x-goog-api-key"], "fixture-secret");
assert!(!seen.headers.contains_key("authorization"));
assert_eq!(converted["contents"][0]["role"], "user");
}
_ => unreachable!(),
}
assert!(!seen.headers.values().any(|v| v.contains(TOKEN)));
let models = client()
.get(&format!("http://127.0.0.1:{}/v1/models", proxy.port()))
.set("Authorization", &format!("Bearer {TOKEN}"))
.call()
.unwrap()
.into_string()
.unwrap();
let models: Value = serde_json::from_str(&models).unwrap();
assert_eq!(models["object"], "list");
assert_eq!(models["data"][0]["id"], MODEL);
assert_eq!(upstream.observed().len(), 1);
proxy.shutdown();
}
}
#[test]
fn converted_routes_reject_remote_state_and_compaction_without_upstream_request() {
let upstream = Upstream::json(200, "{}");
let mut supplier = route("converted", &upstream, "fixture-secret");
supplier.protocol = UpstreamApi::Gemini;
let proxy = start(vec![supplier]);
let error = client()
.post(&format!("http://127.0.0.1:{}/v1/responses", proxy.port()))
.set("Authorization", &format!("Bearer {TOKEN}"))
.set("Content-Type", "application/json")
.send_string(
&json!({"model":MODEL,"input":"x","previous_response_id":"opaque-server-state"})
.to_string(),
)
.unwrap_err();
assert!(matches!(error, ureq::Error::Status(400, _)));
let error = client()
.post(&format!(
"http://127.0.0.1:{}/v1/responses/compact",
proxy.port()
))
.set("Authorization", &format!("Bearer {TOKEN}"))
.set("Content-Type", "application/json")
.send_string(&json!({"model":MODEL,"input":"x"}).to_string())
.unwrap_err();
assert!(matches!(error, ureq::Error::Status(400, _)));
assert!(upstream.observed().is_empty());
proxy.shutdown();
}
#[test]
fn early_bridge_sse_error_can_fail_over_but_committed_output_is_not_replayed() {
let early = Upstream::serve(|stream| {
let data = "event: error\ndata: {\"error\":{\"message\":\"fixture outage\"}}\n\n";
write!(stream,"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{data}",data.len()).unwrap();
});
let backup = Upstream::json(
200,
r#"{"id":"backup","choices":[{"message":{"content":"recovered"},"finish_reason":"stop"}]}"#,
);
let mut first = route("early", &early, "one");
first.protocol = UpstreamApi::ChatCompletions;
let mut second = route("backup", &backup, "two");
second.protocol = UpstreamApi::ChatCompletions;
let proxy = start(vec![first, second]);
let result = request(&proxy, &stream_payload()).into_string().unwrap();
assert!(result.contains("response.completed"));
assert!(result.contains("recovered"));
assert_eq!(backup.observed().len(), 1);
proxy.shutdown();
let (release, await_release) = mpsc::channel();
let late = Upstream::serve(move |stream| {
let first="data: {\"id\":\"partial\",\"choices\":[{\"delta\":{\"content\":\"committed\"}}]}\n\n";
write!(stream,"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n{:x}\r\n{first}\r\n",first.len()).unwrap();
stream.flush().unwrap();
await_release.recv_timeout(Duration::from_secs(3)).unwrap();
let error = "event: error\ndata: {\"error\":{\"message\":\"late outage\"}}\n\n";
write!(stream, "{:x}\r\n{error}\r\n0\r\n\r\n", error.len()).unwrap();
});
let untouched = Upstream::json(200, "{}");
let mut first = route("late", &late, "one");
first.protocol = UpstreamApi::ChatCompletions;
let proxy = start(vec![first, route("untouched", &untouched, "two")]);
let result = request(&proxy, &stream_payload());
release.send(()).unwrap();
let result = result.into_string().unwrap();
// The client can receive EOF before the worker publishes final statistics.
eventually(|| proxy.snapshot().in_flight == 0);
assert!(result.contains("response.failed"));
assert!(!result.contains("response.completed"));
assert!(untouched.observed().is_empty());
assert!(proxy.snapshot().last_error.is_some());
proxy.shutdown();
}
#[test]
fn gemini_stream_endpoint_converts_sse_and_preserves_function_call() {
let upstream = Upstream::serve(|stream| {
let events = [
json!({"responseId":"g","candidates":[{"content":{"parts":[{"text":"中文🙂"}]}}]}),
json!({"candidates":[{"content":{"parts":[{"functionCall":{"name":"read","args":{"path":"x"}},"thoughtSignature":"fixture-signature"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":5,"candidatesTokenCount":2}}),
];
let body = events
.iter()
.map(|event| format!("data: {event}\r\n\r\n"))
.collect::<String>();
write!(stream,"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n").unwrap();
for chunk in body.as_bytes().chunks(1) {
write!(stream, "1\r\n").unwrap();
stream.write_all(chunk).unwrap();
stream.write_all(b"\r\n").unwrap();
}
stream.write_all(b"0\r\n\r\n").unwrap();
});
let mut supplier = route("gemini", &upstream, "secret");
supplier.protocol = UpstreamApi::Gemini;
let proxy = start(vec![supplier]);
let bytes=serde_json::to_vec(&json!({"model":MODEL,"input":"x","stream":true,"tools":[{"type":"function","name":"read"}]})).unwrap();
let output = request(&proxy, &bytes).into_string().unwrap();
assert!(output.contains("response.completed"));
assert!(output.contains("中文🙂"));
assert!(output.contains("function_call"));
assert!(output.contains("encrypted_content"));
let seen = &upstream.observed()[0];
assert!(seen.target.contains(":streamGenerateContent?alt=sse"));
proxy.shutdown();
}
fn client() -> ureq::Agent {
ureq::AgentBuilder::new()
.try_proxy_from_env(false)
@@ -27,6 +27,7 @@ impl Fixture {
api_key: Some(format!("fixture-provider-secret-{index}")),
toml_config: None,
wire_api: "responses".into(),
upstream_api: None,
requires_openai_auth: false,
model_mappings: vec![],
};
@@ -373,6 +374,458 @@ fn failed_manual_switch_reattaches_original_route() {
assert_eq!(status.primary.unwrap().id, fixture.providers[0].id);
}
#[test]
fn converted_provider_requires_live_takeover_and_shutdown_preserves_bridge() {
let _guard = crate::app_db::test_db_guard();
let mut fixture = Fixture::new();
fixture.providers[1].upstream_api = Some("gemini".into());
fixture.providers[1] =
crate::providers::save_provider_inner(fixture.providers[1].clone()).unwrap();
assert!(ensure_conversion_route(fixture.scope(), &fixture.providers[1]).is_err());
fixture.enable();
ensure_conversion_route(fixture.scope(), &fixture.providers[1]).unwrap();
with_provider_change(fixture.scope(), || {
crate::providers::activate_saved_provider_inner(
fixture.scope(),
fixture.providers[1].id.clone(),
)
})
.unwrap();
let before = FileCheckpoint::capture(&fixture.dir).unwrap();
let mut disabled = get_status(fixture.scope()).unwrap().settings;
disabled.router_enabled = false;
assert!(save_settings(fixture.scope(), disabled)
.err()
.unwrap()
.to_string()
.contains("协议转换"));
shutdown_all().unwrap();
let after = FileCheckpoint::capture(&fixture.dir).unwrap();
assert_eq!(before.config, after.config);
assert_eq!(before.auth, after.auth);
assert_eq!(before.selected, after.selected);
assert!(!get_status(fixture.scope()).unwrap().running);
assert!(fixture.text().contains("127.0.0.1"));
resume_after_failed_update().unwrap();
assert!(get_status(fixture.scope()).unwrap().takeover_active);
with_provider_change(fixture.scope(), || {
crate::providers::activate_saved_provider_inner(
fixture.scope(),
fixture.providers[0].id.clone(),
)
})
.unwrap();
stop(&fixture);
assert!(!get_status(fixture.scope()).unwrap().running);
}
#[test]
fn shutdown_preflight_is_read_only_for_native_and_converted_routes() {
let _guard = crate::app_db::test_db_guard();
let mut fixture = Fixture::new();
fixture.enable();
let before = FileCheckpoint::capture(&fixture.dir).unwrap();
assert!(!SHUTTING_DOWN.load(Ordering::Acquire));
ensure_shutdown_allowed().unwrap();
assert!(!SHUTTING_DOWN.load(Ordering::Acquire));
assert_eq!(
before.config,
FileCheckpoint::capture(&fixture.dir).unwrap().config
);
fixture.providers[1].upstream_api = Some("gemini".into());
fixture.providers[1] =
crate::providers::save_provider_inner(fixture.providers[1].clone()).unwrap();
with_provider_change(fixture.scope(), || {
crate::providers::activate_saved_provider_inner(
fixture.scope(),
fixture.providers[1].id.clone(),
)
})
.unwrap();
let before = FileCheckpoint::capture(&fixture.dir).unwrap();
let (routes, revision, instance) = {
let runtimes = lock_manager().unwrap();
let runtime = runtimes.get(&fixture.dir).unwrap();
(
runtime.routes.clone(),
runtime.proxy.revision(),
runtime.instance_id,
)
};
for flag in [false, true] {
SHUTTING_DOWN.store(flag, Ordering::Release);
ensure_shutdown_allowed().unwrap();
assert_eq!(SHUTTING_DOWN.load(Ordering::Acquire), flag);
let after = FileCheckpoint::capture(&fixture.dir).unwrap();
assert_eq!(before.config, after.config);
assert_eq!(before.auth, after.auth);
assert_eq!(before.selected, after.selected);
let runtimes = lock_manager().unwrap();
let runtime = runtimes.get(&fixture.dir).unwrap();
assert!(runtime.routes == routes);
assert_eq!(runtime.proxy.revision(), revision);
assert_eq!(runtime.instance_id, instance);
assert!(runtime.journal.is_some());
}
SHUTTING_DOWN.store(false, Ordering::Release);
}
fn converted_fixture(api: &str) -> Fixture {
let mut fixture = Fixture::new();
fixture.providers[1].upstream_api = Some(api.into());
fixture.providers[1] =
crate::providers::save_provider_inner(fixture.providers[1].clone()).unwrap();
let mut settings = fixture.settings();
settings.auto_failover_enabled = false;
save_settings(fixture.scope(), settings).unwrap();
with_provider_change(fixture.scope(), || {
crate::providers::activate_saved_provider_inner(
fixture.scope(),
fixture.providers[1].id.clone(),
)
})
.unwrap();
fixture
}
#[test]
fn converted_normal_exit_restarts_the_owned_bridge_without_direct_restore() {
let _guard = crate::app_db::test_db_guard();
let fixture = converted_fixture("gemini");
let before = FileCheckpoint::capture(&fixture.dir).unwrap();
let settings = get_status(fixture.scope()).unwrap().settings;
ensure_shutdown_allowed().unwrap();
shutdown_all().unwrap();
let after = FileCheckpoint::capture(&fixture.dir).unwrap();
assert_eq!(before.config, after.config);
assert_eq!(before.auth, after.auth);
assert_eq!(before.selected, after.selected);
assert!(!lock_manager().unwrap().contains_key(&fixture.dir));
assert!(SHUTTING_DOWN.load(Ordering::Acquire));
let called = std::cell::Cell::new(false);
assert!(with_provider_change(fixture.scope(), || {
called.set(true);
Ok(())
})
.is_err());
assert!(!called.get());
SHUTTING_DOWN.store(false, Ordering::Release);
initialize().unwrap();
let status = get_status(fixture.scope()).unwrap();
assert!(status.running && status.takeover_active);
assert_eq!(status.settings, settings);
let runtimes = lock_manager().unwrap();
let runtime = runtimes.get(&fixture.dir).unwrap();
assert_eq!(runtime.routes[0].protocol, UpstreamApi::Gemini);
assert!(runtime.journal.as_ref().unwrap().requires_conversion);
}
#[test]
fn update_handoff_freezes_mutations_without_stopping_native_or_converted_listener() {
let _guard = crate::app_db::test_db_guard();
for conversion in [false, true] {
let fixture = if conversion {
converted_fixture("anthropic_messages")
} else {
let fixture = Fixture::new();
fixture.enable();
fixture
};
let before = FileCheckpoint::capture(&fixture.dir).unwrap();
let (revision, instance) = {
let runtimes = lock_manager().unwrap();
let runtime = runtimes.get(&fixture.dir).unwrap();
(runtime.proxy.revision(), runtime.instance_id)
};
begin_update_handoff().unwrap();
assert!(SHUTTING_DOWN.load(Ordering::Acquire));
let called = std::cell::Cell::new(false);
assert!(with_provider_change(fixture.scope(), || {
called.set(true);
fs::write(crate::config_path(&fixture.dir), "changed").unwrap();
Ok(())
})
.is_err());
assert!(!called.get());
assert!(save_settings(fixture.scope(), fixture.settings()).is_err());
assert!(refresh_saved_routes().is_err());
let after = FileCheckpoint::capture(&fixture.dir).unwrap();
assert_eq!(before.config, after.config);
assert_eq!(before.auth, after.auth);
assert_eq!(before.selected, after.selected);
{
let runtimes = lock_manager().unwrap();
let runtime = runtimes.get(&fixture.dir).unwrap();
assert_eq!(runtime.proxy.revision(), revision);
assert_eq!(runtime.instance_id, instance);
assert!(runtime.journal.is_some());
}
resume_after_failed_update().unwrap();
assert!(!SHUTTING_DOWN.load(Ordering::Acquire));
{
let runtimes = lock_manager().unwrap();
let runtime = runtimes.get(&fixture.dir).unwrap();
assert_eq!(runtime.proxy.revision(), revision);
assert_eq!(runtime.instance_id, instance);
}
with_provider_change(fixture.scope(), || Ok(())).unwrap();
assert!(get_status(fixture.scope()).unwrap().takeover_active);
}
}
#[test]
fn converted_stopped_update_handoff_resumes_the_same_protocol_and_settings() {
let _guard = crate::app_db::test_db_guard();
let fixture = converted_fixture("anthropic_messages");
let before = FileCheckpoint::capture(&fixture.dir).unwrap();
let settings = get_status(fixture.scope()).unwrap().settings;
shutdown_all().unwrap();
assert!(!lock_manager().unwrap().contains_key(&fixture.dir));
assert_eq!(
before.config,
FileCheckpoint::capture(&fixture.dir).unwrap().config
);
resume_after_failed_update().unwrap();
assert!(!SHUTTING_DOWN.load(Ordering::Acquire));
let status = get_status(fixture.scope()).unwrap();
assert!(status.running && status.takeover_active);
assert_eq!(status.settings, settings);
assert_eq!(
lock_manager().unwrap().get(&fixture.dir).unwrap().routes[0].protocol,
UpstreamApi::AnthropicMessages
);
assert_eq!(
before.auth,
FileCheckpoint::capture(&fixture.dir).unwrap().auth
);
}
#[test]
fn converted_shutdown_keeps_external_selection_and_does_not_reattach_it() {
let _guard = crate::app_db::test_db_guard();
for detach_before_shutdown in [false, true] {
let fixture = converted_fixture("gemini");
let journal = lock_manager()
.unwrap()
.get(&fixture.dir)
.unwrap()
.journal
.clone()
.unwrap();
let auth = fs::read(fixture.dir.join("auth.json")).unwrap();
if !detach_before_shutdown {
// Freeze the watcher before the external edit so this case covers
// shutdown seeing the converted journal itself, deterministically.
begin_update_handoff().unwrap();
}
let mut doc = parsed(&fixture);
doc["model_provider"] = value("external");
let mut table = Table::new();
table["name"] = value("External fixture");
table["base_url"] = value("https://external-fixture.example.test/v1");
table["wire_api"] = value("responses");
table["requires_openai_auth"] = value(false);
replace_table(&mut doc, "external", table).unwrap();
let external = doc.to_string();
let detached_doc = restored_document(&doc, &journal).unwrap();
// Independently verify that the projection only changes our inactive
// provider table, not the external selection/table or any user config.
let mut unmanaged_before = doc.clone();
let mut unmanaged_after = detached_doc.clone();
for document in [&mut unmanaged_before, &mut unmanaged_after] {
document
.get_mut("model_providers")
.and_then(Item::as_table_mut)
.unwrap()
.remove(&journal.provider_key);
}
assert_eq!(unmanaged_after.to_string(), unmanaged_before.to_string());
let detached = detached_doc.to_string();
fs::write(crate::config_path(&fixture.dir), &external).unwrap();
let expected = if detach_before_shutdown {
// The production watcher is allowed to clean its inactive owned
// overlay after an external selection. Complete that same path
// synchronously rather than racing its three-second scan.
refresh_saved_routes().unwrap();
assert_eq!(fixture.text(), detached);
assert!(lock_manager()
.unwrap()
.get(&fixture.dir)
.unwrap()
.journal
.is_none());
detached
} else {
external
};
shutdown_all().unwrap();
assert_eq!(fixture.text(), expected);
assert_eq!(
parsed(&fixture)["model_provider"].as_str(),
Some("external")
);
assert_eq!(fs::read(fixture.dir.join("auth.json")).unwrap(), auth);
assert!(!load_record(&fixture.dir).unwrap().settings.takeover_enabled);
SHUTTING_DOWN.store(false, Ordering::Release);
initialize().unwrap();
assert_eq!(fixture.text(), expected);
assert_eq!(fs::read(fixture.dir.join("auth.json")).unwrap(), auth);
let runtime = lock_manager().unwrap().remove(&fixture.dir).unwrap();
assert!(runtime.journal.is_none());
runtime.proxy.shutdown();
}
}
#[test]
fn converted_shutdown_failure_keeps_files_listener_and_mutation_gate_open() {
let _guard = crate::app_db::test_db_guard();
let fixture = converted_fixture("gemini");
let before = FileCheckpoint::capture(&fixture.dir).unwrap();
let record = load_record(&fixture.dir).unwrap();
let mut missing = record.clone();
missing.journals.clear();
save_record(&fixture.dir, &missing).unwrap();
assert!(ensure_shutdown_allowed().is_err());
assert!(begin_update_handoff().is_err());
assert!(!SHUTTING_DOWN.load(Ordering::Acquire));
assert!(shutdown_all().is_err());
assert!(!SHUTTING_DOWN.load(Ordering::Acquire));
assert!(lock_manager().unwrap().contains_key(&fixture.dir));
assert_eq!(
before.config,
FileCheckpoint::capture(&fixture.dir).unwrap().config
);
save_record(&fixture.dir, &record).unwrap();
let mut stale_settings = record.clone();
stale_settings.settings.takeover_enabled = false;
save_record(&fixture.dir, &stale_settings).unwrap();
let conn = crate::app_db::open().unwrap();
conn.execute_batch("CREATE TRIGGER reject_conversion_shutdown BEFORE UPDATE ON provider_failover BEGIN SELECT RAISE(ABORT,'fixture-conversion-shutdown-failure'); END;").unwrap();
let result = shutdown_all();
conn.execute_batch("DROP TRIGGER reject_conversion_shutdown")
.unwrap();
assert!(result
.unwrap_err()
.to_string()
.contains("fixture-conversion-shutdown-failure"));
assert!(!SHUTTING_DOWN.load(Ordering::Acquire));
assert!(lock_manager().unwrap().contains_key(&fixture.dir));
let after = FileCheckpoint::capture(&fixture.dir).unwrap();
assert_eq!(before.config, after.config);
assert_eq!(before.auth, after.auth);
assert_eq!(before.selected, after.selected);
save_record(&fixture.dir, &record).unwrap();
with_provider_change(fixture.scope(), || Ok(())).unwrap();
}
#[test]
fn converted_reattach_failure_restores_complete_files_selection_and_runtime() {
let _guard = crate::app_db::test_db_guard();
let mut fixture = Fixture::new();
fixture.providers[1].upstream_api = Some("anthropic_messages".into());
fixture.providers[1] =
crate::providers::save_provider_inner(fixture.providers[1].clone()).unwrap();
fixture.enable();
with_provider_change(fixture.scope(), || {
crate::providers::activate_saved_provider_inner(
fixture.scope(),
fixture.providers[1].id.clone(),
)
})
.unwrap();
let before = FileCheckpoint::capture(&fixture.dir).unwrap();
let result = with_provider_change(fixture.scope(), || {
fs::write(crate::config_path(&fixture.dir), "not valid = [toml").unwrap();
fs::write(
crate::auth_path(&fixture.dir),
r#"{"OPENAI_API_KEY":"replacement-fixture"}"#,
)
.unwrap();
Ok(())
});
assert!(result.unwrap_err().to_string().contains("恢复原配置"));
let after = FileCheckpoint::capture(&fixture.dir).unwrap();
assert_eq!(before.config, after.config);
assert_eq!(before.auth, after.auth);
assert_eq!(before.selected, after.selected);
assert_eq!(before.common_handled, after.common_handled);
let status = get_status(fixture.scope()).unwrap();
assert!(status.running && status.takeover_active);
assert_eq!(status.primary.unwrap().id, fixture.providers[1].id);
}
#[test]
fn converted_route_restart_keeps_protocol_and_stale_recovery_never_restores_raw_url() {
let _guard = crate::app_db::test_db_guard();
let mut fixture = Fixture::new();
fixture.providers[1].upstream_api = Some("gemini".into());
fixture.providers[1] =
crate::providers::save_provider_inner(fixture.providers[1].clone()).unwrap();
let mut settings = fixture.settings();
settings.auto_failover_enabled = false;
save_settings(fixture.scope(), settings).unwrap();
with_provider_change(fixture.scope(), || {
crate::providers::activate_saved_provider_inner(
fixture.scope(),
fixture.providers[1].id.clone(),
)
})
.unwrap();
let original = fixture.text();
let runtime = lock_manager().unwrap().remove(&fixture.dir).unwrap();
runtime.proxy.shutdown();
assert!(recover_stale_route(fixture.scope())
.unwrap_err()
.to_string()
.contains("协议转换"));
assert_eq!(fixture.text(), original);
initialize().unwrap();
let status = get_status(fixture.scope()).unwrap();
assert!(status.running && status.takeover_active);
assert!(fixture.text().contains("127.0.0.1"));
assert_eq!(
lock_manager().unwrap().get(&fixture.dir).unwrap().routes[0].protocol,
UpstreamApi::Gemini
);
}
#[test]
fn failover_to_converted_provider_preserves_close_guard() {
let _guard = crate::app_db::test_db_guard();
let mut fixture = Fixture::new();
fixture.providers[1].upstream_api = Some("gemini".into());
fixture.providers[1] =
crate::providers::save_provider_inner(fixture.providers[1].clone()).unwrap();
fixture.enable();
let mut runtimes = lock_manager().unwrap();
let runtime = runtimes.get(&fixture.dir).unwrap();
let notice = SelectionNotice {
dir: fixture.dir.clone(),
instance_id: runtime.instance_id,
token: runtime.token.clone(),
event: ProxySelectionEvent {
provider_id: fixture.providers[1].id.clone(),
revision: runtime.proxy.revision(),
},
};
record_selection(notice, &mut runtimes).unwrap();
assert!(
runtimes
.get(&fixture.dir)
.unwrap()
.journal
.as_ref()
.unwrap()
.requires_conversion
);
drop(runtimes);
let before = fixture.text();
let mut disabled = get_status(fixture.scope()).unwrap().settings;
disabled.takeover_enabled = false;
assert!(save_settings(fixture.scope(), disabled).is_err());
assert_eq!(fixture.text(), before);
}
#[test]
fn restore_keeps_external_edits_and_does_not_leave_local_headers() {
let _guard = crate::app_db::test_db_guard();
+137 -11
View File
@@ -15,8 +15,10 @@ use std::process::Command;
mod app_db;
mod app_update;
mod app_update_channel;
mod backups;
mod ccswitch;
mod codex_language;
mod config_health;
mod config_migration;
mod constants;
@@ -29,6 +31,7 @@ mod live_config;
mod paths;
mod platform;
mod prompts;
mod provider_balance;
mod providers;
mod remote;
mod sessions;
@@ -574,6 +577,67 @@ async fn open_codex_config_file(config_dir: Option<String>) -> Result<()> {
.map_err(|_| CodexxError::Config("打开配置文件失败,请稍后重试。".to_string()))?
}
#[tauri::command]
async fn refresh_provider_balance(
config_dir: Option<String>,
source: String,
provider_id: String,
) -> Result<provider_balance::ProviderBalanceResult> {
tauri::async_runtime::spawn_blocking(move || {
provider_balance::refresh_provider_balance_inner(config_dir, source, provider_id)
})
.await
.map_err(|_| CodexxError::Config("刷新供应商余额失败,请稍后重试。".into()))?
}
#[tauri::command]
async fn get_provider_balances(
config_dir: Option<String>,
) -> Result<Vec<provider_balance::ProviderBalanceResult>> {
tauri::async_runtime::spawn_blocking(move || {
provider_balance::get_provider_balances_inner(config_dir)
})
.await
.map_err(|_| CodexxError::Config("读取供应商余额失败,请稍后重试。".into()))?
}
#[tauri::command]
async fn get_codex_language_status(
config_dir: Option<String>,
) -> Result<codex_language::LanguageStatus> {
tauri::async_runtime::spawn_blocking(move || codex_language::get_status(config_dir))
.await
.map_err(|_| CodexxError::Config("读取 Codex 界面语言状态失败,请重试。".into()))?
}
#[tauri::command]
async fn save_codex_language_preferences(
config_dir: Option<String>,
locale: codex_language::Locale,
enabled: bool,
) -> Result<codex_language::LanguageStatus> {
tauri::async_runtime::spawn_blocking(move || {
codex_language::save_preferences(config_dir, locale, enabled)
})
.await
.map_err(|_| CodexxError::Config("保存 Codex 界面语言偏好失败,请重试。".into()))?
}
#[tauri::command]
async fn apply_codex_language_preferences(
config_dir: Option<String>,
restore: bool,
) -> Result<codex_language::LanguageStatus> {
tauri::async_runtime::spawn_blocking(move || {
let codex_dir = resolve_codex_dir(config_dir.clone())?;
sessions::with_session_maintenance(&codex_dir, || {
codex_language::apply(config_dir, restore)
})
})
.await
.map_err(|_| CodexxError::Config("应用 Codex 界面语言失败,请查看状态后重试。".into()))?
}
#[tauri::command]
async fn get_session_sync_status(
config_dir: Option<String>,
@@ -659,11 +723,18 @@ async fn get_about_info(config_dir: Option<String>) -> Result<AboutInfo> {
}
#[tauri::command]
async fn restart_codex_desktop() -> std::result::Result<CodexDesktopRestartResult, String> {
let (app_name, was_running) =
tauri::async_runtime::spawn_blocking(platform::restart_codex_desktop)
.await
.map_err(|error| format!("重启 Codex 桌面客户端失败: {error}"))??;
async fn restart_codex_desktop(
config_dir: Option<String>,
) -> std::result::Result<CodexDesktopRestartResult, String> {
let (app_name, was_running) = tauri::async_runtime::spawn_blocking(move || {
let codex_dir = resolve_codex_dir(config_dir.clone()).map_err(|e| e.to_string())?;
sessions::with_session_maintenance(&codex_dir, || {
codex_language::restart_client(config_dir)
})
.map_err(|e| e.to_string())
})
.await
.map_err(|error| format!("重启 Codex 桌面客户端失败: {error}"))??;
Ok(CodexDesktopRestartResult {
app_name,
was_running,
@@ -1037,6 +1108,19 @@ async fn build_provider_toml_draft(
.map_err(|e| CodexxError::Config(format!("生成供应商 TOML 失败: {e}")))?
}
#[tauri::command]
fn read_provider_headers(config_text: String) -> Result<Vec<providers::ProviderHeader>> {
providers::read_provider_headers_inner(config_text)
}
#[tauri::command]
fn update_provider_headers(
config_text: String,
headers: Vec<providers::ProviderHeader>,
) -> Result<String> {
providers::update_provider_headers_inner(config_text, headers)
}
fn save_provider_command_inner(provider: SavedProvider) -> Result<SavedProvider> {
let saved = save_provider_inner(provider)?;
failover::refresh_saved_routes().map_err(|error| {
@@ -1121,6 +1205,11 @@ async fn activate_saved_provider(
provider_id: String,
) -> Result<ActionResult> {
tauri::async_runtime::spawn_blocking(move || {
let provider = providers::list_saved_providers_inner()?
.into_iter()
.find(|provider| provider.id == provider_id)
.ok_or_else(|| CodexxError::Config("供应商不存在".to_string()))?;
failover::ensure_conversion_route(config_dir.clone(), &provider)?;
failover::with_provider_change(config_dir.clone(), || {
let result = providers::activate_saved_provider_inner(config_dir, provider_id.clone())?;
Ok(finish_provider_selection(
@@ -1140,6 +1229,9 @@ async fn save_active_provider(
apply_common_config: Option<bool>,
) -> Result<ActionResult> {
tauri::async_runtime::spawn_blocking(move || {
let provider =
providers::normalize_saved_provider_for_save(&providers::open_store()?, provider)?;
failover::ensure_conversion_route(config_dir.clone(), &provider)?;
let result = failover::with_provider_change(config_dir.clone(), || {
let provider_id = provider.id.clone();
let result = if apply_common_config.unwrap_or(false) {
@@ -1575,20 +1667,46 @@ async fn save_provider_toml_config(
async fn test_provider_connection(
base_url: String,
api_key: Option<String>,
upstream_api: Option<String>,
config_text: Option<String>,
) -> Result<ProviderConnectionResult> {
tauri::async_runtime::spawn_blocking(move || test_provider_connection_inner(base_url, api_key))
.await
.map_err(|e| CodexxError::Config(format!("测试连接失败: {e}")))?
tauri::async_runtime::spawn_blocking(move || {
if upstream_api.is_none() && config_text.is_none() {
test_provider_connection_inner(base_url, api_key)
} else {
providers::test_provider_connection_with_protocol_inner(
base_url,
api_key,
upstream_api,
config_text,
)
}
})
.await
.map_err(|e| CodexxError::Config(format!("测试连接失败: {e}")))?
}
#[tauri::command]
async fn fetch_provider_models(
base_url: String,
api_key: Option<String>,
upstream_api: Option<String>,
config_text: Option<String>,
) -> Result<ProviderModelsResult> {
tauri::async_runtime::spawn_blocking(move || fetch_provider_models_inner(base_url, api_key))
.await
.map_err(|e| CodexxError::Config(format!("获取模型列表失败: {e}")))?
tauri::async_runtime::spawn_blocking(move || {
if upstream_api.is_none() && config_text.is_none() {
fetch_provider_models_inner(base_url, api_key)
} else {
providers::fetch_provider_models_with_protocol_inner(
base_url,
api_key,
upstream_api,
config_text,
)
}
})
.await
.map_err(|e| CodexxError::Config(format!("获取模型列表失败: {e}")))?
}
#[tauri::command]
@@ -1811,6 +1929,7 @@ pub fn run() {
})
.on_window_event(desktop_lifecycle::handle_window_event)
.invoke_handler(tauri::generate_handler![
app_update_channel::check_online_app_update,
app_update::install_app_update,
get_about_info,
restart_codex_desktop,
@@ -1830,6 +1949,11 @@ pub fn run() {
check_codex_config,
repair_codex_config,
open_codex_config_file,
refresh_provider_balance,
get_provider_balances,
get_codex_language_status,
save_codex_language_preferences,
apply_codex_language_preferences,
get_session_sync_status,
sync_sessions_provider,
delete_codex_sessions,
@@ -1849,6 +1973,8 @@ pub fn run() {
save_provider_order,
get_provider_config_base,
build_provider_toml_draft,
read_provider_headers,
update_provider_headers,
save_provider,
duplicate_provider,
update_codex_context_window,
+192 -104
View File
@@ -7,6 +7,9 @@ use std::sync::{mpsc, OnceLock};
use std::thread;
use std::time::{Duration, Instant};
#[path = "codex_desktop_windows.rs"]
pub(crate) mod desktop_windows;
#[cfg(target_os = "windows")]
use std::env;
@@ -36,7 +39,7 @@ const CODEX_DESKTOP_COMMAND_TIMEOUT: Duration = Duration::from_secs(5);
const CODEX_DESKTOP_QUIT_TIMEOUT: Duration = Duration::from_secs(8);
#[cfg(target_os = "macos")]
const CODEX_DESKTOP_POLL_INTERVAL: Duration = Duration::from_millis(100);
#[cfg(any(target_os = "windows", test))]
#[cfg(test)]
const WINDOWS_RESTART_RESULT_PREFIX: &str = "CODEX_X_DESKTOP_RESTART";
#[cfg(any(target_os = "macos", test))]
@@ -816,96 +819,209 @@ fn macos_main_process_ids(
))
}
pub(crate) fn desktop_command_output(
program: &Path,
args: &[&str],
timeout: Duration,
) -> Result<Output, String> {
run_program_with_timeout(program, args, Some(Instant::now() + timeout), timeout)
.ok_or_else(|| "客户端系统操作超时,未继续重启或连接客户端。".into())
}
#[cfg(target_os = "macos")]
fn wait_macos_stopped(executable: &Path) -> Result<(), String> {
let deadline = Instant::now() + CODEX_DESKTOP_QUIT_TIMEOUT;
let mut empty_since = None;
while Instant::now() < deadline {
let pids = match macos_main_process_ids(executable, Some(deadline)) {
Ok(pids) => pids,
Err(_) if Instant::now() >= deadline => break,
Err(error) => return Err(error),
};
if pids.is_empty() {
let since = empty_since.get_or_insert_with(Instant::now);
if since.elapsed() >= Duration::from_millis(500) {
return Ok(());
}
} else {
empty_since = None;
}
thread::sleep(CODEX_DESKTOP_POLL_INTERVAL);
}
Err("Codex/ChatGPT 客户端未正常退出,已取消重新启动;请先结束当前任务后重试。".into())
}
#[cfg(target_os = "macos")]
fn launch_macos_codex_app(app: &MacosCodexApp) -> Result<(), String> {
let deadline = Instant::now()
.checked_add(CODEX_DESKTOP_COMMAND_TIMEOUT)
.ok_or_else(|| "创建 Codex/ChatGPT 启动超时时间失败".to_string())?;
let bundle_path = app
.bundle_path
.to_str()
.ok_or_else(|| "Codex/ChatGPT 客户端路径不是有效文本".to_string())?;
let output = run_program_with_timeout(
Path::new("/usr/bin/open"),
&["-a", bundle_path],
Some(deadline),
CODEX_DESKTOP_COMMAND_TIMEOUT,
.ok_or("Codex 客户端路径不是有效文本")?;
let mut last_error = "未确认 Codex 客户端已启动".to_owned();
for attempt in 0..2 {
let output = desktop_command_output(
Path::new("/usr/bin/open"),
&["-n", "-a", bundle_path],
CODEX_DESKTOP_COMMAND_TIMEOUT,
);
let accepted = output.as_ref().is_ok_and(|output| output.status.success());
if let Ok(output) = &output {
if !output.status.success() {
let message = String::from_utf8_lossy(&output.stderr).trim().to_owned();
if !message.is_empty() {
last_error = message;
}
}
} else if let Err(error) = output {
last_error = error;
}
// LaunchServices can acknowledge a launch before a process appears,
// or report a stale quit/launch error after the new process starts.
let deadline = Instant::now()
+ if accepted {
CODEX_DESKTOP_QUIT_TIMEOUT
} else {
Duration::from_millis(750)
};
let mut observed = None;
while Instant::now() < deadline {
let pids = match macos_main_process_ids(&app.executable_path, Some(deadline)) {
Ok(pids) => pids,
Err(_) if Instant::now() >= deadline => break,
Err(error) => return Err(error),
};
if !pids.is_empty() {
let (previous, since) =
observed.get_or_insert_with(|| (pids.clone(), Instant::now()));
if *previous == pids && since.elapsed() >= Duration::from_millis(200) {
return Ok(());
}
if *previous != pids {
*previous = pids;
*since = Instant::now();
}
} else {
observed = None;
}
thread::sleep(CODEX_DESKTOP_POLL_INTERVAL);
}
if accepted || attempt == 1 {
break;
}
// Retry only an unacknowledged launch with no surviving main process.
// Never open a second instance after LaunchServices confirmed one.
}
Err(format!("启动 Codex/ChatGPT 未完成:{last_error}"))
}
// Narrow helpers shared with the opt-in locale launcher. They do not quit or
// launch anything until the explicit locale apply command calls them.
#[cfg(target_os = "macos")]
pub(crate) fn locale_platform_command(program: &Path, args: &[&str]) -> Result<Output, String> {
let deadline = Instant::now() + CODEX_DESKTOP_COMMAND_TIMEOUT;
let output =
run_program_with_timeout(program, args, Some(deadline), CODEX_DESKTOP_COMMAND_TIMEOUT)
.ok_or("客户端操作超时,未继续应用语言兼容。")?;
if !output.status.success() {
return Err("客户端操作未完成,请检查官方客户端状态后重试。".into());
}
Ok(output)
}
#[cfg(target_os = "macos")]
pub(crate) fn locale_desktop_app() -> Result<(PathBuf, PathBuf, String, String, String), String> {
let deadline = Some(Instant::now() + CODEX_DESKTOP_COMMAND_TIMEOUT);
let apps: Vec<_> = macos_codex_apps(deadline)?
.into_iter()
.filter(|app| {
matches!(
app.bundle_id.as_str(),
"com.openai.codex" | "com.openai.codex.beta"
)
})
.collect();
let mut running = Vec::new();
for app in &apps {
if !macos_main_process_ids(&app.executable_path, deadline)?.is_empty() {
running.push(app);
}
}
if running.len() > 1 {
return Err("检测到多个官方客户端实例,请先保留一个实例再应用界面语言。".into());
}
let app = running
.first()
.copied()
.or_else(|| apps.first())
.ok_or("未找到官方 Codex 客户端")?;
let version = macos_info_plist_version(&app.bundle_path).unwrap_or_else(|| "unknown".into());
Ok((
app.bundle_path.clone(),
app.executable_path.clone(),
app.bundle_id.clone(),
app.app_name.clone(),
version,
))
}
#[cfg(target_os = "macos")]
pub(crate) fn locale_desktop_pids(executable: &Path) -> Result<Vec<u32>, String> {
macos_main_process_ids(
executable,
Some(Instant::now() + CODEX_DESKTOP_COMMAND_TIMEOUT),
)
.ok_or_else(|| "启动 Codex/ChatGPT 客户端失败或超时".to_string())?;
if output.status.success() {
return Ok(());
}
#[cfg(target_os = "macos")]
pub(crate) fn locale_quit_desktop(executable: &Path, bundle_id: &str) -> Result<(), String> {
if !MACOS_CODEX_BUNDLE_IDS.contains(&bundle_id) {
return Err("不支持的客户端身份".into());
}
if locale_desktop_pids(executable)?.is_empty() {
return wait_macos_stopped(executable);
}
let requested = locale_platform_command(
Path::new("/usr/bin/osascript"),
&[
"-e",
&format!("tell application id \"{bundle_id}\" to quit"),
],
);
// Apple Events may lose the connection while the application exits. An
// error from osascript is not proof that the exact selected process lives.
match wait_macos_stopped(executable) {
Ok(()) => Ok(()),
Err(error) => Err(requested
.err()
.map(|request| format!("{request};{error}"))
.unwrap_or(error)),
}
let message = String::from_utf8_lossy(&output.stderr).trim().to_string();
Err(if message.is_empty() {
"启动 Codex/ChatGPT 客户端失败".to_string()
} else {
format!("启动 Codex/ChatGPT 客户端失败: {message}")
})
}
#[cfg(target_os = "macos")]
pub fn restart_codex_desktop() -> Result<(String, bool), String> {
let detection_deadline = Instant::now()
.checked_add(CODEX_DESKTOP_COMMAND_TIMEOUT)
.ok_or_else(|| "创建 Codex/ChatGPT 检测超时时间失败".to_string())?;
let apps = macos_codex_apps(Some(detection_deadline))?;
let detection_deadline = Some(Instant::now() + CODEX_DESKTOP_COMMAND_TIMEOUT);
let apps = macos_codex_apps(detection_deadline)?;
let mut first_installed = None;
let mut running_app = None;
let mut running = Vec::new();
for app in apps {
let is_running =
!macos_main_process_ids(&app.executable_path, Some(detection_deadline))?.is_empty();
if is_running {
running_app = Some(app);
break;
}
if first_installed.is_none() {
if !macos_main_process_ids(&app.executable_path, detection_deadline)?.is_empty() {
running.push(app);
} else if first_installed.is_none() {
first_installed = Some(app);
}
}
let was_running = running_app.is_some();
let app = running_app
if running.len() > 1 {
return Err("检测到多个官方 Codex 客户端,请先保留一个再重启。".into());
}
let was_running = !running.is_empty();
let app = running
.pop()
.or(first_installed)
.ok_or_else(|| "未找到可重启的 Codex/ChatGPT 桌面客户端".to_string())?;
if !was_running {
launch_macos_codex_app(&app)?;
return Ok((app.app_name, false));
}
let quit_script = format!("tell application id \"{}\" to quit", app.bundle_id);
let command_deadline = Instant::now()
.checked_add(CODEX_DESKTOP_COMMAND_TIMEOUT)
.ok_or_else(|| "创建 Codex/ChatGPT 退出命令超时时间失败".to_string())?;
let output = run_program_with_timeout(
Path::new("/usr/bin/osascript"),
&["-e", quit_script.as_str()],
Some(command_deadline),
CODEX_DESKTOP_COMMAND_TIMEOUT,
)
.ok_or_else(|| "请求 Codex/ChatGPT 客户端正常退出失败或超时".to_string())?;
if !output.status.success() {
let message = String::from_utf8_lossy(&output.stderr).trim().to_string();
return Err(if message.is_empty() {
"请求 Codex/ChatGPT 客户端正常退出失败".to_string()
} else {
format!("请求 Codex/ChatGPT 客户端正常退出失败: {message}")
});
}
let quit_deadline = Instant::now()
.checked_add(CODEX_DESKTOP_QUIT_TIMEOUT)
.ok_or_else(|| "创建 Codex/ChatGPT 退出等待时间失败".to_string())?;
loop {
if macos_main_process_ids(&app.executable_path, Some(quit_deadline))?.is_empty() {
break;
}
if Instant::now() >= quit_deadline {
return Err("Codex/ChatGPT 客户端未在限定时间内正常退出,已取消重新启动".to_string());
}
thread::sleep(CODEX_DESKTOP_POLL_INTERVAL);
}
.ok_or("未找到可重启的 Codex 客户端")?;
locale_quit_desktop(&app.executable_path, &app.bundle_id)?;
launch_macos_codex_app(&app)?;
Ok((app.app_name, true))
Ok((app.app_name, was_running))
}
#[cfg(not(target_os = "macos"))]
@@ -913,7 +1029,7 @@ fn macos_app_version(_deadline: Option<Instant>) -> Option<String> {
None
}
#[cfg(any(target_os = "windows", test))]
#[cfg(test)]
fn parse_windows_restart_result(output: &str) -> Option<(String, bool)> {
output.lines().rev().find_map(|line| {
let payload = line
@@ -934,7 +1050,7 @@ fn parse_windows_restart_result(output: &str) -> Option<(String, bool)> {
})
}
#[cfg(any(target_os = "windows", test))]
#[cfg(test)]
fn windows_restart_script() -> String {
let identities = WINDOWS_CODEX_PACKAGE_IDENTITIES
.iter()
@@ -1026,35 +1142,7 @@ $runningFlag = if ($wasRunning) { '1' } else { '0' }
#[cfg(target_os = "windows")]
pub fn restart_codex_desktop() -> Result<(String, bool), String> {
let script = windows_restart_script();
let timeout = CODEX_DESKTOP_QUIT_TIMEOUT + CODEX_DESKTOP_COMMAND_TIMEOUT;
let deadline = Instant::now()
.checked_add(timeout)
.ok_or_else(|| "创建 Codex/ChatGPT 重启超时时间失败".to_string())?;
let output = run_program_with_timeout(
Path::new("powershell.exe"),
&[
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
"-Command",
script.as_str(),
],
Some(deadline),
timeout,
)
.ok_or_else(|| "重启 Codex/ChatGPT 客户端失败或超时".to_string())?;
if !output.status.success() {
let message = String::from_utf8_lossy(&output.stderr).trim().to_string();
return Err(if message.is_empty() {
"重启 Codex/ChatGPT 客户端失败".to_string()
} else {
format!("重启 Codex/ChatGPT 客户端失败: {message}")
});
}
parse_windows_restart_result(&String::from_utf8_lossy(&output.stdout))
.ok_or_else(|| "无法确认 Codex/ChatGPT 客户端的重启结果".to_string())
desktop_windows::restart()
}
#[cfg(target_os = "windows")]
@@ -0,0 +1,860 @@
//! Read-only balances for saved providers and the current native provider.
//! Request destinations are fixed official URLs, never supplied over IPC.
use crate::error::{CodexxError, Result};
use crate::providers::{self, SavedProvider};
use chrono::{SecondsFormat, Utc};
use reqwest::blocking::Client;
use reqwest::header::{HeaderValue, ACCEPT, AUTHORIZATION};
use serde::Serialize;
use serde_json::Value;
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Condvar, Mutex, OnceLock};
use std::time::{Duration, Instant};
use toml_edit::{DocumentMut, Item};
const SUCCESS_TTL: Duration = Duration::from_secs(300);
const FAILURE_TTL: Duration = Duration::from_secs(60);
const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
const MAX_RESPONSE_BYTES: u64 = 64 * 1024;
const MAX_CACHE_ENTRIES: usize = 256;
#[derive(Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct BalanceAmount {
pub(crate) currency: String,
/// Exact base-10 text. Never route financial values through f64.
pub(crate) amount: String,
}
#[derive(Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct ProviderBalanceResult {
pub(crate) source: String,
pub(crate) provider_id: String,
pub(crate) vendor: Option<&'static str>,
pub(crate) supported: bool,
pub(crate) balance_kind: Option<&'static str>,
pub(crate) balances: Vec<BalanceAmount>,
pub(crate) checked_at: Option<String>,
pub(crate) error_code: Option<&'static str>,
}
#[derive(Clone, Copy)]
enum Vendor {
DeepSeek,
OpenRouter,
SiliconFlow,
Moonshot,
}
impl Vendor {
fn name(self) -> &'static str {
match self {
Self::DeepSeek => "deepseek",
Self::OpenRouter => "openrouter",
Self::SiliconFlow => "siliconflow",
Self::Moonshot => "moonshot",
}
}
fn endpoint(self) -> &'static str {
match self {
Self::DeepSeek => "https://api.deepseek.com/user/balance",
Self::OpenRouter => "https://openrouter.ai/api/v1/key",
Self::SiliconFlow => "https://api.siliconflow.cn/v1/user/info",
Self::Moonshot => "https://api.moonshot.cn/v1/users/me/balance",
}
}
}
fn vendor_for_provider(provider: &SavedProvider) -> Option<Vendor> {
// This flag controls Codex authentication, and legacy third-party routes
// can also set it. Eligibility comes from the official API URL below;
// official login profiles are never enumerated by this module.
let url = reqwest::Url::parse(provider.base_url.trim()).ok()?;
if url.scheme() != "https"
|| !url.username().is_empty()
|| url.password().is_some()
|| url.port().is_some_and(|port| port != 443)
|| url.query().is_some()
|| url.fragment().is_some()
{
return None;
}
let path = url.path().trim_end_matches('/');
let normal_path = matches!(
path,
"" | "/v1" | "/v1/chat/completions" | "/v1/responses" | "/v1/messages"
);
match url.host_str()? {
"api.deepseek.com" if normal_path => Some(Vendor::DeepSeek),
"api.siliconflow.cn" if normal_path => Some(Vendor::SiliconFlow),
"api.moonshot.cn" if normal_path => Some(Vendor::Moonshot),
"openrouter.ai"
if matches!(
path,
"" | "/api/v1"
| "/api/v1/chat/completions"
| "/api/v1/responses"
| "/api/v1/messages"
) =>
{
Some(Vendor::OpenRouter)
}
_ => None,
}
}
fn environment_value(name: &str) -> std::result::Result<String, &'static str> {
let mut bytes = name.bytes();
if !bytes
.next()
.is_some_and(|b| b.is_ascii_alphabetic() || b == b'_')
|| !bytes.all(|b| b.is_ascii_alphanumeric() || b == b'_')
{
return Err("invalid_credential");
}
std::env::var(name).map_err(|_| "missing_key")
}
fn credential(
provider: &SavedProvider,
detected: bool,
) -> std::result::Result<String, &'static str> {
let doc = provider
.toml_config
.as_deref()
.filter(|text| !text.trim().is_empty())
.map(|text| {
text.parse::<DocumentMut>()
.map_err(|_| "invalid_configuration")
})
.transpose()?;
let table = doc.as_ref().and_then(|doc| {
let id = doc
.get("model_provider")
.and_then(Item::as_str)
.unwrap_or(&provider.id);
doc.get("model_providers")?
.as_table_like()?
.get(id)?
.as_table_like()
});
// Only the official API's Bearer credential is relevant. Do not forward
// arbitrary provider headers (Host, cookies, routing headers, etc.).
let mut custom_authorization = None;
if let Some(table) = table {
for (field, from_env) in [("http_headers", false), ("env_http_headers", true)] {
if let Some(item) = table.get(field) {
let headers = item.as_table_like().ok_or("invalid_configuration")?;
for (name, item) in headers.iter() {
if name.eq_ignore_ascii_case("authorization") {
if custom_authorization.is_some() {
return Err("invalid_credential");
}
let value = item.as_str().ok_or("invalid_credential")?;
custom_authorization = Some(if from_env {
environment_value(value)?
} else {
value.to_string()
});
}
}
}
}
}
// The detected-provider helper may carry a legacy auth.json fallback key.
// An explicit native env_key must take precedence over that fallback, so an
// unrelated credential cannot win over the route's own environment key.
let native_key = if detected && custom_authorization.is_none() {
if let Some(key) = table
.and_then(|table| table.get("experimental_bearer_token"))
.and_then(Item::as_str)
.filter(|key| !key.trim().is_empty())
{
Some(key.to_string())
} else if let Some(name) = table
.and_then(|table| table.get("env_key"))
.and_then(Item::as_str)
{
Some(environment_value(name)?)
} else {
None
}
} else {
None
};
let key = if let Some(authorization) = custom_authorization {
let (scheme, key) = authorization.split_once(' ').ok_or("invalid_credential")?;
if !scheme.eq_ignore_ascii_case("bearer") {
return Err("invalid_credential");
}
key.to_string()
} else if let Some(key) = native_key {
key
} else if let Some(key) = provider
.api_key
.as_deref()
.filter(|key| !key.trim().is_empty())
{
key.to_string()
} else if let Some(key) = table
.and_then(|table| table.get("experimental_bearer_token"))
.and_then(Item::as_str)
.filter(|key| !key.trim().is_empty())
.map(ToString::to_string)
.or_else(|| {
doc.as_ref()
.and_then(|doc| providers::experimental_bearer_token_from_doc(doc, None))
})
{
key
} else if let Some(name) = table
.and_then(|table| table.get("env_key"))
.and_then(Item::as_str)
{
environment_value(name)?
} else {
return Err("missing_key");
};
let key = key.trim();
if key.is_empty() {
return Err("missing_key");
}
if key.len() > 16 * 1024 || key.bytes().any(|b| b <= 0x20 || b == 0x7f) {
return Err("invalid_credential");
}
Ok(key.to_string())
}
#[derive(Clone)]
struct BalanceValue {
kind: Option<&'static str>,
balances: Vec<BalanceAmount>,
checked_at: String,
error: Option<&'static str>,
}
impl BalanceValue {
fn failure(error: &'static str) -> Self {
Self {
kind: None,
balances: Vec::new(),
checked_at: Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true),
error: Some(error),
}
}
}
type CacheEntry = Mutex<Option<(Instant, BalanceValue)>>;
fn cache() -> &'static Mutex<HashMap<String, Arc<CacheEntry>>> {
static CACHE: OnceLock<Mutex<HashMap<String, Arc<CacheEntry>>>> = OnceLock::new();
CACHE.get_or_init(|| Mutex::new(HashMap::new()))
}
fn cached_balance(vendor: Vendor, key: &str, force: bool, requested_at: Instant) -> BalanceValue {
let mut digest = Sha256::new();
digest.update(vendor.endpoint().as_bytes());
digest.update([0]);
digest.update(key.as_bytes());
let identity = format!("{:x}", digest.finalize());
let slot = {
let mut entries = cache().lock().unwrap_or_else(|p| p.into_inner());
if !entries.contains_key(&identity) && entries.len() >= MAX_CACHE_ENTRIES {
entries.retain(|_, entry| {
Arc::strong_count(entry) > 1
|| entry.try_lock().map_or(true, |value| {
value
.as_ref()
.is_some_and(|(at, _)| at.elapsed() < SUCCESS_TTL)
})
});
}
if !entries.contains_key(&identity) && entries.len() >= MAX_CACHE_ENTRIES {
return BalanceValue::failure("busy");
}
Arc::clone(
entries
.entry(identity)
.or_insert_with(|| Arc::new(Mutex::new(None))),
)
};
// A lock per credential, held for the bounded request, deduplicates copies
// and overlapping IPC calls without blocking unrelated accounts.
let mut entry = slot.lock().unwrap_or_else(|p| p.into_inner());
if let Some((at, value)) = entry.as_ref() {
let ttl = if value.error.is_some() {
FAILURE_TTL
} else {
SUCCESS_TTL
};
// A manual refresh bypasses an older TTL entry, but not a request
// that finished after this IPC call began. Queued copies of the same
// credential therefore share one refresh rather than serially forcing
// another HTTP request after acquiring this lock.
if *at >= requested_at || (!force && at.elapsed() < ttl) {
return value.clone();
}
}
let value = request_balance(vendor, key).unwrap_or_else(BalanceValue::failure);
*entry = Some((Instant::now(), value.clone()));
value
}
fn json_request(
client: &Client,
url: &'static str,
key: &str,
) -> std::result::Result<Value, &'static str> {
let mut authorization =
HeaderValue::from_str(&format!("Bearer {key}")).map_err(|_| "invalid_credential")?;
authorization.set_sensitive(true);
let response = client
.get(url)
.header(ACCEPT, "application/json")
.header(AUTHORIZATION, authorization)
.send()
.map_err(|error| {
if error.is_timeout() {
"timeout"
} else {
"network_error"
}
})?;
let status = response.status();
if !status.is_success() {
return Err(match status.as_u16() {
300..=399 => "redirect_blocked",
401 => "authentication_failed",
403 => "permission_denied",
429 => "rate_limited",
_ => "http_error",
});
}
if response
.content_length()
.is_some_and(|size| size > MAX_RESPONSE_BYTES)
{
return Err("response_too_large");
}
let mut bytes = Vec::new();
response
.take(MAX_RESPONSE_BYTES + 1)
.read_to_end(&mut bytes)
.map_err(|_| "network_error")?;
if bytes.len() as u64 > MAX_RESPONSE_BYTES {
return Err("response_too_large");
}
// serde_json's arbitrary_precision feature preserves the original numeric
// lexeme, including OpenRouter and Moonshot's JSON number balances.
serde_json::from_slice(&bytes).map_err(|_| "invalid_response")
}
fn amount(currency: &str, value: &Value) -> std::result::Result<BalanceAmount, &'static str> {
Ok(BalanceAmount {
currency: currency.to_string(),
amount: Decimal::from_value(value)?.text(),
})
}
fn request_balance(vendor: Vendor, key: &str) -> std::result::Result<BalanceValue, &'static str> {
crate::remote::ensure_crypto_provider();
// Same fresh-client system/ENV proxy behavior and five-second timeout as
// remote_client, with credentials additionally confined by no redirects.
let client = Client::builder()
.timeout(REQUEST_TIMEOUT)
.user_agent("Codex-X")
.https_only(true)
.redirect(reqwest::redirect::Policy::none())
.build()
.map_err(|_| "network_error")?;
let payload = json_request(&client, vendor.endpoint(), key)?;
let mut kind = "balance";
let balances = match vendor {
// https://api-docs.deepseek.com/api/get-user-balance
Vendor::DeepSeek => {
let infos = payload
.get("balance_infos")
.and_then(Value::as_array)
.filter(|items| !items.is_empty() && items.len() <= 4)
.ok_or("invalid_response")?;
let mut balances = Vec::new();
for info in infos {
let currency = info
.get("currency")
.and_then(Value::as_str)
.filter(|currency| matches!(*currency, "CNY" | "USD"))
.ok_or("invalid_response")?;
if balances
.iter()
.any(|item: &BalanceAmount| item.currency == currency)
{
return Err("invalid_response");
}
balances.push(amount(
currency,
info.get("total_balance").ok_or("invalid_response")?,
)?);
}
balances
}
// https://openrouter.ai/docs/api/api-reference/api-keys/get-current-key
// https://openrouter.ai/docs/api/api-reference/credits/get-credits
Vendor::OpenRouter => {
let data = payload.get("data").ok_or("invalid_response")?;
let remaining = data.get("limit_remaining").ok_or("invalid_response")?;
if !remaining.is_null() {
kind = "credit_limit";
vec![amount("USD", remaining)?]
} else {
// Management permission may be unavailable to ordinary model
// keys. Surface its short error code, never request a new key.
let credits = json_request(&client, "https://openrouter.ai/api/v1/credits", key)?;
let data = credits.get("data").ok_or("invalid_response")?;
let total =
Decimal::from_value(data.get("total_credits").ok_or("invalid_response")?)?;
let usage =
Decimal::from_value(data.get("total_usage").ok_or("invalid_response")?)?;
vec![BalanceAmount {
currency: "USD".into(),
amount: total.subtract(usage)?.text(),
}]
}
}
// Official CN OpenAPI: github.com/siliconflow/siliconcloud/openapi.yaml
// CN monetary units: docs.siliconflow.cn/docs/userguide/faqs/rate-limit-and-upgradation
Vendor::SiliconFlow => {
if payload.get("status").and_then(Value::as_bool) != Some(true)
|| payload.get("code").and_then(Value::as_u64) != Some(20000)
{
return Err("api_error");
}
vec![amount(
"CNY",
payload
.get("data")
.and_then(|data| data.get("totalBalance"))
.ok_or("invalid_response")?,
)?]
}
// https://platform.moonshot.cn/docs/api/balance (CN keys only)
Vendor::Moonshot => {
if payload.get("status").and_then(Value::as_bool) != Some(true)
|| payload.get("code").and_then(Value::as_u64) != Some(0)
{
return Err("api_error");
}
vec![amount(
"CNY",
payload
.get("data")
.and_then(|data| data.get("available_balance"))
.ok_or("invalid_response")?,
)?]
}
};
Ok(BalanceValue {
kind: Some(kind),
balances,
checked_at: Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true),
error: None,
})
}
struct Decimal {
units: i128,
scale: u32,
}
impl Decimal {
fn from_value(value: &Value) -> std::result::Result<Self, &'static str> {
let text = match value {
Value::String(text) => text.clone(),
Value::Number(number) => number.to_string(),
_ => return Err("invalid_response"),
};
Self::parse(&text)
}
fn parse(text: &str) -> std::result::Result<Self, &'static str> {
if text.is_empty() || text.len() > 128 || text.trim() != text {
return Err("invalid_response");
}
let (negative, unsigned) = text
.strip_prefix('-')
.map_or((false, text), |text| (true, text));
let (mantissa, exponent) = match unsigned.find(['e', 'E']) {
Some(index) => (
&unsigned[..index],
unsigned[index + 1..]
.parse::<i32>()
.map_err(|_| "invalid_response")?,
),
None => (unsigned, 0),
};
if exponent.unsigned_abs() > 36 {
return Err("invalid_response");
}
let (integer, fraction) = mantissa
.split_once('.')
.map_or((mantissa, ""), |parts| parts);
if integer.is_empty()
|| !integer.bytes().all(|b| b.is_ascii_digit())
|| !fraction.bytes().all(|b| b.is_ascii_digit())
|| (mantissa.contains('.') && fraction.is_empty())
{
return Err("invalid_response");
}
let digits = format!("{integer}{fraction}");
let mut units = digits.parse::<i128>().map_err(|_| "invalid_response")?;
if negative {
units = -units;
}
let scale = fraction.len() as i32 - exponent;
let scale = if scale < 0 {
units = units
.checked_mul(
10_i128
.checked_pow((-scale) as u32)
.ok_or("invalid_response")?,
)
.ok_or("invalid_response")?;
0
} else if scale > 36 {
return Err("invalid_response");
} else {
scale as u32
};
Ok(Self { units, scale }.normalized())
}
fn normalized(mut self) -> Self {
while self.scale > 0 && self.units % 10 == 0 {
self.units /= 10;
self.scale -= 1;
}
self
}
fn subtract(self, other: Self) -> std::result::Result<Self, &'static str> {
let scale = self.scale.max(other.scale);
let align = |number: Self| {
number
.units
.checked_mul(10_i128.checked_pow(scale - number.scale)?)
};
let units = align(self)
.and_then(|left| align(other).and_then(|right| left.checked_sub(right)))
.ok_or("invalid_response")?;
Ok(Self { units, scale }.normalized())
}
fn text(&self) -> String {
let digits = self.units.unsigned_abs().to_string();
let sign = if self.units < 0 { "-" } else { "" };
if self.scale == 0 {
return format!("{sign}{digits}");
}
let scale = self.scale as usize;
if digits.len() <= scale {
format!("{sign}0.{}{digits}", "0".repeat(scale - digits.len()))
} else {
let at = digits.len() - scale;
format!("{sign}{}.{}", &digits[..at], &digits[at..])
}
}
}
fn provider_result(
source: &str,
provider: &SavedProvider,
force: bool,
requested_at: Instant,
) -> ProviderBalanceResult {
let mut result = ProviderBalanceResult {
source: source.into(),
provider_id: if source == "detected" {
format!("detected-{}", provider.id)
} else {
provider.id.clone()
},
vendor: None,
supported: false,
balance_kind: None,
balances: Vec::new(),
checked_at: None,
error_code: None,
};
let Some(vendor) = vendor_for_provider(provider) else {
return result;
};
result.vendor = Some(vendor.name());
result.supported = true;
let key = match credential(provider, source == "detected") {
Ok(key) => key,
Err(code) => {
result.error_code = Some(code);
return result;
}
};
let value = cached_balance(vendor, &key, force, requested_at);
result.balance_kind = value.kind;
result.balances = value.balances;
result.checked_at = Some(value.checked_at);
result.error_code = value.error;
result
}
fn read_balances_at(
home: &Path,
continue_query: &(dyn Fn() -> bool + Sync),
) -> Result<Vec<ProviderBalanceResult>> {
let mut targets: Vec<_> = providers::list_saved_providers_inner()
.map_err(|_| CodexxError::Config("读取已保存供应商失败,请稍后重试。".into()))?
.into_iter()
.map(|provider| ("local", provider))
.collect();
if let Some(provider) = providers::detected_live_custom_provider(home)
.map_err(|_| CodexxError::Config("读取当前供应商配置失败,请检查配置格式后重试。".into()))?
{
targets.push(("detected", provider));
}
if targets.is_empty() {
return Ok(Vec::new());
}
// Bound concurrent network work. Duplicate account credentials still share
// the same cache lock even when represented by multiple cards/sources.
let workers = targets.len().min(4);
let batches = std::thread::scope(|scope| {
let handles: Vec<_> = (0..workers)
.map(|offset| {
let targets = &targets;
scope.spawn(move || {
(offset..targets.len())
.step_by(workers)
.take_while(|_| continue_query())
.map(|index| {
(
index,
provider_result(
targets[index].0,
&targets[index].1,
false,
Instant::now(),
),
)
})
.collect::<Vec<_>>()
})
})
.collect();
handles
.into_iter()
.map(|handle| {
handle
.join()
.map_err(|_| CodexxError::Config("读取供应商余额失败,请稍后重试。".into()))
})
.collect::<Result<Vec<_>>>()
})?;
let mut results: Vec<_> = batches.into_iter().flatten().collect();
results.sort_by_key(|(index, _)| *index);
Ok(results.into_iter().map(|(_, result)| result).collect())
}
#[derive(Clone)]
struct MonitorTarget {
home: PathBuf,
scope: String,
generation: u64,
}
#[derive(Default)]
struct MonitorState {
target: Option<MonitorTarget>,
next_refresh: Option<Instant>,
}
struct BalanceMonitor {
state: Mutex<MonitorState>,
changed: Condvar,
}
fn refresh_delay(result: &Result<Vec<ProviderBalanceResult>>) -> Duration {
let Ok(rows) = result else {
return FAILURE_TTL;
};
let now = Utc::now();
rows.iter()
.filter(|row| row.supported)
.map(|row| {
let ttl = if row.error_code.is_some() {
FAILURE_TTL
} else {
SUCCESS_TTL
};
let elapsed = row
.checked_at
.as_deref()
.and_then(|text| chrono::DateTime::parse_from_rfc3339(text).ok())
.map(|checked| {
now.signed_duration_since(checked.with_timezone(&Utc))
.to_std()
.unwrap_or(Duration::ZERO)
});
elapsed.map_or(ttl, |elapsed| {
// checkedAt is second-precision; allow one extra second so
// the credential cache's monotonic TTL has certainly expired.
// Reading warm/manual-refresh results must not reset a full TTL.
ttl.saturating_sub(elapsed)
.saturating_add(Duration::from_secs(1))
})
})
.min()
.unwrap_or(SUCCESS_TTL)
}
impl BalanceMonitor {
fn select(&self, home: PathBuf) -> u64 {
let scope = crate::paths::normalized_path_scope(&home);
let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner());
if let Some(target) = &state.target {
if target.scope == scope {
return target.generation;
}
}
let generation = state
.target
.as_ref()
.map_or(1, |target| target.generation.wrapping_add(1));
state.target = Some(MonitorTarget {
home,
scope,
generation,
});
// The selecting IPC call performs the first query. Schedule only once
// it has completed, rather than racing it or counting from its start.
state.next_refresh = None;
self.changed.notify_one();
generation
}
fn is_current(&self, generation: u64) -> bool {
self.state
.lock()
.unwrap_or_else(|p| p.into_inner())
.target
.as_ref()
.is_some_and(|target| target.generation == generation)
}
fn completed(&self, generation: u64, delay: Duration, native: bool) {
let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner());
if state
.target
.as_ref()
.is_some_and(|target| target.generation == generation)
&& (native || state.next_refresh.is_none())
{
// Reading a warm cache from the renderer must not continually
// postpone the independent native deadline.
state.next_refresh = Some(Instant::now() + delay);
self.changed.notify_one();
}
}
fn run(&self) {
loop {
let target = {
let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner());
loop {
if let (Some(target), Some(deadline)) =
(state.target.clone(), state.next_refresh)
{
let now = Instant::now();
if now >= deadline {
state.next_refresh = None;
break target;
}
let (next, _) = self
.changed
.wait_timeout(state, deadline.saturating_duration_since(now))
.unwrap_or_else(|p| p.into_inner());
state = next;
} else {
state = self.changed.wait(state).unwrap_or_else(|p| p.into_inner());
}
}
};
// Re-enumerate current saved/native providers every round. A scope
// change cancels queued old work between cards; active HTTP calls
// retain their existing bounded timeout and official-only URLs.
let result = read_balances_at(&target.home, &|| self.is_current(target.generation));
self.completed(target.generation, refresh_delay(&result), true);
}
}
}
fn native_monitor() -> Result<&'static Arc<BalanceMonitor>> {
static MONITOR: OnceLock<std::result::Result<Arc<BalanceMonitor>, String>> = OnceLock::new();
MONITOR
.get_or_init(|| {
let monitor = Arc::new(BalanceMonitor {
state: Mutex::new(MonitorState::default()),
changed: Condvar::new(),
});
let worker = Arc::clone(&monitor);
std::thread::Builder::new()
.name("provider-balance-monitor".into())
.spawn(move || worker.run())
.map_err(|_| "无法启动供应商余额后台刷新,请重启 Codex-X 后重试。".to_string())?;
Ok(monitor)
})
.as_ref()
.map_err(|message| CodexxError::Config(message.clone()))
}
/// The IPC wrapper should run this blocking function on spawn_blocking.
/// No URL, API key, arbitrary header or official account ID is accepted.
pub(crate) fn get_provider_balances_inner(
config_dir: Option<String>,
) -> Result<Vec<ProviderBalanceResult>> {
let home = crate::resolve_codex_dir(config_dir)?;
let monitor = native_monitor()?;
let generation = monitor.select(home.clone());
let result = read_balances_at(&home, &|| monitor.is_current(generation));
monitor.completed(generation, refresh_delay(&result), false);
result
}
/// Refresh a single persisted/current card. All connection details are read
/// again from trusted local provider storage, never accepted from the caller.
pub(crate) fn refresh_provider_balance_inner(
config_dir: Option<String>,
source: String,
provider_id: String,
) -> Result<ProviderBalanceResult> {
// Include provider lookup in the concurrency window: overlapping calls
// may spend different amounts of time reading the store/current config.
let requested_at = Instant::now();
if !matches!(source.as_str(), "local" | "detected") {
return Err(CodexxError::Config(
"仅支持刷新已保存或当前检测到的第三方供应商余额。".into(),
));
}
let home = crate::resolve_codex_dir(config_dir)?;
let provider = if source == "local" {
providers::list_saved_providers_inner()
.map_err(|_| CodexxError::Config("读取已保存供应商失败,请稍后重试。".into()))?
.into_iter()
.find(|provider| provider.id == provider_id)
} else {
providers::detected_live_custom_provider(&home)
.map_err(|_| {
CodexxError::Config("读取当前供应商配置失败,请检查配置格式后重试。".into())
})?
.filter(|provider| format!("detected-{}", provider.id) == provider_id)
}
.ok_or_else(|| {
CodexxError::Config("该供应商已不存在或当前配置已改变,请刷新供应商列表。".into())
})?;
if vendor_for_provider(&provider).is_none() {
return Err(CodexxError::Config("该供应商不支持余额刷新。".into()));
}
// Deliberately leave the independent five-minute monitor deadline alone.
Ok(provider_result(&source, &provider, true, requested_at))
}
+396 -14
View File
@@ -6,6 +6,7 @@ use super::{
};
use crate::ccswitch::{ccswitch_db_candidates, default_ccswitch_db_path};
use crate::error::{CodexxError, Result};
use crate::failover::protocol::UpstreamApi;
use crate::sqlite_utils::table_column_set;
use crate::string_value;
use crate::toml_utils::ensure_table;
@@ -43,6 +44,7 @@ pub(crate) struct CcSwitchCodexRow {
pub(crate) name: String,
pub(crate) settings_config: String,
pub(crate) category: Option<String>,
pub(crate) meta: Option<String>,
}
pub(crate) fn is_official_ccswitch_row(row: &CcSwitchCodexRow) -> bool {
@@ -60,8 +62,13 @@ pub(crate) fn read_ccswitch_codex_rows(conn: &Connection) -> Result<Vec<CcSwitch
} else {
"NULL"
};
let meta_column = if provider_columns.contains("meta") {
"meta"
} else {
"NULL"
};
let provider_query = format!(
"SELECT id, name, settings_config, {category_column} FROM providers
"SELECT id, name, settings_config, {category_column}, {meta_column} FROM providers
WHERE app_type = 'codex' ORDER BY sort_index ASC, created_at ASC"
);
let mut stmt = conn
@@ -74,6 +81,7 @@ pub(crate) fn read_ccswitch_codex_rows(conn: &Connection) -> Result<Vec<CcSwitch
name: row.get::<_, String>(1)?,
settings_config: row.get::<_, String>(2)?,
category: row.get::<_, Option<String>>(3)?,
meta: row.get::<_, Option<String>>(4)?,
})
})
.map_err(|e| CodexxError::Database(e.to_string()))?;
@@ -116,6 +124,94 @@ fn ccswitch_auth_api_key(settings: &Value) -> Option<String> {
.map(ToString::to_string)
}
fn explicit_ccswitch_api_format(
row: &CcSwitchCodexRow,
object: &Value,
prefix: &str,
) -> Result<Option<(String, String)>> {
for key in ["apiFormat", "api_format"] {
let Some(value) = object.get(key).filter(|value| !value.is_null()) else {
continue;
};
let field = format!("{prefix}.{key}");
let text = value.as_str().ok_or_else(|| {
CodexxError::Config(format!(
"cc-switch 供应商 {} 的 {field} 必须是协议名称文本",
row.id
))
})?;
if !text.trim().is_empty() {
return Ok(Some((text.trim().to_string(), field)));
}
}
Ok(None)
}
fn ccswitch_upstream_api(
row: &CcSwitchCodexRow,
settings: &Value,
wire_api: &str,
provider_id: Option<&str>,
) -> Result<Option<String>> {
let mut selected = None;
if let Some(text) = row.meta.as_deref().filter(|text| !text.trim().is_empty()) {
let meta: Value = serde_json::from_str(text).map_err(|_| {
CodexxError::Config(format!("cc-switch 供应商 {} 的 meta 不是有效 JSON", row.id))
})?;
if !meta.is_null() && !meta.is_object() {
return Err(CodexxError::Config(format!(
"cc-switch 供应商 {} 的 meta 必须是 JSON 对象",
row.id
)));
}
selected = explicit_ccswitch_api_format(row, &meta, "meta")?;
}
if selected.is_none() {
if let Some(meta) = settings.get("meta").filter(|meta| !meta.is_null()) {
if !meta.is_object() {
return Err(CodexxError::Config(format!(
"cc-switch 供应商 {} 的 settings.meta 必须是 JSON 对象",
row.id
)));
}
selected = explicit_ccswitch_api_format(row, meta, "settings.meta")?;
}
}
if selected.is_none() {
selected = explicit_ccswitch_api_format(row, settings, "settings")?;
}
let explicit = selected.is_some();
let (format, field) = selected.unwrap_or_else(|| {
(
wire_api.trim().to_string(),
format!(
"config.model_providers.{}.wire_api",
provider_id.unwrap_or("<当前供应商>")
),
)
});
let protocol = UpstreamApi::from_provider(Some(&format), "responses").map_err(|_| {
CodexxError::Config(format!(
"cc-switch 供应商 {} 的 {field} 上游协议不受支持;请选择 Responses、Chat Completions、Anthropic Messages 或 Gemini",
row.id
))
})?;
// An old native template says nothing about a locally selected bridge.
// Leave None so a refresh can retain Codex-X's independent metadata.
if !explicit && protocol == UpstreamApi::Responses {
return Ok(None);
}
Ok(Some(
match protocol {
UpstreamApi::Responses => "responses",
UpstreamApi::ChatCompletions => "chat_completions",
UpstreamApi::AnthropicMessages => "anthropic_messages",
UpstreamApi::Gemini => "gemini",
}
.to_string(),
))
}
pub(super) fn codex_section_from_table(
id: &str,
table: &Table,
@@ -285,6 +381,12 @@ fn ccswitch_provider_template(
}
providers.insert(provider_id, Item::Table(table));
}
let table = providers
.get_mut(provider_id)
.and_then(Item::as_table_mut)?;
if table.get("wire_api").and_then(Item::as_str) != Some("responses") {
table["wire_api"] = value("responses");
}
strip_provider_bearer_tokens(&mut doc);
Some(doc.to_string().trim_end().to_string())
}
@@ -292,9 +394,18 @@ fn ccswitch_provider_template(
pub(crate) fn build_ccswitch_codex_provider(
row: &CcSwitchCodexRow,
global_sections: &HashMap<String, CcSwitchCodexSection>,
) -> Option<SavedProvider> {
let settings: Value = serde_json::from_str(&row.settings_config).ok()?;
let section = select_ccswitch_section_for_row(row, &settings, global_sections)?;
) -> Result<Option<SavedProvider>> {
let Ok(settings) = serde_json::from_str::<Value>(&row.settings_config) else {
ccswitch_upstream_api(row, &Value::Null, "responses", None)?;
return Ok(None);
};
let Some(section) = select_ccswitch_section_for_row(row, &settings, global_sections) else {
// A configured but unsupported protocol should not be hidden behind
// the generic incomplete-provider warning.
ccswitch_upstream_api(row, &settings, "responses", None)?;
return Ok(None);
};
let upstream_api = ccswitch_upstream_api(row, &settings, &section.wire_api, Some(&section.id))?;
let api_key = ccswitch_auth_api_key(&settings).or(section.experimental_bearer_token.clone());
let provider_name = section
.name
@@ -304,19 +415,25 @@ pub(crate) fn build_ccswitch_codex_provider(
(!name.is_empty()).then(|| name.to_string())
})
.unwrap_or_else(|| row.id.clone());
let model = section.model.clone()?;
let toml_config = ccswitch_provider_template(&settings, &section, &provider_name, &model)?;
Some(SavedProvider {
let Some(model) = section.model.clone() else {
return Ok(None);
};
let Some(toml_config) = ccswitch_provider_template(&settings, &section, &provider_name, &model)
else {
return Ok(None);
};
Ok(Some(SavedProvider {
id: custom_provider_id(&row.id),
provider_name,
base_url: section.base_url,
model,
api_key,
toml_config: Some(toml_config),
wire_api: section.wire_api,
wire_api: "responses".to_string(),
requires_openai_auth: section.requires_openai_auth,
upstream_api,
model_mappings: Vec::new(),
})
}))
}
pub(crate) fn import_ccswitch_codex_providers_inner(path: Option<String>) -> Result<ImportResult> {
@@ -388,7 +505,7 @@ pub(crate) fn import_ccswitch_codex_providers_inner(path: Option<String>) -> Res
));
continue;
}
match build_ccswitch_codex_provider(&row, &global_sections) {
match build_ccswitch_codex_provider(&row, &global_sections)? {
Some(provider) => {
let provider = normalize_saved_provider(provider)?;
let result =
@@ -521,6 +638,249 @@ mod tests {
use super::*;
use serde_json::json;
fn protocol_row(format: Option<&str>) -> CcSwitchCodexRow {
CcSwitchCodexRow {
id: "protocol-fixture".into(),
name: "Protocol fixture".into(),
settings_config: json!({
"auth": {"OPENAI_API_KEY": "fixture-api-key"},
"config": "# keep imported comment\nmodel_provider='custom'\nmodel='fixture-model'\n[model_providers.custom]\nname='Protocol fixture'\nbase_url='https://neutral-gateway.example.test/custom-api-prefix'\nwire_api='responses'\nrequires_openai_auth=false\nhttp_headers={X-Title='Fixture title'}\n[mcp_servers.keep]\ncommand='fixture-server'\n",
}).to_string(),
category: None,
meta: format.map(|format| json!({"apiFormat":format}).to_string()),
}
}
fn fixture_ccswitch_database(with_meta: bool) -> (tempfile::TempDir, Connection) {
let dir = tempfile::tempdir().unwrap();
let conn = Connection::open(dir.path().join("fixture-ccswitch.db")).unwrap();
let optional = if with_meta {
"category TEXT, meta TEXT,"
} else {
""
};
conn.execute_batch(&format!(
"CREATE TABLE providers (id TEXT, name TEXT, app_type TEXT, settings_config TEXT, {optional} sort_index INTEGER, created_at INTEGER);"
)).unwrap();
(dir, conn)
}
#[test]
fn current_database_reads_metadata_and_builds_all_four_protocols_without_endpoint_guessing() {
let (_dir, conn) = fixture_ccswitch_database(true);
for (index, (format, canonical)) in [
("openai_responses", "responses"),
("openai_chat", "chat_completions"),
("anthropic", "anthropic_messages"),
("gemini", "gemini"),
]
.into_iter()
.enumerate()
{
let mut row = protocol_row(Some(format));
row.id = format!("protocol-{index}");
conn.execute(
"INSERT INTO providers (id,name,app_type,settings_config,meta,sort_index,created_at) VALUES (?1,?2,'codex',?3,?4,?5,1)",
rusqlite::params![row.id,row.name,row.settings_config,row.meta,index],
).unwrap();
let read = read_ccswitch_codex_rows(&conn).unwrap().pop().unwrap();
let provider = build_ccswitch_codex_provider(&read, &HashMap::new())
.unwrap()
.unwrap();
assert_eq!(provider.upstream_api.as_deref(), Some(canonical));
assert_eq!(provider.wire_api, "responses");
assert_eq!(
provider.base_url,
"https://neutral-gateway.example.test/custom-api-prefix"
);
let text = provider.toml_config.unwrap();
assert!(text.contains("# keep imported comment"));
let doc = text.parse::<DocumentMut>().unwrap();
let table = doc["model_providers"]["custom"].as_table().unwrap();
assert_eq!(table["wire_api"].as_str(), Some("responses"));
assert_eq!(
table["http_headers"]["X-Title"].as_str(),
Some("Fixture title")
);
assert!(table.get("upstream_api").is_none());
assert!(table.get("apiFormat").is_none());
assert_eq!(
doc["mcp_servers"]["keep"]["command"].as_str(),
Some("fixture-server")
);
}
}
#[test]
fn old_database_without_metadata_columns_preserves_absence_and_uses_settings_formats() {
let (_dir, conn) = fixture_ccswitch_database(false);
let mut row = protocol_row(None);
let mut settings: Value = serde_json::from_str(&row.settings_config).unwrap();
settings["api_format"] = json!("anthropic_messages");
row.settings_config = settings.to_string();
conn.execute(
"INSERT INTO providers (id,name,app_type,settings_config,sort_index,created_at) VALUES (?1,?2,'codex',?3,0,1)",
rusqlite::params![row.id,row.name,row.settings_config],
).unwrap();
let read = read_ccswitch_codex_rows(&conn).unwrap().pop().unwrap();
assert!(read.category.is_none());
assert!(read.meta.is_none());
let provider = build_ccswitch_codex_provider(&read, &HashMap::new())
.unwrap()
.unwrap();
assert_eq!(provider.upstream_api.as_deref(), Some("anthropic_messages"));
let native = build_ccswitch_codex_provider(&protocol_row(None), &HashMap::new())
.unwrap()
.unwrap();
assert!(native.upstream_api.is_none());
}
#[test]
fn protocol_metadata_priority_is_database_meta_then_nested_settings_then_settings_format() {
let mut row = protocol_row(Some("openai_chat"));
let mut settings: Value = serde_json::from_str(&row.settings_config).unwrap();
settings["meta"] = json!({"apiFormat":"anthropic"});
settings["apiFormat"] = json!("gemini");
settings["api_format"] = json!("responses");
row.settings_config = settings.to_string();
let db = build_ccswitch_codex_provider(&row, &HashMap::new())
.unwrap()
.unwrap();
assert_eq!(db.upstream_api.as_deref(), Some("chat_completions"));
row.meta = None;
let nested = build_ccswitch_codex_provider(&row, &HashMap::new())
.unwrap()
.unwrap();
assert_eq!(nested.upstream_api.as_deref(), Some("anthropic_messages"));
settings.as_object_mut().unwrap().remove("meta");
row.settings_config = settings.to_string();
let camel = build_ccswitch_codex_provider(&row, &HashMap::new())
.unwrap()
.unwrap();
assert_eq!(camel.upstream_api.as_deref(), Some("gemini"));
settings.as_object_mut().unwrap().remove("apiFormat");
row.settings_config = settings.to_string();
let snake = build_ccswitch_codex_provider(&row, &HashMap::new())
.unwrap()
.unwrap();
assert_eq!(snake.upstream_api.as_deref(), Some("responses"));
}
#[test]
fn explicit_metadata_overrides_legacy_wire_format_and_legacy_chat_migrates_native_toml() {
let mut row = protocol_row(None);
row.settings_config = row
.settings_config
.replace("wire_api='responses'", "wire_api='chat'");
let legacy = build_ccswitch_codex_provider(&row, &HashMap::new())
.unwrap()
.unwrap();
assert_eq!(legacy.upstream_api.as_deref(), Some("chat_completions"));
assert_eq!(legacy.wire_api, "responses");
assert_eq!(
legacy.toml_config.unwrap().parse::<DocumentMut>().unwrap()["model_providers"]
["custom"]["wire_api"]
.as_str(),
Some("responses")
);
row.meta = Some(json!({"apiFormat":"openai_responses"}).to_string());
let explicit = build_ccswitch_codex_provider(&row, &HashMap::new())
.unwrap()
.unwrap();
assert_eq!(explicit.upstream_api.as_deref(), Some("responses"));
row.settings_config = row
.settings_config
.replace("wire_api='chat'", "wire_api='unknown-wire'");
let overridden = build_ccswitch_codex_provider(&row, &HashMap::new())
.unwrap()
.unwrap();
assert_eq!(overridden.upstream_api.as_deref(), Some("responses"));
}
#[test]
fn unknown_protocol_metadata_reports_its_provider_and_field_without_echoing_credentials() {
for (meta, settings_format, key) in [
(Some("future_protocol"), None, "meta.apiFormat"),
(None, Some("future_protocol"), "settings.api_format"),
] {
let mut row = protocol_row(meta);
if let Some(format) = settings_format {
let mut settings: Value = serde_json::from_str(&row.settings_config).unwrap();
settings["api_format"] = json!(format);
row.settings_config = settings.to_string();
}
let error = build_ccswitch_codex_provider(&row, &HashMap::new())
.unwrap_err()
.to_string();
assert!(error.contains(&row.id));
assert!(error.contains(key));
assert!(error.contains("不受支持"));
assert!(!error.contains("fixture-api-key"));
}
let mut row = protocol_row(None);
row.settings_config = row
.settings_config
.replace("wire_api='responses'", "wire_api='future_wire'");
let error = build_ccswitch_codex_provider(&row, &HashMap::new())
.unwrap_err()
.to_string();
assert!(error.contains("config.model_providers.custom.wire_api"));
row.meta = Some(json!({"apiFormat":"future_protocol"}).to_string());
row.settings_config = json!({"apiFormat":"responses","config":""}).to_string();
assert!(build_ccswitch_codex_provider(&row, &HashMap::new()).is_err());
}
#[test]
fn malformed_metadata_and_non_text_protocol_fields_are_rejected_without_raw_json() {
for meta in ["{fixture-private-meta", "[]", "{\"apiFormat\":42}"] {
let mut row = protocol_row(None);
row.meta = Some(meta.to_string());
let error = build_ccswitch_codex_provider(&row, &HashMap::new())
.unwrap_err()
.to_string();
assert!(error.contains("meta"));
assert!(!error.contains("fixture-private-meta"));
assert!(!error.contains("fixture-api-key"));
}
}
#[test]
fn refreshing_old_native_input_keeps_the_local_protocol_but_an_explicit_choice_replaces_it() {
let conn = Connection::open_in_memory().unwrap();
conn.execute_batch("CREATE TABLE providers (id TEXT PRIMARY KEY,provider_name TEXT NOT NULL,base_url TEXT NOT NULL,model TEXT NOT NULL,api_key TEXT,toml_config TEXT,wire_api TEXT NOT NULL,requires_openai_auth INTEGER NOT NULL,model_mappings_json TEXT NOT NULL,upstream_api TEXT,source TEXT NOT NULL,source_id TEXT,created_at TEXT NOT NULL,updated_at TEXT NOT NULL);").unwrap();
let original = normalize_saved_provider(
build_ccswitch_codex_provider(&protocol_row(Some("openai_chat")), &HashMap::new())
.unwrap()
.unwrap(),
)
.unwrap();
upsert_ccswitch_provider_on_connection(&conn, original, "protocol-fixture").unwrap();
let old_input = build_ccswitch_codex_provider(&protocol_row(None), &HashMap::new())
.unwrap()
.unwrap();
assert!(old_input.upstream_api.is_none());
let retained = upsert_ccswitch_provider_on_connection(
&conn,
normalize_saved_provider(old_input).unwrap(),
"protocol-fixture",
)
.unwrap()
.provider;
assert_eq!(retained.upstream_api.as_deref(), Some("chat_completions"));
let explicit =
build_ccswitch_codex_provider(&protocol_row(Some("openai_responses")), &HashMap::new())
.unwrap()
.unwrap();
let replaced = upsert_ccswitch_provider_on_connection(
&conn,
normalize_saved_provider(explicit).unwrap(),
"protocol-fixture",
)
.unwrap()
.provider;
assert_eq!(replaced.upstream_api.as_deref(), Some("responses"));
}
#[test]
fn provider_import_round_trips_complete_config_without_bearer_tokens() {
let settings_config = json!({
@@ -540,6 +900,8 @@ wire_api = "responses"
requires_openai_auth = false
experimental_bearer_token = "sk-from-config"
request_max_retries = 7
http_headers = { "HTTP-Referer" = "https://header.example.test", "User-Agent" = "Fixture agent" }
env_http_headers = { "X-Project" = "PROJECT_ID" }
[model_providers.other]
name = "Other provider"
@@ -576,10 +938,12 @@ command = "docs-server"
name: " Sky2_free ".to_string(),
settings_config,
category: None,
meta: None,
};
let provider =
build_ccswitch_codex_provider(&row, &HashMap::new()).expect("build cc-switch provider");
let provider = build_ccswitch_codex_provider(&row, &HashMap::new())
.expect("valid cc-switch provider")
.expect("build cc-switch provider");
assert_eq!(provider.id, "magicai-123");
assert_eq!(provider.provider_name, "Sky2api");
assert_eq!(provider.base_url, "https://proxy.example.com/v1");
@@ -607,6 +971,18 @@ command = "docs-server"
doc["model_providers"]["custom"]["request_max_retries"].as_integer(),
Some(7)
);
assert_eq!(
doc["model_providers"]["custom"]["http_headers"]["HTTP-Referer"].as_str(),
Some("https://header.example.test")
);
assert_eq!(
doc["model_providers"]["custom"]["http_headers"]["User-Agent"].as_str(),
Some("Fixture agent")
);
assert_eq!(
doc["model_providers"]["custom"]["env_http_headers"]["X-Project"].as_str(),
Some("PROJECT_ID")
);
assert_eq!(
doc["model_providers"]["other"]["base_url"].as_str(),
Some("https://other.example.com/v1")
@@ -665,9 +1041,12 @@ requires_openai_auth = false
})
.to_string(),
category: None,
meta: None,
};
assert!(build_ccswitch_codex_provider(&row, &HashMap::new()).is_none());
assert!(build_ccswitch_codex_provider(&row, &HashMap::new())
.unwrap()
.is_none());
}
#[test]
@@ -697,8 +1076,11 @@ requires_openai_auth = false
})
.to_string(),
category: None,
meta: None,
};
assert!(build_ccswitch_codex_provider(&row, &global_sections).is_none());
assert!(build_ccswitch_codex_provider(&row, &global_sections)
.unwrap()
.is_none());
}
}
@@ -1,12 +1,15 @@
use crate::error::{CodexxError, Result};
use crate::failover::protocol::UpstreamApi;
#[cfg(test)]
use crate::remote::ensure_crypto_provider;
use crate::remote::{remote_client, remote_request_error, RemoteSource};
use reqwest::blocking::Client;
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::collections::HashMap;
use std::time::Instant;
use toml_edit::{DocumentMut, Item};
const MODELS_SOURCE_KEY: &str = "获取模型列表";
@@ -46,18 +49,31 @@ struct ModelPayload {
created: Option<serde_json::Value>,
}
#[derive(Debug, Deserialize)]
struct GeminiModelsPayload {
models: Vec<GeminiModelPayload>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct GeminiModelPayload {
name: String,
#[serde(default)]
supported_generation_methods: Vec<String>,
}
enum ProviderModelsAttempt {
Success(ProviderModelsResult),
HttpError { status: u16, duration_ms: u128 },
}
fn provider_models_url(base_url: &str) -> Result<reqwest::Url> {
fn provider_base_url(base_url: &str) -> Result<reqwest::Url> {
let trimmed = base_url.trim();
if trimmed.is_empty() {
return Err(CodexxError::Config("base_url 不能为空".to_string()));
}
let mut url = reqwest::Url::parse(trimmed)
let url = reqwest::Url::parse(trimmed)
.map_err(|_| CodexxError::Config("base_url 格式不正确".to_string()))?;
if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
return Err(CodexxError::Config(
@@ -65,6 +81,11 @@ fn provider_models_url(base_url: &str) -> Result<reqwest::Url> {
));
}
Ok(url)
}
fn provider_models_url(base_url: &str) -> Result<reqwest::Url> {
let mut url = provider_base_url(base_url)?;
let segments = url
.path_segments()
.ok_or_else(|| CodexxError::Config("base_url 格式不正确".to_string()))?
@@ -93,6 +114,97 @@ fn provider_models_url(base_url: &str) -> Result<reqwest::Url> {
Ok(url)
}
fn provider_models_url_with_protocol(
base_url: &str,
protocol: UpstreamApi,
) -> Result<reqwest::Url> {
if protocol != UpstreamApi::Gemini {
let mut url = provider_base_url(base_url)?;
let path = url.path().trim_end_matches('/');
let suffix = match protocol {
UpstreamApi::Responses => "/responses",
UpstreamApi::ChatCompletions => "/chat/completions",
UpstreamApi::AnthropicMessages => "/messages",
UpstreamApi::Gemini => unreachable!(),
};
if let Some(prefix) = path.strip_suffix(suffix) {
let prefix = prefix.to_string();
url.set_path(&prefix);
}
return provider_models_url(url.as_str());
}
let mut url = provider_base_url(base_url)?;
let path = url.path().trim_end_matches('/');
// A pasted generateContent endpoint still points to the same API prefix.
let prefix = path
.split_once("/models/")
.map_or(path, |(prefix, _)| prefix);
let path = if prefix.ends_with("/models") {
prefix.to_string()
} else if prefix.ends_with("/v1") || prefix.ends_with("/v1beta") {
format!("{prefix}/models")
} else {
format!("{prefix}/v1beta/models")
};
url.set_path(&path);
url.set_fragment(None);
Ok(url)
}
fn provider_models_headers_with_env(
config_text: Option<&str>,
resolve_env: impl Fn(&str) -> Option<String>,
) -> Result<HeaderMap> {
let Some(config_text) = config_text.filter(|text| !text.trim().is_empty()) else {
return Ok(HeaderMap::new());
};
let doc = config_text
.parse::<DocumentMut>()
.map_err(|_| CodexxError::Config("供应商 TOML 无效,请先修正配置".into()))?;
let id = doc
.get("model_provider")
.and_then(Item::as_str)
.map(str::trim)
.filter(|id| !id.is_empty())
.ok_or_else(|| CodexxError::Config("供应商 TOML 缺少 model_provider".into()))?;
let table = doc
.get("model_providers")
.and_then(Item::as_table)
.and_then(|providers| providers.get(id))
.and_then(Item::as_table)
.ok_or_else(|| CodexxError::Config("供应商 TOML 缺少当前供应商配置表".into()))?;
super::store::validate_provider_header_table(table)?;
let mut headers = HeaderMap::new();
for header in super::store::read_provider_headers_inner(config_text.to_string())? {
let text = match header.source {
super::store::ProviderHeaderSource::Static => header.value,
super::store::ProviderHeaderSource::Env => {
resolve_env(&header.value).ok_or_else(|| {
CodexxError::Config(format!(
"供应商 Header ({}) 所需的环境变量不可用",
header.name
))
})?
}
};
let name = HeaderName::from_bytes(header.name.as_bytes())
.map_err(|_| CodexxError::Config("供应商 Header 名称无效".into()))?;
let mut value = HeaderValue::from_str(&text).map_err(|_| {
CodexxError::Config(format!(
"供应商 Header ({}) 值无效,不能包含换行或控制字符",
header.name
))
})?;
value.set_sensitive(true);
headers.insert(name, value);
}
Ok(headers)
}
fn provider_models_headers(config_text: Option<&str>) -> Result<HeaderMap> {
provider_models_headers_with_env(config_text, |name| std::env::var(name).ok())
}
fn parse_created(value: Option<serde_json::Value>) -> Option<i64> {
value.and_then(|value| {
value
@@ -158,10 +270,42 @@ fn natural_model_id_cmp(left: &str, right: &str) -> Ordering {
fn parse_models(body: &str) -> Result<Vec<ProviderModel>> {
let payload: ModelsPayload = serde_json::from_str(body)
.map_err(|_| CodexxError::Config("模型列表返回格式不正确".to_string()))?;
Ok(normalize_models(payload.data))
}
fn parse_models_with_protocol(body: &str, protocol: UpstreamApi) -> Result<Vec<ProviderModel>> {
if protocol != UpstreamApi::Gemini {
return parse_models(body);
}
let payload: GeminiModelsPayload = serde_json::from_str(body)
.map_err(|_| CodexxError::Config("模型列表返回格式不正确".to_string()))?;
let models = payload
.models
.into_iter()
.filter(|model| {
model
.supported_generation_methods
.iter()
.any(|method| method == "generateContent")
})
.map(|model| ModelPayload {
id: model
.name
.trim()
.strip_prefix("models/")
.unwrap_or(model.name.trim())
.to_string(),
created: None,
})
.collect();
Ok(normalize_models(models))
}
fn normalize_models(payload: Vec<ModelPayload>) -> Vec<ProviderModel> {
let mut models = Vec::<ProviderModel>::new();
let mut indexes = HashMap::<String, usize>::new();
for model in payload.data {
for model in payload {
let id = model.id.trim();
if id.is_empty() {
continue;
@@ -187,22 +331,70 @@ fn parse_models(body: &str) -> Result<Vec<ProviderModel>> {
.then_with(|| natural_model_id_cmp(&right.id, &left.id))
});
Ok(models)
models
}
#[cfg(test)]
fn request_provider_models_with_client(
client: &Client,
base_url: &str,
api_key: Option<&str>,
) -> Result<ProviderModelsAttempt> {
let url = provider_models_url(base_url)?;
request_provider_models_with_protocol_client(
client,
base_url,
api_key,
UpstreamApi::Responses,
None,
)
}
fn request_provider_models_with_protocol_client(
client: &Client,
base_url: &str,
api_key: Option<&str>,
protocol: UpstreamApi,
config_text: Option<&str>,
) -> Result<ProviderModelsAttempt> {
let headers = provider_models_headers(config_text)?;
request_provider_models_with_headers(client, base_url, api_key, protocol, headers)
}
fn request_provider_models_with_headers(
client: &Client,
base_url: &str,
api_key: Option<&str>,
protocol: UpstreamApi,
headers: HeaderMap,
) -> Result<ProviderModelsAttempt> {
let url = provider_models_url_with_protocol(base_url, protocol)?;
let source = RemoteSource::new(MODELS_SOURCE_KEY, url.as_str(), Some("application/json"));
let mut request = client
.get(url.as_str())
.header(reqwest::header::ACCEPT, "application/json");
if let Some(api_key) = api_key.map(str::trim).filter(|key| !key.is_empty()) {
request = request.bearer_auth(api_key);
if protocol == UpstreamApi::AnthropicMessages {
request = request.header("anthropic-version", "2023-06-01");
}
let custom_auth = ["authorization", "x-api-key", "x-goog-api-key"]
.iter()
.any(|name| headers.contains_key(*name));
if let Some(api_key) = api_key
.map(str::trim)
.filter(|key| !key.is_empty() && !custom_auth)
{
let (name, text) = match protocol {
UpstreamApi::Responses | UpstreamApi::ChatCompletions => {
("authorization", format!("Bearer {api_key}"))
}
UpstreamApi::AnthropicMessages => ("x-api-key", api_key.to_string()),
UpstreamApi::Gemini => ("x-goog-api-key", api_key.to_string()),
};
let mut value = HeaderValue::from_str(&text)
.map_err(|_| CodexxError::Config("供应商 API Key 格式不正确".into()))?;
value.set_sensitive(true);
request = request.header(name, value);
}
request = request.headers(headers);
let started = Instant::now();
let response = request
@@ -221,15 +413,21 @@ fn request_provider_models_with_client(
.text()
.map_err(|_| CodexxError::Config("模型列表读取失败".to_string()))?;
Ok(ProviderModelsAttempt::Success(ProviderModelsResult {
models: parse_models(&body)?,
models: parse_models_with_protocol(&body, protocol)?,
status,
duration_ms,
}))
}
fn request_provider_models(base_url: &str, api_key: Option<&str>) -> Result<ProviderModelsAttempt> {
fn request_provider_models_with_protocol(
base_url: &str,
api_key: Option<&str>,
upstream_api: Option<&str>,
config_text: Option<&str>,
) -> Result<ProviderModelsAttempt> {
let protocol = UpstreamApi::from_provider(upstream_api, "responses")?;
let client = remote_client()?;
request_provider_models_with_client(&client, base_url, api_key)
request_provider_models_with_protocol_client(&client, base_url, api_key, protocol, config_text)
}
pub(crate) fn provider_status_result(status: u16, duration_ms: u128) -> ProviderConnectionResult {
@@ -251,7 +449,21 @@ pub(crate) fn test_provider_connection_inner(
base_url: String,
api_key: Option<String>,
) -> Result<ProviderConnectionResult> {
match request_provider_models(&base_url, api_key.as_deref())? {
test_provider_connection_with_protocol_inner(base_url, api_key, None, None)
}
pub(crate) fn test_provider_connection_with_protocol_inner(
base_url: String,
api_key: Option<String>,
upstream_api: Option<String>,
config_text: Option<String>,
) -> Result<ProviderConnectionResult> {
match request_provider_models_with_protocol(
&base_url,
api_key.as_deref(),
upstream_api.as_deref(),
config_text.as_deref(),
)? {
ProviderModelsAttempt::Success(result) => {
Ok(provider_status_result(result.status, result.duration_ms))
}
@@ -266,7 +478,21 @@ pub(crate) fn fetch_provider_models_inner(
base_url: String,
api_key: Option<String>,
) -> Result<ProviderModelsResult> {
match request_provider_models(&base_url, api_key.as_deref())? {
fetch_provider_models_with_protocol_inner(base_url, api_key, None, None)
}
pub(crate) fn fetch_provider_models_with_protocol_inner(
base_url: String,
api_key: Option<String>,
upstream_api: Option<String>,
config_text: Option<String>,
) -> Result<ProviderModelsResult> {
match request_provider_models_with_protocol(
&base_url,
api_key.as_deref(),
upstream_api.as_deref(),
config_text.as_deref(),
)? {
ProviderModelsAttempt::Success(result) => Ok(result),
ProviderModelsAttempt::HttpError { status, .. } => {
Err(CodexxError::Config(if matches!(status, 401 | 403) {
@@ -434,4 +660,204 @@ mod tests {
assert!(!message.contains(&base_url));
server.join().expect("join mock server");
}
#[test]
fn protocol_model_urls_preserve_api_prefix_and_do_not_repeat_versions() {
for (protocol, base, expected) in [
(UpstreamApi::Responses, "https://example.test/v1/responses", "https://example.test/v1/models"),
(UpstreamApi::ChatCompletions, "https://example.test/v1/chat/completions", "https://example.test/v1/models"),
(UpstreamApi::AnthropicMessages, "https://example.test", "https://example.test/v1/models"),
(UpstreamApi::AnthropicMessages, "https://example.test/anthropic/v1/messages", "https://example.test/anthropic/v1/models"),
(UpstreamApi::Gemini, "https://example.test", "https://example.test/v1beta/models"),
(UpstreamApi::Gemini, "https://example.test/v1beta", "https://example.test/v1beta/models"),
(UpstreamApi::Gemini, "https://example.test/v1beta/", "https://example.test/v1beta/models"),
(UpstreamApi::Gemini, "https://example.test/v1", "https://example.test/v1/models"),
(UpstreamApi::Gemini, "https://example.test/api/google/v1/models", "https://example.test/api/google/v1/models"),
(UpstreamApi::Gemini, "https://example.test/api/google/v1beta/models/gemini-2.5-pro:generateContent?route=fixture#ignored", "https://example.test/api/google/v1beta/models?route=fixture"),
(UpstreamApi::Gemini, "https://example.test/api/google", "https://example.test/api/google/v1beta/models"),
] {
assert_eq!(provider_models_url_with_protocol(base, protocol).unwrap().as_str(), expected);
}
}
#[test]
fn chat_and_anthropic_models_use_their_protocol_authentication() {
for (protocol, auth) in [
(
UpstreamApi::ChatCompletions,
"authorization: bearer fixture-protocol-key",
),
(
UpstreamApi::AnthropicMessages,
"x-api-key: fixture-protocol-key",
),
] {
let (url, server) = serve_once(200, r#"{"data":[{"id":"fixture-model"}]}"#);
let attempt = request_provider_models_with_protocol_client(
&direct_client(),
&url,
Some("fixture-protocol-key"),
protocol,
None,
)
.unwrap();
let ProviderModelsAttempt::Success(result) = attempt else {
panic!("expected model list")
};
assert_eq!(result.models[0].id, "fixture-model");
let request = server.join().unwrap().to_ascii_lowercase();
assert!(request.starts_with("get /v1/models http/1.1"));
assert!(request.contains(auth));
if protocol == UpstreamApi::AnthropicMessages {
assert!(request.contains("anthropic-version: 2023-06-01"));
assert!(!request.contains("authorization:"));
} else {
assert!(!request.contains("x-api-key:"));
}
assert!(!request.contains("x-goog-api-key:"));
}
}
#[test]
fn gemini_models_use_google_header_and_include_only_generate_content_models() {
let body = r#"{"models":[{"name":"models/gemini-2.5-pro","supportedGenerationMethods":["generateContent","countTokens"]},{"name":"models/text-embedding-004","supportedGenerationMethods":["embedContent"]},{"name":" models/gemini-2.5-flash ","supportedGenerationMethods":["generateContent"]},{"name":"models/gemini-2.5-pro","supportedGenerationMethods":["generateContent"]},{"name":"models/count-only","supportedGenerationMethods":["countTokens"]}]}"#;
let (url, server) = serve_once(200, body);
let attempt = request_provider_models_with_protocol_client(
&direct_client(),
&format!("{url}/v1beta"),
Some("fixture-google-key"),
UpstreamApi::Gemini,
None,
)
.unwrap();
let ProviderModelsAttempt::Success(result) = attempt else {
panic!("expected Gemini model list")
};
assert_eq!(
result
.models
.iter()
.map(|model| model.id.as_str())
.collect::<Vec<_>>(),
["gemini-2.5-pro", "gemini-2.5-flash"]
);
let request = server.join().unwrap().to_ascii_lowercase();
assert!(request.starts_with("get /v1beta/models http/1.1"));
assert!(request.contains("x-goog-api-key: fixture-google-key"));
assert!(!request.contains("authorization:"));
assert!(!request.contains("x-api-key:"));
assert!(!request
.lines()
.next()
.unwrap()
.contains("fixture-google-key"));
}
#[test]
fn static_and_environment_headers_are_applied_to_model_discovery() {
let config = "model_provider='custom'\n[model_providers.custom]\nhttp_headers={User-Agent='Fixture agent',HTTP-Referer='https://fixture.example.test'}\nenv_http_headers={X-Project='FIXTURE_PROJECT'}\n";
let headers = provider_models_headers_with_env(Some(config), |name| {
(name == "FIXTURE_PROJECT").then(|| "fixture-project-value".to_string())
})
.unwrap();
assert!(!format!("{headers:?}").contains("fixture-project-value"));
let (url, server) = serve_once(200, r#"{"data":[]}"#);
request_provider_models_with_headers(
&direct_client(),
&url,
Some("fixture-api-key"),
UpstreamApi::Responses,
headers,
)
.unwrap();
let request = server.join().unwrap().to_ascii_lowercase();
assert!(request.contains("user-agent: fixture agent"));
assert!(request.contains("http-referer: https://fixture.example.test"));
assert!(request.contains("x-project: fixture-project-value"));
assert!(request.contains("authorization: bearer fixture-api-key"));
}
#[test]
fn explicit_auth_and_anthropic_version_headers_override_request_defaults() {
let config = "model_provider='custom'\n[model_providers.custom]\nhttp_headers={Authorization='Bearer fixture-custom-auth',anthropic-version='2099-01-01'}\n";
let (url, server) = serve_once(200, r#"{"data":[]}"#);
request_provider_models_with_protocol_client(
&direct_client(),
&url,
Some("fixture-unused-key"),
UpstreamApi::AnthropicMessages,
Some(config),
)
.unwrap();
let request = server.join().unwrap().to_ascii_lowercase();
assert!(request.contains("authorization: bearer fixture-custom-auth"));
assert!(request.contains("anthropic-version: 2099-01-01"));
assert!(!request.contains("anthropic-version: 2023-06-01"));
assert!(!request.contains("x-api-key:"));
assert!(!request.contains("fixture-unused-key"));
}
#[test]
fn header_validation_rejects_duplicates_and_invalid_resolved_values_without_secret_echo() {
let duplicate = "model_provider='custom'\n[model_providers.custom]\nhttp_headers={X-Project='fixture-static-secret'}\nenv_http_headers={x-project='FIXTURE_PROJECT'}\n";
let error = provider_models_headers_with_env(Some(duplicate), |_| {
panic!("validation must happen before resolving environment values")
})
.unwrap_err()
.to_string();
assert!(!error.contains("fixture-static-secret"));
assert!(error.contains("重复"));
let env = "model_provider='custom'\n[model_providers.custom]\nenv_http_headers={X-Project='FIXTURE_PROJECT'}\n";
for resolved in [
None,
Some("fixture-env-secret\r\nInjected: value".to_string()),
] {
let error = provider_models_headers_with_env(Some(env), |_| resolved.clone())
.unwrap_err()
.to_string();
assert!(error.contains("X-Project"));
assert!(!error.contains("fixture-env-secret"));
assert!(!error.contains("Injected"));
}
}
#[test]
fn gemini_payload_errors_and_authentication_statuses_do_not_echo_private_data() {
let (url, server) = serve_once(200, r#"{"models":"fixture-private-response"}"#);
let error = request_provider_models_with_protocol_client(
&direct_client(),
&url,
Some("fixture-google-secret"),
UpstreamApi::Gemini,
None,
)
.err()
.unwrap()
.to_string();
assert!(!error.contains("fixture-private-response"));
assert!(!error.contains("fixture-google-secret"));
server.join().unwrap();
let (url, server) = serve_once(401, r#"{"error":"fixture-auth-private-response"}"#);
let attempt = request_provider_models_with_protocol_client(
&direct_client(),
&url,
Some("fixture-anthropic-secret"),
UpstreamApi::AnthropicMessages,
None,
)
.unwrap();
let ProviderModelsAttempt::HttpError {
status,
duration_ms,
} = attempt
else {
panic!("expected authentication status")
};
let result = provider_status_result(status, duration_ms);
assert!(!result.ok);
assert_eq!(result.status, Some(401));
assert!(!result.message.contains("fixture-auth-private-response"));
assert!(!result.message.contains("fixture-anthropic-secret"));
server.join().unwrap();
}
}
+51 -1
View File
@@ -583,6 +583,7 @@ pub(crate) fn detected_live_custom_provider(codex_dir: &Path) -> Result<Option<S
toml_config: (!toml_config.is_empty()).then_some(toml_config),
wire_api: section.wire_api,
requires_openai_auth: section.requires_openai_auth,
upstream_api: None,
model_mappings: Vec::new(),
}))
}
@@ -1203,6 +1204,7 @@ fn merge_provider_toml_into_live_with_policy(
"config.toml 缺少 [model_providers.{source_provider_id}]"
))
})?;
super::store::validate_provider_header_table(&source_provider)?;
let source_name = source_provider
.get("name")
.and_then(|item| item.as_str())
@@ -1768,6 +1770,52 @@ mod tests {
use std::fs;
use std::sync::atomic::{AtomicU64, Ordering};
#[test]
fn header_values_survive_direct_toml_activation_and_invalid_values_are_rejected() {
let config = "model_provider='custom'\nmodel='gpt-test'\n[model_providers.custom]\nname='Header fixture'\nbase_url='https://headers.example.test/v1'\nwire_api='responses'\nrequires_openai_auth=false\nhttp_headers={User-Agent='Fixture agent'}\nenv_http_headers={X-Project='PROJECT_ID'}\n";
let (doc, _) =
merge_provider_toml_into_live(Path::new("fixture.toml"), "", config, None).unwrap();
assert_eq!(
doc["model_providers"]["custom"]["http_headers"]["User-Agent"].as_str(),
Some("Fixture agent")
);
assert_eq!(
doc["model_providers"]["custom"]["env_http_headers"]["X-Project"].as_str(),
Some("PROJECT_ID")
);
let invalid = config.replace(
"User-Agent='Fixture agent'",
"User-Agent=\"secret\\r\\ninjected\"",
);
let error = merge_provider_toml_into_live(Path::new("fixture.toml"), "", &invalid, None)
.unwrap_err()
.to_string();
assert!(error.contains("Header"));
assert!(!error.contains("secret"));
}
#[test]
fn explicit_api_key_removes_stale_authorization_headers_from_both_sources() {
let mut doc = "[custom]\nhttp_headers={Authorization='Bearer stale',X-Trace='keep'}\nenv_http_headers={aUtHoRiZaTiOn='STALE_AUTH',X-Project='PROJECT_ID'}\n".parse::<DocumentMut>().unwrap();
let table = doc["custom"].as_table_mut().unwrap();
configure_live_provider_auth(table, Some("fixture-key"), false);
assert!(table["http_headers"]
.as_table_like()
.unwrap()
.get("Authorization")
.is_none());
assert!(table["env_http_headers"]
.as_table_like()
.unwrap()
.get("aUtHoRiZaTiOn")
.is_none());
assert_eq!(table["http_headers"]["X-Trace"].as_str(), Some("keep"));
assert_eq!(
table["env_http_headers"]["X-Project"].as_str(),
Some("PROJECT_ID")
);
}
fn active_provider_fixture(
tag: u64,
id: &str,
@@ -1795,6 +1843,7 @@ requires_openai_auth = false
)),
wire_api: "responses".to_string(),
requires_openai_auth: false,
upstream_api: None,
model_mappings: Vec::new(),
}
}
@@ -2280,6 +2329,7 @@ command = "docs-server"
toml_config: None,
wire_api: "responses".to_string(),
requires_openai_auth: false,
upstream_api: None,
model_mappings: Vec::new(),
},
Some(codex_dir.display().to_string()),
@@ -2848,7 +2898,7 @@ command = "docs-server"
r#"env_key = "STALE_ENV_KEY"
env_key_instructions = "Stale environment instructions"
auth = { command = "fixture-never-executed" }
http_headers = { Authorization = "Bearer stale", "X-Trace" = "keep-static" }
http_headers = { "X-Trace" = "keep-static" }
env_http_headers = { aUtHoRiZaTiOn = "STALE_AUTH", "X-Project" = "PROJECT_ENV" }
"#,
);
+9 -7
View File
@@ -24,8 +24,9 @@ pub(crate) use ccswitch::{
#[cfg(test)]
pub(crate) use connection::provider_status_result;
pub(crate) use connection::{
fetch_provider_models_inner, test_provider_connection_inner, ProviderConnectionResult,
ProviderModelsResult,
fetch_provider_models_inner, fetch_provider_models_with_protocol_inner,
test_provider_connection_inner, test_provider_connection_with_protocol_inner,
ProviderConnectionResult, ProviderModelsResult,
};
pub(crate) use live::{
activate_saved_provider_inner, build_provider_toml_draft_inner,
@@ -62,11 +63,12 @@ pub(crate) use store::{
get_provider_order_inner, is_placeholder_provider, list_saved_providers_inner,
list_saved_providers_on_connection, matching_saved_provider_ids_for_live,
matching_saved_provider_ids_for_live_on_connection, normalize_saved_provider,
normalize_saved_provider_for_save, provider_template_from_document, reserved_codex_provider_id,
rollback_provider_store_inner, save_detected_provider_with_rollback_inner, save_provider_inner,
save_provider_order_inner, save_provider_with_rollback_inner, strip_provider_bearer_tokens,
upsert_ccswitch_provider_on_connection, DuplicateProviderResult, ProviderStoreRollback,
ProviderUpsertKind, SavedProvider,
normalize_saved_provider_for_save, provider_template_from_document,
read_provider_headers_inner, reserved_codex_provider_id, rollback_provider_store_inner,
save_detected_provider_with_rollback_inner, save_provider_inner, save_provider_order_inner,
save_provider_with_rollback_inner, strip_provider_bearer_tokens, update_provider_headers_inner,
upsert_ccswitch_provider_on_connection, DuplicateProviderResult, ProviderHeader,
ProviderStoreRollback, ProviderUpsertKind, SavedProvider,
};
pub(crate) fn open_store() -> Result<Connection> {
+573 -22
View File
@@ -5,7 +5,170 @@ use crate::{now_rfc3339, resolve_codex_dir, sanitize_id};
use rusqlite::{params, Connection, OptionalExtension, TransactionBehavior};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use toml_edit::{value, DocumentMut};
use toml_edit::{value, DocumentMut, Item, Table};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum ProviderHeaderSource {
Static,
Env,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct ProviderHeader {
pub(crate) name: String,
pub(crate) value: String,
pub(crate) source: ProviderHeaderSource,
}
fn provider_headers_from_table(table: &Table) -> Result<Vec<ProviderHeader>> {
let mut result = Vec::new();
for (field, source) in [
("http_headers", ProviderHeaderSource::Static),
("env_http_headers", ProviderHeaderSource::Env),
] {
let Some(item) = table.get(field) else {
continue;
};
let headers = item
.as_table_like()
.ok_or_else(|| CodexxError::Config(format!("供应商 {field} 必须是键值表")))?;
for (name, item) in headers.iter() {
let text = item
.as_str()
.ok_or_else(|| CodexxError::Config(format!("供应商 {field} 的值必须是文本")))?;
result.push(ProviderHeader {
name: name.to_string(),
value: text.to_string(),
source,
});
}
}
Ok(result)
}
fn validate_provider_headers(headers: &[ProviderHeader]) -> Result<()> {
let mut names = HashSet::new();
for (index, header) in headers.iter().enumerate() {
let row = index + 1;
reqwest::header::HeaderName::from_bytes(header.name.as_bytes())
.map_err(|_| CodexxError::Config(format!("第 {row} 个供应商 Header 名称无效")))?;
if !names.insert(header.name.to_ascii_lowercase()) {
return Err(CodexxError::Config(format!(
"第 {row} 个供应商 Header 名称重复(不区分大小写)"
)));
}
match header.source {
ProviderHeaderSource::Static => {
reqwest::header::HeaderValue::from_str(&header.value).map_err(|_| {
CodexxError::Config(format!(
"第 {row} 个供应商 Header ({}) 值无效,不能包含换行或控制字符",
header.name
))
})?;
}
ProviderHeaderSource::Env => {
let mut bytes = header.value.bytes();
let valid_first = bytes
.next()
.is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_');
if !valid_first || !bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') {
return Err(CodexxError::Config(format!(
"第 {row} 个供应商 Header ({}) 环境变量名无效,请使用字母、数字和下划线,且不要以数字开头", header.name
)));
}
}
}
}
Ok(())
}
pub(super) fn validate_provider_header_table(table: &Table) -> Result<()> {
validate_provider_headers(&provider_headers_from_table(table)?)
}
fn selected_provider_id(doc: &DocumentMut) -> Result<String> {
doc.get("model_provider")
.and_then(Item::as_str)
.map(str::trim)
.filter(|id| !id.is_empty())
.map(ToString::to_string)
.ok_or_else(|| CodexxError::Config("供应商 TOML 缺少 model_provider".to_string()))
}
/// Read only the selected provider's headers. Invalid names and values remain
/// visible to the editor so users can repair older configurations.
pub(crate) fn read_provider_headers_inner(config_text: String) -> Result<Vec<ProviderHeader>> {
let doc = config_text
.parse::<DocumentMut>()
.map_err(|_| CodexxError::Config("供应商 TOML 无效,请先修正配置".to_string()))?;
let provider_id = selected_provider_id(&doc)?;
let table = doc
.get("model_providers")
.and_then(Item::as_table)
.and_then(|providers| providers.get(&provider_id))
.and_then(Item::as_table)
.ok_or_else(|| CodexxError::Config("供应商 TOML 缺少当前供应商配置表".to_string()))?;
provider_headers_from_table(table)
}
/// Patch Codex's native TOML fields without changing credentials or unrelated
/// provider/shared configuration. An empty list removes both header fields.
pub(crate) fn update_provider_headers_inner(
config_text: String,
mut headers: Vec<ProviderHeader>,
) -> Result<String> {
for header in &mut headers {
header.name = header.name.trim().to_string();
}
validate_provider_headers(&headers)?;
let mut doc = config_text
.parse::<DocumentMut>()
.map_err(|_| CodexxError::Config("供应商 TOML 无效,请先修正配置".to_string()))?;
let provider_id = selected_provider_id(&doc)?;
let table = doc
.get_mut("model_providers")
.and_then(Item::as_table_mut)
.and_then(|providers| providers.get_mut(&provider_id))
.and_then(Item::as_table_mut)
.ok_or_else(|| CodexxError::Config("供应商 TOML 缺少当前供应商配置表".to_string()))?;
for (field, source) in [
("http_headers", ProviderHeaderSource::Static),
("env_http_headers", ProviderHeaderSource::Env),
] {
let rows = headers
.iter()
.filter(|header| header.source == source)
.collect::<Vec<_>>();
if rows.is_empty() {
table.remove(field);
continue;
}
// Retain table style, comments and ordering for existing header names.
if table.get(field).and_then(Item::as_table_like).is_none() {
table.insert(field, Item::Table(Table::new()));
}
let values = table
.get_mut(field)
.and_then(Item::as_table_like_mut)
.unwrap();
let removed = values
.iter()
.filter(|(name, _)| !rows.iter().any(|header| header.name == *name))
.map(|(name, _)| name.to_string())
.collect::<Vec<_>>();
for name in removed {
values.remove(&name);
}
for header in rows {
if values.get(&header.name).and_then(Item::as_str) != Some(header.value.as_str()) {
values.insert(&header.name, value(header.value.clone()));
}
}
}
Ok(doc.to_string().trim_end().to_string())
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -17,6 +180,9 @@ pub(crate) struct SavedProvider {
pub(crate) api_key: Option<String>,
pub(crate) toml_config: Option<String>,
pub(crate) wire_api: String,
/// Upstream format used by the app's local bridge; Codex still speaks Responses.
#[serde(default)]
pub(crate) upstream_api: Option<String>,
pub(crate) requires_openai_auth: bool,
#[serde(default)]
pub(crate) model_mappings: Vec<super::model_catalog::ProviderModelMapping>,
@@ -182,17 +348,15 @@ pub(crate) fn provider_template_from_document(
provider_id: &str,
model: &str,
) -> Result<String> {
let provider_exists = doc
let provider_table = doc
.get("model_providers")
.and_then(|item| item.as_table())
.and_then(|providers| providers.get(provider_id))
.and_then(|item| item.as_table())
.is_some();
if !provider_exists {
return Err(CodexxError::Config(format!(
"供应商 TOML 缺少 [model_providers.{provider_id}]"
)));
}
.ok_or_else(|| {
CodexxError::Config(format!("供应商 TOML 缺少 [model_providers.{provider_id}]"))
})?;
validate_provider_header_table(provider_table)?;
let mut template = doc.clone();
template["model_provider"] = value(provider_id);
@@ -359,6 +523,7 @@ fn saved_provider_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<SavedPro
api_key: row.get(4)?,
toml_config: row.get(5)?,
wire_api: row.get(6)?,
upstream_api: row.get(9)?,
requires_openai_auth: row.get::<_, i64>(7)? != 0,
model_mappings: serde_json::from_str(&row.get::<_, String>(8)?).map_err(|error| {
rusqlite::Error::FromSqlConversionFailure(
@@ -374,7 +539,7 @@ fn stored_providers_on_connection(conn: &Connection) -> Result<Vec<StoredProvide
let mut stmt = conn
.prepare(
"SELECT id, provider_name, base_url, model, api_key, toml_config, wire_api,
requires_openai_auth, model_mappings_json, created_at, updated_at, source, source_id
requires_openai_auth, model_mappings_json, upstream_api, created_at, updated_at, source, source_id
FROM providers
ORDER BY created_at ASC, rowid ASC",
)
@@ -383,10 +548,10 @@ fn stored_providers_on_connection(conn: &Connection) -> Result<Vec<StoredProvide
.query_map([], |row| {
Ok(StoredProvider {
provider: saved_provider_from_row(row)?,
created_at: row.get(9)?,
updated_at: row.get(10)?,
source: row.get(11)?,
source_id: row.get(12)?,
created_at: row.get(10)?,
updated_at: row.get(11)?,
source: row.get(12)?,
source_id: row.get(13)?,
})
})
.map_err(|e| CodexxError::Database(e.to_string()))?;
@@ -507,7 +672,7 @@ pub(crate) fn provider_by_id_on_connection(
let mut stmt = conn
.prepare(
"SELECT id, provider_name, base_url, model, api_key, toml_config, wire_api,
requires_openai_auth, model_mappings_json
requires_openai_auth, model_mappings_json, upstream_api
FROM providers WHERE id = ?1 LIMIT 1",
)
.map_err(|e| CodexxError::Database(e.to_string()))?;
@@ -542,8 +707,8 @@ fn write_provider_with_origin(
conn.execute(
"INSERT INTO providers
(id, provider_name, base_url, model, api_key, toml_config, wire_api,
requires_openai_auth, model_mappings_json, source, source_id, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?12)
requires_openai_auth, model_mappings_json, upstream_api, source, source_id, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?13)
ON CONFLICT(id) DO UPDATE SET
provider_name = excluded.provider_name,
base_url = excluded.base_url,
@@ -553,6 +718,7 @@ fn write_provider_with_origin(
wire_api = excluded.wire_api,
requires_openai_auth = excluded.requires_openai_auth,
model_mappings_json = excluded.model_mappings_json,
upstream_api = excluded.upstream_api,
source = CASE
WHEN excluded.source_id IS NULL THEN providers.source
ELSE excluded.source
@@ -572,6 +738,7 @@ fn write_provider_with_origin(
provider.wire_api,
if provider.requires_openai_auth { 1 } else { 0 },
model_mappings_json,
provider.upstream_api,
source,
source_id,
now,
@@ -634,6 +801,11 @@ fn merge_authoritative_import(
if incoming.model_mappings.is_empty() {
incoming.model_mappings = existing.model_mappings.clone();
}
// CC Switch can refresh native TOML without knowing the local bridge's
// format selection. Keep the app metadata unless the import supplies one.
if incoming.upstream_api.is_none() {
incoming.upstream_api = existing.upstream_api.clone();
}
incoming
}
@@ -838,6 +1010,59 @@ fn normalize_stored_provider_from_toml(provider: &mut SavedProvider) {
// TOML template. Reads must trust a valid template without making one bad
// legacy row prevent the provider list from loading.
let _ = apply_provider_toml_authority(provider);
if normalize_provider_upstream_api(provider).is_ok() && provider.upstream_api.is_some() {
// Migrate legacy native Chat templates in memory, preserving comments
// and the independent bridge format instead of putting metadata in TOML.
if let Some(mut doc) = provider
.toml_config
.as_deref()
.and_then(|text| text.parse::<DocumentMut>().ok())
{
if let Ok(id) = selected_provider_id(&doc) {
if let Some(table) = doc
.get_mut("model_providers")
.and_then(Item::as_table_mut)
.and_then(|providers| providers.get_mut(&id))
.and_then(Item::as_table_mut)
{
if table.get("wire_api").and_then(Item::as_str) != Some("responses") {
table["wire_api"] = value("responses");
}
provider.toml_config = Some(doc.to_string().trim_end().to_string());
}
}
}
}
}
fn normalize_provider_upstream_api(provider: &mut SavedProvider) -> Result<()> {
if !matches!(
provider.wire_api.trim(),
"" | "responses" | "chat" | "chat_completions"
) {
return Err(CodexxError::Config(
"供应商 wire_api 不受支持;Codex 客户端仅支持 Responses,请通过上游协议选择 Chat Completions、Anthropic Messages 或 Gemini".to_string(),
));
}
let selected = provider.upstream_api.as_deref().map(str::trim);
provider.upstream_api =
match selected {
Some("responses" | "chat_completions" | "anthropic_messages" | "gemini") => {
selected.map(ToString::to_string)
}
Some(_) => return Err(CodexxError::Config(
"供应商上游协议必须是 responses、chat_completions、anthropic_messages 或 gemini"
.to_string(),
)),
None if matches!(provider.wire_api.trim(), "chat" | "chat_completions") => {
Some("chat_completions".to_string())
}
None => None,
};
if provider.upstream_api.is_some() {
provider.wire_api = "responses".to_string();
}
Ok(())
}
fn sync_provider_toml_from_fields(provider: &mut SavedProvider) -> Result<()> {
@@ -907,6 +1132,7 @@ pub(crate) fn normalize_saved_provider(provider: SavedProvider) -> Result<SavedP
} else {
provider.wire_api.trim().to_string()
},
upstream_api: provider.upstream_api,
requires_openai_auth: provider.requires_openai_auth,
model_mappings,
};
@@ -928,17 +1154,28 @@ pub(crate) fn normalize_saved_provider(provider: SavedProvider) -> Result<SavedP
// reach this path. For an explicit user edit, the latest form fields win
// while the full TOML (comments, MCP, projects, desktop settings, etc.) is
// retained verbatim apart from the standard provider fields.
normalize_provider_upstream_api(&mut normalized)?;
sync_provider_toml_from_fields(&mut normalized)?;
Ok(normalized)
}
pub(crate) fn normalize_saved_provider_for_save(
conn: &Connection,
provider: SavedProvider,
mut provider: SavedProvider,
) -> Result<SavedProvider> {
let requested_id = provider.id.trim().to_string();
let existing = provider_by_id_on_connection(conn, &requested_id)?;
if provider.upstream_api.is_none()
&& !matches!(provider.wire_api.trim(), "chat" | "chat_completions")
{
// Older clients omit this new app-only field. Preserve their existing
// route format; selecting native Responses explicitly uses Some(responses).
provider.upstream_api = existing
.as_ref()
.and_then(|saved| saved.upstream_api.clone());
}
let mut normalized = normalize_saved_provider(provider)?;
if provider_by_id_on_connection(conn, &requested_id)?.is_some() {
if existing.is_some() {
// Existing IDs are record identities. Preserve legacy reserved IDs such
// as `custom` instead of treating an edit as a new normalized record.
normalized.id = requested_id;
@@ -1021,6 +1258,7 @@ fn duplicate_provider_on_connection(
if let Some(original) = saved.iter().find(|provider| &provider.id == saved_id) {
detected.id = original.id.clone();
detected.model_mappings = original.model_mappings.clone();
detected.upstream_api = original.upstream_api.clone();
if detected.api_key.is_none() {
detected.api_key = original.api_key.clone();
}
@@ -1112,6 +1350,7 @@ pub(crate) fn save_detected_provider_with_rollback_inner(
[saved_id] => {
if let Some(saved) = saved.iter().find(|provider| &provider.id == saved_id) {
live.model_mappings = saved.model_mappings.clone();
live.upstream_api = saved.upstream_api.clone();
}
if live.api_key.is_none() {
live.api_key = saved
@@ -1148,8 +1387,8 @@ fn insert_stored_provider(conn: &Connection, stored: &StoredProvider) -> Result<
conn.execute(
"INSERT INTO providers
(id, provider_name, base_url, model, api_key, toml_config, wire_api,
requires_openai_auth, model_mappings_json, source, source_id, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)",
requires_openai_auth, model_mappings_json, upstream_api, source, source_id, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)",
params![
provider.id,
provider.provider_name,
@@ -1160,6 +1399,7 @@ fn insert_stored_provider(conn: &Connection, stored: &StoredProvider) -> Result<
provider.wire_api,
if provider.requires_openai_auth { 1 } else { 0 },
model_mappings_json,
provider.upstream_api,
stored.source,
stored.source_id,
stored.created_at,
@@ -1283,6 +1523,155 @@ pub(crate) fn experimental_bearer_token_from_doc(
mod tests {
use super::*;
const HEADER_CONFIG: &str = r#"# keep the shared configuration
model_provider = "custom"
model = "gpt-test"
[model_providers.custom]
name = "Header provider"
base_url = "https://header.example.test/v1"
wire_api = "responses"
http_headers = { "X-Title" = "Codex-X" }
env_http_headers = { "X-Project" = "PROJECT_ID" }
[model_providers.other.http_headers]
X-Other = "keep-other-provider"
[mcp_servers.keep]
command = "fixture-server"
"#;
fn header(name: &str, text: &str, source: ProviderHeaderSource) -> ProviderHeader {
ProviderHeader {
name: name.to_string(),
value: text.to_string(),
source,
}
}
#[test]
fn headers_read_patch_and_remove_only_touch_the_selected_provider() {
let rows = read_provider_headers_inner(HEADER_CONFIG.to_string()).unwrap();
assert_eq!(
rows,
vec![
header("X-Title", "Codex-X", ProviderHeaderSource::Static),
header("X-Project", "PROJECT_ID", ProviderHeaderSource::Env),
]
);
let next = update_provider_headers_inner(
HEADER_CONFIG.to_string(),
vec![
header(
" User-Agent ",
" custom agent ",
ProviderHeaderSource::Static,
),
header("X-Project", "PROJECT_ID", ProviderHeaderSource::Env),
],
)
.unwrap();
let doc = next.parse::<DocumentMut>().unwrap();
assert!(next.contains("# keep the shared configuration"));
assert_eq!(
doc["mcp_servers"]["keep"]["command"].as_str(),
Some("fixture-server")
);
assert_eq!(
doc["model_providers"]["other"]["http_headers"]["X-Other"].as_str(),
Some("keep-other-provider")
);
assert_eq!(
doc["model_providers"]["custom"]["http_headers"]["User-Agent"].as_str(),
Some(" custom agent ")
);
assert!(doc["model_providers"]["custom"]["http_headers"]
.as_table_like()
.unwrap()
.get("X-Title")
.is_none());
let removed = update_provider_headers_inner(next, Vec::new()).unwrap();
assert!(read_provider_headers_inner(removed.clone())
.unwrap()
.is_empty());
let removed = removed.parse::<DocumentMut>().unwrap();
assert!(removed["model_providers"]["custom"]
.as_table()
.unwrap()
.get("http_headers")
.is_none());
assert!(removed["model_providers"]["custom"]
.as_table()
.unwrap()
.get("env_http_headers")
.is_none());
}
#[test]
fn headers_patch_accepts_table_syntax_and_preserves_unchanged_comments() {
let text = HEADER_CONFIG.replace("http_headers = { \"X-Title\" = \"Codex-X\" }\nenv_http_headers = { \"X-Project\" = \"PROJECT_ID\" }", "[model_providers.custom.http_headers]\n# keep header comment\nX-Title = \"Codex-X\" # keep value comment\n[model_providers.custom.env_http_headers]\nX-Project = \"PROJECT_ID\"");
let rows = read_provider_headers_inner(text.clone()).unwrap();
let patched = update_provider_headers_inner(text.clone(), rows).unwrap();
assert_eq!(patched, text.trim_end());
}
#[test]
fn headers_reject_duplicate_names_and_injection_without_echoing_values() {
for rows in [
vec![
header("X-Test", "secret", ProviderHeaderSource::Static),
header("x-test", "PROJECT_ID", ProviderHeaderSource::Env),
],
vec![header("bad:name", "secret", ProviderHeaderSource::Static)],
vec![header(
"X-Test",
"secret\r\nInjected: yes",
ProviderHeaderSource::Static,
)],
vec![header("X-Test", "secret\0", ProviderHeaderSource::Static)],
vec![header(
"X-Test",
"PROJECT=secret",
ProviderHeaderSource::Env,
)],
] {
let error = update_provider_headers_inner(HEADER_CONFIG.to_string(), rows)
.unwrap_err()
.to_string();
assert!(!error.contains("secret"));
assert!(error.contains("供应商 Header"));
}
}
#[test]
fn invalid_legacy_headers_can_be_read_and_repaired_but_cannot_be_saved() {
let text = HEADER_CONFIG.replace("\"Codex-X\"", "\"secret\\r\\ninjection\"");
let rows = read_provider_headers_inner(text.clone()).unwrap();
assert_eq!(rows[0].value, "secret\r\ninjection");
let doc = text.parse::<DocumentMut>().unwrap();
assert!(provider_template_from_document(&doc, "custom", "gpt-test").is_err());
let repaired = update_provider_headers_inner(
text,
vec![header("X-Title", "safe", ProviderHeaderSource::Static)],
)
.unwrap();
assert!(provider_template_from_document(
&repaired.parse::<DocumentMut>().unwrap(),
"custom",
"gpt-test"
)
.is_ok());
}
#[test]
fn headers_reject_malformed_tables_and_non_text_values() {
for replacement in ["http_headers = 4", "http_headers = { X-Test = 4 }"] {
let text =
HEADER_CONFIG.replace("http_headers = { \"X-Title\" = \"Codex-X\" }", replacement);
assert!(read_provider_headers_inner(text).is_err());
}
}
fn test_connection() -> Connection {
let conn = Connection::open_in_memory().expect("open provider test database");
conn.execute_batch(
@@ -1292,6 +1681,7 @@ mod tests {
wire_api TEXT NOT NULL DEFAULT 'responses',
requires_openai_auth INTEGER NOT NULL DEFAULT 1,
model_mappings_json TEXT NOT NULL DEFAULT '[]',
upstream_api TEXT,
source TEXT NOT NULL DEFAULT 'manual',
source_id TEXT,
created_at TEXT NOT NULL, updated_at TEXT NOT NULL);",
@@ -1310,10 +1700,169 @@ mod tests {
toml_config: None,
wire_api: "responses".to_string(),
requires_openai_auth: true,
upstream_api: None,
model_mappings: Vec::new(),
}
}
#[test]
fn bridge_protocol_metadata_defaults_for_old_payloads_and_validates_on_save() {
let old = serde_json::json!({
"id":"old", "providerName":"Old", "baseUrl":"https://upstream.example.test/v1",
"model":"gpt-test", "apiKey":null, "tomlConfig":null,
"wireApi":"responses", "requiresOpenaiAuth":false,
});
let parsed = serde_json::from_value::<SavedProvider>(old).unwrap();
assert!(parsed.upstream_api.is_none());
for protocol in [
"responses",
"chat_completions",
"anthropic_messages",
"gemini",
] {
let mut selected = provider("bridge", "Bridge", None);
selected.upstream_api = Some(format!(" {protocol} "));
selected.toml_config = Some(HEADER_CONFIG.to_string());
let normalized = normalize_saved_provider(selected).unwrap();
assert_eq!(normalized.upstream_api.as_deref(), Some(protocol));
assert_eq!(normalized.wire_api, "responses");
let doc = normalized
.toml_config
.unwrap()
.parse::<DocumentMut>()
.unwrap();
assert_eq!(
doc["model_providers"]["custom"]["wire_api"].as_str(),
Some("responses")
);
assert!(doc["model_providers"]["custom"]
.as_table()
.unwrap()
.get("upstream_api")
.is_none());
}
let mut invalid = provider("bad-protocol", "Bad protocol", None);
invalid.upstream_api = Some("unknown".into());
assert!(normalize_saved_provider(invalid)
.unwrap_err()
.to_string()
.contains("上游协议"));
}
#[test]
fn legacy_chat_wire_api_migrates_to_independent_bridge_metadata() {
for legacy in ["chat", "chat_completions"] {
let conn = test_connection();
let mut old = provider("legacy-chat", "Legacy chat", None);
old.toml_config = Some(HEADER_CONFIG.replace(
"wire_api = \"responses\"",
&format!("wire_api = \"{legacy}\""),
));
// The TOML remains authoritative when old DB scalar columns disagree.
write_provider_on_connection(&conn, &old).unwrap();
let migrated = provider_by_id_on_connection(&conn, &old.id)
.unwrap()
.unwrap();
assert_eq!(migrated.wire_api, "responses");
assert_eq!(migrated.upstream_api.as_deref(), Some("chat_completions"));
let text = migrated.toml_config.as_ref().unwrap();
assert!(text.contains("# keep the shared configuration"));
assert_eq!(
text.parse::<DocumentMut>().unwrap()["model_providers"]["custom"]["wire_api"]
.as_str(),
Some("responses")
);
let saved = save_manual_provider_on_connection(&conn, migrated).unwrap();
assert_eq!(saved.upstream_api.as_deref(), Some("chat_completions"));
assert_eq!(
conn.query_row(
"SELECT wire_api FROM providers WHERE id=?1",
[&saved.id],
|row| row.get::<_, String>(0)
)
.unwrap(),
"responses"
);
}
}
#[test]
fn unknown_legacy_wire_api_remains_readable_and_is_rejected_on_save() {
let conn = test_connection();
let mut unknown = provider("unknown-wire", "Unknown wire", None);
unknown.wire_api = "unrecognized-wire-format".into();
write_provider_on_connection(&conn, &unknown).unwrap();
let read = provider_by_id_on_connection(&conn, &unknown.id)
.unwrap()
.unwrap();
assert_eq!(read.wire_api, "unrecognized-wire-format");
assert!(read.upstream_api.is_none());
assert!(save_manual_provider_on_connection(&conn, read)
.unwrap_err()
.to_string()
.contains("wire_api 不受支持"));
}
#[test]
fn edits_from_older_clients_keep_bridge_metadata_until_explicitly_reset() {
let conn = test_connection();
let mut configured = provider("configured", "Configured", None);
configured.upstream_api = Some("anthropic_messages".into());
let saved = save_manual_provider_on_connection(&conn, configured).unwrap();
let mut older_edit = saved.clone();
older_edit.upstream_api = None;
older_edit.provider_name = "Renamed".into();
let preserved = save_manual_provider_on_connection(&conn, older_edit).unwrap();
assert_eq!(preserved.upstream_api, saved.upstream_api);
let mut native = preserved;
native.upstream_api = Some("responses".into());
let reset = save_manual_provider_on_connection(&conn, native).unwrap();
assert_eq!(reset.upstream_api.as_deref(), Some("responses"));
}
#[test]
fn upstream_metadata_and_headers_survive_store_copy_import_refresh_and_snapshot_restore() {
let mut conn = test_connection();
let mut original = provider("gemini-bridge", "Gemini bridge", Some("fixture-key"));
original.upstream_api = Some("gemini".into());
original.toml_config = Some(HEADER_CONFIG.to_string());
let original = normalize_saved_provider(original).unwrap();
let saved =
upsert_ccswitch_provider_on_connection(&conn, original.clone(), "ccswitch-fixture")
.unwrap()
.provider;
assert_eq!(saved.upstream_api.as_deref(), Some("gemini"));
let copied = duplicate_provider_on_connection(
&mut conn,
std::path::Path::new("/fixture/upstream-copy"),
None,
Some(&saved.id),
None,
)
.unwrap()
.provider;
assert_eq!(copied.upstream_api, saved.upstream_api);
assert_eq!(
read_provider_headers_inner(copied.toml_config.unwrap()).unwrap(),
read_provider_headers_inner(saved.toml_config.clone().unwrap()).unwrap()
);
let mut incoming = original;
incoming.upstream_api = None;
let refreshed = upsert_ccswitch_provider_on_connection(&conn, incoming, "ccswitch-fixture")
.unwrap()
.provider;
assert_eq!(refreshed.upstream_api.as_deref(), Some("gemini"));
let snapshots = stored_providers_on_connection(&conn).unwrap();
let restored = test_connection();
for snapshot in &snapshots {
insert_stored_provider(&restored, snapshot).unwrap();
}
assert_eq!(
stored_providers_on_connection(&restored).unwrap(),
snapshots
);
}
fn provider_count(conn: &Connection) -> usize {
list_saved_providers_on_connection(conn).unwrap().len()
}
@@ -2130,6 +2679,7 @@ enabled = true
toml_config: Some("\n".to_string()),
wire_api: String::new(),
requires_openai_auth: false,
upstream_api: None,
model_mappings: Vec::new(),
};
let result = upsert_ccswitch_provider_on_connection(&conn, missing, "cc-row")
@@ -2374,7 +2924,8 @@ command = "keep-this-command"
assert_eq!(normalized.provider_name, "Edited Name");
assert_eq!(normalized.base_url, "https://edited.example.com/v1");
assert_eq!(normalized.model, "edited-model");
assert_eq!(normalized.wire_api, "chat_completions");
assert_eq!(normalized.wire_api, "responses");
assert_eq!(normalized.upstream_api.as_deref(), Some("chat_completions"));
assert!(!normalized.requires_openai_auth);
assert_eq!(doc["model"].as_str(), Some("edited-model"));
assert_eq!(
@@ -2387,7 +2938,7 @@ command = "keep-this-command"
);
assert_eq!(
doc["model_providers"]["proxy"]["wire_api"].as_str(),
Some("chat_completions")
Some("responses")
);
assert_eq!(
doc["model_providers"]["proxy"]["requires_openai_auth"].as_bool(),
@@ -0,0 +1,409 @@
// Every source, SQLite database, backup and lock in these tests is temporary.
fn compress_rollout(logical: &Path) -> std::path::PathBuf {
let compressed = logical.with_extension("jsonl.zst");
let mut source = fs::File::open(logical).unwrap();
let output = fs::File::create(&compressed).unwrap();
let mut encoder = zstd::stream::write::Encoder::new(output, 1).unwrap();
std::io::copy(&mut source, &mut encoder).unwrap();
encoder.finish().unwrap();
drop(source);
fs::remove_file(logical).unwrap();
compressed
}
fn decoded(path: &Path) -> Vec<u8> {
let mut source = super::super::super::rollout_stream::decoded_rollout_reader(
fs::File::open(path).unwrap(),
path,
)
.unwrap();
let mut bytes = Vec::new();
source.read_to_end(&mut bytes).unwrap();
bytes
}
fn indexed_compressed_fixture(
label: &str,
) -> (
std::path::PathBuf,
String,
std::path::PathBuf,
std::path::PathBuf,
) {
let dir = temp_codex_dir(label);
write_config(&dir, SHARED_SESSION_PROVIDER);
let id = "01a0e854-0000-7000-8000-000000000001".to_string();
let logical = write_rollout(&dir, &id, "openai");
create_thread_database_with_rollout(&dir.join("state_5.sqlite"), &id, "openai", &logical);
let compressed = compress_rollout(&logical);
(dir, id, logical, compressed)
}
#[test]
fn compressed_logical_reference_syncs_and_keeps_sqlite_alias_and_content() {
let (dir, id, logical, compressed) = indexed_compressed_fixture("zst-logical-alias");
let mut text = decoded(&compressed);
text.extend_from_slice(b"\r\n{\"type\":\"event_msg\",\"payload\":{\"message\":\"untouched\\ntext\",\"unicode\":\"\xe4\xb8\xad\xe6\x96\x87\"}}");
fs::write(
&compressed,
zstd::stream::encode_all(text.as_slice(), 1).unwrap(),
)
.unwrap();
let original = fs::read(&compressed).unwrap();
let database = dir.join("state_5.sqlite");
Connection::open(&database)
.unwrap()
.execute("UPDATE threads SET title='renamed title'", [])
.unwrap();
let status = session_sync_status_inner(Some(dir.display().to_string()), None).unwrap();
assert!(status.scan_complete, "{:?}", status.scan_failures);
assert!(status.needs_sync);
assert_eq!(status.rollout_files, 1);
assert_eq!(status.sessions[0].title, "renamed title");
assert_eq!(
fs::read(&compressed).unwrap(),
original,
"status is read-only"
);
let result = sync_sessions_provider_inner(Some(dir.display().to_string()), None).unwrap();
assert!(result.status.scan_complete);
assert!(!result.status.needs_sync);
assert_eq!(result.updated_rollouts, 1);
assert_eq!(thread_provider(&database, &id), SHARED_SESSION_PROVIDER);
let expected = String::from_utf8(text).unwrap().replace(
"\"model_provider\":\"openai\"",
"\"model_provider\":\"custom\"",
);
assert_eq!(decoded(&compressed), expected.as_bytes());
let stored: String = Connection::open(&database)
.unwrap()
.query_row(
"SELECT rollout_path FROM threads WHERE id=?1",
[&id],
|row| row.get(0),
)
.unwrap();
assert_eq!(stored, logical.display().to_string());
assert!(
!logical.exists(),
"sync must not expand or rename logical storage"
);
let next = fs::read(&compressed).unwrap();
let again = sync_sessions_provider_inner(Some(dir.display().to_string()), None).unwrap();
assert_eq!(again.updated_rollouts, 0);
assert_eq!(again.updated_threads, 0);
assert!(again.backup_dir.is_empty());
assert_eq!(
fs::read(&compressed).unwrap(),
next,
"matched compressed bytes stay identical"
);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn plain_rollout_wins_over_stale_compressed_sibling() {
let (dir, id, logical, compressed) = indexed_compressed_fixture("zst-plain-priority");
let stale = fs::read(&compressed).unwrap();
write_rollout_at(&logical, &id, "openai");
let result = sync_sessions_provider_inner(Some(dir.display().to_string()), None).unwrap();
assert!(
result.status.scan_complete,
"{:?}",
result.status.scan_failures
);
assert_eq!(result.updated_rollouts, 1);
assert_eq!(result.status.rollout_files, 1);
assert_eq!(fs::read(&compressed).unwrap(), stale);
assert!(fs::read_to_string(&logical)
.unwrap()
.contains("\"model_provider\":\"custom\""));
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn compressed_archive_and_internal_threads_are_not_promoted_or_modified() {
let (dir, id, logical, compressed) = indexed_compressed_fixture("zst-hidden-threads");
let database = dir.join("state_5.sqlite");
let archived_id = "01a0e854-0000-7000-8000-000000000002";
let archived_logical = dir.join(format!(
"archived_sessions/rollout-test-{archived_id}.jsonl"
));
write_rollout_at(&archived_logical, archived_id, "openai");
let archived = compress_rollout(&archived_logical);
let internal_id = "01a0e854-0000-7000-8000-000000000003";
let internal_logical = write_rollout(&dir, internal_id, "openai");
fs::write(&internal_logical, format!("{{\"type\":\"session_meta\",\"payload\":{{\"id\":\"{internal_id}\",\"source\":{{\"internal\":\"guardian\"}},\"model_provider\":\"openai\"}}}}\n")).unwrap();
let internal = compress_rollout(&internal_logical);
let archive_bytes = fs::read(&archived).unwrap();
let internal_bytes = fs::read(&internal).unwrap();
let conn = Connection::open(&database).unwrap();
for (thread, path, archived) in [
(archived_id, &archived_logical, 1),
(internal_id, &internal_logical, 0),
] {
conn.execute("INSERT INTO threads(id,model_provider,rollout_path,archived) VALUES(?1,'openai',?2,?3)", (thread, path.display().to_string(), archived)).unwrap();
}
drop(conn);
let catalog = dir.join("sqlite/codex-dev.db");
create_catalog_database(&catalog, &[]);
let result = sync_sessions_provider_inner(Some(dir.display().to_string()), None).unwrap();
assert!(
result.status.scan_complete,
"{:?}",
result.status.scan_failures
);
assert!(!result.status.needs_sync);
assert_eq!(result.updated_rollouts, 1);
assert_eq!(thread_provider(&database, &id), SHARED_SESSION_PROVIDER);
assert_eq!(thread_provider(&database, internal_id), "openai");
assert_eq!(thread_provider(&database, archived_id), "openai");
assert_eq!(fs::read(&archived).unwrap(), archive_bytes);
assert_eq!(fs::read(&internal).unwrap(), internal_bytes);
assert!(catalog_provider_and_visibility(&catalog, internal_id).is_none());
assert!(catalog_provider_and_visibility(&catalog, archived_id).is_none());
assert_eq!(
result
.status
.sessions
.iter()
.find(|row| row.id == internal_id)
.unwrap()
.is_subagent,
true
);
assert!(!logical.exists());
assert!(compressed.exists());
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn compressed_revert_uses_thread_id_and_current_alias_for_internal_classification() {
let dir = temp_codex_dir("zst-revert-identity");
write_config(&dir, SHARED_SESSION_PROVIDER);
let thread = "01a0e854-0000-7000-8000-000000000004";
let rollout = "01a0e854-0000-7000-8000-000000000005";
let old = write_rollout(&dir, thread, "openai");
fs::write(&old, format!("{{\"type\":\"session_meta\",\"payload\":{{\"id\":\"{thread}\",\"source\":\"subagent\",\"model_provider\":\"openai\"}}}}\n")).unwrap();
let old = compress_rollout(&old);
let old_bytes = fs::read(&old).unwrap();
let current = dir.join(format!(
"sessions/2026/10/01/rollout-2026-10-01-{thread}_{rollout}.jsonl"
));
write_rollout_at(&current, thread, "openai");
let compressed = compress_rollout(&current);
let database = dir.join("state_5.sqlite");
create_thread_database_with_rollout(&database, thread, "openai", &current);
let catalog = dir.join("sqlite/codex-dev.db");
create_catalog_database(&catalog, &[]);
let result = sync_sessions_provider_inner(Some(dir.display().to_string()), None).unwrap();
assert!(
result.status.scan_complete,
"{:?}",
result.status.scan_failures
);
assert_eq!(result.updated_rollouts, 1);
assert_eq!(thread_provider(&database, thread), SHARED_SESSION_PROVIDER);
assert!(catalog_provider_and_visibility(&catalog, rollout).is_none());
assert_eq!(fs::read(&old).unwrap(), old_bytes);
assert!(String::from_utf8(decoded(&compressed))
.unwrap()
.contains("\"model_provider\":\"custom\""));
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn corrupted_or_truncated_compressed_reference_never_reports_synced() {
for invalid in [b"not zstandard".to_vec(), {
let mut compressed = zstd::stream::encode_all(&b"{\"type\":\"session_meta\",\"payload\":{\"id\":\"t\",\"model_provider\":\"custom\"}}\n"[..], 1).unwrap();
compressed.truncate(compressed.len() - 4);
compressed
}] {
let (dir, id, _logical, compressed) = indexed_compressed_fixture("zst-corrupt");
fs::write(&compressed, &invalid).unwrap();
let status = session_sync_status_inner(Some(dir.display().to_string()), None).unwrap();
assert!(!status.scan_complete);
assert!(!status.scan_failures.is_empty());
sync_sessions_provider_inner(Some(dir.display().to_string()), None)
.expect_err("invalid compressed data blocks every mutation");
assert_eq!(thread_provider(&dir.join("state_5.sqlite"), &id), "openai");
assert_eq!(fs::read(&compressed).unwrap(), invalid);
fs::remove_dir_all(dir).unwrap();
}
}
#[test]
fn compressed_transaction_rollback_restores_exact_original_compressed_bytes() {
let (dir, id, _logical, compressed) = indexed_compressed_fixture("zst-rollback");
let original = fs::read(&compressed).unwrap();
let error = sync_sessions_provider_with_hook(Some(dir.display().to_string()), None, |point| {
if point == MutationPoint::AfterSqliteCommit(0) {
assert_ne!(fs::read(&compressed).unwrap(), original);
return Err(CodexxError::Config("fixture rollback".into()));
}
Ok(())
})
.unwrap_err();
assert!(error.to_string().contains("fixture rollback"));
assert_eq!(fs::read(&compressed).unwrap(), original);
assert_eq!(thread_provider(&dir.join("state_5.sqlite"), &id), "openai");
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn compressed_source_replacement_or_expansion_during_sync_aborts_without_overwrite() {
for expansion in [false, true] {
for point_to_change in [
MutationPoint::BeforeRolloutMutation,
MutationPoint::BeforeEachRolloutMutation(0),
] {
let (dir, id, logical, compressed) =
indexed_compressed_fixture("zst-concurrent-representation");
let original = fs::read(&compressed).unwrap();
let external = format!("{{\"type\":\"session_meta\",\"payload\":{{\"id\":\"{id}\",\"model_provider\":\"external\"}}}}\n").into_bytes();
let external_compressed = zstd::stream::encode_all(external.as_slice(), 1).unwrap();
sync_sessions_provider_with_hook(Some(dir.display().to_string()), None, |point| {
if point == point_to_change {
if expansion {
fs::write(&logical, &external).unwrap();
} else {
fs::write(&compressed, &external_compressed).unwrap();
}
}
Ok(())
})
.expect_err("external replacement/expansion must abort synchronization");
assert_eq!(thread_provider(&dir.join("state_5.sqlite"), &id), "openai");
if expansion {
assert_eq!(fs::read(&logical).unwrap(), external);
assert_eq!(fs::read(&compressed).unwrap(), original);
} else {
assert_eq!(fs::read(&compressed).unwrap(), external_compressed);
}
fs::remove_dir_all(dir).unwrap();
}
}
}
#[test]
fn compressed_reference_with_wrong_metadata_id_blocks_sync_without_uuid_reassociation() {
let (dir, id, logical, compressed) = indexed_compressed_fixture("zst-wrong-identity");
let other = "01a0e854-0000-7000-8000-000000000009";
let wrong = format!("{{\"type\":\"session_meta\",\"payload\":{{\"id\":\"{other}\",\"model_provider\":\"openai\"}}}}\n");
let bytes = zstd::stream::encode_all(wrong.as_bytes(), 1).unwrap();
fs::write(&compressed, &bytes).unwrap();
// A different file with the right ID must not replace an explicit current alias.
let fallback = dir.join(format!("sessions/history/rollout-old-{id}.jsonl"));
write_rollout_at(&fallback, &id, "openai");
let status = session_sync_status_inner(Some(dir.display().to_string()), None).unwrap();
assert!(!status.scan_complete);
assert!(status
.scan_failures
.iter()
.any(|failure| failure.contains("线程 ID 不一致")));
sync_sessions_provider_inner(Some(dir.display().to_string()), None).unwrap_err();
assert_eq!(fs::read(&compressed).unwrap(), bytes);
assert_eq!(thread_provider(&dir.join("state_5.sqlite"), &id), "openai");
assert!(!logical.exists());
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn active_reference_moved_to_compressed_archive_is_reported_as_archive_conflict() {
let (dir, id, logical, compressed) = indexed_compressed_fixture("zst-archive-conflict");
let archived = dir
.join("archived_sessions")
.join(compressed.file_name().unwrap());
fs::create_dir_all(archived.parent().unwrap()).unwrap();
fs::rename(&compressed, &archived).unwrap();
let bytes = fs::read(&archived).unwrap();
let status = session_sync_status_inner(Some(dir.display().to_string()), None).unwrap();
assert!(!status.scan_complete);
assert!(status
.scan_failures
.iter()
.any(|failure| failure.contains("归档状态不一致")
&& failure.contains(&id)
&& failure.contains(&logical.display().to_string())
&& failure.contains(&archived.display().to_string())));
assert!(!status
.scan_failures
.iter()
.any(|failure| failure.contains("均缺失")));
sync_sessions_provider_inner(Some(dir.display().to_string()), None).unwrap_err();
assert_eq!(fs::read(&archived).unwrap(), bytes);
assert_eq!(thread_provider(&dir.join("state_5.sqlite"), &id), "openai");
assert!(!logical.exists());
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn compressed_expansion_after_commit_preserves_external_plain_log_and_retains_backup() {
let (dir, id, logical, compressed) = indexed_compressed_fixture("zst-expansion-after-commit");
let external = format!("{{\"type\":\"session_meta\",\"payload\":{{\"id\":\"{id}\",\"model_provider\":\"external\"}}}}\n");
let error = sync_sessions_provider_with_hook(Some(dir.display().to_string()), None, |point| {
if point == MutationPoint::AfterSqliteCommit(0) {
fs::write(&logical, external.as_bytes()).unwrap();
}
Ok(())
})
.expect_err("postcommit expansion must not be mistaken for a successful synchronization");
assert!(error.to_string().contains("变化") || error.to_string().contains("回滚"));
assert_eq!(fs::read(&logical).unwrap(), external.as_bytes());
assert_eq!(thread_provider(&dir.join("state_5.sqlite"), &id), "openai");
assert!(compressed.exists());
let backups = crate::sessions::provider_sync_backup_root(&dir);
assert!(fs::read_dir(backups).unwrap().next().is_some());
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn provider_can_really_switch_during_sync_while_session_target_stays_fixed() {
let _app_db_guard = crate::app_db::test_db_guard();
let dir = temp_codex_dir("provider-switch-during-session-sync");
write_config(&dir, "openai");
let id = "01a0e854-0000-7000-8000-000000000011";
let logical = write_rollout(&dir, id, "historical-provider");
let compressed = compress_rollout(&logical);
let database = dir.join("state_5.sqlite");
create_thread_database_with_rollout(&database, id, "historical-provider", &logical);
let mut switched = false;
let result = sync_sessions_provider_with_hook(Some(dir.display().to_string()), None, |point| {
if point == MutationPoint::BeforeSqliteLock {
crate::providers::switch_provider_inner(crate::providers::ProviderInput {
config_dir: Some(dir.display().to_string()),
provider_id: Some("session-sync-switch-fixture".into()),
provider_name: "Session sync switch fixture".into(),
base_url: "https://session-sync-fixture.invalid/v1".into(),
model: "fixture-model".into(),
api_key: Some("fixture-key-never-sent".into()),
wire_api: Some("responses".into()),
requires_openai_auth: None,
})?;
assert_eq!(current_model_provider(&dir, None)?, "custom");
switched = true;
}
Ok(())
})
.unwrap();
assert!(
switched,
"the real provider switch ran while the maintenance lock was held"
);
assert_eq!(result.status.target_provider, "openai");
assert!(!result.status.needs_sync);
assert_eq!(thread_provider(&database, id), "openai");
assert!(String::from_utf8(decoded(&compressed))
.unwrap()
.contains("\"model_provider\":\"openai\""));
assert_eq!(current_model_provider(&dir, None).unwrap(), "custom");
let current = session_sync_status_inner(Some(dir.display().to_string()), None).unwrap();
assert_eq!(current.target_provider, "custom");
assert!(
current.needs_sync,
"a new explicit status read sees the new target, without stale scan caching"
);
let live_config = fs::read_to_string(dir.join("config.toml")).unwrap();
assert!(live_config.contains("https://session-sync-fixture.invalid/v1"));
fs::remove_dir_all(dir).unwrap();
}
+148 -17
View File
@@ -1,5 +1,7 @@
use super::app_server::delete_sessions_via_codex_app_server;
use super::rollout_stream::{for_each_jsonl_record, record_matches_top_level_strings};
use super::rollout_stream::{
for_each_jsonl_record, record_matches_top_level_strings, resolved_rollout_path,
};
use super::storage::{
current_model_provider, discover_sqlite_databases, ensure_sqlite_discovery_writable,
is_canonical_rollout_storage_path, rollout_filename_matches_id, scan_rollouts,
@@ -404,9 +406,11 @@ fn canonical_rollout_path(codex_dir: &Path, value: &str, id: &str) -> Result<Opt
} else {
codex_dir.join(raw)
};
if !path.exists() {
return Ok(None);
}
let path = match resolved_rollout_path(&path) {
Ok(path) => path,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(io_err(&path, error)),
};
if !rollout_filename_matches_id(&path, id) {
return Err(CodexxError::Config(format!(
"会话文件名与 ID 不匹配,已拒绝删除: {}",
@@ -730,7 +734,7 @@ fn preflight_session_jsonl_cleanup(codex_dir: &Path) -> Result<()> {
fn commit_index_cleanup(
path: &Path,
source: &fs::File,
source: fs::File,
prepared: PreparedJsonlCleanup,
) -> Result<usize> {
if prepared.removed == 0 {
@@ -738,7 +742,7 @@ fn commit_index_cleanup(
}
ensure_cleanup_source_unchanged(
path,
source,
&source,
&prepared.original_stamp,
&prepared.original_hash,
)?;
@@ -750,11 +754,40 @@ fn commit_index_cleanup(
.output
.as_file()
.set_permissions(permissions)
.map_err(|error| io_err(path, error))?;
prepared
.output
.persist(path)
.map_err(|error| io_err(path, error.error))?;
.map_err(|error| {
io_err(
path,
std::io::Error::new(error.kind(), format!("设置临时会话索引权限失败: {error}")),
)
})?;
// tempfile's Windows persist uses SetFileAttributesW followed by MoveFileExW.
// Close both our destination and staging handles before that replacement;
// the index has no history-style inode/append-lock requirement.
drop(source);
let output = prepared.output.into_temp_path();
let verifier = fs::File::open(path).map_err(|error| {
io_err(
path,
std::io::Error::new(error.kind(), format!("最终复核会话索引失败: {error}")),
)
})?;
let unchanged = ensure_cleanup_source_unchanged(
path,
&verifier,
&prepared.original_stamp,
&prepared.original_hash,
);
drop(verifier);
unchanged?;
output.persist(path).map_err(|error| {
io_err(
path,
std::io::Error::new(
error.error.kind(),
format!("原子替换会话索引失败: {}", error.error),
),
)
})?;
Ok(prepared.removed)
}
@@ -769,7 +802,7 @@ fn remove_jsonl_session_entries(
Err(error) => return Err(io_err(path, error)),
};
let prepared = prepare_jsonl_cleanup(path, &mut source, id_keys, session_ids, false)?;
commit_index_cleanup(path, &source, prepared)
commit_index_cleanup(path, source, prepared)
}
fn remove_session_index_entries(codex_dir: &Path, session_ids: &HashSet<String>) -> Result<usize> {
@@ -1370,6 +1403,26 @@ mod tests {
.expect("insert thread");
}
#[test]
fn deletion_target_resolves_compressed_logical_alias_without_selecting_another_history() {
let codex_dir = temp_codex_dir();
let id = "01a0e854-0000-7000-8000-000000000001";
let logical = codex_dir.join(format!("sessions/rollout-current-{id}.jsonl"));
fs::create_dir_all(logical.parent().unwrap()).unwrap();
let compressed = logical.with_extension("jsonl.zst");
fs::write(
&compressed,
zstd::stream::encode_all(&b"{}\n"[..], 1).unwrap(),
)
.unwrap();
let found = canonical_rollout_path(&codex_dir, &logical.display().to_string(), id).unwrap();
assert_eq!(found, Some(compressed.canonicalize().unwrap()));
fs::write(&logical, b"{}\n").unwrap();
let found = canonical_rollout_path(&codex_dir, &logical.display().to_string(), id).unwrap();
assert_eq!(found, Some(logical.canonicalize().unwrap()));
fs::remove_dir_all(codex_dir).unwrap();
}
#[test]
fn deletion_verification_checks_second_visible_database() {
let codex_dir = temp_codex_dir();
@@ -1777,22 +1830,100 @@ mod tests {
drop(external);
let grown = fs::read(&path).unwrap();
let result = if history {
commit_history_cleanup_with_writer(&path, &mut source, prepared, |_, _, _, _| {
panic!("growth must be rejected before writing history")
})
let result = commit_history_cleanup_with_writer(
&path,
&mut source,
prepared,
|_, _, _, _| panic!("growth must be rejected before writing history"),
);
drop(source);
result
} else {
commit_index_cleanup(&path, &source, prepared)
commit_index_cleanup(&path, source, prepared)
};
assert!(result
.expect_err("a stale staged result must not replace appended data")
.to_string()
.contains("发生变化"));
assert_eq!(fs::read(&path).unwrap(), grown);
drop(source);
fs::remove_dir_all(codex_dir).unwrap();
}
}
#[cfg(windows)]
#[test]
fn index_replacement_closes_a_delete_denying_source_handle_and_preserves_all_kept_bytes() {
use std::os::windows::fs::OpenOptionsExt;
use windows_sys::Win32::Storage::FileSystem::{FILE_SHARE_READ, FILE_SHARE_WRITE};
let codex_dir = temp_codex_dir();
let path = codex_dir.join("session_index.jsonl");
fs::write(
&path,
b"{\"id\":\"selected\"}\r\nnot-json\r\n{\"id\":\"kept\"}",
)
.unwrap();
let mut initial = fs::File::open(&path).unwrap();
let prepared = prepare_jsonl_cleanup(
&path,
&mut initial,
&["id"],
&HashSet::from(["selected".to_string()]),
false,
)
.unwrap();
drop(initial);
// Allow all verification reads while denying DELETE sharing, which is
// specifically required for Windows rename/replacement operations.
let source = fs::OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
.open(&path)
.unwrap();
assert_eq!(commit_index_cleanup(&path, source, prepared).unwrap(), 1);
assert_eq!(fs::read(&path).unwrap(), b"not-json\r\n{\"id\":\"kept\"}");
fs::remove_dir_all(codex_dir).unwrap();
}
#[test]
fn index_replacement_rejects_same_length_modified_bytes_even_with_restored_mtime() {
let codex_dir = temp_codex_dir();
let path = codex_dir.join("session_index.jsonl");
let original = b"{\"id\":\"selected\"}\n{\"id\":\"kept\"}\n";
fs::write(&path, original).unwrap();
let mut source = fs::File::open(&path).unwrap();
let prepared = prepare_jsonl_cleanup(
&path,
&mut source,
&["id"],
&HashSet::from(["selected".to_string()]),
false,
)
.unwrap();
let mtime = prepared.original_stamp.modified.unwrap();
let mut changed = original.to_vec();
let last = changed.iter().rposition(|byte| *byte == b't').unwrap();
changed[last] = b'x';
let mut external = fs::OpenOptions::new().write(true).open(&path).unwrap();
external.write_all(&changed).unwrap();
external.sync_all().unwrap();
drop(external);
// Set the timestamp through a fresh handle after closing the data writer;
// Windows may otherwise finalize a pending write time when it closes.
let timestamp = fs::OpenOptions::new().write(true).open(&path).unwrap();
timestamp
.set_times(fs::FileTimes::new().set_modified(mtime))
.unwrap();
drop(timestamp);
assert_eq!(fs::metadata(&path).unwrap().modified().unwrap(), mtime);
assert_eq!(fs::metadata(&path).unwrap().len(), original.len() as u64);
let error = commit_index_cleanup(&path, source, prepared)
.expect_err("a matching length and timestamp must not bypass the source digest");
assert!(error.to_string().contains("发生变化"));
assert_eq!(fs::read(&path).unwrap(), changed);
fs::remove_dir_all(codex_dir).unwrap();
}
#[test]
fn history_commit_write_failure_restores_backup_and_keeps_its_lock_and_inode() {
for fail_after_truncate in [false, true] {
@@ -175,6 +175,7 @@ fn directory_lookup(path: &str) -> DirectoryIdentity {
.unwrap_or_else(|_| unresolved_directory_identity(path))
}
#[cfg(test)]
fn directory_identity(path: &str) -> String {
directory_lookup(path).key
}
@@ -187,9 +188,11 @@ fn pin_scope_key(path: &str, identity: &DirectoryIdentity) -> String {
}
}
/// Resolve the paths represented by this status only. The raw spelling remains
/// the map key. Persistent home scope uses native identity only when birth time
/// was verified; otherwise it conservatively follows the original home path.
/// The explicitly selected Codex home may use its native identity. Historical
/// workspace paths remain lexical: opening or probing them merely to group
/// sessions can request access to protected macOS folders such as Documents.
/// Preserve their complete spelling on every platform; without inspecting a
/// directory, volume defaults cannot exclude per-directory case sensitivity.
pub(super) fn session_directory_identities(
codex_dir: &Path,
sessions: &[SessionPreview],
@@ -202,7 +205,7 @@ pub(super) fn session_directory_identities(
for path in sessions.iter().filter_map(|session| session.cwd.as_deref()) {
identities
.entry(path.to_string())
.or_insert_with(|| directory_identity(path));
.or_insert_with(|| unresolved_directory_identity(path).key);
}
(identities, pin_scope)
}
@@ -366,7 +369,9 @@ mod tests {
#[test]
fn creation_generation_includes_epoch_sign_full_seconds_and_nanoseconds() {
use std::time::Duration;
let created = UNIX_EPOCH + Duration::new(1234, 17);
// Windows SystemTime uses 100 ns intervals; use exactly representable
// fractions while still testing that subsecond birth precision matters.
let created = UNIX_EPOCH + Duration::new(1234, 100);
let original = unix_directory_identity(1, 9, Some(created)).unwrap();
assert!(original.birth_verified);
assert_eq!(
@@ -374,9 +379,9 @@ mod tests {
unix_directory_identity(1, 9, Some(created)).unwrap()
);
for new_generation in [
UNIX_EPOCH + Duration::new(1234, 18),
UNIX_EPOCH + Duration::new(1234 + (1u64 << 32), 17),
UNIX_EPOCH - Duration::new(1234, 17),
UNIX_EPOCH + Duration::new(1234, 200),
UNIX_EPOCH + Duration::new(1234 + (1u64 << 32), 100),
UNIX_EPOCH - Duration::new(1234, 100),
] {
assert_ne!(
original,
@@ -387,7 +392,7 @@ mod tests {
let file_id = [7; 16];
assert_ne!(
windows_directory_identity(1, &file_id, Some(created)),
windows_directory_identity(1, &file_id, Some(created + Duration::from_nanos(1)))
windows_directory_identity(1, &file_id, Some(created + Duration::from_nanos(100)))
);
}
+131 -4
View File
@@ -1,3 +1,4 @@
use super::rollout_stream::{decoded_rollout_reader, resolved_rollout_path};
use super::storage::{
is_canonical_rollout_storage_path, list_session_previews_with_paths, session_project_title,
sqlite_candidate_paths,
@@ -187,6 +188,7 @@ struct JsonLine<'a, R: BufRead> {
buffered: usize,
buffer_ends_line: bool,
has_content: bool,
too_large: bool,
}
impl<R: BufRead> Read for JsonLine<'_, R> {
fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {
@@ -199,6 +201,7 @@ impl<R: BufRead> Read for JsonLine<'_, R> {
return Ok(0);
}
if self.consumed >= MAX_RECORD_BYTES {
self.too_large = true;
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"record too large",
@@ -240,13 +243,16 @@ fn drain_line<R: BufRead>(reader: &mut R) -> std::io::Result<()> {
fn visit_records(
file: &mut File,
path: &Path,
length: u64,
expected_id: &str,
mut visitor: impl FnMut(Message) -> Result<()>,
) -> Result<usize> {
file.seek(SeekFrom::Start(0))
.map_err(|error| CodexxError::Config(format!("无法读取会话:{error}")))?;
let mut reader = BufReader::new(file.take(length));
let decoded =
decoded_rollout_reader(file.take(length), path).map_err(|error| io_err(path, error))?;
let mut reader = BufReader::new(decoded);
let mut malformed = 0;
let mut verified_meta = false;
loop {
@@ -264,8 +270,14 @@ fn visit_records(
buffered: 0,
buffer_ends_line: false,
has_content: false,
too_large: false,
};
let parsed = serde_json::from_reader::<_, Record>(&mut line);
if let Err(error) = &parsed {
if error.is_io() && !line.too_large {
return Err(CodexxError::Config(format!("无法读取会话:{error}")));
}
}
let ended = line.ended;
let has_content = line.has_content;
if !ended {
@@ -315,10 +327,12 @@ fn safe_rollout_path(codex_dir: &Path, session: &SessionPreview) -> Result<PathB
} else {
codex_dir.join(path)
};
let path = resolved_rollout_path(&path).map_err(|error| io_err(&path, error))?;
let metadata = fs::symlink_metadata(&path).map_err(|error| io_err(&path, error))?;
if !metadata.is_file()
|| metadata.file_type().is_symlink()
|| !path.to_string_lossy().ends_with(".jsonl")
|| !(path.to_string_lossy().ends_with(".jsonl")
|| path.to_string_lossy().ends_with(".jsonl.zst"))
{
return Err(CodexxError::Config("不支持此会话文件类型".to_string()));
}
@@ -351,7 +365,7 @@ fn write_markdown(codex_dir: &Path, session: &SessionPreview, output: &mut File)
let mut file = File::open(&path).map_err(|error| io_err(&path, error))?;
let length = file.metadata().map_err(|error| io_err(&path, error))?.len();
let mut event_counts = HashMap::<[u8; 32], usize>::new();
let malformed = visit_records(&mut file, length, &session.id, |message| {
let malformed = visit_records(&mut file, &path, length, &session.id, |message| {
if message.event {
if event_counts.len() >= MAX_MESSAGE_KEYS {
return Err(CodexxError::Config(
@@ -388,7 +402,7 @@ fn write_markdown(codex_dir: &Path, session: &SessionPreview, output: &mut File)
markdown_label(&session.id)
))?;
let mut count = 0;
visit_records(&mut file, length, &session.id, |message| {
visit_records(&mut file, &path, length, &session.id, |message| {
if !message.event {
if let Some(remaining) = event_counts.get_mut(&message_key(&message)) {
if *remaining > 0 {
@@ -712,6 +726,119 @@ mod tests {
json!({"type":"response_item","timestamp":"2026-09-12T10:00:00Z","payload":{"type":"message","role":role,"content":[{"type":if role == "user" { "input_text" } else { "output_text" },"text":body}]}})
}
fn compress_fixture(path: &Path) -> PathBuf {
let compressed = path.with_extension("jsonl.zst");
let mut input = File::open(path).unwrap();
let mut encoder =
zstd::stream::write::Encoder::new(File::create(&compressed).unwrap(), 1).unwrap();
encoder.include_checksum(true).unwrap();
std::io::copy(&mut input, &mut encoder).unwrap();
encoder.finish().unwrap();
drop(input);
fs::remove_file(path).unwrap();
compressed
}
#[test]
fn exports_compressed_logical_reference_with_same_deduplication_and_no_storage_changes() {
let fixture = Fixture::new();
let path = fixture.add(
"compressed",
"已改名的会话",
&[
event("user", "中文问题"),
response("user", "中文问题"),
response("assistant", "完整回答"),
],
false,
);
let expected = fixture.export(&["compressed"], "plain.md").unwrap();
let compressed = compress_fixture(&path);
let raw_before = fs::read(&compressed).unwrap();
let db_before = fs::read(&fixture.database).unwrap();
let result = fixture.export(&["compressed"], "compressed.md").unwrap();
assert_eq!(
fs::read(result.path).unwrap(),
fs::read(expected.path).unwrap()
);
assert_eq!(result.failed_sessions, 0);
assert!(result.warnings.is_empty());
assert!(!path.exists());
assert_eq!(fs::read(compressed).unwrap(), raw_before);
assert_eq!(fs::read(&fixture.database).unwrap(), db_before);
}
#[test]
fn export_prefers_current_plain_file_over_stale_compressed_sibling() {
let fixture = Fixture::new();
let path = fixture.add("current", "当前会话", &[event("user", "stale body")], false);
let compressed = compress_fixture(&path);
fs::write(
&path,
format!(
"{}\n{}\n",
json!({"type":"session_meta","payload":{"id":"current"}}),
event("user", "current body")
),
)
.unwrap();
let before = fs::read(&compressed).unwrap();
let result = fixture.export(&["current"], "current.md").unwrap();
let text = fs::read_to_string(result.path).unwrap();
assert!(text.contains("current body"));
assert!(!text.contains("stale body"));
assert_eq!(fs::read(compressed).unwrap(), before);
}
#[test]
fn corrupt_compression_is_an_error_and_preserves_existing_export() {
let fixture = Fixture::new();
let path = fixture.add(
"corrupt",
"损坏的压缩会话",
&[event("user", "must not publish a partial export")],
false,
);
let compressed = compress_fixture(&path);
let mut bytes = fs::read(&compressed).unwrap();
let last = bytes.len() - 1;
bytes[last] ^= 0x80;
fs::write(&compressed, &bytes).unwrap();
let destination = fixture.root.join("protected.md");
fs::write(&destination, "existing export").unwrap();
assert!(fixture.export(&["corrupt"], "protected.md").is_err());
assert_eq!(fs::read_to_string(destination).unwrap(), "existing export");
assert_eq!(fs::read(compressed).unwrap(), bytes);
assert!(fs::read_dir(&fixture.root).unwrap().all(|entry| !entry
.unwrap()
.file_name()
.to_string_lossy()
.starts_with(".codex-x-export-")));
}
#[test]
fn compressed_identity_mismatch_does_not_export_another_conversation() {
let fixture = Fixture::new();
let path = fixture.add(
"selected",
"所选会话",
&[event("user", "private fixture")],
false,
);
fs::write(
&path,
format!(
"{}\n{}\n",
json!({"type":"session_meta","payload":{"id":"different"}}),
event("user", "private fixture")
),
)
.unwrap();
compress_fixture(&path);
assert!(fixture.export(&["selected"], "mismatch.md").is_err());
assert!(!fixture.root.join("mismatch.md").exists());
}
#[test]
fn exports_markdown_titles_times_and_code_without_system_tools_or_reasoning() {
let fixture = Fixture::new();
@@ -31,3 +31,56 @@ pub(crate) use storage::{
};
pub(crate) use sync::{session_sync_status_inner, sync_sessions_provider_inner};
pub(crate) use types::{SessionSyncResult, SessionSyncStatus};
/// Serialize operations that can restart the official client with session
/// synchronization and deletion, including callers from other windows or IPC.
/// Provider activation remains independent of this maintenance lock.
pub(crate) fn with_session_maintenance<T>(
codex_dir: &std::path::Path,
operation: impl FnOnce() -> crate::error::Result<T>,
) -> crate::error::Result<T> {
let _guard = sync::acquire_session_maintenance_lock(codex_dir)?;
operation()
}
#[cfg(test)]
mod maintenance_tests {
use super::*;
use std::cell::Cell;
#[test]
fn maintenance_conflict_never_executes_callback_and_release_allows_retry() {
let directory = tempfile::tempdir().unwrap();
let held = sync::acquire_session_maintenance_lock(directory.path()).unwrap();
let called = Cell::new(false);
let error = with_session_maintenance(directory.path(), || {
called.set(true);
Ok(())
})
.expect_err("another session operation must block the callback");
assert!(!called.get());
assert!(error.to_string().contains("会话维护正在进行"));
drop(held);
let result = with_session_maintenance(directory.path(), || {
called.set(true);
Ok(17)
})
.unwrap();
assert!(called.get());
assert_eq!(result, 17);
let _available = sync::acquire_session_maintenance_lock(directory.path()).unwrap();
}
#[test]
fn maintenance_guard_releases_when_callback_returns_an_error() {
let directory = tempfile::tempdir().unwrap();
let error = with_session_maintenance(directory.path(), || {
Err::<(), _>(crate::error::CodexxError::Config(
"fixture operation failed".into(),
))
})
.unwrap_err();
assert!(error.to_string().contains("fixture operation failed"));
let _available = sync::acquire_session_maintenance_lock(directory.path()).unwrap();
}
}
@@ -19,6 +19,66 @@ const MAX_KEY_CAPTURE_BYTES: usize = 128;
const MAX_METADATA_STRING_BYTES: usize = 4096;
const MAX_CWD_BYTES: usize = 32 * 1024;
pub(super) fn is_compressed_rollout(path: &Path) -> bool {
path.to_string_lossy().ends_with(".jsonl.zst")
}
pub(super) fn logical_rollout_path(path: &Path) -> PathBuf {
if is_compressed_rollout(path) {
path.with_extension("")
} else {
path.to_path_buf()
}
}
/// Codex keeps the logical .jsonl reference after compressing the same file.
/// An existing plain representation always wins; other IO failures must not
/// silently select a possibly stale compressed sibling.
pub(super) fn resolved_rollout_path(path: &Path) -> std::io::Result<PathBuf> {
let logical = logical_rollout_path(path);
match fs::symlink_metadata(&logical) {
Ok(_) => Ok(logical),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
let mut compressed = logical.into_os_string();
compressed.push(".zst");
let compressed = PathBuf::from(compressed);
fs::symlink_metadata(&compressed)?;
Ok(compressed)
}
Err(error) => Err(error),
}
}
pub(super) fn decoded_rollout_reader<'a, R: Read + 'a>(
reader: R,
path: &Path,
) -> std::io::Result<Box<dyn Read + 'a>> {
if is_compressed_rollout(path) {
Ok(Box::new(zstd::stream::read::Decoder::new(reader)?))
} else {
Ok(Box::new(reader))
}
}
/// Never overwrite a compressed history after Codex has expanded its current
/// logical file. This is checked again at transaction and atomic-write edges.
pub(super) fn ensure_current_rollout_representation(path: &Path) -> Result<()> {
if is_compressed_rollout(path) {
let logical = logical_rollout_path(path);
match fs::symlink_metadata(&logical) {
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(io_err(&logical, error)),
Ok(_) => {
return Err(format_error(
path,
"会话压缩状态已变化,已停止同步;请重新检查会话",
))
}
}
}
Ok(())
}
#[derive(Debug)]
pub(super) struct FirstMeta {
pub(super) id: String,
@@ -729,9 +789,9 @@ pub(super) fn record_matches_top_level_strings(
JsonReader::new(record, path).matching_fields(field_names, expected, max_decoded_bytes)
}
fn copy_hashed<R: Read>(
fn copy_hashed<R: Read, W: Write>(
mut reader: R,
output: &mut File,
output: &mut W,
hash: &mut Sha256,
path: &Path,
) -> Result<u64> {
@@ -752,11 +812,11 @@ fn copy_hashed<R: Read>(
}
}
fn patched_record(
fn patched_record<W: Write>(
record: &mut File,
metadata: &Metadata,
provider: &[u8],
next: &mut File,
next: &mut W,
hash: &mut Sha256,
path: &Path,
) -> Result<()> {
@@ -858,23 +918,14 @@ pub(super) fn read_first_meta<R: Read>(reader: R, path: &Path) -> Result<FirstMe
}
}
/// Validate the whole rollout and stage byte-preserving Provider patches. The
/// only retained buffers are fixed IO buffers and bounded identity fields.
pub(super) fn scan_rollout_stream(
file: &mut File,
fn scan_records<R: Read, W: Write>(
reader: R,
path: &Path,
directory: &Path,
target_provider: &str,
) -> Result<StreamedRollout> {
if target_provider.len() > MAX_METADATA_STRING_BYTES {
return Err(format_error(path, "目标 Provider 标识过长"));
}
file.seek(SeekFrom::Start(0))
.map_err(|error| io_err(path, error))?;
let directory = private_directory("codex-x-rollout-snapshot-", path)?;
let original_path = directory.path().join("original.jsonl");
let next_path = directory.path().join("next.jsonl");
let mut original = private_file(&original_path)?;
let mut next = private_file(&next_path)?;
mut original: Option<&mut File>,
next: &mut W,
) -> Result<(FirstMeta, usize, usize, [u8; 32], [u8; 32])> {
let provider_json = serde_json::to_vec(target_provider)
.map_err(|_| format_error(path, "目标 Provider 无法编码"))?;
let mut original_hash = Sha256::new();
@@ -882,11 +933,13 @@ pub(super) fn scan_rollout_stream(
let mut first_meta = None;
let mut session_meta_count = 0;
let mut mismatch_count = 0;
frame_records(&mut *file, directory.path(), path, |record, _length| {
frame_records(reader, directory, path, |record, _length| {
record
.seek(SeekFrom::Start(0))
.map_err(|error| io_err(path, error))?;
copy_hashed(&mut *record, &mut original, &mut original_hash, path)?;
if let Some(original) = original.as_deref_mut() {
copy_hashed(&mut *record, original, &mut original_hash, path)?;
}
record
.seek(SeekFrom::Start(0))
.map_err(|error| io_err(path, error))?;
@@ -909,7 +962,7 @@ pub(super) fn scan_rollout_stream(
record,
&metadata,
&provider_json,
&mut next,
next,
&mut next_hash,
path,
)?;
@@ -919,17 +972,147 @@ pub(super) fn scan_rollout_stream(
record
.seek(SeekFrom::Start(0))
.map_err(|error| io_err(path, error))?;
copy_hashed(record, &mut next, &mut next_hash, path)?;
copy_hashed(record, next, &mut next_hash, path)?;
Ok(())
})?;
let first_meta = first_meta.ok_or_else(|| format_error(path, "缺少起始 session_meta"))?;
Ok((
first_meta,
session_meta_count,
mismatch_count,
original_hash.finalize().into(),
next_hash.finalize().into(),
))
}
/// Validate decoded JSONL with bounded memory. Compressed histories retain
/// their exact original compressed bytes and receive a streamed compressed
/// replacement, so ordinary hashes, atomic writes and rollback stay exact.
pub(super) fn scan_rollout_stream(
file: &mut File,
path: &Path,
target_provider: &str,
) -> Result<StreamedRollout> {
scan_rollout_stream_inner(file, path, target_provider, true)
}
pub(super) fn inspect_rollout_stream(
file: &mut File,
path: &Path,
target_provider: &str,
) -> Result<StreamedRollout> {
scan_rollout_stream_inner(file, path, target_provider, false)
}
struct HashingReader<'a> {
source: &'a mut File,
hash: &'a mut Sha256,
}
impl Read for HashingReader<'_> {
fn read(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
let count = self.source.read(bytes)?;
self.hash.update(&bytes[..count]);
Ok(count)
}
}
fn scan_rollout_stream_inner(
file: &mut File,
path: &Path,
target_provider: &str,
stage_changes: bool,
) -> Result<StreamedRollout> {
if target_provider.len() > MAX_METADATA_STRING_BYTES {
return Err(format_error(path, "目标 Provider 标识过长"));
}
ensure_current_rollout_representation(path)?;
file.seek(SeekFrom::Start(0))
.map_err(|error| io_err(path, error))?;
let directory = private_directory("codex-x-rollout-snapshot-", path)?;
if !stage_changes {
let mut raw_hash = Sha256::new();
let reader = HashingReader {
source: &mut *file,
hash: &mut raw_hash,
};
let reader = decoded_rollout_reader(reader, path).map_err(|error| io_err(path, error))?;
let (first_meta, session_meta_count, mismatch_count, _, _) = scan_records(
reader,
path,
directory.path(),
target_provider,
None,
&mut std::io::sink(),
)?;
return Ok(StreamedRollout {
first_meta,
session_meta_count,
mismatch_count,
original_hash: raw_hash.finalize().into(),
original_mtime: file
.metadata()
.map_err(|error| io_err(path, error))?
.modified()
.ok(),
staged: None,
});
}
let extension = if is_compressed_rollout(path) {
"jsonl.zst"
} else {
"jsonl"
};
let original_path = directory.path().join(format!("original.{extension}"));
let next_path = directory.path().join(format!("next.{extension}"));
let mut original = private_file(&original_path)?;
let mut next = private_file(&next_path)?;
let (first_meta, session_meta_count, mismatch_count, original_hash, next_hash) =
if is_compressed_rollout(path) {
let mut original_hash = Sha256::new();
copy_hashed(&mut *file, &mut original, &mut original_hash, path)?;
original
.seek(SeekFrom::Start(0))
.map_err(|error| io_err(path, error))?;
let decoder =
decoded_rollout_reader(&mut original, path).map_err(|error| io_err(path, error))?;
let mut encoder = zstd::stream::write::Encoder::new(&mut next, 3)
.map_err(|error| io_err(path, error))?;
let (first, count, mismatches, _, _) = scan_records(
decoder,
path,
directory.path(),
target_provider,
None,
&mut encoder,
)?;
encoder.finish().map_err(|error| io_err(path, error))?;
next.seek(SeekFrom::Start(0))
.map_err(|error| io_err(path, error))?;
let mut next_hash = Sha256::new();
copy_hashed(&mut next, &mut std::io::sink(), &mut next_hash, path)?;
(
first,
count,
mismatches,
original_hash.finalize().into(),
next_hash.finalize().into(),
)
} else {
scan_records(
&mut *file,
path,
directory.path(),
target_provider,
Some(&mut original),
&mut next,
)?
};
let original_mtime = file
.metadata()
.map_err(|error| io_err(path, error))?
.modified()
.ok();
let original_hash: [u8; 32] = original_hash.finalize().into();
let next_hash: [u8; 32] = next_hash.finalize().into();
let staged = if mismatch_count != 0 {
original
.sync_all()
@@ -1005,6 +1188,111 @@ mod tests {
}
}
#[test]
fn compressed_inspection_keeps_full_validation_and_raw_hash_without_snapshot_or_recompression()
{
let original = b"{\"type\":\"session_meta\",\"payload\":{\"id\":\"thread\",\"model_provider\":\"openai\"}}\r\n{\"type\":\"event_msg\",\"payload\":{\"message\":\"kept\"}}";
let fixture = Fixture::bytes(original);
let compressed = fixture.path.with_extension("jsonl.zst");
fs::write(
&compressed,
zstd::stream::encode_all(&original[..], 1).unwrap(),
)
.unwrap();
fs::remove_file(&fixture.path).unwrap();
for target in ["openai", "custom"] {
let checked =
inspect_rollout_stream(&mut File::open(&compressed).unwrap(), &compressed, target)
.unwrap();
let staged =
scan_rollout_stream(&mut File::open(&compressed).unwrap(), &compressed, target)
.unwrap();
assert!(checked.staged.is_none());
assert_eq!(checked.original_hash, file_hash(&compressed));
assert_eq!(checked.original_hash, staged.original_hash);
assert_eq!(checked.session_meta_count, staged.session_meta_count);
assert_eq!(checked.mismatch_count, staged.mismatch_count);
assert_eq!(checked.first_meta.id, staged.first_meta.id);
}
// A valid metadata prefix must not make a damaged later frame healthy.
let mut raw = zstd::stream::encode_all(&original[..], 1).unwrap();
let mut tail = zstd::stream::encode_all(
&b"\n{\"type\":\"event_msg\",\"payload\":{\"x\":1}}\n"[..],
1,
)
.unwrap();
tail.truncate(tail.len() - 2);
raw.extend(tail);
fs::write(&compressed, raw).unwrap();
assert!(inspect_rollout_stream(
&mut File::open(&compressed).unwrap(),
&compressed,
"openai"
)
.is_err());
}
#[test]
fn compressed_records_above_legacy_limit_are_streamed_and_byte_preserved() {
let fixture = Fixture::bytes(b"");
let compressed = fixture.path.with_extension("jsonl.zst");
fs::remove_file(&fixture.path).unwrap();
let mut encoder =
zstd::stream::write::Encoder::new(File::create(&compressed).unwrap(), 1).unwrap();
encoder.write_all(b"{\"type\":\"session_meta\",\"payload\":{\"id\":\"thread\",\"model_provider\":\"openai\"}}\n{\"type\":\"event_msg\",\"payload\":{\"huge\":\"").unwrap();
let buffer = [b'x'; IO_BUFFER_BYTES];
for _ in 0..(33 * 1024 * 1024 / IO_BUFFER_BYTES) {
encoder.write_all(&buffer).unwrap();
}
encoder.write_all(b"\"}}\r\n").unwrap();
encoder.finish().unwrap();
let result =
scan_rollout_stream(&mut File::open(&compressed).unwrap(), &compressed, "custom")
.unwrap();
let snapshot = result.staged.unwrap();
assert_eq!(file_hash(&compressed), snapshot.original_hash);
assert_eq!(file_hash(&snapshot.original_path), snapshot.original_hash);
let mut decoded = decoded_rollout_reader(
File::open(&snapshot.next_path).unwrap(),
&snapshot.next_path,
)
.unwrap();
let meta = read_first_meta(&mut decoded, &snapshot.next_path).unwrap();
assert_eq!(meta.provider.as_deref(), Some("custom"));
let mut original = BufReader::new(
decoded_rollout_reader(File::open(&compressed).unwrap(), &compressed).unwrap(),
);
let mut original_hash = Sha256::new();
let mut next_hash = Sha256::new();
let mut first_record = Vec::new();
original.read_until(b'\n', &mut first_record).unwrap();
copy_hashed(
&mut original,
&mut std::io::sink(),
&mut original_hash,
&compressed,
)
.unwrap();
let mut next = BufReader::new(
decoded_rollout_reader(
File::open(&snapshot.next_path).unwrap(),
&snapshot.next_path,
)
.unwrap(),
);
first_record.clear();
next.read_until(b'\n', &mut first_record).unwrap();
let count =
copy_hashed(&mut next, &mut std::io::sink(), &mut next_hash, &compressed).unwrap();
assert!(count > 32 * 1024 * 1024);
assert_eq!(
original_hash.finalize(),
next_hash.finalize(),
"all nonmetadata bytes stay exact after decompression"
);
assert_eq!(snapshot.next_hash, file_hash(&snapshot.next_path));
}
#[test]
fn provider_patch_preserves_other_bytes_crlf_and_missing_final_lf() {
let original = b"\r\n{\"type\":\"session_meta\",\"payload\":{\"id\":\"thread\",\"cwd\":\"/tmp/work\",\"model_provider\" : \"openai\",\"source\":\"vscode\"}}\r\n{\"type\":\"event_msg\",\"payload\":{\"text\":\"openai chat content \\\\n\"}}";
@@ -0,0 +1,204 @@
// Manual release-profile benchmark. It never accepts a user-supplied Codex
// directory; all databases, config, histories and backups belong to TempDir.
use super::super::super::rollout_stream::decoded_rollout_reader;
use std::io::BufReader;
use std::time::Instant;
fn random_ascii(buffer: &mut [u8], seed: &mut u64) {
const ASCII: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-";
for byte in buffer {
*seed ^= *seed << 13;
*seed ^= *seed >> 7;
*seed ^= *seed << 17;
*byte = ASCII[(*seed >> 8) as usize & 63];
}
}
fn event_payload(writer: &mut impl Write, size: usize, seed: &mut u64) -> u64 {
let prefix = b"{\"type\":\"event_msg\",\"payload\":{\"type\":\"agent_message\",\"message\":\"";
let suffix = b"\"}}\n";
writer.write_all(prefix).unwrap();
let mut buffer = [0; 64 * 1024];
let mut remaining = size;
while remaining != 0 {
let count = remaining.min(buffer.len());
random_ascii(&mut buffer[..count], seed);
writer.write_all(&buffer[..count]).unwrap();
remaining -= count;
}
writer.write_all(suffix).unwrap();
(prefix.len() + size + suffix.len()) as u64
}
fn content_hash(path: &Path) -> [u8; 32] {
let file = fs::File::open(path).unwrap();
let mut reader = BufReader::new(decoded_rollout_reader(file, path).unwrap());
let mut first = Vec::new();
reader.read_until(b'\n', &mut first).unwrap();
assert!(first.len() < 4096);
let first: serde_json::Value = serde_json::from_slice(&first).unwrap();
assert_eq!(first["type"], "session_meta");
let mut hash = Sha256::new();
let mut buffer = [0; 64 * 1024];
loop {
let count = reader.read(&mut buffer).unwrap();
if count == 0 {
break;
}
hash.update(&buffer[..count]);
}
hash.finalize().into()
}
fn timed<T>(action: impl FnOnce() -> T) -> (T, f64) {
let started = Instant::now();
let value = action();
(value, started.elapsed().as_secs_f64() * 1000.0)
}
#[test]
#[ignore = "manual release-profile measurement using temporary session fixtures only"]
fn measure_session_sync_on_temporary_plain_and_compressed_logs() {
const FILES: usize = 24;
const LARGE_RECORD_BYTES: usize = 34 * 1024 * 1024;
const SMALL_RECORDS_PER_FILE: usize = 1000;
const SMALL_RECORD_BYTES: usize = 512;
let directory = tempfile::tempdir().unwrap();
let dir = directory.path();
write_config(dir, SHARED_SESSION_PROVIDER);
let database = dir.join("state_5.sqlite");
let conn = Connection::open(&database).unwrap();
conn.execute_batch("CREATE TABLE threads(id TEXT PRIMARY KEY, model_provider TEXT NOT NULL, title TEXT, rollout_path TEXT, archived INTEGER NOT NULL DEFAULT 0)").unwrap();
let mut raw_bytes = 0u64;
let mut raw_compressed_bytes = 0u64;
let mut plain_bytes = 0u64;
let mut compressed_bytes = 0u64;
let mut record_count = 0usize;
let mut fixtures = Vec::new();
let mut seed = 0x1357_2468_90ab_cdef;
for index in 0..FILES {
let id = format!("01a0e854-0000-7000-8000-{index:012}");
let logical = dir.join(format!("sessions/2026/10/16/rollout-benchmark-{id}.jsonl"));
fs::create_dir_all(logical.parent().unwrap()).unwrap();
let compressed = index % 2 == 1;
let path = if compressed {
logical.with_extension("jsonl.zst")
} else {
logical.clone()
};
let mut file = fs::File::create(&path).unwrap();
let mut encoder = if compressed {
Some(zstd::stream::write::Encoder::new(file.try_clone().unwrap(), 1).unwrap())
} else {
None
};
let mut output = std::io::BufWriter::new(if let Some(encoder) = encoder.as_mut() {
encoder as &mut dyn Write
} else {
&mut file as &mut dyn Write
});
let meta = format!("{{\"type\":\"session_meta\",\"payload\":{{\"id\":\"{id}\",\"source\":\"cli\",\"model_provider\":\"openai\"}}}}\n");
output.write_all(meta.as_bytes()).unwrap();
let mut bytes = meta.len() as u64;
record_count += 1;
if index < 2 {
bytes += event_payload(&mut output, LARGE_RECORD_BYTES, &mut seed);
record_count += 1;
} else {
for _ in 0..SMALL_RECORDS_PER_FILE {
bytes += event_payload(&mut output, SMALL_RECORD_BYTES, &mut seed);
record_count += 1;
}
}
output.flush().unwrap();
drop(output);
if let Some(encoder) = encoder {
encoder.finish().unwrap();
}
drop(file);
let stored_bytes = fs::metadata(&path).unwrap().len();
raw_bytes += bytes;
if compressed {
compressed_bytes += stored_bytes;
raw_compressed_bytes += bytes;
} else {
plain_bytes += stored_bytes;
}
conn.execute(
"INSERT INTO threads(id,model_provider,title,rollout_path) VALUES(?1,'openai',?1,?2)",
(&id, logical.display().to_string()),
)
.unwrap();
let hash = content_hash(&path);
fixtures.push((id, logical, path, hash));
}
drop(conn);
let config_dir = Some(dir.display().to_string());
let (before, status_before_ms) =
timed(|| session_sync_status_inner(config_dir.clone(), None).unwrap());
assert!(before.scan_complete, "{:?}", before.scan_failures);
assert!(before.needs_sync);
assert_eq!(before.rollout_files, FILES);
assert_eq!(before.mismatched_sessions, FILES);
let (result, sync_ms) =
timed(|| sync_sessions_provider_inner(config_dir.clone(), None).unwrap());
assert!(
result.status.scan_complete,
"{:?}",
result.status.scan_failures
);
assert!(!result.status.needs_sync);
assert_eq!(result.updated_rollouts, FILES);
assert_eq!(result.updated_threads, FILES);
let (after, status_after_ms) =
timed(|| session_sync_status_inner(config_dir.clone(), None).unwrap());
assert!(after.scan_complete);
assert!(!after.needs_sync);
let raw_hashes = fixtures
.iter()
.map(|(_, _, path, _)| rollout_digest(path))
.collect::<Vec<_>>();
let (repeat, idempotent_sync_ms) =
timed(|| sync_sessions_provider_inner(config_dir, None).unwrap());
assert_eq!(repeat.updated_rollouts, 0);
assert_eq!(repeat.updated_threads, 0);
assert!(repeat.backup_dir.is_empty());
assert!(repeat.status.scan_complete);
assert!(!repeat.status.needs_sync);
let conn = Connection::open(&database).unwrap();
for ((id, logical, path, expected_content_hash), raw_hash) in fixtures.iter().zip(raw_hashes) {
assert_eq!(content_hash(path), *expected_content_hash);
assert_eq!(
rollout_digest(path),
raw_hash,
"idempotent sync must not recompress matching storage"
);
let (provider, reference): (String, String) = conn
.query_row(
"SELECT model_provider,rollout_path FROM threads WHERE id=?1",
[id],
|row| Ok((row.get(0)?, row.get(1)?)),
)
.unwrap();
assert_eq!(provider, SHARED_SESSION_PROVIDER);
assert_eq!(reference, logical.display().to_string());
}
println!(
"SESSION_SYNC_BENCHMARK {}",
serde_json::json!({
"profile": if cfg!(debug_assertions) { "debug" } else { "release" },
"fixture_only": true, "files": FILES, "plain_files": FILES / 2,
"compressed_files": FILES / 2, "jsonl_records": record_count,
"largest_record_payload_bytes": LARGE_RECORD_BYTES,
"decoded_jsonl_bytes": raw_bytes, "plain_stored_bytes": plain_bytes,
"compressed_decoded_bytes": raw_compressed_bytes, "compressed_stored_bytes": compressed_bytes,
"total_stored_bytes": plain_bytes + compressed_bytes,
"status_before_ms": status_before_ms, "sync_ms": sync_ms,
"status_after_ms": status_after_ms, "idempotent_sync_ms": idempotent_sync_ms,
"updated_rollouts": result.updated_rollouts, "updated_threads": result.updated_threads,
"all_content_hashes_preserved": true, "logical_references_unchanged": true,
"cache_context": "warm local filesystem after fixture generation; no cache flush",
"comparison": "current implementation only; previous implementation did not support compressed rollouts"
})
);
}
+118 -64
View File
@@ -1,5 +1,9 @@
use super::global_state::normalize_workspace_path;
use super::rollout_stream::{read_first_meta, scan_rollout_stream};
use super::rollout_stream::{
decoded_rollout_reader, ensure_current_rollout_representation, inspect_rollout_stream,
is_compressed_rollout, logical_rollout_path, read_first_meta, resolved_rollout_path,
scan_rollout_stream,
};
use super::types::{RolloutScan, SessionFileChange, SessionPreview, SqliteScan};
use crate::error::{CodexxError, Result};
use crate::file_io::{io_err, parse_toml_document, read_to_string_if_exists};
@@ -50,7 +54,10 @@ pub(super) fn current_model_provider(codex_dir: &Path, explicit: Option<String>)
fn is_rollout_file(path: &Path) -> bool {
path.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| name.starts_with("rollout-") && name.ends_with(".jsonl"))
.is_some_and(|name| {
name.starts_with("rollout-")
&& (name.ends_with(".jsonl") || name.ends_with(".jsonl.zst"))
})
}
pub(super) fn rollout_filename_matches_id(path: &Path, id: &str) -> bool {
@@ -80,6 +87,30 @@ pub(super) fn is_canonical_rollout_storage_path(codex_dir: &Path, path: &Path) -
.any(|root| path.starts_with(root))
}
fn missing_rollout_reference_failure(codex_dir: &Path, path: &Path, thread_id: &str) -> String {
let mut archived = Vec::new();
collect_rollout_paths(
&codex_dir.join("archived_sessions"),
&mut archived,
&mut Vec::new(),
);
let logical_name = logical_rollout_path(path);
archived.sort();
if let Some(archived) = archived.into_iter().find(|candidate| {
logical_rollout_path(candidate).file_name() == logical_name.file_name()
&& read_rollout_identity(candidate).is_ok_and(|identity| {
identity.payload.id.as_deref().map(str::trim) == Some(thread_id)
})
}) {
return format!(
"活动 SQLite 引用的会话文件已位于归档目录,活动索引与归档状态不一致,未自动恢复为活动会话: {} [线程 {thread_id};归档文件 {}]",
path.display(), archived.display());
}
format!(
"活动 SQLite 引用的会话文件不存在(原文件及同名压缩文件均缺失,无法确认是否已删除): {} [线程 {thread_id}]",
path.display())
}
fn referenced_rollout_paths(
codex_dir: &Path,
rollout_paths_by_thread_id: &HashMap<String, String>,
@@ -87,13 +118,31 @@ fn referenced_rollout_paths(
failures: &mut Vec<String>,
) -> HashMap<PathBuf, HashSet<String>> {
let mut referenced = HashMap::<PathBuf, HashSet<String>>::new();
for (thread_id, value) in rollout_paths_by_thread_id {
let mut ordered = rollout_paths_by_thread_id.iter().collect::<Vec<_>>();
ordered.sort_by(|left, right| left.0.cmp(right.0));
for (thread_id, value) in ordered {
let raw = PathBuf::from(value.trim());
let path = if raw.is_absolute() {
raw
} else {
codex_dir.join(raw)
};
let path = match resolved_rollout_path(&path) {
Ok(path) => path,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
failures.push(missing_rollout_reference_failure(
codex_dir, &path, thread_id,
));
continue;
}
Err(error) => {
failures.push(format!(
"无法检查活动会话文件: {} ({error})",
path.display()
));
continue;
}
};
let metadata = match fs::symlink_metadata(&path) {
Ok(metadata) => metadata,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
@@ -159,6 +208,34 @@ fn referenced_rollout_paths(
referenced
}
/// The full provider scan below validates every eligible log. This index pass
/// only needs to check its explicit references and first-record identities;
/// creating and parsing complete snapshots here would duplicate all log IO.
pub(super) fn validate_rollout_references(
codex_dir: &Path,
rollout_paths_by_thread_id: &HashMap<String, String>,
) -> Vec<String> {
let mut failures = Vec::new();
let referenced =
referenced_rollout_paths(codex_dir, rollout_paths_by_thread_id, false, &mut failures);
let mut referenced = referenced.into_iter().collect::<Vec<_>>();
referenced.sort_by(|left, right| left.0.cmp(&right.0));
for (path, expected) in referenced {
match read_rollout_identity(&path) {
Ok(identity)
if expected.len() == 1
&& expected
.contains(identity.payload.id.as_deref().unwrap_or_default().trim()) => {}
Ok(_) => failures.push(format!(
"活动 SQLite 引用的会话文件与线程 ID 不一致: {}",
path.display()
)),
Err(failure) => failures.push(failure),
}
}
failures
}
fn collect_rollout_paths(root: &Path, out: &mut Vec<PathBuf>, failures: &mut Vec<String>) {
let entries = match fs::read_dir(root) {
Ok(entries) => entries,
@@ -205,7 +282,7 @@ fn is_locked_io_error(error: &std::io::Error) -> bool {
}
pub(crate) fn scan_rollouts(codex_dir: &Path, target_provider: &str) -> Result<RolloutScan> {
scan_rollouts_with_thread_filter(codex_dir, target_provider, None, None, true, None, false)
scan_rollouts_with_thread_filter(codex_dir, target_provider, None, true, None, false, true)
}
pub(super) fn scan_provider_rollouts(
@@ -217,43 +294,42 @@ pub(super) fn scan_provider_rollouts(
scan_rollouts_with_thread_filter(
codex_dir,
target_provider,
None,
Some(authoritative_rollout_paths),
false,
Some(excluded_thread_ids),
true,
true,
)
}
pub(super) fn scan_rollouts_for_thread_ids(
pub(super) fn inspect_provider_rollouts(
codex_dir: &Path,
target_provider: &str,
thread_ids: &HashSet<String>,
rollout_paths_by_thread_id: &HashMap<String, String>,
excluded_thread_ids: &HashSet<String>,
authoritative_rollout_paths: &HashMap<String, String>,
) -> Result<RolloutScan> {
scan_rollouts_with_thread_filter(
codex_dir,
target_provider,
Some(thread_ids),
Some(rollout_paths_by_thread_id),
Some(authoritative_rollout_paths),
false,
None,
Some(excluded_thread_ids),
true,
false,
)
}
fn scan_rollouts_with_thread_filter(
codex_dir: &Path,
target_provider: &str,
allowed_thread_ids: Option<&HashSet<String>>,
rollout_paths_by_thread_id: Option<&HashMap<String, String>>,
include_archived_storage: bool,
excluded_thread_ids: Option<&HashSet<String>>,
exclude_source_marked_subagents: bool,
stage_changes: bool,
) -> Result<RolloutScan> {
let mut paths = Vec::new();
let mut scan = RolloutScan::default();
let mut referenced = HashMap::new();
collect_rollout_paths(
&codex_dir.join("sessions"),
&mut paths,
@@ -266,47 +342,26 @@ fn scan_rollouts_with_thread_filter(
&mut scan.scan_failures,
);
}
// Codex may leave a compressed history beside a newly expanded current
// log. Resolve the pair once and never synchronize both representations.
paths.retain(|path| {
!is_compressed_rollout(path) || fs::symlink_metadata(logical_rollout_path(path)).is_err()
});
paths.sort();
scan.discovered_rollout_files = paths.len();
if let Some(excluded_thread_ids) = excluded_thread_ids {
paths.retain(|path| {
if let Some(id) = rollout_filename_thread_id(path) {
return !excluded_thread_ids.contains(id);
}
!excluded_thread_ids
.iter()
.any(|id| rollout_filename_matches_id(path, id))
});
}
if let Some(allowed_thread_ids) = allowed_thread_ids {
let empty_rollout_paths = HashMap::new();
let rollout_paths_by_thread_id = rollout_paths_by_thread_id.unwrap_or(&empty_rollout_paths);
let explicitly_referenced_thread_ids = rollout_paths_by_thread_id
.keys()
.filter(|id| allowed_thread_ids.contains(*id))
.cloned()
.collect::<HashSet<_>>();
referenced = referenced_rollout_paths(
codex_dir,
rollout_paths_by_thread_id,
include_archived_storage,
&mut scan.scan_failures,
);
paths.retain(|path| {
let is_unreferenced_thread_rollout = allowed_thread_ids
.iter()
.filter(|id| !explicitly_referenced_thread_ids.contains(*id))
.any(|id| rollout_filename_matches_id(path, id));
is_unreferenced_thread_rollout
|| path
.canonicalize()
.is_ok_and(|canonical| referenced.contains_key(&canonical))
});
}
scan.rollout_files = paths.len();
for path in paths {
let expected_thread_ids = path
.canonicalize()
.ok()
.and_then(|canonical| referenced.get(&canonical));
let mut rollout_file = match fs::File::open(&path) {
Ok(file) => file,
Err(error) => {
@@ -325,15 +380,6 @@ fn scan_rollouts_with_thread_filter(
}
};
let identity_id = identity.payload.id.as_deref().unwrap_or_default().trim();
if expected_thread_ids
.is_some_and(|expected| expected.len() != 1 || !expected.contains(identity_id))
{
scan.scan_failures.push(format!(
"活动 SQLite 引用的会话文件与线程 ID 不一致: {}",
path.display()
));
continue;
}
let authoritative_identity = rollout_paths_by_thread_id.is_none_or(|authority| {
is_authoritative_rollout(codex_dir, &path, identity_id, authority)
});
@@ -345,12 +391,14 @@ fn scan_rollouts_with_thread_filter(
continue;
}
}
if excluded_thread_ids.is_some_and(|excluded| excluded.contains(identity_id))
|| allowed_thread_ids.is_some_and(|allowed| !allowed.contains(identity_id))
{
if excluded_thread_ids.is_some_and(|excluded| excluded.contains(identity_id)) {
continue;
}
let streamed = match scan_rollout_stream(&mut rollout_file, &path, target_provider) {
let streamed = match if stage_changes {
scan_rollout_stream(&mut rollout_file, &path, target_provider)
} else {
inspect_rollout_stream(&mut rollout_file, &path, target_provider)
} {
Ok(streamed) => streamed,
Err(error) => {
scan.scan_failures.push(format!(
@@ -385,10 +433,12 @@ fn scan_rollouts_with_thread_filter(
{
scan.cwd_by_thread_id.insert(thread_id.clone(), cwd);
}
if let Some(snapshot) = streamed.staged {
if streamed.mismatch_count > 0 {
scan.mismatched_rollouts += 1;
scan.mismatched_session_meta += streamed.mismatch_count;
scan.mismatched_thread_ids.insert(thread_id);
}
if let Some(snapshot) = streamed.staged {
scan.changes.push(SessionFileChange {
path,
original_text: String::new(),
@@ -426,6 +476,7 @@ fn rollout_file_is_open(_path: &Path) -> bool {
}
fn ensure_rollout_snapshot_unchanged(path: &Path, expected: &[u8; 32]) -> Result<()> {
ensure_current_rollout_representation(path)?;
if hash_rollout_file(path).map_err(|error| io_err(path, error))? == *expected {
Ok(())
} else {
@@ -1273,12 +1324,15 @@ fn read_rollout_identity_from_reader<R: Read>(
reader: R,
path: &Path,
) -> std::result::Result<RolloutIdentityRecord, String> {
let first = read_first_meta(reader, path).map_err(|error| {
format!(
"会话文件包含无法解析的 JSON 或无法读取会话文件来源信息: {} ({error})",
path.display()
)
})?;
let first = decoded_rollout_reader(reader, path)
.map_err(|error| io_err(path, error))
.and_then(|reader| read_first_meta(reader, path))
.map_err(|error| {
format!(
"会话文件包含无法解析的 JSON 或无法读取会话文件来源信息: {} ({error})",
path.display()
)
})?;
let record = RolloutIdentityRecord {
kind: "session_meta".into(),
payload: RolloutIdentityPayload {
@@ -1330,8 +1384,8 @@ fn is_authoritative_rollout(
} else {
codex_dir.join(raw)
};
resolved
.canonicalize()
resolved_rollout_path(&resolved)
.and_then(|path| path.canonicalize())
.ok()
.zip(path.canonicalize().ok())
.is_some_and(|(expected, actual)| expected == actual)
+31 -40
View File
@@ -3,8 +3,8 @@ use super::catalog::{scan_catalog_internal_thread_ids, scan_catalog_sync, Catalo
use super::directory_identity::session_directory_identities;
use super::storage::{
current_model_provider, discover_sqlite_databases, ensure_sqlite_discovery_writable,
list_session_previews_with_paths, rollout_internal_thread_ids, scan_provider_rollouts,
scan_rollouts_for_thread_ids, scan_sqlite_with_paths, SqliteDiscovery,
inspect_provider_rollouts, list_session_previews_with_paths, rollout_internal_thread_ids,
scan_provider_rollouts, scan_sqlite_with_paths, validate_rollout_references, SqliteDiscovery,
};
use super::transaction::{
execute_provider_sync_mutation, mutation_error, prepare_sqlite_updates, rollback_mutation,
@@ -28,22 +28,6 @@ fn scan_failure_error(failures: &[String]) -> CodexxError {
)
}
fn scan_provider_buckets(
codex_dir: &Path,
target_provider: &str,
sqlite: &SqliteScan,
) -> Result<RolloutScan> {
let mut rollouts = scan_rollouts_for_thread_ids(
codex_dir,
target_provider,
&sqlite.syncable_thread_ids,
&sqlite.rollout_paths_by_thread_id,
)?;
// Provider synchronization must not repair or rewrite the independent cwd index.
rollouts.cwd_by_thread_id.clear();
Ok(rollouts)
}
fn scan_legacy_index_warnings(
codex_dir: &Path,
target_provider: &str,
@@ -62,8 +46,7 @@ fn scan_legacy_index_warnings(
return Vec::new();
}
let failures = scan_sqlite_with_paths(&legacy_paths, &RolloutScan::default(), target_provider)
.and_then(|sqlite| scan_provider_buckets(codex_dir, target_provider, &sqlite))
.map(|scan| scan.scan_failures)
.map(|sqlite| validate_rollout_references(codex_dir, &sqlite.rollout_paths_by_thread_id))
.unwrap_or_else(|error| vec![error.to_string()]);
failures
.into_iter()
@@ -85,6 +68,7 @@ fn scan_provider_sync_data(
codex_dir: &Path,
target_provider: &str,
discovery: &SqliteDiscovery,
stage_changes: bool,
) -> Result<ProviderSyncScan> {
let active_unclassified = scan_sqlite_with_paths(
&discovery.active_paths,
@@ -128,18 +112,21 @@ fn scan_provider_sync_data(
sqlite.mismatched_thread_ids = mismatched_thread_ids;
sqlite.mismatched_threads = sqlite.mismatched_thread_ids.len();
// Only diagnostics from this authority scan are needed below. Drop its
// planned file copies before scanning the complete provider history.
let (indexed_rollout_failures, indexed_blocked_failures) = {
let rollouts = if active_sqlite.sqlite_dbs > 0 {
scan_provider_buckets(codex_dir, target_provider, &active_sqlite)?
let indexed_rollout_failures = {
let authority = if active_sqlite.sqlite_dbs > 0 {
&active_sqlite
} else {
scan_provider_buckets(codex_dir, target_provider, &sqlite)?
&sqlite
};
(rollouts.scan_failures, rollouts.blocked_failures)
validate_rollout_references(codex_dir, &authority.rollout_paths_by_thread_id)
};
let legacy_index_warnings = scan_legacy_index_warnings(codex_dir, target_provider, discovery);
let mut rollouts = scan_provider_rollouts(
let scan_rollouts = if stage_changes {
scan_provider_rollouts
} else {
inspect_provider_rollouts
};
let mut rollouts = scan_rollouts(
codex_dir,
target_provider,
&excluded_thread_ids,
@@ -176,7 +163,6 @@ fn scan_provider_sync_data(
scan_failures.extend(active_sqlite.scan_failures.iter().cloned());
scan_failures.extend(sqlite.scan_failures.iter().cloned());
scan_failures.extend(indexed_rollout_failures.iter().cloned());
scan_failures.extend(indexed_blocked_failures);
// A size/buffer limit means the rollout was not completely inspected.
// This is blocking even for an orphan, rather than a success with a warning.
scan_failures.extend(rollouts.blocked_failures.iter().cloned());
@@ -224,7 +210,7 @@ pub(super) fn session_sync_status_with_discovery(
target: String,
discovery: &SqliteDiscovery,
) -> Result<SessionSyncStatus> {
let scan = scan_provider_sync_data(codex_dir, &target, discovery)?;
let scan = scan_provider_sync_data(codex_dir, &target, discovery, false)?;
let display_sqlite = if scan.active_sqlite.sqlite_dbs > 0 {
&scan.active_sqlite
} else {
@@ -385,14 +371,10 @@ where
if !initial_status.scan_complete {
return Err(scan_failure_error(&initial_status.scan_failures));
}
let preflight_scan = scan_provider_sync_data(&codex_dir, &target_provider, &discovery)?;
if !preflight_scan.scan_failures.is_empty() {
return Err(scan_failure_error(&preflight_scan.scan_failures));
}
if preflight_scan.rollouts.changes.is_empty()
&& preflight_scan.sqlite.mismatched_threads == 0
&& preflight_scan.catalog.total_updates() == 0
{
// This status already completed the same full scan. Repeating it before
// acquiring SQLite locks neither establishes a newer protected snapshot
// nor improves the mutation guard; the locked scan below does that.
if !initial_status.needs_sync {
return Ok(SessionSyncResult {
status: initial_status,
updated_rollouts: 0,
@@ -400,11 +382,10 @@ where
backup_dir: String::new(),
});
}
drop(preflight_scan);
hook(MutationPoint::BeforeSqliteLock)?;
let mut pending_sqlite = prepare_sqlite_updates(&discovery.related_paths)?;
let scan = match scan_provider_sync_data(&codex_dir, &target_provider, &discovery) {
let scan = match scan_provider_sync_data(&codex_dir, &target_provider, &discovery, true) {
Ok(scan) => scan,
Err(error) => {
rollback_open_transactions(&mut pending_sqlite);
@@ -521,6 +502,16 @@ mod tests {
const SHARED_SESSION_PROVIDER: &str = "custom";
const LEGACY_LIMIT: u64 = 32 * 1024 * 1024;
mod compressed {
use super::*;
include!("compressed_sync_tests.rs");
}
mod benchmark {
use super::*;
include!("session_sync_benchmark.rs");
}
fn temp_codex_dir(label: &str) -> std::path::PathBuf {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let path = std::env::temp_dir().join(format!(
@@ -2,6 +2,7 @@ use super::catalog::{
apply_catalog_updates, catalog_columns, create_catalog_rollback_tables,
restore_catalog_updates, CatalogRepairThread,
};
use super::rollout_stream::ensure_current_rollout_representation;
use super::storage::{
apply_session_changes_with_hook, hash_rollout_file, restore_session_changes,
rollout_path_has_syncable_identity, rollout_text_is_internal, sqlite_subagent_thread_ids,
@@ -492,6 +493,7 @@ fn expected_rollout_hashes(rollouts: &RolloutScan) -> Result<HashMap<PathBuf, [u
fn validate_rollout_snapshots(expected: &HashMap<PathBuf, [u8; 32]>) -> Result<()> {
for (path, expected_hash) in expected {
ensure_current_rollout_representation(path)?;
if hash_rollout_file(path).map_err(|error| io_err(path, error))? != *expected_hash {
return Err(CodexxError::Config(format!(
"会话文件已发生变化,已停止同步;请重新检查会话:{}",
@@ -0,0 +1,9 @@
{
"testOnly": true,
"fixturePurpose": "Synthetic fixture for cfg(test) Tauri SDK download and Minisign verification. The 256-byte PE header contains no executable code, sections or entry point. Never install or run it. This public key must never replace the production updater public key. Its private key was generated only in memory and was not saved.",
"expectedVersion": "0.3.24",
"publicKeyBase64": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDMxOUI5MzI2MzA2QkQ5NUMKUldSYzJXc3dKcE9iTWZrYjhWL1VCZXZ0TWFBNE9IWE9zTENncU5LSFFKaW9wblF4c3VtQXVSSVMK",
"signatureBase64": "dW50cnVzdGVkIGNvbW1lbnQ6IHN5bnRoZXRpYyB0ZXN0IHNpZ25hdHVyZTsgbmV2ZXIgdXNlIGZvciBwcm9kdWN0aW9uIHVwZGF0ZXMKUlVSYzJXc3dKcE9iTWRZZ0xROVZ0T3c1SXVuWXYvU3FUbkRrNGowMjNId2FhcnhTeFpIa25DUm80bGdINzd4UEYvcE1mRWxKUHJZeVczQzBiNHlwWjJYZ3Mxcm0yNVJaYmdBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkxNTA0MDAwCWZpbGU6b25saW5lLXVwZGF0ZS1maXh0dXJlLmV4ZQoxYWxWSVlaWHdYcHlib01YcjdRS1V3RlR4d3FvVFhqMERJWlBGVGR1Z1hyYnZKTFByR1RwaFJjTnRWRGM4d2tLUEsxV01Lcmk5dy9sSzMyVEg0dWRBZz09Cg==",
"payloadBase64": "TVoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAFBFAABkhgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQ29kZXgtWCBzeW50aGV0aWMgdXBkYXRlciBmaXh0dXJlOiBubyBzZWN0aW9ucywgbm8gZW50cnkgcG9pbnQsIG5vIGV4ZWN1dGFibGUgY29kZS4gTmV2ZXIgaW5zdGFsbC4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==",
"sha256": "7764dacacade2426d04ec977eb28b25ed31f8e272c096c1a9d1e9873d0e49be4"
}
+20 -3
View File
@@ -134,6 +134,7 @@ fn provider_test_connection() -> Connection {
wire_api TEXT NOT NULL DEFAULT 'responses',
requires_openai_auth INTEGER NOT NULL DEFAULT 1,
model_mappings_json TEXT NOT NULL DEFAULT '[]',
upstream_api TEXT,
source TEXT NOT NULL DEFAULT 'manual',
source_id TEXT,
created_at TEXT NOT NULL,
@@ -160,6 +161,7 @@ fn provider_fixture(
api_key: api_key.map(ToString::to_string),
toml_config: toml_config.map(ToString::to_string),
wire_api: "responses".to_string(),
upstream_api: None,
requires_openai_auth: true,
model_mappings: Vec::new(),
}
@@ -551,6 +553,7 @@ fn ccswitch_row_reader_supports_legacy_schema_without_category() {
name: "OpenAI Official".to_string(),
settings_config: "{}".to_string(),
category: None,
meta: None,
};
assert!(is_official_ccswitch_row(&official));
}
@@ -961,6 +964,7 @@ wire_api = "responses"
api_key: Some("sk-same".to_string()),
toml_config: Some(toml.to_string()),
wire_api: "responses".to_string(),
upstream_api: None,
requires_openai_auth: true,
model_mappings: Vec::new(),
};
@@ -1809,6 +1813,7 @@ enabled = true
api_key: Some("sk-provider-a".to_string()),
toml_config: Some(provider_a_config.to_string()),
wire_api: "responses".to_string(),
upstream_api: None,
requires_openai_auth: true,
model_mappings: Vec::new(),
},
@@ -1820,6 +1825,7 @@ enabled = true
api_key: Some("sk-provider-b".to_string()),
toml_config: Some(provider_b_config.to_string()),
wire_api: "responses".to_string(),
upstream_api: None,
requires_openai_auth: true,
model_mappings: Vec::new(),
},
@@ -2730,6 +2736,7 @@ requires_openai_auth = true
api_key: None,
toml_config: Some(provider_config.to_string()),
wire_api: "responses".to_string(),
upstream_api: None,
requires_openai_auth: true,
model_mappings: Vec::new(),
})
@@ -3198,6 +3205,7 @@ requires_openai_auth = true
api_key: Some("sk-duplicate-current".to_string()),
toml_config: Some(custom_config.trim_end().to_string()),
wire_api: "responses".to_string(),
upstream_api: None,
requires_openai_auth: true,
model_mappings: Vec::new(),
};
@@ -3656,8 +3664,11 @@ experimental_bearer_token = "sk-from-config"
name: "Proxy".to_string(),
settings_config,
category: None,
meta: None,
};
let provider = build_ccswitch_codex_provider(&row, &HashMap::new()).expect("provider");
let provider = build_ccswitch_codex_provider(&row, &HashMap::new())
.expect("valid provider")
.expect("provider");
assert_eq!(provider.id, "openai-custom");
assert_eq!(provider.api_key.as_deref(), Some("sk-from-config"));
assert_eq!(provider.base_url, "https://proxy.example.com/v1");
@@ -3682,6 +3693,7 @@ requires_openai_auth = true
})
.to_string(),
category: None,
meta: None,
};
let magic_row = CcSwitchCodexRow {
id: "magicai-1782956845071".to_string(),
@@ -3706,6 +3718,7 @@ requires_openai_auth = true
})
.to_string(),
category: None,
meta: None,
};
let mut sections = HashMap::new();
@@ -3718,8 +3731,12 @@ requires_openai_auth = true
}
}
let sky = build_ccswitch_codex_provider(&sky_row, &sections).expect("sky");
let magic = build_ccswitch_codex_provider(&magic_row, &sections).expect("magic");
let sky = build_ccswitch_codex_provider(&sky_row, &sections)
.expect("valid sky provider")
.expect("sky");
let magic = build_ccswitch_codex_provider(&magic_row, &sections)
.expect("valid magic provider")
.expect("magic");
assert_eq!(sky.provider_name, "Sky2api");
assert_eq!(sky.base_url, "https://ikuncode.site/v1");
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Codex-X",
"version": "0.3.23",
"version": "0.3.27",
"identifier": "com.yynxxxxx.codexx",
"build": {
"frontendDist": "../dist",
+11 -2
View File
@@ -1,6 +1,6 @@
import { useSyncExternalStore } from "react";
import { Channel, invoke } from "@tauri-apps/api/core";
import { check as checkForTauriUpdate } from "@tauri-apps/plugin-updater";
import { Update } from "@tauri-apps/plugin-updater";
import { relaunch } from "@tauri-apps/plugin-process";
import { AppUpdaterController, type AppUpdateEvent } from "./appUpdaterController";
@@ -8,7 +8,16 @@ export { INITIAL_APP_UPDATER_STATE, isAppUpdateBusy } from "./appUpdaterControll
export type { AppUpdaterPhase, AppUpdaterState, AppUpdaterFailure, AppUpdaterCheckResult, AppUpdaterCheckOptions } from "./appUpdaterController";
export const appUpdater = new AppUpdaterController({
check: checkForTauriUpdate,
check: async (options) => {
const metadata = await invoke<ConstructorParameters<typeof Update>[0] | null>("check_online_app_update", {
timeout: options.timeout,
headers: options.headers ? Array.from(new Headers(options.headers).entries()) : undefined,
proxy: options.proxy,
target: options.target,
allowDowngrades: options.allowDowngrades,
});
return metadata ? new Update(metadata) : null;
},
install: async (update, onEvent, options) => {
const channel = new Channel<AppUpdateEvent>(onEvent);
return invoke<{ restartRequired: boolean }>("install_app_update", {
+52 -7
View File
@@ -1,6 +1,7 @@
import type { CheckOptions, DownloadOptions } from "@tauri-apps/plugin-updater";
export type AppUpdaterPhase = "idle" | "checking" | "available" | "downloading" | "verifying" | "preparing" | "installing" | "handed-off" | "ready" | "error";
export type AppUpdaterCheckFailureKind = "timeout" | "network" | "platform" | "invalid-release" | "public-key" | "unknown";
export type AppUpdaterFailure = "check" | "download" | "verify" | "prepare" | "install" | "restart" | null;
export type AppUpdaterState = Readonly<{
phase: AppUpdaterPhase;
@@ -12,6 +13,7 @@ export type AppUpdaterState = Readonly<{
totalBytes: number | null;
failure: AppUpdaterFailure;
errorMessage: string | null;
checkFailure?: AppUpdaterCheckFailureKind | null;
logPath: string | null;
takingLonger: boolean;
}>;
@@ -39,7 +41,7 @@ export type AppUpdaterDependencies = {
export const UPDATER_SLOW_NOTICE_MS = 30_000;
export const INITIAL_APP_UPDATER_STATE: AppUpdaterState = {
phase: "idle", currentVersion: null, latestVersion: null, notes: null, publishedAt: null,
downloadedBytes: 0, totalBytes: null, failure: null, errorMessage: null, logPath: null, takingLonger: false,
downloadedBytes: 0, totalBytes: null, failure: null, errorMessage: null, checkFailure: null, logPath: null, takingLonger: false,
};
export function isAppUpdateBusy(phase: AppUpdaterPhase): boolean {
return ["downloading", "verifying", "preparing", "installing", "handed-off"].includes(phase);
@@ -47,6 +49,45 @@ export function isAppUpdateBusy(phase: AppUpdaterPhase): boolean {
function normalizeByteCount(value: number | undefined): number | null {
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : null;
}
// Plugin errors can contain private endpoints and credentials. Inspect bounded
// text only to select one of these fixed explanations; never return that text.
export function classifyAppUpdaterCheckError(error: unknown): AppUpdaterCheckFailureKind {
let text = "";
if (typeof error === "string") text = error;
else if (error instanceof Error) text = `${error.name} ${error.message}`;
else if (typeof error === "object" && error !== null) {
const record = error as Record<string, unknown>;
text = ["code", "kind", "type", "name", "message"].map((key) => record[key])
.filter((value): value is string => typeof value === "string").join(" ");
}
text = text.slice(0, 4096).replace(/https?:\/\/[^\s<>"']+/gi, "").toLowerCase();
if (/timeout|timed?\s*out|time out|etimedout|deadline exceeded|超时/.test(text)) return "timeout";
if (/(?:platform|target)[\s\S]{0,200}(?:not found|missing|unsupported)|unsupported[\s\S]{0,80}(?:architecture|platform|operating system|\bos\b)|unsupportedarch|unsupportedos|targets?notfound|不支持.*(?:平台|系统|架构)/.test(text)) return "platform";
if (/release json|(?:invalid|malformed)[^\n]{0,80}(?:release|json|manifest|version)|serialization|semver|invalid updater resource|missing field|expected (?:value|ident)[^\n]{0,80}line|eof while parsing|trailing characters|key must be a string|(?:relative url without a base)|更新信息.*(?:无效|格式)/.test(text)) return "invalid-release";
if (/public.?key|pubkey|minisign|signature|invalid base64|base64[^\n]{0,80}(?:invalid|decode)|公钥|签名/.test(text)) return "public-key";
if (/network|failed to fetch|error sending request|connection (?:refused|reset|closed)|connect error|dns|tcp|tls|certificate|resolve (?:host|dns)|http (?:error|status)|status code|could not connect|enotfound|econnreset|econnrefused|网络|连接失败/.test(text)) return "network";
return "unknown";
}
export function appUpdaterCheckFailureMessage(kind: AppUpdaterCheckFailureKind, lang: "zh" | "en" = "zh"): string {
const messages = lang === "zh" ? {
timeout: "在线更新检查超时。请检查网络或代理后重试在线检查。",
network: "无法连接在线更新服务。请检查网络或代理后重试在线检查。",
platform: "更新服务没有提供适用于当前系统或架构的在线安装包。请重试在线检查;也可使用下载页的对应平台安装包。",
"invalid-release": "在线更新信息格式无效或未能读取。请重试在线检查;若持续失败,可使用下载页的安装包。",
"public-key": "在线更新签名或公钥配置无效。请重试在线检查;若持续失败,请从下载页获取官方安装包。",
unknown: "在线更新检查未完成。请重试在线检查;下载页可作为备用。",
} : {
timeout: "The online update check timed out. Check your network or proxy, then retry the online check.",
network: "The online update service could not be reached. Check your network or proxy, then retry the online check.",
platform: "The update service did not provide an online installer for this system or architecture. Retry the online check, or use your platform’s installer from the download page.",
"invalid-release": "Online update information is invalid or could not be read. Retry the online check; if it keeps failing, use the installer from the download page.",
"public-key": "The online update signature or public key configuration is invalid. Retry the online check; if it keeps failing, get the official installer from the download page.",
unknown: "The online update check did not finish. Retry the online check; the download page is available as a fallback.",
};
return messages[kind] ?? messages.unknown;
}
function installationError(error: unknown, fallback: AppUpdaterFailure) {
// Only the app's structured installation command supplies user-facing details.
// Do not render arbitrary plugin/network errors, which can include private URLs.
@@ -97,7 +138,7 @@ export class AppUpdaterController {
if (this.state.phase === "ready" || this.state.phase === "handed-off") return Promise.resolve(this.state.phase);
if (!this.update) {
this.retryAction = "check";
this.setState({ phase: "error", failure: "check" });
this.setState({ phase: "error", failure: "check", checkFailure: "invalid-release", errorMessage: appUpdaterCheckFailureMessage("invalid-release"), latestVersion: null, notes: null, publishedAt: null });
return Promise.resolve("error");
}
this.updatePromise = this.performDownloadAndInstall(this.update, options).finally(() => { this.updatePromise = null; });
@@ -117,10 +158,13 @@ export class AppUpdaterController {
private async performCheck(options: CheckOptions): Promise<AppUpdaterCheckResult> {
this.retryAction = "check";
this.setState({ phase: "checking", downloadedBytes: 0, totalBytes: null, failure: null, errorMessage: null, logPath: null, takingLonger: false });
this.setState({ phase: "checking", downloadedBytes: 0, totalBytes: null, failure: null, errorMessage: null, checkFailure: null, latestVersion: null, notes: null, publishedAt: null, logPath: null, takingLonger: false });
try {
const nextUpdate = await this.dependencies.check(options);
await this.replaceUpdate(nextUpdate);
if (nextUpdate && (!Number.isInteger(nextUpdate.rid) || nextUpdate.rid < 0 || nextUpdate.rid > 0xffff_ffff)) {
throw new Error("invalid updater resource");
}
if (!nextUpdate) {
this.setState({ phase: "idle", latestVersion: null, notes: null, publishedAt: null });
return "up-to-date";
@@ -129,9 +173,10 @@ export class AppUpdaterController {
this.setState({ phase: "available", currentVersion: nextUpdate.currentVersion, latestVersion: nextUpdate.version,
notes: nextUpdate.body?.trim() || null, publishedAt: nextUpdate.date || null });
return "available";
} catch {
} catch (error) {
await this.replaceUpdate(null);
this.setState({ phase: "error", failure: "check" });
const checkFailure = classifyAppUpdaterCheckError(error);
this.setState({ phase: "error", failure: "check", checkFailure, errorMessage: appUpdaterCheckFailureMessage(checkFailure), latestVersion: null, notes: null, publishedAt: null });
return "error";
}
}
@@ -141,7 +186,7 @@ export class AppUpdaterController {
const attempt = ++this.attempt;
let acceptingEvents = true;
let handedOff = false;
this.setState({ phase: "downloading", downloadedBytes: 0, totalBytes: null, failure: null, errorMessage: null, logPath: null, takingLonger: false });
this.setState({ phase: "downloading", downloadedBytes: 0, totalBytes: null, failure: null, errorMessage: null, checkFailure: null, logPath: null, takingLonger: false });
this.armSlowNotice();
try {
const result = await this.dependencies.install(update, (event) => {
@@ -194,7 +239,7 @@ export class AppUpdaterController {
}
private async performRestart(): Promise<AppUpdaterPhase> {
this.retryAction = "restart";
this.setState({ failure: null, errorMessage: null, logPath: null });
this.setState({ failure: null, errorMessage: null, checkFailure: null, logPath: null });
try { await this.dependencies.restart(); this.setState({ phase: "ready" }); return "ready"; }
catch { this.setState({ phase: "error", failure: "restart" }); return "error"; }
}
+9
View File
@@ -0,0 +1,9 @@
import type { CodexLanguageStatus } from "./codexLanguageTypes";
// Keep the last detected setting across settings-page mounts. Never invent an
// initial "off" state while the native configuration is still being read.
const statuses = new Map<string, CodexLanguageStatus>();
export function cachedCodexLanguageStatus(configDir: string) { return statuses.get(configDir) ?? null; }
export function rememberCodexLanguageStatus(configDir: string, status: CodexLanguageStatus) {
statuses.set(configDir, status);
}
+13
View File
@@ -0,0 +1,13 @@
export type CodexLocale = "auto" | "zh-CN" | "en-US";
export type CodexLanguageStatus = {
locale: string;
enabled: boolean;
pendingEnabled: boolean | null;
supported: boolean;
appName: string | null;
appVersion: string | null;
phase: "inactive" | "pending" | "starting" | "active" | "failed" | "unsupported";
message: string;
readyPages: number;
restoreAvailable: boolean;
};
+27 -10
View File
@@ -8,9 +8,11 @@ import {
RotateCcw,
Settings,
Sparkles,
X,
} from "lucide-react";
import { INITIAL_APP_UPDATER_STATE, isAppUpdateBusy, type AppUpdaterState } from "../appUpdater";
import { appUpdaterCheckFailureMessage } from "../appUpdaterController";
import type { Lang, StartupDiagnostics } from "../types";
import { Button, ModalShell } from "./ui";
@@ -19,6 +21,8 @@ export type AppToastProps = {
message: string;
error: string;
loading?: boolean;
persistent?: boolean;
action?: { label: string; onClick: () => void; disabled?: boolean };
onDismissMessage: () => void;
onDismissError: () => void;
};
@@ -28,6 +32,8 @@ export function AppToast({
message,
error,
loading = false,
action,
persistent = false,
onDismissMessage,
onDismissError,
}: AppToastProps) {
@@ -39,11 +45,12 @@ export function AppToast({
const [firstLine, ...remainingLines] = activeText.split("\n");
const detail = remainingLines.join("\n").trim();
const dismiss = isError ? onDismissError : onDismissMessage;
const visibleAction = !loading ? action : undefined;
return (
<div
key={`${status}:${activeText}`}
className={`cx-app-toast cx-app-toast--${status}`}
className={`cx-app-toast cx-app-toast--${status}${visibleAction ? " cx-app-toast--actionable" : ""}${persistent ? " cx-app-toast--persistent" : ""}`}
role={isError ? "alert" : "status"}
aria-live={isError ? "assertive" : "polite"}
onAnimationEnd={(event) => {
@@ -58,6 +65,10 @@ export function AppToast({
<strong>{firstLine || (isError ? (lang === "zh" ? "操作失败" : "Action failed") : "Codex-X")}</strong>
{detail && <span>{detail}</span>}
</div>
{visibleAction && <>
<button type="button" className="cx-app-toast-action" onClick={visibleAction.onClick} disabled={visibleAction.disabled}>{visibleAction.label}</button>
<button type="button" className="cx-app-toast-dismiss" onClick={dismiss} aria-label={lang === "zh" ? "关闭提示" : "Dismiss notification"}><X size={14} aria-hidden="true" /></button>
</>}
</div>
);
}
@@ -103,6 +114,10 @@ export function UpdateDialog({
};
const phase = updaterState.phase;
const isBusy = isAppUpdateBusy(phase);
const checkFailed = phase === "error" && updaterState.failure === "check";
const failureDetails = checkFailed
? appUpdaterCheckFailureMessage(updaterState.checkFailure ?? "unknown", lang)
: updaterState.errorMessage;
const totalBytes = updaterState.totalBytes;
const hasKnownProgress = totalBytes !== null && totalBytes > 0;
const progress = totalBytes !== null && totalBytes > 0
@@ -129,8 +144,8 @@ export function UpdateDialog({
handedOffDescription: "Codex-X 即将退出,请在安装窗口继续。首次升级旧版时,系统可能需要一次管理员授权。",
readyTitle: "更新已准备好",
readyDescription: "重新启动 Codex-X 即可使用新版本。",
errorTitle: "更新没有完成",
errorDescription: updaterState.failure === "restart"
errorTitle: checkFailed ? "在线更新检查失败" : "更新没有完成",
errorDescription: checkFailed ? "在线安装尚未开始。请重试在线检查;下载页可作为备用。" : updaterState.failure === "restart"
? "软件未能重新启动,请再试一次。"
: "请重试;如果仍然失败,也可以前往下载页更新。",
idleTitle: "当前已是最新版本",
@@ -152,8 +167,9 @@ export function UpdateDialog({
detailLabel: "失败原因",
logLabel: "安装日志",
restart: "重新启动",
retry: "重试",
retry: checkFailed ? "重试在线检查" : "重试",
downloadPage: "打开下载页",
backupDownloadPage: "打开下载页(备用)",
releaseNotes: "本次更新",
}
: {
@@ -175,8 +191,8 @@ export function UpdateDialog({
handedOffDescription: "Codex-X will exit. Continue in the installer window. Upgrading an older installation may ask for administrator permission once.",
readyTitle: "Update is ready",
readyDescription: "Restart Codex-X to use the new version.",
errorTitle: "Update did not finish",
errorDescription: updaterState.failure === "restart"
errorTitle: checkFailed ? "Online update check failed" : "Update did not finish",
errorDescription: checkFailed ? "Online installation has not started. Retry the online check; the download page is available as a fallback." : updaterState.failure === "restart"
? "Codex-X could not restart. Please try again."
: "Try again, or use the download page if the problem continues.",
idleTitle: "Codex-X is up to date",
@@ -198,8 +214,9 @@ export function UpdateDialog({
detailLabel: "What went wrong",
logLabel: "Installation log",
restart: "Restart",
retry: "Try again",
retry: checkFailed ? "Retry online check" : "Try again",
downloadPage: "Open download page",
backupDownloadPage: "Open download page (fallback)",
releaseNotes: "What's new",
};
@@ -250,7 +267,7 @@ export function UpdateDialog({
? (
<>
<Button variant="secondary" icon={<Download size={16} />} onClick={onDownload}>
{copy.downloadPage}
{checkFailed ? copy.backupDownloadPage : copy.downloadPage}
</Button>
<Button icon={<RotateCcw size={16} />} onClick={() => void onRetry?.()}>
{copy.retry}
@@ -328,10 +345,10 @@ export function UpdateDialog({
<p>{copy.slowDescription}</p>
</section>
)}
{phase === "error" && updaterState.errorMessage && (
{phase === "error" && failureDetails && (
<section className="cx-update-notes" role="alert">
<strong>{copy.detailLabel}</strong>
<p>{updaterState.errorMessage}</p>
<p>{failureDetails}</p>
{updaterState.logPath && <p className="cx-update-log-path">{copy.logLabel}: {updaterState.logPath}</p>}
</section>
)}
@@ -0,0 +1,113 @@
import { useEffect, useRef, useState } from "react";
import { invoke } from "@tauri-apps/api/core";
import { Languages, Loader2 } from "lucide-react";
import type { CodexLanguageStatus } from "../codexLanguageTypes";
import { Toggle } from "./ui";
import { cachedCodexLanguageStatus, rememberCodexLanguageStatus } from "../codexLanguageState";
import "../styles/codex-language.css";
export function CodexLanguageControl({ lang, configDir, active = true, disabled = false, onBusyChange, onPreferencesSaved }: {
lang: "zh" | "en";
configDir: string;
active?: boolean;
disabled?: boolean;
onBusyChange?: (busy: boolean) => void;
onPreferencesSaved?: (status: CodexLanguageStatus) => void;
}) {
const text = (zh: string, en: string) => lang === "zh" ? zh : en;
const [detected, setDetected] = useState(() => ({ configDir, value: cachedCodexLanguageStatus(configDir) }));
const status = detected.configDir === configDir ? detected.value : cachedCodexLanguageStatus(configDir);
const setStatus = (value: CodexLanguageStatus) => {
rememberCodexLanguageStatus(configDir, value);
setDetected({ configDir, value });
};
const [busy, setBusy] = useState(false);
const [readError, setReadError] = useState("");
const [actionError, setActionError] = useState("");
const parentBusy = useRef(disabled);
parentBusy.current = disabled;
const generation = useRef(0);
const operationInFlight = useRef(false);
const statusRequest = useRef(0);
useEffect(() => {
generation.current += 1;
setDetected({ configDir, value: cachedCodexLanguageStatus(configDir) });
setReadError(""); setActionError(""); setBusy(false);
}, [configDir]);
useEffect(() => () => { generation.current += 1; }, []);
useEffect(() => {
const current = generation.current;
let disposed = false;
let loading = false;
const load = async () => {
if (loading || disposed || !active || operationInFlight.current || parentBusy.current) return;
loading = true;
const request = ++statusRequest.current;
try {
const next = await invoke<CodexLanguageStatus>("get_codex_language_status", { configDir });
if (!disposed && generation.current === current && request === statusRequest.current && !operationInFlight.current && !parentBusy.current) {
setStatus(next); setReadError("");
}
} catch (cause) {
if (!disposed && generation.current === current && request === statusRequest.current && !operationInFlight.current && !parentBusy.current) setReadError(String(cause));
} finally { loading = false; }
};
if (active) void load();
const interval = active ? window.setInterval(() => { void load(); }, 1800) : undefined;
return () => { disposed = true; if (interval !== undefined) window.clearInterval(interval); };
}, [configDir, active]);
const save = async (enabled: boolean) => {
if (busy || disabled || operationInFlight.current) return;
operationInFlight.current = true;
statusRequest.current += 1;
onBusyChange?.(true);
const current = generation.current;
setBusy(true); setActionError("");
try {
const next = await invoke<CodexLanguageStatus>("save_codex_language_preferences", { configDir, locale: enabled ? "zh-CN" : "auto", enabled });
if (current === generation.current) { setStatus(next); setReadError(""); onPreferencesSaved?.(next); }
} catch (cause) {
if (current === generation.current) setActionError(String(cause));
} finally {
operationInFlight.current = false;
onBusyChange?.(false);
if (current === generation.current) setBusy(false);
}
};
const pending = status?.pendingEnabled != null;
const enabled = status?.pendingEnabled ?? status?.enabled ?? false;
const starting = status?.phase === "starting";
const blocked = busy || disabled || starting;
const error = actionError || readError || (status?.phase === "failed" ? status.message : "");
const description = error || (status && !status.supported ? status.message : text(
"为 Codex 应用简体中文,重启生效。自动检测当前配置。",
"Use Simplified Chinese in Codex after restart. Detects current settings.",
));
const stateLabel = busy ? text("处理中", "Saving")
: readError ? text("检测失败", "Unavailable")
: actionError ? text("操作失败", "Failed")
: !status ? text("检测中", "Checking")
: status.phase === "failed" ? text("应用失败", "Failed")
: starting ? text("应用中", "Applying")
: pending ? text("待重启", "Restart needed")
: enabled ? text("已开启", "On") : text("已关闭", "Off");
return <section className="cx-page-setting-row cx-codex-language" aria-labelledby="codex-language-title" aria-busy={busy || starting}>
<div className="cx-page-setting-icon" aria-hidden="true"><Languages size={18} strokeWidth={1.9} /></div>
<div className="cx-page-setting-copy">
<strong id="codex-language-title">{text("Codex 简体中文", "Codex Simplified Chinese")}</strong>
<p id="codex-language-description" title={description} role={error ? "alert" : undefined} className={error ? "cx-codex-language-error" : undefined}>{description}</p>
</div>
<div className="cx-page-setting-action cx-codex-language-action">
<div className="cx-codex-language-switch">
<span className={enabled && !pending && !error ? "cx-codex-language-enabled" : undefined} aria-live="polite">{stateLabel}</span>
{status ? <Toggle checked={enabled} disabled={blocked || !status.supported || Boolean(readError)} aria-labelledby="codex-language-title" aria-describedby="codex-language-description" onCheckedChange={next => void save(next)} />
: <span className="cx-codex-language-loading" aria-hidden="true"><Loader2 size={15} className="cx-page-spin" /></span>}
</div>
</div>
</section>;
}
@@ -1,6 +1,7 @@
import { useId } from "react";
import { AlertTriangle, CheckCircle2, FileSearch, FolderOpen, Loader2, RefreshCw, Wrench } from "lucide-react";
import type { ConfigHealthReport } from "../configHealthTypes";
import { configHealthIssueLocation, configHealthRepairUnavailableReason } from "../configHealthPresentation";
import type { ConfigHealthIssue, ConfigHealthReport } from "../configHealthTypes";
import { Button } from "./ui";
import "../styles/config-health.css";
@@ -15,6 +16,15 @@ export type ConfigHealthPanelProps = {
onOpenConfig?: () => void;
};
export function ConfigHealthIssueDetails({ issue, report, lang }: { issue: ConfigHealthIssue; report: ConfigHealthReport; lang: "zh" | "en" }) {
const location = configHealthIssueLocation(issue, report, lang);
return <>
<p className="cx-config-health-location"><code>{location.path}</code><span>{location.position}</span></p>
<p className="cx-config-health-key">{lang === "zh" ? "参数:" : "Setting: "}<code>{location.key}</code></p>
{issue.suggestion && <p className="cx-config-health-suggestion">{lang === "zh" ? "修复建议:" : "Suggested fix: "}{issue.suggestion}</p>}
</>;
}
export function ConfigHealthStatus({ lang, report, checking, repairing, error }: Pick<ConfigHealthPanelProps, "lang" | "report" | "checking" | "repairing" | "error">) {
const zh = lang === "zh";
const busy = checking || repairing;
@@ -60,14 +70,14 @@ export function ConfigHealthPanel({ lang, report, checking, repairing, error, on
<ul className="cx-config-health-issues">
{report.issues.map((issue, index) => <li key={`${issue.code}-${index}`}>
<AlertTriangle size={15} aria-hidden="true" />
<div><strong>{issue.title}</strong><p>{issue.description}</p></div>
<div><strong>{issue.title}</strong><p>{issue.description}</p><ConfigHealthIssueDetails issue={issue} report={report} lang={lang} /></div>
</li>)}
</ul>
{report.canRepair && report.repairSummary.length > 0 && <div className="cx-config-health-plan">
<strong>{zh ? "点击修复后,将进行以下调整:" : "Repair will make these changes:"}</strong>
<ul>{report.repairSummary.map((summary, index) => <li key={index}>{summary}</li>)}</ul>
</div>}
{manualIssues && <p className="cx-config-health-note">{zh ? "部分问题需要手动检查。为保留你的配置,软件不会猜测或覆盖无法确认的内容。" : "Some issues need a manual check. Settings that cannot be determined safely will be left for you to review."}</p>}
{manualIssues && <p className="cx-config-health-note">{zh ? "请按每项问题的文件位置与修复建议处理需要手动确认的参数,然后重新检查。" : "Use each issue’s file location and suggested fix to review settings that need manual confirmation, then check again."}</p>}
</div>}
{report?.status === "missing" && <p className="cx-config-health-note">{zh ? "还没有找到配置文件。完成 Codex 登录或启用供应商后,可以再次检查。" : "No configuration file was found. Check again after signing in to Codex or enabling a provider."}</p>}
@@ -80,6 +90,7 @@ export function ConfigHealthPanel({ lang, report, checking, repairing, error, on
<div className="cx-config-health-actions">
{onOpenConfig && (hasIssues || report?.status === "unavailable") && <Button variant="ghost" size="sm" icon={<FolderOpen size={15} />} disabled={busy} onClick={onOpenConfig}>{zh ? "查看配置" : "View configuration"}</Button>}
<Button variant="secondary" size="sm" icon={checking ? <Loader2 size={15} className="cx-config-health-spinner" /> : <RefreshCw size={15} />} disabled={busy} onClick={onCheck}>{checking ? (zh ? "检查中" : "Checking") : (zh ? "检查配置" : "Check configuration")}</Button>
{hasIssues && !report.canRepair && <Button variant="secondary" size="sm" icon={<Wrench size={15} />} disabled title={configHealthRepairUnavailableReason(report, lang)}>{zh ? "需手动修复" : "Manual repair needed"}</Button>}
{report?.canRepair && hasIssues && <Button size="sm" icon={repairing ? <Loader2 size={15} className="cx-config-health-spinner" /> : <Wrench size={15} />} disabled={busy} onClick={onRepair}>{repairing ? (zh ? "修复中" : "Repairing") : (zh ? "修复配置" : "Repair configuration")}</Button>}
</div>
</div>
@@ -1,4 +1,6 @@
import { AlertTriangle, ArrowRight, Loader2, Wrench, X } from "lucide-react";
import { primaryConfigHealthIssue } from "../configHealthPresentation";
import { ConfigHealthIssueDetails } from "./ConfigHealthPanel";
import type { ConfigHealthReport } from "../configHealthTypes";
import { Button } from "./ui";
import "../styles/config-health.css";
@@ -15,12 +17,14 @@ export type ConfigHealthToastProps = {
/** The caller owns notification lifetime; CSS never dismisses this toast. */
export function ConfigHealthToast({ lang, report, repairing, onRepair, onDismiss, onOpenSettings }: ConfigHealthToastProps) {
const zh = lang === "zh";
const issue = primaryConfigHealthIssue(report);
return <aside className="cx-config-health-toast" aria-label={zh ? "配置检查提醒" : "Configuration check notification"}>
<span className="cx-config-health-toast-icon" aria-hidden="true"><AlertTriangle size={20} /></span>
<div className="cx-config-health-toast-content">
<div role="status" aria-live="polite" aria-atomic="true">
<strong>{repairing ? (zh ? "正在修复 Codex 配置" : "Repairing Codex configuration") : (zh ? "检测到 Codex 配置问题" : "Codex configuration needs attention")}</strong>
<p>{(report.canRepair ? report.issues[0]?.title : report.issues[0]?.description) || (zh ? "部分配置可能影响 Codex 正常使用。" : "Some settings may prevent Codex from working correctly.")}</p>
<p>{(report.canRepair ? issue?.title : issue?.description) || (zh ? "部分配置可能影响 Codex 正常使用。" : "Some settings may prevent Codex from working correctly.")}</p>
{issue && <ConfigHealthIssueDetails issue={issue} report={report} lang={lang} />}
{report.canRepair && report.repairSummary[0] && <p className="cx-config-health-toast-plan">{report.repairSummary[0]}</p>}
</div>
<div className="cx-config-health-toast-actions">
@@ -0,0 +1,64 @@
import { AlertCircle, RefreshCw } from "lucide-react";
import type { ProviderBalance } from "../providerBalance";
import "../styles/provider-balance.css";
function errorLabel(code: string | null, zh: boolean) {
if (code === "permission_denied") return zh ? "查询权限不足" : "Access denied";
if (code === "invalid_credential" || code === "authentication_failed") return zh ? "请检查 API Key" : "Check API key";
if (code === "missing_key") return zh ? "未设置 API Key" : "API key missing";
if (code === "rate_limited") return zh ? "请求较多,请稍后刷新" : "Rate limited. Try again shortly.";
if (code === "timeout" || code === "network_error") return zh ? "网络异常,请稍后刷新" : "Check your connection and retry.";
return zh ? "暂时无法查询" : "Temporarily unavailable";
}
function amountText(amount: string) {
const match = /^(-?)(\d+)(?:\.(\d+))?$/.exec(amount);
if (!match) return amount;
const integer = match[2].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
const fraction = (match[3] || "").replace(/0+$/, "").padEnd(2, "0");
// Group the exact decimal string; financial values never pass through Number.
return `${match[1] === "-" ? "−" : ""}${integer}.${fraction}`;
}
export function ProviderBalanceBadge({ balance, loading, refreshing = false, failed, lang, onRefresh }: {
balance?: ProviderBalance;
loading: boolean;
refreshing?: boolean;
failed: boolean;
lang: "zh" | "en";
onRefresh?: () => void;
}) {
const zh = lang === "zh";
const hasBalance = Boolean(balance?.balances.length);
const unavailable = failed || Boolean(balance?.errorCode);
const busy = loading || refreshing;
const label = balance?.balanceKind === "credit_limit" ? (zh ? "Key 剩余额度" : "Key credit left") : (zh ? "可用余额" : "Available balance");
const updated = balance?.checkedAt ? new Date(balance.checkedAt) : null;
const updateTime = updated && Number.isFinite(updated.getTime())
? updated.toLocaleTimeString(zh ? "zh-CN" : "en-GB", { hour12: false, hour: "2-digit", minute: "2-digit", second: "2-digit" }) : null;
const detail = errorLabel(balance?.errorCode ?? null, zh);
const hint = [balance?.balanceKind === "credit_limit" ? (zh ? "此 API Key 的剩余额度。" : "Remaining credit for this API key.") : "",
unavailable ? detail : "", updateTime ? `${hasBalance ? (zh ? "余额更新于" : "Balance updated") : (zh ? "最近查询于" : "Last checked")} ${updated!.toLocaleString(zh ? "zh-CN" : "en-GB")}` : "",
zh ? "后台每 5 分钟自动刷新,也可点击余额旁的按钮立即查询。" : "Refreshes every 5 minutes in the background. Use the refresh button to query now."].filter(Boolean).join("\n");
return <section className={`cx-provider-balance${unavailable ? " cx-provider-balance--stale" : ""}`} aria-label={label} aria-busy={busy} title={hint}>
<div className="cx-provider-balance-heading">
<span>{label}</span>
</div>
<div className="cx-provider-balance-reading">
{hasBalance ? <div className={`cx-provider-balance-amounts${balance!.balances.length > 1 ? " cx-provider-balance-amounts--multiple" : ""}`}>
{balance!.balances.map(item => <div key={item.currency} className={`cx-provider-balance-value${item.amount.startsWith("-") || /^0(?:\.0+)?$/.test(item.amount) ? " cx-provider-balance-value--empty" : ""}`} title={`${item.amount} ${item.currency}`}>
<strong>{amountText(item.amount)}</strong><span>{item.currency}</span>
</div>)}
</div> : busy ? <div className="cx-provider-balance-placeholder" aria-label={zh ? "正在查询余额" : "Loading balance"}><span /></div>
: <div className="cx-provider-balance-unavailable"><AlertCircle size={14} aria-hidden="true" /><span>{detail}</span></div>}
<button type="button" className="cx-provider-balance-refresh" disabled={busy || !onRefresh} onClick={onRefresh}
title={zh ? "立即刷新余额" : "Refresh balance now"} aria-label={zh ? "刷新余额" : "Refresh balance"}>
<RefreshCw size={13} strokeWidth={1.8} className={busy ? "cx-provider-balance-spin" : undefined} aria-hidden="true" />
</button>
</div>
<div className={`cx-provider-balance-footer${unavailable && !busy ? " cx-provider-balance-footer--error" : ""}`} aria-live="polite">
{busy ? (zh ? "正在刷新…" : "Refreshing…") : <>{unavailable ? (zh ? "刷新失败" : "Refresh failed") : !hasBalance ? (zh ? "尚未更新" : "Not updated") : (zh ? "已更新" : "Updated")}{updateTime && <><span aria-hidden="true"> · </span>{unavailable && hasBalance ? (zh ? "上次 " : "Last ") : ""}<time dateTime={balance!.checkedAt!}>{updateTime}</time></>}</>}
</div>
</section>;
}
@@ -0,0 +1,61 @@
import { useEffect, useRef, useState } from "react";
import { invoke } from "@tauri-apps/api/core";
import { ProviderHeadersEditor } from "./ProviderHeadersEditor";
import { normalizeProviderHeaders, validateProviderHeaders } from "../providerHeaders";
import type { ProviderHeader } from "../providerHeaders";
import { createProviderHeadersControl } from "../providerHeadersControl";
import type { ProviderHeadersControlState } from "../providerHeadersControl";
export function ProviderHeadersControl({ lang, configText, disabled = false, onConfigChange, onBusyChange, onValidityChange }: {
lang: "zh" | "en";
configText: string;
disabled?: boolean;
onConfigChange: (configText: string) => void;
onBusyChange: (busy: boolean) => void;
onValidityChange: (valid: boolean) => void;
}) {
const runtime = useRef({ configText, onConfigChange, onBusyChange, onValidityChange });
runtime.current = { configText, onConfigChange, onBusyChange, onValidityChange };
const control = useRef<ReturnType<typeof createProviderHeadersControl> | null>(null);
const [rows, setRows] = useState<ProviderHeader[]>([]);
const [state, setState] = useState<ProviderHeadersControlState>({ busy: true, reading: true, valid: false, error: null });
useEffect(() => {
const instance = createProviderHeadersControl({
read: (text) => invoke<ProviderHeader[]>("read_provider_headers", { configText: text }),
update: (text, headers) => invoke<string>("update_provider_headers", { configText: text, headers }),
getConfigText: () => runtime.current.configText,
isValid: (next) => validateProviderHeaders(next).valid,
normalize: normalizeProviderHeaders,
onRowsChange: setRows,
onConfigChange: (text) => runtime.current.onConfigChange(text),
onStateChange: (next) => {
setState(next);
runtime.current.onBusyChange(next.busy);
runtime.current.onValidityChange(next.valid);
},
});
control.current = instance;
void instance.load(runtime.current.configText);
return () => {
instance.dispose();
if (control.current === instance) control.current = null;
runtime.current.onBusyChange(false);
runtime.current.onValidityChange(true);
};
}, []);
useEffect(() => { void control.current?.load(configText); }, [configText]);
const errorText = state.error === "read"
? lang === "zh" ? "无法读取 Headers,请检查供应商 TOML 后重试。" : "Could not read headers. Check the provider TOML and retry."
: lang === "zh" ? "无法更新 Headers,请重试或检查供应商 TOML。" : "Could not update headers. Retry or check the provider TOML.";
return <div className="cx-provider-headers-control">
<ProviderHeadersEditor lang={lang} rows={rows} disabled={disabled || state.reading} onChange={(next) => { void control.current?.changeRows(next); }} />
{state.busy && <p className="cx-provider-headers-hint" role="status">{state.reading
? lang === "zh" ? "正在读取 Headers…" : "Reading headers…"
: lang === "zh" ? "正在更新配置…" : "Updating configuration…"}</p>}
{state.error && <div className="cx-provider-headers-feedback"><p className="cx-provider-headers-error" role="status">{errorText}</p><button type="button" className="cx-providers-button cx-providers-button--secondary cx-providers-button--small" disabled={disabled || state.busy} onClick={() => { void control.current?.retry(); }}>{lang === "zh" ? "重试" : "Retry"}</button></div>}
</div>;
}
@@ -0,0 +1,70 @@
import { useId } from "react";
import { Plus, Trash2 } from "lucide-react";
import {
createProviderHeader,
removeProviderHeader,
updateProviderHeader,
validateProviderHeaders,
} from "../providerHeaders";
import type { ProviderHeader, ProviderHeaderSource } from "../providerHeaders";
import { applyProviderHeaderPreset, PROVIDER_HEADER_PRESETS, providerHeaderValuePlaceholder } from "../providerHeaderPresets";
import "../styles/provider-headers.css";
export function ProviderHeadersEditor({ lang, rows, disabled = false, onChange }: {
lang: "zh" | "en";
rows: readonly ProviderHeader[];
disabled?: boolean;
onChange: (rows: ProviderHeader[]) => void;
}) {
const id = useId();
const copy = lang === "zh" ? {
title: "自定义请求头 Headers", optional: "可选", hint: "按供应商要求设置 User-Agent(客户端标识)或其他附加请求头;不填写时使用默认设置。",
presets: "User-Agent 预设", presetHint: "预设只设置 User-Agent,其他请求头保留;已有 User-Agent 会更新为所选固定值。预设是否适用以供应商要求为准。",
envHint: "环境变量模式只保存变量名;直连由 Codex 读取,路由由 Codex-X 读取,请在启动对应应用前设置。",
add: "添加 Header", empty: "尚未配置自定义 Headers", name: "名称", value: "值", source: "值来源", literal: "固定值", env: "环境变量", remove: "删除 Header",
placeholder: "例如 User-Agent", envPlaceholder: "例如 PROVIDER_HEADER_VALUE", fix: "请先修正标红的 Headers,再保存供应商。",
row: (index: number) => `第 ${index + 1} 行`,
} : {
title: "Custom headers", optional: "Optional", hint: "Set User-Agent (client identification) or other HTTP headers required by your provider. Leave them empty to keep the defaults.",
presets: "User-Agent presets", presetHint: "Presets set only User-Agent and keep other headers. An existing User-Agent becomes the selected literal value. Check your provider requirements before choosing one.",
envHint: "Environment mode saves only the variable name. Set it before launching Codex for direct requests, or Codex-X for routed requests.",
add: "Add header", empty: "No custom headers configured", name: "Name", value: "Value", source: "Value source", literal: "Literal value", env: "Environment variable", remove: "Remove header",
placeholder: "e.g. User-Agent", envPlaceholder: "e.g. PROVIDER_HEADER_VALUE", fix: "Correct the highlighted headers before saving this provider.",
row: (index: number) => `Row ${index + 1}`,
};
const validation = validateProviderHeaders(rows, lang);
const update = (index: number, patch: Partial<ProviderHeader>) => {
if (!disabled) onChange(updateProviderHeader(rows, index, patch));
};
return <section className="cx-provider-headers" aria-labelledby={`${id}-title`}>
<div className="cx-provider-headers-heading">
<div><strong id={`${id}-title`}>{copy.title}<span>{copy.optional}</span></strong><p>{copy.hint}</p></div>
<div className="cx-provider-headers-actions">
<select className="cx-provider-headers-presets" aria-label={copy.presets} aria-describedby={`${id}-preset-hint`} value="" disabled={disabled} onChange={(event) => {
const selected = event.currentTarget.value;
if (selected) onChange(applyProviderHeaderPreset(rows, selected));
}}>
<option value="">{copy.presets}</option>
{PROVIDER_HEADER_PRESETS.map((preset) => <option key={preset.id} value={preset.id}>{preset.label[lang]} · {preset.value}</option>)}
</select>
<button type="button" className="cx-providers-button cx-providers-button--secondary cx-providers-button--small" disabled={disabled} onClick={() => onChange([...rows, createProviderHeader()])}><Plus size={14} aria-hidden="true" />{copy.add}</button>
</div>
</div>
<p className="cx-provider-headers-hint cx-provider-headers-preset-hint" id={`${id}-preset-hint`}>{copy.presetHint}</p>
{rows.length === 0 ? <p className="cx-provider-headers-empty">{copy.empty}</p> : <div className="cx-provider-headers-rows">
{rows.map((row, index) => {
const error = validation.errors[index];
return <div key={index} className="cx-provider-header-row" role="group" aria-label={copy.row(index)}>
<label className="cx-provider-header-field"><span>{copy.name}</span><input value={row.name} placeholder={copy.placeholder} aria-label={`${copy.name} · ${copy.row(index)}`} aria-invalid={Boolean(error.name)} aria-describedby={error.name ? `${id}-${index}-name-error` : undefined} onChange={(event) => update(index, { name: event.currentTarget.value })} disabled={disabled} autoComplete="off" autoCapitalize="none" spellCheck={false} />{error.name && <small id={`${id}-${index}-name-error`}>{error.name}</small>}</label>
<label className="cx-provider-header-field"><span>{copy.source}</span><select value={row.source} aria-label={`${copy.source} · ${copy.row(index)}`} aria-invalid={Boolean(error.source)} aria-describedby={error.source ? `${id}-${index}-source-error` : undefined} onChange={(event) => update(index, { source: event.currentTarget.value as ProviderHeaderSource })} disabled={disabled}><option value="static">{copy.literal}</option><option value="env">{copy.env}</option></select>{error.source && <small id={`${id}-${index}-source-error`}>{error.source}</small>}</label>
<label className="cx-provider-header-field"><span>{row.source === "env" ? copy.env : copy.value}</span><input value={row.value} placeholder={row.source === "env" ? copy.envPlaceholder : providerHeaderValuePlaceholder(row.name, lang)} aria-label={`${row.source === "env" ? copy.env : copy.value} · ${copy.row(index)}`} aria-invalid={Boolean(error.value)} aria-describedby={error.value ? `${id}-${index}-value-error` : row.source === "env" ? `${id}-env-hint` : undefined} onChange={(event) => update(index, { value: event.currentTarget.value })} disabled={disabled} autoComplete="off" autoCapitalize="none" spellCheck={false} />{error.value && <small id={`${id}-${index}-value-error`}>{error.value}</small>}</label>
<button type="button" className="cx-providers-icon-button cx-providers-icon-button--danger cx-provider-header-remove" title={`${copy.remove} · ${copy.row(index)}`} aria-label={`${copy.remove} · ${copy.row(index)}`} disabled={disabled} onClick={() => onChange(removeProviderHeader(rows, index))}><Trash2 size={14} aria-hidden="true" /></button>
</div>;
})}
</div>}
<p className="cx-provider-headers-hint" id={`${id}-env-hint`}>{copy.envHint}</p>
{rows.some((row) => row.name.trim().toLowerCase() === "authorization") && <p className="cx-provider-headers-hint">{lang === "zh" ? "直连使用 Authorization Header 认证时,请留空 API Key;填写 API Key 会替换原有 Authorization。" : "For direct Authorization header authentication, leave API Key empty. An explicit API Key replaces the existing Authorization header."}</p>}
{!validation.valid && <p className="cx-provider-headers-error" role="status">{copy.fix}</p>}
</section>;
}
+1 -1
View File
@@ -95,7 +95,7 @@ function labelHash(value: string) {
return `${(first >>> 0).toString(16)}-${(second >>> 0).toString(16)}`;
}
export function configHealthIssueKey(report: ConfigHealthReport) {
return labelHash(JSON.stringify(report.issues.map(({ code, title, description }) => [code, title, description]).sort()));
return labelHash(JSON.stringify(report.issues.map(({ code, title, description, key, suggestion, repairable }) => [code, title, description, key, suggestion, repairable]).sort()));
}
type StorageLike = Pick<Storage, "getItem" | "setItem">;
export function createConfigHealthNoticeRegistry(storage?: StorageLike) {
@@ -0,0 +1,27 @@
import type { ConfigHealthIssue, ConfigHealthReport } from "./configHealthTypes";
// Fall back for older backend/fixture reports while retaining exact locations
// from the diagnostic command. Missing definitions do not have a source line.
export function configHealthIssueLocation(issue: ConfigHealthIssue, report: ConfigHealthReport, lang: "zh" | "en") {
const zh = lang === "zh";
const path = issue.path || `${report.codexDir.replace(/[\\/]$/, "")}/config.toml`;
const position = issue.line != null && issue.line > 0
? (zh ? `第 ${issue.line} 行${issue.column != null ? `,第 ${issue.column} 列` : ""}`
: `line ${issue.line}${issue.column != null ? `, column ${issue.column}` : ""}`)
: !issue.key
? (zh ? "旧版报告未提供行列,请重新检查" : "location not supplied; check again")
: issue.key.startsWith('"<')
? (zh ? "文件层面" : "file level")
: (zh ? "未定义,尚无对应行" : "not defined; no source line");
return { path, position, key: issue.key || (zh ? "配置文件" : "configuration file") };
}
export function primaryConfigHealthIssue(report: ConfigHealthReport) {
return (report.canRepair ? report.issues.find((issue) => issue.repairable) : undefined) ?? report.issues[0];
}
export function configHealthRepairUnavailableReason(report: ConfigHealthReport, lang: "zh" | "en") {
return (report.issues.find((issue) => issue.code === "config-linked-file")
?? report.issues.find((issue) => !issue.repairable))?.suggestion
|| (lang === "zh" ? "现有配置无法可靠确定,请按问题中的建议修改后重新检查。" : "The correct settings cannot be determined safely. Follow the issue's suggestion and check again.");
}
+5
View File
@@ -3,6 +3,11 @@ export type ConfigHealthIssue = {
title: string;
description: string;
repairable: boolean;
path: string;
line: number | null;
column: number | null;
key: string;
suggestion: string;
};
export type ConfigHealthReport = {
+271 -82
View File
@@ -1,3 +1,5 @@
import { releaseInfoFromFallback, releaseInfoFromCheckFailure } from "./updateCheckFlow";
import { providerUpstreamApi, providerRequiresConversion } from "./providerProtocol";
import React from "react";
import { flushSync } from "react-dom";
import ReactDOM from "react-dom/client";
@@ -13,6 +15,7 @@ import { OverviewPage } from "./pages/OverviewPage";
import { AboutPage, SettingsPage, TomlConfigPage } from "./pages/UtilityPages";
import { PromptsPage } from "./pages/PromptsPage";
import { SkillsMcpPage, type SkillsMcpNoteKind } from "./pages/SkillsMcpPage";
import { useProviderBalances } from "./providerBalance";
import { ProvidersPage, type ProviderCopy, type ProviderRow } from "./pages/ProvidersPage";
import { AppShell, type AppTab, type AppTheme } from "./components/AppShell";
import {
@@ -28,6 +31,8 @@ import { applyProviderRowOrder, orderProviderRows } from "./providerRowOrder";
import { createPresetProvider, getProviderPreset, getProviderPresetVariant } from "./providerPresets";
import { validateProviderModelMappings } from "./components/ProviderModelMappings";
import { createOfficialProfileMonitor } from "./officialProfileMonitor";
import { createSessionStatusTracker, providerActivationIsBusy, readCurrentSessionStatus, sessionStatusContextKey } from "./sessionOperationState";
import type { LoadingScope, SessionStatusContext } from "./sessionOperationState";
import { useConfigHealth } from "./useConfigHealth";
import { ConfigHealthPanel, ConfigHealthStatus } from "./components/ConfigHealthPanel";
import { ConfigHealthToast } from "./components/ConfigHealthToast";
@@ -129,6 +134,7 @@ const defaultProviderForm: SavedProvider = {
apiKey: "",
tomlConfig: "",
wireApi: "responses",
upstreamApi: "responses",
requiresOpenaiAuth: false,
};
@@ -140,6 +146,7 @@ const blankProviderForm: SavedProvider = {
apiKey: "",
tomlConfig: "",
wireApi: "responses",
upstreamApi: "responses",
requiresOpenaiAuth: false,
};
@@ -568,7 +575,7 @@ function buildProviderTomlPreview(provider: SavedProvider) {
const providerKey = "custom";
const baseUrl = provider.baseUrl.trim().replace(/\/+$/, "");
if (!model || !name || !baseUrl) return "";
const wireApi = provider.wireApi || "responses";
const wireApi = "responses";
return [
`model_provider = "${tomlEscape(providerKey)}"`,
`model = "${tomlEscape(model)}"`,
@@ -794,8 +801,10 @@ function App() {
const [healthConfigDir, setHealthConfigDir] = React.useState("");
const [settingsGeneralRequest, setSettingsGeneralRequest] = React.useState(0);
const [loading, setLoading] = React.useState(false);
const [providerActivationBusy, setProviderActivationBusy] = React.useState(false);
const [refreshing, setRefreshing] = React.useState(true);
const [toast, setToast] = React.useState<string>("");
const [languageRestartNotice, setLanguageRestartNotice] = React.useState<{ configDir: string; message: string } | null>(null);
const [error, setError] = React.useState<string>("");
const [providerForm, setProviderForm] = React.useState<SavedProvider>(defaultProviderForm);
const [providerTomlDraft, setProviderTomlDraft] = React.useState("");
@@ -808,7 +817,9 @@ function App() {
const [providerModelsLoading, setProviderModelsLoading] = React.useState(false);
const [actionBusy, setActionBusy] = React.useState<string>("");
const [skillsMcpNoteBusy, setSkillsMcpNoteBusy] = React.useState("");
const [restartCodexError, setRestartCodexError] = React.useState("");
const [restartCodexBusy, setRestartCodexBusy] = React.useState(false);
React.useEffect(() => { setLanguageRestartNotice(null); setRestartCodexError(""); }, [configDir]);
const [promptSyncing, setPromptSyncing] = React.useState(false);
const [promptDetailLoading, setPromptDetailLoading] = React.useState(false);
const [promptCatalogReady, setPromptCatalogReady] = React.useState(false);
@@ -839,7 +850,8 @@ function App() {
const savedProvidersRequestRef = React.useRef(0);
const providerOrderRequestRef = React.useRef(0);
const loadingGenerationRef = React.useRef(0);
const loadingTokensRef = React.useRef(new Set<number>());
const loadingTokensRef = React.useRef(new Map<number, LoadingScope>());
const languageLoadingTokenRef = React.useRef<number | null>(null);
const actionBusyGenerationRef = React.useRef(0);
const actionBusyTokensRef = React.useRef(new Map<number, string>());
const skillsMcpNoteBusyRef = React.useRef("");
@@ -850,7 +862,16 @@ function App() {
const refreshRequestRef = React.useRef(0);
const aboutLoadKeyRef = React.useRef("");
const sessionAutoLoadKeyRef = React.useRef("");
const sessionLoadRequestRef = React.useRef(0);
const sessionStatusTrackerRef = React.useRef(createSessionStatusTracker());
const sessionStateRef = React.useRef(state);
sessionStateRef.current = state;
const providerActivationRevisionRef = React.useRef(0);
const providerActivationInFlightRef = React.useRef(0);
const sessionMutationInFlightRef = React.useRef(false);
const sessionDeleteBusyRef = React.useRef(false);
const sessionRefreshPendingRef = React.useRef(false);
const sessionSyncToastPendingRef = React.useRef(false);
const refreshSyncedSessionStatusRef = React.useRef<() => Promise<SessionSyncStatus | null>>(async () => null);
const promptRefreshInFlightRef = React.useRef<Promise<BuiltinPromptStatus[]> | null>(null);
const promptAutoRefreshAttemptedRef = React.useRef(false);
const promptCatalogReadyRef = React.useRef(false);
@@ -881,6 +902,10 @@ function App() {
? activeBuiltinTemplateId
: "";
const syncProviderActivationBusy = React.useCallback(() => {
setProviderActivationBusy(providerActivationIsBusy(loadingTokensRef.current.values(), actionBusyTokensRef.current.values()));
}, []);
const syncActionBusy = React.useCallback(() => {
let latestToken = -1;
let latestAction = "";
@@ -891,26 +916,39 @@ function App() {
}
}
setActionBusy(latestAction);
}, []);
syncProviderActivationBusy();
}, [syncProviderActivationBusy]);
const beginLoading = React.useCallback(() => {
const beginLoading = React.useCallback((scope: LoadingScope = "general") => {
const token = ++loadingGenerationRef.current;
loadingTokensRef.current.add(token);
loadingTokensRef.current.set(token, scope);
setLoading(true);
syncProviderActivationBusy();
return token;
}, []);
}, [syncProviderActivationBusy]);
const endLoading = React.useCallback((token: number) => {
if (!loadingTokensRef.current.delete(token)) return;
setLoading(loadingTokensRef.current.size > 0);
}, []);
syncProviderActivationBusy();
}, [syncProviderActivationBusy]);
const beginActionBusy = React.useCallback((action: string) => {
const token = ++actionBusyGenerationRef.current;
actionBusyTokensRef.current.set(token, action);
setActionBusy(action);
syncProviderActivationBusy();
return token;
}, []);
}, [syncProviderActivationBusy]);
const handleLanguageBusyChange = React.useCallback((busy: boolean) => {
if (busy && languageLoadingTokenRef.current === null) {
languageLoadingTokenRef.current = beginLoading();
} else if (!busy && languageLoadingTokenRef.current !== null) {
endLoading(languageLoadingTokenRef.current);
languageLoadingTokenRef.current = null;
}
}, [beginLoading, endLoading]);
const endActionBusy = React.useCallback((token: number) => {
if (!actionBusyTokensRef.current.delete(token)) return;
@@ -927,6 +965,36 @@ function App() {
if (changed) syncActionBusy();
}, [syncActionBusy]);
const invalidateSessionStatus = React.useCallback(() => {
sessionStatusTrackerRef.current.invalidate();
sessionAutoLoadKeyRef.current = "";
setSessionStatus(null);
}, []);
const getSessionStatusContext = React.useCallback((): SessionStatusContext | null => {
const current = sessionStateRef.current;
if (!current || providerActivationInFlightRef.current) return null;
return {
configDir: current.codexDir,
targetProvider: current.modelProvider || "openai",
providerRevision: providerActivationRevisionRef.current,
};
}, []);
const loadCurrentSessionStatus = React.useCallback(() => readCurrentSessionStatus(
sessionStatusTrackerRef.current,
getSessionStatusContext,
(context) => invoke<SessionSyncStatus>("get_session_sync_status", {
configDir: context.configDir,
targetProvider: context.targetProvider,
}),
(status) => {
setSessionStatus(status);
const context = getSessionStatusContext();
if (context) sessionAutoLoadKeyRef.current = sessionStatusContextKey(context);
},
), [getSessionStatusContext]);
const invalidatePromptDetail = React.useCallback(() => {
promptDetailRequestRef.current += 1;
setPromptDetailLoading(false);
@@ -1268,6 +1336,7 @@ function App() {
modelDisplayName: local?.modelMappings?.find((mapping) => mapping.model === row.model)?.displayName,
apiKey: row.apiKey,
wireApi: row.wireApi,
upstreamApi: local?.upstreamApi || row.upstreamApi,
requiresOpenaiAuth: row.requiresOpenaiAuth,
isCurrent: row.isCurrent,
isDefaultOfficial: row.isDefaultOfficial,
@@ -1285,6 +1354,13 @@ function App() {
};
}), [findLocalProviderForRow, lang, providerCopySourceForRow, providerRows, providerOrder, state?.codexDir]);
const balanceRevision = React.useMemo(() => JSON.stringify([
providerRows.filter(row => row.source !== "official").map(row => [row.source, row.id, row.baseUrl, row.apiKey]),
savedProviders.map(provider => [provider.id, provider.tomlConfig]),
state?.configText,
]), [providerRows, savedProviders, state?.configText]);
const providerBalances = useProviderBalances(state?.codexDir || configDir, balanceRevision, Boolean(state) && !refreshing);
const saveProviderOrder = async (order: string[]): Promise<boolean> => {
const directory = state?.codexDir;
if (!directory || providerOrder.directory !== directory || loadingTokensRef.current.size || actionBusyTokensRef.current.size) return false;
@@ -1400,6 +1476,7 @@ function App() {
const activeCodexDir = state?.codexDir || configDir;
setRefreshing(true);
setError("");
sessionStateRef.current = null;
setState(null);
setOfficialProfiles([]);
setSessionStatus(null);
@@ -1409,7 +1486,7 @@ function App() {
setAboutInfo(null);
aboutLoadKeyRef.current = "";
sessionAutoLoadKeyRef.current = "";
sessionLoadRequestRef.current += 1;
sessionStatusTrackerRef.current.invalidate();
if (includeDiagnostics) {
setStartupDiagnostics(null);
@@ -1463,6 +1540,7 @@ function App() {
setConfigDir(next.codexDir);
setHealthConfigDir(next.codexDir);
setConfigDirDraft(next.codexDir);
sessionStateRef.current = next;
setState(next);
setRefreshing(false);
@@ -1673,10 +1751,9 @@ function App() {
const handleActionResult = (result: ActionResult) => {
const profilesRequestId = ++officialProfilesRequestRef.current;
const providersRequestId = ++savedProvidersRequestRef.current;
sessionStateRef.current = result.state;
setState(result.state);
setSessionStatus(null);
sessionAutoLoadKeyRef.current = "";
sessionLoadRequestRef.current += 1;
invalidateSessionStatus();
setToast(result.message);
return Promise.allSettled([
invoke<SavedPrompt[]>("list_saved_prompts"),
@@ -1910,7 +1987,8 @@ function App() {
model: providerForm.model.trim(),
apiKey: (providerForm.apiKey || "").trim(),
tomlConfig: tomlConfig.trimEnd(),
wireApi: providerForm.wireApi || "responses",
wireApi: "responses",
upstreamApi: providerUpstreamApi(providerForm),
requiresOpenaiAuth: providerForm.requiresOpenaiAuth,
});
@@ -1918,6 +1996,9 @@ function App() {
if (savedProviders.some((saved) => saved.id === provider.id)) {
return invoke<ActionResult>("activate_saved_provider", { configDir: configDir || null, providerId: provider.id });
}
if (providerRequiresConversion(provider)) {
return Promise.reject(lang === "zh" ? "请先保存供应商,并在设置中开启本地路由和配置接管后启用。" : "Save this provider and enable the local router with config takeover in Settings before activating it.");
}
const tomlConfig = provider.tomlConfig?.trim();
if (tomlConfig) {
return invoke<ActionResult>("save_provider_toml_config", {
@@ -2000,8 +2081,25 @@ function App() {
);
};
const activateProvider = async (apply: () => Promise<ActionResult>, success: (result: ActionResult) => void) => {
if (!getSessionStatusContext() || providerActivationInFlightRef.current || sessionDeleteBusyRef.current
|| providerActivationIsBusy(loadingTokensRef.current.values(), actionBusyTokensRef.current.values())) return;
providerActivationInFlightRef.current += 1;
providerActivationRevisionRef.current += 1;
if (Array.from(actionBusyTokensRef.current.values()).includes("syncSessions")) sessionRefreshPendingRef.current = true;
invalidateSessionStatus();
try {
await call(apply, success);
} finally {
providerActivationInFlightRef.current -= 1;
if (sessionRefreshPendingRef.current && !sessionMutationInFlightRef.current) {
await refreshSyncedSessionStatusRef.current();
}
}
};
const switchProvider = (provider: SavedProvider) =>
call(
activateProvider(
() => applyProviderConfig(provider),
(result) => {
localStorage.setItem(ACTIVE_PROVIDER_KEY, provider.id);
@@ -2022,9 +2120,9 @@ function App() {
const fetchProviderModels = async () => {
const baseUrl = providerForm.baseUrl.trim();
const apiKey = (providerForm.apiKey || "").trim();
if (!baseUrl || !apiKey) {
if (!baseUrl) {
setError("");
setToast(lang === "zh" ? "请先填写 API 请求地址和 API Key" : "Enter the API URL and API key first");
setToast(lang === "zh" ? "请先填写 API 请求地址;认证可使用 API Key 或供应商 Headers" : "Enter the API URL first. Authentication can use an API key or provider headers");
return;
}
@@ -2034,7 +2132,7 @@ function App() {
setError("");
setToast(lang === "zh" ? "正在获取模型列表..." : "Fetching model list...");
try {
const result = await invoke<ProviderModelsResult>("fetch_provider_models", { baseUrl, apiKey });
const result = await invoke<ProviderModelsResult>("fetch_provider_models", { baseUrl, apiKey, upstreamApi: providerUpstreamApi(providerForm), configText: providerTomlDraft });
if (providerModelsRequestRef.current !== requestId) return;
setAvailableProviderModels(result.models);
setToast(result.models.length > 0
@@ -2049,13 +2147,13 @@ function App() {
}
};
const testProvider = async (id: string, baseUrl: string, apiKey?: string | null) => {
const testProvider = async (id: string, baseUrl: string, apiKey?: string | null, provider?: SavedProvider) => {
const actionToken = beginActionBusy("testProvider");
setProviderTestingId(id);
setError("");
setToast(lang === "zh" ? "正在检测连接..." : "Testing connection...");
try {
const result = await invoke<ProviderConnectionResult>("test_provider_connection", { baseUrl, apiKey: apiKey || null });
const result = await invoke<ProviderConnectionResult>("test_provider_connection", { baseUrl, apiKey: apiKey || null, upstreamApi: provider ? providerUpstreamApi(provider) : "responses", configText: provider?.tomlConfig || null });
if (result.ok) {
setToast(lang === "zh" ? `连接成功,响应延迟 ${result.durationMs}ms` : `Connected, ${result.durationMs}ms latency`);
} else {
@@ -2074,7 +2172,7 @@ function App() {
const saveProviderConfig = saveProviderOnly;
const switchOfficialProvider = (profileId = DEFAULT_OFFICIAL_PROFILE_ID) =>
call(
activateProvider(
() => invoke<ActionResult>("switch_official_profile", { configDir: configDir || null, profileId }),
(result) => {
localStorage.removeItem(ACTIVE_PROVIDER_KEY);
@@ -2179,9 +2277,11 @@ function App() {
const checkForUpdates = React.useCallback(async ({ quiet = false }: { quiet?: boolean } = {}) => {
setReleaseInfo({ status: "checking" });
let nativeCheckAttempted = false;
try {
if (aboutInfo?.nativeUpdaterSupported !== false) {
const updaterResult = await appUpdater.check({ force: !quiet, timeout: 15_000 });
nativeCheckAttempted = true;
const updaterResult = await appUpdater.check({ force: !quiet, timeout: 30_000 });
if (updaterResult === "available") {
const snapshot = appUpdater.getSnapshot();
const latestVersion = snapshot.latestVersion || "";
@@ -2207,25 +2307,27 @@ function App() {
latestVersion: aboutInfo?.appVersion,
htmlUrl: `https://github.com/${FALLBACK_GITHUB_REPO}/releases/latest`,
hasUpdate: false,
updateMethod: "native",
});
if (!quiet) setToast(lang === "zh" ? "当前已是最新版本" : "You are up to date");
return;
}
}
// Keep the existing lightweight release check as a manual-download fallback for
// bootstrap and portable builds that cannot use the native updater yet.
// Metadata is useful even when the native channel is unavailable. It
// cannot supply an updater RID or replace the signed installation check.
const update = await invoke<AppUpdateInfo>("check_app_update");
const message = update.hasUpdate
? (lang === "zh" ? "发现新版本" : "Update available")
: (lang === "zh" ? "当前已是最新版本" : "You are up to date");
setReleaseInfo({
status: "ok",
latestVersion: update.latestVersion,
htmlUrl: update.htmlUrl,
hasUpdate: update.hasUpdate,
updateMethod: update.hasUpdate ? "download" : undefined,
});
setReleaseInfo(releaseInfoFromFallback(update, nativeCheckAttempted));
if (nativeCheckAttempted) {
if (quiet && update.hasUpdate) {
setToast(lang === "zh"
? `发现新版本 ${update.latestVersion},但在线更新检查失败,可重新检查`
: `Version ${update.latestVersion} is available, but the in-app update check failed. Retry the check`);
} else if (!quiet) {
setUpdatePromptOpen(true);
}
return;
}
if (update.hasUpdate) {
if (quiet) {
setToast(lang === "zh" ? `发现新版本 ${update.latestVersion},可在概览页查看` : `New version ${update.latestVersion} is available`);
@@ -2233,14 +2335,15 @@ function App() {
setUpdatePromptOpen(true);
}
} else if (!quiet) {
setToast(message);
setToast(lang === "zh" ? "当前已是最新版本" : "You are up to date");
}
} catch {
const message = quiet ? (lang === "zh" ? "自动检查失败" : "Auto check failed") : (lang === "zh" ? "检查失败" : "Check failed");
setReleaseInfo({
status: "error",
});
if (!quiet) setToast(message);
setReleaseInfo(releaseInfoFromCheckFailure(nativeCheckAttempted));
if (!quiet && nativeCheckAttempted) {
setUpdatePromptOpen(true);
} else if (!quiet) {
setToast(lang === "zh" ? "检查失败" : "Check failed");
}
}
}, [aboutInfo?.appVersion, aboutInfo?.nativeUpdaterSupported, lang]);
@@ -2426,19 +2529,22 @@ function App() {
};
const restartCodexDesktop = async () => {
if (restartCodexBusyRef.current) return false;
if (restartCodexBusyRef.current || loadingTokensRef.current.size || actionBusyTokensRef.current.size) return false;
restartCodexBusyRef.current = true;
setRestartCodexBusy(true);
const actionToken = beginActionBusy("restartCodexDesktop");
setError("");
setRestartCodexError("");
try {
const result = await invoke<CodexDesktopRestartResult>("restart_codex_desktop");
const result = await invoke<CodexDesktopRestartResult>("restart_codex_desktop", { configDir });
setLanguageRestartNotice(null);
setToast(result.wasRunning
? (lang === "zh" ? `${result.appName} 已重新启动` : `${result.appName} restarted`)
: (lang === "zh" ? `${result.appName} 已启动` : `${result.appName} started`));
return true;
} catch (e) {
setError(String(e));
setRestartCodexError(String(e));
return false;
} finally {
endActionBusy(actionToken);
@@ -2649,7 +2755,8 @@ function App() {
const newCustomProviderForm = (configText = providerCreationBase): SavedProvider => ({
...blankProviderForm,
model: state?.model?.trim() || blankProviderForm.model,
wireApi: currentProvider?.wireApi?.trim() || blankProviderForm.wireApi,
wireApi: "responses",
upstreamApi: providerUpstreamApi(currentProvider || blankProviderForm),
requiresOpenaiAuth: currentProvider?.requiresOpenaiAuth ?? blankProviderForm.requiresOpenaiAuth,
tomlConfig: configText.trim(),
});
@@ -2771,7 +2878,8 @@ function App() {
model: provider.model,
apiKey: provider.apiKey || "",
tomlConfig: state?.configText?.trim() || "",
wireApi: provider.wireApi || "responses",
wireApi: "responses",
upstreamApi: providerUpstreamApi(provider),
requiresOpenaiAuth: provider.requiresOpenaiAuth,
};
setProviderForm(next);
@@ -2829,13 +2937,14 @@ function App() {
};
const checkSessions = async () => {
sessionLoadRequestRef.current += 1;
if (!getSessionStatusContext() || loadingTokensRef.current.size || actionBusyTokensRef.current.size || sessionDeleteBusyRef.current) return;
sessionStatusTrackerRef.current.invalidate();
const actionToken = beginActionBusy("checkSessions");
setSessionStatus(null);
await call(
() => invoke<SessionSyncStatus>("get_session_sync_status", { configDir: configDir || null, targetProvider: null }),
loadCurrentSessionStatus,
(status) => {
setSessionStatus(status);
if (!status) return;
if (!status.scanComplete) {
setToast(status.scanFailures[0] || (lang === "zh" ? "无法确认会话同步状态" : "Unable to verify session sync status"));
return;
@@ -2851,52 +2960,90 @@ function App() {
};
React.useEffect(() => {
if (tab !== "sessions" || refreshing || !state?.codexDir) return;
const loadKey = state.codexDir;
if (tab !== "sessions" || refreshing || loading) return;
const context = getSessionStatusContext();
if (!context) return;
const loadKey = sessionStatusContextKey(context);
if (sessionAutoLoadKeyRef.current === loadKey) return;
const requestId = ++sessionLoadRequestRef.current;
const actionToken = beginActionBusy("checkSessions");
sessionAutoLoadKeyRef.current = loadKey;
void invoke<SessionSyncStatus>("get_session_sync_status", {
configDir: loadKey,
targetProvider: null,
})
.then((status) => {
if (requestId === sessionLoadRequestRef.current) setSessionStatus(status);
})
void loadCurrentSessionStatus()
.catch((sessionError) => {
if (requestId !== sessionLoadRequestRef.current) return;
sessionAutoLoadKeyRef.current = "";
setError(String(sessionError));
})
.finally(() => {
endActionBusy(actionToken);
});
}, [beginActionBusy, endActionBusy, refreshing, state?.codexDir, tab]);
}, [beginActionBusy, endActionBusy, getSessionStatusContext, loadCurrentSessionStatus, loading, refreshing, state?.codexDir, state?.modelProvider, state?.activeSavedProviderId, state?.activeOfficialProfileId, tab]);
const syncSessions = async () => {
sessionLoadRequestRef.current += 1;
const refreshSyncedSessionStatus = async () => {
if (sessionMutationInFlightRef.current || !getSessionStatusContext()) {
sessionRefreshPendingRef.current = true;
return null;
}
sessionRefreshPendingRef.current = false;
const loadingToken = beginLoading("sessionSync");
const actionToken = beginActionBusy("syncSessions");
await call(
() => invoke<SessionSyncResult>("sync_sessions_provider", { configDir: configDir || null, targetProvider: null }),
(result) => {
setSessionStatus(result.status);
setSelectedSessionIds([]);
if (!result.status.scanComplete) {
setToast(result.status.scanFailures[0] || (lang === "zh" ? "无法确认会话同步状态" : "Unable to verify session sync status"));
} else if (result.status.needsSync) {
const remaining = sessionMismatchCount(result.status);
try {
const status = await loadCurrentSessionStatus();
if (status && sessionSyncToastPendingRef.current) {
sessionSyncToastPendingRef.current = false;
if (!status.scanComplete) {
setToast(status.scanFailures[0] || (lang === "zh" ? "无法确认会话同步状态" : "Unable to verify session sync status"));
} else if (status.needsSync) {
const remaining = sessionMismatchCount(status);
setToast(lang === "zh"
? `已同步可写的会话索引,仍有 ${remaining} 条需要重试;聊天内容未改动`
: `Writable session indexes were synced; ${remaining} still need retrying. Chat content was not changed.`);
? `本轮同步已完成,当前供应商仍有 ${remaining} 条会话需要同步;聊天内容未改动`
: `This sync finished; ${remaining} session(s) still need syncing for the current provider. Chat content was not changed.`);
} else {
setToast(lang === "zh"
? "会话索引已全部同步,聊天内容未改动"
: "All session indexes are synced. Chat content was not changed.");
}
},
);
endActionBusy(actionToken);
}
return status;
} catch (sessionError) {
sessionSyncToastPendingRef.current = false;
setError(String(sessionError));
return null;
} finally {
endLoading(loadingToken);
endActionBusy(actionToken);
}
};
refreshSyncedSessionStatusRef.current = refreshSyncedSessionStatus;
const syncSessions = async () => {
const context = getSessionStatusContext();
if (!context || loadingTokensRef.current.size || actionBusyTokensRef.current.size || sessionDeleteBusyRef.current) return;
// Capture primitives at the click, before the IPC worker can be queued
// behind a provider switch. The backend keeps this target for the whole job.
const target = { ...context };
sessionStatusTrackerRef.current.invalidate();
const actionToken = beginActionBusy("syncSessions");
const loadingToken = beginLoading("sessionSync");
sessionMutationInFlightRef.current = true;
sessionSyncToastPendingRef.current = false;
setError("");
try {
await invoke<SessionSyncResult>("sync_sessions_provider", {
configDir: target.configDir,
targetProvider: target.targetProvider,
});
setSelectedSessionIds([]);
sessionSyncToastPendingRef.current = true;
} catch (syncError) {
if (target.configDir === sessionStateRef.current?.codexDir) setError(String(syncError));
} finally {
sessionMutationInFlightRef.current = false;
sessionRefreshPendingRef.current = true;
// Never apply the old job's status to a newly active provider. Re-read
// the current context, or let the in-flight activation do so on completion.
await refreshSyncedSessionStatusRef.current();
endLoading(loadingToken);
endActionBusy(actionToken);
}
};
const toggleSessionSelected = (id: string) => {
@@ -2921,7 +3068,10 @@ function App() {
};
const deleteSelectedSessions = async () => {
if (!selectedSessionIds.length || sessionDeleteBusy || !sessionDeleteSafetyConfirmed) return;
if (!selectedSessionIds.length || sessionDeleteBusyRef.current || !sessionDeleteSafetyConfirmed
|| loadingTokensRef.current.size || actionBusyTokensRef.current.size) return;
sessionDeleteBusyRef.current = true;
const loadingToken = beginLoading();
setSessionDeleteBusy(true);
setToast("");
setError("");
@@ -2950,7 +3100,9 @@ function App() {
} catch (e) {
setError(String(e));
} finally {
sessionDeleteBusyRef.current = false;
setSessionDeleteBusy(false);
endLoading(loadingToken);
}
};
@@ -3009,8 +3161,18 @@ function App() {
message={toast}
error={error}
loading={Boolean(providerTestingId || providerModelsLoading) && Boolean(toast)}
onDismissMessage={() => setToast("")}
onDismissError={() => setError("")}
persistent={Boolean(error) && error === restartCodexError}
action={error && error === restartCodexError ? {
label: lang === "zh" ? "重试" : "Retry",
onClick: () => { void restartCodexDesktop(); },
disabled: restartCodexBusy || loading || Boolean(actionBusy),
} : !error && languageRestartNotice?.configDir === configDir && languageRestartNotice.message === toast ? {
label: lang === "zh" ? "点我重启" : "Restart now",
onClick: () => { void restartCodexDesktop(); },
disabled: restartCodexBusy || loading || Boolean(actionBusy),
} : undefined}
onDismissMessage={() => { setToast(""); setLanguageRestartNotice(null); }}
onDismissError={() => { setError(""); setRestartCodexError(""); }}
/>
{configHealth.noticeVisible && configHealth.notice && <ConfigHealthToast
lang={lang}
@@ -3033,7 +3195,10 @@ function App() {
latestVersion={releaseInfo.latestVersion}
onClose={() => setUpdatePromptOpen(false)}
onUpdate={releaseInfo.updateMethod === "native" ? updater.downloadAndInstall : undefined}
onRetry={releaseInfo.updateMethod === "native" ? updater.retry : undefined}
onRetry={releaseInfo.updateMethod === "native" ? async () => {
if (updater.state.failure === "check") await checkForUpdates();
else await updater.retry();
} : undefined}
onRestart={releaseInfo.updateMethod === "native" ? updater.restart : undefined}
onDownload={() => {
setUpdatePromptOpen(false);
@@ -3117,10 +3282,12 @@ function App() {
officialProfileIsDefault={editingOfficialProfileId === DEFAULT_OFFICIAL_PROFILE_ID}
canLoadCurrentOfficial={Boolean(state.isOfficialProvider)}
providerRows={providerPageRows}
providerBalances={providerBalances}
configDir={configDir}
loading={loading}
testingId={providerTestingId}
actionBusy={actionBusy}
activationBusy={providerActivationBusy || refreshing || sessionDeleteBusy}
orderBusy={providerOrder.directory !== state.codexDir}
onReorderProviders={saveProviderOrder}
editingProviderId={editingProviderId || (editingDetectedProvider ? providerForm.id : null)}
@@ -3129,7 +3296,8 @@ function App() {
baseUrl: providerForm.baseUrl,
providerName: providerForm.providerName,
model: providerForm.model,
wireApi: providerForm.wireApi,
wireApi: "responses",
upstreamApi: providerUpstreamApi(providerForm),
requiresOpenaiAuth: providerForm.requiresOpenaiAuth,
}}
officialForm={officialForm}
@@ -3170,7 +3338,7 @@ function App() {
}}
onTestProvider={(row) => {
const local = findLocalProviderForRow(row);
void testProvider(row.testingKey || `${row.source}-${row.id}`, row.baseUrl, local?.apiKey || row.apiKey || null);
void testProvider(row.testingKey || `${row.source}-${row.id}`, row.baseUrl, local?.apiKey || row.apiKey || null, local);
}}
onEditProvider={(row) => {
if (row.source === "official") {
@@ -3226,7 +3394,10 @@ function App() {
}))}
onProviderModelChange={(value) => setProviderForm((current) => ({ ...current, model: value }))}
onFetchModels={() => void fetchProviderModels()}
onWireApiChange={(value) => setProviderForm((current) => ({ ...current, wireApi: value }))}
onUpstreamApiChange={(value) => {
resetAvailableProviderModels();
setProviderForm((current) => ({ ...current, upstreamApi: value, wireApi: "responses" }));
}}
onRequiresAuthChange={(value) => setProviderForm((current) => ({ ...current, requiresOpenaiAuth: value }))}
onToggleApiKeyVisibility={() => setProviderApiKeyVisible((value) => !value)}
onProviderTomlDraftChange={(value, origin = "manual") => {
@@ -3235,6 +3406,11 @@ function App() {
setProviderTomlDirty(true);
if (origin === "manual") setProviderCommonConfigDirty(true);
}}
onProviderHeadersConfigChange={(value) => {
providerDraftRequestRef.current += 1;
setProviderTomlDraft(value);
setProviderForm((current) => ({ ...current, tomlConfig: value }));
}}
onResetProviderToml={() => {
providerDraftRequestRef.current += 1;
setProviderTomlDraft(
@@ -3462,6 +3638,19 @@ function App() {
configDir={configDir}
onChange={async () => { routingRequestRefreshRef.current(); }}
generalRequest={settingsGeneralRequest}
interactionBusy={loading || refreshing || Boolean(actionBusy) || restartCodexBusy || isAppUpdateBusy(updater.state.phase)}
onLanguageBusyChange={handleLanguageBusyChange}
onCodexLanguageSaved={(status) => {
setError("");
if (status.pendingEnabled == null) {
setLanguageRestartNotice(null);
setToast(lang === "zh" ? "已取消待重启的语言更改" : "Pending language change cancelled");
return;
}
const message = lang === "zh" ? "语言设置已保存,重启 Codex / ChatGPT 后生效" : "Language setting saved. Restart Codex / ChatGPT to apply.";
setLanguageRestartNotice({ configDir, message });
setToast(message);
}}
configHealthStatus={<ConfigHealthStatus
lang={lang}
report={configHealth.report}
+37
View File
@@ -0,0 +1,37 @@
export const MAX_AUTH_IMPORT_BYTES = 1024 * 1024;
type ImportErrorCode = "too_large" | "invalid_text" | "invalid_json" | "unsupported_shape";
export class OfficialAuthImportError extends Error {
readonly code: ImportErrorCode;
constructor(code: ImportErrorCode) {
super(code);
this.name = "OfficialAuthImportError";
this.code = code;
}
}
export function parseOfficialAuthImport(bytes: Uint8Array): string {
if (bytes.byteLength > MAX_AUTH_IMPORT_BYTES) throw new OfficialAuthImportError("too_large");
let text: string;
try { text = new TextDecoder("utf-8", { fatal: true }).decode(bytes).replace(/^\uFEFF/, "").trim(); }
catch { throw new OfficialAuthImportError("invalid_text"); }
let value: unknown;
try { value = JSON.parse(text); }
catch { throw new OfficialAuthImportError("invalid_json"); }
if (!value || typeof value !== "object" || Array.isArray(value)) throw new OfficialAuthImportError("unsupported_shape");
const auth = value as Record<string, unknown>;
const tokens = auth.tokens && typeof auth.tokens === "object" && !Array.isArray(auth.tokens)
? auth.tokens as Record<string, unknown> : null;
const nonempty = (value: unknown) => typeof value === "string" && Boolean(value.trim());
if (["base_url", "baseUrl", "api_base", "endpoint"].some(key => Object.prototype.hasOwnProperty.call(auth, key))
|| !(nonempty(auth.OPENAI_API_KEY) || (tokens && [tokens.access_token, tokens.id_token, tokens.refresh_token].some(nonempty)))) {
throw new OfficialAuthImportError("unsupported_shape");
}
// Only load the editor draft. The existing save command validates credentials.
return text;
}
export async function readOfficialAuthImport(file: Pick<File, "size" | "arrayBuffer">): Promise<string> {
if (file.size > MAX_AUTH_IMPORT_BYTES) throw new OfficialAuthImportError("too_large");
return parseOfficialAuthImport(new Uint8Array(await file.arrayBuffer()));
}
+92 -17
View File
@@ -23,8 +23,13 @@ import type { LucideIcon } from "lucide-react";
import type { Ref } from "react";
import { PageTransition } from "../components/PageTransition";
import { OfficialQuotaDialog } from "../components/OfficialQuotaDialog";
import { ProviderBalanceBadge } from "../components/ProviderBalanceBadge";
import { supportsProviderBalance, type ProviderBalanceState } from "../providerBalance";
import { OfficialAccountBadge } from "../components/OfficialAccountBadge";
import { ProviderModelMappings, validateProviderModelMappings } from "../components/ProviderModelMappings";
import { ProviderHeadersControl } from "../components/ProviderHeadersControl";
import { providerUpstreamApi } from "../providerProtocol";
import { OfficialAuthImportError, readOfficialAuthImport } from "../officialAuthImport";
import { ProviderPresetPicker } from "../components/ProviderPresetPicker";
import { PROVIDER_PRESETS, getProviderPreset, getProviderPresetVariant } from "../providerPresets";
import { Button, Checkbox, ModalShell } from "../components/ui";
@@ -43,6 +48,7 @@ export type ProviderRow = {
modelDisplayName?: string;
apiKey?: string;
wireApi: string;
upstreamApi?: string | null;
requiresOpenaiAuth: boolean;
isCurrent: boolean;
isDefaultOfficial?: boolean;
@@ -65,6 +71,7 @@ export type ProviderFormValue = {
providerName: string;
model: string;
wireApi: string;
upstreamApi?: string | null;
requiresOpenaiAuth: boolean;
};
@@ -149,9 +156,11 @@ export type ProvidersPageProps = {
copy: ProviderCopy;
mode: ProviderMode;
providerRows: readonly ProviderRow[];
providerBalances?: ProviderBalanceState;
loading: boolean;
testingId: string;
actionBusy?: string;
activationBusy?: boolean;
orderBusy?: boolean;
onReorderProviders: (order: string[]) => Promise<boolean>;
editingProviderId: string | null;
@@ -196,10 +205,11 @@ export type ProvidersPageProps = {
onProviderNameChange: (value: string) => void;
onProviderModelChange: (value: string) => void;
onFetchModels: () => void;
onWireApiChange: (value: string) => void;
onUpstreamApiChange: (value: string) => void;
onRequiresAuthChange: (value: boolean) => void;
onToggleApiKeyVisibility: () => void;
onProviderTomlDraftChange: (value: string, origin?: "manual" | "context") => void;
onProviderHeadersConfigChange: (value: string) => void;
onResetProviderToml: () => void;
onSaveProvider: () => void;
};
@@ -396,9 +406,11 @@ function ListPage({
configDir,
copy,
providerRows,
providerBalances,
loading,
testingId,
actionBusy,
activationBusy,
orderBusy,
onImportCcSwitch,
onAddProvider,
@@ -408,11 +420,12 @@ function ListPage({
onDuplicateProvider,
onDeleteProvider,
onReorderProviders,
}: Pick<ProvidersPageProps, "lang" | "configDir" | "copy" | "providerRows" | "loading" | "testingId" | "actionBusy" | "orderBusy" | "onReorderProviders" | "onImportCcSwitch" | "onAddProvider" | "onEnableProvider" | "onTestProvider" | "onEditProvider" | "onDuplicateProvider" | "onDeleteProvider">) {
}: Pick<ProvidersPageProps, "lang" | "configDir" | "copy" | "providerRows" | "providerBalances" | "loading" | "testingId" | "actionBusy" | "activationBusy" | "orderBusy" | "onReorderProviders" | "onImportCcSwitch" | "onAddProvider" | "onEnableProvider" | "onTestProvider" | "onEditProvider" | "onDuplicateProvider" | "onDeleteProvider">) {
const [providerToDelete, setProviderToDelete] = useState<ProviderRow | null>(null);
const [quotaSelection, setQuotaSelection] = useState<{ id: string; configDir: string; email: string | null } | null>(null);
const [deleting, setDeleting] = useState(false);
const providerActionsBusy = loading || Boolean(actionBusy);
const providerActivationBusy = activationBusy ?? providerActionsBusy;
const sortingDisabled = providerActionsBusy || Boolean(orderBusy) || providerRows.length < 2;
const listRef = useRef<HTMLDivElement>(null);
const pointerDragRef = useRef<{ key: string; pointerId: number; startY: number; moved: boolean } | null>(null);
@@ -529,13 +542,15 @@ function ListPage({
{providerRows.length === 0 ? (
<div className="cx-providers-empty" role="status">{copy.noProviders}</div>
) : providerRows.map((row) => {
const balance = providerBalances?.balances.find(item => item.source === row.source && item.providerId === row.id);
const showBalance = row.source !== "official" && (balance ? balance.supported : supportsProviderBalance(row.baseUrl));
const testingKey = row.testingKey || `${row.source}-${row.id}`;
const isTesting = testingId === testingKey;
const isProtectedOfficial = row.source === "official" && row.isDefaultOfficial === true;
const key = providerRowKey(row);
const modelName = row.modelDisplayName || row.model || (lang === "zh" ? "跟随 Codex" : "Follow Codex");
return (
<article className={`cx-providers-row${row.isCurrent ? " cx-providers-row--current" : ""}${row.source === "official" ? " cx-providers-row--official" : ""}${draggedKey === key ? " cx-providers-row--dragging" : ""}${dropTarget?.key === key && draggedKey !== key ? ` cx-providers-row--drop-${dropTarget.position}` : ""}`} key={key} role="listitem" data-provider-key={key}>
<article className={`cx-providers-row${row.isCurrent ? " cx-providers-row--current" : ""}${row.source === "official" ? " cx-providers-row--official" : showBalance ? " cx-providers-row--balance" : ""}${draggedKey === key ? " cx-providers-row--dragging" : ""}${dropTarget?.key === key && draggedKey !== key ? ` cx-providers-row--drop-${dropTarget.position}` : ""}`} key={key} role="listitem" data-provider-key={key}>
<button type="button" className="cx-providers-drag-handle" disabled={sortingDisabled}
aria-label={lang === "zh" ? `排序 ${row.providerName}:拖动或按上下箭头移动` : `Reorder ${row.providerName}: drag or use Up and Down arrows`}
title={lang === "zh" ? "拖动排序,也可按上下箭头移动" : "Drag to reorder, or use Up and Down arrows"}
@@ -593,13 +608,14 @@ function ListPage({
</div>
</div>
{row.source === "official" && <OfficialAccountBadge lang={lang} email={row.email} planType={row.planType} hasAuth={Boolean(row.hasAuth)} canQueryQuota={Boolean(row.canQueryQuota)} className="cx-providers-login-badge" />}
{showBalance && <ProviderBalanceBadge balance={balance} loading={providerBalances?.loading ?? true} refreshing={providerBalances?.refreshingKeys.includes(`${row.source}:${row.id}`)} failed={providerBalances?.failed ?? false} lang={lang} onRefresh={row.source !== "official" && providerBalances ? () => { void providerBalances.refreshBalance(row.source as "local" | "detected", row.id); } : undefined} />}
<div className="cx-providers-row-actions">
{row.isCurrent && <span className="cx-providers-current-badge"><span aria-hidden="true" />{copy.currentLabel}</span>}
<button
type="button"
className="cx-providers-button cx-providers-button--small cx-providers-button--secondary"
onClick={() => onEnableProvider(row)}
disabled={providerActionsBusy || row.isCurrent}
disabled={providerActivationBusy || row.isCurrent}
>
{copy.enableLabel}
</button>
@@ -731,9 +747,15 @@ function OfficialForm({
}: Pick<ProvidersPageProps, "lang" | "copy" | "creatingProvider" | "selectedPresetId" | "selectedPresetVariantId" | "onPresetSelect" | "onPresetVariantSelect" | "officialForm" | "officialProfileIsDefault" | "canLoadCurrentOfficial" | "officialAuthRef" | "officialTomlRef" | "officialInfo" | "loading" | "actionBusy" | "onCancelMode" | "onOfficialNameChange" | "onOfficialModelChange" | "onOfficialAuthChange" | "onOfficialConfigChange" | "onSaveOfficial" | "onLoadCcSwitchOfficial" | "onLoadCurrentOfficial" | "onResetOfficial">) {
const [resetConfirmOpen, setResetConfirmOpen] = useState(false);
const [contextWindowBusy, setContextWindowBusy] = useState(false);
const [authImportBusy, setAuthImportBusy] = useState(false);
const [authImportError, setAuthImportError] = useState("");
const [authImportName, setAuthImportName] = useState("");
const authFileRef = useRef<HTMLInputElement>(null);
const authImportRequest = useRef(0);
useEffect(() => () => { authImportRequest.current += 1; }, []);
const loadingCcSwitch = actionBusy === "loadCcSwitchOfficial";
const loadingCurrent = actionBusy === "loadCurrentOfficial";
const formBusy = loading || actionBusy === "loadOfficialDraft" || loadingCcSwitch || loadingCurrent || contextWindowBusy;
const formBusy = loading || actionBusy === "loadOfficialDraft" || loadingCcSwitch || loadingCurrent || contextWindowBusy || authImportBusy;
const showDefaultActions = officialProfileIsDefault && !creatingProvider;
const profileHint = lang === "zh"
? "认证内容可留空;保存并启用后,在 Codex 中完成登录。复制官方供应商会保留原认证,并可修改名称。"
@@ -745,6 +767,23 @@ function OfficialForm({
onResetOfficial();
};
const importAuthFile = async (file: File) => {
if (formBusy) return;
const request = ++authImportRequest.current;
setAuthImportBusy(true); setAuthImportError(""); setAuthImportName("");
try {
const text = await readOfficialAuthImport(file);
if (request !== authImportRequest.current) return;
onOfficialAuthChange(text);
setAuthImportName(file.name);
} catch (error) {
if (request !== authImportRequest.current) return;
setAuthImportError(error instanceof OfficialAuthImportError && error.code === "too_large"
? (lang === "zh" ? "认证文件超过 1 MiB,请选择单个 auth.json。" : "Choose a single auth.json file smaller than 1 MiB.")
: (lang === "zh" ? "请选择有效的单个 Codex auth.json;批量账号或其他工具的封装格式暂不支持。" : "Choose a valid single Codex auth.json. Account arrays and other export formats are not supported yet."));
} finally { if (request === authImportRequest.current) setAuthImportBusy(false); }
};
return (
<>
<ModeHeader
@@ -781,6 +820,17 @@ function OfficialForm({
/>
</div>
<Field label={copy.officialAuthLabel} className="cx-providers-editor-field">
<div className="cx-providers-context-heading">
<button type="button" className="cx-providers-button cx-providers-button--secondary" disabled={formBusy} onClick={() => authFileRef.current?.click()}>
<Download size={14} aria-hidden="true" />{lang === "zh" ? "导入 auth.json 文件" : "Import auth.json file"}
</button>
<input ref={authFileRef} type="file" accept=".json,application/json" hidden onChange={event => {
const file = event.currentTarget.files?.[0]; event.currentTarget.value = "";
if (file) void importAuthFile(file);
}} />
</div>
{authImportError && <span className="cx-providers-context-error" role="alert">{authImportError}</span>}
{authImportName && <span className="cx-providers-context-hint" role="status">{lang === "zh" ? `已读入 ${authImportName},保存官方账号后生效。` : `Loaded ${authImportName}. Save the official account to apply it.`}</span>}
<textarea
ref={officialAuthRef}
className="cx-providers-code-editor cx-providers-auth-editor"
@@ -859,17 +909,21 @@ function ProviderForm({
onProviderNameChange,
onProviderModelChange,
onFetchModels,
onWireApiChange,
onUpstreamApiChange,
onRequiresAuthChange,
onToggleApiKeyVisibility,
onProviderTomlDraftChange,
onProviderHeadersConfigChange,
onResetProviderToml,
onSaveProvider,
}: Pick<ProvidersPageProps, "lang" | "copy" | "creatingProvider" | "selectedPresetId" | "selectedPresetVariantId" | "onPresetSelect" | "onPresetVariantSelect" | "providerForm" | "providerModelMappings" | "onProviderModelMappingsChange" | "loading" | "editingProviderId" | "providerAuthPreview" | "providerTomlDraft" | "providerTomlRef" | "apiKeyVisible" | "availableModels" | "fetchingModels" | "onCancelMode" | "onApiKeyChange" | "onBaseUrlChange" | "onProviderNameChange" | "onProviderModelChange" | "onFetchModels" | "onWireApiChange" | "onRequiresAuthChange" | "onToggleApiKeyVisibility" | "onProviderTomlDraftChange" | "onResetProviderToml" | "onSaveProvider">) {
}: Pick<ProvidersPageProps, "lang" | "copy" | "creatingProvider" | "selectedPresetId" | "selectedPresetVariantId" | "onPresetSelect" | "onPresetVariantSelect" | "providerForm" | "providerModelMappings" | "onProviderModelMappingsChange" | "loading" | "editingProviderId" | "providerAuthPreview" | "providerTomlDraft" | "providerTomlRef" | "apiKeyVisible" | "availableModels" | "fetchingModels" | "onCancelMode" | "onApiKeyChange" | "onBaseUrlChange" | "onProviderNameChange" | "onProviderModelChange" | "onFetchModels" | "onUpstreamApiChange" | "onRequiresAuthChange" | "onToggleApiKeyVisibility" | "onProviderTomlDraftChange" | "onProviderHeadersConfigChange" | "onResetProviderToml" | "onSaveProvider">) {
const modelListId = useId();
const [contextWindowBusy, setContextWindowBusy] = useState(false);
const canFetchModels = Boolean(providerForm.baseUrl.trim() && providerForm.apiKey.trim());
const formBusy = loading || fetchingModels || contextWindowBusy;
const [headersBusy, setHeadersBusy] = useState(false);
const [headersValid, setHeadersValid] = useState(true);
const [headersRevision, setHeadersRevision] = useState(0);
const canFetchModels = Boolean(providerForm.baseUrl.trim());
const formBusy = loading || fetchingModels || contextWindowBusy || headersBusy;
const mappingsValid = validateProviderModelMappings(providerModelMappings, providerForm.model, lang).valid;
return (
@@ -918,7 +972,7 @@ function ProviderForm({
type="button"
className="cx-providers-button cx-providers-button--secondary cx-providers-button--small cx-providers-fetch-models"
onClick={onFetchModels}
disabled={loading || fetchingModels || !canFetchModels}
disabled={formBusy || !canFetchModels || !headersValid}
title={copy.fetchModelsLabel}
aria-label={copy.fetchModelsLabel}
>
@@ -948,12 +1002,22 @@ function ProviderForm({
</>
)}
</Field>
<Field label={copy.wireApiLabel}>
<select value={providerForm.wireApi} onChange={(event) => onWireApiChange(event.target.value)} disabled={formBusy}>
<option value="responses">responses</option>
<option value="chat">chat</option>
<Field label={lang === "zh" ? "上游接口协议" : "Upstream API protocol"}>
<select value={providerUpstreamApi(providerForm)} onChange={(event) => onUpstreamApiChange(event.target.value)} disabled={formBusy}>
<option value="responses">OpenAI Responses</option>
<option value="chat_completions">OpenAI Chat Completions</option>
<option value="anthropic_messages">Claude Messages</option>
<option value="gemini">Gemini generateContent</option>
{!["responses", "chat_completions", "anthropic_messages", "gemini"].includes(providerUpstreamApi(providerForm)) && <option value={providerUpstreamApi(providerForm)} disabled>{lang === "zh" ? "不支持的协议,请重新选择" : "Unsupported protocol — choose a supported API"}</option>}
</select>
</Field>
{providerUpstreamApi(providerForm) !== "responses" && (
<p className="cx-providers-field--full cx-providers-protocol-hint">
{lang === "zh"
? "Codex 仍使用 Responses。本协议需在设置中开启本地路由和配置接管;使用期间请保持 Codex-X 运行。关闭路由前请切回 Responses 供应商或官方账号;退出期间请求会暂停,重开后自动恢复。"
: "Codex still uses Responses. Enable the local router and config takeover in Settings, and keep Codex-X running. Switch to a Responses provider or official account before disabling the router. Requests pause while Codex-X is closed and resume after reopening."}
</p>
)}
<Checkbox
className="cx-providers-checkbox cx-providers-checkbox--full"
checked={providerForm.requiresOpenaiAuth}
@@ -964,6 +1028,16 @@ function ProviderForm({
</div>
</section>
<ProviderHeadersControl
key={`headers:${editingProviderId ?? "new-provider"}:${selectedPresetId}:${selectedPresetVariantId}:${headersRevision}`}
lang={lang}
configText={providerTomlDraft}
disabled={loading || fetchingModels || contextWindowBusy}
onConfigChange={onProviderHeadersConfigChange}
onBusyChange={setHeadersBusy}
onValidityChange={setHeadersValid}
/>
<ProviderModelMappings
key={editingProviderId ?? "new-provider"}
lang={lang}
@@ -984,15 +1058,16 @@ function ProviderForm({
<div><h3>{copy.tomlTitle}</h3><p>{copy.tomlDescription}</p></div>
<div className="cx-providers-context-actions">
<ContextWindowControl lang={lang} configText={providerTomlDraft} onConfigChange={(value) => onProviderTomlDraftChange(value, "context")} disabled={formBusy} onBusyChange={setContextWindowBusy} />
<button type="button" className="cx-providers-button cx-providers-button--secondary cx-providers-button--small" onClick={onResetProviderToml} disabled={formBusy}><RefreshCw size={14} aria-hidden="true" />{copy.resetTomlLabel}</button>
<button type="button" className="cx-providers-button cx-providers-button--secondary cx-providers-button--small" onClick={() => { setHeadersRevision((value) => value + 1); onResetProviderToml(); }} disabled={formBusy}><RefreshCw size={14} aria-hidden="true" />{copy.resetTomlLabel}</button>
</div>
</div>
<textarea ref={providerTomlRef} className="cx-providers-code-editor cx-providers-toml-editor" aria-label={copy.tomlTitle} value={providerTomlDraft} onChange={(event) => onProviderTomlDraftChange(event.target.value)} disabled={formBusy} spellCheck={false} />
<textarea ref={providerTomlRef} className="cx-providers-code-editor cx-providers-toml-editor" aria-label={copy.tomlTitle} value={providerTomlDraft} onChange={(event) => { setHeadersRevision((value) => value + 1); onProviderTomlDraftChange(event.target.value); }} disabled={formBusy} spellCheck={false} />
</section>
<div className="cx-providers-form-actions cx-providers-form-actions--save">
{!headersValid && <span className="cx-provider-mappings-save-hint">{lang === "zh" ? "请先修正请求头中的错误。" : "Correct the HTTP header errors before saving."}</span>}
{!mappingsValid && <span className="cx-provider-mappings-save-hint">{lang === "zh" ? "请先修正模型映射中的错误。" : "Correct the model mapping errors before saving."}</span>}
<button type="button" className="cx-providers-button cx-providers-button--primary" onClick={onSaveProvider} disabled={formBusy || !mappingsValid}>
<button type="button" className="cx-providers-button cx-providers-button--primary" onClick={onSaveProvider} disabled={formBusy || !mappingsValid || !headersValid}>
{loading ? <Loader2 size={15} className="cx-providers-spin" aria-hidden="true" /> : <CheckCircle2 size={15} aria-hidden="true" />}
{loading ? copy.savingLabel : copy.saveLabel}
</button>
+13 -3
View File
@@ -18,6 +18,8 @@ import { PageTransition } from "../components/PageTransition";
import { Button, ModalShell } from "../components/ui";
import { UsageStatisticsPage } from "./UsageStatisticsPage";
import { ProviderFailoverPage } from "./ProviderFailoverPage";
import type { CodexLanguageStatus } from "../codexLanguageTypes";
import { CodexLanguageControl } from "../components/CodexLanguageControl";
import "../styles/utility-pages.css";
export type UtilityLanguage = "zh" | "en";
@@ -114,6 +116,9 @@ export type SettingsPageProps = {
onRestartCodex: () => Promise<boolean>;
recheckBusy?: boolean;
restartBusy?: boolean;
interactionBusy?: boolean;
onLanguageBusyChange?: (busy: boolean) => void;
onCodexLanguageSaved?: (status: CodexLanguageStatus) => void;
generalRequest?: number;
configHealthStatus?: ReactNode;
onChange?: () => void | Promise<void>;
@@ -167,6 +172,9 @@ export function SettingsPage({
onRestartCodex,
recheckBusy = false,
restartBusy = false,
interactionBusy = false,
onLanguageBusyChange,
onCodexLanguageSaved,
generalRequest = 0,
configHealthStatus,
onChange,
@@ -182,7 +190,7 @@ export function SettingsPage({
if (!restartBusy) setRestartConfirmOpen(false);
};
const confirmRestart = async () => {
if (restartBusy) return;
if (restartBusy || interactionBusy) return;
if (await onRestartCodex()) setRestartConfirmOpen(false);
};
@@ -232,6 +240,8 @@ export function SettingsPage({
)}
/>
<CodexLanguageControl lang={lang} configDir={configDir} active={active && tab === "general"} disabled={interactionBusy} onBusyChange={onLanguageBusyChange} onPreferencesSaved={onCodexLanguageSaved} />
<SettingRow
icon={Sparkles}
title={copy.productTitle}
@@ -268,7 +278,7 @@ export function SettingsPage({
type="button"
className="cx-page-button cx-page-button--secondary"
onClick={() => setRestartConfirmOpen(true)}
disabled={restartBusy}
disabled={restartBusy || interactionBusy}
>
{restartBusy ? <Loader2 size={15} className="cx-page-spin" aria-hidden="true" /> : <Power size={15} aria-hidden="true" />}
{restartBusy ? copy.restartingLabel : copy.restartLabel}
@@ -306,7 +316,7 @@ export function SettingsPage({
variant="danger"
icon={restartBusy ? <Loader2 size={16} className="cx-page-spin" /> : <Power size={16} />}
onClick={() => void confirmRestart()}
disabled={restartBusy}
disabled={restartBusy || interactionBusy}
>
{restartBusy ? copy.restartingLabel : copy.restartConfirmLabel}
</Button>
+129
View File
@@ -0,0 +1,129 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { invoke } from "@tauri-apps/api/core";
export type ProviderBalance = {
source: "local" | "detected";
providerId: string;
vendor: "deepseek" | "openrouter" | "siliconflow" | "moonshot" | null;
supported: boolean;
balanceKind: "balance" | "credit_limit" | null;
balances: { currency: string; amount: string }[];
checkedAt: string | null;
errorCode: string | null;
};
export type ProviderBalanceState = {
balances: ProviderBalance[];
failed: boolean;
loading: boolean;
refreshingKeys: string[];
refreshBalance: (source: "local" | "detected", providerId: string) => Promise<void>;
};
function keepLastBalance(previous: ProviderBalance | undefined, next: ProviderBalance): ProviderBalance {
if (next.errorCode && previous?.balances.length) {
return { ...next, balances: previous.balances, balanceKind: previous.balanceKind, checkedAt: previous.checkedAt };
}
if (!next.errorCode && previous?.checkedAt && next.checkedAt && previous.checkedAt > next.checkedAt) return previous;
return next;
}
const REFRESH_INTERVAL = 5 * 60 * 1000;
// Lives in App, so navigating away from Providers does not stop refreshing.
export function useProviderBalances(configDir: string, revision: string, ready: boolean) {
const [snapshot, setSnapshot] = useState({ configDir, revision, balances: [] as ProviderBalance[], failed: false, loading: true });
const scope = JSON.stringify([configDir, revision]);
const scopeRef = useRef(scope);
scopeRef.current = scope;
const manualInFlight = useRef(new Set<string>());
const manualVersions = useRef(new Map<string, number>());
const [manualBusy, setManualBusy] = useState<Record<string, boolean>>({});
const refreshBalance = useCallback(async (source: "local" | "detected", providerId: string) => {
if (!ready) return;
const token = JSON.stringify([scope, source, providerId]);
if (manualInFlight.current.has(token)) return;
manualInFlight.current.add(token);
manualVersions.current.set(token, (manualVersions.current.get(token) ?? 0) + 1);
setManualBusy(previous => ({ ...previous, [token]: true }));
try {
const result = await invoke<ProviderBalance>("refresh_provider_balance", { configDir, source, providerId });
if (scopeRef.current !== scope) return;
setSnapshot(previous => {
const matches = (item: ProviderBalance) => item.source === source && item.providerId === providerId;
const updated = keepLastBalance(previous.balances.find(matches), result);
return { ...previous, failed: false, balances: [...previous.balances.filter(item => !matches(item)), updated] };
});
} catch {
if (scopeRef.current === scope) setSnapshot(previous => ({ ...previous, balances: previous.balances.some(item => item.source === source && item.providerId === providerId)
? previous.balances.map(item => item.source === source && item.providerId === providerId ? { ...item, errorCode: "refresh_failed" } : item)
: [...previous.balances, { source, providerId, supported: true, vendor: null, balanceKind: null, balances: [], checkedAt: null, errorCode: "refresh_failed" }] }));
} finally {
manualVersions.current.set(token, (manualVersions.current.get(token) ?? 0) + 1);
manualInFlight.current.delete(token);
setManualBusy(previous => { const next = { ...previous }; delete next[token]; return next; });
}
}, [configDir, ready, scope]);
useEffect(() => {
if (!ready) return;
let disposed = false;
let inFlight = false;
let lastAttempt = 0;
let timer: number | undefined;
setSnapshot(previous => previous.configDir === configDir && previous.revision === revision
? { ...previous, loading: previous.balances.length === 0 }
: { configDir, revision, balances: [], failed: false, loading: true });
const refresh = async () => {
if (disposed || inFlight) return;
inFlight = true;
if (timer !== undefined) window.clearTimeout(timer);
lastAttempt = Date.now();
let nextDelay = REFRESH_INTERVAL;
const versionsAtStart = new Map(manualVersions.current);
const shouldPreserveManual = (item: ProviderBalance) => {
const token = JSON.stringify([scope, item.source, item.providerId]);
return manualInFlight.current.has(token) || (manualVersions.current.get(token) ?? 0) !== (versionsAtStart.get(token) ?? 0);
};
try {
const balances = await invoke<ProviderBalance[]>("get_provider_balances", { configDir });
// A manual query can warm the cache between automatic reads. Follow
// the data's timestamp rather than restarting a full five-minute wait.
const now = Date.now();
for (const item of balances.filter(item => item.supported)) {
const ttl = item.errorCode ? 60_000 : REFRESH_INTERVAL;
const checked = item.checkedAt ? Date.parse(item.checkedAt) : NaN;
const age = Number.isFinite(checked) ? Math.max(0, now - checked) : 0;
nextDelay = Math.min(nextDelay, Math.max(1_000, ttl - age + 1_000));
}
if (!disposed) setSnapshot(previous => ({ configDir, revision, balances: balances.map(next => {
const current = previous.balances.find(item => item.source === next.source && item.providerId === next.providerId);
return current && shouldPreserveManual(next) ? current : keepLastBalance(current, next);
}), failed: false, loading: false }));
} catch {
nextDelay = 60_000;
if (!disposed) setSnapshot(previous => ({ ...previous, loading: false, failed: previous.balances.length === 0, balances: previous.balances.map(item => item.supported && !shouldPreserveManual(item) ? { ...item, errorCode: "refresh_failed" } : item) }));
} finally {
inFlight = false;
lastAttempt = Date.now();
if (!disposed) timer = window.setTimeout(() => { void refresh(); }, nextDelay);
}
};
const onWake = () => { if (Date.now() - lastAttempt >= REFRESH_INTERVAL) void refresh(); };
void refresh();
window.addEventListener("focus", onWake);
document.addEventListener("visibilitychange", onWake);
return () => { disposed = true; if (timer !== undefined) window.clearTimeout(timer); window.removeEventListener("focus", onWake); document.removeEventListener("visibilitychange", onWake); };
}, [configDir, revision, ready, scope]);
const visible = snapshot.configDir === configDir && snapshot.revision === revision
? snapshot : { configDir, revision, balances: [] as ProviderBalance[], loading: true, failed: false };
const refreshingKeys = Object.keys(manualBusy).flatMap(token => {
const [requestScope, source, id] = JSON.parse(token) as string[];
return requestScope === scope ? [`${source}:${id}`] : [];
});
return { ...visible, refreshingKeys, refreshBalance };
}
export function supportsProviderBalance(baseUrl: string) {
try {
const url = new URL(baseUrl);
return url.protocol === "https:" && ["api.deepseek.com", "openrouter.ai", "api.siliconflow.cn", "api.moonshot.cn"].includes(url.hostname);
} catch { return false; }
}
+50
View File
@@ -0,0 +1,50 @@
import type { ProviderHeader } from "./providerHeaders";
export const PROVIDER_HEADER_PRESETS = [
{
id: "claude_code",
label: { zh: "Claude Code", en: "Claude Code" },
name: "User-Agent",
value: "claude-cli/2.1.161 (external, cli)",
},
{
id: "kilo_code",
label: { zh: "Kilo Code", en: "Kilo Code" },
name: "User-Agent",
value: "Kilo-Code/1.0",
},
] as const;
export type ProviderHeaderPresetId = typeof PROVIDER_HEADER_PRESETS[number]["id"];
/** Unknown IDs are a no-op. A preset changes one UA row and preserves drafts. */
export function applyProviderHeaderPreset(rows: readonly ProviderHeader[], id: string): ProviderHeader[] {
const preset = PROVIDER_HEADER_PRESETS.find((entry) => entry.id === id);
if (!preset) return [...rows];
let index = rows.findIndex((row) => row.name.trim().toLowerCase() === "user-agent");
if (index < 0) index = rows.findIndex((row) => !row.name.trim() && row.value === "");
const header: ProviderHeader = { name: preset.name, value: preset.value, source: "static" };
if (index < 0) return [...rows, header];
return rows.map((row, position) => position === index ? { ...row, ...header } : row);
}
/** Literal examples describe the named header's purpose; environment rows use their own hint. */
export function providerHeaderValuePlaceholder(name: string, lang: "zh" | "en"): string {
switch (name.trim().toLowerCase()) {
case "user-agent":
return lang === "zh" ? "例如 claude-cli/2.1.161 (external, cli)" : "e.g. claude-cli/2.1.161 (external, cli)";
case "http-referer":
return lang === "zh" ? "例如 https://your-app.example" : "e.g. https://your-app.example";
case "x-title":
case "x-openrouter-title":
return lang === "zh" ? "例如 你的应用名称" : "e.g. Your app name";
case "authorization":
return lang === "zh" ? "例如 Bearer <访问令牌>" : "e.g. Bearer <access token>";
case "x-api-key":
case "x-goog-api-key":
return lang === "zh" ? "例如 供应商提供的 API Key" : "e.g. API key from your provider";
default:
return lang === "zh" ? "填写该请求头的值" : "Enter this header's value";
}
}
+63
View File
@@ -0,0 +1,63 @@
export type ProviderHeaderSource = "static" | "env";
export type ProviderHeader = {
name: string;
value: string;
source: ProviderHeaderSource;
};
export type ProviderHeaderError = { name?: string; value?: string; source?: string };
type Language = "zh" | "en";
// RFC 9110 field-name tokens. Header values may contain horizontal tabs and
// UTF-8 text, matching reqwest's HeaderValue validation on the backend.
const HEADER_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
const INVALID_HEADER_VALUE = /[\u0000-\u0008\u000a-\u001f\u007f]/;
const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
export function createProviderHeader(source: ProviderHeaderSource = "static"): ProviderHeader {
return { name: "", value: "", source };
}
export function updateProviderHeader(rows: readonly ProviderHeader[], index: number, patch: Partial<ProviderHeader>): ProviderHeader[] {
return rows.map((row, position) => position === index ? { ...row, ...patch } : row);
}
export function removeProviderHeader(rows: readonly ProviderHeader[], index: number): ProviderHeader[] {
return rows.filter((_, position) => position !== index);
}
export function validateProviderHeaders(rows: readonly ProviderHeader[], lang: Language = "en") {
const counts = new Map<string, number>();
for (const row of rows) {
const name = row.name.trim().toLowerCase();
if (name) counts.set(name, (counts.get(name) ?? 0) + 1);
}
const errors: ProviderHeaderError[] = rows.map((row) => {
const error: ProviderHeaderError = {};
const name = row.name.trim();
if (!name) error.name = lang === "zh" ? "请填写 Header 名称" : "Enter a header name";
else if (!HEADER_NAME.test(name)) error.name = lang === "zh" ? "名称只能使用英文字母、数字和 HTTP 允许的符号" : "Use letters, numbers and valid HTTP header symbols";
else if ((counts.get(name.toLowerCase()) ?? 0) > 1) error.name = lang === "zh" ? "此名称重复(不区分大小写),请删除或重命名" : "Duplicate header name (case insensitive). Remove or rename it";
if (row.source === "env") {
if (!ENV_NAME.test(row.value)) error.value = lang === "zh" ? "请填写环境变量名,如 PROVIDER_PROJECT;仅允许字母、数字和下划线,且不能以数字开头" : "Enter an environment variable name, e.g. PROVIDER_PROJECT, using letters, numbers and underscores, without a leading digit";
} else if (row.source === "static") {
if (INVALID_HEADER_VALUE.test(row.value)) error.value = lang === "zh" ? "Header 值不能包含换行或控制字符" : "Header values cannot contain line breaks or control characters";
} else {
error.source = lang === "zh" ? "请选择固定值或环境变量" : "Choose a literal value or environment variable";
}
return error;
});
return { errors, valid: errors.every((error) => !error.name && !error.value && !error.source) };
}
/** Normalize only names; changing a value's whitespace can change its meaning. */
export function normalizeProviderHeaders(rows: readonly ProviderHeader[]): ProviderHeader[] {
if (!validateProviderHeaders(rows).valid) throw new Error("Invalid provider headers");
return rows.map((row) => ({ ...row, name: row.name.trim() }));
}
export function findProviderHeader(rows: readonly ProviderHeader[], name: string): ProviderHeader | undefined {
const target = name.trim().toLowerCase();
return rows.find((row) => row.name.trim().toLowerCase() === target);
}
+123
View File
@@ -0,0 +1,123 @@
import type { ProviderHeader } from "./providerHeaders";
export type ProviderHeadersControlState = {
busy: boolean;
reading: boolean;
valid: boolean;
error: "read" | "write" | null;
};
type Options = {
read: (configText: string) => Promise<ProviderHeader[]>;
update: (configText: string, headers: ProviderHeader[]) => Promise<string>;
getConfigText: () => string;
isValid: (rows: readonly ProviderHeader[]) => boolean;
normalize: (rows: readonly ProviderHeader[]) => ProviderHeader[];
onRowsChange: (rows: ProviderHeader[]) => void;
onConfigChange: (configText: string) => void;
onStateChange: (state: ProviderHeadersControlState) => void;
};
/** Keep local drafts and asynchronous TOML patches within the current form. */
export function createProviderHeadersControl(options: Options) {
let disposed = false;
let request = 0;
let revision = 0;
let source: string | null = null;
let rows: ProviderHeader[] = [];
let dirty = false;
let published: { text: string; revision: number } | null = null;
const emit = (state: ProviderHeadersControlState) => {
if (!disposed) options.onStateChange(state);
};
const current = (id: number, text: string) => !disposed && request === id && options.getConfigText() === text;
const idle = (valid: boolean) => emit({ busy: false, reading: false, valid, error: null });
async function read(text: string) {
const id = ++request;
emit({ busy: true, reading: true, valid: false, error: null });
try {
const result = await options.read(text);
if (!current(id, text)) return;
rows = result.map((row) => ({ ...row }));
options.onRowsChange(rows);
idle(options.isValid(rows));
} catch {
// IPC errors can contain configuration snippets. Only expose the failed
// operation, never the raw exception or a resolved environment value.
if (current(id, text)) emit({ busy: false, reading: false, valid: false, error: "read" });
}
}
async function write(text: string) {
const id = ++request;
const editedRevision = revision;
const headers = options.normalize(rows);
emit({ busy: true, reading: false, valid: true, error: null });
try {
const result = await options.update(text, headers);
if (!current(id, text)) return;
dirty = false;
if (result !== text) {
published = { text: result, revision: editedRevision };
options.onConfigChange(result);
}
idle(true);
} catch {
if (current(id, text)) emit({ busy: false, reading: false, valid: false, error: "write" });
}
}
async function load(configText: string) {
if (disposed || source === configText) return;
source = configText;
++request;
const echo = published;
published = null;
if (echo?.text === configText && echo.revision === revision && !dirty) {
idle(options.isValid(rows));
return;
}
if (dirty) {
// Reapply only edited header fields to the latest source, preserving an
// unrelated model, endpoint or TOML change. Invalid rows stay editable.
if (options.isValid(rows)) await write(configText);
else idle(false);
return;
}
if (!configText.trim()) {
emit({ busy: false, reading: true, valid: false, error: null });
return;
}
await read(configText);
}
async function changeRows(next: readonly ProviderHeader[]) {
if (disposed) return;
++request;
++revision;
rows = next.map((row) => ({ ...row }));
dirty = true;
options.onRowsChange(rows);
if (!options.isValid(rows)) {
idle(false);
return;
}
await write(options.getConfigText());
}
async function retry() {
if (disposed) return;
const text = options.getConfigText();
if (dirty && options.isValid(rows)) await write(text);
else if (!dirty) await read(text);
}
return {
load,
changeRows,
retry,
dispose() { disposed = true; ++request; },
};
}
+17
View File
@@ -0,0 +1,17 @@
export type UpstreamApi = "responses" | "chat_completions" | "anthropic_messages" | "gemini";
export function providerUpstreamApi(provider: { upstreamApi?: string | null; wireApi?: string }): string {
const configured = provider.upstreamApi?.trim().toLowerCase();
if (configured === "chat_completions" || configured === "openai_chat") return "chat_completions";
if (configured === "anthropic_messages" || configured === "anthropic") return "anthropic_messages";
if (configured === "gemini" || configured === "gemini_native") return "gemini";
if (configured === "responses") return "responses";
if (configured) return configured;
const legacy = provider.wireApi?.trim();
if (legacy === "chat" || legacy === "chat_completions") return "chat_completions";
return !legacy || legacy === "official" ? "responses" : legacy;
}
export function providerRequiresConversion(provider: { upstreamApi?: string | null; wireApi?: string }): boolean {
return providerUpstreamApi(provider) !== "responses";
}
+54
View File
@@ -0,0 +1,54 @@
export type LoadingScope = "general" | "sessionSync";
/** Session maintenance still blocks other UI actions; only activation is exempt. */
export function providerActivationIsBusy(loadingScopes: Iterable<LoadingScope>, actions: Iterable<string>): boolean {
for (const scope of loadingScopes) if (scope !== "sessionSync") return true;
for (const action of actions) if (action !== "syncSessions") return true;
return false;
}
export type SessionStatusContext = {
configDir: string;
targetProvider: string;
providerRevision: number;
};
export function sessionStatusContextKey(context: SessionStatusContext): string {
return JSON.stringify([context.configDir, context.targetProvider, context.providerRevision]);
}
export function createSessionStatusTracker() {
let sequence = 0;
return {
invalidate() { sequence += 1; },
begin(context: SessionStatusContext) {
return Object.freeze({ sequence: ++sequence, context: Object.freeze({ ...context }) });
},
isCurrent(request: { sequence: number; context: SessionStatusContext }, current: SessionStatusContext | null) {
return Boolean(current && request.sequence === sequence
&& request.context.configDir === current.configDir
&& request.context.targetProvider === current.targetProvider
&& request.context.providerRevision === current.providerRevision);
},
};
}
export async function readCurrentSessionStatus<T extends { targetProvider: string }>(
tracker: ReturnType<typeof createSessionStatusTracker>,
getContext: () => SessionStatusContext | null,
read: (context: Readonly<SessionStatusContext>) => Promise<T>,
accept: (status: T) => void,
): Promise<T | null> {
const context = getContext();
if (!context) return null;
const request = tracker.begin(context);
try {
const status = await read(request.context);
if (!tracker.isCurrent(request, getContext()) || status.targetProvider !== request.context.targetProvider) return null;
accept(status);
return status;
} catch (error) {
if (!tracker.isCurrent(request, getContext())) return null;
throw error;
}
}
+11
View File
@@ -420,3 +420,14 @@
@keyframes cx-app-dialog-spin {
to { transform: rotate(360deg); }
}
/* Actionable notices allow time to read and click, using the existing toast. */
.cx-app-toast--actionable { pointer-events: auto; animation: cx-app-toast-enter 180ms ease-out both, cx-app-toast-exit 180ms ease-in 15s forwards; }
.cx-app-toast--actionable:hover, .cx-app-toast--actionable:focus-within { animation-play-state: paused; }
.cx-app-toast-action, .cx-app-toast-dismiss { flex-shrink: 0; border: 0; padding: 4px; background: transparent; color: inherit; cursor: pointer; }
.cx-app-toast-action { font: inherit; font-size: 12px; font-weight: 600; text-decoration: underline; text-underline-offset: 3px; }
.cx-app-toast-dismiss { display: grid; place-items: center; opacity: .65; }
.cx-app-toast-action:disabled { cursor: wait; opacity: .5; }
.cx-app-toast-action:focus-visible, .cx-app-toast-dismiss:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; border-radius: 3px; }
.cx-app-toast--persistent { pointer-events: auto; animation: cx-app-toast-enter 180ms ease-out both; }
@@ -0,0 +1,30 @@
/* Reuse the settings page row, icon, typography and theme tokens. */
.cx-page-setting-row.cx-codex-language {
grid-template-columns: 40px minmax(0, 1fr) auto;
}
.cx-codex-language .cx-page-setting-copy p {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.cx-page-setting-action.cx-codex-language-action {
grid-column: auto;
justify-self: end;
display: grid;
justify-items: end;
gap: 5px;
}
.cx-codex-language-switch {
display: flex;
align-items: center;
gap: 10px;
color: var(--cx-page-muted);
font-size: 12px;
white-space: nowrap;
}
.cx-codex-language-switch .ui-toggle {
--ui-accent: var(--cx-page-blue);
}
.cx-codex-language-enabled { color: var(--cx-page-blue); }
.cx-codex-language-loading { width: 40px; height: 23px; display: grid; place-items: center; }
.cx-codex-language .cx-page-setting-copy .cx-codex-language-error { color: var(--ui-danger); }
@@ -125,3 +125,10 @@
@keyframes cx-config-health-enter { from { opacity: 0; transform: translateY(-5px); } to { opacity: 1; transform: translateY(0); } }
@keyframes cx-config-health-spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) { .cx-config-health-toast, .cx-config-health-spinner { animation: none; } }
.cx-config-health-location { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; }
.cx-config-health-location code,
.cx-config-health-key code { color: var(--cx-health-text); font-size: 11px; white-space: pre-wrap; overflow-wrap: anywhere; }
.cx-config-health-location span { flex-shrink: 0; }
.cx-config-health-issues p.cx-config-health-suggestion,
.cx-config-health-toast-content p.cx-config-health-suggestion { color: var(--cx-health-text); }
@@ -0,0 +1,60 @@
.cx-provider-balance {
--cx-balance-value: #16845a;
min-width: 0;
width: 100%;
max-width: 250px;
justify-self: center;
display: grid;
gap: 3px;
padding: 0 12px 0 14px;
border-left: 1px solid var(--cx-provider-border);
}
:root[data-theme="dark"] .cx-provider-balance { --cx-balance-value: var(--cx-dark-green); }
.cx-provider-balance-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
min-height: 18px;
color: var(--cx-provider-muted);
font-size: 11px;
line-height: 1.3;
}
.cx-provider-balance-refresh {
display: grid;
place-items: center;
flex: 0 0 22px;
width: 22px;
height: 22px;
margin: 0;
padding: 0;
border: 0;
border-radius: 5px;
color: var(--cx-provider-muted);
background: transparent;
cursor: pointer;
opacity: .75;
transition: opacity 140ms ease, background 140ms ease;
}
.cx-provider-balance-refresh:hover:not(:disabled) { opacity: 1; background: color-mix(in srgb, currentColor 10%, transparent); }
.cx-provider-balance-refresh:focus-visible { outline: 2px solid var(--cx-provider-blue); outline-offset: 2px; opacity: 1; }
.cx-provider-balance-refresh:disabled { cursor: default; opacity: .45; }
.cx-provider-balance-spin { animation: cx-provider-balance-spin 900ms linear infinite; }
.cx-provider-balance-reading { display: flex; align-items: center; gap: 8px; min-width: 0; }
.cx-provider-balance-amounts { display: flex; min-width: 0; gap: 14px; align-items: baseline; }
.cx-provider-balance-amounts--multiple { flex-wrap: wrap; gap: 3px 12px; }
.cx-provider-balance-value { display: flex; align-items: baseline; gap: 6px; min-width: 0; max-width: 100%; }
.cx-provider-balance-value strong { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--cx-balance-value); font-size: 21px; font-weight: 650; line-height: 1.25; letter-spacing: -.35px; font-variant-numeric: tabular-nums; }
.cx-provider-balance-value > span { flex-shrink: 0; color: var(--cx-provider-muted); font-size: 10px; font-weight: 500; }
.cx-provider-balance-amounts--multiple .cx-provider-balance-value strong { font-size: 17px; }
.cx-provider-balance-value--empty strong { color: var(--ui-danger); }
.cx-provider-balance--stale .cx-provider-balance-value strong { color: var(--cx-provider-text); }
.cx-provider-balance-footer { color: var(--cx-provider-muted); font-size: 10px; line-height: 1.4; font-variant-numeric: tabular-nums; }
.cx-provider-balance-footer--error { color: var(--ui-warning); }
.cx-provider-balance-unavailable { min-height: 26px; display: flex; align-items: center; gap: 6px; color: var(--cx-provider-muted); font-size: 12px; }
.cx-provider-balance-unavailable > svg { flex-shrink: 0; color: var(--ui-warning); }
.cx-provider-balance-placeholder { display: flex; align-items: center; height: 26px; }
.cx-provider-balance-placeholder > span { height: 18px; width: 88px; border-radius: 4px; background: color-mix(in srgb, var(--cx-provider-muted) 14%, transparent); }
@keyframes cx-provider-balance-spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) { .cx-provider-balance-spin { animation: none; } }
@media (max-width: 760px) { .cx-provider-balance { grid-column: 3; justify-self: start; max-width: 250px; padding: 0; border-left: 0; } }
@@ -0,0 +1,39 @@
.cx-provider-headers-control { grid-column: 1 / -1; min-width: 0; }
.cx-provider-headers-feedback { display: flex; align-items: center; gap: 10px; margin-top: 8px; }
.cx-provider-headers-feedback > p { margin: 0; }
.cx-provider-headers { grid-column: 1 / -1; min-width: 0; padding: 15px; border: 1px solid var(--cx-provider-border-soft); border-radius: 10px; }
.cx-provider-headers-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; margin-bottom: 12px; }
.cx-provider-headers-heading > div { min-width: 0; }
.cx-provider-headers-heading strong { display: flex; align-items: center; gap: 8px; color: var(--cx-provider-text); font-size: 13px; }
.cx-provider-headers-heading strong > span { color: var(--cx-provider-muted); font-size: 10px; font-weight: 500; }
.cx-provider-headers-heading p, .cx-provider-headers-hint, .cx-provider-headers-empty { margin: 5px 0 0; color: var(--cx-provider-muted); font-size: 11px; line-height: 1.6; }
.cx-provider-headers-actions { display: flex; flex-shrink: 0; flex-wrap: wrap; align-items: center; gap: 8px; }
.cx-provider-headers-presets { width: 180px; max-width: 100%; min-height: 32px; padding: 0 9px; border: 1px solid var(--cx-provider-border); border-radius: 6px; background: var(--ui-surface); color: var(--cx-provider-text); font-size: 11px; }
.cx-provider-headers-presets:focus-visible { outline: 2px solid var(--cx-provider-blue); outline-offset: 2px; }
.cx-provider-headers-presets:disabled { opacity: .6; cursor: not-allowed; }
.cx-provider-headers .cx-provider-headers-preset-hint { margin: 0 0 12px; }
.cx-provider-headers-rows { display: grid; gap: 10px; }
.cx-provider-header-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(130px, .8fr) minmax(0, 1.5fr) 32px; gap: 9px; align-items: start; }
.cx-provider-header-field { display: grid; min-width: 0; gap: 5px; }
.cx-provider-header-field > span { color: var(--cx-provider-muted); font-size: 10px; font-weight: 600; line-height: 1.5; }
.cx-provider-header-field > input, .cx-provider-header-field > select { width: 100%; min-width: 0; height: 38px; padding: 0 9px; border: 1px solid var(--cx-provider-border); border-radius: 6px; outline: none; background: var(--ui-surface); color: var(--cx-provider-text); font-size: 12px; }
.cx-provider-header-field > input::placeholder { color: var(--cx-provider-muted); opacity: .8; font-size: 11px; }
.cx-provider-header-field > input:focus, .cx-provider-header-field > select:focus { border-color: var(--cx-provider-blue); box-shadow: 0 0 0 2px color-mix(in srgb, var(--cx-provider-blue) 12%, transparent); }
.cx-provider-header-field > [aria-invalid="true"] { border-color: color-mix(in srgb, var(--ui-danger) 65%, var(--cx-provider-border)); }
.cx-provider-header-field > small, .cx-provider-headers-error { color: var(--ui-danger); font-size: 10px; line-height: 1.5; overflow-wrap: anywhere; }
.cx-provider-header-field > :disabled { opacity: .6; cursor: not-allowed; }
.cx-provider-header-remove { margin-top: 22px; }
.cx-provider-headers-hint, .cx-provider-headers-error { margin: 10px 0 0; }
@media (max-width: 900px) {
.cx-provider-header-row { grid-template-columns: minmax(0, 1fr) minmax(130px, .8fr) 32px; }
.cx-provider-header-field:nth-child(3) { grid-column: 1 / 3; grid-row: 2; }
.cx-provider-header-remove { grid-column: 3; grid-row: 1; }
}
@media (max-width: 640px) {
.cx-provider-headers { padding: 12px; }
.cx-provider-headers-heading { flex-wrap: wrap; }
.cx-provider-headers-actions { width: 100%; }
.cx-provider-header-row { grid-template-columns: minmax(0, 1fr) 32px; }
.cx-provider-header-field, .cx-provider-header-field:nth-child(3) { grid-column: 1; grid-row: auto; }
.cx-provider-header-remove { grid-column: 2; }
}
+16 -6
View File
@@ -222,9 +222,9 @@
box-shadow: 0 0 0 1px rgba(147, 197, 253, 0.5), 0 3px 10px rgba(37, 99, 235, 0.08);
}
/* Give official account emails their own centered column. Current-state
badges can change the actions without moving the email in any row. */
.cx-providers-row--official {
/* Keep account details and provider balances in the same centered column. */
.cx-providers-row--official,
.cx-providers-row--balance {
grid-template-columns: 18px 42px minmax(0, 1fr) minmax(200px, 300px) minmax(310px, 1fr);
}
@@ -242,7 +242,8 @@
.cx-providers-row-model>b { font-weight: 550; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--cx-provider-text); }
.cx-providers-row-model>code { margin: 0; flex: 0 1 auto; }
.cx-providers-row--official > .cx-providers-login-badge {
.cx-providers-row--official > .cx-providers-login-badge,
.cx-providers-row--balance > .cx-providers-login-badge {
width: 100%;
max-width: 100%;
justify-self: center;
@@ -928,11 +929,13 @@
@media (max-width: 760px) {
.cx-providers-row,
.cx-providers-row--official {
.cx-providers-row--official,
.cx-providers-row--balance {
grid-template-columns: 18px 40px minmax(0, 1fr);
}
.cx-providers-row--official > .cx-providers-login-badge {
.cx-providers-row--official > .cx-providers-login-badge,
.cx-providers-row--balance > .cx-providers-login-badge {
grid-column: 3;
width: min(300px, 100%);
justify-self: start;
@@ -974,3 +977,10 @@
animation: none;
}
}
.cx-providers-protocol-hint {
margin: 0;
color: var(--cx-provider-muted);
font-size: 12px;
line-height: 1.6;
}
+1
View File
@@ -36,6 +36,7 @@ export type SavedProvider = {
apiKey?: string;
tomlConfig?: string;
wireApi: string;
upstreamApi?: string | null;
requiresOpenaiAuth: boolean;
modelMappings?: ProviderModelMapping[];
};
+19
View File
@@ -0,0 +1,19 @@
import type { AppUpdateInfo, ReleaseInfo } from "./types";
/** Release metadata can identify a version, but does not authorize installation.
* An installed edition keeps its native check/retry controls after a failed
* signed-channel check; only editions without a native updater use download-only.
*/
export function releaseInfoFromFallback(update: AppUpdateInfo, nativeCheckAttempted: boolean): ReleaseInfo {
return {
status: nativeCheckAttempted && !update.hasUpdate ? "error" : "ok",
latestVersion: update.latestVersion,
htmlUrl: update.htmlUrl,
hasUpdate: update.hasUpdate,
updateMethod: nativeCheckAttempted ? "native" : update.hasUpdate ? "download" : undefined,
};
}
export function releaseInfoFromCheckFailure(nativeCheckAttempted: boolean): ReleaseInfo {
return { status: "error", updateMethod: nativeCheckAttempted ? "native" : undefined };
}
+5 -2
View File
@@ -155,14 +155,17 @@ export function useConfigHealth(options: {
dismiss(); accept(result.report);
if (result.report.status === "healthy") registry.current?.clear(result.report);
const zh = runtime.current.lang === "zh";
const remaining = result.report.issues[0];
runtime.current.onHint(result.report.status === "healthy"
? (zh ? "配置已检查并修复,请重新打开原来的 Codex 对话。" : "Configuration checked and repaired. Reopen the Codex conversation.")
: (zh ? "可自动处理的部分已修复,其余问题可在通用设置中查看。" : "Supported repairs are complete. Review the remaining issues in General settings."));
: remaining
? `${zh ? "已完成安全修复;仍需处理:" : "Supported repairs are complete; review: "}${remaining.path || `${result.report.codexDir}/config.toml`}${remaining.line ? `:${remaining.line}:${remaining.column || 1}` : ""} · ${remaining.key || remaining.title}。${remaining.suggestion || remaining.description}`
: (zh ? "请在通用设置中查看检查结果。" : "Review the check result in General settings."));
runtime.current.onRepaired();
} catch (cause) {
if (current()) {
dismiss(); setError(String(cause));
runtime.current.onHint(runtime.current.lang === "zh" ? "配置未修复,请到「设置 → 通用设置」查看原因或重新检查。" : "Configuration was not repaired. Review the issue or check again in Settings → General.");
runtime.current.onHint(`${runtime.current.lang === "zh" ? "配置未修复:" : "Configuration was not repaired: "}${String(cause)}`);
}
} finally { if (current()) { busyRef.current = false; setRepairing(false); } }
}, [accept, dismiss]);
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
import { AppUpdaterController, isAppUpdateBusy, UPDATER_SLOW_NOTICE_MS } from "../src/appUpdaterController.ts";
import { AppUpdaterController, appUpdaterCheckFailureMessage, classifyAppUpdaterCheckError, isAppUpdateBusy, UPDATER_SLOW_NOTICE_MS } from "../src/appUpdaterController.ts";
function deferred() {
let resolve, reject;
@@ -198,3 +198,130 @@ test("a pending forced check cannot install its stale update resource", async ()
await check;
assert.equal(f.counts.closes, 1);
});
const checkFailures = [
["timeout", new Error("error sending request: operation timed out at https://private.fixture.test/update?token=private-secret")],
["network", { code: "NetworkError", message: "connection refused; Authorization: Bearer private-secret at https://private.fixture.test" }],
["platform", "the platform `windows-x86_64` was not found in the response `platforms` object"],
["platform", new Error("Unsupported application architecture, expected x86 or aarch64")],
["invalid-release", "Could not fetch a valid release JSON from the remote"],
["invalid-release", { code: "Serialization", message: "missing field `signature` at line 1 column 1: private-secret" }],
["public-key", "Could not decode public key or signature: private-secret"],
["unknown", { message: "Something unexpected happened: private-secret", url: "https://private.fixture.test", authorization: "Bearer private-secret" }],
];
test("check failures are classified into fixed safe explanations in both languages", () => {
for (const [kind, cause] of checkFailures) {
assert.equal(classifyAppUpdaterCheckError(cause), kind);
for (const lang of ["zh", "en"]) {
const message = appUpdaterCheckFailureMessage(kind, lang);
assert.ok(message.length > 20);
assert.ok(!message.includes("private-secret"));
assert.ok(!message.includes("https://"));
assert.ok(!message.includes("Authorization"));
}
}
for (const cause of [null, undefined, 123, false, {}, { message: {} }]) assert.equal(classifyAppUpdaterCheckError(cause), "unknown");
assert.equal(classifyAppUpdaterCheckError("Unrecognized error https://fixture.test/timeout?publickey=secret"), "unknown", "URL text alone must not invent the reason");
});
test("SDK check rejection retains a safe cause without any raw endpoint or credentials", async () => {
for (const [kind, cause] of checkFailures) {
const f = fixture();
const rejected = deferred();
f.setCheckOperation(rejected);
const job = f.controller.check();
rejected.reject(cause);
assert.equal(await job, "error");
const state = f.controller.getSnapshot();
assert.equal(state.phase, "error");
assert.equal(state.failure, "check");
assert.equal(state.checkFailure, kind);
assert.equal(state.errorMessage, appUpdaterCheckFailureMessage(kind));
const visible = JSON.stringify(state);
for (const secret of ["private-secret", "private.fixture.test", "Authorization", "Bearer"]) assert.ok(!visible.includes(secret));
assert.equal(f.counts.installs, 0);
}
});
test("failed forced checks release their prior RID and clear stale release details", async () => {
const f = fixture();
f.setUpdate({ rid: 21, currentVersion: "0.3.21", version: "0.3.24", body: "Old release notes", date: "2026-10-01", close: async () => { f.counts.closes++; } });
await f.controller.check();
assert.equal(f.controller.getSnapshot().latestVersion, "0.3.24");
const failed = deferred();
f.setCheckOperation(failed);
const job = f.controller.check({ force: true });
assert.equal(f.controller.getSnapshot().latestVersion, null);
assert.equal(f.controller.getSnapshot().notes, null);
failed.reject(new Error("NetworkError: connection refused"));
await job;
assert.equal(f.counts.closes, 1);
assert.equal(f.controller.getSnapshot().failure, "check");
assert.equal(f.controller.getSnapshot().checkFailure, "network");
for (const field of ["latestVersion", "notes", "publishedAt"]) assert.equal(f.controller.getSnapshot()[field], null);
assert.equal(await f.controller.downloadAndInstall(), "error");
assert.equal(f.counts.installs, 0, "failed SDK metadata cannot authorize an installer");
});
test("retry checks again and installation requires a newly obtained legal SDK RID", async () => {
const f = fixture();
const failed = deferred();
f.setCheckOperation(failed);
const first = f.controller.check();
failed.reject(new Error("operation timed out"));
await first;
const pending = deferred();
f.setCheckOperation(pending);
const retry = f.controller.retry();
assert.equal(f.counts.checks, 2);
assert.equal(f.controller.getSnapshot().phase, "checking");
assert.equal(await f.controller.downloadAndInstall(), "checking");
assert.equal(f.counts.installs, 0);
pending.resolve({ rid: 24, currentVersion: "0.3.21", version: "0.3.24", body: "New release", close: async () => { f.counts.closes++; } });
assert.equal(await retry, "available");
assert.equal(f.controller.getSnapshot().errorMessage, null);
assert.equal(f.controller.getSnapshot().checkFailure, null);
assert.equal(f.counts.installs, 0, "retrying the check must not automatically install");
const installing = f.controller.downloadAndInstall();
assert.equal(f.operation.value.rid, 24);
assert.equal(f.counts.installs, 1);
f.operation.resolve({ restartRequired: true });
assert.equal(await installing, "ready");
});
test("invalid SDK resource IDs are closed and can never reach installation", async () => {
for (const rid of [-1, NaN, Infinity, 1.5, 0x1_0000_0000, "24", undefined]) {
const f = fixture();
f.setUpdate({ rid, currentVersion: "0.3.21", version: "0.3.24", close: async () => { f.counts.closes++; } });
assert.equal(await f.controller.check(), "error", String(rid));
assert.equal(f.controller.getSnapshot().checkFailure, "invalid-release");
assert.equal(f.counts.closes, 1);
assert.equal(await f.controller.downloadAndInstall(), "error");
assert.equal(f.counts.installs, 0);
}
const f = fixture();
f.setUpdate({ rid: 0, currentVersion: "0.3.21", version: "0.3.24", close: async () => { f.counts.closes++; } });
assert.equal(await f.controller.check(), "available", "Tauri resource IDs may start at zero");
});
test("automatic transport recovery starts a fresh byte count and installs only once", async () => {
const f = fixture();
await f.controller.check();
const job = f.controller.downloadAndInstall();
f.operation.onEvent({ event: "Started", data: { contentLength: 100 } });
f.operation.onEvent({ event: "Progress", data: { chunkLength: 45 } });
assert.equal(f.controller.getSnapshot().downloadedBytes, 45);
f.operation.onEvent({ event: "Started", data: { contentLength: 100 } });
assert.equal(f.controller.getSnapshot().downloadedBytes, 0);
f.operation.onEvent({ event: "Progress", data: { chunkLength: 100 } });
f.operation.onEvent({ event: "Verifying" });
f.operation.onEvent({ event: "Preparing" });
f.operation.onEvent({ event: "HandedOff" });
f.operation.resolve({ restartRequired: false });
assert.equal(await job, "handed-off");
assert.equal(f.counts.installs, 1);
assert.equal(f.counts.checks, 1);
});
@@ -0,0 +1,170 @@
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { closeSync, existsSync, openSync, readFileSync, readSync } from "node:fs";
import { createRequire } from "node:module";
import test from "node:test";
import vm from "node:vm";
// Optional local compatibility evidence. No installed application is launched,
// and no bundle is executed or copied into this repository. Only the narrow
// SDK registration / getter / compiled memo fragments are extracted at run time.
const archive = "/Applications/ChatGPT.app/Contents/Resources/app.asar";
const available = process.platform === "darwin" && existsSync(archive);
const runtime = readFileSync(new URL("../src-tauri/src/codex_locale_runtime.js", import.meta.url), "utf8");
const owner = "c".repeat(64);
const marker = "__CODEXX_LOCALE_RUNTIME_V1__";
function readInstalledEvidence() {
const fd = openSync(archive, "r");
try {
const prefix = Buffer.alloc(16);
readSync(fd, prefix, 0, prefix.length, 0);
assert.equal(prefix.readUInt32LE(0), 4);
const headerSize = prefix.readUInt32LE(12);
assert.ok(headerSize > 0 && headerSize < 32 * 1024 * 1024);
const header = Buffer.alloc(headerSize);
assert.equal(readSync(fd, header, 0, header.length, 16), header.length);
const assets = JSON.parse(header.toString()).files.webview.files.assets.files;
const base = 8 + prefix.readUInt32LE(4);
function asset(pattern) {
const matches = Object.entries(assets).filter(([name]) => pattern.test(name));
assert.equal(matches.length, 1, `installed asset shape changed: ${pattern}`);
const [name, entry] = matches[0];
assert.ok(!entry.unpacked && entry.size < 16 * 1024 * 1024);
const bytes = Buffer.alloc(entry.size);
assert.equal(readSync(fd, bytes, 0, bytes.length, base + Number(entry.offset)), bytes.length);
return { name, source: bytes.toString(), sha256: createHash("sha256").update(bytes).digest("hex") };
}
const shared = asset(/^app-shared-.*\.js$/);
// The language consumer's compiled memo is in app-initial, not app-shared.
const initial = asset(/^app-initial-.*\.js$/);
const plist = readFileSync("/Applications/ChatGPT.app/Contents/Info.plist", "utf8");
const plistValue = (key) => plist.match(new RegExp(`<key>${key}</key>\\s*<string>([^<]+)`))?.[1];
return { shared, initial, version: plistValue("CFBundleShortVersionString"), build: plistValue("CFBundleVersion") };
} finally { closeSync(fd); }
}
function extractedFragments(evidence) {
const require = createRequire(new URL("../package.json", import.meta.url));
const ts = require("typescript");
const shared = evidence.shared.source;
function declaration(marker) {
const index = shared.indexOf(marker);
assert.ok(index >= 0, `installed SDK fragment changed: ${marker}`);
// Parse a bounded window; execute only its first complete declaration.
const parsed = ts.createSourceFile("fragment.js", shared.slice(index, index + 4096), ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
assert.ok(ts.isFunctionDeclaration(parsed.statements[0]));
return parsed.statements[0].getText(parsed);
}
const registration = declaration("function p(e,t){if((0,s._isServerEnv)())return");
const useLayer = declaration("function Nyn(");
const readLayer = declaration("function Pyn(");
const memoIndex = shared.indexOf("_memoize(e,t){");
assert.ok(memoIndex >= 0);
const parsedMemo = ts.createSourceFile("memo.js", `class Extracted {${shared.slice(memoIndex, memoIndex + 2048)}`, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
const memoize = parsedMemo.statements[0].members[0].getText(parsedMemo);
const assignmentStart = shared.indexOf("this.getLayer=this._memoize(");
const assignmentEnd = shared.indexOf(",this.getParameterStore=", assignmentStart);
assert.ok(assignmentStart >= 0 && assignmentEnd > assignmentStart);
const assignment = shared.slice(assignmentStart, assignmentEnd);
const derivedStart = shared.lastIndexOf("constructor(", assignmentStart);
assert.ok(shared.slice(derivedStart, assignmentStart).includes("super("), "the real derived constructor calls super before assigning getLayer");
const registerCall = shared.indexOf("p(e,this)");
const baseStart = shared.lastIndexOf("constructor(", registerCall);
assert.ok(baseStart > 0 && registerCall > baseStart);
assert.equal(shared.slice(registerCall, registerCall + 10), "p(e,this)}", "registration is at the end of the real base constructor");
const getterStart = shared.indexOf("e._getStatsigGlobal=()=>");
const getterEnd = shared.indexOf(",e._getStatsigGlobalFlag", getterStart);
const globalsStart = shared.indexOf("var n=`__STATSIG__`,", getterEnd);
const globalsEnd = shared.indexOf("a[n]=o", globalsStart) + "a[n]=o".length;
assert.ok(getterStart >= 0 && getterEnd > getterStart && globalsStart > getterEnd && globalsEnd > globalsStart);
const globalInitialization = `${shared.slice(getterStart, getterEnd)};${shared.slice(globalsStart, globalsEnd)};`;
const consumerStart = evidence.initial.source.indexOf("function O9s(");
const expressionStart = evidence.initial.source.indexOf("t[0]===s?c=t[1]", consumerStart);
const expressionEnd = evidence.initial.source.indexOf(";let l=c", expressionStart);
assert.ok(consumerStart >= 0 && expressionStart > consumerStart && expressionEnd > expressionStart);
const consumerMemo = evidence.initial.source.slice(expressionStart, expressionEnd);
assert.ok(consumerMemo.includes("enable_i18n") && consumerMemo.length < 256);
return { registration, useLayer, readLayer, memoize, assignment, globalInitialization, consumerMemo };
}
function isolatedSdk(fragments, installEarly) {
const timers = new Map();
const sandbox = {
URL, location: { href: "app://-/index.html" }, document: { documentElement: { lang: "zh-CN" } },
performance: { getEntriesByType: () => [{ name: "app://-/assets/zh-CN-fixture.js" }] },
setInterval(callback) { timers.set(1, callback); return 1; }, clearInterval(id) { timers.delete(id); },
};
sandbox.window = sandbox; sandbox.top = sandbox;
const context = vm.createContext(sandbox);
const install = () => vm.runInContext(runtime.replace("__CODEXX_LANGUAGE_CONFIG__", JSON.stringify({ locale: "zh-CN", owner })), context, { timeout: 500 });
if (installEarly) install();
// These are independently supplied stubs, not live SDK stores, React, DOM,
// networking, or account data. Extracted code has no bundle/module loader.
vm.runInContext(`
globalThis.fakeLayer={get:(key,fallback)=>key==='enable_i18n'?false:key==='locale_source'?'IDE':fallback};
globalThis.originalCalls=0;
const sdkGlobals=(()=>{const e={_getInstance(){}};${fragments.globalInitialization}return e;})();
const s={_isServerEnv:()=>false},a={Log:{warn(){throw Error('unexpected duplicate fixture key')}}};
const n={_getStatsigGlobal:sdkGlobals._getStatsigGlobal,MemoPrefix:{_layer:'fixture-layer'}};
const o={createMemoKey:(...args)=>JSON.stringify(args)},f=1000;
${fragments.registration}
class Base { constructor(e){this._options={};this._memoCache={};p(e,this)} ${fragments.memoize} }
const originalMemoize=Base.prototype._memoize;
Base.prototype._memoize=function(...args){const raw=originalMemoize.apply(this,args);this.fixtureOriginalGetLayer=raw;return raw;};
class Derived extends Base { constructor(e){super(e);globalThis.registeredBeforeGetter=typeof this.getLayer!=='function';${fragments.assignment}} _getLayerImpl(){originalCalls++;return fakeLayer} }
const hookCache=Array(8).fill(Symbol.for('fixture.uninitialized'));
const consumerCache=Array(33).fill(Symbol.for('fixture.uninitialized'));
const iW={c:()=>hookCache};
function rW(){return {client:globalThis.client,getLayer:globalThis.client.getLayer}}
${fragments.readLayer}
${fragments.useLayer}
globalThis.readCompiledLanguage=()=>{const s=Nyn('72216192');let t=consumerCache,c;${fragments.consumerMemo};return c;};
globalThis.makeClient=key=>new Derived(key);
globalThis.client=makeClient('fixture-key');
`, context, { timeout: 500 });
return { sandbox, context, timers, install, read: () => vm.runInContext("readCompiledLanguage()", context, { timeout: 500 }) };
}
test("installed SDK registration and compiled first language memo see the early override synchronously", { skip: !available }, (t) => {
const evidence = readInstalledEvidence();
t.diagnostic(`Installed build ${evidence.version} (${evidence.build}); ${evidence.shared.name}; SHA256 ${evidence.shared.sha256}`);
const fragments = extractedFragments(evidence);
const f = isolatedSdk(fragments, true);
assert.equal(f.sandbox.registeredBeforeGetter, true);
assert.equal(f.read(), true, "the first compiled memo sees true without timer ticks or SDK events");
assert.equal(f.read(), true);
assert.equal(f.sandbox.originalCalls, 1, "the real SDK and React memo keep the initial layer cached");
assert.equal(f.sandbox.fakeLayer.get("enable_i18n", false), false);
assert.equal(f.sandbox.client.getLayer("72216192").get("locale_source", "wrong"), "IDE");
const registry = f.sandbox.__STATSIG__;
f.sandbox.__STATSIG__ = registry;
f.sandbox.second = vm.runInContext("makeClient('second-fixture-key')", f.context);
assert.equal(f.sandbox.second.getLayer("72216192").get("enable_i18n", false), true, "subsequent SDK registrations remain observed");
assert.equal(f.sandbox[marker].status().ready, true);
f.sandbox[marker].restore();
assert.equal(f.sandbox[marker], undefined);
assert.equal(f.timers.size, 0);
assert.equal(f.sandbox.__STATSIG__, registry);
assert.equal(registry.instances["fixture-key"], f.sandbox.client);
assert.equal(registry.instances["second-fixture-key"], f.sandbox.second);
for (const [object, key] of [[f.sandbox, "__STATSIG__"], [registry, "firstInstance"], [registry, "instances"], [registry.instances, "fixture-key"], [registry.instances, "second-fixture-key"], [f.sandbox.client, "getLayer"], [f.sandbox.second, "getLayer"]]) {
const descriptor = Object.getOwnPropertyDescriptor(object, key);
assert.ok(descriptor && Object.hasOwn(descriptor, "value"), `restore removes the owned accessor for ${key}`);
assert.equal(descriptor.writable, true);
assert.equal(descriptor.configurable, true);
}
assert.equal(f.sandbox.client.getLayer, f.sandbox.client.fixtureOriginalGetLayer);
assert.equal(f.sandbox.second.getLayer, f.sandbox.second.fixtureOriginalGetLayer);
assert.equal(f.sandbox.client.getLayer("72216192").get("enable_i18n", false), false);
assert.equal(f.sandbox.second.getLayer("72216192").get("enable_i18n", false), false);
});
test("installed compiled language memo demonstrates why a timer-only late hook cannot repair its first false value", { skip: !available }, () => {
const f = isolatedSdk(extractedFragments(readInstalledEvidence()), false);
assert.equal(f.read(), false);
f.install();
assert.equal(f.sandbox.client.getLayer("72216192").get("enable_i18n", false), true);
assert.equal(f.read(), false, "the unchanged React client/layer memo retains the pre-hook false value");
f.sandbox[marker].restore();
});
@@ -0,0 +1,322 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import vm from "node:vm";
const source = readFileSync(new URL("../src-tauri/src/codex_locale_runtime.js", import.meta.url), "utf8");
const marker = "__CODEXX_LOCALE_RUNTIME_V1__";
const layerName = "72216192";
const owner = "a".repeat(64);
const languageResource = "app://-/assets/zh-CN-fixture.js";
class FixtureLayer {
#values;
constructor(values = {}) { this.#values = { enable_i18n: false, locale_source: "fixture-original", ...values }; this.name = "fixture layer"; }
get(parameter, fallback) { return Object.hasOwn(this.#values, parameter) ? this.#values[parameter] : fallback; }
readPrivate() { return this.#values.locale_source; }
get privateValue() { return this.#values.locale_source; }
}
class FixtureClient {
#layers;
constructor(layer = new FixtureLayer()) {
this.#layers = { [layerName]: layer, other_layer: new FixtureLayer({ enable_i18n: false }) };
this.calls = [];
this.events = [];
this.gateCalls = [];
}
getLayer(name, ...options) { this.calls.push({ name, options, receiver: this }); return this.#layers[name]; }
checkGate(name) { this.gateCalls.push(name); return this.#layers.other_layer.get("enable_i18n", false); }
$emt(event) { this.events.push(event.name); this.onValuesUpdated?.(event); }
}
function fixture({ url = "app://-/index.html", language = "zh-CN", resources = [languageResource], client = new FixtureClient(), registry, iframe = false, observer = true, documentElement = true } = {}) {
const parsed = new URL(url);
// Location deliberately has no username/password fields: browsers expose
// those through new URL(location.href), not through the Location interface.
const location = { href: parsed.href, protocol: parsed.protocol, host: parsed.host, hostname: parsed.hostname, port: parsed.port, pathname: parsed.pathname, search: parsed.search, hash: parsed.hash, origin: parsed.origin };
const timers = new Map(), scheduled = [], observers = [];
let entries = resources.map((name) => ({ name, initiatorType: "script" }));
const sandbox = {
location, URL,
document: { documentElement: documentElement ? { lang: language } : null },
performance: { getEntriesByType(type) { assert.equal(type, "resource"); return entries; } },
setInterval(callback, interval) { assert.equal(interval, 100); const id = scheduled.length + 1; scheduled.push(callback); timers.set(id, callback); return id; },
clearInterval(id) { timers.delete(id); },
};
if (observer) sandbox.PerformanceObserver = class {
constructor(callback) { this.callback = callback; this.active = false; observers.push(this); }
observe(options) { assert.equal(options.type, "resource"); this.active = true; if (options.buffered) this.callback({ getEntries: () => entries }); }
disconnect() { this.active = false; }
};
sandbox.window = sandbox;
sandbox.top = iframe ? {} : sandbox;
sandbox.__STATSIG__ = registry ?? { firstInstance: client, instances: { fixture: client } };
const context = vm.createContext(sandbox);
return {
sandbox, client, timers, observers, scheduled,
install(options = { locale: "zh-CN", owner }) { return vm.runInContext(source.replace("__CODEXX_LANGUAGE_CONFIG__", JSON.stringify(options)), context, { timeout: 500 }); },
state() { return sandbox[marker]; },
tick() { for (const callback of [...timers.values()]) callback(); },
emitResources(names) { const delivered = names.map((name) => ({ name, initiatorType: "script" })); for (const current of observers) if (current.active) current.callback({ getEntries: () => delivered }); },
clearResources() { entries = []; },
};
}
test("only the i18n parameter of the named layer changes; other gates, fields and receivers remain original", () => {
const client = new FixtureClient();
const layer = client.getLayer(layerName);
const other = client.getLayer("other_layer");
client.calls.length = 0;
const checkGate = client.checkGate;
const f = fixture({ client });
assert.equal(f.install().ready, true);
assert.ok(client.calls.every((call) => call.name === layerName && call.receiver === client));
assert.deepEqual(client.gateCalls, [], "the runtime never evaluates unrelated feature gates");
assert.equal(client.checkGate, checkGate);
assert.equal(client.checkGate("unrelated-account-gate"), false);
assert.equal(client.getLayer("other_layer"), other);
const view = client.getLayer(layerName);
assert.equal(view.get("enable_i18n", false), true);
assert.equal(view.get("locale_source", "wrong"), "fixture-original");
assert.equal(view.get("unrelated-field", "original fallback"), "original fallback");
assert.equal(view.readPrivate(), "fixture-original");
assert.equal(view.privateValue, "fixture-original");
assert.equal(view.get, view.get, "the i18n getter has a stable reference for React dependencies");
assert.equal(view.readPrivate, view.readPrivate, "other bound methods have stable references");
const previousBoundMethod = view.readPrivate;
layer.readPrivate = function () { return `${this.privateValue}-updated`; };
assert.notEqual(view.readPrivate, previousBoundMethod, "a later SDK method replacement is observed");
assert.equal(view.readPrivate(), "fixture-original-updated");
assert.equal(layer.get("enable_i18n", false), false, "the actual SDK layer data is not mutated");
assert.equal(Object.getPrototypeOf(view), Object.getPrototypeOf(layer));
f.state().restore();
});
test("frozen layers with immutable own get methods do not violate Proxy invariants", () => {
const layer = new FixtureLayer();
Object.defineProperty(layer, "get", { value: layer.get, configurable: false, writable: false, enumerable: true });
Object.freeze(layer);
const f = fixture({ client: new FixtureClient(layer) });
assert.equal(f.install().ready, true);
const view = f.client.getLayer(layerName);
assert.equal(view.get("enable_i18n", false), true);
assert.equal(view.readPrivate(), "fixture-original");
assert.equal(view.privateValue, "fixture-original");
assert.equal("name" in view, true);
assert.deepEqual(Object.keys(view), Object.keys(layer));
f.state().restore();
assert.equal(view.get("enable_i18n", false), false, "held views stop overriding after restoration");
});
test("writable nonconfigurable methods and configurable accessors restore their exact descriptors", () => {
for (const accessor of [false, true]) {
const client = new FixtureClient();
const original = client.getLayer;
Object.defineProperty(client, "getLayer", accessor
? { configurable: true, enumerable: true, get() { return original; } }
: { configurable: false, enumerable: true, writable: true, value: original });
const descriptor = Object.getOwnPropertyDescriptor(client, "getLayer");
const f = fixture({ client });
assert.equal(f.install().ready, true);
f.state().restore();
assert.deepEqual(Object.getOwnPropertyDescriptor(client, "getLayer"), descriptor);
}
});
test("unpatchable client methods fail closed without reporting the compatibility layer ready", () => {
const client = new FixtureClient();
const original = client.getLayer;
Object.defineProperty(client, "getLayer", { configurable: false, writable: false, value: original });
const f = fixture({ client });
assert.equal(f.install().ready, false);
assert.equal(client.getLayer, original);
assert.deepEqual(client.events, []);
f.state().restore();
});
test("only the top-level official app origin and supported page paths are accepted", () => {
for (const url of ["https://chatgpt.com/", "http://127.0.0.1/index.html", "app://other/index.html", "app://-/browser.html", "app://user@-/index.html", "app://user:password@-/index.html", "app://-:123/index.html"]) {
const f = fixture({ url });
assert.equal(f.install().reason, "unsupported_origin", url);
assert.equal(f.state(), undefined);
assert.equal(f.timers.size, 0);
assert.deepEqual(f.client.events, []);
}
assert.equal(fixture({ iframe: true }).install().reason, "unsupported_origin");
for (const url of ["app://-/", "app://-/index.html?initialRoute=%2Fsettings#fixture"]) {
const f = fixture({ url });
assert.equal(f.install().installed, true);
f.state().restore();
}
});
test("unsupported locales and untrusted option shapes cause no hooks", () => {
for (const options of [null, {}, { locale: "fr-FR", owner }, { locale: "zh-CN", owner: "not-a-session-id" }, { locale: "zh-CN", owner: '";globalThis.fixtureInjected=true;//' }]) {
const f = fixture();
assert.equal(f.install(options).reason, "invalid_options");
assert.equal(f.state(), undefined);
assert.equal(f.sandbox.fixtureInjected, undefined);
assert.deepEqual(f.client.events, []);
}
});
test("a late SDK singleton notifies subscribers after the narrow hook becomes available", () => {
const f = fixture({ registry: {} });
assert.equal(f.install().ready, false);
const observed = [];
f.client.onValuesUpdated = () => observed.push(f.client.getLayer(layerName).get("enable_i18n", false));
f.sandbox.__STATSIG__ = { firstInstance: f.client, instances: { same: f.client } };
f.tick();
assert.equal(f.state().status().ready, true);
assert.deepEqual(observed, [true]);
assert.deepEqual(f.client.events, ["values_updated"]);
f.state().restore();
});
test("early registry and base-constructor registration intercept a later getter assignment before the first read", () => {
const f = fixture({ registry: {} });
delete f.sandbox.__STATSIG__;
assert.equal(f.install().ready, false);
const registry = {};
f.sandbox.__STATSIG__ = registry;
const rawLayer = new FixtureLayer();
const original = function () { assert.equal(this, client); return rawLayer; };
let missingDuringBase = false;
class Base {
constructor() {
const instances = registry.instances ?? {};
instances.fixture = this;
registry.firstInstance ||= this;
registry.instances = instances;
f.sandbox.__STATSIG__ = registry;
missingDuringBase = typeof this.getLayer !== "function";
}
}
class Derived extends Base {
constructor() { super(); this.getLayer = original; }
}
const client = new Derived();
assert.equal(missingDuringBase, true);
assert.equal(client.getLayer(layerName).get("enable_i18n", false), true, "no timer tick or SDK event is needed");
assert.equal(client.getLayer(layerName).get("locale_source", "wrong"), "fixture-original");
assert.equal(rawLayer.get("enable_i18n", false), false);
const laterSdkGetter = function () { return rawLayer; };
client.getLayer = laterSdkGetter;
assert.equal(client.getLayer(layerName).get("enable_i18n", false), true);
f.state().restore();
assert.equal(client.getLayer, laterSdkGetter, "restoration preserves the latest SDK-assigned method exactly");
assert.equal(f.sandbox.__STATSIG__, registry);
assert.equal(registry.instances.fixture, client);
for (const [object, key] of [[f.sandbox, "__STATSIG__"], [registry, "firstInstance"], [registry, "instances"], [registry.instances, "fixture"], [client, "getLayer"]]) {
assert.ok(Object.hasOwn(Object.getOwnPropertyDescriptor(object, key), "value"), `${key} is no longer an owned accessor`);
}
});
test("repeated injection and duplicate registry references never stack hooks or pollers", () => {
const f = fixture();
f.install();
const replacement = f.client.getLayer;
f.install(); f.tick(); f.install();
assert.equal(f.client.getLayer, replacement);
assert.equal(f.timers.size, 1);
assert.equal(f.observers.length, 1);
assert.deepEqual(f.client.events, ["values_updated"]);
assert.equal(f.install({ locale: "zh-CN", owner: "b".repeat(64) }).reason, "another_owner");
assert.equal(f.client.getLayer, replacement);
f.state().restore();
});
test("restoration removes inherited overrides and old handles or queued scans cannot rehook", () => {
const f = fixture();
const original = f.client.getLayer;
f.install();
const state = f.state();
const heldView = f.client.getLayer(layerName);
const queuedScan = f.scheduled[0];
state.restore();
assert.equal(f.state(), undefined);
assert.equal(f.timers.size, 0);
assert.ok(f.observers.every((observer) => !observer.active));
assert.equal(Object.hasOwn(f.client, "getLayer"), false);
assert.equal(f.client.getLayer, original);
assert.equal(heldView.get("enable_i18n", false), false);
const events = f.client.events.length;
assert.equal(state.status().installed, false);
queuedScan(); state.restore();
assert.equal(f.client.getLayer, original);
assert.equal(Object.hasOwn(f.client, "getLayer"), false);
assert.equal(f.client.events.length, events);
});
test("restoration preserves later SDK method replacements", () => {
const f = fixture();
const original = f.client.getLayer;
f.install();
const external = function (name, ...args) { return original.call(this, name, ...args); };
f.client.getLayer = external;
f.tick(); // The SDK replaced its method while compatibility was active.
f.state().restore();
assert.equal(f.client.getLayer, external);
});
test("readiness follows only current SDK registry clients, not past account instances", () => {
const f = fixture();
const old = f.client;
const original = old.getLayer;
f.install();
const next = new FixtureClient();
f.sandbox.__STATSIG__ = { firstInstance: next, instances: { same: next } };
f.tick();
assert.equal(f.state().status().clients, 1);
assert.equal(f.state().status().ready, true);
f.sandbox.__STATSIG__ = {};
assert.equal(f.state().status().ready, false);
assert.equal(f.state().status().clients, 0);
f.state().restore();
assert.equal(old.getLayer, original);
assert.equal(Object.hasOwn(next, "getLayer"), false);
});
test("readiness requires the selected language and the official bundled translation resource", () => {
for (const resources of [[], ["https://other.example/assets/zh-CN-fixture.js"], ["app://other/assets/zh-CN-fixture.js"], ["app://-/different/zh-CN-fixture.js"], ["app://user@-/assets/zh-CN-fixture.js"]]) {
const f = fixture({ resources });
assert.equal(f.install().ready, false);
f.state().restore();
}
for (const language of ["zh-TW", "zh-HK", "en-US"]) {
const f = fixture({ language });
assert.equal(f.install().ready, false);
f.state().restore();
}
const english = fixture({ language: "en-US", resources: [] });
assert.equal(english.install({ locale: "en-US", owner }).ready, true);
english.state().restore();
});
test("observed language resources survive resource-timing buffer eviction", () => {
const f = fixture({ resources: [] });
assert.equal(f.install().ready, false);
f.emitResources([languageResource]);
f.clearResources();
assert.equal(f.state().status().ready, true);
f.state().restore();
});
test("early documents without a documentElement remain unready until the language is present", () => {
const f = fixture({ documentElement: false });
assert.equal(f.install().ready, false);
f.sandbox.document.documentElement = { lang: "zh-CN" };
assert.equal(f.state().status().ready, true);
f.state().restore();
});
test("the runtime does not access account data, messages, credential storage or network APIs", () => {
const f = fixture();
for (const [object, names] of [[f.sandbox, ["fetch", "XMLHttpRequest", "localStorage", "sessionStorage"]], [f.client, ["user", "apiKey", "messages", "account"]], [f.sandbox.document, ["body", "cookie"]]]) {
for (const name of names) Object.defineProperty(object, name, { configurable: true, get() { assert.fail(`runtime accessed forbidden fixture field ${name}`); } });
}
assert.equal(f.install().ready, true);
assert.equal(f.state().status().ready, true);
f.tick();
f.state().restore();
});
@@ -0,0 +1,135 @@
import assert from "node:assert/strict";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { dirname, join, relative, resolve } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import test from "node:test";
import ts from "typescript";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { configHealthIssueLocation, primaryConfigHealthIssue, configHealthRepairUnavailableReason } from "../src/configHealthPresentation.ts";
import { configHealthIssueKey } from "../src/configHealthMonitor.ts";
const desktop = dirname(dirname(fileURLToPath(import.meta.url)));
const issue = {
code: "provider-boolean-text", title: "供应商开关格式不正确", description: "supports_websockets 被写成了字符串。",
repairable: true, path: "/fixtures/配置目录/config.toml", line: 7, column: 3,
key: "model_providers.custom.supports_websockets", suggestion: "将 supports_websockets 改为 false(不带引号)。",
};
const report = {
codexDir: "/fixtures/配置目录", fingerprint: "fixture-only", status: "issues", issues: [issue],
canRepair: true, repairSummary: ["将写成文字的开关恢复为正确格式"], checkedAt: "2026-10-08T00:00:00Z",
};
let components;
async function ui() {
if (components) return components;
components = (async () => {
const scratch = await mkdtemp(join(desktop, "tests/.config-health-ui-"));
try {
const emitted = new Map();
async function compile(sourcePath) {
if (emitted.has(sourcePath)) return emitted.get(sourcePath);
const outputPath = join(scratch, relative(desktop, sourcePath).replace(/\.tsx?$/, ".mjs"));
emitted.set(sourcePath, outputPath);
const source = await readFile(sourcePath, "utf8");
let output = ts.transpileModule(source, {
fileName: sourcePath,
compilerOptions: { target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.ESNext, jsx: ts.JsxEmit.ReactJSX },
}).outputText.replace(/import\s*["'][^"']+\.css["'];?/g, "");
for (const match of [...output.matchAll(/\bfrom\s*["'](\.[^"']+)["']/g)]) {
const specifier = match[1];
const base = resolve(dirname(sourcePath), specifier);
let dependency;
for (const candidate of [`${base}.ts`, `${base}.tsx`, join(base, "index.ts")]) {
try { await readFile(candidate, "utf8"); dependency = candidate; break; } catch { /* Try normal TS module resolution candidates. */ }
}
assert.ok(dependency, `could not resolve ${specifier} from ${sourcePath}`);
const dependencyOutput = await compile(dependency);
let replacement = relative(dirname(outputPath), dependencyOutput).replaceAll("\\", "/");
if (!replacement.startsWith(".")) replacement = `./${replacement}`;
output = output.replaceAll(`"${specifier}"`, `"${replacement}"`).replaceAll(`'${specifier}'`, `'${replacement}'`);
}
await mkdir(dirname(outputPath), { recursive: true });
await writeFile(outputPath, output);
return outputPath;
}
const panel = await compile(join(desktop, "src/components/ConfigHealthPanel.tsx"));
const toast = await compile(join(desktop, "src/components/ConfigHealthToast.tsx"));
return { ...await import(pathToFileURL(panel).href), ...await import(pathToFileURL(toast).href) };
} finally { await rm(scratch, { recursive: true, force: true }); }
})();
return components;
}
const panelProps = { lang: "zh", report, checking: false, repairing: false, error: "", onCheck() {}, onRepair() {}, onOpenConfig() {} };
const toastProps = { lang: "zh", report, repairing: false, onRepair() {}, onDismiss() {}, onOpenSettings() {} };
test("exact path, original line and column, parameter, and suggestion render in panel and notice", async () => {
const { ConfigHealthPanel, ConfigHealthToast } = await ui();
for (const [Component, props] of [[ConfigHealthPanel, panelProps], [ConfigHealthToast, toastProps]]) {
const html = renderToStaticMarkup(createElement(Component, props));
for (const detail of [issue.path, "第 7 行,第 3 列", issue.key, issue.suggestion, "修复配置"]) assert.ok(html.includes(detail), detail);
const repairButton = [...html.matchAll(/<button\b[^>]*>[\s\S]*?<\/button>/g)].map(([button]) => button).find((button) => button.includes("修复配置"));
assert.ok(repairButton);
assert.doesNotMatch(repairButton, /\bdisabled=/);
}
assert.equal(configHealthIssueLocation(issue, report, "en").position, "line 7, column 3");
});
test("official history repair is actionable and a missing table never claims an invented source line", async () => {
const missing = { ...issue, code: "session-provider-definition-missing", title: "旧会话使用的供应商缺少配置", line: null, column: null, key: "model_providers.old_proxy", suggestion: "新增 model_providers.old_proxy,使用当前已确认的 OpenAI 官方登录。" };
const official = { ...report, issues: [missing], repairSummary: ["让旧会话沿用当前供应商「OpenAI」"] };
const { ConfigHealthPanel, ConfigHealthToast } = await ui();
for (const [Component, props] of [[ConfigHealthPanel, panelProps], [ConfigHealthToast, toastProps]]) {
const html = renderToStaticMarkup(createElement(Component, { ...props, report: official }));
assert.ok(html.includes("修复配置"));
assert.ok(html.includes("未定义,尚无对应行"));
assert.ok(html.includes("model_providers.old_proxy"));
assert.ok(html.includes("OpenAI"));
assert.ok(!html.includes("第 7 行"));
}
});
test("unsupported values display their precise manual action and explain the unavailable repair button", async () => {
const unsupported = { ...issue, repairable: false, key: "model_providers.custom.wire_api", suggestion: "先向供应商确认 Responses API 支持,再设置 wire_api = responses。" };
const manual = { ...report, canRepair: false, repairSummary: [], issues: [unsupported] };
const { ConfigHealthPanel, ConfigHealthToast } = await ui();
const html = renderToStaticMarkup(createElement(ConfigHealthPanel, { ...panelProps, report: manual }));
assert.ok(html.includes("需手动修复"));
assert.ok(html.includes(unsupported.suggestion));
assert.ok(html.includes(`title="${unsupported.suggestion}"`));
const manualButton = [...html.matchAll(/<button\b[^>]*>[\s\S]*?<\/button>/g)].map(([button]) => button).find((button) => button.includes("需手动修复"));
assert.ok(manualButton);
assert.match(manualButton, /\bdisabled=""/);
const toast = renderToStaticMarkup(createElement(ConfigHealthToast, { ...toastProps, report: manual }));
assert.ok(toast.includes(unsupported.key));
assert.ok(toast.includes(unsupported.suggestion));
assert.ok(toast.includes("查看设置"));
assert.ok(!toast.includes("修复配置"));
});
test("a mixed report advertises a supported issue while the panel retains all manual diagnostics", async () => {
const manual = { ...issue, repairable: false, title: "必须手动处理", key: "model_providers.custom.base_url" };
const mixed = { ...report, issues: [manual, issue] };
assert.equal(primaryConfigHealthIssue(mixed), issue);
assert.equal(configHealthRepairUnavailableReason({ ...mixed, canRepair: false }, "zh"), manual.suggestion);
const { ConfigHealthToast, ConfigHealthPanel } = await ui();
const toast = renderToStaticMarkup(createElement(ConfigHealthToast, { ...toastProps, report: mixed }));
assert.ok(toast.includes(issue.key));
assert.ok(!toast.includes(manual.key));
const panel = renderToStaticMarkup(createElement(ConfigHealthPanel, { ...panelProps, report: mixed }));
assert.ok(panel.includes(manual.key));
assert.ok(panel.includes(issue.key));
});
test("notification identity follows the parameter and repairability while ignoring source line shifts", () => {
assert.equal(configHealthIssueKey(report), configHealthIssueKey({ ...report, issues: [{ ...issue, line: 80, column: 5 }] }));
assert.notEqual(configHealthIssueKey(report), configHealthIssueKey({ ...report, issues: [{ ...issue, key: "model_providers.other.supports_websockets" }] }));
assert.notEqual(configHealthIssueKey(report), configHealthIssueKey({ ...report, issues: [{ ...issue, repairable: false }] }));
});
test("file-level diagnostics and legacy reports use a usable path without claiming a line", () => {
assert.deepEqual(configHealthIssueLocation({ ...issue, key: '"<文件编码>"', line: null, column: null }, report, "zh"), { path: issue.path, position: "文件层面", key: '"<文件编码>"' });
const legacy = { code: "legacy", title: "Legacy", description: "Review", repairable: false };
assert.equal(configHealthIssueLocation(legacy, { ...report, codexDir: "/fixtures/codex/" }, "en").path, "/fixtures/codex/config.toml");
});
+64 -1
View File
@@ -28,6 +28,39 @@
let transferMode = "success";
let lastTransfer = null;
let existingImportAvailable = true;
// Independent of the persisted provider fixture: language controls only model
// the current page's memory, never a real Codex process or configuration.
let codexLanguageEnabled = true;
let codexLanguagePendingEnabled = null;
let codexLanguageMode = "normal";
function codexLanguageStatus() {
return {
locale: codexLanguageEnabled ? "zh-CN" : "auto",
enabled: codexLanguageEnabled,
pendingEnabled: codexLanguagePendingEnabled,
supported: true,
appName: "ChatGPT",
appVersion: "fixture",
phase: codexLanguageEnabled ? "active" : "inactive",
message: "",
readyPages: 0,
restoreAvailable: false,
};
}
function setCodexLanguageActual(enabled) {
if (typeof enabled !== "boolean") throw new Error("Unknown fixture language state");
codexLanguageEnabled = enabled;
codexLanguagePendingEnabled = null;
render();
}
function setCodexLanguageMode(mode) {
if (!["normal", "save-error", "apply-error"].includes(mode)) throw new Error("Unknown fixture language mode");
codexLanguageMode = mode;
render();
}
const defaultRoutingSettings = () => ({ version: 2, routerEnabled: false, takeoverEnabled: false, autoFailoverEnabled: false,
listenAddress: "127.0.0.1", listenPort: 15721, providerIds: [], maxRetries: 3, streamingFirstByteTimeout: 60,
streamingIdleTimeout: 120, nonStreamingTimeout: 600, circuitFailureThreshold: 4, circuitSuccessThreshold: 2,
@@ -277,6 +310,8 @@
function snapshot() {
return {
startupWizardSeen: localStorage.getItem("codexx.startupWizardSeen"),
codexLanguage: codexLanguageStatus(),
codexLanguageMode,
transferMode, lastTransfer,
failoverSettings: clone(failoverSettings), failoverMode,
pendingSync: pending.sync.length,
@@ -838,6 +873,20 @@
async function dispatch(command, args) {
switch (command) {
case "get_codex_language_status": return codexLanguageStatus();
case "save_codex_language_preferences": {
if (codexLanguageMode === "save-error") throw new Error("Fixture:语言设置保存失败,当前配置未改变");
if (typeof args.enabled !== "boolean" || args.locale !== (args.enabled ? "zh-CN" : "auto")) throw new Error("Fixture:语言偏好参数无效");
codexLanguagePendingEnabled = args.enabled === codexLanguageEnabled ? null : args.enabled;
return codexLanguageStatus();
}
case "apply_codex_language_preferences": {
if (codexLanguageMode === "apply-error") throw new Error("Fixture:语言设置应用失败,尚未重启客户端");
if (args.restore === true) throw new Error("Fixture:没有可恢复的语言快照");
codexLanguageEnabled = codexLanguagePendingEnabled ?? codexLanguageEnabled;
codexLanguagePendingEnabled = null;
return codexLanguageStatus();
}
case "get_provider_config_base": {
if (providerBaseReadFailure) throw new Error("Fixture:无法读取供应商配置底稿");
// Model a legacy route-only file with the official integration snapshot
@@ -1088,6 +1137,8 @@
window.__CODEX_X_FIXTURE__ = {
snapshot,
loginSecondOfficialAccount,
setCodexLanguageActual,
setCodexLanguageMode,
setUsageMode,
setQuotaMode,
setProviderOrderMode,
@@ -1109,7 +1160,7 @@
document.addEventListener("DOMContentLoaded", () => {
const panel = document.createElement("aside");
panel.setAttribute("aria-label", "Fixture 控制面板");
panel.style.cssText = "position:fixed;left:8px;bottom:8px;z-index:2147483647;width:224px;max-width:calc(100vw - 16px);box-sizing:border-box;background:#fff;color:#111;border:2px solid #1463d6;border-radius:8px;padding:8px;font:12px monospace;box-shadow:0 2px 8px #0003";
panel.style.cssText = "position:fixed;left:8px;bottom:8px;z-index:2147483647;width:224px;max-width:calc(100vw - 16px);max-height:calc(100vh - 16px);overflow:auto;box-sizing:border-box;background:#fff;color:#111;border:2px solid #1463d6;border-radius:8px;padding:8px;font:12px monospace;box-shadow:0 2px 8px #0003";
const panelBody = document.createElement("details");
panelBody.open = true;
const label = document.createElement("summary");
@@ -1137,6 +1188,18 @@
const option = document.createElement("option"); option.value = value; option.textContent = label; transferSelect.append(option);
}
transferSelect.addEventListener("change", () => { transferMode = transferSelect.value; render(); }); controls.append(transferSelect);
for (const [text, action] of [
["Fixture:语言外部改为中文", () => setCodexLanguageActual(true)],
["Fixture:语言外部改为自动", () => setCodexLanguageActual(false)],
["Fixture:语言保存失败", () => setCodexLanguageMode("save-error")],
["Fixture:语言应用失败", () => setCodexLanguageMode("apply-error")],
["Fixture:语言恢复正常", () => setCodexLanguageMode("normal")],
]) {
const button = document.createElement("button");
button.type = "button"; button.textContent = text;
button.style.cssText = "font:inherit;padding:5px;border:1px solid #aaa;border-radius:4px;background:#eee;color:#111;cursor:pointer";
button.addEventListener("click", action); controls.append(button);
}
for (const [text, mode] of [["Fixture:配置正常", "healthy"], ["Fixture:缺失供应商配置", "missing"], ["Fixture:配置语法错误", "syntax"]]) {
const button = document.createElement("button");
button.type = "button"; button.textContent = text;
@@ -0,0 +1,36 @@
import assert from "node:assert/strict";
import test from "node:test";
import { MAX_AUTH_IMPORT_BYTES, parseOfficialAuthImport, readOfficialAuthImport } from "../src/officialAuthImport.ts";
const encoded = text => new TextEncoder().encode(text);
const auth = { auth_mode: "chatgpt", tokens: { access_token: "fixture-access", refresh_token: "fixture-refresh", account_id: "fixture-account" }, last_refresh: "2026-10-16", extra: { preserve: true } };
test("reads a standard auth file into a draft while preserving unknown fields", async () => {
const original = JSON.stringify(auth, null, 2);
const bytes = encoded(original);
const result = await readOfficialAuthImport({ size: bytes.length, arrayBuffer: async () => bytes.buffer });
assert.equal(result, original);
assert.deepEqual(JSON.parse(result), auth);
});
test("accepts UTF-8 BOM and a standard OpenAI API key auth file", () => {
assert.deepEqual(JSON.parse(parseOfficialAuthImport(encoded("\uFEFF" + JSON.stringify(auth)))), auth);
assert.deepEqual(JSON.parse(parseOfficialAuthImport(encoded('{"OPENAI_API_KEY":"fixture-key"}'))), { OPENAI_API_KEY: "fixture-key" });
});
test("rejects oversized files before reading their contents", async () => {
let reads = 0;
await assert.rejects(readOfficialAuthImport({ size: MAX_AUTH_IMPORT_BYTES + 1, arrayBuffer: async () => { reads++; return new ArrayBuffer(0); } }), { code: "too_large" });
assert.equal(reads, 0);
});
test("rejects invalid UTF-8 and JSON without echoing credential text", () => {
assert.throws(() => parseOfficialAuthImport(new Uint8Array([0xff, 0xfe])), { code: "invalid_text" });
assert.throws(() => parseOfficialAuthImport(encoded('{"tokens":"private-fixture-token')), error => error.code === "invalid_json" && !error.message.includes("private-fixture-token"));
});
test("does not treat arrays, third party configurations, or arbitrary JSON as official auth", () => {
for (const value of [[], [auth], null, "x", {}, { accounts: [auth] }, { tokens: {} }, { OPENAI_API_KEY: " " }, { ...auth, base_url: "https://fixture.invalid/v1" }]) {
assert.throws(() => parseOfficialAuthImport(encoded(JSON.stringify(value))), { code: "unsupported_shape" });
}
});
test("checks actual decoded byte size even when a file supplies an inaccurate size", async () => {
const bytes = new Uint8Array(MAX_AUTH_IMPORT_BYTES + 1);
await assert.rejects(readOfficialAuthImport({ size: 1, arrayBuffer: async () => bytes.buffer }), { code: "too_large" });
});
@@ -0,0 +1,83 @@
import assert from "node:assert/strict";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { dirname, join, relative, resolve } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import test from "node:test";
import ts from "typescript";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
const desktop = dirname(dirname(fileURLToPath(import.meta.url)));
let page;
async function loadPage() {
if (page) return page;
page = (async () => {
const scratch = await mkdtemp(join(desktop, "tests/.provider-activation-ui-"));
try {
const emitted = new Map();
async function compile(sourcePath) {
if (emitted.has(sourcePath)) return emitted.get(sourcePath);
const outputPath = join(scratch, relative(desktop, sourcePath).replace(/\.tsx?$/, ".mjs"));
emitted.set(sourcePath, outputPath);
const source = await readFile(sourcePath, "utf8");
// Animation is unrelated to action locks and has browser layout effects.
let output = sourcePath.endsWith("/PageTransition.tsx") ? "export function PageTransition({ children }) { return children; }" : ts.transpileModule(source, {
fileName: sourcePath,
compilerOptions: { target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.ESNext, jsx: ts.JsxEmit.ReactJSX },
}).outputText.replace(/import\s*["'][^"']+\.css["'];?/g, "");
for (const match of [...output.matchAll(/\bfrom\s*["'](\.[^"']+)["']/g)]) {
const specifier = match[1];
const base = resolve(dirname(sourcePath), specifier);
let dependency;
for (const candidate of [`${base}.ts`, `${base}.tsx`, join(base, "index.ts")]) {
try { await readFile(candidate, "utf8"); dependency = candidate; break; } catch { /* Try the next TS module candidate. */ }
}
assert.ok(dependency, `could not resolve ${specifier}`);
const dependencyOutput = await compile(dependency);
let replacement = relative(dirname(outputPath), dependencyOutput).replaceAll("\\", "/");
if (!replacement.startsWith(".")) replacement = `./${replacement}`;
output = output.replaceAll(`"${specifier}"`, `"${replacement}"`).replaceAll(`'${specifier}'`, `'${replacement}'`);
}
await mkdir(dirname(outputPath), { recursive: true });
await writeFile(outputPath, output);
return outputPath;
}
return (await import(pathToFileURL(await compile(join(desktop, "src/pages/ProvidersPage.tsx"))).href)).ProvidersPage;
} finally { await rm(scratch, { recursive: true, force: true }); }
})();
return page;
}
const baseRow = { baseUrl: "https://fixture.example.test/v1", model: "fixture-model", wireApi: "responses", requiresOpenaiAuth: false, editable: true, duplicable: true, deletable: true, testable: true };
const copy = new Proxy({ enableLabel: "Enable fixture", addLabel: "Add fixture", importLabel: "Import fixture" }, { get: (target, key) => target[key] ?? String(key) });
const props = {
mode: "list", lang: "en", configDir: "/fixture/codex", copy, loading: true, actionBusy: "syncSessions",
providerRows: [
{ ...baseRow, id: "current", source: "local", providerName: "Current fixture", isCurrent: true },
{ ...baseRow, id: "next", source: "local", providerName: "Next fixture", isCurrent: false },
{ ...baseRow, id: "official-next", source: "official", providerName: "Official fixture", isCurrent: false },
],
onImportCcSwitch() {}, onAddProvider() {}, onEnableProvider() {}, onTestProvider() {}, onEditProvider() {}, onDuplicateProvider() {}, onDeleteProvider() {}, onReorderProviders() {},
};
const buttons = (html, label) => [...html.matchAll(/<button\b[^>]*>[\s\S]*?<\/button>/g)].map(([button]) => button).filter((button) => button.includes(label));
test("sync permits switching local and official providers while other provider actions stay disabled", async () => {
const ProvidersPage = await loadPage();
const html = renderToStaticMarkup(createElement(ProvidersPage, { ...props, activationBusy: false }));
const enable = buttons(html, "Enable fixture");
assert.equal(enable.length, 3);
assert.match(enable[0], /\bdisabled=/, "the current provider is never activated again");
assert.doesNotMatch(enable[1], /\bdisabled=/, "another API provider can be enabled during sync");
assert.doesNotMatch(enable[2], /\bdisabled=/, "an official profile can be enabled during sync");
for (const label of ["Add fixture", "Import fixture"]) assert.match(buttons(html, label)[0], /\bdisabled=/);
assert.match(buttons(html, "editLabel")[0], /\bdisabled=/);
assert.match(buttons(html, "duplicateLabel")[0], /\bdisabled=/);
});
test("a real activation or unrelated operation keeps every activation button locked", async () => {
const ProvidersPage = await loadPage();
for (const extra of [{ activationBusy: true }, {}]) {
const html = renderToStaticMarkup(createElement(ProvidersPage, { ...props, ...extra }));
assert.ok(buttons(html, "Enable fixture").every((button) => /\bdisabled=/.test(button)));
}
});
@@ -0,0 +1,265 @@
import assert from "node:assert/strict";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { dirname, join, relative, resolve } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import test from "node:test";
import ts from "typescript";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
const desktop = dirname(dirname(fileURLToPath(import.meta.url)));
let components;
async function ui() {
if (components) return components;
components = (async () => {
const scratch = await mkdtemp(join(desktop, "tests/.provider-editor-ui-"));
try {
const emitted = new Map();
async function compile(sourcePath) {
if (emitted.has(sourcePath)) return emitted.get(sourcePath);
const outputPath = join(scratch, relative(desktop, sourcePath).replace(/\.tsx?$/, ".mjs"));
emitted.set(sourcePath, outputPath);
let output = ts.transpileModule(await readFile(sourcePath, "utf8"), {
fileName: sourcePath,
compilerOptions: { target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.ESNext, jsx: ts.JsxEmit.ReactJSX },
}).outputText.replace(/import\s*["'][^"']+\.css["'];?/g, "");
for (const match of [...output.matchAll(/\bfrom\s*["'](\.[^"']+)["']/g)]) {
const specifier = match[1];
const base = resolve(dirname(sourcePath), specifier);
let dependency;
for (const candidate of [`${base}.ts`, `${base}.tsx`, join(base, "index.ts")]) {
try { await readFile(candidate, "utf8"); dependency = candidate; break; } catch { /* Normal TypeScript resolution candidates. */ }
}
assert.ok(dependency, `could not resolve ${specifier} from ${sourcePath}`);
const dependencyOutput = await compile(dependency);
let replacement = relative(dirname(outputPath), dependencyOutput).replaceAll("\\", "/");
if (!replacement.startsWith(".")) replacement = `./${replacement}`;
output = output.replaceAll(`"${specifier}"`, `"${replacement}"`).replaceAll(`'${specifier}'`, `'${replacement}'`);
}
await mkdir(dirname(outputPath), { recursive: true });
await writeFile(outputPath, output);
return outputPath;
}
const editor = await compile(join(desktop, "src/components/ProviderHeadersEditor.tsx"));
const page = await compile(join(desktop, "src/pages/ProvidersPage.tsx"));
return { ...await import(pathToFileURL(editor).href), ...await import(pathToFileURL(page).href) };
} finally { await rm(scratch, { recursive: true, force: true }); }
})();
return components;
}
function render(Component, props) {
// PageTransition uses a layout effect. SSR deliberately runs neither it nor
// the HeadersControl effects; this checks presentation, not Tauri IPC.
const warnings = [];
const originalError = console.error;
try {
console.error = (...args) => warnings.push(args.join(" "));
const html = renderToStaticMarkup(createElement(Component, props));
for (const warning of warnings) assert.match(warning, /^Warning: useLayoutEffect does nothing on the server/);
return html;
} finally { console.error = originalError; }
}
function attributes(tag) {
return Object.fromEntries([...tag.matchAll(/\s([A-Za-z][\w:-]*)="([^"]*)"/g)].map(([, name, value]) => [name, value]));
}
function elements(html, name) {
const pattern = name === "input" ? /<input\b[^>]*>/g : new RegExp(`<${name}\\b[^>]*>[\\s\\S]*?<\\/${name}>`, "g");
return [...html.matchAll(pattern)].map(([tag]) => ({ tag, attrs: attributes(tag.slice(0, tag.indexOf(">") + 1)) }));
}
function control(html, name, label) {
const found = elements(html, name).find((element) => element.attrs["aria-label"] === label);
assert.ok(found, `${name} with accessible label ${label}`);
return found;
}
function selectedOption(select) {
const selected = elements(select.tag, "option").filter(({ attrs }) => "selected" in attrs);
assert.equal(selected.length, 1, "a protocol/source selector must have one explicit selected option");
return selected[0];
}
function protocolSelect(html) {
const found = elements(html, "select").find(({ tag }) => elements(tag, "option").some(({ attrs }) => attrs.value === "responses"));
assert.ok(found, "the actual provider form must include its upstream protocol selector");
return found;
}
const noop = () => {};
const validRows = [
{ name: "X-Title", value: "Fixture Project", source: "static" },
{ name: "X-Project", value: "FIXTURE_PROJECT_NAME", source: "env" },
];
function formProps(lang, protocol = "responses", overrides = {}) {
const text = (zh, en) => lang === "zh" ? zh : en;
return {
lang, mode: "form", creatingProvider: false, editingProviderId: "fixture-provider",
selectedPresetId: "custom", selectedPresetVariantId: "custom",
loading: false, fetchingModels: false, apiKeyVisible: false, availableModels: [],
providerForm: { providerName: "Fixture provider", baseUrl: "https://fixture.example/v1", apiKey: "", model: "fixture-model", wireApi: "responses", upstreamApi: protocol, requiresOpenaiAuth: false },
providerModelMappings: [], providerAuthPreview: "Fixture auth preview",
providerTomlDraft: 'model_provider = "custom"\n[model_providers.custom]\nname = "Fixture provider"\nhttp_headers = { "X-Title" = "Fixture Project" }\n',
copy: {
formEyebrow: "Fixture", formAddTitle: text("新增供应商", "Add provider"), formEditTitle: text("编辑供应商", "Edit provider"),
formHint: text("供应商配置", "Provider configuration"), cancelLabel: text("取消", "Cancel"),
apiConfigTitle: "API", apiConfigDescription: text("接口设置", "API settings"), apiKeyLabel: "API Key", apiKeyPlaceholder: "Fixture API key",
showApiKeyLabel: text("显示密钥", "Show API key"), hideApiKeyLabel: text("隐藏密钥", "Hide API key"), baseUrlLabel: "Base URL",
nameLabel: text("供应商名称", "Provider name"), modelLabel: text("模型", "Model"), fetchModelsLabel: text("获取模型", "Fetch models"), fetchingModelsLabel: text("获取中", "Fetching"),
requiresAuthLabel: text("使用 OpenAI 认证", "Use OpenAI authentication"), authPreviewTitle: text("认证预览", "Authentication preview"), authPreviewDescription: "Fixture preview",
tomlTitle: "config.toml", tomlDescription: "Fixture TOML", resetTomlLabel: text("重置 TOML", "Reset TOML"), saveLabel: text("保存供应商", "Save provider"), savingLabel: text("保存中", "Saving"),
},
onPresetSelect: noop, onPresetVariantSelect: noop, onProviderModelMappingsChange: noop, onCancelMode: noop,
onApiKeyChange: noop, onBaseUrlChange: noop, onProviderNameChange: noop, onProviderModelChange: noop, onFetchModels: noop,
onUpstreamApiChange: noop, onRequiresAuthChange: noop, onToggleApiKeyVisibility: noop,
onProviderTomlDraftChange: noop, onProviderHeadersConfigChange: noop, onResetProviderToml: noop, onSaveProvider: noop,
...overrides,
};
}
for (const lang of ["zh", "en"]) {
const zh = lang === "zh";
const rowLabel = (index) => zh ? `第 ${index + 1} 行` : `Row ${index + 1}`;
const nameLabel = zh ? "名称" : "Name";
const valueLabel = zh ? "值" : "Value";
const sourceLabel = zh ? "值来源" : "Value source";
const envLabel = zh ? "环境变量" : "Environment variable";
test(`model discovery allows authentication headers without requiring an API key field (${lang})`, async () => {
const { ProvidersPage } = await ui();
const props = formProps(lang);
const label = zh ? "获取模型" : "Fetch models";
assert.equal(props.providerForm.apiKey, "");
const html = render(ProvidersPage, props);
assert.equal(control(html, "button", label).attrs.disabled, undefined);
const missingUrl = render(ProvidersPage, { ...props, providerForm: { ...props.providerForm, baseUrl: "" } });
assert.notEqual(control(missingUrl, "button", label).attrs.disabled, undefined);
});
test(`Headers editor renders literal and environment rows with accessible help (${lang})`, async () => {
const { ProviderHeadersEditor } = await ui();
const html = render(ProviderHeadersEditor, { lang, rows: validRows, onChange: noop });
assert.ok(html.includes(`role="group" aria-label="${rowLabel(0)}"`));
assert.ok(html.includes(`role="group" aria-label="${rowLabel(1)}"`));
assert.equal(control(html, "input", `${nameLabel} · ${rowLabel(0)}`).attrs.value, "X-Title");
assert.equal(control(html, "input", `${valueLabel} · ${rowLabel(0)}`).attrs.value, "Fixture Project");
assert.equal(selectedOption(control(html, "select", `${sourceLabel} · ${rowLabel(0)}`)).attrs.value, "static");
assert.equal(selectedOption(control(html, "select", `${sourceLabel} · ${rowLabel(1)}`)).attrs.value, "env");
const env = control(html, "input", `${envLabel} · ${rowLabel(1)}`);
assert.equal(env.attrs.value, "FIXTURE_PROJECT_NAME");
assert.equal(env.attrs["aria-invalid"], "false");
assert.ok(env.attrs["aria-describedby"]);
const help = elements(html, "p").find(({ attrs }) => attrs.id === env.attrs["aria-describedby"]);
assert.ok(help, "the environment input must reference existing help text");
assert.ok(help.tag.includes(zh ? "环境变量模式只保存变量名" : "Environment mode saves only the variable name"));
assert.ok(html.includes(zh ? "固定值" : "Literal value"));
assert.ok(!html.includes('aria-invalid="true"'));
});
test(`Headers editor exposes row errors through aria-invalid and exact descriptions (${lang})`, async () => {
const { ProviderHeadersEditor } = await ui();
const rows = [
{ name: "bad name", value: "ok", source: "static" },
{ name: "X-Env", value: "2INVALID_ENV", source: "env" },
{ name: "X-Line", value: "one\ntwo", source: "static" },
{ name: "X-Source", value: "ok", source: "unknown" },
{ name: "X-Title", value: "one", source: "static" },
{ name: "x-title", value: "FIXTURE_TITLE", source: "env" },
];
const html = render(ProviderHeadersEditor, { lang, rows, onChange: noop });
const cases = [
["input", `${nameLabel} · ${rowLabel(0)}`, zh ? "名称只能使用" : "Use letters, numbers"],
["input", `${envLabel} · ${rowLabel(1)}`, zh ? "请填写环境变量名" : "Enter an environment variable name"],
["input", `${valueLabel} · ${rowLabel(2)}`, zh ? "不能包含换行或控制字符" : "cannot contain line breaks or control characters"],
["select", `${sourceLabel} · ${rowLabel(3)}`, zh ? "请选择固定值或环境变量" : "Choose a literal value or environment variable"],
["input", `${nameLabel} · ${rowLabel(4)}`, zh ? "此名称重复" : "Duplicate header name"],
["input", `${nameLabel} · ${rowLabel(5)}`, zh ? "此名称重复" : "Duplicate header name"],
];
const errorIds = new Set();
for (const [element, label, message] of cases) {
const field = control(html, element, label);
assert.equal(field.attrs["aria-invalid"], "true", label);
const errorId = field.attrs["aria-describedby"];
assert.ok(errorId, `error description for ${label}`);
assert.ok(!errorIds.has(errorId), "each field must reference its own row error");
errorIds.add(errorId);
const error = elements(html, "small").find(({ attrs }) => attrs.id === errorId);
assert.ok(error?.tag.includes(message), `specific visible error for ${label}`);
}
assert.ok(html.includes(zh ? "请先修正标红的 Headers" : "Correct the highlighted headers"));
assert.equal(control(html, "input", `${valueLabel} · ${rowLabel(0)}`).attrs["aria-invalid"], "false", "a name error must not mark that row's valid value invalid");
});
test(`Headers editor offers explicit UA presets and header-specific examples (${lang})`, async () => {
const { ProviderHeadersEditor } = await ui();
const empty = render(ProviderHeadersEditor, { lang, rows: [], onChange: noop });
const preset = control(empty, "select", zh ? "User-Agent 预设" : "User-Agent presets");
assert.deepEqual(elements(preset.tag, "option").map(({ attrs }) => attrs.value), ["", "claude_code", "kilo_code"]);
assert.ok(preset.tag.includes("claude-cli/2.1.161 (external, cli)"));
assert.ok(preset.tag.includes("Kilo-Code/1.0"));
assert.equal(elements(empty, "input").length, 0, "mounting must not create headers from presets");
assert.ok(empty.includes(zh ? "其他请求头保留" : "keep other headers"));
const names = ["User-Agent", "HTTP-Referer", "X-Title", "Authorization"];
const html = render(ProviderHeadersEditor, { lang, rows: names.map((name) => ({ name, value: "", source: "static" })), onChange: noop });
const placeholders = names.map((_, index) => control(html, "input", `${valueLabel} · ${rowLabel(index)}`).attrs.placeholder);
assert.equal(new Set(placeholders).size, names.length);
assert.ok(placeholders.every((placeholder) => !placeholder.includes("Codex-X")));
assert.ok(placeholders[1].includes("https://your-app.example"));
assert.ok(placeholders[3].includes("Bearer "));
});
test(`disabled Headers editor disables every row control (${lang})`, async () => {
const { ProviderHeadersEditor } = await ui();
const html = render(ProviderHeadersEditor, { lang, rows: validRows, disabled: true, onChange: noop });
const controls = ["input", "select", "button"].flatMap((name) => elements(html, name));
assert.equal(controls.length, 10);
assert.ok(controls.every(({ attrs }) => "disabled" in attrs));
});
test(`provider form contains the real HeadersControl and all four API choices (${lang})`, async () => {
const { ProvidersPage } = await ui();
let configChanges = 0;
const html = render(ProvidersPage, formProps(lang, "responses", { onProviderHeadersConfigChange() { configChanges += 1; } }));
assert.ok(html.includes('class="cx-provider-headers-control"'));
assert.ok(html.includes('class="cx-provider-headers"'));
assert.ok(html.includes(zh ? "正在读取 Headers…" : "Reading headers…"));
assert.ok(html.includes(zh ? "尚未配置自定义 Headers" : "No custom headers configured"), "SSR shows initial control state and does not run the TOML-read effect");
assert.equal(configChanges, 0);
const select = protocolSelect(html);
assert.deepEqual(elements(select.tag, "option").map(({ attrs }) => attrs.value), ["responses", "chat_completions", "anthropic_messages", "gemini"]);
for (const label of ["OpenAI Responses", "OpenAI Chat Completions", "Claude Messages", "Gemini generateContent"]) assert.ok(select.tag.includes(label));
assert.equal(selectedOption(select).attrs.value, "responses");
assert.ok(html.includes(zh ? "上游接口协议" : "Upstream API protocol"));
});
test(`converted APIs select their actual format and explain router lifetime (${lang})`, async () => {
const { ProvidersPage } = await ui();
for (const protocol of ["chat_completions", "anthropic_messages", "gemini"]) {
const html = render(ProvidersPage, formProps(lang, protocol));
assert.equal(selectedOption(protocolSelect(html)).attrs.value, protocol);
const hint = elements(html, "p").find(({ attrs }) => attrs.class?.includes("cx-providers-protocol-hint"));
assert.ok(hint, `routing explanation for ${protocol}`);
for (const text of zh ? ["Codex 仍使用 Responses", "开启本地路由和配置接管", "保持 Codex-X 运行", "退出期间请求会暂停", "重开后自动恢复", "切回 Responses"] : ["Codex still uses Responses", "local router and config takeover", "keep Codex-X running", "before disabling the router", "resume after reopening"]) assert.ok(hint.tag.includes(text), text);
}
});
test(`native Responses hides conversion guidance, while unknown APIs remain visibly unsupported (${lang})`, async () => {
const { ProvidersPage } = await ui();
for (const upstreamApi of [undefined, "responses"]) {
const html = render(ProvidersPage, formProps(lang, upstreamApi, { providerForm: { ...formProps(lang).providerForm, upstreamApi } }));
assert.equal(selectedOption(protocolSelect(html)).attrs.value, "responses");
assert.ok(!html.includes("cx-providers-protocol-hint"));
}
for (const providerForm of [
{ ...formProps(lang).providerForm, upstreamApi: "fixture_unknown_api" },
{ ...formProps(lang).providerForm, upstreamApi: null, wireApi: "fixture_legacy_api" },
]) {
const html = render(ProvidersPage, formProps(lang, "responses", { providerForm }));
const chosen = selectedOption(protocolSelect(html));
assert.equal(chosen.attrs.value, providerForm.upstreamApi || providerForm.wireApi);
assert.ok("disabled" in chosen.attrs);
assert.ok(chosen.tag.includes(zh ? "不支持的协议,请重新选择" : "Unsupported protocol"));
assert.notEqual(chosen.attrs.value, "responses");
}
const legacyChat = render(ProvidersPage, formProps(lang, "responses", { providerForm: { ...formProps(lang).providerForm, upstreamApi: null, wireApi: "chat" } }));
assert.equal(selectedOption(protocolSelect(legacyChat)).attrs.value, "chat_completions");
assert.ok(legacyChat.includes("cx-providers-protocol-hint"));
});
}
@@ -0,0 +1,102 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
PROVIDER_HEADER_PRESETS,
applyProviderHeaderPreset,
providerHeaderValuePlaceholder,
} from "../src/providerHeaderPresets.ts";
import { validateProviderHeaders } from "../src/providerHeaders.ts";
const row = (name, value = "", source = "static") => ({ name, value, source });
test("two explicit UA presets retain their reference values and bilingual labels", () => {
assert.deepEqual(PROVIDER_HEADER_PRESETS.map(({ id, name, value, label }) => ({ id, name, value, label })), [
{ id: "claude_code", name: "User-Agent", value: "claude-cli/2.1.161 (external, cli)", label: { zh: "Claude Code", en: "Claude Code" } },
{ id: "kilo_code", name: "User-Agent", value: "Kilo-Code/1.0", label: { zh: "Kilo Code", en: "Kilo Code" } },
]);
});
test("selecting a preset on an empty configuration creates only one static UA header", () => {
for (const preset of PROVIDER_HEADER_PRESETS) {
const configured = applyProviderHeaderPreset([], preset.id);
assert.deepEqual(configured, [row("User-Agent", preset.value)]);
assert.equal(validateProviderHeaders(configured).valid, true);
}
});
test("selecting the same preset repeatedly is idempotent and switching presets updates that row", () => {
const first = applyProviderHeaderPreset([], "claude_code");
const second = applyProviderHeaderPreset(first, "claude_code");
assert.deepEqual(second, first);
assert.deepEqual(applyProviderHeaderPreset(second, "kilo_code"), [row("User-Agent", "Kilo-Code/1.0")]);
assert.equal(first[0].value, "claude-cli/2.1.161 (external, cli)");
});
test("an existing environment UA is updated case insensitively without changing other sensitive values", () => {
const original = [
row("Authorization", " Bearer fixture-token "),
row(" uSeR-aGeNt ", "PROVIDER_UA", "env"),
row("x-api-key", " fixture-key\t"),
row("X-Project", "PROJECT_ENV", "env"),
];
const selected = applyProviderHeaderPreset(original, "claude_code");
assert.deepEqual(selected, [original[0], row("User-Agent", "claude-cli/2.1.161 (external, cli)"), original[2], original[3]]);
assert.equal(selected[0], original[0]);
assert.equal(selected[2], original[2]);
assert.equal(selected[3], original[3]);
assert.deepEqual(original[1], row(" uSeR-aGeNt ", "PROVIDER_UA", "env"));
});
test("only the first UA is updated and duplicate names remain visible to validation", () => {
const original = [row("", ""), row("USER-AGENT", "old-first"), row("user-agent", "SECOND_UA", "env"), row("X-Title", "App")];
const selected = applyProviderHeaderPreset(original, "kilo_code");
assert.equal(selected.length, original.length);
assert.equal(selected[0], original[0]);
assert.deepEqual(selected[1], row("User-Agent", "Kilo-Code/1.0"));
assert.equal(selected[2], original[2]);
assert.equal(selected[3], original[3]);
const validation = validateProviderHeaders(selected);
assert.equal(validation.valid, false);
assert.ok(validation.errors[1].name.includes("Duplicate"));
assert.ok(validation.errors[2].name.includes("Duplicate"));
});
test("a completely empty draft row is reused before appending a UA", () => {
const original = [row("X-Title", "App"), row(" \t ", "", "env"), row("", "")];
const selected = applyProviderHeaderPreset(original, "claude_code");
assert.equal(selected.length, 3);
assert.equal(selected[0], original[0]);
assert.deepEqual(selected[1], row("User-Agent", "claude-cli/2.1.161 (external, cli)"));
assert.equal(selected[2], original[2]);
assert.equal(original[1].source, "env");
});
test("unfinished drafts containing values are preserved and a UA is appended", () => {
const original = [row("", "unfinished secret"), row(" ", " "), row("X-Title", "App")];
const selected = applyProviderHeaderPreset(original, "kilo_code");
assert.deepEqual(selected, [...original, row("User-Agent", "Kilo-Code/1.0")]);
for (let index = 0; index < original.length; index++) assert.equal(selected[index], original[index]);
});
test("unknown preset IDs are a no-op and never overwrite a blank draft", () => {
const original = [row("Authorization", " fixture-token "), row("", "")];
assert.deepEqual(applyProviderHeaderPreset(original, "unknown"), original);
assert.equal(applyProviderHeaderPreset(original, "unknown")[0], original[0]);
assert.deepEqual(applyProviderHeaderPreset([], ""), []);
});
test("literal placeholders explain each header's purpose without a generic Codex-X value", () => {
for (const lang of ["zh", "en"]) {
const names = ["User-Agent", "HTTP-Referer", "X-Title", "Authorization", "x-api-key", "X-Custom"];
const hints = names.map((name) => providerHeaderValuePlaceholder(name, lang));
assert.equal(new Set(hints).size, names.length);
assert.ok(hints.every((hint) => hint && !hint.includes("Codex-X")));
assert.ok(hints[0].includes("claude-cli/"));
assert.ok(hints[1].includes("https://"));
assert.ok(hints[3].includes("Bearer"));
assert.ok(hints[4].includes("API key") || hints[4].includes("API Key"));
assert.equal(providerHeaderValuePlaceholder("x-OpenRouter-Title", lang), hints[2]);
assert.equal(providerHeaderValuePlaceholder("X-GOOG-API-KEY", lang), hints[4]);
assert.equal(providerHeaderValuePlaceholder(" user-agent ", lang), hints[0]);
}
});
@@ -0,0 +1,66 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
createProviderHeader,
findProviderHeader,
normalizeProviderHeaders,
removeProviderHeader,
updateProviderHeader,
validateProviderHeaders,
} from "../src/providerHeaders.ts";
const header = (name, value = "Codex-X", source = "static") => ({ name, value, source });
test("normalization retains original values and supports static/environment headers", () => {
const rows = [header(" X-Title ", " keep whitespace "), header("X-Project", "PROJECT_KEY", "env")];
assert.equal(validateProviderHeaders(rows).valid, true);
assert.deepEqual(normalizeProviderHeaders(rows), [header("X-Title", " keep whitespace "), rows[1]]);
assert.equal(findProviderHeader(rows, "x-title"), rows[0]);
assert.equal(rows[0].name, " X-Title ");
});
test("duplicate names are rejected across sources and letter case", () => {
const result = validateProviderHeaders([header("User-Agent"), header("user-agent", "CUSTOM_UA", "env")], "zh");
assert.equal(result.valid, false);
assert.ok(result.errors.every((error) => error.name.includes("重复")));
});
test("header names follow HTTP token syntax", () => {
for (const name of ["", "bad name", "bad:name", "x\r\ninjected", "中文", "x\u007f"]) {
assert.equal(validateProviderHeaders([header(name)]).valid, false, name);
}
assert.equal(validateProviderHeaders([header("!#$%&'*+-.^_`|~09AZaz")]).valid, true);
});
test("values reject CRLF and other control characters without exposing secrets in errors", () => {
for (const value of ["secret\r\nInjected: yes", "secret\n", "secret\u0000", "secret\u000b", "secret\u007f"]) {
const result = validateProviderHeaders([header("X-Test", value)]);
assert.equal(result.valid, false);
assert.equal(JSON.stringify(result.errors).includes("secret"), false);
}
assert.equal(validateProviderHeaders([header("X-Test", ""), header("X-Other", "text\t中文")]).valid, true);
});
test("environment sources store names, rejecting pasted values and invalid identifiers", () => {
for (const value of ["", "9PROJECT", "PROJECT KEY", "PROJECT=secret", "secret\r\n", " key "]) {
assert.equal(validateProviderHeaders([header("X-Project", value, "env")]).valid, false);
}
assert.equal(validateProviderHeaders([header("X-Project", "_PROJECT_9", "env")]).valid, true);
});
test("incomplete drafts and unsupported source types cannot be silently saved", () => {
assert.equal(validateProviderHeaders([createProviderHeader()]).valid, false);
assert.equal(validateProviderHeaders([header("X-Test", "value", "unsupported")]).valid, false);
assert.throws(() => normalizeProviderHeaders([createProviderHeader()]), /Invalid provider headers/);
assert.deepEqual(normalizeProviderHeaders([]), []);
});
test("row editing and removal preserve other rows without mutating the input", () => {
const original = [header("X-Title"), header("X-Project", "PROJECT", "env")];
const changed = updateProviderHeader(original, 0, { name: "User-Agent", value: "Agent" });
assert.deepEqual(changed[0], header("User-Agent", "Agent"));
assert.equal(changed[1], original[1]);
assert.equal(original[0].name, "X-Title");
assert.deepEqual(removeProviderHeader(changed, 0), [original[1]]);
assert.deepEqual(createProviderHeader("env"), header("", "", "env"));
});
@@ -0,0 +1,152 @@
import assert from "node:assert/strict";
import test from "node:test";
import { createProviderHeadersControl } from "../src/providerHeadersControl.ts";
import { normalizeProviderHeaders, validateProviderHeaders } from "../src/providerHeaders.ts";
const row = (name = "X-Title", value = "Fixture", source = "static") => ({ name, value, source });
function deferred() {
let resolve, reject;
const promise = new Promise((accept, fail) => { resolve = accept; reject = fail; });
return { promise, resolve, reject };
}
function fixture(text = "source-a") {
let currentText = text;
const reads = [], writes = [], events = [], published = [];
const control = createProviderHeadersControl({
read(configText) { const task = deferred(); reads.push({ configText, ...task }); return task.promise; },
update(configText, headers) { const task = deferred(); writes.push({ configText, headers, ...task }); return task.promise; },
getConfigText: () => currentText,
isValid: (rows) => validateProviderHeaders(rows).valid,
normalize: normalizeProviderHeaders,
onRowsChange: (rows) => events.push({ rows }),
onConfigChange: (configText) => published.push(configText),
onStateChange: (state) => events.push({ state }),
});
return { control, reads, writes, events, published, setText(text) { currentText = text; }, latestState() { return events.findLast((event) => event.state)?.state; } };
}
test("read requests never replace rows from a newer source or after the source changed before its effect", async () => {
const f = fixture();
const first = f.control.load("source-a");
f.setText("source-b");
f.reads[0].resolve([row("Old", "old")]);
await first;
assert.equal(f.events.some((event) => event.rows), false);
const second = f.control.load("source-b");
f.reads[1].resolve([row("New", "new")]);
await second;
assert.deepEqual(f.events.filter((event) => event.rows).at(-1).rows, [row("New", "new")]);
assert.equal(f.latestState().valid, true);
});
test("invalid rows stay editable and prevent saving without starting IPC updates", async () => {
const f = fixture();
const loading = f.control.load("source-a");
await f.control.changeRows([row("", "")]);
f.reads[0].resolve([row("Stale")]);
await loading;
assert.equal(f.writes.length, 0);
assert.deepEqual(f.events.filter((event) => event.rows).at(-1).rows, [row("", "")]);
assert.deepEqual(f.latestState(), { busy: false, reading: false, valid: false, error: null });
});
test("rapid valid edits accept only the latest write and normalize names without trimming values", async () => {
const f = fixture();
const first = f.control.changeRows([row(" X-Title ", "first")]);
const second = f.control.changeRows([row(" X-Title ", " last ")]);
assert.deepEqual(f.writes[1].headers, [row("X-Title", " last ")]);
f.writes[1].resolve("patched-last");
await second;
f.writes[0].resolve("patched-first");
await first;
assert.deepEqual(f.published, ["patched-last"]);
assert.equal(f.latestState().busy, false);
});
test("a new TOML source rebases edited headers and cannot be overwritten by an old response", async () => {
const f = fixture();
const first = f.control.changeRows([row("X-Title", "edited")]);
f.setText("source-b-with-new-model");
const rebased = f.control.load("source-b-with-new-model");
assert.equal(f.writes[1].configText, "source-b-with-new-model");
f.writes[0].resolve("old-source-result");
await first;
assert.deepEqual(f.published, []);
f.writes[1].resolve("new-source-with-edited-headers");
await rebased;
assert.deepEqual(f.published, ["new-source-with-edited-headers"]);
});
test("a local invalid draft survives an unrelated TOML change", async () => {
const f = fixture();
await f.control.changeRows([row("invalid name", "keep-editing")]);
f.setText("changed-model");
await f.control.load("changed-model");
assert.equal(f.reads.length, 0);
assert.equal(f.writes.length, 0);
assert.equal(f.latestState().valid, false);
assert.deepEqual(f.events.filter((event) => event.rows).at(-1).rows, [row("invalid name", "keep-editing")]);
});
test("the parent echo of a successful patch does not reread or erase local drafts", async () => {
const f = fixture();
const writing = f.control.changeRows([row()]);
f.writes[0].resolve("patched-a");
await writing;
f.setText("patched-a");
await f.control.load("patched-a");
assert.equal(f.reads.length, 0);
assert.equal(f.writes.length, 1);
assert.equal(f.latestState().valid, true);
});
test("editing before an earlier patch is echoed rebases the latest edit against that patch", async () => {
const f = fixture();
const first = f.control.changeRows([row("X-Title", "first")]);
f.writes[0].resolve("patched-a");
await first;
const second = f.control.changeRows([row("X-Title", "second")]);
f.setText("patched-a");
const rebase = f.control.load("patched-a");
f.writes[1].resolve("stale-second");
await second;
f.writes[2].resolve("patched-second");
await rebase;
assert.equal(f.writes[2].configText, "patched-a");
assert.deepEqual(f.published, ["patched-a", "patched-second"]);
});
test("unmount invalidates pending reads and writes without emitting events", async () => {
for (const operation of ["read", "write"]) {
const f = fixture();
const task = operation === "read" ? f.control.load("source-a") : f.control.changeRows([row()]);
const count = f.events.length;
f.control.dispose();
if (operation === "read") f.reads[0].resolve([row("Stale")]);
else f.writes[0].resolve("stale-result");
await task;
assert.equal(f.events.length, count);
assert.deepEqual(f.published, []);
}
});
test("IPC failures expose only a generic operation marker and can be retried", async () => {
const f = fixture();
const loading = f.control.load("source-a");
f.reads[0].reject(new Error("header-secret\nresolved-env-secret"));
await loading;
assert.equal(f.latestState().error, "read");
const retry = f.control.retry();
f.reads[1].resolve([row()]);
await retry;
const writing = f.control.changeRows([row("X-Title", "changed")]);
f.writes[0].reject(new Error("header-secret\nresolved-env-secret"));
await writing;
assert.equal(f.latestState().error, "write");
assert.equal(JSON.stringify(f.events).includes("header-secret"), false);
const writeRetry = f.control.retry();
f.writes[1].resolve("retry-success");
await writeRetry;
assert.deepEqual(f.published, ["retry-success"]);
assert.equal(f.latestState().valid, true);
});
@@ -0,0 +1,28 @@
import assert from "node:assert/strict";
import test from "node:test";
import { providerUpstreamApi, providerRequiresConversion } from "../src/providerProtocol.ts";
test("all upstream choices are retained independently of the native wire API", () => {
for (const upstreamApi of ["responses", "chat_completions", "anthropic_messages", "gemini"]) {
assert.equal(providerUpstreamApi({ upstreamApi, wireApi: "responses" }), upstreamApi);
assert.equal(providerRequiresConversion({ upstreamApi, wireApi: "responses" }), upstreamApi !== "responses");
}
});
test("legacy chat and protocol aliases remain editable", () => {
assert.equal(providerUpstreamApi({ wireApi: "chat" }), "chat_completions");
assert.equal(providerUpstreamApi({ wireApi: "chat_completions" }), "chat_completions");
assert.equal(providerUpstreamApi({ upstreamApi: "openai_chat" }), "chat_completions");
assert.equal(providerUpstreamApi({ upstreamApi: "anthropic" }), "anthropic_messages");
assert.equal(providerUpstreamApi({ upstreamApi: "gemini_native" }), "gemini");
});
test("an explicit native selection clears a legacy chat choice", () => {
assert.equal(providerUpstreamApi({ wireApi: "chat", upstreamApi: "responses" }), "responses");
assert.equal(providerRequiresConversion({ wireApi: "responses", upstreamApi: null }), false);
});
test("unknown metadata is retained so saving cannot silently switch protocols", () => {
assert.equal(providerUpstreamApi({ upstreamApi: "unsupported", wireApi: "responses" }), "unsupported");
assert.equal(providerUpstreamApi({ wireApi: "unknown_native" }), "unknown_native");
});
@@ -0,0 +1,132 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
createSessionStatusTracker,
providerActivationIsBusy,
readCurrentSessionStatus,
sessionStatusContextKey,
} from "../src/sessionOperationState.ts";
const context = (targetProvider = "custom", providerRevision = 0, configDir = "/fixture/codex") => ({ configDir, targetProvider, providerRevision });
const deferred = () => {
let resolve, reject;
const promise = new Promise((accept, fail) => { resolve = accept; reject = fail; });
return { promise, resolve, reject };
};
test("session sync permits activation while general operations and other actions keep their locks", () => {
assert.equal(providerActivationIsBusy(["sessionSync"], ["syncSessions"]), false);
assert.equal(providerActivationIsBusy(["sessionSync", "sessionSync"], ["syncSessions", "syncSessions"]), false);
assert.equal(providerActivationIsBusy(["sessionSync", "general"], ["syncSessions"]), true);
assert.equal(providerActivationIsBusy(["general"], []), true);
assert.equal(providerActivationIsBusy([], ["checkSessions"]), true);
assert.equal(providerActivationIsBusy([], []), false);
// A newer sync token must not hide an older unrelated operation.
assert.equal(providerActivationIsBusy(["sessionSync"], ["importCcSwitch", "syncSessions"]), true);
});
test("captured targets cannot change when the current context is mutated", () => {
const tracker = createSessionStatusTracker();
const source = context("openai");
const request = tracker.begin(source);
source.targetProvider = "custom";
assert.equal(request.context.targetProvider, "openai");
assert.equal(Object.isFrozen(request.context), true);
assert.equal(tracker.isCurrent(request, source), false);
});
test("an old status cannot overwrite a newly activated provider", async () => {
const tracker = createSessionStatusTracker();
let current = context("openai");
const old = deferred();
const published = [];
const oldRead = readCurrentSessionStatus(tracker, () => current, () => old.promise, (status) => published.push(status));
current = null; // Activation has begun but the new live config is not ready.
tracker.invalidate();
old.resolve({ targetProvider: "openai", needsSync: false });
assert.equal(await oldRead, null);
current = context("custom", 1);
await readCurrentSessionStatus(tracker, () => current, async () => ({ targetProvider: "custom", needsSync: true }), (status) => published.push(status));
assert.deepEqual(published, [{ targetProvider: "custom", needsSync: true }]);
});
test("switching between providers sharing the custom key still invalidates old replies", async () => {
const tracker = createSessionStatusTracker();
let current = context("custom", 10);
const old = deferred();
const published = [];
const pending = readCurrentSessionStatus(tracker, () => current, () => old.promise, (status) => published.push(status));
current = context("custom", 11);
old.resolve({ targetProvider: "custom", needsSync: false });
assert.equal(await pending, null);
assert.deepEqual(published, []);
});
test("completion reads the current provider instead of publishing the completed job's old status", async () => {
const tracker = createSessionStatusTracker();
let current = context("openai");
const capturedTarget = { ...current };
const job = deferred();
const reads = [], published = [];
const completion = job.promise.then(() => readCurrentSessionStatus(tracker, () => current, async (scope) => {
reads.push(scope);
return { targetProvider: scope.targetProvider, needsSync: true };
}, (status) => published.push(status)));
current = context("custom", 1);
job.resolve({ status: { targetProvider: "openai", needsSync: false } });
await completion;
assert.equal(capturedTarget.targetProvider, "openai");
assert.equal(reads[0].targetProvider, "custom");
assert.deepEqual(published, [{ targetProvider: "custom", needsSync: true }]);
});
test("late responses from a different Codex directory are ignored", async () => {
const tracker = createSessionStatusTracker();
let current = context("custom", 0, "/fixture/old");
const task = deferred();
let applied = false;
const read = readCurrentSessionStatus(tracker, () => current, () => task.promise, () => { applied = true; });
current = context("custom", 0, "/fixture/new");
task.resolve({ targetProvider: "custom" });
assert.equal(await read, null);
assert.equal(applied, false);
});
test("the newest status request wins when reads finish out of order", async () => {
const tracker = createSessionStatusTracker();
const current = context();
const old = deferred(), fresh = deferred();
const published = [];
const a = readCurrentSessionStatus(tracker, () => current, () => old.promise, (status) => published.push(status));
const b = readCurrentSessionStatus(tracker, () => current, () => fresh.promise, (status) => published.push(status));
fresh.resolve({ targetProvider: "custom", needsSync: true });
await b;
old.resolve({ targetProvider: "custom", needsSync: false });
assert.equal(await a, null);
assert.deepEqual(published, [{ targetProvider: "custom", needsSync: true }]);
});
test("late failures are ignored and a current failure remains visible", async () => {
const tracker = createSessionStatusTracker();
let current = context();
const task = deferred();
const old = readCurrentSessionStatus(tracker, () => current, () => task.promise, () => assert.fail("stale read applied"));
current = context("openai", 1);
task.reject(new Error("old provider read failed"));
assert.equal(await old, null);
await assert.rejects(readCurrentSessionStatus(tracker, () => current, async () => { throw new Error("current read failed"); }, () => {}), /current read failed/);
});
test("provider mismatches and suspended contexts never publish a misleading synced status", async () => {
const tracker = createSessionStatusTracker();
let reads = 0, applied = false;
assert.equal(await readCurrentSessionStatus(tracker, () => null, async () => { reads += 1; return { targetProvider: "old" }; }, () => { applied = true; }), null);
assert.equal(reads, 0);
assert.equal(await readCurrentSessionStatus(tracker, () => context("custom"), async () => ({ targetProvider: "openai", needsSync: false }), () => { applied = true; }), null);
assert.equal(applied, false);
});
test("context keys distinguish target, directory and activation generation", () => {
const variants = [context(), context("openai"), context("custom", 1), context("custom", 0, "/fixture/other")];
assert.equal(new Set(variants.map(sessionStatusContextKey)).size, variants.length);
});
@@ -0,0 +1,113 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import vm from "node:vm";
const source = readFileSync(new URL("./fixtures/ui-runtime.js", import.meta.url), "utf8");
const plain = (value) => JSON.parse(JSON.stringify(value));
function memoryStorage() {
const values = new Map();
return { getItem: (key) => values.get(key) ?? null, setItem: (key, value) => values.set(key, String(value)), removeItem: (key) => values.delete(key) };
}
function loadFixture() {
class Element {
constructor(tag) { this.tagName = tag; this.style = {}; this.children = []; this.listeners = new Map(); this.attributes = new Map(); }
append(...children) { this.children.push(...children); }
setAttribute(name, value) { this.attributes.set(name, value); }
addEventListener(name, callback) { this.listeners.set(name, callback); }
click() { this.listeners.get("click")?.({ target: this }); }
}
const ready = [];
const body = new Element("body");
const sandbox = {
structuredClone, URL, URLSearchParams,
location: { search: "", reload() { assert.fail("fixture language commands must not reload the browser"); } },
localStorage: memoryStorage(), sessionStorage: memoryStorage(),
document: { body, createElement: (tag) => new Element(tag), addEventListener(name, callback) { assert.equal(name, "DOMContentLoaded"); ready.push(callback); } },
};
sandbox.window = sandbox;
vm.runInNewContext(source, sandbox, { timeout: 1000 });
const invoke = async (command, args) => plain(await sandbox.__TAURI_INTERNALS__.invoke(command, args));
const get = () => invoke("get_codex_language_status", { configDir: "/fixture/codex" });
const save = (enabled) => invoke("save_codex_language_preferences", { configDir: "/fixture/codex", locale: enabled ? "zh-CN" : "auto", enabled });
const apply = () => invoke("apply_codex_language_preferences", { configDir: "/fixture/codex", restore: false });
return { sandbox, body, get, save, apply, invoke, controls: sandbox.__CODEX_X_FIXTURE__, mount() { for (const callback of ready) callback(); } };
}
test("language fixture starts in Chinese and save stages or cancels without changing actual state", async () => {
const f = loadFixture();
assert.deepEqual(await f.get(), { locale: "zh-CN", enabled: true, pendingEnabled: null, supported: true, appName: "ChatGPT", appVersion: "fixture", phase: "active", message: "", readyPages: 0, restoreAvailable: false });
const staged = await f.save(false);
assert.equal(staged.enabled, true);
assert.equal(staged.locale, "zh-CN");
assert.equal(staged.pendingEnabled, false);
assert.equal((await f.get()).pendingEnabled, false);
assert.equal((await f.save(true)).pendingEnabled, null, "choosing the actual state cancels the pending change");
});
test("language apply changes only the memory state and clears pending intent", async () => {
const f = loadFixture();
await f.save(false);
assert.deepEqual(await f.apply(), { locale: "auto", enabled: false, pendingEnabled: null, supported: true, appName: "ChatGPT", appVersion: "fixture", phase: "inactive", message: "", readyPages: 0, restoreAvailable: false });
assert.equal((await f.apply()).enabled, false, "applying without a new choice keeps the actual state");
await f.save(true);
assert.equal((await f.apply()).enabled, true);
await f.save(false); await f.apply();
assert.equal((await loadFixture().get()).enabled, true, "language state is not persisted outside this fixture instance");
});
test("save and apply failures preserve state and normal mode permits retry", async () => {
const f = loadFixture();
await f.save(false);
const original = await f.get();
f.controls.setCodexLanguageMode("save-error");
await assert.rejects(f.save(true), /保存失败/);
assert.deepEqual(await f.get(), original);
f.controls.setCodexLanguageMode("apply-error");
await assert.rejects(f.apply(), /应用失败/);
assert.deepEqual(await f.get(), original);
f.controls.setCodexLanguageMode("normal");
const result = await f.apply();
assert.equal(result.enabled, false);
assert.equal(result.pendingEnabled, null);
assert.equal(f.controls.snapshot().codexLanguageMode, "normal");
});
test("external state controls are visible and change the next status response", async () => {
const f = loadFixture();
f.mount();
const elements = [];
const visit = (node) => { if (!node || typeof node !== "object") return; elements.push(node); for (const child of node.children ?? []) visit(child); };
visit(f.body);
const button = (label) => {
const found = elements.find((node) => node.tagName === "button" && node.textContent === label);
assert.ok(found, `missing visible control: ${label}`);
return found;
};
button("Fixture:语言外部改为自动").click();
assert.equal((await f.get()).locale, "auto");
await f.save(true);
button("Fixture:语言外部改为中文").click();
assert.equal((await f.get()).enabled, true);
assert.equal((await f.get()).pendingEnabled, null, "external replacement invalidates an old pending choice");
button("Fixture:语言保存失败").click();
await assert.rejects(f.save(false), /保存失败/);
button("Fixture:语言应用失败").click();
await assert.rejects(f.apply(), /应用失败/);
button("Fixture:语言恢复正常").click();
assert.equal((await f.save(false)).pendingEnabled, false);
assert.equal((await f.apply()).locale, "auto");
});
test("invalid language arguments reject without mutating actual or pending state", async () => {
const f = loadFixture();
const original = await f.get();
for (const args of [{ locale: "en-US", enabled: true }, { locale: "auto", enabled: true }, { locale: "zh-CN", enabled: "true" }]) {
await assert.rejects(f.invoke("save_codex_language_preferences", args), /参数无效/);
assert.deepEqual(await f.get(), original);
}
await assert.rejects(f.invoke("apply_codex_language_preferences", { restore: true }), /没有可恢复/);
assert.deepEqual(await f.get(), original);
});
@@ -0,0 +1,59 @@
import assert from "node:assert/strict";
import test from "node:test";
import { AppUpdaterController } from "../src/appUpdaterController.ts";
import { releaseInfoFromFallback, releaseInfoFromCheckFailure } from "../src/updateCheckFlow.ts";
const metadata = {
latestVersion: "v0.3.24",
htmlUrl: "https://github.com/yynxxxxx/Codex-X/releases/tag/v0.3.24",
hasUpdate: true,
};
test("an installed 0.3.21 edition keeps native retry after a failed channel check and a newer release lookup", async () => {
let recovery = false;
let installs = 0;
const update = { rid: 12, currentVersion: "0.3.21", version: "0.3.24", close: async () => {} };
const controller = new AppUpdaterController({
check: async () => {
if (!recovery) throw new Error("request timed out");
return update;
},
install: async (checked) => {
assert.equal(checked, update);
installs++;
return { restartRequired: true };
},
restart: async () => {},
setTimer: () => 1,
clearTimer: () => {},
});
assert.equal(await controller.check(), "error");
const release = releaseInfoFromFallback(metadata, true);
assert.equal(release.updateMethod, "native", "a failed check must not turn an installed edition into download-only");
assert.equal(release.hasUpdate, true);
assert.equal(release.latestVersion, "v0.3.24");
assert.equal(controller.getSnapshot().failure, "check");
assert.equal(await controller.downloadAndInstall(), "error");
assert.equal(installs, 0, "release metadata is not a checked installer resource");
recovery = true;
assert.equal(await controller.retry(), "available");
assert.equal(await controller.downloadAndInstall(), "ready");
assert.equal(installs, 1);
});
test("portable and unsupported editions retain their intentional manual download path", () => {
assert.deepEqual(releaseInfoFromFallback(metadata, false), { status: "ok", ...metadata, updateMethod: "download" });
assert.equal(releaseInfoFromFallback({ ...metadata, hasUpdate: false }, false).updateMethod, undefined);
});
test("a failed native channel never claims up-to-date from fallback metadata alone", () => {
const release = releaseInfoFromFallback({ ...metadata, latestVersion: "v0.3.21", hasUpdate: false }, true);
assert.equal(release.status, "error");
assert.equal(release.updateMethod, "native");
assert.equal(release.hasUpdate, false);
});
test("both checks failing still preserves installed-edition retry instead of a download-only dialog", () => {
assert.deepEqual(releaseInfoFromCheckFailure(true), { status: "error", updateMethod: "native" });
assert.deepEqual(releaseInfoFromCheckFailure(false), { status: "error", updateMethod: undefined });
});
@@ -0,0 +1,153 @@
import assert from "node:assert/strict";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { dirname, join, relative, resolve } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import test from "node:test";
import ts from "typescript";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { INITIAL_APP_UPDATER_STATE, appUpdaterCheckFailureMessage } from "../src/appUpdaterController.ts";
const desktop = dirname(dirname(fileURLToPath(import.meta.url)));
let component;
async function ui() {
if (component) return component;
component = (async () => {
const scratch = await mkdtemp(join(desktop, "tests/.update-dialog-ui-"));
try {
// SSR cannot render a React DOM portal. Adapt only its container transport
// while keeping the real UpdateDialog, ModalShell and Button components.
const portal = join(scratch, "portal.mjs");
await writeFile(portal, "export function createPortal(children) { return children; }\n");
const emitted = new Map();
async function compile(sourcePath) {
if (emitted.has(sourcePath)) return emitted.get(sourcePath);
const outputPath = join(scratch, relative(desktop, sourcePath).replace(/\.tsx?$/, ".mjs"));
emitted.set(sourcePath, outputPath);
let output = ts.transpileModule(await readFile(sourcePath, "utf8"), {
fileName: sourcePath,
compilerOptions: { target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.ESNext, jsx: ts.JsxEmit.ReactJSX },
}).outputText.replace(/import\s*["'][^"']+\.css["'];?/g, "");
for (const match of [...output.matchAll(/\bfrom\s*["'](\.[^"']+)["']/g)]) {
const specifier = match[1];
const base = resolve(dirname(sourcePath), specifier);
let dependency;
for (const candidate of [`${base}.ts`, `${base}.tsx`, join(base, "index.ts")]) {
try { await readFile(candidate, "utf8"); dependency = candidate; break; } catch { /* Normal TypeScript resolution candidates. */ }
}
assert.ok(dependency, `could not resolve ${specifier} from ${sourcePath}`);
let replacement = relative(dirname(outputPath), await compile(dependency)).replaceAll("\\", "/");
if (!replacement.startsWith(".")) replacement = `./${replacement}`;
output = output.replaceAll(`"${specifier}"`, `"${replacement}"`).replaceAll(`'${specifier}'`, `'${replacement}'`);
}
if (sourcePath.endsWith(join("components", "ui", "ModalShell.tsx"))) {
const portalImport = relative(dirname(outputPath), portal).replaceAll("\\", "/");
assert.ok(output.includes('from "react-dom"'), "the only adapted dependency must be ModalShell's portal");
output = output.replace('from "react-dom"', `from "${portalImport}"`);
}
await mkdir(dirname(outputPath), { recursive: true });
await writeFile(outputPath, output);
return outputPath;
}
const path = await compile(join(desktop, "src/components/AppDialogs.tsx"));
return (await import(pathToFileURL(path).href)).UpdateDialog;
} finally { await rm(scratch, { recursive: true, force: true }); }
})();
return component;
}
async function render(props) {
const UpdateDialog = await ui();
const previousDocument = Object.getOwnPropertyDescriptor(globalThis, "document");
// Effects, event handlers and Tauri IPC never run in renderToStaticMarkup.
Object.defineProperty(globalThis, "document", { configurable: true, value: { body: {} } });
try { return renderToStaticMarkup(createElement(UpdateDialog, props)); }
finally {
if (previousDocument) Object.defineProperty(globalThis, "document", previousDocument);
else delete globalThis.document;
}
}
function buttons(html) {
return [...html.matchAll(/<button\b[^>]*>[\s\S]*?<\/button>/g)].map(([button]) => button);
}
const noop = () => {};
const props = (lang) => ({ open: true, lang, currentVersion: "0.3.21", latestVersion: "0.3.24", onClose: noop, onDownload: noop });
for (const lang of ["zh", "en"]) {
const zh = lang === "zh";
test(`native check failure offers online retry as primary and manual download as fallback (${lang})`, async () => {
const state = { ...INITIAL_APP_UPDATER_STATE, phase: "error", failure: "check", checkFailure: "network", errorMessage: appUpdaterCheckFailureMessage("network"), currentVersion: "0.3.21" };
const html = await render({ ...props(lang), state, onRetry: noop, onUpdate: noop });
assert.ok(html.includes('role="dialog"'));
assert.ok(html.includes(zh ? "在线更新检查失败" : "Online update check failed"));
assert.ok(html.includes(appUpdaterCheckFailureMessage("network", lang)));
const retry = buttons(html).find((button) => button.includes(zh ? "重试在线检查" : "Retry online check"));
assert.ok(retry);
assert.ok(retry.includes("ui-button--primary"));
const download = buttons(html).find((button) => button.includes(zh ? "打开下载页(备用)" : "Open download page (fallback)"));
assert.ok(download);
assert.ok(download.includes("ui-button--secondary"));
assert.ok(!html.includes(zh ? "立即更新" : "Update now"), "a callback alone cannot expose installation after a failed check");
assert.ok(!html.includes(zh ? "可前往下载页获取对应平台" : "A new version is available from the download page"));
});
test(`check error details remain fixed safe explanations even for an older error state (${lang})`, async () => {
const state = { ...INITIAL_APP_UPDATER_STATE, phase: "error", failure: "check", checkFailure: undefined, errorMessage: "error at https://private.fixture.test?token=private-secret Authorization: Bearer private-secret" };
const html = await render({ ...props(lang), state, onRetry: noop });
assert.ok(html.includes(appUpdaterCheckFailureMessage("unknown", lang)));
for (const secret of ["private-secret", "private.fixture.test", "Authorization", "Bearer"]) assert.ok(!html.includes(secret));
assert.ok(html.includes('role="alert"'));
});
test(`portable manual-download dialog remains available without native updater state (${lang})`, async () => {
const html = await render(props(lang));
assert.ok(html.includes(zh ? "发现新版本" : "New version available"));
assert.ok(html.includes(zh ? "检测到新版本,可前往下载页" : "A new version is available from the download page"));
const download = buttons(html).find((button) => button.includes(zh ? "打开下载页" : "Open download page"));
assert.ok(download?.includes("ui-button--primary"));
assert.ok(!html.includes(zh ? "重试在线检查" : "Retry online check"));
assert.ok(!html.includes(zh ? "立即更新" : "Update now"));
assert.ok(!html.includes(zh ? "备用" : "fallback"));
assert.ok(html.includes("0.3.21"));
assert.ok(html.includes("0.3.24"));
});
test(`a successfully checked native update still offers installation (${lang})`, async () => {
const state = { ...INITIAL_APP_UPDATER_STATE, phase: "available", currentVersion: "0.3.21", latestVersion: "0.3.24" };
const html = await render({ ...props(lang), state, onUpdate: noop, onRetry: noop });
const install = buttons(html).find((button) => button.includes(zh ? "立即更新" : "Update now"));
assert.ok(install?.includes("ui-button--primary"));
assert.ok(!html.includes(zh ? "在线更新检查失败" : "Online update check failed"));
});
test(`native retry uses its fresh version and cannot remain a stale fallback download dialog (${lang})`, async () => {
const state = { ...INITIAL_APP_UPDATER_STATE, phase: "available", currentVersion: "0.3.21", latestVersion: "0.3.24" };
const html = await render({ ...props(lang), latestVersion: "v0.3.23", state, onUpdate: noop, onRetry: noop });
assert.ok(html.includes("0.3.24"));
assert.ok(!html.includes("0.3.23"));
assert.ok(buttons(html).some((button) => button.includes(zh ? "立即更新" : "Update now")));
});
test(`a native retry reporting no update renders up-to-date without installation or download-only actions (${lang})`, async () => {
const state = { ...INITIAL_APP_UPDATER_STATE, phase: "idle", currentVersion: "0.3.24" };
const html = await render({ ...props(lang), state, onUpdate: noop, onRetry: noop });
assert.ok(html.includes(zh ? "当前已是最新版本" : "Codex-X is up to date"));
assert.ok(!buttons(html).some((button) => button.includes(zh ? "立即更新" : "Update now")));
assert.ok(!buttons(html).some((button) => button.includes(zh ? "打开下载页" : "Open download page")));
});
test(`download, verification, preparation, installation and restart errors keep existing copy (${lang})`, async () => {
for (const failure of ["download", "verify", "prepare", "install", "restart"]) {
const state = { ...INITIAL_APP_UPDATER_STATE, phase: "error", failure, errorMessage: "Fixture installation failure", logPath: "/fixtures/update.log" };
const html = await render({ ...props(lang), state, onRetry: noop, onUpdate: noop });
assert.ok(html.includes(zh ? "更新没有完成" : "Update did not finish"));
assert.ok(html.includes("Fixture installation failure"));
assert.ok(html.includes("/fixtures/update.log"));
assert.ok(buttons(html).some((button) => button.includes(zh ? "重试" : "Try again")));
assert.ok(buttons(html).some((button) => button.includes(zh ? "打开下载页" : "Open download page")));
assert.ok(!html.includes(zh ? "重试在线检查" : "Retry online check"));
assert.ok(!html.includes(zh ? "(备用)" : "(fallback)"));
if (failure === "restart") assert.ok(html.includes(zh ? "软件未能重新启动" : "Codex-X could not restart"));
}
});
}
+40
View File
@@ -8,6 +8,34 @@
日志不得包含 Token、认证文件内容、用户数据或仅适用于某台电脑的隐私路径。
## 2026-10-09:在线更新主通道故障后的自动恢复
- 用户确认 Windows EXE 安装版 0.3.21 能发现新版,但只提供下载页。代码核对显示原生检查失败后仍从版本元数据服务发现新版,却把安装版更新方式静默改为 download。0.3.21 / 0.3.24 的更新模块无代码差异;公开清单平台、URL、公钥和安装包签名核验通过,Git 邮箱改写没有改变发行资产。用户机器的首通道失败原因未在现场复现,不能只凭提示判断网络、代理或便携标识。
- 改为真正的原生在线恢复:主清单检查失败自动读取官方 GitHub API 的 latest.json 资产,仍由 SDK 检查版本/平台并创建 WebView 所有的资源;下载传输失败自动从同仓库/同 release/同文件的官方 API 资产重取,原 SDK 公钥及签名检查保持,只有验签成功的字节进入 Windows 安装暂存。跨源清空自定义认证头,使用 HTTP/1 和原有系统/显式代理;仅版本 badge 不提供安装依据。
- 主通道和备用通道全部失败时显示安全原因和在线重试,下载页仅作备用;不再将安装版静默降为手动更新,不把失败检查称为最新。重复下载进度重新计算,不重复启动安装器。
- 修正此前本地协议转换的退出/更新限制:保留本地地址和恢复记录,正常退出及更新后重开恢复同一协议;安装期间冻结配置并保持服务,交接失败恢复。安装中的普通 Quit 被延后,Windows 安装器交接后允许授权退出;Mac blocking 任务中断也解除冻结,已安装后的恢复警告不触发第二次安装。
- 761 项 release/串行 Rust、154 项 Node、类型及 renderer 构建通过。真实 SDK 测试模拟 0.3.21,使用严格 HTTPS 本地服务和测试专用公钥:主检查 503 → 官方 API 清单 → SDK check → 主包 503 → API 包 → SDK 验签 → Windows 私有暂存通过;改动包字节被 SDK 拒绝。测试不运行安装器,不改真实配置/认证/会话。公开 0.3.24 EXE 的匿名 API 下载和旧公钥静态验签另行通过。没有实际在用户 Windows 上执行在线安装。
- 修复仍在本地分支,尚未发布。旧 0.3.21 只有编译在程序中的 GitHub 主入口,不能通过修改新源码直接让旧二进制自动新增 API 通道;需要原入口恢复后升级,或一次官方安装引导后获得新通道。后续 Windows runner 打包/原生安装验证与正式发布须完成现有审阅流程。
## 2026-10-08:Headers 预设与填写提示补齐
- 用户指出供应商 Headers 缺少可选择预设,通用 `Codex-X` 值示例容易误导。复核 Issue #53 原文仅要求 Header 设置;CC Switch 的 Codex 界面使用独立 UA 控件及 `meta.customUserAgent`,通用 `X-Title` / `CC Switch` 示例来自 OpenCode / Pi 编辑器。
- 新增用户显式选择的 Claude Code、Kilo Code `User-Agent` 预设;只更新一个 UA 行,优先复用空白草稿,不覆盖其他请求头/凭据/环境变量,重复行继续显示校验错误。不自动配置客户端身份,不生成认证凭据。
- 填写提示按 UA、应用网址、应用名称、认证及其他 Header 区分;占位值不保存或发送。保留通用 Headers 和固定/环境变量设置,直连及路由发送行为保持原有实现。
- 新增 9 项预设逻辑测试、中英文实际组件预设/占位渲染测试;130 项前端测试、类型检查和 renderer 构建通过。本次未修改后端、未请求真实上游。
- macOS release 本机打包、签名/二进制摘要校验及旧 App ZIP 备份通过,已更新 Applications 中的安装。当前窗口存在未保存的供应商编辑,因此保留原进程和草稿;用户结束编辑并重开后使用新预设。构建 App 副本经校验归档,未推送 GitHub。
## 2026-10-08:供应商协议转换、配置定位和 Headers(待本地验收)
- Issue #68:原路由仅透传 Responses;新增独立上游协议元数据及 Chat Completions、Claude Messages、Gemini 原生 JSON/SSE 转换。Codex TOML 始终使用 Responses,DB v8→v9 新增可空协议列,旧记录保留,历史 Chat 配置兼容转换。CC Switch 的显式协议按元数据导入,模型获取与连接检测使用所选协议和供应商 Headers。
- 转换包含图片、函数/命名空间/custom 工具及其结果、结构化输出、推理回放和 Gemini 签名。回归覆盖跨块 UTF-8/CRLF、工具媒体顺序、空 added 初值、单一终止事件及首个输出前后故障转移。Gemini 禁止并行工具时先检查调用数量,违规调用不会交给 Codex 执行。
- 转换供应商需要运行中的路由和配置接管。候选配置提前校验,重接管失败恢复配置、认证、选择和原运行路由;不能恢复成无效的原生直连。关闭路由或退出前需切回 Responses/官方,异常退出后重新启动本地路由。安装更新前也使用只读校验,转换路由阻止安装时明确给出切换建议。
- Issue #67:配置问题展示文件、原始行列、参数和修正建议;缺失参数不伪造行号。当前官方登录与路由证据充分时补齐旧会话缺失的官方别名;先备份,保留 fingerprint、外部写入和认证变动保护,不改会话日志或索引。
- Issue #53:新增固定/环境变量 Headers 编辑与逐行校验,保留其他 TOML 字段及注释。异步读取/写入丢弃过期结果,未完成或无效草稿不能保存。该项独立快照通过 159 项供应商 Rust 测试、16 项 Node 测试和类型检查。
- 全批按既有 CI 的 release + 串行设置运行 744 项 Rust 测试,全部通过;119 项 Node 测试、类型检查、renderer 构建及格式/差异检查通过。并行 debug 全套曾遇测试数据库锁争用,后续验证使用仓库已有串行规则;没有通过修改生产锁策略掩盖测试争用。
- 已生成 macOS arm64 debug 测试包,随后按用户要求以 release 重新打包,校验 ad-hoc 签名及二进制摘要,验证旧安装 ZIP 备份后替换 `/Applications/Codex-X.app` 并启动;原生概览正常加载。构建副本经 ZIP/摘要验证后归档并注销重复注册,保留 Applications 中的安装。版本号暂沿用 0.3.24,未做 Apple 公证或真实上游联网验收。
- 测试使用临时配置/SQLite/会话和本地模拟 HTTP/SSE,不访问真实模型上游,不改真实会话日志;原生供应商的实际网络兼容性仍需用户本地验收。转换范围与明确拒绝的能力见[供应商协议说明](PROVIDER_PROTOCOLS.md)。本批尚未推送、发布或关闭 Issues。
## 2026-09-30:图片输入、模型展示与供应商卡片排序(本地验证完成)
- Issues #63/#65 的图片拦截来自自定义模型目录的 `input_modalities = [text]`。
@@ -662,3 +690,15 @@ Tauri 事件循环随最后一个窗口关闭而结束,后台管理能力也
当前 `b-nnett/codex-plusplus` 源码没有 rollout JSONL/SQLite 分桶同步实现,不能把这部分
描述为对其逐行复刻;`custom` 共享分桶语义来自对 CC Switch 可验证实现和本地 Codex
存储行为的交叉检查。
## 2026-10-16:压缩会话、并发切换与客户端中文兼容(本地测试)
- 本机只读核实:报告的 7 个缺失 `.jsonl` 均有同名 `.jsonl.zst`,活动 SQLite 保留逻辑 `.jsonl` 引用;改标题后重新检查暴露了此兼容缺口。未执行真实会话同步或修改真实聊天日志。
- 逻辑路径优先读取普通文件,不存在时定位同名压缩文件;身份仍以权威引用和 `session_meta.id` 校验,不能按相同 UUID 猜测旧副本。保留数据库逻辑路径。同步以压缩原字节做快照/哈希,流式解压、改写、重压;并发展开或换代必须中止并按所有权回滚。
- 前端仅允许供应商启用穿过 sessionSync 忙碌状态;维护、删除、其它配置操作仍互斥。同步入口固定目录与目标,状态请求按目录、目标及供应商变更代次丢弃旧响应。
- 完整日志解析规划由常见的 8 遍减少为 3 遍;备份、提交前哈希复核和逐记录磁盘暂存仍保留。无跨请求状态缓存。24 文件(12 plain/12 zst)、84,088,210 解压字节、22,026 记录、最大单条 34 MiB 的临时数据,release/arm64 温缓存三次中位数:检查 453 ms,实际同步 2.698 s,同步后检查 451 ms,幂等同步 460 ms。旧版不支持该压缩数据集,不据此宣称对比倍率。
- 中文机制参考 BigPizzaV3/CodexPlusPlus 的行为与本机官方 26.1007.71326 资源,独立实现;没有复制 AGPL 代码。官方客户端使用 `[desktop] localeOverride`,API 模式下翻译还受 i18n Layer 控制。兼容模式仅针对界面翻译,保持官方安装文件与签名;经用户确认后以随机本机 CDP 连接受验证的官方进程。当前实现限 macOS,首次实际应用与中文效果由维护者手动验证;mock/静态检查不等于真实客户端验证。
- 语言保存仅存 Codex-X 偏好。应用/恢复需显式确认重启;保持 Codex-X 运行以支持新窗口。状态读取不会启动、连接或修改官方客户端。会话维护锁阻止同步期间由语言操作重启客户端。
- Issue 审查:无开放 PR;#53/#68 按已发布 v0.3.26 完成功能回复并关闭;#67/#56/#49 保留复测;#70 组合提示词与 #48 统一出口代理保留建议;#26 本地新增标准单文件认证导入,批量及其它封装待样本;#66 因没有可复现的加载故障、无法按描述保证模型行为,按未计划处理回复关闭。本轮应用代码未推送或发布。
- 本地最终检查:Rust release 全套 796 通过;唯一默认忽略项为手动性能基准,已单独执行三次并通过。Node 190 通过(含两个本机 SDK 静态片段测试),TypeScript 类型检查与 renderer 生产构建通过。真实官方客户端的 CDP 连接和视觉中文效果未在本任务中运行。
- 本机交付:已构建并用本地 ad-hoc 签名校验 `0.3.27-local.1`,替换 `/Applications/Codex-X.app` 并启动。原 v0.3.26 备份于 `/Users/sky/.codex/app-backups/Codex-X/20261016-011622/Codex-X-before-sync-locale.zip`。未点击实际语言应用或对真实会话执行同步;交维护者手动验证。
+57
View File
@@ -0,0 +1,57 @@
# 供应商协议与 Headers
## 选择上游协议
在「供应商 → 新增 / 编辑」选择上游实际提供的协议:
| 上游接口协议 | 上游请求 | 默认认证 | 需要本地路由 |
| --- | --- | --- | --- |
| OpenAI Responses | `/v1/responses` | Bearer API Key | 否 |
| OpenAI Chat Completions | `/v1/chat/completions` | Bearer API Key | 是 |
| Claude Messages | `/v1/messages` | `x-api-key`、`anthropic-version` | 是 |
| Gemini generateContent | `/v1beta/models/{model}:generateContent` 或 `:streamGenerateContent` | `x-goog-api-key` | 是 |
Base URL 可以包含服务的路径前缀。Gemini 地址已有 `/v1` 或 `/v1beta` 时使用该版本,不重复添加。
模型名称必须是该供应商支持的名称;获取模型列表和连接检测也使用所选协议及 Headers。
Chat、Claude、Gemini 供应商可以先保存,再到「设置 → 路由与故障转移」开启路由总开关和 Codex 请求接管,随后启用供应商。
Codex 始终使用 Responses,本地路由负责转换请求及普通 / 流式响应。自动切换是独立选项,不是使用协议转换的前提。
协议转换期间保持 Codex-X 运行。关闭路由或取消接管前,请先切回 Responses 供应商或官方账号。退出期间 Codex 请求会暂停,重开 Codex-X 后自动恢复本地转换路由。在线更新会保留转换协议和恢复记录,安装后重开恢复;无需为了更新强制切换供应商。
应用不会将 Claude / Gemini 原生地址恢复成不能使用的 Responses 直连地址;异常退出后会按保存的配置重新启动路由。
端口被占用或配置损坏时会明确提示,需要修复路由或切换供应商。
上游协议保存在 Codex-X 的供应商记录中;生成的 Codex TOML 使用 `wire_api = "responses"`。
旧的 Chat 配置会识别为 Chat Completions 转换,复制供应商和再次导入保留协议选择。
## 转换范围
- 转换文字、图片、函数工具、命名空间工具及 custom 工具(包括 `apply_patch`)的输入输出。
- 支持 JSON 与 SSE 响应、工具参数增量、用量及结束状态;已向 Codex 输出内容后不会重放到其他供应商。
- Claude 的思考预算受 `max_output_tokens` 和上游模型能力约束。Gemini 3 使用相应模型支持的 `thinkingLevel`;其他 Gemini 模型的非 `none` 强度使用上游动态思考预算,强度不是与 OpenAI 一一对应的保证。
- Gemini 思考签名跟随对应模型消息回放;不能把其他协议的加密推理状态当成 Gemini 签名。
- 不支持的参数、媒体形式或上游返回内容会报告具体兼容问题,不会静默丢弃后显示成功。Gemini 不接受无法原生保证的 `strict = true` 工具声明;普通 Codex 内置 shell 工具使用 `strict = false`。
- Claude / Gemini 原生图片输入支持 `detail = auto`,不接受无法对应的 `high` / `low` 图像精度参数。本地 base64 图片直接转换;远程文件 URI 由上游检验,路由不会擅自下载文件。
- Claude 未指定输出上限时使用 8192 tokens。Gemini 禁止并行工具的请求会在本地检查;上游违规返回多个调用时明确报错,不会执行多个或丢弃其中一个。
转换协议不提供 Responses 的服务端会话状态、后台任务、托管工具或 `/compact` 接口。
带 `previous_response_id`、不兼容的加密状态等请求需要完整对话、新建会话或使用原生 Responses 供应商。
上游仍可能拒绝不支持的模型、工具或采样组合;选择协议不会增加模型本身的能力。
## 编辑 Headers
在供应商表单中添加固定值或环境变量来源的 Header。
`User-Agent` 用于客户端标识,可手动填写或明确选择 Claude Code / Kilo Code 预设。预设只添加或更新一个 `User-Agent` 固定值,其他请求头保留;不选预设就保持现有设置。预设值来自本次核对的 CC Switch 配置,不保证每家供应商均接受,也不会填入任何 API Key。
填写示例随名称变化:`HTTP-Referer` 填应用网址,`X-Title` / `X-OpenRouter-Title` 填应用名称,认证头按供应商文档填写。`X-Title: Codex-X` 表示应用名称,是合法的可选标识;它不承担 User-Agent 客户端校验的作用。占位提示不会作为实际值保存或发送。
CC Switch 的 Codex 页面将 UA 保存在 `meta.customUserAgent`,日常转发通过本地路由生效;其通用 Headers 键值编辑器主要用于 OpenCode / Pi。Codex-X 将这些字段保存到 Codex 原生 `http_headers` / `env_http_headers`:直连由 Codex 发送,路由模式由 Codex-X 发送。
同一个名称不能重复(忽略大小写),字段错误直接显示在对应行。固定值保留原有空格。
环境变量模式仅保存变量名:直连时由 Codex 读取,经过路由时由 Codex-X 读取,请在启动应用前设置变量。
直连使用 `Authorization` Header 认证时请留空 API Key;显式 API Key 会替换旧的 Authorization。
本地路由使用当前上游供应商自己的认证和 Headers,供应商的显式认证 Header 优先于默认认证。
本地路由不允许自定义 Host、Cookie、连接控制头或内部路由认证头,不会把 Codex 的本地路由令牌发送给上游。
Headers 保存在已有的 TOML `http_headers` / `env_http_headers` 字段;编辑会保留其他 TOML 字段及注释。
+6 -5
View File
@@ -2,7 +2,7 @@
本说明记录 Codex-X 本轮路由实现与 CC Switch 的对应关系,供维护者检查行为和后续回归使用。
入口为「设置 → 路由与故障转移」。本轮对齐 Codex 的监听、接管、优先队列、请求重试、熔断和
原生官方账号路由;不等于移植 CC Switch 的全部应用适配器和请求转换功能。
原生官方账号路由。新增 Chat Completions、Claude Messages 与 Gemini 上游转换见[供应商协议说明](PROVIDER_PROTOCOLS.md)。
参考版本固定为 CC Switch 提交
[`06082e189d65e6d6dbadc35dacdac1ce6c79d89a`](https://github.com/farion1231/cc-switch/tree/06082e189d65e6d6dbadc35dacdac1ce6c79d89a)
@@ -19,7 +19,7 @@
| `autoFailoverEnabled` | `false` | 对第三方 API 请求使用完整优先队列;关闭时只使用当前供应商。 |
- 首次开启自动故障转移要求服务与接管均已开启。保存设置、让开关从关变为开时立即启用队列 P1。
- 关闭接管会先恢复直连,监听服务可以继续运行。关闭路由总开关会恢复直连并关闭接管,
- 原生 Responses 供应商关闭接管会先恢复直连,监听服务可以继续运行。关闭路由总开关会恢复直连并关闭接管,
但保留自动故障转移偏好、队列和参数。
- 官方登录使用独立的原生官方路由,自动队列暂不参与;这不要求删除原有第三方队列。
- 手动切换第三方供应商、编辑当前配置、切换官方账号时,完整原操作包在
@@ -176,10 +176,11 @@ HTTP 400–599 中,以下状态不进入候补重试:`400/405/406/413/414/41
## 适用边界与实现差异
- 当前数据面提供 `POST /v1/responses`、`POST /v1/responses/compact`、`GET /v1/models`,使用 HTTP/SSE,
- 当前数据面提供 `POST /v1/responses`、`GET /v1/models`;原生 Responses 上游另支持 `POST /v1/responses/compact`。使用 HTTP/SSE,
不提供 WebSocket 升级或任意 URL 转发。
- 第三方接口需兼容 Responses。没有 Chat Completions/Anthropic 协议转换、请求整流器、图片降级、
Claude/Gemini/Grok 应用接管或跨应用配置管理;不能把这些上游能力写成本项目已具备。
- 原生 Responses 直接转发,Chat Completions/Claude Messages/Gemini 原生接口通过本地路由转换。
转换接口不支持 Responses 的服务端状态与 `/compact`;具体范围见[供应商协议说明](PROVIDER_PROTOCOLS.md)。
不提供 Claude/Gemini/Grok 应用接管或跨应用配置管理。
- 队列不限制模型名称,但不保证任意第三方都支持请求中的模型、工具或服务端状态。
厂商专用 `query_params` 目前不支持自动路由;无效认证、缺失环境变量或不适用的认证头会报告原因。
- 本地监听即使绑定非回环地址,也保留随机令牌、Host 和来源检查。不是无需认证的公开代理。
+14 -4
View File
@@ -4,12 +4,14 @@ Windows 新安装包使用 NSIS EXE,安装到原登录用户的本地应用目
## 更新交接
- 插件 `check` 返回的 `Update` 资源仍负责下载与签名验证。自定义 `install_app_update` 只接受本 WebView 的资源 ID,不能指定任意安装路径或未验签字节。
- 下载使用独立的 10 分钟总超时,不再继承版本检查的 15 秒超时。前端显示下载、验签、准备退出、启动安装、已交给安装器;30 秒无进展提供提示,但不并发重试或强杀安装器。
- Windows 先把已验签 EXE 写入本次私有临时目录,再恢复接管配置和停止本地监听。准备失败不启动安装;启动失败恢复保存的路由,恢复失败保留偏好并如实提示。
- `check_online_app_update` 通过原生 SDK 创建更新资源,保留原有版本、平台、公钥、TLS 和签名检查。`install_app_update` 只接受本 WebView 管理的 SDK 资源,不能指定任意安装路径或未验签字节。
- 主更新检查失败时自动通过本仓库官方 GitHub API 的 `latest.json` 资产端点继续 SDK 检查;使用 HTTP/1 请求及原有系统/显式代理。备用 API 返回的是完整更新清单,不是仅含版本号的 badge。
- 主安装包下载出现传输失败时,自动查找同仓库、同 release、同文件的官方 API 资产地址重新下载;备用下载仍由原 SDK 验签,签名失败不会启动安装。跨源不携带自定义认证头。
- 下载使用独立的 10 分钟总超时,不再继承版本检查的 30 秒超时。前端显示下载、验签、准备退出、启动安装、已交给安装器;30 秒无进展提供提示,但不并发重试或强杀安装器。
- Windows 先把已验签 EXE 写入本次私有临时目录,再完成路由交接并停止本地监听。原生 Responses 恢复直连;转换协议保留本地地址及恢复记录,安装后新进程恢复同一协议。准备失败不启动安装;启动失败恢复保存的路由,恢复失败保留偏好并如实提示。
- 启动安装器使用原生 `Command` 参数,随后通过正常 Tauri 退出事件释放窗口、托盘和单实例锁。安装器通过 `/CODEXXPID` 句柄等待旧进程退出;30 秒未退出则停止本次安装,不杀进程、不复制新文件。
- “已交给安装器”只表示成功启动,不等于更新已完成。后续 IPC 断开不能触发第二个安装进程。
- macOS/Linux 继续使用插件原有安装逻辑,安装成功后才进入等待重启状态。
- macOS/Linux 继续使用插件原有安装逻辑,安装期间冻结配置变更但保留监听,失败恢复原路由;安装成功后解除冻结,随后重启时恢复转换协议。
## 兼容已发布的 MSI
@@ -29,6 +31,14 @@ Windows 新安装包使用 NSIS EXE,安装到原登录用户的本地应用目
官网本地下载选择器已支持优先 EXE、回退旧 MSI;官网是独立部署,软件正式发布前须同步该兼容修改。便携版仍使用手动更新。
## 0.3.21 安装版只显示下载页的排查
已发布 0.3.21 的 Windows 安装包已是 NSIS EXE。其原生更新检查失败后会继续用 Shields / GitHub Release API 查版本,却将 `updateMethod` 改为 `download`,从而隐藏原生失败原因和在线安装入口。本轮改为先自动恢复原生通道;全部通道均失败才显示原因及在线重试,下载页只是备用。
0.3.21 / 0.3.24 公钥及更新器版本相同,当前公开 `latest.json` 的三个 Windows 平台键及签名均有效;使用旧公钥对当前 EXE 静态验签通过。改写 Git 提交邮箱不会改变这些资产。该证据不等于已复现用户机器的网络故障。
旧客户端的检查入口已经编译在程序中,新通道需要客户端升级后生效。若旧版无法访问唯一的 GitHub 入口,不能仅通过改新源码远程替换它;应先恢复其 GitHub/代理连接完成一次原生更新,或使用官方安装包完成首次引导。Windows 程序目录旁的 `Codex-X.portable` 标识也会将旧版识别为便携版,需结合实际安装目录确认,不把正常便携版强制变成安装版。
## 验证
- 本机 Rust 回归覆盖安装交接、失败恢复、端口冲突、签名失败阶段、并发更新保护和安装包暂存;前端覆盖各阶段、迟到事件、断连和长等待。

Some files were not shown because too many files have changed in this diff Show More