Comprehensive workflow reminder management for booking lifecycle events
Tier 2 hard typescript · local · real merged PR from calcom/cal.com #7232
Ground-truth defects
Asynchronous functions deleteScheduledEmailReminder and deleteScheduledSMSReminder are called without await inside forEach loops. This occurs during booking rescheduling/cancellation, and workflow/workflow step deletion/updates. Consequently, scheduled workflow reminders may not be reliably cancelled, potentially leaving them active.
The new immediateDelete branch of deleteScheduledEmailReminder cancels the scheduled email at SendGrid on the spot, and three new call sites use it (rescheduling in handleNewBooking, workflow and workflow-step deletion in workflows.tsx). Each such cancellation stays pending in SendGrid's scheduled_sends until the email's send time, up to 72h ahead, and SendGrid allows only 100 pending cancellations: the limit this PR's deferred, cron-driven cancellation exists to stay under. Under steady rescheduling the immediate cancellations fill it, after which cancellations are rejected (and only logged), both the immediate ones and the cron's deferred ones, so reminders for rescheduled and cancelled bookings are sent anyway.
The new cancellation sweep awaits a SendGrid cancel per reminder inside the loop while pushing `prisma.workflowReminder.delete(...)` into an array that is awaited only after the loop. Prisma returns a lazy PrismaPromise that does not execute until awaited, so a SendGrid rejection at index N jumps to the catch and none of the 0..N-1 deletes ever run, while reminders from N onward are never cancelled even though their rows are marked cancelled.
The change under review
diff (truncated — full diff)
@@ -1,8 +1,6 @@ import { BookingStatus, MembershipRole, - Prisma, - PrismaPromise, WebhookTriggerEvents, WorkflowMethods, WorkflowReminder, @@ -483,29 +481,18 @@ async function handler(req: NextApiRequest & { userId?: number }) { cancelScheduledJobs(booking); }); - //Workflows - delete all reminders for bookings - const remindersToDelete: PrismaPromise<Prisma.BatchPayload>[] = []; + //Workflows - cancel all reminders for cancelled bookings updatedBookings.forEach((booking) => { booking.workflowReminders.forEach((reminder) => { - if (reminder.scheduled && reminder.referenceId) { - if (reminder.method === WorkflowMethods.EMAIL) { - deleteScheduledEmailReminder(reminder.referenceId); - } else if (reminder.method === WorkflowMethods.SMS) { - deleteScheduledSMSReminder(reminder.referenceId); - } + if (reminder.method === WorkflowMethods.EMAIL) { + deleteScheduledEmailReminder(reminder.id, reminder.referenceId); + } else if (reminder.method === WorkflowMethods.SMS) { + deleteScheduledSMSReminder(reminder.id, reminder.referenceId); } - const reminderToDelete = prisma.workflowReminder.deleteMany({ - where: { - id: reminder.id, - }, - }); - remindersToDelete.push(reminderToDelete); }); }); - const prismaPromises: Promise<unknown>[] = [attendeeDeletes, bookingReferenceDeletes].concat( - remindersToDelete - ); + const prismaPromises: Promise<unknown>[] = [attendeeDeletes, bookingReferenceDeletes]; await Promise.all(prismaPromises.concat(apiDeletes)); @@ -1,5 +1,13 @@ -import type { App, Credential, EventTypeCustomInput, Prisma } from "@prisma/client"; -import { BookingStatus, SchedulingType, WebhookTriggerEvents } from "@prisma/client"; +import { + App, + BookingStatus, + Credential, + EventTypeCustomInput, + Prisma, + SchedulingType, + WebhookTriggerEvents, + WorkflowMethods, +} from "@prisma/client"; import async from "async"; import { isValidPhoneNumber } from "libphonenumber-js"; import { cloneDeep } from "lodash"; @@ -28,7 +36,9 @@ import { sendScheduledEmails, sendScheduledSeatsEmails, } from "@calcom/emails"; +import { deleteScheduledEmailReminder } from "@calcom/features/ee/workflows/lib/reminders/emailReminderManager"; import { scheduleWorkflowReminders } from "@calcom/features/ee/workflows/lib/reminders/reminderScheduler"; +import { deleteScheduledSMSReminder } from "@calcom/features/ee/workflows/lib/reminders/smsReminderManager"; import getWebhooks from "@calcom/features/webhooks/lib/getWebhooks"; import { isPrismaObjOrUndefined, parseRecurringEvent } from "@calcom/lib"; import { getVideoCallUrl } from "@calcom/lib/CalEventParser"; @@ -759,6 +769,7 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) { }, }, payment: true, + workflowReminders: true, }, }); } @@ -950,6 +961,19 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) { let videoCallUrl; if (originalRescheduledBooking?.uid) { + try { + // cancel workflow reminders from previous rescheduled booking + originalRescheduledBooking.workflowReminders.forEach((reminder) => { + if (reminder.method === WorkflowMethods.EMAIL) { + deleteScheduledEmailReminder(reminder.id, reminder.referenceId, true); + } else if (reminder.method === WorkflowMethods.SMS) { + deleteScheduledSMSReminder(reminder.id, reminder.referenceId); + } + }); + } catch (error) { + log.error("Error while canceling scheduled workflow reminders", error); + } + // Use EventManager to conditionally use all needed integrations. const updateManager = await eventManager.reschedule( evt, @@ -7,6 +7,7 @@ import type { NextApiRequest, NextApiResponse } from "next"; import dayjs from "@calcom/dayjs"; import { defaultHandler } from "@calcom/lib/server"; import prisma from "@calcom/prisma"; +import { Prisma, WorkflowReminder } from "@calcom/prisma/client"; import { bookingMetadataSchema } from "@calcom/prisma/zod-utils"; import customTemplate, { VariablesType } from "../lib/reminders/templates/customTemplate"; @@ -39,6 +40,42 @@ async function handler(req: NextApiRequest, res: NextApiResponse) { }, }); + //cancel reminders for cancelled/rescheduled bookings that are scheduled within the next hour + const remindersToCancel = await prisma.workflowReminder.findMany({ + where: { + cancelled: true, + scheduledDate: { + lte: dayjs().add(1, "hour").toISOString(), + }, + }, + }); + + try { + const workflowRemindersToDelete: Prisma.Prisma__WorkflowReminderClient<WorkflowReminder, never>[] = []; + + for (const reminder of remindersToCancel) { + await client.request({ + url: "/v3/user/scheduled_sends", + method: "POST", + body: { + batch_id: reminder.referenceId, + status: "cancel", + }, + }); + + const workflowReminderToDelete = prisma.workflowReminder.delete({ + where: { + id: reminder.id, + }, + }); + + workflowRemindersToDelete.push(workflowReminderToDelete); + } + await Promise.all(workflowRemindersToDelete); + } catch (error) { + console.log(`Error cancelling scheduled Emails: ${error}`); + } + //find all unscheduled Email reminders const unscheduledReminders = await prisma.workflowReminder.findMany({ where: { @@ -387,81 +387,75 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) { }} /> </div> - {(isPhoneNumberNeeded || isSenderIdNeeded) && ( + {isPhoneNumberNeeded && ( <div className="mt-2 rounded-md bg-gray-50 p-4 pt-0"> - {isPhoneNumberNeeded && ( + <Label className="pt-4">{t("custom_phone_number")}</Label> + <div className="block sm:flex"> + <PhoneInput<FormValues> + control={form.control} + name={`steps.${step.stepNumber - 1}.sendTo`} + placeholder={t("phone_number")} + id={`steps.${step.stepNumber - 1}.sendTo`} + className="min-w-fit sm:rounded-tl-md sm:rounded-bl-md sm:border-r-transparent" + required + onChange={() => { + const isAlreadyVerified = !!verifiedNumbers + ?.concat([]) + .find((number) => number === form.getValues(`steps.${step.stepNumber - 1}.sendTo`)); + setNumberVerified(isAlreadyVerified); + }} + /> + <Button + color="secondary" + disabled={numberVerified || false} + className={classNames( + "-ml-[3px] h-[40px] min-w-fit sm:block sm:rounded-tl-none sm:rounded-bl-none ", + numberVerified ? "hidden" : "mt-3 sm:mt-0" + )} + onClick={() => + sendVerificationCodeMutation.mutate({ + phoneNumber: form.getValues(`steps.${step.stepNumber - 1}.sendTo`) || "", + }) + }> + {t("send_code")} + </Button> + </div> + + {form.formState.errors.steps && + form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo && ( + <p className="mt-1 text-xs text-red-500"> + {form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo?.message || ""} + </p> + )} + {numberVerified ? ( + <div className="mt-1"> + <Badge variant="green">{t("number_verified")}</Badge> + </div> + ) : ( <> - <Label className="pt-4">{t("custom_phone_number")}</Label> - <div className="block sm:flex"> - <PhoneInput<FormValues> - control={form.control} - name={`steps.${step.stepNumber - 1}.sendTo`} - placeholder={t("phone_number")} - id={`steps.${step.stepNumber - 1}.sendTo`} - className="min-w-fit sm:rounded-tl-md sm:rounded-bl-md sm:border-r-transparent" - required - onChange={() => { - const isAlreadyVerified = !!verifiedNumbers - ?.concat([]) - .find( - (number) => number === form.getValues(`steps.${step.stepNumber - 1}.sendTo`) - ); - setNumberVerified(isAlreadyVerified); + <div className="mt-3 flex"> + <TextField + className=" border-r-transparent" + placeholder="Verification code" + value={verificationCode} + onChange={(e) => { + setVerificationCode(e.target.value); }} + required /> <Button color="secondary" - disabled={numberVerified || false} - className={classNames( - "-ml-[3px] h-[40px] min-w-fit sm:block sm:rounded-tl-none sm:rounded-bl-none ", - numberVerified ? "hidden" : "mt-3 sm:mt-0" - )} - onClick={() => - sendVerificationCodeMutation.mutate({ + className="-ml-[3px] rounded-tl-none rounded-bl-none " + disabled={verifyPhoneNumberMutation.isLoading} + onClick={() => { + verifyPhoneNumberMutation.mutate({ phoneNumber: form.getValues(`steps.${step.stepNumber - 1}.sendTo`) || "", - }) - }> - {t("send_code")} + code: verificationCode, + }); + }}> + Verify </Button> </div> - - {form.formState.errors.steps && - form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo && ( - <p className="mt-1 text-xs text-red-500"> - {form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo?.message || ""} - </p> - )} - {numberVerified ? ( - <div className="mt-1"> - <Badge variant="green">{t("number_verified")}</Badge> - </div> - ) : ( - <> - <div className="mt-3 flex"> - <TextField - className=" border-r-transparent" - placeholder="Verification code" - value={verificationCode} - onChange={(e) => { - setVerificationCode(e.target.value); - }} - required - /> - <Button - color="secondary" - className="-ml-[3px] rounded-tl-none rounded-bl-none " - disabled={verifyPhoneNumberMutation.isLoading} - onClick={() => { - verifyPhoneNumberMutation.mutate({ - phoneNumber: form.getValues(`steps.${step.stepNumber - 1}.sendTo`) || "", - code: verificationCode, - }); - }}> - Verify - </Button> - </div> - </> - )} </> )} </div> @@ -194,20 +194,41 @@ export const scheduleEmailReminder = async ( } }; -export const deleteScheduledEmailReminder = async (referenceId: string) => { +export const deleteScheduledEmailReminder = async ( + reminderId: number, + referenceId: string | null, + immediateDelete?: boolean +) => { try { - await client.request({ - url: "/v3/user/scheduled_sends", - method: "POST", - body: { - batch_id: referenceId, - status: "cancel", - }, - }); + if (!referenceId) { + await prisma.workflowReminder.delete({ + where: { + id: reminderId, + }, + }); + + return; + } - await client.request({ - url: `/v3/user/scheduled_sends/${referenceId}`, - method: "DELETE", + if (immediateDelete) { + await client.request({ + url: "/v3/user/scheduled_sends", + method: "POST", + body: { + batch_id: referenceId, + status: "cancel", + }, + }); + return; + } + + await prisma.workflowReminder.update({ + where: { + id: reminderId, + }, + data: { + cancelled: true, + }, }); } catch (error) { console.log(`Error canceling reminder with error ${error}`); @@ -174,9 +174,16 @@ export const scheduleSMSReminder = async ( } }; -export const deleteScheduledSMSReminder = async (referenceId: string) => { +export const deleteScheduledSMSReminder = async (reminderId: number, referenceId: string | null) => { try { - await twilio.cancelSMS(referenceId); + if (referenceId) { + await twilio.cancelSMS(referenceId); + } + await prisma.workflowReminder.delete({ + where: { + id: reminderId, + }, + }); } catch (error) { console.log(`Error canceling reminder with error ${error}`); } new file mode 100644 @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "WorkflowReminder" ADD COLUMN "cancelled" BOOLEAN; @@ -641,6 +641,7 @@ model WorkflowReminder { scheduled Boolean workflowStepId Int workflowStep WorkflowStep @relation(fields: [workflowStepId], references: [id], onDelete: Cascade) + cancelled Boolean? } enum WorkflowTemplates { @@ -5,7 +5,6 @@ import type { Workflow, WorkflowsOnEventTypes, WorkflowStep, - PrismaPromise, } from "@prisma/client"; import { BookingStatus, @@ -482,30 +481,18 @@ export const bookingsRouter = router({ }, }); - // delete scheduled jobs of cancelled bookings + // delete scheduled jobs of previous booking cancelScheduledJobs(bookingToReschedule); - //cancel workflow reminders - const remindersToDelete: PrismaPromise<Prisma.BatchPayload>[] = []; - + //cancel workflow reminders of previous booking bookingToReschedule.workflowReminders.forEach((reminder) => { - if (reminder.scheduled && reminder.referenceId) { - if (reminder.method === WorkflowMethods.EMAIL) { - deleteScheduledEmailReminder(reminder.referenceId); - } else if (reminder.method === WorkflowMethods.SMS) { - deleteScheduledSMSReminder(reminder.referenceId); - } + if (reminder.method === WorkflowMethods.EMAIL) { + deleteScheduledEmailReminder(reminder.id, reminder.referenceId); + } else if (reminder.method === WorkflowMethods.SMS) { + deleteScheduledSMSReminder(reminder.id, reminder.referenceId); } - const reminderToDelete = prisma.workflowReminder.deleteMany({ - where: { - id: reminder.id, - }, - }); - remindersToDelete.push(reminderToDelete); }); - await Promise.all(remindersToDelete); - const [mainAttendee] = bookingToReschedule.attendees; // @NOTE: Should we assume attendees language? const tAttendees = await getTranslation(mainAttendee.locale ?? "en", "common"); @@ -1,11 +1,12 @@ -import type { Prisma, PrismaPromise } from "@prisma/client"; import { + PrismaPromise, WorkflowTemplates, WorkflowActions, WorkflowTriggerEvents, BookingStatus, WorkflowMethods, TimeUnit, + Prisma } from "@prisma/client"; import { z } from "zod"; @@ -23,7 +24,6 @@ import { scheduleEmailReminder, } from "@calcom/features/ee/workflows/lib/reminders/emailReminderManager"; import { - // BookingInfo, deleteScheduledSMSReminder, scheduleSMSReminder, } from "@calcom/features/ee/workflows/lib/reminders/smsReminderManager"; @@ -208,13 +208,12 @@ export const workflowsRouter = router({ }, }); + //cancel workflow reminders of deleted workflow scheduledReminders.forEach((reminder) => { - if (reminder.referenceId) { - if (reminder.method === WorkflowMethods.EMAIL) { - deleteScheduledEmailReminder(reminder.referenceId); - } else if (reminder.method === WorkflowMethods.SMS) { - deleteScheduledSMSReminder(reminder.referenceId); - } + if (reminder.method === WorkflowMethods.EMAIL) { + deleteScheduledEmailReminder(reminder.id, reminder.referenceId, true); + } else if (reminder.method === WorkflowMethods.SMS) { + deleteScheduledSMSReminder(reminder.id, reminder.referenceId);
Leaderboard for this case
hard · 1 of 9 bots fully caught it (11% solve rate) · 56% avg coverage.
| # | Bot | Result | Caught | Coverage | Findings | False alarms |
|---|---|---|---|---|---|---|
| 1 | Claude Code (Opus 5.5) | solved | 3/3 | 100.0% | 5 | 0 |
| 2 | cursor | partial | 2/3 | 66.7% | 2 | 0 |
| 3 | Mjolnir (Sonnet 5.5) | partial | 2/3 | 66.7% | 5 | 0 |
| 4 | qodo | partial | 2/3 | 66.7% | 3 | 0 |
| 5 | greptile | partial | 2/3 | 66.7% | 4 | 1 |
| 6 | Drape (Deep Review) | partial | 1/3 | 33.3% | 4 | 0 |
| 7 | Drape (Review) | partial | 1/3 | 33.3% | 4 | 0 |
| 8 | Mjolnir (Opus 5.5) | partial | 1/3 | 33.3% | 4 | 0 |
| 9 | Cubic | partial | 1/3 | 33.3% | 4 | 2 |
Bot results
Claude Code (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | off by one |
| d2 | medium | ✓ | exact |
| d3 | medium | ✓ | exact |
The handleNewBooking reschedule path calls the immediate SendGrid cancel. requestReschedule in bookings.tsx uses the deferred `cancelled: true` path, so the two reschedule paths behave differently. The wrapping try/catch is also useless because the async calls aren't awaited. That second point causes little harm, since the helpers catch their own errors. [grounded: diff] [consensus 3/3: valid=3]
The prisma delete follows cancelSMS in the same try, so a cancel failure skips the delete. The diff removed the callers' own deleteMany calls, which previously always cleaned up the row, so failed cancels now leave orphan reminder rows. [grounded: diff] [consensus 3/5: valid=3, invalid=2]
raw comments (5)
All cancellations run inside one try block, so if any SendGrid cancel request throws, the whole loop stops. That can happen on a rate limit, an invalid or expired batch_id, or a batch that was already cancelled. The remaining reminders are never cancelled. The queued `prisma.workflowReminder.delete` calls are lazy PrismaPromises and never run either, because `Promise.all` is skipped. The failing reminder stays `cancelled: true` and is retried first on every cron run, so it can keep blocking every later cancellation until its scheduledDate passes. Once that happens the reminder is purged and the emails for cancelled or rescheduled bookings it held back are sent anyway. Each reminder needs its own try/catch.
The `immediateDelete` path cancels the SendGrid batch but no longer calls `DELETE /v3/user/scheduled_sends/{id}`. It also never deletes the WorkflowReminder row. On reschedule (`handleNewBooking`), the old booking's scheduled email reminders stay in the DB with `scheduled: true` and no `cancelled` flag. Nothing removes them until the cron purges past-dated rows. The cancelled batches also pile up on SendGrid, which caps the number of cancelled/paused scheduled sends. That cap was the reason for this deferred-cancellation change, and it can make later cancels fail.
Rescheduling here passes `immediateDelete=true`, but the equivalent reschedule path in `bookings.tsx` (requestReschedule) uses deferred cancellation. The two behave differently: this path cancels on SendGrid immediately and works against the SendGrid cancel limit the change is meant to avoid. The try/catch also does nothing, because the async delete functions aren't awaited and their rejections never reach it.
The DB delete now runs after `twilio.cancelSMS` in the same try block. If the cancel throws, the reminder row is not deleted. This happens when the SMS was already sent or the SID is no longer cancelable, which is common now that callers no longer filter on `scheduled`. Callers also removed their own `deleteMany` calls, so these rows are never cleaned up. Before this change they were always deleted.
Reminder cancellation and deletion used to be awaited as part of `Promise.all(prismaPromises)`. They are now fire-and-forget async calls inside `forEach`. In a serverless handler the response can return before these DB updates and deletes finish, and all errors are swallowed. The same pattern was added in `bookings.tsx` and `workflows.tsx`.
Cubic · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | off by one |
| d2 | medium | ✗ | — |
| d3 | medium | ✗ | — |
The PR deliberately defers SendGrid cancellation: it sets `cancelled: true`, and the cron job cancels those batches in the hour before they send. handleCancelBooking uses the same pattern. Leaving the batch active until that window is the intended design, so the claimed failure (the reminder going out) does not happen. [invalid: contradiction] [consensus 5/5: invalid=5]
Before this change, the mutation awaited the DB deletes. The PR removes that await and moves the DB work into the cancel helpers, which are called without await, so the mutation can return before cancellation finishes and the work can be lost or race later updates. [grounded: diff] [consensus 5/5: valid=5]
Only deleteScheduledEmailReminder ever sets `cancelled: true`; the SMS path deletes the row outright. A cancelled non-email reminder therefore can't exist, so the missing method filter is never triggered. [invalid: contradiction] [consensus 5/5: invalid=5]
raw comments (5)
<!-- cubic:v=8166677f-c553-46e5-af44-0f35f7732f6b -->
<!-- cubic:review-run=c2af7a72-b97a-5c72-a4f1-d02f4843beed -->
<!-- metadata:{"confidence":8} -->
P1: When a booking is rescheduled more than one hour before an email reminder, this call leaves its SendGrid batch active until the scheduler’s cancellation window. Cancel the scheduled email immediately in this reschedule path by passing `true` for `immediateDelete`.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At packages/trpc/server/routers/viewer/bookings.tsx, line 490:
<comment>When a booking is rescheduled more than one hour before an email reminder, this call leaves its SendGrid batch active until the scheduler’s cancellation window. Cancel the scheduled email immediately in this reschedule path by passing `true` for `immediateDelete`.</comment>
<file context>
@@ -482,30 +481,18 @@ export const bookingsRouter = router({
- deleteScheduledSMSReminder(reminder.referenceId);
- }
+ if (reminder.method === WorkflowMethods.EMAIL) {
+ deleteScheduledEmailReminder(reminder.id, reminder.referenceId);
+ } else if (reminder.method === WorkflowMethods.SMS) {
+ deleteScheduledSMSReminder(reminder.id, reminder.referenceId);
</file context>
```
</details>
```suggestion
deleteScheduledEmailReminder(reminder.id, reminder.referenceId, true);
```
<!-- cubic:v=8dd10ae1-147b-4055-b146-153e1cf51171 -->
<!-- cubic:review-run=c2af7a72-b97a-5c72-a4f1-d02f4843beed -->
<!-- metadata:{"confidence":9} -->
P1: During a reschedule, the handler starts these asynchronous cancellations without awaiting them. The old SendGrid/Twilio reminder can therefore remain active when the request proceeds or finishes; await all deletion promises before calling `eventManager.reschedule`.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At packages/features/bookings/lib/handleNewBooking.ts, line 966:
<comment>During a reschedule, the handler starts these asynchronous cancellations without awaiting them. The old SendGrid/Twilio reminder can therefore remain active when the request proceeds or finishes; await all deletion promises before calling `eventManager.reschedule`.</comment>
<file context>
@@ -950,6 +961,19 @@ async function handler(req: NextApiRequest & { userId?: number | undefined }) {
if (originalRescheduledBooking?.uid) {
+ try {
+ // cancel workflow reminders from previous rescheduled booking
+ originalRescheduledBooking.workflowReminders.forEach((reminder) => {
+ if (reminder.method === WorkflowMethods.EMAIL) {
+ deleteScheduledEmailReminder(reminder.id, reminder.referenceId, true);
</file context>
```
</details>
```suggestion
await Promise.all(
originalRescheduledBooking.workflowReminders.map((reminder) => {
if (reminder.method === WorkflowMethods.EMAIL) {
return deleteScheduledEmailReminder(reminder.id, reminder.referenceId, true);
} else if (reminder.method === WorkflowMethods.SMS) {
return deleteScheduledSMSReminder(reminder.id, reminder.referenceId);
}
return Promise.resolve();
})
);
```
<!-- cubic:v=5504b1de-dcc4-497c-9d69-35a712a39f76 -->
<!-- cubic:review-run=c2af7a72-b97a-5c72-a4f1-d02f4843beed -->
<!-- metadata:{"confidence":9} -->
P2: When disabling event types, the mutation proceeds without waiting for reminder cancellation, so stale reminders can remain and SMS cancellation can race subsequent workflow updates. Await all cancellation promises before updating relationships or returning from the mutation.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At packages/trpc/server/routers/viewer/workflows.tsx, line 378:
<comment>When disabling event types, the mutation proceeds without waiting for reminder cancellation, so stale reminders can remain and SMS cancellation can race subsequent workflow updates. Await all cancellation promises before updating relationships or returning from the mutation.</comment>
<file context>
@@ -373,29 +372,15 @@ export const workflowsRouter = router({
- deleteScheduledSMSReminder(reminder.referenceId);
- }
+ if (reminder.method === WorkflowMethods.EMAIL) {
+ deleteScheduledEmailReminder(reminder.id, reminder.referenceId);
+ } else if (reminder.method === WorkflowMethods.SMS) {
+ deleteScheduledSMSReminder(reminder.id, reminder.referenceId);
</file context>
```
</details>
<!-- cubic:v=d067378a-97f1-4d2a-b601-2750dcc616fd -->
<!-- cubic:review-run=c2af7a72-b97a-5c72-a4f1-d02f4843beed -->
<!-- metadata:{"confidence":6} -->
P2: When a cancelled non-email `WorkflowReminder` is present, this email-only job sends its provider reference to SendGrid and deletes the reminder. Restrict the query to `method: WorkflowMethods.EMAIL` (and scheduled reminders) before processing it.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At packages/features/ee/workflows/api/scheduleEmailReminders.ts, line 46:
<comment>When a cancelled non-email `WorkflowReminder` is present, this email-only job sends its provider reference to SendGrid and deletes the reminder. Restrict the query to `method: WorkflowMethods.EMAIL` (and scheduled reminders) before processing it.</comment>
<file context>
@@ -39,6 +40,42 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
+ //cancel reminders for cancelled/rescheduled bookings that are scheduled within the next hour
+ const remindersToCancel = await prisma.workflowReminder.findMany({
+ where: {
+ cancelled: true,
+ scheduledDate: {
+ lte: dayjs().add(1, "hour").toISOString(),
</file context>
```
</details>
```suggestion
cancelled: true,
method: WorkflowMethods.EMAIL,
scheduled: true,
```
<!-- cubic:review-summary:start -->
**4 issues found** across 10 files
<!-- cubic:review-summary:end -->
<details>
<summary>Prompt for AI agents (unresolved issues)</summary>
```text
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="packages/trpc/server/routers/viewer/bookings.tsx">
<violation number="1" location="packages/trpc/server/routers/viewer/bookings.tsx:490">
P1: When a booking is rescheduled more than one hour before an email reminder, this call leaves its SendGrid batch active until the scheduler’s cancellation window. Cancel the scheduled email immediately in this reschedule path by passing `true` for `immediateDelete`.</violation>
</file>
<file name="packages/trpc/server/routers/viewer/workflows.tsx">
<violation number="1" location="packages/trpc/server/routers/viewer/workflows.tsx:378">
P2: When disabling event types, the mutation proceeds without waiting for reminder cancellation, so stale reminders can remain and SMS cancellation can race subsequent workflow updates. Await all cancellation promises before updating relationships or returning from the mutation.</violation>
</file>
<file name="packages/features/bookings/lib/handleNewBooking.ts">
<violation number="1" location="packages/features/bookings/lib/handleNewBooking.ts:966">
P1: During a reschedule, the handler starts these asynchronous cancellations without awaiting them. The old SendGrid/Twilio reminder can therefore remain active when the request proceeds or finishes; await all deletion promises before calling `eventManager.reschedule`.</violation>
</file>
<file name="packages/features/ee/workflows/api/scheduleEmailReminders.ts">
<violation number="1" location="packages/features/ee/workflows/api/scheduleEmailReminders.ts:46">
P2: When a cancelled non-email `WorkflowReminder` is present, this email-only job sends its provider reference to SendGrid and deletes the reminder. Restrict the query to `method: WorkflowMethods.EMAIL` (and scheduled reminders) before processing it.</violation>
</file>
```
</details>
<sub>Reply with feedback, questions, or to request a fix.<br /><br />[Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/23/ai_pr_review_github_delivery_6083a01264f1387423fc9e0513c81010df792ec054ceba2084f8b451942b84ed?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F23)</sub>
<!-- cubic:review-post:ai_pr_review_github_delivery_6083a01264f1387423fc9e0513c81010df792ec054ceba2084f8b451942b84ed:ec80914659b1a7eab63cdb93a8e47bd1e8feada9:c2af7a72-b97a-5c72-a4f1-d02f4843beed -->
cursor · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | exact |
| d2 | medium | ✗ | — |
| d3 | medium | ✓ | off by one |
raw comments (3)
### Cron cancel failure blocks remaining reminders
**High Severity**
<!-- DESCRIPTION START -->
The new cancel loop wraps every SendGrid cancel and the follow-up deletes in one `try/catch`. A single failed `POST` (already-cancelled `batch_id`, missing `referenceId`, or the concurrent-cancel cap) skips remaining reminders and never deletes rows already cancelled in that run. The next cron retries those same rows, fails immediately, and the queue stays stuck while cancelled-booking emails still send.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: 4cf22411-3968-4116-90e0-a01053e9f57b -->
<!-- LOCATIONS START
packages/features/ee/workflows/api/scheduleEmailReminders.ts#L52-L77
LOCATIONS END -->
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjhjOWM4NTVjLTU1NjEtNDc3NC04NTQ0LTY1ZTU2MTYyNzY3MiIsImVuY3J5cHRpb25LZXkiOiJNV0prcDBQT3B1TFVfSHBnUkFQT19kSTE3aHpjUzMzQnZ5WXoxdm40ZWxRIiwiYnJhbmNoIjoidDItY2FsLWNvbS03MjMyIiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjhjOWM4NTVjLTU1NjEtNDc3NC04NTQ0LTY1ZTU2MTYyNzY3MiIsImVuY3J5cHRpb25LZXkiOiJNV0prcDBQT3B1TFVfSHBnUkFQT19kSTE3aHpjUzMzQnZ5WXoxdm40ZWxRIiwiYnJhbmNoIjoidDItY2FsLWNvbS03MjMyIiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwck51bWJlciI6MjQsImNvbW1pdFNoYSI6ImZhNzgxZDVmOGIyNjlmOWI0MDI2NGMxZGE1OThjOGFkZDI5MDQ5MmUiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit fa781d5f8b269f9b40264c1da598c8add290492e. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
### Reminder cancellation is not awaited
**Medium Severity**
<!-- DESCRIPTION START -->
Callers now fire `deleteScheduledEmailReminder` and `deleteScheduledSMSReminder` from `forEach` without awaiting them, and they dropped the previously awaited Prisma deletes. The `cancelled` update and SMS row delete can still be in flight when the handler returns, so serverless runtimes may never persist cancellation and the reminder still sends.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: 34024521-2698-4c5e-8659-f561f065fe60 -->
<!-- LOCATIONS START
packages/features/bookings/lib/handleCancelBooking.ts#L483-L493
packages/trpc/server/routers/viewer/bookings.tsx#L486-L494
packages/features/bookings/lib/handleNewBooking.ts#L963-L972
LOCATIONS END -->
<details>
<summary>Additional Locations (2)</summary>
- [`packages/trpc/server/routers/viewer/bookings.tsx#L486-L494`](https://github.com/drape-io/crbench-cursor-2026-09/blob/fa781d5f8b269f9b40264c1da598c8add290492e/packages/trpc/server/routers/viewer/bookings.tsx#L486-L494)
- [`packages/features/bookings/lib/handleNewBooking.ts#L963-L972`](https://github.com/drape-io/crbench-cursor-2026-09/blob/fa781d5f8b269f9b40264c1da598c8add290492e/packages/features/bookings/lib/handleNewBooking.ts#L963-L972)
</details>
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjcwNzdiMWQ2LTQyOWItNGMyZC1hOTg3LWRiY2Y4NTUyMzU3OCIsImVuY3J5cHRpb25LZXkiOiJXZlFIZWlhTXlSZTNKMWpFdklhZWQtM0tzODBhS29BSE1IUEtGLXNjNnRZIiwiYnJhbmNoIjoidDItY2FsLWNvbS03MjMyIiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjcwNzdiMWQ2LTQyOWItNGMyZC1hOTg3LWRiY2Y4NTUyMzU3OCIsImVuY3J5cHRpb25LZXkiOiJXZlFIZWlhTXlSZTNKMWpFdklhZWQtM0tzODBhS29BSE1IUEtGLXNjNnRZIiwiYnJhbmNoIjoidDItY2FsLWNvbS03MjMyIiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwck51bWJlciI6MjQsImNvbW1pdFNoYSI6ImZhNzgxZDVmOGIyNjlmOWI0MDI2NGMxZGE1OThjOGFkZDI5MDQ5MmUiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit fa781d5f8b269f9b40264c1da598c8add290492e. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- BUGBOT_REVIEW -->
Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.
<!-- BUGBOT_FIX_ALL -->
<a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aTpjMzk3NjVlZS03MjE5LTRmY2ItYTA4NC0wNGNkNzg1ZTFkYTIiLCJlbmNyeXB0aW9uS2V5IjoiVkJoazU0N3o3bTEya3R3S0NRNU5aOGdvRWZZeTE0ck5YQjJJbjhBM0tEZyIsImJyYW5jaCI6InQyLWNhbC1jb20tNzIzMiIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>
<!-- /BUGBOT_FIX_ALL -->
<!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_BEGIN -->
<sup>❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_END -->
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit fa781d5f8b269f9b40264c1da598c8add290492e. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
Drape (Deep Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✗ | — |
| d2 | medium | ✗ | — |
| d3 | medium | ✓ | exact |
The immediateDelete branch cancels the SendGrid batch and then returns without deleting the WorkflowReminder row. When the step or workflow is deleted, a cascade removes the row. In the handleNewBooking reschedule path nothing deletes it, so the stale row stays (scheduled=true) until the cron's past-date cleanup removes it. This is real, but the impact is small. [grounded: tree packages/features/ee/workflows/lib/reminders/emailReminderManager.ts] [consensus 3/3: valid=3]
Before this change, cancelling or rescheduling a booking cancelled the SendGrid send immediately. Now the code only sets cancelled=true and relies on the cron to cancel batches due within the next hour. A cancelled booking can still get its reminder if the cron doesn't run in time or isn't configured. [grounded: tree packages/features/ee/workflows/lib/reminders/emailReminderManager.ts] [consensus 3/3: valid=3]
The delete now runs inside the same try block, after twilio.cancelSMS. If the cancel throws, the row is never deleted. Before this change, callers deleted the row regardless (the old deleteMany was pushed unconditionally). [grounded: tree packages/features/ee/workflows/lib/reminders/smsReminderManager.ts] [consensus 3/3: valid=3]
raw comments (4)
**Immediate cancel leaves the reminder row behind**
With immediateDelete, the SendGrid batch is cancelled but the WorkflowReminder row is never deleted. When handleNewBooking reschedules, the old booking keeps the row marked scheduled, and a later workflow edit cancels it a second time. Delete the WorkflowReminder row after the immediate SendGrid cancel.
```
packages/features/ee/workflows/lib/reminders/emailReminderManager.ts:213 if (immediateDelete) {
packages/features/ee/workflows/lib/reminders/emailReminderManager.ts:214 await client.request({
packages/features/ee/workflows/lib/reminders/emailReminderManager.ts:215 url: "/v3/user/scheduled_sends",
packages/features/ee/workflows/lib/reminders/emailReminderManager.ts:216 method: "POST",
packages/features/ee/workflows/lib/reminders/emailReminderManager.ts:217 body: {
packages/features/ee/workflows/lib/reminders/emailReminderManager.ts:218 batch_id: referenceId,
packages/features/ee/workflows/lib/reminders/emailReminderManager.ts:219 status: "cancel",
packages/features/ee/workflows/lib/reminders/emailReminderManager.ts:220 },
packages/features/ee/workflows/lib/reminders/emailReminderManager.ts:221 });
packages/features/ee/workflows/lib/reminders/emailReminderManager.ts:222 return;
```
**One failed cancel stops all later email cancellations**
All cancellations share one try/catch. If one SendGrid cancel fails, for example on a batch that was already cancelled, the loop ends, later reminders stay scheduled, and the queued deletes never run. Put a try/catch around each reminder inside the loop.
```
packages/features/ee/workflows/api/scheduleEmailReminders.ts:53 try {
packages/features/ee/workflows/api/scheduleEmailReminders.ts:54 const workflowRemindersToDelete: Prisma.Prisma__WorkflowReminderClient<WorkflowReminder, never>[] = [];
packages/features/ee/workflows/api/scheduleEmailReminders.ts:56 for (const reminder of remindersToCancel) {
packages/features/ee/workflows/api/scheduleEmailReminders.ts:57 await client.request({
packages/features/ee/workflows/api/scheduleEmailReminders.ts:74 await Promise.all(workflowRemindersToDelete);
packages/features/ee/workflows/api/scheduleEmailReminders.ts:75 } catch (error) {
packages/features/ee/workflows/api/scheduleEmailReminders.ts:76 console.log(`Error cancelling scheduled Emails: ${error}`);
packages/features/ee/workflows/api/scheduleEmailReminders.ts:77 }
```
**Cancelled bookings still receive reminder emails**
`deleteScheduledEmailReminder` now only sets `cancelled: true`, leaving the SendGrid send queued until the 15‑minute cron cancels it. Sends due sooner, or on instances without the cron, still go out. Cancel the SendGrid batch immediately here as well, instead of relying only on the cron.
```
packages/features/ee/workflows/lib/reminders/emailReminderManager.ts:225 await prisma.workflowReminder.update({
packages/features/ee/workflows/lib/reminders/emailReminderManager.ts:226 where: {
packages/features/ee/workflows/lib/reminders/emailReminderManager.ts:227 id: reminderId,
packages/features/ee/workflows/lib/reminders/emailReminderManager.ts:228 },
packages/features/ee/workflows/api/scheduleEmailReminders.ts:34 await prisma.workflowReminder.deleteMany({
packages/features/ee/workflows/api/scheduleEmailReminders.ts:35 where: {
packages/features/ee/workflows/api/scheduleEmailReminders.ts:36 method: WorkflowMethods.EMAIL,
packages/features/ee/workflows/api/scheduleEmailReminders.ts:37 scheduledDate: {
packages/features/ee/workflows/api/scheduleEmailReminders.ts:38 lte: dayjs().toISOString(),
packages/features/ee/workflows/api/scheduleEmailReminders.ts:39 },
```
**SMS reminder rows kept when Twilio cancel fails**
The row is deleted only after `twilio.cancelSMS` succeeds. If Twilio rejects the cancel (for example, the SMS was already sent), the row stays. Before, callers always deleted it. Delete the row even when the Twilio cancel fails (e.g. in a finally).
```
packages/features/ee/workflows/lib/reminders/smsReminderManager.ts:177 export const deleteScheduledSMSReminder = async (reminderId: number, referenceId: string | null) => {
packages/features/ee/workflows/lib/reminders/smsReminderManager.ts:178 try {
packages/features/ee/workflows/lib/reminders/smsReminderManager.ts:179 if (referenceId) {
packages/features/ee/workflows/lib/reminders/smsReminderManager.ts:180 await twilio.cancelSMS(referenceId);
packages/features/ee/workflows/lib/reminders/smsReminderManager.ts:181 }
packages/features/ee/workflows/lib/reminders/smsReminderManager.ts:182 await prisma.workflowReminder.delete({
packages/features/ee/workflows/lib/reminders/smsReminderManager.ts:183 where: {
packages/features/ee/workflows/lib/reminders/smsReminderManager.ts:184 id: reminderId,
packages/features/ee/workflows/lib/reminders/smsReminderManager.ts:185 },
packages/features/ee/workflows/lib/reminders/smsReminderManager.ts:186 });
```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✗ | — |
| d2 | medium | ✗ | — |
| d3 | medium | ✓ | exact |
In the new immediateDelete path the SendGrid call sits inside a try/catch that only logs. If the call fails, `cancelled` is never set, so the cron (which filters on `cancelled: true`) never retries and the reminder is sent. This is a robustness gap in new code; before the change, reschedule didn't cancel the old reminders at all. [grounded: tree packages/features/ee/workflows/lib/reminders/emailReminderManager.ts] [consensus 3/3: valid=3]
After a successful SendGrid cancel, the immediateDelete branch returns without deleting or updating the row, so it stays `scheduled: true` until the cron's past-date deleteMany removes it. SMS rows, by contrast, are deleted at once. The effect is a stale row rather than a wrong send. [grounded: tree packages/features/ee/workflows/lib/reminders/emailReminderManager.ts] [consensus 3/3: valid=3]
The cancel-booking path used to call SendGrid's cancel immediately. Now it only sets `cancelled = true` and waits for the cron. A reminder already queued at SendGrid and due before the next cron run is still sent, which is a regression. [grounded: diff] [consensus 3/3: valid=3]
raw comments (4)
**One failed cancel blocks all later cancellations**
The whole cancel loop sits in one try/catch, and the lazy `prisma.workflowReminder.delete` calls only run at `Promise.all` after it. If one SendGrid cancel throws, the loop aborts and no deletes run. Use a try/catch per reminder and await each delete right after its cancel.
```
packages/features/ee/workflows/api/scheduleEmailReminders.ts:53 try {
packages/features/ee/workflows/api/scheduleEmailReminders.ts:54 const workflowRemindersToDelete: Prisma.Prisma__WorkflowReminderClient<WorkflowReminder, never>[] = [];
packages/features/ee/workflows/api/scheduleEmailReminders.ts:56 for (const reminder of remindersToCancel) {
packages/features/ee/workflows/api/scheduleEmailReminders.ts:57 await client.request({
```
**Failed reschedule cancel still sends old reminder**
When rescheduling, the email reminder path with immediateDelete only calls SendGrid. If that call fails, it is logged and nothing marks the row cancelled, so the cron never retries and the old booking's reminder is sent. Set cancelled=true (or delete the row) when the SendGrid cancel fails.
```
packages/features/bookings/lib/handleNewBooking.ts:964 try {
packages/features/bookings/lib/handleNewBooking.ts:965 // cancel workflow reminders from previous rescheduled booking
packages/features/bookings/lib/handleNewBooking.ts:966 originalRescheduledBooking.workflowReminders.forEach((reminder) => {
packages/features/bookings/lib/handleNewBooking.ts:967 if (reminder.method === WorkflowMethods.EMAIL) {
```
**Rescheduled email reminder rows stay scheduled**
When rescheduling, deleteScheduledEmailReminder with immediateDelete cancels at SendGrid but leaves the old booking's row as scheduled:true until the cron deletes it after scheduledDate. SMS rows are deleted instead. Delete the row after a successful SendGrid cancel.
```
packages/features/ee/workflows/lib/reminders/emailReminderManager.ts:197 export const deleteScheduledEmailReminder = async (
packages/features/ee/workflows/lib/reminders/emailReminderManager.ts:198 reminderId: number,
packages/features/ee/workflows/lib/reminders/emailReminderManager.ts:199 referenceId: string | null,
packages/features/ee/workflows/lib/reminders/emailReminderManager.ts:200 immediateDelete?: boolean
```
**Cancelled booking still gets imminent reminder email**
Cancelling a booking now only sets cancelled=true, and SendGrid is told later by a cron that runs about every 15 minutes. A reminder queued at SendGrid and due before the next run is still sent. Cancel at SendGrid immediately when the reminder is due soon.
```
packages/features/ee/workflows/lib/reminders/emailReminderManager.ts:197 export const deleteScheduledEmailReminder = async (
packages/features/ee/workflows/lib/reminders/emailReminderManager.ts:198 reminderId: number,
packages/features/ee/workflows/lib/reminders/emailReminderManager.ts:199 referenceId: string | null,
packages/features/ee/workflows/lib/reminders/emailReminderManager.ts:200 immediateDelete?: boolean
```
greptile · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | off by one |
| d2 | medium | ✗ | — |
| d3 | medium | ✓ | off by one |
Before this change, deleteScheduledEmailReminder cancelled the send in SendGrid right away. Now cancel and reschedule paths without immediateDelete only set cancelled=true. The cron that acts on that flag runs every 15 minutes (cron-scheduleEmailReminders.yml: "0,15,30,45 * * * *"). A reminder due within the gap before the next run is still sent, and the cron then just deletes it from the DB because its scheduledDate has passed. [grounded: tree packages/features/ee/workflows/lib/reminders/emailReminderManager.ts] [consensus 3/3: valid=3]
The sender-ID editor was never inside this container. In the old code the container held only the `isPhoneNumberNeeded &&` phone section. The sender ID is rendered in a separate div guarded by isSenderIdNeeded, so SMS_ATTENDEE steps still show it. The change only removes an empty gray box. [invalid: contradiction] [consensus 3/3: invalid=3]
raw comments (5)
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Cancellation can arrive late**
This path only marks the reminder as cancelled and relies on a cron that runs every 15 minutes to contact SendGrid. If a booking is cancelled or rescheduled shortly before its reminder is due, the scheduled email can be sent before the cron processes the marker, so attendees may receive a reminder for a cancelled booking.
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Cancellation promises are discarded**
These reminder-manager calls are not awaited, unlike the previous database deletions. The request can finish, or later booking and workflow mutations can proceed, before reminders are marked, deleted, or cancelled. This can leave scheduled notifications active even though the cancellation or reschedule operation reported success. The same unawaited pattern also appears in the new-booking reschedule flow and the booking and workflow routers.
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Attendee sender field disappears**
`SMS_ATTENDEE` needs a sender ID but does not need a custom phone number. Guarding this whole section only with `isPhoneNumberNeeded` therefore hides the sender-ID editor for attendee SMS steps. Users can no longer inspect or correct a stale or invalid sender value used by those workflows.
```suggestion
{(isPhoneNumberNeeded || isSenderIdNeeded) && (
```
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **One failure blocks cleanup**
A SendGrid cancellation error exits the entire loop before later reminders are processed and before any accumulated database deletions run. Because the failed row remains eligible for the next run, a persistent provider error can repeatedly block unrelated cancelled reminders until their scheduled emails are sent.
<h3>Greptile Summary</h3>
This PR changes workflow-reminder cancellation from immediate row deletion to provider-aware cancellation, adds deferred email cleanup through the reminder scheduler, and adjusts SMS workflow configuration UI.
- Adds a nullable cancellation marker to `WorkflowReminder`.
- Defers ordinary SendGrid cancellation to the email-reminder cron while retaining immediate cancellation for selected workflow operations.
- Moves SMS cancellation and reminder deletion into the reminder manager.
- Cancels reminders when bookings are rescheduled and when workflows or workflow steps change.
- Restructures the phone-number and sender-ID controls in the workflow step editor.
<h3>Confidence Score: 1/5</h3>
The PR is not safe to merge because cancelled reminders can still be delivered, cancellation work is not awaited, attendee SMS sender configuration disappears, and one provider error can block an entire cleanup batch.
Deferred email cancellation introduces a cron-sized delivery window, while discarded manager promises remove request-level completion guarantees. The workflow editor also hides a required operational control for attendee SMS steps, and batch-level error handling allows one failed SendGrid cancellation to prevent unrelated reminders from being cancelled.
**Files Needing Attention:** packages/features/ee/workflows/lib/reminders/emailReminderManager.ts, packages/features/ee/workflows/api/scheduleEmailReminders.ts, packages/features/ee/workflows/components/WorkflowStepContainer.tsx, packages/features/bookings/lib/handleCancelBooking.ts, packages/features/bookings/lib/handleNewBooking.ts, packages/trpc/server/routers/viewer/bookings.tsx, packages/trpc/server/routers/viewer/workflows.tsx
<details><summary><h3>Important Files Changed</h3></summary>
| Filename | Overview |
|----------|----------|
| packages/features/ee/workflows/lib/reminders/emailReminderManager.ts | Replaces immediate SendGrid cancellation with a deferred database marker, introducing a delivery window before cron processing. |
| packages/features/ee/workflows/api/scheduleEmailReminders.ts | Adds cron-based cancellation, but one provider failure aborts cleanup for the entire batch. |
| packages/features/ee/workflows/components/WorkflowStepContainer.tsx | Restructures SMS controls while unintentionally hiding sender-ID configuration for attendee SMS actions. |
| packages/features/bookings/lib/handleCancelBooking.ts | Delegates reminder cleanup to asynchronous managers without awaiting their completion. |
| packages/features/bookings/lib/handleNewBooking.ts | Adds reminder cancellation for rescheduled bookings, but launches that cancellation without awaiting it. |
| packages/trpc/server/routers/viewer/bookings.tsx | Replaces awaited reminder-row deletion with unawaited manager calls during rescheduling. |
| packages/trpc/server/routers/viewer/workflows.tsx | Routes workflow and step cleanup through reminder managers without preserving completion ordering. |
| packages/features/ee/workflows/lib/reminders/smsReminderManager.ts | Extends SMS cancellation to delete its reminder row, requiring callers to await the resulting provider and database work. |
| packages/prisma/schema.prisma | Adds the nullable cancellation marker used by deferred email cleanup. |
| packages/prisma/migrations/20230217230604_add_cancelled_to_workflow_reminder/migration.sql | Adds the corresponding nullable database column without affecting existing reminder interpretation. |
</details>
<details open><summary><h3>Sequence Diagram</h3></summary>
```mermaid
sequenceDiagram
participant Request as Booking/workflow request
participant DB as WorkflowReminder
participant Cron as Email reminder cron
participant SG as SendGrid
Request->>DB: "Set cancelled=true"
Request-->>Request: Returns without awaiting manager
Note over DB,Cron: Cancellation waits up to the next cron run
Cron->>DB: Select cancelled reminders due within 1 hour
loop Sequential reminders
Cron->>SG: Cancel scheduled batch
SG-->>Cron: Success or error
end
Cron->>DB: Delete rows only if entire loop completes
```
</details>
<!-- greptile_other_comments_section -->
<sub>Reviews (1): Last reviewed commit: ["Update packages/features/bookings/lib/ha..."](https://github.com/drape-io/crbench-greptile-2026-09/commit/ebf97c6364dcbaa48bfb20a9f0724f723a165037) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=64284282)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✗ | — |
| d2 | medium | ✗ | — |
| d3 | medium | ✓ | exact |
The new loop awaits each SendGrid cancel inside a single try. If one request throws, the remaining reminders are skipped, and because Prisma queries are lazy, the queued deletes never run. [grounded: tree packages/features/ee/workflows/api/scheduleEmailReminders.ts] [consensus 3/3: valid=3]
Booking cancellation now only sets `cancelled: true`, and the actual SendGrid cancel waits for the 15-minute cron. That cron first runs a deleteMany on reminders past their scheduledDate without cancelling them. So reminders cancelled close to their send time can still go out, which is a regression from the old immediate cancel. [grounded: tree packages/features/ee/workflows/lib/reminders/emailReminderManager.ts] [consensus 3/3: valid=3]
requestReschedule and handleCancelBooking no longer pass immediateDelete, so the cancel waits for the cron, which runs every 15 minutes. A reminder due before the next cron run can still be sent. [grounded: diff] [consensus 3/3: valid=3]
raw comments (4)
[P2] One failed SendGrid cancel stops the cron from cancelling any other reminder
The whole cancellation loop sits inside one `try`, and each `client.request` is awaited in sequence. If one cancel request throws (for example a bad or stale batch id, or a SendGrid 4xx), every later reminder in `remindersToCancel` is skipped. The DB deletes queued in `workflowRemindersToDelete` never run either, because Prisma promises are lazy and `Promise.all` is never reached. The failing reminder keeps matching the `cancelled: true` / next-hour query on each run until its time passes. Until then, every 15-minute run hits the same error, and other cancelled bookings' emails may not be cancelled and get sent. Each reminder needs its own error handling.
[P2] Deferring the cancel to the cron lets near-term reminders still be sent
Booking cancellation, reschedule via `requestReschedule`, event-type deactivation and step edits now only set `cancelled: true` instead of cancelling the SendGrid batch right away. The cron runs every 15 minutes (`.github/workflows/cron-scheduleEmailReminders.yml`), and its first step deletes every EMAIL reminder whose `scheduledDate ‹= now` without cancelling it. So if a booking is cancelled roughly 15–25 minutes before its reminder's send time, the cancel can come too late or never happen: no cron run picks the reminder up before it sends, or the `deleteMany` removes the row first. The attendee then gets a reminder for a cancelled booking. The old code cancelled immediately, so this is a regression for cancellations made close to the send time; for example, reminders due within the next hour could still be cancelled immediately.
[P2] One failed SendGrid cancel stops all remaining cancellations in the cron run
A single `try` wraps the whole `for` loop. If `client.request` throws for any cancelled reminder (for example an invalid or expired batch id, or a SendGrid rate-limit or 4xx response), the loop stops. Every later reminder in `remindersToCancel` is then left un-cancelled at SendGrid. The lazy Prisma `delete` promises collected so far are never awaited, so the batches that were already cancelled keep their rows and get re-POSTed on the next run. The same failing reminder is also retried every 15 minutes until its send time passes, and it can block the others each time. Because cancellation now happens only in this cron, those other reminders' emails get sent for bookings that were cancelled or rescheduled. Each reminder needs its own error handling, and each delete should only depend on its own cancel request succeeding.
[P2] Waiting for the cron to cancel lets reminders due soon still be sent
Booking cancellation (handleCancelBooking), requestReschedule (bookings.tsx), turning off an event type and editing a step now only set `cancelled: true`. The SendGrid batch is cancelled later by the cron, which runs every 15 minutes (`0,15,30,45`). Before this change, the cancel request went to SendGrid right away. Now, if a booking is cancelled shortly before an email reminder's `scheduledDate` (for example 5–15 minutes before a BEFORE_EVENT reminder), the email can go out before the next cron run cancels it. The attendee or host then gets a reminder for a cancelled booking. Reminders due within roughly the cron interval still need to be cancelled immediately.
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | exact |
| d2 | medium | ✗ | — |
| d3 | medium | ✓ | exact |
With immediateDelete the function cancels the SendGrid batch and returns without deleting the row. On the reschedule path in handleNewBooking, the old booking still exists, so its reminder rows stay until the cron job deletes rows whose date has passed. In the workflow-delete and step-delete paths, cascade deletes remove the rows anyway. [grounded: tree packages/features/ee/workflows/lib/reminders/emailReminderManager.ts] [consensus 3/3: valid=3]
The row delete now sits after cancelSMS in the same try, so a Twilio error skips it. The removed caller code used to delete the row unconditionally. [grounded: tree packages/features/ee/workflows/lib/reminders/smsReminderManager.ts] [consensus 3/3: valid=3]
Prisma promises are lazy, so the queued deletes only run at the Promise.all after the loop. If any client.request in the loop throws, control jumps to the catch and none of the queued deletes run, including those for reminders already cancelled. [grounded: tree packages/features/ee/workflows/api/scheduleEmailReminders.ts] [consensus 3/3: valid=3]
raw comments (5)
[P2] Fire-and-forget reminder cancellation now carries the DB update
The reminder DB deletes used to be collected and awaited, and now they run inside un-awaited `deleteScheduledEmailReminder` / `deleteScheduledSMSReminder` calls. Those calls now do the `workflowReminder.update({cancelled: true})` or `delete`, and nothing awaits them. The same pattern appears in `packages/trpc/server/routers/viewer/bookings.tsx` (about line 487) and in several places in `packages/trpc/server/routers/viewer/workflows.tsx`. In a serverless runtime, the handler can return before the promise runs. The reminder row is then never marked cancelled or deleted, so the email or SMS reminder still goes out for a cancelled or rescheduled booking. The old code at least awaited the DB cleanup. The returned promises should be collected and awaited, for example in the existing `Promise.all`.
[P2] Cron cancel loop can stall permanently on one failing reminder
All SendGrid cancel calls and the delete queries share one `try` block, and the `delete` calls are lazy Prisma promises that only run at `Promise.all` after the loop. The query selects every `cancelled: true` reminder with `scheduledDate ‹= now+1h`, including ones whose date has already passed. If the SendGrid cancel call throws for one of them (for example a batch that has already been sent or is invalid), the loop aborts. None of the queued deletes run, including those for reminders already cancelled earlier in the loop. The failing row is never removed, so it is retried first on every cron run and blocks every reminder after it from being cancelled. Cancelled reminders can then still be sent. Each reminder should be handled in its own try/catch, and its row deleted right after its cancel call.
[P3] Immediate email delete leaves the DB row behind
With `immediateDelete`, the function cancels the SendGrid batch and returns without deleting or marking the `WorkflowReminder` row. The reschedule path in `handleNewBooking.ts` calls it this way, and nothing else removes those rows. The old booking is not deleted, so a `scheduled: true` row with a stale `referenceId` stays attached to it. The SMS variant does delete its row, so the two behave differently.
[P3] SMS reminder row is no longer removed when Twilio cancel fails
`prisma.workflowReminder.delete` now sits after `twilio.cancelSMS` inside the same `try`. If Twilio throws, the row is skipped and left behind with no `cancelled` flag and no retry. The old callers always deleted the row regardless of the Twilio result.
[P2] One failed SendGrid cancel blocks all other cancellations and DB cleanup
The loop awaits `client.request` for each cancelled reminder and only queues the `prisma.workflowReminder.delete` calls. The queued deletes run later, in `Promise.all` after the loop, and Prisma queries only execute once awaited. If any one cancel request throws, for example a batch that can no longer be cancelled because it is within 10 minutes of its send time, the loop jumps to the catch. None of the queued deletes run, including those for reminders already cancelled at SendGrid. The next cron run fetches the same rows again, tries to cancel them again, and likely hits the same failing reminder, so the rows are never cleaned up. Only the unconditional deletion of rows whose `scheduledDate` has passed eventually removes them. Handling each reminder in its own try/catch and deleting the row right after its cancel succeeds would avoid this
qodo · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | exact |
| d2 | medium | ✗ | — |
| d3 | medium | ✓ | off by one |
The new immediateDelete branch cancels the SendGrid batch and returns without deleting or marking the WorkflowReminder row. On reschedule, handleNewBooking calls this branch, so the old booking's row stays stored as scheduled and not cancelled. Nothing in the shown code deletes it, and steps or workflows are not deleted in that path, so cascade deletes don't help. The cron job only removes it once its scheduledDate has passed. The effect is mainly stale data. [grounded: tree packages/features/ee/workflows/lib/reminders/emailReminderManager.ts] [consensus 3/3: valid=3]
raw comments (5)
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
1\. One error leaves later emails queued <code>🐞 Bug</code> <code>☼ Reliability</code>
<pre>
The cancellation sweep wraps the entire serial loop in one <b><i>try</i></b>, so a rejected SendGrid request
skips every later reminder and also bypasses deletion of reminders already cancelled successfully.
When any eligible batch fails to cancel, subsequent cancelled emails remain queued for at least
another cron run and a repeatedly failing row can keep blocking those behind it.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
A single SendGrid error aborts the whole cancellation loop and prevents both later cancellations and cleanup of earlier successful cancellations.
## Fix Focus Areas
- packages/features/ee/workflows/api/scheduleEmailReminders.ts[53-77]
## Recommended Fix
Handle each reminder independently with a per-reminder `try` block or `Promise.allSettled`. Delete each database row only after its provider cancellation succeeds, while recording failures and continuing to process all remaining reminders.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
2\. Rescheduled bookings retain old reminders <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
<b><i>deleteScheduledEmailReminder</i></b> returns after cancelling the SendGrid batch in its <b><i>immediateDelete</i></b>
branch without deleting, marking, or otherwise completing the lifecycle of the corresponding
<b><i>WorkflowReminder</i></b> row. <b><i>handleNewBooking</i></b> uses this branch for the previous booking during a
reschedule and retains that booking as the new booking’s <b><i>fromReschedule</i></b> target, so the reminder
remains stored as scheduled and uncancelled until scheduled-date cleanup eventually removes it.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
The immediate email-cancellation path cancels the provider-side SendGrid batch and returns without removing or marking the corresponding local `WorkflowReminder` record. This path is used when a booking is rescheduled, while the previous booking remains in the database, leaving an obsolete reminder stored as scheduled until later cleanup.
## Fix Focus Areas
- packages/features/ee/workflows/lib/reminders/emailReminderManager.ts[213-223]
- packages/features/bookings/lib/handleNewBooking.ts[963-980]
## Recommended Fix
After SendGrid confirms an immediate cancellation, complete the local reminder lifecycle before returning. Prefer removing the `WorkflowReminder` row with an idempotent `deleteMany` operation, or consistently persist an explicit terminal cancellation state, and await this cleanup so the reschedule does not proceed while retaining an obsolete scheduled reminder.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
3\. Cancelled bookings report success too early <code>🐞 Bug</code> <code>☼ Reliability</code>
<pre>
<b><i>handler</i></b> and the related rescheduling and workflow-edit paths invoke <b><i>deleteScheduledEmailReminder</i></b>
and <b><i>deleteScheduledSMSReminder</i></b> from synchronous <b><i>forEach</i></b> callbacks without collecting or awaiting
their promises. When the surrounding operation returns or continues first, provider cancellation and
the local Prisma <b><i>cancelled</i></b> write can remain incomplete, scheduled notifications can stay active,
and asynchronous failures bypass the reschedule path's <b><i>try</i></b> block.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
Reminder cancellation functions perform asynchronous provider and Prisma operations, but the changed cancellation, rescheduling, and workflow-edit callers invoke them without awaiting or collecting the returned promises. The parent operation can therefore finish before reminder cancellation completes, and failures may not be propagated or handled.
## Fix Focus Areas
- packages/features/bookings/lib/handleCancelBooking.ts[484-497]
- packages/features/bookings/lib/handleNewBooking.ts[963-975]
- packages/trpc/server/routers/viewer/bookings.tsx[487-494]
- packages/trpc/server/routers/viewer/workflows.tsx[211-218]
- packages/trpc/server/routers/viewer/workflows.tsx[375-382]
- packages/trpc/server/routers/viewer/workflows.tsx[517-524]
- packages/trpc/server/routers/viewer/workflows.tsx[573-580]
## Recommended Fix
Replace synchronous `forEach` fire-and-forget calls with promise-producing `map` calls or awaited loops, then wait for the resulting cancellation operations with `Promise.all` or `Promise.allSettled` before continuing or returning. Propagate failures or handle them explicitly, retaining deliberate error handling where reminder-cancellation failures should not abort the parent operation rather than relying on a `try` block around unawaited calls.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<h3>PR Summary by Qodo</h3>
Improve workflow reminder cancellation across booking lifecycles
<code>🐞 Bug fix</code> <code>🕐 40+ Minutes</code>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<details>
<summary>AI Description</summary>
<dl>
<dd>
<br/>
><pre>
>• Defers SendGrid reminder cancellation until delivery approaches, preserving cancellation state in
> Prisma.
>• Cancels reminders across booking cancellation, rescheduling, and workflow lifecycle changes.
>• Shows phone verification controls only for steps requiring custom recipient numbers.
></pre>
</dd>
</dl>
</details>
<details>
<summary>Diagram</summary>
<dl>
<dd>
<br/>
```mermaid
graph TD
A["Booking lifecycle"] --> B["Reminder managers"] --> C[("Workflow reminders")]
D["Workflow changes"] --> B
B --> E["Twilio"]
C --> F["Email cron"] --> G["SendGrid"]
B --> G
```
</dd>
</dl>
</details>
<details>
<summary>High-Level Assessment</summary>
<dl>
<dd>
<br/>
>The following are alternative approaches to this PR:
<details>
<summary><b>1. Dedicated cancellation job queue</b></summary>
<dl>
<dd>
- ➕ Separates cancellation retries from the email scheduling endpoint
- ➕ Provides explicit retry, observability, and dead-letter handling
- ➕ Can apply consistent semantics across SendGrid and Twilio
- ➖ Requires additional queue infrastructure and worker ownership
- ➖ Adds operational complexity for a narrowly scoped lifecycle fix
- ➖ Needs idempotency and migration handling for existing reminders
</dd>
</dl>
</details>
>**Recommendation:** The PR's persisted cancellation flag and cron-based cleanup are a pragmatic fit for the existing reminder scheduler and avoid new infrastructure. A dedicated cancellation queue would be preferable if reminder volume, retry requirements, or provider diversity grows; tests should be added around deferred email cancellation, immediate cancellation, null references, and rescheduling.
</dd>
</dl>
</details>
<details>
<summary> Files changed (10) <code> +241 / -203 </code> </summary>
<dl>
<dd>
<br/>
<details>
<summary>Bug fix (8) <code> +238 / -203 </code></summary>
<dl>
<dd>
<details>
<summary>handleCancelBooking.ts<code>Delegate cancelled-booking reminder cleanup to provider managers</code> <code>+6/-19</code></summary>
<br/>
>Delegate cancelled-booking reminder cleanup to provider managers
>
><pre>
>• Cancels every associated email or SMS workflow reminder through its provider manager, including unscheduled reminders without reference IDs. Removes direct reminder deletion so each manager controls persistence semantics.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/23/files#diff-87a46901f0685bc1affbfaab91860fb47aaf0f689c17bd379a56d8a9aaa51716'>packages/features/bookings/lib/handleCancelBooking.ts</a>
</details>
<details>
<summary>handleNewBooking.ts<code>Cancel reminders from the original rescheduled booking</code> <code>+26/-2</code></summary>
<br/>
>Cancel reminders from the original rescheduled booking
>
><pre>
>• Loads workflow reminders with the original booking and cancels them before completing a reschedule. Email reminders use immediate provider cancellation, while SMS reminders use the centralized SMS manager.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/23/files#diff-a7c21727d9a0d4d1aaff9d24fca9293bc28468861bc8022dfa03116908b6fae7'>packages/features/bookings/lib/handleNewBooking.ts</a>
</details>
<details>
<summary>scheduleEmailReminders.ts<code>Process deferred SendGrid cancellations in the email cron</code> <code>+37/-0</code></summary>
<br/>
>Process deferred SendGrid cancellations in the email cron
>
><pre>
>• Finds cancelled reminders approaching their scheduled time, cancels their SendGrid batches, and deletes successfully processed records. Existing scheduling then continues for unscheduled email reminders.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/23/files#diff-4a6863137d67b960b1965946faaa227ff662cfbbd5f3b4a5dfe372d1a2911c32'>packages/features/ee/workflows/api/scheduleEmailReminders.ts</a>
</details>
<details>
<summary>WorkflowStepContainer.tsx<code>Restrict phone verification UI to number-recipient steps</code> <code>+60/-66</code></summary>
<br/>
>Restrict phone verification UI to number-recipient steps
>
><pre>
>• Renders the custom phone number and verification controls only when a phone number is required. This avoids displaying an empty container for steps that require only a sender ID.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/23/files#diff-ba9f500e239dbe541cbecf8691c1a19301dcf9b5c25c4844620a5fd873e56815'>packages/features/ee/workflows/components/WorkflowStepContainer.tsx</a>
</details>
<details>
<summary>emailReminderManager.ts<code>Support persisted and immediate email cancellation modes</code> <code>+33/-12</code></summary>
<br/>
>Support persisted and immediate email cancellation modes
>
><pre>
>• Changes email cancellation to accept the reminder record ID and nullable provider reference. Unscheduled records are deleted, immediate cancellations call SendGrid directly, and deferred cancellations mark the record as cancelled for cron processing.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/23/files#diff-675b1da8590d6cdd4d5e3d50ada134c6cbdf4ec2893b991247595df3b95c9617'>packages/features/ee/workflows/lib/reminders/emailReminderManager.ts</a>
</details>
<details>
<summary>smsReminderManager.ts<code>Centralize SMS cancellation and reminder deletion</code> <code>+9/-2</code></summary>
<br/>
>Centralize SMS cancellation and reminder deletion
>
><pre>
>• Accepts the reminder ID alongside an optional Twilio reference. It cancels scheduled SMS messages when possible and removes the database record in the same manager.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/23/files#diff-acb11ce116d641d0a2d490f510cb5ba36139a06587576f68c31555ef08bd8814'>packages/features/ee/workflows/lib/reminders/smsReminderManager.ts</a>
</details>
<details>
<summary>bookings.tsx<code>Use reminder managers during booking rescheduling</code> <code>+6/-19</code></summary>
<br/>
>Use reminder managers during booking rescheduling
>
><pre>
>• Routes previous-booking email and SMS reminder cancellation through the updated managers. Removes duplicate direct Prisma deletion logic from the booking router.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/23/files#diff-1f41e2e253ba5e8709f8acc2db09d5ed70727be132f7c63d5ad6af734013cac8'>packages/trpc/server/routers/viewer/bookings.tsx</a>
</details>
<details>
<summary>workflows.tsx<code>Apply centralized cancellation across workflow mutations</code> <code>+61/-83</code></summary>
<br/>
>Apply centralized cancellation across workflow mutations
>
><pre>
>• Uses provider managers when workflows, event-type associations, or workflow steps are deleted or edited. Selects immediate email cancellation where records are removed through workflow cascades and deferred cancellation where reminders remain persisted.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/23/files#diff-6a506e7c97abcd5e4cc65683c3dfaaf14d7f983cfb807b94072980c69833d729'>packages/trpc/server/routers/viewer/workflows.tsx</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Other (2) <code> +3 / -0 </code></summary>
<dl>
<dd>
<details>
<summary>migration.sql<code>Add workflow reminder cancellation state</code> <code>+2/-0</code></summary>
<br/>
>Add workflow reminder cancellation state
>
><pre>
>• Adds a nullable cancelled boolean column to the WorkflowReminder table for deferred email cancellation.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/23/files#diff-64f7158e125741555f9dd38145c39c35b63983d415e6f3237b1b4369b0eb5c6a'>packages/prisma/migrations/20230217230604_add_cancelled_to_workflow_reminder/migration.sql</a>
</details>
<details>
<summary>schema.prisma<code>Model deferred workflow reminder cancellation</code> <code>+1/-0</code></summary>
<br/>
>Model deferred workflow reminder cancellation
>
><pre>
>• Adds the nullable cancelled field to the WorkflowReminder Prisma model, enabling lifecycle handlers and the email cron to coordinate cancellation.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/23/files#diff-56fa4d384ba6fb94b130e9eb42c5cad00734b025ebd6c197f76873469725ae87'>packages/prisma/schema.prisma</a>
</details>
</dd>
</dl>
</details>
</dd>
</dl>
</details>
<h3>Code Review by Qodo</h3>
<code>🐞 Bugs (3)</code> <code>📘 Rule violations (0)</code> <code>📜 Skill insights (0)</code>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<br/>
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
<details>
<summary> 1. One error leaves later emails queued <code>🐞 Bug</code> <code>☼ Reliability</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
>The cancellation sweep wraps the entire serial loop in one <b><i>try</i></b>, so a rejected SendGrid request
>skips every later reminder and also bypasses deletion of reminders already cancelled successfully.
>When any eligible batch fails to cancel, subsequent cancelled emails remain queued for at least
>another cron run and a repeatedly failing row can keep blocking those behind it.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[packages/features/ee/workflows/api/scheduleEmailReminders.ts[R56-57]](https://github.com/drape-io/crbench-qodo-2026-09/pull/23/files#diff-4a6863137d67b960b1965946faaa227ff662cfbbd5f3b4a5dfe372d1a2911c32R56-R57)</code>
>
>```diff
>+ for (const reminder of remindersToCancel) {
>+ await client.request({
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>Each provider request is awaited before the reminder is added to the deletion list, but the only
>catch surrounds the complete loop and <b><i>Promise.all</i></b>. Therefore, one rejection exits the loop and
>skips both later provider requests and the queued database deletions; failed rows remain eligible in
>future sweeps.
></pre>
>
> <code>[packages/features/ee/workflows/api/scheduleEmailReminders.ts[43-77]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4b13cb4cf3764b8d078a0120525e3bf3487178eb/packages/features/ee/workflows/api/scheduleEmailReminders.ts/#L43-L77)</code>
> <code>[packages/features/ee/workflows/lib/reminders/emailReminderManager.ts[225-231]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4b13cb4cf3764b8d078a0120525e3bf3487178eb/packages/features/ee/workflows/lib/reminders/emailReminderManager.ts/#L225-L231)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>A single SendGrid error aborts the whole cancellation loop and prevents both later cancellations and cleanup of earlier successful cancellations.
>
>## Fix Focus Areas
>- packages/features/ee/workflows/api/scheduleEmailReminders.ts[53-77]
>
>## Recommended Fix
>Handle each reminder independently with a per-reminder `try` block or `Promise.allSettled`. Delete each database row only after its provider cancellation succeeds, while recording failures and continuing to process all remaining reminders.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<br/>
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
<details>
<summary> 2. Rescheduled bookings retain old reminders <code>🐞 Bug</code> <code>≡ Correctness</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
><b><i>deleteScheduledEmailReminder</i></b> returns after cancelling the SendGrid batch in its <b><i>immediateDelete</i></b>
>branch without deleting, marking, or otherwise completing the lifecycle of the corresponding
><b><i>WorkflowReminder</i></b> row. <b><i>handleNewBooking</i></b> uses this branch for the previous booking during a
>reschedule and retains that booking as the new booking’s <b><i>fromReschedule</i></b> target, so the reminder
>remains stored as scheduled and uncancelled until scheduled-date cleanup eventually removes it.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[packages/features/ee/workflows/lib/reminders/emailReminderManager.ts[R213-222]](https://github.com/drape-io/crbench-qodo-2026-09/pull/23/files#diff-675b1da8590d6cdd4d5e3d50ada134c6cbdf4ec2893b991247595df3b95c9617R213-R222)</code>
>
>```diff
>+ if (immediateDelete) {
>+ await client.request({
>+ url: "/v3/user/scheduled_sends",
>+ method: "POST",
>+ body: {
>+ batch_id: referenceId,
>+ status: "cancel",
>+ },
>+ });
>+ return;
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>The rescheduling caller in <b><i>handleNewBooking</i></b> explicitly passes <b><i>true</i></b> for immediate deletion while
>preserving a reference to the original booking. In <b><i>deleteScheduledEmailReminder</i></b>, that branch
>returns directly after the provider request without a Prisma mutation; the only database deletion is
>in a separate null-reference branch, and cron cleanup does not remove the uncancelled future row
>until its scheduled date passes.
></pre>
>
> <code>[packages/features/ee/workflows/lib/reminders/emailReminderManager.ts[197-235]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4b13cb4cf3764b8d078a0120525e3bf3487178eb/packages/features/ee/workflows/lib/reminders/emailReminderManager.ts/#L197-L235)</code>
> <code>[packages/features/bookings/lib/handleNewBooking.ts[848-850]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4b13cb4cf3764b8d078a0120525e3bf3487178eb/packages/features/bookings/lib/handleNewBooking.ts/#L848-L850)</code>
> <code>[packages/features/bookings/lib/handleNewBooking.ts[963-980]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4b13cb4cf3764b8d078a0120525e3bf3487178eb/packages/features/bookings/lib/handleNewBooking.ts/#L963-L980)</code>
> <code>[packages/prisma/schema.prisma[634-645]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4b13cb4cf3764b8d078a0120525e3bf3487178eb/packages/prisma/schema.prisma/#L634-L645)</code>
> <code>[packages/features/bookings/lib/handleNewBooking.ts[963-972]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4b13cb4cf3764b8d078a0120525e3bf3487178eb/packages/features/bookings/lib/handleNewBooking.ts/#L963-L972)</code>
> <code>[packages/features/ee/workflows/lib/reminders/emailReminderManager.ts[203-231]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4b13cb4cf3764b8d078a0120525e3bf3487178eb/packages/features/ee/workflows/lib/reminders/emailReminderManager.ts/#L203-L231)</code>
> <code>[packages/features/ee/workflows/api/scheduleEmailReminders.ts[33-51]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4b13cb4cf3764b8d078a0120525e3bf3487178eb/packages/features/ee/workflows/api/scheduleEmailReminders.ts/#L33-L51)</code>
> <code>[packages/prisma/schema.prisma[634-644]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4b13cb4cf3764b8d078a0120525e3bf3487178eb/packages/prisma/schema.prisma/#L634-L644)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>The immediate email-cancellation path cancels the provider-side SendGrid batch and returns without removing or marking the corresponding local `WorkflowReminder` record. This path is used when a booking is rescheduled, while the previous booking remains in the database, leaving an obsolete reminder stored as scheduled until later cleanup.
>
>## Fix Focus Areas
>- packages/features/ee/workflows/lib/reminders/emailReminderManager.ts[213-223]
>- packages/features/bookings/lib/handleNewBooking.ts[963-980]
>
>## Recommended Fix
>After SendGrid confirms an immediate cancellation, complete the local reminder lifecycle before returning. Prefer removing the `WorkflowReminder` row with an idempotent `deleteMany` operation, or consistently persist an explicit terminal cancellation state, and await this cleanup so the reschedule does not proceed while retaining an obsolete scheduled reminder.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<details>
<summary> 3. Cancelled bookings report success too early <code>🐞 Bug</code> <code>☼ Reliability</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
><b><i>handler</i></b> and the related rescheduling and workflow-edit paths invoke <b><i>deleteScheduledEmailReminder</i></b>
>and <b><i>deleteScheduledSMSReminder</i></b> from synchronous <b><i>forEach</i></b> callbacks without collecting or awaiting
>their promises. When the surrounding operation returns or continues first, provider cancellation and
>the local Prisma <b><i>cancelled</i></b> write can remain incomplete, scheduled notifications can stay active,
>and asynchronous failures bypass the reschedule path's <b><i>try</i></b> block.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[packages/features/bookings/lib/handleCancelBooking.ts[R486-491]](https://github.com/drape-io/crbench-qodo-2026-09/pull/23/files#diff-87a46901f0685bc1affbfaab91860fb47aaf0f689c17bd379a56d8a9aaa51716R486-R491)</code>
>
>```diff
> booking.workflowReminders.forEach((reminder) => {
>- if (reminder.scheduled && reminder.referenceId) {
>- if (reminder.method === WorkflowMethods.EMAIL) {
>- deleteScheduledEmailReminder(reminder.referenceId);
>- } else if (reminder.method === WorkflowMethods.SMS) {
>- deleteScheduledSMSReminder(reminder.referenceId);
>- }
>+ if (reminder.method === WorkflowMethods.EMAIL) {
>+ deleteScheduledEmailReminder(reminder.id, reminder.referenceId);
>+ } else if (reminder.method === WorkflowMethods.SMS) {
>+ deleteScheduledSMSReminder(reminder.id, reminder.referenceId);
> }
>- const reminderToDelete = prisma.workflowReminder.deleteMany({
>- where: {
>- id: reminder.id,
>- },
>- });
>- remindersToDelete.push(reminderToDelete);
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>Both reminder manager functions are asynchronous and await provider or Prisma operations, but the
>changed booking-cancellation loop discards their promises and awaits only unrelated deletion
>promises before returning. The changed rescheduling and workflow-mutation call sites repeat this
>unawaited pattern, proving that none of those surrounding operations waits for reminder cancellation
>or observes its asynchronous failures.
></pre>
>
> <code>[packages/features/ee/workflows/lib/reminders/emailReminderManager.ts[197-235]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4b13cb4cf3764b8d078a0120525e3bf3487178eb/packages/features/ee/workflows/lib/reminders/emailReminderManager.ts/#L197-L235)</code>
> <code>[packages/features/ee/workflows/lib/reminders/smsReminderManager.ts[177-189]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4b13cb4cf3764b8d078a0120525e3bf3487178eb/packages/features/ee/workflows/lib/reminders/smsReminderManager.ts/#L177-L189)</code>
> <code>[packages/features/bookings/lib/handleCancelBooking.ts[484-502]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4b13cb4cf3764b8d078a0120525e3bf3487178eb/packages/features/bookings/lib/handleCancelBooking.ts/#L484-L502)</code>
> <code>[packages/features/bookings/lib/handleNewBooking.ts[963-980]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4b13cb4cf3764b8d078a0120525e3bf3487178eb/packages/features/bookings/lib/handleNewBooking.ts/#L963-L980)</code>
> <code>[packages/trpc/server/routers/viewer/workflows.tsx[573-580]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4b13cb4cf3764b8d078a0120525e3bf3487178eb/packages/trpc/server/routers/viewer/workflows.tsx/#L573-L580)</code>
> <code>[packages/features/bookings/lib/handleNewBooking.ts[963-975]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4b13cb4cf3764b8d078a0120525e3bf3487178eb/packages/features/bookings/lib/handleNewBooking.ts/#L963-L975)</code>
> <code>[packages/features/ee/workflows/lib/reminders/emailReminderManager.ts[197-234]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4b13cb4cf3764b8d078a0120525e3bf3487178eb/packages/features/ee/workflows/lib/reminders/emailReminderManager.ts/#L197-L234)</code>
> <code>[packages/features/ee/workflows/lib/reminders/smsReminderManager.ts[177-188]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4b13cb4cf3764b8d078a0120525e3bf3487178eb/packages/features/ee/workflows/lib/reminders/smsReminderManager.ts/#L177-L188)</code>
> <code>[packages/trpc/server/routers/viewer/workflows.tsx[211-225]](https://github.com/drape-io/crbench-qodo-2026-09/blob/4b13cb4cf3764b8d078a0120525e3bf3487178eb/packages/trpc/server/routers/viewer/workflows.tsx/#L211-L225)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>Reminder cancellation functions perform asynchronous provider and Prisma operations, but the changed cancellation, rescheduling, and workflow-edit callers invoke them without awaiting or collecting the returned promises. The parent operation can therefore finish before reminder cancellation completes, and failures may not be propagated or handled.
>
>## Fix Focus Areas
>- packages/features/bookings/lib/handleCancelBooking.ts[484-497]
>- packages/features/bookings/lib/handleNewBooking.ts[963-975]
>- packages/trpc/server/routers/viewer/bookings.tsx[487-494]
>- packages/trpc/server/routers/viewer/workflows.tsx[211-218]
>- packages/trpc/server/routers/viewer/workflows.tsx[375-382]
>- packages/trpc/server/routers/viewer/workflows.tsx[517-524]
>- packages/trpc/server/routers/viewer/workflows.tsx[573-580]
>
>## Recommended Fix
>Replace synchronous `forEach` fire-and-forget calls with promise-producing `map` calls or awaited loops, then wait for the resulting cancellation operations with `Promise.all` or `Promise.allSettled` before continuing or returning. Propagate failures or handle them explicitly, retaining deliberate error handling where reminder-cancellation failures should not abort the parent operation rather than relying on a `try` block around unawaited calls.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<!-- qodo-context:start -->
<details><summary><strong>Context sources</strong></summary>
<div>Review mode: <code>🧠 Deep</code>: This broad, behavior-heavy change spans booking cancellation/rescheduling, workflow reminder cancellation, external email/SMS APIs, UI verification, and a schema migration, with many independent logic sites and substantial failure modes.</div>
<!-- qodo-context:end -->
</details>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<!-- qodo-daily-tip:start -->
<details>
<summary><strong>Tip of the day</strong></summary>
<br/>
<pre>💡 Did you know, you can reply 'qodo' on any finding to push back, ask questions, or dig deeper</pre>
<a href="https://docs.qodo.ai/tips-and-tricks">More tips ↗</a> | <a href="https://app.qodo.ai/configurations?tab=display-preferences">Customize Qodo ↗</a> | <a href="https://docs.qodo.ai">Qodo docs ↗</a>
</details>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<!-- qodo-daily-tip:end -->
<!-- https://github.com/drape-io/crbench-qodo-2026-09/commit/4b13cb4cf3764b8d078a0120525e3bf3487178eb -->
<a href="https://www.qodo.ai"><img src="https://www.qodo.ai/wp-content/uploads/2025/03/qodo-logo.svg" width="80" alt="Qodo Logo"></a>