Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio Desktop: stop the launch-time PATH probe from rewriting shell history (#12846)

Daniel Han10b39dae9c1a
diff --git a/scripts/lockfile_supply_chain_audit.py b/scripts/lockfile_supply_chain_audit.py
index abb295690b2..303b00f6732 100644
--- a/scripts/lockfile_supply_chain_audit.py
+++ b/scripts/lockfile_supply_chain_audit.py
@@ -270,14 +270,8 @@ NPM_REGISTRY_PREFIXES_ALLOWED: tuple[str, ...] = (NPM_REGISTRY_PREFIX,)
CARGO_REGISTRY_SOURCE = "registry+https://github.com/rust-lang/crates.io-index"
-# Cargo non-registry source allowlist of `(crate_name, exact_source_string)`, both matched verbatim so bumping the pinned SHA forces a re-review. Unsloth's Tauri shell pulls `fix-path-env` from git because it is not published to crates.io; commit c4c45d5 was reviewed when it landed.
-CARGO_SOURCE_ALLOWLIST: tuple[tuple[str, str], ...] = (
- (
- "fix-path-env",
- "git+https://github.com/tauri-apps/fix-path-env-rs#"
- "c4c45d503ea115a839aae718d02f79e7c7f0f673",
- ),
-)
+# Cargo non-registry source allowlist of `(crate_name, exact_source_string)`, both matched verbatim so bumping a pinned SHA forces a re-review. Empty since the Tauri shell dropped its only git dependency, `fix-path-env` (unsloth#12678).
+CARGO_SOURCE_ALLOWLIST: tuple[tuple[str, str], ...] = ()
class Finding:
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 6fbdde90400..82a1fad436a 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -23,7 +23,7 @@ os.environ.setdefault("CUDA_DEVICE_ORDER", "PCI_BUS_ID")
os.environ.setdefault("TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL", "1")
# The desktop app hands this process a GUI environment, and a GUI environment has
-# no ~/.bashrc in it. `fix_path_env::fix()` in src-tauri/src/main.rs spawns the
+# no ~/.bashrc in it. `shell_path::fix_path()` in src-tauri spawns the
# login shell and then takes PATH out of it and nothing else, so an AMD host's
# HSA_OVERRIDE_GFX_VERSION / ROCM_PATH / USE_CK are dropped on the desktop path
# and kept on the `unsloth studio` one. #9926 is that difference: identical model
diff --git a/studio/backend/tests/test_desktop_shell_env_9926.py b/studio/backend/tests/test_desktop_shell_env_9926.py
index d0262aeea36..e93af515646 100644
--- a/studio/backend/tests/test_desktop_shell_env_9926.py
+++ b/studio/backend/tests/test_desktop_shell_env_9926.py
@@ -4,8 +4,8 @@
"""unsloth#9926: a desktop launch must end with the ROCm environment a terminal has.
An RX 7600 SIGSEGVs from the desktop app and trains from ``unsloth studio``,
-because ``fix_path_env::fix()`` is ``fix_vars(&["PATH"])`` and keeps only PATH
-out of the login shell. These pin the shape of the fix, not the crash, which
+because ``shell_path::fix_path()`` in src-tauri keeps only PATH out of the
+login shell. These pin the shape of the fix, not the crash, which
needs the card.
"""
diff --git a/studio/backend/tests/test_shell_probe_history_12678.py b/studio/backend/tests/test_shell_probe_history_12678.py
new file mode 100644
index 00000000000..dec50fbba59
--- /dev/null
+++ b/studio/backend/tests/test_shell_probe_history_12678.py
@@ -0,0 +1,189 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""unsloth#12678: reading the login shell's environment must not touch its history.
+
+Real shells, throwaway HOME; each case first shows the old command damaging it.
+"""
+
+from __future__ import annotations
+
+import shutil
+import sys
+
+import pytest
+
+from utils import desktop_shell_env as dse
+
+pytestmark = pytest.mark.skipif(sys.platform == "win32", reason = "no POSIX shell on Windows")
+
+SENTINEL = "UNSLOTH_TEST_RC_LOADED"
+ZSH = (
+ "HISTFILE=$HOME/.zsh_history\nHISTSIZE=2000\nSAVEHIST=1000\n"
+ "unsetopt APPEND_HISTORY\nprint -s plugin-entry\n"
+)
+BASH = "HISTSIZE=100000\nHISTFILESIZE=100000\nhistory -s plugin-entry\n"
+
+
+def _history(extended: bool) -> bytes:
+ lines = [f"echo history-{i}" for i in range(3000)]
+ if extended:
+ lines = [f": {1700000000 + i}:0;{line}" for i, line in enumerate(lines)]
+ return ("\n".join(lines) + "\n").encode()
+
+
+# name: (shell, rc file, rc body, extra files, extended history, history after the fix)
+CASES = {
+ "bash_history_s": ("bash", ".bash_profile", BASH, {}, False, "kept"),
+ "bash_exit_trap": (
+ "bash",
+ ".bash_profile",
+ BASH + "trap 'history -w ~/.bash_history' EXIT\n",
+ {},
+ False,
+ "kept",
+ ),
+ # zsh execs a lone final command and skips its save; a trap turns that off.
+ "zsh_exit_trap": ("zsh", ".zshrc", ZSH + "trap true EXIT\n", {}, False, "kept"),
+ "zsh_share_history_extended": (
+ "zsh",
+ ".zshrc",
+ ZSH + "setopt EXTENDED_HISTORY SHARE_HISTORY\ntrap true EXIT\n",
+ {},
+ True,
+ "kept",
+ ),
+ "zsh_zlogout": (
+ "zsh",
+ ".zshrc",
+ ZSH + "trap true EXIT\n",
+ {".zlogout": "fc -W $HOME/.zsh_history\n"},
+ False,
+ "kept",
+ ),
+ # Readonly HISTFILE: RCS still stops the save; the failed unset must not abort.
+ "zsh_readonly_histfile_errexit": (
+ "zsh",
+ ".zshrc",
+ ZSH + "trap true EXIT\ntypeset -r HISTFILE SAVEHIST\nsetopt ERR_EXIT\n",
+ {},
+ False,
+ "kept",
+ ),
+ # bash has no RCS: appends as on base, but the rewriting trap no longer runs.
+ "bash_readonly_histfile_errexit": (
+ "bash",
+ ".bash_profile",
+ BASH + "trap 'history -w ~/.bash_history' EXIT\nreadonly HISTFILE\nset -e\n",
+ {},
+ False,
+ "appended",
+ ),
+}
+
+
+def _home(tmp_path, monkeypatch, name, case):
+ shell, rc, body, extra, extended, _ = case
+ path = shutil.which(shell)
+ if path is None:
+ pytest.skip(
+ reason = f"{shell} is not installed; this case needs the real shell (unsloth#12678)"
+ )
+ home = tmp_path / name
+ home.mkdir()
+ (home / rc).write_text(f"export {SENTINEL}=1\n{body}", encoding = "utf-8")
+ for extra_name, text in extra.items():
+ (home / extra_name).write_text(text, encoding = "utf-8")
+ hist = home / (".zsh_history" if shell == "zsh" else ".bash_history")
+ hist.write_bytes(_history(extended))
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setenv("ZDOTDIR", str(home))
+ # Apple Terminal's session-history code, and the runner's own history settings.
+ for var in (
+ "HISTFILE",
+ "ENV",
+ "BASH_ENV",
+ "TERM_PROGRAM",
+ "TERM_SESSION_ID",
+ "SHELL_SESSION_HISTORY",
+ "HISTCONTROL",
+ "HISTIGNORE",
+ ):
+ monkeypatch.delenv(var, raising = False)
+ return path, hist
+
+
[email protected]("name", sorted(CASES))
+def test_reading_the_login_shell_leaves_its_history_alone(tmp_path, monkeypatch, name):
+ case = CASES[name]
+ extended, after = case[4], case[5]
+
+ # Control: the command as it was must damage this fixture, or the test proves nothing.
+ shell, hist = _home(tmp_path, monkeypatch, name + "_before", case)
+ with monkeypatch.context() as patch:
+ patch.setattr(dse, "probe_command", lambda _shell, command: command)
+ assert dse.read_login_shell_env(shell = shell).get(SENTINEL) == "1"
+ assert hist.read_bytes() != _history(extended)
+
+ shell, hist = _home(tmp_path, monkeypatch, name + "_after", case)
+ for _ in range(2):
+ assert dse.read_login_shell_env(shell = shell).get(SENTINEL) == "1"
+ data = hist.read_bytes()
+ if after == "kept":
+ assert data == _history(extended)
+ else:
+ assert data.startswith(_history(extended)) and len(data) > len(_history(extended))
+
+
+ "shell",
+ [
+ "/bin/sh",
+ "/bin/bash",
+ "/usr/local/bin/zsh",
+ "/opt/homebrew/bin/bash",
+ "ksh",
+ "zsh5",
+ "bash-5.2",
+ ],
+)
+def test_posix_shells_unset_histfile_first(shell):
+ command = dse.probe_command(shell, "env -0 > x")
+ assert command.endswith("(unset HISTFILE) 2>/dev/null && unset HISTFILE; exec env -0 > x")
+ assert "unsetopt RCS" in command
+
+
+ "shell", ["/usr/bin/fish", "/opt/homebrew/bin/nu", "/bin/tcsh", "/usr/bin/pwsh"]
+)
+def test_other_shells_keep_the_command(shell):
+ assert dse.probe_command(shell, "env -0 > x") == "env -0 > x"
+
+
[email protected]("shell", ["dash", "bash", "zsh"])
+def test_readonly_histfile_still_reads_the_environment(tmp_path, monkeypatch, shell):
+ # dash exits on `unset` of a readonly variable, even inside eval with `|| :`.
+ path = shutil.which(shell)
+ if path is None:
+ pytest.skip(
+ reason = f"{shell} is not installed; this case needs the real shell (unsloth#12678)"
+ )
+ rc = f"export {SENTINEL}=1\nHISTFILE=$HOME/.h\nreadonly HISTFILE\nset -e\n"
+ for name in (".profile", ".bash_profile", ".zshrc"):
+ (tmp_path / name).write_text(rc, encoding = "utf-8")
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("ZDOTDIR", str(tmp_path))
+ for var in ("HISTFILE", "ENV", "BASH_ENV"):
+ monkeypatch.delenv(var, raising = False)
+ assert dse.read_login_shell_env(shell = path).get(SENTINEL) == "1"
+
+
+def test_a_shell_rejecting_the_probe_falls_back(tmp_path):
+ # Stands in for a non-POSIX shell missing from the list (Plan 9 rc, a renamed fish).
+ shell = tmp_path / "notposix"
+ shell.write_text(
+ f'#!/bin/sh\ncase "$2" in if*) exit 2 ;; esac\n{SENTINEL}=1 exec /bin/sh -c "$2"\n',
+ encoding = "utf-8",
+ )
+ shell.chmod(0o755)
+ assert dse.read_login_shell_env(shell = str(shell)).get(SENTINEL) == "1"
diff --git a/studio/backend/utils/desktop_shell_env.py b/studio/backend/utils/desktop_shell_env.py
index 9c47d99bf6b..9506134efb7 100644
--- a/studio/backend/utils/desktop_shell_env.py
+++ b/studio/backend/utils/desktop_shell_env.py
@@ -3,10 +3,10 @@
"""Give the desktop app the ROCm environment a terminal launch already has.
-unsloth#9926: ``fix_path_env::fix()`` is ``fix_vars(&["PATH"])``, so src-tauri
-reads the login shell and keeps PATH out of it, dropping every ROCm variable
-beside it. Parity, not policy: only a desktop launch, only an AMD host, only
-allowlisted names that are absent here. Every other launch reads no shell.
+unsloth#9926: ``shell_path::fix_path()`` in src-tauri reads the login shell and
+keeps PATH out of it, dropping every ROCm variable beside it. Parity, not
+policy: only a desktop launch, only an AMD host, only allowlisted names that
+are absent here. Every other launch reads no shell.
"""
from __future__ import annotations
@@ -63,6 +63,25 @@ ROCM_SHELL_ENV_ALLOWLIST: tuple[str, ...] = (
)
# Not HSA_TOOLS_LIB: HSA dlopens it, which loads a library rather than tuning one.
+# Exception list, so a renamed bash/zsh still gets the unsloth#12678 probe.
+_NON_POSIX_SHELLS = frozenset(
+ {"fish", "nu", "nushell", "csh", "tcsh", "xonsh", "elvish", "pwsh", "ion", "murex"}
+)
+
+
+def probe_command(shell: str, command: str) -> str:
+ """``command`` for ``shell -ilc`` without the exit-time history save (unsloth#12678).
+
+ ``RCS`` covers zsh's readonly HISTFILE; subshell first, as dash exits on a readonly unset.
+ """
+ if os.path.basename(shell) in _NON_POSIX_SHELLS:
+ return command
+ return (
+ "if [ -n \"${ZSH_VERSION-}\" ]; then eval 'unsetopt RCS' 2>/dev/null || :; fi; "
+ f"(unset HISTFILE) 2>/dev/null && unset HISTFILE; exec {command}"
+ )
+
+
# NVIDIA's open kernel module registers KFD nodes too (4318), hence the check.
_AMD_VENDOR_ID = "4098"
@@ -117,30 +136,12 @@ def read_login_shell_env(shell: "str | None" = None, timeout: float = 15.0) -> d
shell = shell or os.environ.get("SHELL") or "/bin/sh"
with tempfile.TemporaryDirectory(prefix = "unsloth-shell-env-") as work:
target = os.path.join(work, "env")
- try:
- process = subprocess.Popen(
- [shell, "-ilc", f"env -0 > {shlex.quote(target)}"],
- stdin = subprocess.DEVNULL,
- stdout = subprocess.DEVNULL,
- stderr = subprocess.DEVNULL,
- # Oh My Zsh's auto-update prompt can block the shell forever.
- env = {**os.environ, "DISABLE_AUTO_UPDATE": "true"},
- # Its own group, so the cleanup below takes the whole shell.
- start_new_session = True,
- )
- except Exception as error:
- logger.debug("login shell environment unavailable: %s", error)
- return {}
- # pgid == pid, read before the wait reaps it: getpgid then raises.
- group = process.pid
- try:
- returncode = process.wait(timeout = timeout)
- except Exception as error:
- logger.debug("login shell did not finish: %s", error)
- returncode = None
- finally:
- # Every path: a clean exit still leaves an rc's agent running.
- _terminate_group(group, process)
+ command = f"env -0 > {shlex.quote(target)}"
+ probe = probe_command(shell, command)
+ returncode = _run_login_shell(shell, probe, timeout)
+ # A non-POSIX shell missing from the list rejects the probe; never after a timeout.
+ if returncode not in (0, None) and probe != command:
+ returncode = _run_login_shell(shell, command, timeout)
if returncode != 0:
logger.debug("login shell exited %s", returncode)
return {}
@@ -160,6 +161,34 @@ def read_login_shell_env(shell: "str | None" = None, timeout: float = 15.0) -> d
return out
+def _run_login_shell(shell: str, command: str, timeout: float) -> "int | None":
+ """``shell -ilc command``'s exit status; ``None`` if it could not start or timed out."""
+ try:
+ process = subprocess.Popen(
+ [shell, "-ilc", command],
+ stdin = subprocess.DEVNULL,
+ stdout = subprocess.DEVNULL,
+ stderr = subprocess.DEVNULL,
+ # Oh My Zsh's auto-update prompt can block the shell forever.
+ env = {**os.environ, "DISABLE_AUTO_UPDATE": "true"},
+ # Its own group, so the cleanup below takes the whole shell.
+ start_new_session = True,
+ )
+ except Exception as error:
+ logger.debug("login shell environment unavailable: %s", error)
+ return None
+ # pgid == pid, read before the wait reaps it: getpgid then raises.
+ group = process.pid
+ try:
+ return process.wait(timeout = timeout)
+ except Exception as error:
+ logger.debug("login shell did not finish: %s", error)
+ return None
+ finally:
+ # Every path: a clean exit still leaves an rc's agent running.
+ _terminate_group(group, process)
+
+
def _terminate_group(group: int, process) -> None:
"""Kill the shell's session and anything left in it. Never raises."""
try:
diff --git a/studio/src-tauri/Cargo.lock b/studio/src-tauri/Cargo.lock
index 362d22d0734..300b66ee2a9 100644
--- a/studio/src-tauri/Cargo.lock
+++ b/studio/src-tauri/Cargo.lock
@@ -1302,16 +1302,6 @@ version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
-[[package]]
-name = "fix-path-env"
-version = "0.0.0"
-source = "git+https://github.com/tauri-apps/fix-path-env-rs#c4c45d503ea115a839aae718d02f79e7c7f0f673"
-dependencies = [
- "home",
- "strip-ansi-escapes",
- "thiserror 1.0.69",
-]
-
[[package]]
name = "fixedbitset"
version = "0.5.7"
@@ -1900,15 +1890,6 @@ dependencies = [
"digest 0.11.3",
]
-[[package]]
-name = "home"
-version = "0.5.12"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d"
-dependencies = [
- "windows-sys 0.61.2",
-]
-
[[package]]
name = "html5ever"
version = "0.29.1"
@@ -5698,7 +5679,6 @@ dependencies = [
"cairo-rs",
"dirs 6.0.0",
"elevated-command",
- "fix-path-env",
"gdk",
"gdk-pixbuf",
"glib",
@@ -5722,6 +5702,7 @@ dependencies = [
"sha2 0.11.0",
"signal-hook",
"simplelog",
+ "strip-ansi-escapes",
"tauri",
"tauri-build",
"tauri-plugin-autostart",
diff --git a/studio/src-tauri/Cargo.toml b/studio/src-tauri/Cargo.toml
index 663f96476b0..18751a68cdd 100644
--- a/studio/src-tauri/Cargo.toml
+++ b/studio/src-tauri/Cargo.toml
@@ -37,7 +37,7 @@ regex = "1"
url = "2"
open = "5"
process-wrap = { version = "9", features = ["std"] }
-fix-path-env = { git = "https://github.com/tauri-apps/fix-path-env-rs" }
+strip-ansi-escapes = "0.2"
tauri-plugin-opener = "2.5.4"
tauri-plugin-updater = "2"
tauri-plugin-clipboard-manager = "2"
diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rs
index 8273d530e81..2446993eebf 100644
--- a/studio/src-tauri/src/main.rs
+++ b/studio/src-tauri/src/main.rs
@@ -31,6 +31,7 @@ mod native_path_policy;
mod preflight;
mod process;
mod process_identity;
+mod shell_path;
mod staged_update;
mod update;
mod webview_permissions;
@@ -2173,7 +2174,7 @@ fn main() {
// Fix PATH for GUI apps (macOS .app bundles, Linux AppImage, Windows)
// GUI apps don't inherit shell dotfile PATH — this spawns the user's
// login shell to source .zshrc/.bashrc/.profile and sets PATH properly.
- let _ = fix_path_env::fix();
+ shell_path::fix_path();
setup_logging();
log_panics();
diff --git a/studio/src-tauri/src/shell_path.rs b/studio/src-tauri/src/shell_path.rs
new file mode 100644
index 00000000000..19ff6b834d2
--- /dev/null
+++ b/studio/src-tauri/src/shell_path.rs
@@ -0,0 +1,289 @@
+//! PATH from the login shell for a GUI launch. Adapted from tauri-apps/fix-path-env-rs
+//! (MIT OR Apache-2.0) `fix()`, except unsloth#12678: a `-c` shell never loads $HISTFILE
+//! but saves history on exit, so the probe disables that save and `exec`s past exit hooks.
+
+const DELIMITER: &str = "_SHELL_ENV_DELIMITER_";
+
+/// Keep the old command; an exception list so a renamed bash/zsh still gets the fix.
+const NON_POSIX_SHELLS: &[&str] = &[
+ "fish", "nu", "nushell", "csh", "tcsh", "xonsh", "elvish", "pwsh", "ion", "murex",
+];
+
+#[cfg_attr(windows, allow(dead_code))]
+fn env_command() -> String {
+ format!("echo -n \"{DELIMITER}\"; env; echo -n \"{DELIMITER}\"; exit")
+}
+
+#[cfg_attr(windows, allow(dead_code))]
+fn probe_command(shell: &str) -> String {
+ let name = std::path::Path::new(shell)
+ .file_name()
+ .and_then(|name| name.to_str())
+ .unwrap_or("");
+ if NON_POSIX_SHELLS.contains(&name) {
+ return env_command();
+ }
+ // RCS covers zsh's readonly HISTFILE; subshell first: dash exits on a readonly unset.
+ format!(
+ "if [ -n \"${{ZSH_VERSION-}}\" ]; then eval 'unsetopt RCS' 2>/dev/null || :; fi; \
+ (unset HISTFILE) 2>/dev/null && unset HISTFILE; \
+ exec /bin/sh -c 'printf \"%s\" \"{DELIMITER}\"; env; printf \"%s\" \"{DELIMITER}\"'"
+ )
+}
+
+#[cfg(test)]
+fn path_from_output(stdout: &[u8]) -> Option<String> {
+ env_block_path(stdout)?
+}
+
+/// `None` when there is no delimited block (the shell did not run the command),
+/// `Some(None)` when it ran but printed no PATH.
+#[cfg_attr(windows, allow(dead_code))]
+fn env_block_path(stdout: &[u8]) -> Option<Option<String>> {
+ let stdout = String::from_utf8_lossy(stdout);
+ let env = stdout.split(DELIMITER).nth(1)?;
+ let env = strip_ansi_escapes::strip(env);
+ Some(
+ String::from_utf8_lossy(&env)
+ .split('\n')
+ .filter_map(|line| line.strip_prefix("PATH=").map(str::to_owned))
+ .last(),
+ )
+}
+
+/// `None` when the shell rejected `command`; `Some(None)` when it ran without PATH.
+#[cfg(not(windows))]
+fn read_login_shell_path(shell: &str, command: &str) -> Option<Option<String>> {
+ let mut cmd = std::process::Command::new(shell);
+ cmd.arg("-ilc")
+ .arg(command)
+ // Oh My Zsh's auto-update prompt can block the shell forever.
+ .env("DISABLE_AUTO_UPDATE", "true");
+ if let Some(home) = dirs::home_dir() {
+ cmd.current_dir(home);
+ }
+ let out = cmd.output().ok()?;
+ if !out.status.success() {
+ return None;
+ }
+ env_block_path(&out.stdout)
+}
+
+/// Old command only if the shell rejected the probe (Plan 9 rc, a renamed fish); a probe
+/// that ran without PATH (`export -n PATH`) must not rerun the history-rewriting one.
+#[cfg(not(windows))]
+fn login_shell_path(shell: &str) -> Option<String> {
+ let probe = probe_command(shell);
+ match read_login_shell_path(shell, &probe) {
+ Some(path) => path,
+ None if probe != env_command() => read_login_shell_path(shell, &env_command()).flatten(),
+ None => None,
+ }
+}
+
+/// Best effort: on any failure PATH stays as the process inherited it.
+pub fn fix_path() {
+ #[cfg(windows)]
+ {
+ // std::process::Command can miss a GUI app's PATH until it is set again.
+ if let Ok(path) = std::env::var("PATH") {
+ std::env::set_var("PATH", path);
+ }
+ }
+ #[cfg(not(windows))]
+ {
+ let default_shell = if cfg!(target_os = "macos") {
+ "/bin/zsh"
+ } else {
+ "/bin/sh"
+ };
+ let shell = std::env::var("SHELL").unwrap_or_else(|_| default_shell.into());
+ if let Some(path) = login_shell_path(&shell) {
+ std::env::set_var("PATH", path);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn posix_shells_unset_histfile_first() {
+ for shell in [
+ "/bin/zsh",
+ "/bin/bash",
+ "/opt/homebrew/bin/bash",
+ "/bin/sh",
+ "dash",
+ "/usr/local/bin/zsh5",
+ "/opt/bash-5.2/bin/bash-5.2",
+ ] {
+ assert!(
+ probe_command(shell)
+ .contains("(unset HISTFILE) 2>/dev/null && unset HISTFILE; exec "),
+ "{shell}"
+ );
+ }
+ for shell in ["/opt/homebrew/bin/fish", "/usr/bin/nu", "/bin/tcsh"] {
+ assert_eq!(probe_command(shell), env_command(), "{shell}");
+ }
+ }
+
+ #[test]
+ fn path_comes_from_between_the_delimiters() {
+ let out = format!(
+ "motd PATH=/rc/noise\n{DELIMITER}HOME=/h\nPATH=/a:/b=c\n\x1b[0mX=1\n{DELIMITER}"
+ );
+ assert_eq!(path_from_output(out.as_bytes()).as_deref(), Some("/a:/b=c"));
+ assert_eq!(path_from_output(b"no delimiter"), None);
+ }
+
+ /// A shell that cannot parse the probe still yields PATH through the old command.
+ #[cfg(not(windows))]
+ #[test]
+ fn a_shell_rejecting_the_probe_falls_back() {
+ use std::os::unix::fs::PermissionsExt;
+ let dir = std::env::temp_dir().join(format!("unsloth-12678-fb-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let shell = dir.join("notposix");
+ std::fs::write(
+ &shell,
+ "#!/bin/sh\ncase \"$2\" in if*) exit 2 ;; esac\nPATH=/from/fallback:$PATH exec /bin/sh -c \"$2\"\n",
+ )
+ .unwrap();
+ std::fs::set_permissions(&shell, std::fs::Permissions::from_mode(0o755)).unwrap();
+ let shell = shell.to_str().unwrap();
+ assert_eq!(read_login_shell_path(shell, &probe_command(shell)), None);
+ assert_eq!(read_login_shell_path(shell, "true"), None);
+ let path = login_shell_path(shell).unwrap_or_default();
+ let _ = std::fs::remove_dir_all(&dir);
+ assert!(path.starts_with("/from/fallback:"), "{path:?}");
+ }
+
+ /// A probe that ran without PATH (`export -n PATH`) is not retried with the old command.
+ #[cfg(not(windows))]
+ #[test]
+ fn a_probe_without_path_is_not_retried() {
+ use std::os::unix::fs::PermissionsExt;
+ let dir = std::env::temp_dir().join(format!("unsloth-12678-np-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let shell = dir.join("nopath");
+ std::fs::write(
+ &shell,
+ format!("#!/bin/sh\necho run >> \"$0.calls\"\nprintf %s {DELIMITER}X=1{DELIMITER}\n"),
+ )
+ .unwrap();
+ std::fs::set_permissions(&shell, std::fs::Permissions::from_mode(0o755)).unwrap();
+ let path = login_shell_path(shell.to_str().unwrap());
+ let calls = std::fs::read_to_string(dir.join("nopath.calls")).unwrap_or_default();
+ let _ = std::fs::remove_dir_all(&dir);
+ assert_eq!(path, None);
+ assert_eq!(calls.lines().count(), 1, "{calls:?}");
+ }
+
+ #[cfg(not(windows))]
+ fn run_probe_in(home: &std::path::Path, shell: &str, command: &str) -> Option<String> {
+ let out = std::process::Command::new(shell)
+ .arg("-ilc")
+ .arg(command)
+ .env_clear()
+ .env("HOME", home)
+ .env("ZDOTDIR", home)
+ .env("PATH", "/usr/bin:/bin")
+ .current_dir(home)
+ .output()
+ .ok()?;
+ out.status
+ .success()
+ .then(|| path_from_output(&out.stdout))
+ .flatten()
+ }
+
+ /// unsloth#12678 against real shells: the old command loses the history, this one keeps it.
+ #[cfg(not(windows))]
+ #[test]
+ fn reading_path_leaves_the_history_file_alone() {
+ const ZSH: &str = "HISTFILE=$HOME/.zsh_history\nHISTSIZE=2000\nSAVEHIST=1000\n\
+ unsetopt APPEND_HISTORY\nprint -s plugin-entry\n";
+ const BASH: &str = "HISTSIZE=100000\nHISTFILESIZE=100000\nhistory -s plugin-entry\n";
+ // (shell, rc file, history file, rc body, extra file)
+ let cases = [
+ (
+ "bash",
+ ".bash_profile",
+ ".bash_history",
+ BASH.to_string(),
+ None,
+ ),
+ (
+ "bash",
+ ".bash_profile",
+ ".bash_history",
+ format!("{BASH}trap 'history -w ~/.bash_history' EXIT\n"),
+ None,
+ ),
+ ("zsh", ".zshrc", ".zsh_history", ZSH.to_string(), None),
+ (
+ "zsh",
+ ".zshrc",
+ ".zsh_history",
+ ZSH.to_string(),
+ Some((".zlogout", "fc -W $HOME/.zsh_history\n")),
+ ),
+ // Readonly HISTFILE: RCS still stops the save; the failed unset must not abort.
+ (
+ "zsh",
+ ".zshrc",
+ ".zsh_history",
+ format!("{ZSH}typeset -r HISTFILE SAVEHIST\nsetopt ERR_EXIT\n"),
+ None,
+ ),
+ ];
+ let history: String = (0..3000).map(|i| format!("echo history-{i}\n")).collect();
+ let nanos = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos();
+ let root =
+ std::env::temp_dir().join(format!("unsloth-12678-{}-{nanos}", std::process::id()));
+ std::fs::create_dir(&root).unwrap();
+ let mut ran = 0;
+ for (index, (shell, rc, hist, body, extra)) in cases.into_iter().enumerate() {
+ let Some(shell) = ["/bin", "/usr/bin", "/usr/local/bin", "/opt/homebrew/bin"]
+ .iter()
+ .map(|dir| format!("{dir}/{shell}"))
+ .find(|path| std::path::Path::new(path).exists())
+ else {
+ eprintln!("{shell} not installed, skipped");
+ continue;
+ };
+ ran += 1;
+ for (arm, command) in [("before", env_command()), ("after", probe_command(&shell))] {
+ let home = root.join(format!("{arm}-{index}"));
+ std::fs::create_dir_all(&home).unwrap();
+ std::fs::write(home.join(rc), format!("export PATH=/from/rc:$PATH\n{body}"))
+ .unwrap();
+ if let Some((name, text)) = extra {
+ std::fs::write(home.join(name), text).unwrap();
+ }
+ std::fs::write(home.join(hist), &history).unwrap();
+ let path = run_probe_in(&home, &shell, &command).unwrap_or_default();
+ let kept = std::fs::read_to_string(home.join(hist)).unwrap() == history;
+ assert_eq!(
+ kept,
+ arm == "after",
+ "case {index} ({shell}) {arm}: kept = {kept}"
+ );
+ if arm == "after" {
+ assert!(
+ path.starts_with("/from/rc:"),
+ "case {index} ({shell}): {path:?}"
+ );
+ }
+ }
+ }
+ let _ = std::fs::remove_dir_all(&root);
+ assert!(ran > 0, "no POSIX shell found to test against");
+ }
+}