Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(agent): reliable bash on Windows + working TUI scrollback for the terminal scroll wheel (#8692)

Akarshan Biswasd1d5d47ed439
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
index 9f07cc7ab..fb20e5cb3 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
@@ -714,6 +714,10 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {
let (tx, mut rx) = oneshot::channel();
let spill_scratch = ctx.scratch_root.map(Path::to_path_buf);
let sandboxed = ctx.sandbox;
+ // The model writes POSIX commands by default, which `cmd` rejects. Surface
+ // the resolved shell so it can adapt when the only shell on a Windows box
+ // is cmd, instead of the tool silently presenting cmd as bash.
+ let shell_description = shell.description;
tokio::spawn(async move {
let mut out = collect_and_format(child, spill_scratch).await;
// Appended inside the task so a backgrounded job carries the hint too.
@@ -724,6 +728,14 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {
if sandboxed && bash_result_failed(&out) && jail::looks_denied(&out) {
out.push_str(&jail::denial_hint(&policy));
}
+ if shell_description == "cmd" {
+ out.insert_str(
+ 0,
+ "[shell: cmd.exe - no bash is installed. Write commands in cmd syntax \
+ (e.g. `dir`, `type`, `set`, `mkdir`, `%VAR%` for variables), not \
+ POSIX/bash. Alternatively install git-bash and this tool will use it.]\n",
+ );
+ }
if let Some(pid) = pid {
proc::unregister(pid);
}
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs
index f25f24fe2..94c6c29e2 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs
@@ -228,11 +228,13 @@ pub fn wrap(cfg: &ShellConfig, policy: &Policy) -> Option<ShellConfig> {
program: bwrap_path()?,
args: bwrap_args(policy, cfg),
via_stdin: cfg.via_stdin,
+ description: cfg.description,
}),
Backend::Seatbelt => Some(ShellConfig {
program: PathBuf::from(seatbelt_program()),
args: seatbelt_args(policy, cfg),
via_stdin: cfg.via_stdin,
+ description: cfg.description,
}),
// AppContainer is a token attribute on the spawn rather than an argv
// prefix, and `tokio::process::Command` cannot set one, so the wrapper is
@@ -249,6 +251,7 @@ pub fn wrap(cfg: &ShellConfig, policy: &Policy) -> Option<ShellConfig> {
&cfg.args,
),
via_stdin: cfg.via_stdin,
+ description: cfg.description,
}),
Backend::None => None,
}
@@ -585,6 +588,7 @@ mod tests {
program: PathBuf::from("/bin/bash"),
args: vec!["-c".to_string()],
via_stdin: false,
+ description: "bash",
}
}
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs
index 6b1083f40..62d654136 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs
@@ -14,11 +14,15 @@ use tokio::process::{Child, Command};
/// How to invoke the host shell. `program` + `args` are fixed; the command
/// string is appended as the final argv element, or piped to stdin when
/// `via_stdin` is set (legacy WSL `bash.exe`, which cannot take `-c`).
+/// `description` names the shell for the model (e.g. git-bash vs `cmd`), so it
+/// can adapt command syntax instead of assuming POSIX bash.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShellConfig {
pub program: PathBuf,
pub args: Vec<String>,
pub via_stdin: bool,
+ /// A short human-readable name of the resolved shell, for the model.
+ pub description: &'static str,
}
/// Resolved shell for this process, computed once. Prefers a real `bash`
@@ -29,11 +33,12 @@ pub fn shell() -> &'static ShellConfig {
SHELL.get_or_init(resolve_shell)
}
-fn c(program: &str, args: &[&str]) -> ShellConfig {
+fn c(program: &str, args: &[&str], description: &'static str) -> ShellConfig {
ShellConfig {
program: PathBuf::from(program),
args: args.iter().map(|s| s.to_string()).collect(),
via_stdin: false,
+ description,
}
}
@@ -45,6 +50,7 @@ fn resolve_shell() -> ShellConfig {
program: p,
args: vec!["-c".to_string()],
via_stdin: false,
+ description: "custom",
};
}
}
@@ -62,15 +68,20 @@ fn resolve_shell() -> ShellConfig {
program: p,
args: vec!["-c".to_string()],
via_stdin: false,
+ description: "bash",
};
}
if Path::new("/bin/bash").exists() {
- return c("/bin/bash", &["-c"]);
+ return c("/bin/bash", &["-c"], "bash");
}
- c("/bin/sh", &["-c"])
+ c("/bin/sh", &["-c"], "sh")
}
#[cfg(windows)]
{
+ // Prefer a real bash before ever falling back to cmd, so POSIX command
+ // syntax keeps working. Check the standard git-bash/msys install
+ // locations under the well-known program dirs first, then `bash` on
+ // PATH.
for var in ["ProgramFiles", "ProgramFiles(x86)", "ProgramW6432"] {
if let Some(base) = std::env::var_os(var) {
let git_bash = PathBuf::from(base).join("Git").join("bin").join("bash.exe");
@@ -79,31 +90,47 @@ fn resolve_shell() -> ShellConfig {
program: git_bash,
args: vec!["-c".to_string()],
via_stdin: false,
+ description: "git-bash",
};
}
}
}
if let Some(p) = which("bash") {
- // System32\bash.exe is the WSL launcher: it rejects `-c`, so the
- // command must be piped to `bash -s` on stdin instead.
+ // The WSL launcher is the shim at System32\bash.exe; it rejects
+ // `-c`, so the command must be piped to `bash -s` on stdin. Only
+ // that exact location is treated as WSL, so a real bash that merely
+ // lives under a directory named `system32` is not misrouted to
+ // stdin one-shot mode.
let is_wsl = p
- .to_string_lossy()
- .to_lowercase()
- .contains("system32");
+ .file_name()
+ .and_then(|n| n.to_str())
+ .map(|n| n.eq_ignore_ascii_case("bash.exe"))
+ .unwrap_or(false)
+ && p.parent()
+ .and_then(|d| d.file_name())
+ .and_then(|n| n.to_str())
+ .map(|n| n.eq_ignore_ascii_case("System32"))
+ .unwrap_or(false);
if is_wsl {
return ShellConfig {
program: p,
args: vec!["-s".to_string()],
via_stdin: true,
+ description: "wsl bash",
};
}
return ShellConfig {
program: p,
args: vec!["-c".to_string()],
via_stdin: false,
+ description: "bash",
};
}
- c("cmd.exe", &["/C"])
+ // No bash anywhere: cmd is the only shell. The model is told this (the
+ // runtime env block reports COMSPEC, and the bash handler's output note
+ // names cmd) so it can write cmd syntax rather than silently passing
+ // POSIX commands that cmd would reject.
+ c("cmd.exe", &["/C"], "cmd")
}
}
@@ -135,7 +162,25 @@ pub(crate) fn which(name: &str) -> Option<PathBuf> {
/// `JAN_DATA_FOLDER` -- so the shell is launched with only what a command needs
/// to run at all. Applied here, the one choke point all backends (bubblewrap,
/// seatbelt, and the Windows AppContainer helper) funnel through.
-const SANDBOX_ENV_ALLOW: &[&str] = &["PATH", "HOME", "USERPROFILE", "TMPDIR", "TMP", "TEMP", "LANG", "TERM"];
+const SANDBOX_ENV_ALLOW: &[&str] = &[
+ "PATH",
+ "HOME",
+ "USERPROFILE",
+ "TMPDIR",
+ "TMP",
+ "TEMP",
+ "LANG",
+ "TERM",
+ // Windows processes (cmd, and the cygwin/git-bash and MSYS runtimes) need
+ // the system location keys to find system DLLs, `cmd.exe` itself, and run
+ // `.bat`/`.cmd` helpers. Harmless no-ops on unix, where none are set.
+ "SystemRoot",
+ "windir",
+ "ComSpec",
+ "PATHEXT",
+ "ProgramFiles",
+ "ProgramData",
+];
/// Every spelling of "where temporary files go": POSIX tools read `TMPDIR`,
/// Windows ones `TEMP`/`TMP`, and a mixed toolchain (git-bash, MSYS) reads both.
@@ -292,6 +337,25 @@ pub fn kill_all() {
}
}
+#[cfg(test)]
+mod env_allowlist_tests {
+ use super::*;
+
+ /// Windows-native processes (cmd, plus the cygwin/git-bash and MSYS
+ /// runtimes) need the system-location keys to find DLLs and `cmd.exe`
+ /// itself. These are the keys the ticket adds; assert they stay present so
+ /// a bare Windows box can actually run a command.
+ #[test]
+ fn allowlist_has_windows_system_keys() {
+ for key in ["SystemRoot", "windir", "ComSpec", "PATHEXT", "ProgramFiles", "ProgramData"] {
+ assert!(
+ SANDBOX_ENV_ALLOW.contains(&key),
+ "missing {key} in SANDBOX_ENV_ALLOW"
+ );
+ }
+ }
+}
+
#[cfg(all(test, unix))]
mod tests {
use super::*;
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index de98f6762..104860222 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -64,6 +64,30 @@ const MOUSE_TRACK_ON: &str = "\x1b[?1000h\x1b[?1002h\x1b[?1006h";
const ALT_SCROLL_SAVE_OFF: &str = "\x1b[?1007s\x1b[?1007l";
const ALT_SCROLL_RESTORE: &str = "\x1b[?1007r";
+/// Whether to hand the wheel to the terminal's native alternate-scroll instead
+/// of asking it to report wheel events to the app. Disabling alternate scroll
+/// (`?1007l`) makes an xterm-family terminal deliver the wheel as SGR mouse
+/// reports for the app to turn into scrollback. Windows Terminal accepts the
+/// mode but does not do the same: with it forced off the wheel goes dead in the
+/// alternate buffer, so there the app keeps `?1000h` SGR mouse as the sole wheel
+/// path and leaves alternate scroll alone. Same decision on save/restore, so
+/// the pair is always balanced.
+fn alt_scroll_save_off() -> &'static str {
+ if cfg!(windows) {
+ ""
+ } else {
+ ALT_SCROLL_SAVE_OFF
+ }
+}
+
+fn alt_scroll_restore() -> &'static str {
+ if cfg!(windows) {
+ ""
+ } else {
+ ALT_SCROLL_RESTORE
+ }
+}
+
/// How long the dock advertises a finished copy.
const COPY_NOTICE: Duration = Duration::from_millis(1500);
/// Terminals cap the OSC 52 payload they will accept; past this the sequence is
@@ -4882,7 +4906,7 @@ pub async fn run(
enable_raw_mode().map_err(|e| e.to_string())?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen, EnableBracketedPaste).map_err(|e| e.to_string())?;
- let mut modes = String::from(ALT_SCROLL_SAVE_OFF);
+ let mut modes = String::from(alt_scroll_save_off());
if crate::core::agent::global_config::mouse_enabled() {
modes.push_str(MOUSE_TRACK_ON);
}
@@ -4972,7 +4996,7 @@ pub async fn run(
terminal.backend_mut(),
DisableBracketedPaste,
DisableMouseCapture,
- Print(ALT_SCROLL_RESTORE),
+ Print(alt_scroll_restore()),
LeaveAlternateScreen,
);
let _ = terminal.show_cursor();
@@ -10485,7 +10509,7 @@ mod tests {
SnapshotJob, Status, AGENT_SETTINGS, ALT_SCROLL_RESTORE, ALT_SCROLL_SAVE_OFF,
COMMAND_LABEL_MAX, DIFF_ADD_BG, DIFF_DEL_BG, DIFF_MAX_ROWS, DIFF_PREVIEW_MAX_ROWS,
KEY_BINDINGS, MOUSE_TRACK_ON, SLASH_COMMANDS, SPINNER,
- SPINNER_ADVANCE_MS,
+ SPINNER_ADVANCE_MS, alt_scroll_restore, alt_scroll_save_off,
};
use crate::core::agent::events::{StreamEvent, Usage};
use crate::core::agent::r#loop::PermissionRegistry;
@@ -15110,6 +15134,21 @@ mod tests {
assert!(ALT_SCROLL_RESTORE.contains("?1007r"), "restore on exit");
}
+ #[test]
+ fn alt_scroll_is_disabled_only_where_the_terminal_reports_wheel() {
+ // The app keeps native alternate scroll (i.e. sends nothing) on Windows,
+ // where forcing `?1007l` kills the wheel; everywhere else it disables it
+ // so the wheel arrives as SGR mouse reports. The save/off and restore
+ // pair must always agree so the mode is left balanced on exit.
+ if cfg!(windows) {
+ assert_eq!(alt_scroll_save_off(), "", "Windows must not disable alt scroll");
+ assert_eq!(alt_scroll_restore(), "", "Windows must not restore alt scroll");
+ } else {
+ assert_eq!(alt_scroll_save_off(), ALT_SCROLL_SAVE_OFF);
+ assert_eq!(alt_scroll_restore(), ALT_SCROLL_RESTORE);
+ }
+ }
+
#[test]
fn linear_selection_spans_whole_rows_between_the_ends() {
let sel = Selection {