Repository navigation
Alert when a scheduled report sends no email - #1236
Conversation
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 <noreply@anthropic.com>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Important
This repository does not receive automatic reviews because it has fewer than 10 stars.
|
There was a problem hiding this comment.
8 issues found across 27 files
Confidence score: 3/5
formatMissedReportsAlert.tsbuilds a single Telegram message that can exceed the 4,000-character limit, hiding later reports and run IDs. Split long alerts into multiple messages.checkMissedReportsHandler.tsreturns 500 when the team alert fails after customer emails have been sent, so a retry can resend those notices. Make the Telegram alert best-effort or make customer notifications idempotent.findMissedReport.tscan miss a run when any later email exists for the account, and can flag prompts that mention email without requesting delivery. Bound the lookup to the run’s execution/grace window and require explicit send intent.types.tsallows aplan_blockedreport without abillingUrl, which can produce an upgrade email with anundefinedlink. Require the URL for that cause in the type.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="lib/tasks/missedReports/types.ts">
<violation number="1" location="lib/tasks/missedReports/types.ts:26">
P2: `billingUrl` is optional even when `cause` is `"plan_blocked"`, so a valid `MissedReport` can generate an upgrade email linking to `undefined`. Model the result as a discriminated union so plan-blocked reports require `billingUrl`, while the other causes omit it.</violation>
</file>
<file name="lib/tasks/missedReports/formatMissedReportsAlert.ts">
<violation number="1" location="lib/tasks/missedReports/formatMissedReportsAlert.ts:21">
P2: This builds one unbounded Telegram message, but `sendMessage` silently truncates messages at 4,000 characters. A busy one-hour window can contain up to 100 misses, so later reports and their run IDs disappear from the alert; split the alert into Telegram-sized messages (or otherwise preserve every entry) before sending.</violation>
</file>
<file name="lib/emails/validateSendEmailBody.ts">
<violation number="1" location="lib/emails/validateSendEmailBody.ts:84">
P2: Custom agent: **Enforce Clear Code Style and Maintainability Practices**
`validateSendEmailBody.ts` is now 137 lines, exceeding the under-100-line limit. Move the rejection-reason handling into a focused module instead of further expanding this validator.</violation>
</file>
<file name="lib/trigger/__tests__/fetchTriggerRuns.test.ts">
<violation number="1" location="lib/trigger/__tests__/fetchTriggerRuns.test.ts:7">
P3: This test never verifies the Trigger.dev authentication header, so an implementation that drops or corrupts the Bearer token would pass. Assert the fetch init contains `Authorization: "Bearer tr_test"`.</violation>
</file>
<file name="lib/tasks/missedReports/checkMissedReportsHandler.ts">
<violation number="1" location="lib/tasks/missedReports/checkMissedReportsHandler.ts:52">
P2: The team-alert failure occurs after customer emails and returns 500, so retrying this stateless window can resend successful customer notices. Isolate the best-effort Telegram failure or persist idempotent notification state before making the batch retryable.</violation>
</file>
<file name="lib/tasks/missedReports/findMissedReport.ts">
<violation number="1" location="lib/tasks/missedReports/findMissedReport.ts:7">
P2: `EMAILS` matches any occurrence of “email,” so prompts that discuss email without requesting delivery become missed reports. Detect an explicit send intent or persist the task’s delivery requirement instead.</violation>
<violation number="2" location="lib/tasks/missedReports/findMissedReport.ts:30">
P2: This lower-bound-only lookup lets any later email from the account hide the missed run. Bound attempts to the run’s execution/grace window, while retaining the documented account-level overlap behavior.</violation>
</file>
<file name="lib/emails/sendEmailHandler.ts">
<violation number="1" location="lib/emails/sendEmailHandler.ts:53">
P2: This records only `resend_error: Failed to send email.` for every provider failure because `processAndSendEmail` discards Resend's `details`. Preserve a bounded provider error/code before logging so historical failure reasons remain actionable.</violation>
</file>
Architecture diagram
sequenceDiagram
participant Cron as Vercel Cron
participant API as API Route
participant Handler as Check Handler
participant Trigger as Trigger.dev API
participant DB as Supabase DB
participant Email as Email Service
participant Telegram as Telegram Bot
Note over Cron,Telegram: Hourly Missed Report Check Flow
Cron->>API: GET /api/internal/missed-report-check
API->>API: Validate CRON_SECRET
alt Valid cron secret
API->>Handler: checkMissedReportsHandler()
Handler->>Handler: Calculate window (2-3 hours ago)
Handler->>Trigger: List runs (taskIdentifier=customer-prompt-task)
Trigger-->>Handler: Run list
loop Each run
Handler->>Trigger: Get run details
Trigger-->>Handler: Task ID from schedule
Handler->>DB: Get scheduled action
alt Task exists and enabled
DB-->>Handler: Task data
alt Task prompt asks for email
Handler->>DB: Query email_send_log (account, time window)
DB-->>Handler: Send attempts
alt No sent email found
Handler->>DB: Check plan block
DB-->>Handler: Plan status
alt Plan blocked
Handler->>Handler: Classify as plan_blocked
else Has rejection reason
Handler->>Handler: Classify as email_rejected
else No send attempt
Handler->>Handler: Classify as no_email
end
opt Customer notices enabled (MISSED_REPORT_CUSTOMER_NOTICES=true)
alt Plan blocked OR catalog report task
Handler->>Email: Send customer notice
Email-->>Handler: Send result
else
Handler->>Handler: Skip customer notice
end
end
Handler->>Handler: Record miss with notification state
end
end
end
end
alt Misses found
Handler->>Telegram: Send team alert
Telegram-->>Handler: Message sent
end
Handler-->>API: JSON summary
API-->>Cron: 200 OK
else Invalid cron secret
API-->>Cron: 401 Unauthorized
end
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| /** The plan message, the latest rejection reason, or the run status. */ | ||
| detail: string; | ||
| /** Where to upgrade, when the plan blocked the task. */ | ||
| billingUrl?: string; |
There was a problem hiding this comment.
P2: billingUrl is optional even when cause is "plan_blocked", so a valid MissedReport can generate an upgrade email linking to undefined. Model the result as a discriminated union so plan-blocked reports require billingUrl, while the other causes omit it.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/tasks/missedReports/types.ts, line 26:
<comment>`billingUrl` is optional even when `cause` is `"plan_blocked"`, so a valid `MissedReport` can generate an upgrade email linking to `undefined`. Model the result as a discriminated union so plan-blocked reports require `billingUrl`, while the other causes omit it.</comment>
<file context>
@@ -0,0 +1,31 @@
+ /** The plan message, the latest rejection reason, or the run status. */
+ detail: string;
+ /** Where to upgrade, when the plan blocked the task. */
+ billingUrl?: string;
+}
+
</file context>
| 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"}`, |
There was a problem hiding this comment.
P2: This builds one unbounded Telegram message, but sendMessage silently truncates messages at 4,000 characters. A busy one-hour window can contain up to 100 misses, so later reports and their run IDs disappear from the alert; split the alert into Telegram-sized messages (or otherwise preserve every entry) before sending.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/tasks/missedReports/formatMissedReportsAlert.ts, line 21:
<comment>This builds one unbounded Telegram message, but `sendMessage` silently truncates messages at 4,000 characters. A busy one-hour window can contain up to 100 misses, so later reports and their run IDs disappear from the alert; split the alert into Telegram-sized messages (or otherwise preserve every entry) before sending.</comment>
<file context>
@@ -0,0 +1,24 @@
+ 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");
</file context>
| status: "send_failed", | ||
| accountId, | ||
| chatId: chat_id, | ||
| reason: `resend_error: ${result.error}`, |
There was a problem hiding this comment.
P2: This records only resend_error: Failed to send email. for every provider failure because processAndSendEmail discards Resend's details. Preserve a bounded provider error/code before logging so historical failure reasons remain actionable.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/emails/sendEmailHandler.ts, line 53:
<comment>This records only `resend_error: Failed to send email.` for every provider failure because `processAndSendEmail` discards Resend's `details`. Preserve a bounded provider error/code before logging so historical failure reasons remain actionable.</comment>
<file context>
@@ -46,7 +46,12 @@ export async function sendEmailHandler(request: NextRequest): Promise<NextRespon
+ status: "send_failed",
+ accountId,
+ chatId: chat_id,
+ reason: `resend_error: ${result.error}`,
+ };
} else {
</file context>
| { status: "error", missing_fields: firstError.path, error: firstError.message }, | ||
| { status: 400, headers: getCorsHeaders() }, | ||
| ), | ||
| reason: `invalid_body: ${field ? `${field}: ` : ""}${firstError.message}`, |
There was a problem hiding this comment.
P2: Custom agent: Enforce Clear Code Style and Maintainability Practices
validateSendEmailBody.ts is now 137 lines, exceeding the under-100-line limit. Move the rejection-reason handling into a focused module instead of further expanding this validator.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/emails/validateSendEmailBody.ts, line 84:
<comment>`validateSendEmailBody.ts` is now 137 lines, exceeding the under-100-line limit. Move the rejection-reason handling into a focused module instead of further expanding this validator.</comment>
<file context>
@@ -72,18 +74,20 @@ export async function validateSendEmailBody(
{ status: "error", missing_fields: firstError.path, error: firstError.message },
{ status: 400, headers: getCorsHeaders() },
),
+ reason: `invalid_body: ${field ? `${field}: ` : ""}${firstError.message}`,
};
}
</file context>
| describe("fetchTriggerRuns", () => { | ||
| beforeEach(() => { | ||
| vi.stubEnv("TRIGGER_SECRET_KEY", "tr_test"); | ||
| global.fetch = vi.fn().mockResolvedValue({ |
There was a problem hiding this comment.
P3: This test never verifies the Trigger.dev authentication header, so an implementation that drops or corrupts the Bearer token would pass. Assert the fetch init contains Authorization: "Bearer tr_test".
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/trigger/__tests__/fetchTriggerRuns.test.ts, line 7:
<comment>This test never verifies the Trigger.dev authentication header, so an implementation that drops or corrupts the Bearer token would pass. Assert the fetch init contains `Authorization: "Bearer tr_test"`.</comment>
<file context>
@@ -0,0 +1,30 @@
+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" }] }),
</file context>
- 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 <noreply@anthropic.com>
There was a problem hiding this comment.
2 existing issues remain and 3 new issues found across 10 files (changes from recent commits).
Confidence score: 3/5
findMissedReport.tscan treat an unrelated failed email from the same account as proof this scheduled run attempted a send, misclassifying a plan-blocked report. Tie the attempt check to the specific run.checkMissedReportsHandler.tssends customer notices and a Telegram alert onGET, so repeated requests can trigger duplicate deliveries. UsePOSTfor the cron action and update its caller.sendMissedReportNotice.tshas a race in the 30-day cap: overlapping checks can both pass the lookup and send notices. Reserve the window atomically or enforce a database uniqueness constraint.sendMissedReportNotice.test.tsdoes not verify the 30-day boundary because the mocked row is returned regardless of age. Freeze time and assert thecreatedAfterlower bound.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="lib/tasks/missedReports/checkMissedReportsHandler.ts">
<violation number="1" location="lib/tasks/missedReports/checkMissedReportsHandler.ts:63">
P2: Custom agent: **API Design Consistency and Maintainability**
This `GET` handler sends customer notices and a Telegram alert. Expose the cron action as `POST` and update its caller; duplicate GET deliveries can repeat the team alert.</violation>
</file>
<file name="lib/supabase/email_send_log/selectAccountEmailAttempts.ts">
<violation number="1" location="lib/supabase/email_send_log/selectAccountEmailAttempts.ts:21">
P2: This duplicates the existing `selectEmailSendLog` table query. Extend that accessor with an opt-in throw-on-error mode and call it with `accountId` and `createdAfter` here, so filters and error handling remain centralized.</violation>
</file>
<file name="lib/tasks/missedReports/__tests__/sendMissedReportNotice.test.ts">
<violation number="1" location="lib/tasks/missedReports/__tests__/sendMissedReportNotice.test.ts:90">
P2: This test does not verify the claimed 30-day boundary: the mocked row is returned regardless of its age, and the expectation omits `createdAfter`. Freeze time and assert the lower bound (ideally with an in-window and out-of-window case) so a regression to all-time suppression is caught.</violation>
</file>
Requires human review: Auto-approval blocked because this review re-detected 3 unresolved issues already reported by Cubic.
View guided diff | Turn on auto-fix | Re-trigger cubic
| accountId: string; | ||
| since: string; | ||
| }): Promise<Tables<"email_send_log">[]> { | ||
| const { data, error } = await supabase |
There was a problem hiding this comment.
P2: This duplicates the existing selectEmailSendLog table query. Extend that accessor with an opt-in throw-on-error mode and call it with accountId and createdAfter here, so filters and error handling remain centralized.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/supabase/email_send_log/selectAccountEmailAttempts.ts, line 21:
<comment>This duplicates the existing `selectEmailSendLog` table query. Extend that accessor with an opt-in throw-on-error mode and call it with `accountId` and `createdAfter` here, so filters and error handling remain centralized.</comment>
<file context>
@@ -0,0 +1,28 @@
+ accountId: string;
+ since: string;
+}): Promise<Tables<"email_send_log">[]> {
+ const { data, error } = await supabase
+ .from("email_send_log")
+ .select("*")
</file context>
| }); | ||
|
|
||
| vi.clearAllMocks(); | ||
| mockSelectEmailSendLog.mockResolvedValue([{ id: "earlier-notice" }]); |
There was a problem hiding this comment.
P2: This test does not verify the claimed 30-day boundary: the mocked row is returned regardless of its age, and the expectation omits createdAfter. Freeze time and assert the lower bound (ideally with an in-window and out-of-window case) so a regression to all-time suppression is caught.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/tasks/missedReports/__tests__/sendMissedReportNotice.test.ts, line 90:
<comment>This test does not verify the claimed 30-day boundary: the mocked row is returned regardless of its age, and the expectation omits `createdAfter`. Freeze time and assert the lower bound (ideally with an in-window and out-of-window case) so a regression to all-time suppression is caught.</comment>
<file context>
@@ -49,6 +60,36 @@ describe("sendMissedReportNotice", () => {
+ });
+
+ vi.clearAllMocks();
+ mockSelectEmailSendLog.mockResolvedValue([{ id: "earlier-notice" }]);
+ expect(await sendMissedReportNotice(blocked)).toBe(false);
+ expect(mockSend).not.toHaveBeenCalled();
</file context>
| } | ||
|
|
||
| if (misses.length > 0 || unchecked > 0) { | ||
| await sendMessage(formatMissedReportsAlert(misses, unchecked)); |
There was a problem hiding this comment.
P2: Custom agent: API Design Consistency and Maintainability
This GET handler sends customer notices and a Telegram alert. Expose the cron action as POST and update its caller; duplicate GET deliveries can repeat the team alert.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/tasks/missedReports/checkMissedReportsHandler.ts, line 63:
<comment>This `GET` handler sends customer notices and a Telegram alert. Expose the cron action as `POST` and update its caller; duplicate GET deliveries can repeat the team alert.</comment>
<file context>
@@ -28,34 +31,44 @@ export async function checkMissedReportsHandler(request: NextRequest): Promise<N
- if (misses.length > 0) await sendMessage(formatMissedReportsAlert(misses));
+ if (misses.length > 0 || unchecked > 0) {
+ await sendMessage(formatMissedReportsAlert(misses, unchecked));
+ }
</file context>
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 <noreply@anthropic.com>
There was a problem hiding this comment.
1 existing issue remains and no new issues found across 11 files (changes from recent commits).
Confidence score: 3/5
formatMissedReportsAlert.tscan still produce a message that exceeds Telegram’s length limit when titles or details are long, so the alert may fail to send. Enforce a character budget or truncate rendered fields before joining.
Requires human review: Auto-approval blocked because this review re-detected 1 unresolved issue already reported by Cubic.
View guided diff | Turn on auto-fix | Re-trigger cubic
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 <noreply@anthropic.com>
There was a problem hiding this comment.
0 issues found across 4 files (changes from recent commits).
Confidence score: 5/5
- Automated review surfaced no issues in the provided summaries.
- No files require special attention.
Requires human review: Auto-approval blocked by 11 unresolved issues from previous reviews.
View guided diff | Turn on auto-fix | Re-trigger cubic
Summary
An hourly check that finds scheduled reports that sent no email, tells the team on Telegram, and (once switched on) tells the customer.
Why
Today a report can stop without anyone knowing:
GET /api/tasks?id=answers 402 when the plan no longer covers a task; the Trigger runner (tasks/src/recoup/fetchTask.ts) treats that as "no task" and exits. The customer never hears, at exactly the moment an upgrade prompt would land.runningforever; no timeout, no cancel app#2022).POST /api/emails(Report emails silently rejected at validation (59% of sends); stale run columns, dead IG handle, cold-load error toast app#1949).One check after the fact catches all three without fixing each path first.
How it works
17 * * * *→GET /api/internal/missed-report-check(CRON_SECRET, same as the other internal crons).sentrow inemail_send_logfor the task's account after the run started? The run's sandbox key is minted for the task's account (handleStartChatRun.ts:53), so its sends are logged there. This read throws on a database error, so "unknown" is never mistaken for "not sent".Customer emails are off until switched on
MISSED_REPORT_CUSTOMER_NOTICES=trueturns on owner emails:Every notice carries a per-run Resend idempotency key, so a duplicated cron delivery can't email twice (it can repeat the team alert). I couldn't read production to size the volume, so the team alert runs alone first. Turning notices on is one environment variable.
Known limits
Merge order
This branch is built on #1235 (rejection reasons) and needs recoupable/database#132. Merge database#132, then #1235, then this. The diff shows #1235's commit until it merges.
Tests
Tests first: 6 new test files (window bounds, run listing, miss classification, notice rules, dedupe and escaping, alert text, handler flow including a failing run). An independent review's findings are addressed in a49a373.
pnpm vitest run→ 9,303 passed. The 3 MCP test files that fail need a generated./generated-uimodule that a fresh worktree lacks; they fail the same way onmain. ESLint and Prettier clean on changed files.🤖 Generated with Claude Code