Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Show 14 days of backup job outcomes beside Backup health
rcourtmanc9c668bb6085
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 653ee593a4..4bc13c72e1 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -10625,6 +10625,17 @@ through both monitor initialization paths, including explicit and legacydefault organizations. These notifications refresh inventory presentation;they do not grant enrollment, removal, re-enrollment or command authority.+### Backup jobs history preserves lifecycle authority (2 November 2026)++`GET /api/backups/jobs` reads current tenant inventory and retained `pve-task:`+recovery evidence through `recovery.BuildBackupHealth`, behind the existing+authentication and `monitoring:read` scope. It summarizes outcomes only and adds+no agent enrollment, credential, command, collection or remediation authority;+it never triggers a poll or a backup. `backup_jobs_test.go` covers retained+history beyond the live window, unobserved and unavailable history, the+viewer's zone and method rejection. Collection and persistence proofs remain+owned by monitoring and storage-recovery.+### Backup health reporting preserves lifecycle authorityThe reporting API's `backup_health` schedule kind reads current tenant inventorydiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 959a2c3584..16ed9f8a64 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -2095,6 +2095,23 @@ files, owner, and comment. Recovery history may index those artifacts, but itmust not be the only API path for PBS protection or verification state when aplatform page needs source-native backup columns.+`/api/backups/jobs` owns summarized PVE backup job outcomes for the Backups+page: counts for the last 24 hours and for each of the last 14 days in the+viewer's `timezone` (an IANA name; anything unreadable is UTC), with a+`historyState` of `complete`, `partial`, `not_observed` or `unavailable` on the+window and on every day. It is built by `recovery.BuildBackupHealth` from+retained `pve-task:` history and its collection coverage, the authority behind+the backup health report, never from the live `/api/backups/pve` task list,+which spans only the latest collection window. Failures name the workload and+outcome only; provider error text stays out of this summary. Unreadable history+reports `unavailable` and zero counts, never a clean window. Only Proxmox VE+guests are rated, so another platform's VMs cannot mark every day partial.+Windows end at the oldest latest observation when every rated instance was+polled within 30 minutes (coverage ends at the last completed poll, so "now"+would read partial on every healthy install), and only tasks that started or+finished inside a window count there. Mock mode maps the fixture tasks the+same way and treats every rated instance as observed.+Hosted workspace handoff exchange is a canonical API/session payload boundary.`/api/cloud/handoff/exchange` may redirect to a tenant-local target path onlywhen that path is carried in the signed control-plane JWT as `target_path`.diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.mdindex 094f635375..495b429665 100644--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md@@ -508,6 +508,24 @@ desktop/narrow browser journeys cover the shared filter rail, keyboard/touchday selection, metric switching, empty matches and recovery. No shared-filter,route, navigation, access or backup operation changes.+### Backup jobs card composes the overview primitives (2 November 2026)++`ProxmoxBackupJobsCard` is a `TableCard` with a `TableCardHeader` strip, like+Backup health: last-24-hour outcome count pills in the header actions (they+wrap rather than clip, and failed and warning guests are named in their own+pill's title) and one stacked bar per calendar day. A day Pulse did not fully+observe keeps a dashed outline and says so in its accessible text; it is never+drawn as a clean empty day. Unavailable history replaces the pills with+"History unavailable" rather than zero counts.++`ProxmoxBackupsTable` takes the card through its `summaryAside` slot. The page+surface owns that read, so the table's inventory reads stay PVE plus PBS and+the slot renders identically in both route-backed views. The summary grid puts+the card beside Backup health from `xl` only while it renders and stacks it on+narrower screens. `ProxmoxBackupJobsCard.test.tsx` and+`proxmoxBackupJobs.test.ts` cover pill order, failure names, outlined days and+unavailable or malformed history.+### Backup activity uses calendar-day chart slotsThe Proxmox backup activity producer supplies one slot per consecutive localdiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 85838c232e..32a4cf68a7 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -5041,6 +5041,27 @@ read "0 protected, 38 attention", which left the operator counting rows tofind the cause; on the 932-guest mock it now reads as five lines. No posture,freshness or protection evaluation changes.+### Backup jobs show 14 days of retained outcomes beside Backup health (2 November 2026)++A Backup jobs card answers "did last night's backups run, and is that+normal?": last-24-hour outcome pills ("456 ok", "35 failed", "33 running") in+its header strip and one stacked bar per day for the last 14 local days. It+reads `/api/backups/jobs`, which summarizes retained `pve-task:` history+through `recovery.BuildBackupHealth`, so a multi-guest vzdump job counts+through its attributed guest results, a stale running observation is not+counted as running, and days Pulse did not fully observe are outlined rather+than drawn as clean empty days. The live `/api/backups/pve` task list spans+only the latest collection window and must not be used for this history.+Unreadable history, malformed counts or a failed read after history was shown+read "History unavailable", never zero failures. Failed and warning guests are+named in their own pill's hover title.++The card is a page-owned section passed into `ProxmoxBackupsTable` as+`summaryAside`, so the table keeps exactly its PVE and PBS inventory reads. It+renders nothing until a backup task is counted (a PVE install without vzdump+jobs collects successfully and finds nothing), and sits beside Backup health+from `xl` only when it renders.+### Backups page states its answer before its caveats (1 November 2026)The health strip's posture rule moved behind a collapsed "What the countsdiff --git a/frontend-modern/browser-verification/ce696240838bd5dd.json b/frontend-modern/browser-verification/ce696240838bd5dd.jsonnew file mode 100644index 0000000000..8bd8de39e8--- /dev/null+++ b/frontend-modern/browser-verification/ce696240838bd5dd.json@@ -0,0 +1,46 @@+{+ "version": 1,+ "base_sha": "daa183bfda853796173c8f5f0a1e04b4ff084fcb",+ "verified_at": "2026-11-02T00:37:45Z",+ "result": "passed",+ "changed_paths": [+ "frontend-modern/src/features/proxmox/ProxmoxBackupJobsCard.tsx",+ "frontend-modern/src/features/proxmox/ProxmoxBackupsTable.tsx",+ "frontend-modern/src/features/proxmox/ProxmoxPageSurface.tsx",+ "frontend-modern/src/features/proxmox/proxmoxBackupJobs.ts"+ ],+ "content_sha256": {+ "frontend-modern/src/features/proxmox/ProxmoxBackupJobsCard.tsx": "dc9cb13ab26b4d41a10a5c32279b8569e7b351c26bdc38a7725bec4f2d33ea6c",+ "frontend-modern/src/features/proxmox/ProxmoxBackupsTable.tsx": "4c253a21e3403932b177c485cab0f974838881c5736bce2e89e38f858bbd7387",+ "frontend-modern/src/features/proxmox/ProxmoxPageSurface.tsx": "6be3624ad2462702ca92f511ed92ab2d2d1004aa19e20ecb3c715dcefe9437b4",+ "frontend-modern/src/features/proxmox/proxmoxBackupJobs.ts": "23ee639676869317424bacb3282d3e066161e7b6a23ff14ba60295aefa0171e6"+ },+ "routes": [+ "/proxmox/backups/date",+ "/proxmox/backups/coverage"+ ],+ "viewports": [+ {+ "width": 1440,+ "height": 1000+ },+ {+ "width": 375,+ "height": 812+ }+ ],+ "states": [+ "private mock-mode backend built from this branch on pulse-dev, serving /api/backups/jobs from the fixture tasks",+ "backup jobs card beside Backup health at desktop width, stacked below it on phone",+ "dark theme, desktop and phone layouts"+ ],+ "interactions": [+ "signed in to the private mock backend and opened Backups By date at 1440x1000 and 375x812",+ "read the Backup jobs header strip: 619 ok, 33 running, 35 failed for the last 24 hours, with the 24h label from sm",+ "checked 14 day bars against /api/backups/jobs: every day observed, stacked ok/running/failed on today, thin baseline on observed days without backups",+ "confirmed the card sits beside Backup health at desktop width with equal height and stacks below it on phone, pills unwrapped",+ "after review fixes, rechecked that a healthy install reads complete (windows end at the last poll) and the 24h window counts only tasks that started or finished inside it",+ "before fixing mock coverage and the PVE-only guest filter, every day rendered outlined as not fully observed rather than clean",+ "no horizontal page overflow at either width"+ ]+}diff --git a/frontend-modern/src/features/proxmox/ProxmoxBackupJobsCard.tsx b/frontend-modern/src/features/proxmox/ProxmoxBackupJobsCard.tsxnew file mode 100644index 0000000000..a3a81792a0--- /dev/null+++ b/frontend-modern/src/features/proxmox/ProxmoxBackupJobsCard.tsx@@ -0,0 +1,226 @@+import { createMemo, For, Show, type Component } from 'solid-js';+import { createNonSuspendingQuery } from '@/hooks/createNonSuspendingQuery';+import { TableCard } from '@/components/shared/TableCard';+import { TableCardHeader } from '@/components/shared/TableCardHeader';+import { getRecoveryPrettyDateLabel } from '@/utils/recoveryDatePresentation';+import {+ backupJobsDayObserved,+ backupJobsHasHistory,+ backupJobsTotal,+ backupJobsUnavailable,+ fetchBackupJobs,+ type BackupJobsCounts,+ type BackupJobsDay,+ type BackupJobsPayload,+} from './proxmoxBackupJobs';++// "Did last night's backups run, and is that normal?" in the platform+// overview's vocabulary: last-24-hour outcome pills in the header strip and+// one stacked bar per day for the last 14 days. Days Pulse did not fully+// observe are outlined, never drawn as clean empty days.++type Outcome = keyof BackupJobsCounts;++const PILL_BASE =+ 'inline-flex items-center whitespace-nowrap rounded-md px-1.5 py-0.5 text-[11px] font-semibold tabular-nums';++const OUTCOMES: readonly {+ key: Outcome;+ label: string;+ pill: string;+ segment: string;+}[] = [+ {+ key: 'failed',+ label: 'failed',+ pill: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300',+ segment: 'bg-red-500',+ },+ {+ key: 'warning',+ label: 'warnings',+ pill: 'bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300',+ segment: 'bg-amber-500',+ },+ {+ key: 'running',+ label: 'running',+ pill: 'bg-sky-100 text-sky-700 dark:bg-sky-900/40 dark:text-sky-300',+ segment: 'bg-sky-400',+ },+ {+ key: 'unknown',+ label: 'unknown',+ pill: 'bg-surface-alt text-muted',+ segment: 'bg-slate-400',+ },+ {+ key: 'success',+ label: 'ok',+ pill: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300',+ segment: 'bg-emerald-500',+ },+];++const FAILED_NAMES = 8;++const describe = (counts: BackupJobsCounts): string => {+ const parts = OUTCOMES.filter(({ key }) => counts[key] > 0)+ .reverse()+ .map(({ key, label }) => `${counts[key]} ${label}`);+ return parts.length > 0 ? parts.join(', ') : 'no backups';+};++const dayTitle = (day: BackupJobsDay): string => {+ const date = getRecoveryPrettyDateLabel(day.date);+ const observed = backupJobsDayObserved(day) ? '' : ' (not fully observed)';+ return `${date}: ${describe(day.counts)}${observed}`;+};++export const ProxmoxBackupJobsCard: Component<{ jobs: BackupJobsPayload }> = (props) => {+ const last = () => props.jobs.last24h;+ const maxTotal = () => Math.max(1, ...props.jobs.days.map((day) => backupJobsTotal(day.counts)));+ const pills = () => {+ const counts = last().counts;+ const shown = OUTCOMES.filter(({ key }) => counts[key] > 0);+ return shown.length > 0 ? shown.reverse() : [OUTCOMES[OUTCOMES.length - 1]];+ };+ const namesFor = (outcome: string) => {+ const names = [+ ...new Set(+ last()+ .failures.filter((failure) => failure.outcome === outcome)+ .map((failure) => failure.workloadName),+ ),+ ];+ const shown = names.slice(0, FAILED_NAMES);+ const more = names.length - shown.length;+ return more > 0 ? `${shown.join(', ')} and ${more} more` : shown.join(', ');+ };+ const unavailable = () => props.jobs.historyState === 'unavailable';++ return (+ <TableCard class="flex h-full flex-col" data-backup-jobs={props.jobs.historyState}>+ <TableCardHeader+ title={+ <span class="inline-flex items-center gap-2 whitespace-nowrap">+ Backup jobs+ <span class="hidden font-medium normal-case tracking-normal sm:inline">14 days</span>+ </span>+ }+ actions={+ <Show+ when={!unavailable()}+ fallback={<span class="text-[11px] text-muted">History unavailable</span>}+ >+ <span+ class="inline-flex flex-wrap items-center justify-end gap-1.5"+ data-backup-jobs-last24h+ >+ <span class="hidden text-[10px] font-medium text-muted sm:inline">24h</span>+ <For each={pills()}>+ {(outcome) => (+ <span+ class={`${PILL_BASE} ${outcome.pill}`}+ title={+ outcome.key === 'failed'+ ? namesFor('failed')+ : outcome.key === 'warning'+ ? namesFor('warning')+ : undefined+ }+ data-backup-jobs-pill={outcome.key}+ >+ {last().counts[outcome.key]} {outcome.label}+ </span>+ )}+ </For>+ <Show when={last().historyState !== 'complete'}>+ <span+ class="text-[10px] font-medium text-muted"+ title="Pulse did not observe the whole window"+ >+ partial+ </span>+ </Show>+ </span>+ </Show>+ }+ />+ <div class="flex flex-1 flex-col px-3 pb-2 pt-3">+ <ol+ class="flex min-h-14 flex-1 items-end gap-1"+ aria-label={`Backups per day, last ${props.jobs.days.length} days`}+ >+ <For each={props.jobs.days}>+ {(day) => {+ const total = () => backupJobsTotal(day.counts);+ const observed = () => backupJobsDayObserved(day);+ return (+ <li+ class={`flex h-full min-w-0 flex-1 flex-col-reverse rounded-xs ${+ observed() ? '' : 'border border-dashed border-border'+ }`}+ title={dayTitle(day)}+ data-backup-jobs-day={observed() ? 'observed' : day.historyState}+ >+ <span class="sr-only">{dayTitle(day)}</span>+ <Show+ when={total() > 0}+ fallback={+ <Show when={observed()}>+ <span class="h-0.5 w-full rounded-xs bg-surface-hover" aria-hidden="true" />+ </Show>+ }+ >+ <For each={[...OUTCOMES].reverse()}>+ {(outcome) => (+ <Show when={day.counts[outcome.key] > 0}>+ <span+ class={`w-full first:rounded-b-xs last:rounded-t-xs ${outcome.segment}`}+ style={{+ height: `max(2px, ${(day.counts[outcome.key] / maxTotal()) * 100}%)`,+ }}+ aria-hidden="true"+ />+ </Show>+ )}+ </For>+ </Show>+ </li>+ );+ }}+ </For>+ </ol>+ <div class="mt-1 flex justify-between text-[10px] text-muted" aria-hidden="true">+ <span>{getRecoveryPrettyDateLabel(props.jobs.days[0]?.date ?? '')}</span>+ <span>Today</span>+ </div>+ </div>+ </TableCard>+ );+};++const BACKUP_JOBS_POLL_MS = 60_000;++// Owns the backup jobs read. Renders nothing until history exists, so a page+// without PVE backup jobs keeps Backup health alone at full width.+export const ProxmoxBackupJobsSection: Component = () => {+ const query = createNonSuspendingQuery({+ source: () => 'jobs',+ fetcher: (_source, signal) => fetchBackupJobs(signal),+ initialValue: null as BackupJobsPayload | null,+ pollMs: BACKUP_JOBS_POLL_MS,+ });+ // The last payload that was worth showing; a later failed read keeps the+ // card as unavailable rather than making history disappear.+ let lastShown: BackupJobsPayload | null = null;+ const shown = createMemo((): BackupJobsPayload | null => {+ if (query.error()) return lastShown ? backupJobsUnavailable(lastShown) : null;+ const jobs = query.value();+ const visible = jobs && jobs.days.length > 0 && backupJobsHasHistory(jobs) ? jobs : null;+ if (visible) lastShown = visible;+ return visible;+ });+ return <Show when={shown()}>{(jobs) => <ProxmoxBackupJobsCard jobs={jobs()} />}</Show>;+};diff --git a/frontend-modern/src/features/proxmox/ProxmoxBackupsTable.tsx b/frontend-modern/src/features/proxmox/ProxmoxBackupsTable.tsxindex ad8d1ce6c3..02f0f81600 100644--- a/frontend-modern/src/features/proxmox/ProxmoxBackupsTable.tsx+++ b/frontend-modern/src/features/proxmox/ProxmoxBackupsTable.tsx@@ -141,6 +141,9 @@ export const ProxmoxBackupsTable: Component<{emptyIcon: JSX.Element;workloads?: readonly Resource[];servers?: readonly Resource[];+ // A page-owned summary beside Backup health (the backup jobs card). It owns+ // its own read, so the table's inventory reads stay PVE plus PBS.+ summaryAside?: JSX.Element;}> = (props) => {let inspection: HTMLDivElement | undefined;// Recovering a read removes its notice (or the whole-inventory error).@@ -891,42 +894,48 @@ export const ProxmoxBackupsTable: Component<{</div></Show>- {/* The health strip renders identically in both route-backed views. */}- <ProxmoxBackupsCoverageStrip- title="Backup health"- rule={- <Show when={getBackupPostureRuleText(protectionPostures.policy())}>- {(rule) => <span data-coverage-posture-rule>{rule()}</span>}- </Show>- }- tail={- <span>- {recoveryModel().coverageSummary.recoverableArtifacts} completed restore{' '}- {recoveryModel().coverageSummary.recoverableArtifacts === 1 ? 'point' : 'points'}- {inventoryIncomplete() ? ' read' : ''}- <Show when={recoveryModel().coverageSummary.runningArtifacts > 0}>- {' · '}- {recoveryModel().coverageSummary.runningArtifacts} running- </Show>- <Show when={recoveryModel().coverageSummary.failedArtifacts > 0}>- {' · '}- {recoveryModel().coverageSummary.failedArtifacts} failed+ {/* The health and backup-job cards render identically in both+ route-backed views, side by side once there is room. */}+ <div class="grid gap-3 xl:[&:has([data-backup-jobs])]:grid-cols-[minmax(0,3fr)_minmax(0,2fr)]">+ <ProxmoxBackupsCoverageStrip+ title="Backup health"+ rule={+ <Show when={getBackupPostureRuleText(protectionPostures.policy())}>+ {(rule) => <span data-coverage-posture-rule>{rule()}</span>}</Show>- <Show when={recoveryModel().coverageSummary.withPBS > 0}>- {' · '}- {recoveryModel().coverageSummary.withPBS} with{' '}- {getProxmoxBackupSourcePresentation('pbs').filterLabel}- </Show>- <Show when={orphanedTotalCount() > 0}>- {' · '}- {orphanedTotalCount()} unmatched- </Show>- </span>- }- verdict={backupVerdict()}- isGroupPressed={exceptionGroupPressed}- onSelectGroup={selectExceptionGroup}- />+ }+ tail={+ <span>+ {recoveryModel().coverageSummary.recoverableArtifacts} completed restore{' '}+ {recoveryModel().coverageSummary.recoverableArtifacts === 1+ ? 'point'+ : 'points'}+ {inventoryIncomplete() ? ' read' : ''}+ <Show when={recoveryModel().coverageSummary.runningArtifacts > 0}>+ {' · '}+ {recoveryModel().coverageSummary.runningArtifacts} running+ </Show>+ <Show when={recoveryModel().coverageSummary.failedArtifacts > 0}>+ {' · '}+ {recoveryModel().coverageSummary.failedArtifacts} failed+ </Show>+ <Show when={recoveryModel().coverageSummary.withPBS > 0}>+ {' · '}+ {recoveryModel().coverageSummary.withPBS} with{' '}+ {getProxmoxBackupSourcePresentation('pbs').filterLabel}+ </Show>+ <Show when={orphanedTotalCount() > 0}>+ {' · '}+ {orphanedTotalCount()} unmatched+ </Show>+ </span>+ }+ verdict={backupVerdict()}+ isGroupPressed={exceptionGroupPressed}+ onSelectGroup={selectExceptionGroup}+ />+ {props.summaryAside}+ </div><Show when={unreadBackupSourcesNotice()}>{(notice) => (diff --git a/frontend-modern/src/features/proxmox/ProxmoxPageSurface.tsx b/frontend-modern/src/features/proxmox/ProxmoxPageSurface.tsxindex d6d4219ef6..ce0f9cc738 100644--- a/frontend-modern/src/features/proxmox/ProxmoxPageSurface.tsx+++ b/frontend-modern/src/features/proxmox/ProxmoxPageSurface.tsx@@ -49,6 +49,7 @@ import {PlatformTableLoadingState,} from '@/features/platformPage/sharedPlatformPage';import { ProxmoxBackupsTable } from './ProxmoxBackupsTable';+import { ProxmoxBackupJobsSection } from './ProxmoxBackupJobsCard';import { ProxmoxCephTable } from './ProxmoxCephTable';import { ProxmoxMailGatewayTable } from './ProxmoxMailGatewayTable';import { ProxmoxNodesTable } from './ProxmoxNodesTable';@@ -434,6 +435,7 @@ export function ProxmoxPageSurface() {emptyIcon={<ProxmoxIcon class="h-6 w-6 text-slate-400" />}workloads={model().guests}servers={model().resources}+ summaryAside={<ProxmoxBackupJobsSection />}/></Show><Show when={activeTab() === 'ceph'}>diff --git a/frontend-modern/src/features/proxmox/__tests__/ProxmoxBackupJobsCard.test.tsx b/frontend-modern/src/features/proxmox/__tests__/ProxmoxBackupJobsCard.test.tsxnew file mode 100644index 0000000000..af81e8246a--- /dev/null+++ b/frontend-modern/src/features/proxmox/__tests__/ProxmoxBackupJobsCard.test.tsx@@ -0,0 +1,105 @@+import { render, screen, within } from '@solidjs/testing-library';+import { describe, expect, it } from 'vitest';+import { ProxmoxBackupJobsCard } from '../ProxmoxBackupJobsCard';+import type { BackupJobsDay, BackupJobsPayload } from '../proxmoxBackupJobs';++const counts = (success = 0, failed = 0, running = 0) => ({+ success,+ failed,+ warning: 0,+ running,+ unknown: 0,+});++const days = (overrides: Partial<Record<number, Partial<BackupJobsDay>>> = {}): BackupJobsDay[] =>+ Array.from({ length: 14 }, (_, i) => ({+ date: `2026-10-${String(19 + i).padStart(2, '0')}`,+ historyState: 'complete' as const,+ counts: counts(10),+ ...overrides[i],+ }));++const payload = (overrides: Partial<BackupJobsPayload> = {}): BackupJobsPayload => ({+ historyState: 'complete',+ timezone: 'UTC',+ last24h: {+ historyState: 'complete',+ counts: counts(456, 35, 33),+ failures: [+ { workloadId: 'vm-1', workloadName: 'web', instance: 'lab', at: '', outcome: 'failed' },+ { workloadId: 'vm-2', workloadName: 'db', instance: 'lab', at: '', outcome: 'failed' },+ { workloadId: 'vm-3', workloadName: 'cache', instance: 'lab', at: '', outcome: 'warning' },+ ],+ },+ days: days(),+ ...overrides,+});++describe('ProxmoxBackupJobsCard', () => {+ it('shows the last 24 hours as outcome pills and names failures on hover', () => {+ const { container } = render(() => <ProxmoxBackupJobsCard jobs={payload()} />);+ const pills = container.querySelectorAll('[data-backup-jobs-pill]');+ expect([...pills].map((pill) => pill.textContent)).toEqual([+ '456 ok',+ '33 running',+ '35 failed',+ ]);+ // Warnings are not named as failures.+ expect(container.querySelector('[data-backup-jobs-pill="failed"]')).toHaveAttribute(+ 'title',+ 'web, db',+ );+ });++ it('draws one bar per day and outlines days Pulse did not fully observe', () => {+ render(() => (+ <ProxmoxBackupJobsCard+ jobs={payload({+ historyState: 'partial',+ days: days({+ 0: { historyState: 'partial', counts: counts() },+ 13: { counts: counts(3, 1) },+ }),+ })}+ />+ ));+ const list = within(screen.getByRole('list', { name: 'Backups per day, last 14 days' }));+ const items = list.getAllByRole('listitem');+ expect(items).toHaveLength(14);+ expect(items[0]).toHaveAttribute('data-backup-jobs-day', 'partial');+ expect(items[0]).toHaveClass('border-dashed');+ expect(items[13]).toHaveAttribute('data-backup-jobs-day', 'observed');+ expect(items[13]).toHaveTextContent('3 ok, 1 failed');+ expect(items[0]).toHaveTextContent('no backups (not fully observed)');+ });++ it('says so when no backup ran in the last 24 hours', () => {+ const { container } = render(() => (+ <ProxmoxBackupJobsCard+ jobs={payload({ last24h: { historyState: 'complete', counts: counts(), failures: [] } })}+ />+ ));+ expect(container.querySelector('[data-backup-jobs-pill]')).toHaveTextContent('0 ok');+ });++ it('never presents unreadable history as counts', () => {+ const { container } = render(() => (+ <ProxmoxBackupJobsCard+ jobs={payload({+ historyState: 'unavailable',+ last24h: { historyState: 'unavailable', counts: counts(), failures: [] },+ days: days(+ Object.fromEntries(+ Array.from({ length: 14 }, (_, i) => [+ i,+ { historyState: 'unavailable', counts: counts() },+ ]),+ ),+ ),+ })}+ />+ ));+ expect(container).toHaveTextContent('History unavailable');+ expect(container.querySelector('[data-backup-jobs-pill]')).toBeNull();+ });+});diff --git a/frontend-modern/src/features/proxmox/__tests__/ProxmoxBackupsTable.test.tsx b/frontend-modern/src/features/proxmox/__tests__/ProxmoxBackupsTable.test.tsxindex 5be2529c70..62833bedc5 100644--- a/frontend-modern/src/features/proxmox/__tests__/ProxmoxBackupsTable.test.tsx+++ b/frontend-modern/src/features/proxmox/__tests__/ProxmoxBackupsTable.test.tsx@@ -786,6 +786,31 @@ describe('ProxmoxBackupsTable', () => {expect(screen.queryByRole('button', { name: '1 attention' })).toBeNull();});+ it('places a page-owned summary beside Backup health', async () => {+ mockBackupAPIs('attention');+ window.history.replaceState({}, '', '/proxmox/backups/date');++ renderInRouter(() => (+ <ProxmoxBackupsTable+ emptyIcon={<span />}+ workloads={[workloadResource]}+ summaryAside={<section data-backup-jobs="complete">Backup jobs</section>}+ />+ ));++ const verdict = await waitFor(() => {+ const element = document.querySelector('[data-backup-verdict]');+ expect(element).toHaveTextContent('0 of 1 protected');+ return element!;+ });+ const aside = document.querySelector('[data-backup-jobs]')!;+ const grid = aside.parentElement!;+ // Same summary grid as the health card, which goes two-up from xl only+ // while the jobs card renders.+ expect(grid).toContainElement(verdict as HTMLElement);+ expect(grid.className).toContain('xl:[&:has([data-backup-jobs])]:grid-cols-');+ });+it('lets a backup exception group filter Coverage to those workloads', async () => {// "17 attention" was text: finding which workloads it counted took the// Filters sheet on a phone. A group is one tap to exactly its workloads.diff --git a/frontend-modern/src/features/proxmox/__tests__/proxmoxBackupJobs.test.ts b/frontend-modern/src/features/proxmox/__tests__/proxmoxBackupJobs.test.tsnew file mode 100644index 0000000000..4b3b61987b--- /dev/null+++ b/frontend-modern/src/features/proxmox/__tests__/proxmoxBackupJobs.test.ts@@ -0,0 +1,102 @@+import { describe, expect, it } from 'vitest';+import {+ backupJobsDayObserved,+ backupJobsHasHistory,+ backupJobsTotal,+ parseBackupJobsPayload,+} from '../proxmoxBackupJobs';++const counts = (success = 0, failed = 0) => ({+ success,+ failed,+ warning: 0,+ running: 0,+ unknown: 0,+});++const body = (overrides: Record<string, unknown> = {}) => ({+ data: {+ historyState: 'complete',+ timezone: 'Europe/London',+ last24h: {+ historyState: 'complete',+ counts: counts(3, 1),+ failures: [+ {+ workloadId: 'vm-100',+ workloadName: 'web',+ instance: 'lab',+ at: '2026-11-01T02:00:00Z',+ outcome: 'failed',+ },+ ],+ },+ days: [+ { date: '2026-10-31', historyState: 'complete', counts: counts(4) },+ { date: '2026-11-01', historyState: 'complete', counts: counts(3, 1) },+ ],+ ...overrides,+ },+});++describe('parseBackupJobsPayload', () => {+ it('reads the server summary as sent', () => {+ const payload = parseBackupJobsPayload(body());+ expect(payload?.last24h.counts).toEqual(counts(3, 1));+ expect(payload?.last24h.failures[0].workloadName).toBe('web');+ expect(payload?.days).toHaveLength(2);+ });++ it('treats an unknown history state as unavailable, never clean', () => {+ const payload = parseBackupJobsPayload(+ body({+ historyState: 'fine',+ days: [{ date: '2026-11-01', historyState: 'later', counts: counts() }],+ }),+ );+ expect(payload?.historyState).toBe('unavailable');+ expect(payload?.days[0].historyState).toBe('unavailable');+ expect(backupJobsDayObserved(payload!.days[0])).toBe(false);+ });++ it('rejects a body without days and never turns bad counts into a clean day', () => {+ expect(parseBackupJobsPayload({})).toBeNull();+ expect(parseBackupJobsPayload({ data: { days: 'no' } })).toBeNull();+ const payload = parseBackupJobsPayload(+ body({+ days: [+ { date: '2026-11-01', historyState: 'complete', counts: { success: -2, failed: 'x' } },+ ],+ }),+ );+ expect(backupJobsTotal(payload!.days[0].counts)).toBe(0);+ expect(payload!.days[0].historyState).toBe('unavailable');+ expect(backupJobsDayObserved(payload!.days[0])).toBe(false);+ });+});++describe('backupJobsHasHistory', () => {+ it('hides the card until a backup task is counted, but never hides a read failure', () => {+ expect(backupJobsHasHistory(null)).toBe(false);+ const never = parseBackupJobsPayload(+ body({+ historyState: 'not_observed',+ last24h: { historyState: 'not_observed', counts: counts(), failures: [] },+ days: [{ date: '2026-11-01', historyState: 'not_observed', counts: counts() }],+ }),+ );+ expect(backupJobsHasHistory(never)).toBe(false);+ // Collected without error, but no vzdump job exists.+ const empty = parseBackupJobsPayload(+ body({+ last24h: { historyState: 'complete', counts: counts(), failures: [] },+ days: [{ date: '2026-11-01', historyState: 'complete', counts: counts() }],+ }),+ );+ expect(backupJobsHasHistory(empty)).toBe(false);+ expect(+ backupJobsHasHistory(parseBackupJobsPayload(body({ historyState: 'unavailable' }))),+ ).toBe(true);+ expect(backupJobsHasHistory(parseBackupJobsPayload(body()))).toBe(true);+ });+});diff --git a/frontend-modern/src/features/proxmox/proxmoxBackupJobs.ts b/frontend-modern/src/features/proxmox/proxmoxBackupJobs.tsnew file mode 100644index 0000000000..d97f59a25b--- /dev/null+++ b/frontend-modern/src/features/proxmox/proxmoxBackupJobs.ts@@ -0,0 +1,155 @@+import { apiFetch } from '@/utils/apiClient';++// PVE backup job outcomes from `GET /api/backups/jobs`: the last 24 hours and+// each of the last 14 local days, summarized server-side from retained task+// history by the same authority as the backup health report. The browser only+// presents them; it never re-derives outcomes from the live task list, which+// spans just the latest collection window.++export type BackupJobsHistoryState = 'complete' | 'partial' | 'not_observed' | 'unavailable';++export interface BackupJobsCounts {+ success: number;+ failed: number;+ warning: number;+ running: number;+ unknown: number;+}++export interface BackupJobsFailure {+ workloadId: string;+ workloadName: string;+ instance: string;+ at: string;+ outcome: string;+}++export interface BackupJobsDay {+ date: string;+ historyState: BackupJobsHistoryState;+ counts: BackupJobsCounts;+}++export interface BackupJobsPayload {+ historyState: BackupJobsHistoryState;+ timezone: string;+ last24h: {+ historyState: BackupJobsHistoryState;+ counts: BackupJobsCounts;+ failures: BackupJobsFailure[];+ };+ days: BackupJobsDay[];+}++const HISTORY_STATES = new Set<BackupJobsHistoryState>([+ 'complete',+ 'partial',+ 'not_observed',+ 'unavailable',+]);++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const isCount = (value: unknown): value is number =>+ typeof value === 'number' && Number.isInteger(value) && value >= 0;++const text = (value: unknown): string => (typeof value === 'string' ? value : '');++// An unknown or missing state reads as unavailable, never as clean history.+const historyState = (value: unknown): BackupJobsHistoryState =>+ HISTORY_STATES.has(value as BackupJobsHistoryState)+ ? (value as BackupJobsHistoryState)+ : 'unavailable';++const ZERO_COUNTS: BackupJobsCounts = { success: 0, failed: 0, warning: 0, running: 0, unknown: 0 };++// Unreadable counts must not become clean zeroes: the window that carried+// them reads unavailable instead.+const parseWindow = (+ counts: unknown,+ state: unknown,+): { counts: BackupJobsCounts; historyState: BackupJobsHistoryState } => {+ const record = isRecord(counts) ? counts : null;+ const keys = Object.keys(ZERO_COUNTS) as (keyof BackupJobsCounts)[];+ if (!record || !keys.every((key) => isCount(record[key]))) {+ return { counts: { ...ZERO_COUNTS }, historyState: 'unavailable' };+ }+ return {+ counts: Object.fromEntries(+ keys.map((key) => [key, record[key]]),+ ) as unknown as BackupJobsCounts,+ historyState: historyState(state),+ };+};++export function parseBackupJobsPayload(body: unknown): BackupJobsPayload | null {+ const data = isRecord(body) && isRecord(body.data) ? body.data : null;+ if (!data || !Array.isArray(data.days)) return null;+ const last = isRecord(data.last24h) ? data.last24h : {};+ return {+ historyState: historyState(data.historyState),+ timezone: text(data.timezone),+ last24h: {+ ...parseWindow(last.counts, last.historyState),+ failures: (Array.isArray(last.failures) ? last.failures : [])+ .filter(isRecord)+ .map((failure) => ({+ workloadId: text(failure.workloadId),+ workloadName: text(failure.workloadName),+ instance: text(failure.instance),+ at: text(failure.at),+ outcome: text(failure.outcome),+ })),+ },+ days: data.days.filter(isRecord).map((day) => ({+ date: text(day.date),+ ...parseWindow(day.counts, day.historyState),+ })),+ };+}++export async function fetchBackupJobs(signal: AbortSignal): Promise<BackupJobsPayload | null> {+ let timezone = '';+ try {+ timezone = Intl.DateTimeFormat().resolvedOptions().timeZone ?? '';+ } catch {+ timezone = '';+ }+ const query = timezone ? `?timezone=${encodeURIComponent(timezone)}` : '';+ const response = await apiFetch(`/api/backups/jobs${query}`, { signal });+ if (!response.ok) {+ throw Object.assign(new Error(`Failed to load backup jobs (${response.status})`), {+ status: response.status,+ });+ }+ return parseBackupJobsPayload(await response.json());+}++export const backupJobsTotal = (counts: BackupJobsCounts): number =>+ counts.success + counts.failed + counts.warning + counts.running + counts.unknown;++// A day Pulse did not fully observe is never drawn as a clean empty day.+export const backupJobsDayObserved = (day: BackupJobsDay): boolean =>+ day.historyState === 'complete';++// Coverage alone is not history: a PVE install without vzdump jobs collects+// successfully and finds nothing. Show the card once any task is counted, or+// when history could not be read, so a read failure is never silent.+export const backupJobsHasHistory = (payload: BackupJobsPayload | null): boolean =>+ payload !== null &&+ (payload.historyState === 'unavailable' ||+ backupJobsTotal(payload.last24h.counts) > 0 ||+ payload.days.some((day) => backupJobsTotal(day.counts) > 0));++// A failed read after history was shown keeps the card, marked unavailable.+export const backupJobsUnavailable = (previous: BackupJobsPayload): BackupJobsPayload => ({+ ...previous,+ historyState: 'unavailable',+ last24h: { historyState: 'unavailable', counts: { ...ZERO_COUNTS }, failures: [] },+ days: previous.days.map((day) => ({+ ...day,+ historyState: 'unavailable',+ counts: { ...ZERO_COUNTS },+ })),+});diff --git a/internal/api/backup_jobs.go b/internal/api/backup_jobs.gonew file mode 100644index 0000000000..3ce3113097--- /dev/null+++ b/internal/api/backup_jobs.go@@ -0,0 +1,289 @@+package api++import (+ "net/http"+ "strings"+ "time"++ "github.com/rs/zerolog/log"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/mock"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/internal/recovery"+ proxmoxrecoverymapper "github.com/rcourtman/pulse-go-rewrite/internal/recovery/mapper/proxmox"+ "github.com/rcourtman/pulse-go-rewrite/internal/recovery/model"+ "github.com/rcourtman/pulse-go-rewrite/internal/utils"+)++// BackupJobsResponse is the payload for `GET /api/backups/jobs`: PVE backup+// job outcomes for the last 24 hours and for each of the last 14 local days,+// summarized by recovery.BuildBackupHealth from retained task history (the+// same authority as the scheduled backup health report). The live+// /api/backups/pve task list only spans the latest collection window, so it+// cannot answer "is this normal compared with the last two weeks".+type BackupJobsResponse struct {+ Data BackupJobsPayload `json:"data"`+}++type BackupJobsPayload struct {+ // complete, partial, not_observed or unavailable, over the 14 days.+ HistoryState string `json:"historyState"`+ Timezone string `json:"timezone"`+ Last24h BackupJobsWindow `json:"last24h"`+ Days []BackupJobsDay `json:"days"`+}++type BackupJobsCounts struct {+ Success int `json:"success"`+ Failed int `json:"failed"`+ Warning int `json:"warning"`+ Running int `json:"running"`+ Unknown int `json:"unknown"`+}++type BackupJobsWindow struct {+ Start time.Time `json:"start"`+ End time.Time `json:"end"`+ HistoryState string `json:"historyState"`+ Counts BackupJobsCounts `json:"counts"`+ Failures []BackupJobsFailure `json:"failures"`+}++// BackupJobsFailure names the workload only. Provider error text stays in+// the task drill-down, outside this summary (BACKUP_TASK_TIMELINE_CONTRACT.md).+type BackupJobsFailure struct {+ WorkloadID string `json:"workloadId"`+ WorkloadName string `json:"workloadName"`+ Instance string `json:"instance"`+ At time.Time `json:"at"`+ Outcome string `json:"outcome"`+}++type BackupJobsDay struct {+ Date string `json:"date"`+ HistoryState string `json:"historyState"`+ Counts BackupJobsCounts `json:"counts"`+}++const backupJobsHistoryDays = 14++func (r *Router) handleBackupJobs(w http.ResponseWriter, req *http.Request) {+ if req.Method != http.MethodGet {+ writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed",+ "Only GET method is allowed", nil)+ return+ }+ monitor := r.getTenantMonitor(req.Context())+ if monitor == nil {+ writeErrorResponse(w, http.StatusInternalServerError, "no_monitor",+ "Monitor not available", nil)+ return+ }++ // Day boundaries follow the viewer's IANA zone; anything unreadable is UTC.+ location := time.UTC+ if name := strings.TrimSpace(req.URL.Query().Get("timezone")); name != "" {+ if loaded, err := time.LoadLocation(name); err == nil {+ location = loaded+ }+ }+ now := time.Now().UTC()+ from := backupJobsHistoryStart(now, location)++ resources, _ := monitor.UnifiedResourceSnapshot()+ all, err := backupHealthWorkloads(reportingEnrichmentSnapshot{Resources: resources}, config.ReportScheduleScope{})+ if err != nil {+ writeErrorResponse(w, http.StatusInternalServerError, "workloads_unavailable",+ "Backup job workloads are unavailable", nil)+ return+ }+ workloads := pveBackupJobWorkloads(all)++ var points []recovery.RecoveryPoint+ var coverage model.BackupHistoryCoverage+ available := true+ if mock.IsMockEnabled() {+ points, coverage = mockBackupJobHistory(monitor.PVEBackupsSnapshot().BackupTasks, workloads, from, now)+ } else if r.recoveryHandlers == nil {+ available = false+ } else if store, storeErr := r.recoveryHandlers.storeForOrg(GetOrgID(req.Context())); storeErr != nil {+ available = false+ log.Warn().Err(storeErr).Msg("Backup job history store unavailable")+ } else if points, coverage, err = store.BackupHealthHistory(req.Context(), from, now); err != nil {+ available = false+ log.Warn().Err(err).Msg("Backup job history unavailable")+ }++ payload := buildBackupJobsPayload(workloads, points, coverage, available, from, now, location)++ if err := utils.WriteJSONResponse(w, BackupJobsResponse{Data: payload}); err != nil {+ log.Error().Err(err).Msg("Failed to encode backup jobs response")+ }+}++// backupJobsHistoryStart is local midnight 13 days before today, so the+// window holds 14 whole local days ending now.+func backupJobsHistoryStart(now time.Time, location *time.Location) time.Time {+ local := now.In(location)+ return time.Date(local.Year(), local.Month(), local.Day(), 0, 0, 0, 0, location).+ AddDate(0, 0, -(backupJobsHistoryDays - 1)).UTC()+}++func buildBackupJobsPayload(+ workloads []model.BackupHealthWorkload,+ points []recovery.RecoveryPoint,+ coverage model.BackupHistoryCoverage,+ available bool,+ from, now time.Time,+ location *time.Location,+) BackupJobsPayload {+ to := backupJobsObservedThrough(workloads, coverage, now)+ lastFrom := now.Add(-24 * time.Hour)+ days := recovery.BuildBackupHealth(workloads, backupJobPointsSince(points, from), coverage, from, to, location)+ last := recovery.BuildBackupHealth(workloads, backupJobPointsSince(points, lastFrom), coverage, lastFrom, to, location)++ payload := BackupJobsPayload{+ HistoryState: days.HistoryState,+ Timezone: location.String(),+ Last24h: BackupJobsWindow{+ Start: last.Start,+ End: last.End,+ HistoryState: last.HistoryState,+ Counts: backupJobsCounts(last.Counts),+ Failures: make([]BackupJobsFailure, 0, len(last.Failures)),+ },+ Days: make([]BackupJobsDay, 0, len(days.Days)),+ }+ for _, failure := range last.Failures {+ payload.Last24h.Failures = append(payload.Last24h.Failures, BackupJobsFailure{+ WorkloadID: failure.WorkloadID,+ WorkloadName: failure.WorkloadName,+ Instance: failure.Instance,+ At: failure.At,+ Outcome: string(failure.Outcome),+ })+ }+ for _, day := range days.Days {+ payload.Days = append(payload.Days, BackupJobsDay{+ Date: day.Date,+ HistoryState: day.HistoryState,+ Counts: backupJobsCounts(day.Counts),+ })+ }+ if !available {+ // No successful backups are assumed when history cannot be read.+ payload.HistoryState = "unavailable"+ payload.Last24h.HistoryState = "unavailable"+ for i := range payload.Days {+ payload.Days[i].HistoryState = "unavailable"+ }+ }++ return payload+}++// pveBackupJobWorkloads keeps Proxmox VE guests only. A VM from another+// platform has no PVE instance; BuildBackupHealth would rate its empty+// instance as an unobserved source and mark every day partial.+func pveBackupJobWorkloads(workloads []model.BackupHealthWorkload) []model.BackupHealthWorkload {+ out := make([]model.BackupHealthWorkload, 0, len(workloads))+ for _, workload := range workloads {+ if workload.Instance != "" && workload.VMID > 0 {+ out = append(out, workload)+ }+ }+ return out+}++// Collection is recorded per completed poll, so coverage always ends a poll+// interval before the request. A window that ran to "now" would read partial+// on every healthy install. When every rated instance was observed within+// backupJobsCollectionGrace, the windows end at the oldest of those latest+// observations instead; anything staler keeps "now" and reads partial.+const backupJobsCollectionGrace = 30 * time.Minute++func backupJobsObservedThrough(workloads []model.BackupHealthWorkload, coverage model.BackupHistoryCoverage, now time.Time) time.Time {+ latest := map[string]time.Time{}+ for _, interval := range coverage.Intervals {+ if interval.Provider != recovery.ProviderProxmoxPVE {+ continue+ }+ if interval.End.After(latest[interval.Instance]) {+ latest[interval.Instance] = interval.End+ }+ }+ through := now+ for _, workload := range workloads {+ end, ok := latest[workload.Instance]+ if !ok || now.Sub(end) > backupJobsCollectionGrace {+ return now+ }+ if end.Before(through) {+ through = end+ }+ }+ return through+}++// backupJobPointsSince keeps tasks that started or finished inside a window.+// BuildBackupHealth clamps an unresolved older task to the window start, so+// one abandoned task would otherwise read "unknown" in every window.+func backupJobPointsSince(points []recovery.RecoveryPoint, start time.Time) []recovery.RecoveryPoint {+ out := make([]recovery.RecoveryPoint, 0, len(points))+ for _, point := range points {+ started := point.StartedAt != nil && !point.StartedAt.Before(start)+ finished := point.CompletedAt != nil && !point.CompletedAt.Before(start)+ if started || finished {+ out = append(out, point)+ }+ }+ return out+}++func backupJobsCounts(counts model.BackupOutcomeCounts) BackupJobsCounts {+ return BackupJobsCounts{+ Success: counts.Success,+ Failed: counts.Failed,+ Warning: counts.Warning,+ Running: counts.Running,+ Unknown: counts.Unknown,+ }+}++// Mock mode has no retained store. Its fixture tasks are the whole history,+// so map them as the monitor would and treat every rated instance as observed+// for the full window, as a polled real instance would be.+func mockBackupJobHistory(tasks []models.BackupTask, workloads []model.BackupHealthWorkload, from, to time.Time) ([]recovery.RecoveryPoint, model.BackupHistoryCoverage) {+ points, err := proxmoxrecoverymapper.FromPVEBackupTasksWithEvidence(tasks, nil, to)+ if err != nil {+ return nil, model.BackupHistoryCoverage{}+ }+ coverage := model.BackupHistoryCoverage{}+ seen := map[string]bool{}+ instances := make([]string, 0, len(tasks)+len(workloads))+ for _, task := range tasks {+ instances = append(instances, task.Instance)+ }+ for _, workload := range workloads {+ instances = append(instances, workload.Instance)+ }+ for _, instance := range instances {+ if instance == "" || seen[instance] {+ continue+ }+ seen[instance] = true+ coverage.Sources = append(coverage.Sources, model.BackupHistorySource{+ Provider: recovery.ProviderProxmoxPVE, Instance: instance,+ FirstObservedAt: from, LastObservedAt: to, Complete: true,+ })+ coverage.Intervals = append(coverage.Intervals, model.BackupHistoryInterval{+ Provider: recovery.ProviderProxmoxPVE, Instance: instance, Start: from, End: to,+ })+ }+ return points, coverage+}++func (r *Router) registerBackupJobsRoutes() {+ r.mux.HandleFunc("/api/backups/jobs", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.handleBackupJobs)))+}diff --git a/internal/api/backup_jobs_test.go b/internal/api/backup_jobs_test.gonew file mode 100644index 0000000000..11c85404b2--- /dev/null+++ b/internal/api/backup_jobs_test.go@@ -0,0 +1,177 @@+package api++import (+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/internal/recovery"+ "github.com/rcourtman/pulse-go-rewrite/internal/recovery/model"+ "github.com/stretchr/testify/require"+)++func backupJobsFixturePoint(id string, outcome recovery.Outcome, at time.Time, vmid int) recovery.RecoveryPoint {+ return recovery.RecoveryPoint{+ ID: "pve-task:" + id, Provider: recovery.ProviderProxmoxPVE, Kind: recovery.KindOther,+ Outcome: outcome, StartedAt: &at, CompletedAt: &at,+ Details: map[string]any{"instance": "lab", "vmid": vmid},+ }+}++func backupJobsFixtureCoverage(from, to time.Time) model.BackupHistoryCoverage {+ return model.BackupHistoryCoverage{+ Sources: []model.BackupHistorySource{{Provider: recovery.ProviderProxmoxPVE, Instance: "lab", FirstObservedAt: from, LastObservedAt: to, Complete: true}},+ Intervals: []model.BackupHistoryInterval{{Provider: recovery.ProviderProxmoxPVE, Instance: "lab", Start: from, End: to}},+ }+}++var backupJobsFixtureWorkloads = []model.BackupHealthWorkload{+ {ID: "vm-100", Name: "web", Instance: "lab", Type: "vm", VMID: 100},+ {ID: "vm-101", Name: "db", Instance: "lab", Type: "vm", VMID: 101},+}++func TestBackupJobsPayloadReadsRetainedHistoryBeyondTheLiveWindow(t *testing.T) {+ now := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)+ from := backupJobsHistoryStart(now, time.UTC)+ require.Equal(t, time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC), from)+ points := []recovery.RecoveryPoint{+ backupJobsFixturePoint("recent-failed", recovery.OutcomeFailed, now.Add(-2*time.Hour), 100),+ backupJobsFixturePoint("recent-ok", recovery.OutcomeSuccess, now.Add(-3*time.Hour), 101),+ // Ten days back: outside the live /api/backups/pve window, inside retention.+ backupJobsFixturePoint("old-ok", recovery.OutcomeSuccess, now.Add(-10*24*time.Hour), 100),+ }++ payload := buildBackupJobsPayload(backupJobsFixtureWorkloads, points, backupJobsFixtureCoverage(from.Add(-24*time.Hour), now), true, from, now, time.UTC)++ require.Equal(t, "complete", payload.HistoryState)+ require.Len(t, payload.Days, backupJobsHistoryDays)+ require.Equal(t, "2026-10-22", payload.Days[3].Date)+ require.Equal(t, 1, payload.Days[3].Counts.Success)+ require.Equal(t, BackupJobsCounts{Success: 1, Failed: 1}, payload.Days[13].Counts)+ require.Equal(t, BackupJobsCounts{Success: 1, Failed: 1}, payload.Last24h.Counts)+ require.Equal(t, "complete", payload.Last24h.HistoryState)+ require.Len(t, payload.Last24h.Failures, 1)+ require.Equal(t, "web", payload.Last24h.Failures[0].WorkloadName)+ require.Equal(t, "vm-100", payload.Last24h.Failures[0].WorkloadID)+ require.Equal(t, "failed", payload.Last24h.Failures[0].Outcome)+}++func TestBackupJobsPayloadMarksUnobservedDaysInsteadOfClean(t *testing.T) {+ now := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)+ from := backupJobsHistoryStart(now, time.UTC)+ // Pulse only started collecting three days ago.+ coverage := backupJobsFixtureCoverage(now.Add(-72*time.Hour), now)++ payload := buildBackupJobsPayload(backupJobsFixtureWorkloads, nil, coverage, true, from, now, time.UTC)++ require.Equal(t, "partial", payload.HistoryState)+ // Days before collection began are not clean history.+ require.Equal(t, "partial", payload.Days[0].HistoryState)+ require.Equal(t, "complete", payload.Days[13].HistoryState)+ require.Zero(t, payload.Days[0].Counts.Success+payload.Days[0].Counts.Failed)+}++func TestBackupJobsPayloadUnavailableHistoryNeverReadsAsClean(t *testing.T) {+ now := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)+ from := backupJobsHistoryStart(now, time.UTC)++ payload := buildBackupJobsPayload(backupJobsFixtureWorkloads, nil, model.BackupHistoryCoverage{}, false, from, now, time.UTC)++ require.Equal(t, "unavailable", payload.HistoryState)+ require.Equal(t, "unavailable", payload.Last24h.HistoryState)+ for _, day := range payload.Days {+ require.Equal(t, "unavailable", day.HistoryState, day.Date)+ }+ require.Empty(t, payload.Last24h.Failures)+}++func TestBackupJobsHistoryStartFollowsTheViewerZone(t *testing.T) {+ london, err := time.LoadLocation("Europe/London")+ require.NoError(t, err)+ // 23:30 UTC on 1 November is already 2 November in Auckland.+ now := time.Date(2026, 11, 1, 23, 30, 0, 0, time.UTC)+ // London is still on summer time on 19 October.+ require.Equal(t, time.Date(2026, 10, 19, 0, 0, 0, 0, london).UTC(), backupJobsHistoryStart(now, london))+ auckland, err := time.LoadLocation("Pacific/Auckland")+ require.NoError(t, err)+ require.Equal(t, time.Date(2026, 10, 20, 0, 0, 0, 0, auckland), backupJobsHistoryStart(now, auckland).In(auckland))+}++func TestMockBackupJobHistoryObservesFixtureInstances(t *testing.T) {+ now := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)+ from := backupJobsHistoryStart(now, time.UTC)+ tasks := []models.BackupTask{{+ ID: "lab-UPID:pve1:1:2:vzdump:100:root@pam:", Node: "pve1", Instance: "lab", Type: "vzdump",+ VMID: 100, Status: "OK", StartTime: now.Add(-time.Hour), EndTime: now.Add(-50 * time.Minute),+ }}++ // A second rated instance without fixture tasks still counts as observed.+ workloads := append([]model.BackupHealthWorkload{{ID: "vm-200", Name: "quiet", Instance: "edge", Type: "vm", VMID: 200}}, backupJobsFixtureWorkloads...)+ points, coverage := mockBackupJobHistory(tasks, workloads, from, now)++ require.Len(t, points, 1)+ require.True(t, strings.HasPrefix(points[0].ID, "pve-task:"))+ require.Len(t, coverage.Sources, 2)+ payload := buildBackupJobsPayload(workloads, points, coverage, true, from, now, time.UTC)+ require.Equal(t, 1, payload.Last24h.Counts.Success)+ require.Equal(t, "complete", payload.HistoryState)+ require.Equal(t, "complete", payload.Days[0].HistoryState)+}++func TestBackupJobsRejectsNonGet(t *testing.T) {+ router := &Router{}+ rec := httptest.NewRecorder()+ router.handleBackupJobs(rec, httptest.NewRequest(http.MethodPost, "/api/backups/jobs", nil))+ require.Equal(t, http.StatusMethodNotAllowed, rec.Code)+}++func TestBackupJobsRateProxmoxGuestsOnly(t *testing.T) {+ now := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)+ from := backupJobsHistoryStart(now, time.UTC)+ // A vSphere VM has no PVE instance or VMID.+ mixed := append([]model.BackupHealthWorkload{{ID: "vsphere-vm", Name: "esx-guest", Type: "vm"}}, backupJobsFixtureWorkloads...)++ workloads := pveBackupJobWorkloads(mixed)+ payload := buildBackupJobsPayload(workloads, nil, backupJobsFixtureCoverage(from, now), true, from, now, time.UTC)++ require.Len(t, workloads, 2)+ require.Equal(t, "complete", payload.HistoryState)+ require.Equal(t, "complete", payload.Days[0].HistoryState)+}++func TestBackupJobsHealthyPollLagIsNotPartial(t *testing.T) {+ now := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)+ from := backupJobsHistoryStart(now, time.UTC)+ // The last poll finished a minute ago, as on any healthy install.+ coverage := backupJobsFixtureCoverage(from.Add(-24*time.Hour), now.Add(-time.Minute))++ payload := buildBackupJobsPayload(backupJobsFixtureWorkloads, nil, coverage, true, from, now, time.UTC)+ require.Equal(t, "complete", payload.HistoryState)+ require.Equal(t, "complete", payload.Last24h.HistoryState)+ require.Equal(t, "complete", payload.Days[13].HistoryState)++ // Collection that stopped an hour ago is a real gap.+ stale := backupJobsFixtureCoverage(from.Add(-24*time.Hour), now.Add(-time.Hour))+ payload = buildBackupJobsPayload(backupJobsFixtureWorkloads, nil, stale, true, from, now, time.UTC)+ require.Equal(t, "partial", payload.Last24h.HistoryState)+ require.Equal(t, "partial", payload.Days[13].HistoryState)+}++func TestBackupJobsIgnoreAbandonedOlderTasks(t *testing.T) {+ now := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)+ from := backupJobsHistoryStart(now, time.UTC)+ started := now.Add(-20 * 24 * time.Hour)+ abandoned := recovery.RecoveryPoint{+ ID: "pve-task:abandoned", Provider: recovery.ProviderProxmoxPVE, Kind: recovery.KindOther,+ Outcome: recovery.OutcomeRunning, StartedAt: &started,+ Details: map[string]any{"instance": "lab", "vmid": 100},+ }++ payload := buildBackupJobsPayload(backupJobsFixtureWorkloads, []recovery.RecoveryPoint{abandoned}, backupJobsFixtureCoverage(from.Add(-24*time.Hour), now), true, from, now, time.UTC)++ require.Zero(t, payload.Last24h.Counts.Unknown+payload.Last24h.Counts.Running)+ require.Zero(t, payload.Days[0].Counts.Unknown+payload.Days[0].Counts.Running)+}diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 5e1c888a2d..40d0eba274 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -29150,3 +29150,46 @@ func TestContractReportDownloadWithdrawal(t *testing.T) {func TestContractAuditReadWithdrawal(t *testing.T) {auditReadNativeWithdrawal(t)}++// Pins the /api/backups/jobs payload the Backups page reads (BackupJobsCard).+func TestContract_BackupJobsPayloadJSONSnapshot(t *testing.T) {+ at := time.Date(2026, 11, 2, 1, 30, 0, 0, time.UTC)+ payload := BackupJobsResponse{Data: BackupJobsPayload{+ HistoryState: "partial",+ Timezone: "Europe/London",+ Last24h: BackupJobsWindow{+ Start: at.Add(-24 * time.Hour),+ End: at,+ HistoryState: "complete",+ Counts: BackupJobsCounts{Success: 3, Failed: 1},+ Failures: []BackupJobsFailure{{+ WorkloadID: "vm-100", WorkloadName: "web", Instance: "lab", At: at, Outcome: "failed",+ }},+ },+ Days: []BackupJobsDay{{+ Date: "2026-11-02",+ HistoryState: "not_observed",+ Counts: BackupJobsCounts{},+ }},+ }}++ got, err := json.Marshal(payload)+ if err != nil {+ t.Fatalf("marshal backup jobs payload: %v", err)+ }++ const want = `{"data":{+ "historyState":"partial",+ "timezone":"Europe/London",+ "last24h":{+ "start":"2026-11-01T01:30:00Z",+ "end":"2026-11-02T01:30:00Z",+ "historyState":"complete",+ "counts":{"success":3,"failed":1,"warning":0,"running":0,"unknown":0},+ "failures":[{"workloadId":"vm-100","workloadName":"web","instance":"lab","at":"2026-11-02T01:30:00Z","outcome":"failed"}]+ },+ "days":[{"date":"2026-11-02","historyState":"not_observed","counts":{"success":0,"failed":0,"warning":0,"running":0,"unknown":0}}]+ }}`++ assertJSONSnapshot(t, got, want)+}diff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.goindex 5e76d5736f..b57fb27b8c 100644--- a/internal/api/route_inventory_test.go+++ b/internal/api/route_inventory_test.go@@ -57,6 +57,39 @@ func TestReleaseNoteImageRouteAuthorization(t *testing.T) {}}+// /api/backups/jobs is registered from backup_jobs.go, outside the parsed+// router files, so its authentication and scope are pinned here.+func TestBackupJobsRouteAuthorization(t *testing.T) {+ const endpoint = "/api/backups/jobs"+ for _, tc := range []struct {+ name, token string+ scope string+ status int+ }{+ {name: "anonymous", status: http.StatusUnauthorized},+ {name: "agent-only token", token: "jobs-agent-token.12345678", scope: config.ScopeAgentReport, status: http.StatusForbidden},+ // Admitted: with no monitor wired the handler itself answers.+ {name: "monitoring reader", token: "jobs-monitor-token.12345678", scope: config.ScopeMonitoringRead, status: http.StatusInternalServerError},+ } {+ t.Run(tc.name, func(t *testing.T) {+ cfg := newTestConfigWithTokens(t, newTokenRecord(t, "configured-token.12345678", []string{config.ScopeMonitoringRead}, nil))+ if tc.token != "" {+ cfg = newTestConfigWithTokens(t, newTokenRecord(t, tc.token, []string{tc.scope}, nil))+ }+ router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")+ req := httptest.NewRequest(http.MethodGet, endpoint, nil)+ if tc.token != "" {+ req.Header.Set("X-API-Token", tc.token)+ }+ w := httptest.NewRecorder()+ router.Handler().ServeHTTP(w, req)+ if w.Code != tc.status {+ t.Fatalf("status = %d, want %d: %s", w.Code, tc.status, w.Body.String())+ }+ })+ }+}+func TestRouterRouteInventory(t *testing.T) {literalRoutes, dynamicRoutes, bareLiteralRoutes := parseRouterRoutes(t)diff --git a/internal/api/router_routes_monitoring.go b/internal/api/router_routes_monitoring.goindex 41586de126..1b0fc91bb5 100644--- a/internal/api/router_routes_monitoring.go+++ b/internal/api/router_routes_monitoring.go@@ -31,6 +31,7 @@ func (r *Router) registerMonitoringResourceRoutes(r.mux.HandleFunc("/api/recovery/postures", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.recoveryHandlers.HandleListProtectionPostures)))r.registerReplicationRoutes()r.registerPVEBackupsRoutes()+ r.registerBackupJobsRoutes()r.registerPBSBackupsRoutes()r.registerPMGRoutes()