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 browser and tauri notifications (#911)
Peter Chinman301379191edd
diff --git a/js/app/packages/app/component/dock/QuickAccess.tsx b/js/app/packages/app/component/dock/QuickAccess.tsxindex 165f4889a0..4ae0ae2ffc 100644--- a/js/app/packages/app/component/dock/QuickAccess.tsx+++ b/js/app/packages/app/component/dock/QuickAccess.tsx@@ -3,6 +3,7 @@ import {useGlobalNotificationSource,} from '@app/component/GlobalAppState';import { useSplitLayout } from '@app/component/split-layout/layout';+import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';import { useChannelsContext } from '@core/component/ChannelsProvider';import { Tooltip } from '@core/component/Tooltip';import { UserIcon } from '@core/component/UserIcon';@@ -64,8 +65,8 @@ function QuickAccessItem(props: QuickAccessItemProps) {) => {const blockHandle = await blockOrchestrator.getBlockHandle(channelId);await blockHandle?.goToLocationFromParams({- message_id: messageId,- thread_id: threadId,+ [CHANNEL_URL_PARAMS.message]: messageId,+ [CHANNEL_URL_PARAMS.thread]: threadId,});};diff --git a/js/app/packages/app/component/split-layout/componentRegistry.tsx b/js/app/packages/app/component/split-layout/componentRegistry.tsxindex 19f2aed37a..4692b5e59e 100644--- a/js/app/packages/app/component/split-layout/componentRegistry.tsx+++ b/js/app/packages/app/component/split-layout/componentRegistry.tsx@@ -7,6 +7,7 @@ import { type JSXElement, lazy } from 'solid-js';import { EmailCompose } from '../../../block-email/component/Compose';import { Soup } from '../Soup';import { SettingsPanel } from '../settings/Settings';+import NotificationRoute from '@notifications/components/NotificationRoute';export type ComponentFactory = (params?: Record<string, any>) => JSXElement;@@ -60,6 +61,7 @@ registerComponent('channel-compose', () => <ChannelCompose />);registerComponent('email-compose', () => <EmailCompose />);registerComponent('task-compose', () => <ComposeTask />);registerComponent('settings', () => <SettingsPanel />);+registerComponent('notification', () => <NotificationRoute />);if (LOCAL_ONLY) {registerComponent(diff --git a/js/app/packages/block-channel/component/MessageList/MessageList.tsx b/js/app/packages/block-channel/component/MessageList/MessageList.tsxindex b137611860..5b4debcb53 100644--- a/js/app/packages/block-channel/component/MessageList/MessageList.tsx+++ b/js/app/packages/block-channel/component/MessageList/MessageList.tsx@@ -294,6 +294,10 @@ function MessageListImpl(props: MessageListProps) {const [lastTargetMessageTimestamp, setLastTargetMessageTimestamp] =createSignal<number>(Date.now());+ // Track missing target message retries+ let missingTargetRetryCount = 0;+ let lastMissingTargetId: string | undefined;+// represents active highlighted state on the target messageconst [targetMessageActive, setTargetMessageActive] =createSignal<boolean>(false);@@ -338,12 +342,33 @@ function MessageListImpl(props: MessageListProps) {?.findIndex((m) => m.id === targetMessageId);if (index === -1) {+ // Retry briefly to allow hydration to complete before showing an error. Necessary for push notifications.+ if (lastMissingTargetId !== targetMessageId) {+ lastMissingTargetId = targetMessageId;+ missingTargetRetryCount = 0;+ }++ const retries = missingTargetRetryCount;+ if (retries < 6) {+ missingTargetRetryCount = retries + 1;+ setLastTargetMessageTimestamp(Date.now());+ setTimeout(() => {+ scrollToBottomOrTarget();+ }, 200);+ return;+ }+console.warn('Target message not found');toast.failure('Message not found.');scrollToBottomOrTarget({ forceBottom: true });return;}+ // Reset retry state on success.+ if (lastMissingTargetId === targetMessageId) {+ missingTargetRetryCount = 0;+ }+if (threadId) {listContext.toggleThread(threadId, true);}diff --git a/js/app/packages/notifications/components/NotificationRoute.tsx b/js/app/packages/notifications/components/NotificationRoute.tsxnew file mode 100644index 0000000000..b62c4147d9--- /dev/null+++ b/js/app/packages/notifications/components/NotificationRoute.tsx@@ -0,0 +1,60 @@+import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';+import { globalSplitManager } from '@app/signal/splitLayout';+import { LoadingBlock } from '@core/component/LoadingBlock';+import { toast } from '@core/component/Toast/Toast';+import { openNotificationFromId } from '@notifications/notification-navigation';+import { logger } from '@observability';+import { useSearchParams } from '@solidjs/router';+import { createEffect, onCleanup, onMount } from 'solid-js';++export default function NotificationRoute() {+ const split = useSplitPanelOrThrow();+ const [searchParams] = useSearchParams();++ const getNotificationId = (): string | undefined => {+ const raw = searchParams.notificationId;+ if (typeof raw === 'string') return raw;+ if (Array.isArray(raw) && typeof raw[0] === 'string') return raw[0];+ return undefined;+ };++ const replaceWithUnifiedList = (cause?: Error) => {+ logger.error('Failed to open notification.', { cause });+ toast.failure('Failed to open notification.');+ split.handle.replace({+ next: { type: 'component', id: 'unified-list' },+ mergeHistory: true,+ });+ };++ // Give the router a tick to populate params before falling back to unified-list+ onMount(() => {+ const timeout = window.setTimeout(() => {+ const notificationId = getNotificationId();+ if (!notificationId) {+ replaceWithUnifiedList(new Error('No notification ID found.'));+ }+ }, 0);+ onCleanup(() => window.clearTimeout(timeout));+ });++ createEffect(() => {+ const notificationId = getNotificationId();+ const layoutManager = globalSplitManager();+ if (!notificationId) return;+ if (!layoutManager) return;++ openNotificationFromId(notificationId, layoutManager).match(+ () => {+ // We only use this route as a "bridge" from external navigation+ // (e.g. push tap / deep link) into the split layout.+ split.handle.close();+ },+ (err) => {+ replaceWithUnifiedList(new Error(err.tag));+ }+ );+ });++ return <LoadingBlock />;+}diff --git a/js/app/packages/notifications/notification-navigation.ts b/js/app/packages/notifications/notification-navigation.tsindex cca6ed1f49..ab2e56337c 100644--- a/js/app/packages/notifications/notification-navigation.ts+++ b/js/app/packages/notifications/notification-navigation.ts@@ -1,10 +1,15 @@import type { SplitManager } from '@app/component/split-layout/layoutManager';+import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';import type { BlockAlias, BlockName } from '@core/block';import { fileTypeToBlockName } from '@core/constant/allBlocks';import { NotificationType } from '@core/types';-import type { TypedNotification } from '@notifications';+import { getNotificationById } from '@queries/notification/user-notifications';import { errAsync, ResultAsync } from 'neverthrow';import { match, P } from 'ts-pattern';+import {+ tryToTypedNotification,+ type TypedNotification,+} from './notification-metadata';/*** Notification event types that are all handled by opening a channel@@ -37,14 +42,16 @@ function openSplitIfNotOpen(type: BlockName | BlockAlias | 'component',id: string) {- const isSplitOpen = layoutManager.hasSplit(type, id);-- if (!isSplitOpen) {- layoutManager.createNewSplit({- content: { type, id },- referredFrom: null,- });+ const existing = layoutManager.getSplitByContent(type, id);+ if (existing) {+ existing.activate();+ return;}+ layoutManager.createNewSplit({+ content: { type, id },+ activate: true,+ referredFrom: null,+ });}/**@@ -71,8 +78,8 @@ async function openChannelNotification(const handle = await orchestrator.getBlockHandle(channelId, 'channel');handle?.goToLocationFromParams({- message_id: messageId,- thread_id: threadId,+ [CHANNEL_URL_PARAMS.message]: messageId,+ [CHANNEL_URL_PARAMS.thread]: threadId,});}@@ -85,6 +92,21 @@ type NotSupportedError = {notificationType: NotificationType;};+type NotFoundError = {+ tag: 'NotFoundError';+ notificationId: string;+};++type NotTypedError = {+ tag: 'NotTypedError';+ notificationId: string;+};++export type OpenNotificationFromIdError =+ | NotSupportedError+ | NotFoundError+ | NotTypedError;+function getSupportedHandler(notification: TypedNotification<NotificationType>): ((layoutManager: SplitManager) => Promise<void>) | null {@@ -168,3 +190,25 @@ export function openNotification(}return ResultAsync.fromSafePromise(handler(layoutManager));}++export function openNotificationFromId(+ notificationId: string,+ layoutManager: SplitManager+): ResultAsync<void, OpenNotificationFromIdError> {+ return ResultAsync.fromSafePromise(+ getNotificationById(notificationId)+ ).andThen((unified) => {+ if (!unified) {+ const err: NotFoundError = { tag: 'NotFoundError', notificationId };+ return errAsync(err);+ }++ const typed = tryToTypedNotification(unified);+ if (!typed) {+ const err: NotTypedError = { tag: 'NotTypedError', notificationId };+ return errAsync(err);+ }++ return openNotification(typed, layoutManager);+ });+}diff --git a/js/app/packages/queries/notification/user-notifications.ts b/js/app/packages/queries/notification/user-notifications.tsindex 3b3a6d92dc..ea10d21d0e 100644--- a/js/app/packages/queries/notification/user-notifications.ts+++ b/js/app/packages/queries/notification/user-notifications.ts@@ -362,6 +362,21 @@ export const useMarkNotificationsAsDoneMutation = createNotificationsMutation(type NotificationItem = GetAllUserNotificationsResponse['items'][number];+/**+ * Lookup a notification by id via the notification-service.+ */+export async function getNotificationById(+ notificationId: string+): Promise<NotificationItem | undefined> {+ const res = await throwOnErr(async () => {+ return await notificationServiceClient.getUserNotificationById(+ notificationId+ );+ });++ return res as NotificationItem;+}+export function optimisticInsertNotification(notification: Omit<NotificationItem, 'ownerId'>) {diff --git a/js/app/packages/service-clients/service-notification/client.ts b/js/app/packages/service-clients/service-notification/client.tsindex cb7c2991b3..e0ad5691eb 100644--- a/js/app/packages/service-clients/service-notification/client.ts+++ b/js/app/packages/service-clients/service-notification/client.ts@@ -117,6 +117,15 @@ export const notificationServiceClient = {});},+ async getUserNotificationById(notificationId: string) {+ return mapOk(+ await notificationFetch<UserNotification>(+ `/user_notifications/${notificationId}`,+ { method: 'GET' }+ ),+ (result) => result+ );+ },async bulkGetUserNotificationsByEventItemId(args: GetUserNotificationParams &BulkGetUserNotificationsByEventItemIdRequestdiff --git a/js/app/packages/tauri/src/PushNotification.tsx b/js/app/packages/tauri/src/PushNotification.tsxindex 0f86a7c4ee..d0c498f69d 100644--- a/js/app/packages/tauri/src/PushNotification.tsx+++ b/js/app/packages/tauri/src/PushNotification.tsx@@ -22,6 +22,7 @@ import {type JSX,type Setter,} from 'solid-js';+import { triggerNavigation } from './navigation';import { createTauriNotificationInterface } from './notification';import { useExpectTauri } from './TauriProvider';@@ -127,7 +128,19 @@ export function MaybePushNotificationRegistration(props: {);}- const push = usePushNotifications(os);+ const push = usePushNotifications(os, (event) => {+ const notificationId: string | undefined = event.payload.notificationId;++ const tapped =+ event.type === 'BACKGROUND_TAP' || event.type === 'FOREGROUND_TAP';+ // Only navigate on explicit user interaction.+ if (!tapped) return;+ if (!notificationId) return;++ triggerNavigation(+ `/component/notification?notificationId=${notificationId}`+ );+ });// now we compose the standard tauri notif plugin with the push notification pluginfunction curriedTauriPushNotification(@@ -137,11 +150,19 @@ export function MaybePushNotificationRegistration(props: {requestPermission,unregisterNotifications,getCurrentPermission,- showNotification,+ showNotification: baseShowNotification,} = createTauriNotificationInterface(setDisabled);return {- showNotification,+ showNotification: async (data) => {+ // If remote push is enabled, the OS will display notifications for us.+ // Avoid also generating a local notification from websocket events,+ // which would cause duplicates.+ if (push.permission() === 'granted') {+ return 'not-granted';+ }+ return baseShowNotification(data);+ },getCurrentPermission: async () => {const appNotification = await getCurrentPermission();if (appNotification === 'granted' && push.permission() === 'granted') {diff --git a/js/app/packages/tauri/src/navigation.ts b/js/app/packages/tauri/src/navigation.tsindex 4babbe7db6..af471b4e73 100644--- a/js/app/packages/tauri/src/navigation.ts+++ b/js/app/packages/tauri/src/navigation.ts@@ -5,21 +5,53 @@ import { createEffect, onCleanup } from 'solid-js';type NavigateEvent = {path: string;query: string;+ notificationId?: string;};+let registeredNavigate: ((path: string) => void) | null = null;++/**+ * Register a navigate function to be called from outside the router context.+ * Called by useTauriNavigationEffect when the router is ready.+ */+export function registerNavigate(fn: (path: string) => void) {+ registeredNavigate = fn;+}++/**+ * Trigger navigation from outside the router context.+ * Used by PushNotification to navigate when a notification is tapped.+ */+export function triggerNavigation(path: string) {+ if (registeredNavigate) {+ registeredNavigate(path);+ } else {+ console.warn('Navigation triggered before navigate was registered');+ }+}+/// this must be used as a child of routerexport function useTauriNavigationEffect() {const navigate = useNavigate();++ registerNavigate(navigate);+createEffect(() => {let unsubscribe: () => void | undefined;async function inner() {unsubscribe = await listen<NavigateEvent>('navigate', (ev) => {console.info({ ev });- if (ev.payload.query) {- navigate(`${ev.payload.path}?${ev.payload.query}`);+ if (ev.payload.notificationId) {+ navigate(+ `/component/notification?notificationId=${ev.payload.notificationId}`+ );} else {- navigate(ev.payload.path);+ if (ev.payload.query) {+ navigate(`${ev.payload.path}?${ev.payload.query}`);+ } else {+ navigate(ev.payload.path);+ }}});}