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(notifications): handle on click for browser notifications (#357)
teo44ae250e024b
diff --git a/js/app/packages/app/component/Root.tsx b/js/app/packages/app/component/Root.tsxindex c45d42251b..eff49eac22 100644--- a/js/app/packages/app/component/Root.tsx+++ b/js/app/packages/app/component/Root.tsx@@ -1,4 +1,5 @@import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';+import { globalSplitManager } from '@app/signal/splitLayout';import { withAnalytics } from '@coparse/analytics';import { useIsAuthenticated } from '@core/auth';import { ChannelsContextProvider } from '@core/component/ChannelsProvider';@@ -21,8 +22,10 @@ import { isTauri, MaybeTauriProvider } from '@macro/tauri';import { createEmailSource, Provider as EntityProvider } from '@macro-entity';import {createNotificationSource,+ type UnifiedNotification,usePlatformNotificationState,} from '@notifications';+import { maybeHandlePlatformNotification } from '@notifications/notification-platform';import { setUser, useObserveRouting } from '@observability';import { ws as connectionGatewayWebsocket } from '@service-connection/websocket';import { gqlServiceClient } from '@service-gql/client';@@ -256,11 +259,20 @@ const ROUTES: RouteDefinition[] = [export function ConfiguredGlobalAppStateProvider(props: ParentProps) {// Initialize global notification helpersconst notifInterface = usePlatformNotificationState();++ const onNotification = (notification: UnifiedNotification) => {+ if (notifInterface === 'not-supported') return;+ const layoutManager = globalSplitManager();+ if (!layoutManager) return;+ maybeHandlePlatformNotification(+ notification,+ notifInterface,+ layoutManager+ );+ };const notificationSource = createNotificationSource(connectionGatewayWebsocket,- notifInterface === 'not-supported'- ? undefined- : notifInterface.showNotification+ onNotification);const emailActive = useEmailLinksStatus();diff --git a/js/app/packages/app/component/UnifiedListView.tsx b/js/app/packages/app/component/UnifiedListView.tsxindex 4f7032adc4..d0b6abc5d5 100644--- a/js/app/packages/app/component/UnifiedListView.tsx+++ b/js/app/packages/app/component/UnifiedListView.tsx@@ -66,7 +66,7 @@ import {isChannelMention,isChannelMessageReply,isChannelMessageSend,- notificationWithMetadata,+ tryToTypedNotification,type UnifiedNotification,useNotificationsForEntity,} from '@notifications';@@ -1359,7 +1359,7 @@ export function UnifiedListView(props: UnifiedListViewProps) {: undefined}onClickNotification={(notifiedEntity) => {- const notification = notificationWithMetadata(+ const notification = tryToTypedNotification(notifiedEntity.notification);if (!notification) return;diff --git a/js/app/packages/app/component/split-layout/layoutManager.ts b/js/app/packages/app/component/split-layout/layoutManager.tsindex 382ec578fb..cd25ef152a 100644--- a/js/app/packages/app/component/split-layout/layoutManager.ts+++ b/js/app/packages/app/component/split-layout/layoutManager.ts@@ -1,5 +1,5 @@import type { BlockName } from '@core/block';-import { ResizeZoneCtx } from '@core/component/Resize/types';+import type { ResizeZoneCtx } from '@core/component/Resize/types';import type {BlockInstanceHandle,BlockOrchestrator,@@ -129,6 +129,8 @@ export type SplitManager = {toggleSpotlightSplit: (id: SplitId) => void;+ getOrchestrator: () => BlockOrchestrator;+/*** Reconcile the splits with the provided list of splits.* Useful for when the url changes.@@ -681,5 +683,6 @@ export function createSplitLayout(returnFocus: () => dispatchEvent(SplitEvent.ReturnFocus, undefined),resizeContext,setResizeContext,+ getOrchestrator: () => orchestrator,};}diff --git a/js/app/packages/core/component/GlobalNotificationBell.tsx b/js/app/packages/core/component/GlobalNotificationBell.tsxindex c784409d0a..c96702c1ed 100644--- a/js/app/packages/core/component/GlobalNotificationBell.tsx+++ b/js/app/packages/core/component/GlobalNotificationBell.tsx@@ -1,16 +1,11 @@-import {- useGlobalBlockOrchestrator,- useGlobalNotificationSource,-} from '@app/component/GlobalAppState';-import { useSplitLayout } from '@app/component/split-layout/layout';+import { useGlobalNotificationSource } from '@app/component/GlobalAppState';+import { globalSplitManager } from '@app/signal/splitLayout';import { NotificationRenderer } from '@core/component/NotificationRenderer';import Bell from '@icon/regular/bell.svg';import {- extractNotificationData,- type NavigationActions,type NotificationSource,- navigateToNotification,- notificationWithMetadata,+ openNotification,+ tryToTypedNotification,useUnreadNotifications,} from '@notifications';import { Show } from 'solid-js';@@ -21,8 +16,6 @@ export type GlobalNotificationBellProps = {};export function GlobalNotificationBell(props: GlobalNotificationBellProps) {- const blockOrchestrator = useGlobalBlockOrchestrator();- const { insertSplit, replaceSplit } = useSplitLayout();const allUnreadNotifications = useUnreadNotifications(props.notificationSource);@@ -38,42 +31,16 @@ export function GlobalNotificationBell(props: GlobalNotificationBellProps) {const mostRecent = () =>unreadNotifications().sort((a, b) => b.createdAt - a.createdAt)[0];- const messageLocation = async (- channelId: string,- messageId: string,- threadId?: string- ) => {- const blockHandle = await blockOrchestrator.getBlockHandle(channelId);- await blockHandle?.goToLocationFromParams({- message_id: messageId,- thread_id: threadId,- });- };-const handleNotificationClick = async () => {const notification = mostRecent();if (!notification) return;- const nm = notificationWithMetadata(notification);- if (!nm) return;-- const notificationData = extractNotificationData(nm);- if (typeof notificationData === 'string') {- notificationSource.markAsRead(notification);- return;- }-- const actions: NavigationActions = {- insertSplit,- replaceSplit,- messageLocation,- };+ const nm = tryToTypedNotification(notification);+ const layoutManager = globalSplitManager();+ if (!nm || !layoutManager) return;- navigateToNotification({- data: notificationData,- actions,- });+ openNotification(nm, layoutManager);notificationSource.markAsRead(notification);diff --git a/js/app/packages/core/component/NotificationRenderer.tsx b/js/app/packages/core/component/NotificationRenderer.tsxindex 24a3165d63..7933073e73 100644--- a/js/app/packages/core/component/NotificationRenderer.tsx+++ b/js/app/packages/core/component/NotificationRenderer.tsx@@ -4,7 +4,7 @@ import { useDisplayName } from '@core/user/displayName';import { formatDate } from '@core/util/date';import {extractNotificationData,- notificationWithMetadata,+ tryToTypedNotification,type UnifiedNotification,} from '@notifications';import { Show } from 'solid-js';@@ -15,7 +15,7 @@ type NotificationRendererProps = {};export function NotificationRenderer(props: NotificationRendererProps) {- const typed = () => notificationWithMetadata(props.notification);+ const typed = () => tryToTypedNotification(props.notification);const data = () => {const t = typed();if (!t) return null;diff --git a/js/app/packages/core/component/Notifications.tsx b/js/app/packages/core/component/Notifications.tsxindex 70a328ce2f..6f8b581654 100644--- a/js/app/packages/core/component/Notifications.tsx+++ b/js/app/packages/core/component/Notifications.tsx@@ -1,17 +1,15 @@-import { useGlobalBlockOrchestrator } from '@app/component/GlobalAppState';-import { useSplitLayout } from '@app/component/split-layout/layout';+import { globalSplitManager } from '@app/signal/splitLayout';import { NotificationRenderer } from '@core/component/NotificationRenderer';import type { Entity } from '@core/types';import { formatDate } from '@core/util/date';import { useSplitNavigationHandler } from '@core/util/useSplitNavigationHandler';import {- extractNotificationData,NOTIFICATION_LABEL_BY_TYPE,type NotificationSource,- navigateToNotification,- notificationWithMetadata,+ tryToTypedNotification,type UnifiedNotification,} from '@notifications';+import { openNotification } from '@notifications/notification-navigation';import { createMemo, For, Show } from 'solid-js';export type NotificationsProps = {@@ -30,37 +28,12 @@ export function Notifications(props: NotificationsProps) {});});- const { replaceSplit, insertSplit } = useSplitLayout();- const blockOrchestrator = useGlobalBlockOrchestrator();-- const messageLocation = async (- channelId: string,- messageId: string,- threadId?: string- ) => {- const blockHandle = await blockOrchestrator.getBlockHandle(channelId);- await blockHandle?.goToLocationFromParams({- message_id: messageId,- thread_id: threadId,- });- };-const handleNotificationClick = async (notification: UnifiedNotification) => {- const typed = notificationWithMetadata(notification);- if (!typed) return;-- const data = extractNotificationData(typed);- if (data === 'no_extractor' || data === 'no_extracted_data') return;-- navigateToNotification({- actions: {- insertSplit,- replaceSplit,- messageLocation,- },- data,- });+ const splitManager = globalSplitManager();+ const typed = tryToTypedNotification(notification);+ if (!typed || !splitManager) return;+ openNotification(typed, splitManager);await props.notificationSource.markAsRead(notification);};diff --git a/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx b/js/app/packages/macro-entity/src/components/EntityWithEverything.tsxindex b4107c2ec4..95189bc36d 100644--- a/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx+++ b/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx@@ -3,7 +3,7 @@ import { LabelAndHotKey, Tooltip } from '@core/component/Tooltip';import { TOKENS } from '@core/hotkey/tokens';import { matches } from '@core/util/match';import CheckIcon from '@icon/regular/check.svg';-import { notificationWithMetadata } from '@notifications';+import { tryToTypedNotification } from '@notifications';import { useEmail, useUserId } from '@service-gql/client';import { mergeRefs } from '@solid-primitives/refs';import { createDraggable, createDroppable } from '@thisbeyond/solid-dnd';@@ -612,9 +612,7 @@ export function EntityWithEverything(}const metadata =- notificationWithMetadata(- notification- )?.notificationMetadata;+ tryToTypedNotification(notification)?.notificationMetadata;if (!metadata ||!('messageContent' in metadata) ||@@ -635,9 +633,7 @@ export function EntityWithEverything(}const metadata =- notificationWithMetadata(- notification- )?.notificationMetadata;+ tryToTypedNotification(notification)?.notificationMetadata;if (!metadata ||!('messageContent' in metadata) ||diff --git a/js/app/packages/notifications/components/PlatformNotificationProvider.tsx b/js/app/packages/notifications/components/PlatformNotificationProvider.tsxindex 52743b224a..12acfac23d 100644--- a/js/app/packages/notifications/components/PlatformNotificationProvider.tsx+++ b/js/app/packages/notifications/components/PlatformNotificationProvider.tsx@@ -10,6 +10,10 @@ import {useContext,} from 'solid-js';import { createTabLeaderSignal } from '../notification-election';+import type {+ PlatformNotificationData,+ PlatformNotificationHandle,+} from '../notification-platform';type NotGranted = 'not-granted';@@ -19,9 +23,8 @@ export interface PlatformNotificationInterface {requestPermission: () => Promise<NotificationPermission>;getCurrentPermission: () => Promise<NotificationPermission>;showNotification: (- title: string,- options?: NotificationOptions- ) => Promise<AppNotification | NotGranted>;+ data: PlatformNotificationData+ ) => Promise<PlatformNotificationHandle | NotGranted>;unregisterNotifications: () => Promise<void>;}@@ -29,12 +32,6 @@ export type CreateAppNotificationInterface = (setDisabled: () => Promise<void>) => PlatformNotificationInterface;-/// the interface for a singular notification on this device-export interface AppNotification {- onClick: (cb: () => void) => void;- close: () => void;-}-export type NotificationUnsupported = 'not-supported';const ELECTION_NAMESPACE = 'notification-provider';@@ -59,7 +56,7 @@ function createDefaultBrowserInterface(return window.Notification.requestPermission();},getCurrentPermission,- showNotification: async (title, opts) => {+ showNotification: async (data: PlatformNotificationData) => {if (!isLeader()) {// treat as no-opreturn 'not-granted';@@ -69,17 +66,16 @@ function createDefaultBrowserInterface(return 'not-granted';}- return createBrowserNotication(title, opts);+ return createBrowserNotication(data);},unregisterNotifications,};}function createBrowserNotication(- title: string,- opts?: NotificationOptions-): AppNotification {- const notif = new Notification(title, opts);+ data: PlatformNotificationData+): PlatformNotificationHandle {+ const notif = new Notification(data.title, data.options);return {onClick: (cb) => {@@ -114,14 +110,13 @@ export function usePlatformNotifications():type UiDisabled = 'disabled-in-ui';export type UserSetting = 'allowed' | UiDisabled;-interface PlatformNotificationState {+export interface PlatformNotificationState {permission: Resource<NotificationPermission | UiDisabled>;requestPermission: () => Promise<NotificationPermission>;unregisterNotification: () => Promise<void>;showNotification: (- title: string,- opts: NotificationOptions- ) => Promise<AppNotification | NotGranted | UiDisabled>;+ data: PlatformNotificationData+ ) => Promise<PlatformNotificationHandle | NotGranted | UiDisabled>;}export const NotificationStateContext = createContext<@@ -179,9 +174,8 @@ function PlatformNotificationState(props: {}async function showNotification(- title: string,- opts: NotificationOptions- ): Promise<AppNotification | NotGranted | UiDisabled> {+ data: PlatformNotificationData+ ): Promise<PlatformNotificationHandle | NotGranted | UiDisabled> {const manuallyDisabled = props.manuallyDisabled();if (manuallyDisabled === 'disabled-in-ui') {return manuallyDisabled;@@ -191,7 +185,7 @@ function PlatformNotificationState(props: {return 'not-granted';}- return await platformNotif.showNotification(title, opts);+ return await platformNotif.showNotification(data);}return (diff --git a/js/app/packages/notifications/components/Playground.tsx b/js/app/packages/notifications/components/Playground.tsxindex a95d1a3235..98a124f084 100644--- a/js/app/packages/notifications/components/Playground.tsx+++ b/js/app/packages/notifications/components/Playground.tsx@@ -1,3 +1,4 @@+import { globalSplitManager } from '@app/signal/splitLayout';import { useChannelMarkdownArea } from '@block-channel/component/MarkdownArea';import { NotificationRenderer } from '@core/component/NotificationRenderer';import { TextButton } from '@core/component/TextButton';@@ -10,12 +11,16 @@ import {For,Show,} from 'solid-js';-import { notificationWithMetadata } from '../notification-metadata';+import { tryToTypedNotification } from '../notification-metadata';+import {+ maybeHandlePlatformNotification,+ type PlatformNotificationData,+ toPlatformNotificationData,+} from '../notification-platform';import {extractNotificationData,NOTIFICATION_LABEL_BY_TYPE,type NotificationData,- toBrowserNotification,} from '../notification-preview';import {DefaultDocumentNameResolver,@@ -26,6 +31,7 @@ import type { UnifiedNotification } from '../types';import { createMockWebsocket } from '../utils/mock-websocket';import {PlatformNotificationProvider,+ type PlatformNotificationState,usePlatformNotificationState,} from './PlatformNotificationProvider';@@ -48,7 +54,7 @@ function groupNotificationsByType(function extractTypedNotificationData(notification: UnifiedNotification): NotificationData | null {- const typed = notificationWithMetadata(notification);+ const typed = tryToTypedNotification(notification);if (!typed) return null;const data = extractNotificationData(typed);if (data === 'no_extractor' || data === 'no_extracted_data') return null;@@ -150,7 +156,7 @@ function BrowserFormat(props: { notification: UnifiedNotification }) {createEffect(() => {const notifData = data();if (notifData) {- toBrowserNotification(+ toPlatformNotificationData(notifData,DefaultUserNameResolver,DefaultDocumentNameResolver@@ -180,8 +186,8 @@ function BrowserFormat(props: { notification: UnifiedNotification }) {</div><BrowserNotificationPreviewtitle={browserNotif()!.title}- body={browserNotif()!.body}- icon={browserNotif()!.icon}+ body={browserNotif()!.options.body}+ icon={browserNotif()!.options.icon}/></div>@@ -527,30 +533,32 @@ function PlaygroundContent() {const handleTestNotification = async (notification: UnifiedNotification) => {if (platformNotif === 'not-supported') return;- const data = extractTypedNotificationData(notification);- if (!data) return;-- const browserNotif = await toBrowserNotification(- data,- DefaultUserNameResolver,- DefaultDocumentNameResolver- );-- if (!browserNotif) return;-- const result = await platformNotif.showNotification(- browserNotif.title,- browserNotif- );-- if (result === 'not-granted' || result === 'disabled-in-ui') {- if (- typeof Notification !== 'undefined' &&- Notification.permission === 'granted'- ) {- new Notification(browserNotif.title, browserNotif);+ const onNotification = (notification: UnifiedNotification) => {+ const layoutManager = globalSplitManager();+ if (!layoutManager) {+ console.warn('no layout manager');+ return;}- }+ maybeHandlePlatformNotification(+ notification,+ {+ showNotification: async (data: PlatformNotificationData) => {+ const notif = new Notification(data.title, data.options);+ return {+ onClick: (cb: any) => {+ notif.addEventListener('click', cb);+ },+ close: () => {+ notif.close();+ },+ };+ },+ } as PlatformNotificationState,+ layoutManager+ );+ };++ onNotification(notification);};const isLoading = () => notificationSource.isLoading();diff --git a/js/app/packages/notifications/index.ts b/js/app/packages/notifications/index.tsindex 2315a0b85b..9a6682f65a 100644--- a/js/app/packages/notifications/index.ts+++ b/js/app/packages/notifications/index.ts@@ -6,7 +6,6 @@ export {EmailDebouncedReadMarker,} from './components/DebouncedNotificationReadMarker';export type {- AppNotification,CreateAppNotificationInterface,NotificationUnsupported,PlatformNotificationInterface,@@ -53,15 +52,18 @@ export {isNewEmail,isNotificationWithMetadata,isRejectTeamInvite,- notificationWithMetadata,+ tryToTypedNotification,} from './notification-metadata';-export type { NavigationActions } from './notification-navigation';-export { navigateToNotification } from './notification-navigation';+export { openNotification } from './notification-navigation';+export type {+ PlatformNotificationData,+ PlatformNotificationHandle,+ toPlatformNotificationData,+} from './notification-platform';export type { NotificationData } from './notification-preview';export {extractNotificationData,NOTIFICATION_LABEL_BY_TYPE,- toBrowserNotification,} from './notification-preview';export type {DocumentNameResolver,diff --git a/js/app/packages/notifications/notification-metadata.ts b/js/app/packages/notifications/notification-metadata.tsindex 6b32a56bfe..a715a7b3d0 100644--- a/js/app/packages/notifications/notification-metadata.ts+++ b/js/app/packages/notifications/notification-metadata.ts@@ -29,15 +29,19 @@ export interface NotificationMetadataByType {export type UnifiedNotificationMetadata =NotificationMetadataByType[keyof NotificationMetadataByType];-export type TypedNotification<T extends NotificationEventType> = Omit<- UnifiedNotification,- 'notificationEventType' | 'notificationMetadata'-> & {- notificationEventType: T;- notificationMetadata: T extends keyof NotificationMetadataByType- ? NotificationMetadataByType[T]- : never;-};+export type TypedNotification<+ T extends NotificationEventType = NotificationEventType,+> = {+ [K in T]: Omit<+ UnifiedNotification,+ 'notificationEventType' | 'notificationMetadata'+ > & {+ notificationEventType: K;+ notificationMetadata: K extends keyof NotificationMetadataByType+ ? NotificationMetadataByType[K]+ : never;+ };+}[T];export function isItemSharedUser(n: UnifiedNotification@@ -168,7 +172,7 @@ export type UnifiedNotificationWithMetadata<T extends keyof NotificationMetadataByType = keyof NotificationMetadataByType,> = TypedNotification<T>;-export function notificationWithMetadata(+export function tryToTypedNotification(notification: UnifiedNotification): TypedNotification<NotificationEventType> | null {if (!isNotificationWithMetadata(notification)) return null;diff --git a/js/app/packages/notifications/notification-navigation.ts b/js/app/packages/notifications/notification-navigation.tsindex e295f9af53..969102dc30 100644--- a/js/app/packages/notifications/notification-navigation.ts+++ b/js/app/packages/notifications/notification-navigation.ts@@ -1,69 +1,164 @@+import type { SplitManager } from '@app/component/split-layout/layoutManager';import type { BlockName } from '@core/block';import { fileTypeToBlockName } from '@core/constant/allBlocks';-import type { NotificationData } from './notification-preview';+import { NotificationType } from '@core/types';+import type { TypedNotification } from '@notifications';+import { errAsync, ResultAsync } from 'neverthrow';+import { match, P } from 'ts-pattern';-export type NavigationActions = {- insertSplit: (item: { type: BlockName; id: string }) => void;- replaceSplit: (item: { type: BlockName; id: string }) => void;- messageLocation: (- channelId: string,- messageId: string,- threadId?: string- ) => Promise<void>;-};+/**+ * Notification event types that are all handled by opening a channel+ * with a specific message and optionally a thread id+ */+const ChannelNotificationType = {+ channel_mention: NotificationType.channel_mention,+ channel_message_send: NotificationType.channel_message_send,+ channel_message_reply: NotificationType.channel_message_reply,+} as const satisfies Partial<Record<string, NotificationType>>;-export function navigateToNotification({- data,- actions,- shouldInsert = false,-}: {- data: NotificationData;- actions: NavigationActions;- shouldInsert?: boolean;-}): void {- const { messageLocation } = actions;+type ChannelNotificationType =+ (typeof ChannelNotificationType)[keyof typeof ChannelNotificationType];- const replaceOrInsertSplit = shouldInsert- ? actions.insertSplit- : actions.replaceSplit;+const CHANNEL_EVENT_TYPES = Object.values(ChannelNotificationType) as [+ ChannelNotificationType,+ ...ChannelNotificationType[],+];- console.log(replaceOrInsertSplit);+/**+ * Opens a split if it is not already open.+ *+ * @param layoutManager The layout manager to use.+ * @param type The type of the block to open.+ * @param id The id of the block to open.+ * @returns A result async that resolves to void if the split was opened successfully, or an error if the split could not be opened.+ */+function openSplitIfNotOpen(+ layoutManager: SplitManager,+ type: BlockName | 'component',+ id: string+) {+ const isSplitOpen = layoutManager.hasSplit(type, id);- if (!data.target?.id) return;+ if (!isSplitOpen) {+ layoutManager.createNewSplit({+ type,+ id,+ });+ }+}- const targetType = data.target.type;- const targetId = data.target.id;+/**+ * Opens a channel notification.+ *+ * @param notification The notification to open.+ * @param layoutManager The layout manager to use.+ * @returns A result async that resolves to void if the notification was opened successfully, or an error if the notification could not be opened.+ */+async function openChannelNotification(+ notification: TypedNotification<ChannelNotificationType>,+ layoutManager: SplitManager+) {+ const channelId = notification.eventItemId;+ const messageId = notification.notificationMetadata.messageId;+ const threadId =+ 'threadId' in notification.notificationMetadata+ ? notification.notificationMetadata.threadId+ : undefined;+ openSplitIfNotOpen(layoutManager, 'channel', channelId);- switch (targetType) {- case 'channel':- if (data.meta?.messageId) {- replaceOrInsertSplit({ type: 'channel', id: targetId });- messageLocation(targetId, data.meta.messageId, data.meta.threadId);- } else {- replaceOrInsertSplit({ type: 'channel', id: targetId });- }- break;+ const orchestrator = layoutManager.getOrchestrator();- case 'document':- if (data.meta?.fileType) {- const blockType = fileTypeToBlockName(data.meta.fileType) as BlockName;- replaceOrInsertSplit({ type: blockType, id: targetId });- }- break;+ const handle = await orchestrator.getBlockHandle(channelId, 'channel');- case 'email':- replaceOrInsertSplit({ type: 'email', id: targetId });- break;+ handle?.goToLocationFromParams({+ message_id: messageId,+ thread_id: threadId,+ });+}- case 'team':- // Team notifications don't have a corresponding block to navigate to- break;+function safeFileTypeToBlockName(fileType: string | undefined | null) {+ return fileTypeToBlockName(fileType) ?? 'unknown';+}++type NotSupportedError = {+ tag: 'NotSupportedError';+ notificationType: NotificationType;+};- default:- if (data.meta?.itemType) {- const blockType = data.meta.itemType.toLowerCase() as BlockName;- replaceOrInsertSplit({ type: blockType, id: targetId });+function getSupportedHandler(+ notification: TypedNotification<NotificationType>+): ((layoutManager: SplitManager) => Promise<void>) | null {+ return match(notification)+ .with(+ { notificationEventType: P.union(...CHANNEL_EVENT_TYPES) },+ (n) => (lm: SplitManager) => openChannelNotification(n, lm)+ )+ .with(+ { notificationEventType: 'new_email' },+ (n) => async (lm: SplitManager) => {+ openSplitIfNotOpen(lm, 'email', n.notificationMetadata.threadId);}- break;+ )+ .with(+ { notificationEventType: 'channel_invite' },+ (n) => async (lm: SplitManager) =>+ openSplitIfNotOpen(lm, 'channel', n.eventItemId)+ )+ .with(+ {+ notificationEventType: P.union(+ 'item_shared_user',+ 'item_shared_organization'+ ),+ },+ (n) => async (lm: SplitManager) =>+ openSplitIfNotOpen(+ lm,+ safeFileTypeToBlockName(n.notificationMetadata.itemType),+ n.eventItemId+ )+ )+ .with(+ {+ notificationEventType: P.union(+ 'document_mention',+ 'channel_message_document'+ ),+ },+ (n) => async (lm: SplitManager) =>+ openSplitIfNotOpen(+ lm,+ safeFileTypeToBlockName(n.notificationMetadata.fileType),+ n.eventItemId+ )+ )+ .with(+ {+ notificationEventType: P.union('invite_to_team', 'reject_team_invite'),+ },+ () => null+ )+ .exhaustive();+}++/**+ * Opens the notification given the layout manager.+ * Some notifications are not supported and will return an error.+ *+ * @param notification The notification to open.+ * @param layoutManager The layout manager to use.+ * @returns A result async that resolves to void if the notification was opened successfully, or an error if the notification is not supported.+ */+export function openNotification(+ notification: TypedNotification<NotificationType>,+ layoutManager: SplitManager+): ResultAsync<void, NotSupportedError> {+ const handler = getSupportedHandler(notification);+ if (!handler) {+ return errAsync({+ tag: 'NotSupportedError',+ notificationType: notification.notificationEventType,+ });}+ return ResultAsync.fromSafePromise(handler(layoutManager));}diff --git a/js/app/packages/notifications/notification-platform.ts b/js/app/packages/notifications/notification-platform.tsnew file mode 100644index 0000000000..a634b04585--- /dev/null+++ b/js/app/packages/notifications/notification-platform.ts@@ -0,0 +1,107 @@+import type { SplitManager } from '@app/component/split-layout/layoutManager';+import { getFaviconUrl } from '@app/util/favicon';+import { markdownToPlainText } from '@lexical-core';+import type { UnifiedNotification } from '@service-notification/client';+import { themeReactive } from '../block-theme/signals/themeReactive';+import type { PlatformNotificationState } from './components/PlatformNotificationProvider';+import { tryToTypedNotification } from './notification-metadata';+import { openNotification } from './notification-navigation';+import {+ extractNotificationData,+ type NotificationData,+} from './notification-preview';+import {+ DefaultDocumentNameResolver,+ DefaultUserNameResolver,+ type DocumentNameResolver,+ type UserNameResolver,+} from './notification-resolvers';++/// the interface for a singular notification on this device+export interface PlatformNotificationHandle {+ onClick: (cb: () => void) => void;+ close: () => void;+}++export interface PlatformNotificationData {+ title: string;+ options?: NotificationOptions;+}++const USER_NAME_FALLBACK = 'Someone';+const DOCUMENT_NAME_FALLBACK = 'Something';++function getAccentColorForIcon(): string {+ const { l, c, h } = themeReactive.a0;+ return `oklch(${l[0]()} ${c[0]()} ${h[0]()}deg)`;+}++export async function toPlatformNotificationData(+ data: NotificationData,+ resolveUserName: UserNameResolver,+ resolveDocumentName: DocumentNameResolver+): Promise<PlatformNotificationData | null> {+ if (!data) return null;++ const actor =+ (data.actor ? await resolveUserName(data.actor.id) : undefined) ??+ USER_NAME_FALLBACK;++ const showTarget = data.target?.show ?? false;++ const targetName =+ data.target?.name ??+ (data.target?.id+ ? await resolveDocumentName(data.target.id, data.target.type)+ : undefined) ??+ DOCUMENT_NAME_FALLBACK;++ const accentColor = getAccentColorForIcon();+ const icon = getFaviconUrl(accentColor);++ return {+ title: `${actor}${showTarget ? ` <${targetName}>` : ''}`,+ options: {+ body: data.content ? markdownToPlainText(data.content) : `${data.action}`,+ icon,+ },+ };+}++/**+ * Maybe handles a new notification as a platform notification.+ * If the notification is supported and formattable emit it and handle click events.+ * @param notification+ * @param notificationInterface+ * @param splitLayoutManager+ */+export async function maybeHandlePlatformNotification(+ notification: UnifiedNotification,+ notificationInterface: PlatformNotificationState,+ splitLayoutManager: SplitManager+) {+ const nm = tryToTypedNotification(notification);+ if (!nm) return;+ const data = extractNotificationData(nm);+ if (data === 'no_extractor' || data === 'no_extracted_data') return;++ const platformNotificationData = await toPlatformNotificationData(+ data,+ DefaultUserNameResolver,+ DefaultDocumentNameResolver+ );++ if (platformNotificationData) {+ let notificationHandle = await notificationInterface.showNotification(+ platformNotificationData+ );+ if (+ notificationHandle !== 'not-granted' &&+ notificationHandle !== 'disabled-in-ui'+ ) {+ notificationHandle.onClick(() => {+ openNotification(nm, splitLayoutManager);+ });+ }+ }+}diff --git a/js/app/packages/notifications/notification-preview.ts b/js/app/packages/notifications/notification-preview.tsindex 96292c1d42..8968aed5ac 100644--- a/js/app/packages/notifications/notification-preview.ts+++ b/js/app/packages/notifications/notification-preview.ts@@ -2,10 +2,6 @@ import type { BlockName } from '@core/block';import { type EntityType, NotificationType } from '@core/types';import type { NotificationEventType } from '@service-notification/generated/schemas';import type { TypedNotification } from './notification-metadata';-import type {- DocumentNameResolver,- UserNameResolver,-} from './notification-resolvers';export type NotificationData = {actor?: { id: string };@@ -234,51 +230,3 @@ export function extractNotificationData<T extends NotificationEventType>(if (!extractor) return 'no_extractor';return extractor(notification as any) ?? 'no_extracted_data';}--export interface BrowserNotificationPreview {- title: string;- body: string;- icon: string;-}--import { getFaviconUrl } from '@app/util/favicon';-import { markdownToPlainText } from '@lexical-core';-import { themeReactive } from '../block-theme/signals/themeReactive';--const USER_NAME_FALLBACK = 'Someone';-const DOCUMENT_NAME_FALLBACK = 'Something';--function getAccentColorForIcon(): string {- const { l, c, h } = themeReactive.a0;- return `oklch(${l[0]()} ${c[0]()} ${h[0]()}deg)`;-}--export async function toBrowserNotification(- data: NotificationData,- resolveUserName: UserNameResolver,- resolveDocumentName: DocumentNameResolver-): Promise<BrowserNotificationPreview | null> {- if (!data) return null;-- const actor =- (data.actor ? await resolveUserName(data.actor.id) : undefined) ??- USER_NAME_FALLBACK;-- const showTarget = data.target?.show ?? false;-- const targetName =- data.target?.name ??- (data.target?.id- ? await resolveDocumentName(data.target.id, data.target.type)- : undefined) ??- DOCUMENT_NAME_FALLBACK;-- const accentColor = getAccentColorForIcon();- const icon = getFaviconUrl(accentColor);-- return {- title: `${actor}${showTarget ? ` <${targetName}>` : ''}`,- body: data.content ? markdownToPlainText(data.content) : `${data.action}`,- icon,- };-}diff --git a/js/app/packages/notifications/notification-source.ts b/js/app/packages/notifications/notification-source.tsindex d9098e0669..823f806117 100644--- a/js/app/packages/notifications/notification-source.ts+++ b/js/app/packages/notifications/notification-source.ts@@ -23,15 +23,6 @@ import {type Store,unwrap,} from 'solid-js/store';-import { notificationWithMetadata } from './notification-metadata';-import {- extractNotificationData,- toBrowserNotification,-} from './notification-preview';-import {- DefaultDocumentNameResolver,- DefaultUserNameResolver,-} from './notification-resolvers';import { fetchNotificationsForEntities } from './queries/entities-notifications-query';import { createMutedEntitiesQuery } from './queries/muted-entities-query';import {@@ -84,7 +75,7 @@ const QUERY_LIMIT = 500;export function createNotificationSource(ws: ConnectionGatewayWebsocket,- onNotification?: (title: string, opts: NotificationOptions) => void+ onNotification?: (notification: UnifiedNotification) => void): NotificationSource {const [store, setStore] = createStore<NotificationStoreInner>({});const notifications = createMemo(() =>@@ -165,25 +156,6 @@ export function createNotificationSource(reconcileNotifications(unwrap(notificationsQuery.data));});- const maybeHandleBrowserNotification = async (- notification: UnifiedNotification- ) => {- const nm = notificationWithMetadata(notification);- if (!nm) return;- const data = extractNotificationData(nm);- if (data === 'no_extractor' || data === 'no_extracted_data') return;-- const browserNotification = await toBrowserNotification(- data,- DefaultUserNameResolver,- DefaultDocumentNameResolver- );-- if (browserNotification) {- onNotification?.(browserNotification.title, browserNotification);- }- };-createSocketEffect(ws, (wsData) => {if (wsData.type !== NOTIFICATION_EVENT_TYPE) {return;@@ -195,7 +167,7 @@ export function createNotificationSource(console.error('Failed to parse notification', wsData.data, e);return;}- maybeHandleBrowserNotification(parsedNotification);+ onNotification?.(parsedNotification);refetchAndReconcileNotifications([parsedNotification]);});diff --git a/js/app/packages/tauri/src/notification.ts b/js/app/packages/tauri/src/notification.tsindex 5b99474631..dbe8b78a62 100644--- a/js/app/packages/tauri/src/notification.ts+++ b/js/app/packages/tauri/src/notification.ts@@ -1,5 +1,5 @@import type {- AppNotification,+ PlatformNotificationHandle,PlatformNotificationInterface,} from '@notifications';import {@@ -23,21 +23,21 @@ export function createTauriNotificationInterface(return await requestPermission();},getCurrentPermission: getCur,- showNotification: async (title, opts) => {+ showNotification: async (data) => {const granted = await getCur();if (granted !== 'granted') {return 'not-granted';}- if (!opts) {- sendNotification(title);+ if (!data.options) {+ sendNotification(data.title);return createTauriNotification();}- const { body, icon, ...rest } = opts;+ const { body, icon, ...rest } = data.options;sendNotification({- title,+ title: data.title,body,icon,extra: {@@ -50,7 +50,7 @@ export function createTauriNotificationInterface(};}-function createTauriNotification(): AppNotification {+function createTauriNotification(): PlatformNotificationHandle {return {onClick: (_cb) => {console.warn(