Compare commits

...
1 Commits
Author SHA1 Message Date
sky a309f402c1 feat: add official profiles and usage statistics for v0.3.16 2026-09-09 00:05:49 +08:00
34 changed files with 8679 additions and 329 deletions
+15 -1
View File
@@ -2,7 +2,21 @@
All notable changes to Codex-X will be documented here.
## [Unreleased]
## [v0.3.16] - 2026-09-09
### 新增与调整
- 官方登录与第三方供应商统一为一键复制:副本立即加入列表,不进入编辑页,不弹出二次确认;自动添加不重复的副本名称。
- 官方与第三方配置的 TOML 编辑区新增“开启 1M 上下文窗口”复选框,保留自定义压缩阈值及其他配置。
- 设置新增“通用设置 / 用量统计”标签页,并复用统一的淡入淡出动画;用量统计展示本地 Codex Token 总量、输入与输出、缓存命中率、每日趋势、模型分布和最近 10 个会话,支持时间范围、模型筛选与手动刷新。最近会话显示聊天标题,无标题时使用项目名。
- 用量统计按主会话归并子代理及其后代的实际用量,子代理不再单独列入最近会话或增加活跃会话数;用户主动分叉的新聊天保持独立。
- 支持添加、复制和重命名多个官方 Codex 登录配置,可与第三方 API 供应商一起管理和切换;各配置独立保存认证与完整 TOML,切换前保留当前账号最新登录状态。
- 指令提示词页面顶部标题的强调色统一为蓝色,适配浅色与深色主题。
### 修复 Bug
- 修复 GitHub 模板同步期间查看、编辑或启用提示词可能拖住供应商操作的问题;模板内容优先读取本地修改、缓存和内置版本,模板详情加载不再占用其他页面的操作状态。
- 修复首次识别到的 CC Switch 当前供应商在切换后从列表消失的问题;切换前保存完整配置与认证信息,并处理同名记录、重复配置和失败回滚。
## [v0.3.15] - 2026-08-20
+10 -4
View File
@@ -37,9 +37,10 @@ When you use Codex Desktop, the CLI, third-party APIs, and multiple prompts toge
You can use it to:
- Choose from the prompt library or import your own `.md`, then keep the existing prompt or replace it
- Save, test, and switch between OpenAI Official and third-party APIs, including Providers imported from cc-switch
- Manage multiple named official Codex login profiles and third-party APIs, duplicate or switch them with a click, and import Providers from cc-switch
- Search and organize local sessions by project, check / automatically repair problems, and precisely delete sessions you no longer need
- Manage Skills and MCP in one place, and inspect the current `config.toml`, `auth.json`, and operation backups
- Explore token usage by date and model in Settings, with subagent usage attributed to its main conversation
## Preview
@@ -117,7 +118,7 @@ You can use it to:
</tr>
<tr>
<td align="center">⚡ <b>Switch APIs / relays</b></td>
<td align="left">Save, test, and enable multiple third-party Providers, or import them from cc-switch; entries with the same endpoint and Key are merged automatically. Create or reopen a session after switching to apply the change without restarting the entire Codex client.</td>
<td align="left">Save multiple named official Codex login profiles alongside third-party Providers, with one-click duplication and switching. Third-party Providers support connection checks, model discovery / testing, and imports from cc-switch.</td>
</tr>
<tr>
<td align="center">💬 <b>Organize local sessions</b></td>
@@ -129,7 +130,11 @@ You can use it to:
</tr>
<tr>
<td align="center">📝 <b>Manage config and login</b></td>
<td align="left">Inspect the active Codex <code>config.toml</code> and <code>auth.json</code> in one place, with a clear distinction between official login credentials and third-party API Keys. Important writes are backed up automatically and can be restored when needed.</td>
<td align="left">Inspect <code>config.toml</code> and <code>auth.json</code> in one place. Both official and third-party profile editors offer an “Enable 1M context window” checkbox beside <code>config.toml>; it applies on save and requires model support. Important writes are backed up automatically.</td>
</tr>
<tr>
<td align="center">📊 <b>Track token usage</b></td>
<td align="left">Switch between General and Usage statistics in Settings. Filter local usage by date and model, explore daily trends, cache hit rate, and model distribution, and view the 10 most recent main conversations. Subagent usage is attributed to its main conversation and does not count as a separate session.</td>
</tr>
<tr>
<td align="center">📦 <b>Use it across platforms</b></td>
@@ -238,7 +243,8 @@ A backup is created automatically before every enable or disable action. In addi
> [!NOTE]
> After enabling a new third-party Provider, create or reopen a Codex session to use the new relay. You do not need to restart the entire Codex client.
- Save multiple third-party Providers and always see which one is currently active
- Save multiple named official Codex login profiles and third-party Providers, and always see which one is currently active
- Duplicate a profile immediately with one click, without a confirmation dialog or opening the editor; rename it whenever needed
- Test an API endpoint before switching, and save or enable a configuration separately
- Edit the Base URL, API Key, Model, Wire API, and complete TOML on the same page
- cc-switch imports report added, updated, merged, and skipped entries; the same URL + Key is no longer shown more than once
+10 -4
View File
@@ -38,9 +38,10 @@
- 像管理插件一样管理提示词:分类、导入 Markdown、自定义编辑、一键启用 / 禁用
- 内置 5 套提示词模板,同时支持用户把自己的提示词变成可视化模板库
- 保存、测试并切换 OpenAI Official 与第三方 API,还能从 cc-switch 导入现有供应商
- 管理多个可命名的官方 Codex 登录与第三方 API,一键复制、切换,并从 cc-switch 导入现有供应商
- 同步、检查、搜索和删除本地会话,按项目路径整理 Codex 历史记录
- 集中管理 Skills 与 MCP,查看当前 `config.toml`、`auth.json` 和操作备份
- 在设置中按日期、模型查看 Token 用量趋势,子代理用量归入所属主会话
## 软件预览
@@ -97,7 +98,7 @@
</tr>
<tr>
<td align="center"><b>Provider / API</b></td>
<td align="left">添加、编辑、启用、删除第三方供应商;支持连接检测、模型获取 / 测试、从 cc-switch 导入,并可在 OpenAI Official 与中转 API 之间切换。</td>
<td align="left">保存多个可命名的官方 Codex 登录配置,与第三方供应商统一管理、一键复制和切换;第三方供应商支持连接检测、模型获取 / 测试及从 cc-switch 导入。</td>
</tr>
<tr>
<td align="center"><b>会话管理</b></td>
@@ -109,7 +110,11 @@
</tr>
<tr>
<td align="center"><b>配置与登录</b></td>
<td align="left">集中查看 Codex 当前使用的 <code>config.toml</code> 与 <code>auth.json</code>,区分官方登录态和第三方 API Key;重要写入前自动备份。</td>
<td align="left">集中查看 <code>config.toml</code> 与 <code>auth.json</code>;官方登录和第三方供应商编辑页均可在 <code>config.toml</code> 旁勾选“开启 1M 上下文窗口”,保存后生效,需模型支持;重要写入前自动备份。</td>
</tr>
<tr>
<td align="center"><b>用量统计</b></td>
<td align="left">设置页提供“通用设置 / 用量统计”标签,按日期与模型筛选本地 Token 用量,查看每日趋势、缓存命中率、模型分布及最近 10 个主会话;子代理用量归入所属主会话,不单独计为会话。</td>
</tr>
<tr>
<td align="center"><b>跨平台使用</b></td>
@@ -230,7 +235,8 @@ Codex-X 现在不只是“几套内置 Prompt”的启动器,而是一个可
> [!NOTE]
> 启用新的第三方供应商后,新建或重新打开 Codex 会话即可使用新的中转,不需要重启整个 Codex 客户端。
- 保存多个第三方供应商,随时查看当前正在使用哪一个
- 保存多个可命名的官方 Codex 登录配置与第三方供应商,随时查看当前正在使用哪一个
- 点击“复制”直接新增独立副本,无需确认或进入编辑页;名称可稍后修改
- 切换前可检测连接,并可获取模型进行测试
- 在同一页面编辑 Base URL、API Key、Model、Wire API 和完整 TOML
- 从 cc-switch 导入时自动区分新增、更新、合并与跳过;相同 URL + Key 不再重复显示
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "codex-x",
"version": "0.3.15",
"version": "0.3.16",
"private": true,
"description": "Codex Switch & Instruct desktop manager",
"type": "module",
+1 -1
View File
@@ -490,7 +490,7 @@ dependencies = [
[[package]]
name = "codex-x"
version = "0.3.15"
version = "0.3.16"
dependencies = [
"chrono",
"dirs 5.0.1",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "codex-x"
version = "0.3.15"
version = "0.3.16"
description = "Codex Switch & Instruct desktop manager"
authors = ["yynxxxxx"]
license = "MIT"
+14 -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 = 3;
const APP_DB_SCHEMA_VERSION: i64 = 4;
struct DatabaseInitializer {
migration_lock: Mutex<()>,
@@ -206,6 +206,19 @@ fn initialize_schema(conn: &Connection) -> Result<()> {
codex_dir TEXT PRIMARY KEY,
provider_id TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS official_profiles (
codex_dir TEXT NOT NULL,
id TEXT NOT NULL,
provider_name TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
PRIMARY KEY(codex_dir, id)
);
CREATE TABLE IF NOT EXISTS official_profile_selections (
codex_dir TEXT PRIMARY KEY,
profile_id TEXT NOT NULL,
updated_at TEXT NOT NULL
);",
)
.map_err(|e| CodexxError::Database(e.to_string()))?;
@@ -0,0 +1,235 @@
use crate::error::{CodexxError, Result};
use serde::{Deserialize, Serialize};
use toml_edit::{value, DocumentMut};
const CONTEXT_WINDOW: &str = "model_context_window";
const COMPACT_TOKEN_LIMIT: &str = "model_auto_compact_token_limit";
const ONE_MILLION: i64 = 1_000_000;
const DEFAULT_COMPACT_LIMIT: i64 = 900_000;
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct ContextWindowValues {
pub(crate) context_window: Option<i64>,
pub(crate) compact_token_limit: Option<i64>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct ContextWindowConfig {
pub(crate) config_text: String,
pub(crate) enabled: bool,
#[serde(flatten)]
pub(crate) values: ContextWindowValues,
}
fn read_integer(doc: &DocumentMut, key: &str) -> Result<Option<i64>> {
doc.get(key)
.map(|item| {
item.as_integer()
.ok_or_else(|| CodexxError::Config(format!("{key} 必须为整数")))
})
.transpose()
}
fn write_integer(doc: &mut DocumentMut, key: &str, number: i64) {
// Keep existing inline comments and spacing when replacing a setting.
let decor = doc
.get(key)
.and_then(|item| item.as_value())
.map(|value| value.decor().clone());
doc[key] = value(number);
if let Some(decor) = decor {
*doc[key].as_value_mut().expect("integer value").decor_mut() = decor;
}
}
fn restore_integer(doc: &mut DocumentMut, key: &str, number: Option<i64>) {
if let Some(number) = number {
write_integer(doc, key, number);
} else {
doc.as_table_mut().remove(key);
}
}
/// Edits a supplied draft only; this never reads or writes the live configuration.
/// `enabled = None` parses the checkbox state after a manual TOML edit.
pub(crate) fn update_codex_context_window_inner(
config_text: String,
enabled: Option<bool>,
previous_values: Option<ContextWindowValues>,
) -> Result<ContextWindowConfig> {
let mut doc = config_text
.parse::<DocumentMut>()
.map_err(|error| CodexxError::Toml {
path: "config.toml".to_string(),
message: error.to_string(),
})?;
let context_window = read_integer(&doc, CONTEXT_WINDOW)?;
let compact_token_limit = read_integer(&doc, COMPACT_TOKEN_LIMIT)?;
match enabled {
Some(true) => {
write_integer(&mut doc, CONTEXT_WINDOW, ONE_MILLION);
if compact_token_limit.is_none() {
write_integer(&mut doc, COMPACT_TOKEN_LIMIT, DEFAULT_COMPACT_LIMIT);
}
}
Some(false) => {
// Only undo the 1M preset. A manual edit to either value wins.
if context_window == Some(ONE_MILLION) {
restore_integer(
&mut doc,
CONTEXT_WINDOW,
previous_values
.as_ref()
.and_then(|values| values.context_window),
);
}
let expected_compact_limit = previous_values
.as_ref()
.and_then(|values| values.compact_token_limit)
.unwrap_or(DEFAULT_COMPACT_LIMIT);
if compact_token_limit == Some(expected_compact_limit) {
restore_integer(
&mut doc,
COMPACT_TOKEN_LIMIT,
previous_values
.as_ref()
.and_then(|values| values.compact_token_limit),
);
}
}
None => {}
}
let context_window = read_integer(&doc, CONTEXT_WINDOW)?;
let compact_token_limit = read_integer(&doc, COMPACT_TOKEN_LIMIT)?;
Ok(ContextWindowConfig {
config_text: if enabled.is_none() {
config_text
} else {
doc.to_string()
},
enabled: context_window == Some(ONE_MILLION),
values: ContextWindowValues {
context_window,
compact_token_limit,
},
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn enables_at_top_level_and_preserves_unrelated_tables_and_comments() {
let original = "# My Codex settings\nmodel = \"gpt-5.5\" # keep model\n\n[mcp_servers.notes]\ncommand = \"notes\"\nmodel_context_window = 120000\n\n[model_providers.custom]\nbase_url = \"https://api.example.test/v1\"\n";
let result = update_codex_context_window_inner(original.into(), Some(true), None).unwrap();
let doc = result.config_text.parse::<DocumentMut>().unwrap();
assert_eq!(doc[CONTEXT_WINDOW].as_integer(), Some(ONE_MILLION));
assert_eq!(
doc[COMPACT_TOKEN_LIMIT].as_integer(),
Some(DEFAULT_COMPACT_LIMIT)
);
assert_eq!(
doc["mcp_servers"]["notes"][CONTEXT_WINDOW].as_integer(),
Some(120000)
);
assert!(result.config_text.contains("# My Codex settings"));
assert!(result
.config_text
.contains("model = \"gpt-5.5\" # keep model"));
assert!(result
.config_text
.contains("base_url = \"https://api.example.test/v1\""));
}
#[test]
fn parses_underscores_and_quoted_keys_without_reformatting_the_draft() {
let original = "\"model_context_window\" = 1_000_000 # large\nmodel_auto_compact_token_limit = 850_000\n";
let result = update_codex_context_window_inner(original.into(), None, None).unwrap();
assert!(result.enabled);
assert_eq!(result.values.compact_token_limit, Some(850000));
assert_eq!(result.config_text, original);
}
#[test]
fn ignores_context_values_in_tables_or_multiline_strings() {
let original = "instructions = '''\nmodel_context_window = 1000000\n'''\n[profiles.large]\nmodel_context_window = 1000000\n";
let result = update_codex_context_window_inner(original.into(), None, None).unwrap();
assert!(!result.enabled);
assert_eq!(result.values.context_window, None);
}
#[test]
fn preserves_custom_compaction_when_enabling_and_disabling() {
let original = "model_auto_compact_token_limit = 850000 # custom\n";
let enabled = update_codex_context_window_inner(original.into(), Some(true), None).unwrap();
assert_eq!(enabled.values.compact_token_limit, Some(850000));
let disabled =
update_codex_context_window_inner(enabled.config_text, Some(false), None).unwrap();
assert_eq!(disabled.values.context_window, None);
assert_eq!(disabled.config_text, original);
}
#[test]
fn restores_custom_context_and_existing_default_compaction_in_same_edit() {
let original = "model_context_window = 256000 # original\nmodel_auto_compact_token_limit = 900000 # intentional\n";
let parsed = update_codex_context_window_inner(original.into(), None, None).unwrap();
let enabled = update_codex_context_window_inner(original.into(), Some(true), None).unwrap();
let disabled = update_codex_context_window_inner(
enabled.config_text,
Some(false),
Some(parsed.values),
)
.unwrap();
assert_eq!(disabled.config_text, original);
}
#[test]
fn disabling_a_saved_preset_removes_both_default_values() {
let original = "model = \"gpt-5.5\"\n";
let enabled = update_codex_context_window_inner(original.into(), Some(true), None).unwrap();
let disabled =
update_codex_context_window_inner(enabled.config_text, Some(false), None).unwrap();
assert_eq!(disabled.config_text, original);
assert!(!disabled.enabled);
}
#[test]
fn disabling_does_not_undo_new_manual_values() {
let manual = "model_context_window = 500000\nmodel_auto_compact_token_limit = 420000\n";
let result = update_codex_context_window_inner(
manual.into(),
Some(false),
Some(ContextWindowValues {
context_window: Some(256000),
compact_token_limit: Some(200000),
}),
)
.unwrap();
assert_eq!(result.config_text, manual);
}
#[test]
fn rejects_invalid_toml_and_invalid_top_level_field_types() {
for original in [
"[unfinished",
"model_context_window = '1000000'",
"model_auto_compact_token_limit = 'automatic'",
] {
assert!(update_codex_context_window_inner(original.into(), Some(true), None).is_err());
}
}
#[test]
fn a_blank_draft_can_be_enabled_and_returned_to_blank() {
let enabled = update_codex_context_window_inner(String::new(), Some(true), None).unwrap();
assert!(enabled.enabled);
let disabled =
update_codex_context_window_inner(enabled.config_text, Some(false), None).unwrap();
assert!(disabled.config_text.is_empty());
}
}
+150 -24
View File
@@ -18,6 +18,7 @@ mod backups;
mod ccswitch;
mod config_migration;
mod constants;
mod context_config;
mod desktop_lifecycle;
mod error;
mod file_io;
@@ -33,6 +34,7 @@ mod sqlite_utils;
mod state;
mod toml_utils;
mod updates;
mod usage;
use backups::{
action_backup_root, backups, create_backup, validate_backup_codex_dir, BackupEntry, BackupMeta,
@@ -70,25 +72,32 @@ use prompts::{
prompt_content_source_urls, stable_remote_prompt_id, stale_cached_prompt_ids,
uninstall_managed_agents_block, CachedBuiltinPrompt, GithubContentEntry,
};
use providers::official_profiles::{
delete_official_profile_inner, duplicate_official_profile_inner, get_official_profile_inner,
list_official_profiles_inner, save_official_profile_inner, switch_official_profile_inner,
OfficialProfileActionResult, OfficialProfileDetail, OfficialProfileInput,
OfficialProfileSummary,
};
#[cfg(test)]
use providers::{
build_ccswitch_codex_provider, canonical_provider_base_url, codex_sections_from_config,
consolidate_legacy_provider_duplicates_on_connection, detected_live_custom_provider,
is_official_ccswitch_row, list_saved_providers_on_connection, normalize_saved_provider,
official_snapshot_path_for_test, provider_by_id_on_connection, provider_identity,
provider_status_result, read_ccswitch_codex_rows, save_manual_provider_on_connection,
save_provider_toml_config_with_pre_persist, switch_official_provider_with_pre_persist,
get_official_config_draft_inner, is_official_ccswitch_row, list_saved_providers_on_connection,
normalize_saved_provider, official_snapshot_path_for_test, provider_by_id_on_connection,
provider_identity, provider_status_result, read_ccswitch_codex_rows,
reset_official_provider_inner, restore_official_provider_inner,
save_manual_provider_on_connection, save_provider_toml_config_with_pre_persist,
switch_official_provider_inner, switch_official_provider_with_pre_persist,
switch_provider_with_pre_persist, upsert_ccswitch_provider_on_connection,
upsert_provider_on_connection, CcSwitchCodexRow, ProviderUpsertKind, ProviderUpsertMode,
};
use providers::{
build_provider_toml_draft_inner, clear_active_provider_on_connection,
delete_saved_provider_inner, fetch_provider_models_inner, get_official_config_draft_inner,
delete_saved_provider_inner, fetch_provider_models_inner,
import_ccswitch_codex_providers_inner, list_saved_providers_inner, open_store,
read_ccswitch_official_auth_inner, remember_active_provider_on_connection,
reset_official_provider_inner, restore_official_provider_inner, save_active_provider_inner,
save_official_config_inner, save_provider_inner, save_provider_toml_config_inner,
switch_official_provider_inner, switch_provider_inner, test_provider_connection_inner,
save_active_provider_inner, save_official_config_inner, save_provider_inner,
save_provider_toml_config_inner, switch_provider_inner, test_provider_connection_inner,
ImportResult, OfficialAuthCandidate, OfficialConfigDraft, OfficialConfigInput,
ProviderConnectionResult, ProviderInput, ProviderModelsResult, ProviderTomlInput,
SavedProvider,
@@ -902,21 +911,21 @@ fn finish_provider_selection(
{
return result;
}
match &update {
ActiveProviderSelectionUpdate::Set(provider_id) => {
result.state.active_saved_provider_id = Some(provider_id.clone());
}
ActiveProviderSelectionUpdate::ClearIfOfficial => {
result.state.active_saved_provider_id = None;
}
}
let codex_dir = PathBuf::from(&result.state.codex_dir);
let refreshed_state = (|| -> Result<CodexState> {
let conn = open_store()?;
match update {
ActiveProviderSelectionUpdate::Set(provider_id) => {
remember_active_provider_on_connection(&conn, &codex_dir, &provider_id)?;
let saved = providers::list_saved_providers_on_connection(&conn)?;
let matches = providers::detected_live_custom_provider(&codex_dir)?
.map(|live| providers::matching_saved_provider_ids_for_live(&live, &saved))
.unwrap_or_default();
// A detected UI row can carry a provisional ID. Adoption may
// allocate a different ID, so only honor an explicit selection
// that actually matches the now-active saved configuration.
if matches.contains(&provider_id) {
remember_active_provider_on_connection(&conn, &codex_dir, &provider_id)?;
}
}
ActiveProviderSelectionUpdate::ClearIfOfficial => {
clear_active_provider_on_connection(&conn, &codex_dir)?;
@@ -959,6 +968,42 @@ async fn save_provider(provider: SavedProvider) -> Result<SavedProvider> {
.map_err(|e| CodexxError::Config(format!("保存供应商失败: {e}")))?
}
#[tauri::command]
async fn duplicate_provider(
config_dir: Option<String>,
provider_id: Option<String>,
provider_name: Option<String>,
) -> Result<providers::DuplicateProviderResult> {
tauri::async_runtime::spawn_blocking(move || {
providers::duplicate_provider_inner(config_dir, provider_id, provider_name)
})
.await
.map_err(|error| CodexxError::Config(format!("复制供应商失败: {error}")))?
}
#[tauri::command]
async fn update_codex_context_window(
config_text: String,
enabled: Option<bool>,
previous_values: Option<context_config::ContextWindowValues>,
) -> Result<context_config::ContextWindowConfig> {
context_config::update_codex_context_window_inner(config_text, enabled, previous_values)
}
#[tauri::command]
async fn get_usage_statistics(
config_dir: Option<String>,
range: Option<String>,
model: Option<String>,
force_refresh: Option<bool>,
) -> Result<usage::UsageStatistics> {
tauri::async_runtime::spawn_blocking(move || {
usage::get_usage_statistics_inner(config_dir, range, model, force_refresh)
})
.await
.map_err(|error| CodexxError::Config(format!("读取用量统计失败: {error}")))?
}
#[tauri::command]
async fn save_active_provider(
provider: SavedProvider,
@@ -998,7 +1043,10 @@ fn get_codex_state_inner(config_dir: Option<String>) -> Result<CodexState> {
#[tauri::command]
async fn switch_official_provider(config_dir: Option<String>) -> Result<ActionResult> {
tauri::async_runtime::spawn_blocking(move || {
let result = switch_official_provider_inner(config_dir)?;
let result = switch_official_profile_inner(
config_dir,
providers::official_profiles::DEFAULT_OFFICIAL_PROFILE_ID.to_string(),
)?;
Ok(finish_provider_selection(
result,
ActiveProviderSelectionUpdate::ClearIfOfficial,
@@ -1012,15 +1060,85 @@ async fn switch_official_provider(config_dir: Option<String>) -> Result<ActionRe
async fn get_official_config_draft(
config_dir: Option<String>,
) -> Result<Option<OfficialConfigDraft>> {
tauri::async_runtime::spawn_blocking(move || get_official_config_draft_inner(config_dir))
tauri::async_runtime::spawn_blocking(move || {
let detail = get_official_profile_inner(
config_dir,
providers::official_profiles::DEFAULT_OFFICIAL_PROFILE_ID.to_string(),
)?;
Ok(Some(OfficialConfigDraft {
auth_json: detail.auth_json,
config_text: detail.config_text,
model: detail.profile.model,
source: detail.source,
}))
})
.await
.map_err(|e| CodexxError::Config(format!("读取官方配置快照失败: {e}")))?
}
#[tauri::command]
async fn list_official_profiles(config_dir: Option<String>) -> Result<Vec<OfficialProfileSummary>> {
tauri::async_runtime::spawn_blocking(move || list_official_profiles_inner(config_dir))
.await
.map_err(|e| CodexxError::Config(format!("读取官方配置快照失败: {e}")))?
.map_err(|error| CodexxError::Config(format!("读取官方配置列表失败: {error}")))?
}
#[tauri::command]
async fn get_official_profile(
config_dir: Option<String>,
profile_id: String,
) -> Result<OfficialProfileDetail> {
tauri::async_runtime::spawn_blocking(move || get_official_profile_inner(config_dir, profile_id))
.await
.map_err(|error| CodexxError::Config(format!("读取官方配置失败: {error}")))?
}
#[tauri::command]
async fn save_official_profile(input: OfficialProfileInput) -> Result<OfficialProfileActionResult> {
tauri::async_runtime::spawn_blocking(move || save_official_profile_inner(input))
.await
.map_err(|error| CodexxError::Config(format!("保存官方配置失败: {error}")))?
}
#[tauri::command]
async fn duplicate_official_profile(
config_dir: Option<String>,
profile_id: String,
provider_name: Option<String>,
) -> Result<OfficialProfileActionResult> {
tauri::async_runtime::spawn_blocking(move || {
duplicate_official_profile_inner(config_dir, profile_id, provider_name)
})
.await
.map_err(|error| CodexxError::Config(format!("复制官方配置失败: {error}")))?
}
#[tauri::command]
async fn switch_official_profile(
config_dir: Option<String>,
profile_id: String,
) -> Result<ActionResult> {
tauri::async_runtime::spawn_blocking(move || {
switch_official_profile_inner(config_dir, profile_id)
})
.await
.map_err(|error| CodexxError::Config(format!("切换官方配置失败: {error}")))?
}
#[tauri::command]
async fn delete_official_profile(config_dir: Option<String>, profile_id: String) -> Result<()> {
tauri::async_runtime::spawn_blocking(move || {
delete_official_profile_inner(config_dir, profile_id)
})
.await
.map_err(|error| CodexxError::Config(format!("删除官方配置失败: {error}")))?
}
#[tauri::command]
async fn restore_official_provider(config_dir: Option<String>) -> Result<ActionResult> {
tauri::async_runtime::spawn_blocking(move || {
let result = restore_official_provider_inner(config_dir)?;
let result =
providers::official_profiles::restore_default_official_profile_inner(config_dir)?;
Ok(finish_provider_selection(
result,
ActiveProviderSelectionUpdate::ClearIfOfficial,
@@ -1033,8 +1151,7 @@ async fn restore_official_provider(config_dir: Option<String>) -> Result<ActionR
#[tauri::command]
async fn reset_official_provider(input: OfficialConfigInput) -> Result<ActionResult> {
tauri::async_runtime::spawn_blocking(move || {
let result =
reset_official_provider_inner(input.config_dir, input.model, input.config_text)?;
let result = providers::official_profiles::reset_default_official_profile_inner(input)?;
Ok(finish_provider_selection(
result,
ActiveProviderSelectionUpdate::ClearIfOfficial,
@@ -1501,11 +1618,20 @@ pub fn run() {
list_saved_providers,
build_provider_toml_draft,
save_provider,
duplicate_provider,
update_codex_context_window,
get_usage_statistics,
save_active_provider,
delete_saved_provider,
get_codex_state,
switch_official_provider,
get_official_config_draft,
list_official_profiles,
get_official_profile,
save_official_profile,
duplicate_official_profile,
switch_official_profile,
delete_official_profile,
restore_official_provider,
reset_official_provider,
save_official_config,
+193 -21
View File
@@ -23,7 +23,8 @@ use serde::Deserialize;
use std::collections::{HashMap, HashSet};
use std::sync::Mutex;
static BUILTIN_PROMPT_CACHE_LOCK: Mutex<()> = Mutex::new(());
// Only serialize remote syncs. Local reads must stay available during downloads.
static BUILTIN_PROMPT_SYNC_LOCK: Mutex<()> = Mutex::new(());
const CATALOG_CDN_KEY: &str = "模板 CDN";
const CATALOG_GITHUB_KEY: &str = "GitHub 模板目录";
const PROMPT_CDN_KEY: &str = "模板 CDN";
@@ -305,6 +306,13 @@ pub(crate) fn delete_cached_prompt_ids(
fn prune_builtin_prompt_cache(active_ids: &HashSet<String>) -> Result<usize> {
let mut conn = open_db()?;
prune_builtin_prompt_cache_on_connection(&mut conn, active_ids)
}
fn prune_builtin_prompt_cache_on_connection(
conn: &mut Connection,
active_ids: &HashSet<String>,
) -> Result<usize> {
let transaction = conn
.transaction_with_behavior(TransactionBehavior::Immediate)
.map_err(|e| CodexxError::Database(e.to_string()))?;
@@ -315,7 +323,14 @@ fn prune_builtin_prompt_cache(active_ids: &HashSet<String>) -> Result<usize> {
let mut deleted = 0;
for id in stale_ids {
deleted += transaction
.execute("DELETE FROM builtin_prompt_cache WHERE id = ?1", [id])
.execute(
"DELETE FROM builtin_prompt_cache
WHERE id = ?1
AND NOT EXISTS (
SELECT 1 FROM builtin_prompt_overrides WHERE template_id = ?1
)",
[id],
)
.map_err(|e| CodexxError::Database(e.to_string()))?;
}
transaction
@@ -678,6 +693,24 @@ fn mark_customized_prompt_statuses(
}
}
fn include_customized_prompt_statuses(
statuses: &mut Vec<BuiltinPromptStatus>,
customized_ids: &HashSet<String>,
caches: Vec<CachedBuiltinPrompt>,
) {
for cache in caches {
if customized_ids.contains(&cache.id)
&& !statuses.iter().any(|status| status.id == cache.id)
{
statuses.push(prompt_status_from_cache(
cache,
"本地已修改,GitHub 同步已跳过",
));
}
}
mark_customized_prompt_statuses(statuses, customized_ids);
}
fn should_sync_prompt_content(id: &str, customized_ids: &HashSet<String>) -> bool {
!customized_ids.contains(id)
}
@@ -733,7 +766,7 @@ pub(crate) fn builtin_prompt_status_inner() -> Result<Vec<BuiltinPromptStatus>>
pub(crate) fn refresh_builtin_prompts_with_active(
active_remote_builtin_prompt_id: impl FnOnce() -> Option<String>,
) -> Result<Vec<BuiltinPromptStatus>> {
let _cache_guard = BUILTIN_PROMPT_CACHE_LOCK
let _sync_guard = BUILTIN_PROMPT_SYNC_LOCK
.lock()
.map_err(|_| CodexxError::Database("提示词缓存锁已损坏".to_string()))?;
let customized_ids = builtin_prompt_override_ids_inner()?;
@@ -828,7 +861,10 @@ pub(crate) fn refresh_builtin_prompts_with_active(
if catalog_confirmation_failed {
mark_catalog_confirmation_failed(&mut statuses);
}
mark_customized_prompt_statuses(&mut statuses, &customized_ids);
// Local edits can finish while remote requests are pending. Use their
// latest IDs and retained cache entries when returning the catalog.
let customized_ids = builtin_prompt_override_ids_inner()?;
include_customized_prompt_statuses(&mut statuses, &customized_ids, cached_builtin_prompts()?);
let order = bundled_prompt_metas()
.into_iter()
.enumerate()
@@ -849,9 +885,8 @@ pub(crate) fn refresh_builtin_prompts_with_active(
pub(crate) fn builtin_prompt_content(
template_id: &str,
) -> Result<(String, String, String, String)> {
let _cache_guard = BUILTIN_PROMPT_CACHE_LOCK
.lock()
.map_err(|_| CodexxError::Database("提示词缓存锁已损坏".to_string()))?;
// Editing and enabling a template are local operations. Network refreshes
// update SQLite separately, whose reads see the last committed cache entry.
let id = if template_id.trim().is_empty() {
"gpt5.5-unrestricted"
} else {
@@ -872,19 +907,6 @@ pub(crate) fn builtin_prompt_content(
"本地已修改".to_string(),
));
}
let trust = PromptContentTrust {
cached: cached.as_ref().map(|item| item.content.as_str()),
bundled: bundled.map(|item| item.content),
};
if let Ok((remote, source_url)) = fetch_remote_prompt(&filename, trust) {
save_builtin_prompt_cache(id, &filename, &source_url, &remote)?;
return Ok((
filename.clone(),
format!("./{filename}"),
remote,
"在线最新".to_string(),
));
}
if let Some(cache) = cached {
return Ok((
cache.filename.clone(),
@@ -894,7 +916,9 @@ pub(crate) fn builtin_prompt_content(
));
}
let bundled = bundled.ok_or_else(|| {
CodexxError::Config(format!("无法下载提示词且没有可用缓存: {template_id}"))
CodexxError::Config(format!(
"提示词尚无本地内容,请先同步 GitHub 模板: {template_id}"
))
})?;
Ok((
bundled.filename.to_string(),
@@ -925,6 +949,91 @@ pub(crate) fn builtin_prompt_detail_inner(template_id: &str) -> Result<BuiltinPr
mod tests {
use super::*;
#[test]
fn local_prompt_detail_does_not_wait_for_background_sync() {
let _db_guard = crate::app_db::test_db_guard();
let id = "github-detail-during-sync";
save_builtin_prompt_cache(
id,
"detail-during-sync.md",
"https://example.test/prompt.md",
"cached content",
)
.expect("cache template");
super::super::store::save_builtin_prompt_override_inner(id, "local edit")
.expect("save local edit");
let sync_guard = BUILTIN_PROMPT_SYNC_LOCK
.lock()
.expect("simulate pending sync");
let (sender, receiver) = std::sync::mpsc::channel();
let reader = std::thread::spawn(move || {
sender.send(builtin_prompt_detail_inner(id)).unwrap();
});
let detail = receiver.recv_timeout(std::time::Duration::from_secs(1));
// Release before asserting so a regression cannot leave a blocked worker.
drop(sync_guard);
reader.join().expect("finish detail reader");
let conn = open_db().expect("open test store");
conn.execute(
"DELETE FROM builtin_prompt_overrides WHERE template_id = ?1",
[id],
)
.unwrap();
conn.execute("DELETE FROM builtin_prompt_cache WHERE id = ?1", [id])
.unwrap();
let detail = detail
.expect("local detail must finish while sync is pending")
.unwrap();
assert_eq!(detail.content, "local edit");
assert!(detail.customized);
}
#[test]
fn cached_and_bundled_prompt_content_stays_available_during_sync() {
let _db_guard = crate::app_db::test_db_guard();
let id = "github-cached-content-during-sync";
save_builtin_prompt_cache(
id,
"cached-during-sync.md",
"https://example.test/prompt.md",
"last downloaded content",
)
.expect("cache online template");
let before = cached_builtin_prompt(id).unwrap().unwrap().checked_at;
let sync_guard = BUILTIN_PROMPT_SYNC_LOCK
.lock()
.expect("simulate pending sync");
let (sender, receiver) = std::sync::mpsc::channel();
let reader = std::thread::spawn(move || {
let result = (|| -> Result<_> {
Ok((
builtin_prompt_content(id)?,
builtin_prompt_content("gpt5.5-unrestricted")?,
))
})();
sender.send(result).unwrap();
});
let result = receiver.recv_timeout(std::time::Duration::from_secs(1));
drop(sync_guard);
reader.join().expect("finish content reader");
let after = cached_builtin_prompt(id).unwrap().unwrap().checked_at;
open_db()
.unwrap()
.execute("DELETE FROM builtin_prompt_cache WHERE id = ?1", [id])
.unwrap();
let (cached, bundled) = result
.expect("local content must not wait for sync")
.unwrap();
assert_eq!(cached.2, "last downloaded content");
assert_eq!(cached.3, "本地缓存");
assert_eq!(bundled.2, INSTRUCTION_CONTENT);
assert_eq!(bundled.3, "打包内置");
assert_eq!(before, after, "reading must not refresh the cache");
}
const TEST_SOURCES: [RemoteSource<'static>; 2] = [
RemoteSource::new(PROMPT_CDN_KEY, "https://cdn.test/prompt.md", None),
RemoteSource::new(PROMPT_GITHUB_KEY, "https://github.test/prompt.md", None),
@@ -939,6 +1048,10 @@ mod tests {
content TEXT NOT NULL,
checked_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE builtin_prompt_overrides (
template_id TEXT PRIMARY KEY,
content TEXT NOT NULL
);",
)
.expect("create prompt cache table");
@@ -950,6 +1063,65 @@ mod tests {
conn
}
#[test]
fn edit_saved_during_sync_survives_stale_catalog_pruning_and_returned_statuses() {
let mut conn = prompt_cache_connection();
for id in [
"removed-but-edited",
"removed-unedited",
"remote-still-present",
] {
save_builtin_prompt_cache_on_connection(
&conn,
id,
&format!("{id}.md"),
"https://example.test/prompt.md",
"downloaded content",
)
.unwrap();
}
// Sync started before this edit, so its original retained IDs omit it.
let retained_at_sync_start = HashSet::from(["remote-still-present".to_string()]);
conn.execute(
"INSERT INTO builtin_prompt_overrides (template_id, content) VALUES (?1, ?2)",
["removed-but-edited", "new local content"],
)
.unwrap();
let removed = prune_builtin_prompt_cache_on_connection(&mut conn, &retained_at_sync_start)
.expect("prune the old catalog after the local save");
assert_eq!(removed, 1);
let cache = cached_builtin_prompt_from_connection(&conn, "removed-but-edited")
.unwrap()
.expect("keep the filename needed to reopen the saved edit");
assert_eq!(cache.filename, "removed-but-edited.md");
assert!(
cached_builtin_prompt_from_connection(&conn, "removed-unedited")
.unwrap()
.is_none()
);
let mut statuses = vec![prompt_status_from_cache(
cached_builtin_prompt_from_connection(&conn, "remote-still-present")
.unwrap()
.unwrap(),
"synced",
)];
let customized_ids = HashSet::from(["removed-but-edited".to_string()]);
include_customized_prompt_statuses(
&mut statuses,
&customized_ids,
cached_builtin_prompts_from_connection(&conn).unwrap(),
);
assert_eq!(statuses.len(), 2);
let edited = statuses
.iter()
.find(|status| status.id == "removed-but-edited")
.expect("include the newly edited template in the sync response");
assert!(edited.customized);
assert!(edited.message.contains("本地已修改"));
}
#[test]
fn synced_remote_prompt_is_available_from_sqlite_after_restart() {
let database_path = std::env::temp_dir().join(format!(
+284 -29
View File
@@ -1,18 +1,21 @@
use super::ccswitch::codex_section_from_table;
#[cfg(test)]
use super::official_auth::mark_official_config_reset;
use super::official_auth::{
auth_value_has_material, build_official_config_text,
capture_live_official_config_before_provider_switch, document_is_official,
live_config_is_official, mark_official_config_reset, official_config_candidate,
official_snapshot_path, save_official_config_snapshot, validate_official_config_text,
live_config_is_official, official_config_candidate, official_snapshot_path,
save_official_config_snapshot, validate_official_config_text,
};
use super::{
custom_provider_id, delete_provider_inner, experimental_bearer_token_from_doc,
is_placeholder_provider, list_saved_providers_inner, list_saved_providers_on_connection,
is_placeholder_provider, list_saved_providers_on_connection,
matching_saved_provider_ids_for_live, normalize_saved_provider,
normalize_saved_provider_for_save, open_store, provider_template_from_document,
reconcile_active_provider_on_connection, reserved_codex_provider_id,
rollback_provider_store_inner, save_provider_with_rollback_inner, strip_provider_bearer_tokens,
unique_saved_provider_id_for_live, ProviderStoreRollback, SavedProvider,
rollback_provider_store_inner, save_detected_provider_with_rollback_inner,
save_provider_with_rollback_inner, strip_provider_bearer_tokens, ProviderStoreRollback,
SavedProvider,
};
use crate::backups::create_backup;
use crate::config_migration::migrate_legacy_prompt_config_locked;
@@ -62,7 +65,8 @@ pub(crate) struct OfficialConfigInput {
pub(crate) config_text: Option<String>,
}
enum LiveAuthAction {
pub(super) enum LiveAuthAction {
#[cfg(test)]
Keep,
Replace(Value),
Remove,
@@ -149,7 +153,7 @@ fn live_auth_api_key(codex_dir: &Path) -> Result<Option<String>> {
}
#[derive(Debug)]
struct AppliedLiveFiles {
pub(super) struct AppliedLiveFiles {
config_path: PathBuf,
auth_path: PathBuf,
old_config: Option<Vec<u8>>,
@@ -159,7 +163,7 @@ struct AppliedLiveFiles {
}
impl AppliedLiveFiles {
fn rollback(&self) -> Result<()> {
pub(super) fn rollback(&self) -> Result<()> {
ensure_file_snapshot_unchanged(&self.config_path, Some(self.new_config.as_slice()))?;
if let Some(new_auth) = &self.new_auth {
ensure_file_snapshot_unchanged(&self.auth_path, new_auth.as_deref())?;
@@ -378,6 +382,7 @@ where
let auth = auth_path(codex_dir);
let new_config = config_text.as_bytes().to_vec();
let new_auth = match auth_action {
#[cfg(test)]
LiveAuthAction::Keep => None,
LiveAuthAction::Replace(value) => Some(Some(json_bytes(&auth, value)?)),
LiveAuthAction::Remove => Some(None),
@@ -549,25 +554,13 @@ pub(crate) fn detected_live_custom_provider(codex_dir: &Path) -> Result<Option<S
}))
}
fn persist_detected_live_custom_provider(
pub(super) fn persist_detected_live_custom_provider(
codex_dir: &Path,
) -> Result<Option<ProviderStoreRollback>> {
let Some(mut live) = detected_live_custom_provider(codex_dir)? else {
let Some(live) = detected_live_custom_provider(codex_dir)? else {
return Ok(None);
};
let saved = list_saved_providers_inner()?;
let Some(saved_id) = unique_saved_provider_id_for_live(&live, &saved) else {
return Ok(None);
};
if live.api_key.is_none() {
live.api_key = saved
.iter()
.find(|provider| provider.id == saved_id)
.and_then(|provider| provider.api_key.clone());
}
live.id = saved_id;
let (_, rollback) = save_provider_with_rollback_inner(live)?;
Ok(Some(rollback))
save_detected_provider_with_rollback_inner(live)
}
pub(crate) fn build_provider_toml_draft_inner(
@@ -616,7 +609,7 @@ pub(crate) fn build_provider_toml_draft_inner(
.ok_or_else(|| CodexxError::Config("无法生成供应商 TOML".to_string()))
}
fn apply_official_config_locked(
pub(super) fn apply_official_config_locked(
codex_dir: &Path,
config_text: Option<&str>,
model: Option<&str>,
@@ -624,10 +617,38 @@ fn apply_official_config_locked(
auth_action: LiveAuthAction,
action: &str,
) -> Result<(Option<String>, AppliedLiveFiles)> {
let cfg = config_path(codex_dir);
let auth = auth_path(codex_dir);
let old_config = read_file_snapshot(&cfg)?;
let old_auth = read_file_snapshot(&auth)?;
apply_official_config_with_snapshot_locked(
codex_dir,
config_text,
model,
clear_model_if_none,
auth_action,
action,
read_live_file_snapshot(codex_dir)?,
)
}
pub(super) struct LiveFileSnapshot {
config: Option<Vec<u8>>,
auth: Option<Vec<u8>>,
}
pub(super) fn read_live_file_snapshot(codex_dir: &Path) -> Result<LiveFileSnapshot> {
Ok(LiveFileSnapshot {
config: read_file_snapshot(&config_path(codex_dir))?,
auth: read_file_snapshot(&auth_path(codex_dir))?,
})
}
pub(super) fn apply_official_config_with_snapshot_locked(
codex_dir: &Path,
config_text: Option<&str>,
model: Option<&str>,
clear_model_if_none: bool,
auth_action: LiveAuthAction,
action: &str,
before: LiveFileSnapshot,
) -> Result<(Option<String>, AppliedLiveFiles)> {
let backup_id = create_backup(codex_dir, action)?;
let config_text = match config_text.map(str::trim).filter(|text| !text.is_empty()) {
@@ -638,7 +659,13 @@ fn apply_official_config_locked(
}
};
let applied = write_live_files(codex_dir, old_config, old_auth, &config_text, &auth_action)?;
let applied = write_live_files(
codex_dir,
before.config,
before.auth,
&config_text,
&auth_action,
)?;
Ok((backup_id, applied))
}
@@ -665,6 +692,7 @@ fn finish_live_action(
}
}
#[cfg(test)]
pub(crate) fn switch_official_provider_with_pre_persist<F>(
config_dir: Option<String>,
pre_persist: F,
@@ -732,6 +760,7 @@ where
finish_live_action(&codex_dir, message, backup_id, &live, snapshot.as_ref())
}
#[cfg(test)]
pub(crate) fn switch_official_provider_inner(config_dir: Option<String>) -> Result<ActionResult> {
let mut provider_rollback = None;
let result = switch_official_provider_with_pre_persist(config_dir, |codex_dir| {
@@ -843,6 +872,7 @@ pub(crate) fn save_official_config_inner(
}
}
#[cfg(test)]
pub(crate) fn restore_official_provider_inner(config_dir: Option<String>) -> Result<ActionResult> {
let codex_dir = resolve_codex_dir(config_dir)?;
ensure_directory(&codex_dir)?;
@@ -874,6 +904,7 @@ pub(crate) fn restore_official_provider_inner(config_dir: Option<String>) -> Res
}
}
#[cfg(test)]
fn reset_official_provider_with_pre_persist<F>(
config_dir: Option<String>,
model: Option<String>,
@@ -926,6 +957,7 @@ where
)
}
#[cfg(test)]
pub(crate) fn reset_official_provider_inner(
config_dir: Option<String>,
model: Option<String>,
@@ -2344,4 +2376,227 @@ experimental_bearer_token = "sk-external"
delete_provider_inner(&id).expect("delete adopted provider");
fs::remove_dir_all(codex_dir).expect("remove detected provider test directory");
}
#[test]
fn detected_live_provider_survives_activation_and_later_provider_switches() {
let _db_guard = crate::app_db::test_db_guard();
for activate_first in [false, true] {
let tag = if activate_first { 40_001 } else { 40_002 };
let codex_dir = active_provider_test_dir("detected-retained", tag);
let config_dir = Some(codex_dir.display().to_string());
let name = format!("Detected {tag}");
let live = active_provider_fixture(tag, "custom", &name, "live-model", "sk-live");
write_active_provider_files(&codex_dir, &live);
let original_config = fs::read_to_string(config_path(&codex_dir)).unwrap();
let original_auth = fs::read(auth_path(&codex_dir)).unwrap();
let state = crate::get_codex_state_inner(config_dir.clone()).unwrap();
assert!(state.active_saved_provider_id.is_none());
assert!(list_saved_providers_inner()
.unwrap()
.iter()
.all(|provider| provider.base_url != live.base_url));
assert_eq!(
fs::read_to_string(config_path(&codex_dir)).unwrap(),
original_config
);
assert_eq!(fs::read(auth_path(&codex_dir)).unwrap(), original_auth);
if activate_first {
let activated = switch_provider_inner(ProviderInput {
config_dir: config_dir.clone(),
provider_id: Some(custom_provider_id(&live.provider_name)),
provider_name: live.provider_name.clone(),
base_url: live.base_url.clone(),
model: live.model.clone(),
api_key: live.api_key.clone(),
wire_api: Some(live.wire_api.clone()),
requires_openai_auth: Some(live.requires_openai_auth),
})
.expect("activate the detected CC Switch live configuration");
let adopted_id = activated.state.active_saved_provider_id.clone();
assert!(adopted_id.is_some());
let selected = crate::finish_provider_selection(
activated,
crate::ActiveProviderSelectionUpdate::Set(format!("provisional-{tag}")),
);
assert_eq!(selected.state.active_saved_provider_id, adopted_id);
assert!(!selected.message.contains("当前供应商状态记录失败"));
}
switch_official_provider_inner(config_dir.clone()).expect("switch to official");
let retained = list_saved_providers_inner()
.unwrap()
.into_iter()
.filter(|provider| provider.base_url == live.base_url)
.collect::<Vec<_>>();
assert_eq!(retained.len(), 1);
let retained = &retained[0];
assert_eq!(retained.api_key, live.api_key);
assert_eq!(retained.provider_name, name);
let retained_config = retained.toml_config.clone().unwrap();
assert!(retained_config.contains("approval_policy = \"never\""));
assert!(retained_config.contains("docs-server"));
save_provider_toml_config_inner(ProviderTomlInput {
config_dir: config_dir.clone(),
config_text: retained_config,
api_key: retained.api_key.clone(),
})
.expect("restore the retained provider");
assert_eq!(fs::read(auth_path(&codex_dir)).unwrap(), original_auth);
switch_provider_inner(ProviderInput {
config_dir,
provider_id: Some(format!("other-{tag}")),
provider_name: "Other".to_string(),
base_url: format!("https://other-{tag}.example.com/v1"),
model: "other-model".to_string(),
api_key: Some("sk-other".to_string()),
wire_api: Some("responses".to_string()),
requires_openai_auth: Some(true),
})
.expect("switch from the detected provider to another third party");
let final_rows = list_saved_providers_inner().unwrap();
assert_eq!(
final_rows
.iter()
.filter(|provider| provider.base_url == live.base_url)
.count(),
1
);
assert_eq!(saved_provider(&retained.id).api_key, live.api_key);
delete_provider_inner(&retained.id).unwrap();
let _ = fs::remove_file(official_snapshot_path(&codex_dir).unwrap());
fs::remove_dir_all(codex_dir).unwrap();
}
}
#[test]
fn detected_live_provider_adoption_preserves_an_unrelated_colliding_id() {
let _db_guard = crate::app_db::test_db_guard();
let tag = 40_003;
let codex_dir = active_provider_test_dir("detected-collision", tag);
let live = active_provider_fixture(tag, "custom", "Detected Collision", "live", "sk-live");
let existing = save_provider_inner(active_provider_fixture(
tag + 1,
&custom_provider_id(&live.provider_name),
"Existing",
"existing-model",
"sk-existing",
))
.unwrap();
write_active_provider_files(&codex_dir, &live);
let activated = save_provider_toml_config_inner(ProviderTomlInput {
config_dir: Some(codex_dir.display().to_string()),
config_text: fs::read_to_string(config_path(&codex_dir)).unwrap(),
api_key: live.api_key.clone(),
})
.unwrap();
assert_eq!(saved_provider(&existing.id), existing);
let retained = list_saved_providers_inner()
.unwrap()
.into_iter()
.find(|provider| provider.base_url == live.base_url)
.expect("retain detected provider beside the colliding saved ID");
assert_ne!(retained.id, existing.id);
assert_eq!(retained.api_key, live.api_key);
assert_eq!(
activated.state.active_saved_provider_id.as_deref(),
Some(retained.id.as_str())
);
let selected = crate::finish_provider_selection(
activated,
crate::ActiveProviderSelectionUpdate::Set(existing.id.clone()),
);
assert_eq!(
selected.state.active_saved_provider_id.as_deref(),
Some(retained.id.as_str())
);
assert!(!selected.message.contains("当前供应商状态记录失败"));
switch_official_provider_inner(Some(codex_dir.display().to_string())).unwrap();
assert_eq!(saved_provider(&existing.id), existing);
delete_provider_inner(&existing.id).unwrap();
delete_provider_inner(&retained.id).unwrap();
fs::remove_dir_all(codex_dir).unwrap();
}
#[test]
fn failed_switch_rolls_back_new_detected_provider_adoption() {
let _db_guard = crate::app_db::test_db_guard();
let tag = 40_005;
let codex_dir = active_provider_test_dir("detected-rollback", tag);
let live = active_provider_fixture(tag, "custom", "Detected Rollback", "live", "sk-live");
write_active_provider_files(&codex_dir, &live);
let config_before = fs::read(config_path(&codex_dir)).unwrap();
let auth_before = fs::read(auth_path(&codex_dir)).unwrap();
let error = switch_provider_inner(ProviderInput {
config_dir: Some(codex_dir.display().to_string()),
provider_id: Some("missing-key".to_string()),
provider_name: "Missing Key".to_string(),
base_url: "https://missing-key.example.com/v1".to_string(),
model: "target-model".to_string(),
api_key: None,
wire_api: Some("responses".to_string()),
requires_openai_auth: Some(true),
})
.expect_err("reject target credentials after the pre-switch adoption");
assert!(error.to_string().contains("需要 API Key"));
assert!(list_saved_providers_inner()
.unwrap()
.iter()
.all(|provider| provider.base_url != live.base_url));
assert_eq!(fs::read(config_path(&codex_dir)).unwrap(), config_before);
assert_eq!(fs::read(auth_path(&codex_dir)).unwrap(), auth_before);
fs::remove_dir_all(codex_dir).unwrap();
}
#[test]
fn detected_live_provider_does_not_overwrite_ambiguous_saved_copies() {
let _db_guard = crate::app_db::test_db_guard();
let tag = 40_006;
let codex_dir = active_provider_test_dir("detected-ambiguous", tag);
let live = active_provider_fixture(tag, "custom", "Duplicate", "live", "sk-live");
let mut first = live.clone();
first.id = "detected-ambiguous-first".to_string();
let first = save_provider_inner(first).unwrap();
let mut second = live.clone();
second.id = "detected-ambiguous-second".to_string();
let second = save_provider_inner(second).unwrap();
write_active_provider_files(&codex_dir, &live);
let activated = save_provider_toml_config_inner(ProviderTomlInput {
config_dir: Some(codex_dir.display().to_string()),
config_text: fs::read_to_string(config_path(&codex_dir)).unwrap(),
api_key: live.api_key.clone(),
})
.unwrap();
let selected = crate::finish_provider_selection(
activated,
crate::ActiveProviderSelectionUpdate::Set(second.id.clone()),
);
assert_eq!(
selected.state.active_saved_provider_id.as_deref(),
Some(second.id.as_str())
);
switch_official_provider_inner(Some(codex_dir.display().to_string())).unwrap();
assert_eq!(saved_provider(&first.id), first);
assert_eq!(saved_provider(&second.id), second);
assert_eq!(
list_saved_providers_inner()
.unwrap()
.iter()
.filter(|provider| provider.base_url == live.base_url)
.count(),
2
);
delete_provider_inner(&first.id).unwrap();
delete_provider_inner(&second.id).unwrap();
fs::remove_dir_all(codex_dir).unwrap();
}
}
+16 -14
View File
@@ -2,6 +2,7 @@ mod ccswitch;
mod connection;
mod live;
mod official_auth;
pub(crate) mod official_profiles;
mod selection;
mod store;
@@ -25,21 +26,22 @@ pub(crate) use connection::{
};
pub(crate) use live::detected_live_custom_provider;
pub(crate) use live::{
build_provider_toml_draft_inner, delete_saved_provider_inner, reset_official_provider_inner,
restore_official_provider_inner, save_active_provider_inner, save_official_config_inner,
save_provider_toml_config_inner, switch_official_provider_inner, switch_provider_inner,
build_provider_toml_draft_inner, delete_saved_provider_inner, save_active_provider_inner,
save_official_config_inner, save_provider_toml_config_inner, switch_provider_inner,
OfficialConfigInput, ProviderInput, ProviderTomlInput,
};
#[cfg(test)]
pub(crate) use live::{
save_provider_toml_config_with_pre_persist, switch_official_provider_with_pre_persist,
switch_provider_with_pre_persist,
reset_official_provider_inner, restore_official_provider_inner,
save_provider_toml_config_with_pre_persist, switch_official_provider_inner,
switch_official_provider_with_pre_persist, switch_provider_with_pre_persist,
};
#[cfg(test)]
pub(crate) use official_auth::{capture_live_chatgpt_config, official_snapshot_path_for_test};
pub(crate) use official_auth::{
document_is_official, get_official_config_draft_inner, official_auth_available,
OfficialConfigDraft,
capture_live_chatgpt_config, get_official_config_draft_inner, official_snapshot_path_for_test,
};
pub(crate) use official_auth::{
document_is_official, official_auth_available, OfficialConfigDraft,
};
pub(crate) use selection::{
clear_active_provider_on_connection, clear_provider_selections_on_connection,
@@ -52,14 +54,14 @@ pub(crate) use store::{
};
pub(crate) use store::{
consolidate_legacy_provider_duplicates_on_connection, custom_provider_id,
delete_provider_inner, experimental_bearer_token_from_doc, is_placeholder_provider,
list_saved_providers_inner, list_saved_providers_on_connection,
delete_provider_inner, duplicate_provider_inner, experimental_bearer_token_from_doc,
is_placeholder_provider, list_saved_providers_inner, list_saved_providers_on_connection,
matching_saved_provider_ids_for_live, normalize_saved_provider,
normalize_saved_provider_for_save, provider_template_from_document, reserved_codex_provider_id,
rollback_provider_store_inner, save_provider_inner, save_provider_with_rollback_inner,
strip_provider_bearer_tokens, unique_saved_provider_id_for_live,
upsert_ccswitch_provider_on_connection, ProviderStoreRollback, ProviderUpsertKind,
SavedProvider,
rollback_provider_store_inner, save_detected_provider_with_rollback_inner, save_provider_inner,
save_provider_with_rollback_inner, strip_provider_bearer_tokens,
upsert_ccswitch_provider_on_connection, DuplicateProviderResult, ProviderStoreRollback,
ProviderUpsertKind, SavedProvider,
};
pub(crate) fn open_store() -> Result<Connection> {
@@ -1,3 +1,6 @@
use super::official_profiles::{
has_named_profiles, selected_profile_id, DEFAULT_OFFICIAL_PROFILE_ID,
};
use crate::backups::{action_backup_root, BackupMeta};
use crate::error::{CodexxError, Result};
use crate::file_io::{ensure_directory, io_err, parse_toml_document, write_private_json};
@@ -27,10 +30,10 @@ pub(crate) struct OfficialConfigCandidate {
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct OfficialConfigDraft {
auth_json: String,
config_text: String,
model: Option<String>,
source: String,
pub(crate) auth_json: String,
pub(crate) config_text: String,
pub(crate) model: Option<String>,
pub(crate) source: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -60,11 +63,29 @@ fn canonical_identity(path: &Path) -> String {
}
pub(crate) fn official_snapshot_path(codex_dir: &Path) -> Result<PathBuf> {
let profile_id = selected_profile_id(codex_dir)?;
official_snapshot_path_for_profile(codex_dir, &profile_id)
}
pub(crate) fn official_snapshot_path_for_profile(
codex_dir: &Path,
profile_id: &str,
) -> Result<PathBuf> {
if profile_id.trim().is_empty() {
return Err(CodexxError::Config("官方配置 ID 不能为空".to_string()));
}
let identity = canonical_identity(codex_dir);
let digest = Sha256::digest(identity.as_bytes());
Ok(app_home()?
.join("official-configs")
.join(format!("{digest:x}.json")))
let root = app_home()?.join("official-configs");
if profile_id == DEFAULT_OFFICIAL_PROFILE_ID {
// The built-in profile keeps the legacy recovery path so existing
// installations can restore their saved official login unchanged.
return Ok(root.join(format!("{digest:x}.json")));
}
let profile_digest = Sha256::digest(profile_id.as_bytes());
Ok(root
.join(format!("{digest:x}"))
.join(format!("{profile_digest:x}.json")))
}
fn value_has_material(value: &Value) -> bool {
@@ -306,7 +327,26 @@ fn write_snapshot(
model: Option<String>,
auth: Option<Value>,
) -> Result<()> {
let path = official_snapshot_path(codex_dir)?;
let profile_id = selected_profile_id(codex_dir)?;
write_official_profile_snapshot(codex_dir, &profile_id, config, model, auth)
}
pub(crate) fn write_official_profile_snapshot(
codex_dir: &Path,
profile_id: &str,
config: Option<String>,
model: Option<String>,
auth: Option<Value>,
) -> Result<()> {
if auth
.as_ref()
.is_some_and(|auth| !auth.is_object() || !auth_value_has_material(auth))
{
return Err(CodexxError::Config(
"官方 auth.json 没有可用认证信息,请先完成官方登录".to_string(),
));
}
let path = official_snapshot_path_for_profile(codex_dir, profile_id)?;
if let Some(parent) = path.parent() {
ensure_directory(parent)?;
}
@@ -329,14 +369,10 @@ pub(crate) fn save_official_config_snapshot(
model: Option<String>,
auth: &Value,
) -> Result<()> {
if !auth.is_object() || !auth_value_has_material(auth) {
return Err(CodexxError::Config(
"官方 auth.json 没有可用认证信息,请先完成官方登录".to_string(),
));
}
write_snapshot(codex_dir, config, model, Some(auth.clone()))
}
#[cfg(test)]
pub(crate) fn mark_official_config_reset(
codex_dir: &Path,
config: Option<String>,
@@ -370,7 +406,8 @@ pub(crate) fn capture_live_official_config_before_provider_switch(
is_chatgpt_auth(auth) || (has_explicit_official_route && has_openai_api_key(auth))
});
let previous = match load_snapshot(codex_dir)? {
let profile_id = selected_profile_id(codex_dir)?;
let previous = match load_snapshot_for_profile(codex_dir, &profile_id)? {
SnapshotState::Ready(candidate) | SnapshotState::Reset(candidate) => Some(candidate),
SnapshotState::Missing => None,
};
@@ -387,11 +424,18 @@ pub(crate) fn capture_live_official_config_before_provider_switch(
let previous_auth = previous
.as_ref()
.and_then(|candidate| candidate.auth.clone());
let auth = prefer_chatgpt_auth(live_auth, previous_auth);
let auth = if profile_id == DEFAULT_OFFICIAL_PROFILE_ID {
prefer_chatgpt_auth(live_auth, previous_auth)
} else {
// A named profile is the user's selected working configuration. Its
// current official login belongs to that profile, including an
// intentional change between OAuth and API-key authentication.
live_auth.or(previous_auth)
};
if config.is_none() && auth.is_none() {
return Ok(false);
}
write_snapshot(codex_dir, config, model, auth)?;
write_official_profile_snapshot(codex_dir, &profile_id, config, model, auth)?;
Ok(true)
}
@@ -424,8 +468,8 @@ pub(crate) fn capture_live_chatgpt_config(codex_dir: &Path) -> Result<bool> {
capture_live_official_auth(codex_dir, is_chatgpt_auth)
}
fn load_snapshot(codex_dir: &Path) -> Result<SnapshotState> {
let path = official_snapshot_path(codex_dir)?;
fn load_snapshot_for_profile(codex_dir: &Path, profile_id: &str) -> Result<SnapshotState> {
let path = official_snapshot_path_for_profile(codex_dir, profile_id)?;
if !path.is_file() {
return Ok(SnapshotState::Missing);
}
@@ -440,6 +484,18 @@ fn load_snapshot(codex_dir: &Path) -> Result<SnapshotState> {
Ok(snapshot_state(codex_dir, &path, snapshot).unwrap_or(SnapshotState::Missing))
}
pub(crate) fn saved_official_profile_candidate(
codex_dir: &Path,
profile_id: &str,
) -> Result<Option<OfficialConfigCandidate>> {
// Explicit account selection must never consult the live login or an
// unrelated historical backup, even when the requested snapshot is empty.
match load_snapshot_for_profile(codex_dir, profile_id)? {
SnapshotState::Ready(candidate) | SnapshotState::Reset(candidate) => Ok(Some(candidate)),
SnapshotState::Missing => Ok(None),
}
}
fn prefer_chatgpt_auth(primary: Option<Value>, fallback: Option<Value>) -> Option<Value> {
if primary.as_ref().is_some_and(is_chatgpt_auth) {
return primary;
@@ -606,8 +662,11 @@ fn live_auth_candidate(
}))
}
fn live_chatgpt_candidate(codex_dir: &Path) -> Result<Option<OfficialConfigCandidate>> {
live_auth_candidate(codex_dir, false, is_chatgpt_auth)
fn live_chatgpt_candidate(
codex_dir: &Path,
allow_proxy_route: bool,
) -> Result<Option<OfficialConfigCandidate>> {
live_auth_candidate(codex_dir, !allow_proxy_route, is_chatgpt_auth)
}
fn live_official_auth_candidate(codex_dir: &Path) -> Result<Option<OfficialConfigCandidate>> {
@@ -639,18 +698,42 @@ fn complete_candidate_config(
Ok(candidate)
}
fn selected_named_profile_candidate(
codex_dir: &Path,
profile_id: &str,
) -> Result<Option<OfficialConfigCandidate>> {
let saved = saved_official_profile_candidate(codex_dir, profile_id)?;
// The selected profile owns login/refreshes only while its official
// route is active. OAuth left under a proxy route may belong to a
// different account and must never replace an explicitly saved login.
if let Some(live) = live_official_auth_candidate(codex_dir)? {
return complete_candidate_config(codex_dir, live, saved.as_ref()).map(Some);
}
saved
.map(|candidate| complete_candidate_config(codex_dir, candidate, None))
.transpose()
}
pub(crate) fn official_config_candidate(
codex_dir: &Path,
include_history_after_reset: bool,
) -> Result<Option<OfficialConfigCandidate>> {
match load_snapshot(codex_dir)? {
let profile_id = selected_profile_id(codex_dir)?;
if profile_id != DEFAULT_OFFICIAL_PROFILE_ID {
return selected_named_profile_candidate(codex_dir, &profile_id);
}
// Legacy backups and OAuth left under proxy routes do not record which
// account they belong to. Keep their old recovery behavior only while
// there are no named accounts that they could be confused with.
let allow_legacy_recovery = !has_named_profiles(codex_dir)?;
match load_snapshot_for_profile(codex_dir, &profile_id)? {
SnapshotState::Ready(candidate) => {
// A third-party route may deliberately keep the user's ChatGPT
// login in auth.json and carry its own key in
// experimental_bearer_token. Prefer that live OAuth value so a
// token refresh during proxy use is not replaced by an older
// official snapshot when switching back.
if let Some(live) = live_chatgpt_candidate(codex_dir)? {
// experimental_bearer_token. In legacy single-account mode,
// preserve token refreshes made during proxy use. With named
// profiles, only trust live OAuth under the official route.
if let Some(live) = live_chatgpt_candidate(codex_dir, allow_legacy_recovery)? {
return complete_candidate_config(codex_dir, live, Some(&candidate)).map(Some);
}
// Never let an API-key-only live file silently downgrade a trusted
@@ -664,11 +747,11 @@ pub(crate) fn official_config_candidate(
}
return complete_candidate_config(codex_dir, candidate, None).map(Some);
}
SnapshotState::Reset(reset) if !include_history_after_reset => {
SnapshotState::Reset(reset) if !include_history_after_reset || !allow_legacy_recovery => {
if let Some(live) = live_official_auth_candidate(codex_dir)? {
return complete_candidate_config(codex_dir, live, Some(&reset)).map(Some);
}
if let Some(live) = live_chatgpt_candidate(codex_dir)? {
if let Some(live) = live_chatgpt_candidate(codex_dir, allow_legacy_recovery)? {
return complete_candidate_config(codex_dir, live, Some(&reset)).map(Some);
}
return complete_candidate_config(codex_dir, reset, None).map(Some);
@@ -677,7 +760,7 @@ pub(crate) fn official_config_candidate(
if let Some(live) = live_official_auth_candidate(codex_dir)? {
return complete_candidate_config(codex_dir, live, Some(&reset)).map(Some);
}
if let Some(live) = live_chatgpt_candidate(codex_dir)? {
if let Some(live) = live_chatgpt_candidate(codex_dir, allow_legacy_recovery)? {
return complete_candidate_config(codex_dir, live, Some(&reset)).map(Some);
}
if let Some(mut backup) = latest_official_backup(codex_dir)? {
@@ -692,8 +775,12 @@ pub(crate) fn official_config_candidate(
SnapshotState::Missing => {}
}
let backup = latest_official_backup(codex_dir)?;
if let Some(candidate) = live_chatgpt_candidate(codex_dir)? {
let backup = if allow_legacy_recovery {
latest_official_backup(codex_dir)?
} else {
None
};
if let Some(candidate) = live_chatgpt_candidate(codex_dir, allow_legacy_recovery)? {
return complete_candidate_config(codex_dir, candidate, backup.as_ref()).map(Some);
}
backup
@@ -702,7 +789,8 @@ pub(crate) fn official_config_candidate(
}
pub(crate) fn official_auth_available(codex_dir: &Path) -> Result<bool> {
match load_snapshot(codex_dir)? {
let profile_id = selected_profile_id(codex_dir)?;
match load_snapshot_for_profile(codex_dir, &profile_id)? {
SnapshotState::Ready(_) => return Ok(true),
SnapshotState::Reset(_) => return Ok(live_official_auth_candidate(codex_dir)?.is_some()),
SnapshotState::Missing => {}
@@ -710,6 +798,9 @@ pub(crate) fn official_auth_available(codex_dir: &Path) -> Result<bool> {
if live_official_auth_candidate(codex_dir)?.is_some() {
return Ok(true);
}
if profile_id != DEFAULT_OFFICIAL_PROFILE_ID || has_named_profiles(codex_dir)? {
return Ok(false);
}
if let Some(auth) = read_auth_value(&auth_path(codex_dir))? {
if is_chatgpt_auth(&auth) {
return Ok(true);
@@ -720,6 +811,7 @@ pub(crate) fn official_auth_available(codex_dir: &Path) -> Result<bool> {
Ok(false)
}
#[cfg(test)]
pub(crate) fn get_official_config_draft_inner(
config_dir: Option<String>,
) -> Result<Option<OfficialConfigDraft>> {
@@ -740,6 +832,7 @@ pub(crate) fn get_official_config_draft_inner(
official_config_draft(candidate).map(Some)
}
#[cfg(test)]
fn official_config_draft(candidate: OfficialConfigCandidate) -> Result<OfficialConfigDraft> {
let auth_json = candidate
.auth
@@ -766,6 +859,302 @@ mod tests {
use super::*;
use serde_json::json;
fn profile_test_dir(name: &str) -> PathBuf {
let path = std::env::temp_dir().join(format!(
"codex-x-official-profile-{name}-{}-{}",
std::process::id(),
Local::now().timestamp_nanos_opt().unwrap_or_default()
));
fs::create_dir_all(&path).expect("create profile test Codex directory");
path
}
#[test]
fn profile_snapshot_paths_keep_legacy_default_and_isolate_accounts_and_homes() {
let codex_dir = profile_test_dir("paths");
let other_home = profile_test_dir("other-home");
let digest = Sha256::digest(canonical_identity(&codex_dir).as_bytes());
let default_path =
official_snapshot_path_for_profile(&codex_dir, DEFAULT_OFFICIAL_PROFILE_ID)
.expect("default snapshot path");
assert_eq!(
default_path,
app_home()
.unwrap()
.join("official-configs")
.join(format!("{digest:x}.json"))
);
let first = official_snapshot_path_for_profile(&codex_dir, "account-a").unwrap();
let second = official_snapshot_path_for_profile(&codex_dir, "account-b").unwrap();
let elsewhere = official_snapshot_path_for_profile(&other_home, "account-a").unwrap();
assert_ne!(first, default_path);
assert_ne!(first, second);
assert_ne!(first, elsewhere);
assert_eq!(first.parent(), second.parent());
assert!(official_snapshot_path_for_profile(&codex_dir, " ").is_err());
fs::remove_dir_all(codex_dir).unwrap();
fs::remove_dir_all(other_home).unwrap();
}
#[test]
fn explicit_profile_snapshot_reads_never_borrow_other_auth_and_preserve_resets() {
let codex_dir = profile_test_dir("explicit-read");
let live_auth = json!({"tokens": {"access_token": "other-account"}});
fs::write(
config_path(&codex_dir),
"model_provider = \"openai\"\nmodel = \"live-model\"\n",
)
.unwrap();
fs::write(
auth_path(&codex_dir),
serde_json::to_vec(&live_auth).unwrap(),
)
.unwrap();
write_official_profile_snapshot(
&codex_dir,
DEFAULT_OFFICIAL_PROFILE_ID,
None,
None,
Some(live_auth),
)
.unwrap();
assert!(
saved_official_profile_candidate(&codex_dir, "missing-account")
.unwrap()
.is_none()
);
let profile_id = "saved-account";
let saved_auth = json!({"tokens": {"access_token": "saved-account"}});
write_official_profile_snapshot(
&codex_dir,
profile_id,
None,
Some("saved-model".to_string()),
Some(saved_auth.clone()),
)
.unwrap();
let candidate = saved_official_profile_candidate(&codex_dir, profile_id)
.unwrap()
.unwrap();
assert_eq!(candidate.auth, Some(saved_auth));
assert!(candidate.config_text.is_none());
assert_eq!(candidate.model.as_deref(), Some("saved-model"));
let path = official_snapshot_path_for_profile(&codex_dir, profile_id).unwrap();
let before = fs::read(&path).unwrap();
assert!(write_official_profile_snapshot(
&codex_dir,
profile_id,
None,
None,
Some(json!({"auth_mode": "chatgpt"})),
)
.is_err());
assert_eq!(fs::read(&path).unwrap(), before);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(
fs::metadata(&path).unwrap().permissions().mode() & 0o777,
0o600
);
}
let reset_config = "model_provider = \"openai\"\nmodel = \"reset-model\"\n";
write_official_profile_snapshot(
&codex_dir,
profile_id,
Some(reset_config.to_string()),
Some("reset-model".to_string()),
None,
)
.unwrap();
let reset = saved_official_profile_candidate(&codex_dir, profile_id)
.unwrap()
.unwrap();
assert!(reset.auth.is_none());
assert_eq!(reset.config_text.as_deref(), Some(reset_config));
fs::remove_file(path).unwrap();
fs::remove_file(
official_snapshot_path_for_profile(&codex_dir, DEFAULT_OFFICIAL_PROFILE_ID).unwrap(),
)
.unwrap();
fs::remove_dir_all(codex_dir).unwrap();
}
#[test]
fn selected_named_profile_accepts_official_refresh_but_ignores_proxy_login() {
let codex_dir = profile_test_dir("refresh");
let profile_id = "selected-account";
let saved_config = "model_provider = \"openai\"\nmodel = \"saved-model\"\n";
let saved_auth = json!({"tokens": {"access_token": "saved-token"}});
let refreshed_auth = json!({"tokens": {"access_token": "refreshed-token"}});
write_official_profile_snapshot(
&codex_dir,
profile_id,
Some(saved_config.to_string()),
Some("saved-model".to_string()),
Some(saved_auth.clone()),
)
.unwrap();
fs::write(
config_path(&codex_dir),
"model_provider = \"custom\"\nmodel = \"proxy-model\"\n[model_providers.custom]\nname = \"Proxy\"\nbase_url = \"https://proxy.example/v1\"\n",
)
.unwrap();
fs::write(
auth_path(&codex_dir),
serde_json::to_vec(&refreshed_auth).unwrap(),
)
.unwrap();
let candidate = selected_named_profile_candidate(&codex_dir, profile_id)
.unwrap()
.unwrap();
assert_eq!(candidate.auth, Some(saved_auth));
assert_eq!(candidate.config_text.as_deref(), Some(saved_config));
write_official_profile_snapshot(
&codex_dir,
profile_id,
Some(saved_config.to_string()),
Some("saved-model".to_string()),
None,
)
.unwrap();
assert!(selected_named_profile_candidate(&codex_dir, profile_id)
.unwrap()
.unwrap()
.auth
.is_none());
let live_config = "model_provider = \"openai\"\nmodel = \"fresh-model\"\n";
fs::write(config_path(&codex_dir), live_config).unwrap();
let refreshed = selected_named_profile_candidate(&codex_dir, profile_id)
.unwrap()
.unwrap();
assert_eq!(refreshed.auth, Some(refreshed_auth));
assert_eq!(refreshed.config_text.as_deref(), Some(live_config));
let api_key_auth = json!({"OPENAI_API_KEY": "official-key"});
fs::write(
auth_path(&codex_dir),
serde_json::to_vec(&api_key_auth).unwrap(),
)
.unwrap();
assert_eq!(
selected_named_profile_candidate(&codex_dir, profile_id)
.unwrap()
.unwrap()
.auth,
Some(api_key_auth)
);
fs::remove_file(official_snapshot_path_for_profile(&codex_dir, profile_id).unwrap())
.unwrap();
fs::remove_dir_all(codex_dir).unwrap();
}
#[test]
fn default_profile_ignores_proxy_oauth_once_named_profiles_exist() {
let codex_dir = profile_test_dir("default-proxy-isolation");
let default_auth = json!({"tokens": {"access_token": "default-account"}});
let proxy_auth = json!({"tokens": {"access_token": "other-account"}});
let official_config = "model_provider = \"openai\"\nmodel = \"official-model\"\n";
fs::write(
config_path(&codex_dir),
"model_provider = \"custom\"\n[model_providers.custom]\nname = \"Proxy\"\nbase_url = \"https://proxy.example/v1\"\n",
)
.unwrap();
fs::write(
auth_path(&codex_dir),
serde_json::to_vec(&proxy_auth).unwrap(),
)
.unwrap();
write_official_profile_snapshot(
&codex_dir,
DEFAULT_OFFICIAL_PROFILE_ID,
Some(official_config.to_string()),
Some("official-model".to_string()),
Some(default_auth.clone()),
)
.unwrap();
// Preserve existing single-account recovery of OAuth refreshed while
// a proxy route is active.
assert!(!has_named_profiles(&codex_dir).unwrap());
assert_eq!(
official_config_candidate(&codex_dir, false)
.unwrap()
.unwrap()
.auth,
Some(proxy_auth.clone())
);
let conn = crate::providers::open_store().unwrap();
let scope = crate::paths::normalized_path_scope(&codex_dir);
conn.execute(
"INSERT INTO official_profiles (codex_dir, id, provider_name, created_at, updated_at)
VALUES (?1, 'another-account', 'Another account', 'test', 'test')",
[&scope],
)
.unwrap();
assert!(has_named_profiles(&codex_dir).unwrap());
assert_eq!(
selected_profile_id(&codex_dir).unwrap(),
DEFAULT_OFFICIAL_PROFILE_ID
);
let saved = official_config_candidate(&codex_dir, false)
.unwrap()
.unwrap();
assert_eq!(saved.auth, Some(default_auth));
assert_eq!(saved.config_text.as_deref(), Some(official_config));
write_official_profile_snapshot(
&codex_dir,
DEFAULT_OFFICIAL_PROFILE_ID,
Some(official_config.to_string()),
Some("official-model".to_string()),
None,
)
.unwrap();
for include_history in [false, true] {
assert!(official_config_candidate(&codex_dir, include_history)
.unwrap()
.unwrap()
.auth
.is_none());
}
assert!(!official_auth_available(&codex_dir).unwrap());
let default_path =
official_snapshot_path_for_profile(&codex_dir, DEFAULT_OFFICIAL_PROFILE_ID).unwrap();
fs::remove_file(default_path).unwrap();
for include_history in [false, true] {
assert!(official_config_candidate(&codex_dir, include_history)
.unwrap()
.is_none());
}
assert!(!official_auth_available(&codex_dir).unwrap());
// Login and refreshes performed in the selected official profile
// remain usable after multiple accounts have been added.
fs::write(config_path(&codex_dir), official_config).unwrap();
assert_eq!(
official_config_candidate(&codex_dir, false)
.unwrap()
.unwrap()
.auth,
Some(proxy_auth)
);
assert!(official_auth_available(&codex_dir).unwrap());
conn.execute(
"DELETE FROM official_profiles WHERE codex_dir = ?1",
[&scope],
)
.unwrap();
fs::remove_dir_all(codex_dir).unwrap();
}
#[test]
fn legacy_oauth_without_auth_mode_is_trusted() {
assert!(is_chatgpt_auth(&json!({
File diff suppressed because it is too large Load Diff
+248 -1
View File
@@ -282,7 +282,8 @@ pub(crate) fn matching_saved_provider_ids_for_live(
.collect()
}
pub(crate) fn unique_saved_provider_id_for_live(
#[cfg(test)]
fn unique_saved_provider_id_for_live(
live: &SavedProvider,
providers: &[SavedProvider],
) -> Option<String> {
@@ -800,6 +801,98 @@ pub(crate) fn save_provider_inner(provider: SavedProvider) -> Result<SavedProvid
save_manual_provider_on_connection(&conn, provider)
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct DuplicateProviderResult {
pub(crate) provider: SavedProvider,
pub(crate) providers: Vec<SavedProvider>,
pub(crate) active_provider_id: Option<String>,
}
pub(crate) fn duplicate_provider_inner(
config_dir: Option<String>,
provider_id: Option<String>,
provider_name: Option<String>,
) -> Result<DuplicateProviderResult> {
let codex_dir = crate::resolve_codex_dir(config_dir)?;
let _lock = crate::live_config::acquire_live_config_lock(&codex_dir)?;
let live = super::live::detected_live_custom_provider(&codex_dir)?;
duplicate_provider_on_connection(
&mut open_db()?,
&codex_dir,
live,
provider_id.as_deref(),
provider_name.as_deref(),
)
}
fn duplicate_provider_on_connection(
conn: &mut Connection,
codex_dir: &std::path::Path,
live: Option<SavedProvider>,
provider_id: Option<&str>,
provider_name: Option<&str>,
) -> Result<DuplicateProviderResult> {
let transaction = conn
.transaction_with_behavior(TransactionBehavior::Immediate)
.map_err(|error| CodexxError::Database(error.to_string()))?;
let mut saved = list_saved_providers_on_connection(&transaction)?;
let source = if let Some(id) = provider_id {
provider_by_id_on_connection(&transaction, id)?
.ok_or_else(|| CodexxError::Config("供应商已不存在,请刷新列表后重试".to_string()))?
} else {
let mut detected = live.clone().ok_or_else(|| {
CodexxError::Config("当前第三方配置已变更,请刷新列表后重试".to_string())
})?;
// Adopt an unsaved detected original before adding its copy. Otherwise
// the copy would become the only matching row and appear to be enabled.
if matching_saved_provider_ids_for_live(&detected, &saved).is_empty() {
detected.id = unique_provider_id_on_connection(
&transaction,
&custom_provider_id(&detected.provider_name),
)?;
detected = save_manual_provider_on_connection(&transaction, detected)?;
saved.push(detected.clone());
}
detected
};
let active_provider_id = if let Some(live) = live.as_ref() {
super::reconcile_active_provider_on_connection(
&transaction,
codex_dir,
&matching_saved_provider_ids_for_live(live, &saved),
)?
} else {
None
};
let base_name = provider_name
.map(str::trim)
.filter(|name| !name.is_empty())
.map(ToString::to_string)
.unwrap_or_else(|| format!("{} 副本", source.provider_name));
let mut copy = source.clone();
copy.id = unique_provider_id_on_connection(&transaction, &format!("{}-copy", source.id))?;
copy.provider_name = base_name.clone();
let mut suffix = 2;
while saved
.iter()
.any(|provider| provider.provider_name == copy.provider_name)
{
copy.provider_name = format!("{base_name} {suffix}");
suffix += 1;
}
let provider = save_manual_provider_on_connection(&transaction, copy)?;
let providers = list_saved_providers_on_connection(&transaction)?;
transaction
.commit()
.map_err(|error| CodexxError::Database(error.to_string()))?;
Ok(DuplicateProviderResult {
provider,
providers,
active_provider_id,
})
}
pub(crate) fn save_provider_with_rollback_inner(
provider: SavedProvider,
) -> Result<(SavedProvider, ProviderStoreRollback)> {
@@ -816,6 +909,49 @@ pub(crate) fn save_provider_with_rollback_inner(
Ok((saved, ProviderStoreRollback { before, after }))
}
pub(crate) fn save_detected_provider_with_rollback_inner(
mut live: SavedProvider,
) -> Result<Option<ProviderStoreRollback>> {
let mut conn = open_db()?;
let transaction = conn
.transaction_with_behavior(TransactionBehavior::Immediate)
.map_err(|error| CodexxError::Database(error.to_string()))?;
let before = stored_providers_on_connection(&transaction)?;
let saved = before
.iter()
.map(|stored| stored.provider.clone())
.collect::<Vec<_>>();
let matches = matching_saved_provider_ids_for_live(&live, &saved);
match matches.as_slice() {
[saved_id] => {
if live.api_key.is_none() {
live.api_key = saved
.iter()
.find(|provider| &provider.id == saved_id)
.and_then(|provider| provider.api_key.clone());
}
live.id = saved_id.clone();
}
[] => {
// A detected live route is only a temporary UI row until a write
// action adopts it. Preserve it before replacing config/auth, and
// allocate its ID under the same transaction to avoid overwriting
// an unrelated manual profile or a concurrent adoption.
live.id = unique_provider_id_on_connection(
&transaction,
&custom_provider_id(&live.provider_name),
)?;
}
_ => return Ok(None),
}
save_manual_provider_on_connection(&transaction, live)?;
let after = stored_providers_on_connection(&transaction)?;
transaction
.commit()
.map_err(|error| CodexxError::Database(error.to_string()))?;
Ok(Some(ProviderStoreRollback { before, after }))
}
fn insert_stored_provider(conn: &Connection, stored: &StoredProvider) -> Result<()> {
let provider = &stored.provider;
conn.execute(
@@ -988,6 +1124,117 @@ mod tests {
list_saved_providers_on_connection(conn).unwrap().len()
}
fn copy_test_connection() -> Connection {
let conn = test_connection();
conn.execute_batch("CREATE TABLE active_provider_selections (codex_dir TEXT PRIMARY KEY, provider_id TEXT NOT NULL, updated_at TEXT NOT NULL);").unwrap();
conn
}
#[test]
fn immediate_copy_preserves_original_selection_and_complete_template() {
let mut conn = copy_test_connection();
let dir = std::path::Path::new("/fixture/copy-selection");
let mut original = provider("original", "Original", Some("fixture-key"));
original.toml_config = Some("model = \"gpt-5.5\"\nmodel_provider = \"custom\"\nmodel_context_window = 1000000\n[model_providers.custom]\nname = \"Original\"\nbase_url = \"https://example.com/v1\"\nwire_api = \"responses\"\n[mcp_servers.keep]\ncommand = \"fixture\"\n".to_string());
let original = save_manual_provider_on_connection(&conn, original).unwrap();
let first = duplicate_provider_on_connection(
&mut conn,
dir,
Some(original.clone()),
Some(&original.id),
None,
)
.unwrap();
assert_eq!(
first.active_provider_id.as_deref(),
Some(original.id.as_str())
);
assert_ne!(first.provider.id, original.id);
assert_eq!(first.provider.api_key, original.api_key);
assert_eq!(first.provider.provider_name, "Original 副本");
let config = first
.provider
.toml_config
.as_ref()
.unwrap()
.parse::<DocumentMut>()
.unwrap();
assert_eq!(config["model_context_window"].as_integer(), Some(1_000_000));
assert_eq!(
config["mcp_servers"]["keep"]["command"].as_str(),
Some("fixture")
);
assert_eq!(
provider_by_id_on_connection(&conn, &original.id)
.unwrap()
.unwrap(),
original
);
let second = duplicate_provider_on_connection(
&mut conn,
dir,
Some(original.clone()),
Some(&original.id),
None,
)
.unwrap();
assert_eq!(second.provider.provider_name, "Original 副本 2");
assert_eq!(
second.active_provider_id.as_deref(),
Some(original.id.as_str())
);
assert_ne!(second.provider.id, first.provider.id);
}
#[test]
fn immediate_copy_adopts_detected_original_without_enabling_the_copy() {
let mut conn = copy_test_connection();
let dir = std::path::Path::new("/fixture/copy-detected");
let live = provider("custom", "Detected", Some("fixture-key"));
let result =
duplicate_provider_on_connection(&mut conn, dir, Some(live.clone()), None, None)
.unwrap();
assert_eq!(result.providers.len(), 2);
let original = result
.providers
.iter()
.find(|provider| provider.id != result.provider.id)
.unwrap();
assert_eq!(original.provider_name, live.provider_name);
assert_eq!(
result.active_provider_id.as_deref(),
Some(original.id.as_str())
);
assert_ne!(
result.active_provider_id.as_deref(),
Some(result.provider.id.as_str())
);
}
#[test]
fn failed_immediate_copy_rolls_back_detected_adoption_and_selection() {
let mut conn = copy_test_connection();
conn.execute_batch("CREATE TRIGGER fail_copy BEFORE INSERT ON providers WHEN NEW.provider_name LIKE '%副本%' BEGIN SELECT RAISE(ABORT, 'fixture failure'); END;").unwrap();
let result = duplicate_provider_on_connection(
&mut conn,
std::path::Path::new("/fixture/copy-failure"),
Some(provider("custom", "Detected", Some("fixture-key"))),
None,
None,
);
assert!(result.is_err());
assert_eq!(provider_count(&conn), 0);
assert_eq!(
conn.query_row(
"SELECT COUNT(*) FROM active_provider_selections",
[],
|row| row.get::<_, i64>(0)
)
.unwrap(),
0
);
}
#[test]
fn provider_upsert_uses_record_ids_and_stable_import_sources() {
let stable = test_connection();
+4 -1
View File
@@ -15,11 +15,14 @@ pub(crate) use backup::{
#[cfg(test)]
pub(crate) use delete::{active_session_ids_present, hard_delete_sessions_locally};
pub(crate) use delete::{delete_codex_sessions_inner, SessionDeleteInput, SessionDeleteResult};
pub(crate) use storage::sqlite_candidate_paths;
#[cfg(test)]
pub(crate) use storage::{
apply_session_changes, list_session_previews, restore_session_changes, scan_rollouts,
scan_sqlite, sqlite_session_db_paths,
};
pub(crate) use storage::{
session_project_title, session_titles_by_id, source_value_is_subagent, sqlite_candidate_paths,
usage_thread_identities, UsageThreadIdentity,
};
pub(crate) use sync::{session_sync_status_inner, sync_sessions_provider_inner};
pub(crate) use types::{SessionSyncResult, SessionSyncStatus};
+608 -9
View File
@@ -13,7 +13,7 @@ use std::collections::{HashMap, HashSet};
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use std::time::{Duration, SystemTime};
use toml_edit::DocumentMut;
pub(super) fn current_model_provider(codex_dir: &Path, explicit: Option<String>) -> Result<String> {
@@ -700,12 +700,15 @@ fn sqlite_state_version(path: &Path) -> Option<u64> {
.and_then(|value| value.parse::<u64>().ok())
}
fn sqlite_table_names(path: &Path) -> Option<HashSet<String>> {
fn sqlite_table_names(path: &Path, busy_timeout: Option<Duration>) -> Option<HashSet<String>> {
let conn = Connection::open_with_flags(
path,
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
)
.ok()?;
if let Some(timeout) = busy_timeout {
conn.busy_timeout(timeout).ok()?;
}
let mut stmt = conn
.prepare("SELECT name FROM sqlite_master WHERE type = 'table'")
.ok()?;
@@ -778,6 +781,13 @@ fn ordered_database_paths(
}
pub(super) fn discover_sqlite_databases(codex_dir: &Path) -> SqliteDiscovery {
discover_sqlite_databases_with_busy_timeout(codex_dir, None)
}
fn discover_sqlite_databases_with_busy_timeout(
codex_dir: &Path,
busy_timeout: Option<Duration>,
) -> SqliteDiscovery {
let mut databases = Vec::new();
let mut seen_paths = HashSet::new();
let mut unreadable_paths = Vec::new();
@@ -838,7 +848,7 @@ pub(super) fn discover_sqlite_databases(codex_dir: &Path) -> SqliteDiscovery {
continue;
}
let codex_named = is_root_codex_sqlite_file(&path);
let Some(tables) = sqlite_table_names(&path) else {
let Some(tables) = sqlite_table_names(&path, busy_timeout) else {
let header_is_sqlite = has_sqlite_header(&path);
let read_error = fs::File::open(&path).err();
if header_is_sqlite || read_error.is_some() {
@@ -912,6 +922,116 @@ pub(crate) fn sqlite_candidate_paths(codex_dir: &Path) -> Vec<PathBuf> {
discover_sqlite_databases(codex_dir).active_paths
}
fn clean_session_title(values: [Option<String>; 3]) -> Option<String> {
values
.into_iter()
.flatten()
.map(|value| value.trim().to_string())
.find(|value| !value.is_empty())
}
pub(crate) fn session_project_title(cwd: &str) -> Option<String> {
let path = normalize_workspace_path(cwd)?.replace('\\', "/");
if path.chars().any(char::is_control) || path.contains("://") {
return None;
}
let parts = path
.split('/')
.filter(|part| !part.is_empty())
.collect::<Vec<_>>();
// A UNC share root is a storage location, rather than a project directory.
if path.starts_with("//") && parts.len() <= 2 {
return None;
}
let name = parts.last()?.trim();
if name.is_empty()
|| matches!(name, "." | ".." | "~")
|| (name.len() == 2 && name.as_bytes()[0].is_ascii_alphabetic() && name.ends_with(':'))
{
return None;
}
Some(name.to_string())
}
/// Best-effort titles for the small recent-usage list. Read only the requested
/// IDs and re-read metadata on each refresh so renamed chats appear immediately.
pub(crate) fn session_titles_by_id(codex_dir: &Path, ids: &[String]) -> HashMap<String, String> {
let ids = ids
.iter()
.map(|id| id.trim())
.filter(|id| !id.is_empty())
.collect::<HashSet<_>>();
if ids.is_empty() {
return HashMap::new();
}
let timeout = Duration::from_millis(50);
let discovery = discover_sqlite_databases_with_busy_timeout(codex_dir, Some(timeout));
let mut titles = HashMap::new();
let mut projects = HashMap::new();
for path in discovery.active_first_session_paths() {
let Ok(conn) = Connection::open_with_flags(
&path,
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
) else {
continue;
};
if conn.busy_timeout(timeout).is_err()
|| !sqlite_has_table(&conn, "threads").unwrap_or(false)
{
continue;
}
let Ok(cols) = table_column_set(&conn, "threads") else {
continue;
};
if !cols.contains("id") {
continue;
}
let unresolved = ids
.iter()
.copied()
.filter(|id| !titles.contains_key(*id))
.collect::<Vec<_>>();
if unresolved.is_empty() {
break;
}
let title = sql_select_column(&cols, "title", "NULL");
let first = sql_select_column(&cols, "first_user_message", "NULL");
let preview = sql_select_column(&cols, "preview", "NULL");
let cwd = sql_select_column(&cols, "cwd", "NULL");
// Keep below SQLite's variable limit even if another caller requests more IDs.
for chunk in unresolved.chunks(400) {
let placeholders = vec!["?"; chunk.len()].join(",");
let query = format!("SELECT \"id\", {title}, {first}, {preview}, {cwd} FROM threads WHERE \"id\" IN ({placeholders})");
let Ok(mut statement) = conn.prepare(&query) else {
continue;
};
let Ok(rows) = statement.query_map(rusqlite::params_from_iter(chunk.iter()), |row| {
let id = row.get::<_, String>(0)?;
let text = |index| row.get::<_, Option<String>>(index).ok().flatten();
Ok((
id,
clean_session_title([text(1), text(2), text(3)]),
text(4),
))
}) else {
continue;
};
for (id, title, cwd) in rows.flatten() {
if let Some(title) = title {
titles.entry(id).or_insert(title);
} else if let Some(project) = cwd.as_deref().and_then(session_project_title) {
projects.entry(id).or_insert(project);
}
}
}
}
// Prefer a real chat title from an older database over a project-only fallback.
for (id, project) in projects {
titles.entry(id).or_insert(project);
}
titles
}
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn sqlite_session_db_paths(codex_dir: &Path) -> Vec<PathBuf> {
discover_sqlite_databases(codex_dir).session_paths
@@ -991,7 +1111,7 @@ pub(super) fn sqlite_subagent_thread_ids(
Ok(ids)
}
fn source_value_is_subagent(source: &Value) -> bool {
pub(crate) fn source_value_is_subagent(source: &Value) -> bool {
match source {
Value::String(source) => source.trim().eq_ignore_ascii_case("subagent"),
Value::Object(source) => source.contains_key("subagent"),
@@ -1008,6 +1128,160 @@ fn source_text_is_subagent(source: &str) -> bool {
.is_some_and(source_value_is_subagent)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct UsageThreadIdentity {
pub(crate) is_subagent: bool,
pub(crate) classification_known: bool,
pub(crate) parent_id: Option<String>,
pub(crate) parent_conflict: bool,
}
fn usage_identities_on_connection(
conn: &Connection,
) -> Result<HashMap<String, (bool, bool, HashSet<String>)>> {
if !sqlite_has_table(conn, "threads")? {
return Ok(HashMap::new());
}
let cols = table_column_set(conn, "threads")?;
if !cols.contains("id") {
return Ok(HashMap::new());
}
let subagents = sqlite_subagent_thread_ids(conn, &cols)?;
let source = sql_select_column(&cols, "source", "NULL");
let thread_source = sql_select_column(&cols, "thread_source", "NULL");
let mut statement = conn
.prepare(&format!(
"SELECT id, {source}, {thread_source} FROM threads"
))
.map_err(|error| CodexxError::Database(error.to_string()))?;
let rows = statement
.query_map([], |row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, Option<String>>(1).ok().flatten(),
row.get::<_, Option<String>>(2).ok().flatten(),
))
})
.map_err(|error| CodexxError::Database(error.to_string()))?;
let mut identities = HashMap::new();
for row in rows {
let (id, source, thread_source) =
row.map_err(|error| CodexxError::Database(error.to_string()))?;
if id.trim().is_empty() {
continue;
}
let is_subagent = subagents.contains(&id);
let classification_known = is_subagent
|| thread_source
.as_deref()
.is_some_and(|value| !value.trim().is_empty())
|| source
.as_deref()
.is_some_and(|value| !value.trim().is_empty());
let mut parents = HashSet::new();
if is_subagent {
if let Some(parent) = source
.as_deref()
.and_then(|text| serde_json::from_str::<Value>(text).ok())
.and_then(|value| {
value
.pointer("/subagent/thread_spawn/parent_thread_id")
.and_then(Value::as_str)
.map(ToString::to_string)
})
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
{
parents.insert(parent);
}
}
identities.insert(id, (is_subagent, classification_known, parents));
}
if sqlite_has_table(conn, "thread_spawn_edges")? {
let cols = table_column_set(conn, "thread_spawn_edges")?;
if cols.contains("child_thread_id") && cols.contains("parent_thread_id") {
let mut statement = conn
.prepare("SELECT child_thread_id, parent_thread_id FROM thread_spawn_edges")
.map_err(|error| CodexxError::Database(error.to_string()))?;
let rows = statement
.query_map([], |row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, Option<String>>(1).ok().flatten(),
))
})
.map_err(|error| CodexxError::Database(error.to_string()))?;
for row in rows {
let (child, parent) =
row.map_err(|error| CodexxError::Database(error.to_string()))?;
if let Some((true, _, parents)) = identities.get_mut(&child) {
if let Some(parent) = parent
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
{
parents.insert(parent);
}
}
}
}
}
Ok(identities)
}
/// Reuse session-management classification without reading any rollout content.
/// Current database records override stale legacy classification and parentage.
pub(crate) fn usage_thread_identities(codex_dir: &Path) -> HashMap<String, UsageThreadIdentity> {
let timeout = Duration::from_millis(50);
let discovery = discover_sqlite_databases_with_busy_timeout(codex_dir, Some(timeout));
let mut active_ids = HashSet::new();
let mut combined = HashMap::<String, (bool, bool, HashSet<String>)>::new();
for path in discovery.active_first_session_paths() {
let Ok(conn) = Connection::open_with_flags(
&path,
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
) else {
continue;
};
if conn.busy_timeout(timeout).is_err() {
continue;
}
let Ok(identities) = usage_identities_on_connection(&conn) else {
continue;
};
let is_active = discovery.active_paths.contains(&path);
for (id, (is_subagent, classification_known, parents)) in identities {
if is_active {
active_ids.insert(id.clone());
combined.insert(id, (is_subagent, classification_known, parents));
} else if !active_ids.contains(&id) {
let existing = combined
.entry(id)
.or_insert_with(|| (false, false, HashSet::new()));
existing.0 |= is_subagent;
existing.1 |= classification_known;
existing.2.extend(parents);
}
}
}
combined
.into_iter()
.map(|(id, (is_subagent, classification_known, parents))| {
let parent_conflict = is_subagent && parents.len() > 1;
let parent_id =
(is_subagent && parents.len() == 1).then(|| parents.into_iter().next().unwrap());
(
id,
UsageThreadIdentity {
is_subagent,
classification_known,
parent_id,
parent_conflict,
},
)
})
.collect()
}
pub(super) struct SqliteThreadIndexState<'a> {
pub(super) thread_id: &'a str,
pub(super) provider: Option<&'a str>,
@@ -1240,11 +1514,7 @@ pub(super) fn list_session_previews_with_paths(
let updated_at: Option<i64> = row.get(9)?;
let archived: i64 = row.get(10)?;
let has_user_event: i64 = row.get(11)?;
let clean_title = [title, first_message, preview]
.into_iter()
.flatten()
.map(|v| v.trim().to_string())
.find(|v| !v.is_empty())
let clean_title = clean_session_title([title, first_message, preview])
.unwrap_or_else(|| format!("会话 {}", id.chars().take(8).collect::<String>()));
let normalized_provider = model_provider
.as_ref()
@@ -1351,6 +1621,335 @@ mod tests {
.expect("insert thread");
}
fn create_title_database(path: &Path) -> Connection {
fs::create_dir_all(path.parent().unwrap()).unwrap();
let conn = Connection::open(path).unwrap();
conn.execute_batch("CREATE TABLE threads (id TEXT PRIMARY KEY, title, first_user_message, preview, cwd TEXT);").unwrap();
conn
}
fn create_identity_database(path: &Path) -> Connection {
fs::create_dir_all(path.parent().unwrap()).unwrap();
let conn = Connection::open(path).unwrap();
conn.execute_batch(
"CREATE TABLE threads (id TEXT PRIMARY KEY, thread_source TEXT, source TEXT);
CREATE TABLE thread_spawn_edges (parent_thread_id TEXT, child_thread_id TEXT);",
)
.unwrap();
conn
}
#[test]
fn usage_thread_identity_reuses_edges_source_and_authoritative_thread_source() {
let dir = temp_codex_dir("usage-identities-source");
let path = dir.join("state_10.sqlite");
let conn = create_identity_database(&path);
conn.execute_batch(r#"INSERT INTO threads VALUES
('parent', 'user', NULL),
('edge', NULL, NULL),
('source', NULL, '{"subagent":{"thread_spawn":{"parent_thread_id":"parent"}}}'),
('thread-source', 'subagent', NULL),
('source-only', NULL, 'subagent'),
('user-override', 'user', '{"subagent":{"thread_spawn":{"parent_thread_id":"parent"}}}');
INSERT INTO thread_spawn_edges VALUES ('parent', 'edge'), ('parent', 'user-override');"#).unwrap();
drop(conn);
let before = fs::read(&path).unwrap();
let identities = usage_thread_identities(&dir);
assert_eq!(
identities["edge"],
UsageThreadIdentity {
classification_known: true,
is_subagent: true,
parent_id: Some("parent".into()),
parent_conflict: false,
}
);
assert_eq!(identities["source"], identities["edge"]);
assert_eq!(
identities["thread-source"],
UsageThreadIdentity {
classification_known: true,
is_subagent: true,
parent_id: None,
parent_conflict: false,
}
);
assert_eq!(identities["source-only"], identities["thread-source"]);
assert_eq!(
identities["user-override"],
UsageThreadIdentity {
classification_known: true,
is_subagent: false,
parent_id: None,
parent_conflict: false,
}
);
assert_eq!(identities["parent"], identities["user-override"]);
assert_eq!(fs::read(&path).unwrap(), before);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn usage_thread_identity_missing_or_blank_source_is_unknown_not_explicit_user() {
let dir = temp_codex_dir("usage-identities-unknown");
let active = create_identity_database(&dir.join("state_10.sqlite"));
active
.execute_batch(
"INSERT INTO threads VALUES
('null-source', NULL, NULL), ('blank-source', ' ', ' '),
('known-user', 'user', NULL), ('source-user', NULL, 'cli');",
)
.unwrap();
let legacy_path = dir.join("sqlite/state_5.sqlite");
create_thread_database(&legacy_path, "no-source-columns", "openai");
let identities = usage_thread_identities(&dir);
for id in ["null-source", "blank-source", "no-source-columns"] {
assert_eq!(
identities[id],
UsageThreadIdentity {
is_subagent: false,
classification_known: false,
parent_id: None,
parent_conflict: false,
}
);
}
for id in ["known-user", "source-user"] {
assert!(!identities[id].is_subagent);
assert!(identities[id].classification_known);
}
drop(active);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn usage_thread_identity_active_records_override_stale_legacy_subagents_and_parents() {
let dir = temp_codex_dir("usage-identities-active");
let active = create_identity_database(&dir.join("state_10.sqlite"));
let legacy = create_identity_database(&dir.join("sqlite/state_5.sqlite"));
active
.execute_batch(
"INSERT INTO threads VALUES ('user', 'user', NULL), ('child', 'subagent', NULL);
INSERT INTO thread_spawn_edges VALUES ('current-parent', 'child');",
)
.unwrap();
legacy.execute_batch("INSERT INTO threads VALUES ('user', 'subagent', NULL), ('child', 'subagent', NULL), ('legacy-child', 'subagent', NULL);
INSERT INTO thread_spawn_edges VALUES ('old-parent', 'user'), ('old-parent', 'child'), ('legacy-parent', 'legacy-child');").unwrap();
let identities = usage_thread_identities(&dir);
assert_eq!(
identities["user"],
UsageThreadIdentity {
classification_known: true,
is_subagent: false,
parent_id: None,
parent_conflict: false,
}
);
assert_eq!(
identities["child"].parent_id.as_deref(),
Some("current-parent")
);
assert_eq!(
identities["legacy-child"].parent_id.as_deref(),
Some("legacy-parent")
);
drop(active);
drop(legacy);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn usage_thread_identity_conflicting_parent_edges_or_sources_remain_unassigned() {
let dir = temp_codex_dir("usage-identities-conflicts");
let active = create_identity_database(&dir.join("state_10.sqlite"));
let first = create_identity_database(&dir.join("sqlite/state_5.sqlite"));
let second = create_identity_database(&dir.join("sqlite/state_6.sqlite"));
active.execute_batch(r#"INSERT INTO threads VALUES ('conflict', 'subagent', '{"subagent":{"thread_spawn":{"parent_thread_id":"source-parent"}}}');
INSERT INTO thread_spawn_edges VALUES ('edge-parent', 'conflict');"#).unwrap();
first.execute_batch("INSERT INTO threads VALUES ('legacy', 'subagent', NULL); INSERT INTO thread_spawn_edges VALUES ('first-parent', 'legacy');").unwrap();
second.execute_batch("INSERT INTO threads VALUES ('legacy', 'subagent', NULL); INSERT INTO thread_spawn_edges VALUES ('second-parent', 'legacy');").unwrap();
let identities = usage_thread_identities(&dir);
assert_eq!(
identities["conflict"],
UsageThreadIdentity {
classification_known: true,
is_subagent: true,
parent_id: None,
parent_conflict: true,
}
);
assert_eq!(identities["legacy"], identities["conflict"]);
drop(active);
drop(first);
drop(second);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn usage_thread_identity_missing_corrupt_and_locked_databases_are_best_effort() {
let dir = temp_codex_dir("usage-identities-unavailable");
assert!(usage_thread_identities(&dir.join("missing")).is_empty());
assert!(!dir.join("missing").exists());
fs::write(
dir.join("state_12.sqlite"),
b"SQLite format 3\0broken fixture",
)
.unwrap();
assert!(usage_thread_identities(&dir).is_empty());
let locked = create_identity_database(&dir.join("state_10.sqlite"));
locked
.execute_batch("INSERT INTO threads VALUES ('user', 'user', NULL); BEGIN EXCLUSIVE;")
.unwrap();
let start = std::time::Instant::now();
assert!(usage_thread_identities(&dir).is_empty());
assert!(start.elapsed() < Duration::from_secs(2));
locked.execute_batch("ROLLBACK;").unwrap();
assert!(!usage_thread_identities(&dir)["user"].is_subagent);
drop(locked);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn usage_session_titles_follow_chat_title_fallbacks_and_only_requested_ids() {
let codex_dir = temp_codex_dir("usage-title-fields");
let conn = create_title_database(&codex_dir.join("state_10.sqlite"));
conn.execute_batch(
"INSERT INTO threads VALUES
('named', ' 真实聊天标题 ', 'First message', 'Preview', '/projects/unused'),
('first', ' ', ' 首条用户消息 ', 'Preview', NULL),
('preview', NULL, ' ', ' 会话摘要 ', NULL),
('project', NULL, NULL, NULL, 'C:\\work\\Codex-X\\'),
('invalid-title', X'FF', ' 可读取的首条消息 ', NULL, NULL),
('invalid-values', 42, 3.14, X'FF', NULL),
('root', NULL, NULL, NULL, '/'),
('excluded', 'This row was not requested', NULL, NULL, NULL);",
)
.unwrap();
let ids = [
"named",
"first",
"preview",
"project",
"invalid-title",
"invalid-values",
"root",
"x' OR 1=1 --",
]
.map(ToString::to_string);
let titles = session_titles_by_id(&codex_dir, &ids);
assert_eq!(titles.len(), 5);
assert_eq!(titles["named"], "真实聊天标题");
assert_eq!(titles["first"], "首条用户消息");
assert_eq!(titles["preview"], "会话摘要");
assert_eq!(titles["project"], "Codex-X");
assert_eq!(titles["invalid-title"], "可读取的首条消息");
assert!(!titles.contains_key("excluded"));
assert!(!titles.contains_key("invalid-values"));
assert!(!titles.contains_key("root"));
drop(conn);
fs::remove_dir_all(codex_dir).unwrap();
}
#[test]
fn usage_session_titles_prefer_active_database_and_reread_renames() {
let codex_dir = temp_codex_dir("usage-title-priority");
let active = create_title_database(&codex_dir.join("state_10.sqlite"));
let legacy = create_title_database(&codex_dir.join("sqlite/state_5.sqlite"));
active
.execute_batch(
"INSERT INTO threads VALUES
('shared', 'Current title', NULL, NULL, NULL),
('fallback', ' ', NULL, NULL, '/projects/active-project'),
('project', NULL, NULL, NULL, '/projects/active-project');",
)
.unwrap();
legacy
.execute_batch(
"INSERT INTO threads VALUES
('shared', 'Old title', NULL, NULL, NULL),
('fallback', 'Recovered chat title', NULL, NULL, '/projects/old-project'),
('project', NULL, NULL, NULL, '/projects/old-project');",
)
.unwrap();
let ids = ["shared", "fallback", "project"].map(ToString::to_string);
let titles = session_titles_by_id(&codex_dir, &ids);
assert_eq!(titles["shared"], "Current title");
assert_eq!(titles["fallback"], "Recovered chat title");
assert_eq!(titles["project"], "active-project");
active
.execute(
"UPDATE threads SET title = 'Renamed chat title' WHERE id = 'shared'",
[],
)
.unwrap();
assert_eq!(
session_titles_by_id(&codex_dir, &ids)["shared"],
"Renamed chat title"
);
drop(active);
drop(legacy);
fs::remove_dir_all(codex_dir).unwrap();
}
#[test]
fn usage_session_titles_are_read_only_and_tolerate_missing_corrupt_or_locked_databases() {
let codex_dir = temp_codex_dir("usage-title-read-only");
let missing = codex_dir.join("missing");
let ids = ["session".to_string()];
assert!(session_titles_by_id(&missing, &ids).is_empty());
assert!(!missing.exists());
let path = codex_dir.join("state_10.sqlite");
create_thread_database(&path, "session", "openai");
fs::write(
codex_dir.join("state_12.sqlite"),
b"SQLite format 3\0broken fixture",
)
.unwrap();
let before = fs::read(&path).unwrap();
let modified = fs::metadata(&path).unwrap().modified().unwrap();
let original_permissions = fs::metadata(&path).unwrap().permissions();
let mut permissions = original_permissions.clone();
permissions.set_readonly(true);
fs::set_permissions(&path, permissions.clone()).unwrap();
assert_eq!(
session_titles_by_id(&codex_dir, &ids)["session"],
"test session"
);
assert_eq!(fs::read(&path).unwrap(), before);
assert_eq!(fs::metadata(&path).unwrap().modified().unwrap(), modified);
assert!(!codex_dir.join("state_10.sqlite-journal").exists());
fs::set_permissions(&path, original_permissions).unwrap();
let locked = Connection::open(&path).unwrap();
locked.execute_batch("BEGIN EXCLUSIVE;").unwrap();
let start = std::time::Instant::now();
assert!(session_titles_by_id(&codex_dir, &ids).is_empty());
assert!(start.elapsed() < Duration::from_secs(2));
locked.execute_batch("ROLLBACK;").unwrap();
drop(locked);
fs::remove_dir_all(codex_dir).unwrap();
}
#[test]
fn session_project_titles_support_platform_paths_and_reject_roots() {
for (path, expected) in [
("/Users/test/projects/Codex-X/", Some("Codex-X")),
(r"C:\work\Codex-X\", Some("Codex-X")),
(r"\\?\C:\work\Codex-X", Some("Codex-X")),
(r"\\server\share\project", Some("project")),
("relative/project", Some("project")),
("", None),
(" ", None),
("/", None),
(r"C:\", None),
("C:", None),
(r"\\server\share\", None),
(".", None),
("..", None),
] {
assert_eq!(session_project_title(path).as_deref(), expected, "{path}");
}
}
#[test]
fn root_state_10_honors_an_explicit_provider_target() {
let codex_dir = temp_codex_dir("root-state-10");
+5
View File
@@ -47,6 +47,7 @@ pub(crate) struct CodexState {
pub(crate) instruction_template_key: Option<String>,
agents_path: String,
pub(crate) active_saved_provider_id: Option<String>,
pub(crate) active_official_profile_id: Option<String>,
providers: Vec<ProviderSummary>,
pub(crate) config_text: String,
auth_preview: Option<Value>,
@@ -249,6 +250,10 @@ pub(crate) fn build_state_after_migration(codex_dir: PathBuf) -> Result<CodexSta
instruction_template_key,
agents_path: agents_path(&codex_dir).display().to_string(),
active_saved_provider_id,
active_official_profile_id: crate::providers::official_profiles::active_profile_id(
&codex_dir,
is_official_provider,
)?,
providers,
config_text: text,
auth_preview: redacted_auth_preview(&auth)?,
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Codex-X",
"version": "0.3.15",
"version": "0.3.16",
"identifier": "com.yynxxxxx.codexx",
"build": {
"frontendDist": "../dist",
+305 -94
View File
@@ -38,6 +38,10 @@ import type {
Lang,
OfficialAuthCandidate,
OfficialConfigDraft,
OfficialProfileActionResult,
OfficialProfileDetail,
OfficialProfileSummary,
DuplicateProviderResult,
PromptInjectionMode,
ProviderConnectionResult,
ProviderModel,
@@ -67,6 +71,7 @@ const STARTUP_WIZARD_SEEN_KEY = "codexx.startupWizardSeen";
const ACTIVE_PROVIDER_KEY = "codexx.activeProviderId";
const PROMPT_INJECTION_MODE_KEY = "codexx.promptInjectionMode";
const FALLBACK_GITHUB_REPO = "yynxxxxx/Codex-X";
const DEFAULT_OFFICIAL_PROFILE_ID = "openai-official";
type ThemeTransitionDocument = Document & {
startViewTransition?: (update: () => void | Promise<void>) => { finished: Promise<void> };
@@ -176,7 +181,7 @@ const dict = {
},
provider: {
title: "供应商列表",
subtitle: "像 cc-switch 一样管理 Codex 第三方 API。点击卡片可切换,点击 + 添加新供应商。",
subtitle: "管理多个官方 Codex 登录与第三方 API,按名称区分账号并随时切换。",
add: "添加供应商",
importCc: "从 cc-switch 导入",
edit: "编辑",
@@ -196,7 +201,7 @@ const dict = {
officialUrl: "官方入口",
formAdd: "添加新供应商",
formEdit: "编辑供应商",
formHint: "保存后会写入供应商列表,并同步写入 Codex live 配置。下方可预览将生成的 config.toml。",
formHint: "选择供应商类型并填写配置。新增配置保存到列表,点击启用后生效。",
name: "供应商名称",
baseUrl: "Base URL",
model: "模型",
@@ -277,7 +282,7 @@ const dict = {
},
provider: {
title: "Provider list",
subtitle: "Manage Codex third-party APIs like cc-switch. Click a row to switch; use + to add a provider.",
subtitle: "Manage named Codex sign-in profiles and third-party APIs, and switch between them.",
add: "Add provider",
importCc: "Import from cc-switch",
edit: "Edit",
@@ -297,7 +302,7 @@ const dict = {
officialUrl: "Official URL",
formAdd: "Add provider",
formEdit: "Edit provider",
formHint: "Save writes the provider to the list and applies it to the Codex live config. The generated config.toml is previewed below.",
formHint: "Choose a provider type and enter its settings. New profiles are saved to the list; enable one to use it.",
name: "Provider name",
baseUrl: "Base URL",
model: "Model",
@@ -365,8 +370,8 @@ function getProviderPageCopy(lang: Lang): ProviderCopy {
? `“${providerName}”将从供应商列表中删除,此操作无法撤销。`
: `“${providerName}” will be removed from the provider list. This cannot be undone.`,
deleteCurrentDescription: (providerName) => isChinese
? `“${providerName}”当前正在使用。删除前会先热切换到 OpenAI Official,确定继续吗?`
: `“${providerName}” is currently active. Codex-X will hot-switch to OpenAI Official before deleting it. Continue?`,
? `“${providerName}”当前正在使用。删除前会先切换到默认官方登录配置,确定继续吗?`
: `“${providerName}” is currently active. Codex-X will switch to the default official sign-in profile before deleting it. Continue?`,
deleteCancelLabel: isChinese ? "取消" : "Cancel",
deleteConfirmLabel: isChinese ? "确认删除" : "Delete",
noBaseUrlLabel: "no base_url",
@@ -381,13 +386,13 @@ function getProviderPageCopy(lang: Lang): ProviderCopy {
officialSaveLabel: isChinese ? "保存官方配置" : "Save official config",
loadCcSwitchOfficialLabel: isChinese ? "从 CC Switch 载入" : "Load from CC Switch",
restoreOfficialLabel: isChinese ? "读取已保存配置" : "Load saved config",
resetOfficialLabel: isChinese ? "新建官方配置" : "Create official config",
resetOfficialTitle: isChinese ? "新建官方配置" : "Create official config",
resetOfficialLabel: isChinese ? "重置默认官方配置" : "Reset default official config",
resetOfficialTitle: isChinese ? "重置默认官方配置" : "Reset default official config",
resetOfficialDescription: isChinese
? "这会切换到 OpenAI Official、清除当前 live auth.json,并要求你在 Codex 中重新登录。操作前会自动备份当前配置。"
: "This switches to OpenAI Official, removes the live auth.json, and requires a new Codex login. The current files are backed up first.",
resetOfficialCancelLabel: isChinese ? "取消" : "Cancel",
resetOfficialConfirmLabel: isChinese ? "清除并新建" : "Clear and create",
resetOfficialConfirmLabel: isChinese ? "确认重置" : "Reset",
cancelLabel: t.provider.cancel,
formEyebrow: "Provider",
formAddTitle: t.provider.formAdd,
@@ -744,6 +749,10 @@ function App() {
const [editingPromptId, setEditingPromptId] = React.useState<string | null>(null);
const [editingBuiltinPrompt, setEditingBuiltinPrompt] = React.useState<BuiltinPromptDetail | null>(null);
const [savedProviders, setSavedProviders] = React.useState<SavedProvider[]>([]);
const [officialProfiles, setOfficialProfiles] = React.useState<OfficialProfileSummary[]>([]);
const [editingOfficialProfileId, setEditingOfficialProfileId] = React.useState<string | null>(DEFAULT_OFFICIAL_PROFILE_ID);
const [creatingProvider, setCreatingProvider] = React.useState(false);
const [officialAuthDirty, setOfficialAuthDirty] = React.useState(false);
const [activeProviderId, setActiveProviderId] = React.useState(() => localStorage.getItem(ACTIVE_PROVIDER_KEY) || "");
const [savedPrompts, setSavedPrompts] = React.useState<SavedPrompt[]>([]);
const [builtinPromptStatus, setBuiltinPromptStatus] = React.useState<BuiltinPromptStatus[]>([]);
@@ -785,9 +794,11 @@ function App() {
const [skillsMcpNoteBusy, setSkillsMcpNoteBusy] = React.useState("");
const [restartCodexBusy, setRestartCodexBusy] = React.useState(false);
const [promptSyncing, setPromptSyncing] = React.useState(false);
const [promptDetailLoading, setPromptDetailLoading] = React.useState(false);
const [promptCatalogReady, setPromptCatalogReady] = React.useState(false);
const [promptForm, setPromptForm] = React.useState<SavedPrompt>(blankPromptForm);
const [officialForm, setOfficialForm] = React.useState({
providerName: "OpenAI Official",
model: "gpt-5.5",
authJson: "",
configText: buildOfficialTomlPreview("gpt-5.5"),
@@ -802,6 +813,8 @@ function App() {
const providerModelsRequestRef = React.useRef(0);
const providerDraftRequestRef = React.useRef(0);
const officialDraftRequestRef = React.useRef(0);
const officialProfilesRequestRef = React.useRef(0);
const savedProvidersRequestRef = React.useRef(0);
const loadingGenerationRef = React.useRef(0);
const loadingTokensRef = React.useRef(new Set<number>());
const actionBusyGenerationRef = React.useRef(0);
@@ -810,6 +823,7 @@ function App() {
const restartCodexBusyRef = React.useRef(false);
const promptModeHelpRef = React.useRef<HTMLDivElement | null>(null);
const promptRefreshRequestRef = React.useRef(0);
const promptDetailRequestRef = React.useRef(0);
const refreshRequestRef = React.useRef(0);
const aboutLoadKeyRef = React.useRef("");
const sessionAutoLoadKeyRef = React.useRef("");
@@ -884,6 +898,15 @@ function App() {
}
if (changed) syncActionBusy();
}, [syncActionBusy]);
const invalidatePromptDetail = React.useCallback(() => {
promptDetailRequestRef.current += 1;
setPromptDetailLoading(false);
}, []);
const commitSavedProviders = React.useCallback((providers: SavedProvider[]) => {
savedProvidersRequestRef.current += 1;
setSavedProviders(providers);
}, []);
const currentInstructionId = instructionIdFromPath(state?.instructionFile, instructionTemplates);
const releaseStatusLabel = React.useMemo(() => {
if (updater.state.phase === "downloading") return lang === "zh" ? "下载中" : "Downloading";
@@ -1128,20 +1151,34 @@ function App() {
}));
}, [effectiveActiveProviderId, savedProviders]);
const providerRows = React.useMemo(() => {
const officialRow = {
id: "openai-official",
source: "official" as const,
const currentOfficialProfileId = state?.isOfficialProvider
? state.activeOfficialProfileId || DEFAULT_OFFICIAL_PROFILE_ID
: "";
const currentOfficialProfile = officialProfiles.find((profile) => profile.id === currentOfficialProfileId);
const providerRows = React.useMemo<ProviderRow[]>(() => {
const defaultProfile = officialProfiles.find((profile) => profile.isDefault) || {
id: DEFAULT_OFFICIAL_PROFILE_ID,
providerName: "OpenAI Official",
model: null,
isDefault: true,
hasAuth: Boolean(state?.officialAuthAvailable),
};
const officialRow = (profile: typeof defaultProfile): ProviderRow => ({
id: profile.id,
source: "official",
providerName: profile.providerName,
baseUrl: "https://chatgpt.com/codex",
model: state?.model || "official",
model: profile.model || "official",
apiKey: "",
wireApi: "official",
requiresOpenaiAuth: false,
isCurrent: Boolean(state?.isOfficialProvider),
};
return orderProviderRows(officialRow, detectedRows, localRows);
}, [detectedRows, localRows, state?.isOfficialProvider, state?.model]);
requiresOpenaiAuth: true,
isCurrent: profile.id === currentOfficialProfileId,
isDefaultOfficial: profile.isDefault,
meta: !profile.hasAuth ? (lang === "zh" ? "待登录" : "Sign-in required") : undefined,
});
const rows = orderProviderRows(officialRow(defaultProfile), detectedRows, localRows);
return [rows[0], ...officialProfiles.filter((profile) => !profile.isDefault).map(officialRow), ...rows.slice(1)];
}, [currentOfficialProfileId, detectedRows, lang, localRows, officialProfiles, state?.officialAuthAvailable]);
const findLocalProviderForRow = React.useCallback((row: ProviderRow) => {
if (row.source === "official") return undefined;
@@ -1180,10 +1217,12 @@ function App() {
wireApi: row.wireApi,
requiresOpenaiAuth: row.requiresOpenaiAuth,
isCurrent: row.isCurrent,
isDefaultOfficial: row.isDefaultOfficial,
meta: row.meta,
sourceLabel: row.source === "official" ? (lang === "zh" ? "Codex 登录" : "Codex login") : undefined,
editable: row.source === "official" || Boolean(local) || row.source === "detected",
duplicable: Boolean(providerCopySourceForRow(row)),
deletable: Boolean(local),
duplicable: row.source === "official" || Boolean(providerCopySourceForRow(row)),
deletable: row.source === "official" ? !row.isDefaultOfficial : Boolean(local),
testable: row.source !== "official",
testingKey: `${row.source}-${row.id}`,
};
@@ -1263,7 +1302,10 @@ function App() {
}, [beginLoading, endLoading]);
const refresh = React.useCallback((includeDiagnostics: boolean) => {
invalidatePromptDetail();
const requestId = ++refreshRequestRef.current;
const profilesRequestId = ++officialProfilesRequestRef.current;
const providersRequestId = ++savedProvidersRequestRef.current;
officialDraftRequestRef.current += 1;
clearActionBusy("loadOfficialDraft");
skillsMcpRequestRef.current += 1;
@@ -1275,6 +1317,7 @@ function App() {
setRefreshing(true);
setError("");
setState(null);
setOfficialProfiles([]);
setSessionStatus(null);
setSkillsMcpState(null);
setSkillsMcpImportOpen(false);
@@ -1303,6 +1346,8 @@ function App() {
providerModelsRequestRef.current += 1;
setProviderMode("list");
setEditingProviderId(null);
setEditingOfficialProfileId(null);
setCreatingProvider(false);
setEditingDetectedProvider(false);
setProviderTomlDirty(false);
setProviderTomlDraft("");
@@ -1319,9 +1364,14 @@ function App() {
invoke<SavedProvider[]>("list_saved_providers"),
invoke<SavedPrompt[]>("list_saved_prompts"),
invoke<BuiltinPromptStatus[]>("get_builtin_prompt_status"),
]).then(([providers, prompts, promptStatus]) => {
invoke<OfficialProfileSummary[]>("list_official_profiles", { configDir: next.codexDir }),
]).then(([providers, prompts, promptStatus, profiles]) => {
if (requestId !== refreshRequestRef.current) return;
if (providers.status === "fulfilled") setSavedProviders(providers.value);
if (providersRequestId === savedProvidersRequestRef.current && providers.status === "fulfilled") setSavedProviders(providers.value);
if (profilesRequestId === officialProfilesRequestRef.current) {
if (profiles.status === "fulfilled") setOfficialProfiles(profiles.value);
else setError(String(profiles.reason));
}
if (prompts.status === "fulfilled") setSavedPrompts(prompts.value);
if (promptStatus.status === "fulfilled") {
setBuiltinPromptStatus(uniqueBuiltinPromptStatuses(promptStatus.value));
@@ -1333,7 +1383,7 @@ function App() {
setRefreshing(false);
setError(String(nextError));
});
}, [clearActionBusy, configDir, configDirDraft, state?.codexDir]);
}, [clearActionBusy, configDir, configDirDraft, invalidatePromptDetail, state?.codexDir]);
React.useEffect(() => {
refresh(startupWizardOpen);
@@ -1387,18 +1437,26 @@ function App() {
}, [activeProviderId, inferredActiveProviderId, liveProviderId, savedProviders, state]);
const handleActionResult = (result: ActionResult) => {
const profilesRequestId = ++officialProfilesRequestRef.current;
const providersRequestId = ++savedProvidersRequestRef.current;
setState(result.state);
setSessionStatus(null);
sessionAutoLoadKeyRef.current = "";
sessionLoadRequestRef.current += 1;
setToast(result.message);
void Promise.allSettled([
return Promise.allSettled([
invoke<SavedPrompt[]>("list_saved_prompts"),
invoke<SavedProvider[]>("list_saved_providers"),
invoke<OfficialProfileSummary[]>("list_official_profiles", { configDir: result.state.codexDir }),
])
.then(([prompts, providers]) => {
.then(([prompts, providers, profiles]) => {
if (normalizedConfigDirForComparison(result.state.codexDir) !== activeConfigDirKeyRef.current) return;
if (prompts.status === "fulfilled") setSavedPrompts(prompts.value);
if (providers.status === "fulfilled") setSavedProviders(providers.value);
if (providersRequestId === savedProvidersRequestRef.current && providers.status === "fulfilled") setSavedProviders(providers.value);
if (profilesRequestId === officialProfilesRequestRef.current) {
if (profiles.status === "fulfilled") setOfficialProfiles(profiles.value);
else setError(String(profiles.reason));
}
})
.catch(() => undefined);
};
@@ -1422,6 +1480,7 @@ function App() {
);
const openAddPrompt = () => {
invalidatePromptDetail();
setEditingPromptId(null);
setEditingBuiltinPrompt(null);
setPromptForm({ ...blankPromptForm });
@@ -1429,27 +1488,36 @@ function App() {
};
const openEditPrompt = (prompt: SavedPrompt) => {
invalidatePromptDetail();
setEditingPromptId(prompt.id);
setEditingBuiltinPrompt(null);
setPromptForm(prompt);
setInstructionMode("form");
};
const openEditBuiltinPrompt = (templateId: string) =>
call(
() => invoke<BuiltinPromptDetail>("get_builtin_prompt_detail", { templateId }),
(detail) => {
setEditingPromptId(null);
setEditingBuiltinPrompt(detail);
setPromptForm({
id: detail.id,
title: detail.title,
filename: detail.filename,
content: detail.content,
});
setInstructionMode("form");
},
);
const openEditBuiltinPrompt = async (templateId: string) => {
const requestId = ++promptDetailRequestRef.current;
// A local template read must not disable provider or other page actions.
setPromptDetailLoading(true);
setError("");
try {
const detail = await invoke<BuiltinPromptDetail>("get_builtin_prompt_detail", { templateId });
if (requestId !== promptDetailRequestRef.current) return;
setEditingPromptId(null);
setEditingBuiltinPrompt(detail);
setPromptForm({
id: detail.id,
title: detail.title,
filename: detail.filename,
content: detail.content,
});
setInstructionMode("form");
} catch (detailError) {
if (requestId === promptDetailRequestRef.current) setError(String(detailError));
} finally {
if (requestId === promptDetailRequestRef.current) setPromptDetailLoading(false);
}
};
const normalizedPromptForm = (): SavedPrompt => {
const existing = savedPrompts.filter((item) => item.id !== editingPromptId);
@@ -1670,7 +1738,7 @@ function App() {
},
({ applied, providerList }) => {
if (applied) handleActionResult(applied);
setSavedProviders(providerList);
commitSavedProviders(providerList);
setProviderMode("list");
setEditingProviderId(null);
setEditingDetectedProvider(false);
@@ -1752,9 +1820,9 @@ function App() {
const saveProviderConfig = saveProviderOnly;
const switchOfficialProvider = () =>
const switchOfficialProvider = (profileId = DEFAULT_OFFICIAL_PROFILE_ID) =>
call(
() => invoke<ActionResult>("switch_official_provider", { configDir: configDir || null }),
() => invoke<ActionResult>("switch_official_profile", { configDir: configDir || null, profileId }),
(result) => {
localStorage.removeItem(ACTIVE_PROVIDER_KEY);
setActiveProviderId("");
@@ -1773,7 +1841,9 @@ function App() {
},
({ result, draft }) => {
if (draft) {
setOfficialAuthDirty(false);
setOfficialForm({
providerName: officialForm.providerName,
model: draft.model || "gpt-5.5",
authJson: draft.authJson,
configText: draft.configText || buildOfficialTomlPreview(draft.model || "gpt-5.5"),
@@ -1797,7 +1867,9 @@ function App() {
setToast(lang === "zh" ? "未找到 CC Switch 官方配置" : "No CC Switch official config found");
return;
}
setOfficialAuthDirty(true);
setOfficialForm((current) => ({
...current,
model: candidate.model || current.model || state?.model || "gpt-5.5",
authJson: candidate.authJson,
configText: candidate.configText || current.configText,
@@ -1823,9 +1895,11 @@ function App() {
(result) => {
localStorage.removeItem(ACTIVE_PROVIDER_KEY);
setActiveProviderId("");
setOfficialAuthDirty(false);
setOfficialForm({
providerName: officialForm.providerName,
model: result.state.model || officialForm.model || "gpt-5.5",
authJson: officialAuthPlaceholder,
authJson: "",
configText: result.state.configText
|| officialForm.configText
|| buildOfficialTomlPreview(result.state.model || officialForm.model || "gpt-5.5"),
@@ -1848,11 +1922,11 @@ function App() {
: `cc-switch import complete: ${result.added} added, ${result.updated} updated, ${result.merged} merged${warningText}; current provider unchanged`;
try {
const nextState = await invoke<CodexState>("get_codex_state", { configDir: configDir || null });
setSavedProviders(result.providers);
commitSavedProviders(result.providers);
setState(nextState);
setToast(successText);
} catch (refreshError) {
setSavedProviders(result.providers);
commitSavedProviders(result.providers);
setToast(lang === "zh"
? `${successText};状态刷新失败,请手动刷新:${String(refreshError)}`
: `${successText}; state refresh failed, refresh manually: ${String(refreshError)}`);
@@ -2173,61 +2247,143 @@ function App() {
}
};
const officialAuthPlaceholder = '{\n "OPENAI_API_KEY": null,\n "auth_mode": "chatgpt",\n "tokens": {\n "access_token": "",\n "refresh_token": "",\n "id_token": ""\n }\n}';
const openOfficialEdit = async () => {
const openOfficialEdit = async (profileId = DEFAULT_OFFICIAL_PROFILE_ID) => {
const requestId = ++officialDraftRequestRef.current;
const actionToken = beginActionBusy("loadOfficialDraft");
const liveIsOfficial = Boolean(state?.isOfficialProvider);
const fallbackModel = state?.model || "gpt-5.5";
const fallbackConfigText = liveIsOfficial && state?.configText?.trim()
? state.configText
: "";
const profile = officialProfiles.find((item) => item.id === profileId);
setEditingDetectedProvider(false);
setEditingOfficialProfileId(profileId);
setCreatingProvider(false);
setOfficialAuthDirty(false);
setOfficialForm({
model: fallbackModel,
authJson: liveIsOfficial && state?.authText ? state.authText : officialAuthPlaceholder,
configText: fallbackConfigText,
providerName: profile?.providerName || "OpenAI Official",
model: profile?.model || "gpt-5.5",
authJson: "",
configText: "",
});
setProviderMode("official");
setError("");
try {
const draft = await invoke<OfficialConfigDraft | null>("get_official_config_draft", {
const draft = await invoke<OfficialProfileDetail>("get_official_profile", {
configDir: configDir || null,
profileId,
});
if (requestId !== officialDraftRequestRef.current) return;
if (draft) {
setOfficialForm({
model: draft.model || fallbackModel,
authJson: draft.authJson,
configText: draft.configText || fallbackConfigText,
});
}
setOfficialForm({
providerName: draft.providerName,
model: draft.model || "gpt-5.5",
authJson: draft.authJson,
configText: draft.configText,
});
} catch (e) {
if (requestId === officialDraftRequestRef.current) setError(String(e));
if (requestId === officialDraftRequestRef.current) {
setError(String(e));
setProviderMode("list");
}
} finally {
endActionBusy(actionToken);
}
};
const saveOfficialConfig = () =>
call(
const saveOfficialConfig = () => {
if (!officialForm.providerName.trim()) {
setError(lang === "zh" ? "请填写供应商名称" : "Provider name is required");
return;
}
return call(
() =>
invoke<ActionResult>("save_official_config", {
invoke<OfficialProfileActionResult>("save_official_profile", {
input: {
configDir: configDir || null,
id: editingOfficialProfileId,
providerName: officialForm.providerName.trim(),
model: officialForm.model,
authJson: officialForm.authJson,
authJson: officialAuthDirty || editingOfficialProfileId === null ? officialForm.authJson : null,
configText: officialForm.configText,
},
}),
(result) => {
handleActionResult(result);
setCreatingProvider(false);
setProviderMode("list");
},
);
};
const loadCurrentOfficial = async () => {
const requestId = ++officialDraftRequestRef.current;
const actionToken = beginActionBusy("loadCurrentOfficial");
setError("");
try {
const current = await invoke<CodexState>("get_codex_state", { configDir: configDir || null });
if (requestId !== officialDraftRequestRef.current) return;
if (!current.isOfficialProvider) {
throw new Error(lang === "zh" ? "请先在 Codex 中切换到官方登录" : "Switch Codex to official sign-in first");
}
setOfficialAuthDirty(true);
setOfficialForm((form) => ({
...form,
model: current.model || form.model,
configText: current.configText,
authJson: current.authText || "",
}));
setToast(lang === "zh" ? "已读取当前官方登录,保存后保留到此配置" : "Current sign-in loaded. Save to keep it in this profile.");
} catch (loadError) {
if (requestId === officialDraftRequestRef.current) setError(String(loadError));
} finally {
endActionBusy(actionToken);
}
};
const duplicateOfficialProfile = (row: ProviderRow) => {
const providerName = `${row.providerName}${lang === "zh" ? " 副本" : " Copy"}`;
return call(
() => invoke<OfficialProfileActionResult>("duplicate_official_profile", {
configDir: configDir || null, profileId: row.id, providerName,
}),
(result) => {
if (normalizedConfigDirForComparison(result.state.codexDir) !== activeConfigDirKeyRef.current) return;
handleActionResult(result);
setToast(lang === "zh" ? `已复制为“${result.profile.providerName}”` : `Created “${result.profile.providerName}”`);
},
);
};
const changeProviderKind = async (kind: "api" | "official") => {
const requestId = ++officialDraftRequestRef.current;
clearActionBusy("loadOfficialDraft");
if (kind === "api") {
setProviderMode("form");
return;
}
setEditingOfficialProfileId(null);
setProviderMode("official");
if (officialForm.configText.trim()) return;
// Start with a complete official template so a context-window toggle does
// not turn an otherwise empty draft into a two-line replacement config.
const actionToken = beginActionBusy("loadOfficialDraft");
try {
const template = await invoke<OfficialProfileDetail>("get_official_profile", {
configDir: configDir || null, profileId: DEFAULT_OFFICIAL_PROFILE_ID,
});
if (requestId !== officialDraftRequestRef.current) return;
setOfficialForm((form) => ({ ...form, configText: template.configText, model: template.model || form.model }));
} catch (templateError) {
if (requestId === officialDraftRequestRef.current) {
setError(String(templateError));
setProviderMode("list");
}
} finally {
endActionBusy(actionToken);
}
};
const openAddProvider = () => {
officialDraftRequestRef.current += 1;
setCreatingProvider(true);
setEditingOfficialProfileId(null);
setOfficialAuthDirty(false);
setOfficialForm({ providerName: "", model: state?.model || "gpt-5.5", configText: "", authJson: "" });
const liveToml = state?.configText?.trim() || "";
const next = {
...blankProviderForm,
@@ -2246,6 +2402,7 @@ function App() {
};
const openEditProvider = (provider: SavedProvider) => {
setCreatingProvider(false);
resetAvailableProviderModels();
setEditingProviderId(provider.id);
setEditingDetectedProvider(false);
@@ -2255,21 +2412,30 @@ function App() {
setProviderMode("form");
};
const openDuplicateProvider = (provider: SavedProvider) => {
resetAvailableProviderModels();
const duplicate = {
...provider,
id: uniqueId(provider.id || provider.providerName, savedProviders.map((item) => item.id)),
};
setEditingProviderId(null);
setEditingDetectedProvider(false);
setProviderForm(duplicate);
setProviderTomlDraft(duplicate.tomlConfig?.trim() || buildProviderTomlPreview(duplicate));
setProviderTomlDirty(false);
setProviderMode("form");
const duplicateProvider = (row: ProviderRow) => {
const requestedDirKey = activeConfigDirKeyRef.current;
return call(
() => invoke<DuplicateProviderResult>("duplicate_provider", {
configDir: configDir || null,
providerId: findLocalProviderForRow(row)?.id || null,
providerName: `${row.providerName}${lang === "zh" ? " 副本" : " Copy"}`,
}),
(result) => {
if (requestedDirKey !== activeConfigDirKeyRef.current) return;
commitSavedProviders(result.providers);
if (result.activeProviderId) {
setActiveProviderId(result.activeProviderId);
localStorage.setItem(ACTIVE_PROVIDER_KEY, result.activeProviderId);
setState((current) => current && !current.isOfficialProvider
? { ...current, activeSavedProviderId: result.activeProviderId || undefined } : current);
}
setToast(lang === "zh" ? `已复制为“${result.provider.providerName}”` : `Created “${result.provider.providerName}”`);
},
);
};
const openEditDetectedProvider = (provider: { id: string; providerName: string; baseUrl: string; model: string; apiKey?: string; wireApi: string; requiresOpenaiAuth: boolean }) => {
setCreatingProvider(false);
resetAvailableProviderModels();
const id = uniqueId(
customProviderId(provider.providerName || provider.baseUrl),
@@ -2305,7 +2471,7 @@ function App() {
}
await invoke<void>("delete_saved_provider", { id, configDir: configDir || null });
const providerList = await invoke<SavedProvider[]>("list_saved_providers");
setSavedProviders(providerList);
commitSavedProviders(providerList);
setToast(lang === "zh" ? "供应商已删除" : "Provider deleted");
return true;
} catch (e) {
@@ -2316,6 +2482,30 @@ function App() {
}
};
const removeOfficialProfile = async (id: string, isCurrent: boolean) => {
const loadingToken = beginLoading();
setError("");
try {
if (isCurrent) {
const result = await invoke<ActionResult>("switch_official_profile", {
configDir: configDir || null, profileId: DEFAULT_OFFICIAL_PROFILE_ID,
});
await handleActionResult(result);
}
await invoke<void>("delete_official_profile", { configDir: configDir || null, profileId: id });
const profilesRequestId = ++officialProfilesRequestRef.current;
const profiles = await invoke<OfficialProfileSummary[]>("list_official_profiles", { configDir: configDir || null });
if (profilesRequestId === officialProfilesRequestRef.current) setOfficialProfiles(profiles);
setToast(lang === "zh" ? "官方登录配置已删除" : "Official sign-in profile deleted");
return true;
} catch (deleteError) {
setError(String(deleteError));
return false;
} finally {
endLoading(loadingToken);
}
};
const checkSessions = async () => {
sessionLoadRequestRef.current += 1;
const actionToken = beginActionBusy("checkSessions");
@@ -2452,8 +2642,10 @@ function App() {
};
const changeTab = (nextTab: Tab) => {
if (nextTab !== "instruction") invalidatePromptDetail();
if (nextTab !== "provider") {
officialDraftRequestRef.current += 1;
if (actionBusy === "loadOfficialDraft") setProviderMode("list");
clearActionBusy("loadOfficialDraft");
}
setTab(nextTab);
@@ -2535,7 +2727,7 @@ function App() {
configDir={configDirDraft}
resolvedCodexDir={state?.codexDir || ""}
configExists={Boolean(state?.configExists)}
providerLabel={currentProvider?.name || state?.modelProvider}
providerLabel={currentOfficialProfile?.providerName || currentProvider?.name || state?.modelProvider}
instructionEnabled={Boolean(state?.instructionEnabled)}
authExists={Boolean(state?.authExists)}
officialAuthAvailable={Boolean(state?.officialAuthAvailable)}
@@ -2560,6 +2752,11 @@ function App() {
lang={lang}
copy={getProviderPageCopy(lang)}
mode={providerMode}
creatingProvider={creatingProvider}
providerKind={providerMode === "official" ? "official" : "api"}
onProviderKindChange={changeProviderKind}
officialProfileIsDefault={editingOfficialProfileId === DEFAULT_OFFICIAL_PROFILE_ID}
canLoadCurrentOfficial={Boolean(state.isOfficialProvider)}
providerRows={providerPageRows}
loading={loading}
testingId={providerTestingId}
@@ -2579,7 +2776,7 @@ function App() {
officialInfo={{
officialUrl: "https://chatgpt.com/codex",
authPath: state.authPath,
current: state.isOfficialProvider ? "OpenAI Official" : state.modelProvider,
current: state.isOfficialProvider ? currentOfficialProfile?.providerName || "OpenAI Official" : state.modelProvider,
}}
providerAuthPreview={<JsonPreview text={providerAuthPreview} />}
providerTomlDraft={providerTomlDraft}
@@ -2592,7 +2789,7 @@ function App() {
onLoadCcSwitchOfficial={() => void loadCcSwitchOfficial()}
onEnableProvider={(row) => {
if (row.source === "official") {
switchOfficialProvider();
switchOfficialProvider(row.id);
return;
}
const local = findLocalProviderForRow(row);
@@ -2613,7 +2810,7 @@ function App() {
}}
onEditProvider={(row) => {
if (row.source === "official") {
void openOfficialEdit();
void openOfficialEdit(row.id);
return;
}
const local = findLocalProviderForRow(row);
@@ -2621,10 +2818,14 @@ function App() {
else if (row.source === "detected") openEditDetectedProvider(row);
}}
onDuplicateProvider={(row) => {
const copySource = providerCopySourceForRow(row);
if (copySource) openDuplicateProvider(copySource);
if (row.source === "official") {
void duplicateOfficialProfile(row);
return;
}
void duplicateProvider(row);
}}
onDeleteProvider={(row) => {
if (row.source === "official") return removeOfficialProfile(row.id, row.isCurrent);
const local = findLocalProviderForRow(row);
return local ? removeProvider(local.id, row.isCurrent) : Promise.resolve(false);
}}
@@ -2633,11 +2834,17 @@ function App() {
onCancelMode={() => {
officialDraftRequestRef.current += 1;
setProviderMode("list");
setCreatingProvider(false);
setEditingDetectedProvider(false);
setProviderTomlDirty(false);
}}
onOfficialModelChange={(value) => setOfficialForm((current) => ({ ...current, model: value }))}
onOfficialAuthChange={(value) => setOfficialForm((current) => ({ ...current, authJson: value }))}
onOfficialNameChange={(value) => setOfficialForm((current) => ({ ...current, providerName: value }))}
onLoadCurrentOfficial={() => void loadCurrentOfficial()}
onOfficialAuthChange={(value) => {
setOfficialAuthDirty(true);
setOfficialForm((current) => ({ ...current, authJson: value }));
}}
onOfficialConfigChange={(value) => setOfficialForm((current) => ({ ...current, configText: value }))}
onSaveOfficial={saveOfficialConfig}
onApiKeyChange={(value) => {
@@ -2758,7 +2965,7 @@ function App() {
promptForm={promptForm}
editingPromptId={editingPromptId}
editingBuiltinPrompt={editingBuiltinPrompt}
loading={loading}
loading={loading || promptDetailLoading}
actionBusy={actionBusy}
promptSyncing={promptSyncing}
promptCatalogReady={promptCatalogReady}
@@ -2803,7 +3010,10 @@ function App() {
onSyncBuiltinPrompts={() => refreshBuiltinPrompts()}
onImportPrompt={importPromptMd}
onAddPrompt={openAddPrompt}
onInstructionModeChange={setInstructionMode}
onInstructionModeChange={(mode) => {
invalidatePromptDetail();
setInstructionMode(mode);
}}
onPromptInjectionModeChange={setPromptInjectionMode}
onTogglePromptModeHelp={() => setPromptModeHelpOpen((open) => !open)}
onEnableBuiltinPrompt={switchInstructionTemplate}
@@ -2882,6 +3092,7 @@ function App() {
{tab === "settings" && (
<SettingsPage
lang={lang}
configDir={configDir}
copy={{
eyebrow: "Settings",
title: t.settings.title,
+215 -18
View File
@@ -1,5 +1,6 @@
import { useId, useState } from "react";
import { useEffect, useId, useRef, useState } from "react";
import type { ReactNode } from "react";
import { invoke } from "@tauri-apps/api/core";
import {
Activity,
AlertTriangle,
@@ -36,6 +37,7 @@ export type ProviderRow = {
wireApi: string;
requiresOpenaiAuth: boolean;
isCurrent: boolean;
isDefaultOfficial?: boolean;
sourceLabel?: string;
editable?: boolean;
duplicable?: boolean;
@@ -55,6 +57,7 @@ export type ProviderFormValue = {
};
export type OfficialFormValue = {
providerName: string;
model: string;
authJson: string;
configText: string;
@@ -138,8 +141,12 @@ export type ProvidersPageProps = {
testingId: string;
actionBusy?: string;
editingProviderId: string | null;
creatingProvider: boolean;
providerKind: "api" | "official";
providerForm: ProviderFormValue;
officialForm: OfficialFormValue;
officialProfileIsDefault: boolean;
canLoadCurrentOfficial: boolean;
officialAuthRef?: Ref<HTMLTextAreaElement>;
officialTomlRef?: Ref<HTMLTextAreaElement>;
officialInfo: ProviderOfficialInfo;
@@ -151,7 +158,9 @@ export type ProvidersPageProps = {
fetchingModels: boolean;
onImportCcSwitch: () => void;
onAddProvider: () => void;
onProviderKindChange: (kind: "api" | "official") => void;
onLoadCcSwitchOfficial: () => void;
onLoadCurrentOfficial: () => void;
onRestoreOfficial: () => void;
onResetOfficial: () => void;
onEnableProvider: (row: ProviderRow) => void;
@@ -160,6 +169,7 @@ export type ProvidersPageProps = {
onDuplicateProvider: (row: ProviderRow) => void;
onDeleteProvider: (row: ProviderRow) => Promise<boolean>;
onCancelMode: () => void;
onOfficialNameChange: (value: string) => void;
onOfficialModelChange: (value: string) => void;
onOfficialAuthChange: (value: string) => void;
onOfficialConfigChange: (value: string) => void;
@@ -192,6 +202,145 @@ function Field({ label, children, className }: FieldProps) {
);
}
type ContextWindowValues = {
contextWindow: number | null;
compactTokenLimit: number | null;
};
type ContextWindowConfig = ContextWindowValues & {
configText: string;
enabled: boolean;
};
function ContextWindowControl({
lang,
configText,
disabled,
onConfigChange,
onBusyChange,
}: {
lang: "zh" | "en";
configText: string;
disabled: boolean;
onConfigChange: (text: string) => void;
onBusyChange: (busy: boolean) => void;
}) {
const [settings, setSettings] = useState<ContextWindowConfig | null>(null);
const [error, setError] = useState("");
const [changing, setChanging] = useState(false);
const currentText = useRef(configText);
const requestId = useRef(0);
const previousValues = useRef<ContextWindowValues | null>(null);
currentText.current = configText;
useEffect(() => {
const id = ++requestId.current;
let mounted = true;
setError("");
const timer = setTimeout(() => {
void invoke<ContextWindowConfig>("update_codex_context_window", {
configText,
enabled: null,
previousValues: null,
}).then((result) => {
if (mounted && requestId.current === id && currentText.current === configText) {
setSettings(result);
}
}).catch((cause: unknown) => {
if (mounted && requestId.current === id && currentText.current === configText) {
setSettings(null);
setError(String(cause));
}
});
}, 100);
return () => {
mounted = false;
++requestId.current;
clearTimeout(timer);
};
}, [configText]);
const toggle = async (enabled: boolean) => {
if (disabled || changing || !settings || settings.configText !== configText) return;
const originalText = configText;
const id = ++requestId.current;
setChanging(true);
onBusyChange(true);
setError("");
try {
const result = await invoke<ContextWindowConfig>("update_codex_context_window", {
configText: originalText,
enabled,
previousValues: enabled ? null : previousValues.current,
});
if (requestId.current !== id || currentText.current !== originalText) return;
previousValues.current = enabled
? { contextWindow: settings.contextWindow, compactTokenLimit: settings.compactTokenLimit }
: null;
setSettings(result);
onConfigChange(result.configText);
} catch (cause: unknown) {
if (requestId.current === id && currentText.current === originalText) setError(String(cause));
} finally {
setChanging(false);
onBusyChange(false);
}
};
return (
<div className="cx-providers-context-control">
<Checkbox
className="cx-providers-checkbox cx-providers-context-checkbox"
label={lang === "zh" ? "开启 1M 上下文窗口" : "Enable 1M context window"}
checked={Boolean(settings?.enabled)}
onCheckedChange={(enabled) => void toggle(enabled)}
disabled={disabled || changing || !settings || settings.configText !== configText}
/>
{error ? (
<span className="cx-providers-context-error" role="status" title={error}>
{lang === "zh" ? "请先修正 config.toml 的格式或上下文字段" : "Check the TOML syntax and context settings first"}
</span>
) : settings?.enabled && settings.configText === configText ? (
<span className="cx-providers-context-hint">
{settings.compactTokenLimit !== null
? lang === "zh"
? `自动压缩阈值:${settings.compactTokenLimit.toLocaleString("zh-CN")} tokens`
: `Auto-compact at ${settings.compactTokenLimit.toLocaleString("en-US")} tokens`
: lang === "zh" ? "自动压缩使用 Codex 默认值" : "Codex determines the compaction limit"}
</span>
) : (
<span className="cx-providers-context-hint">
{lang === "zh" ? "保存后生效,需模型支持" : "Applies on save; requires model support"}
</span>
)}
</div>
);
}
function ProviderKindSelect({
lang,
creatingProvider,
providerKind,
onProviderKindChange,
disabled,
}: Pick<ProvidersPageProps, "lang" | "creatingProvider" | "providerKind" | "onProviderKindChange"> & { disabled: boolean }) {
if (!creatingProvider) return null;
return (
<div className="cx-providers-form-grid cx-providers-form-grid--single">
<Field label={lang === "zh" ? "供应商类型" : "Provider type"}>
<select
value={providerKind}
onChange={(event) => onProviderKindChange(event.target.value === "official" ? "official" : "api")}
disabled={disabled}
>
<option value="api">{lang === "zh" ? "第三方 API" : "Third-party API"}</option>
<option value="official">{lang === "zh" ? "官方 Codex 登录" : "Official Codex login"}</option>
</select>
</Field>
</div>
);
}
function ProviderAvatar({ row }: { row: ProviderRow }) {
const initial = row.providerName.trim().slice(0, 1).toUpperCase() || "?";
const className = [
@@ -323,7 +472,7 @@ function ListPage({
>
{copy.enableLabel}
</button>
{row.source === "official" && (
{row.source === "official" && row.isDefaultOfficial && (
<ActionIconButton
icon={RotateCcw}
label={copy.restoreOfficialLabel}
@@ -407,52 +556,81 @@ function ModeHeader({ eyebrow, title, description, cancelLabel, onCancel, disabl
}
function OfficialForm({
lang,
copy,
creatingProvider,
providerKind,
onProviderKindChange,
officialForm,
officialProfileIsDefault,
canLoadCurrentOfficial,
officialAuthRef,
officialTomlRef,
officialInfo,
loading,
actionBusy,
onCancelMode,
onOfficialNameChange,
onOfficialModelChange,
onOfficialAuthChange,
onOfficialConfigChange,
onSaveOfficial,
onLoadCcSwitchOfficial,
onLoadCurrentOfficial,
onRestoreOfficial,
onResetOfficial,
}: Pick<ProvidersPageProps, "copy" | "officialForm" | "officialAuthRef" | "officialTomlRef" | "officialInfo" | "loading" | "actionBusy" | "onCancelMode" | "onOfficialModelChange" | "onOfficialAuthChange" | "onOfficialConfigChange" | "onSaveOfficial" | "onLoadCcSwitchOfficial" | "onRestoreOfficial" | "onResetOfficial">) {
}: Pick<ProvidersPageProps, "lang" | "copy" | "creatingProvider" | "providerKind" | "onProviderKindChange" | "officialForm" | "officialProfileIsDefault" | "canLoadCurrentOfficial" | "officialAuthRef" | "officialTomlRef" | "officialInfo" | "loading" | "actionBusy" | "onCancelMode" | "onOfficialNameChange" | "onOfficialModelChange" | "onOfficialAuthChange" | "onOfficialConfigChange" | "onSaveOfficial" | "onLoadCcSwitchOfficial" | "onLoadCurrentOfficial" | "onRestoreOfficial" | "onResetOfficial">) {
const [resetConfirmOpen, setResetConfirmOpen] = useState(false);
const [contextWindowBusy, setContextWindowBusy] = useState(false);
const loadingCcSwitch = actionBusy === "loadCcSwitchOfficial";
const formBusy = loading || actionBusy === "loadOfficialDraft" || loadingCcSwitch;
const loadingCurrent = actionBusy === "loadCurrentOfficial";
const formBusy = loading || actionBusy === "loadOfficialDraft" || loadingCcSwitch || loadingCurrent || contextWindowBusy;
const showDefaultActions = officialProfileIsDefault && !creatingProvider;
const profileHint = lang === "zh"
? "认证内容可留空;保存并启用后,在 Codex 中完成登录。复制官方供应商会保留原认证,并可修改名称。"
: "Authentication may be left empty. Save and enable this provider, then sign in through Codex. A copied official provider keeps its authentication and can be renamed.";
const confirmReset = () => {
if (!showDefaultActions || formBusy) return;
setResetConfirmOpen(false);
onResetOfficial();
};
return (
<>
<ModeHeader eyebrow={copy.officialEyebrow} title={copy.officialTitle} description={copy.officialHint} cancelLabel={copy.cancelLabel} onCancel={onCancelMode} disabled={formBusy} />
<ModeHeader
eyebrow={copy.officialEyebrow}
title={creatingProvider ? copy.formAddTitle : copy.officialTitle}
description={showDefaultActions ? `${copy.officialHint} ${profileHint}` : profileHint}
cancelLabel={copy.cancelLabel}
onCancel={onCancelMode}
disabled={formBusy}
/>
<ProviderKindSelect lang={lang} creatingProvider={creatingProvider} providerKind={providerKind} onProviderKindChange={onProviderKindChange} disabled={formBusy} />
<div className="cx-providers-info-grid">
<div><span>{copy.officialUrlLabel}</span><code>{officialInfo.officialUrl}</code></div>
<div><span>{copy.authPathLabel}</span><code>{officialInfo.authPath}</code></div>
<div><span>{copy.officialCurrentLabel}</span><code>{officialInfo.current}</code></div>
</div>
<div className="cx-providers-form-grid cx-providers-form-grid--single">
<Field label={copy.nameLabel}><input value={officialForm.providerName} onChange={(event) => onOfficialNameChange(event.target.value)} disabled={formBusy} /></Field>
<Field label={copy.modelLabel}><input value={officialForm.model} onChange={(event) => onOfficialModelChange(event.target.value)} disabled={formBusy} /></Field>
</div>
<Field label={copy.officialTomlLabel} className="cx-providers-editor-field">
<div className="cx-providers-editor-field">
<div className="cx-providers-context-heading">
<span>{copy.officialTomlLabel}</span>
<ContextWindowControl lang={lang} configText={officialForm.configText} onConfigChange={onOfficialConfigChange} disabled={formBusy} onBusyChange={setContextWindowBusy} />
</div>
<textarea
ref={officialTomlRef}
className="cx-providers-code-editor cx-providers-toml-editor"
value={officialForm.configText}
aria-label={copy.officialTomlLabel}
onChange={(event) => onOfficialConfigChange(event.target.value)}
disabled={formBusy}
spellCheck={false}
/>
</Field>
</div>
<Field label={copy.officialAuthLabel} className="cx-providers-editor-field">
<textarea
ref={officialAuthRef}
@@ -465,22 +643,32 @@ function OfficialForm({
/>
</Field>
<div className="cx-providers-form-actions cx-providers-form-actions--save cx-providers-official-actions">
<button type="button" className="cx-providers-button cx-providers-button--secondary" onClick={onLoadCurrentOfficial} disabled={formBusy || !canLoadCurrentOfficial}>
{loadingCurrent
? <Loader2 size={15} className="cx-providers-spin" aria-hidden="true" />
: <Download size={15} aria-hidden="true" />}
{lang === "zh" ? "读取当前官方登录" : "Load current official login"}
</button>
<button type="button" className="cx-providers-button cx-providers-button--secondary" onClick={onLoadCcSwitchOfficial} disabled={formBusy}>
{loadingCcSwitch
? <Loader2 size={15} className="cx-providers-spin" aria-hidden="true" />
: <Download size={15} aria-hidden="true" />}
{copy.loadCcSwitchOfficialLabel}
</button>
<button type="button" className="cx-providers-button cx-providers-button--secondary" onClick={onRestoreOfficial} disabled={formBusy}>
<RotateCcw size={15} aria-hidden="true" />{copy.restoreOfficialLabel}
</button>
<button type="button" className="cx-providers-button cx-providers-button--secondary" onClick={() => setResetConfirmOpen(true)} disabled={formBusy}>
<FilePlus2 size={15} aria-hidden="true" />{copy.resetOfficialLabel}
</button>
{showDefaultActions && (
<>
<button type="button" className="cx-providers-button cx-providers-button--secondary" onClick={onRestoreOfficial} disabled={formBusy}>
<RotateCcw size={15} aria-hidden="true" />{copy.restoreOfficialLabel}
</button>
<button type="button" className="cx-providers-button cx-providers-button--secondary" onClick={() => setResetConfirmOpen(true)} disabled={formBusy}>
<FilePlus2 size={15} aria-hidden="true" />{copy.resetOfficialLabel}
</button>
</>
)}
<button type="button" className="cx-providers-button cx-providers-button--primary" onClick={onSaveOfficial} disabled={formBusy}><CheckCircle2 size={15} aria-hidden="true" />{copy.officialSaveLabel}</button>
</div>
<ModalShell
open={resetConfirmOpen}
open={resetConfirmOpen && showDefaultActions}
onClose={() => setResetConfirmOpen(false)}
title={copy.resetOfficialTitle}
description={copy.resetOfficialDescription}
@@ -503,7 +691,11 @@ function OfficialForm({
}
function ProviderForm({
lang,
copy,
creatingProvider,
providerKind,
onProviderKindChange,
providerForm,
loading,
editingProviderId,
@@ -525,10 +717,11 @@ function ProviderForm({
onProviderTomlDraftChange,
onResetProviderToml,
onSaveProvider,
}: Pick<ProvidersPageProps, "copy" | "providerForm" | "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" | "providerKind" | "onProviderKindChange" | "providerForm" | "loading" | "editingProviderId" | "providerAuthPreview" | "providerTomlDraft" | "providerTomlRef" | "apiKeyVisible" | "availableModels" | "fetchingModels" | "onCancelMode" | "onApiKeyChange" | "onBaseUrlChange" | "onProviderNameChange" | "onProviderModelChange" | "onFetchModels" | "onWireApiChange" | "onRequiresAuthChange" | "onToggleApiKeyVisibility" | "onProviderTomlDraftChange" | "onResetProviderToml" | "onSaveProvider">) {
const modelListId = useId();
const [contextWindowBusy, setContextWindowBusy] = useState(false);
const canFetchModels = Boolean(providerForm.baseUrl.trim() && providerForm.apiKey.trim());
const formBusy = loading || fetchingModels;
const formBusy = loading || fetchingModels || contextWindowBusy;
return (
<>
@@ -540,6 +733,7 @@ function ProviderForm({
onCancel={onCancelMode}
disabled={formBusy}
/>
<ProviderKindSelect lang={lang} creatingProvider={creatingProvider} providerKind={providerKind} onProviderKindChange={onProviderKindChange} disabled={formBusy} />
<section className="cx-providers-form-section">
<div className="cx-providers-section-heading">
@@ -629,9 +823,12 @@ function ProviderForm({
<section className="cx-providers-form-section">
<div className="cx-providers-section-heading cx-providers-section-heading--with-action">
<div><h3>{copy.tomlTitle}</h3><p>{copy.tomlDescription}</p></div>
<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>
<div className="cx-providers-context-actions">
<ContextWindowControl lang={lang} configText={providerTomlDraft} onConfigChange={onProviderTomlDraftChange} 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>
</div>
</div>
<textarea ref={providerTomlRef} className="cx-providers-code-editor cx-providers-toml-editor" 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) => onProviderTomlDraftChange(event.target.value)} disabled={formBusy} spellCheck={false} />
</section>
<div className="cx-providers-form-actions cx-providers-form-actions--save">
@@ -0,0 +1,316 @@
import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
import type { KeyboardEvent, ReactNode } from "react";
import { invoke } from "@tauri-apps/api/core";
import {
Activity, AlertCircle, ArrowDownLeft, ArrowUpRight, BarChart3,
CalendarDays, Check, Database, Loader2, MessageSquare, RefreshCw,
} from "lucide-react";
import type { LucideIcon } from "lucide-react";
import type { UsageDay, UsageModel, UsageRange, UsageStatistics } from "../usageTypes";
import "../styles/usage-statistics.css";
type Language = "zh" | "en";
export type UsageStatisticsPageProps = {
lang: Language;
configDir: string;
active?: boolean;
};
export function formatUsageTokens(value: number): string {
if (!Number.isFinite(value) || value <= 0) return "0";
const units: [number, string][] = [[1_000_000_000, "B"], [1_000_000, "M"], [1_000, "K"]];
for (const [divisor, unit] of units) {
if (value >= divisor) {
const scaled = value / divisor;
return `${Number(scaled.toFixed(scaled < 10 ? 2 : 1))}${unit}`;
}
}
return Math.round(value).toString();
}
const exact = (value: number, lang: Language) => value.toLocaleString(lang === "zh" ? "zh-CN" : "en-US");
const ratio = (part: number, total: number) => total > 0 ? Math.min(100, Math.max(0, part / total * 100)) : 0;
const percentage = (value: number) => `${Number(value.toFixed(1))}%`;
function modelLabel(model: string, lang: Language): string {
if (model === "unknown") return lang === "zh" ? "未知模型" : "Unknown model";
if (model === "multiple") return lang === "zh" ? "多个模型" : "Multiple models";
return model;
}
function sessionTitleLabel(title: string, lang: Language): string {
return title && title !== "未命名会话" ? title : lang === "zh" ? "未命名会话" : "Untitled session";
}
function dateLabel(date: string, lang: Language, includeYear = false): string {
const value = new Date(date.length === 10 ? `${date}T12:00:00` : date);
if (Number.isNaN(value.getTime())) return date;
return value.toLocaleDateString(lang === "zh" ? "zh-CN" : "en-US", {
...(includeYear ? { year: "numeric" as const } : {}), month: "short", day: "numeric",
});
}
function timestampLabel(date: string, lang: Language): string {
const value = new Date(date);
return Number.isNaN(value.getTime()) ? date : value.toLocaleString(lang === "zh" ? "zh-CN" : "en-US", {
month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hour12: false,
});
}
function copyFor(lang: Language) {
return lang === "zh" ? {
title: "Token 用量统计",
description: "查看 Codex 的 Token 使用情况,了解用量趋势与模型分布。",
range: "统计范围", ranges: { today: "今天", "7d": "近 7 天", "30d": "近 30 天", all: "全部" },
model: "模型", allModels: "全部模型", refresh: "刷新用量", refreshing: "更新中", retry: "重试",
total: "总 Token 用量", totalHint: "输入 + 输出", input: "输入 Token", output: "输出 Token",
freshInput: "未缓存输入", cache: "缓存输入", cached: "已缓存", cacheRate: "缓存命中率",
inputHint: "包含缓存输入", outputHint: "包含推理 Token", reasoning: "推理 Token",
sessions: "活跃会话", sessionsHint: "主会话数量,含子代理产生的用量", tokens: "Token",
trend: "用量趋势", trendHint: "按日查看输入、缓存和输出的构成", peak: "最高用量日",
legendLabel: "Token 构成", chartLabel: "每日 Token 用量;左右方向键切换日期",
breakdown: "每日明细", date: "日期", totalColumn: "合计", modelTitle: "模型分布",
modelHint: "按 Token 用量排序", modelCount: "个模型", modelFilter: "筛选此模型",
recent: "最近会话", recentHint: "展示最近 10 个有用量的主会话;子代理用量合并到所属主会话,总量包含全部符合条件的记录。",
session: "会话", lastActive: "最近活动", noData: "这里将记录你的 Codex 用量",
noDataDescription: "当前范围内还没有可统计的会话记录。使用 Codex 后点击刷新,或试试更大的日期范围。",
showAll: "查看全部时间", loading: "正在整理本地会话用量…",
error: "暂时无法读取用量", stale: "刷新失败,下面保留上次读取的结果。",
partial: "部分记录未计入", partialHint: "部分本地记录不完整,当前结果仅包含可读取的用量。",
source: "本地会话记录", updated: "更新于", notes: "缓存输入已包含在输入 Token 中,推理 Token 已包含在输出 Token 中。历史记录缺失的用量无法补算。",
scanned: "已检查", files: "份记录", filtered: "当前模型", activity: "使用概览",
noModels: "暂无模型用量", zeroDay: "当天无用量",
} : {
title: "Token usage statistics",
description: "Explore your Codex usage, daily activity, and model distribution.",
range: "Date range", ranges: { today: "Today", "7d": "7 days", "30d": "30 days", all: "All time" },
model: "Model", allModels: "All models", refresh: "Refresh usage", refreshing: "Updating", retry: "Retry",
total: "Total token usage", totalHint: "Input + output", input: "Input tokens", output: "Output tokens",
freshInput: "Uncached input", cache: "Cached input", cached: "cached", cacheRate: "Cache hit rate",
inputHint: "Includes cached input", outputHint: "Includes reasoning tokens", reasoning: "Reasoning tokens",
sessions: "Active sessions", sessionsHint: "Main conversations, including subagent usage", tokens: "tokens",
trend: "Usage over time", trendHint: "Daily input, cache, and output breakdown", peak: "Peak day",
legendLabel: "Token breakdown", chartLabel: "Daily token usage; use left and right arrows to explore dates",
breakdown: "Daily details", date: "Date", totalColumn: "Total", modelTitle: "Model distribution",
modelHint: "Ranked by token usage", modelCount: "models", modelFilter: "Filter by this model",
recent: "Recent sessions", recentHint: "Showing the 10 most recent main conversations. Subagent usage is included in its parent conversation; totals include all matching records.",
session: "Session", lastActive: "Last active", noData: "Your Codex usage will appear here",
noDataDescription: "No usage records in this range yet. Refresh after using Codex, or try a broader date range.",
showAll: "View all time", loading: "Reading local session usage…",
error: "Unable to load usage", stale: "Refresh failed. The last available results are shown below.",
partial: "Some records were excluded", partialHint: "Some local records are incomplete. These results include readable usage only.",
source: "Local session records", updated: "Updated", notes: "Cached input is included in input tokens; reasoning is included in output tokens. Usage cannot be recovered from missing historical records.",
scanned: "Checked", files: "records", filtered: "Selected model", activity: "Usage overview",
noModels: "No model usage yet", zeroDay: "No usage this day",
};
}
type UsageCopy = ReturnType<typeof copyFor>;
function TokenValue({ value, lang, className = "" }: { value: number; lang: Language; className?: string }) {
return <span className={`cx-usage-number ${className}`} title={exact(value, lang)} aria-label={exact(value, lang)}>{formatUsageTokens(value)}</span>;
}
function Metric({ icon: Icon, label, children, hint, accent }: {
icon: LucideIcon; label: string; children: ReactNode; hint: ReactNode; accent: string;
}) {
return <article className={`cx-usage-metric cx-usage-metric--${accent}`}>
<div className="cx-usage-metric-label"><Icon size={15} aria-hidden="true" /><span>{label}</span></div>
<div className="cx-usage-metric-value">{children}</div>
<p>{hint}</p>
</article>;
}
function Legend({ copy }: { copy: UsageCopy }) {
return <div className="cx-usage-legend" aria-label={copy.legendLabel}>
<span><i className="cx-usage-swatch--input" />{copy.freshInput}</span>
<span><i className="cx-usage-swatch--cache" />{copy.cache}</span>
<span><i className="cx-usage-swatch--output" />{copy.output}</span>
</div>;
}
function UsageTrend({ days, lang, copy }: { days: UsageDay[]; lang: Language; copy: UsageCopy }) {
const chartId = useId();
const [selectedDate, setSelectedDate] = useState<string | null>(null);
const barsRef = useRef<(SVGGElement | null)[]>([]);
const peakIndex = days.reduce((winner, day, index) => day.totalTokens > (days[winner]?.totalTokens ?? -1) ? index : winner, 0);
const selectedIndex = Math.max(0, selectedDate ? days.findIndex((day) => day.date === selectedDate) : peakIndex);
const selected = days[selectedIndex];
const chartWidth = Math.max(600, days.length * 13 + 56);
const chartHeight = 218;
const baseline = 181;
const top = 15;
const left = 48;
const drawableWidth = chartWidth - left - 12;
const max = Math.max(...days.map((day) => day.inputTokens + day.outputTokens), 1);
const ceiling = max <= 5 ? 5 : Math.ceil(max / 10 ** Math.floor(Math.log10(max))) * 10 ** Math.floor(Math.log10(max));
const step = drawableWidth / Math.max(days.length, 1);
const width = Math.min(38, step * 0.62);
const spansYears = days[0]?.date.slice(0, 4) !== days[days.length - 1]?.date.slice(0, 4);
const scale = (value: number) => value / ceiling * (baseline - top);
const keyDown = (event: KeyboardEvent<SVGGElement>, index: number) => {
let next = index;
if (event.key === "Enter" || event.key === " ") next = index;
else if (event.key === "ArrowLeft") next = Math.max(0, index - 1);
else if (event.key === "ArrowRight") next = Math.min(days.length - 1, index + 1);
else if (event.key === "Home") next = 0;
else if (event.key === "End") next = days.length - 1;
else return;
event.preventDefault();
setSelectedDate(days[next].date);
barsRef.current[next]?.focus();
};
return <section className="cx-usage-card cx-usage-trend">
<div className="cx-usage-card-heading"><div><h3>{copy.trend}</h3><p>{copy.trendHint}</p></div><BarChart3 size={18} aria-hidden="true" /></div>
<Legend copy={copy} />
{selected && <div className="cx-usage-day-summary" id={`${chartId}-selection`} aria-live="polite" aria-atomic="true">
<div><strong>{dateLabel(selected.date, lang, true)}</strong>{selectedIndex === peakIndex && selected.totalTokens > 0 && <span>{copy.peak}</span>}</div>
<div><TokenValue value={selected.totalTokens} lang={lang} /><small>{copy.tokens}</small></div>
<p>{copy.input} {exact(selected.inputTokens, lang)} · {copy.cache} {exact(selected.cachedInputTokens, lang)} · {copy.output} {exact(selected.outputTokens, lang)}</p>
</div>}
<div className="cx-usage-chart-scroll">
<svg className="cx-usage-chart" viewBox={`0 0 ${chartWidth} ${chartHeight}`} style={{ minWidth: Math.max(440, days.length * 11 + 56) }} role="group" aria-label={copy.chartLabel}>
{[0, 0.5, 1].map((fraction) => <g key={fraction} aria-hidden="true">
<line x1={left} x2={chartWidth - 12} y1={baseline - scale(ceiling * fraction)} y2={baseline - scale(ceiling * fraction)} className="cx-usage-gridline" />
<text x={left - 9} y={baseline - scale(ceiling * fraction) + 3} textAnchor="end" className="cx-usage-axis">{formatUsageTokens(ceiling * fraction)}</text>
</g>)}
{days.map((day, index) => {
const cached = Math.min(day.cachedInputTokens, day.inputTokens);
const fresh = Math.max(0, day.inputTokens - cached);
const inputHeight = scale(fresh);
const cachedHeight = scale(cached);
const outputHeight = scale(day.outputTokens);
const x = left + step * index + (step - width) / 2;
const showLabel = days.length <= 8 || index === days.length - 1 || index % Math.ceil(days.length / 7) === 0;
const label = `${dateLabel(day.date, lang, true)}: ${copy.input} ${exact(day.inputTokens, lang)}, ${copy.cache} ${exact(cached, lang)}, ${copy.output} ${exact(day.outputTokens, lang)}, ${copy.totalColumn} ${exact(day.totalTokens, lang)}`;
return <g key={day.date} ref={(element) => { barsRef.current[index] = element; }} className={`cx-usage-day${index === selectedIndex ? " cx-usage-day--selected" : ""}`} role="button" tabIndex={index === selectedIndex ? 0 : -1} aria-label={label} aria-pressed={index === selectedIndex} onMouseEnter={() => setSelectedDate(day.date)} onFocus={() => setSelectedDate(day.date)} onClick={() => setSelectedDate(day.date)} onKeyDown={(event) => keyDown(event, index)}>
<title>{label}</title>
<rect x={left + step * index} y={top - 4} width={step} height={baseline - top + 10} rx={4} className="cx-usage-chart-hit" />
<rect x={x} y={baseline - inputHeight} width={width} height={inputHeight} className="cx-usage-swatch--input" />
<rect x={x} y={baseline - inputHeight - cachedHeight} width={width} height={cachedHeight} className="cx-usage-swatch--cache" />
<rect x={x} y={baseline - inputHeight - cachedHeight - outputHeight} width={width} height={outputHeight} className="cx-usage-swatch--output" />
{day.totalTokens === 0 && <rect x={x} y={baseline - 2} width={width} height={2} rx={1} className="cx-usage-zero-bar" />}
{showLabel && <text x={x + width / 2} y={baseline + 22} textAnchor="middle" className="cx-usage-axis" aria-hidden="true">{dateLabel(day.date, lang, spansYears)}</text>}
</g>;
})}
</svg>
</div>
<details className="cx-usage-daily-details"><summary>{copy.breakdown}<span>{days.length}</span></summary>
<div className="cx-usage-table-scroll"><table className="cx-usage-table"><caption className="cx-usage-sr-only">{copy.breakdown}</caption><thead><tr><th>{copy.date}</th><th>{copy.input}</th><th>{copy.cache}</th><th>{copy.output}</th><th>{copy.totalColumn}</th></tr></thead><tbody>
{days.map((day) => <tr key={day.date}><th scope="row">{dateLabel(day.date, lang, true)}</th><td>{exact(day.inputTokens, lang)}</td><td>{exact(day.cachedInputTokens, lang)}</td><td>{exact(day.outputTokens, lang)}</td><td>{exact(day.totalTokens, lang)}</td></tr>)}
</tbody></table></div>
</details>
</section>;
}
function ModelDistribution({ models, lang, copy, onModel }: { models: UsageModel[]; lang: Language; copy: UsageCopy; onModel: (model: string) => void }) {
const rows = [...models].sort((a, b) => b.totalTokens - a.totalTokens);
const total = rows.reduce((sum, model) => sum + model.totalTokens, 0);
const circumference = 2 * Math.PI * 58;
let cumulative = 0;
return <section className="cx-usage-card cx-usage-models">
<div className="cx-usage-card-heading"><div><h3>{copy.modelTitle}</h3><p>{copy.modelHint}</p></div></div>
<div className="cx-usage-donut-wrap"><svg className="cx-usage-donut" viewBox="0 0 160 160" role="img" aria-label={`${copy.modelTitle}: ${rows.map((row) => `${modelLabel(row.model, lang)} ${percentage(ratio(row.totalTokens, total))}`).join(", ")}`}>
<circle cx="80" cy="80" r="58" fill="none" className="cx-usage-donut-track" strokeWidth="15" />
{rows.map((row, index) => {
const fraction = total > 0 ? row.totalTokens / total : 0;
const offset = cumulative;
cumulative += fraction;
return <circle key={row.model} cx="80" cy="80" r="58" fill="none" strokeWidth="15" strokeDasharray={`${Math.max(0, fraction * circumference - (rows.length > 1 ? 3 : 0))} ${circumference}`} strokeDashoffset={-offset * circumference} transform="rotate(-90 80 80)" className={`cx-usage-model-color-${index % 5}`}><title>{modelLabel(row.model, lang)}: {exact(row.totalTokens, lang)} {copy.tokens}</title></circle>;
})}
</svg><div className="cx-usage-donut-label"><strong>{rows.length}</strong><span>{copy.modelCount}</span></div></div>
<div className="cx-usage-model-list">
{rows.length === 0 && <p className="cx-usage-muted">{copy.noModels}</p>}
{rows.map((row, index) => <button key={row.model} type="button" className="cx-usage-model-row" onClick={() => onModel(row.model)} title={`${copy.modelFilter}: ${modelLabel(row.model, lang)}`}>
<span className={`cx-usage-model-dot cx-usage-model-color-${index % 5}`} aria-hidden="true" />
<span className="cx-usage-model-name">{modelLabel(row.model, lang)}</span>
<span className="cx-usage-model-amount"><TokenValue value={row.totalTokens} lang={lang} /><small>{percentage(ratio(row.totalTokens, total))}</small></span>
</button>)}
</div>
</section>;
}
export function UsageStatisticsPage({ lang, configDir, active = true }: UsageStatisticsPageProps) {
const copy = copyFor(lang);
const [range, setRange] = useState<UsageRange>("7d");
const [model, setModel] = useState("");
const [record, setRecord] = useState<{ key: string; data: UsageStatistics } | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const requestRef = useRef(0);
const previousDir = useRef(configDir);
const queryKey = JSON.stringify([configDir, range, model]);
const data = record?.key === queryKey ? record.data : null;
const load = useCallback(async (forceRefresh = false) => {
if (!active) return;
const request = ++requestRef.current;
setBusy(true);
setError("");
try {
const next = await invoke<UsageStatistics>("get_usage_statistics", { configDir, range, model: model || null, forceRefresh });
if (request === requestRef.current) setRecord({ key: queryKey, data: next });
} catch (cause) {
if (request === requestRef.current) setError(cause instanceof Error ? cause.message : String(cause));
} finally {
if (request === requestRef.current) setBusy(false);
}
}, [active, configDir, range, model, queryKey]);
useEffect(() => {
if (previousDir.current !== configDir) {
previousDir.current = configDir;
if (model) {
setModel("");
return;
}
}
void load();
return () => { requestRef.current += 1; };
}, [configDir, model, load]);
const modelOptions = useMemo(() => {
const available = record?.key && JSON.parse(record.key)[0] === configDir ? record.data.availableModels : [];
return Array.from(new Set([...available, ...(model ? [model] : [])])).sort();
}, [record, configDir, model]);
const partial = data && (data.coverage.skippedFiles > 0 || data.coverage.truncated || data.coverage.warnings.length > 0);
const hasUsage = data && data.totals.totalTokens > 0;
const cacheRate = data ? ratio(data.totals.cachedInputTokens, data.totals.inputTokens) : 0;
return <div className="cx-usage" aria-busy={busy}>
<header className="cx-usage-heading"><div><h3>{copy.title}</h3><p>{copy.description}</p></div><span className="cx-usage-local-badge"><Database size={12} aria-hidden="true" />{copy.source}</span></header>
<div className="cx-usage-toolbar">
<div className="cx-usage-range" role="group" aria-label={copy.range}>
{(Object.keys(copy.ranges) as UsageRange[]).map((value) => <button key={value} type="button" aria-pressed={range === value} className={range === value ? "cx-usage-range-active" : ""} onClick={() => setRange(value)}>{copy.ranges[value]}</button>)}
</div>
<div className="cx-usage-toolbar-actions"><label className="cx-usage-model-select"><span className="cx-usage-sr-only">{copy.model}</span><select value={model} onChange={(event) => setModel(event.currentTarget.value)} aria-label={copy.model}><option value="">{copy.allModels}</option>{modelOptions.map((value) => <option key={value} value={value}>{modelLabel(value, lang)}</option>)}</select></label>
<button type="button" className="cx-page-button cx-page-button--secondary cx-usage-refresh" disabled={busy} onClick={() => void load(true)}><RefreshCw size={14} className={busy ? "cx-page-spin" : ""} aria-hidden="true" />{busy ? copy.refreshing : copy.refresh}</button>
</div>
</div>
{error && <div className="cx-usage-notice cx-usage-notice--error" role="alert"><AlertCircle size={18} aria-hidden="true" /><div><strong>{copy.error}</strong>{data && <p>{copy.stale}</p>}<p>{error}</p></div><button type="button" onClick={() => void load(true)} disabled={busy}>{copy.retry}</button></div>}
{!data && !error && <div className="cx-usage-loading" role="status"><Loader2 size={27} className="cx-page-spin" aria-hidden="true" /><p>{copy.loading}</p><div className="cx-usage-loading-cards" aria-hidden="true"><span /><span /><span /></div></div>}
{partial && <div className="cx-usage-notice cx-usage-notice--warning" role="status"><AlertCircle size={18} aria-hidden="true" /><div><strong>{copy.partial}</strong><p>{copy.partialHint}</p>{data.coverage.warnings.length > 0 && <details><summary>{lang === "zh" ? "查看详情" : "View details"}</summary><ul>{data.coverage.warnings.map((warning, index) => <li key={`${index}-${warning}`}>{warning}</li>)}</ul></details>}</div></div>}
{data && !hasUsage && <section className="cx-usage-empty"><div className="cx-usage-empty-visual" aria-hidden="true"><span /><span /><span /><span /><BarChart3 size={23} /></div><h3>{copy.noData}</h3><p>{copy.noDataDescription}</p>{(range !== "all" || model) && <button type="button" className="cx-page-button cx-page-button--secondary" onClick={() => { setRange("all"); setModel(""); }}>{copy.showAll}</button>}</section>}
{data && hasUsage && <>
<section className="cx-usage-summary" aria-label={copy.activity}>
<article className="cx-usage-total">
<div className="cx-usage-total-heading"><span><Activity size={16} aria-hidden="true" />{copy.total}</span><span className="cx-usage-period-label">{copy.ranges[range]}</span></div>
<div className="cx-usage-total-value"><TokenValue value={data.totals.totalTokens} lang={lang} /><span>{copy.tokens}</span></div>
<div className="cx-usage-total-caption"><span>{exact(data.totals.totalTokens, lang)} {copy.tokens}</span><span>{copy.totalHint}</span></div>
<div className="cx-usage-composition" aria-hidden="true"><span className="cx-usage-swatch--input" style={{ width: `${ratio(data.totals.inputTokens - data.totals.cachedInputTokens, data.totals.totalTokens)}%` }} /><span className="cx-usage-swatch--cache" style={{ width: `${ratio(data.totals.cachedInputTokens, data.totals.totalTokens)}%` }} /><span className="cx-usage-swatch--output" style={{ width: `${ratio(data.totals.outputTokens, data.totals.totalTokens)}%` }} /></div>
<div className="cx-usage-total-footer"><CalendarDays size={12} aria-hidden="true" /><span>{data.rangeStart ? `${dateLabel(data.rangeStart, lang, true)} – ${dateLabel(data.rangeEnd, lang, true)}` : copy.ranges.all}</span></div>
</article>
<div className="cx-usage-metrics">
<Metric icon={ArrowDownLeft} label={copy.input} hint={copy.inputHint} accent="input"><TokenValue value={data.totals.inputTokens} lang={lang} /></Metric>
<Metric icon={ArrowUpRight} label={copy.output} hint={<>{copy.reasoning} <TokenValue value={data.totals.reasoningTokens} lang={lang} /></>} accent="output"><TokenValue value={data.totals.outputTokens} lang={lang} /></Metric>
<Metric icon={Database} label={copy.cacheRate} hint={<><TokenValue value={data.totals.cachedInputTokens} lang={lang} /> {copy.cached}</>} accent="cache"><span className="cx-usage-number">{percentage(cacheRate)}</span></Metric>
<Metric icon={MessageSquare} label={copy.sessions} hint={copy.sessionsHint} accent="sessions"><TokenValue value={data.totals.sessionCount} lang={lang} /></Metric>
</div>
</section>
<div className="cx-usage-charts"><UsageTrend days={data.days} lang={lang} copy={copy} /><ModelDistribution models={data.models} lang={lang} copy={copy} onModel={setModel} /></div>
<section className="cx-usage-card cx-usage-sessions"><div className="cx-usage-card-heading"><div><h3>{copy.recent}<span className="cx-usage-count">{data.sessions.length}</span></h3><p>{copy.recentHint}</p></div><MessageSquare size={18} aria-hidden="true" /></div>
<div className="cx-usage-table-scroll"><table className="cx-usage-table"><caption className="cx-usage-sr-only">{copy.recent}</caption><thead><tr><th>{copy.session}</th><th>{copy.model}</th><th>{copy.input}</th><th>{copy.output}</th><th>{copy.totalColumn}</th><th>{copy.lastActive}</th></tr></thead><tbody>{data.sessions.map((session) => <tr key={`${session.id}-${session.model}`}><th scope="row"><span className="cx-usage-session-name" title={sessionTitleLabel(session.title, lang)}>{sessionTitleLabel(session.title, lang)}</span></th><td><span className="cx-usage-session-model" title={modelLabel(session.model, lang)}>{modelLabel(session.model, lang)}</span></td><td><TokenValue value={session.inputTokens} lang={lang} /></td><td><TokenValue value={session.outputTokens} lang={lang} /></td><td className="cx-usage-cell-total"><TokenValue value={session.totalTokens} lang={lang} /></td><td className="cx-usage-cell-date">{timestampLabel(session.lastActiveAt, lang)}</td></tr>)}</tbody></table></div>
</section>
</>}
{data && <footer className="cx-usage-footer"><div><Check size={12} aria-hidden="true" /><span>{copy.updated} {timestampLabel(data.refreshedAt, lang)} · {data.timezone} · {copy.scanned} {exact(data.coverage.scannedFiles, lang)} {copy.files}</span></div><p>{copy.notes}</p></footer>}
</div>;
}
+111 -68
View File
@@ -1,7 +1,8 @@
import { useState } from "react";
import { createContext, useContext, useId, useRef, useState } from "react";
import type { ReactNode } from "react";
import {
CheckCircle2,
BarChart3,
Download,
ExternalLink,
Globe2,
@@ -9,9 +10,12 @@ import {
Power,
RefreshCw,
Sparkles,
SlidersHorizontal,
} from "lucide-react";
import type { LucideIcon } from "lucide-react";
import { PageTransition } from "../components/PageTransition";
import { Button, ModalShell } from "../components/ui";
import { UsageStatisticsPage } from "./UsageStatisticsPage";
import "../styles/utility-pages.css";
export type UtilityLanguage = "zh" | "en";
@@ -100,6 +104,8 @@ export type SettingsCopy = {
export type SettingsPageProps = {
lang: UtilityLanguage;
configDir: string;
active?: boolean;
copy: SettingsCopy;
onLanguageChange: (lang: UtilityLanguage) => void;
onRecheck: () => void;
@@ -108,6 +114,16 @@ export type SettingsPageProps = {
restartBusy?: boolean;
};
// PageTransition keeps the previous content during its exit animation. Context
// still propagates the current activity state so requests stop immediately,
// while the retained usage component keeps its filters between tabs.
const SettingsUsageActiveContext = createContext(false);
function SettingsUsagePanel({ lang, configDir }: Pick<SettingsPageProps, "lang" | "configDir">) {
const active = useContext(SettingsUsageActiveContext);
return <UsageStatisticsPage lang={lang} configDir={configDir} active={active} />;
}
type SettingRowProps = {
icon: LucideIcon;
title: ReactNode;
@@ -132,6 +148,8 @@ function SettingRow({ icon: Icon, title, description, action }: SettingRowProps)
export function SettingsPage({
lang,
configDir,
active = true,
copy,
onLanguageChange,
onRecheck,
@@ -139,6 +157,10 @@ export function SettingsPage({
recheckBusy = false,
restartBusy = false,
}: SettingsPageProps) {
const [tab, setTab] = useState<"general" | "usage">("general");
const [usageOpened, setUsageOpened] = useState(false);
const tabId = useId();
const tabRefs = useRef<(HTMLButtonElement | null)[]>([]);
const [restartConfirmOpen, setRestartConfirmOpen] = useState(false);
const closeRestartConfirm = () => {
if (!restartBusy) setRestartConfirmOpen(false);
@@ -151,74 +173,95 @@ export function SettingsPage({
return (
<section className="cx-utility cx-page cx-page--settings">
<PageHeader eyebrow={copy.eyebrow} title={copy.title} />
<div className="cx-page-settings-list">
<SettingRow
icon={Globe2}
title={copy.languageTitle}
description={copy.languageDescription}
action={(
<div className="cx-page-segmented" role="group" aria-label={String(copy.languageTitle)}>
<button
type="button"
className={lang === "zh" ? "cx-page-segmented-button cx-page-segmented-button--active" : "cx-page-segmented-button"}
onClick={() => onLanguageChange("zh")}
aria-pressed={lang === "zh"}
>
{copy.chineseLabel}
</button>
<button
type="button"
className={lang === "en" ? "cx-page-segmented-button cx-page-segmented-button--active" : "cx-page-segmented-button"}
onClick={() => onLanguageChange("en")}
aria-pressed={lang === "en"}
>
{copy.englishLabel}
</button>
</div>
)}
/>
<SettingRow
icon={Sparkles}
title={copy.productTitle}
description={copy.productDescription}
action={<span className="cx-page-value-pill">{copy.productValue}</span>}
/>
<SettingRow
icon={CheckCircle2}
title={copy.recheckTitle}
description={copy.recheckDescription}
action={(
<button
type="button"
className="cx-page-button cx-page-button--secondary"
onClick={onRecheck}
disabled={recheckBusy}
>
{recheckBusy && <Loader2 size={15} className="cx-page-spin" aria-hidden="true" />}
{copy.recheckLabel}
</button>
)}
/>
<SettingRow
icon={Power}
title={copy.restartTitle}
description={copy.restartDescription}
action={(
<button
type="button"
className="cx-page-button cx-page-button--secondary"
onClick={() => setRestartConfirmOpen(true)}
disabled={restartBusy}
>
{restartBusy ? <Loader2 size={15} className="cx-page-spin" aria-hidden="true" /> : <Power size={15} aria-hidden="true" />}
{restartBusy ? copy.restartingLabel : copy.restartLabel}
</button>
)}
/>
<div className="cx-settings-tabs" role="tablist" aria-label={lang === "zh" ? "设置页面" : "Settings pages"}>
{(["general", "usage"] as const).map((value, index) => {
const Icon = value === "general" ? SlidersHorizontal : BarChart3;
const select = () => { setTab(value); if (value === "usage") setUsageOpened(true); };
return <button key={value} ref={(element) => { tabRefs.current[index] = element; }} type="button" role="tab" id={`${tabId}-${value}-tab`} aria-controls={`${tabId}-${value}-panel`} aria-selected={tab === value} tabIndex={tab === value ? 0 : -1} className="cx-settings-tab" onClick={select} onKeyDown={(event) => {
if (!["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) return;
event.preventDefault();
const next = event.key === "Home" ? 0 : event.key === "End" ? 1 : 1 - index;
tabRefs.current[next]?.click();
tabRefs.current[next]?.focus();
}}><Icon size={14} aria-hidden="true" />{value === "general" ? (lang === "zh" ? "通用设置" : "General") : (lang === "zh" ? "用量统计" : "Usage statistics")}</button>;
})}
</div>
<SettingsUsageActiveContext.Provider value={active && tab === "usage"}>
<PageTransition pageKey={`settings:${tab}`}>
<div className="cx-settings-panel cx-page-settings-list" role="tabpanel" id={`${tabId}-general-panel`} aria-labelledby={`${tabId}-general-tab`} hidden={tab !== "general"}>
<SettingRow
icon={Globe2}
title={copy.languageTitle}
description={copy.languageDescription}
action={(
<div className="cx-page-segmented" role="group" aria-label={String(copy.languageTitle)}>
<button
type="button"
className={lang === "zh" ? "cx-page-segmented-button cx-page-segmented-button--active" : "cx-page-segmented-button"}
onClick={() => onLanguageChange("zh")}
aria-pressed={lang === "zh"}
>
{copy.chineseLabel}
</button>
<button
type="button"
className={lang === "en" ? "cx-page-segmented-button cx-page-segmented-button--active" : "cx-page-segmented-button"}
onClick={() => onLanguageChange("en")}
aria-pressed={lang === "en"}
>
{copy.englishLabel}
</button>
</div>
)}
/>
<SettingRow
icon={Sparkles}
title={copy.productTitle}
description={copy.productDescription}
action={<span className="cx-page-value-pill">{copy.productValue}</span>}
/>
<SettingRow
icon={CheckCircle2}
title={copy.recheckTitle}
description={copy.recheckDescription}
action={(
<button
type="button"
className="cx-page-button cx-page-button--secondary"
onClick={onRecheck}
disabled={recheckBusy}
>
{recheckBusy && <Loader2 size={15} className="cx-page-spin" aria-hidden="true" />}
{copy.recheckLabel}
</button>
)}
/>
<SettingRow
icon={Power}
title={copy.restartTitle}
description={copy.restartDescription}
action={(
<button
type="button"
className="cx-page-button cx-page-button--secondary"
onClick={() => setRestartConfirmOpen(true)}
disabled={restartBusy}
>
{restartBusy ? <Loader2 size={15} className="cx-page-spin" aria-hidden="true" /> : <Power size={15} aria-hidden="true" />}
{restartBusy ? copy.restartingLabel : copy.restartLabel}
</button>
)}
/>
</div>
<div className="cx-settings-panel" role="tabpanel" id={`${tabId}-usage-panel`} aria-labelledby={`${tabId}-usage-tab`} hidden={tab !== "usage"}>
{usageOpened && <SettingsUsagePanel lang={lang} configDir={configDir} />}
</div>
</PageTransition>
</SettingsUsageActiveContext.Provider>
<ModalShell
open={restartConfirmOpen}
@@ -632,6 +632,52 @@
line-height: 1.4;
}
.cx-providers-context-heading,
.cx-providers-context-actions {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 10px 18px;
}
.cx-providers-context-heading {
margin-bottom: 8px;
}
.cx-providers-context-heading > span {
color: var(--cx-provider-muted);
font-size: 11px;
font-weight: 660;
}
.cx-providers-context-actions {
justify-content: flex-end;
}
.cx-providers-context-control {
display: grid;
justify-items: start;
gap: 4px;
}
.cx-providers-context-checkbox {
min-height: 20px;
color: var(--cx-provider-text);
}
.cx-providers-context-hint,
.cx-providers-context-error {
max-width: 310px;
color: var(--cx-provider-muted);
font-size: 10px;
line-height: 1.4;
}
.cx-providers-context-error {
color: #c85042;
}
.cx-providers-preview {
min-width: 0;
max-height: 240px;
@@ -673,10 +673,6 @@
border-color: #5944d5;
}
.cx-prompts-heading > p {
color: var(--cx-prompt-accent);
}
.cx-prompts-mode-panel {
position: relative;
min-width: 0;
@@ -0,0 +1,246 @@
.cx-settings-tabs {
display: inline-flex;
gap: 3px;
padding: 4px;
margin-bottom: 22px;
border: 1px solid var(--cx-page-border);
border-radius: 9px;
background: var(--cx-page-status-neutral);
}
.cx-settings-tab {
min-height: 34px;
min-width: 128px;
display: inline-flex;
justify-content: center;
align-items: center;
gap: 8px;
padding: 0 15px;
border: 1px solid transparent;
border-radius: 6px;
color: var(--cx-page-muted);
background: transparent;
font-size: 12px;
font-weight: 650;
}
.cx-settings-tab:hover { color: var(--cx-page-text); background: var(--cx-page-surface-hover); }
.cx-settings-tab[aria-selected="true"] { color: var(--cx-page-blue); border-color: var(--cx-page-border); background: var(--cx-page-surface); box-shadow: 0 1px 3px #2022260d; }
.cx-settings-tab:focus-visible,
.cx-usage button:focus-visible,
.cx-usage select:focus-visible,
.cx-usage summary:focus-visible { outline: 2px solid var(--cx-page-blue); outline-offset: 3px; }
.cx-settings-panel[hidden] { display: none; }
.cx-usage {
--cx-usage-input: #3b6fea;
--cx-usage-cache: #96b9fa;
--cx-usage-output: #25acb5;
--cx-usage-hero: #eef4ff;
--cx-usage-hero-border: #d9e5fd;
--cx-usage-hero-text: #183c80;
--cx-usage-warning: #8a601b;
--cx-usage-warning-bg: #fffbef;
--cx-usage-warning-border: #f0e2bd;
--cx-usage-error: #ae3b43;
--cx-usage-error-bg: #fff3f4;
--cx-usage-error-border: #f0cfd2;
display: grid;
gap: 18px;
min-width: 0;
padding-bottom: 8px;
}
.cx-usage-heading { display: flex; justify-content: space-between; align-items: flex-start; gap: 14px; }
.cx-usage-heading h3 { margin: 0; font-size: 17px; line-height: 1.4; font-weight: 690; letter-spacing: -.02em; color: var(--cx-page-text); }
.cx-usage-heading p { margin: 5px 0 0; color: var(--cx-page-muted); font-size: 12px; line-height: 1.6; }
.cx-usage-local-badge { display: inline-flex; align-items: center; gap: 5px; flex-shrink: 0; padding: 5px 8px; border: 1px solid var(--cx-page-border-soft); border-radius: 6px; color: var(--cx-page-muted); font-size: 10px; background: var(--cx-page-surface); }
.cx-usage-toolbar { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; }
.cx-usage-range { display: inline-flex; gap: 3px; padding: 3px; border: 1px solid var(--cx-page-border); border-radius: 8px; background: var(--cx-page-surface); }
.cx-usage-range button { min-height: 30px; padding: 0 14px; border: none; border-radius: 5px; background: transparent; color: var(--cx-page-muted); font-size: 11px; font-weight: 640; }
.cx-usage-range button:hover { color: var(--cx-page-blue); background: var(--cx-page-surface-hover); }
.cx-usage-range button.cx-usage-range-active { color: var(--cx-page-blue); background: var(--cx-page-blue-soft); }
.cx-usage-toolbar-actions { min-width: 0; display: flex; align-items: center; gap: 8px; }
.cx-usage-model-select { min-width: 0; display: block; }
.cx-usage-model-select select { width: 170px; max-width: 100%; height: 38px; padding: 0 24px 0 11px; border: 1px solid var(--cx-page-border); border-radius: 7px; background: var(--cx-page-control); color: var(--cx-page-text); font-size: 11px; text-overflow: ellipsis; }
.cx-usage .cx-usage-refresh { min-height: 38px; padding: 0 12px; font-size: 11px; white-space: nowrap; }
.cx-usage-number { font-variant-numeric: tabular-nums; letter-spacing: -.025em; }
.cx-usage-muted { color: var(--cx-page-muted); font-size: 12px; }
.cx-usage-summary { display: grid; grid-template-columns: minmax(220px, 1.05fr) minmax(0, 1.6fr); gap: 14px; }
.cx-usage-total { display: flex; flex-direction: column; justify-content: center; min-width: 0; padding: 20px 22px 16px; border: 1px solid var(--cx-usage-hero-border); border-radius: 12px; background: var(--cx-usage-hero); color: var(--cx-usage-hero-text); }
.cx-usage-total-heading { display: flex; align-items: center; justify-content: space-between; gap: 10px; font-size: 12px; font-weight: 660; }
.cx-usage-total-heading > span:first-child { display: inline-flex; align-items: center; gap: 7px; }
.cx-usage-period-label { white-space: nowrap; padding: 4px 6px; border: 1px solid var(--cx-usage-hero-border); border-radius: 5px; font-size: 10px; font-weight: 560; }
.cx-usage-total-value { display: flex; align-items: baseline; flex-wrap: wrap; column-gap: 9px; margin-top: 17px; }
.cx-usage-total-value > .cx-usage-number { font-size: clamp(34px, 4.3vw, 47px); font-weight: 740; line-height: 1.2; letter-spacing: -.055em; overflow-wrap: anywhere; }
.cx-usage-total-value > span:last-child { font-size: 12px; opacity: .75; }
.cx-usage-total-caption { display: flex; align-items: center; flex-wrap: wrap; justify-content: space-between; gap: 5px 9px; margin-top: 5px; font-size: 10px; line-height: 1.5; opacity: .76; font-variant-numeric: tabular-nums; }
.cx-usage-total-caption > span { overflow-wrap: anywhere; }
.cx-usage-composition { display: flex; width: 100%; height: 6px; margin-top: 19px; overflow: hidden; border-radius: 5px; background: var(--cx-page-border); }
.cx-usage-composition > span { height: 100%; }
.cx-usage-total-footer { display: flex; align-items: center; gap: 6px; margin-top: 12px; font-size: 10px; line-height: 1.5; opacity: .8; }
.cx-usage-total-footer > svg { flex-shrink: 0; }
.cx-usage-metrics { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 11px; }
.cx-usage-metric { min-width: 0; padding: 15px 17px 12px; border: 1px solid var(--cx-page-border); border-radius: 10px; background: var(--cx-page-surface); }
.cx-usage-metric-label { display: flex; align-items: center; gap: 7px; color: var(--cx-page-muted); font-size: 11px; line-height: 1.5; }
.cx-usage-metric-label > svg { color: var(--cx-page-blue); flex-shrink: 0; }
.cx-usage-metric--output .cx-usage-metric-label > svg { color: var(--cx-usage-output); }
.cx-usage-metric-value { margin-top: 7px; color: var(--cx-page-text); font-size: 26px; font-weight: 700; line-height: 1.2; overflow-wrap: anywhere; }
.cx-usage-metric p { margin: 5px 0 0; color: var(--cx-page-muted); font-size: 10px; line-height: 1.5; }
.cx-usage-metric p .cx-usage-number { font-weight: 600; }
.cx-usage-charts { display: grid; grid-template-columns: minmax(0, 1.8fr) minmax(210px, 1fr); align-items: start; gap: 14px; }
.cx-usage-card { min-width: 0; border: 1px solid var(--cx-page-border); border-radius: 11px; background: var(--cx-page-surface); box-shadow: 0 3px 14px #1b233005; }
.cx-usage-card-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; padding: 18px 18px 0; }
.cx-usage-card-heading h3 { display: flex; align-items: center; gap: 8px; margin: 0; color: var(--cx-page-text); font-size: 13px; font-weight: 690; line-height: 1.45; }
.cx-usage-card-heading p { margin: 4px 0 0; color: var(--cx-page-muted); font-size: 10px; line-height: 1.6; }
.cx-usage-card-heading > svg { flex-shrink: 0; margin-top: 1px; color: var(--cx-page-subtle); }
.cx-usage-legend { display: flex; align-items: center; flex-wrap: wrap; gap: 7px 14px; padding: 12px 18px 0; }
.cx-usage-legend > span { display: inline-flex; align-items: center; gap: 5px; color: var(--cx-page-muted); font-size: 10px; }
.cx-usage-legend i { display: block; width: 7px; height: 7px; border-radius: 2px; }
.cx-usage-swatch--input { fill: var(--cx-usage-input); background: var(--cx-usage-input); }
.cx-usage-swatch--cache { fill: var(--cx-usage-cache); background: var(--cx-usage-cache); }
.cx-usage-swatch--output { fill: var(--cx-usage-output); background: var(--cx-usage-output); }
.cx-usage-day-summary { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 5px 10px; margin: 15px 18px 3px; padding: 10px 12px; border: 1px solid var(--cx-page-border-soft); border-radius: 7px; background: var(--cx-page-surface-muted); }
.cx-usage-day-summary > div { display: flex; align-items: center; gap: 7px; flex-wrap: wrap; }
.cx-usage-day-summary strong { color: var(--cx-page-text); font-size: 11px; font-weight: 610; }
.cx-usage-day-summary > div:first-child > span { color: var(--cx-page-blue); font-size: 9px; }
.cx-usage-day-summary .cx-usage-number { color: var(--cx-page-text); font-size: 15px; font-weight: 700; }
.cx-usage-day-summary small { color: var(--cx-page-muted); font-size: 9px; }
.cx-usage-day-summary p { grid-column: 1 / -1; margin: 0; color: var(--cx-page-muted); font-size: 9px; line-height: 1.65; overflow-wrap: anywhere; font-variant-numeric: tabular-nums; }
.cx-usage-chart-scroll { overflow-x: auto; padding: 4px 12px 0 5px; scrollbar-width: thin; }
.cx-usage-chart { display: block; width: 100%; height: auto; max-height: 240px; }
.cx-usage-gridline { stroke: var(--cx-page-border-soft); stroke-width: 1; stroke-dasharray: 3 4; }
.cx-usage-axis { fill: var(--cx-page-muted); font-size: 10px; font-family: inherit; }
.cx-usage-chart-hit { fill: transparent; }
.cx-usage-day { cursor: pointer; outline: none; }
.cx-usage-day--selected .cx-usage-chart-hit { fill: var(--cx-page-blue-soft); }
.cx-usage-day:focus-visible .cx-usage-chart-hit { stroke: var(--cx-page-blue); stroke-width: 1.5; }
.cx-usage-zero-bar { fill: var(--cx-page-border); }
.cx-usage-daily-details { border-top: 1px solid var(--cx-page-border-soft); }
.cx-usage-daily-details > summary { display: flex; align-items: center; gap: 8px; padding: 11px 18px; color: var(--cx-page-muted); font-size: 10px; cursor: pointer; }
.cx-usage-daily-details > summary::before { content: "+"; color: var(--cx-page-subtle); font-size: 13px; }
.cx-usage-daily-details[open] > summary::before { content: "−"; }
.cx-usage-daily-details > summary::-webkit-details-marker { display: none; }
.cx-usage-daily-details > summary > span { margin-left: auto; color: var(--cx-page-subtle); font-variant-numeric: tabular-nums; }
.cx-usage-daily-details .cx-usage-table-scroll { max-height: 290px; }
.cx-usage-donut-wrap { position: relative; width: 150px; margin: 11px auto 5px; }
.cx-usage-donut { display: block; width: 150px; height: 150px; }
.cx-usage-donut-track { stroke: var(--cx-page-border-soft); }
.cx-usage-donut-label { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; pointer-events: none; }
.cx-usage-donut-label strong { color: var(--cx-page-text); font-size: 28px; font-weight: 700; line-height: 1.2; font-variant-numeric: tabular-nums; }
.cx-usage-donut-label span { color: var(--cx-page-muted); font-size: 10px; margin-top: 4px; }
.cx-usage-model-color-0 { stroke: #3b6fea; background: #3b6fea; }
.cx-usage-model-color-1 { stroke: #25acb5; background: #25acb5; }
.cx-usage-model-color-2 { stroke: #91b7fa; background: #91b7fa; }
.cx-usage-model-color-3 { stroke: #8983cc; background: #8983cc; }
.cx-usage-model-color-4 { stroke: #d5a159; background: #d5a159; }
.cx-usage-model-list { display: grid; max-height: 212px; overflow-y: auto; padding: 0 11px 11px; scrollbar-width: thin; }
.cx-usage-model-row { min-width: 0; display: grid; grid-template-columns: 7px minmax(0, 1fr) auto; align-items: center; gap: 8px; padding: 9px 7px; border: 0; border-radius: 6px; text-align: left; color: var(--cx-page-text); background: transparent; }
.cx-usage-model-row:hover { background: var(--cx-page-surface-hover); }
.cx-usage-model-dot { width: 7px; height: 7px; border-radius: 50%; }
.cx-usage-model-name { font-size: 10px; line-height: 1.4; overflow-wrap: anywhere; }
.cx-usage-model-amount { display: flex; flex-direction: column; gap: 2px; text-align: right; }
.cx-usage-model-amount > span { font-size: 11px; font-weight: 650; }
.cx-usage-model-amount > small { color: var(--cx-page-muted); font-size: 9px; font-variant-numeric: tabular-nums; }
.cx-usage-count { padding: 2px 6px; border-radius: 5px; background: var(--cx-page-status-neutral); color: var(--cx-page-muted); font-size: 10px; font-variant-numeric: tabular-nums; }
.cx-usage-sessions .cx-usage-card-heading { padding-bottom: 14px; }
.cx-usage-table-scroll { min-width: 0; overflow: auto; scrollbar-width: thin; border-radius: 0 0 11px 11px; }
.cx-usage-table { width: 100%; border-collapse: collapse; text-align: left; font-size: 10px; font-variant-numeric: tabular-nums; }
.cx-usage-table th { font-weight: 550; }
.cx-usage-table thead th { position: sticky; top: 0; z-index: 1; background: var(--cx-page-surface-muted); color: var(--cx-page-muted); border-top: 1px solid var(--cx-page-border-soft); border-bottom: 1px solid var(--cx-page-border-soft); font-size: 9px; }
.cx-usage-table td, .cx-usage-table th { padding: 11px 13px; line-height: 1.5; white-space: nowrap; }
.cx-usage-table td:first-child, .cx-usage-table th:first-child { padding-left: 18px; }
.cx-usage-table td:last-child, .cx-usage-table th:last-child { padding-right: 18px; }
.cx-usage-table td { color: var(--cx-page-muted); }
.cx-usage-table tbody tr + tr { border-top: 1px solid var(--cx-page-border-soft); }
.cx-usage-table tbody tr:hover { background: var(--cx-page-surface-hover); }
.cx-usage-table th:nth-child(n+3), .cx-usage-table td:nth-child(n+3) { text-align: right; }
.cx-usage-table .cx-usage-cell-total { color: var(--cx-page-text); font-weight: 650; }
.cx-usage-session-name { display: block; max-width: 190px; overflow: hidden; text-overflow: ellipsis; color: var(--cx-page-text); }
.cx-usage-session-model { display: block; max-width: 150px; overflow: hidden; text-overflow: ellipsis; font-size: 9px; }
.cx-usage-footer { color: var(--cx-page-subtle); font-size: 10px; line-height: 1.6; }
.cx-usage-footer > div { display: flex; align-items: flex-start; gap: 5px; }
.cx-usage-footer svg { flex-shrink: 0; margin-top: 2px; color: var(--cx-page-green); }
.cx-usage-footer p { margin: 5px 0 0; font-size: 9px; }
.cx-usage-notice { display: flex; align-items: flex-start; gap: 10px; padding: 12px 14px; border: 1px solid; border-radius: 8px; font-size: 11px; line-height: 1.6; }
.cx-usage-notice > svg { flex-shrink: 0; margin-top: 1px; }
.cx-usage-notice > div { flex: 1; min-width: 0; }
.cx-usage-notice strong { font-size: 11px; font-weight: 640; }
.cx-usage-notice p { margin: 3px 0 0; overflow-wrap: anywhere; font-size: 10px; }
.cx-usage-notice--warning { border-color: var(--cx-usage-warning-border); color: var(--cx-usage-warning); background: var(--cx-usage-warning-bg); }
.cx-usage-notice--error { border-color: var(--cx-usage-error-border); color: var(--cx-usage-error); background: var(--cx-usage-error-bg); }
.cx-usage-notice > button { flex-shrink: 0; margin-top: 1px; padding: 3px 7px; color: inherit; background: transparent; border: 1px solid currentColor; border-radius: 5px; font-size: 10px; }
.cx-usage-notice details { margin-top: 4px; font-size: 10px; }
.cx-usage-notice summary { width: fit-content; cursor: pointer; }
.cx-usage-notice ul { margin: 4px 0 0; padding-left: 17px; overflow-wrap: anywhere; }
.cx-usage-loading, .cx-usage-empty { display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 310px; padding: 35px; border: 1px dashed var(--cx-page-border); border-radius: 12px; background: var(--cx-page-surface); text-align: center; }
.cx-usage-loading > svg { color: var(--cx-page-blue); }
.cx-usage-loading > p { color: var(--cx-page-muted); font-size: 12px; margin: 14px 0 0; }
.cx-usage-loading-cards { display: flex; gap: 10px; margin-top: 25px; }
.cx-usage-loading-cards > span { width: 68px; height: 43px; background: var(--cx-page-status-neutral); border-radius: 7px; animation: cx-usage-pulse 1.5s ease-in-out infinite alternate; }
.cx-usage-loading-cards > span:nth-child(2) { animation-delay: .15s; }
.cx-usage-loading-cards > span:nth-child(3) { animation-delay: .3s; }
.cx-usage-empty-visual { position: relative; display: flex; align-items: flex-end; justify-content: center; gap: 7px; width: 110px; height: 90px; padding: 23px 17px 10px; margin-bottom: 15px; border-radius: 13px; background: var(--cx-page-blue-soft); }
.cx-usage-empty-visual > span { width: 12px; border-radius: 4px 4px 0 0; background: var(--cx-usage-cache); opacity: .7; }
.cx-usage-empty-visual > span:nth-child(1) { height: 22px; }
.cx-usage-empty-visual > span:nth-child(2) { height: 39px; }
.cx-usage-empty-visual > span:nth-child(3) { height: 30px; }
.cx-usage-empty-visual > span:nth-child(4) { height: 52px; background: var(--cx-usage-input); }
.cx-usage-empty-visual > svg { position: absolute; right: -9px; bottom: -8px; box-sizing: content-box; padding: 7px; border: 3px solid var(--cx-page-surface); border-radius: 11px; color: var(--cx-page-blue); background: var(--cx-page-blue-soft); }
.cx-usage-empty h3 { color: var(--cx-page-text); font-size: 15px; margin: 7px 0 0; }
.cx-usage-empty p { max-width: 360px; margin: 9px 0 17px; font-size: 12px; line-height: 1.8; color: var(--cx-page-muted); }
.cx-usage-sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
:root[data-theme="dark"] .cx-usage { --cx-usage-input: #76a8ff; --cx-usage-cache: #405e8f; --cx-usage-output: #60c7c8; --cx-usage-hero: #2d3d58; --cx-usage-hero-border: #415777; --cx-usage-hero-text: #d8e7ff; --cx-usage-warning: #e1bd76; --cx-usage-warning-bg: #3b3529; --cx-usage-warning-border: #5c4e34; --cx-usage-error: #f0a4ab; --cx-usage-error-bg: #453037; --cx-usage-error-border: #66404a; }
:root[data-theme="dark"] .cx-usage-model-color-0 { stroke: #76a8ff; background: #76a8ff; }
:root[data-theme="dark"] .cx-usage-model-color-1 { stroke: #60c7c8; background: #60c7c8; }
:root[data-theme="dark"] .cx-usage-model-color-2 { stroke: #526f9f; background: #526f9f; }
:root[data-theme="dark"] .cx-usage-model-color-3 { stroke: #b0a9e8; background: #b0a9e8; }
:root[data-theme="dark"] .cx-usage-model-color-4 { stroke: #d8b478; background: #d8b478; }
@keyframes cx-usage-pulse { from { opacity: .4; } to { opacity: 1; } }
@media (prefers-reduced-motion: reduce) { .cx-usage-loading-cards > span { animation: none; } }
@media (max-width: 1050px) {
.cx-usage-summary { grid-template-columns: minmax(210px, 1fr) minmax(0, 1.4fr); }
.cx-usage-total { padding: 18px 16px 15px; }
.cx-usage-metric { padding: 14px 13px 11px; }
.cx-usage-charts { grid-template-columns: minmax(0, 1.6fr) minmax(200px, 1fr); }
.cx-usage-local-badge { display: none; }
}
@media (max-width: 820px) {
.cx-usage-charts { grid-template-columns: minmax(0, 1fr); }
.cx-usage-models { display: grid; grid-template-columns: 160px minmax(0, 1fr); align-items: center; }
.cx-usage-models .cx-usage-card-heading { grid-column: 1 / -1; }
.cx-usage-model-list { padding-top: 12px; padding-right: 18px; max-height: 180px; }
.cx-usage-summary { grid-template-columns: minmax(0, 1fr); }
.cx-usage-total { padding: 18px 20px; }
.cx-usage-total-value { margin-top: 11px; }
.cx-usage-total-value > .cx-usage-number { font-size: 42px; }
.cx-usage-metrics { grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; }
.cx-usage-metric { padding: 12px 10px; }
.cx-usage-metric-value { font-size: 23px; }
.cx-usage-metric-label { gap: 5px; font-size: 10px; }
}
@media (max-width: 600px) {
.cx-settings-tabs { width: 100%; }
.cx-settings-tab { min-width: 0; flex: 1; }
.cx-usage-toolbar { align-items: stretch; }
.cx-usage-range { width: 100%; }
.cx-usage-range button { flex: 1; padding: 0 8px; }
.cx-usage-toolbar-actions { width: 100%; justify-content: space-between; }
.cx-usage-model-select { flex: 1; }
.cx-usage-model-select select { width: 100%; }
.cx-usage-metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.cx-usage-metric { padding: 14px; }
.cx-usage-day-summary { margin-left: 12px; margin-right: 12px; }
.cx-usage-card-heading { padding-left: 14px; padding-right: 14px; }
.cx-usage-models { grid-template-columns: 135px minmax(0, 1fr); }
.cx-usage-donut-wrap { width: 130px; }
.cx-usage-donut { width: 130px; height: 130px; }
.cx-usage-model-list { padding-right: 10px; }
.cx-usage-loading, .cx-usage-empty { padding: 28px 20px; }
}
+25
View File
@@ -33,6 +33,30 @@ export type SavedProvider = {
requiresOpenaiAuth: boolean;
};
export type OfficialProfileSummary = {
id: string;
providerName: string;
model: string | null;
hasAuth: boolean;
isDefault: boolean;
isCurrent: boolean;
};
export type OfficialProfileDetail = OfficialProfileSummary & {
authJson: string;
configText: string;
};
export type OfficialProfileActionResult = ActionResult & {
profile: OfficialProfileSummary;
};
export type DuplicateProviderResult = {
provider: SavedProvider;
providers: SavedProvider[];
activeProviderId: string | null;
};
export type SavedPrompt = {
id: string;
title: string;
@@ -90,6 +114,7 @@ export type CodexState = {
instructionTemplateKey?: string;
agentsPath: string;
activeSavedProviderId?: string;
activeOfficialProfileId?: string | null;
providers: ProviderSummary[];
configText: string;
authPreview?: unknown;
+41
View File
@@ -0,0 +1,41 @@
export type UsageRange = "today" | "7d" | "30d" | "all";
export type UsageTotals = {
inputTokens: number;
cachedInputTokens: number;
outputTokens: number;
reasoningTokens: number;
totalTokens: number;
sessionCount: number;
usageEventCount: number;
};
export type UsageDay = UsageTotals & { date: string };
export type UsageModel = UsageTotals & { model: string };
export type UsageSession = UsageTotals & {
id: string;
title: string;
model: string;
startedAt: string;
lastActiveAt: string;
};
export type UsageStatistics = {
totals: UsageTotals;
days: UsageDay[];
models: UsageModel[];
sessions: UsageSession[];
availableModels: string[];
coverage: {
scannedFiles: number;
matchedSessions: number;
skippedFiles: number;
warnings: string[];
truncated: boolean;
};
rangeStart: string | null;
rangeEnd: string;
refreshedAt: string;
timezone: string;
sourceDirectories: string[];
};
+183
View File
@@ -0,0 +1,183 @@
# Renderer UI fixture
From the repository root:
```sh
node apps/desktop/tests/serve-ui-fixture.mjs
```
Open `http://127.0.0.1:1421/`. An optional positional port overrides `1421`.
The server listens only on `127.0.0.1` and fails if that port is occupied.
Stop with Ctrl+C.
This serves the real React renderer through Vite with a test-only script injected
before the renderer loads. All Tauri IPC is intercepted. Commands use in-memory
data, `.example.test` addresses and fake credentials. No native process, real
Codex configuration, app database, or remote API is used. Unknown IPC commands
fail explicitly. The fixture does not alter production entry points or Vite
configuration.
## Delayed template detail and cross-page controls
1. Open **指令提示词**. Its automatic template sync remains pending.
2. Click the edit button for **Fixture 内置模板**. The detail read also remains
pending independently of the sync.
3. Open **供应商** while both requests are pending. **新增供应商**, editing a
supplier, and enabling **Fixture Saved Provider** should remain usable when
the template-detail loading state is correctly scoped to its page.
4. Use **Fixture:完成模板详情** after leaving the prompt page. Returning to
**指令提示词** should not unexpectedly open an editor from that stale request.
5. **Fixture:完成模板同步** resolves the pending catalog sync separately.
Before the UI fix, step 2 uses the shared `loading` flag and step 3 shows disabled
supplier actions. The delayed detail is intentional even after backend reads are
made fast, so this fixture can test the UI against a slow IPC response.
The panel sits in the lower-left corner. Click **Fixture:所有命令均为内存模拟**
to collapse it when testing the sidebar. The appearance switch can also be
focused and toggled with the Space key.
The fixture controls are:
- **Fixture:完成模板同步**
- **Fixture:使模板同步失败**
- **Fixture:完成模板详情**
- **Fixture:使模板详情失败**
Each template control settles all currently pending requests of its kind.
Clicking it with no pending request has no effect. Reloading resets pending
requests and command counters, while provider and official-profile data survive
in this fixture origin's `sessionStorage` (`codexx.fixture.backend.v2`). Use
**Fixture:重置测试数据** for a clean starting model. The fixture also resets the
renderer's language, startup-wizard marker, remembered provider and prompt
categories in this fixture origin's localStorage.
## Multiple official logins
1. Reset the fixture. The default **OpenAI Official** profile has ID
`openai-official` and fake OAuth identity `fixture-account-one`.
2. In **供应商**, select **新增供应商**, change **供应商类型** to
**官方 Codex 登录**, name it **第二账号**, and leave authentication empty.
Save it. The current supplier must stay unchanged; the new profile has
`hasAuth: false` in the fixture diagnostics.
3. Enable **第二账号**. Diagnostics must show its new `activeOfficialProfileId`,
with `currentOfficialAccount: null`. This models waiting for a Codex login.
4. Click **Fixture:登录第二个官方账号**. This changes only the live in-memory
official authentication to `fixture-account-two`, modeling an external Codex
sign-in. It does not immediately modify the saved profile snapshot.
5. Switch to **OpenAI Official**, then switch back to **第二账号**. The fake
backend captures the previous live login before switching, so the diagnostics
should alternate between `fixture-account-one` and `fixture-account-two`.
Reload the browser and repeat to verify that the fixture model survives reload.
6. To test explicit capture, activate an official profile, use the fixture login
button, open another official profile's editor, click **读取当前官方登录**, and
save. Authentication is copied into that chosen profile without switching the
current supplier.
7. Copy **OpenAI Official**. A named copy appears immediately in the list, with
the same fake authentication and a distinct ID. No editor or confirmation
dialog opens. Copy it again to check that names gain a numeric suffix. Open
the copy's editor separately to rename it. Clearing its authentication and
saving must leave the default profile unchanged.
8. Delete a named profile. The fixture rejects deletion of the default or the
currently active profile, so the frontend must switch to the default first
when deleting an active named profile.
The official-login fixture implements `list_official_profiles`,
`get_official_profile`, `save_official_profile`, `duplicate_official_profile`,
`switch_official_profile`, and `delete_official_profile`. Saving a new/inactive
profile does not switch; saving the active profile updates its live in-memory
configuration. `authJson: null` preserves a saved profile's authentication; for
the current official profile it captures the latest simulated live login.
`authJson: ""` explicitly clears authentication. Both default and named profiles
can be renamed. The additional
controls are:
- **Fixture:登录第二个官方账号** — enabled only while an official profile is active.
- **Fixture:重置测试数据** — removes the fixture session data and reloads.
For browser assertions, these actions are also exposed as
`window.__CODEX_X_FIXTURE__.loginSecondOfficialAccount()` and `.reset()`.
After editing `ui-runtime.js`, restart the fixture server: it reads the injected
script once at startup.
## Immediate copies and 1M context
1. Copy **Fixture CC Switch** before switching providers. The detected original
is preserved and a separate copy appears. The original stays current. Repeat
with **Fixture Saved Provider** and an official profile: every click creates
a unique name and ID, without opening an editor or confirmation dialog.
2. Open either provider type's editor. Next to **config.toml**, enable
**开启 1M 上下文窗口**. The draft gains top-level `model_context_window = 1000000`
and, if absent, `model_auto_compact_token_limit = 900000`. Nothing is saved
until the form's save button is clicked.
3. Edit the context value manually to `1_000_000` and then `256000`; the checkbox
should follow the draft. An existing compaction value such as `850000` must
survive enabling and disabling. Turning on and off within the same edit
restores the previous custom context value.
4. Add an MCP table and test the toggle again. Those lines remain present. A
`model_context_window` inside an MCP/profile table or a multiline string
must not make the top-level checkbox checked. Invalid context-field types
or an unfinished table header disable the checkbox and show an inline hint.
5. Save, reopen the editor, and check that the 1M settings persist in the fake
profile. Resetting the whole fixture intentionally removes them.
`update_codex_context_window` is a **limited mock**, supporting the simple
line-based TOML used in these scenarios. It recognizes quoted context keys,
integer separators, comments, tables and basic multiline strings. It does not
validate arbitrary TOML and is not a substitute for the production `toml_edit`
parser. The Rust `context_config` tests establish parser and mutation behavior.
The same limitation applies to the fixture's provider form-to-TOML updates.
## Usage statistics
Open **设置 → 用量统计**. The fixture generates synthetic records relative to
today across 40 days and three models. Input includes cached input; output
includes reasoning; total is input plus output. The 7-day trend includes a day
with no usage. **今天**, **近 7 天**, **近 30 天**, **全部** and the model filter
actually aggregate different subsets. The daily and model sums must agree with
the total cards. The recent-session list is capped at 10 while totals include
all matching records. Rows show sample chat titles, not shortened session IDs.
These sample rows represent main conversations with their subagent usage already
included. Thread classification, recursive ownership, and replay deduplication
are covered by the Rust usage/SQLite tests, not simulated by this UI fixture.
Switch between **通用设置** and **用量统计** to check the shared fade-out/fade-in
transition. Returning to usage keeps the selected date range and model.
Use the following panel controls, then click **刷新用量** (or **重试**):
- **Fixture:用量示例数据** restores the normal sample.
- **Fixture:用量空数据** returns zero totals and no sessions/models.
- **Fixture:用量读取失败** rejects the read. A first read shows the error view;
after a successful read, a failed refresh should keep the last result with a
failure notice.
- **Fixture:用量部分数据** returns the sample with two synthetic skipped files,
so the coverage notice is visible.
The selected mode appears in diagnostics as `usageMode`; it resets to `sample`
on reload. Tests may call `window.__CODEX_X_FIXTURE__.setUsageMode(mode)`.
`get_usage_statistics` accepts `configDir`, `range`, `model` and `forceRefresh`
with the production response shape from `src/usageTypes.ts`. Both refresh
paths return newly aggregated sample data; there is no filesystem scan or
real usage cache in this fixture.
## Diagnostics and scope
The accessible **Fixture 命令记录** output (`#fixture-command-log`) displays JSON
with pending counts, invocation counts, provider switches (including official
profile IDs), saved provider IDs, official-profile summaries, fake account IDs,
and the ordered command names. Authentication tokens are omitted from this
diagnostic output. The same snapshot is available to browser assertions:
```js
window.__CODEX_X_FIXTURE__.snapshot()
```
Initially **Fixture CC Switch** is a detected current supplier, while
**Fixture Saved Provider** is the only saved entry. The fake backend preserves
the detected entry when switching away, allowing the renderer to show both
entries and switch back. This models the desired backend response; it does **not**
validate Rust persistence, credential resolution or database behavior. The same
limitation applies to official-profile capture, independence, and storage: these
responses are models for frontend verification. Use the Rust regression tests
for backend guarantees. All persisted fixture credentials are synthetic and
scoped to the local fixture origin and browser session.
+812
View File
@@ -0,0 +1,812 @@
(() => {
"use strict";
// Browser-only fixture. Every command below changes this in-memory model only.
const clone = (value) => structuredClone(value);
const codexDir = "/fixture/codex";
const defaultOfficialId = "openai-official";
const storageKey = "codexx.fixture.backend.v2";
const counts = {};
const switches = [];
const commands = [];
const pending = { sync: [], detail: [] };
const callbacks = new Map();
let nextCallback = 1;
let output;
let loginButton;
let nextOfficialId = 1;
let externalOfficialLogins = 0;
let savedPrompts = [];
let usageMode = "sample";
function officialToml(model) {
return `model_provider = "openai"\nmodel = ${JSON.stringify(model || "fixture-official-model")}\n`;
}
function officialAuth(account) {
return JSON.stringify({
auth_mode: "chatgpt",
OPENAI_API_KEY: null,
tokens: {
id_token: `fixture-only-id-token-${account}`,
access_token: `fixture-only-access-token-${account}`,
refresh_token: `fixture-only-refresh-token-${account}`,
account_id: `fixture-account-${account}`,
},
last_refresh: "2026-09-08T00:00:00Z",
}, null, 2);
}
const officialProfiles = new Map([[defaultOfficialId, {
id: defaultOfficialId,
providerName: "OpenAI Official",
model: "fixture-official-model",
authJson: officialAuth("one"),
configText: officialToml("fixture-official-model"),
isDefault: true,
}]]);
function toml(provider) {
return [
`model = ${JSON.stringify(provider.model)}`,
`model_provider = ${JSON.stringify(provider.id)}`,
"",
`[model_providers.${provider.id}]`,
`name = ${JSON.stringify(provider.providerName)}`,
`base_url = ${JSON.stringify(provider.baseUrl)}`,
`wire_api = ${JSON.stringify(provider.wireApi)}`,
`experimental_bearer_token = ${JSON.stringify(provider.apiKey || "")}`,
"requires_openai_auth = false",
"",
].join("\n");
}
function providerTomlDraft(provider) {
const original = provider.tomlConfig?.trim();
if (!original) return toml(provider);
// Preserve the complete simple fixture draft, including 1M and MCP settings,
// while reflecting form fields in its active provider section.
const originalId = original.match(/^model_provider\s*=\s*"([^"]+)"/m)?.[1];
let section = "";
let foundSection = false;
const values = {
name: provider.providerName, base_url: provider.baseUrl,
wire_api: provider.wireApi, experimental_bearer_token: provider.apiKey || "",
requires_openai_auth: provider.requiresOpenaiAuth,
};
const lines = original.split("\n").map((line) => {
const header = line.match(/^\s*\[([^\]]+)\]\s*$/);
if (header) {
section = header[1];
if (section === `model_providers.${originalId}`) {
foundSection = true;
return `[model_providers.${provider.id}]`;
}
}
if (!section && /^model\s*=/.test(line)) return `model = ${JSON.stringify(provider.model)}`;
if (!section && /^model_provider\s*=/.test(line)) return `model_provider = ${JSON.stringify(provider.id)}`;
if (section === `model_providers.${originalId}`) {
const key = line.match(/^([a-z_]+)\s*=/)?.[1];
if (key && Object.hasOwn(values, key)) return `${key} = ${JSON.stringify(values[key])}`;
}
return line;
});
if (!foundSection) lines.push("", ...toml(provider).split("\n").slice(3));
return `${lines.join("\n")}\n`;
}
const detectedProvider = {
id: "fixture-ccswitch",
providerName: "Fixture CC Switch",
baseUrl: "https://ccswitch.example.test/v1",
model: "fixture-model-a",
apiKey: "sk-fixture-only-a",
wireApi: "responses",
requiresOpenaiAuth: false,
};
detectedProvider.tomlConfig = toml(detectedProvider);
let savedProviders = [{
id: "fixture-saved",
providerName: "Fixture Saved Provider",
baseUrl: "https://saved.example.test/v1",
model: "fixture-model-b",
apiKey: "sk-fixture-only-b",
wireApi: "responses",
requiresOpenaiAuth: false,
tomlConfig: "",
}];
const statuses = ["fixture-template", "fixture-template-other"].map((id, index) => ({
id,
filename: `${id}.md`,
title: index === 0 ? "Fixture 内置模板" : "Fixture 第二模板",
subtitle: "用于延迟请求与切页验证的本地假模板",
badge: "Fixture",
sourceUrl: `https://templates.example.test/${id}.md`,
cached: true,
updated: false,
contentSource: "cache",
syncIssue: null,
checkedAt: null,
message: "Fixture cached template",
customized: false,
}));
const details = new Map(statuses.map((item) => [item.id, {
id: item.id,
filename: item.filename,
title: item.title,
content: `# ${item.title}\n\nThis is a local UI fixture.\n`,
customized: false,
}]));
let state = {
codexDir,
configPath: `${codexDir}/config.toml`,
authPath: `${codexDir}/auth.json`,
agentsPath: `${codexDir}/AGENTS.md`,
configExists: true,
authExists: true,
officialAuthAvailable: true,
model: detectedProvider.model,
modelProvider: detectedProvider.id,
isOfficialProvider: false,
instructionEnabled: false,
instructionInjectionMode: "append",
instructionTemplateKey: undefined,
activeSavedProviderId: undefined,
activeOfficialProfileId: null,
providers: [{
id: detectedProvider.id,
name: detectedProvider.providerName,
baseUrl: detectedProvider.baseUrl,
wireApi: "responses",
requiresOpenaiAuth: false,
isCurrent: true,
}],
configText: detectedProvider.tomlConfig,
authText: JSON.stringify({ OPENAI_API_KEY: "sk-fixture-only-a" }),
authPreview: { OPENAI_API_KEY: "sk-fixture-only-a" },
};
try {
const saved = JSON.parse(sessionStorage.getItem(storageKey) || "null");
if (saved?.version === 2 && saved.state && Array.isArray(saved.savedProviders)
&& Array.isArray(saved.savedPrompts) && Number.isSafeInteger(saved.nextOfficialId)
&& Array.isArray(saved.officialProfiles)
&& saved.officialProfiles.some((profile) => profile.id === defaultOfficialId)) {
state = saved.state;
savedProviders = saved.savedProviders;
savedPrompts = saved.savedPrompts;
nextOfficialId = saved.nextOfficialId;
officialProfiles.clear();
for (const profile of saved.officialProfiles) officialProfiles.set(profile.id, profile);
}
} catch {
// Corrupt or unavailable fixture storage leaves the fresh in-memory model intact.
}
function persist() {
try {
sessionStorage.setItem(storageKey, JSON.stringify({
version: 2,
state,
savedProviders,
savedPrompts,
nextOfficialId,
officialProfiles: Array.from(officialProfiles.values()),
}));
} catch {
// Tests still work in memory if sessionStorage is unavailable.
}
}
localStorage.setItem("codexx.lang", "zh");
localStorage.setItem("codexx.startupWizardSeen", "1");
localStorage.removeItem("codexx.activeProviderId");
localStorage.removeItem("codexx.promptCategories.v1");
function snapshot() {
return {
pendingSync: pending.sync.length,
pendingDetail: pending.detail.length,
commandCounts: clone(counts),
providerSwitches: clone(switches),
currentProvider: state.modelProvider,
activeOfficialProfileId: state.activeOfficialProfileId,
currentOfficialAccount: state.isOfficialProvider ? accountId(state.authText) : null,
officialProfiles: Array.from(officialProfiles.values(), (profile) => ({
...officialSummary(profile),
accountId: accountId(profile.authJson),
})),
externalOfficialLogins,
usageMode,
savedProviderIds: savedProviders.map((provider) => provider.id),
commands: clone(commands),
};
}
function render() {
if (output) output.textContent = JSON.stringify(snapshot(), null, 2);
if (loginButton) loginButton.disabled = !state.isOfficialProvider;
}
function accountId(authJson) {
try { return JSON.parse(authJson || "null")?.tokens?.account_id || null; }
catch { return null; }
}
function officialSummary(profile) {
return {
id: profile.id,
providerName: profile.providerName,
model: profile.model || null,
hasAuth: Boolean(profile.authJson.trim()),
isDefault: profile.id === defaultOfficialId,
isCurrent: state.isOfficialProvider && state.activeOfficialProfileId === profile.id,
};
}
function officialProfile(profileId) {
const profile = officialProfiles.get(profileId);
if (!profile) throw new Error(`Unknown fixture official profile: ${profileId}`);
return profile;
}
function officialDetail(profile) {
return clone({ ...officialSummary(profile), authJson: profile.authJson, configText: profile.configText });
}
function captureCurrentOfficial() {
if (!state.isOfficialProvider || !state.activeOfficialProfileId) return;
const profile = officialProfile(state.activeOfficialProfileId);
profile.authJson = state.authText || "";
profile.configText = state.configText;
profile.model = state.model || null;
}
function loginSecondOfficialAccount() {
if (!state.isOfficialProvider) return false;
// Simulates Codex changing auth.json externally; the profile snapshot is saved later.
state.authText = officialAuth("two");
state.authPreview = JSON.parse(state.authText);
state.authExists = true;
externalOfficialLogins += 1;
persist();
render();
return true;
}
function defer(kind, result) {
return new Promise((resolve, reject) => {
pending[kind].push({ resolve, reject, result });
render();
});
}
function settle(kind, fail) {
for (const request of pending[kind].splice(0)) {
if (fail) request.reject(new Error(`Fixture ${kind} failure`));
else request.resolve(clone(request.result()));
}
render();
}
function saveProvider(provider) {
const next = clone(provider);
const existingIndex = savedProviders.findIndex((item) => item.id === next.id);
if (existingIndex >= 0) savedProviders[existingIndex] = next;
else savedProviders.push(next);
return next;
}
function uniqueCopyName(requested, names) {
const base = requested?.trim() || "Fixture 副本";
const used = new Set(names);
let name = base;
for (let suffix = 2; used.has(name); suffix += 1) name = `${base} ${suffix}`;
return name;
}
function duplicateProvider(providerId, providerName) {
if (providerId == null) preserveDetectedProvider();
const sourceId = providerId || state.activeSavedProviderId || state.modelProvider;
const source = savedProviders.find((provider) => provider.id === sourceId);
if (!source || state.isOfficialProvider && providerId == null) throw new Error("Unknown fixture provider to duplicate");
let suffix = 1;
let id = `fixture-copy-${suffix}`;
while (savedProviders.some((provider) => provider.id === id)) id = `fixture-copy-${++suffix}`;
const provider = saveProvider({
...clone(source),
id,
providerName: uniqueCopyName(providerName || `${source.providerName} 副本`, savedProviders.map((item) => item.providerName)),
});
// Capturing a detected row makes its existing identity explicit; copying never switches it.
if (!state.isOfficialProvider && !state.activeSavedProviderId && sourceId === state.modelProvider) {
state.activeSavedProviderId = sourceId;
}
return clone({ provider, providers: savedProviders, activeProviderId: state.activeSavedProviderId || null });
}
function updateContextWindow({ configText, enabled, previousValues }) {
// This is a deliberately limited model for the fixture's simple TOML drafts,
// not a production TOML parser. Rust tests cover the real toml_edit behavior.
const keys = ["model_context_window", "model_auto_compact_token_limit"];
function scan(text) {
const lines = text.split("\n");
const fields = {};
let firstTable = lines.length;
let multiline = null;
for (let index = 0; index < lines.length; index += 1) {
const line = lines[index];
const trimmed = line.trim();
if (multiline) {
if (line.includes(multiline)) multiline = null;
continue;
}
if (!trimmed || trimmed.startsWith("#")) continue;
if (trimmed.startsWith("[")) {
if (!/^\[.+\]\s*(?:#.*)?$/.test(trimmed)) throw new Error("Fixture TOML table syntax error");
firstTable = Math.min(firstTable, index);
continue;
}
for (const quote of ['"""', "'''"]) {
if (line.split(quote).length % 2 === 0) multiline = quote;
}
if (index >= firstTable) continue;
for (const key of keys) {
const start = new RegExp(`^\\s*(?:${key}|"${key}"|'${key}')\\s*=`);
if (!start.test(line)) continue;
const match = line.match(new RegExp(`^(\\s*(?:${key}|"${key}"|'${key}')\\s*=\\s*)([+-]?[0-9][0-9_]*)(\\s*(?:#.*)?)$`));
if (!match || fields[key]) throw new Error(`Fixture invalid integer setting: ${key}`);
const value = Number(match[2].replaceAll("_", ""));
if (!Number.isSafeInteger(value)) throw new Error(`Fixture unsupported integer: ${key}`);
fields[key] = { index, value, prefix: match[1], suffix: match[3] };
}
}
if (multiline) throw new Error("Fixture TOML multiline string syntax error");
return { lines, fields, firstTable };
}
function set(text, key, value) {
const { lines, fields, firstTable } = scan(text);
const field = fields[key];
if (field) {
if (value == null) lines.splice(field.index, 1);
else lines[field.index] = `${field.prefix}${value}${field.suffix}`;
} else if (value != null) {
lines.splice(Math.min(firstTable, lines.length - (lines.at(-1) === "" ? 1 : 0)), 0, `${key} = ${value}`);
}
return lines.join("\n");
}
let next = configText;
const original = scan(next).fields;
const context = original[keys[0]]?.value ?? null;
const compact = original[keys[1]]?.value ?? null;
if (enabled === true) {
next = set(next, keys[0], 1000000);
if (compact == null) next = set(next, keys[1], 900000);
} else if (enabled === false) {
if (context === 1000000) next = set(next, keys[0], previousValues?.contextWindow ?? null);
if (compact === (previousValues?.compactTokenLimit ?? 900000)) {
next = set(next, keys[1], previousValues?.compactTokenLimit ?? null);
}
}
const fields = scan(next).fields;
return {
configText: next,
enabled: fields[keys[0]]?.value === 1000000,
contextWindow: fields[keys[0]]?.value ?? null,
compactTokenLimit: fields[keys[1]]?.value ?? null,
};
}
function preserveDetectedProvider() {
// This stub models the expected Rust persistence behavior. It does not test Rust.
if (state.modelProvider === detectedProvider.id
&& !savedProviders.some((provider) => provider.id === detectedProvider.id)) {
saveProvider(detectedProvider);
}
}
function action(message) {
return clone({ ok: true, message, state });
}
function usageStatistics({ range = "7d", model = null } = {}) {
if (usageMode === "error") throw new Error("Fixture usage read failed; no real files were accessed");
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12);
const dateKey = (value) => `${value.getFullYear()}-${String(value.getMonth() + 1).padStart(2, "0")}-${String(value.getDate()).padStart(2, "0")}`;
const dayAt = (daysAgo) => { const day = new Date(today); day.setDate(day.getDate() - daysAgo); return day; };
const daysBack = ({ today: 0, "7d": 6, "30d": 29, all: 39 })[range];
if (daysBack === undefined) throw new Error(`Unknown fixture usage range: ${range}`);
const modelNames = ["gpt-5.5", "gpt-5.4-mini", "gpt-5.3-codex"];
const titles = ["优化供应商切换", "设计用量统计", "完善本地回归验证"];
const emptyTotals = () => ({ inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, reasoningTokens: 0, totalTokens: 0, sessionCount: 0, usageEventCount: 0 });
const sum = (rows) => rows.reduce((totals, row) => {
for (const key of Object.keys(totals)) totals[key] += row[key];
return totals;
}, emptyTotals());
const records = [];
if (usageMode !== "empty") {
for (let daysAgo = daysBack; daysAgo >= 0; daysAgo -= 1) {
if (daysAgo === 3 || daysAgo === 12 || daysAgo === 25) continue;
for (let modelIndex = 0; modelIndex < modelNames.length; modelIndex += 1) {
if ((daysAgo + modelIndex) % 5 === 4) continue;
const volume = [2.4, 1.1, 0.7][modelIndex] * (1 + ((daysAgo * 7 + modelIndex * 3) % 13) / 5);
const inputTokens = Math.round(134500 * volume);
const cachedInputTokens = Math.round(inputTokens * (0.42 + (daysAgo % 4) / 10));
const outputTokens = Math.round(18400 * volume);
const reasoningTokens = Math.round(outputTokens * 0.36);
const date = dateKey(dayAt(daysAgo));
const requestedEnd = new Date(`${date}T${15 + modelIndex}:32:00`);
const lastActive = requestedEnd > now ? now : requestedEnd;
const midnight = new Date(lastActive.getFullYear(), lastActive.getMonth(), lastActive.getDate());
const startedAt = new Date(Math.max(midnight.getTime(), lastActive.getTime() - 80 * 60 * 1000));
records.push({
id: `fixture-usage-${date}-${modelIndex}`,
title: `${titles[modelIndex]} · ${date.slice(5)}`,
model: modelNames[modelIndex], date,
startedAt: startedAt.toISOString(), lastActiveAt: lastActive.toISOString(),
inputTokens, cachedInputTokens, outputTokens, reasoningTokens,
totalTokens: inputTokens + outputTokens, sessionCount: 1, usageEventCount: 8 + daysAgo % 19,
});
}
}
}
const availableModels = Array.from(new Set(records.map((record) => record.model))).sort();
const selected = records.filter((record) => !model || record.model === model);
const days = [];
for (let daysAgo = daysBack; daysAgo >= 0; daysAgo -= 1) {
const date = dateKey(dayAt(daysAgo));
days.push({ date, ...sum(selected.filter((record) => record.date === date)) });
}
return {
totals: sum(selected), days,
models: availableModels.map((name) => ({ model: name, ...sum(selected.filter((record) => record.model === name)) }))
.filter((item) => item.totalTokens > 0).sort((left, right) => right.totalTokens - left.totalTokens),
sessions: selected.slice().sort((left, right) => right.lastActiveAt.localeCompare(left.lastActiveAt)).slice(0, 10)
.map(({ date: _date, ...session }) => session),
availableModels,
coverage: {
scannedFiles: usageMode === "empty" ? 0 : 103,
matchedSessions: selected.length,
skippedFiles: usageMode === "partial" ? 2 : 0,
warnings: usageMode === "partial" ? ["Fixture: two synthetic files could not be parsed"] : [],
truncated: false,
},
rangeStart: range === "all" ? null : new Date(today.getFullYear(), today.getMonth(), today.getDate() - daysBack).toISOString(),
rangeEnd: now.toISOString(), refreshedAt: now.toISOString(),
timezone: `UTC${now.getTimezoneOffset() > 0 ? "-" : "+"}${String(Math.floor(Math.abs(now.getTimezoneOffset()) / 60)).padStart(2, "0")}:${String(Math.abs(now.getTimezoneOffset()) % 60).padStart(2, "0")}`,
sourceDirectories: [`${codexDir}/sessions`, `${codexDir}/archived_sessions`],
};
}
function setUsageMode(mode) {
if (!["sample", "empty", "error", "partial"].includes(mode)) throw new Error(`Unknown fixture usage mode: ${mode}`);
usageMode = mode;
render();
}
function switchProvider(provider) {
preserveDetectedProvider();
captureCurrentOfficial();
const from = state.modelProvider;
const fromProfile = state.activeOfficialProfileId;
state = {
...state,
model: provider.model,
modelProvider: provider.id,
isOfficialProvider: false,
activeOfficialProfileId: null,
activeSavedProviderId: provider.id,
authExists: Boolean(provider.apiKey),
configText: provider.tomlConfig || toml(provider),
authText: JSON.stringify({ OPENAI_API_KEY: provider.apiKey }),
providers: [{
id: provider.id,
name: provider.providerName,
baseUrl: provider.baseUrl,
wireApi: provider.wireApi,
requiresOpenaiAuth: provider.requiresOpenaiAuth,
isCurrent: true,
}],
};
switches.push({ from, fromProfile, to: provider.id, toProfile: null });
render();
return action(`Fixture switched to ${provider.providerName}`);
}
function switchOfficial(profileId = defaultOfficialId) {
officialProfile(profileId);
preserveDetectedProvider();
captureCurrentOfficial();
const profile = officialProfile(profileId);
const from = state.modelProvider;
const fromProfile = state.activeOfficialProfileId;
state = {
...state,
modelProvider: "openai",
model: profile.model || "fixture-official-model",
isOfficialProvider: true,
activeOfficialProfileId: profile.id,
activeSavedProviderId: undefined,
authExists: Boolean(profile.authJson),
providers: [],
configText: profile.configText,
authText: profile.authJson,
authPreview: profile.authJson ? JSON.parse(profile.authJson) : null,
};
switches.push({ from, fromProfile, to: "openai", toProfile: profile.id });
render();
return action(`Fixture switched to ${profile.providerName}`);
}
function saveOfficial(input) {
const providerName = input.providerName.trim();
if (!providerName) throw new Error("Fixture official provider name is required");
if (input.authJson?.trim()) JSON.parse(input.authJson);
if (input.id) officialProfile(input.id);
if (input.id && input.authJson == null) captureCurrentOfficial();
const authJson = input.authJson == null
? (input.id ? officialProfile(input.id).authJson : "")
: input.authJson.trim();
const id = input.id || `fixture-official-${nextOfficialId++}`;
const profile = {
id,
providerName,
model: input.model?.trim() || null,
configText: input.configText?.trim() || officialToml(input.model),
authJson,
isDefault: id === defaultOfficialId,
};
officialProfiles.set(id, profile);
if (state.isOfficialProvider && state.activeOfficialProfileId === id) {
state.model = profile.model || "fixture-official-model";
state.configText = profile.configText;
state.authText = profile.authJson;
state.authExists = Boolean(profile.authJson);
state.authPreview = profile.authJson ? JSON.parse(profile.authJson) : null;
}
return clone({ ...action("Fixture official profile saved"), profile: officialSummary(profile) });
}
function duplicateOfficial(profileId, providerName) {
captureCurrentOfficial();
const original = officialProfile(profileId);
return saveOfficial({
...clone(original), id: null,
providerName: uniqueCopyName(providerName || `${original.providerName} 副本`, Array.from(officialProfiles.values(), (profile) => profile.providerName)),
});
}
async function invoke(command, args = {}) {
counts[command] = (counts[command] || 0) + 1;
commands.push(command);
render();
try {
return await dispatch(command, args);
} finally {
persist();
render();
}
}
async function dispatch(command, args) {
switch (command) {
case "get_codex_state": return clone(state);
case "list_saved_providers": return clone(savedProviders);
case "list_saved_prompts": return clone(savedPrompts);
case "get_builtin_prompt_status": return clone(statuses);
case "list_official_profiles":
captureCurrentOfficial();
return Array.from(officialProfiles.values(), (profile) => clone(officialSummary(profile)));
case "get_official_profile":
captureCurrentOfficial();
return officialDetail(officialProfile(args.profileId));
case "save_official_profile": return saveOfficial(args.input);
case "duplicate_official_profile": return duplicateOfficial(args.profileId, args.providerName);
case "switch_official_profile": return switchOfficial(args.profileId);
case "delete_official_profile":
officialProfile(args.profileId);
if (args.profileId === defaultOfficialId) throw new Error("Cannot delete the fixture default official profile");
if (state.isOfficialProvider && state.activeOfficialProfileId === args.profileId) {
throw new Error("Switch away before deleting the current fixture official profile");
}
officialProfiles.delete(args.profileId);
return undefined;
case "get_about_info": return {
appVersion: "0.3.15", codexVersion: "fixture-cli", codexDir,
projectUrl: "https://project.example.test/", githubRepo: "fixture/example",
nativeUpdaterSupported: false,
};
case "get_startup_diagnostics": return {
codexDir, needsManualSelect: false, summary: "Fixture ready", items: [],
};
case "check_app_update": return {
latestVersion: "0.3.15", htmlUrl: "https://releases.example.test/", hasUpdate: false,
};
case "plugin:updater|check": return null;
case "refresh_builtin_prompts": return defer("sync", () => statuses);
case "get_builtin_prompt_detail": {
if (!details.has(args.templateId)) throw new Error("Unknown fixture template");
return defer("detail", () => details.get(args.templateId));
}
case "save_builtin_prompt_override": {
const detail = details.get(args.templateId);
if (!detail) throw new Error("Unknown fixture template");
detail.content = args.content;
detail.customized = true;
statuses.find((item) => item.id === args.templateId).customized = true;
return clone(detail);
}
case "enable_instruction_template":
state.instructionEnabled = true;
state.instructionTemplateKey = `builtin:${args.templateId}`;
state.instructionInjectionMode = args.injectionMode;
return action("Fixture prompt enabled");
case "disable_instruction":
case "disable_external_instruction":
state.instructionEnabled = false;
state.instructionTemplateKey = undefined;
return action("Fixture prompt disabled");
case "save_prompt":
savedPrompts = [...savedPrompts.filter((prompt) => prompt.id !== args.prompt.id), clone(args.prompt)];
return clone(args.prompt);
case "delete_saved_prompt":
savedPrompts = savedPrompts.filter((prompt) => prompt.id !== args.id);
return undefined;
case "enable_saved_prompt":
state.instructionEnabled = true;
state.instructionTemplateKey = `saved:${args.id}`;
return action("Fixture saved prompt enabled");
case "build_provider_toml_draft": return providerTomlDraft(args.provider);
case "update_codex_context_window": return updateContextWindow(args);
case "get_usage_statistics": return usageStatistics(args);
case "duplicate_provider": return duplicateProvider(args.providerId, args.providerName);
case "save_provider": return saveProvider(args.provider);
case "save_active_provider": return switchProvider(saveProvider(args.provider));
case "switch_provider": {
const input = args.input;
return switchProvider(savedProviders.find((provider) => provider.id === input.providerId) || {
id: input.providerId, providerName: input.providerName,
baseUrl: input.baseUrl, model: input.model, apiKey: input.apiKey,
wireApi: input.wireApi, requiresOpenaiAuth: input.requiresOpenaiAuth,
});
}
case "save_provider_toml_config": {
const provider = savedProviders.find((item) => item.id === args.providerId);
if (!provider) throw new Error("Unknown fixture provider");
return switchProvider({ ...provider, tomlConfig: args.input.configText, apiKey: args.input.apiKey });
}
case "switch_official_provider":
case "restore_official_provider": return switchOfficial();
case "reset_official_provider":
saveOfficial({ id: defaultOfficialId, providerName: officialProfile(defaultOfficialId).providerName, model: "fixture-official-model", authJson: "", configText: "" });
return switchOfficial();
case "save_official_config": {
const input = args.input || args;
return saveOfficial({ ...input, id: defaultOfficialId, providerName: officialProfile(defaultOfficialId).providerName });
}
case "get_official_config_draft": {
captureCurrentOfficial();
const profile = officialProfile(defaultOfficialId);
return { authJson: profile.authJson, configText: profile.configText, model: profile.model, source: "fixture" };
}
case "read_ccswitch_official_auth": return {
authJson: officialAuth("one"), configText: officialToml("fixture-official-model"),
model: "fixture-official-model", source: "fixture",
};
case "delete_saved_provider":
savedProviders = savedProviders.filter((provider) => provider.id !== args.id);
render();
return undefined;
case "import_ccswitch_codex_providers":
preserveDetectedProvider();
return { imported: 1, added: 1, updated: 0, merged: 0, skipped: 0, warnings: [], providers: clone(savedProviders) };
case "test_provider_connection": return { ok: true, status: 200, message: "Fixture connection OK", durationMs: 1 };
case "fetch_provider_models": return { models: [{ id: "fixture-model-a" }, { id: "fixture-model-b" }], status: 200, durationMs: 1 };
case "get_session_sync_status": return {
codexDir, targetProvider: state.modelProvider, rolloutFiles: 0, sessionMetaCount: 0,
mismatchedRollouts: 0, mismatchedSessionMeta: 0, sqliteDbs: 1, sqliteThreads: 0,
topLevelThreads: 0, subagentThreads: 0, mismatchedThreads: 0, mismatchedSessions: 0,
needsSync: false, scanComplete: true, scanFailures: [], warnings: [], sessions: [],
};
case "get_skills_mcp_state": return {
codexDir, codexSkillsDir: `${codexDir}/skills`, disabledSkillsDir: `${codexDir}/disabled-skills`,
skills: [], mcpServers: [], warnings: [],
};
case "open_url": return undefined;
default: throw new Error(`Fixture has no handler for command: ${command}`);
}
}
window.__TAURI_INTERNALS__ = {
invoke,
transformCallback(callback, once = false) {
const id = nextCallback++;
callbacks.set(id, (value) => {
if (once) callbacks.delete(id);
callback(value);
});
return id;
},
unregisterCallback(id) { callbacks.delete(id); },
runCallback(id, value) { callbacks.get(id)?.(value); },
};
window.__CODEX_X_FIXTURE__ = {
snapshot,
loginSecondOfficialAccount,
setUsageMode,
completeSync: () => settle("sync", false),
failSync: () => settle("sync", true),
completeDetail: () => settle("detail", false),
failDetail: () => settle("detail", true),
reset() {
sessionStorage.removeItem(storageKey);
window.location.reload();
},
};
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";
const panelBody = document.createElement("details");
panelBody.open = true;
const label = document.createElement("summary");
label.textContent = "Fixture:所有命令均为内存模拟";
panelBody.append(label);
panel.append(panelBody);
const controls = document.createElement("div");
controls.style.cssText = "display:flex;flex-wrap:wrap;gap:4px;margin-top:6px";
for (const [text, kind, fail] of [
["Fixture:完成模板同步", "sync", false],
["Fixture:使模板同步失败", "sync", true],
["Fixture:完成模板详情", "detail", false],
["Fixture:使模板详情失败", "detail", true],
]) {
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", () => settle(kind, fail));
controls.append(button);
}
loginButton = document.createElement("button");
loginButton.type = "button";
loginButton.textContent = "Fixture:登录第二个官方账号";
loginButton.style.cssText = "font:inherit;padding:5px;border:1px solid #aaa;border-radius:4px;background:#eee;color:#111;cursor:pointer";
loginButton.addEventListener("click", loginSecondOfficialAccount);
controls.append(loginButton);
for (const [text, mode] of [
["Fixture:用量示例数据", "sample"],
["Fixture:用量空数据", "empty"],
["Fixture:用量读取失败", "error"],
["Fixture:用量部分数据", "partial"],
]) {
const button = document.createElement("button");
button.type = "button";
button.textContent = text;
button.style.cssText = loginButton.style.cssText;
button.addEventListener("click", () => setUsageMode(mode));
controls.append(button);
}
const resetButton = document.createElement("button");
resetButton.type = "button";
resetButton.textContent = "Fixture:重置测试数据";
resetButton.style.cssText = loginButton.style.cssText;
resetButton.addEventListener("click", () => window.__CODEX_X_FIXTURE__.reset());
controls.append(resetButton);
panelBody.append(controls);
const diagnostics = document.createElement("details");
diagnostics.open = false;
const summary = document.createElement("summary");
summary.textContent = "Fixture:命令次数与供应商切换记录";
output = document.createElement("pre");
output.id = "fixture-command-log";
output.setAttribute("aria-label", "Fixture 命令记录");
output.style.cssText = "white-space:pre-wrap;max-height:135px;overflow:auto;margin:6px 0 0";
diagnostics.append(summary, output);
panelBody.append(diagnostics);
document.body.append(panel);
render();
});
})();
+46
View File
@@ -0,0 +1,46 @@
import { readFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import react from "@vitejs/plugin-react";
import { createServer } from "vite";
// This renderer-only server never starts Tauri or connects to the real Codex store.
// Run: node apps/desktop/tests/serve-ui-fixture.mjs [port]
const root = fileURLToPath(new URL("../", import.meta.url));
const port = Number(process.argv[2] || 1421);
if (!Number.isInteger(port) || port < 1024 || port > 65535) {
throw new Error("Fixture port must be an integer between 1024 and 65535");
}
const fixture = await readFile(new URL("./fixtures/ui-runtime.js", import.meta.url), "utf8");
const server = await createServer({
root,
configFile: false,
clearScreen: false,
plugins: [
{
name: "codex-x-ui-fixture",
transformIndexHtml: {
order: "pre",
handler: () => [{ tag: "script", children: fixture, injectTo: "head-prepend" }],
},
},
react(),
],
server: {
host: "127.0.0.1",
port,
strictPort: true,
watch: { ignored: ["**/src-tauri/**"] },
headers: {
"Content-Security-Policy": "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; connect-src 'self' ws://127.0.0.1:*; img-src 'self' data:; font-src 'self' data:; object-src 'none'; frame-src 'none'; base-uri 'none'",
},
},
});
await server.listen();
console.log(`Fixture ready: http://127.0.0.1:${port}/`);
console.log("All IPC is mocked. Use the Fixture controls to resolve pending template requests.");
for (const signal of ["SIGINT", "SIGTERM"]) {
process.once(signal, async () => {
await server.close();
process.exit(0);
});
}
+121
View File
@@ -8,6 +8,127 @@
日志不得包含 Token、认证文件内容、用户数据或仅适用于某台电脑的隐私路径。
## 2026-09-08:子代理用量归属主会话
- 根因:用量聚合使用物理线程 ID 作为会话 ID,未接入会话管理的子代理分类与父子关系,导致内部线程
出现在最近会话并增加活跃会话数。
- 复用 `sqlite_subagent_thread_ids` 与日志 `source` 判定,读取 `thread_spawn_edges` 和来源中的父线程。
当前数据库的显式分类优先;旧库无来源字段、NULL 或空白不视为明确的普通用户会话,保留日志分类。
所有身份读取保持只读及短锁等待;父关系冲突不随意选择归属。
- 每个物理线程继续独立计算精确用量、累计增量和重放去重,再递归汇入主会话。总量、日期和模型计数
按主会话 ID 去重,最近列表在归并之后截取 10 条。筛选只命中子代理时也显示所属主会话的标题。
- 子代理归属与历史继承分别处理。用户主动 fork 保持独立主会话;纯 spawn 不自动视为继承历史,
避免与父线程数值相同的独立请求被误删。只有明确 fork 或不同 ID 的继承元数据才检查重放前缀。
- 无法确定主会话的子代理不生成独立会话行,其可核实的 Token 仍进入全局、日期与模型统计,并说明范围。
明确继承但父日志缺失时,继续保守跳过无法去重的历史并显示完整性提示。
- 验证:Rust 全量 363 项测试通过,覆盖多层子代理、同计数独立请求、归档副本、普通 fork、仅子代理
命中筛选、SQLite-only 父子边、缺失来源字段、未知父关系与环路;TypeScript 检查通过。
- macOS 发布构建、renderer 构建及签名严格校验通过;备份旧版后替换并启动本地 App,安装摘要与构建一致。
## 2026-09-08:设置标签过渡与最近会话标题
- 设置的两类标签内容复用 `PageTransition`,保留旧内容完成淡出后再淡入新内容。用量组件保持实例和筛选,
页面切换时通过活动状态停止接收旧请求,首次打开仍按需加载。
- 最近会话限制为 10 条,统计总量、趋势和模型分布仍覆盖全部匹配记录。
- 最近会话在截取列表后,按 ID 只读查询会话管理同源的 SQLite 标题。共用标题清理与优先级:标题、
首条用户消息、预览文本;当前数据库优先,无聊天标题时以项目名兜底。数据库缺失或暂不可读时,
继续尝试日志元数据中的项目名,最后显示“未命名会话”,不再把截短的会话 ID 当标题。
- 标题每次读取时重新查询,聊天改名后不需要重新解析 Token 日志;悬停可查看完整标题。
- 验证:Rust 全量 351 项测试通过,覆盖只读标题查询、当前/旧数据库优先级、项目名兜底、锁定数据库、
标题改名与缓存并存、10 条展示上限不截断总量。TypeScript 检查及 renderer 生产构建通过。
浏览器实际观察设置标签的 `exit`、`enter` 状态,切回保留日期/模型筛选,最近会话表为 10 行。
- macOS 发布构建与本地签名严格校验通过;备份旧版后替换本地 App 并启动,可执行文件摘要与本轮构建一致。
## 2026-09-08:直接复制、1M 上下文与用量统计
### 行为与实现
- 官方登录与第三方供应商点击复制后立即保存并留在列表,不打开编辑或确认框。名称由后端在锁内判重;
官方副本按 Unicode 字符截断主体,为副本及数字后缀预留空间,避免合法长名称无法复制。
- 第三方复制在一个 SQLite 事务中完成检测项持久化、原启用项识别和副本保存,复制失败全部回滚;
不写 live 配置或认证。前端保存列表使用请求序号,使迟到的旧列表读取不能覆盖新副本。
- 两类配置的 TOML 标题旁增加 1M 复选框。使用 `toml_edit` 修改草稿的顶层
`model_context_window = 1000000`,未设置自动压缩时补 `model_auto_compact_token_limit = 900000`。
已有自定义阈值、注释、MCP 及其他表均保留;取消时移除预设值或恢复本次编辑前的值。
手工编辑 TOML 会同步复选框,格式错误时阻止开关覆盖草稿。新建官方配置先读取完整官方模板,认证仍为空。
- 设置分为通用设置和用量统计。统计页首次打开才读取本地 `sessions` 与 `archived_sessions` JSONL,
命令在阻塞工作线程运行,使用独立缓存锁与前端加载状态,不占用供应商的操作锁。
- 统计优先使用精确 `last_token_usage`,缺失时以累计计数的增量计算;按会话身份合并归档与恢复片段,
对累计快照、限额来源重复和分叉继承前缀去重。父日志不完整时暂缓对应分叉统计并明确提示。
输入包含缓存,输出包含推理,两者不额外加到总量;没有历史记录的用量不推算。
- 按本地日历日提供今天、近 7 天、近 30 天和全部范围及模型过滤;展示总量、每日堆叠图、模型分布、
最近 30 个会话和精确每日明细。最近会话显示上限不影响总量。读取失败可保留同一筛选的旧结果,
空目录显示空状态,损坏、缺失和扫描限额通过覆盖提示说明。
- 内存缓存只保留身份、时间、模型和计数,不保存会话正文;支持追加读取、部分尾行重试、文件替换与删除。
每次扫描有文件数、目录深度和字节预算,跳过符号链接;手动刷新重新核对完整文件内容。
超出预算时跨次刷新继续当前轮扫描;复核尚未完成的完整缓存保留至新结果读完,避免中途清空已有用量。
- 参考 CC Switch 的配置与会话统计实现,参考版本为
`farion1231/cc-switch@f3b18df12007d0fd79fd8ad8d310880664015197`。
### 验证
- Rust 全量 341 项测试通过;补充缺损提示与大库刷新后,统计模块最终 30 项全部通过(当前共 345 项)。
- TypeScript 类型检查、renderer 生产构建与 5 项现有前端供应商测试通过;Rust 格式检查与差异空白检查通过。
- Rust 开发检查无告警,macOS App 发布构建与本地签名严格校验通过;备份旧 App 后完成本地替换并启动,
安装后的可执行文件摘要与本轮构建一致,版本号保持 0.3.15。
- 浏览器通过纯内存 IPC fixture 验证官方/API 直接复制、检测项仍为当前项、重复名称编号、两类 1M 保存,
以及通用/用量标签、四种时间范围、模型筛选、每日明细、失败保留旧值、空状态及部分数据提示。
浅色和深色截图布局正常,1280px 视口下页面无横向溢出。新建官方账号启用 1M、保存再打开时完整模板保留、
认证为空,关闭预设后其他设置保留。所有测试均使用虚构账号或临时目录。
## 2026-09-08:多个官方登录配置与标题配色
### 设计与兼容
- 供应商新增入口可选择第三方 API 或官方 Codex 登录。默认官方配置和命名配置均可编辑名称、
复制;新建与复制仅加入列表,点击启用后切换。空认证配置启用后由用户在 Codex 中完成登录。
- 官方配置使用稳定 ID,与可编辑名称分离。SQLite schema v4 按 CODEX_HOME 保存名称与选择状态,
私有快照按目录和配置 ID 隔离完整 TOML 与认证;默认项继续兼容原快照位置。
- 当前官方配置拥有随后发生的登录与凭据刷新。切走前捕获到所属配置,未修改认证的保存使用最新值,
显式清空则保留待登录状态。存在命名账号后,不再把来源无法归属的代理认证或旧历史备份混入默认账号。
- 修改 live 文件前校验读取时的配置与认证是否仍一致,写入、快照及选择记录失败时条件回滚。
删除当前命名账号先切回默认项;默认项保留,损坏的命名快照仍可在列表中删除。
- 启动列表只读取元数据、当前认证与显式快照,不扫描历史或生成编辑草稿;显式编辑和恢复保留旧兼容能力。
前端忽略过期列表及离开页面后迟到的复制编辑回调,避免覆盖新列表或留下空编辑草稿。
- 提示词顶部强调色复用页面蓝色变量,浅色为 `#2563eb`,深色为 `#76a8ff`。
### 验证
- 最终 Rust 全量 302 项测试通过,覆盖账号命名、完整复制、认证隔离、刷新、第三方往返、待登录归属、
默认入口兼容、删除、数据库失败回滚、并发修改与启动不扫历史。
- TypeScript 类型检查、renderer 生产构建及 5 项前端供应商测试通过。
- Rust 开发构建检查无告警通过,格式化与差异空白检查通过。
- 浏览器使用隔离 IPC fixture 验证新增类型、默认改名、两账号往返、复制及独立清空认证、刷新后保留、
删除当前账号回到默认项;实际 DOM 确认两种主题的提示词标题蓝色。
- 界面验证使用虚构账号,文件与数据库持久化由临时目录中的 Rust 回归验证,未操作真实用户认证。
## 2026-09-08:模板同步与页面操作隔离、保留首次检测的供应商
### 根因与修复
- 后台模板同步本身仅设置 `promptSyncing`,但远程下载与模板内容读取共用长时间持有的互斥锁。
同步期间查看/编辑或启用模板会等待该锁,前端共享的 `loading` 又会使供应商页面的按钮禁用。
查看与启用现在依次使用本地修改、已提交的 SQLite 缓存和打包模板;联网更新统一由同步命令处理。
- 模板详情请求使用页面独立的加载状态。离开提示词页、切换配置目录、打开另一编辑对象时使旧请求
失效,迟到的成功、失败及清理回调不能覆盖新的编辑草稿或其他页面的状态。
- 本地编辑允许与同步并行。同步清理在数据库事务中保留已有本地修改的模板,返回目录前再次读取
最新修改记录,避免下载开始时的旧快照误删刚编辑过的下架模板。
- 首次显示的 CC Switch 供应商可能只是当前 Codex live 配置的检测结果,并未执行数据库导入。
旧逻辑在切换前只更新已有的唯一匹配记录,因此未保存的检测项会在 live 配置被替换后消失。
现在明确启用/切换时保存未匹配的当前第三方配置:在同一 SQLite 事务内完成匹配、分配不冲突的
记录 ID 和保存,保留完整 TOML 与独立 API Key,切换失败时沿用条件回滚。多个匹配项不擅自覆盖。
- 当前供应商标记只接受与实际 live 配置匹配的已保存 ID;临时或冲突 ID 不覆盖后端识别结果。
普通状态读取继续保持无配置写入,不触发 CC Switch 全量导入。
### 验证
- Rust 回归覆盖同步锁持有期间读取本地模板、同步期间新增本地修改、首次供应商启用/直接切走、
官方与第三方往返、完整模板及密钥保留、ID 冲突、多份相同配置和失败回滚。
- 使用仅模拟 Tauri IPC 的浏览器测试页面复现旧版按钮禁用;修复后同步与详情请求同时挂起时,
可切换第三方或官方、打开供应商新增表单。迟到详情不覆盖新草稿,同步失败后可重试。
- 隔离界面复现入口为 `node apps/desktop/tests/serve-ui-fixture.mjs`,步骤见
`apps/desktop/tests/fixtures/README.md`;其中供应商持久化为模拟响应,实际保证来自 Rust 回归测试。
## 2026-08-11:供应商认证往返、模板完整性与启动读取
### 决策
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "codex-x-workspace",
"private": true,
"version": "0.3.15",
"version": "0.3.16",
"scripts": {
"dev": "pnpm --dir apps/desktop tauri dev",
"build": "pnpm --dir apps/desktop tauri build",