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
feat(jobs): host-idiom Jobs page + server-side search/paging + job retention
Juan Denis634f21340ddd
diff --git a/backend/app/api/jobs.py b/backend/app/api/jobs.pyindex 7e3cd8bf..f6e603cf 100644--- a/backend/app/api/jobs.py+++ b/backend/app/api/jobs.py@@ -26,18 +26,24 @@ def list_jobs():return jsonify({'error': 'Admin access required'}), 403try:limit = min(int(request.args.get('limit', 50)), 200)- offset = int(request.args.get('offset', 0))+ offset = max(int(request.args.get('offset', 0)), 0)except (TypeError, ValueError):limit, offset = 50, 0- jobs = JobService.list(- status=request.args.get('status'),- kind=request.args.get('kind'),- owner_type=request.args.get('owner_type'),- owner_id=request.args.get('owner_id'),- limit=limit,- offset=offset,- )- return jsonify({'jobs': [j.to_dict() for j in jobs]})+ filters = {+ 'status': request.args.get('status'),+ 'kind': request.args.get('kind'),+ 'owner_type': request.args.get('owner_type'),+ 'owner_id': request.args.get('owner_id'),+ 'q': request.args.get('q'),+ }+ jobs = JobService.list(limit=limit, offset=offset, **filters)+ total = JobService.count(**filters)+ return jsonify({+ 'jobs': [j.to_dict() for j in jobs],+ 'total': total,+ 'limit': limit,+ 'offset': offset,+ })@jobs_bp.route('/stats', methods=['GET'])diff --git a/backend/app/jobs/builtin_handlers.py b/backend/app/jobs/builtin_handlers.pyindex 3e138bd0..e77e3afb 100644--- a/backend/app/jobs/builtin_handlers.py+++ b/backend/app/jobs/builtin_handlers.py@@ -263,6 +263,27 @@ def run_backup_scheduler():BackupService.check_backup_schedules()+def run_job_retention():+ """Prune old terminal jobs so scheduler-tick rows (backup/workflow/auto-sync+ ticks) don't accumulate forever — the "107,834 Total" fix at the source.+ Succeeded/cancelled are kept ``jobs.retention_days`` (default 14), failed+ kept 3x that; queued/running rows are never touched. ``0`` disables it."""+ from app.jobs.service import JobService+ from app.services.settings_service import SettingsService+ days = SettingsService.get('jobs.retention_days', 14)+ try:+ days = int(days)+ except (TypeError, ValueError):+ days = 14+ if days <= 0:+ return None+ deleted = JobService.prune_terminal(retention_days=days)+ if deleted:+ logger.info(f'Job retention pruned {deleted} terminal job row(s)')+ return {'deleted': deleted}+ return None++def run_extension_update_check():"""Daily registry check for installed-extension updates (#50).@@ -324,6 +345,7 @@ _BUILTINS = [('builtin.registrar_expiry', run_registrar_expiry, 'registrar-expiry', 86400, 300),('builtin.backup_scheduler', run_backup_scheduler, 'backup-scheduler', 30, 30),('builtin.extension_updates', run_extension_update_check, 'extension-updates', 86400, 600),+ ('builtin.job_retention', run_job_retention, 'job-retention', 21600, 1500),]diff --git a/backend/app/jobs/service.py b/backend/app/jobs/service.pyindex d6ab1790..a09527b3 100644--- a/backend/app/jobs/service.py+++ b/backend/app/jobs/service.py@@ -69,8 +69,8 @@ class JobService:def get(cls, job_id):return Job.query.get(job_id)- @classmethod- def list(cls, status=None, kind=None, owner_type=None, owner_id=None, limit=50, offset=0):+ @staticmethod+ def _filtered_query(status=None, kind=None, owner_type=None, owner_id=None, q=None):query = Job.queryif status:query = query.filter_by(status=status)@@ -80,8 +80,26 @@ class JobService:query = query.filter_by(owner_type=owner_type)if owner_id is not None:query = query.filter_by(owner_id=str(owner_id))+ if q and str(q).strip():+ from sqlalchemy import func, or_+ like = f'%{str(q).strip().lower()}%'+ query = query.filter(or_(+ func.lower(Job.kind).like(like),+ func.lower(Job.owner_type).like(like),+ func.lower(Job.owner_id).like(like),+ ))+ return query++ @classmethod+ def list(cls, status=None, kind=None, owner_type=None, owner_id=None, q=None, limit=50, offset=0):+ query = cls._filtered_query(status, kind, owner_type, owner_id, q)return query.order_by(Job.created_at.desc()).limit(limit).offset(offset).all()+ @classmethod+ def count(cls, status=None, kind=None, owner_type=None, owner_id=None, q=None):+ """Total rows matching the same filters as ``list`` (before paging)."""+ return cls._filtered_query(status, kind, owner_type, owner_id, q).count()+@classmethoddef cancel(cls, job_id):"""Mark a pending/running job cancelled. Cannot interrupt a handler that@@ -135,6 +153,42 @@ class JobService:db.session.commit()return deleted+ @classmethod+ def prune_terminal(cls, retention_days=14, batch_size=5000):+ """Prune accumulated terminal jobs so scheduler-tick rows don't grow+ without bound. Succeeded/cancelled jobs are kept ``retention_days``;+ failed jobs 3x as long (they're worth keeping longer for diagnosis).+ Queued/running rows are never touched. Deletes in batches so a huge+ backlog doesn't lock the table in one statement. Returns the count.+ """+ from sqlalchemy import func+ now = datetime.utcnow()+ age = func.coalesce(Job.completed_at, Job.created_at)+ specs = [+ ((Job.STATUS_SUCCEEDED, Job.STATUS_CANCELLED),+ now - timedelta(days=retention_days)),+ ((Job.STATUS_FAILED,),+ now - timedelta(days=retention_days * 3)),+ ]+ deleted = 0+ for statuses, cutoff in specs:+ while True:+ ids = [row[0] for row in (+ db.session.query(Job.id)+ .filter(Job.status.in_(statuses))+ .filter(age < cutoff)+ .limit(batch_size)+ .all())]+ if not ids:+ break+ deleted += (Job.query+ .filter(Job.id.in_(ids))+ .delete(synchronize_session=False))+ db.session.commit()+ if len(ids) < batch_size:+ break+ return deleted+class ScheduledJobService:diff --git a/backend/app/services/settings_service.py b/backend/app/services/settings_service.pyindex d5a7f2e1..06c4634f 100644--- a/backend/app/services/settings_service.py+++ b/backend/app/services/settings_service.py@@ -29,6 +29,11 @@ class SettingsService:'type': 'integer','description': 'Number of days to retain audit logs'},+ 'jobs.retention_days': {+ 'value': 14,+ 'type': 'integer',+ 'description': 'Days to retain succeeded/cancelled background jobs before pruning (failed jobs are kept 3x as long). 0 disables pruning.'+ },'onboarding_use_cases': {'value': [],'type': 'json',diff --git a/backend/tests/test_jobs.py b/backend/tests/test_jobs.pyindex 5665cc82..8c02b09e 100644--- a/backend/tests/test_jobs.py+++ b/backend/tests/test_jobs.py@@ -175,15 +175,17 @@ class TestBuiltins:assert 'builtin.health_check' in kindsassert 'builtin.backup_scheduler' in kindsassert 'builtin.extension_updates' in kinds- assert len([k for k in kinds if k.startswith('builtin.')]) == 10+ assert 'builtin.job_retention' in kinds+ assert len([k for k in kinds if k.startswith('builtin.')]) == 11builtin_handlers.seed_builtin_schedules()- # 10 builtin.* schedules + login-link/SSO reapers + drift/FIM/bandwidth- # sweeps + the host doctor sweep (plan 26) + the setup-health nag (plan 22).- assert ScheduledJob.query.count() == 17+ # 11 builtin.* schedules (incl. job-retention) + login-link/SSO reapers ++ # drift/FIM/bandwidth sweeps + the host doctor sweep (plan 26) + the+ # setup-health nag (plan 22).+ assert ScheduledJob.query.count() == 18# Seeding twice doesn't duplicate.builtin_handlers.seed_builtin_schedules()- assert ScheduledJob.query.count() == 17+ assert ScheduledJob.query.count() == 18class TestApi:@@ -216,6 +218,91 @@ class TestApi:assert resp.status_code == 200assert any(s['name'] == 'api-sched' for s in resp.get_json()['scheduled'])+ def test_list_returns_total_and_paging_metadata(self, client, auth_headers, app):+ for i in range(5):+ JobService.enqueue('test.page', {'i': i})+ resp = client.get('/api/v1/jobs?limit=2&offset=0', headers=auth_headers)+ assert resp.status_code == 200+ body = resp.get_json()+ assert len(body['jobs']) == 2+ assert body['total'] == 5+ assert body['limit'] == 2 and body['offset'] == 0++ def test_q_filters_over_kind_and_owner(self, client, auth_headers, app):+ JobService.enqueue('backup.run', {}, owner_type='schedule', owner_id='nightly')+ JobService.enqueue('workflow.execute', {}, owner_type='workflow', owner_id='42')++ # Match by kind fragment.+ resp = client.get('/api/v1/jobs?q=backup', headers=auth_headers)+ body = resp.get_json()+ assert body['total'] == 1+ assert body['jobs'][0]['kind'] == 'backup.run'++ # Match by owner_id fragment (case-insensitive).+ resp = client.get('/api/v1/jobs?q=NIGHTLY', headers=auth_headers)+ assert resp.get_json()['total'] == 1++ # Match by owner_type fragment spanning both would be broader; a specific+ # term isolates one row.+ resp = client.get('/api/v1/jobs?q=workflow', headers=auth_headers)+ assert resp.get_json()['total'] == 1+++class TestJobRetention:+ def test_prune_removes_old_terminal_keeps_fresh_and_running(self, app):+ from datetime import datetime, timedelta++ now = datetime.utcnow()++ def _job(kind, status, completed_delta_days):+ j = Job(kind=kind, status=status)+ if completed_delta_days is not None:+ j.completed_at = now - timedelta(days=completed_delta_days)+ j.created_at = now - timedelta(days=(completed_delta_days or 0))+ db.session.add(j)+ return j++ old_ok = _job('t.ok', Job.STATUS_SUCCEEDED, 30) # > 14d → pruned+ old_cancel = _job('t.c', Job.STATUS_CANCELLED, 20) # > 14d → pruned+ fresh_ok = _job('t.ok', Job.STATUS_SUCCEEDED, 2) # < 14d → kept+ old_failed = _job('t.f', Job.STATUS_FAILED, 30) # < 42d → kept+ ancient_failed = _job('t.f', Job.STATUS_FAILED, 60) # > 42d → pruned+ running = _job('t.r', Job.STATUS_RUNNING, None) # never touched+ pending = _job('t.p', Job.STATUS_PENDING, None) # never touched+ db.session.commit()++ # Capture ids before pruning — accessing .id on a deleted ORM object+ # (synchronize_session=False) would trigger a failed row refresh.+ ids = {name: j.id for name, j in {+ 'old_ok': old_ok, 'old_cancel': old_cancel, 'fresh_ok': fresh_ok,+ 'old_failed': old_failed, 'ancient_failed': ancient_failed,+ 'running': running, 'pending': pending,+ }.items()}++ deleted = JobService.prune_terminal(retention_days=14)+ assert deleted == 3++ survivors = {j.id for j in Job.query.all()}+ assert ids['fresh_ok'] in survivors+ assert ids['old_failed'] in survivors+ assert ids['running'] in survivors+ assert ids['pending'] in survivors+ assert ids['old_ok'] not in survivors+ assert ids['old_cancel'] not in survivors+ assert ids['ancient_failed'] not in survivors++ def test_retention_handler_respects_zero_disable(self, app, monkeypatch):+ from app.jobs import builtin_handlers+ from app.services.settings_service import SettingsService++ monkeypatch.setattr(SettingsService, 'get',+ staticmethod(lambda key, default=None: 0 if key == 'jobs.retention_days' else default))+ called = {'n': 0}+ monkeypatch.setattr(JobService, 'prune_terminal',+ classmethod(lambda cls, **kw: called.__setitem__('n', called['n'] + 1)))+ assert builtin_handlers.run_job_retention() is None+ assert called['n'] == 0+class TestDeploymentInstallHandler:"""Phase 5 — template installs run as a 'deploy.install' unified job ratherdiff --git a/frontend/src/pages/Jobs.jsx b/frontend/src/pages/Jobs.jsxindex 211f0562..8f4ca965 100644--- a/frontend/src/pages/Jobs.jsx+++ b/frontend/src/pages/Jobs.jsx@@ -1,25 +1,31 @@// Jobs — admin view over the unified job system (job orchestration, "Phase 9").//-// NOTE: This file was reconstructed after a data-loss corruption. It is wired to-// the real ApiService job methods (see frontend/src/services/api/jobs.js) and-// follows the host page idioms (PageTopbar + DS components), but the exact-// original layout could not be recovered — this is a faithful, functional-// rebuild rather than a byte-for-byte restore.+// Host-idiom rebuild (plan 39): the Servers/Domains table-with-search treatment+// — SegControl status filter + kind select + debounced search, DataTable rows,+// clickable compact KPIs, and server-side pagination against a job store that+// can hold six figures of scheduler-tick rows. Wired to the real ApiService job+// methods (see frontend/src/services/api/jobs.js).import { useState, useEffect, useCallback, useRef } from 'react';-import { ListChecks, RefreshCw, RotateCcw, XCircle, Play, Clock } from 'lucide-react';+import { ListChecks, RefreshCw, RotateCcw, XCircle, Play, Clock, Search, ChevronLeft, ChevronRight } from 'lucide-react';import api from '../services/api';-import { PageTopbar, MetricCard, KpiBand, Pill } from '@/components/ds';+import { PageTopbar, MetricCard, KpiBand, Pill, DataTable, SegControl } from '@/components/ds';import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import {+ Select, SelectTrigger, SelectValue, SelectContent, SelectItem,+} from '@/components/ui/select';import { useAuth } from '../contexts/AuthContext';import { useToast } from '../contexts/ToastContext';import { timeAgo } from '../utils/timeAgo';const STATUSES = ['all', 'queued', 'running', 'succeeded', 'failed', 'cancelled'];+const PAGE_SIZE = 50;const POLL_MS = 5000;// Map a job status to a DS Pill colour.const STATUS_KIND = {queued: 'gray',+ pending: 'gray',scheduled: 'gray',running: 'cyan',succeeded: 'green',@@ -35,29 +41,61 @@ function statusKind(status) {return STATUS_KIND[String(status || '').toLowerCase()] || 'gray';}+function ownerLabel(job) {+ if (!job.owner_type) return '—';+ return `${job.owner_type}${job.owner_id ? ` #${job.owner_id}` : ''}`;+}++function progressLabel(job) {+ if (typeof job.progress === 'number') return `${Math.round(job.progress)}%`;+ if (job.completed_units != null && job.total_units != null) {+ return `${job.completed_units}/${job.total_units}`;+ }+ return '—';+}++const isRunning = (s) => ['running', 'queued', 'pending', 'scheduled'].includes(String(s || '').toLowerCase());+const canRetry = (s) => ['failed', 'error', 'cancelled', 'canceled'].includes(String(s || '').toLowerCase());+export default function Jobs() {const { isAdmin } = useAuth();const toast = useToast();const [jobs, setJobs] = useState([]);+ const [total, setTotal] = useState(0);const [stats, setStats] = useState(null);const [scheduled, setScheduled] = useState([]);const [status, setStatus] = useState('all');const [kind, setKind] = useState('all');const [kinds, setKinds] = useState([]);+ const [searchInput, setSearchInput] = useState('');+ const [q, setQ] = useState('');+ const [page, setPage] = useState(0);const [loading, setLoading] = useState(true);const pollRef = useRef(null);+ // Debounce the raw search box into the query term; reset to the first page+ // whenever the term changes so results start from the top.+ useEffect(() => {+ const t = setTimeout(() => {+ setQ(searchInput.trim());+ setPage(0);+ }, 350);+ return () => clearTimeout(t);+ }, [searchInput]);+const load = useCallback(async () => {try {- const params = { limit: 100 };+ const params = { limit: PAGE_SIZE, offset: page * PAGE_SIZE };if (status !== 'all') params.status = status;if (kind !== 'all') params.kind = kind;+ if (q) params.q = q;const [jobsRes, statsRes, schedRes] = await Promise.all([api.getJobs(params),api.getJobStats().catch(() => null),api.getScheduledJobs().catch(() => null),]);- setJobs(jobsRes?.jobs || jobsRes || []);+ setJobs(jobsRes?.jobs || []);+ setTotal(jobsRes?.total ?? (jobsRes?.jobs?.length || 0));setStats(statsRes?.stats || statsRes || null);setScheduled(schedRes?.scheduled || schedRes?.jobs || schedRes || []);} catch {@@ -65,7 +103,7 @@ export default function Jobs() {} finally {setLoading(false);}- }, [status, kind]);+ }, [status, kind, q, page]);useEffect(() => {if (!isAdmin) return undefined;@@ -82,43 +120,24 @@ export default function Jobs() {return () => clearInterval(pollRef.current);}, [isAdmin, load]);+ const setStatusFilter = (value) => { setStatus(value); setPage(0); };+ const setKindFilter = (value) => { setKind(value); setPage(0); };+const onRetry = async (id) => {- try {- await api.retryJob(id);- toast.success('Job re-queued');- load();- } catch {- toast.error('Retry failed');- }+ try { await api.retryJob(id); toast.success('Job re-queued'); load(); }+ catch { toast.error('Retry failed'); }};-const onCancel = async (id) => {- try {- await api.cancelJob(id);- toast.success('Job cancelled');- load();- } catch {- toast.error('Cancel failed');- }+ try { await api.cancelJob(id); toast.success('Job cancelled'); load(); }+ catch { toast.error('Cancel failed'); }};-const onRunScheduled = async (id) => {- try {- await api.runScheduledJob(id);- toast.success('Scheduled job triggered');- load();- } catch {- toast.error('Trigger failed');- }+ try { await api.runScheduledJob(id); toast.success('Scheduled job triggered'); load(); }+ catch { toast.error('Trigger failed'); }};-const onToggleScheduled = async (id, enabled) => {- try {- await api.setScheduledJobEnabled(id, enabled);- load();- } catch {- toast.error('Update failed');- }+ try { await api.setScheduledJobEnabled(id, enabled); load(); }+ catch { toast.error('Update failed'); }};if (!isAdmin) {@@ -131,8 +150,78 @@ export default function Jobs() {}const byStatus = stats?.by_status || {};- const isRunning = (s) => ['running', 'queued', 'scheduled'].includes(String(s || '').toLowerCase());- const canRetry = (s) => ['failed', 'error', 'cancelled', 'canceled'].includes(String(s || '').toLowerCase());+ const hasFilters = status !== 'all' || kind !== 'all' || Boolean(q);+ const rangeStart = total === 0 ? 0 : page * PAGE_SIZE + 1;+ const rangeEnd = page * PAGE_SIZE + jobs.length;+ const hasPrev = page > 0;+ const hasNext = (page + 1) * PAGE_SIZE < total;++ const kindOptions = kinds+ .map((k) => (typeof k === 'string' ? k : k.kind || k.name))+ .filter(Boolean);++ const jobColumns = [+ { key: 'status', header: 'Status', render: (j) => <Pill kind={statusKind(j.status)}>{j.status}</Pill> },+ { key: 'kind', header: 'Kind', cellClassName: 'sk-jobs__kind', render: (j) => j.kind || '—' },+ { key: 'owner', header: 'Owner', cellClassName: 'sk-jobs__owner', render: ownerLabel },+ {+ key: 'progress',+ header: 'Progress',+ render: (j) => (+ <>+ {progressLabel(j)}+ {j.error_message && (+ <div className="sk-jobs__error" title={j.error_message}>{j.error_message}</div>+ )}+ </>+ ),+ },+ { key: 'when', header: 'When', cellClassName: 'sk-jobs__when', render: (j) => timeAgo(j.created_at || j.updated_at) },+ {+ key: 'actions',+ header: '',+ className: 'sk-jobs__actions-col',+ cellClassName: 'sk-jobs__actions-cell',+ render: (j) => (+ <div className="sk-jobs__actions">+ {isRunning(j.status) && (+ <Button variant="ghost" size="sm" onClick={() => onCancel(j.id)}>+ <XCircle size={14} /> Cancel+ </Button>+ )}+ {canRetry(j.status) && (+ <Button variant="ghost" size="sm" onClick={() => onRetry(j.id)}>+ <RotateCcw size={14} /> Retry+ </Button>+ )}+ </div>+ ),+ },+ ];++ const scheduledColumns = [+ { key: 'name', header: 'Name', render: (s) => s.name || s.kind || `#${s.id}` },+ { key: 'kind', header: 'Kind', cellClassName: 'sk-jobs__kind', render: (s) => s.kind || '—' },+ { key: 'schedule', header: 'Schedule', cellClassName: 'sk-jobs__owner', render: (s) => s.schedule || s.cron || (s.interval_seconds ? `every ${s.interval_seconds}s` : '—') },+ { key: 'next', header: 'Next run', cellClassName: 'sk-jobs__when', render: (s) => (s.next_run_at ? timeAgo(s.next_run_at) : '—') },+ { key: 'enabled', header: 'Enabled', render: (s) => <Pill kind={s.enabled ? 'green' : 'gray'}>{s.enabled ? 'On' : 'Off'}</Pill> },+ {+ key: 'actions',+ header: '',+ className: 'sk-jobs__actions-col',+ cellClassName: 'sk-jobs__actions-cell',+ render: (s) => (+ <div className="sk-jobs__actions">+ <Button variant="ghost" size="sm" onClick={() => onRunScheduled(s.id)}>+ <Play size={14} /> Run now+ </Button>+ <Button variant="ghost" size="sm" onClick={() => onToggleScheduled(s.id, !s.enabled)}>+ {s.enabled ? 'Disable' : 'Enable'}+ </Button>+ </div>+ ),+ },+ ];return (<>@@ -149,92 +238,92 @@ export default function Jobs() {<div className="sk-jobs"><KpiBand>- <MetricCard label="Total" value={stats?.total ?? jobs.length ?? 0} tone="accent" />- <MetricCard label="Running" value={byStatus.running ?? 0} tone="cyan" />- <MetricCard label="Queued" value={byStatus.queued ?? 0} tone="amber" />- <MetricCard label="Failed" value={byStatus.failed ?? 0} tone="red" />+ <MetricCard label="Total" value={stats?.total ?? total ?? 0} tone="accent" compact+ onClick={() => setStatusFilter('all')} />+ <MetricCard label="Running" value={byStatus.running ?? 0} tone="cyan" compact+ onClick={() => setStatusFilter('running')} />+ <MetricCard label="Queued" value={byStatus.pending ?? byStatus.queued ?? 0} tone="amber" compact+ onClick={() => setStatusFilter('queued')} />+ <MetricCard label="Failed" value={byStatus.failed ?? 0} tone="red" compact+ onClick={() => setStatusFilter('failed')} /></KpiBand>- <div className="sk-jobs__filters">- <label>- Status- <select value={status} onChange={(e) => setStatus(e.target.value)}>- {STATUSES.map((s) => <option key={s} value={s}>{s}</option>)}- </select>- </label>- <label>- Kind- <select value={kind} onChange={(e) => setKind(e.target.value)}>- <option value="all">all</option>- {kinds.map((k) => {- const value = typeof k === 'string' ? k : k.kind || k.name;- return <option key={value} value={value}>{value}</option>;- })}- </select>- </label>+ <div className="sk-jobs__command-bar">+ <div className="sk-jobs__filters">+ <SegControl+ options={STATUSES.map((s) => ({ value: s, label: s.charAt(0).toUpperCase() + s.slice(1) }))}+ value={status}+ onChange={setStatusFilter}+ aria-label="Filter by status"+ />+ <Select value={kind} onValueChange={setKindFilter}>+ <SelectTrigger className="sk-jobs__kind-select" aria-label="Filter by kind">+ <SelectValue placeholder="All kinds" />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="all">All kinds</SelectItem>+ {kindOptions.map((k) => <SelectItem key={k} value={k}>{k}</SelectItem>)}+ </SelectContent>+ </Select>+ <label className="search-box sk-jobs__search">+ <Search size={16} />+ <Input+ type="text"+ placeholder="Search by kind or owner..."+ value={searchInput}+ onChange={(e) => setSearchInput(e.target.value)}+ aria-label="Search jobs"+ />+ </label>+ </div>+ <div className="sk-jobs__results-summary">+ {total > 0 ? (+ <span>Showing <strong>{rangeStart}</strong>–<strong>{rangeEnd}</strong> of <strong>{total}</strong></span>+ ) : (+ <span>No jobs</span>+ )}+ {hasFilters && (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="sk-jobs__clear-filters"+ onClick={() => {+ setStatus('all');+ setKind('all');+ setSearchInput('');+ setPage(0);+ }}+ >+ Clear filters+ </Button>+ )}+ </div></div>- {loading && jobs.length === 0 ? (- <div className="sk-jobs__empty">Loading…</div>- ) : jobs.length === 0 ? (- <div className="sk-jobs__empty">- <ListChecks size={24} aria-hidden="true" />- <p>No jobs match these filters.</p>- </div>- ) : (- <div className="sk-jobs__table-wrap">- <table className="sk-jobs__table">- <thead>- <tr>- <th>Status</th>- <th>Kind</th>- <th>Owner</th>- <th>Progress</th>- <th>When</th>- <th aria-label="Actions" />- </tr>- </thead>- <tbody>- {jobs.map((job) => (- <tr key={job.id}>- <td>- <Pill kind={statusKind(job.status)}>{job.status}</Pill>- </td>- <td className="sk-jobs__kind">{job.kind || '—'}</td>- <td className="sk-jobs__owner">- {job.owner_type- ? `${job.owner_type}${job.owner_id ? ` #${job.owner_id}` : ''}`- : '—'}- </td>- <td>- {typeof job.progress === 'number'- ? `${Math.round(job.progress)}%`- : (job.completed_units != null && job.total_units != null)- ? `${job.completed_units}/${job.total_units}`- : '—'}- {job.error && (- <div className="sk-jobs__error" title={job.error}>{job.error}</div>- )}- </td>- <td className="sk-jobs__when">- {timeAgo(job.created_at || job.updated_at)}- </td>- <td className="sk-jobs__actions">- {isRunning(job.status) && (- <Button variant="ghost" size="sm" onClick={() => onCancel(job.id)}>- <XCircle size={14} /> Cancel- </Button>- )}- {canRetry(job.status) && (- <Button variant="ghost" size="sm" onClick={() => onRetry(job.id)}>- <RotateCcw size={14} /> Retry- </Button>- )}- </td>- </tr>- ))}- </tbody>- </table>+ <DataTable+ columns={jobColumns}+ data={jobs}+ keyField="id"+ sortable={false}+ loading={loading && jobs.length === 0}+ emptyState={(+ <div className="sk-jobs__empty">+ <ListChecks size={24} aria-hidden="true" />+ <p>{hasFilters ? 'No jobs match these filters.' : 'No jobs have run yet.'}</p>+ </div>+ )}+ />++ {(hasPrev || hasNext) && (+ <div className="sk-jobs__pager">+ <Button variant="outline" size="sm" disabled={!hasPrev} onClick={() => setPage((p) => Math.max(0, p - 1))}>+ <ChevronLeft size={14} /> Prev+ </Button>+ <span className="sk-jobs__pager-label">Page {page + 1}</span>+ <Button variant="outline" size="sm" disabled={!hasNext} onClick={() => setPage((p) => p + 1)}>+ Next <ChevronRight size={14} />+ </Button></div>)}@@ -243,49 +332,12 @@ export default function Jobs() {<h2 className="sk-jobs__section-title"><Clock size={16} aria-hidden="true" /> Scheduled jobs</h2>- <div className="sk-jobs__table-wrap">- <table className="sk-jobs__table">- <thead>- <tr>- <th>Name</th>- <th>Kind</th>- <th>Schedule</th>- <th>Next run</th>- <th>Enabled</th>- <th aria-label="Actions" />- </tr>- </thead>- <tbody>- {scheduled.map((sched) => (- <tr key={sched.id}>- <td>{sched.name || sched.kind || `#${sched.id}`}</td>- <td className="sk-jobs__kind">{sched.kind || '—'}</td>- <td className="sk-jobs__owner">{sched.schedule || sched.cron || '—'}</td>- <td className="sk-jobs__when">- {sched.next_run_at ? timeAgo(sched.next_run_at) : '—'}- </td>- <td>- <Pill kind={sched.enabled ? 'green' : 'gray'}>- {sched.enabled ? 'On' : 'Off'}- </Pill>- </td>- <td className="sk-jobs__actions">- <Button variant="ghost" size="sm" onClick={() => onRunScheduled(sched.id)}>- <Play size={14} /> Run now- </Button>- <Button- variant="ghost"- size="sm"- onClick={() => onToggleScheduled(sched.id, !sched.enabled)}- >- {sched.enabled ? 'Disable' : 'Enable'}- </Button>- </td>- </tr>- ))}- </tbody>- </table>- </div>+ <DataTable+ columns={scheduledColumns}+ data={scheduled}+ keyField="id"+ sortable={false}+ /></section>)}</div>diff --git a/frontend/src/services/api/jobs.js b/frontend/src/services/api/jobs.jsindex e1fdfc27..5ae311dd 100644--- a/frontend/src/services/api/jobs.js+++ b/frontend/src/services/api/jobs.js@@ -6,6 +6,7 @@ export async function getJobs(params = {}) {if (params.kind) query.append('kind', params.kind);if (params.owner_type) query.append('owner_type', params.owner_type);if (params.owner_id) query.append('owner_id', params.owner_id);+ if (params.q) query.append('q', params.q);if (params.limit) query.append('limit', params.limit);if (params.offset) query.append('offset', params.offset);const suffix = query.toString() ? `?${query}` : '';diff --git a/frontend/src/styles/pages/_jobs.scss b/frontend/src/styles/pages/_jobs.scssindex 06c5c3cd..0046dd24 100644--- a/frontend/src/styles/pages/_jobs.scss+++ b/frontend/src/styles/pages/_jobs.scss@@ -1,208 +1,120 @@-.jobs-page {- padding: $spacing-md;-}+// Jobs page (plan 39) — host-idiom table-with-search, the /servers–/domains+// pattern. Most weight is carried by shared primitives: .sk-dtable (DataTable),+// .sk-kpiband (KpiBand), .sk-seg (SegControl) and the global .search-box. This+// file only lays out the page shell, the command bar, pagination, the+// scheduled-jobs section, and the row cell tints.++.sk-jobs {+ padding: $space-5;-.jobs-stats {- display: grid;- grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));- gap: $spacing-md;- margin-bottom: $spacing-lg;+ .sk-kpiband-wrap { margin-bottom: $space-5; }}-.jobs-filters {+// ── Command bar: status seg + kind select + search, results summary ─────+.sk-jobs__command-bar {display: flex;- gap: $spacing-lg;+ justify-content: space-between;+ align-items: center;+ gap: $space-3;+ margin: $space-5 0 $space-4;flex-wrap: wrap;- margin-bottom: $spacing-md;-- label {- display: flex;- flex-direction: column;- gap: $spacing-xs;- font-size: 0.75rem;- text-transform: uppercase;- letter-spacing: 0.05em;- color: $text-tertiary;- }-- select {- padding: $spacing-sm;- border-radius: $radius-sm;- border: 1px solid $border-default;- background: $bg-card;- color: $text-primary;- font-size: 0.875rem;- min-width: 160px;- }}-.jobs-table-wrap {- overflow-x: auto;- border: 1px solid $border-default;- border-radius: $radius-md;- background: $bg-card;- margin-bottom: $spacing-lg;+.sk-jobs__filters {+ display: flex;+ align-items: center;+ gap: $space-3;+ flex: 1;+ flex-wrap: wrap;+ min-width: 0;}-.jobs-table {- width: 100%;- border-collapse: collapse;- font-size: 0.875rem;-- th {- text-align: left;- padding: $spacing-sm $spacing-md;- font-size: 0.75rem;- text-transform: uppercase;- letter-spacing: 0.05em;- color: $text-tertiary;- border-bottom: 1px solid $border-default;- white-space: nowrap;- }-- td {- padding: $spacing-sm $spacing-md;- border-bottom: 1px solid $border-default;- color: $text-primary;- vertical-align: middle;- }-- tbody tr:last-child td {- border-bottom: none;- }-- tr.is-disabled td {- opacity: 0.55;- }+.sk-jobs__search {+ flex: 1;+ min-width: 220px;+ max-width: 360px;}-.jobs-row {- cursor: pointer;- transition: background $transition-fast;+.sk-jobs__kind-select { min-width: 150px; }- &:hover,- &.is-open {- background: $bg-hover;- }-}--.jobs-caret svg {+.sk-jobs__results-summary {+ display: flex;+ align-items: center;+ gap: $space-2;color: $text-tertiary;- transition: transform $transition-fast;+ font-size: $font-size-sm;+ white-space: nowrap;- &.is-open {- transform: rotate(90deg);- }+ strong { color: $text-primary; font-family: $font-mono; }}-.jobs-mono {- font-family: var(--mono, monospace);- font-size: 0.8125rem;-}+.sk-jobs__clear-filters { margin-left: $space-2; }-.jobs-owner {+// ── Row cell tints ──────────────────────────────────────────────────────+.sk-jobs__kind { color: $text-secondary; }++.sk-jobs__owner {color: $text-tertiary;- font-size: 0.8125rem;+ font-family: $font-mono;+ font-size: $font-size-xs;}-.jobs-when {+.sk-jobs__when {color: $text-tertiary;white-space: nowrap;}-.jobs-actions {+.sk-jobs__error {+ margin-top: 3px;+ font-size: $font-size-xs;+ color: $danger;+ max-width: 320px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.sk-jobs__actions-col { text-align: right; }++.sk-jobs__actions {display: flex;- gap: $spacing-xs;+ gap: $space-1;justify-content: flex-end;white-space: nowrap;}-.jobs-detail-row > td {- padding: 0;- background: $bg-tertiary;-}+// ── Pagination ──────────────────────────────────────────────────────────+.sk-jobs__pager {+ display: flex;+ align-items: center;+ justify-content: flex-end;+ gap: $space-3;+ margin-top: $space-4;-.jobs-detail {- padding: $spacing-md $spacing-lg;-- &--loading {- color: $text-tertiary;- }-- &__grid {- display: grid;- grid-template-columns: max-content 1fr;- gap: $spacing-xs $spacing-md;- font-size: 0.8125rem;- margin-bottom: $spacing-md;-- span:nth-child(odd) {- color: $text-tertiary;- }-- code {- font-family: var(--mono, monospace);- color: $text-primary;- word-break: break-all;- }- }-- &__block {- margin-top: $spacing-sm;-- > span {- display: block;- font-size: 0.75rem;- text-transform: uppercase;- letter-spacing: 0.05em;- color: $text-tertiary;- margin-bottom: $spacing-xs;- }-- pre {- margin: 0;- background: $bg-card;- border: 1px solid $border-default;- border-radius: $radius-sm;- padding: $spacing-sm $spacing-md;- overflow-x: auto;- font-size: 0.8125rem;- color: $text-primary;- white-space: pre-wrap;- word-break: break-word;- }-- &--error pre {- color: $danger;- border-color: $danger;- }- }+ &-label { color: $text-tertiary; font-size: $font-size-sm; }}-.jobs-section-head {+// ── Scheduled jobs section ──────────────────────────────────────────────+.sk-jobs__scheduled { margin-top: $space-6; }++.sk-jobs__section-title {display: flex;align-items: center;- gap: $spacing-sm;- margin: $spacing-lg 0 $spacing-md;+ gap: $space-2;+ margin: 0 0 $space-3;+ font-size: $font-size-md;+ font-weight: $font-weight-semibold;color: $text-primary;- svg {- color: $text-tertiary;- }-- h2 {- margin: 0;- font-size: 1rem;- font-weight: 600;- }+ svg { color: $text-tertiary; }}-.jobs-empty {+.sk-jobs__empty {display: flex;flex-direction: column;align-items: center;justify-content: center;- gap: $spacing-md;- padding: $spacing-xl;+ gap: $space-3;+ padding: $space-8;color: $text-tertiary;}