Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(calendar): share mentioned calendar events with channel participants (#6871)

gbirmanbf2efd75e76f
diff --git a/.sqlx/query-1f9328ecb53d4f78cbceb65c7b092a5bd85efe81fc60714924fedbf29b30434c.json b/.sqlx/query-1f9328ecb53d4f78cbceb65c7b092a5bd85efe81fc60714924fedbf29b30434c.json
new file mode 100644
index 0000000000..38fdc9ea20
--- /dev/null
+++ b/.sqlx/query-1f9328ecb53d4f78cbceb65c7b092a5bd85efe81fc60714924fedbf29b30434c.json
@@ -0,0 +1,65 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n grant_row.source_type AS \"source_type!: EntityAccessSourceType\",\n grant_row.source_id,\n grant_row.access_level AS \"access_level!: AccessLevel\",\n grant_row.granted_from_project_id\n FROM calendar_events event\n JOIN entity_access grant_row\n ON grant_row.entity_id = event.id\n AND grant_row.entity_type = 'calendar_event'\n AND grant_row.source_type = 'channel'\n JOIN comms_channel_participants participant\n ON participant.channel_id::text = grant_row.source_id\n AND participant.user_id = $2\n AND participant.left_at IS NULL\n WHERE event.id = $1\n AND event.status <> 'cancelled'\n AND event.visibility IN ('default', 'public')\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "source_type!: EntityAccessSourceType",
+ "type_info": {
+ "Custom": {
+ "name": "entity_access_source_type",
+ "kind": {
+ "Enum": [
+ "channel",
+ "team",
+ "user",
+ "bot"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 1,
+ "name": "source_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "access_level!: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 3,
+ "name": "granted_from_project_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "1f9328ecb53d4f78cbceb65c7b092a5bd85efe81fc60714924fedbf29b30434c"
+}
diff --git a/.sqlx/query-27eb7fa656e642da28f0937f7c9cf5cb27097157ed86b5cfb29caf98b679c55b.json b/.sqlx/query-27eb7fa656e642da28f0937f7c9cf5cb27097157ed86b5cfb29caf98b679c55b.json
new file mode 100644
index 0000000000..cdedca8129
--- /dev/null
+++ b/.sqlx/query-27eb7fa656e642da28f0937f7c9cf5cb27097157ed86b5cfb29caf98b679c55b.json
@@ -0,0 +1,139 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n (mentioned.id IS NOT NULL) AS \"mention_exists!\",\n viewer_event.id AS \"resolved_event_id?\",\n viewer_event.is_channel_shared AS \"is_channel_shared?\",\n viewer_event.title AS \"title?\",\n viewer_event.location AS \"location?\",\n viewer_event.organizer_email AS \"organizer_email?\",\n viewer_event.organizer_name AS \"organizer_name?\",\n viewer_event.recurrence_lines AS \"recurrence_lines?\",\n viewer_event.starts_at AS \"event_starts_at?\",\n viewer_event.ends_at AS \"event_ends_at?\",\n viewer_event.start_date AS \"event_start_date?\",\n viewer_event.end_date AS \"event_end_date?\",\n viewer_event.time_zone AS \"time_zone?\",\n viewer_event.updated_at AS \"updated_at?\",\n occurrence.occurrence_key AS \"occurrence_key?\",\n occurrence.starts_at AS \"occurrence_starts_at?\",\n occurrence.ends_at AS \"occurrence_ends_at?\",\n occurrence.start_date AS \"occurrence_start_date?\",\n occurrence.end_date AS \"occurrence_end_date?\",\n attendees.attendee_count AS \"attendee_count?\"\n FROM unnest($2::uuid[], $3::text[])\n WITH ORDINALITY AS requested(event_id, occurrence_key, ord)\n LEFT JOIN calendar_events mentioned\n ON mentioned.id = requested.event_id\n AND mentioned.status <> 'cancelled'\n LEFT JOIN LATERAL (\n SELECT resolved.*\n FROM (\n SELECT\n candidate.id,\n false AS is_channel_shared,\n (candidate.owner_id = $1) AS is_owned,\n (candidate.id = mentioned.id) AS is_mentioned,\n candidate.title,\n candidate.location,\n candidate.organizer_email,\n candidate.organizer_name,\n candidate.recurrence_lines,\n candidate.starts_at,\n candidate.ends_at,\n candidate.start_date,\n candidate.end_date,\n candidate.time_zone,\n candidate.updated_at\n FROM calendar_events candidate\n WHERE candidate.ical_uid = mentioned.ical_uid\n AND candidate.status <> 'cancelled'\n AND (\n candidate.owner_id = $1\n OR EXISTS (\n SELECT 1\n FROM macro_user_links link\n WHERE link.link_id = candidate.source_link_id\n AND link.primary_macro_id = $1\n )\n )\n UNION ALL\n SELECT\n mentioned.id,\n true,\n false,\n true,\n mentioned.title,\n mentioned.location,\n mentioned.organizer_email,\n mentioned.organizer_name,\n mentioned.recurrence_lines,\n mentioned.starts_at,\n mentioned.ends_at,\n mentioned.start_date,\n mentioned.end_date,\n mentioned.time_zone,\n mentioned.updated_at\n WHERE mentioned.visibility IN ('default', 'public')\n AND EXISTS (\n SELECT 1\n FROM entity_access grant_row\n JOIN comms_channel_participants participant\n ON participant.channel_id::text = grant_row.source_id\n AND participant.user_id = $1\n AND participant.left_at IS NULL\n WHERE grant_row.entity_id = mentioned.id\n AND grant_row.entity_type = 'calendar_event'\n AND grant_row.source_type = 'channel'\n )\n ) resolved\n ORDER BY\n resolved.is_channel_shared,\n resolved.is_owned DESC,\n resolved.is_mentioned DESC,\n resolved.updated_at DESC,\n resolved.id\n LIMIT 1\n ) viewer_event ON true\n LEFT JOIN LATERAL (\n SELECT\n instance.occurrence_key,\n instance.starts_at,\n instance.ends_at,\n instance.start_date,\n instance.end_date\n FROM calendar_event_occurrences instance\n CROSS JOIN LATERAL (\n SELECT COALESCE(\n instance.starts_at,\n instance.start_date::timestamp AT TIME ZONE 'UTC'\n ) AS at\n ) instance_start\n WHERE instance.event_id = viewer_event.id\n AND NOT instance.is_cancelled\n ORDER BY\n (instance.occurrence_key\n IS NOT DISTINCT FROM requested.occurrence_key) DESC,\n (instance_start.at >= $4) DESC,\n CASE WHEN instance_start.at >= $4 THEN instance_start.at END ASC,\n instance_start.at DESC,\n instance.occurrence_key\n LIMIT 1\n ) occurrence ON true\n LEFT JOIN LATERAL (\n SELECT count(*) AS attendee_count\n FROM calendar_event_attendees attendee\n WHERE attendee.event_id = viewer_event.id\n ) attendees ON true\n ORDER BY requested.ord\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "mention_exists!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 1,
+ "name": "resolved_event_id?",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "is_channel_shared?",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 3,
+ "name": "title?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "location?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "organizer_email?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "organizer_name?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 7,
+ "name": "recurrence_lines?",
+ "type_info": "TextArray"
+ },
+ {
+ "ordinal": 8,
+ "name": "event_starts_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "event_ends_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 10,
+ "name": "event_start_date?",
+ "type_info": "Date"
+ },
+ {
+ "ordinal": 11,
+ "name": "event_end_date?",
+ "type_info": "Date"
+ },
+ {
+ "ordinal": 12,
+ "name": "time_zone?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 13,
+ "name": "updated_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 14,
+ "name": "occurrence_key?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 15,
+ "name": "occurrence_starts_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 16,
+ "name": "occurrence_ends_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 17,
+ "name": "occurrence_start_date?",
+ "type_info": "Date"
+ },
+ {
+ "ordinal": 18,
+ "name": "occurrence_end_date?",
+ "type_info": "Date"
+ },
+ {
+ "ordinal": 19,
+ "name": "attendee_count?",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "UuidArray",
+ "TextArray",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ null,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ null
+ ]
+ },
+ "hash": "27eb7fa656e642da28f0937f7c9cf5cb27097157ed86b5cfb29caf98b679c55b"
+}
diff --git a/.sqlx/query-34476a8c58f66bdf4485dbf26077ce12ab3863682090ea3a4fc895aa0370134b.json b/.sqlx/query-34476a8c58f66bdf4485dbf26077ce12ab3863682090ea3a4fc895aa0370134b.json
deleted file mode 100644
index 28072abac3..0000000000
--- a/.sqlx/query-34476a8c58f66bdf4485dbf26077ce12ab3863682090ea3a4fc895aa0370134b.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT event.owner_id = $2 AS \"is_owner!\"\n FROM calendar_events event\n WHERE event.id = $1\n AND (\n event.owner_id = $2\n OR EXISTS (\n SELECT 1\n FROM macro_user_links link\n WHERE link.link_id = event.source_link_id\n AND link.primary_macro_id = $2\n )\n )\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "is_owner!",
- "type_info": "Bool"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "34476a8c58f66bdf4485dbf26077ce12ab3863682090ea3a4fc895aa0370134b"
-}
diff --git a/.sqlx/query-3fbe926f3799c34ca5df0e947e387203a9700ca0aaec3609a84078aa3f50ae98.json b/.sqlx/query-3fbe926f3799c34ca5df0e947e387203a9700ca0aaec3609a84078aa3f50ae98.json
deleted file mode 100644
index c1ffd696f1..0000000000
--- a/.sqlx/query-3fbe926f3799c34ca5df0e947e387203a9700ca0aaec3609a84078aa3f50ae98.json
+++ /dev/null
@@ -1,133 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT\n (mentioned.id IS NOT NULL) AS \"mention_exists!\",\n viewer_event.id AS \"viewer_event_id?\",\n viewer_event.title AS \"title?\",\n viewer_event.location AS \"location?\",\n viewer_event.organizer_email AS \"organizer_email?\",\n viewer_event.organizer_name AS \"organizer_name?\",\n viewer_event.recurrence_lines AS \"recurrence_lines?\",\n viewer_event.starts_at AS \"event_starts_at?\",\n viewer_event.ends_at AS \"event_ends_at?\",\n viewer_event.start_date AS \"event_start_date?\",\n viewer_event.end_date AS \"event_end_date?\",\n viewer_event.time_zone AS \"time_zone?\",\n viewer_event.updated_at AS \"updated_at?\",\n occurrence.occurrence_key AS \"occurrence_key?\",\n occurrence.starts_at AS \"occurrence_starts_at?\",\n occurrence.ends_at AS \"occurrence_ends_at?\",\n occurrence.start_date AS \"occurrence_start_date?\",\n occurrence.end_date AS \"occurrence_end_date?\",\n attendees.attendee_count AS \"attendee_count?\"\n FROM unnest($2::uuid[], $3::text[])\n WITH ORDINALITY AS requested(event_id, occurrence_key, ord)\n LEFT JOIN calendar_events mentioned\n ON mentioned.id = requested.event_id\n AND mentioned.status <> 'cancelled'\n LEFT JOIN LATERAL (\n SELECT\n candidate.id,\n candidate.title,\n candidate.location,\n candidate.organizer_email,\n candidate.organizer_name,\n candidate.recurrence_lines,\n candidate.starts_at,\n candidate.ends_at,\n candidate.start_date,\n candidate.end_date,\n candidate.time_zone,\n candidate.updated_at\n FROM calendar_events candidate\n WHERE candidate.ical_uid = mentioned.ical_uid\n AND candidate.status <> 'cancelled'\n AND (\n candidate.owner_id = $1\n OR EXISTS (\n SELECT 1\n FROM macro_user_links link\n WHERE link.link_id = candidate.source_link_id\n AND link.primary_macro_id = $1\n )\n )\n ORDER BY\n (candidate.owner_id = $1) DESC,\n (candidate.id = mentioned.id) DESC,\n candidate.updated_at DESC,\n candidate.id\n LIMIT 1\n ) viewer_event ON true\n LEFT JOIN LATERAL (\n SELECT\n instance.occurrence_key,\n instance.starts_at,\n instance.ends_at,\n instance.start_date,\n instance.end_date\n FROM calendar_event_occurrences instance\n CROSS JOIN LATERAL (\n SELECT COALESCE(\n instance.starts_at,\n instance.start_date::timestamp AT TIME ZONE 'UTC'\n ) AS at\n ) instance_start\n WHERE instance.event_id = viewer_event.id\n AND NOT instance.is_cancelled\n ORDER BY\n (instance.occurrence_key\n IS NOT DISTINCT FROM requested.occurrence_key) DESC,\n (instance_start.at >= $4) DESC,\n CASE WHEN instance_start.at >= $4 THEN instance_start.at END ASC,\n instance_start.at DESC,\n instance.occurrence_key\n LIMIT 1\n ) occurrence ON true\n LEFT JOIN LATERAL (\n SELECT count(*) AS attendee_count\n FROM calendar_event_attendees attendee\n WHERE attendee.event_id = viewer_event.id\n ) attendees ON true\n ORDER BY requested.ord\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "mention_exists!",
- "type_info": "Bool"
- },
- {
- "ordinal": 1,
- "name": "viewer_event_id?",
- "type_info": "Uuid"
- },
- {
- "ordinal": 2,
- "name": "title?",
- "type_info": "Text"
- },
- {
- "ordinal": 3,
- "name": "location?",
- "type_info": "Text"
- },
- {
- "ordinal": 4,
- "name": "organizer_email?",
- "type_info": "Text"
- },
- {
- "ordinal": 5,
- "name": "organizer_name?",
- "type_info": "Text"
- },
- {
- "ordinal": 6,
- "name": "recurrence_lines?",
- "type_info": "TextArray"
- },
- {
- "ordinal": 7,
- "name": "event_starts_at?",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 8,
- "name": "event_ends_at?",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 9,
- "name": "event_start_date?",
- "type_info": "Date"
- },
- {
- "ordinal": 10,
- "name": "event_end_date?",
- "type_info": "Date"
- },
- {
- "ordinal": 11,
- "name": "time_zone?",
- "type_info": "Text"
- },
- {
- "ordinal": 12,
- "name": "updated_at?",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 13,
- "name": "occurrence_key?",
- "type_info": "Text"
- },
- {
- "ordinal": 14,
- "name": "occurrence_starts_at?",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 15,
- "name": "occurrence_ends_at?",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 16,
- "name": "occurrence_start_date?",
- "type_info": "Date"
- },
- {
- "ordinal": 17,
- "name": "occurrence_end_date?",
- "type_info": "Date"
- },
- {
- "ordinal": 18,
- "name": "attendee_count?",
- "type_info": "Int8"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "UuidArray",
- "TextArray",
- "Timestamptz"
- ]
- },
- "nullable": [
- null,
- true,
- true,
- true,
- true,
- true,
- true,
- true,
- true,
- true,
- true,
- true,
- true,
- true,
- true,
- true,
- true,
- true,
- null
- ]
- },
- "hash": "3fbe926f3799c34ca5df0e947e387203a9700ca0aaec3609a84078aa3f50ae98"
-}
diff --git a/.sqlx/query-df93754df9b24e4fc2dc358799202a5d510086a889c5d80f077049f9868c2632.json b/.sqlx/query-df93754df9b24e4fc2dc358799202a5d510086a889c5d80f077049f9868c2632.json
new file mode 100644
index 0000000000..9ee011c92a
--- /dev/null
+++ b/.sqlx/query-df93754df9b24e4fc2dc358799202a5d510086a889c5d80f077049f9868c2632.json
@@ -0,0 +1,35 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n event.owner_id = $2 AS \"is_owner!\",\n EXISTS (\n SELECT 1\n FROM macro_user_links link\n WHERE link.link_id = event.source_link_id\n AND link.primary_macro_id = $2\n ) AS \"is_linked!\",\n (\n event.status <> 'cancelled'\n AND event.visibility IN ('default', 'public')\n AND EXISTS (\n SELECT 1\n FROM entity_access grant_row\n JOIN comms_channel_participants participant\n ON participant.channel_id::text = grant_row.source_id\n AND participant.user_id = $2\n AND participant.left_at IS NULL\n WHERE grant_row.entity_id = event.id\n AND grant_row.entity_type = 'calendar_event'\n AND grant_row.source_type = 'channel'\n )\n ) AS \"is_channel_shared!\"\n FROM calendar_events event\n WHERE event.id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "is_owner!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 1,
+ "name": "is_linked!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 2,
+ "name": "is_channel_shared!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null,
+ null,
+ null
+ ]
+ },
+ "hash": "df93754df9b24e4fc2dc358799202a5d510086a889c5d80f077049f9868c2632"
+}
diff --git a/apps/web/src/features/calendar-view/calendar-target-request.test.ts b/apps/web/src/features/calendar-view/calendar-target-request.test.ts
index 30d5217a43..e7682f39c8 100644
--- a/apps/web/src/features/calendar-view/calendar-target-request.test.ts
+++ b/apps/web/src/features/calendar-view/calendar-target-request.test.ts
@@ -1,8 +1,11 @@
+import { fetchCalendarMentionPreview } from '@queries/calendar/mention-preview';
+import type { CalendarMentionEvent } from '@service-storage/generated/schemas/calendarMentionEvent';
import { createRoot } from 'solid-js';
import { describe, expect, it, vi } from 'vitest';
import {
type CalendarTargetAim,
createCalendarTargetAim,
+ resolveTargetRequestFromPreview,
} from './calendar-target-request';
import type { CalendarFocusRequest, CalendarViewTarget } from './types';
@@ -20,6 +23,10 @@ const NEXT_WEEK_RANGE = {
endDate: '2026-08-25',
};
+vi.mock('@queries/calendar/mention-preview', () => ({
+ fetchCalendarMentionPreview: vi.fn(),
+}));
+
const standup: CalendarViewTarget = {
eventId: 'event-1',
occurrenceKey: '2026-08-17T14:00:00+00:00',
@@ -144,3 +151,53 @@ describe('createCalendarTargetAim', () => {
expect(aim.target()?.eventId).toBe('newer-event');
});
});
+
+describe('resolveTargetRequestFromPreview', () => {
+ const previewed = (viewerEventId: string | null): CalendarMentionEvent => ({
+ viewerEventId,
+ title: 'Pilates',
+ time: {
+ kind: 'timed',
+ startsAt: '2026-08-17T14:00:00Z',
+ endsAt: '2026-08-17T15:00:00Z',
+ },
+ occurrenceKey: '2026-08-17T14:00:00+00:00',
+ isRecurring: false,
+ attendeeCount: 2,
+ updatedAt: '2026-08-10T00:00:00Z',
+ });
+
+ it("aims at the viewer's own copy of the meeting", async () => {
+ vi.mocked(fetchCalendarMentionPreview).mockResolvedValueOnce(
+ previewed('viewer-copy')
+ );
+
+ const target = await resolveTargetRequestFromPreview(
+ { eventId: 'someone-elses-copy' },
+ 1
+ );
+
+ expect(target?.eventId).toBe('viewer-copy');
+ expect(target?.occurrenceKey).toBe('2026-08-17T14:00:00+00:00');
+ });
+
+ // A meeting the viewer sees only through a channel share is on none of
+ // their calendars, so the block has no event of theirs to focus.
+ it('does not aim at a channel-shared meeting', async () => {
+ vi.mocked(fetchCalendarMentionPreview).mockResolvedValueOnce(
+ previewed(null)
+ );
+
+ await expect(
+ resolveTargetRequestFromPreview({ eventId: 'someone-elses-copy' }, 1)
+ ).resolves.toBeUndefined();
+ });
+
+ it('does not aim at a meeting the viewer cannot access', async () => {
+ vi.mocked(fetchCalendarMentionPreview).mockResolvedValueOnce(null);
+
+ await expect(
+ resolveTargetRequestFromPreview({ eventId: 'private-event' }, 1)
+ ).resolves.toBeUndefined();
+ });
+});
diff --git a/apps/web/src/features/calendar-view/calendar-target-request.ts b/apps/web/src/features/calendar-view/calendar-target-request.ts
index fded9b1f49..5cfba98c99 100644
--- a/apps/web/src/features/calendar-view/calendar-target-request.ts
+++ b/apps/web/src/features/calendar-view/calendar-target-request.ts
@@ -51,7 +51,9 @@ export async function resolveTargetRequestFromPreview(
params.eventId,
occurrenceKey
).catch(() => null);
- if (!event) return undefined;
+ // A channel-shared meeting is on none of the viewer's calendars, so there
+ // is no event of theirs for the block to focus.
+ if (!event?.viewerEventId) return undefined;
const time: CalendarEventTime =
event.time.kind === 'timed'
diff --git a/apps/web/src/features/calendar-view/mention-open-target.test.ts b/apps/web/src/features/calendar-view/mention-open-target.test.ts
new file mode 100644
index 0000000000..052af8eaf6
--- /dev/null
+++ b/apps/web/src/features/calendar-view/mention-open-target.test.ts
@@ -0,0 +1,94 @@
+import type { PreviewItem } from '@queries/preview/types';
+import type { CalendarMentionEvent } from '@service-storage/generated/schemas/calendarMentionEvent';
+import { describe, expect, it } from 'vitest';
+import { calendarMentionOpen } from './mention-open-target';
+
+const OCCURRENCE = '2026-09-17T21:00:00+00:00';
+const OTHER_OCCURRENCE = '2026-09-24T21:00:00+00:00';
+
+function preview(event: Partial<CalendarMentionEvent>): PreviewItem {
+ return {
+ id: 'mentioned-event',
+ type: 'calendar_event',
+ access: 'access',
+ loading: false,
+ rawName: 'Pilates',
+ name: 'Pilates',
+ event: {
+ title: 'Pilates',
+ time: {
+ kind: 'timed',
+ startsAt: '2026-09-17T21:00:00Z',
+ endsAt: '2026-09-17T22:00:00Z',
+ },
+ occurrenceKey: OCCURRENCE,
+ isRecurring: true,
+ attendeeCount: 2,
+ updatedAt: '2026-09-15T00:00:00Z',
+ viewerEventId: 'viewer-copy',
+ ...event,
+ },
+ };
+}
+
+const noAccess: PreviewItem = {
+ id: 'mentioned-event',
+ type: 'calendar_event',
+ access: 'no_access',
+ loading: false,
+};
+
+describe('calendarMentionOpen', () => {
+ it("opens the viewer's own copy of the meeting", () => {
+ const open = calendarMentionOpen(preview({}), 'mentioned-event');
+
+ expect(open).toEqual({
+ kind: 'calendar',
+ target: {
+ eventId: 'viewer-copy',
+ occurrenceKey: OCCURRENCE,
+ time: {
+ kind: 'timed',
+ startsAt: '2026-09-17T21:00:00Z',
+ endsAt: '2026-09-17T22:00:00Z',
+ },
+ },
+ });
+ });
+
+ it('keeps the mention-targeted instance but drops the previewed time', () => {
+ const open = calendarMentionOpen(
+ preview({}),
+ 'mentioned-event',
+ OTHER_OCCURRENCE
+ );
+
+ expect(open).toEqual({
+ kind: 'calendar',
+ target: {
+ eventId: 'viewer-copy',
+ occurrenceKey: OTHER_OCCURRENCE,
+ time: undefined,
+ },
+ });
+ });
+
+ // A channel member without their own copy sees another member's
+ // projection; opening the calendar would target an event they don't have.
+ it('is read-only for a channel-shared meeting', () => {
+ const shared = preview({ viewerEventId: null });
+
+ expect(calendarMentionOpen(shared, 'mentioned-event')).toEqual({
+ kind: 'read_only',
+ });
+ });
+
+ it('routes an inaccessible mention through the mentioned id', () => {
+ expect(
+ calendarMentionOpen(noAccess, 'mentioned-event', OCCURRENCE)
+ ).toEqual({
+ kind: 'calendar',
+ target: { eventId: 'mentioned-event', occurrenceKey: OCCURRENCE },
+ });
+ });
+});
diff --git a/apps/web/src/features/calendar-view/mention-open-target.ts b/apps/web/src/features/calendar-view/mention-open-target.ts
new file mode 100644
index 0000000000..7340edc3b3
--- /dev/null
+++ b/apps/web/src/features/calendar-view/mention-open-target.ts
@@ -0,0 +1,53 @@
+import {
+ isCalendarEventPreviewItem,
+ type PreviewItem,
+} from '@queries/preview/types';
+import type { CalendarEventOpenTarget } from './open-calendar-event';
+
+/** What opening a calendar event mention does for the current viewer. */
+export type CalendarMentionOpen =
+ | {
+ kind: 'calendar';
+ target: Omit<CalendarEventOpenTarget, 'openInNewSplit'>;
+ }
+ /**
+ * The meeting is on none of the viewer's calendars: they see it only
+ * because it was shared with one of their channels, so there is no event
+ * of theirs to open and the preview card is the whole experience.
+ */
+ | { kind: 'read_only' };
+
+/**
+ * Resolve a calendar mention to the viewer's own copy of the meeting, which
+ * the preview found through the shared iCalendar UID. Without an accessible
+ * preview (e.g. the recent-mention fallback for a just-created event) the
+ * mentioned id is still routed through the singleton calendar opener.
+ */
+export function calendarMentionOpen(
+ item: PreviewItem,
+ mentionedEventId: string,
+ occurrenceKey?: string
+): CalendarMentionOpen {
+ if (!isCalendarEventPreviewItem(item)) {
+ return {
+ kind: 'calendar',
+ target: { eventId: mentionedEventId, occurrenceKey },
+ };
+ }
+ const { event } = item;
+ if (!event.viewerEventId) return { kind: 'read_only' };
+ return {
+ kind: 'calendar',
+ target: {
+ eventId: event.viewerEventId,
+ occurrenceKey: occurrenceKey ?? event.occurrenceKey ?? undefined,
+ // The preview's time only locates the instance it previewed; a
+ // mention aimed at a different instance derives its range from the
+ // occurrence key instead.
+ time:
+ !occurrenceKey || occurrenceKey === event.occurrenceKey
+ ? event.time
+ : undefined,
+ },
+ };
+}
diff --git a/apps/web/src/lib/core/component/DocumentPreview.tsx b/apps/web/src/lib/core/component/DocumentPreview.tsx
index f459c3a04f..39d0eaee27 100644
--- a/apps/web/src/lib/core/component/DocumentPreview.tsx
+++ b/apps/web/src/lib/core/component/DocumentPreview.tsx
@@ -3,6 +3,7 @@ import {
type CalendarMentionTarget,
copyCalendarEventMentionTarget,
} from '@app/features/calendar-view/copy-event-mention';
+import { calendarMentionOpen } from '@app/features/calendar-view/mention-open-target';
import { openCalendarEventSplit } from '@app/features/calendar-view/open-calendar-event';
import { CALENDAR_VIEW_ID } from '@app/features/calendar-view/types';
import { openChatWithAgent } from '@app/features/chat/ChatWithAgentButton';
@@ -34,6 +35,7 @@ import ThreadIcon from '@phosphor/chats-circle.svg';
import ClockIcon from '@phosphor/clock.svg';
import ColumnsPlusRight from '@phosphor/columns-plus-right.svg';
import DotsThree from '@phosphor/dots-three.svg';
+import EyeIcon from '@phosphor/eye.svg';
import GitBranchIcon from '@phosphor/git-branch.svg';
import HighlightIcon from '@phosphor/highlighter-circle.svg';
import Link from '@phosphor/link.svg';
@@ -372,6 +374,11 @@ function CalendarEventPreviewDetails(props: {
props.event.organizerName ?? props.event.organizerEmail;
return (
<div class="px-2 pb-2 flex flex-col gap-1 text-sm text-ink-muted">
+ <Show when={!props.event.viewerEventId}>
+ <MetadataInfo icon={EyeIcon}>
+ Shared with you · not on your calendar
+ </MetadataInfo>
+ </Show>
<Show when={calendarPreviewSchedule(props.event)}>
{(schedule) => (
<MetadataInfo icon={ClockIcon}>
@@ -504,27 +511,26 @@ export function DocumentPreviewContent(props: DocumentPreviewContentProps) {
};
// Calendar is a singleton application view: a mentioned event opens it aimed
- // at the viewer's own copy of the meeting rather than a per-id split.
+ // at the viewer's own copy of the meeting rather than a per-id split. A
+ // preview that is not (yet) accessible still routes the mentioned id through
+ // the singleton opener so it resolves through the event preview API.
+ const calendarOpen = () => {
+ if (targetBlockType() !== 'calendar') return undefined;
+ return calendarMentionOpen(
+ item(),
+ props.documentInfo.id,
+ props.documentInfo.params?.occurrenceKey
+ );
+ };
const calendarOpenTarget = () => {
- const i = item();
- if (isCalendarEventPreviewItem(i)) {
- return {
- eventId: i.event.viewerEventId,
- occurrenceKey: i.event.occurrenceKey ?? undefined,
- time: i.event.time,
- };
- }
- // Preview not (yet) accessible — e.g. the recent-mention fallback for a
- // just-created event. Still route through the singleton Calendar opener
- // with the mentioned id so it resolves through the event preview API.
- if (targetBlockType() === 'calendar') {
- return {
- eventId: props.documentInfo.id,
- occurrenceKey: props.documentInfo.params?.occurrenceKey,
- };
- }
- return undefined;
+ const open = calendarOpen();
+ return open?.kind === 'calendar' ? open.target : undefined;
};
+ // A meeting shared through a channel but absent from the viewer's own
+ // calendars previews read-only: there is no event of theirs to open.
+ const isReadOnlyCalendarShare = () => calendarOpen()?.kind === 'read_only';
+ const isOpenable = () =>
+ !!props.documentInfo.isOpenable && !isReadOnlyCalendarShare();
const openDocument = createCallback(async (event: MouseEvent) => {
const calendarTarget = calendarOpenTarget();
@@ -582,8 +588,16 @@ export function DocumentPreviewContent(props: DocumentPreviewContentProps) {
// writes, so pasting into an editor rebuilds the mention instead of
// dropping in a bare deep link.
const calendarMentionTarget = (): CalendarMentionTarget | undefined => {
- const target = calendarOpenTarget();
- if (!target) return undefined;
+ const open = calendarOpen();
+ if (!open) return undefined;
+ // A read-only share re-mentions the id that was shared with the channel.
+ const target =
+ open.kind === 'calendar'
+ ? open.target
+ : {
+ eventId: props.documentInfo.id,
+ occurrenceKey: props.documentInfo.params?.occurrenceKey,
+ };
const i = item();
const previewed = isCalendarEventPreviewItem(i) ? i.event : undefined;
return {
@@ -684,7 +698,7 @@ export function DocumentPreviewContent(props: DocumentPreviewContentProps) {
const PreviewTitle = (local: { name: string }) => (
<Item.Title>
<Show
- when={props.documentInfo.isOpenable}
+ when={isOpenable()}
fallback={<span class="wrap-anywhere">{local.name}</span>}
>
<button
@@ -755,7 +769,7 @@ export function DocumentPreviewContent(props: DocumentPreviewContentProps) {
Copy Branch Name
</Dropdown.Item>
</Show>
- <Show when={props.documentInfo.isOpenable && !isSplitAlreadyOpen()}>
+ <Show when={isOpenable() && !isSplitAlreadyOpen()}>
<Dropdown.Item onSelect={() => void openInNewSplit()}>
<ColumnsPlusRight class="size-4" />
Open in New Split
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx
index b45fefa45a..ce39073b96 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx
@@ -1,4 +1,5 @@
import { parseLocalDate } from '@app/features/calendar/utils/calendar-date';
+import { calendarMentionOpen } from '@app/features/calendar-view/mention-open-target';
import { openCalendarEventSplit } from '@app/features/calendar-view/open-calendar-event';
import { URL_PARAMS as CHANNEL_PARAMS } from '@block-channel/constants';
import {
@@ -539,24 +540,25 @@ function DocumentMentionInner(props: DocumentMentionDecoratorProps) {
return props.blockName;
});
+ const [previewCardOpen, setPreviewCardOpen] = createSignal(false);
+
const open = createCallback((e: MouseEvent | KeyboardEvent | null) => {
// The calendar is a singleton block: open it aimed at the viewer's own
- // copy of the meeting, which the preview resolved through the shared
- // iCalendar UID.
+ // copy of the meeting. A meeting shared through the channel but absent
+ // from the viewer's calendars has nothing to open, so its read-only
+ // preview card is shown instead.
if (verifyBlockName(props.blockName) === 'calendar') {
- const i = item();
- const event = isCalendarEventPreviewItem(i) ? i.event : undefined;
- const paramKey = props.blockParams?.occurrenceKey;
+ const target = calendarMentionOpen(
+ item(),
+ props.documentId,
+ props.blockParams?.occurrenceKey
+ );
+ if (target.kind === 'read_only') {
+ setPreviewCardOpen(true);
+ return;
+ }
openCalendarEventSplit({
- eventId: event?.viewerEventId ?? props.documentId,
- occurrenceKey: paramKey ?? event?.occurrenceKey ?? undefined,
- // The preview's time only locates the instance it previewed; a
- // mention aimed at a different instance derives its range from the
- // occurrence key instead.
- time:
- !paramKey || paramKey === event?.occurrenceKey
- ? event?.time
- : undefined,
+ ...target.target,
openInNewSplit: openInNewSplitForMention(e?.shiftKey, e != null),
});
return;
@@ -647,6 +649,8 @@ function DocumentMentionInner(props: DocumentMentionDecoratorProps) {
return (
<HoverCard
+ open={previewCardOpen()}
+ onOpenChange={setPreviewCardOpen}
trigger={
<span class="relative">
<span
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarMentionEvent.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarMentionEvent.ts
index 1aa1283149..513d340ae4 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarMentionEvent.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarMentionEvent.ts
@@ -8,15 +8,17 @@ import type { CalendarMentionEventLocation } from './calendarMentionEventLocatio
import type { CalendarMentionEventOccurrenceKey } from './calendarMentionEventOccurrenceKey';
import type { CalendarMentionEventOrganizerEmail } from './calendarMentionEventOrganizerEmail';
import type { CalendarMentionEventOrganizerName } from './calendarMentionEventOrganizerName';
+import type { CalendarMentionEventViewerEventId } from './calendarMentionEventViewerEventId';
import type { EventTime } from './eventTime';
/**
* Meeting-level fields shown in a calendar event mention preview, taken from
-the requester's own projection of the meeting.
+the requester's own projection of the meeting, or — when the requester has
+none — from the mentioned projection a channel they belong to was given.
*/
export interface CalendarMentionEvent {
/**
- * Number of attendees on the requester's copy.
+ * Number of attendees on the previewed copy.
* @minimum 0
*/
attendeeCount: number;
@@ -37,9 +39,12 @@ series start. */
time: EventTime;
/** Display title. */
title: string;
- /** Entity update time of the requester's copy. */
+ /** Entity update time of the previewed copy. */
updatedAt: string;
/** The requester's own event entity for the mentioned meeting. Differs
-from the mentioned id when the mention came from another attendee. */
- viewerEventId: string;
+from the mentioned id when the mention came from another attendee.
+Absent when the meeting is on none of the requester's calendars and
+they see it only because it was shared with one of their channels:
+that preview is read-only and there is no event of theirs to open. */
+ viewerEventId?: CalendarMentionEventViewerEventId;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarMentionEventViewerEventId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarMentionEventViewerEventId.ts
new file mode 100644
index 0000000000..c1a37f382d
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/calendarMentionEventViewerEventId.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The requester's own event entity for the mentioned meeting. Differs
+from the mentioned id when the mention came from another attendee.
+Absent when the meeting is on none of the requester's calendars and
+they see it only because it was shared with one of their channels:
+that preview is read-only and there is no event of theirs to open.
+ */
+export type CalendarMentionEventViewerEventId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index 529c02701d..c08acfdad7 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -242,6 +242,7 @@ export * from './calendarMentionEventLocation';
export * from './calendarMentionEventOccurrenceKey';
export * from './calendarMentionEventOrganizerEmail';
export * from './calendarMentionEventOrganizerName';
+export * from './calendarMentionEventViewerEventId';
export * from './calendarMentionPreviewItem';
export * from './calendarMentionPreviewItemEvent';
export * from './calendarMentionPreviewKind';
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.ts
index 4db7c1be09..0aaad4c161 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
@@ -1602,7 +1602,7 @@ export const mentionPreviewsResponse = zod
attendeeCount: zod
.number()
.min(mentionPreviewsResponseItemsItemEventAttendeeCountMin)
- .describe("Number of attendees on the requester's copy."),
+ .describe('Number of attendees on the previewed copy.'),
isRecurring: zod
.boolean()
.describe('Whether the event repeats.'),
@@ -1663,15 +1663,16 @@ export const mentionPreviewsResponse = zod
title: zod.string().describe('Display title.'),
updatedAt: zod.iso
.datetime({})
- .describe("Entity update time of the requester's copy."),
+ .describe('Entity update time of the previewed copy.'),
viewerEventId: zod
.uuid()
+ .nullish()
.describe(
- "The requester's own event entity for the mentioned meeting. Differs\nfrom the mentioned id when the mention came from another attendee."
+ "The requester's own event entity for the mentioned meeting. Differs\nfrom the mentioned id when the mention came from another attendee.\nAbsent when the meeting is on none of the requester's calendars and\nthey see it only because it was shared with one of their channels:\nthat preview is read-only and there is no event of theirs to open."
),
})
.describe(
- "Meeting-level fields shown in a calendar event mention preview, taken from\nthe requester's own projection of the meeting."
+ "Meeting-level fields shown in a calendar event mention preview, taken from\nthe requester's own projection of the meeting, or — when the requester has\nnone — from the mentioned projection a channel they belong to was given."
),
])
.optional(),
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 2dd5d5354c..45712139cf 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -17198,9 +17198,8 @@
},
"CalendarMentionEvent": {
"type": "object",
- "description": "Meeting-level fields shown in a calendar event mention preview, taken from\nthe requester's own projection of the meeting.",
+ "description": "Meeting-level fields shown in a calendar event mention preview, taken from\nthe requester's own projection of the meeting, or — when the requester has\nnone — from the mentioned projection a channel they belong to was given.",
"required": [
- "viewerEventId",
"title",
"time",
"isRecurring",
@@ -17210,7 +17209,7 @@
"properties": {
"attendeeCount": {
"type": "integer",
- "description": "Number of attendees on the requester's copy.",
+ "description": "Number of attendees on the previewed copy.",
"minimum": 0
},
"isRecurring": {
@@ -17244,12 +17243,12 @@
"updatedAt": {
"type": "string",
"format": "date-time",
- "description": "Entity update time of the requester's copy."
+ "description": "Entity update time of the previewed copy."
},
"viewerEventId": {
- "type": "string",
+ "type": ["string", "null"],
"format": "uuid",
- "description": "The requester's own event entity for the mentioned meeting. Differs\nfrom the mentioned id when the mention came from another attendee."
+ "description": "The requester's own event entity for the mentioned meeting. Differs\nfrom the mentioned id when the mention came from another attendee.\nAbsent when the meeting is on none of the requester's calendars and\nthey see it only because it was shared with one of their channels:\nthat preview is read-only and there is no event of theirs to open."
}
}
},
@@ -17265,7 +17264,7 @@
},
{
"$ref": "#/components/schemas/CalendarMentionEvent",
- "description": "Preview of the requester's own copy, present only with access."
+ "description": "Preview of the requester's own copy, or of the channel-shared copy,\npresent only with access."
}
]
},
diff --git a/crates/calendar_events/src/domain/models.rs b/crates/calendar_events/src/domain/models.rs
index f068114dd6..9a717fe012 100644
--- a/crates/calendar_events/src/domain/models.rs
+++ b/crates/calendar_events/src/domain/models.rs
@@ -836,10 +836,12 @@ pub struct CalendarMentionRequestItem {
///
/// Event entities are per-owner projections of a meeting, so a mention from
/// another attendee resolves through the shared iCalendar UID to the
-/// requester's own copy — the preview never exposes another user's row.
+/// requester's own copy. Another user's row is exposed only when it was
+/// explicitly shared with a channel the requester belongs to.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CalendarMentionPreview {
- /// The requester holds a live copy of the meeting on a visible calendar.
+ /// The requester holds a live copy of the meeting on a visible calendar,
+ /// or the mentioned copy was shared with one of their channels.
Accessible(Box<CalendarMentionEvent>),
/// The event exists but is on no calendar the requester can see.
NoAccess,
@@ -848,14 +850,18 @@ pub enum CalendarMentionPreview {
}
/// Meeting-level fields shown in a calendar event mention preview, taken from
-/// the requester's own projection of the meeting.
+/// the requester's own projection of the meeting, or — when the requester has
+/// none — from the mentioned projection a channel they belong to was given.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct CalendarMentionEvent {
/// The requester's own event entity for the mentioned meeting. Differs
/// from the mentioned id when the mention came from another attendee.
- pub viewer_event_id: Uuid,
+ /// Absent when the meeting is on none of the requester's calendars and
+ /// they see it only because it was shared with one of their channels:
+ /// that preview is read-only and there is no event of theirs to open.
+ pub viewer_event_id: Option<Uuid>,
/// Display title.
pub title: String,
/// Time of the previewed instance: the requested occurrence when it
@@ -873,9 +879,9 @@ pub struct CalendarMentionEvent {
pub organizer_email: Option<String>,
/// Organizer display name.
pub organizer_name: Option<String>,
- /// Number of attendees on the requester's copy.
+ /// Number of attendees on the previewed copy.
pub attendee_count: usize,
- /// Entity update time of the requester's copy.
+ /// Entity update time of the previewed copy.
pub updated_at: DateTime<Utc>,
}
diff --git a/crates/calendar_events/src/inbound/axum_router.rs b/crates/calendar_events/src/inbound/axum_router.rs
index 594f5b4d16..d8ef32c595 100644
--- a/crates/calendar_events/src/inbound/axum_router.rs
+++ b/crates/calendar_events/src/inbound/axum_router.rs
@@ -384,7 +384,8 @@ pub struct CalendarMentionPreviewRequest {
#[derive(Serialize, utoipa::ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum CalendarMentionPreviewKind {
- /// The requester holds a copy of the meeting on a visible calendar.
+ /// The requester holds a copy of the meeting on a visible calendar, or
+ /// sees the mentioned copy read-only through a channel share.
Access,
/// The event exists but is on no calendar the requester can see.
NoAccess,
@@ -401,7 +402,8 @@ pub struct CalendarMentionPreviewItem {
/// Visibility of the mentioned event to the requester.
#[serde(rename = "type")]
kind: CalendarMentionPreviewKind,
- /// Preview of the requester's own copy, present only with access.
+ /// Preview of the requester's own copy, or of the channel-shared copy,
+ /// present only with access.
#[serde(skip_serializing_if = "Option::is_none")]
event: Option<CalendarMentionEvent>,
}
diff --git a/crates/calendar_events/src/inbound/axum_router/test.rs b/crates/calendar_events/src/inbound/axum_router/test.rs
index 53ffe7c48c..1c2e0edcc3 100644
--- a/crates/calendar_events/src/inbound/axum_router/test.rs
+++ b/crates/calendar_events/src/inbound/axum_router/test.rs
@@ -48,7 +48,7 @@ fn mention_preview_items_serialize_the_preview_contract() {
event_id,
kind: CalendarMentionPreviewKind::Access,
event: Some(CalendarMentionEvent {
- viewer_event_id: event_id,
+ viewer_event_id: Some(event_id),
title: "Smart Macro Discussion".to_string(),
time: crate::domain::models::EventTime::Timed {
starts_at,
@@ -71,6 +71,16 @@ fn mention_preview_items_serialize_the_preview_contract() {
assert_eq!(json["event"]["time"]["kind"], "timed");
assert_eq!(json["event"]["attendeeCount"], 3);
+ // A channel-shared preview carries no event of the viewer's to open.
+ let mut shared = accessible;
+ if let Some(event) = shared.event.as_mut() {
+ event.viewer_event_id = None;
+ }
+ let json = serde_json::to_value(&shared).unwrap();
+ assert_eq!(json["type"], "access");
+ assert!(json["event"]["viewerEventId"].is_null());
+ assert_eq!(json["event"]["title"], "Smart Macro Discussion");
+
let no_access = CalendarMentionPreviewItem {
event_id,
kind: CalendarMentionPreviewKind::NoAccess,
diff --git a/crates/calendar_events/src/outbound/pg.rs b/crates/calendar_events/src/outbound/pg.rs
index 46c9cafd8d..9c4a62ae9d 100644
--- a/crates/calendar_events/src/outbound/pg.rs
+++ b/crates/calendar_events/src/outbound/pg.rs
@@ -321,7 +321,8 @@ struct OccurrenceJoinRow {
struct MentionPreviewRow {
mention_exists: bool,
- viewer_event_id: Option<Uuid>,
+ resolved_event_id: Option<Uuid>,
+ is_channel_shared: Option<bool>,
title: Option<String>,
location: Option<String>,
organizer_email: Option<String>,
@@ -1132,14 +1133,17 @@ impl CalendarRepository for PgCalendarRepository {
// The viewer lateral resolves the mentioned meeting to the
// requester's own projection through the shared iCalendar UID,
// preferring an owned copy over a delegated one and the mentioned
- // row itself among ties, so the preview only ever reads rows the
- // requester could already see on their calendar.
+ // row itself among ties. Only without such a copy does it fall back
+ // to the mentioned row, and only when that row was shared with a
+ // channel the requester currently belongs to and is still neither
+ // private nor confidential — the same rule entity access applies.
let rows = sqlx::query_as!(
MentionPreviewRow,
r#"
SELECT
(mentioned.id IS NOT NULL) AS "mention_exists!",
- viewer_event.id AS "viewer_event_id?",
+ viewer_event.id AS "resolved_event_id?",
+ viewer_event.is_channel_shared AS "is_channel_shared?",
viewer_event.title AS "title?",
viewer_event.location AS "location?",
viewer_event.organizer_email AS "organizer_email?",
@@ -1163,36 +1167,72 @@ impl CalendarRepository for PgCalendarRepository {
ON mentioned.id = requested.event_id
AND mentioned.status <> 'cancelled'
LEFT JOIN LATERAL (
- SELECT
- candidate.id,
- candidate.title,
- candidate.location,
- candidate.organizer_email,
- candidate.organizer_name,
- candidate.recurrence_lines,
- candidate.starts_at,
- candidate.ends_at,
- candidate.start_date,
- candidate.end_date,
- candidate.time_zone,
- candidate.updated_at
- FROM calendar_events candidate
- WHERE candidate.ical_uid = mentioned.ical_uid
- AND candidate.status <> 'cancelled'
- AND (
- candidate.owner_id = $1
- OR EXISTS (
+ SELECT resolved.*
+ FROM (
+ SELECT
+ candidate.id,
+ false AS is_channel_shared,
+ (candidate.owner_id = $1) AS is_owned,
+ (candidate.id = mentioned.id) AS is_mentioned,
+ candidate.title,
+ candidate.location,
+ candidate.organizer_email,
+ candidate.organizer_name,
+ candidate.recurrence_lines,
+ candidate.starts_at,
+ candidate.ends_at,
+ candidate.start_date,
+ candidate.end_date,
+ candidate.time_zone,
+ candidate.updated_at
+ FROM calendar_events candidate
+ WHERE candidate.ical_uid = mentioned.ical_uid
+ AND candidate.status <> 'cancelled'
+ AND (
+ candidate.owner_id = $1
+ OR EXISTS (
+ SELECT 1
+ FROM macro_user_links link
+ WHERE link.link_id = candidate.source_link_id
+ AND link.primary_macro_id = $1
+ )
+ )
+ UNION ALL
+ SELECT
+ mentioned.id,
+ true,
+ false,
+ true,
+ mentioned.title,
+ mentioned.location,
+ mentioned.organizer_email,
+ mentioned.organizer_name,
+ mentioned.recurrence_lines,
+ mentioned.starts_at,
+ mentioned.ends_at,
+ mentioned.start_date,
+ mentioned.end_date,
+ mentioned.time_zone,
+ mentioned.updated_at
+ WHERE mentioned.visibility IN ('default', 'public')
+ AND EXISTS (
SELECT 1
- FROM macro_user_links link
- WHERE link.link_id = candidate.source_link_id
- AND link.primary_macro_id = $1
- )
- )
+ FROM entity_access grant_row
+ JOIN comms_channel_participants participant
+ ON participant.channel_id::text = grant_row.source_id
+ AND participant.user_id = $1
+ AND participant.left_at IS NULL
+ WHERE grant_row.entity_id = mentioned.id
+ AND grant_row.entity_type = 'calendar_event'
+ AND grant_row.source_type = 'channel'
+ )
+ ) resolved
ORDER BY
- (candidate.owner_id = $1) DESC,
- (candidate.id = mentioned.id) DESC,
- candidate.updated_at DESC,
- candidate.id
+ resolved.is_channel_shared,
+ resolved.is_owned DESC,
+ resolved.is_mentioned DESC,
+ resolved.updated_at DESC,
+ resolved.id
LIMIT 1
) viewer_event ON true
LEFT JOIN LATERAL (
@@ -3966,9 +4006,10 @@ fn mention_preview_from_row(row: MentionPreviewRow) -> Result<CalendarMentionPre
if !row.mention_exists {
return Ok(CalendarMentionPreview::DoesNotExist);
}
- let Some(viewer_event_id) = row.viewer_event_id else {
+ let Some(resolved_event_id) = row.resolved_event_id else {
return Ok(CalendarMentionPreview::NoAccess);
};
+ let is_channel_shared = row.is_channel_shared.unwrap_or_default();
let time = if row.occurrence_key.is_some() {
row_time(
row.occurrence_starts_at,
@@ -3990,7 +4031,7 @@ fn mention_preview_from_row(row: MentionPreviewRow) -> Result<CalendarMentionPre
};
Ok(CalendarMentionPreview::Accessible(Box::new(
CalendarMentionEvent {
- viewer_event_id,
+ viewer_event_id: (!is_channel_shared).then_some(resolved_event_id),
title: row.title.unwrap_or_default(),
time,
occurrence_key: row.occurrence_key,
diff --git a/crates/calendar_events/src/outbound/pg/test.rs b/crates/calendar_events/src/outbound/pg/test.rs
index 1acf664c2f..06bdb5e4ac 100644
--- a/crates/calendar_events/src/outbound/pg/test.rs
+++ b/crates/calendar_events/src/outbound/pg/test.rs
@@ -4110,7 +4110,7 @@ async fn mention_previews_resolve_through_the_shared_uid(pool: PgPool) {
let CalendarMentionPreview::Accessible(own) = &previews[0] else {
panic!("author preview should be accessible: {:?}", previews[0]);
};
- assert_eq!(own.viewer_event_id, author_event_id);
+ assert_eq!(own.viewer_event_id, Some(author_event_id));
assert_eq!(own.title, "Smart Macro Discussion");
assert!(own.is_recurring);
assert_eq!(own.attendee_count, 1);
@@ -4133,11 +4133,192 @@ async fn mention_previews_resolve_through_the_shared_uid(pool: PgPool) {
let CalendarMentionPreview::Accessible(resolved) = &previews[0] else {
panic!("attendee preview should be accessible: {:?}", previews[0]);
};
- assert_eq!(resolved.viewer_event_id, attendee_event_id);
+ assert_eq!(resolved.viewer_event_id, Some(attendee_event_id));
assert_eq!(previews[1], CalendarMentionPreview::NoAccess);
assert_eq!(previews[2], CalendarMentionPreview::DoesNotExist);
}
+async fn share_with_channel(pool: &PgPool, event_id: Uuid, channel_id: Uuid) {
+ sqlx::query(
+ r#"
+ INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ($1, 'calendar_event', $2::uuid::text, 'channel', 'view')
+ "#,
+ )
+ .bind(event_id)
+ .bind(channel_id)
+ .execute(pool)
+ .await
+ .unwrap();
+}
+
+async fn insert_channel(pool: &PgPool, owner_id: &str, members: &[&str]) -> Uuid {
+ let channel_id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO comms_channels (id, channel_type, owner_id) VALUES ($1, 'private', $2)",
+ )
+ .bind(channel_id)
+ .bind(owner_id)
+ .execute(pool)
+ .await
+ .unwrap();
+ for member in members {
+ sqlx::query(
+ "INSERT INTO comms_channel_participants (channel_id, user_id, role) VALUES ($1, $2, 'member')",
+ )
+ .bind(channel_id)
+ .bind(*member)
+ .execute(pool)
+ .await
+ .unwrap();
+ }
+ channel_id
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn mention_previews_fall_back_to_a_channel_shared_projection(pool: PgPool) {
+ let author_id = "macro|[email protected]";
+ let attendee_id = "macro|[email protected]";
+ let member_id = "macro|[email protected]";
+ let former_id = "macro|[email protected]";
+ let stranger_id = "macro|[email protected]";
+ let author_link = insert_link(&pool, author_id).await;
+ let attendee_link = insert_link(&pool, attendee_id).await;
+ let repo = PgCalendarRepository::new(pool.clone());
+ let author_provider = provider_ids(&repo, author_link).await;
+ let attendee_provider = provider_ids(&repo, attendee_link).await;
+
+ let author_copy = timed_upsert(
+ author_id,
+ author_link,
+ author_provider,
+ "Pilates",
+ 1,
+ );
+ let shared_event_id = author_copy.event.id;
+ repo.upsert_event_fixture(author_copy).await.unwrap();
+ let attendee_copy = timed_upsert(
+ attendee_id,
+ attendee_link,
+ attendee_provider,
+ "Pilates",
+ 1,
+ );
+ let attendee_event_id = attendee_copy.event.id;
+ repo.upsert_event_fixture(attendee_copy).await.unwrap();
+ let mut private_copy = timed_upsert(
+ author_id,
+ author_link,
+ author_provider,
+ "Doctor",
+ 1,
+ );
+ private_copy.event.visibility = EventVisibility::Private;
+ let private_event_id = private_copy.event.id;
+ repo.upsert_event_fixture(private_copy).await.unwrap();
+ let unshared_copy = timed_upsert(
+ author_id,
+ author_link,
+ author_provider,
+ "Unshared",
+ 1,
+ );
+ let unshared_event_id = unshared_copy.event.id;
+ repo.upsert_event_fixture(unshared_copy).await.unwrap();
+
+ let channel_id = insert_channel(
+ &pool,
+ author_id,
+ &[author_id, attendee_id, member_id, former_id],
+ )
+ .await;
+ sqlx::query(
+ "UPDATE comms_channel_participants SET left_at = now() WHERE channel_id = $1 AND user_id = $2",
+ )
+ .bind(channel_id)
+ .bind(former_id)
+ .execute(&pool)
+ .await
+ .unwrap();
+ share_with_channel(&pool, shared_event_id, channel_id).await;
+ share_with_channel(&pool, private_event_id, channel_id).await;
+
+ let now = Utc.with_ymd_and_hms(2026, 7, 23, 0, 0, 0).unwrap();
+ let request = |event_id| CalendarMentionRequestItem {
+ event_id,
+ occurrence_key: None,
+ };
+
+ // A member without a copy sees the shared projection read-only.
+ let previews = repo
+ .mention_previews(
+ member_id,
+ vec![
+ request(shared_event_id),
+ request(private_event_id),
+ request(unshared_event_id),
+ ],
+ now,
+ )
+ .await
+ .unwrap();
+ let CalendarMentionPreview::Accessible(shared) = &previews[0] else {
+ panic!("member preview should be accessible: {:?}", previews[0]);
+ };
+ assert_eq!(shared.viewer_event_id, None);
+ assert_eq!(shared.title, "Pilates");
+ assert!(shared.occurrence_key.is_some());
+ // Private events stay hidden despite the grant, and a grant covers only
+ // the event it names.
+ assert_eq!(previews[1], CalendarMentionPreview::NoAccess);
+ assert_eq!(previews[2], CalendarMentionPreview::NoAccess);
+
+ // A member with their own copy keeps resolving to it.
+ let previews = repo
+ .mention_previews(attendee_id, vec![request(shared_event_id)], now)
+ .await
+ .unwrap();
+ let CalendarMentionPreview::Accessible(own) = &previews[0] else {
+ panic!("attendee preview should be accessible: {:?}", previews[0]);
+ };
+ assert_eq!(own.viewer_event_id, Some(attendee_event_id));
+
+ // So does the owner, who can open the private event they shared.
+ let previews = repo
+ .mention_previews(author_id, vec![request(private_event_id)], now)
+ .await
+ .unwrap();
+ let CalendarMentionPreview::Accessible(owned) = &previews[0] else {
+ panic!("owner preview should be accessible: {:?}", previews[0]);
+ };
+ assert_eq!(owned.viewer_event_id, Some(private_event_id));
+
+ // Nonparticipants and people who left the channel get nothing.
+ for outsider in [stranger_id, former_id] {
+ let previews = repo
+ .mention_previews(outsider, vec![request(shared_event_id)], now)
+ .await
+ .unwrap();
+ assert_eq!(previews[0], CalendarMentionPreview::NoAccess, "{outsider}");
+ }
+
+ // A cancelled event no longer previews for anyone.
+ sqlx::query("UPDATE calendar_events SET status = 'cancelled' WHERE id = $1")
+ .bind(shared_event_id)
+ .execute(&pool)
+ .await
+ .unwrap();
+ let previews = repo
+ .mention_previews(member_id, vec![request(shared_event_id)], now)
+ .await
+ .unwrap();
+ assert_eq!(previews[0], CalendarMentionPreview::DoesNotExist);
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn mention_preview_picks_the_requested_or_nearest_occurrence(pool: PgPool) {
let owner_id = "macro|[email protected]";
diff --git a/crates/channels/src/domain/models.rs b/crates/channels/src/domain/models.rs
index 227a463912..bdd4fcf3af 100644
--- a/crates/channels/src/domain/models.rs
+++ b/crates/channels/src/domain/models.rs
@@ -794,6 +794,8 @@ pub enum ReferencedShareItemType {
EmailThread,
/// Call entity.
Call,
+ /// Calendar event entity: one owner's projection of a meeting.
+ CalendarEvent,
}
impl ReferencedShareItemType {
@@ -806,6 +808,7 @@ impl ReferencedShareItemType {
"project" => Some(Self::Project),
"thread" | "email" | "email_thread" => Some(Self::EmailThread),
"call" => Some(Self::Call),
+ "calendar_event" => Some(Self::CalendarEvent),
_ => None,
}
}
@@ -819,6 +822,7 @@ impl ReferencedShareItemType {
Self::Project => "project",
Self::EmailThread => "thread",
Self::Call => "call",
+ Self::CalendarEvent => "calendar_event",
}
}
diff --git a/crates/channels/src/domain/reference_sharing.rs b/crates/channels/src/domain/reference_sharing.rs
index 7c9d47503d..a8c5252fc0 100644
--- a/crates/channels/src/domain/reference_sharing.rs
+++ b/crates/channels/src/domain/reference_sharing.rs
@@ -5,6 +5,10 @@ use entity_access::domain::models::AccessLevel;
/// Only owners may share session references, and automatic sharing grants view
/// access. Sending a reference never grants control of an agent session.
+///
+/// A calendar event is shareable only by someone holding it on their own
+/// calendar: its owner or a linked account. A member who sees the event only
+/// through an earlier channel share holds view access and cannot pass it on.
pub(crate) fn grant_level(
item_type: ReferencedShareItemType,
access: Option<AccessLevel>,
@@ -13,7 +17,11 @@ pub(crate) fn grant_level(
(ReferencedShareItemType::AgentSession, Some(AccessLevel::Owner)) => {
Some(AccessLevel::View)
}
- (ReferencedShareItemType::AgentSession, _) | (_, None) => None,
+ (ReferencedShareItemType::CalendarEvent, Some(level)) if level >= AccessLevel::Edit => {
+ Some(AccessLevel::View)
+ }
+ (ReferencedShareItemType::AgentSession | ReferencedShareItemType::CalendarEvent, _)
+ | (_, None) => None,
(_, Some(_)) => Some(AccessLevel::View),
}
}
diff --git a/crates/channels/src/domain/reference_sharing/test.rs b/crates/channels/src/domain/reference_sharing/test.rs
index fdc2887c42..c1834d03eb 100644
--- a/crates/channels/src/domain/reference_sharing/test.rs
+++ b/crates/channels/src/domain/reference_sharing/test.rs
@@ -36,3 +36,19 @@ fn existing_reference_types_keep_view_sharing() {
);
}
}
+
+#[test]
+fn only_calendar_holders_can_share_event_view_with_channel() {
+ for (access, expected) in [
+ (None, None),
+ (Some(AccessLevel::View), None),
+ (Some(AccessLevel::Comment), None),
+ (Some(AccessLevel::Edit), Some(AccessLevel::View)),
+ (Some(AccessLevel::Owner), Some(AccessLevel::View)),
+ ] {
+ assert_eq!(
+ grant_level(ReferencedShareItemType::CalendarEvent, access),
+ expected
+ );
+ }
+}
diff --git a/crates/channels/src/outbound/pg_channel_reference_share_permissions.rs b/crates/channels/src/outbound/pg_channel_reference_share_permissions.rs
index cf6479be9d..d2a97afbdd 100644
--- a/crates/channels/src/outbound/pg_channel_reference_share_permissions.rs
+++ b/crates/channels/src/outbound/pg_channel_reference_share_permissions.rs
@@ -82,14 +82,18 @@ async fn ensure_referenced_item_visible_to_channel(
.context("failed to insert thread share permissions")?;
}
- // Session channel grants are canonical entity-access rows. A reference must
- // preserve explicit sharing and the originating channel's control grant.
- if item.entity_type() == ReferencedShareItemType::AgentSession {
+ // Session and calendar event channel grants are canonical entity-access
+ // rows. A reference must preserve explicit sharing and the originating
+ // channel's control grant. Calendar events carry no SharePermission row.
+ if matches!(
+ item.entity_type(),
+ ReferencedShareItemType::AgentSession | ReferencedShareItemType::CalendarEvent
+ ) {
let mut transaction = db.begin().await?;
entity_access_db_utils::channel_share::insert_if_absent(
&mut transaction,
&entity_id,
- entity_access_db_utils::EntityType::AgentSession,
+ entity_access_db_type_for(item.entity_type()),
&channel_id,
level,
)
@@ -145,6 +149,7 @@ fn entity_access_type_for(item_type: ReferencedShareItemType) -> EntityType {
ReferencedShareItemType::Project => EntityType::Project,
ReferencedShareItemType::EmailThread => EntityType::EmailThread,
ReferencedShareItemType::Call => EntityType::Call,
+ ReferencedShareItemType::CalendarEvent => EntityType::CalendarEvent,
}
}
@@ -158,5 +163,6 @@ fn entity_access_db_type_for(
ReferencedShareItemType::Project => entity_access_db_utils::EntityType::Project,
ReferencedShareItemType::EmailThread => entity_access_db_utils::EntityType::EmailThread,
ReferencedShareItemType::Call => entity_access_db_utils::EntityType::Call,
+ ReferencedShareItemType::CalendarEvent => entity_access_db_utils::EntityType::CalendarEvent,
}
}
diff --git a/crates/channels/src/outbound/pg_channel_reference_share_permissions/test.rs b/crates/channels/src/outbound/pg_channel_reference_share_permissions/test.rs
index 91c12461f8..2d3f1320f3 100644
--- a/crates/channels/src/outbound/pg_channel_reference_share_permissions/test.rs
+++ b/crates/channels/src/outbound/pg_channel_reference_share_permissions/test.rs
@@ -49,3 +49,27 @@ async fn session_references_grant_view_and_preserve_existing_channel_access(pool
assert_eq!(levels, vec![existing.unwrap_or(AccessLevel::View)]);
}
}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn calendar_event_references_grant_the_channel_view_without_a_share_permission(pool: PgPool) {
+ let channel_id = Uuid::now_v7();
+ let event_id = Uuid::now_v7();
+ let item = ReferencedShareItem::from_raw(event_id.to_string(), "calendar_event").unwrap();
+ let level = grant_level(item.entity_type(), Some(AccessLevel::Owner)).unwrap();
+ for _ in 0..2 {
+ ensure_referenced_item_visible_to_channel(&pool, channel_id, &item, level)
+ .await
+ .unwrap();
+ }
+ let levels: Vec<AccessLevel> = sqlx::query_scalar(
+ r#"SELECT access_level FROM entity_access
+ WHERE entity_id = $1 AND entity_type = 'calendar_event' AND source_id = $2
+ AND source_type = 'channel' AND granted_from_project_id IS NULL"#,
+ )
+ .bind(event_id)
+ .bind(channel_id.to_string())
+ .fetch_all(&pool)
+ .await
+ .unwrap();
+ assert_eq!(levels, vec![AccessLevel::View]);
+}
diff --git a/crates/entity_access/src/outbound/pg_access_repo.rs b/crates/entity_access/src/outbound/pg_access_repo.rs
index d735047aca..46ddbea2cd 100644
--- a/crates/entity_access/src/outbound/pg_access_repo.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo.rs
@@ -154,20 +154,37 @@ impl AccessRepository for PgAccessRepository {
return Ok(None);
};
let user_id = user_id.as_ref();
- let is_owner = sqlx::query_scalar!(
+ // A channel share reaches current participants only, and only while
+ // the event is live and not marked private or confidential: the grant
+ // records that someone shared it, not that its details may outlive the
+ // owner's later decision to hide them.
+ let access = sqlx::query!(
r#"
- SELECT event.owner_id = $2 AS "is_owner!"
+ SELECT
+ event.owner_id = $2 AS "is_owner!",
+ EXISTS (
+ SELECT 1
+ FROM macro_user_links link
+ WHERE link.link_id = event.source_link_id
+ AND link.primary_macro_id = $2
+ ) AS "is_linked!",
+ (
+ event.status <> 'cancelled'
+ AND event.visibility IN ('default', 'public')
+ AND EXISTS (
+ SELECT 1
+ FROM entity_access grant_row
+ JOIN comms_channel_participants participant
+ ON participant.channel_id::text = grant_row.source_id
+ AND participant.user_id = $2
+ AND participant.left_at IS NULL
+ WHERE grant_row.entity_id = event.id
+ AND grant_row.entity_type = 'calendar_event'
+ AND grant_row.source_type = 'channel'
+ )
+ ) AS "is_channel_shared!"
FROM calendar_events event
WHERE event.id = $1
- AND (
- event.owner_id = $2
- OR EXISTS (
- SELECT 1
- FROM macro_user_links link
- WHERE link.link_id = event.source_link_id
- AND link.primary_macro_id = $2
- )
- )
"#,
event_id,
user_id,
@@ -176,11 +193,15 @@ impl AccessRepository for PgAccessRepository {
.await
.map_err(AccessError::from)?;
- Ok(is_owner.map(|is_owner| {
- if is_owner {
- AccessLevel::Owner
+ Ok(access.and_then(|access| {
+ if access.is_owner {
+ Some(AccessLevel::Owner)
+ } else if access.is_linked {
+ Some(AccessLevel::Edit)
+ } else if access.is_channel_shared {
+ Some(AccessLevel::View)
} else {
- AccessLevel::Edit
+ None
}
}))
}
diff --git a/crates/entity_access/src/outbound/pg_access_repo/test.rs b/crates/entity_access/src/outbound/pg_access_repo/test.rs
index 7e5c401f14..cd7c424dc3 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/test.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/test.rs
@@ -1157,3 +1157,109 @@ async fn reminder_access_is_owner_for_the_owner_and_nothing_for_anyone_else(
Ok(())
}
+
+async fn insert_calendar_event(pool: &PgPool, owner_id: &str, visibility: &str) -> Uuid {
+ let link_id = Uuid::now_v7();
+ sqlx::query(
+ r#"
+ INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider)
+ VALUES ($1, $2, $2, $1::text || '@example.com', 'GMAIL')
+ "#,
+ )
+ .bind(link_id)
+ .bind(owner_id)
+ .execute(pool)
+ .await
+ .unwrap();
+ let event_id = Uuid::now_v7();
+ sqlx::query(
+ r#"
+ INSERT INTO calendar_events (
+ id, owner_id, source_link_id, ical_uid, title, visibility,
+ canonical_source_kind, starts_at, ends_at
+ )
+ VALUES ($1, $2, $3, $1::text, 'Pilates', $4, 'google', now(), now() + interval '1 hour')
+ "#,
+ )
+ .bind(event_id)
+ .bind(owner_id)
+ .bind(link_id)
+ .bind(visibility)
+ .execute(pool)
+ .await
+ .unwrap();
+ event_id
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn calendar_event_channel_share_grants_current_participants_view(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let owner = "macro|[email protected]";
+ let member = "macro|[email protected]";
+ let former = "macro|[email protected]";
+ let stranger = "macro|[email protected]";
+ let shared = insert_calendar_event(&pool, owner, "default").await;
+ let private = insert_calendar_event(&pool, owner, "private").await;
+ let unshared = insert_calendar_event(&pool, owner, "default").await;
+
+ let channel_id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO comms_channels (id, channel_type, owner_id) VALUES ($1, 'private', $2)",
+ )
+ .bind(channel_id)
+ .bind(owner)
+ .execute(&pool)
+ .await?;
+ for (participant, left) in [(owner, false), (member, false), (former, true)] {
+ sqlx::query(
+ r#"
+ INSERT INTO comms_channel_participants (channel_id, user_id, role, left_at)
+ VALUES ($1, $2, 'member', CASE WHEN $3 THEN now() END)
+ "#,
+ )
+ .bind(channel_id)
+ .bind(participant)
+ .bind(left)
+ .execute(&pool)
+ .await?;
+ }
+ for event_id in [shared, private] {
+ sqlx::query(
+ r#"
+ INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ($1, 'calendar_event', $2::uuid::text, 'channel', 'view')
+ "#,
+ )
+ .bind(event_id)
+ .bind(channel_id)
+ .execute(&pool)
+ .await?;
+ }
+
+ let repo = PgAccessRepository::new(pool.clone());
+ let access = |event_id: Uuid, user: &'static str| {
+ let repo = repo.clone();
+ async move {
+ repo.get_calendar_event_access(&event_id.to_string(), Some(&user_id(user)))
+ .await
+ .unwrap()
+ }
+ };
+
+ assert_eq!(access(shared, owner).await, Some(AccessLevel::Owner));
+ assert_eq!(access(private, owner).await, Some(AccessLevel::Owner));
+ assert_eq!(access(shared, member).await, Some(AccessLevel::View));
+ assert_eq!(access(private, member).await, None);
+ assert_eq!(access(unshared, member).await, None);
+ assert_eq!(access(shared, former).await, None);
+ assert_eq!(access(shared, stranger).await, None);
+
+ sqlx::query("UPDATE calendar_events SET status = 'cancelled' WHERE id = $1")
+ .bind(shared)
+ .execute(&pool)
+ .await?;
+ assert_eq!(access(shared, member).await, None);
+ assert_eq!(access(shared, owner).await, Some(AccessLevel::Owner));
+ Ok(())
+}
diff --git a/crates/entity_access/src/outbound/pg_explain_access_repo.rs b/crates/entity_access/src/outbound/pg_explain_access_repo.rs
index f4439ecdef..86f802c986 100644
--- a/crates/entity_access/src/outbound/pg_explain_access_repo.rs
+++ b/crates/entity_access/src/outbound/pg_explain_access_repo.rs
@@ -1,9 +1,12 @@
use crate::domain::{
- models::{AccessError, AccessGrant, EntityType, ForeignEntityAuthEntity, UserTeamInfo},
+ models::{
+ AccessError, AccessGrant, AccessLevel, EntityType, ForeignEntityAuthEntity, UserTeamInfo,
+ },
ports::ExplainAccessRepository,
};
use crate::outbound::pg_access_repo::queries;
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use models_entity_access_management::EntityAccessSourceType;
use sqlx::PgPool;
use uuid::Uuid;
@@ -257,6 +260,34 @@ async fn explain_calendar_event_access(
.fetch_optional(pool)
.await?;
+ // Mirrors the access query: a channel share counts only for a current
+ // participant while the event is live and not private or confidential.
+ let channel_grants = sqlx::query!(
+ r#"
+ SELECT
+ grant_row.source_type AS "source_type!: EntityAccessSourceType",
+ grant_row.source_id,
+ grant_row.access_level AS "access_level!: AccessLevel",
+ grant_row.granted_from_project_id
+ FROM calendar_events event
+ JOIN entity_access grant_row
+ ON grant_row.entity_id = event.id
+ AND grant_row.entity_type = 'calendar_event'
+ AND grant_row.source_type = 'channel'
+ JOIN comms_channel_participants participant
+ ON participant.channel_id::text = grant_row.source_id
+ AND participant.user_id = $2
+ AND participant.left_at IS NULL
+ WHERE event.id = $1
+ AND event.status <> 'cancelled'
+ AND event.visibility IN ('default', 'public')
+ "#,
+ event_id,
+ user_id.as_ref(),
+ )
+ .fetch_all(pool)
+ .await?;
+
Ok(is_owner
.map(|is_owner| {
if is_owner {
@@ -266,6 +297,16 @@ async fn explain_calendar_event_access(
}
})
.into_iter()
+ .chain(
+ channel_grants
+ .into_iter()
+ .map(|row| AccessGrant::EntityAccess {
+ source_type: row.source_type,
+ source_id: row.source_id,
+ access_level: row.access_level,
+ granted_from_project_id: row.granted_from_project_id,
+ }),
+ )
.collect())
}
diff --git a/crates/soup_realtime/src/inbound/kafka_consumer.rs b/crates/soup_realtime/src/inbound/kafka_consumer.rs
index 11cef443b8..2b73a846dc 100644
--- a/crates/soup_realtime/src/inbound/kafka_consumer.rs
+++ b/crates/soup_realtime/src/inbound/kafka_consumer.rs
@@ -323,6 +323,8 @@ fn soup_entity_type_from_channel_reference(entity_type: &str) -> Option<EntityTy
ReferencedShareItemType::Project => Some(EntityType::Project),
ReferencedShareItemType::EmailThread => Some(EntityType::EmailThread),
ReferencedShareItemType::Call => Some(EntityType::Call),
+ // A shared event is previewed in place, never listed in the soup.
+ ReferencedShareItemType::CalendarEvent => None,
}
}
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 7c23cedd19..84f38348ce 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -663,6 +663,13 @@ none — and lists the next 90 days of teammate absences; clicking a row navigat
that date. Coverage depends on each teammate having connected their own calendar and using
Google's out-of-office event type.
+A calendar event mentioned in a channel message opens the calendar focused on the viewer's
+own copy of the meeting. When the sender holds the event on their own calendar, the mention
+also shares it read-only with the channel's current members: a member without a copy of their
+own sees the mention's title and time, and its hover card adds a `Shared with you · not on
+your calendar` line with no open action. Clicking such a mention shows that hover card
+instead of opening the calendar. Private and confidential events are never shared this way.
+
## Calls — `/app/component/calls`
Tabs `All` / `Missed` / `Unattended`; `Call` button to start one. Recordings, transcriptions
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index 2e11614547..bfd0f00755 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -1740,11 +1740,12 @@ export type CalendarEventSourceContent = {
/**
* Meeting-level fields shown in a calendar event mention preview, taken from
- * the requester's own projection of the meeting.
+ * the requester's own projection of the meeting, or — when the requester has
+ * none — from the mentioned projection a channel they belong to was given.
*/
export type CalendarMentionEvent = {
/**
- * Number of attendees on the requester's copy.
+ * Number of attendees on the previewed copy.
*/
attendeeCount: number;
/**
@@ -1779,14 +1780,17 @@ export type CalendarMentionEvent = {
*/
title: string;
/**
- * Entity update time of the requester's copy.
+ * Entity update time of the previewed copy.
*/
updatedAt: string;
/**
* The requester's own event entity for the mentioned meeting. Differs
* from the mentioned id when the mention came from another attendee.
+ * Absent when the meeting is on none of the requester's calendars and
+ * they see it only because it was shared with one of their channels:
+ * that preview is read-only and there is no event of theirs to open.
*/
- viewerEventId: string;
+ viewerEventId?: string | null;
};
/**
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 2dd5d5354c..45712139cf 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -17198,9 +17198,8 @@
},
"CalendarMentionEvent": {
"type": "object",
- "description": "Meeting-level fields shown in a calendar event mention preview, taken from\nthe requester's own projection of the meeting.",
+ "description": "Meeting-level fields shown in a calendar event mention preview, taken from\nthe requester's own projection of the meeting, or — when the requester has\nnone — from the mentioned projection a channel they belong to was given.",
"required": [
- "viewerEventId",
"title",
"time",
"isRecurring",
@@ -17210,7 +17209,7 @@
"properties": {
"attendeeCount": {
"type": "integer",
- "description": "Number of attendees on the requester's copy.",
+ "description": "Number of attendees on the previewed copy.",
"minimum": 0
},
"isRecurring": {
@@ -17244,12 +17243,12 @@
"updatedAt": {
"type": "string",
"format": "date-time",
- "description": "Entity update time of the requester's copy."
+ "description": "Entity update time of the previewed copy."
},
"viewerEventId": {
- "type": "string",
+ "type": ["string", "null"],
"format": "uuid",
- "description": "The requester's own event entity for the mentioned meeting. Differs\nfrom the mentioned id when the mention came from another attendee."
+ "description": "The requester's own event entity for the mentioned meeting. Differs\nfrom the mentioned id when the mention came from another attendee.\nAbsent when the meeting is on none of the requester's calendars and\nthey see it only because it was shared with one of their channels:\nthat preview is read-only and there is no event of theirs to open."
}
}
},
@@ -17265,7 +17264,7 @@
},
{
"$ref": "#/components/schemas/CalendarMentionEvent",
- "description": "Preview of the requester's own copy, present only with access."
+ "description": "Preview of the requester's own copy, or of the channel-shared copy,\npresent only with access."
}
]
},