The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
tech(M1): Hintergrund-Shell leitet die Argumentform aus dem Shell-NAMEN ab
Davidba9557df588a
diff --git a/src-tauri/src/commands/bg_tasks.rs b/src-tauri/src/commands/bg_tasks.rsindex 933971cf..40bbf358 100644--- a/src-tauri/src/commands/bg_tasks.rs+++ b/src-tauri/src/commands/bg_tasks.rs@@ -139,11 +139,10 @@ fn sweep_isolation() -> std::sync::MutexGuard<'static, ()> {////// Windows: no `shell` at all, i.e. the PowerShell this module spawns by/// default and therefore the shell a real background task actually runs-/// there, with `ping` as the child that outlives the test. Git Bash is-/// deliberately not asked for: `shell_task_start_impl` builds PowerShell's-/// argument form for whatever program it is given on Windows, so a POSIX-/// shell would be handed `-NoProfile -NonInteractive -Command` and would never-/// run the command at all.+/// there, with `ping` as the child that outlives the test. Git Bash is still+/// deliberately not asked for — not because it would be mis-invoked any more+/// (the argument form follows the shell name now), but because a Git Bash+/// install is not something a Windows test run may assume.#[cfg(test)]fn a_task_that_starts_a_child() -> Value {if cfg!(target_os = "windows") {@@ -277,21 +276,18 @@ pub(crate) async fn shell_task_start_impl(args: &Value) -> CmdResult {}let id = Uuid::new_v4().to_string();- let (program, args_vec) = if cfg!(target_os = "windows") {- let shell = a.shell.unwrap_or_else(|| "powershell".into());- (- shell,- vec![- "-NoProfile".into(),- "-NonInteractive".into(),- "-Command".into(),- a.command.clone(),- ],- )- } else {- let shell = a.shell.unwrap_or_else(|| "bash".into());- (shell, vec!["-c".into(), a.command.clone()])- };+ // The argument form follows the SHELL, not the platform. This file used to+ // decide it here, on its own, and always built PowerShell's form on+ // Windows — so a caller-named `cmd` or `bash` was handed+ // `-NoProfile -NonInteractive -Command` and never ran the command at all.+ // The foreground twin already derived it from the shell name; both now ask+ // the same function, so a task started in the background and the same task+ // run in the foreground produce the identical command line.+ let (program, args_vec) = crate::commands::shell::shell_argv(+ cfg!(target_os = "windows"),+ a.shell.as_deref(),+ &a.command,+ );let mut cmd = TokioCommand::new(&program);cmd.args(&args_vec);@@ -1094,3 +1090,162 @@ mod cwd_default_tests {let _ = std::fs::remove_dir_all(&b);}}++/// The background task and its foreground twin, held against each other.+///+/// They are the same tool with two lifetimes: `shell_execute` waits,+/// `shell_execute` with `background: true` hands back a task id. A caller that+/// names a shell must get that shell, invoked the same way, on either path.+/// They drifted apart once — this file built PowerShell's argument form for+/// every program on Windows while the foreground built it from the shell's+/// name — and the drift was invisible to every non-Windows test run.+#[cfg(test)]+mod foreground_parity_tests {+ use super::*;++ /// A shell that is deliberately NOT the platform default, so the `shell`+ /// field is actually exercised rather than skipped.+ ///+ /// Windows: `cmd`, the exact value that used to be handed+ /// `-NoProfile -NonInteractive -Command` and fail. Unix: `sh`, which is+ /// not the `bash` default and is present on every machine this runs on.+ fn a_named_shell() -> &'static str {+ if cfg!(target_os = "windows") {+ "cmd"+ } else {+ "sh"+ }+ }++ /// One line, one word of output, and the same source text in cmd.exe and+ /// in a POSIX shell — so the assertion is about the invocation, not about+ /// a dialect difference in the command itself.+ const TOKEN: &str = "lu-parity-7f3a";++ fn the_command() -> String {+ format!("echo {TOKEN}")+ }++ /// A directory both runs can start in, so neither path has to fall back to+ /// the per-chat workspace and touch the user's home.+ fn a_directory() -> std::path::PathBuf {+ let d = std::env::temp_dir().join(format!("lu-parity-{}", std::process::id()));+ std::fs::create_dir_all(&d).expect("temp dir");+ d+ }++ async fn what_the_foreground_printed(dir: &std::path::Path) -> (String, i64) {+ let out = crate::commands::shell::shell_execute(+ the_command(),+ None,+ Some(dir.to_string_lossy().to_string()),+ Some(20_000),+ Some(a_named_shell().to_string()),+ None,+ None,+ None,+ )+ .await+ .expect("the foreground shell tool ran");+ (+ out["stdout"].as_str().unwrap_or_default().trim().to_string(),+ out["exitCode"].as_i64().unwrap_or(-1),+ )+ }++ async fn what_the_background_printed(dir: &std::path::Path) -> (String, i64) {+ let start = shell_task_start_impl(&json!({+ "command": the_command(),+ "shell": a_named_shell(),+ "cwd": dir.to_string_lossy(),+ }))+ .await+ .expect("the background task started");+ let id = start["id"].as_str().expect("id").to_string();+ for _ in 0..200 {+ let st = shell_task_status_impl(&json!({ "id": id })).await.expect("status");+ if !st["running"].as_bool().unwrap_or(true) {+ return (+ st["output_tail"].as_str().unwrap_or_default().trim().to_string(),+ st["exit_code"].as_i64().unwrap_or(-1),+ );+ }+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;+ }+ panic!("the background task never finished");+ }++ /// The behavioural half: same shell, same command, same result.+ ///+ /// On Windows this fails outright without the shared argument builder —+ /// `cmd -NoProfile -NonInteractive -Command echo …` prints cmd.exe's usage+ /// complaint and never echoes the token. On Unix it holds `sh` to the same+ /// contract on both paths, which is the property that has to keep holding+ /// for the Windows one to stay true.+ ///+ /// The isolation guard is a plain `Mutex` held across the awaits below, on+ /// purpose and like every other test here that stands up a live task: it is+ /// what keeps the shutdown-sweep tests from killing this task's child+ /// mid-run. There is nothing to deadlock against — the lock is only ever+ /// taken by tests, never by the code under test.+ #[allow(clippy::await_holding_lock)]+ #[tokio::test]+ async fn a_named_shell_behaves_the_same_in_the_background_as_in_the_foreground() {+ let _isolation = super::sweep_isolation();+ let dir = a_directory();++ let (foreground, fg_code) = what_the_foreground_printed(&dir).await;+ let (background, bg_code) = what_the_background_printed(&dir).await;++ // Both really ran — without this the assertion below would also pass+ // on two empty strings, i.e. on two equally broken paths.+ assert!(+ foreground.contains(TOKEN),+ "the foreground shell tool printed {foreground:?} with shell {:?}",+ a_named_shell(),+ );+ assert!(+ background.contains(TOKEN),+ "the background task printed {background:?} with shell {:?} — \+ the shell it was given was invoked with the wrong argument form",+ a_named_shell(),+ );+ assert_eq!(+ foreground, background,+ "the same command in the same shell came out differently on the two paths",+ );+ assert_eq!((fg_code, bg_code), (0, 0), "one of the two paths failed");++ let _ = std::fs::remove_dir_all(&dir);+ }++ /// The structural half: this file must not grow a second copy of the+ /// branch. The behavioural test above can only observe ONE shell per+ /// platform per run; a re-inlined branch that breaks a different shell+ /// would slip past it, and that is exactly how the original bug survived.+ ///+ /// Scoped to this file on purpose: `system.rs` and `install.rs` also spawn+ /// PowerShell with these flags, but they hardcode PowerShell for scripts of+ /// their own and never take a shell from a caller, so they are not twins of+ /// anything and are none of this test's business.+ #[test]+ fn the_background_path_builds_no_shell_flags_of_its_own() {+ const BG_TASKS_RS: &str = include_str!("bg_tasks.rs");+ // Split out of one string rather than written as separate literals:+ // a list of quoted flags would itself be the quoted flag this test+ // searches for, and the test would trip over its own source.+ for flag in "-NoProfile -NonInteractive -Command /C -c".split(' ') {+ let literal = format!("{:?}", flag);+ assert!(+ !BG_TASKS_RS.contains(&literal),+ "bg_tasks.rs builds the shell argument {flag} itself again — \+ that branch belongs in shell::shell_argv, which the foreground \+ path uses too",+ );+ }+ assert!(+ BG_TASKS_RS.contains("shell::shell_argv("),+ "the background path no longer goes through the shared argument builder",+ );+ }+}diff --git a/src-tauri/src/commands/shell.rs b/src-tauri/src/commands/shell.rsindex 857c4e20..a9489e36 100644--- a/src-tauri/src/commands/shell.rs+++ b/src-tauri/src/commands/shell.rs@@ -178,6 +178,64 @@ pub(crate) fn settle(a: &Arc<AtomicBool>, b: &Arc<AtomicBool>, max: std::time::D}}+/// The command line a shell wants for "run this one string as a command": the+/// program to spawn, and the arguments to hand it.+///+/// ONE copy, because there used to be two. The foreground `shell_execute`+/// derived the argument form from the shell's NAME; the background+/// `shell_task_start` derived it from the PLATFORM alone and gave PowerShell's+/// `-NoProfile -NonInteractive -Command` to whatever program the caller had+/// named. A background task with `shell: "cmd"` — a value the tool schema+/// advertises — therefore became `cmd -NoProfile -NonInteractive -Command+/// <command>`, which cmd.exe rejects flag by flag; `shell: "bash"` fared no+/// better. Only one of the two copies was ever repaired, which is the entire+/// argument for there being a single function: the same shell must produce the+/// same command line whether the task runs in the foreground or the background.+///+/// `windows` is a parameter rather than a `cfg!` inside the body so that BOTH+/// platforms' argument forms can be asserted from either platform's test run —+/// the Windows form is precisely the half no Mac or Linux run would otherwise+/// ever look at.+///+/// `command` stays ONE argument. It is never folded into the flag string, so+/// nothing inside it can close the argument and open a second command.+pub(crate) fn shell_argv(+ windows: bool,+ shell: Option<&str>,+ command: &str,+) -> (String, Vec<String>) {+ let shell_bin = shell+ .map(str::to_string)+ .unwrap_or_else(|| default_shell(windows).to_string());+ let name = shell_bin.to_lowercase();+ let mut args: Vec<String> = if windows && name.contains("powershell") {+ vec![+ "-NoProfile".into(),+ "-NonInteractive".into(),+ "-Command".into(),+ ]+ } else if windows && name.contains("cmd") {+ vec!["/C".into()]+ } else {+ // Every POSIX shell — and, on Windows, anything else the caller names,+ // `pwsh` included. Unchanged from what the foreground path has always+ // done with a name it does not recognise.+ vec!["-c".into()]+ };+ args.push(command.to_string());+ (shell_bin, args)+}++/// The shell a caller gets when it names none: PowerShell on Windows, bash+/// everywhere else. This is the path every user is on today.+pub(crate) fn default_shell(windows: bool) -> &'static str {+ if windows {+ "powershell"+ } else {+ "bash"+ }+}+#[tauri::command]#[allow(non_snake_case)]pub async fn shell_execute(@@ -208,24 +266,13 @@ fn shell_execute_sync(working_directory: Option<String>,) -> Result<serde_json::Value, String> {let timeout_ms = timeout.unwrap_or(120_000);- let shell_bin = shell.unwrap_or_else(|| {- if cfg!(target_os = "windows") {- "powershell".to_string()- } else {- "bash".to_string()- }- });+ // Shell name in, program + argument form out — the same function the+ // background twin in bg_tasks.rs calls, so the two cannot drift apart.+ let (shell_bin, shell_args) =+ shell_argv(cfg!(target_os = "windows"), shell.as_deref(), &command);let mut cmd = Command::new(&shell_bin);-- // Build shell command- if cfg!(target_os = "windows") && shell_bin.to_lowercase().contains("powershell") {- cmd.arg("-NoProfile").arg("-NonInteractive").arg("-Command").arg(&command);- } else if cfg!(target_os = "windows") && shell_bin.to_lowercase().contains("cmd") {- cmd.arg("/C").arg(&command);- } else {- cmd.arg("-c").arg(&command);- }+ cmd.args(&shell_args);// Append extra argsif let Some(extra_args) = args {@@ -336,6 +383,114 @@ fn shell_execute_sync(}}+/// The argument form, asserted for both platforms from either platform.+///+/// `shell_argv` takes `windows` as a parameter precisely so this module can+/// pin the Windows command lines on a Mac and the Unix ones on Windows. The+/// bug that made the function necessary lived in the Windows half and was+/// therefore invisible to every non-Windows test run there had ever been.+#[cfg(test)]+mod shell_dialect_tests {+ use super::shell_argv;++ const WINDOWS: bool = true;+ const UNIX: bool = false;+ const CMD: &str = "echo hi";++ fn argv(windows: bool, shell: Option<&str>) -> (String, Vec<String>) {+ shell_argv(windows, shell, CMD)+ }++ fn args_of(windows: bool, shell: &str) -> Vec<String> {+ argv(windows, Some(shell)).1+ }++ fn powershell_form() -> Vec<String> {+ vec![+ "-NoProfile".to_string(),+ "-NonInteractive".to_string(),+ "-Command".to_string(),+ CMD.to_string(),+ ]+ }++ fn cmd_form() -> Vec<String> {+ vec!["/C".to_string(), CMD.to_string()]+ }++ fn posix_form() -> Vec<String> {+ vec!["-c".to_string(), CMD.to_string()]+ }++ /// The path every user is on today — no `shell` named at all. Windows gets+ /// PowerShell with `-Command`, Unix gets bash with `-c`, exactly as before+ /// the two branches were merged into one function.+ #[test]+ fn the_default_shell_is_unchanged_on_both_platforms() {+ assert_eq!(+ argv(WINDOWS, None),+ ("powershell".to_string(), powershell_form()),+ );+ assert_eq!(argv(UNIX, None), ("bash".to_string(), posix_form()));+ }++ /// On Windows the form follows the name, including a full path to the+ /// binary and the `.exe` suffix — the spellings a caller actually sends.+ #[test]+ fn windows_gets_the_form_of_the_shell_it_was_named() {+ for ps in [+ "powershell",+ "PowerShell",+ "powershell.exe",+ r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe",+ ] {+ assert_eq!(args_of(WINDOWS, ps), powershell_form(), "{ps}");+ }+ for c in ["cmd", "CMD", "cmd.exe", r"C:\Windows\System32\cmd.exe"] {+ assert_eq!(args_of(WINDOWS, c), cmd_form(), "{c}");+ }+ // The two the background path used to break outright.+ for posix in ["bash", "sh", r"C:\Program Files\Git\bin\bash.exe"] {+ assert_eq!(args_of(WINDOWS, posix), posix_form(), "{posix}");+ }+ }++ /// PowerShell's flags are a Windows-only dialect. A `powershell` named on+ /// a Mac is a POSIX-style invocation like everything else there.+ #[test]+ fn unix_never_gets_windows_flags() {+ for shell in ["bash", "sh", "zsh", "/bin/sh", "powershell", "cmd"] {+ assert_eq!(args_of(UNIX, shell), posix_form(), "{shell}");+ }+ }++ /// The program is the shell the caller named, never a rewritten one.+ #[test]+ fn the_program_is_the_shell_that_was_named() {+ assert_eq!(argv(WINDOWS, Some("cmd.exe")).0, "cmd.exe");+ assert_eq!(argv(UNIX, Some("/bin/zsh")).0, "/bin/zsh");+ }++ /// No shell injection: the command travels as ONE argument, byte for byte,+ /// and never gets concatenated onto a flag. Quotes, `&&`, semicolons and+ /// newlines inside it are the shell's problem to parse, not a way to add a+ /// second argument to the shell's own command line.+ #[test]+ fn the_command_stays_a_single_argument() {+ let nasty = "echo \"a\" && whoami ; echo 'b'\nrm -rf /";+ for (windows, shell, flags) in [+ (WINDOWS, "powershell", 3usize),+ (WINDOWS, "cmd", 1),+ (WINDOWS, "bash", 1),+ (UNIX, "bash", 1),+ ] {+ let (_, args) = shell_argv(windows, Some(shell), nasty);+ assert_eq!(args.len(), flags + 1, "{shell} on windows={windows}");+ assert_eq!(args.last().map(String::as_str), Some(nasty));+ }+ }+}+/// The IPC surface itself, asserted against the shipped config files.////// `shell:allow-spawn` is the only permission the WebView holds that starts a