Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(desktop): show macOS notifications as messages from their sender (#8566)
Eric Hayes867b76638c19
diff --git a/.github/workflows/build_desktop_on_tag.yml b/.github/workflows/build_desktop_on_tag.ymlindex 5c18b8e731..1d5aa11fa6 100644--- a/.github/workflows/build_desktop_on_tag.yml+++ b/.github/workflows/build_desktop_on_tag.yml@@ -316,10 +316,23 @@ jobs:fiecho "APPLE_SIGNING_IDENTITY=$identity" >> "$GITHUB_ENV"echo "Using signing identity: $identity"++ # The Developer ID provisioning profile authorizes the communication+ # notifications entitlement, which shows senders' avatars on notifications.+ # A signed build without it would be killed at launch, so require both.+ if [ -z "${MACOS_DEVELOPER_ID_PROVISIONING_PROFILE_BASE64}" ]; then+ echo "MACOS_DEVELOPER_ID_PROVISIONING_PROFILE_BASE64 must be set alongside the Developer ID certificate" >&2+ exit 1+ fi+ profile_path="$RUNNER_TEMP/macro-developer-id.provisionprofile"+ printf '%s' "$MACOS_DEVELOPER_ID_PROVISIONING_PROFILE_BASE64" | base64 --decode > "$profile_path" 2>/dev/null \+ || printf '%s' "$MACOS_DEVELOPER_ID_PROVISIONING_PROFILE_BASE64" | base64 -D > "$profile_path"+ echo "MACOS_PROVISIONING_PROFILE=$profile_path" >> "$GITHUB_ENV"shell: bashenv:MACOS_DEVELOPER_ID_CERTIFICATE_BASE64: ${{ secrets.MACOS_DEVELOPER_ID_CERTIFICATE_BASE64 }}MACOS_DEVELOPER_ID_CERTIFICATE_PASSWORD: ${{ secrets.MACOS_DEVELOPER_ID_CERTIFICATE_PASSWORD }}+ MACOS_DEVELOPER_ID_PROVISIONING_PROFILE_BASE64: ${{ secrets.MACOS_DEVELOPER_ID_PROVISIONING_PROFILE_BASE64 }}- id: metadataname: Derive artifact metadatarun: |diff --git a/.github/workflows/build_dmg_on_tag.yml b/.github/workflows/build_dmg_on_tag.ymlindex 288c0ff5c2..32b62455f9 100644--- a/.github/workflows/build_dmg_on_tag.yml+++ b/.github/workflows/build_dmg_on_tag.yml@@ -138,10 +138,23 @@ jobs:fiecho "APPLE_SIGNING_IDENTITY=$identity" >> "$GITHUB_ENV"echo "Using signing identity: $identity"++ # The Developer ID provisioning profile authorizes the communication+ # notifications entitlement, which shows senders' avatars on notifications.+ # A signed build without it would be killed at launch, so require both.+ if [ -z "${MACOS_DEVELOPER_ID_PROVISIONING_PROFILE_BASE64}" ]; then+ echo "MACOS_DEVELOPER_ID_PROVISIONING_PROFILE_BASE64 must be set alongside the Developer ID certificate" >&2+ exit 1+ fi+ profile_path="$RUNNER_TEMP/macro-developer-id.provisionprofile"+ printf '%s' "$MACOS_DEVELOPER_ID_PROVISIONING_PROFILE_BASE64" | base64 --decode > "$profile_path" 2>/dev/null \+ || printf '%s' "$MACOS_DEVELOPER_ID_PROVISIONING_PROFILE_BASE64" | base64 -D > "$profile_path"+ echo "MACOS_PROVISIONING_PROFILE=$profile_path" >> "$GITHUB_ENV"shell: bashenv:MACOS_DEVELOPER_ID_CERTIFICATE_BASE64: ${{ secrets.MACOS_DEVELOPER_ID_CERTIFICATE_BASE64 }}MACOS_DEVELOPER_ID_CERTIFICATE_PASSWORD: ${{ secrets.MACOS_DEVELOPER_ID_CERTIFICATE_PASSWORD }}+ MACOS_DEVELOPER_ID_PROVISIONING_PROFILE_BASE64: ${{ secrets.MACOS_DEVELOPER_ID_PROVISIONING_PROFILE_BASE64 }}- id: metadataname: Derive artifact metadatarun: |diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex f421d95433..ab018ff786 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -241,7 +241,11 @@ Install and retain the UserNotifications delegate before the native event loopstarts. Clicking restores and focuses the main window; receipt and dismissal donot navigate. Preserve iOS and Android `createPushApi` tap navigation when changingdesktop delivery, including buffered launch taps before device registration.-This requires a native macOS release; see the+Send the sender and conversation as their own fields so macOS can show a+communication notification (avatar, sender, conversation); keep new native+arguments optional for OTA compatibility. Releases need the Developer ID+provisioning profile for the communication entitlement; see+`tauri/src-tauri/README.md`. This requires a native macOS release; see the[notification walkthrough](../../docs/agent-guide/notifications.md).## Desktop page zoomdiff --git a/apps/web/src/features/notifications/components/Playground.tsx b/apps/web/src/features/notifications/components/Playground.tsxindex bd611ff0e3..b372bba7e3 100644--- a/apps/web/src/features/notifications/components/Playground.tsx+++ b/apps/web/src/features/notifications/components/Playground.tsx@@ -22,6 +22,7 @@ import {import { NOTIFICATION_LABEL_BY_TYPE } from '../notification-preview';import {DefaultDocumentNameResolver,+ DefaultUserAvatarResolver,DefaultUserNameResolver,} from '../notification-resolvers';import { createNotificationSource } from '../notification-source';@@ -151,7 +152,8 @@ function BrowserFormat(props: { notification: UnifiedNotification }) {toPlatformNotificationData(props.notification,DefaultUserNameResolver,- DefaultDocumentNameResolver+ DefaultDocumentNameResolver,+ DefaultUserAvatarResolver).then(setBrowserNotif).catch((error) =>diff --git a/apps/web/src/features/notifications/notification-platform.ts b/apps/web/src/features/notifications/notification-platform.tsindex 5642c86b2c..97edac6180 100644--- a/apps/web/src/features/notifications/notification-platform.ts+++ b/apps/web/src/features/notifications/notification-platform.ts@@ -14,10 +14,13 @@ import {import { openNotification } from './notification-navigation';import {DefaultDocumentNameResolver,+ DefaultUserAvatarResolver,DefaultUserNameResolver,type DocumentNameResolver,+ type UserAvatarResolver,type UserNameResolver,} from './notification-resolvers';+import { getNotificationSenderAvatarUrl } from './notification-sender';import type { UnifiedNotification } from './types';/// the interface for a singular notification on this device@@ -27,10 +30,21 @@ export interface PlatformNotificationHandle {close: () => void;}+export interface PlatformNotificationSender {+ /** The sender's Macro user id, or the agent's name when it has none. */+ id: string;+ name: string;+ avatarUrl?: string;+}+export interface PlatformNotificationData {title: string;notificationId?: string;options?: NotificationOptions;+ /** Who it is from, for platforms that show the sender apart from `title`. */+ sender?: PlatformNotificationSender;+ /** Where it happened. `name` is set only when `title` names it too. */+ conversation?: { id: string; name?: string };}const USER_NAME_FALLBACK = 'Someone';@@ -65,10 +79,22 @@ async function resolveActorName(: undefined;}+async function resolveSenderAvatarUrl(+ notification: UnifiedNotification,+ resolveUserAvatar: UserAvatarResolver+): Promise<string | undefined> {+ const avatarUrl = getNotificationSenderAvatarUrl(notification);+ if (avatarUrl) return avatarUrl;+ return notification.sender_id+ ? await resolveUserAvatar(notification.sender_id)+ : undefined;+}+export async function toPlatformNotificationData(notification: UnifiedNotification,resolveUserName: UserNameResolver,- resolveDocumentName: DocumentNameResolver+ resolveDocumentName: DocumentNameResolver,+ resolveUserAvatar: UserAvatarResolver): Promise<PlatformNotificationData | null> {const accentColor = committedThemeAccent();const icon = getFaviconUrl(accentColor);@@ -86,9 +112,11 @@ export async function toPlatformNotificationData(};}- const actor =- (await resolveActorName(notification, resolveUserName)) ??- USER_NAME_FALLBACK;+ const [actorName, avatarUrl] = await Promise.all([+ resolveActorName(notification, resolveUserName),+ resolveSenderAvatarUrl(notification, resolveUserAvatar),+ ]);+ const actor = actorName ?? USER_NAME_FALLBACK;const showTarget = shouldShowNotificationTarget(notification);const targetName =@@ -108,6 +136,17 @@ export async function toPlatformNotificationData(body: content ? markdownToPlainText(content) : action,icon,},+ sender: actorName+ ? {+ id: notification.sender_id ?? actorName,+ name: actorName,+ avatarUrl,+ }+ : undefined,+ conversation: {+ id: notification.entity_id,+ name: showTarget ? targetName : undefined,+ },};}@@ -135,7 +174,8 @@ export async function maybeHandlePlatformNotification(const platformNotificationData = await toPlatformNotificationData(notification,DefaultUserNameResolver,- DefaultDocumentNameResolver+ DefaultDocumentNameResolver,+ DefaultUserAvatarResolver);if (platformNotificationData) {diff --git a/apps/web/src/features/notifications/notification-resolvers.ts b/apps/web/src/features/notifications/notification-resolvers.tsindex b4eaf2a05a..7d91685c7f 100644--- a/apps/web/src/features/notifications/notification-resolvers.ts+++ b/apps/web/src/features/notifications/notification-resolvers.ts@@ -1,5 +1,6 @@import type { BlockName } from '@core/block';import { itemToResolvedBlockName } from '@core/constant/allBlocks';+import { getProfilePictureUrl } from '@core/signal/profilePicture';import type { EntityType } from '@core/types';import { getDisplayName, macroIdToEmail, tryMacroId } from '@core/user';import { getItemPreview, isAccessiblePreviewItem } from '@queries/preview';@@ -7,6 +8,7 @@ import { stringToItemType } from '@service-storage/client';import { raceTimeout, until } from '@solid-primitives/promise';export type UserNameResolver = (id: string) => Promise<string | undefined>;+export type UserAvatarResolver = (id: string) => Promise<string | undefined>;export type DocumentNameResolver = (id: string,type: EntityType@@ -29,6 +31,10 @@ export const DefaultUserNameResolver: UserNameResolver = async (id: string) => {return macroId ? macroIdToEmail(macroId) : id || undefined;};+export const DefaultUserAvatarResolver: UserAvatarResolver = async (+ id: string+) => await raceTimeout(getProfilePictureUrl(id), RESOLVER_TIMEOUT);+const getPreview = async (id: string, type: string) => {const itemType = stringToItemType(type);if (!itemType) return undefined;diff --git a/apps/web/src/features/notifications/notification-sender.ts b/apps/web/src/features/notifications/notification-sender.tsindex b6ab434bda..1b55dfb14f 100644--- a/apps/web/src/features/notifications/notification-sender.ts+++ b/apps/web/src/features/notifications/notification-sender.ts@@ -60,6 +60,13 @@ export function getNotificationSenderFallbackName(.otherwise(() => undefined);}+/** The sender's avatar when the notification metadata carries one. */+export function getNotificationSenderAvatarUrl(+ notification: UnifiedNotification+): string | undefined {+ return senderContent(notification)?.senderProfilePictureUrl ?? undefined;+}+export type NotificationAgentSender = {name: string;avatarUrl?: string;diff --git a/apps/web/src/features/notifications/tests/notification-platform.test.ts b/apps/web/src/features/notifications/tests/notification-platform.test.tsindex 811bba9eb3..040c3a4ab0 100644--- a/apps/web/src/features/notifications/tests/notification-platform.test.ts+++ b/apps/web/src/features/notifications/tests/notification-platform.test.ts@@ -24,6 +24,7 @@ vi.mock('../notification-navigation', () => ({vi.mock('../notification-resolvers', () => ({DefaultDocumentNameResolver: vi.fn(async () => undefined),DefaultUserNameResolver: vi.fn(async () => undefined),+ DefaultUserAvatarResolver: vi.fn(async () => undefined),}));import {@@ -178,7 +179,8 @@ describe('maybeHandlePlatformNotification', () => {const result = await toPlatformNotificationData(createReminderNotification(),resolveUserName,- resolveDocumentName+ resolveDocumentName,+ async () => undefined);expect(result).toEqual({@@ -320,8 +322,86 @@ it('uses the project discussion bot display name for platform notifications', asconst result = await toPlatformNotificationData(notification,async () => undefined,+ async () => undefined,async () => undefined);expect(result?.title).toContain('Launch agent');expect(JSON.stringify(result)).toContain('Launch');});++describe('platform notification sender and conversation', () => {+ function channelMessage(+ channelType: 'public' | 'directMessage',+ senderProfilePictureUrl?: string+ ): UnifiedNotification {+ return baseNotification({+ entity_id: 'channel-1',+ sender_id: 'macro|[email protected]',+ notification_event_type: 'channel_message_send',+ notification_metadata: {+ tag: 'channel_message_send',+ content: {+ messageId: 'message-1',+ messageContent: 'Ship it',+ sender: 'macro|[email protected]',+ channelType,+ senderProfilePictureUrl,+ },+ },+ } as Partial<UnifiedNotification>);+ }++ it('names the sender, their avatar, and the group conversation', async () => {+ const resolveUserAvatar = vi.fn(+ async () => 'https://cdn.example.com/ada.png'+ );+ const result = await toPlatformNotificationData(+ channelMessage('public'),+ async () => 'Ada',+ async () => 'design',+ resolveUserAvatar+ );++ expect(result).toMatchObject({+ title: 'Ada <design>',+ sender: {+ id: 'macro|[email protected]',+ name: 'Ada',+ avatarUrl: 'https://cdn.example.com/ada.png',+ },+ conversation: { id: 'channel-1', name: 'design' },+ });+ expect(resolveUserAvatar).toHaveBeenCalledExactlyOnceWith(+ 'macro|[email protected]'+ );+ });++ it('keeps a direct message unnamed and prefers the avatar the server sent', async () => {+ const resolveUserAvatar = vi.fn(+ async () => 'https://cdn.example.com/old.png'+ );+ const result = await toPlatformNotificationData(+ channelMessage('directMessage', 'https://cdn.example.com/ada.png'),+ async () => 'Ada',+ async () => 'Ada, Grace',+ resolveUserAvatar+ );++ expect(result?.title).toBe('Ada');+ expect(result?.sender?.avatarUrl).toBe('https://cdn.example.com/ada.png');+ expect(result?.conversation).toEqual({ id: 'channel-1', name: undefined });+ expect(resolveUserAvatar).not.toHaveBeenCalled();+ });++ it('has no sender when nobody can be named', async () => {+ const result = await toPlatformNotificationData(+ createChannelInviteNotification(),+ async () => undefined,+ async () => undefined,+ async () => undefined+ );++ expect(result?.title).toBe('Someone <General>');+ expect(result?.sender).toBeUndefined();+ });+});diff --git a/apps/web/src/lib/core/signal/profilePicture.ts b/apps/web/src/lib/core/signal/profilePicture.tsindex 49f9c446b6..67d4288b29 100644--- a/apps/web/src/lib/core/signal/profilePicture.ts+++ b/apps/web/src/lib/core/signal/profilePicture.ts@@ -1,6 +1,7 @@import { debounce } from '@core/util/debounce';import { authServiceClient } from '@service-auth/client';+import { until } from '@solid-primitives/promise';import {type Accessor,createEffect,@@ -152,3 +153,15 @@ export function useProfilePictureUrl(id?: string): ProfilePictureUrlFetcher {return [accessor, controls];}++/** A user's profile picture URL from the shared cache, fetched if needed. */+export async function getProfilePictureUrl(+ id: string+): Promise<string | undefined> {+ useProfilePictureUrl(id);+ const item = await until(() => {+ const item = userProfilePictures[id];+ return item && !item.loading ? item : undefined;+ });+ return item.url;+}diff --git a/apps/web/src/lib/tauri/notification.test.ts b/apps/web/src/lib/tauri/notification.test.tsindex ed46626ed3..7b98ae67b2 100644--- a/apps/web/src/lib/tauri/notification.test.ts+++ b/apps/web/src/lib/tauri/notification.test.ts@@ -99,6 +99,45 @@ describe('desktop notification delivery', () => {expect(mocks.sendNotification).not.toHaveBeenCalled();});+ it('titles macOS notifications with the sender and names the conversation beneath', async () => {+ const adapter = createTauriNotificationInterface(vi.fn());+ const sender = {+ id: 'macro|[email protected]',+ name: 'Ada',+ avatarUrl: 'https://cdn.example.com/ada.png',+ };+ await adapter.showNotification({+ ...notification,+ title: 'Ada <design>',+ sender,+ conversation: { id: 'channel-1', name: 'design' },+ });+ expect(mocks.invoke).toHaveBeenCalledWith('send_macos_notification', {+ title: 'Ada',+ body: notification.options.body,+ notificationId: notification.notificationId,+ subtitle: 'design',+ threadId: 'channel-1',+ sender,+ });+ });++ it('keeps the full title on macOS when nobody can be named', async () => {+ const adapter = createTauriNotificationInterface(vi.fn());+ await adapter.showNotification({+ title: 'Someone <General>',+ conversation: { id: 'channel-1', name: 'General' },+ });+ expect(mocks.invoke).toHaveBeenCalledWith('send_macos_notification', {+ title: 'Someone <General>',+ body: undefined,+ notificationId: undefined,+ subtitle: undefined,+ threadId: 'channel-1',+ sender: undefined,+ });+ });+it.each(['default', 'denied'])('does not send when macOS permission is %s',async (permission) => {diff --git a/apps/web/src/lib/tauri/notification.ts b/apps/web/src/lib/tauri/notification.tsindex ceebdfe136..98575671f2 100644--- a/apps/web/src/lib/tauri/notification.ts+++ b/apps/web/src/lib/tauri/notification.ts@@ -68,11 +68,17 @@ export function createTauriNotificationInterface(}if (isMacOS) {+ const { sender, conversation } = data;try {+ // macOS shows the sender as the title and the conversation beneath+ // it; without a sender the title already names both.await invoke<void>('send_macos_notification', {- title: data.title,+ title: sender?.name ?? data.title,body: data.options?.body,notificationId: data.notificationId,+ subtitle: sender ? conversation?.name : undefined,+ threadId: conversation?.id,+ sender,});} catch (error) {// OTA frontend updates can reach an older native app. Its legacydiff --git a/apps/web/tauri/Cargo.lock b/apps/web/tauri/Cargo.lockindex c915d6aab1..208bba81df 100644--- a/apps/web/tauri/Cargo.lock+++ b/apps/web/tauri/Cargo.lock@@ -268,6 +268,7 @@ dependencies = ["objc2 0.5.2","objc2 0.6.4","objc2-foundation",+ "objc2-intents","objc2-ui-kit","objc2-user-notifications","reqwest",@@ -4326,6 +4327,17 @@ dependencies = ["objc2-core-foundation",]+[[package]]+name = "objc2-intents"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "80fac082e6de12282b24ea745e9707cd374363c7ae0b2f813bf1813cfc289325"+dependencies = [+ "block2",+ "objc2 0.6.4",+ "objc2-foundation",+]+[[package]]name = "objc2-io-surface"version = "0.3.2"diff --git a/apps/web/tauri/desktop-cef/Cargo.lock b/apps/web/tauri/desktop-cef/Cargo.lockindex b174f232f8..97e47448f3 100644--- a/apps/web/tauri/desktop-cef/Cargo.lock+++ b/apps/web/tauri/desktop-cef/Cargo.lock@@ -276,6 +276,8 @@ dependencies = ["objc2 0.5.3","objc2 0.6.5","objc2-foundation",+ "objc2-intents",+ "objc2-ui-kit","objc2-user-notifications","reqwest","rootcause",@@ -821,6 +823,7 @@ dependencies = ["chrono","lru","maybe_send",+ "miniz_oxide 0.8.9","postcard","predicate-index","serde",@@ -4112,6 +4115,7 @@ dependencies = ["tokio","tracing","url",+ "uuid","zip 6.0.0",]@@ -4771,6 +4775,17 @@ dependencies = ["objc2-core-foundation",]+[[package]]+name = "objc2-intents"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "80fac082e6de12282b24ea745e9707cd374363c7ae0b2f813bf1813cfc289325"+dependencies = [+ "block2",+ "objc2 0.6.5",+ "objc2-foundation",+]+[[package]]name = "objc2-io-surface"version = "0.3.2"diff --git a/apps/web/tauri/src-tauri/Cargo.toml b/apps/web/tauri/src-tauri/Cargo.tomlindex ff116421cf..2873e7d178 100644--- a/apps/web/tauri/src-tauri/Cargo.toml+++ b/apps/web/tauri/src-tauri/Cargo.toml@@ -94,9 +94,24 @@ objc2 = "0.6"objc2-foundation = { version = "0.3", default-features = false, features = ["std","NSBundle",+ "NSData","NSError","NSString",] }+objc2-intents = { version = "0.3", default-features = false, features = [+ "std",+ "block2",+ "INImage",+ "INIntent",+ "INIntentResponse",+ "INInteraction",+ "INOutgoingMessageType",+ "INPerson",+ "INPersonHandle",+ "INSendMessageAttachment",+ "INSendMessageIntent",+ "INSpeakableString",+] }objc2-user-notifications = { version = "0.3", default-features = false, features = ["std","block2",@@ -105,6 +120,7 @@ objc2-user-notifications = { version = "0.3", default-features = false, features"UNNotificationContent","UNNotificationRequest","UNNotificationSettings",+ "UNNotificationSound","UNNotificationTrigger","UNUserNotificationCenter",] }diff --git a/apps/web/tauri/src-tauri/README.md b/apps/web/tauri/src-tauri/README.mdindex c86a25c150..0b83365f76 100644--- a/apps/web/tauri/src-tauri/README.md+++ b/apps/web/tauri/src-tauri/README.md@@ -323,6 +323,23 @@ builds ignore the added ID and cannot navigate. Previously delivered alerts haveno destination to recover. Verify the [notification walkthrough](../../../../docs/agent-guide/notifications.md)in an installed macOS bundle before release.+`send_macos_notification` also takes an optional `subtitle` (the conversation),+`threadId` (stacks a conversation's alerts), and `sender` (`id`, `name`,+`avatarUrl`). A sender makes it a communication notification, as on iOS: the+downloaded avatar replaces the app icon and group conversations show their name.+The new arguments are optional, so older frontends and native builds keep+working together. macOS honors this only for an app signed with the restricted+`com.apple.developer.usernotifications.communication` entitlement and+`INSendMessageIntent` in `NSUserActivityTypes`; local and ad-hoc builds show the+plain title and subtitle. A Developer ID build carries the entitlement only with+an embedded provisioning profile, so the release workflow requires the+`MACOS_DEVELOPER_ID_PROVISIONING_PROFILE_BASE64` secret next to the certificate.+Create it in the Apple Developer portal: enable **Communication Notifications**+on the `com.macro.app.prod` App ID, create a **Developer ID** macOS provisioning+profile for that App ID and the certificate, and store the base64 profile as the+secret. The DMG build fails if the profile is missing or does not grant the+entitlement to the bundle identifier; renew the secret when the profile expires.+Linux notification activation requires `send_linux_notification` and`close_linux_notification`. Ship a full native AppImage containing these commands;a frontend-only update cannot add clickable system notifications. Before publishingdiff --git a/apps/web/tauri/src-tauri/icons/macos/Info.plist b/apps/web/tauri/src-tauri/icons/macos/Info.plistindex e85b8b7e31..255cc15e4a 100644--- a/apps/web/tauri/src-tauri/icons/macos/Info.plist+++ b/apps/web/tauri/src-tauri/icons/macos/Info.plist@@ -6,5 +6,9 @@<string>Macro</string><key>CFBundleIconName</key><string>Macro</string>+ <key>NSUserActivityTypes</key>+ <array>+ <string>INSendMessageIntent</string>+ </array></dict></plist>diff --git a/apps/web/tauri/src-tauri/src/macos_notification_permission.rs b/apps/web/tauri/src-tauri/src/macos_notification_permission.rsindex 1b4689ba5c..a28cb6c627 100644--- a/apps/web/tauri/src-tauri/src/macos_notification_permission.rs+++ b/apps/web/tauri/src-tauri/src/macos_notification_permission.rs@@ -13,13 +13,15 @@ use objc2::runtime::Bool;use objc2_foundation::{NSBundle, NSError, NSString};use objc2_user_notifications::{UNAuthorizationOptions, UNAuthorizationStatus, UNMutableNotificationContent,- UNNotificationRequest, UNNotificationSettings, UNUserNotificationCenter,+ UNNotificationContent, UNNotificationRequest, UNNotificationSettings, UNNotificationSound,+ UNUserNotificationCenter,};use serde::{Serialize, Serializer};use tokio::sync::mpsc;use uuid::Uuid;mod activation;+mod communication;pub use activation::install_delegate;#[cfg(test)]@@ -155,14 +157,30 @@ pub async fn request_macos_notification_permission().ok_or(NotificationError::CallbackDropped)?}-fn notification_request(+fn notification_content(title: &str,+ subtitle: Option<&str>,body: Option<&str>,- notification_id: Option<&str>,-) -> Retained<UNNotificationRequest> {+ thread_id: Option<&str>,+) -> Retained<UNMutableNotificationContent> {let content = UNMutableNotificationContent::new();content.setTitle(&NSString::from_str(title));content.setBody(&NSString::from_str(body.unwrap_or_default()));+ if let Some(subtitle) = subtitle {+ content.setSubtitle(&NSString::from_str(subtitle));+ }+ // Notification Center stacks a conversation's notifications together.+ if let Some(thread_id) = thread_id {+ content.setThreadIdentifier(&NSString::from_str(thread_id));+ }+ content.setSound(Some(&UNNotificationSound::defaultSound()));+ content+}++fn notification_request(+ content: &UNNotificationContent,+ notification_id: Option<&str>,+) -> Retained<UNNotificationRequest> {// Reusing an identifier would replace a previously delivered notification.let delivery_id = Uuid::new_v4().to_string();let identifier = match notification_id {@@ -176,22 +194,59 @@ fn notification_request(}None => NSString::from_str(&delivery_id),};- UNNotificationRequest::requestWithIdentifier_content_trigger(&identifier, &content, None)+ UNNotificationRequest::requestWithIdentifier_content_trigger(&identifier, content, None)}/// Deliver immediately through the same framework used for authorization./// Completion means macOS accepted the request; system presentation settings/// still determine whether it appears as a banner.+///+/// Every argument after `body` is optional so frontends and native builds of+/// different versions keep working together.#[tauri::command]+#[tracing::instrument(+ name = "notification.desktop_deliver",+ skip_all,+ fields(notification_id, has_sender = sender.is_some(), has_avatar),+ err+)]pub async fn send_macos_notification(title: String,body: Option<String>,notification_id: Option<String>,+ subtitle: Option<String>,+ thread_id: Option<String>,+ sender: Option<communication::Sender>,) -> Result<(), NotificationError> {+ let span = tracing::Span::current();+ if let Some(notification_id) = ¬ification_id {+ span.record("notification_id", notification_id.as_str());+ }ensure_application_bundle()?;- let (sender, mut receiver) = mpsc::channel(1);+ let avatar = match &sender {+ Some(sender) => sender.download_avatar().await,+ None => None,+ };+ span.record("has_avatar", avatar.is_some());+ let (result_sender, mut receiver) = mpsc::channel(1);{- let request = notification_request(&title, body.as_deref(), notification_id.as_deref());+ let content = notification_content(+ &title,+ subtitle.as_deref(),+ body.as_deref(),+ thread_id.as_deref(),+ );+ let content = match &sender {+ Some(sender) => communication::from_sender(+ content,+ sender,+ avatar.as_deref(),+ subtitle.as_deref(),+ thread_id.as_deref(),+ ),+ None => Retained::into_super(content),+ };+ let request = notification_request(&content, notification_id.as_deref());let callback = RcBlock::new(move |error: *mut NSError| {// SAFETY: the optional NSError is valid for this completion handler.// Copy its details before the native callback returns.@@ -199,7 +254,7 @@ pub async fn send_macos_notification(Some(error) => Err(native_error(NotificationOperation::Delivery, error)),None => Ok(()),};- let _ = sender.try_send(result);+ let _ = result_sender.try_send(result);});UNUserNotificationCenter::currentNotificationCenter().addNotificationRequest_withCompletionHandler(&request, Some(&callback));diff --git a/apps/web/tauri/src-tauri/src/macos_notification_permission/communication.rs b/apps/web/tauri/src-tauri/src/macos_notification_permission/communication.rsnew file mode 100644index 0000000000..8081172df3--- /dev/null+++ b/apps/web/tauri/src-tauri/src/macos_notification_permission/communication.rs@@ -0,0 +1,187 @@+//! Present notifications from people as macOS communication notifications:+//! the sender's avatar replaces the app icon, and group conversations are+//! titled with their name, as on iOS.+//!+//! macOS 12+ honors this only when the signed app carries the+//! `com.apple.developer.usernotifications.communication` entitlement and lists+//! `INSendMessageIntent` in `NSUserActivityTypes`. Builds without the+//! entitlement (local development) deliver the plain notification.++use std::{sync::LazyLock, time::Duration};++use block2::RcBlock;+use objc2::rc::Retained;+use objc2::{AllocAnyThread, available, msg_send};+use objc2_foundation::{NSData, NSError, NSString, ns_string};+use objc2_intents::{+ INImage, INInteraction, INInteractionDirection, INOutgoingMessageType, INPerson,+ INPersonHandle, INPersonHandleType, INSendMessageIntent, INSpeakableString,+};+use objc2_user_notifications::{UNMutableNotificationContent, UNNotificationContent};+use serde::Deserialize;+use url::Url;++const AVATAR_TIMEOUT: Duration = Duration::from_secs(5);+const MAX_AVATAR_BYTES: usize = 5 * 1024 * 1024;++static AVATAR_CLIENT: LazyLock<reqwest::Client> = LazyLock::new(|| {+ reqwest::Client::builder()+ .timeout(AVATAR_TIMEOUT)+ .build()+ .expect("a reqwest client with only a timeout configured always builds")+});++/// The person a notification is from.+#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Sender {+ /// Stable identifier, such as a Macro user id or an agent's name.+ id: String,+ name: String,+ avatar_url: Option<String>,+}++impl Sender {+ /// The sender's avatar image. A notification without one is still worth+ /// delivering, so failures are logged rather than returned.+ #[tracing::instrument(name = "notification.desktop_avatar", skip_all)]+ pub(super) async fn download_avatar(&self) -> Option<Vec<u8>> {+ let url = Url::parse(self.avatar_url.as_deref()?)+ .ok()+ .filter(|url| url.scheme() == "https")?;+ let response = match AVATAR_CLIENT+ .get(url)+ .send()+ .await+ .and_then(reqwest::Response::error_for_status)+ {+ Ok(response) => response,+ Err(error) => {+ tracing::warn!(?error, "Unable to download notification avatar");+ return None;+ }+ };+ match response.bytes().await {+ Ok(bytes) if bytes.len() <= MAX_AVATAR_BYTES => Some(bytes.to_vec()),+ Ok(bytes) => {+ tracing::warn!(bytes = bytes.len(), "Notification avatar is too large");+ None+ }+ Err(error) => {+ tracing::warn!(?error, "Unable to read notification avatar");+ None+ }+ }+ }+}++/// Present `content` as a message from `sender`. `group_name` is set for+/// conversations with more than two people.+pub(super) fn from_sender(+ content: Retained<UNMutableNotificationContent>,+ sender: &Sender,+ avatar: Option<&[u8]>,+ group_name: Option<&str>,+ conversation_id: Option<&str>,+) -> Retained<UNNotificationContent> {+ if !available!(macos = 12.0) {+ return Retained::into_super(content);+ }+ let intent = message_intent(&content, sender, avatar, group_name, conversation_id);+ donate_incoming(&intent);+ // SAFETY: Intents declares INSendMessageIntent's conformance to+ // UNNotificationContentProviding (macOS 12+, checked above); objc2 does not+ // bind that category, so send the message directly.+ let updated: Result<Retained<UNNotificationContent>, Retained<NSError>> =+ unsafe { msg_send![&*content, contentByUpdatingWithProvider: &*intent, error: _] };+ match updated {+ Ok(updated) => updated,+ Err(error) => {+ tracing::warn!(+ domain = %error.domain(),+ code = error.code(),+ "Unable to present notification as a message"+ );+ Retained::into_super(content)+ }+ }+}++fn message_intent(+ content: &UNMutableNotificationContent,+ sender: &Sender,+ avatar: Option<&[u8]>,+ group_name: Option<&str>,+ conversation_id: Option<&str>,+) -> Retained<INSendMessageIntent> {+ let id = NSString::from_str(&sender.id);+ let image = avatar.map(|bytes| {+ // SAFETY: INImage copies arbitrary image data; undecodable data only+ // leaves the avatar blank.+ unsafe { INImage::imageWithImageData(&NSData::with_bytes(bytes)) }+ });+ // SAFETY: every argument is a valid object or nil, as the initializers+ // allow; the objects are retained for as long as they are used.+ unsafe {+ let handle = INPersonHandle::initWithValue_type(+ INPersonHandle::alloc(),+ Some(&id),+ INPersonHandleType::Unknown,+ );+ let person =+ INPerson::initWithPersonHandle_nameComponents_displayName_image_contactIdentifier_customIdentifier(+ INPerson::alloc(),+ &handle,+ None,+ Some(&NSString::from_str(&sender.name)),+ image.as_deref(),+ None,+ Some(&id),+ );+ let group_name = group_name.map(|name| {+ INSpeakableString::initWithSpokenPhrase(+ INSpeakableString::alloc(),+ &NSString::from_str(name),+ )+ });+ let intent =+ INSendMessageIntent::initWithRecipients_outgoingMessageType_content_speakableGroupName_conversationIdentifier_serviceName_sender_attachments(+ INSendMessageIntent::alloc(),+ None,+ INOutgoingMessageType::OutgoingMessageText,+ Some(&content.body()),+ group_name.as_deref(),+ conversation_id.map(NSString::from_str).as_deref(),+ None,+ Some(&person),+ None,+ );+ intent.setImage_forParameterNamed(image.as_deref(), ns_string!("sender"));+ intent+ }+}++/// macOS uses donated messages to rank conversations and suggest them in+/// Focus and sharing.+fn donate_incoming(intent: &INSendMessageIntent) {+ // SAFETY: the intent is a valid INSendMessageIntent and no response is+ // required for an incoming message.+ let interaction =+ unsafe { INInteraction::initWithIntent_response(INInteraction::alloc(), intent, None) };+ let completion = RcBlock::new(|error: *mut NSError| {+ // SAFETY: the optional NSError is valid for this completion handler.+ if let Some(error) = unsafe { error.as_ref() } {+ tracing::warn!(+ domain = %error.domain(),+ code = error.code(),+ "Unable to donate notification message"+ );+ }+ });+ // SAFETY: the direction is a valid INInteractionDirection, and the+ // completion block is copied by the framework before this returns.+ unsafe {+ interaction.setDirection(INInteractionDirection::Incoming);+ interaction.donateInteractionWithCompletion(Some(&completion));+ }+}diff --git a/apps/web/tauri/src-tauri/src/macos_notification_permission/test.rs b/apps/web/tauri/src-tauri/src/macos_notification_permission/test.rsindex b911ce0fad..bfaa528f06 100644--- a/apps/web/tauri/src-tauri/src/macos_notification_permission/test.rs+++ b/apps/web/tauri/src-tauri/src/macos_notification_permission/test.rs@@ -59,7 +59,15 @@ fn native_authorization_errors_reach_the_frontend_with_their_details() {#[test]fn immediate_notifications_preserve_the_title_and_optional_body() {- let request = notification_request("Macro — new message", Some("Hello 👋\nSecond line"), None);+ let request = notification_request(+ ¬ification_content(+ "Macro — new message",+ None,+ Some("Hello 👋\nSecond line"),+ None,+ ),+ None,+ );assert_eq!(request.content().title().to_string(), "Macro — new message");assert_eq!(request.content().body().to_string(),@@ -67,24 +75,52 @@ fn immediate_notifications_preserve_the_title_and_optional_body() {);assert!(request.trigger().is_none());- let title_only = notification_request("Reminder", None, None);+ let title_only =+ notification_request(¬ification_content("Reminder", None, None, None), None);assert_eq!(title_only.content().title().to_string(), "Reminder");assert!(title_only.content().body().is_empty());}+#[test]+fn conversation_notifications_name_and_stack_their_conversation() {+ let request = notification_request(+ ¬ification_content("Ada", Some("design"), Some("Ship it"), Some("channel-1")),+ None,+ );+ assert_eq!(request.content().subtitle().to_string(), "design");+ assert_eq!(+ request.content().threadIdentifier().to_string(),+ "channel-1"+ );+ assert!(request.content().sound().is_some());++ let direct = notification_request(¬ification_content("Ada", None, None, None), None);+ assert!(direct.content().subtitle().is_empty());+ assert!(direct.content().threadIdentifier().is_empty());+}+#[test]fn repeated_notifications_do_not_replace_each_other() {- let first = notification_request("Same title", None, None);- let second = notification_request("Same title", None, None);+ let first = notification_request(¬ification_content("Same title", None, None, None), None);+ let second = notification_request(¬ification_content("Same title", None, None, None), None);assert_ne!(first.identifier(), second.identifier());assert!(Uuid::parse_str(&first.identifier().to_string()).is_ok());}#[test]fn delivered_notifications_keep_their_destination_without_webview_callbacks() {- let request = notification_request("Message", None, Some("first-notification"));- let second = notification_request("Message", None, Some("second-notification"));- let repeated = notification_request("Message", None, Some("first-notification"));+ let request = notification_request(+ ¬ification_content("Message", None, None, None),+ Some("first-notification"),+ );+ let second = notification_request(+ ¬ification_content("Message", None, None, None),+ Some("second-notification"),+ );+ let repeated = notification_request(+ ¬ification_content("Message", None, None, None),+ Some("first-notification"),+ );assert_ne!(request.identifier(), repeated.identifier());for (request, expected) in [(request, "first-notification"),diff --git a/apps/web/tauri/src-tauri/tauri.android.conf.json b/apps/web/tauri/src-tauri/tauri.android.conf.jsonindex 2962ae39a6..62b7a45317 100644--- a/apps/web/tauri/src-tauri/tauri.android.conf.json+++ b/apps/web/tauri/src-tauri/tauri.android.conf.json@@ -2,7 +2,7 @@"version": "2.5.0","bundle": {"android": {- "versionCode": 15+ "versionCode": 16}},"$schema": "https://schema.tauri.app/config/2",diff --git a/docs/agent-guide/notifications.md b/docs/agent-guide/notifications.mdindex e6d3b1e681..73dfc704eb 100644--- a/docs/agent-guide/notifications.md+++ b/docs/agent-guide/notifications.md@@ -27,6 +27,14 @@ comment to check the location inside the entity, not just the entity itself.This requires a full native macOS release; frontend-only updates cannot add theresponse delegate or repair destinations in previously delivered alerts.+In a signed macOS release, an alert from a person shows their avatar in place of+the app icon, their name as the title, and the channel or document name beneath+for group conversations; direct messages show only the sender. Alerts from one+conversation stack together in Notification Center and play the default sound.+Verify a channel message, a direct message, a document comment, and a reminder+(no sender: app icon and the combined title). Local and ad-hoc builds lack the+communication entitlement and show the app icon with the sender and subtitle.+On Linux desktop builds with native notification activation, clicking a systemnotification (or its **Open** action) restores/presents Macro and opens thatnotification's target using the normal in-app navigation. Dismissing or expiringdiff --git a/nix/tauri-desktop.nix b/nix/tauri-desktop.nixindex 862b511df2..486626cf9e 100644--- a/nix/tauri-desktop.nix+++ b/nix/tauri-desktop.nix@@ -757,6 +757,16 @@};};tauriDesktopDmgSigningIdentity = builtins.getEnv "APPLE_SIGNING_IDENTITY";+ # The Developer ID provisioning profile that authorizes the communication+ # notifications entitlement. Profiles ship inside every app, so copying+ # it to the store exposes nothing.+ tauriDesktopDmgProvisioningProfilePath = builtins.getEnv "MACOS_PROVISIONING_PROFILE";+ tauriDesktopDmgProvisioningProfile = lib.optionalString (tauriDesktopDmgProvisioningProfilePath != "") (+ builtins.path {+ path = /. + tauriDesktopDmgProvisioningProfilePath;+ name = "macro.provisionprofile";+ }+ );tauriDesktopDmgAppleLd = pkgs.writeShellScriptBin "ld" ''appleDeveloperDir=$(unset DEVELOPER_DIR@@ -952,6 +962,7 @@pname = "macro-tauri-desktop-dmg";version = appVersion;APPLE_SIGNING_IDENTITY = tauriDesktopDmgSigningIdentity;+ MACOS_PROVISIONING_PROFILE = tauriDesktopDmgProvisioningProfile;nativeBuildInputs = [pkgs.coreutils(pkgs.python3.withPackages (ps: [ ps.ds-store ]))@@ -964,6 +975,10 @@echo "APPLE_SIGNING_IDENTITY must be set when building the signed macOS DMG; use nix build --impure." >&2exit 1fi+ if [ "$APPLE_SIGNING_IDENTITY" != "-" ] && [ -z "$MACOS_PROVISIONING_PROFILE" ]; then+ echo "MACOS_PROVISIONING_PROFILE must name the Developer ID provisioning profile when signing with a Developer ID; use nix build --impure." >&2+ exit 1+ fiexport PATH="$PATH:/usr/bin:/bin:/usr/sbin:/sbin"appPath="$TMPDIR/Macro.app"cp -a ${tauriDesktopCefApp}/Macro.app "$appPath"@@ -1071,18 +1086,55 @@fi# Helper executables (the macrod sidecar) must be signed- # individually for notarization; the --deep pass below re-seals- # the bundle on top of them.+ # individually for notarization.while IFS= read -r -d "" file; doif otool -hv "$file" >/dev/null 2>&1; thencodesign "''${executable_sign_args[@]}" "$file"fidone < <(find "$app/Contents/MacOS" -type f -print0)- codesign "''${executable_sign_args[@]}" --deep "$app"+ # Nested code is signed above, so seal the bundle without --deep:+ # the app's restricted entitlements must not reach the CEF helpers+ # or the macrod sidecar.+ local -a app_sign_args=("''${executable_sign_args[@]}")+ if [ "$APPLE_SIGNING_IDENTITY" != "-" ]; then+ cp "$MACOS_PROVISIONING_PROFILE" "$app/Contents/embedded.provisionprofile"+ write_app_entitlements "$app" "$TMPDIR/macro.entitlements"+ app_sign_args=("''${sign_args[@]}" --entitlements "$TMPDIR/macro.entitlements")+ fi+ codesign "''${app_sign_args[@]}" "$app"codesign --verify --deep --strict --verbose=2 "$app"}+ # Add the profile-backed entitlements to CEF's, after checking the+ # profile grants them to this bundle identifier. Communication+ # notifications show senders' avatars in macOS notifications.+ write_app_entitlements() {+ local app="$1" out="$2"+ local profile="$TMPDIR/macro-provisionprofile.plist"+ security cms -D -i "$MACOS_PROVISIONING_PROFILE" > "$profile"+ local team_id bundle_id app_id communication+ team_id=$(/usr/libexec/PlistBuddy -c 'Print :TeamIdentifier:0' "$profile")+ bundle_id=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$app/Contents/Info.plist")+ app_id=$(/usr/libexec/PlistBuddy -c 'Print :Entitlements:com.apple.application-identifier' "$profile")+ if [ "$app_id" != "$team_id.$bundle_id" ]; then+ echo "Provisioning profile is for $app_id, not $team_id.$bundle_id" >&2+ exit 1+ fi+ communication=$(/usr/libexec/PlistBuddy -c 'Print :Entitlements:com.apple.developer.usernotifications.communication' "$profile" 2>/dev/null || true)+ if [ "$communication" != "true" ]; then+ echo "Provisioning profile does not grant com.apple.developer.usernotifications.communication" >&2+ exit 1+ fi+ cp ${../apps/web/tauri/desktop-cef/entitlements.plist} "$out"+ chmod u+w "$out"+ /usr/libexec/PlistBuddy \+ -c "Add :com.apple.application-identifier string $app_id" \+ -c "Add :com.apple.developer.team-identifier string $team_id" \+ -c 'Add :com.apple.developer.usernotifications.communication bool true' \+ "$out"+ }+bundle_nix_dylibs "$appPath"sign_darwin_app "$appPath"diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/build_dmg_on_tag.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/build_dmg_on_tag.rsindex 5f1ffae8f5..e8d7aec973 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/build_dmg_on_tag.rs+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/build_dmg_on_tag.rs@@ -110,6 +110,10 @@ fn configure_signing_identity() -> Step<Run> {"MACOS_DEVELOPER_ID_CERTIFICATE_PASSWORD",vars::MACOS_DEVELOPER_ID_CERTIFICATE_PASSWORD,))+ .add_env((+ "MACOS_DEVELOPER_ID_PROVISIONING_PROFILE_BASE64",+ vars::MACOS_DEVELOPER_ID_PROVISIONING_PROFILE_BASE64,+ ))}fn nix_build_dmg() -> Step<Run> {diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/configure_signing_identity.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/configure_signing_identity.shindex 56ba56d067..fa7403db4d 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/configure_signing_identity.sh+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/configure_signing_identity.sh@@ -34,3 +34,15 @@ if [ -z "$identity" ]; thenfiecho "APPLE_SIGNING_IDENTITY=$identity" >> "$GITHUB_ENV"echo "Using signing identity: $identity"++# The Developer ID provisioning profile authorizes the communication+# notifications entitlement, which shows senders' avatars on notifications.+# A signed build without it would be killed at launch, so require both.+if [ -z "${MACOS_DEVELOPER_ID_PROVISIONING_PROFILE_BASE64}" ]; then+ echo "MACOS_DEVELOPER_ID_PROVISIONING_PROFILE_BASE64 must be set alongside the Developer ID certificate" >&2+ exit 1+fi+profile_path="$RUNNER_TEMP/macro-developer-id.provisionprofile"+printf '%s' "$MACOS_DEVELOPER_ID_PROVISIONING_PROFILE_BASE64" | base64 --decode > "$profile_path" 2>/dev/null \+ || printf '%s' "$MACOS_DEVELOPER_ID_PROVISIONING_PROFILE_BASE64" | base64 -D > "$profile_path"+echo "MACOS_PROVISIONING_PROFILE=$profile_path" >> "$GITHUB_ENV"diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/vars.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/vars.rsindex 6455bc17b6..8e26ef6391 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/vars.rs+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/vars.rs@@ -23,6 +23,7 @@ secret!(DOPPLER_TOKEN);secret!(IOS_RELEASE_DOPPLER_TOKEN);secret!(MACOS_DEVELOPER_ID_CERTIFICATE_BASE64);secret!(MACOS_DEVELOPER_ID_CERTIFICATE_PASSWORD);+secret!(MACOS_DEVELOPER_ID_PROVISIONING_PROFILE_BASE64);secret!(MACOS_RELEASE_DOPPLER_TOKEN);secret!(NIX_CACHE_SIGNING_KEY);secret!(POSTHOG_API_KEY);