Skip to content

post-commit hook launcher pops a focus-stealing console window on every Windows commit — DETACHED_PROCESS on a console-subsystem sys.executable #2253

Closed

Description

@OdinMB

By Claude Code, Opus 5, after I fixed the issue in the title locally. I can only vouch for the title issue. AI analysis and suggestions could be completely wrong.

Summary:
After graphify hook install, every git commit that touches a code file opens a new console window that takes keyboard focus, then closes when the background rebuild finishes (~40s here). The window is produced by the very flag that was meant to hide the child process. The detach logic added for #1161 is correct; only the Windows console handling is wrong.

Environment:

  • OS: Windows 11
  • Shell: Git for Windows (Git Bash / MSYS)
  • Python: 3.12
  • Graphify: 0.9.27, installed via uv tool install graphifyy (root cause re-verified against branch v8)

Reproduction Steps:

  1. graphify hook install in any repo
  2. Edit a code file, git commit
  3. Observe a new console window appear and grab focus for the duration of the rebuild

Expected Behavior:
The rebuild runs detached and invisibly. Its output already goes to the rebuild log, so it needs no console.

Actual Behavior:
A conhost window is created, shown, and focused for ~40s on every commit. On a normal commit cadence this is highly disruptive — it steals keystrokes from the editor mid-typing.

Root Cause:
graphify/hooks.py, _LAUNCHER_TEMPLATE (≈L221–242 in 0.9.27; unchanged on v8):

_kw = dict(stdout=_out, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, cwd=os.getcwd(), close_fds=True)
_cmd = [sys.executable, '-c', _src]
if os.name == 'nt':
    _flags = 0x00000008 | 0x00000200  # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
    try:
        subprocess.Popen(_cmd, creationflags=_flags | 0x01000000, **_kw)  # + CREATE_BREAKAWAY_FROM_JOB
    except OSError:
        subprocess.Popen(_cmd, creationflags=_flags, **_kw)
else:
    subprocess.Popen(_cmd, start_new_session=True, **_kw)

sys.executable here is python.exe, a console-subsystem binary — the hook resolves $GRAPHIFY_PYTHON to it, and the launcher re-spawns sys.executable for the child. DETACHED_PROCESS (0x00000008) tells Windows not to give the child the parent's console. For a console-subsystem binary that does not mean "no console": the child gets its own new conhost, which is created shown and focused. The flag intended to hide the process is what produces the window.

Why this regressed from #1161:
#1161 replaced nohup ... & (absent from Git for Windows' MSYS runtime, so the rebuild silently never ran) with subprocess.Popen + DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP — the flags named in that issue's own Suggested Fix section. That fix is right about detachment: the process does survive the hook and does break out of git's job object. It just picked the one detach flag that materialises a console for a console-subsystem child. This is a UX regression on top of a correct correctness fix, not a reason to revert #1161.

Suggested Fixes (either works; the first is more robust):

1. Run the child under the GUI-subsystem interpreter. pythonw.exe sits next to python.exe in every CPython, venv, and uv-tool layout, and a GUI-subsystem process can never be given a console under any flag combination:

_exe = sys.executable
if os.name == 'nt':
    _cand = os.path.join(os.path.dirname(_exe), 'pythonw.exe')
    if os.path.exists(_cand):
        _exe = _cand
_cmd = [_exe, '-c', _src]

2. Or use CREATE_NO_WINDOW (0x08000000) — the documented flag for "console application run without a console window" — in place of DETACHED_PROCESS, not alongside it. Windows treats DETACHED_PROCESS, CREATE_NEW_CONSOLE, and CREATE_NO_WINDOW as mutually exclusive; passing two is an invalid parameter. CREATE_NEW_PROCESS_GROUP and CREATE_BREAKAWAY_FROM_JOB stay as they are, so #1161's detachment is preserved.

Belt and braces would be both: prefer pythonw.exe when it exists, and swap DETACHED_PROCESS for CREATE_NO_WINDOW so the fallback path is also quiet.

Either way the child needs no console: stdout/stderr are already redirected to the log file and stdin is DEVNULL.

One authoring note for whoever patches this — per the docblock on _REBUILD_BODY_COMMIT, these templates are carried inside a double-quoted sh -c "..." argument and must contain no ", $, backtick, or backslash. The snippet above complies (single quotes only, os.path.join); an f-string or a literal \\ would break the hook script.

