The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): hide Electron git spawns with CREATE_NO_WINDOW
brooklyn!e4a2c105b9a7
diff --git a/apps/desktop/electron/desktop-plugin-install.ts b/apps/desktop/electron/desktop-plugin-install.tsindex f384db7caf5..ebb8e1a3bde 100644--- a/apps/desktop/electron/desktop-plugin-install.ts+++ b/apps/desktop/electron/desktop-plugin-install.ts@@ -4,13 +4,14 @@* async entry points with a resolved git binary.*/-import { execFile, spawn } from 'node:child_process'+import { spawn } from 'node:child_process'import fs from 'node:fs'import fsp from 'node:fs/promises'import os from 'node:os'import path from 'node:path'import { publishDesktopTree, writeDesktopHalfMarker } from './desktop-plugins-root'+import { execGit, hiddenGitSpawnSpec } from './no-console-git'const GITHUB_BROWSER_SEGMENTS = new Set(['tree', 'blob', 'commit'])@@ -267,12 +268,12 @@ const GIT_TIMEOUT_MS = 300_000function runGit(gitBin: string, args: string[], cwd?: string): Promise<{ code: number; stderr: string }> {return new Promise((resolve, reject) => {- const child = spawn(gitBin, args, {+ const spec = hiddenGitSpawnSpec(gitBin, args, {cwd,env: noninteractiveGitEnv(),- stdio: ['ignore', 'ignore', 'pipe'],- windowsHide: true+ stdio: ['ignore', 'ignore', 'pipe']})+ const child = spawn(spec.command, spec.args, spec.options)let stderr = ''@@ -487,9 +488,8 @@ export async function installDesktopPluginFromGit(/** Resolve git binary via execFile which path on unix; caller passes Windows-resolved path. */export function runGitVersion(gitBin: string): Promise<boolean> {- return new Promise(resolve => {- execFile(gitBin, ['--version'], { windowsHide: true, timeout: 5_000 }, err => {- resolve(!err)- })- })+ return execGit(gitBin, ['--version'], { timeoutMs: 5_000 }).then(+ result => result.code === 0,+ () => false+ )}diff --git a/apps/desktop/electron/git-review-ops.ts b/apps/desktop/electron/git-review-ops.tsindex 393ede5f85a..61c48578f3f 100644--- a/apps/desktop/electron/git-review-ops.ts+++ b/apps/desktop/electron/git-review-ops.ts@@ -11,6 +11,7 @@ import path from 'node:path'import simpleGit from 'simple-git'import { resolveRequestedPathForIpc } from './hardening'+import { execGit, noConsoleGitEnv, simpleGitBinary, windowsGitHost } from './no-console-git'const COMMIT_CONTEXT_DIFF_MAX_CHARS = 120_000const COMMIT_CONTEXT_UNTRACKED_MAX = 80@@ -51,13 +52,26 @@ function gitFor(cwd, gitBin) {// For spaced paths, opt into simple-git's trusted-binary escape hatch instead// of falling back to PATH (often absent in GUI-launched apps, and PATH lookup// could resolve a repo-local git.exe).- return simpleGit({+ // On Windows the binary tuple is [python.exe, host script]. simple-git has no+ // creationFlags slot; the script spawns the real git with CREATE_NO_WINDOW and+ // forwards argv unchanged.+ const host = windowsGitHost()+ const binary = simpleGitBinary(gitBin, host)+ const binaryParts = Array.isArray(binary) ? binary : [binary]+ const unsafe = binaryParts.some(part => /\s/.test(part)) || Boolean(gitBin && /\s/.test(gitBin))+ const git = simpleGit({baseDir: cwd,- binary: gitBin || 'git',+ binary,maxConcurrentProcesses: 4,trimmed: false,- ...(gitBin && /\s/.test(gitBin) ? { unsafe: { allowUnsafeCustomBinary: true } } : {})+ ...(unsafe ? { unsafe: { allowUnsafeCustomBinary: true } } : {})})++ if (Array.isArray(binary)) {+ return git.env(noConsoleGitEnv(process.env, gitBin || 'git'))+ }++ return git}// simple-git reports renames as `old => new` (and `dir/{old => new}/f`); resolve@@ -360,14 +374,13 @@ async function reviewDiff(repoPath, filePath, scope, baseRef, staged, gitBin) {// Untracked file: no worktree diff exists, so synthesize an all-add diff via// --no-index (exits non-zero by design when files differ, so go around// simple-git's reject-on-nonzero with a raw execFile).- return new Promise(resolve => {- execFile(- gitBin || 'git',- ['diff', '--no-index', '--', '/dev/null', filePath],- { cwd, windowsHide: true, timeout: 30_000, maxBuffer: 32 * 1024 * 1024 },- (_err, stdout) => resolve(String(stdout || ''))- )- })+ return execGit(gitBin || 'git', ['diff', '--no-index', '--', '/dev/null', filePath], {+ cwd,+ timeoutMs: 30_000+ }).then(+ result => result.stdout,+ () => ''+ )}// Working-tree-vs-HEAD diff for ONE file — the "what changed since the last@@ -398,14 +411,13 @@ async function fileDiffVsHead(repoPath, filePath, gitBin) {return ''}- return new Promise(resolve => {- execFile(- gitBin || 'git',- ['diff', '--no-index', '--', '/dev/null', filePath],- { cwd, windowsHide: true, timeout: 30_000, maxBuffer: 32 * 1024 * 1024 },- (_err, stdout) => resolve(String(stdout || ''))- )- })+ return execGit(gitBin || 'git', ['diff', '--no-index', '--', '/dev/null', filePath], {+ cwd,+ timeoutMs: 30_000+ }).then(+ result => result.stdout,+ () => ''+ )}async function reviewStage(repoPath, filePath, gitBin) {diff --git a/apps/desktop/electron/git-worktree-ops.ts b/apps/desktop/electron/git-worktree-ops.tsindex 992322936bc..4e51d5068f8 100644--- a/apps/desktop/electron/git-worktree-ops.ts+++ b/apps/desktop/electron/git-worktree-ops.ts@@ -2,29 +2,22 @@// fresh worktree the lightest way (`git worktree add -b`), list real worktrees,// and remove them. Git is the source of truth; the renderer just drives these.-import { execFile } from 'node:child_process'import fs from 'node:fs'import path from 'node:path'import { resolveRequestedPathForIpc } from './hardening'+import { execGit } from './no-console-git'function runGit(gitBin, args, cwd): Promise<string> {- return new Promise((resolve, reject) => {- execFile(- gitBin,- args,- { cwd, windowsHide: true, timeout: 30_000, maxBuffer: 8 * 1024 * 1024 },- (err, stdout, stderr) => {- if (err) {- err.stderr = String(stderr || '')- reject(err)-- return- }+ return execGit(gitBin, args, { cwd, timeoutMs: 30_000 }).then(result => {+ if (result.code !== 0) {+ const error = new Error(result.stderr || `git exited ${result.code}`) as Error & { stderr?: string }- resolve(String(stdout || ''))- }- )+ error.stderr = result.stderr+ throw error+ }++ return result.stdout})}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 05e08a58e1f..cd1d80a235d 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -344,6 +344,7 @@ import {} from './native-oauth'import { runNativeLogin } from './native-oauth-login'import { loadNativeTokenSet, type NativeTokenStoreIo, persistNativeTokenSet } from './native-token-store'+import { planNoConsoleGitSpawn, setNoConsoleGitRoots, windowsGitHost } from './no-console-git'import { registerNativeNotifications } from './notification-ipc'import { serializeJsonBody, setJsonRequestHeaders } from './oauth-net-request'import { LEGACY_OAUTH_PARTITION, resolveOauthPartition } from './oauth-partition'@@ -868,6 +869,7 @@ const HERMES_HOME: string = resolveDesktopHermesHome({// install.ps1 / install.sh use, so a desktop-only user and a CLI-only user end// up with identical layouts and can share one install.const ACTIVE_HERMES_ROOT = path.join(HERMES_HOME, 'hermes-agent')+setNoConsoleGitRoots([!IS_PACKAGED ? SOURCE_REPO_ROOT : null, ACTIVE_HERMES_ROOT])// VENV_ROOT — venv lives inside the repo, exactly like install.ps1 does it.const VENV_ROOT = path.join(ACTIVE_HERMES_ROOT, 'venv')// BOOTSTRAP_COMPLETE_MARKER — written by the first-launch bootstrap runner@@ -3104,14 +3106,24 @@ function resolveUpdateRoot() {function runGit(args, options: any = {}): Promise<{ code: number; stdout: string; stderr: string }> {return new Promise((resolve, reject) => {const gitBinary = resolveGitBinary()+ const gitArgs = IS_WINDOWS ? ['-c', 'windows.appendAtomically=false', ...args] : args+ const host = IS_WINDOWS ? windowsGitHost(true) : null+ const plan = planNoConsoleGitSpawn({+ gitBin: gitBinary,+ args: gitArgs,+ isWindows: IS_WINDOWS,+ pythonBin: host?.pythonBin ?? null,+ scriptPath: host?.scriptPath ?? null,+ env: { ...process.env, ...((options.env || {}) as any), GIT_TERMINAL_PROMPT: '0' }+ })const child = spawn(- gitBinary,- IS_WINDOWS ? ['-c', 'windows.appendAtomically=false', ...args] : args,+ plan.command,+ plan.args,hiddenWindowsChildOptions({cwd: options.cwd,- env: { ...process.env, ...((options.env || {}) as any), GIT_TERMINAL_PROMPT: '0' },- stdio: ['ignore', 'pipe', 'pipe']+ env: plan.env,+ stdio: plan.stdio}))diff --git a/apps/desktop/electron/no-console-git.test.ts b/apps/desktop/electron/no-console-git.test.tsnew file mode 100644index 00000000000..6c52aae1f42--- /dev/null+++ b/apps/desktop/electron/no-console-git.test.ts@@ -0,0 +1,134 @@+import assert from 'node:assert/strict'+import { execFileSync } from 'node:child_process'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'++import { test } from 'vitest'++import {+ CREATE_NO_WINDOW,+ NO_CONSOLE_GIT_SCRIPT,+ planNoConsoleGitSpawn,+ resolveNoConsolePython,+ simpleGitBinary+} from './no-console-git'++const gitArgs = ['-c', 'windows.appendAtomically=false', 'merge-base', '--is-ancestor', 'origin/main', 'HEAD']+const gitBin = 'C:\\Program Files\\Git\\cmd\\git.exe'++test('windows git spawn uses a CREATE_NO_WINDOW host and does not rewrite git argv', () => {+ const plan = planNoConsoleGitSpawn({+ gitBin,+ args: gitArgs,+ isWindows: true,+ pythonBin: 'C:\\hermes\\venv\\Scripts\\python.exe',+ scriptPath: 'C:\\hermes\\no-console-git.py',+ env: { GIT_TERMINAL_PROMPT: '0', PATH: 'C:\\Windows' }+ })++ assert.equal(plan.command, 'C:\\hermes\\venv\\Scripts\\python.exe')+ assert.deepEqual(plan.args, ['C:\\hermes\\no-console-git.py', ...gitArgs])+ assert.equal(plan.env.HERMES_GIT_ARGV0, JSON.stringify(gitBin))+ assert.equal(plan.env.GIT_TERMINAL_PROMPT, '0')+ assert.equal(plan.windowsHide, true)+ assert.deepEqual(plan.stdio, ['ignore', 'pipe', 'pipe'])+ assert.equal(plan.creationFlags, CREATE_NO_WINDOW)+ assert.equal(CREATE_NO_WINDOW, 0x08000000)+})++test('non-windows git spawn keeps the git binary and argv', () => {+ const plan = planNoConsoleGitSpawn({+ gitBin: '/usr/bin/git',+ args: ['status', '--porcelain'],+ isWindows: false,+ pythonBin: '/usr/bin/python3',+ scriptPath: '/tmp/host.py'+ })++ assert.equal(plan.command, '/usr/bin/git')+ assert.deepEqual(plan.args, ['status', '--porcelain'])+ assert.equal(plan.creationFlags, 0)+})++test('missing python does not rewrite git argv', () => {+ const plan = planNoConsoleGitSpawn({+ gitBin: 'git.exe',+ args: gitArgs,+ isWindows: true,+ pythonBin: null,+ scriptPath: 'C:\\hermes\\no-console-git.py'+ })++ assert.equal(plan.command, 'git.exe')+ assert.deepEqual(plan.args, gitArgs)+})++test('simple-git binary is the python host tuple on windows', () => {+ assert.deepEqual(+ simpleGitBinary('git.exe', {+ isWindows: true,+ pythonBin: 'C:\\hermes\\venv\\Scripts\\python.exe',+ scriptPath: 'C:\\hermes\\no-console-git.py'+ }),+ ['C:\\hermes\\venv\\Scripts\\python.exe', 'C:\\hermes\\no-console-git.py']+ )+})++test('python resolver skips pythonw and the WindowsApps stub', () => {+ const python = resolveNoConsolePython({+ isWindows: true,+ env: {+ HERMES_DESKTOP_PYTHON: 'C:\\Users\\me\\AppData\\Local\\Microsoft\\WindowsApps\\python.exe',+ HERMES_DESKTOP_HERMES_ROOT: 'D:\\hermes'+ },+ roots: ['E:\\src'],+ fileExists: () => true+ })++ assert.equal(python, path.win32.join('D:\\hermes', '.venv', 'Scripts', 'python.exe'))+ assert.equal(+ resolveNoConsolePython({+ isWindows: true,+ env: { HERMES_DESKTOP_PYTHON: 'C:\\hermes\\venv\\Scripts\\pythonw.exe' },+ roots: [],+ fileExists: () => true+ }),+ null+ )+ assert.equal(+ resolveNoConsolePython({+ isWindows: true,+ env: { HERMES_DESKTOP_PYTHON: 'C:\\Users\\me\\AppData\\Local\\Microsoft\\WindowsApps\\python.exe' },+ roots: [],+ fileExists: () => true+ }),+ null+ )+})++test('host script forwards git argv unchanged and sets CREATE_NO_WINDOW', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-no-console-git-'))++ try {+ const script = path.join(dir, 'host.py')++ fs.writeFileSync(script, NO_CONSOLE_GIT_SCRIPT)++ const out = execFileSync('python3', [script, ...gitArgs], {+ encoding: 'utf8',+ env: {+ ...process.env,+ HERMES_GIT_ARGV0: JSON.stringify(gitBin),+ HERMES_GIT_DRY_RUN: '1',+ HERMES_GIT_NO_CONSOLE: '1'+ }+ })+ const parsed = JSON.parse(out)++ assert.deepEqual(parsed.argv, [gitBin, ...gitArgs])+ assert.equal(parsed.creationflags, CREATE_NO_WINDOW)+ } finally {+ fs.rmSync(dir, { force: true, recursive: true })+ }+})diff --git a/apps/desktop/electron/no-console-git.ts b/apps/desktop/electron/no-console-git.tsnew file mode 100644index 00000000000..c4cb567ba13--- /dev/null+++ b/apps/desktop/electron/no-console-git.ts@@ -0,0 +1,284 @@+// Electron is a GUI-subsystem process, so a direct git.exe spawn allocates its+// own console even when Node's windowsHide is set. windowsHide is SW_HIDE and,+// from a console-less parent, does not stop that flash (hermes_cli/_subprocess_compat.py).+//+// The flag that does is CREATE_NO_WINDOW (0x08000000). A console-subsystem+// python.exe started with that flag owns one hidden console; git is then+// spawned from that host with the same flag, and the git argv is forwarded+// unchanged. simple-git cannot take a creation flag, so its binary tuple is+// [python, this host script].++import { spawn, type SpawnOptions } from 'node:child_process'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'++export const CREATE_NO_WINDOW = 0x08000000++export const NO_CONSOLE_GIT_SCRIPT = `import json, os, subprocess, sys+git = json.loads(os.environ["HERMES_GIT_ARGV0"])+argv = [git, *sys.argv[1:]]+kwargs = {"stdout": subprocess.PIPE, "stderr": subprocess.PIPE}+if sys.platform == "win32" or os.environ.get("HERMES_GIT_NO_CONSOLE") == "1":+ kwargs["creationflags"] = 0x08000000+if os.environ.get("HERMES_GIT_DRY_RUN") == "1":+ sys.stdout.write(json.dumps({"argv": argv, "creationflags": kwargs.get("creationflags", 0)}))+ raise SystemExit(0)+proc = subprocess.run(argv, **kwargs)+sys.stdout.buffer.write(proc.stdout or b"")+sys.stderr.buffer.write(proc.stderr or b"")+code = proc.returncode+raise SystemExit(code if isinstance(code, int) and code >= 0 else 1)+`++const PIPED_STDIO = ['ignore', 'pipe', 'pipe'] as const++export interface NoConsoleGitPlan {+ command: string+ args: string[]+ env: NodeJS.ProcessEnv+ windowsHide: boolean+ stdio: ['ignore', 'pipe', 'pipe']+ creationFlags: number+}++export interface NoConsoleGitHost {+ isWindows: true+ pythonBin: string+ scriptPath: string+}++let configuredRoots: string[] = []++export function setNoConsoleGitRoots(roots: Array<string | null | undefined | false>) {+ configuredRoots = roots.filter((root): root is string => Boolean(root))+}++function isPythonW(candidate: string) {+ return path.win32.basename(candidate).toLowerCase() === 'pythonw.exe'+}++function isWindowsAppsStub(candidate: string) {+ return candidate.replace(/\\/g, '/').toLowerCase().includes('/windowsapps/')+}++export function resolveNoConsolePython({+ isWindows,+ env = process.env,+ roots = configuredRoots,+ fileExists = fs.existsSync+}: {+ isWindows: boolean+ env?: NodeJS.ProcessEnv+ roots?: string[]+ fileExists?: (candidate: string) => boolean+}): string | null {+ if (!isWindows) return null++ const candidates: string[] = []+ const override = env.HERMES_DESKTOP_PYTHON++ if (override) candidates.push(override)++ const hermesRoot = env.HERMES_DESKTOP_HERMES_ROOT+ const searchRoots = hermesRoot ? [hermesRoot, ...roots] : roots++ for (const root of searchRoots) {+ if (!root) continue++ candidates.push(path.win32.join(root, '.venv', 'Scripts', 'python.exe'))+ candidates.push(path.win32.join(root, 'venv', 'Scripts', 'python.exe'))+ }++ for (const candidate of candidates) {+ if (!candidate || isPythonW(candidate) || isWindowsAppsStub(candidate)) continue++ try {+ if (fileExists(candidate)) return candidate+ } catch {+ continue+ }+ }++ return null+}++export function ensureNoConsoleGitScript(dir = os.tmpdir()) {+ const scriptPath = path.join(dir, 'hermes-no-console-git.py')++ try {+ if (fs.readFileSync(scriptPath, 'utf8') === NO_CONSOLE_GIT_SCRIPT) return scriptPath+ } catch {+ // Missing or unreadable: rewrite below.+ }++ fs.writeFileSync(scriptPath, NO_CONSOLE_GIT_SCRIPT, { encoding: 'utf8', mode: 0o600 })++ return scriptPath+}++export function windowsGitHost(isWindows = process.platform === 'win32'): NoConsoleGitHost | null {+ if (!isWindows) return null++ const pythonBin = resolveNoConsolePython({ isWindows: true })++ if (!pythonBin) return null++ try {+ return { isWindows: true, pythonBin, scriptPath: ensureNoConsoleGitScript() }+ } catch {+ return null+ }+}++export function noConsoleGitEnv(base: NodeJS.ProcessEnv | undefined, gitBin: string): NodeJS.ProcessEnv {+ const env: NodeJS.ProcessEnv = {}++ for (const [key, value] of Object.entries(base || {})) {+ if (value !== undefined) env[key] = value+ }++ env.HERMES_GIT_ARGV0 = JSON.stringify(gitBin || 'git')++ if (!env.GIT_TERMINAL_PROMPT) env.GIT_TERMINAL_PROMPT = '0'++ return env+}++export function planNoConsoleGitSpawn({+ gitBin,+ args,+ isWindows = false,+ pythonBin = null,+ scriptPath = null,+ env+}: {+ gitBin: string+ args: string[]+ isWindows?: boolean+ pythonBin?: string | null+ scriptPath?: string | null+ env?: NodeJS.ProcessEnv+}): NoConsoleGitPlan {+ if (isWindows && pythonBin && scriptPath) {+ return {+ command: pythonBin,+ args: [scriptPath, ...args],+ env: noConsoleGitEnv(env, gitBin),+ windowsHide: true,+ stdio: [...PIPED_STDIO],+ creationFlags: CREATE_NO_WINDOW+ }+ }++ return {+ command: gitBin || 'git',+ args,+ env: { ...(env || {}) },+ windowsHide: Boolean(isWindows),+ stdio: [...PIPED_STDIO],+ creationFlags: 0+ }+}++export function simpleGitBinary(+ gitBin: string | undefined,+ host?: { isWindows: boolean; pythonBin?: string | null; scriptPath?: string | null } | null+): string | [string, string] {+ if (host?.isWindows && host.pythonBin && host.scriptPath) {+ return [host.pythonBin, host.scriptPath]+ }++ return gitBin || 'git'+}++export function hiddenGitSpawnSpec(+ gitBin: string,+ args: string[],+ options: SpawnOptions & { isWindows?: boolean } = {}+) {+ const isWindows = options.isWindows ?? process.platform === 'win32'+ const host = isWindows ? windowsGitHost(true) : null+ const plan = planNoConsoleGitSpawn({+ gitBin,+ args,+ isWindows,+ pythonBin: host?.pythonBin ?? null,+ scriptPath: host?.scriptPath ?? null,+ env: (options.env as NodeJS.ProcessEnv | undefined) || process.env+ })+ const { isWindows: _ignored, ...rest } = options++ return {+ command: plan.command,+ args: plan.args,+ creationFlags: plan.creationFlags,+ options: {+ ...rest,+ env: plan.env,+ windowsHide: plan.windowsHide || rest.windowsHide,+ stdio: rest.stdio ?? plan.stdio+ }+ }+}++export function execGit(+ gitBin: string,+ args: string[],+ options: { cwd?: string; env?: NodeJS.ProcessEnv; timeoutMs?: number } = {}+): Promise<{ code: number | null; stdout: string; stderr: string }> {+ const spec = hiddenGitSpawnSpec(gitBin, args, {+ cwd: options.cwd,+ env: options.env,+ stdio: ['ignore', 'pipe', 'pipe']+ })++ return new Promise((resolve, reject) => {+ const child = spawn(spec.command, spec.args, spec.options)+ let stdout = ''+ let stderr = ''+ let settled = false++ const finish = (error?: Error) => {+ if (settled) return++ settled = true++ if (error) {+ reject(error)++ return+ }++ resolve({ code: child.exitCode, stdout, stderr })+ }++ const timer = options.timeoutMs+ ? setTimeout(() => {+ child.kill()+ const error = new Error('git timed out') as NodeJS.ErrnoException & { stderr?: string }++ error.stderr = stderr+ finish(error)+ }, options.timeoutMs)+ : null++ child.stdout?.on('data', chunk => {+ stdout += chunk.toString()+ })+ child.stderr?.on('data', chunk => {+ stderr += chunk.toString()+ })+ child.once('error', error => {+ if (timer) clearTimeout(timer)++ finish(error)+ })+ child.once('close', code => {+ if (timer) clearTimeout(timer)++ child.exitCode = code+ finish()+ })+ })+}