Overhaul system health section with job trigger controls and live timestamps

Rebuild the background jobs card as a sortable table showing each job's
schedule, last run time (live-updating via a new useTimeAgo hook), last
duration, and a manual trigger button backed by a new POST
/api/admin/jobs/trigger route. Extract StatusDot into a shared
component. Add cronToHuman() to display schedule patterns as readable
strings (e.g. "Every 6h", "Daily at 03:00"). Replace static
formatDistanceToNow calls throughout the health section with a
LiveTimeAgo component that refreshes every 30 seconds. Also swap a
handful of section icons for better visual matches across settings cards.
This commit is contained in:
2026-03-05 11:52:37 -05:00
parent b474d07d97
commit 107eb9a9e7
18 changed files with 2698 additions and 260 deletions
@@ -1,6 +1,6 @@
"use client";
import { IconCalendarRepeat, IconChevronDown } from "@tabler/icons-react";
import { IconCalendarWeek, IconChevronDown } from "@tabler/icons-react";
import { format, formatDistanceToNow } from "date-fns";
import { createStore, Provider, useAtomValue } from "jotai";
import { AnimatePresence, motion } from "motion/react";
@@ -150,7 +150,7 @@ function BackupScheduleInner() {
<div className="flex items-center justify-between gap-4">
<div className="flex items-start gap-3">
<div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10">
<IconCalendarRepeat className="size-4 text-primary" />
<IconCalendarWeek className="size-4 text-primary" />
</div>
<div>
<CardTitle>Backup schedule</CardTitle>
@@ -1,6 +1,6 @@
"use client";
import { IconUserPlus } from "@tabler/icons-react";
import { IconDoorEnter } from "@tabler/icons-react";
import { useState } from "react";
import { toast } from "sonner";
import { CardContent, CardDescription, CardTitle } from "@/components/ui/card";
@@ -37,7 +37,7 @@ export function RegistrationSection({
<div className="flex items-center justify-between gap-4">
<div className="flex items-start gap-3">
<div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10">
<IconUserPlus className="size-4 text-primary" />
<IconDoorEnter className="size-4 text-primary" />
</div>
<div>
<CardTitle>Open registration</CardTitle>
@@ -2,13 +2,16 @@
import {
IconActivity,
IconClock,
IconAlertTriangle,
IconCalendarCheck,
IconCheck,
IconDatabase,
IconPlayerPlay,
IconRefresh,
} from "@tabler/icons-react";
import { formatDistanceToNow } from "date-fns";
import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
import { StatusDot } from "@/components/status-dot";
import { Button } from "@/components/ui/button";
import {
Card,
@@ -18,6 +21,20 @@ import {
} from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { Spinner } from "@/components/ui/spinner";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { useTimeAgo } from "@/hooks/use-time-ago";
import type { SystemHealthData } from "@/lib/services/system-health";
const JOB_LABELS: Record<string, string> = {
@@ -30,6 +47,40 @@ const JOB_LABELS: Record<string, string> = {
updateCheck: "Update check",
};
/** Convert a cron pattern to a short human-readable string */
function cronToHuman(pattern: string): string {
const parts = pattern.split(" ");
if (parts.length !== 5) return pattern;
const [min, hour, _dom, _mon, dow] = parts;
// Every N hours: "0 */6 * * *"
if (hour.startsWith("*/")) {
const n = Number.parseInt(hour.slice(2), 10);
return `Every ${n}h`;
}
// Twice daily: "0 1,13 * * *"
if (hour.includes(",") && !hour.includes("/") && !hour.includes("-")) {
const hours = hour.split(",");
if (hours.length === 2) {
return `Daily at ${hours.map((h) => `${h.padStart(2, "0")}:${min.padStart(2, "0")}`).join(", ")}`;
}
}
// Daily at specific time: "0 3 * * *"
if (/^\d+$/.test(hour) && /^\d+$/.test(min) && dow === "*") {
return `Daily at ${hour.padStart(2, "0")}:${min.padStart(2, "0")}`;
}
// Weekly
if (/^\d+$/.test(dow)) {
const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
return `Weekly on ${days[Number(dow)] ?? dow}`;
}
return pattern;
}
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
@@ -44,25 +95,6 @@ function formatDuration(ms: number): string {
return `${Math.round(ms / 60000)}m`;
}
/** Small colored status dot */
function StatusDot({
status,
}: {
status: "ok" | "error" | "warn" | "inactive";
}) {
const color = {
ok: "bg-green-500",
error: "bg-destructive",
warn: "bg-amber-500",
inactive: "bg-muted-foreground/30",
}[status];
return (
<span
className={`inline-block h-1.5 w-1.5 shrink-0 rounded-full ${color}`}
/>
);
}
function SkeletonCards() {
return (
<div className="space-y-3">
@@ -83,6 +115,18 @@ function SkeletonCards() {
);
}
/** Inline component that live-updates a relative timestamp */
function LiveTimeAgo({
date,
fallback = "",
}: {
date: string | Date | null | undefined;
fallback?: string;
}) {
const text = useTimeAgo(date, { fallback });
return <>{text}</>;
}
/** Renders 3 separate cards: System status, Background jobs, Storage */
export function SystemHealthCards() {
const [data, setData] = useState<SystemHealthData | null>(null);
@@ -122,34 +166,34 @@ export function SystemHealthCards() {
<IconActivity className="size-4 text-primary" />
</div>
<div>
<CardTitle>System status</CardTitle>
<CardTitle>Health status</CardTitle>
<CardDescription suppressHydrationWarning>
Checked{" "}
{formatDistanceToNow(new Date(data.checkedAt), {
addSuffix: true,
})}
Checked <LiveTimeAgo date={data.checkedAt} />
</CardDescription>
</div>
</div>
<Button
variant="outline"
onClick={() => fetchHealth(true)}
disabled={refreshing}
>
{refreshing ? (
<Spinner className="size-3" />
) : (
<IconRefresh className="size-3.5" />
)}
Refresh
</Button>
<Tooltip>
<TooltipTrigger
render={
<Button
variant="ghost"
size="icon"
onClick={() => fetchHealth(true)}
disabled={refreshing}
/>
}
>
{refreshing ? <Spinner /> : <IconRefresh />}
</TooltipTrigger>
<TooltipContent>Refresh</TooltipContent>
</Tooltip>
</div>
</CardContent>
{/* Database */}
<CardContent className="border-t border-border/30 pt-4">
<div className="flex items-center gap-2">
<span className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground/40">
<span className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground/70">
Database
</span>
<span className="font-mono text-[11px] text-muted-foreground">
@@ -158,24 +202,17 @@ export function SystemHealthCards() {
` + ${formatBytes(data.database.walSizeBytes)} WAL`}
</span>
</div>
<p className="mt-1 text-xs text-muted-foreground">
{data.database.titleCount.toLocaleString()} titles
{" · "}
{data.database.episodeCount.toLocaleString()} episodes
{" · "}
{data.database.userCount.toLocaleString()} users
</p>
</CardContent>
{/* TMDB */}
<CardContent className="border-t border-border/30 pt-4">
<div className="flex items-center gap-2">
<span className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground/40">
<span className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground/70">
TMDB API
</span>
{!data.tmdb.tokenConfigured ? (
<>
<StatusDot status="inactive" />
<StatusDot status="error" />
<span className="text-xs text-muted-foreground/50">
Not configured
</span>
@@ -184,7 +221,7 @@ export function SystemHealthCards() {
<>
<StatusDot status="ok" />
<span className="text-xs text-muted-foreground">Connected</span>
<span className="font-mono text-[11px] text-muted-foreground/40">
<span className="font-mono text-[11px] text-muted-foreground/80">
{data.tmdb.responseTimeMs}ms
</span>
</>
@@ -210,8 +247,13 @@ export function SystemHealthCards() {
{/* Environment */}
<CardContent className="border-t border-border/30 pt-4">
<div className="space-y-2">
<span className="inline-block text-[11px] font-medium uppercase tracking-wider text-muted-foreground/40">
<span className="inline-flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wider text-muted-foreground/70">
Environment
{data.environment.dataDirWritable ? (
<IconCheck className="size-3 text-green-500" />
) : (
<IconAlertTriangle className="size-3 text-destructive" />
)}
</span>
<div className="space-y-1">
{data.environment.envVars
@@ -219,9 +261,9 @@ export function SystemHealthCards() {
.map((env) => (
<div
key={env.name}
className="flex items-baseline gap-1 font-mono text-[11px] leading-relaxed"
className="flex items-baseline gap-[1px] font-mono text-[11px] leading-relaxed"
>
<span className="text-muted-foreground/50">
<span className="text-muted-foreground/60">
{env.name}=
</span>
<span className="text-muted-foreground break-all">
@@ -235,71 +277,10 @@ export function SystemHealthCards() {
</Card>
{/* ── Card 2: Background Jobs ── */}
<Card className="border-l-2 border-l-primary/30">
<CardContent>
<div className="flex items-start gap-3">
<div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10">
<IconClock className="size-4 text-primary" />
</div>
<div>
<CardTitle>Background jobs</CardTitle>
<CardDescription>
{data.jobs.filter((j) => j.lastStatus === "success").length} of{" "}
{data.jobs.length} jobs healthy
</CardDescription>
</div>
</div>
</CardContent>
<CardContent className="border-t border-border/30 pt-4">
<div className="space-y-1.5">
{data.jobs.map((job) => (
<div
key={job.jobName}
className={`grid grid-cols-[auto_1fr_auto_auto] items-center gap-x-2.5 ${
job.isCurrentlyRunning ? "animate-pulse" : ""
}`}
>
{job.isCurrentlyRunning ? (
<Spinner className="size-2.5" />
) : job.lastStatus === null ? (
<StatusDot status="inactive" />
) : job.lastStatus === "success" ? (
<StatusDot status="ok" />
) : (
<StatusDot status="error" />
)}
<span className="text-xs text-muted-foreground">
{JOB_LABELS[job.jobName] ?? job.jobName}
</span>
{job.lastRunAt ? (
<span
className="text-right text-[11px] text-muted-foreground/50"
suppressHydrationWarning
>
{formatDistanceToNow(new Date(job.lastRunAt), {
addSuffix: true,
})}
</span>
) : (
<span className="text-[11px] text-muted-foreground/30">
</span>
)}
{job.lastDurationMs !== null ? (
<span className="w-12 text-right font-mono text-[11px] text-muted-foreground/40">
{formatDuration(job.lastDurationMs)}
</span>
) : (
<span className="w-12" />
)}
</div>
))}
</div>
</CardContent>
</Card>
<BackgroundJobsCard
jobs={data.jobs}
onRefresh={() => fetchHealth(true)}
/>
{/* ── Card 3: Storage ── */}
<Card className="border-l-2 border-l-primary/30">
@@ -320,7 +301,7 @@ export function SystemHealthCards() {
{/* Image cache */}
<CardContent className="border-t border-border/30 pt-4">
<div className="flex items-center justify-between">
<span className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground/40">
<span className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground/70">
Image cache
</span>
{data.imageCache.enabled ? (
@@ -334,7 +315,7 @@ export function SystemHealthCards() {
<p className="mt-1 text-xs text-muted-foreground">
{data.imageCache.imageCount.toLocaleString()} cached images
</p>
<p className="mt-0.5 text-[10px] leading-relaxed text-muted-foreground/30">
<p className="mt-0.5 text-[10px] leading-relaxed text-muted-foreground/50">
{Object.entries(data.imageCache.categories)
.map(([name, cat]) => `${name} ${cat.count}`)
.join(" · ")}
@@ -351,7 +332,7 @@ export function SystemHealthCards() {
{/* Backup summary */}
<CardContent className="border-t border-border/30 pt-4">
<div className="flex items-center justify-between">
<span className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground/40">
<span className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground/70">
Backups
</span>
{data.backups.backupCount > 0 && (
@@ -366,11 +347,10 @@ export function SystemHealthCards() {
suppressHydrationWarning
>
{data.backups.backupCount} backups · last{" "}
{data.backups.lastBackupAt
? formatDistanceToNow(new Date(data.backups.lastBackupAt), {
addSuffix: true,
})
: "unknown"}
<LiveTimeAgo
date={data.backups.lastBackupAt}
fallback="unknown"
/>
</p>
) : (
<p className="mt-1 flex items-center gap-1.5 text-xs text-muted-foreground/50">
@@ -383,3 +363,216 @@ export function SystemHealthCards() {
</div>
);
}
/** Background Jobs card with table layout and manual trigger */
function BackgroundJobsCard({
jobs,
onRefresh,
}: {
jobs: SystemHealthData["jobs"];
onRefresh: () => void;
}) {
const [triggeringJob, setTriggeringJob] = useState<string | null>(null);
const handleTrigger = async (jobName: string) => {
setTriggeringJob(jobName);
try {
const res = await fetch("/api/admin/jobs/trigger", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ jobName }),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data.error || "Failed to trigger job");
}
toast.success(`${JOB_LABELS[jobName] ?? jobName} triggered`);
// Refresh after a brief delay so the run shows up
setTimeout(onRefresh, 1500);
} catch (err) {
toast.error(err instanceof Error ? err.message : "Failed to trigger job");
} finally {
setTriggeringJob(null);
}
};
const healthyCount = jobs.filter((j) => j.lastStatus === "success").length;
return (
<Card className="border-l-2 border-l-primary/30">
<CardContent>
<div className="flex items-start gap-3">
<div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10">
<IconCalendarCheck className="size-4 text-primary" />
</div>
<div>
<CardTitle>Background jobs</CardTitle>
<CardDescription>
{healthyCount} of {jobs.length} jobs healthy
</CardDescription>
</div>
</div>
</CardContent>
<CardContent className="border-t border-border/30 px-0 pt-0 pb-0">
<Table>
<TableHeader>
<TableRow className="border-b-border/30 hover:bg-transparent">
<TableHead className="h-8 pl-5 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
Job
</TableHead>
<TableHead className="h-8 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
Schedule
</TableHead>
<TableHead className="h-8 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
Last run
</TableHead>
<TableHead className="h-8 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
Next run
</TableHead>
<TableHead className="h-8 pr-5 text-right text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
<span className="sr-only">Actions</span>
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{jobs.map((job) => {
const isTriggering = triggeringJob === job.jobName;
const isRunning = job.isCurrentlyRunning || isTriggering;
return (
<TableRow
key={job.jobName}
className="border-b-border/20 hover:bg-muted/30"
>
{/* Job name + status */}
<TableCell className="pl-5">
<div className="flex items-center gap-2">
{isRunning ? (
<Spinner className="size-2.5" />
) : job.lastStatus === null ? (
<StatusDot status="inactive" label="Never run" />
) : job.lastStatus === "success" ? (
<StatusDot status="ok" label="Last run succeeded" />
) : (
<StatusDot
status="error"
label={job.lastError ?? "Last run failed"}
/>
)}
<span className="text-xs text-muted-foreground">
{JOB_LABELS[job.jobName] ?? job.jobName}
</span>
</div>
</TableCell>
{/* Schedule */}
<TableCell>
{job.cronPattern ? (
<Tooltip>
<TooltipTrigger className="cursor-default">
<span className="text-xs text-muted-foreground/80">
{cronToHuman(job.cronPattern)}
</span>
</TooltipTrigger>
<TooltipContent>
<span className="font-mono">{job.cronPattern}</span>
</TooltipContent>
</Tooltip>
) : (
<span className="text-xs text-muted-foreground/50">
</span>
)}
</TableCell>
{/* Last run */}
<TableCell>
{job.lastRunAt ? (
<Tooltip>
<TooltipTrigger className="cursor-default">
<div className="flex items-baseline gap-1.5">
<span
className="text-xs text-muted-foreground/80"
suppressHydrationWarning
>
<LiveTimeAgo date={job.lastRunAt} />
</span>
{job.lastDurationMs !== null &&
job.lastDurationMs > 0 && (
<span className="font-mono text-[10px] text-muted-foreground/50">
{formatDuration(job.lastDurationMs)}
</span>
)}
</div>
</TooltipTrigger>
<TooltipContent>
{new Date(job.lastRunAt).toLocaleString()}
{job.lastError && (
<div className="mt-1 text-destructive">
{job.lastError}
</div>
)}
</TooltipContent>
</Tooltip>
) : (
<span className="text-xs text-muted-foreground/50">
Never
</span>
)}
</TableCell>
{/* Next run */}
<TableCell>
{job.nextRunAt ? (
<Tooltip>
<TooltipTrigger className="cursor-default">
<span
className="text-xs text-muted-foreground/80"
suppressHydrationWarning
>
<LiveTimeAgo date={job.nextRunAt} />
</span>
</TooltipTrigger>
<TooltipContent>
{new Date(job.nextRunAt).toLocaleString()}
</TooltipContent>
</Tooltip>
) : (
<span className="text-xs text-muted-foreground/50">
</span>
)}
</TableCell>
{/* Trigger button */}
<TableCell className="pr-5 text-right">
<Tooltip>
<TooltipTrigger
render={
<Button
variant="ghost"
size="icon"
className="size-6"
disabled={isRunning}
onClick={() => handleTrigger(job.jobName)}
/>
}
>
{isRunning ? (
<Spinner className="size-3" />
) : (
<IconPlayerPlay className="size-3 text-muted-foreground/50" />
)}
</TooltipTrigger>
<TooltipContent>Run now</TooltipContent>
</Tooltip>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</CardContent>
</Card>
);
}
@@ -1,6 +1,6 @@
"use client";
import { IconCloudDownload } from "@tabler/icons-react";
import { IconWorldUpload } from "@tabler/icons-react";
import { useState } from "react";
import { toast } from "sonner";
import { CardContent, CardDescription, CardTitle } from "@/components/ui/card";
@@ -37,7 +37,7 @@ export function UpdateCheckSection({
<div className="flex items-center justify-between gap-4">
<div className="flex items-start gap-3">
<div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10">
<IconCloudDownload className="size-4 text-primary" />
<IconWorldUpload className="size-4 text-primary" />
</div>
<div>
<CardTitle>Automatic update checks</CardTitle>
+114 -97
View File
@@ -1,6 +1,7 @@
"use client";
import {
IconBook2,
IconCheck,
IconChevronDown,
IconCopy,
@@ -25,7 +26,6 @@ import {
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import {
Tooltip,
TooltipContent,
@@ -55,13 +55,8 @@ export function WebhookCard({
}: {
provider: "plex" | "jellyfin" | "emby";
}) {
const {
connection,
handleConnect,
handleDelete,
handleRegenerateToken,
handleToggle,
} = useConnectionActions(provider);
const { connection, handleConnect, handleDelete, handleRegenerateToken } =
useConnectionActions(provider);
const [connecting, setConnecting] = useState(false);
const [copied, setCopied] = useState(false);
const [setupOpen, setSetupOpen] = useState(false);
@@ -107,7 +102,7 @@ export function WebhookCard({
{connection
? connection.lastEventAt
? `Last event ${formatDistanceToNow(new Date(connection.lastEventAt), { addSuffix: true })}`
: "Connected — no events yet"
: "Ready — no events yet"
: "Not configured"}
</CardDescription>
</div>
@@ -120,23 +115,11 @@ export function WebhookCard({
<CollapsibleContent className="h-[var(--collapsible-panel-height)] overflow-hidden transition-[height] duration-200 ease-out data-[ending-style]:h-0 data-[starting-style]:h-0">
<CardContent className="space-y-3 border-t border-border/30 pt-4">
{connection && (
<div className="flex items-center justify-between rounded-lg bg-muted/30 px-3 py-2">
<span className="text-xs text-muted-foreground">
Webhook {connection.enabled ? "enabled" : "disabled"}
</span>
<Switch
checked={connection.enabled}
onCheckedChange={(checked) => handleToggle(checked)}
/>
</div>
)}
{isPlex && (
<div className="flex gap-2.5 rounded-lg border border-primary/20 bg-primary/5 px-3 py-2.5">
<IconInfoCircle className="mt-0.5 size-3.5 shrink-0 text-primary" />
<p className="text-xs leading-relaxed text-foreground/80">
Plex webhooks require an active{" "}
Requires an active{" "}
<a
href="https://www.plex.tv/plex-pass/"
target="_blank"
@@ -155,7 +138,11 @@ export function WebhookCard({
<div className="flex gap-2.5 rounded-lg border border-primary/20 bg-primary/5 px-3 py-2.5">
<IconInfoCircle className="mt-0.5 size-3.5 shrink-0 text-primary" />
<p className="text-xs leading-relaxed text-foreground/80">
Emby webhooks require an active{" "}
Requires{" "}
<span className="font-medium text-foreground">
Emby Server 4.7.9+
</span>{" "}
and an active{" "}
<a
href="https://emby.media/premiere.html"
target="_blank"
@@ -165,7 +152,7 @@ export function WebhookCard({
<span>Emby Premiere</span>
<IconExternalLink className="inline-block size-3 translate-y-[-1px]" />
</a>{" "}
subscription.
license.
</p>
</div>
)}
@@ -174,6 +161,7 @@ export function WebhookCard({
<Button
onClick={onConnect}
disabled={connecting}
size="lg"
className="w-full"
>
{connecting ? "Connecting..." : `Connect ${label}`}
@@ -253,79 +241,108 @@ export function WebhookCard({
Setup instructions
</CollapsibleTrigger>
<CollapsibleContent className="h-[var(--collapsible-panel-height)] overflow-hidden transition-[height] duration-200 ease-out data-[ending-style]:h-0 data-[starting-style]:h-0">
<div className="mt-2 rounded-lg bg-muted/30 p-3 text-xs leading-relaxed text-muted-foreground">
{isPlex ? (
<ol className="list-inside list-decimal space-y-1.5">
<li>
Open Plex, go to{" "}
<span className="font-medium text-foreground">
Settings &gt; Webhooks
</span>
</li>
<li>
Click{" "}
<span className="font-medium text-foreground">
Add Webhook
</span>{" "}
and paste the URL above
</li>
<li>
Sofa will automatically log movies and episodes when you
finish watching them
</li>
</ol>
) : isEmby ? (
<ol className="list-inside list-decimal space-y-1.5">
<li>
Open Emby, go to{" "}
<span className="font-medium text-foreground">
Settings &gt; Webhooks
</span>
</li>
<li>Add a new webhook and paste the URL above</li>
<li>
Enable the{" "}
<span className="font-medium text-foreground">
Playback Stop
</span>{" "}
event type
</li>
<li>
Sofa will automatically log movies and episodes when you
finish watching them
</li>
</ol>
) : (
<ol className="list-inside list-decimal space-y-1.5">
<li>
Install the{" "}
<span className="font-medium text-foreground">
Webhook plugin
</span>{" "}
from Jellyfin&apos;s plugin catalog
</li>
<li>
Go to{" "}
<span className="font-medium text-foreground">
Dashboard &gt; Plugins &gt; Webhook
</span>
</li>
<li>
Add a{" "}
<span className="font-medium text-foreground">
Generic Destination
</span>{" "}
and paste the URL above
</li>
<li>
Enable the{" "}
<span className="font-medium text-foreground">
Playback Stop
</span>{" "}
notification type
</li>
</ol>
)}
<div className="mt-2 rounded-lg bg-muted/30 border border-border/50 p-3 text-xs leading-relaxed text-muted-foreground">
<ol className="list-inside list-decimal space-y-1.5">
{isPlex ? (
<>
<li>
Open Plex, go to{" "}
<a
href="https://app.plex.tv/desktop/#!/settings/webhooks"
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-0.5 font-medium text-foreground underline-offset-2 hover:underline"
>
Settings &gt; Webhooks
<IconExternalLink className="inline-block size-3 translate-y-[-1px]" />
</a>
</li>
<li>
Click{" "}
<span className="font-medium text-foreground">
Add Webhook
</span>{" "}
and paste the URL above
</li>
</>
) : isEmby ? (
<>
<li>
Open Emby, go to{" "}
<span className="font-medium text-foreground">
Settings &gt; Webhooks
</span>
</li>
<li>Add a new webhook and paste the URL above</li>
<li>
Enable the{" "}
<span className="font-medium text-foreground">
Playback
</span>{" "}
event category
</li>
</>
) : (
<>
<li>
Install the{" "}
<a
href="https://github.com/jellyfin/jellyfin-plugin-webhook/tree/master"
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-0.5 font-medium text-foreground underline-offset-2 hover:underline"
>
Webhook plugin
<IconExternalLink className="inline-block size-3 translate-y-[-1px]" />
</a>{" "}
from Jellyfin&apos;s plugin catalog
</li>
<li>
Go to{" "}
<span className="font-medium text-foreground">
Dashboard &gt; Plugins &gt; Webhook
</span>
</li>
<li>
Add a{" "}
<span className="font-medium text-foreground">
Generic Destination
</span>{" "}
and paste the URL above
</li>
<li>
Enable the{" "}
<span className="font-medium text-foreground">
Playback Stop
</span>{" "}
notification type
</li>
</>
)}
<li>
Sofa will automatically log movies and episodes when you
finish watching them
</li>
</ol>
<p className="mt-2 -ml-0.5">
<IconBook2 className="inline-block size-3 translate-y-[-1px] mr-1" />
Need more help?{" "}
<a
href={
isPlex
? "https://support.plex.tv/hc/en-us/articles/115002267687-Webhooks/"
: isEmby
? "https://emby.media/support/articles/Webhooks.html"
: "https://jellyfin.org/docs/general/server/notifications/"
}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-0.5 font-medium text-foreground underline-offset-2 hover:underline"
>
Open docs{" "}
<IconExternalLink className="inline-block size-3 translate-y-[-1px]" />
</a>
</p>
</div>
</CollapsibleContent>
</Collapsible>
+2 -2
View File
@@ -1,6 +1,6 @@
import {
IconDatabaseExport,
IconServerCog,
IconServer2,
IconShieldLock,
} from "@tabler/icons-react";
import { desc, eq } from "drizzle-orm";
@@ -154,7 +154,7 @@ export default async function SettingsPage() {
{/* Server health */}
<div>
<div className="mb-3 flex items-center gap-2">
<IconServerCog className="size-4 text-muted-foreground" />
<IconServer2 className="size-4 text-muted-foreground" />
<h2 className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
Server
</h2>
+31
View File
@@ -0,0 +1,31 @@
import { headers } from "next/headers";
import { NextResponse } from "next/server";
import { auth } from "@/lib/auth/server";
import { triggerJob } from "@/lib/cron";
export async function POST(request: Request) {
const session = await auth.api.getSession({ headers: await headers() });
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
if (session.user.role !== "admin") {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const body = await request.json();
const jobName = body?.jobName;
if (!jobName || typeof jobName !== "string") {
return NextResponse.json(
{ error: "Missing jobName in request body" },
{ status: 400 },
);
}
const triggered = await triggerJob(jobName);
if (!triggered) {
return NextResponse.json({ error: "Job not found" }, { status: 404 });
}
return NextResponse.json({ ok: true, jobName });
}
+4 -2
View File
@@ -5,10 +5,12 @@ import { getSystemHealth } from "@/lib/services/system-health";
export async function GET() {
const session = await auth.api.getSession({ headers: await headers() });
if (!session)
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
if (session.user.role !== "admin")
}
if (session.user.role !== "admin") {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const health = await getSystemHealth();
return NextResponse.json(health);
+4 -2
View File
@@ -5,10 +5,12 @@ import { getCachedUpdateCheck } from "@/lib/services/update-check";
export async function GET() {
const session = await auth.api.getSession({ headers: await headers() });
if (!session)
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
if (session.user.role !== "admin")
}
if (session.user.role !== "admin") {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const result = getCachedUpdateCheck();
return NextResponse.json(result);
+79
View File
@@ -0,0 +1,79 @@
"use client";
import { motion } from "motion/react";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
const colors = {
ok: { bg: "bg-green-500", shadow: "0 0 0 0px rgba(74,222,128,0.5)" },
error: { bg: "bg-destructive", shadow: "0 0 0 0px rgba(248,113,113,0.5)" },
warn: { bg: "bg-amber-500", shadow: "0 0 0 0px rgba(251,191,36,0.5)" },
inactive: { bg: "bg-muted-foreground/30", shadow: "" },
};
const pulseColors = {
ok: "0 0 0 4px rgba(74,222,128,0)",
error: "0 0 0 4px rgba(248,113,113,0)",
warn: "0 0 0 4px rgba(251,191,36,0)",
};
const defaultLabels: Record<string, string> = {
ok: "Healthy",
error: "Error",
warn: "Warning",
inactive: "Inactive",
};
/** Small colored status dot with a pulsing ring for active states. */
export function StatusDot({
status,
label,
className,
}: {
status: "ok" | "error" | "warn" | "inactive";
/** Tooltip text. Defaults to a label derived from the status. */
label?: string;
className?: string;
}) {
const { bg, shadow } = colors[status];
const pulse = status !== "inactive";
const tooltipText = label ?? defaultLabels[status];
const dotEl = pulse ? (
<motion.span
className={cn(
"inline-block h-2 w-2 shrink-0 rounded-full",
bg,
className,
)}
animate={{
boxShadow: [shadow, pulseColors[status as keyof typeof pulseColors]],
}}
transition={{
duration: 1.2,
repeat: Number.POSITIVE_INFINITY,
ease: "easeOut",
repeatDelay: 0.3,
}}
/>
) : (
<span
className={cn(
"inline-block h-2 w-2 shrink-0 rounded-full",
bg,
className,
)}
/>
);
return (
<Tooltip>
<TooltipTrigger className="cursor-default">{dotEl}</TooltipTrigger>
<TooltipContent>{tooltipText}</TooltipContent>
</Tooltip>
);
}
@@ -0,0 +1 @@
ALTER TABLE `cronRuns` ADD `durationMs` integer;
File diff suppressed because it is too large Load Diff
+34
View File
@@ -0,0 +1,34 @@
import { formatDistanceToNowStrict } from "date-fns";
import { useEffect, useEffectEvent, useState } from "react";
function toTimestamp(date: string | Date | null | undefined): number | null {
if (!date) return null;
const t = date instanceof Date ? date.getTime() : new Date(date).getTime();
return Number.isFinite(t) ? t : null;
}
export function useTimeAgo(
date: string | Date | null | undefined,
{ intervalMs = 1_000, addSuffix = true, fallback = "" } = {},
): string {
const ts = toTimestamp(date);
const [text, setText] = useState(() =>
ts === null ? fallback : formatDistanceToNowStrict(ts, { addSuffix }),
);
const tick = useEffectEvent(() => {
const next =
ts === null ? fallback : formatDistanceToNowStrict(ts, { addSuffix });
if (next !== text) setText(next);
});
useEffect(() => {
tick();
if (ts === null) return;
const id = setInterval(tick, intervalMs);
return () => clearInterval(id);
}, [ts, intervalMs]); // tick is NOT listed — that's the point
return text;
}
-18
View File
@@ -59,28 +59,10 @@ export function useConnectionActions(provider: "plex" | "jellyfin" | "emby") {
}
}, [provider, label, setConnections]);
const handleToggle = useCallback(
async (enabled: boolean) => {
const previous = connections;
setConnections((prev) =>
prev.map((c) => (c.provider === provider ? { ...c, enabled } : c)),
);
try {
await saveWebhookConnection(provider, enabled);
toast.success(`${label} webhook ${enabled ? "enabled" : "disabled"}`);
} catch {
setConnections(previous);
toast.error(`Failed to update ${label}`);
}
},
[provider, label, connections, setConnections],
);
return {
connection,
handleConnect,
handleDelete,
handleRegenerateToken,
handleToggle,
};
}
+27 -2
View File
@@ -51,6 +51,7 @@ function schedule(name: string, cron: string, handler: () => Promise<void>) {
name,
new Cron(cron, { name, protect: true }, async () => {
log.info(`Running job: ${name}`);
const startMs = performance.now();
const run = db
.insert(cronRuns)
.values({ jobName: name, status: "running", startedAt: new Date() })
@@ -58,16 +59,19 @@ function schedule(name: string, cron: string, handler: () => Promise<void>) {
.get();
try {
await handler();
const durationMs = Math.round(performance.now() - startMs);
db.update(cronRuns)
.set({ status: "success", finishedAt: new Date() })
.set({ status: "success", finishedAt: new Date(), durationMs })
.where(eq(cronRuns.id, run.id))
.run();
log.info(`Completed job: ${name}`);
log.info(`Completed job: ${name} (${durationMs}ms)`);
} catch (err) {
const durationMs = Math.round(performance.now() - startMs);
db.update(cronRuns)
.set({
status: "error",
finishedAt: new Date(),
durationMs,
errorMessage: err instanceof Error ? err.message : String(err),
})
.where(eq(cronRuns.id, run.id))
@@ -78,6 +82,27 @@ function schedule(name: string, cron: string, handler: () => Promise<void>) {
);
}
/** Get schedule metadata for all registered jobs */
export function getJobSchedules(): {
jobName: string;
pattern: string;
nextRunAt: string | null;
}[] {
return Array.from(jobs.entries()).map(([name, cron]) => ({
jobName: name,
pattern: cron.getPattern() ?? "",
nextRunAt: cron.nextRun()?.toISOString() ?? null,
}));
}
/** Manually trigger a job by name. Returns false if job not found. */
export async function triggerJob(name: string): Promise<boolean> {
const job = jobs.get(name);
if (!job) return false;
await job.trigger();
return true;
}
function getLibraryTitleIds(): string[] {
const rows = db
.select({ titleId: userTitleStatus.titleId })
+1
View File
@@ -350,6 +350,7 @@ export const cronRuns = sqliteTable(
}).notNull(),
startedAt: int("startedAt", { mode: "timestamp" }).notNull(),
finishedAt: int("finishedAt", { mode: "timestamp" }),
durationMs: int("durationMs"),
errorMessage: text("errorMessage"),
},
(table) => [
+14 -2
View File
@@ -32,6 +32,8 @@ export interface SystemHealthData {
};
jobs: {
jobName: string;
cronPattern: string | null;
nextRunAt: string | null;
lastRunAt: string | null;
lastDurationMs: number | null;
lastStatus: "running" | "success" | "error" | null;
@@ -143,6 +145,12 @@ async function getTmdbHealth(): Promise<SystemHealthData["tmdb"]> {
}
function getJobsHealth(): SystemHealthData["jobs"] {
// Lazy-import to avoid circular dependency issues at module level
const { getJobSchedules } =
require("@/lib/cron") as typeof import("@/lib/cron");
const schedules = getJobSchedules();
const scheduleMap = new Map(schedules.map((s) => [s.jobName, s]));
return JOB_NAMES.map((jobName) => {
const latest = db
.select()
@@ -153,14 +161,18 @@ function getJobsHealth(): SystemHealthData["jobs"] {
.get();
const isCurrentlyRunning = latest?.status === "running";
const schedule = scheduleMap.get(jobName);
let lastDurationMs: number | null = null;
if (latest?.finishedAt && latest.startedAt) {
// Prefer the in-memory durationMs column; fall back to timestamp diff
let lastDurationMs: number | null = latest?.durationMs ?? null;
if (lastDurationMs === null && latest?.finishedAt && latest.startedAt) {
lastDurationMs = latest.finishedAt.getTime() - latest.startedAt.getTime();
}
return {
jobName,
cronPattern: schedule?.pattern ?? null,
nextRunAt: schedule?.nextRunAt ?? null,
lastRunAt: latest?.startedAt?.toISOString() ?? null,
lastDurationMs,
lastStatus: (latest?.status as "running" | "success" | "error") ?? null,
+4 -4
View File
@@ -9,10 +9,10 @@
"lint": "biome check",
"format": "biome format --write",
"check-types": "tsc --noEmit",
"db:generate": "drizzle-kit generate",
"db:migrate": "drizzle-kit migrate",
"db:push": "drizzle-kit push",
"db:studio": "drizzle-kit studio"
"db:generate": "bun --bun drizzle-kit generate",
"db:migrate": "bun --bun drizzle-kit migrate",
"db:push": "bun --bun drizzle-kit push",
"db:studio": "bun --bun drizzle-kit studio"
},
"dependencies": {
"@base-ui/react": "1.2.0",