Skip to content

feat: add native Windows support across runtime, CLI/TUI, web UI, ConPTY, desktop app, and CI - #201

Open
Miguel del Amor (forlayo) wants to merge 1 commit into
microsoft:mainfrom
forlayo:feat/native-windows-support
Open

Miguel del Amor (forlayo) wants to merge 1 commit into
microsoft:mainfrom
forlayo:feat/native-windows-support

Conversation

@forlayo

Copy link
Copy Markdown

Linked issue

Addresses #180 ("Windows build") — adds full native Windows support for the runtime, CLI/TUI, web UI, integrated terminal, desktop Electron app, installer, CI, and offline test suite (without requiring WSL).

What changed (Before / After)

  • Before: Running freehand on native Windows exited immediately with "Freehand does not run natively on Windows yet (it requires POSIX bash)". POSIX-only primitives (fcntl.flock, os.killpg, os.openpty, termios, bash -lc, / path assumptions, 0o600 permission checks) prevented the runtime, CLI/TUI, snapshots, MCP stdio/daemon servers, integrated terminals, web UI, desktop app, and test suite from working natively on Windows.
  • After: Freehand runs natively end-to-end on Windows (win32) using native PowerShell (pwsh preferred, falling back to powershell.exe), Win32 LockFileEx, Win32 Job Objects, stdlib ctypes ConPTY integrated terminals, native Windows clipboard/editor/Explorer integrations, a native PowerShell installer (install.ps1), Windows NSIS Electron packaging & auto-updates, and windows-latest CI/release workflows — with zero new Python or JS dependencies and zero changes to macOS, Linux, or benchmark container behavior.

