Events 3.4.0, Accounts 1.4.0, contracts 1.12.0, agent 1.3.0: jobs from the dashboard, styled Accounts emails, .env from the Hub

- Events and Accounts: Background jobs are switched on or off and rescheduled from the admin;
  the choice is kept in the database (job_overrides), wins over the .env and applies at once.
  Accounts gets an Admin -> Background jobs page and per-job env flags, as Events.
- Accounts: every email styled as Cross Events' (church colour, logo, button, footer), same
  plain text (src/lib/emails.ts).
- Contracts 1.12.0: env-read / env-set agent jobs, envReadResultSchema, isSecretEnvName.
- crosscode script: `crosscode env <church> <product>` reads the .env (secrets hidden) and, with
  --set/--unset/--restart, changes one file, rebuilds the frontend when its file changed, reloads,
  and puts the file back if the site doesn't answer (lib/envedit.cjs, tests/envedit.bats).
- Agent 1.3.0: runs env-read and env-set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 12:14:02 +02:00
co-authored by Claude Opus 5.5
parent a85347bff8
commit bbcafe61b9
43 changed files with 2276 additions and 131 deletions
@@ -1,16 +1,21 @@
"use client";
import React, { useCallback, useState } from "react";
import { Timer, Play, RefreshCw } from "lucide-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 JobInfo = { name: string; label: string; cron: string; enabled: boolean; envFlag: string | null; nextRun: string | null; recent: JobRun[] };
type JobsResponse = { mode: "queue" | "timers" | "off"; timezone: string; jobs: JobInfo[] };
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<string, string> = {
completed: "bg-green-50 text-green-800",
@@ -21,12 +26,23 @@ const STATE: Record<string, string> = {
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;
@@ -38,13 +54,16 @@ function outputText(run: JobRun): string {
try { return JSON.stringify(run.output); } catch { return ""; }
}
// Settings → Background jobs: what runs when, the last runs of each job, and "Run now".
// 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<JobsResponse | null>(null);
const [loading, setLoading] = useState(true);
const [running, setRunning] = useState<string | null>(null);
const [saving, setSaving] = useState<string | null>(null);
const [open, setOpen] = useState<string | null>(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 () => {
@@ -75,6 +94,24 @@ export function JobsTab({ active }: { active: boolean }) {
}
};
/** 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 (
<div className="space-y-4">
<div className="flex items-start justify-between gap-3">
@@ -82,6 +119,7 @@ export function JobsTab({ active }: { active: boolean }) {
<h2 className="text-lg font-semibold flex items-center gap-2"><Timer className="w-5 h-5 text-brand-600" /> Background jobs</h2>
<p className="text-sm text-gray-500 mt-0.5">
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&apos;s .env and takes effect straight away.
</p>
</div>
<button type="button" onClick={load} disabled={loading} className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm rounded border bg-white hover:bg-gray-50 disabled:opacity-50 shrink-0">
@@ -89,24 +127,37 @@ export function JobsTab({ active }: { active: boolean }) {
</button>
</div>
{message && <div className={`p-3 border rounded text-sm ${message.type === "ok" ? "bg-green-50 text-green-800" : "bg-red-50 text-red-700"}`}>{message.text}</div>}
{message && <div role="status" className={`p-3 border rounded text-sm ${message.type === "ok" ? "bg-green-50 text-green-800" : "bg-red-50 text-red-700"}`}>{message.text}</div>}
{data?.mode === "timers" && (
<div className="p-3 border rounded bg-amber-50 text-amber-900 text-sm">The job queue couldn&apos;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 &quot;[jobs]&quot;.</div>
)}
{data?.mode === "off" && (
<div className="p-3 border rounded bg-gray-50 text-gray-700 text-sm">All background jobs are switched off (JOBS_ENABLED=false).</div>
{off && (
<div className="p-3 border rounded bg-gray-50 text-gray-700 text-sm">All background jobs are switched off in the server&apos;s .env (JOBS_ENABLED=false), so nothing here runs. Cross Code can change it from the Hub.</div>
)}
<ul className="divide-y border rounded-lg">
{(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 (
<li key={job.name} className="p-3">
<div className="flex flex-wrap items-center gap-2">
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
<Switch
checked={job.enabled}
disabled={busy || off}
onCheckedChange={(on) => save(job, { enabled: on }, `"${job.label}" is ${on ? "on" : "off"}.`)}
aria-label={`${job.label}: ${job.enabled ? "on" : "off"}`}
/>
<div className="min-w-0 mr-auto">
<div className="font-medium text-sm text-gray-900">{job.label}</div>
<div className={`font-medium text-sm ${job.enabled ? "text-gray-900" : "text-gray-500"}`}>{job.label}</div>
<div className="text-xs text-gray-500">
{job.enabled ? `${describeCron(job.cron)} · next ${when(job.nextRun)}` : `Off${job.envFlag ? ` (${job.envFlag}=false)` : ""}`}
{job.enabled ? `${describeCron(job.cron)} · next ${when(job.nextRun)}` : "Off"}
{enabledHere
? <> · {job.enabled ? "switched on" : "switched off"} here <button type="button" disabled={busy} className="underline hover:text-gray-700" onClick={() => save(job, { enabled: null }, `"${job.label}" follows the .env again (${job.envEnabled ? "on" : "off"}).`)}>use the .env ({job.envEnabled ? "on" : "off"})</button></>
: !job.envEnabled && job.envFlag ? ` (${job.envFlag}=false in the .env)` : ""}
</div>
</div>
{last && (
@@ -114,11 +165,43 @@ export function JobsTab({ active }: { active: boolean }) {
{last.state} · {when(last.completedOn || last.startedOn || last.createdOn || null)}
</button>
)}
<button type="button" disabled={running !== null || data?.mode === "off"} onClick={() => runNow(job)}
<button type="button" disabled={busy || isEditing} onClick={() => setEditing({ name: job.name, cron: job.cron })}
className="inline-flex items-center gap-1 px-2.5 py-1 text-xs rounded border bg-white hover:bg-gray-50 disabled:opacity-50">
<Pencil className="w-3.5 h-3.5" /> Schedule
</button>
<button type="button" disabled={running !== null || off} onClick={() => runNow(job)}
className="inline-flex items-center gap-1 px-2.5 py-1 text-xs rounded border border-brand-200 bg-brand-50 text-brand-700 hover:bg-brand-100 disabled:opacity-50">
<Play className="w-3.5 h-3.5" /> {running === job.name ? "Starting…" : "Run now"}
</button>
</div>
{isEditing && editing && (
<form className="mt-3 rounded border bg-gray-50 p-3 space-y-2" onSubmit={e => { e.preventDefault(); save(job, { cron: editing.cron.trim() }, `"${job.label}" now runs: ${describeCron(editing.cron.trim())}.`); }}>
<div className="flex flex-wrap gap-1.5">
{PRESETS.map(p => (
<button key={p.cron} type="button" onClick={() => setEditing({ name: job.name, cron: p.cron })}
className={`text-xs px-2 py-1 rounded border ${editing.cron === p.cron ? "bg-brand-50 border-brand-300 text-brand-800" : "bg-white hover:bg-gray-100"}`}>{p.label}</button>
))}
</div>
<div className="flex flex-wrap items-end gap-2">
<label className="text-xs text-gray-600">
Cron (minute hour day month weekday)
<input value={editing.cron} onChange={e => setEditing({ name: job.name, cron: e.target.value })} maxLength={100}
className="mt-1 block w-56 rounded border px-2 py-1 font-mono text-sm" aria-label="Cron schedule" />
</label>
<span className="text-xs text-gray-500 pb-1.5">{describeCron(editing.cron.trim())}</span>
<div className="ml-auto flex gap-2">
<button type="button" onClick={() => setEditing(null)} className="text-xs px-2.5 py-1.5 rounded border bg-white hover:bg-gray-100">Cancel</button>
<button type="submit" disabled={busy || !editing.cron.trim()} className="text-xs px-2.5 py-1.5 rounded bg-brand-600 text-white hover:bg-brand-700 disabled:opacity-50">{busy ? "Saving…" : "Save schedule"}</button>
</div>
</div>
<p className="text-xs text-gray-500">
The server&apos;s own schedule for this job is {describeCron(job.envCron)}{job.envCron !== job.defaultCron ? ` (set in the .env; normally ${describeCron(job.defaultCron)})` : ""}.
{cronHere && <> <button type="button" disabled={busy} className="inline-flex items-center gap-1 underline hover:text-gray-700" onClick={() => save(job, { cron: null }, `"${job.label}" is back on its own schedule.`)}><RotateCcw className="w-3 h-3" /> Use that again</button></>}
</p>
</form>
)}
{open === job.name && job.recent.length > 0 && (
<table className="mt-2 w-full text-xs">
<thead className="text-gray-500"><tr><th className="text-left font-medium py-1">Started</th><th className="text-left font-medium">Finished</th><th className="text-left font-medium">State</th><th className="text-left font-medium">Result</th></tr></thead>
@@ -139,7 +222,7 @@ export function JobsTab({ active }: { active: boolean }) {
})}
{!loading && data && data.jobs.length === 0 && <li className="p-3 text-sm text-gray-500">No jobs.</li>}
</ul>
<p className="text-xs text-gray-400">Change a schedule with the env var JOB_SCHEDULE_&lt;NAME&gt; (cron, e.g. JOB_SCHEDULE_WAITLIST=&quot;*/5 * * * *&quot;), or switch one off with its own flag.</p>
<p className="text-xs text-gray-400">Without a choice here, the server&apos;s .env applies: each job&apos;s own flag (e.g. WAITLIST_JOB_ENABLED=false) and JOB_SCHEDULE_&lt;NAME&gt;.</p>
</div>
);
}