Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(calendar): show a declined join request and refuse asking again (#8662)
gbirmanb923a1773947
diff --git a/.sqlx/query-2c0bb02770ea65192fc8be83adcb90153695a67cd04039748814bb7a1f80ca7f.json b/.sqlx/query-2c0bb02770ea65192fc8be83adcb90153695a67cd04039748814bb7a1f80ca7f.jsondeleted file mode 100644index 05383c3d07..0000000000--- a/.sqlx/query-2c0bb02770ea65192fc8be83adcb90153695a67cd04039748814bb7a1f80ca7f.json+++ /dev/null@@ -1,61 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n WITH previous AS (\n SELECT status\n FROM calendar_event_join_requests\n WHERE event_id = $2 AND requester_id = $3\n )\n INSERT INTO calendar_event_join_requests\n (id, event_id, requester_id, requester_email, status)\n VALUES ($1, $2, $3, $4, 'pending')\n ON CONFLICT (event_id, requester_id) DO UPDATE SET\n status = 'pending',\n requester_email = EXCLUDED.requester_email,\n created_at = now(),\n resolved_at = NULL\n WHERE calendar_event_join_requests.status = 'declined'\n RETURNING\n id,\n event_id,\n requester_id,\n requester_email,\n status,\n created_at,\n COALESCE((SELECT status FROM previous), 'declined') = 'declined' AS \"opened!\"\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "event_id",- "type_info": "Uuid"- },- {- "ordinal": 2,- "name": "requester_id",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "requester_email",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "status",- "type_info": "Text"- },- {- "ordinal": 5,- "name": "created_at",- "type_info": "Timestamptz"- },- {- "ordinal": 6,- "name": "opened!",- "type_info": "Bool"- }- ],- "parameters": {- "Left": [- "Uuid",- "Uuid",- "Text",- "Text"- ]- },- "nullable": [- false,- false,- false,- false,- false,- false,- null- ]- },- "hash": "2c0bb02770ea65192fc8be83adcb90153695a67cd04039748814bb7a1f80ca7f"-}diff --git a/.sqlx/query-a85c7f6c703fe072032ac017fedc8d2f3a7ba8f34c1e1b9e8112f029c846e411.json b/.sqlx/query-a85c7f6c703fe072032ac017fedc8d2f3a7ba8f34c1e1b9e8112f029c846e411.jsonnew file mode 100644index 0000000000..2c97af2983--- /dev/null+++ b/.sqlx/query-a85c7f6c703fe072032ac017fedc8d2f3a7ba8f34c1e1b9e8112f029c846e411.json@@ -0,0 +1,55 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO calendar_event_join_requests\n (id, event_id, requester_id, requester_email, status)\n VALUES ($1, $2, $3, $4, 'pending')\n ON CONFLICT (event_id, requester_id) DO NOTHING\n RETURNING id, event_id, requester_id, requester_email, status, created_at\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "event_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "requester_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "requester_email",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "status",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "created_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "a85c7f6c703fe072032ac017fedc8d2f3a7ba8f34c1e1b9e8112f029c846e411"+}diff --git a/apps/web/src/features/calendar-view/components/SharedEventActions.test.tsx b/apps/web/src/features/calendar-view/components/SharedEventActions.test.tsxindex cafe3f2c34..5f335afdb8 100644--- a/apps/web/src/features/calendar-view/components/SharedEventActions.test.tsx+++ b/apps/web/src/features/calendar-view/components/SharedEventActions.test.tsx@@ -56,6 +56,8 @@ vi.mock('@queries/calendar/copy', () => ({vi.mock('@queries/calendar/join-requests', () => ({isSharerCannotInvite: (error: unknown) =>(error as { code?: string }).code === 'sharer_cannot_invite',+ isJoinRequestDeclined: (error: unknown) =>+ (error as { code?: string }).code === 'request_declined',useRequestToJoinCalendarEventMutation: (callbacks?: {onSuccess?: () => void;onError?: (error: unknown) => void;@@ -264,25 +266,59 @@ describe('shared event actions', () => {fireEvent.click(screen.getByRole('button', { name: 'Ask to join' }));expect(screen.getByText('Requested')).toBeTruthy();- setStatus('declined');- expect(screen.getByRole('button', { name: 'Ask to join' })).toBeTruthy();+ setStatus('accepted');+ expect(screen.getByText('Invited')).toBeTruthy();+ expect(screen.queryByText('Requested')).toBeNull();+ });+ it('says a request was declined and offers no second ask', () => {+ const [status, setStatus] = createSignal<'pending' | 'declined'>();+ render(() => (+ <SharedEventActions+ eventId="shared-event"+ title="Design review"+ canRequestToJoin+ joinRequestStatus={status()}+ onAdded={vi.fn()}+ />+ ));fireEvent.click(screen.getByRole('button', { name: 'Ask to join' }));+ setStatus('pending');expect(screen.getByText('Requested')).toBeTruthy();- setStatus('accepted');- expect(screen.getByText('Invited')).toBeTruthy();+ // Even a preview that still says the viewer may ask stops offering it.+ setStatus('declined');+ expect(screen.getByText('Declined')).toBeTruthy();+ expect(+ screen.getByText(+ 'The person who shared this event declined your request to join.'+ )+ ).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'Ask to join' })).toBeNull();expect(screen.queryByText('Requested')).toBeNull();+ expect(+ screen.queryByText(+ "The person who shared this event can't add guests to it."+ )+ ).toBeNull();+ expect(mocks.ask).toHaveBeenCalledOnce();});- it('lets a declined viewer ask again but not a pending or invited one', () => {- renderActions(vi.fn(), {- canRequestToJoin: true,- joinRequestStatus: 'declined',+ it('says so when the sharer already declined an ask the card still offered', () => {+ mocks.ask.mockImplementationOnce(() => {+ throw { code: 'request_declined' };});- expect(screen.getByRole('button', { name: 'Ask to join' })).toBeTruthy();- cleanup();+ renderActions(vi.fn(), { canRequestToJoin: true });++ fireEvent.click(screen.getByRole('button', { name: 'Ask to join' }));++ expect(mocks.failure).toHaveBeenCalledWith(+ 'The person who shared this event declined your request'+ );+ expect(screen.queryByText('Requested')).toBeNull();+ });+ it('lets neither a pending nor an invited viewer ask again', () => {renderActions(vi.fn(), {canRequestToJoin: true,joinRequestStatus: 'pending',diff --git a/apps/web/src/features/calendar-view/components/SharedEventActions.tsx b/apps/web/src/features/calendar-view/components/SharedEventActions.tsxindex 3fbb1670d4..cc51cf685c 100644--- a/apps/web/src/features/calendar-view/components/SharedEventActions.tsx+++ b/apps/web/src/features/calendar-view/components/SharedEventActions.tsx@@ -8,6 +8,7 @@ import CaretDownIcon from '@phosphor/caret-down.svg';import CheckIcon from '@phosphor/check.svg';import DownloadSimpleIcon from '@phosphor/download-simple.svg';import UserPlusIcon from '@phosphor/user-plus.svg';+import XIcon from '@phosphor/x.svg';import { useVisibleCalendarsQuery } from '@queries/calendar/calendars';import {isAlreadyOnCalendar,@@ -15,6 +16,7 @@ import {useCopySharedCalendarEventMutation,} from '@queries/calendar/copy';import {+ isJoinRequestDeclined,isSharerCannotInvite,useRequestToJoinCalendarEventMutation,} from '@queries/calendar/join-requests';@@ -104,9 +106,14 @@ export function SharedEventActions(props: {toast.failure(isSharerCannotInvite(error)? "The person who shared this event can't add guests to it"- : 'Failed to ask to join the event'+ : isJoinRequestDeclined(error)+ ? 'The person who shared this event declined your request'+ : 'Failed to ask to join the event'),});+ // A declined request stands: the card says so instead of offering to ask+ // again, and the sharer is never asked twice.+ const declined = () => props.joinRequestStatus === 'declined';return (<div@@ -126,6 +133,12 @@ export function SharedEventActions(props: {Invited</span></Match>+ <Match when={declined()}>+ <span class="flex h-5 items-center gap-1 px-1 text-xs text-ink-muted">+ <XIcon class="size-3" />+ Declined+ </span>+ </Match><Match when={props.canRequestToJoin}><Buttonvariant="outline"@@ -200,11 +213,18 @@ export function SharedEventActions(props: {<DownloadSimpleIcon />Download .ics</Button>- <Show when={!props.canRequestToJoin && !requestOutstanding()}>- <p class="w-full text-xs text-ink-muted">- The person who shared this event can't add guests to it.- </p>- </Show>+ <Switch>+ <Match when={declined()}>+ <p class="w-full text-xs text-ink-muted">+ The person who shared this event declined your request to join.+ </p>+ </Match>+ <Match when={!props.canRequestToJoin && !requestOutstanding()}>+ <p class="w-full text-xs text-ink-muted">+ The person who shared this event can't add guests to it.+ </p>+ </Match>+ </Switch></div>);}diff --git a/apps/web/src/lib/queries/calendar/join-requests.ts b/apps/web/src/lib/queries/calendar/join-requests.tsindex 2a9ea64472..2fd27fa725 100644--- a/apps/web/src/lib/queries/calendar/join-requests.ts+++ b/apps/web/src/lib/queries/calendar/join-requests.ts@@ -47,6 +47,14 @@ export function isSharerCannotInvite(error: unknown): boolean {);}+/** Whether the person who shared the event declined the viewer's request. */+export function isJoinRequestDeclined(error: unknown): boolean {+ return thrownResultErrorHasCode(+ error,+ CalendarJoinRequestErrorCode.request_declined+ );+}+async function requestToJoinCalendarEvent(eventId: string): Promise<CalendarJoinRequest> {@@ -60,12 +68,15 @@ async function requestToJoinCalendarEvent(span.setAttr('calendar.join_request.outcome', 'requested');return request;} catch (error) {- const refused = isSharerCannotInvite(error);- span.setAttr(- 'calendar.join_request.outcome',- refused ? 'sharer_cannot_invite' : 'failed'+ const outcome = isSharerCannotInvite(error)+ ? 'sharer_cannot_invite'+ : isJoinRequestDeclined(error)+ ? 'declined'+ : 'failed';+ span.setAttr('calendar.join_request.outcome', outcome);+ span.error(+ outcome === 'failed' ? 'Join request failed' : 'Join request refused');- span.error(refused ? 'Join request refused' : 'Join request failed');throw error;}});diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarJoinRequest.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarJoinRequest.tsindex 1980add9e8..ae9b953125 100644--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarJoinRequest.ts+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarJoinRequest.ts@@ -11,7 +11,7 @@ import type { CalendarJoinRequestStatus } from './calendarJoinRequestStatus';only through a channel share.*/export interface CalendarJoinRequest {- /** When the request was made, or last reopened. */+ /** When the request was made. */createdAt: string;/** The sharer's event entity that was shared with the channel. */eventId: string;diff --git a/apps/web/src/lib/service-clients/service-calendar/openapi.json b/apps/web/src/lib/service-clients/service-calendar/openapi.jsonindex f6aacdcfec..2a7ce3e2e2 100644--- a/apps/web/src/lib/service-clients/service-calendar/openapi.json+++ b/apps/web/src/lib/service-clients/service-calendar/openapi.json@@ -1428,7 +1428,7 @@"createdAt": {"type": "string","format": "date-time",- "description": "When the request was made, or last reopened."+ "description": "When the request was made."},"eventId": {"type": "string",diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarJoinRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarJoinRequest.tsindex 5bef83c50a..925ba321bb 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarJoinRequest.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarJoinRequest.ts@@ -11,7 +11,7 @@ import type { CalendarJoinRequestStatus } from './calendarJoinRequestStatus';only through a channel share.*/export interface CalendarJoinRequest {- /** When the request was made, or last reopened. */+ /** When the request was made. */createdAt: string;/** The sharer's event entity that was shared with the channel. */eventId: string;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarJoinRequestErrorCode.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarJoinRequestErrorCode.tsindex e73761ce38..65e37914ae 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarJoinRequestErrorCode.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarJoinRequestErrorCode.ts@@ -16,5 +16,6 @@ export const CalendarJoinRequestErrorCode = {not_found: 'not_found',already_on_calendar: 'already_on_calendar',sharer_cannot_invite: 'sharer_cannot_invite',+ request_declined: 'request_declined',internal: 'internal',} as const;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.tsindex bc16e43b34..04abed375e 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts@@ -1798,7 +1798,7 @@ export const listJoinRequestsResponse = zod.object({createdAt: zod.iso.datetime({})- .describe('When the request was made, or last reopened.'),+ .describe('When the request was made.'),eventId: zod.uuid().describe(@@ -1834,9 +1834,7 @@ export const requestToJoinParams = zod.object({export const requestToJoinResponse = zod.object({- createdAt: zod.iso- .datetime({})- .describe('When the request was made, or last reopened.'),+ createdAt: zod.iso.datetime({}).describe('When the request was made.'),eventId: zod.uuid().describe("The sharer's event entity that was shared with the channel."),diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex 1675804aa5..67211bfa85 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -21338,7 +21338,7 @@"createdAt": {"type": "string","format": "date-time",- "description": "When the request was made, or last reopened."+ "description": "When the request was made."},"eventId": {"type": "string",@@ -21386,6 +21386,7 @@"not_found","already_on_calendar","sharer_cannot_invite",+ "request_declined","internal"]},diff --git a/crates/calendar_events/AGENTS.md b/crates/calendar_events/AGENTS.mdindex 2dc9f6b91e..9215991dbf 100644--- a/crates/calendar_events/AGENTS.md+++ b/crates/calendar_events/AGENTS.md@@ -113,7 +113,9 @@ reminder dispatch, team availability, and provider/Postgres persistence.write. Eligibility is the invite path's own `copy_capabilities` on thesharer's copy, so a request that can be made is one the sharer can accept,and accepting calls `invite_guests` as the sharer- (`src/domain/mutations/join.rs`).+ (`src/domain/mutations/join.rs`). A declined request stands: asking again+ is refused with `Declined` (409 `request_declined`) and never notifies the+ sharer twice.- `viewer_can` is viewer-relative, like an attendee's `is_self`: resolve it with`ActorInboxes::mark_event` and the copy's source link wherever a read pathmarks the viewer, and never store it. Each connected inbox gets its own copydiff --git a/crates/calendar_events/src/domain/join_requests.rs b/crates/calendar_events/src/domain/join_requests.rsindex 515e393df5..f031332aab 100644--- a/crates/calendar_events/src/domain/join_requests.rs+++ b/crates/calendar_events/src/domain/join_requests.rs@@ -71,7 +71,7 @@ pub struct CalendarJoinRequest {pub requester_email: String,/// Where the request stands.pub status: CalendarJoinRequestStatus,- /// When the request was made, or last reopened.+ /// When the request was made.pub created_at: DateTime<Utc>,}@@ -145,14 +145,17 @@ pub async fn annotate_join_state<R: CalendarRepository>(_ => None,});for (event_id, event) in shared {- event.can_request_to_join = matches!(- join_eligibility(repository, requester_id, event_id).await?,- JoinEligibility::Eligible { .. }- );event.join_request_status = repository.find_join_request(event_id, requester_id).await?.map(|request| request.status);+ // A declined requester may not ask again.+ event.can_request_to_join = event.join_request_status+ != Some(CalendarJoinRequestStatus::Declined)+ && matches!(+ join_eligibility(repository, requester_id, event_id).await?,+ JoinEligibility::Eligible { .. }+ );}Ok(())}@@ -208,6 +211,11 @@ where.open_join_request(event_id, requester_id, &email).await.map_err(CalendarJoinRequestError::Internal)?;+ // A declined request stands: the requester cannot ask again, so the+ // sharer is never asked twice.+ if request.status == CalendarJoinRequestStatus::Declined {+ return Err(CalendarJoinRequestError::Declined);+ }if opened {self.notifier.notify_join_request(&sharer_id, &request, &title)@@ -257,6 +265,7 @@ whereErr(CalendarJoinRequestError::NotFound) => "not_found",Err(CalendarJoinRequestError::AlreadyOnCalendar) => "already_on_calendar",Err(CalendarJoinRequestError::SharerCannotInvite) => "sharer_cannot_invite",+ Err(CalendarJoinRequestError::Declined) => "declined",Err(CalendarJoinRequestError::Internal(_)) => "failed",};span.record("outcome", outcome);diff --git a/crates/calendar_events/src/domain/mutations/test.rs b/crates/calendar_events/src/domain/mutations/test.rsindex be3e698277..23ea5b58ba 100644--- a/crates/calendar_events/src/domain/mutations/test.rs+++ b/crates/calendar_events/src/domain/mutations/test.rs@@ -311,16 +311,10 @@ impl CalendarRepository for FakeRepo {use crate::domain::join_requests::{CalendarJoinRequest, CalendarJoinRequestStatus};let mut requests = self.join_requests.lock().unwrap();if let Some(existing) = requests- .iter_mut()+ .iter().find(|request| request.event_id == event_id && request.requester_id == requester_id){- if existing.status != CalendarJoinRequestStatus::Declined {- return Ok((existing.clone(), false));- }- existing.status = CalendarJoinRequestStatus::Pending;- existing.requester_email = requester_email.to_string();- existing.created_at = Utc::now();- return Ok((existing.clone(), true));+ return Ok((existing.clone(), false));}let request = CalendarJoinRequest {id: Uuid::now_v7(),diff --git a/crates/calendar_events/src/domain/mutations/test/join.rs b/crates/calendar_events/src/domain/mutations/test/join.rsindex 6460d1e4d1..5cdee6aa66 100644--- a/crates/calendar_events/src/domain/mutations/test/join.rs+++ b/crates/calendar_events/src/domain/mutations/test/join.rs@@ -109,7 +109,7 @@ fn pending_request(repo: &FakeRepo, status: CalendarJoinRequestStatus) -> Calend}#[tokio::test]-async fn a_channel_member_asks_the_sharer_once_until_declined() {+async fn a_channel_member_asks_the_sharer_only_once() {let repo = sharer_organizes();let requests = repo.join_requests.clone();let (service, notifier) = asking(repo);@@ -124,16 +124,21 @@ async fn a_channel_member_asks_the_sharer_once_until_declined() {assert_eq!(again.id, first.id);assert_eq!(notifier.notified.lock().unwrap().len(), 1);+ // A declined request stands: asking again is refused and the sharer is+ // not asked a second time.requests.lock().unwrap()[0].status = CalendarJoinRequestStatus::Declined;- let reopened = service.request_to_join(MEMBER, event_id).await.unwrap();- assert_eq!(reopened.id, first.id);- assert_eq!(reopened.status, CalendarJoinRequestStatus::Pending);+ let error = service.request_to_join(MEMBER, event_id).await.unwrap_err();+ assert!(+ matches!(error, CalendarJoinRequestError::Declined),+ "{error:?}"+ );+ assert_eq!(+ requests.lock().unwrap()[0].status,+ CalendarJoinRequestStatus::Declined+ );assert_eq!(notifier.notified.lock().unwrap().as_slice(),- [- (SHARER.to_string(), first.id, "Offsite".to_string()),- (SHARER.to_string(), first.id, "Offsite".to_string()),- ]+ [(SHARER.to_string(), first.id, "Offsite".to_string())]);}@@ -493,3 +498,27 @@ async fn channel_shared_previews_carry_the_ask_to_join_state() {assert!(!own.can_request_to_join);assert_eq!(own.join_request_status, None);}++#[tokio::test]+async fn a_declined_requester_may_not_ask_again() {+ let repo = sharer_organizes();+ let request = pending_request(&repo, CalendarJoinRequestStatus::Declined);+ let items = [CalendarMentionRequestItem {+ event_id: request.event_id,+ occurrence_key: None,+ }];+ let mut previews = vec![preview(None)];++ annotate_join_state(&repo, MEMBER, &items, &mut previews)+ .await+ .unwrap();++ let CalendarMentionPreview::Accessible(shared) = &previews[0] else {+ panic!("the shared preview stays accessible");+ };+ assert!(!shared.can_request_to_join);+ assert_eq!(+ shared.join_request_status,+ Some(CalendarJoinRequestStatus::Declined)+ );+}diff --git a/crates/calendar_events/src/domain/ports.rs b/crates/calendar_events/src/domain/ports.rsindex affe4914ae..d4e9f03e8e 100644--- a/crates/calendar_events/src/domain/ports.rs+++ b/crates/calendar_events/src/domain/ports.rs@@ -843,6 +843,9 @@ pub enum CalendarJoinRequestError {/// accept.#[error("the person who shared this event cannot add guests to it")]SharerCannotInvite,+ /// The sharer declined the requester's earlier request, which stands.+ #[error("the person who shared this event declined the request to join")]+ Declined,/// Persistence failed.#[error("calendar join request failed: {0}")]Internal(Report),@@ -854,7 +857,8 @@ pub trait CalendarJoinRequestService: Send + Sync + 'static {/// Ask the person who shared an event with one of the requester's/// channels to add them as a guest, notifying them when the request/// becomes pending. Asking again while pending changes nothing; asking- /// after a decline reopens the request.+ /// after a decline is refused with `Declined`, so the sharer is asked+ /// only once.fn request_to_join(&self,requester_id: &str,diff --git a/crates/calendar_events/src/inbound/join_request_router.rs b/crates/calendar_events/src/inbound/join_request_router.rsindex e8096461ee..2d1dfc10ac 100644--- a/crates/calendar_events/src/inbound/join_request_router.rs+++ b/crates/calendar_events/src/inbound/join_request_router.rs@@ -86,6 +86,9 @@ pub enum CalendarJoinRequestErrorCode {AlreadyOnCalendar,/// The person who shared the event cannot add guests to it.SharerCannotInvite,+ /// The person who shared the event declined the requester's earlier+ /// request, which stands.+ RequestDeclined,/// An internal failure.Internal,}@@ -131,6 +134,11 @@ impl From<CalendarJoinRequestError> for CalendarJoinRequestApiError {CalendarJoinRequestErrorCode::SharerCannotInvite,"the person who shared this event cannot add guests to it",),+ CalendarJoinRequestError::Declined => (+ StatusCode::CONFLICT,+ CalendarJoinRequestErrorCode::RequestDeclined,+ "the person who shared this event declined your request to join",+ ),CalendarJoinRequestError::Internal(report) => {tracing::error!(error=?report, "calendar join request failed");(diff --git a/crates/calendar_events/src/inbound/join_request_router/test.rs b/crates/calendar_events/src/inbound/join_request_router/test.rsindex 6b13845a8f..71527d2457 100644--- a/crates/calendar_events/src/inbound/join_request_router/test.rs+++ b/crates/calendar_events/src/inbound/join_request_router/test.rs@@ -21,6 +21,11 @@ fn domain_failures_map_to_their_statuses_and_codes() {StatusCode::CONFLICT,CalendarJoinRequestErrorCode::SharerCannotInvite,),+ (+ CalendarJoinRequestError::Declined,+ StatusCode::CONFLICT,+ CalendarJoinRequestErrorCode::RequestDeclined,+ ),(CalendarJoinRequestError::Internal(rootcause::report!("db down")),StatusCode::INTERNAL_SERVER_ERROR,diff --git a/crates/calendar_events/src/outbound/pg/join_requests.rs b/crates/calendar_events/src/outbound/pg/join_requests.rsindex efef6c6a12..d4cd4339ad 100644--- a/crates/calendar_events/src/outbound/pg/join_requests.rs+++ b/crates/calendar_events/src/outbound/pg/join_requests.rs@@ -31,33 +31,16 @@ pub(super) async fn open_join_request(requester_id: &str,requester_email: &str,) -> Result<(CalendarJoinRequest, bool), Report> {- // A declined request reopens with a fresh time and address; a pending or- // accepted one is left as it is. `previous` reads the row before the- // upsert, so `opened` is true only when this call made it pending.- let row = sqlx::query!(+ // An existing request, pending, accepted or declined, is left as it is:+ // only the first ask inserts, so `opened` is true only for that call.+ let row = sqlx::query_as!(+ JoinRequestRow,r#"- WITH previous AS (- SELECT status- FROM calendar_event_join_requests- WHERE event_id = $2 AND requester_id = $3- )INSERT INTO calendar_event_join_requests(id, event_id, requester_id, requester_email, status)VALUES ($1, $2, $3, $4, 'pending')- ON CONFLICT (event_id, requester_id) DO UPDATE SET- status = 'pending',- requester_email = EXCLUDED.requester_email,- created_at = now(),- resolved_at = NULL- WHERE calendar_event_join_requests.status = 'declined'- RETURNING- id,- event_id,- requester_id,- requester_email,- status,- created_at,- COALESCE((SELECT status FROM previous), 'declined') = 'declined' AS "opened!"+ ON CONFLICT (event_id, requester_id) DO NOTHING+ RETURNING id, event_id, requester_id, requester_email, status, created_at"#,Uuid::now_v7(),event_id,@@ -68,18 +51,9 @@ pub(super) async fn open_join_request(.await.map_err(report)?;if let Some(row) = row {- let request = CalendarJoinRequest {- id: row.id,- event_id: row.event_id,- requester_id: row.requester_id,- requester_email: row.requester_email,- status: CalendarJoinRequestStatus::from_db(&row.status),- created_at: row.created_at,- };- return Ok((request, row.opened));+ return Ok((row.into(), true));}- // The conflict update was skipped: the request is already pending or- // accepted, and asking again changes nothing.+ // The request already exists; asking again changes nothing.let existing = find_join_request(pool, event_id, requester_id).await?.ok_or_else(|| rootcause::report!("join request vanished during the ask"))?;diff --git a/crates/calendar_events/src/outbound/pg/test/join_requests.rs b/crates/calendar_events/src/outbound/pg/test/join_requests.rsindex e2a2632b3f..f7c3664f61 100644--- a/crates/calendar_events/src/outbound/pg/test/join_requests.rs+++ b/crates/calendar_events/src/outbound/pg/test/join_requests.rs@@ -59,36 +59,44 @@ async fn join_requests_open_once_and_resolve_once(pool: PgPool) {.is_empty());- // Asking after a decline reopens the same request at the new address.- let (reopened, opened) = repo+ // A declined request stands: asking again changes nothing, keeps the+ // original address and is not news.+ let (after_decline, opened) = repo.open_join_request(event_id, member_id, "[email protected]").await.unwrap();- assert!(opened);- assert_eq!(reopened.id, first.id);- assert_eq!(reopened.status, CalendarJoinRequestStatus::Pending);- assert_eq!(reopened.requester_email, "[email protected]");+ assert!(!opened);+ assert_eq!(after_decline, declined);+ assert_eq!(after_decline.requester_email, "[email protected]");assert_eq!(repo.find_join_request(event_id, member_id).await.unwrap(),- Some(reopened.clone())+ Some(declined.clone()));+ // Another member's request is accepted.+ let second_id = "macro|[email protected]";+ insert_user(&pool, second_id).await;+ let (second, opened) = repo+ .open_join_request(event_id, second_id, "[email protected]")+ .await+ .unwrap();+ assert!(opened);let accepted = repo- .resolve_join_request(first.id, CalendarJoinRequestStatus::Accepted)+ .resolve_join_request(second.id, CalendarJoinRequestStatus::Accepted).await.unwrap()- .expect("the reopened request resolves");+ .expect("a pending request resolves");assert_eq!(accepted.status, CalendarJoinRequestStatus::Accepted);// A decline that arrives after the invitation was written changes nothing.assert_eq!(- repo.resolve_join_request(first.id, CalendarJoinRequestStatus::Declined)+ repo.resolve_join_request(second.id, CalendarJoinRequestStatus::Declined).await.unwrap(),None);// An accepted request is not reopened by asking again.let (after_accept, opened) = repo- .open_join_request(event_id, member_id, "[email protected]")+ .open_join_request(event_id, second_id, "[email protected]").await.unwrap();assert!(!opened);@@ -97,12 +105,12 @@ async fn join_requests_open_once_and_resolve_once(pool: PgPool) {// An acceptance whose invitation was written while a decline landed// still records the grant the guest list now holds.sqlx::query("UPDATE calendar_event_join_requests SET status = 'declined' WHERE id = $1")- .bind(first.id)+ .bind(second.id).execute(&pool).await.unwrap();let granted = repo- .resolve_join_request(first.id, CalendarJoinRequestStatus::Accepted)+ .resolve_join_request(second.id, CalendarJoinRequestStatus::Accepted).await.unwrap().expect("the acceptance overrides the decline");diff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.mdindex bc0281d71b..c7e9a3ed68 100644--- a/docs/agent-guide/calendar.md+++ b/docs/agent-guide/calendar.md@@ -603,8 +603,11 @@ notification (Settings → Notifications → Calendar → Requests to join), whi`<requester> asked to join <event>` with a person-plus glyph, like a comment row. It opens the event,whose details list each request with `Add as guest` and `Decline` on desktop and in the phonedrawer. Adding writes the guest through the same invite path as `Add guests`, so Google or-Outlook sends the invitation and the mention then opens the viewer's own copy; declining tells-the requester nothing, and asking again reopens the request. A classic `@Macro` reply that+Outlook sends the invitation and the mention then opens the viewer's own copy. Declining sends+the requester nothing, but their card then reads `Declined` and `The person who shared this event+declined your request to join.` with no `Ask to join`, and offers `Add to calendar` again. A+declined request stands: the server refuses another ask with 409 `request_declined`, so the+sharer is asked only once. 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 threadwrites the same channel grant. Private and confidential events are never shared this way.diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/CalendarJoinRequest.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/CalendarJoinRequest.mdindex 8f25b41909..e3e3cfa62f 100644--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/CalendarJoinRequest.md+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/CalendarJoinRequest.md@@ -9,7 +9,7 @@ only through a channel share.| Property | Type | Description || ------ | ------ | ------ |-| <a id="property-createdat"></a> `createdAt` | `string` | When the request was made, or last reopened. |+| <a id="property-createdat"></a> `createdAt` | `string` | When the request was made. || <a id="property-eventid"></a> `eventId` | `string` | The sharer's event entity that was shared with the channel. || <a id="property-id"></a> `id` | `string` | Request identifier. || <a id="property-requesteremail"></a> `requesterEmail` | `string` | Address the sharer invites when accepting. |diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/CalendarJoinRequest.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/CalendarJoinRequest.mdindex 8f25b41909..e3e3cfa62f 100644--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/CalendarJoinRequest.md+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/CalendarJoinRequest.md@@ -9,7 +9,7 @@ only through a channel share.| Property | Type | Description || ------ | ------ | ------ |-| <a id="property-createdat"></a> `createdAt` | `string` | When the request was made, or last reopened. |+| <a id="property-createdat"></a> `createdAt` | `string` | When the request was made. || <a id="property-eventid"></a> `eventId` | `string` | The sharer's event entity that was shared with the channel. || <a id="property-id"></a> `id` | `string` | Request identifier. || <a id="property-requesteremail"></a> `requesterEmail` | `string` | Address the sharer invites when accepting. |diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/CalendarJoinRequestErrorCode.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/CalendarJoinRequestErrorCode.mdindex 5eec975ccb..ea42394f40 100644--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/CalendarJoinRequestErrorCode.md+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/CalendarJoinRequestErrorCode.md@@ -1,5 +1,5 @@# Type Alias: CalendarJoinRequestErrorCode-> **CalendarJoinRequestErrorCode** = `"not_found"` \| `"already_on_calendar"` \| `"sharer_cannot_invite"` \| `"internal"`+> **CalendarJoinRequestErrorCode** = `"not_found"` \| `"already_on_calendar"` \| `"sharer_cannot_invite"` \| `"request_declined"` \| `"internal"`Machine-readable join-request failure category.diff --git a/packages/sdk/generated/calendar/types.gen.ts b/packages/sdk/generated/calendar/types.gen.tsindex f8dbf944af..c80eac10e3 100644--- a/packages/sdk/generated/calendar/types.gen.ts+++ b/packages/sdk/generated/calendar/types.gen.ts@@ -359,7 +359,7 @@ export type CalendarGuestInputBody = {*/export type CalendarJoinRequest = {/**- * When the request was made, or last reopened.+ * When the request was made.*/createdAt: string;/**diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex e4b8eb654b..2a78a1d8d0 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -1797,7 +1797,7 @@ export type CalendarEventSourceContent = {*/export type CalendarJoinRequest = {/**- * When the request was made, or last reopened.+ * When the request was made.*/createdAt: string;/**@@ -1839,7 +1839,7 @@ export type CalendarJoinRequestApiError = {/*** Machine-readable join-request failure category.*/-export type CalendarJoinRequestErrorCode = 'not_found' | 'already_on_calendar' | 'sharer_cannot_invite' | 'internal';+export type CalendarJoinRequestErrorCode = 'not_found' | 'already_on_calendar' | 'sharer_cannot_invite' | 'request_declined' | 'internal';/*** Lifecycle of a request to be added as a guest of a shared event.diff --git a/packages/sdk/specs/calendar.json b/packages/sdk/specs/calendar.jsonindex f6aacdcfec..2a7ce3e2e2 100644--- a/packages/sdk/specs/calendar.json+++ b/packages/sdk/specs/calendar.json@@ -1428,7 +1428,7 @@"createdAt": {"type": "string","format": "date-time",- "description": "When the request was made, or last reopened."+ "description": "When the request was made."},"eventId": {"type": "string",diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex 1675804aa5..67211bfa85 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -21338,7 +21338,7 @@"createdAt": {"type": "string","format": "date-time",- "description": "When the request was made, or last reopened."+ "description": "When the request was made."},"eventId": {"type": "string",@@ -21386,6 +21386,7 @@"not_found","already_on_calendar","sharer_cannot_invite",+ "request_declined","internal"]},