Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

fix(codex): detect Windows MSIX and PATH .cmd CLIs and prefer newest version for bundled models (#10234)

Lee31654e795ff8
diff --git a/src-tauri/src/codex_config.rs b/src-tauri/src/codex_config.rs
index 59f941255..1c15fbb74 100644
--- a/src-tauri/src/codex_config.rs
+++ b/src-tauri/src/codex_config.rs
@@ -1638,7 +1638,9 @@ const CODEX_DESKTOP_CLI_PACKAGE_IN_BUNDLE: &str = "Contents/Resources/codex-cli/
/// 桌面版自带的 Codex CLI 的版本,读文件、不跑子进程:
///
/// - macOS:ChatGPT.app / Codex.app 里 `codex-cli/codex-package.json` 的 `version`;
-/// - Windows:`%LOCALAPPDATA%\OpenAI\Codex\bin` 下装着 `codex.exe` 的版本目录名。
+/// - Windows:`%LOCALAPPDATA%\OpenAI\Codex\bin` 下装着 `codex.exe` 的版本目录名(微软商店
+/// MSIX 包的 `app\resources` 里没有类似 `codex-package.json` 的 CLI 版本文件,这里保持
+/// 不拉起子进程)。
///
/// 桌面版自动更新后、用它建新对话之前,Codex 线程里记的还都是旧版本,而只装桌面版的人 PATH
/// 上又没有 `codex`:不看这里就一直按旧版本拉官方模型列表。版本号认不认得由调用方判断。
@@ -1695,6 +1697,9 @@ fn push_codex_cli_candidate(
seen: &mut HashSet<String>,
candidate: PathBuf,
) {
+ #[cfg(windows)]
+ let key = candidate.to_string_lossy().to_ascii_lowercase();
+ #[cfg(not(windows))]
let key = candidate.to_string_lossy().into_owned();
if seen.insert(key) {
candidates.push(candidate);
@@ -1827,10 +1832,171 @@ fn push_env_codex_cli_candidates(candidates: &mut Vec<PathBuf>, seen: &mut HashS
}
}
+#[cfg(any(windows, test))]
+const WINDOWS_MSIX_CODEX_PACKAGE_PREFIX: &str = "OpenAI.Codex_";
+
+#[cfg(any(windows, test))]
+const WINDOWS_MSIX_CODEX_CLI_IN_PACKAGE: &[&str] = &[
+ "app/resources/codex-cli/bin/codex.exe",
+ "app/resources/codex.exe",
+];
+
+#[cfg(any(windows, test))]
+fn is_windows_msix_codex_package_name(name: &str) -> bool {
+ name.len() > WINDOWS_MSIX_CODEX_PACKAGE_PREFIX.len()
+ && name
+ .get(..WINDOWS_MSIX_CODEX_PACKAGE_PREFIX.len())
+ .is_some_and(|prefix| prefix.eq_ignore_ascii_case(WINDOWS_MSIX_CODEX_PACKAGE_PREFIX))
+}
+
+#[cfg(any(windows, test))]
+fn parse_windows_msix_codex_package_version(name: &str) -> Option<&str> {
+ if !is_windows_msix_codex_package_name(name) {
+ return None;
+ }
+ let rest = &name[WINDOWS_MSIX_CODEX_PACKAGE_PREFIX.len()..];
+ let version = rest.split('_').next()?;
+ (version.contains('.')
+ && crate::services::provider::codex_official_models::usable_version(version))
+ .then_some(version)
+}
+
+#[cfg(any(windows, test))]
+fn collect_windows_msix_codex_cli_candidates_from_roots(roots: &[PathBuf]) -> Vec<PathBuf> {
+ let mut ranked = Vec::new();
+ for root in roots {
+ let pkg_version = root
+ .file_name()
+ .and_then(|name| name.to_str())
+ .and_then(parse_windows_msix_codex_package_version)
+ .map(str::to_string);
+ for (layout_idx, relative) in WINDOWS_MSIX_CODEX_CLI_IN_PACKAGE.iter().enumerate() {
+ let candidate = root.join(relative);
+ if candidate.is_file() {
+ let modified = fs::metadata(&candidate)
+ .ok()
+ .and_then(|m| m.modified().ok());
+ ranked.push((pkg_version.clone(), modified, layout_idx, candidate));
+ }
+ }
+ }
+ ranked.sort_by(
+ |(a_ver, a_time, a_layout, a_path), (b_ver, b_time, b_layout, b_path)| {
+ let ver_ord = match (a_ver.as_deref(), b_ver.as_deref()) {
+ (Some(a), Some(b)) => {
+ crate::services::provider::codex_official_models::compare_versions(b, a)
+ }
+ (Some(_), None) => std::cmp::Ordering::Less,
+ (None, Some(_)) => std::cmp::Ordering::Greater,
+ (None, None) => std::cmp::Ordering::Equal,
+ };
+ ver_ord
+ .then_with(|| b_time.cmp(a_time))
+ .then_with(|| a_layout.cmp(b_layout))
+ .then_with(|| a_path.cmp(b_path))
+ },
+ );
+ ranked.into_iter().map(|(_, _, _, path)| path).collect()
+}
+
+#[cfg(windows)]
+fn windows_msix_codex_package_roots() -> Vec<PathBuf> {
+ use winreg::enums::HKEY_CURRENT_USER;
+ use winreg::RegKey;
+
+ const PACKAGES_SUBKEY: &str = r"Software\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\Repository\Packages";
+ let Ok(packages) = RegKey::predef(HKEY_CURRENT_USER).open_subkey(PACKAGES_SUBKEY) else {
+ return Vec::new();
+ };
+
+ let mut roots = Vec::new();
+ for subkey_name in packages.enum_keys().filter_map(Result::ok) {
+ if !is_windows_msix_codex_package_name(&subkey_name) {
+ continue;
+ }
+ let Ok(pkg_key) = packages.open_subkey(&subkey_name) else {
+ continue;
+ };
+ let Ok(root) = pkg_key.get_value::<String, _>("PackageRootFolder") else {
+ continue;
+ };
+ let trimmed = root.trim();
+ if !trimmed.is_empty() {
+ roots.push(PathBuf::from(trimmed));
+ }
+ }
+ roots
+}
+
+#[cfg(any(windows, test))]
+fn windows_codex_pathext_extensions(pathext: Option<&str>) -> Vec<&'static str> {
+ const SUPPORTED: &[&str] = &[".exe", ".cmd", ".bat"];
+ let mut ordered = Vec::new();
+ if let Some(raw) = pathext {
+ for entry in raw.split(';').map(str::trim) {
+ if let Some(&ext) = SUPPORTED.iter().find(|ext| entry.eq_ignore_ascii_case(ext)) {
+ if !ordered.contains(&ext) {
+ ordered.push(ext);
+ }
+ }
+ }
+ }
+ if ordered.is_empty() {
+ SUPPORTED.to_vec()
+ } else {
+ ordered
+ }
+}
+
+#[cfg(any(windows, test))]
+fn is_windows_app_execution_alias_dir(path: &Path) -> bool {
+ let normalized = path
+ .to_string_lossy()
+ .replace('/', "\\")
+ .to_ascii_lowercase();
+ normalized
+ .trim_end_matches('\\')
+ .ends_with("\\microsoft\\windowsapps")
+}
+
+/// 在 Windows 上解析 `PATH` 里的 `codex.exe` / `codex.cmd` / `codex.bat`:
+/// `Command::new("codex")` 走 `CreateProcessW`,不会命中 `PATH` 上自定义的 `.cmd` 垫片(#9890)。
+#[cfg(any(windows, test))]
+fn push_windows_path_codex_cli_candidates(
+ candidates: &mut Vec<PathBuf>,
+ seen: &mut HashSet<String>,
+ path_env: &std::ffi::OsStr,
+ pathext: Option<&str>,
+) {
+ let extensions = windows_codex_pathext_extensions(pathext);
+ for dir in std::env::split_paths(path_env) {
+ if dir.as_os_str().is_empty() || is_windows_app_execution_alias_dir(&dir) {
+ continue;
+ }
+ for ext in &extensions {
+ let candidate = dir.join(format!("codex{ext}"));
+ if candidate.is_file() {
+ push_codex_cli_candidate(candidates, seen, candidate);
+ }
+ }
+ }
+}
+
fn codex_cli_candidates() -> Vec<PathBuf> {
let mut candidates = Vec::new();
let mut seen = HashSet::new();
+ #[cfg(windows)]
+ if let Some(path_env) = std::env::var_os("PATH") {
+ let pathext = std::env::var("PATHEXT").ok();
+ push_windows_path_codex_cli_candidates(
+ &mut candidates,
+ &mut seen,
+ &path_env,
+ pathext.as_deref(),
+ );
+ }
+
for candidate in CODEX_CLI_FIXED_CANDIDATES {
push_codex_cli_candidate(&mut candidates, &mut seen, PathBuf::from(candidate));
}
@@ -1859,7 +2025,9 @@ fn codex_desktop_cli_in(home: &Path) -> Option<PathBuf> {
///
/// - macOS:`/Applications` 和 `~/Applications` 下的 ChatGPT.app、Codex.app,新 bundle
/// 排在前面,不管装在哪个目录(别的系统上不存在,自然跳过);
-/// - Windows:`%LOCALAPPDATA%\OpenAI\Codex\bin\<版本>\codex.exe`,版本目录随桌面版更新而变。
+/// - Windows:先取微软商店 MSIX 安装包(`OpenAI.Codex_*`,按包版本号从高到低)里的
+/// `app\resources\codex.exe`,再兜底 `%LOCALAPPDATA%\OpenAI\Codex\bin\<版本>\codex.exe`
+/// (按修改时间从新到旧)。
fn push_desktop_codex_cli_candidates(
candidates: &mut Vec<PathBuf>,
seen: &mut HashSet<String>,
@@ -1879,6 +2047,11 @@ fn push_desktop_codex_cli_candidates(
#[cfg(windows)]
{
+ for candidate in collect_windows_msix_codex_cli_candidates_from_roots(
+ &windows_msix_codex_package_roots(),
+ ) {
+ push_codex_cli_candidate(candidates, seen, candidate);
+ }
if let Some(local_appdata) = std::env::var_os("LOCALAPPDATA") {
push_codex_cli_candidates_newest_first(
candidates,
@@ -1921,15 +2094,9 @@ fn push_codex_cli_candidates_newest_first(
}
}
-/// `login_path` 是登录 shell 的 PATH(解析不到为 `None`)。GUI 启动时继承的是 launchd 的
-/// 窄 PATH,npm 装的 `codex` 是 `#!/usr/bin/env node` 脚本,找不到 node 就 exit 127,
-/// 只能退到后面的候选(常是桌面版自带的旧版本,目录里缺新模型,#9764)。与运行时命令一样
-/// (#8653),把候选自己的目录、登录 shell 的 PATH 补在继承的 PATH 前面。
-fn codex_bundled_models_command(candidate: &Path, login_path: Option<&str>) -> Command {
+fn codex_cli_command(candidate: &Path, args: &[&str], login_path: Option<&str>) -> Command {
let mut command = Command::new(candidate);
- command
- .args(["debug", "models", "--bundled"])
- .stdin(Stdio::null());
+ command.args(args).stdin(Stdio::null());
#[cfg(not(target_os = "windows"))]
{
@@ -1959,6 +2126,117 @@ fn codex_bundled_models_command(candidate: &Path, login_path: Option<&str>) -> C
command
}
+/// `login_path` 是登录 shell 的 PATH(解析不到为 `None`)。GUI 启动时继承的是 launchd 的
+/// 窄 PATH,npm 装的 `codex` 是 `#!/usr/bin/env node` 脚本,找不到 node 就 exit 127,
+/// 只能退到后面的候选(常是桌面版自带的旧版本,目录里缺新模型,#9764)。与运行时命令一样
+/// (#8653),把候选自己的目录、登录 shell 的 PATH 补在继承的 PATH 前面。
+fn codex_bundled_models_command(candidate: &Path, login_path: Option<&str>) -> Command {
+ codex_cli_command(candidate, &["debug", "models", "--bundled"], login_path)
+}
+
+fn parse_codex_cli_version(stdout: &str) -> Option<String> {
+ stdout
+ .lines()
+ .map(str::trim)
+ .filter(|line| !line.is_empty())
+ .take(5)
+ .filter(|line| !line.starts_with('{') && !line.starts_with('['))
+ .find_map(|line| {
+ line.split_whitespace().find_map(|token| {
+ let cleaned = token
+ .trim_matches(|c: char| {
+ !c.is_ascii_alphanumeric() && c != '.' && c != '-' && c != '+'
+ })
+ .trim_start_matches(['v', 'V']);
+ (cleaned.contains('.')
+ && crate::services::provider::codex_official_models::usable_version(cleaned))
+ .then(|| cleaned.to_string())
+ })
+ })
+}
+
+fn candidate_may_exist(candidate: &Path) -> bool {
+ candidate.components().count() <= 1 || candidate.exists()
+}
+
+#[cfg(windows)]
+fn resolve_bare_windows_codex_exe(candidate: &Path) -> Option<PathBuf> {
+ if candidate != Path::new("codex") {
+ return None;
+ }
+ let path_env = std::env::var_os("PATH")?;
+ std::env::split_paths(&path_env)
+ .filter(|dir| !dir.as_os_str().is_empty())
+ .map(|dir| dir.join("codex.exe"))
+ .find(|exe| exe.is_file())
+}
+
+/// 多份 Codex 并存时,先探各自 `--version` 按版本号从高到低排序(版本相同或解析不到版本时
+/// 保持原候选顺序),避免 PATH 上遗留的旧版 CLI 抢在更新的独立版或桌面版前面(#9890)。
+fn order_codex_cli_candidates_by_version(
+ candidates: Vec<PathBuf>,
+ login_path: Option<&str>,
+) -> Vec<(PathBuf, Option<String>)> {
+ let mut unique = Vec::new();
+ let mut seen_real = HashSet::new();
+ for candidate in candidates {
+ #[cfg(windows)]
+ let resolved_for_dedup = resolve_bare_windows_codex_exe(&candidate);
+ #[cfg(not(windows))]
+ let resolved_for_dedup: Option<PathBuf> = None;
+
+ let target = resolved_for_dedup.as_deref().unwrap_or(candidate.as_path());
+ if let Ok(real) = fs::canonicalize(target) {
+ #[cfg(windows)]
+ let real_key = real.to_string_lossy().to_ascii_lowercase();
+ #[cfg(not(windows))]
+ let real_key = real.to_string_lossy().into_owned();
+ if !seen_real.insert(real_key) {
+ continue;
+ }
+ }
+ unique.push(candidate);
+ }
+
+ let runnable_count = unique.iter().filter(|c| candidate_may_exist(c)).count();
+ if runnable_count <= 1 {
+ return unique.into_iter().map(|c| (c, None)).collect();
+ }
+
+ let mut probed = Vec::new();
+ for (index, candidate) in unique.into_iter().enumerate() {
+ if !candidate_may_exist(&candidate) {
+ continue;
+ }
+ let version = match codex_cli_command(&candidate, &["--version"], login_path).output() {
+ Ok(output) if output.status.success() => {
+ parse_codex_cli_version(&String::from_utf8_lossy(&output.stdout))
+ }
+ Ok(_) => None,
+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue,
+ Err(_) => None,
+ };
+ probed.push((index, version, candidate));
+ }
+
+ probed.sort_by(|(a_idx, a_ver, _), (b_idx, b_ver, _)| {
+ match (a_ver.as_deref(), b_ver.as_deref()) {
+ (Some(a), Some(b)) => {
+ crate::services::provider::codex_official_models::compare_versions(b, a)
+ .then_with(|| a_idx.cmp(b_idx))
+ }
+ (Some(_), None) => std::cmp::Ordering::Less,
+ (None, Some(_)) => std::cmp::Ordering::Greater,
+ (None, None) => a_idx.cmp(b_idx),
+ }
+ });
+
+ probed
+ .into_iter()
+ .map(|(_, version, candidate)| (candidate, version))
+ .collect()
+}
+
/// 没跑出 Codex 自带的模型列表。
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum CodexBundledModelsError {
@@ -1994,16 +2272,17 @@ pub(crate) fn load_codex_bundled_models() -> Result<Vec<Value>, CodexBundledMode
})
}
-/// 依次跑各个候选的 `codex debug models --bundled`,返回第一份 `pick` 取得出东西的结果。
-/// 候选里有不存在的路径(固定位置、PATH 上的裸名),启动不了不算失败;一个都启动不了才是
-/// 找不到命令行。
+/// 优先按版本从高到低依次跑各个候选的 `codex debug models --bundled`,返回第一份 `pick`
+/// 取得出东西的结果。候选里有不存在的路径(固定位置、PATH 上的裸名),启动不了不算失败;
+/// 一个都启动不了才是找不到命令行。
fn first_bundled_catalog<T>(
candidates: Vec<PathBuf>,
login_path: Option<&str>,
pick: impl Fn(&Value) -> Option<T>,
) -> Result<T, CodexBundledModelsError> {
+ let ordered = order_codex_cli_candidates_by_version(candidates, login_path);
let mut failure = None;
- for candidate in candidates {
+ for (candidate, version) in ordered {
let candidate_label = candidate.to_string_lossy();
let output = match codex_bundled_models_command(&candidate, login_path).output() {
Ok(output) => output,
@@ -2039,6 +2318,10 @@ fn first_bundled_catalog<T>(
}
};
if let Some(found) = pick(&catalog) {
+ log::debug!(
+ "Loaded Codex bundled catalog from `{candidate_label}` (version={})",
+ version.as_deref().unwrap_or("unknown")
+ );
return Ok(found);
}
failure = Some(format!(
@@ -2770,13 +3053,24 @@ fn codex_catalog_from_specs_for_row(
}
entry
}
- None => codex_catalog_model_entry(
- &template,
- spec,
- index,
- profile,
- default_context_window,
- ),
+ None => {
+ if profile == CodexCatalogToolProfile::NativeResponses
+ && spec.model.to_ascii_lowercase().starts_with("gpt-")
+ {
+ log::warn!(
+ "Codex catalog model `{}` did not match any official bundled entry (official_count={}); falling back to native responses template",
+ spec.model,
+ official.len()
+ );
+ }
+ codex_catalog_model_entry(
+ &template,
+ spec,
+ index,
+ profile,
+ default_context_window,
+ )
+ }
};
// A changed window needs a matching compaction threshold in single-provider
// catalogs too. Otherwise an official/template threshold can stay at 244800
diff --git a/src-tauri/src/codex_config/tests.rs b/src-tauri/src/codex_config/tests.rs
index e500bb155..feeacde5b 100644
--- a/src-tauri/src/codex_config/tests.rs
+++ b/src-tauri/src/codex_config/tests.rs
@@ -3759,6 +3759,180 @@ fn codex_cli_candidates_try_the_desktop_app_cli_after_standalone_installs() {
assert!(position(&standalone) < position(&desktop));
}
+#[test]
+fn windows_msix_codex_package_detection_matches_codex_and_orders_newest_version_first() {
+ assert!(is_windows_msix_codex_package_name(
+ "OpenAI.Codex_26.1120.6357.0_x64__2p2nqsd0c76g0"
+ ));
+ assert!(is_windows_msix_codex_package_name(
+ "openai.codex_26.1117.4957.0_arm64__2p2nqsd0c76g0"
+ ));
+ assert!(!is_windows_msix_codex_package_name(
+ "OpenAI.CodexPrimaryRuntime.v26-1123-915-0_26.1123.915.0_x64__3k8sg7r9htsxt"
+ ));
+ assert!(!is_windows_msix_codex_package_name("OpenAI.Codex_"));
+ assert!(!is_windows_msix_codex_package_name("中文包名"));
+
+ let temp = tempfile::tempdir().expect("create temp dir");
+ let now = std::time::SystemTime::now();
+
+ let older_msix_root = temp.path().join("OpenAI.Codex_26.1117.4957.0_x64__pub");
+ let older_msix_cli = older_msix_root.join("app/resources/codex.exe");
+ create_cli_candidate(&older_msix_cli);
+ // 故意把旧包的 mtime 设得更新,验证优先按包版本号排序而非只看 mtime。
+ set_mtime(&older_msix_cli, now);
+
+ let newer_msix_root = temp.path().join("OpenAI.Codex_26.1120.6357.0_x64__pub");
+ let newer_msix_cli = newer_msix_root.join("app/resources/codex.exe");
+ create_cli_candidate(&newer_msix_cli);
+ set_mtime(&newer_msix_cli, now - std::time::Duration::from_secs(3600));
+
+ let discovered =
+ collect_windows_msix_codex_cli_candidates_from_roots(&[older_msix_root, newer_msix_root]);
+ assert_eq!(discovered, vec![newer_msix_cli, older_msix_cli]);
+}
+
+#[test]
+fn windows_path_codex_candidates_resolve_cmd_respect_pathext_and_skip_store_alias_dir() {
+ let temp = tempfile::tempdir().expect("create temp dir");
+ let custom_dir = temp.path().join("CodexCLI");
+ let mixed_dir = temp.path().join("MixedBin");
+ let alias_dir = temp.path().join("Microsoft").join("WindowsApps");
+
+ let custom_cmd = custom_dir.join("codex.cmd");
+ let mixed_exe = mixed_dir.join("codex.exe");
+ let mixed_cmd = mixed_dir.join("codex.cmd");
+ let alias_exe = alias_dir.join("codex.exe");
+
+ for path in [&custom_cmd, &mixed_exe, &mixed_cmd, &alias_exe] {
+ create_cli_candidate(path);
+ }
+
+ let path_env =
+ std::env::join_paths([&alias_dir, &custom_dir, &mixed_dir]).expect("join PATH entries");
+
+ let mut default_candidates = Vec::new();
+ let mut seen = HashSet::new();
+ push_windows_path_codex_cli_candidates(
+ &mut default_candidates,
+ &mut seen,
+ &path_env,
+ Some(".COM;.EXE;.BAT;.CMD"),
+ );
+ assert_eq!(
+ default_candidates,
+ vec![custom_cmd.clone(), mixed_exe.clone(), mixed_cmd.clone()]
+ );
+
+ let mut cmd_first_candidates = Vec::new();
+ let mut cmd_seen = HashSet::new();
+ push_windows_path_codex_cli_candidates(
+ &mut cmd_first_candidates,
+ &mut cmd_seen,
+ &path_env,
+ Some(".CMD;.EXE"),
+ );
+ assert_eq!(cmd_first_candidates, vec![custom_cmd, mixed_cmd, mixed_exe]);
+}
+
+#[test]
+fn parse_codex_cli_version_extracts_semver_and_ignores_non_versions() {
+ assert_eq!(
+ parse_codex_cli_version("codex-cli 0.171.0-alpha.13.2\n").as_deref(),
+ Some("0.171.0-alpha.13.2")
+ );
+ assert_eq!(
+ parse_codex_cli_version("Active code page: 65001\r\ncodex-cli 0.171.0-alpha.13.2\r\n")
+ .as_deref(),
+ Some("0.171.0-alpha.13.2")
+ );
+ assert_eq!(
+ parse_codex_cli_version("codex v0.167.2\r\n").as_deref(),
+ Some("0.167.2")
+ );
+ assert_eq!(
+ parse_codex_cli_version(r#"{"models":[{"slug":"x"}]}"#),
+ None
+ );
+ assert_eq!(parse_codex_cli_version("codex-cli 2026"), None);
+}
+
+#[test]
+fn bundled_models_prefer_highest_cli_version_and_fall_back_if_newest_fails() {
+ let dir = tempfile::tempdir().expect("create temp dir");
+ let pick = |catalog: &Value| catalog.get("models").cloned();
+
+ #[cfg(windows)]
+ let write_fake_cli = |name: &str, version: &str, bundled_json: Option<&str>| -> PathBuf {
+ let path = dir.path().join(format!("{name}.cmd"));
+ let bundled_branch = match bundled_json {
+ Some(json) => format!("echo {json}\r\nexit /b 0"),
+ None => "echo bundled failed 1>&2\r\nexit /b 1".to_string(),
+ };
+ let script = format!(
+ "@echo off\r\nif \"%~1\"==\"--version\" (\r\n echo codex-cli {version}\r\n exit /b 0\r\n)\r\n{bundled_branch}\r\n"
+ );
+ fs::write(&path, script).expect("write fake cmd");
+ path
+ };
+
+ #[cfg(unix)]
+ let write_fake_cli = |name: &str, version: &str, bundled_json: Option<&str>| -> PathBuf {
+ use std::os::unix::fs::PermissionsExt;
+ let path = dir.path().join(name);
+ let bundled_branch = match bundled_json {
+ Some(json) => format!("printf '%s\\n' '{json}'\nexit 0"),
+ None => "echo 'bundled failed' >&2\nexit 1".to_string(),
+ };
+ let script = format!(
+ "#!/bin/sh\nif [ \"$1\" = \"--version\" ]; then\n echo 'codex-cli {version}'\n exit 0\nfi\n{bundled_branch}\n"
+ );
+ fs::write(&path, script).expect("write fake sh");
+ fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).expect("chmod fake sh");
+ path
+ };
+
+ let older_cli = write_fake_cli(
+ "older",
+ "0.167.2",
+ Some(r#"{"models":[{"slug":"gpt-6.1"}]}"#),
+ );
+ let newer_cli = write_fake_cli(
+ "newer",
+ "0.171.0-alpha.13.2",
+ Some(r#"{"models":[{"slug":"gpt-6.2-sol"}]}"#),
+ );
+ let broken_newest = write_fake_cli("broken", "0.172.0", None);
+ let same_ver_first = write_fake_cli(
+ "same-a",
+ "0.171.0",
+ Some(r#"{"models":[{"slug":"from-standalone"}]}"#),
+ );
+ let same_ver_second = write_fake_cli(
+ "same-b",
+ "0.171.0",
+ Some(r#"{"models":[{"slug":"from-desktop"}]}"#),
+ );
+
+ // 即使旧版 CLI 排在前面,也要优先采用版本更新的候选。
+ assert_eq!(
+ first_bundled_catalog(vec![older_cli.clone(), newer_cli.clone()], None, pick).ok(),
+ Some(json!([{ "slug": "gpt-6.2-sol" }]))
+ );
+
+ // 版本最高的候选在 --bundled 阶段失败时,退回次新且可用的候选。
+ assert_eq!(
+ first_bundled_catalog(vec![older_cli, broken_newest, newer_cli], None, pick).ok(),
+ Some(json!([{ "slug": "gpt-6.2-sol" }]))
+ );
+
+ // 版本号一致时维持原有候选顺序(独立 CLI 优先于桌面版兜底)。
+ assert_eq!(
+ first_bundled_catalog(vec![same_ver_first, same_ver_second], None, pick).ok(),
+ Some(json!([{ "slug": "from-standalone" }]))
+ );
+}
+
#[test]
fn classic_tool_template_keeps_the_classic_tool_contract() {
let template = load_codex_classic_tool_template();
diff --git a/src-tauri/src/services/provider/codex_official_models.rs b/src-tauri/src/services/provider/codex_official_models.rs
index 2522f7e27..ec2421639 100644
--- a/src-tauri/src/services/provider/codex_official_models.rs
+++ b/src-tauri/src/services/provider/codex_official_models.rs
@@ -184,7 +184,7 @@ pub(crate) fn reset_test_env() {
/// 服务端按版本过滤列表:报低了少模型(`0.60.0` 返回 0 条),报高了会列出本机驱动不了的
/// 模型。拿不到版本就不请求,不编一个默认值。
-fn usable_version(version: &str) -> bool {
+pub(crate) fn usable_version(version: &str) -> bool {
let version = version.trim();
let core = version.split(['-', '+']).next().unwrap_or_default();
!core.is_empty()
@@ -211,7 +211,7 @@ fn newest_codex_version(path: Option<String>, others: Vec<String>) -> Option<Str
/// 按 semver 比较 Codex 版本:先比数字段,同一版本的预发布(`-alpha.2`)比正式版旧,
/// 预发布之间逐段比(数字段按数值)。`+` 之后的构建信息不参与比较。
-fn compare_versions(a: &str, b: &str) -> CmpOrdering {
+pub(crate) fn compare_versions(a: &str, b: &str) -> CmpOrdering {
fn split(version: &str) -> (Vec<u64>, Option<&str>) {
let version = version.split('+').next().unwrap_or_default();
let (core, pre) = match version.split_once('-') {