Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(channel_bots): calendar UX in channel mentions (#6219)
gbirman149bcffa3dba
diff --git a/.sqlx/query-acd7979ca95295b44da587f433e2c20d0308d95e81db97ca65e37891824aee8c.json b/.sqlx/query-acd7979ca95295b44da587f433e2c20d0308d95e81db97ca65e37891824aee8c.jsonnew file mode 100644index 0000000000..ed7e5397e9--- /dev/null+++ b/.sqlx/query-acd7979ca95295b44da587f433e2c20d0308d95e81db97ca65e37891824aee8c.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT calendar.time_zone\n FROM email_links link\n JOIN calendar_accounts account ON account.email_link_id = link.id\n JOIN calendars calendar ON calendar.account_id = account.id\n WHERE NOT calendar.is_deleted\n AND account.sync_status <> 'disabled'\n AND calendar.is_primary\n AND (\n link.macro_id = $1\n OR EXISTS (\n SELECT 1\n FROM macro_user_links delegation\n WHERE delegation.link_id = link.id\n AND delegation.primary_macro_id = $1\n )\n )\n ORDER BY\n (link.macro_id = $1) DESC,\n link.is_primary DESC,\n link.created_at ASC\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "time_zone",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "acd7979ca95295b44da587f433e2c20d0308d95e81db97ca65e37891824aee8c"+}diff --git a/Cargo.lock b/Cargo.lockindex 77684958f0..e5c6aaec88 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3320,8 +3320,10 @@ dependencies = ["anyhow","async-trait","bot_id",+ "calendar_events","channels","chrono",+ "chrono-tz","futures","macro_user_id","models_pagination",diff --git a/apps/web/src/lib/queries/calendar/keys.ts b/apps/web/src/lib/queries/calendar/keys.tsindex 528cbdf155..1acab62b93 100644--- a/apps/web/src/lib/queries/calendar/keys.ts+++ b/apps/web/src/lib/queries/calendar/keys.ts@@ -7,6 +7,11 @@ export interface CalendarOccurrenceQueryRange {endDate: string;}+/** Mutation key shared by the RSVP mutation and the websocket refresh+ * handler, which must not refetch occurrences over in-flight optimistic+ * RSVP state. */+export const RSVP_MUTATION_KEY = ['calendar', 'rsvp'] as const;+export const calendarKeys = createQueryKeys('calendar', {visibleCalendars: null,occurrences: (diff --git a/apps/web/src/lib/queries/calendar/mention-preview.ts b/apps/web/src/lib/queries/calendar/mention-preview.tsindex c141ef4277..befbb7b919 100644--- a/apps/web/src/lib/queries/calendar/mention-preview.ts+++ b/apps/web/src/lib/queries/calendar/mention-preview.ts@@ -1,4 +1,6 @@import { queryClient } from '@queries/client';+import { previewKeys } from '@queries/preview/keys';+import type { PreviewItem } from '@queries/preview/types';import { storageServiceClient } from '@service-storage/client';import type { CalendarMentionEvent } from '@service-storage/generated/schemas/calendarMentionEvent';import { useQuery } from '@tanstack/solid-query';@@ -7,6 +9,40 @@ import { calendarKeys } from './keys';const MENTION_PREVIEW_STALE_TIME = 60_000;+/**+ * Revalidate every cached projection of mentioned calendar events — the+ * shared item-preview entries that message chips render and the calendar+ * block's occurrence-scoped entries — scoped to one event when given.+ * Mounted chips refetch immediately, so a rename or reschedule reaches+ * already-rendered mentions.+ */+export function invalidateCalendarEventPreviews(eventId?: string): void {+ if (eventId) {+ queryClient.invalidateQueries({+ queryKey: previewKeys.item(eventId).queryKey,+ });+ } else {+ queryClient.invalidateQueries({+ queryKey: previewKeys._def,+ // The key carries no type, so it can only be read from cached data.+ // Entries without data need no sweep: null is a cached+ // channel-message-context miss (never a calendar event), and+ // undefined means no fetch has resolved — invalidation cannot outrun+ // it, since an in-flight fetch is joined rather than restarted and a+ // fresh mount refetches regardless.+ predicate: (query) => {+ const data = query.state.data as PreviewItem | null | undefined;+ return data != null && data.type === 'calendar_event';+ },+ });+ }+ queryClient.invalidateQueries({+ queryKey: eventId+ ? [...calendarKeys.mentionPreview._def, eventId]+ : calendarKeys.mentionPreview._def,+ });+}+async function fetchPreview(eventId: string,occurrenceKey?: stringdiff --git a/apps/web/src/lib/queries/calendar/mutations.ts b/apps/web/src/lib/queries/calendar/mutations.tsindex 818283e6d8..b8ba3af712 100644--- a/apps/web/src/lib/queries/calendar/mutations.ts+++ b/apps/web/src/lib/queries/calendar/mutations.ts@@ -13,7 +13,8 @@ import type { AttendeeResponseStatus } from '@service-storage/generated/schemas/import type { CalendarOccurrenceItem } from '@service-storage/generated/schemas/calendarOccurrenceItem';import type { EventTime } from '@service-storage/generated/schemas/eventTime';import { useMutation } from '@tanstack/solid-query';-import { calendarKeys } from './keys';+import { calendarKeys, RSVP_MUTATION_KEY } from './keys';+import { invalidateCalendarEventPreviews } from './mention-preview';import {type CalendarOccurrencesData,invalidateCalendarOccurrences,@@ -100,8 +101,6 @@ type RsvpCallbacks = MutationCallbacks<RsvpMutationContext>;-const RSVP_MUTATION_KEY = ['calendar', 'rsvp'] as const;-type RsvpMutationContext = CalendarMutationContext & {/** Drops this mutation's writer stamps once it has settled. */release: () => void;@@ -249,11 +248,12 @@ export function useRsvpCalendarEventMutation(callbacks?: RsvpCallbacks) {};},onError: (_error, _args, context) => context?.rollback(),- onSettled: (_data, _error, _args, context) => {+ onSettled: (_data, _error, args, context) => {context?.release();if (queryClient.isMutating({ mutationKey: RSVP_MUTATION_KEY }) > 1) {return;}+ invalidateCalendarEventPreviews(args.eventId);return invalidateCalendarOccurrences();},},@@ -317,7 +317,10 @@ export function useDeleteCalendarEventMutation(callbacks?: DeleteCallbacks) {items.filter((item) => survivesDeletion(item, args))),onError: (_error, _args, context) => context?.rollback(),- onSettled: () => invalidateCalendarOccurrences(),+ onSettled: (_data, _error, args) => {+ invalidateCalendarEventPreviews(args.eventId);+ return invalidateCalendarOccurrences();+ },},callbacks),@@ -394,7 +397,10 @@ export function useUpdateCalendarEventMutation(callbacks?: UpdateCallbacks) {)),onError: (_error, _args, context) => context?.rollback(),- onSettled: () => invalidateCalendarOccurrences(),+ onSettled: (_data, _error, args) => {+ invalidateCalendarEventPreviews(args.eventId);+ return invalidateCalendarOccurrences();+ },},callbacks),diff --git a/apps/web/src/lib/queries/calendar/sync.ts b/apps/web/src/lib/queries/calendar/sync.tsindex b037654240..80f9448c96 100644--- a/apps/web/src/lib/queries/calendar/sync.ts+++ b/apps/web/src/lib/queries/calendar/sync.ts@@ -1,29 +1,31 @@import { queryClient } from '@queries/client';-import { calendarKeys } from './keys';+import { calendarKeys, RSVP_MUTATION_KEY } from './keys';+import { invalidateCalendarEventPreviews } from './mention-preview';import { invalidateCalendarOccurrences } from './occurrences';+import { invalidateTeamOutOfOffice } from './team-ooo';/*** Refetches everything the calendar UI reads: every mounted occurrence- * viewport and the calendar list, which also carries per-calendar colors and- * names.+ * viewport, the calendar list (which also carries per-calendar colors and+ * names), teammates' out-of-office overlays, and the cached previews behind+ * calendar mention chips.*/export function invalidateCalendarViews(): void {invalidateCalendarOccurrences();+ invalidateCalendarEventPreviews();+ invalidateTeamOutOfOffice();queryClient.invalidateQueries({queryKey: calendarKeys.visibleCalendars.queryKey,});}/**- * Handles `refresh_calendar` websocket events: a sync run committed- * provider-side changes for one of the viewer's (owned or delegated)- * inboxes, so mounted calendar viewports refetch. The calendar list is- * invalidated too, since the same sync discovers new calendars and- * renames/recolors existing ones.- *- * Macro-originated mutations don't need this signal in the acting tab —- * they persist the provider echo synchronously — but their sync echo- * flows through here, which is what keeps other tabs and devices fresh.+ * Handles `refresh_calendar` websocket events: a provider sync run — or a+ * Macro-originated mutation, which nudges every viewer of the link+ * including the acting tab — committed changes for one of the viewer's+ * (owned or delegated) inboxes, so mounted calendar viewports refetch. The+ * calendar list is invalidated too, since a sync discovers new calendars+ * and renames/recolors existing ones.*/export function handleRefreshCalendar(payload: unknown): void {const event =@@ -32,5 +34,15 @@ export function handleRefreshCalendar(payload: unknown): void {: undefined;if (event?.event !== 'synced' || typeof event.link_id !== 'string') return;- invalidateCalendarViews();+ // An in-flight RSVP holds optimistic occurrence state a refetch would+ // clobber; the last RSVP to settle re-invalidates occurrences itself, so+ // only the caches without optimistic writes refresh meanwhile.+ if (queryClient.isMutating({ mutationKey: RSVP_MUTATION_KEY }) === 0) {+ invalidateCalendarOccurrences();+ }+ invalidateCalendarEventPreviews();+ invalidateTeamOutOfOffice();+ queryClient.invalidateQueries({+ queryKey: calendarKeys.visibleCalendars.queryKey,+ });}diff --git a/apps/web/src/lib/queries/calendar/tests/mutations.test.tsx b/apps/web/src/lib/queries/calendar/tests/mutations.test.tsxindex 1ff3adc67b..798332f1d5 100644--- a/apps/web/src/lib/queries/calendar/tests/mutations.test.tsx+++ b/apps/web/src/lib/queries/calendar/tests/mutations.test.tsx@@ -1,3 +1,4 @@+import { previewKeys } from '@queries/preview/keys';import type { CalendarOccurrenceItem } from '@service-storage/generated/schemas/calendarOccurrenceItem';import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';import { err, ok } from 'neverthrow';@@ -419,7 +420,12 @@ describe('useRsvpCalendarEventMutation', () => {second.resolve(ok({ id: 'event-1' }));await secondMutation;- expect(invalidateSpy).toHaveBeenCalledTimes(1);+ expect(invalidateSpy).toHaveBeenCalledWith({+ queryKey: calendarKeys.occurrences._def,+ });+ expect(invalidateSpy).toHaveBeenCalledWith({+ queryKey: previewKeys.item('event-1').queryKey,+ });});});diff --git a/apps/web/src/lib/queries/calendar/tests/sync.test.ts b/apps/web/src/lib/queries/calendar/tests/sync.test.tsindex eef39123a9..859e5cd9e6 100644--- a/apps/web/src/lib/queries/calendar/tests/sync.test.ts+++ b/apps/web/src/lib/queries/calendar/tests/sync.test.ts@@ -3,10 +3,14 @@ import { calendarKeys } from '../keys';import { handleRefreshCalendar } from '../sync';const invalidateQueriesMock = vi.hoisted(() => vi.fn());+const isMutatingMock = vi.hoisted(() => vi.fn());const invalidateCalendarOccurrencesMock = vi.hoisted(() => vi.fn());vi.mock('../../client', () => ({- queryClient: { invalidateQueries: invalidateQueriesMock },+ queryClient: {+ invalidateQueries: invalidateQueriesMock,+ isMutating: isMutatingMock,+ },}));vi.mock('../occurrences', () => ({@@ -16,6 +20,7 @@ vi.mock('../occurrences', () => ({describe('handleRefreshCalendar', () => {beforeEach(() => {vi.clearAllMocks();+ isMutatingMock.mockReturnValue(0);});it('refetches occurrence viewports and the calendar list on synced', () => {@@ -28,6 +33,23 @@ describe('handleRefreshCalendar', () => {expect(invalidateQueriesMock).toHaveBeenCalledWith({queryKey: calendarKeys.visibleCalendars.queryKey,});+ expect(invalidateQueriesMock).toHaveBeenCalledWith({+ queryKey: calendarKeys.teamOutOfOffice._def,+ });+ });++ it('defers the occurrence refetch while an RSVP is in flight', () => {+ isMutatingMock.mockReturnValue(1);++ handleRefreshCalendar({+ event: 'synced',+ link_id: '019fdd65-dcc1-74fb-a9c6-8162c11c5854',+ });++ expect(invalidateCalendarOccurrencesMock).not.toHaveBeenCalled();+ expect(invalidateQueriesMock).toHaveBeenCalledWith({+ queryKey: calendarKeys.visibleCalendars.queryKey,+ });});it('ignores malformed or unknown payloads', () => {diff --git a/apps/web/src/lib/queries/preview/preview.ts b/apps/web/src/lib/queries/preview/preview.tsindex 0793636e21..d9efd1bafc 100644--- a/apps/web/src/lib/queries/preview/preview.ts+++ b/apps/web/src/lib/queries/preview/preview.ts@@ -42,11 +42,19 @@ const SIMULATE_FAILURE = false;const PREVIEW_STALE_TIME = 60 * 1000 * 60 * 24; // 24 hours+/** Calendar events rename and reschedule far more often than documents, and+ * their preview carries the title and datetime chips render — so they go+ * stale on the mention-preview cadence rather than the 24h default. */+const CALENDAR_EVENT_PREVIEW_STALE_TIME = 60 * 1000;+function itemPreviewQueryOptions(item: ItemEntity,enabled = true,staleTime = PREVIEW_STALE_TIME) {+ if (item.type === 'calendar_event') {+ staleTime = Math.min(staleTime, CALENDAR_EVENT_PREVIEW_STALE_TIME);+ }return {queryKey: previewKeys.item(item.id).queryKey,queryFn: async () => {diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex edd533c436..2dc088e479 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts@@ -3109,7 +3109,8 @@ export interface ListCalendarsToolResponse {export interface ToolCalendar {/*** Calendar id; pass as `calendarId` to CreateCalendarEvent to target- * this calendar.+ * this calendar. Not a mentionable entity: never put it in a mention+ * tag — only individual calendar events can be mentioned.*/calendarId: string;/**diff --git a/crates/calendar_events/src/domain/mutations.rs b/crates/calendar_events/src/domain/mutations.rsindex 10084d37bd..318d23cbac 100644--- a/crates/calendar_events/src/domain/mutations.rs+++ b/crates/calendar_events/src/domain/mutations.rs@@ -22,10 +22,10 @@ use super::{ports::{CalendarAccessTokenProvider, CalendarDeletionScope, CalendarEventChange,CalendarEventWrite, CalendarEventWriteOutcome, CalendarMutationError,- CalendarMutationService, CalendarRepository, CalendarRsvpScope, CalendarTokenError,- CalendarUpdateScope, GoogleCalendarMutationProvider, GoogleInstanceUpdateOutcome,- GoogleProviderError, GoogleProviderErrorKind, GoogleRsvpOutcome,- GoogleSeriesMutationOutcome, RetiredCalendarEvent,+ CalendarMutationService, CalendarRefreshNotifier, CalendarRepository, CalendarRsvpScope,+ CalendarTokenError, CalendarUpdateScope, GoogleCalendarMutationProvider,+ GoogleInstanceUpdateOutcome, GoogleProviderError, GoogleProviderErrorKind,+ GoogleRsvpOutcome, GoogleSeriesMutationOutcome, RetiredCalendarEvent,},};use crate::domain::events::{CalendarEventMetadata, CalendarMacroEvent, CalendarTopicEvent};@@ -33,27 +33,30 @@ use macro_event_broker::MacroEventBroker;/// Calendar mutation use cases with provider, token, and persistence/// details behind ports.-pub struct CalendarMutationServiceImpl<R, G, T, B> {+pub struct CalendarMutationServiceImpl<R, G, T, B, N> {repository: R,provider: G,tokens: T,macro_event_broker: B,+ refresh: N,}-impl<R, G, T, B> CalendarMutationServiceImpl<R, G, T, B>+impl<R, G, T, B, N> CalendarMutationServiceImpl<R, G, T, B, N>whereR: CalendarRepository,G: GoogleCalendarMutationProvider,T: CalendarAccessTokenProvider,B: MacroEventBroker,+ N: CalendarRefreshNotifier,{/// Construct the service from its ports.- pub fn new(repository: R, provider: G, tokens: T, macro_event_broker: B) -> Self {+ pub fn new(repository: R, provider: G, tokens: T, macro_event_broker: B, refresh: N) -> Self {Self {repository,provider,tokens,macro_event_broker,+ refresh,}}@@ -88,6 +91,21 @@ where}}+ /// Announce retired events and, when anything was actually retired, nudge+ /// the link's calendar viewers to refetch their projections.+ async fn announce_retirements(+ &self,+ owner_id: &str,+ email_link_id: Uuid,+ retired: Vec<RetiredCalendarEvent>,+ ) {+ if retired.is_empty() {+ return;+ }+ self.publish_retirements(retired);+ self.refresh.calendar_changed(owner_id, email_link_id).await;+ }+/// Announce what a write did to the canonical row. A write that changed/// nothing publishes nothing, so an idempotent replay stays quiet.fn publish_write_outcome(&self, outcome: &CalendarEventWriteOutcome) {@@ -141,6 +159,8 @@ whereupsert: CalendarEventUpsert,) -> Result<CalendarEvent, CalendarMutationError> {let mut event = upsert.event.clone();+ let super::models::CalendarEventSource::Google(source) = &upsert.source;+ let email_link_id = source.email_link_id;let outcome = self.repository.upsert_event(CalendarEventWrite::UserMutation(upsert))@@ -148,6 +168,11 @@ where.map_err(|error| CalendarMutationError::PersistFailed(format!("{error:?}")))?;event.id = outcome.event_id;self.publish_write_outcome(&outcome);+ if outcome.change != CalendarEventChange::Unchanged {+ self.refresh+ .calendar_changed(&outcome.owner_id, email_link_id)+ .await;+ }if let Some(viewer) = viewer {viewer.mark_attendees(&mut event.attendees);}@@ -155,12 +180,13 @@ where}}-impl<R, G, T, B> CalendarMutationService for CalendarMutationServiceImpl<R, G, T, B>+impl<R, G, T, B, N> CalendarMutationService for CalendarMutationServiceImpl<R, G, T, B, N>whereR: CalendarRepository,G: GoogleCalendarMutationProvider,T: CalendarAccessTokenProvider,B: MacroEventBroker,+ N: CalendarRefreshNotifier,{#[tracing::instrument(skip(self, requester_id, draft), err)]async fn create_event(@@ -388,7 +414,8 @@ where).await.map_err(|error| CalendarMutationError::PersistFailed(format!("{error:?}")))?;- self.publish_retirements(retired);+ self.announce_retirements(&target.owner_id, target.email_link_id, retired)+ .await;Ok(())}}@@ -459,16 +486,22 @@ where.ok_or(CalendarMutationError::NotFound)?;self.release_watch_channels(email_link_id, &disconnected).await;+ // The purge removed whole calendars, and no sync echo will ever+ // arrive for a disconnected link, so viewers have to be nudged here.+ self.refresh+ .calendar_changed(requester_id, email_link_id)+ .await;Ok(())}}-impl<R, G, T, B> CalendarMutationServiceImpl<R, G, T, B>+impl<R, G, T, B, N> CalendarMutationServiceImpl<R, G, T, B, N>whereR: CalendarRepository,G: GoogleCalendarMutationProvider,T: CalendarAccessTokenProvider,B: MacroEventBroker,+ N: CalendarRefreshNotifier,{/// Close the push channels a disconnected calendar left open. Best-effort:/// the local calendars are already gone, so a notification that still@@ -539,7 +572,8 @@ where.unwrap_or_default();// The row may be gone now, so search cannot rediscover this by// re-reading Postgres — the retirement has to be announced.- self.publish_retirements(retired);+ self.announce_retirements(&target.owner_id, target.email_link_id, retired)+ .await;}}diff --git a/crates/calendar_events/src/domain/mutations/test.rs b/crates/calendar_events/src/domain/mutations/test.rsindex c07ca78593..484334432a 100644--- a/crates/calendar_events/src/domain/mutations/test.rs+++ b/crates/calendar_events/src/domain/mutations/test.rs@@ -358,6 +358,13 @@ impl CalendarRepository for FakeRepo {Ok(self.visible_calendars.clone())}+ async fn primary_time_zone(+ &self,+ _requester_id: &str,+ ) -> Result<Option<String>, rootcause::Report> {+ Ok(None)+ }+async fn owned_inbox_emails(&self,_requester_id: &str,@@ -675,21 +682,61 @@ impl macro_event_broker::MacroEventBroker for RecordingEventBroker {}}-fn service(+/// Records every viewer refresh nudge the service emits.+#[derive(Clone, Default)]+struct RecordingRefreshNotifier {+ notified: Arc<Mutex<Vec<(String, Uuid)>>>,+}++impl CalendarRefreshNotifier for RecordingRefreshNotifier {+ async fn calendar_changed(&self, owner_id: &str, email_link_id: Uuid) {+ self.notified+ .lock()+ .expect("notifier lock")+ .push((owner_id.to_string(), email_link_id));+ }+}++type TestMutationService = CalendarMutationServiceImpl<+ FakeRepo,+ FakeProvider,+ FakeTokens,+ RecordingEventBroker,+ RecordingRefreshNotifier,+>;++fn service(repo: FakeRepo, provider: FakeProvider, tokens: FakeTokens) -> TestMutationService {+ service_with_broker(repo, provider, tokens, RecordingEventBroker::default())+}++fn service_with_broker(repo: FakeRepo,provider: FakeProvider,tokens: FakeTokens,-) -> CalendarMutationServiceImpl<FakeRepo, FakeProvider, FakeTokens, RecordingEventBroker> {- CalendarMutationServiceImpl::new(repo, provider, tokens, RecordingEventBroker::default())+ broker: RecordingEventBroker,+) -> TestMutationService {+ CalendarMutationServiceImpl::new(+ repo,+ provider,+ tokens,+ broker,+ RecordingRefreshNotifier::default(),+ )}-fn service_with_broker(+fn service_with_refresh(repo: FakeRepo,provider: FakeProvider,tokens: FakeTokens,- broker: RecordingEventBroker,-) -> CalendarMutationServiceImpl<FakeRepo, FakeProvider, FakeTokens, RecordingEventBroker> {- CalendarMutationServiceImpl::new(repo, provider, tokens, broker)+ refresh: RecordingRefreshNotifier,+) -> TestMutationService {+ CalendarMutationServiceImpl::new(+ repo,+ provider,+ tokens,+ RecordingEventBroker::default(),+ refresh,+ )}#[tokio::test]@@ -886,6 +933,50 @@ async fn a_write_that_changed_nothing_publishes_nothing() {);}+#[tokio::test]+async fn a_persisted_mutation_nudges_the_links_calendar_viewers() {+ let repo = FakeRepo {+ creation_target: Some(creation_target(false)),+ write_change: CalendarEventChange::Updated,+ ..FakeRepo::default()+ };+ let refresh = RecordingRefreshNotifier::default();+ service_with_refresh(+ repo,+ FakeProvider::new(FakeProviderBehavior::Echo),+ FakeTokens::ok(),+ refresh.clone(),+ )+ .create_event("macro|user", None, None, draft())+ .await+ .unwrap();++ let notified = refresh.notified.lock().expect("notifier lock").clone();+ assert_eq!(notified.len(), 1);+ assert_eq!(notified[0].0, "macro|[email protected]");+}++#[tokio::test]+async fn a_write_that_changed_nothing_sends_no_refresh_nudge() {+ let repo = FakeRepo {+ creation_target: Some(creation_target(false)),+ write_change: CalendarEventChange::Unchanged,+ ..FakeRepo::default()+ };+ let refresh = RecordingRefreshNotifier::default();+ service_with_refresh(+ repo,+ FakeProvider::new(FakeProviderBehavior::Echo),+ FakeTokens::ok(),+ refresh.clone(),+ )+ .create_event("macro|user", None, None, draft())+ .await+ .unwrap();++ assert!(refresh.notified.lock().expect("notifier lock").is_empty());+}+#[tokio::test]async fn deleting_a_series_publishes_deleted_per_removed_event() {// Retiring a recurring master's source also retires its expanded@@ -2109,6 +2200,30 @@ async fn disconnecting_calendar_closes_every_open_watch_channel() {);}+#[tokio::test]+async fn disconnecting_calendar_nudges_the_links_calendar_viewers() {+ let link_id = Uuid::now_v7();+ let repo = FakeRepo {+ disconnected: Some(disconnected(&[])),+ ..FakeRepo::default()+ };+ let refresh = RecordingRefreshNotifier::default();+ service_with_refresh(+ repo,+ FakeProvider::new(FakeProviderBehavior::Echo),+ FakeTokens::ok(),+ refresh.clone(),+ )+ .disconnect_calendar("macro|user", link_id)+ .await+ .unwrap();++ assert_eq!(+ refresh.notified.lock().expect("notifier lock").as_slice(),+ [("macro|user".to_string(), link_id)]+ );+}+/// The local removal has already committed by the time channels are closed, so/// a provider or token failure must not report the disconnect as failed — the/// stale channel resolves to no watch target and expires on its own.diff --git a/crates/calendar_events/src/domain/ports.rs b/crates/calendar_events/src/domain/ports.rsindex e6f81537ae..436d41421e 100644--- a/crates/calendar_events/src/domain/ports.rs+++ b/crates/calendar_events/src/domain/ports.rs@@ -328,6 +328,14 @@ pub trait CalendarOccurrenceService: Send + Sync + 'static {range: OccurrenceRange,limit: u16,) -> impl Future<Output = Result<Vec<TeamOutOfOffice>, Report>> + Send;++ /// The IANA time zone of the requester's primary calendar, resolved the+ /// same way event creation picks its default target. `None` when no+ /// calendar is connected or the provider reported no zone.+ fn primary_time_zone(+ &self,+ requester_id: &str,+ ) -> impl Future<Output = Result<Option<String>, Report>> + Send;}/// What a write did to one event's canonical `calendar_events` row.@@ -553,6 +561,14 @@ pub trait CalendarRepository: Send + Sync + 'static {requester_id: &str,) -> impl Future<Output = Result<Vec<VisibleCalendar>, Report>> + Send;+ /// The IANA time zone of the requester's primary calendar, resolved the+ /// same way [`get_creation_target`](Self::get_creation_target) picks its+ /// default target.+ fn primary_time_zone(+ &self,+ requester_id: &str,+ ) -> impl Future<Output = Result<Option<String>, Report>> + Send;+/// Addresses of every connected inbox the requester owns/// (`email_links.macro_id = requester`). Raw and unnormalized;/// [`ActorInboxes::from_owned`] is the single normalization point.@@ -574,6 +590,19 @@ pub trait CalendarRepository: Send + Sync + 'static {) -> impl Future<Output = Result<Vec<RetiredCalendarEvent>, Report>> + Send;}+/// Outbound port that nudges a connected inbox's calendar viewers — the link+/// owner plus its delegates — to refetch their calendar projections after a+/// Macro-originated mutation changed them. Best effort: implementations log+/// and swallow delivery failures, since the mutation is already committed.+pub trait CalendarRefreshNotifier: Send + Sync + 'static {+ /// Signal that `email_link_id`'s calendar projection changed.+ fn calendar_changed(+ &self,+ owner_id: &str,+ email_link_id: Uuid,+ ) -> impl Future<Output = ()> + Send;+}+/// Inbound service port for user-initiated calendar event mutations.pub trait CalendarMutationService: Send + Sync + 'static {/// Create an event on the selected calendar — or the requester's (ordiff --git a/crates/calendar_events/src/domain/service.rs b/crates/calendar_events/src/domain/service.rsindex 876c9daf6a..e4b5bfb612 100644--- a/crates/calendar_events/src/domain/service.rs+++ b/crates/calendar_events/src/domain/service.rs@@ -171,6 +171,12 @@ where.await}+ /// The IANA time zone of the requester's primary calendar.+ #[tracing::instrument(skip(self, requester_id), err)]+ pub async fn primary_time_zone(&self, requester_id: &str) -> Result<Option<String>, Report> {+ self.repository.primary_time_zone(requester_id).await+ }+/// Re-arm the watched inbox's sync job for a push notification whose/// channel token the adapter already verified. Returns whether the/// notification matched an active channel.@@ -240,6 +246,13 @@ where) -> impl Future<Output = Result<Vec<super::models::TeamOutOfOffice>, Report>> + Send {CalendarService::list_team_out_of_office(self, requester_id, range, limit)}++ fn primary_time_zone(+ &self,+ requester_id: &str,+ ) -> impl Future<Output = Result<Option<String>, Report>> + Send {+ CalendarService::primary_time_zone(self, requester_id)+ }}/// Orchestrates a Google account backfill while keeping HTTP and SQL behind ports.diff --git a/crates/calendar_events/src/domain/service/test.rs b/crates/calendar_events/src/domain/service/test.rsindex 68d72f698a..2885410b07 100644--- a/crates/calendar_events/src/domain/service/test.rs+++ b/crates/calendar_events/src/domain/service/test.rs@@ -137,6 +137,10 @@ impl CalendarRepository for FakeRepo {Ok(Vec::new())}+ async fn primary_time_zone(&self, _requester_id: &str) -> Result<Option<String>, Report> {+ Ok(None)+ }+async fn owned_inbox_emails(&self, _requester_id: &str) -> Result<Vec<String>, Report> {Ok(Vec::new())}diff --git a/crates/calendar_events/src/inbound/toolset/list_calendars.rs b/crates/calendar_events/src/inbound/toolset/list_calendars.rsindex 528b2c8dec..ce8a71cc13 100644--- a/crates/calendar_events/src/inbound/toolset/list_calendars.rs+++ b/crates/calendar_events/src/inbound/toolset/list_calendars.rs@@ -15,7 +15,8 @@ use crate::domain::ports::{CalendarMutationService, CalendarOccurrenceService};#[serde(rename_all = "camelCase")]pub struct ToolCalendar {/// Calendar id; pass as `calendarId` to CreateCalendarEvent to target- /// this calendar.+ /// this calendar. Not a mentionable entity: never put it in a mention+ /// tag — only individual calendar events can be mentioned.pub calendar_id: uuid::Uuid,/// Provider display name.pub name: String,diff --git a/crates/calendar_events/src/inbound/toolset/test.rs b/crates/calendar_events/src/inbound/toolset/test.rsindex 5b4cdf2394..9e3ac8798e 100644--- a/crates/calendar_events/src/inbound/toolset/test.rs+++ b/crates/calendar_events/src/inbound/toolset/test.rs@@ -267,6 +267,13 @@ impl CalendarOccurrenceService for MockOccurrences {) -> Result<Vec<crate::domain::models::TeamOutOfOffice>, rootcause::Report> {unreachable!("no calendar tool lists team out-of-office")}++ async fn primary_time_zone(+ &self,+ _requester_id: &str,+ ) -> Result<Option<String>, rootcause::Report> {+ unreachable!("no calendar tool resolves the primary time zone")+ }}fn context(diff --git a/crates/calendar_events/src/outbound/pg.rs b/crates/calendar_events/src/outbound/pg.rsindex 40e96da861..7329894220 100644--- a/crates/calendar_events/src/outbound/pg.rs+++ b/crates/calendar_events/src/outbound/pg.rs@@ -1805,6 +1805,40 @@ impl CalendarRepository for PgCalendarRepository {}))}+ #[tracing::instrument(skip(self, requester_id), err)]+ async fn primary_time_zone(&self, requester_id: &str) -> Result<Option<String>, Report> {+ let time_zone = sqlx::query_scalar!(+ r#"+ SELECT calendar.time_zone+ FROM email_links link+ JOIN calendar_accounts account ON account.email_link_id = link.id+ JOIN calendars calendar ON calendar.account_id = account.id+ WHERE NOT calendar.is_deleted+ AND account.sync_status <> 'disabled'+ AND calendar.is_primary+ AND (+ link.macro_id = $1+ OR EXISTS (+ SELECT 1+ FROM macro_user_links delegation+ WHERE delegation.link_id = link.id+ AND delegation.primary_macro_id = $1+ )+ )+ ORDER BY+ (link.macro_id = $1) DESC,+ link.is_primary DESC,+ link.created_at ASC+ LIMIT 1+ "#,+ requester_id,+ )+ .fetch_optional(&self.pool)+ .await+ .map_err(report)?;+ Ok(time_zone.flatten())+ }+#[tracing::instrument(skip(self, requester_id), err)]async fn list_visible_calendars(&self,diff --git a/crates/calendar_events/src/outbound/pg/test.rs b/crates/calendar_events/src/outbound/pg/test.rsindex 2844e495e0..2b17d0b0e9 100644--- a/crates/calendar_events/src/outbound/pg/test.rs+++ b/crates/calendar_events/src/outbound/pg/test.rs@@ -2544,6 +2544,39 @@ async fn mutation_target_resolves_only_for_visible_requesters(pool: PgPool) {assert!(hidden.is_none(), "stranger cannot see the mutation target");}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn primary_time_zone_is_the_primary_calendars(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let (account_id, _) = grant_and_provider_ids(&repo, link_id).await;+ repo.upsert_calendar_fixture(+ account_id,+ ProviderCalendar {+ provider_calendar_id: "primary".to_string(),+ name: "Primary".to_string(),+ description: None,+ time_zone: Some("America/New_York".to_string()),+ color: None,+ access_role: Some("owner".to_string()),+ is_primary: true,+ is_selected: true,+ default_reminders: Vec::new(),+ },+ )+ .await+ .unwrap();++ let zone = repo.primary_time_zone(owner_id).await.unwrap();+ assert_eq!(zone.as_deref(), Some("America/New_York"));++ let stranger = repo+ .primary_time_zone("macro|[email protected]")+ .await+ .unwrap();+ assert!(stranger.is_none(), "a stranger has no primary calendar");+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn creation_target_actor_is_owned_inboxes_not_the_calendar_inbox(pool: PgPool) {let owner_id = "macro|[email protected]";diff --git a/crates/channel_bots/Cargo.toml b/crates/channel_bots/Cargo.tomlindex 17173783bc..5ecd12b536 100644--- a/crates/channel_bots/Cargo.toml+++ b/crates/channel_bots/Cargo.toml@@ -12,7 +12,10 @@ ai_toolset = { path = "../ai_toolset" }anyhow = { workspace = true }async-trait = { workspace = true }bot_id = { path = "../bot_id" }+calendar_events = { path = "../calendar_events" }channels = { path = "../channels", features = ["inbound", "outbound"] }+chrono = { workspace = true }+chrono-tz = { workspace = true }futures = { workspace = true }macro_user_id = { path = "../macro_user_id" }prompt = { path = "../prompt" }@@ -24,5 +27,4 @@ uuid = { workspace = true }workspace-hack = { version = "0.1", path = "../workspace-hack" }[dev-dependencies]-chrono = { workspace = true }models_pagination = { path = "../models_pagination" }diff --git a/crates/channel_bots/src/domain/ports.rs b/crates/channel_bots/src/domain/ports.rsindex 545c2b45c5..9997eb94b5 100644--- a/crates/channel_bots/src/domain/ports.rs+++ b/crates/channel_bots/src/domain/ports.rs@@ -13,6 +13,14 @@ pub trait AgentResponder: Send + Sync {async fn respond(&self, user_id: &str, prompt: String) -> anyhow::Result<String>;}+/// Resolves the time zone a user's schedule lives in.+#[async_trait]+pub trait UserTimeZones: Send + Sync {+ /// The IANA time zone of the user's primary calendar, `None` when no+ /// calendar is connected. Best effort: lookup failures resolve to `None`.+ async fn primary_time_zone(&self, user_id: &str) -> Option<String>;+}+/// Decides whether a candidate channel message should invoke any bots.#[async_trait]pub trait TriggerDetector: Send + Sync {diff --git a/crates/channel_bots/src/domain/service.rs b/crates/channel_bots/src/domain/service.rsindex f832864a48..6b9c00a90e 100644--- a/crates/channel_bots/src/domain/service.rs+++ b/crates/channel_bots/src/domain/service.rs@@ -12,7 +12,7 @@ use channels::domain::ports::{ChannelMutationErr, ChannelService};use uuid::Uuid;use super::models::{BotEvent, BotTrigger};-use super::ports::AgentResponder;+use super::ports::{AgentResponder, UserTimeZones};use super::sender_label;/// How many channel messages to include around the trigger.@@ -92,25 +92,60 @@ const THINKING_MESSAGE: &str = r#"<m-await>{"text":"Macro is thinking…","inlinconst EMPTY_RESPONSE_FALLBACK: &str = "I wasn't able to come up with a response.";const ERROR_FALLBACK: &str = "Sorry — I ran into an error while responding.";+/// Render the `<current_time>` block: now in the user's primary calendar+/// time zone when one is known and parseable, UTC otherwise.+fn current_time_block(now: chrono::DateTime<chrono::Utc>, time_zone: Option<&str>) -> String {+ const FORMAT: &str = "%A, %B %-d, %Y, %-I:%M %p";+ let parsed = time_zone.map(|name| {+ (+ name,+ name.parse::<chrono_tz::Tz>().inspect_err(|error| {+ tracing::warn!(error=?error, time_zone = name, "unparseable calendar time zone");+ }),+ )+ });+ let line = match parsed {+ Some((name, Ok(tz))) => format!(+ "{} — {name}, the time zone of the user's primary calendar",+ now.with_timezone(&tz).format(FORMAT)+ ),+ // A calendar IS connected here, so the no-calendar wording would+ // mislead the model into denying the connection.+ Some((_, Err(_))) => format!(+ "{} — UTC; the user's own time zone is unknown (their calendar's time \+ zone could not be interpreted)",+ now.format(FORMAT)+ ),+ None => format!(+ "{} — UTC; the user's own time zone is unknown (no connected calendar)",+ now.format(FORMAT)+ ),+ };+ format!("\n<current_time>\n{line}\n</current_time>\n")+}+/// In-process handler for the Macro AI system bot.////// Posts an immediate "thinking" reply in a thread, runs the agent loop, then/// edits that same message with the final answer.-pub struct MacroAiHandler<C, R> {+pub struct MacroAiHandler<C, R, Z> {channels: Arc<C>,responder: Arc<R>,+ time_zones: Arc<Z>,}-impl<C, R> MacroAiHandler<C, R>+impl<C, R, Z> MacroAiHandler<C, R, Z>whereC: ChannelService,R: AgentResponder,+ Z: UserTimeZones,{/// Create a Macro AI handler.- pub fn new(channels: Arc<C>, responder: Arc<R>) -> Self {+ pub fn new(channels: Arc<C>, responder: Arc<R>, time_zones: Arc<Z>) -> Self {Self {channels,responder,+ time_zones,}}@@ -179,17 +214,24 @@ wherelet mentioner = sender_label(event.requesting_user.as_ref());let trigger_id = event.message.id;- let nearby = self- .channels- .get_message_context(- event.channel_id,- trigger_id,- CONTEXT_MESSAGES_BEFORE,- CONTEXT_MESSAGES_AFTER,- )- .await- .inspect_err(|err| tracing::warn!(error=?err, "failed to load local channel context"))- .unwrap_or_default();+ let (nearby, time_zone) = futures::join!(+ async {+ self.channels+ .get_message_context(+ event.channel_id,+ trigger_id,+ CONTEXT_MESSAGES_BEFORE,+ CONTEXT_MESSAGES_AFTER,+ )+ .await+ .inspect_err(+ |err| tracing::warn!(error=?err, "failed to load local channel context"),+ )+ .unwrap_or_default()+ },+ self.time_zones+ .primary_time_zone(event.requesting_user.as_ref()),+ );let mut prompt = String::new();if let Some(parent_id) = event.message.thread_id {@@ -259,6 +301,11 @@ where);}+ prompt.push_str(¤t_time_block(+ chrono::Utc::now(),+ time_zone.as_deref(),+ ));+let _ = write!(prompt, "\nReply to {mentioner}.");prompt}diff --git a/crates/channel_bots/src/domain/service/tests.rs b/crates/channel_bots/src/domain/service/tests.rsindex 97eacdc1e2..f30298380d 100644--- a/crates/channel_bots/src/domain/service/tests.rs+++ b/crates/channel_bots/src/domain/service/tests.rs@@ -10,7 +10,7 @@ use channels::domain::models::{use channels::domain::ports::{ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesQueryResult, ChannelService,};-use chrono::Utc;+use chrono::{TimeZone as _, Utc};use macro_user_id::user_id::MacroUserIdStr;use models_pagination::{CreatedAt, Query};use uuid::Uuid;@@ -18,9 +18,23 @@ use uuid::Uuid;use super::*;use crate::domain::{models::{BotEvent, BotTrigger},- ports::AgentResponder,+ ports::{AgentResponder, UserTimeZones},};+/// Time zone fake with a fixed answer.+struct FixedTimeZones(Option<&'static str>);++#[async_trait]+impl UserTimeZones for FixedTimeZones {+ async fn primary_time_zone(&self, _user_id: &str) -> Option<String> {+ self.0.map(str::to_string)+ }+}++fn eastern_time_zones() -> Arc<FixedTimeZones> {+ Arc::new(FixedTimeZones(Some("America/New_York")))+}+struct TestChannelService {around_args: Mutex<Option<(Uuid, Uuid, i64, i64)>>,around_messages: Vec<ChannelContextMessage>,@@ -363,7 +377,11 @@ fn bot_event(async fn handle_patches_thinking_message_with_reply() {let channel_id = Uuid::new_v4();let channels = Arc::new(MutationChannelService::new(false));- let handler = MacroAiHandler::new(channels.clone(), Arc::new(FixedResponder("the answer")));+ let handler = MacroAiHandler::new(+ channels.clone(),+ Arc::new(FixedResponder("the answer")),+ eastern_time_zones(),+ );handler.handle(&mention_event(@@ -394,7 +412,11 @@ async fn handle_patches_thinking_message_with_reply() {async fn handle_drops_reply_when_thinking_message_was_deleted() {let channel_id = Uuid::new_v4();let channels = Arc::new(MutationChannelService::new(true));- let handler = MacroAiHandler::new(channels.clone(), Arc::new(FixedResponder("the answer")));+ let handler = MacroAiHandler::new(+ channels.clone(),+ Arc::new(FixedResponder("the answer")),+ eastern_time_zones(),+ );handler.handle(&mention_event(@@ -430,7 +452,11 @@ async fn top_level_prompt_marks_trigger_inline_in_channel_context() {],thread_replies: Vec::new(),});- let handler = MacroAiHandler::new(channels.clone(), Arc::new(TestResponder));+ let handler = MacroAiHandler::new(+ channels.clone(),+ Arc::new(TestResponder),+ eastern_time_zones(),+ );let event = mention_event(channel_id,trigger_id,@@ -500,7 +526,11 @@ async fn thread_prompt_puts_thread_first_and_demotes_channel_noise() {"@macro can you make a task out of this?",)],});- let handler = MacroAiHandler::new(channels.clone(), Arc::new(TestResponder));+ let handler = MacroAiHandler::new(+ channels.clone(),+ Arc::new(TestResponder),+ eastern_time_zones(),+ );let event = mention_event(channel_id,trigger_id,@@ -568,7 +598,11 @@ async fn inferred_thread_prompt_does_not_claim_a_mention() {thread_reply(trigger_id, "macro|[email protected]", "it fires twice"),],});- let handler = MacroAiHandler::new(channels.clone(), Arc::new(TestResponder));+ let handler = MacroAiHandler::new(+ channels.clone(),+ Arc::new(TestResponder),+ eastern_time_zones(),+ );let event = bot_event(BotTrigger::Inferred,channel_id,@@ -603,7 +637,11 @@ async fn thread_prompt_includes_trigger_when_reply_fetch_fails_to_return_it() {)],thread_replies: Vec::new(),});- let handler = MacroAiHandler::new(channels.clone(), Arc::new(TestResponder));+ let handler = MacroAiHandler::new(+ channels.clone(),+ Arc::new(TestResponder),+ eastern_time_zones(),+ );let event = mention_event(channel_id,trigger_id,@@ -617,3 +655,79 @@ async fn thread_prompt_includes_trigger_when_reply_fetch_fails_to_return_it() {assert!(prompt.contains("peter: parent message"));assert!(prompt.contains("austin [this message mentioned you]: @macro help with this"));}++#[tokio::test]+async fn prompt_carries_the_current_time_in_the_users_zone() {+ let channels = Arc::new(TestChannelService {+ around_args: Mutex::new(None),+ around_messages: Vec::new(),+ thread_replies: Vec::new(),+ });+ let handler = MacroAiHandler::new(channels, Arc::new(TestResponder), eastern_time_zones());+ let event = mention_event(+ Uuid::new_v4(),+ Uuid::new_v4(),+ None,+ "[email protected]",+ "@macro help",+ );++ let prompt = handler.build_prompt(&event).await;++ assert!(prompt.contains("<current_time>"));+ assert!(prompt.contains("America/New_York, the time zone of the user's primary calendar"));+ assert!(prompt.ends_with("Reply to teo."));+}++#[tokio::test]+async fn prompt_says_the_time_zone_is_unknown_without_a_calendar() {+ let channels = Arc::new(TestChannelService {+ around_args: Mutex::new(None),+ around_messages: Vec::new(),+ thread_replies: Vec::new(),+ });+ let handler = MacroAiHandler::new(+ channels,+ Arc::new(TestResponder),+ Arc::new(FixedTimeZones(None)),+ );+ let event = mention_event(+ Uuid::new_v4(),+ Uuid::new_v4(),+ None,+ "[email protected]",+ "@macro help",+ );++ let prompt = handler.build_prompt(&event).await;++ assert!(prompt.contains("UTC; the user's own time zone is unknown"));+}++#[test]+fn current_time_block_renders_the_users_zone() {+ let now = Utc.with_ymd_and_hms(2026, 1, 6, 18, 23, 0).unwrap();+ assert_eq!(+ current_time_block(now, Some("America/New_York")),+ "\n<current_time>\nTuesday, January 6, 2026, 1:23 PM — America/New_York, the time zone \+ of the user's primary calendar\n</current_time>\n"+ );+}++#[test]+fn current_time_block_falls_back_to_utc_for_missing_or_bad_zones() {+ let now = Utc.with_ymd_and_hms(2026, 1, 6, 18, 23, 0).unwrap();+ assert_eq!(+ current_time_block(now, None),+ "\n<current_time>\nTuesday, January 6, 2026, 6:23 PM — UTC; the user's own \+ time zone is unknown (no connected calendar)\n</current_time>\n"+ );+ // An unparseable zone still means a calendar is connected, so the line+ // must not claim otherwise.+ assert_eq!(+ current_time_block(now, Some("Not/AZone")),+ "\n<current_time>\nTuesday, January 6, 2026, 6:23 PM — UTC; the user's own \+ time zone is unknown (their calendar's time zone could not be \+ interpreted)\n</current_time>\n"+ );+}diff --git a/crates/channel_bots/src/inbound/bot_trigger_router.rs b/crates/channel_bots/src/inbound/bot_trigger_router.rsindex 00b10076be..81d41d1a6c 100644--- a/crates/channel_bots/src/inbound/bot_trigger_router.rs+++ b/crates/channel_bots/src/inbound/bot_trigger_router.rs@@ -9,7 +9,7 @@ use tracing::Instrument as _;use crate::domain::{models::BotEvent,- ports::{AgentResponder, TriggerDetector},+ ports::{AgentResponder, TriggerDetector, UserTimeZones},service::MacroAiHandler,};@@ -25,12 +25,12 @@ use crate::domain::{/// are ignored here; only Macro AI is handled by this branch. Non-system bots/// are notified of mentions out of process via the `channel.mentioned`/// webhook event instead (see the `webhook` crate).-pub struct BotTriggerRouter<C, R, D> {- macro_ai: Arc<MacroAiHandler<C, R>>,+pub struct BotTriggerRouter<C, R, D, Z> {+ macro_ai: Arc<MacroAiHandler<C, R, Z>>,detector: Arc<D>,}-impl<C, R, D> Clone for BotTriggerRouter<C, R, D> {+impl<C, R, D, Z> Clone for BotTriggerRouter<C, R, D, Z> {fn clone(&self) -> Self {Self {macro_ai: self.macro_ai.clone(),@@ -39,16 +39,17 @@ impl<C, R, D> Clone for BotTriggerRouter<C, R, D> {}}-impl<C, R, D> BotTriggerRouter<C, R, D>+impl<C, R, D, Z> BotTriggerRouter<C, R, D, Z>whereC: ChannelService,R: AgentResponder,D: TriggerDetector,+ Z: UserTimeZones,{/// Create a router with the built-in system bots registered.- pub fn new(channels: Arc<C>, responder: Arc<R>, detector: Arc<D>) -> Self {+ pub fn new(channels: Arc<C>, responder: Arc<R>, detector: Arc<D>, time_zones: Arc<Z>) -> Self {Self {- macro_ai: Arc::new(MacroAiHandler::new(channels, responder)),+ macro_ai: Arc::new(MacroAiHandler::new(channels, responder, time_zones)),detector,}}@@ -58,6 +59,7 @@ wherewhereR: 'static,D: 'static,+ Z: 'static,{tokio::spawn(async move {while let Some(candidate) = candidates.recv().await {diff --git a/crates/channel_bots/src/outbound/mod.rs b/crates/channel_bots/src/outbound/mod.rsindex aaa6f5b8fb..ee836943e4 100644--- a/crates/channel_bots/src/outbound/mod.rs+++ b/crates/channel_bots/src/outbound/mod.rs@@ -2,6 +2,8 @@mod agent_loop_responder;mod fast_model_trigger_classifier;+mod primary_calendar_time_zones;pub use agent_loop_responder::AgentLoopResponder;pub use fast_model_trigger_classifier::FastModelTriggerClassifier;+pub use primary_calendar_time_zones::PrimaryCalendarTimeZones;diff --git a/crates/channel_bots/src/outbound/primary_calendar_time_zones.rs b/crates/channel_bots/src/outbound/primary_calendar_time_zones.rsnew file mode 100644index 0000000000..ba5f9da7c9--- /dev/null+++ b/crates/channel_bots/src/outbound/primary_calendar_time_zones.rs@@ -0,0 +1,38 @@+//! Calendar-backed time zone lookup for channel bot prompts.++use std::sync::Arc;++use async_trait::async_trait;+use calendar_events::domain::ports::CalendarOccurrenceService;++use crate::domain::ports::UserTimeZones;++/// [`UserTimeZones`] backed by the calendar read service: a user's time zone+/// is their primary calendar's.+pub struct PrimaryCalendarTimeZones<O> {+ calendars: Arc<O>,+}++impl<O> PrimaryCalendarTimeZones<O> {+ /// Create the lookup from the calendar occurrence read service.+ pub fn new(calendars: Arc<O>) -> Self {+ Self { calendars }+ }+}++#[async_trait]+impl<O> UserTimeZones for PrimaryCalendarTimeZones<O>+where+ O: CalendarOccurrenceService,+{+ async fn primary_time_zone(&self, user_id: &str) -> Option<String> {+ self.calendars+ .primary_time_zone(user_id)+ .await+ .inspect_err(|error| {+ tracing::warn!(error=?error, "failed to resolve a primary calendar time zone");+ })+ .ok()+ .flatten()+ }+}diff --git a/crates/prompt/src/channel_mention.rs b/crates/prompt/src/channel_mention.rsindex 34426fd625..857a71def0 100644--- a/crates/prompt/src/channel_mention.rs+++ b/crates/prompt/src/channel_mention.rs@@ -15,6 +15,16 @@ Context is grouped into tagged blocks:Be concise and directly useful. Use your tools to look things up when helpful.Respond in Markdown.+The prompt carries a `<current_time>` block with the current date and time. When it names the+user's own time zone (their primary calendar's), resolve relative dates and times — "tomorrow",+"Tuesday", "4 pm", "end of day" — from that block yourself and never ask the user for their+time zone. Interpret "EOD" or "end of day" as 5:00 PM in that time zone unless the user says+otherwise, and state assumptions like that briefly in your reply instead of asking a clarifying+question. When the block instead says the user's own time zone is unknown and falls back to+UTC, do not silently treat requested clock times as UTC — ask for the time zone when the+request needs a specific local time, and only proceed without asking when the request carries+no clock time at all.+Tool calls in a channel execute immediately. There is no composer, review card, or pendingconfirmation here, so never tell the user an action is awaiting their approval or ask them toconfirm it in a composer — when a tool call succeeds the action is already done, and when you@@ -28,10 +38,13 @@ chat or using the email composer."##;static INTENT: &str = "The model replies to the marked mention, treats the <thread> block as \-authoritative over <channel_background> noise, answers concisely in Markdown, treats tool calls \-as executing immediately (no composer or pending confirmation to point the user at), only takes \-explicitly requested actions, checks before creating events with attendees, and declines email \-drafting/sending with a pointer to AI chat or the email composer.";+authoritative over <channel_background> noise, answers concisely in Markdown, resolves relative \+dates and times from the <current_time> block (EOD = 5:00 PM local) instead of asking for the \+user's time zone when the block names one — asking rather than silently assuming UTC when it \+does not — treats tool calls as executing immediately (no composer or pending \+confirmation to point the user at), only takes explicitly requested actions, checks before \+creating events with attendees, and declines email drafting/sending with a pointer to AI chat \+or the email composer.";/// The channel-mention prompt for the Macro channel bot.pub static PROMPT: StaticPrompt<'static> = StaticPrompt::borrowed(TITLE, INSTRUCTIONS, INTENT);diff --git a/crates/prompt/src/mentions.rs b/crates/prompt/src/mentions.rsindex 58f1640159..0376f3c87b 100644--- a/crates/prompt/src/mentions.rs+++ b/crates/prompt/src/mentions.rs@@ -37,6 +37,7 @@ If a tool result tells you an app is not connected for the person you are workinThe `blockName` for an email thread is always exactly `email` — never `thread` or `email_thread`, which the frontend cannot resolve.The `blockName` for a calendar event is always exactly `calendar` — never `calendar_event`, which the frontend cannot resolve. `documentId` is the `eventId` a calendar tool returned. To point at one instance of a recurring event, pass that occurrence's `recurrenceId` from ListCalendarEvents as the `occurrenceKey` block param; otherwise omit it and the mention previews the nearest instance. A calendar event mention resolves only for users who have that event on their own calendar.+Only the entity types listed above can be mentioned. A calendar itself is NOT a mentionable entity: never put a `calendarId` (e.g. from ListCalendars) in a mention tag — the frontend cannot resolve it and renders a broken chip. Refer to a calendar by name in plain text and mention only individual events on it. The same goes for any other id with no mention format listed here: plain text, never an improvised tag.When a tool returns both a channel id and a channel message id, link the specific message using the channel message mention format. Do not link only the channel unless you are referring to the whole channel.### Example Response@@ -50,7 +51,9 @@ static INTENT: &str = "Entities and channel messages are referenced with correctincluding exactly \"email\" for email threads, exactly \"calendar\" for calendar events, and \channel_message_id for specific channel messages, \across every Markdown surface (AI chat replies, agent session replies, channel messages, \-email bodies, and Markdown documents) — never inside non-Markdown documents.";+email bodies, and Markdown documents) — never inside non-Markdown documents, and never for \+ids outside the listed entity types (a calendar id from ListCalendars is not mentionable; \+only individual events are).";/// The entity-mention prompt.pub static PROMPT: StaticPrompt<'static> = StaticPrompt::borrowed(TITLE, INSTRUCTIONS, INTENT);diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.mdindex dafc1c86d0..1513e03144 100644--- a/docs/AGENT_GUIDE/channels.md+++ b/docs/AGENT_GUIDE/channels.md@@ -37,8 +37,12 @@ event without attendees creates the event right away (unlike AI chat, where creafor the user to confirm a composer card). For an event with attendees the bot is prompted toask for confirmation in the thread first, since Google sends the invitations the moment theevent is created — no invitation goes out from the initial request. It cannot draft or send-email at all. `@macro-new` / `@coder` / `@cursor` open an agent session; follow-up `@`-mentions of that bot in the same thread route to it.+email at all. The bot's prompt carries the current date and time in the mentioning user's+own time zone (their primary calendar's), so it resolves relative times ("tomorrow at 4",+"EOD") without asking; when no calendar is connected the prompt falls back to UTC and the+bot asks before scheduling a specific clock time. `@macro-new` / `@coder` / `@cursor` open+an agent session; follow-up+`@` mentions of that bot in the same thread route to it.Agent replies may contain mention chips (`<m-document-mention>`) that render like anyother channel mention.diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rsindex 27c16781d3..e387a5d7fb 100644--- a/services/document_storage_service/src/main.rs+++ b/services/document_storage_service/src/main.rs@@ -1049,6 +1049,11 @@ async fn run() -> anyhow::Result<()> {)),),),+ Arc::new(channel_bots::outbound::PrimaryCalendarTimeZones::new(+ Arc::new(calendar_events::domain::service::CalendarService::new(+ calendar_events::outbound::pg::PgCalendarRepository::new(readonly_db.clone()),+ )),+ )),);bot_trigger_router.spawn(bot_trigger_receiver);diff --git a/services/email_service/src/api/context.rs b/services/email_service/src/api/context.rsindex 60567c89b6..b3c4b0707b 100644--- a/services/email_service/src/api/context.rs+++ b/services/email_service/src/api/context.rs@@ -12,6 +12,7 @@ use email::{},outbound::{EmailPgRepo, GmailTokenProviderImpl},};+use email_service::calendar_refresh::ConnectionGatewayCalendarRefresh;use email_service::calendar_tokens::CalendarTokenProviderAdapter;use email_service::pubsub::calendar_backfill_adapters::RedisCalendarRequestGate;@@ -39,6 +40,7 @@ pub(crate) type CalendarMutationSvc = CalendarMutationServiceImpl<GoogleCalendarClient<RedisCalendarRequestGate>,CalendarTokenProviderAdapter,EmailEventBroker,+ ConnectionGatewayCalendarRefresh,>;pub(crate) type EmailEntityAccessService = EntityAccessServiceImpl<PgAccessRepository>;pub(crate) type EmailEntityAccessManagementService =diff --git a/services/email_service/src/calendar_refresh.rs b/services/email_service/src/calendar_refresh.rsnew file mode 100644index 0000000000..e7c0aa7907--- /dev/null+++ b/services/email_service/src/calendar_refresh.rs@@ -0,0 +1,38 @@+//! Connection-gateway adapter that nudges calendar viewers after mutations.++use calendar_events::domain::ports::CalendarRefreshNotifier;+use connection_gateway_client::client::ConnectionGatewayClient;+use uuid::Uuid;++use crate::pubsub::util::cg_refresh_calendar;++/// [`CalendarRefreshNotifier`] backed by the connection gateway: fans one+/// mutation's refresh nudge out to the link owner and its delegates, exactly+/// like the backfill-completion nudge, so open tabs refetch calendar+/// projections without waiting for a provider sync echo.+#[derive(Clone)]+pub struct ConnectionGatewayCalendarRefresh {+ client: ConnectionGatewayClient,+ db: sqlx::PgPool,+}++impl ConnectionGatewayCalendarRefresh {+ /// Construct the adapter.+ pub fn new(client: ConnectionGatewayClient, db: sqlx::PgPool) -> Self {+ Self { client, db }+ }+}++impl CalendarRefreshNotifier for ConnectionGatewayCalendarRefresh {+ async fn calendar_changed(&self, owner_id: &str, email_link_id: Uuid) {+ // Spawned so the mutation response never waits on the gateway: the+ // client has no request timeout and the fan-out posts serially per+ // recipient, while the write this announces is already committed.+ let client = self.client.clone();+ let db = self.db.clone();+ let owner_id = owner_id.to_string();+ tokio::spawn(async move {+ cg_refresh_calendar(&client, &db, &owner_id, email_link_id).await;+ });+ }+}diff --git a/services/email_service/src/lib.rs b/services/email_service/src/lib.rsindex 4ae82fa2fc..f5f9213a65 100644--- a/services/email_service/src/lib.rs+++ b/services/email_service/src/lib.rs@@ -4,6 +4,8 @@ pub mod backfill_completion_service;pub mod backfill_init_service;/// Durable publication of grant-triggered calendar work.pub mod calendar_outbox;+/// Connection-gateway refresh adapter for user-initiated calendar mutations.+pub mod calendar_refresh;/// Access-token adapter for user-initiated calendar mutations.pub mod calendar_tokens;pub mod config;diff --git a/services/email_service/src/main.rs b/services/email_service/src/main.rsindex d8b6807189..13f4f106f1 100644--- a/services/email_service/src/main.rs+++ b/services/email_service/src/main.rs@@ -15,6 +15,7 @@ use email::{outbound::{EmailPgRepo, GmailTokenProviderImpl},};use email_api_client::GmailApiClientRepository;+use email_service::calendar_refresh::ConnectionGatewayCalendarRefresh;use email_service::calendar_tokens::CalendarTokenProviderAdapter;use email_service::outbound::email_api::{EmailServiceTokenSource, GmailApi, RateBudget, RedisProviderRateLimiter,@@ -30,7 +31,9 @@ use macro_authorization::{use macro_entrypoint::MacroEntrypoint;use macro_env::Environment;use macro_event_broker::{KafkaEventPublisher, MacroEventBrokerService};-use macro_service_urls::{AuthServiceUrl, DocumentStorageServiceUrl, StaticFileServiceUrl};+use macro_service_urls::{+ AuthServiceUrl, ConnectionGatewayUrl, DocumentStorageServiceUrl, StaticFileServiceUrl,+};use sqlx::postgres::PgPoolOptions;use static_file_service_client::StaticFileServiceClient;use std::{sync::Arc, time::Duration};@@ -206,6 +209,10 @@ async fn main() -> anyhow::Result<()> {auth_service_client.clone(),));let calendar_service = Arc::new(CalendarService::new(PgCalendarRepository::new(db.clone())));+ let connection_gateway_client = connection_gateway_client::client::ConnectionGatewayClient::new(+ config.internal_api_key.to_string(),+ ConnectionGatewayUrl::new()?.to_string(),+ );let calendar_mutation_service = Arc::new(CalendarMutationServiceImpl::new(PgCalendarRepository::new(db.clone()),GoogleCalendarClient::with_gate(@@ -217,6 +224,7 @@ async fn main() -> anyhow::Result<()> {),CalendarTokenProviderAdapter::new(redis_conn.clone(), auth_service_client.clone()),macro_event_broker.clone(),+ ConnectionGatewayCalendarRefresh::new(connection_gateway_client, db.clone()),));let api_result = api::setup_and_serve(ApiContext {db,