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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(shell): add web terminal with xterm.js and node-pty
Adam Eivy62b8e650e30b
diff --git a/.changelog/v0.10.x.md b/.changelog/v0.10.x.mdindex 5829b0eb05..b3474019ad 100644--- a/.changelog/v0.10.x.md+++ b/.changelog/v0.10.x.md@@ -170,6 +170,15 @@ This release introduces a structured changelog documentation system for creating- **API Endpoints**: New `/api/attachments` CRUD endpoints for uploading, retrieving, and deleting attachments- **Task Metadata Integration**: Attachments stored in task metadata and serialized properly in TASKS.md+### Web Shell Terminal+- **Full Terminal Emulator**: New `/shell` page provides a web-based terminal interface using xterm.js+- **Real Shell Access**: Uses node-pty for a genuine pseudo-terminal, supporting all shell features including command history, tab completion, and signal handling+- **WebSocket-Based I/O**: Real-time bidirectional communication via Socket.IO for responsive terminal interaction+- **Session Management**: Start, stop, and restart shell sessions with visual connection status indicator+- **Automatic Sizing**: Terminal automatically fits container and resizes when window dimensions change+- **Theme Integration**: Uses PortOS dark theme colors matching the rest of the application+- **Link Detection**: Clickable URLs in terminal output via xterm-addon-web-links+### File Uploads Page- **Dedicated Upload Interface**: New `/uploads` page for general-purpose file storage at `data/uploads/`- **Drag and Drop**: Drop zone with visual feedback for easy file uploadsdiff --git a/client/package.json b/client/package.jsonindex 4a448887c0..2d2a10df61 100644--- a/client/package.json+++ b/client/package.json@@ -12,6 +12,9 @@"@dnd-kit/core": "^6.3.1","@dnd-kit/sortable": "^10.0.0","@dnd-kit/utilities": "^3.2.2",+ "@xterm/addon-fit": "^0.11.0",+ "@xterm/addon-web-links": "^0.12.0",+ "@xterm/xterm": "^6.0.0","lucide-react": "^0.562.0","react": "^18.3.1","react-dom": "^18.3.1",diff --git a/client/src/App.jsx b/client/src/App.jsxindex b0043efc53..b03465b365 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -12,6 +12,7 @@ import Media from './pages/Media';import DigitalTwin from './pages/DigitalTwin';import Agents from './pages/Agents';import Uploads from './pages/Uploads';+import Shell from './pages/Shell';// Lazy load heavier pages for code splitting// DevTools pages are large (~2300 lines total) so lazy load them@@ -58,6 +59,7 @@ export default function App() {<Route path="templates" element={<Templates />} /><Route path="media" element={<Media />} /><Route path="uploads" element={<Uploads />} />+ <Route path="shell" element={<Shell />} /><Route path="agents" element={<Navigate to="/agents/personalities" replace />} /><Route path="agents/:tab" element={<Agents />} /><Route path="*" element={<Navigate to="/" replace />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 0f8e53643b..b2188b40b8 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -31,7 +31,8 @@ import {Users,Link2,LineChart,- Upload+ Upload,+ SquareTerminal} from 'lucide-react';import packageJson from '../../package.json';import Logo from './Logo';@@ -101,7 +102,8 @@ const navItems = []},{ to: '/media', label: 'Media', icon: Camera, single: true },- { to: '/uploads', label: 'Uploads', icon: Upload, single: true }+ { to: '/uploads', label: 'Uploads', icon: Upload, single: true },+ { to: '/shell', label: 'Shell', icon: SquareTerminal, single: true }];const SIDEBAR_KEY = 'portos-sidebar-collapsed';@@ -455,8 +457,8 @@ export default function Layout() {</header>{/* Main content */}- <main id="main-content" className={`flex-1 overflow-auto ${location.pathname.startsWith('/cos') || location.pathname.startsWith('/brain') || location.pathname.startsWith('/digital-twin') || location.pathname.startsWith('/agents') ? '' : 'p-4 md:p-6'}`}>- {location.pathname.startsWith('/cos') || location.pathname.startsWith('/brain') || location.pathname.startsWith('/digital-twin') || location.pathname.startsWith('/agents') ? (+ <main id="main-content" className={`flex-1 overflow-auto ${location.pathname.startsWith('/cos') || location.pathname.startsWith('/brain') || location.pathname.startsWith('/digital-twin') || location.pathname.startsWith('/agents') || location.pathname === '/shell' ? '' : 'p-4 md:p-6'}`}>+ {location.pathname.startsWith('/cos') || location.pathname.startsWith('/brain') || location.pathname.startsWith('/digital-twin') || location.pathname.startsWith('/agents') || location.pathname === '/shell' ? (<Outlet />) : (<div className="max-w-7xl mx-auto">diff --git a/client/src/pages/Shell.jsx b/client/src/pages/Shell.jsxnew file mode 100644index 0000000000..63b86fda59--- /dev/null+++ b/client/src/pages/Shell.jsx@@ -0,0 +1,259 @@+import { useEffect, useRef, useState, useCallback } from 'react';+import { Terminal } from '@xterm/xterm';+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 } from 'lucide-react';++export default function Shell() {+ const terminalRef = useRef(null);+ const termInstanceRef = useRef(null);+ const fitAddonRef = useRef(null);+ const sessionIdRef = useRef(null);+ const socket = useSocket();+ const [connected, setConnected] = useState(false);++ // Initialize terminal once+ useEffect(() => {+ if (!terminalRef.current || termInstanceRef.current) return;++ const term = new Terminal({+ cursorBlink: true,+ cursorStyle: 'block',+ fontSize: 14,+ fontFamily: 'Menlo, Monaco, "Courier New", monospace',+ theme: {+ background: '#0f0f0f',+ foreground: '#e5e5e5',+ cursor: '#3b82f6',+ cursorAccent: '#0f0f0f',+ selectionBackground: '#3b82f640',+ black: '#1a1a1a',+ red: '#ef4444',+ green: '#22c55e',+ yellow: '#f59e0b',+ blue: '#3b82f6',+ magenta: '#a855f7',+ cyan: '#06b6d4',+ white: '#e5e5e5',+ brightBlack: '#404040',+ brightRed: '#f87171',+ brightGreen: '#4ade80',+ brightYellow: '#fbbf24',+ brightBlue: '#60a5fa',+ brightMagenta: '#c084fc',+ brightCyan: '#22d3ee',+ brightWhite: '#ffffff'+ },+ scrollback: 5000,+ allowProposedApi: true+ });++ const fitAddon = new FitAddon();+ const webLinksAddon = new WebLinksAddon();++ term.loadAddon(fitAddon);+ term.loadAddon(webLinksAddon);++ term.open(terminalRef.current);++ // Defer initial fit to next frame for proper sizing+ requestAnimationFrame(() => {+ fitAddon.fit();+ });++ termInstanceRef.current = term;+ fitAddonRef.current = fitAddon;++ return () => {+ term.dispose();+ termInstanceRef.current = null;+ fitAddonRef.current = null;+ };+ }, []);++ // Handle window resize+ useEffect(() => {+ 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,+ cols: termInstanceRef.current.cols,+ rows: termInstanceRef.current.rows+ });+ }+ }+ };++ window.addEventListener('resize', handleResize);+ return () => window.removeEventListener('resize', handleResize);+ }, [socket]);++ // Handle terminal input+ useEffect(() => {+ if (!termInstanceRef.current || !socket) return;++ const disposable = termInstanceRef.current.onData((data) => {+ if (sessionIdRef.current) {+ socket.emit('shell:input', { sessionId: sessionIdRef.current, data });+ }+ });++ return () => disposable.dispose();+ }, [socket]);++ const startSession = useCallback(() => {+ if (!socket) return;+ if (termInstanceRef.current) {+ termInstanceRef.current.clear();+ termInstanceRef.current.writeln('\x1b[36mStarting shell session...\x1b[0m');+ }+ socket.emit('shell:start');+ }, [socket]);++ const stopSession = useCallback(() => {+ if (socket && sessionIdRef.current) {+ socket.emit('shell:stop', { sessionId: sessionIdRef.current });+ sessionIdRef.current = null;+ setConnected(false);+ }+ }, [socket]);++ const restartSession = useCallback(() => {+ if (sessionIdRef.current && socket) {+ socket.emit('shell:stop', { sessionId: sessionIdRef.current });+ }+ sessionIdRef.current = null;+ setConnected(false);+ startSession();+ }, [socket, startSession]);++ // Handle socket connection and shell session events+ useEffect(() => {+ if (!socket) return;++ const handleConnect = () => {+ startSession();+ };++ const handleShellStarted = ({ sessionId: sid }) => {+ sessionIdRef.current = sid;+ setConnected(true);+ // Send initial size+ if (termInstanceRef.current) {+ socket.emit('shell:resize', {+ sessionId: sid,+ cols: termInstanceRef.current.cols,+ rows: termInstanceRef.current.rows+ });+ }+ };++ const handleShellOutput = ({ data }) => {+ if (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 handleShellError = ({ error }) => {+ if (termInstanceRef.current) {+ termInstanceRef.current.writeln(`\r\n\x1b[31m[Error: ${error}]\x1b[0m`);+ }+ };++ socket.on('connect', handleConnect);+ socket.on('shell:started', handleShellStarted);+ socket.on('shell:output', handleShellOutput);+ socket.on('shell:exit', handleShellExit);+ socket.on('shell:error', handleShellError);++ // Start session if already connected+ if (socket.connected) {+ startSession();+ }++ return () => {+ socket.off('connect', handleConnect);+ socket.off('shell:started', handleShellStarted);+ 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;+ }+ };+ }, [socket, startSession]);++ 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 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 ${+ connected ? 'bg-green-500/20 text-green-400' : 'bg-gray-500/20 text-gray-400'+ }`}>+ <div className={`w-2 h-2 rounded-full ${connected ? 'bg-green-500' : 'bg-gray-500'}`} />+ {connected ? 'Connected' : 'Disconnected'}+ </div>+ </div>+ <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"+ >+ <PowerOff size={16} />+ Stop+ </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"+ >+ <Power size={16} />+ Start+ </button>+ )}+ </div>+ </div>++ {/* Terminal container */}+ <div className="flex-1 bg-port-bg rounded-lg border border-port-border overflow-hidden">+ <div+ ref={terminalRef}+ className="w-full h-full"+ style={{ padding: '8px' }}+ />+ </div>+ </div>+ );+}diff --git a/package-lock.json b/package-lock.jsonindex 75bc7abe8e..7b474c1740 100644--- a/package-lock.json+++ b/package-lock.json@@ -33,6 +33,9 @@"@dnd-kit/core": "^6.3.1","@dnd-kit/sortable": "^10.0.0","@dnd-kit/utilities": "^3.2.2",+ "@xterm/addon-fit": "^0.11.0",+ "@xterm/addon-web-links": "^0.12.0",+ "@xterm/xterm": "^6.0.0","lucide-react": "^0.562.0","react": "^18.3.1","react-dom": "^18.3.1",@@ -92,6 +95,7 @@"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@babel/code-frame": "^7.27.1","@babel/generator": "^7.28.5",@@ -380,6 +384,7 @@"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz","integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==","license": "MIT",+ "peer": true,"dependencies": {"@dnd-kit/accessibility": "^3.1.1","@dnd-kit/utilities": "^3.2.2",@@ -1678,6 +1683,7 @@"resolved": "https://registry.npmjs.org/@types/node/-/node-25.0.6.tgz","integrity": "sha512-NNu0sjyNxpoiW3YuVFfNz7mxSQ+S4X2G28uqg2s+CzoqoQjLPsWSbsFFyztIAqt2vb8kfEAsJNepMGPTxFDx3Q==","license": "MIT",+ "peer": true,"dependencies": {"undici-types": "~7.16.0"}@@ -1846,6 +1852,27 @@"url": "https://opencollective.com/vitest"}},+ "node_modules/@xterm/addon-fit": {+ "version": "0.11.0",+ "resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.11.0.tgz",+ "integrity": "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==",+ "license": "MIT"+ },+ "node_modules/@xterm/addon-web-links": {+ "version": "0.12.0",+ "resolved": "https://registry.npmjs.org/@xterm/addon-web-links/-/addon-web-links-0.12.0.tgz",+ "integrity": "sha512-4Smom3RPyVp7ZMYOYDoC/9eGJJJqYhnPLGGqJ6wOBfB8VxPViJNSKdgRYb8NpaM6YSelEKbA2SStD7lGyqaobw==",+ "license": "MIT"+ },+ "node_modules/@xterm/xterm": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.0.0.tgz",+ "integrity": "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==",+ "license": "MIT",+ "workspaces": [+ "addons/*"+ ]+ },"node_modules/accepts": {"version": "2.0.0","resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",@@ -2168,6 +2195,7 @@}],"license": "MIT",+ "peer": true,"dependencies": {"baseline-browser-mapping": "^2.9.0","caniuse-lite": "^1.0.30001759",@@ -2543,7 +2571,8 @@"version": "3.2.3","resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz","integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",- "license": "MIT"+ "license": "MIT",+ "peer": true},"node_modules/culvert": {"version": "0.1.2",@@ -3065,6 +3094,7 @@"resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz","integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==","license": "MIT",+ "peer": true,"dependencies": {"accepts": "^2.0.0","body-parser": "^2.2.1",@@ -3734,6 +3764,7 @@"integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==","dev": true,"license": "MIT",+ "peer": true,"bin": {"jiti": "bin/jiti.js"}@@ -4136,6 +4167,22 @@"node": ">= 0.4.0"}},+ "node_modules/node-addon-api": {+ "version": "7.1.1",+ "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz",+ "integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==",+ "license": "MIT"+ },+ "node_modules/node-pty": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/node-pty/-/node-pty-1.1.0.tgz",+ "integrity": "sha512-20JqtutY6JPXTUnL0ij1uad7Qe1baT46lyolh2sSENDd4sTzKZ4nmAFkeAARDKwmlLjPx6XKRlwRUxwjOy+lUg==",+ "hasInstallScript": true,+ "license": "MIT",+ "dependencies": {+ "node-addon-api": "^7.1.0"+ }+ },"node_modules/node-releases": {"version": "2.0.27","resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.27.tgz",@@ -4578,6 +4625,7 @@}],"license": "MIT",+ "peer": true,"dependencies": {"nanoid": "^3.3.11","picocolors": "^1.1.1",@@ -4842,6 +4890,7 @@"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz","integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==","license": "MIT",+ "peer": true,"dependencies": {"loose-envify": "^1.1.0"},@@ -4854,6 +4903,7 @@"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz","integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==","license": "MIT",+ "peer": true,"dependencies": {"loose-envify": "^1.1.0","scheduler": "^0.23.2"@@ -5865,6 +5915,7 @@"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==","dev": true,"license": "MIT",+ "peer": true,"engines": {"node": ">=12"},@@ -6058,6 +6109,7 @@"integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"esbuild": "^0.25.0","fdir": "^6.4.4",@@ -6151,6 +6203,7 @@"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==","dev": true,"license": "MIT",+ "peer": true,"engines": {"node": ">=12"},@@ -6164,6 +6217,7 @@"integrity": "sha512-E4t7DJ9pESL6E3I8nFjPa4xGUd3PmiWDLsDztS2qXSJWfHtbQnwAWylaBvSNY48I3vr8PTqIZlyK8TE3V3CA4Q==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@vitest/expect": "4.0.16","@vitest/mocker": "4.0.16",@@ -6430,6 +6484,7 @@"dependencies": {"cors": "^2.8.5","express": "^4.21.2",+ "node-pty": "^1.1.0","pm2": "^5.4.3","portos-ai-toolkit": "github:atomantic/portos-ai-toolkit#v0.2.0","socket.io": "^4.8.3",diff --git a/server/package.json b/server/package.jsonindex 004a1da079..7e66b7882e 100644--- a/server/package.json+++ b/server/package.json@@ -12,9 +12,10 @@},"dependencies": {"cors": "^2.8.5",- "portos-ai-toolkit": "github:atomantic/portos-ai-toolkit#v0.2.0","express": "^4.21.2",+ "node-pty": "^1.1.0","pm2": "^5.4.3",+ "portos-ai-toolkit": "github:atomantic/portos-ai-toolkit#v0.2.0","socket.io": "^4.8.3","socket.io-client": "^4.8.3","uuid": "^11.0.3",diff --git a/server/services/shell.js b/server/services/shell.jsnew file mode 100644index 0000000000..4171c2c3c1--- /dev/null+++ b/server/services/shell.js@@ -0,0 +1,131 @@+import * as pty from 'node-pty';+import os from 'os';+import { v4 as uuidv4 } from 'uuid';++// Store active shell sessions+const shellSessions = new Map();++/**+ * Get the default shell for the current OS+ */+function getDefaultShell() {+ if (process.platform === 'win32') {+ return process.env.COMSPEC || 'cmd.exe';+ }+ return process.env.SHELL || '/bin/zsh';+}++/**+ * Create a new shell session+ */+export function createShellSession(socket, options = {}) {+ const sessionId = uuidv4();+ const shell = options.shell || getDefaultShell();+ const cwd = options.cwd || os.homedir();+ const cols = options.cols || 80;+ const rows = options.rows || 24;++ console.log(`🐚 Creating shell session ${sessionId.slice(0, 8)} (${shell})`);++ const ptyProcess = pty.spawn(shell, [], {+ name: 'xterm-256color',+ cols,+ rows,+ cwd,+ env: {+ ...process.env,+ TERM: 'xterm-256color',+ COLORTERM: 'truecolor'+ }+ });++ // Store session info+ shellSessions.set(sessionId, {+ pty: ptyProcess,+ socket,+ createdAt: Date.now()+ });++ // Handle pty output+ ptyProcess.onData((data) => {+ socket.emit('shell:output', { sessionId, data });+ });++ // Handle pty exit+ ptyProcess.onExit(({ exitCode }) => {+ console.log(`🐚 Shell session ${sessionId.slice(0, 8)} exited (code: ${exitCode})`);+ shellSessions.delete(sessionId);+ socket.emit('shell:exit', { sessionId, code: exitCode });+ });++ return sessionId;+}++/**+ * Write input to a shell session+ */+export function writeToSession(sessionId, data) {+ const session = shellSessions.get(sessionId);+ if (session) {+ session.pty.write(data);+ return true;+ }+ return false;+}++/**+ * Resize a shell session+ */+export function resizeSession(sessionId, cols, rows) {+ const session = shellSessions.get(sessionId);+ if (session) {+ session.pty.resize(cols, rows);+ return true;+ }+ return false;+}++/**+ * Kill a shell session+ */+export function killSession(sessionId) {+ const session = shellSessions.get(sessionId);+ if (session) {+ console.log(`🐚 Killing shell session ${sessionId.slice(0, 8)}`);+ session.pty.kill();+ shellSessions.delete(sessionId);+ return true;+ }+ return false;+}++/**+ * Get all active sessions for a socket+ */+export function getSessionsForSocket(socket) {+ const sessions = [];+ for (const [sessionId, session] of shellSessions.entries()) {+ if (session.socket === socket) {+ sessions.push(sessionId);+ }+ }+ 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;+}++/**+ * Get session count+ */+export function getSessionCount() {+ return shellSessions.size;+}diff --git a/server/services/socket.js b/server/services/socket.jsindex 9f15826b4a..d3596161fd 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -11,6 +11,7 @@ import { agentPersonalityEvents } from './agentPersonalities.js';import { platformAccountEvents } from './platformAccounts.js';import { scheduleEvents } from './automationScheduler.js';import { activityEvents } from './agentActivity.js';+import * as shellService from './shell.js';// Store active log streams per socketconst activeStreams = new Map();@@ -231,6 +232,26 @@ export function initSocket(io) {});});+ // Shell session handlers+ socket.on('shell:start', () => {+ const sessionId = shellService.createShellSession(socket);+ socket.emit('shell:started', { sessionId });+ });++ socket.on('shell:input', ({ sessionId, data }) => {+ if (!shellService.writeToSession(sessionId, data)) {+ socket.emit('shell:error', { sessionId, error: 'Session not found' });+ }+ });++ socket.on('shell:resize', ({ sessionId, cols, rows }) => {+ shellService.resizeSession(sessionId, cols, rows);+ });++ socket.on('shell:stop', ({ sessionId }) => {+ shellService.killSession(sessionId);+ });+// Cleanup on disconnectsocket.on('disconnect', () => {console.log(`🔌 Client disconnected: ${socket.id}`);@@ -239,6 +260,11 @@ export function initSocket(io) {errorSubscribers.delete(socket);notificationSubscribers.delete(socket);agentSubscribers.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)`);+ }});});