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
//! Test-only OS helpers — one place where "and how does that work on Windows"
//! is answered for the whole crate.
//!
//! Nothing here ships: the module is `#[cfg(test)]` in `lib.rs`.
//!
//! It exists because the process-level tests — `state.rs` (the quit path),
//! `commands/engine.rs` (the health wait) and `commands/bg_tasks.rs`
//! (cancel, quit sweep, working directory) — all need the same four things
//! from the OS: a shell that runs a POSIX one-liner, a child that stays alive
//! while the test works, an answer to "is this pid still a process", and the
//! children a process started. Each of them used to spell those out in Unix
//! terms only (`sh`, `sleep`, `ps -o state=`), which is why eight of them were
//! switched off on Windows — that is, on the platform whose process handling
//! differs the most from the one they were written on, and where being
//! untested is worth the least.
//!
//! Everything below is compiled on every platform (`if cfg!(windows)`, not
//! `#[cfg(windows)]`), so the Windows half at least type-checks in a macOS
//! `cargo test` run and the pure parts of the resolver are unit-tested at the
//! bottom of this file.
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::OnceLock;
const BASH_EXE: &str = "bash.exe";
// ── The shell ─────────────────────────────────────────────────────────────
/// A shell that can run the POSIX one-liners these tests are written in.
///
/// Unix: `sh`, exactly as before.
///
/// Windows: the bash that Git for Windows installs. A bare `bash` is NOT
/// usable there, and that is the whole reason this function exists: on a
/// stock Windows 10/11 the PATH resolves `bash` to
/// `%LOCALAPPDATA%\Microsoft\WindowsApps\bash.exe` — the WSL
/// app-execution-alias stub, a zero-length reparse point. `where bash` prints
/// it and every existence check says yes to it, but with no WSL distro
/// registered CreateProcess refuses it outright, so the spawn dies before a
/// shell is ever reached. Git for Windows always installs a real bash next to
/// git, so that one is resolved deterministically and every WindowsApps
/// candidate is dropped on the floor *before* it is even checked for
/// existence.
///
/// This is the Rust twin of `src/api/__tests__/bash-interpreter.ts`, which
/// solved the same problem for the vitest side; same sources, same order.
pub(crate) fn posix_shell() -> String {
static RESOLVED: OnceLock<String> = OnceLock::new();
RESOLVED
.get_or_init(|| {
if !cfg!(windows) {
return "sh".to_string();
}
let candidates = windows_bash_candidates();
match candidates.iter().find(|c| is_usable_bash(c)) {
Some(found) => found.clone(),
None => panic!("{}", no_bash_message(&candidates)),
}
})
.clone()
}
/// `...\WindowsApps\bash.exe` is the WSL alias stub — never an actual shell.
fn is_wsl_alias_stub(candidate: &str) -> bool {
let lower = candidate.to_ascii_lowercase().replace('/', "\\");
lower.contains("\\windowsapps\\")
}
/// The stub filter runs BEFORE the existence check, on purpose: the stub is a
/// file as far as the file system is concerned, so checking first would let it
/// win.
fn is_usable_bash(candidate: &str) -> bool {
!is_wsl_alias_stub(candidate) && Path::new(candidate).is_file()
}
/// `where <program>` on Windows: one absolute path per line, and no lines at
/// all when the program is not on PATH. Off Windows there is no `where`
/// executable, the spawn fails, and the caller gets an empty list — which is
/// correct, because nothing off Windows asks.
fn where_on_path(program: &str) -> Vec<String> {
let out = match Command::new("where").arg(program).output() {
Ok(o) if o.status.success() => o.stdout,
_ => return Vec::new(),
};
String::from_utf8_lossy(&out)
.lines()
.map(|l| l.trim().to_string())
.filter(|l| !l.is_empty())
.collect()
}
/// The documented install roots, for a git that is not on PATH at all.
fn program_roots() -> Vec<PathBuf> {
let mut roots = Vec::new();
for var in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(v) = std::env::var_os(var) {
roots.push(PathBuf::from(v));
}
}
if let Some(local) = std::env::var_os("LOCALAPPDATA") {
roots.push(PathBuf::from(local).join("Programs"));
}
roots
}
fn windows_bash_candidates() -> Vec<String> {
build_candidates(
&where_on_path("git"),
&program_roots(),
&where_on_path("bash"),
)
}
/// Every place a real bash could be, most trustworthy first. Nothing in here
/// is machine specific: git's own location is the primary source, the install
/// roots are the fallback, and PATH comes last — after the stub filter, so a
/// WSL alias can never win just because it happens to be first on PATH.
///
/// Split out from its inputs so the ordering can be tested without a Windows
/// machine (see the tests at the bottom of this file).
fn build_candidates(git_exes: &[String], roots: &[PathBuf], bash_on_path: &[String]) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
// Compared as strings, case-insensitively, because that is the question a
// Windows path actually poses (`C:\Program Files` and `c:\program files`
// are one directory, and `Path` would call them two). Every input here
// comes from `where` or from an environment variable, so the separators
// are already the platform's own and a `/`-vs-`\` spelling of one path
// cannot arise. A duplicate that slipped through would cost one wasted
// existence check and nothing else — the first usable candidate wins.
let add = |p: PathBuf, out: &mut Vec<String>| {
let s = p.to_string_lossy().to_string();
if !out.iter().any(|e| e.eq_ignore_ascii_case(&s)) {
out.push(s);
}
};
// 1. Derive it from git. Git for Windows ships bash in the same install,
// so `where git` -> ...\Git\cmd\git.exe pins down ...\Git\bin\bash.exe.
// Walk up a few levels instead of assuming `cmd\`, because git.exe also
// lives under mingw64\bin in some layouts.
for git_exe in git_exes {
let mut dir = PathBuf::from(git_exe);
dir.pop(); // the directory holding git.exe
for _ in 0..3 {
if !dir.pop() {
break;
}
add(dir.join("bin").join(BASH_EXE), &mut out);
add(dir.join("usr").join("bin").join(BASH_EXE), &mut out);
}
}
// 2. The install roots, for a git that is not on PATH at all.
for root in roots {
add(root.join("Git").join("bin").join(BASH_EXE), &mut out);
add(
root.join("Git").join("usr").join("bin").join(BASH_EXE),
&mut out,
);
}
// 3. Whatever PATH itself offers, last.
for on_path in bash_on_path {
add(PathBuf::from(on_path), &mut out);
}
out
}
/// The death message. It names every candidate that was looked at, marks the
/// ones that were skipped as stubs, and says how to get a real bash — a bare
/// "no bash found" on somebody else's machine is unactionable.
fn no_bash_message(candidates: &[String]) -> String {
let mut msg = String::from(
"no usable bash found on Windows. The `bash` on PATH is the WSL \
app-execution-alias stub under WindowsApps, which cannot run without a \
registered WSL distro, so it is deliberately ignored. Install Git for \
Windows (https://git-scm.com/download/win, or `winget install --id \
Git.Git`), which ships Git Bash. Checked:",
);
if candidates.is_empty() {
msg.push_str("\n (nothing — neither git nor bash is on PATH)");
}
for c in candidates {
msg.push_str("\n ");
msg.push_str(c);
if is_wsl_alias_stub(c) {
msg.push_str(" (WSL stub, skipped)");
}
}
msg
}
// ── A child that stays alive ──────────────────────────────────────────────
/// A child that runs for `secs` seconds and whose pid stays THIS process for
/// all of them.
///
/// Unix: `sleep`, as before. Windows: `ping`, the Windows sleep — a native
/// single process, always present in System32.
///
/// Deliberately NOT `bash -c "sleep 30"` on Windows: bash exec-optimises a
/// `-c` that holds a single command, and the MSYS runtime emulates `exec` by
/// starting a NEW Windows process while the original `bash.exe` exits. The pid
/// the test had just tracked would be gone within milliseconds and every
/// "the shutdown killed it" assertion would pass without proving anything.
pub(crate) fn sleeper(secs: u32) -> Command {
if cfg!(windows) {
// -n counts the pings; the first goes out at once and the rest are a
// second apart, so n = secs + 1 lasts about `secs`.
let mut cmd = Command::new("ping");
cmd.args(["-n", &(secs + 1).to_string(), "127.0.0.1"]);
cmd
} else {
let mut cmd = Command::new("sleep");
cmd.arg(secs.to_string());
cmd
}
}
// ── Is this pid still a process ───────────────────────────────────────────
/// Is this pid a live process?
///
/// A killed-but-unreaped child is NOT alive: on Unix `ps -p` still lists a
/// zombie, so the process STATE has to be read — `Z` means the kill landed and
/// only the exit status is still pending; at quit the parent dies and init
/// reaps it. Windows has no zombies at all (a terminated process leaves the
/// table at once, even while a handle keeps its number reserved), so there the
/// question is simply whether the process table still lists it — read through
/// `sysinfo`, the same view the production `kill_tree` walks.
pub(crate) fn is_alive(pid: u32) -> bool {
if cfg!(windows) {
in_process_table(pid)
} else {
let state = unix_ps_field(pid, "state=");
!state.is_empty() && !state.starts_with('Z')
}
}
/// Is this number still taken — zombie included?
///
/// [`is_alive`] reports a zombie as dead, which is the wrong question when
/// what matters is the moment the kernel may hand the number out again: a
/// zombie has not been reaped, so its pid is still reserved, and `ps` keeps
/// listing it until it is. On Windows the number is held by the open process
/// handle rather than by an unreaped entry, and the process table is the only
/// thing that can be observed from outside.
pub(crate) fn pid_is_taken(pid: u32) -> bool {
if cfg!(windows) {
in_process_table(pid)
} else {
!unix_ps_field(pid, "pid=").is_empty()
}
}
fn unix_ps_field(pid: u32, field: &str) -> String {
Command::new("ps")
.args(["-o", field, "-p", &pid.to_string()])
.output()
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
.unwrap_or_default()
}
fn in_process_table(pid: u32) -> bool {
use sysinfo::{Pid, ProcessesToUpdate, System};
let mut sys = System::new();
// A full refresh, not `Some(&[pid])`: on Windows a terminated process can
// still be opened by pid while somebody holds a handle to it, and the
// per-pid refresh goes through exactly that door. The full snapshot lists
// what is actually running.
sys.refresh_processes(ProcessesToUpdate::All, true);
sys.process(Pid::from_u32(pid)).is_some()
}
/// Everything below `root` in the real parent/child links that is actually
/// doing work.
///
/// The same view the production `kill_tree` walks, which is what makes it the
/// right way to find the child a shell started when the shell cannot report it
/// itself: PowerShell has no `$!`, and Git Bash's `$!` is an MSYS pid that no
/// Windows API can address.
///
/// `conhost.exe` is filtered out because Windows attaches one to every process
/// that gets a console — CREATE_NO_WINDOW still creates one — and it appears
/// as a child of the shell, usually before the shell has started anything of
/// its own. A test that grabbed it would end up asserting that Windows' own
/// console host dies, which says nothing about the `pnpm install` underneath.
/// The name matches nothing on Unix, so the filter is inert there.
///
/// This IS the production view, not a copy of it: `kill_tree` walks the same
/// list, so there is one implementation and the tests borrow it.
pub(crate) fn worker_descendants_of(root: u32) -> Vec<u32> {
use sysinfo::{ProcessesToUpdate, System};
let mut sys = System::new();
sys.refresh_processes(ProcessesToUpdate::All, true);
// A parent link alone is not ownership. Windows keeps the parent pid in a
// process entry after the parent is gone, so a stranger whose dead creator
// once held the number `root` has now is listed under it as well. Such a
// stranger is older than `root`, and a test that took it for its own child
// would go on to fell it. Without a start time for `root` nothing is its.
let Some(root_start) = sys.process(sysinfo::Pid::from_u32(root)).map(|p| p.start_time()) else {
return Vec::new();
};
crate::commands::shell::worker_descendants_in(&sys, root)
.into_iter()
.filter(|pid| {
sys.process(sysinfo::Pid::from_u32(*pid)).is_some_and(|p| p.start_time() >= root_start)
})
.collect()
}
// ── Tests for the helpers themselves ──────────────────────────────────────
// ── Ports, stand-ins and the process table ────────────────────────────────
//
// Three things every test that scans the REAL process table needs, in one
// place instead of once per module. `commands/remote.rs` grew them first, for
// the cloudflared sweep; `commands/process.rs` needed the same three for the
// ComfyUI adoption scan and copying them would have meant two versions of an
// argument that took a day to get right.
/// A port number the kernel will not hand to anybody else for as long as the
/// returned listener is alive.
///
/// Tests that need a port NUMBER rather than a socket — because the thing under
/// test matches on a command line, not on a connection — used to write a
/// constant. A constant is shared by every concurrent copy of the same test
/// binary, and that is not hypothetical: with a hard-coded 61888, a second
/// suite running the ComfyUI adoption test at the same moment put a second
/// stand-in with the identical argv into the table, and the scan returned
/// whichever the iteration reached first. Measured over a 0/300/600/1000 ms
/// delay series under three concurrent suites, every one of the nine failures
/// was that: a found pid HIGHER than the test's own, i.e. a stranger's.
///
/// Binding `:0` and holding the socket removes the collision at the source: the
/// kernel does not assign a bound port to a second `bind(0)`, so two concurrent
/// copies of a test cannot draw the same number. Keep the listener in scope for
/// as long as the number has to stay yours.
// The one test that draws a port this way is `#[cfg(unix)]`; on Windows the
// helper was dead and clippy -D warnings rejected it.
#[cfg(unix)]
pub(crate) fn reserved_port() -> (u16, std::net::TcpListener) {
let listener = std::net::TcpListener::bind("127.0.0.1:0")
.expect("the loopback interface refused an ephemeral port");
let port = listener
.local_addr()
.expect("a bound listener has a local address")
.port();
(port, listener)
}
/// A port that refuses every connection for as long as the returned socket
/// lives: bound, never listened on.
///
/// Tests used to bind a port, free it and probe the number. In a parallel run
/// the stub of a neighbour test can draw the freed number before the probe
/// gets there, and the probe then finds a server where it expects none.
/// macOS, 09.10.2026: 4 of 300 runs of the health module red that way.
/// Linux, 10.10.2026: the same in `vram_release_tests`, 1 of 100 full runs.
/// A bound socket cannot be drawn by a second `bind(0)`, so keep it in scope
/// until the probe is back.
pub(crate) fn refusing_port() -> (u16, socket2::Socket) {
let held = socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::STREAM, None)
.expect("a TCP socket for the loopback interface");
let loopback: std::net::SocketAddr = "127.0.0.1:0".parse().expect("a literal address");
held.bind(&loopback.into()).expect("the loopback interface refused an ephemeral port");
let port = held
.local_addr()
.expect("a bound socket has a local address")
.as_socket()
.expect("an IPv4 socket has a socket address")
.port();
(port, held)
}
/// Path to `examples/park`, the compiled do-nothing stand-in.
///
/// Why a compiled binary and not a copy of `/bin/sh`: the full argument is in
/// the header of `src-tauri/examples/park.rs`. The short version is that macOS
/// SIGKILLs a copy of a SIP platform binary within a few hundred milliseconds,
/// so a test built on one is racing the kernel; a binary this toolchain
/// produced is ad-hoc signed and is left alone.
///
/// `cargo test` builds examples, so it is there whenever the tests are, and
/// Cargo copies it to `target/<profile>/examples/park`. The test binary sits
/// somewhere below `target/<profile>/`, but where is not stable: up to Cargo
/// 1.99 it was `deps/<test binary>`, from 1.100 it is
/// `build/<package>/<hash>/out/<test binary>`. So walk up from the test binary
/// to the first directory that has `examples/park`.
#[cfg(unix)]
pub(crate) fn park_binary() -> PathBuf {
let exe = std::env::current_exe().expect("current_exe");
let below = exe.parent().expect("the test binary has a directory");
let park = below
.ancestors()
.map(|dir| dir.join("examples").join("park"))
.find(|park| park.is_file())
// The old place, so the message below names a path worth looking at.
.unwrap_or_else(|| below.parent().unwrap_or(below).join("examples").join("park"));
assert!(
park.is_file(),
"{} is missing. It is `src-tauri/examples/park.rs`, which `cargo test` builds \
alongside the tests; if it is gone, the tests that spawn it are not measuring \
anything.",
park.display(),
);
park
}
/// A process table that has PROVEN itself, or the reason it could not.
///
/// The check is an invariant that cannot be false when the enumeration worked:
/// this very process is running, so a table without it was not read at all.
/// That is not a theoretical concern — sysinfo-0.33.1's macOS
/// `refresh_processes_specifics` takes its pids from `get_proc_list()`, and when
/// that returns `None` (its second `proc_listallpids` filling the buffer the
/// first one sized) the function returns 0 and leaves the list untouched, so a
/// fresh `System` comes back EMPTY with no error anywhere.
///
/// Retrying is therefore not hope: every retry is gated on a check, and the
/// caller only ever asserts on a snapshot that passed. Between the check and the
/// assertion there is no clock, no syscall and no other thread — the assertions
/// are a pure function of data already in hand.
///
/// ── The third check, added 01.09.2026 ──
///
/// `pid` must also CARRY ITS COMMAND LINE. Both callers exist to assert on argv,
/// and being listed is not the same as being readable: on macOS the argv of
/// another process comes from a separate `KERN_PROCARGS2` read, and a child that
/// has forked but not finished `exec` is in the table with an EMPTY `cmd()`.
/// Measured under six concurrent copies of the suite, ten rounds:
/// `the_call_does_not_block_for_the_grace_period` failed 2 of 60 runs on exactly
/// that — `argv=[]` for a `sleep 40` that was perfectly alive a moment later.
///
/// Putting it here rather than in each caller is deliberate: the other caller,
/// `the_scan_finds_a_real_process_by_the_argv_lu_would_have_used`, has the same
/// window and had simply not been unlucky yet. A table whose subject has no argv
/// is not a table this function should hand out.
///
/// ── The fourth check, added 05.09.2026 ──
///
/// Linux shows the same fork-to-exec window differently: `/proc/<pid>/cmdline`
/// of a child that has forked but not yet exec'd is not empty, it is the
/// PARENT'S argv, verbatim. On a fresh 4-vCPU Ubuntu 22.04 box,
/// `the_scan_finds_a_real_process_by_the_argv_lu_would_have_used` failed 2 of
/// 10 full-suite runs with exactly that: the stand-in "carried" nothing but
/// the path of this test binary. So a subject whose argv equals ours is not
/// the subject yet, and the table is not handed out.
#[cfg(unix)]
pub(crate) fn checked_table(pid: u32) -> Result<sysinfo::System, String> {
use std::time::{Duration, Instant};
let me = sysinfo::Pid::from_u32(std::process::id());
let deadline = Instant::now() + Duration::from_secs(10);
let mut attempts = 0usize;
let mut blind = 0usize;
let mut speechless = 0usize;
let mut unborn = 0usize;
loop {
if Instant::now() >= deadline {
return Err(format!(
"no usable process table in 10s ({attempts} attempts, {blind} of them \
without this test's own process in them, {speechless} with pid {pid} \
listed but carrying no command line, {unborn} with pid {pid} still \
carrying this test's own argv, i.e. forked but not exec'd). That is \
the TEST ENVIRONMENT, not the code under test."
));
}
if attempts > 0 {
// Paces retries so a pathological environment does not spin a core.
// It is not what makes the result correct — the checks below are.
std::thread::sleep(Duration::from_millis(20));
}
attempts += 1;
let sys = crate::process_util::process_table_with_cmdlines();
let Some(myself) = sys.process(me) else {
blind += 1;
continue;
};
let Some(subject) = sys.process(sysinfo::Pid::from_u32(pid)) else {
blind += 1;
continue;
};
let argv = crate::process_util::cmdline_of(subject);
if argv.is_empty() {
speechless += 1;
continue;
}
if pid != std::process::id() && argv == crate::process_util::cmdline_of(myself) {
unborn += 1;
continue;
}
return Ok(sys);
}
}
// ── Files that are big in name only ───────────────────────────────────────
/// A file of `bytes` apparent size that takes no room on disk, on every
/// platform.
///
/// The disk plans and the "is this pack complete" checks only ask for the size
/// of a file, so their tests stand in a 10 GB download with an empty file of
/// that length. `set_len` alone does that on APFS and ext4, where the grown
/// part is a hole. On NTFS it is not: the bytes are allocated, and one video
/// test left 23 GB in the scratch folder per run (Windows-Gegenprobe,
/// 09.10.2026: the second `cargo test` ended with "disk full", and took two
/// unrelated tests that measure free space with it). So the file is marked
/// sparse first, which makes the grown part a hole there as well.
pub(crate) fn sized_file(path: &Path, bytes: u64) {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).expect("the folder of a sized file");
}
let file = std::fs::File::create(path).expect("create a sized file");
#[cfg(windows)]
mark_sparse(&file);
file.set_len(bytes).expect("give a sized file its length");
}
#[cfg(windows)]
fn mark_sparse(file: &std::fs::File) {
use std::ffi::c_void;
use std::os::windows::io::AsRawHandle;
// Declared here and not taken from windows-sys: the crate has it behind
// features this build does not enable, and a test helper is no reason to
// widen what ships.
#[link(name = "kernel32")]
extern "system" {
fn DeviceIoControl(
device: *mut c_void,
control_code: u32,
in_buffer: *const c_void,
in_size: u32,
out_buffer: *mut c_void,
out_size: u32,
bytes_returned: *mut u32,
overlapped: *mut c_void,
) -> i32;
}
const FSCTL_SET_SPARSE: u32 = 0x0009_00C4;
let mut returned = 0u32;
// SAFETY: the handle belongs to `file`, which outlives the call. The
// control code takes no input buffer (that means "set") and writes no
// output, and `returned` is a valid place for the count.
let ok = unsafe {
DeviceIoControl(
file.as_raw_handle(),
FSCTL_SET_SPARSE,
std::ptr::null(),
0,
std::ptr::null_mut(),
0,
&mut returned,
std::ptr::null_mut(),
)
};
assert!(ok != 0, "the file could not be marked sparse: {}", std::io::Error::last_os_error());
}
/// The room a file really takes on its volume, as opposed to its length.
pub(crate) fn bytes_on_disk(path: &Path) -> u64 {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
std::fs::metadata(path).expect("metadata of a file").blocks() * 512
}
#[cfg(windows)]
{
use std::os::windows::ffi::OsStrExt;
use windows_sys::Win32::Storage::FileSystem::{GetCompressedFileSizeW, INVALID_FILE_SIZE};
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(std::iter::once(0)).collect();
let mut high = 0u32;
// SAFETY: `wide` is NUL terminated and outlives the call, `high` is a
// valid place for the upper half of the size.
let low = unsafe { GetCompressedFileSizeW(wide.as_ptr(), &mut high) };
assert!(
low != INVALID_FILE_SIZE || std::io::Error::last_os_error().raw_os_error() == Some(0),
"the size on disk could not be read: {}",
std::io::Error::last_os_error()
);
(u64::from(high) << 32) | u64::from(low)
}
}
// ── A script the test starts itself ───────────────────────────────────────
/// Put an executable script at `path`, ready to be started at once.
///
/// The text is written to a neighbour file and reaches `path` through `cp`, so
/// this process never has the script itself open for writing. That is the whole
/// point. Written here directly, the open file is copied into every child that
/// another test thread starts in the same moment, and stays open there until
/// that child's own exec. Starting the script inside that window fails with
/// "Text file busy" (os error 26), and a fake interpreter that cannot start
/// reads to the code under test as an interpreter that failed its probe. Linux
/// only in practice; macOS does not refuse the start.
///
/// Measured on Linux, 09.10.2026, `commands::install::` in a loop of 300 runs
/// before the tests in there used this: 10 red at a fake interpreter that
/// could not start.
#[cfg(unix)]
pub(crate) fn write_script(path: &Path, text: impl AsRef<[u8]>) {
use std::os::unix::fs::PermissionsExt;
let mut source = path.as_os_str().to_owned();
source.push(".txt");
std::fs::write(&source, text).expect("write the script text");
let copied = Command::new("cp").arg(&source).arg(path).status().expect("start cp");
assert!(copied.success(), "cp could not put the script at {}", path.display());
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).expect("make the script executable");
}
#[cfg(test)]
mod tests {
use super::*;
/// Windows-Gegenprobe, 09.10.2026: a stand-in for a download of many
/// gigabytes has that length and takes next to nothing, on NTFS too.
#[test]
fn a_sized_file_has_its_length_and_takes_no_room() {
const LEN: u64 = 6_000_000_000;
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("deep").join("download.safetensors");
sized_file(&path, LEN);
assert_eq!(std::fs::metadata(&path).expect("it exists").len(), LEN);
let taken = bytes_on_disk(&path);
assert!(taken < 1_000_000, "a stand-in of {LEN} bytes takes {taken} bytes of real disk");
// And the measure can tell: a file with content takes its room.
let full = dir.path().join("full.bin");
std::fs::write(&full, vec![7u8; 300_000]).expect("write");
assert!(bytes_on_disk(&full) >= 300_000, "{}", bytes_on_disk(&full));
}
/// The tests that stand in big files go through `sized_file`. A bare
/// `set_len` in one of them writes real bytes on Windows again.
#[test]
fn the_media_tests_make_their_big_files_through_sized_file() {
let bare = ["File::create(&path).unwrap()", ".set_len("].concat();
for (name, src) in [
("video.rs", include_str!("commands/video.rs")),
("image_mflux.rs", include_str!("commands/image_mflux.rs")),
("video_ltx2mlx.rs", include_str!("commands/video_ltx2mlx.rs")),
] {
assert!(!src.contains(&bare), "{name} grows a test file with a bare set_len");
assert!(src.contains("test_support::sized_file("), "{name} no longer uses sized_file");
}
}
#[test]
fn the_wsl_alias_stub_is_recognised_in_both_slash_flavours() {
for stub in [
r"C:\Users\x\AppData\Local\Microsoft\WindowsApps\bash.exe",
r"c:\users\x\appdata\local\microsoft\windowsapps\bash.exe",
"C:/Users/x/AppData/Local/Microsoft/WindowsApps/bash.exe",
] {
assert!(is_wsl_alias_stub(stub), "{stub} is the WSL stub");
}
for real in [
r"C:\Program Files\Git\bin\bash.exe",
r"C:\Program Files\Git\usr\bin\bash.exe",
"/bin/sh",
] {
assert!(!is_wsl_alias_stub(real), "{real} is a real shell");
}
// The word has to be a path SEGMENT. A folder that merely starts with
// it is somebody's own install, not the alias directory.
assert!(!is_wsl_alias_stub(r"C:\WindowsAppsBackup\bin\bash.exe"));
}
/// Every comparison in these fixtures goes through `Path`, never through
/// the string.
///
/// The inputs are Unix-shaped on purpose — the ORDER and the derivation
/// are the subject, not the separator — but `PathBuf::join` writes the
/// PLATFORM's separator, so on Windows `/opt/Git` + `bin` comes back as
/// `/opt/Git\bin\bash.exe`: the same path, a different string. Asserting
/// on the string turned this test red on the Windows box while the
/// resolver under it was correct. `Path` compares components, and both
/// slashes are separators there, so the question is asked in the form
/// both platforms can answer.
fn same_path(a: &str, b: &str) -> bool {
Path::new(a) == Path::new(b)
}
#[test]
fn git_comes_first_the_install_roots_next_and_path_last() {
let candidates = build_candidates(
&["/opt/Git/cmd/git.exe".to_string()],
&[PathBuf::from("/Program Files")],
&["/WindowsApps/bash.exe".to_string()],
);
// Derived from git: one level up from cmd\ is the install root.
assert_eq!(Path::new(&candidates[0]), Path::new("/opt/Git/bin/bash.exe"));
assert_eq!(Path::new(&candidates[1]), Path::new("/opt/Git/usr/bin/bash.exe"));
// ...and it keeps walking up, because git.exe is not always in cmd\.
assert!(
candidates.iter().any(|c| same_path(c, "/opt/bin/bash.exe")),
"the walk up stopped too early: {candidates:?}",
);
// The install roots come after everything git could tell us.
let root_pos = candidates
.iter()
.position(|c| same_path(c, "/Program Files/Git/bin/bash.exe"))
.expect("the install root is a candidate");
assert!(root_pos > 1, "the roots must not outrank git's own location");
// PATH is last, so a WSL stub can never win a race it only leads
// because it happens to come first on PATH.
let last = candidates.last().unwrap();
assert!(
same_path(last, "/WindowsApps/bash.exe"),
"PATH must come last, got {last}",
);
assert!(is_wsl_alias_stub(last));
}
#[test]
fn a_candidate_is_never_listed_twice() {
// The duplicate that PATH contributes is built with the same `join`
// the resolver uses, so it is byte-identical to git's own candidate on
// every platform. Spelling it out as a literal would only prove that
// two separators differ, which is a fact about the fixture and not
// about the resolver.
let from_git = PathBuf::from("/opt/Git")
.join("bin")
.join(BASH_EXE)
.to_string_lossy()
.to_string();
let candidates = build_candidates(
&["/opt/Git/cmd/git.exe".to_string(), "/opt/Git/cmd/git.exe".to_string()],
&[PathBuf::from("/Program Files"), PathBuf::from("/Program Files")],
&[from_git],
);
for (i, a) in candidates.iter().enumerate() {
for b in &candidates[i + 1..] {
assert!(!same_path(a, b), "{a} is listed twice in {candidates:?}");
}
}
}
#[test]
fn the_failure_message_names_every_candidate_and_marks_the_stubs() {
let msg = no_bash_message(&[
r"C:\Program Files\Git\bin\bash.exe".to_string(),
r"C:\Users\x\AppData\Local\Microsoft\WindowsApps\bash.exe".to_string(),
]);
assert!(msg.contains(r"C:\Program Files\Git\bin\bash.exe"), "{msg}");
assert!(msg.contains("WSL stub, skipped"), "{msg}");
assert!(msg.contains("git-scm.com/download/win"), "{msg}");
// The empty case must still say something an operator can act on.
assert!(no_bash_message(&[]).contains("neither git nor bash is on PATH"));
}
/// The stub filter must run before the existence check, or a stub that
/// really is on disk would be handed to CreateProcess.
#[test]
fn a_windowsapps_path_is_refused_even_when_the_file_exists() {
let dir = std::env::temp_dir().join(format!("lu-wsl-stub-{}", std::process::id()));
let apps = dir.join("WindowsApps");
std::fs::create_dir_all(&apps).unwrap();
let stub = apps.join(BASH_EXE);
std::fs::write(&stub, b"").unwrap();
let stub = stub.to_string_lossy().to_string();
assert!(Path::new(&stub).is_file(), "the stub is a file on disk");
assert!(!is_usable_bash(&stub), "and it must still be refused");
std::fs::remove_dir_all(&dir).ok();
}
/// `sleeper` has one job: a child that is still there a moment later, with
/// the pid the caller was handed.
#[test]
fn a_refusing_port_refuses_and_is_not_handed_out_again_while_held() {
let (port, held) = refusing_port();
let address: std::net::SocketAddr = format!("127.0.0.1:{port}").parse().unwrap();
let refused = std::net::TcpStream::connect_timeout(&address, std::time::Duration::from_secs(5));
assert!(refused.is_err(), "nobody listens on a port that was only bound");
// The number stays taken: a second owner cannot bind it, so no stub of
// a neighbour test can end up behind it.
assert!(std::net::TcpListener::bind(address).is_err(), "port {port} was handed out twice");
drop(held);
}
#[test]
fn the_sleeper_is_alive_under_its_own_pid_and_dies_when_killed() {
let mut child = sleeper(30)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.expect("spawn a sleeper");
let pid = child.id();
std::thread::sleep(std::time::Duration::from_millis(300));
assert!(is_alive(pid), "the sleeper must outlive the test's first look");
assert!(pid_is_taken(pid));
let _ = child.kill();
let _ = child.wait(); // reaped, so not even a zombie is left
// Asked until it is so: on a loaded Windows machine the process table
// can list the ended process for a moment after wait() has returned.
let gone_by = std::time::Instant::now() + std::time::Duration::from_secs(10);
while is_alive(pid) && std::time::Instant::now() < gone_by {
std::thread::sleep(std::time::Duration::from_millis(100));
}
assert!(!is_alive(pid), "a killed and reaped sleeper is not alive");
}
/// The descendant lookup is how the bg-task tests find the process a task
/// started, so it has to actually find one — under the pid of whoever
/// started it.
#[test]
fn descendants_finds_a_child_of_this_process() {
let mut child = sleeper(20)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.expect("spawn a sleeper");
let pid = child.id();
let mut found = false;
for _ in 0..20 {
if worker_descendants_of(std::process::id()).contains(&pid) {
found = true;
break;
}
std::thread::sleep(std::time::Duration::from_millis(100));
}
assert!(found, "the child ({pid}) this test started was not found below it");
let _ = child.kill();
let _ = child.wait();
}
/// The resolved shell has to be a shell that RUNS.
///
/// On Windows this is the end-to-end check on the whole resolver: the WSL
/// alias stub the PATH offers passes every existence test and then fails
/// in CreateProcess, so the only way to tell a real bash from it is to
/// spawn it. `exit` is a shell builtin on purpose — this must not depend
/// on which of Git Bash's directories are on PATH.
#[test]
fn the_resolved_shell_actually_runs_a_one_liner() {
let status = Command::new(posix_shell())
.args(["-c", "exit 7"])
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.unwrap_or_else(|e| panic!("could not spawn the resolved shell: {e}"));
assert_eq!(
status.code(),
Some(7),
"the resolved shell did not run the one-liner it was given",
);
}
}