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
Revert "fix(ai): auto attachments (#624)" (#683)
gbirman564af4e0cd8c
diff --git a/js/app/packages/core/component/AI/component/input/ActiveTabAttachment.tsx b/js/app/packages/core/component/AI/component/input/ActiveTabAttachment.tsxnew file mode 100644index 0000000000..39e383f037--- /dev/null+++ b/js/app/packages/core/component/AI/component/input/ActiveTabAttachment.tsx@@ -0,0 +1,361 @@+import { SUPPORTED_CHAT_ATTACHMENT_BLOCKS } from '@core/component/AI/constant/fileType';+import type { Attachment } from '@core/component/AI/types';+import { useChannelsContext } from '@core/component/ChannelsProvider';+import { EntityIcon } from '@core/component/EntityIcon';+import {+ DropdownMenuContent,+ MenuItem,+ MenuSeparator,+} from '@core/component/Menu';+import { fileTypeToBlockName } from '@core/constant/allBlocks';+import type { ChannelWithParticipants } from '@core/user';+import PlusIcon from '@icon/regular/plus.svg?component-solid';+import { DropdownMenu } from '@kobalte/core/dropdown-menu';+import { type EmailEntity, useEmails } from '@macro-entity';+import type {+ AttachmentType,+ ChannelType,+ FileType,+} from '@service-cognition/generated/schemas';+import type { BasicDocument } from '@service-storage/generated/schemas/basicDocument';+import { useHistory } from '@service-storage/history';+import type { SplitContent } from 'app/component/split-layout/layoutManager';+import { globalSplitManager } from 'app/signal/splitLayout';+import { createEffect, createMemo, createSignal, For, Show } from 'solid-js';++type ActiveTabAttachmentProps = {+ onAddAttachment: (attachment: Attachment) => void;+ onAddAll: (attachments: Attachment[]) => void;+ attachedAttachments: () => Attachment[];+ attachAllOnMount?: boolean;+};++function convertSplitToAttachment(+ split: SplitContent,+ item: BasicDocument | null,+ channel: ChannelWithParticipants | null = null,+ email: EmailEntity | null = null+): Attachment | null {+ let metadata: Attachment['metadata'];+ let attachmentType: AttachmentType;++ switch (split.type) {+ case 'image':+ if (!item) return null;+ const imageName = item.name || 'Image';+ const imageExtension = (item.fileType || 'png') as FileType;+ metadata = {+ type: 'image',+ image_name: imageName,+ image_extension: imageExtension,+ };+ attachmentType = 'image';+ break;+ case 'channel':+ if (!channel) return null;+ const channelName = channel.name || 'Channel';+ const channelType: ChannelType = channel.channel_type || 'public';+ metadata = {+ type: 'channel',+ channel_name: channelName,+ channel_type: channelType,+ };+ attachmentType = 'channel';+ break;+ case 'email':+ if (!email) return null;+ const emailSubject = email.name || 'No Subject';+ metadata = {+ type: 'email',+ email_subject: emailSubject,+ };+ attachmentType = 'email';+ break;+ default:+ if (!item) return null;+ const documentName = item.name || 'Document';+ const documentType = (item.fileType || 'txt') as FileType;+ metadata = {+ type: 'document',+ document_name: documentName,+ document_type: documentType,+ };+ attachmentType = 'document';+ break;+ }++ return {+ id: `split-${split.id}-${Date.now()}`,+ attachmentId: split.id,+ attachmentType,+ metadata,+ };+}++function AddContextDropdown(props: {+ activeTabs: Array<{+ split: SplitContent;+ item: BasicDocument | null;+ channel: ChannelWithParticipants | null;+ email: EmailEntity | null;+ }>;+ onAddAttachment: (attachment: Attachment) => void;+ onAddAll: (attachments: Attachment[]) => void;+ attachedAttachments: () => Attachment[];+}) {+ const handleAddAttachment = (tabData: {+ split: SplitContent;+ item: BasicDocument | null;+ channel: ChannelWithParticipants | null;+ email: EmailEntity | null;+ }) => {+ const { split, item, channel, email } = tabData;+ const attachment = convertSplitToAttachment(split, item, channel, email);+ if (attachment) {+ props.onAddAttachment(attachment);+ }+ };++ // Filter out already attached tabs+ const unattachedTabs = () => {+ const attachedIds = new Set(+ props.attachedAttachments().map((att) => att.attachmentId)+ );+ return props.activeTabs.filter(({ split }) => !attachedIds.has(split.id));+ };++ const handleAddAll = () => {+ const attachments: Attachment[] = [];+ for (const tabData of unattachedTabs()) {+ const { split, item, channel, email } = tabData;+ const attachment = convertSplitToAttachment(split, item, channel, email);+ if (attachment) {+ attachments.push(attachment);+ }+ }+ props.onAddAll(attachments);+ };++ return (+ <DropdownMenuContent+ width="md"+ class="z-modal-overlay max-h-[200px] overflow-y-auto"+ >+ <For each={unattachedTabs()}>+ {(tabData, index) => {+ const { split, item, channel, email } = tabData;++ let name: string | undefined;+ if (split.type === 'channel') {+ name = channel?.name ?? undefined;+ } else if (split.type === 'email') {+ name = email?.name ?? undefined;+ } else {+ name = item?.name;+ }++ return (+ <Show when={name}>+ {(name) => (+ <>+ <MenuItem+ text={name()}+ icon={() => {+ return (+ <EntityIcon+ targetType={fileTypeToBlockName(split.type)}+ size="sm"+ />+ );+ }}+ onClick={() => handleAddAttachment(tabData)}+ />+ <Show when={index() < unattachedTabs().length - 1}>+ <MenuSeparator />+ </Show>+ </>+ )}+ </Show>+ );+ }}+ </For>++ <Show when={unattachedTabs().length > 1}>+ <MenuSeparator />+ <MenuItem+ text="All"+ icon={() => <PlusIcon width={14} height={14} />}+ onClick={handleAddAll}+ />+ </Show>+ </DropdownMenuContent>+ );+}++export function ActiveTabAttachment(props: ActiveTabAttachmentProps) {+ const [showDropdown, setShowDropdown] = createSignal(false);+ const [hasAutoAttached, setHasAutoAttached] = createSignal(false);+ const history = useHistory();+ const channelsContext = useChannelsContext();+ const channels = () => channelsContext.channels();+ const emails = useEmails();++ // Get valid active tabs using createMemo+ const validActiveTabs = createMemo(() => {+ const splitManager = globalSplitManager();+ if (!splitManager) return [];++ const splits = splitManager.splits();+ const historyItems = history();+ const channelList = channels();+ const emailList = emails();++ // Deduplicate by type:id key and resolve names from history/channels/emails+ const uniqueSplits = new Map<+ string,+ {+ split: SplitContent;+ item: BasicDocument | null;+ channel: ChannelWithParticipants | null;+ email: EmailEntity | null;+ }+ >();++ for (const split of splits) {+ // TODO: need smarter type checking/inference+ if (+ split.content.type === 'component' ||+ !SUPPORTED_CHAT_ATTACHMENT_BLOCKS.includes(split.content.type)+ ) {+ continue;+ }++ const key = `${split.content.type}:${split.content.id}`;+ if (!uniqueSplits.has(key)) {+ // For email splits, find in email list+ if (split.content.type === 'email') {+ const emailItem = emailList.find(+ (email) => email.id === split.content.id+ );+ if (!emailItem) {+ continue;+ }++ uniqueSplits.set(key, {+ split: split.content,+ item: null,+ channel: null,+ email: emailItem,+ });+ continue;+ }++ // Find matching item in history+ const historyItem =+ historyItems.find((item) => item.id === split.content.id) || null;+ if (!historyItem || historyItem.type !== 'document') {+ continue;+ }++ // Find matching channel if this is a channel split+ const channelItem =+ split.content.type === 'channel'+ ? channelList.find((channel) => channel.id === split.content.id) ||+ null+ : null;++ uniqueSplits.set(key, {+ split: split.content,+ item: historyItem,+ channel: channelItem,+ email: null,+ });+ }+ }++ return Array.from(uniqueSplits.values());+ });++ // Auto-attach all available context when component first loads+ createEffect(() => {+ if (!props.attachAllOnMount) return;++ const tabs = validActiveTabs();+ if (tabs.length > 0 && !hasAutoAttached()) {+ const attachments: Attachment[] = [];+ for (const tabData of tabs) {+ const { split, item, channel, email } = tabData;+ const attachment = convertSplitToAttachment(+ split,+ item,+ channel,+ );+ if (attachment) {+ attachments.push(attachment);+ }+ }+ if (attachments.length > 0) {+ props.onAddAll(attachments);+ setHasAutoAttached(true);+ }+ }+ });++ // Count attached tabs (from available context)+ const attachedTabCount = createMemo(() => {+ const availableTabs = validActiveTabs();+ const currentAttachments = props.attachedAttachments();++ if (availableTabs.length === 0) return 0;++ // Count available tabs that are in current attachments+ const attachedIds = new Set(+ currentAttachments.map((att) => att.attachmentId)+ );+ let count = 0;+ for (const { split } of availableTabs) {+ if (attachedIds.has(split.id)) {+ count++;+ }+ }+ return count;+ });++ const unattachedTabCount = createMemo(() => {+ const availableTabs = validActiveTabs();+ const attachedCount = attachedTabCount();+ return availableTabs.length - attachedCount;+ });++ const hasUnattachedTabs = createMemo(() => unattachedTabCount() > 0);++ return (+ <Show when={hasUnattachedTabs()}>+ <div class="py-[1.5] px-2 hover:bg-hover hover-transition-bg text-xs border border-edge border-dashed">+ <DropdownMenu+ open={showDropdown()}+ onOpenChange={setShowDropdown}+ placement="top-start"+ >+ <DropdownMenu.Trigger>+ <div+ class="flex items-center gap-1 text-ink"+ onClick={() => setShowDropdown(!showDropdown())}+ >+ Tabs+ </div>+ </DropdownMenu.Trigger>+ <DropdownMenu.Portal>+ <AddContextDropdown+ activeTabs={validActiveTabs()}+ onAddAttachment={props.onAddAttachment}+ onAddAll={props.onAddAll}+ attachedAttachments={props.attachedAttachments}+ />+ </DropdownMenu.Portal>+ </DropdownMenu>+ </div>+ </Show>+ );+}diff --git a/js/app/packages/core/component/AI/component/input/useChatInput.tsx b/js/app/packages/core/component/AI/component/input/useChatInput.tsxindex d20e577018..689c7c6aaa 100644--- a/js/app/packages/core/component/AI/component/input/useChatInput.tsx+++ b/js/app/packages/core/component/AI/component/input/useChatInput.tsx@@ -24,8 +24,8 @@ import XIcon from '@icon/regular/x.svg';import { createCallback } from '@solid-primitives/rootless';import type { LexicalEditor } from 'lexical';import type { Accessor, Component, Setter } from 'solid-js';-import { createEffect, createSignal, Match, on, Show, Switch } from 'solid-js';-import { useTabAttachments } from '../../signal/tabAttachments';+import { createEffect, createSignal, Match, Show, Switch } from 'solid-js';+import { ActiveTabAttachment } from './ActiveTabAttachment';import { AttachmentList } from './Attachment';import { ChatAttachMenu } from './ChatAttachMenu';import { SendMessageButton, StopButton } from './SendMessageButton';@@ -93,21 +93,6 @@ export function useChatInput(},});- const tabAttachments = useTabAttachments();- createEffect(- on(tabAttachments, (tabs, p) => {- for (const prev of p ?? []) {- // remove stuff from closed tabs- if (!tabs.find((t) => t.attachmentId === prev.attachmentId)) {- attachments.removeAttachment(prev.attachmentId);- }- }- for (const tab of tabs) {- attachments.addAttachment(tab);- }- })- );-const ChatInputComponent = (innerProps: ChatInputProps) => (<ChatInput{...innerProps}@@ -271,6 +256,22 @@ function ChatInput(props: ChatInputInternalProps) {ref={setAttachMenuAnchorRef}onClick={() => setShowAttachMenu((prev) => !prev)}/>+ <Show when={props.showActiveTabs}>+ <ActiveTabAttachment+ onAddAttachment={(attachment) => {+ track(TrackingEvents.CHAT.ATTACHMENT.ADD);+ props.attachments.addAttachment(attachment);+ }}+ onAddAll={(attachments_) => {+ attachments_.forEach((attachment) => {+ track(TrackingEvents.CHAT.ATTACHMENT.ADD);+ props.attachments.addAttachment(attachment);+ });+ }}+ attachedAttachments={props.attachments.attached}+ attachAllOnMount={!props.chatId()}+ />+ </Show></div><Switch><Match when={props.uploadQueue.uploading().length !== 0}>diff --git a/js/app/packages/core/component/AI/signal/tabAttachments.ts b/js/app/packages/core/component/AI/signal/tabAttachments.tsdeleted file mode 100644index 470178b990..0000000000--- a/js/app/packages/core/component/AI/signal/tabAttachments.ts+++ /dev/null@@ -1,253 +0,0 @@-import { SUPPORTED_CHAT_ATTACHMENT_BLOCKS } from '@core/component/AI/constant/fileType';-import type { Attachment } from '@core/component/AI/types';-import { useChannelsContext } from '@core/component/ChannelsProvider';-import type { ChannelWithParticipants } from '@core/user';-import { isOk } from '@core/util/maybeResult';-import { type EmailEntity, useEmails } from '@macro-entity';-import type {- AttachmentType,- ChannelType,- ChatAttachmentWithName,- FileType,-} from '@service-cognition/generated/schemas';-import { emailClient } from '@service-email/client';-import { useHistory } from '@service-storage/history';-import type { SplitContent } from 'app/component/split-layout/layoutManager';-import { globalSplitManager } from 'app/signal/splitLayout';-import type { Accessor } from 'solid-js';-import { createMemo, createResource } from 'solid-js';--type Item = ReturnType<ReturnType<typeof useHistory>>[number] | null;--function convertSplitToAttachment(- split: SplitContent,- item: Item,- channel: ChannelWithParticipants | null = null,- email: EmailEntity | null = null-): Attachment | null {- let metadata: Attachment['metadata'];- let attachmentType: AttachmentType;-- switch (split.type) {- case 'image':- if (!item || item.type !== 'document') return null;- const imageName = item.name || 'Image';- const imageExtension = (item.fileType || 'png') as FileType;- // this is correct- metadata = {- type: 'document',- document_name: imageName,- document_type: imageExtension,- };- attachmentType = 'document';- break;- case 'channel':- if (!channel) return null;- const channelName = channel.name || 'Channel';- const channelType: ChannelType = channel.channel_type || 'public';- metadata = {- type: 'channel',- channel_name: channelName,- channel_type: channelType,- };- attachmentType = 'channel';- break;- case 'email':- if (!email) return null;- const emailSubject = email.name || 'No Subject';- metadata = {- type: 'email',- email_subject: emailSubject,- };- attachmentType = 'email';- break;- case 'project':- if (!item || item.type !== 'project') return null;- metadata = {- type: 'project',- project_name: item.name,- };- attachmentType = 'project';- break;- default:- if (!item || item.type !== 'document') return null;- const documentName = item.name || 'Document';- const documentType = (item.fileType || 'txt') as FileType;- metadata = {- type: 'document',- document_name: documentName,- document_type: documentType,- };- attachmentType = 'document';- break;- }-- return {- id: `split-${split.id}-${Date.now()}`,- attachmentId: split.id,- attachmentType,- metadata,- };-}--export function useTabAttachments(): Accessor<ChatAttachmentWithName[]> {- const history = useHistory();- const channelsContext = useChannelsContext();- const channels = () => channelsContext.channels();- const emails = useEmails();-- // Get valid active tabs using createMemo- const tabs = createMemo(() => {- const splitManager = globalSplitManager();- if (!splitManager) return [];-- const splits = splitManager.splits();- const historyItems = history();- const channelList = channels();- const emailList = emails();-- // Deduplicate by type:id key and resolve names from history/channels/emails- const uniqueSplits = new Map<- string,- {- split: SplitContent;- item: Item;- channel: ChannelWithParticipants | null;- email: EmailEntity | null;- }- >();-- for (const split of splits) {- // TODO: need smarter type checking/inference- if (- split.content.type === 'component' ||- !SUPPORTED_CHAT_ATTACHMENT_BLOCKS.includes(split.content.type)- ) {- continue;- }-- const key = `${split.content.type}:${split.content.id}`;- // For email splits, find in email list- if (split.content.type === 'email') {- const emailItem = emailList.find(- (email) => email.id === split.content.id- );- if (!emailItem) {- continue;- }-- uniqueSplits.set(key, {- split: split.content,- item: null,- channel: null,- email: emailItem,- });- continue;- }-- const channelItem =- split.content.type === 'channel'- ? channelList.find((channel) => channel.id === split.content.id) ||- null- : null;- if (split.content.type === 'channel') {- uniqueSplits.set(key, {- split: split.content,- item: null,- channel: channelItem,- email: null,- });- continue;- }-- const historyItem =- historyItems.find((item) => item.id === split.content.id) || null;- if (historyItem) {- uniqueSplits.set(key, {- split: split.content,- item: historyItem,- channel: channelItem,- email: null,- });- }- }-- return Array.from(uniqueSplits.values());- });-- const emailTabs = createMemo(() => {- const splitManager = globalSplitManager();- if (!splitManager) return [];- return splitManager- .splits()- .filter((split) => split.content.type === 'email');- });-- const [emailAttachments] = createResource(emailTabs, async (eTabs) => {- const threads = await Promise.allSettled(- eTabs.map((email) =>- emailClient- .getThread({- thread_id: email.content.id,- limit: 1,- })- .then((r) => ({ id: email.content.id, result: r }))- )- ).then((threads) =>- threads.flatMap((r) => {- if (r.status === 'rejected') return [];- return isOk(r.value.result)- ? [- {- id: r.value.id,- thread: r.value.result[1],- },- ]- : [];- })- );-- const attachments: ChatAttachmentWithName[] = threads.flatMap((thread) => {- // :(- const subject = thread.thread.thread.messages[0]?.subject;- if (!subject) return [];- return [- {- attachmentType: 'email',- attachmentId: thread.id,- id: thread.id,- metadata: {- email_subject: subject,- type: 'email',- },- },- ];- });- return attachments;- });-- const tabAttachments = createMemo(() => {- const openTabs = tabs();- const attachments: Attachment[] = [];- for (const tabData of openTabs) {- const { split, item, channel, email } = tabData;- const attachment = convertSplitToAttachment(split, item, channel, email);- if (attachment) {- attachments.push(attachment);- }- }- return attachments;- });-- const combinedAttachments = createMemo(() => {- const tabs = tabAttachments();- const existingAttachments = new Set(tabs.map((a) => a.attachmentId));- const queriedEmails = emailAttachments() ?? [];- const newEmails = queriedEmails.filter(- (e) => !existingAttachments.has(e.attachmentId)- );- return [...newEmails, ...tabs];- });-- return combinedAttachments;-}