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 Packages/Services tabs, JobProgressModal, pyenv runtime mgmt and template library
Juan Denisa534fbf00243
diff --git a/agent/internal/agent/agent.go b/agent/internal/agent/agent.goindex fad17188..60876c73 100644--- a/agent/internal/agent/agent.go+++ b/agent/internal/agent/agent.go@@ -179,6 +179,9 @@ func New(cfg *config.Config, log *logger.Logger) (*Agent, error) {)agent.sudoMode = probeSudoMode(probeCtx)agent.capabilities.Sudo = string(agent.sudoMode)+ agent.capabilities.RuntimeManagers = map[string]string{+ "python": pyenvManagerKind(),+ }agent.capabilities.ProbedAt = time.Now().UnixMilli()probeCancel()log.Info("Sudo probe complete", "mode", agent.sudoMode)@@ -309,6 +312,20 @@ func (a *Agent) registerHandlers() {a.handlers[protocol.ActionAgentUpdate] = a.handleAgentUpdatea.handlers[protocol.ActionAgentRecapabilities] = a.handleAgentRecapabilities+ // Runtime version managers (Phase 5). pyenv on Linux,+ // pyenv-win on Windows. Always registered so pages that probe+ // runtimes:list can tell "manager not installed" from "unknown+ // action" — bootstrap then becomes a one-click action.+ a.handlers[protocol.ActionRuntimesList] = a.handleRuntimesList+ a.handlers[protocol.ActionRuntimesPyenvBootstrap] = a.handleRuntimesPyenvBootstrap+ a.handlers[protocol.ActionRuntimesPythonInstalled] = a.handleRuntimesPythonInstalled+ a.handlers[protocol.ActionRuntimesPythonAvailable] = a.handleRuntimesPythonAvailable+ a.handlers[protocol.ActionRuntimesPythonInstall] = a.handleRuntimesPythonInstall+ a.handlers[protocol.ActionRuntimesPythonUninstall] = a.handleRuntimesPythonUninstall+ a.handlers[protocol.ActionRuntimesPythonSetGlobal] = a.handleRuntimesPythonSetGlobal+ a.handlers[protocol.ActionRuntimesPythonSetLocal] = a.handleRuntimesPythonSetLocal+ a.handlers[protocol.ActionRuntimesPythonCurrent] = a.handleRuntimesPythonCurrent+// GUI SDK — primitives that panel extensions (serverkit-gui, etc.)// compose into desktop-streaming or synthetic-UI features. Always// registered; the SDK reports "none" capability on hosts that can'tdiff --git a/agent/internal/agent/recapabilities.go b/agent/internal/agent/recapabilities.goindex a2e7ff37..479139b2 100644--- a/agent/internal/agent/recapabilities.go+++ b/agent/internal/agent/recapabilities.go@@ -60,6 +60,11 @@ func (a *Agent) handleAgentRecapabilities(ctx context.Context, params json.RawMe// sudoers config since boot.mode := probeSudoMode(probeCtx)fresh.Sudo = string(mode)+ // Re-detect runtime version managers; user may have just bootstrapped+ // pyenv via runtimes:pyenv:bootstrap and is hitting refresh.+ fresh.RuntimeManagers = map[string]string{+ "python": pyenvManagerKind(),+ }fresh.ProbedAt = time.Now().UnixMilli()// Capabilities are additive across re-probes: if the previousdiff --git a/agent/internal/agent/runtime_handlers.go b/agent/internal/agent/runtime_handlers.gonew file mode 100644index 00000000..d6710748--- /dev/null+++ b/agent/internal/agent/runtime_handlers.go@@ -0,0 +1,400 @@+package agent++// Phase 5 — runtime version managers (pyenv on Linux, pyenv-win on+// Windows). The agent already ships a Python version via the+// capability probe; these handlers add install / uninstall / select-+// version flows so users can pick a Python without SSHing in.+//+// Bootstrap and install actions stream on a job channel because they+// take minutes — pyenv compiles CPython from source on Linux and+// downloads + extracts MSI installers on Windows.++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "strings"+ "sync"+ "time"++ "github.com/serverkit/agent/internal/jobs"+)++// pyenvLock serializes pyenv mutations on a single agent. pyenv's+// shim management is not safe under concurrent installs.+var pyenvLock sync.Mutex++// pyenvBin returns the path to the pyenv binary the agent should use,+// or "" if pyenv isn't installed. On Linux we look at $HOME/.pyenv/bin+// and PATH; on Windows we look at %USERPROFILE%\.pyenv\pyenv-win\bin.+func pyenvBin() string {+ if runtime.GOOS == "windows" {+ home, _ := os.UserHomeDir()+ if home == "" {+ home = os.Getenv("USERPROFILE")+ }+ if home != "" {+ candidate := filepath.Join(home, ".pyenv", "pyenv-win", "bin", "pyenv.bat")+ if _, err := os.Stat(candidate); err == nil {+ return candidate+ }+ }+ if p, err := exec.LookPath("pyenv"); err == nil {+ return p+ }+ return ""+ }+ // Linux/macOS+ home, _ := os.UserHomeDir()+ if home != "" {+ candidate := filepath.Join(home, ".pyenv", "bin", "pyenv")+ if _, err := os.Stat(candidate); err == nil {+ return candidate+ }+ }+ if p, err := exec.LookPath("pyenv"); err == nil {+ return p+ }+ return ""+}++// pyenvManagerKind returns "pyenv", "pyenv-win", or "" for absent.+// Surfaced as RuntimeManagers["python"] in the capabilities payload.+func pyenvManagerKind() string {+ if pyenvBin() == "" {+ return ""+ }+ if runtime.GOOS == "windows" {+ return "pyenv-win"+ }+ return "pyenv"+}++// runPyenv runs the pyenv binary with the given args and returns the+// trimmed stdout/stderr. Used by the read-only handlers.+func runPyenv(ctx context.Context, args ...string) (string, error) {+ bin := pyenvBin()+ if bin == "" {+ return "", errors.New("pyenv not installed (run runtimes:pyenv:bootstrap first)")+ }+ cctx, cancel := context.WithTimeout(ctx, 30*time.Second)+ defer cancel()+ out, err := exec.CommandContext(cctx, bin, args...).CombinedOutput()+ return strings.TrimSpace(string(out)), err+}++// ───── runtimes:list ──────────────────────────────────────────────++func (a *Agent) handleRuntimesList(ctx context.Context, params json.RawMessage) (interface{}, error) {+ out := map[string]interface{}{+ "managers": map[string]string{+ "python": pyenvManagerKind(),+ },+ "runtimes": a.capabilities.Runtimes,+ }+ if pyenvManagerKind() != "" {+ current, _ := runPyenv(ctx, "version")+ installed, _ := runPyenv(ctx, "versions", "--bare")+ out["python"] = map[string]interface{}{+ "current": strings.SplitN(current, " ", 2)[0],+ "installed": splitNonEmptyLines(installed),+ }+ }+ return out, nil+}++// ───── runtimes:python:installed ─────────────────────────────────++func (a *Agent) handleRuntimesPythonInstalled(ctx context.Context, params json.RawMessage) (interface{}, error) {+ out, err := runPyenv(ctx, "versions", "--bare")+ if err != nil {+ return nil, err+ }+ return map[string]interface{}{+ "versions": splitNonEmptyLines(out),+ "manager": pyenvManagerKind(),+ }, nil+}++// ───── runtimes:python:available ─────────────────────────────────++func (a *Agent) handleRuntimesPythonAvailable(ctx context.Context, params json.RawMessage) (interface{}, error) {+ // `pyenv install --list` on Linux and `pyenv install -l` on+ // pyenv-win both work, but pyenv-win prints them with leading+ // whitespace. Normalize.+ out, err := runPyenv(ctx, "install", "--list")+ if err != nil && pyenvManagerKind() == "pyenv-win" {+ out, err = runPyenv(ctx, "install", "-l")+ }+ if err != nil {+ return nil, err+ }+ versions := []string{}+ for _, line := range strings.Split(out, "\n") {+ line = strings.TrimSpace(line)+ if line == "" || strings.HasPrefix(line, "Available") || strings.HasPrefix(line, ":") {+ continue+ }+ versions = append(versions, line)+ }+ return map[string]interface{}{+ "versions": versions,+ "manager": pyenvManagerKind(),+ }, nil+}++// ───── runtimes:python:current ───────────────────────────────────++func (a *Agent) handleRuntimesPythonCurrent(ctx context.Context, params json.RawMessage) (interface{}, error) {+ out, err := runPyenv(ctx, "version")+ if err != nil {+ return nil, err+ }+ parts := strings.SplitN(out, " ", 2)+ return map[string]interface{}{+ "version": parts[0],+ "raw": out,+ }, nil+}++// ───── runtimes:python:set_global ────────────────────────────────++func (a *Agent) handleRuntimesPythonSetGlobal(ctx context.Context, params json.RawMessage) (interface{}, error) {+ var p struct {+ Version string `json:"version"`+ }+ if err := json.Unmarshal(params, &p); err != nil {+ return nil, err+ }+ if err := validateVersion(p.Version); err != nil {+ return nil, err+ }+ out, err := runPyenv(ctx, "global", p.Version)+ if err != nil {+ return nil, fmt.Errorf("pyenv global %s: %w (%s)", p.Version, err, out)+ }+ return map[string]interface{}{"global": p.Version}, nil+}++// ───── runtimes:python:set_local ─────────────────────────────────++func (a *Agent) handleRuntimesPythonSetLocal(ctx context.Context, params json.RawMessage) (interface{}, error) {+ var p struct {+ Version string `json:"version"`+ Dir string `json:"dir"`+ }+ if err := json.Unmarshal(params, &p); err != nil {+ return nil, err+ }+ if err := validateVersion(p.Version); err != nil {+ return nil, err+ }+ abs, err := filepath.Abs(p.Dir)+ if err != nil {+ return nil, fmt.Errorf("dir: %w", err)+ }+ if !a.contextPathAllowed(abs) {+ return nil, fmt.Errorf("dir %q is not under any allowed root", abs)+ }+ bin := pyenvBin()+ if bin == "" {+ return nil, errors.New("pyenv not installed")+ }+ cctx, cancel := context.WithTimeout(ctx, 30*time.Second)+ defer cancel()+ cmd := exec.CommandContext(cctx, bin, "local", p.Version)+ cmd.Dir = abs+ out, err := cmd.CombinedOutput()+ if err != nil {+ return nil, fmt.Errorf("pyenv local %s in %s: %w (%s)", p.Version, abs, err, string(out))+ }+ return map[string]interface{}{"local": p.Version, "dir": abs}, nil+}++// ───── runtimes:python:uninstall ─────────────────────────────────++func (a *Agent) handleRuntimesPythonUninstall(ctx context.Context, params json.RawMessage) (interface{}, error) {+ var p struct {+ Version string `json:"version"`+ }+ if err := json.Unmarshal(params, &p); err != nil {+ return nil, err+ }+ if err := validateVersion(p.Version); err != nil {+ return nil, err+ }+ pyenvLock.Lock()+ defer pyenvLock.Unlock()+ out, err := runPyenv(ctx, "uninstall", "-f", p.Version)+ if err != nil {+ return nil, fmt.Errorf("pyenv uninstall %s: %w (%s)", p.Version, err, out)+ }+ return map[string]interface{}{"uninstalled": p.Version}, nil+}++// ───── runtimes:python:install (streaming) ───────────────────────++func (a *Agent) handleRuntimesPythonInstall(ctx context.Context, params json.RawMessage) (interface{}, error) {+ var p struct {+ Version string `json:"version"`+ }+ if err := json.Unmarshal(params, &p); err != nil {+ return nil, err+ }+ if err := validateVersion(p.Version); err != nil {+ return nil, err+ }+ if pyenvBin() == "" {+ return nil, errors.New("pyenv not installed (run runtimes:pyenv:bootstrap first)")+ }+ job := a.jobs.New(500)+ go a.runPyenvInstallJob(job, p.Version)+ return map[string]interface{}{+ "job_id": job.ID,+ "channel": job.Channel,+ "version": p.Version,+ }, nil+}++func (a *Agent) runPyenvInstallJob(job *jobs.Job, version string) {+ pyenvLock.Lock()+ defer pyenvLock.Unlock()++ exit := 0+ emitDone := func(errStr string) {+ _ = job.Push(a.ws, jobs.Event{+ Phase: jobs.PhaseDone,+ ExitCode: &exit,+ Error: errStr,+ Extra: map[string]interface{}{"version": version, "manager": pyenvManagerKind()},+ })+ }++ cctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)+ defer cancel()+ cmd := exec.CommandContext(cctx, pyenvBin(), "install", "-s", version)+ _ = job.Push(a.ws, jobs.Event{Phase: jobs.PhaseStart, Message: fmt.Sprintf("pyenv install %s", version)})+ if err := streamCmdOutput(cmd, job, a.ws); err != nil {+ exit = -1+ emitDone(err.Error())+ return+ }+ if cerr := cmd.Wait(); cerr != nil {+ exit = exitCodeOfCmd(cerr)+ if exit == 0 {+ exit = -1+ }+ emitDone(cerr.Error())+ return+ }+ emitDone("")+}++// ───── runtimes:pyenv:bootstrap (streaming) ──────────────────────+//+// Linux: clones pyenv to ~/.pyenv. Does NOT touch ~/.bashrc — most+// agents run as a non-login systemd unit and the user already has+// shell init from their interactive sessions; we don't want to+// duplicate it. Clone path matches the upstream installer.+//+// Windows: clones pyenv-win to %USERPROFILE%\.pyenv\pyenv-win.++func (a *Agent) handleRuntimesPyenvBootstrap(ctx context.Context, params json.RawMessage) (interface{}, error) {+ if pyenvBin() != "" {+ return map[string]interface{}{+ "status": "already_installed",+ "manager": pyenvManagerKind(),+ }, nil+ }+ if _, err := exec.LookPath("git"); err != nil {+ return nil, errors.New("git is required to install pyenv (please install git first)")+ }+ job := a.jobs.New(200)+ go a.runPyenvBootstrapJob(job)+ return map[string]interface{}{+ "job_id": job.ID,+ "channel": job.Channel,+ }, nil+}++func (a *Agent) runPyenvBootstrapJob(job *jobs.Job) {+ exit := 0+ emitDone := func(errStr string) {+ _ = job.Push(a.ws, jobs.Event{+ Phase: jobs.PhaseDone,+ ExitCode: &exit,+ Error: errStr,+ Extra: map[string]interface{}{"manager": pyenvManagerKind()},+ })+ }++ home, _ := os.UserHomeDir()+ if home == "" && runtime.GOOS == "windows" {+ home = os.Getenv("USERPROFILE")+ }+ if home == "" {+ exit = -1+ emitDone("could not determine user home directory")+ return+ }++ var repo, dest string+ if runtime.GOOS == "windows" {+ repo = "https://github.com/pyenv-win/pyenv-win.git"+ dest = filepath.Join(home, ".pyenv")+ } else {+ repo = "https://github.com/pyenv/pyenv.git"+ dest = filepath.Join(home, ".pyenv")+ }++ _ = job.Push(a.ws, jobs.Event{Phase: jobs.PhaseStart, Message: fmt.Sprintf("git clone %s %s", repo, dest)})++ cctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)+ defer cancel()+ cmd := exec.CommandContext(cctx, "git", "clone", "--depth", "1", repo, dest)+ if err := streamCmdOutput(cmd, job, a.ws); err != nil {+ exit = -1+ emitDone(err.Error())+ return+ }+ if cerr := cmd.Wait(); cerr != nil {+ exit = exitCodeOfCmd(cerr)+ if exit == 0 {+ exit = -1+ }+ emitDone(cerr.Error())+ return+ }+ emitDone("")+}++// validateVersion rejects shell metacharacters in the user-supplied+// pyenv version reference. pyenv tags are dotted-version strings ("3.12.0",+// "3.13.0a4") so the allow-list is conservative.+func validateVersion(v string) error {+ v = strings.TrimSpace(v)+ if v == "" {+ return errors.New("version is required")+ }+ for _, r := range v {+ if r >= 'a' && r <= 'z' {+ continue+ }+ if r >= 'A' && r <= 'Z' {+ continue+ }+ if r >= '0' && r <= '9' {+ continue+ }+ if r == '.' || r == '-' || r == '_' || r == '+' {+ continue+ }+ return fmt.Errorf("invalid version: %q", v)+ }+ return nil+}diff --git a/backend/app/api/servers.py b/backend/app/api/servers.pyindex d1c2db9f..9880850c 100644--- a/backend/app/api/servers.py+++ b/backend/app/api/servers.py@@ -2476,6 +2476,109 @@ def remote_services_control(server_id, unit, action):return _agent_result(result)+# ==================== Remote Runtimes (pyenv) ====================+#+# Manages Python versions via pyenv (Linux) and pyenv-win (Windows).+# Bootstrap and install return {job_id, channel} for streaming+# progress; everything else is a synchronous round-trip.++from app.services.remote_runtimes_service import RemoteRuntimesService+++@servers_bp.route('/<server_id>/runtimes', methods=['GET'])+@jwt_required()+def remote_runtimes_list(server_id):+ user_id = get_jwt_identity()+ result = RemoteRuntimesService.list_state(server_id, user_id=user_id)+ return _agent_result(result)+++@servers_bp.route('/<server_id>/runtimes/pyenv/bootstrap', methods=['POST'])+@jwt_required()+@developer_required+def remote_runtimes_pyenv_bootstrap(server_id):+ user_id = get_jwt_identity()+ result = RemoteRuntimesService.pyenv_bootstrap(server_id, user_id=user_id)+ return _agent_result(result)+++@servers_bp.route('/<server_id>/runtimes/python', methods=['GET'])+@jwt_required()+def remote_runtimes_python_installed(server_id):+ user_id = get_jwt_identity()+ result = RemoteRuntimesService.python_installed(server_id, user_id=user_id)+ return _agent_result(result)+++@servers_bp.route('/<server_id>/runtimes/python/available', methods=['GET'])+@jwt_required()+def remote_runtimes_python_available(server_id):+ user_id = get_jwt_identity()+ result = RemoteRuntimesService.python_available(server_id, user_id=user_id)+ return _agent_result(result)+++@servers_bp.route('/<server_id>/runtimes/python/current', methods=['GET'])+@jwt_required()+def remote_runtimes_python_current(server_id):+ user_id = get_jwt_identity()+ result = RemoteRuntimesService.python_current(server_id, user_id=user_id)+ return _agent_result(result)+++@servers_bp.route('/<server_id>/runtimes/python/install', methods=['POST'])+@jwt_required()+@developer_required+def remote_runtimes_python_install(server_id):+ user_id = get_jwt_identity()+ data = request.get_json(silent=True) or {}+ version = (data.get('version') or '').strip()+ if not version:+ return jsonify({'error': 'version is required'}), 400+ result = RemoteRuntimesService.python_install(server_id, version, user_id=user_id)+ return _agent_result(result)+++@servers_bp.route('/<server_id>/runtimes/python/uninstall', methods=['POST'])+@jwt_required()+@developer_required+def remote_runtimes_python_uninstall(server_id):+ user_id = get_jwt_identity()+ data = request.get_json(silent=True) or {}+ version = (data.get('version') or '').strip()+ if not version:+ return jsonify({'error': 'version is required'}), 400+ result = RemoteRuntimesService.python_uninstall(server_id, version, user_id=user_id)+ return _agent_result(result)+++@servers_bp.route('/<server_id>/runtimes/python/global', methods=['POST'])+@jwt_required()+@developer_required+def remote_runtimes_python_set_global(server_id):+ user_id = get_jwt_identity()+ data = request.get_json(silent=True) or {}+ version = (data.get('version') or '').strip()+ if not version:+ return jsonify({'error': 'version is required'}), 400+ result = RemoteRuntimesService.python_set_global(server_id, version, user_id=user_id)+ return _agent_result(result)+++@servers_bp.route('/<server_id>/runtimes/python/local', methods=['POST'])+@jwt_required()+@developer_required+def remote_runtimes_python_set_local(server_id):+ user_id = get_jwt_identity()+ data = request.get_json(silent=True) or {}+ version = (data.get('version') or '').strip()+ dir_path = (data.get('dir') or '').strip()+ if not version or not dir_path:+ return jsonify({'error': 'version and dir are required'}), 400+ result = RemoteRuntimesService.python_set_local(server_id, version, dir_path, user_id=user_id)+ return _agent_result(result)++# ==================== Remote File Operations ====================## Endpoints under /servers/<id>/files/ proxy to the agent's file:*diff --git a/backend/app/services/remote_runtimes_service.py b/backend/app/services/remote_runtimes_service.pynew file mode 100644index 00000000..a283c159--- /dev/null+++ b/backend/app/services/remote_runtimes_service.py@@ -0,0 +1,92 @@+"""+Remote Runtimes Service.++Wraps the agent's runtimes:* handlers (pyenv on Linux, pyenv-win on+Windows) so the panel can install / uninstall / select Python versions+on a remote host.++Long-running operations (bootstrap, install) return {job_id, channel}+just like packages:install_async — the frontend subscribes to the+matching Socket.IO room for live build output.+"""++from typing import Any, Dict, Optional++from app.services.agent_registry import agent_registry+++class RemoteRuntimesService:+ """Thin dispatcher to runtimes:* on a remote agent."""++ @staticmethod+ def _send(server_id: str, action: str, params: Optional[Dict[str, Any]] = None,+ user_id: Optional[int] = None, timeout: float = 30.0) -> Dict[str, Any]:+ return agent_registry.send_command(+ server_id=server_id,+ action=action,+ params=params or {},+ user_id=user_id,+ timeout=timeout,+ )++ @staticmethod+ def list_state(server_id: str, user_id: Optional[int] = None) -> Dict[str, Any]:+ return RemoteRuntimesService._send(server_id, 'runtimes:list', user_id=user_id)++ @staticmethod+ def python_installed(server_id: str, user_id: Optional[int] = None) -> Dict[str, Any]:+ return RemoteRuntimesService._send(+ server_id, 'runtimes:python:installed', user_id=user_id, timeout=15.0,+ )++ @staticmethod+ def python_available(server_id: str, user_id: Optional[int] = None) -> Dict[str, Any]:+ return RemoteRuntimesService._send(+ server_id, 'runtimes:python:available', user_id=user_id, timeout=30.0,+ )++ @staticmethod+ def python_current(server_id: str, user_id: Optional[int] = None) -> Dict[str, Any]:+ return RemoteRuntimesService._send(+ server_id, 'runtimes:python:current', user_id=user_id, timeout=15.0,+ )++ @staticmethod+ def python_install(server_id: str, version: str, user_id: Optional[int] = None) -> Dict[str, Any]:+ return RemoteRuntimesService._send(+ server_id, 'runtimes:python:install',+ params={'version': version},+ user_id=user_id, timeout=10.0, # async — returns job_id quickly+ )++ @staticmethod+ def python_uninstall(server_id: str, version: str, user_id: Optional[int] = None) -> Dict[str, Any]:+ return RemoteRuntimesService._send(+ server_id, 'runtimes:python:uninstall',+ params={'version': version},+ user_id=user_id, timeout=120.0,+ )++ @staticmethod+ def python_set_global(server_id: str, version: str, user_id: Optional[int] = None) -> Dict[str, Any]:+ return RemoteRuntimesService._send(+ server_id, 'runtimes:python:set_global',+ params={'version': version},+ user_id=user_id, timeout=15.0,+ )++ @staticmethod+ def python_set_local(server_id: str, version: str, dir_path: str,+ user_id: Optional[int] = None) -> Dict[str, Any]:+ return RemoteRuntimesService._send(+ server_id, 'runtimes:python:set_local',+ params={'version': version, 'dir': dir_path},+ user_id=user_id, timeout=15.0,+ )++ @staticmethod+ def pyenv_bootstrap(server_id: str, user_id: Optional[int] = None) -> Dict[str, Any]:+ return RemoteRuntimesService._send(+ server_id, 'runtimes:pyenv:bootstrap',+ user_id=user_id, timeout=10.0, # async+ )diff --git a/backend/app/services/server_template_service.py b/backend/app/services/server_template_service.pyindex 6d74b9f9..b034ae9f 100644--- a/backend/app/services/server_template_service.py+++ b/backend/app/services/server_template_service.py@@ -59,6 +59,128 @@ class ServerTemplateService:{'port': 22, 'protocol': 'tcp', 'action': 'allow'},],},++ # ───── one-click stacks (Phase 4) ─────────────────────────────+ # Curated entries that the agent's packages:* + systemd:* surface+ # can apply unattended. Package names target Debian/Ubuntu where+ # they differ across distros — RHEL/Alpine users will need to+ # tweak names. The list here drives the workflow engine's+ # capability_gate + agent_command nodes; the agent makes the+ # apt/dnf/apk distinction at install time.+ 'lemp': {+ 'name': 'LEMP Stack',+ 'description': 'Nginx + MariaDB + PHP-FPM (Linux/Nginx/MariaDB/PHP)',+ 'category': 'web',+ 'packages': ['nginx', 'mariadb-server', 'php-fpm', 'php-mysql'],+ 'services': [+ {'name': 'nginx', 'enabled': True, 'running': True},+ {'name': 'mariadb', 'enabled': True, 'running': True},+ {'name': 'php-fpm', 'enabled': True, 'running': True},+ ],+ 'firewall_rules': [+ {'port': 80, 'protocol': 'tcp', 'action': 'allow'},+ {'port': 443, 'protocol': 'tcp', 'action': 'allow'},+ {'port': 22, 'protocol': 'tcp', 'action': 'allow'},+ ],+ },+ 'lamp': {+ 'name': 'LAMP Stack',+ 'description': 'Apache + MariaDB + PHP (mod_php)',+ 'category': 'web',+ 'packages': ['apache2', 'mariadb-server', 'php', 'libapache2-mod-php', 'php-mysql'],+ 'services': [+ {'name': 'apache2', 'enabled': True, 'running': True},+ {'name': 'mariadb', 'enabled': True, 'running': True},+ ],+ 'firewall_rules': [+ {'port': 80, 'protocol': 'tcp', 'action': 'allow'},+ {'port': 443, 'protocol': 'tcp', 'action': 'allow'},+ {'port': 22, 'protocol': 'tcp', 'action': 'allow'},+ ],+ },+ 'docker-host': {+ 'name': 'Docker Host',+ 'description': 'Docker Engine + Compose plugin',+ 'category': 'container',+ # docker.io is the Debian/Ubuntu package; users on RHEL/Fedora+ # should swap to docker-ce via the Docker repo. The agent+ # surfaces a clear "no candidate" error on those distros so+ # the failure mode is explicit, not silent.+ 'packages': ['docker.io', 'docker-compose-plugin'],+ 'services': [+ {'name': 'docker', 'enabled': True, 'running': True},+ ],+ 'firewall_rules': [+ {'port': 22, 'protocol': 'tcp', 'action': 'allow'},+ ],+ },+ 'node-host': {+ 'name': 'Node.js Host',+ 'description': 'Node.js + npm runtime (no service — start your apps via systemd or pm2)',+ 'category': 'runtime',+ 'packages': ['nodejs', 'npm'],+ 'services': [],+ 'firewall_rules': [+ {'port': 22, 'protocol': 'tcp', 'action': 'allow'},+ ],+ },+ 'python-host': {+ 'name': 'Python Host',+ 'description': 'Python 3 + venv + pip + Gunicorn',+ 'category': 'runtime',+ 'packages': ['python3', 'python3-venv', 'python3-pip', 'gunicorn'],+ 'services': [],+ 'firewall_rules': [+ {'port': 22, 'protocol': 'tcp', 'action': 'allow'},+ ],+ },+ 'redis': {+ 'name': 'Redis',+ 'description': 'Redis in-memory data store',+ 'category': 'cache',+ 'packages': ['redis-server'],+ 'services': [+ {'name': 'redis-server', 'enabled': True, 'running': True},+ ],+ 'firewall_rules': [+ {'port': 6379, 'protocol': 'tcp', 'action': 'allow'},+ {'port': 22, 'protocol': 'tcp', 'action': 'allow'},+ ],+ },+ 'postgres': {+ 'name': 'PostgreSQL',+ 'description': 'PostgreSQL relational database',+ 'category': 'database',+ 'packages': ['postgresql'],+ 'services': [+ {'name': 'postgresql', 'enabled': True, 'running': True},+ ],+ 'firewall_rules': [+ {'port': 5432, 'protocol': 'tcp', 'action': 'allow'},+ {'port': 22, 'protocol': 'tcp', 'action': 'allow'},+ ],+ },+ 'cloudflared': {+ 'name': 'Cloudflare Tunnel',+ 'description': 'cloudflared agent for outbound-only Cloudflare named tunnels',+ 'category': 'network',+ 'packages': ['cloudflared'],+ 'services': [+ {'name': 'cloudflared', 'enabled': True, 'running': False},+ ],+ 'firewall_rules': [+ {'port': 22, 'protocol': 'tcp', 'action': 'allow'},+ ],+ },+ 'fail2ban': {+ 'name': 'Fail2ban',+ 'description': 'Brute-force protection / log-driven IP banning',+ 'category': 'security',+ 'packages': ['fail2ban'],+ 'services': [+ {'name': 'fail2ban', 'enabled': True, 'running': True},+ ],+ },}@staticmethoddiff --git a/frontend/src/components/JobProgressModal.jsx b/frontend/src/components/JobProgressModal.jsxnew file mode 100644index 00000000..d21fb69e--- /dev/null+++ b/frontend/src/components/JobProgressModal.jsx@@ -0,0 +1,120 @@+import React, { useEffect, useRef, useState } from 'react';+import Modal from './Modal';+import { Button } from '@/components/ui/button';+import socketService from '../services/socket';++// Subscribes to a remote agent's job:<id> stream channel and renders+// the live log output. Used by PackagesTab and ServicesTab for+// long-running install / upgrade / journal-follow operations.+//+// The agent emits {phase, lines[], message, percent, exit_code, error}+// events on the channel. The panel re-broadcasts those over Socket.IO+// as `server_stream` events into room `server_<serverId>_<channel>`.+// We join the room on mount, listen for matching server_stream events,+// and surface a "done" phase as success/error in the footer.+export default function JobProgressModal({+ open,+ serverId,+ channel,+ title = 'Working…',+ onClose,+ onComplete,+}) {+ const [lines, setLines] = useState([]);+ const [done, setDone] = useState(null); // null | { exitCode, error, extra }+ const logEndRef = useRef(null);++ useEffect(() => {+ if (!open || !channel || !serverId) return;+ const room = `server_${serverId}_${channel}`;+ const socket = socketService.socket;+ if (!socket) {+ // Connect lazily — happens once per panel session normally.+ socketService.connect();+ }++ const activeSocket = socketService.socket;+ if (!activeSocket) return;++ const onStream = (msg) => {+ if (msg?.channel !== channel) return;+ const ev = msg.data || {};+ if (Array.isArray(ev.lines) && ev.lines.length) {+ setLines((prev) => [...prev, ...ev.lines]);+ } else if (ev.message) {+ setLines((prev) => [...prev, ev.message]);+ }+ if (ev.phase === 'done') {+ const exitCode = typeof ev.exit_code === 'number' ? ev.exit_code : null;+ setDone({+ exitCode,+ error: ev.error || '',+ extra: ev.extra || null,+ });+ if (onComplete) onComplete(ev);+ }+ };++ activeSocket.emit('join_room', { room });+ activeSocket.on('server_stream', onStream);++ return () => {+ activeSocket.emit('leave_room', { room });+ activeSocket.off('server_stream', onStream);+ };+ }, [open, channel, serverId, onComplete]);++ // Reset state on close so the next job starts fresh.+ useEffect(() => {+ if (!open) {+ setLines([]);+ setDone(null);+ }+ }, [open]);++ // Auto-scroll to the bottom as new lines arrive.+ useEffect(() => {+ logEndRef.current?.scrollIntoView({ behavior: 'smooth' });+ }, [lines.length]);++ const success = done && done.exitCode === 0 && !done.error;+ const failure = done && !success;++ return (+ <Modal+ open={open}+ onClose={onClose}+ title={title}+ size="xl"+ footer={+ <div className="flex items-center gap-3 w-full">+ <div className="flex-1">+ {!done && <span className="text-muted-foreground text-sm">Streaming progress…</span>}+ {success && <span className="text-success text-sm">Completed successfully</span>}+ {failure && (+ <span className="text-destructive text-sm">+ Failed{done.exitCode !== null ? ` (exit ${done.exitCode})` : ''}+ {done.error ? `: ${done.error}` : ''}+ </span>+ )}+ </div>+ <Button variant="outline" onClick={onClose} disabled={!done}>+ {done ? 'Close' : 'Working…'}+ </Button>+ </div>+ }+ >+ <div className="job-progress-modal">+ {lines.length === 0 && !done && (+ <p className="text-muted-foreground text-sm">Waiting for the agent to begin…</p>+ )}+ {lines.length > 0 && (+ <pre className="job-progress-modal__log">+ {lines.join('\n')}+ <div ref={logEndRef} />+ </pre>+ )}+ </div>+ </Modal>+ );+}diff --git a/frontend/src/components/serverdetail/PackagesTab.jsx b/frontend/src/components/serverdetail/PackagesTab.jsxnew file mode 100644index 00000000..3111407c--- /dev/null+++ b/frontend/src/components/serverdetail/PackagesTab.jsx@@ -0,0 +1,275 @@+import React, { useCallback, useEffect, useState } from 'react';+import api from '../../services/api';+import { useToast } from '../../contexts/ToastContext';+import { useConfirm } from '../../hooks/useConfirm';+import { ConfirmDialog } from '../ConfirmDialog';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Badge } from '@/components/ui/badge';+import JobProgressModal from '../JobProgressModal';++// Quick-install presets — packages most users want first when setting+// up a new server. The agent's manager-detect handles distro mapping;+// for the few packages whose names actually differ across distros+// (docker.io vs docker-ce, php-fpm versioning) we keep the most common+// Debian/Ubuntu name and let the user override via the search field.+const QUICK_PRESETS = [+ { name: 'nginx', label: 'nginx' },+ { name: 'redis-server', label: 'redis' },+ { name: 'mariadb-server', label: 'mariadb' },+ { name: 'postgresql', label: 'postgresql' },+ { name: 'docker.io', label: 'docker' },+ { name: 'fail2ban', label: 'fail2ban' },+ { name: 'certbot', label: 'certbot' },+ { name: 'htop', label: 'htop' },+];++const PackagesTab = ({ serverId, serverStatus }) => {+ const toast = useToast();+ const { confirm, confirmState, handleConfirm, handleCancel } = useConfirm();++ const [installedRaw, setInstalledRaw] = useState('');+ const [manager, setManager] = useState('');+ const [loadingInstalled, setLoadingInstalled] = useState(true);++ const [searchQuery, setSearchQuery] = useState('');+ const [searchResults, setSearchResults] = useState(null);+ const [searching, setSearching] = useState(false);++ const [job, setJob] = useState(null); // { channel, title }++ const loadInstalled = useCallback(async () => {+ try {+ const data = await api.getRemotePackages(serverId);+ setInstalledRaw(data?.output || '');+ setManager(data?.manager || '');+ } catch (err) {+ toast.error(err.message || 'Failed to load packages');+ } finally {+ setLoadingInstalled(false);+ }+ }, [serverId, toast]);++ useEffect(() => {+ if (serverStatus !== 'online') {+ setLoadingInstalled(false);+ return;+ }+ loadInstalled();+ }, [serverStatus, loadInstalled]);++ async function handleSearch(e) {+ e?.preventDefault?.();+ const q = searchQuery.trim();+ if (!q) {+ setSearchResults(null);+ return;+ }+ setSearching(true);+ try {+ const data = await api.searchRemotePackages(serverId, q, 100);+ setSearchResults(data?.results || []);+ } catch (err) {+ toast.error(err.message || 'Search failed');+ setSearchResults([]);+ } finally {+ setSearching(false);+ }+ }++ async function handleInstall(name) {+ try {+ const result = await api.installRemotePackages(serverId, [name]);+ const channel = result?.channel || `job:${result?.job_id}`;+ setJob({ channel, title: `Installing ${name}` });+ } catch (err) {+ toast.error(err.message || `Failed to start install`);+ }+ }++ async function handleRemove(name) {+ const ok = await confirm({+ title: `Remove ${name}`,+ message: `Uninstall ${name} from this server?`,+ variant: 'danger',+ });+ if (!ok) return;+ try {+ await api.removeRemotePackage(serverId, name);+ toast.success(`${name} removed`);+ } catch (err) {+ toast.error(err.message || 'Remove failed');+ }+ }++ async function handleUpdateCache() {+ try {+ await api.updateRemotePackageCache(serverId);+ toast.success(`Package cache updated (${manager || 'manager'})`);+ } catch (err) {+ toast.error(err.message || 'Update failed');+ }+ }++ async function handleUpgradeAll() {+ const ok = await confirm({+ title: 'Upgrade all packages',+ message: 'Run a full system upgrade? This may take several minutes.',+ });+ if (!ok) return;+ try {+ const result = await api.upgradeRemotePackages(serverId, { all: true });+ const channel = result?.channel || `job:${result?.job_id}`;+ setJob({ channel, title: 'Upgrading all packages' });+ } catch (err) {+ toast.error(err.message || 'Upgrade failed to start');+ }+ }++ function handleJobComplete() {+ // Refresh the installed-list once an install/upgrade settles so+ // the user sees the new state without a manual reload.+ loadInstalled();+ }++ if (serverStatus !== 'online') {+ return (+ <div className="empty-state">+ <p>Server is offline. Reconnect to manage packages.</p>+ </div>+ );+ }++ return (+ <div className="server-packages">+ <div className="server-packages__toolbar">+ <form onSubmit={handleSearch} className="server-packages__search">+ <Input+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ placeholder="Search packages…"+ />+ <Button type="submit" variant="outline" disabled={searching}>+ {searching ? 'Searching…' : 'Search'}+ </Button>+ </form>+ <div className="server-packages__actions">+ <Button variant="outline" onClick={handleUpdateCache}>Update cache</Button>+ <Button variant="outline" onClick={handleUpgradeAll}>Upgrade all</Button>+ </div>+ </div>++ <section className="server-packages__presets">+ <h3>Quick install</h3>+ <div className="server-packages__chips">+ {QUICK_PRESETS.map((p) => (+ <button+ key={p.name}+ type="button"+ className="server-packages__chip"+ onClick={() => handleInstall(p.name)}+ >+ {p.label}+ </button>+ ))}+ </div>+ </section>++ {searchResults !== null && (+ <section className="server-packages__results">+ <h3>Search results {manager && <Badge>{manager}</Badge>}</h3>+ {searchResults.length === 0 ? (+ <p className="text-muted-foreground">No matches.</p>+ ) : (+ <ul className="server-packages__list">+ {searchResults.map((line, i) => {+ // First whitespace-separated token is the package name on+ // every supported manager output format. Anything after is+ // the description and gets truncated visually by CSS.+ const name = line.split(/\s+/)[0]?.replace(/[-/].*/, '') || line;+ return (+ <li key={`${name}-${i}`} className="server-packages__list-item">+ <span className="server-packages__list-name">{line}</span>+ <Button size="sm" variant="outline" onClick={() => handleInstall(name)}>+ Install+ </Button>+ </li>+ );+ })}+ </ul>+ )}+ </section>+ )}++ <section className="server-packages__installed">+ <h3>Installed packages {manager && <Badge>{manager}</Badge>}</h3>+ {loadingInstalled ? (+ <p className="text-muted-foreground">Loading…</p>+ ) : (+ <pre className="server-packages__raw">+ {installedRaw || 'No packages reported.'}+ </pre>+ )}+ <p className="server-packages__hint text-muted-foreground">+ Output is the raw package-manager listing. Use search to find a specific+ package, then click Install.+ </p>+ </section>++ <JobProgressModal+ open={!!job}+ serverId={serverId}+ channel={job?.channel}+ title={job?.title}+ onClose={() => setJob(null)}+ onComplete={handleJobComplete}+ />++ <ConfirmDialog+ isOpen={confirmState.isOpen}+ title={confirmState.title}+ message={confirmState.message}+ variant={confirmState.variant}+ onConfirm={handleConfirm}+ onCancel={handleCancel}+ />++ <div className="server-packages__remove-tip text-muted-foreground">+ Tip: to remove a specific package, search for it and use the row's+ <em> Install </em>+ button to reinstall, or open a terminal session for advanced operations.+ Direct remove from this UI:+ <RemoveByName onRemove={handleRemove} />+ </div>+ </div>+ );+};++// Small inline form for ad-hoc package removal. Kept separate so the+// main render stays readable.+function RemoveByName({ onRemove }) {+ const [name, setName] = useState('');+ return (+ <form+ onSubmit={(e) => {+ e.preventDefault();+ if (!name.trim()) return;+ onRemove(name.trim());+ setName('');+ }}+ className="server-packages__remove-form"+ >+ <Input+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder="package name"+ size="sm"+ />+ <Button type="submit" variant="outline" size="sm" disabled={!name.trim()}>+ Remove+ </Button>+ </form>+ );+}++export default PackagesTab;diff --git a/frontend/src/components/serverdetail/ServicesTab.jsx b/frontend/src/components/serverdetail/ServicesTab.jsxnew file mode 100644index 00000000..77957bc6--- /dev/null+++ b/frontend/src/components/serverdetail/ServicesTab.jsx@@ -0,0 +1,201 @@+import React, { useCallback, useEffect, useMemo, useState } from 'react';+import api from '../../services/api';+import { useToast } from '../../contexts/ToastContext';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Badge } from '@/components/ui/badge';+import Modal from '../Modal';++const STATE_FILTERS = [+ { value: '', label: 'All' },+ { value: 'active', label: 'Active' },+ { value: 'failed', label: 'Failed' },+ { value: 'inactive', label: 'Inactive' },+];++const ServicesTab = ({ serverId, serverStatus }) => {+ const toast = useToast();+ const [units, setUnits] = useState([]);+ const [loading, setLoading] = useState(true);+ const [stateFilter, setStateFilter] = useState('');+ const [search, setSearch] = useState('');+ const [busyUnit, setBusyUnit] = useState(null);+ const [logsFor, setLogsFor] = useState(null); // { unit, entries, raw }++ const loadUnits = useCallback(async () => {+ setLoading(true);+ try {+ const data = await api.getRemoteServices(serverId, { state: stateFilter || null });+ setUnits(data?.units || []);+ } catch (err) {+ toast.error(err.message || 'Failed to load services');+ } finally {+ setLoading(false);+ }+ }, [serverId, stateFilter, toast]);++ useEffect(() => {+ if (serverStatus !== 'online') {+ setLoading(false);+ return;+ }+ loadUnits();+ }, [serverStatus, loadUnits]);++ const filtered = useMemo(() => {+ if (!search.trim()) return units;+ const needle = search.trim().toLowerCase();+ return units.filter((u) => u.unit?.toLowerCase().includes(needle));+ }, [units, search]);++ async function control(unit, action) {+ setBusyUnit(unit);+ try {+ await api.controlRemoteService(serverId, unit, action);+ toast.success(`${unit}: ${action} ok`);+ // Refresh state — only the affected row needs a reload but+ // re-fetching the list is simpler and keeps the filter consistent.+ loadUnits();+ } catch (err) {+ toast.error(err.message || `Failed to ${action} ${unit}`);+ } finally {+ setBusyUnit(null);+ }+ }++ async function viewLogs(unit) {+ try {+ const data = await api.getRemoteServiceLogs(serverId, unit, 200);+ setLogsFor({ unit, entries: data?.entries || [] });+ } catch (err) {+ toast.error(err.message || 'Failed to load logs');+ }+ }++ async function reloadDaemon() {+ setBusyUnit('__daemon__');+ try {+ await api.reloadRemoteSystemdDaemon(serverId);+ toast.success('systemctl daemon-reload completed');+ } catch (err) {+ toast.error(err.message || 'daemon-reload failed');+ } finally {+ setBusyUnit(null);+ }+ }++ if (serverStatus !== 'online') {+ return (+ <div className="empty-state">+ <p>Server is offline. Reconnect to manage services.</p>+ </div>+ );+ }++ return (+ <div className="server-services">+ <div className="server-services__toolbar">+ <Input+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder="Filter by unit name…"+ className="server-services__search"+ />+ <div className="server-services__filters">+ {STATE_FILTERS.map((f) => (+ <Button+ key={f.value || 'all'}+ variant={stateFilter === f.value ? 'default' : 'outline'}+ size="sm"+ onClick={() => setStateFilter(f.value)}+ >+ {f.label}+ </Button>+ ))}+ </div>+ <div className="server-services__actions">+ <Button variant="outline" onClick={loadUnits}>Refresh</Button>+ <Button+ variant="outline"+ onClick={reloadDaemon}+ disabled={busyUnit === '__daemon__'}+ >+ Reload daemon+ </Button>+ </div>+ </div>++ {loading ? (+ <p className="text-muted-foreground">Loading…</p>+ ) : filtered.length === 0 ? (+ <p className="text-muted-foreground">No matching units.</p>+ ) : (+ <table className="server-services__table">+ <thead>+ <tr>+ <th>Unit</th>+ <th>State</th>+ <th>Description</th>+ <th aria-label="actions" />+ </tr>+ </thead>+ <tbody>+ {filtered.map((u) => (+ <tr key={u.unit}>+ <td className="mono">{u.unit}</td>+ <td>+ <Badge variant={u.active === 'active' ? 'default' : 'outline'}>+ {u.active || u.sub || 'unknown'}+ </Badge>+ </td>+ <td className="server-services__desc">{u.description}</td>+ <td className="server-services__row-actions">+ <Button+ size="sm" variant="outline"+ disabled={busyUnit === u.unit}+ onClick={() => control(u.unit, 'start')}+ >Start</Button>+ <Button+ size="sm" variant="outline"+ disabled={busyUnit === u.unit}+ onClick={() => control(u.unit, 'stop')}+ >Stop</Button>+ <Button+ size="sm" variant="outline"+ disabled={busyUnit === u.unit}+ onClick={() => control(u.unit, 'restart')}+ >Restart</Button>+ <Button+ size="sm" variant="outline"+ onClick={() => viewLogs(u.unit)}+ >Logs</Button>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ )}++ <Modal+ open={!!logsFor}+ onClose={() => setLogsFor(null)}+ title={logsFor ? `Logs — ${logsFor.unit}` : ''}+ size="xl"+ >+ {logsFor && (+ <pre className="server-services__logs">+ {logsFor.entries.length === 0+ ? '(no entries)'+ : logsFor.entries.map((e, i) => (+ <div key={i}>+ [{e.priority || '-'}] {e.message}+ </div>+ ))}+ </pre>+ )}+ </Modal>+ </div>+ );+};++export default ServicesTab;diff --git a/frontend/src/pages/ServerDetail.jsx b/frontend/src/pages/ServerDetail.jsxindex 186c46fc..086193ac 100644--- a/frontend/src/pages/ServerDetail.jsx+++ b/frontend/src/pages/ServerDetail.jsx@@ -12,6 +12,8 @@ import { Input } from '@/components/ui/input';import { Textarea } from '@/components/ui/textarea';import { Badge } from '@/components/ui/badge';import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';+import PackagesTab from '../components/serverdetail/PackagesTab';+import ServicesTab from '../components/serverdetail/ServicesTab';const ServerDetail = () => {const { id, tab } = useParams();@@ -25,7 +27,7 @@ const ServerDetail = () => {const [showTokenModal, setShowTokenModal] = useState(false);const toast = useToast();- const validTabs = ['overview', 'docker', 'cron', 'cloudflared', 'metrics', 'settings'];+ const validTabs = ['overview', 'docker', 'cron', 'cloudflared', 'packages', 'services', 'metrics', 'settings'];const activeTab = validTabs.includes(tab) ? tab : 'overview';const loadServer = useCallback(async () => {@@ -165,6 +167,8 @@ const ServerDetail = () => {{ id: 'docker', label: 'Docker' },...(server.capabilities?.cron ? [{ id: 'cron', label: 'Cron' }] : []),...(server.capabilities?.cloudflared ? [{ id: 'cloudflared', label: 'Tunnels' }] : []),+ ...(server.capabilities?.packages ? [{ id: 'packages', label: 'Packages' }] : []),+ ...(server.capabilities?.systemd ? [{ id: 'services', label: 'Services' }] : []),{ id: 'metrics', label: 'Metrics' },{ id: 'settings', label: 'Settings' }];@@ -262,6 +266,16 @@ const ServerDetail = () => {<CloudflaredTab serverId={id} serverStatus={server.status} /></TabsContent>)}+ {server.capabilities?.packages && (+ <TabsContent value="packages">+ <PackagesTab serverId={id} serverStatus={server.status} />+ </TabsContent>+ )}+ {server.capabilities?.systemd && (+ <TabsContent value="services">+ <ServicesTab serverId={id} serverStatus={server.status} />+ </TabsContent>+ )}<TabsContent value="metrics"><MetricsTab serverId={id} metrics={metrics} /></TabsContent>diff --git a/frontend/src/services/api/servers.js b/frontend/src/services/api/servers.jsindex e0c269f5..ee4c61eb 100644--- a/frontend/src/services/api/servers.js+++ b/frontend/src/services/api/servers.js@@ -199,6 +199,152 @@ export async function toggleRemoteCronJob(serverId, jobId, enabled) {});}+// Remote Capabilities++// Asks the agent to re-run its capability probe and pushes the+// refreshed payload back. Used after the user installs a runtime,+// configures sudoers, or adds a new package manager so feature tabs+// light up without restarting the agent service.+export async function refreshRemoteCapabilities(serverId) {+ return this.request(`/servers/${serverId}/refresh-capabilities`, {+ method: 'POST'+ });+}++// Remote Packages (via agent)+//+// install / upgrade are streaming: the panel returns+// { jobId, channel } and the frontend subscribes to the matching+// Socket.IO room (server_<id>_<channel>) for live install output.++export async function getRemotePackages(serverId) {+ return this.request(`/servers/${serverId}/packages`);+}++export async function searchRemotePackages(serverId, query, limit = 100) {+ const params = new URLSearchParams({ q: query, limit: String(limit) });+ return this.request(`/servers/${serverId}/packages/search?${params.toString()}`);+}++export async function getRemotePackageInfo(serverId, name) {+ return this.request(`/servers/${serverId}/packages/info/${encodeURIComponent(name)}`);+}++export async function updateRemotePackageCache(serverId) {+ return this.request(`/servers/${serverId}/packages/update-cache`, {+ method: 'POST'+ });+}++export async function installRemotePackages(serverId, names) {+ return this.request(`/servers/${serverId}/packages/install`, {+ method: 'POST',+ body: { names: Array.isArray(names) ? names : [names] }+ });+}++export async function removeRemotePackage(serverId, name) {+ return this.request(`/servers/${serverId}/packages/remove`, {+ method: 'POST',+ body: { name }+ });+}++export async function upgradeRemotePackages(serverId, { names = null, all = false } = {}) {+ const body = {};+ if (all) body.all = true;+ if (names && names.length) body.names = names;+ return this.request(`/servers/${serverId}/packages/upgrade`, {+ method: 'POST',+ body+ });+}++// Remote Services (systemd)++export async function getRemoteServices(serverId, { state = null, type = 'service' } = {}) {+ const params = new URLSearchParams({ type });+ if (state) params.set('state', state);+ return this.request(`/servers/${serverId}/services?${params.toString()}`);+}++export async function getRemoteServiceStatus(serverId, unit) {+ return this.request(`/servers/${serverId}/services/${encodeURIComponent(unit)}`);+}++export async function controlRemoteService(serverId, unit, action) {+ return this.request(`/servers/${serverId}/services/${encodeURIComponent(unit)}/${action}`, {+ method: 'POST'+ });+}++export async function getRemoteServiceLogs(serverId, unit, lines = 200) {+ const params = new URLSearchParams({ lines: String(lines) });+ return this.request(`/servers/${serverId}/services/${encodeURIComponent(unit)}/logs?${params.toString()}`);+}++export async function reloadRemoteSystemdDaemon(serverId) {+ return this.request(`/servers/${serverId}/services/daemon-reload`, {+ method: 'POST'+ });+}++// Remote Runtimes (pyenv / pyenv-win)+//+// pyenvBootstrap and installPythonVersion are streaming: returned+// payload contains { jobId, channel } and the frontend subscribes via+// the same Socket.IO room pattern as installRemotePackages.++export async function getRemoteRuntimes(serverId) {+ return this.request(`/servers/${serverId}/runtimes`);+}++export async function bootstrapRemotePyenv(serverId) {+ return this.request(`/servers/${serverId}/runtimes/pyenv/bootstrap`, {+ method: 'POST'+ });+}++export async function getRemotePythonVersions(serverId) {+ return this.request(`/servers/${serverId}/runtimes/python`);+}++export async function getRemotePythonAvailable(serverId) {+ return this.request(`/servers/${serverId}/runtimes/python/available`);+}++export async function getRemotePythonCurrent(serverId) {+ return this.request(`/servers/${serverId}/runtimes/python/current`);+}++export async function installRemotePythonVersion(serverId, version) {+ return this.request(`/servers/${serverId}/runtimes/python/install`, {+ method: 'POST',+ body: { version }+ });+}++export async function uninstallRemotePythonVersion(serverId, version) {+ return this.request(`/servers/${serverId}/runtimes/python/uninstall`, {+ method: 'POST',+ body: { version }+ });+}++export async function setRemotePythonGlobal(serverId, version) {+ return this.request(`/servers/${serverId}/runtimes/python/global`, {+ method: 'POST',+ body: { version }+ });+}++export async function setRemotePythonLocal(serverId, version, dir) {+ return this.request(`/servers/${serverId}/runtimes/python/local`, {+ method: 'POST',+ body: { version, dir }+ });+}+// Remote Files (via agent)export async function getRemoteAllowedPaths(serverId) {return this.request(`/servers/${serverId}/files/allowed-paths`);diff --git a/frontend/src/styles/main.scss b/frontend/src/styles/main.scssindex 16ad7573..417613c1 100644--- a/frontend/src/styles/main.scss+++ b/frontend/src/styles/main.scss@@ -96,6 +96,8 @@@import 'pages/_fleet-monitor';@import 'pages/_agent-plugins';@import 'pages/_server-templates';+@import 'pages/_server-packages';+@import 'pages/_server-services';@import 'pages/_workspaces';@import 'pages/_dns-zones';@import 'pages/_status-pages';diff --git a/frontend/src/styles/pages/_server-packages.scss b/frontend/src/styles/pages/_server-packages.scssnew file mode 100644index 00000000..a9ddc2c1--- /dev/null+++ b/frontend/src/styles/pages/_server-packages.scss@@ -0,0 +1,138 @@+// Packages tab on Server Detail. Mirrors the layout of _cron.scss so+// nothing feels foreign when bouncing between server tabs.++.server-packages {+ display: flex;+ flex-direction: column;+ gap: 1.25rem;++ &__toolbar {+ display: flex;+ gap: 0.75rem;+ align-items: center;+ flex-wrap: wrap;+ }++ &__search {+ display: flex;+ gap: 0.5rem;+ flex: 1 1 320px;+ }++ &__actions {+ display: flex;+ gap: 0.5rem;+ }++ &__presets h3,+ &__results h3,+ &__installed h3 {+ margin: 0 0 0.5rem;+ font-size: 0.95rem;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: var(--muted-foreground);+ }++ &__chips {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5rem;+ }++ &__chip {+ padding: 0.4rem 0.85rem;+ border-radius: 999px;+ border: 1px solid var(--border);+ background: var(--card);+ color: var(--foreground);+ cursor: pointer;+ font-size: 0.85rem;+ transition: background 120ms ease, border-color 120ms ease;++ &:hover {+ background: var(--accent);+ border-color: var(--primary);+ }+ }++ &__list {+ list-style: none;+ margin: 0;+ padding: 0;+ max-height: 360px;+ overflow-y: auto;+ border: 1px solid var(--border);+ border-radius: 0.5rem;+ }++ &__list-item {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.75rem;+ padding: 0.5rem 0.75rem;+ border-bottom: 1px solid var(--border);++ &:last-child {+ border-bottom: 0;+ }+ }++ &__list-name {+ font-family: var(--font-mono, monospace);+ font-size: 0.85rem;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ flex: 1 1 auto;+ }++ &__raw {+ max-height: 320px;+ overflow: auto;+ padding: 0.75rem;+ border: 1px solid var(--border);+ border-radius: 0.5rem;+ background: var(--muted);+ font-family: var(--font-mono, monospace);+ font-size: 0.8rem;+ white-space: pre-wrap;+ }++ &__hint {+ font-size: 0.85rem;+ }++ &__remove-tip {+ font-size: 0.85rem;+ padding: 0.75rem;+ border: 1px dashed var(--border);+ border-radius: 0.5rem;+ background: var(--muted);+ }++ &__remove-form {+ display: inline-flex;+ gap: 0.5rem;+ margin-left: 0.5rem;+ align-items: center;+ }+}++// Shared by JobProgressModal — kept here because Packages is its primary+// consumer. Services tab logs use a different component path.+.job-progress-modal {+ &__log {+ max-height: 60vh;+ overflow: auto;+ padding: 0.75rem;+ border: 1px solid var(--border);+ border-radius: 0.5rem;+ background: var(--muted);+ font-family: var(--font-mono, monospace);+ font-size: 0.8rem;+ white-space: pre-wrap;+ margin: 0;+ }+}diff --git a/frontend/src/styles/pages/_server-services.scss b/frontend/src/styles/pages/_server-services.scssnew file mode 100644index 00000000..5f18d811--- /dev/null+++ b/frontend/src/styles/pages/_server-services.scss@@ -0,0 +1,72 @@+// Services (systemd) tab on Server Detail.++.server-services {+ display: flex;+ flex-direction: column;+ gap: 1rem;++ &__toolbar {+ display: flex;+ gap: 0.75rem;+ align-items: center;+ flex-wrap: wrap;+ }++ &__search {+ flex: 1 1 280px;+ }++ &__filters,+ &__actions {+ display: flex;+ gap: 0.4rem;+ }++ &__table {+ width: 100%;+ border-collapse: collapse;++ th, td {+ padding: 0.55rem 0.75rem;+ text-align: left;+ border-bottom: 1px solid var(--border);+ vertical-align: middle;+ }++ th {+ font-size: 0.78rem;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: var(--muted-foreground);+ }+ }++ &__desc {+ color: var(--muted-foreground);+ font-size: 0.85rem;+ max-width: 360px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ &__row-actions {+ display: flex;+ gap: 0.35rem;+ flex-wrap: wrap;+ justify-content: flex-end;+ }++ &__logs {+ max-height: 60vh;+ overflow: auto;+ padding: 0.75rem;+ border: 1px solid var(--border);+ border-radius: 0.5rem;+ background: var(--muted);+ font-family: var(--font-mono, monospace);+ font-size: 0.8rem;+ white-space: pre-wrap;+ margin: 0;+ }+}