ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
Add full-stack remote terminal/PTY support
Juan Denisfd90e2eead28
diff --git a/SERVERS_INTEGRATION_PLAN.md b/SERVERS_INTEGRATION_PLAN.mdindex a4889659..d090cf47 100644--- a/SERVERS_INTEGRATION_PLAN.md+++ b/SERVERS_INTEGRATION_PLAN.md@@ -1344,7 +1344,7 @@ system:exec: # Requires explicit permission[x] Download page in UI```-### Phase 10.8: Advanced Features ✅ MOSTLY COMPLETE+### Phase 10.8: Advanced Features ✅ COMPLETE**Duration: ~3-4 weeks**```@@ -1364,10 +1364,11 @@ system:exec: # Requires explicit permission[ ] Log search/filter (future)[ ] Download logs (future)-[ ] Remote terminal (optional - lower priority)- [ ] PTY support in agent- [ ] Terminal UI component- [ ] Session management+[x] Remote terminal+ [x] PTY support in agent (creack/pty library)+ [x] Terminal manager for session management+ [x] Backend terminal service and API endpoints+ [x] Frontend xterm.js terminal component (RemoteTerminal.jsx)```---diff --git a/agent/agent.exe b/agent/agent.exeindex 0f316df4..7fce245a 100644Binary files a/agent/agent.exe and b/agent/agent.exe differdiff --git a/agent/go.mod b/agent/go.modindex 688d2d17..9bd057c9 100644--- a/agent/go.mod+++ b/agent/go.mod@@ -3,6 +3,7 @@ module github.com/serverkit/agentgo 1.21require (+ github.com/creack/pty v1.1.21github.com/docker/docker v24.0.7+incompatiblegithub.com/gorilla/websocket v1.5.1github.com/shirou/gopsutil/v3 v3.24.1diff --git a/agent/go.sum b/agent/go.sumindex a273f328..30a2141c 100644--- a/agent/go.sum+++ b/agent/go.sum@@ -3,6 +3,8 @@ github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg6github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow=github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM=github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=+github.com/creack/pty v1.1.21 h1:1/QdRyBaHHJP61QkWMXlOIBfsgdDeeKfK8SYVUWJKf0=+github.com/creack/pty v1.1.21/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4=github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=diff --git a/agent/internal/agent/agent.go b/agent/internal/agent/agent.goindex 3cc50354..88460a43 100644--- a/agent/internal/agent/agent.go+++ b/agent/internal/agent/agent.go@@ -2,6 +2,7 @@ package agentimport ("context"+ "encoding/base64""encoding/json""fmt""sync"@@ -12,18 +13,20 @@ import ("github.com/serverkit/agent/internal/docker""github.com/serverkit/agent/internal/logger""github.com/serverkit/agent/internal/metrics"+ "github.com/serverkit/agent/internal/terminal""github.com/serverkit/agent/internal/ws""github.com/serverkit/agent/pkg/protocol")// Agent is the main agent that coordinates all componentstype Agent struct {- cfg *config.Config- log *logger.Logger- auth *auth.Authenticator- ws *ws.Client- docker *docker.Client- metrics *metrics.Collector+ cfg *config.Config+ log *logger.Logger+ auth *auth.Authenticator+ ws *ws.Client+ docker *docker.Client+ metrics *metrics.Collector+ terminal *terminal.Manager// Active subscriptionssubscriptions map[string]context.CancelFunc@@ -61,6 +64,13 @@ func New(cfg *config.Config, log *logger.Logger) (*Agent, error) {metricsCollector = metrics.NewCollector(cfg.Metrics, log)}+ // Create terminal manager if exec is enabled+ var termManager *terminal.Manager+ if cfg.Features.Exec {+ termManager = terminal.NewManager()+ log.Info("Terminal/PTY support enabled")+ }+agent := &Agent{cfg: cfg,log: log,@@ -68,6 +78,7 @@ func New(cfg *config.Config, log *logger.Logger) (*Agent, error) {ws: wsClient,docker: dockerClient,metrics: metricsCollector,+ terminal: termManager,subscriptions: make(map[string]context.CancelFunc),handlers: make(map[string]CommandHandler),}@@ -122,6 +133,14 @@ func (a *Agent) registerHandlers() {a.handlers[protocol.ActionSystemInfo] = a.handleSystemInfoa.handlers[protocol.ActionSystemProcesses] = a.handleSystemProcesses}++ // Terminal commands+ if a.terminal != nil {+ a.handlers[protocol.ActionTerminalCreate] = a.handleTerminalCreate+ a.handlers[protocol.ActionTerminalInput] = a.handleTerminalInput+ a.handlers[protocol.ActionTerminalResize] = a.handleTerminalResize+ a.handlers[protocol.ActionTerminalClose] = a.handleTerminalClose+ }}// Run starts the agent@@ -368,6 +387,11 @@ func (a *Agent) cleanup() {a.subscriptions = make(map[string]context.CancelFunc)a.subMu.Unlock()+ // Close all terminal sessions+ if a.terminal != nil {+ a.terminal.CloseAll()+ }+// Close WebSocketa.ws.Close()@@ -707,3 +731,155 @@ func (a *Agent) handleDockerComposePull(ctx context.Context, params json.RawMess"output": output,}, nil}++// Terminal command handlers++func (a *Agent) handleTerminalCreate(ctx context.Context, params json.RawMessage) (interface{}, error) {+ var p struct {+ SessionID string `json:"session_id"`+ Cols uint16 `json:"cols"`+ Rows uint16 `json:"rows"`+ }+ if err := json.Unmarshal(params, &p); err != nil {+ return nil, fmt.Errorf("invalid params: %w", err)+ }++ if p.SessionID == "" {+ return nil, fmt.Errorf("session_id is required")+ }++ // Default terminal size+ if p.Cols == 0 {+ p.Cols = 80+ }+ if p.Rows == 0 {+ p.Rows = 24+ }++ // Create terminal session+ session, err := a.terminal.CreateSession(p.SessionID, p.Cols, p.Rows)+ if err != nil {+ return nil, fmt.Errorf("failed to create terminal session: %w", err)+ }++ // Set up output handler to stream data back+ channel := fmt.Sprintf(protocol.ChannelTerminal, p.SessionID)+ session.SetOutputHandler(func(data []byte) {+ // Encode as base64 for safe transport+ encoded := base64.StdEncoding.EncodeToString(data)+ if err := a.ws.SendStream(channel, map[string]interface{}{+ "type": "output",+ "data": encoded,+ }); err != nil {+ a.log.Warn("Failed to send terminal output", "error", err)+ }+ })++ // Set up close handler+ session.SetCloseHandler(func() {+ if err := a.ws.SendStream(channel, map[string]interface{}{+ "type": "closed",+ }); err != nil {+ a.log.Warn("Failed to send terminal close event", "error", err)+ }+ // Clean up session+ a.terminal.CloseSession(p.SessionID)+ })++ a.log.Info("Terminal session created",+ "session_id", p.SessionID,+ "cols", p.Cols,+ "rows", p.Rows,+ "shell", session.Shell,+ )++ return map[string]interface{}{+ "success": true,+ "session_id": p.SessionID,+ "shell": session.Shell,+ "cols": session.Cols,+ "rows": session.Rows,+ }, nil+}++func (a *Agent) handleTerminalInput(ctx context.Context, params json.RawMessage) (interface{}, error) {+ var p struct {+ SessionID string `json:"session_id"`+ Data string `json:"data"` // base64 encoded+ }+ if err := json.Unmarshal(params, &p); err != nil {+ return nil, fmt.Errorf("invalid params: %w", err)+ }++ session, ok := a.terminal.GetSession(p.SessionID)+ if !ok {+ return nil, fmt.Errorf("terminal session not found: %s", p.SessionID)+ }++ // Decode base64 data+ data, err := base64.StdEncoding.DecodeString(p.Data)+ if err != nil {+ return nil, fmt.Errorf("invalid base64 data: %w", err)+ }++ // Write to terminal+ _, err = session.Write(data)+ if err != nil {+ return nil, fmt.Errorf("failed to write to terminal: %w", err)+ }++ return map[string]interface{}{+ "success": true,+ }, nil+}++func (a *Agent) handleTerminalResize(ctx context.Context, params json.RawMessage) (interface{}, error) {+ var p struct {+ SessionID string `json:"session_id"`+ Cols uint16 `json:"cols"`+ Rows uint16 `json:"rows"`+ }+ if err := json.Unmarshal(params, &p); err != nil {+ return nil, fmt.Errorf("invalid params: %w", err)+ }++ session, ok := a.terminal.GetSession(p.SessionID)+ if !ok {+ return nil, fmt.Errorf("terminal session not found: %s", p.SessionID)+ }++ if err := session.Resize(p.Cols, p.Rows); err != nil {+ return nil, fmt.Errorf("failed to resize terminal: %w", err)+ }++ a.log.Debug("Terminal resized",+ "session_id", p.SessionID,+ "cols", p.Cols,+ "rows", p.Rows,+ )++ return map[string]interface{}{+ "success": true,+ "cols": p.Cols,+ "rows": p.Rows,+ }, nil+}++func (a *Agent) handleTerminalClose(ctx context.Context, params json.RawMessage) (interface{}, error) {+ var p struct {+ SessionID string `json:"session_id"`+ }+ if err := json.Unmarshal(params, &p); err != nil {+ return nil, fmt.Errorf("invalid params: %w", err)+ }++ if err := a.terminal.CloseSession(p.SessionID); err != nil {+ return nil, fmt.Errorf("failed to close terminal: %w", err)+ }++ a.log.Info("Terminal session closed", "session_id", p.SessionID)++ return map[string]interface{}{+ "success": true,+ }, nil+}diff --git a/agent/internal/terminal/terminal.go b/agent/internal/terminal/terminal.gonew file mode 100644index 00000000..d46835ca--- /dev/null+++ b/agent/internal/terminal/terminal.go@@ -0,0 +1,303 @@+// Package terminal provides PTY (pseudo-terminal) support for remote shell sessions.+package terminal++import (+ "context"+ "fmt"+ "io"+ "os"+ "os/exec"+ "runtime"+ "sync"++ "github.com/creack/pty"+)++// Session represents an active terminal session+type Session struct {+ ID string+ Shell string+ Cols uint16+ Rows uint16+ cmd *exec.Cmd+ pty *os.File+ ctx context.Context+ cancel context.CancelFunc+ mu sync.Mutex+ closed bool+ onOutput func(data []byte)+ onClose func()+}++// Manager manages terminal sessions+type Manager struct {+ sessions map[string]*Session+ mu sync.RWMutex+}++// NewManager creates a new terminal manager+func NewManager() *Manager {+ return &Manager{+ sessions: make(map[string]*Session),+ }+}++// CreateSession creates a new terminal session+func (m *Manager) CreateSession(id string, cols, rows uint16) (*Session, error) {+ m.mu.Lock()+ defer m.mu.Unlock()++ // Check if session already exists+ if _, exists := m.sessions[id]; exists {+ return nil, fmt.Errorf("session %s already exists", id)+ }++ // Determine the shell to use+ shell := getDefaultShell()++ ctx, cancel := context.WithCancel(context.Background())++ session := &Session{+ ID: id,+ Shell: shell,+ Cols: cols,+ Rows: rows,+ ctx: ctx,+ cancel: cancel,+ }++ // Start the shell with PTY+ if err := session.start(); err != nil {+ cancel()+ return nil, fmt.Errorf("failed to start shell: %w", err)+ }++ m.sessions[id] = session+ return session, nil+}++// GetSession retrieves a session by ID+func (m *Manager) GetSession(id string) (*Session, bool) {+ m.mu.RLock()+ defer m.mu.RUnlock()+ session, exists := m.sessions[id]+ return session, exists+}++// CloseSession closes and removes a session+func (m *Manager) CloseSession(id string) error {+ m.mu.Lock()+ session, exists := m.sessions[id]+ if exists {+ delete(m.sessions, id)+ }+ m.mu.Unlock()++ if !exists {+ return fmt.Errorf("session %s not found", id)+ }++ return session.Close()+}++// CloseAll closes all sessions+func (m *Manager) CloseAll() {+ m.mu.Lock()+ sessions := make([]*Session, 0, len(m.sessions))+ for _, s := range m.sessions {+ sessions = append(sessions, s)+ }+ m.sessions = make(map[string]*Session)+ m.mu.Unlock()++ for _, s := range sessions {+ s.Close()+ }+}++// ListSessions returns all active session IDs+func (m *Manager) ListSessions() []string {+ m.mu.RLock()+ defer m.mu.RUnlock()++ ids := make([]string, 0, len(m.sessions))+ for id := range m.sessions {+ ids = append(ids, id)+ }+ return ids+}++// start initializes the PTY and starts the shell+func (s *Session) start() error {+ s.mu.Lock()+ defer s.mu.Unlock()++ // Create the command+ s.cmd = exec.CommandContext(s.ctx, s.Shell)++ // Set up environment+ s.cmd.Env = append(os.Environ(),+ "TERM=xterm-256color",+ "COLORTERM=truecolor",+ )++ // Start with PTY+ ptmx, err := pty.StartWithSize(s.cmd, &pty.Winsize{+ Cols: s.Cols,+ Rows: s.Rows,+ })+ if err != nil {+ return fmt.Errorf("failed to start pty: %w", err)+ }++ s.pty = ptmx++ // Start reading output in background+ go s.readLoop()++ return nil+}++// readLoop continuously reads from the PTY and calls the output handler+func (s *Session) readLoop() {+ buf := make([]byte, 4096)++ for {+ select {+ case <-s.ctx.Done():+ return+ default:+ }++ n, err := s.pty.Read(buf)+ if err != nil {+ if err != io.EOF {+ // Log error but don't break - might be temporary+ }+ // Check if we should exit+ s.mu.Lock()+ closed := s.closed+ s.mu.Unlock()+ if closed {+ return+ }+ // Shell might have exited+ if s.onClose != nil {+ s.onClose()+ }+ return+ }++ if n > 0 && s.onOutput != nil {+ // Make a copy of the data+ data := make([]byte, n)+ copy(data, buf[:n])+ s.onOutput(data)+ }+ }+}++// Write sends input to the terminal+func (s *Session) Write(data []byte) (int, error) {+ s.mu.Lock()+ defer s.mu.Unlock()++ if s.closed || s.pty == nil {+ return 0, fmt.Errorf("session is closed")+ }++ return s.pty.Write(data)+}++// Resize changes the terminal size+func (s *Session) Resize(cols, rows uint16) error {+ s.mu.Lock()+ defer s.mu.Unlock()++ if s.closed || s.pty == nil {+ return fmt.Errorf("session is closed")+ }++ s.Cols = cols+ s.Rows = rows++ return pty.Setsize(s.pty, &pty.Winsize{+ Cols: cols,+ Rows: rows,+ })+}++// SetOutputHandler sets the callback for terminal output+func (s *Session) SetOutputHandler(handler func(data []byte)) {+ s.onOutput = handler+}++// SetCloseHandler sets the callback for when the session closes+func (s *Session) SetCloseHandler(handler func()) {+ s.onClose = handler+}++// Close terminates the terminal session+func (s *Session) Close() error {+ s.mu.Lock()+ defer s.mu.Unlock()++ if s.closed {+ return nil+ }++ s.closed = true+ s.cancel()++ var errs []error++ if s.pty != nil {+ if err := s.pty.Close(); err != nil {+ errs = append(errs, fmt.Errorf("failed to close pty: %w", err))+ }+ }++ if s.cmd != nil && s.cmd.Process != nil {+ if err := s.cmd.Process.Kill(); err != nil {+ // Process might have already exited+ }+ }++ if len(errs) > 0 {+ return errs[0]+ }+ return nil+}++// IsClosed returns whether the session is closed+func (s *Session) IsClosed() bool {+ s.mu.Lock()+ defer s.mu.Unlock()+ return s.closed+}++// getDefaultShell returns the default shell for the current platform+func getDefaultShell() string {+ if runtime.GOOS == "windows" {+ // Try PowerShell first, fall back to cmd+ if _, err := exec.LookPath("powershell.exe"); err == nil {+ return "powershell.exe"+ }+ return "cmd.exe"+ }++ // Unix: try to get user's shell from environment+ if shell := os.Getenv("SHELL"); shell != "" {+ return shell+ }++ // Fall back to common shells+ shells := []string{"/bin/bash", "/bin/sh", "/bin/zsh"}+ for _, shell := range shells {+ if _, err := os.Stat(shell); err == nil {+ return shell+ }+ }++ return "/bin/sh"+}diff --git a/agent/pkg/protocol/messages.go b/agent/pkg/protocol/messages.goindex e713f81f..51ece102 100644--- a/agent/pkg/protocol/messages.go+++ b/agent/pkg/protocol/messages.go@@ -198,11 +198,18 @@ const (ActionFileRead = "file:read"ActionFileWrite = "file:write"ActionFileList = "file:list"++ // Terminal/PTY actions+ ActionTerminalCreate = "terminal:create"+ ActionTerminalInput = "terminal:input"+ ActionTerminalResize = "terminal:resize"+ ActionTerminalClose = "terminal:close")// Stream channelsconst (- ChannelMetrics = "metrics"- ChannelContainerLogs = "container:%s:logs"+ ChannelMetrics = "metrics"+ ChannelContainerLogs = "container:%s:logs"ChannelContainerStats = "container:%s:stats"+ ChannelTerminal = "terminal:%s")diff --git a/backend/app/api/servers.py b/backend/app/api/servers.pyindex 7c35bbf5..08aa77c5 100644--- a/backend/app/api/servers.py+++ b/backend/app/api/servers.py@@ -611,6 +611,7 @@ def get_permission_profiles():from app.services.remote_docker_service import RemoteDockerServicefrom app.services.server_metrics_service import ServerMetricsService+from app.services.terminal_service import TerminalService@servers_bp.route('/available', methods=['GET'])@@ -1102,6 +1103,124 @@ def trigger_metrics_cleanup():})+# ==================== Remote Terminal ====================++@servers_bp.route('/<server_id>/terminal', methods=['POST'])+@jwt_required()+@developer_required+def create_terminal_session(server_id):+ """Create a new terminal session on a remote server.++ Body:+ cols: Terminal width (default: 80)+ rows: Terminal height (default: 24)+ """+ user_id = get_jwt_identity()+ data = request.get_json() or {}++ cols = data.get('cols', 80)+ rows = data.get('rows', 24)++ result = TerminalService.create_session(+ server_id=server_id,+ user_id=user_id,+ cols=cols,+ rows=rows+ )++ if not result.get('success'):+ return jsonify(result), 500 if result.get('code') != 'AGENT_OFFLINE' else 503++ return jsonify(result)+++@servers_bp.route('/terminal/<session_id>/input', methods=['POST'])+@jwt_required()+@developer_required+def terminal_input(session_id):+ """Send input to a terminal session.++ Body:+ data: Base64-encoded input data+ """+ user_id = get_jwt_identity()+ data = request.get_json()++ if not data or not data.get('data'):+ return jsonify({'error': 'data is required'}), 400++ result = TerminalService.send_input(+ session_id=session_id,+ data=data['data'],+ user_id=user_id+ )++ if not result.get('success'):+ return jsonify(result), 400++ return jsonify(result)+++@servers_bp.route('/terminal/<session_id>/resize', methods=['POST'])+@jwt_required()+@developer_required+def terminal_resize(session_id):+ """Resize a terminal session.++ Body:+ cols: New terminal width+ rows: New terminal height+ """+ user_id = get_jwt_identity()+ data = request.get_json()++ if not data or not data.get('cols') or not data.get('rows'):+ return jsonify({'error': 'cols and rows are required'}), 400++ result = TerminalService.resize_session(+ session_id=session_id,+ cols=data['cols'],+ rows=data['rows'],+ user_id=user_id+ )++ if not result.get('success'):+ return jsonify(result), 400++ return jsonify(result)+++@servers_bp.route('/terminal/<session_id>', methods=['DELETE'])+@jwt_required()+@developer_required+def close_terminal_session(session_id):+ """Close a terminal session."""+ user_id = get_jwt_identity()++ result = TerminalService.close_session(+ session_id=session_id,+ user_id=user_id+ )++ if not result.get('success'):+ return jsonify(result), 400++ return jsonify(result)+++@servers_bp.route('/terminal/sessions', methods=['GET'])+@jwt_required()+def list_terminal_sessions():+ """List all terminal sessions for the current user."""+ user_id = get_jwt_identity()++ sessions = TerminalService.get_user_sessions(user_id)+ return jsonify({+ 'sessions': sessions,+ 'count': len(sessions)+ })++# ==================== Installation Scripts ====================def _get_scripts_dir():diff --git a/backend/app/services/terminal_service.py b/backend/app/services/terminal_service.pynew file mode 100644index 00000000..76c4cc9e--- /dev/null+++ b/backend/app/services/terminal_service.py@@ -0,0 +1,216 @@+"""Service for managing remote terminal sessions via agents."""++import uuid+import logging+from typing import Dict, Any, Optional+from datetime import datetime++from app.services.agent_registry import agent_registry++logger = logging.getLogger(__name__)+++class TerminalService:+ """Service for managing remote terminal sessions."""++ # Active terminal sessions: session_id -> {server_id, user_id, created_at}+ _sessions: Dict[str, Dict[str, Any]] = {}++ @classmethod+ def create_session(cls, server_id: str, user_id: int,+ cols: int = 80, rows: int = 24) -> Dict[str, Any]:+ """Create a new terminal session on a remote server.++ Args:+ server_id: Target server ID+ user_id: User ID creating the session+ cols: Terminal width in columns+ rows: Terminal height in rows++ Returns:+ dict: {success, session_id, shell, error}+ """+ if server_id == 'local':+ return {'success': False, 'error': 'Terminal not supported for local server'}++ # Generate unique session ID+ session_id = f"term_{uuid.uuid4().hex[:12]}"++ # Send command to agent to create terminal+ result = agent_registry.send_command(+ server_id=server_id,+ action='terminal:create',+ params={+ 'session_id': session_id,+ 'cols': cols,+ 'rows': rows+ },+ timeout=30.0,+ user_id=user_id+ )++ if not result.get('success'):+ return result++ # Store session info+ cls._sessions[session_id] = {+ 'server_id': server_id,+ 'user_id': user_id,+ 'created_at': datetime.utcnow(),+ 'cols': cols,+ 'rows': rows,+ 'shell': result.get('data', {}).get('shell', 'unknown')+ }++ data = result.get('data', {})+ return {+ 'success': True,+ 'session_id': session_id,+ 'server_id': server_id,+ 'shell': data.get('shell'),+ 'cols': data.get('cols', cols),+ 'rows': data.get('rows', rows)+ }++ @classmethod+ def send_input(cls, session_id: str, data: str, user_id: int) -> Dict[str, Any]:+ """Send input to a terminal session.++ Args:+ session_id: Terminal session ID+ data: Base64-encoded input data+ user_id: User ID (for authorization)++ Returns:+ dict: {success, error}+ """+ session = cls._sessions.get(session_id)+ if not session:+ return {'success': False, 'error': 'Session not found'}++ # Verify user owns this session+ if session['user_id'] != user_id:+ return {'success': False, 'error': 'Unauthorized'}++ result = agent_registry.send_command(+ server_id=session['server_id'],+ action='terminal:input',+ params={+ 'session_id': session_id,+ 'data': data+ },+ timeout=5.0,+ user_id=user_id+ )++ return result++ @classmethod+ def resize_session(cls, session_id: str, cols: int, rows: int,+ user_id: int) -> Dict[str, Any]:+ """Resize a terminal session.++ Args:+ session_id: Terminal session ID+ cols: New width in columns+ rows: New height in rows+ user_id: User ID (for authorization)++ Returns:+ dict: {success, error}+ """+ session = cls._sessions.get(session_id)+ if not session:+ return {'success': False, 'error': 'Session not found'}++ # Verify user owns this session+ if session['user_id'] != user_id:+ return {'success': False, 'error': 'Unauthorized'}++ result = agent_registry.send_command(+ server_id=session['server_id'],+ action='terminal:resize',+ params={+ 'session_id': session_id,+ 'cols': cols,+ 'rows': rows+ },+ timeout=5.0,+ user_id=user_id+ )++ if result.get('success'):+ session['cols'] = cols+ session['rows'] = rows++ return result++ @classmethod+ def close_session(cls, session_id: str, user_id: int) -> Dict[str, Any]:+ """Close a terminal session.++ Args:+ session_id: Terminal session ID+ user_id: User ID (for authorization)++ Returns:+ dict: {success, error}+ """+ session = cls._sessions.get(session_id)+ if not session:+ return {'success': False, 'error': 'Session not found'}++ # Verify user owns this session+ if session['user_id'] != user_id:+ return {'success': False, 'error': 'Unauthorized'}++ result = agent_registry.send_command(+ server_id=session['server_id'],+ action='terminal:close',+ params={+ 'session_id': session_id+ },+ timeout=5.0,+ user_id=user_id+ )++ # Remove from local tracking+ if session_id in cls._sessions:+ del cls._sessions[session_id]++ return result++ @classmethod+ def get_session(cls, session_id: str) -> Optional[Dict[str, Any]]:+ """Get session info.++ Args:+ session_id: Terminal session ID++ Returns:+ Session info dict or None+ """+ return cls._sessions.get(session_id)++ @classmethod+ def get_user_sessions(cls, user_id: int) -> list:+ """Get all sessions for a user.++ Args:+ user_id: User ID++ Returns:+ List of session info dicts+ """+ return [+ {'session_id': sid, **info}+ for sid, info in cls._sessions.items()+ if info['user_id'] == user_id+ ]++ @classmethod+ def cleanup_session(cls, session_id: str):+ """Remove a session from tracking (called when session closes)."""+ if session_id in cls._sessions:+ del cls._sessions[session_id]+ logger.info(f"Terminal session {session_id} cleaned up")diff --git a/frontend/package.json b/frontend/package.jsonindex 2ce77ff1..4bffede5 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -10,6 +10,9 @@"preview": "vite preview"},"dependencies": {+ "@xterm/addon-fit": "^0.10.0",+ "@xterm/addon-web-links": "^0.11.0",+ "@xterm/xterm": "^5.5.0","@xyflow/react": "^12.10.0","lucide-react": "^0.363.0","react": "^18.3.1",diff --git a/frontend/src/components/RemoteTerminal.jsx b/frontend/src/components/RemoteTerminal.jsxnew file mode 100644index 00000000..e219bc89--- /dev/null+++ b/frontend/src/components/RemoteTerminal.jsx@@ -0,0 +1,328 @@+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 api from '../services/api';+import { useSocket } from '../contexts/SocketContext';++/**+ * RemoteTerminal - Interactive terminal component for remote server access+ *+ * Props:+ * serverId: string - The server ID to connect to+ * onClose: function - Called when terminal is closed+ */+export default function RemoteTerminal({ serverId, onClose }) {+ const terminalRef = useRef(null);+ const terminalInstance = useRef(null);+ const fitAddon = useRef(null);+ const [sessionId, setSessionId] = useState(null);+ const [connected, setConnected] = useState(false);+ const [error, setError] = useState(null);+ const [shellName, setShellName] = useState('');+ const { socket, connected: socketConnected } = useSocket();++ // Initialize terminal+ useEffect(() => {+ if (!terminalRef.current) return;++ const term = new Terminal({+ cursorBlink: true,+ fontSize: 14,+ fontFamily: 'Menlo, Monaco, "Courier New", monospace',+ theme: {+ background: '#1e1e1e',+ foreground: '#d4d4d4',+ cursor: '#ffffff',+ cursorAccent: '#1e1e1e',+ selection: 'rgba(255, 255, 255, 0.3)',+ black: '#000000',+ red: '#cd3131',+ green: '#0dbc79',+ yellow: '#e5e510',+ blue: '#2472c8',+ magenta: '#bc3fbc',+ cyan: '#11a8cd',+ white: '#e5e5e5',+ brightBlack: '#666666',+ brightRed: '#f14c4c',+ brightGreen: '#23d18b',+ brightYellow: '#f5f543',+ brightBlue: '#3b8eea',+ brightMagenta: '#d670d6',+ brightCyan: '#29b8db',+ brightWhite: '#ffffff'+ },+ allowProposedApi: true+ });++ const fit = new FitAddon();+ const webLinks = new WebLinksAddon();++ term.loadAddon(fit);+ term.loadAddon(webLinks);+ term.open(terminalRef.current);++ // Fit terminal to container+ setTimeout(() => fit.fit(), 0);++ terminalInstance.current = term;+ fitAddon.current = fit;++ // Handle window resize+ const handleResize = () => {+ if (fitAddon.current) {+ fitAddon.current.fit();+ }+ };+ window.addEventListener('resize', handleResize);++ // Write welcome message+ term.writeln('\x1b[1;36mServerKit Remote Terminal\x1b[0m');+ term.writeln('Connecting to server...');+ term.writeln('');++ return () => {+ window.removeEventListener('resize', handleResize);+ term.dispose();+ };+ }, []);++ // Create terminal session+ useEffect(() => {+ if (!terminalInstance.current || !serverId) return;++ const createSession = async () => {+ try {+ const term = terminalInstance.current;+ const cols = term.cols;+ const rows = term.rows;++ const result = await api.createTerminalSession(serverId, cols, rows);++ if (!result.success) {+ throw new Error(result.error || 'Failed to create terminal session');+ }++ setSessionId(result.session_id);+ setShellName(result.shell || 'shell');+ setConnected(true);++ term.writeln(`\x1b[1;32mConnected to ${result.shell}\x1b[0m`);+ term.writeln('');++ } catch (err) {+ console.error('Failed to create terminal session:', err);+ setError(err.message);+ if (terminalInstance.current) {+ terminalInstance.current.writeln(`\x1b[1;31mError: ${err.message}\x1b[0m`);+ }+ }+ };++ createSession();+ }, [serverId]);++ // Handle terminal input+ useEffect(() => {+ if (!terminalInstance.current || !sessionId || !connected) return;++ const term = terminalInstance.current;++ // Handle user input+ const inputDisposable = term.onData(async (data) => {+ try {+ // Encode data as base64+ const encoded = btoa(data);+ await api.sendTerminalInput(sessionId, encoded);+ } catch (err) {+ console.error('Failed to send terminal input:', err);+ }+ });++ // Handle resize+ const resizeDisposable = term.onResize(async ({ cols, rows }) => {+ try {+ await api.resizeTerminal(sessionId, cols, rows);+ } catch (err) {+ console.error('Failed to resize terminal:', err);+ }+ });++ return () => {+ inputDisposable.dispose();+ resizeDisposable.dispose();+ };+ }, [sessionId, connected]);++ // Listen for terminal output via WebSocket+ useEffect(() => {+ if (!socket || !sessionId || !socketConnected) return;++ const channel = `terminal:${sessionId}`;++ const handleTerminalData = (data) => {+ if (!terminalInstance.current) return;++ if (data.type === 'output' && data.data) {+ // Decode base64 output+ try {+ const decoded = atob(data.data);+ terminalInstance.current.write(decoded);+ } catch (err) {+ console.error('Failed to decode terminal output:', err);+ }+ } else if (data.type === 'closed') {+ terminalInstance.current.writeln('');+ terminalInstance.current.writeln('\x1b[1;33mSession closed\x1b[0m');+ setConnected(false);+ }+ };++ socket.on(channel, handleTerminalData);++ return () => {+ socket.off(channel, handleTerminalData);+ };+ }, [socket, sessionId, socketConnected]);++ // Cleanup session on unmount+ useEffect(() => {+ return () => {+ if (sessionId) {+ api.closeTerminalSession(sessionId).catch(console.error);+ }+ };+ }, [sessionId]);++ // Handle close button+ const handleClose = useCallback(async () => {+ if (sessionId) {+ try {+ await api.closeTerminalSession(sessionId);+ } catch (err) {+ console.error('Error closing session:', err);+ }+ }+ onClose?.();+ }, [sessionId, onClose]);++ // Focus terminal on click+ const handleClick = () => {+ terminalInstance.current?.focus();+ };++ return (+ <div className="remote-terminal-container">+ <div className="terminal-header">+ <div className="terminal-title">+ <span className={`terminal-status ${connected ? 'connected' : 'disconnected'}`} />+ <span>{shellName || 'Terminal'}</span>+ {sessionId && <span className="session-id">({sessionId})</span>}+ </div>+ <div className="terminal-actions">+ <button+ className="terminal-close-btn"+ onClick={handleClose}+ title="Close terminal"+ >+ ×+ </button>+ </div>+ </div>+ <div+ ref={terminalRef}+ className="terminal-content"+ onClick={handleClick}+ />+ {error && (+ <div className="terminal-error">+ {error}+ </div>+ )}+ <style>{`+ .remote-terminal-container {+ display: flex;+ flex-direction: column;+ height: 100%;+ background: #1e1e1e;+ border-radius: 6px;+ overflow: hidden;+ }++ .terminal-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 8px 12px;+ background: #252526;+ border-bottom: 1px solid #3c3c3c;+ }++ .terminal-title {+ display: flex;+ align-items: center;+ gap: 8px;+ color: #cccccc;+ font-size: 13px;+ }++ .terminal-status {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background: #666;+ }++ .terminal-status.connected {+ background: #0dbc79;+ }++ .terminal-status.disconnected {+ background: #cd3131;+ }++ .session-id {+ color: #666;+ font-size: 11px;+ }++ .terminal-actions {+ display: flex;+ gap: 4px;+ }++ .terminal-close-btn {+ background: none;+ border: none;+ color: #cccccc;+ font-size: 18px;+ cursor: pointer;+ padding: 2px 6px;+ border-radius: 4px;+ }++ .terminal-close-btn:hover {+ background: #3c3c3c;+ }++ .terminal-content {+ flex: 1;+ padding: 8px;+ }++ .terminal-content .xterm {+ height: 100%;+ }++ .terminal-error {+ padding: 8px 12px;+ background: #5a1d1d;+ color: #f48771;+ font-size: 13px;+ }+ `}</style>+ </div>+ );+}diff --git a/frontend/src/services/api.js b/frontend/src/services/api.jsindex 9586f429..d3cb8599 100644--- a/frontend/src/services/api.js+++ b/frontend/src/services/api.js@@ -2801,6 +2801,38 @@ class ApiService {return this.request('/servers/metrics/cleanup', { method: 'POST' });}+ // Remote Terminal+ async createTerminalSession(serverId, cols = 80, rows = 24) {+ return this.request(`/servers/${serverId}/terminal`, {+ method: 'POST',+ body: { cols, rows }+ });+ }++ async sendTerminalInput(sessionId, data) {+ return this.request(`/servers/terminal/${sessionId}/input`, {+ method: 'POST',+ body: { data }+ });+ }++ async resizeTerminal(sessionId, cols, rows) {+ return this.request(`/servers/terminal/${sessionId}/resize`, {+ method: 'POST',+ body: { cols, rows }+ });+ }++ async closeTerminalSession(sessionId) {+ return this.request(`/servers/terminal/${sessionId}`, {+ method: 'DELETE'+ });+ }++ async listTerminalSessions() {+ return this.request('/servers/terminal/sessions');+ }+// Agent Downloadsasync getAgentVersion() {return this.request('/servers/agent/version');