"use client"; import React, { useCallback, useState } from "react"; import { Timer, Play, RefreshCw, Pencil, RotateCcw } from "lucide-react"; import { useAuth } from "@/hooks/useAuth"; import { useDismissingState } from "@/hooks/useDismissingState"; import { errorMessage } from "@/lib/utils"; import { apiV2Data } from "@/lib/apiV2"; import { useExternalEffect } from "@/lib/hooks"; import { Switch } from "@/components/ui/switch"; type JobRun = { state: string; createdOn?: string; startedOn: string | null; completedOn: string | null; output: unknown }; type Override = { enabled: boolean | null; cron: string | null }; type JobInfo = { name: string; label: string; cron: string; enabled: boolean; envFlag: string | null; nextRun: string | null; recent: JobRun[]; envEnabled: boolean; envCron: string; defaultCron: string; override: Override; }; type JobsResponse = { mode: "queue" | "timers" | "off"; timezone: string; jobsEnabledEnv: boolean; jobs: JobInfo[] }; const STATE: Record = { completed: "bg-green-50 text-green-800", failed: "bg-red-50 text-red-700", active: "bg-blue-50 text-blue-700", created: "bg-gray-100 text-gray-600", retry: "bg-amber-50 text-amber-800", cancelled: "bg-gray-100 text-gray-500", }; const PRESETS: { label: string; cron: string }[] = [ { label: "Every minute", cron: "* * * * *" }, { label: "Every 5 minutes", cron: "*/5 * * * *" }, { label: "Every 15 minutes", cron: "*/15 * * * *" }, { label: "Every hour", cron: "0 * * * *" }, { label: "Daily at 02:00", cron: "0 2 * * *" }, { label: "Daily at 07:00", cron: "0 7 * * *" }, ]; const when = (d: string | null) => (d ? new Date(d).toLocaleString("en-GB", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }) : "—"); function describeCron(cron: string): string { if (cron === "* * * * *") return "Every minute"; const m = /^\*\/(\d+) \* \* \* \*$/.exec(cron); if (m) return `Every ${m[1]} minutes`; const h = /^(\d+) \* \* \* \*$/.exec(cron); if (h) return `Every hour at :${h[1].padStart(2, "0")}`; const d = /^(\d+) (\d+) \* \* \*$/.exec(cron); if (d) return `Daily at ${d[2].padStart(2, "0")}:${d[1].padStart(2, "0")}`; return cron; } function outputText(run: JobRun): string { if (run.output === null || run.output === undefined) return ""; if (typeof run.output === "object" && run.output && "message" in run.output && run.state === "failed") return String((run.output as { message: unknown }).message); try { return JSON.stringify(run.output); } catch { return ""; } } // Settings → Background jobs: what runs when, the last runs of each job, "Run now", and (3.4.0) // switching a job on or off and changing its schedule here, over what the server's .env says. export function JobsTab({ active }: { active: boolean }) { const { token } = useAuth(); const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [running, setRunning] = useState(null); const [saving, setSaving] = useState(null); const [open, setOpen] = useState(null); const [editing, setEditing] = useState<{ name: string; cron: string } | null>(null); const [message, setMessage] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null); const load = useCallback(async () => { if (!token) return; setLoading(true); try { setData(await (apiV2Data("get", "/admin/jobs", { authToken: token }) as Promise)); } catch (e) { setMessage({ type: "err", text: errorMessage(e) || "Failed to load background jobs" }); } finally { setLoading(false); } }, [token, setMessage]); useExternalEffect(() => { if (active) load(); }, [active, load]); const runNow = async (job: JobInfo) => { if (!token) return; setRunning(job.name); try { const r = await (apiV2Data("post", "/admin/jobs/{name}/run", { params: { name: job.name }, authToken: token, body: {} }) as Promise<{ queued: boolean }>); setMessage({ type: "ok", text: r.queued ? `"${job.label}" queued — it starts within a few seconds.` : `"${job.label}" ran.` }); setTimeout(load, r.queued ? 4000 : 0); } catch (e) { setMessage({ type: "err", text: errorMessage(e) || "Couldn't run the job" }); } finally { setRunning(null); } }; /** Saves a choice for one job: a value wins over the .env, null goes back to it. */ const save = async (job: JobInfo, change: { enabled?: boolean | null; cron?: string | null }, done: string) => { if (!token) return; setSaving(job.name); try { await apiV2Data("put", "/admin/jobs/{name}", { params: { name: job.name }, authToken: token, body: change }); setMessage({ type: "ok", text: done }); setEditing(null); await load(); } catch (e) { setMessage({ type: "err", text: errorMessage(e) || "Couldn't save that" }); } finally { setSaving(null); } }; const off = data?.mode === "off"; return (

Background jobs

Tasks the server runs on a schedule ({data?.timezone || "local"} time). Each runs once per schedule, even with more than one server process, and failed runs are retried. Switch a job on or off, or change when it runs: what you choose here wins over the server's .env and takes effect straight away.

{message &&
{message.text}
} {data?.mode === "timers" && (
The job queue couldn't start, so jobs are running on simple timers in this server process (no retries, history only since the last restart). Check the server log for "[jobs]".
)} {off && (
All background jobs are switched off in the server's .env (JOBS_ENABLED=false), so nothing here runs. Cross Code can change it from the Hub.
)}
    {(data?.jobs || []).map(job => { const last = job.recent[0]; const busy = saving === job.name; const enabledHere = job.override.enabled !== null; const cronHere = job.override.cron !== null; const isEditing = editing?.name === job.name; return (
  • save(job, { enabled: on }, `"${job.label}" is ${on ? "on" : "off"}.`)} aria-label={`${job.label}: ${job.enabled ? "on" : "off"}`} />
    {job.label}
    {job.enabled ? `${describeCron(job.cron)} · next ${when(job.nextRun)}` : "Off"} {enabledHere ? <> · {job.enabled ? "switched on" : "switched off"} here : !job.envEnabled && job.envFlag ? ` (${job.envFlag}=false in the .env)` : ""}
    {last && ( )}
    {isEditing && editing && (
    { e.preventDefault(); save(job, { cron: editing.cron.trim() }, `"${job.label}" now runs: ${describeCron(editing.cron.trim())}.`); }}>
    {PRESETS.map(p => ( ))}
    {describeCron(editing.cron.trim())}

    The server's own schedule for this job is {describeCron(job.envCron)}{job.envCron !== job.defaultCron ? ` (set in the .env; normally ${describeCron(job.defaultCron)})` : ""}. {cronHere && <> }

    )} {open === job.name && job.recent.length > 0 && ( {job.recent.map((r, i) => ( ))}
    StartedFinishedStateResult
    {when(r.startedOn)} {when(r.completedOn)} {r.state} {outputText(r)}
    )}
  • ); })} {!loading && data && data.jobs.length === 0 &&
  • No jobs.
  • }

Without a choice here, the server's .env applies: each job's own flag (e.g. WAITLIST_JOB_ENABLED=false) and JOB_SCHEDULE_<NAME>.

); }