Workaround (available today):
Re-pin the hook to pythonw.exe. graphify hook install bakes sys.executable into the hook as _PINNED (#2166), and the launcher spawns sys.executable, so installing from pythonw propagates all the way to the detached child:

graphify hook uninstall
"$(uv tool dir)/graphifyy/Scripts/pythonw.exe" -m graphify hook install

The uninstall step is required — see below. The pinned pythonw.exe path passes _pinned_python()'s allowlist, and the hook's _GFY_PROBE uses sys.exit(...) with no print, so it is unaffected by pythonw's null sys.stdout.


Secondary (related, smaller): hook install over an existing graphify hook is a silent no-op.

_install_hook() returns f"already installed at {hook_path}" and writes nothing whenever the marker is already present, and install() exposes no --force. So a user re-running graphify hook install to change the pinned interpreter — exactly the workaround above — or to pick up a newer graphify's hook script gets a no-op with a message that reads like success. A --force flag, or at minimum wording that says the existing hook was left untouched and may be stale, would help. Happy to split this into its own issue if preferred.

Activity

  1. safishamsi commented on Jul 28, 2026

    @safishamsi
    Member

    Fixed in v0.9.29 (#2254, thanks @hopstreax). The post-commit hook launcher uses CREATE_NO_WINDOW, so it no longer pops a focus-stealing console window on Windows. https://github.com/Graphify-Labs/graphify/releases/tag/v0.9.29

  2. leonjeng commented on Oct 19, 2026

    @leonjeng

    Confirming this on another machine, with one detail that I think is worth pinning to the thread because it changes what the symptom looks like on multi-core boxes: under DETACHED_PROCESS the launcher child itself never gets a console — it is the ProcessPoolExecutor workers in extract.py that each get a new, visible console. So instead of one focus-stealing window per commit you get min(os.cpu_count(), uncached_files) windows at once (12 here), Windows 11 hands them to Windows Terminal, and they all close a few seconds later when the workers exit. Someone searching for "a burst of a dozen terminal windows that close themselves" may not connect it to this title, hence the data point.

    Environment

    • Windows 11 Home 23H2 (build 22631), Windows Terminal 1.24.12741.0 as the default terminal (the "Let Windows decide" default)
    • CPython 3.11.9 (per-user install under %LOCALAPPDATA%\Programs\Python\Python311, not the Store build), graphifyy 0.8.36 via pip; hooks written by that version's graphify hook install
    • Git for Windows; triggers were git commit and git worktree add (post-commit / post-checkout)
    • 12 logical CPUs; rebuild log says AST extraction: 851/851 files (100%) [12 workers]

    Symptom: ~3 s after a commit, a burst of Windows Terminal windows titled C:\Users\<me>\AppData\Local\Programs\Python\Python311\python.exe pops up, sits for ~5 s, then all of them close; one shows the WT "[process exited with code …]" banner. The rebuild log for that run says [12 workers]; a 250 ms process watcher saw 1 WindowsTerminal.exe + 8 OpenConsole.exe + 9 python.exe born in a single tick, 3 s after the first OpenConsole.exe (the one that had to start WT).

    Mechanism (verified with the script below)

    1. _LAUNCHER_TEMPLATE spawns the rebuild with DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP. That process really has no console: GetConsoleWindow() returns NULL inside it. The launcher child is invisible, as the flag promises.
    2. _rebuild_code → extract.py opens ProcessPoolExecutor(max_workers=min(cpu_count, len(uncached_work))) (0.8.36: ≈L11202–L11210). multiprocessing starts each worker as python.exe -c "from multiprocessing.spawn import spawn_main; …" with creationflags 0.
    3. A console-subsystem child whose parent has no console gets a brand-new console allocated by Windows, and it is created visible. One per worker.
    4. With Windows Terminal as the default terminal host, every one of those consoles becomes a WT window (one OpenConsole.exe each). The first one has to start WindowsTerminal.exe (~3 s on this machine), so all the workers' windows appear in one burst once it is up.
    5. The pool finishes → workers exit → windows close.

    With CREATE_NO_WINDOW the rebuild process gets a console host with no window (GetConsoleWindow() is NULL for it too, but a conhost.exe is attached — see the census below), the workers inherit that console, and nothing is ever shown. Same fix as 3bac3df; this is just the "why N windows" part.

    Minimal repro — no graphify needed. The parent spawns a child with the flag under test, the child runs a 2-worker pool exactly like extract.py, each worker reports its own console HWND, and the parent counts OpenConsole / WindowsTerminal processes meanwhile:

    """python repro_console_windows.py detached   # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP (<=0.9.28 launcher)
       python repro_console_windows.py nowindow   # CREATE_NO_WINDOW  | CREATE_NEW_PROCESS_GROUP (3bac3df)"""
    import ctypes, json, os, subprocess, sys, time
    from concurrent.futures import ProcessPoolExecutor
    
    WORKERS, HOLD_SECONDS = 2, 2
    
    def _console_state():
        hwnd = ctypes.windll.kernel32.GetConsoleWindow()
        return {"console_hwnd": hwnd, "visible": bool(ctypes.windll.user32.IsWindowVisible(hwnd)) if hwnd else False}
    
    def worker(i):
        state = _console_state()
        time.sleep(HOLD_SECONDS)
        return {"worker": i, "pid": os.getpid(), **state}
    
    def census():
        out = subprocess.run(["tasklist", "/FO", "CSV", "/NH"], capture_output=True, text=True).stdout
        names = [line.split('","')[0].strip('"') for line in out.splitlines() if line.strip()]
        return {n: names.count(n) for n in ("OpenConsole.exe", "WindowsTerminal.exe", "conhost.exe")}
    
    if __name__ == "__main__":
        mode = sys.argv[1]
        if mode == "child":
            parent = {"parent_pid": os.getpid(), **_console_state()}
            with ProcessPoolExecutor(max_workers=WORKERS) as pool:
                results = list(pool.map(worker, range(1, WORKERS + 1)))
            with open(sys.argv[2], "a", encoding="utf-8") as f:
                f.write(json.dumps({"parent": parent, "workers": results}) + "\n")
            sys.exit(0)
        flags = {"detached": 0x00000008 | 0x00000200, "nowindow": 0x08000000 | 0x00000200}[mode]
        log = os.path.join(os.path.dirname(os.path.abspath(__file__)), f"repro-{mode}.log")
        if os.path.exists(log):
            os.remove(log)
        baseline = census()
        subprocess.Popen([sys.executable, os.path.abspath(__file__), "child", log], creationflags=flags,
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, close_fds=True)
        peak, deadline = dict(baseline), time.time() + 10
        while time.time() < deadline:
            for k, v in census().items():
                peak[k] = max(peak[k], v)
            if os.path.exists(log) and time.time() > deadline - 7:
                break
            time.sleep(0.5)
        print(f"mode={mode} flags=0x{flags:08X}")
        for k in baseline:
            print(f"  {k:20s} {baseline[k]:3d} -> {peak[k]:3d}   (+{peak[k] - baseline[k]})")
        print(open(log, encoding="utf-8").read().strip())

    Output on this machine (Python 3.11.9, WT 1.24; JSON re-wrapped for readability):

    mode=detached flags=0x00000208
      OpenConsole.exe        0 ->   2   (+2)
      WindowsTerminal.exe    0 ->   1   (+1)
      conhost.exe          129 -> 131   (+2)
    {"parent": {"parent_pid": 69892, "console_hwnd": 0, "visible": false},
     "workers": [{"worker": 1, "pid": 138176, "console_hwnd": 27334552, "visible": true},
                 {"worker": 2, "pid": 139648, "console_hwnd": 176168606, "visible": true}]}
    
    mode=nowindow flags=0x08000200
      OpenConsole.exe        0 ->   0   (+0)
      WindowsTerminal.exe    0 ->   0   (+0)
      conhost.exe          128 -> 133   (+5)
    {"parent": {"parent_pid": 140160, "console_hwnd": 0, "visible": false},
     "workers": [{"worker": 1, "pid": 139912, "console_hwnd": 0, "visible": false},
                 {"worker": 2, "pid": 139640, "console_hwnd": 0, "visible": false}]}
    

    Parent: no console either way. Workers: a visible console each under DETACHED_PROCESS, none under CREATE_NO_WINDOW (the conhost.exe delta in the second run is the windowless host; no OpenConsole / WindowsTerminal means nothing was shown).

    Fix: identical to 3bac3df, one line in _LAUNCHER_TEMPLATE:

    -    _flags = 0x00000008 | 0x00000200  # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
    +    _flags = 0x08000000 | 0x00000200  # CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP

    Applied to the two installed hooks and the local 0.8.36 hooks.py, then re-triggered a real post-checkout (git worktree add) with the watcher running: rebuild completed (851 files, 12 workers, 9427 nodes), all 12 spawn_main workers sat under one hidden conhost, 0 OpenConsole / 0 WindowsTerminal.

    Two notes

    • Anyone whose hooks were written by a release before 0.9.29 keeps the old launcher after upgrading (Upgrading doesn't refresh already-installed git hooks: #2253 console-window fix never reaches existing repos (or init.templateDir) #3771): patch the flag in .git/hooks/post-commit / post-checkout in place, or re-run graphify hook install after the upgrade.
    • The "Last resort" probe in the same hook (python3 -c … tried before python -c …; 0.8.36 hooks.py L64–68, still L131–135 in 0.9.92) has a separate Windows window problem. With the Microsoft Store app-execution alias on (the Windows default) and no Store Python installed, command -v python3 resolves to …\AppData\Local\Microsoft\WindowsApps\python3.exe (AppInstallerPythonRedirector); running it opens a visible console for ~1.1 s and exits 9009. Measured directly on this machine (3 runs, ~1.1 s each). My hook never reached that branch because the pinned interpreter has graphify, so this is latent rather than something I hit through the hook — but every commit on a machine where the earlier probes miss would flash a window before falling through to python. Probing python before python3 on Windows, or skipping a candidate under \WindowsApps\, avoids it. Filed separately as hooks: last-resort python3 probe launches the Microsoft Store redirector on Windows (visible console flash, exit 9009) #4563 so it does not get lost in a closed thread.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions