Files
helder/src/main/pty-service.ts

137 lines
5.6 KiB
TypeScript

import { createRequire } from 'node:module'
import type { WebContents } from 'electron'
import { getRoot } from './project'
import { getConfig } from './config'
import { logger } from './logger'
/**
* Real PTYs. The agent pane is a shell that auto-launches the `claude` CLI; the
* bottom pane is a plain shell. node-pty is a native module — loaded defensively
* so the app still launches (with a friendly message) if it wasn't rebuilt for
* this Electron via `npm run rebuild`.
*
* Shell + ai command/autoLaunch come from `.helder/config.json` (terminal.shell,
* ai.command, ai.autoLaunch) via the config module.
*/
const require = createRequire(import.meta.url)
type PtyModule = typeof import('node-pty')
let pty: PtyModule | null = null
try {
pty = require('node-pty') as PtyModule
} catch (e) {
logger.error('pty', 'node-pty unavailable — run `npm run rebuild`', e)
}
const terms = new Map<number, import('node-pty').IPty>()
/** Ids we killed on purpose (pane closed, window quitting, StrictMode remount).
* Their exit is expected, so it must NOT be logged as a warning — a log full of
* false alarms is a log nobody reads. */
const killing = new Set<number>()
let seq = 0
/**
* Env for spawned PTYs. Electron launched from a Homebrew/GUI context leaks
* `npm_config_prefix` (e.g. "/opt/homebrew") into the child shell, which makes
* nvm refuse to load ("nvm is not compatible with the npm_config_prefix
* environment variable"). Strip it so the user's shell init runs cleanly.
*
* A macOS app launched from Spotlight/Finder (launchd GUI context) inherits NO
* `LANG`/`LC_*`, so the child shell falls back to the `C`/POSIX locale — not
* UTF-8. Anything multibyte the shell or `claude` emits then renders as high-byte
* mojibake in xterm. Launching from a terminal (`npm run dev`) inherits the
* terminal's UTF-8 locale, which is why dev looks fine and the packaged app does
* not. Default a UTF-8 locale when none is set so both paths match.
*/
function ptyEnv(): { [key: string]: string } {
const env = { ...process.env } as { [key: string]: string }
delete env.npm_config_prefix
delete env.npm_config_globalconfig
if (process.platform !== 'win32' && !env.LC_ALL && !env.LC_CTYPE && !env.LANG) {
env.LANG = 'en_US.UTF-8'
}
// Same inheritance gap as locale, but for color: a terminal launch leaks
// COLORTERM=truecolor so `claude` renders its UI backgrounds as exact 24-bit
// colors; the GUI-launched packaged app has none, so claude falls back to a
// 256/16-color approximation and the same backgrounds shift shade. Match both.
if (process.platform !== 'win32' && !env.COLORTERM) {
env.COLORTERM = 'truecolor'
}
return env
}
function defaultShell(): string {
const configured = getConfig().terminal.shell
if (configured) return configured
if (process.platform === 'win32') return process.env.COMSPEC || 'powershell.exe'
return process.env.SHELL || '/bin/zsh'
}
export function ptyAvailable(): boolean {
return !!pty
}
export function createPty(sender: WebContents, kind: 'agent' | 'shell', cols: number, rows: number): number {
if (!pty) {
logger.warn('pty', `create(${kind}) refused — node-pty never loaded`)
return -1
}
const cwd = getRoot() || process.env.HOME || process.cwd()
const shell = defaultShell()
const ai = getConfig().ai
const launchAgent = kind === 'agent' && ai.autoLaunch && process.platform !== 'win32'
// For the agent pane we exec the `claude` CLI directly as the shell's command
// (`zsh -i -c 'claude'`) instead of typing it into an interactive prompt — `-i`
// still sources the user's rc (nvm etc.), but there's no prompt line and no
// echoed command cluttering the pane; claude takes over a clean terminal.
const args = launchAgent ? ['-i', '-c', ai.command] : []
const proc = pty.spawn(shell, args, {
name: 'xterm-256color',
cols: cols || 80,
rows: rows || 24,
cwd,
env: ptyEnv(),
})
const id = ++seq
terms.set(id, proc)
logger.info('pty', `spawned ${kind}`, { id, pid: proc.pid, shell, args, cwd })
proc.onData((data) => { if (!sender.isDestroyed()) sender.send('pty:data', { id, data }) })
proc.onExit(({ exitCode, signal }) => {
terms.delete(id)
// The agent pane dying on its own (`claude` not on PATH, OOM-killed,
// segfault) looks from the UI like "the terminal just went blank" — the exit
// code and signal are the only evidence of what actually happened. An exit we
// asked for is routine, so only an unrequested one is a warning.
const expected = killing.delete(id)
const abnormal = !expected && (exitCode !== 0 || (signal != null && signal !== 0))
if (abnormal) logger.warn('pty', `${kind} exited unexpectedly`, { id, exitCode, signal })
else logger.info('pty', `${kind} exited`, { id, exitCode, expected })
if (!sender.isDestroyed()) sender.send('pty:exit', { id })
})
// Windows path keeps the type-into-shell launch (no `-i -c` semantics there).
if (kind === 'agent' && ai.autoLaunch && process.platform === 'win32') {
setTimeout(() => { try { proc.write(ai.command + '\r') } catch { /* exited */ } }, 350)
}
return id
}
export function writePty(id: number, data: string): void {
terms.get(id)?.write(data)
}
export function resizePty(id: number, cols: number, rows: number): void {
try { terms.get(id)?.resize(cols, rows) } catch { /* race with exit */ }
}
export function killPty(id: number): void {
const p = terms.get(id)
if (p) { killing.add(id); try { p.kill() } catch { /* already gone */ } terms.delete(id) }
}
export function killAllPtys(): void {
for (const [id, p] of terms) { killing.add(id); try { p.kill() } catch { /* noop */ } }
terms.clear()
}