Skip to content

armgit / macro

Public Imported from GitHub
0

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

5.0 KB
Raw Blame
import type {
  PlatformNotificationHandle,
  PlatformNotificationInterface,
} from '@notifications';
import { invoke } from '@tauri-apps/api/core';
import {
  isPermissionGranted,
  requestPermission,
  sendNotification,
} from '@tauri-apps/plugin-notification';
import { type as osType } from '@tauri-apps/plugin-os';
import { showLinuxNotification } from './linux-notification';
import { MacOSNotificationUpdateRequiredError } from './notification-errors';

export { MacOSNotificationUpdateRequiredError } from './notification-errors';

export function createTauriNotificationInterface(
  setDisabled: () => Promise<void>,
  shouldSend: () => boolean = () => true
): PlatformNotificationInterface {
  const platform = osType();
  const isMacOS = platform === 'macos';
  let hasMacOSPermissionCommands = isMacOS;

  async function getCur(): Promise<NotificationPermission> {
    // The notification plugin always reports permission as granted on desktop.
    // Read the actual OS authorization on macOS instead.
    if (hasMacOSPermissionCommands) {
      try {
        return await invoke<NotificationPermission>(
          'get_macos_notification_permission'
        );
      } catch (error) {
        // Older native builds can receive this frontend through an OTA update.
        // Preserve their existing behavior only when the command is absent.
        if (error !== 'Command get_macos_notification_permission not found') {
          throw error;
        }
        hasMacOSPermissionCommands = false;
      }
    }
    return (await isPermissionGranted()) ? 'granted' : 'denied';
  }
  return {
    requestPermission: async () => {
      const cur = await getCur();
      if (cur === 'granted') {
        return 'granted';
      }
      if (hasMacOSPermissionCommands) {
        // macOS will not prompt again after denial; permission must be changed
        // in System Settings.
        if (cur === 'denied') return 'denied';
        try {
          return await invoke<NotificationPermission>(
            'request_macos_notification_permission'
          );
        } catch (error) {
          // UNErrorCodeNotificationsNotAllowed: only System Settings can
          // allow this app again, for example after it was re-signed.
          if (typeof error === 'string' && error.includes('(UNErrorDomain 1)'))
            return 'denied';
          throw error;
        }
      }
      return await requestPermission();
    },
    getCurrentPermission: getCur,
    showNotification: async (data) => {
      const granted = await getCur();

      // A user can disable notifications while the native permission check
      // is in flight. Check the current preference just before dispatching.
      if (granted !== 'granted' || !shouldSend()) {
        return 'not-granted';
      }

      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: sender?.name ?? data.title,
            body: data.options?.body,
            notificationId: data.notificationId,
            subtitle: sender ? conversation?.name : undefined,
            threadId: conversation?.id,
            sender,
            // Older native builds ignore this and keep the system sound.
            silent: data.options?.silent,
          });
        } catch (error) {
          // OTA frontend updates can reach an older native app. Its legacy
          // sender silently drops notifications, so require a native update.
          if (error === 'Command send_macos_notification not found') {
            throw new MacOSNotificationUpdateRequiredError(error);
          }
          throw error;
        }
        // Native activation carries the ID through the startup-safe navigation
        // bridge. It also works after this webview (and its callbacks) is gone.
        return {
          onClick: () => {},
          onDismiss: () => {},
          close: () => {},
        };
      }

      if (platform === 'linux') {
        return await showLinuxNotification(data.title, data.options);
      }

      if (!data.options) {
        sendNotification(data.title);
        return createTauriNotification();
      }
      const { body, icon, ...rest } = data.options;

      sendNotification({
        title: data.title,
        body,
        icon,
        extra: {
          ...rest,
        },
      });
      return createTauriNotification();
    },
    unregisterNotifications: setDisabled,
  };
}

function createTauriNotification(): PlatformNotificationHandle {
  return {
    onClick: (_cb) => {
      console.warn(
        'notification on click is not yet supported on this platform'
      );
    },
    onDismiss: (_cb) => {
      console.warn(
        'notification on dismiss is not yet supported on this platform'
      );
    },
    close() {
      console.warn('notification close is not yet supported on this platform');
    },
  };
}