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-tools): keep Windows sandboxed shell output clean and `..` honest

thinhlpgb6877ca43424
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 14fc8f574..ae3fb7893 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
@@ -1709,6 +1709,7 @@ async fn collect_and_format(
let mut be = vec![0u8; 8192];
let mut out_open = stdout.is_some();
let mut err_open = stderr.is_some();
+ let mut startup = proc::StderrStartupFilter::default();
// A read boundary can land mid-character, so decoding each chunk on its own
// would emit a replacement character for any multi-byte sequence unlucky
// enough to straddle one. Hold the incomplete tail back for the next chunk.
@@ -1744,8 +1745,17 @@ async fn collect_and_format(
}
},
r = stderr.as_mut().unwrap().read(&mut be), if err_open => match r {
- Ok(0) | Err(_) => err_open = false,
- Ok(n) => { cap.push(&be[..n]); tee(&be[..n], &mut carry); }
+ Ok(0) | Err(_) => {
+ err_open = false;
+ let held = startup.finish();
+ cap.push(&held);
+ tee(&held, &mut carry);
+ }
+ Ok(n) => {
+ let shown = startup.feed(&be[..n]);
+ cap.push(&shown);
+ tee(&shown, &mut carry);
+ }
},
}
}
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 0c6069f45..a4fc8aa20 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
@@ -197,9 +197,14 @@ const POWERSHELL_CORE_ASSEMBLIES: &str = "'Microsoft.PowerShell.Commands.Managem
/// the path; relative paths, `Get-ChildItem` and, on 5.1, every external
/// program then fail. The session first moves to the process's working
/// directory by its real path. Only if that is refused does it fall back to
-/// a `JanWs:` drive rooted there, which needs no parent access, so the drive
-/// is never used where a real path works. Under the drive, `$PWD` and
-/// `Resolve-Path` read `JanWs:\...`, which a native program cannot open;
+/// a `JanWs:` drive, which needs no parent access, so the drive is never
+/// used where a real path works. The drive is rooted at the workspace's
+/// parent, not the workspace: a drive root's `..` is the root itself, so
+/// rooted at the workspace `..\x` silently wrote into the workspace and
+/// reported success. From the parent, `..` names the real parent and the
+/// container's write there is refused. Only a workspace that is itself a
+/// drive root, with no parent, gets the drive at the workspace. Under the
+/// drive, `$PWD` and `Resolve-Path` read `JanWs:\...`, which a native program cannot open;
/// [`ShellKind::syntax_note`] tells the model to pass `Convert-Path` output
/// instead, which is the real path.
///
@@ -214,7 +219,7 @@ pub fn powershell_script(command: &str) -> String {
try {{ [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) }} catch {{}}\n\
$OutputEncoding = [System.Text.UTF8Encoding]::new($false)\n\
$JanWs = [Environment]::CurrentDirectory\n\
- try {{ Set-Location -LiteralPath $JanWs -ErrorAction Stop }} catch {{ try {{ $null = New-PSDrive -Name JanWs -PSProvider FileSystem -Root $JanWs -Scope Global -ErrorAction Stop; Set-Location JanWs:\\ }} catch {{}} }}\n\
+ try {{ Set-Location -LiteralPath $JanWs -ErrorAction Stop }} catch {{ try {{ $JanUp = [System.IO.Path]::GetDirectoryName($JanWs); if (-not $JanUp) {{ throw 'drive root' }}; $null = New-PSDrive -Name JanWs -PSProvider FileSystem -Root $JanUp -Scope Global -ErrorAction Stop; Set-Location -LiteralPath ('JanWs:\\' + [System.IO.Path]::GetFileName($JanWs)) -ErrorAction Stop }} catch {{ try {{ Remove-PSDrive -Name JanWs -Scope Global -ErrorAction SilentlyContinue; $null = New-PSDrive -Name JanWs -PSProvider FileSystem -Root $JanWs -Scope Global -ErrorAction Stop; Set-Location JanWs:\\ }} catch {{}} }} }}\n\
$global:LASTEXITCODE = $null\n\
$JanExit = $null\n\
function jan_cmd {{\n\
@@ -227,6 +232,66 @@ pub fn powershell_script(command: &str) -> String {
)
}
+/// What Windows PowerShell prints on stderr when its FileSystem provider cannot
+/// open a drive root, which inside the AppContainer is every start: the token
+/// cannot read `C:\`. It is printed while the runspace opens, before the
+/// script runs, so nothing in [`powershell_script`] can stop it, and it says
+/// nothing about the command. Left in, it led every result and models read it
+/// as the command failing.
+const POWERSHELL_DRIVE_NOISE: &[u8] =
+ b"Attempting to perform the InitializeDefaultDrives operation on the 'FileSystem' provider failed.";
+
+/// Drops [`POWERSHELL_DRIVE_NOISE`] from the start of a shell's stderr and
+/// passes everything else through unchanged. Only the first line is held back,
+/// and only until it is complete, so a command's own errors are never touched
+/// and arrive no later than the line after it.
+#[derive(Default)]
+pub struct StderrStartupFilter {
+ pending: Vec<u8>,
+ decided: bool,
+}
+
+impl StderrStartupFilter {
+ /// The bytes of `chunk` that belong in the output.
+ pub fn feed(&mut self, chunk: &[u8]) -> Vec<u8> {
+ if self.decided {
+ return chunk.to_vec();
+ }
+ self.pending.extend_from_slice(chunk);
+ match self.pending.iter().position(|&b| b == b'\n') {
+ Some(end) => self.decide(end + 1),
+ // A first line longer than the noise cannot be the noise.
+ None if self.pending.len() > POWERSHELL_DRIVE_NOISE.len() + 2 => {
+ self.decided = true;
+ std::mem::take(&mut self.pending)
+ }
+ None => Vec::new(),
+ }
+ }
+
+ /// Whatever is still held once the stream ends.
+ pub fn finish(&mut self) -> Vec<u8> {
+ if self.decided {
+ return Vec::new();
+ }
+ let end = self.pending.len();
+ self.decide(end)
+ }
+
+ fn decide(&mut self, line_end: usize) -> Vec<u8> {
+ self.decided = true;
+ let mut rest = std::mem::take(&mut self.pending);
+ let mut line = &rest[..line_end];
+ while let [head @ .., b'\r' | b'\n' | b' '] = line {
+ line = head;
+ }
+ if line == POWERSHELL_DRIVE_NOISE {
+ rest.drain(..line_end);
+ }
+ rest
+ }
+}
+
/// The text appended, unescaped, after [`CMD_ARGS`]. cmd does its own quote
/// handling rather than the `CommandLineToArgvW` rules every argv quoter
/// follows, so an escaped `\"` reaches it literally; the command is wrapped in
@@ -1332,6 +1397,25 @@ mod shell_kind_tests {
assert!(rest.contains("$host.SetShouldExit($JanExit)"), "exit without dropping output");
}
+ /// Only PowerShell's drive complaint, as the whole first line, is dropped:
+ /// however the pipe splits it, and never a command's own error.
+ #[test]
+ fn stderr_filter_drops_only_the_startup_drive_line() {
+ let run = |chunks: &[&[u8]]| {
+ let mut f = StderrStartupFilter::default();
+ let mut out: Vec<u8> = chunks.iter().flat_map(|c| f.feed(c)).collect();
+ out.extend(f.finish());
+ String::from_utf8(out).unwrap()
+ };
+ let noise = [POWERSHELL_DRIVE_NOISE, b"\r\n"].concat();
+ assert_eq!(run(&[&noise]), "");
+ assert_eq!(run(&[&noise[..20], &noise[20..], b"real error\r\n"]), "real error\r\n");
+ assert_eq!(run(&[POWERSHELL_DRIVE_NOISE]), "", "no trailing newline");
+ assert_eq!(run(&[b"boom\n", &noise]), format!("boom\n{}", String::from_utf8_lossy(&noise)));
+ assert_eq!(run(&[b"fatal: ", b"not a repo\n"]), "fatal: not a repo\n");
+ assert_eq!(run(&[b"partial"]), "partial");
+ }
+
/// The syntax note names the language for every non-POSIX shell and is
/// absent for POSIX, which the model already assumes.
#[test]
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/tests/sandbox_spawn.rs b/src-tauri/plugins/tauri-plugin-agent-tools/tests/sandbox_spawn.rs
index 86cb89b23..53b98c692 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/tests/sandbox_spawn.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/tests/sandbox_spawn.rs
@@ -113,6 +113,26 @@ mod windows {
for name in ["rel-a.txt", "rel-b.txt", "rel-c.txt"] {
assert!(ws.join(name).is_file(), "{name} must be written inside the workspace");
}
+ // `..` is the workspace's parent, which the container cannot write:
+ // the write must fail rather than land in the workspace and report
+ // success.
+ for (label, shell) in &shells[..2] {
+ let (code, out) =
+ rt.block_on(spawn_code(shell, &ws, "Set-Content -Path ..\\up.txt -Value x"));
+ assert_ne!(code, Some(0), "{label}: a write to .. must fail: {out}");
+ assert!(!ws.join("up.txt").exists(), "{label}: .. resolved to the workspace: {out}");
+ // The working directory is still the workspace, by its real path.
+ let (_, out) = rt.block_on(spawn_code(shell, &ws, "Convert-Path ."));
+ let real = proc::without_verbatim_prefix(&ws.canonicalize().unwrap());
+ assert!(
+ out.lines().any(|l| l
+ .trim()
+ .trim_end_matches('\\')
+ .eq_ignore_ascii_case(&real.to_string_lossy())),
+ "{label}: the shell must start in {}: {out}",
+ real.display()
+ );
+ }
// An error names the command, never the wrapper script around it.
for (label, shell) in &shells[..2] {
let (ok, out) = rt.block_on(spawn(shell, &ws, "Write-Error boom; exit 2"));
@@ -197,6 +217,14 @@ mod shell_tool {
);
}
+ // PowerShell's start-up complaint that it cannot open the drive roots
+ // is not the command's output: the model read it as every command
+ // failing. A command's own error still comes through.
+ let out = shell("echo clean", json!({}));
+ assert!(!out.contains("InitializeDefaultDrives"), "start-up noise kept: {out}");
+ let out = shell("Write-Error own-error", json!({}));
+ assert!(out.contains("own-error"), "the command's own stderr was lost: {out}");
+
// handlers::tests::bash_success_emits_exit_0_marker
let out = shell("echo done", json!({}));
assert!(!out.starts_with("ERROR"), "unexpected: {out}");