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.

Seanaye/feat/handle fe notification updates (#3432)

Sean Ayeee9232e912ba
diff --git a/js/app/packages/notifications/notification-source.ts b/js/app/packages/notifications/notification-source.ts
index 87cf759b39..decbb0dc86 100644
--- a/js/app/packages/notifications/notification-source.ts
+++ b/js/app/packages/notifications/notification-source.ts
@@ -1,6 +1,8 @@
import { ENABLE_DOCUMENT_MENTION_NOTIFICATIONS } from '@core/constant/featureFlags';
import type { Entity } from '@core/types';
import {
+ applyNotificationStatusUpdate,
+ type NotificationStatusUpdate,
optimisticInsertNotification,
useMarkNotificationsAsDoneMutation,
useMarkNotificationsAsSeenMutation,
@@ -89,6 +91,7 @@ export type NotificationSource = {
};
const NOTIFICATION_EVENT_TYPE = 'notification';
+const NOTIFICATION_STATUS_UPDATED_EVENT_TYPE = 'notification_status_updated';
const QUERY_LIMIT = 500;
@@ -212,6 +215,24 @@ export function createNotificationSource(
};
createSocketEffect(ws, (wsData) => {
+ if (wsData.type === NOTIFICATION_STATUS_UPDATED_EVENT_TYPE) {
+ try {
+ const update = (
+ typeof wsData.data === 'string'
+ ? JSON.parse(wsData.data)
+ : wsData.data
+ ) as NotificationStatusUpdate;
+ applyNotificationStatusUpdate(update);
+ } catch (e) {
+ console.error(
+ 'Failed to parse notification status update',
+ wsData.data,
+ e
+ );
+ }
+ return;
+ }
+
if (wsData.type !== NOTIFICATION_EVENT_TYPE) {
return;
}
diff --git a/js/app/packages/queries/notification/tests/user-notifications.test.tsx b/js/app/packages/queries/notification/tests/user-notifications.test.tsx
index 478fa0e523..3d9a85966b 100644
--- a/js/app/packages/queries/notification/tests/user-notifications.test.tsx
+++ b/js/app/packages/queries/notification/tests/user-notifications.test.tsx
@@ -12,6 +12,7 @@ import { render } from 'solid-js/web';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { notificationKeys } from '../keys';
import {
+ applyNotificationStatusUpdate,
optimisticInsertNotification,
useMarkNotificationsAsDoneMutation,
useMarkNotificationsAsSeenMutation,
@@ -32,6 +33,11 @@ vi.mock('@queries/soup/normalized-cache', () => ({
optimisticUpdateSoupItemUpdatedAt: vi.fn(),
}));
+vi.mock('@app/signal/sidebarBadges', () => ({
+ removeBadgeNotifications: vi.fn(),
+}));
+
+import { removeBadgeNotifications } from '@app/signal/sidebarBadges';
import { optimisticUpdateSoupItemUpdatedAt } from '@queries/soup/normalized-cache';
import { notificationServiceClient } from '@service-notification/client';
@@ -44,6 +50,7 @@ const mockBulkMarkNotificationAsDone = vi.mocked(
const mockOptimisticUpdateSoupItemUpdatedAt = vi.mocked(
optimisticUpdateSoupItemUpdatedAt
);
+const mockRemoveBadgeNotifications = vi.mocked(removeBadgeNotifications);
let testQueryClient: QueryClient;
@@ -139,6 +146,75 @@ function renderWithClient(Component: () => JSX.Element): () => void {
};
}
+describe('notification realtime status updates', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ testQueryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+ });
+
+ afterEach(() => {
+ testQueryClient.clear();
+ });
+
+ it('patches notifications in the user cache', () => {
+ const n1 = createMockNotification({ id: 'n1', viewed_at: null });
+ const n2 = createMockNotification({ id: 'n2', viewed_at: null });
+ seedQueryCache([createMockNotificationPage([n1, n2])]);
+
+ applyNotificationStatusUpdate({
+ type: 'notification_status_updated',
+ updates: [
+ {
+ t: 'Patch',
+ c: {
+ id: 'n1',
+ done: false,
+ viewed_at: '2024-01-01T00:00:00.000Z',
+ updated_at: '2024-01-01T00:00:01.000Z',
+ },
+ },
+ ],
+ });
+
+ const notifications = getNotificationsFromCache();
+ expect(notifications[0].viewed_at).toBe('2024-01-01T00:00:00.000Z');
+ expect(notifications[0].updated_at).toBe('2024-01-01T00:00:01.000Z');
+ expect(notifications[1].viewed_at).toBe(null);
+ expect(mockRemoveBadgeNotifications).toHaveBeenCalledWith(['n1']);
+ });
+
+ it('removes deleted and done notifications from the user cache', () => {
+ const n1 = createMockNotification({ id: 'n1' });
+ const n2 = createMockNotification({ id: 'n2' });
+ const n3 = createMockNotification({ id: 'n3' });
+ seedQueryCache([createMockNotificationPage([n1, n2, n3])]);
+
+ applyNotificationStatusUpdate({
+ type: 'notification_status_updated',
+ updates: [
+ { t: 'Delete', c: { id: 'n1' } },
+ {
+ t: 'Patch',
+ c: {
+ id: 'n2',
+ done: true,
+ viewed_at: null,
+ updated_at: '2024-01-01T00:00:01.000Z',
+ },
+ },
+ ],
+ });
+
+ expect(getNotificationsFromCache().map((n) => n.id)).toEqual(['n3']);
+ expect(mockRemoveBadgeNotifications).toHaveBeenCalledWith(['n1', 'n2']);
+ });
+});
+
describe('notification mutations', () => {
beforeEach(() => {
vi.clearAllMocks();
diff --git a/js/app/packages/queries/notification/user-notifications.ts b/js/app/packages/queries/notification/user-notifications.ts
index 1783c398c8..efb23b5993 100644
--- a/js/app/packages/queries/notification/user-notifications.ts
+++ b/js/app/packages/queries/notification/user-notifications.ts
@@ -1,3 +1,4 @@
+import { removeBadgeNotifications } from '@app/signal/sidebarBadges';
import type { Maybe } from '@core/types';
import { type ResultError, throwOnErr } from '@core/util/result';
import type { UnifiedNotification } from '@notifications/types';
@@ -400,6 +401,86 @@ export const useMarkNotificationsAsDoneMutation = createNotificationsMutation(
type NotificationItem = GetAllUserNotificationsResponse['items'][number];
+export type NotificationStatusPatch = {
+ id: string;
+ done: boolean;
+ viewed_at: string | null;
+ updated_at: string;
+};
+
+export type NotificationStatusPatchDelete =
+ | { t: 'Patch'; c: NotificationStatusPatch }
+ | { t: 'Delete'; c: { id: string } };
+
+export type NotificationStatusUpdate = {
+ type: 'notification_status_updated';
+ updates: NotificationStatusPatchDelete[];
+};
+
+function applyNotificationStatusPatch(
+ notification: NotificationItem,
+ patch: NotificationStatusPatch
+): NotificationItem {
+ return {
+ ...notification,
+ ...(patch.done !== undefined ? { done: patch.done } : {}),
+ ...(patch.viewed_at !== undefined ? { viewed_at: patch.viewed_at } : {}),
+ ...(patch.updated_at !== undefined ? { updated_at: patch.updated_at } : {}),
+ };
+}
+
+export function applyNotificationStatusUpdate(
+ update: NotificationStatusUpdate
+) {
+ const patches = update.updates
+ .filter((item) => item.t === 'Patch')
+ .map((item) => item.c);
+ const patchById = new Map(patches.map((patch) => [patch.id, patch]));
+ const deleteIds = new Set(
+ update.updates
+ .filter((item) => item.t === 'Delete')
+ .map((item) => item.c.id)
+ );
+ const doneIds = new Set(
+ [...patchById.values()]
+ .filter((patch) => patch.done === true)
+ .map((patch) => patch.id)
+ );
+ const removeIds = new Set([...deleteIds, ...doneIds]);
+ const viewedIds = patches
+ .filter((patch) => patch.viewed_at)
+ .map((patch) => patch.id);
+
+ queryClient.setQueriesData<NotificationData<UserNotificationsPageParam>>(
+ { queryKey: notificationKeys.user._def },
+ (data) => {
+ if (!data) return data;
+
+ return {
+ ...data,
+ pages: data.pages.map((page) => ({
+ ...page,
+ items: page.items
+ .filter((notification) => !removeIds.has(notification.id))
+ .map((notification) => {
+ const patch = patchById.get(notification.id);
+ return patch
+ ? applyNotificationStatusPatch(notification, patch)
+ : notification;
+ }),
+ })),
+ };
+ }
+ );
+
+ removeBadgeNotifications([...removeIds, ...viewedIds]);
+
+ queryClient.invalidateQueries({
+ queryKey: notificationKeys.user._def,
+ refetchType: 'none',
+ });
+}
+
/**
* Lookup a notification by id via the notification-service.
*/
diff --git a/js/app/packages/queries/sync/SyncProvider.tsx b/js/app/packages/queries/sync/SyncProvider.tsx
index 76d567bb40..844a6ee903 100644
--- a/js/app/packages/queries/sync/SyncProvider.tsx
+++ b/js/app/packages/queries/sync/SyncProvider.tsx
@@ -5,6 +5,10 @@ import {
} from '@queries/channel/sync';
import { handleCommsTyping } from '@queries/channel/typing';
import { invalidateContacts } from '@queries/contacts/contacts';
+import {
+ applyNotificationStatusUpdate,
+ type NotificationStatusUpdate,
+} from '@queries/notification/user-notifications';
// Side-effect import: registers the scheduled-action live-update websocket
// listener. Must be imported somewhere that always loads on app start — this
// provider is guaranteed to mount alongside the other sync handlers.
@@ -12,11 +16,35 @@ import '@queries/agent-schedule/sync';
import { createConnectionWebsocketEffect } from '@service-connection/websocket';
import type { Accessor, ParentProps } from 'solid-js';
import { match } from 'ts-pattern';
+import { z } from 'zod';
type SyncProviderProps = ParentProps<{
userId: Accessor<string | undefined>;
}>;
+const notificationStatusUpdateSchema = z.object({
+ type: z.literal('notification_status_updated'),
+ updates: z.array(
+ z.discriminatedUnion('t', [
+ z.object({
+ t: z.literal('Patch'),
+ c: z.object({
+ id: z.string(),
+ done: z.boolean(),
+ viewed_at: z.string().nullable(),
+ updated_at: z.string(),
+ }),
+ }),
+ z.object({
+ t: z.literal('Delete'),
+ c: z.object({
+ id: z.string(),
+ }),
+ }),
+ ])
+ ),
+}) satisfies z.ZodType<NotificationStatusUpdate>;
+
export function QuerySyncProvider(props: SyncProviderProps) {
createConnectionWebsocketEffect((data) => {
const payload =
@@ -40,6 +68,14 @@ export function QuerySyncProvider(props: SyncProviderProps) {
if (!userId) return;
handleCommsTyping(payload, userId);
})
+ .with({ type: 'notification_status_updated' }, () => {
+ const result = notificationStatusUpdateSchema.safeParse(payload);
+ if (!result.success) {
+ console.warn('Malformed notification status update payload', payload);
+ return;
+ }
+ applyNotificationStatusUpdate(result.data);
+ })
.otherwise(() => {});
});
diff --git a/rust/cloud-storage/notification/src/domain/models.rs b/rust/cloud-storage/notification/src/domain/models.rs
index 515731457f..0280a801bd 100644
--- a/rust/cloud-storage/notification/src/domain/models.rs
+++ b/rust/cloud-storage/notification/src/domain/models.rs
@@ -48,7 +48,7 @@ pub struct NotificationStatusPatch {
/// A patch-or-delete update for an entity identified by `I`.
#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(untagged)]
+#[serde(tag = "t", content = "c")]
pub enum PatchDelete<I, T> {
/// The value with id I should be patched with data T.
Patch {