File size: 17,786 Bytes
064bfd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 | /**
* Terminal Launcher
*
* Detects the user's preferred terminal emulator and launches Claude Code
* inside it. Used by the deep link protocol handler when invoked by the OS
* (i.e., not already running inside a terminal).
*
* Platform support:
* macOS β Terminal.app, iTerm2, Ghostty, Kitty, Alacritty, WezTerm
* Linux β $TERMINAL, x-terminal-emulator, gnome-terminal, konsole, etc.
* Windows β Windows Terminal (wt.exe), PowerShell, cmd.exe
*/
import { spawn } from 'child_process'
import { basename } from 'path'
import { getGlobalConfig } from '../config.js'
import { logForDebugging } from '../debug.js'
import { execFileNoThrow } from '../execFileNoThrow.js'
import { which } from '../which.js'
export type TerminalInfo = {
name: string
command: string
}
// macOS terminals in preference order.
// Each entry: [display name, app bundle name or CLI command, detection method]
const MACOS_TERMINALS: Array<{
name: string
bundleId: string
app: string
}> = [
{ name: 'iTerm2', bundleId: 'com.googlecode.iterm2', app: 'iTerm' },
{ name: 'Ghostty', bundleId: 'com.mitchellh.ghostty', app: 'Ghostty' },
{ name: 'Kitty', bundleId: 'net.kovidgoyal.kitty', app: 'kitty' },
{ name: 'Alacritty', bundleId: 'org.alacritty', app: 'Alacritty' },
{ name: 'WezTerm', bundleId: 'com.github.wez.wezterm', app: 'WezTerm' },
{
name: 'Terminal.app',
bundleId: 'com.apple.Terminal',
app: 'Terminal',
},
]
// Linux terminals in preference order (command name)
const LINUX_TERMINALS = [
'ghostty',
'kitty',
'alacritty',
'wezterm',
'gnome-terminal',
'konsole',
'xfce4-terminal',
'mate-terminal',
'tilix',
'xterm',
]
/**
* Detect the user's preferred terminal on macOS.
* Checks running processes first (most likely to be what the user prefers),
* then falls back to checking installed .app bundles.
*/
async function detectMacosTerminal(): Promise<TerminalInfo> {
// Stored preference from a previous interactive session. This is the only
// signal that survives into the headless LaunchServices context β the env
// var check below never hits when we're launched from a browser link.
const stored = getGlobalConfig().deepLinkTerminal
if (stored) {
const match = MACOS_TERMINALS.find(t => t.app === stored)
if (match) {
return { name: match.name, command: match.app }
}
}
// Check the TERM_PROGRAM env var β if set, the user has a clear preference.
// TERM_PROGRAM may include a .app suffix (e.g., "iTerm.app"), so strip it.
const termProgram = process.env.TERM_PROGRAM
if (termProgram) {
const normalized = termProgram.replace(/\.app$/i, '').toLowerCase()
const match = MACOS_TERMINALS.find(
t =>
t.app.toLowerCase() === normalized ||
t.name.toLowerCase() === normalized,
)
if (match) {
return { name: match.name, command: match.app }
}
}
// Check which terminals are installed by looking for .app bundles.
// Try mdfind first (Spotlight), but fall back to checking /Applications
// directly since mdfind can return empty results if Spotlight is disabled
// or hasn't indexed the app yet.
for (const terminal of MACOS_TERMINALS) {
const { code, stdout } = await execFileNoThrow(
'mdfind',
[`kMDItemCFBundleIdentifier == "${terminal.bundleId}"`],
{ timeout: 5000, useCwd: false },
)
if (code === 0 && stdout.trim().length > 0) {
return { name: terminal.name, command: terminal.app }
}
}
// Fallback: check /Applications directly (mdfind may not work if
// Spotlight indexing is disabled or incomplete)
for (const terminal of MACOS_TERMINALS) {
const { code: lsCode } = await execFileNoThrow(
'ls',
[`/Applications/${terminal.app}.app`],
{ timeout: 1000, useCwd: false },
)
if (lsCode === 0) {
return { name: terminal.name, command: terminal.app }
}
}
// Terminal.app is always available on macOS
return { name: 'Terminal.app', command: 'Terminal' }
}
/**
* Detect the user's preferred terminal on Linux.
* Checks $TERMINAL, then x-terminal-emulator, then walks a priority list.
*/
async function detectLinuxTerminal(): Promise<TerminalInfo | null> {
// Check $TERMINAL env var
const termEnv = process.env.TERMINAL
if (termEnv) {
const resolved = await which(termEnv)
if (resolved) {
return { name: basename(termEnv), command: resolved }
}
}
// Check x-terminal-emulator (Debian/Ubuntu alternative)
const xte = await which('x-terminal-emulator')
if (xte) {
return { name: 'x-terminal-emulator', command: xte }
}
// Walk the priority list
for (const terminal of LINUX_TERMINALS) {
const resolved = await which(terminal)
if (resolved) {
return { name: terminal, command: resolved }
}
}
return null
}
/**
* Detect the user's preferred terminal on Windows.
*/
async function detectWindowsTerminal(): Promise<TerminalInfo> {
// Check for Windows Terminal first
const wt = await which('wt.exe')
if (wt) {
return { name: 'Windows Terminal', command: wt }
}
// PowerShell 7+ (separate install)
const pwsh = await which('pwsh.exe')
if (pwsh) {
return { name: 'PowerShell', command: pwsh }
}
// Windows PowerShell 5.1 (built into Windows)
const powershell = await which('powershell.exe')
if (powershell) {
return { name: 'PowerShell', command: powershell }
}
// cmd.exe is always available
return { name: 'Command Prompt', command: 'cmd.exe' }
}
/**
* Detect the user's preferred terminal emulator.
*/
export async function detectTerminal(): Promise<TerminalInfo | null> {
switch (process.platform) {
case 'darwin':
return detectMacosTerminal()
case 'linux':
return detectLinuxTerminal()
case 'win32':
return detectWindowsTerminal()
default:
return null
}
}
/**
* Launch Claude Code in the detected terminal emulator.
*
* Pure argv paths (no shell, user input never touches an interpreter):
* macOS β Ghostty, Alacritty, Kitty, WezTerm (via open -na --args)
* Linux β all ten in LINUX_TERMINALS
* Windows β Windows Terminal
*
* Shell-string paths (user input is shell-quoted and relied upon):
* macOS β iTerm2, Terminal.app (AppleScript `write text` / `do script`
* are inherently shell-interpreted; no argv interface exists)
* Windows β PowerShell -Command, cmd.exe /k (no argv exec mode)
*
* For pure-argv paths: claudePath, --prefill, query, cwd travel as distinct
* argv elements end-to-end. No sh -c. No shellQuote(). The terminal does
* chdir(cwd) and execvp(claude, argv). Spaces/quotes/metacharacters in
* query or cwd are preserved by argv boundaries with zero interpretation.
*/
export async function launchInTerminal(
claudePath: string,
action: {
query?: string
cwd?: string
repo?: string
lastFetchMs?: number
},
): Promise<boolean> {
const terminal = await detectTerminal()
if (!terminal) {
logForDebugging('No terminal emulator detected', { level: 'error' })
return false
}
logForDebugging(
`Launching in terminal: ${terminal.name} (${terminal.command})`,
)
const claudeArgs = ['--deep-link-origin']
if (action.repo) {
claudeArgs.push('--deep-link-repo', action.repo)
if (action.lastFetchMs !== undefined) {
claudeArgs.push('--deep-link-last-fetch', String(action.lastFetchMs))
}
}
if (action.query) {
claudeArgs.push('--prefill', action.query)
}
switch (process.platform) {
case 'darwin':
return launchMacosTerminal(terminal, claudePath, claudeArgs, action.cwd)
case 'linux':
return launchLinuxTerminal(terminal, claudePath, claudeArgs, action.cwd)
case 'win32':
return launchWindowsTerminal(terminal, claudePath, claudeArgs, action.cwd)
default:
return false
}
}
async function launchMacosTerminal(
terminal: TerminalInfo,
claudePath: string,
claudeArgs: string[],
cwd?: string,
): Promise<boolean> {
switch (terminal.command) {
// --- SHELL-STRING PATHS (AppleScript has no argv interface) ---
// User input is shell-quoted via shellQuote(). These two are the only
// macOS paths where shellQuote() correctness is load-bearing.
case 'iTerm': {
const shCmd = buildShellCommand(claudePath, claudeArgs, cwd)
// If iTerm isn't running, `tell application` launches it and iTerm's
// default startup behavior opens a window β so `create window` would
// make a second one. Check `running` first: if already running (even
// with zero windows), create a window; if not, `activate` lets iTerm's
// startup create the first window.
const script = `tell application "iTerm"
if running then
create window with default profile
else
activate
end if
tell current session of current window
write text ${appleScriptQuote(shCmd)}
end tell
end tell`
const { code } = await execFileNoThrow('osascript', ['-e', script], {
useCwd: false,
})
if (code === 0) return true
break
}
case 'Terminal': {
const shCmd = buildShellCommand(claudePath, claudeArgs, cwd)
const script = `tell application "Terminal"
do script ${appleScriptQuote(shCmd)}
activate
end tell`
const { code } = await execFileNoThrow('osascript', ['-e', script], {
useCwd: false,
})
return code === 0
}
// --- PURE ARGV PATHS (no shell, no shellQuote) ---
// open -na <App> --args <argv> β app receives argv verbatim β
// terminal's native --working-directory + -e exec the command directly.
case 'Ghostty': {
const args = [
'-na',
terminal.command,
'--args',
'--window-save-state=never',
]
if (cwd) args.push(`--working-directory=${cwd}`)
args.push('-e', claudePath, ...claudeArgs)
const { code } = await execFileNoThrow('open', args, { useCwd: false })
if (code === 0) return true
break
}
case 'Alacritty': {
const args = ['-na', terminal.command, '--args']
if (cwd) args.push('--working-directory', cwd)
args.push('-e', claudePath, ...claudeArgs)
const { code } = await execFileNoThrow('open', args, { useCwd: false })
if (code === 0) return true
break
}
case 'kitty': {
const args = ['-na', terminal.command, '--args']
if (cwd) args.push('--directory', cwd)
args.push(claudePath, ...claudeArgs)
const { code } = await execFileNoThrow('open', args, { useCwd: false })
if (code === 0) return true
break
}
case 'WezTerm': {
const args = ['-na', terminal.command, '--args', 'start']
if (cwd) args.push('--cwd', cwd)
args.push('--', claudePath, ...claudeArgs)
const { code } = await execFileNoThrow('open', args, { useCwd: false })
if (code === 0) return true
break
}
}
logForDebugging(
`Failed to launch ${terminal.name}, falling back to Terminal.app`,
)
return launchMacosTerminal(
{ name: 'Terminal.app', command: 'Terminal' },
claudePath,
claudeArgs,
cwd,
)
}
async function launchLinuxTerminal(
terminal: TerminalInfo,
claudePath: string,
claudeArgs: string[],
cwd?: string,
): Promise<boolean> {
// All Linux paths are pure argv. Each terminal's --working-directory
// (or equivalent) sets cwd natively; the command is exec'd directly.
// For the few terminals without a cwd flag (xterm, and the opaque
// x-terminal-emulator / $TERMINAL), spawn({cwd}) sets the terminal
// process's cwd β most inherit it for the child.
let args: string[]
let spawnCwd: string | undefined
switch (terminal.name) {
case 'gnome-terminal':
args = cwd ? [`--working-directory=${cwd}`, '--'] : ['--']
args.push(claudePath, ...claudeArgs)
break
case 'konsole':
args = cwd ? ['--workdir', cwd, '-e'] : ['-e']
args.push(claudePath, ...claudeArgs)
break
case 'kitty':
args = cwd ? ['--directory', cwd] : []
args.push(claudePath, ...claudeArgs)
break
case 'wezterm':
args = cwd ? ['start', '--cwd', cwd, '--'] : ['start', '--']
args.push(claudePath, ...claudeArgs)
break
case 'alacritty':
args = cwd ? ['--working-directory', cwd, '-e'] : ['-e']
args.push(claudePath, ...claudeArgs)
break
case 'ghostty':
args = cwd ? [`--working-directory=${cwd}`, '-e'] : ['-e']
args.push(claudePath, ...claudeArgs)
break
case 'xfce4-terminal':
case 'mate-terminal':
args = cwd ? [`--working-directory=${cwd}`, '-x'] : ['-x']
args.push(claudePath, ...claudeArgs)
break
case 'tilix':
args = cwd ? [`--working-directory=${cwd}`, '-e'] : ['-e']
args.push(claudePath, ...claudeArgs)
break
default:
// xterm, x-terminal-emulator, $TERMINAL β no reliable cwd flag.
// spawn({cwd}) sets the terminal's own cwd; most inherit.
args = ['-e', claudePath, ...claudeArgs]
spawnCwd = cwd
break
}
return spawnDetached(terminal.command, args, { cwd: spawnCwd })
}
async function launchWindowsTerminal(
terminal: TerminalInfo,
claudePath: string,
claudeArgs: string[],
cwd?: string,
): Promise<boolean> {
const args: string[] = []
switch (terminal.name) {
// --- PURE ARGV PATH ---
case 'Windows Terminal':
if (cwd) args.push('-d', cwd)
args.push('--', claudePath, ...claudeArgs)
break
// --- SHELL-STRING PATHS ---
// PowerShell -Command and cmd /k take a command string. No argv exec
// mode that also keeps the session interactive after claude exits.
// User input is escaped per-shell; correctness of that escaping is
// load-bearing here.
case 'PowerShell': {
// Single-quoted PowerShell strings have NO escape sequences (only
// '' for a literal quote). Double-quoted strings interpret backtick
// escapes β a query containing `" could break out.
const cdCmd = cwd ? `Set-Location ${psQuote(cwd)}; ` : ''
args.push(
'-NoExit',
'-Command',
`${cdCmd}& ${psQuote(claudePath)} ${claudeArgs.map(psQuote).join(' ')}`,
)
break
}
default: {
const cdCmd = cwd ? `cd /d ${cmdQuote(cwd)} && ` : ''
args.push(
'/k',
`${cdCmd}${cmdQuote(claudePath)} ${claudeArgs.map(a => cmdQuote(a)).join(' ')}`,
)
break
}
}
// cmd.exe does NOT use MSVCRT-style argument parsing. libuv's default
// quoting for spawn() on Windows assumes MSVCRT rules and would double-
// escape our already-cmdQuote'd string. Bypass it for cmd.exe only.
return spawnDetached(terminal.command, args, {
windowsVerbatimArguments: terminal.name === 'Command Prompt',
})
}
/**
* Spawn a terminal detached so the handler process can exit without
* waiting for the terminal to close. Resolves false on spawn failure
* (ENOENT, EACCES) rather than crashing.
*/
function spawnDetached(
command: string,
args: string[],
opts: { cwd?: string; windowsVerbatimArguments?: boolean } = {},
): Promise<boolean> {
return new Promise<boolean>(resolve => {
const child = spawn(command, args, {
detached: true,
stdio: 'ignore',
cwd: opts.cwd,
windowsVerbatimArguments: opts.windowsVerbatimArguments,
})
child.once('error', err => {
logForDebugging(`Failed to spawn ${command}: ${err.message}`, {
level: 'error',
})
void resolve(false)
})
child.once('spawn', () => {
child.unref()
void resolve(true)
})
})
}
/**
* Build a single-quoted POSIX shell command string. ONLY used by the
* AppleScript paths (iTerm, Terminal.app) which have no argv interface.
*/
function buildShellCommand(
claudePath: string,
claudeArgs: string[],
cwd?: string,
): string {
const cdPrefix = cwd ? `cd ${shellQuote(cwd)} && ` : ''
return `${cdPrefix}${[claudePath, ...claudeArgs].map(shellQuote).join(' ')}`
}
/**
* POSIX single-quote escaping. Single-quoted strings have zero
* interpretation except for the closing single quote itself.
* Only used by buildShellCommand() for the AppleScript paths.
*/
function shellQuote(s: string): string {
return `'${s.replace(/'/g, "'\\''")}'`
}
/**
* AppleScript string literal escaping (backslash then double-quote).
*/
function appleScriptQuote(s: string): string {
return `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`
}
/**
* PowerShell single-quoted string. The ONLY special sequence is '' for a
* literal single quote β no backtick escapes, no variable expansion, no
* subexpressions. This is the safe PowerShell quoting; double-quoted
* strings interpret `n `t `" etc. and can be escaped out of.
*/
function psQuote(s: string): string {
return `'${s.replace(/'/g, "''")}'`
}
/**
* cmd.exe argument quoting. cmd.exe does NOT use CommandLineToArgvW-style
* backslash escaping β it toggles its quoting state on every raw "
* character, so an embedded " breaks out of the quoted region and exposes
* metacharacters (& | < > ^) to cmd.exe interpretation = command injection.
*
* Strategy: strip " from the input (it cannot be safely represented in a
* cmd.exe double-quoted string). Escape % as %% to prevent environment
* variable expansion (%PATH% etc.) which cmd.exe performs even inside
* double quotes. Trailing backslashes are still doubled because the
* *child process* (claude.exe) uses CommandLineToArgvW, where a trailing
* \ before our closing " would eat the close-quote.
*/
function cmdQuote(arg: string): string {
const stripped = arg.replace(/"/g, '').replace(/%/g, '%%')
const escaped = stripped.replace(/(\\+)$/, '$1$1')
return `"${escaped}"`
}
|