Summary of changes by area

  1. Stdlib-only Python 3.9+ Windows runtime primitives (src/freehand/runtime/osutil.py, agent.py, providers.py, shellenv.py, auth.py, copilot.py, calltrace.py)

    • Native PowerShell execution: find_shell() prefers pwsh and falls back to powershell.exe (never invoking WSL's System32\bash.exe). prepare_shell_command() sets UTF-8 console encoding, initializes $global:LASTEXITCODE = 0, preserves native command exit codes accurately, and automatically falls back to a temporary .ps1 -File script when commands exceed 20,000 characters (avoiding the 32 KB CreateProcess command-line limit). Output \r\n is normalized to \n.
    • Cross-platform file locking: fcntl.flock on POSIX, Win32 LockFileEx/UnlockFileEx via ctypes.windll.kernel32 + msvcrt.get_osfhandle on Windows. On Windows, session lock files live under $FREEHAND_HOME/locks/session-<sha256>.lock so session.trash() can hold the exclusive lock across shutil.move without hitting WinError 32.
    • Win32 Job Objects & process trees: create_process_job / assign_process_job / kill_process_tree replace os.killpg / SIGKILL on Windows (JOB_OBJECT_LIMIT_BREAKAWAY_OK, intentionally without KILL_ON_JOB_CLOSE so detached background jobs outlive normal exit while TerminateJobObject kills the entire tree on timeout/cancel/interrupt).
    • Retry-safe atomic writes: replace_file retries transient Windows PermissionError (WinError 5/32), and atomic_write_bytes/atomic_write_text use unique per-call temp filenames with guaranteed cleanup.
    • Immediate Winsock cancel: On Windows, sock.shutdown(SHUT_RDWR) alone does not wake a thread blocked in recv(), and sock.close() defers while http.client's makefile() holds _io_refs. _abort_socket() and Agent.cancel() invoke _real_close() on Windows so stopping a turn during TTFT or mid-stream aborts immediately.
    • Model-facing text policy: Kept the tool name "bash" on all platforms for full transcript, journal, provider, Copilot bridge, hook, and UI compatibility. Updated _tool_specs(), session.environment(), and session.own_command() exclusively under win32 to accurately describe PowerShell; macOS, Linux, and Linux benchmark containers are byte-for-byte unchanged.
  2. CLI, TUI, Server, Snapshots, Workbench, Hooks, Daemon, MCP & Limits (src/freehand/cli.py, session.py, control.py, server.py, workbench.py, snapshots.py, inputs.py, tui.py, ui.py, daemon.py, hooks.py, mcp.py, limits.py, copilot_bridge.py, integrations/harbor.py)

    • Removed the win32 hard block in cli.main(), enabled UTF-8 console stdio + ENABLE_VIRTUAL_TERMINAL_PROCESSING, added SIGBREAK graceful shutdown to freehand web, and updated freehand doctor for PowerShell, Windows user ACLs, and native clipboard reporting.
    • Native Win32 CF_UNICODETEXT clipboard copy (tui.py), PowerShell System.Windows.Forms.Clipboard image paste (inputs.py), os.startfile / explorer.exe /select,<path> (handling Explorer's exit code 1) (server.py, workbench.py), and .cmd/.exe resolution via osutil.resolve_executable (mcp.py, limits.py, server.py, workbench.py, tui.py).
    • Fixed prompt_toolkit NoConsoleScreenBufferError under redirected/dummy outputs on Windows by wrapping Interactive.run() in create_app_session(input=..., output=...), and ensured clear_input() calls load_history_if_not_yet_loaded() so ↑ immediately restores cleared drafts.
    • Fixed ProjectHistory CRLF handling, Windows backslash-escaped space image paths (\ ), Controller.shell() [stopped] detection on Job Object termination, workbench.parse_mcp Windows quote/backslash tokenization, ConnectionAbortedError (WinError 10053) handling in server.py, and snapshots.py excluding FREEHAND_HOME/git_dir when working in an ancestor directory.
  3. Win32 ConPTY Integrated Terminal (src/freehand/winpty.py, src/freehand/terminals.py)

    • Stdlib-only ctypes wrapper (ConPtyProcess) around CreatePseudoConsole, ResizePseudoConsole, and ClosePseudoConsole (with STARTF_USESTDHANDLES isolation so redirected parent pipes do not hijack child stdio, plus Job Object cleanup). No pywinpty or native binary wheel dependency required.
  4. Web UI Windows Path & Paste Support (src/freehand/web/app.js, workbench.js, md.js, panels.js)

    • Added drive-letter and backslash-aware helpers (pathSep, joinPath, normPath, pathInside), updated short, baseName, langOf, skills filtering, folder breadcrumbs, changed-files filtering, and allowed Ctrl+V paste in the integrated terminal.
  5. Desktop Electron App, Installer, Packaging & CI (install.ps1, pyproject.toml, desktop/main.js, desktop/package.json, desktop/updates.js, desktop/scripts/release-updates.js, desktop/scripts/bundle-cli.js, desktop/scripts/render-icons.py, desktop/build/icon.ico, desktop/build/icons.json, .github/workflows/ci.yml, .github/workflows/desktop-release.yml, .github/scripts/ci.py, .github/scripts/npm_audit.py, README.md, README.zh-CN.md, desktop/README.md)

    • Added install.ps1 mirroring install.sh (installs uv if needed, installs Freehand via uv tool install --upgrade --python 3.12, respects FREEHAND_INSTALL_SPEC).
    • Added Windows x64 NSIS desktop target (Freehand-Setup-${version}.exe), multi-size desktop/build/icon.ico, cross-platform PyInstaller bundler (desktop/scripts/bundle-cli.js with --hidden-import freehand.winpty), freehand.exe/freehand.cmd discovery + windowsHide in desktop/main.js, and win32/x64 release manifest & updater support.
    • Added windows-latest to CI (core, browser, install-script) and desktop-release.yml (package).
  6. Cross-platform Test Suite & Dedicated Windows Coverage (tests/test_windows_support.py, tests/fakes.py, tests/pty_driver.py, tests/repl_driver.py, tests/conftest.py, tests/test_web_e2e.py, and targeted cross-platform test updates)

    • Added tests/test_windows_support.py covering osutil locks, Job Object tree termination, PowerShell exit codes and >20 KB command fallback, ConPTY interactive I/O/resize/Ctrl-C, web JS Windows path helpers, and install.ps1 verification in tests/test_packaging.py.
    • Fixed a Windows-specific CDPPage Chrome deadlock (4 KB anonymous stderr pipe filling under Chrome's verbose logs) by logging Chrome stderr to a file inside user_dir, pinned en-US locale in CDPPage for deterministic number formatting across non-English developer machines, and added Driver.close() teardown cleanup so failed tests never leave Win32PipeInput executor threads blocking pytest exit.

Visual proof (UI / TUI / Web / Desktop / export changes)

Native Windows freehand doctor output (Windows 11, Python 3.12.13, PowerShell 7):

Freehand 0.1.3 doctor (win32, Python 3.12.13)
  ✓ git              git version 2.55.0.windows.5
  ✓ shell            C:\Program Files\PowerShell\7\pwsh.EXE
  ✗ credentials      not configured — run `freehand login` or set an API key
  ✓ proxy            NO_PROXY=127.0.0.1,localhost,::1
  ✓ tools            editor=unset, clipboard=windows, node=yes
  ✓ disk             0 B (empty)

Real browser UI, integrated ConPTY terminal, file preview matrix (HTML, Markdown, PNG, PDF, CSV/TSV, code, downloads, right-click menus), and fullscreen TUI were all exercised directly on native Windows via the offline browser and PTY test suites (440/440 browser tests + 4/4 ConPTY fullscreen tests passing).

How you verified it

All checks were run natively on Windows (win32, Python 3.12.13 via uv, Python 3.9 via uv, Node.js v24.19.0, Google Chrome 158):

  • Lint: uv run --no-sync pyflakes src tests .github/scripts → prints nothing (0 warnings).
  • Python 3.9 stdlib-only runtime check:
    uv run --no-project --python 3.9 python -I -c "import sys; sys.path.insert(0, 'src/freehand/runtime'); import agent, providers, auth, shellenv, wsclient, calltrace, osutil, copilot" → passed.
  • JS syntax check: node --check on every .js file in src/freehand/web/, desktop/, and desktop/scripts/ → passed.
  • Full Core Suite (--suite=core, 3 parallel shards):
    • Shard 1/3: 665 passed, 15 skipped, 0 failed
    • Shard 2/3: 633 passed, 15 skipped, 0 failed (632 + test_esc_esc_clears_the_input_and_up_brings_it_back verified 3/3 after adding load_history_if_not_yet_loaded() to clear_input())
    • Shard 3/3: 651 passed, 11 skipped, 0 failed
    • Total Core: 1,949 passed, 0 failed.
  • Full Real-Browser Suite (--suite=browser --require-browser, 3 shards on real Chrome 158):
    • Shard 1/3: 151 passed, 0 failed
    • Shard 2/3: 156 passed, 0 failed
    • Shard 3/3: 133 passed, 0 failed (including test_web_file_review.py 2/2 in 13.52s)
    • Total Browser: 440 passed, 0 failed.
  • Desktop / Electron checks (inside desktop/):
    • python ../.github/scripts/npm_audit.py → clean (no unreviewed advisories)
    • npm run test:build-deps → passed
    • npm run test:updates → 22 + 19 tests passed, 0 failed
    • node ../tests/desktop_development.js (POSIX + Windows findFreehand), desktop_recovery.js, desktop_service.js → all passed
  • Post-rebase verification on latest microsoft/FreeHand:main (7660526, v0.1.3): re-ran pyflakes, Python 3.9 stdlib check, test_windows_support.py, test_packaging.py, test_release_workflows.py, test_brand_assets.py, test_tui_details.py (54 passed), and all desktop tests (41+ passed).

AI disclosure & checklist

  • AI disclosure: AI-assisted (personally tested and verified natively on Windows across the full core, real-browser, and desktop suites)
  • uv run pyflakes src tests .github/scripts prints nothing and relevant tests pass locally (full cross-OS suite runs in CI)
  • Left CHANGELOG.md untouched (maintainers update it at release time)
  • No change to what the model sees on macOS, Linux, or benchmark containers (prompt.md, tool descriptions, status line, harness notes are byte-for-byte unchanged on POSIX); on native Windows only (sys.platform == "win32"), the tool description and environment block accurately describe PowerShell while keeping the tool name "bash"
  • src/freehand/runtime/ still uses only the standard library and imports on Python 3.9

Copilot AI balanced review requested due to automatic review settings December 6, 2026 11:47
@github-actions

github-actions Bot commented Dec 6, 2026

Copy link
Copy Markdown

Thanks for the pull request! A few friendly reminders based on the files changed:

  • Model-facing / runtime core: This PR touches benchmark-sensitive or Python 3.9 stdlib runtime files (src/freehand/integrations/harbor.py, src/freehand/runtime/agent.py, src/freehand/runtime/auth.py, src/freehand/runtime/calltrace.py ...). Please make sure Python 3.9 stdlib imports still pass and attach benchmark evidence if model-visible behaviour changed.

(This comment updates automatically when you edit the PR description or push new commits.)

@forlayo

Copy link
Copy Markdown
Author

@microsoft-github-policy-service agree

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved critical defects can clear clipboard contents, hang process timeouts and terminal shutdown, and break Windows release builds.

12 open issues
What changed in this PR

Adds native Windows support across Freehand’s runtime, interfaces, desktop packaging, and CI, addressing #180 without requiring WSL.

Changes:

  • Introduces PowerShell execution, Windows locking and process management, and ConPTY terminals.
  • Adapts clipboard, editor, path, and file handling for Windows.
  • Adds Windows installation and desktop releases, with cross-platform test coverage.
File Description
tests/​test_workbench.py Adapts terminal and editor tests.
tests/​test_windows_support.py Adds dedicated Windows coverage.
tests/​test_web_workbench.py Uses portable terminal commands.
tests/​test_web_ui.py Adapts paths and Unicode fixtures.
tests/​test_web_panels.py Sends JavaScript through stdin.
tests/​test_web_no_project.py Uses portable file commands.
tests/​test_web_files.py Adapts Windows file checks.
tests/​test_web_e2e.py Supports Windows browser discovery and logging.
tests/​test_web_e2e_more.py Controls fixture line endings.
tests/​test_ux_matrix.py Tests native CLI execution.
tests/​test_usercommands.py Normalizes path assertions.
tests/​test_tui_fixes.py Makes command fixtures portable.
tests/​test_tui_details.py Uses portable editor fixtures.
tests/​test_tui_audit.py Replaces shell-specific editor fixture.
tests/​test_trust.py Escapes project keys correctly.
tests/​test_terminal.py Adapts permissions and file commands.
tests/​test_terminal_theme.py Guards POSIX-only tests.
tests/​test_terminal_startup_cleanup.py Isolates POSIX descriptor checks.
tests/​test_snapshots.py Adapts encoding and path assertions.
tests/​test_snapshot_repositories.py Normalizes relative paths.
tests/​test_setup.py Guards POSIX permission assertions.
tests/​test_server.py Adapts interrupts and JavaScript execution.
tests/​test_runtime.py Uses portable transcript-editing commands.
tests/​test_release_workflows.py Verifies Windows release configuration.
tests/​test_providers.py Measures latency from cancellation.
tests/​test_packaging.py Adds PowerShell installer tests.
tests/​test_no_project.py Uses portable workspace commands.
tests/​test_interactive.py Adapts signals and process checks.
tests/​test_inputs.py Isolates platform mocks and paths.
tests/​test_image_recovery.py Makes transcript edits portable.
tests/​test_hardening.py Tests shared locking and atomic writes.
tests/​test_gitflow.py Adapts Git input and terminal scripts.
tests/​test_fullscreen.py Accommodates ConPTY terminal modes.
tests/​test_file_index_paths.py Skips Windows-invalid filenames.
tests/​test_desktop_workbench.py Updates packaging assertions.
tests/​test_desktop_service_ui.py Reads launcher source as UTF-8.
tests/​test_daemon.py Guards POSIX permission assertions.
tests/​test_connections.py Guards POSIX credential modes.
tests/​test_ci.py Parses test sources as UTF-8.
tests/​test_chat_images.py Uses portable transcript edits.
tests/​test_brand_assets.py Validates Windows icon packaging.
tests/​test_auth.py Guards POSIX credential modes.
tests/​test_anthropic_images.py Uses portable image-transcript edits.
tests/​repl_driver.py Adds failed-test teardown cleanup.
tests/​pty_driver.py Adds ConPTY-backed test sessions.
tests/​fakes.py Adds portable command and process helpers.
tests/​desktop_updates.js Checks Windows installer selection.
tests/​desktop_service.js Uses platform-aware test paths.
tests/​desktop_release_updates.js Tests Windows release artifacts.
tests/​desktop_recovery.js Guards POSIX permission assertions.
tests/​desktop_development.js Tests Windows CLI discovery.
tests/​conftest.py Cleans up remaining interactive drivers.
src/​freehand/​workbench.py Adapts parsing, paths, and native actions.
src/​freehand/​winpty.py Implements the ConPTY backend.
src/​freehand/​web/​workbench.js Uses cross-platform path helpers.
src/​freehand/​web/​panels.js Allows Ctrl+V terminal paste.
src/​freehand/​web/​md.js Recognizes Windows path separators.
src/​freehand/​web/​app.js Adds path joining and comparison helpers.
src/​freehand/​ui.py Adapts terminal sessions and editor launching.
src/​freehand/​tui.py Adds Windows clipboard and editor support.
src/​freehand/​terminals.py Integrates ConPTY terminals.
src/​freehand/​snapshots.py Adapts locking, exclusions, and restoration.
src/​freehand/​session.py Adapts persistence, locks, and environment context.
src/​freehand/​server.py Adapts native actions and connection handling.
src/​freehand/​runtime/​shellenv.py Handles case-insensitive Windows environments.
src/​freehand/​runtime/​providers.py Adapts socket cancellation and workdirs.
src/​freehand/​runtime/​osutil.py Centralizes cross-platform OS primitives.
src/​freehand/​runtime/​copilot.py Adapts bridge persistence and process cleanup.
src/​freehand/​runtime/​calltrace.py Writes consistent trace line endings.
src/​freehand/​runtime/​auth.py Uses shared locking and private writes.
src/​freehand/​runtime/​agent.py Integrates Windows execution and cancellation.
src/​freehand/​mcp.py Adapts executable resolution and daemon startup.
src/​freehand/​limits.py Adapts tool discovery and process cleanup.
src/​freehand/​integrations/​harbor.py Normalizes container script line endings.
src/​freehand/​inputs.py Adds Windows image paste and shell execution.
src/​freehand/​hooks.py Runs Windows hooks through PowerShell.
src/​freehand/​daemon.py Adapts background launch and state writes.
src/​freehand/​copilot_bridge.py Configures UTF-8 protocol streams.
src/​freehand/​control.py Adapts locks, cancellation, and image URLs.
src/​freehand/​cli.py Enables native Windows CLI operation.
README.zh-CN.md Documents Windows installation in Chinese.
README.md Documents native Windows installation.
pyproject.toml Declares Windows platform support.
install.ps1 Adds the PowerShell installer.
desktop/​updates.js Selects Windows update installers.
desktop/​scripts/​render-icons.py Generates multi-size Windows icons.
desktop/​scripts/​release-updates.js Merges and publishes Windows artifacts.
desktop/​scripts/​bundle-cli.js Adds cross-platform CLI bundling.
desktop/​README.md Documents Windows desktop builds.
desktop/​package.json Configures NSIS packaging and portable scripts.
desktop/​main.js Adapts Windows discovery and service launch.
desktop/​build/​icons.json Updates icon checksums.
.github/​workflows/​desktop-release.yml Adds Windows release packaging.
.github/​workflows/​ci.yml Adds Windows test and installer jobs.
.github/​scripts/​npm_audit.py Resolves npm and uses UTF-8.
.github/​scripts/​ci.py Uses UTF-8 for CI metadata.

Review effort: Balanced

fail-fast: false
matrix:
os: [macos-15, macos-15-intel, ubuntu-24.04]
os: [macos-15, macos-15-intel, ubuntu-24.04, windows-latest]
Comment thread desktop/build/icons.json
{
"sha256": {
"src/freehand/web/favicon.svg": "d1dc05d0a29946bf085045cfd2bbff9a8d1a21503de9ae9b83263462e5611077",
"src/freehand/web/favicon.svg": "0b0c313413caec86c745bebdea3e692e4c74b9daae627f60c499f141825bd2f6",
Comment on lines +353 to +354
if _kernel32.TerminateJobObject(job, 1):
return
Comment thread src/freehand/tui.py
k32.GlobalFree.argtypes = [wintypes.HGLOBAL]
k32.GlobalFree.restype = wintypes.HGLOBAL
raw = text.encode("utf-16-le") + b"\x00\x00"
if not u32.OpenClipboard(None):
Comment thread src/freehand/winpty.py
_k32.CloseHandle(in_write)
if hpc:
# ClosePseudoConsole notifies the attached console process to exit and unblocks ReadFile on out_read.
_k32.ClosePseudoConsole(hpc)
if not IS_WINDOWS:
return
import sys
for stream in (sys.stdout, sys.stderr):
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:
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"))
Comment thread src/freehand/web/app.js
Comment on lines +305 to +309
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));
Comment on lines +173 to +183
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")

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants