Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

Make scheduled report delivery visible and recoverable

rcourtmanc4189614d840
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 33fec096ad..ca05293067 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -9284,6 +9284,9 @@ counts projected from existing action audit records.
The `patrol_digest` report schedule kind in `internal/api/report_schedules.go`
only reads the digest and sends an email. It issues no agent commands, plans
no actions, and changes no capability, token, or binding state.
+Persisted report attempts and email retries retain that boundary. Recovery of a
+report delivery never replays an infrastructure action or grants an agent new
+execution authority.
### Independent module CPU sampling baselines
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index f5c6b0e851..b4fb98c80d 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -13,6 +13,7 @@
"agent-lifecycle",
"ai-runtime",
"cloud-paid",
+ "notifications",
"patrol-intelligence"
]
}
@@ -825,10 +826,7 @@ failure retention require their own owner result, not source acceptance.
43. `internal/api/relay_hosted_runtime.go`
44. `internal/api/ai_hosted_runtime.go`
45. `internal/api/router_routes_licensing.go`
-46. `internal/api/reporting_inventory_handlers.go`
- 46a. `internal/api/report_schedules.go`
- 46b. `internal/config/report_schedules.go`
- 46c. `internal/notifications/email_enhanced.go`
+46. `internal/api/reporting_inventory_handlers.go`, `internal/api/report_schedules.go`, `internal/config/report_schedules.go` and the notification-owned delivery boundary in `internal/notifications/email_enhanced.go`
47. `internal/cloudcp/portal/bootstrap.go`
48. `internal/cloudcp/portal/handlers.go`
49. `internal/cloudcp/portal/page.go`
@@ -924,6 +922,12 @@ engine's `summary`), typed once as `AlertResolution` in
## Shared Boundaries
+Scheduled reporting owns report generation, persisted attempts and scheduling.
+Notifications owns SMTP configuration validation, MIME construction, structured
+failure classification and the completed-message acceptance boundary. Report
+retries must consume those shared verdicts rather than parse SMTP prose or
+create another transport retry loop.
+
- Quick security setup must synchronise the router-captured configurable authorizer when committing the local administrator identity, before establishing its session. The resulting Settings capabilities must grant both administrator-session surfaces and API Access/Pulse Intelligence permission surfaces without requiring a process restart. Permission checks and token scopes remain enforced for other identities.
### Notification recovery reload ownership
@@ -12058,8 +12062,9 @@ Attachment delivery through `internal/notifications/email_enhanced.go` uses
notifications-owned `sendEmailWithOptions`; reporting must not introduce a
separate retry classification. That transport stops on authentication,
configuration, or rejection failures and preserves temporary-failure retries.
-Its returned failure retains the structured cause and actual attempt count;
-this does not change report API schemas or prove recipient acceptance.
+Its returned failure retains the structured cause and actual attempt count.
+SMTP acceptance proves only that the configured server accepted the message,
+not that it reached the recipient's inbox.
`internal/notifications/email_retry_class_test.go` verifies the shared transport
failure boundary with in-memory SMTP replies, not end-to-end report delivery.
The transaction-stage regression matrix additionally checks MAIL, RCPT, DATA
@@ -12067,6 +12072,40 @@ command and completed-message rejections, including transient-then-accepted
termination. It exercises the shared sender with plain SMTP and no attachments;
it is not separate qualification of report rendering, TLS or report receipt.
+### Scheduled reports persist delivery outcomes and bounded retries
+
+`internal/config/report_schedules.go` owns the additive persisted schedule
+outcome fields. The report API distinguishes `running`, `retrying`, `ok`,
+`failed` and `unconfirmed`, records attempt count, next retry, last successful
+run, saved artifact and delivery result, and tolerates older schedules without
+those fields. Server-owned run fields cannot be supplied through schedule
+creation or overwritten through edits. The existing `advanced_reporting`
+capability, pricing, grants and retention limits remain unchanged.
+
+The list response adds per-schedule `delivery_checks`. Enabled email schedules
+require valid current notification configuration. A disabled draft can be
+saved for later. Static configuration checks do not prove connectivity or
+delivery. Every actual run rechecks the current entitlement and delivery
+configuration. Missing email configuration fails rather than masquerading as a
+successful disk fallback, and a requested attachment above the size limit
+fails clearly rather than silently sending a path-only notice.
+
+The scheduler persists the active attempt before external delivery. Safe
+transient email failures use the notification-owned retry verdict with a
+three-attempt budget and delays of one and five minutes. Pending retries
+survive restart. Resource report retries retain the original reporting window.
+Edits, disablement and deletion cancel pending retries. A completed-message
+connection loss, or a previous email run whose completion was not recorded,
+stays unconfirmed without automatic resend. The existing manual run endpoint
+accepts `retry=true` for deliberate recovery. A full schedule read/modify/write
+and execution share the reporting mutex so concurrent operations cannot
+overwrite a completed status or resurrect removed work.
+
+Proofs: `internal/api/report_schedule_delivery_test.go`,
+`internal/api/report_schedules_test.go`,
+`internal/config/report_schedule_delivery_test.go`,
+`internal/notifications/email_delivery_test.go` and the Reports browser receipt.
+
### Explicit historical incident archives
`internal/api/router.go` pins a read-only legacy archive to each organization's
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 681caca931..7814950fa0 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -8140,6 +8140,21 @@ flow, and `reportingSchedulesModel.ts` owns schedule payload normalization,
labels, default form state, and cadence formatting. Schedule scope selection
must reuse the shared `ResourcePicker` and reporting catalog types rather than
creating a separate resource selector or browser-local schedule API contract.
+The report list distinguishes saved files, SMTP acceptance, retry scheduling,
+terminal failure and unconfirmed delivery. SMTP acceptance must not be labelled
+as inbox receipt. Actionable delivery errors and the next automatic retry stay
+visible at narrow widths. Saved server paths and previous success times belong
+in the report details disclosure. A deliberate retry of unconfirmed delivery
+requires a duplicate warning. Active attempts and pending retries refresh from
+the server, and the browser never manufactures a delivery success. The existing
+advanced-reporting capability remains the access boundary. Proofs:
+`frontend-modern/src/components/Settings/__tests__/ReportingPanel.test.tsx`,
+`frontend-modern/src/components/Settings/__tests__/reportingSchedulesModel.delivery.test.ts`,
+`frontend-modern/src/components/Settings/__tests__/useReportingPanelState.test.ts`.
+The report list keeps status and Run/Retry visible at every width. Scope,
+recipients, file paths, Edit and Delete share the full-width details disclosure.
+Keyed store reconciliation preserves row identity, open details and keyboard
+focus across background refreshes.
The settings navigation model now exposes a single `infrastructure-systems`
sidebar entry for the infrastructure settings area. The former
`infrastructure-connections` and `infrastructure-install` entries have been
diff --git a/docs/release-control/v6/internal/subsystems/notifications.md b/docs/release-control/v6/internal/subsystems/notifications.md
index 4c30ccd353..9fffc000fb 100644
--- a/docs/release-control/v6/internal/subsystems/notifications.md
+++ b/docs/release-control/v6/internal/subsystems/notifications.md
@@ -735,9 +735,19 @@ resolved batches are not guaranteed to contain the same alert set and a
group-level reference would attach messages to the wrong thread.
Scheduled report delivery uses that same enhanced email boundary. Report
attachments must be emitted as MIME attachment parts by
-`internal/notifications/email_enhanced.go`, and oversized-report fallback copy
-belongs to the reporting scheduler. SMTP transport, recipient parsing,
+`internal/notifications/email_enhanced.go`. The scheduler owns report-size
+validation and the operator's attachment choice. SMTP transport, recipient parsing,
headers, body encoding, and attachment encoding remain notification-owned.
+`EnhancedEmailManager.ValidateConfiguration` checks the same sender/recipient
+and provider credential inputs without sending mail. A connection failure while
+awaiting the completed-message reply is a typed `EmailAcceptanceUnconfirmedError`.
+The sender stops its inner retry loop because the server may already have the
+message. Explicit SMTP replies still use the canonical failure classifier.
+`internal/notifications/email_delivery_test.go` checks configuration and a dropped
+completed-message response with an attachment. Report scheduling consumes that
+typed uncertainty rather than inferring rejection from a generic connection
+error. This does not assert inbox receipt or change the persistent alert queue's
+state vocabulary.
That same queue ownership also governs persistent queue storage roots. The
notifications queue database must normalize its owned data directory and
resolve the fixed `notification_queue.db` leaf through the shared storage-path
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index 40222a1441..ac9bcf8f62 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -2832,6 +2832,7 @@
"frontend-modern/src/utils/infrastructureSettingsPresentation.ts",
"internal/api/configapi/setup_script_render.go",
"internal/config/persistence_metadata_accessors.go",
+ "internal/config/report_schedules.go",
"internal/websocket/hub.go",
"pkg/aicontracts/action_broker.go",
"pkg/aicontracts/fix_execution.go",
@@ -3237,6 +3238,22 @@
"internal/api/route_inventory_test.go"
]
},
+ {
+ "id": "scheduled-report-delivery",
+ "label": "scheduled report persistence, delivery and retry proof",
+ "match_prefixes": [],
+ "match_files": [
+ "internal/api/report_schedules.go",
+ "internal/config/report_schedules.go"
+ ],
+ "allow_same_subsystem_tests": false,
+ "test_prefixes": [],
+ "exact_files": [
+ "internal/api/report_schedule_delivery_test.go",
+ "internal/api/report_schedules_test.go",
+ "internal/config/report_schedule_delivery_test.go"
+ ]
+ },
{
"id": "backend-payload-contracts",
"label": "backend API payload proof",
@@ -5314,6 +5331,7 @@
"frontend-modern/src/components/Settings/RecoverySettingsPanel.tsx",
"frontend-modern/src/components/Settings/ReportingPanel.tsx",
"frontend-modern/src/components/Settings/reportingPanelModel.ts",
+ "frontend-modern/src/components/Settings/reportingSchedulesModel.ts",
"frontend-modern/src/components/Settings/ResourcePicker.tsx",
"frontend-modern/src/components/Settings/SecurityAuthPanel.tsx",
"frontend-modern/src/components/Settings/SecurityOverviewPanel.tsx",
@@ -5682,6 +5700,7 @@
"frontend-modern/src/components/Settings/AvailabilitySettingsPanel.tsx",
"frontend-modern/src/components/Settings/ReportingPanel.tsx",
"frontend-modern/src/components/Settings/reportingPanelModel.ts",
+ "frontend-modern/src/components/Settings/reportingSchedulesModel.ts",
"frontend-modern/src/components/Settings/ResourcePicker.tsx",
"frontend-modern/src/components/Settings/SystemLogsPanel.tsx",
"frontend-modern/src/components/Settings/useReportingPanelState.ts",
@@ -5696,11 +5715,14 @@
"exact_files": [
"frontend-modern/src/__tests__/App.architecture.test.ts",
"frontend-modern/src/components/Settings/__tests__/AvailabilitySettingsPanel.test.tsx",
+ "frontend-modern/src/components/Settings/__tests__/ReportingPanel.test.tsx",
"frontend-modern/src/components/Settings/__tests__/reportingPanelModel.test.ts",
"frontend-modern/src/components/Settings/__tests__/reportingResourceTypes.test.ts",
+ "frontend-modern/src/components/Settings/__tests__/reportingSchedulesModel.delivery.test.ts",
"frontend-modern/src/components/Settings/__tests__/ResourcePicker.test.tsx",
"frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts",
"frontend-modern/src/components/Settings/__tests__/SystemLogsPanel.test.tsx",
+ "frontend-modern/src/components/Settings/__tests__/useReportingPanelState.test.ts",
"frontend-modern/src/routing/__tests__/routePreload.test.ts",
"frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts",
"frontend-modern/src/utils/__tests__/reportableResourceTypes.test.ts",
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 453af34825..95fdba0afa 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -1215,6 +1215,12 @@ PDF/CSV files are not recovery points, backup artifacts, storage-health
evidence, restore manifests, or cross-client storage inventory. Storage and
recovery flows may preserve them as normal tenant data during backup/restore,
but must not interpret their presence as infrastructure protection.
+Report attempt counts, retry deadlines and delivery outcomes are persisted
+alongside the tenant's schedule definitions. A saved report file is separate
+from an SMTP acceptance record and does not establish recipient receipt.
+Restart recovery preserves pending safe retries and marks an interrupted email
+attempt unconfirmed. These fields are normal tenant configuration data, not
+restore verification or independent proof of an external delivery.
Commercial downgrade preserves the schedule definitions as inert tenant
configuration and blocks background generation when `advanced_reporting` is
absent. Existing generated files outside the lower entitlement become hidden
diff --git a/frontend-modern/browser-verification/99a9747d121bbe9b.json b/frontend-modern/browser-verification/99a9747d121bbe9b.json
new file mode 100644
index 0000000000..ca18869948
--- /dev/null
+++ b/frontend-modern/browser-verification/99a9747d121bbe9b.json
@@ -0,0 +1,61 @@
+{
+ "version": 1,
+ "base_sha": "2cc581428273ea3bef085445bad8a23e8308cbb9",
+ "verified_at": "2026-10-17T09:46:30.269Z",
+ "result": "passed",
+ "changed_paths": [
+ "frontend-modern/src/components/Settings/ReportingPanel.tsx",
+ "frontend-modern/src/components/Settings/reportingSchedulesModel.ts",
+ "frontend-modern/src/components/Settings/useReportingPanelState.ts"
+ ],
+ "content_sha256": {
+ "frontend-modern/src/components/Settings/ReportingPanel.tsx": "9225c7de9530a6dc236b2ecbf317f762d2ee3ef63fd95d55651e13fdd3e00eef",
+ "frontend-modern/src/components/Settings/reportingSchedulesModel.ts": "dc38758cba08430f46263b9419bae641bfa7bcc372cf2799af0cf77756219df9",
+ "frontend-modern/src/components/Settings/useReportingPanelState.ts": "c0a400927f39ab2cb06f7944282e1f76cc71a4bd3533647530cccb0758764bf3"
+ },
+ "routes": [
+ "/settings/support/reporting",
+ "/alerts/notifications"
+ ],
+ "viewports": [
+ {
+ "width": 1440,
+ "height": 1000
+ },
+ {
+ "width": 820,
+ "height": 844
+ },
+ {
+ "width": 390,
+ "height": 844
+ }
+ ],
+ "states": [
+ "Confirmed empty list, initial list loading and initial load failure without a false empty-state message",
+ "Enabled email schedule refuses missing configuration; disabled draft remains saveable",
+ "Real CSV attachment accepted by local SMTP; inbox receipt remains explicitly unconfirmed",
+ "Real PDF saved on disk without sending email",
+ "451 temporary failure persists attempt count and retry deadline across a real process restart, then succeeds once on attempt 2 with the same reporting window",
+ "550 permanent rejection has no automatic retry and recovers through explicit Retry",
+ "Lost completed-message acknowledgement remains unconfirmed across reload; cancelling retry sends nothing",
+ "Controlled response fixtures additionally cover running, saved, accepted, retrying, failed and unconfirmed states"
+ ],
+ "interactions": [
+ "Create, edit, save and cancel; choose actual unified inventory resource; switch disk/email and PDF/CSV; inspect disabled recipients and attachment option",
+ "Navigate configuration remedy to Notifications; enable/disable persists through reload",
+ "Run and Retry remain visible and pointer-accessible at all three widths; hover/focus inspected and running disables Run",
+ "Expand/collapse report details, saved server path and edit/delete controls at every width; details stay open across polling",
+ "Cancel and accept the duplicate warning for uncertain delivery; inspect actual unconfirmed and rejected states",
+ "Cancel deletion preserves the schedule; confirm deletion removes it without resurrection",
+ "Refresh list failure/loading/recovery and return to page; review actual desktop, intermediate and narrow screenshots for wrapping, clipping and control placement"
+ ],
+ "environment": "Private runtime built from the verified working tree over base_sha, ephemeral signed Pro grant, dev/mock modes disabled. Synthetic infrastructure and local SMTP only.",
+ "backend_content_sha256": {
+ "internal/api/report_schedules.go": "e8f50c1f2b171134d7b9982ad46933e4b4f3f6e49dd9c381d82acfdcf206f675",
+ "internal/config/report_schedules.go": "2f19c181bd52741cc4ce720544a1d828ab64843685e9b492b2463527280643ca",
+ "internal/notifications/email_enhanced.go": "695e947fe7d9010863d7c8075d4977edde507cbb960108931e299c2c7bc67ae2"
+ },
+ "evidence": "/opt/pulse-release-worker/task-proofs/scheduled-reporting-20261017/browser-evidence",
+ "pixel_review": "Reviewed actual images for accepted delivery, pending retry, rejected and unconfirmed delivery, running, disk output, list failure, form states and expanded file details. Report names, status and recovery controls fit 1440, 820 and 390px."
+}
diff --git a/frontend-modern/src/components/Settings/ReportingPanel.tsx b/frontend-modern/src/components/Settings/ReportingPanel.tsx
index 8ad9a59e73..5d891d0263 100644
--- a/frontend-modern/src/components/Settings/ReportingPanel.tsx
+++ b/frontend-modern/src/components/Settings/ReportingPanel.tsx
@@ -4,7 +4,6 @@ import Download from 'lucide-solid/icons/download';
import BarChart from 'lucide-solid/icons/bar-chart';
import TableProperties from 'lucide-solid/icons/table-properties';
import Plus from 'lucide-solid/icons/plus';
-import EllipsisVertical from 'lucide-solid/icons/ellipsis-vertical';
import Pencil from 'lucide-solid/icons/pencil';
import Play from 'lucide-solid/icons/play';
import RefreshCw from 'lucide-solid/icons/refresh-cw';
@@ -27,7 +26,10 @@ import {
reportScheduleDeliveryLabel,
reportScheduleKindLabel,
reportScheduleLastRunLabel,
+ reportScheduleOutcomeDetail,
+ reportScheduleRunActionLabel,
reportScheduleScopeLabel,
+ type ReportSchedule,
type ReportScheduleKind,
} from '@/components/Settings/reportingSchedulesModel';
import { ResourcePicker } from './ResourcePicker';
@@ -109,6 +111,10 @@ export function ReportingPanel() {
updateScheduleForm,
upgradeDestination,
} = useReportingPanelState();
+ const visibleOutcome = (schedule: ReportSchedule): ReportSchedule =>
+ runningScheduleID() === schedule.id
+ ? { ...schedule, last_run_status: 'running', last_error: '' }
+ : schedule;
const performanceReport = () => reportingCatalog()?.performanceReport ?? null;
const isDigestForm = () => scheduleForm().kind === 'patrol_digest';
@@ -351,190 +357,169 @@ export function ReportingPanel() {
<Show
when={reportSchedules().length > 0}
fallback={
- <div class="flex flex-col gap-3 border border-dashed border-base-300 p-4 sm:flex-row sm:items-center sm:justify-between">
- <p class="text-sm text-muted">No scheduled reports are configured yet.</p>
- <Button
- variant="secondary"
- size="sm"
- class="gap-2"
- onClick={startCreateSchedule}
- >
- <Plus size={16} />
- Create schedule
- </Button>
- </div>
+ <Show when={!reportSchedulesLoading() && !reportSchedulesError()}>
+ <div class="flex flex-col gap-3 border border-dashed border-base-300 p-4 sm:flex-row sm:items-center sm:justify-between">
+ <p class="text-sm text-muted">No scheduled reports are configured yet.</p>
+ <Button
+ variant="secondary"
+ size="sm"
+ class="gap-2"
+ onClick={startCreateSchedule}
+ >
+ <Plus size={16} />
+ Create schedule
+ </Button>
+ </div>
+ </Show>
}
>
- <div class="table-scroll-shell overflow-x-auto rounded-md border border-base-300">
- <table class="w-full min-w-0 table-fixed text-left text-sm">
- <thead class="border-b border-base-300 bg-base-200/50 text-xs uppercase text-muted">
- <tr>
- <th class="w-[56%] px-3 py-2 font-semibold sm:w-[18%]">Name</th>
- <th class="hidden w-[16%] px-3 py-2 font-semibold sm:table-cell">
- Cadence
- </th>
- <th class="report-schedule-detail-column w-[14%] px-3 py-2 font-semibold">
- Scope
- </th>
- <th class="report-schedule-detail-column w-[14%] px-3 py-2 font-semibold">
- Delivery
- </th>
- <th class="hidden w-[16%] px-3 py-2 font-semibold sm:table-cell">
- Last run
- </th>
- <th class="w-[16%] px-3 py-2 font-semibold sm:w-[8%]">Enabled</th>
- <th class="w-[28%] px-3 py-2 text-right font-semibold sm:w-[14%]">
- Actions
- </th>
- </tr>
- </thead>
- <tbody class="divide-y divide-base-300">
- <For each={reportSchedules()}>
- {(schedule) => (
- <tr>
- <td
- class="truncate px-3 py-2 font-medium text-base-content"
- title={schedule.name}
- >
- {schedule.name}
- <span class="mt-0.5 block truncate text-xs font-normal text-muted sm:hidden">
- {reportScheduleCadenceLabel(schedule)}
- </span>
- </td>
- <td
- class="hidden truncate px-3 py-2 text-muted sm:table-cell"
- title={reportScheduleCadenceLabel(schedule)}
- >
+ <ul
+ class="divide-y divide-base-300 rounded-md border border-base-300 text-sm"
+ aria-label="Scheduled reports"
+ >
+ <For each={reportSchedules()}>
+ {(schedule) => (
+ <li class="space-y-3 p-3">
+ <div class="grid grid-cols-[minmax(0,1fr)_auto_auto] items-start gap-3">
+ <div class="min-w-0 whitespace-normal break-words">
+ <div class="font-medium text-base-content">{schedule.name}</div>
+ <div class="mt-1 text-xs text-muted">
{reportScheduleCadenceLabel(schedule)}
- </td>
- <td
- class="report-schedule-detail-column truncate px-3 py-2 text-muted"
- title={reportScheduleScopeLabel(schedule)}
+ </div>
+ <div class="mt-1 text-sm">
+ {reportScheduleLastRunLabel(visibleOutcome(schedule))}
+ </div>
+ <Show when={schedule.last_run_at}>
+ <div class="mt-0.5 text-xs text-muted">
+ {formatReportScheduleTime(schedule.last_run_at)}
+ </div>
+ </Show>
+ </div>
+ <label class="flex min-h-11 cursor-pointer flex-col items-center gap-2 text-xs text-muted">
+ Enabled
+ <input
+ type="checkbox"
+ class="h-4 w-4"
+ checked={schedule.enabled}
+ aria-label={`Enable ${schedule.name}`}
+ onChange={() => toggleReportSchedule(schedule)}
+ />
+ </label>
+ <div class="w-20">
+ <Button
+ variant="ghost"
+ size="sm"
+ class="min-h-11 w-full gap-1 px-1"
+ aria-label={`${reportScheduleRunActionLabel(schedule)} ${schedule.name} now`}
+ isLoading={runningScheduleID() === schedule.id}
+ disabled={
+ runningScheduleID() !== '' || schedule.last_run_status === 'running'
+ }
+ onClick={() => runReportScheduleNow(schedule)}
>
- {reportScheduleScopeLabel(schedule)}
- </td>
- <td
- class="report-schedule-detail-column truncate px-3 py-2 text-muted"
- title={reportScheduleDeliveryLabel(schedule)}
+ <Show when={runningScheduleID() !== schedule.id}>
+ <Play size={15} />
+ </Show>
+ {reportScheduleRunActionLabel(schedule)}
+ </Button>
+ </div>
+ </div>
+ <div
+ class="space-y-1 whitespace-normal break-words text-xs text-muted"
+ aria-live="polite"
+ >
+ <Show when={reportScheduleOutcomeDetail(visibleOutcome(schedule))}>
+ <p
+ class={
+ visibleOutcome(schedule).last_run_status === 'failed' ||
+ visibleOutcome(schedule).last_run_status === 'unconfirmed'
+ ? 'text-warning'
+ : ''
+ }
>
- {reportScheduleDeliveryLabel(schedule)}
- </td>
- <td
- class="hidden truncate px-3 py-2 text-muted sm:table-cell"
- title={schedule.last_error || ''}
+ {reportScheduleOutcomeDetail(visibleOutcome(schedule))}
+ </p>
+ </Show>
+ <Show when={schedule.delivery_check && !schedule.delivery_check.ready}>
+ <p class="text-warning">
+ {schedule.delivery_check?.message}{' '}
+ <a href="/alerts/notifications" class="underline">
+ Email settings
+ </a>
+ </p>
+ </Show>
+ <Show when={schedule.retry_at && schedule.enabled}>
+ <p>
+ Automatic retry: {formatReportScheduleTime(schedule.retry_at)}.{' '}
+ {schedule.run_attempts} of 3 attempts used.
+ </p>
+ </Show>
+ <Show when={schedule.enabled && schedule.next_run_at}>
+ <p>
+ Next scheduled report:{' '}
+ {formatReportScheduleTime(schedule.next_run_at)}
+ </p>
+ </Show>
+ <details>
+ <summary
+ class="cursor-pointer py-2"
+ aria-label={`Details for ${schedule.name}`}
>
- <div class="truncate">{reportScheduleLastRunLabel(schedule)}</div>
- <Show when={schedule.last_run_at}>
- <div class="truncate text-xs text-muted">
- {formatReportScheduleTime(schedule.last_run_at)}
- </div>
+ Report details
+ </summary>
+ <div class="space-y-2 pb-1 pt-2">
+ <p>
+ <span>{reportScheduleScopeLabel(schedule)}</span> ·{' '}
+ <span>{reportScheduleDeliveryLabel(schedule)}</span> ·{' '}
+ {schedule.format.toUpperCase()}
+ </p>
+ <Show when={(schedule.delivery.to?.length ?? 0) > 0}>
+ <p class="break-all">
+ Recipients: {schedule.delivery.to?.join(', ')}
+ </p>
</Show>
- </td>
- <td class="px-3 py-2">
- <label class="inline-flex items-center">
- <input
- type="checkbox"
- class="h-4 w-4"
- checked={schedule.enabled}
- onChange={() => toggleReportSchedule(schedule)}
- />
- </label>
- </td>
- <td class="px-3 py-2">
- <details class="group sm:hidden">
- <summary
- class="ml-auto flex min-h-11 min-w-11 cursor-pointer list-none items-center justify-center rounded-md text-base-content hover:bg-surface-hover"
- aria-label={`Actions for ${schedule.name}`}
- >
- <EllipsisVertical size={18} />
- </summary>
- <div class="mt-1 flex flex-col gap-1">
- <Button
- variant="ghost"
- size="sm"
- class="min-h-11 w-full gap-2 px-2"
- aria-label={`Run ${schedule.name} now`}
- isLoading={runningScheduleID() === schedule.id}
- disabled={runningScheduleID() !== ''}
- onClick={() => runReportScheduleNow(schedule)}
- >
- <Show when={runningScheduleID() !== schedule.id}>
- <Play size={15} />
- </Show>
- Run
- </Button>
- <Button
- variant="ghost"
- size="sm"
- class="min-h-11 w-full gap-2 px-2"
- aria-label={`Edit ${schedule.name}`}
- onClick={() => startEditSchedule(schedule)}
- >
- <Pencil size={15} />
- Edit
- </Button>
- <Button
- variant="ghost"
- size="sm"
- class="min-h-11 w-full gap-2 px-2"
- aria-label={`Delete ${schedule.name}`}
- isLoading={deletingScheduleID() === schedule.id}
- disabled={deletingScheduleID() !== ''}
- onClick={() => deleteReportSchedule(schedule)}
- >
- <Trash2 size={15} />
- Delete
- </Button>
- </div>
- </details>
- <div class="hidden justify-end gap-1 sm:flex">
- <Button
- variant="ghost"
- size="sm"
- class="gap-1 px-2"
- title="Run now"
- aria-label={`Run ${schedule.name} now`}
- isLoading={runningScheduleID() === schedule.id}
- disabled={runningScheduleID() !== ''}
- onClick={() => runReportScheduleNow(schedule)}
- >
- <Show when={runningScheduleID() !== schedule.id}>
- <Play size={15} />
- </Show>
- Run
- </Button>
+ <Show when={schedule.last_success_at}>
+ <p>
+ Last successful run:{' '}
+ {formatReportScheduleTime(schedule.last_success_at)}
+ </p>
+ </Show>
+ <Show when={schedule.last_report_path}>
+ <p class="break-all">
+ Last saved report on this server: {schedule.last_report_path}
+ </p>
+ </Show>
+ <div class="flex flex-wrap gap-2 pt-1">
<Button
- variant="ghost"
+ variant="secondary"
size="sm"
- class="gap-1 px-2"
- title="Edit"
+ class="min-h-11 gap-2"
aria-label={`Edit ${schedule.name}`}
onClick={() => startEditSchedule(schedule)}
>
<Pencil size={15} />
- Edit
+ Edit schedule
</Button>
<Button
variant="ghost"
size="sm"
- class="gap-1 px-2"
- title="Delete"
+ class="min-h-11 gap-2"
aria-label={`Delete ${schedule.name}`}
isLoading={deletingScheduleID() === schedule.id}
disabled={deletingScheduleID() !== ''}
onClick={() => deleteReportSchedule(schedule)}
>
<Trash2 size={15} />
- Delete
+ Delete schedule
</Button>
</div>
- </td>
- </tr>
- )}
- </For>
- </tbody>
- </table>
- </div>
+ </div>
+ </details>
+ </div>
+ </li>
+ )}
+ </For>
+ </ul>
</Show>
<Show when={scheduleFormOpen()}>
@@ -696,7 +681,7 @@ export function ReportingPanel() {
<option value="email">Email recipients</option>
<option value="disk">Save to disk</option>
</FormSelect>
- <FormField label="Retention">
+ <FormField label="Retention" helpText="Generated files kept on this server">
<input
aria-label="Retention"
type="number"
@@ -727,7 +712,7 @@ export function ReportingPanel() {
disabled={scheduleForm().deliveryMethod !== 'email'}
/>
</FormField>
- <div class="grid grid-cols-1 gap-3 pt-6 sm:grid-cols-3">
+ <div class="grid grid-cols-1 gap-3 pt-6 sm:grid-cols-2">
<label class="inline-flex items-center gap-2 text-sm text-muted">
<input
type="checkbox"
@@ -746,22 +731,19 @@ export function ReportingPanel() {
}
disabled={scheduleForm().deliveryMethod !== 'email'}
/>
- Attach
- </label>
- <label class="inline-flex items-center gap-2 text-sm text-muted">
- <input
- type="checkbox"
- checked={scheduleForm().saveToDisk}
- onChange={(e) =>
- updateScheduleForm({ saveToDisk: e.currentTarget.checked })
- }
- />
- Save copy
+ Attach report
</label>
</Show>
</div>
</div>
+ <Show when={!isDigestForm()}>
+ <p class="text-xs text-muted">
+ Generated reports are saved on this Pulse server. With Attach report off,
+ email sends a notice containing the saved path.
+ </p>
+ </Show>
+
<div class="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
<Button variant="secondary" size="md" class="gap-2" onClick={closeScheduleForm}>
<X size={16} />
diff --git a/frontend-modern/src/components/Settings/__tests__/ReportingPanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/ReportingPanel.test.tsx
index f947e2968c..5f4b29c94d 100644
--- a/frontend-modern/src/components/Settings/__tests__/ReportingPanel.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/ReportingPanel.test.tsx
@@ -158,7 +158,7 @@ describe('ReportingPanel', () => {
expect(screen.getByText('Report Title')).toBeInTheDocument();
});
- it('shows the scheduled reports table surface with an empty state', () => {
+ it('shows the scheduled reports surface with a confirmed empty state', () => {
useReportingPanelStateMock.mockReturnValue(buildState());
render(() => <ReportingPanel />);
@@ -167,6 +167,22 @@ describe('ReportingPanel', () => {
expect(screen.getByText('No scheduled reports are configured yet.')).toBeInTheDocument();
});
+ it.each(['loading', 'error'])('does not claim an empty schedule list during %s', (state) => {
+ useReportingPanelStateMock.mockReturnValue(
+ buildState({
+ reportSchedulesLoading: () => state === 'loading',
+ reportSchedulesError: () => (state === 'error' ? 'Report schedules are unavailable' : ''),
+ }),
+ );
+ render(() => <ReportingPanel />);
+ expect(screen.queryByText('No scheduled reports are configured yet.')).not.toBeInTheDocument();
+ expect(
+ screen.getByText(
+ state === 'loading' ? 'Loading report schedules...' : 'Report schedules are unavailable',
+ ),
+ ).toBeVisible();
+ });
+
it('keeps the schedule form free of the report type choice while Patrol cannot run', () => {
useReportingPanelStateMock.mockReturnValue(
buildState({ scheduleFormOpen: () => true, patrolDigestAvailable: () => false }),
@@ -256,7 +272,7 @@ describe('ReportingPanel', () => {
expect(screen.queryByText('Save copy')).not.toBeInTheDocument();
});
- it('describes a digest schedule by its Patrol window in the schedules table', () => {
+ it('describes a digest schedule by its Patrol window in the schedules list', () => {
useReportingPanelStateMock.mockReturnValue(
buildState({
reportSchedules: () => [
@@ -443,4 +459,37 @@ describe('ReportingPanel', () => {
exportButton.click();
expect(handleExportVMInventory).toHaveBeenCalledOnce();
});
+ it('keeps delivery failures and the remedy visible with an explicit retry action', () => {
+ useReportingPanelStateMock.mockReturnValue(
+ buildState({
+ reportSchedules: () => [
+ {
+ id: 'weekly',
+ name: 'Client report',
+ enabled: true,
+ cadence: { type: 'weekly', weekday: 'monday', time: '09:00', timezone: 'UTC' },
+ scope: { resources: [], tags: [] },
+ format: 'csv',
+ delivery: { method: 'email', to: [], attach: true, save_to_disk: true },
+ last_run_status: 'failed',
+ run_window_end: '2026-10-17T09:00:00Z',
+ last_error: 'The email sender needs fixing.',
+ delivery_check: { ready: false, message: 'Email is disabled.' },
+ last_report_path: '/reports/generated/client.csv',
+ },
+ ],
+ }),
+ );
+ render(() => <ReportingPanel />);
+ expect(screen.getByText('The email sender needs fixing.')).toBeVisible();
+ expect(screen.getByRole('link', { name: 'Email settings' })).toHaveAttribute(
+ 'href',
+ '/alerts/notifications',
+ );
+ expect(
+ screen.getAllByRole('button', { name: 'Retry Client report now', hidden: true }),
+ ).toHaveLength(1);
+ expect(screen.getByText('Report details')).toBeInTheDocument();
+ expect(screen.getByRole('checkbox', { name: 'Enable Client report' })).toBeChecked();
+ });
});
diff --git a/frontend-modern/src/components/Settings/__tests__/reportingSchedulesModel.branchcov2.test.ts b/frontend-modern/src/components/Settings/__tests__/reportingSchedulesModel.branchcov2.test.ts
index 8931200e41..9778aea10f 100644
--- a/frontend-modern/src/components/Settings/__tests__/reportingSchedulesModel.branchcov2.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/reportingSchedulesModel.branchcov2.test.ts
@@ -653,22 +653,22 @@ describe('reportScheduleLastRunLabel', () => {
expect(reportScheduleLastRunLabel(schedule)).toBe('Not run yet');
});
- it('returns "Last run OK" for the ok status', () => {
- expect(reportScheduleLastRunLabel(makeSchedule({ last_run_status: 'ok' }))).toBe('Last run OK');
+ it('does not invent delivery confirmation for a legacy ok status', () => {
+ expect(reportScheduleLastRunLabel(makeSchedule({ last_run_status: 'ok' }))).toBe('Completed');
});
- it('surfaces last_error for a failed run', () => {
+ it('uses a concise failed status label', () => {
expect(
reportScheduleLastRunLabel(
makeSchedule({ last_run_status: 'failed', last_error: 'timeout' }),
),
- ).toBe('Failed: timeout');
+ ).toBe('Failed');
});
it('falls back to the generic failed copy when last_error is missing', () => {
const schedule = makeSchedule({ last_run_status: 'failed' });
delete schedule.last_error;
- expect(reportScheduleLastRunLabel(schedule)).toBe('Last run failed');
+ expect(reportScheduleLastRunLabel(schedule)).toBe('Failed');
});
});
diff --git a/frontend-modern/src/components/Settings/__tests__/reportingSchedulesModel.delivery.test.ts b/frontend-modern/src/components/Settings/__tests__/reportingSchedulesModel.delivery.test.ts
new file mode 100644
index 0000000000..07c634d442
--- /dev/null
+++ b/frontend-modern/src/components/Settings/__tests__/reportingSchedulesModel.delivery.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from 'vitest';
+import {
+ buildReportSchedulePayload,
+ DEFAULT_REPORT_SCHEDULE_FORM,
+ normalizeReportSchedule,
+ parseReportSchedulesResponse,
+ reportScheduleLastRunLabel,
+ reportScheduleNeedsRetry,
+ reportScheduleOutcomeDetail,
+} from '../reportingSchedulesModel';
+
+const schedule = () =>
+ normalizeReportSchedule({
+ ...buildReportSchedulePayload(DEFAULT_REPORT_SCHEDULE_FORM(), []),
+ id: 'weekly',
+ });
+
+describe('report delivery outcomes', () => {
+ it('distinguishes disk output, accepted mail and legacy completion', () => {
+ expect(
+ reportScheduleLastRunLabel({
+ ...schedule(),
+ last_run_status: 'ok',
+ last_delivery_status: 'saved',
+ }),
+ ).toBe('Saved to disk');
+ const accepted = {
+ ...schedule(),
+ last_run_status: 'ok' as const,
+ last_delivery_status: 'sent_with_attachment',
+ };
+ expect(reportScheduleLastRunLabel(accepted)).toBe('Email accepted');
+ expect(reportScheduleOutcomeDetail(accepted)).toContain('Inbox receipt is not confirmed');
+ expect(reportScheduleLastRunLabel({ ...schedule(), last_run_status: 'ok' })).toBe('Completed');
+ });
+
+ it('keeps uncertainty visible and offers deliberate retry', () => {
+ const uncertain = {
+ ...schedule(),
+ run_window_end: '2026-10-17T09:00:00Z',
+ last_run_status: 'unconfirmed' as const,
+ };
+ expect(reportScheduleLastRunLabel(uncertain)).toBe('Delivery unconfirmed');
+ expect(reportScheduleOutcomeDetail(uncertain)).toContain('avoid a duplicate');
+ expect(reportScheduleNeedsRetry(uncertain)).toBe(true);
+ expect(reportScheduleNeedsRetry({ ...schedule(), last_run_status: 'running' })).toBe(false);
+ expect(reportScheduleNeedsRetry({ ...schedule(), last_run_status: 'failed' })).toBe(false);
+ });
+
+ it('preserves actionable failures and joins current configuration checks', () => {
+ const [failed] = parseReportSchedulesResponse({
+ schedules: [
+ {
+ ...schedule(),
+ last_run_status: 'failed',
+ last_error: 'Fix the email sender in notification settings',
+ },
+ ],
+ delivery_checks: { weekly: { ready: false, message: 'Email is disabled' } },
+ });
+ expect(reportScheduleOutcomeDetail(failed!)).toBe(
+ 'Fix the email sender in notification settings',
+ );
+ expect(failed?.delivery_check).toEqual({ ready: false, message: 'Email is disabled' });
+ });
+});
diff --git a/frontend-modern/src/components/Settings/__tests__/useReportingPanelState.test.ts b/frontend-modern/src/components/Settings/__tests__/useReportingPanelState.test.ts
index 3713db20aa..776272beeb 100644
--- a/frontend-modern/src/components/Settings/__tests__/useReportingPanelState.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/useReportingPanelState.test.ts
@@ -108,6 +108,7 @@ describe('useReportingPanelState', () => {
let loadCommercialLicenseStatusMock: ReturnType<typeof vi.fn>;
let aiEnabled: boolean | null;
let showWarningMock: ReturnType<typeof vi.fn>;
+ let showSuccessMock: ReturnType<typeof vi.fn>;
beforeEach(async () => {
vi.resetModules();
@@ -116,6 +117,7 @@ describe('useReportingPanelState', () => {
hasReportingFeature = true;
aiEnabled = null;
showWarningMock = vi.fn();
+ showSuccessMock = vi.fn();
loadRuntimeLicenseStatusMock = vi.fn();
loadCommercialLicenseStatusMock = vi.fn();
@@ -136,7 +138,7 @@ describe('useReportingPanelState', () => {
});
vi.doMock('@/utils/toast', () => ({
- showSuccess: vi.fn(),
+ showSuccess: showSuccessMock,
showWarning: showWarningMock,
}));
@@ -533,12 +535,14 @@ describe('useReportingPanelState', () => {
format: 'email',
delivery: { method: 'email', to: [], attach: false, save_to_disk: false },
};
+ let scheduleSaved = false;
apiFetchMock.mockImplementation((url: string, init?: RequestInit) => {
if (url === '/api/admin/reports/schedules' && init?.method === 'POST') {
+ scheduleSaved = true;
return Promise.resolve(jsonResponse(savedSchedule));
}
if (url === '/api/admin/reports/schedules') {
- return Promise.resolve(jsonResponse(schedulesPayload));
+ return Promise.resolve(jsonResponse({ schedules: scheduleSaved ? [savedSchedule] : [] }));
}
return Promise.resolve(jsonResponse(catalogPayload));
});
@@ -585,4 +589,118 @@ describe('useReportingPanelState', () => {
dispose();
});
+ const deliverySchedule = (status: 'failed' | 'retrying' | 'unconfirmed' = 'failed') => ({
+ id: 'weekly',
+ name: 'Client report',
+ enabled: true,
+ cadence: { type: 'weekly' as const, weekday: 'monday', time: '09:00', timezone: 'UTC' },
+ scope: { resources: [], tags: [] },
+ format: 'csv' as const,
+ delivery: { method: 'email' as const, to: [], attach: true, save_to_disk: true },
+ last_run_status: status,
+ run_window_end: '2026-10-17T09:00:00Z',
+ last_error: 'Mail server rejected this report.',
+ });
+
+ it('uses the retry endpoint and retains the actionable failed response', async () => {
+ const failed = deliverySchedule();
+ apiFetchMock.mockImplementation((url: string) => {
+ if (url.includes('/run')) return Promise.resolve(jsonResponse({ schedule: failed }, 500));
+ if (url === '/api/admin/reports/schedules')
+ return Promise.resolve(jsonResponse({ schedules: [failed] }));
+ return Promise.resolve(jsonResponse(catalogPayload));
+ });
+ const { hookState, dispose } = mountHook();
+ await settleMountLoads(hookState);
+ await hookState.runReportScheduleNow(failed);
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ '/api/admin/reports/schedules/weekly/run?retry=true',
+ { method: 'POST' },
+ );
+ expect(showWarningMock).toHaveBeenCalledWith(failed.last_error);
+ expect(hookState.reportSchedules()[0].last_run_status).toBe('failed');
+ dispose();
+ });
+
+ it('requires deliberate confirmation before retrying uncertain acceptance', async () => {
+ const confirm = vi.spyOn(window, 'confirm').mockReturnValue(false);
+ const { hookState, dispose } = mountHook();
+ await settleMountLoads(hookState);
+ apiFetchMock.mockClear();
+ await hookState.runReportScheduleNow(deliverySchedule('unconfirmed'));
+ expect(confirm).toHaveBeenCalledWith(expect.stringContaining('risk of a duplicate'));
+ expect(apiFetchMock).not.toHaveBeenCalled();
+ confirm.mockRestore();
+ dispose();
+ });
+
+ it('refreshes a pending delivery after returning to the page and cleans up', async () => {
+ const pending = deliverySchedule('retrying');
+ apiFetchMock.mockImplementation((url: string) =>
+ Promise.resolve(
+ jsonResponse(
+ url === '/api/admin/reports/schedules' ? { schedules: [pending] } : catalogPayload,
+ ),
+ ),
+ );
+ const { hookState, dispose } = mountHook();
+ await settleMountLoads(hookState);
+ apiFetchMock.mockClear();
+ document.dispatchEvent(new Event('visibilitychange'));
+ await vi.waitFor(() =>
+ expect(apiFetchMock).toHaveBeenCalledWith('/api/admin/reports/schedules'),
+ );
+ await settleMountLoads(hookState);
+ dispose();
+ apiFetchMock.mockClear();
+ document.dispatchEvent(new Event('visibilitychange'));
+ expect(apiFetchMock).not.toHaveBeenCalled();
+ });
+
+ it('keeps row identity through refreshes so open details and keyboard focus survive', async () => {
+ let outcome = 'retrying';
+ apiFetchMock.mockImplementation((url: string) =>
+ Promise.resolve(
+ jsonResponse(
+ url === '/api/admin/reports/schedules'
+ ? { schedules: [{ ...deliverySchedule('retrying'), last_run_status: outcome }] }
+ : catalogPayload,
+ ),
+ ),
+ );
+ const { hookState, dispose } = mountHook();
+ await settleMountLoads(hookState);
+ const row = hookState.reportSchedules()[0];
+ hookState.reloadReportSchedules();
+ await settleMountLoads(hookState);
+ expect(hookState.reportSchedules()[0]).toBe(row);
+ outcome = 'ok';
+ hookState.reloadReportSchedules();
+ await vi.waitFor(() => expect(row.last_run_status).toBe('ok'));
+ expect(hookState.reportSchedules()[0]).toBe(row);
+ dispose();
+ });
+
+ it('does not send the transient configuration check back when toggling', async () => {
+ const failed = { ...deliverySchedule(), delivery_check: { ready: false, message: 'Disabled' } };
+ let scheduleEnabled = true;
+ apiFetchMock.mockImplementation((url: string, init?: RequestInit) => {
+ if (init?.method === 'PUT') {
+ scheduleEnabled = false;
+ expect(JSON.parse(String(init.body))).not.toHaveProperty('delivery_check');
+ return Promise.resolve(jsonResponse({ ...failed, enabled: false }));
+ }
+ if (url === '/api/admin/reports/schedules')
+ return Promise.resolve(
+ jsonResponse({ schedules: [{ ...failed, enabled: scheduleEnabled }] }),
+ );
+ return Promise.resolve(jsonResponse(catalogPayload));
+ });
+ const { hookState, dispose } = mountHook();
+ await settleMountLoads(hookState);
+ await hookState.toggleReportSchedule(hookState.reportSchedules()[0]);
+ expect(hookState.reportSchedules()[0].enabled).toBe(false);
+ expect(showSuccessMock).toHaveBeenCalledWith('Report schedule disabled');
+ dispose();
+ });
});
diff --git a/frontend-modern/src/components/Settings/reportingSchedulesModel.ts b/frontend-modern/src/components/Settings/reportingSchedulesModel.ts
index 6201c2a7d8..9b2513942e 100644
--- a/frontend-modern/src/components/Settings/reportingSchedulesModel.ts
+++ b/frontend-modern/src/components/Settings/reportingSchedulesModel.ts
@@ -2,7 +2,7 @@ import type { SelectedResource } from '@/components/Settings/ResourcePicker';
import type { ReportingFormat } from '@/components/Settings/reportingCatalogModel';
export type ReportScheduleCadenceType = 'monthly' | 'weekly';
-export type ReportScheduleRunStatus = '' | 'ok' | 'failed';
+export type ReportScheduleRunStatus = '' | 'ok' | 'failed' | 'running' | 'retrying' | 'unconfirmed';
export type ReportScheduleDeliveryMethod = 'email' | 'disk';
// 'resources' is the multi-resource performance report; 'patrol_digest' emails
// the last seven days of Patrol work and has no scope, format, or disk output.
@@ -44,6 +44,14 @@ export interface ReportSchedule {
last_run_at?: string;
last_run_status?: ReportScheduleRunStatus;
last_error?: string;
+ last_delivery_status?: string;
+ last_report_path?: string;
+ last_success_at?: string;
+ run_attempts?: number;
+ retry_at?: string;
+ run_window_end?: string;
+ run_manual?: boolean;
+ delivery_check?: { ready: boolean; message: string };
next_run_at?: string;
created_at?: string;
updated_at?: string;
@@ -70,6 +78,7 @@ export interface ReportScheduleFormState {
export interface ReportSchedulesResponse {
schedules?: ReportSchedule[];
+ delivery_checks?: Record<string, { ready: boolean; message: string }>;
}
const WEEKDAY_LABELS: Record<string, string> = {
@@ -104,7 +113,12 @@ export const DEFAULT_REPORT_SCHEDULE_FORM = (): ReportScheduleFormState => ({
export function parseReportSchedulesResponse(value: unknown): ReportSchedule[] {
if (!value || typeof value !== 'object') return [];
const schedules = (value as ReportSchedulesResponse).schedules;
- return Array.isArray(schedules) ? schedules.map(normalizeReportSchedule) : [];
+ const checks = (value as ReportSchedulesResponse).delivery_checks;
+ return Array.isArray(schedules)
+ ? schedules.map((schedule) =>
+ normalizeReportSchedule({ ...schedule, delivery_check: checks?.[schedule.id] }),
+ )
+ : [];
}
export function normalizeReportScheduleKind(kind: unknown): ReportScheduleKind {
@@ -308,8 +322,46 @@ export function reportScheduleDeliveryLabel(schedule: ReportSchedule): string {
export function reportScheduleLastRunLabel(schedule: ReportSchedule): string {
if (!schedule.last_run_status) return 'Not run yet';
- if (schedule.last_run_status === 'ok') return 'Last run OK';
- return schedule.last_error ? `Failed: ${schedule.last_error}` : 'Last run failed';
+ if (schedule.last_run_status === 'running') return 'Running';
+ if (schedule.last_run_status === 'retrying') return 'Retry scheduled';
+ if (schedule.last_run_status === 'unconfirmed') return 'Delivery unconfirmed';
+ if (schedule.last_run_status === 'ok') {
+ if (schedule.last_delivery_status === 'saved') return 'Saved to disk';
+ if (
+ schedule.last_delivery_status === 'sent_with_attachment' ||
+ schedule.last_delivery_status === 'sent'
+ )
+ return 'Email accepted';
+ if (schedule.last_delivery_status === 'sent_saved_path') return 'Email notice accepted';
+ return 'Completed';
+ }
+ return 'Failed';
+}
+
+export function reportScheduleNeedsRetry(schedule: ReportSchedule): boolean {
+ return (
+ !!schedule.run_window_end &&
+ ['failed', 'retrying', 'unconfirmed'].includes(schedule.last_run_status || '')
+ );
+}
+
+export function reportScheduleRunActionLabel(schedule: ReportSchedule): string {
+ return reportScheduleNeedsRetry(schedule) ? 'Retry' : 'Run';
+}
+
+export function reportScheduleOutcomeDetail(schedule: ReportSchedule): string {
+ if (schedule.last_run_status === 'unconfirmed')
+ return 'The connection ended before delivery was confirmed. Check the recipient before retrying to avoid a duplicate.';
+ if (schedule.last_run_status === 'running') return 'Generating the report and checking delivery.';
+ if (schedule.last_error) return schedule.last_error;
+ if (
+ schedule.last_delivery_status === 'sent_with_attachment' ||
+ schedule.last_delivery_status === 'sent'
+ )
+ return 'The mail server accepted the email. Inbox receipt is not confirmed.';
+ if (schedule.last_delivery_status === 'sent_saved_path')
+ return 'The mail server accepted a notice with the saved report path. No report was attached.';
+ return '';
}
export function formatReportScheduleTime(value?: string): string {
diff --git a/frontend-modern/src/components/Settings/useReportingPanelState.ts b/frontend-modern/src/components/Settings/useReportingPanelState.ts
index 2d8e7c7e8c..7a2bb58eb6 100644
--- a/frontend-modern/src/components/Settings/useReportingPanelState.ts
+++ b/frontend-modern/src/components/Settings/useReportingPanelState.ts
@@ -1,4 +1,5 @@
-import { createEffect, createSignal, onMount } from 'solid-js';
+import { createEffect, createSignal, onMount, onCleanup, untrack } from 'solid-js';
+import { createStore, reconcile, unwrap } from 'solid-js/store';
import { apiErrorFromResponse, apiFetch } from '@/utils/apiClient';
import { showSuccess, showWarning } from '@/utils/toast';
import { aiChatStore } from '@/stores/aiChat';
@@ -37,6 +38,8 @@ import {
parseReportSchedulesResponse,
scheduleToForm,
scheduleToSelectedResources,
+ reportScheduleLastRunLabel,
+ reportScheduleNeedsRetry,
type ReportSchedule,
type ReportScheduleFormState,
type ReportScheduleKind,
@@ -54,7 +57,19 @@ export const useReportingPanelState = () => {
const [reportingCatalogError, setReportingCatalogError] = createSignal('');
const [reportingCatalogAttempted, setReportingCatalogAttempted] = createSignal(false);
const [title, setTitle] = createSignal('');
- const [reportSchedules, setReportSchedules] = createSignal<ReportSchedule[]>([]);
+ const [scheduleState, setScheduleState] = createStore<{ schedules: ReportSchedule[] }>({
+ schedules: [],
+ });
+ const reportSchedules = () => scheduleState.schedules;
+ const setReportSchedules = (
+ update: ReportSchedule[] | ((current: ReportSchedule[]) => ReportSchedule[]),
+ ) => {
+ const next =
+ typeof update === 'function'
+ ? untrack(() => update(unwrap(scheduleState.schedules)))
+ : update;
+ setScheduleState('schedules', reconcile(next, { key: 'id' }));
+ };
const [reportSchedulesLoading, setReportSchedulesLoading] = createSignal(false);
const [reportSchedulesAttempted, setReportSchedulesAttempted] = createSignal(false);
const [reportSchedulesError, setReportSchedulesError] = createSignal('');
@@ -148,6 +163,23 @@ export const useReportingPanelState = () => {
void loadReportSchedules();
});
+ createEffect(() => {
+ if (!isReportingEnabled()) return;
+ const active = reportSchedules().some((schedule) =>
+ ['running', 'retrying'].includes(schedule.last_run_status || ''),
+ );
+ if (!active && !reportSchedules().some((schedule) => schedule.enabled)) return;
+ const refreshVisibleSchedules = () => {
+ if (!document.hidden) void loadReportSchedules();
+ };
+ const timer = window.setInterval(refreshVisibleSchedules, active ? 5000 : 30000);
+ document.addEventListener('visibilitychange', refreshVisibleSchedules);
+ onCleanup(() => {
+ window.clearInterval(timer);
+ document.removeEventListener('visibilitychange', refreshVisibleSchedules);
+ });
+ });
+
createEffect(() => {
const performanceReport = reportingCatalog()?.performanceReport;
if (!performanceReport) {
@@ -332,6 +364,7 @@ export const useReportingPanelState = () => {
return next;
});
closeScheduleForm();
+ await loadReportSchedules();
showSuccess('Report schedule saved');
} catch (error) {
console.error('Save report schedule error:', error);
@@ -343,12 +376,14 @@ export const useReportingPanelState = () => {
const updateReportSchedule = async (schedule: ReportSchedule) => {
const normalized = normalizeReportSchedule(schedule);
+ const payload = { ...normalized };
+ delete payload.delivery_check;
const response = await apiFetch(
`/api/admin/reports/schedules/${encodeURIComponent(normalized.id)}`,
{
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(normalized),
+ body: JSON.stringify(payload),
},
);
if (!response.ok) {
@@ -358,12 +393,14 @@ export const useReportingPanelState = () => {
setReportSchedules((current) =>
current.map((candidate) => (candidate.id === saved.id ? saved : candidate)),
);
+ await loadReportSchedules();
};
const toggleReportSchedule = async (schedule: ReportSchedule) => {
+ const enabled = !schedule.enabled;
try {
- await updateReportSchedule({ ...schedule, enabled: !schedule.enabled });
- showSuccess(schedule.enabled ? 'Report schedule disabled' : 'Report schedule enabled');
+ await updateReportSchedule({ ...schedule, enabled });
+ showSuccess(enabled ? 'Report schedule enabled' : 'Report schedule disabled');
} catch (error) {
console.error('Toggle report schedule error:', error);
showWarning(error instanceof Error ? error.message : 'Failed to update report schedule');
@@ -372,25 +409,47 @@ export const useReportingPanelState = () => {
const runReportScheduleNow = async (schedule: ReportSchedule) => {
if (runningScheduleID()) return;
+ if (
+ schedule.last_run_status === 'unconfirmed' &&
+ !window.confirm(
+ 'The previous email may have been accepted. Check the recipient first. Retry anyway, with a risk of a duplicate?',
+ )
+ )
+ return;
+ const retry = reportScheduleNeedsRetry(schedule);
setRunningScheduleID(schedule.id);
try {
const response = await apiFetch(
- `/api/admin/reports/schedules/${encodeURIComponent(schedule.id)}/run`,
+ `/api/admin/reports/schedules/${encodeURIComponent(schedule.id)}/run${retry ? '?retry=true' : ''}`,
{ method: 'POST' },
);
- if (!response.ok) {
- throw await apiErrorFromResponse(response, 'Failed to run report schedule');
- }
- const body = await response.json();
+ const body = await response
+ .clone()
+ .json()
+ .catch(() => null);
if (body?.schedule) {
const updated = normalizeReportSchedule(body.schedule);
setReportSchedules((current) =>
current.map((candidate) => (candidate.id === updated.id ? updated : candidate)),
);
- } else {
- await loadReportSchedules();
}
- showSuccess('Report schedule ran');
+ await loadReportSchedules();
+ if (!response.ok) {
+ if (body?.schedule) {
+ showWarning(body.schedule.last_error || reportScheduleLastRunLabel(body.schedule));
+ return;
+ }
+ throw await apiErrorFromResponse(response, 'Failed to run report schedule');
+ }
+ if (
+ body?.schedule?.last_run_status === 'retrying' ||
+ body?.schedule?.last_run_status === 'unconfirmed'
+ )
+ showWarning(body.schedule.last_error || reportScheduleLastRunLabel(body.schedule));
+ else
+ showSuccess(
+ body?.schedule ? reportScheduleLastRunLabel(body.schedule) : 'Report schedule ran',
+ );
} catch (error) {
console.error('Run report schedule error:', error);
showWarning(error instanceof Error ? error.message : 'Failed to run report schedule');
diff --git a/internal/api/report_schedule_delivery_test.go b/internal/api/report_schedule_delivery_test.go
new file mode 100644
index 0000000000..ea5303bd7e
--- /dev/null
+++ b/internal/api/report_schedule_delivery_test.go
@@ -0,0 +1,369 @@
+package api
+
+import (
+ "context"
+ "encoding/json"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/textproto"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/notifications"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/reporting"
+ "github.com/stretchr/testify/require"
+)
+
+func reportDeliveryFixture(t *testing.T) (*ReportingHandlers, *config.ConfigPersistence, *stubReportingEngine, context.Context, config.ReportSchedule) {
+ t.Helper()
+ h, p := newTestReportingScheduleHandlers(t)
+ engine := &stubReportingEngine{data: []byte("cpu\n42\n"), contentType: "text/csv"}
+ previous := reporting.GetEngine()
+ reporting.SetEngine(engine)
+ t.Cleanup(func() { reporting.SetEngine(previous) })
+ s := validReportSchedulePayload()
+ s.ID = "delivery"
+ s.Cadence = config.ReportScheduleCadence{Type: "weekly", Weekday: "monday", Time: "09:00", Timezone: "UTC"}
+ s.Format = "csv"
+ s.Delivery = config.ReportScheduleDelivery{Method: "email", To: []string{"[email protected]"}, Attach: true, SaveToDisk: true}
+ return h, p, engine, context.WithValue(context.Background(), OrgIDContextKey, "default"), s
+}
+
+// SMTP receives real report bytes and supplies structured completed-message
+// verdicts. Zero drops the connection after DATA, making acceptance uncertain.
+func reportSMTP(t *testing.T, replies []int, onMessage func()) (notifications.EmailConfig, *atomic.Int32) {
+ t.Helper()
+ listener, err := net.Listen("tcp4", "127.0.0.1:0")
+ require.NoError(t, err)
+ var sessions sync.WaitGroup
+ attempts := &atomic.Int32{}
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ for {
+ wire, err := listener.Accept()
+ if err != nil {
+ return
+ }
+ sessions.Add(1)
+ go func() {
+ defer sessions.Done()
+ defer wire.Close()
+ _ = wire.SetDeadline(time.Now().Add(10 * time.Second))
+ conn := textproto.NewConn(wire)
+ if conn.PrintfLine("220 localhost") != nil {
+ return
+ }
+ for {
+ line, err := conn.ReadLine()
+ if err != nil {
+ return
+ }
+ switch strings.Fields(line)[0] {
+ case "EHLO", "HELO", "MAIL", "RCPT":
+ err = conn.PrintfLine("250 OK")
+ case "DATA":
+ if conn.PrintfLine("354 Send message") != nil {
+ return
+ }
+ body, readErr := conn.ReadDotBytes()
+ if readErr != nil {
+ return
+ }
+ if !strings.Contains(string(body), "Content-Disposition: attachment") {
+ t.Error("report has no MIME attachment")
+ }
+ attempt := int(attempts.Add(1)) - 1
+ if onMessage != nil {
+ onMessage()
+ }
+ code := replies[len(replies)-1]
+ if attempt < len(replies) {
+ code = replies[attempt]
+ }
+ if code == 0 {
+ return
+ }
+ err = conn.PrintfLine("%d provider-verdict-do-not-persist", code)
+ case "QUIT":
+ _ = conn.PrintfLine("221 Bye")
+ return
+ default:
+ t.Errorf("unexpected SMTP command %q", line)
+ return
+ }
+ if err != nil {
+ return
+ }
+ }
+ }()
+ }
+ }()
+ t.Cleanup(func() { _ = listener.Close(); <-done; sessions.Wait() })
+ _, port, err := net.SplitHostPort(listener.Addr().String())
+ require.NoError(t, err)
+ n, err := strconv.Atoi(port)
+ require.NoError(t, err)
+ return notifications.EmailConfig{Enabled: true, SMTPHost: "127.0.0.1", SMTPPort: n, From: "[email protected]", To: []string{"[email protected]"}}, attempts
+}
+
+func storedReport(t *testing.T, p *config.ConfigPersistence) config.ReportSchedule {
+ t.Helper()
+ store, err := p.LoadReportScheduleStore()
+ require.NoError(t, err)
+ require.Len(t, store.Schedules, 1)
+ return store.Schedules[0]
+}
+
+func runDeliveryRequest(h *ReportingHandlers, ctx context.Context, retry bool) *httptest.ResponseRecorder {
+ url := "/api/admin/reports/schedules/delivery/run"
+ if retry {
+ url += "?retry=true"
+ }
+ r := httptest.NewRequest(http.MethodPost, url, nil).WithContext(ctx)
+ r.SetPathValue("id", "delivery")
+ w := httptest.NewRecorder()
+ h.HandleRunReportSchedule(w, r)
+ return w
+}
+
+func TestReportScheduleDeliveryPreflightAndServerOwnedState(t *testing.T) {
+ h, p, engine, ctx, s := reportDeliveryFixture(t)
+ now := time.Now().UTC()
+ s.LastRunStatus = "ok"
+ s.LastReportPath = "/untrusted/path"
+ s.LastSuccessAt = &now
+ s.RetryAt = &now
+ s.RunWindowEnd = &now
+ s.RunAttempts = 99
+ r := httptest.NewRequest(http.MethodPost, "/api/admin/reports/schedules", encodeScheduleBody(t, s)).WithContext(ctx)
+ w := httptest.NewRecorder()
+ h.HandleCreateReportSchedule(w, r)
+ require.Equal(t, http.StatusBadRequest, w.Code, w.Body.String())
+ require.Contains(t, w.Body.String(), "Enable email notifications")
+ s.Enabled = false
+ r = httptest.NewRequest(http.MethodPost, "/api/admin/reports/schedules", encodeScheduleBody(t, s)).WithContext(ctx)
+ w = httptest.NewRecorder()
+ h.HandleCreateReportSchedule(w, r)
+ require.Equal(t, http.StatusCreated, w.Code, w.Body.String())
+ created := storedReport(t, p)
+ require.Empty(t, created.LastRunStatus)
+ require.Empty(t, created.LastReportPath)
+ require.Nil(t, created.LastSuccessAt)
+ require.Nil(t, created.RetryAt)
+ require.Nil(t, created.RunWindowEnd)
+ require.Zero(t, created.RunAttempts)
+ created.ID = "delivery"
+ require.NoError(t, p.SaveReportScheduleStore(config.ReportScheduleStore{Schedules: []config.ReportSchedule{created}}))
+ w = runDeliveryRequest(h, ctx, false)
+ require.Equal(t, http.StatusInternalServerError, w.Code, w.Body.String())
+ require.Empty(t, engine.lastMulti.Resources, "missing email config must fail before generation")
+ failed := storedReport(t, p)
+ require.Equal(t, "failed", failed.LastRunStatus)
+ require.Nil(t, failed.RetryAt)
+ require.Empty(t, failed.LastReportPath)
+ list := httptest.NewRecorder()
+ h.HandleListReportSchedules(list, httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx))
+ var payload reportScheduleListResponse
+ require.NoError(t, json.Unmarshal(list.Body.Bytes(), &payload))
+ require.False(t, payload.DeliveryChecks["delivery"].Ready)
+}
+
+func TestReportScheduleDeliveryRetriesSurviveRestartAndKeepWindow(t *testing.T) {
+ h, p, engine, ctx, s := reportDeliveryFixture(t)
+ cfg, attempts := reportSMTP(t, []int{451, 451, 250}, nil)
+ require.NoError(t, p.SaveEmailConfig(cfg))
+ require.NoError(t, p.SaveReportScheduleStore(config.ReportScheduleStore{Schedules: []config.ReportSchedule{s}}))
+ now := time.Date(2026, 10, 19, 9, 0, 1, 0, time.UTC)
+ h.runDueReportSchedulesForOrg(ctx, "default", now)
+ first := storedReport(t, p)
+ require.Equal(t, "retrying", first.LastRunStatus)
+ require.Equal(t, 1, first.RunAttempts)
+ require.NotNil(t, first.RetryAt)
+ window := engine.lastMulti.End
+ require.NotContains(t, first.LastError, "provider-verdict")
+ // A fresh handler reads only the persisted state, with no in-memory retry job.
+ restarted := NewReportingHandlers(h.mtMonitor, nil)
+ restarted.runDueReportSchedulesForOrg(ctx, "default", now.Add(30*time.Second))
+ require.EqualValues(t, 1, attempts.Load())
+ restarted.runDueReportSchedulesForOrg(ctx, "default", first.RetryAt.Add(time.Second))
+ second := storedReport(t, p)
+ require.Equal(t, "retrying", second.LastRunStatus)
+ require.Equal(t, 2, second.RunAttempts)
+ require.True(t, second.RetryAt.After(first.RetryAt.Add(4*time.Minute)))
+ restarted.runDueReportSchedulesForOrg(ctx, "default", second.RetryAt.Add(time.Second))
+ finished := storedReport(t, p)
+ require.Equal(t, "ok", finished.LastRunStatus)
+ require.Equal(t, "sent_with_attachment", finished.LastDeliveryStatus)
+ require.Equal(t, 3, finished.RunAttempts)
+ require.Nil(t, finished.RetryAt)
+ require.NotNil(t, finished.LastSuccessAt)
+ require.FileExists(t, finished.LastReportPath)
+ require.Equal(t, window, engine.lastMulti.End)
+ restarted.runDueReportSchedulesForOrg(ctx, "default", now.Add(time.Hour))
+ require.EqualValues(t, 3, attempts.Load())
+}
+
+func TestReportScheduleDeliveryStopsAtBudgetRejectionAndUncertainty(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ code int
+ want string
+ attempts int32
+ }{{"exhausted", 451, "failed", 3}, {"rejected", 550, "failed", 1}, {"unconfirmed", 0, "unconfirmed", 1}} {
+ t.Run(tc.name, func(t *testing.T) {
+ h, p, _, ctx, s := reportDeliveryFixture(t)
+ cfg, attempts := reportSMTP(t, []int{tc.code}, nil)
+ require.NoError(t, p.SaveEmailConfig(cfg))
+ require.NoError(t, p.SaveReportScheduleStore(config.ReportScheduleStore{Schedules: []config.ReportSchedule{s}}))
+ now := time.Date(2026, 10, 19, 9, 0, 1, 0, time.UTC)
+ for i := 0; i < 5; i++ {
+ h.runDueReportSchedulesForOrg(ctx, "default", now.Add(time.Duration(i)*10*time.Minute))
+ }
+ out := storedReport(t, p)
+ require.Equal(t, tc.want, out.LastRunStatus)
+ require.Nil(t, out.RetryAt)
+ require.Equal(t, tc.attempts, attempts.Load())
+ require.NotContains(t, out.LastError, "provider-verdict")
+ if tc.code == 0 {
+ require.Contains(t, out.LastError, "duplicate")
+ }
+ })
+ }
+}
+
+func TestReportScheduleDeliveryRecoversInterruptedEmailWithoutResending(t *testing.T) {
+ h, p, _, ctx, s := reportDeliveryFixture(t)
+ cfg, attempts := reportSMTP(t, []int{250}, nil)
+ require.NoError(t, p.SaveEmailConfig(cfg))
+ now := time.Date(2026, 10, 19, 9, 0, 1, 0, time.UTC)
+ s.LastRunStatus = "running"
+ s.RunWindowEnd = &now
+ s.RunAttempts = 1
+ s.LastOccurrenceKey = currentReportScheduleOccurrenceKey(s, now)
+ require.NoError(t, p.SaveReportScheduleStore(config.ReportScheduleStore{Schedules: []config.ReportSchedule{s}}))
+ h.runDueReportSchedulesForOrg(ctx, "default", now.Add(time.Minute))
+ require.Equal(t, "unconfirmed", storedReport(t, p).LastRunStatus)
+ require.Zero(t, attempts.Load())
+ w := runDeliveryRequest(h, ctx, true)
+ require.Equal(t, http.StatusOK, w.Code, w.Body.String())
+ require.EqualValues(t, 1, attempts.Load())
+ require.Equal(t, "ok", storedReport(t, p).LastRunStatus)
+}
+
+func TestReportScheduleDeliveryEditCancelsRetryAndPreservesOutcome(t *testing.T) {
+ h, p, _, ctx, s := reportDeliveryFixture(t)
+ cfg, attempts := reportSMTP(t, []int{451}, nil)
+ require.NoError(t, p.SaveEmailConfig(cfg))
+ require.NoError(t, p.SaveReportScheduleStore(config.ReportScheduleStore{Schedules: []config.ReportSchedule{s}}))
+ require.Equal(t, http.StatusAccepted, runDeliveryRequest(h, ctx, false).Code)
+ pending := storedReport(t, p)
+ lastRun := *pending.LastRunAt
+ pending.Enabled = false
+ pending.LastRunStatus = "ok"
+ pending.LastReportPath = "/forged"
+ pending.RunAttempts = 99
+ r := httptest.NewRequest(http.MethodPut, "/", encodeScheduleBody(t, pending)).WithContext(ctx)
+ r.SetPathValue("id", "delivery")
+ w := httptest.NewRecorder()
+ h.HandleUpdateReportSchedule(w, r)
+ require.Equal(t, http.StatusOK, w.Code, w.Body.String())
+ out := storedReport(t, p)
+ require.Equal(t, "failed", out.LastRunStatus)
+ require.Equal(t, lastRun, *out.LastRunAt)
+ require.NotEqual(t, "/forged", out.LastReportPath)
+ require.Equal(t, 1, out.RunAttempts)
+ require.Nil(t, out.RetryAt)
+ require.Nil(t, out.RunWindowEnd)
+ h.runDueReportSchedulesForOrg(ctx, "default", time.Now().Add(time.Hour))
+ require.EqualValues(t, 1, attempts.Load())
+ require.Equal(t, http.StatusConflict, runDeliveryRequest(h, ctx, true).Code)
+}
+
+func TestReportScheduleDeliveryPersistsBeforeSMTPAndCannotResurrectDeletedSchedule(t *testing.T) {
+ h, p, _, ctx, s := reportDeliveryFixture(t)
+ entered, release := make(chan struct{}), make(chan struct{})
+ var releaseOnce sync.Once
+ unblock := func() { releaseOnce.Do(func() { close(release) }) }
+ var observed atomic.Bool
+ cfg, _ := reportSMTP(t, []int{250}, func() {
+ store, err := p.LoadReportScheduleStore()
+ if err == nil && len(store.Schedules) == 1 && store.Schedules[0].LastRunStatus == "running" {
+ observed.Store(true)
+ }
+ close(entered)
+ <-release
+ })
+ t.Cleanup(unblock)
+ require.NoError(t, p.SaveEmailConfig(cfg))
+ require.NoError(t, p.SaveReportScheduleStore(config.ReportScheduleStore{Schedules: []config.ReportSchedule{s}}))
+ runDone := make(chan *httptest.ResponseRecorder, 1)
+ go func() { runDone <- runDeliveryRequest(h, ctx, false) }()
+ select {
+ case <-entered:
+ case result := <-runDone:
+ t.Fatalf("report ended before SMTP: %d %s", result.Code, result.Body.String())
+ case <-time.After(15 * time.Second):
+ t.Fatal("report did not reach SMTP")
+ }
+ deleteDone := make(chan *httptest.ResponseRecorder, 1)
+ go func() {
+ r := httptest.NewRequest(http.MethodDelete, "/", nil).WithContext(ctx)
+ r.SetPathValue("id", "delivery")
+ w := httptest.NewRecorder()
+ h.HandleDeleteReportSchedule(w, r)
+ deleteDone <- w
+ }()
+ select {
+ case <-deleteDone:
+ t.Error("delete passed an active delivery")
+ case <-time.After(30 * time.Millisecond):
+ }
+ unblock()
+ require.Equal(t, http.StatusOK, (<-runDone).Code)
+ require.Equal(t, http.StatusNoContent, (<-deleteDone).Code)
+ require.True(t, observed.Load())
+ store, err := p.LoadReportScheduleStore()
+ require.NoError(t, err)
+ require.Empty(t, store.Schedules)
+}
+
+func TestReportScheduleDeliveryOversizeAndDiskOutcomes(t *testing.T) {
+ h, p, _, ctx, s := reportDeliveryFixture(t)
+ cfg, attempts := reportSMTP(t, []int{250}, nil)
+ require.NoError(t, p.SaveEmailConfig(cfg))
+ _, err := sendScheduledReportEmail(p, s, generatedMultiReport{Data: make([]byte, reportScheduleAttachmentLimitBytes+1)}, "/owned/report.pdf")
+ require.ErrorContains(t, err, "15 MiB")
+ require.Zero(t, attempts.Load())
+ s.Delivery.Method = "disk"
+ require.NoError(t, p.SaveReportScheduleStore(config.ReportScheduleStore{Schedules: []config.ReportSchedule{s}}))
+ require.Equal(t, http.StatusOK, runDeliveryRequest(h, ctx, false).Code)
+ out := storedReport(t, p)
+ require.Equal(t, "saved", out.LastDeliveryStatus)
+ require.Equal(t, "ok", out.LastRunStatus)
+ require.FileExists(t, out.LastReportPath)
+ require.Zero(t, attempts.Load())
+}
+
+func TestReportScheduleDeliveryRechecksEntitlementBeforeRetry(t *testing.T) {
+ h, p, _, ctx, s := reportDeliveryFixture(t)
+ cfg, attempts := reportSMTP(t, []int{451}, nil)
+ require.NoError(t, p.SaveEmailConfig(cfg))
+ require.NoError(t, p.SaveReportScheduleStore(config.ReportScheduleStore{Schedules: []config.ReportSchedule{s}}))
+ require.Equal(t, http.StatusAccepted, runDeliveryRequest(h, ctx, false).Code)
+ pending := storedReport(t, p)
+ service := newLicenseService()
+ h.SetCommercialLicenseResolver(func(context.Context) *licenseService { return service })
+ h.runDueReportSchedulesForOrg(ctx, "default", pending.RetryAt.Add(time.Second))
+ out := storedReport(t, p)
+ require.Equal(t, "failed", out.LastRunStatus)
+ require.Contains(t, out.LastError, "advanced reporting entitlement required")
+ require.Nil(t, out.RetryAt)
+ require.EqualValues(t, 1, attempts.Load(), "expired entitlement must not dispatch another message")
+}
diff --git a/internal/api/report_schedules.go b/internal/api/report_schedules.go
index 72e4aaf25f..d5bea5ba1b 100644
--- a/internal/api/report_schedules.go
+++ b/internal/api/report_schedules.go
@@ -26,10 +26,17 @@ const (
reportScheduleAttachmentLimitBytes = 15 * 1024 * 1024
reportScheduleTickInterval = time.Minute
reportScheduleMissedRunGrace = 24 * time.Hour
+ reportScheduleMaxAttempts = 3
)
type reportScheduleListResponse struct {
- Schedules []config.ReportSchedule `json:"schedules"`
+ Schedules []config.ReportSchedule `json:"schedules"`
+ DeliveryChecks map[string]reportScheduleDeliveryCheck `json:"delivery_checks"`
+}
+
+type reportScheduleDeliveryCheck struct {
+ Ready bool `json:"ready"`
+ Message string `json:"message"`
}
type reportScheduleRunResponse struct {
@@ -44,12 +51,16 @@ func (h *ReportingHandlers) HandleListReportSchedules(w http.ResponseWriter, r *
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
- store, err := h.loadReportScheduleStore(r.Context())
+ persistence, store, err := h.reportSchedulePersistenceAndStore(r.Context())
if err != nil {
writeErrorResponse(w, http.StatusInternalServerError, "schedule_store_unavailable", "Report schedules are unavailable", nil)
return
}
- writeReportScheduleJSON(w, http.StatusOK, reportScheduleListResponse{Schedules: store.Schedules})
+ checks := make(map[string]reportScheduleDeliveryCheck, len(store.Schedules))
+ for _, schedule := range store.Schedules {
+ checks[schedule.ID] = checkReportScheduleDelivery(persistence, schedule)
+ }
+ writeReportScheduleJSON(w, http.StatusOK, reportScheduleListResponse{Schedules: store.Schedules, DeliveryChecks: checks})
}
func (h *ReportingHandlers) HandleCreateReportSchedule(w http.ResponseWriter, r *http.Request) {
@@ -61,6 +72,8 @@ func (h *ReportingHandlers) HandleCreateReportSchedule(w http.ResponseWriter, r
if err := decodeReportScheduleBody(w, r, &incoming); err != nil {
return
}
+ h.scheduleRunMu.Lock()
+ defer h.scheduleRunMu.Unlock()
persistence, store, err := h.reportSchedulePersistenceAndStore(r.Context())
if err != nil {
@@ -71,11 +84,13 @@ func (h *ReportingHandlers) HandleCreateReportSchedule(w http.ResponseWriter, r
incoming.ID = uuid.NewString()
incoming.CreatedAt = now
incoming.UpdatedAt = now
+ copyReportScheduleRunState(&incoming, config.ReportSchedule{})
schedule, err := h.prepareReportSchedule(r.Context(), incoming, now, false)
if err != nil {
writeReportScheduleValidationError(w, err)
return
}
+ schedule.LastOccurrenceKey = currentReportScheduleOccurrenceKey(schedule, now)
store.Schedules = append(store.Schedules, schedule)
if err := persistence.SaveReportScheduleStore(*store); err != nil {
writeErrorResponse(w, http.StatusInternalServerError, "schedule_save_failed", "Failed to save report schedule", nil)
@@ -98,6 +113,8 @@ func (h *ReportingHandlers) HandleUpdateReportSchedule(w http.ResponseWriter, r
if err := decodeReportScheduleBody(w, r, &incoming); err != nil {
return
}
+ h.scheduleRunMu.Lock()
+ defer h.scheduleRunMu.Unlock()
persistence, store, err := h.reportSchedulePersistenceAndStore(r.Context())
if err != nil {
@@ -115,15 +132,20 @@ func (h *ReportingHandlers) HandleUpdateReportSchedule(w http.ResponseWriter, r
incoming.ID = existing.ID
incoming.CreatedAt = existing.CreatedAt
incoming.UpdatedAt = now
- incoming.LastRunAt = existing.LastRunAt
- incoming.LastRunStatus = existing.LastRunStatus
- incoming.LastError = existing.LastError
- incoming.LastOccurrenceKey = existing.LastOccurrenceKey
+ copyReportScheduleRunState(&incoming, existing)
schedule, err := h.prepareReportSchedule(r.Context(), incoming, now, false)
if err != nil {
writeReportScheduleValidationError(w, err)
return
}
+ if schedule.RetryAt != nil {
+ schedule.LastRunStatus = config.ReportScheduleLastRunFailed
+ schedule.LastError = "Automatic retry cancelled because the schedule was edited. Run a new report when ready."
+ }
+ schedule.RetryAt = nil
+ schedule.RunWindowEnd = nil
+ schedule.RunManual = false
+ schedule.LastOccurrenceKey = currentReportScheduleOccurrenceKey(schedule, now)
store.Schedules[index] = schedule
if err := persistence.SaveReportScheduleStore(*store); err != nil {
writeErrorResponse(w, http.StatusInternalServerError, "schedule_save_failed", "Failed to save report schedule", nil)
@@ -142,6 +164,8 @@ func (h *ReportingHandlers) HandleDeleteReportSchedule(w http.ResponseWriter, r
writeErrorResponse(w, http.StatusBadRequest, "missing_schedule_id", "Schedule ID is required", nil)
return
}
+ h.scheduleRunMu.Lock()
+ defer h.scheduleRunMu.Unlock()
persistence, store, err := h.reportSchedulePersistenceAndStore(r.Context())
if err != nil {
writeErrorResponse(w, http.StatusInternalServerError, "schedule_store_unavailable", "Report schedules are unavailable", nil)
@@ -170,6 +194,8 @@ func (h *ReportingHandlers) HandleRunReportSchedule(w http.ResponseWriter, r *ht
writeErrorResponse(w, http.StatusBadRequest, "missing_schedule_id", "Schedule ID is required", nil)
return
}
+ h.scheduleRunMu.Lock()
+ defer h.scheduleRunMu.Unlock()
persistence, store, err := h.reportSchedulePersistenceAndStore(r.Context())
if err != nil {
writeErrorResponse(w, http.StatusInternalServerError, "schedule_store_unavailable", "Report schedules are unavailable", nil)
@@ -181,15 +207,28 @@ func (h *ReportingHandlers) HandleRunReportSchedule(w http.ResponseWriter, r *ht
return
}
- result, updated := h.runReportSchedule(r.Context(), persistence, store.Schedules[index], time.Now().UTC(), true, "")
- store.Schedules[index] = updated
- if err := persistence.SaveReportScheduleStore(*store); err != nil {
- writeErrorResponse(w, http.StatusInternalServerError, "schedule_save_failed", "Failed to save report schedule status", nil)
+ schedule := store.Schedules[index]
+ if schedule.LastRunStatus == config.ReportScheduleLastRunRunning {
+ writeErrorResponse(w, http.StatusConflict, "schedule_running", "This report is already running. Refresh its status before trying again.", nil)
+ return
+ }
+ retry := r.URL.Query().Get("retry") == "true"
+ if retry && (schedule.RunWindowEnd == nil || !reportScheduleRetryableOutcome(schedule.LastRunStatus)) {
+ writeErrorResponse(w, http.StatusConflict, "retry_unavailable", "The original failed report window is unavailable. Run a new report.", nil)
+ return
+ }
+ result, updated, err := h.executeReportSchedule(r.Context(), persistence, store, index, time.Now().UTC(), true, "", retry)
+ if err != nil {
+ writeErrorResponse(w, http.StatusInternalServerError, "schedule_save_failed", "The report outcome could not be saved. Check its status and the recipient before running again.", nil)
return
}
status := http.StatusOK
if updated.LastRunStatus == config.ReportScheduleLastRunFailed {
status = http.StatusInternalServerError
+ } else if updated.LastRunStatus == config.ReportScheduleLastRunRetrying {
+ status = http.StatusAccepted
+ } else if updated.LastRunStatus == config.ReportScheduleLastRunUnconfirmed {
+ status = http.StatusBadGateway
}
writeReportScheduleJSON(w, status, reportScheduleRunResponse{
Schedule: updated,
@@ -254,11 +293,6 @@ func (h *ReportingHandlers) reportSchedulePersistenceAndStore(ctx context.Contex
return persistence, store, nil
}
-func (h *ReportingHandlers) loadReportScheduleStore(ctx context.Context) (*config.ReportScheduleStore, error) {
- _, store, err := h.reportSchedulePersistenceAndStore(ctx)
- return store, err
-}
-
func (h *ReportingHandlers) reportSchedulePersistence(ctx context.Context) (*config.ConfigPersistence, error) {
if h == nil || h.mtMonitor == nil {
return nil, fmt.Errorf("multi-tenant monitor is not configured")
@@ -287,6 +321,105 @@ func findReportScheduleIndex(schedules []config.ReportSchedule, id string) int {
return -1
}
+// Outcomes are server-owned even when older clients PUT a whole schedule.
+func copyReportScheduleRunState(dst *config.ReportSchedule, src config.ReportSchedule) {
+ dst.LastRunAt = src.LastRunAt
+ dst.LastRunStatus = src.LastRunStatus
+ dst.LastError = src.LastError
+ dst.LastDeliveryStatus = src.LastDeliveryStatus
+ dst.LastReportPath = src.LastReportPath
+ dst.LastSuccessAt = src.LastSuccessAt
+ dst.RunAttempts = src.RunAttempts
+ dst.RetryAt = src.RetryAt
+ dst.RunWindowEnd = src.RunWindowEnd
+ dst.RunManual = src.RunManual
+ dst.NextRunAt = src.NextRunAt
+ dst.LastOccurrenceKey = src.LastOccurrenceKey
+}
+
+func currentReportScheduleOccurrenceKey(schedule config.ReportSchedule, now time.Time) string {
+ _, key, _ := lastReportScheduleOccurrenceAt(schedule, now)
+ return key
+}
+
+func checkReportScheduleDelivery(persistence *config.ConfigPersistence, schedule config.ReportSchedule) reportScheduleDeliveryCheck {
+ if schedule.Delivery.Method == config.ReportScheduleDeliveryDisk {
+ return reportScheduleDeliveryCheck{Ready: true, Message: "Reports are saved on this Pulse server."}
+ }
+ _, err := scheduledReportEmailManager(persistence, schedule)
+ if err != nil {
+ return reportScheduleDeliveryCheck{Message: err.Error()}
+ }
+ return reportScheduleDeliveryCheck{Ready: true, Message: "Email configuration checked. Run the report to test delivery."}
+}
+
+func (h *ReportingHandlers) validateEnabledReportDelivery(ctx context.Context, schedule config.ReportSchedule) error {
+ if !schedule.Enabled || schedule.Delivery.Method != config.ReportScheduleDeliveryEmail {
+ return nil
+ }
+ persistence, err := h.reportSchedulePersistence(ctx)
+ if err != nil {
+ return reportScheduleValidationError{code: "email_configuration_unavailable", message: "Email configuration is unavailable. Check Alerts > Notifications."}
+ }
+ check := checkReportScheduleDelivery(persistence, schedule)
+ if !check.Ready {
+ return reportScheduleValidationError{code: "email_not_ready", message: check.Message}
+ }
+ return nil
+}
+
+func reportScheduleRetryableOutcome(status string) bool {
+ return status == config.ReportScheduleLastRunFailed || status == config.ReportScheduleLastRunRetrying || status == config.ReportScheduleLastRunUnconfirmed
+}
+
+// The caller owns scheduleRunMu across load, side effect and final persistence.
+// Persisting running first makes a lost completion record visible after restart.
+func (h *ReportingHandlers) executeReportSchedule(ctx context.Context, persistence *config.ConfigPersistence, store *config.ReportScheduleStore, index int, now time.Time, manual bool, key string, retry bool) (reportScheduleRunResult, config.ReportSchedule, error) {
+ schedule := config.NormalizeReportSchedule(store.Schedules[index])
+ if !retry {
+ windowEnd := now.UTC().Truncate(time.Second)
+ schedule.RunWindowEnd = &windowEnd
+ schedule.RunManual = manual
+ if manual && key == "" {
+ key = currentReportScheduleOccurrenceKey(schedule, now)
+ }
+ }
+ // An explicit operator retry starts a fresh bounded delivery budget.
+ if !retry || manual {
+ schedule.RunAttempts = 0
+ }
+ schedule.RunAttempts++
+ schedule.LastRunStatus = config.ReportScheduleLastRunRunning
+ schedule.LastDeliveryStatus = ""
+ schedule.LastError = ""
+ schedule.RetryAt = nil
+ schedule.LastRunAt = &now
+ schedule.UpdatedAt = now
+ if key != "" {
+ schedule.LastOccurrenceKey = key
+ }
+ if next, err := nextReportScheduleRunAt(schedule, now); err == nil {
+ schedule.NextRunAt = &next
+ }
+ store.Schedules[index] = schedule
+ if err := persistence.SaveReportScheduleStore(*store); err != nil {
+ return reportScheduleRunResult{}, schedule, err
+ }
+ started := time.Now()
+ result, updated := h.runReportSchedule(ctx, persistence, schedule, now, schedule.RunManual, "")
+ completed := now.Add(time.Since(started)).UTC()
+ updated.UpdatedAt = completed
+ if updated.RetryAt != nil {
+ retryAt := completed.Add(updated.RetryAt.Sub(now))
+ updated.RetryAt = &retryAt
+ }
+ if updated.LastRunStatus == config.ReportScheduleLastRunOK {
+ updated.LastSuccessAt = &completed
+ }
+ store.Schedules[index] = updated
+ return result, updated, persistence.SaveReportScheduleStore(*store)
+}
+
func (h *ReportingHandlers) prepareReportSchedule(ctx context.Context, schedule config.ReportSchedule, now time.Time, statusOnly bool) (config.ReportSchedule, error) {
schedule = config.NormalizeReportSchedule(schedule)
if schedule.ID == "" {
@@ -301,7 +434,11 @@ func (h *ReportingHandlers) prepareReportSchedule(ctx context.Context, schedule
switch schedule.Kind {
case config.ReportScheduleKindResources:
case config.ReportScheduleKindPatrolDigest:
- return preparePatrolDigestSchedule(schedule, now)
+ prepared, err := preparePatrolDigestSchedule(schedule, now)
+ if err != nil {
+ return prepared, err
+ }
+ return prepared, h.validateEnabledReportDelivery(ctx, prepared)
default:
return schedule, reportScheduleValidationError{code: "invalid_kind", message: "Schedule kind must be resources or patrol_digest"}
}
@@ -321,6 +458,8 @@ func (h *ReportingHandlers) prepareReportSchedule(ctx context.Context, schedule
schedule.Delivery.Attach = true
schedule.Delivery.SaveToDisk = true
}
+ // Resource reports have always been retained on disk, including email runs.
+ schedule.Delivery.SaveToDisk = true
if err := validateReportScheduleCadence(schedule.Cadence); err != nil {
return schedule, err
}
@@ -332,7 +471,7 @@ func (h *ReportingHandlers) prepareReportSchedule(ctx context.Context, schedule
return schedule, err
}
schedule.NextRunAt = &next
- return schedule, nil
+ return schedule, h.validateEnabledReportDelivery(ctx, schedule)
}
func validateReportScheduleCadence(cadence config.ReportScheduleCadence) error {
@@ -454,11 +593,11 @@ type reportScheduleRunResult struct {
}
func (h *ReportingHandlers) runReportSchedule(ctx context.Context, persistence *config.ConfigPersistence, schedule config.ReportSchedule, now time.Time, manual bool, occurrenceKey string) (reportScheduleRunResult, config.ReportSchedule) {
- h.scheduleRunMu.Lock()
- defer h.scheduleRunMu.Unlock()
-
schedule = config.NormalizeReportSchedule(schedule)
result := reportScheduleRunResult{}
+ if schedule.RunAttempts < 1 {
+ schedule.RunAttempts = 1
+ }
schedule.LastRunAt = &now
schedule.UpdatedAt = now
if occurrenceKey != "" {
@@ -473,13 +612,22 @@ func (h *ReportingHandlers) runReportSchedule(ctx context.Context, persistence *
if schedule.Kind == config.ReportScheduleKindPatrolDigest {
return h.runPatrolDigestSchedule(ctx, persistence, schedule, now)
}
+ if schedule.Delivery.Method == config.ReportScheduleDeliveryEmail {
+ if _, err := scheduledReportEmailManager(persistence, schedule); err != nil {
+ return result, markReportScheduleDeliveryFailed(schedule, now, err)
+ }
+ }
orgID := GetOrgID(ctx)
resources, err := h.resolveReportScheduleResources(ctx, orgID, schedule.Scope)
if err != nil {
return result, markReportScheduleFailed(schedule, now, err)
}
- start, end, err := reportScheduleWindow(schedule, now, manual)
+ windowEnd := now
+ if schedule.RunWindowEnd != nil {
+ windowEnd = *schedule.RunWindowEnd
+ }
+ start, end, err := reportScheduleWindow(schedule, windowEnd, manual)
if err != nil {
return result, markReportScheduleFailed(schedule, now, err)
}
@@ -500,17 +648,22 @@ func (h *ReportingHandlers) runReportSchedule(ctx context.Context, persistence *
return result, markReportScheduleFailed(schedule, now, err)
}
result.path = path
+ schedule.LastReportPath = path
+ schedule.LastDeliveryStatus = "saved"
if schedule.Delivery.Method == config.ReportScheduleDeliveryEmail {
emailStatus, err := sendScheduledReportEmail(persistence, schedule, report, path)
if err != nil {
- return result, markReportScheduleFailed(schedule, now, err)
+ return result, markReportScheduleDeliveryFailed(schedule, now, err)
}
result.email = emailStatus
+ schedule.LastDeliveryStatus = emailStatus
}
schedule.LastRunStatus = config.ReportScheduleLastRunOK
schedule.LastError = ""
+ schedule.RetryAt = nil
+ schedule.LastSuccessAt = &now
return result, schedule
}
@@ -519,6 +672,49 @@ func markReportScheduleFailed(schedule config.ReportSchedule, now time.Time, err
schedule.LastError = strings.TrimSpace(err.Error())
schedule.LastRunAt = &now
schedule.UpdatedAt = now
+ schedule.RetryAt = nil
+ return schedule
+}
+
+func markReportScheduleDeliveryFailed(schedule config.ReportSchedule, now time.Time, err error) config.ReportSchedule {
+ schedule = markReportScheduleFailed(schedule, now, err)
+ schedule.LastDeliveryStatus = "failed"
+ var unconfirmed *notifications.EmailAcceptanceUnconfirmedError
+ if errors.As(err, &unconfirmed) {
+ schedule.LastRunStatus = config.ReportScheduleLastRunUnconfirmed
+ schedule.LastDeliveryStatus = "unconfirmed"
+ schedule.LastError = "The mail server may have accepted the report. Check the recipient before retrying to avoid a duplicate."
+ return schedule
+ }
+ class := notifications.ClassifyNotificationFailureError(err)
+ switch class {
+ case notifications.NotificationFailureAuthentication:
+ schedule.LastError = "Email authentication failed. Check the credentials in Alerts > Notifications."
+ case notifications.NotificationFailureConfiguration:
+ var setup reportScheduleValidationError
+ if errors.As(err, &setup) {
+ schedule.LastError = setup.message
+ } else {
+ schedule.LastError = "Email configuration was rejected. Check Alerts > Notifications."
+ }
+ case notifications.NotificationFailureRejected:
+ schedule.LastError = "The mail server rejected this report. Check the recipient and notification settings."
+ case notifications.NotificationFailureTLS:
+ schedule.LastError = "The secure mail connection failed. Check the server certificate and TLS settings in Alerts > Notifications."
+ default:
+ schedule.LastError = "The mail server is temporarily unavailable. Check the connection and notification settings."
+ }
+ if class.Retryable() && schedule.Enabled && schedule.RunAttempts < reportScheduleMaxAttempts {
+ delay := time.Minute
+ if schedule.RunAttempts >= 2 {
+ delay = 5 * time.Minute
+ }
+ retryAt := now.Add(delay)
+ schedule.RetryAt = &retryAt
+ schedule.LastRunStatus = config.ReportScheduleLastRunRetrying
+ } else if class.Retryable() && schedule.RunAttempts >= reportScheduleMaxAttempts {
+ schedule.LastError = "Delivery failed after 3 attempts. " + schedule.LastError
+ }
return schedule
}
@@ -612,16 +808,23 @@ func pruneGeneratedReports(dir string, retentionCount int) {
}
}
-// scheduledReportEmailManager builds the email manager for a schedule from the
-// tenant email config. It returns nil, nil when email is not configured or no
-// recipient can be resolved, so callers decide how to report that.
+func reportEmailConfigurationFailure(message string) error {
+ return notifications.FailWithClass(notifications.NotificationFailureConfiguration,
+ reportScheduleValidationError{code: "email_not_ready", message: message})
+}
+
+// Configuration validation and SMTP semantics remain owned by notifications.
+// Reporting persists the retry budget, so one attempt must be one SMTP send.
func scheduledReportEmailManager(persistence *config.ConfigPersistence, schedule config.ReportSchedule) (*notifications.EnhancedEmailManager, error) {
+ if persistence == nil {
+ return nil, reportEmailConfigurationFailure("Email configuration is unavailable. Check Alerts > Notifications.")
+ }
emailCfg, err := persistence.LoadEmailConfig()
if err != nil {
- return nil, fmt.Errorf("load email config: %w", err)
+ return nil, reportEmailConfigurationFailure("Email configuration could not be loaded. Check notification settings and server storage.")
}
if emailCfg == nil || !emailCfg.Enabled {
- return nil, nil
+ return nil, reportEmailConfigurationFailure("Enable email notifications in Alerts > Notifications before running this report.")
}
recipients := schedule.Delivery.To
if len(recipients) == 0 {
@@ -631,7 +834,7 @@ func scheduledReportEmailManager(persistence *config.ConfigPersistence, schedule
recipients = []string{emailCfg.From}
}
if len(recipients) == 0 {
- return nil, nil
+ return nil, reportEmailConfigurationFailure("Add report recipients or email notification recipients in Alerts > Notifications.")
}
providerConfig := notifications.EmailProviderConfig{
EmailConfig: notifications.EmailConfig{
@@ -647,13 +850,16 @@ func scheduledReportEmailManager(persistence *config.ConfigPersistence, schedule
RateLimit: emailCfg.RateLimit,
},
Provider: emailCfg.Provider,
- MaxRetries: 2,
- RetryDelay: 3,
+ MaxRetries: 0,
RateLimit: emailCfg.RateLimit,
StartTLS: emailCfg.StartTLS,
AuthRequired: emailCfg.Username != "" && emailCfg.Password != "",
}
- return notifications.NewEnhancedEmailManager(providerConfig), nil
+ manager := notifications.NewEnhancedEmailManager(providerConfig)
+ if err := manager.ValidateConfiguration(); err != nil {
+ return nil, reportEmailConfigurationFailure(err.Error())
+ }
+ return manager, nil
}
func sendScheduledReportEmail(persistence *config.ConfigPersistence, schedule config.ReportSchedule, report generatedMultiReport, path string) (string, error) {
@@ -661,9 +867,6 @@ func sendScheduledReportEmail(persistence *config.ConfigPersistence, schedule co
if err != nil {
return "", err
}
- if manager == nil {
- return "saved_to_disk_email_unconfigured", nil
- }
subject := "Pulse report: " + schedule.Name
htmlBody := "<p>Your scheduled Pulse report is ready.</p>"
textBody := "Your scheduled Pulse report is ready."
@@ -675,8 +878,7 @@ func sendScheduledReportEmail(persistence *config.ConfigPersistence, schedule co
Data: report.Data,
})
} else if schedule.Delivery.Attach && len(report.Data) > reportScheduleAttachmentLimitBytes {
- htmlBody = "<p>Your scheduled Pulse report was generated but is too large to attach.</p><p>Saved path: " + htmlEscape(path) + "</p>"
- textBody = "Your scheduled Pulse report was generated but is too large to attach.\nSaved path: " + path
+ return "", reportEmailConfigurationFailure("The report exceeds the 15 MiB attachment limit. Choose CSV or turn off Attach report to email a saved-path notice.")
} else {
htmlBody = "<p>Your scheduled Pulse report was generated and saved to disk.</p><p>Saved path: " + htmlEscape(path) + "</p>"
textBody = "Your scheduled Pulse report was generated and saved to disk.\nSaved path: " + path
@@ -921,21 +1123,81 @@ func purgeGeneratedReportsAfterDowngrade(persistence *config.ConfigPersistence)
}
func (h *ReportingHandlers) runDueReportSchedulesForOrg(ctx context.Context, orgID string, now time.Time) {
+ h.scheduleRunMu.Lock()
+ defer h.scheduleRunMu.Unlock()
persistence, store, err := h.reportSchedulePersistenceAndStore(ctx)
if err != nil {
log.Warn().Err(err).Str("org_id", orgID).Msg("report schedules: load store")
return
}
- changed := false
+ save := func(index int, schedule config.ReportSchedule) bool {
+ store.Schedules[index] = schedule
+ if err := persistence.SaveReportScheduleStore(*store); err != nil {
+ log.Warn().Err(err).Str("org_id", orgID).Msg("report schedules: save status")
+ return false
+ }
+ return true
+ }
for i := range store.Schedules {
+ if ctx.Err() != nil {
+ return
+ }
schedule := config.NormalizeReportSchedule(store.Schedules[i])
+ if schedule.LastRunStatus == config.ReportScheduleLastRunRunning {
+ schedule.UpdatedAt = now
+ schedule.RetryAt = nil
+ schedule.LastRunStatus = config.ReportScheduleLastRunFailed
+ schedule.LastError = "The previous report run ended before completion was recorded. Run it again."
+ if schedule.Delivery.Method == config.ReportScheduleDeliveryEmail {
+ schedule.LastRunStatus = config.ReportScheduleLastRunUnconfirmed
+ schedule.LastDeliveryStatus = "unconfirmed"
+ schedule.LastError = "The previous email run ended before delivery was recorded. Check the recipient before retrying to avoid a duplicate."
+ } else if schedule.Enabled && schedule.RunWindowEnd != nil && schedule.RunAttempts < reportScheduleMaxAttempts {
+ schedule.LastRunStatus = config.ReportScheduleLastRunRetrying
+ schedule.LastError = "Report generation was interrupted. Retrying the saved report window."
+ schedule.RetryAt = &now
+ }
+ if !save(i, schedule) {
+ return
+ }
+ }
if !schedule.Enabled {
+ if schedule.RetryAt != nil {
+ schedule.RetryAt = nil
+ schedule.RunWindowEnd = nil
+ schedule.LastRunStatus = config.ReportScheduleLastRunFailed
+ schedule.LastError = "Automatic retry cancelled because this schedule is disabled."
+ schedule.UpdatedAt = now
+ if !save(i, schedule) {
+ return
+ }
+ }
+ continue
+ }
+ if schedule.RetryAt != nil {
+ if schedule.LastRunStatus != config.ReportScheduleLastRunRetrying || schedule.RunWindowEnd == nil || schedule.RunAttempts >= reportScheduleMaxAttempts {
+ schedule.RetryAt = nil
+ schedule.LastRunStatus = config.ReportScheduleLastRunFailed
+ schedule.LastError = "The saved retry is incomplete or exhausted. Run a new report."
+ if !save(i, schedule) {
+ return
+ }
+ continue
+ }
+ if now.Before(*schedule.RetryAt) {
+ continue
+ }
+ if _, _, err := h.executeReportSchedule(ctx, persistence, store, i, now, false, "", true); err != nil {
+ log.Warn().Err(err).Str("org_id", orgID).Msg("report schedules: persist retry outcome")
+ return
+ }
continue
}
occurrence, key, err := lastReportScheduleOccurrenceAt(schedule, now)
if err != nil {
- store.Schedules[i] = markReportScheduleFailed(schedule, now, err)
- changed = true
+ if !save(i, markReportScheduleFailed(schedule, now, err)) {
+ return
+ }
continue
}
if key == "" || key == schedule.LastOccurrenceKey || occurrence.After(now) {
@@ -947,17 +1209,14 @@ func (h *ReportingHandlers) runDueReportSchedulesForOrg(ctx context.Context, org
schedule.NextRunAt = &next
}
schedule.UpdatedAt = now
- store.Schedules[i] = schedule
- changed = true
+ if !save(i, schedule) {
+ return
+ }
continue
}
- _, updated := h.runReportSchedule(ctx, persistence, schedule, now, false, key)
- store.Schedules[i] = updated
- changed = true
- }
- if changed {
- if err := persistence.SaveReportScheduleStore(*store); err != nil {
- log.Warn().Err(err).Str("org_id", orgID).Msg("report schedules: save statuses")
+ if _, _, err := h.executeReportSchedule(ctx, persistence, store, i, now, false, key, false); err != nil {
+ log.Warn().Err(err).Str("org_id", orgID).Msg("report schedules: persist outcome")
+ return
}
}
}
@@ -1004,18 +1263,18 @@ func (h *ReportingHandlers) runPatrolDigestSchedule(ctx context.Context, persist
}
manager, err := scheduledReportEmailManager(persistence, schedule)
if err != nil {
- return result, markReportScheduleFailed(schedule, now, err)
- }
- if manager == nil {
- return result, markReportScheduleFailed(schedule, now, errors.New("email notifications are not configured; add an email destination under Settings > Notifications or list recipients on the schedule"))
+ return result, markReportScheduleDeliveryFailed(schedule, now, err)
}
subject, htmlBody, textBody := renderPatrolDigestEmail(digest, h.patrolDigestPublicURL())
if err := manager.SendEmailWithRetry(subject, htmlBody, textBody); err != nil {
- return result, markReportScheduleFailed(schedule, now, fmt.Errorf("send Patrol weekly summary: %w", err))
+ return result, markReportScheduleDeliveryFailed(schedule, now, err)
}
result.email = "sent"
schedule.LastRunStatus = config.ReportScheduleLastRunOK
schedule.LastError = ""
+ schedule.LastDeliveryStatus = result.email
+ schedule.RetryAt = nil
+ schedule.LastSuccessAt = &now
return result, schedule
}
diff --git a/internal/api/report_schedules_test.go b/internal/api/report_schedules_test.go
index 7dc384e33b..9e2e650ed2 100644
--- a/internal/api/report_schedules_test.go
+++ b/internal/api/report_schedules_test.go
@@ -16,6 +16,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/ai"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
+ "github.com/rcourtman/pulse-go-rewrite/internal/notifications"
"github.com/rcourtman/pulse-go-rewrite/internal/securityutil"
"github.com/rcourtman/pulse-go-rewrite/pkg/reporting"
)
@@ -257,7 +258,10 @@ func TestSaveGeneratedReportUsesHashedScheduleDirectory(t *testing.T) {
}
func TestPreparePatrolDigestScheduleFixesFormatScopeAndDelivery(t *testing.T) {
- handlers, _ := newTestReportingScheduleHandlers(t)
+ handlers, persistence := newTestReportingScheduleHandlers(t)
+ if err := persistence.SaveEmailConfig(notifications.EmailConfig{Enabled: true, SMTPHost: "smtp.example.test", SMTPPort: 25, From: "[email protected]", To: []string{"[email protected]"}}); err != nil {
+ t.Fatal(err)
+ }
ctx := context.WithValue(context.Background(), OrgIDContextKey, "default")
now := time.Date(2026, 9, 2, 10, 0, 0, 0, time.UTC)
base := config.ReportSchedule{
@@ -348,7 +352,7 @@ func TestRunPatrolDigestScheduleFailsClearlyWithoutDigestOrEmail(t *testing.T) {
if calls != 1 {
t.Fatalf("resolver calls = %d, want 1", calls)
}
- if noEmail.LastRunStatus != config.ReportScheduleLastRunFailed || !strings.Contains(noEmail.LastError, "email notifications are not configured") {
+ if noEmail.LastRunStatus != config.ReportScheduleLastRunFailed || !strings.Contains(noEmail.LastError, "Enable email notifications") {
t.Fatalf("run without email config = %+v, want a failure that names the missing email destination", noEmail)
}
if noEmail.NextRunAt == nil {
diff --git a/internal/config/report_schedule_delivery_test.go b/internal/config/report_schedule_delivery_test.go
new file mode 100644
index 0000000000..32d5dd7bb7
--- /dev/null
+++ b/internal/config/report_schedule_delivery_test.go
@@ -0,0 +1,42 @@
+package config
+
+import (
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestReportScheduleDeliverySurvivesReload(t *testing.T) {
+ for _, encrypted := range []bool{false, true} {
+ t.Run(map[bool]string{false: "plain", true: "encrypted"}[encrypted], func(t *testing.T) {
+ dir := t.TempDir()
+ persistence := newPlainReportSchedulePersistence(dir)
+ if encrypted {
+ persistence = NewConfigPersistence(dir)
+ }
+ now := time.Date(2026, 10, 17, 9, 0, 0, 0, time.UTC)
+ retry := now.Add(time.Minute)
+ schedule := ReportSchedule{
+ ID: "delivery", LastRunAt: &now, LastRunStatus: ReportScheduleLastRunRetrying,
+ LastError: "Mail server temporarily unavailable", LastDeliveryStatus: "failed",
+ LastReportPath: "/owned/reports/report.csv", LastSuccessAt: &now,
+ RunAttempts: 1, RetryAt: &retry, RunWindowEnd: &now, RunManual: true,
+ LastOccurrenceKey: "weekly:2026-10-17T09:00:00Z:UTC",
+ }
+ require.NoError(t, persistence.SaveReportScheduleStore(ReportScheduleStore{Schedules: []ReportSchedule{schedule}}))
+ loaded, err := persistence.LoadReportScheduleStore()
+ require.NoError(t, err)
+ require.Equal(t, NormalizeReportSchedule(schedule), loaded.Schedules[0])
+ })
+ }
+}
+
+func TestLegacyReportScheduleHasNoInventedDeliveryOutcome(t *testing.T) {
+ store, err := parseReportScheduleStoreJSON([]byte(`[{"id":"old","last_run_status":"ok"}]`))
+ require.NoError(t, err)
+ require.Equal(t, ReportScheduleLastRunOK, store.Schedules[0].LastRunStatus)
+ require.Empty(t, store.Schedules[0].LastDeliveryStatus)
+ require.Nil(t, store.Schedules[0].RetryAt)
+ require.Zero(t, store.Schedules[0].RunAttempts)
+}
diff --git a/internal/config/report_schedules.go b/internal/config/report_schedules.go
index edfcc222d1..3756a9aebf 100644
--- a/internal/config/report_schedules.go
+++ b/internal/config/report_schedules.go
@@ -28,8 +28,11 @@ const (
ReportScheduleDeliveryEmail = "email"
ReportScheduleDeliveryDisk = "disk"
- ReportScheduleLastRunOK = "ok"
- ReportScheduleLastRunFailed = "failed"
+ ReportScheduleLastRunOK = "ok"
+ ReportScheduleLastRunFailed = "failed"
+ ReportScheduleLastRunRunning = "running"
+ ReportScheduleLastRunRetrying = "retrying"
+ ReportScheduleLastRunUnconfirmed = "unconfirmed"
DefaultReportScheduleRetentionCount = 12
)
@@ -39,23 +42,30 @@ type ReportScheduleStore struct {
}
type ReportSchedule struct {
- ID string `json:"id"`
- Name string `json:"name"`
- Enabled bool `json:"enabled"`
- Kind string `json:"kind,omitempty"`
- Cadence ReportScheduleCadence `json:"cadence"`
- Scope ReportScheduleScope `json:"scope"`
- Window string `json:"window,omitempty"`
- Format string `json:"format"`
- Delivery ReportScheduleDelivery `json:"delivery"`
- RetentionCount int `json:"retention_count,omitempty"`
- LastRunAt *time.Time `json:"last_run_at,omitempty"`
- LastRunStatus string `json:"last_run_status,omitempty"`
- LastError string `json:"last_error,omitempty"`
- NextRunAt *time.Time `json:"next_run_at,omitempty"`
- LastOccurrenceKey string `json:"last_occurrence_key,omitempty"`
- CreatedAt time.Time `json:"created_at"`
- UpdatedAt time.Time `json:"updated_at"`
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Enabled bool `json:"enabled"`
+ Kind string `json:"kind,omitempty"`
+ Cadence ReportScheduleCadence `json:"cadence"`
+ Scope ReportScheduleScope `json:"scope"`
+ Window string `json:"window,omitempty"`
+ Format string `json:"format"`
+ Delivery ReportScheduleDelivery `json:"delivery"`
+ RetentionCount int `json:"retention_count,omitempty"`
+ LastRunAt *time.Time `json:"last_run_at,omitempty"`
+ LastRunStatus string `json:"last_run_status,omitempty"`
+ LastError string `json:"last_error,omitempty"`
+ LastDeliveryStatus string `json:"last_delivery_status,omitempty"`
+ LastReportPath string `json:"last_report_path,omitempty"`
+ LastSuccessAt *time.Time `json:"last_success_at,omitempty"`
+ RunAttempts int `json:"run_attempts,omitempty"`
+ RetryAt *time.Time `json:"retry_at,omitempty"`
+ RunWindowEnd *time.Time `json:"run_window_end,omitempty"`
+ RunManual bool `json:"run_manual,omitempty"`
+ NextRunAt *time.Time `json:"next_run_at,omitempty"`
+ LastOccurrenceKey string `json:"last_occurrence_key,omitempty"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
}
type ReportScheduleCadence struct {
@@ -114,6 +124,10 @@ func NormalizeReportSchedule(schedule ReportSchedule) ReportSchedule {
schedule.Delivery.Method = strings.ToLower(strings.TrimSpace(schedule.Delivery.Method))
schedule.LastRunStatus = strings.ToLower(strings.TrimSpace(schedule.LastRunStatus))
schedule.LastError = strings.TrimSpace(schedule.LastError)
+ schedule.LastDeliveryStatus = strings.TrimSpace(schedule.LastDeliveryStatus)
+ if schedule.RunAttempts < 0 {
+ schedule.RunAttempts = 0
+ }
schedule.LastOccurrenceKey = strings.TrimSpace(schedule.LastOccurrenceKey)
if schedule.RetentionCount <= 0 {
schedule.RetentionCount = DefaultReportScheduleRetentionCount
diff --git a/internal/notifications/email_acceptance_test.go b/internal/notifications/email_acceptance_test.go
index b81b61c069..7cee7578ce 100644
--- a/internal/notifications/email_acceptance_test.go
+++ b/internal/notifications/email_acceptance_test.go
@@ -2,6 +2,7 @@ package notifications
import (
"crypto/tls"
+ "errors"
"fmt"
"net"
"net/http"
@@ -134,7 +135,7 @@ func TestSMTPDeliveryAcceptanceSurvivesCleanup(t *testing.T) {
{"auth prose at QUIT", "535 private-cleanup-token", 250, "", 1},
{"message rejected", "221 Bye", 550, NotificationFailureRejected, 1},
{"temporary message failure", "221 Bye", 451, NotificationFailureServerError, 3},
- {"missing acceptance", "221 Bye", 0, NotificationFailureUnknown, 3},
+ {"missing acceptance", "221 Bye", 0, NotificationFailureUnknown, 1},
} {
t.Run(mode+"/"+tc.name, func(t *testing.T) {
manager, connections, accepted := acceptanceSMTPServer(t, mode, tc.dataCode, tc.quit)
@@ -146,6 +147,12 @@ func TestSMTPDeliveryAcceptanceSurvivesCleanup(t *testing.T) {
if tc.class != "" && ClassifyNotificationFailureError(err) != tc.class {
t.Errorf("failure class = %q; want %q", ClassifyNotificationFailureError(err), tc.class)
}
+ if tc.dataCode == 0 {
+ var unconfirmed *EmailAcceptanceUnconfirmedError
+ if !errors.As(err, &unconfirmed) {
+ t.Errorf("missing acceptance must retain typed uncertainty: %v", err)
+ }
+ }
if got := connections.Load(); got != tc.attempts {
t.Errorf("connections = %d; want %d", got, tc.attempts)
}
diff --git a/internal/notifications/email_delivery_test.go b/internal/notifications/email_delivery_test.go
new file mode 100644
index 0000000000..bc589ed18c
--- /dev/null
+++ b/internal/notifications/email_delivery_test.go
@@ -0,0 +1,95 @@
+package notifications
+
+import (
+ "errors"
+ "net"
+ "net/textproto"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestEmailDeliveryConfigurationCheck(t *testing.T) {
+ valid := EmailProviderConfig{EmailConfig: EmailConfig{
+ SMTPHost: "smtp.example.test", SMTPPort: 25, From: "[email protected]", To: []string{"[email protected]"},
+ }}
+ for _, tc := range []struct {
+ name string
+ change func(*EmailProviderConfig)
+ }{
+ {"host", func(c *EmailProviderConfig) { c.SMTPHost = "" }},
+ {"port", func(c *EmailProviderConfig) { c.SMTPPort = 65536 }},
+ {"sender", func(c *EmailProviderConfig) { c.From = "invalid" }},
+ {"recipient", func(c *EmailProviderConfig) { c.To = []string{"invalid"} }},
+ {"no recipient", func(c *EmailProviderConfig) { c.To = nil }},
+ {"partial credentials", func(c *EmailProviderConfig) { c.Username = "user" }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ cfg := valid
+ tc.change(&cfg)
+ err := NewEnhancedEmailManager(cfg).ValidateConfiguration()
+ require.Error(t, err)
+ require.Equal(t, NotificationFailureConfiguration, ClassifyNotificationFailureError(err))
+ })
+ }
+ require.NoError(t, NewEnhancedEmailManager(valid).ValidateConfiguration())
+ valid.Provider = "SendGrid"
+ valid.Password = "test-provider-credential"
+ valid.AuthRequired = true
+ require.NoError(t, NewEnhancedEmailManager(valid).ValidateConfiguration())
+}
+
+func TestEmailDoesNotRepeatUnconfirmedCompletedMessage(t *testing.T) {
+ var servers sync.WaitGroup
+ originalDial := smtpDialTimeout
+ t.Cleanup(func() { smtpDialTimeout = originalDial; servers.Wait() })
+ attempts := 0
+ smtpDialTimeout = func(string, string, time.Duration) (net.Conn, error) {
+ attempts++
+ client, server := net.Pipe()
+ servers.Add(1)
+ go func() {
+ defer servers.Done()
+ defer server.Close()
+ _ = server.SetDeadline(time.Now().Add(5 * time.Second))
+ conn := textproto.NewConn(server)
+ if conn.PrintfLine("220 smtp.example.test") != nil {
+ return
+ }
+ for {
+ line, err := conn.ReadLine()
+ if err != nil {
+ return
+ }
+ switch strings.Fields(line)[0] {
+ case "EHLO", "HELO", "MAIL", "RCPT":
+ if conn.PrintfLine("250 OK") != nil {
+ return
+ }
+ case "DATA":
+ if conn.PrintfLine("354 Send message") != nil {
+ return
+ }
+ _, _ = conn.ReadDotBytes()
+ // The server has the message but drops before its final verdict.
+ return
+ default:
+ t.Errorf("unexpected command %q", line)
+ return
+ }
+ }
+ }()
+ return client, nil
+ }
+ manager := NewEnhancedEmailManager(EmailProviderConfig{
+ EmailConfig: EmailConfig{SMTPHost: "smtp.example.test", SMTPPort: 25, From: "[email protected]", To: []string{"[email protected]"}},
+ MaxRetries: 2,
+ })
+ err := manager.SendEmailWithAttachments("test", "<p>test</p>", "test", []EmailAttachment{{Filename: "report.csv", Data: []byte("cpu\n42")}})
+ var unconfirmed *EmailAcceptanceUnconfirmedError
+ require.True(t, errors.As(err, &unconfirmed), "expected an explicit uncertain acceptance result, got %v", err)
+ require.Equal(t, 1, attempts, "repeating this message could create duplicates")
+}
diff --git a/internal/notifications/email_enhanced.go b/internal/notifications/email_enhanced.go
index 4c26697a00..e398fb39d2 100644
--- a/internal/notifications/email_enhanced.go
+++ b/internal/notifications/email_enhanced.go
@@ -6,6 +6,7 @@ import (
"crypto/tls"
"encoding/base64"
"encoding/hex"
+ "errors"
"fmt"
"io"
"mime"
@@ -533,6 +534,40 @@ func (e *EnhancedEmailManager) SendEmailWithAttachments(subject, htmlBody, textB
return e.sendEmailWithOptions(subject, htmlBody, textBody, attachments, "")
}
+// ValidateConfiguration checks delivery inputs without contacting the server or
+// sending mail. Authentication and connectivity are established by a real send.
+func (e *EnhancedEmailManager) ValidateConfiguration() error {
+ if strings.TrimSpace(e.config.SMTPHost) == "" || e.config.SMTPPort < 1 || e.config.SMTPPort > 65535 {
+ return FailfWithClass(NotificationFailureConfiguration, "configure an SMTP server and valid port in email notification settings")
+ }
+ username := resolveProviderUsername(e.config)
+ if (username == "") != (e.config.Password == "") || (e.config.AuthRequired && username == "") {
+ return FailfWithClass(NotificationFailureConfiguration, "complete the email notification credentials")
+ }
+ if _, err := e.resolveEmailAddresses(); err != nil {
+ return FailfWithClass(NotificationFailureConfiguration, "configure valid sender and recipient email addresses")
+ }
+ return nil
+}
+
+// EmailAcceptanceUnconfirmedError means the connection ended while waiting for
+// the completed-message verdict. SMTP may already have accepted the message.
+// Callers must not assume failure is proof that another send is duplicate-free.
+type EmailAcceptanceUnconfirmedError struct{ Err error }
+
+func (e *EmailAcceptanceUnconfirmedError) Error() string {
+ return "mail server acceptance could not be confirmed"
+}
+func (e *EmailAcceptanceUnconfirmedError) Unwrap() error { return e.Err }
+
+func completedEmailError(err error) error {
+ var reply *textproto.Error
+ if errors.As(err, &reply) {
+ return err
+ }
+ return &EmailAcceptanceUnconfirmedError{Err: err}
+}
+
func (e *EnhancedEmailManager) sendEmailWithOptions(subject, htmlBody, textBody string, attachments []EmailAttachment, threadID string) error {
var lastErr error
@@ -570,7 +605,8 @@ func (e *EnhancedEmailManager) sendEmailWithOptions(subject, htmlBody, textBody
Str("provider", e.config.Provider).
Msg("email send attempt failed")
- if !ClassifyNotificationFailureError(err).Retryable() {
+ var unconfirmed *EmailAcceptanceUnconfirmedError
+ if errors.As(err, &unconfirmed) || !ClassifyNotificationFailureError(err).Retryable() {
return fmt.Errorf("email failed after %d attempts: %w", attempt+1, err)
}
}
@@ -707,7 +743,7 @@ func (e *EnhancedEmailManager) sendTLS(addr string, msg []byte, addresses resolv
err = w.Close()
if err != nil {
- return fmt.Errorf("message close failed: %w", err)
+ return fmt.Errorf("message close failed: %w", completedEmailError(err))
}
finishAcceptedSMTPSession(client)
@@ -778,7 +814,7 @@ func (e *EnhancedEmailManager) sendStartTLS(addr string, msg []byte, addresses r
err = w.Close()
if err != nil {
- return fmt.Errorf("message close failed: %w", err)
+ return fmt.Errorf("message close failed: %w", completedEmailError(err))
}
finishAcceptedSMTPSession(client)
@@ -899,7 +935,7 @@ func (e *EnhancedEmailManager) sendPlain(addr string, msg []byte, addresses reso
err = w.Close()
if err != nil {
- return fmt.Errorf("message close failed: %w", err)
+ return fmt.Errorf("message close failed: %w", completedEmailError(err))
}
finishAcceptedSMTPSession(client)