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.

fix(ai): fix ask ai, invisible explicit attachments (#5196)

teoc3ab0076bd31
diff --git a/apps/web/src/features/block-chat/client.ts b/apps/web/src/features/block-chat/client.ts
deleted file mode 100644
index 6cac294647..0000000000
--- a/apps/web/src/features/block-chat/client.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import type { BlockName } from '@core/block';
-import { usePaywallState } from '@core/constant/PaywallState';
-import { isPaymentError } from '@core/util/handlePaymentError';
-
-import { cognitionApiServiceClient } from '@service-cognition/client';
-
-export function useOpenChatForAttachment() {
- const { showPaywall } = usePaywallState();
-
- return async function openChatForAttachment(args: {
- attachmentId: string;
- callerBlock?: {
- name: BlockName;
- id: string;
- };
- }) {
- const { attachmentId, callerBlock } = args;
- const res = await cognitionApiServiceClient.getChatsForAttachment({
- attachment_id: attachmentId,
- });
- if (res.isErr()) return;
- const data = res.value;
-
- let recent_id = data?.recent_chat?.id;
-
- if (
- (!recent_id || !data?.recent_chat?.isPersistent) &&
- callerBlock?.name === 'image'
- ) {
- const res = await cognitionApiServiceClient.createChat({});
-
- if (isPaymentError(res)) {
- showPaywall();
- return;
- }
- if (res.isErr()) {
- return;
- }
- const data = res.value;
- recent_id = data?.id;
- } else if (!recent_id || !data?.recent_chat?.isPersistent) {
- const res = await cognitionApiServiceClient.createChat({});
-
- if (isPaymentError(res)) {
- showPaywall();
- return;
- }
- if (res.isErr()) {
- return;
- }
- const data = res.value;
- recent_id = data?.id;
- }
- };
-}
diff --git a/apps/web/src/features/block-chat/component/Chat.tsx b/apps/web/src/features/block-chat/component/Chat.tsx
index 6d200a7636..d476a5b1ef 100644
--- a/apps/web/src/features/block-chat/component/Chat.tsx
+++ b/apps/web/src/features/block-chat/component/Chat.tsx
@@ -1,4 +1,3 @@
-import { useAnalytics } from '@app/lib/analytics/analytics-context';
import type { SendBuilder } from '@block-chat/blockClient';
import { TopBar } from '@block-chat/component/TopBar';
import type { ChatData } from '@block-chat/definition';
@@ -32,6 +31,7 @@ import {
peekPendingSend,
} from '@core/component/AI/signal/pendingSend';
import { registerToolHandler } from '@core/component/AI/signal/tool';
+import { insertChatAttachmentMention } from '@core/component/AI/util/chatAttachmentMention';
import { deriveChatName } from '@core/component/AI/util/deriveName';
import { parseModel } from '@core/component/AI/util/parse';
import {
@@ -140,7 +140,6 @@ function ChatInner(props: {
loadedInputText: string | undefined;
}) {
const owner = getOwner();
- const analytics = useAnalytics();
const input = useChatInputContext();
const chat = useChatContext();
const canEdit = useCanEdit();
@@ -156,13 +155,12 @@ function ChatInner(props: {
);
const { getAttachmentFromMention } = useGetChatAttachmentInfo();
-
const editor = buildChatEditor().withMentions({
onCreate: (mention) => {
- analytics.track('mentions_menu_use', { itemType: 'chat' });
const attachment = getAttachmentFromMention(mention);
if (attachment) input.attachments.addAttachment(attachment);
},
+ onRemove: (mention) => input.attachments.removeAttachment(mention.itemId),
block: 'chat',
showOpenTabs: true,
});
@@ -179,7 +177,9 @@ function ChatInner(props: {
const chatId = useBlockId();
const { droppable, isDraggingOver } = useEntityDropAttachment(
'chat-input-' + chatId,
- input.attachments
+ input.attachments,
+ (mention) =>
+ insertChatAttachmentMention(editor.controls.getLexical(), mention)
);
false && droppable;
diff --git a/apps/web/src/features/chat/ChatWithAgentButton.test.ts b/apps/web/src/features/chat/ChatWithAgentButton.test.ts
new file mode 100644
index 0000000000..11efd8e91c
--- /dev/null
+++ b/apps/web/src/features/chat/ChatWithAgentButton.test.ts
@@ -0,0 +1,64 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ createChat: vi.fn(),
+ openWithSplit: vi.fn(),
+ storeChatStateImmediate: vi.fn(),
+}));
+
+vi.mock('@app/signal/splitLayout', () => ({
+ globalSplitManager: () => ({ openWithSplit: mocks.openWithSplit }),
+}));
+vi.mock('@core/component/AI/signal/pendingSend', () => ({
+ setPendingSendData: vi.fn(),
+}));
+vi.mock('@core/component/LexicalMarkdown/plugins/mentions', () => ({
+ INSERT_DOCUMENT_MENTION_COMMAND: {},
+}));
+vi.mock('@core/component/AI/util/storage', () => ({
+ storeChatStateImmediate: mocks.storeChatStateImmediate,
+}));
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { failure: vi.fn() },
+}));
+vi.mock('@core/constant/allBlocks', () => ({
+ fileTypeToBlockName: (fileType: string | null | undefined) =>
+ fileType ?? 'unknown',
+}));
+vi.mock('@core/util/create', () => ({
+ createChat: mocks.createChat,
+}));
+vi.mock('@icon/wide-star', () => ({
+ AnimatedStarIcon: () => null,
+}));
+vi.mock('@ui', () => ({
+ Button: () => null,
+}));
+
+import { openChatWithAgent } from './ChatWithAgentButton';
+
+describe('openChatWithAgent', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.createChat.mockResolvedValue({ chatId: 'chat-id' });
+ });
+
+ it('seeds and opens a new chat with a visible mention and attachment', async () => {
+ await openChatWithAgent({
+ type: 'document',
+ id: 'document-id',
+ name: 'Project plan',
+ fileType: 'md',
+ });
+
+ expect(mocks.storeChatStateImmediate).toHaveBeenCalledWith('chat-id', {
+ input:
+ '<m-document-mention>{"documentId":"document-id","documentName":"Project plan","blockName":"md","blockParams":{}}</m-document-mention>',
+ attachments: [{ entity_id: 'document-id', entity_type: 'document' }],
+ });
+ expect(mocks.openWithSplit).toHaveBeenCalledWith(
+ { type: 'chat', id: 'chat-id' },
+ { activate: true, preferNewSplit: true }
+ );
+ });
+});
diff --git a/apps/web/src/features/chat/ChatWithAgentButton.tsx b/apps/web/src/features/chat/ChatWithAgentButton.tsx
index f22802f9f0..6cc077e8cb 100644
--- a/apps/web/src/features/chat/ChatWithAgentButton.tsx
+++ b/apps/web/src/features/chat/ChatWithAgentButton.tsx
@@ -2,26 +2,21 @@ import { globalSplitManager } from '@app/signal/splitLayout';
import { DEFAULT_MODEL } from '@core/component/AI/constant';
import { setPendingSendData } from '@core/component/AI/signal/pendingSend';
import type { Attachment } from '@core/component/AI/types';
+import {
+ type ChatAttachmentMention,
+ chatAttachmentMentionToMarkdown,
+} from '@core/component/AI/util/chatAttachmentMention';
import { storeChatStateImmediate } from '@core/component/AI/util/storage';
import { toast } from '@core/component/Toast/Toast';
+import { fileTypeToBlockName } from '@core/constant/allBlocks';
import { createChat } from '@core/util/create';
import { AnimatedStarIcon } from '@icon/wide-star';
-import { ChannelType } from '@service-cognition/generated/schemas/channelType';
+import type { ChannelType } from '@service-cognition/generated/schemas/channelType';
import { Button } from '@ui';
import { createSignal } from 'solid-js';
-import { match } from 'ts-pattern';
export { AnimatedStarIcon as ChatWithAgentIcon };
-const CHANNEL_TYPE_VALUES = new Set<string>(Object.values(ChannelType));
-
-function _toChatChannelType(
- t: string | undefined | null
-): ChannelType | undefined {
- if (t && CHANNEL_TYPE_VALUES.has(t)) return t as ChannelType;
- return undefined;
-}
-
type ChatWithAgentEntity =
| { type: 'email'; id: string; name: string }
| {
@@ -33,25 +28,31 @@ type ChatWithAgentEntity =
| { type: 'project'; id: string; name: string }
| { type: 'channel'; id: string; name: string; channelType: ChannelType };
-function buildAttachment(entity: ChatWithAgentEntity): Attachment | undefined {
- return match(entity)
- .with({ type: 'email' }, (e) => ({
- entity_id: e.id,
- entity_type: 'email_thread' as const,
- }))
- .with({ type: 'document' }, (e) => ({
- entity_id: e.id,
- entity_type: 'document' as const,
- }))
- .with({ type: 'project' }, (e) => ({
- entity_id: e.id,
- entity_type: 'project' as const,
- }))
- .with({ type: 'channel' }, (e) => ({
- entity_id: e.id,
- entity_type: 'channel' as const,
- }))
- .exhaustive();
+function buildSeed(entity: ChatWithAgentEntity): {
+ mention: ChatAttachmentMention;
+ attachment: Attachment;
+} {
+ const attachmentType: Attachment['entity_type'] =
+ entity.type === 'email' ? 'email_thread' : entity.type;
+ const blockName =
+ entity.type === 'document'
+ ? fileTypeToBlockName(entity.fileType, true)
+ : entity.type === 'email'
+ ? 'email'
+ : entity.type;
+
+ return {
+ mention: {
+ documentId: entity.id,
+ documentName: entity.name,
+ blockName,
+ ...(entity.type === 'channel' ? { channelType: entity.channelType } : {}),
+ },
+ attachment: {
+ entity_id: entity.id,
+ entity_type: attachmentType,
+ },
+ };
}
async function createAndOpenChat(seed: {
@@ -84,13 +85,9 @@ async function createAndOpenChat(seed: {
}
export async function openChatWithAgent(entity: ChatWithAgentEntity) {
- const attachment = buildAttachment(entity);
- if (!attachment) {
- console.warn('openChatWithAgent: unable to build attachment', entity);
- toast.failure("Can't attach this item to a chat");
- return;
- }
- await createAndOpenChat({ attachments: [attachment] });
+ const { mention, attachment } = buildSeed(entity);
+ const input = chatAttachmentMentionToMarkdown(mention);
+ await createAndOpenChat({ input, attachments: [attachment] });
}
export async function openChatWithInput(initialInput: string) {
diff --git a/apps/web/src/features/chat/SoupChatInput.tsx b/apps/web/src/features/chat/SoupChatInput.tsx
index 95cdd52035..87d7700831 100644
--- a/apps/web/src/features/chat/SoupChatInput.tsx
+++ b/apps/web/src/features/chat/SoupChatInput.tsx
@@ -1,4 +1,3 @@
-import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import { buildChatEditor } from '@core/component/AI/component/input/buildChatEditor';
import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';
@@ -24,18 +23,16 @@ import { cognitionApiServiceClient } from '@service-cognition/client';
import { createEffect, onMount } from 'solid-js';
function SoupChatInputInner() {
- const analytics = useAnalytics();
const splitPanelContext = useSplitPanelOrThrow();
const input = useChatInputContext();
const { getAttachmentFromMention } = useGetChatAttachmentInfo();
-
const editor = buildChatEditor().withMentions({
onCreate: (mention) => {
- analytics.track('mentions_menu_use', { itemType: 'chat' });
const attachment = getAttachmentFromMention(mention);
if (attachment) input.attachments.addAttachment(attachment);
},
+ onRemove: (mention) => input.attachments.removeAttachment(mention.itemId),
block: 'chat',
showOpenTabs: true,
});
diff --git a/apps/web/src/features/home/home.tsx b/apps/web/src/features/home/home.tsx
index 8d0c67b722..38fa2ce28c 100644
--- a/apps/web/src/features/home/home.tsx
+++ b/apps/web/src/features/home/home.tsx
@@ -1,4 +1,3 @@
-import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { ShowFeatureFlag } from '@app/lib/analytics/posthog';
import { FloatRegionOrInline } from '@components/app/mobile/float-regions/FloatRegion';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
@@ -168,18 +167,16 @@ function HomeContent() {
}
const HomeChatInput = () => {
- const analytics = useAnalytics();
const splitPanelContext = useSplitPanelOrThrow();
const input = useChatInputContext();
const { getAttachmentFromMention } = useGetChatAttachmentInfo();
-
const editor = buildChatEditor().withMentions({
onCreate: (mention) => {
- analytics.track('mentions_menu_use', { itemType: 'chat' });
const attachment = getAttachmentFromMention(mention);
if (attachment) input.attachments.addAttachment(attachment);
},
+ onRemove: (mention) => input.attachments.removeAttachment(mention.itemId),
block: 'chat',
showOpenTabs: true,
});
diff --git a/apps/web/src/lib/core/component/AI/component/input/ChatAttachMenu.tsx b/apps/web/src/lib/core/component/AI/component/input/ChatAttachMenu.tsx
index c6bfb346ad..eb92ecfa85 100644
--- a/apps/web/src/lib/core/component/AI/component/input/ChatAttachMenu.tsx
+++ b/apps/web/src/lib/core/component/AI/component/input/ChatAttachMenu.tsx
@@ -42,7 +42,7 @@ type ChatAttachMenuProps = {
close: () => void;
anchorRef: HTMLDivElement;
containerRef: HTMLElement;
- onAttach: (attachment: Attachment) => void;
+ onAttach: (attachment: Attachment, item: HistoryItem) => void;
};
function truncate(str: string, maxLength: number = 30) {
@@ -191,11 +191,7 @@ export function ChatAttachMenu(props: ChatAttachMenuProps) {
}
const attachment = getDocumentAttachment(item.id, item.fileType);
-
- if (attachment) {
- props.onAttach(attachment);
- }
-
+ if (attachment) props.onAttach(attachment, item);
props.close();
};
diff --git a/apps/web/src/lib/core/component/AI/component/input/ChatInput.tsx b/apps/web/src/lib/core/component/AI/component/input/ChatInput.tsx
index e4a2777003..3dc3cdda84 100644
--- a/apps/web/src/lib/core/component/AI/component/input/ChatInput.tsx
+++ b/apps/web/src/lib/core/component/AI/component/input/ChatInput.tsx
@@ -10,15 +10,18 @@ import {
import { useChatInputContext } from '@core/component/AI/context';
import type { ToolSet } from '@core/component/AI/types';
import { isImageAttachment } from '@core/component/AI/util/attachment';
+import { insertChatAttachmentMention } from '@core/component/AI/util/chatAttachmentMention';
import type { EditorConfigBuilder } from '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder';
import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';
import { toast } from '@core/component/Toast/Toast';
+import { fileTypeToBlockName } from '@core/constant/allBlocks';
import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';
import { TOKENS } from '@core/hotkey/tokens';
import { isMobile } from '@core/mobile/isMobile';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { useTouchOutsideToDismissKeyboard } from '@core/mobile/useTouchOutsideToDismissKeyboard';
+import { getItemBlockName } from '@core/util/getItemBlockName';
import { handleFileFolderDrop } from '@core/util/upload';
import PaperclipIcon from '@phosphor/paperclip.svg';
import { createElementSize } from '@solid-primitives/resize-observer';
@@ -133,6 +136,17 @@ export function ChatInput(props: ChatInputComponentProps) {
.forEach((upload) => {
analytics.track('ai_attachment_add');
attachments.addAttachment(upload.attachment);
+ const metadata = upload.preview.metadata;
+ if (
+ upload.attachment.entity_type === 'document' &&
+ metadata?.type === 'document'
+ ) {
+ insertChatAttachmentMention(props.editor.controls.getLexical(), {
+ documentId: upload.attachment.entity_id,
+ documentName: metadata.document_name,
+ blockName: fileTypeToBlockName(metadata.document_type, true),
+ });
+ }
});
});
@@ -305,9 +319,17 @@ export function ChatInput(props: ChatInputComponentProps) {
close={() => setShowAttachMenu(false)}
containerRef={containerRef}
open={showAttachMenu()}
- onAttach={(attachment) => {
+ onAttach={(attachment, item) => {
analytics.track('ai_attachment_add');
attachments.addAttachment(attachment);
+ insertChatAttachmentMention(
+ props.editor.controls.getLexical(),
+ {
+ documentId: item.id,
+ documentName: item.name,
+ blockName: getItemBlockName(item, true),
+ }
+ );
}}
/>
</Show>
diff --git a/apps/web/src/lib/core/component/AI/component/message/EditableChatMessage.tsx b/apps/web/src/lib/core/component/AI/component/message/EditableChatMessage.tsx
index ae365b19ec..bffa135389 100644
--- a/apps/web/src/lib/core/component/AI/component/message/EditableChatMessage.tsx
+++ b/apps/web/src/lib/core/component/AI/component/message/EditableChatMessage.tsx
@@ -1,4 +1,3 @@
-import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { buildChatEditor } from '@core/component/AI/component/input/buildChatEditor';
import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';
import { ChatInput } from '@core/component/AI/component/input/ChatInput';
@@ -18,17 +17,14 @@ function EditableChatMessageInner(props: {
onCancel: () => void;
model: Model;
}) {
- const analytics = useAnalytics();
-
const input = useChatInputContext();
const { getAttachmentFromMention } = useGetChatAttachmentInfo();
-
const editor = buildChatEditor().withMentions({
onCreate: (mention) => {
- analytics.track('mentions_menu_use', { itemType: 'chat' });
const attachment = getAttachmentFromMention(mention);
if (attachment) input.attachments.addAttachment(attachment);
},
+ onRemove: (mention) => input.attachments.removeAttachment(mention.itemId),
block: 'chat',
showOpenTabs: true,
});
diff --git a/apps/web/src/lib/core/component/AI/component/message/UserMessage.tsx b/apps/web/src/lib/core/component/AI/component/message/UserMessage.tsx
index 008ecc1268..3ae83972a2 100644
--- a/apps/web/src/lib/core/component/AI/component/message/UserMessage.tsx
+++ b/apps/web/src/lib/core/component/AI/component/message/UserMessage.tsx
@@ -5,11 +5,12 @@ import PencilIcon from '@phosphor/note-pencil.svg';
import QuoteIcon from '@phosphor-icons/core/bold/arrow-elbow-down-right-bold.svg?component-solid';
import type { ChatMessageWithAttachments } from '@service-cognition/generated/schemas/chatMessageWithAttachments';
import { Button, Layer } from '@ui';
-import { createSignal, For, Match, Show, Switch } from 'solid-js';
+import { createMemo, createSignal, For, Match, Show, Switch } from 'solid-js';
import { DEFAULT_MODEL } from '../../constant';
import { ChatMessageMarkdown } from './ChatMessageMarkdown';
import { CollapsibleMessage } from './CollapsibleMessage';
import { EditableChatMessage } from './EditableChatMessage';
+import { getVisibleUserMessageAttachments } from './userMessageAttachments';
// Function to insert soft hyphens into long words / urls / etc so that they won't lock the width
function insertSoftHyphens(text: string): string {
@@ -64,13 +65,16 @@ export function UserMessage(props: {
return rawContent?.trim() ? rawContent : undefined;
};
- const imageAttachments = () =>
- props.message.attachments.filter((a) => a.entity_type === 'static_file');
+ const visibleAttachments = createMemo(() =>
+ getVisibleUserMessageAttachments(
+ props.message.content.toString(),
+ props.message.attachments
+ )
+ );
- const itemPreviewAttachments = () =>
- props.message.attachments.filter((a) =>
- ['channel', 'document', 'email_thread', 'project'].includes(a.entity_type)
- );
+ const hasVisibleAttachments = () =>
+ visibleAttachments().images.length > 0 ||
+ visibleAttachments().items.length > 0;
return (
<div class="flex flex-col group">
@@ -82,9 +86,9 @@ export function UserMessage(props: {
</div>
</div>
</Show>
- <Show when={props.message.attachments.length > 0}>
+ <Show when={hasVisibleAttachments()}>
<div class="flex flex-col items-end gap-1 ml-auto max-w-[calc(100%-8rem)] mb-2">
- <For each={imageAttachments()}>
+ <For each={visibleAttachments().images}>
{(attachment) => (
<ImagePreview
image={{ id: attachment.entity_id }}
@@ -93,7 +97,7 @@ export function UserMessage(props: {
/>
)}
</For>
- <For each={itemPreviewAttachments()}>
+ <For each={visibleAttachments().items}>
{(attachment) => (
<div class="max-w-full overflow-hidden p-[0.5px]">
<ItemPreview
diff --git a/apps/web/src/lib/core/component/AI/component/message/userMessageAttachments.test.ts b/apps/web/src/lib/core/component/AI/component/message/userMessageAttachments.test.ts
new file mode 100644
index 0000000000..bc881bc66c
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/message/userMessageAttachments.test.ts
@@ -0,0 +1,37 @@
+import type { Attachment } from '@core/component/AI/types';
+import { describe, expect, it } from 'vitest';
+import { getVisibleUserMessageAttachments } from './userMessageAttachments';
+
+describe('getVisibleUserMessageAttachments', () => {
+ it('hides item cards already represented by mentions', () => {
+ const attachments: Attachment[] = [
+ { entity_id: 'document-id', entity_type: 'document' },
+ { entity_id: 'email-id', entity_type: 'email_thread' },
+ { entity_id: 'legacy-id', entity_type: 'project' },
+ { entity_id: 'image-id', entity_type: 'static_file' },
+ ];
+ const content = [
+ '<m-document-mention>{"documentId":"document-id","documentName":"Plan","blockName":"md"}</m-document-mention>',
+ '<m-document-mention>{"documentId":"email-id","documentName":"Resume","blockName":"email"}</m-document-mention>',
+ 'What are these?',
+ ].join(' ');
+
+ expect(getVisibleUserMessageAttachments(content, attachments)).toEqual({
+ images: [{ entity_id: 'image-id', entity_type: 'static_file' }],
+ items: [{ entity_id: 'legacy-id', entity_type: 'project' }],
+ });
+ });
+
+ it('keeps the card when malformed mention markup contains its id', () => {
+ const attachments: Attachment[] = [
+ { entity_id: 'document-id', entity_type: 'document' },
+ ];
+
+ expect(
+ getVisibleUserMessageAttachments(
+ '<m-document-mention>{"documentId":"document-id"</m-document-mention>',
+ attachments
+ ).items
+ ).toEqual(attachments);
+ });
+});
diff --git a/apps/web/src/lib/core/component/AI/component/message/userMessageAttachments.ts b/apps/web/src/lib/core/component/AI/component/message/userMessageAttachments.ts
new file mode 100644
index 0000000000..4679a9c77d
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/message/userMessageAttachments.ts
@@ -0,0 +1,54 @@
+import type { Attachment } from '@core/component/AI/types';
+
+const ITEM_ATTACHMENT_TYPES = new Set<Attachment['entity_type']>([
+ 'channel',
+ 'document',
+ 'email_thread',
+ 'project',
+]);
+
+const DOCUMENT_MENTION_PATTERN =
+ /<m-document-mention>([\s\S]*?)<\/m-document-mention>/g;
+
+function getMentionedItemIds(content: string): Set<string> {
+ const ids = new Set<string>();
+
+ for (const match of content.matchAll(DOCUMENT_MENTION_PATTERN)) {
+ try {
+ const mention = JSON.parse(match[1]);
+ if (
+ mention &&
+ typeof mention === 'object' &&
+ typeof mention.documentId === 'string' &&
+ 'documentName' in mention
+ ) {
+ ids.add(mention.documentId);
+ }
+ } catch {
+ // Malformed mention markup renders as an unknown item, not a reference.
+ }
+ }
+
+ return ids;
+}
+
+export function getVisibleUserMessageAttachments(
+ content: string,
+ attachments: Attachment[]
+): {
+ images: Attachment[];
+ items: Attachment[];
+} {
+ const mentionedItemIds = getMentionedItemIds(content);
+
+ return {
+ images: attachments.filter(
+ (attachment) => attachment.entity_type === 'static_file'
+ ),
+ items: attachments.filter(
+ (attachment) =>
+ ITEM_ATTACHMENT_TYPES.has(attachment.entity_type) &&
+ !mentionedItemIds.has(attachment.entity_id)
+ ),
+ };
+}
diff --git a/apps/web/src/lib/core/component/AI/hook/useEntityDropAttachment.ts b/apps/web/src/lib/core/component/AI/hook/useEntityDropAttachment.ts
index 6cf81a2be6..24b20f9bf6 100644
--- a/apps/web/src/lib/core/component/AI/hook/useEntityDropAttachment.ts
+++ b/apps/web/src/lib/core/component/AI/hook/useEntityDropAttachment.ts
@@ -1,24 +1,25 @@
import { SUPPORTED_CHAT_ATTACHMENT_BLOCKS } from '@core/component/AI/constant';
import type { Attachment, Attachments } from '@core/component/AI/types';
+import type { ChatAttachmentMention } from '@core/component/AI/util/chatAttachmentMention';
import { toast } from '@core/component/Toast/Toast';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
import type { EntityDragData, EntityDragEvent } from '@entity';
-import type { EntityType } from '@service-cognition/generated/schemas/entityType';
import { createDroppable, useDragDropContext } from '@thisbeyond/solid-dnd';
import { type Accessor, createMemo } from 'solid-js';
-import { match, P } from 'ts-pattern';
/**
* Hook to handle entity drag-and-drop for chat attachments.
* Creates a droppable zone and handles converting dropped entities to attachments.
*
* @param droppableId - Unique ID for the droppable zone
- * @param attachments - The attachments object from ChatContext
+ * @param attachments - Chat attachment state
+ * @param onAttach - Inserts the dropped entity into the chat composer
* @returns Object with droppable directive and isDraggingOver signal
*/
export function useEntityDropAttachment(
droppableId: string,
- attachments: Attachments
+ attachments: Attachments,
+ onAttach: (mention: ChatAttachmentMention) => void
): {
droppable: ReturnType<typeof createDroppable>;
isDraggingOver: Accessor<boolean>;
@@ -69,38 +70,48 @@ export function useEntityDropAttachment(
return;
}
- const attachment: Attachment | undefined = match(entityType)
- .with('document', () => ({
- entity_id: entityId,
- entity_type: 'document' as EntityType,
- }))
- .with('project', () => ({
- entity_id: entityId,
- entity_type: 'project' as EntityType,
- }))
- .with(P.union('channel', 'channel_message', 'channel_thread'), () => {
- const channelId =
- 'channelId' in data ? (data.channelId as string) : entityId;
- return {
- entity_id: channelId,
- entity_type: 'channel' as EntityType,
- };
- })
- .with('email', () => ({
- entity_id: entityId,
- entity_type: 'email_thread' as EntityType,
- }))
- .with('chat', () => undefined)
- .with('call', () => undefined)
- .with('automation', () => undefined)
- .with('foreign', () => undefined)
- .with('crm_company', () => undefined)
- .with('crm_contact', () => undefined)
- .exhaustive();
+ let attachment: Attachment | undefined;
+ let mention: ChatAttachmentMention | undefined;
- if (attachment) {
- attachments.addAttachment(attachment);
+ if (entityType === 'document') {
+ attachment = { entity_id: entityId, entity_type: 'document' };
+ mention = {
+ documentId: entityId,
+ documentName: data.name,
+ blockName,
+ };
+ } else if (entityType === 'project') {
+ attachment = { entity_id: entityId, entity_type: 'project' };
+ mention = {
+ documentId: entityId,
+ documentName: data.name,
+ blockName: 'project',
+ };
+ } else if (
+ entityType === 'channel' ||
+ entityType === 'channel_message' ||
+ entityType === 'channel_thread'
+ ) {
+ const channelId = 'channelId' in data ? data.channelId : entityId;
+ attachment = { entity_id: channelId, entity_type: 'channel' };
+ mention = {
+ documentId: channelId,
+ documentName: data.name,
+ blockName: 'channel',
+ channelType: data.channelType,
+ };
+ } else if (entityType === 'email') {
+ attachment = { entity_id: entityId, entity_type: 'email_thread' };
+ mention = {
+ documentId: entityId,
+ documentName: data.name,
+ blockName: 'email',
+ };
}
+
+ if (!attachment || !mention) return;
+ attachments.addAttachment(attachment);
+ onAttach(mention);
});
return { droppable, isDraggingOver };
diff --git a/apps/web/src/lib/core/component/AI/signal/attachment.ts b/apps/web/src/lib/core/component/AI/signal/attachment.ts
index 11be40c6cf..58b2f8d3a7 100644
--- a/apps/web/src/lib/core/component/AI/signal/attachment.ts
+++ b/apps/web/src/lib/core/component/AI/signal/attachment.ts
@@ -4,7 +4,6 @@ import type { Attachment, Attachments } from '@core/component/AI/types';
import { asFileType } from '@core/component/AI/util';
import type { ItemMention } from '@core/component/LexicalMarkdown/plugins/mentions';
import { ENABLE_CHAT_CHANNEL_ATTACHMENT } from '@core/constant/featureFlags';
-import { useChannelsContext } from '@core/context/channels';
import {
getCachedItemPreview,
isAccessiblePreviewItem,
@@ -46,8 +45,6 @@ export const useChatAttachableHistory = () => {
};
export const useGetChatAttachmentInfo = () => {
- const { channels } = useChannelsContext();
-
// fallback for callers that only have an id: the mentions menu and
// attachment pickers render previews, so the item is usually cached
const cachedDocumentFileType = (id: string): string | undefined => {
@@ -80,45 +77,30 @@ export const useGetChatAttachmentInfo = () => {
};
};
- const getProjectAttachment = (id: string): Attachment | undefined => {
- return {
- entity_id: id,
- entity_type: 'project',
- };
- };
-
const getChannelAttachment = ({
itemId: id,
}: ItemMention): Attachment | undefined => {
if (!ENABLE_CHAT_CHANNEL_ATTACHMENT) return;
- const item = channels().find((item) => item.id === id);
- if (!item) return;
-
return {
- entity_id: item.id,
+ entity_id: id,
entity_type: 'channel',
};
};
- const getEmailAttachment = (mention: ItemMention): Attachment | undefined => {
- return {
- entity_id: mention.itemId,
- entity_type: 'email_thread',
- };
- };
-
const mentionToAttachment = (
mention: ItemMention
): Attachment | undefined => {
if (mention.itemType === 'document') {
return getDocumentAttachment(mention.itemId, mention.fileType);
+ } else if (mention.itemType === 'call') {
+ return { entity_id: mention.itemId, entity_type: 'document' };
} else if (mention.itemType === 'channel') {
return getChannelAttachment(mention);
} else if (mention.itemType === 'thread') {
- return getEmailAttachment(mention);
+ return { entity_id: mention.itemId, entity_type: 'email_thread' };
} else if (mention.itemType === 'project') {
- return getProjectAttachment(mention.itemId);
+ return { entity_id: mention.itemId, entity_type: 'project' };
}
};
diff --git a/apps/web/src/lib/core/component/AI/types/attachment.ts b/apps/web/src/lib/core/component/AI/types/attachment.ts
index 1866f58e7a..d3406b894c 100644
--- a/apps/web/src/lib/core/component/AI/types/attachment.ts
+++ b/apps/web/src/lib/core/component/AI/types/attachment.ts
@@ -32,6 +32,7 @@ export type UploadResult =
| {
type: 'ok';
attachment: Attachment;
+ preview: AttachmentPreview;
}
| {
type: 'error';
diff --git a/apps/web/src/lib/core/component/AI/util/chatAttachmentMention.ts b/apps/web/src/lib/core/component/AI/util/chatAttachmentMention.ts
new file mode 100644
index 0000000000..5ce0f3bd00
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/util/chatAttachmentMention.ts
@@ -0,0 +1,26 @@
+import { INSERT_DOCUMENT_MENTION_COMMAND } from '@core/component/LexicalMarkdown/plugins/mentions';
+import type { DocumentMentionInfo } from '@macro-inc/lexical-core';
+import { buildMentionMarkdownString } from '@macro-inc/lexical-core/utils/mentions';
+import type { LexicalEditor } from 'lexical';
+
+export type ChatAttachmentMention = Pick<
+ DocumentMentionInfo,
+ 'documentId' | 'documentName' | 'blockName' | 'channelType'
+>;
+
+export function chatAttachmentMentionToMarkdown(
+ mention: ChatAttachmentMention
+): string {
+ return buildMentionMarkdownString({
+ type: 'document',
+ ...mention,
+ blockParams: {},
+ });
+}
+
+export function insertChatAttachmentMention(
+ editor: LexicalEditor,
+ mention: ChatAttachmentMention
+): boolean {
+ return editor.dispatchCommand(INSERT_DOCUMENT_MENTION_COMMAND, mention);
+}
diff --git a/apps/web/src/lib/core/component/AI/util/uploadToChat.ts b/apps/web/src/lib/core/component/AI/util/uploadToChat.ts
index 8be82511af..ddc81a165e 100644
--- a/apps/web/src/lib/core/component/AI/util/uploadToChat.ts
+++ b/apps/web/src/lib/core/component/AI/util/uploadToChat.ts
@@ -56,6 +56,7 @@ async function uploadFileForChat(
return {
type: 'ok',
+ preview,
attachment: {
entity_id: entityId,
entity_type: entityType,
diff --git a/apps/web/src/lib/core/component/DocumentPreview.tsx b/apps/web/src/lib/core/component/DocumentPreview.tsx
index 6c087596f8..c377818f21 100644
--- a/apps/web/src/lib/core/component/DocumentPreview.tsx
+++ b/apps/web/src/lib/core/component/DocumentPreview.tsx
@@ -1,13 +1,12 @@
+import { openChatWithAgent } from '@app/features/chat/ChatWithAgentButton';
import { globalSplitManager } from '@app/signal/splitLayout';
import { URL_PARAMS as URL_PARAMS_CANVAS } from '@block-canvas/constants';
import { URL_PARAMS as CHANNEL_PARAMS } from '@block-channel/constants';
-import { useOpenChatForAttachment } from '@block-chat/client';
import { URL_PARAMS as URL_PARAMS_MD } from '@block-md/constants';
import { URL_PARAMS as URL_PARAMS_PDF } from '@block-pdf/constants';
import {
type BlockAlias,
type BlockName,
- useMaybeBlockId,
useMaybeBlockName,
} from '@core/block';
import { EntityIcon } from '@core/component/EntityIcon';
@@ -500,8 +499,6 @@ export function DocumentPreviewContent(props: DocumentPreviewContentProps) {
const navigate = useNavigate();
const blockName = useMaybeBlockName();
- const blockId = useMaybeBlockId();
-
const itemPreviewEntity = () => {
const type = blockNameToItemType(props.documentInfo.type);
let messageId: string | undefined;
@@ -571,13 +568,16 @@ export function DocumentPreviewContent(props: DocumentPreviewContentProps) {
});
});
- // H opening document in chat
- const openChatForAttachment = useOpenChatForAttachment();
const handleOpenInChat = () => {
- openChatForAttachment({
- attachmentId: props.documentInfo.id,
- callerBlock:
- blockName && blockId ? { name: blockName, id: blockId } : undefined,
+ const preview = item();
+ void openChatWithAgent({
+ type: 'document',
+ id: props.documentInfo.id,
+ name:
+ (isAccessiblePreviewItem(preview) ? preview.name : undefined) ??
+ props.documentInfo.name ??
+ '',
+ fileType: targetBlockType(),
});
};
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts
index 9a6b1e6441..526ccb3f17 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts
@@ -193,6 +193,9 @@ function $mentionItemFromNode(node: MentionNode): ItemMention {
} else if (blockName === 'email') {
fileType = 'email';
itemType = 'thread';
+ } else if (blockName === 'call') {
+ fileType = 'call';
+ itemType = 'call';
} else if (blockName === 'company') {
fileType = 'company';
itemType = 'crm_company';
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/tests/mentionCallbacks.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/tests/mentionCallbacks.test.ts
index 5d8af39f83..9bd07be461 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/tests/mentionCallbacks.test.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/tests/mentionCallbacks.test.ts
@@ -39,6 +39,7 @@ vi.mock('@service-storage/client', () => ({
project: 'project',
chat: 'chat',
email: 'email',
+ call: 'call',
};
return map[name] ?? 'document';
},
@@ -316,6 +317,46 @@ describe('mentionsPlugin callbacks', () => {
cleanup();
});
+ test('call mentions keep the same item type when created and removed', () => {
+ const editor = createTestEditor();
+ const created: ItemMention[] = [];
+ const removed: ItemMention[] = [];
+ const cleanup = mentionsPlugin({
+ onCreateMention: (mention) => created.push(mention),
+ onRemoveMention: (mention) => removed.push(mention),
+ })(editor);
+
+ editor.dispatchCommand(INSERT_DOCUMENT_MENTION_COMMAND, {
+ documentId: 'call-1',
+ documentName: 'Weekly sync',
+ blockName: 'call',
+ });
+ editor.read(() => {});
+
+ expect(created).toContainEqual(
+ expect.objectContaining({
+ itemType: 'call',
+ itemId: 'call-1',
+ fileType: 'call',
+ })
+ );
+
+ editor.update(
+ () => {
+ $getRoot().clear().append($createParagraphNode());
+ },
+ { discrete: true }
+ );
+ editor.read(() => {});
+
+ expect(removed).toContainEqual({
+ itemType: 'call',
+ itemId: 'call-1',
+ });
+
+ cleanup();
+ });
+
test('custom plugin passed to builder runs and cleans up', () => {
const editor = createTestEditor();
const pluginInit = vi.fn();