Skip to content

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.

Add agent Phase4 primitives, remote files & UI

Juan Denis1f61513c261f
diff --git a/agent/internal/agent/agent.go b/agent/internal/agent/agent.go
index fe8d719f..4446b30c 100644
--- a/agent/internal/agent/agent.go
+++ b/agent/internal/agent/agent.go
@@ -147,7 +147,13 @@ func New(cfg *config.Config, log *logger.Logger) (*Agent, error) {
// from whether NewClient succeeded above; the capability layer
// doesn't redo that work.
probeCtx, probeCancel := context.WithTimeout(context.Background(), 5*time.Second)
- agent.capabilities = capabilities.Probe(probeCtx, log, dockerClient != nil)
+ agent.capabilities = capabilities.Probe(
+ probeCtx,
+ log,
+ dockerClient != nil,
+ cfg.Features.FileAccess,
+ cfg.Security.AllowedPaths,
+ )
probeCancel()
// Register command handlers
@@ -243,6 +249,21 @@ func (a *Agent) registerHandlers() {
a.handlers[protocol.ActionCloudflaredTunnelRoute] = a.handleCloudflaredTunnelRoute
a.handlers[protocol.ActionCloudflaredTunnelDelete] = a.handleCloudflaredTunnelDelete
+ // Phase 4 primitives — packages, systemd, exec. Registered
+ // unconditionally so non-Linux agents return a clear error rather
+ // than "unknown action"; the capability probe gates the panel's
+ // target picker so users don't normally hit this on Windows.
+ a.handlers[protocol.ActionPackagesInstall] = a.handlePackagesInstall
+ a.handlers[protocol.ActionPackagesRemove] = a.handlePackagesRemove
+ a.handlers[protocol.ActionPackagesListInstalled] = a.handlePackagesListInstalled
+ a.handlers[protocol.ActionSystemdStatus] = a.handleSystemdStatus
+ a.handlers[protocol.ActionSystemdStart] = a.handleSystemdStart
+ a.handlers[protocol.ActionSystemdStop] = a.handleSystemdStop
+ a.handlers[protocol.ActionSystemdRestart] = a.handleSystemdRestart
+ a.handlers[protocol.ActionSystemdEnable] = a.handleSystemdEnable
+ a.handlers[protocol.ActionSystemdDisable] = a.handleSystemdDisable
+ a.handlers[protocol.ActionSystemExec] = a.handleSystemExec
+
// Agent commands
a.handlers[protocol.ActionAgentUpdate] = a.handleAgentUpdate
@@ -475,6 +496,8 @@ func (a *Agent) sendCapabilities() {
Platform: a.capabilities.Platform,
Distro: a.capabilities.Distro,
DistroVersion: a.capabilities.DistroVersion,
+ Runtimes: a.capabilities.Runtimes,
+ AllowedPaths: a.capabilities.AllowedPaths,
}
if err := a.ws.Send(msg); err != nil {
a.log.Warn("Failed to send capabilities", "error", err)
diff --git a/agent/internal/agent/workflow_handlers.go b/agent/internal/agent/workflow_handlers.go
new file mode 100644
index 00000000..1d0766e5
--- /dev/null
+++ b/agent/internal/agent/workflow_handlers.go
@@ -0,0 +1,406 @@
+package agent
+
+// Phase 4 primitive handlers — package install/remove/list, systemd
+// unit control, and bounded shell exec. The workflow engine on the
+// panel sequences these to drive playbooks like "install Docker" or
+// "install LAMP" against any agent-managed server.
+//
+// All handlers are Linux-only. The capability probe advertises
+// "packages" / "systemd" only on Linux hosts where the relevant tooling
+// is present, so the panel won't normally call these on Windows/macOS;
+// the runtime guard here is belt-and-suspenders.
+//
+// Idempotency is the contract: re-running an install on a host where
+// the package is already there returns success with installed=true and
+// no side effects. Same for systemd start on a unit already active.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os/exec"
+ "runtime"
+ "strings"
+ "time"
+)
+
+const (
+ // Package install can be slow on a fresh host (apt update + index
+ // + downloads). Bound at 5 minutes — longer than any single
+ // install we've seen, short enough to surface a hung mirror.
+ packageOpTimeout = 5 * time.Minute
+ // systemctl operations are quick; if one hangs longer than 30s
+ // something is wrong (mount-blocked unit, hung shutdown).
+ systemdOpTimeout = 30 * time.Second
+ // Default exec ceiling. Caller can override per-request via
+ // "timeout_seconds" param, capped at this value.
+ maxExecTimeout = 10 * time.Minute
+)
+
+// ───── packages ────────────────────────────────────────────────────
+
+type packageManager struct {
+ bin string // "apt-get", "dnf", "apk", "pacman", "zypper"
+ install []string // args before package name(s)
+ remove []string
+ list []string
+ queryFlag string // arg pattern for "is X installed"
+}
+
+// detectPackageManager returns the active manager on PATH or an error
+// if none is recognised. Order matters — apt-get is preferred over apt
+// for non-interactive use.
+func detectPackageManager() (*packageManager, error) {
+ if runtime.GOOS != "linux" {
+ return nil, errors.New("packages:* is Linux-only")
+ }
+ candidates := []*packageManager{
+ {bin: "apt-get", install: []string{"install", "-y"}, remove: []string{"remove", "-y"}, list: []string{"list", "--installed"}, queryFlag: "dpkg"},
+ {bin: "dnf", install: []string{"install", "-y"}, remove: []string{"remove", "-y"}, list: []string{"list", "installed"}, queryFlag: "rpm"},
+ {bin: "yum", install: []string{"install", "-y"}, remove: []string{"remove", "-y"}, list: []string{"list", "installed"}, queryFlag: "rpm"},
+ {bin: "apk", install: []string{"add"}, remove: []string{"del"}, list: []string{"info"}, queryFlag: "apk"},
+ {bin: "pacman", install: []string{"-S", "--noconfirm"}, remove: []string{"-R", "--noconfirm"}, list: []string{"-Q"}, queryFlag: "pacman"},
+ {bin: "zypper", install: []string{"install", "-y"}, remove: []string{"remove", "-y"}, list: []string{"se", "--installed-only"}, queryFlag: "rpm"},
+ }
+ for _, c := range candidates {
+ if _, err := exec.LookPath(c.bin); err == nil {
+ return c, nil
+ }
+ }
+ return nil, errors.New("no recognised package manager on PATH")
+}
+
+// isInstalled checks the package database directly so install/remove
+// can short-circuit when there's nothing to do. Avoids re-running the
+// full manager (which on apt would otherwise refresh sources first).
+func (pm *packageManager) isInstalled(ctx context.Context, name string) (bool, error) {
+ switch pm.queryFlag {
+ case "dpkg":
+ out, err := exec.CommandContext(ctx, "dpkg-query", "-W", "-f=${Status}", name).Output()
+ if err != nil {
+ return false, nil // not installed
+ }
+ return strings.Contains(string(out), "install ok installed"), nil
+ case "rpm":
+ err := exec.CommandContext(ctx, "rpm", "-q", name).Run()
+ return err == nil, nil
+ case "apk":
+ err := exec.CommandContext(ctx, "apk", "info", "-e", name).Run()
+ return err == nil, nil
+ case "pacman":
+ err := exec.CommandContext(ctx, "pacman", "-Q", name).Run()
+ return err == nil, nil
+ }
+ return false, fmt.Errorf("unsupported query flag: %s", pm.queryFlag)
+}
+
+func validatePackageName(name string) error {
+ name = strings.TrimSpace(name)
+ if name == "" {
+ return errors.New("name is required")
+ }
+ // Reject shell metacharacters — the package name goes straight
+ // into argv but we still don't want to explain to a user why
+ // `apt-get install "foo; rm -rf /"` worked.
+ if strings.ContainsAny(name, ";&|`$<>\n\r\"'\\") {
+ return fmt.Errorf("invalid package name: %q", name)
+ }
+ return nil
+}
+
+func (a *Agent) handlePackagesInstall(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ var p struct {
+ Name string `json:"name"`
+ }
+ if err := json.Unmarshal(params, &p); err != nil {
+ return nil, fmt.Errorf("invalid params: %w", err)
+ }
+ if err := validatePackageName(p.Name); err != nil {
+ return nil, err
+ }
+ pm, err := detectPackageManager()
+ if err != nil {
+ return nil, err
+ }
+
+ // Idempotency: check first so a re-run is cheap and obvious.
+ if installed, _ := pm.isInstalled(ctx, p.Name); installed {
+ return map[string]interface{}{
+ "package": p.Name,
+ "installed": true,
+ "action": "noop",
+ "manager": pm.bin,
+ }, nil
+ }
+
+ cctx, cancel := context.WithTimeout(ctx, packageOpTimeout)
+ defer cancel()
+ args := append(append([]string{}, pm.install...), p.Name)
+ out, err := exec.CommandContext(cctx, pm.bin, args...).CombinedOutput()
+ if err != nil {
+ return nil, fmt.Errorf("%s %s: %w (%s)", pm.bin, strings.Join(args, " "), err, truncate(string(out), 1024))
+ }
+ return map[string]interface{}{
+ "package": p.Name,
+ "installed": true,
+ "action": "installed",
+ "manager": pm.bin,
+ "output": truncate(string(out), 4096),
+ }, nil
+}
+
+func (a *Agent) handlePackagesRemove(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ var p struct {
+ Name string `json:"name"`
+ }
+ if err := json.Unmarshal(params, &p); err != nil {
+ return nil, fmt.Errorf("invalid params: %w", err)
+ }
+ if err := validatePackageName(p.Name); err != nil {
+ return nil, err
+ }
+ pm, err := detectPackageManager()
+ if err != nil {
+ return nil, err
+ }
+
+ if installed, _ := pm.isInstalled(ctx, p.Name); !installed {
+ return map[string]interface{}{
+ "package": p.Name,
+ "installed": false,
+ "action": "noop",
+ "manager": pm.bin,
+ }, nil
+ }
+
+ cctx, cancel := context.WithTimeout(ctx, packageOpTimeout)
+ defer cancel()
+ args := append(append([]string{}, pm.remove...), p.Name)
+ out, err := exec.CommandContext(cctx, pm.bin, args...).CombinedOutput()
+ if err != nil {
+ return nil, fmt.Errorf("%s %s: %w (%s)", pm.bin, strings.Join(args, " "), err, truncate(string(out), 1024))
+ }
+ return map[string]interface{}{
+ "package": p.Name,
+ "installed": false,
+ "action": "removed",
+ "manager": pm.bin,
+ "output": truncate(string(out), 4096),
+ }, nil
+}
+
+func (a *Agent) handlePackagesListInstalled(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ pm, err := detectPackageManager()
+ if err != nil {
+ return nil, err
+ }
+ cctx, cancel := context.WithTimeout(ctx, packageOpTimeout)
+ defer cancel()
+ out, err := exec.CommandContext(cctx, pm.bin, pm.list...).Output()
+ if err != nil {
+ return nil, fmt.Errorf("%s %s: %w", pm.bin, strings.Join(pm.list, " "), err)
+ }
+ // Don't try to parse — formats vary too much. Ship the raw output
+ // and let downstream tooling pick what it cares about.
+ return map[string]interface{}{
+ "manager": pm.bin,
+ "output": truncate(string(out), 1024*256),
+ }, nil
+}
+
+// ───── systemd ─────────────────────────────────────────────────────
+
+func validateUnitName(name string) error {
+ name = strings.TrimSpace(name)
+ if name == "" {
+ return errors.New("unit is required")
+ }
+ if strings.ContainsAny(name, ";&|`$<>\n\r\"'\\ ") {
+ return fmt.Errorf("invalid unit name: %q", name)
+ }
+ return nil
+}
+
+func systemctlAvailable() error {
+ if runtime.GOOS != "linux" {
+ return errors.New("systemd:* is Linux-only")
+ }
+ if _, err := exec.LookPath("systemctl"); err != nil {
+ return errors.New("systemctl not on PATH")
+ }
+ return nil
+}
+
+func runSystemctl(ctx context.Context, args ...string) (string, error) {
+ cctx, cancel := context.WithTimeout(ctx, systemdOpTimeout)
+ defer cancel()
+ out, err := exec.CommandContext(cctx, "systemctl", args...).CombinedOutput()
+ return strings.TrimSpace(string(out)), err
+}
+
+func parseUnitParam(params json.RawMessage) (string, error) {
+ var p struct {
+ Unit string `json:"unit"`
+ }
+ if err := json.Unmarshal(params, &p); err != nil {
+ return "", fmt.Errorf("invalid params: %w", err)
+ }
+ if err := validateUnitName(p.Unit); err != nil {
+ return "", err
+ }
+ return p.Unit, nil
+}
+
+func (a *Agent) handleSystemdStatus(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ if err := systemctlAvailable(); err != nil {
+ return nil, err
+ }
+ unit, err := parseUnitParam(params)
+ if err != nil {
+ return nil, err
+ }
+ // is-active exits non-zero for inactive — that's expected, capture it.
+ active, _ := runSystemctl(ctx, "is-active", unit)
+ enabled, _ := runSystemctl(ctx, "is-enabled", unit)
+ return map[string]interface{}{
+ "unit": unit,
+ "active": active,
+ "enabled": enabled,
+ }, nil
+}
+
+func (a *Agent) handleSystemdStart(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ if err := systemctlAvailable(); err != nil {
+ return nil, err
+ }
+ unit, err := parseUnitParam(params)
+ if err != nil {
+ return nil, err
+ }
+ if out, err := runSystemctl(ctx, "start", unit); err != nil {
+ return nil, fmt.Errorf("systemctl start %s: %w (%s)", unit, err, out)
+ }
+ return map[string]interface{}{"unit": unit, "action": "started"}, nil
+}
+
+func (a *Agent) handleSystemdStop(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ if err := systemctlAvailable(); err != nil {
+ return nil, err
+ }
+ unit, err := parseUnitParam(params)
+ if err != nil {
+ return nil, err
+ }
+ if out, err := runSystemctl(ctx, "stop", unit); err != nil {
+ return nil, fmt.Errorf("systemctl stop %s: %w (%s)", unit, err, out)
+ }
+ return map[string]interface{}{"unit": unit, "action": "stopped"}, nil
+}
+
+func (a *Agent) handleSystemdRestart(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ if err := systemctlAvailable(); err != nil {
+ return nil, err
+ }
+ unit, err := parseUnitParam(params)
+ if err != nil {
+ return nil, err
+ }
+ if out, err := runSystemctl(ctx, "restart", unit); err != nil {
+ return nil, fmt.Errorf("systemctl restart %s: %w (%s)", unit, err, out)
+ }
+ return map[string]interface{}{"unit": unit, "action": "restarted"}, nil
+}
+
+func (a *Agent) handleSystemdEnable(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ if err := systemctlAvailable(); err != nil {
+ return nil, err
+ }
+ unit, err := parseUnitParam(params)
+ if err != nil {
+ return nil, err
+ }
+ if out, err := runSystemctl(ctx, "enable", unit); err != nil {
+ return nil, fmt.Errorf("systemctl enable %s: %w (%s)", unit, err, out)
+ }
+ return map[string]interface{}{"unit": unit, "action": "enabled"}, nil
+}
+
+func (a *Agent) handleSystemdDisable(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ if err := systemctlAvailable(); err != nil {
+ return nil, err
+ }
+ unit, err := parseUnitParam(params)
+ if err != nil {
+ return nil, err
+ }
+ if out, err := runSystemctl(ctx, "disable", unit); err != nil {
+ return nil, fmt.Errorf("systemctl disable %s: %w (%s)", unit, err, out)
+ }
+ return map[string]interface{}{"unit": unit, "action": "disabled"}, nil
+}
+
+// ───── system:exec ─────────────────────────────────────────────────
+
+// handleSystemExec runs an arbitrary command, captures stdout/stderr,
+// and returns the exit code. The first token must be an absolute path
+// (same rule as cron commands) so a misconfigured caller can't depend
+// on $PATH state of the agent process. Output is truncated to keep the
+// command envelope reasonable; the runner can poll a file if it needs
+// the full output of a chatty install.
+func (a *Agent) handleSystemExec(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ var p struct {
+ Command string `json:"command"`
+ Args []string `json:"args"`
+ WorkingDir string `json:"working_dir"`
+ TimeoutSeconds int `json:"timeout_seconds"`
+ }
+ if err := json.Unmarshal(params, &p); err != nil {
+ return nil, fmt.Errorf("invalid params: %w", err)
+ }
+ cmd := strings.TrimSpace(p.Command)
+ if cmd == "" {
+ return nil, errors.New("command is required")
+ }
+ if !strings.HasPrefix(cmd, "/") {
+ return nil, errors.New("command must be an absolute path")
+ }
+ if strings.ContainsAny(cmd, ";&|`$<>\n\r") {
+ return nil, errors.New("command contains shell metacharacters; pass arguments via args[]")
+ }
+
+ timeout := time.Duration(p.TimeoutSeconds) * time.Second
+ if timeout <= 0 || timeout > maxExecTimeout {
+ timeout = maxExecTimeout
+ }
+ cctx, cancel := context.WithTimeout(ctx, timeout)
+ defer cancel()
+
+ c := exec.CommandContext(cctx, cmd, p.Args...)
+ if p.WorkingDir != "" {
+ c.Dir = p.WorkingDir
+ }
+ out, err := c.CombinedOutput()
+ exitCode := 0
+ if err != nil {
+ var ee *exec.ExitError
+ if errors.As(err, &ee) {
+ exitCode = ee.ExitCode()
+ } else {
+ return nil, fmt.Errorf("exec %s: %w", cmd, err)
+ }
+ }
+ return map[string]interface{}{
+ "command": cmd,
+ "args": p.Args,
+ "exit_code": exitCode,
+ "output": truncate(string(out), 1024*32),
+ }, nil
+}
+
+func truncate(s string, n int) string {
+ if len(s) <= n {
+ return s
+ }
+ return s[:n] + "\n…[truncated]"
+}
diff --git a/agent/internal/capabilities/capabilities.go b/agent/internal/capabilities/capabilities.go
index 464c9e19..da527071 100644
--- a/agent/internal/capabilities/capabilities.go
+++ b/agent/internal/capabilities/capabilities.go
@@ -31,7 +31,12 @@ import (
// dockerAvailable is passed in by the agent because it has already
// dialled the docker socket during startup; re-probing here would just
// duplicate that work.
-func Probe(ctx context.Context, log *logger.Logger, dockerAvailable bool) protocol.CapabilitiesMessage {
+//
+// fileAccess + allowedPaths come from agent config (Features.FileAccess /
+// Security.AllowedPaths). Surfacing them here lets the panel hide
+// remote-file features on agents that have file access disabled, and
+// show the user which roots they can browse instead of guessing.
+func Probe(ctx context.Context, log *logger.Logger, dockerAvailable bool, fileAccess bool, allowedPaths []string) protocol.CapabilitiesMessage {
caps := protocol.Capabilities{}
// Docker — the agent's own client is the source of truth. If the
@@ -39,6 +44,12 @@ func Probe(ctx context.Context, log *logger.Logger, dockerAvailable bool) protoc
// it.
caps["docker"] = dockerAvailable
+ // File access — exposed via the Features.FileAccess config bit.
+ // The agent already gates file:* handler registration on this; we
+ // advertise it so the panel can hide the file manager target picker
+ // for agents where it's off (and Phase 3+ verbs that depend on it).
+ caps["files"] = fileAccess && len(allowedPaths) > 0
+
// Linux service surfaces. On non-Linux these stay false; the
// panel's UI is already conditional on them.
caps["cron"] = probeCron()
@@ -88,12 +99,20 @@ func Probe(ctx context.Context, log *logger.Logger, dockerAvailable bool) protoc
)
}
+ // Only forward allowed_paths when files capability is true — saves
+ // the panel from having to defensively check both fields.
+ var advertisedPaths []string
+ if caps["files"] {
+ advertisedPaths = append(advertisedPaths, allowedPaths...)
+ }
+
return protocol.CapabilitiesMessage{
Capabilities: caps,
Platform: platform,
Distro: distro,
DistroVersion: distroVer,
Runtimes: runtimes,
+ AllowedPaths: advertisedPaths,
}
}
diff --git a/agent/pkg/protocol/messages.go b/agent/pkg/protocol/messages.go
index 24904b83..4931b7dc 100644
--- a/agent/pkg/protocol/messages.go
+++ b/agent/pkg/protocol/messages.go
@@ -174,6 +174,11 @@ type CapabilitiesMessage struct {
// "installed but the version probe failed." Forward-compatible —
// new keys just light up in the panel without protocol changes.
Runtimes map[string]string `json:"runtimes,omitempty"`
+ // AllowedPaths advertises the file-access roots the agent is willing
+ // to expose. Sent only when capabilities["files"] is true so the
+ // panel's file manager can render the available browse roots without
+ // guessing. Empty/missing => the panel must hide remote file features.
+ AllowedPaths []string `json:"allowed_paths,omitempty"`
}
// SystemInfo contains detailed system information
@@ -234,6 +239,24 @@ const (
ActionSystemProcesses = "system:processes"
ActionSystemExec = "system:exec"
+ // Package management actions — Phase 4 primitives the workflow
+ // engine sequences for "install Docker", "install LAMP" templates.
+ // Linux-only; the agent picks the right manager (apt/dnf/apk/…)
+ // based on what's on PATH. Calls are idempotent — installing an
+ // already-installed package is a no-op success.
+ ActionPackagesInstall = "packages:install"
+ ActionPackagesRemove = "packages:remove"
+ ActionPackagesListInstalled = "packages:list_installed"
+
+ // Systemd unit actions. Linux-only and require systemd as PID 1
+ // (the capability probe already gates this).
+ ActionSystemdStatus = "systemd:status"
+ ActionSystemdStart = "systemd:start"
+ ActionSystemdStop = "systemd:stop"
+ ActionSystemdRestart = "systemd:restart"
+ ActionSystemdEnable = "systemd:enable"
+ ActionSystemdDisable = "systemd:disable"
+
// Cron actions — manage entries in the agent host's user crontab.
// Linux-only; non-Linux agents return an "unsupported" error.
ActionCronStatus = "cron:status"
diff --git a/backend/app/api/servers.py b/backend/app/api/servers.py
index 202cb392..2b0c3a17 100644
--- a/backend/app/api/servers.py
+++ b/backend/app/api/servers.py
@@ -2296,3 +2296,61 @@ def remote_cloudflared_delete(server_id, tunnel_ref):
user_id = get_jwt_identity()
result = RemoteCloudflaredService.delete_tunnel(server_id, tunnel_ref, user_id=user_id)
return _agent_result(result)
+
+
+# ==================== Remote File Operations ====================
+#
+# Endpoints under /servers/<id>/files/ proxy to the agent's file:*
+# command handlers. Phase 3b ships browse/read/write only — the broader
+# verb set (delete, mkdir, rename, copy, chmod, search, disk_usage)
+# requires new agent handlers and lands in a follow-up. The agent owns
+# allowed_paths enforcement; the panel just transports.
+
+from app.services.remote_file_service import RemoteFileService
+
+
+@servers_bp.route('/<server_id>/files/allowed-paths', methods=['GET'])
+@jwt_required()
+def remote_file_allowed_paths(server_id):
+ """Return the file roots the agent advertised on connect. Lets the
+ file manager seed the browse picker without guessing or hardcoding."""
+ paths = RemoteFileService.get_allowed_paths(server_id)
+ return jsonify({'allowed_paths': paths})
+
+
+@servers_bp.route('/<server_id>/files/browse', methods=['GET'])
+@jwt_required()
+def remote_file_browse(server_id):
+ user_id = get_jwt_identity()
+ path = request.args.get('path')
+ if not path:
+ return jsonify({'error': 'path is required'}), 400
+ result = RemoteFileService.list_directory(server_id, path, user_id=user_id)
+ return _agent_result(result)
+
+
+@servers_bp.route('/<server_id>/files/read', methods=['GET'])
+@jwt_required()
+def remote_file_read(server_id):
+ user_id = get_jwt_identity()
+ path = request.args.get('path')
+ if not path:
+ return jsonify({'error': 'path is required'}), 400
+ result = RemoteFileService.read_file(server_id, path, user_id=user_id)
+ return _agent_result(result)
+
+
+@servers_bp.route('/<server_id>/files/write', methods=['POST'])
+@jwt_required()
+@developer_required
+def remote_file_write(server_id):
+ user_id = get_jwt_identity()
+ data = request.get_json(silent=True) or {}
+ path = (data.get('path') or '').strip()
+ content = data.get('content')
+ if not path:
+ return jsonify({'error': 'path is required'}), 400
+ if content is None:
+ return jsonify({'error': 'content is required'}), 400
+ result = RemoteFileService.write_file(server_id, path, content, user_id=user_id)
+ return _agent_result(result)
diff --git a/backend/app/services/agent_registry.py b/backend/app/services/agent_registry.py
index db57762f..2e99fdda 100644
--- a/backend/app/services/agent_registry.py
+++ b/backend/app/services/agent_registry.py
@@ -57,6 +57,10 @@ class ConnectedAgent:
# ({"python": "3.11.4", "node": "20.10.0"}). Empty for older
# agents and for hosts where no runtime probes matched.
runtimes: Dict[str, str] = field(default_factory=dict)
+ # File-access roots advertised when capabilities["files"] is true.
+ # Used by the file manager to seed the browse picker. Empty for
+ # agents that have file access disabled or don't speak the protocol.
+ allowed_paths: list = field(default_factory=list)
@dataclass
@@ -761,6 +765,12 @@ class AgentRegistry:
if isinstance(k, str) and isinstance(v, (str, type(None))):
clean_runtimes[k] = v or ''
+ # Allowed paths — only meaningful when capabilities["files"] is
+ # true; coerce to list of strings either way for safety.
+ raw_paths = payload.get('allowed_paths') or []
+ clean_paths = [str(p) for p in raw_paths if isinstance(p, str) and p.strip()] \
+ if isinstance(raw_paths, list) else []
+
with self._lock:
agent = self._agents.get(server_id)
if not agent:
@@ -770,6 +780,7 @@ class AgentRegistry:
agent.distro = payload.get('distro') or None
agent.distro_version = payload.get('distro_version') or None
agent.runtimes = clean_runtimes
+ agent.allowed_paths = clean_paths
logger.info(
"Capabilities updated for server %s: %s",
@@ -795,6 +806,14 @@ class AgentRegistry:
return False
return bool(caps.get(feature))
+ def get_allowed_paths(self, server_id: str) -> list:
+ """File roots the agent advertised on connect, empty if not advertised."""
+ with self._lock:
+ agent = self._agents.get(server_id)
+ if not agent:
+ return []
+ return list(agent.allowed_paths)
+
# ==================== System Info ====================
def update_system_info(self, server_id: str, info: dict):
diff --git a/backend/app/services/plugin_service.py b/backend/app/services/plugin_service.py
index cf33fa4d..78e870f2 100644
--- a/backend/app/services/plugin_service.py
+++ b/backend/app/services/plugin_service.py
@@ -146,19 +146,82 @@ def install_from_url(url, user_id=None):
Returns:
InstalledPlugin instance
"""
- _ensure_dirs()
-
- # Download
try:
buf = _download_zip(url)
except Exception as e:
raise ValueError(f'Failed to download plugin: {e}')
+ return _install_from_buffer(
+ buf, source_url=url, source_type='url', user_id=user_id,
+ )
+
+
+def install_from_path(path, user_id=None):
+ """Install a plugin from a local directory.
+
+ Useful during plugin development: point at the working tree, install,
+ iterate. Internally we zip the folder in memory and reuse the same
+ install pipeline as URL/upload installs so behavior is identical.
+ """
+ if not path:
+ raise ValueError('path is required')
+ path = os.path.abspath(os.path.expanduser(path))
+ if not os.path.isdir(path):
+ raise ValueError(f'Not a directory: {path}')
+ if not os.path.exists(os.path.join(path, 'plugin.json')):
+ raise ValueError(f'No plugin.json in {path}')
+
+ # Zip the folder in memory, skipping dev junk that bloats the bundle.
+ skip_dirs = {
+ '.git', '.github', 'node_modules', '__pycache__',
+ '.venv', 'venv', 'dist', 'build', '.pytest_cache',
+ '.idea', '.vscode',
+ }
+ skip_files_endswith = ('.pyc', '.pyo')
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, 'w', zipfile.ZIP_DEFLATED) as zf:
+ for root, dirs, files in os.walk(path):
+ # mutate dirs in place so os.walk skips them
+ dirs[:] = [d for d in dirs if d not in skip_dirs]
+ for name in files:
+ if name.endswith(skip_files_endswith):
+ continue
+ full = os.path.join(root, name)
+ rel = os.path.relpath(full, path).replace(os.sep, '/')
+ zf.write(full, rel)
+ buf.seek(0)
+
+ return _install_from_buffer(
+ buf, source_url=path, source_type='local', user_id=user_id,
+ )
+
+
+def install_from_zip(zip_bytes, user_id=None, source_name=None):
+ """Install a plugin from raw zip bytes (e.g. a multipart upload)."""
+ if not zip_bytes:
+ raise ValueError('Empty upload')
+ buf = io.BytesIO(zip_bytes)
+ return _install_from_buffer(
+ buf,
+ source_url=source_name or 'uploaded.zip',
+ source_type='upload',
+ user_id=user_id,
+ )
+
+
+def _install_from_buffer(buf, source_url, source_type, user_id=None):
+ """Shared install pipeline: takes a seekable BytesIO containing a zip,
+ extracts it into the panel's plugin dirs, and registers / hot-loads
+ the resulting blueprint. All public install_* helpers funnel here so
+ behavior matches across URL / local / upload sources.
+ """
+ _ensure_dirs()
+
# Open zip
try:
zf = zipfile.ZipFile(buf)
except zipfile.BadZipFile:
- raise ValueError('Downloaded file is not a valid zip archive')
+ raise ValueError('File is not a valid zip archive')
# Find and read manifest
manifest_path, prefix = _find_manifest(zf)
@@ -181,7 +244,8 @@ def install_from_url(url, user_id=None):
plugin.status = InstalledPlugin.STATUS_INSTALLING
plugin.error_message = None
plugin.version = manifest['version']
- plugin.source_url = url
+ plugin.source_url = source_url
+ plugin.source_type = source_type
plugin.manifest = manifest
else:
plugin = InstalledPlugin(
@@ -195,8 +259,8 @@ def install_from_url(url, user_id=None):
repository=manifest.get('repository', ''),
license=manifest.get('license', ''),
category=manifest.get('category', 'utility'),
- source_url=url,
- source_type='url',
+ source_url=source_url,
+ source_type=source_type,
installed_by=user_id,
status=InstalledPlugin.STATUS_INSTALLING,
)
diff --git a/backend/app/services/remote_docker_service.py b/backend/app/services/remote_docker_service.py
index 93c24974..6ae6c864 100644
--- a/backend/app/services/remote_docker_service.py
+++ b/backend/app/services/remote_docker_service.py
@@ -359,7 +359,86 @@ class RemoteDockerService:
# ==================== System ====================
@staticmethod
- def get_system_metrics(server_id: str, user_id: int = None) -> Dict[str, Any]:
+ def _human_bytes(n: int) -> str:
+ n = float(n or 0)
+ for unit in ('B', 'KB', 'MB', 'GB', 'TB'):
+ if n < 1024:
+ return f"{n:.1f}{unit}"
+ n /= 1024
+ return f"{n:.1f}PB"
+
+ @classmethod
+ def _normalize_agent_metrics(cls, flat: Dict[str, Any]) -> Dict[str, Any]:
+ # Agent emits a flat shape (cpu_percent, memory_used, …); the panel
+ # frontend (Dashboard, MetricsGraph) was designed against the nested
+ # shape that local SystemService.get_all_metrics returns. Project the
+ # flat agent payload into the nested shape and keep the flat fields
+ # for callers that still consume them (ServerDetail MetricsTab).
+ if not isinstance(flat, dict):
+ return flat
+ h = cls._human_bytes
+ mem_total = flat.get('memory_total', 0) or 0
+ mem_used = flat.get('memory_used', 0) or 0
+ mem_avail = max(mem_total - mem_used, 0)
+ nested = {
+ 'cpu': {
+ 'percent': flat.get('cpu_percent', 0),
+ 'count_logical': len(flat.get('cpu_per_core') or []) or None,
+ 'per_cpu': flat.get('cpu_per_core') or [],
+ },
+ 'memory': {
+ 'ram': {
+ 'total': mem_total,
+ 'used': mem_used,
+ 'available': mem_avail,
+ 'cached': 0,
+ 'percent': flat.get('memory_percent', 0),
+ 'total_human': h(mem_total),
+ 'used_human': h(mem_used),
+ 'available_human': h(mem_avail),
+ 'cached_human': h(0),
+ },
+ 'swap': {
+ 'total': flat.get('swap_total', 0),
+ 'used': flat.get('swap_used', 0),
+ 'percent': flat.get('swap_percent', 0),
+ 'total_human': h(flat.get('swap_total', 0)),
+ 'used_human': h(flat.get('swap_used', 0)),
+ },
+ },
+ 'disk': {
+ 'partitions': [{
+ 'mountpoint': '/',
+ 'total': flat.get('disk_total', 0),
+ 'used': flat.get('disk_used', 0),
+ 'free': max((flat.get('disk_total', 0) or 0) - (flat.get('disk_used', 0) or 0), 0),
+ 'percent': flat.get('disk_percent', 0),
+ 'total_human': h(flat.get('disk_total', 0)),
+ 'used_human': h(flat.get('disk_used', 0)),
+ 'free_human': h(max((flat.get('disk_total', 0) or 0) - (flat.get('disk_used', 0) or 0), 0)),
+ }],
+ },
+ 'network': {
+ 'io': {
+ 'bytes_sent': flat.get('network_tx', 0),
+ 'bytes_recv': flat.get('network_rx', 0),
+ 'bytes_sent_human': h(flat.get('network_tx', 0)),
+ 'bytes_recv_human': h(flat.get('network_rx', 0)),
+ },
+ },
+ 'load_average': {
+ '1min': flat.get('load_avg_1', 0),
+ '5min': flat.get('load_avg_5', 0),
+ '15min': flat.get('load_avg_15', 0),
+ },
+ }
+ # Merge — flat keys preserved for legacy consumers
+ merged = dict(flat)
+ merged.update(nested)
+ return merged
+
+ @classmethod
+ def get_system_metrics(cls, server_id: str, user_id: int = None) -> Dict[str, Any]:
"""Get system metrics from a remote server"""
if not server_id or server_id == 'local':
from app.services.system_service import SystemService
@@ -369,12 +448,16 @@ class RemoteDockerService:
except Exception as e:
return {'success': False, 'error': str(e)}
- return agent_registry.send_command(
+ result = agent_registry.send_command(
server_id=server_id,
action='system:metrics',
params={},
user_id=user_id
)
+ if result.get('success') and isinstance(result.get('data'), dict):
+ result = dict(result)
+ result['data'] = cls._normalize_agent_metrics(result['data'])
+ return result
@staticmethod
def get_system_info(server_id: str, user_id: int = None) -> Dict[str, Any]:
@@ -420,13 +503,19 @@ class RemoteDockerService:
for server in remote_servers:
has_docker_perm = server.has_permission('docker:container:read')
+ # Capabilities and allowed_paths are only meaningful when the
+ # agent is actually connected (in-memory registry state).
+ caps = agent_registry.get_capabilities(server.id) if server.id in connected_ids else None
+ allowed_paths = agent_registry.get_allowed_paths(server.id) if server.id in connected_ids else []
servers.append({
'id': server.id,
'name': server.name,
'status': 'online' if server.id in connected_ids else server.status,
'is_local': False,
'has_docker': has_docker_perm,
- 'group_name': server.group.name if server.group else None
+ 'group_name': server.group.name if server.group else None,
+ 'capabilities': caps or {},
+ 'allowed_paths': allowed_paths,
})
return servers
diff --git a/backend/app/services/remote_file_service.py b/backend/app/services/remote_file_service.py
new file mode 100644
index 00000000..f3fba763
--- /dev/null
+++ b/backend/app/services/remote_file_service.py
@@ -0,0 +1,71 @@
+"""
+Remote File Service
+
+Mirrors the local FileService surface but routes through the agent
+registry so callers can target a remote server. Phase 3b ships only the
+verbs the agent already supports (file:read, file:write, file:list);
+other operations (delete, mkdir, rename, copy, chmod, search, disk
+usage) require new agent handlers and land in a follow-up.
+
+Action mapping (panel → agent):
+ file:list -> {path, files: [{name, path, is_dir, size, modified, ...}]}
+ file:read -> {path, content, size}
+ file:write -> {success: true, path, size}
+
+Allowed paths are enforced on the agent side via validateFileAccess —
+the panel never sees the agent's filesystem state and shouldn't try to
+second-guess it.
+"""
+
+from typing import Any, Dict, Optional
+
+from app.services.agent_registry import agent_registry
+
+
+class RemoteFileService:
+ """Thin dispatcher to agent file:* handlers."""
+
+ @staticmethod
+ def _send(server_id: str, action: str, params: Optional[Dict[str, Any]] = None,
+ user_id: Optional[int] = None, timeout: float = 15.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_directory(server_id: str, path: str,
+ user_id: Optional[int] = None) -> Dict[str, Any]:
+ return RemoteFileService._send(
+ server_id, 'file:list',
+ params={'path': path},
+ user_id=user_id,
+ )
+
+ @staticmethod
+ def read_file(server_id: str, path: str,
+ user_id: Optional[int] = None) -> Dict[str, Any]:
+ return RemoteFileService._send(
+ server_id, 'file:read',
+ params={'path': path},
+ user_id=user_id,
+ )
+
+ @staticmethod
+ def write_file(server_id: str, path: str, content: str,
+ user_id: Optional[int] = None) -> Dict[str, Any]:
+ return RemoteFileService._send(
+ server_id, 'file:write',
+ params={'path': path, 'content': content},
+ user_id=user_id,
+ timeout=30.0,
+ )
+
+ @staticmethod
+ def get_allowed_paths(server_id: str) -> list:
+ """Roots the agent advertised on connect — used by the UI to seed
+ the browse picker. Empty for agents that don't expose files."""
+ return agent_registry.get_allowed_paths(server_id)
diff --git a/backend/app/services/workflow_engine.py b/backend/app/services/workflow_engine.py
index f5d75647..a07fe926 100644
--- a/backend/app/services/workflow_engine.py
+++ b/backend/app/services/workflow_engine.py
@@ -35,6 +35,49 @@ DEFAULT_RETRY_DELAY = 5 # seconds
MAX_OUTPUT_SIZE = 1024 * 512 # 512 KB
+def _parse_version(s: str) -> tuple:
+ """Turn '3.11.4' / 'v20.10.0' / '8.2' into a comparable tuple of ints.
+ Trailing non-numeric parts are dropped silently."""
+ if not s:
+ return ()
+ s = s.lstrip('vV').strip()
+ parts = []
+ for part in s.split('.'):
+ digits = ''.join(c for c in part if c.isdigit())
+ if not digits:
+ break
+ parts.append(int(digits))
+ return tuple(parts)
+
+
+def _runtime_satisfies(actual: str, spec: str) -> bool:
+ """Compare actual version against a spec like '>=3.11', '>=18',
+ '==8.2', or just '3.11' (treated as >=). Naive but covers the
+ realistic gate cases without an extra dep."""
+ spec = spec.strip()
+ op = '>='
+ for prefix in ('>=', '<=', '==', '>', '<'):
+ if spec.startswith(prefix):
+ op = prefix
+ spec = spec[len(prefix):].strip()
+ break
+ a = _parse_version(actual)
+ b = _parse_version(spec)
+ if not a or not b:
+ return False
+ if op == '>=':
+ return a >= b
+ if op == '<=':
+ return a <= b
+ if op == '==':
+ return a == b
+ if op == '>':
+ return a > b
+ if op == '<':
+ return a < b
+ return False
+
+
class CycleDetectedError(Exception):
"""Raised when a cycle is detected in the workflow graph."""
pass
@@ -348,8 +391,197 @@ class WorkflowEngine:
elif node_type == 'logic_if':
return WorkflowEngine._execute_logic_if(node, context, results)
+ # Phase 4 — fleet workflow primitives. Each routes to an agent
+ # via the registry; on failure they short-circuit the workflow
+ # so a missing capability or wrong runtime doesn't silently
+ # mutate the target host.
+ elif node_type == 'agent_command':
+ return WorkflowEngine._execute_agent_command(node, execution, context, results)
+ elif node_type == 'capability_gate':
+ return WorkflowEngine._execute_capability_gate(node)
+ elif node_type == 'runtime_gate':
+ return WorkflowEngine._execute_runtime_gate(node)
+
return {'success': True, 'message': f"Node type {node_type} passed through"}
+ # ------------------------------------------------------------------
+ # Phase 4: Agent Command + Gate Execution
+ # ------------------------------------------------------------------
+
+ @staticmethod
+ def _resolve_target(node_data: Dict) -> Optional[str]:
+ """Pull a `{kind, server_id}` target from node_data and return
+ the server_id for agent dispatch, or None for the local panel
+ host. Raises if the target dict is malformed."""
+ target = node_data.get('target') or {'kind': 'local'}
+ kind = target.get('kind')
+ if kind == 'local' or kind is None:
+ return None
+ if kind == 'agent':
+ sid = target.get('server_id')
+ if not sid:
+ raise ValueError("agent target missing server_id")
+ return sid
+ # 'agent_group' lands when multi-target execution does — for
+ # now reject so a user authoring a template against a
+ # not-yet-implemented mode gets a clear error instead of
+ # silent passthrough.
+ raise ValueError(f"unsupported target kind: {kind}")
+
+ @staticmethod
+ def _execute_agent_command(node: Dict, execution: WorkflowExecution,
+ context: Dict, results: Dict) -> Dict:
+ """Dispatch an action to an agent and return the result. The
+ node's data carries the action verb, params, and target — see
+ plan §Phase 4 for the schema."""
+ from app.services.agent_registry import agent_registry
+
+ node_data = node.get('data', {})
+ action = (node_data.get('action') or '').strip()
+ if not action:
+ return {'success': False, 'error': 'agent_command node missing action'}
+
+ try:
+ server_id = WorkflowEngine._resolve_target(node_data)
+ except ValueError as e:
+ return {'success': False, 'error': str(e)}
+
+ if server_id is None:
+ # Local target on an agent_command node is unusual — the
+ # equivalent panel-local action belongs in the original
+ # node types. Treat as a config error rather than guessing.
+ return {
+ 'success': False,
+ 'error': "agent_command requires an agent target; use the matching local node type instead",
+ }
+
+ # Interpolate params so templates can reference earlier results.
+ raw_params = node_data.get('params') or {}
+ params: Dict[str, Any] = {}
+ for k, v in raw_params.items():
+ if isinstance(v, str):
+ params[k] = WorkflowEngine._interpolate(v, context, results, execution)
+ else:
+ params[k] = v
+
+ timeout = float(node_data.get('timeout_s') or DEFAULT_TIMEOUT)
+ timeout = min(timeout, MAX_TIMEOUT)
+
+ WorkflowEngine._log(
+ execution.id,
+ f"agent {server_id}: {action} {params}",
+ node_id=node.get('id'),
+ )
+
+ result = agent_registry.send_command(
+ server_id=server_id,
+ action=action,
+ params=params,
+ user_id=execution.workflow.user_id if execution.workflow else None,
+ timeout=timeout,
+ )
+
+ # Translate agent_registry's envelope into the engine's
+ # standard {success, output|error} shape so downstream nodes
+ # can branch on it uniformly.
+ if not result.get('success'):
+ on_failure = (node_data.get('on_failure') or 'abort').lower()
+ return {
+ 'success': False,
+ 'error': result.get('error') or 'agent command failed',
+ 'code': result.get('code'),
+ 'critical': on_failure == 'abort',
+ }
+ return {
+ 'success': True,
+ 'output': result.get('data'),
+ 'action': action,
+ 'server_id': server_id,
+ }
+
+ @staticmethod
+ def _execute_capability_gate(node: Dict) -> Dict:
+ """Pass the workflow only if the target server reports every
+ listed capability. A gate failure aborts by default — gates
+ exist precisely to prevent the next step from running on an
+ unsupported host."""
+ from app.services.agent_registry import agent_registry
+
+ node_data = node.get('data', {})
+ try:
+ server_id = WorkflowEngine._resolve_target(node_data)
+ except ValueError as e:
+ return {'success': False, 'error': str(e), 'critical': True}
+
+ require = node_data.get('require') or []
+ if isinstance(require, str):
+ require = [require]
+ require = [str(r).strip() for r in require if str(r).strip()]
+ if not require:
+ return {'success': True, 'message': 'no capabilities required'}
+
+ if server_id is None:
+ # Panel host — every "capability" we ask about is implicitly
+ # available (it's the panel itself). Tighter modelling can
+ # come later; refusing here would break local-only workflows
+ # that want to use the same gate node for clarity.
+ return {'success': True, 'satisfied': require, 'target': 'local'}
+
+ caps = agent_registry.get_capabilities(server_id) or {}
+ missing = [r for r in require if not caps.get(r)]
+ if missing:
+ on_missing = (node_data.get('on_missing') or 'abort').lower()
+ return {
+ 'success': False,
+ 'error': f"target missing capabilities: {', '.join(missing)}",
+ 'missing': missing,
+ 'satisfied': [r for r in require if caps.get(r)],
+ 'critical': on_missing == 'abort',
+ }
+ return {'success': True, 'satisfied': require, 'server_id': server_id}
+
+ @staticmethod
+ def _execute_runtime_gate(node: Dict) -> Dict:
+ """Pass the workflow only if every required runtime is present
+ at >= the requested version. Comparison is naive lexicographic
+ on tuples-of-ints — good enough for "python >= 3.11" style
+ gates without dragging in a semver dependency."""
+ from app.services.agent_registry import agent_registry
+
+ node_data = node.get('data', {})
+ try:
+ server_id = WorkflowEngine._resolve_target(node_data)
+ except ValueError as e:
+ return {'success': False, 'error': str(e), 'critical': True}
+
+ require = node_data.get('require') or {}
+ if not isinstance(require, dict) or not require:
+ return {'success': True, 'message': 'no runtimes required'}
+
+ if server_id is None:
+ # Local panel — we don't track runtime versions for the
+ # panel itself; accept and move on.
+ return {'success': True, 'target': 'local'}
+
+ # agent_registry stores the runtime map alongside capabilities.
+ agent = agent_registry._agents.get(server_id) if hasattr(agent_registry, '_agents') else None
+ runtimes = dict(getattr(agent, 'runtimes', {})) if agent else {}
+
+ unmet = []
+ for name, spec in require.items():
+ actual = runtimes.get(name) or ''
+ if not _runtime_satisfies(actual, str(spec)):
+ unmet.append({'runtime': name, 'required': spec, 'actual': actual or 'not installed'})
+
+ if unmet:
+ return {
+ 'success': False,
+ 'error': 'runtime requirements not met',
+ 'unmet': unmet,
+ 'critical': True,
+ }
+ return {'success': True, 'satisfied': require}
+
# ------------------------------------------------------------------
# Logic If Evaluation
# ------------------------------------------------------------------
diff --git a/frontend/src/components/TargetPicker.jsx b/frontend/src/components/TargetPicker.jsx
new file mode 100644
index 00000000..3a3cfa44
--- /dev/null
+++ b/frontend/src/components/TargetPicker.jsx
@@ -0,0 +1,66 @@
+import { useState, useEffect, useMemo } from 'react';
+import { Server } from 'lucide-react';
+import { api } from '../services/api';
+
+// TargetPicker — a small reusable selector for "local panel host vs.
+// connected agent." Used by the Cron, Cloudflared, and File Manager
+// pages to switch which server an action runs against.
+//
+// `feature` gates the agent list: only agents that report
+// capabilities[feature] === true are shown. Agents that haven't
+// reported capabilities yet (older builds) are filtered out — same
+// pattern as the cron picker.
+//
+// onChange receives `{ kind: 'local' } | { kind: 'agent', server_id, name, allowedPaths }`.
+export default function TargetPicker({ feature, value, onChange, includeLocal = true }) {
+ const [servers, setServers] = useState([]);
+
+ useEffect(() => {
+ let cancelled = false;
+ api.getAvailableServers()
+ .then(data => { if (!cancelled) setServers(Array.isArray(data) ? data : []); })
+ .catch(() => { if (!cancelled) setServers([]); });
+ return () => { cancelled = true; };
+ }, []);
+
+ const eligible = useMemo(() => {
+ return servers.filter(s => {
+ if (s.id === 'local') return false; // handled separately
+ if (s.status !== 'online') return false;
+ if (!feature) return true;
+ return s.capabilities && s.capabilities[feature];
+ });
+ }, [servers, feature]);
+
+ function handleChange(e) {
+ const id = e.target.value;
+ if (id === 'local') {
+ onChange({ kind: 'local' });
+ return;
+ }
+ const s = eligible.find(x => x.id === id);
+ if (!s) return;
+ onChange({
+ kind: 'agent',
+ server_id: s.id,
+ name: s.name || s.hostname || s.id,
+ allowedPaths: s.allowed_paths || [],
+ });
+ }
+
+ const selectValue = value?.kind === 'agent' ? value.server_id : 'local';
+
+ return (
+ <div className="target-picker">
+ <Server size={14} className="target-picker__icon" />
+ <select value={selectValue} onChange={handleChange} className="target-picker__select">
+ {includeLocal && <option value="local">Local (this server)</option>}
+ {eligible.map(s => (
+ <option key={s.id} value={s.id}>
+ {s.name || s.hostname || s.id}
+ </option>
+ ))}
+ </select>
+ </div>
+ );
+}
diff --git a/frontend/src/pages/FileManager.jsx b/frontend/src/pages/FileManager.jsx
index ad34c4e4..533c5d30 100644
--- a/frontend/src/pages/FileManager.jsx
+++ b/frontend/src/pages/FileManager.jsx
@@ -23,8 +23,32 @@ import FileCard from '../components/file-manager/FileCard';
import FileRow from '../components/file-manager/FileRow';
import PreviewDrawer from '../components/file-manager/PreviewDrawer';
import ContextMenu from '../components/file-manager/ContextMenu';
+import TargetPicker from '../components/TargetPicker';
import { TREE_ROOTS, DEFAULT_PINNED, getFileType, formatBytes } from '../components/file-manager/fileTypes';
+// File manager operations that the agent can serve over file:* commands.
+// Anything else (mkdir, delete, rename, copy, chmod, search, disk usage,
+// upload/download) is panel-host-only until the matching agent verbs land.
+const REMOTE_SUPPORTED = new Set(['browse', 'read', 'write']);
+
+function deriveParent(path) {
+ if (!path || path === '/' || path === '') return null;
+ const trimmed = path.replace(/\/+$/, '');
+ const idx = trimmed.lastIndexOf('/');
+ if (idx <= 0) return '/';
+ return trimmed.slice(0, idx);
+}
+
+function unwrapAgentData(res) {
+ // Remote endpoints return the agent payload directly
+ // (RemoteFileService → _agent_result unwraps {data}). Defensive
+ // unwrap covers both shapes for older agent responses.
+ if (res && typeof res === 'object' && 'success' in res && 'data' in res) {
+ return res.data;
+ }
+ return res;
+}
+
const STORAGE = {
sidebar: 'serverkit-fm-sidebar',
treeCollapsed: 'serverkit-fm-tree-collapsed',
@@ -51,6 +75,13 @@ const FILTER_CHIPS = [
];
function FileManager() {
+ // ─── target ──────────────────────────────────────────
+ // Local panel host by default. Switching to an agent re-routes the
+ // browse/read/write verbs through /servers/<id>/files/* and disables
+ // operations the agent can't serve yet.
+ const [target, setTarget] = useState({ kind: 'local' });
+ const isRemote = target.kind === 'agent';
+
// ─── core ────────────────────────────────────────────
const [currentPath, setCurrentPath] = useState('/home');
const [entries, setEntries] = useState([]);
@@ -161,6 +192,54 @@ function FileManager() {
localStorage.setItem(STORAGE.expanded, JSON.stringify([...treeExpanded]));
}, [treeExpanded]);
+ // ─── file API adapter ────────────────────────────────
+ // Routes the three verbs the agent supports through the remote
+ // endpoints when target is an agent; falls back to the panel-local
+ // FileService otherwise. Other ops keep going to panel-local — the
+ // remoteGuard helper short-circuits them with a toast when the user
+ // is on a remote target so we don't accidentally write to the panel
+ // host while they think they're editing a remote server.
+ const fileApi = useMemo(() => ({
+ browse: async (path, hidden) => {
+ if (isRemote) {
+ return unwrapAgentData(await api.browseRemoteFiles(target.server_id, path));
+ }
+ return api.browseFiles(path, hidden);
+ },
+ read: async (path) => {
+ if (isRemote) {
+ return unwrapAgentData(await api.readRemoteFile(target.server_id, path));
+ }
+ return api.readFile(path);
+ },
+ write: async (path, content) => {
+ if (isRemote) {
+ return unwrapAgentData(await api.writeRemoteFile(target.server_id, path, content));
+ }
+ return api.writeFile(path, content);
+ },
+ }), [isRemote, target]);
+
+ const remoteGuard = useCallback((op) => {
+ if (isRemote && !REMOTE_SUPPORTED.has(op)) {
+ toast.error(`${op} is not yet supported on remote agents`);
+ return true;
+ }
+ return false;
+ }, [isRemote, toast]);
+
+ // When the user switches to a remote target, jump to its first
+ // advertised allowed_path so they don't see a "panel /home" view
+ // that doesn't exist on the remote host.
+ useEffect(() => {
+ if (target.kind === 'agent' && Array.isArray(target.allowedPaths) && target.allowedPaths.length > 0) {
+ setCurrentPath(target.allowedPaths[0]);
+ } else if (target.kind === 'local') {
+ setCurrentPath('/home');
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [target.kind, target.server_id]);
+
// ─── load directory ──────────────────────────────────
const loadDirectory = useCallback(async (path) => {
setLoading(true);
@@ -169,16 +248,21 @@ function FileManager() {
setTypeBreakdown(null);
setSelectedPaths(new Set());
try {
- const data = await api.browseFiles(path, showHidden);
- setEntries(data.entries || []);
- setParentPath(data.parent);
- setCurrentPath(data.path);
+ const data = await fileApi.browse(path, showHidden);
+ // Agent file:list returns {path, files: [...]} with a flat
+ // entry shape; panel browseFiles returns {path, parent,
+ // entries: [...]}. Normalize so the UI can keep using
+ // entries/parent.
+ const entriesList = data.entries || data.files || [];
+ setEntries(entriesList);
+ setParentPath(data.parent ?? deriveParent(data.path || path));
+ setCurrentPath(data.path || path);
} catch (error) {
toast.error(`Failed to load directory: ${error.message}`);
} finally {
setLoading(false);
}
- }, [showHidden, toast]);
+ }, [showHidden, toast, fileApi]);
useEffect(() => {
loadDirectory(currentPath);
@@ -245,8 +329,9 @@ function FileManager() {
if (!treeCache.has(path)) {
setTreeLoading((s) => { const n = new Set(s); n.add(path); return n; });
try {
- const data = await api.browseFiles(path, false);
- const folders = (data.entries || []).filter((e) => e.is_dir).map((e) => ({
+ const data = await fileApi.browse(path, false);
+ const entries = data.entries || data.files || [];
+ const folders = entries.filter((e) => e.is_dir).map((e) => ({
path: e.path,
name: e.name,
}));
@@ -258,7 +343,7 @@ function FileManager() {
}
}
setTreeExpanded((s) => { const n = new Set(s); n.add(path); return n; });
- }, [treeExpanded, treeCache]);
+ }, [treeExpanded, treeCache, fileApi]);
// Auto-expand the tree along the current path so the active row is visible.
useEffect(() => {
@@ -279,6 +364,7 @@ function FileManager() {
// ─── search ──────────────────────────────────────────
const handleSearch = async () => {
+ if (remoteGuard('search')) { setSearchResults([]); return; }
if (!searchQuery.trim()) { setSearchResults(null); return; }
setLoading(true);
try {
@@ -322,7 +408,7 @@ function FileManager() {
setEditing(false);
if (entry.is_editable) {
try {
- const data = await api.readFile(entry.path);
+ const data = await fileApi.read(entry.path);
setFileContent(data.content);
} catch (error) {
toast.error(`Failed to read file: ${error.message}`);
@@ -357,7 +443,7 @@ function FileManager() {
const handleSaveFile = async () => {
if (!previewFile) return;
try {
- await api.writeFile(previewFile.path, fileContent);
+ await fileApi.write(previewFile.path, fileContent);
toast.success('File saved');
setEditing(false);
loadDirectory(currentPath);
@@ -368,6 +454,7 @@ function FileManager() {
const handleCreateFile = async () => {
if (!newFileName.trim()) return;
+ if (remoteGuard('create file')) return;
try {
await api.createFile(`${currentPath}/${newFileName}`);
toast.success('File created');
@@ -381,6 +468,7 @@ function FileManager() {
const handleCreateFolder = async () => {
if (!newFolderName.trim()) return;
+ if (remoteGuard('create folder')) return;
try {
await api.createDirectory(`${currentPath}/${newFolderName}`);
toast.success('Folder created');
@@ -404,6 +492,7 @@ function FileManager() {
const handleDelete = (target) => {
const items = Array.isArray(target) ? target : [target];
if (items.length === 0) return;
+ if (remoteGuard('delete')) return;
const message = items.length === 1
? `Delete "${items[0].name}"?${items[0].is_dir ? ' All contents inside will be removed.' : ''}`
: `Delete ${items.length} items? This cannot be undone.`;
@@ -434,6 +523,7 @@ function FileManager() {
const handleRename = async () => {
if (!renameTarget || !newName.trim()) return;
+ if (remoteGuard('rename')) return;
try {
await api.renameFile(renameTarget.path, newName);
toast.success('Renamed');
@@ -448,6 +538,7 @@ function FileManager() {
const handleChangePermissions = async () => {
if (!permissionsTarget || !newPermissions.trim()) return;
+ if (remoteGuard('change permissions')) return;
try {
await api.changeFilePermissions(permissionsTarget.path, newPermissions);
toast.success('Permissions updated');
@@ -475,6 +566,7 @@ function FileManager() {
const uploadFiles = async (files) => {
const fileList = Array.from(files);
if (fileList.length === 0) return;
+ if (remoteGuard('upload')) return;
const queue = fileList.map((f, i) => ({
id: `${Date.now()}-${i}`,
name: f.name,
@@ -668,13 +760,14 @@ function FileManager() {
<p className="page-description">Browse, edit, and manage your server files</p>
</div>
<div className="page-header-actions">
- <Button variant="outline" onClick={() => fileInputRef.current?.click()}>
+ <TargetPicker feature="files" value={target} onChange={setTarget} />
+ <Button variant="outline" onClick={() => fileInputRef.current?.click()} disabled={isRemote}>
<Upload size={16} /> Upload
</Button>
- <Button variant="outline" onClick={() => setShowNewFolderModal(true)}>
+ <Button variant="outline" onClick={() => setShowNewFolderModal(true)} disabled={isRemote}>
<FolderPlus size={16} /> New Folder
</Button>
- <Button onClick={() => setShowNewFileModal(true)}>
+ <Button onClick={() => setShowNewFileModal(true)} disabled={isRemote}>
<FilePlus size={16} /> New File
</Button>
<input
@@ -687,6 +780,13 @@ function FileManager() {
</div>
</div>
+ {isRemote && (
+ <div className="file-manager-target-banner">
+ Browsing on <strong>{target.name}</strong> — read/write only.
+ Mkdir/delete/rename/upload aren&apos;t yet supported on remote agents.
+ </div>
+ )}
+
{uploads.length > 0 && (
<div className="upload-tray">
<div className="upload-tray-header">
diff --git a/frontend/src/pages/ServerDetail.jsx b/frontend/src/pages/ServerDetail.jsx
index faf75261..186c46fc 100644
--- a/frontend/src/pages/ServerDetail.jsx
+++ b/frontend/src/pages/ServerDetail.jsx
@@ -44,9 +44,8 @@ const ServerDetail = () => {
if (!server || server.status !== 'online') return;
try {
const data = await api.getRemoteSystemMetrics(id);
- if (data.success) {
- setMetrics(data.data);
- }
+ // Endpoint returns the metrics payload directly, not a {success,data} envelope.
+ if (data) setMetrics(data);
} catch (err) {
console.error('Failed to load metrics:', err);
}
@@ -56,9 +55,7 @@ const ServerDetail = () => {
if (!server || server.status !== 'online') return;
try {
const data = await api.getRemoteSystemInfo(id);
- if (data.success) {
- setSystemInfo(data.data);
- }
+ if (data) setSystemInfo(data);
} catch (err) {
console.error('Failed to load system info:', err);
}
@@ -412,6 +409,16 @@ const ResourceMeter = ({ label, value, color }) => {
);
};
+// The /servers/<id>/docker/* endpoints return raw arrays from Flask
+// (route extracts result.get('data') before jsonify). The agent envelope's
+// {success, data} shape is gone by the time it reaches the client, so unwrap
+// both forms defensively.
+const unwrapList = (response) => {
+ if (Array.isArray(response)) return response;
+ if (response?.success && Array.isArray(response.data)) return response.data;
+ return [];
+};
+
const DockerTab = ({ serverId, serverStatus }) => {
const [containers, setContainers] = useState([]);
const [images, setImages] = useState([]);
@@ -436,8 +443,8 @@ const DockerTab = ({ serverId, serverStatus }) => {
api.getRemoteImages(serverId)
]);
- if (containersRes.success) setContainers(containersRes.data || []);
- if (imagesRes.success) setImages(imagesRes.data || []);
+ setContainers(unwrapList(containersRes));
+ setImages(unwrapList(imagesRes));
} catch (err) {
console.error('Failed to load Docker data:', err);
} finally {
diff --git a/frontend/src/services/api/servers.js b/frontend/src/services/api/servers.js
index c6d54606..e0c269f5 100644
--- a/frontend/src/services/api/servers.js
+++ b/frontend/src/services/api/servers.js
@@ -199,6 +199,26 @@ export async function toggleRemoteCronJob(serverId, jobId, enabled) {
});
}
+// Remote Files (via agent)
+export async function getRemoteAllowedPaths(serverId) {
+ return this.request(`/servers/${serverId}/files/allowed-paths`);
+}
+
+export async function browseRemoteFiles(serverId, path) {
+ return this.request(`/servers/${serverId}/files/browse?path=${encodeURIComponent(path)}`);
+}
+
+export async function readRemoteFile(serverId, path) {
+ return this.request(`/servers/${serverId}/files/read?path=${encodeURIComponent(path)}`);
+}
+
+export async function writeRemoteFile(serverId, path, content) {
+ return this.request(`/servers/${serverId}/files/write`, {
+ method: 'POST',
+ body: { path, content }
+ });
+}
+
// Remote Cloudflared (Tunnels)
export async function getRemoteCloudflaredStatus(serverId) {
return this.request(`/servers/${serverId}/cloudflared/status`);
diff --git a/frontend/src/styles/pages/_file-manager.scss b/frontend/src/styles/pages/_file-manager.scss
index 054a64c6..cd223410 100644
--- a/frontend/src/styles/pages/_file-manager.scss
+++ b/frontend/src/styles/pages/_file-manager.scss
@@ -1777,3 +1777,32 @@ $drawer-width: 520px;
.file-grid { grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)) !important; }
}
}
+
+.file-manager-target-banner {
+ margin: $space-2 0 $space-3;
+ padding: $space-2 $space-3;
+ border-radius: $radius-md;
+ background: rgba(99, 102, 241, 0.1);
+ color: var(--text-primary);
+ font-size: $text-sm;
+ border: 1px solid rgba(99, 102, 241, 0.25);
+}
+
+.target-picker {
+ display: inline-flex;
+ align-items: center;
+ gap: $space-1;
+ padding: $space-1 $space-2;
+ background: var(--surface);
+ border: 1px solid var(--border);
+ border-radius: $radius-md;
+ .target-picker__select {
+ background: transparent;
+ border: none;
+ color: var(--text-primary);
+ font-size: $text-sm;
+ outline: none;
+ cursor: pointer;
+ }
+ .target-picker__icon { color: var(--text-secondary); }
+}