Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

fix(ai): resolve Codex CLI on Windows (#1935)

林剑凛895f116b0478
diff --git a/crates/dbx-core/src/ai_codex_cli.rs b/crates/dbx-core/src/ai_codex_cli.rs
index 16dec8fd76..b637c98ba5 100644
--- a/crates/dbx-core/src/ai_codex_cli.rs
+++ b/crates/dbx-core/src/ai_codex_cli.rs
@@ -15,6 +15,7 @@ use tokio::process::Command;
use tokio::sync::Notify;
const DEFAULT_CODEX_MODELS: &[&str] = &["default", "gpt-5.5", "gpt-5.4-mini"];
+#[cfg(not(windows))]
const CODEX_PATH_MARKER: &str = "__DBX_CODEX_PATH__";
pub type CodexRunOptions = CliAgentRunOptions;
@@ -27,7 +28,8 @@ fn codex_program(config: &AiConfig) -> String {
async fn resolve_codex_command(config: &AiConfig) -> CodexCommandSpec {
let configured = codex_program(config);
if is_path_like_program(&configured) {
- return CodexCommandSpec { program: expand_tilde(&configured), args: Vec::new() };
+ let expanded = expand_tilde(&configured);
+ return CodexCommandSpec { program: direct_program_path(&expanded).unwrap_or(expanded), args: Vec::new() };
}
if let Some(path) = resolve_program_path(&configured).await {
CodexCommandSpec { program: path, args: Vec::new() }
@@ -71,12 +73,39 @@ async fn resolve_program_path(program: &str) -> Option<String> {
fn direct_program_path(program: &str) -> Option<String> {
let path = Path::new(program);
if path.is_absolute() && path.is_file() {
+ #[cfg(windows)]
+ {
+ if let Some(path) = windows_launchable_program_path(path) {
+ return Some(path);
+ }
+ }
Some(path.to_string_lossy().to_string())
} else {
None
}
}
+#[cfg(windows)]
+fn windows_launchable_program_path(path: &Path) -> Option<String> {
+ if is_windows_launchable_program(path) {
+ return Some(path.to_string_lossy().to_string());
+ }
+ let parent = path.parent()?;
+ let stem = path.file_name()?.to_str()?;
+ program_path_candidates(parent, stem)
+ .into_iter()
+ .find(|candidate| is_windows_launchable_program(candidate))
+ .and_then(|candidate| candidate.is_file().then(|| candidate.to_string_lossy().to_string()))
+}
+
+#[cfg(windows)]
+fn is_windows_launchable_program(path: &Path) -> bool {
+ matches!(
+ path.extension().and_then(|extension| extension.to_str()).map(str::to_ascii_lowercase).as_deref(),
+ Some("exe" | "cmd" | "bat" | "com")
+ )
+}
+
fn common_program_path(program: &str) -> Option<String> {
common_executable_dirs()
.into_iter()
@@ -96,7 +125,10 @@ fn program_path_candidates(dir: &Path, program: &str) -> Vec<PathBuf> {
if path.extension().is_some() {
return vec![dir.join(program)];
}
- ["", ".cmd", ".exe", ".bat", ".ps1"].iter().map(|extension| dir.join(format!("{program}{extension}"))).collect()
+ [".cmd", ".exe", ".bat", ".com", "", ".ps1"]
+ .iter()
+ .map(|extension| dir.join(format!("{program}{extension}")))
+ .collect()
}
#[cfg(not(windows))]
@@ -119,19 +151,25 @@ async fn shell_program_path(program: &str) -> Option<String> {
#[cfg(windows)]
async fn shell_program_path(program: &str) -> Option<String> {
- let script = format!("(Get-Command {} -ErrorAction SilentlyContinue).Source", windows_shell_quote(program));
+ let script = format!("(Get-Command -All {} -ErrorAction SilentlyContinue).Source", windows_shell_quote(program));
let mut command = Command::new("powershell.exe");
command.args(["-NoProfile", "-Command", &script]);
command.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null());
let output = command.output().await.ok()?;
output.status.success().then_some(())?;
let stdout = String::from_utf8_lossy(&output.stdout);
- stdout
- .lines()
- .map(str::trim)
- .find(|line| !line.is_empty())
- .filter(|path| Path::new(path).is_file())
- .map(ToString::to_string)
+ first_windows_program_path(&stdout)
+}
+
+#[cfg(windows)]
+fn first_windows_program_path(value: &str) -> Option<String> {
+ let paths = value.lines().map(str::trim).filter(|line| !line.is_empty()).collect::<Vec<_>>();
+ if let Some(path) =
+ paths.iter().copied().find(|path| is_windows_launchable_program(Path::new(path)) && Path::new(path).is_file())
+ {
+ return Some(path.to_string());
+ }
+ paths.into_iter().find(|path| Path::new(path).is_file()).map(ToOwned::to_owned)
}
#[cfg(windows)]
@@ -399,28 +437,12 @@ pub async fn test_codex_connection(config: &AiConfig) -> Result<AiTestConnection
validate_codex_program(config)?;
let codex_command = resolve_codex_command(config).await;
let mut command = cli_command(&codex_command.program);
- command.args(["exec", "--json", "--skip-git-repo-check", "--sandbox", "read-only"]);
+ command.args(["login", "status"]);
command.envs(codex_process_env(config, &codex_command)?.iter().map(|(key, value)| (key.as_str(), value.as_str())));
- let model = config.model.trim();
- if !model.is_empty() && !model.eq_ignore_ascii_case("default") {
- command.args(["--model", model]);
- }
-
- let output = command
- .arg("Reply with exactly: DBX Codex OK")
- .output()
- .await
- .map_err(|e| classify_codex_spawn_error(&e.to_string()))?;
+ let output = command.output().await.map_err(|e| classify_codex_spawn_error(&e.to_string()))?;
if output.status.success() {
- let stdout = String::from_utf8_lossy(&output.stdout);
- if !stdout.contains("DBX Codex OK") {
- let stderr = String::from_utf8_lossy(&output.stderr);
- return Err(format!(
- "[codexRunFailed] Codex CLI smoke test returned unexpected output. stdout: {stdout} stderr: {stderr}"
- ));
- }
Ok(AiTestConnectionResult {
success: true,
message: format!("OK - {}ms", start.elapsed().as_millis()),
@@ -491,10 +513,13 @@ mod tests {
#[cfg(not(windows))]
use super::shell_quote;
use super::{
- build_codex_exec_command, codex_cli_env, codex_enabled_tools, codex_process_env, common_executable_dirs,
- is_path_like_program, merged_path_with_dir, parse_codex_jsonl_event, parse_codex_models,
- validate_codex_program, CodexRunOptions, DEFAULT_CODEX_MODELS,
+ build_codex_exec_command, codex_cli_env, codex_enabled_tools, is_path_like_program, parse_codex_jsonl_event,
+ parse_codex_models, validate_codex_program, CodexRunOptions, DEFAULT_CODEX_MODELS,
};
+ #[cfg(not(windows))]
+ use super::{codex_process_env, common_executable_dirs, merged_path_with_dir};
+ #[cfg(windows)]
+ use super::{first_windows_program_path, program_path_candidates};
use crate::agent_events::AgentEvent;
use crate::ai::{AiApiStyle, AiAuthMethod, AiConfig, AiProvider, AiReasoningLevel};
use crate::ai_cli_agent::{model_infos, CliAgentCommandSpec};
@@ -586,6 +611,34 @@ mod tests {
assert!(!is_path_like_program("codex"));
}
+ #[test]
+ #[cfg(windows)]
+ fn windows_codex_lookup_prefers_cmd_over_extensionless_shim() {
+ let candidates = program_path_candidates(std::path::Path::new(r"C:\nvm4w\nodejs"), "codex");
+
+ assert_eq!(candidates[0], std::path::Path::new(r"C:\nvm4w\nodejs\codex.cmd"));
+ assert!(candidates.iter().position(|path| path == std::path::Path::new(r"C:\nvm4w\nodejs\codex")).unwrap() > 0);
+ }
+
+ #[test]
+ #[cfg(windows)]
+ fn windows_shell_lookup_prefers_launchable_command() {
+ let dir = std::env::temp_dir().join(format!("dbx-codex-test-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let extensionless = dir.join("codex");
+ let cmd = dir.join("codex.cmd");
+ std::fs::write(&extensionless, "#!/bin/sh\n").unwrap();
+ std::fs::write(&cmd, "@echo off\n").unwrap();
+
+ let output = format!("{}\n{}\n", extensionless.display(), cmd.display());
+ let resolved = first_windows_program_path(&output).unwrap();
+
+ assert_eq!(resolved, cmd.to_string_lossy());
+ let _ = std::fs::remove_file(extensionless);
+ let _ = std::fs::remove_file(cmd);
+ let _ = std::fs::remove_dir(dir);
+ }
+
#[test]
#[cfg(not(windows))]
fn common_codex_lookup_dirs_include_homebrew_and_system_paths() {
diff --git a/src-tauri/src/commands/mcp.rs b/src-tauri/src/commands/mcp.rs
index d509137d39..b1637f9d2c 100644
--- a/src-tauri/src/commands/mcp.rs
+++ b/src-tauri/src/commands/mcp.rs
@@ -145,14 +145,36 @@ fn installed_mcp_bin_script() -> Option<String> {
fn locate_windows_command(command: &str) -> Option<String> {
command_stdout("where", &[command])
.ok()
- .and_then(first_non_empty_line)
+ .and_then(first_windows_command_path)
.or_else(|| {
- let script = format!("(Get-Command {} -ErrorAction SilentlyContinue).Source", windows_shell_quote(command));
- command_stdout("powershell.exe", &["-NoProfile", "-Command", &script]).ok().and_then(first_non_empty_line)
+ let script =
+ format!("(Get-Command -All {} -ErrorAction SilentlyContinue).Source", windows_shell_quote(command));
+ command_stdout("powershell.exe", &["-NoProfile", "-Command", &script])
+ .ok()
+ .and_then(first_windows_command_path)
})
.or_else(|| windows_command_candidates(command).into_iter().find(|candidate| Path::new(candidate).is_file()))
}
+#[cfg(windows)]
+fn first_windows_command_path(value: String) -> Option<String> {
+ let paths = value.lines().map(str::trim).filter(|line| !line.is_empty()).collect::<Vec<_>>();
+ if let Some(path) =
+ paths.iter().copied().find(|path| is_windows_launchable_command(path) && Path::new(path).is_file())
+ {
+ return Some(path.to_string());
+ }
+ paths.into_iter().find(|path| Path::new(path).is_file()).map(ToOwned::to_owned)
+}
+
+#[cfg(windows)]
+fn is_windows_launchable_command(path: &str) -> bool {
+ matches!(
+ Path::new(path).extension().and_then(|extension| extension.to_str()).map(str::to_ascii_lowercase).as_deref(),
+ Some("exe" | "cmd" | "bat" | "com")
+ )
+}
+
fn command_success(command: &str, args: &[&str]) -> bool {
command_output(command, args).is_ok_and(|output| output.success)
}
@@ -225,7 +247,7 @@ fn windows_command_candidates(command: &str) -> Vec<String> {
if Path::new(command).extension().is_some() {
return Vec::new();
}
- let names = ["cmd", "exe", "ps1"].iter().map(|extension| format!("{command}.{extension}"));
+ let names = ["cmd", "exe", "bat", "com", "ps1"].iter().map(|extension| format!("{command}.{extension}"));
names
.clone()
.chain(