chore: bump version to 0.1538

This commit is contained in:
arkon
2026-02-18 12:51:35 +01:00
parent c548c2d6ee
commit 88422cab57
40 changed files with 369 additions and 3547 deletions
+63 -63
View File
@@ -1350,7 +1350,7 @@ class ClaudemanApp {
this.terminalBuffers = new Map(); // Store terminal content per session
this.editingSessionId = null; // Session being edited in options modal
this.pendingCloseSessionId = null; // Session pending close confirmation
this.screenSessions = []; // Screen sessions for process monitor
this.muxSessions = []; // Screen sessions for process monitor
// Ralph loop/todo state per session
this.ralphStates = new Map(); // Map<sessionId, { loop, todos }>
@@ -1428,7 +1428,7 @@ class ClaudemanApp {
this.renderSessionTabsTimeout = null;
this.renderRalphStatePanelTimeout = null;
this.renderTaskPanelTimeout = null;
this.renderScreenSessionsTimeout = null;
this.renderMuxSessionsTimeout = null;
// System stats polling
this.systemStatsInterval = null;
@@ -2766,29 +2766,29 @@ class ClaudemanApp {
});
// Screen events
addListener('screen:created', (e) => {
addListener('mux:created', (e) => {
const screen = JSON.parse(e.data);
this.screenSessions.push(screen);
this.renderScreenSessions();
this.muxSessions.push(screen);
this.renderMuxSessions();
});
addListener('screen:killed', (e) => {
addListener('mux:killed', (e) => {
const data = JSON.parse(e.data);
this.screenSessions = this.screenSessions.filter(s => s.sessionId !== data.sessionId);
this.renderScreenSessions();
this.muxSessions = this.muxSessions.filter(s => s.sessionId !== data.sessionId);
this.renderMuxSessions();
});
addListener('screen:died', (e) => {
addListener('mux:died', (e) => {
const data = JSON.parse(e.data);
this.screenSessions = this.screenSessions.filter(s => s.sessionId !== data.sessionId);
this.renderScreenSessions();
this.muxSessions = this.muxSessions.filter(s => s.sessionId !== data.sessionId);
this.renderMuxSessions();
this.showToast('Mux session died: ' + data.sessionId.slice(0, 8), 'warning');
});
addListener('screen:statsUpdated', (e) => {
this.screenSessions = JSON.parse(e.data);
addListener('mux:statsUpdated', (e) => {
this.muxSessions = JSON.parse(e.data);
if (document.getElementById('monitorPanel').classList.contains('open')) {
this.renderScreenSessions();
this.renderMuxSessions();
}
});
@@ -3272,7 +3272,7 @@ class ClaudemanApp {
// Chain on dispatch only — wait for the previous request to be sent before
// dispatching the next one (preserves keystroke ordering), but don't wait
// for the server's response. The server handles writeViaScreen as
// for the server's response. The server handles writeViaMux as
// fire-and-forget anyway, so the HTTP response carries no useful data
// beyond success/failure for retry purposes.
this._inputSendChain = this._inputSendChain.then(() => {
@@ -4318,9 +4318,9 @@ class ClaudemanApp {
delete this.respawnActionLogs[sessionId];
}
async closeSession(sessionId, killScreen = true) {
async closeSession(sessionId, killMux = true) {
try {
await fetch(`/api/sessions/${sessionId}?killScreen=${killScreen}`, { method: 'DELETE' });
await fetch(`/api/sessions/${sessionId}?killMux=${killMux}`, { method: 'DELETE' });
this._cleanupSessionData(sessionId);
if (this.activeSessionId === sessionId) {
@@ -4339,7 +4339,7 @@ class ClaudemanApp {
this.renderSessionTabs();
if (killScreen) {
if (killMux) {
this.showToast('Session closed and tmux killed', 'success');
} else {
this.showToast('Tab hidden, tmux still running', 'info');
@@ -4369,12 +4369,12 @@ class ClaudemanApp {
document.getElementById('closeConfirmModal').classList.remove('active');
}
async confirmCloseSession(killScreen = true) {
async confirmCloseSession(killMux = true) {
const sessionId = this.pendingCloseSessionId;
this.cancelCloseSession();
if (sessionId) {
await this.closeSession(sessionId, killScreen);
await this.closeSession(sessionId, killMux);
}
}
@@ -7187,7 +7187,7 @@ class ClaudemanApp {
}
// Step 3: Enable respawn if requested (with Ralph-specific prompts)
// NOTE: Prompts must be single-line because screen-manager.ts strips newlines
// NOTE: Prompts must be single-line because tmux send-keys handles them as single input
if (config.enableRespawn) {
const ralphUpdatePrompt = 'Before /clear: Update CLAUDE.md with discoveries and notes, mark completed tasks in @fix_plan.md, write a brief progress summary to a file so the next iteration can continue seamlessly.';
@@ -7269,7 +7269,7 @@ class ClaudemanApp {
const initRes = await fetch(`/api/sessions/${sessionId}/input`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ input: '/init\r', useScreen: true })
body: JSON.stringify({ input: '/init\r', useMux: true })
});
if (!initRes.ok) {
@@ -7319,7 +7319,7 @@ class ClaudemanApp {
const inputRes = await fetch(`/api/sessions/${sessionId}/input`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ input: readCommand, useScreen: true })
body: JSON.stringify({ input: readCommand, useMux: true })
});
if (!inputRes.ok) {
@@ -8363,7 +8363,7 @@ class ClaudemanApp {
await fetch(`/api/sessions/${this.activeSessionId}/input`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ input, useScreen: true })
body: JSON.stringify({ input, useMux: true })
});
}
@@ -10473,13 +10473,13 @@ class ClaudemanApp {
if (panel.classList.contains('open')) {
// Load screens and start stats collection
await this.loadScreens();
await fetch('/api/screens/stats/start', { method: 'POST' });
await this.loadMuxSessions();
await fetch('/api/mux-sessions/stats/start', { method: 'POST' });
this.renderTaskPanel();
if (toggleBtn) toggleBtn.innerHTML = '&#x25BC;'; // Down arrow when open
} else {
// Stop stats collection when panel is closed
await fetch('/api/screens/stats/stop', { method: 'POST' });
await fetch('/api/mux-sessions/stats/stop', { method: 'POST' });
if (toggleBtn) toggleBtn.innerHTML = '&#x25B2;'; // Up arrow when closed
}
}
@@ -14659,19 +14659,19 @@ class ClaudemanApp {
// ========== Mux Sessions (in Monitor Panel) ==========
async loadScreens() {
async loadMuxSessions() {
try {
const res = await fetch('/api/screens');
const res = await fetch('/api/mux-sessions');
const data = await res.json();
this.screenSessions = data.screens || [];
this.renderScreenSessions();
this.muxSessions = data.sessions || [];
this.renderMuxSessions();
} catch (err) {
console.error('Failed to load screens:', err);
console.error('Failed to load mux sessions:', err);
}
}
killAllSessions() {
const count = this.screenSessions?.length || 0;
const count = this.muxSessions?.length || 0;
if (count === 0) {
alert('No sessions to kill');
return;
@@ -14697,27 +14697,27 @@ class ClaudemanApp {
}
}
async confirmKillAll(killScreens) {
async confirmKillAll(killMux) {
this.closeKillAllModal();
try {
if (killScreens) {
if (killMux) {
// Kill everything including tmux sessions
const res = await fetch('/api/sessions', { method: 'DELETE' });
const data = await res.json();
if (data.success) {
this.sessions.clear();
this.screenSessions = [];
this.muxSessions = [];
this.activeSessionId = null;
try { localStorage.removeItem('claudeman-active-session'); } catch {}
this.renderSessionTabs();
this.renderScreenSessions();
this.renderMuxSessions();
this.terminal.clear();
this.terminal.reset();
this.toast('All sessions and tmux killed', 'success');
}
} else {
// Just remove tabs, keep screens running
// Just remove tabs, keep mux sessions running
this.sessions.clear();
this.activeSessionId = null;
try { localStorage.removeItem('claudeman-active-session'); } catch {}
@@ -15048,43 +15048,43 @@ class ClaudemanApp {
setTimeout(() => modal.classList.remove('from-mobile'), 300);
}
renderScreenSessions() {
renderMuxSessions() {
// Debounce renders at 100ms to prevent excessive DOM updates
if (this.renderScreenSessionsTimeout) {
clearTimeout(this.renderScreenSessionsTimeout);
if (this.renderMuxSessionsTimeout) {
clearTimeout(this.renderMuxSessionsTimeout);
}
this.renderScreenSessionsTimeout = setTimeout(() => {
this._renderScreenSessionsImmediate();
this.renderMuxSessionsTimeout = setTimeout(() => {
this._renderMuxSessionsImmediate();
}, 100);
}
_renderScreenSessionsImmediate() {
const body = document.getElementById('screenSessionsBody');
_renderMuxSessionsImmediate() {
const body = document.getElementById('muxSessionsBody');
if (!this.screenSessions || this.screenSessions.length === 0) {
if (!this.muxSessions || this.muxSessions.length === 0) {
body.innerHTML = '<div class="monitor-empty">No mux sessions</div>';
return;
}
let html = '';
for (const screen of this.screenSessions) {
const stats = screen.stats || { memoryMB: 0, cpuPercent: 0, childCount: 0 };
const modeClass = screen.mode === 'shell' ? 'shell' : '';
for (const muxSession of this.muxSessions) {
const stats = muxSession.stats || { memoryMB: 0, cpuPercent: 0, childCount: 0 };
const modeClass = muxSession.mode === 'shell' ? 'shell' : '';
html += `
<div class="process-item">
<span class="process-mode ${modeClass}">${screen.mode}</span>
<span class="process-mode ${modeClass}">${muxSession.mode}</span>
<div class="process-info">
<div class="process-name">${this.escapeHtml(screen.name || screen.screenName)}</div>
<div class="process-name">${this.escapeHtml(muxSession.name || muxSession.muxName)}</div>
<div class="process-meta">
<span class="process-stat memory">${stats.memoryMB}MB</span>
<span class="process-stat cpu">${stats.cpuPercent}%</span>
<span class="process-stat children">${stats.childCount} children</span>
<span>PID: ${screen.pid}</span>
<span>PID: ${muxSession.pid}</span>
</div>
</div>
<div class="process-actions">
<button class="btn-toolbar btn-sm btn-danger" onclick="app.killScreen('${this.escapeHtml(screen.sessionId)}')" title="Kill tmux session">Kill</button>
<button class="btn-toolbar btn-sm btn-danger" onclick="app.killMuxSession('${this.escapeHtml(muxSession.sessionId)}')" title="Kill tmux session">Kill</button>
</div>
</div>
`;
@@ -15136,32 +15136,32 @@ class ClaudemanApp {
body.innerHTML = html;
}
async killScreen(sessionId) {
async killMuxSession(sessionId) {
if (!confirm('Kill this mux session?')) return;
try {
await fetch(`/api/screens/${sessionId}`, { method: 'DELETE' });
this.screenSessions = this.screenSessions.filter(s => s.sessionId !== sessionId);
this.renderScreenSessions();
await fetch(`/api/mux-sessions/${sessionId}`, { method: 'DELETE' });
this.muxSessions = this.muxSessions.filter(s => s.sessionId !== sessionId);
this.renderMuxSessions();
this.showToast('Tmux session killed', 'success');
} catch (err) {
this.showToast('Failed to kill tmux session', 'error');
}
}
async reconcileScreens() {
async reconcileMuxSessions() {
try {
const res = await fetch('/api/screens/reconcile', { method: 'POST' });
const res = await fetch('/api/mux-sessions/reconcile', { method: 'POST' });
const data = await res.json();
if (data.dead && data.dead.length > 0) {
this.showToast(`Found ${data.dead.length} dead screen(s)`, 'warning');
await this.loadScreens();
this.showToast(`Found ${data.dead.length} dead mux session(s)`, 'warning');
await this.loadMuxSessions();
} else {
this.showToast('All screens are alive', 'success');
this.showToast('All mux sessions are alive', 'success');
}
} catch (err) {
this.showToast('Failed to reconcile screens', 'error');
this.showToast('Failed to reconcile mux sessions', 'error');
}
}
+5 -5
View File
@@ -385,13 +385,13 @@
</div>
</div>
<!-- Monitor Panel (Screen Sessions + Background Tasks) -->
<!-- Monitor Panel (Tmux Sessions + Background Tasks) -->
<div class="monitor-panel" id="monitorPanel">
<div class="monitor-panel-header" id="monitorPanelHeader">
<div class="monitor-panel-title">Monitor</div>
<div class="monitor-panel-actions">
<button class="btn-toolbar btn-sm btn-danger" onclick="app.killAllSessions()" title="Kill all sessions and their tmux processes">Kill All</button>
<button class="btn-icon-sm" onclick="app.reconcileScreens()" title="Refresh screens">&#x21BB;</button>
<button class="btn-icon-sm" onclick="app.reconcileMuxSessions()" title="Refresh tmux sessions">&#x21BB;</button>
<button class="btn-icon-sm" onclick="app.toggleMonitorDetach()" title="Detach panel" id="monitorDetachBtn">&#x29C9;</button>
<button class="btn-icon-sm" onclick="app.toggleMonitorPanel()" title="Toggle panel" id="monitorToggleBtn">&#x25B2;</button>
<button class="btn-icon-sm" onclick="app.closeMonitor()" title="Close monitor">&times;</button>
@@ -401,10 +401,10 @@
<div class="monitor-panel-body" id="monitorTabContent">
<div class="monitor-section">
<div class="monitor-section-header">
<span>Screen Sessions</span>
<span>Tmux Sessions</span>
</div>
<div class="monitor-section-body" id="screenSessionsBody">
<div class="monitor-empty">No screen sessions</div>
<div class="monitor-section-body" id="muxSessionsBody">
<div class="monitor-empty">No mux sessions</div>
</div>
</div>
<div class="monitor-section" id="monitorPlanAgentsSection" style="display: none;">
+1 -1
View File
@@ -4626,7 +4626,7 @@ kbd {
color: var(--yellow);
}
/* Combined Monitor Panel (Screen Sessions + Background Tasks) */
/* Combined Monitor Panel (Tmux Sessions + Background Tasks) */
.monitor-panel {
position: fixed;
bottom: var(--toolbar-height);
+3 -3
View File
@@ -41,7 +41,7 @@ const ALLOWED_ENV_PREFIXES = ['CLAUDE_CODE_'];
/** Env var keys that are always blocked (security-sensitive) */
const BLOCKED_ENV_KEYS = new Set([
'PATH', 'LD_PRELOAD', 'LD_LIBRARY_PATH', 'NODE_OPTIONS',
'CLAUDEMAN_SCREEN_NAME', 'CLAUDEMAN_TMUX',
'CLAUDEMAN_MUX_NAME', 'CLAUDEMAN_TMUX',
]);
/** Validate that an env var key is allowed */
@@ -86,7 +86,7 @@ export const RunPromptSchema = z.object({
*/
export const SessionInputSchema = z.object({
input: z.string(),
useScreen: z.boolean().optional(),
useMux: z.boolean().optional(),
});
/**
@@ -193,7 +193,7 @@ export const SettingsUpdateSchema = z.object({
*/
export const SessionInputWithLimitSchema = z.object({
input: z.string().max(100000), // 100KB max input
useScreen: z.boolean().optional(),
useMux: z.boolean().optional(),
});
// ========== Session Mutation Routes ==========
+75 -75
View File
@@ -429,18 +429,18 @@ export class WebServer extends EventEmitter {
}
this.mux = createMultiplexer();
// Set up mux event listeners (SSE event names kept as screen:* for frontend compat)
// Set up mux event listeners
this.mux.on('sessionCreated', (session) => {
this.broadcast('screen:created', session);
this.broadcast('mux:created', session);
});
this.mux.on('sessionKilled', (data) => {
this.broadcast('screen:killed', data);
this.broadcast('mux:killed', data);
});
this.mux.on('sessionDied', (data) => {
this.broadcast('screen:died', data);
this.broadcast('mux:died', data);
});
this.mux.on('statsUpdated', (screens) => {
this.broadcast('screen:statsUpdated', screens);
this.mux.on('statsUpdated', (sessions) => {
this.broadcast('mux:statsUpdated', sessions);
});
// Set up subagent watcher listeners
@@ -789,8 +789,8 @@ export class WebServer extends EventEmitter {
workingDir,
mode: body.mode || 'claude',
name: body.name || '',
screenManager: this.mux,
useScreen: true,
mux: this.mux,
useMux: true,
niceConfig: globalNice,
});
@@ -820,7 +820,7 @@ export class WebServer extends EventEmitter {
const name = String(body.name || '').slice(0, MAX_SESSION_NAME_LENGTH);
session.name = name;
// Also update the screen name if this session has a screen
// Also update the mux session name if applicable
this.mux.updateSessionName(id, session.name);
this.persistSessionState(session);
this.broadcast('session:updated', this.getSessionStateWithRespawn(session));
@@ -854,14 +854,14 @@ export class WebServer extends EventEmitter {
this.app.delete('/api/sessions/:id', async (req): Promise<ApiResponse> => {
const { id } = req.params as { id: string };
const query = req.query as { killScreen?: string };
const killScreen = query.killScreen !== 'false'; // Default to true
const query = req.query as { killMux?: string };
const killMux = query.killMux !== 'false'; // Default to true
if (!this.sessions.has(id)) {
return createErrorResponse(ApiErrorCode.NOT_FOUND, 'Session not found');
}
await this.cleanupSession(id, killScreen);
await this.cleanupSession(id, killMux);
return { success: true };
});
@@ -1512,7 +1512,7 @@ export class WebServer extends EventEmitter {
});
// Write Ralph prompt to file in session's working directory
// This avoids screen input escaping issues with long multi-line prompts
// This avoids mux input escaping issues with long multi-line prompts
this.app.post('/api/sessions/:id/ralph-prompt/write', async (req) => {
const { id } = req.params as { id: string };
const promptResult = RalphPromptWriteSchema.safeParse(req.body);
@@ -1630,14 +1630,14 @@ export class WebServer extends EventEmitter {
});
// Send input to interactive session
// useScreen: true uses writeViaScreen which is more reliable for programmatic input
// useMux: true uses writeViaMux which is more reliable for programmatic input
this.app.post('/api/sessions/:id/input', async (req): Promise<ApiResponse> => {
const { id } = req.params as { id: string };
const result = SessionInputWithLimitSchema.safeParse(req.body);
if (!result.success) {
return createErrorResponse(ApiErrorCode.INVALID_INPUT, result.error.issues[0]?.message ?? 'Validation failed');
}
const { input, useScreen } = result.data;
const { input, useMux } = result.data;
const session = this.sessions.get(id);
if (!session) {
@@ -1649,14 +1649,14 @@ export class WebServer extends EventEmitter {
return createErrorResponse(ApiErrorCode.INVALID_INPUT, `Input exceeds maximum length (${MAX_INPUT_LENGTH} bytes)`);
}
// Write input to PTY. Direct write is synchronous; writeViaScreen
// Write input to PTY. Direct write is synchronous; writeViaMux
// (tmux send-keys) is fire-and-forget to avoid blocking the HTTP response.
if (useScreen) {
if (useMux) {
// Fire-and-forget: don't block HTTP response on tmux child process.
// Fallback to direct write on failure.
session.writeViaScreen(inputStr).then(ok => {
session.writeViaMux(inputStr).then(ok => {
if (!ok) {
console.warn(`[Server] writeViaScreen failed for session ${id}, falling back to direct write`);
console.warn(`[Server] writeViaMux failed for session ${id}, falling back to direct write`);
session.write(inputStr);
}
}).catch(() => {
@@ -1766,7 +1766,7 @@ export class WebServer extends EventEmitter {
return { success: true, config: controller.getConfig(), active: true };
}
// Return pre-saved config from screens.json
// Return pre-saved config from mux-sessions.json
const preConfig = this.mux.getSession(id)?.respawnConfig;
if (preConfig) {
return { success: true, config: preConfig, active: false };
@@ -1795,7 +1795,7 @@ export class WebServer extends EventEmitter {
// Create or get existing controller
let controller = this.respawnControllers.get(id);
if (!controller) {
// Merge request body with pre-saved config from screens.json
// Merge request body with pre-saved config from mux-sessions.json
const preConfig = this.mux.getSession(id)?.respawnConfig;
const config = body || preConfig ? { ...preConfig, ...body } : undefined;
controller = new RespawnController(session, config);
@@ -2566,8 +2566,8 @@ export class WebServer extends EventEmitter {
const niceConfig = await this.getGlobalNiceConfig();
const session = new Session({
workingDir: casePath,
screenManager: this.mux,
useScreen: true,
mux: this.mux,
useMux: true,
mode: mode,
niceConfig: niceConfig,
});
@@ -2738,8 +2738,8 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
// Create temporary session for the AI call using Opus 4.5 for deep reasoning
const session = new Session({
workingDir: process.cwd(),
screenManager: this.mux,
useScreen: false, // No screen needed for one-shot
mux: this.mux,
useMux: false, // No mux needed for one-shot
mode: 'claude',
});
@@ -3449,38 +3449,38 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
}
});
// ============ Screen Management Endpoints ============
// ============ Mux Session Management Endpoints ============
// Get all tracked screens with stats
this.app.get('/api/screens', async () => {
const screens = await this.mux.getSessionsWithStats();
// Get all tracked mux sessions with stats
this.app.get('/api/mux-sessions', async () => {
const sessions = await this.mux.getSessionsWithStats();
return {
screens,
screenAvailable: this.mux.isAvailable()
sessions,
muxAvailable: this.mux.isAvailable()
};
});
// Kill a mux session
this.app.delete('/api/screens/:sessionId', async (req) => {
this.app.delete('/api/mux-sessions/:sessionId', async (req) => {
const { sessionId } = req.params as { sessionId: string };
const success = await this.mux.killSession(sessionId);
return { success };
});
// Reconcile screens (find dead ones)
this.app.post('/api/screens/reconcile', async () => {
// Reconcile mux sessions (find dead ones)
this.app.post('/api/mux-sessions/reconcile', async () => {
const result = await this.mux.reconcileSessions();
return result;
});
// Start stats collection
this.app.post('/api/screens/stats/start', async () => {
this.app.post('/api/mux-sessions/stats/start', async () => {
this.mux.startStatsCollection(STATS_COLLECTION_INTERVAL_MS);
return { success: true };
});
// Stop stats collection
this.app.post('/api/screens/stats/stop', async () => {
this.app.post('/api/mux-sessions/stats/stop', async () => {
this.mux.stopStatsCollection();
return { success: true };
});
@@ -3891,19 +3891,19 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
// Track sessions currently being cleaned up to prevent concurrent cleanup races
private cleaningUp: Set<string> = new Set();
private async cleanupSession(sessionId: string, killScreen: boolean = true): Promise<void> {
private async cleanupSession(sessionId: string, killMux: boolean = true): Promise<void> {
// Guard against concurrent cleanup of the same session
if (this.cleaningUp.has(sessionId)) return;
this.cleaningUp.add(sessionId);
try {
await this._doCleanupSession(sessionId, killScreen);
await this._doCleanupSession(sessionId, killMux);
} finally {
this.cleaningUp.delete(sessionId);
}
}
private async _doCleanupSession(sessionId: string, killScreen: boolean): Promise<void> {
private async _doCleanupSession(sessionId: string, killMux: boolean): Promise<void> {
const session = this.sessions.get(sessionId);
// Stop watching @fix_plan.md for this session
@@ -3912,7 +3912,7 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
}
// Kill all subagents spawned by this session
if (session && killScreen) {
if (session && killMux) {
try {
await subagentWatcher.killSubagentsForSession(session.workingDir);
} catch (err) {
@@ -3994,7 +3994,7 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
if (session) {
// Accumulate tokens to global stats before removing session
// This preserves lifetime usage even after sessions are deleted
if (killScreen && (session.inputTokens > 0 || session.outputTokens > 0 || session.totalCost > 0)) {
if (killMux && (session.inputTokens > 0 || session.outputTokens > 0 || session.totalCost > 0)) {
this.store.addToGlobalStats(session.inputTokens, session.outputTokens, session.totalCost);
// Record to daily stats (for what hasn't been recorded yet via periodic recording)
const lastRecorded = this.lastRecordedTokens.get(sessionId) || { input: 0, output: 0 };
@@ -4043,11 +4043,11 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
fileStreamManager.closeSessionStreams(sessionId);
// Stop watching for images in this session's directory
imageWatcher.unwatchSession(sessionId);
await session.stop(killScreen);
await session.stop(killMux);
this.sessions.delete(sessionId);
// Only remove from state.json if we're also killing the screen.
// When killScreen=false (server shutdown), preserve state for recovery.
if (killScreen) {
// Only remove from state.json if we're also killing the mux session.
// When killMux=false (server shutdown), preserve state for recovery.
if (killMux) {
this.store.removeSession(sessionId);
}
}
@@ -4083,7 +4083,7 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
},
clearTerminal: () => {
// Tell clients to clear their terminal (after screen attach)
// Tell clients to clear their terminal (after mux attach)
this.broadcast('session:clearTerminal', { id: session.id });
},
@@ -4452,7 +4452,7 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
*
* @param session - The session to attach the controller to
* @param config - The persisted respawn configuration
* @param source - Source of the config for logging (e.g., 'state.json' or 'screens.json')
* @param source - Source of the config for logging (e.g., 'state.json' or 'mux-sessions.json')
*/
private restoreRespawnController(
session: Session,
@@ -5074,10 +5074,10 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
// This prevents race conditions where clients connect before state is ready
// CRITICAL: Skip in test mode to prevent tests from picking up user sessions
if (!this.testMode) {
await this.restoreScreenSessions();
await this.restoreMuxSessions();
}
// Clean up stale sessions from state file that don't have active screens
// Clean up stale sessions from state file that don't have active mux sessions
this.cleanupStaleSessions();
await this.app.listen({ port: this.port, host: '0.0.0.0' });
@@ -5156,9 +5156,9 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
return false; // Default disabled (matches UI default)
}
private async restoreScreenSessions(): Promise<void> {
private async restoreMuxSessions(): Promise<void> {
try {
// Reconcile screens to find which ones are still alive (also discovers unknown screens)
// Reconcile mux sessions to find which ones are still alive (also discovers unknown ones)
const { alive, dead, discovered } = await this.mux.reconcileSessions();
if (discovered.length > 0) {
@@ -5168,31 +5168,31 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
if (alive.length > 0 || discovered.length > 0) {
console.log(`[Server] Found ${alive.length + discovered.length} alive mux session(s) from previous run`);
// For each alive screen, create a Session object if it doesn't exist
const screens = this.mux.getSessions();
for (const screen of screens) {
if (!this.sessions.has(screen.sessionId)) {
// For each alive mux session, create a Session object if it doesn't exist
const muxSessions = this.mux.getSessions();
for (const muxSession of muxSessions) {
if (!this.sessions.has(muxSession.sessionId)) {
// Restore session settings from state.json (single source of truth)
const savedState = this.store.getSession(screen.sessionId);
const savedState = this.store.getSession(muxSession.sessionId);
// Determine the correct session name (priority: savedState > screen > muxName)
// Determine the correct session name (priority: savedState > muxSession > muxName)
// This ensures renamed sessions keep their name after server restart
const sessionName = savedState?.name || screen.name || screen.muxName;
const sessionName = savedState?.name || muxSession.name || muxSession.muxName;
// Create a session object for this mux session with the existing session
// Create a session object for this mux session
const session = new Session({
id: screen.sessionId, // Preserve the original session ID
workingDir: screen.workingDir,
mode: screen.mode,
id: muxSession.sessionId, // Preserve the original session ID
workingDir: muxSession.workingDir,
mode: muxSession.mode,
name: sessionName,
mux: this.mux,
useMux: true,
muxSession: screen // Pass the existing session so startInteractive() can attach to it
muxSession: muxSession // Pass the existing session so startInteractive() can attach to it
});
// Update screen name if it was a "Restored:" placeholder or doesn't match saved name
if (savedState?.name && screen.name !== savedState.name) {
this.mux.updateSessionName(screen.sessionId, savedState.name);
// Update session name if it was a "Restored:" placeholder or doesn't match saved name
if (savedState?.name && muxSession.name !== savedState.name) {
this.mux.updateSessionName(muxSession.sessionId, savedState.name);
}
if (savedState) {
// Auto-compact
@@ -5263,18 +5263,18 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
}
}
// Fallback: restore respawn from screens.json if state.json didn't have it
if (!this.respawnControllers.has(session.id) && screen.respawnConfig?.enabled) {
// Fallback: restore respawn from mux-sessions.json if state.json didn't have it
if (!this.respawnControllers.has(session.id) && muxSession.respawnConfig?.enabled) {
try {
this.restoreRespawnController(session, screen.respawnConfig, 'screens.json');
this.restoreRespawnController(session, muxSession.respawnConfig, 'mux-sessions.json');
} catch (err) {
console.error(`[Server] Failed to restore respawn from screens.json for session ${session.id}:`, err);
console.error(`[Server] Failed to restore respawn from mux-sessions.json for session ${session.id}:`, err);
}
}
// Fallback: restore Ralph state from state-inner.json if not already set and not explicitly disabled
if (!session.ralphTracker.enabled && !session.ralphTracker.autoEnableDisabled) {
const ralphState = this.store.getRalphState(screen.sessionId);
const ralphState = this.store.getRalphState(muxSession.sessionId);
if (ralphState?.loop?.enabled) {
session.ralphTracker.restoreState(ralphState.loop, ralphState.todos);
console.log(`[Server] Restored Ralph state from inner store for session ${session.id}`);
@@ -5296,16 +5296,16 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
this.persistSessionState(session);
// Mark it as restored (not started yet - user needs to attach)
console.log(`[Server] Restored session ${session.id} from mux ${screen.muxName}`);
console.log(`[Server] Restored session ${session.id} from mux ${muxSession.muxName}`);
}
}
// Start stats collection to show screen info
// Start stats collection for mux sessions
this.mux.startStatsCollection(STATS_COLLECTION_INTERVAL_MS);
// Start mouse mode sync (tmux only) — toggles mouse on/off based on pane count.
// Mouse off = native xterm.js selection; mouse on = tmux pane clicking (split layouts).
if (this.mux.backend === 'tmux' && 'startMouseModeSync' in this.mux) {
if ('startMouseModeSync' in this.mux) {
(this.mux as { startMouseModeSync: (ms?: number) => void }).startMouseModeSync();
}
}
@@ -5415,7 +5415,7 @@ NOW: Generate the implementation plan for the task above. Think step by step.`;
);
// Properly clean up all remaining sessions in parallel (removes listeners, clears state, etc.)
// Don't kill screens on server stop - they can be reattached on restart
// Don't kill mux sessions on server stop - they can be reattached on restart
// Use Promise.race with a 30s timeout to prevent shutdown from hanging indefinitely
const sessionCleanup = Promise.allSettled(
Array.from(this.sessions.keys()).map(id => this.cleanupSession(id, false))