Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(reminders): single-panel editor, click-to-edit, and inbox cleanup (#6070)
gbirman5521c048dfa9
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsxindex d025080fb9..ef2f6c31e9 100644--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx@@ -11,6 +11,7 @@ import { getViewPreset } from '@app/features/next-soup/sidebar/soup-filter-preseimport { NonMemberChannelPreview } from '@app/features/next-soup/soup-view/non-member-channel-preview';import { SoupView } from '@app/features/next-soup/soup-view/soup-view';import { useRecentViewFlag } from '@app/features/next-soup/use-recent-view-flag';+import { ReminderEditorSplit } from '@app/features/reminders/ReminderEditorSplit';import { SettingsPanelComponentWrapper } from '@app/features/settings/Settings';import { useAnalytics } from '@app/lib/analytics/analytics-context';import { usePosthog } from '@app/lib/analytics/posthog';@@ -137,12 +138,31 @@ function RedirectSplit(props: { to: SplitContent }) {return null;}+/**+ * A reminder view carries its reminder id in the id slot — `reminder-view~<id>`+ * — because component params are dropped on URL restore (see `contentUrlSegments`)+ * and split identity is keyed on the id, so each reminder needs a distinct one.+ */+const REMINDER_VIEW_PREFIX = 'reminder-view~';+export function resolveComponent(name: string,params?: ComponentParams): ResolvedComponent {const registration = REGISTRY.get(name);- if (!registration) throw new Error(`Component '${name}' not registered`);+ if (!registration) {+ if (name.startsWith(REMINDER_VIEW_PREFIX)) {+ const base = REGISTRY.get('reminder-view');+ if (base) {+ const reminderId = name.slice(REMINDER_VIEW_PREFIX.length);+ return {+ element: () => base.factory({ ...(params ?? {}), reminderId }),+ initialMeta: base.initialMeta,+ };+ }+ }+ throw new Error(`Component '${name}' not registered`);+ }return {element: () => registration.factory(params ?? {}),initialMeta: registration.initialMeta,@@ -600,6 +620,10 @@ registerComponent('skill-compose', (params) => {usePageViewTracking('skill-compose');return <ComposeSkill {...params} />;});+registerComponent('reminder-view', (params) => {+ usePageViewTracking('reminder-view');+ return <ReminderEditorSplit reminderId={params.reminderId as string} />;+});registerComponent('import-linear',lazy(() => import('@app/features/integrations/import-linear/ImportLinear'))diff --git a/apps/web/src/components/app/split-layout/components/SplitFileMenu.tsx b/apps/web/src/components/app/split-layout/components/SplitFileMenu.tsxindex caa2f5b33a..71a8b2a6fb 100644--- a/apps/web/src/components/app/split-layout/components/SplitFileMenu.tsx+++ b/apps/web/src/components/app/split-layout/components/SplitFileMenu.tsx@@ -467,6 +467,9 @@ export function SplitFileMenu(props: {const copyLinkOp = (): SplitFileMenuAction | undefined => {const entity = menuEntity();+ // Some entities have no shareable link (a reminder resolves to no block, so+ // its URL is dead); skip the item rather than copy one that won't open.+ if (entity && !copyLinkAction.canExecute(entity)) return undefined;// Foreign PRs link out via their entity URL (GitHub); the block-derived// fallback would mint an internal /pr URL that doesn't resolve, so omit// the item when the entity is unavailable.diff --git a/apps/web/src/features/next-soup/actions/make-copy-link-action.ts b/apps/web/src/features/next-soup/actions/make-copy-link-action.tsindex 46aa775ee7..e9b76b14d4 100644--- a/apps/web/src/features/next-soup/actions/make-copy-link-action.ts+++ b/apps/web/src/features/next-soup/actions/make-copy-link-action.ts@@ -53,10 +53,10 @@ const getEntityUrl = (entity: EntityData): string => {};export const makeCopyLinkAction = () => {- const canExecute = (_entity: EntityData): boolean => {- // Can copy link for any entity type- return true;- };+ // A reminder has no block of its own, so `/app/reminder/{id}` resolves to+ // nothing the orchestrator can open — there is no link to copy.+ const canExecute = (entity: EntityData): boolean =>+ entity.type !== 'reminder';const execute = async (entities: EntityData[]) => {// Only copy link for the first entity (doesn't make sense for bulk)diff --git a/apps/web/src/features/next-soup/actions/make-edit-reminder-action.test.ts b/apps/web/src/features/next-soup/actions/make-edit-reminder-action.test.tsindex 6e38013709..403bc35ffe 100644--- a/apps/web/src/features/next-soup/actions/make-edit-reminder-action.test.ts+++ b/apps/web/src/features/next-soup/actions/make-edit-reminder-action.test.ts@@ -2,20 +2,18 @@ import type { EntityData, ReminderEntity } from '@entity';import { beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({- openReminderEditor: vi.fn(),+ openEntityInSplitFromUnifiedList: vi.fn(),remindersEnabled: true,- cachedPreview: undefined as { rawName: string; access: string } | undefined,+ activeSplit: { id: 'controller' } as unknown,}));-vi.mock('@app/features/reminders/reminder-composer', () => ({- openReminderEditor: mocks.openReminderEditor,+// The action opens the reminder's editor the same way a row click does.+vi.mock('../utils', () => ({+ openEntityInSplitFromUnifiedList: mocks.openEntityInSplitFromUnifiedList,}));-// The reference name comes from the preview cache the row already populated.-vi.mock('@queries/preview', () => ({- getCachedItemPreview: () => mocks.cachedPreview,- isAccessiblePreviewItem: (item: { access?: string } | undefined) =>- item?.access === 'access',+vi.mock('@app/signal/splitLayout', () => ({+ globalSplitManager: () => ({ activeSplit: () => mocks.activeSplit }),}));// Spread the original so the other flags in this module keep working; only the@@ -28,20 +26,8 @@ vi.mock('@core/constant/featureFlags', async (importOriginal) => ({import { makeEditReminderAction } from './make-edit-reminder-action';-const NEXT_RUN = '2026-08-09T09:00:00.000Z';-const reminder = (overrides: Partial<ReminderEntity> = {}) =>- ({- type: 'reminder',- id: 'rem-1',- name: 'Chase the contract',- description: 'Chase the contract',- ownerId: '',- scheduleType: 'once',- nextRunAt: NEXT_RUN,- enabled: true,- ...overrides,- }) as ReminderEntity;+ ({ type: 'reminder', id: 'rem-1', ...overrides }) as ReminderEntity;const entity = (type: EntityData['type'], id = 'e1') =>({ type, id, name: 'Thing' }) as EntityData;@@ -50,10 +36,9 @@ describe('makeEditReminderAction', () => {beforeEach(() => {vi.clearAllMocks();mocks.remindersEnabled = true;- mocks.cachedPreview = undefined;});- it('can run for a one-shot reminder', () => {+ it('can run for a reminder', () => {expect(makeEditReminderAction().canExecute(reminder())).toBe(true);});@@ -64,164 +49,43 @@ describe('makeEditReminderAction', () => {expect(canExecute(entity('email'))).toBe(false);});- it('can run for a recurring reminder', () => {- const recurring = reminder({- scheduleType: 'recurring',- cron: '0 0 9 * * *',- timezone: 'UTC',- });-- expect(makeEditReminderAction().canExecute(recurring)).toBe(true);- });-- it('opens the editor with the reminder as the row knows it', () => {- makeEditReminderAction().execute([reminder()]);-- expect(mocks.openReminderEditor).toHaveBeenCalledWith({- id: 'rem-1',- description: 'Chase the contract',- remindAt: new Date(NEXT_RUN),- schedule: { type: 'once', remindAt: new Date(NEXT_RUN).toISOString() },- completed: false,- });- });-- // The composer diffs the edit against this, so a recurring reminder has to- // arrive as its cron rather than as its next firing — otherwise opening one- // and saving it would quietly flatten the series into a single date.- // The row and the editor both rebuild the schedule from a soup row, and each- // inventing its own substitution for an absent zone would describe the same- // reminder two ways — with the editor's diff then reading the substitution as- // a change and re-sending it, moving when the reminder fires. UTC is the- // shared fallback because it does not depend on who is looking.- it('falls back to UTC for a recurring reminder with no timezone', () => {- makeEditReminderAction().execute([- reminder({ scheduleType: 'recurring', cron: '0 0 9 * * *' }),- ]);-- expect(mocks.openReminderEditor).toHaveBeenCalledWith(- expect.objectContaining({- schedule: { type: 'recurring', cron: '0 0 9 * * *', timezone: 'UTC' },- })- );- });-- it('passes a recurring reminder its cron, not its next firing', () => {- makeEditReminderAction().execute([- reminder({- scheduleType: 'recurring',- cron: '0 0 9 * * 2-6',- timezone: 'America/New_York',- }),- ]);+ it('opens the reminder editor through the shared open path', () => {+ const row = reminder();+ makeEditReminderAction().execute([row]);- expect(mocks.openReminderEditor).toHaveBeenCalledWith(+ expect(mocks.openEntityInSplitFromUnifiedList).toHaveBeenCalledWith(+ row,expect.objectContaining({- schedule: {- type: 'recurring',- cron: '0 0 9 * * 2-6',- timezone: 'America/New_York',- },+ splitHandle: mocks.activeSplit,+ referredFrom: null,}));});- // A reschedule has to clear the done flag, so the editor needs to know the- // reminder was completed — see reminderEditPatch.- it('reports a completed reminder as completed', () => {- makeEditReminderAction().execute([- reminder({ completedAt: '2026-08-08T10:00:00.000Z' }),- ]);-- expect(mocks.openReminderEditor).toHaveBeenCalledWith(- expect.objectContaining({ completed: true })- );- });-- // Blanking the description in the editor means "name it after what it is- // about", exactly as it does when creating — so the name has to travel with- // the draft.- it('carries the reference name as the blank-description fallback', () => {- mocks.cachedPreview = { rawName: 'Q3 Contract', access: 'access' };-- makeEditReminderAction().execute([- reminder({ referencedEntity: { id: 'doc-1', type: 'document' } }),- ]);-- expect(mocks.openReminderEditor).toHaveBeenCalledWith(- expect.objectContaining({ fallbackDescription: 'Q3 Contract' })- );- });-- it('falls back to how lists label an unnamed reference', () => {- mocks.cachedPreview = { rawName: '', access: 'access' };-- makeEditReminderAction().execute([- reminder({ referencedEntity: { id: 'thread-1', type: 'email' } }),- ]);-- expect(mocks.openReminderEditor).toHaveBeenCalledWith(- expect.objectContaining({ fallbackDescription: '(No Subject)' })- );- });-- // Without a fallback the editor keeps the existing description, rather than- // renaming the reminder to a placeholder because a lookup missed.- it('carries no fallback for a standalone reminder', () => {- makeEditReminderAction().execute([reminder()]);-- expect(mocks.openReminderEditor).toHaveBeenCalledWith(- expect.objectContaining({ fallbackDescription: undefined })- );- });-- it('carries no fallback when the reference is not cached', () => {- mocks.cachedPreview = undefined;-- makeEditReminderAction().execute([- reminder({ referencedEntity: { id: 'doc-1', type: 'document' } }),- ]);-- expect(mocks.openReminderEditor).toHaveBeenCalledWith(- expect.objectContaining({ fallbackDescription: undefined })- );- });-- it('carries no fallback when the reference is inaccessible', () => {- mocks.cachedPreview = { rawName: 'Secret', access: 'no_access' };-- makeEditReminderAction().execute([- reminder({ referencedEntity: { id: 'doc-1', type: 'document' } }),- ]);-- expect(mocks.openReminderEditor).toHaveBeenCalledWith(- expect.objectContaining({ fallbackDescription: undefined })- );- });-it('does nothing for an empty selection', () => {makeEditReminderAction().execute([]);- expect(mocks.openReminderEditor).not.toHaveBeenCalled();+ expect(mocks.openEntityInSplitFromUnifiedList).not.toHaveBeenCalled();});- // The editor asks about one reminder's time, so a multi-select is not a- // batch — the menu only offers it for a single row.+ // The editor is about one reminder's time, so a multi-select is not a batch —+ // the menu only offers it for a single row, and the action takes the first.it('uses only the first entity of a multi-selection', () => {const first = reminder();makeEditReminderAction().execute([first, reminder({ id: 'rem-2' })]);- expect(mocks.openReminderEditor).toHaveBeenCalledOnce();- expect(mocks.openReminderEditor).toHaveBeenCalledWith(- expect.objectContaining({ id: 'rem-1' })+ expect(mocks.openEntityInSplitFromUnifiedList).toHaveBeenCalledOnce();+ expect(mocks.openEntityInSplitFromUnifiedList).toHaveBeenCalledWith(+ first,+ expect.anything());});it('does not open the editor for a non-reminder', () => {makeEditReminderAction().execute([entity('document')]);- expect(mocks.openReminderEditor).not.toHaveBeenCalled();+ expect(mocks.openEntityInSplitFromUnifiedList).not.toHaveBeenCalled();});it('cannot run when the reminders flag is off', () => {@@ -237,7 +101,7 @@ describe('makeEditReminderAction', () => {makeEditReminderAction().execute([reminder()]);- expect(mocks.openReminderEditor).not.toHaveBeenCalled();+ expect(mocks.openEntityInSplitFromUnifiedList).not.toHaveBeenCalled();});// The soup context menu and soup command menu both drive actions through@@ -250,8 +114,6 @@ describe('makeEditReminderAction', () => {>[1]);- expect(mocks.openReminderEditor).toHaveBeenCalledWith(- expect.objectContaining({ id: 'rem-1' })- );+ expect(mocks.openEntityInSplitFromUnifiedList).toHaveBeenCalledOnce();});});diff --git a/apps/web/src/features/next-soup/actions/make-edit-reminder-action.ts b/apps/web/src/features/next-soup/actions/make-edit-reminder-action.tsindex b16e11c02c..0eb43aa387 100644--- a/apps/web/src/features/next-soup/actions/make-edit-reminder-action.ts+++ b/apps/web/src/features/next-soup/actions/make-edit-reminder-action.ts@@ -1,41 +1,16 @@-import { openReminderEditor } from '@app/features/reminders/reminder-composer';-import {- reminderDescriptionForReference,- scheduleFromRow,-} from '@app/features/reminders/reminder-schedule';+import { globalSplitManager } from '@app/signal/splitLayout';import { ENABLE_REMINDERS } from '@core/constant/featureFlags';-import type { EntityData, ReminderEntity } from '@entity';-import {- getCachedItemPreview,- isAccessiblePreviewItem,-} from '@queries/preview';+import type { EntityData } from '@entity';+import { openEntityInSplitFromUnifiedList } from '../utils';import type { EntityActionListState } from './entity-action-context';-/**- * The description this reminder would get if it were being created now, for a- * blank description to fall back to.- *- * Read from the preview cache rather than fetched: the row the editor was- * opened from has already rendered this name, so it is cached. A miss returns- * undefined and the editor keeps the existing description instead — better than- * blocking on a request to answer a question the user may not even ask.- */-function fallbackDescriptionFor(entity: ReminderEntity): string | undefined {- const reference = entity.referencedEntity;- if (!reference) return undefined;-- const cached = getCachedItemPreview(reference.id);- if (!cached || !isAccessiblePreviewItem(cached)) return undefined;-- return reminderDescriptionForReference(cached.rawName, reference.type);-}-/*** Edit an existing reminder — its description, its schedule, or both.*- * `execute` opens the composer prefilled rather than writing anything: both- * answers come from the user, so there is nothing to do until that modal- * resolves. Single-entity only, like creating one.+ * Opens the reminder's editor the same way a row click does: through+ * {@link openEntityInSplitFromUnifiedList}, which resolves the reminder to its+ * `reminder-view` split and previews it into the Viewer when driven from a+ * Preview Pair. Single-entity only, like creating one.*/export const makeEditReminderAction = () => {const canExecute = (entity: EntityData): boolean =>@@ -47,13 +22,9 @@ export const makeEditReminderAction = () => {// otherwise still fire against a row that has since changed.if (!entity || entity.type !== 'reminder' || !canExecute(entity)) return;- openReminderEditor({- id: entity.id,- description: entity.description,- remindAt: new Date(entity.nextRunAt),- schedule: scheduleFromRow(entity),- completed: entity.completedAt != null,- fallbackDescription: fallbackDescriptionFor(entity),+ openEntityInSplitFromUnifiedList(entity, {+ splitHandle: globalSplitManager()?.activeSplit(),+ referredFrom: null,});};@@ -61,7 +32,7 @@ export const makeEditReminderAction = () => {entities: EntityData[],_soup: EntityActionListState) => {- // Opening the composer doesn't change the list, so selection and focus are+ // Opening the editor doesn't change the list, so selection and focus are// left where they are.execute(entities);};diff --git a/apps/web/src/features/next-soup/filters/configs/entity.ts b/apps/web/src/features/next-soup/filters/configs/entity.tsindex be7b6cc16e..d5e8f0f580 100644--- a/apps/web/src/features/next-soup/filters/configs/entity.ts+++ b/apps/web/src/features/next-soup/filters/configs/entity.ts@@ -11,6 +11,7 @@ import {doneRemindersFilter as doneRemindersPredicate,filesAndFolderFilter as filesAndFolderPredicate,firedRemindersFilter as firedRemindersPredicate,+ notDoneRemindersFilter as notDoneRemindersPredicate,projectFilter as projectPredicate,remindersFilter as remindersPredicate,scheduledRemindersFilter as scheduledRemindersPredicate,@@ -122,6 +123,19 @@ export const scheduledRemindersFilter = config({}),});+// Everything not done — fired and scheduled together — for a single inbox+// tab. Unlike Active/Scheduled it does not split on `reminderFired`, so both+// ends share one `comp:false` query; the page limit is generous enough for an+// inbox, and `soupQueryExcludesDone` still drops a reminder the moment it is+// marked done.+export const notDoneRemindersFilter = config({+ id: 'reminders-not-done',+ predicate: notDoneRemindersPredicate,+ query: defineQueryFilters({+ include: { includeReminders: true, reminderCompleted: false },+ }),+});+export const doneRemindersFilter = config({id: 'reminders-done',predicate: doneRemindersPredicate,diff --git a/apps/web/src/features/next-soup/filters/configs/index.ts b/apps/web/src/features/next-soup/filters/configs/index.tsindex 6df63d5737..75c5ec9e89 100644--- a/apps/web/src/features/next-soup/filters/configs/index.ts+++ b/apps/web/src/features/next-soup/filters/configs/index.ts@@ -39,6 +39,7 @@ import {firedRemindersFilter,foldersFilter,inFolderFilter,+ notDoneRemindersFilter,notTaskFilter,remindersFilter,scheduledRemindersFilter,@@ -104,6 +105,7 @@ export const SOUP_FILTERS = [remindersFilter,firedRemindersFilter,scheduledRemindersFilter,+ notDoneRemindersFilter,doneRemindersFilter,searchSupportedFilter,...ENTITY_TYPE_FILTERS,diff --git a/apps/web/src/features/next-soup/filters/predicates.ts b/apps/web/src/features/next-soup/filters/predicates.tsindex 327fcab3b2..6f4b4d63b7 100644--- a/apps/web/src/features/next-soup/filters/predicates.ts+++ b/apps/web/src/features/next-soup/filters/predicates.ts@@ -177,6 +177,14 @@ export function scheduledRemindersFilter(entity: EntityData): boolean {);}+/**+ * Reminders not yet dealt with — the scheduled ones still ahead and the fired+ * ones waiting on their owner, together. Everything but Done.+ */+export function notDoneRemindersFilter(entity: EntityData): boolean {+ return entity.type === 'reminder' && !entity.completedAt;+}+/** Reminders the owner has marked as dealt with. */export function doneRemindersFilter(entity: EntityData): boolean {return entity.type === 'reminder' && !!entity.completedAt;diff --git a/apps/web/src/features/next-soup/sidebar/soup-filter-presets.ts b/apps/web/src/features/next-soup/sidebar/soup-filter-presets.tsindex b5d0b379f8..0a8062346d 100644--- a/apps/web/src/features/next-soup/sidebar/soup-filter-presets.ts+++ b/apps/web/src/features/next-soup/sidebar/soup-filter-presets.ts@@ -220,20 +220,18 @@ export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {clientFilters: { and: ['explicit-noise'] },groupBy: 'date',}),- // Pending reminders only: scheduled but not yet fired. A fired reminder- // has already hit the inbox — Signal surfaces it through its not-done- // notification — so this tab is the forward-looking complement: what is- // coming, not what is due. Soonest first, since "newest first" on future- // dates would put December above tomorrow.+ // Every reminder still on the hook: the ones coming up and the ones that+ // have fired and are waiting to be dealt with (fired ones also surface in+ // Signal as their notification). Only marking one done drops it. Ascending+ // by fire time, so overdue leads and upcoming follows soonest-first.reminders: () => ({filters: defineQueryFilters({include: {includeReminders: true,reminderCompleted: false,- reminderFired: false,},}),- clientFilters: { and: ['reminders-scheduled'] },+ clientFilters: { and: ['reminders-not-done'] },sortDirection: 'asc',}),},diff --git a/apps/web/src/features/next-soup/soup-view/soup-view-create-button.tsx b/apps/web/src/features/next-soup/soup-view/soup-view-create-button.tsxindex 307febaaca..e93bfa17df 100644--- a/apps/web/src/features/next-soup/soup-view/soup-view-create-button.tsx+++ b/apps/web/src/features/next-soup/soup-view/soup-view-create-button.tsx@@ -24,6 +24,7 @@ import UploadIcon from '@phosphor/upload-simple.svg';import { Button, cn, Dropdown } from '@ui';import { createMemo, For, Show } from 'solid-js';import { NewCallButton } from './NewCallButton';+import { useMaybeSoupView } from './soup-view-context';// Which blocks to show as create options per view, in orderconst VIEW_CREATE_BLOCKNAMES: Partial<Record<ListView, CreatableName[]>> = {@@ -131,6 +132,7 @@ export const SoupViewCreateButton = () => {const panel = useSplitPanelOrThrow();const handleFileUpload = useHandleFileUpload();const isCreatableEnabled = useCreatableEnabled();+ const soupView = useMaybeSoupView();const currentView = createMemo(() => {const content = panel.handle.content();@@ -138,13 +140,24 @@ export const SoupViewCreateButton = () => {return isListViewID(content.id) ? content.id : undefined;});- const options = createMemo<CreateOption[]>(() => {+ // The inbox's Reminders tab is not a ListView of its own, but it offers the+ // same create button the standalone Reminders view does — a reminder is the+ // one thing you make from that list rather than triage into it.+ const createView = createMemo(() => {const view = currentView();+ if (view === 'inbox' && soupView?.activeTab() === 'reminders') {+ return 'reminders';+ }+ return view;+ });++ const options = createMemo<CreateOption[]>(() => {+ const view = createView();if (!view) return [];return getViewCreateOptions(view, isCreatableEnabled);});const createLabel = createMemo(() => {- const view = currentView();+ const view = createView();if (!view) return 'Create';return VIEW_CREATE_LABELS[view] ?? 'Create';});diff --git a/apps/web/src/features/next-soup/soup-view/views/inbox/inbox-card-layouts.tsx b/apps/web/src/features/next-soup/soup-view/views/inbox/inbox-card-layouts.tsxindex 6ea6c9c33f..39aef94096 100644--- a/apps/web/src/features/next-soup/soup-view/views/inbox/inbox-card-layouts.tsx+++ b/apps/web/src/features/next-soup/soup-view/views/inbox/inbox-card-layouts.tsx@@ -1,9 +1,10 @@import { ListPropertyValue } from '@app/features/next-soup/soup-view/views/tasks/list-property-value';+import { describeReminderWhen } from '@app/features/reminders/reminder-schedule';import { formatCallDuration } from '@block-call/utils';import { BotIcon } from '@channel/Message/BotIcon';import { MACRO_AI_BOT_ID, MACRO_AI_NAME } from '@channel/macroAi';import { EntityIcon, getEntityIconType } from '@core/component/EntityIcon';-import { ItemPreview, useItemPreviewData } from '@core/component/ItemPreview';+import { ItemPreview } from '@core/component/ItemPreview';import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';import {createTheme,@@ -136,11 +137,10 @@ const getNotificationSenderFallbackName = (};const getTimestamp = (entity: EntityData, notification?: Notification) => {- // Reminders sort on when they fire, so the row has to show that field too.- // The notification's time drifts from it for anything recurring, retried, or- // dispatched late, and the list then reads as unsorted.+ // The reminder's body already says when it fires, so the timestamp says when+ // it was set instead — the way other rows show when they arrived.if (entity.type === 'reminder') {- return entity.nextRunAt != null ? String(entity.nextRunAt) : undefined;+ return entity.createdAt != null ? String(entity.createdAt) : undefined;}const messageTime =@@ -1458,13 +1458,9 @@ export function CalendarEventCardLayout(props: InboxCardLayoutProps) {}/**- * A reminder is self-set, so there is no sender and no action to describe.- *- * With something to point at, the description leads and the chip below says- * what it is about. Standalone, there is nothing to link to, so the generic- * title leads — matching `ReminderMetadata::format_title` on the backend, so- * the row and the push notification read the same — and the description- * becomes the body.+ * A reminder is self-set, so there is no sender and no action to describe. Its+ * own description is the title; below it sit what it is about — a clickable chip+ * when it points at something — and when it next fires.*/export function ReminderCardLayout(props: InboxCardLayoutProps) {// The current description, not the notification's copy of it, so editing a@@ -1476,6 +1472,13 @@ export function ReminderCardLayout(props: InboxCardLayoutProps) {? props.item.entity.referencedEntity: undefined;+ // When it next comes due — a one-shot's firing time, or a recurring one's+ // cadence — so the row says when as well as what.+ const when = () =>+ props.item.entity.type === 'reminder'+ ? describeReminderWhen(props.item.entity)+ : undefined;+return (<BaseCarditem={props.item}@@ -1485,63 +1488,39 @@ export function ReminderCardLayout(props: InboxCardLayoutProps) {// Always the bell, never the referenced entity's icon: the row is a// reminder first, and the thing it points at is named right below.icon={<BellSimpleIcon class={AVATAR_GLYPH_CLASS} />}- title={- <Show when={referenced()} fallback="Reminder">+ // The reminder's own text, not a generic "Reminder" — its name is the+ // title, with a fallback only for the rare empty description.+ title={description() || 'Reminder'}+ >+ {/* A reminder fills the two body lines its three-line neighbors use, so+ the list rhythm stays even: what it is about (a chip, when there's+ something to point at) and when it fires. */}+ <div class="min-h-[2lh] min-w-0">+ <Show when={referenced()}>{(reference) => (- <ReminderTitle- description={description()}- id={reference().id}- type={reference().type}- />+ <InboxCard.Content class="truncate">+ {/* Its own click target: the chip opens what the reminder is+ about, while a click anywhere else on the row opens the editor.+ `ItemPreview` navigates but does not stop propagation itself. */}+ <span onClick={(event) => event.stopPropagation()}>+ <ReminderReferenceChip+ id={reference().id}+ type={reference().type}+ />+ </span>+ </InboxCard.Content>+ )}+ </Show>+ <Show when={when()}>+ {(text) => (+ <InboxCard.Content class="truncate">{text()}</InboxCard.Content>)}</Show>- }- >- {/* A reminder only says one thing, so the body reserves the two lines- its three-line neighbors use to keep the list rhythm even. The chip- replaces the description when there's something to point at. */}- <div class="min-h-[2lh] min-w-0">- <InboxCard.Content class="truncate">- <Show when={referenced()} fallback={description()}>- {(reference) => (- <ReminderReferenceChip- id={reference().id}- type={reference().type}- />- )}- </Show>- </InboxCard.Content></div></BaseCard>);}-/**- * The reminder's description, unless it says nothing the chip below doesn't.- *- * The composer derives the description from the entity, so today it usually- * *is* the referenced entity's name — printing it as the title would just- * repeat the chip. Falling back to the generic title keeps the row readable- * until descriptions become editable, and gets out of the way once they are.- */-function ReminderTitle(props: ItemEntity & { description: string }) {- const { item, name } = useItemPreviewData(() => ({- id: props.id,- type: props.type,- }));-- const ownText = () => {- const description = props.description.trim();- // While the reference is resolving, `name()` is a placeholder, so the two- // cannot be compared yet — hold the generic title rather than flash text- // that is about to collapse into it.- if (!description || item().loading) return undefined;- return description === name().trim() ? undefined : description;- };-- return <>{ownText() ?? 'Reminder'}</>;-}-/*** What the reminder is about, as an inline mention chip — the same icon, name,* and hover preview a document mention gets inside a message. `ItemPreview`diff --git a/apps/web/src/features/next-soup/utils.ts b/apps/web/src/features/next-soup/utils.tsindex eaa775da15..1e7bfe2a8d 100644--- a/apps/web/src/features/next-soup/utils.ts+++ b/apps/web/src/features/next-soup/utils.ts@@ -221,14 +221,15 @@ export const openEntityInNewTab = ({entity: EntityData;location?: SearchLocation;}) => {- // A reminder has no route of its own — it opens what it references, the- // same as the split paths. A standalone one references nothing, so there is- // no tab to open.+ // A reminder opens its own editor — a `reminder-view` component split with a+ // URL of its own — the same as the split paths, even a standalone one that+ // references nothing.if (entity.type === 'reminder') {- const target = reminderSplitTarget(entity);- if (!target) return;openExternalUrl(- new URL(`/app/${target.type}/${target.id}`, window.location.origin).href+ new URL(+ `/app/component/reminder-view~${entity.id}`,+ window.location.origin+ ).href);return;}@@ -640,9 +641,6 @@ export const openEntityInSplitFromUnifiedList = async (const blockOrchestrator = splitManager.getOrchestrator();- // A standalone reminder points at nothing, so there is nothing to open.- if (entity.type === 'reminder' && !entity.referencedEntity) return;-// Calendar is a singleton block. Event opens retarget that one instance// with a locator range, including repeat clicks on an already-open split.if (entity.type === 'calendar_event') {@@ -855,9 +853,10 @@ export function calendarBlockParamsForEntity(}/**- * The split a reminder opens: the entity it references, never itself.- * `undefined` for a standalone reminder, which points at nothing — callers use- * that to decide whether opening is possible at all.+ * The entity a reminder references, as block content. A reminder itself opens+ * its own `reminder-view` editor (see `getEntitySplitContent`); this is only+ * the reference, used where the reference is shown directly (PreviewPanel).+ * `undefined` for a standalone reminder, which points at nothing.** `fileType`/`subType` come resolved from the server, so a referenced document* lands on its real block rather than 'unknown'.@@ -899,12 +898,14 @@ function getEntitySplitContent(entity: EntityData) {return { type: 'contact' as const, id: entity.id };}).with({ type: 'reminder' }, (entity) => {- return (- reminderSplitTarget(entity) ?? {- type: 'unknown' as const,- id: entity.id,- }- );+ // A reminder has no block of its own; it opens its editor as a+ // component split. The reminder id rides in the content id (component+ // params are dropped on URL restore, and split identity is keyed on the+ // id, so each reminder needs a distinct one) — see `resolveComponent`.+ return {+ type: 'component' as const,+ id: `reminder-view~${entity.id}`,+ };})// Calendar events open the singleton calendar block; the open path// branches before reaching here, so this only serves duplicate checks.diff --git a/apps/web/src/features/reminders/ReminderComposerModal.tsx b/apps/web/src/features/reminders/ReminderComposerModal.tsxindex 9c6bfd7e26..54d26eba85 100644--- a/apps/web/src/features/reminders/ReminderComposerModal.tsx+++ b/apps/web/src/features/reminders/ReminderComposerModal.tsx@@ -1,116 +1,32 @@import { toast } from '@core/component/Toast/Toast';-import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';-import {- type CronParts,- describeCron,- isValidCronParts,- type ScheduleFrequency,- WEEKDAY_OPTIONS,-} from '@core/util/cron';-import {- type DateOption,- useDateSearch,-} from '@core/util/dateSearch/useDateSearch';-import {- type ListNavActions,- useListKeyBindings,-} from '@core/util/useListKeyBindings';import { type EntityData, InlineEntity } from '@entity';import BellIcon from '@phosphor/bell-simple.svg';import {- reminderSoupPatch,reminderTarget,useCreateReminderMutation,- useUpdateReminderMutation,} from '@queries/reminders/reminders';-import {- getSoupEntityById,- optimisticUpdateSoupEntity,- refetchSoupEntity,-} from '@queries/soup/cache';+import { refetchSoupEntity } from '@queries/soup/cache';import type { ReminderSchedule } from '@service-storage/generated/schemas/reminderSchedule';-import { mergeRefs } from '@solid-primitives/refs';-import {- Button,- CommandMenuEmptyState,- CommandMenuHotkeyHint,- CommandMenuListItem,- CommandMenuSearchInput,- CommandMenuShell,- cn,- Dialog,- Hotkey,-} from '@ui';-import {- createEffect,- createMemo,- createSelector,- createSignal,- For,- Match,- on,- onCleanup,- onMount,- Show,- Switch,-} from 'solid-js';+import { Dialog, Panel } from '@ui';+import { Show } from 'solid-js';+import { ReminderForm } from './ReminderForm';import {closeReminderComposer,- type ReminderDraft,reminderComposerOpen,reminderComposerState,takeReminderCreatedHandler,} from './reminder-composer';import {- defaultRepeatParts,- describeReminderSchedule,- futureDateOptions,- isRecurring,- onceSchedule,- REMINDER_DEFAULT_TIME,- REMINDER_DESCRIPTION_MAX_LENGTH,- recurringSchedule,- reminderDefaultOptions,- reminderEditOptions,- reminderEditPatch,- repeatPartsFromDate,- repeatPartsFromSchedule,- resolveEditedDescription,resolveReminderDescription,resolveStandaloneDescription,} from './reminder-schedule';-/** The composer's questions, asked in this order. */-type Step = 'description' | 'when' | 'repeat';-/**- * Asks two questions — what and when — for a reminder, either a new one about- * an entity or an existing one being edited.- *- * The date step is deliberately the date editor reached by `shift+cmd+o`: the- * same shell, entity chip, search input and `useDateSearch` list. The- * description step in front of it is optional when creating, and Enter on an- * empty field falls straight through to the date list.- *- * Editing runs the same two steps, prefilled from the reminder. Both keep the- * create flow's meaning of a blank answer: clearing the description names the- * reminder after whatever it is about, and the date list leads with keeping the- * time it already has.+ * 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+ * (`ReminderEditorSplit`), not here, so this only ever composes a new one.*/export function ReminderComposerModal() {- const [dialogRef, setDialogRef] = createSignal<HTMLElement | undefined>();- const [attach, hotkeyScope] = useHotkeyDOMScope('reminder-composer');- const [step, setStep] = createSignal<Step>('description');- const [description, setDescription] = createSignal('');- const [query, setQuery] = createSignal('');- const [selectedIndex, setSelectedIndex] = createSignal(0);- // The recurrence being built, only meaningful on the repeat step. Seeded when- // that step opens — from the reminder's own schedule when editing one that- // already repeats, so its picker starts where the user left it.- const [repeatParts, setRepeatParts] = createSignal<CronParts>(- repeatPartsFromDate(new Date())- );-// Nothing else brings a new reminder into Soup: the service emits no// websocket event on create (its only outbound signals are the dispatch// queue and the notification when a reminder fires), so without this fetch@@ -119,138 +35,16 @@ export function ReminderComposerModal() {const createReminder = useCreateReminderMutation({onSuccess: (reminder) => void refetchSoupEntity(reminder.id, 'reminder'),});- // Soup rows come from the normalized soup cache, not the reminders queries,- // so the mutation's own invalidation leaves an edited row reading its old- // description and firing time until a reload. Applying the response is not an- // optimistic guess — `nextRunAt` is derived server-side from the schedule,- // and this is the value it derived, which is why it lands on success rather- // than in `onMutate`.- const updateReminder = useUpdateReminderMutation({- onSuccess: (reminder) =>- optimisticUpdateSoupEntity(- reminderSoupPatch(- reminder,- getSoupEntityById(reminder.id)?.frecency_score- )- ),- });- const keybindings = useListKeyBindings(() => dialogRef());const entity = () => reminderComposerState.entity;- const editing = () => reminderComposerState.editing;const standalone = () => reminderComposerState.standalone === true;- /**- * The description as it would be stored, for a reminder about nothing.- *- * `undefined` means the field has nothing usable in it, which is what both- * the step's gate and its submit read — one answer, so a description of- * spaces cannot pass one and fail the other.- */- const standaloneDescription = () =>- resolveStandaloneDescription(description());-- /**- * Escape steps back to the description before it closes the composer,- * matching how the command menu treats a sub-scope.- *- * @returns whether it stepped back rather than closed.- */- const handleEscape = (): boolean => {- // Unwinds one step at a time, so escape from the repeat picker lands back on- // the date list rather than throwing the whole reminder away.- if (step() === 'repeat') {- setStep('when');- return true;- }- if (step() === 'when') {- setStep('description');- return true;- }- closeReminderComposer();- return false;- };-- /**- * Open the repeat picker, seeded from whatever is most specific.- *- * An existing recurrence first, so changing one starts where it is. Failing- * that the date the list is currently leading with, so typing "tomorrow 3pm"- * and then choosing to repeat gives a 3pm recurrence rather than discarding- * the time that was just asked for.- */- const openRepeatStep = (seed?: Date) => {- const current = editing()?.schedule;- setRepeatParts(- current && isRecurring(current)- ? repeatPartsFromSchedule(current)- : seed- ? repeatPartsFromDate(seed)- : defaultRepeatParts()- );- setStep('repeat');- };-- // Only reachable with focus outside the header input — the hotkey layer skips- // handlers while an editable is focused. Kobalte's document-level escape- // handler below covers the usual case; both have to agree.- const { dispose: disposeHotkey } = registerHotkey({- hotkey: ['escape'],- description: 'Go back, or close the reminder composer',- keyDownHandler: () => {- handleEscape();- return true;- },- scopeId: hotkeyScope,- });- onCleanup(disposeHotkey);-- createEffect(- on(reminderComposerOpen, () => {- setStep('description');- // Prefilled when editing, so the field starts from what the reminder- // already says rather than asking for it again.- setDescription(reminderComposerState.editing?.description ?? '');- setQuery('');- setSelectedIndex(0);- })- );-- /**- * Whether the description step has been answered well enough to leave.- *- * Only a standalone reminder can fail this. Everywhere else the field is- * optional because there is an entity to name the reminder after, so an- * empty one is an answer; with nothing to fall back on it is not, and the API- * rejects it.- */- const canAdvanceFromDescription = () =>- !standalone() || standaloneDescription() !== undefined;-- const advanceFromDescription = () => {- if (!canAdvanceFromDescription()) return;- setStep('when');- };-- // The dialog's Enter binding is a single shared slot, so whichever step is on- // screen has to claim it or the other step's stale handler stays live. The- // date step claims it from inside `WhenList`, which owns the list it moves- // through; the other two have no list, so they claim it here.- createEffect(- on(step, (current) => {- if (current === 'description') {- keybindings(descriptionStepKeybindings(advanceFromDescription));- } else if (current === 'repeat') {- keybindings(listlessStepKeybindings(() => void submitRepeat()));- }- })- );-const submitCreate = async (schedule: ReminderSchedule,- target: EntityData+ target: EntityData,+ input: string) => {- const resolved = resolveReminderDescription(description(), target);+ const resolved = resolveReminderDescription(input, target);const attachTo = reminderTarget(target);// Taken before the close, which clears it.const onCreated = takeReminderCreatedHandler();@@ -282,14 +76,14 @@ export function ReminderComposerModal() {* `entityType` without an `entityId` — and the description is whatever was* typed, since there is nothing to derive one from.*/- const submitStandalone = async (schedule: ReminderSchedule) => {- const resolved = standaloneDescription();- // Unreachable: the date step cannot be reached without a description. Kept- // as the last word on it rather than a `!` on the value above.- if (!resolved) {- setStep('description');- return;- }+ const submitStandalone = async (+ schedule: ReminderSchedule,+ input: string+ ) => {+ const resolved = resolveStandaloneDescription(input);+ // Unreachable: Save is disabled without a description. Kept as the last word+ // 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.@@ -307,96 +101,22 @@ export function ReminderComposerModal() {await onCreated?.();};- const submitEdit = async (- schedule: ReminderSchedule,- draft: ReminderDraft- ) => {- const patch = reminderEditPatch(draft, {- // Blank means the same here as it does when creating: name it after- // whatever it is about.- description: resolveEditedDescription(- description(),- draft.description,- draft.fallbackDescription- ),- schedule,- });- closeReminderComposer();-- // Neither answer moved. There is nothing to send — and an empty patch is- // rejected as having no fields to update.- if (!patch) return;-- try {- await updateReminder.mutateAsync({ id: draft.id, patch });- toast.success('Reminder updated');- } catch {- toast.failure('Failed to update reminder');- }- };-- /** Send whichever kind of schedule the user landed on. */- const submitSchedule = async (schedule: ReminderSchedule) => {- const draft = editing();- if (draft) return await submitEdit(schedule, draft);-+ const handleSubmit = (values: {+ description: string;+ schedule: ReminderSchedule;+ }) => {const target = entity();- if (target) return await submitCreate(schedule, target);-- if (standalone()) return await submitStandalone(schedule);- };-- const submit = async (date: Date) => {- const draft = editing();-- // The options are filtered against the time the list was built, so one can- // slip into the past while the composer sits open. Re-check rather than- // let the API reject it with an opaque failure. Keeping an existing time is- // exempt: it sends no schedule, so an overdue reminder stays renamable.- const keepsCurrentTime = date.getTime() === draft?.remindAt.getTime();- if (!keepsCurrentTime && date.getTime() <= Date.now()) {- toast.failure('That time has already passed — pick another');+ if (target) {+ submitCreate(values.schedule, target, values.description);return;}-- await submitSchedule(onceSchedule(date));- };-- /**- * Send the recurrence built on the repeat step.- *- * The validity gate lives here rather than at each control that can trigger a- * submit. It was in two places — the button's `disabled` and the Enter- * handler — and a gate written twice is one that eventually only holds in one- * of them. Every path in goes through this, so there is no path that skips- * it; the button's `disabled` is now an affordance rather than the check.- *- * No past-date check: a recurrence has no single instant to have passed, and- * the backend derives its first firing from the cron itself.- */- const submitRepeat = async () => {- const parts = repeatParts();- if (!isValidCronParts(parts)) return;- await submitSchedule(recurringSchedule(parts));+ if (standalone()) submitStandalone(values.schedule, values.description);};- /**- * Whether there is a reminder to compose at all.- *- * Both targets are cleared on close, so this unmounts the body while the- * dialog animates shut — otherwise the reset back to the description step- * would be visible as the date list flicking back to a Continue button.- */- const hasTarget = () =>- entity() !== undefined || editing() !== undefined || standalone();-- // The chip row carries the entity a new reminder is about, and — on the date- // step — the description typed so far as a way back to it. Editing and- // standalone have no entity, so the row is only there once something has been- // typed.- const showsToolbar = () =>- entity() !== undefined ||- (step() !== 'description' && !!description().trim());+ // Both targets are cleared on close, so this unmounts the form while the+ // dialog animates shut — and remounts it fresh (clearing the title) on the+ // next open, since a close always sits between two opens.+ const hasTarget = () => entity() !== undefined || standalone();return (<Dialog@@ -404,563 +124,49 @@ export function ReminderComposerModal() {onOpenChange={(open) => {if (!open) closeReminderComposer();}}- // Kobalte dismisses the whole dialog on escape unless the default is- // prevented, which would skip the step back.- onEscapeKeyDown={(event) => {- if (handleEscape()) event.preventDefault();- }}- contentRef={mergeRefs(attach, setDialogRef)}+ // The form autofocuses its title; keep Kobalte from stealing focus onto+ // the referenced-entity chip, which is the first tabbable otherwise.+ onOpenAutoFocus={(event) => event.preventDefault()}+ position="center"+ class="w-[28rem]">- <CommandMenuShell depth={2} class="rounded-xl max-h-108 text-sm">- <CommandMenuShell.Header>- <span class="pl-2 text-ink-extra-muted/55 pointer-events-none">- <BellIcon class="size-3" />- </span>- <Switch>- <Match when={step() === 'description'}>- <StepInput- placeholder={- editing()- ? 'Reminder description'- : // Not optional for a standalone reminder: there is no- // entity to name it after, so this is all it will ever- // say.- standalone()- ? "What's the reminder?"- : "What's the reminder? (optional)"- }- value={description()}- onInput={setDescription}- // Counts UTF-16 code units where the service counts characters,- // so this only ever stops short of the real limit, never past- // it. `resolveReminderDescription` applies the exact cap.- maxLength={REMINDER_DESCRIPTION_MAX_LENGTH}- />- </Match>- <Match when={step() === 'when'}>- <StepInput- placeholder="Remind me when?"- value={query()}- onInput={setQuery}- />- </Match>- <Match when={step() === 'repeat'}>- {/* Not an input: the repeat picker is controls, not a query, so- the header states what is being answered instead. */}- <span class="px-2 text-base text-ink-muted">How often?</span>- </Match>- </Switch>- </CommandMenuShell.Header>+ <Panel depth={2} class="rounded-xl">+ <Panel.Header class="px-4">+ <Dialog.Title class="flex items-center gap-2 text-sm font-semibold text-ink">+ <BellIcon class="size-3.5 text-ink-muted" />+ New reminder+ </Dialog.Title>+ </Panel.Header><Show when={hasTarget()}>- <Show when={showsToolbar()}>- <CommandMenuShell.Toolbar class="p-3 py-2 border-b-0 gap-2">- <Show when={entity()}>- {(target) => (- <div class="bg-active border border-edge-muted px-2 py-1 truncate text-xs rounded max-w-[50%]">- <InlineEntity entity={target()} />- </div>- )}- </Show>- {/* Sized to the space the entity chip leaves rather than to a- share of its own, so the pair can never overflow. */}- <Show when={step() === 'when' && description().trim()}>- {(typed) => (- <button- type="button"- class="bg-active border border-edge-muted px-2 py-1 truncate text-xs rounded min-w-0 flex-1 text-left text-ink-muted hover:text-ink"- title="Edit the description"- onClick={() => setStep('description')}- >- {typed()}- </button>- )}- </Show>- </CommandMenuShell.Toolbar>- </Show>- <Switch>- <Match when={step() === 'description'}>- <DescriptionStep- onContinue={advanceFromDescription}- // An affordance, not the check: `advanceFromDescription` holds- // the gate for every way through this step.- disabled={!canAdvanceFromDescription()}- />- </Match>- <Match when={step() === 'when'}>- <CommandMenuShell.Body>- <WhenList- query={query}- // Withheld for a recurring reminder. `reminderEditOptions`- // turns this into a "Keep current time" date row holding the- // next firing — which, activated, submits that single instant- // as a one-shot and collapses the series. The `keep` row- // carries the recurrence instead, and two adjacent rows both- // promising to preserve, one of which destroys, is worse than- // either alone.- current={() => {- const draft = editing();- if (!draft) return undefined;- return isRecurring(draft.schedule)- ? undefined- : draft.remindAt;- }}- currentRecurrence={() => {- const schedule = editing()?.schedule;- if (!schedule || !isRecurring(schedule)) return undefined;- return {- schedule,- description: describeReminderSchedule(schedule) ?? '',- };- }}- selectedIndex={selectedIndex}- setSelectedIndex={setSelectedIndex}- onSubmit={(date) => void submit(date)}- onKeep={(schedule) => void submitSchedule(schedule)}- onRepeat={openRepeatStep}- setKeybindings={keybindings}- />- </CommandMenuShell.Body>- </Match>- <Match when={step() === 'repeat'}>- <CommandMenuShell.Body>- <RepeatStep- parts={repeatParts}- setParts={setRepeatParts}- onSubmit={() => void submitRepeat()}- />- </CommandMenuShell.Body>- </Match>- </Switch>- </Show>- </CommandMenuShell>- </Dialog>- );-}--/**- * The dialog's shared list bindings for a step that has no list.- *- * The arrows go inert and Enter does the step's one action, so a step made of- * controls rather than rows still answers the key everything else answers.- */-function listlessStepKeybindings(select: VoidFunction): ListNavActions {- return { next: () => {}, previous: () => {}, select };-}--/**- * What the description step does with those bindings: Enter is the- * skip-through, advancing whether or not anything was typed.- */-function descriptionStepKeybindings(advance: VoidFunction): ListNavActions {- return listlessStepKeybindings(advance);-}--/**- * The header input for one step.- *- * Focused on mount rather than with `autofocus`, which only fires for the step- * that happens to be on screen when the dialog opens — moving between steps- * remounts the input inside an already-open dialog.- */-function StepInput(props: {- placeholder: string;- value: string;- onInput: (value: string) => void;- maxLength?: number;-}) {- let ref: HTMLInputElement | undefined;-- onMount(() => {- ref?.focus();- // Caret at the end: stepping back to a field that already has text should- // continue it, not land in front of it.- const end = ref?.value.length ?? 0;- ref?.setSelectionRange(end, end);- });-- return (- <CommandMenuSearchInput- ref={ref}- class="text-base"- placeholder={props.placeholder}- value={props.value}- maxLength={props.maxLength}- onInput={(e) => props.onInput(e.currentTarget.value)}- />- );-}--/**- * The optional first step: name the reminder, or press Enter past it.- *- * When creating, the entity name a blank field falls back to is never- * pre-filled, so skipping stays a single keystroke instead of a select-all and- * delete. When editing it necessarily is pre-filled — clearing it back out asks- * for that same fallback.- *- * Not optional for a standalone reminder, which has no fallback: `disabled`- * says so, and the caller's gate is what enforces it.- */-function DescriptionStep(props: {- onContinue: VoidFunction;- disabled?: boolean;-}) {- return (- <CommandMenuShell.Footer class="gap-2 border-t-0 py-3">- <CommandMenuHotkeyHint- hotkey={<Hotkey shortcut="escape" />}- label="Cancel"- />- <Button- variant="accent"- size="sm"- depth={3}- class="ml-auto gap-3 rounded-lg border-0"- disabled={props.disabled}- onClick={props.onContinue}- >- Continue- <Hotkey shortcut="enter" theme="current" />- </Button>- </CommandMenuShell.Footer>- );-}--/**- * One row of the date list: a date to fire once at, or the way through to the- * repeat picker.- *- * Modelled as a union rather than appending a fake `DateOption` so the repeat- * row cannot be mistaken for a date and submitted as one.- */-type WhenRow =- | { kind: 'date'; option: DateOption }- /**- * Leave an existing recurring schedule exactly as it is.- *- * Its own kind rather than a relabelled date row. A recurring reminder's next- * firing is one instant out of a series, so activating it as a date would- * submit that instant as a one-shot — quietly collapsing the whole series- * into a single day, from a row that says "Keep repeating".- */- | { kind: 'keep'; schedule: ReminderSchedule; detail: string }- | { kind: 'repeat'; label: string; detail?: string };--function WhenList(props: {- query: () => string;- /** The firing an edited reminder already has, offered as "Keep current time". */- current: () => Date | undefined;- /** An edited reminder's existing recurrence, when it has one. */- currentRecurrence: () =>- | { schedule: ReminderSchedule; description: string }- | undefined;- selectedIndex: () => number;- setSelectedIndex: (next: number | ((prev: number) => number)) => void;- onSubmit: (date: Date) => void;- /** Submit an existing recurring schedule unchanged. */- onKeep: (schedule: ReminderSchedule) => void;- onRepeat: (seed?: Date) => void;- setKeybindings: (actions: {- next: VoidFunction;- previous: VoidFunction;- select: () => void;- }) => void;-}) {- const rawOptions = useDateSearch({- query: props.query,- defaultTime: REMINDER_DEFAULT_TIME,- showTimeInResults: true,- });-- const dateOptions = createMemo(() => {- const now = new Date();- // The resting list is reminder-specific; typing hands off to the shared- // date search. Either way a reminder must fire in the future.- if (!props.query().trim()) {- const current = props.current();- return current- ? reminderEditOptions(current, now)- : reminderDefaultOptions(now);- }- return futureDateOptions(rawOptions(), now);- });-- const rows = createMemo<WhenRow[]>(() => {- const existing = props.currentRecurrence();- const typing = !!props.query().trim();-- // A reminder that already repeats has no single "current time" to keep —- // its schedule is the recurrence — so leading with a row that hands back- // that schedule untouched beats offering its next firing as if that were- // the whole story. Dropped while typing: a query is a request for a- // different time, and the keep row would sit above the answer.- const keep: WhenRow[] =- existing && !typing- ? [- {- kind: 'keep',- schedule: existing.schedule,- detail: existing.description,- },- ]- : [];-- const dates: WhenRow[] = dateOptions().map((option) => ({- kind: 'date',- option,- }));-- // Always last, so it never displaces the date someone is reaching for, and- // Enter on a date still creates a one-shot in two keystrokes.- return [- ...keep,- ...dates,- {- kind: 'repeat',- label: existing ? 'Change repeat…' : 'Repeat…',- detail: existing?.description,- },- ];- });-- // The date the selection last rested on, which is what a recurrence started- // from here should inherit. Arrowing down to "In 2 hours" and carrying on to- // "Repeat…" means that time, not whichever date happens to head the list.- const [seedDate, setSeedDate] = createSignal<Date | undefined>();- createEffect(() => {- const row = rows()[props.selectedIndex()];- if (row?.kind === 'date') setSeedDate(row.option.date);- });-- const activate = (row: WhenRow) => {- // Falls back to the leading option, which is what a typed query resolves- // to — so "tomorrow 3pm" then Repeat still gives a 3pm recurrence even- // without having moved the selection onto it.- if (row.kind === 'repeat') {- return props.onRepeat(seedDate() ?? dateOptions()[0]?.date);- }- if (row.kind === 'keep') return props.onKeep(row.schedule);- props.onSubmit(row.option.date);- };-- createEffect(- on(rows, (current) => {- props.setSelectedIndex(- Math.min(props.selectedIndex(), Math.max(current.length - 1, 0))- );- })- );-- props.setKeybindings({- next: () => {- const len = rows().length;- if (len === 0) return;- props.setSelectedIndex((prev) => (prev + 1) % len);- },- previous: () => {- const len = rows().length;- if (len === 0) return;- props.setSelectedIndex((prev) => (prev - 1 + len) % len);- },- select: () => {- const selected = rows()[props.selectedIndex()];- if (selected) activate(selected);- },- });-- createEffect(() => {- const index = props.selectedIndex();- document- .getElementById(`reminder-date-option-${index}`)- ?.scrollIntoView({ block: 'nearest' });- });-- const isSelected = createSelector(props.selectedIndex);-- return (- <>- <div class="p-2 max-h-54 overflow-y-auto overflow-x-hidden scrollbar-hidden">- <Show- when={dateOptions().length > 0 || !props.query().trim()}- fallback={- <CommandMenuEmptyState>- No future dates match "{props.query()}"- </CommandMenuEmptyState>- }- >- <For each={rows()}>- {(row, index) => (- <CommandMenuListItem- id={`reminder-date-option-${index()}`}- selected={isSelected(index())}- onClick={() => activate(row)}- onMouseMove={() => props.setSelectedIndex(index())}- class="scroll-m-2"- >- <div class="flex-1 text-left">- <p class="text-sm font-medium">- {row.kind === 'date'- ? row.option.displayText- : row.kind === 'keep'- ? 'Keep repeating'- : row.label}- </p>- </div>- <span class="text-xs text-ink-muted">- {row.kind === 'date' ? row.option.secondaryText : row.detail}- </span>- </CommandMenuListItem>- )}- </For>- </Show>- </div>-- <div class="p-4 border-t border-edge-muted flex items-center gap-4">- <div class="text-xs text-ink-muted">- <span>Use queries like </span>- <code class="bg-active px-1">3d</code>,{' '}- <code class="bg-active px-1">1w</code>,{' '}- <code class="bg-active px-1">feb 17</code>,{' '}- <code class="bg-active px-1">tomorrow</code>, or{' '}- <code class="bg-active px-1">tomorrow 3pm</code>- </div>- <CommandMenuHotkeyHint- class="ml-auto shrink-0 text-xs text-ink-extra-muted/80"- hotkey={<Hotkey shortcut="escape" />}- label="Back"- />- </div>- </>- );-}--/**- * The recurrences the picker offers, in ascending period.- *- * No daily entry: weekly with every day ticked says the same thing, and the- * summary reads it back as "every day".- */-const REPEAT_FREQUENCIES: Array<{ value: ScheduleFrequency; label: string }> = [- { value: 'week', label: 'Weekly' },- { value: 'month', label: 'Monthly' },-];--/**- * Builds a recurrence: how often, on which days, at what time.- *- * Deliberately the same shape as the automation schedule editor — frequency,- * then the one control that frequency needs, then a time — because it is the- * same question, and someone who has set up an automation should not have to- * learn a second way to say "every weekday at 9".- */-function RepeatStep(props: {- parts: () => CronParts;- setParts: (next: CronParts) => void;- onSubmit: VoidFunction;-}) {- const update = (patch: Partial<CronParts>) =>- props.setParts({ ...props.parts(), ...patch });-- const toggleDay = (value: string) => {- const days = props.parts().daysOfWeek;- // Never empty: an empty selection builds an every-day cron, which is not- // what unticking your last day is asking for.- const next = days.includes(value)- ? days.filter((day) => day !== value)- : [...days, value];- if (next.length > 0) update({ daysOfWeek: next });- };-- const summary = () => describeCron(props.parts());- // Gates submit on everything `buildCron` would otherwise substitute a- // fallback for — an out-of-range time, a day-of-month like 99 — so the- // schedule that gets stored is the one the summary above describes.- const isValid = () => isValidCronParts(props.parts());-- return (- <>- <div class="p-3 space-y-3 max-h-72 overflow-y-auto scrollbar-hidden">- <div class="flex gap-1">- <For each={REPEAT_FREQUENCIES}>- {(option) => (- <button- type="button"- class={cn(- 'flex-1 rounded px-2 py-1.5 text-sm border',- props.parts().frequency === option.value- ? 'bg-active border-edge text-ink'- : 'border-edge-muted text-ink-muted hover:text-ink'- )}- onClick={() => update({ frequency: option.value })}- >- {option.label}- </button>- )}- </For>- </div>-- <Show when={props.parts().frequency === 'week'}>- <div class="flex gap-1">- <For each={WEEKDAY_OPTIONS}>- {(day) => (- <button- type="button"- class={cn(- 'flex-1 rounded px-1 py-1.5 text-xs border',- props.parts().daysOfWeek.includes(day.value)- ? 'bg-active border-edge text-ink'- : 'border-edge-muted text-ink-muted hover:text-ink'+ <Panel.Body class="p-4 font-sans">+ <ReminderForm+ autofocus+ placeholder={+ // Not optional for a standalone reminder: there is no entity to+ // name it after, so this is all it will ever say.+ standalone()+ ? "What's the reminder?"+ : "What's the reminder? (optional)"+ }+ descriptionRequired={standalone()}+ submitLabel="Set reminder"+ reference={+ <Show when={entity()}>+ {(target) => (+ <div class="flex">+ <div class="max-w-full truncate rounded border border-edge-muted bg-active px-2 py-1 text-xs">+ <InlineEntity entity={target()} />+ </div>+ </div>)}- aria-pressed={props.parts().daysOfWeek.includes(day.value)}- onClick={() => toggleDay(day.value)}- >- {day.label}- </button>- )}- </For>- </div>- </Show>-- <div class="flex items-center gap-2">- <Show when={props.parts().frequency === 'month'}>- <label class="flex items-center gap-2 text-sm text-ink-muted">- Day- <input- type="number"- min="1"- max="31"- class="w-16 rounded-sm border border-edge-muted bg-surface px-2 py-1.5 text-sm text-ink outline-none focus:border-accent/20"- value={props.parts().dayOfMonth}- onInput={(e) => update({ dayOfMonth: e.currentTarget.value })}- />- </label>- </Show>- <label class="flex items-center gap-2 text-sm text-ink-muted">- At- <input- type="time"- class="rounded-sm border border-edge-muted bg-surface px-2 py-1.5 text-sm text-ink outline-none focus:border-accent/20"- value={props.parts().time}- onInput={(e) => update({ time: e.currentTarget.value })}+ </Show>+ }+ onCancel={closeReminderComposer}+ onSubmit={handleSubmit}/>- </label>- </div>- </div>-- <CommandMenuShell.Footer class="gap-3 py-3">- <span class="text-xs text-ink-muted truncate">{summary()}</span>- <Button- variant="accent"- size="sm"- depth={3}- class="ml-auto gap-3 rounded-lg border-0"- disabled={!isValid()}- onClick={props.onSubmit}- >- Set reminder- <Hotkey shortcut="enter" theme="current" />- </Button>- </CommandMenuShell.Footer>- </>+ </Panel.Body>+ </Show>+ </Panel>+ </Dialog>);}diff --git a/apps/web/src/features/reminders/ReminderEditorSplit.tsx b/apps/web/src/features/reminders/ReminderEditorSplit.tsxnew file mode 100644index 0000000000..5652e7f232--- /dev/null+++ b/apps/web/src/features/reminders/ReminderEditorSplit.tsx@@ -0,0 +1,174 @@+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import { ItemPreview } from '@core/component/ItemPreview';+import { toast } from '@core/component/Toast/Toast';+import type { ReminderEntity } from '@entity';+import BellIcon from '@phosphor/bell-simple.svg';+import SpinnerIcon from '@phosphor/spinner.svg';+import {+ reminderSoupPatch,+ useReminderQuery,+ useUpdateReminderMutation,+} from '@queries/reminders/reminders';+import {+ getSoupEntityById,+ optimisticUpdateSoupEntity,+} from '@queries/soup/cache';+import type { Reminder } from '@service-storage/generated/schemas/reminder';+import { createMemo, Match, onMount, Show, Switch } from 'solid-js';+import { ReminderForm, type ReminderFormValues } from './ReminderForm';+import {+ reminderEditPatch,+ resolveEditedDescription,+} from './reminder-schedule';++/** The display type an inline mention takes for the referenced entity. */+type MentionType = NonNullable<ReminderEntity['referencedEntity']>['type'];++/**+ * The referenced entity as a mention, resolved from the reminder's stored+ * `entityType` (the API name) to the display type a mention chip renders. The+ * chip resolves the name, icon, and access state itself. `undefined` for a+ * standalone reminder, or a target that has no mention of its own.+ */+function referenceMention(+ reminder: Reminder+): { id: string; type: MentionType } | undefined {+ if (!reminder.entityId || !reminder.entityType) return undefined;+ const type: MentionType | undefined =+ reminder.entityType === 'email_thread'+ ? 'email'+ : reminder.entityType === 'foreign_entity'+ ? 'foreign'+ : // A message reminder attaches to its parent channel; the rest map+ // straight across (document, chat, project, channel, call, crm_*).+ reminder.entityType === 'channel_message'+ ? 'channel'+ : reminder.entityType === 'document' ||+ reminder.entityType === 'chat' ||+ reminder.entityType === 'project' ||+ reminder.entityType === 'channel' ||+ reminder.entityType === 'call' ||+ reminder.entityType === 'crm_company' ||+ reminder.entityType === 'crm_contact'+ ? reminder.entityType+ : undefined;+ return type ? { id: reminder.entityId, type } : undefined;+}++/**+ * The reminder editor, hosted in a split so it previews into the Viewer like any+ * other entity rather than a modal over the list.+ *+ * It fetches the reminder by id (the id is encoded in the split content, so it+ * survives a reload), seeds the shared {@link ReminderForm}, and shows the+ * entity the reminder is about as a preview card. Saving writes through the same+ * mutation the create modal uses and closes the split.+ */+export function ReminderEditorSplit(props: { reminderId: string }) {+ const panel = useSplitPanelOrThrow();+ onMount(() => panel.handle.setDisplayName('Reminder'));++ const query = useReminderQuery(() => props.reminderId);++ // 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+ // and firing time until a reload. `nextRunAt` is derived server-side, so this+ // applies the value the server returned rather than an optimistic guess.+ const updateReminder = useUpdateReminderMutation({+ onSuccess: (reminder) =>+ optimisticUpdateSoupEntity(+ reminderSoupPatch(+ reminder,+ getSoupEntityById(reminder.id)?.frecency_score+ )+ ),+ });++ const reference = createMemo(() => {+ const reminder = query.data;+ return reminder ? referenceMention(reminder) : undefined;+ });++ const save = async (values: ReminderFormValues, reminder: Reminder) => {+ const patch = reminderEditPatch(+ {+ description: reminder.description,+ schedule: reminder.schedule,+ completed: reminder.completedAt != null,+ },+ {+ // A blanked title keeps the current description rather than re-deriving+ // the referenced entity's name. It cannot safely re-derive: a thread+ // reminder attaches to its parent channel but is described by the+ // message text, so naming it after the channel would drop the only+ // thing telling two reminders on that channel apart — and the stored+ // reminder cannot tell a thread reminder from a plain channel one.+ description: resolveEditedDescription(+ values.description,+ reminder.description+ ),+ schedule: values.schedule,+ }+ );+ // Neither answer moved — nothing to send, and an empty patch is rejected.+ if (!patch) {+ panel.handle.close();+ return;+ }+ try {+ await updateReminder.mutateAsync({ id: reminder.id, patch });+ toast.success('Reminder updated');+ panel.handle.close();+ } catch {+ toast.failure('Failed to update reminder');+ }+ };++ return (+ <div class="h-full min-h-0 overflow-y-auto bg-panel font-sans">+ <div class="mx-auto w-full max-w-xl p-6">+ <Switch>+ <Match when={query.data}>+ {(reminder) => (+ <ReminderForm+ initialDescription={reminder().description}+ initialSchedule={reminder().schedule}+ initialRemindAt={reminder().nextRunAt}+ placeholder="Reminder description"+ submitLabel="Save"+ pending={updateReminder.isPending}+ reference={+ <Show when={reference()}>+ {(ref) => (+ <div class="flex">+ <ItemPreview id={ref().id} type={ref().type} />+ </div>+ )}+ </Show>+ }+ revertOnCancel+ onCancel={(wasDirty) => {+ // Reverting an edit keeps the panel open; a clean cancel+ // dismisses the preview.+ if (!wasDirty) panel.handle.close();+ }}+ onSubmit={(values) => void save(values, reminder())}+ />+ )}+ </Match>+ <Match when={query.isLoading}>+ <div class="flex items-center justify-center py-16 text-ink-muted">+ <SpinnerIcon class="size-5 animate-spin" />+ </div>+ </Match>+ <Match when={query.isError || !query.data}>+ <div class="flex flex-col items-center justify-center gap-2 py-16 text-ink-muted">+ <BellIcon class="size-6 text-ink-extra-muted" />+ <span class="text-sm">This reminder is no longer available.</span>+ </div>+ </Match>+ </Switch>+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/reminders/ReminderForm.tsx b/apps/web/src/features/reminders/ReminderForm.tsxnew file mode 100644index 0000000000..8f66a116db--- /dev/null+++ b/apps/web/src/features/reminders/ReminderForm.tsx@@ -0,0 +1,583 @@+import { toast } from '@core/component/Toast/Toast';+import {+ type CronParts,+ describeCron,+ getDefaultTimezone,+ isValidCronParts,+ type ScheduleFrequency,+ WEEKDAY_OPTIONS,+} from '@core/util/cron';+import { TZDateMini } from '@date-fns/tz';+import type { ReminderSchedule } from '@service-storage/generated/schemas/reminderSchedule';+import { Button, cn } from '@ui';+import {+ createEffect,+ createSignal,+ For,+ type JSX,+ Match,+ onMount,+ Show,+ Switch,+} from 'solid-js';+import {+ isRecurring,+ onceSchedule,+ REMINDER_DEFAULT_TIME,+ REMINDER_DESCRIPTION_MAX_LENGTH,+ recurringSchedule,+ repeatPartsFromDate,+ repeatPartsFromSchedule,+} from './reminder-schedule';+import { TimezoneSelect } from './TimezoneSelect';++/** How a reminder repeats: not at all (a one-shot), or on a weekly/monthly cron. */+type RepeatKind = 'once' | ScheduleFrequency;++/** What the form hands back on submit: the raw title and the chosen schedule. */+export interface ReminderFormValues {+ /** The raw title input; the caller resolves and clamps it per its mode. */+ description: string;+ /**+ * The schedule to store. On an unchanged edit this is the reminder's original+ * schedule verbatim, so the caller's diff omits it — which is what lets an+ * overdue reminder be renamed without being rejected as in the past.+ */+ schedule: ReminderSchedule;+}++export interface ReminderFormProps {+ /** Prefilled title. Absent when creating. */+ initialDescription?: string;+ /**+ * The reminder's current schedule, when editing one. Its presence marks the+ * form as an edit: only then can an untouched schedule be sent back unchanged.+ */+ initialSchedule?: ReminderSchedule;+ /**+ * The reminder's next firing, when editing one. Seeds the one-shot date/time+ * so switching a recurring reminder to "Does not repeat" defaults to its next+ * occurrence rather than a generic tomorrow-morning slot.+ */+ initialRemindAt?: Date | string;+ placeholder: string;+ /** A standalone reminder has no entity to name it after, so it needs a title. */+ descriptionRequired?: boolean;+ /** A card or chip for the entity this reminder is about, shown above the title. */+ reference?: JSX.Element;+ submitLabel: string;+ pending?: boolean;+ 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.+ */+ revertOnCancel?: boolean;+ /** Notified when the fields drift from (or return to) their 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.+ */+ onCancel: (wasDirty: boolean) => void;+ onSubmit: (values: ReminderFormValues) => void;+}++const pad = (value: number) => String(value).padStart(2, '0');++/** `YYYY-MM-DD` for a date in local time — the value a `<input type="date">` takes. */+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. */+function toTimeInput(date: Date): string {+ return `${pad(date.getHours())}:${pad(date.getMinutes())}`;+}++/** Whether two picker recurrences say the same thing, ignoring day order. */+function samePartsShape(a: CronParts, b: CronParts): boolean {+ return (+ a.frequency === b.frequency &&+ a.time === b.time &&+ a.dayOfMonth === b.dayOfMonth &&+ a.daysOfWeek.length === b.daysOfWeek.length &&+ a.daysOfWeek.every((day) => b.daysOfWeek.includes(day))+ );+}++/** The same instant, at `REMINDER_DEFAULT_TIME`, one day out — the create default. */+function atDefault(now: Date): Date {+ const result = new Date(now);+ result.setDate(result.getDate() + 1);+ result.setHours(+ REMINDER_DEFAULT_TIME.hours,+ REMINDER_DEFAULT_TIME.minutes,+ 0,+ 0+ );+ return result;+}++/** The control values to open with, derived from the reminder (or the defaults). */+function deriveSeed(+ description: string | undefined,+ schedule: ReminderSchedule | undefined,+ remindAt: Date | string | undefined+) {+ const now = new Date();+ const recurring = schedule !== undefined && isRecurring(schedule);+ // The reminder's next firing seeds the one-shot fields — for a recurring+ // reminder that is its next occurrence, so switching to "Does not repeat"+ // lands there rather than on a generic tomorrow-morning slot.+ const onceSeedDate = remindAt ? new Date(remindAt) : atDefault(now);+ const parts = recurring+ ? repeatPartsFromSchedule(schedule)+ : repeatPartsFromDate(onceSeedDate);+ const kind: RepeatKind = recurring ? parts.frequency : 'once';++ return {+ description: description ?? '',+ repeat: kind,+ onceDate: toDateInput(onceSeedDate),+ onceTime: toTimeInput(onceSeedDate),+ parts,+ // The zone a recurring reminder was built in, so re-sending an edited+ // recurrence keeps firing at the same wall-clock time even when the editor+ // sits in a different timezone. Absent for a one-shot or a new recurrence.+ recurringTimezone: recurring ? schedule.timezone : undefined,+ // What an untouched edit sends back unchanged. For a create the controls+ // are always rebuilt (and past-checked), so this is only read on edit.+ originalSchedule: schedule ?? onceSchedule(onceSeedDate),+ };+}++/** The zone's offset from UTC at `instant`, as sortable minutes and a ±HH:MM tag. */+function gmtOffset(+ zone: string,+ instant: Date+): { minutes: number; text: string } {+ const offset = new Intl.DateTimeFormat('en-US', {+ timeZone: zone,+ timeZoneName: 'longOffset',+ })+ .formatToParts(instant)+ .find((part) => part.type === 'timeZoneName')?.value;+ const match = offset?.match(/GMT([+-])(\d{2}):(\d{2})/);+ if (!match) return { minutes: 0, text: '+00:00' };+ const sign = match[1] === '-' ? -1 : 1;+ const minutes = sign * (Number(match[2]) * 60 + Number(match[3]));+ return { minutes, text: `${match[1]}${match[2]}:${match[3]}` };+}++/** A short zone tag ("EDT", "GMT+5:30") for the schedule summary and once view. */+function shortZone(zone: string, instant = new Date()): string {+ return (+ new Intl.DateTimeFormat('en-US', { timeZone: zone, timeZoneName: 'short' })+ .formatToParts(instant)+ .find((part) => part.type === 'timeZoneName')?.value ?? zone+ );+}++/**+ * Every IANA zone the runtime lists, labelled with its current GMT offset and+ * ordered by that offset so the list reads west-to-east. Built once — the set+ * does not change within a session.+ */+const TIMEZONE_OPTIONS: { value: string; label: string }[] = (() => {+ const zones =+ typeof Intl.supportedValuesOf === 'function'+ ? Intl.supportedValuesOf('timeZone')+ : [getDefaultTimezone()];+ const now = new Date();+ return zones+ .map((zone) => {+ const offset = gmtOffset(zone, now);+ return {+ value: zone,+ label: `(GMT${offset.text}) ${zone.replace(/_/g, ' ')}`,+ order: offset.minutes,+ };+ })+ .sort((a, b) => a.order - b.order || a.value.localeCompare(b.value))+ .map(({ value, label }) => ({ value, label }));+})();++/**+ * The reminder editor's fields — title, how it repeats, and when — shared by the+ * create modal and the edit split.+ *+ * It owns the controls and their validity and hands back the resolved+ * `{ description, schedule }` on submit; the caller decides whether that is a+ * create or an update. The title and schedule sit together, laid out like the+ * calendar event editor, so either can be changed in one pass.+ */+export function ReminderForm(props: ReminderFormProps) {+ const seed = deriveSeed(+ props.initialDescription,+ props.initialSchedule,+ props.initialRemindAt+ );+ const isEdit = props.initialSchedule !== undefined;++ const localZone = getDefaultTimezone();+ 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);+ 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+ // editable, so a reminder can fire in a zone other than the one editing it.+ const [timezone, setTimezone] = createSignal(+ seed.recurringTimezone ?? localZone+ );++ // 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.+ const initialRepeat = seed.repeat;+ const initialOnceDate = seed.onceDate;+ const initialOnceTime = seed.onceTime;+ const initialParts = seed.parts;+ const initialTimezone = seed.recurringTimezone ?? localZone;++ let titleRef: HTMLInputElement | undefined;+ onMount(() => {+ if (props.autofocus) titleRef?.focus();+ });++ const onceDateTime = () => new Date(`${onceDate()}T${onceTime()}`);++ /** Whether the schedule controls still hold exactly what they were seeded to. */+ const scheduleUntouched = () => {+ if (repeat() !== initialRepeat) return false;+ return repeat() === 'once'+ ? onceDate() === initialOnceDate && onceTime() === initialOnceTime+ : samePartsShape(repeatParts(), initialParts) &&+ timezone() === initialTimezone;+ };++ /**+ * Whether saving would actually change anything — kept in step with what+ * `reminderEditPatch` treats as a change, so the "Unsaved changes" hint and+ * the Save button never light up for an edit that no-ops. A blank title keeps+ * the current description and surrounding whitespace clamps away, so only a+ * different non-blank title counts.+ */+ const isDirty = () => {+ const trimmed = description().trim();+ const titleChanged = trimmed !== '' && trimmed !== seed.description.trim();+ return titleChanged || !scheduleUntouched();+ };++ // Let the host reflect the unsaved state (e.g. a dot on the split's title).+ createEffect(() => props.onDirtyChange?.(isDirty()));++ const reset = () => {+ setDescription(seed.description);+ setRepeat(seed.repeat);+ setOnceDate(seed.onceDate);+ setOnceTime(seed.onceTime);+ setRepeatParts(seed.parts);+ setTimezone(initialTimezone);+ };++ 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;+ }+ }+ setRepeatParts((parts) => ({ ...parts, frequency: kind }));+ };++ const updateParts = (patch: Partial<CronParts>) =>+ setRepeatParts((parts) => ({ ...parts, ...patch }));++ const toggleDay = (value: string) => {+ const days = repeatParts().daysOfWeek;+ // Never empty: an empty selection builds an every-day cron, which is not+ // what unticking your last day is asking for.+ const next = days.includes(value)+ ? days.filter((day) => day !== value)+ : [...days, value];+ if (next.length > 0) updateParts({ daysOfWeek: next });+ };++ 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+ // renamed, and keeps a description-only edit from clearing its done flag.+ // A create always rebuilds (and past-checks) its schedule.+ if (isEdit && scheduleUntouched()) {+ props.onSubmit({+ description: description(),+ schedule: seed.originalSchedule,+ });+ return;+ }++ if (repeat() === 'once') {+ const date = onceDateTime();+ if (Number.isNaN(date.getTime())) 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()) {+ toast.failure('That time has already passed — pick another');+ return;+ }+ props.onSubmit({+ description: description(),+ schedule: onceSchedule(date),+ });+ return;+ }++ const parts = repeatParts();+ // No past-date check: a recurrence has no single instant to have passed, and+ // the backend derives its first firing from the cron itself. The zone comes+ // from the picker, seeded from the reminder's own zone (or the viewer's).+ if (!isValidCronParts(parts)) return;+ props.onSubmit({+ description: description(),+ schedule: recurringSchedule(parts, timezone()),+ });+ };++ /**+ * Whether Save may fire. A standalone reminder needs a description; every+ * schedule needs to be one the backend will accept. The past-date check lives+ * in `submit` (as a toast) rather than here, so the button reads as an+ * affordance rather than blinking disabled as the clock passes a chosen time.+ */+ const canSubmit = () => {+ if (props.descriptionRequired && !description().trim()) return false;+ if (props.pending) return false;+ return repeat() === 'once'+ ? !Number.isNaN(onceDateTime().getTime())+ : isValidCronParts(repeatParts());+ };++ return (+ <div class="flex flex-col gap-4 text-sm">+ {/* Outside the <form> on purpose: the reference card carries its own+ buttons (Copy Link, etc.), and a button inside a form submits it —+ which here would save-and-close the panel on a stray click. */}+ <Show when={props.reference}>{(node) => node()}</Show>++ <form+ class="flex flex-col gap-4"+ onSubmit={(event) => {+ event.preventDefault();+ submit();+ }}+ >+ <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}+ class="w-full rounded-md border border-edge-muted bg-surface px-2 py-2 text-sm text-ink outline-none placeholder:text-ink-placeholder focus:border-accent"+ />++ <div class="flex flex-col gap-2">+ <span class="text-xs font-medium text-ink-muted">Repeat</span>+ <div class="flex gap-1">+ <For+ each={+ [+ { value: 'once', label: 'Does not repeat' },+ { value: 'week', label: 'Weekly' },+ { value: 'month', label: 'Monthly' },+ ] as const+ }+ >+ {(option) => (+ <button+ type="button"+ class={cn(+ 'flex-1 rounded border px-2 py-1.5 text-xs',+ repeat() === option.value+ ? 'border-edge bg-active text-ink'+ : 'border-edge-muted text-ink-muted hover:text-ink'+ )}+ onClick={() => setRepeatKind(option.value)}+ >+ {option.label}+ </button>+ )}+ </For>+ </div>+ </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)}+ class="rounded-sm border border-edge-muted bg-surface px-2 py-1.5 text-sm text-ink outline-none focus:border-accent"+ />+ <input+ type="time"+ aria-label="Time"+ value={onceTime()}+ onInput={(event) => setOnceTime(event.currentTarget.value)}+ class="rounded-sm border border-edge-muted bg-surface px-2 py-1.5 text-sm text-ink outline-none focus:border-accent"+ />+ </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) => (+ <button+ type="button"+ class={cn(+ 'flex-1 rounded border px-1 py-1.5 text-xs',+ repeatParts().daysOfWeek.includes(day.value)+ ? 'border-edge bg-active text-ink'+ : 'border-edge-muted text-ink-muted hover:text-ink'+ )}+ aria-pressed={repeatParts().daysOfWeek.includes(+ day.value+ )}+ onClick={() => toggleDay(day.value)}+ >+ {day.label}+ </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 rounded-sm border border-edge-muted bg-surface px-2 py-1.5 text-sm text-ink outline-none focus:border-accent"+ />+ </label>+ <TimeField+ value={repeatParts().time}+ onChange={(time) => updateParts({ time })}+ />+ </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">+ <span class="font-medium">Timezone</span>+ <TimezoneSelect+ value={timezone()}+ onChange={setTimezone}+ options={TIMEZONE_OPTIONS}+ />+ </label>+ <span class="truncate text-xs text-ink-muted">+ {describeCron(repeatParts())} · {shortZone(timezone())}+ </span>+ </div>+ </Show>++ <div class="flex items-center gap-3 pt-2">+ <Show when={isEdit && isDirty()}>+ <span class="flex items-center gap-1.5 text-xs text-ink-muted">+ <span class="size-1.5 rounded-full bg-warning" />+ Unsaved changes+ </span>+ </Show>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ class="ml-auto rounded-lg"+ onClick={cancel}+ >+ Cancel+ </Button>+ <Button+ type="submit"+ variant="accent"+ size="sm"+ depth={3}+ class="rounded-lg border-0"+ disabled={!canSubmit() || (isEdit && !isDirty())}+ >+ {props.submitLabel}+ </Button>+ </div>+ </form>+ </div>+ );+}++/** A time-of-day field for the recurring schedule. `At HH:MM`. */+function TimeField(props: {+ value: string;+ onChange: (value: string) => void;+}) {+ return (+ <label class="flex items-center gap-2 text-sm text-ink-muted">+ At+ <input+ type="time"+ value={props.value}+ onInput={(event) => props.onChange(event.currentTarget.value)}+ class="rounded-sm border border-edge-muted bg-surface px-2 py-1.5 text-sm text-ink outline-none focus:border-accent"+ />+ </label>+ );+}diff --git a/apps/web/src/features/reminders/TimezoneSelect.tsx b/apps/web/src/features/reminders/TimezoneSelect.tsxnew file mode 100644index 0000000000..b7a030b38b--- /dev/null+++ b/apps/web/src/features/reminders/TimezoneSelect.tsx@@ -0,0 +1,160 @@+import type { CollectionNode } from '@kobalte/core';+import { Combobox } from '@kobalte/core/combobox';+import CaretDownIcon from '@phosphor/caret-down.svg';+import CheckIcon from '@phosphor/check.svg';+import SearchIcon from '@phosphor/magnifying-glass.svg';+import { cn, Layer } from '@ui';+import { type Accessor, createMemo, createSignal, Show } from 'solid-js';+import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';++export type TimezoneOption = { value: string; label: string };++const ITEM_HEIGHT = 32;++const VirtualizedListbox = () => {+ let handle: VirtualizerHandle | undefined;+ // Kobalte hands back the collection after applying its filter, so scroll+ // targeting must index the filtered list, not the original options.+ let visibleItems:+ | Accessor<Iterable<CollectionNode<TimezoneOption>>>+ | undefined;+ return (+ <Combobox.Listbox<TimezoneOption>+ scrollToItem={(key) => {+ const idx = Array.from(visibleItems?.() ?? []).findIndex(+ (item) => item.rawValue.value === key+ );+ if (idx !== -1) handle?.scrollToIndex(idx, { align: 'nearest' });+ }}+ class="max-h-[240px] overflow-y-auto scrollbar-hidden"+ >+ {(items) => {+ visibleItems = items;+ return (+ <Virtualizer+ ref={(h) => {+ handle = h;+ }}+ data={[...items()]}+ itemSize={ITEM_HEIGHT}+ >+ {(item) => (+ <Combobox.Item+ item={item}+ class="group flex w-full cursor-default items-center gap-1.5 rounded-lg p-1.5 px-2 text-left text-sm data-highlighted:bg-ink/5"+ >+ <span class="flex size-3.5 shrink-0 items-center justify-center text-accent">+ <Combobox.ItemIndicator>+ <CheckIcon class="size-3" />+ </Combobox.ItemIndicator>+ </span>+ <Combobox.ItemLabel class="flex-1 truncate text-ink">+ {item.rawValue.label}+ </Combobox.ItemLabel>+ </Combobox.Item>+ )}+ </Virtualizer>+ );+ }}+ </Combobox.Listbox>+ );+};++/**+ * A single-select timezone dropdown built on the same portalled, searchable+ * Combobox the rest of the app uses, so a 400-zone list stays a normal-sized+ * scrollable menu rather than the browser's full-height native picker.+ */+export function TimezoneSelect(props: {+ value: string;+ onChange: (zone: string) => void;+ options: TimezoneOption[];+ class?: string;+}) {+ const [search, setSearch] = createSignal('');+ // Keep the current zone in the collection even when the runtime no longer+ // lists it (a zone dropped between releases), so it resolves as the selection+ // and a stray pick cannot silently replace a still-valid stored zone.+ const optionsWithCurrent = createMemo(() =>+ props.options.some((option) => option.value === props.value)+ ? props.options+ : [+ { value: props.value, label: props.value.replace(/_/g, ' ') },+ ...props.options,+ ]+ );+ const selected = () =>+ optionsWithCurrent().find((option) => option.value === props.value) ?? null;+ const triggerLabel = () =>+ selected()?.label ?? props.value.replace(/_/g, ' ');+ const hasMatches = () => {+ const query = search().trim().toLowerCase();+ if (!query) return optionsWithCurrent().length > 0;+ return optionsWithCurrent().some((option) =>+ option.label.toLowerCase().includes(query)+ );+ };++ return (+ <Combobox<TimezoneOption>+ multiple={false}+ options={optionsWithCurrent()}+ value={selected()}+ onChange={(option) => option && props.onChange(option.value)}+ onInputChange={setSearch}+ onOpenChange={(open) => {+ if (!open) setSearch('');+ }}+ optionValue="value"+ optionTextValue="label"+ // Empty so Kobalte does not seed the search box with the selected zone's+ // text on open — our own trigger shows the selection; the box is for+ // filtering, which still runs on `optionTextValue`.+ optionLabel={() => ''}+ virtualized+ allowsEmptyCollection+ placement="bottom-start"+ gutter={4}+ >+ <Combobox.Control>+ <Combobox.Trigger+ type="button"+ aria-label="Timezone"+ class={cn(+ 'flex flex-1 items-center justify-between gap-2 rounded-sm border border-edge-muted bg-surface px-2 py-1.5 text-sm text-ink outline-none focus:border-accent',+ props.class+ )}+ >+ <span class="truncate">{triggerLabel()}</span>+ <CaretDownIcon class="size-3 shrink-0 text-ink-muted" />+ </Combobox.Trigger>+ </Combobox.Control>++ <Combobox.Portal>+ <Layer depth={2}>+ <Combobox.Content class="z-action-menu w-[24rem] max-w-[90vw] overflow-hidden rounded-xl border border-edge-muted bg-surface shadow-md">+ <div class="flex items-center gap-2 border-b border-edge-muted px-3 py-2">+ <SearchIcon class="size-3.5 shrink-0 text-ink-muted" />+ <Combobox.Input+ class="min-w-0 flex-1 bg-transparent text-sm caret-accent outline-none placeholder:text-ink-placeholder"+ placeholder="Search timezones..."+ />+ </div>+ <div class="p-1">+ <Show+ when={hasMatches()}+ fallback={+ <div class="px-2 py-3 text-center text-xs text-ink-muted">+ No timezones match "{search()}"+ </div>+ }+ >+ <VirtualizedListbox />+ </Show>+ </div>+ </Combobox.Content>+ </Layer>+ </Combobox.Portal>+ </Combobox>+ );+}diff --git a/apps/web/src/features/reminders/reminder-composer.test.ts b/apps/web/src/features/reminders/reminder-composer.test.tsindex e360df2f52..87fb39be01 100644--- a/apps/web/src/features/reminders/reminder-composer.test.ts+++ b/apps/web/src/features/reminders/reminder-composer.test.ts@@ -4,7 +4,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import {closeReminderComposer,openReminderComposer,- openReminderEditor,openStandaloneReminderComposer,reminderComposerOpen,reminderComposerState,@@ -14,16 +13,6 @@ import {const doc = (id: string, name: string) =>({ type: 'document', id, name }) as EntityData;-const REMIND_AT = '2026-08-09T09:00:00.000Z';--const draft = (id: string, description: string) => ({- id,- description,- remindAt: new Date(REMIND_AT),- schedule: { type: 'once' as const, remindAt: REMIND_AT },- completed: false,-});-describe('reminder composer state', () => {beforeEach(() => {closeReminderComposer();@@ -63,71 +52,19 @@ describe('reminder composer state', () => {});});-describe('reminder composer edit mode', () => {- beforeEach(() => {- closeReminderComposer();- });-- it('opens with the reminder being edited', () => {- openReminderEditor(draft('rem-1', 'Chase the contract'));-- expect(reminderComposerOpen()).toBe(true);- expect(reminderComposerState.editing?.id).toBe('rem-1');- expect(reminderComposerState.editing?.description).toBe(- 'Chase the contract'- );- });-- it('clears the reminder on close', () => {- openReminderEditor(draft('rem-1', 'Chase the contract'));- closeReminderComposer();-- expect(reminderComposerOpen()).toBe(false);- expect(reminderComposerState.editing).toBeUndefined();- });-- // The two modes are exclusive: the modal shows an entity chip for one and- // prefills from the reminder for the other, so a leftover from the previous- // open would put it in both at once.- it('drops a create target when opened to edit', () => {- openReminderComposer(doc('doc-1', 'Q3 Contract'));- openReminderEditor(draft('rem-1', 'Chase the contract'));-- expect(reminderComposerState.entity).toBeUndefined();- expect(reminderComposerState.editing?.id).toBe('rem-1');- });-- it('drops an edit target when opened to create', () => {- openReminderEditor(draft('rem-1', 'Chase the contract'));- openReminderComposer(doc('doc-1', 'Q3 Contract'));-- expect(reminderComposerState.editing).toBeUndefined();- expect(reminderComposerState.entity?.id).toBe('doc-1');- });-- it('replaces the reminder when reopened for another one', () => {- openReminderEditor(draft('rem-1', 'Chase the contract'));- openReminderEditor(draft('rem-2', 'Send the invoice'));-- expect(reminderComposerState.editing?.id).toBe('rem-2');- expect(reminderComposerState.editing?.description).toBe('Send the invoice');- });-});-describe('reminder composer standalone mode', () => {beforeEach(() => {closeReminderComposer();});// The flag is what the modal reads to know it is composing at all: with no- // entity and no draft, a closed composer and a standalone one look alike.- it('opens with no target of any kind', () => {+ // entity, a closed composer and a standalone one look alike.+ it('opens with no entity target', () => {openStandaloneReminderComposer();expect(reminderComposerOpen()).toBe(true);expect(reminderComposerState.standalone).toBe(true);expect(reminderComposerState.entity).toBeUndefined();- expect(reminderComposerState.editing).toBeUndefined();});it('clears the flag on close', () => {@@ -138,8 +75,8 @@ describe('reminder composer standalone mode', () => {expect(reminderComposerState.standalone).toBeUndefined();});- // The three modes are exclusive. A leftover flag would make the modal treat- // an entity's reminder as being about nothing, and drop the attachment.+ // The two modes are exclusive. A leftover flag would make the modal treat an+ // entity's reminder as being about nothing, and drop the attachment.it('drops a create target when opened standalone', () => {openReminderComposer(doc('doc-1', 'Q3 Contract'));openStandaloneReminderComposer();@@ -148,14 +85,6 @@ describe('reminder composer standalone mode', () => {expect(reminderComposerState.standalone).toBe(true);});- it('drops an edit target when opened standalone', () => {- openReminderEditor(draft('rem-1', 'Chase the contract'));- openStandaloneReminderComposer();-- expect(reminderComposerState.editing).toBeUndefined();- expect(reminderComposerState.standalone).toBe(true);- });-it('drops the standalone flag when opened for an entity', () => {openStandaloneReminderComposer();openReminderComposer(doc('doc-1', 'Q3 Contract'));@@ -163,14 +92,6 @@ describe('reminder composer standalone mode', () => {expect(reminderComposerState.standalone).toBeUndefined();expect(reminderComposerState.entity?.id).toBe('doc-1');});-- it('drops the standalone flag when opened to edit', () => {- openStandaloneReminderComposer();- openReminderEditor(draft('rem-1', 'Chase the contract'));-- expect(reminderComposerState.standalone).toBeUndefined();- expect(reminderComposerState.editing?.id).toBe('rem-1');- });});describe('reminder composer created handler', () => {@@ -195,15 +116,6 @@ describe('reminder composer created handler', () => {expect(takeReminderCreatedHandler()).toBeUndefined();});- // Editing an existing reminder is not a create, so the previous open's- // follow-up must not survive into it.- it('drops the created handler when opened to edit', () => {- openReminderComposer(doc('doc-1', 'Q3 Contract'), { onCreated: vi.fn() });- openReminderEditor(draft('rem-1', 'Chase the contract'));-- expect(takeReminderCreatedHandler()).toBeUndefined();- });-it('drops the previous created handler when reopened to create', () => {openReminderComposer(doc('doc-1', 'Q3 Contract'), { onCreated: vi.fn() });openReminderComposer(doc('doc-2', 'Roadmap'));diff --git a/apps/web/src/features/reminders/reminder-composer.ts b/apps/web/src/features/reminders/reminder-composer.tsindex 0fcd5b98c8..fee4b35768 100644--- a/apps/web/src/features/reminders/reminder-composer.ts+++ b/apps/web/src/features/reminders/reminder-composer.ts@@ -1,57 +1,20 @@import { createControlledOpenSignal } from '@core/util/createControlledOpenSignal';import type { EntityData } from '@entity';-import type { ReminderSchedule } from '@service-storage/generated/schemas/reminderSchedule';import { batch } from 'solid-js';import { createStore, reconcile } from 'solid-js/store';export const [reminderComposerOpen, setReminderComposerOpen] =createControlledOpenSignal(false, { id: 'reminder-create' });-/**- * The reminder being edited, as its row already knows it.- *- * Taken from the list rather than re-fetched: a soup row carries the- * description and `nextRunAt` already, so opening the editor costs no request- * and cannot show a spinner over a value the user is looking at.- */-export interface ReminderDraft {- /** The reminder's id, which the patch is addressed to. */- id: string;- /** Its current description, prefilled into the first step. */- description: string;- /** Its next firing, offered as "Keep current time". */- remindAt: Date;- /**- * Its current schedule, which the edit is diffed against.- *- * Distinct from `remindAt` because a recurring reminder is not its next- * firing: two reminders can come due at the same instant and still be- * different schedules, and only this says which.- */- schedule: ReminderSchedule;- /** Whether the owner has marked it done, which a reschedule has to undo. */- completed: boolean;- /**- * What a blank description falls back to — the name of the entity this- * reminder is about, as creating one would have derived it.- *- * Absent for a standalone reminder, and for a reference whose name is not- * cached; blanking the field then leaves the description alone.- */- fallbackDescription?: string;-}-interface ReminderComposerState {- /** The entity a new reminder is about. Absent when editing. */+ /** The entity a new reminder is about. Absent for a standalone reminder. */entity?: EntityData;- /** The reminder being edited. Absent when creating. */- editing?: ReminderDraft;/*** A new reminder about nothing at all.*- * Its own flag rather than the absence of the other two: "no entity and no- * draft" is how a closed composer looks, so without this the modal cannot- * tell a standalone reminder from nothing to compose.+ * Its own flag rather than the absence of an entity: "no entity" is also how+ * a closed composer looks, so without this the modal cannot tell a standalone+ * reminder from nothing to compose.*/standalone?: boolean;}@@ -81,16 +44,14 @@ export function takeReminderCreatedHandler():const [state, setState] = createStore<ReminderComposerState>({entity: undefined,- editing: undefined,standalone: undefined,});/*** Open the composer to create a reminder about an entity.*- * There is only one thing left to ask: when. The entity is whatever the command- * was invoked on and the description is derived from it, so the composer opens- * straight onto the date list.+ * The composer opens on the form with the entity named at the top; the+ * description is optional and derived from the entity when left blank.*/export function openReminderComposer(entity: EntityData,@@ -100,7 +61,7 @@ export function openReminderComposer(// Batched so the modal's open-keyed effect sees this entity rather than the// previous one.batch(() => {- setState(reconcile({ entity, editing: undefined, standalone: undefined }));+ setState(reconcile({ entity, standalone: undefined }));setReminderComposerOpen(true);});}@@ -108,38 +69,15 @@ export function openReminderComposer(/*** Open the composer to create a reminder about nothing.*- * There is no entity to name it after, so the description step it opens on is- * the one thing it cannot skip — see `resolveStandaloneDescription`.+ * There is no entity to name it after, so its description is the one field it+ * cannot skip — see `resolveStandaloneDescription`.*/export function openStandaloneReminderComposer(options?: {onCreated?: ReminderCreatedHandler;}) {createdHandler = options?.onCreated;batch(() => {- setState(- reconcile({ entity: undefined, editing: undefined, standalone: true })- );- setReminderComposerOpen(true);- });-}--/**- * Open the composer to edit an existing reminder.- *- * The same two steps as creating one, prefilled: the description step starts- * from what the reminder says, and the date step leads with keeping its current- * time so a rename does not force a new date to be picked.- */-export function openReminderEditor(reminder: ReminderDraft) {- createdHandler = undefined;- batch(() => {- setState(- reconcile({- entity: undefined,- editing: reminder,- standalone: undefined,- })- );+ setState(reconcile({ entity: undefined, standalone: true }));setReminderComposerOpen(true);});}@@ -148,13 +86,7 @@ export function closeReminderComposer() {createdHandler = undefined;batch(() => {setReminderComposerOpen(false);- setState(- reconcile({- entity: undefined,- editing: undefined,- standalone: undefined,- })- );+ setState(reconcile({ entity: undefined, standalone: undefined }));});}diff --git a/apps/web/src/features/reminders/reminder-schedule.test.ts b/apps/web/src/features/reminders/reminder-schedule.test.tsindex ddf9629f88..dbb5490555 100644--- a/apps/web/src/features/reminders/reminder-schedule.test.ts+++ b/apps/web/src/features/reminders/reminder-schedule.test.ts@@ -1,20 +1,16 @@-import type { DateOption } from '@core/util/dateSearch/useDateSearch';import type { EntityData } from '@entity';import { describe, expect, it } from 'vitest';import {- defaultRepeatParts,describeReminderSchedule,- futureDateOptions,+ describeReminderWhen,isRecurring,onceSchedule,REMINDER_DEFAULT_TIME,REMINDER_DESCRIPTION_MAX_LENGTH,recurringSchedule,- reminderDefaultOptions,reminderDescriptionFor,reminderDescriptionForReference,- reminderEditOptions,reminderEditPatch,repeatPartsFromDate,repeatPartsFromSchedule,@@ -24,41 +20,6 @@ import {sameSchedule,} from './reminder-schedule';-const option = (id: string, date: Date): DateOption => ({- id,- displayText: id,- date,- type: 'preset',-});--describe('futureDateOptions', () => {- const now = new Date('2026-07-29T12:00:00.000Z');-- it('keeps options after now and drops ones already past', () => {- const kept = option('later', new Date('2026-07-30T09:00:00.000Z'));- const dropped = option('earlier', new Date('2026-07-28T09:00:00.000Z'));-- expect(futureDateOptions([dropped, kept], now)).toEqual([kept]);- });-- // The API rejects a remindAt that is not strictly in the future, so an option- // landing exactly on "now" has to go too.- it('drops an option exactly at now', () => {- expect(futureDateOptions([option('now', new Date(now))], now)).toEqual([]);- });-- it('preserves the order of the options it keeps', () => {- const first = option('first', new Date('2026-07-30T09:00:00.000Z'));- const second = option('second', new Date('2026-07-31T09:00:00.000Z'));- const past = option('past', new Date('2026-07-01T09:00:00.000Z'));-- expect(futureDateOptions([first, past, second], now)).toEqual([- first,- second,- ]);- });-});-describe('onceSchedule', () => {it('builds a one-shot schedule at the given instant', () => {const date = new Date('2026-07-30T13:00:00.000Z');@@ -70,83 +31,6 @@ describe('onceSchedule', () => {});});-describe('reminderDefaultOptions', () => {- // A Wednesday afternoon, so every entry is still ahead of "now".- const wednesdayAfternoon = new Date(2026, 6, 29, 16, 37, 52, 400);-- it('offers the four reminder defaults in order', () => {- expect(- reminderDefaultOptions(wednesdayAfternoon).map((o) => o.displayText)- ).toEqual(['In 1 hour', 'In 2 hours', 'Tomorrow', 'In 1 week']);- });-- it('offsets the hour entries from now, keeping the time of day', () => {- const [oneHour, twoHours] = reminderDefaultOptions(wednesdayAfternoon);-- expect(oneHour.date.getHours()).toBe(17);- expect(oneHour.date.getMinutes()).toBe(37);- expect(twoHours.date.getHours()).toBe(18);- expect(twoHours.date.getMinutes()).toBe(37);- });-- // Seconds dropped so the stored instant is a whole minute.- it('rounds the hour entries down to the minute', () => {- const hourEntries = reminderDefaultOptions(wednesdayAfternoon).slice(0, 2);-- for (const option of hourEntries) {- expect(option.date.getSeconds()).toBe(0);- expect(option.date.getMilliseconds()).toBe(0);- }- });-- it('puts the day-scale entries at the default time', () => {- for (const option of reminderDefaultOptions(wednesdayAfternoon).slice(2)) {- expect(option.date.getHours()).toBe(REMINDER_DEFAULT_TIME.hours);- expect(option.date.getMinutes()).toBe(REMINDER_DEFAULT_TIME.minutes);- }- });-- it('dates the day-scale entries a day and a week out', () => {- const [, , tomorrow, oneWeek] = reminderDefaultOptions(wednesdayAfternoon);-- expect(tomorrow.date.getDate()).toBe(30);- expect(oneWeek.date.getDate()).toBe(5);- });-- // No two presets can currently land on the same instant, so this guards the- // list as it grows rather than a case it has today.- it('never offers the same instant under two labels', () => {- for (const now of [- new Date(2026, 7, 1, 13, 0, 0),- new Date(2026, 7, 2, 20, 0, 0),- wednesdayAfternoon,- ]) {- const options = reminderDefaultOptions(now);- expect(new Set(options.map((o) => o.date.getTime())).size).toBe(- options.length- );- }- });-- // The API rejects a firing that is not strictly in the future, and every- // preset is now offset forward from `now` — so this holds whenever it runs.- it('only ever offers times in the future', () => {- for (const now of [new Date(2026, 7, 2, 23, 59, 0), wednesdayAfternoon]) {- for (const option of reminderDefaultOptions(now)) {- expect(option.date.getTime()).toBeGreaterThan(now.getTime());- }- }- });-- it('describes each entry with a concrete date and time', () => {- const [oneHour] = reminderDefaultOptions(wednesdayAfternoon);-- // Matched rather than compared: the time is rendered with the runtime- // locale's hour cycle, so an exact string pins the test to en-US.- expect(oneHour.secondaryText).toMatch(/^Today, \d{1,2}:\d{2}/);- });-});-describe('reminderDescriptionFor', () => {const named = (type: EntityData['type'], name: string) =>({ type, id: 'e1', name }) as EntityData;@@ -326,50 +210,6 @@ describe('REMINDER_DEFAULT_TIME', () => {});});-describe('reminderEditOptions', () => {- // A Wednesday afternoon, so every default entry is still ahead of "now".- const wednesdayAfternoon = new Date(2026, 6, 29, 16, 37, 52, 400);- const current = new Date(2026, 7, 3, 9, 0, 0, 0);-- it('leads with keeping the current time, then the defaults', () => {- expect(- reminderEditOptions(current, wednesdayAfternoon).map((o) => o.displayText)- ).toEqual([- 'Keep current time',- 'In 1 hour',- 'In 2 hours',- 'Tomorrow',- 'In 1 week',- ]);- });-- it('keeps the exact instant the reminder already has', () => {- const [keep] = reminderEditOptions(current, wednesdayAfternoon);-- expect(keep.date.getTime()).toBe(current.getTime());- });-- // Both would submit the same instant, so offering them separately would read- // as two different choices with one outcome.- it('drops a default that lands on the current time', () => {- const tomorrowMorning = new Date(2026, 6, 30, 9, 0, 0, 0);- const options = reminderEditOptions(tomorrowMorning, wednesdayAfternoon);-- expect(options.map((o) => o.displayText)).not.toContain('Tomorrow');- expect(options[0].displayText).toBe('Keep current time');- });-- // An overdue reminder still has to be renamable, and keeping its time sends- // no schedule at all — so the future filter must not remove the keep option.- it('offers keeping a time that has already passed', () => {- const overdue = new Date(2026, 6, 20, 9, 0, 0, 0);- const [keep] = reminderEditOptions(overdue, wednesdayAfternoon);-- expect(keep.displayText).toBe('Keep current time');- expect(keep.date.getTime()).toBe(overdue.getTime());- });-});-describe('reminderEditPatch', () => {const remindAt = new Date('2026-08-09T09:00:00.000Z');const original = {@@ -599,18 +439,6 @@ describe('repeatPartsFromDate', () => {});});-describe('defaultRepeatParts', () => {- it('starts a new recurrence at the reminder morning default', () => {- // Not the current time: a repeat picked at 4pm should still default to the- // morning, the same way a bare date does.- const parts = defaultRepeatParts(new Date('2026-08-17T16:42:00'));-- expect(parts.time).toBe(- `${String(REMINDER_DEFAULT_TIME.hours).padStart(2, '0')}:${String(REMINDER_DEFAULT_TIME.minutes).padStart(2, '0')}`- );- });-});-describe('recurringSchedule', () => {it('builds a cron schedule carrying the timezone it was built in', () => {const schedule = recurringSchedule(@@ -680,6 +508,33 @@ describe('describeReminderSchedule', () => {});});+describe('describeReminderWhen', () => {+ it('reads a one-shot as its firing date and time', () => {+ // Built from local components and formatted in local time, so the string is+ // the same wherever the test runs. The current year keeps it in+ // `formatDateAndTime`'s same-year "MMM d" branch rather than the numeric one.+ const year = new Date().getFullYear();+ expect(+ describeReminderWhen({+ scheduleType: 'once',+ nextRunAt: new Date(year, 7, 10, 9, 0),+ })+ ).toBe('Aug 10, 9:00 AM');+ });++ it('reads a recurring reminder as its cadence, not its next firing', () => {+ const when = describeReminderWhen({+ scheduleType: 'recurring',+ cron: '0 0 9 * * 2-6',+ timezone: 'UTC',+ nextRunAt: new Date(2026, 7, 10, 9, 0),+ });++ expect(when).toMatch(/^Weekdays at /);+ expect(when).not.toContain('Aug');+ });+});+describe('sameSchedule', () => {const cron = (expr: string, timezone = 'UTC') =>({ type: 'recurring', cron: expr, timezone }) as const;diff --git a/apps/web/src/features/reminders/reminder-schedule.ts b/apps/web/src/features/reminders/reminder-schedule.tsindex 98e48add15..fa57a671d5 100644--- a/apps/web/src/features/reminders/reminder-schedule.ts+++ b/apps/web/src/features/reminders/reminder-schedule.ts@@ -1,3 +1,4 @@+import { formatDateAndTime } from '@app/features/entity/utils/timestamp';import {buildCron,type CronParts,@@ -7,14 +8,9 @@ import {parseCron,type ScheduleFrequency,} from '@core/util/cron';-import {- type DateOption,- formatDateWithContext,-} from '@core/util/dateSearch/useDateSearch';import type { EntityData } from '@entity';import type { ReminderSchedule } from '@service-storage/generated/schemas/reminderSchedule';import type { UpdateReminderRequest } from '@service-storage/generated/schemas/updateReminderRequest';-import { addDays, addHours, addWeeks } from 'date-fns';/*** The time of day a bare date resolves to.@@ -28,20 +24,6 @@ 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;-/**- * Drop options that have already passed.- *- * The API rejects a `remindAt` in the past, and the date search happily returns- * past dates for a typed query ("yesterday", or a month already gone by). The- * no-query preset list filters itself; this covers everything else.- */-export function futureDateOptions(- options: readonly DateOption[],- now: Date-): DateOption[] {- return options.filter((option) => option.date.getTime() > now.getTime());-}-/** A one-shot schedule firing at `date`. */export function onceSchedule(date: Date): ReminderSchedule {return { type: 'once', remindAt: date.toISOString() };@@ -96,14 +78,6 @@ export function repeatPartsFromDate(};}-/**- * What the repeat picker starts from for a brand-new recurrence: weekly on- * today, at the same morning time a bare date would resolve to.- */-export function defaultRepeatParts(now: Date = new Date()): CronParts {- return repeatPartsFromDate(atDefaultTime(now));-}-/*** The schedule a soup row is on, rebuilt as the tagged union the API speaks.*@@ -134,6 +108,26 @@ export function scheduleFromRow(row: {return { type: 'once', remindAt: new Date(row.nextRunAt).toISOString() };}+/**+ * When a reminder next comes due, as one line for a row to show.+ *+ * A recurring reminder reads as its cadence ("Every weekday at 9:00 AM"), which+ * is what says it fires again at all; a one-shot reads as the single instant it+ * fires, date and time together. Both answer "when?" without repeating what the+ * recurrence badge beside them already says.+ */+export function describeReminderWhen(row: {+ scheduleType: 'once' | 'recurring';+ cron?: string;+ timezone?: string;+ nextRunAt: string | Date;+}): string {+ return (+ describeReminderSchedule(scheduleFromRow(row)) ??+ formatDateAndTime(row.nextRunAt)+ );+}+/** Whether a schedule repeats, narrowed for the caller. */export function isRecurring(schedule: ReminderSchedule@@ -196,104 +190,6 @@ export function sameSchedule(return false;}-/** The same instant, at `REMINDER_DEFAULT_TIME`. */-function atDefaultTime(date: Date): Date {- const result = new Date(date);- result.setHours(- REMINDER_DEFAULT_TIME.hours,- REMINDER_DEFAULT_TIME.minutes,- 0,- 0- );- return result;-}--/** The same instant, with seconds dropped. */-function toWholeMinute(date: Date): Date {- const result = new Date(date);- result.setSeconds(0, 0);- return result;-}--/**- * What the reminder picker offers before anything is typed.- *- * Deliberately not the shared `searchPresets` list, which is built for due dates- * — it leads with "Today"/"Yesterday" and every entry lands on `endOfDay`.- * Typing still goes through `useDateSearch`, so the shared presets remain- * reachable by name; this only replaces the resting list.- *- * The hour offsets keep their computed clock time (an "in 1 hour" reminder at- * 9am would be useless); the day-scale ones get the morning default.- */-export function reminderDefaultOptions(now: Date): DateOption[] {- const entries: Array<{ id: string; label: string; date: Date }> = [- {- id: 'in-1-hour',- label: 'In 1 hour',- date: toWholeMinute(addHours(now, 1)),- },- {- id: 'in-2-hours',- label: 'In 2 hours',- date: toWholeMinute(addHours(now, 2)),- },- { id: 'tomorrow', label: 'Tomorrow', date: atDefaultTime(addDays(now, 1)) },- {- id: 'in-1-week',- label: 'In 1 week',- date: atDefaultTime(addWeeks(now, 1)),- },- ];-- // No two of the presets above can currently land on the same instant, but- // they are a list people add to, and two entries offering one time under two- // labels is the kind of thing nobody notices until it ships.- const seen = new Set<number>();- const unique = entries.filter(({ date }) => {- const time = date.getTime();- if (seen.has(time)) return false;- seen.add(time);- return true;- });-- return futureDateOptions(- unique.map(({ id, label, date }) => ({- id,- displayText: label,- secondaryText: formatDateWithContext(date, now, true),- date,- type: 'preset' as const,- })),- now- );-}--/**- * What the picker offers when editing a reminder that already has a time.- *- * "Keep current time" leads, so a rename costs one Enter rather than forcing a- * date to be re-picked. It is the only option exempt from the future filter: an- * overdue reminder still has to be renamable, and keeping its time sends no- * schedule at all — see {@link reminderEditPatch}.- *- * Presets landing on the current time are dropped, or the same instant would be- * offered twice under two labels.- */-export function reminderEditOptions(current: Date, now: Date): DateOption[] {- const keep: DateOption = {- id: 'keep',- displayText: 'Keep current time',- secondaryText: formatDateWithContext(current, now, true),- date: current,- type: 'preset',- };- const rest = reminderDefaultOptions(now).filter(- (option) => option.date.getTime() !== current.getTime()- );- return [keep, ...rest];-}-/*** The patch that turns `original` into `next`, or undefined when they match.*diff --git a/apps/web/src/features/soup/createSoupEntityActions.ts b/apps/web/src/features/soup/createSoupEntityActions.tsindex 2dcad9d9a0..5c22afb4c4 100644--- a/apps/web/src/features/soup/createSoupEntityActions.ts+++ b/apps/web/src/features/soup/createSoupEntityActions.ts@@ -28,7 +28,6 @@ import {import {markReminderSeenOnOpen,openEntityInSplitFromUnifiedList,- reminderSplitTarget,} from '@app/features/next-soup/utils';import { useAnalytics } from '@app/lib/analytics/analytics-context';import { globalSplitManager } from '@app/signal/splitLayout';@@ -230,12 +229,14 @@ export function createSoupEntityActions(): {if (!entity || entity.type === 'foreign') return undefined;const splitManager = globalSplitManager();if (!splitManager) return undefined;- // A reminder opens what it references. A standalone one references- // nothing, so there is nothing to open.+ // A reminder opens its own editor — a `reminder-view` component split —+ // not what it references, so a standalone reminder is openable too and+ // the dedup check is against that editor split, not the reference.if (entity.type === 'reminder') {- const target = reminderSplitTarget(entity);- if (!target) return undefined;- const open = splitManager.getSplitByContent(target.type, target.id);+ const open = splitManager.getSplitByContent(+ 'component',+ `reminder-view~${entity.id}`+ );if (open && open.id !== splitHandle?.viewerId()) return undefined;return entity;}@@ -386,12 +387,14 @@ export function createSoupEntityActions(): {}if (entities.length === 1) {- middleItems.push({- id: 'copy-link',- label: 'Copy Link',- hotkeyToken: TOKENS.entity.action.copyLink,- onClick: handle(copyLinkAction.executeWithSoup),- });+ if (copyLinkAction.canExecute(entities[0])) {+ middleItems.push({+ id: 'copy-link',+ label: 'Copy Link',+ hotkeyToken: TOKENS.entity.action.copyLink,+ onClick: handle(copyLinkAction.executeWithSoup),+ });+ }if (copyBranchNameAction.canExecute(entities[0])) {middleItems.push({