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.

feat(github): github pr notifications (#3686)

Will Hutchinson407b654f65c8
diff --git a/js/app/packages/core/component/AI/component/tool/Notifications.tsx b/js/app/packages/core/component/AI/component/tool/Notifications.tsx
index 44edf48ec8..0724f76ac6 100644
--- a/js/app/packages/core/component/AI/component/tool/Notifications.tsx
+++ b/js/app/packages/core/component/AI/component/tool/Notifications.tsx
@@ -18,6 +18,7 @@ const NOTIFICATION_TYPE_LABELS: Record<NotificationFilterType, string> = {
chat: 'chats',
call: 'calls',
task: 'tasks',
+ github: 'GitHub',
};
const formatList = (items: string[]) => {
diff --git a/js/app/packages/entity/src/extractors-notification/notification-description-helpers.ts b/js/app/packages/entity/src/extractors-notification/notification-description-helpers.ts
index 7cb1f3e636..aab4385a87 100644
--- a/js/app/packages/entity/src/extractors-notification/notification-description-helpers.ts
+++ b/js/app/packages/entity/src/extractors-notification/notification-description-helpers.ts
@@ -34,6 +34,7 @@ export function getActionVerb(type: NotificationType): string {
.with('channel_invite', () => 'invited you')
.with('invite_to_team', () => 'invited you')
.with('task_assigned', () => 'assigned you')
+ .with('github_pr_event', () => 'updated a pull request')
.with('call-started', () => 'started a call')
.exhaustive();
}
@@ -62,6 +63,9 @@ export function getTypeNoun(type: NotificationType, count: number): string {
.with('channel_invite', () => (count === 1 ? 'invite' : 'invites'))
.with('invite_to_team', () => (count === 1 ? 'invite' : 'invites'))
.with('task_assigned', () => (count === 1 ? 'task' : 'tasks'))
+ .with('github_pr_event', () =>
+ count === 1 ? 'pull request' : 'pull requests'
+ )
.with('call-started', () => (count === 1 ? 'call' : 'calls'))
.exhaustive();
}
diff --git a/js/app/packages/entity/src/extractors-notification/notification-icon.tsx b/js/app/packages/entity/src/extractors-notification/notification-icon.tsx
index 30fa4e6eca..4e26086d3e 100644
--- a/js/app/packages/entity/src/extractors-notification/notification-icon.tsx
+++ b/js/app/packages/entity/src/extractors-notification/notification-icon.tsx
@@ -1,4 +1,5 @@
import type { NotificationType } from '@core/types';
+import GithubIcon from '@icon/mcp-github.svg';
import PhoneIcon from '@icon/wide-call.svg';
import type { NotificationStack } from '@notifications';
import ArrowBendUpLeftIcon from '@phosphor/arrow-bend-up-left.svg';
@@ -39,6 +40,7 @@ function getNotificationIcon(
.with('invite_to_team', () => UserPlusIcon)
.with('task_assigned', () => CheckIcon)
.with('ai_response', () => ChatIcon)
+ .with('github_pr_event', () => GithubIcon)
.with('call-started', () => PhoneIcon)
.exhaustive();
}
diff --git a/js/app/packages/entity/src/utils/notification.ts b/js/app/packages/entity/src/utils/notification.ts
index dcaab30c2f..abc6cb1324 100644
--- a/js/app/packages/entity/src/utils/notification.ts
+++ b/js/app/packages/entity/src/utils/notification.ts
@@ -80,6 +80,7 @@ export function getNotificationActionText(n: Notification): string {
.with('invite_to_team', () => 'invited')
.with('task_assigned', () => 'assigned')
.with('ai_response', () => 'responded')
+ .with('github_pr_event', () => 'updated')
.with('call-started', () => 'called')
.exhaustive();
}
@@ -108,6 +109,10 @@ export function extractMessageContent(notification: Notification): string {
.with({ tag: 'new_email' }, (m) => m.content.subject || '')
.with({ tag: 'task_assigned' }, (m) => m.content.taskName ?? '')
.with({ tag: 'ai_response' }, (m) => m.content.summary || '')
+ .with(
+ { tag: 'github_pr_event' },
+ (m) => m.content.title || m.content.displayName || ''
+ )
.with({ tag: 'channel_invite' }, () => '')
.with({ tag: 'invite_to_team' }, () => '')
.with({ tag: 'call-started' }, (m) => m.content.channel_name ?? '')
diff --git a/js/app/packages/entity/tests/notification-description.test.ts b/js/app/packages/entity/tests/notification-description.test.ts
index c4c9cac561..fa4d5dfb17 100644
--- a/js/app/packages/entity/tests/notification-description.test.ts
+++ b/js/app/packages/entity/tests/notification-description.test.ts
@@ -78,7 +78,7 @@ describe('notification-description helpers', () => {
});
it('returns correct verb for document_mention', () => {
- expect(getActionVerb('document_mention')).toBe('mentioned you');
+ expect(getActionVerb('document_mention')).toBe('shared with you');
});
it('returns correct verb for channel_message_reply', () => {
@@ -110,6 +110,10 @@ describe('notification-description helpers', () => {
it('returns correct verb for task_assigned', () => {
expect(getActionVerb('task_assigned')).toBe('assigned you');
});
+
+ it('returns correct verb for github_pr_event', () => {
+ expect(getActionVerb('github_pr_event')).toBe('updated a pull request');
+ });
});
describe('getTypeNoun', () => {
@@ -147,11 +151,11 @@ describe('notification-description helpers', () => {
describe('document_mention', () => {
it('returns singular for count of 1', () => {
- expect(getTypeNoun('document_mention', 1)).toBe('mention');
+ expect(getTypeNoun('document_mention', 1)).toBe('document shared');
});
it('returns plural for count greater than 1', () => {
- expect(getTypeNoun('document_mention', 4)).toBe('mentions');
+ expect(getTypeNoun('document_mention', 4)).toBe('documents shared');
});
});
@@ -207,6 +211,16 @@ describe('notification-description helpers', () => {
});
});
+ describe('github_pr_event', () => {
+ it('returns singular for count of 1', () => {
+ expect(getTypeNoun('github_pr_event', 1)).toBe('pull request');
+ });
+
+ it('returns plural for count greater than 1', () => {
+ expect(getTypeNoun('github_pr_event', 2)).toBe('pull requests');
+ });
+ });
+
describe('edge cases', () => {
it('handles count of 0 as plural', () => {
expect(getTypeNoun('channel_message_send', 0)).toBe('messages');
diff --git a/js/app/packages/entity/tests/notification.test.ts b/js/app/packages/entity/tests/notification.test.ts
index e3b28adb8a..44b1805844 100644
--- a/js/app/packages/entity/tests/notification.test.ts
+++ b/js/app/packages/entity/tests/notification.test.ts
@@ -1,3 +1,4 @@
+import type { GithubPrEvent } from '@service-notification/generated/schemas';
import { describe, expect, it } from 'vitest';
import type { Notification } from '../src/types/notification';
import {
@@ -9,6 +10,42 @@ import {
isNotificationUnread,
} from '../src/utils/notification';
+const GITHUB_PR_FOREIGN_ENTITY_ID = '123e4567-e89b-12d3-a456-426614174000';
+
+type GithubPrNotification = Notification & {
+ notification_metadata: {
+ content: GithubPrEvent;
+ tag: 'github_pr_event';
+ };
+};
+
+function githubPrEvent(overrides: Partial<GithubPrEvent> = {}): GithubPrEvent {
+ return {
+ action: 'opened',
+ displayName: 'macro/macro#42',
+ foreignEntityId: GITHUB_PR_FOREIGN_ENTITY_ID,
+ githubKey: 'macro/macro/pull/42',
+ number: 42,
+ owner: 'macro',
+ repo: 'macro',
+ status: 'open',
+ title: 'Add notification support',
+ url: 'https://github.com/macro/macro/pull/42',
+ ...overrides,
+ };
+}
+
+function githubPrNotification(
+ overrides: Partial<GithubPrEvent> = {}
+): GithubPrNotification {
+ return {
+ notification_metadata: {
+ content: githubPrEvent(overrides),
+ tag: 'github_pr_event',
+ },
+ } as GithubPrNotification;
+}
+
describe('notification utils', () => {
describe('filterValidNotifications', () => {
it('returns empty array for undefined input', () => {
@@ -248,6 +285,10 @@ describe('notification utils', () => {
} as Notification;
expect(getNotificationActionText(notification)).toBe('assigned');
});
+
+ it('returns correct action text for github_pr_event', () => {
+ expect(getNotificationActionText(githubPrNotification())).toBe('updated');
+ });
});
describe('extractMessageContent', () => {
@@ -330,6 +371,23 @@ describe('notification utils', () => {
expect(extractMessageContent(notification)).toBe('Review PR');
});
+ it('extracts GitHub PR title and preserves foreignEntityId', () => {
+ const notification = githubPrNotification();
+
+ expect(extractMessageContent(notification)).toBe(
+ 'Add notification support'
+ );
+ expect(notification.notification_metadata.content.foreignEntityId).toBe(
+ GITHUB_PR_FOREIGN_ENTITY_ID
+ );
+ });
+
+ it('falls back to GitHub PR display name when title is empty', () => {
+ expect(extractMessageContent(githubPrNotification({ title: '' }))).toBe(
+ 'macro/macro#42'
+ );
+ });
+
it('returns empty string for channel_invite', () => {
const notification = {
notification_metadata: {
diff --git a/js/app/packages/notifications/notification-metadata.ts b/js/app/packages/notifications/notification-metadata.ts
index 92281cdd1d..0ad16f5e95 100644
--- a/js/app/packages/notifications/notification-metadata.ts
+++ b/js/app/packages/notifications/notification-metadata.ts
@@ -17,6 +17,7 @@ export function getNotificationAction(n: UnifiedNotification): string {
.with('new_email', () => 'sent a new email')
.with('invite_to_team', () => 'invited you to')
.with('task_assigned', () => 'assigned you a task')
+ .with('github_pr_event', () => 'updated a pull request')
.exhaustive();
}
@@ -38,6 +39,10 @@ export function getNotificationTargetName(
.with({ tag: 'commented_on_document' }, (m) => m.content.documentName)
.with({ tag: 'invite_to_team' }, (m) => m.content.teamName)
.with({ tag: 'task_assigned' }, (m) => m.content.taskName ?? undefined)
+ .with(
+ { tag: 'github_pr_event' },
+ (m) => `${m.content.owner}/${m.content.repo}#${m.content.number}`
+ )
.with({ tag: 'channel_mention' }, () => undefined)
.with({ tag: 'channel_message_send' }, () => undefined)
.with({ tag: 'ai_response' }, () => undefined)
@@ -61,6 +66,10 @@ export function getNotificationContent(
.with({ tag: 'commented_on_document' }, (m) => m.content.text)
.with({ tag: 'new_email' }, (m) => m.content.subject)
.with({ tag: 'task_assigned' }, (m) => m.content.taskName ?? undefined)
+ .with(
+ { tag: 'github_pr_event' },
+ (m) => m.content.title || m.content.displayName
+ )
.with({ tag: 'channel_invite' }, () => undefined)
.with({ tag: 'invite_to_team' }, () => undefined)
.exhaustive();
@@ -84,6 +93,7 @@ export function shouldShowNotificationTarget(n: UnifiedNotification): boolean {
.with({ tag: 'ai_response' }, () => false)
.with({ tag: 'new_email' }, () => false)
.with({ tag: 'task_assigned' }, () => true)
+ .with({ tag: 'github_pr_event' }, () => true)
.with({ tag: 'document_mention' }, () => true)
.with({ tag: 'mentioned_in_document_comment' }, () => true)
.with({ tag: 'replied_to_document_comment_thread' }, () => true)
diff --git a/js/app/packages/notifications/notification-navigation.ts b/js/app/packages/notifications/notification-navigation.ts
index cb7119ff71..cdc2878aa2 100644
--- a/js/app/packages/notifications/notification-navigation.ts
+++ b/js/app/packages/notifications/notification-navigation.ts
@@ -12,6 +12,7 @@ import {
resolveBlockAlias,
} from '@core/constant/allBlocks';
import type { NotificationType } from '@core/types';
+import { openExternalUrl } from '@core/util/url';
import { getNotificationById } from '@queries/notification/user-notifications';
import { errAsync, ResultAsync } from 'neverthrow';
import { match, P } from 'ts-pattern';
@@ -237,6 +238,13 @@ function getSupportedHandler(
openSplitIfNotOpen(lm, 'task', meta.content.taskId, { newSplit });
};
})
+ .with('github_pr_event', () => {
+ const meta = notification.notification_metadata;
+ if (meta.tag !== 'github_pr_event') return null;
+ return async () => {
+ openExternalUrl(meta.content.url);
+ };
+ })
.with('mentioned_in_document_comment', () => {
const meta = notification.notification_metadata;
if (meta.tag !== 'mentioned_in_document_comment') return null;
diff --git a/js/app/packages/notifications/notification-preview.ts b/js/app/packages/notifications/notification-preview.ts
index 4063b298e0..c1a0071602 100644
--- a/js/app/packages/notifications/notification-preview.ts
+++ b/js/app/packages/notifications/notification-preview.ts
@@ -13,5 +13,6 @@ export const NOTIFICATION_LABEL_BY_TYPE: Record<NotificationType, string> = {
invite_to_team: 'INVITE',
task_assigned: 'ASSIGNED',
ai_response: 'AI',
+ github_pr_event: 'GITHUB',
'call-started': 'CALL',
} as const;
diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts
index fc3bca55fb..c90a5aeea9 100644
--- a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts
@@ -617,6 +617,7 @@ export const ListNotifications = z.object({
'chat',
'call',
'task',
+ 'github',
]),
id: z.string(),
})
@@ -636,6 +637,7 @@ export const ListNotifications = z.object({
'chat',
'call',
'task',
+ 'github',
])
),
z.null(),
diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts
index 8350ad8bcb..fedaee0df0 100644
--- a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts
@@ -157,7 +157,8 @@ export type NotificationItemType =
| 'project'
| 'chat'
| 'call'
- | 'task';
+ | 'task'
+ | 'github';
/**
* Direction for reading more messages around a cursor.
*/
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEvent.ts b/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEvent.ts
new file mode 100644
index 0000000000..79e2af0c6d
--- /dev/null
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEvent.ts
@@ -0,0 +1,57 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { GithubPrEventAction } from './githubPrEventAction';
+import type { GithubPrEventBaseBranch } from './githubPrEventBaseBranch';
+import type { GithubPrEventHeadBranch } from './githubPrEventHeadBranch';
+import type { GithubPrEventMergedAt } from './githubPrEventMergedAt';
+import type { GithubPrEventPreviousStatus } from './githubPrEventPreviousStatus';
+import type { GithubPrEventSenderGithubAvatarUrl } from './githubPrEventSenderGithubAvatarUrl';
+import type { GithubPrEventSenderGithubLogin } from './githubPrEventSenderGithubLogin';
+import type { GithubPrEventSenderGithubUserId } from './githubPrEventSenderGithubUserId';
+import type { GithubPrEventStatus } from './githubPrEventStatus';
+
+/**
+ * Metadata for a GitHub pull request lifecycle notification.
+ */
+export interface GithubPrEvent {
+ /** The webhook action that triggered this notification. */
+ action: GithubPrEventAction;
+ /** The pull request base branch, when available. */
+ baseBranch?: GithubPrEventBaseBranch;
+ /** A compact label suitable for display in the UI. */
+ displayName: string;
+ /** The source-specific internal foreign entity row id for this pull request. */
+ foreignEntityId: string;
+ /** The external GitHub key, in `owner/repo/pull/number` format. */
+ githubKey: string;
+ /** The pull request head branch, when available. */
+ headBranch?: GithubPrEventHeadBranch;
+ /** When the pull request was merged, when available. */
+ mergedAt?: GithubPrEventMergedAt;
+ /**
+ * The GitHub pull request number.
+ * @minimum 0
+ */
+ number: number;
+ /** The GitHub repository owner or organization. */
+ owner: string;
+ previousStatus?: GithubPrEventPreviousStatus;
+ /** The GitHub repository name. */
+ repo: string;
+ /** The GitHub avatar URL for the sender, when available. */
+ senderGithubAvatarUrl?: GithubPrEventSenderGithubAvatarUrl;
+ /** The GitHub login for the sender, when available. */
+ senderGithubLogin?: GithubPrEventSenderGithubLogin;
+ /** The stable GitHub numeric user id for the sender, serialized as a string. */
+ senderGithubUserId?: GithubPrEventSenderGithubUserId;
+ /** The current normalized pull request status. */
+ status: GithubPrEventStatus;
+ /** The GitHub pull request title. Falls back to `display_name` when GitHub has no title. */
+ title: string;
+ /** The public GitHub URL for the pull request. */
+ url: string;
+}
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventAction.ts b/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventAction.ts
new file mode 100644
index 0000000000..03537617ee
--- /dev/null
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventAction.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The GitHub pull request webhook action that triggered the notification.
+ */
+export type GithubPrEventAction =
+ (typeof GithubPrEventAction)[keyof typeof GithubPrEventAction];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const GithubPrEventAction = {
+ opened: 'opened',
+ reopened: 'reopened',
+ closed: 'closed',
+} as const;
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventBaseBranch.ts b/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventBaseBranch.ts
new file mode 100644
index 0000000000..4116bacfa5
--- /dev/null
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventBaseBranch.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The pull request base branch, when available.
+ */
+export type GithubPrEventBaseBranch = string | null;
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventHeadBranch.ts b/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventHeadBranch.ts
new file mode 100644
index 0000000000..ac66aa1045
--- /dev/null
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventHeadBranch.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The pull request head branch, when available.
+ */
+export type GithubPrEventHeadBranch = string | null;
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventMergedAt.ts b/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventMergedAt.ts
new file mode 100644
index 0000000000..f548197229
--- /dev/null
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventMergedAt.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * When the pull request was merged, when available.
+ */
+export type GithubPrEventMergedAt = string | null;
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventPreviousStatus.ts b/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventPreviousStatus.ts
new file mode 100644
index 0000000000..99a9df0ce9
--- /dev/null
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventPreviousStatus.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { GithubPrEventStatus } from './githubPrEventStatus';
+
+export type GithubPrEventPreviousStatus = null | GithubPrEventStatus;
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventSenderGithubAvatarUrl.ts b/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventSenderGithubAvatarUrl.ts
new file mode 100644
index 0000000000..766ba1ea25
--- /dev/null
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventSenderGithubAvatarUrl.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The GitHub avatar URL for the sender, when available.
+ */
+export type GithubPrEventSenderGithubAvatarUrl = string | null;
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventSenderGithubLogin.ts b/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventSenderGithubLogin.ts
new file mode 100644
index 0000000000..40821dbfb9
--- /dev/null
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventSenderGithubLogin.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The GitHub login for the sender, when available.
+ */
+export type GithubPrEventSenderGithubLogin = string | null;
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventSenderGithubUserId.ts b/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventSenderGithubUserId.ts
new file mode 100644
index 0000000000..48ad2d9fc3
--- /dev/null
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventSenderGithubUserId.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The stable GitHub numeric user id for the sender, serialized as a string.
+ */
+export type GithubPrEventSenderGithubUserId = string | null;
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventStatus.ts b/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventStatus.ts
new file mode 100644
index 0000000000..b866b4de94
--- /dev/null
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/githubPrEventStatus.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The normalized lifecycle status for a GitHub pull request notification.
+ */
+export type GithubPrEventStatus =
+ (typeof GithubPrEventStatus)[keyof typeof GithubPrEventStatus];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const GithubPrEventStatus = {
+ open: 'open',
+ closed: 'closed',
+ merged: 'merged',
+} as const;
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/index.ts b/js/app/packages/service-clients/service-notification/generated/schemas/index.ts
index caf4f09d4a..c090b471e2 100644
--- a/js/app/packages/service-clients/service-notification/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/index.ts
@@ -55,6 +55,16 @@ export * from './getAllUserNotificationsResponse';
export * from './getAllUserNotificationsResponseNextCursor';
export * from './getNotificationTypePreferencesResponse';
export * from './getTypedNotificationsByEventItemIdParams';
+export * from './githubPrEvent';
+export * from './githubPrEventAction';
+export * from './githubPrEventBaseBranch';
+export * from './githubPrEventHeadBranch';
+export * from './githubPrEventMergedAt';
+export * from './githubPrEventPreviousStatus';
+export * from './githubPrEventSenderGithubAvatarUrl';
+export * from './githubPrEventSenderGithubLogin';
+export * from './githubPrEventSenderGithubUserId';
+export * from './githubPrEventStatus';
export * from './inviteToTeamMetadata';
export * from './inviteToTeamMetadataRole';
export * from './inviteToTeamMetadataSenderProfilePictureUrl';
@@ -90,6 +100,8 @@ export * from './notifEventOneOfSevenTag';
export * from './notifEventOneOfTag';
export * from './notifEventOneOfThree';
export * from './notifEventOneOfThreeTag';
+export * from './notifEventOneOfTwofive';
+export * from './notifEventOneOfTwofiveTag';
export * from './notifEventOneOfTwoone';
export * from './notifEventOneOfTwooneTag';
export * from './notifEventOneOfTwothree';
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEvent.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEvent.ts
index b912e7db25..89682d89a2 100644
--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEvent.ts
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEvent.ts
@@ -14,6 +14,7 @@ import type { NotifEventOneOfOneseven } from './notifEventOneOfOneseven';
import type { NotifEventOneOfOnethree } from './notifEventOneOfOnethree';
import type { NotifEventOneOfSeven } from './notifEventOneOfSeven';
import type { NotifEventOneOfThree } from './notifEventOneOfThree';
+import type { NotifEventOneOfTwofive } from './notifEventOneOfTwofive';
import type { NotifEventOneOfTwoone } from './notifEventOneOfTwoone';
import type { NotifEventOneOfTwothree } from './notifEventOneOfTwothree';
@@ -37,4 +38,5 @@ export type NotifEvent =
| NotifEventOneOfOneseven
| NotifEventOneOfOnenine
| NotifEventOneOfTwoone
- | NotifEventOneOfTwothree;
+ | NotifEventOneOfTwothree
+ | NotifEventOneOfTwofive;
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwofive.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwofive.ts
new file mode 100644
index 0000000000..524d3c5bb0
--- /dev/null
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwofive.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { GithubPrEvent } from './githubPrEvent';
+import type { NotifEventOneOfTwofiveTag } from './notifEventOneOfTwofiveTag';
+
+/**
+ * A GitHub pull request changed lifecycle state.
+ */
+export type NotifEventOneOfTwofive = {
+ /** A GitHub pull request changed lifecycle state. */
+ content: GithubPrEvent;
+ tag: NotifEventOneOfTwofiveTag;
+};
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwofiveTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwofiveTag.ts
new file mode 100644
index 0000000000..e5d09b173d
--- /dev/null
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfTwofiveTag.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type NotifEventOneOfTwofiveTag =
+ (typeof NotifEventOneOfTwofiveTag)[keyof typeof NotifEventOneOfTwofiveTag];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const NotifEventOneOfTwofiveTag = {
+ github_pr_event: 'github_pr_event',
+} as const;
diff --git a/js/app/packages/service-clients/service-notification/generated/zod.ts b/js/app/packages/service-clients/service-notification/generated/zod.ts
index 368a86a7f8..d0bb45c1fd 100644
--- a/js/app/packages/service-clients/service-notification/generated/zod.ts
+++ b/js/app/packages/service-clients/service-notification/generated/zod.ts
@@ -99,6 +99,8 @@ export const listTypedNotificationsQueryParams = zod.object({
.describe('Cursor value. Base64 encoded timestamp and item id.'),
});
+export const listTypedNotificationsResponseItemsItemNotificationMetadataContentNumberMin = 0;
+
export const listTypedNotificationsResponse = zod
.object({
items: zod
@@ -554,6 +556,112 @@ export const listTypedNotificationsResponse = zod
tag: zod.enum(['ai_response']),
})
.describe('An AI assistant responded to a chat.'),
+ zod
+ .object({
+ content: zod
+ .object({
+ action: zod
+ .enum(['opened', 'reopened', 'closed'])
+ .describe(
+ 'The GitHub pull request webhook action that triggered the notification.'
+ ),
+ baseBranch: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The pull request base branch, when available.'
+ ),
+ displayName: zod
+ .string()
+ .describe(
+ 'A compact label suitable for display in the UI.'
+ ),
+ foreignEntityId: zod
+ .uuid()
+ .describe(
+ 'The source-specific internal foreign entity row id for this pull request.'
+ ),
+ githubKey: zod
+ .string()
+ .describe(
+ 'The external GitHub key, in `owner\/repo\/pull\/number` format.'
+ ),
+ headBranch: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The pull request head branch, when available.'
+ ),
+ mergedAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe(
+ 'When the pull request was merged, when available.'
+ ),
+ number: zod
+ .number()
+ .min(
+ listTypedNotificationsResponseItemsItemNotificationMetadataContentNumberMin
+ )
+ .describe('The GitHub pull request number.'),
+ owner: zod
+ .string()
+ .describe(
+ 'The GitHub repository owner or organization.'
+ ),
+ previousStatus: zod
+ .union([
+ zod.null(),
+ zod
+ .enum(['open', 'closed', 'merged'])
+ .describe(
+ 'The normalized lifecycle status for a GitHub pull request notification.'
+ ),
+ ])
+ .optional(),
+ repo: zod
+ .string()
+ .describe('The GitHub repository name.'),
+ senderGithubAvatarUrl: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The GitHub avatar URL for the sender, when available.'
+ ),
+ senderGithubLogin: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The GitHub login for the sender, when available.'
+ ),
+ senderGithubUserId: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The stable GitHub numeric user id for the sender, serialized as a string.'
+ ),
+ status: zod
+ .enum(['open', 'closed', 'merged'])
+ .describe(
+ 'The normalized lifecycle status for a GitHub pull request notification.'
+ ),
+ title: zod
+ .string()
+ .describe(
+ 'The GitHub pull request title. Falls back to `display_name` when GitHub has no title.'
+ ),
+ url: zod
+ .string()
+ .describe(
+ 'The public GitHub URL for the pull request.'
+ ),
+ })
+ .describe(
+ 'Metadata for a GitHub pull request lifecycle notification.'
+ ),
+ tag: zod.enum(['github_pr_event']),
+ })
+ .describe('A GitHub pull request changed lifecycle state.'),
])
.describe(
'Mirrors [`model_notifications::NotificationEvent`] but uses `tag` \/ `content`\nas the serde adjacently-tagged field names so it can be deserialized from the\nshape produced by [`UserNotificationRow::into_tagged`] +\n[`UserNotificationRow::into_json`].\n\nOnly includes variants whose metadata types implement the `Notification` trait.'
@@ -613,6 +721,8 @@ export const bulkGetTypedNotificationsByEventItemIdsBody = zod
})
.describe('Request body for bulk-fetching notifications by event item IDs.');
+export const bulkGetTypedNotificationsByEventItemIdsResponseItemsItemNotificationMetadataContentNumberMin = 0;
+
export const bulkGetTypedNotificationsByEventItemIdsResponse = zod
.object({
items: zod
@@ -1068,6 +1178,112 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zod
tag: zod.enum(['ai_response']),
})
.describe('An AI assistant responded to a chat.'),
+ zod
+ .object({
+ content: zod
+ .object({
+ action: zod
+ .enum(['opened', 'reopened', 'closed'])
+ .describe(
+ 'The GitHub pull request webhook action that triggered the notification.'
+ ),
+ baseBranch: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The pull request base branch, when available.'
+ ),
+ displayName: zod
+ .string()
+ .describe(
+ 'A compact label suitable for display in the UI.'
+ ),
+ foreignEntityId: zod
+ .uuid()
+ .describe(
+ 'The source-specific internal foreign entity row id for this pull request.'
+ ),
+ githubKey: zod
+ .string()
+ .describe(
+ 'The external GitHub key, in `owner\/repo\/pull\/number` format.'
+ ),
+ headBranch: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The pull request head branch, when available.'
+ ),
+ mergedAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe(
+ 'When the pull request was merged, when available.'
+ ),
+ number: zod
+ .number()
+ .min(
+ bulkGetTypedNotificationsByEventItemIdsResponseItemsItemNotificationMetadataContentNumberMin
+ )
+ .describe('The GitHub pull request number.'),
+ owner: zod
+ .string()
+ .describe(
+ 'The GitHub repository owner or organization.'
+ ),
+ previousStatus: zod
+ .union([
+ zod.null(),
+ zod
+ .enum(['open', 'closed', 'merged'])
+ .describe(
+ 'The normalized lifecycle status for a GitHub pull request notification.'
+ ),
+ ])
+ .optional(),
+ repo: zod
+ .string()
+ .describe('The GitHub repository name.'),
+ senderGithubAvatarUrl: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The GitHub avatar URL for the sender, when available.'
+ ),
+ senderGithubLogin: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The GitHub login for the sender, when available.'
+ ),
+ senderGithubUserId: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The stable GitHub numeric user id for the sender, serialized as a string.'
+ ),
+ status: zod
+ .enum(['open', 'closed', 'merged'])
+ .describe(
+ 'The normalized lifecycle status for a GitHub pull request notification.'
+ ),
+ title: zod
+ .string()
+ .describe(
+ 'The GitHub pull request title. Falls back to `display_name` when GitHub has no title.'
+ ),
+ url: zod
+ .string()
+ .describe(
+ 'The public GitHub URL for the pull request.'
+ ),
+ })
+ .describe(
+ 'Metadata for a GitHub pull request lifecycle notification.'
+ ),
+ tag: zod.enum(['github_pr_event']),
+ })
+ .describe('A GitHub pull request changed lifecycle state.'),
])
.describe(
'Mirrors [`model_notifications::NotificationEvent`] but uses `tag` \/ `content`\nas the serde adjacently-tagged field names so it can be deserialized from the\nshape produced by [`UserNotificationRow::into_tagged`] +\n[`UserNotificationRow::into_json`].\n\nOnly includes variants whose metadata types implement the `Notification` trait.'
@@ -1121,6 +1337,8 @@ export const getTypedNotificationsByEventItemIdQueryParams = zod.object({
.describe('Cursor value. Base64 encoded timestamp and item id.'),
});
+export const getTypedNotificationsByEventItemIdResponseItemsItemNotificationMetadataContentNumberMin = 0;
+
export const getTypedNotificationsByEventItemIdResponse = zod
.object({
items: zod
@@ -1576,6 +1794,112 @@ export const getTypedNotificationsByEventItemIdResponse = zod
tag: zod.enum(['ai_response']),
})
.describe('An AI assistant responded to a chat.'),
+ zod
+ .object({
+ content: zod
+ .object({
+ action: zod
+ .enum(['opened', 'reopened', 'closed'])
+ .describe(
+ 'The GitHub pull request webhook action that triggered the notification.'
+ ),
+ baseBranch: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The pull request base branch, when available.'
+ ),
+ displayName: zod
+ .string()
+ .describe(
+ 'A compact label suitable for display in the UI.'
+ ),
+ foreignEntityId: zod
+ .uuid()
+ .describe(
+ 'The source-specific internal foreign entity row id for this pull request.'
+ ),
+ githubKey: zod
+ .string()
+ .describe(
+ 'The external GitHub key, in `owner\/repo\/pull\/number` format.'
+ ),
+ headBranch: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The pull request head branch, when available.'
+ ),
+ mergedAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe(
+ 'When the pull request was merged, when available.'
+ ),
+ number: zod
+ .number()
+ .min(
+ getTypedNotificationsByEventItemIdResponseItemsItemNotificationMetadataContentNumberMin
+ )
+ .describe('The GitHub pull request number.'),
+ owner: zod
+ .string()
+ .describe(
+ 'The GitHub repository owner or organization.'
+ ),
+ previousStatus: zod
+ .union([
+ zod.null(),
+ zod
+ .enum(['open', 'closed', 'merged'])
+ .describe(
+ 'The normalized lifecycle status for a GitHub pull request notification.'
+ ),
+ ])
+ .optional(),
+ repo: zod
+ .string()
+ .describe('The GitHub repository name.'),
+ senderGithubAvatarUrl: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The GitHub avatar URL for the sender, when available.'
+ ),
+ senderGithubLogin: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The GitHub login for the sender, when available.'
+ ),
+ senderGithubUserId: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The stable GitHub numeric user id for the sender, serialized as a string.'
+ ),
+ status: zod
+ .enum(['open', 'closed', 'merged'])
+ .describe(
+ 'The normalized lifecycle status for a GitHub pull request notification.'
+ ),
+ title: zod
+ .string()
+ .describe(
+ 'The GitHub pull request title. Falls back to `display_name` when GitHub has no title.'
+ ),
+ url: zod
+ .string()
+ .describe(
+ 'The public GitHub URL for the pull request.'
+ ),
+ })
+ .describe(
+ 'Metadata for a GitHub pull request lifecycle notification.'
+ ),
+ tag: zod.enum(['github_pr_event']),
+ })
+ .describe('A GitHub pull request changed lifecycle state.'),
])
.describe(
'Mirrors [`model_notifications::NotificationEvent`] but uses `tag` \/ `content`\nas the serde adjacently-tagged field names so it can be deserialized from the\nshape produced by [`UserNotificationRow::into_tagged`] +\n[`UserNotificationRow::into_json`].\n\nOnly includes variants whose metadata types implement the `Notification` trait.'
@@ -1644,6 +1968,8 @@ export const getTypedNotificationByIdParams = zod.object({
notification_id: zod.uuid().describe('ID of the notification'),
});
+export const getTypedNotificationByIdResponseNotificationMetadataContentNumberMin = 0;
+
export const getTypedNotificationByIdResponse = zod
.object({
entity_id: zod.string().describe('The id of that entity'),
@@ -2061,6 +2387,102 @@ export const getTypedNotificationByIdResponse = zod
tag: zod.enum(['ai_response']),
})
.describe('An AI assistant responded to a chat.'),
+ zod
+ .object({
+ content: zod
+ .object({
+ action: zod
+ .enum(['opened', 'reopened', 'closed'])
+ .describe(
+ 'The GitHub pull request webhook action that triggered the notification.'
+ ),
+ baseBranch: zod
+ .string()
+ .nullish()
+ .describe('The pull request base branch, when available.'),
+ displayName: zod
+ .string()
+ .describe(
+ 'A compact label suitable for display in the UI.'
+ ),
+ foreignEntityId: zod
+ .uuid()
+ .describe(
+ 'The source-specific internal foreign entity row id for this pull request.'
+ ),
+ githubKey: zod
+ .string()
+ .describe(
+ 'The external GitHub key, in `owner\/repo\/pull\/number` format.'
+ ),
+ headBranch: zod
+ .string()
+ .nullish()
+ .describe('The pull request head branch, when available.'),
+ mergedAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe(
+ 'When the pull request was merged, when available.'
+ ),
+ number: zod
+ .number()
+ .min(
+ getTypedNotificationByIdResponseNotificationMetadataContentNumberMin
+ )
+ .describe('The GitHub pull request number.'),
+ owner: zod
+ .string()
+ .describe('The GitHub repository owner or organization.'),
+ previousStatus: zod
+ .union([
+ zod.null(),
+ zod
+ .enum(['open', 'closed', 'merged'])
+ .describe(
+ 'The normalized lifecycle status for a GitHub pull request notification.'
+ ),
+ ])
+ .optional(),
+ repo: zod.string().describe('The GitHub repository name.'),
+ senderGithubAvatarUrl: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The GitHub avatar URL for the sender, when available.'
+ ),
+ senderGithubLogin: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The GitHub login for the sender, when available.'
+ ),
+ senderGithubUserId: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The stable GitHub numeric user id for the sender, serialized as a string.'
+ ),
+ status: zod
+ .enum(['open', 'closed', 'merged'])
+ .describe(
+ 'The normalized lifecycle status for a GitHub pull request notification.'
+ ),
+ title: zod
+ .string()
+ .describe(
+ 'The GitHub pull request title. Falls back to `display_name` when GitHub has no title.'
+ ),
+ url: zod
+ .string()
+ .describe('The public GitHub URL for the pull request.'),
+ })
+ .describe(
+ 'Metadata for a GitHub pull request lifecycle notification.'
+ ),
+ tag: zod.enum(['github_pr_event']),
+ })
+ .describe('A GitHub pull request changed lifecycle state.'),
])
.describe(
'Mirrors [`model_notifications::NotificationEvent`] but uses `tag` \/ `content`\nas the serde adjacently-tagged field names so it can be deserialized from the\nshape produced by [`UserNotificationRow::into_tagged`] +\n[`UserNotificationRow::into_json`].\n\nOnly includes variants whose metadata types implement the `Notification` trait.'
diff --git a/js/app/packages/service-clients/service-notification/openapi.json b/js/app/packages/service-clients/service-notification/openapi.json
index d2bbeae9fe..d427237d2c 100644
--- a/js/app/packages/service-clients/service-notification/openapi.json
+++ b/js/app/packages/service-clients/service-notification/openapi.json
@@ -1521,6 +1521,113 @@
}
}
},
+ "GithubPrEvent": {
+ "type": "object",
+ "description": "Metadata for a GitHub pull request lifecycle notification.",
+ "required": [
+ "foreignEntityId",
+ "githubKey",
+ "owner",
+ "repo",
+ "number",
+ "url",
+ "displayName",
+ "title",
+ "status",
+ "action"
+ ],
+ "properties": {
+ "action": {
+ "$ref": "#/components/schemas/GithubPrEventAction",
+ "description": "The webhook action that triggered this notification."
+ },
+ "baseBranch": {
+ "type": ["string", "null"],
+ "description": "The pull request base branch, when available."
+ },
+ "displayName": {
+ "type": "string",
+ "description": "A compact label suitable for display in the UI."
+ },
+ "foreignEntityId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The source-specific internal foreign entity row id for this pull request."
+ },
+ "githubKey": {
+ "type": "string",
+ "description": "The external GitHub key, in `owner/repo/pull/number` format."
+ },
+ "headBranch": {
+ "type": ["string", "null"],
+ "description": "The pull request head branch, when available."
+ },
+ "mergedAt": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When the pull request was merged, when available."
+ },
+ "number": {
+ "type": "integer",
+ "format": "int64",
+ "description": "The GitHub pull request number.",
+ "minimum": 0
+ },
+ "owner": {
+ "type": "string",
+ "description": "The GitHub repository owner or organization."
+ },
+ "previousStatus": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/GithubPrEventStatus",
+ "description": "The prior normalized pull request status, when known."
+ }
+ ]
+ },
+ "repo": {
+ "type": "string",
+ "description": "The GitHub repository name."
+ },
+ "senderGithubAvatarUrl": {
+ "type": ["string", "null"],
+ "description": "The GitHub avatar URL for the sender, when available."
+ },
+ "senderGithubLogin": {
+ "type": ["string", "null"],
+ "description": "The GitHub login for the sender, when available."
+ },
+ "senderGithubUserId": {
+ "type": ["string", "null"],
+ "description": "The stable GitHub numeric user id for the sender, serialized as a string."
+ },
+ "status": {
+ "$ref": "#/components/schemas/GithubPrEventStatus",
+ "description": "The current normalized pull request status."
+ },
+ "title": {
+ "type": "string",
+ "description": "The GitHub pull request title. Falls back to `display_name` when GitHub has no title."
+ },
+ "url": {
+ "type": "string",
+ "description": "The public GitHub URL for the pull request."
+ }
+ }
+ },
+ "GithubPrEventAction": {
+ "type": "string",
+ "description": "The GitHub pull request webhook action that triggered the notification.",
+ "enum": ["opened", "reopened", "closed"]
+ },
+ "GithubPrEventStatus": {
+ "type": "string",
+ "description": "The normalized lifecycle status for a GitHub pull request notification.",
+ "enum": ["open", "closed", "merged"]
+ },
"InviteToTeamMetadata": {
"type": "object",
"description": "Metadata for when a user is invited to a team.",
@@ -1850,6 +1957,21 @@
"enum": ["ai_response"]
}
}
+ },
+ {
+ "type": "object",
+ "description": "A GitHub pull request changed lifecycle state.",
+ "required": ["content", "tag"],
+ "properties": {
+ "content": {
+ "$ref": "#/components/schemas/GithubPrEvent",
+ "description": "A GitHub pull request changed lifecycle state."
+ },
+ "tag": {
+ "type": "string",
+ "enum": ["github_pr_event"]
+ }
+ }
}
],
"description": "Mirrors [`model_notifications::NotificationEvent`] but uses `tag` / `content`\nas the serde adjacently-tagged field names so it can be deserialized from the\nshape produced by [`UserNotificationRow::into_tagged`] +\n[`UserNotificationRow::into_json`].\n\nOnly includes variants whose metadata types implement the `Notification` trait."
diff --git a/rust/cloud-storage/.sqlx/query-aa7c645fdd129abe705595f4b8c06bb48c977202f069d12143bece9f24bdb6ab.json b/rust/cloud-storage/.sqlx/query-aa7c645fdd129abe705595f4b8c06bb48c977202f069d12143bece9f24bdb6ab.json
new file mode 100644
index 0000000000..74b8c61e48
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-aa7c645fdd129abe705595f4b8c06bb48c977202f069d12143bece9f24bdb6ab.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT user_id\n FROM team_user\n WHERE team_id = $1\n ORDER BY user_id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "aa7c645fdd129abe705595f4b8c06bb48c977202f069d12143bece9f24bdb6ab"
+}
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index e501d3590d..9ce138fa9b 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -4798,10 +4798,13 @@ dependencies = [
"model",
"model-entity",
"model-error-response",
+ "model_notifications",
"models_permissions",
+ "notification",
"redis",
"regex",
"reqwest 0.13.3",
+ "rootcause",
"serde",
"serde_json",
"sha2 0.10.9",
diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rs
index 8430ce8d44..a1707b2eb3 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -285,6 +285,7 @@ pub(crate) type GithubSyncServiceType = GithubSyncServiceImpl<
PgGithubSyncRepo,
GithubSyncClientImpl,
ForeignEntityServiceType,
+ NotificationIngressType,
>;
/// Type alias for the cal.com webhook service.
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index 77197d1972..e2e271a856 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -409,6 +409,7 @@ async fn main() -> anyhow::Result<()> {
},
document_service.clone(),
foreign_entity_service.clone(),
+ (*notification_ingress_service).clone(),
PgGithubSyncRepo::new(db.clone()),
GithubSyncClientImpl::default(),
);
diff --git a/rust/cloud-storage/github/Cargo.toml b/rust/cloud-storage/github/Cargo.toml
index c70276bbcc..a82e1f3ae0 100644
--- a/rust/cloud-storage/github/Cargo.toml
+++ b/rust/cloud-storage/github/Cargo.toml
@@ -23,6 +23,9 @@ sync = [
"dep:documents",
"dep:entity_access",
"dep:foreign_entity",
+ "dep:model-entity",
+ "dep:model_notifications",
+ "dep:notification",
"dep:reqwest",
"ports",
]
@@ -44,6 +47,9 @@ hmac = { workspace = true }
jsonwebtoken = { workspace = true }
macro_env = { path = "../macro_env" }
macro_service_urls = { path = "../macro_service_urls" }
+model-entity = { path = "../model-entity", optional = true }
+model_notifications = { path = "../model_notifications", optional = true }
+notification = { path = "../notification", optional = true }
regex = { workspace = true }
reqwest = { workspace = true, optional = true }
serde = { workspace = true }
@@ -68,12 +74,12 @@ model-error-response = { path = "../model-error-response", optional = true }
utoipa = { workspace = true, optional = true }
[dev-dependencies]
-model-entity = { path = "../model-entity"}
document_sub_type = { path = "../document_sub_type" }
http-body-util = { workspace = true }
macro_db_migrator = { path = "../macro_db_migrator" }
mockall = { workspace = true }
model = { path = "../model" }
models_permissions = { path = "../models_permissions" }
+rootcause = { workspace = true }
tokio = { workspace = true }
tower = { workspace = true }
diff --git a/rust/cloud-storage/github/src/domain/ports/sync.rs b/rust/cloud-storage/github/src/domain/ports/sync.rs
index 911be73c88..72be8b3ced 100644
--- a/rust/cloud-storage/github/src/domain/ports/sync.rs
+++ b/rust/cloud-storage/github/src/domain/ports/sync.rs
@@ -2,6 +2,8 @@
use std::future::Future;
+use macro_user_id::user_id::MacroUserIdStr;
+
use crate::domain::models::{
EnrichedGithubPullRequest, GithubAppInstallationSource, GithubError,
GithubInstallationAccessToken, GithubKey, GithubPullRequestDetails, MacroTaskId,
@@ -68,6 +70,12 @@ pub trait GithubSyncRepo: Send + Sync + 'static {
installation_id: &str,
) -> impl Future<Output = Result<Vec<GithubAppInstallationSource>, Self::Err>> + Send;
+ /// Returns all Macro user IDs that belong to the given team.
+ fn get_team_member_ids(
+ &self,
+ team_id: uuid::Uuid,
+ ) -> impl Future<Output = Result<Vec<MacroUserIdStr<'static>>, Self::Err>> + Send;
+
/// Upserts associations between a GitHub App installation and its sources.
/// Ignores conflicts (idempotent).
fn upsert_installation_sources(
diff --git a/rust/cloud-storage/github/src/domain/service/sync/handle_comment.rs b/rust/cloud-storage/github/src/domain/service/sync/handle_comment.rs
index ca06c0d425..beaa8f48e3 100644
--- a/rust/cloud-storage/github/src/domain/service/sync/handle_comment.rs
+++ b/rust/cloud-storage/github/src/domain/service/sync/handle_comment.rs
@@ -6,11 +6,17 @@ use crate::domain::{
};
use documents::domain::ports::DocumentService;
use foreign_entity::domain::ports::ForeignEntityService;
+use notification::domain::service::NotificationIngress;
use super::GithubSyncServiceImpl;
-impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntityService>
- GithubSyncServiceImpl<D, R, C, F>
+impl<
+ D: DocumentService,
+ R: GithubSyncRepo,
+ C: GithubSyncClient,
+ F: ForeignEntityService,
+ N: NotificationIngress,
+> GithubSyncServiceImpl<D, R, C, F, N>
{
/// Handle `issue_comment`, `pull_request_review`, and
/// `pull_request_review_comment` events.
diff --git a/rust/cloud-storage/github/src/domain/service/sync/handle_installation.rs b/rust/cloud-storage/github/src/domain/service/sync/handle_installation.rs
index abf41d1893..7368f52736 100644
--- a/rust/cloud-storage/github/src/domain/service/sync/handle_installation.rs
+++ b/rust/cloud-storage/github/src/domain/service/sync/handle_installation.rs
@@ -6,11 +6,17 @@ use crate::domain::{
};
use documents::domain::ports::DocumentService;
use foreign_entity::domain::ports::ForeignEntityService;
+use notification::domain::service::NotificationIngress;
use super::GithubSyncServiceImpl;
-impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntityService>
- GithubSyncServiceImpl<D, R, C, F>
+impl<
+ D: DocumentService,
+ R: GithubSyncRepo,
+ C: GithubSyncClient,
+ F: ForeignEntityService,
+ N: NotificationIngress,
+> GithubSyncServiceImpl<D, R, C, F, N>
{
/// Handle `installation` events with action `created`.
///
diff --git a/rust/cloud-storage/github/src/domain/service/sync/handle_pr.rs b/rust/cloud-storage/github/src/domain/service/sync/handle_pr.rs
index e45542e0dc..bd778f2233 100644
--- a/rust/cloud-storage/github/src/domain/service/sync/handle_pr.rs
+++ b/rust/cloud-storage/github/src/domain/service/sync/handle_pr.rs
@@ -6,12 +6,18 @@ use crate::domain::{
};
use documents::domain::ports::DocumentService;
use foreign_entity::domain::ports::ForeignEntityService;
+use notification::domain::service::NotificationIngress;
use std::collections::HashSet;
use super::GithubSyncServiceImpl;
-impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntityService>
- GithubSyncServiceImpl<D, R, C, F>
+impl<
+ D: DocumentService,
+ R: GithubSyncRepo,
+ C: GithubSyncClient,
+ F: ForeignEntityService,
+ N: NotificationIngress,
+> GithubSyncServiceImpl<D, R, C, F, N>
{
/// Handle `pull_request` events with action `opened` or `reopened`.
#[tracing::instrument(skip(self, event), err)]
diff --git a/rust/cloud-storage/github/src/domain/service/sync/mod.rs b/rust/cloud-storage/github/src/domain/service/sync/mod.rs
index d4b4b1d269..b6f17920e5 100644
--- a/rust/cloud-storage/github/src/domain/service/sync/mod.rs
+++ b/rust/cloud-storage/github/src/domain/service/sync/mod.rs
@@ -6,6 +6,7 @@ mod test;
mod handle_comment;
mod handle_installation;
mod handle_pr;
+mod notify_pr;
use crate::domain::{
models::{
@@ -19,10 +20,11 @@ use crate::domain::{
use documents::domain::{models::DocumentError, ports::DocumentService};
use entity_access::domain::models::{EditAccessLevel, ViewAccessLevel};
use foreign_entity::domain::{
- models::{CreateForeignEntity, PatchForeignEntity},
+ models::{CreateForeignEntity, ForeignEntity, PatchForeignEntity},
ports::ForeignEntityService,
};
use hmac::{Hmac, Mac};
+use notification::domain::service::NotificationIngress;
use sha2::Sha256;
use std::{collections::HashSet, sync::Arc};
use subtle::ConstantTimeEq;
@@ -50,22 +52,30 @@ pub struct GithubSyncServiceImpl<
R: GithubSyncRepo,
C: GithubSyncClient,
F: ForeignEntityService,
+ N: NotificationIngress,
> {
config: GithubSyncConfig,
document_service: Arc<D>,
foreign_entity_service: Arc<F>,
+ notification_ingress: N,
repo: R,
pub(crate) client: C,
}
-impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntityService>
- GithubSyncServiceImpl<D, R, C, F>
+impl<
+ D: DocumentService,
+ R: GithubSyncRepo,
+ C: GithubSyncClient,
+ F: ForeignEntityService,
+ N: NotificationIngress,
+> GithubSyncServiceImpl<D, R, C, F, N>
{
/// Create a new github sync service.
pub fn new(
config: GithubSyncConfig,
document_service: Arc<D>,
foreign_entity_service: Arc<F>,
+ notification_ingress: N,
repo: R,
client: C,
) -> Self {
@@ -73,6 +83,7 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntit
config,
document_service,
foreign_entity_service,
+ notification_ingress,
repo,
client,
}
@@ -97,8 +108,26 @@ struct ResolvedTasks {
validated_task_ids: Vec<MacroTaskId>,
}
-impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntityService>
- GithubSyncServiceImpl<D, R, C, F>
+/// Result of creating or refreshing one source-scoped PR foreign entity row.
+#[derive(Debug, Clone)]
+struct PullRequestForeignEntityUpsert {
+ /// The installation source this foreign entity is scoped to.
+ source: GithubAppInstallationSource,
+ /// The internal source-specific foreign entity row ID.
+ foreign_entity_id: uuid::Uuid,
+ /// The previously persisted normalized PR status for this source, when known.
+ previous_status: Option<GithubPullRequestStatus>,
+ /// The newly persisted normalized PR status for this source, when known.
+ status: Option<GithubPullRequestStatus>,
+}
+
+impl<
+ D: DocumentService,
+ R: GithubSyncRepo,
+ C: GithubSyncClient,
+ F: ForeignEntityService,
+ N: NotificationIngress,
+> GithubSyncServiceImpl<D, R, C, F, N>
{
/// Extract PR metadata and generate an installation access token.
/// Returns `None` if any required field is missing or token generation fails.
@@ -357,10 +386,16 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntit
/// Create or refresh foreign entity rows for a pull request, scoped to the
/// Macro source (team or user) associated with the GitHub App installation.
#[tracing::instrument(skip(self, event))]
- async fn upsert_pull_request_foreign_entities(&self, event: &ValidatedGithubWebhookEvent) {
+ async fn upsert_pull_request_foreign_entities(
+ &self,
+ event: &ValidatedGithubWebhookEvent,
+ ) -> Option<(
+ EnrichedGithubPullRequest,
+ Vec<PullRequestForeignEntityUpsert>,
+ )> {
let Some(installation_id) = event.installation_id() else {
tracing::warn!("missing installation id, cannot upsert PR foreign entity");
- return;
+ return None;
};
let installation_id = installation_id.to_string();
@@ -372,7 +407,7 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntit
installation_id,
"failed to fetch GitHub App installation sources for PR foreign entity"
);
- return;
+ return None;
}
};
@@ -381,16 +416,22 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntit
installation_id,
"no GitHub App installation sources found for PR foreign entity upsert"
);
- return;
+ return None;
}
let Some(pull_request) = self.enriched_pull_request_metadata(event).await else {
tracing::warn!("missing PR metadata, cannot upsert foreign entity");
- return;
+ return None;
};
- self.upsert_enriched_pull_request_foreign_entities(pull_request, &stored_for_sources)
+ let upserts = self
+ .upsert_enriched_pull_request_foreign_entities(
+ pull_request.clone(),
+ &stored_for_sources,
+ )
.await;
+
+ Some((pull_request, upserts))
}
/// Create or refresh foreign entity rows from already-enriched pull request metadata.
@@ -399,12 +440,12 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntit
&self,
pull_request: EnrichedGithubPullRequest,
stored_for_sources: &[GithubAppInstallationSource],
- ) {
+ ) -> Vec<PullRequestForeignEntityUpsert> {
let base_metadata = match serde_json::to_value(&pull_request) {
Ok(metadata) => metadata,
Err(error) => {
tracing::error!(error=?error, "failed to serialize PR foreign entity metadata");
- return;
+ return Vec::new();
}
};
@@ -419,10 +460,11 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntit
Ok(existing) => existing,
Err(error) => {
tracing::error!(error=?error, "failed to fetch existing PR foreign entities");
- return;
+ return Vec::new();
}
};
+ let mut upserts = Vec::new();
let mut seen_sources = HashSet::new();
for source in stored_for_sources {
let stored_for_id = source.source_id();
@@ -435,6 +477,8 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntit
entity.stored_for_id.as_str() == stored_for_id.as_str()
&& entity.stored_for_auth_entity.as_str() == stored_for_auth_entity.as_str()
});
+ let previous_status = existing_entity
+ .and_then(|entity| Self::pull_request_status_from_metadata(&entity.metadata));
let existing_metadata = existing_entity
.map(|entity| &entity.metadata)
.or_else(|| existing.first().map(|entity| &entity.metadata));
@@ -443,49 +487,103 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntit
existing_metadata,
);
- if let Some(entity) = existing_entity {
- self.foreign_entity_service
- .patch_foreign_entity(
- entity.id,
- PatchForeignEntity {
- metadata: Some(metadata),
- ..PatchForeignEntity::default()
- },
- )
- .await
- .inspect_err(|error| {
- tracing::error!(
- error=?error,
- foreign_entity_id=%pull_request.github_key,
- stored_for_id=%stored_for_id,
- stored_for_auth_entity=%stored_for_auth_entity,
- "failed to patch PR foreign entity"
- );
- })
- .ok();
- continue;
- }
-
- self.foreign_entity_service
- .create_foreign_entity(CreateForeignEntity {
- foreign_entity_id: pull_request.github_key.clone(),
- foreign_entity_source: GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE.to_string(),
+ let foreign_entity = if let Some(entity) = existing_entity {
+ self.patch_pull_request_foreign_entity(
+ entity,
metadata,
- stored_for_id: stored_for_id.clone(),
- stored_for_auth_entity: stored_for_auth_entity.clone(),
- })
+ &pull_request.github_key,
+ &stored_for_id,
+ &stored_for_auth_entity,
+ )
.await
- .inspect_err(|error| {
- tracing::error!(
- error=?error,
- foreign_entity_id=%pull_request.github_key,
- stored_for_id=%stored_for_id,
- stored_for_auth_entity=%stored_for_auth_entity,
- "failed to create PR foreign entity"
- );
- })
- .ok();
+ } else {
+ self.create_pull_request_foreign_entity(
+ &pull_request.github_key,
+ metadata,
+ &stored_for_id,
+ &stored_for_auth_entity,
+ )
+ .await
+ };
+
+ let Some(foreign_entity) = foreign_entity else {
+ continue;
+ };
+
+ upserts.push(PullRequestForeignEntityUpsert {
+ source: source.clone(),
+ foreign_entity_id: foreign_entity.id,
+ previous_status,
+ status: pull_request.status,
+ });
}
+
+ upserts
+ }
+
+ async fn patch_pull_request_foreign_entity(
+ &self,
+ entity: &ForeignEntity,
+ metadata: serde_json::Value,
+ github_key: &str,
+ stored_for_id: &str,
+ stored_for_auth_entity: &str,
+ ) -> Option<ForeignEntity> {
+ self.foreign_entity_service
+ .patch_foreign_entity(
+ entity.id,
+ PatchForeignEntity {
+ metadata: Some(metadata),
+ ..PatchForeignEntity::default()
+ },
+ )
+ .await
+ .inspect_err(|error| {
+ tracing::error!(
+ error=?error,
+ foreign_entity_id=%github_key,
+ stored_for_id=%stored_for_id,
+ stored_for_auth_entity=%stored_for_auth_entity,
+ "failed to patch PR foreign entity"
+ );
+ })
+ .ok()
+ }
+
+ async fn create_pull_request_foreign_entity(
+ &self,
+ github_key: &str,
+ metadata: serde_json::Value,
+ stored_for_id: &str,
+ stored_for_auth_entity: &str,
+ ) -> Option<ForeignEntity> {
+ self.foreign_entity_service
+ .create_foreign_entity(CreateForeignEntity {
+ foreign_entity_id: github_key.to_string(),
+ foreign_entity_source: GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE.to_string(),
+ metadata,
+ stored_for_id: stored_for_id.to_string(),
+ stored_for_auth_entity: stored_for_auth_entity.to_string(),
+ })
+ .await
+ .inspect_err(|error| {
+ tracing::error!(
+ error=?error,
+ foreign_entity_id=%github_key,
+ stored_for_id=%stored_for_id,
+ stored_for_auth_entity=%stored_for_auth_entity,
+ "failed to create PR foreign entity"
+ );
+ })
+ .ok()
+ }
+
+ fn pull_request_status_from_metadata(
+ metadata: &serde_json::Value,
+ ) -> Option<GithubPullRequestStatus> {
+ metadata
+ .get("status")
+ .and_then(|status| serde_json::from_value(status.clone()).ok())
}
/// Extract both legacy `MACRO-{short_uuid}` IDs and team-scoped
@@ -681,8 +779,13 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntit
}
}
-impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntityService>
- GithubSyncService for GithubSyncServiceImpl<D, R, C, F>
+impl<
+ D: DocumentService,
+ R: GithubSyncRepo,
+ C: GithubSyncClient,
+ F: ForeignEntityService,
+ N: NotificationIngress,
+> GithubSyncService for GithubSyncServiceImpl<D, R, C, F, N>
{
#[tracing::instrument(skip(self, body), err)]
async fn validate_webhook_event(
@@ -726,8 +829,13 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntit
Ok(())
}
GithubWebhookEventType::PullRequest => {
- self.upsert_pull_request_foreign_entities(webhook_event)
+ let upsert_result = self
+ .upsert_pull_request_foreign_entities(webhook_event)
.await;
+ if let Some((pull_request, upserts)) = &upsert_result {
+ self.notify_pr_status_transitions(webhook_event, pull_request, upserts)
+ .await;
+ }
match action {
Some("opened" | "reopened") => self.handle_pr_open(webhook_event).await,
@@ -743,7 +851,8 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntit
| GithubWebhookEventType::PullRequestReview
| GithubWebhookEventType::PullRequestReviewComment => {
if webhook_event.is_associated_with_pull_request() {
- self.upsert_pull_request_foreign_entities(webhook_event)
+ let _ = self
+ .upsert_pull_request_foreign_entities(webhook_event)
.await;
}
@@ -751,7 +860,8 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntit
}
GithubWebhookEventType::CheckRun => {
if webhook_event.is_associated_with_pull_request() {
- self.upsert_pull_request_foreign_entities(webhook_event)
+ let _ = self
+ .upsert_pull_request_foreign_entities(webhook_event)
.await;
} else {
tracing::debug!("skipping check_run event without an associated PR");
diff --git a/rust/cloud-storage/github/src/domain/service/sync/notify_pr.rs b/rust/cloud-storage/github/src/domain/service/sync/notify_pr.rs
new file mode 100644
index 0000000000..8643a30597
--- /dev/null
+++ b/rust/cloud-storage/github/src/domain/service/sync/notify_pr.rs
@@ -0,0 +1,263 @@
+//! GitHub pull request notification helpers.
+
+use std::collections::HashSet;
+
+use chrono::{DateTime, Utc};
+use documents::domain::ports::DocumentService;
+use foreign_entity::domain::ports::ForeignEntityService;
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::EntityType;
+use model_notifications::{GithubPrEvent, GithubPrEventAction, GithubPrEventStatus};
+use notification::domain::{models::SendNotificationRequestBuilder, service::NotificationIngress};
+
+use crate::domain::{
+ models::{
+ EnrichedGithubPullRequest, GithubAppInstallationSource, GithubPullRequestStatus,
+ ValidatedGithubWebhookEvent,
+ },
+ ports::{GithubSyncClient, GithubSyncRepo},
+};
+
+use super::{GithubSyncServiceImpl, PullRequestForeignEntityUpsert};
+
+struct PullRequestStatusTransition {
+ previous_status: Option<GithubPullRequestStatus>,
+ status: GithubPullRequestStatus,
+}
+
+impl<
+ D: DocumentService,
+ R: GithubSyncRepo,
+ C: GithubSyncClient,
+ F: ForeignEntityService,
+ N: NotificationIngress,
+> GithubSyncServiceImpl<D, R, C, F, N>
+{
+ pub(super) async fn notify_pr_status_transitions(
+ &self,
+ event: &ValidatedGithubWebhookEvent,
+ pull_request: &EnrichedGithubPullRequest,
+ upserts: &[PullRequestForeignEntityUpsert],
+ ) {
+ let Some(action) = Self::github_pr_event_action(event) else {
+ return;
+ };
+
+ let transitions: Vec<_> = upserts
+ .iter()
+ .filter_map(|upsert| {
+ Self::status_transition(upsert).map(|transition| (upsert, transition))
+ })
+ .collect();
+ if transitions.is_empty() {
+ return;
+ }
+
+ let sender_id = self.notification_sender_id(event).await;
+ for (upsert, transition) in transitions {
+ let recipient_ids = self.notification_recipient_ids(&upsert.source).await;
+ if recipient_ids.is_empty() {
+ tracing::trace!(
+ source_id=%upsert.source.source_id(),
+ source_type=%upsert.source.source_type(),
+ foreign_entity_id=%upsert.foreign_entity_id,
+ "skipping GitHub PR notification without recipients"
+ );
+ continue;
+ }
+
+ let notification = Self::github_pr_event(
+ event,
+ pull_request,
+ upsert.foreign_entity_id,
+ action,
+ transition,
+ );
+ let notification_entity =
+ EntityType::ForeignEntity.with_entity_string(upsert.foreign_entity_id.to_string());
+ let request = SendNotificationRequestBuilder {
+ notification_entity,
+ notification,
+ sender_id: sender_id.clone(),
+ recipient_ids,
+ }
+ .into_request()
+ .with_apns()
+ .with_conn_gateway();
+
+ if let Err(error) = self.notification_ingress.send_notification(request).await {
+ tracing::error!(
+ error=?error,
+ source_id=%upsert.source.source_id(),
+ source_type=%upsert.source.source_type(),
+ foreign_entity_id=%upsert.foreign_entity_id,
+ "failed to send GitHub PR notification"
+ );
+ }
+ }
+ }
+
+ fn status_transition(
+ upsert: &PullRequestForeignEntityUpsert,
+ ) -> Option<PullRequestStatusTransition> {
+ let status = upsert.status?;
+ if upsert.previous_status == Some(status) {
+ return None;
+ }
+
+ Some(PullRequestStatusTransition {
+ previous_status: upsert.previous_status,
+ status,
+ })
+ }
+
+ async fn notification_recipient_ids(
+ &self,
+ source: &GithubAppInstallationSource,
+ ) -> HashSet<MacroUserIdStr<'static>> {
+ match source {
+ GithubAppInstallationSource::Team(team_id) => self.team_recipient_ids(*team_id).await,
+ GithubAppInstallationSource::User(user_id) => {
+ match MacroUserIdStr::try_from(user_id.clone()) {
+ Ok(user_id) => HashSet::from([user_id]),
+ Err(error) => {
+ tracing::warn!(
+ error=?error,
+ source_id=%user_id,
+ "skipping GitHub PR notification for invalid user source"
+ );
+ HashSet::new()
+ }
+ }
+ }
+ }
+ }
+
+ async fn team_recipient_ids(&self, team_id: uuid::Uuid) -> HashSet<MacroUserIdStr<'static>> {
+ match self.repo.get_team_member_ids(team_id).await {
+ Ok(member_ids) => member_ids.into_iter().collect(),
+ Err(error) => {
+ tracing::error!(
+ error=?error,
+ team_id=%team_id,
+ "failed to expand GitHub PR notification team recipients"
+ );
+ HashSet::new()
+ }
+ }
+ }
+
+ async fn notification_sender_id(
+ &self,
+ event: &ValidatedGithubWebhookEvent,
+ ) -> Option<MacroUserIdStr<'static>> {
+ let github_user_id = event.sender_github_user_id()?;
+ let macro_id = match self
+ .repo
+ .get_macro_id_by_github_user_id(&github_user_id)
+ .await
+ {
+ Ok(Some(macro_id)) => macro_id,
+ Ok(None) => return None,
+ Err(error) => {
+ tracing::warn!(
+ error=?error,
+ sender_github_user_id=%github_user_id,
+ "failed to map GitHub PR notification sender"
+ );
+ return None;
+ }
+ };
+
+ match MacroUserIdStr::try_from(macro_id.clone()) {
+ Ok(sender_id) => Some(sender_id),
+ Err(error) => {
+ tracing::warn!(
+ error=?error,
+ macro_id=%macro_id,
+ sender_github_user_id=%github_user_id,
+ "GitHub PR notification sender mapping is not a valid Macro user ID"
+ );
+ None
+ }
+ }
+ }
+
+ fn github_pr_event(
+ event: &ValidatedGithubWebhookEvent,
+ pull_request: &EnrichedGithubPullRequest,
+ foreign_entity_id: uuid::Uuid,
+ action: GithubPrEventAction,
+ transition: PullRequestStatusTransition,
+ ) -> GithubPrEvent {
+ GithubPrEvent {
+ foreign_entity_id,
+ github_key: pull_request.github_key.clone(),
+ owner: pull_request.owner.clone(),
+ repo: pull_request.repo.clone(),
+ number: pull_request.number,
+ url: pull_request.url.clone(),
+ display_name: pull_request.display_name.clone(),
+ title: GithubPrEvent::title_or_display_name(
+ pull_request.name.clone(),
+ &pull_request.display_name,
+ ),
+ status: Self::github_pr_event_status(transition.status),
+ action,
+ previous_status: transition.previous_status.map(Self::github_pr_event_status),
+ sender_github_login: Self::payload_string(&event.payload, &["sender", "login"]),
+ sender_github_user_id: event.sender_github_user_id(),
+ sender_github_avatar_url: Self::payload_string(
+ &event.payload,
+ &["sender", "avatar_url"],
+ ),
+ head_branch: Self::payload_string(&event.payload, &["pull_request", "head", "ref"]),
+ base_branch: Self::payload_string(&event.payload, &["pull_request", "base", "ref"]),
+ merged_at: Self::pull_request_merged_at(event),
+ }
+ }
+
+ fn github_pr_event_action(event: &ValidatedGithubWebhookEvent) -> Option<GithubPrEventAction> {
+ match event.action() {
+ Some("opened") => Some(GithubPrEventAction::Opened),
+ Some("reopened") => Some(GithubPrEventAction::Reopened),
+ Some("closed") => Some(GithubPrEventAction::Closed),
+ _ => None,
+ }
+ }
+
+ fn github_pr_event_status(status: GithubPullRequestStatus) -> GithubPrEventStatus {
+ match status {
+ GithubPullRequestStatus::Open => GithubPrEventStatus::Open,
+ GithubPullRequestStatus::Closed => GithubPrEventStatus::Closed,
+ GithubPullRequestStatus::Merged => GithubPrEventStatus::Merged,
+ }
+ }
+
+ fn payload_string(payload: &serde_json::Value, path: &[&str]) -> Option<String> {
+ let mut value = payload;
+ for key in path {
+ value = value.get(*key)?;
+ }
+
+ value
+ .as_str()
+ .filter(|value| !value.is_empty())
+ .map(str::to_string)
+ }
+
+ fn pull_request_merged_at(event: &ValidatedGithubWebhookEvent) -> Option<DateTime<Utc>> {
+ let merged_at = Self::payload_string(&event.payload, &["pull_request", "merged_at"])?;
+ match DateTime::parse_from_rfc3339(&merged_at) {
+ Ok(merged_at) => Some(merged_at.with_timezone(&Utc)),
+ Err(error) => {
+ tracing::warn!(
+ error=?error,
+ merged_at,
+ "failed to parse GitHub PR merged_at timestamp for notification"
+ );
+ None
+ }
+ }
+ }
+}
diff --git a/rust/cloud-storage/github/src/domain/service/sync/test.rs b/rust/cloud-storage/github/src/domain/service/sync/test.rs
index 5fece4aa01..8cef48ca70 100644
--- a/rust/cloud-storage/github/src/domain/service/sync/test.rs
+++ b/rust/cloud-storage/github/src/domain/service/sync/test.rs
@@ -34,6 +34,10 @@ use macro_user_id::user_id::MacroUserIdStr;
use model::document::{DocumentBasic, DocumentMetadata};
use model_entity::Entity;
use models_permissions::share_permission::access_level::AccessLevel;
+use notification::domain::{
+ models::{Notification, NotificationResult, SendNotificationRequest},
+ service::{NotificationIngress, SendNotificationError},
+};
use super::*;
@@ -264,6 +268,8 @@ struct StubSyncRepo {
github_links: Mutex<HashMap<String, String>>,
/// Maps macro_id -> team_ids for installation event lookups.
user_teams: Mutex<HashMap<String, Vec<uuid::Uuid>>>,
+ /// Maps team_id -> Macro user IDs for notification recipient lookups.
+ team_members: Mutex<HashMap<uuid::Uuid, Vec<MacroUserIdStr<'static>>>>,
/// Current github_app_installation source rows keyed by installation id.
installation_source_rows: Mutex<HashMap<String, HashSet<GithubAppInstallationSource>>>,
/// Recorded installation source upserts: (installation_id, sources).
@@ -277,6 +283,7 @@ impl StubSyncRepo {
team_task_references: Mutex::new(HashMap::new()),
github_links: Mutex::new(HashMap::new()),
user_teams: Mutex::new(HashMap::new()),
+ team_members: Mutex::new(HashMap::new()),
installation_source_rows: Mutex::new(HashMap::new()),
installation_sources: Mutex::new(Vec::new()),
}
@@ -298,6 +305,18 @@ impl StubSyncRepo {
self
}
+ fn with_team_members(self, team_id: uuid::Uuid, member_ids: Vec<&str>) -> Self {
+ let member_ids = member_ids
+ .into_iter()
+ .map(|member_id| MacroUserIdStr::try_from(member_id.to_string()).unwrap())
+ .collect();
+ self.team_members
+ .lock()
+ .unwrap()
+ .insert(team_id, member_ids);
+ self
+ }
+
fn with_team_task_reference(
self,
installation_id: &str,
@@ -428,6 +447,21 @@ impl GithubSyncRepo for StubSyncRepo {
.unwrap_or_default())
}
+ async fn get_team_member_ids(
+ &self,
+ team_id: uuid::Uuid,
+ ) -> Result<Vec<MacroUserIdStr<'static>>, Self::Err> {
+ let mut member_ids = self
+ .team_members
+ .lock()
+ .unwrap()
+ .get(&team_id)
+ .cloned()
+ .unwrap_or_default();
+ member_ids.sort_by(|left, right| left.as_ref().cmp(right.as_ref()));
+ Ok(member_ids)
+ }
+
async fn get_installation_sources(
&self,
installation_id: &str,
@@ -459,6 +493,30 @@ impl GithubSyncRepo for StubSyncRepo {
}
}
+#[tokio::test]
+async fn test_get_team_member_ids_stub_returns_fixture_members() {
+ let team_id: uuid::Uuid = "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap();
+ let repo = StubSyncRepo::new()
+ .with_team_members(team_id, vec!["macro|[email protected]", "macro|[email protected]"]);
+
+ let member_ids = repo.get_team_member_ids(team_id).await.unwrap();
+ let member_ids: Vec<String> = member_ids.into_iter().map(String::from).collect();
+
+ assert_eq!(
+ member_ids,
+ vec![
+ "macro|[email protected]".to_string(),
+ "macro|[email protected]".to_string(),
+ ]
+ );
+ assert!(
+ repo.get_team_member_ids(uuid::Uuid::nil())
+ .await
+ .unwrap()
+ .is_empty()
+ );
+}
+
/// Recorded PR comment call.
#[derive(Debug, Clone)]
struct PrCommentCall {
@@ -769,11 +827,61 @@ impl ForeignEntityService for StubForeignEntityService {
}
}
+struct StubNotificationIngress {
+ requests: Mutex<Vec<serde_json::Value>>,
+ fail_sends: bool,
+}
+
+impl StubNotificationIngress {
+ fn new() -> Self {
+ Self {
+ requests: Mutex::new(Vec::new()),
+ fail_sends: false,
+ }
+ }
+
+ fn failing() -> Self {
+ Self {
+ requests: Mutex::new(Vec::new()),
+ fail_sends: true,
+ }
+ }
+
+ fn requests(&self) -> Vec<serde_json::Value> {
+ self.requests.lock().unwrap().clone()
+ }
+
+ fn clear_requests(&self) {
+ self.requests.lock().unwrap().clear();
+ }
+}
+
+impl NotificationIngress for StubNotificationIngress {
+ async fn send_notification<
+ 'a,
+ T: Notification + Clone + 'static,
+ U: serde::Serialize + Send + Sync + 'static,
+ >(
+ &'a self,
+ request: SendNotificationRequest<'a, T, U>,
+ ) -> Result<Option<NotificationResult<'a>>, rootcause::Report<SendNotificationError>> {
+ let snapshot = serde_json::to_value(&request).unwrap();
+ self.requests.lock().unwrap().push(snapshot);
+
+ if self.fail_sends {
+ return Err(rootcause::Report::new(SendNotificationError::Other));
+ }
+
+ Ok(None)
+ }
+}
+
type TestGithubSyncService = GithubSyncServiceImpl<
StubDocumentService,
StubSyncRepo,
StubSyncClient,
StubForeignEntityService,
+ StubNotificationIngress,
>;
type TestServiceWithForeignEntityService = (TestGithubSyncService, Arc<StubForeignEntityService>);
@@ -782,6 +890,13 @@ fn make_sync_service() -> TestGithubSyncService {
}
fn make_sync_service_with_repo(repo: StubSyncRepo) -> TestGithubSyncService {
+ make_sync_service_with_repo_and_notification_ingress(repo, StubNotificationIngress::new())
+}
+
+fn make_sync_service_with_repo_and_notification_ingress(
+ repo: StubSyncRepo,
+ notification_ingress: StubNotificationIngress,
+) -> TestGithubSyncService {
let doc_service = Arc::new(StubDocumentService::new());
let foreign_entity_service = Arc::new(StubForeignEntityService::new());
@@ -794,6 +909,7 @@ fn make_sync_service_with_repo(repo: StubSyncRepo) -> TestGithubSyncService {
},
doc_service,
foreign_entity_service,
+ notification_ingress,
repo,
StubSyncClient::new(),
)
@@ -812,6 +928,7 @@ fn make_sync_service_with_doc_service() -> (TestGithubSyncService, Arc<StubDocum
},
doc_service.clone(),
foreign_entity_service,
+ StubNotificationIngress::new(),
StubSyncRepo::new(),
StubSyncClient::new(),
);
@@ -854,6 +971,91 @@ fn expected_pull_request_metadata(
.unwrap()
}
+fn notification_request_content(request: &serde_json::Value) -> &serde_json::Value {
+ request
+ .pointer("/req/notification/content")
+ .expect("notification request content")
+}
+
+fn notification_request_recipients(request: &serde_json::Value) -> Vec<String> {
+ let mut recipient_ids: Vec<String> = request
+ .pointer("/req/recipient_ids")
+ .expect("notification recipients")
+ .as_array()
+ .expect("recipient_ids is an array")
+ .iter()
+ .map(|value| {
+ value
+ .as_str()
+ .expect("recipient id is a string")
+ .to_string()
+ })
+ .collect();
+ recipient_ids.sort();
+ recipient_ids
+}
+
+fn assert_github_pr_notification_delivery_enabled(request: &serde_json::Value) {
+ assert_eq!(
+ request
+ .pointer("/req/notification/tag")
+ .and_then(|value| value.as_str()),
+ Some("github_pr_event")
+ );
+ assert_eq!(
+ request
+ .pointer("/send_conn_gateway")
+ .and_then(|value| value.as_bool()),
+ Some(true)
+ );
+ assert!(
+ !request
+ .pointer("/build_apns")
+ .expect("build_apns field")
+ .is_null(),
+ "GitHub PR notifications should include APNS payloads"
+ );
+}
+
+fn notification_pull_request_event(
+ action: &str,
+ title: &str,
+ state: &str,
+ merged: bool,
+ merged_at: Option<&str>,
+ sender_id: u64,
+ sender_login: &str,
+) -> ValidatedGithubWebhookEvent {
+ ValidatedGithubWebhookEvent::new(
+ "pull_request".to_string(),
+ serde_json::json!({
+ "action": action,
+ "pull_request": {
+ "number": 42,
+ "title": title,
+ "body": null,
+ "head": { "ref": "feature/some-branch" },
+ "base": { "ref": "main" },
+ "state": state,
+ "merged": merged,
+ "merged_at": merged_at,
+ "additions": 10,
+ "deletions": 2
+ },
+ "repository": {
+ "name": "my-repo",
+ "owner": { "login": "my-org" }
+ },
+ "installation": { "id": 12345 },
+ "sender": {
+ "login": sender_login,
+ "id": sender_id,
+ "avatar_url": format!("https://avatars.example/{sender_login}.png")
+ }
+ }),
+ )
+}
+
fn backfilled_pull_request(title: &str) -> EnrichedGithubPullRequest {
EnrichedGithubPullRequest {
github_key: "my-org/my-repo/pull/42".to_string(),
@@ -1733,6 +1935,313 @@ async fn pr_opened_upserts_foreign_entity_for_user_installation_source() {
assert_eq!(foreign_entities[0].stored_for_auth_entity, "user");
}
+#[tokio::test]
+async fn github_pr_event_opened_team_source_notifies_team_members() {
+ let team_id: uuid::Uuid = "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap();
+ let repo = StubSyncRepo::new()
+ .with_installation_sources("12345", vec![GithubAppInstallationSource::Team(team_id)])
+ .with_team_members(team_id, vec!["macro|[email protected]", "macro|[email protected]"])
+ .with_github_link("222", "macro|[email protected]");
+ let service = make_sync_service_with_repo(repo);
+ let event = notification_pull_request_event(
+ "opened",
+ "Add GitHub notifications",
+ "open",
+ false,
+ None,
+ 222,
+ "octocat",
+ );
+
+ service.process_webhook_event(&event).await.unwrap();
+
+ let foreign_entity_id = service.foreign_entity_service.foreign_entities()[0].id;
+ let requests = service.notification_ingress.requests();
+ assert_eq!(requests.len(), 1);
+
+ let request = &requests[0];
+ assert_github_pr_notification_delivery_enabled(request);
+ assert_eq!(
+ request
+ .pointer("/req/notification_entity/entity_type")
+ .and_then(|value| value.as_str()),
+ Some("foreign_entity")
+ );
+ assert_eq!(
+ request
+ .pointer("/req/notification_entity/entity_id")
+ .and_then(|value| value.as_str()),
+ Some(foreign_entity_id.to_string().as_str())
+ );
+ assert_eq!(
+ request
+ .pointer("/req/sender_id")
+ .and_then(|value| value.as_str()),
+ Some("macro|[email protected]")
+ );
+ assert_eq!(
+ notification_request_recipients(request),
+ vec![
+ "macro|[email protected]".to_string(),
+ "macro|[email protected]".to_string(),
+ ]
+ );
+
+ let content = notification_request_content(request);
+ assert_eq!(
+ content
+ .get("foreignEntityId")
+ .and_then(|value| value.as_str()),
+ Some(foreign_entity_id.to_string().as_str())
+ );
+ assert_eq!(
+ content.get("githubKey").and_then(|value| value.as_str()),
+ Some("my-org/my-repo/pull/42")
+ );
+ assert_eq!(
+ content.get("owner").and_then(|value| value.as_str()),
+ Some("my-org")
+ );
+ assert_eq!(
+ content.get("repo").and_then(|value| value.as_str()),
+ Some("my-repo")
+ );
+ assert_eq!(
+ content.get("number").and_then(|value| value.as_u64()),
+ Some(42)
+ );
+ assert_eq!(
+ content.get("url").and_then(|value| value.as_str()),
+ Some("https://github.com/my-org/my-repo/pull/42")
+ );
+ assert_eq!(
+ content.get("displayName").and_then(|value| value.as_str()),
+ Some("my-org/my-repo#42")
+ );
+ assert_eq!(
+ content.get("title").and_then(|value| value.as_str()),
+ Some("Add GitHub notifications")
+ );
+ assert_eq!(
+ content.get("status").and_then(|value| value.as_str()),
+ Some("open")
+ );
+ assert_eq!(
+ content.get("action").and_then(|value| value.as_str()),
+ Some("opened")
+ );
+ assert!(content.get("previousStatus").unwrap().is_null());
+ assert_eq!(
+ content
+ .get("senderGithubLogin")
+ .and_then(|value| value.as_str()),
+ Some("octocat")
+ );
+ assert_eq!(
+ content
+ .get("senderGithubUserId")
+ .and_then(|value| value.as_str()),
+ Some("222")
+ );
+ assert_eq!(
+ content
+ .get("senderGithubAvatarUrl")
+ .and_then(|value| value.as_str()),
+ Some("https://avatars.example/octocat.png")
+ );
+ assert_eq!(
+ content.get("headBranch").and_then(|value| value.as_str()),
+ Some("feature/some-branch")
+ );
+ assert_eq!(
+ content.get("baseBranch").and_then(|value| value.as_str()),
+ Some("main")
+ );
+ assert!(content.get("mergedAt").unwrap().is_null());
+}
+
+#[tokio::test]
+async fn github_pr_event_merged_user_source_notifies_user() {
+ let repo = StubSyncRepo::new()
+ .with_installation_sources(
+ "12345",
+ vec![GithubAppInstallationSource::User(
+ "macro|[email protected]".to_string(),
+ )],
+ )
+ .with_github_link("333", "macro|[email protected]");
+ let service = make_sync_service_with_repo(repo);
+ let opened_event = notification_pull_request_event(
+ "opened",
+ "Add GitHub notifications",
+ "open",
+ false,
+ None,
+ 333,
+ "monalisa",
+ );
+ service.process_webhook_event(&opened_event).await.unwrap();
+ service.notification_ingress.clear_requests();
+
+ let merged_event = notification_pull_request_event(
+ "closed",
+ "Add GitHub notifications",
+ "closed",
+ true,
+ Some("2026-05-27T19:00:00Z"),
+ 333,
+ "monalisa",
+ );
+ service.process_webhook_event(&merged_event).await.unwrap();
+
+ let foreign_entity_id = service.foreign_entity_service.foreign_entities()[0].id;
+ let requests = service.notification_ingress.requests();
+ assert_eq!(requests.len(), 1);
+
+ let request = &requests[0];
+ assert_github_pr_notification_delivery_enabled(request);
+ assert_eq!(
+ notification_request_recipients(request),
+ vec!["macro|[email protected]".to_string()]
+ );
+ assert_eq!(
+ request
+ .pointer("/req/sender_id")
+ .and_then(|value| value.as_str()),
+ Some("macro|[email protected]")
+ );
+ assert_eq!(
+ request
+ .pointer("/req/notification_entity/entity_id")
+ .and_then(|value| value.as_str()),
+ Some(foreign_entity_id.to_string().as_str())
+ );
+
+ let content = notification_request_content(request);
+ assert_eq!(
+ content
+ .get("foreignEntityId")
+ .and_then(|value| value.as_str()),
+ Some(foreign_entity_id.to_string().as_str())
+ );
+ assert_eq!(
+ content.get("status").and_then(|value| value.as_str()),
+ Some("merged")
+ );
+ assert_eq!(
+ content
+ .get("previousStatus")
+ .and_then(|value| value.as_str()),
+ Some("open")
+ );
+ assert_eq!(
+ content.get("action").and_then(|value| value.as_str()),
+ Some("closed")
+ );
+ assert_eq!(
+ content.get("mergedAt").and_then(|value| value.as_str()),
+ Some("2026-05-27T19:00:00Z")
+ );
+ assert_eq!(
+ content
+ .get("senderGithubLogin")
+ .and_then(|value| value.as_str()),
+ Some("monalisa")
+ );
+}
+
+#[tokio::test]
+async fn github_pr_event_edited_does_not_notify() {
+ let team_id: uuid::Uuid = "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap();
+ let repo = StubSyncRepo::new()
+ .with_installation_sources("12345", vec![GithubAppInstallationSource::Team(team_id)])
+ .with_team_members(team_id, vec!["macro|[email protected]"]);
+ let service = make_sync_service_with_repo(repo);
+ let event = notification_pull_request_event(
+ "edited",
+ "Update title",
+ "open",
+ false,
+ None,
+ 222,
+ "octocat",
+ );
+
+ service.process_webhook_event(&event).await.unwrap();
+
+ assert_eq!(service.foreign_entity_service.foreign_entities().len(), 1);
+ assert!(service.notification_ingress.requests().is_empty());
+}
+
+#[tokio::test]
+async fn github_pr_event_installation_backfill_does_not_notify() {
+ let repo = StubSyncRepo::new().with_github_link("12345", "macro|[email protected]");
+ let service = make_sync_service_with_repo(repo);
+ service
+ .client
+ .set_open_pull_requests(vec![backfilled_pull_request("Backfilled PR")]);
+ let event = installation_created_event(12345, 12345);
+
+ service.process_webhook_event(&event).await.unwrap();
+
+ assert_eq!(service.foreign_entity_service.foreign_entities().len(), 1);
+ assert!(service.notification_ingress.requests().is_empty());
+}
+
+#[tokio::test]
+async fn github_pr_event_unchanged_status_does_not_notify() {
+ let team_id: uuid::Uuid = "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap();
+ let repo = StubSyncRepo::new()
+ .with_installation_sources("12345", vec![GithubAppInstallationSource::Team(team_id)])
+ .with_team_members(team_id, vec!["macro|[email protected]"]);
+ let service = make_sync_service_with_repo(repo);
+ let event = notification_pull_request_event(
+ "opened",
+ "Add GitHub notifications",
+ "open",
+ false,
+ None,
+ 222,
+ "octocat",
+ );
+
+ service.process_webhook_event(&event).await.unwrap();
+ service.notification_ingress.clear_requests();
+ service.process_webhook_event(&event).await.unwrap();
+
+ assert_eq!(service.foreign_entity_service.foreign_entities().len(), 1);
+ assert!(service.notification_ingress.requests().is_empty());
+}
+
+#[tokio::test]
+async fn github_pr_event_send_failure_does_not_fail_webhook_processing() {
+ let repo = StubSyncRepo::new().with_installation_sources(
+ "12345",
+ vec![GithubAppInstallationSource::User(
+ "macro|[email protected]".to_string(),
+ )],
+ );
+ let service = make_sync_service_with_repo_and_notification_ingress(
+ repo,
+ StubNotificationIngress::failing(),
+ );
+ let event = notification_pull_request_event(
+ "opened",
+ "Add GitHub notifications",
+ "open",
+ false,
+ None,
+ 222,
+ "octocat",
+ );
+
+ let result = service.process_webhook_event(&event).await;
+
+ assert!(result.is_ok());
+ assert_eq!(service.foreign_entity_service.foreign_entities().len(), 1);
+ assert_eq!(service.notification_ingress.requests().len(), 1);
+}
+
#[tokio::test]
async fn pr_edit_patches_existing_foreign_entity_metadata() {
let (service, foreign_entity_service) = make_sync_service_with_foreign_entity_service();
diff --git a/rust/cloud-storage/github/src/outbound/pg_github_sync_repo.rs b/rust/cloud-storage/github/src/outbound/pg_github_sync_repo.rs
index caf7fd5c0b..1e88465648 100644
--- a/rust/cloud-storage/github/src/outbound/pg_github_sync_repo.rs
+++ b/rust/cloud-storage/github/src/outbound/pg_github_sync_repo.rs
@@ -5,6 +5,7 @@ mod test;
use std::collections::HashSet;
+use macro_user_id::user_id::MacroUserIdStr;
use sqlx::PgPool;
use crate::domain::{
@@ -193,6 +194,40 @@ impl GithubSyncRepo for PgGithubSyncRepo {
Ok(team_ids)
}
+ #[tracing::instrument(skip(self), err)]
+ async fn get_team_member_ids(
+ &self,
+ team_id: uuid::Uuid,
+ ) -> Result<Vec<MacroUserIdStr<'static>>, Self::Err> {
+ let user_ids: Vec<String> = sqlx::query_scalar!(
+ r#"
+ SELECT user_id
+ FROM team_user
+ WHERE team_id = $1
+ ORDER BY user_id
+ "#,
+ team_id,
+ )
+ .fetch_all(&self.pool)
+ .await?;
+
+ Ok(user_ids
+ .into_iter()
+ .filter_map(|user_id| match MacroUserIdStr::try_from(user_id.clone()) {
+ Ok(user_id) => Some(user_id),
+ Err(error) => {
+ tracing::warn!(
+ team_id=%team_id,
+ user_id,
+ error=?error,
+ "team_user.user_id is not a Macro user ID"
+ );
+ None
+ }
+ })
+ .collect())
+ }
+
#[tracing::instrument(skip(self), err)]
async fn get_installation_sources(
&self,
diff --git a/rust/cloud-storage/github/src/outbound/pg_github_sync_repo/test.rs b/rust/cloud-storage/github/src/outbound/pg_github_sync_repo/test.rs
index 0c6290750a..55d869976b 100644
--- a/rust/cloud-storage/github/src/outbound/pg_github_sync_repo/test.rs
+++ b/rust/cloud-storage/github/src/outbound/pg_github_sync_repo/test.rs
@@ -369,6 +369,133 @@ async fn test_get_user_team_ids_no_teams(pool: Pool<Postgres>) {
assert!(team_ids.is_empty());
}
+// ---------------------------------------------------------------------------
+// get_team_member_ids
+// ---------------------------------------------------------------------------
+
+async fn insert_user_account(
+ pool: &Pool<Postgres>,
+ user_id: &str,
+ macro_user_id: Uuid,
+ username: &str,
+ email: &str,
+ stripe_customer_id: &str,
+) {
+ sqlx::query(
+ r#"
+ INSERT INTO public.macro_user (id, username, email, stripe_customer_id)
+ VALUES ($1, $2, $3, $4)
+ "#,
+ )
+ .bind(macro_user_id)
+ .bind(username)
+ .bind(email)
+ .bind(stripe_customer_id)
+ .execute(pool)
+ .await
+ .unwrap();
+
+ sqlx::query(
+ r#"
+ INSERT INTO public."User" (id, email, macro_user_id)
+ VALUES ($1, $2, $3)
+ "#,
+ )
+ .bind(user_id)
+ .bind(email)
+ .bind(macro_user_id)
+ .execute(pool)
+ .await
+ .unwrap();
+}
+
+async fn insert_team_member(pool: &Pool<Postgres>, team_id: Uuid, user_id: &str) {
+ sqlx::query(
+ r#"
+ INSERT INTO public.team_user (user_id, team_id, team_role)
+ VALUES ($1, $2, 'member')
+ "#,
+ )
+ .bind(user_id)
+ .bind(team_id)
+ .execute(pool)
+ .await
+ .unwrap();
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("github_installation_test_data"))
+)]
+async fn test_get_team_member_ids(pool: Pool<Postgres>) {
+ let team_id = "dddddddd-dddd-dddd-dddd-dddddddddddd"
+ .parse::<Uuid>()
+ .unwrap();
+
+ insert_user_account(
+ &pool,
+ "11111111-1111-1111-1111-111111111111".parse().unwrap(),
+ "zeta",
+ "cus_zeta",
+ )
+ .await;
+ insert_user_account(
+ &pool,
+ "22222222-2222-2222-2222-222222222222".parse().unwrap(),
+ "alpha",
+ "cus_alpha",
+ )
+ .await;
+ insert_user_account(
+ &pool,
+ "github-user-without-macro-prefix",
+ "33333333-3333-3333-3333-333333333333".parse().unwrap(),
+ "invalid",
+ "cus_invalid",
+ )
+ .await;
+ insert_team_member(&pool, team_id, "macro|[email protected]").await;
+ insert_team_member(&pool, team_id, "macro|[email protected]").await;
+ insert_team_member(&pool, team_id, "github-user-without-macro-prefix").await;
+
+ let empty_team_id = "44444444-4444-4444-4444-444444444444"
+ .parse::<Uuid>()
+ .unwrap();
+ sqlx::query(
+ r#"
+ INSERT INTO public.team (id, name, owner_id)
+ VALUES ($1, $2, $3)
+ "#,
+ )
+ .bind(empty_team_id)
+ .bind("Empty Team")
+ .bind("macro|[email protected]")
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ let repo = PgGithubSyncRepo::new(pool);
+
+ let member_ids = repo.get_team_member_ids(team_id).await.unwrap();
+ let member_ids: Vec<String> = member_ids.into_iter().map(String::from).collect();
+ assert_eq!(
+ member_ids,
+ vec![
+ "macro|[email protected]".to_string(),
+ "macro|[email protected]".to_string(),
+ "macro|[email protected]".to_string(),
+ ]
+ );
+
+ let empty_member_ids = repo.get_team_member_ids(empty_team_id).await.unwrap();
+ assert!(empty_member_ids.is_empty());
+}
+
// ---------------------------------------------------------------------------
// upsert_installation_sources
// ---------------------------------------------------------------------------
diff --git a/rust/cloud-storage/model_notifications/src/lib.rs b/rust/cloud-storage/model_notifications/src/lib.rs
index 7eebc838e5..52dbdc6ee2 100644
--- a/rust/cloud-storage/model_notifications/src/lib.rs
+++ b/rust/cloud-storage/model_notifications/src/lib.rs
@@ -12,9 +12,10 @@ pub use device::DeviceType;
pub use metadata::{
AiResponseMetadata, ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageSendMetadata,
ChannelReplyMetadata, ChannelType, CommentedOnDocumentMetadata, CommonChannelMetadata,
- DocumentMentionMetadata, InviteToTeamMetadata, ItemSharedMetadata,
- MentionedInDocumentCommentMetadata, NewEmailMetadata, NotificationDocumentSubType,
- NotificationTitle, RepliedToDocumentCommentThreadMetadata, TaskAssignedMetadata,
+ DocumentMentionMetadata, GithubPrEvent, GithubPrEventAction, GithubPrEventStatus,
+ InviteToTeamMetadata, ItemSharedMetadata, MentionedInDocumentCommentMetadata, NewEmailMetadata,
+ NotificationDocumentSubType, NotificationTitle, RepliedToDocumentCommentThreadMetadata,
+ TaskAssignedMetadata,
};
pub use unsubscribe::UserUnsubscribe;
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
@@ -200,6 +201,9 @@ define_notif_event!(
/// An AI assistant responded to a chat.
AiResponse(AiResponseMetadata),
+
+ /// A GitHub pull request changed lifecycle state.
+ GithubPrEvent(GithubPrEvent),
}
);
@@ -235,6 +239,7 @@ impl NotificationTitle for NotifEvent {
NotifEvent::AiResponse(ai_response_metadata) => {
ai_response_metadata.format_title(sender_id)
}
+ NotifEvent::GithubPrEvent(github_pr_event) => github_pr_event.format_title(sender_id),
}
}
@@ -269,6 +274,7 @@ impl NotificationTitle for NotifEvent {
NotifEvent::AiResponse(ai_response_metadata) => {
ai_response_metadata.format_body(sender_id)
}
+ NotifEvent::GithubPrEvent(github_pr_event) => github_pr_event.format_body(sender_id),
}
}
}
diff --git a/rust/cloud-storage/model_notifications/src/metadata.rs b/rust/cloud-storage/model_notifications/src/metadata.rs
index fa08437ea8..3261ba9282 100644
--- a/rust/cloud-storage/model_notifications/src/metadata.rs
+++ b/rust/cloud-storage/model_notifications/src/metadata.rs
@@ -1,3 +1,4 @@
+use chrono::{DateTime, Utc};
use doppleganger::Doppleganger;
pub use invite_email::{ChannelInviteMetadata, InviteToTeamMetadata};
use macro_user_id::cowlike::CowLike;
@@ -26,6 +27,147 @@ pub struct AiResponseMetadata {
pub message_id: String,
}
+/// The normalized lifecycle status for a GitHub pull request notification.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, ToSchema, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum GithubPrEventStatus {
+ /// The pull request is open.
+ Open,
+ /// The pull request is closed without being merged.
+ Closed,
+ /// The pull request is closed and merged.
+ Merged,
+}
+
+/// The GitHub pull request webhook action that triggered the notification.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, ToSchema, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum GithubPrEventAction {
+ /// The pull request was opened.
+ Opened,
+ /// The pull request was reopened.
+ Reopened,
+ /// The pull request was closed.
+ Closed,
+}
+
+/// Metadata for a GitHub pull request lifecycle notification.
+#[derive(Debug, Clone, PartialEq, Eq, ToSchema, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GithubPrEvent {
+ /// The source-specific internal foreign entity row id for this pull request.
+ pub foreign_entity_id: Uuid,
+ /// The external GitHub key, in `owner/repo/pull/number` format.
+ pub github_key: String,
+ /// The GitHub repository owner or organization.
+ pub owner: String,
+ /// The GitHub repository name.
+ pub repo: String,
+ /// The GitHub pull request number.
+ pub number: u64,
+ /// The public GitHub URL for the pull request.
+ pub url: String,
+ /// A compact label suitable for display in the UI.
+ pub display_name: String,
+ /// The GitHub pull request title. Falls back to `display_name` when GitHub has no title.
+ pub title: String,
+ /// The current normalized pull request status.
+ pub status: GithubPrEventStatus,
+ /// The webhook action that triggered this notification.
+ pub action: GithubPrEventAction,
+ /// The prior normalized pull request status, when known.
+ pub previous_status: Option<GithubPrEventStatus>,
+ /// The GitHub login for the sender, when available.
+ pub sender_github_login: Option<String>,
+ /// The stable GitHub numeric user id for the sender, serialized as a string.
+ pub sender_github_user_id: Option<String>,
+ /// The GitHub avatar URL for the sender, when available.
+ pub sender_github_avatar_url: Option<String>,
+ /// The pull request head branch, when available.
+ pub head_branch: Option<String>,
+ /// The pull request base branch, when available.
+ pub base_branch: Option<String>,
+ /// When the pull request was merged, when available.
+ pub merged_at: Option<DateTime<Utc>>,
+}
+
+impl GithubPrEvent {
+ /// Build a required title value, falling back to the display name when GitHub has no title.
+ pub fn title_or_display_name(title: Option<String>, display_name: &str) -> String {
+ match title {
+ Some(title) if !title.trim().is_empty() => title,
+ _ => display_name.to_string(),
+ }
+ }
+
+ fn action_verb(&self) -> &'static str {
+ if self.status == GithubPrEventStatus::Merged {
+ return "merged";
+ }
+
+ match self.action {
+ GithubPrEventAction::Opened => "opened",
+ GithubPrEventAction::Reopened => "reopened",
+ GithubPrEventAction::Closed => "closed",
+ }
+ }
+
+ fn actor_name(&self, sender_id: Option<MacroUserIdStr<'_>>) -> Option<String> {
+ sender_id
+ .map(|sender| sender.email_part().local_part().to_string())
+ .or_else(|| self.sender_github_login.clone())
+ }
+}
+
+impl Notification for GithubPrEvent {
+ const TYPE_NAME: &'static str = "github_pr_event";
+}
+
+impl NotificationTitle for GithubPrEvent {
+ fn format_title(
+ &self,
+ sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report> {
+ let verb = self.action_verb();
+ let title = match self.actor_name(sender_id) {
+ Some(actor) => format!("{actor} {verb} a pull request"),
+ None => format!("Pull request {verb}"),
+ };
+
+ Ok(title)
+ }
+
+ fn format_body(
+ &self,
+ _sender_id: Option<MacroUserIdStr<'_>>,
+ ) -> Result<String, rootcause::Report> {
+ if self.title == self.display_name {
+ return Ok(self.display_name.clone());
+ }
+
+ Ok(format!("{}: {}", self.display_name, self.title))
+ }
+}
+
+impl NotificationExtIos for GithubPrEvent {
+ type NotifData = ::notification::domain::models::apple::PushNotificationData;
+
+ fn collapse_key(&self, entity: &Entity<'_>) -> NotifCollapseKey {
+ let entity_type: &'static str = entity.entity_type.into();
+ NotifCollapseKey::new(entity_type).append(&entity.entity_id)
+ }
+
+ fn as_apns<'a>(
+ &self,
+ sender_id: Option<MacroUserIdStr<'a>>,
+ _entity: &Entity<'_>,
+ notification_id: Uuid,
+ ) -> Option<APNSPushNotification<Self::NotifData>> {
+ let avatar_url = self.sender_github_avatar_url.clone();
+ alert_apns(self, sender_id, notification_id, avatar_url).ok()
+ }
+}
+
#[derive(Debug, Clone, Copy, ToSchema, Doppleganger, Serialize, Deserialize)]
#[dg(backward = models_comms::channel::ChannelType)]
#[serde(rename_all = "camelCase")]
diff --git a/rust/cloud-storage/model_notifications/src/metadata/test.rs b/rust/cloud-storage/model_notifications/src/metadata/test.rs
index 72f41f64f0..0dbf9f948f 100644
--- a/rust/cloud-storage/model_notifications/src/metadata/test.rs
+++ b/rust/cloud-storage/model_notifications/src/metadata/test.rs
@@ -4,6 +4,140 @@ fn uid(value: &str) -> MacroUserIdStr<'static> {
MacroUserIdStr::parse_from_str(value).unwrap().into_owned()
}
+fn utc_datetime(value: &str) -> DateTime<Utc> {
+ DateTime::parse_from_rfc3339(value)
+ .unwrap()
+ .with_timezone(&Utc)
+}
+
+fn github_pr_event() -> GithubPrEvent {
+ GithubPrEvent {
+ foreign_entity_id: Uuid::parse_str("11111111-1111-4111-8111-111111111111").unwrap(),
+ github_key: "macro/app/pull/42".to_string(),
+ owner: "macro".to_string(),
+ repo: "app".to_string(),
+ number: 42,
+ url: "https://github.com/macro/app/pull/42".to_string(),
+ display_name: "macro/app#42".to_string(),
+ title: "Add GitHub PR notifications".to_string(),
+ status: GithubPrEventStatus::Merged,
+ action: GithubPrEventAction::Closed,
+ previous_status: Some(GithubPrEventStatus::Open),
+ sender_github_login: Some("octocat".to_string()),
+ sender_github_user_id: Some("12345".to_string()),
+ sender_github_avatar_url: Some(
+ "https://avatars.githubusercontent.com/u/12345?v=4".to_string(),
+ ),
+ head_branch: Some("feature/github-pr-notifications".to_string()),
+ base_branch: Some("main".to_string()),
+ merged_at: Some(utc_datetime("2026-05-25T18:54:21Z")),
+ }
+}
+
+#[test]
+fn github_pr_event_serializes_with_camel_case_fields_and_lowercase_enums() {
+ let event = github_pr_event();
+
+ let value = serde_json::to_value(&event).unwrap();
+
+ assert_eq!(
+ value,
+ serde_json::json!({
+ "foreignEntityId": "11111111-1111-4111-8111-111111111111",
+ "githubKey": "macro/app/pull/42",
+ "owner": "macro",
+ "repo": "app",
+ "number": 42,
+ "url": "https://github.com/macro/app/pull/42",
+ "displayName": "macro/app#42",
+ "title": "Add GitHub PR notifications",
+ "status": "merged",
+ "action": "closed",
+ "previousStatus": "open",
+ "senderGithubLogin": "octocat",
+ "senderGithubUserId": "12345",
+ "senderGithubAvatarUrl": "https://avatars.githubusercontent.com/u/12345?v=4",
+ "headBranch": "feature/github-pr-notifications",
+ "baseBranch": "main",
+ "mergedAt": "2026-05-25T18:54:21Z"
+ })
+ );
+}
+
+#[test]
+fn github_pr_event_tagged_content_serializes_with_type_name() {
+ let event = github_pr_event();
+ let foreign_entity_id = event.foreign_entity_id.to_string();
+
+ let value =
+ serde_json::to_value(notification::domain::models::TaggedContent::new(event)).unwrap();
+
+ assert_eq!(value["tag"], "github_pr_event");
+ assert_eq!(
+ value["content"]["foreignEntityId"],
+ serde_json::json!(foreign_entity_id)
+ );
+}
+
+#[test]
+fn github_pr_event_formats_title_and_body() {
+ let event = github_pr_event();
+
+ let title = event
+ .format_title(Some(uid("macro|[email protected]")))
+ .unwrap();
+ let body = event.format_body(None).unwrap();
+
+ assert_eq!(title, "pr.sender merged a pull request");
+ assert_eq!(body, "macro/app#42: Add GitHub PR notifications");
+}
+
+#[test]
+fn github_pr_event_title_falls_back_to_display_name() {
+ assert_eq!(
+ GithubPrEvent::title_or_display_name(None, "macro/app#42"),
+ "macro/app#42"
+ );
+ assert_eq!(
+ GithubPrEvent::title_or_display_name(Some(String::new()), "macro/app#42"),
+ "macro/app#42"
+ );
+ assert_eq!(
+ GithubPrEvent::title_or_display_name(
+ Some("Add GitHub PR notifications".to_string()),
+ "macro/app#42"
+ ),
+ "Add GitHub PR notifications"
+ );
+
+ let mut event = github_pr_event();
+ event.title = GithubPrEvent::title_or_display_name(None, &event.display_name);
+
+ assert_eq!(event.format_body(None).unwrap(), "macro/app#42");
+}
+
+#[test]
+fn github_pr_event_uses_foreign_entity_for_collapse_key_and_apns() {
+ let event = github_pr_event();
+ let entity = EntityType::ForeignEntity.with_entity_string(event.foreign_entity_id.to_string());
+ let entity_type: &'static str = EntityType::ForeignEntity.into();
+ let expected_collapse_key = NotifCollapseKey::new(entity_type)
+ .append(&event.foreign_entity_id.to_string())
+ .into_hashed()
+ .into_inner();
+
+ let collapse_key = event.collapse_key(&entity).into_hashed().into_inner();
+ let apns = event.as_apns(None, &entity, Uuid::nil()).unwrap();
+
+ assert_eq!(collapse_key, expected_collapse_key);
+ assert_eq!(
+ apns.push_notification_data
+ .sender_profile_picture_url
+ .as_deref(),
+ Some("https://avatars.githubusercontent.com/u/12345?v=4")
+ );
+}
+
#[test]
fn channel_reply_title_uses_reply_sender_from_metadata() {
let notification = ChannelReplyMetadata {
diff --git a/rust/cloud-storage/notification/src/domain/models/request.rs b/rust/cloud-storage/notification/src/domain/models/request.rs
index 180a7d1e03..9591cacd7d 100644
--- a/rust/cloud-storage/notification/src/domain/models/request.rs
+++ b/rust/cloud-storage/notification/src/domain/models/request.rs
@@ -29,6 +29,7 @@ pub enum NotificationItemType {
Chat,
Call,
Task,
+ Github,
}
impl NotificationItemType {
@@ -42,6 +43,7 @@ impl NotificationItemType {
Self::Chat => "chat",
Self::Call => "call",
Self::Task => "task",
+ Self::Github => "github",
}
}
}
diff --git a/rust/cloud-storage/notification/src/inbound/ai_tool/test.rs b/rust/cloud-storage/notification/src/inbound/ai_tool/test.rs
index 9155981a48..dc424d7c6d 100644
--- a/rust/cloud-storage/notification/src/inbound/ai_tool/test.rs
+++ b/rust/cloud-storage/notification/src/inbound/ai_tool/test.rs
@@ -32,7 +32,7 @@ fn test_list_notifications_deserialization() {
assert_eq!(tool.entities, None);
// With explicit filters
- let json = r#"{"limit": 10, "done": true, "seen": false, "includeTypes": ["email", "message"], "entities": [{"entityType": "email", "id": "thread-1"}]}"#;
+ let json = r#"{"limit": 10, "done": true, "seen": false, "includeTypes": ["email", "message", "github"], "entities": [{"entityType": "email", "id": "thread-1"}, {"entityType": "github", "id": "foreign-entity-1"}]}"#;
let tool: ListNotifications = serde_json::from_str(json).unwrap();
assert_eq!(tool.limit, Some(10));
assert_eq!(tool.done, Some(true));
@@ -41,15 +41,22 @@ fn test_list_notifications_deserialization() {
tool.include_types,
Some(vec![
NotificationItemType::Email,
- NotificationItemType::Message
+ NotificationItemType::Message,
+ NotificationItemType::Github
])
);
assert_eq!(
tool.entities,
- Some(vec![NotificationEntityRef {
- entity_type: NotificationItemType::Email,
- id: "thread-1".to_string()
- }])
+ Some(vec![
+ NotificationEntityRef {
+ entity_type: NotificationItemType::Email,
+ id: "thread-1".to_string()
+ },
+ NotificationEntityRef {
+ entity_type: NotificationItemType::Github,
+ id: "foreign-entity-1".to_string()
+ }
+ ])
);
}
diff --git a/rust/cloud-storage/notification/src/outbound/repository.rs b/rust/cloud-storage/notification/src/outbound/repository.rs
index 676b6179b2..3847d28fa7 100644
--- a/rust/cloud-storage/notification/src/outbound/repository.rs
+++ b/rust/cloud-storage/notification/src/outbound/repository.rs
@@ -167,6 +167,10 @@ fn push_include_types_filter(builder: &mut QueryBuilder<'_, Postgres>, include_t
.iter()
.any(|t| t == "call")
.then_some("n.event_item_type = 'call'"),
+ include_types
+ .iter()
+ .any(|t| t == "github")
+ .then_some("n.notification_event_type = 'github_pr_event'"),
]
.into_iter()
.flatten()
@@ -215,6 +219,10 @@ fn push_entities_filter<'a>(builder: &mut QueryBuilder<'a, Postgres>, entity_tok
builder.push_bind(entity_tokens);
builder.push(")) OR ");
+ builder.push("(n.event_item_type = 'foreign_entity' AND n.notification_event_type = 'github_pr_event' AND 'github:' || n.event_item_id = ANY(");
+ builder.push_bind(entity_tokens);
+ builder.push(")) OR ");
+
builder.push("('message:' || COALESCE(n.metadata->>'messageId', n.metadata->>'message_id', '') = ANY(");
builder.push_bind(entity_tokens);
builder.push("))");
diff --git a/rust/cloud-storage/notification/src/outbound/repository/test.rs b/rust/cloud-storage/notification/src/outbound/repository/test.rs
index 9a4100176c..0604abd966 100644
--- a/rust/cloud-storage/notification/src/outbound/repository/test.rs
+++ b/rust/cloud-storage/notification/src/outbound/repository/test.rs
@@ -1,4 +1,7 @@
-use crate::domain::models::Notification;
+use crate::domain::models::{
+ Notification,
+ request::{NotificationEntityRef, NotificationItemType},
+};
use super::*;
@@ -17,6 +20,15 @@ impl Notification for TestNotification {
const TYPE_NAME: &'static str = "test_notification";
}
+#[derive(Debug, Clone, Serialize, Deserialize)]
+struct TestGithubNotification {
+ message: String,
+}
+
+impl Notification for TestGithubNotification {
+ const TYPE_NAME: &'static str = "github_pr_event";
+}
+
fn test_user(email: &str) -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from_email(email).unwrap()
}
@@ -467,6 +479,118 @@ async fn test_get_user_notifications_filters_type_and_entity(pool: Pool<Postgres
assert!(wrong_entity_results.is_empty());
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_get_user_notifications_filters_github_type_and_entity(pool: Pool<Postgres>) {
+ let user = test_user("[email protected]");
+ let foreign_entity_id = uuid::Uuid::new_v4().to_string();
+ let github_notification_id = uuid::Uuid::new_v4();
+
+ let github_request = SendNotificationRequestBuilder {
+ notification_entity: EntityType::ForeignEntity
+ .with_entity_string(foreign_entity_id.clone()),
+ notification: TaggedContent::new(TestGithubNotification {
+ message: "github".to_string(),
+ }),
+ sender_id: None,
+ recipient_ids: std::collections::HashSet::from([user.clone()]),
+ };
+ pool.create_notification(github_request, github_notification_id, "test_service", None)
+ .await
+ .unwrap();
+
+ let non_github_request = SendNotificationRequestBuilder {
+ notification_entity: EntityType::ForeignEntity
+ .with_entity_string(foreign_entity_id.clone()),
+ notification: TaggedContent::new(TestNotification {
+ message: "foreign entity".to_string(),
+ }),
+ sender_id: None,
+ recipient_ids: std::collections::HashSet::from([user.clone()]),
+ };
+ pool.create_notification(
+ non_github_request,
+ uuid::Uuid::new_v4(),
+ "test_service",
+ None,
+ )
+ .await
+ .unwrap();
+
+ let github_type_results: Vec<UserNotificationRow<serde_json::Value>> = pool
+ .get_user_notifications(
+ user.clone(),
+ 10,
+ Query::Sort(CreatedAt, ()),
+ NotificationListFilters {
+ done: Some(false),
+ seen: None,
+ include_types: vec![NotificationItemType::Github],
+ entities: Vec::new(),
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(github_type_results.len(), 1);
+ assert_eq!(
+ github_type_results[0].notification_id,
+ github_notification_id
+ );
+ assert_eq!(
+ github_type_results[0].notification_event_type,
+ "github_pr_event"
+ );
+ assert_eq!(
+ github_type_results[0].entity.entity_type,
+ EntityType::ForeignEntity
+ );
+ assert_eq!(
+ github_type_results[0].entity.entity_id.as_ref(),
+ foreign_entity_id.as_str()
+ );
+
+ let github_entity_results: Vec<UserNotificationRow<serde_json::Value>> = pool
+ .get_user_notifications(
+ user.clone(),
+ 10,
+ Query::Sort(CreatedAt, ()),
+ NotificationListFilters {
+ done: Some(false),
+ seen: None,
+ include_types: Vec::new(),
+ entities: vec![NotificationEntityRef {
+ entity_type: NotificationItemType::Github,
+ id: foreign_entity_id.clone(),
+ }],
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(github_entity_results.len(), 1);
+ assert_eq!(
+ github_entity_results[0].notification_id,
+ github_notification_id
+ );
+
+ let wrong_entity_results: Vec<UserNotificationRow<serde_json::Value>> = pool
+ .get_user_notifications(
+ user,
+ 10,
+ Query::Sort(CreatedAt, ()),
+ NotificationListFilters {
+ done: Some(false),
+ seen: None,
+ include_types: Vec::new(),
+ entities: vec![NotificationEntityRef {
+ entity_type: NotificationItemType::Document,
+ id: foreign_entity_id,
+ }],
+ },
+ )
+ .await
+ .unwrap();
+ assert!(wrong_entity_results.is_empty());
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("user_notifications_with_invalid"))
diff --git a/rust/cloud-storage/notification_service/src/api/swagger.rs b/rust/cloud-storage/notification_service/src/api/swagger.rs
index af4b22f8b1..aa5ca0bf79 100644
--- a/rust/cloud-storage/notification_service/src/api/swagger.rs
+++ b/rust/cloud-storage/notification_service/src/api/swagger.rs
@@ -8,7 +8,8 @@ use model::{
use model_notifications::{
ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageSendMetadata,
ChannelReplyMetadata, CommentedOnDocumentMetadata, CommonChannelMetadata, DeviceType,
- DocumentMentionMetadata, InviteToTeamMetadata, ItemSharedMetadata, NewEmailMetadata,
+ DocumentMentionMetadata, GithubPrEvent, GithubPrEventAction, GithubPrEventStatus,
+ InviteToTeamMetadata, ItemSharedMetadata, NewEmailMetadata,
RepliedToDocumentCommentThreadMetadata, UserUnsubscribe,
};
use utoipa::OpenApi;
@@ -81,6 +82,9 @@ use crate::{
DocumentMentionMetadata,
RepliedToDocumentCommentThreadMetadata,
CommentedOnDocumentMetadata,
+ GithubPrEvent,
+ GithubPrEventStatus,
+ GithubPrEventAction,
// v2 typed notifications
model_notifications::NotifEvent,
diff --git a/rust/cloud-storage/notification_service/src/api/user_notification.rs b/rust/cloud-storage/notification_service/src/api/user_notification.rs
index f39bb7922b..82190e1623 100644
--- a/rust/cloud-storage/notification_service/src/api/user_notification.rs
+++ b/rust/cloud-storage/notification_service/src/api/user_notification.rs
@@ -10,8 +10,9 @@ use model_entity::Entity;
use model_error_response::ErrorResponse;
use model_notifications::{
AiResponseMetadata, ChannelMentionMetadata, ChannelMessageSendMetadata, ChannelReplyMetadata,
- CommentedOnDocumentMetadata, DocumentMentionMetadata, MentionedInDocumentCommentMetadata,
- NewEmailMetadata, NotifEvent, RepliedToDocumentCommentThreadMetadata, TaskAssignedMetadata,
+ CommentedOnDocumentMetadata, DocumentMentionMetadata, GithubPrEvent,
+ MentionedInDocumentCommentMetadata, NewEmailMetadata, NotifEvent,
+ RepliedToDocumentCommentThreadMetadata, TaskAssignedMetadata,
};
use notification::{
domain::{models::Notification, service::NotificationReader},
@@ -31,6 +32,7 @@ pub(crate) static BLOCKABLE_NOTIFICATIONS: LazyLock<HashSet<&'static str>> = Laz
ChannelMentionMetadata::TYPE_NAME,
ChannelReplyMetadata::TYPE_NAME,
DocumentMentionMetadata::TYPE_NAME,
+ GithubPrEvent::TYPE_NAME,
TaskAssignedMetadata::TYPE_NAME,
MentionedInDocumentCommentMetadata::TYPE_NAME,
RepliedToDocumentCommentThreadMetadata::TYPE_NAME,
diff --git a/rust/cloud-storage/notification_service/src/api/user_notification/test.rs b/rust/cloud-storage/notification_service/src/api/user_notification/test.rs
index cfd99cdaf4..fbd6ef5d1f 100644
--- a/rust/cloud-storage/notification_service/src/api/user_notification/test.rs
+++ b/rust/cloud-storage/notification_service/src/api/user_notification/test.rs
@@ -3,7 +3,7 @@ use chrono::Utc;
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::EntityType;
-use model_notifications::ChannelMentionMetadata;
+use model_notifications::{ChannelMentionMetadata, GithubPrEventAction, GithubPrEventStatus};
use notification::domain::models::UserNotificationRow;
/// Build a [`UserNotificationRow<serde_json::Value>`] with the given event type
@@ -165,6 +165,47 @@ fn to_typed_row_task_assigned() {
));
}
+#[test]
+fn to_typed_row_github_pr_event() {
+ let foreign_entity_id = uuid::Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000")
+ .expect("valid foreign entity id");
+ let metadata = serde_json::json!({
+ "foreignEntityId": foreign_entity_id,
+ "githubKey": "macro/repo/pull/42",
+ "owner": "macro",
+ "repo": "repo",
+ "number": 42,
+ "url": "https://github.com/macro/repo/pull/42",
+ "displayName": "macro/repo#42",
+ "title": "Add GitHub PR notifications",
+ "status": "merged",
+ "action": "closed",
+ "previousStatus": "open",
+ "senderGithubLogin": "octocat",
+ "senderGithubUserId": "12345",
+ "senderGithubAvatarUrl": "https://avatars.githubusercontent.com/u/12345?v=4",
+ "headBranch": "feature/github-pr-notifications",
+ "baseBranch": "main",
+ "mergedAt": "2026-06-01T16:00:00Z"
+ });
+
+ let mut row = make_row("github_pr_event", metadata);
+ row.entity = EntityType::ForeignEntity.with_entity_string(foreign_entity_id.to_string());
+
+ let typed = to_typed_row(row).expect("should deserialize github_pr_event");
+
+ match typed.notification_metadata {
+ NotifEvent::GithubPrEvent(event) => {
+ assert_eq!(event.foreign_entity_id, foreign_entity_id);
+ assert_eq!(event.github_key, "macro/repo/pull/42");
+ assert_eq!(event.status, GithubPrEventStatus::Merged);
+ assert_eq!(event.action, GithubPrEventAction::Closed);
+ assert_eq!(event.previous_status, Some(GithubPrEventStatus::Open));
+ }
+ other => panic!("expected GithubPrEvent variant, got {other:?}"),
+ }
+}
+
#[test]
fn to_typed_row_unknown_event_type_fails() {
let metadata = serde_json::json!({"foo": "bar"});