Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(reminders): dispatch recurring reminders (#5700)
Evan Hutnikc49a8acc13e7
diff --git a/.sqlx/query-0669506bb06d4ac47b1f80cd35ce3415facd3da101d196e0b87a6e12521319e8.json b/.sqlx/query-0669506bb06d4ac47b1f80cd35ce3415facd3da101d196e0b87a6e12521319e8.jsonnew file mode 100644index 0000000000..a6a0228166--- /dev/null+++ b/.sqlx/query-0669506bb06d4ac47b1f80cd35ce3415facd3da101d196e0b87a6e12521319e8.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM notification WHERE id = ANY($1)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray"+ ]+ },+ "nullable": []+ },+ "hash": "0669506bb06d4ac47b1f80cd35ce3415facd3da101d196e0b87a6e12521319e8"+}diff --git a/.sqlx/query-1951b50b2751a6658bec25b3e6b89de9197480f40fb4c8e55fe9c426385c1c86.json b/.sqlx/query-1951b50b2751a6658bec25b3e6b89de9197480f40fb4c8e55fe9c426385c1c86.jsonnew file mode 100644index 0000000000..b78326017f--- /dev/null+++ b/.sqlx/query-1951b50b2751a6658bec25b3e6b89de9197480f40fb4c8e55fe9c426385c1c86.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT r.id, r.next_run_at\n FROM reminder r\n WHERE r.enabled\n -- Completion is per-firing, so it only retires a one-shot. A\n -- recurring reminder its owner has ticked off keeps coming due:\n -- they dealt with the last nudge, not with the standing\n -- arrangement, and ending that is what deleting is for.\n AND (r.cron IS NOT NULL OR r.completed_at IS NULL)\n AND r.next_run_at <= $1\n AND NOT EXISTS (\n SELECT 1\n FROM reminder_occurrence o\n WHERE o.reminder_id = r.id\n AND o.scheduled_for = r.next_run_at\n AND o.sent_at IS NOT NULL\n )\n ORDER BY r.next_run_at\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "next_run_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Timestamptz"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "1951b50b2751a6658bec25b3e6b89de9197480f40fb4c8e55fe9c426385c1c86"+}diff --git a/.sqlx/query-768f7ca693d6cead9738e985801752fea6be33b910542c7da015634e67ee4726.json b/.sqlx/query-768f7ca693d6cead9738e985801752fea6be33b910542c7da015634e67ee4726.jsondeleted file mode 100644index 549a8ea45c..0000000000--- a/.sqlx/query-768f7ca693d6cead9738e985801752fea6be33b910542c7da015634e67ee4726.json+++ /dev/null@@ -1,28 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT r.id, r.next_run_at\n FROM reminder r\n WHERE r.enabled\n AND r.completed_at IS NULL\n AND r.cron IS NULL\n AND r.next_run_at <= $1\n AND NOT EXISTS (\n SELECT 1\n FROM reminder_occurrence o\n WHERE o.reminder_id = r.id\n AND o.scheduled_for = r.next_run_at\n AND o.sent_at IS NOT NULL\n )\n ORDER BY r.next_run_at\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "next_run_at",- "type_info": "Timestamptz"- }- ],- "parameters": {- "Left": [- "Timestamptz"- ]- },- "nullable": [- false,- false- ]- },- "hash": "768f7ca693d6cead9738e985801752fea6be33b910542c7da015634e67ee4726"-}diff --git a/.sqlx/query-925b6d294f595632ddcca168fb945788b76987e58174740988d3e70b8f15e0a7.json b/.sqlx/query-925b6d294f595632ddcca168fb945788b76987e58174740988d3e70b8f15e0a7.jsonnew file mode 100644index 0000000000..ac695a2b0c--- /dev/null+++ b/.sqlx/query-925b6d294f595632ddcca168fb945788b76987e58174740988d3e70b8f15e0a7.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, metadata->>'scheduledFor' AS \"scheduled_for?\"\n FROM notification\n WHERE event_item_type = 'reminder' AND event_item_id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "scheduled_for?",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ null+ ]+ },+ "hash": "925b6d294f595632ddcca168fb945788b76987e58174740988d3e70b8f15e0a7"+}diff --git a/.sqlx/query-cdd0bf72f283fb8ff3e5393aa24ca80ab4d54d877376ed58ca7c4eec479e1a42.json b/.sqlx/query-cdd0bf72f283fb8ff3e5393aa24ca80ab4d54d877376ed58ca7c4eec479e1a42.jsonnew file mode 100644index 0000000000..4f4b0e566c--- /dev/null+++ b/.sqlx/query-cdd0bf72f283fb8ff3e5393aa24ca80ab4d54d877376ed58ca7c4eec479e1a42.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE reminder\n SET next_run_at = $2,\n -- Cleared only when the owner was notified. A firing they can\n -- see supersedes their \"done\" on the previous one; a firing\n -- rolled forward in silence supersedes nothing.\n completed_at = CASE WHEN $4::bool THEN NULL ELSE completed_at END,\n updated_at = now()\n WHERE id = $1 AND next_run_at = $3\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Timestamptz",+ "Timestamptz",+ "Bool"+ ]+ },+ "nullable": []+ },+ "hash": "cdd0bf72f283fb8ff3e5393aa24ca80ab4d54d877376ed58ca7c4eec479e1a42"+}diff --git a/.sqlx/query-921e5411094ca64c56d4476eec49206049f771f35699bf36b1beff103fb68bca.json b/.sqlx/query-d32d32cb5f08f017f662a412ebec1e58c71fdb7651079410fe26ac508161146e.jsonsimilarity index 87%rename from .sqlx/query-921e5411094ca64c56d4476eec49206049f771f35699bf36b1beff103fb68bca.jsonrename to .sqlx/query-d32d32cb5f08f017f662a412ebec1e58c71fdb7651079410fe26ac508161146e.jsonindex 659d04207f..34ff097ff7 100644--- a/.sqlx/query-921e5411094ca64c56d4476eec49206049f771f35699bf36b1beff103fb68bca.json+++ b/.sqlx/query-d32d32cb5f08f017f662a412ebec1e58c71fdb7651079410fe26ac508161146e.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n id,\n user_id,\n description,\n entity_type,\n entity_id,\n remind_at,\n cron,\n timezone,\n next_run_at,\n enabled,\n completed_at,\n created_at,\n updated_at\n FROM reminder\n WHERE id = $1\n AND next_run_at = $2\n AND enabled\n AND completed_at IS NULL\n ",+ "query": "\n SELECT\n id,\n user_id,\n description,\n entity_type,\n entity_id,\n remind_at,\n cron,\n timezone,\n next_run_at,\n enabled,\n completed_at,\n created_at,\n updated_at\n FROM reminder\n WHERE id = $1\n AND next_run_at = $2\n AND enabled\n -- Matches `due_firings`: a completed recurring reminder is still\n -- deliverable, a completed one-shot is finished.\n AND (cron IS NOT NULL OR completed_at IS NULL)\n ","describe": {"columns": [{@@ -91,5 +91,5 @@false]},- "hash": "921e5411094ca64c56d4476eec49206049f771f35699bf36b1beff103fb68bca"+ "hash": "d32d32cb5f08f017f662a412ebec1e58c71fdb7651079410fe26ac508161146e"}diff --git a/apps/web/src/features/block-automation/component/automationUtils.ts b/apps/web/src/features/block-automation/component/automationUtils.tsindex 811fd83a2b..f1cb1c8c00 100644--- a/apps/web/src/features/block-automation/component/automationUtils.ts+++ b/apps/web/src/features/block-automation/component/automationUtils.ts@@ -1,6 +1,15 @@import { DEFAULT_MODEL } from '@core/component/AI/constant';import type { Model } from '@core/component/AI/types';import { blockNameToDefaultFile } from '@core/constant/allBlocks';+import {+ buildCron as buildCronExpression,+ type CronParts,+ DEFAULT_TIME,+ DEFAULT_WEEKDAYS,+ describeCron,+ getDefaultTimezone,+ parseCron as parseCronParts,+} from '@core/util/cron';import { ThrownResultError } from '@core/util/result';import type {AgentTask,@@ -10,9 +19,15 @@ import type {} from '@service-scheduled-action/generated/schemas';import type { ScheduleDraft, ScheduleFrequency } from './types';+export {+ DEFAULT_TIME,+ getDefaultTimezone,+ isValidTime,+ WEEKDAY_OPTIONS,+} from '@core/util/cron';+export const INPUT_CLASS ='w-full border border-edge-muted rounded-sm bg-surface px-2 py-1.5 text-sm text-ink outline-none placeholder:text-ink-placeholder focus:border-accent/20 cursor-default';-export const DEFAULT_TIME = '09:00';export const FREQUENCY_OPTIONS: Array<{value: ScheduleFrequency;@@ -22,25 +37,6 @@ export const FREQUENCY_OPTIONS: Array<{{ value: 'month', label: 'Every month' },];-// Day-of-week values match the `cron` Rust crate convention:-// 1 = Sun, 2 = Mon, 3 = Tue, 4 = Wed, 5 = Thu, 6 = Fri, 7 = Sat-export const WEEKDAY_OPTIONS = [- { value: '1', label: 'Sun', fullLabel: 'Sunday' },- { value: '2', label: 'Mon', fullLabel: 'Monday' },- { value: '3', label: 'Tue', fullLabel: 'Tuesday' },- { value: '4', label: 'Wed', fullLabel: 'Wednesday' },- { value: '5', label: 'Thu', fullLabel: 'Thursday' },- { value: '6', label: 'Fri', fullLabel: 'Friday' },- { value: '7', label: 'Sat', fullLabel: 'Saturday' },-];--const DOW_VALUES = WEEKDAY_OPTIONS.map((option) => option.value);-const DEFAULT_WEEKDAYS = ['2', '3', '4', '5', '6']; // Mon-Fri--export function getDefaultTimezone() {- return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';-}-function normalizePrompt(value: string) {return value.trim()@@ -56,83 +52,18 @@ function deriveScheduleName(prompt: string) {return summary.length > 72 ? `${summary.slice(0, 71)}…` : summary;}-export function isValidTime(value: string) {- return /^\d{2}:\d{2}$/.test(value);-}--function toTimeValue(hour: string, minute: string) {- const safeHour = Number(hour);- const safeMinute = Number(minute);- if (- Number.isNaN(safeHour) ||- Number.isNaN(safeMinute) ||- safeHour < 0 ||- safeHour > 23 ||- safeMinute < 0 ||- safeMinute > 59- ) {- return DEFAULT_TIME;- }-- return `${String(safeHour).padStart(2, '0')}:${String(safeMinute).padStart(2, '0')}`;-}--function formatTimeLabel(value: string) {- if (!isValidTime(value)) return value;- const [hour, minute] = value.split(':').map(Number);- const date = new Date(2026, 0, 1, hour, minute);- return new Intl.DateTimeFormat(undefined, {- hour: 'numeric',- minute: '2-digit',- }).format(date);-}--function formatDayList(daysOfWeek: string[]): string {- if (daysOfWeek.length === 0) return 'no days';- const sorted = [...daysOfWeek].sort(- (a, b) => DOW_VALUES.indexOf(a) - DOW_VALUES.indexOf(b)- );- if (sorted.length === 7) return 'every day';- if (- sorted.length === 5 &&- sorted.every((d) => DEFAULT_WEEKDAYS.includes(d))- ) {- return 'weekdays';- }- if (sorted.length === 2 && sorted.includes('1') && sorted.includes('7')) {- return 'weekends';- }- return sorted- .map((d) => WEEKDAY_OPTIONS.find((opt) => opt.value === d)?.fullLabel)- .filter(Boolean)- .join(', ');-}--function nthSuffix(n: number): string {- const tens = n % 100;- if (tens >= 11 && tens <= 13) return 'th';- switch (n % 10) {- case 1:- return 'st';- case 2:- return 'nd';- case 3:- return 'rd';- default:- return 'th';- }+/** The cron-editable parts of a draft, which is all the shared helpers need. */+function cronParts(draft: ScheduleDraft): CronParts {+ return {+ frequency: draft.frequency,+ time: draft.time,+ daysOfWeek: draft.daysOfWeek,+ dayOfMonth: draft.dayOfMonth,+ };}export function describeSchedule(draft: ScheduleDraft, timezone: string) {- const timeLabel = formatTimeLabel(draft.time);- if (draft.frequency === 'week') {- return `${formatDayList(draft.daysOfWeek)} at ${timeLabel} (${timezone})`;- }- const day = Number(draft.dayOfMonth);- if (Number.isInteger(day) && day >= 1 && day <= 31) {- return `${day}${nthSuffix(day)} of each month at ${timeLabel} (${timezone})`;- }- return `Each month at ${timeLabel} (${timezone})`;+ return describeCron(cronParts(draft), timezone);}type ParsedCron = Pick<@@ -140,106 +71,18 @@ type ParsedCron = Pick<'frequency' | 'time' | 'daysOfWeek' | 'dayOfMonth'>;-export function parseCron(cron: string): ParsedCron {- const fallback: ParsedCron = {- frequency: 'week',- time: DEFAULT_TIME,- daysOfWeek: [...DEFAULT_WEEKDAYS],- dayOfMonth: '1',- };-- const fields = cron.trim().split(/\s+/);- // The Rust `cron` crate requires 6 (`sec min hour dom mon dow`) or- // 7 (with year) fields.- if (fields.length !== 6 && fields.length !== 7) return fallback;-- const [, minute, hour, dayOfMonth, month, dayOfWeek] = fields;- const time = toTimeValue(hour, minute);-- if (month !== '*') return { ...fallback, time };-- // Weekly-ish: dom="*" with a dow list/range.- if (dayOfMonth === '*') {- if (dayOfWeek === '*') {- return {- frequency: 'week',- time,- daysOfWeek: [...DOW_VALUES],- dayOfMonth: '1',- };- }- const days = expandDowExpression(dayOfWeek);- if (days.length > 0) {- return {- frequency: 'week',- time,- daysOfWeek: days,- dayOfMonth: '1',- };- }- return { ...fallback, time };- }-- // Monthly: specific day-of-month, dow="*".- if (dayOfWeek === '*' && /^(?:[1-9]|[12]\d|3[01])$/.test(dayOfMonth)) {- return {- frequency: 'month',- time,- daysOfWeek: [...DEFAULT_WEEKDAYS],- dayOfMonth,- };- }-- return { ...fallback, time };-}-/**- * Expands a day-of-week cron expression like "2,4,6" or "2-6" into a list of- * single DOW values. Returns `[]` if anything in the expression can't be- * interpreted — caller should fall back to defaults.+ * Read a cron expression into the parts an automation's picker edits.+ *+ * A pass-through: the shared parser only ever reports frequencies this picker+ * can render, so there is nothing to adapt.*/-function expandDowExpression(expr: string): string[] {- const parts = expr.split(',');- const set = new Set<string>();- for (const raw of parts) {- const part = raw.trim();- if (/^[1-7]$/.test(part)) {- set.add(part);- continue;- }- const range = part.match(/^([1-7])-([1-7])$/);- if (range) {- const [, lo, hi] = range;- const loN = Number(lo);- const hiN = Number(hi);- if (loN <= hiN) {- for (let n = loN; n <= hiN; n++) set.add(String(n));- continue;- }- }- return [];- }- return [...set].sort((a, b) => DOW_VALUES.indexOf(a) - DOW_VALUES.indexOf(b));+export function parseCron(cron: string): ParsedCron {+ return parseCronParts(cron);}function buildCron(draft: ScheduleDraft) {- const [hour, minute] = (isValidTime(draft.time) ? draft.time : DEFAULT_TIME)- .split(':')- .map((value) => Number(value));-- // 6-field format required by the Rust `cron` crate:- // sec min hour dayOfMonth month dayOfWeek- if (draft.frequency === 'week') {- const days = draft.daysOfWeek.length- ? [...draft.daysOfWeek]- .sort((a, b) => DOW_VALUES.indexOf(a) - DOW_VALUES.indexOf(b))- .join(',')- : '*';- return `0 ${minute} ${hour} * * ${days}`;- }- const day = Number(draft.dayOfMonth);- const safeDay = Number.isInteger(day) && day >= 1 && day <= 31 ? day : 1;- return `0 ${minute} ${hour} ${safeDay} * *`;+ return buildCronExpression(cronParts(draft));}export function createEmptyDraft(): ScheduleDraft {diff --git a/apps/web/src/features/entity/components/Badges.tsx b/apps/web/src/features/entity/components/Badges.tsxindex b0c6abc36e..14d93cbb49 100644--- a/apps/web/src/features/entity/components/Badges.tsx+++ b/apps/web/src/features/entity/components/Badges.tsx@@ -155,6 +155,24 @@ export function ReminderReferenceBadge(props: ParentProps<{ name: string }>) {);}+/**+ * How often a recurring reminder fires, e.g. "Every weekday at 9:00 AM".+ *+ * A reminder row shows its next firing in the timestamp column, which for a+ * recurring one says when it next comes due but not that it will come due+ * again. This is the part that says so.+ */+export function ReminderRecurrenceBadge(props: { recurrence: string }) {+ return (+ <Badge+ class="max-w-40 min-w-0 shrink-0 normal-case font-sans text-ink-extra-muted border-edge-muted px-2"+ title={props.recurrence}+ >+ <span class="truncate">{props.recurrence}</span>+ </Badge>+ );+}+export function CallDurationBadge(props: { duration: string }) {return (<Badge class="normal-case text-ink-extra-muted border-edge-muted px-2">diff --git a/apps/web/src/features/entity/composed/list-entity/reminder.tsx b/apps/web/src/features/entity/composed/list-entity/reminder.tsxindex 27bda15e8f..a0c9c6bb8e 100644--- a/apps/web/src/features/entity/composed/list-entity/reminder.tsx+++ b/apps/web/src/features/entity/composed/list-entity/reminder.tsx@@ -1,3 +1,7 @@+import {+ describeReminderSchedule,+ scheduleFromRow,+} from '@app/features/reminders/reminder-schedule';import {EntityIcon,reminderReferenceIconType,@@ -5,7 +9,10 @@ import {import { useItemPreviewData } from '@core/component/ItemPreview';import { isAccessiblePreviewItem } from '@queries/preview';import { Show } from 'solid-js';-import { ReminderReferenceBadge } from '../../components/Badges';+import {+ ReminderRecurrenceBadge,+ ReminderReferenceBadge,+} from '../../components/Badges';import { Entity } from '../../entity';import type { ReminderEntity } from '../../types/entity';@@ -22,19 +29,31 @@ type Reference = NonNullable<ReminderEntity['referencedEntity']>;* the way `CallWideContent` trails a call with its channel.*/export function ReminderWideContent(props: { entity: ReminderEntity }) {+ // Trails the row, after any reference badge, so the reading order is what the+ // reminder says, what it is about, then how often it repeats.+ const recurrence = () =>+ props.entity.scheduleType === 'recurring'+ ? describeReminderSchedule(scheduleFromRow(props.entity))+ : undefined;+return (- <Show- when={props.entity.referencedEntity}- fallback={- <span class="truncate">- <Entity.Title entity={props.entity} />- </span>- }- >- {(reference) => (- <ReferencedReminder entity={props.entity} reference={reference()} />- )}- </Show>+ <>+ <Show+ when={props.entity.referencedEntity}+ fallback={+ <span class="truncate">+ <Entity.Title entity={props.entity} />+ </span>+ }+ >+ {(reference) => (+ <ReferencedReminder entity={props.entity} reference={reference()} />+ )}+ </Show>+ <Show when={recurrence()}>+ {(text) => <ReminderRecurrenceBadge recurrence={text()} />}+ </Show>+ </>);}diff --git a/apps/web/src/features/next-soup/actions/make-edit-reminder-action.test.ts b/apps/web/src/features/next-soup/actions/make-edit-reminder-action.test.tsindex a3a185a5cd..6e38013709 100644--- a/apps/web/src/features/next-soup/actions/make-edit-reminder-action.test.ts+++ b/apps/web/src/features/next-soup/actions/make-edit-reminder-action.test.ts@@ -64,16 +64,14 @@ describe('makeEditReminderAction', () => {expect(canExecute(entity('email'))).toBe(false);});- // The composer only speaks one-shot schedules, so editing a recurring- // reminder through it would quietly turn a cron into a single firing.- it('cannot run for a recurring reminder', () => {+ it('can run for a recurring reminder', () => {const recurring = reminder({scheduleType: 'recurring',cron: '0 0 9 * * *',timezone: 'UTC',});- expect(makeEditReminderAction().canExecute(recurring)).toBe(false);+ expect(makeEditReminderAction().canExecute(recurring)).toBe(true);});it('opens the editor with the reminder as the row knows it', () => {@@ -83,10 +81,51 @@ describe('makeEditReminderAction', () => {id: 'rem-1',description: 'Chase the contract',remindAt: new Date(NEXT_RUN),+ schedule: { type: 'once', remindAt: new Date(NEXT_RUN).toISOString() },completed: false,});});+ // The composer diffs the edit against this, so a recurring reminder has to+ // arrive as its cron rather than as its next firing — otherwise opening one+ // and saving it would quietly flatten the series into a single date.+ // The row and the editor both rebuild the schedule from a soup row, and each+ // inventing its own substitution for an absent zone would describe the same+ // reminder two ways — with the editor's diff then reading the substitution as+ // a change and re-sending it, moving when the reminder fires. UTC is the+ // shared fallback because it does not depend on who is looking.+ it('falls back to UTC for a recurring reminder with no timezone', () => {+ makeEditReminderAction().execute([+ reminder({ scheduleType: 'recurring', cron: '0 0 9 * * *' }),+ ]);++ expect(mocks.openReminderEditor).toHaveBeenCalledWith(+ expect.objectContaining({+ schedule: { type: 'recurring', cron: '0 0 9 * * *', timezone: 'UTC' },+ })+ );+ });++ it('passes a recurring reminder its cron, not its next firing', () => {+ makeEditReminderAction().execute([+ reminder({+ scheduleType: 'recurring',+ cron: '0 0 9 * * 2-6',+ timezone: 'America/New_York',+ }),+ ]);++ expect(mocks.openReminderEditor).toHaveBeenCalledWith(+ expect.objectContaining({+ schedule: {+ type: 'recurring',+ cron: '0 0 9 * * 2-6',+ timezone: 'America/New_York',+ },+ })+ );+ });+// A reschedule has to clear the done flag, so the editor needs to know the// reminder was completed — see reminderEditPatch.it('reports a completed reminder as completed', () => {diff --git a/apps/web/src/features/next-soup/actions/make-edit-reminder-action.ts b/apps/web/src/features/next-soup/actions/make-edit-reminder-action.tsindex 7426438302..432158ede4 100644--- a/apps/web/src/features/next-soup/actions/make-edit-reminder-action.ts+++ b/apps/web/src/features/next-soup/actions/make-edit-reminder-action.ts@@ -1,5 +1,8 @@import { openReminderEditor } from '@app/features/reminders/reminder-composer';-import { reminderDescriptionForReference } from '@app/features/reminders/reminder-schedule';+import {+ reminderDescriptionForReference,+ scheduleFromRow,+} from '@app/features/reminders/reminder-schedule';import { ENABLE_REMINDERS } from '@core/constant/featureFlags';import type { EntityData, ReminderEntity } from '@entity';import {@@ -28,22 +31,15 @@ function fallbackDescriptionFor(entity: ReminderEntity): string | undefined {}/**- * Edit an existing reminder — its description, its time, or both.+ * Edit an existing reminder — its description, its schedule, or both.** `execute` opens the composer prefilled rather than writing anything: both* answers come from the user, so there is nothing to do until that modal* resolves. Single-entity only, like creating one.- *- * Recurring reminders are excluded. The composer only speaks one-shot- * schedules, so editing one through it would quietly turn a cron into a single- * firing. Nothing in the product creates a recurring reminder today, so this- * excludes nothing a user can actually reach.*/export const makeEditReminderAction = () => {const canExecute = (entity: EntityData): boolean =>- ENABLE_REMINDERS() &&- entity.type === 'reminder' &&- entity.scheduleType === 'once';+ ENABLE_REMINDERS() && entity.type === 'reminder';const execute = (entities: EntityData[]) => {const [entity] = entities;@@ -55,6 +51,7 @@ export const makeEditReminderAction = () => {id: entity.id,description: entity.description,remindAt: new Date(entity.nextRunAt),+ schedule: scheduleFromRow(entity),completed: entity.completedAt != null,fallbackDescription: fallbackDescriptionFor(entity),});diff --git a/apps/web/src/features/reminders/ReminderComposerModal.tsx b/apps/web/src/features/reminders/ReminderComposerModal.tsxindex 7fd62b43e8..c78f51461c 100644--- a/apps/web/src/features/reminders/ReminderComposerModal.tsx+++ b/apps/web/src/features/reminders/ReminderComposerModal.tsx@@ -1,6 +1,16 @@import { toast } from '@core/component/Toast/Toast';import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';-import { useDateSearch } from '@core/util/dateSearch/useDateSearch';+import {+ type CronParts,+ describeCron,+ isValidCronParts,+ type ScheduleFrequency,+ WEEKDAY_OPTIONS,+} from '@core/util/cron';+import {+ type DateOption,+ useDateSearch,+} from '@core/util/dateSearch/useDateSearch';import {type ListNavActions,useListKeyBindings,@@ -18,6 +28,7 @@ import {optimisticUpdateSoupEntity,refetchSoupEntity,} from '@queries/soup/cache';+import type { ReminderSchedule } from '@service-storage/generated/schemas/reminderSchedule';import { mergeRefs } from '@solid-primitives/refs';import {Button,@@ -26,6 +37,7 @@ import {CommandMenuListItem,CommandMenuSearchInput,CommandMenuShell,+ cn,Dialog,Hotkey,} from '@ui';@@ -50,20 +62,25 @@ import {takeReminderCreatedHandler,} from './reminder-composer';import {- formatReminderWhen,+ defaultRepeatParts,+ describeReminderSchedule,futureDateOptions,+ isRecurring,onceSchedule,REMINDER_DEFAULT_TIME,REMINDER_DESCRIPTION_MAX_LENGTH,+ recurringSchedule,reminderDefaultOptions,reminderEditOptions,reminderEditPatch,+ repeatPartsFromDate,+ repeatPartsFromSchedule,resolveEditedDescription,resolveReminderDescription,} from './reminder-schedule';-/** The composer's two questions, asked in this order. */-type Step = 'description' | 'when';+/** The composer's questions, asked in this order. */+type Step = 'description' | 'when' | 'repeat';/*** Asks two questions — what and when — for a reminder, either a new one about@@ -86,6 +103,12 @@ export function ReminderComposerModal() {const [description, setDescription] = createSignal('');const [query, setQuery] = createSignal('');const [selectedIndex, setSelectedIndex] = createSignal(0);+ // The recurrence being built, only meaningful on the repeat step. Seeded when+ // that step opens — from the reminder's own schedule when editing one that+ // already repeats, so its picker starts where the user left it.+ const [repeatParts, setRepeatParts] = createSignal<CronParts>(+ repeatPartsFromDate(new Date())+ );// Nothing else brings a new reminder into Soup: the service emits no// websocket event on create (its only outbound signals are the dispatch@@ -122,6 +145,12 @@ export function ReminderComposerModal() {* @returns whether it stepped back rather than closed.*/const handleEscape = (): boolean => {+ // Unwinds one step at a time, so escape from the repeat picker lands back on+ // the date list rather than throwing the whole reminder away.+ if (step() === 'repeat') {+ setStep('when');+ return true;+ }if (step() === 'when') {setStep('description');return true;@@ -130,6 +159,26 @@ export function ReminderComposerModal() {return false;};+ /**+ * Open the repeat picker, seeded from whatever is most specific.+ *+ * An existing recurrence first, so changing one starts where it is. Failing+ * that the date the list is currently leading with, so typing "tomorrow 3pm"+ * and then choosing to repeat gives a 3pm recurrence rather than discarding+ * the time that was just asked for.+ */+ const openRepeatStep = (seed?: Date) => {+ const current = editing()?.schedule;+ setRepeatParts(+ current && isRecurring(current)+ ? repeatPartsFromSchedule(current)+ : seed+ ? repeatPartsFromDate(seed)+ : defaultRepeatParts()+ );+ setStep('repeat');+ };+// Only reachable with focus outside the header input — the hotkey layer skips// handlers while an editable is focused. Kobalte's document-level escape// handler below covers the usual case; both have to agree.@@ -158,15 +207,23 @@ export function ReminderComposerModal() {const advanceFromDescription = () => setStep('when');// The dialog's Enter binding is a single shared slot, so whichever step is on- // screen has to claim it or the other step's stale handler stays live.+ // screen has to claim it or the other step's stale handler stays live. The+ // date step claims it from inside `WhenList`, which owns the list it moves+ // through; the other two have no list, so they claim it here.createEffect(on(step, (current) => {- if (current !== 'description') return;- keybindings(descriptionStepKeybindings(advanceFromDescription));+ if (current === 'description') {+ keybindings(descriptionStepKeybindings(advanceFromDescription));+ } else if (current === 'repeat') {+ keybindings(listlessStepKeybindings(() => void submitRepeat()));+ }}));- const submitCreate = async (date: Date, target: EntityData) => {+ const submitCreate = async (+ schedule: ReminderSchedule,+ target: EntityData+ ) => {const resolved = resolveReminderDescription(description(), target);const attachTo = reminderTarget(target);// Taken before the close, which clears it.@@ -176,11 +233,11 @@ export function ReminderComposerModal() {try {await createReminder.mutateAsync({description: resolved,- schedule: onceSchedule(date),+ schedule,// Both or neither: the API rejects one without the other....(attachTo ?? undefined),});- toast.success(`Reminder set for ${formatReminderWhen(date)}`);+ toast.success('Reminder set');} catch {toast.failure('Failed to create reminder');return;@@ -192,7 +249,10 @@ export function ReminderComposerModal() {await onCreated?.();};- const submitEdit = async (date: Date, draft: ReminderDraft) => {+ const submitEdit = async (+ schedule: ReminderSchedule,+ draft: ReminderDraft+ ) => {const patch = reminderEditPatch(draft, {// Blank means the same here as it does when creating: name it after// whatever it is about.@@ -201,7 +261,7 @@ export function ReminderComposerModal() {draft.description,draft.fallbackDescription),- remindAt: date,+ schedule,});closeReminderComposer();@@ -211,16 +271,21 @@ export function ReminderComposerModal() {try {await updateReminder.mutateAsync({ id: draft.id, patch });- toast.success(- patch.schedule- ? `Reminder set for ${formatReminderWhen(date)}`- : 'Reminder updated'- );+ toast.success('Reminder updated');} catch {toast.failure('Failed to update reminder');}};+ /** Send whichever kind of schedule the user landed on. */+ const submitSchedule = async (schedule: ReminderSchedule) => {+ const draft = editing();+ if (draft) return await submitEdit(schedule, draft);++ const target = entity();+ if (target) return await submitCreate(schedule, target);+ };+const submit = async (date: Date) => {const draft = editing();@@ -234,10 +299,25 @@ export function ReminderComposerModal() {return;}- if (draft) return await submitEdit(date, draft);+ await submitSchedule(onceSchedule(date));+ };- const target = entity();- if (target) return await submitCreate(date, target);+ /**+ * Send the recurrence built on the repeat step.+ *+ * The validity gate lives here rather than at each control that can trigger a+ * submit. It was in two places — the button's `disabled` and the Enter+ * handler — and a gate written twice is one that eventually only holds in one+ * of them. Every path in goes through this, so there is no path that skips+ * it; the button's `disabled` is now an affordance rather than the check.+ *+ * No past-date check: a recurrence has no single instant to have passed, and+ * the backend derives its first firing from the cron itself.+ */+ const submitRepeat = async () => {+ const parts = repeatParts();+ if (!isValidCronParts(parts)) return;+ await submitSchedule(recurringSchedule(parts));};/**@@ -253,7 +333,8 @@ export function ReminderComposerModal() {// step — the description typed so far as a way back to it. Editing has no// entity, so the row is only there once something has been typed.const showsToolbar = () =>- entity() !== undefined || (step() === 'when' && !!description().trim());+ entity() !== undefined ||+ (step() !== 'description' && !!description().trim());return (<Dialog@@ -296,6 +377,11 @@ export function ReminderComposerModal() {onInput={setQuery}/></Match>+ <Match when={step() === 'repeat'}>+ {/* Not an input: the repeat picker is controls, not a query, so+ the header states what is being answered instead. */}+ <span class="px-2 text-base text-ink-muted">How often?</span>+ </Match></Switch></CommandMenuShell.Header><Show when={hasTarget()}>@@ -332,14 +418,46 @@ export function ReminderComposerModal() {<CommandMenuShell.Body><WhenListquery={query}- current={() => editing()?.remindAt}+ // Withheld for a recurring reminder. `reminderEditOptions`+ // turns this into a "Keep current time" date row holding the+ // next firing — which, activated, submits that single instant+ // as a one-shot and collapses the series. The `keep` row+ // carries the recurrence instead, and two adjacent rows both+ // promising to preserve, one of which destroys, is worse than+ // either alone.+ current={() => {+ const draft = editing();+ if (!draft) return undefined;+ return isRecurring(draft.schedule)+ ? undefined+ : draft.remindAt;+ }}+ currentRecurrence={() => {+ const schedule = editing()?.schedule;+ if (!schedule || !isRecurring(schedule)) return undefined;+ return {+ schedule,+ description: describeReminderSchedule(schedule) ?? '',+ };+ }}selectedIndex={selectedIndex}setSelectedIndex={setSelectedIndex}onSubmit={(date) => void submit(date)}+ onKeep={(schedule) => void submitSchedule(schedule)}+ onRepeat={openRepeatStep}setKeybindings={keybindings}/></CommandMenuShell.Body></Match>+ <Match when={step() === 'repeat'}>+ <CommandMenuShell.Body>+ <RepeatStep+ parts={repeatParts}+ setParts={setRepeatParts}+ onSubmit={() => void submitRepeat()}+ />+ </CommandMenuShell.Body>+ </Match></Switch></Show></CommandMenuShell>@@ -348,14 +466,21 @@ export function ReminderComposerModal() {}/**- * What the description step does with the dialog's shared list bindings.+ * The dialog's shared list bindings for a step that has no list.*- * There is no list to move through, so the arrows are inert and Enter is the- * skip-through: it advances whether or not anything was typed, subject to the- * step's own check.+ * The arrows go inert and Enter does the step's one action, so a step made of+ * controls rather than rows still answers the key everything else answers.+ */+function listlessStepKeybindings(select: VoidFunction): ListNavActions {+ return { next: () => {}, previous: () => {}, select };+}++/**+ * What the description step does with those bindings: Enter is the+ * skip-through, advancing whether or not anything was typed.*/function descriptionStepKeybindings(advance: VoidFunction): ListNavActions {- return { next: () => {}, previous: () => {}, select: advance };+ return listlessStepKeybindings(advance);}/**@@ -422,13 +547,40 @@ function DescriptionStep(props: { onContinue: VoidFunction }) {);}+/**+ * One row of the date list: a date to fire once at, or the way through to the+ * repeat picker.+ *+ * Modelled as a union rather than appending a fake `DateOption` so the repeat+ * row cannot be mistaken for a date and submitted as one.+ */+type WhenRow =+ | { kind: 'date'; option: DateOption }+ /**+ * Leave an existing recurring schedule exactly as it is.+ *+ * Its own kind rather than a relabelled date row. A recurring reminder's next+ * firing is one instant out of a series, so activating it as a date would+ * submit that instant as a one-shot — quietly collapsing the whole series+ * into a single day, from a row that says "Keep repeating".+ */+ | { kind: 'keep'; schedule: ReminderSchedule; detail: string }+ | { kind: 'repeat'; label: string; detail?: string };+function WhenList(props: {query: () => string;/** The firing an edited reminder already has, offered as "Keep current time". */current: () => Date | undefined;+ /** An edited reminder's existing recurrence, when it has one. */+ currentRecurrence: () =>+ | { schedule: ReminderSchedule; description: string }+ | undefined;selectedIndex: () => number;setSelectedIndex: (next: number | ((prev: number) => number)) => void;onSubmit: (date: Date) => void;+ /** Submit an existing recurring schedule unchanged. */+ onKeep: (schedule: ReminderSchedule) => void;+ onRepeat: (seed?: Date) => void;setKeybindings: (actions: {next: VoidFunction;previous: VoidFunction;@@ -454,32 +606,86 @@ function WhenList(props: {return futureDateOptions(rawOptions(), now);});+ const rows = createMemo<WhenRow[]>(() => {+ const existing = props.currentRecurrence();+ const typing = !!props.query().trim();++ // A reminder that already repeats has no single "current time" to keep —+ // its schedule is the recurrence — so leading with a row that hands back+ // that schedule untouched beats offering its next firing as if that were+ // the whole story. Dropped while typing: a query is a request for a+ // different time, and the keep row would sit above the answer.+ const keep: WhenRow[] =+ existing && !typing+ ? [+ {+ kind: 'keep',+ schedule: existing.schedule,+ detail: existing.description,+ },+ ]+ : [];++ const dates: WhenRow[] = dateOptions().map((option) => ({+ kind: 'date',+ option,+ }));++ // Always last, so it never displaces the date someone is reaching for, and+ // Enter on a date still creates a one-shot in two keystrokes.+ return [+ ...keep,+ ...dates,+ {+ kind: 'repeat',+ label: existing ? 'Change repeat…' : 'Repeat…',+ detail: existing?.description,+ },+ ];+ });++ // The date the selection last rested on, which is what a recurrence started+ // from here should inherit. Arrowing down to "In 2 hours" and carrying on to+ // "Repeat…" means that time, not whichever date happens to head the list.+ const [seedDate, setSeedDate] = createSignal<Date | undefined>();+ createEffect(() => {+ const row = rows()[props.selectedIndex()];+ if (row?.kind === 'date') setSeedDate(row.option.date);+ });++ const activate = (row: WhenRow) => {+ // Falls back to the leading option, which is what a typed query resolves+ // to — so "tomorrow 3pm" then Repeat still gives a 3pm recurrence even+ // without having moved the selection onto it.+ if (row.kind === 'repeat') {+ return props.onRepeat(seedDate() ?? dateOptions()[0]?.date);+ }+ if (row.kind === 'keep') return props.onKeep(row.schedule);+ props.onSubmit(row.option.date);+ };+createEffect(- on(dateOptions, (options) => {- if (options.length === 0) {- props.setSelectedIndex(0);- } else {- props.setSelectedIndex(- Math.min(props.selectedIndex(), options.length - 1)- );- }+ on(rows, (current) => {+ props.setSelectedIndex(+ Math.min(props.selectedIndex(), Math.max(current.length - 1, 0))+ );}));props.setKeybindings({next: () => {- const len = dateOptions().length;+ const len = rows().length;if (len === 0) return;props.setSelectedIndex((prev) => (prev + 1) % len);},previous: () => {- const len = dateOptions().length;+ const len = rows().length;if (len === 0) return;props.setSelectedIndex((prev) => (prev - 1 + len) % len);},select: () => {- const selected = dateOptions()[props.selectedIndex()];- if (selected) props.onSubmit(selected.date);+ const selected = rows()[props.selectedIndex()];+ if (selected) activate(selected);},});@@ -496,36 +702,33 @@ function WhenList(props: {<><div class="p-2 max-h-54 overflow-y-auto overflow-x-hidden scrollbar-hidden"><Show- when={dateOptions().length > 0}+ when={dateOptions().length > 0 || !props.query().trim()}fallback={- <Show- when={props.query().trim()}- fallback={- <CommandMenuEmptyState>- Enter a date, time or duration- </CommandMenuEmptyState>- }- >- <CommandMenuEmptyState>- No future dates match "{props.query()}"- </CommandMenuEmptyState>- </Show>+ <CommandMenuEmptyState>+ No future dates match "{props.query()}"+ </CommandMenuEmptyState>}>- <For each={dateOptions()}>- {(option, index) => (+ <For each={rows()}>+ {(row, index) => (<CommandMenuListItemid={`reminder-date-option-${index()}`}selected={isSelected(index())}- onClick={() => props.onSubmit(option.date)}+ onClick={() => activate(row)}onMouseMove={() => props.setSelectedIndex(index())}class="scroll-m-2"><div class="flex-1 text-left">- <p class="text-sm font-medium">{option.displayText}</p>+ <p class="text-sm font-medium">+ {row.kind === 'date'+ ? row.option.displayText+ : row.kind === 'keep'+ ? 'Keep repeating'+ : row.label}+ </p></div><span class="text-xs text-ink-muted">- {option.secondaryText}+ {row.kind === 'date' ? row.option.secondaryText : row.detail}</span></CommandMenuListItem>)}@@ -551,3 +754,134 @@ function WhenList(props: {</>);}++/**+ * The recurrences the picker offers, in ascending period.+ *+ * No daily entry: weekly with every day ticked says the same thing, and the+ * summary reads it back as "every day".+ */+const REPEAT_FREQUENCIES: Array<{ value: ScheduleFrequency; label: string }> = [+ { value: 'week', label: 'Weekly' },+ { value: 'month', label: 'Monthly' },+];++/**+ * Builds a recurrence: how often, on which days, at what time.+ *+ * Deliberately the same shape as the automation schedule editor — frequency,+ * then the one control that frequency needs, then a time — because it is the+ * same question, and someone who has set up an automation should not have to+ * learn a second way to say "every weekday at 9".+ */+function RepeatStep(props: {+ parts: () => CronParts;+ setParts: (next: CronParts) => void;+ onSubmit: VoidFunction;+}) {+ const update = (patch: Partial<CronParts>) =>+ props.setParts({ ...props.parts(), ...patch });++ const toggleDay = (value: string) => {+ const days = props.parts().daysOfWeek;+ // Never empty: an empty selection builds an every-day cron, which is not+ // what unticking your last day is asking for.+ const next = days.includes(value)+ ? days.filter((day) => day !== value)+ : [...days, value];+ if (next.length > 0) update({ daysOfWeek: next });+ };++ const summary = () => describeCron(props.parts());+ // Gates submit on everything `buildCron` would otherwise substitute a+ // fallback for — an out-of-range time, a day-of-month like 99 — so the+ // schedule that gets stored is the one the summary above describes.+ const isValid = () => isValidCronParts(props.parts());++ return (+ <>+ <div class="p-3 space-y-3 max-h-72 overflow-y-auto scrollbar-hidden">+ <div class="flex gap-1">+ <For each={REPEAT_FREQUENCIES}>+ {(option) => (+ <button+ type="button"+ class={cn(+ 'flex-1 rounded px-2 py-1.5 text-sm border',+ props.parts().frequency === option.value+ ? 'bg-active border-edge text-ink'+ : 'border-edge-muted text-ink-muted hover:text-ink'+ )}+ onClick={() => update({ frequency: option.value })}+ >+ {option.label}+ </button>+ )}+ </For>+ </div>++ <Show when={props.parts().frequency === 'week'}>+ <div class="flex gap-1">+ <For each={WEEKDAY_OPTIONS}>+ {(day) => (+ <button+ type="button"+ class={cn(+ 'flex-1 rounded px-1 py-1.5 text-xs border',+ props.parts().daysOfWeek.includes(day.value)+ ? 'bg-active border-edge text-ink'+ : 'border-edge-muted text-ink-muted hover:text-ink'+ )}+ aria-pressed={props.parts().daysOfWeek.includes(day.value)}+ onClick={() => toggleDay(day.value)}+ >+ {day.label}+ </button>+ )}+ </For>+ </div>+ </Show>++ <div class="flex items-center gap-2">+ <Show when={props.parts().frequency === 'month'}>+ <label class="flex items-center gap-2 text-sm text-ink-muted">+ Day+ <input+ type="number"+ min="1"+ max="31"+ class="w-16 rounded-sm border border-edge-muted bg-surface px-2 py-1.5 text-sm text-ink outline-none focus:border-accent/20"+ value={props.parts().dayOfMonth}+ onInput={(e) => update({ dayOfMonth: e.currentTarget.value })}+ />+ </label>+ </Show>+ <label class="flex items-center gap-2 text-sm text-ink-muted">+ At+ <input+ type="time"+ class="rounded-sm border border-edge-muted bg-surface px-2 py-1.5 text-sm text-ink outline-none focus:border-accent/20"+ value={props.parts().time}+ onInput={(e) => update({ time: e.currentTarget.value })}+ />+ </label>+ </div>+ </div>++ <CommandMenuShell.Footer class="gap-3 py-3">+ <span class="text-xs text-ink-muted truncate">{summary()}</span>+ <Button+ variant="active"+ size="sm"+ depth={3}+ class="ml-auto gap-3 rounded-lg border-0"+ disabled={!isValid()}+ onClick={props.onSubmit}+ >+ Set reminder+ <Hotkey shortcut="enter" theme="current" />+ </Button>+ </CommandMenuShell.Footer>+ </>+ );+}diff --git a/apps/web/src/features/reminders/reminder-composer.test.ts b/apps/web/src/features/reminders/reminder-composer.test.tsindex c9d3e35dd3..2f84edc806 100644--- a/apps/web/src/features/reminders/reminder-composer.test.ts+++ b/apps/web/src/features/reminders/reminder-composer.test.ts@@ -13,10 +13,13 @@ import {const doc = (id: string, name: string) =>({ type: 'document', id, name }) as EntityData;+const REMIND_AT = '2026-08-09T09:00:00.000Z';+const draft = (id: string, description: string) => ({id,description,- remindAt: new Date('2026-08-09T09:00:00.000Z'),+ remindAt: new Date(REMIND_AT),+ schedule: { type: 'once' as const, remindAt: REMIND_AT },completed: false,});diff --git a/apps/web/src/features/reminders/reminder-composer.ts b/apps/web/src/features/reminders/reminder-composer.tsindex 9bd2cb7ef2..2afb84daa5 100644--- a/apps/web/src/features/reminders/reminder-composer.ts+++ b/apps/web/src/features/reminders/reminder-composer.ts@@ -1,5 +1,6 @@import { createControlledOpenSignal } from '@core/util/createControlledOpenSignal';import type { EntityData } from '@entity';+import type { ReminderSchedule } from '@service-storage/generated/schemas/reminderSchedule';import { batch } from 'solid-js';import { createStore, reconcile } from 'solid-js/store';@@ -18,8 +19,16 @@ export interface ReminderDraft {id: string;/** Its current description, prefilled into the first step. */description: string;- /** Its current firing, offered as "Keep current time". */+ /** Its next firing, offered as "Keep current time". */remindAt: Date;+ /**+ * Its current schedule, which the edit is diffed against.+ *+ * Distinct from `remindAt` because a recurring reminder is not its next+ * firing: two reminders can come due at the same instant and still be+ * different schedules, and only this says which.+ */+ schedule: ReminderSchedule;/** Whether the owner has marked it done, which a reschedule has to undo. */completed: boolean;/**diff --git a/apps/web/src/features/reminders/reminder-schedule.test.ts b/apps/web/src/features/reminders/reminder-schedule.test.tsindex d15ab0d0db..455a48876a 100644--- a/apps/web/src/features/reminders/reminder-schedule.test.ts+++ b/apps/web/src/features/reminders/reminder-schedule.test.ts@@ -3,18 +3,24 @@ import type { EntityData } from '@entity';import { describe, expect, it } from 'vitest';import {- formatReminderWhen,+ defaultRepeatParts,+ describeReminderSchedule,futureDateOptions,+ isRecurring,onceSchedule,REMINDER_DEFAULT_TIME,REMINDER_DESCRIPTION_MAX_LENGTH,+ recurringSchedule,reminderDefaultOptions,reminderDescriptionFor,reminderDescriptionForReference,reminderEditOptions,reminderEditPatch,+ repeatPartsFromDate,+ repeatPartsFromSchedule,resolveEditedDescription,resolveReminderDescription,+ sameSchedule,} from './reminder-schedule';const option = (id: string, date: Date): DateOption => ({@@ -67,16 +73,10 @@ describe('reminderDefaultOptions', () => {// A Wednesday afternoon, so every entry is still ahead of "now".const wednesdayAfternoon = new Date(2026, 6, 29, 16, 37, 52, 400);- it('offers the five reminder defaults in order', () => {+ it('offers the four reminder defaults in order', () => {expect(reminderDefaultOptions(wednesdayAfternoon).map((o) => o.displayText)- ).toEqual([- 'In 1 hour',- 'In 2 hours',- 'Tomorrow',- 'End of week',- 'In 1 week',- ]);+ ).toEqual(['In 1 hour', 'In 2 hours', 'Tomorrow', 'In 1 week']);});it('offsets the hour entries from now, keeping the time of day', () => {@@ -105,41 +105,36 @@ describe('reminderDefaultOptions', () => {}});- it('dates the day-scale entries a day, a week end and a week out', () => {- const [, , tomorrow, endOfWeek, oneWeek] =- reminderDefaultOptions(wednesdayAfternoon);+ it('dates the day-scale entries a day and a week out', () => {+ const [, , tomorrow, oneWeek] = reminderDefaultOptions(wednesdayAfternoon);expect(tomorrow.date.getDate()).toBe(30);- // Week starts Monday, so the end of this week is Sunday the 2nd.- expect(endOfWeek.date.getMonth()).toBe(7);- expect(endOfWeek.date.getDate()).toBe(2);expect(oneWeek.date.getDate()).toBe(5);});- // On a Saturday the week ends tomorrow, so both land on Sunday morning.- it('drops a preset that duplicates an earlier one', () => {- const saturday = new Date(2026, 7, 1, 13, 0, 0);- const options = reminderDefaultOptions(saturday);- const labels = options.map((o) => o.displayText);-- expect(labels).toContain('Tomorrow');- expect(labels).not.toContain('End of week');- expect(new Set(options.map((o) => o.date.getTime())).size).toBe(- options.length- );+ // No two presets can currently land on the same instant, so this guards the+ // list as it grows rather than a case it has today.+ it('never offers the same instant under two labels', () => {+ for (const now of [+ new Date(2026, 7, 1, 13, 0, 0),+ new Date(2026, 7, 2, 20, 0, 0),+ wednesdayAfternoon,+ ]) {+ const options = reminderDefaultOptions(now);+ expect(new Set(options.map((o) => o.date.getTime())).size).toBe(+ options.length+ );+ }});- // Late on a Sunday, "End of week" has already gone by — offering it would- // just produce a 400 from the API.- it('drops entries that have already passed', () => {- const sundayEvening = new Date(2026, 7, 2, 20, 0, 0);- const labels = reminderDefaultOptions(sundayEvening).map(- (o) => o.displayText- );-- expect(labels).not.toContain('End of week');- expect(labels).toContain('In 1 hour');- expect(labels).toContain('Tomorrow');+ // The API rejects a firing that is not strictly in the future, and every+ // preset is now offset forward from `now` — so this holds whenever it runs.+ it('only ever offers times in the future', () => {+ for (const now of [new Date(2026, 7, 2, 23, 59, 0), wednesdayAfternoon]) {+ for (const option of reminderDefaultOptions(now)) {+ expect(option.date.getTime()).toBeGreaterThan(now.getTime());+ }+ }});it('describes each entry with a concrete date and time', () => {@@ -301,53 +296,6 @@ describe('REMINDER_DEFAULT_TIME', () => {});});-describe('formatReminderWhen', () => {- // Fixed instants rather than the wall clock, and the assertions compare- // against `toLocaleString` output rather than a hardcoded string, so the- // test states what is included and stays put across locales and timezones.- const now = new Date('2026-08-07T10:00:00.000Z').getTime();- const timeOnly = { hour: 'numeric', minute: '2-digit' } as const;- const withDate = { month: 'short', day: 'numeric', ...timeOnly } as const;-- it('omits the date three hours out', () => {- const date = new Date(now + 3 * 60 * 60 * 1000);- expect(formatReminderWhen(date, now)).toBe(- date.toLocaleString(undefined, timeOnly)- );- });-- it('omits the date just under a day out', () => {- const date = new Date(now + 24 * 60 * 60 * 1000 - 1);- expect(formatReminderWhen(date, now)).toBe(- date.toLocaleString(undefined, timeOnly)- );- });-- it('includes the date at exactly a day out', () => {- const date = new Date(now + 24 * 60 * 60 * 1000);- expect(formatReminderWhen(date, now)).toBe(- date.toLocaleString(undefined, withDate)- );- });-- it('includes the date a week out', () => {- const date = new Date(now + 7 * 24 * 60 * 60 * 1000);- expect(formatReminderWhen(date, now)).toBe(- date.toLocaleString(undefined, withDate)- );- });-- // The composer rejects past times before this runs, but a date that slipped- // past while the dialog sat open should still read as a time, not crash or- // sprout a date.- it('omits the date for an instant already past', () => {- const date = new Date(now - 60 * 1000);- expect(formatReminderWhen(date, now)).toBe(- date.toLocaleString(undefined, timeOnly)- );- });-});-describe('reminderEditOptions', () => {// A Wednesday afternoon, so every default entry is still ahead of "now".const wednesdayAfternoon = new Date(2026, 6, 29, 16, 37, 52, 400);@@ -361,7 +309,6 @@ describe('reminderEditOptions', () => {'In 1 hour','In 2 hours','Tomorrow',- 'End of week','In 1 week',]);});@@ -397,7 +344,7 @@ describe('reminderEditPatch', () => {const remindAt = new Date('2026-08-09T09:00:00.000Z');const original = {description: 'Chase the contract',- remindAt,+ schedule: onceSchedule(remindAt),completed: false,};@@ -407,7 +354,7 @@ describe('reminderEditPatch', () => {expect(reminderEditPatch(original, {description: 'Chase the contract',- remindAt: new Date(remindAt),+ schedule: onceSchedule(new Date(remindAt)),})).toBeUndefined();});@@ -416,7 +363,7 @@ describe('reminderEditPatch', () => {expect(reminderEditPatch(original, {description: 'Chase the signed contract',- remindAt: new Date(remindAt),+ schedule: onceSchedule(new Date(remindAt)),})).toEqual({ description: 'Chase the signed contract' });});@@ -427,7 +374,7 @@ describe('reminderEditPatch', () => {expect(reminderEditPatch(original, {description: 'Chase the contract',- remindAt: next,+ schedule: onceSchedule(next),})).toEqual({ schedule: { type: 'once', remindAt: next.toISOString() } });});@@ -436,7 +383,10 @@ describe('reminderEditPatch', () => {const next = new Date('2026-08-10T09:00:00.000Z');expect(- reminderEditPatch(original, { description: 'Follow up', remindAt: next })+ reminderEditPatch(original, {+ description: 'Follow up',+ schedule: onceSchedule(next),+ })).toEqual({description: 'Follow up',schedule: { type: 'once', remindAt: next.toISOString() },@@ -447,7 +397,7 @@ describe('reminderEditPatch', () => {expect(reminderEditPatch(original, {description: ' Chase the contract ',- remindAt: new Date(remindAt),+ schedule: onceSchedule(new Date(remindAt)),})).toBeUndefined();});@@ -458,7 +408,7 @@ describe('reminderEditPatch', () => {expect(reminderEditPatch(original, {description: ' ',- remindAt: new Date(remindAt),+ schedule: onceSchedule(new Date(remindAt)),})).toBeUndefined();});@@ -466,7 +416,7 @@ describe('reminderEditPatch', () => {it('caps an over-long description at the API limit', () => {const patch = reminderEditPatch(original, {description: 'a'.repeat(REMINDER_DESCRIPTION_MAX_LENGTH + 50),- remindAt: new Date(remindAt),+ schedule: onceSchedule(new Date(remindAt)),});expect(patch?.description).toHaveLength(REMINDER_DESCRIPTION_MAX_LENGTH);@@ -480,7 +430,7 @@ describe('reminderEditPatch', () => {expect(reminderEditPatch({ ...original, completed: true },- { description: 'Chase the contract', remindAt: next }+ { description: 'Chase the contract', schedule: onceSchedule(next) })).toEqual({schedule: { type: 'once', remindAt: next.toISOString() },@@ -493,7 +443,7 @@ describe('reminderEditPatch', () => {expect(reminderEditPatch({ ...original, completed: true },- { description: 'Follow up', remindAt: new Date(remindAt) }+ { description: 'Follow up', schedule: onceSchedule(new Date(remindAt)) })).toEqual({ description: 'Follow up' });});@@ -580,3 +530,274 @@ describe('resolveEditedDescription', () => {);});});++describe('repeatPartsFromDate', () => {+ // The backend's `cron` crate numbers day-of-week 1=Sunday, while JS+ // `Date.getDay()` numbers it 0=Sunday. Every value here is therefore one+ // higher than the JS one, and getting it wrong lands the reminder a day off —+ // which nobody notices until a week after it ships.+ it('maps each weekday to the backend numbering', () => {+ // 2026-08-09 is a Sunday, so this walks a full week from Sunday.+ const expected = [+ ['2026-08-09', '1'], // Sunday+ ['2026-08-10', '2'], // Monday+ ['2026-08-11', '3'],+ ['2026-08-12', '4'],+ ['2026-08-13', '5'],+ ['2026-08-14', '6'],+ ['2026-08-15', '7'], // Saturday+ ] as const;++ for (const [day, cronDow] of expected) {+ // Local noon, so the date cannot slide across a day boundary via UTC.+ const parts = repeatPartsFromDate(new Date(`${day}T12:00:00`));+ expect(parts.daysOfWeek).toEqual([cronDow]);+ }+ });++ it('takes the time of day and day of month from the date', () => {+ const parts = repeatPartsFromDate(new Date('2026-08-17T14:05:00'));++ expect(parts.time).toBe('14:05');+ expect(parts.dayOfMonth).toBe('17');+ });++ it('defaults to weekly', () => {+ expect(repeatPartsFromDate(new Date('2026-08-17T09:00:00')).frequency).toBe(+ 'week'+ );+ });+});++describe('defaultRepeatParts', () => {+ it('starts a new recurrence at the reminder morning default', () => {+ // Not the current time: a repeat picked at 4pm should still default to the+ // morning, the same way a bare date does.+ const parts = defaultRepeatParts(new Date('2026-08-17T16:42:00'));++ expect(parts.time).toBe(+ `${String(REMINDER_DEFAULT_TIME.hours).padStart(2, '0')}:${String(REMINDER_DEFAULT_TIME.minutes).padStart(2, '0')}`+ );+ });+});++describe('recurringSchedule', () => {+ it('builds a cron schedule carrying the timezone it was built in', () => {+ const schedule = recurringSchedule(+ // 2026-08-10 is a Monday, which is 2 in the backend's numbering.+ repeatPartsFromDate(new Date('2026-08-10T09:00:00')),+ 'America/Denver'+ );++ expect(schedule).toEqual({+ type: 'recurring',+ cron: '0 0 9 * * 2',+ timezone: 'America/Denver',+ });+ });++ it('builds a weekly cron on the date it was seeded from', () => {+ // 2026-08-10 is a Monday, which is 2 in the backend's numbering.+ const schedule = recurringSchedule(+ repeatPartsFromDate(new Date('2026-08-10T09:00:00'), 'week'),+ 'UTC'+ );++ expect(isRecurring(schedule) && schedule.cron).toBe('0 0 9 * * 2');+ });+});++describe('repeatPartsFromSchedule', () => {+ it('reads an existing recurrence back into picker parts', () => {+ const parts = repeatPartsFromSchedule({+ type: 'recurring',+ cron: '0 30 14 * * 2-6',+ timezone: 'UTC',+ });++ expect(parts.frequency).toBe('week');+ expect(parts.time).toBe('14:30');+ expect(parts.daysOfWeek).toEqual(['2', '3', '4', '5', '6']);+ });++ it('seeds from the firing when the reminder does not repeat yet', () => {+ // Turning a one-shot into a recurrence should start from the time it was+ // already set for, not from an unrelated default.+ const parts = repeatPartsFromSchedule({+ type: 'once',+ remindAt: new Date('2026-08-10T07:15:00').toISOString(),+ });++ expect(parts.time).toBe('07:15');+ });+});++describe('describeReminderSchedule', () => {+ it('describes a recurrence, capitalized for a row', () => {+ const described = describeReminderSchedule({+ type: 'recurring',+ cron: '0 0 9 * * 2-6',+ timezone: 'UTC',+ });++ expect(described).toMatch(/^Weekdays at /);+ });++ it('says nothing for a one-shot, whose date is already shown', () => {+ expect(+ describeReminderSchedule(onceSchedule(new Date('2026-08-10T09:00:00')))+ ).toBeUndefined();+ });+});++describe('sameSchedule', () => {+ const cron = (expr: string, timezone = 'UTC') =>+ ({ type: 'recurring', cron: expr, timezone }) as const;++ it('matches identical one-shots written differently', () => {+ // The same instant with a different offset and precision is not a change,+ // and treating it as one would re-send a schedule the API then rejects for+ // being in the past.+ expect(+ sameSchedule(+ { type: 'once', remindAt: '2026-08-10T09:00:00.000Z' },+ { type: 'once', remindAt: '2026-08-10T05:00:00-04:00' }+ )+ ).toBe(true);+ });++ it('separates different instants', () => {+ expect(+ sameSchedule(+ { type: 'once', remindAt: '2026-08-10T09:00:00.000Z' },+ { type: 'once', remindAt: '2026-08-10T10:00:00.000Z' }+ )+ ).toBe(false);+ });++ it('matches identical recurrences', () => {+ expect(sameSchedule(cron('0 0 9 * * *'), cron('0 0 9 * * *'))).toBe(true);+ });++ it('separates recurrences differing only by timezone', () => {+ // Same wall-clock, different instant — a real change.+ expect(+ sameSchedule(cron('0 0 9 * * *'), cron('0 0 9 * * *', 'Asia/Tokyo'))+ ).toBe(false);+ });++ it('separates the two kinds of schedule', () => {+ expect(+ sameSchedule(cron('0 0 9 * * *'), {+ type: 'once',+ remindAt: '2026-08-10T09:00:00.000Z',+ })+ ).toBe(false);+ });+});++describe('reminderEditPatch with recurrences', () => {+ const weekdays = {+ type: 'recurring' as const,+ cron: '0 0 9 * * 2-6',+ timezone: 'UTC',+ };+ const original = {+ description: 'Standup',+ schedule: weekdays,+ completed: false,+ };++ it('sends nothing when the recurrence is unchanged', () => {+ expect(+ reminderEditPatch(original, {+ description: 'Standup',+ schedule: weekdays,+ })+ ).toBeUndefined();+ });++ it('sends the new recurrence when it changes', () => {+ const daily = { ...weekdays, cron: '0 0 9 * * *' };++ expect(+ reminderEditPatch(original, { description: 'Standup', schedule: daily })+ ).toEqual({ schedule: daily });+ });++ it('turns a recurrence into a one-shot when asked', () => {+ const once = onceSchedule(new Date('2026-09-01T09:00:00.000Z'));++ expect(+ reminderEditPatch(original, { description: 'Standup', schedule: once })+ ).toEqual({ schedule: once });+ });++ it('clears the done flag when a finished series is given a new schedule', () => {+ const daily = { ...weekdays, cron: '0 0 9 * * *' };++ expect(+ reminderEditPatch(+ { ...original, completed: true },+ { description: 'Standup', schedule: daily }+ )+ ).toEqual({ schedule: daily, completed: false });+ });+});++describe('keeping a recurring schedule unchanged', () => {+ const weekdays = {+ type: 'recurring' as const,+ cron: '0 0 9 * * 2-6',+ timezone: 'America/New_York',+ };++ // The regression this guards is a data-loss one. The date list's lead row for+ // a recurring reminder says "Keep repeating"; if activating it submitted the+ // reminder's *next firing* instead of its schedule, one Enter would collapse+ // a standing series into a single day.+ it('sends no schedule when the existing recurrence is handed back', () => {+ const patch = reminderEditPatch(+ { description: 'Standup', schedule: weekdays, completed: false },+ { description: 'Standup', schedule: weekdays }+ );++ expect(patch).toBeUndefined();+ });++ it('sends only the description when a recurring reminder is renamed', () => {+ const patch = reminderEditPatch(+ { description: 'Standup', schedule: weekdays, completed: false },+ { description: 'Team standup', schedule: weekdays }+ );++ expect(patch).toEqual({ description: 'Team standup' });+ expect(patch?.schedule).toBeUndefined();+ });++ // What it would look like if the keep row ever regressed to submitting a date.+ it('treats the next firing as a real change, which is why keep must not send it', () => {+ const nextFiring = onceSchedule(new Date('2026-08-10T13:00:00.000Z'));++ expect(+ reminderEditPatch(+ { description: 'Standup', schedule: weekdays, completed: false },+ { description: 'Standup', schedule: nextFiring }+ )+ ).toEqual({ schedule: nextFiring });+ });++ it('does not treat a re-spelled equivalent cron as a change', () => {+ // `*` and the full list of days are the same schedule spelled two ways,+ // and which one a reminder carries depends on what last wrote it.+ const asDaily = { ...weekdays, cron: '0 0 9 * * *' };+ const asEveryWeekday = { ...weekdays, cron: '0 0 9 * * 1,2,3,4,5,6,7' };++ expect(+ reminderEditPatch(+ { description: 'Standup', schedule: asDaily, completed: false },+ { description: 'Standup', schedule: asEveryWeekday }+ )+ ).toBeUndefined();+ });+});diff --git a/apps/web/src/features/reminders/reminder-schedule.ts b/apps/web/src/features/reminders/reminder-schedule.tsindex b31967dfe9..bd4f65282b 100644--- a/apps/web/src/features/reminders/reminder-schedule.ts+++ b/apps/web/src/features/reminders/reminder-schedule.ts@@ -1,3 +1,12 @@+import {+ buildCron,+ type CronParts,+ describeCron,+ getDefaultTimezone,+ normalizeCron,+ parseCron,+ type ScheduleFrequency,+} from '@core/util/cron';import {type DateOption,formatDateWithContext,@@ -5,7 +14,7 @@ import {import type { EntityData } from '@entity';import type { ReminderSchedule } from '@service-storage/generated/schemas/reminderSchedule';import type { UpdateReminderRequest } from '@service-storage/generated/schemas/updateReminderRequest';-import { addDays, addHours, addWeeks, endOfWeek } from 'date-fns';+import { addDays, addHours, addWeeks } from 'date-fns';/*** The time of day a bare date resolves to.@@ -38,6 +47,155 @@ export function onceSchedule(date: Date): ReminderSchedule {return { type: 'once', remindAt: date.toISOString() };}+/**+ * A recurring schedule from picker parts, evaluated in the viewer's timezone.+ *+ * The zone travels with the cron because that is the only thing that makes+ * "every day at 9am" mean 9am: the backend evaluates the expression in it, so a+ * schedule built in Denver keeps firing at Denver's 9am after a move to Berlin.+ */+export function recurringSchedule(+ parts: CronParts,+ timezone: string = getDefaultTimezone()+): ReminderSchedule {+ return { type: 'recurring', cron: buildCron(parts), timezone };+}++/**+ * Cron day-of-week for a date, in the backend's 1=Sunday numbering.+ *+ * `Date.getDay()` is 0=Sunday, so every value is one higher here. Off-by-one+ * lands the reminder on the wrong day of the week, which is the kind of bug+ * that only shows up a week after it ships.+ */+function cronDayOfWeek(date: Date): string {+ return String(date.getDay() + 1);+}++/** `HH:MM` for a date, in local time — the form the cron helpers take. */+function timeOfDay(date: Date): string {+ return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;+}++/**+ * The recurrence to offer for a reminder the user has just dated.+ *+ * Seeded entirely from that date, so choosing "weekly" repeats on the weekday+ * they picked at the time they picked, and the repeat step needs no second time+ * input to state the obvious.+ */+export function repeatPartsFromDate(+ date: Date,+ frequency: ScheduleFrequency = 'week'+): CronParts {+ return {+ frequency,+ time: timeOfDay(date),+ daysOfWeek: [cronDayOfWeek(date)],+ dayOfMonth: String(date.getDate()),+ };+}++/**+ * What the repeat picker starts from for a brand-new recurrence: weekly on+ * today, at the same morning time a bare date would resolve to.+ */+export function defaultRepeatParts(now: Date = new Date()): CronParts {+ return repeatPartsFromDate(atDefaultTime(now));+}++/**+ * The schedule a soup row is on, rebuilt as the tagged union the API speaks.+ *+ * A row carries the schedule flattened into `scheduleType` plus the fields that+ * variant uses, and more than one surface needs it back in one piece — the+ * editor to diff against, the row to describe. Shared so they cannot disagree:+ * two call sites each picking their own fallback for an absent zone would+ * describe the same reminder differently, and the editor's diff would read the+ * substituted zone as a change and re-send it, moving when the reminder fires.+ *+ * `UTC` is the fallback rather than the viewer's zone, so the answer does not+ * depend on who is looking. It should be unreachable: the database requires a+ * timezone wherever a cron is set.+ */+export function scheduleFromRow(row: {+ scheduleType: 'once' | 'recurring';+ cron?: string;+ timezone?: string;+ nextRunAt: string | Date;+}): ReminderSchedule {+ if (row.scheduleType === 'recurring' && row.cron) {+ return {+ type: 'recurring',+ cron: row.cron,+ timezone: row.timezone ?? 'UTC',+ };+ }+ return { type: 'once', remindAt: new Date(row.nextRunAt).toISOString() };+}++/** Whether a schedule repeats, narrowed for the caller. */+export function isRecurring(+ schedule: ReminderSchedule+): schedule is Extract<ReminderSchedule, { type: 'recurring' }> {+ return schedule.type === 'recurring';+}++/**+ * The picker parts behind an existing recurring schedule, for editing one.+ *+ * Lossy in the same way {@link parseCron} is: a cron the picker cannot express+ * comes back as the nearest thing it can, because there is no UI for the rest.+ */+export function repeatPartsFromSchedule(schedule: ReminderSchedule): CronParts {+ return isRecurring(schedule)+ ? parseCron(schedule.cron)+ : repeatPartsFromDate(new Date(schedule.remindAt));+}++/**+ * A schedule in words, for a row that has to say when it fires.+ *+ * Recurring schedules read as their recurrence ("Every weekday at 9:00 AM")+ * since a single date says nothing useful about them. One-shots return+ * undefined: their next firing is already rendered as a date, and repeating it+ * in words would just be the same thing twice.+ */+export function describeReminderSchedule(+ schedule: ReminderSchedule+): string | undefined {+ if (!isRecurring(schedule)) return undefined;+ // The zone is part of the schedule, not decoration: "every day at 9:00 AM"+ // means a different instant in Denver than in Berlin, and a reminder built in+ // one and read in the other has to say which it fires by.+ const described = describeCron(parseCron(schedule.cron), schedule.timezone);+ return described.charAt(0).toUpperCase() + described.slice(1);+}++/** Whether two schedules are the same, so an unchanged one is not re-sent. */+export function sameSchedule(+ a: ReminderSchedule,+ b: ReminderSchedule+): boolean {+ if (a.type !== b.type) return false;+ if (isRecurring(a) && isRecurring(b)) {+ // Normalized, not compared literally: two spellings of the same schedule+ // must not read as an edit. Sending a schedule the owner did not change+ // is not harmless — the backend treats any schedule write as a reschedule+ // and clears the done flag with it.+ return (+ normalizeCron(a.cron) === normalizeCron(b.cron) &&+ a.timezone === b.timezone+ );+ }+ if (!isRecurring(a) && !isRecurring(b)) {+ // Compared as instants, not strings: the same moment can be written with a+ // different offset or precision.+ return new Date(a.remindAt).getTime() === new Date(b.remindAt).getTime();+ }+ return false;+}+/** The same instant, at `REMINDER_DEFAULT_TIME`. */function atDefaultTime(date: Date): Date {const result = new Date(date);@@ -81,11 +239,6 @@ export function reminderDefaultOptions(now: Date): DateOption[] {date: toWholeMinute(addHours(now, 2)),},{ id: 'tomorrow', label: 'Tomorrow', date: atDefaultTime(addDays(now, 1)) },- {- id: 'end-of-week',- label: 'End of week',- date: atDefaultTime(endOfWeek(now, { weekStartsOn: 1 })),- },{id: 'in-1-week',label: 'In 1 week',@@ -93,8 +246,9 @@ export function reminderDefaultOptions(now: Date): DateOption[] {},];- // On a Saturday `endOfWeek` (Sunday) is the same instant as "Tomorrow" at the- // morning default, which would offer the same time under two labels.+ // No two of the presets above can currently land on the same instant, but+ // they are a list people add to, and two entries offering one time under two+ // labels is the kind of thing nobody notices until it ships.const seen = new Set<number>();const unique = entries.filter(({ date }) => {const time = date.getTime();@@ -149,8 +303,12 @@ export function reminderEditOptions(current: Date, now: Date): DateOption[] {* past. Omitting it is also what lets an overdue reminder be renamed at all.*/export function reminderEditPatch(- original: { description: string; remindAt: Date; completed: boolean },- next: { description: string; remindAt: Date }+ original: {+ description: string;+ schedule: ReminderSchedule;+ completed: boolean;+ },+ next: { description: string; schedule: ReminderSchedule }): UpdateReminderRequest | undefined {const patch: UpdateReminderRequest = {};@@ -158,12 +316,14 @@ export function reminderEditPatch(if (description && description !== original.description) {patch.description = description;}- if (next.remindAt.getTime() !== original.remindAt.getTime()) {- patch.schedule = onceSchedule(next.remindAt);- // Giving a reminder that was marked done a new time is a request for it to- // fire again, and the dispatcher skips completed reminders — so without- // clearing the flag the time the user just picked would silently never- // arrive. A description-only edit leaves it alone.+ if (!sameSchedule(original.schedule, next.schedule)) {+ patch.schedule = next.schedule;+ // Giving a reminder that was marked done a new schedule is a request for it+ // to fire again. For a one-shot that is load-bearing: the dispatcher skips+ // a completed one, so without clearing the flag the time just picked would+ // silently never arrive. For a recurring one it is presentational — the+ // series keeps running either way — but a reminder that fires tomorrow+ // should not sit under Done today. A description-only edit leaves it alone.if (original.completed) patch.completed = false;}@@ -261,24 +421,3 @@ export function resolveEditedDescription(): string {return clampDescription(input) || fallback || current;}--const ONE_DAY_MS = 24 * 60 * 60 * 1000;--/** Confirmation text for a reminder that was just set.- *- * The date is dropped for anything inside the next day: "set for 1:08 PM" is- * what someone who just asked for three hours from now wants to read back, and- * "Aug 7, 1:08 PM" only adds a date they already know. Past the day boundary- * the date carries the meaning, so it stays.- */-export function formatReminderWhen(- date: Date,- now: number = Date.now()-): string {- const withinADay = date.getTime() - now < ONE_DAY_MS;- return date.toLocaleString(undefined, {- ...(withinADay ? {} : { month: 'short', day: 'numeric' }),- hour: 'numeric',- minute: '2-digit',- });-}diff --git a/apps/web/src/lib/core/util/cron.test.ts b/apps/web/src/lib/core/util/cron.test.tsnew file mode 100644index 0000000000..944cb49340--- /dev/null+++ b/apps/web/src/lib/core/util/cron.test.ts@@ -0,0 +1,370 @@+import { describe, expect, it } from 'vitest';++import {+ buildCron,+ type CronParts,+ DEFAULT_TIME,+ describeCron,+ isValidCronParts,+ isValidTime,+ normalizeCron,+ parseCron,+} from './cron';++/** Weekly on Monday and Wednesday at 09:00, in cron's 1=Sun numbering. */+const weekly: CronParts = {+ frequency: 'week',+ time: '09:00',+ daysOfWeek: ['2', '4'],+ dayOfMonth: '1',+};++/** Weekly with every day ticked, which is how "every day" is now said. */+const everyDay: CronParts = {+ frequency: 'week',+ time: '09:00',+ daysOfWeek: ['1', '2', '3', '4', '5', '6', '7'],+ dayOfMonth: '1',+};++const monthly: CronParts = {+ frequency: 'month',+ time: '14:30',+ daysOfWeek: ['2', '3', '4', '5', '6'],+ dayOfMonth: '15',+};++describe('buildCron', () => {+ it('emits six fields, since that is what the cron crate parses', () => {+ for (const parts of [everyDay, weekly, monthly]) {+ expect(buildCron(parts).split(' ')).toHaveLength(6);+ }+ });++ it('builds every day as the full list of days', () => {+ expect(buildCron(everyDay)).toBe('0 0 9 * * 1,2,3,4,5,6,7');+ });++ it('builds a weekly schedule from the selected days', () => {+ // 2=Mon, 4=Wed. Getting this numbering wrong shifts every weekly+ // schedule by a day, which is why it is asserted literally.+ expect(buildCron(weekly)).toBe('0 0 9 * * 2,4');+ });++ it('sorts the selected days so the same selection is one expression', () => {+ expect(buildCron({ ...weekly, daysOfWeek: ['4', '2'] })).toBe(+ '0 0 9 * * 2,4'+ );+ });++ it('builds a monthly schedule on the chosen day', () => {+ expect(buildCron(monthly)).toBe('0 30 14 15 * *');+ });++ it('falls back to the default time when the time is malformed', () => {+ const [, minute, hour] = buildCron({ ...everyDay, time: 'nonsense' }).split(+ ' '+ );+ const [defaultHour, defaultMinute] = DEFAULT_TIME.split(':').map(Number);+ expect(Number(hour)).toBe(defaultHour);+ expect(Number(minute)).toBe(defaultMinute);+ });++ it('falls back to the first of the month for an out-of-range day', () => {+ expect(buildCron({ ...monthly, dayOfMonth: '99' })).toBe('0 30 14 1 * *');+ });++ it('leaves day-of-week unconstrained when a weekly selection is empty', () => {+ // Better than emitting an empty field, which would not parse at all.+ expect(buildCron({ ...weekly, daysOfWeek: [] })).toBe('0 0 9 * * *');+ });+});++describe('parseCron', () => {+ it('round-trips everything buildCron produces', () => {+ for (const parts of [everyDay, weekly, monthly]) {+ const reparsed = parseCron(buildCron(parts));+ expect(reparsed.frequency).toBe(parts.frequency);+ expect(reparsed.time).toBe(parts.time);+ if (parts.frequency === 'week') {+ expect(reparsed.daysOfWeek).toEqual(parts.daysOfWeek);+ }+ if (parts.frequency === 'month') {+ expect(reparsed.dayOfMonth).toBe(parts.dayOfMonth);+ }+ }+ });++ it('reads an unconstrained day-of-week as every day of the week', () => {+ // There is no separate daily frequency: `*` and the full list are the same+ // schedule, and the picker only knows how to show the latter.+ const parts = parseCron('0 0 9 * * *');+ expect(parts.frequency).toBe('week');+ expect(parts.daysOfWeek).toEqual(['1', '2', '3', '4', '5', '6', '7']);+ });++ it('expands a day-of-week range', () => {+ const parts = parseCron('0 0 9 * * 2-6');+ expect(parts.frequency).toBe('week');+ expect(parts.daysOfWeek).toEqual(['2', '3', '4', '5', '6']);+ });++ it('expands a day-of-week list out of order', () => {+ expect(parseCron('0 0 9 * * 6,2').daysOfWeek).toEqual(['2', '6']);+ });++ it('accepts the seven-field form when the year constrains nothing', () => {+ const parts = parseCron('0 0 9 * * 2 *');+ expect(parts.frequency).toBe('week');+ expect(parts.daysOfWeek).toEqual(['2']);+ });++ it('falls back for a specific year, which the picker cannot show', () => {+ // "9am Mondays during 2026" is a real constraint with no control to express+ // it. Reading it as plain weekly would present it as firing forever, and+ // saving from that view would drop the year without saying so.+ const parts = parseCron('0 0 9 * * 2 2026');++ expect(parts.daysOfWeek).toEqual(['2', '3', '4', '5', '6']);+ // The time is still readable, and losing it as well would reset the hour+ // the reminder was actually set for.+ expect(parts.time).toBe('09:00');+ });++ it('keeps the time it could read even when the rest is unrepresentable', () => {+ // A specific month is not something the picker can express, but the time+ // still is — losing it too would silently reset the user's hour.+ const parts = parseCron('0 30 14 1 3 *');+ expect(parts.time).toBe('14:30');+ });++ it('falls back for a five-field expression', () => {+ // The conventional form, which the cron crate does not accept.+ const parts = parseCron('0 9 * * *');+ expect(parts.frequency).toBe('week');+ expect(parts.time).toBe(DEFAULT_TIME);+ });++ it('falls back for an unreadable day-of-week', () => {+ expect(parseCron('0 0 9 * * 9-2').frequency).toBe('week');+ expect(parseCron('0 0 9 * * mon').daysOfWeek).toEqual([+ '2',+ '3',+ '4',+ '5',+ '6',+ ]);+ });++ it('falls back for garbage', () => {+ expect(parseCron('').frequency).toBe('week');+ expect(parseCron('not a cron').time).toBe(DEFAULT_TIME);+ });+});++/**+ * `09:00` as the runtime's locale writes it.+ *+ * Derived rather than written out: `describeCron` formats through `Intl` with no+ * fixed locale — deliberately, so the viewer sees their own convention — so+ * hard-coding "9:00 AM" would fail on any runtime that writes "9:00 a.m.". What+ * these assertions are pinning is the frequency wording around the time, not+ * the time itself.+ */+const NINE_AM = new Intl.DateTimeFormat(undefined, {+ hour: 'numeric',+ minute: '2-digit',+}).format(new Date(2026, 0, 1, 9, 0));++describe('describeCron', () => {+ it('names the sets of days that have a name', () => {+ const week = (daysOfWeek: string[]) =>+ describeCron({ ...weekly, daysOfWeek });++ expect(week(['1', '2', '3', '4', '5', '6', '7'])).toBe(+ `every day at ${NINE_AM}`+ );+ expect(week(['2', '3', '4', '5', '6'])).toBe(`weekdays at ${NINE_AM}`);+ expect(week(['1', '7'])).toBe(`weekends at ${NINE_AM}`);+ });++ it('lists days that have no collective name', () => {+ expect(describeCron(weekly)).toBe(`Monday, Wednesday at ${NINE_AM}`);+ });++ it('ordinalizes the day of the month', () => {+ const on = (dayOfMonth: string) =>+ describeCron({ ...monthly, dayOfMonth, time: '09:00' });++ expect(on('1')).toBe(`1st of each month at ${NINE_AM}`);+ expect(on('2')).toBe(`2nd of each month at ${NINE_AM}`);+ expect(on('3')).toBe(`3rd of each month at ${NINE_AM}`);+ expect(on('4')).toBe(`4th of each month at ${NINE_AM}`);+ // The teens are the case a naive suffix rule gets wrong.+ expect(on('11')).toBe(`11th of each month at ${NINE_AM}`);+ expect(on('12')).toBe(`12th of each month at ${NINE_AM}`);+ expect(on('13')).toBe(`13th of each month at ${NINE_AM}`);+ expect(on('21')).toBe(`21st of each month at ${NINE_AM}`);+ });++ it('appends the timezone when given one', () => {+ expect(describeCron(everyDay, 'America/New_York')).toBe(+ `every day at ${NINE_AM} (America/New_York)`+ );+ });+});++describe('isValidTime', () => {+ it('accepts times in range', () => {+ for (const time of ['00:00', '09:00', '13:45', '23:59']) {+ expect(isValidTime(time)).toBe(true);+ }+ });++ // The shape check alone let these through, which meant the repeat picker+ // reported the schedule as valid, allowed it to be saved, and stored the+ // default time instead — the UI and the stored schedule disagreeing.+ it('rejects times out of range', () => {+ for (const time of ['24:00', '99:99', '12:60', '25:30']) {+ expect(isValidTime(time)).toBe(false);+ }+ });++ it('rejects anything that is not two digits and two digits', () => {+ for (const time of ['', '9:00', '09:0', 'nine', '09:00:00']) {+ expect(isValidTime(time)).toBe(false);+ }+ });+});++describe('isValidCronParts', () => {+ it('accepts each frequency at its defaults', () => {+ for (const parts of [everyDay, weekly, monthly]) {+ expect(isValidCronParts(parts)).toBe(true);+ }+ });++ it('rejects any frequency with an unusable time', () => {+ for (const parts of [everyDay, weekly, monthly]) {+ expect(isValidCronParts({ ...parts, time: '24:00' })).toBe(false);+ }+ });++ // `buildCron` maps an out-of-range day to the 1st, so without this the+ // summary would say one thing and the saved schedule do another.+ it('rejects a monthly day outside 1-31', () => {+ for (const dayOfMonth of ['0', '32', '99', '', 'x', '1.5']) {+ expect(isValidCronParts({ ...monthly, dayOfMonth })).toBe(false);+ }+ });++ it('accepts the edges of the month', () => {+ for (const dayOfMonth of ['1', '31']) {+ expect(isValidCronParts({ ...monthly, dayOfMonth })).toBe(true);+ }+ });++ // An empty weekly selection builds an every-day cron, which is the opposite+ // of what unticking your last day is asking for.+ it('rejects a weekly schedule with no days selected', () => {+ expect(isValidCronParts({ ...weekly, daysOfWeek: [] })).toBe(false);+ });++ it('ignores the day field the frequency does not use', () => {+ // Each frequency reads exactly one of them, so junk in the other is not a+ // reason to refuse a schedule the user can actually see.+ expect(isValidCronParts({ ...weekly, dayOfMonth: '99' })).toBe(true);+ expect(isValidCronParts({ ...monthly, daysOfWeek: [] })).toBe(true);+ });+});++describe('normalizeCron', () => {+ it('gives the two spellings of every day the same form', () => {+ // These are the same schedule, and a comparison that called them different+ // would read a re-save as an edit.+ expect(normalizeCron('0 0 9 * * 1,2,3,4,5,6,7')).toBe(+ normalizeCron('0 0 9 * * *')+ );+ });++ it('leaves a partial week alone', () => {+ expect(normalizeCron('0 0 9 * * 2,4')).toBe('0 0 9 * * 2,4');+ });++ it('is stable when applied twice', () => {+ for (const cron of ['0 0 9 * * *', '0 0 9 * * 2-6', '0 30 14 15 * *']) {+ expect(normalizeCron(normalizeCron(cron))).toBe(normalizeCron(cron));+ }+ });++ // Every expression the picker cannot express parses to the same weekly+ // fallback. Normalizing through that would make two unrelated schedules+ // compare equal — and an equality check answering "unchanged" about a real+ // change does not send the patch, silently discarding the user's edit.+ it('leaves an expression it cannot represent exactly as it was', () => {+ for (const cron of ['0 0 9 1 3 *', 'not a cron', '0 9 * * *', '']) {+ expect(normalizeCron(cron)).toBe(cron);+ }+ });++ it('keeps two different unrepresentable schedules distinct', () => {+ expect(normalizeCron('0 0 9 1 3 *')).not.toBe(normalizeCron('0 0 9 1 6 *'));+ });++ it('does not equate an unrepresentable schedule with the fallback it parses to', () => {+ // The specific collision that would swallow an edit: opening a March-only+ // reminder and saving it as weekdays has to register as a change.+ const marchOnly = '0 0 9 1 3 *';+ const weekdays = buildCron(parseCron(marchOnly));++ expect(normalizeCron(marchOnly)).not.toBe(normalizeCron(weekdays));+ });++ it('treats a year constraint as unrepresentable', () => {+ // The picker has no way to show a year, so rewriting the expression would+ // drop the constraint while reporting the schedule as unchanged.+ const yearly = '0 0 9 * * 2 2026';++ expect(normalizeCron(yearly)).toBe(yearly);+ });++ it('still normalizes a seven-field expression with an open year', () => {+ // `*` in the year field constrains nothing, so it stays representable.+ expect(normalizeCron('0 0 9 * * * *')).toBe('0 0 9 * * 1,2,3,4,5,6,7');+ });+});++describe('normalizeCron on fields the picker cannot express', () => {+ // Each of these is valid to the backend and none is something the picker can+ // show. Rewriting them would change a real schedule — and worse, make a+ // genuine edit normalize to the same string as the original, so the diff+ // reports "unchanged" and the patch is never sent.+ it('leaves an hour range alone', () => {+ // `toTimeValue` cannot read `9-17` and answers with the default, so without+ // a guard this normalized to plain 09:00 daily.+ expect(normalizeCron('0 0 9-17 * * *')).toBe('0 0 9-17 * * *');+ });++ it('leaves a seconds offset alone', () => {+ // `30 0 9 * * *` means 09:00:30. The picker only builds whole minutes.+ expect(normalizeCron('30 0 9 * * *')).toBe('30 0 9 * * *');+ });++ it('leaves minute and hour lists and steps alone', () => {+ for (const cron of ['0 0,30 9 * * *', '0 */15 9 * * *', '0 0 9,17 * * *']) {+ expect(normalizeCron(cron)).toBe(cron);+ }+ });++ it('keeps an hour range distinct from the time it would have collapsed to', () => {+ // The comparison this protects: a stored range and a draft rebuilt as a+ // single hour must not look identical.+ expect(normalizeCron('0 0 9-17 * * *')).not.toBe(+ normalizeCron('0 0 9 * * *')+ );+ });++ it('still normalizes plain in-range fields', () => {+ expect(normalizeCron('0 0 9 * * *')).toBe('0 0 9 * * 1,2,3,4,5,6,7');+ });+});diff --git a/apps/web/src/lib/core/util/cron.ts b/apps/web/src/lib/core/util/cron.tsnew file mode 100644index 0000000000..926716e8cf--- /dev/null+++ b/apps/web/src/lib/core/util/cron.ts@@ -0,0 +1,380 @@+/**+ * Cron expressions as the Rust backend reads them.+ *+ * Shared by every feature that lets someone build a repeating schedule —+ * automations and reminders both — so the two cannot drift on what `0 0 9 * * 2`+ * means. The backend parses these with the `cron` crate, which sets two+ * conventions worth stating up front:+ *+ * - Six fields, `sec min hour dayOfMonth month dayOfWeek`, not the conventional+ * five. A seventh optional `year` field is accepted on read.+ * - Day-of-week is **1-based starting at Sunday**: 1=Sun through 7=Sat. This is+ * not the JS `Date.getDay()` numbering, and mixing them up shifts every+ * weekly schedule by a day.+ */++/**+ * How often a schedule repeats.+ *+ * No daily option: a weekly schedule with every day selected is the same+ * thing, and the pickers let you say it that way. One fewer frequency to+ * render, and no expression that only one picker can express.+ */+export type ScheduleFrequency = 'week' | 'month';++/** Time of day a schedule fires when none was chosen, as `HH:MM`. */+export const DEFAULT_TIME = '09:00';++// Day-of-week values match the `cron` crate convention:+// 1 = Sun, 2 = Mon, 3 = Tue, 4 = Wed, 5 = Thu, 6 = Fri, 7 = Sat+export const WEEKDAY_OPTIONS = [+ { value: '1', label: 'Sun', fullLabel: 'Sunday' },+ { value: '2', label: 'Mon', fullLabel: 'Monday' },+ { value: '3', label: 'Tue', fullLabel: 'Tuesday' },+ { value: '4', label: 'Wed', fullLabel: 'Wednesday' },+ { value: '5', label: 'Thu', fullLabel: 'Thursday' },+ { value: '6', label: 'Fri', fullLabel: 'Friday' },+ { value: '7', label: 'Sat', fullLabel: 'Saturday' },+];++const DOW_VALUES = WEEKDAY_OPTIONS.map((option) => option.value);++/** Monday to Friday, the default weekly selection. */+export const DEFAULT_WEEKDAYS = ['2', '3', '4', '5', '6'];++/** The parts of a cron expression a picker actually edits. */+export type CronParts = {+ frequency: ScheduleFrequency;+ /** `HH:MM`, 24-hour. */+ time: string;+ /** Day-of-week values in the cron crate's 1-7 numbering. Weekly only. */+ daysOfWeek: string[];+ /** 1-31. Monthly only. */+ dayOfMonth: string;+};++/** The IANA zone the browser is in, which is what a local time is relative to. */+export function getDefaultTimezone(): string {+ return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';+}++/**+ * Whether `value` is a real `HH:MM` time, in range as well as in shape.+ *+ * The range check is the point: `buildCron` silently falls back to+ * {@link DEFAULT_TIME} for anything it cannot use, so a picker that accepted+ * `99:99` would report the schedule as valid, let it be saved, and store a+ * different time than the one on screen.+ */+export function isValidTime(value: string): boolean {+ const match = value.match(/^(\d{2}):(\d{2})$/);+ if (!match) return false;++ const [, hour, minute] = match;+ const h = Number(hour);+ const m = Number(minute);+ // Both bounds, though the digits-only pattern already rules out negatives.+ // A range check that only looks one way invites the next reader to widen the+ // pattern and not notice the other half was never there.+ return h >= 0 && h <= 23 && m >= 0 && m <= 59;+}++/**+ * Whether these parts describe a schedule that will be stored as shown.+ *+ * Every field {@link buildCron} would quietly substitute a fallback for, so a+ * picker can refuse to save rather than save something else. A weekly schedule+ * with no days selected builds an every-day cron, which is not what clearing+ * the last day is asking for.+ */+export function isValidCronParts(parts: CronParts): boolean {+ if (!isValidTime(parts.time)) return false;+ if (parts.frequency === 'week') {+ // Every value checked, not just the count: a stray day outside 1-7 would+ // build an expression the backend rejects, and "at least one selected" is+ // only the constraint the buttons happen to enforce today.+ return (+ parts.daysOfWeek.length > 0 &&+ parts.daysOfWeek.every((day) => DOW_VALUES.includes(day))+ );+ }+ const day = Number(parts.dayOfMonth);+ return Number.isInteger(day) && day >= 1 && day <= 31;+}++/** `HH:MM` from separate fields, falling back on anything out of range. */+function toTimeValue(hour: string, minute: string): string {+ const safeHour = Number(hour);+ const safeMinute = Number(minute);+ if (+ Number.isNaN(safeHour) ||+ Number.isNaN(safeMinute) ||+ safeHour < 0 ||+ safeHour > 23 ||+ safeMinute < 0 ||+ safeMinute > 59+ ) {+ return DEFAULT_TIME;+ }++ return `${String(safeHour).padStart(2, '0')}:${String(safeMinute).padStart(2, '0')}`;+}++/** `09:00` as the viewer's locale writes it, e.g. `9:00 AM`. */+export function formatTimeLabel(value: string): string {+ if (!isValidTime(value)) return value;+ const [hour, minute] = value.split(':').map(Number);+ const date = new Date(2026, 0, 1, hour, minute);+ return new Intl.DateTimeFormat(undefined, {+ hour: 'numeric',+ minute: '2-digit',+ }).format(date);+}++/** A day-of-week selection in words, collapsing the sets that have a name. */+function formatDayList(daysOfWeek: string[]): string {+ if (daysOfWeek.length === 0) return 'no days';+ const sorted = [...daysOfWeek].sort(+ (a, b) => DOW_VALUES.indexOf(a) - DOW_VALUES.indexOf(b)+ );+ if (sorted.length === 7) return 'every day';+ if (+ sorted.length === 5 &&+ sorted.every((d) => DEFAULT_WEEKDAYS.includes(d))+ ) {+ return 'weekdays';+ }+ if (sorted.length === 2 && sorted.includes('1') && sorted.includes('7')) {+ return 'weekends';+ }+ return sorted+ .map((d) => WEEKDAY_OPTIONS.find((opt) => opt.value === d)?.fullLabel)+ .filter(Boolean)+ .join(', ');+}++function nthSuffix(n: number): string {+ const tens = n % 100;+ if (tens >= 11 && tens <= 13) return 'th';+ switch (n % 10) {+ case 1:+ return 'st';+ case 2:+ return 'nd';+ case 3:+ return 'rd';+ default:+ return 'th';+ }+}++/**+ * A schedule in words, e.g. `weekdays at 9:00 AM`.+ *+ * Lower-case and un-punctuated so callers can drop it into their own sentence;+ * capitalize at the call site if it stands alone. `timezone` is appended in+ * parentheses when given, for surfaces where the zone is not obvious.+ */+export function describeCron(parts: CronParts, timezone?: string): string {+ const timeLabel = formatTimeLabel(parts.time);+ const zone = timezone ? ` (${timezone})` : '';++ if (parts.frequency === 'week') {+ return `${formatDayList(parts.daysOfWeek)} at ${timeLabel}${zone}`;+ }++ const day = Number(parts.dayOfMonth);+ if (Number.isInteger(day) && day >= 1 && day <= 31) {+ return `${day}${nthSuffix(day)} of each month at ${timeLabel}${zone}`;+ }+ return `each month at ${timeLabel}${zone}`;+}++/**+ * Expand a day-of-week field like `2,4,6` or `2-6` into single values.+ *+ * Returns `[]` when any part of the expression cannot be read, so the caller+ * falls back to defaults rather than silently dropping the days it understood.+ */+function expandDowExpression(expr: string): string[] {+ const parts = expr.split(',');+ const set = new Set<string>();+ for (const raw of parts) {+ const part = raw.trim();+ if (/^[1-7]$/.test(part)) {+ set.add(part);+ continue;+ }+ const range = part.match(/^([1-7])-([1-7])$/);+ if (range) {+ const [, lo, hi] = range;+ const loN = Number(lo);+ const hiN = Number(hi);+ if (loN <= hiN) {+ for (let n = loN; n <= hiN; n++) set.add(String(n));+ continue;+ }+ }+ return [];+ }+ return [...set].sort((a, b) => DOW_VALUES.indexOf(a) - DOW_VALUES.indexOf(b));+}++/** The parts a picker should start from, for anything unreadable. */+function fallbackParts(time: string = DEFAULT_TIME): CronParts {+ return {+ frequency: 'week',+ time,+ daysOfWeek: [...DEFAULT_WEEKDAYS],+ dayOfMonth: '1',+ };+}++/**+ * Read a cron expression back into the parts a picker edits.+ *+ * Lossy by design: this only recognizes the shapes {@link buildCron} produces,+ * and anything else falls back to a sane weekly default rather than throwing.+ * A schedule written by hand may therefore come back as something simpler than+ * what it says — the picker cannot represent it either way.+ *+ * `dayOfMonth: '*'` with `dayOfWeek: '*'` reads as `day`, the most specific+ * frequency that describes it. Callers that have no daily option should map it+ * to a weekly schedule with every day selected, which is the same expression.+ */+export function parseCron(cron: string): CronParts {+ return interpretCron(cron).parts;+}++/**+ * A parse, plus whether the expression was one the pickers can actually say.+ *+ * The distinction matters to anything comparing two expressions: every+ * unrepresentable cron parses to the *same* fallback, so treating those parses+ * as canonical would make two genuinely different schedules look identical.+ */+type CronReading = { parts: CronParts; representable: boolean };++function unrepresentable(time?: string): CronReading {+ return { parts: fallbackParts(time), representable: false };+}++/**+ * Whether a cron field is a single plain number in range.+ *+ * Ranges (`9-17`), lists (`0,30`) and steps (`*/15`) are all valid to the+ * backend and none of them are something the picker can show, so they are+ * rejected here rather than read as whichever number happens to parse first.+ */+function isPlainCronNumber(field: string, min: number, max: number): boolean {+ if (!/^\d+$/.test(field)) return false;+ const value = Number(field);+ return value >= min && value <= max;+}++function interpretCron(cron: string): CronReading {+ const fields = cron.trim().split(/\s+/);+ // Six fields (`sec min hour dom mon dow`), or seven with a trailing year.+ if (fields.length !== 6 && fields.length !== 7) return unrepresentable();++ const [second, minute, hour, dayOfMonth, month, dayOfWeek, year] = fields;+ const time = toTimeValue(hour, minute);++ // Every field the picker cannot express has to be reported, not just the+ // obvious ones. `toTimeValue` answers with the default for anything it cannot+ // read, so a range like `9-17` would otherwise pass as representable with the+ // hour silently reset to 09:00 — and `normalizeCron` would then rewrite a+ // real schedule into a different one, which is exactly what makes a genuine+ // edit compare equal and never get sent.+ if (!isPlainCronNumber(second, 0, 59)) return unrepresentable(time);+ if (!isPlainCronNumber(minute, 0, 59)) return unrepresentable(time);+ if (!isPlainCronNumber(hour, 0, 23)) return unrepresentable(time);++ // Seconds are the owner's — `30 0 9 * * *` means 09:00:30 — and the picker+ // only builds whole minutes, so anything else is not ours to rewrite.+ if (Number(second) !== 0) return unrepresentable(time);++ // A year constraint is a real part of the schedule and the picker has no way+ // to show it, so an expression carrying one is not ours to rewrite.+ if (year !== undefined && year !== '*') return unrepresentable(time);+ if (month !== '*') return unrepresentable(time);++ if (dayOfMonth === '*') {+ if (dayOfWeek === '*') {+ // Every day, said the way the picker says it.+ return {+ parts: {+ frequency: 'week',+ time,+ daysOfWeek: [...DOW_VALUES],+ dayOfMonth: '1',+ },+ representable: true,+ };+ }+ const days = expandDowExpression(dayOfWeek);+ if (days.length > 0) {+ return {+ parts: { frequency: 'week', time, daysOfWeek: days, dayOfMonth: '1' },+ representable: true,+ };+ }+ return unrepresentable(time);+ }++ // Monthly: a specific day-of-month with no day-of-week constraint.+ if (dayOfWeek === '*' && /^(?:[1-9]|[12]\d|3[01])$/.test(dayOfMonth)) {+ return {+ parts: {+ frequency: 'month',+ time,+ daysOfWeek: [...DEFAULT_WEEKDAYS],+ dayOfMonth,+ },+ representable: true,+ };+ }++ return unrepresentable(time);+}++/**+ * A cron expression in the one form the pickers write it.+ *+ * `0 0 9 * * *` and `0 0 9 * * 1,2,3,4,5,6,7` are the same schedule spelled two+ * ways, and which one you hold depends on what last wrote it. Callers comparing+ * two expressions for "did this change?" want them to agree, since a difference+ * that is only spelling still reads as an edit — and on a reminder an edit+ * resets state the owner cares about.+ *+ * Both spellings parse to the same parts, so rebuilding is the whole job.+ */+export function normalizeCron(cron: string): string {+ const { parts, representable } = interpretCron(cron);++ // Anything the pickers cannot express is returned untouched. Every such+ // expression parses to the same fallback, so normalizing them would make two+ // different schedules compare equal — and a comparison that says "unchanged"+ // about a real change silently discards the edit.+ return representable ? buildCron(parts) : cron;+}++/** Build the six-field expression the backend expects. */+export function buildCron(parts: CronParts): string {+ const [hour, minute] = (isValidTime(parts.time) ? parts.time : DEFAULT_TIME)+ .split(':')+ .map((value) => Number(value));++ if (parts.frequency === 'week') {+ const days = parts.daysOfWeek.length+ ? [...parts.daysOfWeek]+ .sort((a, b) => DOW_VALUES.indexOf(a) - DOW_VALUES.indexOf(b))+ .join(',')+ : '*';+ return `0 ${minute} ${hour} * * ${days}`;+ }++ const day = Number(parts.dayOfMonth);+ const safeDay = Number.isInteger(day) && day >= 1 && day <= 31 ? day : 1;+ return `0 ${minute} ${hour} ${safeDay} * *`;+}diff --git a/apps/web/src/lib/queries/notification/user-notifications.ts b/apps/web/src/lib/queries/notification/user-notifications.tsindex 6dc0413e72..dd68ece36b 100644--- a/apps/web/src/lib/queries/notification/user-notifications.ts+++ b/apps/web/src/lib/queries/notification/user-notifications.ts@@ -941,6 +941,59 @@ export function restoreUserNotifications(notifications: NotificationItem[]) {});}+/** The firing a reminder notification was written for, when it records one. */+function reminderFiringOf(notification: NotificationItem): number | undefined {+ const metadata = notification.notification_metadata;+ if (metadata?.tag !== 'reminder') return undefined;+ const { scheduledFor } = metadata.content;+ if (!scheduledFor) return undefined;+ const at = new Date(scheduledFor).getTime();+ return Number.isNaN(at) ? undefined : at;+}++/**+ * Whether `existing` is an earlier firing of the reminder `arriving` is for.+ *+ * A recurring reminder produces one notification per firing, all pointing at+ * the same reminder. The two surfaces deliberately differ in what they do with+ * that, and it is worth stating plainly because the code pulls both ways:+ *+ * - **Push alerts are per firing.** The APNS collapse key includes the firing,+ * so today's lock-screen alert does not replace yesterday's unread one.+ * - **The notification list keeps one row per reminder.** A month away should+ * not return thirty identical "standup" rows to work through; the outstanding+ * firing is the one that matters.+ *+ * The dispatcher enforces the second server-side by retracting earlier firings+ * as the next is delivered. That delete has no realtime event, and the arriving+ * notification is merged into the cache without a refetch, so nothing here+ * would otherwise notice — this is what keeps the two sides agreeing.+ *+ * Matched on the firing rather than on the reminder alone, so a redelivery of+ * the *same* firing arriving under a fresh notification id replaces its twin+ * instead of being treated as a new occurrence, and a row from a firing later+ * than the arriving one is left alone.+ */+function isSupersededReminder(+ existing: NotificationItem,+ arriving: NotificationItem+): boolean {+ if (arriving.entity_type !== 'reminder') return false;+ if (existing.entity_type !== 'reminder') return false;+ if (existing.entity_id !== arriving.entity_id) return false;+ // Same notification, not a superseded one — that case is handled as a+ // duplicate insert.+ if (existing.id === arriving.id) return false;++ const existingFiring = reminderFiringOf(existing);+ const arrivingFiring = reminderFiringOf(arriving);+ // Either side predates the firing being recorded, so there is nothing to+ // compare: fall back to one-row-per-reminder, which is the policy anyway.+ if (existingFiring === undefined || arrivingFiring === undefined) return true;++ return existingFiring <= arrivingFiring;+}+export function optimisticInsertNotification(notification: UnifiedNotification) {@@ -959,6 +1012,30 @@ export function optimisticInsertNotification();if (exists) return data;+ // Clear the firing this one replaces before inserting, so a daily reminder+ // shows one row rather than one per day since the user last looked.+ //+ // Retired from `unconfirmedInserts` as well as dropped from the pages. A+ // superseded firing that arrived over the websocket is still tracked+ // there, and `reapplyUnconfirmedInserts` re-prepends anything it finds+ // missing from the pages — so removing it here alone would put it back on+ // the next query success and leave it sitting beside its replacement.+ const superseded = data.pages.flatMap((page) =>+ page.items.filter((n) => isSupersededReminder(n, item)).map((n) => n.id)+ );+ if (superseded.length > 0) {+ retireUnconfirmedInserts(superseded);+ const ids = new Set(superseded);+ data = {+ ...data,+ pages: data.pages.map((page) =>+ page.items.some((n) => ids.has(n.id))+ ? { ...page, items: page.items.filter((n) => !ids.has(n.id)) }+ : page+ ),+ };+ }+return {...data,pages: data.pages.map((page, index) =>diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.tsindex 4c692282ff..a9e0746698 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts@@ -177,6 +177,7 @@ export * from './realtimeNotifTaggedContentValueAllOfNotificationMetadata';export * from './realtimeNotifTaggedContentValueAllOfSenderId';export * from './realtimeNotifTaggedContentValueAllOfViewedAt';export * from './reminderMetadata';+export * from './reminderMetadataScheduledFor';export * from './repliedToDocumentCommentThreadMetadata';export * from './repliedToDocumentCommentThreadMetadataFileType';export * from './repliedToDocumentCommentThreadMetadataSenderProfilePictureUrl';diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/reminderMetadata.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/reminderMetadata.tsindex 39e3ca50f1..71de7924cf 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/reminderMetadata.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/reminderMetadata.ts@@ -4,6 +4,7 @@* notification_service* OpenAPI spec version: 0.1.0*/+import type { ReminderMetadataScheduledFor } from './reminderMetadataScheduledFor';/*** Metadata for a reminder the user set for themselves coming due.@@ -22,4 +23,14 @@ export interface ReminderMetadata {description: string;/** The reminder that fired. */reminderId: string;+ /** Which firing this is — the occurrence the reminder came due for.++What distinguishes two firings of the same recurring reminder, which are+otherwise identical: same id, same description. The collapse key is+built from it, so without it Tuesday's alert would replace Monday's+unread one on the lock screen.++Optional because notifications written before recurring dispatch existed+have no such field, and they still have to read back. */+ scheduledFor?: ReminderMetadataScheduledFor;}diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/reminderMetadataScheduledFor.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/reminderMetadataScheduledFor.tsnew file mode 100644index 0000000000..2954b23fa3--- /dev/null+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/reminderMetadataScheduledFor.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Which firing this is — the occurrence the reminder came due for.++What distinguishes two firings of the same recurring reminder, which are+otherwise identical: same id, same description. The collapse key is+built from it, so without it Tuesday's alert would replace Monday's+unread one on the lock screen.++Optional because notifications written before recurring dispatch existed+have no such field, and they still have to read back.+ */+export type ReminderMetadataScheduledFor = string | null;diff --git a/apps/web/src/lib/service-clients/service-notification/generated/zod.ts b/apps/web/src/lib/service-clients/service-notification/generated/zod.tsindex 0908b77c2e..1c108bd55a 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/zod.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/zod.ts@@ -696,6 +696,12 @@ export const listTypedNotificationsResponse = zodreminderId: zod.uuid().describe('The reminder that fired.'),+ scheduledFor: zod.iso+ .datetime({})+ .nullish()+ .describe(+ "Which firing this is — the occurrence the reminder came due for.\n\nWhat distinguishes two firings of the same recurring reminder, which are\notherwise identical: same id, same description. The collapse key is\nbuilt from it, so without it Tuesday's alert would replace Monday's\nunread one on the lock screen.\n\nOptional because notifications written before recurring dispatch existed\nhave no such field, and they still have to read back."+ ),}).describe('Metadata for a reminder the user set for themselves coming due.\n\nThere is no sender: a reminder is self-set, so the dispatcher sends it with\n`sender_id: None` (a recipient who is also the sender is filtered out of\ntheir own notification). Every formatter here must therefore work without\none.\n\nThe associated entity, when there is one, lives on the notification row\nrather than in here, and clients resolve its name from that — so the\ndispatcher does not have to look up a name across five entity types.'@@ -2046,6 +2052,12 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zodreminderId: zod.uuid().describe('The reminder that fired.'),+ scheduledFor: zod.iso+ .datetime({})+ .nullish()+ .describe(+ "Which firing this is — the occurrence the reminder came due for.\n\nWhat distinguishes two firings of the same recurring reminder, which are\notherwise identical: same id, same description. The collapse key is\nbuilt from it, so without it Tuesday's alert would replace Monday's\nunread one on the lock screen.\n\nOptional because notifications written before recurring dispatch existed\nhave no such field, and they still have to read back."+ ),}).describe('Metadata for a reminder the user set for themselves coming due.\n\nThere is no sender: a reminder is self-set, so the dispatcher sends it with\n`sender_id: None` (a recipient who is also the sender is filtered out of\ntheir own notification). Every formatter here must therefore work without\none.\n\nThe associated entity, when there is one, lives on the notification row\nrather than in here, and clients resolve its name from that — so the\ndispatcher does not have to look up a name across five entity types.'@@ -3390,6 +3402,12 @@ export const getTypedNotificationsByEventItemIdResponse = zodreminderId: zod.uuid().describe('The reminder that fired.'),+ scheduledFor: zod.iso+ .datetime({})+ .nullish()+ .describe(+ "Which firing this is — the occurrence the reminder came due for.\n\nWhat distinguishes two firings of the same recurring reminder, which are\notherwise identical: same id, same description. The collapse key is\nbuilt from it, so without it Tuesday's alert would replace Monday's\nunread one on the lock screen.\n\nOptional because notifications written before recurring dispatch existed\nhave no such field, and they still have to read back."+ ),}).describe('Metadata for a reminder the user set for themselves coming due.\n\nThere is no sender: a reminder is self-set, so the dispatcher sends it with\n`sender_id: None` (a recipient who is also the sender is filtered out of\ntheir own notification). Every formatter here must therefore work without\none.\n\nThe associated entity, when there is one, lives on the notification row\nrather than in here, and clients resolve its name from that — so the\ndispatcher does not have to look up a name across five entity types.'@@ -4707,6 +4725,12 @@ export const getTypedNotificationByIdResponse = zod.string().describe('What the user asked to be reminded about.'),reminderId: zod.uuid().describe('The reminder that fired.'),+ scheduledFor: zod.iso+ .datetime({})+ .nullish()+ .describe(+ "Which firing this is — the occurrence the reminder came due for.\n\nWhat distinguishes two firings of the same recurring reminder, which are\notherwise identical: same id, same description. The collapse key is\nbuilt from it, so without it Tuesday's alert would replace Monday's\nunread one on the lock screen.\n\nOptional because notifications written before recurring dispatch existed\nhave no such field, and they still have to read back."+ ),}).describe('Metadata for a reminder the user set for themselves coming due.\n\nThere is no sender: a reminder is self-set, so the dispatcher sends it with\n`sender_id: None` (a recipient who is also the sender is filtered out of\ntheir own notification). Every formatter here must therefore work without\none.\n\nThe associated entity, when there is one, lives on the notification row\nrather than in here, and clients resolve its name from that — so the\ndispatcher does not have to look up a name across five entity types.'diff --git a/apps/web/src/lib/service-clients/service-notification/openapi.json b/apps/web/src/lib/service-clients/service-notification/openapi.jsonindex 4bee79a2d4..dd56928e81 100644--- a/apps/web/src/lib/service-clients/service-notification/openapi.json+++ b/apps/web/src/lib/service-clients/service-notification/openapi.json@@ -2499,6 +2499,11 @@"type": "string","format": "uuid","description": "The reminder that fired."+ },+ "scheduledFor": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "Which firing this is — the occurrence the reminder came due for.\n\nWhat distinguishes two firings of the same recurring reminder, which are\notherwise identical: same id, same description. The collapse key is\nbuilt from it, so without it Tuesday's alert would replace Monday's\nunread one on the lock screen.\n\nOptional because notifications written before recurring dispatch existed\nhave no such field, and they still have to read back."}}},diff --git a/crates/graphql_notification/src/notification_event.rs b/crates/graphql_notification/src/notification_event.rsindex 6703fc558d..02caa6f56a 100644--- a/crates/graphql_notification/src/notification_event.rs+++ b/crates/graphql_notification/src/notification_event.rs@@ -756,6 +756,15 @@ impl GraphqlReminderMetadata {async fn description(&self) -> &str {&self.0.description}++ /// Which firing this notification is for, in RFC 3339 format.+ ///+ /// The counterpart of a calendar alarm's `occurrenceKey`: it is what tells+ /// two notifications from the same recurring reminder apart. Absent on+ /// notifications written before recurring dispatch existed.+ async fn scheduled_for(&self) -> Option<String> {+ self.0.scheduled_for.map(|timestamp| timestamp.to_rfc3339())+ }}/// GraphQL wrapper for calendar event reminder metadata.diff --git a/crates/macro_db_client/migrations/20260817202058_recurring_reminders_ignore_completion.sql b/crates/macro_db_client/migrations/20260817202058_recurring_reminders_ignore_completion.sqlnew file mode 100644index 0000000000..6a85e9324b--- /dev/null+++ b/crates/macro_db_client/migrations/20260817202058_recurring_reminders_ignore_completion.sql@@ -0,0 +1,16 @@+-- Completion is per-firing for a recurring reminder, not per-series.+--+-- Marking a reminder done means "I have dealt with the firing in front of me".+-- For a one-shot that is the end of it, so a completed one never comes due+-- again. For a recurring one the series carries on — ending it is what deleting+-- is for — so `completed_at` must not remove it from the dispatcher's reach.+--+-- The old index could not serve that query: it excluded every completed row, so+-- a daily reminder someone had ticked off would fall out of the index and the+-- minutely sweep would have to scan the table to find it.+CREATE INDEX IF NOT EXISTS reminder_due_v2_idx+ ON reminder (next_run_at)+ WHERE enabled AND (cron IS NOT NULL OR completed_at IS NULL);++-- Superseded by the index above, which covers everything it did.+DROP INDEX IF EXISTS reminder_due_idx;diff --git a/crates/model_notifications/src/metadata.rs b/crates/model_notifications/src/metadata.rsindex e55195694a..f98c8c2128 100644--- a/crates/model_notifications/src/metadata.rs+++ b/crates/model_notifications/src/metadata.rs@@ -1351,6 +1351,18 @@ pub struct ReminderMetadata {pub reminder_id: Uuid,/// What the user asked to be reminded about.pub description: String,+ /// Which firing this is — the occurrence the reminder came due for.+ ///+ /// What distinguishes two firings of the same recurring reminder, which are+ /// otherwise identical: same id, same description. The collapse key is+ /// built from it, so without it Tuesday's alert would replace Monday's+ /// unread one on the lock screen.+ ///+ /// Optional because notifications written before recurring dispatch existed+ /// have no such field, and they still have to read back.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schema(value_type = Option<String>, format = DateTime)]+ pub scheduled_for: Option<DateTime<Utc>>,}impl Notification for ReminderMetadata {@@ -1393,7 +1405,16 @@ impl NotificationExtIos for ReminderMetadata {// same firing should replace the alert, but a reminder is not "about"// the entity in the way a mention is, so two reminders on one document// stay two alerts.- NotifCollapseKey::new(Self::TYPE_NAME).append(&self.reminder_id.to_string())+ //+ // The firing is part of the key for the same reason. Two occurrences of+ // a daily reminder share an id and a description, so on the id alone+ // today's alert would quietly replace yesterday's unread one — which is+ // right for a redelivery and wrong for a new day.+ let key = NotifCollapseKey::new(Self::TYPE_NAME).append(&self.reminder_id.to_string());+ match self.scheduled_for {+ Some(scheduled_for) => key.append(&scheduled_for.timestamp().to_string()),+ None => key,+ }}fn as_apns<'a>(diff --git a/crates/model_notifications/src/metadata/test.rs b/crates/model_notifications/src/metadata/test.rsindex 85d686ff43..0ad81ddf62 100644--- a/crates/model_notifications/src/metadata/test.rs+++ b/crates/model_notifications/src/metadata/test.rs@@ -742,6 +742,7 @@ fn reminder_body_is_bounded_for_the_push_payload() {let metadata = ReminderMetadata {reminder_id: Uuid::parse_str("22222222-2222-4222-8222-222222222222").unwrap(),description: "🎉".repeat(2_000),+ scheduled_for: None,};let body = metadata.format_body(None).unwrap();@@ -751,22 +752,62 @@ fn reminder_body_is_bounded_for_the_push_payload() {assert!(body.len() < 4_096, "must fit inside the APNS payload limit");}-#[test]-fn reminder_collapse_key_is_per_reminder_not_per_entity() {+/// A reminder metadata collapse key, hashed for comparison.+fn reminder_key(id: &str, scheduled_for: Option<DateTime<Utc>>) -> String {let entity = EntityType::Document.with_entity_str("doc-1");- let key = |id: &str| {- ReminderMetadata {- reminder_id: Uuid::parse_str(id).unwrap(),- description: "x".to_string(),- }- .collapse_key(&entity)- .into_hashed()- .into_inner()- };+ ReminderMetadata {+ reminder_id: Uuid::parse_str(id).unwrap(),+ description: "x".to_string(),+ scheduled_for,+ }+ .collapse_key(&entity)+ .into_hashed()+ .into_inner()+}++/// The 09:00 firing on the given August day, as a daily reminder would produce.+fn firing(day: u32) -> Option<DateTime<Utc>> {+ Some(utc_datetime(&format!("2026-08-{day:02}T09:00:00Z")))+}+#[test]+fn reminder_collapse_key_is_per_reminder_not_per_entity() {// Two reminders on the same document must not collapse into one alert.assert_ne!(- key("22222222-2222-4222-8222-222222222222"),- key("33333333-3333-4333-8333-333333333333")+ reminder_key("22222222-2222-4222-8222-222222222222", None),+ reminder_key("33333333-3333-4333-8333-333333333333", None));}++#[test]+fn reminder_collapse_key_separates_two_firings_of_one_reminder() {+ // A daily reminder's occurrences share an id and a description, so without+ // the firing in the key Tuesday's alert would replace Monday's unread one.+ const ID: &str = "22222222-2222-4222-8222-222222222222";++ assert_ne!(reminder_key(ID, firing(3)), reminder_key(ID, firing(4)));+}++#[test]+fn reminder_collapse_key_is_stable_for_a_redelivered_firing() {+ // The behaviour the key existed for in the first place: sending the same+ // firing twice must replace the alert rather than stack a duplicate.+ const ID: &str = "22222222-2222-4222-8222-222222222222";++ assert_eq!(reminder_key(ID, firing(3)), reminder_key(ID, firing(3)));+}++#[test]+fn reminder_metadata_reads_back_without_a_firing() {+ // Notifications written before recurring dispatch have no `scheduledFor`,+ // and must still deserialize rather than breaking the inbox.+ let stored = serde_json::json!({+ "reminderId": "22222222-2222-4222-8222-222222222222",+ "description": "follow up",+ });++ let metadata: ReminderMetadata =+ serde_json::from_value(stored).expect("legacy metadata should deserialize");++ assert!(metadata.scheduled_for.is_none());+}diff --git a/crates/reminders/src/domain/models.rs b/crates/reminders/src/domain/models.rsindex 1b35abe568..654b7b3ee7 100644--- a/crates/reminders/src/domain/models.rs+++ b/crates/reminders/src/domain/models.rs@@ -17,6 +17,28 @@ use uuid::Uuid;/// stay sane. Mirrored by the `reminder_description_max_length` DB constraint.pub const MAX_DESCRIPTION_LEN: usize = 2_000;+/// The outside limit on how late a recurring firing may be delivered.+///+/// A backstop for the long-period schedules, where the primary rule — a firing+/// is stale once the next one has come due — would otherwise permit delivering+/// a monthly reminder three weeks after the fact. Deliberately generous: an+/// hour of queue backlog or a short outage must not cost anyone their daily+/// reminder, so the threshold sits far above any delay healthy dispatch+/// produces rather than close to it.+///+/// Also what marks a reminder revived from months out of service as needing a+/// recomputed firing rather than the one it went quiet on.+pub const MAX_RECURRING_LATENESS: chrono::Duration = chrono::Duration::hours(24);++/// The closest together two firings of a recurring reminder may be.+///+/// The sweep ticks once a minute, so a schedule finer than that cannot be+/// honoured; this sits well above the tick because a reminder arriving every+/// few minutes is a notification storm rather than a reminder. The composer+/// only builds daily, weekly and monthly schedules, so this guards the API+/// rather than anything a user can click.+pub const MIN_RECURRING_INTERVAL: chrono::Duration = chrono::Duration::minutes(5);+/// Default number of reminders returned by a list request.pub const DEFAULT_PAGE_SIZE: u32 = 100;@@ -585,6 +607,47 @@ pub struct SweepSummary {pub dispatched: usize,}+/// Where a series goes once the firing in hand is finished.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct Advance {+ /// The firing to move to.+ pub next_run_at: DateTime<Utc>,+ /// Whether to clear the owner's "done" acknowledgement.+ ///+ /// True when this delivery notified them: marking a recurring reminder done+ /// settles the firing in front of you, not the standing arrangement, so a+ /// fresh notification makes that acknowledgement stale and the reminder+ /// outstanding again.+ ///+ /// False when the firing was rolled forward without notifying. Nothing+ /// reached the owner, so nothing has superseded what they already dealt+ /// with, and clearing it would return the reminder to their attention with+ /// no notification to explain why.+ pub clear_completion: bool,+}++/// What finishing a firing did to the reminder behind it.+///+/// Reported rather than assumed because the advance is allowed to not happen,+/// and "the owner rescheduled" and "the advance silently failed" leave exactly+/// the same row behind. Without this the caller cannot tell them apart.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Completion {+ /// Nothing to advance: a one-shot, or a series with no firing left.+ NoAdvance,+ /// The series moved on to the firing it was given.+ Advanced,+ /// An advance was asked for and declined, because the reminder no longer+ /// sits on the firing that was delivered.+ ///+ /// Named for what is known rather than for the likely cause. A reschedule+ /// mid-flight is the ordinary one and outranks the series, but the row may+ /// equally have been deleted, completed, or disabled between the read that+ /// resolved this firing and the write that finished it. All this reports is+ /// that the guard held. Expected, not an error.+ NotAdvanced,+}+/// What became of one `Deliver` message.////// Every variant is a success in the queueing sense — the message is acked.@@ -600,9 +663,11 @@ pub enum DeliveryOutcome {/// Nothing left to deliver: the reminder was deleted, completed, disabled,/// or rescheduled out from under this message between sweep and delivery.Gone,- /// The reminder recurs. Recurring dispatch is not implemented, and firing- /// one here would deliver it once and complete it forever.- SkippedRecurring,+ /// A recurring firing too far behind to be worth sending, moved on to its+ /// next occurrence without notifying. Covers a dispatcher outage, and the+ /// series whose `next_run_at` was frozen before recurring dispatch existed+ /// — delivering either would announce a reminder about a moment long past.+ RolledForward,}/// Errors returned by the reminders service.diff --git a/crates/reminders/src/domain/models/test.rs b/crates/reminders/src/domain/models/test.rsindex 028fb46f5d..621b1cedc0 100644--- a/crates/reminders/src/domain/models/test.rs+++ b/crates/reminders/src/domain/models/test.rs@@ -470,6 +470,10 @@ fn flooring_leaves_an_already_flat_instant_alone() {#[test]fn flooring_leaves_a_cron_schedule_untouched() {// The seconds in a cron are the owner's, not an artifact of request timing.+ //+ // Also what lets the service validate a recurring schedule's interval+ // against the floored cron: flooring cannot rewrite the expression, so the+ // cron checked and the cron stored are necessarily the same one.let schedule = ReminderSchedule::Recurring {cron: ReminderCron::parse("30 0 9 * * *").expect("valid cron"),timezone: New_York,@@ -477,3 +481,81 @@ fn flooring_leaves_a_cron_schedule_untouched() {assert_eq!(schedule.clone().floored_to_minute(), schedule);}++#[test]+fn next_run_after_is_strictly_after_the_instant_given() {+ // Load-bearing for the minimum-interval check, which measures a schedule's+ // period as the gap between its next two firings. If this returned the+ // instant it was handed, that gap would be zero and every recurring+ // reminder would be rejected as firing too often.+ let cron = ReminderCron::parse(DAILY_9AM).expect("valid cron");+ // 13:00 UTC is exactly 09:00 in New York on this date — a firing instant.+ let on_a_firing = utc(2026, 7, 1, 13, 0);++ let next = cron+ .next_run_after(on_a_firing, New_York)+ .expect("a daily cron always has a next firing");++ assert!(+ next > on_a_firing,+ "must not return the instant it was given"+ );+ assert_eq!(next, utc(2026, 7, 2, 13, 0));+}++#[test]+fn every_day_spelled_as_a_full_day_list_fires_daily() {+ // The picker builds every-day schedules as `1,2,3,4,5,6,7` rather than `*`,+ // so this pins that the backend reads the two identically. If the crate's+ // day-of-week were 0-6 rather than 1-7, the `7` would be out of range and+ // this would not even parse.+ let starred = ReminderCron::parse("0 0 9 * * *").expect("`*` parses");+ let listed = ReminderCron::parse("0 0 9 * * 1,2,3,4,5,6,7").expect("a full list parses");++ let mut from_starred = utc(2026, 7, 1, 0, 0);+ let mut from_listed = from_starred;++ // A fortnight, so a day-shift or a missing day shows up rather than hiding+ // inside a single week.+ for _ in 0..14 {+ let a = starred+ .next_run_after(from_starred, New_York)+ .expect("`*` keeps firing");+ let b = listed+ .next_run_after(from_listed, New_York)+ .expect("the list keeps firing");+ assert_eq!(a, b, "the two spellings must fire at the same instants");+ from_starred = a;+ from_listed = b;+ }++ // And that it really is every day, not every other one.+ let first = starred+ .next_run_after(utc(2026, 7, 1, 0, 0), New_York)+ .unwrap();+ let second = starred.next_run_after(first, New_York).unwrap();+ assert_eq!(second - first, chrono::Duration::days(1));+}++#[test]+fn day_of_week_two_is_monday() {+ // Everything the pickers build rests on the crate numbering day-of-week+ // 1=Sunday through 7=Saturday, which is not the JS convention and not the+ // POSIX one. Asserted against a real calendar date so a crate change that+ // shifted it could not pass quietly.+ let mondays = ReminderCron::parse("0 0 9 * * 2").expect("valid cron");++ // 2026-07-01 is a Wednesday, so the next firing is Monday the 6th.+ let next = mondays+ .next_run_after(utc(2026, 7, 1, 0, 0), New_York)+ .expect("a weekly cron keeps firing");++ assert_eq!(+ next.with_timezone(&New_York).date_naive().to_string(),+ "2026-07-06"+ );+ assert_eq!(+ next.with_timezone(&New_York).format("%A").to_string(),+ "Monday"+ );+}diff --git a/crates/reminders/src/domain/ports.rs b/crates/reminders/src/domain/ports.rsindex 7e9c855de3..a48a96f211 100644--- a/crates/reminders/src/domain/ports.rs+++ b/crates/reminders/src/domain/ports.rs@@ -6,9 +6,9 @@ use macro_user_id::user_id::MacroUserIdStr;use uuid::Uuid;use crate::domain::models::{- CreateReminder, DeliveryOutcome, DueFiring, DueReminder, NewReminder, Reminder, ReminderBatch,- ReminderDispatchMessage, ReminderError, ReminderFilter, ReminderForSoup, ReminderPage,- ReminderPatch, ReminderUpdate, SoupReminderQuery, SweepSummary,+ Advance, Completion, CreateReminder, DeliveryOutcome, DueFiring, DueReminder, NewReminder,+ Reminder, ReminderBatch, ReminderDispatchMessage, ReminderError, ReminderFilter,+ ReminderForSoup, ReminderPage, ReminderPatch, ReminderUpdate, SoupReminderQuery, SweepSummary,};/// Source of the current time.@@ -123,9 +123,9 @@ pub trait ReminderDispatchRepo: Send + Sync + 'static {/// Every firing due at or before `now`, soonest first.///- /// Enabled, not yet completed, and not recurring. Returns identifiers- /// rather than whole reminders because a sweep only fans these out; the- /// row is read at delivery, by which point it may have changed.+ /// Enabled and not yet completed, of either schedule kind. Returns+ /// identifiers rather than whole reminders because a sweep only fans these+ /// out; the row is read at delivery, by which point it may have changed.////// Deliberately unbounded — a sweep that silently truncated would strand/// whatever fell off the end until someone noticed. See the note on the@@ -139,9 +139,7 @@ pub trait ReminderDispatchRepo: Send + Sync + 'static {/// Resolve a fanned-out firing back into the reminder to deliver.////// `None` when the reminder no longer wants this firing — deleted,- /// completed, disabled, or rescheduled since the sweep listed it. Recurring- /// reminders are *not* filtered out here; the domain decides what to do- /// with those so the gap stays visible.+ /// completed, disabled, or rescheduled since the sweep listed it.fn find_due_reminder(&self,firing: DueFiring,@@ -172,17 +170,56 @@ pub trait ReminderDispatchRepo: Send + Sync + 'static {scheduled_for: DateTime<Utc>,) -> impl Future<Output = Result<(), Self::Err>> + Send;- /// Record the firing as delivered.+ /// Record the firing as delivered, and move a recurring reminder on to+ /// `advance_to`.+ ///+ /// Named for both halves because it does both, and the pairing is the whole+ /// point — a call site that reads this as "mark sent" alone is a call site+ /// that will eventually drop the advance.////// Marks the occurrence, not the reminder: delivery is not completion./// `completed_at` is the owner saying they are finished with a reminder,/// and one that has just landed in their inbox is not. The sent occurrence/// is what stops [`ReminderDispatchRepo::due_firings`] returning the firing/// again.- fn complete_occurrence(+ ///+ /// `advance_to` is `None` for a one-shot, and for a cron with no further+ /// firing — both leave `next_run_at` where it is and simply stop coming+ /// due. `Some` rolls the series forward.+ ///+ /// **Both writes must land atomically.** A reminder marked sent but not+ /// advanced is excluded by its own sent occurrence and never moves, so it+ /// would go quiet forever rather than fire again — the one failure in this+ /// design that does not heal itself.+ ///+ /// Implementations must not advance a reminder whose `next_run_at` has+ /// moved off `scheduled_for`: that means the owner rescheduled mid-flight,+ /// and their choice outranks the series. Declining to advance is reported+ /// as [`Completion::NotAdvanced`] rather than passed over in silence, so a+ /// no-op that is expected cannot be mistaken for one that is not.+ fn complete_occurrence_and_advance(&self,reminder_id: Uuid,scheduled_for: DateTime<Utc>,+ advance: Option<Advance>,+ ) -> impl Future<Output = Result<Completion, Self::Err>> + Send;++ /// Retract the notifications this reminder's firings before `before` left+ /// behind.+ ///+ /// Only recurring delivery calls this, so a daily reminder shows the firing+ /// its owner has not dealt with rather than every one since they last+ /// looked. A one-shot has no earlier firing to retract.+ ///+ /// Bounded by `before` — the firing just delivered — rather than clearing+ /// the reminder outright. Two things would otherwise be swept up with the+ /// stale ones: the notification this delivery just created, and one a+ /// concurrent delivery of a *later* firing created. Both are the current+ /// state of the inbox, and neither is this call's to remove.+ fn retract_notifications(+ &self,+ reminder_id: Uuid,+ before: DateTime<Utc>,) -> impl Future<Output = Result<(), Self::Err>> + Send;}diff --git a/crates/reminders/src/domain/service.rs b/crates/reminders/src/domain/service.rsindex 99d96cdd2f..7a72af92f7 100644--- a/crates/reminders/src/domain/service.rs+++ b/crates/reminders/src/domain/service.rs@@ -6,15 +6,17 @@ pub mod dispatch;mod test;use chrono::{DateTime, Utc};+use chrono_tz::Tz;use entity_access::domain::models::{AnyEntityPermission, EntityAccessReceipt, OwnerAccessLevel};use macro_user_id::user_id::MacroUserIdStr;use model_entity::Entity;use uuid::Uuid;use crate::domain::models::{- CreateReminder, MAX_DESCRIPTION_LEN, NewReminder, Reminder, ReminderBatch, ReminderCursor,- ReminderError, ReminderFilter, ReminderForSoup, ReminderPage, ReminderPatch, ReminderSchedule,- ReminderUpdate, ScheduleUpdate, SoupReminderQuery,+ CreateReminder, MAX_DESCRIPTION_LEN, MAX_RECURRING_LATENESS, MIN_RECURRING_INTERVAL,+ NewReminder, Reminder, ReminderBatch, ReminderCron, ReminderCursor, ReminderError,+ ReminderFilter, ReminderForSoup, ReminderPage, ReminderPatch, ReminderSchedule, ReminderUpdate,+ ScheduleUpdate, SoupReminderQuery,};use crate::domain::ports::{Clock, RemindersRepo, RemindersService, SystemClock};@@ -23,6 +25,14 @@ use crate::domain::ports::{Clock, RemindersRepo, RemindersService, SystemClock};/// Only reached when rows cannot be decoded; a normal page costs one read.const MAX_LIST_BATCHES: usize = 5;+/// How many consecutive gaps the minimum-interval check measures.+///+/// Enough to cover a schedule that clusters several firings and then waits —+/// the shape a single-gap check reads differently depending on the hour the+/// request arrives — without walking a cron that fires yearly out to its+/// hundredth occurrence.+const INTERVAL_SAMPLE_FIRINGS: usize = 8;+/// Concrete reminders service backed by a [RemindersRepo].#[derive(Debug, Clone)]pub struct RemindersServiceImpl<R, C = SystemClock> {@@ -89,6 +99,44 @@ fn derive_next_run_at(})}+/// Reject a cron that fires more often than [`MIN_RECURRING_INTERVAL`].+///+/// Measured between the next two firings rather than parsed out of the+/// expression, so it holds for every way of writing a too-frequent schedule+/// instead of the handful someone thought to pattern-match. A cron with fewer+/// than two firings left cannot be too frequent, so it passes.+fn validate_recurring_interval(+ cron: &ReminderCron,+ timezone: Tz,+ now: DateTime<Utc>,+) -> Result<(), ReminderError> {+ // Several gaps, not just the next one. A cron's firings need not be evenly+ // spaced — `0 0,4 9 * * *` fires at 09:00 and 09:04 daily — so measuring+ // only the first gap after `now` makes acceptance depend on when the+ // request happened to arrive: rejected at 08:59, accepted at 09:02, for the+ // same schedule.+ let mut previous = match cron.next_run_after(now, timezone) {+ Some(first) => first,+ // Nothing left to fire, so nothing can fire too often.+ None => return Ok(()),+ };++ for _ in 0..INTERVAL_SAMPLE_FIRINGS {+ let Some(next) = cron.next_run_after(previous, timezone) else {+ return Ok(());+ };+ if next - previous < MIN_RECURRING_INTERVAL {+ return Err(ReminderError::BadRequest(format!(+ "a recurring reminder must fire at most once every {} minutes",+ MIN_RECURRING_INTERVAL.num_minutes()+ )));+ }+ previous = next;+ }++ Ok(())+}+/// Check the schedule will fire, then store it at minute granularity.////// Order matters. Flooring first would drag a request inside the current minute@@ -101,11 +149,14 @@ fn normalize_schedule() -> Result<(ReminderSchedule, DateTime<Utc>), ReminderError> {let derived = derive_next_run_at(&schedule, now)?;let schedule = schedule.floored_to_minute();- let next_run_at = match schedule {+ let next_run_at = match &schedule {// Same instant the schedule now carries, so the two cannot disagree.- ReminderSchedule::Once { remind_at } => remind_at,+ ReminderSchedule::Once { remind_at } => *remind_at,// A cron's seconds are the owner's, so its firing is left as derived.- ReminderSchedule::Recurring { .. } => derived,+ ReminderSchedule::Recurring { cron, timezone } => {+ validate_recurring_interval(cron, *timezone, now)?;+ derived+ }};Ok((schedule, next_run_at))}@@ -162,6 +213,77 @@ fn receipt_owner_and_id(Ok((user_id, id))}+impl<R, C> RemindersServiceImpl<R, C>+where+ R: RemindersRepo,+ C: Clock,+{+ /// Pull a revived recurring reminder's firing back into the future.+ ///+ /// A reminder that spent three months disabled still carries the firing it+ /// had when it went quiet, so switching it back on would leave the row+ /// reading "next run: March". Dispatch would sort that out on its own — a+ /// firing that stale is rolled forward rather than delivered — but not+ /// before the owner had seen a date from the past presented as upcoming.+ ///+ /// Deliberately narrow. It runs only when the patch is what revived the+ /// reminder, and only on a firing older than [`MAX_RECURRING_LATENESS`],+ /// which is far older than one merely waiting its turn in the queue. A+ /// broader rule would eventually move a firing that was seconds away from+ /// being delivered, and the delivery already in flight would find the time+ /// changed under it and drop the notification.+ async fn refresh_revived_recurring(+ &self,+ user_id: &MacroUserIdStr<'_>,+ reminder: Reminder,+ patch_revived: bool,+ ) -> Result<Reminder, ReminderError> {+ if !patch_revived || !reminder.enabled || reminder.completed_at.is_some() {+ return Ok(reminder);+ }++ let ReminderSchedule::Recurring { cron, timezone } = &reminder.schedule else {+ return Ok(reminder);+ };++ let now = self.clock.now();+ if now - reminder.next_run_at <= MAX_RECURRING_LATENESS {+ return Ok(reminder);+ }++ let Some(next_run_at) = cron.next_run_after(now, *timezone) else {+ return Ok(reminder);+ };++ let update = ReminderUpdate {+ schedule: Some(ScheduleUpdate {+ schedule: reminder.schedule.clone(),+ next_run_at,+ }),+ ..Default::default()+ };++ // A failure here leaves a stale `next_run_at`, which dispatch corrects+ // on its own. Not worth failing the owner's edit over.+ match self+ .repo+ .update_reminder(user_id, reminder.id, &update)+ .await+ {+ Ok(Some(refreshed)) => Ok(refreshed),+ Ok(None) => Ok(reminder),+ Err(e) => {+ tracing::error!(+ error = ?e,+ reminder_id = %reminder.id,+ "failed to refresh a revived recurring reminder's next firing",+ );+ Ok(reminder)+ }+ }+ }+}+impl<R, C> RemindersService for RemindersServiceImpl<R, C>whereR: RemindersRepo,@@ -330,6 +452,16 @@ where}).transpose()?;+ // Whether this patch is what brought the reminder back into service. An+ // explicit schedule is not a revival: the owner named a firing, and+ // recomputing one over the top of it would discard what they chose.+ //+ // `enabled` is the only thing that can freeze a series. Completion no+ // longer stops a recurring reminder coming due — it settles one firing,+ // not the arrangement — so its `next_run_at` keeps advancing while+ // completed and cannot go stale that way.+ let patch_revived = schedule.is_none() && enabled == Some(true);+let update = ReminderUpdate {description,schedule,@@ -337,11 +469,15 @@ wherecompleted,};- self.repo+ let updated = self+ .repo.update_reminder(&user_id, id, &update).await.map_err(|e| rootcause::Report::new(e).into_dynamic())?- .ok_or(ReminderError::NotFound)+ .ok_or(ReminderError::NotFound)?;++ self.refresh_revived_recurring(&user_id, updated, patch_revived)+ .await}#[tracing::instrument(err, skip(self, receipt))]diff --git a/crates/reminders/src/domain/service/dispatch.rs b/crates/reminders/src/domain/service/dispatch.rsindex 86c5b473fa..40131569b8 100644--- a/crates/reminders/src/domain/service/dispatch.rs+++ b/crates/reminders/src/domain/service/dispatch.rs@@ -15,8 +15,11 @@ mod test;use chrono::{DateTime, Duration, Utc};+use uuid::Uuid;+use crate::domain::models::{- DeliveryOutcome, DueFiring, DueReminder, ReminderDispatchMessage, ReminderError, SweepSummary,+ Advance, Completion, DeliveryOutcome, DueFiring, DueReminder, MAX_RECURRING_LATENESS,+ ReminderDispatchMessage, ReminderError, ReminderSchedule, SweepSummary,};use crate::domain::ports::{Clock, ReminderDispatch, ReminderDispatchQueue, ReminderDispatchRepo, ReminderNotifier,@@ -32,6 +35,49 @@ use crate::domain::ports::{/// a dead worker does not strand the firing.const RETRY_AFTER: Duration = Duration::minutes(5);+/// What to do with a firing once it has been claimed.+enum Delivery {+ /// Notify the owner.+ Notify,+ /// Skip the notification and only move the series on.+ RollForward,+}++/// Whether a recurring firing is too far gone to be worth delivering.+///+/// Two ways to be past it, and the first is the one that matters:+///+/// - **Superseded.** The firing after this one has itself come due, so+/// delivering would announce yesterday's reminder while today's waits behind+/// it. This scales with the schedule on its own — a daily reminder tolerates+/// most of a day's delay, a five-minute one tolerates five minutes — which is+/// why the rule is expressed this way rather than as a flat duration that+/// would be far too tight for one and far too loose for the other.+/// - **Beyond the outside limit.** The backstop for long periods, where the+/// first rule alone would let a monthly reminder arrive three weeks late.+///+/// A firing merely waiting its turn behind a backlog fails both, and is+/// delivered. That is the point: an hour of queue delay must not cost someone+/// their daily reminder.+fn is_stale_firing(+ schedule: &ReminderSchedule,+ scheduled_for: DateTime<Utc>,+ now: DateTime<Utc>,+) -> bool {+ let ReminderSchedule::Recurring { cron, timezone } = schedule else {+ // One-shots are exempt. An overdue one-shot staying overdue until its+ // owner deals with it is the whole point of one.+ return false;+ };++ if now - scheduled_for > MAX_RECURRING_LATENESS {+ return true;+ }++ cron.next_run_after(scheduled_for, *timezone)+ .is_some_and(|following| now >= following)+}+/// Delivers due reminders to their owners.#[derive(Debug, Clone)]pub struct ReminderDispatchService<R, N, Q, C = SystemClock> {@@ -79,13 +125,24 @@ where////// Claiming first is what stops two workers double-sending; completing last/// is what makes a failed delivery retryable rather than lost.+ ///+ /// `next_run_at` carries a recurring reminder's next firing through to+ /// completion, where it lands in the same write that marks this one sent.async fn deliver_claimed(&self,due: &DueReminder,now: DateTime<Utc>,+ next_run_at: Option<DateTime<Utc>>,+ delivery: Delivery,) -> Result<DeliveryOutcome, ReminderError> {let reminder_id = due.reminder.id;let scheduled_for = due.scheduled_for;+ // Only a delivery the owner can see supersedes their "done" on the+ // previous firing.+ let advance = next_run_at.map(|next_run_at| Advance {+ next_run_at,+ clear_completion: matches!(delivery, Delivery::Notify),+ });let claimed = self.repo@@ -96,6 +153,16 @@ wherereturn Ok(DeliveryOutcome::AlreadyClaimed);}+ if let Delivery::RollForward = delivery {+ // No notification, so nothing to retract and nothing to release:+ // completing is the whole job. The previous firing's notification+ // stays — nothing replaced it, so it is still the most recent thing+ // the owner was told.+ self.complete(reminder_id, scheduled_for, advance).await?;++ return Ok(DeliveryOutcome::RolledForward);+ }+if let Err(e) = self.notifier.notify(due).await {tracing::error!(error = ?e,@@ -124,12 +191,60 @@ where));}- self.repo- .complete_occurrence(reminder_id, scheduled_for)+ // Now that the replacement exists, take back what it replaces. After+ // notifying rather than before: a failure here leaves one notification+ // too many, whereas retracting first and then failing to notify would+ // leave the owner with none at all — having silently removed the only+ // reminder they could still see.+ //+ // Bounded by this firing, so it cannot remove the notification just+ // created. Non-fatal: an untidy inbox is no reason to fail a delivery+ // that has already happened.+ if due.reminder.schedule.repeats()+ && let Err(e) = self+ .repo+ .retract_notifications(reminder_id, scheduled_for)+ .await+ {+ tracing::error!(+ error = ?e,+ reminder_id = %reminder_id,+ "failed to retract an earlier reminder notification; leaving it in place",+ );+ }++ self.complete(reminder_id, scheduled_for, advance).await?;++ Ok(DeliveryOutcome::Delivered)+ }++ /// Finish a firing, reporting an advance that was declined rather than+ /// letting it pass unnoticed.+ ///+ /// A declined advance is expected — most often the owner rescheduled+ /// mid-flight — but it is indistinguishable after the fact from an advance+ /// that should have happened and did not, so it is worth a line either way.+ async fn complete(+ &self,+ reminder_id: Uuid,+ scheduled_for: DateTime<Utc>,+ advance: Option<Advance>,+ ) -> Result<Completion, ReminderError> {+ let completion = self+ .repo+ .complete_occurrence_and_advance(reminder_id, scheduled_for, advance).await.map_err(|e| rootcause::Report::new(e).into_dynamic())?;- Ok(DeliveryOutcome::Delivered)+ if completion == Completion::NotAdvanced {+ tracing::info!(+ reminder_id = %reminder_id,+ scheduled_for = %scheduled_for,+ "did not advance a reminder that moved off this firing mid-delivery",+ );+ }++ Ok(completion)}}@@ -189,17 +304,36 @@ wherereturn Ok(DeliveryOutcome::Gone);};- // Recurring reminders are modelled but not dispatched yet. Guarded here- // rather than in the query because this is the only place that could- // actually send one — and completing it would retire the series.- if due.reminder.schedule.repeats() {+ // Where the series goes next, resolved before anything is written so+ // completion can move the reminder on in the same breath as marking+ // this firing sent.+ //+ // Measured from `now` rather than from the firing being delivered, so a+ // backlog collapses into one delivery instead of replaying every+ // occurrence that was missed while nothing was listening. A daily+ // reminder that went undelivered for a week owes its owner one nudge,+ // not seven.+ //+ // `None` means the cron has no further firing — a year-qualified+ // expression that has run out. That reminder then behaves exactly like+ // a delivered one-shot: it stays at its final firing and waits to be+ // dealt with, rather than needing a state of its own.+ let next_run_at = match &due.reminder.schedule {+ ReminderSchedule::Once { .. } => None,+ ReminderSchedule::Recurring { cron, timezone } => cron.next_run_after(now, *timezone),+ };++ let delivery = if is_stale_firing(&due.reminder.schedule, due.scheduled_for, now) {tracing::warn!(reminder_id = %due.reminder.id,- "skipped a due recurring reminder; recurring dispatch is not implemented",+ scheduled_for = %due.scheduled_for,+ "rolling a stale recurring reminder forward instead of delivering it",);- return Ok(DeliveryOutcome::SkippedRecurring);- }+ Delivery::RollForward+ } else {+ Delivery::Notify+ };- self.deliver_claimed(&due, now).await+ self.deliver_claimed(&due, now, next_run_at, delivery).await}}diff --git a/crates/reminders/src/domain/service/dispatch/test.rs b/crates/reminders/src/domain/service/dispatch/test.rsindex 8ab88dfc72..ae02082dcb 100644--- a/crates/reminders/src/domain/service/dispatch/test.rs+++ b/crates/reminders/src/domain/service/dispatch/test.rs@@ -8,7 +8,7 @@ use model_entity::EntityType;use uuid::Uuid;use super::*;-use crate::domain::models::{Reminder, ReminderCron, ReminderSchedule};+use crate::domain::models::{Advance, Reminder, ReminderCron, ReminderSchedule};use crate::domain::ports::RawDispatchMessage;const OWNER: &str = "macro|[email protected]";@@ -82,6 +82,38 @@ fn due_recurring(n: u8) -> DueReminder {}}+/// The same recurring reminder, with its current firing moved to+/// `scheduled_for`.+fn due_recurring_at(n: u8, scheduled_for: DateTime<Utc>) -> DueReminder {+ let mut due = due_recurring(n);+ due.reminder.next_run_at = scheduled_for;+ due.scheduled_for = scheduled_for;+ due+}++/// A recurring reminder on an arbitrary cron, due at `scheduled_for`.+///+/// Staleness depends on how far apart a schedule's firings are, so the tests+/// covering it need periods other than the daily default.+fn due_with_cron(n: u8, cron: &str, scheduled_for: DateTime<Utc>) -> DueReminder {+ let mut due = due_recurring_at(n, scheduled_for);+ due.reminder.schedule = ReminderSchedule::Recurring {+ cron: ReminderCron::parse(cron).expect("valid cron"),+ timezone: New_York,+ };+ due+}++/// Where `DAILY_9AM` in New York lands next, measured from [`now`].+///+/// [`now`] is 12:00 UTC, which is 08:00 in New York on this date, so the next+/// 09:00 there is an hour later — 13:00 UTC the same day.+fn next_daily_9am() -> DateTime<Utc> {+ Utc.with_ymd_and_hms(2026, 7, 1, 13, 0, 0)+ .single()+ .expect("unambiguous instant")+}+#[derive(Debug, thiserror::Error)]#[error("fake failure")]struct FakeErr;@@ -95,7 +127,14 @@ struct FakeRepoState {list_fails: bool,claimed: Vec<Uuid>,released: Vec<Uuid>,- completed: Vec<Uuid>,+ /// Completed firings, each with how it moved the series on.+ completed: Vec<(Uuid, Option<Advance>)>,+ /// Retractions, each with the firing they were bounded by.+ retracted: Vec<(Uuid, DateTime<Utc>)>,+ retract_fails: bool,+ /// Report every advance as declined, standing in for the reminder having+ /// moved off this firing while the delivery was in flight.+ advance_declined: bool,}#[derive(Clone, Default)]@@ -133,7 +172,51 @@ impl FakeRepo {}fn completed(&self) -> Vec<Uuid> {- self.0.lock().unwrap().completed.clone()+ self.0+ .lock()+ .unwrap()+ .completed+ .iter()+ .map(|(id, _)| *id)+ .collect()+ }++ /// Where each completed firing moved its series to, `None` for one that+ /// does not repeat.+ fn advanced(&self) -> Vec<(Uuid, Option<DateTime<Utc>>)> {+ self.0+ .lock()+ .unwrap()+ .completed+ .iter()+ .map(|(id, advance)| (*id, advance.map(|a| a.next_run_at)))+ .collect()+ }++ /// Whether each completed firing cleared the owner's "done", which only a+ /// delivery they were told about should.+ fn cleared_completion(&self) -> Vec<bool> {+ self.0+ .lock()+ .unwrap()+ .completed+ .iter()+ .filter_map(|(_, advance)| advance.map(|a| a.clear_completion))+ .collect()+ }++ fn retracted(&self) -> Vec<(Uuid, DateTime<Utc>)> {+ self.0.lock().unwrap().retracted.clone()+ }++ fn failing_retract(self) -> Self {+ self.0.lock().unwrap().retract_fails = true;+ self+ }++ fn declining_advance(self) -> Self {+ self.0.lock().unwrap().advance_declined = true;+ self}}@@ -194,12 +277,31 @@ impl ReminderDispatchRepo for FakeRepo {Ok(())}- async fn complete_occurrence(+ async fn complete_occurrence_and_advance(&self,reminder_id: Uuid,_scheduled_for: DateTime<Utc>,+ advance: Option<Advance>,+ ) -> Result<Completion, Self::Err> {+ let mut state = self.0.lock().unwrap();+ state.completed.push((reminder_id, advance));+ Ok(match (advance, state.advance_declined) {+ (None, _) => Completion::NoAdvance,+ (Some(_), true) => Completion::NotAdvanced,+ (Some(_), false) => Completion::Advanced,+ })+ }++ async fn retract_notifications(+ &self,+ reminder_id: Uuid,+ before: DateTime<Utc>,) -> Result<(), Self::Err> {- self.0.lock().unwrap().completed.push(reminder_id);+ let mut state = self.0.lock().unwrap();+ if state.retract_fails {+ return Err(FakeErr);+ }+ state.retracted.push((reminder_id, before));Ok(())}}@@ -308,8 +410,8 @@ async fn a_sweep_fans_out_one_message_per_due_firing() {#[tokio::test]async fn a_sweep_fans_out_recurring_reminders_it_is_given() {- // The exclusion lives in the query, not the sweep: whatever the repo- // reports as due is fanned out, and `deliver` is what refuses to send it.+ // The sweep does not read schedules: whatever the repo reports as due is+ // fanned out, and delivery decides what each firing means.let repo = FakeRepo::with_due(vec![due_recurring(1)]);let queue = FakeQueue::default();@@ -379,7 +481,7 @@ async fn delivers_and_completes_a_due_one_shot() {}#[tokio::test]-async fn skips_a_recurring_reminder_without_claiming_it() {+async fn delivers_a_recurring_reminder_and_advances_it_to_the_next_firing() {let repo = FakeRepo::with_due(vec![due_recurring(1)]);let notifier = FakeNotifier::default();@@ -388,13 +490,328 @@ async fn skips_a_recurring_reminder_without_claiming_it() {.await.expect("delivery succeeds");- assert_eq!(outcome, DeliveryOutcome::SkippedRecurring);- // Nothing claimed: a recurring reminder must stay untouched for whenever- // recurring dispatch lands, not burn its occurrence row.- assert!(repo.claimed().is_empty());+ assert_eq!(outcome, DeliveryOutcome::Delivered);+ assert_eq!(notifier.notified(), vec![uuid(1)]);+ // The advance rides along with completion. Without it the reminder would be+ // excluded by its own sent occurrence and never come due again.+ assert_eq!(repo.advanced(), vec![(uuid(1), Some(next_daily_9am()))]);+ assert!(repo.released().is_empty());+}++#[tokio::test]+async fn delivering_a_recurring_firing_clears_an_earlier_done() {+ // Completion settles one firing, not the series. A firing the owner can now+ // see supersedes their "done" on the previous one, so the reminder reads as+ // outstanding again rather than sitting under Done with a fresh nudge in+ // the inbox.+ let repo = FakeRepo::with_due(vec![due_recurring(1)]);++ service(repo.clone(), FakeNotifier::default(), FakeQueue::default())+ .deliver(firing(1))+ .await+ .expect("delivery succeeds");++ assert_eq!(repo.cleared_completion(), vec![true]);+}++#[tokio::test]+async fn rolling_a_firing_forward_silently_leaves_done_alone() {+ // Nothing reached the owner, so nothing supersedes what they already dealt+ // with — returning the reminder to their attention here would be a state+ // change with no notification to explain it.+ let stale_at = now() - Duration::days(2);+ let repo = FakeRepo::with_due(vec![due_recurring_at(1, stale_at)]);++ service(repo.clone(), FakeNotifier::default(), FakeQueue::default())+ .deliver(DueFiring {+ reminder_id: uuid(1),+ scheduled_for: stale_at,+ })+ .await+ .expect("delivery succeeds");++ assert_eq!(repo.cleared_completion(), vec![false]);+}++#[tokio::test]+async fn a_recurring_delivery_retracts_the_earlier_firings_notification() {+ let repo = FakeRepo::with_due(vec![due_recurring(1)]);+ let notifier = FakeNotifier::default();++ service(repo.clone(), notifier.clone(), FakeQueue::default())+ .deliver(firing(1))+ .await+ .expect("delivery succeeds");++ // A daily reminder should leave one thing in the inbox, not one per day+ // since its owner last looked. Bounded by this firing, so the notification+ // just created is not swept up with the ones it replaces.+ assert_eq!(repo.retracted(), vec![(uuid(1), now())]);+}++#[tokio::test]+async fn a_recurring_delivery_retracts_only_after_the_replacement_exists() {+ // Ordering matters more than it looks. Retracting first and then failing to+ // notify would take away the one notification the owner could still see and+ // put nothing in its place.+ let repo = FakeRepo::with_due(vec![due_recurring(1)]);+ let notifier = FakeNotifier::failing_for(uuid(1));++ let result = service(repo.clone(), notifier, FakeQueue::default())+ .deliver(firing(1))+ .await;++ assert!(matches!(result, Err(ReminderError::Internal(_))));+ assert!(+ repo.retracted().is_empty(),+ "a failed delivery must leave the previous firing's notification alone"+ );+}++#[tokio::test]+async fn a_failed_retraction_does_not_fail_a_delivered_firing() {+ // The notification has already gone out. Failing here would leave the+ // firing uncompleted and redeliver it, notifying a second time to tidy up+ // an inbox — which is worse than the untidy inbox.+ let repo = FakeRepo::with_due(vec![due_recurring(1)]).failing_retract();+ let notifier = FakeNotifier::default();++ let outcome = service(repo.clone(), notifier.clone(), FakeQueue::default())+ .deliver(firing(1))+ .await+ .expect("delivery succeeds despite the failed retraction");++ assert_eq!(outcome, DeliveryOutcome::Delivered);+ assert_eq!(notifier.notified(), vec![uuid(1)]);+ assert_eq!(repo.advanced(), vec![(uuid(1), Some(next_daily_9am()))]);+}++#[tokio::test]+async fn a_delivery_whose_advance_was_declined_still_counts_as_delivered() {+ // The owner rescheduled while this was in flight, so the advance was+ // declined and their time stands. The notification still went out, so the+ // message is done with — leaving it for redelivery would notify twice.+ let repo = FakeRepo::with_due(vec![due_recurring(1)]).declining_advance();+ let notifier = FakeNotifier::default();++ let outcome = service(repo.clone(), notifier.clone(), FakeQueue::default())+ .deliver(firing(1))+ .await+ .expect("delivery succeeds");++ assert_eq!(outcome, DeliveryOutcome::Delivered);+ assert_eq!(notifier.notified(), vec![uuid(1)]);+}++#[tokio::test]+async fn a_one_shot_neither_advances_nor_retracts() {+ let repo = FakeRepo::with_due(vec![due_once(1)]);++ service(repo.clone(), FakeNotifier::default(), FakeQueue::default())+ .deliver(firing(1))+ .await+ .expect("delivery succeeds");++ assert_eq!(repo.advanced(), vec![(uuid(1), None)]);+ // Nothing came before it, so there is nothing to take back.+ assert!(repo.retracted().is_empty());+}++#[tokio::test]+async fn a_stale_recurring_firing_rolls_forward_instead_of_notifying() {+ // Two days late: a dispatcher outage, or a series whose next_run_at was+ // frozen before recurring dispatch existed. Announcing it now would be+ // reporting history.+ let stale_at = now() - Duration::days(2);+ let repo = FakeRepo::with_due(vec![due_recurring_at(1, stale_at)]);+ let notifier = FakeNotifier::default();++ let outcome = service(repo.clone(), notifier.clone(), FakeQueue::default())+ .deliver(DueFiring {+ reminder_id: uuid(1),+ scheduled_for: stale_at,+ })+ .await+ .expect("delivery succeeds");++ assert_eq!(outcome, DeliveryOutcome::RolledForward);+ assert!(notifier.notified().is_empty());+ // Nothing was sent, so the previous firing's notification is still the most+ // recent thing the owner has — it must survive.+ assert!(repo.retracted().is_empty());+ // Measured from now, not from the firing being skipped: advancing one day+ // from a two-day-old firing would land in the past and come straight back.+ assert_eq!(repo.advanced(), vec![(uuid(1), Some(next_daily_9am()))]);+}++#[tokio::test]+async fn a_recurring_firing_merely_delayed_is_still_delivered() {+ // The case a flat one-hour threshold got wrong. A daily reminder held up by+ // an hour of queue backlog or a short outage is late, not abandoned, and+ // dropping it silently would cost someone their reminder for that day.+ let delayed = now() - Duration::hours(3);+ let repo = FakeRepo::with_due(vec![due_recurring_at(1, delayed)]);+ let notifier = FakeNotifier::default();++ let outcome = service(repo.clone(), notifier.clone(), FakeQueue::default())+ .deliver(DueFiring {+ reminder_id: uuid(1),+ scheduled_for: delayed,+ })+ .await+ .expect("delivery succeeds");++ assert_eq!(outcome, DeliveryOutcome::Delivered);+ assert_eq!(notifier.notified(), vec![uuid(1)]);+}++#[tokio::test]+async fn a_recurring_firing_the_next_one_has_overtaken_is_rolled_forward() {+ // Staleness scales with the schedule rather than a fixed duration: once the+ // firing *after* this one has itself come due, delivering would announce+ // the previous occurrence while the current one waits behind it.+ //+ // Hourly, two hours late — so the following firing has been and gone while+ // this one is still well inside the 24-hour outside limit. That is what+ // isolates this rule from the backstop.+ let overtaken = now() - Duration::hours(2);+ let repo = FakeRepo::with_due(vec![due_with_cron(1, "0 0 * * * *", overtaken)]);+ let notifier = FakeNotifier::default();++ let outcome = service(repo.clone(), notifier.clone(), FakeQueue::default())+ .deliver(DueFiring {+ reminder_id: uuid(1),+ scheduled_for: overtaken,+ })+ .await+ .expect("delivery succeeds");++ assert_eq!(outcome, DeliveryOutcome::RolledForward);+ assert!(notifier.notified().is_empty());+}++#[tokio::test]+async fn a_firing_is_stale_the_instant_its_successor_comes_due() {+ // The boundary is `>=`, deliberately: at the exact moment the next firing+ // is due, the previous one has been superseded and delivering it would put+ // two of the same reminder in front of the owner at once. Pinned because it+ // decides real notifications, and `>` versus `>=` here is invisible.+ let hourly = "0 0 * * * *";+ // `now` is 12:00 exactly, so this firing's successor falls precisely on it.+ let previous = now() - Duration::hours(1);+ let repo = FakeRepo::with_due(vec![due_with_cron(1, hourly, previous)]);+ let notifier = FakeNotifier::default();++ let outcome = service(repo.clone(), notifier.clone(), FakeQueue::default())+ .deliver(DueFiring {+ reminder_id: uuid(1),+ scheduled_for: previous,+ })+ .await+ .expect("delivery succeeds");++ assert_eq!(outcome, DeliveryOutcome::RolledForward);+ assert!(notifier.notified().is_empty());+}++#[tokio::test]+async fn a_firing_whose_successor_is_still_ahead_is_delivered() {+ // The other side of that boundary, so the assertion above is pinning a+ // line rather than a direction.+ //+ // On the half hour, so `now` falls between two firings rather than on one:+ // with an on-the-hour cron every past firing's successor has already landed+ // at 12:00, and there is no "not yet superseded" case to express.+ let hourly = "0 30 * * * *";+ let previous = now() - Duration::minutes(30);+ let repo = FakeRepo::with_due(vec![due_with_cron(1, hourly, previous)]);+ let notifier = FakeNotifier::default();++ let outcome = service(repo.clone(), notifier.clone(), FakeQueue::default())+ .deliver(DueFiring {+ reminder_id: uuid(1),+ scheduled_for: previous,+ })+ .await+ .expect("delivery succeeds");++ assert_eq!(outcome, DeliveryOutcome::Delivered);+ assert_eq!(notifier.notified(), vec![uuid(1)]);+}++#[tokio::test]+async fn a_long_period_firing_past_the_outside_limit_is_rolled_forward() {+ // The backstop, isolated from the rule above. A monthly reminder a month+ // late has not been overtaken — its successor is still weeks away — but+ // delivering it now would be reporting history.+ let long_ago = now() - Duration::days(30);+ let repo = FakeRepo::with_due(vec![due_with_cron(1, "0 0 9 1 * *", long_ago)]);+ let notifier = FakeNotifier::default();++ let outcome = service(repo.clone(), notifier.clone(), FakeQueue::default())+ .deliver(DueFiring {+ reminder_id: uuid(1),+ scheduled_for: long_ago,+ })+ .await+ .expect("delivery succeeds");++ assert_eq!(outcome, DeliveryOutcome::RolledForward);assert!(notifier.notified().is_empty());}+#[tokio::test]+async fn a_stale_series_with_no_firing_left_is_completed_without_advancing() {+ // A year-qualified cron that has run out. `advance_to` is None, so the+ // reminder stays where it is and stops coming due because its own+ // occurrence is marked sent — subtle enough to be worth pinning, since+ // nothing else would notice if it started coming due forever.+ let schedule = ReminderSchedule::Recurring {+ cron: ReminderCron::parse("0 0 9 * * * 2020").expect("valid cron"),+ timezone: New_York,+ };+ let stale_at = now() - Duration::days(2);+ let mut due = due_recurring_at(1, stale_at);+ due.reminder.schedule = schedule;+ let repo = FakeRepo::with_due(vec![due]);+ let notifier = FakeNotifier::default();++ let outcome = service(repo.clone(), notifier.clone(), FakeQueue::default())+ .deliver(DueFiring {+ reminder_id: uuid(1),+ scheduled_for: stale_at,+ })+ .await+ .expect("delivery succeeds");++ assert_eq!(outcome, DeliveryOutcome::RolledForward);+ assert!(notifier.notified().is_empty());+ assert_eq!(repo.advanced(), vec![(uuid(1), None)]);+}++#[tokio::test]+async fn a_stale_one_shot_is_still_delivered() {+ // The staleness valve is recurring-only. An overdue one-shot staying+ // overdue until its owner deals with it is the point of one.+ let stale_at = now() - Duration::days(2);+ let mut due = due_once(1);+ due.reminder.next_run_at = stale_at;+ due.scheduled_for = stale_at;+ let repo = FakeRepo::with_due(vec![due]);+ let notifier = FakeNotifier::default();++ let outcome = service(repo.clone(), notifier.clone(), FakeQueue::default())+ .deliver(DueFiring {+ reminder_id: uuid(1),+ scheduled_for: stale_at,+ })+ .await+ .expect("delivery succeeds");++ assert_eq!(outcome, DeliveryOutcome::Delivered);+ assert_eq!(notifier.notified(), vec![uuid(1)]);+}+#[tokio::test]async fn a_firing_that_no_longer_exists_is_acked_not_delivered() {let repo = FakeRepo::default();diff --git a/crates/reminders/src/domain/service/test.rs b/crates/reminders/src/domain/service/test.rsindex d9b8939aaa..b88abc67a1 100644--- a/crates/reminders/src/domain/service/test.rs+++ b/crates/reminders/src/domain/service/test.rs@@ -375,6 +375,15 @@ impl RemindersRepo for FakeRemindersRepo {if let Some(enabled) = update.enabled {reminder.enabled = enabled;}+ if let Some(completed) = update.completed {+ // Mirrors the SQL: an explicit `completed` outranks the reschedule+ // revival above, and re-completing leaves the original stamp be.+ reminder.completed_at = if completed {+ reminder.completed_at.or_else(|| Some(now()))+ } else {+ None+ };+ }reminder.updated_at = now();Ok(Some(reminder.clone()))@@ -407,6 +416,29 @@ fn complete(service: &RemindersServiceImpl<FakeRemindersRepo, FixedClock>, id: Ureminder.completed_at = Some(now());}+/// Park a reminder out of service with its firing left in the past, which is+/// the state a recurring reminder is in after spending a while switched off.+fn park(+ service: &RemindersServiceImpl<FakeRemindersRepo, FixedClock>,+ id: Uuid,+ next_run_at: DateTime<Utc>,+) {+ let mut rows = service.repo.rows.lock().expect("rows lock poisoned");+ let (_, reminder) = rows+ .iter_mut()+ .find(|(_, reminder)| reminder.id == id)+ .expect("reminder exists");+ reminder.enabled = false;+ reminder.next_run_at = next_run_at;+}++/// The next 09:00 in New York after [`now`], which is 12:00 UTC — 08:00 there.+fn next_daily_9am() -> DateTime<Utc> {+ Utc.with_ymd_and_hms(2026, 7, 1, 13, 0, 0)+ .single()+ .expect("unambiguous instant")+}+#[tokio::test]async fn creates_a_standalone_reminder_without_a_receipt() {let remind_at = future();@@ -903,6 +935,185 @@ async fn updates_description_and_enabled() {assert_eq!(updated.next_run_at, created.next_run_at);}+#[tokio::test]+async fn rejects_a_cron_that_fires_more_often_than_the_minimum() {+ // Every minute. The sweep could almost keep up, which is exactly why this+ // needs refusing: it would deliver, not fall behind.+ let every_minute = ReminderSchedule::Recurring {+ cron: ReminderCron::parse("0 * * * * *").expect("valid cron"),+ timezone: New_York,+ };++ let result = service()+ .create_reminder(&user(USER_A), create_request(every_minute), None)+ .await;++ assert!(matches!(result, Err(ReminderError::BadRequest(_))));+}++#[tokio::test]+async fn interval_validation_does_not_depend_on_when_the_request_arrives() {+ // Firings need not be evenly spaced. `0 0,4 9 * * *` fires at 09:00 and+ // 09:04 daily, so the gap after `now` is four minutes before 09:00 and+ // nearly a day after it. Measuring only the first gap accepted or rejected+ // the same schedule depending on the hour it was submitted.+ let clustered = ReminderSchedule::Recurring {+ cron: ReminderCron::parse("0 0,4 9 * * *").expect("valid cron"),+ timezone: New_York,+ };++ // `now` here is 12:00 UTC — 08:00 in New York, ahead of both firings.+ let before = service()+ .create_reminder(&user(USER_A), create_request(clustered.clone()), None)+ .await;+ assert!(matches!(before, Err(ReminderError::BadRequest(_))));++ // 13:02 UTC is 09:02 in New York, between the two firings.+ let between = RemindersServiceImpl::with_clock(+ FakeRemindersRepo::default(),+ FixedClock(now() + Duration::hours(1) + Duration::minutes(2)),+ )+ .create_reminder(&user(USER_A), create_request(clustered), None)+ .await;+ assert!(+ matches!(between, Err(ReminderError::BadRequest(_))),+ "the same schedule must be rejected whenever it is submitted"+ );+}++#[tokio::test]+async fn re_enabling_a_long_disabled_recurring_reminder_moves_its_firing_forward() {+ let service = service();+ let created = service+ .create_reminder(&user(USER_A), create_request(recurring()), None)+ .await+ .expect("created");+ // Switched off months ago, so its firing is long past.+ park(&service, created.id, now() - Duration::days(90));++ let updated = service+ .update_reminder(+ owner_receipt(USER_A, created.id),+ ReminderPatch {+ enabled: Some(true),+ ..Default::default()+ },+ )+ .await+ .expect("update should succeed");++ // Switching a reminder back on should not present a date from April as the+ // next thing that will happen.+ assert_eq!(updated.next_run_at, next_daily_9am());+ assert!(updated.enabled);+}++#[tokio::test]+async fn un_completing_a_long_finished_recurring_reminder_moves_its_firing_forward() {+ let service = service();+ let created = service+ .create_reminder(&user(USER_A), create_request(recurring()), None)+ .await+ .expect("created");+ park(&service, created.id, now() - Duration::days(90));+ complete(&service, created.id);++ let updated = service+ .update_reminder(+ owner_receipt(USER_A, created.id),+ ReminderPatch {+ enabled: Some(true),+ completed: Some(false),+ ..Default::default()+ },+ )+ .await+ .expect("update should succeed");++ assert_eq!(updated.next_run_at, next_daily_9am());+ assert!(updated.completed_at.is_none());+}++#[tokio::test]+async fn re_enabling_does_not_move_a_firing_that_is_merely_due() {+ // The guard that keeps this narrow. A firing a minute old is one the+ // dispatcher is about to deliver, and moving it would make that delivery+ // find the time changed underneath it and drop the notification.+ let service = service();+ let created = service+ .create_reminder(&user(USER_A), create_request(recurring()), None)+ .await+ .expect("created");+ let imminent = now() - Duration::minutes(1);+ park(&service, created.id, imminent);++ let updated = service+ .update_reminder(+ owner_receipt(USER_A, created.id),+ ReminderPatch {+ enabled: Some(true),+ ..Default::default()+ },+ )+ .await+ .expect("update should succeed");++ assert_eq!(updated.next_run_at, imminent);+}++#[tokio::test]+async fn re_enabling_alongside_a_new_schedule_keeps_the_schedule_the_owner_chose() {+ let service = service();+ let created = service+ .create_reminder(&user(USER_A), create_request(recurring()), None)+ .await+ .expect("created");+ park(&service, created.id, now() - Duration::days(90));+ let chosen = now() + Duration::days(3);++ let updated = service+ .update_reminder(+ owner_receipt(USER_A, created.id),+ ReminderPatch {+ schedule: Some(once(chosen)),+ enabled: Some(true),+ ..Default::default()+ },+ )+ .await+ .expect("update should succeed");++ // Naming a firing is not a revival: recomputing over the top of it would+ // discard what the owner just asked for.+ assert_eq!(updated.next_run_at, chosen);+}++#[tokio::test]+async fn re_enabling_a_one_shot_leaves_its_firing_alone() {+ // A one-shot has no cron to recompute from, and an overdue one staying+ // overdue is the point of it.+ let service = service();+ let created = service+ .create_reminder(&user(USER_A), create_request(once(future())), None)+ .await+ .expect("created");+ let past = now() - Duration::days(90);+ park(&service, created.id, past);++ let updated = service+ .update_reminder(+ owner_receipt(USER_A, created.id),+ ReminderPatch {+ enabled: Some(true),+ ..Default::default()+ },+ )+ .await+ .expect("update should succeed");++ assert_eq!(updated.next_run_at, past);+}+#[tokio::test]async fn updating_the_schedule_recomputes_next_run_at() {let service = service();diff --git a/crates/reminders/src/outbound/notification_notifier.rs b/crates/reminders/src/outbound/notification_notifier.rsindex 51b27d6f49..8a5b3bfee9 100644--- a/crates/reminders/src/outbound/notification_notifier.rs+++ b/crates/reminders/src/outbound/notification_notifier.rs@@ -52,6 +52,9 @@ impl<I: NotificationIngress> ReminderNotifier for NotificationReminderNotifier<Inotification: ReminderMetadata {reminder_id: due.reminder.id,description: due.reminder.description.clone(),+ // Which occurrence this is. A recurring reminder produces one+ // notification per firing, identical but for this.+ scheduled_for: Some(due.scheduled_for),},// Must stay None. A recipient who is also the sender is filtered// out of their own notification, and a reminder's only recipient isdiff --git a/crates/reminders/src/outbound/notification_notifier/test.rs b/crates/reminders/src/outbound/notification_notifier/test.rsindex 0f0e3cc525..68909f14cc 100644--- a/crates/reminders/src/outbound/notification_notifier/test.rs+++ b/crates/reminders/src/outbound/notification_notifier/test.rs@@ -169,6 +169,12 @@ async fn carries_the_reminder_payload_under_the_reminder_tag() {notification["content"]["description"],"Follow up on the contract");+ // Which firing this is. Two occurrences of a recurring reminder are+ // identical but for this, and the push collapse key is built from it.+ assert_eq!(+ notification["content"]["scheduledFor"],+ "2026-07-01T12:00:00Z"+ );}#[tokio::test]diff --git a/crates/reminders/src/outbound/pg_reminders_repo.rs b/crates/reminders/src/outbound/pg_reminders_repo.rsindex 760d962333..515eff1f0c 100644--- a/crates/reminders/src/outbound/pg_reminders_repo.rs+++ b/crates/reminders/src/outbound/pg_reminders_repo.rs@@ -14,9 +14,9 @@ use sqlx::PgPool;use uuid::Uuid;use crate::domain::models::{- DueFiring, DueReminder, InvalidCron, NewReminder, Reminder, ReminderBatch, ReminderCron,- ReminderCursor, ReminderFilter, ReminderForSoup, ReminderReference, ReminderSchedule,- ReminderUpdate, SoupOrder, SoupReminderQuery,+ Advance, Completion, DueFiring, DueReminder, InvalidCron, NewReminder, Reminder, ReminderBatch,+ ReminderCron, ReminderCursor, ReminderFilter, ReminderForSoup, ReminderReference,+ ReminderSchedule, ReminderUpdate, SoupOrder, SoupReminderQuery,};use crate::domain::ports::{ReminderDispatchRepo, RemindersRepo};@@ -649,13 +649,14 @@ impl ReminderDispatchRepo for PgRemindersRepo {#[tracing::instrument(err, skip(self))]async fn due_firings(&self, now: DateTime<Utc>) -> Result<Vec<DueFiring>, Self::Err> {- // Driven by `reminder_due_idx`: (next_run_at) WHERE enabled AND- // completed_at IS NULL, with recurring rows filtered out on top.+ // Driven by `reminder_due_v2_idx`: (next_run_at) WHERE enabled AND+ // (cron IS NOT NULL OR completed_at IS NULL).//- // Recurring reminders are excluded here as well as at delivery because- // one is never completed and never has its next_run_at advanced, so it- // stays due forever — every sweep would re-fan the same rows and pay- // for a message each, indefinitely.+ // Both schedule kinds. A recurring reminder stops being due the moment+ // delivery rolls its `next_run_at` forward, which is why that advance+ // shares a transaction with the sent occurrence — see+ // `complete_occurrence_and_advance`. Were the two ever to come apart, the+ // row would fall out of this query permanently rather than merely re-fan.//// Unbounded on purpose: a sweep publishes ids, so the cost of a large// one is a batch send per ten rows, and the ceiling is the queue's@@ -676,8 +677,11 @@ impl ReminderDispatchRepo for PgRemindersRepo {SELECT r.id, r.next_run_atFROM reminder rWHERE r.enabled- AND r.completed_at IS NULL- AND r.cron IS NULL+ -- Completion is per-firing, so it only retires a one-shot. A+ -- recurring reminder its owner has ticked off keeps coming due:+ -- they dealt with the last nudge, not with the standing+ -- arrangement, and ending that is what deleting is for.+ AND (r.cron IS NOT NULL OR r.completed_at IS NULL)AND r.next_run_at <= $1AND NOT EXISTS (SELECT 1@@ -706,10 +710,9 @@ impl ReminderDispatchRepo for PgRemindersRepo {async fn find_due_reminder(&self, firing: DueFiring) -> Result<Option<DueReminder>, Self::Err> {// Matching `next_run_at` exactly is what makes a stale message safe: an// edit moves the firing, and this then finds nothing rather than- // delivering the reminder at a time the user cancelled.- //- // `cron IS NULL` is deliberately absent — the domain refuses recurring- // reminders itself so the gap stays visible there.+ // delivering the reminder at a time the user cancelled. It does the+ // same for a recurring firing that was re-fanned after the series had+ // already moved past it.let row = sqlx::query_as!(DueReminderRow,r#"@@ -731,7 +734,9 @@ impl ReminderDispatchRepo for PgRemindersRepo {WHERE id = $1AND next_run_at = $2AND enabled- AND completed_at IS NULL+ -- Matches `due_firings`: a completed recurring reminder is still+ -- deliverable, a completed one-shot is finished.+ AND (cron IS NOT NULL OR completed_at IS NULL)"#,firing.reminder_id,firing.scheduled_for,@@ -804,15 +809,24 @@ impl ReminderDispatchRepo for PgRemindersRepo {}#[tracing::instrument(err, skip(self))]- async fn complete_occurrence(+ async fn complete_occurrence_and_advance(&self,reminder_id: Uuid,scheduled_for: DateTime<Utc>,- ) -> Result<(), Self::Err> {- // Only the occurrence. Delivery is not completion: `completed_at` means- // the owner is finished with the reminder, and a reminder that has just- // arrived in their inbox plainly is not. What stops a delivered firing- // being sent twice is this row, which `due_firings` excludes on.+ advance: Option<Advance>,+ ) -> Result<Completion, Self::Err> {+ // One transaction, because the two writes are only correct together.+ // Marking the occurrence sent is what stops this firing going out+ // twice; advancing `next_run_at` is what brings the next one around. A+ // recurring reminder that got the first without the second would be+ // excluded by its own sent occurrence and never move again — silently+ // dead, and invisible until someone noticed the notifications had+ // stopped. Every other failure here is retryable; that one is not.+ let mut tx = self.pool.begin().await?;++ // The reminder itself is left alone. Delivery is not completion:+ // `completed_at` means the owner is finished with the reminder, and one+ // that has just arrived in their inbox plainly is not.sqlx::query!(r#"UPDATE reminder_occurrence@@ -822,9 +836,110 @@ impl ReminderDispatchRepo for PgRemindersRepo {reminder_id,scheduled_for,)- .execute(&self.pool)+ .execute(tx.as_mut())+ .await?;++ let Some(advance) = advance else {+ tx.commit().await?;+ return Ok(Completion::NoAdvance);+ };++ // `next_run_at = $3` guards against overwriting a reschedule the owner+ // made while this delivery was in flight. Their time is a decision; the+ // advance is bookkeeping, so a mismatch here is a correct no-op rather+ // than a lost update.+ //+ // Which row count tells apart from a failed advance: both leave the+ // reminder where it was, and only this says which happened.+ let advanced = sqlx::query!(+ r#"+ UPDATE reminder+ SET next_run_at = $2,+ -- Cleared only when the owner was notified. A firing they can+ -- see supersedes their "done" on the previous one; a firing+ -- rolled forward in silence supersedes nothing.+ completed_at = CASE WHEN $4::bool THEN NULL ELSE completed_at END,+ updated_at = now()+ WHERE id = $1 AND next_run_at = $3+ "#,+ reminder_id,+ advance.next_run_at,+ scheduled_for,+ advance.clear_completion,+ )+ .execute(tx.as_mut())+ .await?+ .rows_affected();++ tx.commit().await?;++ Ok(if advanced > 0 {+ Completion::Advanced+ } else {+ Completion::NotAdvanced+ })+ }++ #[tracing::instrument(err, skip(self))]+ async fn retract_notifications(+ &self,+ reminder_id: Uuid,+ before: DateTime<Utc>,+ ) -> Result<(), Self::Err> {+ // Reaches into `notification` for the same reason `delete_reminder`+ // does: a reminder *is* its notification's `event_item`, so the two are+ // one thing to a reader even though they belong to different domains.+ // `user_notification` cascades from this row.+ //+ // Bounded by the firing rather than clearing the reminder outright, so+ // the notification this delivery just created — and any a concurrent+ // delivery of a later firing created — survive. `scheduledFor` is the+ // firing each notification was written for; rows without it predate+ // recurring dispatch and are older than anything being delivered now.+ //+ // Read the candidates, decide here, delete by id.+ //+ // The obvious form is one statement comparing the metadata timestamp+ // directly, but that needs a cast, and a cast in a predicate fails the+ // whole statement on a single malformed value — which, since a failed+ // retraction is swallowed, would show up as tidying that quietly never+ // happened. `pg_input_is_valid` would guard it, but that is Postgres 16+ // and production runs 14. Parsing here costs one round trip on a cold+ // path and cannot be defeated by a bad row or an older server.+ let candidates = sqlx::query!(+ r#"+ SELECT id, metadata->>'scheduledFor' AS "scheduled_for?"+ FROM notification+ WHERE event_item_type = 'reminder' AND event_item_id = $1+ "#,+ reminder_id.to_string(),+ )+ .fetch_all(&self.pool).await?;+ let stale: Vec<Uuid> = candidates+ .into_iter()+ .filter(|row| match row.scheduled_for.as_deref() {+ // No firing recorded: written before recurring dispatch, so+ // older than anything being delivered now.+ None => true,+ // Unreadable is treated as stale, which is what it is.+ Some(raw) => match DateTime::parse_from_rfc3339(raw) {+ Ok(at) => at.with_timezone(&Utc) < before,+ Err(_) => true,+ },+ })+ .map(|row| row.id)+ .collect();++ if stale.is_empty() {+ return Ok(());+ }++ sqlx::query!(r#"DELETE FROM notification WHERE id = ANY($1)"#, &stale)+ .execute(&self.pool)+ .await?;+Ok(())}}diff --git a/crates/reminders/src/outbound/pg_reminders_repo/test.rs b/crates/reminders/src/outbound/pg_reminders_repo/test.rsindex 0a53097550..15c7876efc 100644--- a/crates/reminders/src/outbound/pg_reminders_repo/test.rs+++ b/crates/reminders/src/outbound/pg_reminders_repo/test.rs@@ -7,7 +7,7 @@ use sqlx::PgPool;use super::*;use crate::domain::models::{- ReminderCursor, ScheduleUpdate, SoupOrder, SoupReminderQuery, entity_token,+ Advance, ReminderCursor, ScheduleUpdate, SoupOrder, SoupReminderQuery, entity_token,};const USER_A: &str = "macro|[email protected]";@@ -1110,23 +1110,25 @@ async fn due_firings_returns_only_firings_that_have_arrived(pool: PgPool) {}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn due_firings_exclude_recurring_reminders(pool: PgPool) {- // A recurring reminder is never completed and never has its next_run_at- // advanced, so if the query returned it the row would stay due forever and- // every sweep would pay for a message that delivery then refuses.+async fn due_firings_include_recurring_reminders(pool: PgPool) {+ // Both schedule kinds come back. A recurring reminder leaves the due set by+ // having its next_run_at advanced at delivery, not by being filtered here.insert_user(&pool, USER_A).await;let repo = PgRemindersRepo::new(pool.clone());let now = at(2026, 8, 1, 12);- repo.create_reminder(&user(USER_A), &new_reminder("standup", recurring()))+ let recurring_reminder = repo+ .create_reminder(&user(USER_A), &new_reminder("standup", recurring())).await.expect("recurring reminder should insert");let one_shot = create_due(&pool, USER_A, at(2026, 8, 1, 11)).await;let due = repo.due_firings(now).await.expect("query succeeds");- assert_eq!(due.len(), 1);- assert_eq!(due[0].reminder_id, one_shot.id);+ let ids: Vec<_> = due.iter().map(|firing| firing.reminder_id).collect();+ assert_eq!(due.len(), 2);+ assert!(ids.contains(&recurring_reminder.id));+ assert!(ids.contains(&one_shot.id));}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]@@ -1153,6 +1155,159 @@ async fn due_firings_span_users(pool: PgPool) {assert_eq!(owners, vec![USER_B, USER_A], "soonest firing first");}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_completed_recurring_reminder_is_still_due(pool: PgPool) {+ // Marking a recurring reminder done settles the firing in front of you, not+ // the standing arrangement. Ending the series is what deleting is for, so+ // completion must not quietly retire it.+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool.clone());+ let reminder = repo+ .create_reminder(&user(USER_A), &new_reminder("standup", recurring()))+ .await+ .expect("insert");++ repo.update_reminder(+ &user(USER_A),+ reminder.id,+ &ReminderUpdate {+ completed: Some(true),+ ..Default::default()+ },+ )+ .await+ .expect("complete succeeds");++ let due = repo+ .due_firings(at(2026, 8, 1, 12))+ .await+ .expect("query succeeds");+ assert_eq!(due.len(), 1);+ assert_eq!(due[0].reminder_id, reminder.id);++ // And it still resolves at delivery, or the sweep would fan out a firing+ // that then evaporates.+ let resolved = repo.find_due_reminder(due[0]).await.expect("read succeeds");+ assert!(resolved.is_some());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_disabled_recurring_reminder_is_not_due(pool: PgPool) {+ // The distinction completion no longer carries. `enabled` is the pause+ // switch; without it there would be no way to stop a series short of+ // deleting it.+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool.clone());+ let reminder = repo+ .create_reminder(&user(USER_A), &new_reminder("standup", recurring()))+ .await+ .expect("insert");++ repo.update_reminder(+ &user(USER_A),+ reminder.id,+ &ReminderUpdate {+ enabled: Some(false),+ ..Default::default()+ },+ )+ .await+ .expect("disable succeeds");++ let due = repo+ .due_firings(at(2026, 8, 1, 12))+ .await+ .expect("query succeeds");+ assert!(due.is_empty());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn delivering_a_recurring_firing_clears_an_earlier_done(pool: PgPool) {+ // The owner ticked off the last nudge; this one has just landed in their+ // inbox, so the reminder is outstanding again and must not read as Done.+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool.clone());+ let reminder = repo+ .create_reminder(&user(USER_A), &new_reminder("standup", recurring()))+ .await+ .expect("insert");+ repo.update_reminder(+ &user(USER_A),+ reminder.id,+ &ReminderUpdate {+ completed: Some(true),+ ..Default::default()+ },+ )+ .await+ .expect("complete succeeds");++ repo.claim_occurrence(reminder.id, reminder.next_run_at, no_retry())+ .await+ .expect("claim succeeds");+ repo.complete_occurrence_and_advance(+ reminder.id,+ reminder.next_run_at,+ Some(Advance {+ next_run_at: at(2026, 9, 9, 13),+ clear_completion: true,+ }),+ )+ .await+ .expect("complete succeeds");++ let stored = repo+ .get_reminder(&user(USER_A), reminder.id)+ .await+ .expect("read succeeds")+ .expect("still exists");+ assert!(stored.completed_at.is_none());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn rolling_a_firing_forward_silently_leaves_done_alone(pool: PgPool) {+ // Nothing reached the owner, so nothing supersedes what they already dealt+ // with. Clearing here would return the reminder to their attention with no+ // notification to explain why.+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool.clone());+ let reminder = repo+ .create_reminder(&user(USER_A), &new_reminder("standup", recurring()))+ .await+ .expect("insert");+ repo.update_reminder(+ &user(USER_A),+ reminder.id,+ &ReminderUpdate {+ completed: Some(true),+ ..Default::default()+ },+ )+ .await+ .expect("complete succeeds");++ repo.claim_occurrence(reminder.id, reminder.next_run_at, no_retry())+ .await+ .expect("claim succeeds");+ repo.complete_occurrence_and_advance(+ reminder.id,+ reminder.next_run_at,+ Some(Advance {+ next_run_at: at(2026, 9, 9, 13),+ clear_completion: false,+ }),+ )+ .await+ .expect("complete succeeds");++ let stored = repo+ .get_reminder(&user(USER_A), reminder.id)+ .await+ .expect("read succeeds")+ .expect("still exists");+ assert!(stored.completed_at.is_some());+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn due_firings_skip_disabled_and_completed(pool: PgPool) {insert_user(&pool, USER_A).await;@@ -1323,7 +1478,7 @@ async fn releasing_a_delivered_firing_does_not_un_send_it(pool: PgPool) {repo.claim_occurrence(reminder.id, reminder.next_run_at, no_retry()).await.expect("claim succeeds");- repo.complete_occurrence(reminder.id, reminder.next_run_at)+ repo.complete_occurrence_and_advance(reminder.id, reminder.next_run_at, None).await.expect("complete succeeds");repo.release_occurrence(reminder.id, reminder.next_run_at)@@ -1404,7 +1559,7 @@ async fn a_delivered_firing_is_never_reclaimed(pool: PgPool) {repo.claim_occurrence(reminder.id, reminder.next_run_at, no_retry()).await.expect("claim succeeds");- repo.complete_occurrence(reminder.id, reminder.next_run_at)+ repo.complete_occurrence_and_advance(reminder.id, reminder.next_run_at, None).await.expect("complete succeeds");@@ -1431,7 +1586,7 @@ async fn a_delivered_firing_stops_being_due_without_completing_the_reminder(poolrepo.claim_occurrence(reminder.id, reminder.next_run_at, no_retry()).await.expect("claim succeeds");- repo.complete_occurrence(reminder.id, reminder.next_run_at)+ repo.complete_occurrence_and_advance(reminder.id, reminder.next_run_at, None).await.expect("complete succeeds");@@ -1467,6 +1622,311 @@ async fn a_delivered_firing_stops_being_due_without_completing_the_reminder(poolassert!(due.is_empty());}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn completing_a_recurring_firing_advances_it_to_the_next_one(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool.clone());+ let reminder = repo+ .create_reminder(&user(USER_A), &new_reminder("standup", recurring()))+ .await+ .expect("recurring reminder should insert");+ let next = at(2026, 9, 9, 13);++ repo.claim_occurrence(reminder.id, reminder.next_run_at, no_retry())+ .await+ .expect("claim succeeds");+ let completion = repo+ .complete_occurrence_and_advance(+ reminder.id,+ reminder.next_run_at,+ Some(Advance {+ next_run_at: next,+ clear_completion: true,+ }),+ )+ .await+ .expect("complete succeeds");++ assert_eq!(completion, Completion::Advanced);++ // Both halves of the transaction: this firing is spent, and the series has+ // somewhere to go. Either one alone would be a bug — sent without advanced+ // is a reminder that goes quiet forever.+ let sent_at: Option<DateTime<Utc>> = sqlx::query_scalar(+ r#"SELECT sent_at FROM reminder_occurrence WHERE reminder_id = $1 AND scheduled_for = $2"#,+ )+ .bind(reminder.id)+ .bind(reminder.next_run_at)+ .fetch_one(&pool)+ .await+ .expect("occurrence exists");+ assert!(sent_at.is_some());++ let stored = repo+ .get_reminder(&user(USER_A), reminder.id)+ .await+ .expect("read succeeds")+ .expect("reminder still exists");+ assert_eq!(stored.next_run_at, next);+ assert!(+ stored.completed_at.is_none(),+ "a series that fired is not a series its owner has finished with"+ );++ // Due again at the new firing, and not before it.+ let before = repo+ .due_firings(next - Duration::minutes(1))+ .await+ .expect("query succeeds");+ assert!(before.is_empty());++ let after = repo.due_firings(next).await.expect("query succeeds");+ assert_eq!(after.len(), 1);+ assert_eq!(after[0].scheduled_for, next);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn completing_does_not_advance_a_reminder_the_owner_rescheduled(pool: PgPool) {+ // The owner moved the reminder while the delivery was in flight. Their time+ // is a decision and the advance is bookkeeping, so the advance must lose.+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool.clone());+ let reminder = repo+ .create_reminder(&user(USER_A), &new_reminder("standup", recurring()))+ .await+ .expect("recurring reminder should insert");+ let chosen = at(2026, 12, 25, 15);++ repo.claim_occurrence(reminder.id, reminder.next_run_at, no_retry())+ .await+ .expect("claim succeeds");+ repo.update_reminder(+ &user(USER_A),+ reminder.id,+ &ReminderUpdate {+ schedule: Some(ScheduleUpdate {+ schedule: once_at(chosen),+ next_run_at: chosen,+ }),+ ..Default::default()+ },+ )+ .await+ .expect("reschedule succeeds");++ // The delivery finishes afterwards, still holding the firing it started on.+ let completion = repo+ .complete_occurrence_and_advance(+ reminder.id,+ reminder.next_run_at,+ Some(Advance {+ next_run_at: at(2026, 9, 9, 13),+ clear_completion: true,+ }),+ )+ .await+ .expect("complete succeeds");++ // Reported, not silent. This and "the advance failed" leave the same row+ // behind, so the caller has no other way to tell them apart.+ assert_eq!(completion, Completion::NotAdvanced);++ let stored = repo+ .get_reminder(&user(USER_A), reminder.id)+ .await+ .expect("read succeeds")+ .expect("reminder still exists");+ assert_eq!(+ stored.next_run_at, chosen,+ "the advance must not overwrite a reschedule it raced"+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn completing_a_one_shot_reports_that_there_was_nothing_to_advance(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let reminder = create_due(&pool, USER_A, at(2026, 8, 1, 11)).await;+ let repo = PgRemindersRepo::new(pool);++ repo.claim_occurrence(reminder.id, reminder.next_run_at, no_retry())+ .await+ .expect("claim succeeds");+ let completion = repo+ .complete_occurrence_and_advance(reminder.id, reminder.next_run_at, None)+ .await+ .expect("complete succeeds");++ // Distinct from `NotAdvanced`: nothing was asked for, so nothing was+ // declined.+ assert_eq!(completion, Completion::NoAdvance);+}++/// Write a reminder notification for a given firing, as the notifier would.+///+/// `scheduled_for` rides in the metadata, which is what retraction filters on.+/// `None` stands in for a notification written before recurring dispatch, which+/// carries no firing at all.+async fn insert_reminder_notification(+ pool: &PgPool,+ reminder_id: Uuid,+ scheduled_for: Option<DateTime<Utc>>,+) {+ let notification_id = macro_uuid::generate_uuid_v7();+ let metadata = match scheduled_for {+ Some(at) => serde_json::json!({ "scheduledFor": at.to_rfc3339() }),+ None => serde_json::json!({}),+ };+ sqlx::query(+ r#"+ INSERT INTO notification+ (id, notification_event_type, event_item_id, event_item_type, service_sender, metadata)+ VALUES ($1, 'reminder', $2, 'reminder', 'reminders', $3)+ "#,+ )+ .bind(notification_id)+ .bind(reminder_id.to_string())+ .bind(metadata)+ .execute(pool)+ .await+ .expect("notification should insert");+ sqlx::query(r#"INSERT INTO user_notification (user_id, notification_id) VALUES ($1, $2)"#)+ .bind(USER_A)+ .bind(notification_id)+ .execute(pool)+ .await+ .expect("user_notification should insert");+}++/// The firings every reminder notification in the table was written for.+async fn notification_firings(pool: &PgPool, reminder_id: Uuid) -> Vec<Option<String>> {+ sqlx::query_scalar(+ r#"+ SELECT metadata->>'scheduledFor'+ FROM notification+ WHERE event_item_type = 'reminder' AND event_item_id = $1+ ORDER BY 1+ "#,+ )+ .bind(reminder_id.to_string())+ .fetch_all(pool)+ .await+ .expect("query succeeds")+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn retracting_keeps_the_current_firing_and_anything_newer(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool.clone());+ let reminder = repo+ .create_reminder(&user(USER_A), &new_reminder("standup", recurring()))+ .await+ .expect("insert");++ let current = at(2026, 8, 2, 13);+ // An earlier firing to clear, the one being delivered now, one from a+ // concurrent delivery that has already moved ahead, and a legacy row with+ // no firing recorded at all.+ insert_reminder_notification(&pool, reminder.id, Some(at(2026, 8, 1, 13))).await;+ insert_reminder_notification(&pool, reminder.id, Some(current)).await;+ insert_reminder_notification(&pool, reminder.id, Some(at(2026, 8, 3, 13))).await;+ insert_reminder_notification(&pool, reminder.id, None).await;++ repo.retract_notifications(reminder.id, current)+ .await+ .expect("retract succeeds");++ let remaining = notification_firings(&pool, reminder.id).await;+ assert_eq!(+ remaining,+ vec![+ Some(at(2026, 8, 2, 13).to_rfc3339()),+ Some(at(2026, 8, 3, 13).to_rfc3339()),+ ],+ "only firings before the one delivered should be retracted"+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn retracting_survives_an_unreadable_firing_stamp(pool: PgPool) {+ // A malformed `scheduledFor` must not fail the statement. Postgres may+ // evaluate the OR arms in any order, so without a guard on the cast one bad+ // row anywhere would break retraction for every reminder — and because a+ // failed retraction is logged and swallowed, it would look like tidying+ // that simply never happened.+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool.clone());+ let reminder = repo+ .create_reminder(&user(USER_A), &new_reminder("standup", recurring()))+ .await+ .expect("insert");++ let current = at(2026, 8, 2, 13);+ sqlx::query(+ r#"+ INSERT INTO notification+ (id, notification_event_type, event_item_id, event_item_type, service_sender, metadata)+ VALUES ($1, 'reminder', $2, 'reminder', 'reminders', '{"scheduledFor": "not a timestamp"}')+ "#,+ )+ .bind(macro_uuid::generate_uuid_v7())+ .bind(reminder.id.to_string())+ .execute(&pool)+ .await+ .expect("notification should insert");+ insert_reminder_notification(&pool, reminder.id, Some(current)).await;++ repo.retract_notifications(reminder.id, current)+ .await+ .expect("retract must not fail on an unreadable stamp");++ // The unreadable one is treated as stale, which is what it is.+ assert_eq!(+ notification_firings(&pool, reminder.id).await,+ vec![Some(current.to_rfc3339())]+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn retracting_clears_only_this_reminders_notifications(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgRemindersRepo::new(pool.clone());++ let fired = repo+ .create_reminder(&user(USER_A), &new_reminder("standup", recurring()))+ .await+ .expect("insert");+ let untouched = create_due(&pool, USER_A, at(2026, 8, 1, 11)).await;++ for reminder_id in [fired.id, untouched.id] {+ insert_reminder_notification(&pool, reminder_id, Some(at(2026, 8, 1, 13))).await;+ }++ repo.retract_notifications(fired.id, at(2026, 8, 2, 13))+ .await+ .expect("retract succeeds");++ let remaining: Vec<String> = sqlx::query_scalar(+ r#"SELECT event_item_id FROM notification WHERE event_item_type = 'reminder'"#,+ )+ .fetch_all(&pool)+ .await+ .expect("query succeeds");+ assert_eq!(remaining, vec![untouched.id.to_string()]);++ // user_notification cascades, so the owner's inbox row goes with it rather+ // than being left pointing at nothing.+ let orphaned: i64 = sqlx::query_scalar(+ r#"+ SELECT count(*) FROM user_notification un+ WHERE NOT EXISTS (SELECT 1 FROM notification n WHERE n.id = un.notification_id)+ "#,+ )+ .fetch_one(&pool)+ .await+ .expect("query succeeds");+ assert_eq!(orphaned, 0);+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn a_rescheduled_reminder_becomes_due_again_after_delivery(pool: PgPool) {// The sent occurrence is keyed on the firing, so moving the firing makes the@@ -1478,7 +1938,7 @@ async fn a_rescheduled_reminder_becomes_due_again_after_delivery(pool: PgPool) {repo.claim_occurrence(reminder.id, reminder.next_run_at, no_retry()).await.expect("claim succeeds");- repo.complete_occurrence(reminder.id, reminder.next_run_at)+ repo.complete_occurrence_and_advance(reminder.id, reminder.next_run_at, None).await.expect("complete succeeds");diff --git a/packages/sdk/generated/notification/types.gen.ts b/packages/sdk/generated/notification/types.gen.tsindex 250b68c831..028faaeb1d 100644--- a/packages/sdk/generated/notification/types.gen.ts+++ b/packages/sdk/generated/notification/types.gen.ts@@ -980,6 +980,18 @@ export type ReminderMetadata = {* The reminder that fired.*/reminderId: string;+ /**+ * Which firing this is — the occurrence the reminder came due for.+ *+ * What distinguishes two firings of the same recurring reminder, which are+ * otherwise identical: same id, same description. The collapse key is+ * built from it, so without it Tuesday's alert would replace Monday's+ * unread one on the lock screen.+ *+ * Optional because notifications written before recurring dispatch existed+ * have no such field, and they still have to read back.+ */+ scheduledFor?: string | null;};/**diff --git a/packages/sdk/specs/notification.json b/packages/sdk/specs/notification.jsonindex 4bee79a2d4..dd56928e81 100644--- a/packages/sdk/specs/notification.json+++ b/packages/sdk/specs/notification.json@@ -2499,6 +2499,11 @@"type": "string","format": "uuid","description": "The reminder that fired."+ },+ "scheduledFor": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "Which firing this is — the occurrence the reminder came due for.\n\nWhat distinguishes two firings of the same recurring reminder, which are\notherwise identical: same id, same description. The collapse key is\nbuilt from it, so without it Tuesday's alert would replace Monday's\nunread one on the lock screen.\n\nOptional because notifications written before recurring dispatch existed\nhave no such field, and they still have to read back."}}},diff --git a/static_assets/schema.graphql b/static_assets/schema.graphqlindex 10cc5eacdb..87b8924a5a 100644--- a/static_assets/schema.graphql+++ b/static_assets/schema.graphql@@ -3245,6 +3245,14 @@ type GraphqlReminderMetadata {Reminder description."""description: String!+ """+ Which firing this notification is for, in RFC 3339 format.++ The counterpart of a calendar alarm's `occurrenceKey`: it is what tells+ two notifications from the same recurring reminder apart. Absent on+ notifications written before recurring dispatch existed.+ """+ scheduledFor: String}"""