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.

feat(cron): completion — run history, project scope, cwd/run-as (plan 34)

Juan Denis38c281d274a7
diff --git a/backend/app/api/cron.py b/backend/app/api/cron.py
index 94b361a7..2891f4ef 100644
--- a/backend/app/api/cron.py
+++ b/backend/app/api/cron.py
@@ -1,3 +1,5 @@
+# Bucket: PER-APP (plan 29 #9). Per-app cron routes gate via the app-grant
+# family (can_access_app / can_edit_app). See docs/WORKSPACE_SCOPING.md.
"""
Cron Job Management API
@@ -6,12 +8,66 @@ Endpoints for managing scheduled tasks and cron jobs.
from flask import Blueprint, request, jsonify
-from app.middleware.rbac import admin_required, viewer_required
+from app.middleware.rbac import admin_required, viewer_required, require_app_member
from app.services.cron_service import CronService
cron_bp = Blueprint('cron', __name__)
+_INVALID_APP = object() # sentinel: an application_id was given but doesn't exist
+
+
+def _validate_application_id(raw):
+ """Normalize an incoming application_id.
+
+ Returns None (no association), an int (validated, app exists), or the
+ _INVALID_APP sentinel when a non-empty value doesn't resolve to an app.
+ """
+ if raw in (None, ''):
+ return None
+ from app.models import Application
+ try:
+ aid = int(raw)
+ except (TypeError, ValueError):
+ return _INVALID_APP
+ return aid if Application.query.get(aid) else _INVALID_APP
+
+
+def _attach_attribution(jobs):
+ """Resolve each job's `application_id` into live app/workspace/project names.
+
+ Scope is derived, never duplicated: a job only stores `application_id`, and
+ the workspace/project it belongs to are resolved through the app at read
+ time (Decision 3). Jobs with no association are left untouched (System
+ bucket).
+ """
+ from app.models import Application, Workspace
+
+ ids = {int(j['application_id']) for j in jobs
+ if j.get('application_id') not in (None, '')}
+ if not ids:
+ return jobs
+
+ apps = {a.id: a for a in Application.query.filter(Application.id.in_(ids)).all()}
+ ws_ids = {a.workspace_id for a in apps.values() if a.workspace_id}
+ workspaces = ({w.id: w for w in Workspace.query.filter(Workspace.id.in_(ws_ids)).all()}
+ if ws_ids else {})
+
+ for job in jobs:
+ aid = job.get('application_id')
+ app = apps.get(int(aid)) if aid not in (None, '') else None
+ if not app:
+ continue
+ job['app'] = {'id': app.id, 'name': app.name, 'type': app.app_type}
+ if app.workspace_id and app.workspace_id in workspaces:
+ w = workspaces[app.workspace_id]
+ job['workspace'] = {'id': w.id, 'name': w.name}
+ if app.project_id:
+ job['project'] = {'id': app.project_id,
+ 'name': app.project.name if app.project else None}
+ return jobs
+
+
@cron_bp.route('/status', methods=['GET'])
@viewer_required
def get_status():
@@ -23,8 +79,10 @@ def get_status():
@cron_bp.route('/jobs', methods=['GET'])
@viewer_required
def list_jobs():
- """List all cron jobs."""
+ """List all cron jobs (admin surface), with live app/workspace attribution."""
result = CronService.list_jobs()
+ if result.get('jobs'):
+ _attach_attribution(result['jobs'])
return jsonify(result)
@@ -45,11 +103,16 @@ def create_job():
if not command:
return jsonify({'success': False, 'error': 'Command is required'}), 400
+ application_id = _validate_application_id(data.get('application_id'))
+ if application_id is _INVALID_APP:
+ return jsonify({'success': False, 'error': 'Application not found'}), 400
+
result = CronService.add_job(
schedule=schedule,
command=command,
name=name,
- description=description
+ description=description,
+ application_id=application_id,
)
if result.get('success'):
@@ -63,12 +126,21 @@ def update_job(job_id):
"""Update a cron job."""
data = request.get_json()
+ set_application = 'application_id' in data
+ application_id = None
+ if set_application:
+ application_id = _validate_application_id(data.get('application_id'))
+ if application_id is _INVALID_APP:
+ return jsonify({'success': False, 'error': 'Application not found'}), 400
+
result = CronService.update_job(
job_id=job_id,
name=data.get('name'),
command=data.get('command'),
schedule=data.get('schedule'),
- description=data.get('description')
+ description=data.get('description'),
+ application_id=application_id,
+ _set_application=set_application,
)
if result.get('success'):
@@ -118,3 +190,138 @@ def get_presets():
"""Get available schedule presets."""
result = CronService.get_presets()
return jsonify(result)
+
+
+@cron_bp.route('/jobs/for-app/<int:app_id>', methods=['GET'])
+@require_app_member(min_role='viewer', arg='app_id')
+def jobs_for_app(app_id):
+ """Read-only list of the jobs attributed to an application.
+
+ Gated by workspace membership (member+ of the app's workspace, or admin) —
+ NOT @admin_required. This is the member-facing surface (Decision 2): workspace
+ members see the scheduled tasks that keep their app healthy, without being
+ handed the keys to the host crontab. No mutation routes live at this gate,
+ and the raw host command is intentionally omitted.
+ """
+ jobs = CronService.jobs_for_application(app_id)
+ visible = [{
+ 'id': j['id'],
+ 'name': j.get('name'),
+ 'schedule': j.get('schedule'),
+ 'schedule_human': j.get('schedule_human'),
+ 'next_run': j.get('next_run'),
+ 'enabled': j.get('enabled', True),
+ 'last_run': j.get('last_run'),
+ 'last_status': j.get('last_status'),
+ } for j in jobs]
+ return jsonify({'success': True, 'jobs': visible, 'count': len(visible)})
+
+
+@cron_bp.route('/jobs/<job_id>/track', methods=['POST'])
+@admin_required
+def toggle_tracking(job_id):
+ """Enable/disable run tracking for a job (rewrites its crontab line with the
+ serverkit-cron-run shim; disabling restores the bare command)."""
+ data = request.get_json(silent=True) or {}
+ enabled = bool(data.get('enabled', True))
+ result = CronService.set_tracking(job_id, enabled)
+ if result.get('success'):
+ # Persist the optional per-job "alert on failure" flag alongside.
+ if 'alert_on_failure' in data:
+ meta = CronService._load_jobs_metadata()
+ if job_id in meta.get('jobs', {}):
+ meta['jobs'][job_id]['alert_on_failure'] = bool(data['alert_on_failure'])
+ CronService._save_jobs_metadata(meta)
+ return jsonify(result)
+ return jsonify(result), 400
+
+
+@cron_bp.route('/jobs/<job_id>/runs', methods=['GET'])
+@admin_required
+def job_runs(job_id):
+ """Recent run history + success-rate for a job (admin surface)."""
+ from app.services.cron_run_service import CronRunService
+ return jsonify({
+ 'success': True,
+ 'runs': CronRunService.recent_runs(job_id, limit=20),
+ 'stats': CronRunService.stats(job_id),
+ })
+
+
+@cron_bp.route('/runs/ingest', methods=['POST'])
+@admin_required
+def ingest_run():
+ """Ingest a run reported by the serverkit-cron-run shim.
+
+ Localhost-only + a short-mint break-glass admin token (Decision 9, mirroring
+ the CLI break-glass client). Records the run and fires an edge-triggered
+ failure/recovery notification on a status TRANSITION only.
+ """
+ remote = (request.remote_addr or '')
+ if remote not in ('127.0.0.1', '::1', 'localhost'):
+ return jsonify({'error': 'Ingest is restricted to localhost'}), 403
+
+ data = request.get_json(silent=True) or {}
+ job_id = data.get('job_id')
+ if not job_id:
+ return jsonify({'error': 'job_id is required'}), 400
+
+ from app.services.cron_run_service import CronRunService
+ run, transition = CronRunService.record_run(
+ job_id=job_id,
+ started_at=data.get('started_at'),
+ finished_at=data.get('finished_at'),
+ exit_code=data.get('exit_code'),
+ output_tail=data.get('output_tail'),
+ )
+
+ if transition:
+ _notify_run_transition(job_id, transition, run)
+
+ return jsonify({'success': True, 'run_id': run.id, 'status': run.status}), 201
+
+
+def _notify_run_transition(job_id, transition, run):
+ """Edge-triggered failure/recovery alert for a tracked job."""
+ job = CronService.get_job(job_id) or {}
+ # Alerts default on for tracked jobs; a per-job flag can opt out.
+ if not job.get('alert_on_failure', True):
+ return
+
+ name = job.get('name') or job_id
+ payload = {'name': name, 'job_id': job_id, 'exit_code': run.exit_code,
+ 'status': run.status}
+
+ aid = job.get('application_id')
+ if aid:
+ from app.models import Application
+ app = Application.query.get(int(aid))
+ if app:
+ payload['app'] = app.name
+ if app.workspace_id:
+ from app.models import Workspace
+ ws = Workspace.query.get(app.workspace_id)
+ if ws:
+ payload['workspace'] = ws.name
+
+ event = 'cron.job_failed' if transition == 'failure' else 'cron.job_recovered'
+ try:
+ from app.plugins_sdk import notify
+ notify.send(event, to='admins', data=payload, category='system')
+ except Exception: # noqa: BLE001 - alerting must never break ingest
+ pass
+
+
+@cron_bp.route('/preview', methods=['POST'])
+@viewer_required
+def preview_schedule():
+ """Validate + humanize a cron schedule and return the next run times.
+
+ Cheap and side-effect-free (computes over its input only), so it matches the
+ existing cron read gate rather than the admin write gate — the Backups and
+ server-detail embedders shouldn't need admin to preview a schedule.
+ """
+ data = request.get_json(silent=True) or {}
+ schedule = data.get('schedule', '')
+ result = CronService.preview_schedule(schedule)
+ return jsonify(result)
diff --git a/backend/app/cron_runner.py b/backend/app/cron_runner.py
new file mode 100644
index 00000000..fee12b51
--- /dev/null
+++ b/backend/app/cron_runner.py
@@ -0,0 +1,68 @@
+"""serverkit-cron-run — wrap a panel cron command to record its run.
+
+A tracked crontab line invokes this as:
+
+ <python> <backend>/serverkit_cron_run.py <job_id> -- <command...>
+
+It runs the command, passes its stdout/stderr straight through (so cron's own
+mail keeps working), captures a tail of the combined output plus timing and the
+exit code, reports the run to the local panel's ingest endpoint (localhost +
+short-mint break-glass token, mirroring cli_api_client), and re-exits with the
+command's own code so cron behaves identically. Reporting is best-effort: a
+failure to record must never change the job's outcome.
+"""
+import os
+import subprocess
+import sys
+from datetime import datetime, timezone
+
+OUTPUT_TAIL_BYTES = 8 * 1024
+
+
+def _report(job_id, started, finished, exit_code, output_tail):
+ try:
+ from app.services.cli_api_client import mint_breakglass_token, ApiClient
+ token, _ = mint_breakglass_token()
+ ApiClient(token=token).post('/cron/runs/ingest', {
+ 'job_id': job_id,
+ 'started_at': started.isoformat(),
+ 'finished_at': finished.isoformat(),
+ 'exit_code': exit_code,
+ 'output_tail': output_tail,
+ })
+ except Exception as exc: # noqa: BLE001 - never affect the job's exit
+ sys.stderr.write(f'serverkit-cron-run: could not record run: {exc}\n')
+
+
+def main(argv=None):
+ argv = list(sys.argv[1:] if argv is None else argv)
+ if '--' not in argv:
+ sys.stderr.write('usage: serverkit-cron-run <job_id> -- <command...>\n')
+ return 2
+ sep = argv.index('--')
+ job_id = argv[0] if sep >= 1 else ''
+ command = argv[sep + 1:]
+ if not job_id or not command:
+ sys.stderr.write('usage: serverkit-cron-run <job_id> -- <command...>\n')
+ return 2
+
+ started = datetime.now(timezone.utc)
+ stdout, stderr, exit_code = '', '', 127
+ try:
+ proc = subprocess.run(command, capture_output=True, text=True)
+ stdout, stderr, exit_code = proc.stdout or '', proc.stderr or '', proc.returncode
+ except Exception as exc: # noqa: BLE001 - record the failure to launch
+ stderr = f'serverkit-cron-run: failed to execute: {exc}\n'
+ finished = datetime.now(timezone.utc)
+
+ # Pass output through so cron's MAILTO behavior is unchanged.
+ sys.stdout.write(stdout)
+ sys.stderr.write(stderr)
+
+ tail = (stdout + stderr)[-OUTPUT_TAIL_BYTES:]
+ _report(job_id, started, finished, exit_code, tail)
+ return exit_code
+
+
+if __name__ == '__main__': # pragma: no cover - exercised via serverkit_cron_run.py
+ sys.exit(main())
diff --git a/backend/app/models/cron_run.py b/backend/app/models/cron_run.py
new file mode 100644
index 00000000..ef0f5bec
--- /dev/null
+++ b/backend/app/models/cron_run.py
@@ -0,0 +1,50 @@
+"""Cron run records — the trust layer for scheduled tasks.
+
+One row per execution of a panel cron job whose "Track runs" toggle is on. The
+``serverkit-cron-run`` shim wraps the command, captures start/end/exit-code and a
+tail of the combined output, and posts it to ``POST /cron/runs/ingest``. Jobs
+created outside the panel (or with tracking off) never produce rows.
+"""
+from datetime import datetime
+
+from app import db
+
+OUTPUT_TAIL_LIMIT = 8 * 1024 # 8 KB cap on stored output tail
+
+STATUS_RUNNING = 'running'
+STATUS_SUCCESS = 'success'
+STATUS_FAILURE = 'failure'
+
+
+class CronRun(db.Model):
+ __tablename__ = 'cron_runs'
+
+ id = db.Column(db.Integer, primary_key=True)
+ # The panel job id (metadata key), not a DB FK — cron metadata lives in a
+ # JSON store, so this is a loose reference.
+ job_id = db.Column(db.String(64), nullable=False, index=True)
+ started_at = db.Column(db.DateTime, nullable=True)
+ finished_at = db.Column(db.DateTime, nullable=True)
+ exit_code = db.Column(db.Integer, nullable=True)
+ status = db.Column(db.String(16), nullable=False, default=STATUS_RUNNING)
+ output_tail = db.Column(db.Text, nullable=True)
+ created_at = db.Column(db.DateTime, default=datetime.utcnow, index=True)
+
+ @property
+ def duration_seconds(self):
+ if self.started_at and self.finished_at:
+ return max(0.0, (self.finished_at - self.started_at).total_seconds())
+ return None
+
+ def to_dict(self):
+ return {
+ 'id': self.id,
+ 'job_id': self.job_id,
+ 'started_at': self.started_at.isoformat() if self.started_at else None,
+ 'finished_at': self.finished_at.isoformat() if self.finished_at else None,
+ 'exit_code': self.exit_code,
+ 'status': self.status,
+ 'duration_seconds': self.duration_seconds,
+ 'output_tail': self.output_tail,
+ 'created_at': self.created_at.isoformat() if self.created_at else None,
+ }
diff --git a/backend/serverkit_cron_run.py b/backend/serverkit_cron_run.py
new file mode 100644
index 00000000..0a1e4d9c
--- /dev/null
+++ b/backend/serverkit_cron_run.py
@@ -0,0 +1,16 @@
+#!/usr/bin/env python3
+"""Standalone entry for the cron-run shim.
+
+Kept at the backend root (not under app/) so a tracked crontab line can invoke
+it by absolute path without needing PYTHONPATH set: it puts its own directory on
+sys.path and delegates to app.cron_runner.main().
+"""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+
+from app.cron_runner import main # noqa: E402
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/backend/tests/test_cron_runs.py b/backend/tests/test_cron_runs.py
new file mode 100644
index 00000000..58ad91f2
--- /dev/null
+++ b/backend/tests/test_cron_runs.py
@@ -0,0 +1,213 @@
+"""Cron run tracking: the shim, ingest endpoint, and edge-triggered alerts.
+
+Plan 21 Phase 4 (#13–#17). The crontab-rewrite half is Linux-only; these cover
+the OS-agnostic parts — shim exit-code/output round-trip, run recording +
+status-transition logic, ingest auth, and the failure/recovery notification.
+"""
+import sys
+
+import pytest
+
+from app.services.cron_service import CronService
+from app.services.cron_run_service import CronRunService
+from app.models.cron_run import OUTPUT_TAIL_LIMIT
+
+
+def cron_store(tmp_path, monkeypatch):
+ import app.services.cron_service as mod
+ monkeypatch.setattr(mod, 'JOBS_FILE', str(tmp_path / 'cron_jobs.json'))
+ monkeypatch.setattr(CronService, 'is_linux', classmethod(lambda cls: False))
+ return mod
+
+
+# --------------------------------------------------------------------------- #
+# The shim (app/cron_runner.py)
+# --------------------------------------------------------------------------- #
+
+def test_shim_passes_through_exit_code(monkeypatch):
+ import app.cron_runner as runner
+ captured = {}
+ monkeypatch.setattr(runner, '_report',
+ lambda *a, **k: captured.update(args=a))
+ code = runner.main(['job_1', '--', sys.executable, '-c', 'import sys; sys.exit(3)'])
+ assert code == 3
+ # _report(job_id, started, finished, exit_code, tail)
+ assert captured['args'][0] == 'job_1'
+ assert captured['args'][3] == 3
+
+
+def test_shim_captures_output_tail(monkeypatch, capsys):
+ import app.cron_runner as runner
+ captured = {}
+ monkeypatch.setattr(runner, '_report',
+ lambda *a, **k: captured.update(tail=a[4]))
+ code = runner.main(['j', '--', sys.executable, '-c', 'print("hello-from-job")'])
+ assert code == 0
+ assert 'hello-from-job' in captured['tail']
+ # Output is passed through to real stdout too (cron MAILTO stays intact).
+ assert 'hello-from-job' in capsys.readouterr().out
+
+
+def test_shim_usage_error_without_separator(monkeypatch):
+ import app.cron_runner as runner
+ assert runner.main(['job_1', 'echo', 'hi']) == 2
+
+
+# --------------------------------------------------------------------------- #
+# record_run + status-transition logic
+# --------------------------------------------------------------------------- #
+
+def test_record_run_first_failure_is_a_transition(app):
+ _, transition = CronRunService.record_run('jobA', exit_code=1)
+ assert transition == 'failure'
+
+
+def test_record_run_repeat_failure_not_a_transition(app):
+ CronRunService.record_run('jobB', exit_code=1)
+ _, transition = CronRunService.record_run('jobB', exit_code=1)
+ assert transition is None
+
+
+def test_record_run_recovery_transition(app):
+ CronRunService.record_run('jobC', exit_code=1)
+ _, transition = CronRunService.record_run('jobC', exit_code=0)
+ assert transition == 'recovery'
+
+
+def test_record_run_first_success_no_transition(app):
+ _, transition = CronRunService.record_run('jobD', exit_code=0)
+ assert transition is None
+
+
+def test_record_run_caps_output_tail(app):
+ big = 'x' * (OUTPUT_TAIL_LIMIT + 5000)
+ run, _ = CronRunService.record_run('jobE', exit_code=0, output_tail=big)
+ assert len(run.output_tail) == OUTPUT_TAIL_LIMIT
+
+
+def test_stats_success_rate(app):
+ for code in (0, 0, 1, 0):
+ CronRunService.record_run('jobF', exit_code=code)
+ stats = CronRunService.stats('jobF')
+ assert stats['total'] == 4
+ assert stats['success'] == 3
+ assert stats['success_rate'] == 0.75
+ assert stats['last_status'] == 'success'
+
+
+# --------------------------------------------------------------------------- #
+# ingest endpoint (localhost + admin token)
+# --------------------------------------------------------------------------- #
+
+def test_ingest_records_run(client, auth_headers):
+ resp = client.post('/api/v1/cron/runs/ingest', headers=auth_headers, json={
+ 'job_id': 'job_ingest', 'exit_code': 0, 'output_tail': 'ok',
+ })
+ assert resp.status_code == 201
+ assert resp.get_json()['status'] == 'success'
+
+
+def test_ingest_rejects_non_localhost(client, auth_headers):
+ resp = client.post('/api/v1/cron/runs/ingest', headers=auth_headers,
+ environ_base={'REMOTE_ADDR': '10.1.2.3'},
+ json={'job_id': 'x', 'exit_code': 0})
+ assert resp.status_code == 403
+
+
+def test_ingest_requires_job_id(client, auth_headers):
+ resp = client.post('/api/v1/cron/runs/ingest', headers=auth_headers,
+ json={'exit_code': 0})
+ assert resp.status_code == 400
+
+
+def test_ingest_requires_auth(client):
+ resp = client.post('/api/v1/cron/runs/ingest', json={'job_id': 'x', 'exit_code': 0})
+ assert resp.status_code in (401, 403, 422)
+
+
+# --------------------------------------------------------------------------- #
+# edge-triggered notification via ingest
+# --------------------------------------------------------------------------- #
+
+def test_ingest_notifies_on_failure_transition(client, auth_headers, cron_store, monkeypatch):
+ sent = []
+ from app.plugins_sdk import notify
+ monkeypatch.setattr(notify, 'send',
+ lambda event, **kw: sent.append((event, kw.get('data'))))
+
+ jid = CronService.add_job('0 0 * * *', '/bin/false', name='Failing Job')['job_id']
+
+ # First failure -> one alert.
+ client.post('/api/v1/cron/runs/ingest', headers=auth_headers,
+ json={'job_id': jid, 'exit_code': 1})
+ # Second failure -> NO new alert (edge-triggered, not per-occurrence).
+ client.post('/api/v1/cron/runs/ingest', headers=auth_headers,
+ json={'job_id': jid, 'exit_code': 1})
+
+ failed = [s for s in sent if s[0] == 'cron.job_failed']
+ assert len(failed) == 1
+ assert failed[0][1]['name'] == 'Failing Job'
+
+ # Recovery -> one recovery alert.
+ client.post('/api/v1/cron/runs/ingest', headers=auth_headers,
+ json={'job_id': jid, 'exit_code': 0})
+ assert any(s[0] == 'cron.job_recovered' for s in sent)
+
+
+def test_ingest_respects_alert_opt_out(client, auth_headers, cron_store, monkeypatch):
+ sent = []
+ from app.plugins_sdk import notify
+ monkeypatch.setattr(notify, 'send', lambda event, **kw: sent.append(event))
+
+ jid = CronService.add_job('0 0 * * *', '/bin/false', name='Quiet Job')['job_id']
+ meta = CronService._load_jobs_metadata()
+ meta['jobs'][jid]['alert_on_failure'] = False
+ CronService._save_jobs_metadata(meta)
+
+ client.post('/api/v1/cron/runs/ingest', headers=auth_headers,
+ json={'job_id': jid, 'exit_code': 1})
+ assert 'cron.job_failed' not in sent
+
+
+# --------------------------------------------------------------------------- #
+# tracking toggle + wrapper construction
+# --------------------------------------------------------------------------- #
+
+def test_wrapper_command_shape():
+ wrapped = CronService._crontab_command('/usr/bin/task.sh', True, 'job_9')
+ assert 'serverkit_cron_run.py' in wrapped
+ assert 'job_9 -- /usr/bin/task.sh' in wrapped
+ # Untracked is byte-identical to the bare command.
+ assert CronService._crontab_command('/usr/bin/task.sh', False, 'job_9') == '/usr/bin/task.sh'
+
+
+def test_set_tracking_updates_metadata(cron_store):
+ jid = CronService.add_job('0 0 * * *', '/usr/bin/task.sh', name='T')['job_id']
+ assert CronService.set_tracking(jid, True)['tracked'] is True
+ assert CronService.get_job(jid)['tracked'] is True
+ assert CronService.set_tracking(jid, False)['tracked'] is False
+ assert CronService.get_job(jid)['tracked'] is False
+
+
+# --------------------------------------------------------------------------- #
+# "Run now" records a CronRun too (#18)
+# --------------------------------------------------------------------------- #
+
+def test_run_now_records_history(app, cron_store, monkeypatch):
+ import subprocess
+
+ jid = CronService.add_job('0 0 * * *', '/bin/true', name='M')['job_id']
+
+ class _Result:
+ returncode = 0
+ stdout = 'done'
+ stderr = ''
+
+ monkeypatch.setattr(subprocess, 'run', lambda *a, **k: _Result())
+ res = CronService.run_job_now(jid)
+ assert res['success']
+
+ runs = CronRunService.recent_runs(jid)
+ assert len(runs) == 1
+ assert runs[0]['status'] == 'success'
diff --git a/backend/tests/test_remote_cron_update.py b/backend/tests/test_remote_cron_update.py
new file mode 100644
index 00000000..2c01657d
--- /dev/null
+++ b/backend/tests/test_remote_cron_update.py
@@ -0,0 +1,69 @@
+"""Remote cron edit — cron:update dispatch + capability gate (plan 28 #17).
+
+Uses the registry-stub pattern (monkeypatch agent_registry) to prove:
+- an agent without the cron.update capability is refused cleanly (no dispatch);
+- update_job forwards ONLY the fields the caller provided so the agent leaves
+ the rest unchanged;
+- the returned Entry (with its new content-derived id) is passed through.
+"""
+from app.services import agent_registry as ar_mod
+from app.services.remote_cron_service import RemoteCronService
+
+
+def test_update_refused_without_capability(monkeypatch):
+ monkeypatch.setattr(ar_mod.agent_registry, 'has_capability', lambda sid, cap: False)
+
+ def _boom(*a, **k): # send_command must never be called
+ raise AssertionError('send_command should not be reached when uncapable')
+
+ monkeypatch.setattr(ar_mod.agent_registry, 'send_command', _boom)
+
+ res = RemoteCronService.update_job('srv-1', 'cron_abc', schedule='0 4 * * *')
+ assert res['success'] is False
+ assert res['code'] == 'CRON_UPDATE_UNSUPPORTED'
+
+
+def test_update_sends_only_provided_fields(monkeypatch):
+ monkeypatch.setattr(ar_mod.agent_registry, 'has_capability',
+ lambda sid, cap: cap == 'cron.update')
+ captured = {}
+
+ def fake_send(server_id, action, params=None, user_id=None, timeout=15.0):
+ captured['action'] = action
+ captured['params'] = params
+ return {'success': True, 'data': {
+ 'id': 'cron_newid', 'schedule': '0 4 * * *',
+ 'command': '/usr/bin/backup', 'enabled': True,
+ }}
+
+ monkeypatch.setattr(ar_mod.agent_registry, 'send_command', fake_send)
+
+ res = RemoteCronService.update_job('srv-1', 'cron_oldid', schedule='0 4 * * *')
+
+ assert captured['action'] == 'cron:update'
+ # command and name were not provided -> not forwarded (agent keeps them).
+ assert captured['params'] == {'id': 'cron_oldid', 'schedule': '0 4 * * *'}
+ assert res['success'] is True
+ assert res['data']['id'] == 'cron_newid'
+
+
+def test_update_forwards_all_fields_when_given(monkeypatch):
+ monkeypatch.setattr(ar_mod.agent_registry, 'has_capability', lambda sid, cap: True)
+ captured = {}
+
+ def fake_send(server_id, action, params=None, user_id=None, timeout=15.0):
+ captured['params'] = params
+ return {'success': True, 'data': {'id': 'cron_x'}}
+
+ monkeypatch.setattr(ar_mod.agent_registry, 'send_command', fake_send)
+
+ RemoteCronService.update_job(
+ 'srv-1', 'cron_oldid',
+ schedule='*/5 * * * *', command='/opt/run', name='five-min')
+
+ assert captured['params'] == {
+ 'id': 'cron_oldid',
+ 'schedule': '*/5 * * * *',
+ 'command': '/opt/run',
+ 'name': 'five-min',
+ }