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(calendar): finish the join-request notification lifecycle (#9260)
gbirman380e96ec7c62
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 00d292fb74..9e4cdd4299 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -449,8 +449,8 @@ resolved session ID; keep the existing `AgentSessionProvider` subscription to[calendar walkthrough](../../docs/agent-guide/calendar.md).- Mark loaded calendar and agent-session row notifications through thenotification source (`markRowNotificationsSeenOnOpen`) so read dots update- immediately and failed writes roll back; calendar grid selections also mark- the canonical event read, excluding team projections.+ immediately and failed writes roll back; calendar grid selections and links+ to an event also mark the canonical event read, excluding team projections.- Route explicit meeting-page exits using the server's `callEnded` result: endedcalls open their record; ongoing channel and scheduled calls return to thechannel and Calendar. Leaving from a channel's Call tab stays in the channel. Preserve the session ID and send the server leave before mediadiff --git a/apps/web/src/features/calendar-view/calendar-view.test.tsx b/apps/web/src/features/calendar-view/calendar-view.test.tsxnew file mode 100644index 0000000000..53a2e76771--- /dev/null+++ b/apps/web/src/features/calendar-view/calendar-view.test.tsx@@ -0,0 +1,173 @@+/**+ * @vitest-environment jsdom+ */++import { cleanup, render } from '@solidjs/testing-library';+import type { JSX } from 'solid-js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ markRead: vi.fn(async () => {}),+ setSearch: vi.fn(),+ notificationSource: { id: 'notification-source' },+ focusEvent: (_eventId: string | undefined) => {},+ isInlinePreview: false,+ contentParams: undefined as Record<string, unknown> | undefined,+ searchEventId: '',+}));++vi.mock('@app/features/calendar/components/CalendarViewContext', () => ({+ CalendarViewContextProvider: (props: {+ onFocusedEventIdChange: (eventId: string | undefined) => void;+ children: JSX.Element;+ }) => {+ mocks.focusEvent = props.onFocusedEventIdChange;+ return props.children;+ },+}));+vi.mock('@app/features/calendar/hooks/use-calendar-ui-flag', () => ({+ useCalendarUiFlag: () => () => true,+}));+vi.mock('@app/features/calendar/utils/calendar-supported-range', () => ({+ isCalendarRangeSupported: () => true,+}));+vi.mock('@app/lib/analytics/analytics-context', () => ({+ useAnalytics: () => ({ pageView: vi.fn(), track: vi.fn() }),+}));+vi.mock('@app/lib/analytics/posthog', () => ({+ usePosthog: () => ({ flagsLoaded: () => true }),+}));+vi.mock('@app/lib/split-router', () => ({+ createSearchParams: () => [+ {+ eventId: mocks.searchEventId,+ occurrenceKey: '',+ startDate: '',+ endDate: '',+ },+ mocks.setSearch,+ ],+ createSearchParamsCodec: () => ({ serialize: () => ({}) }),+ useNavigate: () => vi.fn(),+ useParams: () => ({ period: 'timeGridWeek' }),+}));+vi.mock('@components/app/GlobalAppState', () => ({+ useGlobalNotificationSource: () => mocks.notificationSource,+}));+vi.mock('@components/app/split-layout/layoutUtils', () => ({+ useSplitPanelOrThrow: () => ({+ isInlinePreview: mocks.isInlinePreview,+ handle: {+ content: () => ({+ type: 'component',+ id: 'calendar',+ params: mocks.contentParams,+ }),+ },+ }),+}));+vi.mock('@core/context/user', () => ({ useUserId: () => () => 'viewer' }));+vi.mock('@notifications/notification-helpers', () => ({+ markNotificationsForEntityAsRead: mocks.markRead,+}));+vi.mock('@queries/calendar/occurrences', () => ({+ useCalendarOccurrencesQuery: () => ({}),+}));+vi.mock('./calendar-focus-target', () => ({+ CalendarFocusContextProvider: (props: { children: JSX.Element }) =>+ props.children,+}));+vi.mock('./calendar-target', () => ({+ createCalendarFocusTarget: () => () => undefined,+}));+vi.mock('./calendar-target-request', () => ({+ createCalendarTargetAim: () => ({+ target: () => undefined,+ aimAt: vi.fn(),+ }),+}));+vi.mock('./calendar-view-skeleton', () => ({+ CalendarViewSkeleton: () => null,+}));+vi.mock('./components/Workspace', () => ({ Workspace: () => null }));++import { CalendarView } from './calendar-view';++function openCalendar() {+ render(() => <CalendarView route={{ id: 'view-calendar' }} />);+}++beforeEach(() => {+ mocks.markRead.mockClear();+ mocks.setSearch.mockClear();+ mocks.isInlinePreview = false;+ mocks.contentParams = undefined;+ mocks.searchEventId = '';+});++afterEach(cleanup);++describe('marking an event read when Calendar lands on it', () => {+ it('marks the event a link opened, keeping the link in the URL', () => {+ mocks.searchEventId = 'event';+ openCalendar();++ mocks.focusEvent('event');++ expect(mocks.markRead).toHaveBeenCalledExactlyOnceWith(+ mocks.notificationSource,+ { type: 'calendar_event', id: 'event' }+ );+ expect(mocks.setSearch).not.toHaveBeenCalled();+ });++ it('leaves the read to the row that opened the event', () => {+ mocks.searchEventId = 'event';+ mocks.contentParams = { eventId: 'event', focusRequestId: 1 };+ openCalendar();++ mocks.focusEvent('event');++ expect(mocks.markRead).not.toHaveBeenCalled();+ });++ it("leaves the read to Home's row in its inline calendar", () => {+ mocks.searchEventId = 'event';+ mocks.isInlinePreview = true;+ openCalendar();++ mocks.focusEvent('event');++ expect(mocks.markRead).not.toHaveBeenCalled();+ });++ it('marks the copy a link resolved to and names it in the URL', () => {+ mocks.searchEventId = 'another-copy';+ openCalendar();++ mocks.focusEvent('own-copy');++ expect(mocks.markRead).toHaveBeenCalledExactlyOnceWith(+ mocks.notificationSource,+ { type: 'calendar_event', id: 'own-copy' }+ );+ expect(mocks.setSearch).toHaveBeenCalledWith(+ { eventId: 'own-copy' },+ { mode: 'replace', history: 'replace' }+ );+ });++ it('marks each event selected after the landing', () => {+ mocks.searchEventId = 'event';+ mocks.contentParams = { eventId: 'event', focusRequestId: 1 };+ openCalendar();+ mocks.focusEvent('event');++ mocks.focusEvent('next-event');++ expect(mocks.markRead).toHaveBeenCalledExactlyOnceWith(+ mocks.notificationSource,+ { type: 'calendar_event', id: 'next-event' }+ );+ });+});diff --git a/apps/web/src/features/calendar-view/calendar-view.tsx b/apps/web/src/features/calendar-view/calendar-view.tsxindex 4c0cfc41c7..4d5c5a2591 100644--- a/apps/web/src/features/calendar-view/calendar-view.tsx+++ b/apps/web/src/features/calendar-view/calendar-view.tsx@@ -185,25 +185,34 @@ export function CalendarView(props: CalendarViewProps) {occurrencesQuery);+ const markEventRead = (eventId: string) => {+ fireAndForget(+ markNotificationsForEntityAsRead(notificationSource, {+ type: 'calendar_event',+ id: eventId,+ }),+ 'calendar-notification-read'+ );+ };+const setFocusedEventId = (eventId: string | undefined) => {const next = eventId ?? '';if (aimingEventId !== undefined) {if (!next) return;const landed = next === aimingEventId;aimingEventId = undefined;- // List activation already marks its row; landing must not send a second- // overlapping read write that could interfere with optimistic rollback.- if (landed) return;- }- if (eventId) {- fireAndForget(- markNotificationsForEntityAsRead(notificationSource, {- type: 'calendar_event',- id: eventId,- }),- 'calendar-notification-read'- );+ if (landed) {+ // List activation already marks its row; landing must not send a second+ // overlapping read write that could interfere with optimistic rollback.+ // A link has no row behind it, so its landing marks the event instead.+ const openedByLink =+ !panel.isInlinePreview &&+ contentTarget().focusRequestId === undefined;+ if (openedByLink) markEventRead(next);+ return;+ }}+ if (eventId) markEventRead(eventId);// Inline, a dismissed popover is not a destination change: the host's// selection still names this event, and clearing it would make the next// request for the same event a navigation.diff --git a/crates/calendar_events/AGENTS.md b/crates/calendar_events/AGENTS.mdindex 8ad347a8ea..f73e5f8304 100644--- a/crates/calendar_events/AGENTS.md+++ b/crates/calendar_events/AGENTS.md@@ -189,18 +189,23 @@ reminder dispatch, team availability, and provider/Postgres persistence.domain retires the sharer's notification: opening the event marks it seen,a trigger on `calendar_event_join_requests` running`delete_answered_join_request_notification` deletes it when anyone answers- the request, and two triggers on `calendar_events` running- `delete_calendar_event_join_request_notifications` delete it with the event- row, or when the row turns `cancelled` (Outlook can keep a cancelled- meeting). That covers the ways a copy goes away listed for channel grants- above, and each delete reaches open clients through+ the request, a second there running+ `delete_removed_join_request_notification` deletes it with the request row,+ which the requester's account deletion cascades away, and two triggers on+ `calendar_events` running `delete_calendar_event_join_request_notifications`+ delete it with the event row, or when the row turns `cancelled` (Outlook can+ keep a cancelled meeting). That covers the ways a copy goes away listed for+ channel grants above, and each delete reaches open clients through`trg_notify_user_notification_deletes`. An event can hold several open- requests, so the answer's trigger matches the `requestId` in the notification's- metadata, not the event alone. The notifier only queues, so a backlog can- deliver a notification after that cleanup; a `notification` insert trigger- skips it while the event is gone or cancelled or the request is no longer- pending, locking the event and then the request to decide in order with a- change in flight. The cancelled row keeps its requests, as it keeps its+ requests, so the triggers on the request row match the `requestId` in the+ notification's metadata, not the event alone. The notifier only queues, so a+ backlog can deliver a notification after that cleanup; a `notification`+ insert trigger skips it while the event is gone or cancelled or the request+ is no longer pending, locking the event and then the request to decide in+ order with a change in flight. Deleting an event reaches both delete cleanups+ in one transaction, and whichever runs first leaves nothing for the other.+ Both lock only `notification` rows, once the delete holds its row, so neither+ changes that order. The cancelled row keeps its requests, as it keeps itsgrants, and a cancelled occurrence changes neither.- Calendar mentions reach the agent as document mentions (`blockName``calendar`), but `ReadContent` and `ReadMetadata` need document access, whichdiff --git a/crates/calendar_events/src/outbound/pg/test/join_requests.rs b/crates/calendar_events/src/outbound/pg/test/join_requests.rsindex ab82db7f50..4e97f48100 100644--- a/crates/calendar_events/src/outbound/pg/test/join_requests.rs+++ b/crates/calendar_events/src/outbound/pg/test/join_requests.rs@@ -815,3 +815,186 @@ async fn an_answer_waits_for_a_queued_insert_then_retires_it(pool: PgPool) {assert!(answering.await.unwrap().unwrap().is_some());assert_eq!(stored_notifications(&pool).await, 0);}++/// The statement `delete_user` runs, which cascades the user's requests away.+async fn delete_account(+ executor: impl sqlx::PgExecutor<'_>,+ user_id: &str,+) -> Result<(), sqlx::Error> {+ sqlx::query!(r#"DELETE FROM "User" WHERE id = $1"#, user_id)+ .execute(executor)+ .await+ .map(|_| ())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn deleting_the_requesters_account_retires_their_requests_notification(pool: PgPool) {+ let removed = open_request(&pool).await;+ let still_open = another_open_request(&pool, &removed).await;+ let delegate_id = "macro|[email protected]";+ insert_user(&pool, delegate_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let about_removed =+ insert_join_request_notification(&pool, &removed, &[SHARER_ID, delegate_id]).await;+ let about_still_open = insert_join_request_notification(&pool, &still_open, &[SHARER_ID]).await;+ let reminder = store_notification(+ &pool,+ "calendar_event_reminder",+ removed.event_id,+ serde_json::json!({}),+ &[SHARER_ID],+ )+ .await;+ let mut listener = PgListener::connect_with(&pool).await.unwrap();+ listener.listen("notification_events").await.unwrap();++ delete_account(&pool, MEMBER_ID).await.unwrap();++ assert_eq!(repo.get_join_request(removed.id).await.unwrap(), None);+ assert!(!recipient_holds(&pool, about_removed).await);+ let mut published = published_delete(&mut listener).await;+ assert_eq!(+ published["notificationId"],+ serde_json::json!(about_removed)+ );+ let recipients = published["userIds"].as_array_mut().unwrap();+ recipients.sort_by_key(ToString::to_string);+ assert_eq!(+ *recipients,+ vec![serde_json::json!(delegate_id), serde_json::json!(SHARER_ID)]+ );++ assert!(recipient_holds(&pool, about_still_open).await);+ assert!(recipient_holds(&pool, reminder).await);+ assert_eq!(+ repo.list_pending_join_requests(removed.event_id)+ .await+ .unwrap(),+ std::slice::from_ref(&still_open)+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn deleting_the_event_retires_each_join_request_notification_once(pool: PgPool) {+ let first = open_request(&pool).await;+ let second = another_open_request(&pool, &first).await;+ let event_id = first.event_id;+ let about_first = insert_join_request_notification(&pool, &first, &[SHARER_ID]).await;+ let about_second = insert_join_request_notification(&pool, &second, &[SHARER_ID]).await;+ let mut listener = PgListener::connect_with(&pool).await.unwrap();+ listener.listen("notification_events").await.unwrap();++ sqlx::query!("DELETE FROM calendar_events WHERE id = $1", event_id)+ .execute(&pool)+ .await+ .unwrap();+ assert_eq!(stored_notifications(&pool).await, 0);++ let mut retired = vec![+ published_delete(&mut listener).await["notificationId"].clone(),+ published_delete(&mut listener).await["notificationId"].clone(),+ ];+ retired.sort_by_key(ToString::to_string);+ let mut expected = vec![+ serde_json::json!(about_first),+ serde_json::json!(about_second),+ ];+ expected.sort_by_key(ToString::to_string);+ assert_eq!(retired, expected);++ // Sent after the delete, so a third publish would arrive ahead of it.+ sqlx::query!(r#"SELECT pg_notify('notification_events', '{"marker":true}')"#)+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(+ published_delete(&mut listener).await,+ serde_json::json!({ "marker": true })+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_queued_insert_waits_for_an_account_delete_then_stores_nothing(pool: PgPool) {+ let request = open_request(&pool).await;+ let mut deleting = pool.begin().await.unwrap();+ let blocker = backend_pid(&mut deleting).await;+ delete_account(&mut *deleting, MEMBER_ID).await.unwrap();++ let arriving = tokio::spawn({+ let pool = pool.clone();+ let request = request.clone();+ async move { ingress_insert(&pool, &request).await }+ });+ wait_for_blocked_transaction(&pool, blocker).await;+ deleting.commit().await.unwrap();++ assert!(!arriving.await.unwrap().unwrap());+ assert_eq!(stored_notifications(&pool).await, 0);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_queued_insert_is_stored_when_the_account_delete_it_waited_for_rolls_back(pool: PgPool) {+ let request = open_request(&pool).await;+ let mut deleting = pool.begin().await.unwrap();+ let blocker = backend_pid(&mut deleting).await;+ delete_account(&mut *deleting, MEMBER_ID).await.unwrap();++ let arriving = tokio::spawn({+ let pool = pool.clone();+ let request = request.clone();+ async move { ingress_insert(&pool, &request).await }+ });+ wait_for_blocked_transaction(&pool, blocker).await;+ deleting.rollback().await.unwrap();++ assert!(arriving.await.unwrap().unwrap());+ assert_eq!(stored_notifications(&pool).await, 1);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn an_account_delete_waits_for_a_queued_insert_then_retires_it(pool: PgPool) {+ let request = open_request(&pool).await;+ let mut arriving = pool.begin().await.unwrap();+ let blocker = backend_pid(&mut arriving).await;+ assert!(ingress_insert(&mut *arriving, &request).await.unwrap());++ let deleting = tokio::spawn({+ let pool = pool.clone();+ async move { delete_account(&pool, MEMBER_ID).await }+ });+ wait_for_blocked_transaction(&pool, blocker).await;+ arriving.commit().await.unwrap();++ deleting.await.unwrap().unwrap();+ assert_eq!(stored_notifications(&pool).await, 0);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn an_event_delete_waits_for_an_account_delete_and_both_retire_once(pool: PgPool) {+ let request = open_request(&pool).await;+ let event_id = request.event_id;+ let asked = insert_join_request_notification(&pool, &request, &[SHARER_ID]).await;+ let mut listener = PgListener::connect_with(&pool).await.unwrap();+ listener.listen("notification_events").await.unwrap();+ let mut deleting_account = pool.begin().await.unwrap();+ let blocker = backend_pid(&mut deleting_account).await;+ delete_account(&mut *deleting_account, MEMBER_ID)+ .await+ .unwrap();++ let deleting_event = tokio::spawn({+ let pool = pool.clone();+ async move {+ sqlx::query!("DELETE FROM calendar_events WHERE id = $1", event_id)+ .execute(&pool)+ .await+ }+ });+ wait_for_blocked_transaction(&pool, blocker).await;+ deleting_account.commit().await.unwrap();++ deleting_event.await.unwrap().unwrap();+ assert_eq!(stored_notifications(&pool).await, 0);+ let published = published_delete(&mut listener).await;+ assert_eq!(published["notificationId"], serde_json::json!(asked));+}diff --git a/crates/macro_db_client/migrations/20261031034808_calendar_event_join_request_removed_notification_cleanup.sql b/crates/macro_db_client/migrations/20261031034808_calendar_event_join_request_removed_notification_cleanup.sqlnew file mode 100644index 0000000000..fe14fa50cb--- /dev/null+++ b/crates/macro_db_client/migrations/20261031034808_calendar_event_join_request_removed_notification_cleanup.sql@@ -0,0 +1,46 @@+-- A join request's notification goes when the request does.+--+-- Deleting the requester's account cascades their requests away and left each+-- one's notification behind: the sharer kept a row, eligible for the digest+-- email, about a request the event no longer lists. As in+-- calendar_event_join_request_answer_notification_cleanup, the cleanup lives on+-- the request row, picks the notification by the requestId in its metadata,+-- since an event can hold several open requests, and deletes rather than marks,+-- which reaches every recipient's open clients and takes it out of a pending+-- digest.+--+-- No code deletes a request; two cascades do. Deleting the event reaches this+-- row too, inside the transaction where+-- calendar_event_join_request_notification_cleanup deletes the same+-- notifications. Whichever runs first leaves nothing for the other, so each+-- notification is deleted and published once.+--+-- This changes no lock order. The trigger runs once the delete holds the request+-- and locks only notification rows, which the insert guard never waits on: the+-- guard takes the event and then the request, as an event delete does, and an+-- account delete takes the request alone, because a requester never owns the+-- event they ask to join. A queued insert behind the delete finds no request and+-- is skipped. A delete behind a queued insert waits for it to commit, then finds+-- the row it stored. The function reads notification only when it runs, so this+-- locks nothing but the small request table.++SET LOCAL lock_timeout = '5s';++CREATE FUNCTION delete_removed_join_request_notification()+ RETURNS TRIGGER+ LANGUAGE PLPGSQL+ AS+$$+ BEGIN+ DELETE FROM notification+ WHERE event_item_type = 'calendar_event'+ AND event_item_id = OLD.event_id::text+ AND notification_event_type = 'calendar_event_join_request'+ AND metadata->>'requestId' = OLD.id::text;+ RETURN NULL;+ END;+$$;++CREATE TRIGGER calendar_event_join_request_removed_notification_cleanup+ AFTER DELETE ON calendar_event_join_requests+ FOR EACH ROW EXECUTE FUNCTION delete_removed_join_request_notification();diff --git a/crates/model_notifications/src/metadata/calendar_join_request.rs b/crates/model_notifications/src/metadata/calendar_join_request.rsindex 29b232734f..6061f192da 100644--- a/crates/model_notifications/src/metadata/calendar_join_request.rs+++ b/crates/model_notifications/src/metadata/calendar_join_request.rs@@ -39,7 +39,8 @@ impl NotificationTitle for CalendarEventJoinRequestMetadata {}impl NotificationExtIos for CalendarEventJoinRequestMetadata {type NotifData = PushNotificationData;- // A request reopened after a decline replaces its earlier banner.+ // A redelivered notification replaces its own banner, and each person's+ // request keeps a banner of its own.fn collapse_key(&self, _entity: &Entity<'_>) -> NotifCollapseKey {NotifCollapseKey::new(Self::TYPE_NAME).append(&self.request_id.to_string())}diff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.mdindex 1995d087e1..33026b88b1 100644--- a/docs/agent-guide/calendar.md+++ b/docs/agent-guide/calendar.md@@ -136,8 +136,10 @@ opened event is reflected in the pane-owned `sN.calendar.eventId` search parametOpening a calendar row in Home clears its loaded reminder dots immediately;failed read writes restore them. Opening event details directly from the grid-also marks the event's notifications read. Verify both on desktop and mobile,-including a delayed read response and a failed write followed by another click.+or by a link to the event also marks the event's notifications read, a join+request's included: seen is not answered, so the row stays listed until the+request is settled. Verify these on desktop and mobile, including a delayed read+response and a failed write followed by another click.Period selection updates its label and route immediately. The active grid redrawson a deferred task; hidden neighboring periods follow on separate tasks. Calendar@@ -886,9 +888,10 @@ the requester nothing, but their card then reads `Declined` and `The person whodeclined your request to join.` with no `Ask to join`, and offers `Add to calendar` again. Adeclined request stands: the server refuses another ask with 409 `request_declined`, so thesharer is asked only once. The notification goes when the request is answered, by whoever answers-it and however they do, leaving the notifications of other requests on the event, and when the-event goes (deleted in Macro, deleted or cancelled in Google or Outlook, its calendar or inbox-removed); deleting one occurrence of a series leaves it, since the sharer can still add the guest.+it and however they do, leaving the notifications of other requests on the event, when the+requester's account is deleted, and when the event goes (deleted in Macro, deleted or cancelled in+Google or Outlook, its calendar or inbox removed); deleting one occurrence of a series leaves it,+since the sharer can still add the guest.A classic `@Macro` reply thatmentions an event does not shareit by posting the chip. It asks whether to share with the channel, and a yes in that thread