From 10b21f9e84c401c1266093f9320f9c828208dc9c Mon Sep 17 00:00:00 2001
From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com>
Date: Fri, 6 Nov 2026 23:30:34 -0500
Subject: [PATCH 1/4] Alert when a scheduled report sends no email
A scheduled report can stop without anyone knowing: the plan gate makes
the Trigger runner exit quietly, runs can stall, and sends can be
rejected. An hourly cron now lists customer-prompt-task runs that
started 2-3 hours ago, and for each task that asks for an email checks
whether its account sent one since the run started. Misses are
classified (plan blocked, email rejected with its reason, or no send
attempted with the run status), posted to the team on Telegram, and,
when MISSED_REPORT_CUSTOMER_NOTICES is "true", emailed to the owner:
the upgrade link for a plan block, otherwise a heads-up for the catalog
report tasks that always email.
The hourly window is the deduplication: each run is checked once.
pickAccountRecipient is extracted from sendAutoTopUpEmail for reuse.
Refs recoupable/app#1949, recoupable/app#2022
Co-Authored-By: Claude Opus 5.5
---
app/api/internal/missed-report-check/route.ts | 18 +++
lib/credits/sendAutoTopUpEmail.ts | 10 +-
.../__tests__/pickAccountRecipient.test.ts | 19 ++++
lib/emails/pickAccountRecipient.ts | 14 +++
.../checkMissedReportsHandler.test.ts | 103 ++++++++++++++++++
.../__tests__/findMissedReport.test.ts | 85 +++++++++++++++
lib/tasks/missedReports/__tests__/fixtures.ts | 23 ++++
.../formatMissedReportsAlert.test.ts | 46 ++++++++
.../__tests__/listScheduledReportRuns.test.ts | 82 ++++++++++++++
.../__tests__/sendMissedReportNotice.test.ts | 77 +++++++++++++
.../checkMissedReportsHandler.ts | 67 ++++++++++++
lib/tasks/missedReports/findMissedReport.ts | 61 +++++++++++
.../missedReports/formatMissedReportsAlert.ts | 24 ++++
.../missedReports/listScheduledReportRuns.ts | 53 +++++++++
.../missedReports/sendMissedReportNotice.ts | 46 ++++++++
lib/tasks/missedReports/types.ts | 31 ++++++
.../__tests__/fetchTriggerRuns.test.ts | 30 +++++
lib/trigger/fetchTriggerRuns.ts | 11 +-
vercel.json | 4 +
19 files changed, 794 insertions(+), 10 deletions(-)
create mode 100644 app/api/internal/missed-report-check/route.ts
create mode 100644 lib/emails/__tests__/pickAccountRecipient.test.ts
create mode 100644 lib/emails/pickAccountRecipient.ts
create mode 100644 lib/tasks/missedReports/__tests__/checkMissedReportsHandler.test.ts
create mode 100644 lib/tasks/missedReports/__tests__/findMissedReport.test.ts
create mode 100644 lib/tasks/missedReports/__tests__/fixtures.ts
create mode 100644 lib/tasks/missedReports/__tests__/formatMissedReportsAlert.test.ts
create mode 100644 lib/tasks/missedReports/__tests__/listScheduledReportRuns.test.ts
create mode 100644 lib/tasks/missedReports/__tests__/sendMissedReportNotice.test.ts
create mode 100644 lib/tasks/missedReports/checkMissedReportsHandler.ts
create mode 100644 lib/tasks/missedReports/findMissedReport.ts
create mode 100644 lib/tasks/missedReports/formatMissedReportsAlert.ts
create mode 100644 lib/tasks/missedReports/listScheduledReportRuns.ts
create mode 100644 lib/tasks/missedReports/sendMissedReportNotice.ts
create mode 100644 lib/tasks/missedReports/types.ts
create mode 100644 lib/trigger/__tests__/fetchTriggerRuns.test.ts
diff --git a/app/api/internal/missed-report-check/route.ts b/app/api/internal/missed-report-check/route.ts
new file mode 100644
index 000000000..518c96713
--- /dev/null
+++ b/app/api/internal/missed-report-check/route.ts
@@ -0,0 +1,18 @@
+import { NextRequest, NextResponse } from "next/server";
+import { checkMissedReportsHandler } from "@/lib/tasks/missedReports/checkMissedReportsHandler";
+
+export const dynamic = "force-dynamic";
+export const fetchCache = "force-no-store";
+export const revalidate = 0;
+
+/**
+ * GET /api/internal/missed-report-check — hourly Vercel Cron entrypoint that
+ * finds scheduled reports that sent no email, tells the owner and alerts the
+ * team on Telegram. Cron-only (CRON_SECRET bearer).
+ *
+ * @param request - The incoming Next.js request.
+ * @returns A NextResponse with how many runs were checked, missed and notified.
+ */
+export async function GET(request: NextRequest): Promise {
+ return checkMissedReportsHandler(request);
+}
diff --git a/lib/credits/sendAutoTopUpEmail.ts b/lib/credits/sendAutoTopUpEmail.ts
index da5b5ff42..e38d9c84e 100644
--- a/lib/credits/sendAutoTopUpEmail.ts
+++ b/lib/credits/sendAutoTopUpEmail.ts
@@ -1,6 +1,7 @@
import selectAccountEmails from "@/lib/supabase/account_emails/selectAccountEmails";
import { sendEmailWithResend } from "@/lib/emails/sendEmail";
import { escapeHtml } from "@/lib/emails/escapeHtml";
+import { pickAccountRecipient } from "@/lib/emails/pickAccountRecipient";
import { RECOUP_FROM_EMAIL } from "@/lib/const";
import { CREDIT_BILLING_URL } from "@/lib/credits/const";
@@ -27,20 +28,13 @@ const describeCard = (card?: ChargedCard): string =>
const BILLING_URL = `${CREDIT_BILLING_URL}/billing`;
-/** The account's most recently updated non-empty email, or null. */
-function pickRecipient(rows: { email: string | null; updated_at?: string }[]): string | null {
- const withEmail = rows.filter(r => r.email);
- withEmail.sort((a, b) => (b.updated_at ?? "").localeCompare(a.updated_at ?? ""));
- return withEmail[0]?.email ?? null;
-}
-
/**
* Receipt after a successful auto top-up charge (the credits land via the
* payment_intent.succeeded webhook moments later), or the notice that a
* decline turned auto top-up off. Silent when the account has no email.
*/
export async function sendAutoTopUpEmail(params: AutoTopUpEmail): Promise {
- const to = pickRecipient(await selectAccountEmails({ accountIds: params.accountId }));
+ const to = pickAccountRecipient(await selectAccountEmails({ accountIds: params.accountId }));
if (!to) {
console.warn(`[sendAutoTopUpEmail] no email for account ${params.accountId}`);
return;
diff --git a/lib/emails/__tests__/pickAccountRecipient.test.ts b/lib/emails/__tests__/pickAccountRecipient.test.ts
new file mode 100644
index 000000000..c471fc89a
--- /dev/null
+++ b/lib/emails/__tests__/pickAccountRecipient.test.ts
@@ -0,0 +1,19 @@
+import { describe, it, expect } from "vitest";
+import { pickAccountRecipient } from "../pickAccountRecipient";
+
+describe("pickAccountRecipient", () => {
+ it("returns the most recently updated non-empty email", () => {
+ expect(
+ pickAccountRecipient([
+ { email: "old@example.com", updated_at: "2026-01-01T00:00:00Z" },
+ { email: null, updated_at: "2026-09-01T00:00:00Z" },
+ { email: "new@example.com", updated_at: "2026-06-01T00:00:00Z" },
+ ]),
+ ).toBe("new@example.com");
+ });
+
+ it("returns null when the account has no email", () => {
+ expect(pickAccountRecipient([{ email: null }])).toBeNull();
+ expect(pickAccountRecipient([])).toBeNull();
+ });
+});
diff --git a/lib/emails/pickAccountRecipient.ts b/lib/emails/pickAccountRecipient.ts
new file mode 100644
index 000000000..ded179837
--- /dev/null
+++ b/lib/emails/pickAccountRecipient.ts
@@ -0,0 +1,14 @@
+/**
+ * The account's most recently updated non-empty email, or null — the one
+ * address an account-level notice goes to.
+ *
+ * @param rows - The account's `account_emails` rows.
+ * @returns The chosen address, or null when the account has none.
+ */
+export function pickAccountRecipient(
+ rows: { email: string | null; updated_at?: string }[],
+): string | null {
+ const withEmail = rows.filter(r => r.email);
+ withEmail.sort((a, b) => (b.updated_at ?? "").localeCompare(a.updated_at ?? ""));
+ return withEmail[0]?.email ?? null;
+}
diff --git a/lib/tasks/missedReports/__tests__/checkMissedReportsHandler.test.ts b/lib/tasks/missedReports/__tests__/checkMissedReportsHandler.test.ts
new file mode 100644
index 000000000..362146166
--- /dev/null
+++ b/lib/tasks/missedReports/__tests__/checkMissedReportsHandler.test.ts
@@ -0,0 +1,103 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { NextRequest, NextResponse } from "next/server";
+import { reportRun, reportTask } from "./fixtures";
+
+const mockValidate = vi.fn();
+vi.mock("@/lib/internal/validateCronRequest", () => ({
+ validateCronRequest: (...args: unknown[]) => mockValidate(...args),
+}));
+const mockListRuns = vi.fn();
+vi.mock("../listScheduledReportRuns", () => ({
+ listScheduledReportRuns: (...args: unknown[]) => mockListRuns(...args),
+}));
+const mockSelectTasks = vi.fn();
+vi.mock("@/lib/supabase/scheduled_actions/selectScheduledActions", () => ({
+ selectScheduledActions: (...args: unknown[]) => mockSelectTasks(...args),
+}));
+const mockFindMissed = vi.fn();
+vi.mock("../findMissedReport", () => ({
+ findMissedReport: (...args: unknown[]) => mockFindMissed(...args),
+}));
+const mockNotice = vi.fn();
+vi.mock("../sendMissedReportNotice", () => ({
+ sendMissedReportNotice: (...args: unknown[]) => mockNotice(...args),
+}));
+const mockSendMessage = vi.fn();
+vi.mock("@/lib/telegram/sendMessage", () => ({
+ sendMessage: (...args: unknown[]) => mockSendMessage(...args),
+}));
+
+const { checkMissedReportsHandler } = await import("../checkMissedReportsHandler");
+
+const request = () => new NextRequest("http://localhost/api/internal/missed-report-check");
+const miss = { task: reportTask, run: reportRun, cause: "no_email", detail: "run completed" };
+
+describe("checkMissedReportsHandler", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-11-06T13:17:00.000Z"));
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ mockValidate.mockReturnValue(null);
+ mockListRuns.mockResolvedValue([reportRun]);
+ mockSelectTasks.mockResolvedValue([reportTask]);
+ mockFindMissed.mockResolvedValue(null);
+ mockNotice.mockResolvedValue(true);
+ });
+ afterEach(() => vi.useRealTimers());
+
+ it("rejects callers other than Vercel Cron", async () => {
+ mockValidate.mockReturnValue(NextResponse.json({}, { status: 401 }));
+ const response = await checkMissedReportsHandler(request());
+ expect(response.status).toBe(401);
+ expect(mockListRuns).not.toHaveBeenCalled();
+ });
+
+ // Hourly cron + a one-hour window that ends two hours ago: each run is
+ // checked exactly once, after a two-hour grace for long reports.
+ it("checks runs that started two to three hours ago", async () => {
+ await checkMissedReportsHandler(request());
+ expect(mockListRuns).toHaveBeenCalledWith({
+ from: "2026-11-06T10:17:00.000Z",
+ to: "2026-11-06T11:17:00.000Z",
+ });
+ });
+
+ it("stays quiet when every report went out", async () => {
+ const response = await checkMissedReportsHandler(request());
+ expect(await response.json()).toEqual({ status: "ok", checked: 1, missed: 0, notified: 0 });
+ expect(mockSendMessage).not.toHaveBeenCalled();
+ });
+
+ it("emails the customer and alerts the team about a missed report", async () => {
+ mockFindMissed.mockResolvedValue(miss);
+ const response = await checkMissedReportsHandler(request());
+ expect(await response.json()).toEqual({ status: "ok", checked: 1, missed: 1, notified: 1 });
+ expect(mockNotice).toHaveBeenCalledWith(miss);
+ expect(mockSendMessage).toHaveBeenCalledTimes(1);
+ expect(mockSendMessage.mock.calls[0][0]).toContain("customer emailed");
+ });
+
+ it("skips runs whose task was deleted or turned off", async () => {
+ mockListRuns.mockResolvedValue([reportRun, { ...reportRun, runId: "run_2", taskId: "gone" }]);
+ mockSelectTasks.mockImplementation(async ({ id }: { id: string }) =>
+ id === "gone" ? [] : [{ ...reportTask, enabled: false }],
+ );
+ await checkMissedReportsHandler(request());
+ expect(mockFindMissed).not.toHaveBeenCalled();
+ });
+
+ it("still alerts the team when the customer notice throws", async () => {
+ mockFindMissed.mockResolvedValue(miss);
+ mockNotice.mockRejectedValue(new Error("resend down"));
+ const response = await checkMissedReportsHandler(request());
+ expect(await response.json()).toMatchObject({ missed: 1, notified: 0 });
+ expect(mockSendMessage.mock.calls[0][0]).toContain("customer not emailed");
+ });
+
+ it("returns 500 when the run list cannot be read", async () => {
+ mockListRuns.mockRejectedValue(new Error("trigger down"));
+ const response = await checkMissedReportsHandler(request());
+ expect(response.status).toBe(500);
+ });
+});
diff --git a/lib/tasks/missedReports/__tests__/findMissedReport.test.ts b/lib/tasks/missedReports/__tests__/findMissedReport.test.ts
new file mode 100644
index 000000000..f30d6513c
--- /dev/null
+++ b/lib/tasks/missedReports/__tests__/findMissedReport.test.ts
@@ -0,0 +1,85 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { reportRun, reportTask } from "./fixtures";
+
+const mockSelectEmailSendLog = vi.fn();
+vi.mock("@/lib/supabase/email_send_log/selectEmailSendLog", () => ({
+ selectEmailSendLog: (...args: unknown[]) => mockSelectEmailSendLog(...args),
+}));
+
+const mockGetTaskRunBlock = vi.fn();
+vi.mock("@/lib/plans/getTaskRunBlock", () => ({
+ getTaskRunBlock: (...args: unknown[]) => mockGetTaskRunBlock(...args),
+}));
+
+const { findMissedReport } = await import("../findMissedReport");
+
+const row = (status: string, created_at: string, reason: string | null = null) => ({
+ id: created_at,
+ account_id: "acc-1",
+ chat_id: null,
+ created_at,
+ raw_body: "{}",
+ reason,
+ resend_id: null,
+ status,
+});
+
+describe("findMissedReport", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockSelectEmailSendLog.mockResolvedValue([]);
+ mockGetTaskRunBlock.mockResolvedValue(null);
+ });
+
+ it("ignores a task whose prompt never asks for an email", async () => {
+ const result = await findMissedReport({
+ run: reportRun,
+ task: { ...reportTask, prompt: "Summarize this week's streams in the chat." },
+ });
+ expect(result).toBeNull();
+ expect(mockSelectEmailSendLog).not.toHaveBeenCalled();
+ });
+
+ it("is not missed when the account sent an email after the run started", async () => {
+ mockSelectEmailSendLog.mockResolvedValue([row("sent", "2026-11-06T10:50:00.000Z")]);
+ expect(await findMissedReport({ run: reportRun, task: reportTask })).toBeNull();
+ expect(mockSelectEmailSendLog).toHaveBeenCalledWith({
+ accountId: "acc-1",
+ createdAfter: reportRun.createdAt,
+ });
+ });
+
+ it("names the plan limit when the plan blocked the run", async () => {
+ mockGetTaskRunBlock.mockResolvedValue({
+ message: "Free includes 1 task. Starter includes 3, Pro is unlimited.",
+ billingUrl: "https://app.recoupable.dev/plan",
+ });
+ expect(await findMissedReport({ run: reportRun, task: reportTask })).toEqual({
+ task: reportTask,
+ run: reportRun,
+ cause: "plan_blocked",
+ detail: "Free includes 1 task. Starter includes 3, Pro is unlimited.",
+ billingUrl: "https://app.recoupable.dev/plan",
+ });
+ });
+
+ it("reports the latest rejection reason when the send was refused", async () => {
+ mockSelectEmailSendLog.mockResolvedValue([
+ row("rejected", "2026-11-06T10:40:00.000Z", "invalid_body: html: empty"),
+ row("rejected", "2026-11-06T10:45:00.000Z", "recipient_not_allowed: a@example.com"),
+ ]);
+ const result = await findMissedReport({ run: reportRun, task: reportTask });
+ expect(result).toMatchObject({
+ cause: "email_rejected",
+ detail: "recipient_not_allowed: a@example.com",
+ });
+ });
+
+ it("falls back to the run status when no send was attempted", async () => {
+ const result = await findMissedReport({
+ run: { ...reportRun, status: "FAILED" },
+ task: reportTask,
+ });
+ expect(result).toMatchObject({ cause: "no_email", detail: "no send attempted; run failed" });
+ });
+});
diff --git a/lib/tasks/missedReports/__tests__/fixtures.ts b/lib/tasks/missedReports/__tests__/fixtures.ts
new file mode 100644
index 000000000..25dfe6acf
--- /dev/null
+++ b/lib/tasks/missedReports/__tests__/fixtures.ts
@@ -0,0 +1,23 @@
+import type { Tables } from "@/types/database.types";
+import type { ScheduledReportRun } from "../types";
+
+export const reportTask: Tables<"scheduled_actions"> = {
+ id: "task-1",
+ account_id: "acc-1",
+ artist_account_id: "artist-1",
+ created_at: "2026-10-01T00:00:00.000Z",
+ enabled: true,
+ model: null,
+ prompt: "Generate a monthly report, then email it to owner@example.com.",
+ schedule: "20 15 6 * *",
+ title: "Monthly Catalog Report: Luh Tyler",
+ trigger_schedule_id: "sched_1",
+ updated_at: null,
+};
+
+export const reportRun: ScheduledReportRun = {
+ runId: "run_1",
+ taskId: "task-1",
+ createdAt: "2026-11-06T10:20:00.000Z",
+ status: "COMPLETED",
+};
diff --git a/lib/tasks/missedReports/__tests__/formatMissedReportsAlert.test.ts b/lib/tasks/missedReports/__tests__/formatMissedReportsAlert.test.ts
new file mode 100644
index 000000000..25fb0561b
--- /dev/null
+++ b/lib/tasks/missedReports/__tests__/formatMissedReportsAlert.test.ts
@@ -0,0 +1,46 @@
+import { describe, it, expect } from "vitest";
+import { formatMissedReportsAlert } from "../formatMissedReportsAlert";
+import { reportRun, reportTask } from "./fixtures";
+
+describe("formatMissedReportsAlert", () => {
+ it("lists each missed report with its cause, account, run and notice state", () => {
+ const text = formatMissedReportsAlert([
+ {
+ task: reportTask,
+ run: reportRun,
+ cause: "email_rejected",
+ detail: "recipient_not_allowed: a@example.com",
+ customerNotified: true,
+ },
+ {
+ task: { ...reportTask, id: "task-2", title: "Daily fan digest", account_id: "acc-2" },
+ run: { ...reportRun, runId: "run_2" },
+ cause: "no_email",
+ detail: "no send attempted; run completed",
+ customerNotified: false,
+ },
+ ]);
+
+ expect(text).toContain("2 scheduled reports did not send");
+ expect(text).toContain(
+ "Monthly Catalog Report: Luh Tyler: email rejected (recipient_not_allowed: a@example.com)",
+ );
+ expect(text).toContain("account acc-1, run run_1, customer emailed");
+ expect(text).toContain("Daily fan digest: no email (no send attempted; run completed)");
+ expect(text).toContain("account acc-2, run run_2, customer not emailed");
+ });
+
+ it("uses the singular for one report", () => {
+ const text = formatMissedReportsAlert([
+ {
+ task: reportTask,
+ run: reportRun,
+ cause: "plan_blocked",
+ detail: "Free includes 1 task.",
+ customerNotified: false,
+ },
+ ]);
+ expect(text).toContain("1 scheduled report did not send");
+ expect(text).toContain("plan blocked (Free includes 1 task.)");
+ });
+});
diff --git a/lib/tasks/missedReports/__tests__/listScheduledReportRuns.test.ts b/lib/tasks/missedReports/__tests__/listScheduledReportRuns.test.ts
new file mode 100644
index 000000000..77ddd439a
--- /dev/null
+++ b/lib/tasks/missedReports/__tests__/listScheduledReportRuns.test.ts
@@ -0,0 +1,82 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+
+const mockFetchTriggerRuns = vi.fn();
+vi.mock("@/lib/trigger/fetchTriggerRuns", () => ({
+ fetchTriggerRuns: (...args: unknown[]) => mockFetchTriggerRuns(...args),
+}));
+
+const mockRetrieveTaskRun = vi.fn();
+vi.mock("@/lib/trigger/retrieveTaskRun", () => ({
+ retrieveTaskRun: (...args: unknown[]) => mockRetrieveTaskRun(...args),
+}));
+
+const { listScheduledReportRuns } = await import("../listScheduledReportRuns");
+
+const window = { from: "2026-11-06T10:00:00.000Z", to: "2026-11-06T11:00:00.000Z" };
+
+describe("listScheduledReportRuns", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ });
+
+ it("lists the scheduled task's runs in the window and resolves each to its task", async () => {
+ mockFetchTriggerRuns.mockResolvedValue([
+ { id: "run_1", status: "COMPLETED", createdAt: "2026-11-06T10:20:00.000Z" },
+ ]);
+ mockRetrieveTaskRun.mockResolvedValue({ schedule: { externalId: "task-1" } });
+
+ const runs = await listScheduledReportRuns(window);
+
+ expect(mockFetchTriggerRuns).toHaveBeenCalledWith(
+ {
+ "filter[taskIdentifier]": "customer-prompt-task",
+ "filter[createdAt][from]": window.from,
+ "filter[createdAt][to]": window.to,
+ },
+ 100,
+ );
+ expect(runs).toEqual([
+ {
+ runId: "run_1",
+ taskId: "task-1",
+ createdAt: "2026-11-06T10:20:00.000Z",
+ status: "COMPLETED",
+ },
+ ]);
+ });
+
+ it("skips runs with no task id and runs that cannot be read", async () => {
+ mockFetchTriggerRuns.mockResolvedValue([
+ { id: "run_manual", status: "COMPLETED", createdAt: "2026-11-06T10:01:00.000Z" },
+ { id: "run_broken", status: "COMPLETED", createdAt: "2026-11-06T10:02:00.000Z" },
+ { id: "run_ok", status: "FAILED", createdAt: "2026-11-06T10:03:00.000Z" },
+ ]);
+ mockRetrieveTaskRun.mockImplementation(async (id: string) => {
+ if (id === "run_manual") return { schedule: undefined };
+ if (id === "run_broken") throw new Error("trigger down");
+ return { schedule: { externalId: "task-2" } };
+ });
+
+ const runs = await listScheduledReportRuns(window);
+
+ expect(runs.map(run => run.runId)).toEqual(["run_ok"]);
+ expect(console.error).toHaveBeenCalled();
+ });
+
+ it("warns when the window may hold more runs than one page", async () => {
+ mockFetchTriggerRuns.mockResolvedValue(
+ Array.from({ length: 100 }, (_, i) => ({
+ id: `run_${i}`,
+ status: "COMPLETED",
+ createdAt: "2026-11-06T10:00:00.000Z",
+ })),
+ );
+ mockRetrieveTaskRun.mockResolvedValue(null);
+
+ await listScheduledReportRuns(window);
+
+ expect(console.warn).toHaveBeenCalled();
+ });
+});
diff --git a/lib/tasks/missedReports/__tests__/sendMissedReportNotice.test.ts b/lib/tasks/missedReports/__tests__/sendMissedReportNotice.test.ts
new file mode 100644
index 000000000..abcf68253
--- /dev/null
+++ b/lib/tasks/missedReports/__tests__/sendMissedReportNotice.test.ts
@@ -0,0 +1,77 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextResponse } from "next/server";
+import { reportRun, reportTask } from "./fixtures";
+import type { MissedReport } from "../types";
+
+const mockSelectAccountEmails = vi.fn();
+vi.mock("@/lib/supabase/account_emails/selectAccountEmails", () => ({
+ default: (...args: unknown[]) => mockSelectAccountEmails(...args),
+}));
+
+const mockSend = vi.fn();
+vi.mock("@/lib/emails/sendEmail", () => ({
+ sendEmailWithResend: (...args: unknown[]) => mockSend(...args),
+}));
+
+const { sendMissedReportNotice } = await import("../sendMissedReportNotice");
+
+const rejected: MissedReport = {
+ task: reportTask,
+ run: reportRun,
+ cause: "email_rejected",
+ detail: "recipient_not_allowed: a@example.com",
+};
+const blocked: MissedReport = {
+ task: { ...reportTask, title: "Daily digest" },
+ run: reportRun,
+ cause: "plan_blocked",
+ detail: "Free runs tasks weekly at most. Starter runs daily, Pro runs hourly.",
+ billingUrl: "https://app.recoupable.dev/plan",
+};
+
+describe("sendMissedReportNotice", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubEnv("MISSED_REPORT_CUSTOMER_NOTICES", "true");
+ mockSelectAccountEmails.mockResolvedValue([{ email: "owner@example.com" }]);
+ mockSend.mockResolvedValue({ id: "re_1" });
+ });
+
+ it("sends nothing while customer notices are switched off", async () => {
+ vi.stubEnv("MISSED_REPORT_CUSTOMER_NOTICES", "");
+ expect(await sendMissedReportNotice(rejected)).toBe(false);
+ expect(mockSend).not.toHaveBeenCalled();
+ });
+
+ it("tells the account owner a report did not arrive", async () => {
+ expect(await sendMissedReportNotice(rejected)).toBe(true);
+ const email = mockSend.mock.calls[0][0];
+ expect(email.to).toBe("owner@example.com");
+ expect(email.subject).toBe("Your report didn't go out: Monthly Catalog Report: Luh Tyler");
+ expect(email.html).toContain("We've been alerted");
+ });
+
+ it("explains a plan block with the upgrade link, escaping the task title", async () => {
+ expect(await sendMissedReportNotice(blocked)).toBe(true);
+ const email = mockSend.mock.calls[0][0];
+ expect(email.subject).toBe("Your task didn't run: Daily digest");
+ expect(email.html).toContain("Daily <fan> digest");
+ expect(email.html).toContain("Free runs tasks weekly at most.");
+ expect(email.html).toContain('href="https://app.recoupable.dev/plan"');
+ });
+
+ it("only emails about other failures for the catalog report tasks", async () => {
+ const custom = { ...rejected, task: { ...reportTask, title: "Daily fan digest" } };
+ expect(await sendMissedReportNotice(custom)).toBe(false);
+ expect(mockSend).not.toHaveBeenCalled();
+ });
+
+ it("returns false when the account has no email or the send fails", async () => {
+ mockSelectAccountEmails.mockResolvedValue([]);
+ expect(await sendMissedReportNotice(rejected)).toBe(false);
+
+ mockSelectAccountEmails.mockResolvedValue([{ email: "owner@example.com" }]);
+ mockSend.mockResolvedValue(NextResponse.json({ error: "x" }, { status: 502 }));
+ expect(await sendMissedReportNotice(rejected)).toBe(false);
+ });
+});
diff --git a/lib/tasks/missedReports/checkMissedReportsHandler.ts b/lib/tasks/missedReports/checkMissedReportsHandler.ts
new file mode 100644
index 000000000..ff6d8931b
--- /dev/null
+++ b/lib/tasks/missedReports/checkMissedReportsHandler.ts
@@ -0,0 +1,67 @@
+import { NextRequest, NextResponse } from "next/server";
+import { validateCronRequest } from "@/lib/internal/validateCronRequest";
+import { selectScheduledActions } from "@/lib/supabase/scheduled_actions/selectScheduledActions";
+import { sendMessage } from "@/lib/telegram/sendMessage";
+import { listScheduledReportRuns } from "./listScheduledReportRuns";
+import { findMissedReport } from "./findMissedReport";
+import { sendMissedReportNotice } from "./sendMissedReportNotice";
+import { formatMissedReportsAlert } from "./formatMissedReportsAlert";
+import type { NotifiedMissedReport } from "./types";
+
+/** Long reports finish well inside this; a run still silent after it has failed. */
+const GRACE_MINUTES = 120;
+/** Matches the hourly cron, so each run falls in exactly one check. */
+const WINDOW_MINUTES = 60;
+
+/**
+ * Handler for `GET /api/internal/missed-report-check` (recoupable/app#1949,
+ * #2022). Cron-only. Finds scheduled runs that started 2-3 hours ago and
+ * asked for an email but sent none — plan-blocked, stalled, rejected or
+ * simply skipped — then emails the owner (see `sendMissedReportNotice`) and
+ * posts one Telegram alert. Stateless: the window does the deduplication.
+ *
+ * @param request - The incoming Next.js request.
+ * @returns A NextResponse with how many runs were checked, missed and notified.
+ */
+export async function checkMissedReportsHandler(request: NextRequest): Promise {
+ const unauthorized = validateCronRequest(request);
+ if (unauthorized) return unauthorized;
+
+ try {
+ const now = Date.now();
+ const runs = await listScheduledReportRuns({
+ from: new Date(now - (GRACE_MINUTES + WINDOW_MINUTES) * 60_000).toISOString(),
+ to: new Date(now - GRACE_MINUTES * 60_000).toISOString(),
+ });
+
+ const misses: NotifiedMissedReport[] = [];
+ for (const run of runs) {
+ const [task] = await selectScheduledActions({ id: run.taskId });
+ if (!task || task.enabled === false) continue;
+
+ const miss = await findMissedReport({ run, task });
+ if (!miss) continue;
+
+ const customerNotified = await sendMissedReportNotice(miss).catch(error => {
+ console.error(`[missed-report-check] notice failed for task ${task.id}:`, error);
+ return false;
+ });
+ misses.push({ ...miss, customerNotified });
+ }
+
+ if (misses.length > 0) await sendMessage(formatMissedReportsAlert(misses));
+
+ return NextResponse.json({
+ status: "ok",
+ checked: runs.length,
+ missed: misses.length,
+ notified: misses.filter(miss => miss.customerNotified).length,
+ });
+ } catch (error) {
+ console.error("[ERROR] checkMissedReportsHandler:", error);
+ return NextResponse.json(
+ { status: "error", message: "Internal server error" },
+ { status: 500 },
+ );
+ }
+}
diff --git a/lib/tasks/missedReports/findMissedReport.ts b/lib/tasks/missedReports/findMissedReport.ts
new file mode 100644
index 000000000..7bb6e5204
--- /dev/null
+++ b/lib/tasks/missedReports/findMissedReport.ts
@@ -0,0 +1,61 @@
+import type { Tables } from "@/types/database.types";
+import { selectEmailSendLog } from "@/lib/supabase/email_send_log/selectEmailSendLog";
+import { getTaskRunBlock } from "@/lib/plans/getTaskRunBlock";
+import type { MissedReport, ScheduledReportRun } from "./types";
+
+/** Only tasks that ask for an email can be checked against email_send_log. */
+const EMAILS = /\bemail/i;
+
+/**
+ * Whether a scheduled run that asked for an email failed to send one, and
+ * why. "Sent" is any successful send from the task's account after the run
+ * started, so two of an account's tasks firing together can mask each other.
+ *
+ * @param input - The run and the task it ran.
+ * @param input.run - The scheduled run.
+ * @param input.task - Its `scheduled_actions` row.
+ * @returns The miss and its cause, or null when nothing is missing.
+ */
+export async function findMissedReport({
+ run,
+ task,
+}: {
+ run: ScheduledReportRun;
+ task: Tables<"scheduled_actions">;
+}): Promise {
+ if (!EMAILS.test(task.prompt)) return null;
+
+ const attempts = await selectEmailSendLog({
+ accountId: task.account_id,
+ createdAfter: run.createdAt,
+ });
+ if (attempts.some(attempt => attempt.status === "sent")) return null;
+
+ const block = await getTaskRunBlock(task);
+ if (block) {
+ return {
+ task,
+ run,
+ cause: "plan_blocked",
+ detail: block.message,
+ billingUrl: block.billingUrl,
+ };
+ }
+
+ const [latestFailure] = attempts.sort((a, b) => b.created_at.localeCompare(a.created_at));
+ if (latestFailure) {
+ return {
+ task,
+ run,
+ cause: "email_rejected",
+ detail: latestFailure.reason ?? latestFailure.status,
+ };
+ }
+
+ return {
+ task,
+ run,
+ cause: "no_email",
+ detail: `no send attempted; run ${run.status.toLowerCase()}`,
+ };
+}
diff --git a/lib/tasks/missedReports/formatMissedReportsAlert.ts b/lib/tasks/missedReports/formatMissedReportsAlert.ts
new file mode 100644
index 000000000..714e88778
--- /dev/null
+++ b/lib/tasks/missedReports/formatMissedReportsAlert.ts
@@ -0,0 +1,24 @@
+import type { MissedReportCause, NotifiedMissedReport } from "./types";
+
+const CAUSE_LABELS: Record = {
+ plan_blocked: "plan blocked",
+ email_rejected: "email rejected",
+ no_email: "no email",
+};
+
+/**
+ * The team's Telegram alert for scheduled reports that did not send: one
+ * line per report with its cause, then the ids needed to look it up.
+ *
+ * @param misses - The missed reports and whether each customer was emailed.
+ * @returns Plain text for `sendMessage`.
+ */
+export function formatMissedReportsAlert(misses: NotifiedMissedReport[]): string {
+ const count = misses.length;
+ const header = `⚠️ ${count} scheduled report${count === 1 ? "" : "s"} did not send (runs started 2-3 hours ago)`;
+ const lines = misses.map(
+ miss =>
+ `• ${miss.task.title}: ${CAUSE_LABELS[miss.cause]} (${miss.detail})\n account ${miss.task.account_id}, run ${miss.run.runId}, customer ${miss.customerNotified ? "emailed" : "not emailed"}`,
+ );
+ return [header, ...lines].join("\n");
+}
diff --git a/lib/tasks/missedReports/listScheduledReportRuns.ts b/lib/tasks/missedReports/listScheduledReportRuns.ts
new file mode 100644
index 000000000..df44d0072
--- /dev/null
+++ b/lib/tasks/missedReports/listScheduledReportRuns.ts
@@ -0,0 +1,53 @@
+import { fetchTriggerRuns } from "@/lib/trigger/fetchTriggerRuns";
+import { retrieveTaskRun } from "@/lib/trigger/retrieveTaskRun";
+import type { ScheduledReportRun } from "./types";
+
+/** The Trigger.dev task every customer schedule runs (tasks repo). */
+const SCHEDULED_TASK_ID = "customer-prompt-task";
+/** One page of the runs API; an hour of schedules fits well inside it. */
+const MAX_RUNS = 100;
+
+/**
+ * Scheduled customer-task runs created inside a window, each resolved to its
+ * `scheduled_actions` id. The list endpoint omits schedule details, so each
+ * run is read once more; a run that cannot be read is skipped and logged.
+ *
+ * @param window - ISO bounds on the runs' `createdAt`.
+ * @param window.from - Inclusive lower bound.
+ * @param window.to - Upper bound.
+ * @returns The runs that belong to a task.
+ */
+export async function listScheduledReportRuns({
+ from,
+ to,
+}: {
+ from: string;
+ to: string;
+}): Promise {
+ const listed = await fetchTriggerRuns(
+ {
+ "filter[taskIdentifier]": SCHEDULED_TASK_ID,
+ "filter[createdAt][from]": from,
+ "filter[createdAt][to]": to,
+ },
+ MAX_RUNS,
+ );
+ if (listed.length === MAX_RUNS) {
+ console.warn(`[missed-report-check] ${MAX_RUNS}+ runs in ${from}..${to}; later ones unchecked`);
+ }
+
+ const resolved = await Promise.all(
+ listed.map(async run => {
+ try {
+ const detail = await retrieveTaskRun(run.id);
+ const taskId = detail?.schedule?.externalId;
+ if (!taskId) return null;
+ return { runId: run.id, taskId, createdAt: run.createdAt, status: run.status };
+ } catch (error) {
+ console.error(`[missed-report-check] could not read run ${run.id}:`, error);
+ return null;
+ }
+ }),
+ );
+ return resolved.filter((run): run is ScheduledReportRun => run !== null);
+}
diff --git a/lib/tasks/missedReports/sendMissedReportNotice.ts b/lib/tasks/missedReports/sendMissedReportNotice.ts
new file mode 100644
index 000000000..276dd88a9
--- /dev/null
+++ b/lib/tasks/missedReports/sendMissedReportNotice.ts
@@ -0,0 +1,46 @@
+import { NextResponse } from "next/server";
+import selectAccountEmails from "@/lib/supabase/account_emails/selectAccountEmails";
+import { sendEmailWithResend } from "@/lib/emails/sendEmail";
+import { escapeHtml } from "@/lib/emails/escapeHtml";
+import { pickAccountRecipient } from "@/lib/emails/pickAccountRecipient";
+import { RECOUP_FROM_EMAIL } from "@/lib/const";
+import type { MissedReport } from "./types";
+
+/**
+ * Onboarding and the homepage card create these; they always email, so a run
+ * without a send is a real failure. Other tasks may email conditionally, so
+ * only a plan block (certain) reaches their owners.
+ */
+const REPORT_TASK_TITLE = /Catalog Report:/;
+
+/**
+ * Tells the account owner that a scheduled report did not arrive: why and
+ * where to upgrade when the plan blocked it, otherwise that the team has been
+ * alerted. Off unless `MISSED_REPORT_CUSTOMER_NOTICES` is "true", so the team
+ * alert can run alone until the volume is known.
+ *
+ * @param miss - The missed report.
+ * @returns Whether a notice was sent.
+ */
+export async function sendMissedReportNotice(miss: MissedReport): Promise {
+ if (process.env.MISSED_REPORT_CUSTOMER_NOTICES !== "true") return false;
+ if (miss.cause !== "plan_blocked" && !REPORT_TASK_TITLE.test(miss.task.title)) return false;
+
+ const to = pickAccountRecipient(await selectAccountEmails({ accountIds: miss.task.account_id }));
+ if (!to) return false;
+
+ const title = escapeHtml(miss.task.title);
+ const { subject, html } =
+ miss.cause === "plan_blocked"
+ ? {
+ subject: `Your task didn't run: ${miss.task.title}`,
+ html: `Your scheduled task “${title}” was due and didn't run, because your plan doesn't cover it. ${escapeHtml(miss.detail)}
Upgrade or change your tasks at ${miss.billingUrl}, and it will run at its next scheduled time.
`,
+ }
+ : {
+ subject: `Your report didn't go out: ${miss.task.title}`,
+ html: `Your scheduled report “${title}” was due and didn't reach your inbox. We've been alerted and are looking into it.
It will run again at its next scheduled time. Questions? Reply to this email.
`,
+ };
+
+ const result = await sendEmailWithResend({ from: RECOUP_FROM_EMAIL, to, subject, html });
+ return !(result instanceof NextResponse);
+}
diff --git a/lib/tasks/missedReports/types.ts b/lib/tasks/missedReports/types.ts
new file mode 100644
index 000000000..236c449e6
--- /dev/null
+++ b/lib/tasks/missedReports/types.ts
@@ -0,0 +1,31 @@
+import type { Tables } from "@/types/database.types";
+
+/** A run of the scheduled `customer-prompt-task`, resolved to the task it ran. */
+export interface ScheduledReportRun {
+ runId: string;
+ /** `scheduled_actions.id`, the schedule's external id. */
+ taskId: string;
+ createdAt: string;
+ /** Trigger.dev run status, e.g. COMPLETED or FAILED. */
+ status: string;
+}
+
+/**
+ * Why a scheduled run sent no email: the plan blocked the task, the send
+ * reached POST /api/emails and was refused, or no send was attempted.
+ */
+export type MissedReportCause = "plan_blocked" | "email_rejected" | "no_email";
+
+export interface MissedReport {
+ task: Tables<"scheduled_actions">;
+ run: ScheduledReportRun;
+ cause: MissedReportCause;
+ /** The plan message, the latest rejection reason, or the run status. */
+ detail: string;
+ /** Where to upgrade, when the plan blocked the task. */
+ billingUrl?: string;
+}
+
+export interface NotifiedMissedReport extends MissedReport {
+ customerNotified: boolean;
+}
diff --git a/lib/trigger/__tests__/fetchTriggerRuns.test.ts b/lib/trigger/__tests__/fetchTriggerRuns.test.ts
new file mode 100644
index 000000000..7d8a6ec8e
--- /dev/null
+++ b/lib/trigger/__tests__/fetchTriggerRuns.test.ts
@@ -0,0 +1,30 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { fetchTriggerRuns } from "../fetchTriggerRuns";
+
+describe("fetchTriggerRuns", () => {
+ beforeEach(() => {
+ vi.stubEnv("TRIGGER_SECRET_KEY", "tr_test");
+ global.fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue({ data: [{ id: "run_1" }] }),
+ }) as unknown as typeof fetch;
+ });
+
+ it("lists one task's runs created inside a time window", async () => {
+ const runs = await fetchTriggerRuns(
+ {
+ "filter[taskIdentifier]": "customer-prompt-task",
+ "filter[createdAt][from]": "2026-11-06T10:00:00.000Z",
+ "filter[createdAt][to]": "2026-11-06T11:00:00.000Z",
+ },
+ 100,
+ );
+
+ expect(runs).toEqual([{ id: "run_1" }]);
+ const url = new URL(vi.mocked(fetch).mock.calls[0][0] as string);
+ expect(url.searchParams.get("filter[taskIdentifier]")).toBe("customer-prompt-task");
+ expect(url.searchParams.get("filter[createdAt][from]")).toBe("2026-11-06T10:00:00.000Z");
+ expect(url.searchParams.get("filter[createdAt][to]")).toBe("2026-11-06T11:00:00.000Z");
+ expect(url.searchParams.get("page[size]")).toBe("100");
+ });
+});
diff --git a/lib/trigger/fetchTriggerRuns.ts b/lib/trigger/fetchTriggerRuns.ts
index 2fd11e6b5..21ea309d7 100644
--- a/lib/trigger/fetchTriggerRuns.ts
+++ b/lib/trigger/fetchTriggerRuns.ts
@@ -8,12 +8,19 @@ export interface TriggerRun {
durationMs: number | null;
}
-export type TriggerRunFilter = { "filter[tag]": string } | { "filter[schedule]": string };
+export type TriggerRunFilter =
+ | { "filter[tag]": string }
+ | { "filter[schedule]": string }
+ | {
+ "filter[taskIdentifier]": string;
+ "filter[createdAt][from]": string;
+ "filter[createdAt][to]": string;
+ };
/**
* Fetches runs from the Trigger.dev Management REST API.
*
- * @param params - Filter params (tag or schedule)
+ * @param params - Filter params (tag, schedule, or one task within a created-at window)
* @param limit - Maximum number of runs to return
* @returns Array of run objects
*/
diff --git a/vercel.json b/vercel.json
index b5721252b..074ffea96 100644
--- a/vercel.json
+++ b/vercel.json
@@ -16,6 +16,10 @@
{
"path": "/api/internal/context-guest-maintenance",
"schedule": "0 8 * * *"
+ },
+ {
+ "path": "/api/internal/missed-report-check",
+ "schedule": "17 * * * *"
}
]
}
From a49a37303e2d061785b173c650dfafb6d63d4776 Mon Sep 17 00:00:00 2001
From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com>
Date: Fri, 6 Nov 2026 23:44:53 -0500
Subject: [PATCH 2/4] Harden the missed-report check from review
- Windows are clock hours (the hour that began three hours ago), so each
run is checked once whatever second the cron fires; customer notices
carry a per-run Resend idempotency key against duplicate deliveries.
- An unreadable email log throws (selectAccountEmailAttempts) instead of
reading as "nothing sent", and one run that cannot be checked is
counted and skipped; the Telegram alert reports it.
- A plan block explains a miss only when the run attempted no send, since
the plan is read at check time.
- Plan-block notices go out at most once per task per 30 days, logged
without an account so they never count as the report being sent.
- The customer notice no longer invites a reply, which would reach the
automated inbox rather than the team.
Co-Authored-By: Claude Opus 5.5
---
lib/const.ts | 3 +
.../selectAccountEmailAttempts.ts | 28 +++++++++
.../checkMissedReportsHandler.test.ts | 49 ++++++++++++---
.../__tests__/findMissedReport.test.ts | 24 +++++++-
.../formatMissedReportsAlert.test.ts | 61 +++++++++++--------
.../__tests__/sendMissedReportNotice.test.ts | 41 +++++++++++++
.../checkMissedReportsHandler.ts | 49 +++++++++------
lib/tasks/missedReports/findMissedReport.ts | 10 +--
.../missedReports/formatMissedReportsAlert.ts | 14 ++++-
.../missedReports/sendMissedReportNotice.ts | 42 +++++++++++--
10 files changed, 257 insertions(+), 64 deletions(-)
create mode 100644 lib/supabase/email_send_log/selectAccountEmailAttempts.ts
diff --git a/lib/const.ts b/lib/const.ts
index 9f2da08b5..899e905fc 100644
--- a/lib/const.ts
+++ b/lib/const.ts
@@ -50,6 +50,9 @@ export const FOUNDER_FROM_EMAIL = `Patrick from Recoup []> {
+ const { data, error } = await supabase
+ .from("email_send_log")
+ .select("*")
+ .eq("account_id", accountId)
+ .gte("created_at", since);
+ if (error) throw new Error(`Failed to read email_send_log: ${error.message}`);
+ return data ?? [];
+}
diff --git a/lib/tasks/missedReports/__tests__/checkMissedReportsHandler.test.ts b/lib/tasks/missedReports/__tests__/checkMissedReportsHandler.test.ts
index 362146166..0fcbb3f74 100644
--- a/lib/tasks/missedReports/__tests__/checkMissedReportsHandler.test.ts
+++ b/lib/tasks/missedReports/__tests__/checkMissedReportsHandler.test.ts
@@ -53,26 +53,44 @@ describe("checkMissedReportsHandler", () => {
expect(mockListRuns).not.toHaveBeenCalled();
});
- // Hourly cron + a one-hour window that ends two hours ago: each run is
- // checked exactly once, after a two-hour grace for long reports.
- it("checks runs that started two to three hours ago", async () => {
+ // Hour-aligned windows ending two hours back: each run lands in one window
+ // whatever second the cron fires, after a two-hour grace for long reports.
+ it("checks the clock hour that started two to three hours ago", async () => {
await checkMissedReportsHandler(request());
expect(mockListRuns).toHaveBeenCalledWith({
- from: "2026-11-06T10:17:00.000Z",
- to: "2026-11-06T11:17:00.000Z",
+ from: "2026-11-06T10:00:00.000Z",
+ to: "2026-11-06T10:59:59.999Z",
+ });
+ vi.setSystemTime(new Date("2026-11-06T13:17:59.000Z"));
+ await checkMissedReportsHandler(request());
+ expect(mockListRuns).toHaveBeenLastCalledWith({
+ from: "2026-11-06T10:00:00.000Z",
+ to: "2026-11-06T10:59:59.999Z",
});
});
it("stays quiet when every report went out", async () => {
const response = await checkMissedReportsHandler(request());
- expect(await response.json()).toEqual({ status: "ok", checked: 1, missed: 0, notified: 0 });
+ expect(await response.json()).toEqual({
+ status: "ok",
+ checked: 1,
+ missed: 0,
+ notified: 0,
+ unchecked: 0,
+ });
expect(mockSendMessage).not.toHaveBeenCalled();
});
it("emails the customer and alerts the team about a missed report", async () => {
mockFindMissed.mockResolvedValue(miss);
const response = await checkMissedReportsHandler(request());
- expect(await response.json()).toEqual({ status: "ok", checked: 1, missed: 1, notified: 1 });
+ expect(await response.json()).toEqual({
+ status: "ok",
+ checked: 1,
+ missed: 1,
+ notified: 1,
+ unchecked: 0,
+ });
expect(mockNotice).toHaveBeenCalledWith(miss);
expect(mockSendMessage).toHaveBeenCalledTimes(1);
expect(mockSendMessage.mock.calls[0][0]).toContain("customer emailed");
@@ -95,6 +113,23 @@ describe("checkMissedReportsHandler", () => {
expect(mockSendMessage.mock.calls[0][0]).toContain("customer not emailed");
});
+ it("keeps checking, and still alerts, when one run cannot be checked", async () => {
+ mockListRuns.mockResolvedValue([
+ { ...reportRun, runId: "run_bad", taskId: "task-bad" },
+ reportRun,
+ ]);
+ mockSelectTasks.mockImplementation(async ({ id }: { id: string }) => {
+ if (id === "task-bad") throw new Error("db down");
+ return [reportTask];
+ });
+ mockFindMissed.mockResolvedValue(miss);
+
+ const response = await checkMissedReportsHandler(request());
+
+ expect(await response.json()).toMatchObject({ missed: 1, unchecked: 1 });
+ expect(mockSendMessage.mock.calls[0][0]).toContain("1 scheduled run could not be checked");
+ });
+
it("returns 500 when the run list cannot be read", async () => {
mockListRuns.mockRejectedValue(new Error("trigger down"));
const response = await checkMissedReportsHandler(request());
diff --git a/lib/tasks/missedReports/__tests__/findMissedReport.test.ts b/lib/tasks/missedReports/__tests__/findMissedReport.test.ts
index f30d6513c..93562c738 100644
--- a/lib/tasks/missedReports/__tests__/findMissedReport.test.ts
+++ b/lib/tasks/missedReports/__tests__/findMissedReport.test.ts
@@ -2,8 +2,8 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
import { reportRun, reportTask } from "./fixtures";
const mockSelectEmailSendLog = vi.fn();
-vi.mock("@/lib/supabase/email_send_log/selectEmailSendLog", () => ({
- selectEmailSendLog: (...args: unknown[]) => mockSelectEmailSendLog(...args),
+vi.mock("@/lib/supabase/email_send_log/selectAccountEmailAttempts", () => ({
+ selectAccountEmailAttempts: (...args: unknown[]) => mockSelectEmailSendLog(...args),
}));
const mockGetTaskRunBlock = vi.fn();
@@ -45,7 +45,7 @@ describe("findMissedReport", () => {
expect(await findMissedReport({ run: reportRun, task: reportTask })).toBeNull();
expect(mockSelectEmailSendLog).toHaveBeenCalledWith({
accountId: "acc-1",
- createdAfter: reportRun.createdAt,
+ since: reportRun.createdAt,
});
});
@@ -75,6 +75,24 @@ describe("findMissedReport", () => {
});
});
+ // The block is read at check time; a send attempt proves the run went ahead.
+ it("reports the rejection, not the plan, when the run attempted a send", async () => {
+ mockGetTaskRunBlock.mockResolvedValue({ message: "Free includes 1 task.", billingUrl: "x" });
+ mockSelectEmailSendLog.mockResolvedValue([
+ row("rejected", "2026-11-06T10:40:00.000Z", "invalid_body: html: empty"),
+ ]);
+ const result = await findMissedReport({ run: reportRun, task: reportTask });
+ expect(result).toMatchObject({ cause: "email_rejected" });
+ expect(mockGetTaskRunBlock).not.toHaveBeenCalled();
+ });
+
+ // An unreadable log is unknown, not "nothing sent": never tell a customer
+ // their report failed because of our own read error.
+ it("throws when the email log cannot be read", async () => {
+ mockSelectEmailSendLog.mockRejectedValue(new Error("db down"));
+ await expect(findMissedReport({ run: reportRun, task: reportTask })).rejects.toThrow("db down");
+ });
+
it("falls back to the run status when no send was attempted", async () => {
const result = await findMissedReport({
run: { ...reportRun, status: "FAILED" },
diff --git a/lib/tasks/missedReports/__tests__/formatMissedReportsAlert.test.ts b/lib/tasks/missedReports/__tests__/formatMissedReportsAlert.test.ts
index 25fb0561b..e5c8c94a0 100644
--- a/lib/tasks/missedReports/__tests__/formatMissedReportsAlert.test.ts
+++ b/lib/tasks/missedReports/__tests__/formatMissedReportsAlert.test.ts
@@ -4,22 +4,25 @@ import { reportRun, reportTask } from "./fixtures";
describe("formatMissedReportsAlert", () => {
it("lists each missed report with its cause, account, run and notice state", () => {
- const text = formatMissedReportsAlert([
- {
- task: reportTask,
- run: reportRun,
- cause: "email_rejected",
- detail: "recipient_not_allowed: a@example.com",
- customerNotified: true,
- },
- {
- task: { ...reportTask, id: "task-2", title: "Daily fan digest", account_id: "acc-2" },
- run: { ...reportRun, runId: "run_2" },
- cause: "no_email",
- detail: "no send attempted; run completed",
- customerNotified: false,
- },
- ]);
+ const text = formatMissedReportsAlert(
+ [
+ {
+ task: reportTask,
+ run: reportRun,
+ cause: "email_rejected",
+ detail: "recipient_not_allowed: a@example.com",
+ customerNotified: true,
+ },
+ {
+ task: { ...reportTask, id: "task-2", title: "Daily fan digest", account_id: "acc-2" },
+ run: { ...reportRun, runId: "run_2" },
+ cause: "no_email",
+ detail: "no send attempted; run completed",
+ customerNotified: false,
+ },
+ ],
+ 0,
+ );
expect(text).toContain("2 scheduled reports did not send");
expect(text).toContain(
@@ -31,16 +34,24 @@ describe("formatMissedReportsAlert", () => {
});
it("uses the singular for one report", () => {
- const text = formatMissedReportsAlert([
- {
- task: reportTask,
- run: reportRun,
- cause: "plan_blocked",
- detail: "Free includes 1 task.",
- customerNotified: false,
- },
- ]);
+ const text = formatMissedReportsAlert(
+ [
+ {
+ task: reportTask,
+ run: reportRun,
+ cause: "plan_blocked",
+ detail: "Free includes 1 task.",
+ customerNotified: false,
+ },
+ ],
+ 0,
+ );
expect(text).toContain("1 scheduled report did not send");
expect(text).toContain("plan blocked (Free includes 1 task.)");
});
+
+ it("says how many runs could not be checked", () => {
+ expect(formatMissedReportsAlert([], 2)).toContain("2 scheduled runs could not be checked");
+ expect(formatMissedReportsAlert([], 1)).toContain("1 scheduled run could not be checked");
+ });
});
diff --git a/lib/tasks/missedReports/__tests__/sendMissedReportNotice.test.ts b/lib/tasks/missedReports/__tests__/sendMissedReportNotice.test.ts
index abcf68253..7077a812f 100644
--- a/lib/tasks/missedReports/__tests__/sendMissedReportNotice.test.ts
+++ b/lib/tasks/missedReports/__tests__/sendMissedReportNotice.test.ts
@@ -13,6 +13,16 @@ vi.mock("@/lib/emails/sendEmail", () => ({
sendEmailWithResend: (...args: unknown[]) => mockSend(...args),
}));
+const mockSelectEmailSendLog = vi.fn();
+vi.mock("@/lib/supabase/email_send_log/selectEmailSendLog", () => ({
+ selectEmailSendLog: (...args: unknown[]) => mockSelectEmailSendLog(...args),
+}));
+
+const mockLogEmailAttempt = vi.fn();
+vi.mock("@/lib/emails/logEmailAttempt", () => ({
+ logEmailAttempt: (...args: unknown[]) => mockLogEmailAttempt(...args),
+}));
+
const { sendMissedReportNotice } = await import("../sendMissedReportNotice");
const rejected: MissedReport = {
@@ -35,6 +45,7 @@ describe("sendMissedReportNotice", () => {
vi.stubEnv("MISSED_REPORT_CUSTOMER_NOTICES", "true");
mockSelectAccountEmails.mockResolvedValue([{ email: "owner@example.com" }]);
mockSend.mockResolvedValue({ id: "re_1" });
+ mockSelectEmailSendLog.mockResolvedValue([]);
});
it("sends nothing while customer notices are switched off", async () => {
@@ -49,6 +60,36 @@ describe("sendMissedReportNotice", () => {
expect(email.to).toBe("owner@example.com");
expect(email.subject).toBe("Your report didn't go out: Monthly Catalog Report: Luh Tyler");
expect(email.html).toContain("We've been alerted");
+ expect(email.html).not.toMatch(/reply/i);
+ // A duplicate cron delivery for the same run must not email twice.
+ expect(mockSend.mock.calls[0][1]).toEqual({ idempotencyKey: "missed-report/run_1" });
+ });
+
+ // A blocked task fires on every scheduled run; tell the owner once a month,
+ // not every hour. The notice log row carries no account_id, so it never
+ // counts as the account's report being sent.
+ it("sends a plan-block notice once per task per 30 days and logs it without an account", async () => {
+ expect(await sendMissedReportNotice(blocked)).toBe(true);
+ expect(mockSelectEmailSendLog).toHaveBeenCalledWith(
+ expect.objectContaining({
+ rawBodyLike: "missed_report_notice:task-1:plan_blocked",
+ limit: 1,
+ }),
+ );
+ expect(mockLogEmailAttempt).toHaveBeenCalledWith({
+ rawBody: JSON.stringify({
+ type: "missed_report_notice:task-1:plan_blocked",
+ account_id: "acc-1",
+ run_id: "run_1",
+ }),
+ status: "sent",
+ resendId: "re_1",
+ });
+
+ vi.clearAllMocks();
+ mockSelectEmailSendLog.mockResolvedValue([{ id: "earlier-notice" }]);
+ expect(await sendMissedReportNotice(blocked)).toBe(false);
+ expect(mockSend).not.toHaveBeenCalled();
});
it("explains a plan block with the upgrade link, escaping the task title", async () => {
diff --git a/lib/tasks/missedReports/checkMissedReportsHandler.ts b/lib/tasks/missedReports/checkMissedReportsHandler.ts
index ff6d8931b..d483ab06d 100644
--- a/lib/tasks/missedReports/checkMissedReportsHandler.ts
+++ b/lib/tasks/missedReports/checkMissedReportsHandler.ts
@@ -8,17 +8,20 @@ import { sendMissedReportNotice } from "./sendMissedReportNotice";
import { formatMissedReportsAlert } from "./formatMissedReportsAlert";
import type { NotifiedMissedReport } from "./types";
-/** Long reports finish well inside this; a run still silent after it has failed. */
-const GRACE_MINUTES = 120;
-/** Matches the hourly cron, so each run falls in exactly one check. */
-const WINDOW_MINUTES = 60;
+const HOUR_MS = 60 * 60_000;
+/** Long reports finish well inside two hours; checking the hour that began three hours ago leaves at least that. */
+const HOURS_BACK = 3;
/**
* Handler for `GET /api/internal/missed-report-check` (recoupable/app#1949,
* #2022). Cron-only. Finds scheduled runs that started 2-3 hours ago and
* asked for an email but sent none — plan-blocked, stalled, rejected or
* simply skipped — then emails the owner (see `sendMissedReportNotice`) and
- * posts one Telegram alert. Stateless: the window does the deduplication.
+ * posts one Telegram alert. The window is the clock hour that started three
+ * hours ago, so each run lands in exactly one window whatever second the cron
+ * fires; a duplicated cron delivery re-alerts the team, but the customer
+ * notice carries a per-run idempotency key. One run that cannot be checked
+ * is counted and skipped rather than ending the batch.
*
* @param request - The incoming Next.js request.
* @returns A NextResponse with how many runs were checked, missed and notified.
@@ -28,34 +31,44 @@ export async function checkMissedReportsHandler(request: NextRequest): Promise {
- console.error(`[missed-report-check] notice failed for task ${task.id}:`, error);
- return false;
- });
- misses.push({ ...miss, customerNotified });
+ const customerNotified = await sendMissedReportNotice(miss).catch(error => {
+ console.error(`[missed-report-check] notice failed for task ${task.id}:`, error);
+ return false;
+ });
+ misses.push({ ...miss, customerNotified });
+ } catch (error) {
+ unchecked += 1;
+ console.error(`[missed-report-check] could not check run ${run.runId}:`, error);
+ }
}
- if (misses.length > 0) await sendMessage(formatMissedReportsAlert(misses));
+ if (misses.length > 0 || unchecked > 0) {
+ await sendMessage(formatMissedReportsAlert(misses, unchecked));
+ }
return NextResponse.json({
status: "ok",
checked: runs.length,
missed: misses.length,
notified: misses.filter(miss => miss.customerNotified).length,
+ unchecked,
});
} catch (error) {
console.error("[ERROR] checkMissedReportsHandler:", error);
diff --git a/lib/tasks/missedReports/findMissedReport.ts b/lib/tasks/missedReports/findMissedReport.ts
index 7bb6e5204..bfd7ea454 100644
--- a/lib/tasks/missedReports/findMissedReport.ts
+++ b/lib/tasks/missedReports/findMissedReport.ts
@@ -1,5 +1,5 @@
import type { Tables } from "@/types/database.types";
-import { selectEmailSendLog } from "@/lib/supabase/email_send_log/selectEmailSendLog";
+import { selectAccountEmailAttempts } from "@/lib/supabase/email_send_log/selectAccountEmailAttempts";
import { getTaskRunBlock } from "@/lib/plans/getTaskRunBlock";
import type { MissedReport, ScheduledReportRun } from "./types";
@@ -10,6 +10,8 @@ const EMAILS = /\bemail/i;
* Whether a scheduled run that asked for an email failed to send one, and
* why. "Sent" is any successful send from the task's account after the run
* started, so two of an account's tasks firing together can mask each other.
+ * The plan is read now, not at run time, so it only explains a run that
+ * attempted no send. Throws when the email log cannot be read.
*
* @param input - The run and the task it ran.
* @param input.run - The scheduled run.
@@ -25,13 +27,13 @@ export async function findMissedReport({
}): Promise {
if (!EMAILS.test(task.prompt)) return null;
- const attempts = await selectEmailSendLog({
+ const attempts = await selectAccountEmailAttempts({
accountId: task.account_id,
- createdAfter: run.createdAt,
+ since: run.createdAt,
});
if (attempts.some(attempt => attempt.status === "sent")) return null;
- const block = await getTaskRunBlock(task);
+ const block = attempts.length === 0 ? await getTaskRunBlock(task) : null;
if (block) {
return {
task,
diff --git a/lib/tasks/missedReports/formatMissedReportsAlert.ts b/lib/tasks/missedReports/formatMissedReportsAlert.ts
index 714e88778..2367deef9 100644
--- a/lib/tasks/missedReports/formatMissedReportsAlert.ts
+++ b/lib/tasks/missedReports/formatMissedReportsAlert.ts
@@ -11,14 +11,24 @@ const CAUSE_LABELS: Record = {
* line per report with its cause, then the ids needed to look it up.
*
* @param misses - The missed reports and whether each customer was emailed.
+ * @param unchecked - Runs that could not be checked (a read failed).
* @returns Plain text for `sendMessage`.
*/
-export function formatMissedReportsAlert(misses: NotifiedMissedReport[]): string {
+export function formatMissedReportsAlert(
+ misses: NotifiedMissedReport[],
+ unchecked: number,
+): string {
const count = misses.length;
const header = `⚠️ ${count} scheduled report${count === 1 ? "" : "s"} did not send (runs started 2-3 hours ago)`;
+ const uncheckedLine =
+ unchecked > 0
+ ? [
+ `${unchecked} scheduled run${unchecked === 1 ? "" : "s"} could not be checked; see the api logs.`,
+ ]
+ : [];
const lines = misses.map(
miss =>
`• ${miss.task.title}: ${CAUSE_LABELS[miss.cause]} (${miss.detail})\n account ${miss.task.account_id}, run ${miss.run.runId}, customer ${miss.customerNotified ? "emailed" : "not emailed"}`,
);
- return [header, ...lines].join("\n");
+ return [header, ...lines, ...uncheckedLine].join("\n");
}
diff --git a/lib/tasks/missedReports/sendMissedReportNotice.ts b/lib/tasks/missedReports/sendMissedReportNotice.ts
index 276dd88a9..b4c0dcf75 100644
--- a/lib/tasks/missedReports/sendMissedReportNotice.ts
+++ b/lib/tasks/missedReports/sendMissedReportNotice.ts
@@ -3,7 +3,9 @@ import selectAccountEmails from "@/lib/supabase/account_emails/selectAccountEmai
import { sendEmailWithResend } from "@/lib/emails/sendEmail";
import { escapeHtml } from "@/lib/emails/escapeHtml";
import { pickAccountRecipient } from "@/lib/emails/pickAccountRecipient";
-import { RECOUP_FROM_EMAIL } from "@/lib/const";
+import { logEmailAttempt } from "@/lib/emails/logEmailAttempt";
+import { selectEmailSendLog } from "@/lib/supabase/email_send_log/selectEmailSendLog";
+import { MISSED_REPORT_NOTICE_LOG_TYPE, RECOUP_FROM_EMAIL } from "@/lib/const";
import type { MissedReport } from "./types";
/**
@@ -12,12 +14,16 @@ import type { MissedReport } from "./types";
* only a plan block (certain) reaches their owners.
*/
const REPORT_TASK_TITLE = /Catalog Report:/;
+/** A blocked task fires on every scheduled run; remind its owner at most this often. */
+const PLAN_NOTICE_INTERVAL_MS = 30 * 24 * 60 * 60_000;
/**
* Tells the account owner that a scheduled report did not arrive: why and
* where to upgrade when the plan blocked it, otherwise that the team has been
* alerted. Off unless `MISSED_REPORT_CUSTOMER_NOTICES` is "true", so the team
- * alert can run alone until the volume is known.
+ * alert can run alone until the volume is known. Each run's notice carries an
+ * idempotency key; plan-block notices are logged (without an account, so they
+ * never count as the report being sent) and repeat at most monthly per task.
*
* @param miss - The missed report.
* @returns Whether a notice was sent.
@@ -26,6 +32,16 @@ export async function sendMissedReportNotice(miss: MissedReport): Promise 0) return false;
+ }
+
const to = pickAccountRecipient(await selectAccountEmails({ accountIds: miss.task.account_id }));
if (!to) return false;
@@ -38,9 +54,25 @@ export async function sendMissedReportNotice(miss: MissedReport): PromiseYour scheduled report “${title}” was due and didn't reach your inbox. We've been alerted and are looking into it.
It will run again at its next scheduled time. Questions? Reply to this email.
`,
+ html: `Your scheduled report “${title}” was due and didn't reach your inbox. We've been alerted and are looking into it.
It will run again at its next scheduled time.
`,
};
- const result = await sendEmailWithResend({ from: RECOUP_FROM_EMAIL, to, subject, html });
- return !(result instanceof NextResponse);
+ const result = await sendEmailWithResend(
+ { from: RECOUP_FROM_EMAIL, to, subject, html },
+ { idempotencyKey: `missed-report/${miss.run.runId}` },
+ );
+ if (result instanceof NextResponse) return false;
+
+ if (miss.cause === "plan_blocked") {
+ await logEmailAttempt({
+ rawBody: JSON.stringify({
+ type: noticeType,
+ account_id: miss.task.account_id,
+ run_id: miss.run.runId,
+ }),
+ status: "sent",
+ resendId: result.id,
+ });
+ }
+ return true;
}
From ed4f762a7e7f783e1792276432ac218ec51c76c9 Mon Sep 17 00:00:00 2001
From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com>
Date: Sat, 7 Nov 2026 03:11:51 -0500
Subject: [PATCH 3/4] Keep the missed-report alert complete and readable
From cubic's review:
- Each Trigger.dev run read gets a 5-second budget; a hung or failed read
is counted as unchecked instead of stalling the whole check.
- The alert lists at most 20 reports (Telegram cuts at 4,000 characters),
says when the hour held more than 100 runs, and has its own heading
when it only reports unchecked runs.
- The customer notice strips control characters from the task title
before using it in the subject.
- A rejection reason names at most five disallowed recipients.
- Tests: env stubs are restored, the notice's account lookup and the 500
body are asserted, and a stalled EXECUTING run is covered.
Co-Authored-By: Claude Opus 5.5
---
.../__tests__/validateSendEmailBody.test.ts | 11 ++++++
lib/emails/validateSendEmailBody.ts | 6 ++-
.../checkMissedReportsHandler.test.ts | 22 +++++++----
.../__tests__/findMissedReport.test.ts | 8 ++++
.../formatMissedReportsAlert.test.ts | 36 ++++++++++++++++--
.../__tests__/listScheduledReportRuns.test.ts | 30 +++++++++++++--
.../__tests__/sendMissedReportNotice.test.ts | 14 ++++++-
.../checkMissedReportsHandler.ts | 8 ++--
.../missedReports/formatMissedReportsAlert.ts | 38 +++++++++++++------
.../missedReports/listScheduledReportRuns.ts | 35 ++++++++++++++---
.../missedReports/sendMissedReportNotice.ts | 6 ++-
11 files changed, 173 insertions(+), 41 deletions(-)
diff --git a/lib/emails/__tests__/validateSendEmailBody.test.ts b/lib/emails/__tests__/validateSendEmailBody.test.ts
index 05a428459..cebeb86cf 100644
--- a/lib/emails/__tests__/validateSendEmailBody.test.ts
+++ b/lib/emails/__tests__/validateSendEmailBody.test.ts
@@ -259,6 +259,17 @@ describe("validateSendEmailBody", () => {
});
});
+ it("caps the recipients named in the reason", async () => {
+ const disallowed = Array.from({ length: 8 }, (_, i) => `r${i}@example.com`);
+ mockAssertRecipientsAllowed.mockResolvedValue({ allowed: false, disallowed });
+ const request = createRequest({ to: disallowed, text: "body" }, { "x-api-key": "k" });
+ const result = await validateSendEmailBody(request);
+ expect(result).toMatchObject({
+ reason:
+ "recipient_not_allowed: r0@example.com, r1@example.com, r2@example.com, r3@example.com, r4@example.com and 3 more",
+ });
+ });
+
it("names the failing field when the body is invalid", async () => {
const request = createRequest({ to: ["d@example.com"], html: " " }, { "x-api-key": "k" });
const result = await validateSendEmailBody(request);
diff --git a/lib/emails/validateSendEmailBody.ts b/lib/emails/validateSendEmailBody.ts
index bcec16611..b65b4b171 100644
--- a/lib/emails/validateSendEmailBody.ts
+++ b/lib/emails/validateSendEmailBody.ts
@@ -122,7 +122,11 @@ export async function validateSendEmailBody(
},
{ status: 403, headers: getCorsHeaders() },
),
- reason: `recipient_not_allowed: ${recipientCheck.disallowed.join(", ")}`,
+ reason: `recipient_not_allowed: ${recipientCheck.disallowed.slice(0, 5).join(", ")}${
+ recipientCheck.disallowed.length > 5
+ ? ` and ${recipientCheck.disallowed.length - 5} more`
+ : ""
+ }`,
accountId: authContext.accountId,
};
}
diff --git a/lib/tasks/missedReports/__tests__/checkMissedReportsHandler.test.ts b/lib/tasks/missedReports/__tests__/checkMissedReportsHandler.test.ts
index 0fcbb3f74..fc4955f30 100644
--- a/lib/tasks/missedReports/__tests__/checkMissedReportsHandler.test.ts
+++ b/lib/tasks/missedReports/__tests__/checkMissedReportsHandler.test.ts
@@ -39,7 +39,7 @@ describe("checkMissedReportsHandler", () => {
vi.setSystemTime(new Date("2026-11-06T13:17:00.000Z"));
vi.spyOn(console, "error").mockImplementation(() => {});
mockValidate.mockReturnValue(null);
- mockListRuns.mockResolvedValue([reportRun]);
+ mockListRuns.mockResolvedValue({ runs: [reportRun], unreadable: 0, truncated: false });
mockSelectTasks.mockResolvedValue([reportTask]);
mockFindMissed.mockResolvedValue(null);
mockNotice.mockResolvedValue(true);
@@ -97,7 +97,11 @@ describe("checkMissedReportsHandler", () => {
});
it("skips runs whose task was deleted or turned off", async () => {
- mockListRuns.mockResolvedValue([reportRun, { ...reportRun, runId: "run_2", taskId: "gone" }]);
+ mockListRuns.mockResolvedValue({
+ runs: [reportRun, { ...reportRun, runId: "run_2", taskId: "gone" }],
+ unreadable: 0,
+ truncated: false,
+ });
mockSelectTasks.mockImplementation(async ({ id }: { id: string }) =>
id === "gone" ? [] : [{ ...reportTask, enabled: false }],
);
@@ -114,10 +118,11 @@ describe("checkMissedReportsHandler", () => {
});
it("keeps checking, and still alerts, when one run cannot be checked", async () => {
- mockListRuns.mockResolvedValue([
- { ...reportRun, runId: "run_bad", taskId: "task-bad" },
- reportRun,
- ]);
+ mockListRuns.mockResolvedValue({
+ runs: [{ ...reportRun, runId: "run_bad", taskId: "task-bad" }, reportRun],
+ unreadable: 1,
+ truncated: false,
+ });
mockSelectTasks.mockImplementation(async ({ id }: { id: string }) => {
if (id === "task-bad") throw new Error("db down");
return [reportTask];
@@ -126,13 +131,14 @@ describe("checkMissedReportsHandler", () => {
const response = await checkMissedReportsHandler(request());
- expect(await response.json()).toMatchObject({ missed: 1, unchecked: 1 });
- expect(mockSendMessage.mock.calls[0][0]).toContain("1 scheduled run could not be checked");
+ expect(await response.json()).toMatchObject({ missed: 1, unchecked: 2 });
+ expect(mockSendMessage.mock.calls[0][0]).toContain("2 scheduled runs could not be checked");
});
it("returns 500 when the run list cannot be read", async () => {
mockListRuns.mockRejectedValue(new Error("trigger down"));
const response = await checkMissedReportsHandler(request());
expect(response.status).toBe(500);
+ expect(await response.json()).toEqual({ status: "error", message: "Internal server error" });
});
});
diff --git a/lib/tasks/missedReports/__tests__/findMissedReport.test.ts b/lib/tasks/missedReports/__tests__/findMissedReport.test.ts
index 93562c738..68de2c2ba 100644
--- a/lib/tasks/missedReports/__tests__/findMissedReport.test.ts
+++ b/lib/tasks/missedReports/__tests__/findMissedReport.test.ts
@@ -93,6 +93,14 @@ describe("findMissedReport", () => {
await expect(findMissedReport({ run: reportRun, task: reportTask })).rejects.toThrow("db down");
});
+ it("names a stalled run that is still executing", async () => {
+ const result = await findMissedReport({
+ run: { ...reportRun, status: "EXECUTING" },
+ task: reportTask,
+ });
+ expect(result).toMatchObject({ cause: "no_email", detail: "no send attempted; run executing" });
+ });
+
it("falls back to the run status when no send was attempted", async () => {
const result = await findMissedReport({
run: { ...reportRun, status: "FAILED" },
diff --git a/lib/tasks/missedReports/__tests__/formatMissedReportsAlert.test.ts b/lib/tasks/missedReports/__tests__/formatMissedReportsAlert.test.ts
index e5c8c94a0..c274046a0 100644
--- a/lib/tasks/missedReports/__tests__/formatMissedReportsAlert.test.ts
+++ b/lib/tasks/missedReports/__tests__/formatMissedReportsAlert.test.ts
@@ -21,7 +21,7 @@ describe("formatMissedReportsAlert", () => {
customerNotified: false,
},
],
- 0,
+ { unchecked: 0, truncated: false },
);
expect(text).toContain("2 scheduled reports did not send");
@@ -44,14 +44,42 @@ describe("formatMissedReportsAlert", () => {
customerNotified: false,
},
],
- 0,
+ { unchecked: 0, truncated: false },
);
expect(text).toContain("1 scheduled report did not send");
expect(text).toContain("plan blocked (Free includes 1 task.)");
});
it("says how many runs could not be checked", () => {
- expect(formatMissedReportsAlert([], 2)).toContain("2 scheduled runs could not be checked");
- expect(formatMissedReportsAlert([], 1)).toContain("1 scheduled run could not be checked");
+ const text = formatMissedReportsAlert([], { unchecked: 2, truncated: false });
+ expect(text).toContain("2 scheduled runs could not be checked");
+ expect(text).not.toContain("0 scheduled reports did not send");
+ expect(formatMissedReportsAlert([], { unchecked: 1, truncated: false })).toContain(
+ "1 scheduled run could not be checked",
+ );
+ });
+
+ // Telegram cuts messages at 4,000 characters; keep every alert readable.
+ it("lists at most 20 reports and counts the rest", () => {
+ const miss = {
+ task: reportTask,
+ run: reportRun,
+ cause: "no_email" as const,
+ detail: "no send attempted; run completed",
+ customerNotified: false,
+ };
+ const text = formatMissedReportsAlert(Array(25).fill(miss), {
+ unchecked: 0,
+ truncated: false,
+ });
+ expect(text.match(/^• /gm)).toHaveLength(20);
+ expect(text).toContain("…and 5 more");
+ expect(text.length).toBeLessThan(4000);
+ });
+
+ it("says when the hour held more runs than one page", () => {
+ expect(formatMissedReportsAlert([], { unchecked: 0, truncated: true })).toContain(
+ "More than 100 runs started in that hour",
+ );
});
});
diff --git a/lib/tasks/missedReports/__tests__/listScheduledReportRuns.test.ts b/lib/tasks/missedReports/__tests__/listScheduledReportRuns.test.ts
index 77ddd439a..7e473827f 100644
--- a/lib/tasks/missedReports/__tests__/listScheduledReportRuns.test.ts
+++ b/lib/tasks/missedReports/__tests__/listScheduledReportRuns.test.ts
@@ -27,7 +27,7 @@ describe("listScheduledReportRuns", () => {
]);
mockRetrieveTaskRun.mockResolvedValue({ schedule: { externalId: "task-1" } });
- const runs = await listScheduledReportRuns(window);
+ const { runs } = await listScheduledReportRuns(window);
expect(mockFetchTriggerRuns).toHaveBeenCalledWith(
{
@@ -59,9 +59,10 @@ describe("listScheduledReportRuns", () => {
return { schedule: { externalId: "task-2" } };
});
- const runs = await listScheduledReportRuns(window);
+ const { runs, unreadable } = await listScheduledReportRuns(window);
expect(runs.map(run => run.runId)).toEqual(["run_ok"]);
+ expect(unreadable).toBe(1);
expect(console.error).toHaveBeenCalled();
});
@@ -75,8 +76,31 @@ describe("listScheduledReportRuns", () => {
);
mockRetrieveTaskRun.mockResolvedValue(null);
- await listScheduledReportRuns(window);
+ const { truncated } = await listScheduledReportRuns(window);
+ expect(truncated).toBe(true);
expect(console.warn).toHaveBeenCalled();
});
+
+ // One hung Trigger.dev read must not stall the whole check.
+ it("gives up on a run read that does not answer in time", async () => {
+ vi.useFakeTimers();
+ mockFetchTriggerRuns.mockResolvedValue([
+ { id: "run_hung", status: "COMPLETED", createdAt: "2026-11-06T10:01:00.000Z" },
+ { id: "run_ok", status: "COMPLETED", createdAt: "2026-11-06T10:02:00.000Z" },
+ ]);
+ mockRetrieveTaskRun.mockImplementation((id: string) =>
+ id === "run_hung"
+ ? new Promise(() => {})
+ : Promise.resolve({ schedule: { externalId: "task-1" } }),
+ );
+
+ const pending = listScheduledReportRuns(window);
+ await vi.advanceTimersByTimeAsync(5_000);
+ const { runs, unreadable } = await pending;
+
+ expect(runs.map(run => run.runId)).toEqual(["run_ok"]);
+ expect(unreadable).toBe(1);
+ vi.useRealTimers();
+ });
});
diff --git a/lib/tasks/missedReports/__tests__/sendMissedReportNotice.test.ts b/lib/tasks/missedReports/__tests__/sendMissedReportNotice.test.ts
index 7077a812f..c1690940b 100644
--- a/lib/tasks/missedReports/__tests__/sendMissedReportNotice.test.ts
+++ b/lib/tasks/missedReports/__tests__/sendMissedReportNotice.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { NextResponse } from "next/server";
import { reportRun, reportTask } from "./fixtures";
import type { MissedReport } from "../types";
@@ -47,6 +47,7 @@ describe("sendMissedReportNotice", () => {
mockSend.mockResolvedValue({ id: "re_1" });
mockSelectEmailSendLog.mockResolvedValue([]);
});
+ afterEach(() => vi.unstubAllEnvs());
it("sends nothing while customer notices are switched off", async () => {
vi.stubEnv("MISSED_REPORT_CUSTOMER_NOTICES", "");
@@ -56,6 +57,7 @@ describe("sendMissedReportNotice", () => {
it("tells the account owner a report did not arrive", async () => {
expect(await sendMissedReportNotice(rejected)).toBe(true);
+ expect(mockSelectAccountEmails).toHaveBeenCalledWith({ accountIds: "acc-1" });
const email = mockSend.mock.calls[0][0];
expect(email.to).toBe("owner@example.com");
expect(email.subject).toBe("Your report didn't go out: Monthly Catalog Report: Luh Tyler");
@@ -115,4 +117,14 @@ describe("sendMissedReportNotice", () => {
mockSend.mockResolvedValue(NextResponse.json({ error: "x" }, { status: 502 }));
expect(await sendMissedReportNotice(rejected)).toBe(false);
});
+
+ it("keeps line breaks in a task title out of the subject", async () => {
+ await sendMissedReportNotice({
+ ...rejected,
+ task: { ...reportTask, title: "Monthly Catalog Report: A\r\nBcc: x@example.com" },
+ });
+ expect(mockSend.mock.calls[0][0].subject).toBe(
+ "Your report didn't go out: Monthly Catalog Report: A Bcc: x@example.com",
+ );
+ });
});
diff --git a/lib/tasks/missedReports/checkMissedReportsHandler.ts b/lib/tasks/missedReports/checkMissedReportsHandler.ts
index d483ab06d..8ddf5e741 100644
--- a/lib/tasks/missedReports/checkMissedReportsHandler.ts
+++ b/lib/tasks/missedReports/checkMissedReportsHandler.ts
@@ -33,13 +33,13 @@ export async function checkMissedReportsHandler(request: NextRequest): Promise 0 || unchecked > 0) {
- await sendMessage(formatMissedReportsAlert(misses, unchecked));
+ if (misses.length > 0 || unchecked > 0 || truncated) {
+ await sendMessage(formatMissedReportsAlert(misses, { unchecked, truncated }));
}
return NextResponse.json({
diff --git a/lib/tasks/missedReports/formatMissedReportsAlert.ts b/lib/tasks/missedReports/formatMissedReportsAlert.ts
index 2367deef9..9b54c293c 100644
--- a/lib/tasks/missedReports/formatMissedReportsAlert.ts
+++ b/lib/tasks/missedReports/formatMissedReportsAlert.ts
@@ -6,29 +6,43 @@ const CAUSE_LABELS: Record = {
no_email: "no email",
};
+/** Telegram cuts messages at 4,000 characters; this many lines stay well inside it. */
+const MAX_LISTED = 20;
+
/**
* The team's Telegram alert for scheduled reports that did not send: one
- * line per report with its cause, then the ids needed to look it up.
+ * line per report with its cause, then the ids needed to look it up, plus
+ * what could not be checked.
*
* @param misses - The missed reports and whether each customer was emailed.
- * @param unchecked - Runs that could not be checked (a read failed).
+ * @param coverage - What the check could not cover.
+ * @param coverage.unchecked - Runs that could not be read or checked.
+ * @param coverage.truncated - True when the hour held more runs than one page.
* @returns Plain text for `sendMessage`.
*/
export function formatMissedReportsAlert(
misses: NotifiedMissedReport[],
- unchecked: number,
+ { unchecked, truncated }: { unchecked: number; truncated: boolean },
): string {
const count = misses.length;
- const header = `⚠️ ${count} scheduled report${count === 1 ? "" : "s"} did not send (runs started 2-3 hours ago)`;
- const uncheckedLine =
- unchecked > 0
+ const header =
+ count > 0
+ ? `⚠️ ${count} scheduled report${count === 1 ? "" : "s"} did not send (runs started 2-3 hours ago)`
+ : "⚠️ Missed-report check could not cover every run (runs started 2-3 hours ago)";
+ const lines = misses
+ .slice(0, MAX_LISTED)
+ .map(
+ miss =>
+ `• ${miss.task.title}: ${CAUSE_LABELS[miss.cause]} (${miss.detail})\n account ${miss.task.account_id}, run ${miss.run.runId}, customer ${miss.customerNotified ? "emailed" : "not emailed"}`,
+ );
+ const notes = [
+ ...(count > MAX_LISTED ? [`…and ${count - MAX_LISTED} more`] : []),
+ ...(unchecked > 0
? [
`${unchecked} scheduled run${unchecked === 1 ? "" : "s"} could not be checked; see the api logs.`,
]
- : [];
- const lines = misses.map(
- miss =>
- `• ${miss.task.title}: ${CAUSE_LABELS[miss.cause]} (${miss.detail})\n account ${miss.task.account_id}, run ${miss.run.runId}, customer ${miss.customerNotified ? "emailed" : "not emailed"}`,
- );
- return [header, ...lines, ...uncheckedLine].join("\n");
+ : []),
+ ...(truncated ? ["More than 100 runs started in that hour; later ones were not checked."] : []),
+ ];
+ return [header, ...lines, ...notes].join("\n");
}
diff --git a/lib/tasks/missedReports/listScheduledReportRuns.ts b/lib/tasks/missedReports/listScheduledReportRuns.ts
index df44d0072..d38252666 100644
--- a/lib/tasks/missedReports/listScheduledReportRuns.ts
+++ b/lib/tasks/missedReports/listScheduledReportRuns.ts
@@ -6,16 +6,27 @@ import type { ScheduledReportRun } from "./types";
const SCHEDULED_TASK_ID = "customer-prompt-task";
/** One page of the runs API; an hour of schedules fits well inside it. */
const MAX_RUNS = 100;
+/** A hung Trigger.dev read must not stall the check (same budget as retrieveScheduleInfo). */
+const READ_TIMEOUT_MS = 5000;
+
+export interface ScheduledReportRunList {
+ runs: ScheduledReportRun[];
+ /** Runs that could not be read in time or at all. */
+ unreadable: number;
+ /** True when the window may hold more runs than one page. */
+ truncated: boolean;
+}
/**
* Scheduled customer-task runs created inside a window, each resolved to its
* `scheduled_actions` id. The list endpoint omits schedule details, so each
- * run is read once more; a run that cannot be read is skipped and logged.
+ * run is read once more, within a time budget; a run that cannot be read is
+ * counted and logged rather than holding up the rest.
*
* @param window - ISO bounds on the runs' `createdAt`.
* @param window.from - Inclusive lower bound.
* @param window.to - Upper bound.
- * @returns The runs that belong to a task.
+ * @returns The runs that belong to a task, plus what could not be checked.
*/
export async function listScheduledReportRuns({
from,
@@ -23,7 +34,7 @@ export async function listScheduledReportRuns({
}: {
from: string;
to: string;
-}): Promise {
+}): Promise {
const listed = await fetchTriggerRuns(
{
"filter[taskIdentifier]": SCHEDULED_TASK_ID,
@@ -32,22 +43,34 @@ export async function listScheduledReportRuns({
},
MAX_RUNS,
);
- if (listed.length === MAX_RUNS) {
+ const truncated = listed.length === MAX_RUNS;
+ if (truncated) {
console.warn(`[missed-report-check] ${MAX_RUNS}+ runs in ${from}..${to}; later ones unchecked`);
}
+ let unreadable = 0;
const resolved = await Promise.all(
listed.map(async run => {
try {
- const detail = await retrieveTaskRun(run.id);
+ const detail = await Promise.race([
+ retrieveTaskRun(run.id),
+ new Promise((_, reject) =>
+ setTimeout(() => reject(new Error("run read timed out")), READ_TIMEOUT_MS),
+ ),
+ ]);
const taskId = detail?.schedule?.externalId;
if (!taskId) return null;
return { runId: run.id, taskId, createdAt: run.createdAt, status: run.status };
} catch (error) {
+ unreadable += 1;
console.error(`[missed-report-check] could not read run ${run.id}:`, error);
return null;
}
}),
);
- return resolved.filter((run): run is ScheduledReportRun => run !== null);
+ return {
+ runs: resolved.filter((run): run is ScheduledReportRun => run !== null),
+ unreadable,
+ truncated,
+ };
}
diff --git a/lib/tasks/missedReports/sendMissedReportNotice.ts b/lib/tasks/missedReports/sendMissedReportNotice.ts
index b4c0dcf75..81d9d4df4 100644
--- a/lib/tasks/missedReports/sendMissedReportNotice.ts
+++ b/lib/tasks/missedReports/sendMissedReportNotice.ts
@@ -45,15 +45,17 @@ export async function sendMissedReportNotice(miss: MissedReport): PromiseYour scheduled task “${title}” was due and didn't run, because your plan doesn't cover it. ${escapeHtml(miss.detail)}Upgrade or change your tasks at ${miss.billingUrl}, and it will run at its next scheduled time.
`,
}
: {
- subject: `Your report didn't go out: ${miss.task.title}`,
+ subject: `Your report didn't go out: ${plainTitle}`,
html: `Your scheduled report “${title}” was due and didn't reach your inbox. We've been alerted and are looking into it.
It will run again at its next scheduled time.
`,
};
From 2db073fd1e01bc85b84680ec3fbd3d3e1494e8e8 Mon Sep 17 00:00:00 2001
From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com>
Date: Sat, 7 Nov 2026 03:17:10 -0500
Subject: [PATCH 4/4] Count missing runs as unchecked and bound alert lines
A listed run that comes back not found now counts as unchecked rather
than vanishing. The alert lists at most ten reports and clips long
titles (80) and details (120), so even worst-case entries stay inside
Telegram's 4,000-character limit.
Co-Authored-By: Claude Opus 5.5
---
.../formatMissedReportsAlert.test.ts | 22 ++++++++++++++++---
.../__tests__/listScheduledReportRuns.test.ts | 5 ++++-
.../missedReports/formatMissedReportsAlert.ts | 11 +++++++---
.../missedReports/listScheduledReportRuns.ts | 5 ++++-
4 files changed, 35 insertions(+), 8 deletions(-)
diff --git a/lib/tasks/missedReports/__tests__/formatMissedReportsAlert.test.ts b/lib/tasks/missedReports/__tests__/formatMissedReportsAlert.test.ts
index c274046a0..79d02557d 100644
--- a/lib/tasks/missedReports/__tests__/formatMissedReportsAlert.test.ts
+++ b/lib/tasks/missedReports/__tests__/formatMissedReportsAlert.test.ts
@@ -60,7 +60,7 @@ describe("formatMissedReportsAlert", () => {
});
// Telegram cuts messages at 4,000 characters; keep every alert readable.
- it("lists at most 20 reports and counts the rest", () => {
+ it("lists at most 10 reports and counts the rest", () => {
const miss = {
task: reportTask,
run: reportRun,
@@ -72,8 +72,8 @@ describe("formatMissedReportsAlert", () => {
unchecked: 0,
truncated: false,
});
- expect(text.match(/^• /gm)).toHaveLength(20);
- expect(text).toContain("…and 5 more");
+ expect(text.match(/^• /gm)).toHaveLength(10);
+ expect(text).toContain("…and 15 more");
expect(text.length).toBeLessThan(4000);
});
@@ -82,4 +82,20 @@ describe("formatMissedReportsAlert", () => {
"More than 100 runs started in that hour",
);
});
+
+ it("shortens long titles and details so the alert stays within Telegram's limit", () => {
+ const miss = {
+ task: { ...reportTask, title: "T".repeat(500) },
+ run: reportRun,
+ cause: "email_rejected" as const,
+ detail: "D".repeat(1000),
+ customerNotified: false,
+ };
+ const text = formatMissedReportsAlert(Array(20).fill(miss), {
+ unchecked: 0,
+ truncated: false,
+ });
+ expect(text.length).toBeLessThan(4000);
+ expect(text).toContain("…");
+ });
});
diff --git a/lib/tasks/missedReports/__tests__/listScheduledReportRuns.test.ts b/lib/tasks/missedReports/__tests__/listScheduledReportRuns.test.ts
index 7e473827f..bb07009b3 100644
--- a/lib/tasks/missedReports/__tests__/listScheduledReportRuns.test.ts
+++ b/lib/tasks/missedReports/__tests__/listScheduledReportRuns.test.ts
@@ -52,9 +52,11 @@ describe("listScheduledReportRuns", () => {
{ id: "run_manual", status: "COMPLETED", createdAt: "2026-11-06T10:01:00.000Z" },
{ id: "run_broken", status: "COMPLETED", createdAt: "2026-11-06T10:02:00.000Z" },
{ id: "run_ok", status: "FAILED", createdAt: "2026-11-06T10:03:00.000Z" },
+ { id: "run_gone", status: "COMPLETED", createdAt: "2026-11-06T10:04:00.000Z" },
]);
mockRetrieveTaskRun.mockImplementation(async (id: string) => {
if (id === "run_manual") return { schedule: undefined };
+ if (id === "run_gone") return null;
if (id === "run_broken") throw new Error("trigger down");
return { schedule: { externalId: "task-2" } };
});
@@ -62,7 +64,8 @@ describe("listScheduledReportRuns", () => {
const { runs, unreadable } = await listScheduledReportRuns(window);
expect(runs.map(run => run.runId)).toEqual(["run_ok"]);
- expect(unreadable).toBe(1);
+ // run_broken threw and run_gone came back empty; a manual run is simply not scheduled.
+ expect(unreadable).toBe(2);
expect(console.error).toHaveBeenCalled();
});
diff --git a/lib/tasks/missedReports/formatMissedReportsAlert.ts b/lib/tasks/missedReports/formatMissedReportsAlert.ts
index 9b54c293c..9b80b9d17 100644
--- a/lib/tasks/missedReports/formatMissedReportsAlert.ts
+++ b/lib/tasks/missedReports/formatMissedReportsAlert.ts
@@ -6,8 +6,13 @@ const CAUSE_LABELS: Record = {
no_email: "no email",
};
-/** Telegram cuts messages at 4,000 characters; this many lines stay well inside it. */
-const MAX_LISTED = 20;
+/** Telegram cuts messages at 4,000 characters; with the field caps below, ten lines stay inside it. */
+const MAX_LISTED = 10;
+const MAX_TITLE = 80;
+const MAX_DETAIL = 120;
+
+const clip = (text: string, max: number): string =>
+ text.length > max ? `${text.slice(0, max - 1)}…` : text;
/**
* The team's Telegram alert for scheduled reports that did not send: one
@@ -33,7 +38,7 @@ export function formatMissedReportsAlert(
.slice(0, MAX_LISTED)
.map(
miss =>
- `• ${miss.task.title}: ${CAUSE_LABELS[miss.cause]} (${miss.detail})\n account ${miss.task.account_id}, run ${miss.run.runId}, customer ${miss.customerNotified ? "emailed" : "not emailed"}`,
+ `• ${clip(miss.task.title, MAX_TITLE)}: ${CAUSE_LABELS[miss.cause]} (${clip(miss.detail, MAX_DETAIL)})\n account ${miss.task.account_id}, run ${miss.run.runId}, customer ${miss.customerNotified ? "emailed" : "not emailed"}`,
);
const notes = [
...(count > MAX_LISTED ? [`…and ${count - MAX_LISTED} more`] : []),
diff --git a/lib/tasks/missedReports/listScheduledReportRuns.ts b/lib/tasks/missedReports/listScheduledReportRuns.ts
index d38252666..69f2661b1 100644
--- a/lib/tasks/missedReports/listScheduledReportRuns.ts
+++ b/lib/tasks/missedReports/listScheduledReportRuns.ts
@@ -58,7 +58,10 @@ export async function listScheduledReportRuns({
setTimeout(() => reject(new Error("run read timed out")), READ_TIMEOUT_MS),
),
]);
- const taskId = detail?.schedule?.externalId;
+ // A listed run that cannot be found is unchecked; one without a schedule
+ // (a manual run) simply is not a scheduled report.
+ if (!detail) throw new Error("run not found");
+ const taskId = detail.schedule?.externalId;
if (!taskId) return null;
return { runId: run.id, taskId, createdAt: run.createdAt, status: run.status };
} catch (error) {