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): keep open join requests current when answered elsewhere (#9263)
gbirmandd3c98c6a109
diff --git a/apps/web/src/features/calendar-view/components/EventJoinRequests.test.tsx b/apps/web/src/features/calendar-view/components/EventJoinRequests.test.tsxindex 4106498379..457f87e17e 100644--- a/apps/web/src/features/calendar-view/components/EventJoinRequests.test.tsx+++ b/apps/web/src/features/calendar-view/components/EventJoinRequests.test.tsx@@ -2,8 +2,17 @@* @vitest-environment jsdom*/-import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { handleRefreshCalendar } from '@queries/calendar/sync';+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@solidjs/testing-library';+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import { err, ok } from 'neverthrow';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { EventJoinRequests } from './EventJoinRequests';const request = {@@ -15,108 +24,237 @@ const request = {createdAt: '2026-10-22T18:00:00Z',};+const otherRequest = {+ ...request,+ id: 'request-2',+ requesterId: 'macro|[email protected]',+ requesterEmail: '[email protected]',+};+const mocks = vi.hoisted(() => ({- requests: [] as (typeof request)[],- listEnabled: vi.fn(),- respond: vi.fn(),+ list: vi.fn(),+ answer: vi.fn(),success: vi.fn(),failure: vi.fn(),+ alert: vi.fn(),}));+let testQueryClient: QueryClient;+/** What the server holds as pending; answering in a test edits it. */+let pending: (typeof request)[];++vi.mock('@queries/client', () => ({+ get queryClient() {+ return testQueryClient;+ },+}));vi.mock('@core/component/Toast/Toast', () => ({- toast: { success: mocks.success, failure: mocks.failure },+ toast: { success: mocks.success, failure: mocks.failure, alert: mocks.alert },}));vi.mock('@entity/owner/owner-display', () => ({OwnerLabel: (props: { ownerId: string }) => <span>{props.ownerId}</span>,}));-vi.mock('@queries/calendar/mutations', () => ({- isGuestInviteRefused: (error: unknown) =>- (error as { code?: string }).code === 'guests_cannot_invite',+vi.mock('@queries/calendar/mutations', async () => {+ const { thrownResultErrorHasCode } = await import('@core/util/result');+ return {+ isGuestInviteRefused: (error: unknown) =>+ thrownResultErrorHasCode(error, 'guests_cannot_invite'),+ };+});+vi.mock('@queries/calendar/occurrences', () => ({+ invalidateCalendarOccurrences: vi.fn(),}));-// The answer's transport and invalidation are the query module's; here it-// resolves with whatever `mocks.respond` returns or throws.-vi.mock('@queries/calendar/join-requests', () => ({- useCalendarJoinRequestsQuery: (- _eventId: () => string,- options: () => { enabled: boolean }- ) => {- mocks.listEnabled(options().enabled);- return { isPending: false, data: mocks.requests };- },- useRespondToCalendarJoinRequestMutation: (callbacks?: {- onSuccess?: (answered: typeof request) => void;- onError?: (error: unknown) => void;- }) => ({- isPending: false,- mutate: (args: { request: typeof request; decision: string }) => {- try {- callbacks?.onSuccess?.(mocks.respond(args));- } catch (error) {- callbacks?.onError?.(error);- }- },- }),+vi.mock('@queries/calendar/invitations', () => ({+ invalidateCalendarInvitations: vi.fn(),+}));+vi.mock('@queries/calendar/team-cache', () => ({+ refreshTeamCalendarQueries: vi.fn(),+}));+vi.mock('@service-storage/client', () => ({+ storageServiceClient: { listCalendarEventJoinRequests: mocks.list },+}));+vi.mock('@service-email/client', () => ({+ emailClient: { respondToCalendarJoinRequest: mocks.answer },}));+function renderRequests(canModify = true) {+ return render(() => (+ <QueryClientProvider client={testQueryClient}>+ <EventJoinRequests eventId="shared-event" canModify={canModify} />+ </QueryClientProvider>+ ));+}++const SYNCED = {+ event: 'synced',+ link_id: '019fdd65-dcc1-74fb-a9c6-8162c11c5854',+};++beforeEach(() => {+ testQueryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ pending = [request];+ // Fresh objects, like every parsed response.+ mocks.list.mockImplementation(async () =>+ ok({ requests: pending.map((row) => ({ ...row })) })+ );+});+afterEach(() => {cleanup();vi.clearAllMocks();- mocks.requests = [];+ testQueryClient.clear();});describe('event join requests', () => {- it('adds a requester as a guest', () => {- mocks.requests = [request];- mocks.respond.mockReturnValue({ ...request, status: 'accepted' });- render(() => <EventJoinRequests eventId="shared-event" canModify />);+ it('adds a requester as a guest', async () => {+ mocks.answer.mockImplementation(async () => {+ pending = [];+ return ok({ ...request, status: 'accepted' });+ });+ renderRequests();- expect(screen.getByText('Someone asked to join')).toBeTruthy();+ expect(await screen.findByText('Someone asked to join')).toBeTruthy();expect(screen.getByText('[email protected]')).toBeTruthy();fireEvent.click(screen.getByRole('button', { name: 'Add as guest' }));- expect(mocks.respond).toHaveBeenCalledWith({- request,+ await waitFor(() =>+ expect(mocks.success).toHaveBeenCalledWith(+ 'Invited [email protected]'+ )+ );+ expect(mocks.answer).toHaveBeenCalledWith('request-1', {decision: 'accept',});- expect(mocks.success).toHaveBeenCalledWith(- 'Invited [email protected]'+ await waitFor(() =>+ expect(+ screen.queryByRole('region', { name: 'Requests to join' })+ ).toBeNull());});- it('declines a request', () => {- mocks.requests = [request];- mocks.respond.mockReturnValue({ ...request, status: 'declined' });- render(() => <EventJoinRequests eventId="shared-event" canModify />);+ it('declines a request', async () => {+ mocks.answer.mockImplementation(async () => {+ pending = [];+ return ok({ ...request, status: 'declined' });+ });+ renderRequests();- fireEvent.click(screen.getByRole('button', { name: 'Decline' }));+ fireEvent.click(await screen.findByRole('button', { name: 'Decline' }));- expect(mocks.respond).toHaveBeenCalledWith({- request,+ await waitFor(() =>+ expect(mocks.success).toHaveBeenCalledWith('Declined the request')+ );+ expect(mocks.answer).toHaveBeenCalledWith('request-1', {decision: 'decline',});});- it('explains when the organizer refuses the new guest', () => {- mocks.requests = [request];- mocks.respond.mockImplementation(() => {- throw { code: 'guests_cannot_invite' };+ // The list is open, so the row is still there when someone else's answer+ // gets in first. The server returns the request as that answer left it.+ it.each([+ {+ press: 'Decline',+ status: 'accepted',+ toast: 'Already answered: [email protected] was invited',+ },+ {+ press: 'Add as guest',+ status: 'declined',+ toast: 'Already answered: this request was declined',+ },+ ])(+ 'says $press was too late when the request is already $status',+ async ({ press, status, toast }) => {+ mocks.answer.mockImplementation(async () => {+ pending = [];+ return ok({ ...request, status });+ });+ renderRequests();++ fireEvent.click(await screen.findByRole('button', { name: press }));++ await waitFor(() => expect(mocks.alert).toHaveBeenCalledWith(toast));+ expect(mocks.success).not.toHaveBeenCalled();+ await waitFor(() =>+ expect(+ screen.queryByRole('region', { name: 'Requests to join' })+ ).toBeNull()+ );+ }+ );++ // An acceptance overrules a decline that lands while it writes the+ // invitation, so its own `accepted` is an invitation, not a late press.+ it('reports an acceptance that overruled a decline as the invitation it is', async () => {+ mocks.answer.mockResolvedValue(ok({ ...request, status: 'accepted' }));+ renderRequests();++ fireEvent.click(+ await screen.findByRole('button', { name: 'Add as guest' })+ );++ await waitFor(() =>+ expect(mocks.success).toHaveBeenCalledWith(+ 'Invited [email protected]'+ )+ );+ expect(mocks.alert).not.toHaveBeenCalled();+ });++ it('drops a request answered elsewhere from an open list', async () => {+ pending = [request, otherRequest];+ renderRequests();+ expect(await screen.findByText('2 people asked to join')).toBeTruthy();++ pending = [otherRequest];+ handleRefreshCalendar(SYNCED);++ expect(await screen.findByText('Someone asked to join')).toBeTruthy();+ expect(screen.queryByText('[email protected]')).toBeNull();+ expect(screen.getByText('[email protected]')).toBeTruthy();+ expect(mocks.answer).not.toHaveBeenCalled();+ });++ it('keeps focus on the remaining row when another request leaves', async () => {+ pending = [request, otherRequest];+ renderRequests();+ const [, otherDecline] = await screen.findAllByRole('button', {+ name: 'Decline',});- render(() => <EventJoinRequests eventId="shared-event" canModify />);+ otherDecline?.focus();- fireEvent.click(screen.getByRole('button', { name: 'Add as guest' }));+ pending = [otherRequest];+ handleRefreshCalendar(SYNCED);++ await screen.findByText('Someone asked to join');+ expect(document.activeElement).toBe(otherDecline);+ });++ it('explains when the organizer refuses the new guest', async () => {+ mocks.answer.mockResolvedValue(+ err([{ code: 'guests_cannot_invite', message: 'refused' }])+ );+ renderRequests();++ fireEvent.click(+ await screen.findByRole('button', { name: 'Add as guest' })+ );- expect(mocks.failure).toHaveBeenCalledWith(- "The organizer doesn't let guests invite others"+ await waitFor(() =>+ expect(mocks.failure).toHaveBeenCalledWith(+ "The organizer doesn't let guests invite others"+ ));});- it('neither fetches nor shows requests for someone who cannot change the event', () => {- mocks.requests = [request];- render(() => (- <EventJoinRequests eventId="shared-event" canModify={false} />- ));+ it('neither fetches nor shows requests for someone who cannot change the event', async () => {+ renderRequests(false);+ handleRefreshCalendar(SYNCED);+ await Promise.resolve();- expect(mocks.listEnabled).toHaveBeenCalledWith(false);+ expect(mocks.list).not.toHaveBeenCalled();expect(screen.queryByRole('region', { name: 'Requests to join' })).toBeNull();diff --git a/apps/web/src/features/calendar-view/components/EventJoinRequests.tsx b/apps/web/src/features/calendar-view/components/EventJoinRequests.tsxindex cc4696ec55..c72d8851ad 100644--- a/apps/web/src/features/calendar-view/components/EventJoinRequests.tsx+++ b/apps/web/src/features/calendar-view/components/EventJoinRequests.tsx@@ -3,6 +3,7 @@ import { OwnerLabel } from '@entity/owner/owner-display';import UserPlusIcon from '@icon/system/regular/user-plus.svg';import {type CalendarJoinRequest,+ isAlreadyAnswered,useCalendarJoinRequestsQuery,useRespondToCalendarJoinRequestMutation,} from '@queries/calendar/join-requests';@@ -29,12 +30,21 @@ export function EventJoinRequests(props: {const pending = () => (queryReadyGate(requests) ? requests.data : []);const respond = useRespondToCalendarJoinRequestMutation({- onSuccess: (request) =>+ onSuccess: (request, { decision }) => {+ if (isAlreadyAnswered(request, decision)) {+ toast.alert(+ request.status === 'accepted'+ ? `Already answered: ${request.requesterEmail} was invited`+ : 'Already answered: this request was declined'+ );+ return;+ }toast.success(request.status === 'accepted'? `Invited ${request.requesterEmail}`: 'Declined the request'- ),+ );+ },onError: (error) =>toast.failure(isGuestInviteRefused(error)diff --git a/apps/web/src/lib/queries/calendar/join-requests.ts b/apps/web/src/lib/queries/calendar/join-requests.tsindex 2fd27fa725..6547f1c55b 100644--- a/apps/web/src/lib/queries/calendar/join-requests.ts+++ b/apps/web/src/lib/queries/calendar/join-requests.ts@@ -7,6 +7,7 @@ import { emailClient } from '@service-email/client';import { storageServiceClient } from '@service-storage/client';import type { CalendarJoinRequest } from '@service-storage/generated/schemas/calendarJoinRequest';import { CalendarJoinRequestErrorCode } from '@service-storage/generated/schemas/calendarJoinRequestErrorCode';+import type { CalendarJoinRequestStatus } from '@service-storage/generated/schemas/calendarJoinRequestStatus';import { useMutation, useQuery } from '@tanstack/solid-query';import type { Accessor } from 'solid-js';import { calendarKeys } from './keys';@@ -26,6 +27,9 @@ function joinRequestsQueryOptions(eventId: string, enabled: boolean) {).requests,enabled,staleTime: 30_000,+ // `refresh_calendar` refetches this under an open list; rows keep their+ // identity, and focus, when another row leaves.+ reconcile: 'id',};}@@ -107,6 +111,24 @@ export type RespondToCalendarJoinRequestArgs = {decision: CalendarJoinRequestDecision;};+const ANSWER_STATUS: Record<+ CalendarJoinRequestDecision,+ CalendarJoinRequestStatus+> = { accept: 'accepted', decline: 'declined' };++/**+ * Whether an answer lost to one given elsewhere. The server returns a request+ * it no longer holds as pending unchanged, so a status other than the decision+ * means the press did nothing. An acceptance can still overrule a decline that+ * lands while its invitation is written; that returns `accepted`, its own.+ */+export function isAlreadyAnswered(+ answered: CalendarJoinRequest,+ decision: CalendarJoinRequestDecision+): boolean {+ return answered.status !== ANSWER_STATUS[decision];+}+async function respondToCalendarJoinRequest({request,decision,@@ -119,7 +141,12 @@ async function respondToCalendarJoinRequest({const answered = await throwOnErr(() =>emailClient.respondToCalendarJoinRequest(request.id, { decision }));- span.setAttr('calendar.join_request.outcome', answered.status);+ span.setAttr(+ 'calendar.join_request.outcome',+ isAlreadyAnswered(answered, decision)+ ? 'already_answered'+ : answered.status+ );return answered;} catch (error) {span.setAttr('calendar.join_request.outcome', 'failed');diff --git a/apps/web/src/lib/queries/calendar/sync.ts b/apps/web/src/lib/queries/calendar/sync.tsindex 40cc88e013..fa649b80a3 100644--- a/apps/web/src/lib/queries/calendar/sync.ts+++ b/apps/web/src/lib/queries/calendar/sync.ts@@ -9,8 +9,8 @@ import { refreshTeamCalendarQueries } from './team-cache';/*** Refetches everything the calendar UI reads: every mounted occurrence* viewport, the calendar list (which also carries per-calendar colors and- * names), teammates' out-of-office overlays, and the cached previews behind- * calendar mention chips.+ * names), teammates' out-of-office overlays, the cached previews behind+ * calendar mention chips, and open event details' requests to join.*/export function invalidateCalendarViews(): void {fireAndForget(refreshTeamCalendarQueries(), 'calendar-sync');@@ -20,6 +20,9 @@ export function invalidateCalendarViews(): void {queryClient.invalidateQueries({queryKey: calendarKeys.visibleCalendars.queryKey,});+ queryClient.invalidateQueries({+ queryKey: calendarKeys.joinRequests._def,+ });}/**@@ -28,17 +31,27 @@ export function invalidateCalendarViews(): void {* including the acting tab — committed changes for one of the viewer's* (owned or delegated) inboxes, so mounted calendar viewports refetch. The* calendar list is invalidated too, since a sync discovers new calendars- * and renames/recolors existing ones.+ * and renames/recolors existing ones, and so are requests to join, since+ * those viewers read and answer them. `join_request_answered` goes to the+ * requester, who views the event through a channel share, so only the+ * event's previews refetch: they carry the request's status.*/export function handleRefreshCalendar(payload: unknown): void {const event =typeof payload === 'object' && payload !== null? (payload as {event?: unknown;+ event_id?: unknown;link_id?: unknown;team_ooo_changed?: unknown;}): undefined;+ if (event?.event === 'join_request_answered') {+ if (typeof event.event_id === 'string') {+ invalidateCalendarEventPreviews(event.event_id);+ }+ return;+ }if (event?.event === 'team_sharing_changed') {fireAndForget(refreshTeamCalendarQueries({@@ -68,4 +81,7 @@ export function handleRefreshCalendar(payload: unknown): void {queryClient.invalidateQueries({queryKey: calendarKeys.visibleCalendars.queryKey,});+ queryClient.invalidateQueries({+ queryKey: calendarKeys.joinRequests._def,+ });}diff --git a/apps/web/src/lib/queries/calendar/tests/sync.test.ts b/apps/web/src/lib/queries/calendar/tests/sync.test.tsindex 05bb568f6c..9076d0b420 100644--- a/apps/web/src/lib/queries/calendar/tests/sync.test.ts+++ b/apps/web/src/lib/queries/calendar/tests/sync.test.ts@@ -1,3 +1,4 @@+import { previewKeys } from '@queries/preview/keys';import { beforeEach, describe, expect, it, vi } from 'vitest';import { calendarKeys } from '../keys';import { handleRefreshCalendar } from '../sync';@@ -44,6 +45,28 @@ describe('handleRefreshCalendar', () => {expect(invalidateQueriesMock).toHaveBeenCalledWith({queryKey: calendarKeys.visibleCalendars.queryKey,});+ expect(invalidateQueriesMock).toHaveBeenCalledWith({+ queryKey: calendarKeys.joinRequests._def,+ });+ });++ it("refetches a requester's view of the answered event, and nothing else", () => {+ handleRefreshCalendar({+ event: 'join_request_answered',+ event_id: 'shared-event',+ });++ expect(invalidateQueriesMock).toHaveBeenCalledWith({+ queryKey: previewKeys.item('shared-event').queryKey,+ });+ expect(invalidateQueriesMock).toHaveBeenCalledWith({+ queryKey: [...calendarKeys.mentionPreview._def, 'shared-event'],+ });+ expect(invalidateQueriesMock).not.toHaveBeenCalledWith({+ queryKey: calendarKeys.visibleCalendars.queryKey,+ });+ expect(invalidateCalendarOccurrencesMock).not.toHaveBeenCalled();+ expect(refreshTeamCalendarQueriesMock).not.toHaveBeenCalled();});it('defers the occurrence refetch while an RSVP is in flight', () => {@@ -73,6 +96,8 @@ describe('handleRefreshCalendar', () => {});handleRefreshCalendar({ event: 'synced' });handleRefreshCalendar({ event: 'synced', link_id: 42 });+ handleRefreshCalendar({ event: 'join_request_answered' });+ handleRefreshCalendar({ event: 'join_request_answered', event_id: 42 });expect(invalidateCalendarOccurrencesMock).not.toHaveBeenCalled();expect(invalidateQueriesMock).not.toHaveBeenCalled();diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/index.tsindex 25117eaef5..2b00a49e8b 100644--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/index.ts@@ -116,6 +116,8 @@ export * from './prepareCalendarReplacementRequestRecurrenceId';export * from './refreshCalendarEvent';export * from './refreshCalendarEventOneOf';export * from './refreshCalendarEventOneOfEvent';+export * from './refreshCalendarEventOneOfFive';+export * from './refreshCalendarEventOneOfFiveEvent';export * from './refreshCalendarEventOneOfThree';export * from './refreshCalendarEventOneOfThreeEvent';export * from './replacementStatus';diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/refreshCalendarEvent.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/refreshCalendarEvent.tsindex d346a8d0d9..8f81bd98cb 100644--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/refreshCalendarEvent.ts+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/refreshCalendarEvent.ts@@ -5,6 +5,7 @@* OpenAPI spec version: 0.1.0*/import type { RefreshCalendarEventOneOf } from './refreshCalendarEventOneOf';+import type { RefreshCalendarEventOneOfFive } from './refreshCalendarEventOneOfFive';import type { RefreshCalendarEventOneOfThree } from './refreshCalendarEventOneOfThree';/**@@ -12,4 +13,5 @@ import type { RefreshCalendarEventOneOfThree } from './refreshCalendarEventOneOf*/export type RefreshCalendarEvent =| RefreshCalendarEventOneOf- | RefreshCalendarEventOneOfThree;+ | RefreshCalendarEventOneOfThree+ | RefreshCalendarEventOneOfFive;diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/refreshCalendarEventOneOfFive.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/refreshCalendarEventOneOfFive.tsnew file mode 100644index 0000000000..12e72cc964--- /dev/null+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/refreshCalendarEventOneOfFive.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * calendar_service+ * OpenAPI spec version: 0.1.0+ */+import type { RefreshCalendarEventOneOfFiveEvent } from './refreshCalendarEventOneOfFiveEvent';++/**+ * The viewer's request to join a shared event was answered.+ */+export type RefreshCalendarEventOneOfFive = {+ event: RefreshCalendarEventOneOfFiveEvent;+ /** The shared event they asked to join. */+ event_id: string;+};diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/refreshCalendarEventOneOfFiveEvent.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/refreshCalendarEventOneOfFiveEvent.tsnew file mode 100644index 0000000000..c213e767de--- /dev/null+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/refreshCalendarEventOneOfFiveEvent.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * calendar_service+ * OpenAPI spec version: 0.1.0+ */++export type RefreshCalendarEventOneOfFiveEvent =+ (typeof RefreshCalendarEventOneOfFiveEvent)[keyof typeof RefreshCalendarEventOneOfFiveEvent];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const RefreshCalendarEventOneOfFiveEvent = {+ join_request_answered: 'join_request_answered',+} as const;diff --git a/apps/web/src/lib/service-clients/service-calendar/openapi.json b/apps/web/src/lib/service-clients/service-calendar/openapi.jsonindex 14a5a29fb8..52cf717875 100644--- a/apps/web/src/lib/service-clients/service-calendar/openapi.json+++ b/apps/web/src/lib/service-clients/service-calendar/openapi.json@@ -2462,6 +2462,22 @@"description": "True for sharing changes and any possibly affected OOO projection."}}+ },+ {+ "type": "object",+ "description": "The viewer's request to join a shared event was answered.",+ "required": ["event_id", "event"],+ "properties": {+ "event": {+ "type": "string",+ "enum": ["join_request_answered"]+ },+ "event_id": {+ "type": "string",+ "format": "uuid",+ "description": "The shared event they asked to join."+ }+ }}],"description": "Realtime signal that a connected inbox's calendar projection changed."diff --git a/crates/calendar_events/AGENTS.md b/crates/calendar_events/AGENTS.mdindex 29891c5be3..95bd9163ed 100644--- a/crates/calendar_events/AGENTS.md+++ b/crates/calendar_events/AGENTS.md@@ -207,6 +207,17 @@ reminder dispatch, team availability, and provider/Postgres persistence.Both lock only `notification` rows, once the delete holds its row, so neitherchanges that order. The cancelled row keeps its requests, as it keeps itsgrants, and a cancelled occurrence changes neither.+ An answer that changes the request reaches open clients through+ `CalendarRefreshNotifier`, after it is stored (an acceptance's invite nudges+ before that, too early to carry it): `calendar_changed` for the owner and+ delegates of the sharer's inbox, whose `refresh_calendar` refetches open+ request lists, and `join_request_answered` for the requester, who views the+ event through the share, so that signal names the event and never the+ sharer's inbox. A list reader may hold no notification, so the delete above+ is not that signal. An answer to a request no longer pending returns it+ unchanged and stays quiet; the client reads a status other than its decision+ as already answered. Only an acceptance whose invitation is being written+ overrules a decline (`resolve_join_request`), and it returns `accepted`.- Calendar mentions reach the agent as document mentions (`blockName``calendar`), but `ReadContent` and `ReadMetadata` need document access, whicha channel-shared event never grants. The agent reads a mentioned event withdiff --git a/crates/calendar_events/src/domain/models.rs b/crates/calendar_events/src/domain/models.rsindex 6668d6561f..95e0825224 100644--- a/crates/calendar_events/src/domain/models.rs+++ b/crates/calendar_events/src/domain/models.rs@@ -1920,6 +1920,11 @@ pub enum RefreshCalendarEvent {/// True for sharing changes and any possibly affected OOO projection.team_ooo_changed: bool,},+ /// The viewer's request to join a shared event was answered.+ JoinRequestAnswered {+ /// The shared event they asked to join.+ event_id: Uuid,+ },}/// Delivery channel of a reminder that Macro owns. Google email remindersdiff --git a/crates/calendar_events/src/domain/mutations/join.rs b/crates/calendar_events/src/domain/mutations/join.rsindex d26df160fd..e777e28835 100644--- a/crates/calendar_events/src/domain/mutations/join.rs+++ b/crates/calendar_events/src/domain/mutations/join.rs@@ -60,6 +60,7 @@ where.await.map_err(internal)?{+ self.announce_answer(&target, &resolved).await;return Ok(resolved);}// Another acceptance landed first; report where it left the request.@@ -69,6 +70,24 @@ where.map_err(internal)?.ok_or(CalendarMutationError::NotFound)}++ /// Refresh everyone with this request on screen, once the answer is+ /// stored so their refetch finds it; the nudge an acceptance's invite+ /// sends goes out before that. The request list's readers, the owner and+ /// delegates of the sharer's inbox, hear it here because the notification+ /// delete reaches only a sharer who still holds one.+ async fn announce_answer(+ &self,+ target: &CalendarEventMutationTarget,+ answered: &CalendarJoinRequest,+ ) {+ self.refresh+ .calendar_changed(&target.owner_id, target.email_link_id, false)+ .await;+ self.refresh+ .join_request_answered(&answered.requester_id, answered.event_id)+ .await;+ }}/// The span outcome of answering a join request.diff --git a/crates/calendar_events/src/domain/mutations/test.rs b/crates/calendar_events/src/domain/mutations/test.rsindex f8cc11e742..56d0717cb9 100644--- a/crates/calendar_events/src/domain/mutations/test.rs+++ b/crates/calendar_events/src/domain/mutations/test.rs@@ -1034,6 +1034,12 @@ impl macro_event_broker::MacroEventBroker for RecordingEventBroker {#[derive(Clone, Default)]struct RecordingRefreshNotifier {notified: Arc<Mutex<Vec<(String, Uuid, bool)>>>,+ /// `(requester, event)` of every requester told of an answer.+ answered_requesters: Arc<Mutex<Vec<(String, Uuid)>>>,+ /// Join requests whose stored status each nudge records in `seen_statuses`.+ join_requests: Arc<Mutex<Vec<crate::domain::join_requests::CalendarJoinRequest>>>,+ /// Status of each of `join_requests` as every nudge went out.+ seen_statuses: Arc<Mutex<Vec<crate::domain::join_requests::CalendarJoinRequestStatus>>>,}impl CalendarRefreshNotifier for RecordingRefreshNotifier {@@ -1043,6 +1049,18 @@ impl CalendarRefreshNotifier for RecordingRefreshNotifier {email_link_id,team_ooo_changed,));+ let statuses = self.join_requests.lock().unwrap();+ self.seen_statuses+ .lock()+ .unwrap()+ .extend(statuses.iter().map(|request| request.status));+ }++ async fn join_request_answered(&self, requester_id: &str, event_id: Uuid) {+ self.answered_requesters+ .lock()+ .expect("notifier lock")+ .push((requester_id.to_string(), event_id));}}diff --git a/crates/calendar_events/src/domain/mutations/test/join.rs b/crates/calendar_events/src/domain/mutations/test/join.rsindex ab2c5eeafe..b8d5a2ec9b 100644--- a/crates/calendar_events/src/domain/mutations/test/join.rs+++ b/crates/calendar_events/src/domain/mutations/test/join.rs@@ -367,6 +367,78 @@ async fn answering_a_resolved_request_returns_it_unchanged() {assert!(calls.lock().unwrap().is_empty());}+#[tokio::test]+async fn an_answer_refreshes_the_list_and_the_requesters_card() {+ for (accept, status) in [+ (true, CalendarJoinRequestStatus::Accepted),+ (false, CalendarJoinRequestStatus::Declined),+ ] {+ let repo = sharer_organizes();+ let request = pending_request(&repo, CalendarJoinRequestStatus::Pending);+ let refresh = RecordingRefreshNotifier {+ join_requests: repo.join_requests.clone(),+ ..RecordingRefreshNotifier::default()+ };++ service_with_refresh(+ repo,+ FakeProvider::new(FakeProviderBehavior::Echo),+ FakeTokens::ok(),+ refresh.clone(),+ )+ .respond_to_join_request(SHARER, request.id, accept)+ .await+ .unwrap();++ // A decline writes nothing to the provider, so nothing else would+ // tell the list's readers; the last nudge carries the stored answer+ // even when an acceptance's invite nudged earlier.+ assert_eq!(+ refresh.notified.lock().unwrap().last(),+ Some(&(SHARER.to_string(), SELF_LINK, false)),+ "accept={accept}"+ );+ assert_eq!(+ refresh.seen_statuses.lock().unwrap().last(),+ Some(&status),+ "accept={accept}"+ );+ assert_eq!(+ refresh.answered_requesters.lock().unwrap().as_slice(),+ [(MEMBER.to_string(), request.event_id)],+ "accept={accept}"+ );+ }+}++#[tokio::test]+async fn a_stale_answer_changes_nothing_so_it_refreshes_nothing() {+ for status in [+ CalendarJoinRequestStatus::Accepted,+ CalendarJoinRequestStatus::Declined,+ ] {+ for accept in [true, false] {+ let repo = sharer_organizes();+ let request = pending_request(&repo, status);+ let refresh = RecordingRefreshNotifier::default();++ let answered = service_with_refresh(+ repo,+ FakeProvider::new(FakeProviderBehavior::Echo),+ FakeTokens::ok(),+ refresh.clone(),+ )+ .respond_to_join_request(SHARER, request.id, accept)+ .await+ .unwrap();++ assert_eq!(answered, request, "{status:?} accept={accept}");+ assert!(refresh.notified.lock().unwrap().is_empty());+ assert!(refresh.answered_requesters.lock().unwrap().is_empty());+ }+ }+}+#[tokio::test]async fn a_refused_invite_leaves_the_request_pending() {let repo = sharer_organizes();diff --git a/crates/calendar_events/src/domain/ports.rs b/crates/calendar_events/src/domain/ports.rsindex 8def7e6ad8..858dfd8127 100644--- a/crates/calendar_events/src/domain/ports.rs+++ b/crates/calendar_events/src/domain/ports.rs@@ -949,6 +949,16 @@ pub trait CalendarRefreshNotifier: Send + Sync + 'static {email_link_id: Uuid,team_ooo_changed: bool,) -> impl Future<Output = ()> + Send;++ /// Signal that the request to join `event_id` by `requester_id` was+ /// answered. The requester views the event through a channel share, so+ /// [`Self::calendar_changed`], which reaches the viewers of the sharer's+ /// inbox, never reaches them.+ fn join_request_answered(+ &self,+ requester_id: &str,+ event_id: Uuid,+ ) -> impl Future<Output = ()> + Send;}/// Outbound port that announces one connected inbox's Google grant has gonediff --git a/crates/email_api_client/src/outbound/outlook/calendar/test/mutations.rs b/crates/email_api_client/src/outbound/outlook/calendar/test/mutations.rsindex 8e5523c1bb..d6d2bce335 100644--- a/crates/email_api_client/src/outbound/outlook/calendar/test/mutations.rs+++ b/crates/email_api_client/src/outbound/outlook/calendar/test/mutations.rs@@ -31,6 +31,7 @@ struct NoOpenClients;impl CalendarRefreshNotifier for NoOpenClients {async fn calendar_changed(&self, _: &str, _: Uuid, _: bool) {}+ async fn join_request_answered(&self, _: &str, _: Uuid) {}}#[derive(Clone, Default)]diff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.mdindex 33026b88b1..6126f2cb0a 100644--- a/docs/agent-guide/calendar.md+++ b/docs/agent-guide/calendar.md@@ -887,7 +887,10 @@ Outlook sends the invitation and the mention then opens the viewer's own copy. Dthe requester nothing, but their card then reads `Declined` and `The person who shared this eventdeclined 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 the-sharer is asked only once. The notification goes when the request is answered, by whoever answers+sharer is asked only once. An answer given anywhere else (a delegate, the API, another window)+drops the request from an open list and updates the requester's open card, without a reload. A+press on a row that had not caught up changes nothing and says so: `Already answered: <address> was+invited` or `Already answered: this request was declined`. The notification goes when the request is answered, by whoever answersit and however they do, leaving the notifications of other requests on the event, when therequester's account is deleted, and when the event goes (deleted in Macro, deleted or cancelled inGoogle or Outlook, its calendar or inbox removed); deleting one occurrence of a series leaves it,diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/RefreshCalendarEvent.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/RefreshCalendarEvent.mdindex fa0471f587..682dfc2a8b 100644--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/RefreshCalendarEvent.md+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/RefreshCalendarEvent.md@@ -1,6 +1,6 @@# Type Alias: RefreshCalendarEvent-> **RefreshCalendarEvent** = \{ `event`: `"synced"`; `link_id`: `string`; `team_ooo_changed`: `boolean`; \} \| \{ `event`: `"team_sharing_changed"`; `team_ooo_changed`: `boolean`; \}+> **RefreshCalendarEvent** = \{ `event`: `"synced"`; `link_id`: `string`; `team_ooo_changed`: `boolean`; \} \| \{ `event`: `"team_sharing_changed"`; `team_ooo_changed`: `boolean`; \} \| \{ `event`: `"join_request_answered"`; `event_id`: `string`; \}Realtime signal that a connected inbox's calendar projection changed.@@ -26,3 +26,14 @@ Realtime signal that a connected inbox's calendar projection changed.| ------ | ------ | ------ || `event` | `"team_sharing_changed"` | - || `team_ooo_changed` | `boolean` | True for sharing changes and any possibly affected OOO projection. |++***++### Type Literal++\{ `event`: `"join_request_answered"`; `event_id`: `string`; \}++| Name | Type | Description |+| ------ | ------ | ------ |+| `event` | `"join_request_answered"` | - |+| `event_id` | `string` | The shared event they asked to join. |diff --git a/packages/sdk/generated/calendar/types.gen.ts b/packages/sdk/generated/calendar/types.gen.tsindex 65209f606f..212098cccd 100644--- a/packages/sdk/generated/calendar/types.gen.ts+++ b/packages/sdk/generated/calendar/types.gen.ts@@ -954,6 +954,12 @@ export type RefreshCalendarEvent = {* True for sharing changes and any possibly affected OOO projection.*/team_ooo_changed: boolean;+} | {+ event: 'join_request_answered';+ /**+ * The shared event they asked to join.+ */+ event_id: string;};/**diff --git a/packages/sdk/specs/calendar.json b/packages/sdk/specs/calendar.jsonindex 14a5a29fb8..52cf717875 100644--- a/packages/sdk/specs/calendar.json+++ b/packages/sdk/specs/calendar.json@@ -2462,6 +2462,22 @@"description": "True for sharing changes and any possibly affected OOO projection."}}+ },+ {+ "type": "object",+ "description": "The viewer's request to join a shared event was answered.",+ "required": ["event_id", "event"],+ "properties": {+ "event": {+ "type": "string",+ "enum": ["join_request_answered"]+ },+ "event_id": {+ "type": "string",+ "format": "uuid",+ "description": "The shared event they asked to join."+ }+ }}],"description": "Realtime signal that a connected inbox's calendar projection changed."diff --git a/services/calendar_service/src/calendar_refresh.rs b/services/calendar_service/src/calendar_refresh.rsindex 493694d830..cd0446de4c 100644--- a/services/calendar_service/src/calendar_refresh.rs+++ b/services/calendar_service/src/calendar_refresh.rs@@ -5,7 +5,7 @@ use connection_gateway_client::client::ConnectionGatewayClient;use tracing::Instrument;use uuid::Uuid;-use crate::pubsub_util::cg_refresh_calendar;+use crate::pubsub_util::{cg_refresh_calendar, cg_refresh_join_request};/// [`CalendarRefreshNotifier`] backed by the connection gateway: fans one/// mutation's refresh nudge out to the link owner and its delegates, exactly@@ -57,6 +57,17 @@ impl CalendarRefreshNotifier for ConnectionGatewayCalendarRefresh {.in_current_span(),);}++ async fn join_request_answered(&self, requester_id: &str, event_id: Uuid) {+ let client = self.client.clone();+ let requester_id = requester_id.to_string();+ tokio::spawn(+ async move {+ cg_refresh_join_request(&client, &requester_id, event_id).await;+ }+ .in_current_span(),+ );+ }}impl calendar_events::domain::team::CalendarTeamNotifier for ConnectionGatewayCalendarRefresh {diff --git a/services/calendar_service/src/pubsub_util.rs b/services/calendar_service/src/pubsub_util.rsindex e6acaa6237..08c09a97f1 100644--- a/services/calendar_service/src/pubsub_util.rs+++ b/services/calendar_service/src/pubsub_util.rs@@ -58,6 +58,29 @@ pub async fn cg_refresh_calendar(}}+/// Tell one requester their request to join `event_id` was answered. It names+/// the event, whose id they hold, and not the sharer's inbox.+#[tracing::instrument(skip(client, requester_id), level = "debug")]+pub async fn cg_refresh_join_request(+ client: &ConnectionGatewayClient,+ requester_id: &str,+ event_id: uuid::Uuid,+) {+ if !cfg!(feature = "connection_gateway") {+ return;+ }+ let payload = serde_json::to_value(+ calendar_events::domain::models::RefreshCalendarEvent::JoinRequestAnswered { event_id },+ )+ .unwrap_or_default();+ let _ = client+ .refresh_calendar(requester_id, payload)+ .await+ .inspect_err(+ |e| tracing::error!(%event_id, "Failed to refresh the requester's calendar: {e}"),+ );+}+/// Invalidate teammate projections without exposing the underlying inbox IDs./// `notify_sharers` also refreshes `shared_by` themselves, for changes no/// inbox refresh reaches them with, such as their own sharing setting.diff --git a/services/email_service/src/calendar_refresh.rs b/services/email_service/src/calendar_refresh.rsindex 74a471b274..847d2f5d6e 100644--- a/services/email_service/src/calendar_refresh.rs+++ b/services/email_service/src/calendar_refresh.rs@@ -5,7 +5,7 @@ use connection_gateway_client::client::ConnectionGatewayClient;use tracing::Instrument;use uuid::Uuid;-use crate::pubsub::util::cg_refresh_calendar;+use crate::pubsub::util::{cg_refresh_calendar, cg_refresh_join_request};/// [`CalendarRefreshNotifier`] backed by the connection gateway: fans one/// mutation's refresh nudge out to the link owner and its delegates, exactly@@ -39,4 +39,15 @@ impl CalendarRefreshNotifier for ConnectionGatewayCalendarRefresh {.in_current_span(),);}++ async fn join_request_answered(&self, requester_id: &str, event_id: Uuid) {+ let client = self.client.clone();+ let requester_id = requester_id.to_string();+ tokio::spawn(+ async move {+ cg_refresh_join_request(&client, &requester_id, event_id).await;+ }+ .in_current_span(),+ );+ }}diff --git a/services/email_service/src/pubsub/util.rs b/services/email_service/src/pubsub/util.rsindex 565c2c699d..17e799e67d 100644--- a/services/email_service/src/pubsub/util.rs+++ b/services/email_service/src/pubsub/util.rs@@ -179,6 +179,29 @@ pub async fn cg_refresh_calendar(}}+/// Tell one requester their request to join `event_id` was answered. It names+/// the event, whose id they hold, and not the sharer's inbox.+#[tracing::instrument(skip(client, requester_id), level = "debug")]+pub async fn cg_refresh_join_request(+ client: &ConnectionGatewayClient,+ requester_id: &str,+ event_id: uuid::Uuid,+) {+ if !cfg!(feature = "connection_gateway") {+ return;+ }+ let payload = serde_json::to_value(+ calendar_events::domain::models::RefreshCalendarEvent::JoinRequestAnswered { event_id },+ )+ .unwrap_or_default();+ let _ = client+ .refresh_calendar(requester_id, payload)+ .await+ .inspect_err(+ |e| tracing::error!(%event_id, "Failed to refresh the requester's calendar: {e}"),+ );+}+/// Shared filter/dedup pass for the CRM populate + depopulate enqueue/// helpers. Returns each input email, lowercased and trimmed, with/// malformed addresses and the caller's own address dropped, and