Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(shell): persist sessions across page navigations with session switcher

Adam Eivy02e97d679caf
diff --git a/client/src/pages/Shell.jsx b/client/src/pages/Shell.jsx
index 881785c491..bff1858468 100644
--- a/client/src/pages/Shell.jsx
+++ b/client/src/pages/Shell.jsx
@@ -5,7 +5,7 @@ import { FitAddon } from '@xterm/addon-fit';
import { WebLinksAddon } from '@xterm/addon-web-links';
import '@xterm/xterm/css/xterm.css';
import { useSocket } from '../hooks/useSocket';
-import { RefreshCw, Power, PowerOff, FolderOpen, ChevronDown } from 'lucide-react';
+import { RefreshCw, Power, PowerOff, FolderOpen, ChevronDown, Plus, X, Terminal as TerminalIcon } from 'lucide-react';
const QUICK_COMMANDS = [
{ label: 'claude', command: 'claude --dangerously-skip-permissions' },
@@ -24,6 +24,17 @@ const getThemeHex = (varName) => {
return '#' + parts.map(n => n.toString(16).padStart(2, '0')).join('');
};
+const formatAge = (createdAt) => {
+ const seconds = Math.floor((Date.now() - createdAt) / 1000);
+ if (seconds < 60) return `${seconds}s`;
+ const minutes = Math.floor(seconds / 60);
+ if (minutes < 60) return `${minutes}m`;
+ const hours = Math.floor(minutes / 60);
+ return `${hours}h${minutes % 60}m`;
+};
+
+const shortId = (id) => id?.slice(0, 6) ?? '';
+
export default function Shell() {
const [searchParams, setSearchParams] = useSearchParams();
const terminalRef = useRef(null);
@@ -31,8 +42,11 @@ export default function Shell() {
const fitAddonRef = useRef(null);
const sessionIdRef = useRef(null);
const initialOptsRef = useRef(null);
+ const hasInitializedRef = useRef(false);
const socket = useSocket();
const [connected, setConnected] = useState(false);
+ const [sessions, setSessions] = useState([]);
+ const [activeSessionId, setActiveSessionId] = useState(null);
const [appFolders, setAppFolders] = useState([]);
const [folderDropdownOpen, setFolderDropdownOpen] = useState(false);
const dropdownRef = useRef(null);
@@ -44,7 +58,6 @@ export default function Shell() {
const cmd = searchParams.get('cmd');
if (cwd || cmd) {
initialOptsRef.current = { cwd, cmd };
- // Clear query params from URL so restart/refresh starts a plain shell
setSearchParams({}, { replace: true });
} else {
initialOptsRef.current = {};
@@ -134,7 +147,6 @@ export default function Shell() {
term.open(terminalRef.current);
- // Defer initial fit to next frame for proper sizing
requestAnimationFrame(() => {
fitAddon.fit();
});
@@ -154,7 +166,6 @@ export default function Shell() {
const handleResize = () => {
if (fitAddonRef.current && termInstanceRef.current) {
fitAddonRef.current.fit();
- // Notify server of resize if we have an active session
if (socket && sessionIdRef.current) {
socket.emit('shell:resize', {
sessionId: sessionIdRef.current,
@@ -182,6 +193,12 @@ export default function Shell() {
return () => disposable.dispose();
}, [socket]);
+ const activateSession = useCallback((sessionId) => {
+ sessionIdRef.current = sessionId;
+ setActiveSessionId(sessionId);
+ setConnected(true);
+ }, []);
+
const startSession = useCallback(() => {
if (!socket) return;
if (termInstanceRef.current) {
@@ -192,40 +209,76 @@ export default function Shell() {
const startOpts = {};
if (opts.cwd) startOpts.cwd = opts.cwd;
if (opts.cmd) startOpts.initialCommand = opts.cmd;
- // Only use initial opts once
initialOptsRef.current = {};
socket.emit('shell:start', Object.keys(startOpts).length > 0 ? startOpts : undefined);
}, [socket]);
+ const attachToSession = useCallback((sessionId) => {
+ if (!socket) return;
+ if (termInstanceRef.current) {
+ termInstanceRef.current.clear();
+ termInstanceRef.current.writeln('\x1b[36mAttaching to session...\x1b[0m');
+ }
+ socket.emit('shell:attach', { sessionId });
+ }, [socket]);
+
const stopSession = useCallback(() => {
if (socket && sessionIdRef.current) {
socket.emit('shell:stop', { sessionId: sessionIdRef.current });
sessionIdRef.current = null;
+ setActiveSessionId(null);
setConnected(false);
+ if (termInstanceRef.current) {
+ termInstanceRef.current.writeln('\r\n\x1b[33m[Session killed]\x1b[0m');
+ }
}
}, [socket]);
- const restartSession = useCallback(() => {
- if (sessionIdRef.current && socket) {
- socket.emit('shell:stop', { sessionId: sessionIdRef.current });
- }
+ const killOtherSession = useCallback((sessionId) => {
+ if (!socket) return;
+ socket.emit('shell:stop', { sessionId });
+ }, [socket]);
+
+ const switchToSession = useCallback((sessionId) => {
+ if (sessionId === sessionIdRef.current) return;
+ // Detach current display (don't kill)
sessionIdRef.current = null;
+ setActiveSessionId(null);
setConnected(false);
- startSession();
- }, [socket, startSession]);
+ attachToSession(sessionId);
+ }, [attachToSession]);
// Handle socket connection and shell session events
useEffect(() => {
if (!socket) return;
const handleConnect = () => {
- startSession();
+ // Request session list first — decide what to do in handleSessions
+ hasInitializedRef.current = false;
+ socket.emit('shell:list');
+ };
+
+ const handleSessions = (sessionList) => {
+ setSessions(sessionList);
+ // On first load, auto-attach to existing session or create new
+ if (!hasInitializedRef.current) {
+ hasInitializedRef.current = true;
+ const opts = initialOptsRef.current || {};
+ // If we have initial opts (cwd/cmd), always create a new session
+ if (opts.cwd || opts.cmd) {
+ startSession();
+ } else if (sessionList.length > 0 && !sessionIdRef.current) {
+ // Attach to most recent existing session
+ const latest = sessionList[sessionList.length - 1];
+ attachToSession(latest.sessionId);
+ } else if (sessionList.length === 0) {
+ startSession();
+ }
+ }
};
const handleShellStarted = ({ sessionId: sid }) => {
- sessionIdRef.current = sid;
- setConnected(true);
- // Send initial size
+ activateSession(sid);
if (termInstanceRef.current) {
socket.emit('shell:resize', {
sessionId: sid,
@@ -235,18 +288,36 @@ export default function Shell() {
}
};
- const handleShellOutput = ({ data }) => {
+ const handleShellAttached = ({ sessionId: sid, bufferedOutput }) => {
+ activateSession(sid);
if (termInstanceRef.current) {
+ termInstanceRef.current.clear();
+ if (bufferedOutput) {
+ termInstanceRef.current.write(bufferedOutput);
+ }
+ socket.emit('shell:resize', {
+ sessionId: sid,
+ cols: termInstanceRef.current.cols,
+ rows: termInstanceRef.current.rows
+ });
+ }
+ };
+
+ const handleShellOutput = ({ sessionId: sid, data }) => {
+ // Only render output for the currently viewed session
+ if (sid === sessionIdRef.current && termInstanceRef.current) {
termInstanceRef.current.write(data);
}
};
- const handleShellExit = ({ code }) => {
- setConnected(false);
- sessionIdRef.current = null;
- if (termInstanceRef.current) {
- termInstanceRef.current.writeln(`\r\n\x1b[33m[Shell exited with code ${code}]\x1b[0m`);
- termInstanceRef.current.writeln('\x1b[90mPress the restart button to start a new session\x1b[0m');
+ const handleShellExit = ({ sessionId: sid, code }) => {
+ if (sid === sessionIdRef.current) {
+ setConnected(false);
+ sessionIdRef.current = null;
+ setActiveSessionId(null);
+ if (termInstanceRef.current) {
+ termInstanceRef.current.writeln(`\r\n\x1b[33m[Shell exited with code ${code}]\x1b[0m`);
+ }
}
};
@@ -257,35 +328,34 @@ export default function Shell() {
};
socket.on('connect', handleConnect);
+ socket.on('shell:sessions', handleSessions);
socket.on('shell:started', handleShellStarted);
+ socket.on('shell:attached', handleShellAttached);
socket.on('shell:output', handleShellOutput);
socket.on('shell:exit', handleShellExit);
socket.on('shell:error', handleShellError);
- // Start session if already connected
if (socket.connected) {
- startSession();
+ handleConnect();
}
return () => {
socket.off('connect', handleConnect);
+ socket.off('shell:sessions', handleSessions);
socket.off('shell:started', handleShellStarted);
+ socket.off('shell:attached', handleShellAttached);
socket.off('shell:output', handleShellOutput);
socket.off('shell:exit', handleShellExit);
socket.off('shell:error', handleShellError);
-
- // Stop shell session on unmount
- if (sessionIdRef.current) {
- socket.emit('shell:stop', { sessionId: sessionIdRef.current });
- sessionIdRef.current = null;
- }
+ // Don't kill session on unmount — it persists server-side
+ sessionIdRef.current = null;
};
- }, [socket, startSession]);
+ }, [socket, startSession, attachToSession, activateSession]);
return (
<div className="h-full flex flex-col p-4 md:p-6">
{/* Header */}
- <div className="flex items-center justify-between mb-4">
+ <div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-3">
<h1 className="text-xl font-semibold text-white">Shell</h1>
<div className={`flex items-center gap-2 px-2 py-1 rounded text-sm ${
@@ -298,40 +368,73 @@ export default function Shell() {
<div className="flex items-center gap-2">
{connected ? (
<>
- <button
- onClick={restartSession}
- className="flex items-center gap-2 px-3 py-2 bg-port-border hover:bg-port-border/80 text-white rounded-lg text-sm transition-colors min-h-[40px]"
- title="Restart session"
- >
- <RefreshCw size={16} />
- Restart
- </button>
<button
onClick={stopSession}
className="flex items-center gap-2 px-3 py-2 bg-red-500/20 hover:bg-red-500/30 text-red-400 rounded-lg text-sm transition-colors min-h-[40px]"
- title="Stop session"
+ title="Kill current session"
>
<PowerOff size={16} />
- Stop
+ Kill
</button>
</>
) : (
<button
onClick={startSession}
className="flex items-center gap-2 px-3 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg text-sm transition-colors min-h-[40px]"
- title="Start session"
+ title="Start new session"
>
<Power size={16} />
- Start
+ New Session
</button>
)}
</div>
</div>
+ {/* Session tabs */}
+ {sessions.length > 0 && (
+ <div className="flex items-center gap-1.5 mb-3 overflow-x-auto pb-1">
+ {sessions.map((s) => {
+ const isActive = s.sessionId === activeSessionId;
+ const label = s.cwd?.split('/').pop() || shortId(s.sessionId);
+ return (
+ <div
+ key={s.sessionId}
+ className={`group flex items-center gap-1.5 px-2.5 py-1.5 rounded text-xs font-mono transition-colors cursor-pointer min-h-[36px] ${
+ isActive
+ ? 'bg-port-accent/20 text-port-accent border border-port-accent/40'
+ : 'bg-port-card hover:bg-port-border text-gray-400 hover:text-white border border-port-border'
+ }`}
+ onClick={() => !isActive && switchToSession(s.sessionId)}
+ title={`${s.cwd || shortId(s.sessionId)} — ${formatAge(s.createdAt)} old`}
+ >
+ <TerminalIcon size={12} />
+ <span className="truncate max-w-[100px]">{label}</span>
+ <span className="text-[10px] opacity-60">{formatAge(s.createdAt)}</span>
+ {!isActive && (
+ <button
+ onClick={(e) => { e.stopPropagation(); killOtherSession(s.sessionId); }}
+ className="opacity-0 group-hover:opacity-100 hover:text-red-400 transition-opacity ml-0.5"
+ title="Kill session"
+ >
+ <X size={12} />
+ </button>
+ )}
+ </div>
+ );
+ })}
+ <button
+ onClick={startSession}
+ className="flex items-center gap-1 px-2 py-1.5 text-xs text-gray-500 hover:text-white hover:bg-port-border rounded transition-colors min-h-[36px]"
+ title="New session"
+ >
+ <Plus size={14} />
+ </button>
+ </div>
+ )}
+
{/* Quick commands toolbar */}
{connected && (
<div className="flex items-center gap-2 mb-3 flex-wrap">
- {/* Quick command buttons */}
{QUICK_COMMANDS.map(({ label, command }) => (
<button
key={label}
diff --git a/server/services/shell.js b/server/services/shell.js
index 283b3e8493..48e1a68777 100644
--- a/server/services/shell.js
+++ b/server/services/shell.js
@@ -2,10 +2,10 @@ import * as pty from 'node-pty';
import os from 'os';
import { v4 as uuidv4 } from 'uuid';
-// Store active shell sessions
+// Store active shell sessions (persist across socket reconnects)
const shellSessions = new Map();
-const MAX_SESSIONS_PER_SOCKET = 3;
+const MAX_TOTAL_SESSIONS = 5;
// Allowlist of safe environment variable prefixes to pass to PTY sessions
// Prevents leaking secrets (API keys, tokens) to the shell
@@ -42,10 +42,9 @@ function getDefaultShell() {
* Create a new shell session
*/
export function createShellSession(socket, options = {}) {
- const existing = getSessionsForSocket(socket);
- if (existing.length >= MAX_SESSIONS_PER_SOCKET) {
- console.warn(`🐚 Socket ${socket.id} exceeded max sessions (${MAX_SESSIONS_PER_SOCKET})`);
- socket.emit('shell:error', { error: `Max ${MAX_SESSIONS_PER_SOCKET} shell sessions per connection` });
+ if (shellSessions.size >= MAX_TOTAL_SESSIONS) {
+ console.warn(`🐚 Max total sessions reached (${MAX_TOTAL_SESSIONS})`);
+ socket.emit('shell:error', { error: `Max ${MAX_TOTAL_SESSIONS} shell sessions. Kill an existing session first.` });
return null;
}
@@ -76,28 +75,95 @@ export function createShellSession(socket, options = {}) {
return null;
}
+ // Buffer recent output for re-attach (last 50KB)
+ const outputBuffer = [];
+ let bufferSize = 0;
+ const MAX_BUFFER = 50 * 1024;
+
// Store session info
shellSessions.set(sessionId, {
pty: ptyProcess,
socket,
- createdAt: Date.now()
+ cwd,
+ createdAt: Date.now(),
+ outputBuffer,
+ bufferSize: () => bufferSize
});
// Handle pty output
ptyProcess.onData((data) => {
- socket.emit('shell:output', { sessionId, data });
+ // Buffer output for re-attach
+ outputBuffer.push(data);
+ bufferSize += data.length;
+ while (bufferSize > MAX_BUFFER && outputBuffer.length > 1) {
+ bufferSize -= outputBuffer.shift().length;
+ }
+ const session = shellSessions.get(sessionId);
+ session?.socket?.emit('shell:output', { sessionId, data });
});
// Handle pty exit
ptyProcess.onExit(({ exitCode }) => {
console.log(`🐚 Shell session ${sessionId.slice(0, 8)} exited (code: ${exitCode})`);
+ const session = shellSessions.get(sessionId);
shellSessions.delete(sessionId);
- socket.emit('shell:exit', { sessionId, code: exitCode });
+ session?.socket?.emit('shell:exit', { sessionId, code: exitCode });
+ // Notify all sockets about session list change
+ broadcastSessionList();
});
+ broadcastSessionList();
return sessionId;
}
+/**
+ * Attach an existing session to a new socket
+ */
+export function attachSession(sessionId, socket) {
+ const session = shellSessions.get(sessionId);
+ if (!session) return null;
+ // Detach from old socket
+ session.socket = socket;
+ console.log(`🐚 Attached session ${sessionId.slice(0, 8)} to socket ${socket.id}`);
+ return {
+ sessionId,
+ bufferedOutput: session.outputBuffer.join('')
+ };
+}
+
+// Subscribers for session list broadcasts
+const sessionListSubscribers = new Set();
+
+export function subscribeSessionList(socket) {
+ sessionListSubscribers.add(socket);
+}
+
+export function unsubscribeSessionList(socket) {
+ sessionListSubscribers.delete(socket);
+}
+
+function broadcastSessionList() {
+ const list = listAllSessions();
+ for (const sock of sessionListSubscribers) {
+ sock.emit('shell:sessions', list);
+ }
+}
+
+/**
+ * List all active sessions with metadata
+ */
+export function listAllSessions() {
+ const sessions = [];
+ for (const [sessionId, session] of shellSessions.entries()) {
+ sessions.push({
+ sessionId,
+ cwd: session.cwd,
+ createdAt: session.createdAt
+ });
+ }
+ return sessions;
+}
+
/**
* Write input to a shell session
*/
@@ -131,33 +197,25 @@ export function killSession(sessionId) {
console.log(`🐚 Killing shell session ${sessionId.slice(0, 8)}`);
session.pty.kill();
shellSessions.delete(sessionId);
+ broadcastSessionList();
return true;
}
return false;
}
/**
- * Get all active sessions for a socket
+ * Detach all sessions from a socket (on disconnect) — sessions stay alive
*/
-export function getSessionsForSocket(socket) {
- const sessions = [];
- for (const [sessionId, session] of shellSessions.entries()) {
+export function detachSocketSessions(socket) {
+ let count = 0;
+ for (const [, session] of shellSessions.entries()) {
if (session.socket === socket) {
- sessions.push(sessionId);
+ session.socket = null;
+ count++;
}
}
- return sessions;
-}
-
-/**
- * Clean up all sessions for a socket (on disconnect)
- */
-export function cleanupSocketSessions(socket) {
- const sessions = getSessionsForSocket(socket);
- for (const sessionId of sessions) {
- killSession(sessionId);
- }
- return sessions.length;
+ unsubscribeSessionList(socket);
+ return count;
}
/**
diff --git a/server/services/socket.js b/server/services/socket.js
index cca2f9c93b..ff0856c36f 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -384,6 +384,22 @@ export function initSocket(io) {
}
});
+ socket.on('shell:attach', (rawData) => {
+ const validated = validateSocketData(shellStopSchema, rawData, socket, 'shell:attach');
+ if (!validated) return;
+ const result = shellService.attachSession(validated.sessionId, socket);
+ if (result) {
+ socket.emit('shell:attached', result);
+ } else {
+ socket.emit('shell:error', { error: 'Session not found' });
+ }
+ });
+
+ socket.on('shell:list', () => {
+ shellService.subscribeSessionList(socket);
+ socket.emit('shell:sessions', shellService.listAllSessions());
+ });
+
socket.on('shell:input', (rawData) => {
const validated = validateSocketData(shellInputSchema, rawData, socket, 'shell:input');
if (!validated) return;
@@ -404,7 +420,7 @@ export function initSocket(io) {
shellService.killSession(validated.sessionId);
});
- // Cleanup on disconnect
+ // Cleanup on disconnect — detach sessions, don't kill them
socket.on('disconnect', () => {
console.log(`🔌 Client disconnected: ${socket.id}`);
cleanupStream(socket.id);
@@ -413,10 +429,9 @@ export function initSocket(io) {
notificationSubscribers.delete(socket);
agentSubscribers.delete(socket);
instanceSubscribers.delete(socket);
- // Clean up any shell sessions for this socket
- const shellsClosed = shellService.cleanupSocketSessions(socket);
- if (shellsClosed > 0) {
- console.log(`🐚 Cleaned up ${shellsClosed} shell session(s)`);
+ const detached = shellService.detachSocketSessions(socket);
+ if (detached > 0) {
+ console.log(`🐚 Detached ${detached} shell session(s) (still running)`);
}
});
});