// Claudeman App with xterm.js terminal class ClaudemanApp { constructor() { this.sessions = new Map(); this.cases = []; this.currentRun = null; this.totalCost = 0; this.totalTasks = 0; this.eventSource = null; this.sessionsCollapsed = true; this.settings = this.loadSettings(); this.terminal = null; this.fitAddon = null; this.activeSessionId = null; // Currently active interactive session this.respawnStatus = {}; // Respawn status per session this.respawnEnabled = false; // Whether respawn is enabled for new sessions (disabled by default) // Terminal write batching for performance this.pendingWrites = ''; this.writeFrameScheduled = false; this.init(); } // Batch terminal writes using requestAnimationFrame for smooth rendering batchTerminalWrite(data) { this.pendingWrites += data; if (!this.writeFrameScheduled) { this.writeFrameScheduled = true; requestAnimationFrame(() => { if (this.pendingWrites && this.terminal) { this.terminal.write(this.pendingWrites); this.pendingWrites = ''; } this.writeFrameScheduled = false; }); } } init() { this.initTerminal(); this.connectSSE(); this.loadState(); this.loadCases(); this.loadQuickStartCases(); this.startTimerUpdates(); this.setupEventListeners(); // Start with sessions collapsed document.getElementById('sessionsPanel').classList.add('collapsed'); } initTerminal() { // Initialize xterm.js this.terminal = new Terminal({ theme: { background: '#1a1a2e', foreground: '#e0e0e0', cursor: '#e0e0e0', cursorAccent: '#1a1a2e', selection: 'rgba(255, 255, 255, 0.3)', black: '#1a1a2e', red: '#ff6b6b', green: '#51cf66', yellow: '#ffd43b', blue: '#339af0', magenta: '#cc5de8', cyan: '#22b8cf', white: '#e0e0e0', brightBlack: '#495057', brightRed: '#ff8787', brightGreen: '#69db7c', brightYellow: '#ffe066', brightBlue: '#5c7cfa', brightMagenta: '#da77f2', brightCyan: '#66d9e8', brightWhite: '#ffffff', }, fontFamily: '"Fira Code", "Cascadia Code", "JetBrains Mono", "SF Mono", Monaco, "Andale Mono", Consolas, monospace', fontSize: 14, lineHeight: 1.3, cursorBlink: true, cursorStyle: 'block', scrollback: 10000, allowTransparency: true, }); this.fitAddon = new FitAddon.FitAddon(); this.terminal.loadAddon(this.fitAddon); const container = document.getElementById('terminalContainer'); this.terminal.open(container); this.fitAddon.fit(); // Welcome message this.terminal.writeln('\x1b[1;36m╔═══════════════════════════════════════════════════════════════╗'); this.terminal.writeln('║ \x1b[1;33m⚡ Claudeman Terminal \x1b[1;36m ║'); this.terminal.writeln('╠═══════════════════════════════════════════════════════════════╣'); this.terminal.writeln('║ \x1b[0;90mCtrl+Enter\x1b[1;36m Quick Start \x1b[0;90mCtrl+K\x1b[1;36m Kill All Sessions ║'); this.terminal.writeln('║ \x1b[0;90mCtrl+L\x1b[1;36m Clear Terminal \x1b[0;90mCtrl+1/2/3\x1b[1;36m Switch Tabs ║'); this.terminal.writeln('╚═══════════════════════════════════════════════════════════════╝\x1b[0m'); this.terminal.writeln(''); // Handle resize window.addEventListener('resize', () => { if (this.fitAddon) { this.fitAddon.fit(); } }); // Resize observer for container changes const resizeObserver = new ResizeObserver(() => { if (this.fitAddon) { this.fitAddon.fit(); // Notify server of resize if (this.activeSessionId) { const dims = this.fitAddon.proposeDimensions(); if (dims) { fetch(`/api/sessions/${this.activeSessionId}/resize`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ cols: dims.cols, rows: dims.rows }) }); } } } }); resizeObserver.observe(container); // Handle keyboard input - send to active session this.terminal.onData((data) => { if (this.activeSessionId) { fetch(`/api/sessions/${this.activeSessionId}/input`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ input: data }) }); } }); } setupEventListeners() { // Duration select document.getElementById('durationSelect').addEventListener('change', (e) => { const customGroup = document.getElementById('customDurationGroup'); customGroup.style.display = e.target.value === 'custom' ? 'block' : 'none'; }); // Quick Start case select document.getElementById('quickStartCase').addEventListener('change', (e) => { this.handleQuickStartSelect(e.target.value); }); // Keyboard shortcuts document.addEventListener('keydown', (e) => { // Escape to close modals if (e.key === 'Escape') { this.closeCaseSelector(); } // Ctrl/Cmd + Enter to quick start (when not in terminal) if ((e.ctrlKey || e.metaKey) && e.key === 'Enter' && document.activeElement.tagName !== 'TEXTAREA') { e.preventDefault(); this.quickStart(); } // Ctrl/Cmd + K to kill all sessions if ((e.ctrlKey || e.metaKey) && e.key === 'k') { e.preventDefault(); this.killAllSessions(); } // Ctrl/Cmd + L to clear terminal if ((e.ctrlKey || e.metaKey) && e.key === 'l' && document.activeElement !== document.getElementById('promptInput')) { e.preventDefault(); this.clearTerminal(); } // Ctrl/Cmd + 1/2/3 to switch tabs if ((e.ctrlKey || e.metaKey) && e.key === '1') { e.preventDefault(); this.switchTab('run'); } if ((e.ctrlKey || e.metaKey) && e.key === '2') { e.preventDefault(); this.switchTab('cases'); } if ((e.ctrlKey || e.metaKey) && e.key === '3') { e.preventDefault(); this.switchTab('settings'); } }); } // Settings loadSettings() { try { return JSON.parse(localStorage.getItem('claudeman-settings') || '{}'); } catch { return {}; } } saveSettings() { this.settings = { defaultDir: document.getElementById('defaultDirInput').value, autoScroll: document.getElementById('autoScrollOutput').checked, soundOnComplete: document.getElementById('soundOnComplete').checked, }; localStorage.setItem('claudeman-settings', JSON.stringify(this.settings)); alert('Settings saved!'); } // Tabs switchTab(tabName) { document.querySelectorAll('.tab').forEach(t => t.classList.remove('active')); document.querySelectorAll('.tab-content').forEach(t => t.classList.remove('active')); document.querySelector(`[data-tab="${tabName}"]`).classList.add('active'); document.getElementById(`tab-${tabName}`).classList.add('active'); if (tabName === 'cases') { this.loadCases(); } } // SSE Connection connectSSE() { this.eventSource = new EventSource('/api/events'); this.eventSource.onopen = () => { this.setConnectionStatus('connected'); }; this.eventSource.onerror = () => { this.setConnectionStatus('disconnected'); setTimeout(() => this.connectSSE(), 3000); }; this.eventSource.addEventListener('init', (e) => { const data = JSON.parse(e.data); this.handleInit(data); }); this.eventSource.addEventListener('session:created', (e) => { const data = JSON.parse(e.data); this.sessions.set(data.id, data); this.renderSessions(); this.terminal.writeln(`\x1b[1;32m► Session created: ${data.id.slice(0, 8)}\x1b[0m`); }); this.eventSource.addEventListener('session:updated', (e) => { const data = JSON.parse(e.data); this.sessions.set(data.id, data); this.updateStats(); this.renderSessions(); }); // Handle raw terminal data from PTY - use batched writes for performance this.eventSource.addEventListener('session:terminal', (e) => { const data = JSON.parse(e.data); this.batchTerminalWrite(data.data); }); this.eventSource.addEventListener('session:output', (e) => { const data = JSON.parse(e.data); // Terminal data is handled by session:terminal, so skip duplicate writes this.updateSessionOutput(data.id, data.data); }); this.eventSource.addEventListener('session:message', (e) => { // JSON messages - we can show these differently if needed }); this.eventSource.addEventListener('session:completion', (e) => { const data = JSON.parse(e.data); this.totalCost += data.cost || 0; this.totalTasks++; this.terminal.writeln(''); this.terminal.writeln(`\x1b[1;32m✓ Completed (Cost: $${(data.cost || 0).toFixed(4)})\x1b[0m`); this.updateStats(); this.setRunning(false); if (this.settings.soundOnComplete) { this.playSound(); } }); this.eventSource.addEventListener('session:error', (e) => { const data = JSON.parse(e.data); this.terminal.writeln(`\x1b[1;31m❌ Error: ${data.error}\x1b[0m`); }); this.eventSource.addEventListener('session:exit', (e) => { const data = JSON.parse(e.data); this.terminal.writeln(''); this.terminal.writeln(`\x1b[90m[Session ${data.id.slice(0, 8)} exited with code ${data.code}]\x1b[0m`); }); this.eventSource.addEventListener('scheduled:created', (e) => { const data = JSON.parse(e.data); this.currentRun = data; this.showTimer(); }); this.eventSource.addEventListener('scheduled:updated', (e) => { const data = JSON.parse(e.data); this.currentRun = data; this.updateTimer(); }); this.eventSource.addEventListener('scheduled:completed', (e) => { const data = JSON.parse(e.data); this.currentRun = data; this.hideTimer(); this.terminal.writeln(''); this.terminal.writeln(`\x1b[1;33m🎉 Scheduled run completed! Tasks: ${data.completedTasks}, Cost: $${data.totalCost.toFixed(4)}\x1b[0m`); this.setRunning(false); if (this.settings.soundOnComplete) { this.playSound(); } }); this.eventSource.addEventListener('scheduled:stopped', (e) => { const data = JSON.parse(e.data); this.currentRun = data; this.hideTimer(); this.terminal.writeln(''); this.terminal.writeln('\x1b[1;33m⏹ Scheduled run stopped.\x1b[0m'); this.setRunning(false); }); this.eventSource.addEventListener('scheduled:log', (e) => { const data = JSON.parse(e.data); this.terminal.writeln(`\x1b[90m${data.log}\x1b[0m`); }); this.eventSource.addEventListener('case:created', (e) => { this.loadCases(); this.loadQuickStartCases(); }); // Respawn events this.eventSource.addEventListener('respawn:started', (e) => { const data = JSON.parse(e.data); this.respawnStatus[data.sessionId] = data.status; this.showRespawnBanner(); this.terminal.writeln(`\x1b[1;32m🔄 Respawn loop started for session ${data.sessionId.slice(0, 8)}\x1b[0m`); }); this.eventSource.addEventListener('respawn:stopped', (e) => { const data = JSON.parse(e.data); delete this.respawnStatus[data.sessionId]; this.hideRespawnBanner(); this.terminal.writeln(`\x1b[1;33m⏹ Respawn loop stopped\x1b[0m`); }); this.eventSource.addEventListener('respawn:stateChanged', (e) => { const data = JSON.parse(e.data); if (this.respawnStatus[data.sessionId]) { this.respawnStatus[data.sessionId].state = data.state; } this.updateRespawnBanner(data.state); }); this.eventSource.addEventListener('respawn:cycleStarted', (e) => { const data = JSON.parse(e.data); if (this.respawnStatus[data.sessionId]) { this.respawnStatus[data.sessionId].cycleCount = data.cycleNumber; } document.getElementById('respawnCycleCount').textContent = data.cycleNumber; this.terminal.writeln(`\x1b[1;36m─── Respawn Cycle #${data.cycleNumber} Started ───\x1b[0m`); }); this.eventSource.addEventListener('respawn:cycleCompleted', (e) => { const data = JSON.parse(e.data); this.terminal.writeln(`\x1b[1;32m✓ Respawn Cycle #${data.cycleNumber} Completed\x1b[0m`); }); this.eventSource.addEventListener('respawn:stepSent', (e) => { const data = JSON.parse(e.data); document.getElementById('respawnStep').textContent = `Sending: ${data.input}`; }); this.eventSource.addEventListener('respawn:stepCompleted', (e) => { const data = JSON.parse(e.data); document.getElementById('respawnStep').textContent = `Completed: ${data.step}`; }); this.eventSource.addEventListener('respawn:log', (e) => { const data = JSON.parse(e.data); console.log('[Respawn]', data.message); }); this.eventSource.addEventListener('respawn:error', (e) => { const data = JSON.parse(e.data); this.terminal.writeln(`\x1b[1;31m❌ Respawn error: ${data.error}\x1b[0m`); }); } playSound() { try { const audio = new Audio('data:audio/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} } setConnectionStatus(status) { const el = document.getElementById('connectionStatus'); const dot = el.querySelector('.status-dot'); const text = el.querySelector('span:last-child'); dot.className = 'status-dot ' + status; text.textContent = status === 'connected' ? 'Connected' : 'Disconnected'; // Show toast on disconnect if (status === 'disconnected') { this.showToast('Connection lost. Reconnecting...', 'warning'); } else if (status === 'connected') { this.showToast('Connected to server', 'success'); } } // Show a toast notification showToast(message, type = 'info') { const toast = document.createElement('div'); toast.className = `toast toast-${type}`; toast.textContent = message; // Create container if needed let container = document.querySelector('.toast-container'); if (!container) { container = document.createElement('div'); container.className = 'toast-container'; document.body.appendChild(container); } container.appendChild(toast); // Animate in requestAnimationFrame(() => { toast.classList.add('show'); }); // Remove after delay setTimeout(() => { toast.classList.remove('show'); setTimeout(() => toast.remove(), 300); }, 3000); } handleInit(data) { this.sessions.clear(); data.sessions.forEach(s => this.sessions.set(s.id, s)); const activeRun = data.scheduledRuns.find(r => r.status === 'running'); if (activeRun) { this.currentRun = activeRun; this.showTimer(); } // Load respawn status if (data.respawnStatus) { this.respawnStatus = data.respawnStatus; // Show respawn banner if any session has active respawn const hasActiveRespawn = Object.values(this.respawnStatus).some(s => s.state !== 'stopped'); if (hasActiveRespawn) { this.showRespawnBanner(); const activeStatus = Object.values(this.respawnStatus).find(s => s.state !== 'stopped'); if (activeStatus) { this.updateRespawnBanner(activeStatus.state); document.getElementById('respawnCycleCount').textContent = activeStatus.cycleCount || 0; } } } this.totalCost = data.sessions.reduce((sum, s) => sum + (s.totalCost || 0), 0); this.totalCost += data.scheduledRuns.reduce((sum, r) => sum + (r.totalCost || 0), 0); this.totalTasks = data.scheduledRuns.reduce((sum, r) => sum + (r.completedTasks || 0), 0); this.updateStats(); this.renderSessions(); } async loadState() { try { const res = await fetch('/api/status'); const data = await res.json(); this.handleInit(data); } catch (err) { console.error('Failed to load state:', err); } } // Cases async loadCases() { try { const res = await fetch('/api/cases'); this.cases = await res.json(); this.renderCases(); } catch (err) { console.error('Failed to load cases:', err); } } // Quick Start async loadQuickStartCases() { try { const res = await fetch('/api/cases'); const cases = await res.json(); const select = document.getElementById('quickStartCase'); // Preserve current selection const currentValue = select.value; // Clear and rebuild options select.innerHTML = ''; // Add existing cases (skip testcase if it exists) cases.forEach(c => { if (c.name !== 'testcase') { const option = document.createElement('option'); option.value = c.name; option.textContent = c.name; select.appendChild(option); } }); // Add "Create new..." option const createOption = document.createElement('option'); createOption.value = '__create_new__'; createOption.textContent = '+ Create new...'; select.appendChild(createOption); // Restore selection if it still exists if ([...select.options].some(o => o.value === currentValue)) { select.value = currentValue; } } catch (err) { console.error('Failed to load Quick Start cases:', err); } } handleQuickStartSelect(value) { if (value === '__create_new__') { const newName = prompt('Enter a name for the new case:', ''); const select = document.getElementById('quickStartCase'); if (newName && newName.trim()) { const cleanName = newName.trim().replace(/[^a-zA-Z0-9_-]/g, '-'); if (cleanName) { // Add the new option and select it const option = document.createElement('option'); option.value = cleanName; option.textContent = cleanName; // Insert before the "Create new..." option select.insertBefore(option, select.lastElementChild); select.value = cleanName; } else { select.value = 'testcase'; } } else { // Revert to default select.value = 'testcase'; } } } async quickStart() { const select = document.getElementById('quickStartCase'); let caseName = select.value; if (caseName === '__create_new__') { caseName = 'testcase'; } this.terminal.clear(); this.terminal.writeln('\x1b[1;32m⚡ Quick Start: Launching Claude session...\x1b[0m'); this.terminal.writeln(`\x1b[90mCase: ${caseName}\x1b[0m`); this.terminal.writeln(''); try { const res = await fetch('/api/quick-start', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ caseName }) }); const data = await res.json(); if (!data.success) { throw new Error(data.error); } this.activeSessionId = data.sessionId; this.terminal.writeln(`\x1b[1;32m✓ Session started in ${data.casePath}\x1b[0m`); this.terminal.writeln(''); // Reload cases in case a new one was created this.loadQuickStartCases(); this.loadCases(); // Send initial resize const dims = this.fitAddon.proposeDimensions(); if (dims) { await fetch(`/api/sessions/${data.sessionId}/resize`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ cols: dims.cols, rows: dims.rows }) }); } // Focus the terminal this.terminal.focus(); } catch (err) { this.terminal.writeln(`\x1b[1;31m❌ Error: ${err.message}\x1b[0m`); } } renderCases() { const list = document.getElementById('casesList'); if (this.cases.length === 0) { list.innerHTML = '
No cases yet. Create one to get started.
'; return; } list.innerHTML = this.cases.map(c => `No cases. Create one in the Cases tab.
'; } else { grid.innerHTML = this.cases.map(c => `