Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(soup): display github pr entities (#3792)
dev-rb33e7a5668ce5
diff --git a/js/app/packages/app/component/PreviewPanel.tsx b/js/app/packages/app/component/PreviewPanel.tsxindex cee334fbe3..51a898732b 100644--- a/js/app/packages/app/component/PreviewPanel.tsx+++ b/js/app/packages/app/component/PreviewPanel.tsx@@ -78,6 +78,10 @@ const PreviewPanelContent: Component<NonNullableFields<PreviewPanel>> = (} else if (props.selectedEntity.type === 'channel_message') {blockType = 'channel';blockId = props.selectedEntity.channelId;+ } else if (props.selectedEntity.type === 'foreign') {+ // TODO(dev-rb/github): Preview GitHub PRs with /pr.+ blockType = 'unknown';+ blockId = props.selectedEntity.id;} else {blockType = props.selectedEntity.type;blockId = props.selectedEntity.id;diff --git a/js/app/packages/app/component/app-sidebar/soup-filter-presets.ts b/js/app/packages/app/component/app-sidebar/soup-filter-presets.tsindex 042ac7112f..f26b5fb011 100644--- a/js/app/packages/app/component/app-sidebar/soup-filter-presets.ts+++ b/js/app/packages/app/component/app-sidebar/soup-filter-presets.ts@@ -5,6 +5,7 @@ import {type Query,} from '@app/component/next-soup/filters/filter-store';import type { ListView } from '@app/constants/list-views';+import { ENABLE_SUPPORTED_SOUP_FOREIGN_ENTITIES_OVERRIDE } from '@core/constant/featureFlags';import { PROPERTY_OPTION_IDS, SYSTEM_PROPERTY_IDS } from '@property/constants';import { startOfDay, subWeeks } from 'date-fns';@@ -91,6 +92,8 @@ export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {channelId: [NIL_UUID],chatId: [NIL_UUID],folderId: [NIL_UUID],+ foreignEntityRecordId:+ ENABLE_SUPPORTED_SOUP_FOREIGN_ENTITIES_OVERRIDE ? [NIL_UUID] : [],},emailView: 'all',},diff --git a/js/app/packages/app/component/command/CommandMenu.tsx b/js/app/packages/app/component/command/CommandMenu.tsxindex 73a26e3aaf..71bb5ccc3b 100644--- a/js/app/packages/app/component/command/CommandMenu.tsx+++ b/js/app/packages/app/component/command/CommandMenu.tsx@@ -8,7 +8,8 @@ import { getActiveCommandsFromScope } from '@core/hotkey/getCommands';import type { RegisterHotkeyReturn } from '@core/hotkey/types';import { runCommand } from '@core/hotkey/utils';import { debouncedDependent } from '@core/util/debounce';-import { type EntityData, InlineEntity } from '@entity';+import { openExternalUrl } from '@core/util/url';+import { type EntityData, InlineEntity, isGithubPrEntity } from '@entity';import Macro from '@icon/macro-logo.svg';import ArrowLeft from '@phosphor/arrow-left.svg';import { cn, Dialog, Hotkey, Panel } from '@ui';@@ -209,15 +210,25 @@ export function CommandMenuInner(props: {// Handle entity items (documents, channels, chats, etc.)if (isEntityItem(item)) {- const blockName = itemToBlockName(item.data);- if (blockName) {- openWithSplit(- { type: blockName, id: item.id },- {- referredFrom: 'kommand-menu',- preferNewSplit: openInNewSplit,- }- );+ // TODO(dev-rb/github): Route GitHub PRs to /pr.+ if (isGithubPrEntity(item.data)) {+ openExternalUrl(item.data.metadata.url);+ CommandState.close();+ CommandState.setQuery('');+ return;+ }++ if (item.data.type !== 'foreign') {+ const blockName = itemToBlockName(item.data);+ if (blockName) {+ openWithSplit(+ { type: blockName, id: item.id },+ {+ referredFrom: 'kommand-menu',+ preferNewSplit: openInNewSplit,+ }+ );+ }}CommandState.close();CommandState.setQuery('');diff --git a/js/app/packages/app/component/mobile/MobileSearch.tsx b/js/app/packages/app/component/mobile/MobileSearch.tsxindex 9fa4e27179..e13a7fc282 100644--- a/js/app/packages/app/component/mobile/MobileSearch.tsx+++ b/js/app/packages/app/component/mobile/MobileSearch.tsx@@ -9,7 +9,13 @@ import { runCommand } from '@core/hotkey/utils';import { virtualKeyboardVisible } from '@core/mobile/virtualKeyboard';import { debouncedDependent } from '@core/util/debounce';import { windowSearchMatch } from '@core/util/searchHighlight';-import { Entity, type EntityData, type WithSearch } from '@entity';+import { openExternalUrl } from '@core/util/url';+import {+ Entity,+ type EntityData,+ isGithubPrEntity,+ type WithSearch,+} from '@entity';import { SearchContent } from '@entity/extractors-search/search-content';import { Dialog } from '@kobalte/core/dialog';import ArrowLeft from '@phosphor/arrow-left.svg';@@ -109,15 +115,25 @@ function MobileSearchInner() {// Handle entity items (documents, channels, chats, etc.)if (isEntityItem(item)) {- const blockName = itemToBlockName(item.data);- if (blockName) {- openWithSplit(- { type: blockName, id: item.id },- {- referredFrom: 'kommand-menu',- preferNewSplit: openInNewSplit,- }- );+ // TODO(dev-rb/github): Route GitHub PRs to /pr.+ if (isGithubPrEntity(item.data)) {+ openExternalUrl(item.data.metadata.url);+ SearchState.close();+ SearchState.setQuery('');+ return;+ }++ if (item.data.type !== 'foreign') {+ const blockName = itemToBlockName(item.data);+ if (blockName) {+ openWithSplit(+ { type: blockName, id: item.id },+ {+ referredFrom: 'kommand-menu',+ preferNewSplit: openInNewSplit,+ }+ );+ }}SearchState.close();SearchState.setQuery('');diff --git a/js/app/packages/app/component/next-soup/actions/make-copy-action.ts b/js/app/packages/app/component/next-soup/actions/make-copy-action.tsindex 3aa1887753..c86ef298b1 100644--- a/js/app/packages/app/component/next-soup/actions/make-copy-action.ts+++ b/js/app/packages/app/component/next-soup/actions/make-copy-action.ts@@ -10,7 +10,8 @@ export const makeCopyAction = () => {return (entity.type !== 'channel' &&entity.type !== 'email' &&- entity.type !== 'channel_message'+ entity.type !== 'channel_message' &&+ entity.type !== 'foreign');};diff --git a/js/app/packages/app/component/next-soup/actions/make-copy-link-action.ts b/js/app/packages/app/component/next-soup/actions/make-copy-link-action.tsindex d1c79980a8..77276cf345 100644--- a/js/app/packages/app/component/next-soup/actions/make-copy-link-action.ts+++ b/js/app/packages/app/component/next-soup/actions/make-copy-link-action.ts@@ -2,7 +2,7 @@ import { getChannelParams } from '@block-channel/utils/link';import { toast } from '@core/component/Toast/Toast';import { fileTypeToBlockName } from '@core/constant/allBlocks';import { buildSimpleEntityUrl } from '@core/util/url';-import type { EntityData } from '@entity';+import { type EntityData, isGithubPrEntity } from '@entity';import type { SoupState } from '../create-soup-state';/**@@ -33,6 +33,9 @@ const getEntityUrlParams = (};const getEntityUrl = (entity: EntityData): string => {+ // TODO(dev-rb/github): Return the Macro /pr/:id URL.+ if (isGithubPrEntity(entity)) return entity.metadata.url;+return buildSimpleEntityUrl({type: getEntityUrlType(entity),diff --git a/js/app/packages/app/component/next-soup/actions/make-move-to-project-action.ts b/js/app/packages/app/component/next-soup/actions/make-move-to-project-action.tsindex 3a98af581b..ec6b941758 100644--- a/js/app/packages/app/component/next-soup/actions/make-move-to-project-action.ts+++ b/js/app/packages/app/component/next-soup/actions/make-move-to-project-action.ts@@ -7,7 +7,11 @@ import { restoreSoupFocus } from '../utils';export const makeMoveToProjectAction = () => {const canExecute = (entity: EntityData): boolean => {- return entity.type !== 'channel' && entity.type !== 'channel_message';+ return (+ entity.type !== 'channel' &&+ entity.type !== 'channel_message' &&+ entity.type !== 'foreign'+ );};const execute = async (entities: EntityData[]) => {diff --git a/js/app/packages/app/component/next-soup/actions/make-rename-action.ts b/js/app/packages/app/component/next-soup/actions/make-rename-action.tsindex 396fbf1c12..6c9e5c6a39 100644--- a/js/app/packages/app/component/next-soup/actions/make-rename-action.ts+++ b/js/app/packages/app/component/next-soup/actions/make-rename-action.ts@@ -15,6 +15,7 @@ export const makeRenameAction = (options: MakeRenameOptions) => {const canExecute = (entity: EntityData): boolean => {if (entity.type === 'email') return false;if (entity.type === 'channel_message') return false;+ if (entity.type === 'foreign') return false;if (entity.type === 'channel') {if (entity.channelType === 'direct_message') return false;diff --git a/js/app/packages/app/component/next-soup/filters/inbox-filters.ts b/js/app/packages/app/component/next-soup/filters/inbox-filters.tsindex 96bc6d832c..bebe8d09ea 100644--- a/js/app/packages/app/component/next-soup/filters/inbox-filters.ts+++ b/js/app/packages/app/component/next-soup/filters/inbox-filters.ts@@ -121,6 +121,8 @@ export function signalFilter(entity: EntityData): boolean {case 'automation':// Automations only show in the Agents > Scheduled tab, not Inbox.return false;+ case 'foreign':+ return false;}}diff --git a/js/app/packages/app/component/next-soup/filters/predicates.ts b/js/app/packages/app/component/next-soup/filters/predicates.tsindex 2ffc0bf0cf..9073044812 100644--- a/js/app/packages/app/component/next-soup/filters/predicates.ts+++ b/js/app/packages/app/component/next-soup/filters/predicates.ts@@ -1,25 +1,16 @@-import type { Entity } from '@core/types';import {type EntityData,getTaskAssigneeIds,getTaskStatusOptionId,isTaskEntity,type TaskEntityWithProperties,+ toNotificationEntity,type WithNotification,} from '@entity';import { getTaskPriorityOptionId } from '@entity/utils/task-properties';import { compositeEntity, type NotificationSource } from '@notifications';import { PROPERTY_OPTION_IDS } from '@property/constants';-// Channel messages don't have their own notifications — they share the parent-// channel's. Resolve to the channel entity for notification lookups.-function notificationLookupEntity(entity: EntityData): Entity {- if (entity.type === 'channel_message') {- return { type: 'channel', id: entity.channelId };- }- return entity;-}-/*** Unread filter - entity has unread content.*@@ -32,9 +23,10 @@ export function unreadFilter(notificationSource: NotificationSource) {if (entity.type === 'email') {return !entity.isRead;}+const notifications =notificationSource.notificationsByEntity()[- compositeEntity(notificationLookupEntity(entity))+ compositeEntity(toNotificationEntity(entity))];return notifications?.some((n) => !n.viewed_at) ?? false;@@ -54,7 +46,7 @@ export function notDoneFilter(notificationSource: NotificationSource) {const notifications =notificationSource.notificationsByEntity()[- compositeEntity(notificationLookupEntity(entity))+ compositeEntity(toNotificationEntity(entity))];return notifications?.some(({ done }) => !done);diff --git a/js/app/packages/app/component/next-soup/soup-view/create-soup-entity-actions.ts b/js/app/packages/app/component/next-soup/soup-view/create-soup-entity-actions.tsindex 33057745a8..ea85ed2e26 100644--- a/js/app/packages/app/component/next-soup/soup-view/create-soup-entity-actions.ts+++ b/js/app/packages/app/component/next-soup/soup-view/create-soup-entity-actions.ts@@ -116,6 +116,8 @@ export function createSoupEntityActions(): {const entity = entities[0];const splitManager = globalSplitManager();if (!splitManager) return false;+ // TODO(dev-rb/github): Allow GitHub PRs once they map to /pr.+ if (entity.type === 'foreign') return false;const contentId =entity.type === 'channel_message' ? entity.channelId : entity.id;const contentType = itemToBlockName(entity);@@ -162,7 +164,7 @@ export function createSoupEntityActions(): {await blockHandle?.goToLocationFromParams(getChannelParams(entity.messageId, entity.threadId));- } else {+ } else if (entity.type !== 'foreign') {splitManager.createNewSplit({content: {type: entity.type,diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsxindex 5c90f357e4..e18ac5269b 100644--- a/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx@@ -22,13 +22,19 @@ import { createSearchState } from '@app/component/next-soup/soup-view/create-seaimport { deduplicateEntities } from '@app/component/next-soup/utils';import { useEntryState } from '@app/component/split-layout/entry-state';import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';-import { ENABLE_FEATURED_SEARCH_RESULTS } from '@core/constant/featureFlags';+import { useFeatureFlag } from '@app/lib/analytics/posthog';+import {+ ENABLE_FEATURED_SEARCH_RESULTS,+ ENABLE_SUPPORTED_SOUP_FOREIGN_ENTITIES_FLAG,+ ENABLE_SUPPORTED_SOUP_FOREIGN_ENTITIES_OVERRIDE,+} from '@core/constant/featureFlags';import { useUserId } from '@core/context/user';import { throwOnErr } from '@core/util/result';import {type EntityData,getPropertyOptionLabel,isWithNotification,+ toNotificationEntity,} from '@entity';import { useNotificationsForEntity } from '@notifications';import { useQueryClient } from '@queries/client';@@ -295,6 +301,12 @@ export const SoupViewContextProvider: FlowComponent<const notificationSource = useGlobalNotificationSource();const userId = useUserId();+ const showSupportedForeignEntitiesFF = useFeatureFlag(+ ENABLE_SUPPORTED_SOUP_FOREIGN_ENTITIES_FLAG,+ {+ enabledOverride: ENABLE_SUPPORTED_SOUP_FOREIGN_ENTITIES_OVERRIDE,+ }+ );// Create filter context for context-aware filter predicatesconst getFilterContext = (): FilterContext => ({@@ -306,7 +318,10 @@ export const SoupViewContextProvider: FlowComponent<const attachNotifications = (entity: EntityData) => {return {...entity,- notifications: useNotificationsForEntity(notificationSource, entity),+ notifications: useNotificationsForEntity(+ notificationSource,+ toNotificationEntity(entity)+ ),};};@@ -318,6 +333,7 @@ export const SoupViewContextProvider: FlowComponent<}),() => ({enabled: !search.isSearching(),+ showSupportedForeignEntities: showSupportedForeignEntitiesFF().enabled,}));@@ -485,7 +501,11 @@ export const SoupViewContextProvider: FlowComponent<const allItems = pages.flatMap((p) => p.items);return mapSoupPageToEntityList({ items: allItems, next_cursor: null },- { instructionsIdQuery }+ {+ instructionsIdQuery,+ showSupportedForeignEntities:+ showSupportedForeignEntitiesFF().enabled,+ }).map((e) => attachNotifications(e)) as SoupEntity[];},enabled: true,diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view.tsxindex 79c85a1908..41eb92670f 100644--- a/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx@@ -297,6 +297,16 @@ const useSoupNotificationInvalidators = () => {}});++ createEffectOnEntityTypeNotification(+ notificationSource,+ 'foreign_entity',+ (notification) => {+ refetchSoupEntity(notification.entity_id, 'foreignEntity');+ invalidateSoupEntity(notification.entity_id);+ invalidateEntityNotifications(notification.entity_id);+ }+ );};const listStateCache = new Map<diff --git a/js/app/packages/app/component/next-soup/utils.ts b/js/app/packages/app/component/next-soup/utils.tsindex 346729fba7..47d6b47060 100644--- a/js/app/packages/app/component/next-soup/utils.ts+++ b/js/app/packages/app/component/next-soup/utils.ts@@ -15,12 +15,15 @@ import type { BlockOrchestrator } from '@core/orchestrator';import type { DateValue } from '@core/util/date';import { throwOnErr } from '@core/util/result';import { waitForFrames } from '@core/util/sleep';+import { openExternalUrl } from '@core/util/url';import {type EntityData,getSnippetHit,+ isGithubPrEntity,isSearchEntity,isSnippetEntity,type SearchLocation,+ toNotificationEntity,type WithSearch,} from '@entity';import { queryKeys } from '@macro-entity';@@ -331,6 +334,13 @@ export const openEntityInSplitFromUnifiedList = async (return;}+ // TODO(dev-rb/github): Route GitHub PRs to /pr.+ if (isGithubPrEntity(entity)) {+ openExternalUrl(entity.metadata.url);+ return;+ }+ if (entity.type === 'foreign') return;+const blockOrchestrator = splitManager.getOrchestrator();const content = getEntitySplitContent(entity);@@ -372,6 +382,7 @@ export const openEntityInSplitFromUnifiedList = async (}};+// TODO(dev-rb/github): Map GitHub PRs to { type: 'pr', id }.function getEntitySplitContent(entity: EntityData) {return match(entity).with({ type: 'document' }, (entity) => {@@ -383,6 +394,9 @@ function getEntitySplitContent(entity: EntityData) {.with({ type: 'channel_message' }, (entity) => {return { type: 'channel' as const, id: entity.channelId };})+ .with({ type: 'foreign' }, (entity) => {+ return { type: 'unknown' as const, id: entity.id };+ }).otherwise((entity) => {return { type: entity.type, id: entity.id };});@@ -637,11 +651,13 @@ export function resolveMarkEntitiesDoneVariables(args: {}): { emailIds: string[]; notificationIds: string[] } {const { entities, notificationSource } = args;const emailIds = entities.filter((e) => e.type === 'email').map((e) => e.id);- const notificationIds = entities.flatMap((entity) =>- (- notificationSource.notificationsByEntity()[compositeEntity(entity)] ?? []- ).map((n) => n.id)- );+ const notificationIds = entities.flatMap((entity) => {+ return (+ notificationSource.notificationsByEntity()[+ compositeEntity(toNotificationEntity(entity))+ ] ?? []+ ).map((n) => n.id);+ });return { emailIds, notificationIds };}diff --git a/js/app/packages/block-canvas/component/CanvasController.tsx b/js/app/packages/block-canvas/component/CanvasController.tsxindex 2f32be132f..61f3851343 100644--- a/js/app/packages/block-canvas/component/CanvasController.tsx+++ b/js/app/packages/block-canvas/component/CanvasController.tsx@@ -863,8 +863,8 @@ export function CanvasController(props: ParentProps) {const entityType = event.draggable.data.type;// TODO: add channel message supportif (entityType === 'channel_message') return;- // Automation entities aren't yet renderable as canvas mentions.- if (entityType === 'automation') return;+ // Automation and foreign entities aren't yet renderable as canvas mentions.+ if (entityType === 'automation' || entityType === 'foreign') return;// Track document mention and get UUIDlet mentionUuid: string | undefined;diff --git a/js/app/packages/block-md/component/MarkdownEditor.tsx b/js/app/packages/block-md/component/MarkdownEditor.tsxindex e0978f0830..ed420c8e3c 100644--- a/js/app/packages/block-md/component/MarkdownEditor.tsx+++ b/js/app/packages/block-md/component/MarkdownEditor.tsx@@ -323,6 +323,7 @@ export function MarkdownEditor(props: {clientY: currentPos.y,};const item = event.draggable.data;+ if (item.type === 'foreign') return;const blockName = itemToBlockName(item);if (!blockName) return;let id = event.draggable.data.id as string;diff --git a/js/app/packages/channel/Attachments/attachment-utils.ts b/js/app/packages/channel/Attachments/attachment-utils.tsindex b23effd545..e2ae540791 100644--- a/js/app/packages/channel/Attachments/attachment-utils.ts+++ b/js/app/packages/channel/Attachments/attachment-utils.ts@@ -110,5 +110,8 @@ export function getEntityClickContent(entity: EntityData): SplitContent {type: 'automation' as const,id: e.id,}))+ .with({ type: 'foreign' }, () => {+ throw new Error('foreign entities do not support channel attachments');+ }).exhaustive();}diff --git a/js/app/packages/core/component/AI/hook/useEntityDropAttachment.ts b/js/app/packages/core/component/AI/hook/useEntityDropAttachment.tsindex 71b222e694..f89a6b3e84 100644--- a/js/app/packages/core/component/AI/hook/useEntityDropAttachment.ts+++ b/js/app/packages/core/component/AI/hook/useEntityDropAttachment.ts@@ -93,6 +93,7 @@ export function useEntityDropAttachment(.with('chat', () => undefined).with('call', () => undefined).with('automation', () => undefined)+ .with('foreign', () => undefined).exhaustive();if (attachment) {diff --git a/js/app/packages/core/component/EntityIcon.tsx b/js/app/packages/core/component/EntityIcon.tsxindex d2ddd4f1ed..4db72fea1f 100644--- a/js/app/packages/core/component/EntityIcon.tsx+++ b/js/app/packages/core/component/EntityIcon.tsx@@ -12,6 +12,7 @@ import type {EmailEntity,EntityData,} from '@entity';+import GithubIcon from '@icon/mcp-github.svg';import WideBook from '@icon/wide-book.svg';import WideCalendar from '@icon/wide-calendar.svg';import PhoneCall from '@icon/wide-call.svg';@@ -79,6 +80,7 @@ export type EntityWithValidIcon =| 'sharedProject'| 'emailRead'| 'emailInvite'+ | 'githubPullRequest'| 'archive'| 'files'| 'html';@@ -252,6 +254,12 @@ export const ENTITY_ICON_CONFIGS: Record<EntityWithValidIcon, IconConfig> = {background: 'bg-calendar/20',prettyName: 'Calendar Invite',},+ githubPullRequest: {+ icon: GithubIcon,+ foreground: 'text-default',+ background: 'bg-default/20',+ prettyName: 'GitHub Pull Request',+ },task: {icon: Check,foreground: 'text-task',@@ -319,6 +327,7 @@ const WIDE_ICONS: Record<EntityWithValidIcon, Component> = {default: WideUnknown,emailRead: WideEmail,emailInvite: WideCalendar,+ githubPullRequest: GithubIcon,task: WideTask,automation: Robot,};diff --git a/js/app/packages/core/component/FileList/itemOperations.ts b/js/app/packages/core/component/FileList/itemOperations.tsindex c1ef38b7d2..7e01b24e95 100644--- a/js/app/packages/core/component/FileList/itemOperations.ts+++ b/js/app/packages/core/component/FileList/itemOperations.ts@@ -191,7 +191,8 @@ export async function deleteItem(args: {itemType === 'email' ||itemType === 'channel_message' ||itemType === 'automation' ||- itemType === 'call'+ itemType === 'call' ||+ itemType === 'foreign')return false;diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.tsindex dd477636b5..aa335aeb3b 100644--- a/js/app/packages/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts@@ -254,6 +254,9 @@ const getDocumentMentionItemType = (.with('channel_message', () => 'channel').with('automation', () => 'automation').with('call', () => 'call')+ .with('foreign', () => {+ throw new Error('foreign entities cannot be document mentions');+ }).exhaustive();};diff --git a/js/app/packages/core/constant/featureFlags.ts b/js/app/packages/core/constant/featureFlags.tsindex 8103812a52..34561284a3 100644--- a/js/app/packages/core/constant/featureFlags.ts+++ b/js/app/packages/core/constant/featureFlags.ts@@ -368,6 +368,12 @@ export const ENABLE_SOUP_GROUP_BY_OVERRIDE = DEV_MODE_ENV ? true : undefined;export const ENABLE_TASK_DUPLICATES_FLAG = 'enable-task-duplicates';export const ENABLE_TASK_DUPLICATES_OVERRIDE = DEV_MODE_ENV ? true : undefined;+export const ENABLE_SUPPORTED_SOUP_FOREIGN_ENTITIES_FLAG =+ 'enable-supported-soup-foreign-entities';+export const ENABLE_SUPPORTED_SOUP_FOREIGN_ENTITIES_OVERRIDE = DEV_MODE_ENV+ ? true+ : undefined;+export const DISABLE_AUTO_UPDATE_UI_FLAG = 'disable-auto-update-ui';export const ENABLE_AUTO_UPDATE_UI_OVERRIDE = getFeatureFlagOverride('ENABLE_AUTO_UPDATE_UI'diff --git a/js/app/packages/core/internal/trackBlockOpened.ts b/js/app/packages/core/internal/trackBlockOpened.tsindex b52326f201..2b6fe4e248 100644--- a/js/app/packages/core/internal/trackBlockOpened.ts+++ b/js/app/packages/core/internal/trackBlockOpened.ts@@ -19,7 +19,7 @@ function isSoupEntityTag(itemType: ItemType): itemType is ItemType & SoupEntityTag {return match(itemType)- .with('email', 'channel_message', 'automation', () => false)+ .with('email', 'channel_message', 'automation', 'foreign', () => false).with('document', 'chat', 'project', 'channel', 'call', () => true).exhaustive();}diff --git a/js/app/packages/entity/src/composed/list-entity/foreign.tsx b/js/app/packages/entity/src/composed/list-entity/foreign.tsxnew file mode 100644index 0000000000..fda6223f49--- /dev/null+++ b/js/app/packages/entity/src/composed/list-entity/foreign.tsx@@ -0,0 +1,453 @@+import { Popover } from '@kobalte/core/popover';+import ArrowSquareOut from '@phosphor/arrow-square-out.svg';+import ChatCircle from '@phosphor/chat-circle.svg';+import Check from '@phosphor/check.svg';+import CircleDashed from '@phosphor/circle-dashed.svg';+import MinusCircle from '@phosphor/minus-circle.svg';+import X from '@phosphor/x.svg';+import CheckCircle from '@phosphor-icons/core/assets/fill/check-circle-fill.svg?component-solid';+import XCircle from '@phosphor-icons/core/assets/fill/x-circle-fill.svg?component-solid';+import { Button, cn, Layer, Surface } from '@ui';+import {+ createSignal,+ For,+ type JSX,+ onCleanup,+ onMount,+ Show,+} from 'solid-js';+import { Dynamic } from 'solid-js/web';+import type { GithubPullRequestEntity } from '../../types/entity';++type PillProps = {+ children: JSX.Element;+ class?: string;+};++function Pill(props: PillProps) {+ return (+ <span+ class={cn(+ 'min-w-0 rounded-full inline-flex items-center gap-1 px-1.5 py-1 leading-tight text-xs font-medium ring ring-edge ring-inset bg-surface/50',+ props.class+ )}+ >+ {props.children}+ </span>+ );+}++const numberFormatter = new Intl.NumberFormat();++function checkFailed(conclusion: string | null | undefined): boolean {+ return (+ conclusion === 'failure' ||+ conclusion === 'timed_out' ||+ conclusion === 'cancelled' ||+ conclusion === 'action_required'+ );+}++type CheckCounts = {+ total: number;+ successful: number;+ failed: number;+ skipped: number;+ pending: number;+};++function checkCounts(entity: GithubPullRequestEntity): CheckCounts {+ let successful = 0;+ let failed = 0;+ let skipped = 0;+ let pending = 0;++ for (const check of entity.metadata.checks) {+ if (check.conclusion === 'skipped') {+ skipped += 1;+ continue;+ }++ if (checkFailed(check.conclusion)) {+ failed += 1;+ }++ if (check.conclusion === 'success') {+ successful += 1;+ }++ if (check.status !== 'completed' || check.conclusion == null) {+ pending += 1;+ }+ }++ return {+ total: entity.metadata.checks.length - skipped,+ successful,+ failed,+ skipped,+ pending,+ };+}++function checkOverviewTitle(counts: CheckCounts) {+ if (counts.total === 0) return 'No checks';++ if (counts.failed > 0) {+ return counts.failed === counts.total+ ? 'All checks failed'+ : 'Some checks failed';+ }+ if (counts.pending > 0) return 'Checks pending';+ if (counts.successful === counts.total) return 'All checks succeeded';+ return 'Checks completed';+}++function checkOverviewTitleClass(state: CheckVisualState): string {+ switch (state) {+ case 'success':+ return 'text-success';+ case 'failure':+ return 'text-failure';+ case 'pending':+ return 'text-alert-ink';+ default:+ return 'text-ink';+ }+}++function showCheckCountSummary(counts: CheckCounts) {+ return counts.failed > 0 || counts.pending > 0;+}++const CHECK_RUN_STATE_LABELS: Record<string, string> = {+ action_required: 'Action required',+ cancelled: 'Cancelled',+ completed: 'Completed',+ failure: 'Failed',+ in_progress: 'In progress',+ neutral: 'Neutral',+ pending: 'Pending',+ queued: 'Queued',+ requested: 'Requested',+ skipped: 'Skipped',+ stale: 'Stale',+ startup_failure: 'Startup failure',+ success: 'Success',+ timed_out: 'Timed out',+ waiting: 'Waiting',+};++type CheckVisualState = 'success' | 'failure' | 'pending' | 'skipped' | 'none';++function checkState(entity: GithubPullRequestEntity): CheckVisualState {+ const counts = checkCounts(entity);+ if (counts.total === 0) return 'none';+ if (counts.failed > 0) return 'failure';+ if (counts.pending > 0) return 'pending';+ if (counts.successful === counts.total) return 'success';+ return 'pending';+}++function checkRunState(+ check: GithubPullRequestEntity['metadata']['checks'][number]+): CheckVisualState {+ if (check.conclusion === 'skipped') return 'skipped';++ if (checkFailed(check.conclusion)) return 'failure';++ if (check.status !== 'completed' || check.conclusion == null) {+ return 'pending';+ }++ if (check.conclusion === 'success') return 'success';++ return 'none';+}++function checkStatusText(+ check: GithubPullRequestEntity['metadata']['checks'][number]+) {+ const state = check.conclusion ?? check.status;+ return CHECK_RUN_STATE_LABELS[state] ?? state.replaceAll('_', ' ');+}++function formatDuration(milliseconds: number): string | undefined {+ if (!Number.isFinite(milliseconds) || milliseconds < 0) return undefined;++ const totalSeconds = Math.max(0, Math.floor(milliseconds / 1000));+ const hours = Math.floor(totalSeconds / 3600);+ const minutes = Math.floor((totalSeconds % 3600) / 60);+ const seconds = totalSeconds % 60;++ if (hours > 0) return `${hours}h ${minutes}m`;++ if (minutes > 0) return `${minutes}m ${seconds}s`;++ return `${seconds}s`;+}++function checkDurationText(+ check: GithubPullRequestEntity['metadata']['checks'][number],+ now: number+): string | undefined {+ if (check.conclusion === 'skipped' || !check.startedAt) return undefined;++ const started = Date.parse(check.startedAt);+ if (!Number.isFinite(started)) return undefined;++ if (check.status === 'completed') {+ if (!check.completedAt) return undefined;++ const completed = Date.parse(check.completedAt);+ if (!Number.isFinite(completed)) return undefined;++ return formatDuration(completed - started);+ }++ return formatDuration(now - started);+}++function CheckStateIcon(props: {+ state: CheckVisualState;+ circle?: boolean;+ class?: string;+}) {+ return (+ <span+ class={cn(+ 'relative inline-flex shrink-0 items-center justify-center',+ props.class+ )}+ >+ <Show when={props.state === 'success'}>+ <Show+ when={props.circle}+ fallback={<Check class="size-3 text-success" />}+ >+ <CheckCircle class="size-5 text-success" />+ </Show>+ </Show>+ <Show when={props.state === 'failure'}>+ <Show when={props.circle} fallback={<X class="size-3 text-failure" />}>+ <XCircle class="size-5 text-failure" />+ </Show>+ </Show>+ <Show when={props.state === 'pending'}>+ <div class="relative size-full inline-flex items-center justify-center">+ <span+ class={cn(+ 'size-4 rounded-full',+ props.circle && [+ 'size-5',+ 'animate-spin',+ 'bg-[conic-gradient(from_0deg,var(--color-alert-ink)_0deg,var(--color-alert-ink)_60deg,rgb(from_var(--color-alert-ink)_r_g_b/0.2)_120deg,transparent_260deg,transparent_360deg)]',+ '[mask:radial-gradient(farthest-side,transparent_calc(100%-1.5px),#000_calc(100%-1.5px))]',+ ]+ )}+ />++ <span+ class={cn(+ 'absolute rounded-full bg-alert-ink',+ props.circle ? 'size-2' : 'size-1.5'+ )}+ />+ </div>+ </Show>+ <Show when={props.state === 'skipped'}>+ <MinusCircle class="size-5 text-ink-extra-muted/50" />+ </Show>+ <Show when={props.state === 'none'}>+ <div class="relative size-4 inline-flex items-center justify-center">+ <span class="size-1.5 rounded-full bg-ink-muted/40" />+ </div>+ </Show>+ </span>+ );+}++function GithubPullRequestChecksPopover(props: {+ entity: GithubPullRequestEntity;+}) {+ const checks = () => props.entity.metadata.checks;+ const counts = () => checkCounts(props.entity);+ const [now, setNow] = createSignal(Date.now());++ onMount(() => {+ const interval = setInterval(() => setNow(Date.now()), 1000);+ onCleanup(() => clearInterval(interval));+ });++ return (+ <div class="w-full flex flex-col gap-0.5 text-left">+ <div class="flex items-start gap-2 py-2 pl-4 border-b border-b-edge">+ <CheckStateIcon+ state={checkState(props.entity)}+ class="mt-1 [&_svg]:size-4"+ />+ <div class="flex min-w-0 flex-col">+ <div+ class={cn(+ 'text-base font-semibold',+ checkOverviewTitleClass(checkState(props.entity))+ )}+ >+ {checkOverviewTitle(counts())}+ </div>+ <Show when={showCheckCountSummary(counts())}>+ <div class="flex items-center gap-2 text-xs text-ink-extra-muted tabular-nums">+ <span>{counts().successful} succeeded</span>+ <span>{counts().failed} failed</span>+ <span>{counts().skipped} skipped</span>+ </div>+ </Show>+ </div>+ </div>+ <div class="max-h-56 p-2 overflow-y-auto">+ <Show+ when={checks().length > 0}+ fallback={+ <div class="flex flex-col items-center gap-2 px-4 py-6 text-center">+ <CircleDashed class="size-6 text-ink-extra-muted" />+ <div class="flex flex-col gap-1">+ <div class="text-sm font-medium text-ink">No checks yet</div>+ <div class="max-w-56 text-xs text-ink-extra-muted">+ GitHub has not reported any check runs for this pull request.+ </div>+ </div>+ </div>+ }+ >+ <div class="flex flex-col gap-0.5">+ <For each={checks()}>+ {(check) => {+ const hasUrl = () => !!check.url;+ return (+ <Dynamic+ component={hasUrl() ? 'a' : 'button'}+ type={!hasUrl() ? 'button' : undefined}+ class={cn(+ 'group/check-card relative flex h-8 w-full min-w-0 items-center gap-2 rounded-lg px-2 text-left text-xs font-medium outline-none',+ hasUrl()+ ? 'cursor-default hover:bg-active hover:ring hover:ring-edge focus-visible:bg-ink/5'+ : 'cursor-not-allowed opacity-50'+ )}+ href={check.url ? check.url : undefined}+ disabled={!hasUrl() ? true : undefined}+ >+ <CheckStateIcon+ state={checkRunState(check)}+ circle={true}+ />+ <div class="min-w-0 flex flex-1 items-center gap-2">+ <span class="truncate font-semibold text-ink">+ {check.name}+ </span>{' '}+ <span class="shrink-0 text-ink-extra-muted/70 capitalize">+ {checkStatusText(check).replaceAll('_', ' ')}+ </span>+ </div>+ <Show when={checkDurationText(check, now())}>+ {(duration) => (+ <span+ class="w-[7ch] shrink-0 text-right tabular-nums text-ink-extra-muted/70"+ title={+ check.status === 'completed'+ ? 'Duration'+ : 'Elapsed'+ }+ >+ {duration()}+ </span>+ )}+ </Show>+ <Layer depth={5}>+ <span+ class={cn(+ 'absolute right-1.5 top-1/2 z-10 inline-flex size-5 -translate-y-1/2 items-center justify-center rounded-md bg-active text-ink-extra-muted opacity-0 shadow-sm ring-1 ring-edge-muted',+ hasUrl() && 'group-hover/check-card:opacity-100'+ )}+ >+ <ArrowSquareOut class="size-3" />+ </span>+ </Layer>+ </Dynamic>+ );+ }}+ </For>+ </div>+ </Show>+ </div>+ </div>+ );+}++export function GithubPullRequestChecksIndicator(props: {+ entity: GithubPullRequestEntity;+}) {+ return (+ <Popover placement="bottom-start" gutter={4} flip={true}>+ <Popover.Trigger+ as={Button}+ type="button"+ variant="ghost"+ size="icon-sm"+ noTouchResize={true}+ class="[&_:where(svg)]:size-4 shrink-0"+ onClick={(event) => event.stopPropagation()}+ >+ <CheckStateIcon state={checkState(props.entity)} />+ </Popover.Trigger>+ <Popover.Portal>+ <Popover.Content+ class="z-tool-tip max-w-[calc(100vw-32px)] min-w-80"+ onClick={(event) => event.stopPropagation()}+ >+ <Surface+ class="flex items-stretch justify-start rounded-xl w-full"+ depth={3}+ >+ <GithubPullRequestChecksPopover entity={props.entity} />+ </Surface>+ </Popover.Content>+ </Popover.Portal>+ </Popover>+ );+}++export function GithubPullRequestPills(props: {+ entity: GithubPullRequestEntity;+}) {+ const additions = () => props.entity.metadata.additions;+ const deletions = () => props.entity.metadata.deletions;+ const largestChanges = () =>+ additions() > deletions() ? 'additions' : 'deletions';++ return (+ <>+ <Pill class="tabular-nums">+ <span+ class={cn(+ 'text-success/70 group-hover/entity:text-success font-normal',+ largestChanges() === 'additions' && 'font-semibold'+ )}+ >+ +{numberFormatter.format(additions())}+ </span>+ <span+ class={cn(+ 'text-failure/70 group-hover/entity:text-failure font-normal',+ largestChanges() === 'deletions' && 'font-semibold'+ )}+ >+ −{numberFormatter.format(deletions())}+ </span>+ </Pill>+ <Pill class="text-ink-muted tabular-nums">+ <ChatCircle class="size-3 shrink-0" />+ {numberFormatter.format(props.entity.metadata.comments.length)}+ </Pill>+ </>+ );+}diff --git a/js/app/packages/entity/src/composed/list-entity/wide-layout.tsx b/js/app/packages/entity/src/composed/list-entity/wide-layout.tsxindex 18512db074..6747ee39b2 100644--- a/js/app/packages/entity/src/composed/list-entity/wide-layout.tsx+++ b/js/app/packages/entity/src/composed/list-entity/wide-layout.tsx@@ -12,6 +12,7 @@ import {isChannelEntity,isChannelMessageEntity,isEmailEntity,+ isGithubPrEntity,isProjectContainedEntity,isTaskEntity,} from '../../types/entity';@@ -20,6 +21,10 @@ import { AutomationWideContent } from './automation';import { CallParticipants, CallWideContent } from './call';import { ChannelMessageWideContent, ChannelWideContent } from './channel';import { EmailWideContent, useOwningInbox } from './email';+import {+ GithubPullRequestChecksIndicator,+ GithubPullRequestPills,+} from './foreign';import type { LayoutProps } from './shared';export function WideLayout(props: LayoutProps) {@@ -100,6 +105,16 @@ export function WideLayout(props: LayoutProps) {<Match when={isAutomationEntity(props.entity) && props.entity}>{(entity) => <AutomationWideContent entity={entity()} />}</Match>+ <Match when={isGithubPrEntity(props.entity) && props.entity}>+ {(entity) => (+ <span class="flex min-w-0 items-center gap-1">+ <span class="min-w-0 truncate">+ <Entity.Title entity={entity()} />+ </span>+ <GithubPullRequestChecksIndicator entity={entity()} />+ </span>+ )}+ </Match><Match when={props.entity}>{(entity) => <Entity.Title entity={entity()} />}</Match>@@ -116,9 +131,16 @@ export function WideLayout(props: LayoutProps) {</span>)}</Show>- <Show when={props.isShared && !owningInbox()}>+ <Show+ when={+ props.isShared && !owningInbox() && !isGithubPrEntity(props.entity)+ }+ ><SharedBadge ownerId={props.entity.ownerId} /></Show>+ <Show when={isGithubPrEntity(props.entity) && props.entity}>+ {(entity) => <GithubPullRequestPills entity={entity()} />}+ </Show><Show when={isCallEntity(props.entity) && props.entity}>{(entity) => (<>diff --git a/js/app/packages/entity/src/extractors-property/entity-key-properties.tsx b/js/app/packages/entity/src/extractors-property/entity-key-properties.tsxindex 15ea0dd788..071a8d6dea 100644--- a/js/app/packages/entity/src/extractors-property/entity-key-properties.tsx+++ b/js/app/packages/entity/src/extractors-property/entity-key-properties.tsx@@ -45,6 +45,9 @@ function getEntityType(entity: EntityData): EntityType {.with({ type: 'automation' }, () => {throw new Error('automation entities do not support properties');})+ .with({ type: 'foreign' }, () => {+ throw new Error('foreign entities do not support properties');+ }).exhaustive();}diff --git a/js/app/packages/entity/src/extractors/entity-icon.tsx b/js/app/packages/entity/src/extractors/entity-icon.tsxindex 15b166e455..832e8d6283 100644--- a/js/app/packages/entity/src/extractors/entity-icon.tsx+++ b/js/app/packages/entity/src/extractors/entity-icon.tsx@@ -5,11 +5,18 @@ import {} from '@core/component/EntityIcon';import { UserIcon } from '@core/component/UserIcon';import { useUserId } from '@core/context/user';+import GitMerge from '@phosphor/git-merge.svg';+import GitPullRequest from '@phosphor/git-pull-request.svg';import type { StreamEvent } from '@service-connection/generated/schemas';import { Match, Show, Switch } from 'solid-js';+import { Dynamic } from 'solid-js/web';import { match } from 'ts-pattern';import { PulsingStar } from '../components/PulsingStar';-import type { ChannelEntity, EntityData } from '../types/entity';+import type {+ ChannelEntity,+ EntityData,+ GithubPullRequestEntity,+} from '../types/entity';import {isCallEntity,isChannelEntity,@@ -64,6 +71,39 @@ function DirectMessageIcon(props: {);}+function GithubPullRequestIcon(props: {+ entity: GithubPullRequestEntity;+ class?: string;+}) {+ function config() {+ const status = props.entity.metadata.status;++ switch (status) {+ case 'open':+ return {+ icon: GitPullRequest,+ iconClass: 'text-success',+ };+ case 'merged':+ return {+ icon: GitMerge,+ iconClass: 'text-note',+ };+ case 'closed':+ return {+ icon: GitPullRequest,+ iconClass: 'text-failure',+ };+ }+ }++ return (+ <div class="size-full flex">+ <Dynamic component={config().icon} class={config().iconClass} />+ </div>+ );+}+export function EntityIcon(props: EntityIconProps) {const iconType = () => {return match(props.entity)@@ -80,6 +120,11 @@ export function EntityIcon(props: EntityIconProps) {).when(isCallEntity, () => 'call').with({ type: 'automation' }, () => 'automation')+ .with(+ { type: 'foreign', foreignSource: 'github_pull_request' },+ () => 'githubPullRequest'+ )+ .with({ type: 'foreign' }, () => 'default').otherwise(() => 'default');};@@ -103,6 +148,12 @@ export function EntityIcon(props: EntityIconProps) {/>}>+ <Match when={iconType() === 'githubPullRequest'}>+ <GithubPullRequestIcon+ entity={props.entity as GithubPullRequestEntity}+ class={props.class}+ />+ </Match><Match when={isDirectMessage()}><DirectMessageIconentity={props.entity as ChannelEntity}diff --git a/js/app/packages/entity/src/extractors/entity-title.tsx b/js/app/packages/entity/src/extractors/entity-title.tsxindex 3f7f6122e4..2c5161fd55 100644--- a/js/app/packages/entity/src/extractors/entity-title.tsx+++ b/js/app/packages/entity/src/extractors/entity-title.tsx@@ -2,13 +2,13 @@ import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/Simport { unifiedListMarkdownTheme } from '@core/component/LexicalMarkdown/theme';import { blockNameToDefaultFile } from '@core/constant/allBlocks';import { formatDocumentName } from '@service-storage/util/filename';-import { Show } from 'solid-js';+import { type JSX, Show } from 'solid-js';import { match } from 'ts-pattern';-import type { EntityData } from '../types/entity';+import { type EntityData, isGithubPrEntity } from '../types/entity';import { isSearchEntity } from '../types/search';-function extractRawTitle(entity: EntityData): string {- return match(entity)+function extractRawTitle(entity: EntityData): JSX.Element {+ return match<EntityData, JSX.Element>(entity).with({ type: 'document' }, (e) =>formatDocumentName(e.name, e.fileType, {fullyQualifiedBlockName: true,@@ -24,6 +24,15 @@ function extractRawTitle(entity: EntityData): string {{ type: 'automation' },(e) => e.name || blockNameToDefaultFile('automation'))+ .when(isGithubPrEntity, (e) => (+ <>+ {e.metadata.name}{' '}+ <span class="text-ink-extra-muted font-normal">+ #{e.metadata.number}+ </span>+ </>+ ))+ .with({ type: 'foreign' }, (e) => e.name).otherwise(() => 'Unknown');}@@ -54,7 +63,7 @@ export function EntityTitle(props: { entity: EntityData }) {fallback={<span class="truncate">{titleData().text}</span>}><StaticMarkdown- markdown={titleData().text}+ markdown={titleData().text as string}theme={unifiedListMarkdownTheme}singleLine={true}/>diff --git a/js/app/packages/entity/src/index.ts b/js/app/packages/entity/src/index.tsindex 74c78d6312..0891cd26a3 100644--- a/js/app/packages/entity/src/index.ts+++ b/js/app/packages/entity/src/index.ts@@ -32,6 +32,7 @@ export { unreadFilterFn } from './utils/filter';export {filterNotDoneNotifications,filterValidNotifications,+ toNotificationEntity,} from './utils/notification';export { useIsShared } from './utils/shared';export {diff --git a/js/app/packages/entity/src/types/entity.ts b/js/app/packages/entity/src/types/entity.tsindex ab6feca730..31bcb23796 100644--- a/js/app/packages/entity/src/types/entity.ts+++ b/js/app/packages/entity/src/types/entity.ts@@ -1,6 +1,8 @@import type { DateValue } from '@core/util/date';import type { ApiLabel } from '@service-email/generated/schemas';import type {+ GithubPullRequestCheckRun,+ GithubPullRequestComment,SoupLabel,SoupProperty,} from '@service-storage/generated/schemas';@@ -16,6 +18,41 @@ export type EntityBase = {sortTs?: DateValue | null;};+type ForeignEntityBase = EntityBase & {+ type: 'foreign';+ foreignId: string;+ storedForId: string;+ storedForAuthEntity: 'team' | (string & {});+};++export type UnknownForeignEntity = ForeignEntityBase & {+ foreignSource: 'unknown';+ rawForeignSource: string;+ metadata: {+ [key: string]: unknown;+ };+};++// Consider making this a generic pull request entity so we can display+// pull requests from other sources besides github+export type GithubPullRequestEntity = ForeignEntityBase & {+ foreignSource: 'github_pull_request';+ metadata: {+ number: number;+ name: string;+ owner: string;+ repo: string;+ url: string;+ status: 'open' | 'merged' | 'closed';+ additions: number;+ deletions: number;+ comments: GithubPullRequestComment[];+ checks: GithubPullRequestCheckRun[];+ };+};++export type ForeignEntity = UnknownForeignEntity | GithubPullRequestEntity;+export type ChannelEntity = EntityBase & {type: 'channel';channelType: 'direct_message' | 'private' | 'public' | 'team';@@ -152,7 +189,8 @@ export type EntityData =| EmailEntity| ProjectEntity| CallEntity- | AutomationEntity;+ | AutomationEntity+ | ForeignEntity;const ENTITY_TYPE_VALUES = new Set<EntityData['type']>(['channel',@@ -163,6 +201,7 @@ const ENTITY_TYPE_VALUES = new Set<EntityData['type']>(['project','call','automation',+ 'foreign',]);const _isEntityData = (item: unknown): item is EntityData => {@@ -185,6 +224,20 @@ export const isTaskEntity = (entity: EntityData): entity is TaskEntity => {);};+export const isGithubPrEntity = (+ entity: EntityData+): entity is GithubPullRequestEntity => {+ return (+ entity.type === 'foreign' && entity.foreignSource === 'github_pull_request'+ );+};++export const isUnknownForeignEntity = (+ entity: EntityData+): entity is UnknownForeignEntity => {+ return entity.type === 'foreign' && entity.foreignSource === 'unknown';+};+export const isChannelEntity = (entity: EntityData): entity is ChannelEntity => {diff --git a/js/app/packages/entity/src/utils/notification.ts b/js/app/packages/entity/src/utils/notification.tsindex abc6cb1324..8ea75470f6 100644--- a/js/app/packages/entity/src/utils/notification.ts+++ b/js/app/packages/entity/src/utils/notification.ts@@ -1,8 +1,9 @@import { ENABLE_DOCUMENT_MENTION_NOTIFICATIONS } from '@core/constant/featureFlags';-import type { NotificationType } from '@core/types';+import type { Entity, NotificationType } from '@core/types';import { notificationIsRead, type UnifiedNotification } from '@notifications';import type { NotificationStack } from '@notifications/notification-stacking';import { match } from 'ts-pattern';+import type { EntityData } from '../types/entity';import type { Notification } from '../types/notification';type CallStartedNotificationMetadata = {@@ -16,6 +17,22 @@ type KnownNotificationMetadata =| UnifiedNotification['notification_metadata']| CallStartedNotificationMetadata;+export function toNotificationEntity(entity: EntityData): Entity {+ if (entity.type === 'email') {+ return { type: 'email_thread', id: entity.id };+ }++ if (entity.type === 'foreign') {+ return { type: 'foreign_entity', id: entity.id };+ }++ if (entity.type === 'channel_message') {+ return { type: 'channel', id: entity.channelId };+ }++ return entity;+}+/*** Filters out invalid notification types that shouldn't be displayed*/diff --git a/js/app/packages/entity/src/utils/shared.ts b/js/app/packages/entity/src/utils/shared.tsindex 1c44baecbb..a6377c7c8d 100644--- a/js/app/packages/entity/src/utils/shared.ts+++ b/js/app/packages/entity/src/utils/shared.ts@@ -6,6 +6,7 @@ export function useIsShared(entity: EntityData) {return () => {if (entity.type === 'channel') return false;if (entity.type === 'call') return false;+ if (entity.type === 'foreign') return entity.storedForId !== userId();if (entity.ownerId === userId()) return false;return true;};diff --git a/js/app/packages/macro-entity/src/queries/rename.ts b/js/app/packages/macro-entity/src/queries/rename.tsindex f70cbc07fa..59a4f257e4 100644--- a/js/app/packages/macro-entity/src/queries/rename.ts+++ b/js/app/packages/macro-entity/src/queries/rename.ts@@ -91,6 +91,8 @@ const validateEntityRename = (entity: EntityData): void => {case 'project':case 'call':return;+ case 'foreign':+ throw new Error('Foreign entities do not support renaming');default:throw new Error(`Unsupported entity type: ${entity.type}`);}@@ -124,7 +126,8 @@ const renameDssSetData = (} else if (itemType !== 'email' &&itemType !== 'channel_message' &&- itemType !== 'automation'+ itemType !== 'automation' &&+ itemType !== 'foreign') {txns.set(id,diff --git a/js/app/packages/notifications/notification-navigation.ts b/js/app/packages/notifications/notification-navigation.tsindex cdc2878aa2..4d97e962c9 100644--- a/js/app/packages/notifications/notification-navigation.ts+++ b/js/app/packages/notifications/notification-navigation.ts@@ -242,6 +242,7 @@ function getSupportedHandler(const meta = notification.notification_metadata;if (meta.tag !== 'github_pr_event') return null;return async () => {+ // TODO(dev-rb/github): Route GitHub PR notifications to /pr.openExternalUrl(meta.content.url);};})diff --git a/js/app/packages/property/src/utils/entityConversion.ts b/js/app/packages/property/src/utils/entityConversion.tsindex 495b2c6cd7..3c53f4ebbc 100644--- a/js/app/packages/property/src/utils/entityConversion.ts+++ b/js/app/packages/property/src/utils/entityConversion.ts@@ -76,5 +76,8 @@ export function macroEntityToPropertyEntityType(.with({ type: 'automation' }, () => {throw new Error('automation entities do not support properties');})+ .with({ type: 'foreign' }, () => {+ throw new Error('foreign entities do not support properties');+ }).exhaustive();}diff --git a/js/app/packages/queries/soup/items.ts b/js/app/packages/queries/soup/items.tsindex e5ce2c02b1..f403e63f89 100644--- a/js/app/packages/queries/soup/items.ts+++ b/js/app/packages/queries/soup/items.ts@@ -47,6 +47,7 @@ export type SoupApiItemFilter = (item: SoupApiItem) => boolean;interface SoupItemsQueryOptions {enabled?: boolean;staleTime?: StaleTime;+ showSupportedForeignEntities?: boolean;}type SoupAstItemsPage = {@@ -95,7 +96,11 @@ export const useSoupItemsQuery = (},select: (data) => {return data.pages.flatMap((page) => {- return mapSoupPageToEntityList(page, { instructionsIdQuery });+ return mapSoupPageToEntityList(page, {+ instructionsIdQuery,+ showSupportedForeignEntities:+ options?.().showSupportedForeignEntities,+ });});},enabled: options?.().enabled,@@ -173,7 +178,11 @@ export const useSoupAstItemsQuery = (select: (data): SoupAstItemsData => {const items = data.pages.flatMap((page) => page.items);const entities = data.pages.flatMap((page) => {- return mapSoupPageToEntityList(page, { instructionsIdQuery });+ return mapSoupPageToEntityList(page, {+ instructionsIdQuery,+ showSupportedForeignEntities:+ options?.().showSupportedForeignEntities,+ });});const rawGroups = data.pages[0]?.groups;const groups = rawGroups?.slice().sort(makeGroupComparator(groupBy));diff --git a/js/app/packages/queries/soup/transform-utils.ts b/js/app/packages/queries/soup/transform-utils.tsindex 9c72672b4d..016ee2392c 100644--- a/js/app/packages/queries/soup/transform-utils.ts+++ b/js/app/packages/queries/soup/transform-utils.ts@@ -18,6 +18,8 @@ import type {DocumentEntity,EmailEntity,EntityData,+ ForeignEntity,+ GithubPullRequestEntity,ProjectEntity,SearchData,WithSearch,@@ -32,6 +34,7 @@ import type {UnifiedSearchResponseItem,} from '@service-search/generated/models';import type {+ GithubPullRequest,SoupDocument,SoupPage,} from '@service-storage/generated/schemas';@@ -49,9 +52,18 @@ type InnerSearchResult =type DisplayableSoupItem = Exclude<SoupPage['items'][number],- { tag: 'foreignEntity' } | { tag: 'crmCompany' }+ { tag: 'crmCompany' }>;+type SoupEntity =+ | DocumentEntity+ | ChatEntity+ | ProjectEntity+ | EmailEntity+ | ChannelEntity+ | CallEntity+ | ForeignEntity;+type TypedInnerSearchResult =| { results: InnerSearchResult[]; type?: undefined }| { results: DocumentSearchResult[]; type: 'pdf'; searchQuery: string }@@ -470,176 +482,206 @@ export const mapSoupPageToEntityList: (data: SoupPage,options: {instructionsIdQuery: UseQueryResult<string | null | undefined, Error>;+ showSupportedForeignEntities?: boolean;}-) => (- | DocumentEntity- | ChatEntity- | ProjectEntity- | EmailEntity- | ChannelEntity- | CallEntity-)[] = (data, options) => {+) => SoupEntity[] = (data, options) => {return data.items- .filter(- (item): item is DisplayableSoupItem =>- item.tag !== 'foreignEntity' &&- item.tag !== 'crmCompany' &&- (item.tag !== 'document' ||- !options.instructionsIdQuery.isSuccess ||- item.data.id !== options.instructionsIdQuery.data)- )- .map(- (- item- ):- | DocumentEntity- | ChatEntity- | ProjectEntity- | EmailEntity- | ChannelEntity- | CallEntity => {- if (item.tag === 'chat') {- return {- ...item.data,- createdAt: item.data.createdAt,- updatedAt: item.data.updatedAt,- type: item.tag,- name: item.data.name || 'New Chat',- frecencyScore: item.frecency_score,- viewedAt: item.data.viewedAt,- projectId: item.data.projectId ?? undefined,- };- }+ .filter((item): item is DisplayableSoupItem => {+ if (item.tag === 'foreignEntity') {+ return (+ options.showSupportedForeignEntities === true &&+ item.data.foreignEntitySource === 'github_pull_request'+ );+ }- if (item.tag === 'project') {- return {- createdAt: item.data.createdAt,- updatedAt: item.data.updatedAt,- id: item.data.id,- ownerId: item.data.ownerId,- frecencyScore: item.frecency_score,- viewedAt: item.data.viewedAt,- projectId: item.data.parentId ?? undefined,- type: item.tag,- name: item.data.name || 'New Project',- };- }+ if (item.tag === 'crmCompany') return false;- if (item.tag === 'emailThread') {- const participants = item.data.participants?.map((p) => ({- email: p.emailAddress ?? '',- name: p.name ?? '',- }));-- const hasIcsAttachment = item.data.attachments?.some(- (a) =>- a.mimeType === 'text/calendar' ||- a.filename?.toLowerCase().endsWith('.ics')- );-- const attachments = item.data.attachments?.map((a) => ({- id: a.id,- filename: a.filename,- mimeType: a.mimeType,- sizeBytes: a.sizeBytes,- }));-- // The thread preview has no link id of its own; its participants and- // labels are scoped to the owning inbox, so they share its link id.- const linkId =- item.data.participants?.[0]?.linkId ??- item.data.labels?.[0]?.linkId;+ return (+ item.tag !== 'document' ||+ !options.instructionsIdQuery.isSuccess ||+ item.data.id !== options.instructionsIdQuery.data+ );+ })+ .map((item): SoupEntity => {+ if (item.tag === 'chat') {+ return {+ ...item.data,+ createdAt: item.data.createdAt,+ updatedAt: item.data.updatedAt,+ type: item.tag,+ name: item.data.name || 'New Chat',+ frecencyScore: item.frecency_score,+ viewedAt: item.data.viewedAt,+ projectId: item.data.projectId ?? undefined,+ };+ }- return {- ...item.data,- createdAt: item.data.createdAt,- updatedAt: item.data.updatedAt,- sortTs: normalizeSentinelTs(item.data.sortTs),- senderEmail: item.data.senderEmail ?? undefined,- senderName: item.data.senderName ?? undefined,- snippet: item.data.snippet ?? undefined,- done: !item.data.inboxVisible,- type: 'email',- name: item.data.name || 'Email Thread',- frecencyScore: item.frecency_score,- viewedAt: item.data.viewedAt,- projectId: item.data.projectId ?? undefined,- linkId,- participants,- hasIcsAttachment,- attachments,- };- }+ if (item.tag === 'project') {+ return {+ createdAt: item.data.createdAt,+ updatedAt: item.data.updatedAt,+ id: item.data.id,+ ownerId: item.data.ownerId,+ frecencyScore: item.frecency_score,+ viewedAt: item.data.viewedAt,+ projectId: item.data.parentId ?? undefined,+ type: item.tag,+ name: item.data.name || 'New Project',+ };+ }- if (item.tag === 'call') {- return {- type: 'call',- id: item.data.callId,- name:- item.data.customName ??- item.data.channelName ??- blockNameToDefaultFile('call'),- channelId: item.data.channelId,- channelName: item.data.channelName ?? undefined,- ownerId: item.data.createdBy,- createdAt: item.data.startedAt,- updatedAt: item.data.endedAt ?? item.data.startedAt,- sortTs: item.data.endedAt ?? item.data.startedAt,- isActive: item.data.isActive,- attended: item.data.attended,- durationMs: item.data.durationMs ?? undefined,- participantIds: item.data.participants.map((p) => p.userId),- summary: item.data.summary ?? undefined,- } satisfies CallEntity;- }+ if (item.tag === 'emailThread') {+ const participants = item.data.participants?.map((p) => ({+ email: p.emailAddress ?? '',+ name: p.name ?? '',+ }));- if (item.tag === 'channel') {- const latestMessage =- item.data.latest_message ?? item.data.latest_non_thread_message;-- const out: ChannelEntity = {- type: 'channel',- id: item.data.channel.id,- name: item.data.channel.name || 'Unknown Channel',- channelType: item.data.channel.channel_type,- ownerId: item.data.channel.owner_id,- frecencyScore: item.frecency_score ?? 0,- updatedAt: item.data.channel.updated_at,- createdAt: item.data.channel.created_at,- participantIds: item.data.participants.map((p) => p.user_id),- viewedAt: item.data.viewed_at ?? item.data.interacted_at,- interactedAt: item.data.interacted_at,- latestMessage: latestMessage- ? {- messageId: latestMessage.message_id,- threadId: latestMessage.thread_id ?? undefined,- content: latestMessage.content,- senderId: latestMessage.sender_id,- createdAt: latestMessage.created_at,- }- : undefined,- };- return out;- }+ const hasIcsAttachment = item.data.attachments?.some(+ (a) =>+ a.mimeType === 'text/calendar' ||+ a.filename?.toLowerCase().endsWith('.ics')+ );++ const attachments = item.data.attachments?.map((a) => ({+ id: a.id,+ filename: a.filename,+ mimeType: a.mimeType,+ sizeBytes: a.sizeBytes,+ }));++ // The thread preview has no link id of its own; its participants and+ // labels are scoped to the owning inbox, so they share its link id.+ const linkId =+ item.data.participants?.[0]?.linkId ?? item.data.labels?.[0]?.linkId;return {...item.data,createdAt: item.data.createdAt,updatedAt: item.data.updatedAt,- type: item.tag,+ sortTs: normalizeSentinelTs(item.data.sortTs),+ senderEmail: item.data.senderEmail ?? undefined,+ senderName: item.data.senderName ?? undefined,+ snippet: item.data.snippet ?? undefined,+ done: !item.data.inboxVisible,+ type: 'email',+ name: item.data.name || 'Email Thread',frecencyScore: item.frecency_score,viewedAt: item.data.viewedAt,- fileType: item.data.fileType ?? undefined,projectId: item.data.projectId ?? undefined,- subType:- item.data.subType === null || item.data.subType === undefined- ? undefined- : {- type: item.data.subType.type as 'task',- is_completed: item.data.subType.is_completed,- },- name: resolveDocumentEntityName(item.data),+ linkId,+ participants,+ hasIcsAttachment,+ attachments,+ };+ }++ if (item.tag === 'call') {+ return {+ type: 'call',+ id: item.data.callId,+ name:+ item.data.customName ??+ item.data.channelName ??+ blockNameToDefaultFile('call'),+ channelId: item.data.channelId,+ channelName: item.data.channelName ?? undefined,+ ownerId: item.data.createdBy,+ createdAt: item.data.startedAt,+ updatedAt: item.data.endedAt ?? item.data.startedAt,+ sortTs: item.data.endedAt ?? item.data.startedAt,+ isActive: item.data.isActive,+ attended: item.data.attended,+ durationMs: item.data.durationMs ?? undefined,+ participantIds: item.data.participants.map((p) => p.userId),+ summary: item.data.summary ?? undefined,+ } satisfies CallEntity;+ }++ if (item.tag === 'channel') {+ const latestMessage =+ item.data.latest_message ?? item.data.latest_non_thread_message;++ const out: ChannelEntity = {+ type: 'channel',+ id: item.data.channel.id,+ name: item.data.channel.name || 'Unknown Channel',+ channelType: item.data.channel.channel_type,+ ownerId: item.data.channel.owner_id,+ frecencyScore: item.frecency_score ?? 0,+ updatedAt: item.data.channel.updated_at,+ createdAt: item.data.channel.created_at,+ participantIds: item.data.participants.map((p) => p.user_id),+ viewedAt: item.data.viewed_at ?? item.data.interacted_at,+ interactedAt: item.data.interacted_at,+ latestMessage: latestMessage+ ? {+ messageId: latestMessage.message_id,+ threadId: latestMessage.thread_id ?? undefined,+ content: latestMessage.content,+ senderId: latestMessage.sender_id,+ createdAt: latestMessage.created_at,+ }+ : undefined,};+ return out;}- );++ if (item.tag === 'foreignEntity') {+ const metadata = item.data.metadata as unknown as GithubPullRequest;++ let status: GithubPullRequestEntity['metadata']['status'] = 'open';++ if (metadata.status === 'merged') {+ status = 'merged';+ } else if (metadata.status === 'closed') {+ status = 'closed';+ }++ const out: GithubPullRequestEntity = {+ type: 'foreign',+ id: item.data.id,+ name: metadata.name ?? metadata.displayName,+ ownerId: item.data.storedForId,+ createdAt: item.data.createdAt,+ updatedAt: item.data.updatedAt,+ foreignSource: 'github_pull_request',+ foreignId: item.data.foreignEntityId,+ storedForId: item.data.storedForId,+ storedForAuthEntity: item.data.storedForAuthEntity,+ metadata: {+ number: metadata.number,+ name: metadata.name ?? metadata.displayName,+ owner: metadata.owner,+ repo: metadata.repo,+ url: metadata.url,+ status: status,+ additions: metadata.additions ?? 0,+ deletions: metadata.deletions ?? 0,+ comments: metadata.comments ?? [],+ checks: metadata.checks?.filter(Boolean) ?? [],+ },+ };++ return out;+ }++ return {+ ...item.data,+ createdAt: item.data.createdAt,+ updatedAt: item.data.updatedAt,+ type: item.tag,+ frecencyScore: item.frecency_score,+ viewedAt: item.data.viewedAt,+ fileType: item.data.fileType ?? undefined,+ projectId: item.data.projectId ?? undefined,+ subType:+ item.data.subType === null || item.data.subType === undefined+ ? undefined+ : {+ type: item.data.subType.type as 'task',+ is_completed: item.data.subType.is_completed,+ },+ name: resolveDocumentEntityName(item.data),+ };+ });};diff --git a/js/app/packages/service-clients/service-storage/client.ts b/js/app/packages/service-clients/service-storage/client.tsindex b18a8bc393..f9e50fa1e1 100644--- a/js/app/packages/service-clients/service-storage/client.ts+++ b/js/app/packages/service-clients/service-storage/client.ts@@ -163,7 +163,8 @@ export type ItemType =| 'email'| 'channel_message'| 'call'- | 'automation';+ | 'automation'+ | 'foreign';export const DEFAULT_ITEM_TYPE: ItemType = 'document';