// CodeBurn 준비/실제 종료 소유 계약: docs/specs/app-lifecycle.md v1.11.0 const pty = require('node-pty'); const { dialog } = require('electron'); const fs = require('fs'); const os = require('os'); const terminalCleanup = require('../services/app-terminal-cleanup'); const { assertHostPathSupported } = require('../security/host-launch'); const { scrubAgentEnvironment, MODEL_KEYS, RUNTIME_KEYS } = require('../security/agent-environment'); // 2. CodeBurn let codeburnPty = null; let stopping = false, startQueue = Promise.resolve(); const pendingStarts = new Set(); module.exports = { getCodeburnPty() { return codeburnPty; }, setCodeburnPty(val) { codeburnPty = val; }, async stopCodeburn() { stopping = true; // 응답이 늦은 준비 결과도 먼저 인수한 뒤 같은 종료 장벽에서 회수한다. await Promise.allSettled([...pendingStarts]); await terminalCleanup.closeCodeburnTerminal(module.exports.getCodeburnPty, module.exports.setCodeburnPty); }, register(ipcMain, ctx) { const start = async () => { assertHostPathSupported('uncontained-task'); const targetWindow = ctx.codeburnWindow; const cancelled = () => stopping || ctx.isQuitting || ctx.codeburnWindow !== targetWindow || targetWindow?.isDestroyed(); if (cancelled()) return; ipcMain.removeAllListeners('codeburn-input'); ipcMain.removeAllListeners('codeburn-resize'); if (codeburnPty) { try { await terminalCleanup.closeCodeburnTerminal(module.exports.getCodeburnPty, module.exports.setCodeburnPty); } catch(error) { console.error('[CodeBurn] 이전 프로세스 종료 미확인:', error.code || 'TERMINAL_CLOSE_FAILED'); return; } } if (cancelled()) return; // ── 분기 A: 원격/로컬 Docker 샌드박스가 연결되어 가동 중인 경우 (컨테이너 내에서 codeburn 직접 실행) ── if (ctx.activeDockerSandbox && ctx.activeDockerSandbox.execWrapper) { const execWrapper = ctx.activeDockerSandbox.execWrapper; try { assertHostPathSupported('uncontained-task'); const result = await execWrapper.createInteractiveShell({ cols: 80, rows: 24, shell: 'codeburn' }); const stream = result.stream; codeburnPty = { write: (data) => stream.write(data), resize: (cols, rows) => { if (result.exec && result.exec.resize) { result.exec.resize(cols, rows).catch(() => {}); } }, destroy: () => stream.end() }; const current = codeburnPty; if (cancelled()) { await terminalCleanup.closeCodeburnTerminal(module.exports.getCodeburnPty, module.exports.setCodeburnPty); return; } targetWindow?.once('closed', () => { if (codeburnPty !== current) return; terminalCleanup.closeTerminal(current).catch(error => console.error('[CodeBurn] 컨테이너 프로세스 종료 미확인:', error.code || 'TERMINAL_CLOSE_FAILED')); }); stream.on('data', (data) => { if (ctx.codeburnWindow && !ctx.codeburnWindow.isDestroyed()) { ctx.codeburnWindow.webContents.send('codeburn-output', data.toString()); } }); stream.on('end', () => { if (codeburnPty !== current) return; ipcMain.removeAllListeners('codeburn-input'); ipcMain.removeAllListeners('codeburn-resize'); // stream.end는 원격 exec 종료 증거가 아니다. 현재 소유 참조를 유지한다. if (ctx.codeburnWindow && !ctx.codeburnWindow.isDestroyed()) { ctx.codeburnWindow.webContents.send('codeburn-output', `\r\n\r\n\x1b[33m[원격 연결이 종료되었습니다. 프로세스 종료는 확인되지 않았습니다.]\x1b[0m\r\n`); ipcMain.once('codeburn-input', () => { if (ctx.codeburnWindow && !ctx.codeburnWindow.isDestroyed()) { ctx.codeburnWindow.close(); } }); } }); ipcMain.on('codeburn-input', (ev, data) => { if (!cancelled() && codeburnPty === current) { try { if (data !== '\x03') assertHostPathSupported('uncontained-task'); current.write(data); } catch { /* 종료 중 입력 실패는 새 작업으로 재시도하지 않는다. */ } } }); ipcMain.on('codeburn-resize', (ev, { cols, rows }) => { if (!cancelled() && codeburnPty === current) current.resize(cols, rows); }); return; } catch (err) { if (cancelled() || codeburnPty) { console.error('[CodeBurn] 컨테이너 프로세스 종료 미확인:', err.code || 'TERMINAL_CLOSE_FAILED'); return; } console.error('[CodeBurn] Failed to spawn codeburn inside container, falling back to local:', err); } } // ── 분기 B: 로컬 세션 실행 (기존 로컬 node-pty 호출) ── const isWin = process.platform === 'win32'; let shell_cmd = isWin ? 'powershell.exe' : (process.env.SHELL || '/bin/bash'); const args = isWin ? ['-NoLogo', '-Command', 'codeburn'] : ['-c', 'export PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"; codeburn']; if (!isWin && !fs.existsSync(shell_cmd)) { if (fs.existsSync('/bin/zsh')) { shell_cmd = '/bin/zsh'; } else if (fs.existsSync('/bin/bash')) { shell_cmd = '/bin/bash'; } else { shell_cmd = '/bin/sh'; } } const cleanEnv = scrubAgentEnvironment(process.env, { trustedKeys: [...MODEL_KEYS, ...RUNTIME_KEYS] }); if (ctx.activeDockerSandbox && ctx.activeDockerSandbox.sessionId) { cleanEnv['CLAUDE_CODE_SESSION_ID'] = ctx.activeDockerSandbox.sessionId; } let workDir = process.env.USERPROFILE || process.env.HOME || process.cwd(); if (!fs.existsSync(workDir)) { workDir = os.homedir() || os.tmpdir() || '/'; } let spawnSuccess = false, fallbackTimer; try { assertHostPathSupported('uncontained-task'); codeburnPty = pty.spawn(shell_cmd, args, { name: 'xterm-256color', cols: 80, rows: 24, cwd: workDir, env: cleanEnv }); spawnSuccess = true; } catch (error) { try { assertHostPathSupported('uncontained-task'); codeburnPty = pty.spawn(shell_cmd, [], { name: 'xterm-256color', cols: 80, rows: 24, cwd: workDir, env: cleanEnv }); spawnSuccess = true; const fallbackChild = codeburnPty; fallbackTimer = setTimeout(() => { if (cancelled() || codeburnPty !== fallbackChild) return; try { assertHostPathSupported('uncontained-task'); fallbackChild.write('codeburn\r'); } catch(e) { /* 종료 중인 자식에 재입력하지 않는다. */ } }, 1000); } catch (fallbackError) { const errorMessage = `CodeBurn 터미널 프로세스를 시작하지 못했습니다.\n\n오류: ${fallbackError.message}`; dialog.showErrorBox('CodeBurn 시작 오류', errorMessage); } } if (spawnSuccess && codeburnPty) { const current = codeburnPty; let outputDisposable, exitDisposable, exited = false; const onWindowClosed = () => { if (codeburnPty !== current) return; clearTimeout(fallbackTimer); terminalCleanup.closeTerminal(current).then(() => { if (codeburnPty === current) codeburnPty = null; }, error => console.error('[CodeBurn] 프로세스 종료 미확인:', error.code || 'TERMINAL_CLOSE_FAILED')); if (codeburnPty === current) { ipcMain.removeAllListeners('codeburn-input'); ipcMain.removeAllListeners('codeburn-resize'); } }; targetWindow?.once('closed', onWindowClosed); try { exitDisposable = current.onExit((e) => { exited = true; clearTimeout(fallbackTimer); targetWindow?.removeListener('closed', onWindowClosed); // 같은 exit 이벤트의 앱 소유 장벽이 먼저 관측한 뒤 구독을 회수한다. Promise.resolve().then(() => { try { outputDisposable?.dispose(); } catch { /* 종료 뒤 출력 구독 정리. */ } try { exitDisposable?.dispose(); } catch { /* 종료 뒤 exit 구독 정리. */ } }); if (codeburnPty !== current) return; ipcMain.removeAllListeners('codeburn-input'); ipcMain.removeAllListeners('codeburn-resize'); codeburnPty = null; if (ctx.codeburnWindow && !ctx.codeburnWindow.isDestroyed()) { ctx.codeburnWindow.webContents.send('codeburn-output', `\r\n\r\n\x1b[33m[프로세스가 종료되었습니다 (Exit Code: ${e.exitCode || 0}). 창을 닫으려면 아무 키나 누르십시오.]\x1b[0m\r\n`); ipcMain.once('codeburn-input', () => { if (ctx.codeburnWindow && !ctx.codeburnWindow.isDestroyed()) { ctx.codeburnWindow.close(); } }); } }); if (exited) return; outputDisposable = current.onData((data) => { if (codeburnPty === current && ctx.codeburnWindow && !ctx.codeburnWindow.isDestroyed()) { ctx.codeburnWindow.webContents.send('codeburn-output', data); } }); ipcMain.on('codeburn-input', (ev, data) => { if (!cancelled() && codeburnPty === current) { try { if (data !== '\x03') assertHostPathSupported('uncontained-task'); current.write(data); } catch { /* 종료 중 입력 실패는 새 작업으로 재시도하지 않는다. */ } } }); ipcMain.on('codeburn-resize', (ev, { cols, rows }) => { if (!cancelled() && codeburnPty === current) current.resize(cols, rows); }); } catch (error) { clearTimeout(fallbackTimer); try { await terminalCleanup.closeCodeburnTerminal(module.exports.getCodeburnPty, module.exports.setCodeburnPty); } catch { /* 정리 실패로 최초 등록 오류를 덮지 않는다. */ } throw error; } } }; ipcMain.on('codeburn-start', () => { // 같은 창의 연속 시작도 앞선 자식의 종료를 추월하지 않는다. const task = startQueue.then(start); startQueue = task.catch(() => {}); pendingStarts.add(task); task.then(() => pendingStarts.delete(task), error => { pendingStarts.delete(task); console.error('[CodeBurn] 시작 실패:', error.code || 'CODEBURN_START_FAILED'); }); return task; }); } };