Skip to content

LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。

TypeScript

fix: harden CLI command resolution

nash_su21bab39766a3
diff --git a/src-tauri/src/commands/claude_cli.rs b/src-tauri/src/commands/claude_cli.rs
index 8b6610c1..8c102dc3 100644
--- a/src-tauri/src/commands/claude_cli.rs
+++ b/src-tauri/src/commands/claude_cli.rs
@@ -28,6 +28,8 @@ use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::{Child, Command};
use tokio::sync::Mutex;
+use super::cli_resolver::find_cli_command;
+
/// Shared state holding running `claude` child processes keyed by the
/// frontend-generated stream id. Registered via .manage() in lib.rs.
#[derive(Default)]
@@ -113,69 +115,18 @@ fn claude_content_blocks(content: &ClaudeContent) -> Vec<serde_json::Value> {
}
}
-/// Spawn the user's login shell to retrieve the full PATH (which
-/// includes nvm/vfox/volta/fnm/… directories that macOS GUI apps
-/// don't inherit from launchd). Returns `None` on any failure so the
-/// caller can fall back to the process-level PATH.
-#[cfg(not(windows))]
-fn shell_path() -> Option<String> {
- let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
- // `-ilc` = interactive + login so both profile and rc files run,
- // picking up version-manager init scripts. We print a unique
- // marker so we can find our line even if the shell prints motd /
- // banners to stdout.
- let output = std::process::Command::new(&shell)
- .args(["-ilc", r#"printf '\x1ePATH=%s\x1e\n' "$PATH""#])
- .stdin(Stdio::null())
- .stdout(Stdio::piped())
- .stderr(Stdio::null())
- .output()
- .ok()?;
-
- let stdout = String::from_utf8_lossy(&output.stdout);
- for line in stdout.lines() {
- // Look for the marker-delimited PATH value.
- if let Some(rest) = line.strip_prefix('\x1e') {
- if let Some(val) = rest.strip_suffix('\x1e') {
- if let Some(path) = val.strip_prefix("PATH=") {
- if !path.is_empty() {
- return Some(path.to_string());
- }
- }
- }
- }
- }
- None
+async fn find_claude_command() -> Result<PathBuf, String> {
+ find_cli_command("claude", &["claude.cmd", "claude.exe"]).await
}
-fn find_claude_command() -> Result<PathBuf, String> {
+fn suppress_windows_console(_cmd: &mut Command) {
#[cfg(windows)]
{
- if let Ok(path) = which::which("claude.cmd") {
- return Ok(path);
- }
- if let Ok(path) = which::which("claude.exe") {
- return Ok(path);
- }
- }
+ use std::os::windows::process::CommandExt;
- if let Ok(path) = which::which("claude") {
- return Ok(path);
+ const CREATE_NO_WINDOW: u32 = 0x08000000;
+ _cmd.creation_flags(CREATE_NO_WINDOW);
}
-
- // macOS / Linux GUI apps inherit a minimal PATH from launchd /
- // the display manager. Ask the user's login shell for its full
- // PATH which includes version-manager directories (nvm, vfox,
- // volta, fnm, …) and search that instead.
- #[cfg(not(windows))]
- if let Some(full_path) = shell_path() {
- // which::which_in searches the given PATH string.
- if let Ok(path) = which::which_in("claude", Some(&full_path), ".") {
- return Ok(path);
- }
- }
-
- Err("`claude` not found on PATH".to_string())
}
/// Locate `claude` on PATH and confirm it's runnable by calling
@@ -183,7 +134,7 @@ fn find_claude_command() -> Result<PathBuf, String> {
/// mount of the settings panel.
#[tauri::command]
pub async fn claude_cli_detect() -> Result<DetectResult, String> {
- let path = match find_claude_command() {
+ let path = match find_claude_command().await {
Ok(p) => p,
Err(error) => {
return Ok(DetectResult {
@@ -197,11 +148,9 @@ pub async fn claude_cli_detect() -> Result<DetectResult, String> {
let path_str = path.to_string_lossy().to_string();
- let output = tokio::time::timeout(
- Duration::from_secs(3),
- Command::new(&path).arg("--version").output(),
- )
- .await;
+ let mut cmd = Command::new(&path);
+ suppress_windows_console(&mut cmd);
+ let output = tokio::time::timeout(Duration::from_secs(3), cmd.arg("--version").output()).await;
match output {
Ok(Ok(out)) if out.status.success() => {
@@ -301,8 +250,9 @@ pub async fn claude_cli_spawn(
})
.collect();
- let claude = find_claude_command()?;
+ let claude = find_claude_command().await?;
let mut cmd = Command::new(&claude);
+ suppress_windows_console(&mut cmd);
cmd.arg("-p")
.arg("--output-format")
.arg("stream-json")
diff --git a/src-tauri/src/commands/cli_resolver.rs b/src-tauri/src/commands/cli_resolver.rs
new file mode 100644
index 00000000..a848991c
--- /dev/null
+++ b/src-tauri/src/commands/cli_resolver.rs
@@ -0,0 +1,172 @@
+use std::collections::HashMap;
+use std::path::PathBuf;
+use std::process::{Command, Stdio};
+use std::sync::{Mutex, OnceLock};
+use std::time::Duration;
+
+const LOGIN_SHELL_PATH_TIMEOUT: Duration = Duration::from_secs(3);
+const PATH_MARKER: char = '\x1e';
+
+static RESOLVED_COMMANDS: OnceLock<Mutex<HashMap<String, PathBuf>>> = OnceLock::new();
+
+pub(crate) async fn find_cli_command(
+ command: &str,
+ windows_candidates: &[&str],
+) -> Result<PathBuf, String> {
+ if let Some(path) = cached_command(command) {
+ return Ok(path);
+ }
+
+ let command = command.to_string();
+ let cache_key = command.clone();
+ let windows_candidates = windows_candidates
+ .iter()
+ .map(|candidate| (*candidate).to_string())
+ .collect::<Vec<_>>();
+ let path = tokio::task::spawn_blocking(move || {
+ find_cli_command_uncached(&command, &windows_candidates)
+ })
+ .await
+ .map_err(|e| format!("Failed to resolve CLI command: {e}"))??;
+
+ cache_command(cache_key, path.clone());
+ Ok(path)
+}
+
+fn command_cache() -> &'static Mutex<HashMap<String, PathBuf>> {
+ RESOLVED_COMMANDS.get_or_init(|| Mutex::new(HashMap::new()))
+}
+
+fn cached_command(command: &str) -> Option<PathBuf> {
+ let mut cache = command_cache().lock().ok()?;
+ let path = cache.get(command)?.clone();
+ if path.exists() {
+ Some(path)
+ } else {
+ cache.remove(command);
+ None
+ }
+}
+
+fn cache_command(command: String, path: PathBuf) {
+ if let Ok(mut cache) = command_cache().lock() {
+ cache.insert(command, path);
+ }
+}
+
+#[cfg_attr(not(windows), allow(unused_variables))]
+fn find_cli_command_uncached(
+ command: &str,
+ windows_candidates: &[String],
+) -> Result<PathBuf, String> {
+ #[cfg(windows)]
+ {
+ for candidate in windows_candidates
+ .iter()
+ .map(String::as_str)
+ .chain(std::iter::once(command))
+ {
+ if let Ok(path) = which::which(candidate) {
+ return Ok(path);
+ }
+ }
+ return Err(format!("`{command}` not found on PATH"));
+ }
+
+ #[cfg(not(windows))]
+ {
+ if let Ok(path) = which::which(command) {
+ return Ok(path);
+ }
+
+ if let Some(full_path) = login_shell_path(LOGIN_SHELL_PATH_TIMEOUT) {
+ if let Ok(path) = which::which_in(command, Some(&full_path), ".") {
+ return Ok(path);
+ }
+ }
+
+ Err(format!("`{command}` not found on PATH"))
+ }
+}
+
+#[cfg(not(windows))]
+fn login_shell_path(timeout: Duration) -> Option<String> {
+ let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
+ let shell_name = PathBuf::from(&shell)
+ .file_name()
+ .and_then(|name| name.to_str())
+ .unwrap_or_default()
+ .to_ascii_lowercase();
+ let shell_args = if matches!(shell_name.as_str(), "sh" | "dash" | "ash") {
+ vec!["-ic", r#"printf '\036PATH=%s\036\n' "$PATH""#]
+ } else {
+ vec!["-ilc", r#"printf '\036PATH=%s\036\n' "$PATH""#]
+ };
+ let mut child = Command::new(&shell)
+ // `-i` is intentional: many version managers only update PATH
+ // from interactive shell rc files. The timeout below bounds
+ // unusual shell configs that hang when run with null stdio.
+ // Minimal /bin/sh variants often do not support `-l`, so they
+ // use `-ic` while zsh/bash/fish keep the login shell path.
+ .args(shell_args)
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()
+ .ok()?;
+
+ let start = std::time::Instant::now();
+ loop {
+ match child.try_wait() {
+ Ok(Some(_)) => {
+ let output = child.wait_with_output().ok()?;
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ return parse_shell_path_output(&stdout);
+ }
+ Ok(None) if start.elapsed() >= timeout => {
+ let _ = child.kill();
+ let _ = child.wait();
+ return None;
+ }
+ Ok(None) => std::thread::sleep(Duration::from_millis(25)),
+ Err(_) => return None,
+ }
+ }
+}
+
+#[cfg(not(windows))]
+fn parse_shell_path_output(stdout: &str) -> Option<String> {
+ for line in stdout.lines() {
+ if let Some(rest) = line.strip_prefix(PATH_MARKER) {
+ if let Some(val) = rest.strip_suffix(PATH_MARKER) {
+ if let Some(path) = val.strip_prefix("PATH=") {
+ if !path.is_empty() {
+ return Some(path.to_string());
+ }
+ }
+ }
+ }
+ }
+ None
+}
+
+#[cfg(all(test, not(windows)))]
+mod tests {
+ use super::parse_shell_path_output;
+
+ #[test]
+ fn parse_shell_path_output_ignores_banners() {
+ let output = "Welcome\n\x1ePATH=/opt/homebrew/bin:/usr/bin\x1e\nGoodbye\n";
+ assert_eq!(
+ parse_shell_path_output(output).as_deref(),
+ Some("/opt/homebrew/bin:/usr/bin")
+ );
+ }
+
+ #[test]
+ fn parse_shell_path_output_rejects_missing_or_empty_markers() {
+ assert_eq!(parse_shell_path_output("PATH=/usr/bin"), None);
+ assert_eq!(parse_shell_path_output("\x1ePATH=\x1e"), None);
+ assert_eq!(parse_shell_path_output("\x1eOTHER=/usr/bin\x1e"), None);
+ }
+}
diff --git a/src-tauri/src/commands/codex_cli.rs b/src-tauri/src/commands/codex_cli.rs
index 5d4af4ae..d8bb41d1 100644
--- a/src-tauri/src/commands/codex_cli.rs
+++ b/src-tauri/src/commands/codex_cli.rs
@@ -19,6 +19,8 @@ use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::{Child, Command};
use tokio::sync::Mutex;
+use super::cli_resolver::find_cli_command;
+
#[derive(Default)]
pub struct CodexCliState {
children: Arc<Mutex<HashMap<String, Child>>>,
@@ -51,18 +53,8 @@ fn append_capped_line(collected: &mut String, line: &str, limit_bytes: usize) {
}
}
-fn find_codex_command() -> Result<PathBuf, String> {
- #[cfg(windows)]
- {
- if let Ok(path) = which::which("codex.cmd") {
- return Ok(path);
- }
- if let Ok(path) = which::which("codex.exe") {
- return Ok(path);
- }
- }
-
- which::which("codex").map_err(|_| "`codex` not found on PATH".to_string())
+async fn find_codex_command() -> Result<PathBuf, String> {
+ find_cli_command("codex", &["codex.cmd", "codex.exe"]).await
}
fn suppress_windows_console(_cmd: &mut Command) {
@@ -77,7 +69,7 @@ fn suppress_windows_console(_cmd: &mut Command) {
#[tauri::command]
pub async fn codex_cli_detect() -> Result<DetectResult, String> {
- let path = match find_codex_command() {
+ let path = match find_codex_command().await {
Ok(p) => p,
Err(error) => {
return Ok(DetectResult {
@@ -144,7 +136,7 @@ pub async fn codex_cli_spawn(
return Err("No prompt to send to codex CLI".to_string());
}
- let codex = find_codex_command()?;
+ let codex = find_codex_command().await?;
let mut cmd = Command::new(&codex);
suppress_windows_console(&mut cmd);
cmd.arg("-a")
diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs
index 88f45203..911dc610 100644
--- a/src-tauri/src/commands/mod.rs
+++ b/src-tauri/src/commands/mod.rs
@@ -1,4 +1,5 @@
pub mod claude_cli;
+mod cli_resolver;
pub mod codex_cli;
pub mod extract_images;
pub mod file_sync;