Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
kwant for Windows (beta) (#410)
Oleksandr Ivanchenko64b16aa949ac
diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.ymlnew file mode 100644index 00000000..fb91363b--- /dev/null+++ b/.github/workflows/windows.yml@@ -0,0 +1,245 @@+name: Windows++# The Windows port (0.7.6, branch win-076). Runs only on win-* branches and by hand,+# so it never touches the Mac and Linux releases.+on:+ push:+ branches: ['win-*']+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: windows-${{ github.ref }}+ cancel-in-progress: true++env:+ CARGO_TERM_COLOR: always+ CARGO_INCREMENTAL: 0+ CARGO_PROFILE_DEV_DEBUG: 0+ CARGO_PROFILE_TEST_DEBUG: 0++jobs:+ frontend:+ name: frontend+ runs-on: ubuntu-latest+ defaults:+ run:+ working-directory: frontend+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: 20+ cache: npm+ cache-dependency-path: frontend/package-lock.json+ - run: npm ci+ - run: npm run build+ - uses: actions/upload-artifact@v4+ with:+ name: frontend-dist+ path: frontend/dist+ retention-days: 1++ rust:+ name: rust (windows)+ runs-on: windows-latest+ needs: frontend+ timeout-minutes: 90+ steps:+ # Byte-for-byte checkout: the test fixtures (PDFs, the docker files whose hash is pinned)+ # must not get CRLF line endings+ - run: git config --global core.autocrlf false+ - uses: actions/checkout@v4+ - uses: actions/download-artifact@v4+ with:+ name: frontend-dist+ path: frontend/dist+ - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable+ with:+ components: clippy+ - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3+ - name: Build (every error, short)+ run: cargo check --all-targets --locked --keep-going --message-format short+ - name: Clippy+ run: cargo clippy --all-targets --locked -- -D warnings+ # The first full run on Windows (125fc52) hung in ask_user_test: most integration tests drive+ # fake `sh` CLIs and aren't ported yet (plan.md, "Tests not ported to Windows yet"). The gate is+ # the unit tests, less the modules listed there, plus the integration tests for Windows behaviour.+ - name: Unit tests+ timeout-minutes: 20+ run: 'cargo test --locked --lib --no-fail-fast -- --skip server::dev:: --skip parallel::harness::'+ # Dev mode's git readers on Windows (0.7.7: #444 head_branch and its refusals, #447 the+ # freshness window, #448 diff sections matched by path). The rest of server::dev:: stays out+ # of the gate above (next-076/windows/plan.md, "Tests not ported").+ - name: Dev mode git readers (head_branch, fresh reviews, diff paths)+ timeout-minutes: 15+ run: 'cargo test --locked --lib --no-fail-fast -- server::dev::floor:: server::dev::poller::tests::fresh_means server::dev::poller::tests::candidates_go_newest server::dev::poller::tests::the_skipped_count server::dev::git::tests::diff_output_parses server::dev::git::tests::patches_are_matched'+ - name: Windows integration tests (bash, Stop ends the process tree)+ timeout-minutes: 20+ run: cargo test --locked --no-fail-fast --test shell_stop_tree_test --test shell_tool_test+ # kwnt.exe on its own: a scratch data dir and a free port, /api/health answers, then Stop and+ # nothing it started is left. Laya stays off (--no-laya) so the step never downloads Python.+ - name: Build kwnt.exe+ run: cargo build --locked --bin kwnt+ - name: kwnt.exe smoke (health, stop, process tree gone)+ shell: pwsh+ run: |+ $ErrorActionPreference = 'Stop'+ $exe = Join-Path $PWD 'target\debug\kwnt.exe'+ $data = Join-Path $env:RUNNER_TEMP 'kwnt-smoke'+ New-Item -ItemType Directory -Force $data | Out-Null+ $l = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Loopback, 0)+ $l.Start(); $port = $l.LocalEndpoint.Port; $l.Stop()+ "port $port"+ $env:KWNT_DATA_DIR = $data+ $out = Join-Path $env:RUNNER_TEMP 'kwnt-smoke.out'+ $err = Join-Path $env:RUNNER_TEMP 'kwnt-smoke.err'+ $proc = Start-Process -FilePath $exe -ArgumentList @('serve', '--host', '127.0.0.1', '--port', "$port", '--no-laya') `+ -RedirectStandardOutput $out -RedirectStandardError $err -PassThru -WindowStyle Hidden++ function Get-Tree([int]$root) {+ $all = Get-CimInstance Win32_Process | Select-Object ProcessId, ParentProcessId, Name+ $tree = @($root); $grew = $true+ while ($grew) {+ $grew = $false+ foreach ($p in $all) {+ if ($tree -contains [int]$p.ParentProcessId -and -not ($tree -contains [int]$p.ProcessId)) {+ $tree += [int]$p.ProcessId; $grew = $true+ }+ }+ }+ $all | Where-Object { $tree -contains [int]$_.ProcessId }+ }++ $health = $null+ $deadline = (Get-Date).AddSeconds(90)+ while ((Get-Date) -lt $deadline -and -not $health) {+ if ($proc.HasExited) { break }+ try {+ $r = Invoke-WebRequest -UseBasicParsing -TimeoutSec 3 "http://127.0.0.1:$port/api/health"+ if ($r.StatusCode -eq 200) { $health = $r.Content }+ } catch { Start-Sleep -Milliseconds 500 }+ }+ if (-not $health) {+ "kwnt.exe exited: $($proc.HasExited)"+ Get-Content $out -Tail 40 -ErrorAction SilentlyContinue+ Get-Content $err -Tail 40 -ErrorAction SilentlyContinue+ Write-Error "kwnt.exe never answered /api/health"; exit 1+ }+ "/api/health: $health"+ $json = $health | ConvertFrom-Json+ if ($json.app -ne 'kwnt' -or $json.status -ne 'ok') { Write-Error "that isn't kwant's health answer"; exit 1 }+ if (-not (Test-Path (Join-Path $data 'config.toml')) -and -not (Get-ChildItem $data)) {+ Write-Error "kwnt.exe didn't use the scratch data dir"; exit 1+ }++ $tree = @(Get-Tree $proc.Id)+ "process tree while running:"; $tree | Format-Table ProcessId, ParentProcessId, Name+ Stop-Process -Id $proc.Id -Force+ $proc.WaitForExit(15000) | Out-Null+ $left = @()+ $deadline = (Get-Date).AddSeconds(15)+ do {+ Start-Sleep -Milliseconds 500+ $left = @($tree | Where-Object { Get-Process -Id $_.ProcessId -ErrorAction SilentlyContinue })+ } while ($left.Count -gt 0 -and (Get-Date) -lt $deadline)+ if ($left.Count -gt 0) {+ "still running after Stop:"; $left | Format-Table ProcessId, Name+ $left | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }+ Write-Error "kwnt.exe's process tree wasn't gone after Stop"; exit 1+ }+ "stopped: all $($tree.Count) process(es) of the tree are gone"+ Get-Content $out -Tail 15 -ErrorAction SilentlyContinue++ # The desktop app and its installer (Pixel): an unsigned per-user NSIS .exe with the WebView2+ # download bootstrapper (apps/mac/tauri.windows.conf.json), then a silent install and a smoke test.+ app:+ name: app (windows installer)+ runs-on: windows-latest+ needs: frontend+ timeout-minutes: 60+ steps:+ - uses: actions/checkout@v4+ - uses: actions/download-artifact@v4+ with:+ name: frontend-dist+ path: frontend/dist+ - uses: actions/setup-node@v4+ with:+ node-version: 20+ - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable+ - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3+ with:+ workspaces: apps/mac -> target+ - name: App tests+ working-directory: apps/mac+ run: cargo test --locked+ - name: Build the NSIS installer+ working-directory: apps/mac+ shell: bash+ run: npx --yes @tauri-apps/[email protected] build --ci --bundles nsis -- --locked+ - name: Installer file+ id: nsis+ shell: pwsh+ run: |+ $exe = Get-ChildItem apps/mac/target/release/bundle/nsis/*-setup.exe | Select-Object -First 1+ if (-not $exe) { Write-Error "no NSIS installer was built"; exit 1 }+ "{0} {1:N1} MB" -f $exe.Name, ($exe.Length / 1MB)+ "path=$($exe.FullName)" >> $env:GITHUB_OUTPUT+ "name=$($exe.Name)" >> $env:GITHUB_OUTPUT+ - uses: actions/upload-artifact@v4+ with:+ name: kwant-windows-installer+ path: ${{ steps.nsis.outputs.path }}+ if-no-files-found: error+ retention-days: 14+ - name: Silent install, start, /api/auth/status, quit+ shell: pwsh+ env:+ SETUP: ${{ steps.nsis.outputs.path }}+ run: |+ $ErrorActionPreference = 'Stop'+ $install = Start-Process -FilePath $env:SETUP -ArgumentList '/S' -Wait -PassThru+ if ($install.ExitCode -ne 0) { Write-Error "the installer exited with $($install.ExitCode)"; exit 1 }+ $dir = Join-Path $env:LOCALAPPDATA 'kwant'+ $app = Join-Path $dir 'kwant.exe'+ if (-not (Test-Path $app)) {+ Get-ChildItem $dir -ErrorAction SilentlyContinue | Format-Table Name, Length+ Write-Error "kwant.exe isn't in $dir after a per-user install"; exit 1+ }+ Get-ChildItem $dir | Format-Table Name, Length+ $shortcut = Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs\kwant'+ "Start menu: $(Test-Path $shortcut)"++ $proc = Start-Process -FilePath $app -PassThru+ $status = $null+ $deadline = (Get-Date).AddSeconds(120)+ while ((Get-Date) -lt $deadline -and -not $status) {+ if ($proc.HasExited) { break }+ try {+ $r = Invoke-WebRequest -UseBasicParsing -TimeoutSec 3 'http://127.0.0.1:8799/api/auth/status'+ if ($r.StatusCode -eq 200) { $status = $r.Content }+ } catch { Start-Sleep -Milliseconds 500 }+ }+ $log = Join-Path $env:USERPROFILE '.kwnt\desktop-app.log'+ if (-not $status) {+ "app exited: $($proc.HasExited)"+ if (Test-Path $log) { Get-Content $log -Tail 80 }+ Write-Error "kwant inside the app never answered /api/auth/status"; exit 1+ }+ "/api/auth/status: $status"+ $json = $status | ConvertFrom-Json+ if ($null -eq $json.auth_required) { Write-Error "that isn't kwant's auth status"; exit 1 }+ "data dir: $(Test-Path (Join-Path $env:USERPROFILE '.kwnt'))"+ if (Test-Path $log) { Get-Content $log -Tail 20 }++ Stop-Process -Id $proc.Id+ $proc.WaitForExit(15000) | Out-Null+ Get-Process kwant -ErrorAction SilentlyContinue | Stop-Process -Force+ $uninstaller = Join-Path $dir 'uninstall.exe'+ if (Test-Path $uninstaller) {+ $u = Start-Process -FilePath $uninstaller -ArgumentList '/S' -Wait -PassThru+ "uninstall exit code: $($u.ExitCode)"+ }diff --git a/Cargo.lock b/Cargo.lockindex 08ee4b58..dd421403 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1459,10 +1459,12 @@ dependencies = ["tracing","tracing-subscriber","tz-rs",+ "tzdb_data","unicode-normalization","url","uuid","webpki-roots 1.0.9",+ "windows-sys 0.61.2","zeroize","zip",]@@ -3242,6 +3244,15 @@ version = "0.7.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4fc6c929ffa10fb34f4a3c7e9a73620a83ef2e85e47f9ec3381b8289e6762f42"+[[package]]+name = "tzdb_data"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "febaa995f6852367564e16c3369988b99d471d43ed12b1255b8d294661797f1c"+dependencies = [+ "tz-rs",+]+[[package]]name = "unicase"version = "2.10.0"diff --git a/Cargo.toml b/Cargo.tomlindex 26c45cd0..0863e538 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -70,6 +70,12 @@ mail-parser = "0.11"[target.'cfg(unix)'.dependencies]libc = "0.2"+# Windows: a Job Object per bot turn, so Stop ends the whole process tree (0.7.6 Windows port)+[target.'cfg(windows)'.dependencies]+# Windows has no system tz database: the IANA zones, bundled (routines::parse_tz)+tzdb_data = "0.2"+windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_JobObjects", "Win32_System_Threading"] }+[features]# Test-only seams: the moved clock (src/clock.rs, KWNT_TEST_NOW_OFFSET_SECS) and the Telegram API# address (KWNT_TELEGRAM_API_BASE). Never on by default and never in a shipped or `make run` build;diff --git a/apps/mac/Cargo.lock b/apps/mac/Cargo.lockindex 685b79d6..61b5a09f 100644--- a/apps/mac/Cargo.lock+++ b/apps/mac/Cargo.lock@@ -2767,10 +2767,12 @@ dependencies = ["tracing","tracing-subscriber","tz-rs",+ "tzdb_data","unicode-normalization","url","uuid","webpki-roots 1.0.9",+ "windows-sys 0.61.2","zeroize","zip",]@@ -6199,6 +6201,15 @@ version = "0.7.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4fc6c929ffa10fb34f4a3c7e9a73620a83ef2e85e47f9ec3381b8289e6762f42"+[[package]]+name = "tzdb_data"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "febaa995f6852367564e16c3369988b99d471d43ed12b1255b8d294661797f1c"+dependencies = [+ "tz-rs",+]+[[package]]name = "uds_windows"version = "1.2.1"@@ -6657,7 +6668,7 @@ version = "0.1.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"dependencies = [- "windows-sys 0.48.0",+ "windows-sys 0.61.2",][[package]]diff --git a/apps/mac/icons/icon.ico b/apps/mac/icons/icon.iconew file mode 100644index 00000000..ae0c5a2bBinary files /dev/null and b/apps/mac/icons/icon.ico differdiff --git a/apps/mac/src/links.rs b/apps/mac/src/links.rsindex 82ccf40f..9ba6d676 100644--- a/apps/mac/src/links.rs+++ b/apps/mac/src/links.rs@@ -75,20 +75,32 @@ pub fn new_window(url: &Url, home: &Home, others: &[Home]) -> Link {}/// The program that hands an address to the default browser: `open` on macOS, `xdg-open`-/// (looked up on PATH) on Linux desktops.+/// (looked up on PATH) on Linux desktops, `rundll32` on Windows (with [`opener_args`]).pub const fn browser_opener() -> &'static str {if cfg!(target_os = "macos") {"/usr/bin/open"+ } else if cfg!(windows) {+ "rundll32"} else {"xdg-open"}}+/// What comes before the address: Windows' URL handler takes it as `url.dll,FileProtocolHandler <url>`+/// (no `cmd /C start`, which would read `&` in the address as a second command).+pub const fn opener_args() -> &'static [&'static str] {+ if cfg!(windows) {+ &["url.dll,FileProtocolHandler"]+ } else {+ &[]+ }+}+/// Opens the address in the default browser ([`browser_opener`]). Only http(s) and mailto reach here.pub fn open_in_browser(url: &Url) {let url = url.as_str().to_string();std::thread::spawn(- move || match std::process::Command::new(browser_opener()).arg(&url).status() {+ move || match std::process::Command::new(browser_opener()).args(opener_args()).arg(&url).status() {Ok(s) if s.success() => {}Ok(s) => tracing::warn!(status = %s, "the browser didn't open the link"),Err(e) => tracing::warn!(error = %e, "couldn't open the link in the browser"),@@ -164,6 +176,10 @@ mod tests {assert_eq!(browser_opener(), "/usr/bin/open");#[cfg(target_os = "linux")]assert_eq!(browser_opener(), "xdg-open");+ #[cfg(not(windows))]+ assert!(opener_args().is_empty());+ #[cfg(windows)]+ assert_eq!((browser_opener(), opener_args()), ("rundll32", &["url.dll,FileProtocolHandler"][..]));}#[test]diff --git a/apps/mac/src/main.rs b/apps/mac/src/main.rsindex 185a40f5..d33d274f 100644--- a/apps/mac/src/main.rs+++ b/apps/mac/src/main.rs@@ -2,6 +2,10 @@//! next-075/side-by-side). A place is the kwant on this Mac (run in this process, or one already//! running here) or a kwant server the person added. A menu-bar (tray) icon lists them; closing a//! window keeps its place running, and Quit in the menu stops the app. Nothing relaunches.+//! On Windows (0.7.6 beta) the icon sits in the notification area.++// No console window behind the app on Windows+#![cfg_attr(windows, windows_subsystem = "windows")]mod connect;mod links;@@ -11,6 +15,8 @@ mod nudge;mod nudge_linux;#[cfg(target_os = "macos")]mod nudge_mac;+#[cfg(windows)]+mod nudge_windows;mod places;mod redact;mod remote;@@ -22,6 +28,8 @@ mod update;use nudge_linux as platform;#[cfg(target_os = "macos")]use nudge_mac as platform;+#[cfg(windows)]+use nudge_windows as platform;use places::{Place, Places};use startup::PortChoice;use std::collections::HashMap;@@ -59,7 +67,7 @@ const TRAY_ICON: &[u8] = include_bytes!("../icons/32x32.png");/// The shell asked for the login PATH when `$SHELL` is unset.#[cfg(target_os = "macos")]const FALLBACK_SHELL: &str = "/bin/zsh";-#[cfg(not(target_os = "macos"))]+#[cfg(not(any(target_os = "macos", windows)))]const FALLBACK_SHELL: &str = "/bin/bash";/// The app's own log in the data dir.@@ -412,6 +420,7 @@ fn demo_start() -> (kwnt::Config, Places) {/// Finder (and a Linux app menu) starts apps with a bare PATH, so the claude, codex and grok CLIs/// would be missing. Runs before any thread exists, so setting the variable is safe.+#[cfg(not(windows))]fn fix_path() {let shell = std::env::var("SHELL").unwrap_or_else(|_| FALLBACK_SHELL.to_string());let login = startup::login_shell_path(&shell, Duration::from_secs(3));@@ -420,6 +429,17 @@ fn fix_path() {std::env::set_var("PATH", startup::merged_path(login.as_deref(), ¤t, &home));}+/// Windows starts apps with the person's full PATH from the registry, so no login shell is+/// asked (Git Bash would answer in /c/... form). Only npm's and the native Claude install's+/// folders are added, in case a fresh install hasn't reached this session's PATH yet.+#[cfg(windows)]+fn fix_path() {+ let current = std::env::var("PATH").unwrap_or_default();+ let appdata = std::env::var("APPDATA").unwrap_or_default();+ let home = dirs::home_dir().unwrap_or_default();+ std::env::set_var("PATH", startup::windows_path(¤t, &appdata, &home.display().to_string()));+}+/// Starts kwant on its own runtime thread; the returned handle stops it.fn start_server(config: kwnt::Config) -> Server {let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>();@@ -1322,7 +1342,8 @@ fn build_tray(handle: &AppHandle) -> tauri::Result<()> {}// The app's own update: when it runs kwant here or shows a server (an attached// kwant updates itself)- if !updates && demo.is_none() && (shared.started_kwant.load(Ordering::Relaxed) || !places.servers.is_empty()) {+ // In-app updates are off on Windows in the beta (no signed Windows release yet)+ if !updates && !cfg!(windows) && demo.is_none() && (shared.started_kwant.load(Ordering::Relaxed) || !places.servers.is_empty()) {updates = true;update::start(&app);}@@ -1427,8 +1448,8 @@ fn collect_waiting(spaces: Option<String>, get: impl Fn(&str) -> Option<String>)all}-/// Platforms without a nudge of their own (the app ships for macOS and Linux) keep the count.-#[cfg(not(any(target_os = "macos", target_os = "linux")))]+/// Platforms without a nudge of their own (the app ships for macOS, Linux and Windows) keep the count.+#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]mod platform {pub struct Nudger;impl Nudger {diff --git a/apps/mac/src/nudge_windows.rs b/apps/mac/src/nudge_windows.rsnew file mode 100644index 00000000..3c785e2c--- /dev/null+++ b/apps/mac/src/nudge_windows.rs@@ -0,0 +1,122 @@+//! The Windows side of the "needs you" nudge (0.7.6 beta). The notification area shows tray+//! pictures as they are and can't say where the icon is, so, like Linux, there is no pill: the+//! icon swaps to Mira's colour "needs you" mark, its tooltip says how many wait, and the taskbar+//! button flashes once when something new arrives. No toast in the beta. The rules are in+//! `nudge.rs`.++use crate::nudge::Change;+use tauri::{image::Image, tray::TrayIcon, AppHandle, UserAttentionType};++// Mira's Linux colour marks (44 px): the notification area draws them as they are, too+const NORMAL_DARK: &[u8] = include_bytes!("../icons/linux/tray-normal-dark.png");+const NORMAL_LIGHT: &[u8] = include_bytes!("../icons/linux/tray-normal-light.png");+const NEEDS_YOU_DARK: &[u8] = include_bytes!("../icons/linux/tray-needs-you-dark.png");+const NEEDS_YOU_LIGHT: &[u8] = include_bytes!("../icons/linux/tray-needs-you-light.png");++/// Whether the taskbar is dark: Windows' "SystemUsesLightTheme" value, `0x0` for dark. Anything+/// unreadable counts as dark, Windows 10 and 11's default.+pub fn taskbar_is_dark(reg_output: Option<&str>) -> bool {+ let Some(out) = reg_output else { return true };+ let value = out+ .lines()+ .find(|l| l.contains("SystemUsesLightTheme"))+ .and_then(|l| l.split_whitespace().last());+ !matches!(value, Some("0x1"))+}++fn detect_dark_taskbar() -> bool {+ use std::os::windows::process::CommandExt;+ const CREATE_NO_WINDOW: u32 = 0x0800_0000;+ let out = std::process::Command::new("reg")+ .args([+ "query",+ r"HKCU\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize",+ "/v",+ "SystemUsesLightTheme",+ ])+ .creation_flags(CREATE_NO_WINDOW)+ .output()+ .ok()+ .filter(|o| o.status.success())+ .map(|o| String::from_utf8_lossy(&o.stdout).into_owned());+ taskbar_is_dark(out.as_deref())+}++pub fn tray_icon(needs_you: bool, dark_taskbar: bool) -> &'static [u8] {+ match (needs_you, dark_taskbar) {+ (false, true) => NORMAL_DARK,+ (false, false) => NORMAL_LIGHT,+ (true, true) => NEEDS_YOU_DARK,+ (true, false) => NEEDS_YOU_LIGHT,+ }+}++/// The icon's tooltip (Windows shows no text next to tray icons).+pub fn tooltip(count: usize) -> String {+ match count {+ 0 => "kwant".to_string(),+ 1 => "kwant: 1 thing needs you".to_string(),+ n => format!("kwant: {n} things need you"),+ }+}++pub struct Nudger {+ tray: TrayIcon,+ dark_taskbar: bool,+ count: Option<usize>,+}++impl Nudger {+ pub fn start(_: &AppHandle, tray: TrayIcon) -> Nudger {+ let dark_taskbar = detect_dark_taskbar();+ let _ = tray.set_icon(Image::from_bytes(tray_icon(false, dark_taskbar)).ok());+ Nudger { tray, dark_taskbar, count: None }+ }++ /// The icon and tooltip follow the count (state, so they stay with "Show nudges" off); the+ /// taskbar flash only while nudges are on and kwant isn't focused.+ pub fn on_poll(&mut self, handle: &AppHandle, change: &Change, show: bool) {+ if self.count != Some(change.count) {+ let needs_you = change.count > 0;+ let _ = self.tray.set_icon(Image::from_bytes(tray_icon(needs_you, self.dark_taskbar)).ok());+ let _ = self.tray.set_tooltip(Some(tooltip(change.count)));+ self.count = Some(change.count);+ }+ if !show || change.arrived.is_empty() || crate::kwant_focused(handle) {+ return;+ }+ let from = change.arrived.first().map(|i| i.place.as_str());+ if let Some(main) = crate::place_window(handle, from) {+ let _ = main.request_user_attention(Some(UserAttentionType::Informational));+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_taskbar_theme_comes_from_the_registry_value() {+ let light = "\r\nHKEY_CURRENT_USER\\...\\Personalize\r\n SystemUsesLightTheme REG_DWORD 0x1\r\n";+ let dark = "\r\nHKEY_CURRENT_USER\\...\\Personalize\r\n SystemUsesLightTheme REG_DWORD 0x0\r\n";+ assert!(!taskbar_is_dark(Some(light)));+ assert!(taskbar_is_dark(Some(dark)));+ assert!(taskbar_is_dark(None));+ assert!(taskbar_is_dark(Some("")));+ }++ #[test]+ fn tooltips_count_what_waits() {+ assert_eq!(tooltip(0), "kwant");+ assert_eq!(tooltip(1), "kwant: 1 thing needs you");+ assert_eq!(tooltip(3), "kwant: 3 things need you");+ }++ #[test]+ fn every_tray_picture_decodes() {+ for (n, d) in [(false, false), (false, true), (true, false), (true, true)] {+ assert!(Image::from_bytes(tray_icon(n, d)).is_ok());+ }+ }+}diff --git a/apps/mac/src/startup.rs b/apps/mac/src/startup.rsindex 98017444..36e45e03 100644--- a/apps/mac/src/startup.rs+++ b/apps/mac/src/startup.rs@@ -33,6 +33,26 @@ pub fn merged_path(login_path: Option<&str>, current: &str, home: &Path) -> Striout.join(":")}+/// Windows: the current PATH, then npm's global folder (`%APPDATA%\npm`, where `claude.cmd` and+/// `codex.cmd` land) and the native Claude install (`%USERPROFILE%\.local\bin`), each folder+/// once (Windows paths compare without case).+#[cfg_attr(not(windows), allow(dead_code))]+pub fn windows_path(current: &str, appdata: &str, home: &str) -> String {+ let mut out: Vec<String> = Vec::new();+ let extras = [+ (!appdata.is_empty()).then(|| format!("{appdata}\\npm")),+ (!home.is_empty()).then(|| format!("{home}\\.local\\bin")),+ ];+ for dir in current.split(';').map(str::to_string).chain(extras.into_iter().flatten()) {+ let dir = dir.trim().to_string();+ let seen = out.iter().any(|d| d.trim_end_matches('\\').eq_ignore_ascii_case(dir.trim_end_matches('\\')));+ if !dir.is_empty() && !seen {+ out.push(dir);+ }+ }+ out.join(";")+}+/// The PATH `$SHELL -lc` sees (so .zprofile/.zshrc additions count), or `None` after `timeout`./// The shell's own output is noise: only the line between the markers is read.pub fn login_shell_path(shell: &str, timeout: Duration) -> Option<String> {@@ -146,6 +166,8 @@ mod tests {PORTS.lock().unwrap_or_else(|e| e.into_inner())}+ // The Mac/Linux PATH (`:`-joined, Homebrew); Windows has its own, tested below+ #[cfg(unix)]#[test]fn login_path_comes_first_then_current_then_extras_without_repeats() {let home = PathBuf::from("/Users/o");@@ -156,6 +178,7 @@ mod tests {);}+ #[cfg(unix)]#[test]fn finder_launch_without_a_shell_answer_still_gets_homebrew_and_local_bin() {let merged = merged_path(None, "/usr/bin:/bin:/usr/sbin:/sbin", Path::new("/Users/o"));@@ -165,6 +188,21 @@ mod tests {);}+ #[test]+ fn windows_path_adds_npm_and_local_bin_once() {+ let merged = windows_path(+ r"C:\Windows\system32;C:\Users\o\AppData\Roaming\npm\;C:\Program Files\Git\cmd",+ r"C:\Users\o\AppData\Roaming",+ r"C:\Users\o",+ );+ assert_eq!(+ merged,+ r"C:\Windows\system32;C:\Users\o\AppData\Roaming\npm\;C:\Program Files\Git\cmd;C:\Users\o\.local\bin"+ );+ assert_eq!(windows_path("", "", ""), "");+ }++ #[cfg(unix)]#[test]fn login_shell_path_reads_only_the_marked_line() {let path = login_shell_path("/bin/sh", Duration::from_secs(5)).expect("sh answers");@@ -172,6 +210,7 @@ mod tests {assert!(!path.contains("__KWANT"), "{path}");}+ #[cfg(unix)]#[test]fn a_shell_that_hangs_is_given_up_on() {let dir = std::env::temp_dir().join(format!("kwant-hang-{}", std::process::id()));diff --git a/apps/mac/tauri.windows.conf.json b/apps/mac/tauri.windows.conf.jsonnew file mode 100644index 00000000..b792453e--- /dev/null+++ b/apps/mac/tauri.windows.conf.json@@ -0,0 +1,21 @@+{+ "$schema": "https://schema.tauri.app/config/2",+ "bundle": {+ "targets": ["nsis"],+ "icon": [+ "icons/32x32.png",+ "icons/128x128.png",+ "icons/[email protected]",+ "icons/icon.ico",+ "icons/icon.png"+ ],+ "windows": {+ "webviewInstallMode": { "type": "downloadBootstrapper", "silent": true },+ "nsis": {+ "installMode": "currentUser",+ "displayLanguageSelector": false,+ "startMenuFolder": "kwant"+ }+ }+ }+}diff --git a/src/drivers/cli.rs b/src/drivers/cli.rsindex 711aa937..eef6d9eb 100644--- a/src/drivers/cli.rs+++ b/src/drivers/cli.rs@@ -12,25 +12,46 @@ use tokio::sync::mpsc;/// servers it started would live on. Declare it after the child, so it drops first, while the/// child is still unreaped and its group id can't be reused. Disarmed once the CLI has exited,/// so anything a finished turn deliberately left running is kept.-pub(crate) struct ProcessGroup(Option<u32>);+///+/// On Windows the "group" is a Job Object holding the CLI and everything it starts+/// (see [`super::win_job`]); `taskkill /T` is the fallback when Windows refuses the job.+pub(crate) struct ProcessGroup {+ pid: Option<u32>,+ #[cfg(windows)]+ job: Option<super::win_job::Job>,+}impl ProcessGroup {pub(crate) fn of(child: &tokio::process::Child) -> Self {- Self(child.id())+ Self {+ pid: child.id(),+ #[cfg(windows)]+ job: child.raw_handle().and_then(super::win_job::Job::holding),+ }}pub(crate) fn disarm(&mut self) {- self.0 = None;+ self.pid = None;+ #[cfg(windows)]+ if let Some(job) = self.job.take() {+ job.release();+ }}}impl Drop for ProcessGroup {fn drop(&mut self) {- kill_group(self.0);+ #[cfg(windows)]+ if let Some(job) = self.job.take() {+ job.kill();+ return;+ }+ kill_group(self.pid);}}/// SIGKILLs the process group led by `pid` (a CLI started with [`own_process_group`]).+/// On Windows: `taskkill /T /F`, which ends `pid` and every process it started.fn kill_group(pid: Option<u32>) {#[cfg(unix)]if let Some(pid) = pid.and_then(|p| i32::try_from(p).ok()).filter(|p| *p > 0) {@@ -39,18 +60,30 @@ fn kill_group(pid: Option<u32>) {libc::kill(-pid, libc::SIGKILL);}}- #[cfg(not(unix))]+ #[cfg(windows)]+ if let Some(pid) = pid.filter(|p| *p > 0) {+ super::win_job::taskkill_tree(pid);+ }+ #[cfg(not(any(unix, windows)))]let _ = pid;}/// Starts the CLI as the leader of its own process group, for [`ProcessGroup`].+/// On Windows the CLI gets no console window of its own (`CREATE_NO_WINDOW`); its tree is held+/// by the Job Object [`ProcessGroup::of`] puts it in.pub(crate) fn own_process_group(cmd: &mut Command) {#[cfg(unix)]cmd.process_group(0);- #[cfg(not(unix))]+ #[cfg(windows)]+ cmd.creation_flags(CREATE_NO_WINDOW);+ #[cfg(not(any(unix, windows)))]let _ = cmd;}+/// `CREATE_NO_WINDOW`: a console program started by the (windowless) app opens no console window.+#[cfg(windows)]+const CREATE_NO_WINDOW: u32 = 0x0800_0000;+static CLI_BINARY_CACHE: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, Option<String>>>> =std::sync::OnceLock::new();@@ -76,6 +109,94 @@ pub fn forget_cli_binaries() {}}+#[cfg(windows)]+fn find_cli_binary_uncached(name: &str) -> Option<String> {+ use std::os::windows::process::CommandExt;+ // `where` lists PATH hits with every PATHEXT extension; an .exe beats a .cmd shim+ let on_path: Vec<String> = std::process::Command::new("where")+ .arg(name)+ .stdin(Stdio::null())+ .stderr(Stdio::null())+ .creation_flags(CREATE_NO_WINDOW)+ .output()+ .ok()+ .filter(|o| o.status.success())+ .map(|o| String::from_utf8_lossy(&o.stdout).lines().map(|l| l.trim().to_string()).filter(|l| !l.is_empty()).collect())+ .unwrap_or_default();+ let env = |k: &str| std::env::var_os(k).map(std::path::PathBuf::from);+ windows_cli_candidates(name, &on_path, env("USERPROFILE"), env("APPDATA"))+ .into_iter()+ .find(|p| Path::new(p).is_file())+}++/// Where a CLI may be on Windows, best first: a native `.exe` on PATH, Claude's native install+/// (`%USERPROFILE%\.local\bin\<name>.exe`), a `.cmd`/`.bat` shim on PATH, then npm's own folder+/// (`%APPDATA%\npm\<name>.cmd`). Plan decision 5.+#[cfg(any(windows, test))]+fn windows_cli_candidates(+ name: &str,+ on_path: &[String],+ user_profile: Option<std::path::PathBuf>,+ app_data: Option<std::path::PathBuf>,+) -> Vec<String> {+ let ext = |p: &str| Path::new(p).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();+ let mut out: Vec<String> = on_path.iter().filter(|p| ext(p) == "exe").cloned().collect();+ if let Some(home) = user_profile {+ out.push(home.join(".local").join("bin").join(format!("{name}.exe")).display().to_string());+ }+ out.extend(on_path.iter().filter(|p| matches!(ext(p).as_str(), "cmd" | "bat")).cloned());+ if let Some(roaming) = app_data {+ out.push(roaming.join("npm").join(format!("{name}.cmd")).display().to_string());+ }+ out+}++/// A command that runs the CLI at `bin`. On Windows an npm `.cmd` shim is skipped: its Node script+/// is run with node directly, since cmd.exe can't safely pass a prompt with line breaks or quotes+/// on. A shim kwnt can't read runs through Rust's own `.cmd` handling (cmd /C with checked+/// quoting). Elsewhere, and for an `.exe`, it is just `bin`.+pub fn cli_command(bin: impl AsRef<std::ffi::OsStr>) -> Command {+ #[cfg(windows)]+ if let Some((node, script)) = npm_shim_target(Path::new(bin.as_ref())) {+ let mut cmd = Command::new(node);+ cmd.arg(script);+ return cmd;+ }+ Command::new(bin)+}++/// For an npm `.cmd` shim, the node to use and the script it runs: the shim names it as+/// `"%dp0%\node_modules\<package>\<script>.js"` (npm's cmd-shim), relative to the shim's folder.+#[cfg(windows)]+fn npm_shim_target(bin: &Path) -> Option<(std::path::PathBuf, std::path::PathBuf)> {+ let ext = bin.extension()?.to_string_lossy().to_ascii_lowercase();+ if ext != "cmd" && ext != "bat" {+ return None;+ }+ let dir = bin.parent()?;+ let script = dir.join(shim_script(&std::fs::read_to_string(bin).ok()?)?);+ if !script.is_file() {+ return None;+ }+ let own_node = dir.join("node.exe");+ let node = if own_node.is_file() { own_node } else { "node".into() };+ Some((node, script))+}++/// The script path inside an npm cmd-shim, relative to the shim's folder: the quoted+/// `"%dp0%\..."` that is a `.js` file (the shim also names `"%dp0%\node.exe"`).+#[cfg(any(windows, test))]+fn shim_script(shim: &str) -> Option<String> {+ const MARK: &str = "\"%dp0%\\";+ shim.match_indices(MARK).find_map(|(at, _)| {+ let rest = &shim[at + MARK.len()..];+ let path = &rest[..rest.find('"')?];+ let lower = path.to_ascii_lowercase();+ (lower.ends_with(".js") || lower.ends_with(".cjs") || lower.ends_with(".mjs")).then(|| path.to_string())+ })+}++#[cfg(not(windows))]fn find_cli_binary_uncached(name: &str) -> Option<String> {// 1. Try standard which commandif let Ok(output) = std::process::Command::new("which").arg(name).output() {@@ -409,7 +530,7 @@ pub async fn codex_user_mcp_servers(cwd: Option<&Path>,profile_env: Option<&crate::profiles::CliEnv>,) -> Result<Vec<String>, String> {- let mut cmd = Command::new(bin);+ let mut cmd = cli_command(bin);cmd.args(["mcp", "list", "--json"]);if let Some(env) = profile_env {env.apply(&mut cmd);@@ -611,7 +732,7 @@ impl CliDriver {event_tx: &mpsc::Sender<RuntimeEvent>,) -> std::io::Result<GrokRun> {let home = super::grok::GrokHome::create(&std::env::temp_dir(), &launch.config)?;- let mut cmd = Command::new(launch.bin_path);+ let mut cmd = cli_command(launch.bin_path);if let Some(dir) = launch.input.workspace_dir.as_ref().filter(|d| d.exists()) {cmd.current_dir(dir);}@@ -1292,7 +1413,7 @@ impl Driver for CliDriver {}};- let mut cmd = Command::new(&bin_path);+ let mut cmd = cli_command(&bin_path);if let Some(ref dir) = input.workspace_dir {if dir.exists() {cmd.current_dir(dir);@@ -1706,6 +1827,37 @@ mod tests {use super::*;use crate::db::models::{Kwant, Message};+ // Plan decision 5: native .exe first, Claude's own install, then npm .cmd shims.+ #[test]+ fn windows_cli_candidates_prefer_native_exe_then_npm_shims() {+ let home = std::path::PathBuf::from("C:/Users/someone");+ let roaming = home.join("AppData").join("Roaming");+ let on_path = vec!["C:/npm/claude.cmd".to_string(), "C:/bin/claude.EXE".to_string(), "C:/x/claude.ps1".to_string()];+ let got = windows_cli_candidates("claude", &on_path, Some(home.clone()), Some(roaming.clone()));+ assert_eq!(+ got,+ vec![+ "C:/bin/claude.EXE".to_string(),+ home.join(".local").join("bin").join("claude.exe").display().to_string(),+ "C:/npm/claude.cmd".to_string(),+ roaming.join("npm").join("claude.cmd").display().to_string(),+ ]+ );+ assert!(windows_cli_candidates("codex", &[], None, None).is_empty());+ }++ #[test]+ fn npm_shim_script_skips_the_node_exe_it_also_names() {+ let shim = "@ECHO off\r\nGOTO start\r\n:find_dp0\r\nSET dp0=%~dp0\r\nEXIT /b\r\n:start\r\nSETLOCAL\r\nCALL :find_dp0\r\n\r\n\+IF EXIST \"%dp0%\\node.exe\" (\r\n SET \"_prog=%dp0%\\node.exe\"\r\n) ELSE (\r\n SET \"_prog=node\"\r\n)\r\n\r\n\+endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & \"%_prog%\" \"%dp0%\\node_modules\\@anthropic-ai\\claude-code\\cli.js\" %*\r\n";+ assert_eq!(shim_script(shim).as_deref(), Some("node_modules\\@anthropic-ai\\claude-code\\cli.js"));+ let codex = "\"%dp0%\\node_modules\\@openai\\codex\\bin\\codex.MJS\" %*";+ assert_eq!(shim_script(codex).as_deref(), Some("node_modules\\@openai\\codex\\bin\\codex.MJS"));+ assert_eq!(shim_script("@echo off\r\nC:\\tools\\thing.exe %*"), None);+ assert_eq!(shim_script("\"%dp0%\\node.exe\" \"%dp0%\\unterminated.js"), None);+ }+#[test]fn claude_stream_reports_usage_so_far() {let mut stream = ClaudeStream::default();diff --git a/src/drivers/engines.rs b/src/drivers/engines.rsindex 2c9ea43f..cd98efe8 100644--- a/src/drivers/engines.rs+++ b/src/drivers/engines.rs@@ -389,7 +389,7 @@ async fn run(bin: &str, args: &[&str]) -> Result<CmdOut, String> {async fn run_in(bin: &str, args: &[&str], claude_home: Option<&std::path::Path>) -> Result<CmdOut, String> {let mut cmd = match claude_home {Some(home) => crate::profiles::CliEnv::for_home(crate::profiles::Engine::Claude, home).command(bin),- None => tokio::process::Command::new(bin),+ None => crate::drivers::cli::cli_command(bin),};let out = cmd.args(args)diff --git a/src/drivers/grok.rs b/src/drivers/grok.rsindex 1fcbf0a6..d9e156f4 100644--- a/src/drivers/grok.rs+++ b/src/drivers/grok.rs@@ -89,6 +89,7 @@ impl GrokHome {pub fn create(base: &Path, config: &toml::Table) -> std::io::Result<Self> {sweep_stale(base);let path = base.join(format!("{DIR_PREFIX}{}", uuid::Uuid::new_v4().simple()));+ #[cfg_attr(not(unix), allow(unused_mut))]let mut builder = std::fs::DirBuilder::new();#[cfg(unix)]{@@ -831,6 +832,8 @@ include_only = ["*"]assert!(auth.exists(), "the user's own file is untouched");}+ // Windows can't open a folder as a file to date it, and Grok is off on Windows+ #[cfg(unix)]#[test]fn sweeps_only_stale_kwnt_homes() {let base = tempfile::tempdir().unwrap();diff --git a/src/drivers/mod.rs b/src/drivers/mod.rsindex 11db2491..301a539e 100644--- a/src/drivers/mod.rs+++ b/src/drivers/mod.rs@@ -6,6 +6,8 @@ pub mod custom;pub mod engines;pub mod events;pub mod grok;+#[cfg(windows)]+pub(crate) mod win_job;pub use api::ApiDriver;pub use cli::{find_cli_binary, forget_cli_binaries, CliDriver};diff --git a/src/drivers/win_job.rs b/src/drivers/win_job.rsnew file mode 100644index 00000000..0b1039f0--- /dev/null+++ b/src/drivers/win_job.rs@@ -0,0 +1,88 @@+//! Windows only: one Job Object per bot turn, so Stop ends the whole process tree (plan decision 3).+//!+//! Windows has no process groups. Every process a job member starts joins the same job, so+//! terminating the job ends the CLI or bot command, its children and their children. The job is+//! created with `KILL_ON_JOB_CLOSE`, so even if kwnt itself dies, closing its handle ends them.++use std::ffi::c_void;+use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};+use windows_sys::Win32::System::JobObjects::{+ AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation, SetInformationJobObject,+ TerminateJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,+};++pub(crate) struct Job(HANDLE);++// SAFETY: a job handle is a kernel handle; any thread may use or close it.+unsafe impl Send for Job {}+unsafe impl Sync for Job {}++impl Job {+ /// A new kill-on-close job holding `process` (a raw process handle), or None if Windows refused.+ pub(crate) fn holding(process: *mut c_void) -> Option<Self> {+ // SAFETY: plain Win32 calls on handles this function owns or was given; the info struct+ // lives on the stack for the duration of the call and its size is passed with it.+ unsafe {+ let handle = CreateJobObjectW(std::ptr::null(), std::ptr::null());+ if handle.is_null() {+ return None;+ }+ let job = Job(handle);+ if !job.set_kill_on_close(true) {+ return None;+ }+ if AssignProcessToJobObject(job.0, process as HANDLE) == 0 {+ return None;+ }+ Some(job)+ }+ }++ fn set_kill_on_close(&self, on: bool) -> bool {+ let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();+ if on {+ info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;+ }+ // SAFETY: see `holding`+ unsafe {+ SetInformationJobObject(+ self.0,+ JobObjectExtendedLimitInformation,+ &info as *const JOBOBJECT_EXTENDED_LIMIT_INFORMATION as *const c_void,+ std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,+ ) != 0+ }+ }++ /// Ends every process in the job now.+ pub(crate) fn kill(&self) {+ // SAFETY: a valid job handle owned by self+ unsafe {+ TerminateJobObject(self.0, 1);+ }+ }++ /// Lets the job's processes outlive it: clears kill-on-close, then closes the handle.+ pub(crate) fn release(self) {+ self.set_kill_on_close(false);+ }+}++impl Drop for Job {+ fn drop(&mut self) {+ // SAFETY: the handle is owned by self and closed exactly once+ unsafe {+ CloseHandle(self.0);+ }+ }+}++/// Fallback when there is no job: `taskkill /T /F` ends `pid` and every process it started.+pub(crate) fn taskkill_tree(pid: u32) {+ let _ = std::process::Command::new("taskkill")+ .args(["/T", "/F", "/PID", &pid.to_string()])+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .status();+}diff --git a/src/fsx.rs b/src/fsx.rsnew file mode 100644index 00000000..6f8c653f--- /dev/null+++ b/src/fsx.rs@@ -0,0 +1,241 @@+//! File modes that work on every platform kwant runs on.+//!+//! On Mac and Linux these are the usual Unix modes (0600 files, 0700 folders), set exactly as+//! before. Windows has no mode bits: everything private lives under the data dir+//! (`%USERPROFILE%\.kwnt`), whose access list [`restrict_to_user`] limits to the current user and+//! SYSTEM, and every file and folder under it inherits that list. So the mode calls are no-ops+//! there.++use std::path::Path;++/// `mode` on Unix (`OpenOptionsExt::mode`, `DirBuilderExt::mode`); nothing on Windows, where the+/// data dir's inherited access list does the job.+pub trait UnixMode {+ fn unix_mode(&mut self, mode: u32) -> &mut Self;+}++impl UnixMode for std::fs::OpenOptions {+ fn unix_mode(&mut self, mode: u32) -> &mut Self {+ #[cfg(unix)]+ std::os::unix::fs::OpenOptionsExt::mode(self, mode);+ #[cfg(not(unix))]+ let _ = mode;+ self+ }+}++impl UnixMode for std::fs::DirBuilder {+ fn unix_mode(&mut self, mode: u32) -> &mut Self {+ #[cfg(unix)]+ std::os::unix::fs::DirBuilderExt::mode(self, mode);+ #[cfg(not(unix))]+ let _ = mode;+ self+ }+}++/// `chmod` on Unix; nothing on Windows (see the module note).+pub fn set_mode(path: &Path, mode: u32) -> std::io::Result<()> {+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode))+ }+ #[cfg(not(unix))]+ {+ let _ = (path, mode);+ Ok(())+ }+}++/// The permission bits of a file (`mode & 0o777`). Windows has only read-only or not: 0444 or+/// 0644.+pub fn mode_of(meta: &std::fs::Metadata) -> u32 {+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ meta.permissions().mode() & 0o777+ }+ #[cfg(not(unix))]+ {+ if meta.permissions().readonly() {+ 0o444+ } else {+ 0o644+ }+ }+}++/// SYSTEM's well-known SID, the same in every Windows language.+#[cfg(windows)]+pub const SYSTEM_SID: &str = "S-1-5-18";++/// The current user's SID (`S-1-5-21-…`), from `whoami /user`.+#[cfg(windows)]+pub fn current_user_sid() -> Option<String> {+ use std::os::windows::process::CommandExt;+ let out = std::process::Command::new("whoami")+ .args(["/user", "/fo", "csv", "/nh"])+ .creation_flags(CREATE_NO_WINDOW)+ .output()+ .ok()?;+ if !out.status.success() {+ return None;+ }+ sid_from_whoami(&String::from_utf8_lossy(&out.stdout))+}++#[cfg(windows)]+const CREATE_NO_WINDOW: u32 = 0x0800_0000;++/// The SID in `whoami /user /fo csv /nh` output: `"pc\name","S-1-5-21-…"`.+#[cfg_attr(not(windows), allow(dead_code))]+fn sid_from_whoami(text: &str) -> Option<String> {+ let sid = text.trim().rsplit(',').next()?.trim().trim_matches('"');+ let ok = sid.starts_with("S-1-") && sid.len() > 4 && sid[4..].chars().all(|c| c.is_ascii_digit() || c == '-');+ ok.then(|| sid.to_string())+}++/// Limits `dir` to the current user and SYSTEM, for the folders and everything below them+/// (Windows: no inherited entries, `(OI)(CI)F` for the two; plan decision 4). Mac and Linux+/// set 0700 on the data dir elsewhere, so this does nothing there. A failure is logged as a+/// warning and never stops kwant.+pub fn restrict_to_user(dir: &Path) {+ #[cfg(windows)]+ if let Err(e) = restrict_windows(dir) {+ tracing::warn!("could not limit {} to this user: {e}", dir.display());+ }+ #[cfg(not(windows))]+ let _ = dir;+}++#[cfg(windows)]+fn restrict_windows(dir: &Path) -> Result<(), String> {+ use std::os::windows::process::CommandExt;+ let sid = current_user_sid().ok_or("no user SID from whoami")?;+ // `*SID` names an account by SID, so a localized "SYSTEM" or a domain user never matters+ let out = std::process::Command::new("icacls")+ .arg(dir)+ .args(["/inheritance:r", "/grant:r"])+ .arg(format!("*{sid}:(OI)(CI)F"))+ .arg(format!("*{SYSTEM_SID}:(OI)(CI)F"))+ .arg("/q")+ .creation_flags(CREATE_NO_WINDOW)+ .output()+ .map_err(|e| format!("icacls: {}", e.kind()))?;+ icacls_answer(out)?;+ // `/grant:r` leaves other explicit entries; a folder made by an elevated process carries one for+ // BUILTIN\Administrators from the token's default access list, so drop it by its SID+ let out = std::process::Command::new("icacls")+ .arg(dir)+ .args(["/remove:g", &format!("*{ADMINISTRATORS_SID}"), "/q"])+ .creation_flags(CREATE_NO_WINDOW)+ .output()+ .map_err(|e| format!("icacls: {}", e.kind()))?;+ icacls_answer(out)+}++#[cfg(windows)]+const ADMINISTRATORS_SID: &str = "S-1-5-32-544";++#[cfg(windows)]+fn icacls_answer(out: std::process::Output) -> Result<(), String> {+ if out.status.success() {+ Ok(())+ } else {+ let said = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));+ Err(format!("icacls exited with {}: {}", out.status, said.trim().chars().take(300).collect::<String>()))+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn whoami_csv_gives_the_sid() {+ assert_eq!(+ sid_from_whoami("\"desktop-1\\alex\",\"S-1-5-21-1004336348-1177238915-682003330-1001\"\r\n").as_deref(),+ Some("S-1-5-21-1004336348-1177238915-682003330-1001")+ );+ assert_eq!(sid_from_whoami("ERROR: no"), None);+ assert_eq!(sid_from_whoami("\"x\",\"S-1-\""), None);+ assert_eq!(sid_from_whoami("\"x\",\"S-1-5-21 & calc\""), None);+ }++ #[test]+ fn modes_round_trip_where_there_are_modes() {+ let tmp = tempfile::tempdir().unwrap();+ let f = tmp.path().join("f");+ let mut o = std::fs::OpenOptions::new();+ let mut file = o.write(true).create_new(true).unix_mode(0o600).open(&f).unwrap();+ std::io::Write::write_all(&mut file, b"x").unwrap();+ drop(file);+ let m = mode_of(&std::fs::metadata(&f).unwrap());+ if cfg!(unix) {+ assert_eq!(m, 0o600);+ set_mode(&f, 0o640).unwrap();+ assert_eq!(mode_of(&std::fs::metadata(&f).unwrap()), 0o640);+ } else {+ assert_eq!(m, 0o644);+ set_mode(&f, 0o640).unwrap();+ }+ std::fs::DirBuilder::new().unix_mode(0o700).create(tmp.path().join("d")).unwrap();+ assert!(tmp.path().join("d").is_dir());+ }++ /// The SIDs on `path`'s access list, and whether any entry is inherited, read back with+ /// PowerShell (`Get-Acl`), independent of how `icacls` wrote them.+ #[cfg(windows)]+ fn acl_sids(path: &Path) -> (Vec<String>, bool) {+ let script = format!(+ "(Get-Acl -LiteralPath '{}').Access | ForEach-Object {{ $_.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value + ' ' + $_.IsInherited }}",+ path.display().to_string().replace('\'', "''")+ );+ // PowerShell 7 (the CI's shell) leaves its own module path behind, which Windows+ // PowerShell can't load Get-Acl from; without it Windows PowerShell uses its default+ let out = std::process::Command::new("powershell")+ .env_remove("PSModulePath")+ .args(["-NoProfile", "-NonInteractive", "-Command", &script])+ .output()+ .unwrap();+ assert!(out.status.success(), "Get-Acl: {}", String::from_utf8_lossy(&out.stderr));+ let text = String::from_utf8_lossy(&out.stdout);+ let mut sids = Vec::new();+ let mut inherited = false;+ for line in text.lines().map(str::trim).filter(|l| !l.is_empty()) {+ let (sid, inh) = line.split_once(' ').unwrap();+ sids.push(sid.to_string());+ inherited |= inh.eq_ignore_ascii_case("true");+ }+ sids.sort();+ sids.dedup();+ (sids, inherited)+ }++ /// Plan decision 4: `.kwnt` is the current user's and SYSTEM's only, and so is a key file+ /// that was already in it.+ #[cfg(windows)]+ #[test]+ fn the_data_dir_is_limited_to_this_user_and_system() {+ let tmp = tempfile::tempdir().unwrap();+ let dir = tmp.path().join(".kwnt");+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(dir.join("api-token"), "t").unwrap();+ let user = current_user_sid().expect("whoami gives a SID");+ let before = acl_sids(&dir).0;+ assert!(before.len() > 2, "a temp folder starts with more than two entries: {before:?}");+ restrict_windows(&dir).expect("icacls limits the folder");+ let mut want = vec![user, SYSTEM_SID.to_string()];+ want.sort();+ let (sids, inherited) = acl_sids(&dir);+ assert!(!inherited, "no entry inherited from the profile: {sids:?}");+ assert_eq!(sids, want, "the folder");+ // The file inherits the folder's two entries, nothing else+ let (file_sids, _) = acl_sids(&dir.join("api-token"));+ assert_eq!(file_sids, want, "a file already in it");+ // ...and so does one made afterwards+ std::fs::write(dir.join("later"), "t").unwrap();+ assert_eq!(acl_sids(&dir.join("later")).0, want, "a file made afterwards");+ }+}diff --git a/src/lib.rs b/src/lib.rsindex 8a7586cf..0330c388 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -8,6 +8,7 @@ pub mod doctor;pub mod documents;pub mod drivers;pub mod embedded;+pub mod fsx;pub mod import;pub mod mcp;pub mod parallel;diff --git a/src/mcp/builtin_tools.rs b/src/mcp/builtin_tools.rsindex 55d5719b..89e158c0 100644--- a/src/mcp/builtin_tools.rs+++ b/src/mcp/builtin_tools.rs@@ -260,6 +260,18 @@ const CREDENTIAL_FOLDERS: &[&str] = &["library/application support/bitwarden", "library/application support/code/user/globalstorage", "library/cookies","library/safari", "library/containers/com.apple.safari", "library/group containers",];+/// Where Windows keeps browser profiles, signed-in apps and its own stored passwords and keys+/// (under `%LOCALAPPDATA%` and `%APPDATA%`).+#[cfg(windows)]+const WINDOWS_CREDENTIAL_FOLDERS: &[&str] = &[+ "appdata/local/google/chrome", "appdata/local/chromium", "appdata/local/microsoft/edge",+ "appdata/local/bravesoftware", "appdata/local/vivaldi", "appdata/roaming/opera software",+ "appdata/roaming/mozilla", "appdata/local/mozilla", "appdata/roaming/1password", "appdata/local/1password",+ "appdata/roaming/bitwarden", "appdata/roaming/bitwarden cli", "appdata/roaming/gh", "appdata/roaming/github cli",+ "appdata/roaming/gcloud", "appdata/roaming/code/user/globalstorage", "appdata/roaming/microsoft/protect",+ "appdata/roaming/microsoft/credentials", "appdata/local/microsoft/credentials", "appdata/roaming/microsoft/crypto",+ "appdata/roaming/microsoft/systemcertificates", "appdata/local/packages",+];/// File endings of keys, certificates and password vaults.const CREDENTIAL_ENDINGS: &[&str] = &[".pem", ".key", ".p12", ".pfx", ".jks", ".keystore", ".kdbx", ".ppk", ".asc", ".gpg"];/// Live process and device data: `/proc/self/environ` holds the gateway token.@@ -271,13 +283,31 @@ const SYSTEM_SECRETS: &[&str] = &["/etc/shadow", "/etc/gshadow", "/etc/master.pa/// Whether `path` (absolute) is live system data or names a credential, and why (`{}` stands/// for the path as the bot wrote it).fn denied_place(path: &Path) -> Option<&'static str> {- let p = path.to_string_lossy().to_lowercase();+ let p = path_text(path);if SYSTEM_PLACES.iter().any(|s| p == *s || p.starts_with(&format!("{s}/"))) {return Some("{} is live system data and can hold secrets");}(credential_text(&p) || system_secret(&p)).then_some("{} can hold passwords or keys")}+/// `path` as lowercase text with `/` between its parts, the form the name checks read. On+/// Windows `\` becomes `/` and the `\\?\` and drive prefixes go, so `C:\Users\x\.ssh` reads as+/// `/users/x/.ssh` (a UNC share `\\host\share` as `//host/share`).+fn path_text(path: &Path) -> String {+ let p = path.to_string_lossy().to_lowercase();+ #[cfg(windows)]+ let p = {+ let slashed = p.replace('\\', "/");+ let bare = match slashed.strip_prefix("//?/") {+ Some(rest) => rest.strip_prefix("unc/").map_or_else(|| rest.to_string(), |share| format!("//{share}")),+ None => slashed,+ };+ let drive = bare.len() >= 2 && bare.as_bytes()[0].is_ascii_alphabetic() && bare.as_bytes()[1] == b':';+ if drive { bare[2..].to_string() } else { bare }+ };+ p+}+/// Whether a lowercase absolute path is one of [`SYSTEM_SECRETS`] (`/etc/shadow-` and/// `/etc/sudoers.d` included) or an ssh host key in `/etc/ssh`.fn system_secret(p: &str) -> bool {@@ -291,7 +321,23 @@ fn credential_text(p: &str) -> bool {let parts: Vec<&str> = p.split('/').filter(|c| !c.is_empty()).collect();parts.iter().any(|c| {CREDENTIAL_NAMES.contains(c) || c.starts_with(".env") || CREDENTIAL_ENDINGS.iter().any(|e| c.ends_with(e))- }) || CREDENTIAL_FOLDERS.iter().any(|f| {+ }) || credential_folder(p, CREDENTIAL_FOLDERS)+ || windows_credential_folder(p)+}++#[cfg(windows)]+fn windows_credential_folder(p: &str) -> bool {+ credential_folder(p, WINDOWS_CREDENTIAL_FOLDERS)+}++#[cfg(not(windows))]+fn windows_credential_folder(_: &str) -> bool {+ false+}++/// Whether a lowercase path is in (or is) one of `folders`.+fn credential_folder(p: &str, folders: &[&str]) -> bool {+ folders.iter().any(|f| {let tail = format!("/{f}");p.contains(&format!("{tail}/")) || p.ends_with(&tail) || p.starts_with(&format!("{f}/")) || p == *f})@@ -306,6 +352,13 @@ fn broad_search(root: &Path) -> Option<String> {let real = resolve(root).unwrap_or_else(|| lexical(root));let shown = real.display();let homes = std::env::var_os("HOME").map(PathBuf::from).into_iter().chain(["/home", "/Users", "/root"].map(PathBuf::from));+ // Windows homes: %USERPROFILE% and the folder holding every user's+ #[cfg(windows)]+ let homes = homes.chain(std::env::var_os("USERPROFILE").map(PathBuf::from)).chain(std::env::var_os("SystemDrive").map(|d| {+ let mut users = PathBuf::from(d);+ users.push("\\Users");+ users+ }));for home in homes {let home = home.canonicalize().unwrap_or(home);if home.starts_with(&real) {@@ -325,7 +378,7 @@ fn broad_search(root: &Path) -> Option<String> {return Some(format!("{shown} is too big for kwnt to check for passwords and keys"));}let path = entry.path();- let lower = path.to_string_lossy().to_lowercase();+ let lower = path_text(&path);if credential_text(&lower) || system_secret(&lower) {return Some(format!("{} can hold passwords or keys", path.display()));}@@ -531,6 +584,8 @@ mod tests {std::os::unix::fs::symlink(ws.join("src"), ws.join("inner")).unwrap();assert!(is_inside(&ws, "inner/ok.rs"), "a symlink within the folder stays inside");}+ #[cfg(not(unix))]+ let _ = tmp;}#[test]@@ -692,8 +747,11 @@ mod tests {#[test]fn smart_searches_from_root_home_or_above_credentials_ask() {let (tmp, ws) = folder();- let home = std::env::var("HOME").unwrap_or_else(|_| "/root".into());- for root in ["/", "/home", "/Users", home.as_str()] {+ #[cfg(unix)]+ let (home, homes) = (std::env::var("HOME").unwrap_or_else(|_| "/root".into()), ["/home", "/Users"]);+ #[cfg(windows)]+ let (home, homes) = (std::env::var("USERPROFILE").unwrap(), [r"C:\Users", "/Users"]);+ for root in ["/", homes[0], homes[1], home.as_str()] {assert!(!smart("Grep", json!({"pattern": "x", "path": root}), &ws), "Grep {root}");assert!(!smart("Glob", json!({"pattern": "**/*", "path": root}), &ws), "Glob {root}");}@@ -708,6 +766,31 @@ mod tests {assert!(!smart("Glob", json!({"pattern": format!("{other_s}/**/*")}), &ws));}+ #[cfg(windows)]+ #[test]+ fn smart_windows_paths_with_backslashes_and_drives_ask() {+ let (_tmp, ws) = folder();+ for path in [+ r"C:\Users\x\.ssh\id_rsa",+ r"c:\users\x\.SSH\id_ed25519",+ r"C:\Users\x\.kwnt\secrets.json",+ r"\\?\C:\Users\x\.aws\credentials",+ r"\\host\share\x\.env",+ r"D:\keys\server.pem",+ r"C:\Users\x\AppData\Roaming\gh\hosts.yml",+ r"C:\Users\x\AppData\Local\Google\Chrome\User Data\Default\Cookies",+ r"C:\Users\x\AppData\Roaming\Microsoft\Protect\S-1-5-21\key",+ r"C:\Users\x\AppData\Local\Microsoft\Credentials\ABC",+ "C:/Users/x/.ssh/config",+ ] {+ assert!(!smart("Read", json!({"file_path": path}), &ws), "{path}");+ }+ assert!(!smart("Grep", json!({"pattern": "x", "path": r"C:\"}), &ws), "a whole drive");+ assert!(smart("Read", json!({"file_path": r"C:\Windows\win.ini"}), &ws), "ordinary reads outside still run");+ assert_eq!(path_text(Path::new(r"\\?\UNC\host\share\A")), "//host/share/a");+ assert_eq!(path_text(Path::new(r"C:\Users\X")), "/users/x");+ }+#[test]fn globs_cannot_escape_through_their_pattern() {let (tmp, ws) = folder();diff --git a/src/mcp/shell_risk.rs b/src/mcp/shell_risk.rsindex e39f734c..1d7ebda9 100644--- a/src/mcp/shell_risk.rs+++ b/src/mcp/shell_risk.rs@@ -1846,9 +1846,9 @@ mod tests {}#[test]+ #[cfg(unix)]fn a_symlink_out_of_the_folder_is_outside() {let (tmp, ws) = folder();- #[cfg(unix)]{std::os::unix::fs::symlink(tmp.path(), ws.join("up")).unwrap();assert!(!classify("rm -rf up/other", &ws).is_allowed());diff --git a/src/profiles/mod.rs b/src/profiles/mod.rsindex ea28c6aa..fa24be6e 100644--- a/src/profiles/mod.rs+++ b/src/profiles/mod.rs@@ -256,7 +256,7 @@ impl CliEnv {/// `bin` run on the profile's home: env applied and [`Self::args`] in place, ready for the/// subcommand's own arguments.pub fn command(&self, bin: impl AsRef<std::ffi::OsStr>) -> tokio::process::Command {- let mut cmd = tokio::process::Command::new(bin);+ let mut cmd = crate::drivers::cli::cli_command(bin);self.apply(&mut cmd);cmd.args(&self.args);cmddiff --git a/src/profiles/status.rs b/src/profiles/status.rsindex 5d157b92..67b94768 100644--- a/src/profiles/status.rs+++ b/src/profiles/status.rs@@ -200,7 +200,7 @@ pub async fn probe(engine: Engine, home: Option<&Path>) -> ProfileStatus {};let mut cmd = match home {Some(home) => super::CliEnv::for_home(engine, home).command(bin),- None => tokio::process::Command::new(bin),+ None => crate::drivers::cli::cli_command(bin),};match engine {Engine::Claude => cmd.args(["auth", "status", "--json"]),diff --git a/src/routines.rs b/src/routines.rsindex 11aaa6aa..bfd5c6e0 100644--- a/src/routines.rs+++ b/src/routines.rs@@ -3,6 +3,7 @@use chrono::{DateTime, Datelike, Duration, LocalResult, NaiveDate, NaiveTime, Utc, Weekday};use serde::{Deserialize, Serialize};+#[cfg(not(windows))]use std::path::Path;/// Shortest interval a routine may repeat at.@@ -103,6 +104,7 @@ fn parse_time(time: &str) -> Result<NaiveTime, String> {}/// Where the system tz database lives (Linux, macOS, BSDs).+#[cfg(not(windows))]const ZONEINFO_DIRS: &[&str] = &["/usr/share/zoneinfo", "/usr/lib/zoneinfo", "/etc/zoneinfo"];/// An IANA time zone read from the system tz database. Reading it per use (rather than@@ -199,9 +201,12 @@ fn parse_tz(tz: &str) -> Result<Zone, String> {if !well_formed {return Err(unknown());}- ZONEINFO_DIRS- .iter()- .find_map(|dir| std::fs::read(Path::new(dir).join(name)).ok())+ #[cfg(not(windows))]+ let bytes = ZONEINFO_DIRS.iter().find_map(|dir| std::fs::read(Path::new(dir).join(name)).ok());+ // Windows ships no tz database, so the IANA zones come bundled+ #[cfg(windows)]+ let bytes = tzdb_data::find_raw(name.as_bytes()).map(<[u8]>::to_vec);+ bytes.and_then(|bytes| tz::TimeZone::from_tz_data(&bytes).ok()).map(Zone).ok_or_else(unknown)diff --git a/src/sandbox/computer.rs b/src/sandbox/computer.rsindex 6ab32446..36317b55 100644--- a/src/sandbox/computer.rs+++ b/src/sandbox/computer.rs@@ -64,7 +64,11 @@ pub fn default_mode(os: &str, env: Option<&str>) -> ComputerMode {}/// A valid saved choice wins over the env/platform default.+/// On Windows (0.7.6 beta) it is always local: the isolated vm computer isn't there yet.pub fn effective_mode(saved: Option<&str>, os: &str, env: Option<&str>) -> ComputerMode {+ if os == "windows" {+ return ComputerMode::Local;+ }saved.and_then(ComputerMode::parse).unwrap_or_else(|| default_mode(os, env))@@ -188,9 +192,15 @@ pub fn window_unavailable_reason(display: bool) -> Option<String> {(!display).then(|| "This computer has no screen to show a browser window on (no display).".into())}+/// The vm computer's reason on Windows (0.7.6 beta: no isolated desktop, Xvfb or rlimits there).+pub const VM_NOT_ON_WINDOWS: &str = "The isolated computer is not available on Windows yet. Bots use this computer.";+/// Why vm mode cannot run here, or `None` if it can. A configured browser service URL is enough/// for the browser even without Docker.pub fn vm_unavailable_reason(docker: bool, browser_url_configured: bool, platform: Platform) -> Option<String> {+ if cfg!(windows) {+ return Some(VM_NOT_ON_WINDOWS.into());+ }(!docker && !browser_url_configured).then(|| match platform {Platform::Docker => format!("No browser service is set for this container. {}", doctor::vm_fix(platform)),_ => format!("Docker is not installed or not running. {}", doctor::vm_fix(platform)),@@ -808,6 +818,10 @@ mod tests {assert_eq!(window_unavailable_reason(true), None);assert!(window_unavailable_reason(false).unwrap().contains("display"));+ if cfg!(windows) {+ assert_eq!(vm_unavailable_reason(true, true, Platform::Linux).as_deref(), Some(VM_NOT_ON_WINDOWS));+ return;+ }assert_eq!(vm_unavailable_reason(true, false, Platform::Linux), None);assert_eq!(vm_unavailable_reason(false, true, Platform::Docker), None);// each platform gets its own advice: no "Docker Desktop on a Mac" on a Linux server@@ -818,6 +832,16 @@ mod tests {assert!(docker.contains("KWNT_BROWSER_CDP_URL") && docker.contains("docker compose up -d browser"), "{docker}");}+ #[test]+ fn windows_always_uses_this_computer() {+ assert_eq!(effective_mode(None, "windows", None), ComputerMode::Local);+ assert_eq!(effective_mode(Some("vm"), "windows", Some("vm")), ComputerMode::Local);+ // Mac and Linux keep their defaults and saved choices+ assert_eq!(effective_mode(None, "linux", None), ComputerMode::Vm);+ assert_eq!(effective_mode(Some("vm"), "macos", None), ComputerMode::Vm);+ assert!(VM_NOT_ON_WINDOWS.contains("not available on Windows yet"));+ }+#[test]fn vm_isolates_the_built_in_shell_only_with_docker() {// Mac/Linux with Docker: the browser and the executor shell both run in containers@@ -963,6 +987,7 @@ mod tests {}/// A pid that is not running: a child that already exited and was reaped.+ #[cfg(unix)]fn dead_pid() -> u32 {let mut child = std::process::Command::new("true").spawn().unwrap();let pid = child.id();diff --git a/src/serve.rs b/src/serve.rsindex f4f45e13..088b40c7 100644--- a/src/serve.rs+++ b/src/serve.rs@@ -21,6 +21,12 @@ pub type ServeError = Box<dyn std::error::Error + Send + Sync>;/// Runs the server on `config.host:config.port` until `shutdown` resolves, then stops the/// background jobs, stops kwant's browser container and gives the Laya sidecar up to 5 s to exit.pub async fn run(config: Config, shutdown: impl Future<Output = ()>) -> Result<(), ServeError> {+ #[cfg(windows)]+ {+ // Keys, tokens and logins live here: this user and SYSTEM only, before anything is in it+ let _ = std::fs::create_dir_all(&config.data_dir);+ crate::fsx::restrict_to_user(&config.data_dir);+ }let db = Database::init(&config.data_dir).await?;restrict_data_dir(&config.data_dir);let tools = ToolRunner::new(config.data_dir.join("workspace"));diff --git a/src/server/dev/floor.rs b/src/server/dev/floor.rsindex 6fae0ce7..0e2efcae 100644--- a/src/server/dev/floor.rs+++ b/src/server/dev/floor.rs@@ -76,8 +76,8 @@ pub fn head_branch(cwd: &Path) -> Option<String> {dir = d.parent();continue;}- Ok(m) if m.is_dir() => gitfile::read(&d.join(".git"), "HEAD", gitfile::REF_MAX)?,- Ok(m) if m.is_file() => worktree_head(d)?,+ Ok(m) if gitfile::plain_dir(&m) => gitfile::read(&d.join(".git"), "HEAD", gitfile::REF_MAX)?,+ Ok(m) if gitfile::plain_file(&m) => worktree_head(d)?,Ok(_) => return None,};let r = head.trim().strip_prefix("ref: ")?.trim();@@ -111,7 +111,7 @@ fn worktree_head(d: &Path) -> Option<String> {let mut at: PathBuf = parts[..shared].iter().collect();for c in &parts[shared..] {at.push(c);- if !std::fs::symlink_metadata(&at).ok()?.file_type().is_dir() {+ if !gitfile::plain_dir(&std::fs::symlink_metadata(&at).ok()?) {return None;}}@@ -127,7 +127,7 @@ fn lexical(p: &Path) -> Option<PathBuf> {match c {Component::CurDir => {}Component::ParentDir => {- let real_dir = !out.as_os_str().is_empty() && std::fs::symlink_metadata(&out).is_ok_and(|m| m.file_type().is_dir());+ let real_dir = !out.as_os_str().is_empty() && std::fs::symlink_metadata(&out).is_ok_and(|m| gitfile::plain_dir(&m));if !real_dir || !out.pop() {return None;}@@ -258,6 +258,46 @@ mod tests {assert_eq!(head_within_5s(&wt), None, "worktree HEAD FIFO");}+ /// Windows: the same refusals without symlinks or FIFOs. A junction as `.git` or on a+ /// worktree's gitdir, a `..` after one, and a hard-linked HEAD are `None`; a plain repo and a+ /// worktree whose gitdir uses `C:/...` with forward slashes (as Git for Windows writes) read.+ #[cfg(windows)]+ #[test]+ fn head_branch_refuses_junctions_and_hard_links_on_windows() {+ use crate::server::gitfile::windows_tests::junction;+ let (d, root) = head_repo();+ assert_eq!(head_within_5s(&root).as_deref(), Some("lin-dev-core"), "a plain repo");+ let other = d.path().join("other");+ std::fs::create_dir_all(other.join(".git/worktrees/wt")).unwrap();+ std::fs::write(other.join(".git/HEAD"), "ref: refs/heads/LEAKED\n").unwrap();+ std::fs::write(other.join(".git/worktrees/wt/HEAD"), "ref: refs/heads/LEAKED\n").unwrap();+ let linked = d.path().join("linked");+ std::fs::create_dir_all(&linked).unwrap();+ junction(&linked.join(".git"), &other.join(".git"));+ assert_eq!(head_within_5s(&linked), None, ".git a junction");+ let wt = d.path().join("wt");+ std::fs::create_dir_all(&wt).unwrap();+ junction(&wt.join("hop"), &other);+ std::fs::write(wt.join(".git"), "gitdir: hop/.git/worktrees/wt\n").unwrap();+ assert_eq!(head_within_5s(&wt), None, "gitdir through a junction");+ std::fs::write(wt.join(".git"), "gitdir: hop/../../other/.git/worktrees/wt\n").unwrap();+ assert_eq!(head_within_5s(&wt), None, "`..` after a junction");+ // a real worktree, gitdir written the Git for Windows way+ std::fs::create_dir_all(root.join(".git/worktrees/w2")).unwrap();+ std::fs::write(root.join(".git/worktrees/w2/HEAD"), "ref: refs/heads/side\n").unwrap();+ let w2 = d.path().join("w2");+ std::fs::create_dir_all(&w2).unwrap();+ let gd = root.join(".git/worktrees/w2").display().to_string().replace('\\', "/");+ std::fs::write(w2.join(".git"), format!("gitdir: {gd}\n")).unwrap();+ assert_eq!(head_within_5s(&w2).as_deref(), Some("side"), "{gd}");+ // HEAD as a second name of a host file+ let host = d.path().join("host-file");+ std::fs::write(&host, "ref: refs/heads/LEAKED\n").unwrap();+ std::fs::remove_file(root.join(".git/HEAD")).unwrap();+ std::fs::hard_link(&host, root.join(".git/HEAD")).unwrap();+ assert_eq!(head_within_5s(&root), None, "a hard-linked HEAD");+ }+/// F-2: a HEAD that is another name for some other file isn't read.#[cfg(unix)]#[test]diff --git a/src/server/dev/git.rs b/src/server/dev/git.rsindex 8d454322..16c7f734 100644--- a/src/server/dev/git.rs+++ b/src/server/dev/git.rs@@ -377,6 +377,11 @@ async fn run_once(bin: &str, git_dir: Option<&Path>, args: &[&str], o: Opts<'_>,Ok(())});}+ // Windows has no setsid, nice or RLIMIT_FSIZE: git runs below normal priority with no+ // console window, and a mirror's size is checked after each fetch (`Repo::cap`) instead of+ // stopping the write at the cap.+ #[cfg(windows)]+ cmd.creation_flags(CREATE_NO_WINDOW | BELOW_NORMAL_PRIORITY_CLASS);let mut child = cmd.spawn().map_err(|e| if e.kind() == std::io::ErrorKind::NotFound { GitError::NoGit } else { GitError::Failed })?;let mut group = crate::drivers::cli::ProcessGroup::of(&child);let (so, se) = (child.stdout.take(), child.stderr.take());@@ -400,6 +405,11 @@ async fn run_once(bin: &str, git_dir: Option<&Path>, args: &[&str], o: Opts<'_>,}}+#[cfg(windows)]+const CREATE_NO_WINDOW: u32 = 0x0800_0000;+#[cfg(windows)]+const BELOW_NORMAL_PRIORITY_CLASS: u32 = 0x0000_4000;+/// Whether a size-limited git (or the index-pack it ran) stopped at `RLIMIT_FSIZE`: killed by/// SIGXFSZ, or told "File too large" if that signal is ignored.fn hit_size_limit(status: &std::process::ExitStatus, stderr: &[u8]) -> bool {@@ -412,7 +422,11 @@ fn hit_size_limit(status: &std::process::ExitStatus, stderr: &[u8]) -> bool {}let _ = status;let e = String::from_utf8_lossy(stderr).to_lowercase();- e.contains(&format!("died of signal {}", libc::SIGXFSZ)) || e.contains("file too large")+ #[cfg(unix)]+ if e.contains(&format!("died of signal {}", libc::SIGXFSZ)) {+ return true;+ }+ e.contains("file too large")}/// [`read_capped`]; with `head`, the first `cap` bytes and `true` once it passes `cap` (and `r`@@ -1614,6 +1628,7 @@ mod tests {/// the script then fails with "text file busy" (ETXTBSY), which `run` reports as `Failed`./// So the bytes go to a draft, and a separate `cp` makes the real file: the only fd ever open/// for writing on it lives and dies in that `cp`, which has exited before anything runs it.+ #[cfg(unix)]fn exe(path: &Path, text: &str) {let draft = path.with_extension("draft");std::fs::write(&draft, text).unwrap();@@ -1909,6 +1924,8 @@ mod tests {assert!(available().await, "the test machine has git {MIN_VERSION:?} or newer");}+ // Unix only: the fake git is a `#!/bin/sh` script, which Windows can't run as a program+ #[cfg(unix)]#[tokio::test]async fn a_slow_git_is_killed_with_its_children() {let tmp = tempfile::tempdir().unwrap();@@ -1926,6 +1943,8 @@ mod tests {assert!(!alive, "the grandchild was killed with the group");}+ // Unix only: the fake git is a `#!/bin/sh` script, which Windows can't run as a program+ #[cfg(unix)]#[tokio::test]async fn the_token_reaches_git_by_environment_only() {let tmp = tempfile::tempdir().unwrap();@@ -2340,6 +2359,8 @@ mod tests {/// F1 (probe P1): an ssh remote runs `ssh`, never an empty command, whatever the repo's own/// config says. A fake `ssh` first on PATH logs what git asked it for.+ // Unix only: the fake git is a `#!/bin/sh` script, which Windows can't run as a program+ #[cfg(unix)]#[tokio::test]async fn ssh_remotes_run_ssh_and_never_the_repos_own_command() {let tmp = tempfile::tempdir().unwrap();@@ -2403,6 +2424,8 @@ mod tests {}/// F2 (probe P3, setup 2): a `.git` symlink is refused.+ // Unix only: making a symlink on Windows needs admin rights or Developer Mode+ #[cfg(unix)]#[tokio::test]async fn a_git_symlink_is_refused() {let tmp = tempfile::tempdir().unwrap();@@ -2428,6 +2451,8 @@ mod tests {/// F2: the same reach by other routes: a `.git` directory with a `commondir`, or with its/// objects or refs a symlink to another repo's.+ // Unix only: making a symlink on Windows needs admin rights or Developer Mode+ #[cfg(unix)]#[tokio::test]async fn a_git_dir_borrowing_another_repos_objects_or_refs_is_refused() {let tmp = tempfile::tempdir().unwrap();diff --git a/src/server/dev/repo.rs b/src/server/dev/repo.rsindex f2e4cf42..e5a8c07b 100644--- a/src/server/dev/repo.rs+++ b/src/server/dev/repo.rs@@ -988,6 +988,8 @@ mod tests {}}+ // Unix only: making a symlink on Windows needs admin rights or Developer Mode+ #[cfg(unix)]#[tokio::test]async fn a_team_folder_whose_git_is_a_symlink_to_another_repo_is_not_detected() {let tmp = tempfile::tempdir().unwrap();diff --git a/src/server/dev/scan/gitleaks.rs b/src/server/dev/scan/gitleaks.rsindex 6e6d751e..40c33bdf 100644--- a/src/server/dev/scan/gitleaks.rs+++ b/src/server/dev/scan/gitleaks.rs@@ -352,6 +352,7 @@ impl TempDir {static N: AtomicU64 = AtomicU64::new(0);let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);let p = std::env::temp_dir().join(format!("kwant-scan-{}-{nanos}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));+ #[cfg_attr(not(unix), allow(unused_mut))]let mut b = std::fs::DirBuilder::new();#[cfg(unix)]{diff --git a/src/server/gitfile.rs b/src/server/gitfile.rsindex b634a4ec..6185d1e8 100644--- a/src/server/gitfile.rs+++ b/src/server/gitfile.rs@@ -1,6 +1,9 @@//! Reading small files under a `.git` that a bot can write (missions' `git_head`, Dev mode's//! `head_branch`). Everything there is untrusted: never follow a symlink, never block on a FIFO,//! socket or device, never read a hard link (it may be a host file's other name), and cap sizes.+//! On Windows the same refusals hold for every reparse point (symlink, junction, mount point,+//! cloud placeholder), DOS device names (`CON`, `NUL`, `COM1`...) and alternate data streams; a+//! file that can't be checked that way is `None`, never read some weaker way.use std::io::Read;use std::path::Path;@@ -17,10 +20,14 @@ pub(crate) fn read(base: &Path, rel: &str, max: u64) -> Option<String> {let mut at = base.to_path_buf();let parts: Vec<&str> = rel.split('/').collect();for (i, p) in parts.iter().enumerate() {+ #[cfg(windows)]+ if !windows_plain_name(p) {+ return None;+ }at.push(p);- let ft = std::fs::symlink_metadata(&at).ok()?.file_type();+ let m = std::fs::symlink_metadata(&at).ok()?;let last = i + 1 == parts.len();- if (last && !ft.is_file()) || (!last && !ft.is_dir()) {+ if (last && !plain_file(&m)) || (!last && !plain_dir(&m)) {return None;}}@@ -32,6 +39,13 @@ pub(crate) fn read(base: &Path, rel: &str, max: u64) -> Option<String> {// A symlink swapped in after the check fails to open; a FIFO opens without waitingo.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);}+ #[cfg(windows)]+ {+ use std::os::windows::fs::OpenOptionsExt;+ // A symlink or junction swapped in after the check opens as itself, not its target, and+ // the handle check below refuses it+ o.custom_flags(windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT);+ }let f = o.open(&at).ok()?;let m = f.metadata().ok()?;if !m.file_type().is_file() || m.len() > max {@@ -45,6 +59,10 @@ pub(crate) fn read(base: &Path, rel: &str, max: u64) -> Option<String> {return None;}}+ #[cfg(windows)]+ if !windows_one_plain_file(&f) {+ return None;+ }let mut buf = Vec::with_capacity(m.len() as usize);f.take(max + 1).read_to_end(&mut buf).ok()?;if buf.len() as u64 > max {@@ -53,6 +71,71 @@ pub(crate) fn read(base: &Path, rel: &str, max: u64) -> Option<String> {String::from_utf8(buf).ok()}+/// `m` (from `symlink_metadata`) is a real folder: not a symlink and, on Windows, no reparse point+/// of any kind. On Mac and Linux this is `is_dir()` of the unfollowed type, as before.+pub(crate) fn plain_dir(m: &std::fs::Metadata) -> bool {+ m.file_type().is_dir() && !reparse_point(m)+}++/// `m` (from `symlink_metadata`) is a regular file, never a link or (on Windows) a reparse point.+pub(crate) fn plain_file(m: &std::fs::Metadata) -> bool {+ m.file_type().is_file() && !reparse_point(m)+}++/// Any reparse point: std only calls the name-surrogate ones (symlinks, junctions) links, and a+/// placeholder or app link would otherwise pass as a plain file or folder.+#[cfg(windows)]+fn reparse_point(m: &std::fs::Metadata) -> bool {+ use std::os::windows::fs::MetadataExt;+ m.file_attributes() & windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT != 0+}++#[cfg(not(windows))]+fn reparse_point(_: &std::fs::Metadata) -> bool {+ false+}++/// A path component Windows takes as the file it names: no `:` (a drive or a data stream), no+/// `\`, no trailing `.` or space (dropped by Win32), and not a DOS device (`CON`, `NUL.txt`...).+#[cfg(any(windows, test))]+fn windows_plain_name(p: &str) -> bool {+ const DEVICES: [&str; 4] = ["CON", "PRN", "AUX", "NUL"];+ let stem = p.split('.').next().unwrap_or("").trim_end_matches(' ').to_ascii_uppercase();+ let numbered = |pre: &str| {+ stem.strip_prefix(pre).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "\u{b9}" | "\u{b2}" | "\u{b3}"))+ };+ !p.is_empty()+ && !p.contains([':', '\\'])+ && !p.ends_with(['.', ' '])+ && !DEVICES.contains(&stem.as_str())+ && !numbered("COM")+ && !numbered("LPT")+}++/// The open handle is a file on disk (not a console, pipe or device), not a reparse point or a+/// folder, with exactly one name (git never hard-links these). Anything unreadable is `false`.+#[cfg(windows)]+fn windows_one_plain_file(f: &std::fs::File) -> bool {+ use std::os::windows::io::AsRawHandle;+ use windows_sys::Win32::Storage::FileSystem::{+ GetFileInformationByHandle, GetFileType, BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_DIRECTORY,+ FILE_ATTRIBUTE_REPARSE_POINT, FILE_TYPE_DISK,+ };+ let h = f.as_raw_handle() as windows_sys::Win32::Foundation::HANDLE;+ // SAFETY: `h` is the live handle `f` owns for this whole call; `info` is a plain out-struct+ // that GetFileInformationByHandle fills.+ unsafe {+ if GetFileType(h) != FILE_TYPE_DISK {+ return false;+ }+ let mut info: BY_HANDLE_FILE_INFORMATION = std::mem::zeroed();+ if GetFileInformationByHandle(h, &mut info) == 0 {+ return false;+ }+ info.dwFileAttributes & (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY) == 0 && info.nNumberOfLinks == 1+ }+}+/// A `ref:` target git would write: `refs/` then plain components of `[A-Za-z0-9._-]`, so it/// can't leave `.git` (no `..`, no empty or absolute part, no backslash).pub(crate) fn plain_ref(r: &str) -> bool {@@ -80,3 +163,65 @@ mod tests {assert_eq!(read(d.path(), "g", 10), None);}}++#[cfg(test)]+mod name_tests {+ #[test]+ fn windows_names_refuse_devices_streams_and_trailing_dots() {+ use super::windows_plain_name as ok;+ for good in ["HEAD", "packed-refs", "main", "feature", "console", "CONTROL", "COM10", "a.b", ".git"] {+ assert!(ok(good), "{good}");+ }+ for bad in ["", "CON", "con", "NUL.txt", "aux.git", "COM1", "lpt9", "COM\u{b9}", "PRN ", "HEAD:x", "a\\b", "HEAD.", "HEAD "] {+ assert!(!ok(bad), "{bad}");+ }+ }+}++/// The Windows refusals, with real junctions, symlinks and hard links on NTFS.+#[cfg(all(test, windows))]+pub(crate) mod windows_tests {+ use super::*;+ use std::path::Path;++ /// A junction needs no privilege, unlike a symlink. cmd reads a `/` in+ /// a path as a switch, so both paths go over with backslashes only.+ pub(crate) fn junction(link: &Path, target: &Path) {+ let back = |p: &Path| p.to_string_lossy().replace('/', "\\");+ let out = std::process::Command::new("cmd").arg("/C").arg("mklink").arg("/J").arg(back(link)).arg(back(target)).output().unwrap();+ assert!(out.status.success(), "mklink /J: {}", String::from_utf8_lossy(&out.stderr));+ }++ #[test]+ fn reads_one_regular_file_and_refuses_the_rest_on_windows() {+ let d = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(d.path().join("a")).unwrap();+ std::fs::write(d.path().join("a/f"), "hi").unwrap();+ assert_eq!(read(d.path(), "a/f", 10).as_deref(), Some("hi"));+ assert_eq!(read(d.path(), "a/f", 1), None, "over the cap");+ assert_eq!(read(d.path(), "a", 10), None, "a folder");+ assert_eq!(read(d.path(), "a/f:alt", 10), None, "a data stream");+ assert_eq!(read(d.path(), "a/f.", 10), None, "a trailing dot Win32 would drop");+ assert_eq!(read(d.path(), "a/NUL", 10), None, "a device");+ assert_eq!(read(d.path(), "CON", 10), None, "the console");++ // a junction anywhere on the way+ let elsewhere = d.path().join("elsewhere");+ std::fs::create_dir_all(&elsewhere).unwrap();+ std::fs::write(elsewhere.join("f"), "LEAKED").unwrap();+ junction(&d.path().join("j"), &elsewhere);+ assert_eq!(read(d.path(), "j/f", 10), None, "through a junction");++ // a second name for the same file+ std::fs::hard_link(d.path().join("a/f"), d.path().join("g")).unwrap();+ assert_eq!(read(d.path(), "a/f", 10), None, "a file with two names");+ assert_eq!(read(d.path(), "g", 10), None);++ // a file symlink (the runner is elevated; on a PC without the right it can't be made,+ // and then there's nothing to refuse)+ match std::os::windows::fs::symlink_file(elsewhere.join("f"), d.path().join("s")) {+ Ok(()) => assert_eq!(read(d.path(), "s", 10), None, "a file symlink"),+ Err(e) => eprintln!("no symlink here ({e}); the junction case covers links"),+ }+ }+}diff --git a/src/server/missions/autofix.rs b/src/server/missions/autofix.rsindex e3414930..6069828e 100644--- a/src/server/missions/autofix.rs+++ b/src/server/missions/autofix.rs@@ -370,11 +370,11 @@ fn diagnostics_root(state: &AppState) -> std::path::PathBuf {/// Writes the redacted diagnostics of a failure, 0600 in a 0700 folder. Server-only.fn write_diagnostics(state: &AppState, task_id: &str, name: &str, text: &str) -> Option<String> {- use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};+ use crate::fsx::UnixMode;let dir = diagnostics_root(state).join(task_id);- std::fs::DirBuilder::new().recursive(true).mode(0o700).create(&dir).ok()?;+ std::fs::DirBuilder::new().recursive(true).unix_mode(0o700).create(&dir).ok()?;let path = dir.join(format!("{name}.log"));- let mut f = std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(&path).ok()?;+ let mut f = std::fs::OpenOptions::new().write(true).create_new(true).unix_mode(0o600).open(&path).ok()?;let body: String = text.chars().take(DIAGNOSTICS_MAX).collect();std::io::Write::write_all(&mut f, body.as_bytes()).ok()?;Some(path.to_string_lossy().into_owned())diff --git a/src/server/missions/checkpoints.rs b/src/server/missions/checkpoints.rsindex a2743fc0..b6831f79 100644--- a/src/server/missions/checkpoints.rs+++ b/src/server/missions/checkpoints.rs@@ -22,7 +22,7 @@ use serde::{Deserialize, Serialize};use serde_json::{json, Value};use std::collections::{BTreeMap, BTreeSet};use std::io::{Read, Write};-use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};+use crate::fsx::UnixMode;use std::path::{Component, Path as FsPath, PathBuf};pub const SETTING: &str = "checkpoints";@@ -114,7 +114,7 @@ struct Run {fn private_dir(dir: &FsPath) -> std::io::Result<()> {std::fs::create_dir_all(dir)?;- std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))+ crate::fsx::set_mode(dir, 0o700)}fn hex(bytes: &[u8]) -> String {@@ -167,7 +167,7 @@ fn current(folder: &FsPath, rel: &str) -> Result<Option<String>, String> {fn store_blob(blobs: &FsPath, src: &FsPath) -> std::io::Result<String> {let mut input = std::fs::File::open(src)?;let tmp = blobs.join(format!(".tmp-{}", new_id()));- let mut out = std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(&tmp)?;+ let mut out = std::fs::OpenOptions::new().write(true).create_new(true).unix_mode(0o600).open(&tmp)?;let mut h = <sha2::Sha256 as sha2::Digest>::new();let mut buf = vec![0u8; 64 * 1024];let res = (|| -> std::io::Result<()> {@@ -205,7 +205,7 @@ fn store_blob(blobs: &FsPath, src: &FsPath) -> std::io::Result<String> {/// including a `.git` file (a `gitdir:` worktree pointer), is `None`.fn git_head(folder: &FsPath) -> Option<String> {let git = folder.join(".git");- if !std::fs::symlink_metadata(&git).ok()?.file_type().is_dir() {+ if !gitfile::plain_dir(&std::fs::symlink_metadata(&git).ok()?) {return None;}let head = gitfile::read(&git, "HEAD", gitfile::REF_MAX)?;@@ -284,7 +284,7 @@ fn snapshot(blobs: &FsPath, folder: &FsPath, max_bytes: u64) -> Result<Taken, St} else if meta.len() > FILE_MAX_BYTES {m.skipped.push(Skip { path: rel, why: "over 20 MB".into() });} else {- candidates.push((rel, entry.path(), meta.len(), meta.permissions().mode() & 0o777));+ candidates.push((rel, entry.path(), meta.len(), crate::fsx::mode_of(&meta)));}}}@@ -336,7 +336,7 @@ fn write_manifest(dir: &FsPath, id: &str, m: &Manifest) -> std::io::Result<(Pathprivate_dir(dir)?;let body = serde_json::to_vec(m).map_err(std::io::Error::other)?;let path = dir.join(format!("{id}.json"));- let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(&path)?;+ let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(true).unix_mode(0o600).open(&path)?;f.write_all(&body)?;Ok((path, hex(&<sha2::Sha256 as sha2::Digest>::digest(&body))))}@@ -360,7 +360,7 @@ pub async fn materialize_first(state: &AppState, task_id: &str, dest: &FsPath) -}// A missing blob is skipped: the replay sees less, never something elseif std::fs::copy(blobs.join(&e.sha256), &to).is_ok() {- let _ = std::fs::set_permissions(&to, std::fs::Permissions::from_mode((e.mode & 0o700) | 0o600));+ let _ = crate::fsx::set_mode(&to, (e.mode & 0o700) | 0o600);n += 1;}}@@ -422,7 +422,7 @@ fn read_runs(dir: &FsPath) -> Vec<Run> {fn append_run(dir: &FsPath, run: &Run) -> std::io::Result<()> {private_dir(dir)?;- let mut f = std::fs::OpenOptions::new().append(true).create(true).mode(0o600).open(dir.join("runs.jsonl"))?;+ let mut f = std::fs::OpenOptions::new().append(true).create(true).unix_mode(0o600).open(dir.join("runs.jsonl"))?;writeln!(f, "{}", serde_json::to_string(run).map_err(std::io::Error::other)?)}@@ -946,7 +946,7 @@ fn apply(blobs: &FsPath, p: &Plan, force: &BTreeSet<String>) -> (Vec<String>, Ve}let tmp = parent.join(format!(".kwant-restore-{}", new_id()));std::fs::copy(blobs.join(&e.sha256), &tmp)?;- std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(if e.mode == 0 { 0o644 } else { e.mode }))?;+ crate::fsx::set_mode(&tmp, if e.mode == 0 { 0o644 } else { e.mode })?;std::fs::rename(&tmp, &dest).inspect_err(|_| {let _ = std::fs::remove_file(&tmp);})?;@@ -1395,6 +1395,36 @@ mod tests {assert_eq!(head_of(&folder), None, ".git symlink");}+ /// Windows: no FIFOs or O_NOFOLLOW there, so the same refusals come from the reparse-point and+ /// link-count checks (gitfile). A hard-linked ref, a junction on the way or as `.git` is `None`.+ #[cfg(windows)]+ #[test]+ fn git_head_refuses_junctions_and_hard_links_on_windows() {+ use crate::server::gitfile::windows_tests::junction;+ let (d, folder, canary) = repo();+ let git = folder.join(".git");+ std::fs::write(git.join("HEAD"), "ref: refs/heads/main\n").unwrap();+ std::fs::write(git.join("refs/heads/main"), format!("{SHA}\n")).unwrap();+ assert_eq!(head_of(&folder).as_deref(), Some(SHA), "a plain repo reads");+ std::fs::remove_file(git.join("refs/heads/main")).unwrap();+ std::fs::hard_link(&canary, git.join("refs/heads/main")).unwrap();+ assert_eq!(head_of(&folder), None, "a ref that is the canary's second name");+ std::fs::remove_file(git.join("refs/heads/main")).unwrap();+ let elsewhere = d.path().join("elsewhere");+ std::fs::create_dir_all(&elsewhere).unwrap();+ std::fs::copy(&canary, elsewhere.join("main")).unwrap();+ std::fs::remove_dir(git.join("refs/heads")).unwrap();+ junction(&git.join("refs/heads"), &elsewhere);+ assert_eq!(head_of(&folder), None, "refs/heads a junction");+ let other = d.path().join("other");+ std::fs::create_dir_all(other.join("refs/heads")).unwrap();+ std::fs::write(other.join("HEAD"), format!("{CANARY}\n")).unwrap();+ let task2 = d.path().join("task2");+ std::fs::create_dir_all(&task2).unwrap();+ junction(&task2.join(".git"), &other);+ assert_eq!(head_of(&task2), None, ".git a junction");+ }+#[cfg(unix)]#[test]fn git_head_does_not_block_on_a_fifo() {diff --git a/src/server/missions/foundry.rs b/src/server/missions/foundry.rsindex 0f86ebb8..35adde44 100644--- a/src/server/missions/foundry.rs+++ b/src/server/missions/foundry.rs@@ -606,13 +606,12 @@ pub fn scratch_dir(state: &AppState, run_id: &str, n: usize) -> PathBuf {}fn private_dir(dir: &FsPath) -> std::io::Result<()> {- use std::os::unix::fs::PermissionsExt;if let Some(parent) = dir.parent() {std::fs::create_dir_all(parent)?;- std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700))?;+ crate::fsx::set_mode(parent, 0o700)?;}std::fs::create_dir_all(dir)?;- std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))+ crate::fsx::set_mode(dir, 0o700)}/// Runs a draft's checks on a replay's scratch folder: file checks run there; command and httpdiff --git a/src/server/video.rs b/src/server/video.rsindex b0137379..31228357 100644--- a/src/server/video.rs+++ b/src/server/video.rs@@ -27,6 +27,9 @@ use tokio::io::{AsyncRead, AsyncReadExt};pub const READ_SECS: u64 = 20;/// The line a bot gets when the server has no ffmpeg.pub const NO_FFMPEG: &str = "Install ffmpeg on the server to let bots look inside videos.";+/// Windows (0.7.6 beta): ffmpeg can't be held short there (no setsid, nice or rlimits), so bots+/// get the size and this line instead.+pub const NOT_ON_WINDOWS: &str = "Looking inside videos is not available on Windows yet.";/// Why a read stopped when ffmpeg or ffprobe couldn't be started.const NO_START: &str = "ffmpeg couldn't start on this server.";const MAX_FRAMES: usize = 6;@@ -37,8 +40,10 @@ const MAX_FRAME_BYTES: u64 = 5 * 1024 * 1024;/// Frames bigger than this many pixels aren't decoded (8K is 33 MP).const MAX_PIXELS: &str = "40000000";/// No file ffmpeg writes may pass this.+#[cfg(unix)]const OUT_FSIZE: u64 = 16 * 1024 * 1024;/// Address space for one ffmpeg/ffprobe.+#[cfg(unix)]const MAX_AS: u64 = 2 * 1024 * 1024 * 1024;/// Most ffprobe JSON read.const MAX_PROBE_OUT: usize = 256 * 1024;@@ -298,6 +303,9 @@ fn os(args: &[&str]) -> Vec<OsString> {/// `read_attachment` for a video: MCP content blocks, and whether it is an error.pub async fn describe(name: &str, mime: &str, size: i64, blob: &Path, tmp_parent: &Path) -> (Value, bool) {+ if cfg!(windows) {+ return (json!([{"type": "text", "text": format!("{name} is a video ({mime}, {}). {NOT_ON_WINDOWS}", human_size(size))}]), false);+ }describe_with(tools(), name, mime, size, blob, tmp_parent, Duration::from_secs(READ_SECS)).await}diff --git a/src/setup.rs b/src/setup.rsindex 5c79a5a8..990baccc 100644--- a/src/setup.rs+++ b/src/setup.rs@@ -21,6 +21,8 @@ pub const UV_VERSION: &str = "0.13.5";/// Playwright, whose `install chromium` puts a private Chromium in the person's cache. Pinned.pub const PLAYWRIGHT_VERSION: &str = "1.64.1";pub const CODEX_NPM: &str = "@openai/codex";+/// Claude Code's npm package, for Windows (elsewhere its own installer script is used).+pub const CLAUDE_NPM: &str = "@anthropic-ai/claude-code";/// Where Codex publishes its standalone builds (one tag per release, `rust-v<version>`).pub const CODEX_RELEASES: &str = "https://github.com/openai/codex/releases";/// The release's checksum file for its `codex-package-<target>.tar.gz` archives.@@ -379,6 +381,13 @@ pub fn plan(item: ItemId, p: &Probe) -> Plan {},}),},+ // Windows: npm and winget only, never curl | bash, apt or sudo (0.7.6 Windows port)+ ItemId::Claude | ItemId::Codex | ItemId::Grok if cfg!(windows) => {+ if p.platform != Platform::Docker && p.cli(item.engine().unwrap_or(Engine::Claude)).is_none() {+ let (npm, git) = windows_tools();+ steps.extend(windows_cli_steps(item, npm.as_deref(), git));+ }+ }ItemId::Claude | ItemId::Grok if p.platform == Platform::Docker => {}ItemId::Claude | ItemId::Grok if p.cli(item.engine().unwrap_or(Engine::Claude)).is_some() => {}ItemId::Claude | ItemId::Grok => {@@ -654,6 +663,46 @@ fn is_root() -> bool {false}+/// Windows: npm (`npm.cmd`, which [`which`] can't see) and whether Git for Windows' bash is here.+#[cfg(windows)]+fn windows_tools() -> (Option<String>, bool) {+ (crate::drivers::find_cli_binary("npm"), crate::tools::shell::git_bash().is_some())+}++#[cfg(not(windows))]+fn windows_tools() -> (Option<String>, bool) {+ (None, true)+}++/// How to install a CLI on Windows: npm into the person's own `%APPDATA%\npm`, Node.js and Git+/// from winget. Git first when it is missing, since bot commands run in its bash. Pure, so it is+/// tested on every platform.+fn windows_cli_steps(item: ItemId, npm: Option<&str>, git: bool) -> Vec<Step> {+ let mut steps = Vec::new();+ if !git {+ steps.push(Step::Manual {+ label: "Install Git for Windows (bots run their commands in its bash)".into(),+ command: "winget install --id Git.Git -e".into(),+ });+ }+ let (name, pkg) = match item {+ ItemId::Claude => ("Claude Code", CLAUDE_NPM),+ ItemId::Codex => ("the Codex CLI", CODEX_NPM),+ _ => {+ steps.push(Step::Manual { label: "Grok CLI".into(), command: "Not available on Windows yet.".into() });+ return steps;+ }+ };+ steps.push(match npm {+ Some(npm) => Step::Run(Cmd::new(format!("Install {name} with npm"), &[npm, "install", "-g", pkg])),+ None => Step::Manual {+ label: format!("Install Node.js, then {name}"),+ command: format!("winget install --id OpenJS.NodeJS.LTS -e, then: npm install -g {pkg}"),+ },+ });+ steps+}+pub fn which(name: &str) -> Option<PathBuf> {let path = std::env::var_os("PATH")?;std::env::split_paths(&path).map(|d| d.join(name)).find(|c| c.is_file())@@ -1296,6 +1345,8 @@ mod tests {}}+ // Linux and Mac plans with their paths; Windows plans are windows_cli_steps' (tested everywhere)+ #[cfg(unix)]#[test]fn laya_on_a_bare_machine_installs_uv_into_the_data_folder_then_laya() {for p in [bare(Platform::Linux), mac()] {@@ -1318,6 +1369,8 @@ mod tests {}}+ // Linux and Mac plans with their paths; Windows plans are windows_cli_steps' (tested everywhere)+ #[cfg(unix)]#[test]fn laya_prefers_uv_then_a_real_python() {let mut p = bare(Platform::Linux);@@ -1403,6 +1456,8 @@ mod tests {assert!(plan(ItemId::Browser, &p).steps.is_empty());}+ // Linux and Mac plans with their paths; Windows plans are windows_cli_steps' (tested everywhere)+ #[cfg(unix)]#[test]fn clis_install_in_user_space() {let p = bare(Platform::Linux);@@ -1464,6 +1519,8 @@ mod tests {assert_eq!(default_selection(&has, None, false), vec![ItemId::Laya, ItemId::Browser]);}+ // Linux and Mac plans with their paths; Windows plans are windows_cli_steps' (tested everywhere)+ #[cfg(unix)]#[test]fn checklist_rows() {let mut p = bare(Platform::Linux);diff --git a/src/tools/shell.rs b/src/tools/shell.rsindex 4da8945d..d086c507 100644--- a/src/tools/shell.rs+++ b/src/tools/shell.rs@@ -15,7 +15,7 @@ pub async fn execute_shell(workspace: &Path, args: &Value) -> Result<Value, Toollet timeout_secs = args["timeout_secs"].as_u64().unwrap_or(30);- let mut cmd = Command::new("bash");+ let mut cmd = Command::new(shell_program()?);cmd.arg("-c").arg(command_str);cmd.current_dir(workspace);cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());@@ -76,3 +76,116 @@ pub async fn execute_shell(workspace: &Path, args: &Value) -> Result<Value, Tool"success": status.success()}))}++/// The bash that runs bot commands. On Windows this is Git for Windows' `bash.exe`, never+/// WSL's `System32\bash.exe` (plan decision 2); without Git, the command is refused with+/// [`GIT_MISSING`].+fn shell_program() -> Result<std::path::PathBuf, ToolError> {+ #[cfg(windows)]+ return git_bash().ok_or_else(|| ToolError::Execution(GIT_MISSING.into()));+ #[cfg(not(windows))]+ Ok("bash".into())+}++/// Shown when Git for Windows (and so its bash) is missing.+pub const GIT_MISSING: &str = "Bot commands need Git for Windows. Install it with: winget install --id Git.Git -e";++/// Git for Windows' `bash.exe`, looked up once: from `git --exec-path`, else the usual install+/// folders. Never WSL's bash in `C:\Windows\System32`.+#[cfg(windows)]+pub fn git_bash() -> Option<std::path::PathBuf> {+ // Only a hit is kept, so Git installed while kwnt runs is found on the next command+ static FOUND: std::sync::OnceLock<std::path::PathBuf> = std::sync::OnceLock::new();+ if let Some(hit) = FOUND.get() {+ return Some(hit.clone());+ }+ let found = {+ let exec_path = std::process::Command::new("git")+ .arg("--exec-path")+ .stdin(Stdio::null())+ .stderr(Stdio::null())+ .output()+ .ok()+ .filter(|o| o.status.success())+ .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string());+ let env = |k: &str| std::env::var_os(k).map(std::path::PathBuf::from);+ git_bash_candidates(exec_path.as_deref(), env("ProgramFiles"), env("LOCALAPPDATA"))+ .into_iter()+ .find(|p| p.is_file())+ }?;+ Some(FOUND.get_or_init(|| found).clone())+}++/// Where Git for Windows' bash may be, best first: `<git --exec-path>\..\..\..\bin\bash.exe`+/// (exec-path is `<Git>\mingw64\libexec\git-core`), then the machine-wide and per-user+/// install folders. WSL's bash is never a candidate.+#[cfg(any(windows, test))]+fn git_bash_candidates(+ exec_path: Option<&str>,+ program_files: Option<std::path::PathBuf>,+ local_app_data: Option<std::path::PathBuf>,+) -> Vec<std::path::PathBuf> {+ let mut out = Vec::new();+ if let Some(root) = exec_path.filter(|p| !p.is_empty()).and_then(|p| Path::new(p).ancestors().nth(3)) {+ out.push(root.join("bin").join("bash.exe"));+ }+ if let Some(pf) = program_files {+ out.push(pf.join("Git").join("bin").join("bash.exe"));+ }+ if let Some(local) = local_app_data {+ out.push(local.join("Programs").join("Git").join("bin").join("bash.exe"));+ }+ out.retain(|p| !is_wsl_bash(p));+ out+}++/// `C:\Windows\System32\bash.exe` (or SysWOW64/Sysnative) is WSL's launcher, not a bash.+#[cfg(any(windows, test))]+fn is_wsl_bash(path: &Path) -> bool {+ let p = path.to_string_lossy().replace('/', "\\").to_ascii_lowercase();+ ["\\windows\\system32\\", "\\windows\\syswow64\\", "\\windows\\sysnative\\"].iter().any(|d| p.contains(d))+}++#[cfg(test)]+mod windows_path_tests {+ use super::*;+ use std::path::PathBuf;++ // Forward slashes so the same paths split the same way on Linux, Mac and Windows.+ #[test]+ fn git_bash_comes_from_git_s_own_folder_first_and_never_from_wsl() {+ let got = git_bash_candidates(+ Some("C:/Program Files/Git/mingw64/libexec/git-core"),+ Some(PathBuf::from("C:/Program Files")),+ Some(PathBuf::from("C:/Users/someone/AppData/Local")),+ );+ let git = |root: &str| Path::new(root).join("bin").join("bash.exe");+ assert_eq!(+ got,+ vec![+ git("C:/Program Files/Git"),+ Path::new("C:/Program Files").join("Git").join("bin").join("bash.exe"),+ Path::new("C:/Users/someone/AppData/Local").join("Programs").join("Git").join("bin").join("bash.exe"),+ ]+ );+ assert!(git_bash_candidates(None, None, None).is_empty());+ assert!(git_bash_candidates(Some(""), None, None).is_empty());+ // A git whose folder is in System32 would point at WSL's bash: dropped+ assert!(git_bash_candidates(Some("C:/Windows/System32/a/b/c"), None, None).is_empty());+ }++ #[test]+ fn wsl_s_launcher_is_not_git_bash() {+ for wsl in ["C:\\Windows\\System32\\bash.exe", "c:/windows/sysnative/bash.exe", "C:\\WINDOWS\\SysWOW64\\bash.exe"] {+ assert!(is_wsl_bash(Path::new(wsl)), "{wsl}");+ }+ for git in ["C:\\Program Files\\Git\\bin\\bash.exe", "D:/tools/Git/bin/bash.exe"] {+ assert!(!is_wsl_bash(Path::new(git)), "{git}");+ }+ }++ #[test]+ fn missing_git_says_how_to_install_it() {+ assert!(GIT_MISSING.contains("winget install --id Git.Git -e"));+ }+}diff --git a/tests/chrome_download_test.rs b/tests/chrome_download_test.rsindex 83d3fee8..9a684661 100644--- a/tests/chrome_download_test.rs+++ b/tests/chrome_download_test.rs@@ -196,6 +196,7 @@ async fn the_first_need_downloads_the_build_once_and_it_is_found_after() {let bin = tempfile::tempdir().unwrap();// never run here, so a plain executable file is enoughstd::fs::write(bin.path().join("chromium"), "#!/bin/sh\n").unwrap();+ #[cfg(unix)]{use std::os::unix::fs::PermissionsExt;std::fs::set_permissions(bin.path().join("chromium"), std::fs::Permissions::from_mode(0o755)).unwrap();diff --git a/tests/dev_any_git_test.rs b/tests/dev_any_git_test.rsindex 1ff2f72f..17a2a218 100644--- a/tests/dev_any_git_test.rs+++ b/tests/dev_any_git_test.rs@@ -382,6 +382,8 @@ async fn a_repo_too_big_to_copy_reads_as_an_error_until_it_is_added_again() {/// folder that read fine is pointed at another team's repo (its `.git` swapped for a symlink): the/// next poll reads `error` and makes no card from the other repo's commits; put back, it reads/// again.+// Swaps `.git` for a symlink, which Windows only allows with Developer Mode or admin rights+#[cfg(unix)]#[tokio::test]async fn a_team_folder_pointed_at_another_repo_reads_as_an_error_on_the_next_poll() {let env = setup().await;diff --git a/tests/foundry_test.rs b/tests/foundry_test.rsindex 65b6711c..84fddac5 100644--- a/tests/foundry_test.rs+++ b/tests/foundry_test.rs@@ -515,8 +515,11 @@ async fn scratch_checks_run_file_checks_and_mark_network_ones_not_replayable() {let n = kwnt::server::missions::checkpoints::materialize_first(&e.state, &tid, &scratch).await.unwrap();assert_eq!(n, 1);assert_eq!(std::fs::read_to_string(scratch.join("NOTES.md")).unwrap(), "v1.2: export fixed");- use std::os::unix::fs::PermissionsExt;- assert_eq!(std::fs::metadata(&scratch).unwrap().permissions().mode() & 0o777, 0o700);+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ assert_eq!(std::fs::metadata(&scratch).unwrap().permissions().mode() & 0o777, 0o700);+ }let checks = vec![json!({"kind": "file_exists", "spec": {"path": "NOTES.md"}}),diff --git a/tests/mcp_runtime_test.rs b/tests/mcp_runtime_test.rsindex d27880a3..4cca0b60 100644--- a/tests/mcp_runtime_test.rs+++ b/tests/mcp_runtime_test.rs@@ -1,4 +1,6 @@//! Turn-time MCP: broker approvals, the claude permission endpoint and the claude config file.+// The fake CLI and agent runs are shell scripts, so their tests and helpers are Unix only+#![cfg_attr(not(unix), allow(dead_code))]#[path = "common/exe.rs"]mod exe;diff --git a/tests/mission_autofix_test.rs b/tests/mission_autofix_test.rsindex e007f040..ce40af3c 100644--- a/tests/mission_autofix_test.rs+++ b/tests/mission_autofix_test.rs@@ -29,6 +29,7 @@ use kwnt::{tools::ToolRunner,};use serde_json::{json, Value};+#[cfg(unix)]use std::os::unix::fs::PermissionsExt;use std::path::PathBuf;use std::sync::OnceLock;@@ -781,9 +782,11 @@ async fn diagnostics_are_redacted_and_their_path_never_reaches_the_api() {}// The full diagnostics are on disk only, redacted, 0600 in a 0700 folderlet dir = e.state.config.data_dir.join("autofix").join(&tid);+ #[cfg(unix)]assert_eq!(std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777, 0o700);let files: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|f| f.unwrap().path()).collect();assert_eq!(files.len(), 1, "{files:?}");+ #[cfg(unix)]assert_eq!(std::fs::metadata(&files[0]).unwrap().permissions().mode() & 0o777, 0o600);let body = std::fs::read_to_string(&files[0]).unwrap();assert!(body.contains("exit code 1") && !body.contains("api03abcdefghij0123456789") && !body.contains("hunter2secretpw"), "{body}");diff --git a/tests/mission_checkpoints_test.rs b/tests/mission_checkpoints_test.rsindex 43afccb6..7999060a 100644--- a/tests/mission_checkpoints_test.rs+++ b/tests/mission_checkpoints_test.rs@@ -25,6 +25,7 @@ use kwnt::{tools::ToolRunner,};use serde_json::{json, Value};+#[cfg(unix)]use std::os::unix::fs::PermissionsExt;use std::path::{Path, PathBuf};use std::sync::OnceLock;@@ -458,7 +459,8 @@ async fn a_stale_preview_is_refused_and_a_repeated_key_writes_nothing() {assert_eq!(s, StatusCode::BAD_REQUEST);}-// 5+// 5 (symlinks need Developer Mode or admin rights on Windows)+#[cfg(unix)]#[tokio::test]async fn unsafe_manifest_paths_and_symlinks_are_skipped_and_never_followed() {let e = setup().await;@@ -561,6 +563,7 @@ async fn no_route_returns_manifest_or_blob_paths_or_file_contents() {}// The snapshot holds the secrets (it must), under a 0700 folderlet root = e.state.config.data_dir.join("checkpoints");+ #[cfg(unix)]assert_eq!(std::fs::metadata(&root).unwrap().permissions().mode() & 0o777, 0o700);assert!(blobs(&e).join(sha(b"API_KEY=SECRET-CONTENT-4242")).exists());let root_s = root.display().to_string();@@ -591,7 +594,8 @@ async fn a_bot_token_cant_checkpoint_restore_or_fork() {assert_eq!(checkpoints(&e, tid).await.len(), 2, "nothing was taken");}-// 9+// 9 (Unix permission bits; Windows folders use ACLs)+#[cfg(unix)]#[tokio::test]async fn an_unreadable_folder_fails_the_checkpoint_but_not_the_turn() {let e = setup().await;diff --git a/tests/shell_stop_tree_test.rs b/tests/shell_stop_tree_test.rsnew file mode 100644index 00000000..ce7a26d4--- /dev/null+++ b/tests/shell_stop_tree_test.rs@@ -0,0 +1,44 @@+//! Stop ends a bot command's whole process tree (Windows plan decision 3: a Job Object per turn;+//! on Mac and Linux, the process group). The command starts a child bash that starts a grandchild;+//! both keep appending to a file until they are gone. Runs on every OS; on windows-latest it is the+//! check that the Job Object holds the tree.+use kwnt::tools::shell::execute_shell;+use serde_json::json;+use std::path::Path;+use std::time::Duration;+use tempfile::tempdir;++fn size(p: &Path) -> u64 {+ std::fs::metadata(p).map(|m| m.len()).unwrap_or(0)+}++#[tokio::test]+async fn stop_ends_the_child_and_the_grandchild() {+ let tmp = tempdir().unwrap();+ // Relative names: the command runs in the workspace, and Git bash on Windows would read the+ // backslashes of an absolute path as escapes+ let args = json!({+ "command": "bash -c '(while :; do echo g >> grandchild.log; sleep 0.2; done) & while :; do echo c >> child.log; sleep 0.2; done'",+ "timeout_secs": 120+ });+ let (child, grandchild) = (tmp.path().join("child.log"), tmp.path().join("grandchild.log"));+ let dir = tmp.path().to_path_buf();+ let task = tokio::spawn(async move { execute_shell(&dir, &args).await });++ // Both are running: each file grows+ let started = std::time::Instant::now();+ while (size(&child) == 0 || size(&grandchild) == 0) && started.elapsed() < Duration::from_secs(30) {+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ assert!(size(&child) > 0, "the child never started");+ assert!(size(&grandchild) > 0, "the grandchild never started");++ // Stop: the turn is cancelled, which drops the command+ task.abort();+ let _ = task.await;+ tokio::time::sleep(Duration::from_secs(1)).await;+ let (c, g) = (size(&child), size(&grandchild));+ tokio::time::sleep(Duration::from_secs(2)).await;+ assert_eq!(size(&child), c, "the child kept running after Stop");+ assert_eq!(size(&grandchild), g, "the grandchild kept running after Stop");+}diff --git a/tests/shell_tool_test.rs b/tests/shell_tool_test.rsindex 59f35a55..5257d60c 100644--- a/tests/shell_tool_test.rs+++ b/tests/shell_tool_test.rs@@ -8,7 +8,8 @@ use tempfile::tempdir;async fn a_timed_out_command_does_not_finish_later() {let tmp = tempdir().unwrap();let marker = tmp.path().join("marker");- let args = json!({ "command": format!("sleep 3; touch {}", marker.display()), "timeout_secs": 1 });+ // Relative names (the command runs in the workspace): Git bash on Windows reads backslashes as escapes+ let args = json!({ "command": "sleep 3; touch marker", "timeout_secs": 1 });let err = execute_shell(tmp.path(), &args).await.unwrap_err();assert!(err.to_string().contains("timed out"), "{err}");tokio::time::sleep(Duration::from_secs(4)).await;@@ -21,7 +22,7 @@ async fn a_timeout_also_stops_background_jobs() {let marker = tmp.path().join("grandchild");// A backgrounded subshell is a grandchild of the tool; it must die with bashlet args = json!({- "command": format!("(sleep 3; touch {}) & sleep 10", marker.display()),+ "command": "(sleep 3; touch grandchild) & sleep 10","timeout_secs": 1});assert!(execute_shell(tmp.path(), &args).await.is_err());@@ -34,7 +35,7 @@ async fn a_cancelled_turn_stops_the_command() {let tmp = tempdir().unwrap();let marker = tmp.path().join("cancelled");let args = json!({- "command": format!("(sleep 3; touch {m}) & sleep 3; touch {m}", m = marker.display()),+ "command": "(sleep 3; touch cancelled) & sleep 3; touch cancelled","timeout_secs": 30});let dir = tmp.path().to_path_buf();diff --git a/tests/support/chrome_guard.rs b/tests/support/chrome_guard.rsindex f094cfac..650a9193 100644--- a/tests/support/chrome_guard.rs+++ b/tests/support/chrome_guard.rs@@ -11,9 +11,12 @@ impl Drop for ChromeGuard {// Nothing when the test closed its Chrome itselfif let Some(pid) = kwnt::sandbox::computer::profile_owner(&self.0) {// SAFETY: kill(2) with a pid that profile_owner just saw as this profile's Chrome+ #[cfg(unix)]unsafe {libc::kill(pid as libc::pid_t, libc::SIGKILL);}+ #[cfg(windows)]+ let _ = std::process::Command::new("taskkill").args(["/F", "/T", "/PID", &pid.to_string()]).output();}}}