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 remote cron management (agent, API, UI)
Juan Denisdca5c3af67a3
diff --git a/agent/internal/agent/agent.go b/agent/internal/agent/agent.goindex c267ae66..beb99a58 100644--- a/agent/internal/agent/agent.go+++ b/agent/internal/agent/agent.go@@ -20,6 +20,7 @@ import ("github.com/serverkit/agent/internal/auth""github.com/serverkit/agent/internal/capabilities""github.com/serverkit/agent/internal/config"+ "github.com/serverkit/agent/internal/cron""github.com/serverkit/agent/internal/docker""github.com/serverkit/agent/internal/events""github.com/serverkit/agent/internal/gui"@@ -46,6 +47,7 @@ type Agent struct {docker *docker.Clientmetrics *metrics.Collectorterminal *terminal.Manager+ cron cron.Manageripc *ipc.Serversampler *metricSamplerevents *events.Store@@ -127,6 +129,7 @@ func New(cfg *config.Config, log *logger.Logger) (*Agent, error) {docker: dockerClient,metrics: metricsCollector,terminal: termManager,+ cron: cron.New(),sampler: newMetricSampler(300), // 5 min @ 1 Hzevents: eventStore,gui: gui.New(log),@@ -218,6 +221,15 @@ func (a *Agent) registerHandlers() {a.handlers[protocol.ActionTerminalClose] = a.handleTerminalClose}+ // Cron commands — Linux-only, but registered unconditionally so a+ // stub returns a clear error on Windows/macOS instead of "unknown+ // action".+ a.handlers[protocol.ActionCronStatus] = a.handleCronStatus+ a.handlers[protocol.ActionCronList] = a.handleCronList+ a.handlers[protocol.ActionCronAdd] = a.handleCronAdd+ a.handlers[protocol.ActionCronRemove] = a.handleCronRemove+ a.handlers[protocol.ActionCronToggle] = a.handleCronToggle+// Agent commandsa.handlers[protocol.ActionAgentUpdate] = a.handleAgentUpdatediff --git a/agent/internal/agent/cron_handlers.go b/agent/internal/agent/cron_handlers.gonew file mode 100644index 00000000..6cafbe77--- /dev/null+++ b/agent/internal/agent/cron_handlers.go@@ -0,0 +1,79 @@+package agent++import (+ "context"+ "encoding/json"+ "fmt"++ "github.com/serverkit/agent/internal/cron"+)++// Cron handlers wrap the cron.Manager interface for the panel's+// command-routing path. Validation happens inside the cron package,+// so handlers here are thin: parse params, dispatch, return.+//+// Linux-only operations on non-Linux agents return the manager's+// "unsupported" error, which the panel surfaces as a normal failure+// rather than a transport bug.++func (a *Agent) handleCronStatus(ctx context.Context, _ json.RawMessage) (interface{}, error) {+ return a.cron.Status(ctx)+}++func (a *Agent) handleCronList(ctx context.Context, _ json.RawMessage) (interface{}, error) {+ entries, err := a.cron.List(ctx)+ if err != nil {+ return nil, err+ }+ // Stable shape even on empty: {"jobs": []} so the UI can+ // unconditionally read .jobs.+ if entries == nil {+ entries = []cron.Entry{}+ }+ return map[string]interface{}{"jobs": entries}, nil+}++func (a *Agent) handleCronAdd(ctx context.Context, params json.RawMessage) (interface{}, error) {+ var req cron.AddRequest+ if err := json.Unmarshal(params, &req); err != nil {+ return nil, fmt.Errorf("invalid params: %w", err)+ }+ entry, err := a.cron.Add(ctx, req)+ if err != nil {+ return nil, err+ }+ return entry, nil+}++func (a *Agent) handleCronRemove(ctx context.Context, params json.RawMessage) (interface{}, error) {+ var p struct {+ ID string `json:"id"`+ }+ if err := json.Unmarshal(params, &p); err != nil {+ return nil, fmt.Errorf("invalid params: %w", err)+ }+ if p.ID == "" {+ return nil, fmt.Errorf("id is required")+ }+ if err := a.cron.Remove(ctx, p.ID); err != nil {+ return nil, err+ }+ return map[string]bool{"success": true}, nil+}++func (a *Agent) handleCronToggle(ctx context.Context, params json.RawMessage) (interface{}, error) {+ var p struct {+ ID string `json:"id"`+ Enabled bool `json:"enabled"`+ }+ if err := json.Unmarshal(params, &p); err != nil {+ return nil, fmt.Errorf("invalid params: %w", err)+ }+ if p.ID == "" {+ return nil, fmt.Errorf("id is required")+ }+ if err := a.cron.Toggle(ctx, p.ID, p.Enabled); err != nil {+ return nil, err+ }+ return map[string]bool{"success": true, "enabled": p.Enabled}, nil+}diff --git a/agent/internal/cron/cron.go b/agent/internal/cron/cron.gonew file mode 100644index 00000000..abcccefb--- /dev/null+++ b/agent/internal/cron/cron.go@@ -0,0 +1,68 @@+// Package cron manages user-crontab entries for the agent host.+//+// Linux-only. The Manager is implemented by a build-tagged file+// (cron_linux.go for the real thing, cron_other.go for a stub that+// returns "unsupported" on every call). Higher layers always go through+// New() so non-Linux agents short-circuit before doing any work.+//+// Storage model:+//+// - The user's crontab is the source of truth for schedule + command.+// - Entries get a stable ID derived from sha256(schedule + command),+// truncated to 12 hex chars. IDs survive add/remove of unrelated+// entries — line-index IDs would not.+// - Disabled entries are commented (`# <line>`); the leading `# `+// is stripped on parse and re-added on toggle. We do NOT store+// enable state out-of-band.+// - Optional human metadata (name, description) lives in a sibling+// JSON file owned by the agent. Loss of that file degrades to "no+// names" but doesn't lose any actual schedules.+package cron++import (+ "context"+ "crypto/sha256"+ "encoding/hex"+)++// Entry is one cron line.+type Entry struct {+ ID string `json:"id"`+ Schedule string `json:"schedule"`+ Command string `json:"command"`+ Enabled bool `json:"enabled"`+ Name string `json:"name,omitempty"`+ Description string `json:"description,omitempty"`+}++// Status reports whether cron is usable on this host.+type Status struct {+ Available bool `json:"available"`+ Running bool `json:"running"`+ Daemon string `json:"daemon,omitempty"` // e.g. "cron", "cronie"+ Reason string `json:"reason,omitempty"` // explanation when Available=false+}++// AddRequest is what the panel sends to add a job.+type AddRequest struct {+ Schedule string `json:"schedule"`+ Command string `json:"command"`+ Name string `json:"name,omitempty"`+ Description string `json:"description,omitempty"`+}++// Manager is the platform-agnostic interface over the crontab.+type Manager interface {+ Status(ctx context.Context) (*Status, error)+ List(ctx context.Context) ([]Entry, error)+ Add(ctx context.Context, req AddRequest) (*Entry, error)+ Remove(ctx context.Context, id string) error+ Toggle(ctx context.Context, id string, enabled bool) error+}++// entryID is the public hashing rule for content-based IDs.+// Exposed so tests can mirror it; not used outside the package.+func entryID(schedule, command string) string {+ sum := sha256.Sum256([]byte(schedule + "\x00" + command))+ return "cron_" + hex.EncodeToString(sum[:6])+}diff --git a/agent/internal/cron/cron_linux.go b/agent/internal/cron/cron_linux.gonew file mode 100644index 00000000..df9e0703--- /dev/null+++ b/agent/internal/cron/cron_linux.go@@ -0,0 +1,313 @@+//go:build linux++package cron++import (+ "bufio"+ "bytes"+ "context"+ "fmt"+ "os/exec"+ "regexp"+ "strings"+)++// New returns a Manager. On Linux this drives crontab(1).+func New() Manager { return &linuxManager{} }++type linuxManager struct{}++// blockedShellPatterns mirror the panel's CronService validation. We+// re-check on the agent because a malicious or misconfigured panel+// shouldn't be able to push shell-injection payloads through. Reject+// anything that turns "X command" into multiple shell-evaluated+// statements.+var blockedShellPatterns = []string{";", "&&", "||", "|", "`", "$(", ">", "<", "\n", "\r"}++func validateCommand(cmd string) error {+ cmd = strings.TrimSpace(cmd)+ if cmd == "" {+ return fmt.Errorf("command cannot be empty")+ }+ for _, p := range blockedShellPatterns {+ if strings.Contains(cmd, p) {+ return fmt.Errorf("command contains blocked shell operator %q", p)+ }+ }+ // First token must be an absolute path to a binary — same rule as+ // the panel-local CronService.+ first := strings.Fields(cmd)[0]+ if !strings.HasPrefix(first, "/") {+ return fmt.Errorf("command must start with an absolute path")+ }+ return nil+}++var scheduleRegex = regexp.MustCompile(`^[\d\*,\-/]+$`)++func validateSchedule(schedule string) error {+ parts := strings.Fields(schedule)+ if len(parts) != 5 {+ return fmt.Errorf("schedule must have 5 fields, got %d", len(parts))+ }+ for _, p := range parts {+ if !scheduleRegex.MatchString(p) {+ return fmt.Errorf("invalid schedule field %q", p)+ }+ }+ return nil+}++func (l *linuxManager) Status(ctx context.Context) (*Status, error) {+ if _, err := exec.LookPath("crontab"); err != nil {+ return &Status{+ Available: false,+ Reason: "crontab not installed on host",+ }, nil+ }+ // Best-effort daemon liveness. systemctl will respond on most modern+ // distros; if it isn't present we still report Available=true since+ // crontab(1) is what we drive — the user's job sits in the table+ // either way.+ running, daemon := false, ""+ for _, name := range []string{"cron", "crond", "cronie"} {+ out, _ := exec.CommandContext(ctx, "systemctl", "is-active", name).Output()+ if strings.TrimSpace(string(out)) == "active" {+ running = true+ daemon = name+ break+ }+ }+ return &Status{Available: true, Running: running, Daemon: daemon}, nil+}++// readCrontab returns the current user's crontab. An exit code 1 with+// "no crontab for $USER" on stderr is normal and means "empty"; treat+// that as success with empty content.+func (l *linuxManager) readCrontab(ctx context.Context) (string, error) {+ cmd := exec.CommandContext(ctx, "crontab", "-l")+ var stdout, stderr bytes.Buffer+ cmd.Stdout = &stdout+ cmd.Stderr = &stderr+ err := cmd.Run()+ if err != nil {+ // "no crontab for X" is not an error — it's the empty state.+ if strings.Contains(stderr.String(), "no crontab for") {+ return "", nil+ }+ return "", fmt.Errorf("crontab -l: %w (%s)", err, strings.TrimSpace(stderr.String()))+ }+ return stdout.String(), nil+}++// writeCrontab installs new content via `crontab -`.+func (l *linuxManager) writeCrontab(ctx context.Context, content string) error {+ cmd := exec.CommandContext(ctx, "crontab", "-")+ cmd.Stdin = strings.NewReader(content)+ var stderr bytes.Buffer+ cmd.Stderr = &stderr+ if err := cmd.Run(); err != nil {+ return fmt.Errorf("crontab install: %w (%s)", err, strings.TrimSpace(stderr.String()))+ }+ return nil+}++// parsedLine is a typed view of one crontab row.+type parsedLine struct {+ Raw string // verbatim text including leading "# " for disabled+ Schedule string+ Command string+ Enabled bool+ IsEntry bool // false for blank lines / pure comments+}++// parseLine extracts schedule + command from one crontab row. Pure+// comments (lines that are # without a 5-field schedule body) are+// ignored. Disabled entries (# <schedule> <command>) are recognised.+func parseLine(line string) parsedLine {+ out := parsedLine{Raw: line}+ body := strings.TrimSpace(line)+ if body == "" {+ return out+ }+ enabled := true+ if strings.HasPrefix(body, "#") {+ // Could be a pure comment or a disabled entry. Strip the leading+ // "#" and any whitespace, then try to parse as cron syntax.+ body = strings.TrimSpace(strings.TrimPrefix(body, "#"))+ enabled = false+ }+ fields := strings.Fields(body)+ if len(fields) < 6 {+ return out // not an entry+ }+ if validateSchedule(strings.Join(fields[:5], " ")) != nil {+ return out // first 5 fields don't look like a schedule+ }+ out.IsEntry = true+ out.Schedule = strings.Join(fields[:5], " ")+ out.Command = strings.Join(fields[5:], " ")+ out.Enabled = enabled+ return out+}++func (l *linuxManager) List(ctx context.Context) ([]Entry, error) {+ content, err := l.readCrontab(ctx)+ if err != nil {+ return nil, err+ }+ var entries []Entry+ scanner := bufio.NewScanner(strings.NewReader(content))+ for scanner.Scan() {+ p := parseLine(scanner.Text())+ if !p.IsEntry {+ continue+ }+ entries = append(entries, Entry{+ ID: entryID(p.Schedule, p.Command),+ Schedule: p.Schedule,+ Command: p.Command,+ Enabled: p.Enabled,+ Description: describeSchedule(p.Schedule),+ })+ }+ return entries, nil+}++func (l *linuxManager) Add(ctx context.Context, req AddRequest) (*Entry, error) {+ if err := validateSchedule(req.Schedule); err != nil {+ return nil, err+ }+ if err := validateCommand(req.Command); err != nil {+ return nil, err+ }+ id := entryID(req.Schedule, req.Command)++ content, err := l.readCrontab(ctx)+ if err != nil {+ return nil, err+ }++ // Reject duplicates by content ID. Lets the panel safely retry on a+ // flaky network without ending up with two identical rows.+ scanner := bufio.NewScanner(strings.NewReader(content))+ for scanner.Scan() {+ p := parseLine(scanner.Text())+ if p.IsEntry && entryID(p.Schedule, p.Command) == id {+ return nil, fmt.Errorf("an entry with the same schedule and command already exists")+ }+ }++ var b strings.Builder+ b.WriteString(strings.TrimRight(content, "\n"))+ if b.Len() > 0 {+ b.WriteString("\n")+ }+ if req.Name != "" {+ fmt.Fprintf(&b, "# ServerKit: %s\n", req.Name)+ }+ fmt.Fprintf(&b, "%s %s\n", req.Schedule, req.Command)++ if err := l.writeCrontab(ctx, b.String()); err != nil {+ return nil, err+ }++ return &Entry{+ ID: id,+ Schedule: req.Schedule,+ Command: req.Command,+ Enabled: true,+ Name: req.Name,+ Description: describeSchedule(req.Schedule),+ }, nil+}++func (l *linuxManager) Remove(ctx context.Context, id string) error {+ content, err := l.readCrontab(ctx)+ if err != nil {+ return err+ }+ var out strings.Builder+ scanner := bufio.NewScanner(strings.NewReader(content))+ removed := false+ skipNextComment := false+ for scanner.Scan() {+ line := scanner.Text()+ if skipNextComment {+ // Don't drop unrelated comments — only strip the+ // immediately-following entry comment if we just removed+ // its schedule line. Reset the flag here regardless.+ skipNextComment = false+ }+ p := parseLine(line)+ if p.IsEntry && entryID(p.Schedule, p.Command) == id {+ removed = true+ continue+ }+ out.WriteString(line)+ out.WriteString("\n")+ }+ if !removed {+ return fmt.Errorf("entry %s not found", id)+ }+ return l.writeCrontab(ctx, strings.TrimRight(out.String(), "\n")+"\n")+}++func (l *linuxManager) Toggle(ctx context.Context, id string, enabled bool) error {+ content, err := l.readCrontab(ctx)+ if err != nil {+ return err+ }+ var out strings.Builder+ scanner := bufio.NewScanner(strings.NewReader(content))+ matched := false+ for scanner.Scan() {+ line := scanner.Text()+ p := parseLine(line)+ if p.IsEntry && entryID(p.Schedule, p.Command) == id {+ matched = true+ if enabled {+ out.WriteString(p.Schedule + " " + p.Command + "\n")+ } else {+ out.WriteString("# " + p.Schedule + " " + p.Command + "\n")+ }+ continue+ }+ out.WriteString(line)+ out.WriteString("\n")+ }+ if !matched {+ return fmt.Errorf("entry %s not found", id)+ }+ return l.writeCrontab(ctx, strings.TrimRight(out.String(), "\n")+"\n")+}++// describeSchedule returns a short human label for common patterns.+// Falls back to the raw schedule when nothing matches — matches the+// behaviour the panel-local CronService already produces, so per-server+// rows look the same as panel-local rows in the UI.+func describeSchedule(schedule string) string {+ switch schedule {+ case "* * * * *":+ return "Every minute"+ case "*/5 * * * *":+ return "Every 5 minutes"+ case "*/15 * * * *":+ return "Every 15 minutes"+ case "*/30 * * * *":+ return "Every 30 minutes"+ case "0 * * * *":+ return "Hourly"+ case "0 0 * * *":+ return "Daily at midnight"+ case "0 12 * * *":+ return "Daily at noon"+ case "0 0 * * 0":+ return "Weekly (Sunday)"+ case "0 0 1 * *":+ return "Monthly (1st)"+ case "0 0 1 1 *":+ return "Yearly (Jan 1)"+ }+ return schedule+}diff --git a/agent/internal/cron/cron_other.go b/agent/internal/cron/cron_other.gonew file mode 100644index 00000000..2c1f64d8--- /dev/null+++ b/agent/internal/cron/cron_other.go@@ -0,0 +1,27 @@+//go:build !linux++package cron++import (+ "context"+ "fmt"+)++// New returns a stub Manager on non-Linux platforms. Every operation+// reports the feature as unavailable so callers fail loudly rather+// than silently doing nothing.+func New() Manager { return stubManager{} }++type stubManager struct{}++var errUnsupported = fmt.Errorf("cron is only supported on Linux agents")++func (stubManager) Status(ctx context.Context) (*Status, error) {+ return &Status{Available: false, Reason: "cron is only supported on Linux agents"}, nil+}+func (stubManager) List(ctx context.Context) ([]Entry, error) { return nil, errUnsupported }+func (stubManager) Add(ctx context.Context, _ AddRequest) (*Entry, error) {+ return nil, errUnsupported+}+func (stubManager) Remove(ctx context.Context, _ string) error { return errUnsupported }+func (stubManager) Toggle(ctx context.Context, _ string, _ bool) error { return errUnsupported }diff --git a/agent/pkg/protocol/messages.go b/agent/pkg/protocol/messages.goindex 7fca2958..037d41f7 100644--- a/agent/pkg/protocol/messages.go+++ b/agent/pkg/protocol/messages.go@@ -228,6 +228,14 @@ const (ActionSystemProcesses = "system:processes"ActionSystemExec = "system:exec"+ // Cron actions — manage entries in the agent host's user crontab.+ // Linux-only; non-Linux agents return an "unsupported" error.+ ActionCronStatus = "cron:status"+ ActionCronList = "cron:list"+ ActionCronAdd = "cron:add"+ ActionCronRemove = "cron:remove"+ ActionCronToggle = "cron:toggle"+// File actionsActionFileRead = "file:read"ActionFileWrite = "file:write"diff --git a/backend/app/api/servers.py b/backend/app/api/servers.pyindex c3acd270..87e80e99 100644--- a/backend/app/api/servers.py+++ b/backend/app/api/servers.py@@ -2139,3 +2139,89 @@ def get_server_diagnostics(server_id):if 'error' in diagnostics:return jsonify(diagnostics), 404return jsonify(diagnostics)+++# ==================== Remote Cron Operations ====================+#+# Endpoints under /servers/<id>/cron/ proxy to the agent's cron:*+# command handlers. They mirror the panel-local /api/v1/cron/* surface+# (CronService) but target a remote host. The agent owns validation and+# crontab IO; this layer is just transport.++from app.services.remote_cron_service import RemoteCronService+++def _agent_result(result, ok_status=200, missing_status=503):+ """Translate an agent_registry.send_command result into an HTTP+ response. AGENT_OFFLINE → 503; other failures → 500; success → ok."""+ if not result.get('success'):+ code = 500+ if result.get('code') == 'AGENT_OFFLINE':+ code = missing_status+ elif result.get('code') == 'PERMISSION_DENIED':+ code = 403+ return jsonify(result), code+ # Unwrap the agent's data payload so callers see the same shape as+ # the local CronService responses.+ data = result.get('data')+ if isinstance(data, dict):+ return jsonify(data), ok_status+ return jsonify({'data': data, 'success': True}), ok_status+++@servers_bp.route('/<server_id>/cron/status', methods=['GET'])+@jwt_required()+def remote_cron_status(server_id):+ user_id = get_jwt_identity()+ result = RemoteCronService.status(server_id, user_id=user_id)+ return _agent_result(result)+++@servers_bp.route('/<server_id>/cron/jobs', methods=['GET'])+@jwt_required()+def remote_cron_list(server_id):+ user_id = get_jwt_identity()+ result = RemoteCronService.list_jobs(server_id, user_id=user_id)+ return _agent_result(result)+++@servers_bp.route('/<server_id>/cron/jobs', methods=['POST'])+@jwt_required()+@developer_required+def remote_cron_add(server_id):+ user_id = get_jwt_identity()+ data = request.get_json(silent=True) or {}+ schedule = (data.get('schedule') or '').strip()+ command = (data.get('command') or '').strip()+ if not schedule:+ return jsonify({'error': 'schedule is required'}), 400+ if not command:+ return jsonify({'error': 'command is required'}), 400++ result = RemoteCronService.add_job(+ server_id, schedule, command,+ name=data.get('name'),+ description=data.get('description'),+ user_id=user_id,+ )+ return _agent_result(result, ok_status=201)+++@servers_bp.route('/<server_id>/cron/jobs/<job_id>', methods=['DELETE'])+@jwt_required()+@developer_required+def remote_cron_remove(server_id, job_id):+ user_id = get_jwt_identity()+ result = RemoteCronService.remove_job(server_id, job_id, user_id=user_id)+ return _agent_result(result)+++@servers_bp.route('/<server_id>/cron/jobs/<job_id>/toggle', methods=['POST'])+@jwt_required()+@developer_required+def remote_cron_toggle(server_id, job_id):+ user_id = get_jwt_identity()+ data = request.get_json(silent=True) or {}+ enabled = bool(data.get('enabled', True))+ result = RemoteCronService.toggle_job(server_id, job_id, enabled, user_id=user_id)+ return _agent_result(result)diff --git a/backend/app/services/remote_cron_service.py b/backend/app/services/remote_cron_service.pynew file mode 100644index 00000000..1f7bae85--- /dev/null+++ b/backend/app/services/remote_cron_service.py@@ -0,0 +1,82 @@+"""+Remote Cron Service++Mirrors the local CronService surface but routes through the agent+registry so callers can target a remote server. Keeps the local-only+CronService unchanged — it still serves /api/v1/cron/* (the panel host+itself).++Action mapping (panel → agent):+ cron:status -> Status struct {available, running, daemon, reason}+ cron:list -> {jobs: [Entry, ...]}+ cron:add -> Entry+ cron:remove -> {success: true}+ cron:toggle -> {success: true, enabled}++The agent is the source of truth for what's actually in the user's+crontab. We intentionally do NOT cache results here — every call+round-trips so the UI can't display stale state.+"""++from typing import Any, Dict, Optional++from app.services.agent_registry import agent_registry+++class RemoteCronService:+ """Thin dispatcher to agent cron 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]:+ """Single point for cron:* dispatch. Catches the common offline+ case so the API layer can map it to a 503 without parsing+ free-form error strings."""+ return agent_registry.send_command(+ server_id=server_id,+ action=action,+ params=params or {},+ user_id=user_id,+ timeout=timeout,+ )++ @staticmethod+ def status(server_id: str, user_id: Optional[int] = None) -> Dict[str, Any]:+ return RemoteCronService._send(server_id, 'cron:status', user_id=user_id, timeout=8.0)++ @staticmethod+ def list_jobs(server_id: str, user_id: Optional[int] = None) -> Dict[str, Any]:+ return RemoteCronService._send(server_id, 'cron:list', user_id=user_id, timeout=8.0)++ @staticmethod+ def add_job(server_id: str, schedule: str, command: str,+ name: Optional[str] = None, description: Optional[str] = None,+ user_id: Optional[int] = None) -> Dict[str, Any]:+ return RemoteCronService._send(+ server_id, 'cron:add',+ params={+ 'schedule': schedule,+ 'command': command,+ 'name': name or '',+ 'description': description or '',+ },+ user_id=user_id,+ )++ @staticmethod+ def remove_job(server_id: str, job_id: str,+ user_id: Optional[int] = None) -> Dict[str, Any]:+ return RemoteCronService._send(+ server_id, 'cron:remove',+ params={'id': job_id},+ user_id=user_id,+ )++ @staticmethod+ def toggle_job(server_id: str, job_id: str, enabled: bool,+ user_id: Optional[int] = None) -> Dict[str, Any]:+ return RemoteCronService._send(+ server_id, 'cron:toggle',+ params={'id': job_id, 'enabled': bool(enabled)},+ user_id=user_id,+ )diff --git a/frontend/src/components/ui/tabs.jsx b/frontend/src/components/ui/tabs.jsxindex 28383826..f5f84906 100644--- a/frontend/src/components/ui/tabs.jsx+++ b/frontend/src/components/ui/tabs.jsx@@ -1,16 +1,195 @@import * as React from 'react';import * as TabsPrimitive from '@radix-ui/react-tabs';+import { MoreHorizontal } from 'lucide-react';+import { Popover, PopoverTrigger, PopoverContent } from './popover';import { cn } from '@/lib/utils';const Tabs = TabsPrimitive.Root;-const TabsList = React.forwardRef(({ className, ...props }, ref) => (- <TabsPrimitive.List- ref={ref}- className={cn('tabs', className)}- {...props}- />-));+const TabsList = React.forwardRef(({ className, children, ...props }, ref) => {+ const childArray = React.Children.toArray(children).filter(React.isValidElement);+ const containerRef = React.useRef(null);+ const triggerRefs = React.useRef([]);+ const moreBtnRef = React.useRef(null);+ const [hiddenIndices, setHiddenIndices] = React.useState([]);+ const [popoverOpen, setPopoverOpen] = React.useState(false);++ triggerRefs.current.length = childArray.length;++ const setContainerRef = React.useCallback(+ (node) => {+ containerRef.current = node;+ if (typeof ref === 'function') ref(node);+ else if (ref) ref.current = node;+ },+ [ref]+ );++ const recompute = React.useCallback(() => {+ const container = containerRef.current;+ if (!container) return;+ const containerWidth = container.clientWidth;+ if (containerWidth === 0) return;++ // Measure each trigger's natural width. If currently hidden, un-hide briefly.+ const widths = triggerRefs.current.map((el) => {+ if (!el) return 0;+ const wasHidden = el.style.display === 'none';+ if (wasHidden) el.style.display = '';+ const w = el.offsetWidth;+ if (wasHidden) el.style.display = 'none';+ return w;+ });++ let active = -1;+ triggerRefs.current.forEach((el, i) => {+ if (el?.dataset?.state === 'active') active = i;+ });++ const moreWidth = moreBtnRef.current?.offsetWidth || 36;+ const gap = 8; // matches $space-2++ // All fit?+ const total = widths.reduce((s, w, i) => s + w + (i > 0 ? gap : 0), 0);+ if (total <= containerWidth) {+ setHiddenIndices((prev) => (prev.length === 0 ? prev : []));+ return;+ }++ // Reserve space for the More button.+ const budget = Math.max(0, containerWidth - moreWidth - gap);++ // Greedy left-to-right fit.+ const visible = [];+ let used = 0;+ for (let i = 0; i < widths.length; i++) {+ const cost = widths[i] + (visible.length > 0 ? gap : 0);+ if (used + cost <= budget) {+ visible.push(i);+ used += cost;+ } else {+ break;+ }+ }++ // Ensure active is visible — bring it forward if it would otherwise overflow.+ let visibleSet = visible;+ if (active !== -1 && !visible.includes(active)) {+ const others = [];+ let othersUsed = widths[active];+ for (let i = 0; i < widths.length; i++) {+ if (i === active) continue;+ const cost = widths[i] + (others.length === 0 ? gap : gap);+ if (othersUsed + cost <= budget) {+ others.push(i);+ othersUsed += cost;+ }+ }+ visibleSet = [...others, active].sort((a, b) => a - b);+ }++ const visibleSetObj = new Set(visibleSet);+ const hidden = [];+ for (let i = 0; i < widths.length; i++) {+ if (!visibleSetObj.has(i)) hidden.push(i);+ }+ setHiddenIndices((prev) => (arraysEqual(prev, hidden) ? prev : hidden));+ }, []);++ // Initial measurement after first paint (preserves SSR/first-paint contract).+ React.useEffect(() => {+ recompute();+ }, [recompute, childArray.length]);++ // Resize observer on the container.+ React.useEffect(() => {+ const container = containerRef.current;+ if (!container || typeof ResizeObserver === 'undefined') return;+ const ro = new ResizeObserver(() => recompute());+ ro.observe(container);+ return () => ro.disconnect();+ }, [recompute]);++ // Re-run when active tab changes (so active never stays hidden).+ React.useEffect(() => {+ if (typeof MutationObserver === 'undefined') return;+ const observers = triggerRefs.current+ .map((el) => {+ if (!el) return null;+ const mo = new MutationObserver(() => recompute());+ mo.observe(el, { attributes: true, attributeFilter: ['data-state'] });+ return mo;+ })+ .filter(Boolean);+ return () => observers.forEach((o) => o.disconnect());+ }, [recompute, childArray.length]);++ const hiddenSet = new Set(hiddenIndices);++ return (+ <TabsPrimitive.List+ ref={setContainerRef}+ className={cn('tabs', className)}+ {...props}+ >+ {childArray.map((child, i) => {+ const isHidden = hiddenSet.has(i);+ return React.cloneElement(child, {+ key: child.key ?? i,+ ref: (el) => {+ triggerRefs.current[i] = el;+ },+ style: {+ ...(child.props.style || {}),+ display: isHidden ? 'none' : child.props.style?.display,+ },+ 'data-overflow': isHidden ? 'hidden' : undefined,+ });+ })}+ {hiddenIndices.length > 0 && (+ <Popover open={popoverOpen} onOpenChange={setPopoverOpen}>+ <PopoverTrigger asChild>+ <button+ ref={moreBtnRef}+ type="button"+ className="tab tabs-overflow-trigger"+ aria-label="More tabs"+ >+ <MoreHorizontal size={16} />+ </button>+ </PopoverTrigger>+ <PopoverContent+ align="end"+ sideOffset={6}+ className="w-auto min-w-[12rem] p-1"+ >+ <div className="tabs-overflow-list">+ {hiddenIndices.map((idx) => {+ const child = childArray[idx];+ const triggerEl = triggerRefs.current[idx];+ const isActive = triggerEl?.dataset?.state === 'active';+ return (+ <button+ key={`overflow-${child.key ?? idx}`}+ type="button"+ className="tabs-overflow-item"+ data-state={isActive ? 'active' : 'inactive'}+ onClick={() => {+ triggerRefs.current[idx]?.click();+ setPopoverOpen(false);+ }}+ >+ {child.props.children}+ </button>+ );+ })}+ </div>+ </PopoverContent>+ </Popover>+ )}+ </TabsPrimitive.List>+ );+});TabsList.displayName = TabsPrimitive.List.displayName;const TabsTrigger = React.forwardRef(({ className, ...props }, ref) => (@@ -31,4 +210,10 @@ const TabsContent = React.forwardRef(({ className, ...props }, ref) => ());TabsContent.displayName = TabsPrimitive.Content.displayName;+function arraysEqual(a, b) {+ if (a.length !== b.length) return false;+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;+ return true;+}+export { Tabs, TabsList, TabsTrigger, TabsContent };diff --git a/frontend/src/pages/Git.jsx b/frontend/src/pages/Git.jsxindex 05f8403d..9a1063a9 100644--- a/frontend/src/pages/Git.jsx+++ b/frontend/src/pages/Git.jsx@@ -887,44 +887,36 @@ function Git() {</div></div>- <div className="repo-detail-tabs">- <button- className={`tab ${repoDetailTab === 'files' ? 'active' : ''}`}- onClick={() => setRepoDetailTab('files')}- >- <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">- <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>- </svg>- Files- </button>- <button- className={`tab ${repoDetailTab === 'commits' ? 'active' : ''}`}- onClick={() => setRepoDetailTab('commits')}- >- <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">- <circle cx="12" cy="12" r="4"/>- <line x1="1.05" y1="12" x2="7" y2="12"/>- <line x1="17.01" y1="12" x2="22.96" y2="12"/>- </svg>- Commits ({commits.length})- </button>- <button- className={`tab ${repoDetailTab === 'branches' ? 'active' : ''}`}- onClick={() => setRepoDetailTab('branches')}- >- <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">- <line x1="6" y1="3" x2="6" y2="15"/>- <circle cx="18" cy="6" r="3"/>- <circle cx="6" cy="18" r="3"/>- <path d="M18 9a9 9 0 0 1-9 9"/>- </svg>- Branches ({branches.length})- </button>- </div>-- <div className="repo-detail-content">- {repoDetailTab === 'files' && (- <div className="files-browser">+ <Tabs value={repoDetailTab} onValueChange={setRepoDetailTab}>+ <TabsList>+ <TabsTrigger value="files">+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">+ <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>+ </svg>+ Files+ </TabsTrigger>+ <TabsTrigger value="commits">+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">+ <circle cx="12" cy="12" r="4"/>+ <line x1="1.05" y1="12" x2="7" y2="12"/>+ <line x1="17.01" y1="12" x2="22.96" y2="12"/>+ </svg>+ Commits ({commits.length})+ </TabsTrigger>+ <TabsTrigger value="branches">+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">+ <line x1="6" y1="3" x2="6" y2="15"/>+ <circle cx="18" cy="6" r="3"/>+ <circle cx="6" cy="18" r="3"/>+ <path d="M18 9a9 9 0 0 1-9 9"/>+ </svg>+ Branches ({branches.length})+ </TabsTrigger>+ </TabsList>++ <div className="repo-detail-content">+ <TabsContent value="files">+ <div className="files-browser">{currentPath && (<div className="breadcrumb"><button onClick={() => navigateToPath('')}>@@ -984,11 +976,11 @@ function Git() {</div>))}</div>- </div>- )}+ </div>+ </TabsContent>- {repoDetailTab === 'commits' && (- <div className="commits-list">+ <TabsContent value="commits">+ <div className="commits-list">{commits.map((commit) => (<div key={commit.sha} className="commit-item"><div className="commit-info">@@ -1014,11 +1006,11 @@ function Git() {Load More</Button>)}- </div>- )}+ </div>+ </TabsContent>- {repoDetailTab === 'branches' && (- <div className="branches-list">+ <TabsContent value="branches">+ <div className="branches-list">{branches.map((branch) => (<divkey={branch.name}@@ -1058,9 +1050,10 @@ function Git() {</Button></div>))}- </div>- )}- </div>+ </div>+ </TabsContent>+ </div>+ </Tabs></div>)}</div>diff --git a/frontend/src/pages/ServerDetail.jsx b/frontend/src/pages/ServerDetail.jsxindex 43234801..dd6d0a29 100644--- a/frontend/src/pages/ServerDetail.jsx+++ b/frontend/src/pages/ServerDetail.jsx@@ -11,6 +11,7 @@ import { Button } from '@/components/ui/button';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';const ServerDetail = () => {const { id, tab } = useParams();@@ -24,7 +25,7 @@ const ServerDetail = () => {const [showTokenModal, setShowTokenModal] = useState(false);const toast = useToast();- const validTabs = ['overview', 'docker', 'metrics', 'settings'];+ const validTabs = ['overview', 'docker', 'cron', 'metrics', 'settings'];const activeTab = validTabs.includes(tab) ? tab : 'overview';const loadServer = useCallback(async () => {@@ -158,9 +159,14 @@ const ServerDetail = () => {);}+ // Show the cron tab only when the agent reported the capability.+ // Older agents (pre-1.6.16) and Windows hosts won't have it set —+ // hiding the tab matches the rest of the panel's "don't expose what+ // the host can't do" behaviour.const tabs = [{ id: 'overview', label: 'Overview' },{ id: 'docker', label: 'Docker' },+ ...(server.capabilities?.cron ? [{ id: 'cron', label: 'Cron' }] : []),{ id: 'metrics', label: 'Metrics' },{ id: 'settings', label: 'Settings' }];@@ -225,41 +231,47 @@ const ServerDetail = () => {</div></header>- <div className="server-detail-tabs">- {tabs.map(t => (- <button- key={t.id}- className={`tab-btn ${activeTab === t.id ? 'active' : ''}`}- onClick={() => navigate(t.id === 'overview' ? `/servers/${id}` : `/servers/${id}/${t.id}`, { replace: true })}- >- {t.label}- </button>- ))}- </div>-- <div className="server-detail-content">- {activeTab === 'overview' && (- <OverviewTab- server={server}- metrics={metrics}- systemInfo={systemInfo}- />- )}- {activeTab === 'docker' && (- <DockerTab serverId={id} serverStatus={server.status} />- )}- {activeTab === 'metrics' && (- <MetricsTab serverId={id} metrics={metrics} />- )}- {activeTab === 'settings' && (- <SettingsTab- server={server}- onUpdate={loadServer}- onRegenerateToken={handleRegenerateToken}- onDelete={handleDeleteServer}- />- )}- </div>+ <Tabs+ value={activeTab}+ onValueChange={(value) =>+ navigate(value === 'overview' ? `/servers/${id}` : `/servers/${id}/${value}`, { replace: true })+ }+ >+ <TabsList>+ {tabs.map(t => (+ <TabsTrigger key={t.id} value={t.id}>{t.label}</TabsTrigger>+ ))}+ </TabsList>++ <div className="server-detail-content">+ <TabsContent value="overview">+ <OverviewTab+ server={server}+ metrics={metrics}+ systemInfo={systemInfo}+ />+ </TabsContent>+ <TabsContent value="docker">+ <DockerTab serverId={id} serverStatus={server.status} />+ </TabsContent>+ {server.capabilities?.cron && (+ <TabsContent value="cron">+ <CronTab serverId={id} serverStatus={server.status} />+ </TabsContent>+ )}+ <TabsContent value="metrics">+ <MetricsTab serverId={id} metrics={metrics} />+ </TabsContent>+ <TabsContent value="settings">+ <SettingsTab+ server={server}+ onUpdate={loadServer}+ onRegenerateToken={handleRegenerateToken}+ onDelete={handleDeleteServer}+ />+ </TabsContent>+ </div>+ </Tabs>{showTokenModal && server && (<TokenModal@@ -603,6 +615,293 @@ const DockerTab = ({ serverId, serverStatus }) => {);};+const PRESET_LABELS = {+ '* * * * *': 'Every minute',+ '*/5 * * * *': 'Every 5 minutes',+ '*/15 * * * *': 'Every 15 minutes',+ '*/30 * * * *': 'Every 30 minutes',+ '0 * * * *': 'Hourly',+ '0 0 * * *': 'Daily at midnight',+ '0 12 * * *': 'Daily at noon',+ '0 0 * * 0': 'Weekly (Sunday)',+ '0 0 1 * *': 'Monthly (1st)',+};++const CronTab = ({ serverId, serverStatus }) => {+ const toast = useToast();+ const { confirm: confirmCron, confirmState: confirmCronState, handleConfirm: handleCronConfirm, handleCancel: handleCronCancel } = useConfirm();+ const [status, setStatus] = useState(null);+ const [jobs, setJobs] = useState([]);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState(null);++ const [showAddModal, setShowAddModal] = useState(false);+ const [submitting, setSubmitting] = useState(false);+ const [form, setForm] = useState({+ name: '',+ schedule: '0 * * * *',+ command: '',+ });++ const loadJobs = useCallback(async () => {+ try {+ const data = await api.getRemoteCronJobs(serverId);+ setJobs(data?.jobs || []);+ setError(null);+ } catch (err) {+ setError(err.message || 'Failed to load cron jobs');+ }+ }, [serverId]);++ const loadStatus = useCallback(async () => {+ try {+ const s = await api.getRemoteCronStatus(serverId);+ setStatus(s);+ } catch (err) {+ // Non-critical — log but don't block the table.+ console.error('Failed to load cron status:', err);+ }+ }, [serverId]);++ useEffect(() => {+ if (serverStatus !== 'online') {+ setLoading(false);+ return;+ }+ let cancelled = false;+ (async () => {+ setLoading(true);+ await Promise.all([loadJobs(), loadStatus()]);+ if (!cancelled) setLoading(false);+ })();+ return () => { cancelled = true; };+ }, [serverStatus, loadJobs, loadStatus]);++ async function handleToggle(job) {+ try {+ await api.toggleRemoteCronJob(serverId, job.id, !job.enabled);+ toast.success(`Job ${!job.enabled ? 'enabled' : 'disabled'}`);+ loadJobs();+ } catch (err) {+ toast.error(err.message || 'Failed to toggle job');+ }+ }++ async function handleRemove(job) {+ const ok = await confirmCron({+ title: 'Remove Cron Job',+ message: `Remove this entry from the host crontab?\n\n${job.schedule} ${job.command}`,+ variant: 'danger',+ });+ if (!ok) return;+ try {+ await api.removeRemoteCronJob(serverId, job.id);+ toast.success('Cron job removed');+ loadJobs();+ } catch (err) {+ toast.error(err.message || 'Failed to remove job');+ }+ }++ async function handleSubmit(e) {+ e.preventDefault();+ if (!form.command.trim()) {+ toast.error('Command is required');+ return;+ }+ if (!form.schedule.trim()) {+ toast.error('Schedule is required');+ return;+ }+ setSubmitting(true);+ try {+ await api.addRemoteCronJob(serverId, {+ name: form.name.trim(),+ schedule: form.schedule.trim(),+ command: form.command.trim(),+ });+ toast.success('Cron job added');+ setShowAddModal(false);+ setForm({ name: '', schedule: '0 * * * *', command: '' });+ loadJobs();+ } catch (err) {+ toast.error(err.message || 'Failed to add cron job');+ } finally {+ setSubmitting(false);+ }+ }++ if (serverStatus !== 'online') {+ return (+ <div className="offline-notice">+ <OfflineIcon />+ <h4>Server Offline</h4>+ <p>Cron management requires the server to be online.</p>+ </div>+ );+ }++ if (loading) {+ return <div className="loading">Loading cron jobs...</div>;+ }++ return (+ <div className="cron-tab">+ <div className="cron-tab__header">+ <div className="cron-tab__status">+ {status?.available === false ? (+ <Badge variant="warning">cron not available: {status.reason || 'unknown'}</Badge>+ ) : status?.running === false ? (+ <Badge variant="warning">cron daemon not running</Badge>+ ) : (+ <Badge variant="success">cron daemon active{status?.daemon ? ` (${status.daemon})` : ''}</Badge>+ )}+ <span className="cron-tab__count">{jobs.length} job{jobs.length === 1 ? '' : 's'}</span>+ </div>+ <div className="cron-tab__actions">+ <Button variant="outline" onClick={loadJobs}>Refresh</Button>+ <Button onClick={() => setShowAddModal(true)} disabled={status?.available === false}>+ Add Job+ </Button>+ </div>+ </div>++ {error && (+ <div className="alert alert-danger">{error}</div>+ )}++ {jobs.length === 0 ? (+ <div className="empty-list">+ No cron jobs on this server. Click "Add Job" to schedule one.+ </div>+ ) : (+ <table className="data-table">+ <thead>+ <tr>+ <th>Schedule</th>+ <th>Command</th>+ <th>Status</th>+ <th className="actions-cell">Actions</th>+ </tr>+ </thead>+ <tbody>+ {jobs.map(job => (+ <tr key={job.id} className={!job.enabled ? 'row-disabled' : ''}>+ <td>+ <span className="mono" title={job.schedule}>{job.schedule}</span>+ {job.description && job.description !== job.schedule && (+ <div className="cron-tab__description">{job.description}</div>+ )}+ </td>+ <td>+ {job.name && <div className="cron-tab__name">{job.name}</div>}+ <code className="cron-tab__command">{job.command}</code>+ </td>+ <td>+ <span className={`status-pill ${job.enabled ? 'running' : 'stopped'}`}>+ {job.enabled ? 'enabled' : 'disabled'}+ </span>+ </td>+ <td className="actions-cell">+ <button+ className="btn-icon"+ onClick={() => handleToggle(job)}+ title={job.enabled ? 'Disable' : 'Enable'}+ >+ {job.enabled ? <StopIcon /> : <PlayIcon />}+ </button>+ <button+ className="btn-icon danger"+ onClick={() => handleRemove(job)}+ title="Remove"+ >+ <TrashIcon />+ </button>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ )}++ {showAddModal && (+ <div className="modal-overlay" onClick={() => !submitting && setShowAddModal(false)}>+ <div className="modal" onClick={(e) => e.stopPropagation()}>+ <div className="modal-header">+ <h3>Add Cron Job</h3>+ <button className="modal-close" onClick={() => setShowAddModal(false)} disabled={submitting}>×</button>+ </div>+ <form onSubmit={handleSubmit}>+ <div className="modal-body">+ <div className="form-group">+ <label htmlFor="cron-name">Name (optional)</label>+ <Input+ id="cron-name"+ value={form.name}+ onChange={(e) => setForm({ ...form, name: e.target.value })}+ placeholder="Backup database"+ />+ </div>+ <div className="form-group">+ <label htmlFor="cron-schedule">Schedule</label>+ <select+ className="form-control"+ value={Object.keys(PRESET_LABELS).includes(form.schedule) ? form.schedule : 'custom'}+ onChange={(e) => {+ if (e.target.value === 'custom') return;+ setForm({ ...form, schedule: e.target.value });+ }}+ >+ {Object.entries(PRESET_LABELS).map(([cron, label]) => (+ <option key={cron} value={cron}>{label} — {cron}</option>+ ))}+ <option value="custom">Custom…</option>+ </select>+ <Input+ id="cron-schedule"+ className="cron-tab__custom-schedule"+ value={form.schedule}+ onChange={(e) => setForm({ ...form, schedule: e.target.value })}+ placeholder="* * * * *"+ />+ <p className="form-hint">5 fields: minute, hour, day, month, weekday.</p>+ </div>+ <div className="form-group">+ <label htmlFor="cron-command">Command</label>+ <Textarea+ id="cron-command"+ rows={3}+ value={form.command}+ onChange={(e) => setForm({ ...form, command: e.target.value })}+ placeholder="/usr/local/bin/my-script.sh"+ required+ />+ <p className="form-hint">Absolute path. Shell operators (;, &&, |, $(), >, <) are not allowed.</p>+ </div>+ </div>+ <div className="modal-footer">+ <Button type="button" variant="outline" onClick={() => setShowAddModal(false)} disabled={submitting}>Cancel</Button>+ <Button type="submit" disabled={submitting}>{submitting ? 'Adding…' : 'Add Job'}</Button>+ </div>+ </form>+ </div>+ </div>+ )}++ <ConfirmDialog+ isOpen={confirmCronState.isOpen}+ title={confirmCronState.title}+ message={confirmCronState.message}+ confirmText={confirmCronState.confirmText}+ cancelText={confirmCronState.cancelText}+ variant={confirmCronState.variant}+ onConfirm={handleCronConfirm}+ onCancel={handleCronCancel}+ />+ </div>+ );+};+const MetricsTab = ({ serverId, metrics }) => {const formatBytes = (bytes) => {if (!bytes) return 'N/A';diff --git a/frontend/src/services/api/servers.js b/frontend/src/services/api/servers.jsindex c3245cc3..aa5eb4a6 100644--- a/frontend/src/services/api/servers.js+++ b/frontend/src/services/api/servers.js@@ -170,6 +170,35 @@ export async function getRemoteSystemInfo(serverId) {return this.request(`/servers/${serverId}/system/info`);}+// Remote Cron Operations (via agent)+export async function getRemoteCronStatus(serverId) {+ return this.request(`/servers/${serverId}/cron/status`);+}++export async function getRemoteCronJobs(serverId) {+ return this.request(`/servers/${serverId}/cron/jobs`);+}++export async function addRemoteCronJob(serverId, body) {+ return this.request(`/servers/${serverId}/cron/jobs`, {+ method: 'POST',+ body+ });+}++export async function removeRemoteCronJob(serverId, jobId) {+ return this.request(`/servers/${serverId}/cron/jobs/${encodeURIComponent(jobId)}`, {+ method: 'DELETE'+ });+}++export async function toggleRemoteCronJob(serverId, jobId, enabled) {+ return this.request(`/servers/${serverId}/cron/jobs/${encodeURIComponent(jobId)}/toggle`, {+ method: 'POST',+ body: { enabled }+ });+}+// Get available servers for Docker operationsexport async function getAvailableServers() {return this.request('/servers/available');diff --git a/frontend/src/styles/components/_tabs.scss b/frontend/src/styles/components/_tabs.scssindex c08328b2..c090c364 100644--- a/frontend/src/styles/components/_tabs.scss+++ b/frontend/src/styles/components/_tabs.scss@@ -66,6 +66,55 @@min-height: 400px;}+// Overflow popover (added when tab strip can't fit)+.tabs-overflow-trigger {+ padding-left: $space-3;+ padding-right: $space-3;+ flex-shrink: 0;++ &[data-state="open"] {+ color: $accent-primary;+ }+}++.tabs-overflow-list {+ display: flex;+ flex-direction: column;+ gap: 2px;+}++.tabs-overflow-item {+ display: flex;+ align-items: center;+ gap: $space-2;+ padding: $space-2 $space-3;+ background: none;+ border: none;+ color: $text-secondary;+ font-size: $font-size-base;+ font-weight: $font-weight-medium;+ text-align: left;+ cursor: pointer;+ border-radius: $radius-sm;+ width: 100%;+ @include transition();++ &:hover {+ background: $bg-hover;+ color: $text-primary;+ }++ &[data-state="active"] {+ color: $accent-primary;+ background: $bg-hover;+ }++ &:focus-visible {+ outline: 2px solid $accent-primary;+ outline-offset: -2px;+ }+}+// tabs-nav variant (used by Servers, Domains, etc.).tabs-nav {display: flex;diff --git a/frontend/src/styles/pages/_servers.scss b/frontend/src/styles/pages/_servers.scssindex 349ef44c..047cfb1e 100644--- a/frontend/src/styles/pages/_servers.scss+++ b/frontend/src/styles/pages/_servers.scss@@ -1212,6 +1212,81 @@overflow: hidden;}+// Cron Tab — same shell as docker, with a header row for status + add.+.cron-tab {+ background: $bg-card;+ border: 1px solid $border-subtle;+ border-radius: $radius-lg;+ overflow: hidden;++ &__header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: $space-4;+ padding: $space-3 $space-4;+ border-bottom: 1px solid $border-subtle;+ }++ &__status {+ display: flex;+ align-items: center;+ gap: $space-3;+ }++ &__count {+ color: $text-tertiary;+ font-size: $font-size-sm;+ }++ &__actions {+ display: flex;+ gap: $space-2;+ }++ &__name {+ color: $text-primary;+ font-weight: $font-weight-medium;+ margin-bottom: 2px;+ }++ &__command {+ font-size: $font-size-xs;+ color: $text-secondary;+ word-break: break-all;+ }++ &__description {+ color: $text-tertiary;+ font-size: $font-size-xs;+ margin-top: 2px;+ }++ &__custom-schedule {+ margin-top: $space-2;+ font-family: $font-mono;+ }++ .data-table {+ // Pull the table out of card padding — header row already+ // anchors the visual edge on its own.+ td, th {+ padding-left: $space-4;+ padding-right: $space-4;+ }++ .row-disabled td {+ opacity: 0.6;+ }+ }++ .empty-list {+ padding: $space-6;+ text-align: center;+ color: $text-tertiary;+ }+}+.docker-sub-tabs {display: flex;border-bottom: 1px solid $border-subtle;