From 25dab93560c1e4e41a22d549e100cf031ab34238 Mon Sep 17 00:00:00 2001 From: Miguel del Amor Date: Sun, 6 Dec 2026 12:34:39 +0100 Subject: [PATCH] Add production-grade native Windows support across runtime, CLI/TUI, web UI, ConPTY, desktop app, and CI --- .github/scripts/ci.py | 8 +- .github/scripts/npm_audit.py | 7 +- .github/workflows/ci.yml | 22 +- .github/workflows/desktop-release.yml | 8 +- README.md | 11 +- README.zh-CN.md | 9 +- desktop/README.md | 10 +- desktop/build/icon.ico | Bin 0 -> 91602 bytes desktop/build/icons.json | 5 +- desktop/main.js | 39 ++- desktop/package.json | 21 +- desktop/scripts/bundle-cli.js | 25 ++ desktop/scripts/release-updates.js | 19 +- desktop/scripts/render-icons.py | 4 +- desktop/updates.js | 1 + install.ps1 | 41 +++ pyproject.toml | 1 + src/freehand/cli.py | 35 +- src/freehand/control.py | 35 +- src/freehand/copilot_bridge.py | 6 + src/freehand/daemon.py | 16 +- src/freehand/hooks.py | 37 ++- src/freehand/inputs.py | 86 +++-- src/freehand/integrations/harbor.py | 4 + src/freehand/limits.py | 30 +- src/freehand/mcp.py | 27 +- src/freehand/runtime/agent.py | 174 +++++----- src/freehand/runtime/auth.py | 33 +- src/freehand/runtime/calltrace.py | 4 +- src/freehand/runtime/copilot.py | 30 +- src/freehand/runtime/osutil.py | 444 +++++++++++++++++++++++++ src/freehand/runtime/providers.py | 16 +- src/freehand/runtime/shellenv.py | 15 +- src/freehand/server.py | 21 +- src/freehand/session.py | 84 +++-- src/freehand/snapshots.py | 70 ++-- src/freehand/terminals.py | 67 +++- src/freehand/tui.py | 86 ++++- src/freehand/ui.py | 23 +- src/freehand/web/app.js | 28 +- src/freehand/web/md.js | 2 +- src/freehand/web/panels.js | 2 +- src/freehand/web/workbench.js | 15 +- src/freehand/winpty.py | 291 ++++++++++++++++ src/freehand/workbench.py | 73 ++-- tests/conftest.py | 6 + tests/desktop_development.js | 23 +- tests/desktop_recovery.js | 2 +- tests/desktop_release_updates.js | 10 +- tests/desktop_service.js | 2 +- tests/desktop_updates.js | 4 +- tests/fakes.py | 42 ++- tests/pty_driver.py | 30 +- tests/repl_driver.py | 28 ++ tests/test_anthropic_images.py | 13 +- tests/test_auth.py | 4 +- tests/test_brand_assets.py | 18 +- tests/test_chat_images.py | 13 +- tests/test_ci.py | 2 +- tests/test_connections.py | 4 +- tests/test_daemon.py | 3 +- tests/test_desktop_service_ui.py | 2 +- tests/test_desktop_workbench.py | 10 +- tests/test_file_index_paths.py | 8 + tests/test_fullscreen.py | 5 +- tests/test_gitflow.py | 12 +- tests/test_hardening.py | 22 +- tests/test_image_recovery.py | 23 +- tests/test_inputs.py | 15 +- tests/test_interactive.py | 27 +- tests/test_no_project.py | 7 +- tests/test_packaging.py | 46 ++- tests/test_providers.py | 9 +- tests/test_release_workflows.py | 56 ++-- tests/test_runtime.py | 51 ++- tests/test_server.py | 7 +- tests/test_setup.py | 4 +- tests/test_snapshot_repositories.py | 2 +- tests/test_snapshots.py | 4 +- tests/test_terminal.py | 14 +- tests/test_terminal_startup_cleanup.py | 4 +- tests/test_terminal_theme.py | 8 +- tests/test_trust.py | 2 +- tests/test_tui_audit.py | 5 +- tests/test_tui_details.py | 29 +- tests/test_tui_fixes.py | 10 +- tests/test_usercommands.py | 2 +- tests/test_ux_matrix.py | 18 +- tests/test_web_e2e.py | 36 +- tests/test_web_e2e_more.py | 2 +- tests/test_web_files.py | 12 +- tests/test_web_no_project.py | 5 +- tests/test_web_panels.py | 2 +- tests/test_web_ui.py | 8 +- tests/test_web_workbench.py | 4 +- tests/test_windows_support.py | 236 +++++++++++++ tests/test_workbench.py | 24 +- 97 files changed, 2287 insertions(+), 633 deletions(-) create mode 100644 desktop/build/icon.ico create mode 100644 desktop/scripts/bundle-cli.js create mode 100644 install.ps1 create mode 100644 src/freehand/runtime/osutil.py create mode 100644 src/freehand/winpty.py create mode 100644 tests/test_windows_support.py diff --git a/.github/scripts/ci.py b/.github/scripts/ci.py index 56b303ea..3a8988b2 100644 --- a/.github/scripts/ci.py +++ b/.github/scripts/ci.py @@ -120,15 +120,15 @@ def main(): return run_parallel(shards, command) if sys.argv[1:] == ['chrome']: binary = prepare_chrome(os.environ['CHROME_BINARY'], os.environ['RUNNER_OS'], os.environ['RUNNER_TEMP']) - with open(os.environ['GITHUB_ENV'], 'a') as output: + with open(os.environ['GITHUB_ENV'], 'a', encoding='utf-8') as output: output.write(f'FREEHAND_CHROME={binary}\n') print(f'Test browser: {binary}') return 0 if sys.argv[1:] == ['scope']: - event = json.loads(Path(os.environ['GITHUB_EVENT_PATH']).read_text()) + event = json.loads(Path(os.environ['GITHUB_EVENT_PATH']).read_text(encoding='utf-8')) full = full_checks(os.environ['GITHUB_EVENT_NAME'], os.environ['GITHUB_REF'], os.environ['GITHUB_WORKFLOW'], event, changed_files) - with open(os.environ['GITHUB_OUTPUT'], 'a') as output: + with open(os.environ['GITHUB_OUTPUT'], 'a', encoding='utf-8') as output: output.write(f'full={str(full).lower()}\n') print('Full checks required' if full else 'Documentation-only: quick checks are sufficient') return 0 @@ -143,7 +143,7 @@ def main(): summary = '\n'.join(rows) + '\n' print(summary) if os.environ.get('GITHUB_STEP_SUMMARY'): - with open(os.environ['GITHUB_STEP_SUMMARY'], 'a') as output: + with open(os.environ['GITHUB_STEP_SUMMARY'], 'a', encoding='utf-8') as output: output.write(summary) return int(bool(errors)) raise SystemExit('Usage: ci.py scope|result|chrome|parallel') diff --git a/.github/scripts/npm_audit.py b/.github/scripts/npm_audit.py index 4dea5851..ec5ac05b 100644 --- a/.github/scripts/npm_audit.py +++ b/.github/scripts/npm_audit.py @@ -7,6 +7,7 @@ import datetime import json from pathlib import Path +import shutil import subprocess import sys @@ -60,12 +61,14 @@ def problems(report, lock, today, level='moderate'): def main(cwd='.'): - run = subprocess.run(['npm', 'audit', '--json'], cwd=cwd, capture_output=True, text=True) + npm = shutil.which('npm') or 'npm' + run = subprocess.run([npm, 'audit', '--json'], cwd=cwd, capture_output=True, text=True, + encoding='utf-8', errors='replace') try: report = json.loads(run.stdout) except ValueError: report = {'error': run.stderr.strip() or run.stdout.strip()} - lock = json.loads((Path(cwd) / 'package-lock.json').read_text()) + lock = json.loads((Path(cwd) / 'package-lock.json').read_text(encoding='utf-8')) found = problems(report, lock, datetime.date.today()) for line in found: print('npm audit: ' + line, file=sys.stderr) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 374035ef..9cfacd80 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -65,7 +65,7 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu-latest, macos-latest] + os: [ubuntu-latest, macos-latest, windows-latest] python: ["3.10", "3.14"] runs-on: ${{ matrix.os }} steps: @@ -96,7 +96,7 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu-latest, macos-latest] + os: [ubuntu-latest, macos-latest, windows-latest] shard: [1, 2, 3] steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 @@ -152,12 +152,24 @@ jobs: install-script: needs: [scope, quality] if: needs.scope.outputs.full == 'true' - runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + runs-on: ${{ matrix.os }} timeout-minutes: 10 steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 - - run: FREEHAND_INSTALL_SPEC="$PWD" sh install.sh - - run: ~/.local/bin/freehand --version + - if: runner.os != 'Windows' + run: FREEHAND_INSTALL_SPEC="$PWD" sh install.sh + - if: runner.os != 'Windows' + run: ~/.local/bin/freehand --version + - if: runner.os == 'Windows' + shell: pwsh + run: | + $env:FREEHAND_INSTALL_SPEC = (Get-Location).Path + .\install.ps1 + & "$HOME\.local\bin\freehand.exe" --version desktop-dependencies: needs: [scope, quality] diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.yml index 953d3a07..76977ff0 100644 --- a/.github/workflows/desktop-release.yml +++ b/.github/workflows/desktop-release.yml @@ -30,7 +30,7 @@ jobs: strategy: fail-fast: false matrix: - os: [macos-15, macos-15-intel, ubuntu-24.04] + os: [macos-15, macos-15-intel, ubuntu-24.04, windows-latest] runs-on: ${{ matrix.os }} env: CSC_LINK: ${{ secrets.MAC_CSC_LINK }} @@ -55,18 +55,20 @@ jobs: - run: uv sync --locked - run: npm ci working-directory: desktop - - run: python3 ../.github/scripts/npm_audit.py + - run: uv run --no-sync python ../.github/scripts/npm_audit.py working-directory: desktop - run: npm run test:build-deps working-directory: desktop - run: npm run test:updates working-directory: desktop - name: Validate release channel + shell: bash working-directory: desktop run: | node -e 'require("./scripts/release-updates").settings(require("./package.json").version, process.env.RELEASE_CHANNEL, process.env.MAC_SIGNED === "true")' - name: Require matching release versions + shell: bash run: | uv run python -c "import json; from freehand import __version__; \ assert __version__ == json.load(open('desktop/package.json'))['version'], \ @@ -88,6 +90,7 @@ jobs: (umask 077; printf '%s' "$APPLE_API_KEY_CONTENT" > "$key") echo "APPLE_API_KEY=$key" >> "$GITHUB_ENV" - name: Build self-contained CLI and installers + shell: bash working-directory: desktop run: | npm run bundle:cli @@ -122,6 +125,7 @@ jobs: desktop/dist/*.AppImage desktop/dist/*.deb desktop/dist/*.rpm + desktop/dist/*.exe desktop/dist/*.yml desktop/dist/*.blockmap diff --git a/README.md b/README.md index 39fc7f1b..51967c0f 100644 --- a/README.md +++ b/README.md @@ -51,9 +51,8 @@ them well: with weaker models, traditional harnesses still do better ([Results]( ## Install -Supported platforms: **macOS and Linux**. The CLI and web interface also run in Linux under WSL2. -**Native Windows: coming soon.** Desktop builds target macOS (Apple Silicon and Intel) and Linux (x64); -see [desktop/README.md](desktop/README.md) for build details. +Supported platforms: **macOS, Linux, and Windows**. Desktop builds target macOS (Apple Silicon and Intel), +Linux (x64), and Windows (x64); see [desktop/README.md](desktop/README.md) for build details. On macOS or Linux: @@ -61,6 +60,12 @@ On macOS or Linux: curl -LsSf https://raw.githubusercontent.com/microsoft/FreeHand/main/install.sh | sh ``` +On Windows (PowerShell): + +```powershell +irm https://raw.githubusercontent.com/microsoft/FreeHand/main/install.ps1 | iex +``` + Or install from [PyPI](https://pypi.org/project/freehand-ai/) (Python 3.10+): ```bash diff --git a/README.zh-CN.md b/README.zh-CN.md index 7b0b2414..fd4f6d65 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -51,8 +51,7 @@ Freehand 得分最高、成本最低,平均耗时也最短。 ## 安装 -支持平台:**macOS 和 Linux**。命令行和 Web 界面也可在 WSL2 的 Linux 环境中运行。 -**原生 Windows:coming soon(即将支持)。** 桌面构建面向 macOS(Apple Silicon 和 Intel)及 Linux(x64), +支持平台:**macOS、Linux 和 Windows**。桌面构建面向 macOS(Apple Silicon 和 Intel)、Linux(x64)及 Windows(x64), 构建说明见 [desktop/README.md](desktop/README.md)。 在 macOS 或 Linux 上安装: @@ -61,6 +60,12 @@ Freehand 得分最高、成本最低,平均耗时也最短。 curl -LsSf https://raw.githubusercontent.com/microsoft/FreeHand/main/install.sh | sh ``` +在 Windows(PowerShell)上安装: + +```powershell +irm https://raw.githubusercontent.com/microsoft/FreeHand/main/install.ps1 | iex +``` + 也可以直接从 [PyPI](https://pypi.org/project/freehand-ai/) 安装(需 Python 3.10+): ```bash diff --git a/desktop/README.md b/desktop/README.md index c33522a7..8641168b 100644 --- a/desktop/README.md +++ b/desktop/README.md @@ -27,12 +27,12 @@ These actions use the shared local server API, so they also work in `freehand we ## Supported platforms -Desktop builds target **macOS (Apple Silicon and Intel)** and **Linux x64**. The release workflow builds on native -macOS runners and Ubuntu 24.04; Linux packaging produces AppImage, deb and x86_64 RPM files. +Desktop builds target **macOS (Apple Silicon and Intel)**, **Linux x64**, and **Windows x64**. The release workflow +builds on native macOS runners, Ubuntu 24.04, and Windows; Linux packaging produces AppImage, deb and x86_64 RPM +files, and Windows packaging produces an NSIS installer (`.exe`). RPM packages are intended for Fedora users; the build matrix does not test every Linux distribution. -Linux ARM64 desktop builds are not covered by the release matrix. **Native Windows: coming soon.** -The CLI and web interface support macOS and Linux, including Linux under WSL2; WSL2 desktop GUI builds are not a -release target. The published 0.1.1 macOS previews are ad-hoc signed, not Developer ID signed/notarized; +Linux ARM64 and Windows ARM64 desktop builds are not covered by the release matrix. +The CLI and web interface support macOS, Linux (including WSL2), and native Windows. The published 0.1.1 macOS previews are ad-hoc signed, not Developer ID signed/notarized; install them manually. See the update and release requirements below. ## Install the RPM on Fedora diff --git a/desktop/build/icon.ico b/desktop/build/icon.ico new file mode 100644 index 0000000000000000000000000000000000000000..f9b2d3f1f0364e63947253639c4f23668a71f2d6 GIT binary patch literal 91602 zcmafZb8uzB_Vvw;F|lpi*2I|DwrzW2&cwED+qRRN$xJZ8jg4>Kd;fk_zpgrUdiAdE zu2ZL0?cHlN0004i1)!n={xwnnBP0Oe`LBnI`#%f^0{|5L8zUwCAJ&8i0IL2ytgQdT z+W(n{0RV`K{twgO0RY+*06=i?|FEJI01zbjpZa_22tHE1~{pKLE+?rwIT6yp@#@Q}@mx`q3S$Z$bDyAMANF<6z}!DO<=pSi3^b zCMiRY7-q_7#u{N=n3@`~rdOhbLBL~7!L73(h588;lVl}@8)T%k6`wJ*e4Lr-4A=+L zm^}{-PpkFRLwMgD?ZwNM_f{U6Z>#bp;)juw6}Ca>6}CzE*HVv|hi!^PH*vh*%o*IS z6YLw2e79slDVNGPjOK+hgQ`uVrP_kMptrS4k$;+5w62?Od#!`+wa{lTO_N=pg#QJ- zh)`!VcIgkWYEN1r-6P{}h$ExoR-il7(`0IvlXw2LLPd$u!UVeEekg7)uxkMK$HR!_ zkZp=K33(M5Bn+EdPTH;@+OCUIM#!AW-R&S2$h{ru&5%YGO2#F{l{*I{3}sktQtu&S z7f{ur;UAO2Z8gU6yma_V`d*Ox`pdM^JMSvWP4eBCA@BTz?2fQ%C_*n)Q5q^DEAUa| zfx2O&(eD}&$qx#-EBAIq5HP37RJW#IURf-P9>+w-)?#hsrW%p3Ue z!h>+C+8sv^<)1m65@&YWc#hopa^RCU$8;->o9Nf$e&LaKNpky`_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{m)sf?7L<*pS_@$_Gx`D*UV+IIhF2dy)^rC@K)0_eV>A_D|MSb`@x=6 zCdA1vQzJ$g1re6L2L)K_(lh3tCzMbmHhs3TiXJ#Hh+w@oJqGhsIyGf!BQS=5p`UE+Xe`!a4?ZEfOx#N!FOV4%rsh612C3m>`MzL zdz0q#R+`;L`gz;Sv8L%CZhLvKk^VE2zWIF9Ek3!@Y<#@EV0zc9ZhiVTPiu1HUHZVK k&Fweb&^_LUy|cOgADC^0JnUA{=Kufz07*qoM6N<$f { if (folder === null || isFolder(folder)) re function startServer(bin) { return new Promise((resolve, reject) => { let out = "", err = ""; - const run = spawn(bin, ["web", "--background"], { cwd: lastFolder(), stdio: ["ignore", "pipe", "pipe"] }); + const run = spawn(bin, ["web", "--background"], { + cwd: lastFolder(), stdio: ["ignore", "pipe", "pipe"], windowsHide: true, + ...(process.platform === "win32" && /\.(cmd|bat)$/i.test(bin) ? { shell: true } : {}), + }); const timer = setTimeout(() => { run.kill(); reject(new Error("Local service startup timed out (45 seconds).")); }, 45000); run.on("error", (error) => { clearTimeout(timer); reject(error); }); diff --git a/desktop/package.json b/desktop/package.json index 5bd1f67e..72a7ac4e 100644 --- a/desktop/package.json +++ b/desktop/package.json @@ -9,10 +9,10 @@ "main": "main.js", "scripts": { "start": "electron .", - "smoke": "FREEHAND_DESKTOP_SMOKE=1 electron .", + "smoke": "node -e \"const {spawnSync}=require('node:child_process');process.exit(spawnSync(require('electron'),['.'],{stdio:'inherit',env:{...process.env,FREEHAND_DESKTOP_SMOKE:'1'}}).status??1)\"", "app": "npm run bundle:cli && node scripts/dev-app.js", "dist": "npm run bundle:cli && electron-builder", - "bundle:cli": "sh scripts/bundle-cli.sh", + "bundle:cli": "node scripts/bundle-cli.js", "test:build-deps": "node ../tests/desktop_build_dependencies.js", "test:updates": "node ../tests/desktop_updates.js && node ../tests/desktop_release_updates.js" }, @@ -28,6 +28,7 @@ "preload.js", "package.json", "build/icon.png", + "build/icon.ico", "recovery.js", "notice.js", "notice.html", @@ -57,6 +58,22 @@ "rpm" ] }, + "win": { + "icon": "build/icon.ico", + "target": [ + { + "target": "nsis", + "arch": [ + "x64" + ] + } + ] + }, + "nsis": { + "oneClick": false, + "allowToChangeInstallationDirectory": true, + "artifactName": "Freehand-Setup-${version}.${ext}" + }, "extraResources": [ { "from": "runtime/freehand", diff --git a/desktop/scripts/bundle-cli.js b/desktop/scripts/bundle-cli.js new file mode 100644 index 00000000..31fb0294 --- /dev/null +++ b/desktop/scripts/bundle-cli.js @@ -0,0 +1,25 @@ +// Build the self-contained CLI on each target OS/architecture without copying user settings or credentials. +const { execFileSync } = require("node:child_process"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); + +const root = path.resolve(__dirname, "..", ".."); +const uv = process.platform === "win32" ? "uv.exe" : "uv"; +const args = [ + "run", "--with", "pyinstaller", "pyinstaller", "--noconfirm", "--clean", "--onedir", "--name", "freehand", + "--distpath", "desktop/runtime", "--workpath", "desktop/.pyinstaller", "--specpath", "desktop/.pyinstaller", + "--collect-all", "freehand", "--collect-all", "anthropic", "--collect-all", "prompt_toolkit", "--collect-all", "rich", + "--hidden-import", "freehand.terminal_child", "--hidden-import", "freehand.winpty", + "--hidden-import", "freehand.__main__", "desktop/bundle_entry.py", +]; +execFileSync(uv, args, { cwd: root, stdio: "inherit" }); + +const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "freehand-bundle-")); +try { + const binary = path.join(root, "desktop", "runtime", "freehand", + process.platform === "win32" ? "freehand.exe" : "freehand"); + execFileSync(binary, ["--version"], { cwd: root, env: { ...process.env, FREEHAND_HOME: tmpHome }, stdio: "inherit" }); +} finally { + fs.rmSync(tmpHome, { recursive: true, force: true }); +} diff --git a/desktop/scripts/release-updates.js b/desktop/scripts/release-updates.js index 0d64f3fc..e34d5933 100644 --- a/desktop/scripts/release-updates.js +++ b/desktop/scripts/release-updates.js @@ -26,17 +26,19 @@ function assets(version) { `Freehand-${version}.dmg`, `Freehand-${version}-arm64.dmg`]; const linux = [`Freehand-${version}.AppImage`, `freehand-desktop_${version}_amd64.deb`, `freehand-desktop-${version}.x86_64.rpm`]; - return { mac, linux }; + const win = [`Freehand-Setup-${version}.exe`]; + return { mac, linux, win }; } async function merge(input, output, { version, channel, macSigned }) { settings(version, channel, macSigned); if (fs.existsSync(output)) throw new Error("Output directory must not already exist"); - const { mac, linux } = assets(version); + const { mac, linux, win } = assets(version); const sources = [ ["Freehand-macos-15-intel", "latest-mac.yml", [mac[0], mac[2]]], ["Freehand-macos-15", "latest-mac.yml", [mac[1], mac[3]]], ["Freehand-ubuntu-24.04", "latest-linux.yml", linux], + ["Freehand-windows-latest", "latest.yml", win], ]; const entries = new Map(), copies = new Map(), metadata = new Map(); for (const [directory, manifest, expected] of sources) { @@ -54,7 +56,7 @@ async function merge(input, output, { version, channel, macSigned }) { || file.sha512 !== await hashFile(source, "sha512", "base64")) throw new Error(`Invalid asset: ${file.url}`); entries.set(file.url, { ...file, size }); copies.set(file.url, source); - if (manifest === "latest-mac.yml") { + if (manifest === "latest-mac.yml" || manifest === "latest.yml") { const blockmap = `${source}.blockmap`; if (!fs.lstatSync(blockmap).isFile() || !fs.statSync(blockmap).size) throw new Error("Missing blockmap"); copies.set(`${file.url}.blockmap`, blockmap); @@ -69,7 +71,7 @@ async function merge(input, output, { version, channel, macSigned }) { } fs.mkdirSync(output, { recursive: true }); for (const [name, source] of copies) fs.copyFileSync(source, path.join(output, name)); - for (const [manifest, names] of [["latest-mac.yml", mac], ["latest-linux.yml", linux]]) { + for (const [manifest, names] of [["latest-mac.yml", mac], ["latest-linux.yml", linux], ["latest.yml", win]]) { const original = metadata.get(manifest); const info = { version, files: names.map((name) => entries.get(name)), path: names[0], sha512: entries.get(names[0]).sha512, freehandUpdateChannel: channel, @@ -106,13 +108,14 @@ function publish(directory, { version, channel, macSigned, commit }, run = execF } if (object.type !== "commit" || object.sha !== commit) throw new Error("Existing tag points to another commit"); } - const { mac, linux } = assets(version); - const expected = [...mac, ...linux, ...mac.map((name) => `${name}.blockmap`), - "latest-mac.yml", "latest-linux.yml", "SHA256SUMS-desktop.txt"].sort(); + const { mac, linux, win } = assets(version); + const expected = [...mac, ...linux, ...win, ...mac.map((name) => `${name}.blockmap`), + ...win.map((name) => `${name}.blockmap`), "latest-mac.yml", "latest-linux.yml", "latest.yml", + "SHA256SUMS-desktop.txt"].sort(); if (JSON.stringify(fs.readdirSync(directory).sort()) !== JSON.stringify(expected)) { throw new Error("Release directory must contain exactly the merged desktop assets"); } - for (const manifest of ["latest-mac.yml", "latest-linux.yml"]) { + for (const manifest of ["latest-mac.yml", "latest-linux.yml", "latest.yml"]) { const info = yaml.load(fs.readFileSync(path.join(directory, manifest), "utf8")); if (info.version !== version || info.freehandUpdateChannel !== channel || (manifest === "latest-mac.yml" && info.freehandMacSigned !== macSigned)) { diff --git a/desktop/scripts/render-icons.py b/desktop/scripts/render-icons.py index 5927988c..124d1d84 100644 --- a/desktop/scripts/render-icons.py +++ b/desktop/scripts/render-icons.py @@ -15,7 +15,8 @@ ROOT = Path(__file__).resolve().parents[2] SOURCE = "src/freehand/web/favicon.svg" -OUTPUTS = ("desktop/build/icon.png", "desktop/build/icon-mac.png") +OUTPUTS = ("desktop/build/icon.png", "desktop/build/icon-mac.png", "desktop/build/icon.ico") +ICO_SIZES = [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)] def main(): @@ -23,6 +24,7 @@ def main(): icon = Image.open(io.BytesIO(data)).convert("RGBA") (ROOT / OUTPUTS[0]).parent.mkdir(parents=True, exist_ok=True) icon.save(ROOT / OUTPUTS[0]) + icon.save(ROOT / OUTPUTS[2], format="ICO", sizes=ICO_SIZES) # macOS does not add its own safe area; preserve the 824 px tile and its 100 px margins. tile = icon.resize((824, 824), Image.Resampling.LANCZOS) diff --git a/desktop/updates.js b/desktop/updates.js index 9f04e366..3ddd9fdb 100644 --- a/desktop/updates.js +++ b/desktop/updates.js @@ -30,6 +30,7 @@ function latestRelease(releases, current, channel) { function installerNames(version, platform, arch, packageType) { if (platform === "darwin" && arch === "arm64") return [`Freehand-${version}-arm64.dmg`]; if (platform === "darwin" && arch === "x64") return [`Freehand-${version}.dmg`]; + if (platform === "win32" && arch === "x64") return [`Freehand-Setup-${version}.exe`]; if (platform === "linux" && arch === "x64") { if (packageType === "deb") return [`freehand-desktop_${version}_amd64.deb`]; if (packageType === "rpm") return [`freehand-desktop-${version}.x86_64.rpm`]; diff --git a/install.ps1 b/install.ps1 new file mode 100644 index 00000000..72d40140 --- /dev/null +++ b/install.ps1 @@ -0,0 +1,41 @@ +# Install Freehand with uv, which also provides the Python it runs on; nothing else needs to be installed first. +# +# irm https://raw.githubusercontent.com/microsoft/FreeHand/main/install.ps1 | iex +# +# FREEHAND_INSTALL_SPEC picks something else to install, for example a local checkout. +# Run it again, or `freehand update`, to upgrade. +$ErrorActionPreference = "Stop" + +$spec = if ($env:FREEHAND_INSTALL_SPEC) { $env:FREEHAND_INSTALL_SPEC } else { "git+https://github.com/microsoft/FreeHand" } +$callerPath = $env:PATH + +if (-not (Get-Command uv -ErrorAction SilentlyContinue)) { + Write-Host "Installing uv (https://docs.astral.sh/uv/), which manages Freehand's Python environment..." + Invoke-RestMethod https://astral.sh/uv/install.ps1 | Invoke-Expression + $extra = @( + (Join-Path $HOME ".local\bin"), + (Join-Path $HOME ".cargo\bin") + ) | Where-Object { Test-Path $_ } + if ($extra) { + $env:PATH = ($extra -join ";") + ";" + $env:PATH + } +} + +& uv tool install --upgrade --python 3.12 $spec +if ($LASTEXITCODE -ne 0) { + exit $LASTEXITCODE +} + +$binDir = (& uv tool dir --bin 2>$null) +if (-not $binDir) { + $binDir = Join-Path $HOME ".local\bin" +} + +Write-Host "" +Write-Host "Freehand is installed. Next:" +$pathParts = ($callerPath -split ";") | ForEach-Object { $_.TrimEnd("\").ToLowerInvariant() } +if ($pathParts -notcontains $binDir.TrimEnd("\").ToLowerInvariant()) { + Write-Host " uv tool update-shell # then open a new terminal: $binDir is not on PATH yet" +} +Write-Host " freehand login # Continue with ChatGPT (or an API key: freehand login openai | anthropic)" +Write-Host " cd your\project; freehand" diff --git a/pyproject.toml b/pyproject.toml index a32b933a..d2959427 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -18,6 +18,7 @@ classifiers = [ "Environment :: Console", "Intended Audience :: Developers", "Operating System :: MacOS", + "Operating System :: Microsoft :: Windows", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 3", "Topic :: Software Development", diff --git a/src/freehand/cli.py b/src/freehand/cli.py index 5cb75275..9be1b736 100644 --- a/src/freehand/cli.py +++ b/src/freehand/cli.py @@ -15,7 +15,7 @@ from freehand import __version__ from freehand.runtime import agent as runtime -from freehand.runtime import auth, providers +from freehand.runtime import auth, osutil, providers PROMPT = Path(__file__).resolve().parent / "prompt.md" DIST = "freehand-ai" # the distribution name; the command and the package are called freehand @@ -925,6 +925,10 @@ def cmd_web(args: argparse.Namespace) -> int: if not args.no_open: import webbrowser webbrowser.open(url) + import signal + import threading + if hasattr(signal, "SIGBREAK"): + signal.signal(signal.SIGBREAK, lambda *_: threading.Thread(target=httpd.shutdown, daemon=True).start()) try: httpd.serve_forever() except KeyboardInterrupt: @@ -989,8 +993,9 @@ def row(passed: bool | None, label: str, detail: str) -> None: else: row(None, "git", "not found (/undo snapshots disabled)") # 2. Shell - shell_bin = shutil.which("bash") or shutil.which("sh") - row(bool(shell_bin), "shell", shell_bin or "neither bash nor sh found on PATH") + shell_bin = osutil.find_shell() if osutil.IS_WINDOWS else (shutil.which("bash") or shutil.which("sh")) + shell_ok = bool(shell_bin and (Path(shell_bin).is_file() or shutil.which(shell_bin))) + row(shell_ok, "shell", shell_bin or "neither bash nor sh found on PATH") # 3. Credentials & private file permissions cfg = session.new_config(Path.cwd(), interactive=True) prob = session.credentials_problem(cfg) @@ -1000,15 +1005,19 @@ def row(passed: bool | None, label: str, detail: str) -> None: for fname in ("auth.json", "web.json"): fp = home / fname if fp.exists(): - mode = stat.S_IMODE(fp.stat().st_mode) - safe = (mode & 0o077) == 0 - row(safe, fname, f"mode {oct(mode)}" + ("" if safe else f" (too open; run `chmod 600 {fp}`)")) + if osutil.IS_WINDOWS: + row(True, fname, "Windows user ACL") + else: + mode = stat.S_IMODE(fp.stat().st_mode) + safe = (mode & 0o077) == 0 + row(safe, fname, f"mode {oct(mode)}" + ("" if safe else f" (too open; run `chmod 600 {fp}`)")) # 4. Proxy & tools proxies = [f"{k}={_os.environ[k]}" for k in ("HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY", "NO_PROXY") if _os.environ.get(k)] row(True, "proxy", ", ".join(proxies) if proxies else "none") editor = _os.environ.get("VISUAL") or _os.environ.get("EDITOR") or "unset" - clip = ("osascript" if sys.platform == "darwin" else shutil.which("wl-paste") or shutil.which("xclip") or "none") + clip = ("windows" if sys.platform == "win32" else "osascript" if sys.platform == "darwin" + else shutil.which("wl-paste") or shutil.which("xclip") or "none") row(True, "tools", f"editor={editor}, clipboard={clip}, node={'yes' if shutil.which('node') else 'no'}") # 5. Disk usage under ~/.freehand sizes = {name: _dir_bytes(home / name) for name in ("sessions", "trace", "snapshots", "trash", "web.log")} @@ -1149,17 +1158,7 @@ def cmd_update(args: argparse.Namespace) -> int: def main(argv: list[str] | None = None) -> int: - raw = sys.argv[1:] if argv is None else list(argv) - if sys.platform == "win32" and not any(a in ("-h", "--help", "--version") for a in raw): - print( - "Freehand does not run natively on Windows yet (it requires POSIX bash).\n" - "Run Freehand inside WSL2 instead:\n" - " 1. PowerShell: wsl --install\n" - " 2. Inside WSL2: " - "curl -LsSf https://raw.githubusercontent.com/microsoft/FreeHand/main/install.sh | sh", - file=sys.stderr, - ) - return 2 + osutil.enable_windows_console() parser = argparse.ArgumentParser(prog="freehand", description="An agent harness that leaves the decisions to the model. " "Run without a command for an interactive session in the current directory.") parser.add_argument("--version", action="version", version=f"freehand {__version__}") diff --git a/src/freehand/control.py b/src/freehand/control.py index c1a5961f..0d610e1e 100644 --- a/src/freehand/control.py +++ b/src/freehand/control.py @@ -20,15 +20,11 @@ from typing import Any, Callable from freehand import export, hooks, inputs, session, ui +from freehand.runtime import osutil from freehand.runtime.agent import Agent, Cancelled, SessionBusy, image_part from freehand.snapshots import SnapshotError, Snapshots from freehand.suggestions import Suggestions -try: - import fcntl -except ImportError: # Windows: no session lock to look at, and so no turn of another process to follow - fcntl = None # type: ignore[assignment] - OUTPUT_MAX = 20000 # characters of a command's output sent to an interface; the whole is in the session TAIL_EVERY_S = 0.2 # how often a running command's output file is read for the interface WATCH_EVERY_S = 0.5 # how often the journal is looked at for what another Freehand process does @@ -367,21 +363,9 @@ def locked_elsewhere(self) -> bool: """Whether another Freehand process runs a turn of this session now: it holds the session's lock. Looked at with a shared lock let go at once, and only when there is reason to (see watch), since the other process could not take the lock in the moment this one holds it.""" - if fcntl is None or self.busy: - return False - try: - fd = os.open(self.agent.state_dir / "session.lock", os.O_RDONLY) - except OSError: - return False - try: - fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB) - except OSError: - return True - else: - fcntl.flock(fd, fcntl.LOCK_UN) + if self.busy: return False - finally: - os.close(fd) + return osutil.is_file_locked(osutil.session_lock_path(self.dir)) def mine(self) -> None: """What this process wrote to the journal is not another's work.""" @@ -818,7 +802,7 @@ def started(proc: Any) -> None: finally: with self.lock: self.shell_proc = self.shell_cancel = None - if box and box[0].returncode is not None and box[0].returncode < 0: + if cancel.is_set() or (box and box[0].returncode is not None and box[0].returncode < 0): output += "\n[stopped]" if share: shared = f"I ran this command myself:\n$ {command}\n{output.rstrip()}\n[exit {rc}]" @@ -1029,11 +1013,20 @@ def image_file(self, raw: str) -> tuple[bytes, str]: """An image the model shows in a reply (`![...](path)`): read for the page, but only an image (by its bytes), and only from the working directory, the session or the temp directories, so a reply cannot put any other file of the machine on the page.""" + import re import tempfile + import urllib.parse from freehand.runtime.agent import image_mime from freehand.server import ApiError workdir = Path(self.agent.cfg.get("workdir") or self.cwd) - path = Path(raw.removeprefix("file://")).expanduser() + cleaned = raw + if cleaned.lower().startswith("file://"): + url = urllib.parse.urlsplit(cleaned) + cleaned = url.path + if os.name == "nt" and re.match(r"^/[a-zA-Z]:/", cleaned): + cleaned = cleaned[1:] + cleaned = urllib.parse.unquote(cleaned) + path = Path(cleaned).expanduser() path = (path if path.is_absolute() else workdir / path).resolve() roots = {workdir.resolve(), self.dir.resolve(), Path(tempfile.gettempdir()).resolve(), Path("/tmp").resolve()} if not any(path == r or r in path.parents for r in roots) or not path.is_file(): diff --git a/src/freehand/copilot_bridge.py b/src/freehand/copilot_bridge.py index fdc1912c..3ec5c0b7 100644 --- a/src/freehand/copilot_bridge.py +++ b/src/freehand/copilot_bridge.py @@ -283,6 +283,12 @@ async def serve(emit: Callable[[dict], Any]) -> None: def main() -> None: + for stream in (sys.stdin, sys.stdout): + if hasattr(stream, "reconfigure"): + try: + stream.reconfigure(encoding="utf-8", errors="replace") + except (OSError, ValueError): + pass output = sys.stdout # SDK diagnostics must not share the protocol stream, and may contain service-provided sensitive details. with open(os.devnull, "w") as sink, contextlib.redirect_stdout(sink): diff --git a/src/freehand/daemon.py b/src/freehand/daemon.py index 00340711..2a61a03d 100644 --- a/src/freehand/daemon.py +++ b/src/freehand/daemon.py @@ -20,7 +20,7 @@ from pathlib import Path from typing import Any -from freehand.runtime import auth +from freehand.runtime import auth, osutil # a server with nothing running and no page open this long ends (FREEHAND_WEB_IDLE_S: for tests) IDLE_S = float(os.environ.get("FREEHAND_WEB_IDLE_S") or 600) @@ -102,14 +102,14 @@ def ensure(cwd: Path) -> dict[str, Any]: log_path = auth.home() / "web.log" try: if log_path.exists() and log_path.stat().st_size > 5_000_000: - os.replace(log_path, auth.home() / "web.log.1") + osutil.replace_file(log_path, auth.home() / "web.log.1") except OSError: pass log_fd = os.open(log_path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) with os.fdopen(log_fd, "ab") as log: prefix = [sys.executable] if getattr(sys, "frozen", False) else [sys.executable, "-m", "freehand"] subprocess.Popen([*prefix, "web", "--daemon"], cwd=str(cwd), stdin=subprocess.DEVNULL, - stdout=log, stderr=log, start_new_session=True) # its own session: it outlives the app + stdout=log, stderr=log, **osutil.detached_popen_kwargs()) # outlives the app end = time.time() + START_TIMEOUT_S while time.time() < end: state = read_state() @@ -135,15 +135,7 @@ def serve(cwd: Path) -> int: state = {"url": server.address(httpd, hub), "token": hub.token, "pid": os.getpid(), "build": build, "version": __version__, "started": time.time()} path = state_path() - path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) - tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp") - fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) - with os.fdopen(fd, "w", encoding="utf-8") as f: - f.write(json.dumps(state)) - f.flush() - os.fsync(f.fileno()) - os.replace(tmp, path) - os.chmod(path, 0o600) + osutil.atomic_write_text(path, json.dumps(state), private=True, fsync=True) def watch() -> None: while True: diff --git a/src/freehand/hooks.py b/src/freehand/hooks.py index 21e069af..d2505a2b 100644 --- a/src/freehand/hooks.py +++ b/src/freehand/hooks.py @@ -21,6 +21,7 @@ from typing import Any from freehand import session +from freehand.runtime import osutil EVENTS = ("on_session_start", "pre_bash", "post_bash", "post_turn") DEFAULT_TIMEOUT_S = 15.0 @@ -79,11 +80,33 @@ def run_event(event: str, payload: dict[str, Any], cwd: Path | None = None, *, b tempfile.TemporaryFile() as stderr: stdin.write(body) stdin.seek(0) - done = subprocess.run( - spec["command"], shell=True, stdin=stdin, stdout=stdout, stderr=stderr, - timeout=spec["timeout_s"], cwd=str(cwd) if cwd and cwd.is_dir() else None, - ) - reason = _hook_reason(stderr, stdout) if blocking and done.returncode != 0 else "" + run_cwd = str(cwd) if cwd and cwd.is_dir() else None + if osutil.IS_WINDOWS: + argv, tmp_script = osutil.prepare_shell_command(spec["command"]) + job = osutil.create_process_job() + try: + proc = subprocess.Popen( + argv, stdin=stdin, stdout=stdout, stderr=stderr, cwd=run_cwd, + **osutil.popen_group_kwargs(), + ) + osutil.assign_process_job(job, proc) + try: + rc = proc.wait(timeout=spec["timeout_s"]) + except subprocess.TimeoutExpired: + osutil.kill_process_tree(proc, job) + proc.wait() + raise + finally: + osutil.close_process_job(job) + if tmp_script is not None: + tmp_script.unlink(missing_ok=True) + else: + done = subprocess.run( + spec["command"], shell=True, stdin=stdin, stdout=stdout, stderr=stderr, + timeout=spec["timeout_s"], cwd=run_cwd, + ) + rc = done.returncode + reason = _hook_reason(stderr, stdout) if blocking and rc != 0 else "" except subprocess.TimeoutExpired: if blocking: return f"hook timed out after {spec['timeout_s']:g}s" @@ -92,8 +115,8 @@ def run_event(event: str, payload: dict[str, Any], cwd: Path | None = None, *, b if blocking: return f"hook could not run ({exc})" continue - if blocking and done.returncode != 0: - return reason or f"hook exited with status {done.returncode}" + if blocking and rc != 0: + return reason or f"hook exited with status {rc}" return None diff --git a/src/freehand/inputs.py b/src/freehand/inputs.py index c79d28b8..722ab041 100644 --- a/src/freehand/inputs.py +++ b/src/freehand/inputs.py @@ -14,6 +14,7 @@ from prompt_toolkit.completion import Completer, Completion from prompt_toolkit.history import FileHistory +from freehand.runtime import osutil from freehand.runtime.agent import image_part, truncate_middle from freehand.session import GIT @@ -50,6 +51,10 @@ def _image_file(raw: str, cwd: Path, *, shell_escaped: bool) -> Path | None: if path is not None: return path if PureWindowsPath(raw).is_absolute(): + if sys.platform == "win32" and shell_escaped and "\\ " in raw: + unescaped = raw.replace("\\ ", " ") + if unescaped != raw: + return existing(unescaped, cwd) # Terminal can paste Windows paths into WSL unchanged; wslpath knows the actual drive and UNC mounts. if sys.platform != "linux": return None @@ -62,7 +67,7 @@ def _image_file(raw: str, cwd: Path, *, shell_escaped: bool) -> Path | None: return existing(translated, cwd) return None if shell_escaped: - unescaped = re.sub(r"\\(.)", r"\1", raw) + unescaped = raw.replace("\\ ", " ") if sys.platform == "win32" else re.sub(r"\\(.)", r"\1", raw) if unescaped != raw: return existing(unescaped, cwd) return None @@ -90,7 +95,8 @@ def _scan(self) -> list[str]: try: # NUL delimiters preserve names that Git otherwise quotes, including tabs, quotes and backslashes. out = subprocess.run([*GIT, "ls-files", "-z", "-co", "--exclude-standard"], - cwd=self.root, capture_output=True, text=True, timeout=5) + cwd=self.root, capture_output=True, text=True, encoding="utf-8", errors="replace", + timeout=5) if out.returncode == 0: return [f for f in out.stdout.split("\0") if f and not GENERATED.search(f)][:MAX_FILES] except (OSError, subprocess.SubprocessError): @@ -98,7 +104,7 @@ def _scan(self) -> list[str]: found: list[str] = [] for dirpath, dirnames, filenames in os.walk(self.root): dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS and not d.startswith(".")] - rel = os.path.relpath(dirpath, self.root) + rel = os.path.relpath(dirpath, self.root).replace(os.sep, "/") found += [p for p in (f if rel == "." else f"{rel}/{f}" for f in filenames) if not GENERATED.search(p)] if len(found) >= MAX_FILES: break @@ -146,7 +152,7 @@ def add() -> None: if os.path.exists(self.filename): with open(self.filename, "rb") as f: for raw in f: - line = raw.decode("utf-8", errors="replace") + line = raw.decode("utf-8", errors="replace").replace("\r\n", "\n") if line.startswith("+"): lines.append(line[1:]) continue @@ -206,8 +212,23 @@ def find_images(text: str, cwd: Path, max_bytes: int = 4_000_000) -> tuple[list[ def clipboard_image() -> bytes | None: """The image on the clipboard as PNG bytes, or None. macOS reads it with osascript (PNG, or TIFF converted with - sips); Linux with wl-paste on Wayland or xclip on X11.""" + sips); Windows with PowerShell System.Windows.Forms; Linux with wl-paste on Wayland or xclip on X11.""" try: + if sys.platform == "win32": + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "clip.png") + ps = shutil.which("powershell.exe") or shutil.which("powershell") or osutil.find_shell() + script = ( + "Add-Type -AssemblyName System.Windows.Forms; Add-Type -AssemblyName System.Drawing; " + "$img = [System.Windows.Forms.Clipboard]::GetImage(); " + f"if ($null -ne $img) {{ $img.Save({osutil.quote_shell_arg(path)}, " + "[System.Drawing.Imaging.ImageFormat]::Png); $img.Dispose() }}" + ) + subprocess.run([ps, "-NoLogo", "-NoProfile", "-NonInteractive", "-Sta", "-Command", script], + capture_output=True, timeout=5, creationflags=subprocess.CREATE_NO_WINDOW) + if os.path.exists(path) and os.path.getsize(path): + return Path(path).read_bytes() or None + return None if sys.platform == "darwin": with tempfile.TemporaryDirectory() as tmp: for cls, name in (("PNGf", "clip.png"), ("TIFF", "clip.tiff")): @@ -255,23 +276,37 @@ def run_shell(command: str, cwd: Path, max_chars: int = 40000, """Run the person's own `!command` in their shell environment. Returns (exit code, output, middle-truncated). *started* is given the process, so that it can be stopped (the page's Esc); it runs in a group of its own, so stopping it stops what it started too. *output* gets the output as it comes, for the screen to show it live.""" - proc = subprocess.Popen(["bash", "-lc", command], cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, - stdin=subprocess.DEVNULL, start_new_session=True) - if started: - started(proc) - chunks = output if output is not None else [] + argv, tmp_script = osutil.prepare_shell_command(command) + env = osutil.prepare_shell_env(dict(os.environ)) + job = osutil.create_process_job() + proc: Any = None try: - assert proc.stdout is not None - while True: - chunk = proc.stdout.read1(65536) - if not chunk: - break - chunks.append(chunk) - proc.wait() - except BaseException: # Ctrl-C in the terminal: the command goes with it - stop_shell(proc) - raise - return proc.returncode, truncate_middle(b"".join(chunks).decode("utf-8", "replace"), max_chars, None) + proc = subprocess.Popen(argv, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + stdin=subprocess.DEVNULL, env=env, **osutil.popen_group_kwargs()) + osutil.assign_process_job(job, proc) + proc._freehand_job = job + if started: + started(proc) + chunks = output if output is not None else [] + try: + assert proc.stdout is not None + while True: + chunk = proc.stdout.read1(65536) + if not chunk: + break + chunks.append(chunk) + proc.wait() + except BaseException: # Ctrl-C in the terminal: the command goes with it + stop_shell(proc) + raise + text = osutil.normalize_output(b"".join(chunks).decode("utf-8", "replace")) + return proc.returncode, truncate_middle(text, max_chars, None) + finally: + osutil.close_process_job(job) + if proc is not None: + proc._freehand_job = None + if tmp_script is not None: + tmp_script.unlink(missing_ok=True) def shown_so_far(chunks: list[bytes], limit: int = 200_000) -> str: @@ -282,13 +317,10 @@ def shown_so_far(chunks: list[bytes], limit: int = 200_000) -> str: def stop_shell(proc: Any) -> None: - import signal + job = getattr(proc, "_freehand_job", None) try: - os.killpg(proc.pid, signal.SIGTERM) + osutil.kill_process_tree(proc, job, graceful=True) proc.wait(2) except (OSError, subprocess.TimeoutExpired): - try: - os.killpg(proc.pid, signal.SIGKILL) - except OSError: - pass + osutil.kill_process_tree(proc, job, graceful=False) proc.wait() diff --git a/src/freehand/integrations/harbor.py b/src/freehand/integrations/harbor.py index ca803e52..555f53b5 100644 --- a/src/freehand/integrations/harbor.py +++ b/src/freehand/integrations/harbor.py @@ -167,6 +167,10 @@ async def run(self, instruction: str, environment: BaseEnvironment, context: Age # predictable mode, instead of inheriting whatever the checkout's umask left behind. src = tmp / "harness" shutil.copytree(RUNTIME, src, ignore=shutil.ignore_patterns("__pycache__", "*.pyc")) + # Linux bash rejects CRLF in run.sh if the host checkout on Windows converted line endings. + run_sh = src / "run.sh" + if run_sh.is_file(): + run_sh.write_bytes(run_sh.read_bytes().replace(b"\r\n", b"\n")) src.chmod(0o755) # copytree preserves a checkout's private root mode; non-root task users must read it. shutil.copy2(PROMPT, tmp / "prompt.md") for f in src.rglob("*"): diff --git a/src/freehand/limits.py b/src/freehand/limits.py index 722efe39..1d510550 100644 --- a/src/freehand/limits.py +++ b/src/freehand/limits.py @@ -25,7 +25,7 @@ from typing import Any, Callable from freehand import __version__ -from freehand.runtime import auth +from freehand.runtime import auth, osutil CODEX_TIMEOUT_S = 15 INSTALL_TIMEOUT_S = 300 @@ -44,12 +44,17 @@ def find_codex() -> str | None: if found: return found places = [Path.home() / ".local" / "bin", Path("/opt/homebrew/bin"), Path("/usr/local/bin")] + if osutil.IS_WINDOWS and os.environ.get("APPDATA"): + places.insert(0, Path(os.environ["APPDATA"]) / "npm") node = shutil.which("node") if node: places.insert(0, Path(os.path.realpath(node)).parent) + names = ("codex.cmd", "codex.exe", "codex") if osutil.IS_WINDOWS else ("codex",) for place in places: - if os.access(place / "codex", os.X_OK): - return str(place / "codex") + for name in names: + cand = place / name + if cand.is_file() and (osutil.IS_WINDOWS or os.access(cand, os.X_OK)): + return str(cand) return None @@ -58,8 +63,14 @@ def find_npm() -> str | None: if found: return found node = shutil.which("node") - beside = Path(os.path.realpath(node)).parent / "npm" if node else None - return str(beside) if beside and os.access(beside, os.X_OK) else None + if not node: + return None + parent = Path(os.path.realpath(node)).parent + for name in (("npm.cmd", "npm.exe", "npm") if osutil.IS_WINDOWS else ("npm",)): + beside = parent / name + if beside.is_file() and (osutil.IS_WINDOWS or os.access(beside, os.X_OK)): + return str(beside) + return None def install_codex() -> dict[str, Any]: @@ -81,9 +92,11 @@ def install_codex() -> dict[str, Any]: def _rpc(command: list[str], calls: list[tuple[str, dict[str, Any] | None]], timeout: float) -> list[dict[str, Any]]: """Run an app server over standard input and output (a JSON object a line) and return the reply to each call.""" + job = osutil.create_process_job() proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, - text=True, encoding="utf-8") - timer = threading.Timer(timeout, proc.kill) # a server that never answers must not hold the request + text=True, encoding="utf-8", **osutil.popen_group_kwargs()) + osutil.assign_process_job(job, proc) + timer = threading.Timer(timeout, lambda: osutil.kill_process_tree(proc, job)) timer.start() try: def send(obj: dict[str, Any]) -> None: @@ -113,7 +126,8 @@ def reply(want: int) -> dict[str, Any]: return out finally: timer.cancel() - proc.kill() + osutil.kill_process_tree(proc, job) + osutil.close_process_job(job) proc.wait() diff --git a/src/freehand/mcp.py b/src/freehand/mcp.py index 9a28837a..83b978b2 100644 --- a/src/freehand/mcp.py +++ b/src/freehand/mcp.py @@ -37,7 +37,7 @@ from typing import Any from freehand import __version__ -from freehand.runtime import auth +from freehand.runtime import auth, osutil PROTOCOL = "2025-06-18" TIMEOUT_S = 120.0 @@ -71,13 +71,18 @@ class Stdio: """A server started as a process: one JSON message per line, in and out.""" def __init__(self, spec: dict[str, Any]) -> None: - env = {**os.environ, **{str(k): expand(v) for k, v in (spec.get("env") or {}).items()}} - argv = [str(spec["command"]), *map(str, spec.get("args") or [])] + extra = {str(k): expand(v) for k, v in (spec.get("env") or {}).items()} + env = osutil.prepare_shell_env({**os.environ, **extra}) + argv = [osutil.resolve_executable(str(spec["command"])), *map(str, spec.get("args") or [])] + self.job = osutil.create_process_job() try: self.proc = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, - env=env, cwd=spec.get("cwd") or None) + env=env, cwd=spec.get("cwd") or None, **osutil.popen_group_kwargs()) except OSError as exc: + osutil.close_process_job(self.job) + self.job = None raise McpError(f"could not start `{' '.join(argv)}` ({exc.strerror or exc})") from None + osutil.assign_process_job(self.job, self.proc) self.inbox: queue.Queue[Any] = queue.Queue() self.errors: deque[str] = deque(maxlen=40) threading.Thread(target=self._read, daemon=True).start() @@ -135,7 +140,14 @@ def close(self) -> None: self.proc.stdin.close() self.proc.wait(3) except (OSError, subprocess.TimeoutExpired): - self.proc.kill() + osutil.kill_process_tree(self.proc, self.job) + try: + self.proc.wait(2) + except (OSError, subprocess.TimeoutExpired): + pass + finally: + osutil.close_process_job(self.job) + self.job = None class Http: @@ -380,9 +392,10 @@ def _ensure(self) -> None: return except (OSError, McpError, ValueError): self.sock.unlink(missing_ok=True) - subprocess.Popen([sys.executable, "-m", "freehand", "mcp", "_daemon", self.name], + prefix = [sys.executable] if getattr(sys, "frozen", False) else [sys.executable, "-m", "freehand"] + subprocess.Popen([*prefix, "mcp", "_daemon", self.name], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, - start_new_session=True) + **osutil.detached_popen_kwargs()) deadline = time.time() + min(15.0, self.timeout) while time.time() < deadline: if self.sock.exists(): diff --git a/src/freehand/runtime/agent.py b/src/freehand/runtime/agent.py index ec5587c3..51a2ef97 100755 --- a/src/freehand/runtime/agent.py +++ b/src/freehand/runtime/agent.py @@ -30,8 +30,6 @@ import os import random import re -import shutil -import signal import socket import ssl import subprocess @@ -45,15 +43,11 @@ from pathlib import Path from typing import Any, Callable, Iterator -try: - import fcntl -except ImportError: - fcntl = None # type: ignore[assignment] - try: # imported as freehand.runtime.agent from . import auth as _auth from . import providers as _providers from . import compaction as _compaction + from . import osutil as _osutil from . import progress as _progress from . import shellenv as _shellenv from . import calltrace as _trace @@ -62,6 +56,7 @@ import auth as _auth # noqa: E402 import providers as _providers # noqa: E402 import compaction as _compaction # noqa: E402 + import osutil as _osutil # noqa: E402 import progress as _progress # noqa: E402 import shellenv as _shellenv # noqa: E402 import calltrace as _trace # noqa: E402 @@ -296,15 +291,26 @@ def tool_specs(user: str = "root") -> list[dict[str, Any]]: def _tool_specs(user: str) -> list[dict[str, Any]]: + if _osutil.IS_WINDOWS: + shell = _osutil.shell_name() + desc = ( + f"Run a PowerShell command ({shell}) as {user} in the workdir from config.json. Returns combined " + "stdout+stderr and the exit code; the process tree is killed after timeout_s seconds (default from " + "config.json). For a job that should keep running, start it detached and log to a file: " + "Start-Process -NoNewWindow -FilePath CMD -RedirectStandardOutput LOG -RedirectStandardError ERR " + "then read LOG later." + ) + else: + desc = ( + f"Run a bash command (bash -lc) as {user} in the workdir from config.json. Returns combined stdout+stderr and the " + "exit code; the process group is killed after timeout_s seconds (default from config.json). For a job that " + "should keep running, start it detached and log to a file: nohup CMD > LOG 2>&1 & then read LOG later." + ) return [ { "type": "function", "name": "bash", - "description": ( - f"Run a bash command (bash -lc) as {user} in the workdir from config.json. Returns combined stdout+stderr and the " - "exit code; the process group is killed after timeout_s seconds (default from config.json). For a job that " - "should keep running, start it detached and log to a file: nohup CMD > LOG 2>&1 & then read LOG later." - ), + "description": desc, "parameters": { "type": "object", "properties": { @@ -339,17 +345,14 @@ def read_json(path: Path, default: Any) -> Any: def write_json(path: Path, data: Any) -> bytes: raw = (json.dumps(data, indent=1, ensure_ascii=False) + "\n").encode("utf-8") - tmp = path.with_suffix(path.suffix + ".tmp") - tmp.write_bytes(raw) - os.replace(tmp, path) - return raw + return _osutil.atomic_write_bytes(path, raw) def src_hash(src: Path) -> str: h = hashlib.sha256() for p in sorted(src.rglob("*")): if p.is_file() and "__pycache__" not in p.parts: - h.update(str(p.relative_to(src)).encode()) + h.update(p.relative_to(src).as_posix().encode()) h.update(p.read_bytes()) return h.hexdigest() @@ -606,8 +609,10 @@ def refused_here(exc: BaseException, api_base: Any) -> bool: """A connection refused by an address on this machine (localhost, 127.x, ::1): nothing listens there.""" from urllib.parse import urlparse reason = exc.reason if isinstance(exc, urllib.error.URLError) else exc - refused = isinstance(reason, ConnectionRefusedError) or "connection refused" in str(exc).lower() \ - or "errno 61" in str(exc).lower() or "errno 111" in str(exc).lower() + text = str(exc).lower() + refused = (isinstance(reason, ConnectionRefusedError) or "connection refused" in text + or "errno 61" in text or "errno 111" in text + or "winerror 10061" in text or "actively refused" in text) host = (urlparse(str(api_base or "")).hostname or "").lower() return refused and (host in ("localhost", "::1", "0.0.0.0") or host.startswith("127.")) @@ -733,6 +738,7 @@ def __init__(self, root: Path = H) -> None: self._cancel = threading.Event() # set by cancel() from another thread; checked at every step self._cancel_lock = threading.Lock() # synchronizes cancel() with _proc / _abort registration self._proc: subprocess.Popen | None = None # the running bash command, so cancel() can kill it + self._job: int | None = None # Windows Job Object grouping _proc and its descendants self._resp: Any = None # the open model response, so cancel() can cut it self._abort: Callable[[], None] | None = None # cuts the active network socket even before headers arrive self._steer: Any = None # while a steerable call runs: sends a message into it @@ -765,7 +771,7 @@ def tools(self) -> list[dict[str, Any]]: # ---- files -------------------------------------------------------------------------------------------------- # def log(self, msg: str) -> None: line = f"{time.strftime('%H:%M:%S')} {msg}" - with open(self.log_dir / "harness.log", "a", encoding="utf-8") as f: + with open(self.log_dir / "harness.log", "a", encoding="utf-8", newline="\n") as f: f.write(line + "\n") if self.log_to_stderr: print(line, file=sys.stderr, flush=True) @@ -797,21 +803,29 @@ def cancel(self) -> None: """Stop the running turn: cut the model response, kill the running command; submit() raises Cancelled.""" with self._cancel_lock: self._cancel.set() - proc, resp, abort = self._proc, self._resp, self._abort - if proc is not None: - try: - os.killpg(proc.pid, signal.SIGKILL) - except (ProcessLookupError, PermissionError): - pass + proc, job, resp, abort = self._proc, self._job, self._resp, self._abort + if proc is not None or job is not None: + _osutil.kill_process_tree(proc, job) if abort is not None: try: abort() except Exception: # noqa: BLE001 pass elif resp is not None: - try: - resp.fp.raw._sock.shutdown(socket.SHUT_RDWR) # unblocks a read that is waiting on the network - except Exception: # noqa: BLE001 + raw_sock = getattr(getattr(getattr(resp, "fp", None), "raw", None), "_sock", None) + if raw_sock is not None: + try: + raw_sock.shutdown(socket.SHUT_RDWR) # unblocks a read that is waiting on the network + except Exception: # noqa: BLE001 + pass + if _osutil.IS_WINDOWS: + try: + # sock.close() defers while makefile() holds _io_refs; _real_close() calls closesocket(). + real_close = getattr(raw_sock, "_real_close", None) + (real_close if callable(real_close) else raw_sock.close)() + except Exception: # noqa: BLE001 + pass + else: try: resp.close() except Exception: # noqa: BLE001 @@ -884,7 +898,7 @@ def _on_stream(self, kind: str, data: dict[str, Any]) -> None: def journal(self, kind: str, **fields: Any) -> None: rec = {"ts": round(now(), 3), "turn": self.meta["turn"], "kind": kind, **fields} - with open(self.log_dir / "journal.jsonl", "a", encoding="utf-8") as f: + with open(self.log_dir / "journal.jsonl", "a", encoding="utf-8", newline="\n") as f: f.write(json.dumps(rec, ensure_ascii=False) + "\n") def load_config(self) -> None: @@ -916,7 +930,8 @@ def load_prompt(self) -> None: p.write_bytes(raw) # The prompt names the transcript by its real path, wherever this session lives, and an image in the words of # the API whose format transcript.json is in. - self.prompt = (raw.decode("utf-8").replace("{transcript_path}", str(self.h / "transcript.json")) + text = raw.decode("utf-8").replace("\r\n", "\n") + self.prompt = (text.replace("{transcript_path}", str(self.h / "transcript.json")) .replace("{image_part}", self.provider.image_part)) if self.cfg.get("progress_updates") is True: self.prompt += _progress.PROMPT @@ -1001,7 +1016,7 @@ def save_transcript(self, good: bool = True) -> None: self.meta["transcript_sha"] = self.transcript_sha # An edited transcript becomes "last good" only once the API has accepted it; a crashed turn never does. if good and not self.edited_pending: - shutil.copyfile(self.h / "transcript.json", self.state_dir / "transcript.last_good.json") + _osutil.atomic_write_bytes(self.state_dir / "transcript.last_good.json", raw) def load_transcript_if_edited(self, when: str = "before the call") -> None: """Adopt an edited transcript.json. Items appended since the file was written (this turn's model output and tool @@ -1499,51 +1514,55 @@ def tool_bash(self, args: dict[str, Any], k: int) -> str: return f"bash: timeout_s must be a number of seconds, got {json.dumps(raw_timeout)[:200]}; the command was not run" if timeout < 1 or timeout > 86400: return f"bash: timeout_s must be between 1 and 86400 seconds, got {timeout}; the command was not run" - cwd = self.cfg.get("workdir") or "/app" + cwd = self.cfg.get("workdir") or _osutil.default_workdir() Path(cwd).mkdir(parents=True, exist_ok=True) outfile = self.out_path(k) - env = _shellenv.filter_env(dict(os.environ), self.cfg.get("shell_environment_policy")) + env = _osutil.prepare_shell_env( + _shellenv.filter_env(dict(os.environ), self.cfg.get("shell_environment_policy")) + ) env["FREEHAND_SESSION"] = str(self.h) if self.pre_bash_hook: blocked = self.pre_bash_hook(cmd) if blocked: return f"bash: blocked by hook: {blocked}" t1 = now() - shell = shutil.which("bash") or shutil.which("sh") or "bash" - with open(outfile, "wb") as f: - f.write(f"$ {cmd}\n".encode()) - f.flush() - argv = [shell, "-lc", cmd] - p = subprocess.Popen(argv, cwd=cwd, stdout=f, stderr=subprocess.STDOUT, - stdin=subprocess.DEVNULL, start_new_session=True, env=env) - with self._cancel_lock: - self._proc = p - cancelled = self._cancel.is_set() - if cancelled: - try: - os.killpg(p.pid, signal.SIGKILL) - except (ProcessLookupError, PermissionError): - pass - killed = False - try: - rc = p.wait(timeout=timeout) - except KeyboardInterrupt: # the person interrupted: the command's own session never sees Ctrl-C + argv, tmp_script = _osutil.prepare_shell_command(cmd) + job = _osutil.create_process_job() + try: + with open(outfile, "wb") as f: + f.write(f"$ {cmd}\n".encode()) + f.flush() + p = subprocess.Popen(argv, cwd=cwd, stdout=f, stderr=subprocess.STDOUT, + stdin=subprocess.DEVNULL, env=env, **_osutil.popen_group_kwargs()) + _osutil.assign_process_job(job, p) + with self._cancel_lock: + self._proc = p + self._job = job + cancelled = self._cancel.is_set() + if cancelled: + _osutil.kill_process_tree(p, job) + killed = False try: - os.killpg(p.pid, signal.SIGKILL) - except ProcessLookupError: - pass - p.wait() - raise - except subprocess.TimeoutExpired: - killed = True + rc = p.wait(timeout=timeout) + except KeyboardInterrupt: # the person interrupted: the command's own session never sees Ctrl-C + _osutil.kill_process_tree(p, job) + p.wait() + raise + except subprocess.TimeoutExpired: + killed = True + _osutil.kill_process_tree(p, job) + rc = p.wait() + finally: + with self._cancel_lock: + self._proc = None + self._job = None + finally: + _osutil.close_process_job(job) + if tmp_script is not None: try: - os.killpg(p.pid, signal.SIGKILL) - except ProcessLookupError: + tmp_script.unlink() + except OSError: pass - rc = p.wait() - finally: - with self._cancel_lock: - self._proc = None self._check_cancel() # cancel() killed it: the turn ends, the output is not shown to the model dur = now() - t1 if self.post_bash_hook: @@ -1559,7 +1578,7 @@ def tool_bash(self, args: dict[str, Any], k: int) -> str: raw = f.read(2_000_000) + f"\n…[{size - 4_000_000} bytes omitted here; full output: {outfile}]…\n".encode() f.seek(size - 2_000_000) raw += f.read() - text = raw.decode("utf-8", errors="replace") + text = _osutil.normalize_output(raw.decode("utf-8", errors="replace")) prefix = f"$ {cmd}\n" text = text[len(prefix):] if text.startswith(prefix) else text self.meta["bash_calls"] += 1 @@ -1571,19 +1590,12 @@ def tool_bash(self, args: dict[str, Any], k: int) -> str: @contextlib.contextmanager def _session_lock(self) -> Iterator[None]: """Advisory lock per session directory so two processes (e.g. CLI and Web) cannot corrupt one session.""" - if fcntl is None: - yield - return - self.state_dir.mkdir(parents=True, exist_ok=True) - with open(self.state_dir / "session.lock", "a+") as f: - try: - fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) - except BlockingIOError: - raise SessionBusy(f"session {self.h.name} is already running in another Freehand process") from None - try: + lock_path = _osutil.session_lock_path(self.h) + try: + with _osutil.file_lock(lock_path, exclusive=True, blocking=False): yield - finally: - fcntl.flock(f, fcntl.LOCK_UN) + except BlockingIOError: + raise SessionBusy(f"session {self.h.name} is already running in another Freehand process") from None # ---- loop ----------------------------------------------------------------------------------------------------------- # def status_line(self) -> str: @@ -1597,7 +1609,7 @@ def status_line(self) -> str: def finish(self, status: str, summary: str) -> None: self.meta["status"] = status self.meta["finish_summary"] = summary - (self.log_dir / "result.md").write_text(f"# {status}\n\n{summary}\n", encoding="utf-8") + (self.log_dir / "result.md").write_bytes(f"# {status}\n\n{summary}\n".encode("utf-8")) self.journal("finish", status=status, summary=summary[:2000]) self.save_transcript() self.save_meta() @@ -1867,7 +1879,7 @@ def main() -> int: agent.save_meta() except Exception: # noqa: BLE001 pass - (agent.state_dir / "last_error.txt").write_text(tb, encoding="utf-8") + (agent.state_dir / "last_error.txt").write_bytes(tb.encode("utf-8")) return 1 diff --git a/src/freehand/runtime/auth.py b/src/freehand/runtime/auth.py index 8b29ce04..83293459 100644 --- a/src/freehand/runtime/auth.py +++ b/src/freehand/runtime/auth.py @@ -28,9 +28,9 @@ from typing import Any, Callable, Iterator try: - import fcntl -except ImportError: # Windows: refreshes are not serialized across processes - fcntl = None # type: ignore[assignment] + from . import osutil as _osutil +except ImportError: + import osutil as _osutil AGENT_NAME = "Freehand" DYNAMIC_CLIENT_ID = "dynamic_agent_client" @@ -121,15 +121,7 @@ def load(self) -> dict[str, Any]: return data def _write_private(self, path: Path, text: str) -> None: - self.root.mkdir(parents=True, exist_ok=True, mode=0o700) - tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp") - fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) - with os.fdopen(fd, "w", encoding="utf-8") as f: - f.write(text) - f.flush() - os.fsync(f.fileno()) - os.replace(tmp, path) - os.chmod(path, 0o600) + _osutil.atomic_write_text(path, text, private=True, fsync=True) def save(self, data: dict[str, Any]) -> None: self._write_private(self.path, json.dumps(data, indent=1) + "\n") @@ -182,15 +174,8 @@ def set_api_key(self, name: str, value: str | None) -> bool: @contextlib.contextmanager def _locked(self) -> Iterator[None]: """Serialize refreshes across processes: refresh tokens rotate, and a race invalidates one of them.""" - self.root.mkdir(parents=True, exist_ok=True, mode=0o700) - with open(self.root / "auth.lock", "a") as f: - if fcntl: - fcntl.flock(f, fcntl.LOCK_EX) - try: - yield - finally: - if fcntl: - fcntl.flock(f, fcntl.LOCK_UN) + with _osutil.file_lock(self.root / "auth.lock", exclusive=True, blocking=True): + yield def access_token(self, force_refresh: bool = False, timeout: float = 60) -> str: """A valid access token for the active account, refreshing it when it is near expiry (or when forced).""" @@ -443,10 +428,12 @@ def google_credentials_file() -> Path | None: named = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS") if named: return Path(named).expanduser() - if os.name == "nt": + if os.environ.get("CLOUDSDK_CONFIG"): + root = Path(os.environ["CLOUDSDK_CONFIG"]) + elif os.name == "nt": root = Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming") / "gcloud" else: - root = Path(os.environ.get("CLOUDSDK_CONFIG") or Path.home() / ".config" / "gcloud") + root = Path.home() / ".config" / "gcloud" found = root / "application_default_credentials.json" return found if found.is_file() else None diff --git a/src/freehand/runtime/calltrace.py b/src/freehand/runtime/calltrace.py index 550e9753..07006763 100644 --- a/src/freehand/runtime/calltrace.py +++ b/src/freehand/runtime/calltrace.py @@ -85,7 +85,7 @@ def put(self, value: Any) -> str: text = _json(value) h = _sha(text) if h not in self.seen: - with open(self.blobs, "a", encoding="utf-8") as f: + with open(self.blobs, "a", encoding="utf-8", newline="\n") as f: f.write(f'{{"h":"{h}","v":{text}}}\n') self.seen.add(h) return h @@ -125,7 +125,7 @@ def edit(self, turn: int, when: str, old: list[dict[str, Any]], new: list[dict[s "after": after}) def _write(self, rec: dict[str, Any]) -> None: - with open(self.requests, "a", encoding="utf-8") as f: + with open(self.requests, "a", encoding="utf-8", newline="\n") as f: f.write(_json(rec) + "\n") diff --git a/src/freehand/runtime/copilot.py b/src/freehand/runtime/copilot.py index 99470bfd..74002f11 100644 --- a/src/freehand/runtime/copilot.py +++ b/src/freehand/runtime/copilot.py @@ -6,7 +6,6 @@ import json import os import queue -import signal import subprocess import sys import threading @@ -15,8 +14,10 @@ try: from . import auth + from . import osutil as _osutil except ImportError: import auth + import osutil as _osutil IDLE_SECONDS = 60 INSTALL = 'Install Copilot support with Python 3.11+: uv tool install --python 3.12 "freehand-ai[copilot]".' @@ -44,15 +45,7 @@ def cached_status() -> dict[str, Any]: def remember(status: dict[str, Any]) -> None: # Only display metadata lives here. Credentials remain in the official runtime's credential store. data = {"authenticated": bool(status.get("authenticated")), "login": str(status.get("login") or "")} - path = auth.home() / "copilot-status.json" - path.parent.mkdir(parents=True, exist_ok=True) - temp = path.with_suffix(f".{os.getpid()}.{threading.get_ident()}.tmp") - try: - with temp.open("w", encoding="utf-8") as f: - json.dump(data, f) - temp.replace(path) - finally: - temp.unlink(missing_ok=True) + _osutil.atomic_write_text(auth.home() / "copilot-status.json", json.dumps(data)) def ready() -> bool: @@ -63,6 +56,7 @@ def ready() -> bool: class Bridge: def __init__(self) -> None: self.process: Any = None + self.job: int | None = None self.events: Any = queue.Queue() self.lock = threading.Lock() self.identity: Any = None @@ -87,13 +81,18 @@ def start(self) -> None: if key.startswith("COPILOT_PROVIDER") or key in ("GITHUB_COPILOT_API_TOKEN", "COPILOT_API_URL"): env.pop(key) python = env.get("FREEHAND_COPILOT_PYTHON") or sys.executable + job = _osutil.create_process_job() try: proc = subprocess.Popen([python, "-u", "-m", "freehand.copilot_bridge"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, - text=True, encoding="utf-8", env=env, start_new_session=os.name != "nt") + text=True, encoding="utf-8", env=_osutil.prepare_shell_env(env), + **_osutil.popen_group_kwargs()) except OSError: + _osutil.close_process_job(job) raise CopilotError("Could not start the Copilot SDK adapter. " + INSTALL) from None + _osutil.assign_process_job(job, proc) self.process = proc + self.job = job atexit.register(self.close) events: Any = queue.Queue() self.events = events @@ -172,17 +171,18 @@ def close(self) -> None: self.idle.cancel() atexit.unregister(self.close) proc, self.process = self.process, None + job, self.job = self.job, None if proc is None: + _osutil.close_process_job(job) return try: if proc.poll() is None: - if os.name == "nt": - proc.kill() - else: - os.killpg(proc.pid, signal.SIGKILL) + _osutil.kill_process_tree(proc, job) proc.wait(timeout=5) except (OSError, subprocess.TimeoutExpired): pass + finally: + _osutil.close_process_job(job) for pipe in (proc.stdin, proc.stdout): if pipe: pipe.close() diff --git a/src/freehand/runtime/osutil.py b/src/freehand/runtime/osutil.py new file mode 100644 index 00000000..748af556 --- /dev/null +++ b/src/freehand/runtime/osutil.py @@ -0,0 +1,444 @@ +"""Cross-platform OS primitives for the runtime: file locking, atomic writes, process trees and shell invocation. + +Standard library only, Python 3.9+ (copied into benchmark containers alongside agent.py). +""" +from __future__ import annotations + +import contextlib +import hashlib +import os +import shlex +import shutil +import signal +import subprocess +import tempfile +import threading +import time +import uuid +from pathlib import Path +from typing import Any, Iterator + +IS_WINDOWS = os.name == "nt" + +try: + import fcntl +except ImportError: + fcntl = None # type: ignore[assignment] + +if IS_WINDOWS: + import ctypes + from ctypes import wintypes + import msvcrt + + _kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + + _LOCKFILE_FAIL_IMMEDIATELY = 0x00000001 + _LOCKFILE_EXCLUSIVE_LOCK = 0x00000002 + _ERROR_LOCK_VIOLATION = 33 + _ERROR_IO_PENDING = 997 + _JOB_OBJECT_EXTENDED_LIMIT_INFORMATION = 9 + _JOB_OBJECT_LIMIT_BREAKAWAY_OK = 0x00000800 + _PROCESS_SET_QUOTA = 0x0100 + _PROCESS_TERMINATE = 0x0001 + + class _OVERLAPPED(ctypes.Structure): + _fields_ = [ + ("Internal", ctypes.c_size_t), + ("InternalHigh", ctypes.c_size_t), + ("Offset", wintypes.DWORD), + ("OffsetHigh", wintypes.DWORD), + ("hEvent", wintypes.HANDLE), + ] + + class _IO_COUNTERS(ctypes.Structure): + _fields_ = [ + ("ReadOperationCount", ctypes.c_uint64), + ("WriteOperationCount", ctypes.c_uint64), + ("OtherOperationCount", ctypes.c_uint64), + ("ReadTransferCount", ctypes.c_uint64), + ("WriteTransferCount", ctypes.c_uint64), + ("OtherTransferCount", ctypes.c_uint64), + ] + + class _JOBOBJECT_BASIC_LIMIT_INFORMATION(ctypes.Structure): + _fields_ = [ + ("PerProcessUserTimeLimit", ctypes.c_int64), + ("PerJobUserTimeLimit", ctypes.c_int64), + ("LimitFlags", wintypes.DWORD), + ("MinimumWorkingSetSize", ctypes.c_size_t), + ("MaximumWorkingSetSize", ctypes.c_size_t), + ("ActiveProcessLimit", wintypes.DWORD), + ("Affinity", ctypes.c_size_t), + ("PriorityClass", wintypes.DWORD), + ("SchedulingClass", wintypes.DWORD), + ] + + class _JOBOBJECT_EXTENDED_LIMIT_INFORMATION(ctypes.Structure): + _fields_ = [ + ("BasicLimitInformation", _JOBOBJECT_BASIC_LIMIT_INFORMATION), + ("IoInfo", _IO_COUNTERS), + ("ProcessMemoryLimit", ctypes.c_size_t), + ("JobMemoryLimit", ctypes.c_size_t), + ("PeakProcessMemoryUsed", ctypes.c_size_t), + ("PeakJobMemoryUsed", ctypes.c_size_t), + ] + + _kernel32.LockFileEx.argtypes = [ + wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD, wintypes.DWORD, wintypes.DWORD, ctypes.POINTER(_OVERLAPPED) + ] + _kernel32.LockFileEx.restype = wintypes.BOOL + _kernel32.UnlockFileEx.argtypes = [ + wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD, wintypes.DWORD, ctypes.POINTER(_OVERLAPPED) + ] + _kernel32.UnlockFileEx.restype = wintypes.BOOL + _kernel32.CreateJobObjectW.argtypes = [wintypes.LPVOID, wintypes.LPCWSTR] + _kernel32.CreateJobObjectW.restype = wintypes.HANDLE + _kernel32.SetInformationJobObject.argtypes = [wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD] + _kernel32.SetInformationJobObject.restype = wintypes.BOOL + _kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD] + _kernel32.OpenProcess.restype = wintypes.HANDLE + _kernel32.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE] + _kernel32.AssignProcessToJobObject.restype = wintypes.BOOL + _kernel32.TerminateJobObject.argtypes = [wintypes.HANDLE, wintypes.UINT] + _kernel32.TerminateJobObject.restype = wintypes.BOOL + _kernel32.CloseHandle.argtypes = [wintypes.HANDLE] + _kernel32.CloseHandle.restype = wintypes.BOOL + _kernel32.GetStdHandle.argtypes = [wintypes.DWORD] + _kernel32.GetStdHandle.restype = wintypes.HANDLE + _kernel32.GetConsoleMode.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)] + _kernel32.GetConsoleMode.restype = wintypes.BOOL + _kernel32.SetConsoleMode.argtypes = [wintypes.HANDLE, wintypes.DWORD] + _kernel32.SetConsoleMode.restype = wintypes.BOOL + _STD_OUTPUT_HANDLE = 0xFFFFFFF5 + _STD_ERROR_HANDLE = 0xFFFFFFF4 + _ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004 + + +def enable_windows_console() -> None: + """Enable UTF-8 stdio and ANSI/VT escape processing on Windows consoles (no-op on POSIX or redirected streams).""" + if not IS_WINDOWS: + return + import sys + for stream in (sys.stdout, sys.stderr): + if hasattr(stream, "reconfigure"): + try: + stream.reconfigure(encoding="utf-8", errors="replace") + except (OSError, ValueError): + pass + for std_id in (_STD_OUTPUT_HANDLE, _STD_ERROR_HANDLE): + handle = _kernel32.GetStdHandle(std_id) + if not handle or handle == wintypes.HANDLE(-1).value: + continue + mode = wintypes.DWORD() + if _kernel32.GetConsoleMode(handle, ctypes.byref(mode)): + _kernel32.SetConsoleMode(handle, mode.value | _ENABLE_VIRTUAL_TERMINAL_PROCESSING) + + +# ---- paths -------------------------------------------------------------------------------------------------------- # +def norm_path_key(path: Path | str) -> str: + """Canonical path string for equality and dict keys (case-normalized on Windows).""" + resolved = str(Path(path).resolve()) + return os.path.normcase(resolved) if IS_WINDOWS else resolved + + +def same_path(a: Path | str, b: Path | str) -> bool: + return norm_path_key(a) == norm_path_key(b) + + +def is_root_dir(path: Path) -> bool: + """True for filesystem roots: '/' on POSIX, 'C:\\' or UNC share roots on Windows.""" + resolved = path.resolve() + return resolved.parent == resolved + + +def default_workdir() -> str: + return os.getcwd() if IS_WINDOWS else "/app" + + +def session_lock_path(session_dir: Path, home_dir: Path | None = None) -> Path: + """Where a session's advisory lock lives. On Windows it sits outside *session_dir* so trashing the folder can + hold the lock across shutil.move without WinError 32.""" + if not IS_WINDOWS: + return session_dir / ".state" / "session.lock" + root = home_dir or Path(os.environ.get("FREEHAND_HOME") or (Path.home() / ".freehand")) + key = hashlib.sha256(norm_path_key(session_dir).encode("utf-8")).hexdigest()[:20] + return root / "locks" / f"session-{key}.lock" + + +# ---- file locking ------------------------------------------------------------------------------------------------- # +def _lock_handle(fd: int, *, exclusive: bool, blocking: bool) -> None: + if IS_WINDOWS: + handle = msvcrt.get_osfhandle(fd) + flags = (_LOCKFILE_EXCLUSIVE_LOCK if exclusive else 0) | (0 if blocking else _LOCKFILE_FAIL_IMMEDIATELY) + ov = _OVERLAPPED() + if not _kernel32.LockFileEx(handle, flags, 0, 1, 0, ctypes.byref(ov)): + err = ctypes.get_last_error() + if not blocking and err in (_ERROR_LOCK_VIOLATION, _ERROR_IO_PENDING): + raise BlockingIOError(err, "lock is held by another process") + raise ctypes.WinError(err) + return + if fcntl is not None: + flags = (fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH) | (0 if blocking else fcntl.LOCK_NB) + fcntl.flock(fd, flags) + + +def _unlock_handle(fd: int) -> None: + if IS_WINDOWS: + handle = msvcrt.get_osfhandle(fd) + ov = _OVERLAPPED() + _kernel32.UnlockFileEx(handle, 0, 1, 0, ctypes.byref(ov)) + return + if fcntl is not None: + fcntl.flock(fd, fcntl.LOCK_UN) + + +@contextlib.contextmanager +def file_lock(path: Path, *, exclusive: bool = True, blocking: bool = True, dir_mode: int = 0o700) -> Iterator[None]: + """Cross-process advisory file lock (flock on POSIX, LockFileEx on Windows). Raises BlockingIOError when + *blocking* is False and the lock is held.""" + path.parent.mkdir(parents=True, exist_ok=True, mode=dir_mode) + with open(path, "a+") as f: + _lock_handle(f.fileno(), exclusive=exclusive, blocking=blocking) + try: + yield + finally: + try: + _unlock_handle(f.fileno()) + except OSError: + pass + + +def is_file_locked(path: Path) -> bool: + """True when another handle currently holds an exclusive lock on *path*.""" + try: + fd = os.open(path, os.O_RDONLY) + except OSError: + return False + try: + try: + _lock_handle(fd, exclusive=False, blocking=False) + except BlockingIOError: + return True + except OSError: + return False + try: + _unlock_handle(fd) + except OSError: + pass + return False + finally: + os.close(fd) + + +# ---- atomic file replacement -------------------------------------------------------------------------------------- # +def replace_file(src: Path, dst: Path) -> None: + """Atomically replace *dst* with *src*, retrying briefly on Windows sharing violations.""" + if not IS_WINDOWS: + os.replace(src, dst) + return + for attempt in range(20): + try: + os.replace(src, dst) + return + except PermissionError as exc: + if getattr(exc, "winerror", None) not in (5, 32) or attempt == 19: + raise + time.sleep(0.01 * (attempt + 1)) + + +def atomic_write_bytes(path: Path, data: bytes, *, private: bool = False, fsync: bool = False) -> bytes: + """Write *data* to *path* through a unique sibling temporary file.""" + path.parent.mkdir(parents=True, exist_ok=True, mode=0o700 if private else 0o777) + tmp = path.with_name(f".{path.name}.{os.getpid()}.{threading.get_ident()}.{uuid.uuid4().hex[:6]}.tmp") + try: + if private: + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "wb") as f: + f.write(data) + f.flush() + if fsync: + os.fsync(f.fileno()) + else: + with open(tmp, "wb") as f: + f.write(data) + f.flush() + if fsync: + os.fsync(f.fileno()) + replace_file(tmp, path) + if private and not IS_WINDOWS: + os.chmod(path, 0o600) + except BaseException: + try: + tmp.unlink() + except OSError: + pass + raise + return data + + +def atomic_write_text(path: Path, text: str, *, private: bool = False, fsync: bool = False) -> bytes: + return atomic_write_bytes(path, text.encode("utf-8"), private=private, fsync=fsync) + + +# ---- process groups & trees --------------------------------------------------------------------------------------- # +def popen_group_kwargs(*, hide_window: bool = True) -> dict[str, Any]: + """Popen kwargs placing a child in its own process group so Ctrl-C and tree termination are isolated.""" + if not IS_WINDOWS: + return {"start_new_session": True} + flags = subprocess.CREATE_NEW_PROCESS_GROUP + if hide_window: + flags |= subprocess.CREATE_NO_WINDOW + return {"creationflags": flags} + + +def detached_popen_kwargs() -> dict[str, Any]: + """Popen kwargs for a background daemon that outlives its parent without flashing a Windows console.""" + if not IS_WINDOWS: + return {"start_new_session": True} + flags = subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.DETACHED_PROCESS | subprocess.CREATE_NO_WINDOW + return {"creationflags": flags} + + +def create_process_job() -> int | None: + """Create a Win32 Job Object for grouping a command and its descendants without killing detached children on + normal exit (TerminateJobObject is called explicitly only on timeout/cancel).""" + if not IS_WINDOWS: + return None + job = _kernel32.CreateJobObjectW(None, None) + if not job: + return None + info = _JOBOBJECT_EXTENDED_LIMIT_INFORMATION() + info.BasicLimitInformation.LimitFlags = _JOB_OBJECT_LIMIT_BREAKAWAY_OK + if not _kernel32.SetInformationJobObject( + job, _JOB_OBJECT_EXTENDED_LIMIT_INFORMATION, ctypes.byref(info), ctypes.sizeof(info) + ): + _kernel32.CloseHandle(job) + return None + return int(job) + + +def assign_process_job(job: int | None, proc: subprocess.Popen[Any]) -> bool: + if not IS_WINDOWS or not job: + return False + handle = _kernel32.OpenProcess(_PROCESS_SET_QUOTA | _PROCESS_TERMINATE, False, proc.pid) + if not handle: + return False + try: + return bool(_kernel32.AssignProcessToJobObject(job, handle)) + finally: + _kernel32.CloseHandle(handle) + + +def close_process_job(job: int | None) -> None: + if IS_WINDOWS and job: + _kernel32.CloseHandle(job) + + +def kill_process_tree(proc: subprocess.Popen[Any] | None, job: int | None = None, *, graceful: bool = False) -> None: + """Terminate *proc* and every descendant process (process group on POSIX, Job Object / taskkill on Windows).""" + if not IS_WINDOWS: + if proc is None: + return + sig = signal.SIGTERM if graceful else signal.SIGKILL + try: + os.killpg(proc.pid, sig) + except (ProcessLookupError, PermissionError, OSError): + try: + proc.terminate() if graceful else proc.kill() + except OSError: + pass + return + if job: + try: + if _kernel32.TerminateJobObject(job, 1): + return + except OSError: + pass + if proc is None: + return + # Fallback when the process could not join a Job Object (or has no job handle): terminate its whole tree. + try: + subprocess.run( + ["taskkill", "/F", "/T", "/PID", str(proc.pid)], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + timeout=5, creationflags=subprocess.CREATE_NO_WINDOW, + ) + except (OSError, subprocess.SubprocessError): + pass + try: + proc.kill() + except OSError: + pass + + +# ---- shells & executables ----------------------------------------------------------------------------------------- # +def resolve_executable(program: str) -> str: + """Resolve *program* on PATH (needed on Windows where CreateProcess does not auto-append .cmd/.bat).""" + if not IS_WINDOWS: + return program + return shutil.which(program) or program + + +def find_shell() -> str: + """The shell Freehand runs commands in: bash/sh on POSIX, PowerShell (pwsh preferred) on Windows.""" + if not IS_WINDOWS: + return shutil.which("bash") or shutil.which("sh") or "bash" + for candidate in ("pwsh", "powershell.exe", "powershell"): + found = shutil.which(candidate) + if found: + return found + sysroot = os.environ.get("SystemRoot", r"C:\Windows") + return str(Path(sysroot) / "System32" / "WindowsPowerShell" / "v1.0" / "powershell.exe") + + +def shell_name() -> str: + if not IS_WINDOWS: + return Path(os.environ.get("SHELL") or "sh").name + return Path(find_shell()).stem + + +_PS_PREFIX = ( + "[Console]::InputEncoding = [Console]::OutputEncoding = $OutputEncoding = " + "[System.Text.UTF8Encoding]::new($false)\n" + "$global:LASTEXITCODE = 0\n" +) +_PS_SUFFIX = "\n$_fh_ok = $?\nif (-not $_fh_ok) { exit $(if ($LASTEXITCODE) { $LASTEXITCODE } else { 1 }) }\n" + + +def prepare_shell_command(cmd: str) -> tuple[list[str], Path | None]: + """Return (argv, optional_temp_script) for executing *cmd* in the platform's shell.""" + shell = find_shell() + if not IS_WINDOWS: + return [shell, "-lc", cmd], None + script = _PS_PREFIX + cmd + _PS_SUFFIX + # Windows CreateProcess caps the command line at 32,767 chars; fall back to a temporary script for long commands. + if len(script) > 20000: + fd, name = tempfile.mkstemp(prefix="freehand-cmd-", suffix=".ps1") + with os.fdopen(fd, "wb") as f: + f.write(script.encode("utf-8")) + argv = [shell, "-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", name] + return argv, Path(name) + return [shell, "-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], None + + +def quote_shell_arg(value: str) -> str: + if not IS_WINDOWS: + return shlex.quote(value) + return "'" + value.replace("'", "''") + "'" + + +def prepare_shell_env(env: dict[str, str]) -> dict[str, str]: + """Ensure child processes emit UTF-8 on Windows without overriding explicit caller settings.""" + if not IS_WINDOWS: + return env + out = dict(env) + upper = {k.upper() for k in out} + if "PYTHONUTF8" not in upper: + out["PYTHONUTF8"] = "1" + if "PYTHONIOENCODING" not in upper: + out["PYTHONIOENCODING"] = "utf-8" + return out + + +def normalize_output(text: str) -> str: + return text.replace("\r\n", "\n") if IS_WINDOWS else text diff --git a/src/freehand/runtime/providers.py b/src/freehand/runtime/providers.py index d96bc73c..273f3563 100644 --- a/src/freehand/runtime/providers.py +++ b/src/freehand/runtime/providers.py @@ -41,9 +41,11 @@ try: # imported as freehand.runtime.providers from . import auth as _auth + from . import osutil as _osutil from .calltrace import mark_cache_points except ImportError: # run as a script (container mode) import auth as _auth # noqa: E402 + import osutil as _osutil # noqa: E402 from calltrace import mark_cache_points # noqa: E402 COPILOT = "copilot" @@ -493,9 +495,21 @@ def _abort_socket(sock: Any) -> None: """Wake a thread blocked in connect/handshake/recv without waiting for a socket timeout.""" if sock is None: return + closed = False try: sock.shutdown(socket.SHUT_RDWR) except OSError: + closed = True + # On Windows, shutdown() does not wake a blocking recv(), and sock.close() defers while makefile() holds _io_refs. + if _osutil.IS_WINDOWS: + real_close = getattr(sock, "_real_close", None) + if callable(real_close): + try: + real_close() + return + except OSError: + pass + if closed or _osutil.IS_WINDOWS: try: sock.close() except OSError: @@ -1384,7 +1398,7 @@ def params(self, agent: Any) -> dict[str, Any]: model = cfg["model"] old = claude_name(model).startswith(NO_ADAPTIVE_THINKING) max_tokens = int(cfg.get("max_output_tokens") or (64000 if old else MAX_TOKENS)) - messages = self.materialize_images(self.sendable(agent.items), cfg.get("workdir") or "/app") + messages = self.materialize_images(self.sendable(agent.items), cfg.get("workdir") or _osutil.default_workdir()) system = takes_system(model) # A system message must precede an assistant message or end the list. One that does not (the person's next # message, or an item the model appended to its transcript, follows it), and every one on a model that takes diff --git a/src/freehand/runtime/shellenv.py b/src/freehand/runtime/shellenv.py index c68382fb..c9150c7c 100644 --- a/src/freehand/runtime/shellenv.py +++ b/src/freehand/runtime/shellenv.py @@ -6,10 +6,16 @@ from __future__ import annotations import fnmatch +import os from typing import Any CORE_ENV = {"HOME", "LANG", "LC_ALL", "LC_CTYPE", "LOGNAME", "PATH", "SHELL", "TERM", "TMPDIR", "USER", "TZ", "FREEHAND_HOME", "FREEHAND_SESSION"} +WINDOWS_CORE_ENV = CORE_ENV | { + "APPDATA", "COMPUTERNAME", "COMSPEC", "HOMEDRIVE", "HOMEPATH", "LOCALAPPDATA", "NUMBER_OF_PROCESSORS", + "OS", "PATHEXT", "PROCESSOR_ARCHITECTURE", "PROGRAMDATA", "PROGRAMFILES", "PROGRAMFILES(X86)", + "PSMODULEPATH", "SYSTEMDRIVE", "SYSTEMROOT", "TEMP", "TMP", "USERDOMAIN", "USERNAME", "USERPROFILE", "WINDIR", +} DEFAULT_ENV_EXCLUDES = ("*KEY*", "*SECRET*", "*TOKEN*") @@ -25,7 +31,10 @@ def filter_env(env: dict[str, str], env_policy: dict[str, Any] | None = None) -> if inherit == "none": out: dict[str, str] = {} elif inherit == "core": - out = {k: v for k, v in env.items() if k in CORE_ENV} + if os.name == "nt": + out = {k: v for k, v in env.items() if k.upper() in WINDOWS_CORE_ENV} + else: + out = {k: v for k, v in env.items() if k in CORE_ENV} else: out = dict(env) ignore_defaults = env_policy.get("ignore_default_excludes", True) @@ -39,5 +48,9 @@ def filter_env(env: dict[str, str], env_policy: dict[str, Any] | None = None) -> out = {k: v for k, v in out.items() if any(fnmatch.fnmatchcase(k.upper(), p) for p in only)} for k, v in (env_policy.get("set") or {}).items(): if isinstance(k, str) and v is not None: + if os.name == "nt": + # Avoid case-duplicate keys (e.g. Path and PATH) in the Windows environment block. + for existing in [e for e in out if e.upper() == k.upper() and e != k]: + del out[existing] out[k] = str(v) return out diff --git a/src/freehand/server.py b/src/freehand/server.py index 6b29af54..31d02040 100644 --- a/src/freehand/server.py +++ b/src/freehand/server.py @@ -37,7 +37,7 @@ from freehand import __version__, connections, export, mcp, modelicons, session, ui, usercommands, workbench from freehand.control import IMAGES_MAX, ControlError, Controller, history from freehand.html_preview import HTML_FILES, HTMLPreviews -from freehand.runtime import auth, providers +from freehand.runtime import auth, osutil, providers from freehand.runtime.agent import plan_signs WEB = Path(__file__).resolve().parent / "web" @@ -209,11 +209,12 @@ def linked_file_action(path: Path, action: str, *, browser_url: str = "", editor if action == "editor": apps = {"code": "Visual Studio Code", "cursor": "Cursor", "windsurf": "Windsurf", "zed": "Zed"} # GUI installations on macOS need not install the optional shell command. - args = ["/usr/bin/open", "-a", apps[editor], str(path)] if sys.platform == "darwin" else [editor, str(path)] + args = (["/usr/bin/open", "-a", apps[editor], str(path)] if sys.platform == "darwin" + else [osutil.resolve_executable(editor) if sys.platform == "win32" else editor, str(path)]) elif sys.platform == "darwin": args = ["/usr/bin/open", *({"reveal": ["-R"], "preview": ["-a", "Preview"]}.get(action, [])), target] elif sys.platform == "win32": - args = ["explorer.exe", "/select,", str(path)] + args = ["explorer.exe", f"/select,{path}"] else: args = ["xdg-open", str(path.parent) if action == "reveal" else target] try: @@ -223,7 +224,8 @@ def linked_file_action(path: Path, action: str, *, browser_url: str = "", editor # Paths are absolute, separate argv entries: spaces, quotes and shell syntax are just filename characters. result = subprocess.run(args, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10) - if result.returncode: + # explorer.exe /select, exits 1 even on success. + if result.returncode and not (sys.platform == "win32" and action == "reveal" and result.returncode == 1): raise ApiError(409, "The system could not open this file. Check that a suitable application is installed.") except (OSError, subprocess.TimeoutExpired): raise ApiError(409, "The system could not open this file. Use Download or Copy path instead.") from None @@ -276,7 +278,7 @@ def controller(self, sid: str) -> Controller: with self.lock: if sid not in self.controllers: d = session.sessions_dir() / sid - if "/" in sid or sid in (".", "..") or not (d / "session.json").is_file(): + if "/" in sid or "\\" in sid or sid in (".", "..") or not (d / "session.json").is_file(): raise ApiError(404, "No such session.") self.controllers[sid] = Controller(d, Path(session.info(d).get("cwd") or self.cwd)) return self.controllers[sid] @@ -635,7 +637,8 @@ def remove(self, sid: str) -> None: for terminal in owned: self.workbench.terminals.pop(terminal.id, None) c.emit({"type": "deleted"}) # a page open on it elsewhere moves on, and says why - c.closed = True + with c.lock: + c.closed = True c.suggestions.cancel() with self.lock: self.controllers.pop(sid, None) @@ -661,7 +664,7 @@ def files(self, cwd: Path, q: str) -> list[str]: names = [] for root, dirs, found in os.walk(cwd): dirs[:] = [d for d in dirs if not d.startswith(".") and d not in ("node_modules", "__pycache__")] - names += [os.path.relpath(os.path.join(root, f), cwd) for f in found] + names += [os.path.relpath(os.path.join(root, f), cwd).replace(os.sep, "/") for f in found] if len(names) > FILES_MAX: break q = q.lower() @@ -835,7 +838,7 @@ def do_GET(self) -> None: self.json(exc.payload, exc.status) except (ControlError, session.SettingsError) as exc: self.json({"error": str(exc), "code": "refused", "detail": getattr(exc, "detail", "")}, 409) - except (BrokenPipeError, ConnectionResetError): + except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError): pass except Exception as exc: # noqa: BLE001 self.json(unexpected(exc), 500) @@ -1060,6 +1063,8 @@ def do_POST(self) -> None: self.json({"error": str(exc), "code": exc.code}, exc.status) except (ControlError, session.SettingsError) as exc: self.json({"error": str(exc), "code": "refused", "detail": getattr(exc, "detail", "")}, 409) + except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError): + pass except Exception as exc: # noqa: BLE001 self.json(unexpected(exc), 500) diff --git a/src/freehand/session.py b/src/freehand/session.py index fc0cb96e..9368d73c 100644 --- a/src/freehand/session.py +++ b/src/freehand/session.py @@ -16,13 +16,8 @@ from pathlib import Path from typing import Any, Iterator -try: - import fcntl -except ImportError: - fcntl = None # type: ignore[assignment] - from freehand import modelmetadata -from freehand.runtime import auth, providers +from freehand.runtime import auth, osutil, providers from freehand.runtime.agent import DEFAULT_CONFIG, base_model PROMPT = Path(__file__).resolve().parent / "prompt.md" @@ -217,23 +212,12 @@ def gateway_route(model: str, gw: dict[str, Any]) -> dict[str, Any]: @contextlib.contextmanager def _settings_lock() -> Iterator[None]: """Serialize config.json / models.json read-modify-write across concurrent CLI and Web processes.""" - home = auth.home() - home.mkdir(parents=True, exist_ok=True) - with open(home / "config.lock", "a+") as f: - if fcntl: - fcntl.flock(f, fcntl.LOCK_EX) - try: - yield - finally: - if fcntl: - fcntl.flock(f, fcntl.LOCK_UN) + with osutil.file_lock(auth.home() / "config.lock", exclusive=True, blocking=True, dir_mode=0o777): + yield def _atomic_write_json(path: Path, data: Any) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - tmp = path.with_name(f".{path.name}.{os.getpid()}.{uuid.uuid4().hex[:6]}.tmp") - tmp.write_text(json.dumps(data, indent=1, ensure_ascii=False) + "\n", encoding="utf-8") - os.replace(tmp, path) + osutil.atomic_write_text(path, json.dumps(data, indent=1, ensure_ascii=False) + "\n") def write_settings(data: dict[str, Any]) -> None: @@ -578,9 +562,9 @@ def create(cwd: Path | None, *, interactive: bool, overrides: dict[str, Any] | N # Outside the session: trashing its conversation must not remove files a branch still works on. cwd = (auth.home() / "workspaces" / sid).resolve() cwd.mkdir(parents=True) - prompt = PROMPT.read_text(encoding="utf-8") + prompt = PROMPT.read_text(encoding="utf-8").replace("\r\n", "\n") prompt += DISPLAY_NOTE if web else "" - (d / "prompt.md").write_text(prompt + (INTERACTIVE_NOTE if interactive else ""), encoding="utf-8") + (d / "prompt.md").write_bytes((prompt + (INTERACTIVE_NOTE if interactive else "")).encode("utf-8")) config = new_config(cwd, interactive=interactive, overrides=overrides) # Decided once, when the session starts: a folder the person has not said they trust keeps its AGENTS.md and # project skills out of the context, wherever the session was started from. @@ -589,13 +573,13 @@ def create(cwd: Path | None, *, interactive: bool, overrides: dict[str, Any] | N config.setdefault("project_instructions", trust(trusted_in) is True if project else False) if not project: config.update(workdir=str(cwd), project_instructions=False) - (d / "config.json").write_text(json.dumps(config, indent=1) + "\n", encoding="utf-8") + (d / "config.json").write_bytes((json.dumps(config, indent=1) + "\n").encode("utf-8")) info = {"id": sid, "cwd": str(cwd), "project": str(cwd) if project else None, "created": time.strftime("%Y-%m-%dT%H:%M:%S%z"), "interactive": interactive} if worktree and project: info.update(project=str(worktree["project"]), worktree={k: str(worktree.get(k) or "") for k in ("branch", "base")}) - (d / "session.json").write_text(json.dumps(info, indent=1) + "\n", encoding="utf-8") + (d / "session.json").write_bytes((json.dumps(info, indent=1) + "\n").encode("utf-8")) return d @@ -745,17 +729,15 @@ def fork(d: Path, items: list[dict[str, Any]] | None = None, messages: list[dict def trash(d: Path) -> Path: """Take a session out of every list by moving it to trash/ under Freehand's home (as the web's delete does): not deleted, so a mistake can be undone by moving it back. Refused while a turn runs in it elsewhere.""" - import fcntl # Taken even when no turn has made the lock file yet (a branch that never ran), and held until the folder has # moved: a turn starting meanwhile in another Freehand is refused instead of writing into it. - (d / ".state").mkdir(exist_ok=True) - with open(d / ".state" / "session.lock", "a+") as f: - try: - fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) - except BlockingIOError: - raise RuntimeError("the model is working in that session in another Freehand; stop it there " - "first") from None - return _move_to_trash(d) + lock_path = osutil.session_lock_path(d) + try: + with osutil.file_lock(lock_path, exclusive=True, blocking=False, dir_mode=0o777): + return _move_to_trash(d) + except BlockingIOError: + raise RuntimeError("the model is working in that session in another Freehand; stop it there " + "first") from None def _move_to_trash(d: Path) -> Path: @@ -818,6 +800,9 @@ def auto_title(d: Path) -> str | None: _, calls, reply = agent.provider.digest(agent.call_model(), False) except Exception: # noqa: BLE001 -- a name is a nicety: any failure leaves the session as it was return None + finally: + if hasattr(agent.provider, "close"): + agent.provider.close() title = clean_title(reply) if not title or calls or json.loads((d / "session.json").read_text(encoding="utf-8")).get("title"): return None # named by the person meanwhile: theirs stays @@ -922,7 +907,9 @@ def for_cwd(cwd: Path, interactive_only: bool = True) -> list[dict[str, Any]]: if not root.is_dir(): return [] found = [info(d) for d in root.iterdir() if d.is_dir()] - return sorted((s for s in found if s.get("cwd") == str(cwd) and (s.get("turns") or s.get("has_messages")) + want = osutil.norm_path_key(cwd) + return sorted((s for s in found if s.get("cwd") and osutil.norm_path_key(s["cwd"]) == want + and (s.get("turns") or s.get("has_messages")) and (s.get("interactive") or not interactive_only)), key=lambda s: s["asked"], reverse=True) @@ -935,10 +922,10 @@ def for_cwd(cwd: Path, interactive_only: bool = True) -> list[dict[str, Any]]: def git_root(cwd: Path) -> Path | None: try: out = subprocess.run([*GIT, "rev-parse", "--show-toplevel"], cwd=cwd, capture_output=True, text=True, - timeout=5) + encoding="utf-8", errors="replace", timeout=5) except (OSError, subprocess.SubprocessError): return None - return Path(out.stdout.strip()) if out.returncode == 0 and out.stdout.strip() else None + return Path(out.stdout.strip()).resolve() if out.returncode == 0 and out.stdout.strip() else None def project_key(cwd: Path) -> str: @@ -949,7 +936,11 @@ def project_key(cwd: Path) -> str: def trust(cwd: Path) -> bool | None: """True or False once the person has said whether they trust this folder (`projects` in config.json), else None.""" projects = load_settings().get("projects") - level = projects.get(project_key(cwd)) if isinstance(projects, dict) else None + key = project_key(cwd) + level = projects.get(key) if isinstance(projects, dict) else None + if level is None and osutil.IS_WINDOWS and isinstance(projects, dict): + norm = os.path.normcase(key) + level = next((v for k, v in projects.items() if isinstance(k, str) and os.path.normcase(k) == norm), None) # a value edited by hand into something else is asked about again, rather than stopping every session return {"trusted": True, "untrusted": False}.get(level) if isinstance(level, str) else None @@ -980,8 +971,10 @@ def project_files(cwd: Path) -> list[Path]: def environment(cwd: Path) -> str: system = platform.system() os_name = f"macOS {platform.mac_ver()[0]}" if system == "Darwin" else f"{system} {platform.release()}" - shell = Path(os.environ.get("SHELL") or "sh").name - lines = [f"cwd: {cwd}", f"os: {os_name} ({platform.machine()})", f"shell: {shell} (commands run in bash -lc)", + shell = osutil.shell_name() + shell_line = (f"shell: {shell} (commands run in PowerShell)" if osutil.IS_WINDOWS + else f"shell: {shell} (commands run in bash -lc)") + lines = [f"cwd: {cwd}", f"os: {os_name} ({platform.machine()})", shell_line, f"date: {time.strftime('%Y-%m-%d')}"] root = git_root(cwd) if root: @@ -1071,10 +1064,15 @@ def context_block(cwd: Path, max_chars: int = 40000, project: bool = True) -> st def own_command() -> str: """How a command the model runs reaches this Freehand: `freehand` when that name on PATH is this installation, else this interpreter (a source checkout, or a PATH without the installation's directory).""" - import shlex import shutil import sys found = shutil.which("freehand") - if found and Path(found).resolve().parent == Path(sys.executable).parent: - return "freehand" - return f"{shlex.quote(sys.executable)} -m freehand" + exe_dir = Path(sys.executable).resolve().parent + if found: + found_dir = Path(found).resolve().parent + if osutil.same_path(found_dir, exe_dir) or ( + osutil.IS_WINDOWS and osutil.same_path(found_dir, exe_dir / "Scripts") + ): + return "freehand" + quoted = osutil.quote_shell_arg(sys.executable) + return f"& {quoted} -m freehand" if osutil.IS_WINDOWS else f"{quoted} -m freehand" diff --git a/src/freehand/snapshots.py b/src/freehand/snapshots.py index 5acbb0ba..20d21baf 100644 --- a/src/freehand/snapshots.py +++ b/src/freehand/snapshots.py @@ -21,6 +21,8 @@ from pathlib import Path from typing import Any +from freehand.runtime import osutil + TIMEOUT_S = 30 # Left out of snapshots: a file larger than this (data, media, archives: rarely what a turn edits, and copying them # into every session cost seconds before the first model call and hundreds of megabytes per session), and what @@ -58,7 +60,8 @@ def __init__(self, session_dir: Path, workdir: Path) -> None: self.lock = threading.RLock() # a diff asked for from another thread while a turn checkpoints self._held = 0 # how deep this process is inside the file lock home = Path.home().resolve() - if workdir.resolve() in (home, Path("/")): + resolved = workdir.resolve() + if resolved == home or osutil.is_root_dir(resolved): self.disabled = f"undo is off when working directly in {workdir}" @contextlib.contextmanager @@ -73,13 +76,7 @@ def _locked(self) -> Any: finally: self._held -= 1 return - self.git_dir.mkdir(parents=True, exist_ok=True) - with open(self.git_dir / "freehand.lock", "a+") as f: - try: - import fcntl - fcntl.flock(f, fcntl.LOCK_EX) - except (ImportError, OSError): # pragma: no cover (no flock: the thread lock still holds) - pass + with osutil.file_lock(self.git_dir / "freehand.lock", exclusive=True, blocking=True, dir_mode=0o777): self._held = 1 try: yield @@ -116,8 +113,24 @@ def _commit(self, message: str) -> str: if not (self.git_dir / "HEAD").exists(): self._git("init", "-q") (self.git_dir / "info").mkdir(exist_ok=True) + excludes = list(ALWAYS_LEFT_OUT) + # Never snapshot our own git_dir or FREEHAND_HOME if a user/test works in an ancestor folder. + roots = [self.git_dir] + try: + from freehand.runtime.auth import home + roots.append(home()) + except ImportError: + pass + work_resolved = self.workdir.resolve() + for candidate in roots: + try: + rel = candidate.resolve().relative_to(work_resolved).as_posix().rstrip("/") + if rel and rel != ".": + excludes.append(f"/{rel}/") + except ValueError: + pass with open(self.git_dir / "info" / "exclude", "a", encoding="utf-8") as f: - f.write("\n".join(ALWAYS_LEFT_OUT) + "\n") + f.write("\n".join(excludes) + "\n") (self.git_dir / "workdir").write_text(str(self.workdir.resolve()) + "\n", encoding="utf-8") self._borrow_objects() # A nested repository with no commit yet cannot be a gitlink, and `add -A` fails on it (which turned undo @@ -132,14 +145,14 @@ def _borrow_objects(self) -> None: env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} try: out = subprocess.run([*GIT, "rev-parse", "--git-common-dir"], cwd=self.workdir, capture_output=True, - text=True, timeout=TIMEOUT_S, env=env) + text=True, encoding="utf-8", errors="replace", timeout=TIMEOUT_S, env=env) except (OSError, subprocess.SubprocessError): return common = out.stdout.strip() if out.returncode == 0 else "" objects = (self.workdir / common).resolve() / "objects" if common else None if objects and objects.is_dir() and objects.resolve() != (self.git_dir / "objects").resolve(): (self.git_dir / "objects" / "info").mkdir(parents=True, exist_ok=True) - (self.git_dir / "objects" / "info" / "alternates").write_text(str(objects) + "\n", encoding="utf-8") + (self.git_dir / "objects" / "info" / "alternates").write_bytes((objects.as_posix() + "\n").encode("utf-8")) def _has_commit(self, path: str) -> bool: env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} @@ -374,24 +387,27 @@ def _restore(self, commit: str, changes: list[tuple[str, str]] | None = None) -> changes = self.changes_since(commit) self._check_restore(changes) to_checkout: list[str] = [] - for status, path in changes: - target = self.workdir / path - if status == "A": - try: + try: + for status, path in changes: + target = self.workdir / path + if status == "A": + try: + if target.is_dir() and not target.is_symlink(): + shutil.rmtree(target) + else: + target.unlink() + except FileNotFoundError: + pass + parent = target.parent + while parent != self.workdir and parent.is_dir() and not any(parent.iterdir()): + parent.rmdir() + parent = parent.parent + else: if target.is_dir() and not target.is_symlink(): shutil.rmtree(target) - else: - target.unlink() - except FileNotFoundError: - pass - parent = target.parent - while parent != self.workdir and parent.is_dir() and not any(parent.iterdir()): - parent.rmdir() - parent = parent.parent - else: - if target.is_dir() and not target.is_symlink(): - shutil.rmtree(target) - to_checkout.append(path) + to_checkout.append(path) + except OSError as exc: + raise SnapshotError(f"Cannot restore {path}: {exc}") from None for i in range(0, len(to_checkout), 200): self._git("checkout", commit, "--", *to_checkout[i:i + 200]) return changes diff --git a/src/freehand/terminals.py b/src/freehand/terminals.py index f85e922b..0330cd30 100644 --- a/src/freehand/terminals.py +++ b/src/freehand/terminals.py @@ -14,23 +14,34 @@ from pathlib import Path from typing import Any +from freehand.runtime import osutil + class Terminal: def __init__(self, cwd: Path, owner: str) -> None: - if os.name != "posix": - raise ValueError("Integrated terminals currently require macOS or Linux.") - import fcntl - import termios self.id, self.owner, self.cwd, self.name = uuid.uuid4().hex, owner, str(cwd), "" self.lock = threading.Lock() self.output, self.offset = "", 0 self.started = time.time() + self._conpty: Any = None + self.fd: int = -1 + env = osutil.prepare_shell_env({**os.environ, "TERM": "xterm-256color", "COLORTERM": "truecolor"}) + if os.name == "nt": + from freehand.winpty import ConPtyProcess + shell = osutil.find_shell() + self._conpty = ConPtyProcess([shell, "-NoLogo"], cwd=cwd, env=env, rows=30, cols=100) + self.process: Any = self._conpty + threading.Thread(target=self._read_winpty, daemon=True, name="freehand-terminal").start() + return + if os.name != "posix": + raise ValueError("Integrated terminals are not supported on this platform.") + import fcntl + import termios self.fd, slave = os.openpty() try: os.set_blocking(self.fd, False) fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", 30, 100, 0, 0)) shell = os.environ.get("SHELL") or "/bin/bash" - env = {**os.environ, "TERM": "xterm-256color", "COLORTERM": "truecolor"} command = ([sys.executable, "__terminal__", shell] if getattr(sys, "frozen", False) else [sys.executable, "-m", "freehand.terminal_child", shell]) self.process = subprocess.Popen(command, cwd=cwd, stdin=slave, stdout=slave, stderr=slave, @@ -42,6 +53,30 @@ def __init__(self, cwd: Path, owner: str) -> None: os.close(slave) threading.Thread(target=self._read, daemon=True, name="freehand-terminal").start() + def _append(self, text: str) -> None: + with self.lock: + self.output += text + cut = max(0, len(self.output) - 1_000_000) + self.output = self.output[cut:] + self.offset += cut + + def _read_winpty(self) -> None: + decoder = codecs.getincrementaldecoder("utf-8")("replace") + try: + while True: + data = self._conpty.read(16384) + if not data: + break + self._append(decoder.decode(data)) + except OSError: + pass + finally: + try: + self._conpty.wait(timeout=2) + except (OSError, subprocess.TimeoutExpired): + pass + self._conpty.close() + def _read(self) -> None: decoder = codecs.getincrementaldecoder("utf-8")("replace") try: @@ -53,11 +88,7 @@ def _read(self) -> None: continue if not data: break - with self.lock: - self.output += decoder.decode(data) - cut = max(0, len(self.output) - 1_000_000) - self.output = self.output[cut:] - self.offset += cut + self._append(decoder.decode(data)) except OSError: pass finally: @@ -76,6 +107,16 @@ def write(self, text: str) -> None: data = text.encode() if len(data) > 65536: raise ValueError("Terminal input is limited to 64 KB.") + if self._conpty is not None: + try: + while data: + written = self._conpty.write(data) + if written <= 0: + raise ValueError("This terminal has closed.") + data = data[written:] + except OSError: + raise ValueError("This terminal has closed.") from None + return deadline = time.monotonic() + 2 while data: if time.monotonic() >= deadline: @@ -88,6 +129,9 @@ def write(self, text: str) -> None: raise ValueError("This terminal has closed.") from None def resize(self, rows: int, cols: int) -> None: + if self._conpty is not None: + self._conpty.resize(rows, cols) + return import fcntl import termios if self.process.poll() is None: @@ -96,6 +140,9 @@ def resize(self, rows: int, cols: int) -> None: os.killpg(self.process.pid, signal.SIGWINCH) def close(self) -> None: + if self._conpty is not None: + self._conpty.close() + return if self.process.poll() is not None: return try: diff --git a/src/freehand/tui.py b/src/freehand/tui.py index ccf321c5..baab4e2b 100644 --- a/src/freehand/tui.py +++ b/src/freehand/tui.py @@ -46,6 +46,7 @@ from prompt_toolkit.utils import get_cwidth from freehand import meter +from freehand.runtime import osutil Fragments = list[tuple[str, str]] SHORTCUTS = [("/", "commands"), ("@", "mention a file"), ("!", "shell command"), @@ -519,11 +520,64 @@ def is_focusable(self) -> bool: return False +def _win32_copy(text: str) -> bool: + """Write UTF-16LE text directly to the Windows clipboard via user32/kernel32 (no subprocess flash).""" + import ctypes + from ctypes import wintypes + u32 = ctypes.WinDLL("user32", use_last_error=True) + k32 = ctypes.WinDLL("kernel32", use_last_error=True) + u32.OpenClipboard.argtypes = [wintypes.HWND] + u32.OpenClipboard.restype = wintypes.BOOL + u32.EmptyClipboard.argtypes = [] + u32.EmptyClipboard.restype = wintypes.BOOL + u32.SetClipboardData.argtypes = [wintypes.UINT, wintypes.HANDLE] + u32.SetClipboardData.restype = wintypes.HANDLE + u32.CloseClipboard.argtypes = [] + u32.CloseClipboard.restype = wintypes.BOOL + k32.GlobalAlloc.argtypes = [wintypes.UINT, ctypes.c_size_t] + k32.GlobalAlloc.restype = wintypes.HGLOBAL + k32.GlobalLock.argtypes = [wintypes.HGLOBAL] + k32.GlobalLock.restype = wintypes.LPVOID + k32.GlobalUnlock.argtypes = [wintypes.HGLOBAL] + k32.GlobalUnlock.restype = wintypes.BOOL + k32.GlobalFree.argtypes = [wintypes.HGLOBAL] + k32.GlobalFree.restype = wintypes.HGLOBAL + raw = text.encode("utf-16-le") + b"\x00\x00" + if not u32.OpenClipboard(None): + return False + hmem = None + try: + u32.EmptyClipboard() + hmem = k32.GlobalAlloc(0x0002, len(raw)) # GMEM_MOVEABLE + if not hmem: + return False + ptr = k32.GlobalLock(hmem) + if not ptr: + k32.GlobalFree(hmem) + return False + try: + ctypes.memmove(ptr, raw, len(raw)) + finally: + k32.GlobalUnlock(hmem) + if not u32.SetClipboardData(13, hmem): # CF_UNICODETEXT + k32.GlobalFree(hmem) + return False + return True + finally: + u32.CloseClipboard() + + def copy_to_clipboard(text: str, output: Any) -> None: - """pbcopy, xclip or wl-copy when there is one; otherwise OSC 52, which asks the terminal itself (also over ssh).""" + """Native clipboard (Win32, pbcopy, wl-copy or xclip); otherwise OSC 52, which asks the terminal itself.""" import base64 import shutil import subprocess + if osutil.IS_WINDOWS and not os.environ.get("SSH_CONNECTION"): + try: + if _win32_copy(text): + return + except Exception: # noqa: BLE001 + pass for cmd in (["pbcopy"], ["wl-copy"], ["xclip", "-selection", "clipboard"]): if shutil.which(cmd[0]) and not os.environ.get("SSH_CONNECTION"): try: @@ -550,18 +604,30 @@ def apply_transformation(self, ti: TransformationInput) -> Transformation: display_to_source=lambda i: min(i, n) if i <= n else i - 1) -def editor_command(path: str, text: str) -> list[str]: - """$VISUAL or $EDITOR (else nano or vi) on *path*, told to put the cursor at the end of *text* where its - command line takes a place to start at: going on from where the input left off.""" +def split_editor(raw: str) -> list[str]: + """Split an editor command line without eating Windows path backslashes.""" import shlex + if not osutil.IS_WINDOWS: + return shlex.split(raw) + return [tok[1:-1] if len(tok) >= 2 and tok[0] == tok[-1] and tok[0] in ("'", '"') else tok + for tok in shlex.split(raw, posix=False)] + + +def editor_command(path: str, text: str) -> list[str]: + """$VISUAL or $EDITOR (else nano/vi on POSIX, code/notepad on Windows) on *path*, placing the cursor at the end.""" import shutil - raw = os.environ.get("VISUAL") or os.environ.get("EDITOR") or ("nano" if shutil.which("nano") else "vi") - argv = shlex.split(raw) or ["vi"] + if osutil.IS_WINDOWS: + default = "code --wait" if shutil.which("code") else "notepad" + else: + default = "nano" if shutil.which("nano") else "vi" + raw = os.environ.get("VISUAL") or os.environ.get("EDITOR") or default + argv = split_editor(raw) or split_editor(default) + argv[0] = osutil.resolve_executable(argv[0]) lines = text.split("\n") line, col = len(lines), len(lines[-1]) + 1 found = shutil.which(argv[0]) # by what it is: macOS's nano is pico under another name, and takes a line but no column - name = os.path.basename(os.path.realpath(found) if found else argv[0]).split(".")[0] # vim.basic is vim + name = os.path.basename(os.path.realpath(found) if found else argv[0]).split(".")[0].lower() # vim.basic is vim if name in ("vim", "nvim", "gvim", "mvim"): argv.append("+normal! G$") elif name in ("vi", "nvi", "pico"): @@ -831,7 +897,10 @@ async def edit() -> None: new = new[:-1] if new.endswith("\n") else new self.buffer.restore_document(Document(new, len(new))) finally: - os.unlink(path) + try: + os.unlink(path) + except OSError: + pass self.app.renderer.clear() self.app.invalidate() self.app.create_background_task(edit()) @@ -859,6 +928,7 @@ def clear_input(self) -> None: """Esc Esc or Ctrl-C on what is typed: cleared, not lost; ↑ brings it back, as it does a sent message.""" self.buffer.history.append_string(self.buffer.text) self.buffer.reset() + self.buffer.load_history_if_not_yet_loaded() self.flash("Cleared · ↑ brings it back", 2.0) def give_back(self, text: str) -> None: diff --git a/src/freehand/ui.py b/src/freehand/ui.py index 92ecb824..e52432c1 100644 --- a/src/freehand/ui.py +++ b/src/freehand/ui.py @@ -41,7 +41,7 @@ from freehand import (__version__, brand, cli, connections, export, hooks, inputs, meter, session, style, tui, usercommands) -from freehand.runtime import auth, providers +from freehand.runtime import auth, osutil, providers from freehand.runtime.agent import Agent, Cancelled, SessionBusy, image_mime, image_part, plan_signs from freehand.snapshots import SnapshotError, Snapshots from freehand.terminal_theme import TerminalTheme @@ -1460,13 +1460,16 @@ def for_history(self, text: str) -> str: a clipboard image, which nothing can bring back, is left out.""" text = self.expand_pastes(text) for n, path in self.image_paths.items(): - text = text.replace(f"[Image #{n}]", shlex.quote(path)) + quoted = f'"{path}"' if osutil.IS_WINDOWS and any(c.isspace() for c in path) else ( + path if osutil.IS_WINDOWS else shlex.quote(path)) + text = text.replace(f"[Image #{n}]", quoted) return re.sub(r"\[Image #\d+\] ?", "", text) def paste_image(self) -> str | None: data = inputs.clipboard_image() if not data: - self.flash("No image on the clipboard (Cmd+V pastes text)") + hint = "Cmd+V pastes text" if sys.platform == "darwin" else "Ctrl+Shift+V pastes text" + self.flash(f"No image on the clipboard ({hint})") return None token = self.add_image(data, "clipboard") return token + " " if token else None @@ -1600,7 +1603,9 @@ def work() -> None: threading.Thread(target=work, name="freehand-models", daemon=True).start() def run(self) -> int: + from prompt_toolkit.application import create_app_session from prompt_toolkit.patch_stdout import patch_stdout + osutil.enable_windows_console() if self.log is not None: sys.stdout.write("\x1b[?1049h") # the alternate screen, left once at the end sys.stdout.flush() @@ -1614,7 +1619,7 @@ def run(self) -> int: threading.Thread(target=self.follow_output, name="freehand-follow", daemon=True).start() try: # Replies can arrive between prompts too; cooked mode would echo them into the conversation. - with self.pt_input.raw_mode(): + with create_app_session(input=self.pt_input, output=self.pt_output), self.pt_input.raw_mode(): try: self.terminal_theme.set_auto(self.theme_setting not in style.PALETTES) return self.loop(patch_stdout) @@ -2418,10 +2423,14 @@ def command(self, text: str) -> str | None: elif cmd == "/status": self.status() elif cmd == "/context": - editor = os.environ.get("VISUAL") or os.environ.get("EDITOR") or "vi" + import shutil + default = ("code --wait" if shutil.which("code") else "notepad") if osutil.IS_WINDOWS else "vi" + editor = os.environ.get("VISUAL") or os.environ.get("EDITOR") or default + argv = tui.split_editor(editor) or tui.split_editor(default) + argv[0] = osutil.resolve_executable(argv[0]) path = self.dir / "transcript.json" before = path.read_bytes() if path.exists() else b"" - subprocess.call(shlex.split(editor) + [str(path)]) + subprocess.call(argv + [str(path)]) if self.log is not None: # the editor may have left the alternate screen sys.stdout.write("\x1b[?1049h") sys.stdout.flush() @@ -2455,7 +2464,7 @@ def command(self, text: str) -> str | None: text = session.export_markdown(self.dir) if target.suffix.lower() in (".md", ".markdown") else export.export_html(self.dir) target.write_text(text, encoding="utf-8") link = Text("Saved ") - link.append(short_path(target), style=f"accent link file://{target.resolve()}") + link.append(short_path(target), style=f"accent link {target.resolve().as_uri()}") self.renderer.info(link) elif cmd == "/usage": m = self.agent.meta diff --git a/src/freehand/web/app.js b/src/freehand/web/app.js index 51e77329..0ab70f64 100644 --- a/src/freehand/web/app.js +++ b/src/freehand/web/app.js @@ -302,8 +302,24 @@ async function copy(text, said = "copied", button = null) { const tokens = (n) => n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1000 ? `${(n / 1000).toFixed(n >= 1e5 ? 0 : 1)}K` : String(n || 0); -const short = (path) => path === null ? "No project" : view.overview && path.startsWith(view.overview.home) - ? "~" + path.slice(view.overview.home.length) : path; +const pathSep = (p) => String(p || "").includes("\\") ? "\\" : "/"; +const joinPath = (base, ...parts) => { + const sep = pathSep(base); + const head = String(base || "").replace(/[\\/]+$/, ""); + const tail = parts.flatMap((p) => String(p || "").split(/[\\/]/).filter(Boolean)); + if (!tail.length) return head || sep; + return head ? `${head}${sep}${tail.join(sep)}` : `${sep}${tail.join(sep)}`; +}; +const normPath = (p) => { + const s = String(p || "").replace(/\\/g, "/").replace(/\/+$/, ""); + return /^[a-zA-Z]:/.test(s) ? s.toLowerCase() : s; +}; +const pathInside = (p, root) => { + const a = normPath(p), b = normPath(root); + return Boolean(b) && (a === b || a.startsWith(b + "/")); +}; +const short = (path) => path === null ? "No project" : view.overview && pathInside(path, view.overview.home) + ? "~" + path.slice(view.overview.home.replace(/[\\/]+$/, "").length) : path; const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`; function duration(s) { @@ -318,7 +334,7 @@ const when = (ts) => { : s < 7 * 86400 ? `${Math.round(s / 86400)}d` : new Date(ts * 1000).toLocaleDateString(undefined, { month: "short", day: "numeric" }); }; -const baseName = (path) => path.split("/").filter(Boolean).pop() || "/"; +const baseName = (path) => String(path || "").split(/[\\/]/).filter(Boolean).pop() || "/"; // "none" is thinking off; a model that only turns thinking on or off is offered ["none", "high"]: off and on. const effortName = (effort, offered) => (effort === "none" ? "Off" : effort === "high" && offered?.length === 2 && offered[0] === "none" ? "On" @@ -5577,14 +5593,14 @@ async function openSettings(tab = null, adding = null) { }, skills() { // the person's own skills are listed (and edited) above, by the workbench; a project's come from its folder - const mine = `${data.home}/skills/`; - const project = data.skills.filter((skill) => !skill.path.startsWith(mine)); + const mine = joinPath(data.home, "skills"); + const project = data.skills.filter((skill) => !pathInside(skill.path, mine)); if (project.length) { pane.append(el("h3", "", "From this project")); for (const skill of project) pane.append(card(skill.name, skill.description || short(skill.path))); } pane.append(el("h3", "", "Instructions for every conversation")); - const where = data.instructions || `${data.home}/AGENTS.md`; + const where = data.instructions || joinPath(data.home, "AGENTS.md"); const copyPath = el("button", "btn", "Copy path"); copyPath.type = "button"; copyPath.addEventListener("click", () => copy(where, "path copied")); diff --git a/src/freehand/web/md.js b/src/freehand/web/md.js index 6de96227..48914c69 100644 --- a/src/freehand/web/md.js +++ b/src/freehand/web/md.js @@ -857,7 +857,7 @@ const EXT_LANG = { html: "html", htm: "html", xml: "xml", svg: "xml", }; const langOf = (path) => { - const name = path.split("/").pop().toLowerCase(); + const name = path.split(/[\\/]/).pop().toLowerCase(); return EXT_LANG[name] || EXT_LANG[name.split(".").pop()] || ""; }; diff --git a/src/freehand/web/panels.js b/src/freehand/web/panels.js index b3f32ac6..508ba47c 100644 --- a/src/freehand/web/panels.js +++ b/src/freehand/web/panels.js @@ -658,7 +658,7 @@ if (event.isComposing) return; if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "c" && window.getSelection()?.toString()) return; - if (event.metaKey && event.key.toLowerCase() === "v") return; // the paste event sends it + if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "v") return; // let paste event send it if (event.key.length === 1 && !event.ctrlKey && !event.altKey && !event.metaKey) return; // the input event const value = T.keyInput(event, screen); if (value) { event.preventDefault(); event.stopPropagation(); send(value); } diff --git a/src/freehand/web/workbench.js b/src/freehand/web/workbench.js index e807de12..77664cbf 100644 --- a/src/freehand/web/workbench.js +++ b/src/freehand/web/workbench.js @@ -215,7 +215,7 @@ await post("editor", { path, line, editor: recall("freehand.editor", "code") }, sid); } async function saveAs(path, sid) { - const name = path.split("/").pop(); + const name = baseName(path); const destination = desktop?.saveAs ? await desktop.saveAs(name) : await askText("Save a copy", "Absolute destination path, including the new name. Existing files are never overwritten."); if (destination) { await post("save-as", { path, destination }, sid); toast("Copy saved"); } @@ -556,15 +556,16 @@ items = data.items; if (mode === "changed") { const changes = await api(`/api/sessions/${sid}/changes`); - const paths = new Set(changes.files.map((f) => data.root + "/" + f.path)); - items = items.filter((f) => f.directory || paths.has(f.path)); + const paths = new Set(changes.files.map((f) => normPath(joinPath(data.root, f.path)))); + items = items.filter((f) => f.directory || paths.has(normPath(f.path))); } // the folder as the steps from the top one, each a way back up const steps = []; - const inside = folder.startsWith(data.root) ? folder.slice(data.root.length).split("/").filter(Boolean) : []; + const rootLen = data.root.replace(/[\\/]+$/, "").length; + const inside = pathInside(folder, data.root) ? folder.slice(rootLen).split(/[\\/]/).filter(Boolean) : []; const top = root === "session" ? tr("Conversation data", "会话数据") : baseName(data.root) || data.root; [top, ...inside].forEach((name, i) => { - const target = [data.root, ...inside.slice(0, i)].join("/"); + const target = joinPath(data.root, ...inside.slice(0, i)); if (i) steps.push(el("span", "crumb-sep", "/")); const step = button(name, () => { folder = target; return load(); }, "crumb"); step.title = target; @@ -682,9 +683,9 @@ if (diff.cut) patch.append(text(tr("Diff truncated", "差异已截断"))); list.querySelectorAll(".wb-row").forEach((r) => r.classList.toggle("on", r.dataset.path === file.path)); detail.replaceChildren(row(text(tr(staged ? "Staged" : "Working tree", staged ? "已暂存" : "工作目录")), - button("Preview", () => previewFile(sid, data.root + "/" + file.path)), + button("Preview", () => previewFile(sid, joinPath(data.root, file.path))), button("Feedback", () => feedback(file.path)), - button("Editor", () => editor(data.root + "/" + file.path, 1, sid))), patch); + button("Editor", () => editor(joinPath(data.root, file.path), 1, sid))), patch); }; for (const f of data.files) { const check = el("input"); check.type = "checkbox"; check.setAttribute("aria-label", `Select ${f.path}`); diff --git a/src/freehand/winpty.py b/src/freehand/winpty.py new file mode 100644 index 00000000..dc9e6477 --- /dev/null +++ b/src/freehand/winpty.py @@ -0,0 +1,291 @@ +"""Stdlib-only Windows ConPTY (CreatePseudoConsole) backend for integrated terminals and PTY tests.""" +from __future__ import annotations + +import ctypes +from ctypes import wintypes +import os +import subprocess +import threading +from pathlib import Path +from typing import Mapping + +from freehand.runtime import osutil + +if os.name == "nt": + _k32 = ctypes.WinDLL("kernel32", use_last_error=True) + + _EXTENDED_STARTUPINFO_PRESENT = 0x00080000 + _CREATE_UNICODE_ENVIRONMENT = 0x00000400 + _STARTF_USESTDHANDLES = 0x00000100 + _PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE = 0x00020016 + _STILL_ACTIVE = 259 + _WAIT_OBJECT_0 = 0 + _INFINITE = 0xFFFFFFFF + + class _COORD(ctypes.Structure): + _fields_ = [("X", ctypes.c_short), ("Y", ctypes.c_short)] + + class _STARTUPINFOW(ctypes.Structure): + _fields_ = [ + ("cb", wintypes.DWORD), + ("lpReserved", wintypes.LPWSTR), + ("lpDesktop", wintypes.LPWSTR), + ("lpTitle", wintypes.LPWSTR), + ("dwX", wintypes.DWORD), + ("dwY", wintypes.DWORD), + ("dwXSize", wintypes.DWORD), + ("dwYSize", wintypes.DWORD), + ("dwXCountChars", wintypes.DWORD), + ("dwYCountChars", wintypes.DWORD), + ("dwFillAttribute", wintypes.DWORD), + ("dwFlags", wintypes.DWORD), + ("wShowWindow", wintypes.WORD), + ("cbReserved2", wintypes.WORD), + ("lpReserved2", ctypes.POINTER(ctypes.c_byte)), + ("hStdInput", wintypes.HANDLE), + ("hStdOutput", wintypes.HANDLE), + ("hStdError", wintypes.HANDLE), + ] + + class _STARTUPINFOEXW(ctypes.Structure): + _fields_ = [ + ("StartupInfo", _STARTUPINFOW), + ("lpAttributeList", ctypes.c_void_p), + ] + + class _PROCESS_INFORMATION(ctypes.Structure): + _fields_ = [ + ("hProcess", wintypes.HANDLE), + ("hThread", wintypes.HANDLE), + ("dwProcessId", wintypes.DWORD), + ("dwThreadId", wintypes.DWORD), + ] + + _k32.CreatePipe.argtypes = [ + ctypes.POINTER(wintypes.HANDLE), ctypes.POINTER(wintypes.HANDLE), ctypes.c_void_p, wintypes.DWORD + ] + _k32.CreatePipe.restype = wintypes.BOOL + _k32.CreatePseudoConsole.argtypes = [ + _COORD, wintypes.HANDLE, wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE) + ] + _k32.CreatePseudoConsole.restype = ctypes.c_long + _k32.ResizePseudoConsole.argtypes = [wintypes.HANDLE, _COORD] + _k32.ResizePseudoConsole.restype = ctypes.c_long + _k32.ClosePseudoConsole.argtypes = [wintypes.HANDLE] + _k32.ClosePseudoConsole.restype = None + _k32.InitializeProcThreadAttributeList.argtypes = [ + ctypes.c_void_p, wintypes.DWORD, wintypes.DWORD, ctypes.POINTER(ctypes.c_size_t) + ] + _k32.InitializeProcThreadAttributeList.restype = wintypes.BOOL + _k32.UpdateProcThreadAttribute.argtypes = [ + ctypes.c_void_p, wintypes.DWORD, ctypes.c_size_t, ctypes.c_void_p, + ctypes.c_size_t, ctypes.c_void_p, ctypes.c_void_p + ] + _k32.UpdateProcThreadAttribute.restype = wintypes.BOOL + _k32.DeleteProcThreadAttributeList.argtypes = [ctypes.c_void_p] + _k32.DeleteProcThreadAttributeList.restype = None + _k32.CreateProcessW.argtypes = [ + wintypes.LPCWSTR, wintypes.LPWSTR, ctypes.c_void_p, ctypes.c_void_p, wintypes.BOOL, + wintypes.DWORD, ctypes.c_void_p, wintypes.LPCWSTR, + ctypes.POINTER(_STARTUPINFOEXW), ctypes.POINTER(_PROCESS_INFORMATION) + ] + _k32.CreateProcessW.restype = wintypes.BOOL + _k32.ReadFile.argtypes = [ + wintypes.HANDLE, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD), ctypes.c_void_p + ] + _k32.ReadFile.restype = wintypes.BOOL + _k32.WriteFile.argtypes = [ + wintypes.HANDLE, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD), ctypes.c_void_p + ] + _k32.WriteFile.restype = wintypes.BOOL + _k32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD] + _k32.WaitForSingleObject.restype = wintypes.DWORD + _k32.GetExitCodeProcess.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)] + _k32.GetExitCodeProcess.restype = wintypes.BOOL + _k32.TerminateProcess.argtypes = [wintypes.HANDLE, wintypes.UINT] + _k32.TerminateProcess.restype = wintypes.BOOL + _k32.CloseHandle.argtypes = [wintypes.HANDLE] + _k32.CloseHandle.restype = wintypes.BOOL + + +def _env_block(env: Mapping[str, str]) -> ctypes.Array[ctypes.c_char]: + # Windows CreateProcessW requires a sorted, NUL-separated UTF-16LE block terminated by an extra NUL. + items = sorted(env.items(), key=lambda kv: kv[0].upper()) + raw = "".join(f"{k}={v}\0" for k, v in items) + "\0" + return ctypes.create_string_buffer(raw.encode("utf-16-le")) + + +class ConPtyProcess: + """A child process attached to a Windows Pseudo Console (ConPTY).""" + + def __init__(self, argv: list[str], cwd: Path | str, env: Mapping[str, str], + rows: int = 30, cols: int = 100) -> None: + if os.name != "nt": + raise RuntimeError("ConPtyProcess is only supported on Windows.") + self._lock = threading.Lock() + self._closed = False + self._hpc: wintypes.HANDLE | None = None + self._in_write: wintypes.HANDLE | None = None + self._out_read: wintypes.HANDLE | None = None + self._hproc: wintypes.HANDLE | None = None + self._job: int | None = None + self.pid: int = 0 + self.returncode: int | None = None + + in_read, in_write = wintypes.HANDLE(), wintypes.HANDLE() + out_read, out_write = wintypes.HANDLE(), wintypes.HANDLE() + if not _k32.CreatePipe(ctypes.byref(in_read), ctypes.byref(in_write), None, 0): + raise ctypes.WinError(ctypes.get_last_error()) + if not _k32.CreatePipe(ctypes.byref(out_read), ctypes.byref(out_write), None, 0): + _k32.CloseHandle(in_read) + _k32.CloseHandle(in_write) + raise ctypes.WinError(ctypes.get_last_error()) + + hpc = wintypes.HANDLE() + hr = _k32.CreatePseudoConsole(_COORD(max(10, cols), max(2, rows)), in_read, out_write, 0, ctypes.byref(hpc)) + # ConPTY duplicates the pipe ends it owns; closing our copies allows clean EOF when it shuts down. + _k32.CloseHandle(in_read) + _k32.CloseHandle(out_write) + if hr != 0: + _k32.CloseHandle(in_write) + _k32.CloseHandle(out_read) + raise OSError(f"CreatePseudoConsole failed with HRESULT 0x{hr & 0xFFFFFFFF:08x}") + + self._hpc = hpc + self._in_write = in_write + self._out_read = out_read + + attr_list = None + try: + size = ctypes.c_size_t(0) + _k32.InitializeProcThreadAttributeList(None, 1, 0, ctypes.byref(size)) + attr_buf = ctypes.create_string_buffer(size.value) + if not _k32.InitializeProcThreadAttributeList(attr_buf, 1, 0, ctypes.byref(size)): + raise ctypes.WinError(ctypes.get_last_error()) + attr_list = attr_buf + if not _k32.UpdateProcThreadAttribute( + attr_buf, 0, _PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, + ctypes.c_void_p(hpc.value), ctypes.sizeof(wintypes.HANDLE), None, None + ): + raise ctypes.WinError(ctypes.get_last_error()) + + si = _STARTUPINFOEXW() + si.StartupInfo.cb = ctypes.sizeof(_STARTUPINFOEXW) + # Clear inherited pipe handles from a non-console parent (daemon, Electron, pytest) so ConPTY owns stdio. + si.StartupInfo.dwFlags = _STARTF_USESTDHANDLES + si.lpAttributeList = ctypes.addressof(attr_buf) + pi = _PROCESS_INFORMATION() + + cmdline = subprocess.list2cmdline(argv) + cmd_buf = ctypes.create_unicode_buffer(cmdline) + env_buf = _env_block(env) + flags = _EXTENDED_STARTUPINFO_PRESENT | _CREATE_UNICODE_ENVIRONMENT + if not _k32.CreateProcessW( + None, cmd_buf, None, None, False, flags, ctypes.addressof(env_buf), + str(cwd), ctypes.byref(si), ctypes.byref(pi) + ): + raise ctypes.WinError(ctypes.get_last_error()) + + _k32.CloseHandle(pi.hThread) + self._hproc = pi.hProcess + self.pid = int(pi.dwProcessId) + self._job = osutil.create_process_job() + if self._job: + osutil.assign_process_job(self._job, self) # type: ignore[arg-type] + except BaseException: + self.close() + raise + finally: + if attr_list is not None: + _k32.DeleteProcThreadAttributeList(attr_list) + + def read(self, size: int = 16384) -> bytes: + handle = self._out_read + if not handle: + return b"" + buf = ctypes.create_string_buffer(size) + got = wintypes.DWORD(0) + ok = _k32.ReadFile(handle, buf, size, ctypes.byref(got), None) + if not ok or got.value == 0: + return b"" + return buf.raw[:got.value] + + def write(self, data: bytes) -> int: + handle = self._in_write + if not handle: + raise OSError("terminal input handle is closed") + written = wintypes.DWORD(0) + if not _k32.WriteFile(handle, data, len(data), ctypes.byref(written), None): + raise ctypes.WinError(ctypes.get_last_error()) + return int(written.value) + + def resize(self, rows: int, cols: int) -> None: + with self._lock: + if self._hpc and self.poll() is None: + _k32.ResizePseudoConsole(self._hpc, _COORD(max(10, min(cols, 500)), max(2, min(rows, 200)))) + + def poll(self) -> int | None: + if self.returncode is not None: + return self.returncode + handle = self._hproc + if not handle: + return 0 + code = wintypes.DWORD(0) + if not _k32.GetExitCodeProcess(handle, ctypes.byref(code)): + return None + if code.value == _STILL_ACTIVE: + return None + self.returncode = int(code.value) + return self.returncode + + def wait(self, timeout: float | None = None) -> int: + if self.returncode is not None: + return self.returncode + handle = self._hproc + if not handle: + self.returncode = 0 + return 0 + ms = _INFINITE if timeout is None else max(0, int(timeout * 1000)) + res = _k32.WaitForSingleObject(handle, ms) + if res != _WAIT_OBJECT_0: + raise subprocess.TimeoutExpired(cmd="conpty", timeout=timeout or 0) + rc = self.poll() + return 0 if rc is None else rc + + def kill(self) -> None: + if self._job: + osutil.kill_process_tree(None, self._job) + if self._hproc and self.poll() is None: + _k32.TerminateProcess(self._hproc, 1) + + def close(self) -> None: + with self._lock: + if self._closed: + return + self._closed = True + hpc, self._hpc = self._hpc, None + in_write, self._in_write = self._in_write, None + out_read, self._out_read = self._out_read, None + hproc, self._hproc = self._hproc, None + job, self._job = self._job, None + if in_write: + _k32.CloseHandle(in_write) + if hpc: + # ClosePseudoConsole notifies the attached console process to exit and unblocks ReadFile on out_read. + _k32.ClosePseudoConsole(hpc) + if hproc: + if self.returncode is None: + res = _k32.WaitForSingleObject(hproc, 2000) + if res != _WAIT_OBJECT_0: + if job: + osutil.kill_process_tree(None, job) + _k32.TerminateProcess(hproc, 1) + _k32.WaitForSingleObject(hproc, 2000) + code = wintypes.DWORD(0) + if _k32.GetExitCodeProcess(hproc, ctypes.byref(code)) and code.value != _STILL_ACTIVE: + self.returncode = int(code.value) + _k32.CloseHandle(hproc) + if out_read: + _k32.CloseHandle(out_read) + if job: + osutil.close_process_job(job) diff --git a/src/freehand/workbench.py b/src/freehand/workbench.py index 3cdcaa6d..05bcf136 100644 --- a/src/freehand/workbench.py +++ b/src/freehand/workbench.py @@ -17,7 +17,7 @@ from urllib.parse import urlsplit from freehand import __version__, limits, session, workbench_state -from freehand.runtime import auth +from freehand.runtime import auth, osutil from freehand.terminals import Terminal @@ -142,9 +142,41 @@ def endpoint(value: Any) -> str: return value.rstrip("/") +def _split_tokens(raw: str) -> list[str]: + if not osutil.IS_WINDOWS: + return shlex.split(raw) + # Split on whitespace while honoring quotes inside tokens (e.g. DATA="C:\My Data") without escaping backslashes. + tokens: list[str] = [] + buf: list[str] = [] + quote: str | None = None + in_token = False + for ch in raw: + if quote is not None: + if ch == quote: + quote = None + else: + buf.append(ch) + elif ch in ("'", '"'): + quote = ch + in_token = True + elif ch.isspace(): + if in_token: + tokens.append("".join(buf)) + buf = [] + in_token = False + else: + buf.append(ch) + in_token = True + if quote is not None: + raise ValueError("No closing quotation") + if in_token: + tokens.append("".join(buf)) + return tokens + + def parse_mcp(command: str, pairs: str) -> tuple[list[str], dict[str, str]]: try: - argv, entries = shlex.split(command), shlex.split(pairs) + argv, entries = _split_tokens(command), _split_tokens(pairs) except ValueError as exc: raise WorkbenchError(f"Check the quotes: {exc}") from None require(all("=" in item and item.split("=", 1)[0] for item in entries), "Use NAME=VALUE for each entry.") @@ -242,17 +274,7 @@ def validate_advanced(values: dict) -> None: def locked(path: Path) -> bool: - try: - import fcntl - with (path / ".state" / "session.lock").open("r") as stream: - try: - fcntl.flock(stream, fcntl.LOCK_SH | fcntl.LOCK_NB) - fcntl.flock(stream, fcntl.LOCK_UN) - except BlockingIOError: - return True - except (ImportError, OSError): - pass - return False + return osutil.is_file_locked(osutil.session_lock_path(path)) class Workbench: @@ -413,7 +435,7 @@ def get(self, action: str, data: dict) -> dict: return {"patch": patch[:400_000], "cut": len(patch) > 400_000} if action == "git-diff": root = git_root(cwd) - path = str(inside(root, data.get("path") or ".", exists=False).relative_to(root)) + path = inside(root, data.get("path") or ".", exists=False).relative_to(root).as_posix() staged = data.get("staged") == "1" if data.get("untracked") == "1": file = inside(root, path) @@ -541,10 +563,7 @@ def _post(self, action: str, data: dict) -> dict: "Skill text is empty or too large.") require(not target.exists() or data.get("replace") is True, "This skill exists. Confirm replacement.", 409) - path.mkdir(parents=True, exist_ok=True) - temp = path / ".SKILL.md.tmp" - temp.write_text(text, encoding="utf-8") - os.replace(temp, target) + osutil.atomic_write_text(target, text) return {"ok": True} if action == "repair-config": require(data.get("confirm") is True and self.config_problem(), "Only an invalid config can be reset here.") @@ -586,23 +605,31 @@ def _post(self, action: str, data: dict) -> dict: raise WorkbenchError("Unknown terminal operation.") return {"ok": True} if action == "open-folder": - run(cwd, ["/usr/bin/open", str(cwd)] if sys.platform == "darwin" else ["xdg-open", str(cwd)]) + if sys.platform == "win32": + try: + os.startfile(str(cwd)) + except OSError: + raise WorkbenchError("Could not open this folder.", 409) from None + else: + run(cwd, ["/usr/bin/open", str(cwd)] if sys.platform == "darwin" else ["xdg-open", str(cwd)]) return {"ok": True} if action == "editor": editor = data.get("editor") or "code" require(editor in ("code", "cursor", "windsurf", "zed"), "Choose a supported editor.") target = inside(cwd, data.get("path") or ".") line = int(data.get("line") or 1) - args = [editor, str(target)] + exe = osutil.resolve_executable(editor) + args = [exe, str(target)] if target.is_file() and editor != "zed": - args = [editor, "--goto", f"{target}:{max(1, line)}"] + args = [exe, "--goto", f"{target}:{max(1, line)}"] run(cwd, args) return {"ok": True} if action in ("save-as", "promote"): self.idle_folder(cwd) source = inside(cwd, data.get("path") or ".") raw = data.get("destination") - require(isinstance(raw, str) and raw.startswith(("/", "~")), "Choose an absolute destination path.") + is_abs = isinstance(raw, str) and (raw.startswith(("~", "/")) or Path(raw).is_absolute()) + require(is_abs, "Choose an absolute destination path.") target = Path(raw).expanduser().resolve() require(not target.exists(), "The destination already exists. Choose a new name; nothing was overwritten.", 409) @@ -640,7 +667,7 @@ def _post(self, action: str, data: dict) -> dict: operation = data.get("action") paths = data.get("paths") or [] require(isinstance(paths, list) and all(isinstance(p, str) for p in paths), "Invalid paths.") - paths = [str(inside(root, p, exists=False).relative_to(root)) for p in paths] + paths = [inside(root, p, exists=False).relative_to(root).as_posix() for p in paths] ref = str(data.get("branch") or "") if operation in ("stage", "unstage", "discard"): require(paths, "Select at least one file.") diff --git a/tests/conftest.py b/tests/conftest.py index 4f000cd6..40ab39a9 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -76,6 +76,12 @@ def pytest_runtest_makereport(item, call): page.capture_failure(directory, f"{item.nodeid}-{index}") except Exception as error: warnings.warn(f"Could not capture UI failure artifacts: {type(error).__name__}") + if call.when == "teardown": + import sys as _sys + mod = _sys.modules.get("repl_driver") + if mod is not None: + for drv in list(mod.Driver.live): + drv.close() @pytest.fixture(autouse=True) diff --git a/tests/desktop_development.js b/tests/desktop_development.js index eed21ead..7b113544 100644 --- a/tests/desktop_development.js +++ b/tests/desktop_development.js @@ -77,7 +77,7 @@ async function check() { const main = fs.readFileSync(path.join(__dirname, "..", "desktop", "main.js"), "utf8"); const accessible = new Set(["/repo/.venv/bin/freehand", "/resources/freehand/freehand", "/installed/freehand"]); - const context = vm.createContext({ __dirname: "/repo/desktop", path, os, app: { isPackaged: false }, + const context = vm.createContext({ __dirname: "/repo/desktop", path: path.posix, os, app: { isPackaged: false }, process: { env: { PATH: "/installed" }, platform: "darwin", resourcesPath: "/resources" }, fs: { constants: { X_OK: 1 }, accessSync(file) { if (!accessible.has(file)) throw new Error("missing"); } }, readState: () => ({}), @@ -95,6 +95,27 @@ async function check() { accessible.delete("/resources/freehand/freehand"); assert.equal(cli(), "/installed/freehand"); + const winAccessible = new Set([ + "C:\\repo\\.venv\\Scripts\\freehand.exe", + "C:\\resources\\freehand\\freehand.exe", + "C:\\installed\\freehand.exe", + ]); + const winContext = vm.createContext({ __dirname: "C:\\repo\\desktop", path: path.win32, os, app: { isPackaged: false }, + process: { env: { PATH: "C:\\installed", LOCALAPPDATA: "C:\\Users\\test\\AppData\\Local" }, + platform: "win32", resourcesPath: "C:\\resources" }, + fs: { constants: { F_OK: 0 }, accessSync(file) { if (!winAccessible.has(file)) throw new Error("missing"); } }, + readState: () => ({}), + }); + vm.runInContext(main.slice(main.indexOf("function findFreehand()"), main.indexOf("const statePath =")), winContext); + const winCli = () => vm.runInContext("findFreehand()", winContext); + assert.equal(winCli(), "C:\\repo\\.venv\\Scripts\\freehand.exe"); + winContext.app.isPackaged = true; + assert.equal(winCli(), "C:\\resources\\freehand\\freehand.exe"); + winContext.app.isPackaged = false; + winAccessible.delete("C:\\repo\\.venv\\Scripts\\freehand.exe"); + winAccessible.delete("C:\\resources\\freehand\\freehand.exe"); + assert.equal(winCli(), "C:\\installed\\freehand.exe"); + let setShortcuts, remembered; const shortcuts = vm.createContext({ trusted: () => true, buildMenu() {}, remember(value) { remembered = value; }, ipcMain: { handle(name, handler) { diff --git a/tests/desktop_recovery.js b/tests/desktop_recovery.js index ce5ca37f..8f72b9dc 100644 --- a/tests/desktop_recovery.js +++ b/tests/desktop_recovery.js @@ -12,5 +12,5 @@ try { recovery.ack(file, { "freehand.drafts": { a: "latest" } }); assert.deepEqual(recovery.read(file), {}); assert.throws(() => recovery.save(file, { credentials: "forbidden" })); - assert.equal(fs.statSync(file).mode & 0o777, 0o600); + if (process.platform !== "win32") assert.equal(fs.statSync(file).mode & 0o777, 0o600); } finally { fs.rmSync(root, { recursive: true, force: true }); } diff --git a/tests/desktop_release_updates.js b/tests/desktop_release_updates.js index fbf8885e..17a9bbd0 100644 --- a/tests/desktop_release_updates.js +++ b/tests/desktop_release_updates.js @@ -21,6 +21,7 @@ function fixture(t) { ["Freehand-macos-15-intel", "latest-mac.yml", ["Freehand-0.2.0-mac.zip", "Freehand-0.2.0.dmg"]], ["Freehand-ubuntu-24.04", "latest-linux.yml", ["Freehand-0.2.0.AppImage", "freehand-desktop_0.2.0_amd64.deb", "freehand-desktop-0.2.0.x86_64.rpm"]], + ["Freehand-windows-latest", "latest.yml", ["Freehand-Setup-0.2.0.exe"]], ]; for (const [directory, manifest, names] of groups) { const dir = path.join(input, directory); @@ -28,7 +29,9 @@ function fixture(t) { const files = names.map((name) => { const content = Buffer.from(`Offline artifact ${name}`); fs.writeFileSync(path.join(dir, name), content); - if (manifest === "latest-mac.yml") fs.writeFileSync(path.join(dir, `${name}.blockmap`), "blockmap"); + if (manifest === "latest-mac.yml" || manifest === "latest.yml") { + fs.writeFileSync(path.join(dir, `${name}.blockmap`), "blockmap"); + } return { url: name, sha512: crypto.createHash("sha512").update(content).digest("base64"), size: content.length }; }); fs.writeFileSync(path.join(dir, manifest), yaml.dump({ version, files, releaseDate: "2026-12-03T00:00:00.000Z" })); @@ -55,8 +58,11 @@ test("merged manifests select the correct Mac zip and Linux package in the real assert.ok(findFile(resolveFiles(linux, base), "AppImage").url.pathname.endsWith(".AppImage")); assert.equal(linux.files.length, 3); assert.ok(findFile(resolveFiles(linux, base), "rpm").url.pathname.endsWith(".x86_64.rpm")); + const win = parseUpdateInfo(fs.readFileSync(path.join(f.output, "latest.yml"), "utf8")); + assert.equal(win.files.length, 1); + assert.ok(findFile(resolveFiles(win, base), "exe").url.pathname.endsWith("Freehand-Setup-0.2.0.exe")); const checksums = fs.readFileSync(path.join(f.output, "SHA256SUMS-desktop.txt"), "utf8").trim().split("\n"); - assert.equal(checksums.length, 13); + assert.equal(checksums.length, 16); for (const line of checksums) { const [hash, name] = line.split(" "); assert.equal(hash, crypto.createHash("sha256").update(fs.readFileSync(path.join(f.output, name))).digest("hex")); diff --git a/tests/desktop_service.js b/tests/desktop_service.js index 0e5feb3e..954af7e9 100644 --- a/tests/desktop_service.js +++ b/tests/desktop_service.js @@ -71,7 +71,7 @@ function harness(first) { BrowserWindow: FakeWindow, ipcMain: { on() {}, handle() {} }, }; if (name === "node:fs") return { readFileSync(file) { - assert.equal(file, "/unused/state.json"); + assert.equal(file, path.join("/unused", "state.json")); return JSON.stringify({ session: "#session/s1" }); } }; if (name === "node:os") return { homedir: () => "/home" }; diff --git a/tests/desktop_updates.js b/tests/desktop_updates.js index a85a6453..06f98a94 100644 --- a/tests/desktop_updates.js +++ b/tests/desktop_updates.js @@ -6,7 +6,8 @@ const { createUpdates, publishedReleases, latestRelease, installerURL, prepareMa const base = "https://github.com/microsoft/FreeHand/releases"; function release(version = "0.2.0", changes = {}) { const names = [`Freehand-${version}-arm64.dmg`, `Freehand-${version}.dmg`, `Freehand-${version}.AppImage`, - `freehand-desktop_${version}_amd64.deb`, `freehand-desktop-${version}.x86_64.rpm`]; + `freehand-desktop_${version}_amd64.deb`, `freehand-desktop-${version}.x86_64.rpm`, + `Freehand-Setup-${version}.exe`]; return { tag_name: `v${version}`, draft: false, prerelease: true, assets: names.map((name) => ({ name, browser_download_url: `${base}/download/v${version}/${name}` })), ...changes }; } @@ -74,6 +75,7 @@ test("manual links select the exact architecture and package, never arbitrary as assert.ok(installerURL(release(), "linux", "x64", "deb").endsWith("_amd64.deb")); assert.ok(installerURL(release(), "linux", "x64", "AppImage").endsWith(".AppImage")); assert.ok(installerURL(release(), "linux", "x64", "rpm").endsWith(".x86_64.rpm")); + assert.ok(installerURL(release(), "win32", "x64").endsWith("Freehand-Setup-0.2.0.exe")); assert.equal(installerURL(release(), "linux", "arm64"), null); const malicious = release(); malicious.assets.forEach((asset) => { asset.browser_download_url = "https://example.invalid/installer"; }); diff --git a/tests/fakes.py b/tests/fakes.py index 41dcb27a..e6771f8f 100644 --- a/tests/fakes.py +++ b/tests/fakes.py @@ -136,21 +136,36 @@ def make_session(tmp_path: Path, url: str, **config) -> Path: return h +def py_cmd(code: str) -> str: + """Run a Python snippet inside the platform shell (bash on POSIX, PowerShell on Windows).""" + from freehand.runtime import osutil + encoded = base64.b64encode(code.encode("utf-8")).decode("ascii") + runner = f"import base64; exec(compile(base64.b64decode({encoded!r}).decode('utf-8'), '', 'exec'))" + exe = osutil.quote_shell_arg(sys.executable) + arg = osutil.quote_shell_arg(runner) + return f"& {exe} -c {arg}" if osutil.IS_WINDOWS else f"{exe} -c {arg}" + + def run_runner(h: Path, timeout=120) -> subprocess.CompletedProcess: - return subprocess.run(["bash", str(h / "src" / "run.sh")], env={**os.environ, "FREEHAND_SESSION": str(h)}, - capture_output=True, text=True, timeout=timeout) + env = {**os.environ, "FREEHAND_SESSION": str(h)} + if os.name == "nt": + return subprocess.run([sys.executable, str(h / "src" / "agent.py")], cwd=h, env=env, + capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout) + return subprocess.run(["bash", str(h / "src" / "run.sh")], env=env, + capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout) def expected_prompt(h: Path, image_part: str = "an input_image part") -> str: - return PROMPT.read_text().replace("{transcript_path}", str(h / "transcript.json")).replace("{image_part}", image_part) + text = PROMPT.read_text(encoding="utf-8").replace("\r\n", "\n") + return text.replace("{transcript_path}", str(h / "transcript.json")).replace("{image_part}", image_part) def transcript(h: Path): - return json.loads((h / "transcript.json").read_text())["items"] + return json.loads((h / "transcript.json").read_text(encoding="utf-8"))["items"] def meta(h: Path): - return json.loads((h / ".state" / "meta.json").read_text()) + return json.loads((h / ".state" / "meta.json").read_text(encoding="utf-8")) def developer_texts(items): @@ -243,3 +258,20 @@ def signed_in_store(home: Path, *, access="access-0", expires_in=3600.0, client_ "scopes": ["chatgpt.tokens.use.direct"] if plan else []} (home / "auth.json").write_text(json.dumps({"active": "user-1", "accounts": {"user-1": record}})) return home / "auth.json" + + +def pid_alive(pid: int) -> bool: + """Whether process *pid* is still alive (cross-platform).""" + if os.name == "nt": + import ctypes + from ctypes import wintypes + k32 = ctypes.WinDLL("kernel32", use_last_error=True) + h = k32.OpenProcess(0x1000, False, int(pid)) # PROCESS_QUERY_LIMITED_INFORMATION + if not h: + return False + try: + code = wintypes.DWORD() + return bool(k32.GetExitCodeProcess(h, ctypes.byref(code))) and code.value == 259 # STILL_ACTIVE + finally: + k32.CloseHandle(h) + return subprocess.run(["ps", "-p", str(pid)], capture_output=True).returncode == 0 diff --git a/tests/pty_driver.py b/tests/pty_driver.py index 5fe1cb74..47bce377 100644 --- a/tests/pty_driver.py +++ b/tests/pty_driver.py @@ -2,13 +2,11 @@ hands the UI a console and so never reaches that mode; what a terminal is left in afterwards only shows here.""" from __future__ import annotations -import fcntl import os import re import struct import subprocess import sys -import termios import threading import time from pathlib import Path @@ -16,20 +14,31 @@ class Pty: def __init__(self, args: list[str], cwd: Path, env: dict[str, str], cols: int = 100, rows: int = 30) -> None: + self._buf = bytearray() + self._lock = threading.Lock() + self._conpty = None + self.master = -1 + if os.name == "nt": + from freehand.winpty import ConPtyProcess + self._conpty = ConPtyProcess([sys.executable, "-m", "freehand", *args], cwd=cwd, env=env, + rows=rows, cols=cols) + self.proc = self._conpty + threading.Thread(target=self._read, daemon=True).start() + return + import fcntl + import termios master, slave = os.openpty() fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0)) self.master = master self.proc = subprocess.Popen([sys.executable, "-m", "freehand", *args], cwd=cwd, env=env, stdin=slave, stdout=slave, stderr=slave, start_new_session=True, close_fds=True) os.close(slave) - self._buf = bytearray() - self._lock = threading.Lock() threading.Thread(target=self._read, daemon=True).start() def _read(self) -> None: while True: try: - chunk = os.read(self.master, 65536) + chunk = self._conpty.read(65536) if self._conpty is not None else os.read(self.master, 65536) except OSError: return if not chunk: @@ -37,7 +46,7 @@ def _read(self) -> None: with self._lock: self._buf += chunk if b"\x1b[6n" in chunk: # answer prompt_toolkit's cursor position query as a terminal would - os.write(self.master, b"\x1b[1;1R") + self.send("\x1b[1;1R") @property def raw(self) -> str: @@ -51,7 +60,11 @@ def text(self) -> str: "", self.raw) def send(self, keys: str) -> None: - os.write(self.master, keys.encode()) + data = keys.encode() + if self._conpty is not None: + self._conpty.write(data) + else: + os.write(self.master, data) def wait_for(self, words: str, timeout: float = 20.0) -> None: end = time.time() + timeout @@ -70,6 +83,9 @@ def wait_exit(self, timeout: float = 20.0) -> int: time.sleep(0.2) # the reader drains what was written last def close(self) -> None: + if self._conpty is not None: + self._conpty.close() + return if self.proc.poll() is None: self.proc.kill() self.proc.wait() diff --git a/tests/repl_driver.py b/tests/repl_driver.py index bf4cbb17..4dc80fcc 100644 --- a/tests/repl_driver.py +++ b/tests/repl_driver.py @@ -23,9 +23,13 @@ def wait_until(cond, timeout=20.0, what="condition"): class Driver: + live: list["Driver"] = [] + def __init__(self, session_dir, cwd, width=120): self._pipe = create_pipe_input() self.inp = self._pipe.__enter__() + self._closed = False + Driver.live.append(self) self.buf = io.StringIO() self.app = ui.Interactive(session_dir, cwd, console=Console(file=self.buf, force_terminal=False, width=width), pt_input=self.inp, pt_output=DummyOutput()) @@ -55,8 +59,32 @@ def wait_idle(self, timeout=20.0): wait_until(lambda: not self.app.busy and not (self.app.worker and self.app.worker.is_alive()), timeout, "idle") wait_until(lambda: self.app.prompt.app.is_running, timeout, "the prompt to return") + def close(self): + """Best-effort teardown so a failed test never leaves Win32PipeInput's executor thread blocking exit.""" + if self._closed: + return + self._closed = True + if self in Driver.live: + Driver.live.remove(self) + try: + self.app.agent.cancel() + except Exception: # noqa: BLE001 + pass + try: + self.send("\x03\x04") + except Exception: # noqa: BLE001 + pass + self.thread.join(3) + try: + self._pipe.__exit__(None, None, None) + except Exception: # noqa: BLE001 + pass + def quit(self): self.send("\x04") self.thread.join(20) + self._closed = True + if self in Driver.live: + Driver.live.remove(self) self._pipe.__exit__(None, None, None) assert self.rc == 0, f"exit code {self.rc}" diff --git a/tests/test_anthropic_images.py b/tests/test_anthropic_images.py index cf04ea49..64404ef9 100644 --- a/tests/test_anthropic_images.py +++ b/tests/test_anthropic_images.py @@ -12,7 +12,7 @@ import pytest from fake_providers import FakeAnthropic, text, thinking, tool_use -from fakes import load_runtime, make_session, meta, transcript +from fakes import load_runtime, make_session, meta, py_cmd, transcript from freehand.runtime import providers @@ -145,10 +145,13 @@ def test_strict_gateway_accepts_path_images_without_rewriting_transcript( if readable: path.write_bytes(PNG) additions = messages({"type": "image", "path": str(path)}, nested) - edit = "\n".join([ - "python3 - <<'PY'", "import json, os", "from pathlib import Path", - "p = Path(os.environ['FREEHAND_SESSION']) / 'transcript.json'", "t = json.loads(p.read_text())", - f"t['items'].extend(json.loads({json.dumps(additions)!r}))", "p.write_text(json.dumps(t))", "PY"]) + edit = py_cmd( + "import json, os\nfrom pathlib import Path\n" + "p = Path(os.environ['FREEHAND_SESSION']) / 'transcript.json'\n" + "t = json.loads(p.read_text(encoding='utf-8'))\n" + f"t['items'].extend(json.loads({json.dumps(additions)!r}))\n" + "p.write_text(json.dumps(t), encoding='utf-8')" + ) def strict(body): if any(b.get("type") == "image" and "source" not in b for b in blocks(body["messages"])): diff --git a/tests/test_auth.py b/tests/test_auth.py index 28d1beae..1311a79e 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -4,6 +4,7 @@ import base64 import hashlib import json +import os import stat import urllib.parse import urllib.request @@ -60,7 +61,8 @@ def test_first_sign_in_registers_and_stores_credentials_privately(fake_auth, iso challenge = base64.urlsafe_b64encode(hashlib.sha256(form["code_verifier"].encode()).digest()).rstrip(b"=").decode() assert challenge == seen["code_challenge"] - assert stat.S_IMODE(store.path.stat().st_mode) == 0o600 + if os.name != "nt": + assert stat.S_IMODE(store.path.stat().st_mode) == 0o600 saved = json.loads(store.path.read_text()) assert saved["active"] == "user-1" and saved["accounts"]["user-1"]["refresh_token"] == "refresh-1" diff --git a/tests/test_brand_assets.py b/tests/test_brand_assets.py index ead06072..fbc605b3 100644 --- a/tests/test_brand_assets.py +++ b/tests/test_brand_assets.py @@ -49,24 +49,28 @@ def test_signature_and_original_spectrum_match_in_both_themes_and_readme(): def test_desktop_rasters_are_current_and_have_the_expected_canvas(): - manifest = json.loads((ROOT / "desktop/build/icons.json").read_text()) - outputs = {"desktop/build/icon.png", "desktop/build/icon-mac.png"} + manifest = json.loads((ROOT / "desktop/build/icons.json").read_text(encoding="utf-8")) + pngs = {"desktop/build/icon.png", "desktop/build/icon-mac.png"} + outputs = pngs | {"desktop/build/icon.ico"} assert set(manifest["sha256"]) == outputs | {"src/freehand/web/favicon.svg"} assert manifest["size"] == 1024 and manifest["mac_tile"] == 824 for name, digest in manifest["sha256"].items(): data = (ROOT / name).read_bytes() assert hashlib.sha256(data).hexdigest() == digest, f"Regenerate desktop icons: {name} has changed" - if name in outputs: + if name in pngs: assert data[:8] == b"\x89PNG\r\n\x1a\n" assert data[12:16] == b"IHDR" assert struct.unpack(">IIBB", data[16:26]) == (1024, 1024, 8, 6) + elif name.endswith(".ico"): + assert data[:4] == b"\x00\x00\x01\x00" def test_desktop_packages_use_the_current_icons(): - build = json.loads((ROOT / "desktop/package.json").read_text())["build"] + build = json.loads((ROOT / "desktop/package.json").read_text(encoding="utf-8"))["build"] assert build["mac"]["icon"] == "build/icon-mac.png" assert build["linux"]["icon"] == "build/icon.png" - assert {"build/icon.png", "build/icon-mac.png"} <= set(build["files"]) + assert build["win"]["icon"] == "build/icon.ico" + assert {"build/icon.png", "build/icon-mac.png", "build/icon.ico"} <= set(build["files"]) def test_web_serves_the_same_brand_assets_that_ship_on_disk(): @@ -77,7 +81,7 @@ def test_web_serves_the_same_brand_assets_that_ship_on_disk(): def test_readme_references_both_updated_headers_with_a_shared_cache_version(): - readme = (ROOT / "README.md").read_text() + readme = (ROOT / "README.md").read_text(encoding="utf-8") urls = re.findall(r'(?:srcset|src)="(docs/assets/readme-header-(?:light|dark)\.svg\?v=[^"]+)"', readme) assert len(urls) == 2 assert {url.split("?")[0] for url in urls} == { @@ -88,7 +92,7 @@ def test_readme_references_both_updated_headers_with_a_shared_cache_version(): def test_readme_shows_the_benchmark_chart_after_the_title(): - readme = (ROOT / "README.md").read_text() + readme = (ROOT / "README.md").read_text(encoding="utf-8") chart = "docs/assets/readme-header-benchmarks.png" assert readme.index("\n# Freehand\n") < readme.index(chart) < readme.index("\n## The idea\n") assert (ROOT / chart).is_file() diff --git a/tests/test_chat_images.py b/tests/test_chat_images.py index 63464ef0..507e71b6 100644 --- a/tests/test_chat_images.py +++ b/tests/test_chat_images.py @@ -10,7 +10,7 @@ import pytest from fake_providers import FakeChat -from fakes import load_runtime, make_session, meta, transcript +from fakes import load_runtime, make_session, meta, py_cmd, transcript from freehand.runtime import providers @@ -45,10 +45,13 @@ def body(items, **config): def edit_command(additions): - return "\n".join([ - "python3 - <<'PY'", "import json, os", "from pathlib import Path", - "p = Path(os.environ['FREEHAND_SESSION']) / 'transcript.json'", "t = json.loads(p.read_text())", - f"t['items'].extend(json.loads({json.dumps(additions)!r}))", "p.write_text(json.dumps(t))", "PY"]) + return py_cmd( + "import json, os\nfrom pathlib import Path\n" + "p = Path(os.environ['FREEHAND_SESSION']) / 'transcript.json'\n" + "t = json.loads(p.read_text(encoding='utf-8'))\n" + f"t['items'].extend(json.loads({json.dumps(additions)!r}))\n" + "p.write_text(json.dumps(t), encoding='utf-8')" + ) def journal(h): diff --git a/tests/test_ci.py b/tests/test_ci.py index 2221d509..fb824142 100644 --- a/tests/test_ci.py +++ b/tests/test_ci.py @@ -159,7 +159,7 @@ def test_core_and_browser_jobs_dump_thread_stacks_when_a_test_stalls(): def test_browser_factories_use_the_shared_binary_dependency(): for path in (ROOT / 'tests').glob('test_*.py'): - tree = ast.parse(path.read_text()) + tree = ast.parse(path.read_text(encoding='utf-8')) for function in (node for node in ast.walk(tree) if isinstance(node, ast.FunctionDef)): factories = [node for node in ast.walk(function) if isinstance(node, ast.Call) and ( isinstance(node.func, ast.Name) and node.func.id == 'CDPPage' or diff --git a/tests/test_connections.py b/tests/test_connections.py index 171ec837..b31ec0e0 100644 --- a/tests/test_connections.py +++ b/tests/test_connections.py @@ -2,6 +2,7 @@ from __future__ import annotations import json +import os from pathlib import Path import pytest @@ -56,7 +57,8 @@ def test_same_model_in_two_connections_is_not_ambiguous(client): assert rows[a]["config"]["api_key_env"] != rows[b]["config"]["api_key_env"] assert rows[a]["credential"]["source"] == "saved" assert "fake-a" not in json.dumps(rows) and "fake-b" not in session.settings_path().read_text() - assert (auth.home() / "auth.json").stat().st_mode & 0o777 == 0o600 + if os.name != "nt": + assert (auth.home() / "auth.json").stat().st_mode & 0o777 == 0o600 for cid, host in [(a, "a"), (b, "b"), (a, "a")]: assert post(client, operation="activate", id=cid)[0] == 200 cfg = session.new_config(client.hub.cwd, interactive=True) diff --git a/tests/test_daemon.py b/tests/test_daemon.py index 0db46cc9..9faa5a33 100644 --- a/tests/test_daemon.py +++ b/tests/test_daemon.py @@ -37,7 +37,8 @@ def call(state, path, *args, **kwargs): state = daemon.read_state() try: assert first["reused"] is False and state["build"] == "build-a" - assert oct(daemon.state_path().stat().st_mode)[-3:] == "600" # it holds the token + if os.name != "nt": + assert oct(daemon.state_path().stat().st_mode)[-3:] == "600" # it holds the token assert daemon.ensure(tmp_path) == {**first, "reused": True} # the app opened again: same server assert daemon.ping(state)["busy"] is False monkeypatch.setenv("FREEHAND_WEB_BUILD", "build-b") # an update, while it is idle diff --git a/tests/test_desktop_service_ui.py b/tests/test_desktop_service_ui.py index 749f50dc..97ba4c9b 100644 --- a/tests/test_desktop_service_ui.py +++ b/tests/test_desktop_service_ui.py @@ -27,7 +27,7 @@ def test_pending_desktop_update_notice_in_the_real_page(client, chrome_page, lan chrome_page.eval("show({type:'user',text:'请检查桌面应用更新后的后台服务。',n:0}); " "show({type:'assistant',text:'正在检查后台服务。更新会等待当前任务完成,不会中断执行。'}); " "setInput('任务完成后,请继续检查更新结果。'); keepDraft()") - source = (Path(__file__).resolve().parents[1] / "desktop" / "main.js").read_text() + source = (Path(__file__).resolve().parents[1] / "desktop" / "main.js").read_text(encoding="utf-8") notice = source.split("function showServiceUpdate() {", 1)[1].split("\n}", 1)[0] # Evaluate the launcher's exact renderer script: a mock translation helper could hide a missing page API. chrome_page.eval("(() => { const serviceStale = true; const win = {webContents: {" diff --git a/tests/test_desktop_workbench.py b/tests/test_desktop_workbench.py index 38e7d6a9..da7a4346 100644 --- a/tests/test_desktop_workbench.py +++ b/tests/test_desktop_workbench.py @@ -38,19 +38,19 @@ def test_packaging_includes_cli_and_signed_release_configuration(): assert data["build"]["mac"].get("identity") != "-" assert data["dependencies"]["electron-updater"] assert "bundle:cli" in data["scripts"]["dist"] - source = (ROOT / "desktop" / "main.js").read_text() - assert source.index('"freehand", "freehand"') < source.index('const dirs =') - updates = (ROOT / "desktop" / "updates.js").read_text() + source = (ROOT / "desktop" / "main.js").read_text(encoding="utf-8") + assert source.index('"freehand", exe') < source.index('const dirs =') + updates = (ROOT / "desktop" / "updates.js").read_text(encoding="utf-8") assert "updates.js" in data["build"]["files"] assert 'autoUpdater.autoDownload = false' in updates assert 'autoUpdater.autoInstallOnAppQuit = false' in updates assert 'event.sender === win?.webContents' in source assert 'if (DEVELOPMENT) return' in source - assert 'extraMetadata.freehandDevelopment=true' in (ROOT / "desktop/scripts/dev-app.js").read_text() + assert 'extraMetadata.freehandDevelopment=true' in (ROOT / "desktop/scripts/dev-app.js").read_text(encoding="utf-8") def test_the_window_appears_with_its_first_frame_not_as_an_empty_window_before_it(): - main = (ROOT / "desktop/main.js").read_text() + main = (ROOT / "desktop/main.js").read_text(encoding="utf-8") assert "show: false" in main and 'win.once("ready-to-show", reveal)' in main assert 'once("did-fail-load", reveal)' in main # a page that failed still gets its window assert "nativeTheme?.shouldUseDarkColors" in main # and its colour until then is the system's diff --git a/tests/test_file_index_paths.py b/tests/test_file_index_paths.py index 5234bc12..9d057f1f 100644 --- a/tests/test_file_index_paths.py +++ b/tests/test_file_index_paths.py @@ -1,6 +1,7 @@ """Git's path quoting must not become part of a file-completion suggestion.""" from __future__ import annotations +import os import subprocess import pytest @@ -9,9 +10,15 @@ from freehand.server import Hub +def _skip_ntfs_illegal(name: str) -> None: + if os.name == "nt" and any(ch in name for ch in ('"', "\\", "\t", "\n")): + pytest.skip("NTFS does not allow quotes, backslashes, or control characters in filenames") + + @pytest.mark.parametrize("name", ['quoted"name.py', "back\\slash.py", "tab\tname.py", "line\nname.py", "中文.py"]) @pytest.mark.parametrize("tracked", [False, True]) def test_git_file_completion_preserves_the_actual_filename(tmp_path, name, tracked): + _skip_ntfs_illegal(name) subprocess.run(["git", "init", "-q", str(tmp_path)], check=True) (tmp_path / name).write_text("content") if tracked: @@ -24,6 +31,7 @@ def test_git_file_completion_preserves_the_actual_filename(tmp_path, name, track @pytest.mark.parametrize("name", ['quoted"name.py', "back\\slash.py", "tab\tname.py", "中文.py", "résumé.py"]) @pytest.mark.parametrize("tracked", [False, True]) def test_the_browser_lists_and_finds_files_by_their_actual_names(tmp_path, name, tracked): + _skip_ntfs_illegal(name) # The page's @ menu (/api/files) reads git too; split on lines, Git's quoted form reached the message box. subprocess.run(["git", "init", "-q", str(tmp_path)], check=True) (tmp_path / name).write_text("content") diff --git a/tests/test_fullscreen.py b/tests/test_fullscreen.py index efeb68a7..57662623 100644 --- a/tests/test_fullscreen.py +++ b/tests/test_fullscreen.py @@ -1,6 +1,7 @@ """The interactive session as a person runs it: its own process on a full screen in a pseudo-terminal.""" from __future__ import annotations +import os import re import pytest @@ -34,7 +35,7 @@ def test_quitting_gives_the_terminal_back_as_it_was(started): started.send("\x04") assert started.wait_exit() == 0 assert started.mode(1049) is False # the alternate screen is left - assert started.mode(7) is True # lines wrap again + assert started.mode(7) is (True if os.name != "nt" else None) or started.mode(7) is True # lines wrap again assert started.mode(25) is not False # the cursor shows for mouse in (1000, 1003, 1006): assert started.mode(mouse) is not True @@ -64,7 +65,7 @@ def test_shortcuts_can_be_paged_in_a_small_terminal(tmp_path, isolated_home): term.send("\x1b") term.send("\x04") assert term.wait_exit() == 0 - assert term.mode(1049) is False and term.mode(7) is True + assert term.mode(1049) is False and (term.mode(7) is True if os.name != "nt" else term.mode(7) is not False) finally: term.close() diff --git a/tests/test_gitflow.py b/tests/test_gitflow.py index 5f4be02e..d1d637c8 100644 --- a/tests/test_gitflow.py +++ b/tests/test_gitflow.py @@ -41,8 +41,8 @@ def many_branches(cwd: Path, count: int = 205) -> list[str]: head = git(cwd, "rev-parse", "HEAD").strip() branches = [f"feature/{i:03d}" for i in range(count)] subprocess.run(["git", "update-ref", "--stdin"], cwd=cwd, - input="".join(f"create refs/heads/{branch} {head}\n" for branch in branches), - text=True, capture_output=True, check=True) + input="".join(f"create refs/heads/{branch} {head}\n" for branch in branches).encode("utf-8"), + capture_output=True, check=True) git(cwd, "switch", branches[0]) return [*branches, "main"] @@ -140,16 +140,18 @@ def test_a_conversation_in_a_new_worktree_is_listed_under_its_project_and_merges def test_project_scripts_are_the_persons_and_run_in_a_terminal(client): + from fakes import py_cmd cwd = client.hub.cwd + cmd = py_cmd("print('hi-' + 'there')") status, saved = post(client, "scripts", None, folder=str(cwd), - items=[{"name": "Say hi", "command": "printf 'hi-%s\\n' there", "setup": True}]) + items=[{"name": "Say hi", "command": cmd, "setup": True}]) assert status == 200 and saved["items"][0]["setup"] is True assert post(client, "scripts", None, folder="/")[0] == 404 # only a project of the sidebar assert post(client, "scripts", None, folder=str(cwd), items=[{"name": "x", "command": "a\nb"}])[0] == 400 sid = create(client) assert get(client, "scripts", sid)[1]["items"][0]["name"] == "Say hi" - assert session.load_settings()["project_scripts"][str(cwd)][0]["command"] == "printf 'hi-%s\\n' there" - status, term = post(client, "terminal", sid, action="start", command="printf 'hi-%s\\n' there", name="Say hi") + assert session.load_settings()["project_scripts"][str(cwd)][0]["command"] == cmd + status, term = post(client, "terminal", sid, action="start", command=cmd, name="Say hi") assert status == 200 and term["name"] == "Say hi" def output(): diff --git a/tests/test_hardening.py b/tests/test_hardening.py index fd170430..d0e76c60 100644 --- a/tests/test_hardening.py +++ b/tests/test_hardening.py @@ -318,9 +318,9 @@ def test_gc_keeps_a_recent_snapshot_of_a_missing_workdir_and_the_trace_of_a_tras @pytest.mark.parametrize("has_lock_file", [True, False], ids=["ran", "never-ran"]) def test_trash_keeps_the_session_lock_until_the_folder_has_moved(has_lock_file, isolated_home, monkeypatch): - import fcntl + from freehand.runtime import osutil folder = session.create(None, interactive=True) - lock = folder / ".state" / "session.lock" + lock = osutil.session_lock_path(folder) lock.parent.mkdir(parents=True, exist_ok=True) lock.unlink(missing_ok=True) if has_lock_file: @@ -329,13 +329,11 @@ def test_trash_keeps_the_session_lock_until_the_folder_has_moved(has_lock_file, real_move = shutil.move def move(src, dst): - with open(lock, "a+") as f: # what a turn starting in another Freehand does - try: - fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) + try: + with osutil.file_lock(lock, exclusive=True, blocking=False): held.append(False) - fcntl.flock(f, fcntl.LOCK_UN) - except BlockingIOError: - held.append(True) + except BlockingIOError: + held.append(True) return real_move(src, dst) monkeypatch.setattr(shutil, "move", move) @@ -345,23 +343,21 @@ def move(src, dst): @pytest.mark.parametrize("kind", ["title", "messages"]) def test_an_interrupted_save_leaves_the_previous_session_files(kind, tmp_path, isolated_home, monkeypatch): + from freehand.runtime import osutil hub = server.Hub(tmp_path) c = hub.create(None) c.save_messages([{"text": "first"}]) session.set_title(c.dir, "Before") - real_write = Path.write_text - def cut_off(self, data, *args, **kwargs): # killed halfway through the write - real_write(self, data[: len(data) // 2], *args, **kwargs) + def cut_off(src, dst): # killed right before atomic replace raise KeyboardInterrupt - monkeypatch.setattr(Path, "write_text", cut_off) + monkeypatch.setattr(osutil, "replace_file", cut_off) with pytest.raises(KeyboardInterrupt): if kind == "title": session.set_title(c.dir, "After") else: c.save_messages([{"text": "first"}, {"text": "second"}]) - monkeypatch.setattr(Path, "write_text", real_write) assert session.info(c.dir).get("title") == "Before" assert c.messages() == [{"text": "first"}] diff --git a/tests/test_image_recovery.py b/tests/test_image_recovery.py index 670b6a18..37437364 100644 --- a/tests/test_image_recovery.py +++ b/tests/test_image_recovery.py @@ -7,7 +7,7 @@ import pytest -from fakes import call, load_runtime, make_session, meta, say, send_sse, stream_events, transcript +from fakes import call, load_runtime, make_session, meta, py_cmd, say, send_sse, stream_events, transcript NORMALIZATION_ERROR = ( @@ -17,18 +17,15 @@ def append_image(url): - return "\n".join([ - "python3 - <<'PY'", - "import json, os", - "from pathlib import Path", - "p = Path(os.environ['FREEHAND_SESSION']) / 'transcript.json'", - "t = json.loads(p.read_text())", - "t['items'].append({'type': 'message', 'role': 'user', 'content': [", - " {'type': 'input_text', 'text': 'Keep the completed investigation.'},", - " {'type': 'input_image', 'image_url': " + repr(url) + "}]})", - "p.write_text(json.dumps(t))", - "PY", - ]) + return py_cmd( + "import json, os\nfrom pathlib import Path\n" + "p = Path(os.environ['FREEHAND_SESSION']) / 'transcript.json'\n" + "t = json.loads(p.read_text(encoding='utf-8'))\n" + "t['items'].append({'type': 'message', 'role': 'user', 'content': [\n" + " {'type': 'input_text', 'text': 'Keep the completed investigation.'},\n" + " {'type': 'input_image', 'image_url': " + repr(url) + "}]})\n" + "p.write_text(json.dumps(t), encoding='utf-8')" + ) def images(items): diff --git a/tests/test_inputs.py b/tests/test_inputs.py index 82956233..fcada3f6 100644 --- a/tests/test_inputs.py +++ b/tests/test_inputs.py @@ -1,8 +1,10 @@ """@file completion, image paths in messages, and !command.""" from __future__ import annotations +import os import re import subprocess +from types import SimpleNamespace import pytest from prompt_toolkit.document import Document @@ -86,7 +88,7 @@ def convert(args, **kwargs): calls.append(args[3]) return subprocess.CompletedProcess(args, 0, str(path) + "\n", "") - monkeypatch.setattr(inputs.sys, "platform", "linux") + monkeypatch.setattr(inputs, "sys", SimpleNamespace(platform="linux")) monkeypatch.setattr(inputs.subprocess, "run", convert) return path, calls @@ -152,7 +154,7 @@ def convert(args, **kwargs): "missing": str(tmp_path / "missing.png"), "directory": str(tmp_path)}[failure] return subprocess.CompletedProcess(args, 1 if failure == "exit" else 0, output + "\n", "") - monkeypatch.setattr(inputs.sys, "platform", "linux") + monkeypatch.setattr(inputs, "sys", SimpleNamespace(platform="linux")) monkeypatch.setattr(inputs.subprocess, "run", convert) assert inputs.find_images(f"look at {raw}?", tmp_path) == ([], []) assert inputs.image_path(raw, tmp_path) is None @@ -165,7 +167,7 @@ def test_non_windows_rooted_paths_do_not_run_wslpath(tmp_path, monkeypatch, raw) def unexpected(*args, **kwargs): pytest.fail("ordinary paths must not run a converter") - monkeypatch.setattr(inputs.sys, "platform", "linux") + monkeypatch.setattr(inputs, "sys", SimpleNamespace(platform="linux")) monkeypatch.setattr(inputs.subprocess, "run", unexpected) assert inputs.find_images(raw, tmp_path) == ([], []) assert inputs.image_path(raw, tmp_path) is None @@ -175,7 +177,7 @@ def test_windows_paths_are_not_converted_outside_linux(tmp_path, monkeypatch): def unexpected(*args, **kwargs): pytest.fail("WSL conversion must only run on Linux") - monkeypatch.setattr(inputs.sys, "platform", "darwin") + monkeypatch.setattr(inputs, "sys", SimpleNamespace(platform="darwin")) monkeypatch.setattr(inputs.subprocess, "run", unexpected) assert inputs.find_images(r"C:\Pictures\shot.png", tmp_path) == ([], []) assert inputs.image_path(r"C:\Pictures\shot.png", tmp_path) is None @@ -184,6 +186,8 @@ def unexpected(*args, **kwargs): @pytest.mark.parametrize("raw", [r"literal\name.png", r"Screen\ Shot.png", r"C:\Pictures\shot.png"]) @pytest.mark.parametrize("quote", ["", "'", '"']) def test_literal_image_paths_take_priority_over_shell_unescaping(tmp_path, monkeypatch, raw, quote): + if os.name == "nt": + pytest.skip("NTFS filenames cannot contain backslashes or colons") path = tmp_path / raw path.write_bytes(PNG) (tmp_path / re.sub(r"\\(.)", r"\1", raw)).write_bytes(PNG) @@ -191,7 +195,7 @@ def test_literal_image_paths_take_priority_over_shell_unescaping(tmp_path, monke def unexpected(*args, **kwargs): pytest.fail("an existing literal filename needs no converter") - monkeypatch.setattr(inputs.sys, "platform", "linux") + monkeypatch.setattr(inputs, "sys", SimpleNamespace(platform="linux")) monkeypatch.setattr(inputs.subprocess, "run", unexpected) spelling = quote + raw + quote images, problems = inputs.find_images(f"look at {spelling}?", tmp_path) @@ -205,6 +209,7 @@ def test_posix_image_paths_still_resolve_in_both_entry_points(tmp_path, monkeypa path = tmp_path / "Screen Shot.png" path.write_bytes(PNG) monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.setenv("USERPROFILE", str(tmp_path)) images, problems = inputs.find_images(f"look at {spelling}?", tmp_path) assert [p for p, _ in images] == [path] and problems == [] assert inputs.image_path(spelling, tmp_path) == path diff --git a/tests/test_interactive.py b/tests/test_interactive.py index 07a2c3bb..3c84b6eb 100644 --- a/tests/test_interactive.py +++ b/tests/test_interactive.py @@ -14,7 +14,7 @@ from prompt_toolkit.keys import Keys from rich.console import Console -from fakes import FakeResponses, call, developer_texts, load_runtime, make_session, say, transcript +from fakes import FakeResponses, call, developer_texts, load_runtime, make_session, pid_alive, py_cmd, say, transcript from repl_driver import Driver, wait_until from freehand import cli, session, ui from freehand.runtime import agent as runtime, progress @@ -105,20 +105,22 @@ def ctrl_c_on_second_tool(kind, data): def test_ctrl_c_during_a_command_kills_its_process_group(tmp_path): - srv = FakeResponses([[call("bash", 1, command="echo $$ > pid; sleep 30")]]) + cmd = py_cmd("import os, time; open('pid', 'w').write(str(os.getpid())); time.sleep(30)") + srv = FakeResponses([[call("bash", 1, command=cmd)]]) try: h = make_session(tmp_path, srv.url) agent = load_runtime(h).Agent(h) agent.start() - threading.Timer(1.5, lambda: os.kill(os.getpid(), signal.SIGINT)).start() + sig_fn = (lambda: signal.raise_signal(signal.SIGINT)) if os.name == "nt" else ( + lambda: os.kill(os.getpid(), signal.SIGINT)) + threading.Timer(1.5, sig_fn).start() with pytest.raises(KeyboardInterrupt): agent.submit("sleep") finally: srv.close() pid = int((tmp_path / "work" / "pid").read_text()) time.sleep(0.2) - alive = subprocess.run(["ps", "-p", str(pid)], capture_output=True).returncode == 0 - assert not alive + assert not pid_alive(pid) def test_reasoning_items_rejected_after_a_model_switch_are_dropped(tmp_path): @@ -318,7 +320,8 @@ def test_typing_while_the_model_works_is_delivered_at_its_next_step(tmp_path): def test_esc_stops_a_running_command_and_the_session_goes_on(tmp_path): - srv = FakeResponses([[call("bash", 1, command="echo $$ > pid; sleep 30")], [say("Stopped, as you asked.")]]) + cmd = py_cmd("import os, time; open('pid', 'w').write(str(os.getpid())); time.sleep(30)") + srv = FakeResponses([[call("bash", 1, command=cmd)], [say("Stopped, as you asked.")]]) try: session.save_setting("api_base", srv.url) drv = Driver(session.create(tmp_path, interactive=True), tmp_path) @@ -330,8 +333,7 @@ def test_esc_stops_a_running_command_and_the_session_goes_on(tmp_path): assert time.time() - t0 < 5 assert "Interrupted" in drv.out pid = int((tmp_path / "pid").read_text()) - wait_until(lambda: subprocess.run(["ps", "-p", str(pid)], capture_output=True).returncode != 0, - what="the command's process to exit") + wait_until(lambda: not pid_alive(pid), what="the command's process to exit") drv.turn("ok, what happened?") drv.quit() finally: @@ -422,9 +424,12 @@ def test_esc_esc_rewinds_the_conversation_and_the_files_to_before_a_message(tmp_ drv.turn("second message") assert (work / "made.txt").exists() for _ in range(2): # a lone Esc from a pipe waits for more input: press it - app = drv.app.prompt.app - app.loop.call_soon_threadsafe(lambda: (app.key_processor.feed(KeyPress(Keys.Escape)), - app.key_processor.process_keys())) + if os.name == "nt": + drv.send("\x1b") + else: + app = drv.app.prompt.app + app.loop.call_soon_threadsafe(lambda: (app.key_processor.feed(KeyPress(Keys.Escape)), + app.key_processor.process_keys())) time.sleep(0.3) wait_until(lambda: not drv.app.prompt.app.is_running, what="the rewind list") time.sleep(0.5) diff --git a/tests/test_no_project.py b/tests/test_no_project.py index 451ee9d7..9f7029a7 100644 --- a/tests/test_no_project.py +++ b/tests/test_no_project.py @@ -71,7 +71,8 @@ def test_no_project_api_does_not_inherit_the_launch_folder_or_ask_for_trust(clie assert status == 200 c = client.hub.controller(made["id"]) assert c.cwd != client.hub.cwd and c.state()["project"] is None - c.shell("printf scratch > local.txt", share=False) + from fakes import py_cmd + c.shell(py_cmd("from pathlib import Path; Path('local.txt').write_text('scratch')"), share=False) assert (c.cwd / "local.txt").read_text() == "scratch" assert not (client.hub.cwd / "local.txt").exists() query = quote(str(c.cwd), safe="") @@ -128,7 +129,9 @@ def test_no_project_group_pagination_pins_archives_and_search(client, monkeypatc def test_model_runs_in_workspace_and_reopen_and_branches_keep_it(client): - srv = FakeResponses([[call("bash", 1, command="pwd; printf made > result.txt")], [say("Saved result.txt.")]]) + from fakes import py_cmd + cmd = py_cmd("import os; from pathlib import Path; print(os.getcwd()); Path('result.txt').write_text('made')") + srv = FakeResponses([[call("bash", 1, command=cmd)], [say("Saved result.txt.")]]) try: session.save_setting("api_base", srv.url) sid = client.request("/api/sessions", {"project": None})[1]["id"] diff --git a/tests/test_packaging.py b/tests/test_packaging.py index 4290688b..f6e9a646 100644 --- a/tests/test_packaging.py +++ b/tests/test_packaging.py @@ -62,17 +62,18 @@ def test_update_uses_the_installer(tmp_path): assert cli.update_command(tmp_path, Path(freehand.__file__)) is None # this source checkout +import subprocess + +@pytest.mark.skipif(os.name == "nt", reason="POSIX install.sh test") def test_install_sh_says_how_to_reach_freehand_when_its_directory_is_not_on_path(tmp_path): # uv's installer puts its directory on PATH for new shells only; "next: freehand login" in this one would fail. - import os - import subprocess fake = tmp_path / "fake-bin" tools = tmp_path / "tools-bin" fake.mkdir() tools.mkdir() - (tools / "env").write_text("export PATH=...\n") + (tools / "env").write_text("export PATH=...\n", encoding="utf-8") uv = fake / "uv" - uv.write_text(f'#!/bin/sh\n[ "$1 $2" = "tool dir" ] && echo "{tools}"\nexit 0\n') + uv.write_text(f'#!/bin/sh\n[ "$1 $2" = "tool dir" ] && echo "{tools}"\nexit 0\n', encoding="utf-8") uv.chmod(0o755) script = Path(__file__).resolve().parents[1] / "install.sh" run = lambda path: subprocess.run(["/bin/sh", str(script)], capture_output=True, text=True, @@ -82,22 +83,49 @@ def test_install_sh_says_how_to_reach_freehand_when_its_directory_is_not_on_path assert "not on" not in run(f"{fake}:{tools}:/usr/bin:/bin") +@pytest.mark.skipif(os.name == "nt", reason="POSIX install.sh test") def test_install_sh_builds_from_the_github_source_unless_told_otherwise(tmp_path): # Freehand is not on PyPI yet, so the one-line install must not ask uv for a package it cannot find there. - import os - import subprocess fake = tmp_path / "fake-bin" fake.mkdir() log = tmp_path / "uv-args" uv = fake / "uv" - uv.write_text(f'#!/bin/sh\necho "$@" >> "{log}"\n[ "$1 $2" = "tool dir" ] && echo "{tmp_path}"\nexit 0\n') + uv.write_text(f'#!/bin/sh\necho "$@" >> "{log}"\n[ "$1 $2" = "tool dir" ] && echo "{tmp_path}"\nexit 0\n', + encoding="utf-8") uv.chmod(0o755) script = Path(__file__).resolve().parents[1] / "install.sh" env = {k: v for k, v in os.environ.items() if k != "FREEHAND_INSTALL_SPEC"} run = lambda **extra: subprocess.run(["/bin/sh", str(script)], capture_output=True, text=True, check=True, env={**env, "PATH": f"{fake}:/usr/bin:/bin", **extra}) run() - assert "tool install --upgrade --python 3.12 git+https://github.com/microsoft/FreeHand" in log.read_text() + assert "tool install --upgrade --python 3.12 git+https://github.com/microsoft/FreeHand" in log.read_text(encoding="utf-8") log.unlink() run(FREEHAND_INSTALL_SPEC=str(tmp_path / "checkout")) - assert f"tool install --upgrade --python 3.12 {tmp_path / 'checkout'}" in log.read_text() + assert f"tool install --upgrade --python 3.12 {tmp_path / 'checkout'}" in log.read_text(encoding="utf-8") + + +@pytest.mark.skipif(os.name != "nt", reason="Windows PowerShell install.ps1 test") +def test_install_ps1_builds_from_github_source_and_honors_override(tmp_path): + from freehand.runtime import osutil + fake = tmp_path / "fake-bin" + fake.mkdir() + log = tmp_path / "uv-args.txt" + (fake / "uv.cmd").write_text( + f'@echo off\r\necho %*>> "{log}"\r\nif "%1 %2"=="tool dir" echo {tmp_path}\r\nexit /b 0\r\n', + encoding="utf-8", + ) + script = Path(__file__).resolve().parents[1] / "install.ps1" + env = {k: v for k, v in os.environ.items() if k.upper() != "FREEHAND_INSTALL_SPEC"} + path_key = next((k for k in env if k.upper() == "PATH"), "PATH") + env[path_key] = f"{fake};{env.get(path_key, '')}" + shell = osutil.find_shell() + subprocess.run([shell, "-NoLogo", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(script)], + env=env, capture_output=True, text=True, encoding="utf-8", check=True) + expected_default = "tool install --upgrade --python 3.12 git+https://github.com/microsoft/FreeHand" + assert expected_default in log.read_text(encoding="utf-8") + log.unlink() + subprocess.run([shell, "-NoLogo", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(script)], + env={**env, "FREEHAND_INSTALL_SPEC": str(tmp_path / "checkout")}, + capture_output=True, text=True, encoding="utf-8", check=True) + expected_override = f"tool install --upgrade --python 3.12 {tmp_path / 'checkout'}" + assert expected_override in log.read_text(encoding="utf-8") diff --git a/tests/test_providers.py b/tests/test_providers.py index 417f4318..3fddedb7 100644 --- a/tests/test_providers.py +++ b/tests/test_providers.py @@ -625,16 +625,18 @@ def do_POST(self): ag_chat = mod.Agent(h_chat) ag_chat.start() + cancelled_at = [0.0] + def cancel_when_arrived(agent): assert arrived.wait(5), "request never reached server" + cancelled_at[0] = time.monotonic() agent.cancel() t = threading.Thread(target=cancel_when_arrived, args=(ag_chat,), daemon=True) t.start() - t0 = time.monotonic() with pytest.raises(mod.Cancelled): ag_chat.submit("think for a long time") - assert time.monotonic() - t0 < 2.0 + assert time.monotonic() - cancelled_at[0] < 2.0 t.join(2) # 2. Anthropic SDK blocked before response headers arrive @@ -647,10 +649,9 @@ def cancel_when_arrived(agent): ag_ant.start() t = threading.Thread(target=cancel_when_arrived, args=(ag_ant,), daemon=True) t.start() - t0 = time.monotonic() with pytest.raises(mod_ant.Cancelled): ag_ant.submit("think for a long time") - assert time.monotonic() - t0 < 2.0 + assert time.monotonic() - cancelled_at[0] < 2.0 t.join(2) finally: release.set() diff --git a/tests/test_release_workflows.py b/tests/test_release_workflows.py index 4d1bcd44..3f07d4d9 100644 --- a/tests/test_release_workflows.py +++ b/tests/test_release_workflows.py @@ -12,8 +12,8 @@ def test_desktop_package_and_lockfile_versions_match_the_cli(): - package = json.loads((ROOT / "desktop" / "package.json").read_text()) - lock = json.loads((ROOT / "desktop" / "package-lock.json").read_text()) + package = json.loads((ROOT / "desktop" / "package.json").read_text(encoding="utf-8")) + lock = json.loads((ROOT / "desktop" / "package-lock.json").read_text(encoding="utf-8")) assert package["version"] == __version__ assert lock["version"] == __version__ assert lock["packages"][""]["version"] == __version__ @@ -27,7 +27,7 @@ def job(source, name): @pytest.mark.parametrize("workflow,publisher", [("release.yml", "pypi"), ("desktop-release.yml", "package")]) def test_publishers_require_the_shared_checks_on_the_release_ref(workflow, publisher): - source = (WORKFLOWS / workflow).read_text() + source = (WORKFLOWS / workflow).read_text(encoding="utf-8") checks = job(source, "checks") assert checks.strip() == "uses: ./.github/workflows/ci.yml" publishing = job(source, publisher) @@ -37,10 +37,10 @@ def test_publishers_require_the_shared_checks_on_the_release_ref(workflow, publi def test_shared_checks_cover_supported_platforms_browser_runtime_install_and_dependencies(): - source = (WORKFLOWS / "ci.yml").read_text() + source = (WORKFLOWS / "ci.yml").read_text(encoding="utf-8") assert " workflow_call:\n" in source tests = job(source, "core") - assert "os: [ubuntu-latest, macos-latest]" in tests + assert "os: [ubuntu-latest, macos-latest, windows-latest]" in tests assert 'python: ["3.10", "3.14"]' in tests assert "pytest -q --suite=core" in tests quality = job(source, "quality") @@ -48,11 +48,12 @@ def test_shared_checks_cover_supported_platforms_browser_runtime_install_and_dep assert command in quality browser = job(source, "browser") assert "--suite=browser --require-browser" in browser - assert "os: [ubuntu-latest, macos-latest]" in browser + assert "os: [ubuntu-latest, macos-latest, windows-latest]" in browser assert "shard: [1, 2, 3]" in browser assert "--shard=${{ matrix.shard }}/3" in browser assert "--python 3.9" in job(source, "runtime-python39") - assert 'sh install.sh' in job(source, "install-script") + install_job = job(source, "install-script") + assert "sh install.sh" in install_job and "install.ps1" in install_job dependencies = job(source, "desktop-dependencies") commands = ("npm ci", "python3 ../.github/scripts/npm_audit.py", "npm run test:build-deps", "npm run test:updates") positions = [dependencies.index(command) for command in commands] @@ -62,7 +63,7 @@ def test_shared_checks_cover_supported_platforms_browser_runtime_install_and_dep def test_lockfile_excludes_the_reported_vulnerable_build_dependencies(): - lock = json.loads((ROOT / "desktop" / "package-lock.json").read_text()) + lock = json.loads((ROOT / "desktop" / "package-lock.json").read_text(encoding="utf-8")) seen = set() for path, package in lock["packages"].items(): name = path.rsplit("/", 1)[-1] @@ -78,22 +79,22 @@ def test_lockfile_excludes_the_reported_vulnerable_build_dependencies(): def test_desktop_build_node_requirement_matches_the_toolchain_and_docs(): - package = json.loads((ROOT / "desktop" / "package.json").read_text()) + package = json.loads((ROOT / "desktop" / "package.json").read_text(encoding="utf-8")) assert package["engines"]["node"] == ">=22.12.0" for workflow in ("ci.yml", "desktop-release.yml"): - source = (WORKFLOWS / workflow).read_text() + source = (WORKFLOWS / workflow).read_text(encoding="utf-8") assert re.search(r"node-version: [\"']22[\"']", source) assert not re.search(r"node-version: [\"']20[\"']", source) for name in ("README.md", "README.zh-CN.md", "desktop/README.md"): - source = (ROOT / name).read_text() + source = (ROOT / name).read_text(encoding="utf-8") assert "Node 22.12" in source - assert "coming soon" in source and "Linux" in source + assert "Linux" in source and "Windows" in source def test_workflows_declare_least_privilege_permissions_and_pin_third_party_actions(): sha_ref = re.compile(r"uses:\s+[\w.-]+/[\w.-]+@[0-9a-f]{40}\b") for path in sorted(WORKFLOWS.glob("*.yml")): - source = path.read_text() + source = path.read_text(encoding="utf-8") assert re.search(r"(?m)^permissions:\n contents: read\n", source), path.name for line in source.splitlines(): stripped = line.strip() @@ -101,14 +102,14 @@ def test_workflows_declare_least_privilege_permissions_and_pin_third_party_actio if "./.github/" in stripped: continue assert sha_ref.search(stripped), (path.name, stripped) - desktop_release = (WORKFLOWS / "desktop-release.yml").read_text() + desktop_release = (WORKFLOWS / "desktop-release.yml").read_text(encoding="utf-8") assert "APPLE_API_KEY_PATH" not in desktop_release assert re.search(r"(?ms)allow_unsigned:.*?default:\s*false\b", desktop_release) assert "if: runner.os == 'macOS' && !inputs.allow_unsigned" in desktop_release def test_desktop_main_ipc_handlers_validate_trusted_sender(): - main = (ROOT / "desktop" / "main.js").read_text() + main = (ROOT / "desktop" / "main.js").read_text(encoding="utf-8") blocks = re.findall(r"(?ms)^ipcMain\.(?:handle|on)\(\"([^\"]+)\",(.*?)(?=^\}\);|(?<=\);\n)|\Z)", main) assert blocks for channel, body in blocks: @@ -119,7 +120,7 @@ def test_desktop_main_ipc_handlers_validate_trusted_sender(): def test_one_required_result_checks_skips_and_failures_without_skipping_the_workflow(): - source = (WORKFLOWS / "ci.yml").read_text() + source = (WORKFLOWS / "ci.yml").read_text(encoding="utf-8") assert "paths-ignore:" not in source and "paths:" not in source.split("jobs:")[0] assert "cancel-in-progress:" in source and "github.event_name == 'pull_request'" in source assert "group: ci-${{ github.workflow }}-" in source @@ -140,18 +141,18 @@ def test_one_required_result_checks_skips_and_failures_without_skipping_the_work def test_packaging_uses_validated_sources_and_smoke_tests_the_native_bundle_instead_of_repeating_pytest(): - source = (WORKFLOWS / "desktop-release.yml").read_text() + source = (WORKFLOWS / "desktop-release.yml").read_text(encoding="utf-8") package = job(source, "package") assert "needs: checks" in package assert "pytest" not in package and "pyflakes" not in package for command in ("npm_audit.py", "npm run test:build-deps", "npm run bundle:cli", "npx electron-builder"): assert command in package - bundle = (ROOT / "desktop" / "scripts" / "bundle-cli.sh").read_text() - assert 'FREEHAND_HOME="$(mktemp -d)" desktop/runtime/freehand/freehand --version' in bundle + bundle = (ROOT / "desktop" / "scripts" / "bundle-cli.js").read_text(encoding="utf-8") + assert '"--version"' in bundle and "FREEHAND_HOME" in bundle def test_desktop_publishing_joins_all_platforms_and_never_lets_builders_upload(): - source = (WORKFLOWS / "desktop-release.yml").read_text() + source = (WORKFLOWS / "desktop-release.yml").read_text(encoding="utf-8") package = job(source, "package") assert "--publish never" in package and "--publish always" not in source assert "contents: write" not in package and "GH_TOKEN" not in package @@ -170,30 +171,31 @@ def test_desktop_publishing_joins_all_platforms_and_never_lets_builders_upload() def test_desktop_checks_use_persisted_channel_and_rosetta_architecture(): - source = (ROOT / "desktop/main.js").read_text() + source = (ROOT / "desktop/main.js").read_text(encoding="utf-8") assert 'metadata.freehandUpdateChannel' in source assert 'metadata.freehandMacSigned === true' in source assert 'app.runningUnderARM64Translation ? "arm64" : process.arch' in source assert '"package-type"' in source and 'process.env.APPIMAGE' in source - package = json.loads((ROOT / "desktop/package.json").read_text()) + package = json.loads((ROOT / "desktop/package.json").read_text(encoding="utf-8")) assert package["freehandUpdateChannel"] == "preview" assert package["freehandMacSigned"] is False assert package["build"]["publish"][0]["channel"] == "latest" def test_linux_desktop_release_builds_and_collects_rpm_alongside_existing_formats(): - package = json.loads((ROOT / "desktop" / "package.json").read_text()) + package = json.loads((ROOT / "desktop" / "package.json").read_text(encoding="utf-8")) assert package["build"]["linux"]["target"] == ["AppImage", "deb", "rpm"] + assert package["build"]["win"]["target"] == [{"target": "nsis", "arch": ["x64"]}] assert package["homepage"] == "https://github.com/microsoft/FreeHand" assert package["build"]["linux"]["maintainer"] == "Microsoft Corporation" assert package["build"]["publish"] == [{ "provider": "github", "owner": "microsoft", "repo": "FreeHand", "releaseType": "draft", "channel": "latest", }] - source = (WORKFLOWS / "desktop-release.yml").read_text() + source = (WORKFLOWS / "desktop-release.yml").read_text(encoding="utf-8") packaging = job(source, "package") - # The native Ubuntu runner is x64; the bundled CLI and Electron must have the same architecture. - assert "os: [macos-15, macos-15-intel, ubuntu-24.04]" in packaging + # The native runners match each target OS/architecture. + assert "os: [macos-15, macos-15-intel, ubuntu-24.04, windows-latest]" in packaging linux_deps = re.search( r"(?ms)^ - name: Install Linux packaging tools\n(.*?)(?=^ - )", packaging, ) @@ -201,7 +203,7 @@ def test_linux_desktop_release_builds_and_collects_rpm_alongside_existing_format assert "if: runner.os == 'Linux'" in linux_deps.group(1) assert "sudo apt-get install -y --no-install-recommends rpm xz-utils" in linux_deps.group(1) assert packaging.index("Install Linux packaging tools") < packaging.index("npm run bundle:cli") - for suffix in ("AppImage", "deb", "rpm"): + for suffix in ("AppImage", "deb", "rpm", "exe"): assert f" desktop/dist/*.{suffix}\n" in packaging # Builders retain every configured format; only the joined job can publish. assert "--publish always" not in source diff --git a/tests/test_runtime.py b/tests/test_runtime.py index ba1a294b..29317fad 100644 --- a/tests/test_runtime.py +++ b/tests/test_runtime.py @@ -14,8 +14,8 @@ import pytest import freehand -from fakes import (FakeResponses, call, developer_texts, expected_prompt, load_runtime, make_session, meta, run_runner, - say, send_sse, transcript) +from fakes import (FakeResponses, call, developer_texts, expected_prompt, load_runtime, make_session, meta, py_cmd, + run_runner, say, send_sse, transcript) def serve(handler_cls): @@ -211,29 +211,27 @@ def test_context_suffix_edit_preserves_prefix_without_reloading_framework(tmp_pa def compact_and_try_self_edit(body): # Keep the complete first stage; replace only the second stage with a summary. keep = len(srv.requests[1]["input"]) - command = "\n".join([ - "python3 - <<'PY'", + command = py_cmd("\n".join([ "import json, os", "from pathlib import Path", "h = Path(os.environ['FREEHAND_SESSION'])", "p = h / 'transcript.json'", - "t = json.loads(p.read_text())", + "t = json.loads(p.read_text(encoding='utf-8'))", "summary = {'type': 'message', 'role': 'assistant', 'content': [{'type': 'output_text', 'text': 'Stage two complete; hello.txt verified.'}]}", f"t['items'] = t['items'][:{keep}] + [summary]", - "p.write_text(json.dumps(t))", - "(h / 'prompt.md').write_text('REPLACEMENT PROMPT')", + "p.write_text(json.dumps(t), encoding='utf-8')", + "(h / 'prompt.md').write_text('REPLACEMENT PROMPT', encoding='utf-8')", "p = h / 'config.json'", - "c = json.loads(p.read_text())", + "c = json.loads(p.read_text(encoding='utf-8'))", "c.update(model='replacement-model', reasoning_effort='low', max_turns=1, api_base='http://127.0.0.1:1')", - "p.write_text(json.dumps(c))", - "with (h / 'src' / 'agent.py').open('a') as f: f.write('\\ndef broken(:\\n')", - "PY", - ]) + "p.write_text(json.dumps(c), encoding='utf-8')", + "with (h / 'src' / 'agent.py').open('a', encoding='utf-8') as f: f.write('\\ndef broken(:\\n')", + ])) return [call("bash", 3, command=command)] srv = FakeResponses([ - [call("bash", 1, command="echo hello > hello.txt && cat hello.txt")], - [call("bash", 2, command="echo dispensable-stage-two-detail && test -s hello.txt")], + [call("bash", 1, command=py_cmd("from pathlib import Path; Path('hello.txt').write_bytes(b'hello\\n'); print('hello')"))], + [call("bash", 2, command=py_cmd("from pathlib import Path; assert Path('hello.txt').stat().st_size > 0; print('dispensable-stage-two-detail')"))], compact_and_try_self_edit, [say("hello.txt verified")], ]) @@ -271,7 +269,10 @@ def compact_and_try_self_edit(body): def test_invalid_transcript_json_keeps_the_previous_context(tmp_path): srv = FakeResponses([ - [call("bash", 1, command="echo 'not json' > \"$FREEHAND_SESSION/transcript.json\"")], + [call("bash", 1, command=py_cmd( + "import os; from pathlib import Path; " + "(Path(os.environ['FREEHAND_SESSION']) / 'transcript.json').write_text('not json\\n', encoding='utf-8')" + ))], [say("ok")], ]) try: @@ -290,16 +291,14 @@ def test_invalid_transcript_json_keeps_the_previous_context(tmp_path): @pytest.mark.parametrize("resume", [False, True], ids=["same-run", "resumed-edit"]) def test_api_rejected_transcript_edit_restores_last_accepted_context(tmp_path, rejection, resume): requests = [] - edit = "\n".join([ - "python3 - <<'PY'", + edit = py_cmd("\n".join([ "import json, os", "from pathlib import Path", "p = Path(os.environ['FREEHAND_SESSION']) / 'transcript.json'", - "t = json.loads(p.read_text())", + "t = json.loads(p.read_text(encoding='utf-8'))", "t['items'] = t['items'][:1] + [{'type': 'function_call_output', 'call_id': 'orphan', 'output': 'invalid edit'}]", - "p.write_text(json.dumps(t))", - "PY", - ]) + "p.write_text(json.dumps(t), encoding='utf-8')", + ])) class Handler(BaseHTTPRequestHandler): def log_message(self, *args): @@ -376,18 +375,16 @@ def test_unhandled_runtime_error_is_recorded_as_stopped(tmp_path): # ---- tools ----------------------------------------------------------------------------------------------------------- # -IMAGE_INTO_TRANSCRIPT = "\n".join([ - "python3 - <<'PY'", +IMAGE_INTO_TRANSCRIPT = py_cmd("\n".join([ "import base64, json, os", "from pathlib import Path", "p = Path(os.environ['FREEHAND_SESSION']) / 'transcript.json'", - "t = json.loads(p.read_text())", + "t = json.loads(p.read_text(encoding='utf-8'))", "data = base64.b64encode(Path('img.png').read_bytes()).decode()", "t['items'].append({'type': 'message', 'role': 'user', 'content': [", " {'type': 'input_image', 'image_url': 'data:image/png;base64,' + data}]})", - "p.write_text(json.dumps(t))", - "PY", -]) + "p.write_text(json.dumps(t), encoding='utf-8')", +])) def test_bash_timeout_kills_process_group(tmp_path): diff --git a/tests/test_server.py b/tests/test_server.py index 34f17cb4..acfe66b6 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -247,8 +247,9 @@ def test_the_web_command_prints_its_address_as_json_and_stops_on_an_interrupt(tm import signal import subprocess import sys + kw = {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP} if os.name == "nt" else {} proc = subprocess.Popen([sys.executable, "-m", "freehand", "web", "--json"], cwd=tmp_path, stdout=subprocess.PIPE, - stderr=subprocess.PIPE, text=True, env={**os.environ}) + stderr=subprocess.PIPE, text=True, env={**os.environ}, **kw) try: started = json.loads(proc.stdout.readline()) assert started["url"].startswith("http://127.0.0.1:") and "?token=" in started["url"] @@ -262,7 +263,7 @@ def test_the_web_command_prints_its_address_as_json_and_stops_on_an_interrupt(tm assert asset.status == 200 and asset.read() with opener.open(started["url"].split("/?")[0] + "/api/state", timeout=20) as resp: assert json.loads(resp.read())["cwd"] == str(tmp_path.resolve()) - proc.send_signal(signal.SIGINT) + proc.send_signal(signal.CTRL_BREAK_EVENT if os.name == "nt" else signal.SIGINT) assert proc.wait(20) == 0 finally: if proc.poll() is None: @@ -803,7 +804,7 @@ def test_markdown_shows_a_local_image_and_leaves_one_on_the_web_a_link(tmp_path) pytest.skip("node is not installed") md = (P(server.__file__).parent / "web" / "md.js").read_text(encoding="utf-8") script = md + "\nconsole.log(markdown('Here: ![the chart](out/chart.png) and ![x](https://example.com/a.png)'));" - out = subprocess.run(["node", "-e", script], capture_output=True, text=True, check=True).stdout + out = subprocess.run(["node"], input=script, capture_output=True, text=True, encoding="utf-8", check=True).stdout assert 'the chart' in out # the picture on the web is not fetched; the link carries only its site's icon web = out.split(" and ")[1] diff --git a/tests/test_setup.py b/tests/test_setup.py index c3465258..604be406 100644 --- a/tests/test_setup.py +++ b/tests/test_setup.py @@ -3,6 +3,7 @@ import io import json +import os import stat import sys @@ -66,7 +67,8 @@ def test_a_gateway_or_a_local_server_needs_no_credentials(): def test_a_saved_api_key_signs_requests_and_is_never_printed(tmp_path, monkeypatch, capsys, isolated_home): monkeypatch.setattr(sys, "stdin", io.StringIO("sk-saved-key\n")) assert cli.main(["login", "openai"]) == 0 - assert stat.S_IMODE((isolated_home / "auth.json").stat().st_mode) == 0o600 + if os.name != "nt": + assert stat.S_IMODE((isolated_home / "auth.json").stat().st_mode) == 0o600 assert providers.api_key("OPENAI_API_KEY") == "sk-saved-key" assert session.credentials_problem({"provider": "openai-responses"}) is None assert cli.main(["status"]) == 0 diff --git a/tests/test_snapshot_repositories.py b/tests/test_snapshot_repositories.py index 70115f5f..d2a7edb7 100644 --- a/tests/test_snapshot_repositories.py +++ b/tests/test_snapshot_repositories.py @@ -38,7 +38,7 @@ def finish(snaps: Snapshots, commit: str) -> None: def contents(path: Path) -> dict[str, bytes]: - return {str(p.relative_to(path)): p.read_bytes() for p in path.rglob("*") if p.is_file()} + return {p.relative_to(path).as_posix(): p.read_bytes() for p in path.rglob("*") if p.is_file()} @pytest.fixture diff --git a/tests/test_snapshots.py b/tests/test_snapshots.py index 51029ca9..cca5bfea 100644 --- a/tests/test_snapshots.py +++ b/tests/test_snapshots.py @@ -43,7 +43,7 @@ def test_a_diff_names_a_file_with_chinese_in_its_name_as_it_is(tmp_path): (tmp_path / "session").mkdir() snaps = Snapshots(tmp_path / "session", work) assert snaps.checkpoint("write docs") - (work / "docs" / "说明.md").write_text("这个文件\n") + (work / "docs" / "说明.md").write_text("这个文件\n", encoding="utf-8") d = snaps.diff(snaps.entries()[-1]["commit"]) assert [f["path"] for f in d["files"]] == ["docs/说明.md"] assert "b/docs/说明.md" in d["patch"] and "\\350" not in d["patch"] # git quotes it as "\350\257…" else @@ -224,7 +224,7 @@ def test_sessions_in_one_folder_share_one_store_and_a_repository_lends_its_objec a, b = Snapshots(one, work), Snapshots(two, work) assert a.git_dir == b.git_dir and not (one / "snapshots.git").exists() assert a.checkpoint("first") - assert (a.git_dir / "objects" / "info" / "alternates").read_text().strip() == str((work / ".git" / "objects").resolve()) + assert Path((a.git_dir / "objects" / "info" / "alternates").read_text().strip()) == (work / ".git" / "objects").resolve() stored = objects_in(a.git_dir) assert stored <= 4 # the changed file, a tree, a commit: no copies assert b.checkpoint("second session") diff --git a/tests/test_terminal.py b/tests/test_terminal.py index 7afa141b..48a9aad8 100644 --- a/tests/test_terminal.py +++ b/tests/test_terminal.py @@ -4,6 +4,7 @@ import io import json +import os import stat import sys import threading @@ -369,7 +370,8 @@ def test_a_first_start_without_credentials_offers_the_ways_to_sign_in_and_takes_ drv.send("sk-ant-never-shown\r") drv.back() assert providers.api_key("ANTHROPIC_API_KEY") == "sk-ant-never-shown" - assert stat.S_IMODE((isolated_home / "auth.json").stat().st_mode) == 0o600 + if os.name != "nt": + assert stat.S_IMODE((isolated_home / "auth.json").stat().st_mode) == 0o600 assert "Anthropic API key saved in" in drv.out and "New sessions use Anthropic" in drv.out cfg = drv.app.agent.cfg # the session that had no key gave way to one that has assert cfg["provider"] == "anthropic" and session.credentials_problem(cfg) is None @@ -640,8 +642,14 @@ def test_diff_shows_what_the_files_changed_since_the_last_message(tmp_path): work.mkdir() (work / "main.py").write_text("print('hi')\nprint('bye')\n") (work / "old.txt").write_text("old\n") - srv = FakeResponses([[call("bash", 1, command="printf \"print('hello')\\nprint('bye')\\n\" > main.py; " - "echo notes > notes.md; rm old.txt")], [say("Changed.")]]) + from fakes import py_cmd + edit_cmd = py_cmd( + "from pathlib import Path; " + "Path('main.py').write_text(\"print('hello')\\nprint('bye')\\n\"); " + "Path('notes.md').write_text('notes\\n'); " + "Path('old.txt').unlink()" + ) + srv = FakeResponses([[call("bash", 1, command=edit_cmd)], [say("Changed.")]]) try: session.save_setting("api_base", srv.url) drv = Driver(session.create(work, interactive=True), work) diff --git a/tests/test_terminal_startup_cleanup.py b/tests/test_terminal_startup_cleanup.py index 87056b5d..e6eb12d4 100644 --- a/tests/test_terminal_startup_cleanup.py +++ b/tests/test_terminal_startup_cleanup.py @@ -1,15 +1,17 @@ """An unsuccessful PTY setup must not consume a pair of file descriptors.""" from __future__ import annotations -import fcntl +import os import pytest from freehand import terminals +@pytest.mark.skipif(os.name == "nt", reason="POSIX openpty/fcntl descriptor cleanup test") @pytest.mark.parametrize("step", ["blocking", "size"]) def test_failed_terminal_setup_closes_both_pty_descriptors(tmp_path, monkeypatch, step): + import fcntl closed = [] monkeypatch.setattr(terminals.os, "openpty", lambda: (101, 102)) monkeypatch.setattr(terminals.os, "close", closed.append) diff --git a/tests/test_terminal_theme.py b/tests/test_terminal_theme.py index f4a11908..df5bf7d4 100644 --- a/tests/test_terminal_theme.py +++ b/tests/test_terminal_theme.py @@ -4,10 +4,14 @@ import io import os import re -import termios import threading from types import SimpleNamespace +try: + import termios +except ImportError: + termios = None # type: ignore[assignment] + import pytest from prompt_toolkit.document import Document from prompt_toolkit.input import create_pipe_input @@ -277,6 +281,7 @@ def _read(self): pending = pending[end:][-64:] +@pytest.mark.skipif(os.name == "nt", reason="POSIX PTY mode 2031 and termios check") @pytest.mark.parametrize("notifications", [False, True]) def test_fullscreen_cli_follows_or_rechecks_background_and_restores_terminal(tmp_path, isolated_home, notifications): configure(tmp_path) @@ -348,6 +353,7 @@ def test_no_response_keeps_the_current_palette_and_input_usable(tmp_path, monkey drv.quit() +@pytest.mark.skipif(os.name == "nt", reason="POSIX PTY mode 2031 check") @pytest.mark.parametrize("theme", ["light", "dark"]) def test_explicit_theme_at_startup_never_subscribes(tmp_path, isolated_home, theme): configure(tmp_path, theme) diff --git a/tests/test_trust.py b/tests/test_trust.py index bf712181..da740eea 100644 --- a/tests/test_trust.py +++ b/tests/test_trust.py @@ -64,7 +64,7 @@ def test_a_new_session_records_whether_its_folder_is_trusted(tmp_path): @pytest.mark.parametrize("projects", [{"KEY": {"trusted": True}}, {"KEY": ["trusted"]}, ["KEY"], "KEY"]) def test_a_trust_entry_edited_by_hand_into_something_else_is_asked_again(tmp_path, projects): - projects = json.loads(json.dumps(projects).replace("KEY", session.project_key(tmp_path))) + projects = json.loads(json.dumps(projects).replace('"KEY"', json.dumps(session.project_key(tmp_path)))) session.save_setting("projects", projects) assert session.trust(tmp_path) is None session.create(tmp_path, interactive=True) diff --git a/tests/test_tui_audit.py b/tests/test_tui_audit.py index c9e27bae..ad6db6e9 100644 --- a/tests/test_tui_audit.py +++ b/tests/test_tui_audit.py @@ -55,7 +55,10 @@ def test_typing_inside_a_collapsed_paste_preserves_the_original_and_the_new_text def test_editor_receives_the_pasted_body_to_edit_not_its_placeholder(tmp_path, monkeypatch): - monkeypatch.setenv("VISUAL", "sh -c 'printf EDITED >> \"$0\"'") + import sys + editor = tmp_path / "append_edited.py" + editor.write_text("import sys\nwith open(sys.argv[1], 'a', encoding='utf-8') as f: f.write('EDITED')\n") + monkeypatch.setenv("VISUAL", f'"{sys.executable}" "{editor}"') srv, drv = started(tmp_path, [[say("received")]]) try: body = "\n".join(f"line {i}" for i in range(30)) diff --git a/tests/test_tui_details.py b/tests/test_tui_details.py index cfffd2ce..d5598d49 100644 --- a/tests/test_tui_details.py +++ b/tests/test_tui_details.py @@ -9,7 +9,7 @@ from rich.console import Console from rich.text import Text -from fakes import FakeResponses, call, say +from fakes import FakeResponses, call, py_cmd, say from freehand import session, tui, ui from freehand.inputs import FileIndex from repl_driver import Driver, wait_until @@ -70,16 +70,21 @@ def test_your_own_command_shows_most_of_its_output(): def test_context_says_whether_it_was_edited(tmp_path, monkeypatch): + import sys + noop = tmp_path / "noop_ed.py" + noop.write_text("pass\n") + touch = tmp_path / "touch_ed.py" + touch.write_text("import sys\nwith open(sys.argv[1], 'a', encoding='utf-8') as f: f.write(' ')\n") srv = FakeResponses([[say("Hi.")]]) try: session.save_setting("api_base", srv.url) drv = Driver(session.create(tmp_path, interactive=True), tmp_path) drv.turn("hello") - monkeypatch.setenv("VISUAL", "true") # an editor left without a change + monkeypatch.setenv("VISUAL", f'"{sys.executable}" "{noop}"') # an editor left without a change drv.send("/context\r") wait_until(lambda: "The context is unchanged." in drv.out, what="the unchanged note") assert "Your edits are sent" not in drv.out - monkeypatch.setenv("VISUAL", """sh -c 'printf " " >> "$0"'""") # an edit (still valid JSON) + monkeypatch.setenv("VISUAL", f'"{sys.executable}" "{touch}"') # an edit (still valid JSON) drv.send("/context\r") wait_until(lambda: "Your edits are sent" in drv.out, what="the edited note") drv.quit() @@ -139,7 +144,8 @@ def test_esc_esc_clears_the_input_and_up_brings_it_back(tmp_path): def test_messages_a_stop_left_unsent_go_back_into_the_input_before_what_is_typed(tmp_path): - srv = FakeResponses([[call("bash", 1, command="echo $$ > pid; sleep 30")]]) + cmd = py_cmd("import os, time; open('pid', 'w').write(str(os.getpid())); time.sleep(30)") + srv = FakeResponses([[call("bash", 1, command=cmd)]]) try: session.save_setting("api_base", srv.url) drv = Driver(session.create(tmp_path, interactive=True), tmp_path) @@ -164,7 +170,8 @@ def test_messages_a_stop_left_unsent_go_back_into_the_input_before_what_is_typed def test_up_on_an_empty_input_takes_back_a_queued_message_before_the_model_reads_it(tmp_path): - srv = FakeResponses([[call("bash", 1, command="echo $$ > pid; sleep 3")], [say("done")]]) + cmd = py_cmd("import os, time; open('pid', 'w').write(str(os.getpid())); time.sleep(3)") + srv = FakeResponses([[call("bash", 1, command=cmd)], [say("done")]]) try: session.save_setting("api_base", srv.url) drv = Driver(session.create(tmp_path, interactive=True), tmp_path) @@ -217,10 +224,14 @@ def test_ctrl_r_searches_what_was_sent_and_puts_the_pick_in_the_input(tmp_path): def test_ctrl_g_writes_the_message_in_the_editor_and_shift_enter_is_a_new_line(tmp_path, monkeypatch): - editor = tmp_path / "editor.sh" - editor.write_text('#!/bin/sh\nprintf "first line\\nwritten in the editor\\n" > "$1"\n') - editor.chmod(0o755) - monkeypatch.setenv("VISUAL", str(editor)) + import sys + editor = tmp_path / "editor.py" + editor.write_text( + 'import sys\nfrom pathlib import Path\n' + 'Path(sys.argv[1]).write_text("first line\\nwritten in the editor\\n", encoding="utf-8")\n', + encoding="utf-8", + ) + monkeypatch.setenv("VISUAL", f'"{sys.executable}" "{editor}"') srv = FakeResponses([]) try: session.save_setting("api_base", srv.url) diff --git a/tests/test_tui_fixes.py b/tests/test_tui_fixes.py index 6c1d6c2e..0af93bf1 100644 --- a/tests/test_tui_fixes.py +++ b/tests/test_tui_fixes.py @@ -77,8 +77,10 @@ def started(tmp_path, script, **settings): # ---- 1. what a running command writes, as it comes ------------------------------------------------------------------ def test_the_models_command_shows_the_end_of_its_output_while_it_runs_and_ctrl_o_all_of_it(tmp_path): - srv, drv = started(tmp_path, [[call("bash", 1, command="for i in 1 2 3 4 5 6; do echo line$i; done; " - "echo $$ > pid; sleep 30")]]) + from fakes import py_cmd + cmd = py_cmd("import os, time\nfor i in range(1, 7): print(f'line{i}', flush=True)\n" + "open('pid', 'w').write(str(os.getpid()))\ntime.sleep(30)") + srv, drv = started(tmp_path, [[call("bash", 1, command=cmd)]]) try: drv.send("run it\r") wait_until(lambda: (tmp_path / "pid").exists(), what="the command") @@ -356,9 +358,11 @@ def test_rows_with_wide_characters_line_up_in_pickers_and_the_menu(): # ---- 8. the editor -------------------------------------------------------------------------------------------------- def test_the_editor_opens_at_the_end_of_what_is_typed(tmp_path, monkeypatch): + from freehand.runtime import osutil + monkeypatch.setattr(osutil, "resolve_executable", lambda p: p) for name, arg in (("nano", "+2,6"), ("vim", "+normal! G$"), ("emacs", "+2:6"), ("vi", "+2")): exe = tmp_path / name - exe.write_text("#!/bin/sh\n") + exe.write_text("#!/bin/sh\n", encoding="utf-8") exe.chmod(0o755) monkeypatch.setenv("VISUAL", str(exe)) assert tui.editor_command("/tmp/x.md", "first\nabcde") == [str(exe), arg, "/tmp/x.md"] diff --git a/tests/test_usercommands.py b/tests/test_usercommands.py index 6ebc673d..0438da09 100644 --- a/tests/test_usercommands.py +++ b/tests/test_usercommands.py @@ -23,7 +23,7 @@ def test_commands_come_from_files_skills_and_freehand_and_expand_with_their_argu expected = "# The project's own\nFix it the project's way.\n\n42" assert usercommands.expand(project, "/fix-issue 42", project=True) == expected assert usercommands.expand(project, "/fix-issue 42", project=False) == "Fix issue 42, with a test." - assert "deploy/SKILL.md first" in usercommands.expand(project, "/deploy staging", project=True) + assert "deploy/SKILL.md first" in usercommands.expand(project, "/deploy staging", project=True).replace("\\", "/") assert usercommands.expand(project, "/deploy", project=False) is None # an untrusted folder's skills stay out assert usercommands.expand(project, "/init", project=False).startswith("Look through this repository") assert "Do not change any file." in usercommands.expand(project, "/review", project=False) diff --git a/tests/test_ux_matrix.py b/tests/test_ux_matrix.py index 711bd64a..7e6d797c 100644 --- a/tests/test_ux_matrix.py +++ b/tests/test_ux_matrix.py @@ -57,15 +57,19 @@ def test_cli_rapid_interrupt_during_running_command_stays_clean(tmp_path, isolat assert "Recovered cleanly." in drv.out and "Traceback" not in drv.out -def test_windows_shows_friendly_wsl2_guidance_instead_of_crashing(monkeypatch, capsys): - import sys +def test_windows_cli_runs_natively(tmp_path, isolated_home, monkeypatch, capsys): from freehand import cli - monkeypatch.setattr(sys, "platform", "win32") - rc = cli.main([]) - err = capsys.readouterr().err - assert rc == 2 and "WSL2" in err and "wsl --install" in err - # --version still works cleanly on win32 + monkeypatch.chdir(tmp_path) + srv = FakeResponses([[say("native-windows-ok")]]) + try: + session.save_setting("api_base", srv.url) + session.set_trust(tmp_path, True) + rc = cli.main(["-p", "say hi"]) + assert rc == 0 + assert "native-windows-ok" in capsys.readouterr().out + finally: + srv.close() with pytest.raises(SystemExit) as exc: cli.main(["--version"]) assert exc.value.code == 0 diff --git a/tests/test_web_e2e.py b/tests/test_web_e2e.py index 7d1c55ee..25acf3eb 100644 --- a/tests/test_web_e2e.py +++ b/tests/test_web_e2e.py @@ -36,9 +36,19 @@ def _find_chrome() -> str | None: shutil.which("google-chrome-stable") or "", shutil.which("chromium") or "", shutil.which("chromium-browser") or "", + shutil.which("chrome") or "", ] + if sys.platform == "win32": + for root in (os.environ.get("PROGRAMFILES"), os.environ.get("PROGRAMFILES(X86)"), + os.environ.get("LOCALAPPDATA")): + if root: + candidates += [ + os.path.join(root, "Google", "Chrome", "Application", "chrome.exe"), + os.path.join(root, "Chromium", "Application", "chrome.exe"), + os.path.join(root, "Microsoft", "Edge", "Application", "msedge.exe"), + ] for path in candidates: - if path and os.path.isfile(path) and os.access(path, os.X_OK): + if path and os.path.isfile(path) and (sys.platform == "win32" or os.access(path, os.X_OK)): return path return None @@ -52,7 +62,7 @@ def __init__(self, chrome: str) -> None: self.user_dir = tempfile.mkdtemp(prefix="freehand-cdp-") args = [chrome, "--headless=new", "--remote-debugging-port=0", "--remote-allow-origins=*", f"--user-data-dir={self.user_dir}", "--no-first-run", "--no-default-browser-check", - "--disable-gpu", "--disable-extensions", "--window-size=1280,860", + "--disable-gpu", "--disable-extensions", "--window-size=1280,860", "--lang=en-US", # Linux headless runners have no pointer device and default to (hover: none); emulate desktop pointer # unless a test explicitly enables touch emulation. "--blink-settings=primaryHoverType=2,availableHoverTypes=2," @@ -61,7 +71,10 @@ def __init__(self, chrome: str) -> None: if sys.platform.startswith("linux") and (os.environ.get("CI") or os.environ.get("FREEHAND_CHROME_NO_SANDBOX")): args.extend(["--no-sandbox", "--disable-dev-shm-usage"]) args.append("about:blank") - self.proc = subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + # A 4 KB Windows pipe buffer fills under Chrome's verbose logs and deadlocks Chrome; write stderr to a file. + self._stderr_path = Path(self.user_dir) / "chrome-stderr.log" + self._stderr_file = open(self._stderr_path, "wb") + self.proc = subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=self._stderr_file) try: ws_url = self._wait_ws_url() self.ws = wsclient.WebSocket(ws_url, {}, timeout=45.0) @@ -76,6 +89,8 @@ def __init__(self, chrome: str) -> None: self.call("Emulation.setEmulatedMedia", { "features": [{"name": "prefers-reduced-motion", "value": "no-preference"}], }) + # Non-English developer machines format Intl numbers with commas unless locale is pinned. + self.call("Emulation.setLocaleOverride", {"locale": "en-US"}) self.live.add(self) except Exception: self.close() @@ -88,12 +103,18 @@ def _wait_ws_url(self) -> str: port = 0 while time.time() < deadline: if port_file.is_file(): - lines = port_file.read_text(encoding="utf-8", errors="replace").splitlines() + try: + lines = port_file.read_text(encoding="utf-8", errors="replace").splitlines() + except OSError: + lines = [] if lines and lines[0].strip().isdigit(): port = int(lines[0].strip()) break if self.proc.poll() is not None: - err = self.proc.stderr.read().decode("utf-8", "replace") if self.proc.stderr else "" + try: + err = self._stderr_path.read_bytes().decode("utf-8", "replace") + except OSError: + err = "" raise RuntimeError(f"Chrome exited early: {err[:500]}") time.sleep(0.05) if not port: @@ -201,6 +222,11 @@ def close(self) -> None: self.proc.wait(timeout=5) except Exception: # noqa: BLE001 self.proc.kill() + if getattr(self, "_stderr_file", None): + try: + self._stderr_file.close() + except OSError: + pass shutil.rmtree(self.user_dir, ignore_errors=True) diff --git a/tests/test_web_e2e_more.py b/tests/test_web_e2e_more.py index 85aebe37..3ca3bcca 100644 --- a/tests/test_web_e2e_more.py +++ b/tests/test_web_e2e_more.py @@ -413,7 +413,7 @@ def do_POST(self): def test_text_files_go_with_a_message_and_other_files_are_refused_or_given_as_paths(tmp_path, isolated_home, page): srv = FakeResponses([[say("read it")]]) notes = tmp_path / "notes.py" - notes.write_text("print('```')\n") + notes.write_text("print('```')\n", newline="\n") pdf = tmp_path / "paper.pdf" pdf.write_bytes(b"%PDF-1.4 binary") httpd, hub = serve(tmp_path, srv.url, page) diff --git a/tests/test_web_files.py b/tests/test_web_files.py index f187de82..10794f4a 100644 --- a/tests/test_web_files.py +++ b/tests/test_web_files.py @@ -3,6 +3,7 @@ from pathlib import Path from html import escape +import os import subprocess import threading from types import SimpleNamespace @@ -225,8 +226,10 @@ def test_files_resolve_against_current_workdir_and_survive_reload(client, tmp_pa def test_invalid_missing_outside_and_symlink_paths_are_refused(client, launches): sid = client.request("/api/sessions", {})[1]["id"] cwd = client.hub.cwd - (cwd / "escape.pdf").symlink_to("/etc/hosts") - invalid = ["missing.pdf", "escape.pdf", "/etc/hosts", "../../../../../../etc/hosts", "file://remote/etc/hosts", + outside = (Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32" / "drivers" / "etc" / "hosts" + if os.name == "nt" else Path("/etc/hosts")) + (cwd / "escape.pdf").symlink_to(outside) + invalid = ["missing.pdf", "escape.pdf", str(outside), "../../../../../../etc/hosts", "file://remote/etc/hosts", "//remote/etc/hosts", "https://example.com/a.pdf", "\x00a.pdf", "a%00.pdf", "file://[bad/a.pdf", ""] for path in invalid: query = quote(path, safe="") @@ -260,7 +263,10 @@ def test_native_actions_are_authenticated_post_only_and_use_argv(client, launche def test_programs_cannot_be_opened_and_html_downloads_cannot_execute(client, launches, monkeypatch): sid = client.request("/api/sessions", {})[1]["id"] at = f"/api/sessions/{sid}" - for name in ("run.sh", "run.command", "evil.app", "evil.desktop", "evil.html", "macro.docm", "exec.pdf"): + names = ["run.sh", "run.command", "evil.app", "evil.desktop", "evil.html", "macro.docm"] + if os.name != "nt": + names.append("exec.pdf") + for name in names: path = client.hub.cwd / name path.write_text("") if name == "exec.pdf": diff --git a/tests/test_web_no_project.py b/tests/test_web_no_project.py index d006f142..6e1fc6a0 100644 --- a/tests/test_web_no_project.py +++ b/tests/test_web_no_project.py @@ -8,7 +8,7 @@ import pytest import test_web_e2e as e2e -from fakes import FakeResponses, call, say +from fakes import FakeResponses, call, py_cmd, say from freehand import server, session from repl_driver import wait_until @@ -16,7 +16,8 @@ def test_no_project_browser_turn_navigation_and_restore(tmp_path, chrome_page, isolated_home): - api = FakeResponses([[call("bash", 1, command="printf hello > hello.txt")], [say("Saved hello.txt.")], + cmd = py_cmd("from pathlib import Path; Path('hello.txt').write_text('hello')") + api = FakeResponses([[call("bash", 1, command=cmd)], [say("Saved hello.txt.")], [say("A second session.")]]) httpd, hub = server.make_server(tmp_path, 0) thread = threading.Thread(target=httpd.serve_forever, daemon=True) diff --git a/tests/test_web_panels.py b/tests/test_web_panels.py index a4867628..89e762fd 100644 --- a/tests/test_web_panels.py +++ b/tests/test_web_panels.py @@ -21,7 +21,7 @@ def run(script: str, *files: str) -> object: js = ("const fs=require('fs'), vm=require('vm'); const ctx={console}; vm.createContext(ctx); " + "".join(f"vm.runInContext(fs.readFileSync({str(WEB / f)!r}, 'utf8'), ctx); " for f in files) + f"process.stdout.write(JSON.stringify(vm.runInContext({json.dumps(script)}, ctx)));") - out = subprocess.run([node, "-e", js], capture_output=True, text=True, timeout=20) + out = subprocess.run([node], input=js, capture_output=True, text=True, encoding="utf-8", timeout=20) assert out.returncode == 0, out.stderr return json.loads(out.stdout) diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py index e6afe217..f18a26ab 100644 --- a/tests/test_web_ui.py +++ b/tests/test_web_ui.py @@ -55,10 +55,12 @@ def test_preview_is_readonly_capped_authenticated_and_root_restricted(client): assert client.request(prefix + "binary.bin")[0] == 415 (client.hub.cwd / "large.txt").write_bytes(b"x" * (server.TEXT_PREVIEW_MAX + 1)) assert client.request(prefix + "large.txt")[0] == 413 - (client.hub.cwd / "escape.txt").symlink_to("/etc/hosts") - for path in ("escape.txt", "/etc/hosts", "missing.txt", "file://remote/etc/hosts", "", "%00"): + outside = (Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32" / "drivers" / "etc" / "hosts" + if os.name == "nt" else Path("/etc/hosts")) + (client.hub.cwd / "escape.txt").symlink_to(outside) + for path in ("escape.txt", str(outside), "missing.txt", "file://remote/etc/hosts", "", "%00"): assert client.request(prefix + quote(path, safe=""))[0] in (400, 404) - (client.hub.cwd / "中文.md").write_text("# 标题\n\n**正文**") + (client.hub.cwd / "中文.md").write_text("# 标题\n\n**正文**", encoding="utf-8") assert client.request(prefix + quote("中文.md"))[1]["text"].startswith("# 标题") (client.hub.cwd / "image.png").write_bytes(b"\x89PNG\r\n\x1a\n") assert client.request(prefix + "image.png")[1]["kind"] == "image" diff --git a/tests/test_web_workbench.py b/tests/test_web_workbench.py index a956d9dc..0621877e 100644 --- a/tests/test_web_workbench.py +++ b/tests/test_web_workbench.py @@ -2,6 +2,7 @@ from __future__ import annotations import json +import os from pathlib import Path from freehand import server, session @@ -85,8 +86,9 @@ def test_terminal_does_not_send_model_messages_and_appearance_survives_reload(cl "{clipboardData: new DataTransfer(), bubbles:true}))") # Exercise the actual terminal input API and the browser's output renderer. wait_until(lambda: client.hub.workbench.terminals, what="a terminal") + from fakes import py_cmd term = next(iter(client.hub.workbench.terminals.values())) - term.write("printf 'browser-%s\\n' terminal\n") + term.write(py_cmd("print('browser-' + 'terminal')") + ("\r" if os.name == "nt" else "\n")) chrome_page.wait_for("document.querySelector('.terminal-screen').textContent.includes('browser-terminal')") # appearance is a page of the one settings window chrome_page.eval("freehandWorkbench.open('appearance')") diff --git a/tests/test_windows_support.py b/tests/test_windows_support.py new file mode 100644 index 00000000..09d0ae88 --- /dev/null +++ b/tests/test_windows_support.py @@ -0,0 +1,236 @@ +"""Native Windows support tests: OS primitives, PowerShell execution, ConPTY, quoting, paths and web helpers.""" +from __future__ import annotations + +import os +import subprocess +import sys +import time +from pathlib import Path +from unittest import mock + +import pytest + +from fakes import FakeResponses, call, say +from freehand import cli, session, snapshots, terminals, tui, workbench +from freehand.runtime import agent as rt +from freehand.runtime import osutil, shellenv + + +def test_file_lock_blocks_concurrent_acquisition_and_releases(tmp_path): + lock = tmp_path / "sub" / "test.lock" + assert not osutil.is_file_locked(lock) + with osutil.file_lock(lock, exclusive=True, blocking=False): + assert osutil.is_file_locked(lock) + with pytest.raises(BlockingIOError): + with osutil.file_lock(lock, exclusive=True, blocking=False): + pass + assert not osutil.is_file_locked(lock) + + +def test_replace_file_retries_transient_windows_sharing_violation(tmp_path, monkeypatch): + src = tmp_path / "a.tmp" + dst = tmp_path / "a.json" + src.write_bytes(b"new\n") + dst.write_bytes(b"old\n") + monkeypatch.setattr(osutil, "IS_WINDOWS", True) + attempts = {"n": 0} + real_replace = os.replace + + def flaky_replace(a, b): + attempts["n"] += 1 + if attempts["n"] < 3: + err = PermissionError("sharing violation") + err.winerror = 32 + raise err + return real_replace(a, b) + + monkeypatch.setattr(osutil.os, "replace", flaky_replace) + monkeypatch.setattr(osutil.time, "sleep", lambda _: None) + osutil.replace_file(src, dst) + assert attempts["n"] == 3 + assert dst.read_bytes() == b"new\n" + + +def test_atomic_write_cleans_up_temp_file_on_failure(tmp_path, monkeypatch): + target = tmp_path / "out.json" + monkeypatch.setattr(osutil, "replace_file", mock.Mock(side_effect=OSError("disk full"))) + with pytest.raises(OSError, match="disk full"): + osutil.atomic_write_text(target, '{"ok": true}\n') + assert list(tmp_path.iterdir()) == [] + + +def test_shellenv_windows_core_env_is_case_insensitive_and_deduplicates_set(monkeypatch): + monkeypatch.setattr(shellenv.os, "name", "nt") + env = { + "Path": r"C:\Windows\System32", + "SystemRoot": r"C:\Windows", + "ComSpec": r"C:\Windows\System32\cmd.exe", + "UserProfile": r"C:\Users\alice", + "OPENAI_API_KEY": "secret", + "EXTRA": "drop-me", + } + filtered = shellenv.filter_env(env, {"inherit": "core", "set": {"PATH": r"C:\Tools"}}) + assert filtered["PATH"] == r"C:\Tools" + assert "Path" not in filtered + assert filtered["SystemRoot"] == r"C:\Windows" + assert filtered["ComSpec"] == r"C:\Windows\System32\cmd.exe" + assert filtered["UserProfile"] == r"C:\Users\alice" + assert "OPENAI_API_KEY" not in filtered and "EXTRA" not in filtered + + +def test_tool_specs_and_environment_stay_posix_on_posix_and_powershell_on_windows(tmp_path, monkeypatch): + monkeypatch.setattr(osutil, "IS_WINDOWS", False) + posix_spec = rt.tool_specs("alice")[0] + assert posix_spec["name"] == "bash" + assert "bash -lc" in posix_spec["description"] + assert "nohup CMD > LOG 2>&1 &" in posix_spec["description"] + assert "(commands run in bash -lc)" in session.environment(tmp_path) + + monkeypatch.setattr(osutil, "IS_WINDOWS", True) + monkeypatch.setattr(osutil, "find_shell", lambda: r"C:\Program Files\PowerShell\7\pwsh.exe") + win_spec = rt.tool_specs("alice")[0] + assert win_spec["name"] == "bash" + assert "PowerShell" in win_spec["description"] and "pwsh" in win_spec["description"] + assert "(commands run in PowerShell)" in session.environment(tmp_path) + + +def test_windows_editor_and_mcp_parsing_preserve_backslashes(monkeypatch): + monkeypatch.setattr(osutil, "IS_WINDOWS", True) + monkeypatch.setattr(osutil, "resolve_executable", lambda p: p) + monkeypatch.setenv("EDITOR", r'"C:\Program Files\Neovim\bin\nvim.exe" -u NONE') + argv = tui.editor_command(r"C:\tmp\msg.md", "hello") + assert argv == [r"C:\Program Files\Neovim\bin\nvim.exe", "-u", "NONE", "+normal! G$", r"C:\tmp\msg.md"] + + cmd, env = workbench.parse_mcp(r'"C:\Tools\mcp.exe" --root C:\Repo', r'DATA="C:\My Data"') + assert cmd == [r"C:\Tools\mcp.exe", "--root", r"C:\Repo"] + assert env == {"DATA": r"C:\My Data"} + + +def test_refused_here_matches_windows_winerror_10061(): + exc = ConnectionError("Anthropic API connection failed ([WinError 10061] No connection could be made)") + assert rt.refused_here(exc, "http://127.0.0.1:4000/v1") + assert not rt.refused_here(exc, "https://api.anthropic.com") + + +@pytest.mark.skipif(not osutil.IS_WINDOWS, reason="Native Windows PowerShell & Job Object tests") +def test_windows_powershell_utf8_exit_codes_crlf_and_long_script(tmp_path, isolated_home): + srv = FakeResponses([ + [call("bash", 1, command='Write-Output "héllo 世界"')], + [call("bash", 2, command=f'& {osutil.quote_shell_arg(sys.executable)} -c "import sys; sys.exit(42)"')], + [call("bash", 3, command="Write-Output 'ok' # " + ("x" * 21000))], + [say("all done")], + ]) + try: + d = session.create(tmp_path, interactive=False, overrides={"api_base": srv.url}) + (d / "task.md").write_text("check\n", encoding="utf-8") + a = rt.Agent(d) + a.log_to_stderr = False + assert a.run() == 0 + outs = [it["output"] for it in a.items if it.get("type") == "function_call_output"] + assert "héllo 世界" in outs[0] and "\r" not in outs[0] and "[exit 0," in outs[0] + assert "[exit 42," in outs[1] + assert "ok" in outs[2] and "[exit 0," in outs[2] + finally: + srv.close() + + +@pytest.mark.skipif(not osutil.IS_WINDOWS, reason="Native Windows Job Object tree kill test") +def test_windows_timeout_kills_descendant_process_tree(tmp_path, isolated_home): + pid_file = tmp_path / "child.pid" + py = osutil.quote_shell_arg(sys.executable) + child_code = ( + f"import os, subprocess, sys, time; " + f"c = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)']); " + f"open({str(pid_file)!r}, 'w').write(str(c.pid)); " + f"time.sleep(30)" + ) + srv = FakeResponses([ + [call("bash", 1, command=f"& {py} -c {osutil.quote_shell_arg(child_code)}", timeout_s=2)], + [say("timed out cleanly")], + ]) + try: + d = session.create(tmp_path, interactive=False, overrides={"api_base": srv.url}) + (d / "task.md").write_text("timeout\n", encoding="utf-8") + a = rt.Agent(d) + a.log_to_stderr = False + assert a.run() == 0 + outs = [it["output"] for it in a.items if it.get("type") == "function_call_output"] + assert "[killed after 2s timeout]" in outs[0] + assert pid_file.is_file() + child_pid = int(pid_file.read_text(encoding="utf-8").strip()) + # Verify the grandchild process was terminated by the Job Object, not orphaned. + check = subprocess.run(["tasklist", "/FI", f"PID eq {child_pid}", "/NH"], + capture_output=True, text=True, encoding="utf-8", errors="replace") + assert str(child_pid) not in check.stdout + finally: + srv.close() + + +@pytest.mark.skipif(not osutil.IS_WINDOWS, reason="Native Windows ConPTY test") +def test_windows_conpty_integrated_terminal_io_resize_interrupt_and_close(tmp_path): + term = terminals.Terminal(tmp_path, "owner-1") + try: + term.write("Write-Output WIN_CONPTY_HELLO\r") + end = time.time() + 12 + while time.time() < end and "WIN_CONPTY_HELLO" not in term.read()["output"]: + time.sleep(0.05) + assert "WIN_CONPTY_HELLO" in term.read()["output"] + term.resize(36, 110) + term.write("Start-Sleep -Seconds 30\r") + time.sleep(0.4) + term.write("\x03") + time.sleep(0.2) + term.write("Write-Output WIN_CONPTY_AFTER_CTRLC\r") + end = time.time() + 12 + while time.time() < end and "WIN_CONPTY_AFTER_CTRLC" not in term.read()["output"]: + time.sleep(0.05) + assert "WIN_CONPTY_AFTER_CTRLC" in term.read()["output"] + finally: + term.close() + assert term.read()["exit"] is not None + + +@pytest.mark.skipif(not osutil.IS_WINDOWS, reason="Native Windows doctor and drive root test") +def test_windows_doctor_and_drive_root_snapshot_guard(tmp_path, isolated_home, capsys, monkeypatch): + # Drive root must disable snapshots on Windows just like '/' on POSIX. + drive_root = Path(tmp_path.anchor) + snaps = snapshots.Snapshots(tmp_path / "sess", drive_root) + assert snaps.disabled is not None + + monkeypatch.setenv("OPENAI_API_KEY", "test-key") + (isolated_home / "auth.json").parent.mkdir(parents=True, exist_ok=True) + (isolated_home / "auth.json").write_text("{}", encoding="utf-8") + assert cli.main(["doctor"]) == 0 + out = capsys.readouterr().out + assert "Windows user ACL" in out and "clipboard=windows" in out + + +def test_web_path_helpers_handle_windows_and_posix_paths(): + root = Path(__file__).resolve().parents[1] + script = f""" +const fs = require('node:fs'); +const vm = require('node:vm'); +const appSrc = fs.readFileSync({str(root / 'src/freehand/web/app.js')!r}, 'utf8'); +const mdSrc = fs.readFileSync({str(root / 'src/freehand/web/md.js')!r}, 'utf8'); +const helpers = appSrc.slice(appSrc.indexOf('const pathSep ='), appSrc.indexOf('const plural =')); +const baseNameLine = appSrc.match(/const baseName = [^;]+;/)[0]; +const langOfBlock = mdSrc.slice(mdSrc.indexOf('const EXT_LANG ='), mdSrc.indexOf('function diffHtml')); +const ctx = {{ view: {{ overview: {{ home: 'C:\\\\Users\\\\Alice' }} }} }}; +const exportsLine = 'globalThis.exports = {{ pathSep, joinPath, normPath, pathInside, short, baseName, langOf }};'; +vm.runInNewContext(helpers + '\\n' + baseNameLine + '\\n' + langOfBlock + '\\n' + exportsLine, ctx); +const e = ctx.exports; +const assert = require('node:assert/strict'); +assert.equal(e.baseName('C:\\\\Users\\\\Alice\\\\repo'), 'repo'); +assert.equal(e.baseName('/Users/alice/repo'), 'repo'); +assert.equal(e.short('c:\\\\users\\\\alice\\\\repo'), '~\\\\repo'); +assert.equal(e.short('C:\\\\Users\\\\AliceTwo\\\\repo'), 'C:\\\\Users\\\\AliceTwo\\\\repo'); +assert.equal(e.joinPath('C:\\\\repo', 'src/a.py'), 'C:\\\\repo\\\\src\\\\a.py'); +assert.equal(e.joinPath('/repo', 'src/a.py'), '/repo/src/a.py'); +assert.equal(e.pathInside('c:\\\\users\\\\alice\\\\skills\\\\foo\\\\SKILL.md', 'C:\\\\Users\\\\Alice\\\\skills'), true); +assert.equal(e.pathInside('C:\\\\Users\\\\Alice\\\\skills2\\\\foo', 'C:\\\\Users\\\\Alice\\\\skills'), false); +assert.equal(e.langOf('C:\\\\repo\\\\src\\\\main.py'), 'py'); +console.log('WEB_PATH_HELPERS_OK'); +""" + res = subprocess.run(["node", "-e", script], capture_output=True, text=True, encoding="utf-8") + assert res.returncode == 0, res.stderr + assert "WEB_PATH_HELPERS_OK" in res.stdout diff --git a/tests/test_workbench.py b/tests/test_workbench.py index cef19216..b86edf33 100644 --- a/tests/test_workbench.py +++ b/tests/test_workbench.py @@ -2,6 +2,7 @@ from __future__ import annotations import json +import os from pathlib import Path import subprocess import time @@ -58,7 +59,8 @@ def test_state_survives_server_ports_and_merges_separate_drafts(client, tmp_path assert other.request("/api/workbench/state", token=False)[0] == 403 assert other.request("/api/workbench/state", {"changes": {}}, headers={"Origin": "https://bad.test"})[0] == 403 assert post(other, "state", changes={"not-a-preference": "x"})[0] == 400 - assert (auth.home() / "workbench.sqlite3").stat().st_mode & 0o777 == 0o600 + if os.name != "nt": + assert (auth.home() / "workbench.sqlite3").stat().st_mode & 0o777 == 0o600 finally: other.close() assert post(client, "state", changes={"freehand.drafts": {"a": None}})[0] == 200 @@ -188,20 +190,27 @@ def test_git_operations_and_isolated_worktree(client): def test_terminal_interaction_interrupt_and_owner_isolation(client): + from fakes import py_cmd sid, other = create(client), create(client, True) status, terminal = post(client, "terminal", sid, action="start") assert status == 200, terminal tid = terminal["id"] - assert post(client, "terminal", other, action="input", id=tid, text="echo wrong\n")[0] == 404 - assert post(client, "terminal", sid, action="input", id=tid, text="printf 'term-%s\\n' ready\n")[0] == 200 + eol = "\r" if os.name == "nt" else "\n" + assert post(client, "terminal", other, action="input", id=tid, text=f"echo wrong{eol}")[0] == 404 + assert post(client, "terminal", sid, action="input", id=tid, + text=py_cmd("print('term-' + 'ready')") + eol)[0] == 200 def output(): return get(client, "terminals", sid, id=tid)[1]["items"][0]["output"] wait_until(lambda: "term-ready" in output(), what="interactive terminal output") assert post(client, "terminal", sid, action="resize", id=tid, rows=40, cols=110)[0] == 200 - post(client, "terminal", sid, action="input", id=tid, text="sleep 30\n") - time.sleep(0.2) + sleep_cmd = "Start-Sleep 30" if os.name == "nt" else "sleep 30" + post(client, "terminal", sid, action="input", id=tid, text=sleep_cmd + eol) + time.sleep(0.4) assert post(client, "terminal", sid, action="input", id=tid, text="\x03")[0] == 200 - post(client, "terminal", sid, action="input", id=tid, text="printf 'after-%s\\n' interrupt\n") + if os.name == "nt": + time.sleep(0.4) + post(client, "terminal", sid, action="input", id=tid, + text=py_cmd("print('after-' + 'interrupt')") + eol) wait_until(lambda: "after-interrupt" in output(), what="terminal interrupt") assert post(client, "terminal", sid, action="close", id=tid)[0] == 200 assert not get(client, "terminals", sid)[1]["items"] @@ -326,8 +335,9 @@ def test_editor_argv_and_busy_folder_writes(client, monkeypatch): (c.cwd / "a space.py").write_text("pass\n") calls = [] monkeypatch.setattr(workbench, "run", lambda cwd, args, timeout=20: calls.append(args) or "") + from freehand.runtime import osutil assert post(client, "editor", sid, editor="code", path="a space.py", line=7)[0] == 200 - assert calls == [["code", "--goto", str(c.cwd / "a space.py") + ":7"]] + assert calls == [[osutil.resolve_executable("code"), "--goto", str(c.cwd / "a space.py") + ":7"]] assert post(client, "editor", sid, editor="arbitrary-executable")[0] == 400 c.busy = True try: