Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(reminders): improve scheduling and draft safety (#6725)

gbirman84ad22d25119
diff --git a/apps/web/src/features/calendar/components/composer/EventDateTimeInputs.tsx b/apps/web/src/features/calendar/components/composer/EventDateTimeInputs.tsx
index c91c04476b..ca0c42d84c 100644
--- a/apps/web/src/features/calendar/components/composer/EventDateTimeInputs.tsx
+++ b/apps/web/src/features/calendar/components/composer/EventDateTimeInputs.tsx
@@ -52,8 +52,13 @@ interface EventTimeInputProps {
/** Highlighted option; defaults to `value` on the anchor day. */
selectedId?: string;
onChange: (option: EventTimeOption) => void;
+ /** Called when the native control is cleared; omitted where empty is invalid UI. */
+ onClear?: () => void;
onFocus?: () => void;
disabled?: boolean;
+ invalid?: boolean;
+ /** Native time precision in seconds. Calendar fields keep quarter-hour slots by default. */
+ step?: number;
hideLabel?: boolean;
class?: string;
}
@@ -109,12 +114,13 @@ export function EventTimeInput(props: EventTimeInputProps) {
<input
id={props.id}
type="time"
- step={900}
+ step={props.step ?? 900}
value={props.value}
disabled={props.disabled}
+ aria-invalid={props.invalid || undefined}
aria-expanded={open()}
aria-haspopup="listbox"
- class="w-full appearance-none rounded-md border border-edge-muted bg-control py-1.5 pr-7 pl-2 text-xs text-ink outline-none focus:border-accent disabled:opacity-50 [&::-webkit-calendar-picker-indicator]:hidden"
+ class="w-full appearance-none rounded-md border border-edge-muted bg-control py-1.5 pr-7 pl-2 text-xs text-ink outline-none focus:border-accent aria-invalid:border-failure aria-invalid:ring-2 aria-invalid:ring-failure/20 disabled:opacity-50 [&::-webkit-calendar-picker-indicator]:hidden"
onFocus={() => {
props.onFocus?.();
setDropdownOpen(true);
@@ -122,7 +128,10 @@ export function EventTimeInput(props: EventTimeInputProps) {
onClick={() => setDropdownOpen(true)}
onInput={(event) => {
const value = event.currentTarget.value;
- if (value && value !== props.value) {
+ if (!value) {
+ props.onClear?.();
+ setOpen(false);
+ } else if (value !== props.value) {
props.onChange(resolveTimeOption(options(), value));
}
}}
diff --git a/apps/web/src/features/reminders/ReminderComposerModal.test.tsx b/apps/web/src/features/reminders/ReminderComposerModal.test.tsx
index 974905c471..81987cc1dd 100644
--- a/apps/web/src/features/reminders/ReminderComposerModal.test.tsx
+++ b/apps/web/src/features/reminders/ReminderComposerModal.test.tsx
@@ -5,7 +5,7 @@ import {
screen,
waitFor,
} from '@solidjs/testing-library';
-import type { ParentProps } from 'solid-js';
+import { createSignal, type ParentProps, Show } from 'solid-js';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { ReminderComposerModal } from './ReminderComposerModal';
import {
@@ -16,21 +16,20 @@ import {
const mocks = vi.hoisted(() => ({
save: vi.fn(),
- pending: false,
- failure: vi.fn(),
+ success: vi.fn(),
+ openReminderDetail: vi.fn(),
}));
+
vi.mock('@queries/reminders/reminders', () => ({
reminderTarget: vi.fn(),
- useCreateReminderMutation: () => ({
- mutateAsync: mocks.save,
- get isPending() {
- return mocks.pending;
- },
- }),
+ useCreateReminderMutation: () => ({ mutateAsync: mocks.save }),
}));
vi.mock('@queries/soup/cache', () => ({ refetchSoupEntity: vi.fn() }));
+vi.mock('@app/features/reminders/reminder-navigation', () => ({
+ openReminderDetail: mocks.openReminderDetail,
+}));
vi.mock('@core/component/Toast/Toast', () => ({
- toast: { success: vi.fn(), failure: mocks.failure },
+ toast: { success: mocks.success, failure: vi.fn() },
}));
vi.mock('@entity/components/EntitySelectionBadge', () => ({
EntitySelectionBadge: () => null,
@@ -47,57 +46,154 @@ vi.mock('@ui', () => {
};
});
vi.mock('./ReminderForm', () => ({
- ReminderForm: (props: { onSubmit: (values: unknown) => void }) => (
- <div>
- <button
- type="button"
- onClick={() =>
+ ReminderForm: (props: {
+ pending?: boolean;
+ error?: string;
+ onSubmit: (values: {
+ description: string;
+ schedule: { type: 'once'; remindAt: string };
+ }) => void;
+ }) => {
+ const [description, setDescription] = createSignal('Follow up');
+ return (
+ <form
+ aria-label="Reminder form"
+ onSubmit={(event) => {
+ event.preventDefault();
props.onSubmit({
- description: 'Follow up',
- schedule: { type: 'once', remind_at: '2099-01-01T09:00:00Z' },
- })
- }
+ description: description(),
+ schedule: { type: 'once', remindAt: '2099-01-01T09:00:00Z' },
+ });
+ }}
>
- Submit
- </button>
- </div>
- ),
+ <input
+ aria-label="Reminder description"
+ value={description()}
+ disabled={props.pending}
+ onInput={(event) => setDescription(event.currentTarget.value)}
+ />
+ <button type="submit" disabled={props.pending}>
+ Submit
+ </button>
+ <Show when={props.error}>
+ <div role="alert">{props.error}</div>
+ </Show>
+ </form>
+ );
+ },
}));
+
+function savedReminder() {
+ return {
+ id: 'reminder-1',
+ schedule: { type: 'once', remindAt: '2099-01-01T09:00:00Z' },
+ };
+}
+
beforeEach(() => {
mocks.save.mockReset();
- mocks.pending = false;
- mocks.failure.mockClear();
+ mocks.success.mockReset();
+ mocks.openReminderDetail.mockReset();
closeReminderComposer();
});
+
afterEach(() => {
cleanup();
closeReminderComposer();
});
-it('dismisses before saving and calls the captured handler after success', async () => {
- let resolve!: (value: object) => void;
+
+it('keeps the draft open and prevents concurrent duplicate submits', async () => {
+ let rejectRequest!: (reason: Error) => void;
mocks.save.mockReturnValueOnce(
- new Promise((done) => {
- resolve = done;
+ new Promise((_resolve, reject) => {
+ rejectRequest = reject;
})
);
const onCreated = vi.fn();
openStandaloneReminderComposer({ onCreated });
render(() => <ReminderComposerModal />);
- fireEvent.click(screen.getByRole('button', { name: 'Submit' }));
- expect(reminderComposerOpen()).toBe(false);
+
+ const input = screen.getByRole('textbox', {
+ name: 'Reminder description',
+ });
+ fireEvent.input(input, { target: { value: 'Keep this draft' } });
+ input.focus();
+ const form = screen.getByRole('form', { name: 'Reminder form' });
+ fireEvent.submit(form);
+ fireEvent.submit(form);
+
+ expect(mocks.save).toHaveBeenCalledOnce();
+ expect(reminderComposerOpen()).toBe(true);
+ expect(
+ (screen.getByRole('button', { name: 'Submit' }) as HTMLButtonElement)
+ .disabled
+ ).toBe(true);
+ expect((input as HTMLInputElement).disabled).toBe(true);
+
+ rejectRequest(new Error('offline'));
+ const error = await screen.findByRole('alert');
+ expect(error.textContent).toContain('Your draft is still here');
+ expect(error.textContent).toContain('may already exist');
+ expect((input as HTMLInputElement).value).toBe('Keep this draft');
+ expect((input as HTMLInputElement).disabled).toBe(false);
+ expect(document.activeElement).toBe(input);
+ expect(reminderComposerOpen()).toBe(true);
expect(onCreated).not.toHaveBeenCalled();
- resolve({});
- await waitFor(() => expect(onCreated).toHaveBeenCalledOnce());
});
-it('reports a failed save by toast without reopening or calling the handler', async () => {
- mocks.save.mockRejectedValueOnce(new Error('offline'));
+
+it('retries with the same draft and opens View while route application is deferred', async () => {
+ mocks.openReminderDetail.mockReturnValue({ status: 'navigating' });
+ mocks.save
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockResolvedValueOnce(savedReminder());
const onCreated = vi.fn();
openStandaloneReminderComposer({ onCreated });
render(() => <ReminderComposerModal />);
- fireEvent.click(screen.getByRole('button', { name: 'Submit' }));
- await waitFor(() =>
- expect(mocks.failure).toHaveBeenCalledWith('Failed to create reminder')
+
+ const input = screen.getByRole('textbox', {
+ name: 'Reminder description',
+ });
+ fireEvent.input(input, { target: { value: 'Retry this reminder' } });
+ const form = screen.getByRole('form', { name: 'Reminder form' });
+ fireEvent.submit(form);
+ await screen.findByRole('alert');
+
+ fireEvent.submit(form);
+ await waitFor(() => expect(reminderComposerOpen()).toBe(false));
+
+ expect(mocks.save).toHaveBeenCalledTimes(2);
+ expect(mocks.save.mock.calls[1]?.[0]).toMatchObject({
+ description: 'Retry this reminder',
+ });
+ expect(onCreated).toHaveBeenCalledOnce();
+ expect(mocks.success).toHaveBeenCalledWith(
+ expect.stringContaining('Reminder set ·'),
+ expect.objectContaining({
+ actions: [expect.objectContaining({ label: 'View' })],
+ })
);
- expect(reminderComposerOpen()).toBe(false);
+ mocks.success.mock.calls[0]?.[1].actions[0].onClick();
+ expect(mocks.openReminderDetail).toHaveBeenCalledExactlyOnceWith(
+ 'reminder-1'
+ );
+});
+
+it('waits for a deferred mutation before closing and running the follow-up', async () => {
+ let resolveRequest!: (value: ReturnType<typeof savedReminder>) => void;
+ mocks.save.mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveRequest = resolve;
+ })
+ );
+ const onCreated = vi.fn();
+ openStandaloneReminderComposer({ onCreated });
+ render(() => <ReminderComposerModal />);
+
+ fireEvent.submit(screen.getByRole('form', { name: 'Reminder form' }));
+ expect(reminderComposerOpen()).toBe(true);
expect(onCreated).not.toHaveBeenCalled();
+
+ resolveRequest(savedReminder());
+ await waitFor(() => expect(reminderComposerOpen()).toBe(false));
+ expect(onCreated).toHaveBeenCalledOnce();
});
diff --git a/apps/web/src/features/reminders/ReminderComposerModal.tsx b/apps/web/src/features/reminders/ReminderComposerModal.tsx
index c6ff6d6598..71d61862d1 100644
--- a/apps/web/src/features/reminders/ReminderComposerModal.tsx
+++ b/apps/web/src/features/reminders/ReminderComposerModal.tsx
@@ -1,3 +1,4 @@
+import { openReminderDetail } from '@app/features/reminders/reminder-navigation';
import { toast } from '@core/component/Toast/Toast';
import type { EntityData } from '@entity';
import { EntitySelectionBadge } from '@entity/components/EntitySelectionBadge';
@@ -6,9 +7,11 @@ import {
useCreateReminderMutation,
} from '@queries/reminders/reminders';
import { refetchSoupEntity } from '@queries/soup/cache';
+import type { CreateReminderRequest } from '@service-storage/generated/schemas/createReminderRequest';
+import type { Reminder } from '@service-storage/generated/schemas/reminder';
import type { ReminderSchedule } from '@service-storage/generated/schemas/reminderSchedule';
import { ActionDialogShell, Dialog } from '@ui';
-import { Show } from 'solid-js';
+import { createSignal, Show } from 'solid-js';
import { ReminderForm } from './ReminderForm';
import {
closeReminderComposer,
@@ -17,10 +20,14 @@ import {
takeReminderCreatedHandler,
} from './reminder-composer';
import {
+ describeReminderConfirmation,
resolveReminderDescription,
resolveStandaloneDescription,
} from './reminder-schedule';
+const CREATE_FAILURE_MESSAGE =
+ 'We couldn’t save this reminder. Your draft is still here—try again. If the request timed out, it may already exist; check Reminders before retrying.';
+
/**
* Creates a reminder — one about an entity, or one about nothing at all — in a
* single panel. Editing an existing reminder happens in its own split view
@@ -38,6 +45,54 @@ export function ReminderComposerModal() {
const entity = () => reminderComposerState.entity;
const standalone = () => reminderComposerState.standalone === true;
+ const [submitting, setSubmitting] = createSignal(false);
+ const [saveError, setSaveError] = createSignal<string>();
+ let focusBeforeSave: HTMLElement | undefined;
+
+ const save = async (args: CreateReminderRequest) => {
+ if (submitting()) return;
+ focusBeforeSave =
+ document.activeElement instanceof HTMLElement
+ ? document.activeElement
+ : undefined;
+ setSubmitting(true);
+ setSaveError(undefined);
+
+ let reminder: Reminder;
+ try {
+ reminder = await createReminder.mutateAsync(args);
+ } catch {
+ setSaveError(CREATE_FAILURE_MESSAGE);
+ setSubmitting(false);
+ queueMicrotask(() => {
+ if (focusBeforeSave?.isConnected) focusBeforeSave.focus();
+ });
+ return;
+ }
+
+ const onCreated = takeReminderCreatedHandler();
+ setSubmitting(false);
+ closeReminderComposer();
+ toast.success(
+ `Reminder set · ${describeReminderConfirmation(reminder.schedule)}`,
+ {
+ actions: [
+ {
+ label: 'View',
+ onClick: () => void openReminderDetail(reminder.id),
+ },
+ ],
+ }
+ );
+ // This host-owned follow-up runs only after persistence. It is intentionally
+ // outside the request catch: a downstream row action failing does not mean
+ // the reminder failed to save and must never invite a duplicate retry.
+ try {
+ await onCreated?.();
+ } catch {
+ toast.failure('Reminder saved, but the source could not be updated');
+ }
+ };
const submitCreate = async (
schedule: ReminderSchedule,
@@ -46,27 +101,12 @@ export function ReminderComposerModal() {
) => {
const resolved = resolveReminderDescription(input, target);
const attachTo = reminderTarget(target);
- // Taken before the close, which clears it.
- const onCreated = takeReminderCreatedHandler();
- closeReminderComposer();
-
- try {
- await createReminder.mutateAsync({
- description: resolved,
- schedule,
- // Both or neither: the API rejects one without the other.
- ...(attachTo ?? undefined),
- });
- toast.success('Reminder set');
- } catch {
- toast.failure('Failed to create reminder');
- return;
- }
-
- // Whatever the invoking surface does with its row now that the reminder
- // will bring it back — marking it done, in every soup list. Runs only once
- // the reminder exists, so a failed create leaves the row alone.
- await onCreated?.();
+ await save({
+ description: resolved,
+ schedule,
+ // Both or neither: the API rejects one without the other.
+ ...(attachTo ?? undefined),
+ });
};
/**
@@ -85,20 +125,7 @@ export function ReminderComposerModal() {
// on it rather than a `!` on the value above.
if (!resolved) return;
- // Taken before the close, which clears it. Nothing passes one today, but
- // taking it is what keeps a handler from leaking into the next open.
- const onCreated = takeReminderCreatedHandler();
- closeReminderComposer();
-
- try {
- await createReminder.mutateAsync({ description: resolved, schedule });
- toast.success('Reminder set');
- } catch {
- toast.failure('Failed to create reminder');
- return;
- }
-
- await onCreated?.();
+ await save({ description: resolved, schedule });
};
const handleSubmit = (values: {
@@ -123,10 +150,13 @@ export function ReminderComposerModal() {
<Dialog
open={reminderComposerOpen()}
onOpenChange={(open) => {
- if (!open) closeReminderComposer();
+ if (!open && !submitting()) {
+ setSaveError(undefined);
+ closeReminderComposer();
+ }
}}
position="center"
- class="w-110"
+ class="w-[calc(100vw-2rem)] max-w-110"
>
<ActionDialogShell>
<Show when={hasTarget()}>
@@ -147,6 +177,9 @@ export function ReminderComposerModal() {
}
descriptionRequired={standalone()}
submitLabel="Set reminder"
+ autofocus
+ pending={submitting()}
+ error={saveError()}
reference={
<Show when={entity()}>
{(target) => (
@@ -156,7 +189,11 @@ export function ReminderComposerModal() {
)}
</Show>
}
- onCancel={closeReminderComposer}
+ onCancel={() => {
+ if (submitting()) return;
+ setSaveError(undefined);
+ closeReminderComposer();
+ }}
onSubmit={(values) => void handleSubmit(values)}
/>
</Show>
diff --git a/apps/web/src/features/reminders/ReminderEditorSplit.test.tsx b/apps/web/src/features/reminders/ReminderEditorSplit.test.tsx
index 3dcb2044af..b0aa21a357 100644
--- a/apps/web/src/features/reminders/ReminderEditorSplit.test.tsx
+++ b/apps/web/src/features/reminders/ReminderEditorSplit.test.tsx
@@ -39,11 +39,14 @@ vi.mock('@queries/soup/cache', () => ({
}));
vi.mock('./ReminderForm', () => ({
ReminderForm: (props: {
+ error?: string;
reference?: import('solid-js').JSX.Element;
+ onCancel: (wasDirty: boolean) => void;
onSubmit: (values: unknown) => void;
}) => (
<div data-testid="reminder-form">
{props.reference}
+ {props.error ? <div role="alert">{props.error}</div> : null}
<button
type="button"
onClick={() =>
@@ -55,10 +58,14 @@ vi.mock('./ReminderForm', () => ({
>
Save fixture
</button>
+ <button type="button" onClick={() => props.onCancel(true)}>
+ Cancel fixture
+ </button>
</div>
),
}));
vi.mock('./reminder-schedule', () => ({
+ describeReminderConfirmation: () => 'Sep 22, 2026 at 9:00 AM (UTC)',
reminderEditPatch: state.editPatch,
resolveEditedDescription: (description: string) => description,
}));
@@ -210,6 +217,26 @@ describe('ReminderDetails', () => {
expect(onClose).toHaveBeenCalledOnce();
});
+ it('clears a failed update error when reverting the edit in place', async () => {
+ state.mutateAsync.mockRejectedValue(new Error('request failed'));
+ const onClose = vi.fn();
+ const view = render(() => (
+ <ReminderDetails reminderId="reminder-1" onClose={onClose} />
+ ));
+
+ fireEvent.click(view.getByRole('button', { name: 'Save fixture' }));
+ expect(
+ await view.findByText(
+ 'We couldn’t save these changes. Your edits are still here—try again.'
+ )
+ ).toBeTruthy();
+
+ fireEvent.click(view.getByRole('button', { name: 'Cancel fixture' }));
+
+ expect(view.queryByRole('alert')).toBeNull();
+ expect(onClose).not.toHaveBeenCalled();
+ });
+
it('renders a useful fallback for a missing or inaccessible reminder', () => {
state.query = {
data: undefined,
diff --git a/apps/web/src/features/reminders/ReminderEditorSplit.tsx b/apps/web/src/features/reminders/ReminderEditorSplit.tsx
index 996df20bc6..f229de50fa 100644
--- a/apps/web/src/features/reminders/ReminderEditorSplit.tsx
+++ b/apps/web/src/features/reminders/ReminderEditorSplit.tsx
@@ -21,9 +21,17 @@ import {
} from '@queries/soup/cache';
import type { Reminder } from '@service-storage/generated/schemas/reminder';
import { Button } from '@ui';
-import { createMemo, Match, onCleanup, Show, Switch } from 'solid-js';
+import {
+ createMemo,
+ createSignal,
+ Match,
+ onCleanup,
+ Show,
+ Switch,
+} from 'solid-js';
import { ReminderForm, type ReminderFormValues } from './ReminderForm';
import {
+ describeReminderConfirmation,
reminderEditPatch,
resolveEditedDescription,
} from './reminder-schedule';
@@ -115,6 +123,8 @@ function ReminderDetailsForId(props: {
const calendarUiEnabled = useCalendarUiFlag();
const query = useReminderQuery(() => props.reminderId);
+ const [updateError, setUpdateError] = createSignal<string>();
+ let focusBeforeSave: HTMLElement | undefined;
// Soup rows come from the normalized soup cache, not the reminders queries, so
// the mutation's own invalidation leaves the row reading its old description
@@ -144,6 +154,12 @@ function ReminderDetailsForId(props: {
query.isError || (query.isSuccess && query.data === undefined);
const save = async (values: ReminderFormValues, reminder: Reminder) => {
+ if (updateReminder.isPending) return;
+ focusBeforeSave =
+ document.activeElement instanceof HTMLElement
+ ? document.activeElement
+ : undefined;
+ setUpdateError(undefined);
const patch = reminderEditPatch(
{
description: reminder.description,
@@ -171,13 +187,29 @@ function ReminderDetailsForId(props: {
}
const submittedReminderId = reminder.id;
try {
- await updateReminder.mutateAsync({ id: reminder.id, patch });
+ const updated = await updateReminder.mutateAsync({
+ id: reminder.id,
+ patch,
+ });
if (!active || props.reminderId !== submittedReminderId) return;
- toast.success('Reminder updated');
+ toast.success(
+ `Reminder updated · ${describeReminderConfirmation(updated.schedule)}`
+ );
props.onClose();
} catch {
if (!active || props.reminderId !== submittedReminderId) return;
- toast.failure('Failed to update reminder');
+ setUpdateError(
+ 'We couldn’t save these changes. Your edits are still here—try again.'
+ );
+ queueMicrotask(() => {
+ if (
+ active &&
+ props.reminderId === submittedReminderId &&
+ focusBeforeSave?.isConnected
+ ) {
+ focusBeforeSave.focus();
+ }
+ });
}
};
@@ -194,6 +226,7 @@ function ReminderDetailsForId(props: {
placeholder="Reminder description"
submitLabel="Save"
pending={updateReminder.isPending}
+ error={updateError()}
reference={
<>
<Show when={reference()}>
@@ -237,6 +270,7 @@ function ReminderDetailsForId(props: {
}
revertOnCancel
onCancel={(wasDirty) => {
+ setUpdateError(undefined);
// Reverting an edit keeps the panel open; a clean cancel
// dismisses the preview.
if (!wasDirty) props.onClose();
diff --git a/apps/web/src/features/reminders/ReminderForm.test.tsx b/apps/web/src/features/reminders/ReminderForm.test.tsx
new file mode 100644
index 0000000000..42dd410471
--- /dev/null
+++ b/apps/web/src/features/reminders/ReminderForm.test.tsx
@@ -0,0 +1,679 @@
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { ReminderForm, type ReminderFormValues } from './ReminderForm';
+
+let originalTimezone: string | undefined;
+
+beforeEach(() => {
+ originalTimezone = process.env.TZ;
+ process.env.TZ = 'UTC';
+ vi.stubGlobal('scrollTo', vi.fn());
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-09-21T12:00:00.000Z'));
+});
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ if (originalTimezone === undefined) delete process.env.TZ;
+ else process.env.TZ = originalTimezone;
+});
+
+function renderForm(
+ overrides: Partial<Parameters<typeof ReminderForm>[0]> = {}
+) {
+ const onSubmit = vi.fn<(values: ReminderFormValues) => void>();
+ const onCancel = vi.fn();
+ render(() => (
+ <ReminderForm
+ layout="inline"
+ placeholder="What's the reminder?"
+ submitLabel="Set reminder"
+ onCancel={onCancel}
+ onSubmit={onSubmit}
+ {...overrides}
+ />
+ ));
+ return { onSubmit, onCancel };
+}
+
+function chooseRepeat(
+ value: 'once' | 'daily' | 'weekdays' | 'weekly' | 'monthly'
+) {
+ const labels = {
+ once: 'Does not repeat',
+ daily: 'Daily',
+ weekdays: 'Weekdays',
+ weekly: 'Weekly',
+ monthly: 'Monthly',
+ } as const;
+ fireEvent.keyDown(screen.getByRole('button', { name: /^Repeat,/ }), {
+ key: 'Enter',
+ });
+ fireEvent.keyDown(
+ screen.getByRole('menuitemradio', { name: labels[value] }),
+ { key: 'Enter' }
+ );
+ fireEvent.keyDown(screen.getByRole('menu'), { key: 'Escape' });
+}
+
+describe('one-shot scheduling', () => {
+ it('parses natural date language and previews the exact timezone', () => {
+ const { onSubmit } = renderForm({ initialDescription: 'Follow up' });
+
+ fireEvent.input(
+ screen.getByPlaceholderText('Try “tomorrow 9am” or “in 30 minutes”'),
+ { target: { value: 'in 30 minutes' } }
+ );
+
+ fireEvent.click(
+ screen.getByRole('button', {
+ name: /in 30 minutes.*Today, 12:30 PM/,
+ })
+ );
+ const preview = screen.getByText(/Scheduled:/).closest('p');
+ expect(preview?.textContent).toContain('12:30 PM');
+ expect(preview?.textContent).toMatch(/\([A-Z]+\)/);
+ fireEvent.click(screen.getByRole('button', { name: 'Set reminder' }));
+
+ expect(onSubmit).toHaveBeenCalledWith({
+ description: 'Follow up',
+ schedule: {
+ type: 'once',
+ remindAt: '2026-09-21T12:30:00.000Z',
+ },
+ });
+ });
+
+ it('treats natural "in 30m" shorthand as minutes, not months', () => {
+ const { onSubmit } = renderForm({ initialDescription: 'Follow up' });
+
+ fireEvent.input(
+ screen.getByPlaceholderText('Try “tomorrow 9am” or “in 30 minutes”'),
+ { target: { value: 'in 30m' } }
+ );
+ fireEvent.click(
+ screen.getByText('in 30m (30 minutes from now)').closest('button')!
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'Set reminder' }));
+
+ expect(onSubmit.mock.calls[0]?.[0].schedule).toEqual({
+ type: 'once',
+ remindAt: '2026-09-21T12:30:00.000Z',
+ });
+ });
+
+ it('offers quick presets with their actual resolved times', () => {
+ const { onSubmit } = renderForm({ initialDescription: 'Follow up' });
+
+ const inThirty = screen.getByRole('button', {
+ name: /In 30m.*12:30 PM/,
+ });
+ const tomorrow = screen.getByRole('button', {
+ name: /Tomorrow.*Sep 22.*9:00 AM/,
+ });
+ expect(inThirty).not.toBeNull();
+ expect(tomorrow).not.toBeNull();
+ expect(inThirty.textContent).toContain('Mon 12:30 PM');
+ expect(tomorrow.textContent).toContain('Tue 9:00 AM');
+
+ fireEvent.click(inThirty);
+ fireEvent.click(screen.getByRole('button', { name: 'Set reminder' }));
+ expect(onSubmit.mock.calls[0]?.[0].schedule).toEqual({
+ type: 'once',
+ remindAt: '2026-09-21T12:30:00.000Z',
+ });
+ });
+
+ it('carries a typed instant into Custom instead of restoring the default', () => {
+ const { onSubmit } = renderForm({ initialDescription: 'Follow up' });
+
+ fireEvent.input(
+ screen.getByPlaceholderText('Try “tomorrow 9am” or “in 30 minutes”'),
+ { target: { value: 'in 30 minutes' } }
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'Choose date & time' }));
+
+ expect(
+ screen.getByLabelText('Custom reminder date').getAttribute('title')
+ ).toContain('Sep 21, 2026');
+ expect((screen.getByLabelText('Time') as HTMLInputElement).value).toBe(
+ '12:30'
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'Set reminder' }));
+ expect(onSubmit.mock.calls[0]?.[0].schedule).toEqual({
+ type: 'once',
+ remindAt: '2026-09-21T12:30:00.000Z',
+ });
+ });
+
+ it('keeps native validation valid for an exact non-quarter-hour time', () => {
+ const { onSubmit } = renderForm({ initialDescription: 'Exact follow up' });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Choose date & time' }));
+ const time = screen.getByLabelText('Time') as HTMLInputElement;
+ fireEvent.input(time, { target: { value: '14:37:23' } });
+
+ expect(time.step).toBe('1');
+ expect(time.form?.checkValidity()).toBe(true);
+ (
+ screen.getByRole('button', { name: 'Set reminder' }) as HTMLButtonElement
+ ).click();
+
+ expect(onSubmit.mock.calls[0]?.[0].schedule).toEqual({
+ type: 'once',
+ remindAt: '2026-09-22T14:37:23.000Z',
+ });
+ });
+
+ it('keeps preset seconds valid and exact after opening Custom', () => {
+ vi.setSystemTime(new Date('2026-09-21T12:07:23.000Z'));
+ const { onSubmit } = renderForm({ initialDescription: 'Exact follow up' });
+
+ fireEvent.click(screen.getByRole('button', { name: /In 30m.*12:37 PM/ }));
+ fireEvent.click(screen.getByRole('button', { name: 'Choose date & time' }));
+ const time = screen.getByLabelText('Time') as HTMLInputElement;
+
+ expect(time.value).toBe('12:37:23');
+ expect(time.step).toBe('1');
+ expect(time.form?.checkValidity()).toBe(true);
+ (
+ screen.getByRole('button', { name: 'Set reminder' }) as HTMLButtonElement
+ ).click();
+ expect(onSubmit.mock.calls[0]?.[0].schedule).toEqual({
+ type: 'once',
+ remindAt: '2026-09-21T12:37:23.000Z',
+ });
+ });
+
+ it('preserves preset seconds when only the Custom date changes', () => {
+ vi.setSystemTime(new Date('2026-09-21T12:07:23.000Z'));
+ const { onSubmit } = renderForm({ initialDescription: 'Exact follow up' });
+
+ fireEvent.click(screen.getByRole('button', { name: /In 30m.*12:37 PM/ }));
+ fireEvent.click(screen.getByRole('button', { name: 'Choose date & time' }));
+ fireEvent.click(screen.getByLabelText('Custom reminder date'));
+ fireEvent.click(screen.getByRole('gridcell', { name: '22' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Set reminder' }));
+
+ expect(onSubmit.mock.calls[0]?.[0].schedule).toEqual({
+ type: 'once',
+ remindAt: '2026-09-22T12:37:23.000Z',
+ });
+ });
+
+ it('saves a seconds-only edit as a schedule change', () => {
+ const original = {
+ type: 'once' as const,
+ remindAt: '2026-09-22T14:37:23.000Z',
+ };
+ const { onSubmit } = renderForm({
+ initialDescription: 'Exact follow up',
+ initialSchedule: original,
+ initialRemindAt: original.remindAt,
+ submitLabel: 'Save',
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Choose date & time' }));
+ fireEvent.input(screen.getByLabelText('Time'), {
+ target: { value: '14:37:24' },
+ });
+ const save = screen.getByRole('button', { name: 'Save' });
+ expect((save as HTMLButtonElement).disabled).toBe(false);
+ fireEvent.click(save);
+
+ expect(onSubmit).toHaveBeenCalledWith({
+ description: 'Exact follow up',
+ schedule: {
+ type: 'once',
+ remindAt: '2026-09-22T14:37:24.000Z',
+ },
+ });
+ });
+
+ it('invalidates a custom schedule when its time is cleared', () => {
+ const { onSubmit } = renderForm({ initialDescription: 'Follow up' });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Choose date & time' }));
+ const time = screen.getByLabelText('Time') as HTMLInputElement;
+ fireEvent.input(time, { target: { value: '' } });
+
+ expect(time.getAttribute('aria-invalid')).toBe('true');
+ expect(screen.getByText('Choose a time for this reminder.')).not.toBeNull();
+ const submit = screen.getByRole('button', {
+ name: 'Set reminder',
+ }) as HTMLButtonElement;
+ expect(submit.disabled).toBe(true);
+ submit.click();
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+
+ it('preserves an overdue schedule for a description-only edit', () => {
+ const overdue = {
+ type: 'once' as const,
+ remindAt: '2026-09-20T09:00:00.000Z',
+ };
+ const { onSubmit } = renderForm({
+ initialDescription: 'Old title',
+ initialSchedule: overdue,
+ initialRemindAt: overdue.remindAt,
+ submitLabel: 'Save',
+ });
+
+ fireEvent.input(screen.getByLabelText('Reminder description'), {
+ target: { value: 'New title' },
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+
+ expect(onSubmit).toHaveBeenCalledWith({
+ description: 'New title',
+ schedule: overdue,
+ });
+ });
+
+ it('preserves the selected instant when In 30m crosses the fall-back fold', () => {
+ const originalTimezone = process.env.TZ;
+ process.env.TZ = 'America/New_York';
+ try {
+ vi.setSystemTime(new Date('2026-11-01T01:45:00-04:00'));
+ const { onSubmit } = renderForm({ initialDescription: 'Follow up' });
+
+ fireEvent.click(screen.getByRole('button', { name: /In 30m/ }));
+ fireEvent.click(screen.getByRole('button', { name: 'Set reminder' }));
+
+ expect(onSubmit.mock.calls[0]?.[0].schedule).toEqual({
+ type: 'once',
+ remindAt: '2026-11-01T06:15:00.000Z',
+ });
+ } finally {
+ if (originalTimezone === undefined) delete process.env.TZ;
+ else process.env.TZ = originalTimezone;
+ }
+ });
+
+ it('keeps the second fall-back-hour instant on a description-only edit', () => {
+ const originalTimezone = process.env.TZ;
+ process.env.TZ = 'America/New_York';
+ try {
+ vi.setSystemTime(new Date('2026-10-31T12:00:00-04:00'));
+ const secondFold = {
+ type: 'once' as const,
+ remindAt: '2026-11-01T06:30:00.000Z',
+ };
+ const { onSubmit } = renderForm({
+ initialDescription: 'Before the clocks change',
+ initialSchedule: secondFold,
+ initialRemindAt: secondFold.remindAt,
+ submitLabel: 'Save',
+ });
+
+ fireEvent.input(screen.getByLabelText('Reminder description'), {
+ target: { value: 'After the clocks change' },
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+
+ expect(onSubmit).toHaveBeenCalledWith({
+ description: 'After the clocks change',
+ schedule: secondFold,
+ });
+ } finally {
+ if (originalTimezone === undefined) delete process.env.TZ;
+ else process.env.TZ = originalTimezone;
+ }
+ });
+
+ it('keeps the second fall-back-hour instant when confirming the same date', () => {
+ const originalTimezone = process.env.TZ;
+ process.env.TZ = 'America/New_York';
+ try {
+ vi.setSystemTime(new Date('2026-10-31T12:00:00-04:00'));
+ const secondFold = {
+ type: 'once' as const,
+ remindAt: '2026-11-01T06:30:00.000Z',
+ };
+ const { onSubmit } = renderForm({
+ initialDescription: 'Before the clocks change',
+ initialSchedule: secondFold,
+ initialRemindAt: secondFold.remindAt,
+ submitLabel: 'Save',
+ });
+
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Choose date & time' })
+ );
+ fireEvent.click(screen.getByLabelText('Custom reminder date'));
+ fireEvent.click(screen.getByRole('gridcell', { selected: true }));
+ fireEvent.input(screen.getByLabelText('Reminder description'), {
+ target: { value: 'After the clocks change' },
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+
+ expect(onSubmit).toHaveBeenCalledWith({
+ description: 'After the clocks change',
+ schedule: secondFold,
+ });
+ } finally {
+ if (originalTimezone === undefined) delete process.env.TZ;
+ else process.env.TZ = originalTimezone;
+ }
+ });
+
+ it('rejects a custom local time skipped by spring-forward', () => {
+ const originalTimezone = process.env.TZ;
+ process.env.TZ = 'America/New_York';
+ try {
+ vi.setSystemTime(new Date('2026-03-07T12:00:00-05:00'));
+ const { onSubmit } = renderForm({ initialDescription: 'Follow up' });
+
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Choose date & time' })
+ );
+ fireEvent.input(screen.getByLabelText('Time'), {
+ target: { value: '02:30' },
+ });
+
+ expect(
+ screen.getByText(/local time doesn’t exist because the clocks change/)
+ ).not.toBeNull();
+ const submit = screen.getByRole('button', { name: 'Set reminder' });
+ expect((submit as HTMLButtonElement).disabled).toBe(true);
+ fireEvent.click(submit);
+ expect(onSubmit).not.toHaveBeenCalled();
+ } finally {
+ if (originalTimezone === undefined) delete process.env.TZ;
+ else process.env.TZ = originalTimezone;
+ }
+ });
+
+ it('rejects a date-language time skipped by spring-forward', () => {
+ const originalTimezone = process.env.TZ;
+ process.env.TZ = 'America/New_York';
+ try {
+ vi.setSystemTime(new Date('2026-03-07T12:00:00-05:00'));
+ const { onSubmit } = renderForm({ initialDescription: 'Follow up' });
+
+ fireEvent.input(
+ screen.getByPlaceholderText('Try “tomorrow 9am” or “in 30 minutes”'),
+ { target: { value: 'Mar 8 2026 2:30am' } }
+ );
+
+ expect(
+ screen.getByText(/local time doesn’t exist because the clocks change/)
+ ).not.toBeNull();
+ expect(
+ (
+ screen.getByRole('button', {
+ name: 'Set reminder',
+ }) as HTMLButtonElement
+ ).disabled
+ ).toBe(true);
+
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Choose date & time' })
+ );
+ expect(
+ screen.getByLabelText('Custom reminder date').getAttribute('title')
+ ).toContain('Mar 8, 2026');
+ expect((screen.getByLabelText('Time') as HTMLInputElement).value).toBe(
+ '02:30'
+ );
+ expect(
+ screen.getByText(/local time doesn’t exist because the clocks change/)
+ ).not.toBeNull();
+ expect(onSubmit).not.toHaveBeenCalled();
+ } finally {
+ if (originalTimezone === undefined) delete process.env.TZ;
+ else process.env.TZ = originalTimezone;
+ }
+ });
+});
+
+describe('recurrence', () => {
+ it.each([
+ ['Daily', 'daily', '0 0 9 * * 1,2,3,4,5,6,7'],
+ ['Weekdays', 'weekdays', '0 0 9 * * 2,3,4,5,6'],
+ ] as const)(
+ 'round-trips the %s preset through the existing cron model',
+ (_label, value, cron) => {
+ const { onSubmit } = renderForm({ initialDescription: 'Standup' });
+
+ chooseRepeat(value);
+ fireEvent.click(screen.getByRole('button', { name: 'Set reminder' }));
+
+ expect(onSubmit.mock.calls[0]?.[0].schedule).toMatchObject({
+ type: 'recurring',
+ cron,
+ });
+ }
+ );
+
+ it('keeps an unsupported stored cron verbatim on a description-only edit', () => {
+ const custom = {
+ type: 'recurring' as const,
+ cron: '0 */15 9 * * *',
+ timezone: 'America/New_York',
+ };
+ const { onSubmit } = renderForm({
+ initialDescription: 'Custom cadence',
+ initialSchedule: custom,
+ initialRemindAt: '2026-09-22T13:00:00.000Z',
+ submitLabel: 'Save',
+ });
+
+ expect(
+ screen.getByRole('button', { name: 'Repeat, Custom schedule' })
+ ).not.toBeNull();
+ expect(
+ screen.getByText(/will stay unchanged unless you choose a replacement/)
+ ).not.toBeNull();
+ fireEvent.input(screen.getByLabelText('Reminder description'), {
+ target: { value: 'Renamed custom cadence' },
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+
+ expect(onSubmit).toHaveBeenCalledWith({
+ description: 'Renamed custom cadence',
+ schedule: custom,
+ });
+ });
+
+ it('seeds Weekly from the selected monthly occurrence', () => {
+ const { onSubmit } = renderForm({
+ initialDescription: 'Monthly review',
+ initialSchedule: {
+ type: 'recurring',
+ cron: '0 30 14 15 * *',
+ timezone: 'UTC',
+ },
+ initialRemindAt: '2026-10-15T14:30:00.000Z',
+ submitLabel: 'Save',
+ });
+
+ chooseRepeat('weekly');
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+
+ expect(onSubmit.mock.calls[0]?.[0].schedule).toEqual({
+ type: 'recurring',
+ cron: '0 30 14 * * 5',
+ timezone: 'UTC',
+ });
+ });
+
+ it('seeds Monthly from the selected weekly occurrence', () => {
+ const { onSubmit } = renderForm({
+ initialDescription: 'Weekly review',
+ initialSchedule: {
+ type: 'recurring',
+ cron: '0 0 9 * * 2,3,4,5,6',
+ timezone: 'UTC',
+ },
+ initialRemindAt: '2026-09-22T09:00:00.000Z',
+ submitLabel: 'Save',
+ });
+
+ chooseRepeat('monthly');
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+
+ expect(onSubmit.mock.calls[0]?.[0].schedule).toEqual({
+ type: 'recurring',
+ cron: '0 0 9 22 * *',
+ timezone: 'UTC',
+ });
+ });
+
+ it('seeds an explicitly chosen Weekly schedule with one weekday', () => {
+ const { onSubmit } = renderForm({ initialDescription: 'Weekly review' });
+
+ chooseRepeat('daily');
+ chooseRepeat('weekly');
+ fireEvent.click(screen.getByRole('button', { name: 'Set reminder' }));
+
+ expect(onSubmit.mock.calls[0]?.[0].schedule).toEqual({
+ type: 'recurring',
+ cron: '0 0 9 * * 3',
+ timezone: 'UTC',
+ });
+ });
+
+ it('keeps Weekly controls visible through preset-equivalent day sets', () => {
+ const { onSubmit } = renderForm({ initialDescription: 'Six-day review' });
+
+ chooseRepeat('weekly');
+ for (const day of [
+ 'Sunday',
+ 'Monday',
+ 'Tuesday',
+ 'Wednesday',
+ 'Thursday',
+ 'Friday',
+ 'Saturday',
+ ]) {
+ const button = screen.getByRole('button', { name: day });
+ const shouldRepeat = day !== 'Sunday';
+ if ((button.getAttribute('aria-pressed') === 'true') !== shouldRepeat) {
+ fireEvent.click(button);
+ }
+ }
+
+ expect(
+ screen.getByRole('button', { name: 'Repeat, Weekly' })
+ ).not.toBeNull();
+ expect(screen.getByRole('button', { name: 'Saturday' })).not.toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'Set reminder' }));
+ expect(onSubmit.mock.calls[0]?.[0].schedule).toEqual({
+ type: 'recurring',
+ cron: '0 0 9 * * 2,3,4,5,6,7',
+ timezone: 'UTC',
+ });
+ });
+
+ it('seeds an edited Weekly cadence independently from its day shape', () => {
+ const { onSubmit } = renderForm({
+ initialDescription: 'Existing weekly review',
+ initialSchedule: {
+ type: 'recurring',
+ cron: '0 0 9 * * 3',
+ timezone: 'UTC',
+ },
+ initialRemindAt: '2026-09-22T09:00:00.000Z',
+ submitLabel: 'Save',
+ });
+
+ for (const day of [
+ 'Sunday',
+ 'Monday',
+ 'Tuesday',
+ 'Wednesday',
+ 'Thursday',
+ 'Friday',
+ 'Saturday',
+ ]) {
+ const button = screen.getByRole('button', { name: day });
+ const shouldRepeat = day !== 'Sunday';
+ if ((button.getAttribute('aria-pressed') === 'true') !== shouldRepeat) {
+ fireEvent.click(button);
+ }
+ }
+
+ expect(
+ screen.getByRole('button', { name: 'Repeat, Weekly' })
+ ).not.toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+ expect(onSubmit.mock.calls[0]?.[0].schedule).toEqual({
+ type: 'recurring',
+ cron: '0 0 9 * * 2,3,4,5,6,7',
+ timezone: 'UTC',
+ });
+ });
+
+ it('keeps edited time and cadence-specific days while switching repeat shapes', () => {
+ const { onSubmit } = renderForm({
+ initialDescription: 'Monthly review',
+ initialSchedule: {
+ type: 'recurring',
+ cron: '0 30 14 15 * *',
+ timezone: 'UTC',
+ },
+ initialRemindAt: '2026-10-15T14:30:00.000Z',
+ submitLabel: 'Save',
+ });
+
+ fireEvent.input(screen.getByLabelText('Day'), {
+ target: { value: '20' },
+ });
+ fireEvent.input(screen.getByLabelText('At'), {
+ target: { value: '16:45' },
+ });
+
+ chooseRepeat('weekly');
+ expect((screen.getByLabelText('At') as HTMLInputElement).value).toBe(
+ '16:45'
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'Friday' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Thursday' }));
+
+ chooseRepeat('monthly');
+ expect((screen.getByLabelText('Day') as HTMLInputElement).value).toBe('20');
+ expect((screen.getByLabelText('At') as HTMLInputElement).value).toBe(
+ '16:45'
+ );
+
+ chooseRepeat('weekly');
+ expect(
+ screen
+ .getByRole('button', { name: 'Friday' })
+ .getAttribute('aria-pressed')
+ ).toBe('true');
+ expect(
+ screen
+ .getByRole('button', { name: 'Thursday' })
+ .getAttribute('aria-pressed')
+ ).toBe('false');
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+
+ expect(onSubmit.mock.calls[0]?.[0].schedule).toEqual({
+ type: 'recurring',
+ cron: '0 45 16 * * 6',
+ timezone: 'UTC',
+ });
+ });
+});
+
+it('reverts an edited form in place when its host requests that behavior', () => {
+ const { onCancel } = renderForm({
+ initialDescription: 'Follow up',
+ revertOnCancel: true,
+ });
+ fireEvent.input(screen.getByLabelText('Reminder description'), {
+ target: { value: 'Unsaved edit' },
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ expect(onCancel).toHaveBeenCalledWith(true);
+ expect(
+ (screen.getByLabelText('Reminder description') as HTMLInputElement).value
+ ).toBe('Follow up');
+
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ expect(onCancel).toHaveBeenLastCalledWith(false);
+});
diff --git a/apps/web/src/features/reminders/ReminderForm.tsx b/apps/web/src/features/reminders/ReminderForm.tsx
index 4d6d2061be..081064ab72 100644
--- a/apps/web/src/features/reminders/ReminderForm.tsx
+++ b/apps/web/src/features/reminders/ReminderForm.tsx
@@ -1,17 +1,26 @@
import { toast } from '@core/component/Toast/Toast';
import {
type CronParts,
+ DEFAULT_WEEKDAYS,
describeCron,
getDefaultTimezone,
+ isCronRepresentable,
isValidCronParts,
type ScheduleFrequency,
WEEKDAY_OPTIONS,
} from '@core/util/cron';
+import { parseTime, useDateSearch } from '@core/util/dateSearch/useDateSearch';
import { TZDateMini } from '@date-fns/tz';
+import CalendarBlankIcon from '@phosphor/calendar-blank.svg';
+import CaretDownIcon from '@phosphor/caret-down.svg';
+import CheckIcon from '@phosphor/check.svg';
+import RepeatIcon from '@phosphor/repeat.svg';
+import SpinnerIcon from '@phosphor/spinner.svg';
import type { ReminderSchedule } from '@service-storage/generated/schemas/reminderSchedule';
-import { ActionDialogShell, Button, Input, Tabs } from '@ui';
+import { ActionDialogShell, Button, Dropdown, Input } from '@ui';
import {
createEffect,
+ createMemo,
createSignal,
createUniqueId,
For,
@@ -22,12 +31,20 @@ import {
Switch,
} from 'solid-js';
import { Dynamic } from 'solid-js/web';
+import { match } from 'ts-pattern';
import {
+ EventDateField,
+ EventTimeInput,
+} from '../calendar/components/composer/EventDateTimeInputs';
+import {
+ formatReminderInstant,
isRecurring,
onceSchedule,
+ parseLocalReminderDateTime,
REMINDER_DEFAULT_TIME,
REMINDER_DESCRIPTION_MAX_LENGTH,
recurringSchedule,
+ reminderQuickPresets,
repeatPartsFromDate,
repeatPartsFromSchedule,
} from './reminder-schedule';
@@ -69,23 +86,16 @@ export interface ReminderFormProps {
reference?: JSX.Element;
submitLabel: string;
pending?: boolean;
+ error?: string;
/** Dialog hosts provide their heading and use a padded body with a fixed footer. */
header?: JSX.Element;
layout?: 'dialog' | 'inline';
autofocus?: boolean;
- /**
- * Cancel reverts the fields to what they were seeded with rather than only
- * bubbling `onCancel` — for an editor that stays open (the split view), so a
- * cancelled edit undoes itself instead of tearing the panel down.
- */
+ /** Revert unsaved editor fields before notifying the host of cancellation. */
revertOnCancel?: boolean;
- /** Notified when the fields drift from (or return to) their seeded values. */
+ /** Notified when the form drifts from (or returns to) its seeded values. */
onDirtyChange?: (dirty: boolean) => void;
- /**
- * Cancel. `wasDirty` is whether there were unsaved edits when it was clicked:
- * with `revertOnCancel`, those edits have already been reverted, so the host
- * can keep the panel open on a revert and only dismiss on a clean cancel.
- */
+ /** Cancel with whether the form contained unsaved changes. */
onCancel: (wasDirty: boolean) => void;
onSubmit: (values: ReminderFormValues) => void;
}
@@ -97,9 +107,12 @@ function toDateInput(date: Date): string {
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
}
-/** `HH:MM` for a date in local time — the value a `<input type="time">` takes. */
+/** Native local time, retaining seconds when the instant carries them. */
function toTimeInput(date: Date): string {
- return `${pad(date.getHours())}:${pad(date.getMinutes())}`;
+ const minuteTime = `${pad(date.getHours())}:${pad(date.getMinutes())}`;
+ return date.getSeconds() === 0
+ ? minuteTime
+ : `${minuteTime}:${pad(date.getSeconds())}`;
}
/** Whether two picker recurrences say the same thing, ignoring day order. */
@@ -126,6 +139,61 @@ function atDefault(now: Date): Date {
return result;
}
+const ALL_WEEKDAYS = WEEKDAY_OPTIONS.map((option) => option.value);
+
+const REPEAT_PRESETS = [
+ { value: 'once', label: 'Does not repeat' },
+ { value: 'daily', label: 'Daily' },
+ { value: 'weekdays', label: 'Weekdays' },
+ { value: 'weekly', label: 'Weekly' },
+ { value: 'monthly', label: 'Monthly' },
+] as const;
+
+type RepeatPreset = (typeof REPEAT_PRESETS)[number]['value'];
+type RepeatChoice = RepeatPreset | 'custom';
+
+function repeatPresetFromShape(
+ repeat: RepeatKind,
+ parts: CronParts
+): RepeatPreset {
+ if (repeat === 'once') return 'once';
+ if (repeat === 'month') return 'monthly';
+ if (sameDays(parts.daysOfWeek, ALL_WEEKDAYS)) return 'daily';
+ if (sameDays(parts.daysOfWeek, DEFAULT_WEEKDAYS)) return 'weekdays';
+ return 'weekly';
+}
+
+function sameDays(a: string[], b: string[]): boolean {
+ return a.length === b.length && a.every((day) => b.includes(day));
+}
+
+function capitalize(value: string): string {
+ return value.charAt(0).toUpperCase() + value.slice(1);
+}
+
+/** Compact but exact enough to compare the quick choices before selecting one. */
+function formatQuickPreset(date: Date, timezone: string): string {
+ return new Intl.DateTimeFormat(undefined, {
+ timeZone: timezone,
+ weekday: 'short',
+ hour: 'numeric',
+ minute: '2-digit',
+ }).format(date);
+}
+
+/** Human-readable zone without awkward output such as `UTC (UTC)`. */
+function formatTimezoneSummary(zone: string): string {
+ const readable = zone.replace(/_/g, ' ');
+ const abbreviation = shortZone(zone);
+ if (
+ abbreviation === readable ||
+ (abbreviation === 'UTC' && (zone === 'UTC' || zone === 'Etc/UTC'))
+ ) {
+ return abbreviation;
+ }
+ return `${readable} (${abbreviation})`;
+}
+
/** The control values to open with, derived from the reminder (or the defaults). */
function deriveSeed(
description: string | undefined,
@@ -228,10 +296,26 @@ export function ReminderForm(props: ReminderFormProps) {
const isEdit = props.initialSchedule !== undefined;
const localZone = getDefaultTimezone();
+ const openedAt = new Date();
const [description, setDescription] = createSignal(seed.description);
const [repeat, setRepeat] = createSignal<RepeatKind>(seed.repeat);
const [onceDate, setOnceDate] = createSignal(seed.onceDate);
const [onceTime, setOnceTime] = createSignal(seed.onceTime);
+ // Presets and parsed durations carry an instant as well as wall-clock fields.
+ // Keep it so the repeated hour at DST fall-back does not collapse to the
+ // browser's first interpretation of an ambiguous `YYYY-MM-DDTHH:MM` value.
+ // Existing one-shots need the same treatment: their ISO timestamp says
+ // which copy of a repeated wall time they use, while the native fields do not.
+ const initialSelectedOnceInstant = isEdit
+ ? seed.originalSchedule.type === 'once'
+ ? new Date(seed.originalSchedule.remindAt)
+ : props.initialRemindAt
+ ? new Date(props.initialRemindAt)
+ : undefined
+ : undefined;
+ const [selectedOnceInstant, setSelectedOnceInstant] = createSignal<
+ Date | undefined
+ >(initialSelectedOnceInstant);
const [repeatParts, setRepeatParts] = createSignal<CronParts>(seed.parts);
// A recurring cron fires at a wall-clock time in this zone. It defaults to the
// reminder's stored zone (or the viewer's, for a new recurrence) and is
@@ -239,31 +323,123 @@ export function ReminderForm(props: ReminderFormProps) {
const [timezone, setTimezone] = createSignal(
seed.recurringTimezone ?? localZone
);
+ const [whenQuery, setWhenQuery] = createSignal('');
+ const [showCustomTime, setShowCustomTime] = createSignal(false);
+ // Keep an explicit cadence choice separate from its cron shape. Weekly can
+ // intentionally contain Mon–Fri or all seven days while the user is still
+ // editing toward another set (for example Mon–Sat); shape inference alone
+ // would relabel it Weekdays/Daily and hide the weekday controls mid-edit.
+ const [selectedRepeatPreset, setSelectedRepeatPreset] =
+ createSignal<RepeatPreset>(repeatPresetFromShape(seed.repeat, seed.parts));
+ const storedCronIsCustom =
+ isEdit &&
+ props.initialSchedule !== undefined &&
+ isRecurring(props.initialSchedule) &&
+ !isCronRepresentable(props.initialSchedule.cron);
+ const [customScheduleReplaced, setCustomScheduleReplaced] =
+ createSignal(false);
+ // Week and month have different editable day shapes. Remember each shape
+ // once it is intentional so crossing cadences can seed a missing shape from
+ // the selected occurrence without throwing away edits when switching back.
+ const initialSavedWeeklyDays =
+ !storedCronIsCustom &&
+ seed.repeat === 'week' &&
+ !sameDays(seed.parts.daysOfWeek, ALL_WEEKDAYS) &&
+ !sameDays(seed.parts.daysOfWeek, DEFAULT_WEEKDAYS)
+ ? [...seed.parts.daysOfWeek]
+ : undefined;
+ const [savedWeeklyDays, setSavedWeeklyDays] = createSignal<
+ string[] | undefined
+ >(initialSavedWeeklyDays);
+ const initialSavedMonthlyDay =
+ !storedCronIsCustom && seed.repeat === 'month'
+ ? seed.parts.dayOfMonth
+ : undefined;
+ const [savedMonthlyDay, setSavedMonthlyDay] = createSignal<
+ string | undefined
+ >(initialSavedMonthlyDay);
+ const quickPresets = reminderQuickPresets(openedAt);
+
+ const dateOptions = useDateSearch({
+ query: whenQuery,
+ baseDate: openedAt,
+ defaultTime: REMINDER_DEFAULT_TIME,
+ maxItems: 4,
+ });
// What the schedule controls were seeded to, so an untouched edit can be told
- // from a real change without depending on second-level precision the pickers
- // do not carry.
+ // from a real change at the native picker's second-level precision.
const initialRepeat = seed.repeat;
const initialOnceDate = seed.onceDate;
const initialOnceTime = seed.onceTime;
+ const initialOnceInstant =
+ seed.originalSchedule.type === 'once'
+ ? new Date(seed.originalSchedule.remindAt)
+ : new Date(`${initialOnceDate}T${initialOnceTime}`);
const initialParts = seed.parts;
const initialTimezone = seed.recurringTimezone ?? localZone;
const formId = createUniqueId();
+ const descriptionId = createUniqueId();
+ const whenLabelId = createUniqueId();
+ const whenInputId = createUniqueId();
+ const whenOptionsId = createUniqueId();
let titleRef: HTMLInputElement | undefined;
+ let errorRef: HTMLDivElement | undefined;
+ let customControlsRef: HTMLDivElement | undefined;
onMount(() => {
if (props.autofocus) titleRef?.focus();
});
- const onceDateTime = () => new Date(`${onceDate()}T${onceTime()}`);
+ const pickedOnceDateTime = () =>
+ selectedOnceInstant() ?? parseLocalReminderDateTime(onceDate(), onceTime());
+ const typedTime = () => parseTime(whenQuery())?.time;
+ const typedWallTimeIsInvalid = () => {
+ const time = typedTime();
+ const option = dateOptions()[0];
+ return (
+ time !== undefined &&
+ option !== undefined &&
+ (option.date.getHours() !== time.hours ||
+ option.date.getMinutes() !== time.minutes)
+ );
+ };
+ const typedOnceDateTime = () => {
+ if (!whenQuery().trim()) return undefined;
+ if (typedWallTimeIsInvalid()) return undefined;
+ const option = dateOptions()[0];
+ if (!option) return undefined;
+ return new Date(option.date);
+ };
+ const onceDateTime = () => typedOnceDateTime() ?? pickedOnceDateTime();
+ const typedWhenIsValid = () =>
+ !whenQuery().trim() || typedOnceDateTime() !== undefined;
+ const customWallTimeIsInvalid = () =>
+ showCustomTime() &&
+ !whenQuery().trim() &&
+ selectedOnceInstant() === undefined &&
+ onceDate() !== '' &&
+ onceTime() !== '' &&
+ parseLocalReminderDateTime(onceDate(), onceTime()) === undefined;
+ const customTimeIsMissing = () =>
+ showCustomTime() && !whenQuery().trim() && onceTime() === '';
/** Whether the schedule controls still hold exactly what they were seeded to. */
const scheduleUntouched = () => {
+ if (storedCronIsCustom && customScheduleReplaced()) return false;
if (repeat() !== initialRepeat) return false;
- return repeat() === 'once'
- ? onceDate() === initialOnceDate && onceTime() === initialOnceTime
- : samePartsShape(repeatParts(), initialParts) &&
- timezone() === initialTimezone;
+ if (repeat() === 'once') {
+ const date = onceDateTime();
+ return (
+ typedWhenIsValid() &&
+ date !== undefined &&
+ date.getTime() === initialOnceInstant.getTime()
+ );
+ }
+ return (
+ samePartsShape(repeatParts(), initialParts) &&
+ timezone() === initialTimezone
+ );
};
/**
@@ -279,50 +455,100 @@ export function ReminderForm(props: ReminderFormProps) {
return titleChanged || !scheduleUntouched();
};
- // Let the host reflect the unsaved state (e.g. a dot on the split's title).
createEffect(() => props.onDirtyChange?.(isDirty()));
+ createEffect(() => {
+ if (!props.error) return;
+ queueMicrotask(() =>
+ errorRef?.scrollIntoView?.({ block: 'nearest', inline: 'nearest' })
+ );
+ });
const reset = () => {
setDescription(seed.description);
setRepeat(seed.repeat);
setOnceDate(seed.onceDate);
setOnceTime(seed.onceTime);
+ setSelectedOnceInstant(
+ initialSelectedOnceInstant
+ ? new Date(initialSelectedOnceInstant.getTime())
+ : undefined
+ );
setRepeatParts(seed.parts);
setTimezone(initialTimezone);
+ setWhenQuery('');
+ setShowCustomTime(false);
+ setSelectedRepeatPreset(repeatPresetFromShape(seed.repeat, seed.parts));
+ setCustomScheduleReplaced(false);
+ setSavedWeeklyDays(
+ initialSavedWeeklyDays ? [...initialSavedWeeklyDays] : undefined
+ );
+ setSavedMonthlyDay(initialSavedMonthlyDay);
};
const cancel = () => {
const wasDirty = isDirty();
- // Revert the edits in place; the host decides whether to also dismiss.
if (props.revertOnCancel && wasDirty) reset();
props.onCancel(wasDirty);
};
- const setRepeatKind = (kind: RepeatKind) => {
- const wasOnce = repeat() === 'once';
- setRepeat(kind);
- if (kind === 'once') return;
- // Coming from a one-shot, seed the recurrence from the date and time the
- // one-shot fields currently hold rather than the mount-time parts, so
- // switching to Weekly or Monthly lands on that weekday and time. Those
- // fields are the viewer's local wall-clock but the cron is read in
- // `timezone()`, so take the weekday and time of that instant AS SEEN in
- // that zone — otherwise the local time would be reinterpreted in a
- // different zone and the reminder would fire at another moment. Between two
- // recurring kinds, keep the parts the user set and only flip frequency.
- if (wasOnce) {
- const from = onceDateTime();
- if (!Number.isNaN(from.getTime())) {
- const inZone = TZDateMini.tz(timezone(), from.getTime());
- setRepeatParts(repeatPartsFromDate(inZone, kind));
- return;
- }
+ const seedRepeatParts = (kind: ScheduleFrequency) => {
+ const from = onceDateTime();
+ if (from) {
+ const inZone = TZDateMini.tz(timezone(), from.getTime());
+ return repeatPartsFromDate(inZone, kind);
+ }
+ return { ...repeatParts(), frequency: kind };
+ };
+
+ const selectRepeat = (option: RepeatPreset) => {
+ setSelectedRepeatPreset(option);
+ if (option === 'once') {
+ setCustomScheduleReplaced(true);
+ setRepeat('once');
+ return;
+ }
+
+ const frequency: ScheduleFrequency =
+ option === 'monthly' ? 'month' : 'week';
+ const seeded = seedRepeatParts(frequency);
+ const canPreserveEditedTime =
+ repeat() !== 'once' && (!storedCronIsCustom || customScheduleReplaced());
+ const parts: CronParts = {
+ ...repeatParts(),
+ frequency,
+ time: canPreserveEditedTime ? repeatParts().time : seeded.time,
+ };
+ if (option === 'weekly') {
+ const days = savedWeeklyDays() ?? seeded.daysOfWeek;
+ parts.daysOfWeek = [...days];
+ setSavedWeeklyDays([...days]);
+ }
+ if (option === 'monthly') {
+ const day = savedMonthlyDay() ?? seeded.dayOfMonth;
+ parts.dayOfMonth = day;
+ setSavedMonthlyDay(day);
}
- setRepeatParts((parts) => ({ ...parts, frequency: kind }));
+ setRepeat(frequency);
+ setRepeatParts({
+ ...parts,
+ ...(option === 'daily' ? { daysOfWeek: [...ALL_WEEKDAYS] } : {}),
+ ...(option === 'weekdays' ? { daysOfWeek: [...DEFAULT_WEEKDAYS] } : {}),
+ });
+ setCustomScheduleReplaced(true);
+ };
+
+ const selectRepeatValue = (value: string) => {
+ const option = REPEAT_PRESETS.find((preset) => preset.value === value);
+ if (option) selectRepeat(option.value);
};
- const updateParts = (patch: Partial<CronParts>) =>
+ const updateParts = (patch: Partial<CronParts>) => {
+ setCustomScheduleReplaced(true);
+ if (patch.dayOfMonth !== undefined && repeat() === 'month') {
+ setSavedMonthlyDay(patch.dayOfMonth);
+ }
setRepeatParts((parts) => ({ ...parts, ...patch }));
+ };
const toggleDay = (value: string) => {
const days = repeatParts().daysOfWeek;
@@ -331,9 +557,78 @@ export function ReminderForm(props: ReminderFormProps) {
const next = days.includes(value)
? days.filter((day) => day !== value)
: [...days, value];
- if (next.length > 0) updateParts({ daysOfWeek: next });
+ if (next.length > 0) {
+ setSavedWeeklyDays([...next]);
+ updateParts({ daysOfWeek: next });
+ }
+ };
+
+ const selectOnceDate = (date: Date) => {
+ setWhenQuery('');
+ setSelectedOnceInstant(new Date(date));
+ setOnceDate(toDateInput(date));
+ setOnceTime(toTimeInput(date));
+ };
+
+ const toggleCustomTime = () => {
+ const opening = !showCustomTime();
+ if (opening && whenQuery().trim()) {
+ const option = dateOptions()[0];
+ const intendedTime = typedTime();
+ if (typedWallTimeIsInvalid() && option && intendedTime) {
+ // Carry the requested wall time into Custom so its existing DST-gap
+ // validation can explain the problem instead of silently discarding it.
+ setSelectedOnceInstant(undefined);
+ setOnceDate(toDateInput(option.date));
+ setOnceTime(`${pad(intendedTime.hours)}:${pad(intendedTime.minutes)}`);
+ setWhenQuery('');
+ } else {
+ const typed = typedOnceDateTime();
+ if (typed) selectOnceDate(typed);
+ else setWhenQuery('');
+ }
+ }
+ setShowCustomTime(opening);
+ if (opening) {
+ queueMicrotask(() =>
+ customControlsRef?.scrollIntoView?.({
+ block: 'nearest',
+ inline: 'nearest',
+ behavior: 'smooth',
+ })
+ );
+ }
+ };
+
+ const repeatChoice = (): RepeatChoice => {
+ if (storedCronIsCustom && !customScheduleReplaced()) return 'custom';
+ return selectedRepeatPreset();
};
+ const repeatLabel = () =>
+ match(repeatChoice())
+ .with('once', () => 'Does not repeat')
+ .with('custom', () => 'Custom schedule')
+ .with('daily', () => 'Daily')
+ .with('weekdays', () => 'Weekdays')
+ .with('weekly', () => 'Weekly')
+ .with('monthly', () => 'Monthly')
+ .exhaustive();
+
+ const schedulePreview = createMemo(() => {
+ if (repeat() === 'once') {
+ if (!typedWhenIsValid()) return;
+ const date = onceDateTime();
+ return date
+ ? formatReminderInstant(date, localZone, openedAt)
+ : undefined;
+ }
+ if (storedCronIsCustom && !customScheduleReplaced()) {
+ return `Custom repeating schedule · ${formatTimezoneSummary(timezone())}`;
+ }
+ return `${capitalize(describeCron(repeatParts()))} · ${formatTimezoneSummary(timezone())}`;
+ });
+
const submit = () => {
// Editing without touching the schedule keeps the stored one verbatim, so
// the caller's diff omits it — which is what lets an overdue reminder be
@@ -349,7 +644,7 @@ export function ReminderForm(props: ReminderFormProps) {
if (repeat() === 'once') {
const date = onceDateTime();
- if (Number.isNaN(date.getTime())) return;
+ if (!date) return;
// The controls can sit open long enough for a picked time to slip into the
// past; re-check rather than let the API reject it with an opaque failure.
if (date.getTime() <= Date.now()) {
@@ -384,7 +679,7 @@ export function ReminderForm(props: ReminderFormProps) {
if (props.descriptionRequired && !description().trim()) return false;
if (props.pending) return false;
return repeat() === 'once'
- ? !Number.isNaN(onceDateTime().getTime())
+ ? typedWhenIsValid() && onceDateTime() !== undefined
: isValidCronParts(repeatParts());
};
@@ -406,142 +701,414 @@ export function ReminderForm(props: ReminderFormProps) {
<form
id={formId}
- class="flex flex-col gap-4"
+ class="flex flex-col gap-3"
+ aria-busy={props.pending}
+ inert={props.pending}
onSubmit={(event) => {
event.preventDefault();
submit();
}}
>
- <fieldset class="flex min-w-0 flex-col gap-4">
- <Input
- ref={titleRef}
- type="text"
- value={description()}
- onInput={(event) => setDescription(event.currentTarget.value)}
- placeholder={props.placeholder}
- aria-label="Reminder description"
- // Counts UTF-16 code units where the service counts characters, so this
- // only ever stops short of the real limit, never past it. The
- // description resolvers apply the exact cap.
- maxLength={REMINDER_DESCRIPTION_MAX_LENGTH}
- size="lg"
- />
-
+ <fieldset
+ class="flex min-w-0 flex-col gap-3"
+ disabled={props.pending}
+ >
<div class="flex flex-col gap-2">
- <span class="text-xs font-medium text-ink-muted">Repeat</span>
- <Tabs
- aria-label="Repeat"
- labelClass="whitespace-nowrap px-2"
- value={repeat()}
- fullWidth
- onChange={(value) => {
- if (value === 'once' || value === 'week' || value === 'month')
- setRepeatKind(value);
- }}
- list={[
- { value: 'once', label: 'Does not repeat' },
- { value: 'week', label: 'Weekly' },
- { value: 'month', label: 'Monthly' },
- ]}
+ <label
+ for={descriptionId}
+ class="text-xs font-medium text-ink-muted"
+ >
+ Reminder
+ </label>
+ <Input
+ id={descriptionId}
+ ref={titleRef}
+ type="text"
+ value={description()}
+ onInput={(event) => setDescription(event.currentTarget.value)}
+ placeholder={props.placeholder}
+ aria-label="Reminder description"
+ // Counts UTF-16 code units where the service counts characters, so this
+ // only ever stops short of the real limit, never past it. The
+ // description resolvers apply the exact cap.
+ maxLength={REMINDER_DESCRIPTION_MAX_LENGTH}
+ size="lg"
/>
</div>
- <Switch>
- <Match when={repeat() === 'once'}>
- <div class="flex flex-col gap-2">
- <div class="flex items-center gap-2">
- <Input
- type="date"
- aria-label="Date"
- value={onceDate()}
- onInput={(event) =>
- setOnceDate(event.currentTarget.value)
+ <Show when={repeat() === 'once'}>
+ <section
+ class="flex flex-col gap-2"
+ aria-labelledby={whenLabelId}
+ >
+ <label
+ id={whenLabelId}
+ for={whenInputId}
+ class="text-xs font-medium text-ink-muted"
+ >
+ When
+ </label>
+ <Input
+ id={whenInputId}
+ type="text"
+ value={whenQuery()}
+ onInput={(event) => setWhenQuery(event.currentTarget.value)}
+ placeholder="Try “tomorrow 9am” or “in 30 minutes”"
+ autocomplete="off"
+ aria-controls={whenOptionsId}
+ aria-expanded={whenQuery().trim().length > 0}
+ aria-invalid={!typedWhenIsValid()}
+ size="lg"
+ />
+ <Show when={whenQuery().trim()}>
+ <div
+ id={whenOptionsId}
+ class="flex max-h-40 flex-col gap-1 overflow-y-auto rounded-lg border border-edge-muted bg-panel p-1"
+ aria-label="Matching reminder times"
+ >
+ <Show
+ when={
+ dateOptions().length > 0 && !typedWallTimeIsInvalid()
}
- class="min-w-0 flex-1 text-sm"
- />
- <Input
- type="time"
- aria-label="Time"
- value={onceTime()}
- onInput={(event) =>
- setOnceTime(event.currentTarget.value)
+ fallback={
+ <Show
+ when={typedWallTimeIsInvalid()}
+ fallback={
+ <span class="px-2 py-1.5 text-xs text-failure-ink">
+ No date found. Try “tomorrow 9am” or use Custom.
+ </span>
+ }
+ >
+ <span
+ class="px-2 py-1.5 text-xs text-failure-ink"
+ role="alert"
+ >
+ That local time doesn’t exist because the clocks
+ change. Choose a time before or after the gap.
+ </span>
+ </Show>
}
- class="min-w-0 flex-1 text-sm"
- />
+ >
+ <For each={dateOptions()}>
+ {(option) => (
+ <Button
+ type="button"
+ variant="ghost"
+ class="min-h-10 justify-between gap-3 text-left"
+ onClick={() => selectOnceDate(option.date)}
+ >
+ <span class="min-w-0 truncate">
+ {option.displayText}
+ </span>
+ <span class="shrink-0 text-xs text-ink-muted">
+ {option.secondaryText}
+ </span>
+ </Button>
+ )}
+ </For>
+ </Show>
</div>
- <span class="text-xs text-ink-muted">
- {localZone.replace(/_/g, ' ')} ({shortZone(localZone)})
- </span>
- </div>
- </Match>
- <Match when={repeat() === 'week'}>
- <div class="flex flex-col gap-3">
- <div class="flex gap-1">
- <For each={WEEKDAY_OPTIONS}>
- {(day) => (
+ </Show>
+
+ <div
+ class="grid min-w-0 grid-cols-2 gap-2"
+ aria-label="Quick reminder times"
+ >
+ <Show when={!showCustomTime()}>
+ <For each={quickPresets}>
+ {(preset) => (
<Button
type="button"
- size="sm"
- class="min-w-0 flex-1 px-1"
variant={
- repeatParts().daysOfWeek.includes(day.value)
+ onceDateTime()?.getTime() === preset.date.getTime()
? 'accent'
: 'outline'
}
- aria-pressed={repeatParts().daysOfWeek.includes(
- day.value
- )}
- onClick={() => toggleDay(day.value)}
+ fullWidth
+ class="h-auto min-h-12 min-w-0 flex-col items-start gap-0.5 rounded-[10px] px-3 py-2 text-left whitespace-normal"
+ data-reminder-quick-preset={preset.id}
+ aria-label={`${preset.label}, ${formatReminderInstant(preset.date, localZone, openedAt)}`}
+ aria-pressed={
+ onceDateTime()?.getTime() === preset.date.getTime()
+ }
+ onClick={() => {
+ setShowCustomTime(false);
+ selectOnceDate(preset.date);
+ }}
>
- {day.label}
+ <span class="max-w-full truncate text-xs font-medium text-ink">
+ {preset.label}
+ </span>
+ <span class="max-w-full truncate text-[11px] font-normal text-ink-muted">
+ {formatQuickPreset(preset.date, localZone)}
+ </span>
</Button>
)}
</For>
- </div>
- <TimeField
- value={repeatParts().time}
- onChange={(time) => updateParts({ time })}
- />
- </div>
- </Match>
- <Match when={repeat() === 'month'}>
- <div class="flex items-center gap-3">
- <label class="flex items-center gap-2 text-sm text-ink-muted">
- Day
- <Input
- type="number"
- min="1"
- max="31"
- value={repeatParts().dayOfMonth}
- onInput={(event) =>
- updateParts({ dayOfMonth: event.currentTarget.value })
- }
- class="w-16 text-sm"
- />
- </label>
- <TimeField
- value={repeatParts().time}
- onChange={(time) => updateParts({ time })}
- />
+ </Show>
+ <Button
+ type="button"
+ size="sm"
+ variant={showCustomTime() ? 'accent' : 'outline'}
+ fullWidth
+ class="col-span-2 min-w-0 justify-start rounded-[10px] px-3"
+ aria-pressed={showCustomTime()}
+ onClick={toggleCustomTime}
+ >
+ <CalendarBlankIcon class="size-4" />
+ Choose date &amp; time
+ </Button>
</div>
- </Match>
- </Switch>
- <Show when={repeat() !== 'once'}>
- <div class="flex flex-col gap-2">
- <label class="flex items-center gap-2 text-xs text-ink-muted">
+ <Show when={showCustomTime()}>
+ <div
+ ref={customControlsRef}
+ class="rounded-[10px] border border-edge-muted bg-input/50 p-3"
+ >
+ <div class="grid min-w-0 gap-2 min-[360px]:grid-cols-2">
+ <div class="flex min-w-0 flex-col gap-1">
+ <span class="text-xxs font-medium text-ink-muted">
+ Date
+ </span>
+ <EventDateField
+ label="Custom reminder"
+ value={onceDate()}
+ invalid={customWallTimeIsInvalid()}
+ disabled={props.pending}
+ portalScope="local"
+ appearance="bare"
+ class="h-9 w-full rounded-md border border-edge-muted bg-control px-2 hover:bg-hover focus-visible:border-accent"
+ onChange={(value) => {
+ setWhenQuery('');
+ const selected = selectedOnceInstant();
+ if (!selected || toDateInput(selected) !== value) {
+ setSelectedOnceInstant(undefined);
+ }
+ setOnceDate(value);
+ }}
+ />
+ </div>
+ <div class="flex min-w-0 flex-col">
+ <EventTimeInput
+ id={`${formId}-custom-time`}
+ label="Time"
+ value={onceTime()}
+ disabled={props.pending}
+ invalid={
+ customTimeIsMissing() || customWallTimeIsInvalid()
+ }
+ step={1}
+ onClear={() => {
+ setWhenQuery('');
+ setSelectedOnceInstant(undefined);
+ setOnceTime('');
+ }}
+ onChange={(option) => {
+ setWhenQuery('');
+ setSelectedOnceInstant(undefined);
+ setOnceTime(option.value);
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ <Show
+ when={customTimeIsMissing()}
+ fallback={
+ <Show when={customWallTimeIsInvalid()}>
+ <p class="text-xs text-failure-ink" role="alert">
+ That local time doesn’t exist because the clocks
+ change. Choose a time before or after the gap.
+ </p>
+ </Show>
+ }
+ >
+ <p class="text-xs text-failure-ink" role="alert">
+ Choose a time for this reminder.
+ </p>
+ </Show>
+ </Show>
+ </section>
+ </Show>
+
+ <Show when={!whenQuery().trim() ? schedulePreview() : undefined}>
+ {(preview) => (
+ <p
+ class="flex min-w-0 items-start gap-2 rounded-lg border border-edge-muted bg-hover px-3 py-2 text-xs text-ink-muted"
+ aria-live="polite"
+ >
+ <CalendarBlankIcon class="mt-0.5 size-3.5 shrink-0 text-ink-extra-muted" />
+ <span class="min-w-0">
+ <span class="font-medium text-ink">Scheduled:</span>{' '}
+ {preview()}
+ </span>
+ </p>
+ )}
+ </Show>
+
+ <Dropdown placement="bottom-start">
+ <Dropdown.Trigger
+ fullWidth
+ aria-label={`Repeat, ${repeatLabel()}`}
+ class="min-h-10 min-w-0 justify-start gap-2 rounded-[10px] px-3"
+ >
+ <RepeatIcon class="size-4 shrink-0 text-ink-extra-muted" />
+ <span class="shrink-0 font-medium text-ink">Repeat</span>
+ <span class="min-w-0 flex-1 truncate text-left font-normal text-ink-muted">
+ {repeatLabel()}
+ </span>
+ <CaretDownIcon class="size-3.5 shrink-0 text-ink-muted" />
+ </Dropdown.Trigger>
+ <Dropdown.Content
+ portalScope="local"
+ class="w-56 max-w-[calc(100vw-1rem)]"
+ >
+ <Dropdown.Group>
+ <Dropdown.RadioGroup
+ value={repeatChoice()}
+ onChange={selectRepeatValue}
+ >
+ <Show
+ when={storedCronIsCustom && !customScheduleReplaced()}
+ >
+ <Dropdown.RadioItem
+ value="custom"
+ disabled
+ class="justify-between"
+ >
+ Custom schedule
+ <Dropdown.ItemIndicator>
+ <CheckIcon class="size-3.5 text-accent" />
+ </Dropdown.ItemIndicator>
+ </Dropdown.RadioItem>
+ </Show>
+ <For each={REPEAT_PRESETS}>
+ {(option) => (
+ <Dropdown.RadioItem
+ value={option.value}
+ closeOnSelect
+ class="justify-between"
+ >
+ {option.label}
+ <Dropdown.ItemIndicator>
+ <CheckIcon class="size-3.5 text-accent" />
+ </Dropdown.ItemIndicator>
+ </Dropdown.RadioItem>
+ )}
+ </For>
+ </Dropdown.RadioGroup>
+ </Dropdown.Group>
+ </Dropdown.Content>
+ </Dropdown>
+
+ <Show when={storedCronIsCustom && !customScheduleReplaced()}>
+ <p class="rounded-lg bg-alert/10 px-3 py-2 text-xs text-alert-ink">
+ This reminder uses a custom repeat schedule. It will stay
+ unchanged unless you choose a replacement.
+ </p>
+ </Show>
+
+ <Show
+ when={
+ repeat() !== 'once' &&
+ (!storedCronIsCustom || customScheduleReplaced())
+ }
+ >
+ <div class="flex min-w-0 flex-col gap-3 rounded-[10px] border border-edge-muted bg-input/40 p-3">
+ <Switch>
+ <Match when={repeat() === 'week'}>
+ <div class="flex flex-col gap-3">
+ <Show when={repeatChoice() === 'weekly'}>
+ <div class="flex flex-col gap-1.5">
+ <span class="text-xs font-medium text-ink-muted">
+ Repeat on
+ </span>
+ <div
+ class="flex min-w-0 flex-wrap items-center gap-1.5"
+ aria-label="Repeat on"
+ >
+ <For each={WEEKDAY_OPTIONS}>
+ {(day) => (
+ <Button
+ type="button"
+ size="icon-sm"
+ class="rounded-full text-xxs"
+ variant={
+ repeatParts().daysOfWeek.includes(day.value)
+ ? 'accent'
+ : 'ghost'
+ }
+ aria-label={day.fullLabel}
+ aria-pressed={repeatParts().daysOfWeek.includes(
+ day.value
+ )}
+ onClick={() => toggleDay(day.value)}
+ >
+ {day.label[0]}
+ </Button>
+ )}
+ </For>
+ </div>
+ </div>
+ </Show>
+ <TimeField
+ value={repeatParts().time}
+ disabled={props.pending}
+ onChange={(time) => updateParts({ time })}
+ />
+ </div>
+ </Match>
+ <Match when={repeat() === 'month'}>
+ <div class="grid min-w-0 gap-3 min-[360px]:grid-cols-2">
+ <label class="flex items-center gap-2 text-sm text-ink-muted">
+ Day
+ <Input
+ type="number"
+ min="1"
+ max="31"
+ value={repeatParts().dayOfMonth}
+ onInput={(event) =>
+ updateParts({
+ dayOfMonth: event.currentTarget.value,
+ })
+ }
+ class="w-20 text-sm"
+ />
+ </label>
+ <TimeField
+ value={repeatParts().time}
+ disabled={props.pending}
+ onChange={(time) => updateParts({ time })}
+ />
+ </div>
+ </Match>
+ </Switch>
+
+ <label class="flex min-w-0 flex-col gap-1.5 text-xs text-ink-muted">
<span class="font-medium">Timezone</span>
<TimezoneSelect
value={timezone()}
- onChange={setTimezone}
+ onChange={(value) => {
+ setCustomScheduleReplaced(true);
+ setTimezone(value);
+ }}
options={TIMEZONE_OPTIONS}
/>
</label>
- <span class="truncate text-xs text-ink-muted">
- {describeCron(repeatParts())} · {shortZone(timezone())}
- </span>
</div>
</Show>
+
+ <Show when={props.error}>
+ {(error) => (
+ <div
+ ref={errorRef}
+ class="rounded-lg border border-failure/40 bg-failure-bg px-3 py-2 text-xs text-failure-ink"
+ role="alert"
+ >
+ {error()}
+ </div>
+ )}
+ </Show>
</fieldset>
</form>
</Dynamic>
@@ -559,7 +1126,13 @@ export function ReminderForm(props: ReminderFormProps) {
Unsaved changes
</span>
</Show>
- <Button type="button" variant="ghost" class="ml-auto" onClick={cancel}>
+ <Button
+ type="button"
+ variant="ghost"
+ class="ml-auto"
+ disabled={props.pending}
+ onClick={cancel}
+ >
Cancel
</Button>
<Button
@@ -568,7 +1141,10 @@ export function ReminderForm(props: ReminderFormProps) {
variant="strong"
disabled={!canSubmit() || (isEdit && !isDirty())}
>
- {props.submitLabel}
+ <Show when={props.pending} fallback={props.submitLabel}>
+ <SpinnerIcon class="size-4 animate-spin" />
+ <span class="sr-only">Saving reminder</span>
+ </Show>
</Button>
</Dynamic>
</div>
@@ -578,17 +1154,27 @@ export function ReminderForm(props: ReminderFormProps) {
/** A time-of-day field for the recurring schedule. `At HH:MM`. */
function TimeField(props: {
value: string;
+ disabled?: boolean;
onChange: (value: string) => void;
}) {
+ const id = createUniqueId();
return (
- <label class="flex items-center gap-2 text-sm text-ink-muted">
- At
- <Input
- type="time"
+ <div class="flex min-w-0 flex-col">
+ <EventTimeInput
+ id={`reminder-repeat-time-${id}`}
+ label="At"
value={props.value}
- onInput={(event) => props.onChange(event.currentTarget.value)}
- class="min-w-0 flex-1 text-sm"
+ disabled={props.disabled}
+ invalid={props.value === ''}
+ step={60}
+ onClear={() => props.onChange('')}
+ onChange={(option) => props.onChange(option.value)}
/>
- </label>
+ <Show when={props.value === ''}>
+ <span class="mt-1 text-xs text-failure-ink" role="alert">
+ Choose a time.
+ </span>
+ </Show>
+ </div>
);
}
diff --git a/apps/web/src/features/reminders/reminder-composer.test.ts b/apps/web/src/features/reminders/reminder-composer.test.ts
index 87fb39be01..31d4da3c32 100644
--- a/apps/web/src/features/reminders/reminder-composer.test.ts
+++ b/apps/web/src/features/reminders/reminder-composer.test.ts
@@ -99,8 +99,8 @@ describe('reminder composer created handler', () => {
closeReminderComposer();
});
- // The composer closes before the create request is awaited, so the follow-up
- // has to be taken out of here first rather than read after the fact.
+ // The modal takes this only after the create request succeeds, immediately
+ // before closing clears the composer state.
it('hands the created handler over once', () => {
const onCreated = vi.fn();
openReminderComposer(doc('doc-1', 'Q3 Contract'), { onCreated });
diff --git a/apps/web/src/features/reminders/reminder-composer.ts b/apps/web/src/features/reminders/reminder-composer.ts
index fee4b35768..1d67d47a85 100644
--- a/apps/web/src/features/reminders/reminder-composer.ts
+++ b/apps/web/src/features/reminders/reminder-composer.ts
@@ -29,10 +29,9 @@ export type ReminderCreatedHandler = () => void | Promise<void>;
let createdHandler: ReminderCreatedHandler | undefined;
/**
- * Hand the pending handler to the caller and forget it.
- *
- * Taken rather than read because the composer closes — and so clears its
- * target — before the create request is awaited.
+ * Hand the pending handler to the caller and forget it after create succeeds.
+ * A rejected create leaves it here so the preserved draft can be retried and
+ * still perform the invoking surface's follow-up exactly once.
*/
export function takeReminderCreatedHandler():
| ReminderCreatedHandler
diff --git a/apps/web/src/features/reminders/reminder-schedule.test.ts b/apps/web/src/features/reminders/reminder-schedule.test.ts
index dbb5490555..8ddfd2bd95 100644
--- a/apps/web/src/features/reminders/reminder-schedule.test.ts
+++ b/apps/web/src/features/reminders/reminder-schedule.test.ts
@@ -2,16 +2,20 @@ import type { EntityData } from '@entity';
import { describe, expect, it } from 'vitest';
import {
+ describeReminderConfirmation,
describeReminderSchedule,
describeReminderWhen,
+ formatReminderInstant,
isRecurring,
onceSchedule,
+ parseLocalReminderDateTime,
REMINDER_DEFAULT_TIME,
REMINDER_DESCRIPTION_MAX_LENGTH,
recurringSchedule,
reminderDescriptionFor,
reminderDescriptionForReference,
reminderEditPatch,
+ reminderQuickPresets,
repeatPartsFromDate,
repeatPartsFromSchedule,
resolveEditedDescription,
@@ -20,6 +24,116 @@ import {
sameSchedule,
} from './reminder-schedule';
+describe('reminderQuickPresets', () => {
+ it('shows actual common times and hides Later today after 5pm', () => {
+ const morning = reminderQuickPresets(new Date(2026, 8, 21, 10, 12, 45));
+
+ expect(morning.map((preset) => preset.id)).toEqual([
+ 'in-30-minutes',
+ 'later-today',
+ 'tomorrow-morning',
+ 'next-week',
+ ]);
+ expect(morning[0]?.date).toEqual(new Date(2026, 8, 21, 10, 42, 45));
+ expect(morning[1]?.date).toEqual(new Date(2026, 8, 21, 17));
+ expect(morning[2]?.date).toEqual(new Date(2026, 8, 22, 9));
+ expect(morning[3]?.date).toEqual(new Date(2026, 8, 28, 9));
+
+ expect(
+ reminderQuickPresets(new Date(2026, 8, 21, 17, 1)).map(
+ (preset) => preset.id
+ )
+ ).not.toContain('later-today');
+ });
+
+ it('makes Next week the following Monday when opened on Monday', () => {
+ const presets = reminderQuickPresets(new Date(2026, 8, 21, 10));
+ expect(presets.find((preset) => preset.id === 'next-week')?.date).toEqual(
+ new Date(2026, 8, 28, 9)
+ );
+ });
+
+ it('adds 30 elapsed minutes across the daylight-saving fall-back hour', () => {
+ const beforeFallback = new Date('2026-11-01T01:45:00-04:00');
+ const inThirty = reminderQuickPresets(beforeFallback)[0]?.date;
+ if (!inThirty) throw new Error('Expected In 30m preset');
+
+ expect(inThirty.getTime() - beforeFallback.getTime()).toBe(30 * 60 * 1000);
+ expect(
+ new Intl.DateTimeFormat('en-US', {
+ timeZone: 'America/New_York',
+ hour: 'numeric',
+ minute: '2-digit',
+ timeZoneName: 'short',
+ }).format(inThirty)
+ ).toBe('1:15 AM EST');
+ });
+});
+
+describe('parseLocalReminderDateTime', () => {
+ it('rejects a wall time skipped by daylight-saving spring-forward', () => {
+ const originalTimezone = process.env.TZ;
+ process.env.TZ = 'America/New_York';
+ try {
+ expect(parseLocalReminderDateTime('2026-03-08', '02:30')).toBeUndefined();
+ expect(
+ parseLocalReminderDateTime('2026-03-08', '03:30')?.toISOString()
+ ).toBe('2026-03-08T07:30:00.000Z');
+ } finally {
+ if (originalTimezone === undefined) delete process.env.TZ;
+ else process.env.TZ = originalTimezone;
+ }
+ });
+
+ it('accepts native time values with seconds and fractional seconds', () => {
+ const originalTimezone = process.env.TZ;
+ process.env.TZ = 'UTC';
+ try {
+ expect(
+ parseLocalReminderDateTime('2026-09-22', '09:15:30.125')?.toISOString()
+ ).toBe('2026-09-22T09:15:30.125Z');
+ } finally {
+ if (originalTimezone === undefined) delete process.env.TZ;
+ else process.env.TZ = originalTimezone;
+ }
+ });
+});
+
+describe('formatReminderInstant', () => {
+ it('includes the relative day, exact date, time, and timezone', () => {
+ const described = formatReminderInstant(
+ new Date('2026-09-22T09:00:00.000Z'),
+ 'UTC',
+ new Date('2026-09-21T12:00:00.000Z')
+ );
+
+ expect(described).toContain('Tomorrow');
+ expect(described).toContain('Sep 22');
+ expect(described).toMatch(/9:00\sAM/);
+ expect(described).toContain('(UTC)');
+ });
+
+ it('describes persisted schedules for success feedback', () => {
+ expect(
+ describeReminderConfirmation({
+ type: 'recurring',
+ cron: '0 0 9 * * 2-6',
+ timezone: 'America/New_York',
+ })
+ ).toContain('Weekdays at 9:00 AM');
+ });
+
+ it('does not invent a cadence for an unsupported custom cron', () => {
+ expect(
+ describeReminderConfirmation({
+ type: 'recurring',
+ cron: '0 */15 9 * * *',
+ timezone: 'America/New_York',
+ })
+ ).toBe('Custom repeating schedule (America/New_York)');
+ });
+});
+
describe('onceSchedule', () => {
it('builds a one-shot schedule at the given instant', () => {
const date = new Date('2026-07-30T13:00:00.000Z');
diff --git a/apps/web/src/features/reminders/reminder-schedule.ts b/apps/web/src/features/reminders/reminder-schedule.ts
index fa57a671d5..b483ea938d 100644
--- a/apps/web/src/features/reminders/reminder-schedule.ts
+++ b/apps/web/src/features/reminders/reminder-schedule.ts
@@ -4,6 +4,7 @@ import {
type CronParts,
describeCron,
getDefaultTimezone,
+ isCronRepresentable,
normalizeCron,
parseCron,
type ScheduleFrequency,
@@ -24,6 +25,174 @@ export const REMINDER_DEFAULT_TIME = { hours: 9, minutes: 0 } as const;
/** Longest description the API accepts, mirroring the service's own limit. */
export const REMINDER_DESCRIPTION_MAX_LENGTH = 2000;
+/**
+ * Parse native date/time control values without accepting DST normalization.
+ *
+ * `new Date('2026-03-08T02:30')` in New York silently becomes 03:30 because
+ * 02:30 never occurs on the spring-forward day. A reminder must not save at a
+ * different time than the controls display, so round-trip every component.
+ */
+export function parseLocalReminderDateTime(
+ dateValue: string,
+ timeValue: string
+): Date | undefined {
+ const dateMatch = dateValue.match(/^(\d{4})-(\d{2})-(\d{2})$/);
+ // Native time values are minute-only with the form's default step, but the
+ // HTML serialization also permits seconds and fractional seconds. Accept the
+ // full shape so a valid value is never mislabeled as a DST gap.
+ const timeMatch = timeValue.match(
+ /^(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?$/
+ );
+ if (!dateMatch || !timeMatch) return undefined;
+
+ const [, year, month, day] = dateMatch.map(Number);
+ const hour = Number(timeMatch[1]);
+ const minute = Number(timeMatch[2]);
+ const second = Number(timeMatch[3] ?? 0);
+ const millisecond = Number((timeMatch[4] ?? '').padEnd(3, '0'));
+ const parsed = new Date(
+ year,
+ month - 1,
+ day,
+ hour,
+ minute,
+ second,
+ millisecond
+ );
+ if (
+ parsed.getFullYear() !== year ||
+ parsed.getMonth() !== month - 1 ||
+ parsed.getDate() !== day ||
+ parsed.getHours() !== hour ||
+ parsed.getMinutes() !== minute ||
+ parsed.getSeconds() !== second ||
+ parsed.getMilliseconds() !== millisecond
+ ) {
+ return undefined;
+ }
+ return parsed;
+}
+
+export interface ReminderQuickPreset {
+ id: 'in-30-minutes' | 'later-today' | 'tomorrow-morning' | 'next-week';
+ label: string;
+ date: Date;
+}
+
+/** Common one-shot choices, computed when the form opens so labels are exact. */
+export function reminderQuickPresets(now: Date): ReminderQuickPreset[] {
+ // Elapsed time, not a local wall-clock mutation: adding 30 via setMinutes
+ // becomes 90 elapsed minutes when daylight saving time falls back.
+ const inThirtyMinutes = new Date(now.getTime() + 30 * 60 * 1000);
+
+ const laterToday = new Date(now);
+ laterToday.setHours(17, 0, 0, 0);
+
+ const tomorrowMorning = new Date(now);
+ tomorrowMorning.setDate(tomorrowMorning.getDate() + 1);
+ tomorrowMorning.setHours(
+ REMINDER_DEFAULT_TIME.hours,
+ REMINDER_DEFAULT_TIME.minutes,
+ 0,
+ 0
+ );
+
+ const nextWeek = new Date(now);
+ const daysUntilNextMonday = (8 - nextWeek.getDay()) % 7 || 7;
+ nextWeek.setDate(nextWeek.getDate() + daysUntilNextMonday);
+ nextWeek.setHours(
+ REMINDER_DEFAULT_TIME.hours,
+ REMINDER_DEFAULT_TIME.minutes,
+ 0,
+ 0
+ );
+
+ return [
+ { id: 'in-30-minutes', label: 'In 30m', date: inThirtyMinutes },
+ ...(laterToday > now
+ ? ([
+ { id: 'later-today', label: 'Later today', date: laterToday },
+ ] satisfies ReminderQuickPreset[])
+ : []),
+ {
+ id: 'tomorrow-morning',
+ label: 'Tomorrow',
+ date: tomorrowMorning,
+ },
+ { id: 'next-week', label: 'Next week', date: nextWeek },
+ ];
+}
+
+/** An exact, human-readable instant for previews and save confirmation. */
+export function formatReminderInstant(
+ date: Date,
+ timezone: string = getDefaultTimezone(),
+ now: Date = new Date()
+): string {
+ const dateParts = (value: Date) =>
+ new Intl.DateTimeFormat('en-CA', {
+ timeZone: timezone,
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ }).format(value);
+ const tomorrow = new Date(now);
+ tomorrow.setDate(tomorrow.getDate() + 1);
+
+ const calendarLabel =
+ dateParts(date) === dateParts(now)
+ ? 'Today'
+ : dateParts(date) === dateParts(tomorrow)
+ ? 'Tomorrow'
+ : new Intl.DateTimeFormat(undefined, {
+ timeZone: timezone,
+ weekday: 'long',
+ }).format(date);
+ const year =
+ new Intl.DateTimeFormat('en-US', {
+ timeZone: timezone,
+ year: 'numeric',
+ }).format(date) ===
+ new Intl.DateTimeFormat('en-US', {
+ timeZone: timezone,
+ year: 'numeric',
+ }).format(now)
+ ? undefined
+ : 'numeric';
+ const exactDate = new Intl.DateTimeFormat(undefined, {
+ timeZone: timezone,
+ month: 'short',
+ day: 'numeric',
+ year,
+ }).format(date);
+ const exactTime = new Intl.DateTimeFormat(undefined, {
+ timeZone: timezone,
+ hour: 'numeric',
+ minute: '2-digit',
+ }).format(date);
+ const zone = new Intl.DateTimeFormat(undefined, {
+ timeZone: timezone,
+ timeZoneName: 'short',
+ })
+ .formatToParts(date)
+ .find((part) => part.type === 'timeZoneName')?.value;
+
+ return `${calendarLabel}, ${exactDate} at ${exactTime} (${zone ?? timezone})`;
+}
+
+/** The schedule wording shown after persistence succeeds. */
+export function describeReminderConfirmation(
+ schedule: ReminderSchedule
+): string {
+ if (isRecurring(schedule)) {
+ if (!isCronRepresentable(schedule.cron)) {
+ return `Custom repeating schedule (${schedule.timezone})`;
+ }
+ return describeReminderSchedule(schedule) ?? 'Repeating reminder';
+ }
+ return formatReminderInstant(new Date(schedule.remindAt));
+}
+
/** A one-shot schedule firing at `date`. */
export function onceSchedule(date: Date): ReminderSchedule {
return { type: 'once', remindAt: date.toISOString() };
diff --git a/apps/web/src/lib/core/util/cron.test.ts b/apps/web/src/lib/core/util/cron.test.ts
index 944cb49340..871e42e2c9 100644
--- a/apps/web/src/lib/core/util/cron.test.ts
+++ b/apps/web/src/lib/core/util/cron.test.ts
@@ -5,6 +5,7 @@ import {
type CronParts,
DEFAULT_TIME,
describeCron,
+ isCronRepresentable,
isValidCronParts,
isValidTime,
normalizeCron,
@@ -162,6 +163,20 @@ describe('parseCron', () => {
});
});
+describe('isCronRepresentable', () => {
+ it('accepts schedules the shared picker can round-trip', () => {
+ expect(isCronRepresentable('0 0 9 * * *')).toBe(true);
+ expect(isCronRepresentable('0 30 14 * * 2-6')).toBe(true);
+ expect(isCronRepresentable('0 0 9 15 * *')).toBe(true);
+ });
+
+ it('rejects valid custom fields the shared picker cannot express', () => {
+ expect(isCronRepresentable('0 */15 9 * * *')).toBe(false);
+ expect(isCronRepresentable('0 0 9 1 3 *')).toBe(false);
+ expect(isCronRepresentable('0 0 9 * * 2 2027')).toBe(false);
+ });
+});
+
/**
* `09:00` as the runtime's locale writes it.
*
diff --git a/apps/web/src/lib/core/util/cron.ts b/apps/web/src/lib/core/util/cron.ts
index 926716e8cf..5666ae4537 100644
--- a/apps/web/src/lib/core/util/cron.ts
+++ b/apps/web/src/lib/core/util/cron.ts
@@ -246,6 +246,11 @@ export function parseCron(cron: string): CronParts {
return interpretCron(cron).parts;
}
+/** Whether the shared recurrence controls can round-trip this expression. */
+export function isCronRepresentable(cron: string): boolean {
+ return interpretCron(cron).representable;
+}
+
/**
* A parse, plus whether the expression was one the pickers can actually say.
*
diff --git a/apps/web/src/lib/core/util/dateSearch/dateParser.test.ts b/apps/web/src/lib/core/util/dateSearch/dateParser.test.ts
index 6f25db0a52..c65e3482d7 100644
--- a/apps/web/src/lib/core/util/dateSearch/dateParser.test.ts
+++ b/apps/web/src/lib/core/util/dateSearch/dateParser.test.ts
@@ -57,6 +57,24 @@ describe('parseDurationString', () => {
expect(parseDurationString('90min')).toEqual({ value: 90, unit: 'min' });
});
+ it('accepts natural "in" duration phrasing', () => {
+ expect(parseDurationString('in 30 minutes')).toEqual({
+ value: 30,
+ unit: 'min',
+ });
+ expect(
+ parseDateFromDuration('in 2 hours', new Date(2026, 8, 21, 10))
+ ).toEqual(new Date(2026, 8, 21, 12));
+ expect(parseDurationString('in 30m')).toEqual({
+ value: 30,
+ unit: 'min',
+ });
+ expect(parseDurationString('in 2mo')).toEqual({ value: 2, unit: 'm' });
+ expect(parseDateFromDuration('in 30m', new Date(2026, 8, 21, 10))).toEqual(
+ new Date(2026, 8, 21, 10, 30)
+ );
+ });
+
it('should parse seconds correctly', () => {
expect(parseDurationString('1s')).toEqual({ value: 1, unit: 's' });
expect(parseDurationString('30s')).toEqual({ value: 30, unit: 's' });
diff --git a/apps/web/src/lib/core/util/dateSearch/dateParser.ts b/apps/web/src/lib/core/util/dateSearch/dateParser.ts
index 60bf37469d..996bb366fc 100644
--- a/apps/web/src/lib/core/util/dateSearch/dateParser.ts
+++ b/apps/web/src/lib/core/util/dateSearch/dateParser.ts
@@ -52,7 +52,12 @@ const UNIT_ALIASES: Record<string, TimeUnit> = {
* Returns null if the input doesn't match the expected format
*/
export function parseDurationString(input: string): ParsedDuration | null {
- const s = input.trim().toLowerCase();
+ const normalized = input.trim().toLowerCase();
+ // Date-language fields commonly phrase a duration as "in 30 minutes".
+ // Keep the duration grammar itself small while accepting that natural
+ // prefix everywhere the shared parser is used.
+ const hasNaturalPrefix = normalized.startsWith('in ');
+ const s = hasNaturalPrefix ? normalized.slice(3).trim() : normalized;
if (!s) return null;
const firstLetter = s.search(/[a-z]/);
@@ -61,6 +66,11 @@ export function parseDurationString(input: string): ParsedDuration | null {
const numPart = s.slice(0, firstLetter).trim();
let unitPart = s.slice(firstLetter).trim() as TimeUnit;
+ // The duration DSL historically uses bare `m` for months, but in natural
+ // phrasing (`in 30m`) that abbreviation conventionally means minutes. Keep
+ // bare `30m` backward-compatible; `in 2mo` and `in 2 months` stay months.
+ if (hasNaturalPrefix && unitPart === 'm') unitPart = 'min';
+
// Resolve word aliases to short units
if (!UNITS.has(unitPart) && unitPart in UNIT_ALIASES) {
unitPart = UNIT_ALIASES[unitPart];
diff --git a/docs/AGENT_GUIDE/README.md b/docs/AGENT_GUIDE/README.md
index 823e533f8e..efce1fd6c4 100644
--- a/docs/AGENT_GUIDE/README.md
+++ b/docs/AGENT_GUIDE/README.md
@@ -13,6 +13,7 @@ verified live against a local stack (`just run_local`).
| [../CLAUDE_CLOUD_DEMO.md](../CLAUDE_CLOUD_DEMO.md) | Claude in Harness settings, encrypted saved connection, Open in Claude, and cloud-side transcript polling |
| [channels.md](channels.md) | Channels: create, invite, message, participants, bots |
| [tasks.md](tasks.md) | Task list and creation dialog |
+| [reminders.md](reminders.md) | Creating and editing reminders, scheduling controls, and safe failure verification |
| [surfaces.md](surfaces.md) | Every other surface: inbox, email, search, files, calendar, calls, customers, activity, settings |
| [browser-technique.md](browser-technique.md) | Generic chrome-devtools MCP lessons learned on this app |
| [observability.md](observability.md) | Correlating a UI action to backend traces/logs with the Grafana MCP |
diff --git a/docs/AGENT_GUIDE/reminders.md b/docs/AGENT_GUIDE/reminders.md
new file mode 100644
index 0000000000..55936d65d8
--- /dev/null
+++ b/docs/AGENT_GUIDE/reminders.md
@@ -0,0 +1,51 @@
+# Reminders
+
+Use the dedicated Reminders workspace to inspect reminder lists and open an
+existing reminder. The create and edit surfaces share the same scheduling
+controls; reminder creation is a real hosted-data mutation, so use request
+interception when checking failures and cancel any draft used only for visual
+inspection.
+
+## Create or edit a reminder
+
+The create dialog is titled **New reminder**. A standalone reminder requires the
+**Reminder description** field; an entity-attached reminder may derive its title
+from the source badge. The **When** field accepts date language such as
+`tomorrow 9am`, `in 30 minutes`, weekdays, and explicit dates. The resolved
+weekday, date, time, and timezone appear in the **Scheduled:** preview before
+saving.
+
+Quick choices are **In 30m**, **Later today** (only before 5 PM), **Tomorrow**,
+**Next week**, and **Custom**. Each choice names its resolved time. Custom reveals
+native **Custom reminder date** and **Custom reminder time** controls. These are
+normal buttons and fields: Tab reaches them, Enter submits a valid form, and the
+dialog restores focus to its opener on dismissal.
+
+A local time skipped by a daylight-saving clock change (for example 2:30 AM on
+a spring-forward day) is rejected inline. Choose a time before or after the gap;
+the form must never silently normalize it to a different displayed time.
+
+**Repeat** is a collapsed secondary section. It offers **Does not repeat**,
+**Daily**, **Weekdays**, **Weekly**, and **Monthly**, followed by weekday/day,
+time, and timezone controls where relevant. An existing cron expression the
+picker cannot represent is labeled **Custom schedule** and remains byte-for-byte
+unchanged unless a replacement repeat choice is selected.
+
+The primary action reads **Set reminder** for create and **Save** for edit.
+**Cancel** dismisses without saving. A description-only edit of an overdue
+reminder keeps its old schedule instead of trying to reschedule it in the past.
+
+## Verify save failure without changing dev data
+
+Intercept `POST **/dss/reminders` and hold or reject the response. While held,
+the primary action shows a spinner, every form control is frozen, and duplicate
+submits issue only one request. On rejection, the dialog stays open, the entered
+title and time remain, focus returns to the control used to submit, and an inline
+alert explains that the draft can be retried.
+The alert also warns that a timed-out request may already have succeeded; the
+create API has no idempotency key, so the UI does not claim retries are
+duplicate-safe.
+
+After a confirmed response, the dialog closes and the success toast includes the
+exact persisted time or recurrence. Only a confirmed create runs the invoking
+surface's follow-up action.